Reference

UsePersistedOperations

Package Trax.Api.GraphQL.PersistedOperationsNamespace Trax.Api.GraphQL.PersistedOperations.ExtensionsSource TraxGraphQLBuilderPersistedOperationsExtensions.cs

Extension on TraxGraphQLBuilder, declared on the static class TraxGraphQLBuilderPersistedOperationsExtensions, that wires the persisted-operation pipeline: storage, enforcement, the optional lookup cache, cross-node invalidation, the allowlist, the introspection bypass, shadow-mode logging and the management fields.

Signature

public static TraxGraphQLBuilder UsePersistedOperations(
    this TraxGraphQLBuilder builder,
    Action<PersistedOperationsBuilder> configure
);

Parameters

ParameterTypeDescription
builderTraxGraphQLBuilderThe GraphQL builder passed to AddTraxGraphQL
configureAction<PersistedOperationsBuilder>Sets the options; see PersistedOperationsBuilder

Returns

The same TraxGraphQLBuilder.

Behavior

Exactly one of SingleNode() and UseRabbitMqInvalidation(...) is required; see One node or many. The options are checked when UsePersistedOperations runs (see Validation).

Generated documents

With persisted operations on, the host registers a document for every exposed machine operation (Persisted documents), so a host that requires persisted operations serves its machines with no upload. It generates none for a train: a frontend reaches a train through a document it wrote, which the host registers from ClientDocuments(path) when it starts (Fetch only what a component needs). A select-everything document of a train grows with the number of paths through its answer, so an EF model whose entities reference each other either passed the parser's limit or was refused for cost on every call; the decision is ADR 0054. The trax_train_ prefix an earlier version registered train documents under stays reserved: such an id answers SERVER_OUTDATED while a node of that version may still serve it, then CLIENT_OUTDATED, so a page built against it reloads.

A train's output is resolved from the object the train returned, not projected from a query, so every field a document selects is read on every call. A navigation the train did not load comes back null or empty, and with EF's lazy-loading proxies on, each one runs a query. Select what the component needs, and load what the answer exposes.

A host where a train carries [TraxRunProgress] also registers the two documents of runProgress, under trax_progress_query_<shapeHash><textHash> and trax_progress_subscription_<shapeHash><textHash>, hashed the same way. One pair serves every such train.

A host that serves views from features registers one document per view of the views root, under trax_view_<view>_<shapeHash><textHash>, hashed the same way.

A host that serves the operations console (UseTraxApiDashboard) registers the console's own documents too, under trax_console_<name>_<hash>, hashed as a client document is, and tells the console their ids. Each reaches only operations or one of the operator's subscriptions; one the host cannot serve is left out and logged rather than refusing the start.

A version of a train's or the progress documents is kept for as long as any node registers it, and collected once no node has for the grace period, the way a machine's is (collection): two hosts on one database that expose one train field with two shapes keep both.

Registered services

ServiceLifetimePurpose
PersistedOperationsOptionsSingleton (Replace)Resolved configuration. Replaces the options AddPersistedOperationStore registers, in either order, so a process has one set.
IPersistedOperationCache -> NoOp or InMemorySingletonCache layer. No-op unless WithInMemoryCache() was called.
IPersistedOperationBroadcaster -> NoOp or RabbitMqSingletonMulti-node invalidation. RabbitMQ with UseRabbitMqInvalidation(), no-op with SingleNode().
PersistedOperationReceiverServiceHosted (when broadcaster is RabbitMQ)Subscribes to the fanout exchange and empties the document, prepared-operation and Trax caches on broadcast, on losing the broker connection, and on recovering it. When the broker closes its channel alone it empties them, subscribes again on a new channel, and empties them once more.
IPersistedOperationStore -> DbPersistedOperationStorageSingletonProgrammatic CRUD. Reads and writes through the Effect data provider's IDataContextProviderFactory, so the host needs UsePostgres (or another data provider); the tables are sets on the Effect DataContext.
IPersistedOperationsServiceSingleton (TryAdd)The management surface the GraphQL fields and the dashboard call.
IPersistedOperationsManagementGateScoped (Replace)The declared management gate, for the dashboard's pages. Scoped so its policies are evaluated with the caller's services, as the fields' are.
IOperationDocumentStorage -> DbPersistedOperationStorageSingletonHotChocolate hot-path lookup.
IPersistedOperationValidator -> HotChocolateSchemaValidatorSingleton (Replace)Runs HotChocolate validation against the live schema before every upsert. Overrides the no-op default from AddPersistedOperationStore.
IPersistedOperationsCapabilitySingletonMarker meaning this process runs UsePersistedOperations. The dashboard gates its pages on IPersistedOperationsService instead, so they also appear on a host that registers only AddPersistedOperationStore.
AllowlistMatcherSingletonUsed by the enforcement middleware.
PersistedOperationPolicySingletonThe enforcement decision, asked once per operation by the request middleware UsePersistedOperations adds after HotChocolate's document parser.
MachineDocumentRegistrationHosted (lifecycle)Generates every exposed machine's persisted documents from the built schema and registers them in the store before the host serves anything, writing nothing for a document already stored as generated. A failure stops the host.
TimeProviderSingleton (TryAdd)Default TimeProvider.System; override for tests. The caches' maximum age is measured on it.
IDocumentCache, IPreparedOperationCacheSingleton (schema services)Replacements for HotChocolate's caches, sized from the host's ModifyOptions (OperationDocumentCacheSize, PreparedOperationCacheSize). Each entry carries the generation it was written in and the time its document was read; it is served only while no change has been applied since and it is younger than WithCacheMaxAge. The executor refuses to build if anything else replaces them.

