Skip to content

Socket

Models bidirectional socket connections in Effect.

The Socket service runs handlers for binary, string, or raw frames and provides a scoped writer for outgoing bytes, text, or close events. This module also includes socket errors, channel adapters, WebSocket layers, and transform-stream-backed sockets.

33 exports Added in v4.0.0 Source

Combinators

toChannel

Added in v4.0.0 Source

Converts a Socket into a binary Channel, encoding incoming string frames as UTF-8 bytes.

Signature

declare function toChannel<IE>(
  self: Socket,
): Channel<
  readonly [Uint8Array<ArrayBufferLike>, Uint8Array<ArrayBufferLike>],
  SocketError | IE,
  void,
  readonly [
    string | Uint8Array<ArrayBufferLike> | CloseEvent,
    string | Uint8Array<ArrayBufferLike> | CloseEvent,
  ],
  IE
>;

toChannelMap

Added in v4.0.0 Source

Converts a Socket into a bidirectional Channel, mapping incoming string or binary frames and writing outgoing frame batches to the socket.

Signature

declare function toChannelMap<IE, A>(
  self: Socket,
  f: (data: string | Uint8Array<ArrayBufferLike>) => A,
): Channel<
  readonly [A, A],
  SocketError | IE,
  void,
  readonly [
    string | Uint8Array<ArrayBufferLike> | CloseEvent,
    string | Uint8Array<ArrayBufferLike> | CloseEvent,
  ],
  IE
>;

Converts a Socket into a string Channel, decoding binary frames with the optional text encoding.

Signature

declare const toChannelString: {
  (
    encoding?: string,
  ): <IE>(
    self: Socket,
  ) => Channel<
    readonly [string, string],
    SocketError | IE,
    void,
    readonly [
      string | Uint8Array<ArrayBufferLike> | CloseEvent,
      string | Uint8Array<ArrayBufferLike> | CloseEvent,
    ],
    IE
  >;
  <IE>(
    self: Socket,
    encoding?: string,
  ): Channel<
    readonly [string, string],
    SocketError | IE,
    void,
    readonly [
      string | Uint8Array<ArrayBufferLike> | CloseEvent,
      string | Uint8Array<ArrayBufferLike> | CloseEvent,
    ],
    IE
  >;
};

Creates a Socket to binary Channel adapter with a fixed upstream error type.

Signature

declare function toChannelWith<IE = never>(): (
  self: Socket,
) => Channel<
  readonly [Uint8Array<ArrayBufferLike>, Uint8Array<ArrayBufferLike>],
  SocketError | IE,
  void,
  readonly [
    string | Uint8Array<ArrayBufferLike> | CloseEvent,
    string | Uint8Array<ArrayBufferLike> | CloseEvent,
  ],
  IE
>;

Constructors

Builds a Socket from a scoped InputTransformStream, reading incoming chunks through socket handlers and writing outgoing chunks to the writable stream, encoding strings as UTF-8 and using close-code classification for CloseEvent values.

Signature

declare function fromTransformStream<R>(
  acquire: Effect<InputTransformStream, SocketError, R>,
  options?: {
    readonly closeCodeIsError?: (code: number) => boolean;
  },
): Effect<Socket, never, Exclude<R, Scope>>;

Builds a Socket from a scoped WebSocket acquisition effect, waiting for the socket to open, dispatching message handlers in fibers, and translating open, read, and close events into SocketError values.

Signature

declare function fromWebSocket<RO>(acquire: Effect<WebSocket, SocketError, RO>, options?: {
  readonly closeCodeIsError?: (code: number) => boolean;
  readonly onInitialRun?: (ws: WebSocket) => readonly Array<MessageEvent<any>>;
  readonly openTimeout?: Input;
}): Effect<Socket, never, Exclude<RO, Scope>>

make

Added in v4.0.0 Source

Constructs a Socket from a raw read loop and scoped writer, deriving binary and string read loops when they are not provided.

Signature

declare function make(options: {
  readonly run?: <_, E, R>(
    handler: (_: Uint8Array) => void | Effect<_, E, R>,
    options?: {
      readonly onOpen?: Effect<void, never, never>;
    },
  ) => Effect<void, SocketError | E, R>;
  readonly runRaw: <_, E, R>(
    handler: (_: string | Uint8Array<ArrayBufferLike>) => void | Effect<_, E, R>,
    options?: {
      readonly onOpen?: Effect<void, never, never>;
    },
  ) => Effect<void, SocketError | E, R>;
  readonly runString?: <_, E, R>(
    handler: (_: string) => void | Effect<_, E, R>,
    options?: {
      readonly onOpen?: Effect<void, never, never>;
    },
  ) => Effect<void, SocketError | E, R>;
  readonly writer: Effect<
    (chunk: string | Uint8Array<ArrayBufferLike> | CloseEvent) => Effect<void, SocketError>,
    never,
    Scope
  >;
}): Socket;

