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