Open History to see the last commit
1import type { QueryPersistence } from "./queryPersistence.ts";
2import { createCommandPermissions } from "./commandPermissions.ts";
3import { followStreamInEnvironment } from "./environmentStreams.ts";
4import { reuseUnchanged } from "./serverConfigProjection.ts";
5export { runStreamInEnvironment, followStreamInEnvironment } from "./environmentStreams.ts";
6import {
7 type ClientGuardedRpcTag,
8 EnvironmentId,
9 type EnvironmentId as EnvironmentIdType,
10} from "@t3tools/contracts";
11import * as Cause from "effect/Cause";
12import * as Effect from "effect/Effect";
13import * as Exit from "effect/Exit";
14import * as Option from "effect/Option";
15import * as Schema from "effect/Schema";
16import * as Stream from "effect/Stream";
17import * as SubscriptionRef from "effect/SubscriptionRef";
18import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
19
20import type { ConnectionAttemptError, SupervisorConnectionState } from "../connection/model.ts";
21import * as EnvironmentRegistry from "../connection/registry.ts";
22import {
23 type EnvironmentRpcInput,
24 type EnvironmentRpcSuccess,
25 type EnvironmentRpcFailure,
26 type EnvironmentRpcStreamFailure,
27 type EnvironmentRpcStreamValue,
28 type EnvironmentSubscriptionRpcTag,
29 type EnvironmentUnaryRpcTag,
30 EnvironmentRpcUnavailableError,
31 request,
32 requestGuarded,
33 RpcPermissionGuard,
34 subscribe,
35} from "../rpc/client.ts";
36import * as EnvironmentSupervisor from "../connection/supervisor.ts";
37import type * as RpcSession from "../rpc/session.ts";
38
39const isEnvironmentRpcUnavailable = Schema.is(EnvironmentRpcUnavailableError);
40
41/**
42 * Holds back the unavailable failure of a query whose session went away. The
43 * query atom reruns when it sees that session change, so settling first would
44 * show a failure for a query that is about to retry. While `session` is still
45 * current no rerun is coming, and the failure stands.
46 */
47const pendingOnceSessionReplaced =
48 (session: RpcSession.RpcSession) =>
49 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
50 effect.pipe(
51 // The query's error type is generic, so its tags are unknown to `catchTags`.
52 Effect.catchIf(isEnvironmentRpcUnavailable, (error) =>
53 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
54 Effect.flatMap((supervisor) => SubscriptionRef.get(supervisor.session)),
55 Effect.flatMap((current) =>
56 Option.isSome(current) && current.value === session ? Effect.fail(error) : Effect.never,
57 ),
58 ),
59 ),
60 );
61
62interface EnvironmentAtomOptions<Input, A, E, R> {
63 readonly label: string;
64 readonly execute: (input: Input) => Effect.Effect<A, E, R>;
65 readonly scheduler?: AtomCommandScheduler;
66 readonly concurrency?: AtomCommandConcurrency<{
67 readonly environmentId: EnvironmentIdType;
68 readonly input: Input;
69 }>;
70}
71
72interface EnvironmentCommandAtomOptions<Input, A, E, R> extends Omit<
73 EnvironmentAtomOptions<Input, A, E, R>,
74 "execute"
75> {
76 readonly execute: (
77 input: Input,
78 registry: AtomRegistry.AtomRegistry,
79 environmentId: EnvironmentIdType,
80 ) => Effect.Effect<A, E, R>;
81}
82
83interface EnvironmentQueryAtomOptions<Input, A, E, R> extends Omit<
84 EnvironmentAtomOptions<Input, A, E, R>,
85 "execute"
86> {
87 /**
88 * `emit` shows a provisional value while the query keeps waiting. The settled
89 * result replaces it, so catch failures that should keep it on screen.
90 */
91 readonly execute: (
92 input: Input,
93 emit: (value: A) => Effect.Effect<void>,
94 ) => Effect.Effect<A, E, R>;
95 readonly persistence?: QueryPersistence<A>;
96 readonly staleTimeMs?: number;
97 readonly idleTtlMs?: number;
98 readonly refreshIntervalMs?: number;
99 readonly refreshTrigger?: (target: {
100 readonly environmentId: EnvironmentIdType;
101 readonly input: Input;
102 }) => Atom.Atom<unknown> | undefined;
103 readonly isFinal?: (value: A) => boolean;
104 /**
105 * Runs where each server answer lands, before readers see it, so derived records (summaries,
106 * snapshots, watches) come from the producer instead of from components watching the data.
107 * Cached and emitted provisional values are not answers.
108 */
109 readonly onAnswer?: QueryAnswerHandler<Input, A>;
110}
111
112export type QueryAnswerHandler<Input, A> = (
113 target: { readonly environmentId: EnvironmentIdType; readonly input: Input },
114 value: A,
115 registry: AtomRegistry.AtomRegistry,
116) => Effect.Effect<void>;
117
118interface EnvironmentSubscriptionAtomOptions<Input, A, E, R> {
119 readonly sensitiveInput?: boolean;
120 readonly label: string;
121 readonly subscribe: (input: Input) => Stream.Stream<A, E, R>;
122 readonly completeWhen?: (value: A) => boolean;
123 readonly idleTtlMs?: number;
124}
125
126export type SettledAsyncResult<A, E> = AsyncResult.Success<A, E> | AsyncResult.Failure<A, E>;
127
128export type AtomCommandResult<A, E> = SettledAsyncResult<A, E>;
129
130export type AtomCommandSuccess<R> = R extends AtomCommandResult<infer A, infer _E> ? A : never;
131
132export type AtomCommandFailure<R> = R extends AtomCommandResult<infer _A, infer E> ? E : never;
133
134export interface AtomCommandOptions {
135 readonly label?: string;
136 readonly reportFailure?: boolean;
137 readonly reportDefect?: boolean;
138}
139
140export interface AtomCommandReporter {
141 readonly warn: (message: string, cause: Cause.Cause<unknown>) => void;
142 readonly error: (message: string, cause: Cause.Cause<unknown>) => void;
143}
144
145export interface AtomCommand<W, A, E> {
146 readonly label: string;
147 readonly run: (registry: AtomRegistry.AtomRegistry, input: W) => Promise<AtomCommandResult<A, E>>;
148}
149
150export type AtomCommandConcurrency<W> =
151 | { readonly mode: "parallel" }
152 | {
153 readonly mode: "serial" | "singleFlight" | "latest";
154 readonly key: (input: W) => string;
155 };
156
157interface AtomCommandSchedulerState {
158 readonly serial: Map<string, Promise<unknown>>;
159 readonly singleFlight: Map<string, Promise<unknown>>;
160 readonly latest: Map<string, AtomCommandLatestLane>;
161}
162
163interface AtomCommandLatestBatch {
164 execute: () => Promise<AtomCommandResult<unknown, unknown>>;
165 readonly resolve: Array<(result: AtomCommandResult<unknown, unknown>) => void>;
166}
167
168interface AtomCommandLatestLane {
169 running: boolean;
170 pending: AtomCommandLatestBatch | undefined;
171}
172
173export interface AtomCommandScheduler {
174 readonly schedule: <W, A, E>(
175 registry: AtomRegistry.AtomRegistry,
176 concurrency: AtomCommandConcurrency<W>,
177 input: W,
178 execute: () => Promise<AtomCommandResult<A, E>>,
179 ) => Promise<AtomCommandResult<A, E>>;
180}
181
182async function settleAtomCommandResult<A, E>(
183 execute: () => Promise<AtomCommandResult<A, E>>,
184): Promise<AtomCommandResult<A, E>> {
185 try {
186 return await execute();
187 } catch (defect) {
188 return AsyncResult.failure(Cause.die(defect));
189 }
190}
191
192export function createAtomCommandScheduler(): AtomCommandScheduler {
193 const registryStates = new WeakMap<AtomRegistry.AtomRegistry, AtomCommandSchedulerState>();
194
195 const stateFor = (registry: AtomRegistry.AtomRegistry): AtomCommandSchedulerState => {
196 const existing = registryStates.get(registry);
197 if (existing !== undefined) {
198 return existing;
199 }
200 const state: AtomCommandSchedulerState = {
201 serial: new Map(),
202 singleFlight: new Map(),
203 latest: new Map(),
204 };
205 registryStates.set(registry, state);
206 return state;
207 };
208
209 return {
210 schedule: <W, A, E>(
211 registry: AtomRegistry.AtomRegistry,
212 concurrency: AtomCommandConcurrency<W>,
213 input: W,
214 execute: () => Promise<AtomCommandResult<A, E>>,
215 ): Promise<AtomCommandResult<A, E>> => {
216 if (concurrency.mode === "parallel") {
217 return execute();
218 }
219
220 const key = concurrency.key(input);
221 const state = stateFor(registry);
222 if (concurrency.mode === "singleFlight") {
223 const existing = state.singleFlight.get(key) as
224 | Promise<AtomCommandResult<A, E>>
225 | undefined;
226 if (existing !== undefined) {
227 return existing;
228 }
229 const current = execute();
230 state.singleFlight.set(key, current);
231 void current.then(
232 () => {
233 if (state.singleFlight.get(key) === current) {
234 state.singleFlight.delete(key);
235 }
236 },
237 () => {
238 if (state.singleFlight.get(key) === current) {
239 state.singleFlight.delete(key);
240 }
241 },
242 );
243 return current;
244 }
245
246 if (concurrency.mode === "serial") {
247 const previous = state.serial.get(key);
248 const current = previous === undefined ? execute() : previous.then(execute, execute);
249 state.serial.set(key, current);
250 void current.then(
251 () => {
252 if (state.serial.get(key) === current) {
253 state.serial.delete(key);
254 }
255 },
256 () => {
257 if (state.serial.get(key) === current) {
258 state.serial.delete(key);
259 }
260 },
261 );
262 return current;
263 }
264
265 let lane = state.latest.get(key);
266 if (lane === undefined) {
267 lane = { running: false, pending: undefined };
268 state.latest.set(key, lane);
269 }
270 const activeLane = lane;
271
272 const result = new Promise<AtomCommandResult<A, E>>((resolve) => {
273 if (activeLane.pending === undefined) {
274 activeLane.pending = {
275 execute: execute as () => Promise<AtomCommandResult<unknown, unknown>>,
276 resolve: [resolve as (result: AtomCommandResult<unknown, unknown>) => void],
277 };
278 return;
279 }
280 activeLane.pending.execute = execute as () => Promise<AtomCommandResult<unknown, unknown>>;
281 activeLane.pending.resolve.push(
282 resolve as (result: AtomCommandResult<unknown, unknown>) => void,
283 );
284 });
285
286 if (!activeLane.running) {
287 activeLane.running = true;
288 void (async () => {
289 while (activeLane.pending !== undefined) {
290 const batch = activeLane.pending;
291 activeLane.pending = undefined;
292 let batchResult: AtomCommandResult<unknown, unknown>;
293 try {
294 batchResult = await batch.execute();
295 } catch (defect) {
296 batchResult = AsyncResult.failure(Cause.die(defect));
297 }
298 for (const resolve of batch.resolve) {
299 resolve(batchResult);
300 }
301 }
302 activeLane.running = false;
303 if (state.latest.get(key) === activeLane) {
304 state.latest.delete(key);
305 }
306 })();
307 }
308
309 return result;
310 },
311 };
312}
313
314export const scheduleAtomCommandEffect =
315 /* Every atom command passes through this scheduler; the command owns its tracing boundary. */
316 Effect.fnUntraced(function* <W, A, E, R>(
317 registry: AtomRegistry.AtomRegistry,
318 scheduler: AtomCommandScheduler,
319 concurrency: AtomCommandConcurrency<W>,
320 input: W,
321 effect: Effect.Effect<A, E, R>,
322 ): Effect.fn.Return<A, E, R> {
323 const context = yield* Effect.context<R>();
324 const result = yield* Effect.promise((signal) =>
325 scheduler.schedule<W, A, E>(registry, concurrency, input, async () => {
326 const exit = await Effect.runPromiseExitWith(context)(effect, { signal });
327 return Exit.isSuccess(exit)
328 ? AsyncResult.success(exit.value)
329 : AsyncResult.failure(exit.cause);
330 }),
331 );
332 return result._tag === "Success" ? result.value : yield* Effect.failCause(result.cause);
333 });
334
335export async function runAtomCommand<W, A, E>(
336 registry: AtomRegistry.AtomRegistry,
337 command: AtomCommand<W, A, E>,
338 input: W,
339 options: AtomCommandOptions = {},
340 reporter: AtomCommandReporter = console,
341): Promise<AtomCommandResult<A, E>> {
342 const result = await settleAtomCommandResult(() => command.run(registry, input));
343 reportAtomCommandResult(result, { ...options, label: options.label ?? command.label }, reporter);
344 return result;
345}
346
347export function mapAtomCommandResult<A, E, B>(
348 result: AtomCommandResult<A, E>,
349 map: (value: A) => B,
350): AtomCommandResult<B, E> {
351 return result._tag === "Success"
352 ? AsyncResult.success(map(result.value))
353 : AsyncResult.failure(result.cause);
354}
355
356export function isAtomCommandInterrupted(result: AtomCommandResult<unknown, unknown>): boolean {
357 return result._tag === "Failure" && Cause.hasInterruptsOnly(result.cause);
358}
359
360export function squashAtomCommandFailure(result: {
361 readonly cause: Cause.Cause<unknown>;
362}): unknown {
363 return Cause.squash(result.cause);
364}
365
366export async function settleAsyncResult<A, E>(
367 execute: () => Promise<Exit.Exit<A, E>>,
368): Promise<SettledAsyncResult<A, E>> {
369 try {
370 return AsyncResult.fromExit(await execute());
371 } catch (defect) {
372 return AsyncResult.failure(Cause.die(defect));
373 }
374}
375
376export async function executeAtomCommand<A, E>(
377 execute: () => Promise<Exit.Exit<A, E>>,
378 options: AtomCommandOptions = {},
379 reporter: AtomCommandReporter = console,
380): Promise<AtomCommandResult<A, E>> {
381 const result = await settleAsyncResult(execute);
382 reportAtomCommandResult(result, options, reporter);
383 return result;
384}
385
386export interface AtomQueryOptions extends AtomCommandOptions {
387 /**
388 * Force a fresh execution instead of accepting a value the atom already
389 * holds (e.g. an SWR-cached result within its stale window). Used by
390 * verification flows where a cached failure must not satisfy a retry.
391 */
392 readonly refresh?: boolean;
393 readonly signal?: AbortSignal;
394}
395
396export async function executeAtomQuery<A, E>(
397 registry: AtomRegistry.AtomRegistry,
398 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
399 options: AtomQueryOptions = {},
400 reporter: AtomCommandReporter = console,
401): Promise<AtomCommandResult<A, E>> {
402 const query = Effect.scoped(
403 Effect.gen(function* () {
404 yield* AtomRegistry.mount(registry, atom);
405 if (options.refresh) {
406 yield* Effect.sync(() => {
407 const current = registry.get(atom);
408 if (current._tag !== "Initial" && !current.waiting) {
409 registry.refresh(atom);
410 }
411 });
412 }
413 return yield* AtomRegistry.getResult(registry, atom, {
414 suspendOnWaiting: true,
415 });
416 }),
417 );
418 return executeAtomCommand(
419 () => Effect.runPromiseExit(query, { signal: options.signal }),
420 options,
421 reporter,
422 );
423}
424
425export function createRuntimeCommand<R, ER, W, A, E>(
426 runtime: Atom.AtomRuntime<R, ER>,
427 options: {
428 readonly label: string;
429 readonly execute: (input: W, registry: AtomRegistry.AtomRegistry) => Effect.Effect<A, E, R>;
430 readonly scheduler?: AtomCommandScheduler;
431 readonly concurrency?: AtomCommandConcurrency<W>;
432 },
433): AtomCommand<W, A, E | ER> {
434 const scheduler = options.scheduler ?? createAtomCommandScheduler();
435 const concurrency = options.concurrency ?? { mode: "parallel" as const };
436 return {
437 label: options.label,
438 run: (registry, input) =>
439 settleAtomCommandResult(() =>
440 scheduler.schedule(registry, concurrency, input, () => {
441 const atom = runtime
442 .atom(options.execute(input, registry))
443 .pipe(Atom.withLabel(options.label));
444 return executeAtomQuery(registry, atom, { reportDefect: false, reportFailure: false });
445 }),
446 ),
447 };
448}
449
450export function reportAtomCommandResult(
451 result: AtomCommandResult<unknown, unknown>,
452 options: AtomCommandOptions = {},
453 reporter: AtomCommandReporter = console,
454): void {
455 if (AsyncResult.isSuccess(result) || Cause.hasInterruptsOnly(result.cause)) {
456 return;
457 }
458
459 const label = options.label ?? "atom command";
460 if (Cause.hasDies(result.cause)) {
461 if (options.reportDefect ?? true) {
462 reporter.error(`[atom-command] ${label} defected`, result.cause);
463 }
464 } else if (options.reportFailure ?? true) {
465 reporter.warn(`[atom-command] ${label} failed`, result.cause);
466 }
467}
468
469export async function settlePromise<A>(
470 execute: () => Promise<A>,
471): Promise<AtomCommandResult<A, never>> {
472 try {
473 return AsyncResult.success(await execute());
474 } catch (defect) {
475 return AsyncResult.failure(Cause.die(defect));
476 }
477}
478
479export function environmentRpcKey<Input>(target: {
480 readonly environmentId: EnvironmentIdType;
481 readonly input: Input;
482}): string {
483 return JSON.stringify([target.environmentId, target.input]);
484}
485
486function parseEnvironmentRpcKey<Input>(key: string): {
487 readonly environmentId: EnvironmentIdType;
488 readonly input: Input;
489} {
490 const decoded = JSON.parse(key) as [EnvironmentIdType, Input];
491 return {
492 environmentId: EnvironmentId.make(decoded[0]),
493 input: decoded[1],
494 };
495}
496
497function runInEnvironment<A, E, R>(
498 environmentId: EnvironmentIdType,
499 effect: Effect.Effect<A, E, R>,
500): Effect.Effect<
501 A,
502 E | EnvironmentRegistry.EnvironmentNotRegisteredError,
503 EnvironmentRegistry.EnvironmentRegistry | Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>
504> {
505 return EnvironmentRegistry.EnvironmentRegistry.pipe(
506 Effect.flatMap((registry) => registry.run(environmentId, effect)),
507 );
508}
509
510/**
511 * `Atom.makeRefreshOnSignal` subscribes to the signal, so a query that outlives its view on an
512 * idle TTL still re-runs on every change. Reading the signal as a dependency instead lets the
513 * registry re-run a mounted query right away and only mark an idle one stale, which then
514 * refreshes on its next read.
515 */
516const refreshOnSignalWhileRead =
517 <V>(signal: Atom.Atom<unknown>, isFinal: (value: V) => boolean) =>
518 <A extends V>(self: Atom.Atom<A>): Atom.Atom<A> => {
519 // The signal value each registry's data was read under. Held outside the node because the
520 // registry can sweep this node while `self` keeps the data, and the rebuilt node must still
521 // see a change it missed.
522 const readUnder = new WeakMap<AtomRegistry.AtomRegistry, unknown>();
523 return Atom.transform(
524 self,
525 (get) => {
526 const current = get(signal);
527 get.subscribe(self, (value) => get.setSelf(value));
528 const changed =
529 readUnder.has(get.registry) && !Object.is(readUnder.get(get.registry), current);
530 readUnder.set(get.registry, current);
531 if (changed && !isFinal(get.once(self))) get.refresh(self);
532 return get.once(self);
533 },
534 { initialValueTarget: self },
535 );
536 };
537
538const refreshEveryUntilFinal =
539 <V>(intervalMs: number, isFinal: (value: V) => boolean) =>
540 <A extends V>(self: Atom.Atom<A>): Atom.Atom<A> =>
541 Atom.transform(
542 self,
543 (get) => {
544 const value = get(self);
545 if (!isFinal(value)) {
546 // @effect-diagnostics-next-line globalTimers:off - Mirrors `Atom.withRefresh`, outside an Effect runtime.
547 const handle = setTimeout(() => get.refresh(self), intervalMs);
548 get.addFinalizer(() => clearTimeout(handle));
549 }
550 return value;
551 },
552 { initialValueTarget: self },
553 );
554
555/**
556 * A query result's data alone. A refetch always publishes a new result (a new
557 * timestamp, `waiting` on and off), while equal data keeps its identity, so a
558 * reader of only this skips the refetches that changed nothing.
559 */
560export const selectEnvironmentQueryData = <A, E>(result: AsyncResult.AsyncResult<A, E>): A | null =>
561 Option.getOrNull(AsyncResult.value(result));
562
563type EnvironmentConnection = readonly [
564 SupervisorConnectionState,
565 Option.Option<RpcSession.RpcSession>,
566];
567
568const connectionAtomsByRuntime = new WeakMap<
569 object,
570 (
571 environmentId: EnvironmentIdType,
572 ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentConnection | null>>
573>();
574
575/**
576 * One connection atom per environment for every query on a runtime, so a reader of the session
577 * generation and a query it re-runs see the same connection change at once.
578 */
579function environmentConnectionAtoms<R, ER>(
580 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
581) {
582 const existing = connectionAtomsByRuntime.get(runtime);
583 if (existing !== undefined) return existing;
584 const family = Atom.family((environmentId: EnvironmentIdType) =>
585 runtime.atom(
586 followStreamInEnvironment(
587 environmentId,
588 Stream.unwrap(
589 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
590 Effect.map((supervisor) =>
591 SubscriptionRef.changes(supervisor.state).pipe(
592 Stream.zipLatest(SubscriptionRef.changes(supervisor.session)),
593 ),
594 ),
595 ),
596 ),
597 ),
598 { initialValue: null },
599 ),
600 ) as (
601 environmentId: EnvironmentIdType,
602 ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentConnection | null>>;
603 connectionAtomsByRuntime.set(runtime, family);
604 return family;
605}
606
607const sessionGenerationAtomsByRuntime = new WeakMap<
608 object,
609 (environmentId: EnvironmentIdType) => Atom.Atom<number>
610>();
611
612/**
613 * Counts established sessions; it changes only when a new one comes up, so failed one-shot reads
614 * can watch it to run again. Keyed on the session object because the supervisor's `generation`
615 * restarts when the registry installs a new supervisor (re-pairing, route edits).
616 */
617export function environmentSessionGenerationAtom<R, ER>(
618 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
619 environmentId: EnvironmentIdType,
620): Atom.Atom<number> {
621 let family = sessionGenerationAtomsByRuntime.get(runtime);
622 if (family === undefined) {
623 const connectionAtom = environmentConnectionAtoms(runtime);
624 const sessionsSeen = Atom.family((id: EnvironmentIdType) =>
625 Atom.make(
626 (get): { readonly session: RpcSession.RpcSession | null; readonly count: number } => {
627 const previous = Option.getOrElse(
628 get.self<{ readonly session: RpcSession.RpcSession | null; readonly count: number }>(),
629 () => ({ session: null, count: 0 }),
630 );
631 const connection = Option.getOrNull(AsyncResult.value(get(connectionAtom(id))));
632 if (connection === null || connection[0].phase !== "connected") return previous;
633 const session = Option.getOrNull(connection[1]);
634 return session === null || session === previous.session
635 ? previous
636 : { session, count: previous.count + 1 };
637 },
638 ),
639 );
640 family = Atom.family((id: EnvironmentIdType) =>
641 Atom.make((get) => get(sessionsSeen(id)).count).pipe(
642 Atom.withLabel(`environment-session-generation:${id}`),
643 ),
644 );
645 sessionGenerationAtomsByRuntime.set(runtime, family);
646 }
647 return family(environmentId);
648}
649
650export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
651 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
652 options: EnvironmentQueryAtomOptions<
653 Input,
654 A,
655 E,
656 | EnvironmentSupervisor.EnvironmentSupervisor
657 | EnvironmentRegistry.EnvironmentRegistry
658 | AtomRegistry.AtomRegistry
659 | R
660 >,
661): (target: {
662 readonly environmentId: EnvironmentIdType;
663 readonly input: Input;
664}) => Atom.Atom<AsyncResult.AsyncResult<A, E | ER | Error>> {
665 const connectionAtom = environmentConnectionAtoms(runtime);
666 const family = Atom.family((key: string) => {
667 const target = parseEnvironmentRpcKey<Input>(key);
668 const idleTtlMs = options.idleTtlMs ?? 5 * 60_000;
669 const queryAtom = runtime
670 .atom<
671 A,
672 | E
673 | ConnectionAttemptError
674 | EnvironmentRegistry.EnvironmentNotRegisteredError
675 | EnvironmentRpcUnavailableError
676 >((get) => {
677 const connection = Option.getOrNull(
678 AsyncResult.value(get(connectionAtom(target.environmentId))),
679 );
680 // A refetch that returns equal content keeps the previous value's
681 // references, so readers of the data skip re-rendering on idle polls.
682 const share = (value: A): A =>
683 reuseUnchanged(
684 Option.getOrUndefined(
685 Option.flatMap(get.self<AsyncResult.AsyncResult<A, unknown>>(), AsyncResult.value),
686 ),
687 value,
688 );
689 const emit = (value: A) =>
690 Effect.sync(() => get.setSelf(AsyncResult.success(share(value), { waiting: true }))).pipe(
691 // A value set while the atom builds wins over the build's own
692 // result, so a query that then settled synchronously would stay
693 // waiting forever. Suspend on a promise (`yieldNow` is drained
694 // inside the build) so the settled result arrives asynchronously.
695 Effect.andThen(Effect.promise(() => Promise.resolve())),
696 );
697 const execute = (): Effect.Effect<
698 A,
699 | E
700 | ConnectionAttemptError
701 | EnvironmentRegistry.EnvironmentNotRegisteredError
702 | EnvironmentRpcUnavailableError,
703 | EnvironmentRegistry.EnvironmentRegistry
704 | AtomRegistry.AtomRegistry
705 | Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>
706 > => {
707 if (connection === null) return Effect.never;
708 const [connectionState, session] = connection;
709 switch (connectionState.phase) {
710 case "connected":
711 return Option.isSome(session)
712 ? runInEnvironment(
713 target.environmentId,
714 options
715 .execute(target.input, emit)
716 .pipe(pendingOnceSessionReplaced(session.value)),
717 )
718 : Effect.never;
719 case "connecting":
720 case "backoff":
721 // A retry can take minutes. A query with an answer keeps showing it while it
722 // waits; one with nothing to show reports the failure the retry is recovering
723 // from, so its reader stops loading, and re-runs when the connection settles.
724 return connectionState.lastFailure !== null &&
725 Option.isNone(
726 Option.flatMap(
727 get.self<AsyncResult.AsyncResult<A, unknown>>(),
728 AsyncResult.value,
729 ),
730 )
731 ? Effect.fail(connectionState.lastFailure)
732 : Effect.never;
733 case "available":
734 case "offline":
735 case "blocked":
736 if (connectionState.lastFailure !== null) {
737 return Effect.fail(connectionState.lastFailure);
738 }
739 return Effect.fail(
740 new EnvironmentRpcUnavailableError({
741 environmentId: target.environmentId,
742 message: `Environment ${target.environmentId} is ${
743 connectionState.phase === "available" ? "not connected" : connectionState.phase
744 }.`,
745 }),
746 );
747 }
748 };
749 const onAnswer = options.onAnswer;
750 const answer = () =>
751 onAnswer === undefined
752 ? execute().pipe(Effect.map(share))
753 : execute().pipe(
754 Effect.map(share),
755 Effect.tap((value) => onAnswer(target, value, get.registry)),
756 );
757 if (!options.persistence) return answer();
758 const persistence = options.persistence;
759 const cacheKey = JSON.stringify([options.label, target.input]);
760 const previous = Option.flatMap(
761 get.self<AsyncResult.AsyncResult<A, unknown>>(),
762 AsyncResult.value,
763 );
764 return Effect.gen(function* () {
765 const cached = Option.isSome(previous)
766 ? previous
767 : yield* persistence.load(target.environmentId, cacheKey);
768 if (
769 Option.isSome(cached) &&
770 (connection === null || connection[0].phase !== "connected")
771 ) {
772 return cached.value;
773 }
774 if (Option.isNone(previous) && Option.isSome(cached)) yield* emit(cached.value);
775 return yield* answer().pipe(
776 Effect.tap((value) => persistence.save(target.environmentId, cacheKey, value)),
777 );
778 });
779 })
780 .pipe(
781 Atom.swr({
782 staleTime: options.staleTimeMs ?? 30_000,
783 revalidateOnMount: true,
784 }),
785 Atom.setIdleTTL(idleTtlMs),
786 );
787 const isFinal = (result: AsyncResult.AsyncResult<A, unknown>) =>
788 options.isFinal !== undefined && Option.exists(AsyncResult.value(result), options.isFinal);
789 const intervalQuery =
790 options.refreshIntervalMs === undefined
791 ? queryAtom
792 : queryAtom.pipe(refreshEveryUntilFinal(options.refreshIntervalMs, isFinal));
793 const refreshTrigger = options.refreshTrigger?.(target);
794 return (
795 refreshTrigger === undefined
796 ? intervalQuery
797 : intervalQuery.pipe(refreshOnSignalWhileRead(refreshTrigger, isFinal))
798 ).pipe(Atom.setIdleTTL(idleTtlMs), Atom.withLabel(`${options.label}:${key}`));
799 });
800 return (target) => family(environmentRpcKey(target));
801}
802
803export function createEnvironmentSubscriptionAtomFamily<R, ER, Input, A, E>(
804 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
805 options: EnvironmentSubscriptionAtomOptions<
806 Input,
807 A,
808 E,
809 EnvironmentSupervisor.EnvironmentSupervisor | R
810 >,
811) {
812 const family = Atom.family((key: string) => {
813 const target = parseEnvironmentRpcKey<Input>(key);
814 return runtime
815 .atom(
816 Stream.suspend(() =>
817 followStreamInEnvironment(target.environmentId, options.subscribe(target.input)),
818 ).pipe(options.completeWhen ? Stream.takeUntil(options.completeWhen) : (stream) => stream),
819 )
820 .pipe(
821 Atom.setIdleTTL(options.idleTtlMs ?? 5 * 60_000),
822 Atom.withLabel(
823 options.sensitiveInput
824 ? `${options.label}:${target.environmentId}`
825 : `${options.label}:${key}`,
826 ),
827 );
828 });
829 return (target: { readonly environmentId: EnvironmentIdType; readonly input: Input }) =>
830 family(environmentRpcKey(target));
831}
832
833export function createEnvironmentCommand<R, ER, Input, A, E>(
834 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
835 options: EnvironmentCommandAtomOptions<
836 Input,
837 A,
838 E,
839 EnvironmentSupervisor.EnvironmentSupervisor | EnvironmentRegistry.EnvironmentRegistry | R
840 >,
841) {
842 return createRuntimeCommand(runtime, {
843 label: options.label,
844 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
845 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
846 execute: (target, registry) =>
847 runInEnvironment(
848 target.environmentId,
849 options.execute(target.input, registry, target.environmentId),
850 ),
851 });
852}
853
854export function createEnvironmentRpcQueryAtomFamily<
855 R,
856 ER,
857 TTag extends Exclude<EnvironmentUnaryRpcTag, ClientGuardedRpcTag>,
858>(
859 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
860 options: {
861 readonly label: string;
862 readonly tag: TTag;
863 readonly execute?: (
864 input: EnvironmentRpcInput<TTag>,
865 emit: (value: EnvironmentRpcSuccess<TTag>) => Effect.Effect<void>,
866 ) => Effect.Effect<
867 EnvironmentRpcSuccess<TTag>,
868 EnvironmentRpcFailure<TTag> | EnvironmentRpcUnavailableError,
869 EnvironmentSupervisor.EnvironmentSupervisor | EnvironmentRegistry.EnvironmentRegistry
870 >;
871 readonly persistence?: QueryPersistence<EnvironmentRpcSuccess<TTag>>;
872 readonly staleTimeMs?: number;
873 readonly idleTtlMs?: number;
874 readonly refreshIntervalMs?: number;
875 readonly refreshTrigger?: (target: {
876 readonly environmentId: EnvironmentIdType;
877 readonly input: EnvironmentRpcInput<TTag>;
878 }) => Atom.Atom<unknown> | undefined;
879 readonly isFinal?: (value: EnvironmentRpcSuccess<TTag>) => boolean;
880 readonly onAnswer?: QueryAnswerHandler<EnvironmentRpcInput<TTag>, EnvironmentRpcSuccess<TTag>>;
881 },
882) {
883 return createEnvironmentQueryAtomFamily(runtime, {
884 label: options.label,
885 ...(options.persistence === undefined ? {} : { persistence: options.persistence }),
886 ...(options.staleTimeMs === undefined ? {} : { staleTimeMs: options.staleTimeMs }),
887 ...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),
888 ...(options.refreshIntervalMs === undefined
889 ? {}
890 : { refreshIntervalMs: options.refreshIntervalMs }),
891 ...(options.refreshTrigger === undefined ? {} : { refreshTrigger: options.refreshTrigger }),
892 ...(options.isFinal === undefined ? {} : { isFinal: options.isFinal }),
893 ...(options.onAnswer === undefined ? {} : { onAnswer: options.onAnswer }),
894 execute: (
895 input: EnvironmentRpcInput<TTag>,
896 emit: (value: EnvironmentRpcSuccess<TTag>) => Effect.Effect<void>,
897 ) => options.execute?.(input, emit) ?? request(options.tag, input),
898 });
899}
900
901export function createEnvironmentRpcSubscriptionAtomFamily<
902 R,
903 ER,
904 TTag extends EnvironmentSubscriptionRpcTag,
905 B = EnvironmentRpcStreamValue<TTag>,
906>(
907 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
908 options: {
909 readonly label: string;
910 readonly tag: TTag;
911 readonly idleTtlMs?: number;
912 readonly completeWhen?: (value: B) => boolean;
913 readonly transform?: (
914 stream: Stream.Stream<
915 EnvironmentRpcStreamValue<TTag>,
916 EnvironmentRpcStreamFailure<TTag>,
917 EnvironmentSupervisor.EnvironmentSupervisor | R
918 >,
919 ) => Stream.Stream<
920 B,
921 EnvironmentRpcStreamFailure<TTag>,
922 EnvironmentSupervisor.EnvironmentSupervisor | R
923 >;
924 },
925) {
926 return createEnvironmentSubscriptionAtomFamily(runtime, {
927 label: options.label,
928 ...(options.completeWhen === undefined ? {} : { completeWhen: options.completeWhen }),
929 ...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),
930 subscribe: (input: EnvironmentRpcInput<TTag>) => {
931 const stream = subscribe(options.tag, input);
932 return options.transform === undefined
933 ? (stream as Stream.Stream<
934 B,
935 EnvironmentRpcStreamFailure<TTag>,
936 EnvironmentSupervisor.EnvironmentSupervisor | R
937 >)
938 : options.transform(stream);
939 },
940 });
941}
942
943export function createEnvironmentRpcCommand<
944 R,
945 ER,
946 TTag extends EnvironmentUnaryRpcTag,
947 Input extends EnvironmentRpcInput<TTag> = EnvironmentRpcInput<TTag>,
948>(
949 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
950 options: {
951 readonly label: string;
952 readonly tag: TTag;
953 readonly execute?: (
954 input: Input,
955 ) => Effect.Effect<
956 EnvironmentRpcSuccess<TTag>,
957 EnvironmentRpcFailure<TTag> | EnvironmentRpcUnavailableError,
958 EnvironmentSupervisor.EnvironmentSupervisor | EnvironmentRegistry.EnvironmentRegistry
959 >;
960 readonly scheduler?: AtomCommandScheduler;
961 readonly concurrency?: AtomCommandConcurrency<{
962 readonly environmentId: EnvironmentIdType;
963 readonly input: NoInfer<Input>;
964 }>;
965 readonly onSuccess?: (
966 target: {
967 readonly environmentId: EnvironmentIdType;
968 readonly input: NoInfer<Input>;
969 },
970 registry: AtomRegistry.AtomRegistry,
971 result: EnvironmentRpcSuccess<TTag>,
972 ) => Effect.Effect<void, never, R>;
973 readonly onSettled?: (
974 target: {
975 readonly environmentId: EnvironmentIdType;
976 readonly input: NoInfer<Input>;
977 },
978 registry: AtomRegistry.AtomRegistry,
979 ) => Effect.Effect<void, never, R>;
980 },
981) {
982 const permissions = createCommandPermissions(runtime, options.tag);
983 const command = createEnvironmentCommand(runtime, {
984 label: options.label,
985 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
986 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
987 execute: (input: Input, registry, environmentId) => {
988 const target = {
989 environmentId,
990 input,
991 };
992 // Routing requires consent on the origin as well as the actual destination.
993 // The transport check below deliberately checks the destination again.
994 return permissions.authorize(registry, environmentId, input).pipe(
995 Effect.andThen(() => options.execute?.(input) ?? requestGuarded(options.tag, input)),
996 Effect.provideService(RpcPermissionGuard, {
997 authorize: (id, method, payload) =>
998 createCommandPermissions(runtime, method).authorize(registry, id, payload),
999 }),
1000 Effect.tap((result) => options.onSuccess?.(target, registry, result) ?? Effect.void),
1001 Effect.ensuring(options.onSettled?.(target, registry) ?? Effect.void),
1002 );
1003 },
1004 });
1005 return {
1006 ...command,
1007 requiredScopes: permissions.requiredScopes,
1008 permissionAtom: permissions.permissionAtom,
1009 };
1010}