Skip to content

Rpc

Defines schema-backed contracts for individual RPC procedures.

An Rpc describes one remote procedure by recording its tag, payload schema, success schema, error schema, defect schema, middleware, and annotations. Clients and servers read the same declaration, so the procedure contract is independent of the transport used to call it. This module includes constructors, type helpers for deriving client and handler shapes, exit schemas, and handler wrappers for special execution modes.

50 exports Added in v4.0.0 Source

Constructors

custom

Added in v4.0.0 Source

Creates a custom Rpc constructor that can transform the output schemas.

Signature

declare function custom<Def extends Custom>(f: (options: OutDefault) => Def & OutDefault["out"]): <Tag extends string, Payload extends Top | Fields = Void, Success extends Top = Void, Error extends Top = Never, Stream extends boolean = false, Out extends OutDefault = Kind<Def, Success, Error>>(tag: Tag, options?: {
  readonly defect?: DefectSchema;
  readonly error?: Error;
  readonly payload?: Payload;
  readonly primaryKey?: [Payload] extends [Fields] ? (payload: Payload extends Fields ? { [K in string | number | symbol]: View<Payload, "Type", TypeOptionalKeys<...>, TypeMutableKeys<...>>[K] } : Payload["Type"]) => string : never;
  readonly stream?: Stream;
  readonly success?: Success;
}) => Rpc<Tag, Payload extends Fields ? Struct<Payload> : Payload, Stream extends true ? Stream<Out["success"], Out["error"]> : Out["success"], Stream extends true ? Never : Out["error"]>

Custom interface

Added in v4.0.0 Source

Defines the type-level contract for an RPC custom constructor.

Details

A custom constructor receives the original success, error, and defect schemas and returns transformed output schemas through out.

Signature

interface Custom {
  readonly defect: DefectSchema;
  readonly error: Top;
  readonly out: OutDefault;
  readonly success: Top;
}

exitSchema

Added in v4.0.0 Source

Builds the Schema.Exit used to encode and decode RPC results.

Details

The failure side includes the RPC error schema, middleware error schemas, and stream error schema for streaming RPCs. Streaming RPCs use Schema.Void for the exit success value. The schema is cached per RPC definition.

Signature

declare function exitSchema<R extends Any>(
  self: R,
): Exit<SuccessExitSchema<R>, ErrorExitSchema<R>, DefectSchema>;

make

Added in v4.0.0 Source

Creates an RPC definition with the supplied tag and optional schemas.

Details

Payload options can be either a schema or struct fields. stream: true wraps the success and error schemas in a stream schema and sets the normal error schema to Schema.Never. primaryKey creates a payload class with a primary key derived from the payload value.

Signature

declare function make<
  Tag extends string,
  Payload extends Top | Fields = Void,
  Success extends Top = Void,
  Error extends Top = Never,
  Stream extends boolean = false,
>(
  tag: Tag,
  options?: {
    readonly defect?: DefectSchema;
    readonly error?: Error;
    readonly payload?: Payload;
    readonly primaryKey?: [Payload] extends [Fields]
      ? (
          payload: Payload extends Fields
            ? {
                [K in string | number | symbol]: View<
                  Payload,
                  "Type",
                  TypeOptionalKeys<Payload>,
                  TypeMutableKeys<Payload>
                >[K];
              }
            : Payload["Type"],
        ) => string
      : never;
    readonly stream?: Stream;
    readonly success?: Success;
  },
): Rpc<
  Tag,
  Payload extends Fields ? Struct<Payload> : Payload,
  Stream extends true ? Stream<Success, Error> : Success,
  Stream extends true ? Never : Error
>;

Guards

isRpc

Added in v4.0.0 Source

Returns true when the value is an Rpc definition.

Signature

declare function isRpc(u: unknown): u is Rpc<any, any, any, Never, never, never>;

isWrapper

Added in v4.0.0 Source

