Purging an archived workspace deleted its intake reports with it: every intake table cascaded from tenants. Benjamin's decision Nr. 17 (docgen#6 17878, V-g): no automatic deletion of the reports when a workspace is deleted. The purge now refuses first, before any file or account is removed: 409 intake_retained while the workspace has reports. Migration 0030 makes the database refuse as well (intake_reports → tenants ON DELETE RESTRICT), and DeleteTenant maps that to ErrConflict. CountIntakeReports on both stores. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_014aRnCGqELxoix5TfpX8Ejf
242 lines
8.5 KiB
Go
242 lines
8.5 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
const intakeReportSelect = `
|
|
SELECT tenant_id::text, reference, received_at, channel, reporter_sub, about, danger FROM intake_reports `
|
|
|
|
func scanIntakeReport(row pgx.Row) (*IntakeReport, error) {
|
|
var r IntakeReport
|
|
if err := row.Scan(&r.TenantID, &r.Reference, &r.ReceivedAt, &r.Channel, &r.ReporterSub, &r.About, &r.Danger); err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, ErrNotFound
|
|
}
|
|
return nil, err
|
|
}
|
|
return &r, nil
|
|
}
|
|
|
|
// CreateIntakeReport takes the tenant's next number and writes the report
|
|
// and its capture in one transaction.
|
|
func (p *Postgres) CreateIntakeReport(ctx context.Context, c IntakeCapture) (*IntakeReport, *IntakeEntry, error) {
|
|
if !validCapture(c) {
|
|
return nil, nil, ErrInvalidInput
|
|
}
|
|
tx, err := p.pool.Begin(ctx)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
defer func() { _ = tx.Rollback(ctx) }()
|
|
var seq int
|
|
err = tx.QueryRow(ctx, `
|
|
INSERT INTO intake_counters (tenant_id, last) VALUES ($1::uuid, 1)
|
|
ON CONFLICT (tenant_id) DO UPDATE SET last = intake_counters.last + 1
|
|
RETURNING last`, c.TenantID).Scan(&seq)
|
|
switch {
|
|
case isFKViolation(err), isInvalidUUID(err):
|
|
return nil, nil, ErrNotFound
|
|
case err != nil:
|
|
return nil, nil, err
|
|
}
|
|
at := c.At.UTC().Truncate(time.Microsecond)
|
|
r := &IntakeReport{TenantID: c.TenantID, Reference: IntakeReference(at, seq), ReceivedAt: at, Channel: c.Channel,
|
|
ReporterSub: c.ReporterSub, About: c.About, Danger: c.Danger}
|
|
if _, err := tx.Exec(ctx, `
|
|
INSERT INTO intake_reports (tenant_id, reference, seq, received_at, channel, reporter_sub, about, danger)
|
|
VALUES ($1::uuid, $2, $3, $4, $5, $6, $7, $8)`,
|
|
r.TenantID, r.Reference, seq, at, r.Channel, r.ReporterSub, r.About, r.Danger); err != nil {
|
|
if isCheckViolation(err) {
|
|
return nil, nil, ErrInvalidInput
|
|
}
|
|
return nil, nil, err
|
|
}
|
|
e, err := insertIntakeEntry(ctx, tx, c.TenantID, r.Reference, IntakeEntryCapture, c.ReporterSub, c.Original, at)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
if err := tx.Commit(ctx); err != nil {
|
|
return nil, nil, err
|
|
}
|
|
return r, e, nil
|
|
}
|
|
|
|
func insertIntakeEntry(ctx context.Context, q interface {
|
|
QueryRow(context.Context, string, ...any) pgx.Row
|
|
}, tenantID, ref, kind, by string, content json.RawMessage, at time.Time) (*IntakeEntry, error) {
|
|
e := &IntakeEntry{TenantID: tenantID, Reference: ref, Kind: kind, Content: content, By: by, At: at, Receipts: []IntakeReceipt{}}
|
|
err := q.QueryRow(ctx, `
|
|
INSERT INTO intake_entries (tenant_id, reference, kind, content, by_sub, at)
|
|
VALUES ($1::uuid, $2, $3, $4::jsonb, $5, $6) RETURNING id`,
|
|
tenantID, ref, kind, string(content), by, at).Scan(&e.ID)
|
|
switch {
|
|
case isFKViolation(err), isInvalidUUID(err):
|
|
return nil, ErrNotFound
|
|
case isCheckViolation(err):
|
|
return nil, ErrInvalidInput
|
|
case err != nil:
|
|
return nil, err
|
|
}
|
|
return e, nil
|
|
}
|
|
|
|
func (p *Postgres) GetIntakeReport(ctx context.Context, tenantID, ref string) (*IntakeReport, error) {
|
|
r, err := scanIntakeReport(p.pool.QueryRow(ctx, intakeReportSelect+`WHERE tenant_id = $1::uuid AND reference = $2`, tenantID, ref))
|
|
if isInvalidUUID(err) {
|
|
return nil, ErrNotFound
|
|
}
|
|
return r, err
|
|
}
|
|
|
|
func (p *Postgres) CountIntakeReports(ctx context.Context, tenantID string) (int, error) {
|
|
var n int
|
|
err := p.pool.QueryRow(ctx, `SELECT count(*) FROM intake_reports WHERE tenant_id = $1::uuid`, tenantID).Scan(&n)
|
|
if isInvalidUUID(err) {
|
|
return 0, nil
|
|
}
|
|
return n, err
|
|
}
|
|
|
|
func (p *Postgres) ListIntakeReports(ctx context.Context, tenantID, reporterSub string) ([]IntakeReport, error) {
|
|
rows, err := p.pool.Query(ctx, intakeReportSelect+`WHERE tenant_id = $1::uuid AND reporter_sub = $2 ORDER BY seq DESC`, tenantID, reporterSub)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := []IntakeReport{}
|
|
for rows.Next() {
|
|
r, err := scanIntakeReport(rows)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, *r)
|
|
}
|
|
if err := rows.Err(); isInvalidUUID(err) {
|
|
return []IntakeReport{}, nil
|
|
} else if err != nil {
|
|
return nil, err
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (p *Postgres) IntakeEntries(ctx context.Context, tenantID, ref string) ([]IntakeEntry, error) {
|
|
if _, err := p.GetIntakeReport(ctx, tenantID, ref); err != nil {
|
|
return nil, err
|
|
}
|
|
rows, err := p.pool.Query(ctx, `
|
|
SELECT e.id, e.kind, e.content, e.by_sub, e.at,
|
|
r.status, r.reason, r.handoff_id, r.run_id, r.by_client, r.at
|
|
FROM intake_entries e LEFT JOIN intake_receipts r ON r.entry_id = e.id
|
|
WHERE e.tenant_id = $1::uuid AND e.reference = $2
|
|
ORDER BY e.id, r.id`, tenantID, ref)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := []IntakeEntry{}
|
|
for rows.Next() {
|
|
var e IntakeEntry
|
|
var content []byte
|
|
var st, reason, handoff, run, by *string
|
|
var at *time.Time
|
|
if err := rows.Scan(&e.ID, &e.Kind, &content, &e.By, &e.At, &st, &reason, &handoff, &run, &by, &at); err != nil {
|
|
return nil, err
|
|
}
|
|
if n := len(out); n == 0 || out[n-1].ID != e.ID {
|
|
e.TenantID, e.Reference, e.Content, e.Receipts = tenantID, ref, json.RawMessage(content), []IntakeReceipt{}
|
|
out = append(out, e)
|
|
}
|
|
if st != nil {
|
|
last := &out[len(out)-1]
|
|
last.Receipts = append(last.Receipts, IntakeReceipt{EntryID: e.ID, Status: *st, Reason: *reason,
|
|
HandoffID: *handoff, RunID: *run, By: *by, At: *at})
|
|
}
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
func (p *Postgres) AddIntakeSupplement(ctx context.Context, tenantID, ref, by string, content json.RawMessage, at time.Time) (*IntakeEntry, error) {
|
|
if by == "" || len(by) > 200 || !isJSONObject(content) {
|
|
return nil, ErrInvalidInput
|
|
}
|
|
return insertIntakeEntry(ctx, p.pool, tenantID, ref, IntakeEntrySupplement, by, content, at.UTC().Truncate(time.Microsecond))
|
|
}
|
|
|
|
func (p *Postgres) PendingIntake(ctx context.Context, after int64, limit int) ([]PendingIntake, error) {
|
|
rows, err := p.pool.Query(ctx, `
|
|
SELECT e.id, e.tenant_id::text, e.reference, e.kind, e.at, rp.received_at, rp.channel, rp.about, rp.danger,
|
|
COALESCE(last.status, ''), COALESCE(last.reason, ''), COALESCE(last.handoff_id, ''),
|
|
EXISTS (SELECT 1 FROM intake_entries c JOIN intake_receipts cr ON cr.entry_id = c.id
|
|
WHERE c.tenant_id = e.tenant_id AND c.reference = e.reference AND c.kind = 'capture'
|
|
AND cr.status IN ('processed', 'refused'))
|
|
FROM intake_entries e
|
|
JOIN intake_reports rp ON rp.tenant_id = e.tenant_id AND rp.reference = e.reference
|
|
LEFT JOIN LATERAL (SELECT status, reason, handoff_id FROM intake_receipts WHERE entry_id = e.id ORDER BY id DESC LIMIT 1) last ON true
|
|
WHERE e.id > $1 AND NOT EXISTS (SELECT 1 FROM intake_receipts s WHERE s.entry_id = e.id AND s.status IN ('processed', 'refused'))
|
|
ORDER BY e.id LIMIT $2`, after, limit)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
out := []PendingIntake{}
|
|
for rows.Next() {
|
|
var x PendingIntake
|
|
if err := rows.Scan(&x.EntryID, &x.TenantID, &x.Reference, &x.Kind, &x.At, &x.ReceivedAt, &x.Channel, &x.About, &x.Danger, &x.Status, &x.Reason, &x.HandoffID, &x.CaptureSettled); err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, x)
|
|
}
|
|
return out, rows.Err()
|
|
}
|
|
|
|
// AddIntakeReceipt locks the entry so that two receipts never race past the
|
|
// settled check.
|
|
func (p *Postgres) AddIntakeReceipt(ctx context.Context, r IntakeReceipt) (bool, error) {
|
|
if !validReceipt(r) {
|
|
return false, ErrInvalidInput
|
|
}
|
|
tx, err := p.pool.Begin(ctx)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
defer func() { _ = tx.Rollback(ctx) }()
|
|
var id int64
|
|
if err := tx.QueryRow(ctx, `SELECT id FROM intake_entries WHERE id = $1`, r.EntryID).Scan(&id); err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return false, ErrNotFound
|
|
}
|
|
return false, err
|
|
}
|
|
if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended('intake_receipt', $1))`, r.EntryID); err != nil {
|
|
return false, err
|
|
}
|
|
var last IntakeReceipt
|
|
err = tx.QueryRow(ctx, `SELECT status, reason, handoff_id, run_id FROM intake_receipts WHERE entry_id = $1 ORDER BY id DESC LIMIT 1`, r.EntryID).
|
|
Scan(&last.Status, &last.Reason, &last.HandoffID, &last.RunID)
|
|
switch {
|
|
case errors.Is(err, pgx.ErrNoRows):
|
|
case err != nil:
|
|
return false, err
|
|
case last.Settled():
|
|
return false, ErrConflict
|
|
case sameReceipt(last, r):
|
|
return false, nil
|
|
}
|
|
if _, err := tx.Exec(ctx, `
|
|
INSERT INTO intake_receipts (entry_id, status, reason, handoff_id, run_id, by_client, at)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
|
|
r.EntryID, r.Status, r.Reason, r.HandoffID, r.RunID, r.By, r.At.UTC()); err != nil {
|
|
if isUniqueViolation(err) {
|
|
return false, ErrConflict
|
|
}
|
|
return false, err
|
|
}
|
|
return true, tx.Commit(ctx)
|
|
}
|