Three hand-written-feeling classes ship as part of every Graphitron code-generation run. They aren’t pulled in from a runtime library; they are emitted into your <outputPackage> source tree alongside the type-specific fetchers, and your consumer module compiles them. This is what keeps the runtime dependency surface flat: your code depends on jOOQ, graphql-java, and your own generated sources, nothing else.

This page documents the public method surface of all three, and the consumer hooks the owned-connection runtime carries. The directive reference under reference/directives covers what gets emitted because of SDL declarations; this page covers what gets emitted unconditionally and how your consumer code calls into it.

Graphitron facade

Emitted by GraphitronFacadeGenerator into <outputPackage>. Single public entry point for building the schema:

public final class Graphitron {

    public static GraphQLSchema buildSchema(
        Consumer<GraphQLSchema.Builder> customizer);

    // Emitted only when your SDL declares a federation @link.
    public static GraphQLSchema buildSchema(
        Consumer<GraphQLSchema.Builder> schemaCustomizer,
        Consumer<SchemaTransformer>     federationCustomizer);
}

buildSchema returns a fully wired GraphQLSchema: every type, field, fetcher, and directive Graphitron understands is attached before the schema is built. Custom scalars are wired automatically from the @scalarType(scalar:) directive on each scalar declaration (see @scalarType directive); the customizer lambda receives the underlying GraphQLSchema.Builder so consumer code can layer in additional non-scalar types, hand-rolled type resolvers, or custom directives before the build.

Customizer contract

The customizer is additive only. The following are unsupported and break the assembled schema:

  • .query(…​) / .mutation(…​) / .subscription(…​) — replaces the root types Graphitron just wired.

  • .clearDirectives() — drops the directive set Graphitron emits for federation, authorization, and validation.

  • .codeRegistry(GraphQLCodeRegistry) (the replace overload) — replaces the fetcher registry Graphitron just populated.

The supported extension shape for codeRegistry is the transform overload .codeRegistry(UnaryOperator<GraphQLCodeRegistry.Builder>); that one is fine and is the seam for adding type resolvers to interfaces and unions whose Java types Graphitron cannot infer (hand-rolled domain types, types pulled in from a non-Graphitron source, polymorphic shapes outside the catalog). How-to: Polymorphic types covers the resolver shape.

The customizer runs once per schema build, not once per request. Per-request runtime values flow through GraphitronContext on the ExecutionInput.graphQLContext, not through this lambda.

Federation two-arg overload

When at least one of your .graphqls files carries an Apollo Federation @link, the generator emits a second overload that exposes the federation builder. The federation customizer’s most useful method is fetchEntities(…​) for swapping in a hand-rolled entity fetcher:

GraphQLSchema schema = Graphitron.buildSchema(
    b   -> {},
    fed -> fed.fetchEntities(myCustomFetcher));

Without the @link, the federation overload isn’t emitted, the federation surface stays out of the build entirely, and buildSchema returns a vanilla schema. How-to: Apollo Federation transport covers the transport-side wiring; How-to: Federation key fields covers entity-side declaration.

GraphitronContext interface

Emitted by GraphitronContextInterfaceGenerator into <outputPackage>.schema. The sealed per-request contract every generated DataFetcher reads from. Apps no longer implement it; the only impl is the generator’s own GraphitronContextImpl singleton (nested inside the interface for same-compilation-unit permits), populated by Graphitron.newExecutionInput(…​).

public sealed interface GraphitronContext {

    default DSLContext getDslContext(DataFetchingEnvironment env) {
        return OwnedConnections.dslFor(env, ConnectionKey.defaultSource());
    }

    default Object getContextArgument(DataFetchingEnvironment env, String name) {
        Object value = env.getGraphQlContext().get(name);
        if (value == null) {
            throw new IllegalStateException("context value '" + name
                + "' was not supplied; call Graphitron.newExecutionInput(...) to populate it");
        }
        return value;
    }

    default Validator getValidator(DataFetchingEnvironment env) {
        return DefaultValidatorHolder.INSTANCE;
    }

