package postgres import ( "context" "errors" "fmt" "github.com/jackc/pgx/v5" "github.com/samcharles93/archie-core/internal/domain/org" "github.com/samcharles93/archie-core/internal/domain/source" "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb" ) var _ storecontract.SourceStore = (*EDA)(nil) // InsertSource stores a new source in one of the acting org's workspaces, // its default one when src names none; a workspace the org does not have is // ErrInvalidWorkspace. The path is the primary key, so a taken path is // refused by the database and surfaced as ErrSourcePathTaken. func (s *EDA) InsertSource(ctx context.Context, src source.Source) error { secret, err := s.sealSecret(src.Secret) if err != nil { return err } workspace := src.WorkspaceID if workspace == "" { workspace = org.DefaultWorkspaceID } n, err := s.q.InsertSource(ctx, postgresdb.InsertSourceParams{ Path: src.Path, Signing: string(src.Signing), Secret: secret, OrgID: string(org.OrgFromContext(ctx)), WorkspaceID: string(workspace), }) if isUniqueViolation(err) { return storecontract.ErrSourcePathTaken } if err != nil { return fmt.Errorf("edastore: insert source: %w", err) } if n == 0 { return fmt.Errorf("%w: %s is not a workspace of this org", org.ErrInvalidWorkspace, workspace) } return nil } // GetSource returns (nil, nil) for an unknown path. func (s *EDA) GetSource(ctx context.Context, path string) (*source.Source, error) { r, err := s.q.GetSource(ctx, postgresdb.GetSourceParams{Path: path, ScopeOrg: scopeOrg(ctx)}) if errors.Is(err, pgx.ErrNoRows) { return nil, nil } if err != nil { return nil, fmt.Errorf("edastore: get source: %w", err) } src, err := s.sourceValue(r) if err != nil { return nil, err } return &src, nil } func (s *EDA) ListSources(ctx context.Context) ([]source.Source, error) { rows, err := s.q.ListSources(ctx, scopeOrg(ctx)) if err != nil { return nil, fmt.Errorf("edastore: list sources: %w", err) } out := make([]source.Source, 0, len(rows)) for _, r := range rows { src, err := s.sourceValue(r) if err != nil { return nil, err } out = append(out, src) } return out, nil } // SetSourceSigning moves a source from one signing state to another, and // refuses when the stored state is no longer from. func (s *EDA) SetSourceSigning(ctx context.Context, path string, from, to source.Signing) error { orgID := string(org.OrgFromContext(ctx)) return pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error { q := postgresdb.New(tx) if err := q.LockAuditRecord(ctx, postgresdb.LockAuditRecordParams{TableName: "sources", RecordKey: path}); err != nil { return err } if from == to { // No transition to write; still report a missing source or a // caller whose idea of the current state is stale. current, err := q.GetSource(ctx, postgresdb.GetSourceParams{Path: path, ScopeOrg: scopeOrg(ctx)}) switch { case errors.Is(err, pgx.ErrNoRows): return storecontract.ErrSourceNotFound case err != nil: return fmt.Errorf("edastore: set source signing: %w", err) case current.Signing != string(to): return storecontract.ErrSourceSigningStale } return nil } n, err := q.SetSourceSigning(ctx, postgresdb.SetSourceSigningParams{ Path: path, FromSigning: string(from), ToSigning: string(to), ScopeOrg: scopeOrg(ctx), }) if err != nil { return fmt.Errorf("edastore: set source signing: %w", err) } if n == 1 { return insertAuditValues(ctx, q, "sources", path, "signing", string(from), string(to), 0, orgID) } exists, err := q.SourceExists(ctx, path) if err != nil { return fmt.Errorf("edastore: set source signing: %w", err) } if !exists { return storecontract.ErrSourceNotFound } return storecontract.ErrSourceSigningStale }) } func (s *EDA) SetSourceSecret(ctx context.Context, path, secret string) error { sealed, err := s.sealSecret(secret) if err != nil { return err } orgID := string(org.OrgFromContext(ctx)) return pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error { q := postgresdb.New(tx) if err := q.LockAuditRecord(ctx, postgresdb.LockAuditRecordParams{TableName: "sources", RecordKey: path}); err != nil { return err } n, err := q.SetSourceSecret(ctx, postgresdb.SetSourceSecretParams{Path: path, Secret: sealed, ScopeOrg: scopeOrg(ctx)}) if err != nil { return fmt.Errorf("edastore: set source secret: %w", err) } if n == 0 { return storecontract.ErrSourceNotFound } // The value never reaches the trail: only the fact that it changed does. changed := map[string]bool{"changed": true} return insertAuditValues(ctx, q, "sources", path, "secret", changed, changed, 0, orgID) }) } // SetSourceName relabels a source. func (s *EDA) SetSourceName(ctx context.Context, path, name string) error { return pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error { q := postgresdb.New(tx) if err := q.LockAuditRecord(ctx, postgresdb.LockAuditRecordParams{TableName: "sources", RecordKey: path}); err != nil { return err } n, err := q.SetSourceName(ctx, postgresdb.SetSourceNameParams{Path: path, Name: name, ScopeOrg: scopeOrg(ctx)}) if err != nil { return fmt.Errorf("edastore: set source name: %w", err) } if n == 0 { return storecontract.ErrSourceNotFound } return nil }) } // SetSourceDeliveryHeader sets the header that names a source's deliveries. func (s *EDA) SetSourceDeliveryHeader(ctx context.Context, path, header string) error { return pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error { q := postgresdb.New(tx) if err := q.LockAuditRecord(ctx, postgresdb.LockAuditRecordParams{TableName: "sources", RecordKey: path}); err != nil { return err } n, err := q.SetSourceDeliveryHeader(ctx, postgresdb.SetSourceDeliveryHeaderParams{Path: path, DeliveryHeader: header, ScopeOrg: scopeOrg(ctx)}) if err != nil { return fmt.Errorf("edastore: set source delivery header: %w", err) } if n == 0 { return storecontract.ErrSourceNotFound } return nil }) } // DeleteSource deletes a source no armed binding fires on. func (s *EDA) DeleteSource(ctx context.Context, path string) error { return pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error { q := postgresdb.New(tx) if err := q.LockAuditRecord(ctx, postgresdb.LockAuditRecordParams{TableName: "sources", RecordKey: path}); err != nil { return err } // The read is scoped like the delete: another org's source is absent, // and its secret never leaves the database. params := postgresdb.GetSourceParams{Path: path, ScopeOrg: scopeOrg(ctx)} old, err := q.GetSource(ctx, params) if errors.Is(err, pgx.ErrNoRows) { return storecontract.ErrSourceNotFound } if err != nil { return fmt.Errorf("edastore: delete source: %w", err) } n, err := q.DeleteUnboundSource(ctx, postgresdb.DeleteUnboundSourceParams{Path: path, ScopeOrg: scopeOrg(ctx)}) if err != nil { return fmt.Errorf("edastore: delete source: %w", err) } if n == 0 { // It was there a moment ago: gone means someone else removed it, // otherwise an armed binding holds it in place. switch _, err := q.GetSource(ctx, params); { case errors.Is(err, pgx.ErrNoRows): return storecontract.ErrSourceNotFound case err != nil: return fmt.Errorf("edastore: delete source: %w", err) default: return storecontract.ErrSourceInUse } } return insertAuditValues(ctx, q, "sources", path, "source", map[string]string{ "path": old.Path, "name": old.Name, "signing": old.Signing, "delivery_header": old.DeliveryHeader, "org_id": old.OrgID, "workspace_id": old.WorkspaceID, }, nil, 0, old.OrgID) }) } // sealSecret encrypts a non-empty secret when a cipher is configured. func (s *EDA) sealSecret(secret string) (string, error) { if s.cipher == nil || secret == "" { return secret, nil } sealed, err := s.cipher.Encrypt(secret) if err != nil { return "", fmt.Errorf("edastore: encrypt source secret: %w", err) } return sealed, nil } func (s *EDA) sourceValue(r postgresdb.Source) (source.Source, error) { secret := r.Secret if s.cipher != nil && secret != "" { plain, err := s.cipher.Decrypt(secret) if err != nil { return source.Source{}, fmt.Errorf("edastore: decrypt source secret: %w", err) } secret = plain } return source.Source{ Path: r.Path, Name: r.Name, DeliveryHeader: r.DeliveryHeader, Signing: source.Signing(r.Signing), Secret: secret, OrgID: org.OrgID(r.OrgID), WorkspaceID: org.WorkspaceID(r.WorkspaceID), CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt, }, nil }