--- name: effect-atom-rpc description: Build reactive Atom-aware RPC clients for React/Atom UIs using AtomRpc. Provides cached query atoms, invalidating mutation atoms, SSR hydration, and reactivity-key invalidation on top of an RpcGroup. --- You are an Effect TypeScript expert specializing in `effect/reactivity/AtomRpc` — the reactive RPC client for Atom-driven frontends. Baseline: `effect@4.1.7`; inspect that tag in the Effect source reference. Core reactivity APIs are `@stability unstable` and may break in minor releases. Use matching Effect-family versions; `@effect/atom-react@4.1.7` requires React 19. ## When to use this skill `AtomRpc` sits on top of an `RpcGroup` and gives you: - A `Service`-style RPC client whose dependencies are wired through an `AtomRuntime` - `client.query(tag, payload, options?)` — a cached, reactive `Atom>` - `client.mutation(tag)` — an `AtomResultFn` that runs the rpc and invalidates dependent atoms - SSR hydration via `Atom.serializable` when you pass `serializationKey` - Time-to-live caching, reactivity-key invalidation, and stream rpcs surfaced as `PullResult` atoms Use this skill when building React (or Atom-based) frontends that consume an existing `RpcGroup`. For the underlying RPC definitions, see the `effect-rpc-cluster` skill. For Atom fundamentals (`Atom.make`, `family`, `keepAlive`, `AsyncResult`, hydration), see the `effect-atom-state` skill. The underlying RPC protocols require `codecFor`. Built-in protocol layers supply it; forward it when implementing a custom transport. You can pair `RpcSerialization.layerSchemaBinary` on client/server without changing query or mutation call sites; see `effect-rpc-client` for frame limits and compatibility. Workflow proxy discard RPCs now return execution IDs, so their mutation success type is `string`. This is distinct from the client's `{ discard: true }` option. ## Effect Source Reference Query and mutation errors include client middleware errors. AtomHttpApi stream successes retain transport, decoding, and SSE failures in the stream error channel; handle them when consuming the stream. An explicit zero `timeToLive` disables default idle retention, so unmount/remount may dispose and refetch. Omission uses the registry default. HttpApi calls accept per-call `sseOptions`. - `packages/effect/src/reactivity/AtomRpc.ts` — the whole API - `packages/effect/test/reactivity/AtomRpc.test.ts` — minimal usage + serialization test - `packages/effect/src/reactivity/AtomHttpApi.ts` — the cousin pattern for `HttpApi` (same idea, same options) - `packages/effect/src/reactivity/AsyncResult.ts` — the `AsyncResult` type returned by `query` - `packages/effect/src/reactivity/Atom.ts` — `runtime`, `family`, `serializable`, `keepAlive`, `setIdleTTL` - `packages/effect/src/reactivity/Hydration.ts` — SSR dehydrate/hydrate helpers - `packages/effect/src/reactivity/Reactivity.ts` — the `Reactivity` service that powers reactivity keys ## Imports ```ts import { AsyncResult, Atom, AtomRpc, Hydration, Reactivity } from 'effect/reactivity'; import { RpcClient, RpcSerialization } from 'effect/rpc'; import { FetchHttpClient } from 'effect/http'; import { useAtomValue, useAtomSet } from '@effect/atom-react'; ``` ## Core idea `AtomRpc.Service()(id, options)` produces a `Context.Service` subclass whose service value is an `RpcClient.RpcClient.Flat` (the `flatten: true` form of the RPC client — single function `(tag, payload, options?)`). It also attaches three things to the class itself: ```ts class UsersClient extends AtomRpc.Service()('UsersClient', { ... }) { // inherited from AtomRpc.Service: static readonly runtime: Atom.AtomRuntime; static query: (tag, payload, options?) => Atom> | Atom.Writable, void>; static mutation: (tag) => Atom.AtomResultFn<{ payload, headers?, reactivityKeys? }, ..., ...>; } ``` The `runtime` is what powers `query` and `mutation` — internally it builds a `Layer` that runs the RPC client effect and threads the protocol layer in. You don't usually touch `runtime` directly; React components use `query` / `mutation` via Atom hooks. ## Defining an AtomRpc client ```ts import { Layer } from 'effect'; import { AtomRpc } from 'effect/reactivity'; import { FetchHttpClient } from 'effect/http'; import { RpcClient, RpcSerialization } from 'effect/rpc'; import { UsersGroup } from '../shared/users-rpc.ts'; export class UsersClient extends AtomRpc.Service()('UsersClient', { group: UsersGroup, protocol: RpcClient.layerProtocolHttp({ url: '/api/rpc' }).pipe( Layer.provide(RpcSerialization.layerJson), Layer.provide(FetchHttpClient.layer) ) }) {} ``` Required: `group` and `protocol`. `protocol` accepts either a `Layer` or a function `(get: AtomContext) => Layer`. The function form lets the protocol layer read other atoms — for example, take the current auth token from a `tokenAtom` and bake it into the HTTP client: ```ts export class UsersClient extends AtomRpc.Service()('UsersClient', { group: UsersGroup, protocol: (get) => Layer.unwrap( Effect.gen(function*() { const token = get(tokenAtom); return RpcClient.layerProtocolHttp({ url: '/api/rpc', transformClient: HttpClient.mapRequest( HttpClientRequest.setHeader('authorization', `Bearer ${token}`) ) }); }) ) }) {} ``` Optional config: ```ts AtomRpc.Service()('UsersClient', { group: UsersGroup, protocol: ProtocolLayer, spanPrefix: 'UsersClient', spanAttributes: { app: 'admin-ui' }, disableTracing: false, generateRequestId: customRequestIdFactory, // for deterministic IDs in tests makeEffect: undefined, // override the default RpcClient.make runtime: Atom.runtime // override with another factory, e.g. Atom.context() }); ``` `makeEffect` is mainly for testing — instead of building a real `RpcClient` from `protocol`, supply an Effect returning a fully typed flat client for the group. Do not cast a partial function to `any`; that hides missing methods, payload mistakes, and wrong result/error types. Default RPC span names are the method name alone in 4.1.0. An explicit `spanPrefix` retains a client-specific prefix. Client/server span kinds and `rpc.system.name` / `rpc.method` attributes identify the transport operation. ## `query` — cached reactive reads ```ts client.query(tag, payload, options?) => non-stream → Atom> stream → Atom.Writable, void> ``` Query atoms are **cached by request key** — calling `query('GetUser', { id: '1' })` from many components returns the *same* atom, so the rpc fires once and shares the result. The key also includes headers, reactivity keys, TTL, and serialization key. Use matching options to share a cache entry. Union-of-tag arguments retain the selected RPCs' payload/result types; they no longer collapse to `never`. Narrow the tag when application logic needs to pair a particular payload with its result. Effect v4 query wrappers preserve serialization and retention metadata while adding reactivity. It is therefore safe to combine `reactivityKeys`, `serializationKey`, and `timeToLive`; hydration identity and idle retention are not discarded by the reactive wrapper. ```tsx import { useAtomValue } from '@effect/atom-react'; function UserProfile({ id }: { id: string }) { const result = useAtomValue( UsersClient.query('GetUser', { id }, { timeToLive: '30 seconds', serializationKey: `user-${id}`, reactivityKeys: ['users', `user-${id}`] }) ); return AsyncResult.builder(result) .onWaiting(() => ) .onError((error) => ) .onSuccess((user) => ) .render(); } ``` ### Query options ```ts client.query(tag, payload, { headers?: Headers.Input, // per-call headers reactivityKeys?: Reactivity.KeysInput, // invalidation keys timeToLive?: Duration.Input, // cache lifetime; idle eviction staleTime?: Duration.Input, // fresh-result window (non-stream RPC) serializationKey?: string // makes the atom hydration-friendly }); ``` - **`reactivityKeys`** — keys this atom listens to. When a `mutation` (or any `Reactivity.invalidate`) fires with overlapping keys, this atom re-fetches. - **`timeToLive`** — idle retention via `Atom.setIdleTTL`. A finite duration permits disposal after inactivity; `Duration.infinity` uses `Atom.keepAlive` until the registry is reset/disposed. Omission uses the registry default, while explicit zero bypasses default idle retention. - **`staleTime`** — opt into stale-while-revalidate for a non-stream RPC or an HTTP query. A fresh result is reused on mount; a stale one is refreshed. Manual refresh and invalidation still fetch. Stream RPC queries ignore it. - **`serializationKey`** — for non-stream queries, a stable key opts the atom into `Atom.serializable` keyed by `AtomRpc:${tag}:${serializationKey}`. Without a `serializationKey`, the query atom is cached for the current registry but is not serializable/hydratable, so SSR clients will fetch again. Stream rpcs cannot be serializable. ### Stream rpcs When the rpc has `stream: true`, `query` returns an `Atom.Writable, void>` instead of `Atom>`: ```tsx const messageAtom = ChatClient.query('Subscribe', { roomId: 'r1' }); function Messages() { const result = useAtomValue(messageAtom); const pullNext = useAtomSet(messageAtom); return AsyncResult.matchWithWaiting(result, { onWaiting: () => , onError: (error) => , onDefect: (defect) => , onSuccess: (success) => ( pullNext()} /> ) }); } ``` `PullResult` is an `AsyncResult<{ done: boolean; items: NonEmptyArray }, E | NoSuchElementError>`. The `waiting` flag is top-level on the `AsyncResult`; `items` and `done` live under the success `value`. Use `Atom.runtime.pull` semantics — write `void` to request the next chunk. ## `mutation` — invalidating writes ```ts client.mutation(tag) => Atom.AtomResultFn< { payload, headers?, reactivityKeys? }, Success, Error | RpcClientError | MiddlewareError >; ``` ```tsx import { useAtomSet } from '@effect/atom-react'; function CreateUserButton() { const createUser = useAtomSet(UsersClient.mutation('CreateUser')); return ( ); } ``` Calling the returned function: - Runs the rpc with the given `payload` and optional `headers` - After success, fires `Reactivity.invalidate(reactivityKeys)`, causing matching `query` atoms to re-fetch - Returns nothing (the result is reflected via the mutation atom's own `AsyncResult` state) The mutation atom is serializable under ``AtomRpc:mutation:${JSON.stringify([id, tag])}``, where `id` is the service ID. Use unique IDs for distinct clients so results cannot collide during hydration. This differs from the old tag-only mutation key; query keys are unchanged. ### Mutation options ```ts mutation({ payload: Rpc.PayloadConstructor, // required; constructed via the rpc payload schema headers?: Headers.Input, // per-call headers reactivityKeys?: Reactivity.KeysInput // keys to invalidate after success }); ``` Stream rpcs are **not** valid mutation targets. Use `query` for streams. ## Reactivity keys Two equivalent ways to declare keys: ```ts // Plain array → all keys map to the global namespace reactivityKeys: ['users', 'user-1']; // Record → keys are scoped to namespaces (useful for cross-cutting domains) reactivityKeys: { users: ['user-1', 'user-2'], tenants: ['t1'] } ``` A `query` re-fires when *any* of its declared keys appears in an invalidation event. The matching is structural — if two atoms both list `'user-1'`, mutating with `reactivityKeys: ['user-1']` invalidates both. For more advanced invalidation patterns (e.g., conditional invalidation, debounced invalidation), use `Reactivity.invalidate(keys)` and `Reactivity.mutation(effect, keys)` directly inside Atom-runtime effects. In 4.1.0, applications can augment `Keys` in `effect/reactivity/Reactivity` to declare names and record-ID types, for example `interface Keys { readonly users: string; readonly events: never }`. Then `{ users: ['u1'] }` and `['events']` are accepted, but undeclared names and numeric user IDs are rejected. `never` marks an array-only key. With no augmentation, array/record inputs remain permissive. **Libraries must not augment this global interface**; service-instance methods remain permissive for runtime-only keys. One invalidation runs a handler once even when several keys overlap. `Reactivity.query` terminates on failure and drops pending reruns; later invalidations do not revive that failed queue. Recover within the query or reacquire it at an owning boundary when that behavior is intended. ## SSR hydration Hydration uses `Atom.serializable` (which `query` opts into when you pass `serializationKey`): ```ts // --- server: render then dehydrate --- import { Effect } from 'effect'; import { AtomRegistry, Hydration } from 'effect/reactivity'; const dehydrated = yield* Effect.scoped(Effect.gen(function* () { const registry = yield* Effect.acquireRelease( Effect.sync(() => AtomRegistry.make()), (registry) => Effect.sync(() => registry.dispose()) ); const userAtom = UsersClient.query('GetUser', { id: 'u1' }, { serializationKey: 'u1' }); yield* AtomRegistry.mount(registry, userAtom); yield* AtomRegistry.getResult(registry, userAtom); return Hydration.toValues(Hydration.dehydrate(registry)); })); // dehydrated is a JSON-safe array of { key, value } pairs to inline in the HTML ``` ```tsx // --- client: hydrate before rendering --- import { AtomRegistry, Hydration } from 'effect/reactivity'; import { RegistryContext } from '@effect/atom-react'; const registry = AtomRegistry.make(); Hydration.hydrate(registry, dehydratedFromServer); ; ``` Stream rpcs are not serializable — only non-stream `query` atoms with a stable `serializationKey` can be dehydrated and hydrated. Hydration provides initial UI data, not a promise of no client request. By default hydrated effect/stream atoms run on mount to establish dependencies. `Atom.serializable(..., { key, schema, skipInitialRun: true })` can opt out on atoms you configure directly; a serializable RPC query with `staleTime` sets this automatically. An `Initial` or waiting seed still runs. Invalid serialized schema data falls back to client computation, and older dehydrated AsyncResults do not replace newer client results. See `effect-atom-state` for seed and refresh rules. ## Custom runtime `AtomRpc.Service` accepts a `runtime` factory option. The default is `Atom.runtime`. Override it when you want all the atoms produced by this client to share a custom reactivity scope, registry, or annotation: ```ts const myRuntime = Atom.context(); export class UsersClient extends AtomRpc.Service()('UsersClient', { group: UsersGroup, protocol: ProtocolLayer, runtime: myRuntime }) {} ``` `withReactivity(keys)` decorates an atom; it is not a runtime factory. Use `reactivityKeys` on queries/mutations for invalidation. Runtime factories use registry-scoped layer memoization by default; provide the same registry to components that should share state. ## End-to-end example ```ts // --- shared/users-rpc.ts --- import { Schema } from 'effect'; import { Rpc, RpcGroup } from 'effect/rpc'; export class User extends Schema.Class('User')({ id: Schema.String, name: Schema.String, email: Schema.String }) {} export class UserNotFound extends Schema.Error('UserNotFound')({ _tag: Schema.tag('UserNotFound'), id: Schema.String }) {} export const GetUser = Rpc.make('GetUser', { payload: { id: Schema.String }, success: User, error: UserNotFound }); export const ListUsers = Rpc.make('ListUsers', { success: Schema.Array(User) }); export const CreateUser = Rpc.make('CreateUser', { payload: { name: Schema.String, email: Schema.String }, success: User }); export const UsersGroup = RpcGroup.make(GetUser, ListUsers, CreateUser); ``` ```ts // --- frontend/clients/users-client.ts --- import { Layer } from 'effect'; import { FetchHttpClient } from 'effect/http'; import { AtomRpc } from 'effect/reactivity'; import { RpcClient, RpcSerialization } from 'effect/rpc'; import { UsersGroup } from '../../shared/users-rpc.ts'; export class UsersClient extends AtomRpc.Service()('UsersClient', { group: UsersGroup, protocol: RpcClient.layerProtocolHttp({ url: '/api/rpc' }).pipe( Layer.provide(RpcSerialization.layerJson), Layer.provide(FetchHttpClient.layer) ), spanPrefix: 'UsersClient' }) {} ``` ```tsx // --- frontend/components/UserList.tsx --- import { useAtomValue, useAtomSet } from '@effect/atom-react'; import { AsyncResult } from 'effect/reactivity'; import { UsersClient } from '../clients/users-client'; export function UserList() { const users = useAtomValue( UsersClient.query('ListUsers', undefined, { timeToLive: '1 minute', reactivityKeys: ['users'], serializationKey: 'all' }) ); const createUser = useAtomSet(UsersClient.mutation('CreateUser')); const onAdd = () => createUser({ payload: { name: 'New user', email: 'new@example.com' }, reactivityKeys: ['users'] }); return ( <> {AsyncResult.builder(users) .onWaiting(() =>