Returns true when the value is an RPC Wrapper.

Signature

declare function isWrapper(u: object): u is Wrapper<any>;

Models

Any interface

Added in v4.0.0 Source

An erased RPC definition that preserves the common runtime metadata shared by all RPCs.

Signature

interface Any extends Pipeable {
  readonly _tag: string;
  readonly "~effect/rpc/Rpc": "~effect/rpc/Rpc";
  readonly annotations: Context<never>;
  readonly key: string;
}

AnyWithProps interface

Added in v4.0.0 Source

An erased RPC definition with all schema, middleware, annotation, and service metadata available.

Signature

interface AnyWithProps extends Pipeable {
  readonly _tag: string;
  readonly "~effect/rpc/Rpc": "~effect/rpc/Rpc";
  readonly "~requires": any;
  readonly annotations: Context<never>;
  readonly defectSchema: Top;
  readonly errorSchema: Top;
  readonly key: string;
  readonly middlewares: ReadonlySet<AnyServiceWithProps>;
  readonly payloadSchema: Top;
  readonly successSchema: Top;
}

Handler interface

Added in v4.0.0 Source

Represents the server-side implementation of an RPC.

Details

The handler receives the decoded request plus client, request id, headers, and RPC metadata, and returns either an effectful result or a stream result.

Signature

interface Handler<Tag extends string> {
  readonly _: typeof _;
  readonly context: Context<never>;
  readonly handler: (
    request: any,
    options: {
      readonly client: ServerClient;
      readonly headers: Headers;
      readonly requestId: RequestId;
      readonly rpc: Any;
    },
  ) => Effect<{} | Deferred<any, any>, any, never> | Stream<any, any, never>;
  readonly tag: Tag;
}

Rpc interface

Added in v4.0.0 Source

Represents a typed RPC definition.

Details

An RPC is identified by a tag and carries payload, success, error, defect, middleware, and annotation metadata used by RPC clients and servers.

Signature

interface Rpc<
  in out Tag extends string,
  out Payload extends Schema.Top = Schema.Void,
  out Success extends Schema.Top = Schema.Void,
  out Error extends Schema.Top = Schema.Never,
  out Middleware extends RpcMiddleware.AnyService = never,
  out Requires = never,
> extends Pipeable {
  constructor(_: never);
  readonly _tag: Tag;
  readonly "~effect/rpc/Rpc": "~effect/rpc/Rpc";
  readonly "~requires": Requires;
  readonly annotations: Context<never>;
  readonly defectSchema: Top;
  readonly errorSchema: Error;
  readonly key: string;
  readonly middlewares: ReadonlySet<Middleware>;
  readonly payloadSchema: Payload;
  readonly successSchema: Success;
  annotate<I, S>(
    tag: Key<I, S>,
    value: NoInfer<S>,
  ): Rpc<Tag, Payload, Success, Error, Middleware, Requires>;
  annotateMerge<I>(
    annotations: Context<I>,
  ): Rpc<Tag, Payload, Success, Error, Middleware, Requires>;
  middleware<M extends AnyService>(
    middleware: M,
  ): Rpc<Tag, Payload, Success, Error, Middleware | M, ApplyServices<M["Identifier"], Requires>>;
  prefix<Prefix extends string>(
    prefix: Prefix,
  ): Rpc<`${Prefix}${Tag}`, Payload, Success, Error, Middleware, Requires>;
  setError<E extends Top>(schema: E): Rpc<Tag, Payload, Success, E, Middleware, Requires>;
  setPayload<P extends Top | Fields>(
    schema: P,
  ): Rpc<Tag, P extends Fields ? Struct<P> : P, Success, Error, Middleware, Requires>;
  setSuccess<S extends Top>(schema: S): Rpc<Tag, Payload, S, Error, Middleware, Requires>;
}

ServerClient

Added in v4.0.0 Source

Represents server-side metadata for the client associated with an RPC request.