It adds nothing to the operations namespace. A host that wants operations exposes it itself, with ExposeOperationQueries() or ExposeOperationMutations(), and answers for it there.

The management fields

The management mutations and queries sit at the root, persistedOperations { ... } on RootQuery and RootMutation, behind a gate of their own. They are served only once the host declares who may use them:

services.AddTraxGraphQL(graphql => graphql
    .UsePersistedOperations(po => po
        .RequirePersisted(true)
        .SingleNode()
        .GateManagement(roles: "Deployer")
    )
);

GateManagement(policy, roles) puts @authorize on both persistedOperations fields, with the same rules as GateOperations: a policy or roles is required, a comma-separated role list is any of, and repeated calls are all of. GateManagementToAuthenticatedUsers() admits any signed-in caller. The gate is separate from the operations gate, so a deploy pipeline that uploads documents holds the management role and none of the operator's, and an operator at the dashboard who manages documents holds both.

Without a management gate the fields are not in the schema and the Trax dashboard shows no management pages. Storage, enforcement, the cache and cross-node invalidation are wired either way, and documents are managed out of band: a deploy step or a migration calling IPersistedOperationsService. With a gate, the dashboard's pages check it for the operator through IPersistedOperationsManagementGate, which operations.config.canManagePersistedOperations answers for the operations console.

Validation

Configuration errors throw InvalidOperationException when UsePersistedOperations runs, during service registration. Each message names the misconfigured method and suggests a fix:

MisconfigBehavior
RequirePersisted(false) and LogNonPersistedRequests(false)Throws: configuration does nothing.
Neither SingleNode() nor UseRabbitMqInvalidation(...)Throws: names both, since a change reaches another node at once only by broadcast.
Both SingleNode() and UseRabbitMqInvalidation(...)Throws: the two contradict each other.
UseRabbitMqInvalidation(...) with no SigningKey and no AllowUnsignedMessages(), a key shorter than 32 bytes, or plain amqp:// to a host that is not loopback without AllowInsecureTransportThrows, naming the option to set.
WithInMemoryCache called twiceThrows.
WithInMemoryCache TTL longer than WithCacheMaxAgeThrows: the TTL would not take effect.
WithCacheMaxAge not positiveThrows ArgumentOutOfRangeException when called.
AllowOperations contains an empty entryThrows.
GateManagement() with neither a policy nor roles, or with a role list of only separatorsThrows when called.
A policy GateManagement names is not registeredThe host fails at startup, naming the policy and the field.
AddPersistedOperationStore in the same host declares a different GateManagementThe host fails at startup, naming both calls.
RequirePersisted(true) with AllowOperations or AllowOperationsMatching, outside DevelopmentThe host fails at startup, naming the environment. Under enforcement the allowlist starts only in Development.

Examples

One node:

services.AddTraxGraphQL(graphql => graphql
    .UsePersistedOperations(opts => opts
        .RequirePersisted(true)
        .SingleNode()
    )
);

More than one node, with the optional Trax lookup cache:

services.AddTraxGraphQL(graphql => graphql
    .UsePersistedOperations(opts => opts
        .RequirePersisted(true)
        .WithInMemoryCache()
        .UseRabbitMqInvalidation(
            rabbitMqConnectionString,
            o => o.SigningKey = Convert.FromBase64String(configuration["Trax:InvalidationSigningKey"]!)
        )
        .GateManagement(policy: "TraxAdmin")
    )
);

See also