Skip to content

Architecture

The API follows a strict layered architecture. Requests flow API → Service → Persistence, and domain types (internal/model) carry data across those boundaries.

graph TD
    subgraph API ["API Layer — internal/api"]
        MW[Middleware<br/>logger · otel · JWT · CORS]
        RT[Echo routes + handlers]
    end
    subgraph SVC ["Service Layer — internal/service"]
        AD[Auth decorator<br/>authz.Check / ScopeOrgs]
        AU[Audit decorator<br/>audit.Logger]
        CR[Core impl]
    end
    subgraph PS ["Persistence — internal/db + storage"]
        PG[(Postgres<br/>via sqlc/pgx)]
        SB[S3 bucket]
    end

    RT --> AD --> AU --> CR --> PG
    CR --> SB

The entry point for all requests, built on Echo v5. api.go holds the route table; middleware.go holds the chain. Handlers parse and validate input, then delegate to a service — they contain minimal business logic.

Routes are split into three groups by auth requirement:

  • public — CORS only.
  • protected — session JWT cookie or a bearer workflow token (Temporal workers calling back on behalf of a user; see Authentication).
  • password-reset — a dedicated JWT purpose.

Handlers follow one consistent shape: a function-scoped request struct with param:"…" / json:"…" tags, c.Bind(req), a service call, then c.JSON(...). Swagger annotations sit directly above each handler.

The core business logic — orchestrating transactions, Temporal, and storage. It’s organized per domain (auth, bond, premium, document, project, audit), and within each domain the files split by concern:

  • service.go — the Service interface + the core struct + constructors.
  • core_*.go — the real implementations (methods on *core).
  • cache_*.go — the cache decorator, memoizing reads and invalidating them on writes (only active when cfg.EnableCache).
  • audit_*.go — the audit decorator (methods on *auditDecorator), which records each successful create / update / delete (evidence rows are the one deliberate exception; see The decorator pattern).
  • auth_*.go — the authorization decorator (methods on *authDecorator), which calls internal/authz before delegating to the core.

Redis is wrapped behind an internal/cache package, initialized only when cfg.EnableCache is set. Service-level caching is live: each domain service is wrapped by a WithCache decorator that memoizes Get/List reads and invalidates them via a scope-based version scheme. Every cache key folds in a version counter for each scope it touches — a scope being any resource id.ULID (or []id.ULID) passed to Key(...). Cache.Invalidate(ctx, prefix, scopes…) bumps the version counter for each affected scope in a single Redis pipeline, which atomically expires both that object’s Get entry and every List entry that referenced it — without scanning keys (internal/cache/cache.go, key.go). The happy path is silent now: Get/Set log nothing on a hit or a miss and only surface a slog.Warn when something is wrong (cache key has no scopes, skipping cache, cache get/set/marshal/unmarshal/invalidate failed), so a cold cache no longer announces itself in the logs.

All database access goes through sqlc-generated, type-safe Go. Services never touch raw rows — they call generated Queries methods and convert results to model types via FromDB converters.

Cross-cutting concerns are applied with the decorator pattern. Each domain service is built as a core, then wrapped by up to three decorators — an audit decorator (WithAudit, always on), a cache decorator (WithCache, when cfg.EnableCache) and an authorization decorator (WithAuth, when cfg.EnableAuthorization). Each wraps the previous, so a call flows authz → cache → audit → core. Composition happens in internal/service/service.go:

authenticator := authn.New(cfg)
svc.Auth = authservice.New(cfg, db, str, wf, authenticator)
svc.Bond = bondservice.New(cfg, db, str, wf)
svc.Project = projectservice.New(cfg, db, str) // note: no wf
svc.Premium = premiumservice.New(db)
// …
auditLogger := audit.NewLogger(db.Audit.Log)
svc.Auth = authservice.WithAudit(svc.Auth, auditLogger)
svc.Bond = bondservice.WithAudit(svc.Bond, auditLogger)
// …
if cfg.EnableCache {
cache, _ := cache.New(cfg)
svc.Project = projectservice.WithCache(svc.Project, cache)
svc.Premium = premiumservice.WithCache(svc.Premium, cache)
svc.Bond = bondservice.WithCache(svc.Bond, cache)
svc.Auth = authservice.WithCache(svc.Auth, cache)
// …
}
if cfg.EnableAuthorization {
authorizer := authz.New(db)
svc.Auth = authservice.WithAuth(svc.Auth, authorizer)
svc.Bond = bondservice.WithAuth(svc.Bond, authorizer)
svc.Audit = auditservice.WithAuth(svc.Audit, authorizer)
// …
}