When to use

Use to inspect or annotate the connected client while handling an RPC request on the server.

Details

It stores the client id and request annotations that handlers can read or extend.

Signature

declare class ServerClient {
  constructor(id: number);
  annotations: Context<never>;
  readonly id: number;
  annotate<I, S>(tag: Key<I, S>, value: NoInfer<S>): ServerClient;
}

Other

Custom

Added in v4.0.0 Source

Helper types for defining RPC custom constructors.

Schemas

DefectSchema interface

Added in v4.0.0 Source

Schema for RPC defects.

Details

Defect schemas decode and encode without services and can be constructed from null, undefined, or an object value.

Signature

interface DefectSchema extends Top {
  constructor(_: never);
  readonly DecodingServices: never;
  readonly EncodingServices: never;
  make(input: null, options?: MakeOptions): unknown;
  make(input: undefined, options?: MakeOptions): unknown;
  make(input: {}, options?: MakeOptions): unknown;
}

Utility Types

AddError type

Added in v4.0.0 Source

Returns an RPC type with an additional error schema unioned into its error channel.

Signature

type AddError<R extends Any, Error extends Schema.Top> =
  R extends Rpc<
    infer _Tag,
    infer _Payload,
    infer _Success,
    infer _Error,
    infer _Middleware,
    infer _Requires
  >
    ? Rpc<_Tag, _Payload, _Success, _Error | Error, _Middleware, _Requires>
    : never;

AddMiddleware type

Added in v4.0.0 Source

Returns an RPC type with additional middleware and the corresponding middleware service requirements applied.

Signature

type AddMiddleware<R extends Any, Middleware extends RpcMiddleware.AnyService> =
  R extends Rpc<
    infer _Tag,
    infer _Payload,
    infer _Success,
    infer _Error,
    infer _Middleware,
    infer _Requires
  >
    ? Rpc<
        _Tag,
        _Payload,
        _Success,
        _Error,
        _Middleware | Middleware,
        RpcMiddleware.ApplyServices<Middleware["Identifier"], _Requires>
      >
    : never;

Error type

Added in v4.0.0 Source

Extracts the decoded error value type from an Rpc, including middleware errors.

Signature

type Error<R> = Schema.Schema.Type<ErrorSchema<R>>;

ErrorExit type

Added in v4.0.0 Source

Extracts the decoded error type used by an RPC exit.

Details

For streaming RPCs, this includes both stream errors and RPC errors.

Signature

type ErrorExit<R> =
  Success<R> extends Stream<infer _A, infer _E, infer _Env> ? _E | Error<R> : Error<R>;

ErrorExitSchema type

Added in v4.0.0 Source

Extracts the error schema used in an RPC exit.

Details

For streaming RPCs, this includes both the stream error schema and the RPC error schema; otherwise it is the RPC error schema.

Signature

type ErrorExitSchema<R> =
  SuccessSchema<R> extends RpcSchema.Stream<infer _A, infer _E>
    ? _E | ErrorSchema<R>
    : ErrorSchema<R>;

ErrorSchema type

Added in v4.0.0 Source

Extracts the RPC error schema, including error schemas contributed by middleware.

Signature

type ErrorSchema<R> =
  R extends Rpc<
    infer _Tag,
    infer _Payload,
    infer _Success,
    infer _Error,
    infer _Middleware,
    infer _Requires
  >
    ? _Error | _Middleware["error"]
    : never;

ExcludeProvides type

Added in v4.0.0 Source

Removes the services provided by middleware for the specified RPC tag from an environment type.

Signature

type ExcludeProvides<Env, R extends Any, Tag extends string> = Exclude<
  Env,
  ExtractProvides<R, Tag>
>;

Exit type

Added in v4.0.0 Source

The Exit type produced for an RPC, using the RPC's exit success and exit error types.

Signature

