eeaad62b10
- 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.
204 lines
6.2 KiB
Go
204 lines
6.2 KiB
Go
// Package account owns durable internal accounts and their platform/email
|
|
// identities. First contact from a platform auto-provisions an account bound to
|
|
// that identity; guests are session-only and never reach this package.
|
|
package account
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/go-jet/jet/v2/postgres"
|
|
"github.com/go-jet/jet/v2/qrm"
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
|
|
"scrabble/backend/internal/postgres/jet/backend/model"
|
|
"scrabble/backend/internal/postgres/jet/backend/table"
|
|
)
|
|
|
|
// Identity kinds recognised by the backend. Email is modelled as an identity
|
|
// alongside platform identities; its confirmed flag is driven by the email
|
|
// confirm-code flow in a later stage.
|
|
const (
|
|
KindTelegram = "telegram"
|
|
KindEmail = "email"
|
|
)
|
|
|
|
// uniqueViolation is the PostgreSQL SQLSTATE for a unique-constraint violation.
|
|
const uniqueViolation = "23505"
|
|
|
|
// ErrNotFound is returned when no account matches the lookup.
|
|
var ErrNotFound = errors.New("account: not found")
|
|
|
|
// Account is a durable internal account.
|
|
type Account struct {
|
|
ID uuid.UUID
|
|
DisplayName string
|
|
PreferredLanguage string
|
|
TimeZone string
|
|
BlockChat bool
|
|
BlockFriendRequests bool
|
|
CreatedAt time.Time
|
|
UpdatedAt time.Time
|
|
}
|
|
|
|
// Store is the Postgres-backed query surface for accounts and identities.
|
|
type Store struct {
|
|
db *sql.DB
|
|
}
|
|
|
|
// NewStore constructs a Store wrapping db.
|
|
func NewStore(db *sql.DB) *Store {
|
|
return &Store{db: db}
|
|
}
|
|
|
|
// ProvisionByIdentity returns the account bound to (kind, externalID), creating
|
|
// a fresh durable account and identity when none exists yet. It is safe under
|
|
// concurrent callers: a losing race on the identity's unique constraint is
|
|
// resolved by re-reading the winner's account. A platform identity is recorded
|
|
// as confirmed; an email identity starts unconfirmed.
|
|
func (s *Store) ProvisionByIdentity(ctx context.Context, kind, externalID string) (Account, error) {
|
|
acc, err := s.findByIdentity(ctx, kind, externalID)
|
|
if err == nil {
|
|
return acc, nil
|
|
}
|
|
if !errors.Is(err, ErrNotFound) {
|
|
return Account{}, err
|
|
}
|
|
|
|
acc, err = s.create(ctx, kind, externalID)
|
|
if err != nil {
|
|
if isUniqueViolation(err) {
|
|
// A concurrent caller created the identity first; return theirs.
|
|
return s.findByIdentity(ctx, kind, externalID)
|
|
}
|
|
return Account{}, err
|
|
}
|
|
return acc, nil
|
|
}
|
|
|
|
// GetByID loads the account identified by id, or ErrNotFound when it is absent.
|
|
func (s *Store) GetByID(ctx context.Context, id uuid.UUID) (Account, error) {
|
|
stmt := postgres.SELECT(table.Accounts.AllColumns).
|
|
FROM(table.Accounts).
|
|
WHERE(table.Accounts.AccountID.EQ(postgres.UUID(id))).
|
|
LIMIT(1)
|
|
|
|
var row model.Accounts
|
|
if err := stmt.QueryContext(ctx, s.db, &row); err != nil {
|
|
if errors.Is(err, qrm.ErrNoRows) {
|
|
return Account{}, ErrNotFound
|
|
}
|
|
return Account{}, fmt.Errorf("account: get by id %s: %w", id, err)
|
|
}
|
|
return modelToAccount(row), nil
|
|
}
|
|
|
|
// findByIdentity joins identities to accounts and returns the matching account,
|
|
// or ErrNotFound.
|
|
func (s *Store) findByIdentity(ctx context.Context, kind, externalID string) (Account, error) {
|
|
stmt := postgres.SELECT(table.Accounts.AllColumns).
|
|
FROM(table.Accounts.INNER_JOIN(
|
|
table.Identities,
|
|
table.Identities.AccountID.EQ(table.Accounts.AccountID),
|
|
)).
|
|
WHERE(
|
|
table.Identities.Kind.EQ(postgres.String(kind)).
|
|
AND(table.Identities.ExternalID.EQ(postgres.String(externalID))),
|
|
).
|
|
LIMIT(1)
|
|
|
|
var row model.Accounts
|
|
if err := stmt.QueryContext(ctx, s.db, &row); err != nil {
|
|
if errors.Is(err, qrm.ErrNoRows) {
|
|
return Account{}, ErrNotFound
|
|
}
|
|
return Account{}, fmt.Errorf("account: find by identity (%s, %s): %w", kind, externalID, err)
|
|
}
|
|
return modelToAccount(row), nil
|
|
}
|
|
|
|
// create inserts a new account and its first identity inside one transaction
|
|
// and returns the persisted account row.
|
|
func (s *Store) create(ctx context.Context, kind, externalID string) (Account, error) {
|
|
accountID, err := uuid.NewV7()
|
|
if err != nil {
|
|
return Account{}, fmt.Errorf("account: new account id: %w", err)
|
|
}
|
|
identityID, err := uuid.NewV7()
|
|
if err != nil {
|
|
return Account{}, fmt.Errorf("account: new identity id: %w", err)
|
|
}
|
|
|
|
var created Account
|
|
err = withTx(ctx, s.db, func(tx *sql.Tx) error {
|
|
insertAccount := table.Accounts.
|
|
INSERT(table.Accounts.AccountID).
|
|
VALUES(accountID).
|
|
RETURNING(table.Accounts.AllColumns)
|
|
|
|
var row model.Accounts
|
|
if err := insertAccount.QueryContext(ctx, tx, &row); err != nil {
|
|
return err
|
|
}
|
|
|
|
insertIdentity := table.Identities.INSERT(
|
|
table.Identities.IdentityID,
|
|
table.Identities.AccountID,
|
|
table.Identities.Kind,
|
|
table.Identities.ExternalID,
|
|
table.Identities.Confirmed,
|
|
).VALUES(identityID, accountID, kind, externalID, kind == KindTelegram)
|
|
if _, err := insertIdentity.ExecContext(ctx, tx); err != nil {
|
|
return err
|
|
}
|
|
|
|
created = modelToAccount(row)
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return Account{}, fmt.Errorf("account: create for identity (%s, %s): %w", kind, externalID, err)
|
|
}
|
|
return created, nil
|
|
}
|
|
|
|
// modelToAccount projects a generated model row into the public Account struct.
|
|
func modelToAccount(row model.Accounts) Account {
|
|
return Account{
|
|
ID: row.AccountID,
|
|
DisplayName: row.DisplayName,
|
|
PreferredLanguage: row.PreferredLanguage,
|
|
TimeZone: row.TimeZone,
|
|
BlockChat: row.BlockChat,
|
|
BlockFriendRequests: row.BlockFriendRequests,
|
|
CreatedAt: row.CreatedAt,
|
|
UpdatedAt: row.UpdatedAt,
|
|
}
|
|
}
|
|
|
|
// isUniqueViolation reports whether err is a PostgreSQL unique-constraint
|
|
// violation, used to collapse a concurrent-provision race into a re-read.
|
|
func isUniqueViolation(err error) bool {
|
|
var pgErr *pgconn.PgError
|
|
return errors.As(err, &pgErr) && pgErr.Code == uniqueViolation
|
|
}
|
|
|
|
// withTx wraps fn in a transaction, committing on nil and rolling back on error.
|
|
func withTx(ctx context.Context, db *sql.DB, fn func(tx *sql.Tx) error) error {
|
|
tx, err := db.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return fmt.Errorf("begin tx: %w", err)
|
|
}
|
|
if err := fn(tx); err != nil {
|
|
_ = tx.Rollback()
|
|
return err
|
|
}
|
|
if err := tx.Commit(); err != nil {
|
|
return fmt.Errorf("commit tx: %w", err)
|
|
}
|
|
return nil
|
|
}
|