makeChannel

Added in v4.0.0 Source

Creates a binary socket Channel from the Socket service in the environment.

Signature

declare function makeChannel<IE = never>(): Channel<
  readonly [Uint8Array<ArrayBufferLike>, Uint8Array<ArrayBufferLike>],
  SocketError | IE,
  void,
  readonly [
    string | Uint8Array<ArrayBufferLike> | CloseEvent,
    string | Uint8Array<ArrayBufferLike> | CloseEvent,
  ],
  IE,
  unknown,
  Socket
>;

Creates a Socket backed by a WebSocketConstructor, acquiring the WebSocket for each run and using the close-code classifier to decide which closes fail the run.

Signature

declare function makeWebSocket(
  url: string | Effect<string, never, never>,
  options?: {
    readonly closeCodeIsError?: (code: number) => boolean;
    readonly openTimeout?: Input;
    readonly protocols?: string | Array<string>;
  },
): Effect<Socket, never, WebSocketConstructor>;

Creates a binary Channel backed by a WebSocket URL, requiring a WebSocketConstructor service.

Signature

declare function makeWebSocketChannel<IE = never>(
  url: string,
  options?: {
    readonly closeCodeIsError?: (code: number) => boolean;
  },
): Channel<
  readonly [Uint8Array<ArrayBufferLike>, Uint8Array<ArrayBufferLike>],
  SocketError | IE,
  void,
  readonly [
    string | Uint8Array<ArrayBufferLike> | CloseEvent,
    string | Uint8Array<ArrayBufferLike> | CloseEvent,
  ],
  IE,
  unknown,
  WebSocketConstructor
>;

Errors

Typed error for a socket close event, carrying the close code and optional close reason.

Signature

declare class SocketCloseError extends {
  readonly _tag: "SocketCloseError";
  readonly closeReason?: string;
  readonly code: number;
} & YieldableError<this> {
  constructor(...args: [props: {
    readonly _tag?: "SocketCloseError";
    readonly closeReason?: string;
    readonly code: number;
  }, options?: MakeOptions]);
  message: string;
  static filterClean(isClean: (code: number) => boolean): <E>(u: E) => Result<SocketCloseError, E>;
}

SocketError

Added in v4.0.0 Source

Tagged error that wraps socket read, write, open, and close failures while preserving the underlying reason.

Signature

declare class SocketError extends {
  readonly _tag: "SocketError";
  readonly reason: SocketReadError | SocketWriteError | SocketOpenError | SocketCloseError;
} & YieldableError<this> {
  constructor(props: {
    readonly reason: SocketReadError | SocketWriteError | SocketOpenError | SocketCloseError;
  });
  readonly "~effect/socket/Socket/SocketError": "~effect/socket/Socket/SocketError";
  readonly message: string;
  static is(u: unknown): u is SocketError;
}

Schema for all socket-specific error reasons.

Signature

declare const SocketErrorReason: Union<
  readonly [
    typeof SocketReadError,
    typeof SocketWriteError,
    typeof SocketOpenError,
    typeof SocketCloseError,
  ]
>;

SocketErrorReason type

Added in v4.0.0 Source

Union of socket-specific read, write, open, and close error reasons.

Signature

type SocketErrorReason = SocketReadError | SocketWriteError | SocketOpenError | SocketCloseError;

Typed error for failures that occur while opening a socket, including unknown open failures and open timeouts.

Signature

declare class SocketOpenError extends {
  readonly _tag: "SocketOpenError";
  readonly cause: unknown;
  readonly kind: "Unknown" | "Timeout";
} & YieldableError<this> {
  constructor(...args: [props: {
    readonly _tag?: "SocketOpenError";
    readonly cause: unknown;
    readonly kind: "Unknown" | "Timeout";
  }, options?: MakeOptions]);
  message: "timeout waiting for \"open\"" | "An error occurred during Open";
}

Typed error for failures that occur while reading from a socket.

Signature

declare class SocketReadError extends {
  readonly _tag: "SocketReadError";
  readonly cause: unknown;
} & YieldableError<this> {
  constructor(...args: [props: {
    readonly _tag?: "SocketReadError";
    readonly cause: unknown;
  }, options?: MakeOptions]);
  readonly message: "An error occurred during Read";
}

Typed error for failures that occur while writing to a socket.

Signature

declare class SocketWriteError extends {
  readonly _tag: "SocketWriteError";
  readonly cause: unknown;
} & YieldableError<this> {
  constructor(...args: [props: {
    readonly _tag?: "SocketWriteError";
    readonly cause: unknown;
  }, options?: MakeOptions]);
  readonly message: "An error occurred during Write";
}

