Stage 1: backend foundation (Postgres, sessions, accounts, OTel)
Tests · Go / test (push) Successful in 11s
Tests · Integration / integration (push) Successful in 8s

- internal/postgres: pgx-over-database/sql pool (otelsql), embedded goose
  migrations into schema 'backend', committed go-jet code + cmd/jetgen tool.
- internal/account: durable accounts + unified telegram/email identities
  (UUIDv7 keys), find-or-create provisioning with unique-conflict handling.
- internal/session: opaque 256-bit tokens stored as a SHA-256 hash, revoke-only
  (no TTL); write-through cache gating /readyz; store + service.
- internal/telemetry: OTel tracer/meter providers (none/stdout) + request-timing
  middleware; internal/config gains Postgres + OTel env loading.
- internal/server: /api/v1 {public,user,internal,admin} skeleton + X-User-ID
  middleware; /readyz checks DB ping + cache; main wires
  telemetry -> db+migrate -> warm cache -> server.
- Tests: unit + integration (build tag 'integration', testcontainers
  postgres:17) for migrations, accounts, sessions, readyz; new integration.yaml.
- Docs: ARCHITECTURE, TESTING, PLAN refinements, root + backend READMEs.

Session/account REST handlers deferred to Stage 6 (gateway); OTLP + dashboards
to Stage 11.
This commit is contained in:
Ilia Denisov
2026-06-02 13:52:26 +02:00
parent da079b2bc6
commit eeaad62b10
45 changed files with 3461 additions and 92 deletions
@@ -0,0 +1,24 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package model
import (
"github.com/google/uuid"
"time"
)
type Accounts struct {
AccountID uuid.UUID `sql:"primary_key"`
DisplayName string
PreferredLanguage string
TimeZone string
BlockChat bool
BlockFriendRequests bool
CreatedAt time.Time
UpdatedAt time.Time
}
@@ -0,0 +1,22 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package model
import (
"github.com/google/uuid"
"time"
)
type Identities struct {
IdentityID uuid.UUID `sql:"primary_key"`
AccountID uuid.UUID
Kind string
ExternalID string
Confirmed bool
CreatedAt time.Time
}
@@ -0,0 +1,23 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package model
import (
"github.com/google/uuid"
"time"
)
type Sessions struct {
SessionID uuid.UUID `sql:"primary_key"`
AccountID uuid.UUID
TokenHash string
Status string
CreatedAt time.Time
LastSeenAt *time.Time
RevokedAt *time.Time
}
@@ -0,0 +1,99 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package table
import (
"github.com/go-jet/jet/v2/postgres"
)
var Accounts = newAccountsTable("backend", "accounts", "")
type accountsTable struct {
postgres.Table
// Columns
AccountID postgres.ColumnString
DisplayName postgres.ColumnString
PreferredLanguage postgres.ColumnString
TimeZone postgres.ColumnString
BlockChat postgres.ColumnBool
BlockFriendRequests postgres.ColumnBool
CreatedAt postgres.ColumnTimestampz
UpdatedAt postgres.ColumnTimestampz
AllColumns postgres.ColumnList
MutableColumns postgres.ColumnList
DefaultColumns postgres.ColumnList
}
type AccountsTable struct {
accountsTable
EXCLUDED accountsTable
}
// AS creates new AccountsTable with assigned alias
func (a AccountsTable) AS(alias string) *AccountsTable {
return newAccountsTable(a.SchemaName(), a.TableName(), alias)
}
// Schema creates new AccountsTable with assigned schema name
func (a AccountsTable) FromSchema(schemaName string) *AccountsTable {
return newAccountsTable(schemaName, a.TableName(), a.Alias())
}
// WithPrefix creates new AccountsTable with assigned table prefix
func (a AccountsTable) WithPrefix(prefix string) *AccountsTable {
return newAccountsTable(a.SchemaName(), prefix+a.TableName(), a.TableName())
}
// WithSuffix creates new AccountsTable with assigned table suffix
func (a AccountsTable) WithSuffix(suffix string) *AccountsTable {
return newAccountsTable(a.SchemaName(), a.TableName()+suffix, a.TableName())
}
func newAccountsTable(schemaName, tableName, alias string) *AccountsTable {
return &AccountsTable{
accountsTable: newAccountsTableImpl(schemaName, tableName, alias),
EXCLUDED: newAccountsTableImpl("", "excluded", ""),
}
}
func newAccountsTableImpl(schemaName, tableName, alias string) accountsTable {
var (
AccountIDColumn = postgres.StringColumn("account_id")
DisplayNameColumn = postgres.StringColumn("display_name")
PreferredLanguageColumn = postgres.StringColumn("preferred_language")
TimeZoneColumn = postgres.StringColumn("time_zone")
BlockChatColumn = postgres.BoolColumn("block_chat")
BlockFriendRequestsColumn = postgres.BoolColumn("block_friend_requests")
CreatedAtColumn = postgres.TimestampzColumn("created_at")
UpdatedAtColumn = postgres.TimestampzColumn("updated_at")
allColumns = postgres.ColumnList{AccountIDColumn, DisplayNameColumn, PreferredLanguageColumn, TimeZoneColumn, BlockChatColumn, BlockFriendRequestsColumn, CreatedAtColumn, UpdatedAtColumn}
mutableColumns = postgres.ColumnList{DisplayNameColumn, PreferredLanguageColumn, TimeZoneColumn, BlockChatColumn, BlockFriendRequestsColumn, CreatedAtColumn, UpdatedAtColumn}
defaultColumns = postgres.ColumnList{DisplayNameColumn, PreferredLanguageColumn, TimeZoneColumn, BlockChatColumn, BlockFriendRequestsColumn, CreatedAtColumn, UpdatedAtColumn}
)
return accountsTable{
Table: postgres.NewTable(schemaName, tableName, alias, allColumns...),
//Columns
AccountID: AccountIDColumn,
DisplayName: DisplayNameColumn,
PreferredLanguage: PreferredLanguageColumn,
TimeZone: TimeZoneColumn,
BlockChat: BlockChatColumn,
BlockFriendRequests: BlockFriendRequestsColumn,
CreatedAt: CreatedAtColumn,
UpdatedAt: UpdatedAtColumn,
AllColumns: allColumns,
MutableColumns: mutableColumns,
DefaultColumns: defaultColumns,
}
}
@@ -0,0 +1,93 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package table
import (
"github.com/go-jet/jet/v2/postgres"
)
var Identities = newIdentitiesTable("backend", "identities", "")
type identitiesTable struct {
postgres.Table
// Columns
IdentityID postgres.ColumnString
AccountID postgres.ColumnString
Kind postgres.ColumnString
ExternalID postgres.ColumnString
Confirmed postgres.ColumnBool
CreatedAt postgres.ColumnTimestampz
AllColumns postgres.ColumnList
MutableColumns postgres.ColumnList
DefaultColumns postgres.ColumnList
}
type IdentitiesTable struct {
identitiesTable
EXCLUDED identitiesTable
}
// AS creates new IdentitiesTable with assigned alias
func (a IdentitiesTable) AS(alias string) *IdentitiesTable {
return newIdentitiesTable(a.SchemaName(), a.TableName(), alias)
}
// Schema creates new IdentitiesTable with assigned schema name
func (a IdentitiesTable) FromSchema(schemaName string) *IdentitiesTable {
return newIdentitiesTable(schemaName, a.TableName(), a.Alias())
}
// WithPrefix creates new IdentitiesTable with assigned table prefix
func (a IdentitiesTable) WithPrefix(prefix string) *IdentitiesTable {
return newIdentitiesTable(a.SchemaName(), prefix+a.TableName(), a.TableName())
}
// WithSuffix creates new IdentitiesTable with assigned table suffix
func (a IdentitiesTable) WithSuffix(suffix string) *IdentitiesTable {
return newIdentitiesTable(a.SchemaName(), a.TableName()+suffix, a.TableName())
}
func newIdentitiesTable(schemaName, tableName, alias string) *IdentitiesTable {
return &IdentitiesTable{
identitiesTable: newIdentitiesTableImpl(schemaName, tableName, alias),
EXCLUDED: newIdentitiesTableImpl("", "excluded", ""),
}
}
func newIdentitiesTableImpl(schemaName, tableName, alias string) identitiesTable {
var (
IdentityIDColumn = postgres.StringColumn("identity_id")
AccountIDColumn = postgres.StringColumn("account_id")
KindColumn = postgres.StringColumn("kind")
ExternalIDColumn = postgres.StringColumn("external_id")
ConfirmedColumn = postgres.BoolColumn("confirmed")
CreatedAtColumn = postgres.TimestampzColumn("created_at")
allColumns = postgres.ColumnList{IdentityIDColumn, AccountIDColumn, KindColumn, ExternalIDColumn, ConfirmedColumn, CreatedAtColumn}
mutableColumns = postgres.ColumnList{AccountIDColumn, KindColumn, ExternalIDColumn, ConfirmedColumn, CreatedAtColumn}
defaultColumns = postgres.ColumnList{ConfirmedColumn, CreatedAtColumn}
)
return identitiesTable{
Table: postgres.NewTable(schemaName, tableName, alias, allColumns...),
//Columns
IdentityID: IdentityIDColumn,
AccountID: AccountIDColumn,
Kind: KindColumn,
ExternalID: ExternalIDColumn,
Confirmed: ConfirmedColumn,
CreatedAt: CreatedAtColumn,
AllColumns: allColumns,
MutableColumns: mutableColumns,
DefaultColumns: defaultColumns,
}
}
@@ -0,0 +1,96 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package table
import (
"github.com/go-jet/jet/v2/postgres"
)
var Sessions = newSessionsTable("backend", "sessions", "")
type sessionsTable struct {
postgres.Table
// Columns
SessionID postgres.ColumnString
AccountID postgres.ColumnString
TokenHash postgres.ColumnString
Status postgres.ColumnString
CreatedAt postgres.ColumnTimestampz
LastSeenAt postgres.ColumnTimestampz
RevokedAt postgres.ColumnTimestampz
AllColumns postgres.ColumnList
MutableColumns postgres.ColumnList
DefaultColumns postgres.ColumnList
}
type SessionsTable struct {
sessionsTable
EXCLUDED sessionsTable
}
// AS creates new SessionsTable with assigned alias
func (a SessionsTable) AS(alias string) *SessionsTable {
return newSessionsTable(a.SchemaName(), a.TableName(), alias)
}
// Schema creates new SessionsTable with assigned schema name
func (a SessionsTable) FromSchema(schemaName string) *SessionsTable {
return newSessionsTable(schemaName, a.TableName(), a.Alias())
}
// WithPrefix creates new SessionsTable with assigned table prefix
func (a SessionsTable) WithPrefix(prefix string) *SessionsTable {
return newSessionsTable(a.SchemaName(), prefix+a.TableName(), a.TableName())
}
// WithSuffix creates new SessionsTable with assigned table suffix
func (a SessionsTable) WithSuffix(suffix string) *SessionsTable {
return newSessionsTable(a.SchemaName(), a.TableName()+suffix, a.TableName())
}
func newSessionsTable(schemaName, tableName, alias string) *SessionsTable {
return &SessionsTable{
sessionsTable: newSessionsTableImpl(schemaName, tableName, alias),
EXCLUDED: newSessionsTableImpl("", "excluded", ""),
}
}
func newSessionsTableImpl(schemaName, tableName, alias string) sessionsTable {
var (
SessionIDColumn = postgres.StringColumn("session_id")
AccountIDColumn = postgres.StringColumn("account_id")
TokenHashColumn = postgres.StringColumn("token_hash")
StatusColumn = postgres.StringColumn("status")
CreatedAtColumn = postgres.TimestampzColumn("created_at")
LastSeenAtColumn = postgres.TimestampzColumn("last_seen_at")
RevokedAtColumn = postgres.TimestampzColumn("revoked_at")
allColumns = postgres.ColumnList{SessionIDColumn, AccountIDColumn, TokenHashColumn, StatusColumn, CreatedAtColumn, LastSeenAtColumn, RevokedAtColumn}
mutableColumns = postgres.ColumnList{AccountIDColumn, TokenHashColumn, StatusColumn, CreatedAtColumn, LastSeenAtColumn, RevokedAtColumn}
defaultColumns = postgres.ColumnList{StatusColumn, CreatedAtColumn}
)
return sessionsTable{
Table: postgres.NewTable(schemaName, tableName, alias, allColumns...),
//Columns
SessionID: SessionIDColumn,
AccountID: AccountIDColumn,
TokenHash: TokenHashColumn,
Status: StatusColumn,
CreatedAt: CreatedAtColumn,
LastSeenAt: LastSeenAtColumn,
RevokedAt: RevokedAtColumn,
AllColumns: allColumns,
MutableColumns: mutableColumns,
DefaultColumns: defaultColumns,
}
}
@@ -0,0 +1,16 @@
//
// Code generated by go-jet DO NOT EDIT.
//
// WARNING: Changes to this file may cause incorrect behavior
// and will be lost if the code is regenerated
//
package table
// UseSchema sets a new schema name for all generated table SQL builder types. It is recommended to invoke
// this method only once at the beginning of the program.
func UseSchema(schema string) {
Accounts = Accounts.FromSchema(schema)
Identities = Identities.FromSchema(schema)
Sessions = Sessions.FromSchema(schema)
}
+130
View File
@@ -0,0 +1,130 @@
package postgres
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"io/fs"
"strings"
"sync"
"time"
"github.com/pressly/goose/v3"
"scrabble/backend/internal/postgres/migrations"
)
// schemaName is the Postgres schema owned by the backend service. Every backend
// table lives here, and the DSN pins search_path to it.
const schemaName = "backend"
// migrationRetryAttempts and migrationRetryBackoff bound the transient-error
// retry around ApplyMigrations. A freshly started Postgres — notably a test
// container — can reset a pooled connection moments after it reports ready,
// which surfaces as "bad connection" mid-migration; a handful of quick retries
// ride over that without masking real failures.
const (
migrationRetryAttempts = 5
migrationRetryBackoff = 250 * time.Millisecond
)
// gooseMu serialises access to goose's package-level filesystem state so a
// second caller in the same process cannot race on goose.SetBaseFS.
var gooseMu sync.Mutex
// ApplyMigrations runs every pending Up migration embedded in the backend
// binary against db. The schema is created upfront so goose's bookkeeping table
// (`goose_db_version`, scoped to the DSN search_path) has somewhere to land
// before the first migration runs; migration 00001_init.sql re-asserts the
// schema with IF NOT EXISTS, so the double-create is idempotent.
//
// The apply is retried on transient connection errors. Both steps are
// idempotent, so a retry after a dropped connection resumes from the last
// committed migration.
func ApplyMigrations(ctx context.Context, db *sql.DB) error {
return retryOnTransient(ctx, migrationRetryAttempts, migrationRetryBackoff, func() error {
if _, err := db.ExecContext(ctx, "CREATE SCHEMA IF NOT EXISTS "+schemaName); err != nil {
return fmt.Errorf("ensure backend schema: %w", err)
}
if err := runMigrations(ctx, db, migrations.Migrations(), "."); err != nil {
return fmt.Errorf("apply backend migrations: %w", err)
}
return nil
})
}
// runMigrations applies every pending Up migration found under dir inside fsys
// against db. The PostgreSQL dialect is forced; goose's package-level base FS is
// restored on the way out so a second caller in the same process is safe. dir
// is "." when the migration files sit at the embed root.
func runMigrations(ctx context.Context, db *sql.DB, fsys fs.FS, dir string) error {
if db == nil {
return errors.New("run migrations: nil db")
}
if fsys == nil {
return errors.New("run migrations: nil fs")
}
gooseMu.Lock()
defer gooseMu.Unlock()
goose.SetBaseFS(fsys)
defer goose.SetBaseFS(nil)
if err := goose.SetDialect("postgres"); err != nil {
return fmt.Errorf("run migrations: set dialect: %w", err)
}
if err := goose.UpContext(ctx, db, dir); err != nil {
return fmt.Errorf("run migrations: %w", err)
}
return nil
}
// retryOnTransient runs op up to attempts times, retrying only when op fails
// with a transient connection error — a dropped, reset, or refused connection,
// as opposed to a deterministic SQL error. It waits backoff between attempts and
// stops early if ctx is cancelled.
func retryOnTransient(ctx context.Context, attempts int, backoff time.Duration, op func() error) error {
var err error
for attempt := 1; attempt <= attempts; attempt++ {
if err = op(); err == nil {
return nil
}
if attempt == attempts || !isTransientConnError(err) {
return err
}
select {
case <-ctx.Done():
return errors.Join(err, ctx.Err())
case <-time.After(backoff):
}
}
return err
}
// isTransientConnError reports whether err is a transient connection-level
// failure worth retrying, leaving deterministic SQL errors (syntax, constraint
// violations) to fail fast.
func isTransientConnError(err error) bool {
if err == nil {
return false
}
if errors.Is(err, driver.ErrBadConn) {
return true
}
msg := strings.ToLower(err.Error())
for _, s := range []string{
"bad connection",
"connection refused",
"connection reset",
"broken pipe",
"server closed the connection",
} {
if strings.Contains(msg, s) {
return true
}
}
return false
}
@@ -0,0 +1,60 @@
-- +goose Up
-- Initial schema for the Scrabble backend service: durable accounts, their
-- platform/email identities, and opaque server sessions.
--
-- Every backend table lives in the `backend` schema. The schema is created here
-- so a fresh database can apply this migration, and search_path is pinned for
-- the rest of the migration so the CREATE statements land in `backend` without
-- qualifying every object. Production also pins search_path via
-- BACKEND_POSTGRES_DSN.
CREATE SCHEMA IF NOT EXISTS backend;
SET search_path = backend, pg_catalog;
-- Durable internal accounts. Guests are session-only and never reach this table.
CREATE TABLE accounts (
account_id uuid PRIMARY KEY,
display_name text NOT NULL DEFAULT '',
preferred_language text NOT NULL DEFAULT 'en',
time_zone text NOT NULL DEFAULT 'UTC',
block_chat boolean NOT NULL DEFAULT false,
block_friend_requests boolean NOT NULL DEFAULT false,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT accounts_preferred_language_chk CHECK (preferred_language IN ('en', 'ru'))
);
-- Platform and email identities attached to an account. external_id is the
-- platform user id (kind='telegram') or the email address (kind='email');
-- confirmed flips true once an email confirm-code is verified (later stages).
CREATE TABLE identities (
identity_id uuid PRIMARY KEY,
account_id uuid NOT NULL REFERENCES accounts (account_id) ON DELETE CASCADE,
kind text NOT NULL,
external_id text NOT NULL,
confirmed boolean NOT NULL DEFAULT false,
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT identities_kind_chk CHECK (kind IN ('telegram', 'email')),
CONSTRAINT identities_kind_external_id_key UNIQUE (kind, external_id)
);
CREATE INDEX identities_account_idx ON identities (account_id);
-- Opaque server sessions. token_hash is the hex-encoded SHA-256 of the bearer
-- token; the plaintext token is never stored. Sessions are revoke-only (no
-- TTL): status moves active -> revoked and revoked_at is stamped.
CREATE TABLE sessions (
session_id uuid PRIMARY KEY,
account_id uuid NOT NULL REFERENCES accounts (account_id) ON DELETE CASCADE,
token_hash text NOT NULL,
status text NOT NULL DEFAULT 'active',
created_at timestamptz NOT NULL DEFAULT now(),
last_seen_at timestamptz,
revoked_at timestamptz,
CONSTRAINT sessions_status_chk CHECK (status IN ('active', 'revoked')),
CONSTRAINT sessions_token_hash_key UNIQUE (token_hash)
);
CREATE INDEX sessions_account_idx ON sessions (account_id);
-- +goose Down
DROP TABLE sessions;
DROP TABLE identities;
DROP TABLE accounts;
@@ -0,0 +1,16 @@
// Package migrations exposes the goose migrations applied at backend startup.
package migrations
import (
"embed"
"io/fs"
)
//go:embed *.sql
var migrationFiles embed.FS
// Migrations returns the embedded goose migration filesystem. The migration
// files sit at the FS root, so callers pass "." as the directory argument.
func Migrations() fs.FS {
return migrationFiles
}
+177
View File
@@ -0,0 +1,177 @@
// Package postgres opens the backend's Postgres pool and applies the embedded
// goose migrations into the `backend` schema at startup.
//
// The pool is a standard library *sql.DB backed by the pgx driver (registered
// through pgx/stdlib) and instrumented with otelsql, so go-jet queries run over
// database/sql while statement spans and connection-pool metrics flow into
// OpenTelemetry. The DSN must pin search_path to the backend schema.
package postgres
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"time"
"github.com/XSAM/otelsql"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/stdlib"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
"go.opentelemetry.io/otel/trace"
)
// Default pool tuning applied by DefaultConfig.
const (
DefaultMaxOpenConns = 25
DefaultMaxIdleConns = 5
DefaultConnMaxLifetime = 30 * time.Minute
DefaultOperationTimeout = 5 * time.Second
)
// dbSystemAttribute identifies the wrapped backend in OpenTelemetry spans
// without pinning the package to a specific semconv release.
var dbSystemAttribute = attribute.String("db.system", "postgresql")
// Config describes how to open the backend Postgres pool.
type Config struct {
// DSN is the pgx/libpq connection string. It must pin search_path to the
// backend schema, e.g. "postgres://…/db?search_path=backend&sslmode=disable".
DSN string
// MaxOpenConns bounds the pool's open connections (database/sql).
MaxOpenConns int
// MaxIdleConns bounds the pool's idle connections (database/sql).
MaxIdleConns int
// ConnMaxLifetime caps how long a pooled connection may be reused.
ConnMaxLifetime time.Duration
// OperationTimeout bounds a single connect attempt and the startup Ping.
OperationTimeout time.Duration
}
// DefaultConfig returns a Config carrying the default pool tuning and an empty
// DSN. Callers fill DSN from the environment before opening.
func DefaultConfig() Config {
return Config{
MaxOpenConns: DefaultMaxOpenConns,
MaxIdleConns: DefaultMaxIdleConns,
ConnMaxLifetime: DefaultConnMaxLifetime,
OperationTimeout: DefaultOperationTimeout,
}
}
// Validate reports whether the configuration is usable.
func (c Config) Validate() error {
if strings.TrimSpace(c.DSN) == "" {
return errors.New("postgres: DSN must not be empty")
}
if c.MaxOpenConns <= 0 {
return fmt.Errorf("postgres: MaxOpenConns must be positive, got %d", c.MaxOpenConns)
}
if c.MaxIdleConns < 0 {
return fmt.Errorf("postgres: MaxIdleConns must not be negative, got %d", c.MaxIdleConns)
}
if c.OperationTimeout <= 0 {
return fmt.Errorf("postgres: OperationTimeout must be positive, got %s", c.OperationTimeout)
}
return nil
}
// Option configures the OpenTelemetry providers attached to a pool by Open.
// Unset providers fall back to the OpenTelemetry global providers.
type Option func(*options)
type options struct {
tracerProvider trace.TracerProvider
meterProvider metric.MeterProvider
}
// WithTracerProvider sets the tracer provider used for SQL statement spans.
func WithTracerProvider(tp trace.TracerProvider) Option {
return func(o *options) { o.tracerProvider = tp }
}
// WithMeterProvider sets the meter provider used for connection-pool metrics.
func WithMeterProvider(mp metric.MeterProvider) Option {
return func(o *options) { o.meterProvider = mp }
}
func evalOptions(opts []Option) options {
var resolved options
for _, opt := range opts {
if opt != nil {
opt(&resolved)
}
}
return resolved
}
func (o options) otelsqlOptions() []otelsql.Option {
out := []otelsql.Option{otelsql.WithAttributes(dbSystemAttribute)}
if o.tracerProvider != nil {
out = append(out, otelsql.WithTracerProvider(o.tracerProvider))
}
if o.meterProvider != nil {
out = append(out, otelsql.WithMeterProvider(o.meterProvider))
}
return out
}
// Open opens the instrumented pool described by cfg, registers connection-pool
// metrics, and verifies connectivity with a bounded Ping. Closing the returned
// *sql.DB is the caller's responsibility.
func Open(ctx context.Context, cfg Config, opts ...Option) (*sql.DB, error) {
if err := cfg.Validate(); err != nil {
return nil, fmt.Errorf("open postgres: %w", err)
}
resolved := evalOptions(opts)
pgxCfg, err := pgx.ParseConfig(cfg.DSN)
if err != nil {
return nil, fmt.Errorf("open postgres: parse dsn: %w", err)
}
pgxCfg.ConnectTimeout = cfg.OperationTimeout
registeredName := stdlib.RegisterConnConfig(pgxCfg)
db, err := otelsql.Open("pgx", registeredName, resolved.otelsqlOptions()...)
if err != nil {
stdlib.UnregisterConnConfig(registeredName)
return nil, fmt.Errorf("open postgres: otelsql open: %w", err)
}
db.SetMaxOpenConns(cfg.MaxOpenConns)
db.SetMaxIdleConns(cfg.MaxIdleConns)
db.SetConnMaxLifetime(cfg.ConnMaxLifetime)
if _, err := otelsql.RegisterDBStatsMetrics(db, resolved.otelsqlOptions()...); err != nil {
_ = db.Close()
stdlib.UnregisterConnConfig(registeredName)
return nil, fmt.Errorf("open postgres: register db stats: %w", err)
}
if err := Ping(ctx, db, cfg.OperationTimeout); err != nil {
_ = db.Close()
stdlib.UnregisterConnConfig(registeredName)
return nil, err
}
return db, nil
}
// Ping bounds db.PingContext under timeout and wraps the error so startup
// failures are easy to spot in service logs. The same call backs the /readyz
// probe. timeout is typically Config.OperationTimeout.
func Ping(ctx context.Context, db *sql.DB, timeout time.Duration) error {
if db == nil {
return errors.New("ping postgres: nil db")
}
if timeout <= 0 {
return errors.New("ping postgres: timeout must be positive")
}
pingCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
if err := db.PingContext(pingCtx); err != nil {
return fmt.Errorf("ping postgres: %w", err)
}
return nil
}