    final class GraphitronContextImpl implements GraphitronContext {
        public static final GraphitronContextImpl INSTANCE = new GraphitronContextImpl();
        private GraphitronContextImpl() {}
    }
}

The factory IS the registration point; the parameter list is schema-driven (DSLContext first, then one parameter per contextArgument named in @service / @condition directives, alphabetically):

ExecutionInput input = Graphitron.newExecutionInput(dsl, /* contextArgs... */)
    .query(query)
    .build();

Generated fetchers retrieve the impl through a private helper emitted once per *Fetchers class (graphitronContext(env)); generated helpers that issue SQL on behalf of those fetchers emit the same shim (for example, ConnectionHelper.dsl(env), which resolves the context a connection’s totalCount and facets run on when the client reads them). The sealed-interface + singleton-impl pair means GraphitronContext is global to the build, not per-request; all per-request state lives in the GraphQLContext the factory populates.

getDslContext

Answers the per-request DSLContext for the connection key with no parts, through OwnedConnections.dslFor(env, key), the one point every generated fetcher reaches a connection by. On the owned path (Graphitron.newOwnedExecutionInput(…​) with GraphitronRuntime.newGraphQL(schema)) that is the connection the request’s ConnectionSource leases for the key, pinned on first use. On the escape-hatch path it is the DSLContext the factory’s defaultDsl parameter put into the request’s GraphQLContext, which serves only the key with no parts. An operation carrying both, or neither, is refused. The default impl is the only impl; this is not an override point. On the escape-hatch path, tenant-specific routing means building the right DSLContext at request entry and passing it to Graphitron.newExecutionInput(dsl, …​); for generator-owned database-per-tenant routing (divined bindings, fan-out), see How-to: Tenant scoping.

getContextArgument

Reads the value from env.getGraphQlContext() (under the contextArgument’s string name) and returns it as Object; the cast to the expected Java type happens at the generated call site ((String) graphitronContext(env).getContextArgument(env, "userId")). A missing entry throws IllegalStateException naming the contextArgument and pointing the reader at Graphitron.newExecutionInput(…​); a wrong-typed entry surfaces as ClassCastException at the generated cast. Both throw paths are only reachable when a consumer hand-rolls an ExecutionInput.Builder outside the factory; going through Graphitron.newExecutionInput(…​) makes the same mistake a compile error at the call site, because the factory’s typed parameter slot IS the reflected expected type. The framework’s redact path replaces the prose message with a correlation-id reference before it reaches the consumer, so the runtime throw is server-log surface only; the typed factory is the load-bearing diagnostic.

How-to: Stacking and overriding conditions covers the call-site shape; the supplying side is the factory’s typed parameter slot.

getValidator

Returns the jakarta.validation.Validator the wrapper’s pre-execution validation step uses for this fetch. Defaults to the JVM’s default validator factory:

default Validator getValidator(DataFetchingEnvironment env) {
    return DefaultValidatorHolder.INSTANCE;
}

DefaultValidatorHolder is a holder-class idiom inside the same emitted file; its INSTANCE is initialised on the first call to getValidator (Validation.buildDefaultValidatorFactory().getValidator()) and shared by every subsequent default-using request. The method is no longer an override point on the sealed interface, and there is no custom-validator-factory configuration today.

NodeIdEncoder utility

Emitted into <outputPackage>.util unconditionally: the class ships on every run, and a schema with no node type simply gets no per-type helpers on it. Static, non-extendable encode/decode helpers for Relay global IDs:

public final class NodeIdEncoder {

    public static String encode(String typeId, Object... values);

    public static String peekTypeId(String base64Id);

    public static String[] decodeValues(String expectedTypeId, String base64Id);

    public static String toCurrentId(String base64Id);

    public static Object[] decodeColumns(
        String expectedTypeId, String base64Id, Class<?>[] parseClasses, Field<?>... columns);

    public static void requireColumnAgreement(
        String conflictLabel, DataType<?> type, Object a, Object b);

    // Per-Node helpers, one pair per node type:
    public static String  encode<TypeName>(T1 v1, ..., TN vN);
    public static RecordN<T1, ..., TN> decode<TypeName>(String base64Id);
}

Wire format

