Reference

PersistedOperationsBuilder

Package Trax.Api.GraphQL.PersistedOperationsNamespace Trax.Api.GraphQL.PersistedOperations.ConfigurationSource PersistedOperationsBuilder.cs, PersistedOperationsBuilder.Enforcement.cs, PersistedOperationsBuilder.Allowlist.cs, PersistedOperationsBuilder.Broadcasting.cs, PersistedOperationsBuilder.Cache.cs, PersistedOperationsBuilder.Management.cs, PersistedOperationsBuilder.MachineDocuments.cs, PersistedOperationsBuilder.Database.cs, PersistedOperationsBuilder.Build.cs

The options passed to UsePersistedOperations. Every method returns the builder.

Signature

public sealed partial class PersistedOperationsBuilder
{
    public PersistedOperationsBuilder RequirePersisted(bool require = true);
    public PersistedOperationsBuilder LogNonPersistedRequests(bool log = true);
    public PersistedOperationsBuilder AllowOperations(params string[] operationNames);
    public PersistedOperationsBuilder AllowOperationsMatching(Func<string, bool> predicate);
    public PersistedOperationsBuilder DisableIntrospection();
    public PersistedOperationsBuilder WithInMemoryCache(Action<CacheOptions>? configure = null);
    public PersistedOperationsBuilder WithCacheMaxAge(TimeSpan maxAge);
    public PersistedOperationsBuilder UseRabbitMqInvalidation(
        string connectionString,
        Action<RabbitMqInvalidationOptions> configure
    );
    public PersistedOperationsBuilder UseRabbitMqInvalidation(string connectionString);
    public PersistedOperationsBuilder SingleNode();
    public PersistedOperationsBuilder GateManagement(string? policy = null, string? roles = null);
    public PersistedOperationsBuilder GateManagementToAuthenticatedUsers();
    public PersistedOperationsBuilder KeepOlderMachineDocumentsFor(TimeSpan grace);
    public PersistedOperationsBuilder ClientDocuments(string path);
    public PersistedOperationsBuilder UseDatabase(string connectionString); // obsolete
}
 
public sealed class CacheOptions
{
    public TimeSpan? Ttl { get; }
    public CacheOptions WithTtl(TimeSpan ttl);
}
 
public sealed class RabbitMqInvalidationOptions
{
    public const int MinimumSigningKeyLength = 32;
    public byte[]? SigningKey { get; set; }
    public TimeSpan MaxClockSkew { get; set; }
    public bool AllowInsecureTransport { get; set; }
    public bool UnsignedMessagesAllowed { get; }
    public RabbitMqInvalidationOptions AllowUnsignedMessages();
}

Members

MethodDefaultPurpose
RequirePersisted(bool require = true)trueRefuse inline documents. false is shadow mode, which needs LogNonPersistedRequests(true).
LogNonPersistedRequests(bool log = true)falseLog every inline-document request at Information.
AllowOperations(params string[] names)emptyOperation names that bypass enforcement. Case-sensitive. Matched against the caller-supplied operationName, not the document: a convenience for developer tools, not a security control. With RequirePersisted(true) the host starts only in Development.
AllowOperationsMatching(Func<string, bool>)emptyPredicate form, such as id => id.StartsWith("dev_"). The predicate sees the caller-supplied operationName (or documentId), never the document. With RequirePersisted(true) the host starts only in Development.
DisableIntrospection()introspection allowedInline introspection requests are refused like any other inline document.
WithInMemoryCache(Action<CacheOptions>?)no cacheCache the store's lookups in IMemoryCache, under the document and prepared-operation caches, which are always on. Without it the database is read when a node first serves an id, after a change empties those caches, and when an entry reaches its maximum age.
WithCacheMaxAge(TimeSpan maxAge)5 minutesThe longest any cache on a node keeps a persisted operation, counted from when its document was read from the database. The backstop for a change that did not reach the node: it serves what it cached for at most this long, then reads the store again. Must be positive.
UseRabbitMqInvalidation(string connectionString, Action<RabbitMqInvalidationOptions> configure)noneBroadcast every change over a RabbitMQ fanout so every node empties its caches, each message signed with the key configure sets. Required when more than one node serves the endpoint. Works with or without WithInMemoryCache(). A publish the broker does not confirm is reported as CHANGE_NOT_BROADCAST. See Signing and transport.
UseRabbitMqInvalidation(string connectionString)noneThe same broker with no key set, which refuses the start until one is set through the overload above.
SingleNode()noneDeclare that one process serves the endpoint and writes the store, so no broadcast is needed.
GateManagement(string? policy = null, string? roles = null)not servedServe the management fields, persistedOperations { ... } at the root, behind @authorize with this policy or these roles. A comma-separated roles list is any of; repeated calls are all of. A policy or roles is required. Without this call or the next, the fields are not in the schema.
GateManagementToAuthenticatedUsers()not servedServe the management fields to any authenticated caller. On a host with public sign-up that is anyone, so prefer GateManagement.
KeepOlderMachineDocumentsFor(TimeSpan grace)7 daysHow long a version of the generated documents stays active once no node registers it, older or newer. Each node registers its own documents when it starts and again every hour (at most a quarter of this) while it runs, so a node still running another version keeps serving its documents; a version no node has registered for this long is deactivated. Must be positive. The same period applies to client documents.
ClientDocuments(string path)noneRegister the documents a frontend wrote, from the trax.documents.json that trax client --documents writes, when the host starts. path resolves against the content root; repeated calls add files. Each document is one named query or mutation of exposed trains under dispatch or discover, with no directive, and must pass the host's own validation. A missing or malformed file, a name used twice, or a document breaking either rule refuses the start, naming it. Each is stored under trax_client_<name>_<hash of its text>; a version a frontend no longer holds keeps running while it validates, until no node has registered it for the grace period above.