type Exit<R> = Exit_<SuccessExit<R>, ErrorExit<R>>;

ExtractProvides type

Added in v4.0.0 Source

Extracts the services provided by middleware on the RPC with the specified tag.

Signature

type ExtractProvides<R extends Any, Tag extends string> =
  R extends Rpc<
    Tag,
    infer _Payload,
    infer _Success,
    infer _Error,
    infer _Middleware,
    infer _Requires
  >
    ? RpcMiddleware.Provides<_Middleware["Identifier"]>
    : never;

ExtractRequires type

Added in v4.0.0 Source

Extracts the service requirements of the RPC with the specified tag.

Signature

type ExtractRequires<R extends Any, Tag extends string> =
  R extends Rpc<
    Tag,
    infer _Payload,
    infer _Success,
    infer _Error,
    infer _Middleware,
    infer _Requires
  >
    ? _Requires
    : never;

ExtractTag type

Added in v4.0.0 Source

Extracts the RPC with the specified tag from an RPC union.

Signature

type ExtractTag<R extends Any, Tag extends string> =
  R extends Rpc<
    Tag,
    infer _Payload,
    infer _Success,
    infer _Error,
    infer _Middleware,
    infer _Requires
  >
    ? R
    : never;

IsStream type

Added in v4.0.0 Source

Returns true when the RPC with the specified tag has a streaming success schema, or never otherwise.

Signature

type IsStream<R extends Any, Tag extends string> =
  R extends Rpc<
    Tag,
    infer _Payload,
    RpcSchema.Stream<infer _A, infer _E>,
    infer _Error,
    infer _Middleware,
    infer _Requires
  >
    ? true
    : never;

Middleware type

Added in v4.0.0 Source

Extracts the service identifiers for middleware attached to an Rpc.

Signature

type Middleware<R> =
  R extends Rpc<
    infer _Tag,
    infer _Payload,
    infer _Success,
    infer _Error,
    infer _Middleware,
    infer _Requires
  >
    ? Context.Service.Identifier<_Middleware>
    : never;

MiddlewareClient type

Added in v4.0.0 Source

Extracts client-side middleware service requirements for middleware marked as required on the client.

Signature

type MiddlewareClient<R> =
  R extends Rpc<
    infer _Tag,
    infer _Payload,
    infer _Success,
    infer _Error,
    infer _Middleware,
    infer _Requires
  >
    ? _Middleware extends {
        readonly requiredForClient: true;
      }
      ? RpcMiddleware.ForClient<_Middleware["Identifier"]>
      : never
    : never;

Payload type

Added in v4.0.0 Source

Extracts the decoded payload type from an Rpc.

Signature

type Payload<R> =
  R extends Rpc<
    infer _Tag,
    infer _Payload,
    infer _Success,
    infer _Error,
    infer _Middleware,
    infer _Requires
  >
    ? _Payload["Type"]
    : never;

PayloadConstructor type

Added in v4.0.0 Source

Extracts the payload constructor input type accepted by the RPC payload schema.

Signature

type PayloadConstructor<R> =
  R extends Rpc<
    infer _Tag,
    infer _Payload,
    infer _Success,
    infer _Error,
    infer _Middleware,
    infer _Requires
  >
    ? _Payload["~type.make.in"]
    : never;

Prefixed type

Added in v4.0.0 Source

Returns an RPC type with the specified string prefix added to its tag while preserving its payload, success, error, middleware, and requirements.

Signature

type Prefixed<Rpcs extends Any, Prefix extends string> =
  Rpcs extends Rpc<
    infer _Tag,
    infer _Payload,
    infer _Success,
    infer _Error,
    infer _Middleware,
    infer _Requires
  >
    ? Rpc<`${Prefix}${_Tag}`, _Payload, _Success, _Error, _Middleware, _Requires>
    : never;

ResultFrom type

Added in v4.0.0 Source

Computes the allowed handler result type for an RPC.

Details