Loading…

) .onError((err) =>

Error: {String(err)}

) .onSuccess((list) => (
    {list.map((u) =>
  • {u.name}
  • )}
)) .render()} ); } ``` ```tsx // --- frontend/components/UserDetail.tsx --- export function UserDetail({ id }: { id: string }) { const user = useAtomValue( UsersClient.query('GetUser', { id }, { timeToLive: '30 seconds', reactivityKeys: ['users', `user-${id}`], serializationKey: `user-${id}` }) ); return AsyncResult.builder(user) .onWaiting(() => ) .onErrorTag('UserNotFound', (err) => ) .onError((err) => ) .onSuccess((u) => ) .render(); } ``` ## Sibling: `AtomHttpApi` If your backend exposes an `HttpApi` instead of an `RpcGroup`, `AtomHttpApi.Service()(id, options)` is the same idea applied to `HttpApiGroup`/`HttpApiEndpoint`: ```ts import { AtomHttpApi } from 'effect/reactivity'; class ApiClient extends AtomHttpApi.Service()('ApiClient', { api: MyHttpApi, httpClient: FetchHttpClient.layer, baseUrl: '/api' }) {} ApiClient.query('users', 'getById', { params: { id: 'u1' }, timeToLive: '30 seconds', reactivityKeys: ['users', 'user-u1'], serializationKey: 'user-u1' }); const updateUser = useAtomSet(ApiClient.mutation('users', 'update')); ``` The `query`/`mutation` arguments differ (you pass `groupName, endpointName, request` because HttpApi has groups). Non-stream `AtomHttpApi.query` atoms are serializable only in decoded-only mode **and** when you provide a stable `serializationKey`; query hydration keys use `AtomHttpApi:${group}:${endpoint}:${serializationKey}`. Decoded-only AtomHttpApi query/mutation serialization uses endpoint + endpoint-middleware wire error schemas; do not document client-only middleware errors as serialized failures. `AtomHttpApi` error types follow the `HttpApiClient` endpoint shape: endpoint decoded errors, endpoint middleware errors, and client middleware errors. With `responseMode: 'response-only'`, endpoint decoded errors are excluded because the caller receives the raw response, but endpoint middleware and client middleware errors remain typed failures. Low-level `HttpClientError` and `SchemaError` are raised as defects by the AtomHttpApi runtime. Omitting `responseMode` infers decoded-only success; an explicit literal or union mode retains the corresponding decoded value, raw response, or paired success shape. Decoded-only mutation serialization keys are now ``AtomHttpApi:mutation:${JSON.stringify([id, group, endpoint])}``; use unique service IDs just as with AtomRpc. Query serialization keys have not changed. ## Anti-patterns 1. **Re-creating the client on every render.** `AtomRpc.Service` produces a *singleton* class — define it once at module scope and import. Constructing it inside a component creates a new runtime per render. 2. **Forgetting `serializationKey` for hydration.** Without it, SSR-rendered data is not transferred to the client. Add a stable key; hydrated queries still run on mount by default. 3. **Using `query` for an action.** Queries are cached and may run more than once due to subscription churn. Use `mutation` for any side-effectful or state-changing call. 4. **Forgetting `reactivityKeys` on mutations.** A mutation that doesn't list keys won't invalidate any queries — the UI will look stale until the user refreshes. 5. **Trying to make a stream rpc serializable.** Not supported — `serializationKey` is silently ignored on streams. 6. **Overlapping reactivity keys without intent.** A widely-used key like `['users']` invalidates *every* user query. Scope keys narrowly (`['user-${id}']`) when only one entry changes; use the broad key only when a list-level refresh is intended. 7. **Assuming every error has `_tag`.** The failure channel includes declared RPC errors, RPC middleware wire errors, and `RpcClientError` transport faults. When you model errors as tagged schemas, use `.onErrorTag(...)` or check `_tag`; otherwise handle by schema/predicate with `.onError(...)` / `.onErrorIf(...)`. 8. **Mixing `Atom.runtime` factories.** If you specify a custom `runtime` for `AtomRpc.Service`, use it consistently across related queries; mixing runtimes scopes reactivity differently and breaks invalidation. ## Rules - Define the `RpcGroup` in a shared module; the same `UsersGroup` powers `RpcServer`, `RpcClient`, and `AtomRpc.Service`. - One `AtomRpc.Service` class per logical client; module-singleton, never per-component. - Always pass `reactivityKeys` to mutations so dependent queries refresh. - Pass `serializationKey` to every query you want SSR-hydratable. - Pick idle `timeToLive` deliberately; omit for registry defaults, zero to bypass default idle retention, or `Duration.infinity` to retain until registry disposal. - Use `AsyncResult.builder(...).onWaiting(...).onError(...).onSuccess(...)` (or `AsyncResult.matchWithWaiting`) to render — never check `.waiting` and `.error` ad-hoc. Reserve `.onFailure((cause) => ...)` for whole-`Cause` fallbacks after typed error branches. - For protocol layers that depend on auth tokens or other reactive state, use the `(get) => Layer` form of `protocol` so the client rebuilds when those atoms change. - For typed error recovery, handle declared RPC errors, RPC middleware wire errors, and `RpcClientError`; branch on `_tag` only when the relevant errors are tagged. - Cross-link to `effect-atom-state` for atom-side patterns; this skill covers only the RPC bridge.