Blob: references/representation-and-api-craft.md
Representation and API craft
Choose a representation that makes the intended operation direct. Put meaningful distinctions where callers can use them: intervals for overlap, streams for incremental consumption, tagged outcomes for different next actions, and separate identities for things with different lifetimes.
Model identity separately from labels
SlugSurvival helps students plan a timetable containing courses, course sections, and custom events. To decide whether a new entry conflicts with the existing schedule, it originally intersected weekdays and compared time strings. Converting each meeting block into numeric start/end timestamps placed different days and repeated meetings into one form for overlap checking. This simplified the comparison without removing the need to examine the relevant intervals.
That representation still had an identity error. The existing schedule was grouped by course code or event name, and an already-seen name caused later entries to be skipped. A course code could support the rule against taking the same course twice in a quarter. A custom event name could not: two events called “Study group” might occupy different days, and both need to participate in conflict detection. The repair appended all intervals to the name's group and then removed duplicate start/end pairs. It retained the name for reporting a conflict without using it as proof that every meeting had already been processed.
The entity, its display label, and equality for one calculation need not coincide. Here, equal time pairs were redundant for overlap checking; equal labels were not. A different operation, such as editing or deleting one of the events, would need to distinguish the event instances even when their times also matched.
The interval representation also carried a boundary choice: the existing tests treated a meeting ending at 10:00 and another beginning at 10:00 as conflicting. Half-open intervals would permit that pair. Either convention can serve a scheduling product, but substituting the latter during a representation cleanup would change the accepted behavior.
Expose material resource behavior
The service b stores small text and link values, file metadata, and uploaded file bodies. A []byte contract is convenient for small values but would require a complete file body in memory. Its separate stream contract made incremental consumption available to upload and download handlers:
type FastBackend interface {
SaveTTL(c context.Context, identifier string, r io.ReadCloser, ttl time.Duration) (int64, error)
Retrieve(c context.Context, identifier string) (io.ReadCloser, error)
Close() error
}SaveTTL consumes a reader and reports the number of bytes written; Retrieve returns a reader the caller can stream to an HTTP response. In the file implementation, saving closes the supplied reader, while the download handler closes the reader returned by retrieval. The interface's own Close() releases backend resources. Those are distinct lifetimes, and a closable type makes them visible even though ownership still needs an agreement between caller and implementation.
The project removed the redundant Save operation because zero-TTL storage already expressed “do not expire,” while composing deletion as an additional capability. It retained a harder lifetime question in the file backend: how should expiration-triggered removal behave while another request is still downloading the file? A streaming interface makes buffering avoidable; it does not by itself settle how expiration and active readers interact. That issue matters when deciding whether two backends really provide substitutable behavior.
Adapt standard interfaces carefully
Specter's tunnel and distributed storage traffic travels over an overlay network, including QUIC streams. Its original custom stream structure carried a connection and a separate remote address. Replacing it with Go's net.Conn gave consumers the standard read, write, close, deadline, and address contract. A QUIC wrapper supplied address methods from the underlying QUIC connection, keeping the transport-specific translation in one place.
Its RPC migration similarly used Twirp-generated clients and handlers over HTTP, with a custom dialer opening an overlay stream to the peer selected for each call. The generated client used a placeholder host, so a request hook replaced it with the actual peer address. HTTP pools by destination; leaving the placeholder unchanged could reuse one peer's connection for a call intended for another, bypassing the dialer that knew the new destination.
A familiar method set is only part of compatibility. These adapters preserved address meaning and connection reuse behavior as well. The gain comes from letting ordinary consumers work correctly; if a transport cannot support a material part of that contract, hiding the difference behind the standard interface would make those consumers harder to reason about.
Encode genuine alternatives
vaskel saves chat drafts locally so they survive reloads. Sending a message creates a SendMessage command containing its identity, body, and attachments. If the response is lost, the browser may not know whether the server accepted it; retrying must preserve that exact command. The draft therefore distinguishes authoring with no command, submitting or retaining an attempt, and cleaning up after an accepted send.
The command's presence alone cannot select the next action: it is present both when a retry might be needed and when Send has succeeded but deleting the local draft is unfinished. The explicit cleanup phase prevents a local persistence failure after success from becoming a retryable Send. submit() owns the fresh-versus-retry decision because the draft controller owns those transitions. Passing a caller-derived isRetry Boolean would let the caller's interpretation disagree with the stored attempt.
Other state in the same workspace was independent. An activity view can have both earlier and later pages available; those are two navigation capabilities, not exclusive “next actions.” A call can involve participation, device capture, and transport readiness in overlapping combinations. In bland's document UI, the selected page can be ready while its ancestor list is still loading. Separate fields preserve those combinations. A phase model is helpful where one outcome rules out another, while using one global phase for unrelated work can create blocking dependencies the product never needed.
Return the decision with its associated data
git-on-cloudflare stores Git objects in pack files in R2 object storage. A per-repository Durable Object—the stateful component owning repository metadata—keeps the catalog of active packs. A background Worker compacts several packs into a replacement and uploads it before asking the catalog owner to accept it. The commit result distinguishes an accepted replacement from work that must be retried:
export type CommitCompactionResult =
| {
status: "committed";
packCatalogVersion: number;
shouldRequeue: boolean;
supersededPackKeys: string[];
targetPackKey: string;
}
| {
status: "retry";
reason: "receive-active" | "lease-mismatch" | "packset-changed" | "source-changed";
message: string;
};Uploading valid pack bytes does not make them the repository's active storage. While the Worker was building them, its compaction lease, the catalog version, or the selected source packs could have changed; a Git push could also be active. The owner checks those conditions against its current state. On acceptance it adds the replacement as active, marks the source packs superseded, and returns their keys with status: "committed".
Only that outcome authorizes deletion of the old packs. Deleting them from the Worker's original plan would remove data that the active catalog may still require if commit was rejected. A retry result instead leads the Worker to remove its unaccepted staged output and retry the queue message. The committed branch schedules deletion using the returned superseded keys. The owning transition supplies the decision; the union keeps the associated data with the outcome that makes it usable, so the caller need not reconstruct that decision from stale inputs or exception text.
Share contracts at the right boundary
Composer is a live video mixer with a browser studio, a control service, and a Rust media engine. The studio and other API clients manipulate productions through the authenticated public control API. The engine receives a private protocol describing the scene to execute and the resolved provider configuration needed to open media streams.
The public API's oRPC contract and Zod validators define client operations, inputs, outputs, and expected errors, and produce an OpenAPI description. Rust structs own the engine's wire format and generate its TypeScript counterpart. Between them, the control adapter resolves a public connectionId into provider settings such as a service endpoint and credentials. A client can select a saved connection without needing the secrets that the native engine uses to connect.
Consequently, credential writes, readable connection metadata, and native engine configuration have different shapes even though they describe parts of the same production. Sharing a secret-bearing engine type with every consumer would erase that access boundary. Generation keeps each wire contract synchronized with its owner; it does not justify merging contracts whose consumers have different needs.
Structural schemas also need model-level relationships. A scene layer refers to a source ID: an individually valid string is still unusable if that source does not exist, and duplicate source IDs make the reference ambiguous. Output transport choices can also be mutually exclusive in the native engine. These checks belong with the model that understands sources, scenes, and outputs, alongside the generated serialization shapes.
An existing named type or helper is valuable for the same reason: consumers share the meaning owned by that boundary. Recreating its shape in several callers allows drift; deriving it through deeply nested implementation return types can make a harmless internal refactor affect unrelated consumers. The useful unit of reuse is the domain contract, with files organized around the responsibility and consumers it serves.
For the underlying state decisions, read authority and state. For choosing what to delegate to a library, read abstraction and dependencies.