Every Graphitron-emitted nodeId is base64-url-encoded "typeId:v1,v2,…​" (no padding, UTF-8). Commas inside values are escaped as %2C, so a key value containing a literal comma round-trips losslessly. Each value is written as its column’s Java type’s toString() and parsed back as that type, so a key column behind a jOOQ converter round-trips through the converter’s user type. The format matches the legacy no.sikt.graphql.NodeIdStrategy encoding, so IDs round-trip across a cut-over from the legacy generator.

encode(typeId, values…​) returns null when any value is null, so the GraphQL field resolves to null rather than emitting a malformed ID.

Per-Node helpers

For each node type the generator emits two static helpers named after the GraphQL type. A node type is a @table type carrying @node, or implementing Node over a table whose generated class publishes node metadata; a node this subgraph does not resolve, @node(resolvable: false), is one too, since its id encodes and decodes like any node’s even though Query.node answers it with null:

  • encode<TypeName>(T1 v1, …​, TN vN) — bakes the typeId into the helper name so call sites pass typed key values directly. Returns null if any value is null.

  • decode<TypeName>(String base64Id) — returns a jOOQ RecordN<T1, …​, TN> typed against the node’s key columns, or null uniformly on malformed input, a typeId mismatch, the wrong number of key values, or a key value that is not a value of its column. Carrier consumers wrap that null through the matching CallSiteExtraction.NodeIdDecodeKeys.* arm.

peekTypeId(base64Id) reads the typeId off the wire string without decoding the rest. Query.node(id:) uses this to dispatch to the right @node type’s table; a non-typed reader can call it the same way.

Untyped helpers

Three more helpers are public because generated code in other packages calls them, or because a consumer reading an id without a typed target needs them, and they are documented here because a consumer reading generated sources will meet them:

  • decodeValues(expectedTypeId, base64Id) — the raw unpack: the key values as a String[] exactly as they sit on the wire, or null when the input is malformed or carries another typeId. No value is checked against a column, so do not bind these strings into SQL; use decodeColumns or the per-Node helper for that. It is the raw unpack in shape too: an id in a type’s legacy key shape comes back with its legacy values, so call toCurrentId first for the current shape.

  • toCurrentId(base64Id) — an id in its type’s current key shape. It returns the id unchanged unless it is a legacy-shape id of a type that declares one (@node(legacyKeyColumns:) or the table class’s __NODE_LEGACY_KEY_COLUMNS), the current-shape id when it is, and null when it is a legacy-shape id carrying a value that is not one of its column. A migration job rewriting the ids it holds calls this; decodeColumns calls it on every id of such a type, so nothing else has to.

  • decodeColumns(expectedTypeId, base64Id, parseClasses, columns…​) — the decode behind every per-Node decode<TypeName>: the key values as values of columns, in key order, or null when the input is malformed, carries another typeId, has the wrong number of key values, or carries a value that is not exactly what encode writes for a value of its column. That last case covers non-numeric text, a number outside the column’s range or precision, and a padded or reformatted number; on a column with a jOOQ converter the value is followed through the converter to its database value and back. parseClasses says which type each value’s text is parsed as: null (the whole array, or one element) parses through the column’s DataType, and a class, which generated code passes as a converter’s user type, parses the text as that class before the converter sees it. Generated code decides it per key column at build time, so a converter-backed key decodes to the value it was minted from.

  • requireColumnAgreement(conflictLabel, type, a, b) — the value-agreement check the write path emits when two input fields land on one column. It coerces both values through the destination column’s DataType and throws a GraphqlErrorException naming conflictLabel when they disagree.

Why a final class with private constructor

A single canonical wire format across every generated dispatcher is what makes nodeIds durable across schema evolution. Subclassing the encoder to override the encoding would let one corner of an app speak a different dialect from another, and the result would not round-trip. How-to: Global object IDs covers Relay Node end-to-end, including stable-ID strategies and keyColumns migrations.

Consumer hooks on GraphitronRuntime

