Files
tenant-registry/internal/store/postgres_document_store.go
T
Sharang ParnerkarandClaude Opus 5.5 251cddf3d3
ci / shared (pull_request) Failing after 4s
ci / test (pull_request) Successful in 25m54s
ci / image (pull_request) Skipped
feat(store): Dokumentenablage — three areas, digest-checked serving, staff bundle import
Workspace ticket #171 (decided 2026-10-20): the tenant's own documents
live next to BreakPilot's deliveries ("Unterlagen") in the same table and
bucket, in three areas, with the original and the prepared version the
Factory delivers.

- migration 0022: documents get area (legal_web / product_public /
  internal; NULL = Unterlagen), legal_kind (the 8 folders as the workspace
  and Factory name them), processing_status (none/pending/ready/failed),
  external_id (the Factory's tenant_document_id, unique per tenant);
  document_preparations (chunk file and/or cookie-banner capture with
  digest, format, revision, pin, image digests); store_assets (images per
  tenant, content-addressed)
- GET /v1/tenants/{id}/store; POST …/store/documents (customer upload:
  legal folder, product of an internal document; legal and product
  documents wait for the Factory, an internal one only on request);
  GET …/original, …/prepared, …/consent-banner and …/store/assets/{sha}:
  every byte is hashed and compared before anything is sent (fail-closed,
  502 digest_mismatch), HTML originals sandboxed
- POST /v1/admin/tenants/{id}/store/import (named staff only): a .tar.gz in
  the Factory's run layout; unsafe paths and links refused, every file
  checked against its digest, keyed on tenant_document_id so it can run
  again; per-document outcome, never content
- Unterlagen lists stay as they were (area NULL only); deleting a store
  document removes its prepared files; storage gains Get
- OpenAPI for the seven routes; tests on memory and Postgres with
  synthetic data only

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 15:07:57 +02:00

192 lines
6.2 KiB
Go

package store
import (
"context"
"errors"
"github.com/jackc/pgx/v5"
)
func (p *Postgres) ListStoreDocuments(ctx context.Context, tenantID string) ([]Document, error) {
rows, err := p.pool.Query(ctx, documentSelect+`
WHERE tenant_id = $1::uuid AND area IS NOT NULL
ORDER BY array_position(ARRAY['legal_web','product_public','internal'], area),
array_position($2::text[], legal_kind) NULLS FIRST, title, id`, tenantID, LegalKinds)
if isInvalidUUID(err) {
return []Document{}, nil
}
if err != nil {
return nil, err
}
defer rows.Close()
out := []Document{}
for rows.Next() {
d, err := scanDocument(rows)
if err != nil {
return nil, err
}
out = append(out, *d)
}
return out, rows.Err()
}
func (p *Postgres) GetDocumentByExternalID(ctx context.Context, tenantID, externalID string) (*Document, error) {
if externalID == "" {
return nil, ErrNotFound
}
d, err := scanDocument(p.pool.QueryRow(ctx, documentSelect+`WHERE tenant_id = $1::uuid AND external_id = $2`, tenantID, externalID))
if isInvalidUUID(err) {
return nil, ErrNotFound
}
return d, err
}
func (p *Postgres) SetDocumentProcessing(ctx context.Context, docID, status, errMsg string) (*Document, error) {
if len(errMsg) > 500 {
errMsg = errMsg[:500]
}
tag, err := p.pool.Exec(ctx, `
UPDATE documents SET processing_status = $2, processing_error = $3, updated_at = now() WHERE id = $1::uuid`,
docID, status, errMsg)
switch {
case isInvalidUUID(err):
return nil, ErrNotFound
case isCheckViolation(err):
return nil, ErrInvalidInput
case err != nil:
return nil, err
case tag.RowsAffected() == 0:
return nil, ErrNotFound
}
return p.GetDocument(ctx, docID)
}
const preparationSelect = `
SELECT document_id::text, format, revision, pin, chunk_object_key, chunk_sha256, chunk_bytes, chunk_count,
consent_object_key, consent_sha256, asset_digests, delivered_by, delivered_at
FROM document_preparations `
func scanPreparation(row pgx.Row) (*Preparation, error) {
var x Preparation
if err := row.Scan(&x.DocumentID, &x.Format, &x.Revision, &x.Pin, &x.ChunkObjectKey, &x.ChunkSHA256, &x.ChunkBytes, &x.ChunkCount,
&x.ConsentObjectKey, &x.ConsentSHA256, &x.AssetDigests, &x.DeliveredBy, &x.DeliveredAt); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrNotFound
}
return nil, err
}
if x.AssetDigests == nil {
x.AssetDigests = []string{}
}
return &x, nil
}
func (p *Postgres) SaveDocumentPreparation(ctx context.Context, in Preparation) (*Preparation, error) {
if !in.HasChunks() && !in.HasConsent() {
return nil, ErrInvalidInput
}
tx, err := p.pool.Begin(ctx)
if err != nil {
return nil, err
}
defer func() { _ = tx.Rollback(ctx) }()
cur, err := scanPreparation(tx.QueryRow(ctx, preparationSelect+`WHERE document_id = $1::uuid FOR UPDATE`, in.DocumentID))
switch {
case isInvalidUUID(err):
return nil, ErrNotFound
case errors.Is(err, ErrNotFound):
cur = nil
case err != nil:
return nil, err
}
next := mergePreparation(cur, in)
_, err = tx.Exec(ctx, `
INSERT INTO document_preparations (document_id, format, revision, pin, chunk_object_key, chunk_sha256, chunk_bytes, chunk_count,
consent_object_key, consent_sha256, asset_digests, delivered_by, delivered_at)
VALUES ($1::uuid, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, now())
ON CONFLICT (document_id) DO UPDATE SET format = $2, revision = $3, pin = $4, chunk_object_key = $5, chunk_sha256 = $6,
chunk_bytes = $7, chunk_count = $8, consent_object_key = $9, consent_sha256 = $10, asset_digests = $11,
delivered_by = $12, delivered_at = now()`,
next.DocumentID, next.Format, next.Revision, next.Pin, next.ChunkObjectKey, next.ChunkSHA256, next.ChunkBytes, next.ChunkCount,
next.ConsentObjectKey, next.ConsentSHA256, next.AssetDigests, next.DeliveredBy)
switch {
case isFKViolation(err):
return nil, ErrNotFound
case isCheckViolation(err):
return nil, ErrInvalidInput
case err != nil:
return nil, err
}
if next.HasChunks() {
if _, err := tx.Exec(ctx, `UPDATE documents SET processing_status = 'ready', processing_error = '', updated_at = now() WHERE id = $1::uuid`,
next.DocumentID); err != nil {
return nil, err
}
}
if err := tx.Commit(ctx); err != nil {
return nil, err
}
return p.GetDocumentPreparation(ctx, next.DocumentID)
}
func (p *Postgres) GetDocumentPreparation(ctx context.Context, docID string) (*Preparation, error) {
x, err := scanPreparation(p.pool.QueryRow(ctx, preparationSelect+`WHERE document_id = $1::uuid`, docID))
if isInvalidUUID(err) {
return nil, ErrNotFound
}
return x, err
}
func (p *Postgres) ListDocumentPreparations(ctx context.Context, tenantID string) (map[string]Preparation, error) {
rows, err := p.pool.Query(ctx, preparationSelect+`
WHERE document_id IN (SELECT id FROM documents WHERE tenant_id = $1::uuid)`, tenantID)
if isInvalidUUID(err) {
return map[string]Preparation{}, nil
}
if err != nil {
return nil, err
}
defer rows.Close()
out := map[string]Preparation{}
for rows.Next() {
x, err := scanPreparation(rows)
if err != nil {
return nil, err
}
out[x.DocumentID] = *x
}
return out, rows.Err()
}
func (p *Postgres) PutStoreAsset(ctx context.Context, a StoreAsset) (*StoreAsset, error) {
if !hex64(a.SHA256) || a.ObjectKey == "" {
return nil, ErrInvalidInput
}
_, err := p.pool.Exec(ctx, `
INSERT INTO store_assets (tenant_id, sha256, object_key, content_type, size_bytes)
VALUES ($1::uuid, $2, $3, $4, $5) ON CONFLICT (tenant_id, sha256) DO NOTHING`,
a.TenantID, a.SHA256, a.ObjectKey, a.ContentType, a.SizeBytes)
switch {
case isFKViolation(err), isInvalidUUID(err):
return nil, ErrNotFound
case err != nil:
return nil, err
}
return p.GetStoreAsset(ctx, a.TenantID, a.SHA256)
}
func (p *Postgres) GetStoreAsset(ctx context.Context, tenantID, sha string) (*StoreAsset, error) {
var a StoreAsset
err := p.pool.QueryRow(ctx, `
SELECT tenant_id::text, sha256, object_key, content_type, size_bytes, created_at
FROM store_assets WHERE tenant_id = $1::uuid AND sha256 = $2`, tenantID, sha).
Scan(&a.TenantID, &a.SHA256, &a.ObjectKey, &a.ContentType, &a.SizeBytes, &a.CreatedAt)
switch {
case errors.Is(err, pgx.ErrNoRows), isInvalidUUID(err):
return nil, ErrNotFound
case err != nil:
return nil, err
}
return &a, nil
}