Streaming RPCs may return a stream or an effect that produces a queue. Other RPCs return an effect that succeeds with the success value or a deferred success value.

Signature

type ResultFrom<R extends Any, Services> =
  R extends Rpc<
    infer _Tag,
    infer _Payload,
    infer _Success,
    infer _Error,
    infer _Middleware,
    infer _Requires
  >
    ? [_Success] extends [RpcSchema.Stream<infer _SA, infer _SE>]
      ?
          | Stream<_SA["Type"], _SE["Type"] | _Error["Type"], Services>
          | Effect<
              Queue.Dequeue<_SA["Type"], _SE["Type"] | _Error["Type"] | Cause.Done>,
              _SE["Type"] | Schema.Schema.Type<_Error>,
              Services
            >
      : Effect<
          _Success["Type"] | Deferred<_Success["Type"], _Error["Type"]>,
          _Error["Type"],
          Services
        >
    : never;

Services type

Added in v4.0.0 Source

Extracts all schema services required to encode or decode an RPC's payload, success, error, and middleware error schemas.

Signature

type Services<R> =
  R extends Rpc<
    infer _Tag,
    infer _Payload,
    infer _Success,
    infer _Error,
    infer _Middleware,
    infer _Requires
  >
    ?
        | _Payload["DecodingServices"]
        | _Payload["EncodingServices"]
        | _Success["DecodingServices"]
        | _Success["EncodingServices"]
        | _Error["DecodingServices"]
        | _Error["EncodingServices"]
        | _Middleware["error"]["DecodingServices"]
        | _Middleware["error"]["EncodingServices"]
    : never;

ServicesClient type

Added in v4.0.0 Source

Extracts the schema services required on the client side of an RPC.

Details

This includes payload encoding services and success, error, and middleware error decoding services.

Signature

type ServicesClient<R> =
  R extends Rpc<
    infer _Tag,
    infer _Payload,
    infer _Success,
    infer _Error,
    infer _Middleware,
    infer _Requires
  >
    ?
        | _Payload["EncodingServices"]
        | _Success["DecodingServices"]
        | _Error["DecodingServices"]
        | _Middleware["error"]["DecodingServices"]
    : never;

ServicesServer type

Added in v4.0.0 Source

Extracts the schema services required on the server side of an RPC.

Details

This includes payload decoding services and success, error, and middleware error encoding services.

Signature

type ServicesServer<R> =
  R extends Rpc<
    infer _Tag,
    infer _Payload,
    infer _Success,
    infer _Error,
    infer _Middleware,
    infer _Requires
  >
    ?
        | _Payload["DecodingServices"]
        | _Success["EncodingServices"]
        | _Error["EncodingServices"]
        | _Middleware["error"]["EncodingServices"]
    : never;

Success type

Added in v4.0.0 Source

Extracts the decoded success value type from an Rpc.

Signature

type Success<R> = SuccessSchema<R>["Type"];

SuccessChunk type

Added in v4.0.0 Source

Extracts the decoded stream element type from a streaming RPC, or never for non-streaming RPCs.

Signature

type SuccessChunk<R> = Success<R> extends Stream<infer _A, infer _E, infer _Env> ? _A : never;

SuccessEncoded type

Added in v4.0.0 Source

Extracts the encoded success value type from an Rpc.

Signature

type SuccessEncoded<R> =
  R extends Rpc<
    infer _Tag,
    infer _Payload,
    infer _Success,
    infer _Error,
    infer _Middleware,
    infer _Requires
  >
    ? _Success["Encoded"]
    : never;

SuccessExit type

Added in v4.0.0 Source

Extracts the decoded success value carried by an RPC exit.

Details

For streaming RPCs, the immediate exit success is void because stream elements are delivered separately.

Signature

type SuccessExit<R> =
  Success<R> extends infer T
    ? T extends Stream<infer _A, infer _E, infer _Env>
      ? void
      : T
    : never;

