package store import ( "context" "errors" "time" "github.com/jackc/pgx/v5" ) // connectionSelect reads a connection with the current names of the sides // that exist (the snapshot otherwise) and whether it is active: not ended, // both tenants there and neither archived. const connectionSelect = ` SELECT c.id::text, COALESCE(c.tenant_a::text, ''), COALESCE(c.tenant_b::text, ''), COALESCE(ta.name, c.name_a), COALESCE(tb.name, c.name_b), c.created_at, c.ended_at, COALESCE(c.ended_by::text, ''), (c.ended_at IS NULL AND ta.status IS NOT NULL AND tb.status IS NOT NULL AND ta.status <> 'archived' AND tb.status <> 'archived') FROM tenant_connections c LEFT JOIN tenants ta ON ta.id = c.tenant_a LEFT JOIN tenants tb ON tb.id = c.tenant_b ` type rowQuerier interface { QueryRow(context.Context, string, ...any) pgx.Row } func scanConnection(row pgx.Row) (*Connection, error) { var c Connection if err := row.Scan(&c.ID, &c.TenantA, &c.TenantB, &c.NameA, &c.NameB, &c.CreatedAt, &c.EndedAt, &c.EndedBy, &c.Active); err != nil { if errors.Is(err, pgx.ErrNoRows) { return nil, ErrNotFound } return nil, err } c.CreatedAt = c.CreatedAt.UTC() if c.EndedAt != nil { t := c.EndedAt.UTC() c.EndedAt = &t } return &c, nil } func getConnection(ctx context.Context, q rowQuerier, id string) (*Connection, error) { c, err := scanConnection(q.QueryRow(ctx, connectionSelect+`WHERE c.id = $1::uuid`, id)) if isInvalidUUID(err) { return nil, ErrNotFound } return c, err } func (p *Postgres) CreateConnectionInvite(ctx context.Context, inv ConnectionInvite) (*ConnectionInvite, error) { if !inv.valid() { return nil, ErrInvalidInput } out := inv out.UsedAt = nil err := p.pool.QueryRow(ctx, ` INSERT INTO connection_invites (tenant_id, code_hash, created_by, expires_at) VALUES ($1::uuid, $2, $3, $4) RETURNING id::text, created_at`, inv.TenantID, inv.CodeHash, inv.CreatedBy, inv.ExpiresAt.UTC()).Scan(&out.ID, &out.CreatedAt) switch { case err == nil: out.CreatedAt = out.CreatedAt.UTC() out.ExpiresAt = out.ExpiresAt.UTC() return &out, nil case isFKViolation(err), isInvalidUUID(err): return nil, ErrNotFound case isUniqueViolation(err): return nil, ErrConflict case isCheckViolation(err): return nil, ErrInvalidInput } return nil, err } func (p *Postgres) ListConnectionInvites(ctx context.Context, tenantID string, now time.Time) ([]ConnectionInvite, error) { rows, err := p.pool.Query(ctx, ` SELECT id::text, tenant_id::text, created_by, created_at, expires_at FROM connection_invites WHERE tenant_id = $1::uuid AND used_at IS NULL AND expires_at > $2 ORDER BY created_at, id`, tenantID, now.UTC()) if isInvalidUUID(err) { return []ConnectionInvite{}, nil } if err != nil { return nil, err } defer rows.Close() out := []ConnectionInvite{} for rows.Next() { var i ConnectionInvite if err := rows.Scan(&i.ID, &i.TenantID, &i.CreatedBy, &i.CreatedAt, &i.ExpiresAt); err != nil { return nil, err } i.CreatedAt, i.ExpiresAt = i.CreatedAt.UTC(), i.ExpiresAt.UTC() out = append(out, i) } if err := rows.Err(); isInvalidUUID(err) { return []ConnectionInvite{}, nil } else if err != nil { return nil, err } return out, nil } func (p *Postgres) DeleteConnectionInvite(ctx context.Context, tenantID, id string) error { tag, err := p.pool.Exec(ctx, ` DELETE FROM connection_invites WHERE tenant_id = $1::uuid AND id = $2::uuid AND used_at IS NULL`, tenantID, id) switch { case isInvalidUUID(err): return ErrNotFound case err != nil: return err case tag.RowsAffected() == 0: return ErrNotFound } return nil } func (p *Postgres) RedeemConnectionInvite(ctx context.Context, codeHash []byte, tenantID string, now time.Time) (*Connection, error) { tx, err := p.pool.Begin(ctx) if err != nil { return nil, err } defer func() { _ = tx.Rollback(ctx) }() // The row lock makes a second redeemer of the same code wait, then see // it used. var inviteID, issuer, issuerName, redeemerName string err = tx.QueryRow(ctx, ` SELECT i.id::text, ta.id::text, ta.name, tb.name FROM connection_invites i JOIN tenants ta ON ta.id = i.tenant_id JOIN tenants tb ON tb.id = $2::uuid WHERE i.code_hash = $1 AND i.used_at IS NULL AND i.expires_at > $3 AND ta.id <> tb.id AND ta.status <> 'archived' AND tb.status <> 'archived' FOR UPDATE OF i`, codeHash, tenantID, now.UTC()).Scan(&inviteID, &issuer, &issuerName, &redeemerName) if errors.Is(err, pgx.ErrNoRows) || isInvalidUUID(err) { return nil, ErrNotFound } if err != nil { return nil, err } var id string err = tx.QueryRow(ctx, ` INSERT INTO tenant_connections (tenant_a, tenant_b, name_a, name_b, created_at) VALUES ($1::uuid, $2::uuid, $3, $4, $5) RETURNING id::text`, issuer, tenantID, issuerName, redeemerName, now.UTC()).Scan(&id) if isUniqueViolation(err) { return nil, ErrConflict } if err != nil { return nil, err } if _, err := tx.Exec(ctx, `UPDATE connection_invites SET used_at = $2 WHERE id = $1::uuid`, inviteID, now.UTC()); err != nil { return nil, err } c, err := getConnection(ctx, tx, id) if err != nil { return nil, err } if err := tx.Commit(ctx); err != nil { return nil, err } return c, nil } func (p *Postgres) ListConnections(ctx context.Context, tenantID string) ([]Connection, error) { rows, err := p.pool.Query(ctx, connectionSelect+` WHERE c.tenant_a = $1::uuid OR c.tenant_b = $1::uuid ORDER BY c.created_at DESC, c.id DESC`, tenantID) if isInvalidUUID(err) { return []Connection{}, nil } if err != nil { return nil, err } defer rows.Close() out := []Connection{} for rows.Next() { c, err := scanConnection(rows) if err != nil { return nil, err } out = append(out, *c) } if err := rows.Err(); isInvalidUUID(err) { return []Connection{}, nil } else if err != nil { return nil, err } return out, nil } func (p *Postgres) GetConnection(ctx context.Context, id string) (*Connection, error) { return getConnection(ctx, p.pool, id) } func (p *Postgres) EndConnection(ctx context.Context, tenantID, id string, at time.Time) (*Connection, bool, error) { tag, err := p.pool.Exec(ctx, ` UPDATE tenant_connections SET ended_at = $3, ended_by = $1::uuid WHERE id = $2::uuid AND ended_at IS NULL AND (tenant_a = $1::uuid OR tenant_b = $1::uuid)`, tenantID, id, at.UTC()) if isInvalidUUID(err) { return nil, false, ErrNotFound } if err != nil { return nil, false, err } c, err := getConnection(ctx, p.pool, id) if err != nil { return nil, false, err } if c.TenantA != tenantID && c.TenantB != tenantID { return nil, false, ErrNotFound } return c, tag.RowsAffected() > 0, nil } func (p *Postgres) EndTenantConnections(ctx context.Context, tenantID string, at time.Time) ([]Connection, error) { rows, err := p.pool.Query(ctx, ` UPDATE tenant_connections SET ended_at = $2 WHERE ended_at IS NULL AND (tenant_a = $1::uuid OR tenant_b = $1::uuid) RETURNING id::text`, tenantID, at.UTC()) if isInvalidUUID(err) { return []Connection{}, nil } if err != nil { return nil, err } ids, err := pgx.CollectRows(rows, pgx.RowTo[string]) if err != nil { return nil, err } out := make([]Connection, 0, len(ids)) for _, id := range ids { c, err := getConnection(ctx, p.pool, id) if err != nil { return nil, err } out = append(out, *c) } return out, nil }