Auditing is the always-on WithAudit decorator (audit_*.go per service, backed by internal/audit/logger.go). It runs after the core method returns, so only committed mutations are logged: creates log the result, updates Get the resource first and log before + after, deletes log what was removed. Each audit.audit_log row records the actor (actor_id, actor_org_id, from the request’s session), the action, the target (target_type, target_id, target_org_id), the before / after snapshots (JSONB; they were in the encrypted domain until #503), and the request’s trace_id. A failed audit write is logged, not returned — it never fails the mutation. There is no unaudited caller: worker requests authenticate with a workflow token and are audited as the user who started the workflow. The one unaudited resource is bond_request_field_evidence (#529): audit_bond_request_field_evidence.go passes its create and delete straight through, because the generate workflow already audits the field update that goes with them.

QUERY /log reads the audit log back, newest first, as a keyset-paginated list. This used to call it “the one keyset-paginated list” (#501), with a default limit of 50; since #505 seven other lists page the same way, and an omitted limit returns every row. Filters are actorOrgIDIn, actorIDIn, actionIn, targetOrgIDIn, and targetIDIn. before / after reach the SDKs as free-form objects.

There is a single db/ tree. For each table, sqlc.yaml points a generated package under internal/db/ at that table’s db/<schema>/<table>/query.sql (the queries:) with a shared schema: "db/_migrations" — sqlc reads the goose migrations as its schema (ignoring the Down halves). Notable global config:

  • Type overrides: uuid → internal/id.ULID, timestamptz → time.Time, jsonb → json.RawMessage, and page → internal/db/page.Params (#505).
  • PII columns are ordinary TEXT / TEXT[] / JSONB. This used to say they used an encrypted Postgres domain mapped to internal/crypt.Encrypted; app-level field encryption was removed in #503, and at-rest encryption is Railway’s. See Data Protection.

Regenerate after editing any db/<schema>/<table>/query.sql with mise run sql (which first formats the query files with sql-formatter, then runs sqlc generate).

Every list endpoint uses the HTTP QUERY method with a JSON body carrying array filters (*In fields) — not GET with query strings. This lets a list take rich, repeatable filters (e.g. statusIn, orgIDIn) in a body without the length and encoding limits of a query string. Not every filter is an array: the bond, bond-request, and organization lists also take a scalar search string (#393), matched server-side over related names (a bond/bond-request against its org and project name, an organization against its own) so the client doesn’t page the whole list to filter it. The bond-request list additionally gained a bondTypeIn filter (#392), matching the bond list.

There are 19 such endpoints. Each is registered once in api.go:

pro.QUERY("/bond_request", bond.ListBondRequest)

The toolchain can’t express QUERY directly: swag’s @Router method whitelist stops at PATCH, and OpenAPI 3.1 has no QUERY. So handlers are annotated as POST /x/query placeholders, and scripts/openapi_query.jq rewrites each one into a first-class QUERY /x operation while bumping the spec to OpenAPI 3.2 (see Development › SDK generation). The POST /x/query path exists only in the annotations, not as a live route, so swagger-ui’s “try it out” on it returns 404. This section used to show a registered POST twin next to each QUERY route; api.go has no such twin.

Eight lists are keyset-paginated and sorted in SQL (#505): /user, /invite, /organization, /attachment, /seal, /bond_request, /bond, and /log. Their request body embeds model.Page (internal/model/page.go): an opaque cursor, a limit, a sort, and an order (asc / desc). They return Paged — {items, nextCursor}, with nextCursor null on the last page. A limit of 0 or omitted returns every row; 1–200 returns one page; anything else is a 400, as are an unknown sort or order and a cursor reused with a different sort or order. Rows are ordered on (value, id), NULLs last in both directions.

Each resource declares its sort enum and default in internal/model/sort.go (the first key is the default):

List sort keys Default
/user name, email, createdAt, admin name asc
/invite createdAt, email createdAt desc
/organization name, members, createdAt name asc
/attachment, /seal createdAt createdAt desc
/bond_request sentAt, createdAt sentAt desc
/bond createdAt, filedAt, endAt createdAt desc
/log createdAt createdAt desc

In SQL, every list query takes a single page composite-type parameter (db/_global/page.sql, migration 00032), which sqlc maps to the hand-written internal/db/page.Params. The other eleven QUERY lists still return plain arrays. In the SDKs the eight paged methods are Speakeasy cursor iterators: scripts/openapi_query.jq stamps x-speakeasy-pagination on every Paged-* operation.

Two domains arrived alongside the rename. A derived /bond resource (bond.bond table) holds the finalized bid/final bond records — QUERY /bond, POST /bond, GET/PUT/DELETE /bond/:bondID. Bonds used to be created implicitly when a bond request was marked completed; that was removed (#424) in favour of the explicit POST /bond (bond.CreateBond), which takes a project plus exactly one matching bidData / finalData payload and derives the org from the project. Create and update also require a bondNumber (#460, #461). Its list filter gained a parentOrgIDIn field that scopes bonds to child orgs of the given parents (a SQL subquery over auth.organization.parent_id), alongside orgIDIn / projectIDIn / bondTypeIn. It also takes date ranges (model.BondDateFilter): createdFrom/createdTo (#517), filedFrom/filedTo (#505), and endFrom/endTo (#515). They are RFC 3339 dates, inclusive, compared as UTC days, and combinable; filedAt is a bid bond’s bid date or a final bond’s contract start date, endAt a final bond’s contract end date, and a bond without that date is excluded while its range is set. A new premium schema (premium.rate, premium.rate_tier) adds full CRUD under /rate and /rate_tier via internal/service/premium/ and internal/api/premium/.

Bid result attachments are a resource of their own (#467, renamed in #506): a bond.bid_result_attachment row per file, so a bond can carry several, with CRUD under /bid_result_attachment and GET /bid_result_attachment/:bidResultAttachmentID/presign (?upload=true for a PUT URL, else a read URL; text/plain body). Objects still live under the bid_result/ prefix keyed by the row ID; the rename moved no objects. Migration 00031 renamed the table and rewrote audit_log.target_type to match. The bid outcome itself is no longer a bidWon boolean: BidBondData carries an optional bidResult (absent means pending) plus bidNotes, and 00031 mapped true → won and false → lost. The upload path used to be a single GET /bond/:bondID/bid_result/presign keyed by the bond ID (#400); a one-off mise run db:bid-result-key backfilled rows for those legacy objects (the command was removed in #488 after it had run everywhere).

Attachments (#463) are PDFs appended to a bond form — CRUD under /attachment plus GET /attachment/:attachmentID/presign, stored under attachment/. A bond.attachment row carries a type (AttachmentType: Power of Attorney, Certificate of Authority, Notary Form, Other) and its page length. A bond form lists them in order in an attachments UUID[] column (GIN-indexed; a trigger blocks deleting an attachment a form still uses), which replaces the form’s single poaID in the model — migration 00022 copied every power of attorney into bond.attachment, and a one-off mise run db:attachment-length filled in their page counts (also removed in #488). Migration 00027 (#488) then dropped bond_form.poa_id and the bond.power_of_attorney table, along with the /power_of_attorney routes. A bond form field is anchored to a segment: attachmentID (null for the form’s own pages) plus a page that is 0-based within that segment. Detaching an attachment deletes its fields. On export the API appends the attachments in order, merges them, and offsets each field by the page count of everything before its segment.

Bond request specs (#525, #527) define each agency’s bond request form: its sections, in order, and per field a snake_case ref, name, format, width, required, whether RAG generated it and with which retrieval and generation query. There is one spec per agency and bond type, stored in bond.bond_request_spec_section and bond.bond_request_spec_field (migration 00035). A section’s type (00036) is fields, contractor_account or bond_forms, which tells the app where to place the contractor select and the bond forms table. Routes:

  • GET /bond_request_spec/base/:bondType: the built-in base spec, embedded from internal/model/base_spec/{bid,final}_bond_request.yaml. It replaces GET /bond_request/spec/:bondType, which served the one global spec.
  • GET /bond_request_spec/:orgID/:bondType: the agency’s spec. A contractor org gets its parent agency’s spec. This read is deliberately uncached.
  • POST / PUT /bond_request_spec/:orgID/:bondType: copy the base spec to an agency, or replace its spec. Root-only (isRootWritable). Fields marked core are read by ref elsewhere, so they can’t be removed or change format.

An agency without a spec can’t create bond requests, so the app creates both specs right after it creates an agency. Field refs are no longer a fixed enum: any snake_case string matching ^[a-z][a-z0-9]*(_[a-z0-9]+)*$ is valid, and 00037 renamed every stored camelCase ref (bidDate → bid_date, #528). The contractor is no longer a spec field either: it is the column bond_request.contractor_account_id (00034, a foreign key to auth.contractor_account, ON DELETE SET NULL).

Field evidence (#529) is a resource of its own, so one generated field can cite several documents and pages. A bond.bond_request_field_evidence row (field_id, document_id, page; migration 00038) replaces the field’s single evidence_doc_id / evidence_page columns, which were dropped. Routes are QUERY /bond_request_field_evidence (filter fieldIDIn, a plain array), POST, GET / DELETE /bond_request_field_evidence/:evidenceID, and GET /bond_request_field_evidence/:evidenceID/presign. There is no update. The image is stored under evidence/ keyed by the evidence ID. This used to be GET /bond_request_field/:fieldID/evidence/presign, keyed by the field ID; 00038 gave each backfilled row its field’s ID, so no objects moved. As of this writing all of this is on staging only.

Enum types live in internal/model as type X string with a typed constant set and a // @name X annotation for the SDK. Database columns stay plain string/TEXT — conversion happens at the boundary (request binding writes string(x), FromDB converters cast back; the spec tables do add CHECK constraints for their three enums). Enums: OrgType, BondType, BondRequestStatus, BondFormFieldType, AttachmentType, WorkflowStatus, AuditAction, BondRequestSpecSectionType, BondRequestFieldFormat, BondRequestFieldWidth (#525, #527), Order and the per-list sort enums (UserSort, InviteSort, OrganizationSort, AttachmentSort, SealSort, BondRequestSort, BondSort, AuditLogSort; #505), and BidResult (won, lost, second, disqualified, no_bid, cancelled; #506, stored in the bond’s data JSONB rather than a column). This list used to include BondRequestFieldRef; since #528 it has no constants and is a plain validated string in the SDK. (The JWT Purpose type is not an SDK enum — it lives in internal/authn, see Authentication.)

BondRequestStatus is special: there is no status column. A bond request’s status is derived from two zero-timestamp sentinels:

sent_at TIMESTAMPTZ NOT NULL DEFAULT '0001-01-01 00:00:00+00',
completed_at TIMESTAMPTZ NOT NULL DEFAULT '0001-01-01 00:00:00+00',

draft if both are the sentinel, sent once sent_at is set, completed once completed_at is set — derived identically in the Go FromDB converter and in the SQL list filter (a CASE comparing against '0001-01-01…', not IS NULL). The draft → sent transition also fires the SendBondRequest notification workflow.

Authentication now lives in its own package, internal/authn, which “owns who is calling”: it mints the session JWT and carries the authenticated principal through the request context (authorization — what they may do — lives in internal/authz, see the decorator pattern).

  • JWT, HS256 (golang-jwt/jwt/v5), carried in an HttpOnly cookie named jwt. The authn.Authenticator (authn.New(cfg)) mints tokens; the Echo JWT middleware verifies them.
  • Claims embed model.SessionClaims{ UserID, OrgID, OrgType } plus a Purpose and the standard registered claims. OrgType (the role) lives in the token so the frontend can route without a round-trip. The per-user Admin flag lives on the DB user row.
  • Purpose is a typed enum — authn.Purpose: PurposeSession ("session", 10d TTL), PurposePasswordReset ("password_reset", 10m TTL), or PurposeWorkflow ("workflow", 3d TTL). It is not a model / SDK enum.
  • Two strategies on the protected group (authMiddleware): the cookie JWT (purpose=session) for users, then a bearer workflow token (purpose=workflow) for Temporal workers. The password-reset group uses a dedicated pwResetAuthMiddleware.
  • Workflow tokens are minted by the API’s Temporal propagator (internal/workflow/propagator.go) whenever a workflow is started from an authenticated request: it copies the caller’s UserID / OrgID / OrgType into a 3-day workflow-purpose JWT and writes it to the x-huddle-token workflow header. RAG and Notification send it back as Authorization: Bearer <token>, so their calls are authorized and audited as that user. Because it’s signed with the HKDF-derived workflow key, it can’t be replayed as a session cookie (or vice versa). There is no service key.
  • Verification is jwtMiddleware(secret, purpose) (internal/api/middleware.go) wrapping echojwt with SigningKey: authn.SigningKey(secret, purpose) and the purpose’s token location from tokenLookups (cookie for session and password-reset, Authorization: Bearer for workflow). Its SuccessHandler rejects a token whose Purpose doesn’t match the group (model.ErrUnauthorized) and stamps the principal via authn.WithSession.

There is no error-mapping middleware anymore. model.Error carries an HTTP status itself and implements Echo’s HTTPStatusCoder, so Echo’s DefaultHTTPErrorHandler alone renders the response — a model.Error returns its own status and a {"message": …} body (the curated message only, never the wrapped cause), while any plain error surfaces as 500 Internal Server Error.

The sentinels (internal/model/error.go) each pin a status: ErrBadRequest (400), ErrUnauthorized (401), ErrForbidden (403), ErrNotFound (404), ErrConflict (409). Wrap(err) attaches a server-side cause for logging, WithMsg(msg) swaps the client-facing message, and errors.Is matches through the derivation chain (pgx.ErrNoRows → ErrNotFound).

The API is a Temporal client only — it defines no workers or workflows. It dials the Temporal cluster (namespace = deployment environment) with an OTel tracing interceptor and a requester propagator that mints the workflow token (see Distributed tracing), and triggers workflows on two task queues:

  • RAG queue: GenerateField, ParseDocument, DeleteDocument, FindBond, FillBond, ProcessBondRequest.
  • Notification queue: SendInvite, SendOTP, SendBondRequest.

internal/workflow wraps the client with Execute(...) and Watch(...). Two behaviors worth knowing:

  • Deterministic workflow IDs — {taskQueue}/{workflow}/sha256(args). Re-triggering with identical args terminates and replaces the running execution. The RAG service replicates this exact ID scheme so the app’s status subscriptions keep working across the parent/child workflow split (see RAG › Architecture).
  • Status is streamed, not polled by callers. The old per-caller GetStatus endpoints are gone; the API exposes SSE watch routes (GET …/watch) that push a bare WorkflowStatus ("running" / "completed" / "failed") whenever it changes — see below.

workflow.Client embeds a Watcher that owns a single background poll loop (internal/workflow/watcher.go). Client.Watch(ctx, workflow, args…) resolves the deterministic workflow ID and subscribes to it, returning a <-chan model.WorkflowStatus. The watcher polls Temporal (describeStatus, mapping execution state → WorkflowStatus; a workflow Temporal no longer knows reads as completed) at a 1s tick, ≤16 concurrent, but only for workflow IDs that currently have at least one subscriber, and fans out changes to subscribers. A subscriber that falls subscriberBuffer (16) behind is dropped so its client reconnects and gets a fresh snapshot.

Handlers turn that channel into an SSE stream with the generic shared.StreamSSE[T] helper (Content-Type: text/event-stream, 15s : ping heartbeats, each value written as data: <json>\n\n — so a frame is just data: "running"). The watch routes, all GET on the protected group:

pro.GET("/document/:documentID/parse/watch", document.WatchParseDocument)
pro.GET("/bond_request/:requestID/find_bond/watch", bond.WatchFindBondForm)
pro.GET("/bond_request/:requestID/process/watch", bond.WatchProcessBondRequest)
pro.GET("/bond_request_field/:fieldID/generate/watch", bond.WatchGenerateBondRequestField)
pro.GET("/bond_form/:formID/fill/watch", bond.WatchFillBondForm)

Each connection watches exactly one workflow. These routes carry no swaggo response body and are x-speakeasy-ignore’d out of the generated SDKs (the app addresses them by path — see App › Workflow status over SSE).

View workflow executions in the Temporal web UI (Google SSO — see Temporal › Inspecting workflows). The old mise run temporal helper has been removed.