TraxQuery and TraxMutation
Package Trax.EffectNamespace Trax.Effect.AttributesSource TraxQueryAttribute.cs, TraxMutationAttribute.cs
[TraxQuery] exposes a train as a query field under query { discover { ... } }, and
[TraxMutation] as a mutation field under mutation { dispatch { ... } }. The fields are
generated by TrainTypeModule; a train with neither attribute is not in the schema. The two are
mutually exclusive. They ship in Trax.Effect, so a train class carries them without depending on
Trax.Api.GraphQL.
Signatures
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class TraxQueryAttribute : Attribute
{
public string? Name { get; init; }
public string? Description { get; init; }
public string? DeprecationReason { get; init; }
public string? Namespace { get; init; }
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class TraxMutationAttribute : Attribute
{
public TraxMutationAttribute(params GraphQLOperation[] operations);
public string? Name { get; init; }
public string? Description { get; init; }
public string? DeprecationReason { get; init; }
public string? Namespace { get; init; }
public GraphQLOperation Operations { get; }
}
[Flags]
public enum GraphQLOperation
{
Run = 1,
Queue = 2,
}Properties
TraxQuery
| Property | Type | Default | Description |
|---|---|---|---|
Name | string? | null | Overrides the auto-derived GraphQL field name. When null, the name is derived by stripping the I prefix and Train suffix from the service type name. |
Description | string? | null | Human-readable description that appears in the GraphQL schema documentation. |
DeprecationReason | string? | null | Marks the generated field as deprecated in the schema. |
Namespace | string? | null | Groups this field under a sub-namespace. When set, the field appears under discover { namespace { field } } instead of directly under discover. |
TraxMutation
| Property | Type | Default | Description |
|---|---|---|---|
Name | string? | null | Overrides the auto-derived GraphQL field name. When null, the name is derived by stripping the I prefix and Train suffix from the service type name. |
Description | string? | null | Human-readable description that appears in the GraphQL schema documentation. |
DeprecationReason | string? | null | Marks the generated fields as deprecated in the schema. |
Namespace | string? | null | Groups this field under a sub-namespace. When set, the field appears under dispatch { namespace { field } } instead of directly under dispatch. |
Operations | GraphQLOperation | Run | Queue | Read-only. Flags value computed from constructor params. When both Run and Queue are set, a mode parameter is exposed; Run alone is synchronous-only; Queue alone is async-only. |
GraphQLOperation
| Value | The generated mutation |
|---|---|
Run | Always runs synchronously. No mode or priority argument |
Queue | Always queues. A priority argument, no mode |
Run | Queue | Takes mode: ExecutionMode (RUN or QUEUE, default RUN) and priority |
Behavior
A query train always runs synchronously through RunAsync; it cannot be queued.
When no operations are passed to the TraxMutationAttribute constructor, both Run and Queue are enabled. The generated mutation accepts an optional mode: ExecutionMode parameter (default RUN) and an optional priority: Int. Priority orders the whole work queue, other callers' work included, so a priority other than 0 is accepted only from a caller who satisfies the operations gate; anyone else is refused with TRAX_AUTHORIZATION and nothing is queued. To restrict a mutation to only one execution mode, pass just GraphQLOperation.Run or GraphQLOperation.Queue to the constructor.
QUEUE writes the run to the scheduler's work queue and answers with its workQueueId; a JobDispatcher picks it up from there. Only a scheduler on a database provider (UsePostgres(), UseSqlite()) runs one. On UseInMemory() nothing can dispatch the entry, so a QUEUE request is refused with the error code TRAX_QUEUE_UNAVAILABLE and nothing is enqueued; RUN is unaffected, and the host still starts but logs a warning naming every train mutation that can queue. The project templates, which run on the in-memory provider, expose GraphQLOperation.Run alone, which drops the mode argument. A host on a database provider queues whether or not it runs the scheduler itself, since a scheduler on another host can dispatch the entry. See Trax.Api ADR 0038.
The mutation's externalId is the external id the dispatched run carries, so a client correlates the queued mutation with that run's subscription events by it (see Queued runs and Watch a queued run). A queued run has no manifest, so if it fails it is not retried and does not become a dead letter; retries belong to manifests (see Retries replay decisions).
The train must declare its authorization posture: [TraxAuthorize] to gate it or
[TraxAllowAnonymous] to open it. A train with neither fails at host startup (AddTraxGraphQL),
unless the endpoint is gated with RequireAuthorization(). See
Authorization: Required Exposure Posture.
Input type requirements
Every train annotated with [TraxQuery] or [TraxMutation] must have a dedicated input record. Unit is not allowed as an input type. Attempting to register a Unit-input train will throw InvalidOperationException at startup.
The mediator routes by input type (input.GetType()), so Unit inputs would collide across trains, and HotChocolate cannot build an InputObjectType with no fields. An empty record is valid: it gives the train a type of its own, and the generated field takes no input argument:
// Valid: empty record gives this train a unique input type
public record RefreshCacheInput;
public interface IRefreshCacheTrain : IServiceTrain<RefreshCacheInput, Unit>;
[TraxMutation(GraphQLOperation.Run)]
[TraxAuthorize(Roles = "Admin")]
public class RefreshCacheTrain : ServiceTrain<RefreshCacheInput, Unit>, IRefreshCacheTrain
{
protected override Task<Either<Exception, Unit>> Junctions() =>
Chain<RefreshCacheJunction>().Resolve();
}
public class RefreshCacheJunction : Junction<RefreshCacheInput, Unit>
{
public override Task<Unit> Run(RefreshCacheInput input) => Task.FromResult(Unit.Default);
}When using trax-cli to generate trains from OpenAPI or GraphQL schemas, operations with no input parameters automatically get an empty input record.
Optional fields
A property's nullability decides whether its GraphQL field is required. A property initializer is
not carried into the schema as a default value, so this field is still take: Int!, and a request
that leaves it out is refused with "take is a required field and cannot be null":
public record GetChatHistoryInput
{
public Guid ChatRoomId { get; init; }
public int Take { get; init; } = 50; // still required in GraphQL
}A nullable property is optional, and the junction applies the default:
public record GetChatHistoryInput
{
public Guid ChatRoomId { get; init; }
public int? Take { get; init; } // optional: take: Int
}
var take = Math.Clamp(input.Take ?? 50, 1, 100);Value types follow the same rule: bool is Boolean!, bool? is optional. A caller-supplied
value reaches the junction as the caller wrote it, unclamped.
The last property
Adding or removing the last property of an input record therefore changes the field's arity: the input argument appears or disappears. That is a breaking schema change for clients, and it does not look like one in the diff, because the record gained or lost a single property like any other.
Field names
When Name is null (the default), the field name is derived from the train's service interface:
- Strip the
Iprefix - Strip the
Trainsuffix - Use the result as the field name (camelCase, no prefix)
| Service Interface | Query Field | Mutation Field |
|---|---|---|
ILookupPlayerTrain | lookupPlayer | lookupPlayer |
IBanPlayerTrain | banPlayer | banPlayer |
When Name is set, it's used directly: [TraxMutation(Name = "BanUser")] produces banUser.
Two exposed trains cannot share a name. AddTraxGraphQL refuses the host when two trains would produce the same field in the same place (both under dispatch, or both under discover { players }), or when two mutation trains would produce the same response type ({Name}Response, whose name is schema-wide even when the fields sit in different namespaces). The error names both trains' interfaces. Set Name on one of them: Billing.ICreateOrderTrain and Shop.ICreateOrderTrain both derive CreateOrder, so give them Name = "BillingCreateOrder" and Name = "ShopCreateOrder". Two query trains with the same name in different namespaces are allowed, because neither has a response type.
Whatever its GraphQL name, a field runs its train by the interface's FullName, the canonical train name, so two trains whose interfaces share a short name each run their own train.
Namespaces
Namespace groups trains under a sub-namespace of discover or dispatch.
[TraxQuery(Namespace = "players", Description = "Looks up a player profile")]
public class LookupPlayerTrain : ServiceTrain<LookupPlayerInput, PlayerProfile>, ILookupPlayerTrain { ... }
[TraxQuery(Namespace = "players", Description = "Searches for players")]
public class SearchPlayersTrain : ServiceTrain<SearchPlayersInput, SearchResult>, ISearchPlayersTrain { ... }
[TraxMutation(Namespace = "alerts", Description = "Creates a new alert")]
public class CreateAlertTrain : ServiceTrain<CreateAlertInput, Alert>, ICreateAlertTrain { ... }This produces the following schema structure:
query {
discover {
players {
lookupPlayer(input: { playerId: "player-42" }) { ... }
searchPlayers(input: { query: "ace" }) { ... }
}
}
}
mutation {
dispatch {
alerts {
createAlert(input: { message: "Server overloaded" }) { ... }
}
}
}Trains without Namespace remain at the root level of discover or dispatch. Both namespaced and non-namespaced trains can coexist. The [TraxQueryModel] attribute also supports Namespace for entity queries.
Typed GraphQL clients targeting a namespaced train pair Namespace with the client's Path property on [GraphQLOperation]. For the schema above, a typed client would use Path = "discover.players" and RootField = "lookupPlayer". See GraphQL client.
Discovery
The attribute metadata is available through ITrainDiscoveryService. Each TrainRegistration includes:
IsQuery: whether the train has[TraxQuery]IsMutation: whether the train has[TraxMutation]GraphQLName: the name override (null if auto-derived)GraphQLNamespace: the namespace grouping (null if at root level)
The trains query exposes isQuery, isMutation and graphQLName; the namespace is not on it.
Examples
Query train
[TraxQuery(Description = "Looks up a player profile")]
[TraxAllowAnonymous]
public class LookupPlayerTrain
: ServiceTrain<LookupPlayerInput, LookupPlayerOutput>, ILookupPlayerTrain
{
protected override Task<Either<Exception, LookupPlayerOutput>> Junctions() => Chain<FetchPlayerJunction>().Resolve();
}Generates the query field lookupPlayer under discover. Returns LookupPlayerOutput directly:
query {
discover {
lookupPlayer(input: { playerId: "player-42" }) {
playerId
rank
wins
losses
rating
}
}
}Default mutation (run and queue)
[TraxAuthorize("Admin")]
[TraxMutation(Description = "Bans a player (admin only)")]
public class BanPlayerTrain : ServiceTrain<BanPlayerInput, Unit>, IBanPlayerTrain
{
protected override Task<Either<Exception, Unit>> Junctions() => Chain<ApplyBanJunction>().Resolve();
}With no operations passed, both Run and Queue are enabled. Generates banPlayer under dispatch with an optional mode: ExecutionMode parameter (default RUN):
# Run synchronously (default)
mutation {
dispatch {
banPlayer(input: { playerId: "player-42", reason: "cheating" }) {
externalId
metadataId
}
}
}
# Queue for async execution
mutation {
dispatch {
banPlayer(
input: { playerId: "player-42", reason: "cheating" }
mode: QUEUE
priority: 10
) {
externalId
workQueueId
}
}
}Run-only mutation
[TraxMutation(GraphQLOperation.Run, Description = "Pings the server")]
[TraxAllowAnonymous]
public class PingTrain : ServiceTrain<PingInput, PongOutput>, IPingTrain
{
protected override Task<Either<Exception, PongOutput>> Junctions() => Chain<PingJunction>().Resolve();
}Generates only ping under dispatch. No mode or priority parameters.
Queue-only mutation
[TraxMutation(GraphQLOperation.Queue, Description = "Recalculates the leaderboard")]
[TraxAuthorize(Roles = "Admin")]
public class RecalculateLeaderboardTrain
: ServiceTrain<RecalculateLeaderboardInput, Unit>, IRecalculateLeaderboardTrain
{
protected override Task<Either<Exception, Unit>> Junctions() =>
Chain<AggregateScoresJunction>().Chain<RankPlayersJunction>().Resolve();
}Generates only recalculateLeaderboard under dispatch. Has priority but no mode parameter.
Both execution modes (explicit)
[TraxMutation(GraphQLOperation.Run, GraphQLOperation.Queue, Description = "Processes a completed match result")]
public class ProcessMatchResultTrain
: ServiceTrain<ProcessMatchResultInput, ProcessMatchResultOutput>, IProcessMatchResultTrain { ... }This is equivalent to [TraxMutation] with no operations. Both forms enable both modes. Generates processMatchResult under dispatch with mode: ExecutionMode parameter.
Deprecating a field
[TraxMutation(DeprecationReason = "Use BanPlayerV2Train instead")]
public class BanPlayerTrain : ServiceTrain<BanPlayerInput, Unit>, IBanPlayerTrain { ... }The generated mutation will show a deprecation warning in GraphQL introspection.