feat(intake): page the pending list and say when a capture is settled #120

Merged
sharang merged 1 commits from feat/r1-intake-cursor into main 2026-11-10 09:57:01 +00:00
9 changed files with 74 additions and 19 deletions

No files matched your search

+14 -3
View File
@@ -295,8 +295,10 @@ func serviceOnly(w http.ResponseWriter, r *http.Request) (*authn.Principal, bool
return p, true
}
// pendingIntake is GET /v1/internal/intake/pending?limit=: entries not
// settled yet, oldest first, across workspaces.
// pendingIntake is GET /v1/internal/intake/pending?after=&limit=: entries
// not settled yet with an id above after, oldest first, across workspaces.
// A reader pages on with the last id it got, so that entries that keep
// waiting in one workspace never hide those of another.
func (s *Server) pendingIntake(w http.ResponseWriter, r *http.Request) {
if _, ok := serviceOnly(w, r); !ok {
return
@@ -310,9 +312,18 @@ func (s *Server) pendingIntake(w http.ResponseWriter, r *http.Request) {
}
limit = n
}
var after int64
if v := r.URL.Query().Get("after"); v != "" {
n, err := strconv.ParseInt(v, 10, 64)
if err != nil || n < 0 {
writeError(w, http.StatusBadRequest, "invalid_after", "after is an entry id, 0 or more")
return
}
after = n
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
items, err := s.Store.PendingIntake(ctx, limit)
items, err := s.Store.PendingIntake(ctx, after, limit)
if err != nil {
writeError(w, http.StatusInternalServerError, "internal", err.Error())
return
+23 -4
View File
@@ -74,18 +74,37 @@ func TestIntakeStore(t *testing.T) {
entries[0].Receipts[1].Reason != "target_ambiguous" || entries[1].Status() != "" || string(entries[0].Content) == "" {
t.Fatalf("entries: %+v %v", entries, err)
}
pending, err := h.store.PendingIntake(ctx, 10)
pending, err := h.store.PendingIntake(ctx, 0, 10)
if err != nil || len(pending) != 2 || pending[0].Reference != r3.Reference || pending[1].EntryID != s1.ID ||
pending[1].About != store.IntakeAboutProduct || !pending[1].ReceivedAt.Equal(r1.ReceivedAt) {
t.Fatalf("pending: %+v %v", pending, err)
}
if p, _ := h.store.PendingIntake(ctx, 1); len(p) != 1 {
if p, _ := h.store.PendingIntake(ctx, 0, 1); len(p) != 1 {
t.Fatalf("limit: %+v", p)
}
// Paging on: only ids above the last one; a supplement says its
// capture is settled, an unsettled capture says it is not.
if p, _ := h.store.PendingIntake(ctx, pending[0].EntryID, 10); len(p) != 1 || p[0].EntryID != s1.ID || !p[0].CaptureSettled {
t.Fatalf("after: %+v", p)
}
if p, _ := h.store.PendingIntake(ctx, s1.ID, 10); len(p) != 0 {
t.Fatalf("after the last: %+v", p)
}
if pending[0].CaptureSettled {
t.Fatalf("an open capture: %+v", pending[0])
}
r4, _ := capture("u-3", store.IntakeAboutUnknown)
s4, err := h.store.AddIntakeSupplement(ctx, h.tenant.ID, r4.Reference, "u-3", json.RawMessage(`{"what":"z"}`), at)
if err != nil {
t.Fatal(err)
}
if p, _ := h.store.PendingIntake(ctx, s1.ID, 10); len(p) != 2 || p[1].EntryID != s4.ID || p[1].CaptureSettled {
t.Fatalf("supplement to an open capture: %+v", p)
}
if _, err := h.store.AddIntakeReceipt(ctx, store.IntakeReceipt{EntryID: s1.ID, Status: store.IntakeDelivered, HandoffID: "h-7", By: "w", At: at}); err != nil {
t.Fatal(err)
}
if p, _ := h.store.PendingIntake(ctx, 10); p[1].Status != store.IntakeDelivered || p[1].HandoffID != "h-7" {
if p, _ := h.store.PendingIntake(ctx, 0, 10); p[1].Status != store.IntakeDelivered || p[1].HandoffID != "h-7" {
t.Fatalf("pending status: %+v", p)
}
@@ -127,7 +146,7 @@ func TestIntakeStore(t *testing.T) {
if err := h.store.DeleteTenant(ctx, h.tenant.ID); err != nil {
t.Fatal(err)
}
if p, err := h.store.PendingIntake(ctx, 10); err != nil || len(p) != 0 {
if p, err := h.store.PendingIntake(ctx, 0, 10); err != nil || len(p) != 0 {
t.Fatalf("after the tenant is purged: %+v %v", p, err)
}
})
+7 -1
View File
@@ -139,9 +139,13 @@ func TestIntakeIsTakenOver(t *testing.T) {
}
}
_, out, _ = f.do(t, "werkmeister", "GET", "/v1/internal/intake/pending", "")
if items := out["items"].([]any); len(items) != 1 || items[0].(map[string]any)["kind"] != "supplement" {
if items := out["items"].([]any); len(items) != 1 || items[0].(map[string]any)["kind"] != "supplement" || items[0].(map[string]any)["capture_settled"] != true {
t.Fatalf("pending after processing: %v", out)
}
last := itoa(int(out["items"].([]any)[0].(map[string]any)["entry_id"].(float64)))
if _, out, _ := f.do(t, "werkmeister", "GET", "/v1/internal/intake/pending?after="+last, ""); len(out["items"].([]any)) != 0 {
t.Fatalf("after the last: %v", out)
}
_, out, raw = f.do(t, "staff", "GET", f.intake("/"+ref), "")
receipts := out["entries"].([]any)[0].(map[string]any)["receipts"].([]any)
if out["handover"] != "processed" || len(receipts) != 3 || receipts[0].(map[string]any)["reason"] != "target_unknown" {
@@ -159,6 +163,8 @@ func TestIntakeIsTakenOver(t *testing.T) {
"not an id": {"werkmeister", "POST", "/v1/internal/intake/entries/x/receipts", `{"status":"waiting"}`, http.StatusNotFound},
"not json": {"werkmeister", "POST", "/v1/internal/intake/entries/2/receipts", `{`, http.StatusBadRequest},
"limit": {"werkmeister", "GET", "/v1/internal/intake/pending?limit=201", "", http.StatusBadRequest},
"after": {"werkmeister", "GET", "/v1/internal/intake/pending?after=-1", "", http.StatusBadRequest},
"after2": {"werkmeister", "GET", "/v1/internal/intake/pending?after=x", "", http.StatusBadRequest},
"user": {"staff", "GET", "/v1/internal/intake/pending", "", http.StatusForbidden},
"portal svc": {"portal", "GET", "/v1/internal/intake/pending", "", http.StatusForbidden},
} {
+1 -1
View File
@@ -56,7 +56,7 @@ func TestOpenAPISpec_loadsAndIsConsistent(t *testing.T) {
{"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/intake/reports"},
{"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/intake/reports/SH-2026-00001"},
{"POST", "/v1/tenants/00000000-0000-0000-0000-000000000001/intake/reports/SH-2026-00001/supplements"},
{"GET", "/v1/internal/intake/pending?limit=10"},
{"GET", "/v1/internal/intake/pending?after=3&limit=10"},
{"POST", "/v1/internal/intake/entries/1/receipts"},
{"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/role-dataset/resolve?decision_type=r1.release_d01"},
{"GET", "/v1/tenants/00000000-0000-0000-0000-000000000001/products/pruefwerk/settings"},
+3
View File
@@ -109,4 +109,7 @@ type PendingIntake struct {
Status string `json:"status,omitempty"`
Reason string `json:"reason,omitempty"`
HandoffID string `json:"handoff_id,omitempty"`
// CaptureSettled: the report's capture is processed or refused. A
// supplement is handed over only after its capture.
CaptureSettled bool `json:"capture_settled"`
}
+13 -2
View File
@@ -109,7 +109,7 @@ func (m *Memory) AddIntakeSupplement(_ context.Context, tenantID, ref, by string
return &e, nil
}
func (m *Memory) PendingIntake(_ context.Context, limit int) ([]PendingIntake, error) {
func (m *Memory) PendingIntake(_ context.Context, after int64, limit int) ([]PendingIntake, error) {
m.mu.RLock()
defer m.mu.RUnlock()
out := []PendingIntake{}
@@ -117,7 +117,7 @@ func (m *Memory) PendingIntake(_ context.Context, limit int) ([]PendingIntake, e
if len(out) >= limit {
break
}
if n := len(e.Receipts); n > 0 && e.Receipts[n-1].Settled() {
if n := len(e.Receipts); e.ID <= after || n > 0 && e.Receipts[n-1].Settled() {
continue
}
r, _ := m.report(e.TenantID, e.Reference)
@@ -127,11 +127,22 @@ func (m *Memory) PendingIntake(_ context.Context, limit int) ([]PendingIntake, e
last := e.Receipts[n-1]
p.Status, p.Reason, p.HandoffID = last.Status, last.Reason, last.HandoffID
}
p.CaptureSettled = m.captureSettled(e.TenantID, e.Reference)
out = append(out, p)
}
return out, nil
}
func (m *Memory) captureSettled(tenantID, ref string) bool {
for _, e := range m.intakeEntries {
if e.TenantID == tenantID && e.Reference == ref && e.Kind == IntakeEntryCapture {
n := len(e.Receipts)
return n > 0 && e.Receipts[n-1].Settled()
}
}
return false
}
func (m *Memory) AddIntakeReceipt(_ context.Context, r IntakeReceipt) (bool, error) {
if !validReceipt(r) {
return false, ErrInvalidInput
+8 -5
View File
@@ -159,15 +159,18 @@ func (p *Postgres) AddIntakeSupplement(ctx context.Context, tenantID, ref, by st
return insertIntakeEntry(ctx, p.pool, tenantID, ref, IntakeEntrySupplement, by, content, at.UTC().Truncate(time.Microsecond))
}
func (p *Postgres) PendingIntake(ctx context.Context, limit int) ([]PendingIntake, error) {
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, '')
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 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 $1`, limit)
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
}
@@ -175,7 +178,7 @@ func (p *Postgres) PendingIntake(ctx context.Context, limit int) ([]PendingIntak
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); err != nil {
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)
+2 -2
View File
@@ -256,7 +256,7 @@ type Store interface {
// IntakeEntries are ErrNotFound for an unknown reference;
// ListIntakeReports lists one reporter's reports, newest first.
// AddIntakeSupplement adds a supplement. PendingIntake lists entries not
// settled yet, oldest first, across tenants. AddIntakeReceipt adds a
// settled yet with an id above after, oldest first, across tenants. AddIntakeReceipt adds a
// receipt unless it repeats the newest one (added=false); ErrConflict
// once the entry is settled, ErrNotFound for an unknown entry.
CreateIntakeReport(ctx context.Context, c IntakeCapture) (*IntakeReport, *IntakeEntry, error)
@@ -264,7 +264,7 @@ type Store interface {
ListIntakeReports(ctx context.Context, tenantID, reporterSub string) ([]IntakeReport, error)
IntakeEntries(ctx context.Context, tenantID, reference string) ([]IntakeEntry, error)
AddIntakeSupplement(ctx context.Context, tenantID, reference, by string, content json.RawMessage, at time.Time) (*IntakeEntry, error)
PendingIntake(ctx context.Context, limit int) ([]PendingIntake, error)
PendingIntake(ctx context.Context, after int64, limit int) ([]PendingIntake, error)
AddIntakeReceipt(ctx context.Context, r IntakeReceipt) (added bool, err error)
// Product settings (0025): the workspace's own choices per product,
+3 -1
View File
@@ -629,6 +629,7 @@ paths:
reference and the reporter's own answers routing reads, never the
text. A person's token is refused (`service_token_required`).
parameters:
- { in: query, name: after, schema: { type: integer, minimum: 0, default: 0 }, description: "Only entries with a higher id: the last id of the previous page." }
- { in: query, name: limit, schema: { type: integer, minimum: 1, maximum: 200, default: 50 } }
responses:
"200":
@@ -639,7 +640,7 @@ paths:
type: object
properties:
items: { type: array, items: { $ref: "#/components/schemas/PendingIntake" } }
"400": { description: invalid_limit. }
"400": { description: invalid_limit or invalid_after. }
"403": { description: service_token_required or FORBIDDEN_CLIENT. }
/v1/internal/intake/entries/{entry}/receipts:
@@ -2557,6 +2558,7 @@ components:
status: { type: string, description: "The newest receipt's status, if any." }
reason: { type: string }
handoff_id: { type: string, description: "The newest receipt's handoff, if any." }
capture_settled: { type: boolean, description: "The report's capture is processed or refused; a supplement goes on only after it." }
RoleDatasetState:
type: object
required: [tenant_id, revision, catalogue_version, data, derived, catalogue]