WebSockets and streams

Serve HTTP and WebSocket together#

Use POST for finite HTTP pipelines and GET upgrades for persistent WebSocket connections. Both routes can share a path:

ts
const RpcRoutes = Layer.merge(
  PipelineServer.layerHttp({ group: AppRpcs, path: "/rpc", id: "app" }),
  PipelineServer.layerWebSocket({ group: AppRpcs, path: "/rpc", id: "app" })
).pipe(Layer.provide(AppLive))

Define a streaming RPC#

Use Effect’s standard stream definition and handler forms:

ts
import * as Stream from "effect/Stream"

const TodoRpcs = RpcGroup.make(
  Rpc.make("listTodos", { success: Schema.Array(Todo) }),
  Rpc.make("watchTodos", {
    success: TodoEvent,
    error: TodoSubscriptionError,
    stream: true
  })
)

const TodoHandlers = TodoRpcs.toLayer({
  listTodos: () => Todos.list,
  watchTodos: () => Stream.fromPubSub(TodoEvents)
})

Own the connection with a Layer#

Result-returning methods produce remote Effects. Streaming methods produce native Effect Streams. A WebSocket client owns a connection, so give it a service Layer whose scope controls that connection:

ts
import * as Socket from "effect/socket/Socket"

class TodoClient extends Context.Service<
  TodoClient,
  PipelineClient.Client<typeof TodoRpcs>
>()("app/TodoClient") {}

const TodoClientWebSocket = PipelineClient.layerClientWebSocket(
  TodoClient,
  TodoRpcs,
  { url: "ws://127.0.0.1:8787/rpc" }
).pipe(
  Layer.provide(RpcSerialization.layerJson),
  Layer.provide(Socket.layerWebSocketConstructorGlobal)
)

const program = Effect.gen(function*() {
  const rpc = yield* TodoClient
  yield* rpc.watchTodos().pipe(
    Stream.runForEach((event) => Effect.log("todo update", event))
  )
}).pipe(Effect.provide(TodoClientWebSocket))

Acquiring the Layer opens one connection. Calls, streams, and persistent capabilities share it. Releasing the Layer closes it.

Provide it at the application boundary for an application-wide connection, or inside Effect.scoped for a shorter lifetime. makeWebSocket also exposes the scoped constructor directly.

For custom socket wiring, layerWebSocket supplies Effect’s protocol and socket RPC transport. It supports multiplexing, acknowledgements, interruption, ping/pong, and reconnect policy hooks. Use layerProtocolWebSocket to supply your own Effect Socket.

Streams have an independent, backpressured lifetime and cannot be embedded in finite Pipeline.all, Pipeline.map, or Pipeline.andThen graphs.