gratos-server/effect runs Effect and Stream resolvers inside gratos-server. It is one schema wrapper (effectSchema), one plugin (effect()), one route for Effect's HTTP platform (effectRoute, or effectRouteLayer with its shutdown drain), and two helpers for the context factory (runInRequest and makeGuard). The server core never imports effect; only this entry does.

effectSchema

effectSchema(schema, options) wraps every resolve and subscribe of the generated schema once, at startup, and returns the schema. This site's:

src/graphql.ts
schema: effectSchema(schema, { failure, isFailure: isAppError }),

For each value a resolver returns, it takes the cheapest path: a plain value after one Effect.isEffect check; an Exit (a guard's refusal, say) at once, with no fiber; an Effect forked with the request's context, and when it finishes synchronously its value is returned with no Promise. A Stream becomes an async iterable whose items take the same error paths as fields.

Its options:

  • failure (required): the mapper from your typed failure to a GraphQL error. Build it with Match.tagsExhaustive, so that a new error tag fails the type check until it is mapped.
  • isFailure (required): a guard, (error: unknown) => error is E, for your typed failure. The schema erases each resolver's error type, so a value that reaches the wrapper may be anything; the mapper only ever sees a value the guard accepts. Any other failure is a masked ResolverDefect. With Schema.TaggedError classes, Schema.is(Schema.Union([...])) is the guard.
  • onTimeout: the error a guard's timeout becomes (default gqlError("Request timeout", 504, { code: "REQUEST_TIMEOUT" })).
  • onDefect: receives the defect of a cause that also holds a typed failure.

The mapper of this site, with gqlError(message, status, extensions) from gratos-server. It repeats a caller's id at most 64 characters long, and its failure wrapper remembers each error it makes, so the playground's error logger can skip them:

src/graphql.ts
const mapFailure = Match.type<AppError>().pipe(
  Match.tagsExhaustive({
    InvalidId: (error) =>
      gqlError(`No record has the id ${echoed(error.id)}`, 404, { code: "NOT_FOUND" }),
    InvalidPage: (error) => gqlError(error.reason, 400, { code: "BAD_USER_INPUT" }),
    MissingRecord: (error) =>
      gqlError(`The content index has no ${echoed(error.what)}`, 500, { code: "INTERNAL" }),
  }),
);

A failure's cause is handled one of three ways. A typed failure goes to failure. An interrupt because the client left, or because the request no longer needs the work, becomes the core's cancelled() sentinel, which reportErrors() skips. Anything else, a die or a rejected value, is a ResolverDefect, which maskErrors() hides. A resolver that returns a tagged-error instance as data counts as an Effect (a tagged error is yieldable) and fails with itself.

effect(), effectRoute and effectRouteLayer

effect({ context }) is the plugin. It opens the graphql <operation> span, with child spans for the parse, validate and jit phases, links each resolver to its request's scope, records the operation's type (so a guard knows a mutation), counts errors, and ends the span once the response body ends. context is the fork context of a request that did not come through a route, such as server.handle(request) in a test:

src/graphql.ts
// `context`: resolvers find the app's services also when the server is used without a
// route (makeServer(...).handle(request) in a test); a route forks with its own context.
effect({ context: services }),

effectRoute(server) is the HttpRouter handler. Register it for every method, so that a GET reaches the core and gets its 405. effectRouteLayer(server, { path, warnAfterMs }) is the route as a Layer, with a finalizer that drains the server on shutdown: it waits for every in-flight mutation to settle, and logs the ones still running every warnAfterMs. Provide it with the same service and tracer layers as the app, so that the drain runs before they are released:

packages/gratos-server/src/effect/route.ts
export const effectRouteLayer = (server: Server, options: EffectRouteLayerOptions = {}) => {
  const warnAfterMs = options.warnAfterMs ?? 5000;
  const drain = Layer.effectDiscard(
    Effect.addFinalizer(() => Effect.promise(() => server.control.drain({ warnAfterMs }))),
  );
  return Layer.merge(HttpRouter.add("*", options.path ?? "/graphql", effectRoute(server)), drain);
};

A drained server stays drained: it answers every later mutation with a 503. So build a server per layer, as this site does, inside Layer.unwrap:

src/host/app.ts
export const routesLayer = (schema: GraphQLSchema, options: HostOptions) =>
  Layer.unwrap(
    Effect.gen(function* () {
      const services = yield* Effect.context<Services>();
      const server = makeServer(schema, services, {
        documents: options.documents ?? persistedDocuments(),
        report: options.report,
      });

The request body's limit is the core's maxBodyBytes (1 MiB by default; a larger body gets a 413). For effectRoute it is the only limit: Effect's HttpIncomingMessage.MaxBodySize bounds only buffered reads, and the core reads the request as a stream. Raise or lower maxBodyBytes on createServer instead.

When a request stops

When a client leaves, its query and subscription fibers are interrupted, and nothing is reported. So are they when the request no longer needs their work: the core stopped the execution (a failed subscription source, a result it never sends), or the response ended with the work still running. A mutation is never interrupted: a half-applied write is worse than a wasted one.

The interrupt carries why. A resolver's Effect.onExit, and the finalizers of a Stream's scope, see HttpServerError.ClientAbort in the interrupt's annotations when the client left. This site's resolvers record it, so its tests can check it:

src/services/Probe.ts
export const endOf = (exit: Exit.Exit<unknown, unknown>): End => {
  if (Exit.isSuccess(exit)) {
    return "success";
  }
  const interrupts = exit.cause.reasons.filter(Cause.isInterruptReason);
  if (interrupts.length === 0) {
    return "failure";
  }
  if (interrupts.some((reason) => reason.annotations.has(HttpServerError.ClientAbort.key))) {
    return "client";
  }
  if (interrupts.some((reason) => reason.annotations.has(REQUEST_ENDED))) {
    return "internal";
  }
  return "interrupt";
};

For a query or a subscription, the graphql <operation> span always ends after the resolver spans it parents: once the body ends, it waits for the tracked resolver work and the opened streams to settle. A mutation is the exception, because it is never interrupted: its span still ends before the drain releases the services, but a nested resolver that a sibling's non-null failure left running may end after it. Resolvers fork without the request's Scope, so one that needs a scope uses Effect.scoped. Build long-lived resources (pools, intervals) in Layers, never lazily inside a resolver.

runInRequest

runInRequest(request, effect, services) runs an Effect from the context factory (reading the session, say) in the route's fiber context, so its span joins the request's trace, as a child of the HTTP span beside the operation span. It returns a Promise. When the client leaves, the Effect is interrupted, and the core answers 499; a mutation then never starts.

packages/gratos-server/src/effect/runInRequest.ts
export const runInRequest = <A, E, R>(
  request: Request,
  effect: Effect.Effect<A, E, R>,
  services: Context.Context<R>,
): Promise<A> => {

Guards

makeGuard({ authorize, refuse, flags, timeout, headers }) builds guard and guardStream for the request's context, so a resolver checks its scopes and feature flag in one call:

packages/gratos-server/src/effect/guard.ts
export interface Guard<E> {
  /** Runs `effect` once the requirements hold, else fails with the app's refusal (an Exit). */
  readonly guard: <A, E2, R>(
    input: GuardRequirements & { readonly effect: Effect.Effect<A, E2, R> },
  ) => Effect.Effect<A, E | E2, R>;
  /**
   * A guarded subscription source. Given the setup Effect (not a Stream.unwrap of it), only that
   * setup is bounded (`setupTimeout`, default the guard timeout); the stream's lifetime is not.
   */
  readonly guardStream: <A, E2, R, E3 = never, R3 = never>(
    input: GuardRequirements & {
      readonly stream: Stream.Stream<A, E2, R> | Effect.Effect<Stream.Stream<A, E2, R>, E3, R3>;
      readonly setupTimeout?: Duration.Input | undefined;
    },
  ) => Stream.Stream<A, E | E2 | E3, R | Exclude<R3, Scope.Scope>>;
}
  • guard({ scopes, flag, effect }) checks the scopes (all of them, through authorize) and the flag, then runs effect. A refusal is Effect.fail(refuse(…)), your own error, as an Exit: no fiber and no span.
  • The timeout (60 s by default) applies to queries only; a mutation is never interrupted. A timeout is a defect, GuardTimeout, not a typed failure, so your resolvers keep their own error type and your exhaustive mapper never sees it. It becomes the field's error through onTimeout, by default "Request timeout" with extensions.code: "REQUEST_TIMEOUT" and extensions.http.status: 504. That status is the response's only when the result has no data, as the HTTP status rules say: a nullable field that times out is null, with the error beside it, and the response stays a 200 with its data.
  • guardStream({ scopes, flag, stream, setupTimeout }) guards a subscription source. A refusal is a Stream that fails on its first pull, so the subscription answers with one error event, then completes. Pass the setup Effect that returns the Stream to have the setup bounded by setupTimeout; a Stream passed as it is, even one built with Stream.unwrap, gets no timeout at all.

OperationType is the Context.Reference the guard reads: effect() sets it per request, and an Effect run outside the server (a unit test) defaults to "query".

Contracts to know

  • One Request, one handle() call. Every per-request state is keyed by the Request object. Never pass a Request to handle() again while an earlier call on it is in flight, until its response body has ended. Replay a POST from a request.clone() taken before the first call.
  • Hooks that must not throw. A wrapExecution(request, run) wrapper calls run exactly once, synchronously, returns its result unchanged, and is reentrant. An executor must not throw after it has called next(): it reports a failure through its result, or a rejected Promise.
  • Subscriptions run graphql-js's own steps in the core: createSourceEventStream, then executeSubscriptionEvent per event, with the core holding the one source iterator it reads and closes. They go out as GraphQL over SSE.
  • graphql 17.1 drops a late subscription source. A source resolver that settles after the client left is dropped without return(). A source that acquires something before it returns must watch info.getAbortSignal() and release it itself. A guardStream source is never late: it is a Stream, returned at once, whose setup runs on its first pull.
  • No @defer or @stream on mutations. incremental() rejects them as validation errors, so deferred work never outlives the shutdown drain.