SuccessExitSchema type

Added in v4.0.0 Source

Extracts the success schema used in an RPC exit.

Details

For streaming RPCs, this is the stream element schema; otherwise it is the RPC success schema.

Signature

type SuccessExitSchema<R> =
  SuccessSchema<R> extends RpcSchema.Stream<infer _A, infer _E> ? _A : SuccessSchema<R>;

SuccessSchema type

Added in v4.0.0 Source

Extracts the success schema from an Rpc.

Signature

type SuccessSchema<R> =
  R extends Rpc<
    infer _Tag,
    infer _Payload,
    infer _Success,
    infer _Error,
    infer _Middleware,
    infer _Requires
  >
    ? _Success
    : never;

Tag type

Added in v4.0.0 Source

Extracts the tag string from an Rpc.

Signature

type Tag<R> =
  R extends Rpc<
    infer _Tag,
    infer _Payload,
    infer _Success,
    infer _Error,
    infer _Middleware,
    infer _Requires
  >
    ? _Tag
    : never;

ToHandler type

Added in v4.0.0 Source

Converts an RPC definition into the corresponding Handler type.

Signature

type ToHandler<R extends Any> =
  R extends Rpc<
    infer _Tag,
    infer _Payload,
    infer _Success,
    infer _Error,
    infer _Middleware,
    infer _Requires
  >
    ? Handler<_Tag>
    : never;

ToHandlerFn type

Added in v4.0.0 Source

The function signature for implementing an RPC handler.

Details

The function receives the decoded payload and request metadata, and returns the RPC result shape, optionally wrapped with Wrapper options.

Signature

type ToHandlerFn<Current extends Any, R = any> = (
  payload: Payload<Current>,
  options: {
    readonly client: ServerClient;
    readonly headers: Headers;
    readonly requestId: RequestId;
    readonly rpc: Current;
  },
) => WrapperOr<ResultFrom<Current, R>>;

Wrapping

fork

Added in v4.0.0 Source

Wraps a response Effect or Stream so the RPC server executes it concurrently regardless of the server concurrency setting.

Signature

declare const fork: <A extends object>(value: A) => Wrapper<A>;

Wraps a response Effect or Stream so the RPC server runs it in an uninterruptible region.

Signature

declare const uninterruptible: <A extends object>(value: A) => Wrapper<A>;

unwrap

Added in v4.0.0 Source

Returns the wrapped response value when the input is an RPC Wrapper, or the input itself when it is already unwrapped.

Signature

declare function unwrap<A extends object>(value: WrapperOr<A>): A;

wrap

Added in v4.0.0 Source

Wraps a handler result with RPC server execution options.

Details

When the value is already wrapped, unspecified options are inherited from the existing wrapper.

Signature

declare function wrap(options: {
  readonly fork?: boolean;
  readonly uninterruptible?: boolean;
}): <A extends object>(value: A) => Wrapper<A>;

wrapMap

Added in v4.0.0 Source

Maps the value inside an RPC wrapper, preserving wrapper options such as fork and uninterruptible; unwrapped values are mapped directly.

Signature

declare function wrapMap<A extends object, B extends object>(
  self: WrapperOr<A>,
  f: (value: A) => B,
): WrapperOr<B>;

Wrapper interface

Added in v4.0.0 Source

Wraps a handler result with execution options for the RPC server.

Details

fork requests concurrent execution, and uninterruptible requests uninterruptible execution.

Signature

interface Wrapper<A> {
  readonly "~effect/rpc/Rpc/Wrapper": "~effect/rpc/Rpc/Wrapper";
  readonly fork: boolean;
  readonly uninterruptible: boolean;
  readonly value: A;
}

WrapperOr type

Added in v4.0.0 Source

A value that may be returned directly or wrapped with RPC server execution options.

Signature

type WrapperOr<A> = A | Wrapper<A>;