Support tickets
tickets-trial is the framework’s second real service. It was built to find what is hard before anything
else is built on the framework, using only the framework’s public modules: support tickets with
assignees, a status machine, comments, a per-client SLA, an SLA timer run by a scheduled job and a
notification run by a dispatch job. It exists in both languages, with the same table, events, operations
and OpenAPI document, and a single-page application on top.
The Orders tutorial is the smaller example: one aggregate, three use cases. Read it first. This service adds everything that one leaves out.
Where to find each thing
Section titled “Where to find each thing”| You want | In the example | Documentation |
|---|---|---|
| A status machine on an aggregate, with comments appended and never rewritten | the ticket status type and the ticket repository | Write path |
| A client’s own setting (the SLA), defined in code and stored by the framework | the SLA setting and the set-sla-policy use case |
Client settings |
| Permissions checked in the use case, so a receiver and an HTTP call are checked alike | requires(...) and the service-only check |
Write path, Context |
| Roles written once for the platform sync and for the sign-in | the roles table | Module, Sessions and login |
| Checked SQL with optional filters, a cursor, a query across every client | the ticket SQL file | Checked SQL |
| Typed operations, a committed OpenAPI document, a generated client | the API and API module | Typed operations |
| A rate limit on one operation | the comment operation | Rate limiting |
| Definitions in code, synced at deploy time | the definitions module | Module |
| A dispatch receiver that calls another service with the client’s own key | NotifyAssignee |
Receivers, Secrets, HTTP client |
| A scheduled job that works across clients | SlaSweep |
Receivers |
| A loop on one replica at a time | the gauge loop | Background and metrics, Locks |
| An admin section of your own next to the framework’s | the tickets admin module | Admin |
| Tests of use cases, the API with two clients, the platform’s part, the browser | the test suites | Testing |
The domain
Section titled “The domain”A ticket belongs to a client. It has a subject, a description, a priority, a requester, an optional assignee, a due time derived from the client’s SLA, and comments. Its status moves along a small machine:
stateDiagram-v2
[*] --> OPEN
OPEN --> IN_PROGRESS: START (needs an assignee)
IN_PROGRESS --> RESOLVED: RESOLVE (needs a note)
RESOLVED --> OPEN: REOPEN (needs a note)
RESOLVED --> CLOSED: CLOSE
The transition table is a single method, so an illegal move is one Optional.empty() (Java) or false
(Go) away from a business-rule rejection:
public Optional<TicketStatus> after(TicketAction action) { return switch (action) { case START -> this == OPEN ? Optional.of(IN_PROGRESS) : Optional.empty(); case RESOLVE -> this == IN_PROGRESS ? Optional.of(RESOLVED) : Optional.empty(); case REOPEN -> this == RESOLVED ? Optional.of(OPEN) : Optional.empty(); case CLOSE -> this == RESOLVED ? Optional.of(CLOSED) : Optional.empty(); };}func (s Status) After(a Action) (Status, bool) { switch a { case Start: return InProgress, s == Open case Resolve: return Resolved, s == InProgress case Reopen: return Open, s == Resolved // ... }}The service has six use cases: open-ticket, assign-ticket, change-status, add-comment,
flag-sla-breach and set-sla-policy, and nine typed operations (list, get, open, assign, transition,
comment, get and set the SLA policy, and an admin overview).
Patterns worth copying
Section titled “Patterns worth copying”Every change goes through a use case, whoever asks
Section titled “Every change goes through a use case, whoever asks”The HTTP operation, the dispatch handler and the scheduled job all run a use case; none writes SQL. So the permission is checked inside the use case, and a receiver is held to the same rules as a person:
private static Check<Object> requires(String permission) { return (context, command) -> { if (context.principal() == null) { return Optional.of(UseCaseError.authorization("PRINCIPAL_REQUIRED", "Sign in to do this.")); } return context.hasPermission(permission) ? Optional.empty() : Optional.of(UseCaseError.authorization("FORBIDDEN", "You may not do this.")); };}
private static final Check<Object> SERVICE_ONLY = (context, command) -> context.principalKind() == PrincipalKind.SERVICE ? Optional.empty() : Optional.of(UseCaseError.authorization("NOT_A_SERVICE", "Only the application's service does this."));.authorize(requires(Permissions.WORK)) on assign-ticket; .authorize(SERVICE_ONLY) on flag-sla-breach.
func (assignTicket) Authorize(_ context.Context, cx fw.Context, _ usecase.Valid[AssignTicketCmd]) (usecase.Grant, error) { return requires(cx, Work)}and the sweep’s use case admits only the service principal with usecase.RequireService(cx).
A rule that needs the record
Section titled “A rule that needs the record”“A requester may comment only on a ticket they opened” cannot be decided from the command alone. The use case has an extra phase, after the load and before the execute:
UseCase.named("add-comment", AddComment.class, TicketCommented.class) .authorize(requires(Permissions.COMMENT)) .conflict(policy) .load((context, command) -> load(context, command.ticketId()), TICKET_NOT_FOUND) // The record-level rule: it needs the ticket, so it runs after the load, before execute. .authorizeLoaded( (context, command, ticket) -> context.hasPermission(Permissions.WORK) || requester(context).equals(ticket.requesterId()) ? Optional.empty() : Optional.of(UseCaseError.authorization("NOT_YOUR_TICKET", "You may comment only on tickets you opened."))) .execute((context, command, ticket) -> { /* ... */ });func (addComment) AuthorizeLoaded(_ context.Context, cx fw.Context, _ usecase.Authorized[AddCommentCmd], loaded usecase.Loaded[domain.Ticket]) error { if cx.HasPermission(Work) || actor(cx) == loaded.Get().RequesterID { return nil } return usecase.Authorization(NotYourTicket, "You may comment only on tickets you opened.")}Comments are appended, not rewritten
Section titled “Comments are appended, not rewritten”The ticket’s version covers its comments, but the repository’s update writes only the positions that are not stored yet, so a ticket with a thousand comments does not rewrite a thousand rows for the next one. The optimistic-lock test posts two comments at once and checks both land, at the next two positions.
A client’s own setting, without a table of your own
Section titled “A client’s own setting, without a table of your own”The SLA is “minutes allowed to resolve a ticket, by priority”, and each client may set its own. It is not a table, repository and aggregate written by hand; it is one client setting declared in code with a default and a validation rule, and the framework stores it:
public record SlaMinutes(int low, int normal, int high, int urgent) { /* minutesFor(priority) */ }
public static final SlaMinutes DEFAULT_SLA = new SlaMinutes(2880, 1440, 480, 60);
public static final ClientSetting<SlaMinutes> SLA = ClientSetting.of("tickets.sla", SlaMinutes.class, DEFAULT_SLA).rule(m -> problem(m).map(Problem::message));open-ticket reads it once, in execute:
settings.forClient(database, context.client()).get(TicketSettings.SLA).minutesFor(command.priority()).
type SlaMinutes struct { Low, Normal, High, Urgent int32 // json: low, normal, high, urgent}
var DefaultSLA = SlaMinutes{Low: 2880, Normal: 1440, High: 480, Urgent: 60}
s, err := clientsettings.NewSetting("tickets.sla", DefaultSLA)open-ticket reads it once, in Execute: u.Settings.ForClient(ctx, db, cx.Client()) then
clientsettings.Get(current.Settings(), SLA).
A policy change applies to the tickets opened afterwards; a ticket keeps the due time it was given. See Client settings.
Roles are written once
Section titled “Roles are written once”A role is a name and a set of permissions. The platform sync needs them (to create the roles) and the
sign-in needs them (to turn a user’s roles into permissions). The example holds each role once and feeds
both: the definitions send Definition.Role.of(name, permissions...) (Go: flowcatalyst.NewRole), and the
sign-in maps the same table with PermissionMapper.byRole(...) (Go: auth.ByRole(...)). The roles are
requester (read, open, comment), agent (adds work) and lead (adds managing the SLA); permissions
have the platform’s four-segment form, tickets-trial:support:ticket:work.
Definitions in code
Section titled “Definitions in code”Event types, a connection, a subscription to the assignment event, the roles and the SLA job are all
declared next to the code, then pushed with sync:
Definitions.in(app) .eventType(TicketEvents.ASSIGNED.type(), "Ticket assigned", "A ticket was given to an agent.") // ... the other event types .connection("main", "Tickets") .subscription( Definition.Subscription.of( "notify-assignee", "Notify the assignee", "/fc/dispatch", TicketEvents.ASSIGNED.type()) .viaConnection("main") .withDescription("Tells the agent a ticket was given to them.")) // Every minute, seconds first (six fields). The platform reports each firing's completion. .scheduledJob(Definition.ScheduledJob.of("sla-sweep", "SLA sweep", "0 * * * * *").tracking(true));defs := d.Definitions(ModuleID). EventTypeOf(Assigned, "Ticket assigned", "A ticket was given to an agent."). // ... the other event types Connection("main", "Tickets"). Subscription(flowcatalyst.NewSubscription("notify-assignee", "Notify the assignee", "/fc/dispatch", Assigned.String()). ViaConnection("main"). WithDescription("Tells the agent a ticket was given to them.")). ScheduledJob(flowcatalyst.NewScheduledJob("sla-sweep", "SLA sweep", "0 * * * * *").Tracking(true))The subscription’s target is a path (/fc/dispatch) resolved against
flowcatalyst.subscription-target-base-url, the service’s own address as the platform sees it. See
the module page for what the platform needs before the first sync.
A per-client credential never leaves its client
Section titled “A per-client credential never leaves its client”The notification handler resolves the key for the client of the delivery (the request context’s client), never from the event’s data, and answers the platform by what happened:
| Outcome | Answer |
|---|---|
| Sent, or assigned to yourself | ack |
| The client has no key; the service refused with a 4xx other than 429 | reject (terminal, visible on the dispatch job) |
| The service is unavailable (429, 5xx, no answer) | throw or return an error: a transient failure the platform retries |
SecretResult key = secrets.resolve(ctx.client(), KEY); // KEY = SecretRef.parse("notify-key")if (!(key instanceof SecretResult.Found found)) { return DispatchResult.reject("this client has no notification key");}ClientResponse response = clients.get(CLIENT, ctx) .post("/notifications") .header("Authorization", "Bearer " + found.secret().reveal()) .idempotencyKey(delivery.jobId()) .json(body) .send();if (response.isSuccess()) { return DispatchResult.ack();}if (response.status() >= 400 && response.status() < 500 && response.status() != 429) { return DispatchResult.reject("the notification service refused the request (" + response.status() + ")");}throw new IllegalStateException("the notification service answered " + response.status());found, err := n.Secrets.Resolve(ctx, cx.Client(), notifyKey)// ...key, ok := found.(secrets.Found)if !ok { return flowcatalyst.Reject{Reason: "this client has no notification key"}, nil}notifier, err := n.Clients.For(NotifierClient, cx)response, err := notifier.Post("/notifications"). Header("Authorization", "Bearer "+key.Secret.Reveal()). IdempotencyKey(d.Meta.JobID). JSON(notification{To: data.AssigneeID, TicketID: data.TicketID, Subject: data.Subject, AssignedBy: data.AssignedBy}). Send(ctx)The request carries the job id as its idempotency key, because a delivery can arrive twice and
once covers database work only, not an HTTP call
(at-least-once). The client’s key comes from
a secret store (the example uses the environment: TICKETS_NOTIFY_<CLIENT>__NOTIFY_KEY); the notification
service’s address is configuration.
A job that works across clients
Section titled “A job that works across clients”The scheduled-job receiver runs as the application’s service principal in the _platform client. The SLA
sweep needs the tickets of every client, so it does the one deliberate thing the tenancy rules
otherwise forbid: a single query that is not scoped to a client, which returns client codes only. Then it
works one client at a time, with that client’s own context, so every other query is scoped and the
use case authorizes the service principal as it does anywhere:
List<ClientId> clients = TicketQueries.overdueClients(database, clock.instant());PerClient.each(ctx, clients, this::sweepClient); // sweepClient(Context forClient) flags that client's ticketsclients, err := OverdueClients(ctx, s.DB, s.Clock.Now())for _, r := range fw.EachClient(ctx, s.Log, cx, clients, s.sweepClient) { // r.Failed() when that client's sweep failed (EachClient logged why); r.Value otherwise}The events it writes carry that client, the service principal as the actor and the job instance as the
cause. The framework holds the scheduled-job:sla-sweep lock around the whole run, so two replicas never
sweep at once (Receivers). The sweep is idempotent: a
ticket resolved or already flagged since the query is skipped (NOT_OVERDUE, TICKET_NOT_FOUND), and the
job reports flagged, skipped and any failures as its result.
A loop on one replica at a time
Section titled “A loop on one replica at a time”A background loop refreshes two gauges (active and overdue tickets) every 30 seconds. It is gated by a service lock so that one replica at a time does the work; every replica still exports the value its last run found:
app.get(Background.class) .loop("ticket-gauges", LoopOptions.every(gaugeInterval).gatedBy(LockGate.service(app.get(Locks.class), "ticket-gauges", Duration.ofMinutes(1))), tick -> { long[] totals = TicketQueries.totals(db); active.set(totals[0]); overdue.set(totals[1]); });gate, err := locks.ServiceGate(all, "ticket-gauges", time.Minute)b.Loop("ticket-gauges", background.Options{Interval: interval, Gate: gate}, func(ctx context.Context, _ background.Tick) error { open, late, err := Totals(ctx, db) // ... store into the gauges return nil})Rate limiting one operation
Section titled “Rate limiting one operation”Comments are limited per signed-in person: 30 per minute with a burst of 10. The operation lists
429 RATE_LIMITED among its documented errors by hand, because the middleware does not contribute it to the
OpenAPI document (Rate limiting).
Putting it together
Section titled “Putting it together”The write path without a server is the same four modules as the orders example plus the tickets module. The web build adds the HTTP server, sessions, the admin area, the platform module with the definitions, the lock store the scheduled-job receiver needs, the secret store and named HTTP client, the receivers, the API and the SPA, each as a line in code:
return TicketsCore.builder() .module(new JettyHttpModule()) .module(new AuthDatabaseModule()) .module(customise.apply(AuthModule.builder()) .application(APPLICATION) .postLogoutRedirect("/signed-out") .loginFailure(LoginFailureHandler.redirectTo("/sign-in-failed")) .permissions(PermissionMapper.scopes().and(PermissionMapper.byRole(Roles.byPlatformName()))) .build()) .module(AdminModule.of(APPLICATION)) .module(AdminConfigModule.of(APPLICATION)) .module(new TicketsAdminModule()) .module(new FlowCatalystModule()) .module(new TicketsDefinitionsModule()) // The scheduled-job receiver takes an overlap lock; the database store is shared by replicas. .module(LocksModule.builder().store("main", DatabaseLockStores.database()).build()) .module(new LocksDatabaseModule()) .module(SecretsModule.builder().store("env", SecretStores.env("TICKETS_NOTIFY_")).build()) .module(HttpClientModule.builder().client(NotifyAssignee.CLIENT, HttpClientOptions.defaults()).build()) .module(new TicketsReceiversModule(tuning.gaugeInterval())) .module(new TicketsApiModule(tuning.commentLimit())) .module(new TicketsSpaModule());java -jar ... openapi --out web/openapi.json writes the OpenAPI document without a database, and a test
fails when the committed one is stale.
Every module has a declare step before configuration is read, in the same order as the Java module list, and one build function that connects and wires:
d := ticketsweb.Declare(app) // every module's Declareapp.Launch(ctx, args, ticketsweb.BuildWeb(d, ticketsweb.Deps{}))// BuildWeb: database + migrations, runner, use cases, locks, secrets, HTTP clients,// flowcatalyst.Build, RegisterReceivers (before Routes seals the registry), the gauge loop,// auth, routes, SPA, serverThe command line is tickets-trial (serve), tickets-trial sync [--dry-run], tickets-trial openapi --out web/openapi.json and tickets-trial e2e for the browser launcher. The Go service’s OpenAPI document
equals the Java service’s byte for byte.
Testing it
Section titled “Testing it”- Use cases: a real application on PostgreSQL, a clock the test moves, rows read back from the outbox, and a repository wrapper that pauses the first load for the conflict tests.
- The API with real sessions: a test helper signs in as a person of a client, so the client of every request is the one in that sign-in and the tests with two clients are plain. Neither client sees the other’s tickets.
- The platform’s part: the platform stand-in for the service account, the sync and the completion calls; signed deliveries built from the outbox row the use case wrote, so a change to an event’s fields breaks the handler’s test (Receivers).
- The browser: a Playwright suite against the real service with a strict content-security-policy monitor and axe at WCAG 2.2 AA; the launcher plays the platform (sign-in provider, fake platform, notification service, a movable clock).
Running it
Section titled “Running it”The service reads config/application.yaml: a database on localhost:5432 named app (override
DATABASE_INSTANCES_MAIN_URL; never point a test at a database you care about, the tests and the launcher
start their own). The platform connection is off by default (flowcatalyst.enabled: false); switch it
on with FLOWCATALYST_ENABLED=true, FLOWCATALYST_BASE_URL, FLOWCATALYST_CLIENT_ID and
FLOWCATALYST_CLIENT_SECRET, and set FLOWCATALYST_RECEIVERS_SIGNING_SECRET to the secret of the
subscription’s connection.
What it did not prove
Section titled “What it did not prove”Everything platform-side was run against the framework’s stand-in; nothing here is a statement about a particular platform deployment. It was not run with a second replica (the lock-gated loop and the overlap lock were tested against one process, with the lock held by the test standing in for the other replica) or in a browser other than Chromium.
What the trial changed
Section titled “What the trial changed”Building this service found friction in the framework, and several findings became framework features that
the pages above describe: the record-level authorizeLoaded phase, Context.forClient with the per-client
sweep helper, client settings (the SLA used to be a table, a repository, an aggregate, an event and a page
for four integers), joining a use case to a handler’s transaction, and a public receiver-testing helper.
Others stayed as documented patterns, for example: in Java, event types are linked to the sync by hand
(Definitions.eventType takes strings, and nothing fails if a use case writes an event type the
definitions never declared, which the platform then drops; Go’s EventTypeOf takes the typed event type),
and a length rule is written in the operation’s validator, the use case, the table’s
CHECK and the generated client schema.