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