UseDatabase(string) is obsolete, hidden from IntelliSense, and does nothing beyond throwing ArgumentException for a blank string: storage reads and writes trax.persisted_operation through the Trax data context that AddEffects(e => e.UsePostgres(...)) registers.

CacheOptions

MethodDefaultPurpose
WithTtl(TimeSpan ttl)the maximum ageEntry lifetime for the Trax lookup cache, read back from Ttl. Must be positive (ArgumentOutOfRangeException) and may not exceed WithCacheMaxAge (InvalidOperationException when the options are built).

Signing and transport

A message on the invalidation exchange empties a node's caches, so the broadcast is signed. Every node and every uploader (AddPersistedOperationStore) sets the same key, and each message carries a trax-signature header: HMAC-SHA256 over the body, the exchange, a timestamp and a message id. The header has the format UseRabbitMq uses for train events, but the MAC is tagged for invalidations, so a train event never verifies as an invalidation even when both use the same key. A node drops a message delivered from any exchange but the one it subscribed to, then checks the signature before it reads the body and drops a message that is unsigned, signed with another key, or further than MaxClockSkew from its clock, logging a warning at most once a minute.

RabbitMqInvalidationOptionsDefaultPurpose
SigningKeynullThe shared key, at least MinimumSigningKeyLength (32) bytes. Required unless AllowUnsignedMessages() is called.
MaxClockSkew5 minutesHow far a message's timestamp may be from the receiving node's clock, either way. Must be positive and at most one hour.
AllowUnsignedMessages()offPublish unsigned and accept messages without a signature when no key is set. The receiver logs a warning when it starts. Only for a broker no one else can publish to. Read back from UnsignedMessagesAllowed.
AllowInsecureTransportfalseAccept plain amqp:// to a broker that is not loopback. Without it such a URI refuses the start, since the broker credentials and every message would cross the network in cleartext. The receiver logs a warning when it is what lets the connection through.
services.AddTraxGraphQL(graphql => graphql
    .UsePersistedOperations(opts => opts
        .UseRabbitMqInvalidation(
            "amqps://trax:secret@rabbitmq.internal:5671/",
            o => o.SigningKey = Convert.FromBase64String(configuration["Trax:InvalidationSigningKey"]!)
        )
    )
);

Behavior

  • Exactly one of SingleNode() and UseRabbitMqInvalidation(...) is required. See One node or many.
  • GateManagement throws InvalidOperationException with neither a policy nor roles, or with a role list that holds only separators. A policy it names that is not registered with AddAuthorization fails startup.
  • ClientDocuments throws ArgumentException for a blank path.
  • With UseRabbitMqInvalidation, building the options throws InvalidOperationException without a SigningKey (unless AllowUnsignedMessages()), with one shorter than 32 bytes, or for plain amqp:// to a host that is not loopback without AllowInsecureTransport.
  • UseRabbitMqInvalidation throws ArgumentException for a blank connection string; WithCacheMaxAge and KeepOlderMachineDocumentsFor throw ArgumentOutOfRangeException for a value that is not positive; a second WithInMemoryCache throws InvalidOperationException.
  • The remaining checks run when UsePersistedOperations builds the options and throw InvalidOperationException; the UsePersistedOperations validation table lists them.
  • With RequirePersisted(true), a host that declares AllowOperations or AllowOperationsMatching fails at startup outside Development.
  • What the allowlist does and does not protect: Allowlist and dev carve-outs.

Example

services.AddTraxGraphQL(graphql => graphql
    .UsePersistedOperations(opts => opts
        .RequirePersisted(true)
        .LogNonPersistedRequests(true)
        .WithCacheMaxAge(TimeSpan.FromMinutes(5))
        .WithInMemoryCache(c => c.WithTtl(TimeSpan.FromMinutes(2)))
        .UseRabbitMqInvalidation(
            rabbitMqConnectionString,
            o => o.SigningKey = Convert.FromBase64String(configuration["Trax:InvalidationSigningKey"]!)
        )
        .GateManagement(roles: "Deployer")
    )
);

See also