Code generation
Topics travel through the same pipeline as the REST API. make gen reads them from the OpenAPI document and writes
two things beside the Orval output: typed topic builders (realtime.ts) and, for each GET marked
@invalidated_by, the topics its React Query query watches. Orval owns the REST operations; the socket stays a
separate protocol adapter (@djangocfg/realtime). No topic string is written by hand in the frontend.
x-realtime in the schema
The drf-spectacular hook django_cfg.modules.django_realtime.openapi.postprocess_realtime is in django-cfg’s default POSTPROCESSING_HOOKS. It writes the registry into the document:
"x-realtime": {"version": 1, "path": "/ws", "topics": [
{"name": "orders:{order_id:int}", "params": [{"name": "order_id", "type": "int"}],
"anonymous": false, "history": 100, "event": {"$ref": "#/components/schemas/OrderEvent"},
"tags": ["orders"], "description": "Order status changes."}
]}- Event models (and their nested models) become ordinary
components.schemas, so they get zod schemas and types like any serializer. - A topic’s tag is its
group(by default the declaring app), so the slicer puts it in that group’s client. - A group slice without topics has no
x-realtimekey at all (nottopics: []), so its committedopenapi.json/openapi.yamldoes not change when another group gains a topic. Only the slices that carry topics have the key. - A schema name that already holds a different schema stops generation (
SchemaCollision): rename the event model. It is never overwritten.
realtime.ts
A target whose slice has topics gets realtime.ts at the root of its tree, beside endpoints/ and models/. A
target without topics gets none.
// AUTO-GENERATED by django_cfg realtime adapter (abridged: the RealtimeTopic type and segment() helper are omitted)
import { OrderEvent, type OrderEventOutput } from "./models/orderEvent.zod";
export const REALTIME_PATH = "/ws";
export const REALTIME_PROTOCOL = 1;
/** `orders:{order_id:int}` (signed-in users, history 100). Order status changes. */
export function ordersTopic(params: { orderId: number }): RealtimeTopic<OrderEventOutput> {
return {
name: `orders:${segment("orders:{order_id:int}", "orderId", "int", params.orderId)}`,
pattern: "orders:{order_id:int}",
anonymous: false,
schema: OrderEvent,
};
}
/** Every topic of this group, by pattern. */
export const realtimeTopics = { "orders:{order_id:int}": { "builder": "ordersTopic", ... } } as const;- One builder per pattern, named after its literal parts:
orders:{order_id:int}→ordersTopic({ orderId }),orders:{order_id:int}:items→ordersItemsTopic({ orderId }),demo.ping→demoPingTopic(). When two patterns map to one name, the one with parameters gets them in its name (ordersByOrderIdTopic). - Parameters are camelCase and typed:
{name:int}is anumber,{name}astring. A value that does not fit the segment syntax throws when the name is built. schemavalidatesmsg.data. A topic with the emptyHintevent is typedRealtimeTopic<RealtimeHintOutput>; a topic whose event has no model,RealtimeTopic<unknown>withschema: null.RealtimeTopic<E>is structural:realtime.tsnever imports@djangocfg/realtime, anduseTopicaccepts it as is.
Query invalidation
Mark the REST reads a topic makes stale, on a view, a viewset or an action:
from django_cfg.modules.django_realtime import invalidated_by
@invalidated_by("orders.all")
class OrderViewSet(viewsets.ReadOnlyModelViewSet):
@invalidated_by("orders:{order_id}")
def retrieve(self, request, *args, **kwargs): ...- Markers on the class and on an action add up.
@api_viewfunctions take it too. - The pattern syntax is checked at import. Whether a declared topic of that shape exists is checked at schema
generation: a marker naming no declared topic stops generation (
UnknownTopic). - A marker matches a declared topic by shape, so it may rename the parameters to match the URL:
invalidated_by("orders:{pk}")matchesorders:{order_id:int}and takespkfrom the path.
django-cfg’s schema class writes the markers as x-realtime-invalidates on each operation. For every GET that
carries it, the generator writes runtime/realtime-query.ts, an Orval query-options mutator, and points that
operation at it. The generated hook then tags its query:
// runtime/realtime-query.ts (generated, abridged)
const TOPICS: Record<string, (props: Record<string, unknown>) => (string | null)[]> = {
orders_list: () => ["orders.all"],
orders_retrieve: (props) => [filled(props, "orderId") ? `orders:${String(props["orderId"])}` : null, "orders.all"],
};
// adds { meta: { realtimeTopics: [...] } } to the query options, keeping the caller's meta- A
{param}comes from the path parameter of the same name, under Orval’s camelCase argument name (order_id→orderId). A parameter that is no path parameter of the GET stops generation, naming the operation: a list cannot know whichorder_idto watch. Mark it with a topic it can fill, or a broader one. - A topic with a parameter is watched only once the query has a value for it.
- Writes (POST, PUT, PATCH, DELETE) of a marked viewset are skipped: they have no query.
- Operations without a marker are byte-identical to what they would be without realtime.
- The options factory of a marked operation is a hook,
use<Op>QueryOptions, instead ofget<Op>QueryOptions.
BaseApp watches the tagged queries while they are mounted and invalidates them on each message and gap. The
generated REST client never imports @djangocfg/realtime. See zero-code refresh.
Any topic name works as a tag, with or without : or .: the tag is the query’s meta, not a part of its key.
Sender id in the auth runtime
@djangocfg/api exports setRealtimeCidProvider(provider). The provider is kept in one page-wide slot, and every
generated tree calls the same djangoFetch, so installing it once (BaseApp does) covers every target; their
writes then carry X-Realtime-Cid. See Frontend.