Guards

isCloseEvent

Added in v4.0.0 Source

Returns true when a value is a CloseEvent.

Signature

declare function isCloseEvent(u: unknown): u is CloseEvent;

isSocket

Added in v4.0.0 Source

Returns true when a value is a Socket.

Signature

declare function isSocket(u: unknown): u is Socket;

Returns true when a value is a SocketError.

Signature

declare function isSocketError(u: unknown): u is SocketError;

Layers

Layer that provides a Socket service backed by a WebSocket URL or URL effect.

Signature

declare const layerWebSocket: (
  url: string | Effect.Effect<string>,
  options?: {
    readonly closeCodeIsError?: (code: number) => boolean;
    readonly openTimeout?: Duration.Input;
    readonly protocols?: string | Array<string>;
  },
) => Layer.Layer<Socket, never, WebSocketConstructor>;

Layer that provides WebSocketConstructor using globalThis.WebSocket.

Signature

declare const layerWebSocketConstructorGlobal: Layer.Layer<WebSocketConstructor>;

Models

CloseEvent

Added in v4.0.0 Source

Represents a socket close event value carrying a close code and optional reason.

Signature

declare class CloseEvent {
  constructor(code: number, reason?: string);
  readonly "~effect/socket/Socket/CloseEvent": "~effect/socket/Socket/CloseEvent";
  readonly code: number;
  readonly reason?: string;
  toString(): string;
}

InputTransformStream interface

Added in v4.0.0 Source

Readable and writable stream pair used to adapt transform-style streams into a Socket.

Signature

interface InputTransformStream {
  readonly readable:
    | ReadableStream<Uint8Array<ArrayBufferLike>>
    | ReadableStream<string>
    | ReadableStream<string | Uint8Array<ArrayBufferLike>>;
  readonly writable: WritableStream<Uint8Array<ArrayBufferLike>>;
}

Socket interface

Added in v4.0.0 Source

Effect-based socket abstraction for running string or binary read handlers and obtaining a scoped writer for outgoing frames and close events.

Signature

interface Socket {
  readonly "~effect/socket/Socket": "~effect/socket/Socket";
  readonly run: <_, E = never, R = never>(
    handler: (_: Uint8Array) => void | Effect<_, E, R>,
    options?: {
      readonly onOpen?: Effect<void, never, never>;
    },
  ) => Effect<void, SocketError | E, R>;
  readonly runRaw: <_, E = never, R = never>(
    handler: (_: string | Uint8Array<ArrayBufferLike>) => void | Effect<_, E, R>,
    options?: {
      readonly onOpen?: Effect<void, never, never>;
    },
  ) => Effect<void, SocketError | E, R>;
  readonly runString: <_, E = never, R = never>(
    handler: (_: string) => void | Effect<_, E, R>,
    options?: {
      readonly onOpen?: Effect<void, never, never>;
    },
  ) => Effect<void, SocketError | E, R>;
  readonly writer: Effect<
    (chunk: string | Uint8Array<ArrayBufferLike> | CloseEvent) => Effect<void, SocketError>,
    never,
    Scope
  >;
}

Predicates

Default close-code classifier that treats every socket close code as an error.

Signature

declare function defaultCloseCodeIsError(_code: number): boolean;

Services

Context reference for socket send queue capacity, defaulting to 16.

Signature

declare const SendQueueCapacity: Reference<number>;

Socket

Added in v4.0.0 Source

Service tag for bidirectional socket transports.

When to use

Use to access or provide the socket implementation used by programs that read and write frames through the Effect environment.

Signature

declare const Socket: Context.Service<Socket, Socket>;

WebSocket

Added in v4.0.0 Source

Context service for the active WebSocket instance available while a WebSocket-backed socket run is handling events.

Signature

declare class WebSocket extends Shape<"~effect/socket/Socket/WebSocket", WebSocket, this> {
  constructor(_: never);
}

Context service for constructing WebSocket instances from a URL and optional protocols.

Signature

declare class WebSocketConstructor extends Shape<
  "@effect/platform/Socket/WebSocketConstructor",
  (url: string, protocols?: string | Array<string>) => WebSocket,
  this
> {
  constructor(_: never);
}

Type IDs

Runtime type identifier attached to SocketError values.

Signature

declare const SocketErrorTypeId: "~effect/socket/Socket/SocketError";

SocketErrorTypeId type

Added in v4.0.0 Source

Type-level identifier used to mark SocketError values.

Signature

type SocketErrorTypeId = "~effect/socket/Socket/SocketError";

TypeId

Added in v4.0.0 Source

Runtime type identifier attached to Socket services.

Signature

declare const TypeId: "~effect/socket/Socket";