Three interfaces are emitted unconditionally into <outputPackage>.schema, next to GraphitronRuntime, and a fourth, VouchedValueLimit, beside them in a build that accepts vouchers. Each is a callback you implement and hand to the runtime through a wither, which returns a copy of the runtime carrying it; a runtime you configure nothing on behaves as the "default" column says. On the escape-hatch engine (Graphitron.newGraphQL()), which has no runtime, put one of the first three into each request’s GraphQLContext under its class; a build that accepts vouchers has no escape hatch, so its VouchedValueLimit is always given to the runtime.

Hook Set with Decides Default

FetcherErrorLog

withFetcherErrorLog(log)

How an exception no @error handler claims is logged (unmatched), and whether one a handler caught is logged (matched). In a <tenantColumn> build, tenantFailed receives a tenant that failed in a fanned-out field.

An unclaimed exception is logged once per request at ERROR, however many fields it failed: a one-line summary when it came from the database driver (the full exception at DEBUG), its stack trace otherwise. A tenant that fails in a fanned-out field is logged the same way, once per failed tenant. A caught exception is not logged.

FetcherErrorResponse

withFetcherErrorResponse(response)

What the client reads for a fetcher exception: its reference, a caught error’s message: (matchedMessage), and the top-level text of a client error (clientErrorMessage) or of anything else unclaimed (unmatchedMessage).

A random UUID as the reference, minted once per exception per request; the handler’s description: or the exception’s message; "An error occurred. Reference: <reference>."

BatchSizeLimit

withBatchSizeLimit(limit)

The most keys one batched query may carry (maxBatchSize(env)), asked once per batched field per request. A batch over the answer runs as several queries.

No limit: one query carries every parent’s key. An answer below 1 means the same.

VouchedValueLimit

withVouchedValueLimit(limit)

The most distinct vouched-for values one request admits (maxVouchedValues(env)), asked once per request, with the environment of the _entities field that admitted the first voucher, and held for the request. A representation whose value is past it answers null and an error at its own index. Accepting builds only.

A thousand (GraphitronRuntime.DEFAULT_VOUCHED_VALUE_LIMIT), sized to a list. It fails closed: an answer below 1 admits no value, so answer Integer.MAX_VALUE for no practical bound. Unlike BatchSizeLimit, which only splits a statement, no limit here would drop a bound on what one request costs the database.

A hook that throws never fails the request: the default stands, and Graphitron logs one ERROR line naming the hook’s class and the class of what it threw. Only JVM-fatal errors propagate.

ErrorRouter.describe(thrown, env), also in <outputPackage>.schema, returns the one-line database summary the default log line uses, or an empty Optional for an exception that did not come from the driver, so a FetcherErrorLog can write the same line.

How-to: Error channel covers the two error hooks in use; Bounding a batch covers the limit.

withOutboxAcquisitionTimeout(timeout)

In a schema with an @outbox(on: ERROR) message, GraphitronRuntime also has withOutboxAcquisitionTimeout(Duration), returning a copy of the runtime, and outboxAcquisitionTimeout(). It bounds the wait for a fresh connection to write a field’s failure messages on, when the field’s transaction cost it its own: past it the messages are not written and the loss is logged. The default is five seconds (DEFAULT_OUTBOX_ACQUISITION_TIMEOUT); the timeout must be positive. The acquisition runs on the fan-out executor in a <tenantColumn> build and otherwise on a small pool of daemon threads the runtime creates on first use and never shuts down, so an idle pool holds no application open. Your `DataSource’s own login timeout does not bound a wait for a free pooled connection, which is why this is a setting of its own.

See also

  • Directive reference is the SDL-driven half of what generated code looks like; this page is the SDL-independent half.

  • How-to: Test your schema covers wiring Graphitron.buildSchema(…​) and a request-scoped GraphitronContext into an execution-tier test.

  • How-to: Custom scalars covers declaring a scalar with @scalarType(scalar:) and authoring the GraphQLScalarType constant the directive points at.

  • How-to: Tenant scoping covers database-per-tenant wiring: the tenant column, per-tenant DataSources, and fanning a field out across tenants with @tenantFanOut.

  • How-to: Global object IDs covers NodeIdEncoder end-to-end, including the per-Node helpers, keyColumns migrations, and Query.node / Query.nodes dispatch.