Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

runtime.ts

928 lines32.4 KB

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 } 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 }>;
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>;
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>;
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;
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;
139​
140export interface AtomCommandReporter {
141 readonly warn: (message: string, cause: Cause.Cause<unknown>) => void;
142 readonly error: (message: string, cause: Cause.Cause<unknown>) => void;
144​
145export interface AtomCommand<W, A, E> {
146 readonly label: string;
147 readonly run: (registry: AtomRegistry.AtomRegistry, input: W) => Promise<AtomCommandResult<A, E>>;
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>;
162​
163interface AtomCommandLatestBatch {
164 execute: () => Promise<AtomCommandResult<unknown, unknown>>;
165 readonly resolve: Array<(result: AtomCommandResult<unknown, unknown>) => void>;
167​
168interface AtomCommandLatestLane {
169 running: boolean;
170 pending: AtomCommandLatestBatch | undefined;
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>>;
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 }
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 };
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;
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);
355​
356export function isAtomCommandInterrupted(result: AtomCommandResult<unknown, unknown>): boolean {
357 return result._tag === "Failure" && Cause.hasInterruptsOnly(result.cause);
359​
360export function squashAtomCommandFailure(result: {
361 readonly cause: Cause.Cause<unknown>;
362}): unknown {
363 return Cause.squash(result.cause);
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 }
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;
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;
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 );
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 };
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 }
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 }
478​
479export function environmentRpcKey<Input>(target: {
480 readonly environmentId: EnvironmentIdType;
481 readonly input: Input;
482}): string {
483 return JSON.stringify([target.environmentId, target.input]);
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 };
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 );
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​
563export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
564 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
565 options: EnvironmentQueryAtomOptions<
566 Input,
567 A,
568 E,
569 | EnvironmentSupervisor.EnvironmentSupervisor
570 | EnvironmentRegistry.EnvironmentRegistry
571 | AtomRegistry.AtomRegistry
572 | R
573 >,
574): (target: {
575 readonly environmentId: EnvironmentIdType;
576 readonly input: Input;
577}) => Atom.Atom<AsyncResult.AsyncResult<A, E | ER | Error>> {
578 const connectionAtom = Atom.family((environmentId: EnvironmentIdType) =>
579 runtime.atom(
580 followStreamInEnvironment(
581 environmentId,
582 Stream.unwrap(
583 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
584 Effect.map((supervisor) =>
585 SubscriptionRef.changes(supervisor.state).pipe(
586 Stream.zipLatest(SubscriptionRef.changes(supervisor.session)),
587 ),
588 ),
589 ),
590 ),
591 ),
592 { initialValue: null },
593 ),
594 );
595 const family = Atom.family((key: string) => {
596 const target = parseEnvironmentRpcKey<Input>(key);
597 const idleTtlMs = options.idleTtlMs ?? 5 * 60_000;
598 const queryAtom = runtime
599 .atom<
600 A,
601 | E
602 | ConnectionAttemptError
603 | EnvironmentRegistry.EnvironmentNotRegisteredError
604 | EnvironmentRpcUnavailableError
605 >((get) => {
606 const connection = Option.getOrNull(
607 AsyncResult.value(get(connectionAtom(target.environmentId))),
608 );
609 // A refetch that returns equal content keeps the previous value's
610 // references, so readers of the data skip re-rendering on idle polls.
611 const share = (value: A): A =>
612 reuseUnchanged(
613 Option.getOrUndefined(
614 Option.flatMap(get.self<AsyncResult.AsyncResult<A, unknown>>(), AsyncResult.value),
615 ),
616 value,
617 );
618 const emit = (value: A) =>
619 Effect.sync(() => get.setSelf(AsyncResult.success(share(value), { waiting: true }))).pipe(
620 // A value set while the atom builds wins over the build's own
621 // result, so a query that then settled synchronously would stay
622 // waiting forever. Suspend on a promise (`yieldNow` is drained
623 // inside the build) so the settled result arrives asynchronously.
624 Effect.andThen(Effect.promise(() => Promise.resolve())),
625 );
626 const execute = (): Effect.Effect<
627 A,
628 | E
629 | ConnectionAttemptError
630 | EnvironmentRegistry.EnvironmentNotRegisteredError
631 | EnvironmentRpcUnavailableError,
632 | EnvironmentRegistry.EnvironmentRegistry
633 | AtomRegistry.AtomRegistry
634 | Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>
635 > => {
636 if (connection === null) return Effect.never;
637 const [connectionState, session] = connection;
638 switch (connectionState.phase) {
639 case "connected":
640 return Option.isSome(session)
641 ? runInEnvironment(
642 target.environmentId,
643 options
644 .execute(target.input, emit)
645 .pipe(pendingOnceSessionReplaced(session.value)),
646 )
647 : Effect.never;
648 case "connecting":
649 case "backoff":
650 return Effect.never;
651 case "available":
652 case "offline":
653 case "blocked":
654 if (connectionState.lastFailure !== null) {
655 return Effect.fail(connectionState.lastFailure);
656 }
657 return Effect.fail(
658 new EnvironmentRpcUnavailableError({
659 environmentId: target.environmentId,
660 message: `Environment ${target.environmentId} is ${
661 connectionState.phase === "available" ? "not connected" : connectionState.phase
662 }.`,
663 }),
664 );
665 }
666 };
667 const onAnswer = options.onAnswer;
668 const answer = () =>
669 onAnswer === undefined
670 ? execute().pipe(Effect.map(share))
671 : execute().pipe(
672 Effect.map(share),
673 Effect.tap((value) => onAnswer(target, value, get.registry)),
674 );
675 if (!options.persistence) return answer();
676 const persistence = options.persistence;
677 const cacheKey = JSON.stringify([options.label, target.input]);
678 const previous = Option.flatMap(
679 get.self<AsyncResult.AsyncResult<A, unknown>>(),
680 AsyncResult.value,
681 );
682 return Effect.gen(function* () {
683 const cached = Option.isSome(previous)
684 ? previous
685 : yield* persistence.load(target.environmentId, cacheKey);
686 if (
687 Option.isSome(cached) &&
688 (connection === null || connection[0].phase !== "connected")
689 ) {
690 return cached.value;
691 }
692 if (Option.isNone(previous) && Option.isSome(cached)) yield* emit(cached.value);
693 return yield* answer().pipe(
694 Effect.tap((value) => persistence.save(target.environmentId, cacheKey, value)),
695 );
696 });
697 })
698 .pipe(
699 Atom.swr({
700 staleTime: options.staleTimeMs ?? 30_000,
701 revalidateOnMount: true,
702 }),
703 Atom.setIdleTTL(idleTtlMs),
704 );
705 const isFinal = (result: AsyncResult.AsyncResult<A, unknown>) =>
706 options.isFinal !== undefined && Option.exists(AsyncResult.value(result), options.isFinal);
707 const intervalQuery =
708 options.refreshIntervalMs === undefined
709 ? queryAtom
710 : queryAtom.pipe(refreshEveryUntilFinal(options.refreshIntervalMs, isFinal));
711 const refreshTrigger = options.refreshTrigger?.(target);
712 return (
713 refreshTrigger === undefined
714 ? intervalQuery
715 : intervalQuery.pipe(refreshOnSignalWhileRead(refreshTrigger, isFinal))
716 ).pipe(Atom.setIdleTTL(idleTtlMs), Atom.withLabel(`${options.label}:${key}`));
717 });
718 return (target) => family(environmentRpcKey(target));
720​
721export function createEnvironmentSubscriptionAtomFamily<R, ER, Input, A, E>(
722 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
723 options: EnvironmentSubscriptionAtomOptions<
724 Input,
725 A,
726 E,
727 EnvironmentSupervisor.EnvironmentSupervisor | R
728 >,
729) {
730 const family = Atom.family((key: string) => {
731 const target = parseEnvironmentRpcKey<Input>(key);
732 return runtime
733 .atom(
734 Stream.suspend(() =>
735 followStreamInEnvironment(target.environmentId, options.subscribe(target.input)),
736 ).pipe(options.completeWhen ? Stream.takeUntil(options.completeWhen) : (stream) => stream),
737 )
738 .pipe(
739 Atom.setIdleTTL(options.idleTtlMs ?? 5 * 60_000),
740 Atom.withLabel(
741 options.sensitiveInput
742 ? `${options.label}:${target.environmentId}`
743 : `${options.label}:${key}`,
744 ),
745 );
746 });
747 return (target: { readonly environmentId: EnvironmentIdType; readonly input: Input }) =>
748 family(environmentRpcKey(target));
750​
751export function createEnvironmentCommand<R, ER, Input, A, E>(
752 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
753 options: EnvironmentCommandAtomOptions<
754 Input,
755 A,
756 E,
757 EnvironmentSupervisor.EnvironmentSupervisor | EnvironmentRegistry.EnvironmentRegistry | R
758 >,
759) {
760 return createRuntimeCommand(runtime, {
761 label: options.label,
762 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
763 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
764 execute: (target, registry) =>
765 runInEnvironment(
766 target.environmentId,
767 options.execute(target.input, registry, target.environmentId),
768 ),
769 });
771​
772export function createEnvironmentRpcQueryAtomFamily<
773 R,
774 ER,
775 TTag extends Exclude<EnvironmentUnaryRpcTag, ClientGuardedRpcTag>,
776>(
777 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
778 options: {
779 readonly label: string;
780 readonly tag: TTag;
781 readonly execute?: (
782 input: EnvironmentRpcInput<TTag>,
783 emit: (value: EnvironmentRpcSuccess<TTag>) => Effect.Effect<void>,
784 ) => Effect.Effect<
785 EnvironmentRpcSuccess<TTag>,
786 EnvironmentRpcFailure<TTag> | EnvironmentRpcUnavailableError,
787 EnvironmentSupervisor.EnvironmentSupervisor | EnvironmentRegistry.EnvironmentRegistry
788 >;
789 readonly persistence?: QueryPersistence<EnvironmentRpcSuccess<TTag>>;
790 readonly staleTimeMs?: number;
791 readonly idleTtlMs?: number;
792 readonly refreshIntervalMs?: number;
793 readonly refreshTrigger?: (target: {
794 readonly environmentId: EnvironmentIdType;
795 readonly input: EnvironmentRpcInput<TTag>;
796 }) => Atom.Atom<unknown> | undefined;
797 readonly isFinal?: (value: EnvironmentRpcSuccess<TTag>) => boolean;
798 readonly onAnswer?: QueryAnswerHandler<EnvironmentRpcInput<TTag>, EnvironmentRpcSuccess<TTag>>;
799 },
800) {
801 return createEnvironmentQueryAtomFamily(runtime, {
802 label: options.label,
803 ...(options.persistence === undefined ? {} : { persistence: options.persistence }),
804 ...(options.staleTimeMs === undefined ? {} : { staleTimeMs: options.staleTimeMs }),
805 ...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),
806 ...(options.refreshIntervalMs === undefined
807 ? {}
808 : { refreshIntervalMs: options.refreshIntervalMs }),
809 ...(options.refreshTrigger === undefined ? {} : { refreshTrigger: options.refreshTrigger }),
810 ...(options.isFinal === undefined ? {} : { isFinal: options.isFinal }),
811 ...(options.onAnswer === undefined ? {} : { onAnswer: options.onAnswer }),
812 execute: (
813 input: EnvironmentRpcInput<TTag>,
814 emit: (value: EnvironmentRpcSuccess<TTag>) => Effect.Effect<void>,
815 ) => options.execute?.(input, emit) ?? request(options.tag, input),
816 });
818​
819export function createEnvironmentRpcSubscriptionAtomFamily<
820 R,
821 ER,
822 TTag extends EnvironmentSubscriptionRpcTag,
823 B = EnvironmentRpcStreamValue<TTag>,
824>(
825 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
826 options: {
827 readonly label: string;
828 readonly tag: TTag;
829 readonly idleTtlMs?: number;
830 readonly completeWhen?: (value: B) => boolean;
831 readonly transform?: (
832 stream: Stream.Stream<
833 EnvironmentRpcStreamValue<TTag>,
834 EnvironmentRpcStreamFailure<TTag>,
835 EnvironmentSupervisor.EnvironmentSupervisor | R
836 >,
837 ) => Stream.Stream<
838 B,
839 EnvironmentRpcStreamFailure<TTag>,
840 EnvironmentSupervisor.EnvironmentSupervisor | R
841 >;
842 },
843) {
844 return createEnvironmentSubscriptionAtomFamily(runtime, {
845 label: options.label,
846 ...(options.completeWhen === undefined ? {} : { completeWhen: options.completeWhen }),
847 ...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),
848 subscribe: (input: EnvironmentRpcInput<TTag>) => {
849 const stream = subscribe(options.tag, input);
850 return options.transform === undefined
851 ? (stream as Stream.Stream<
852 B,
853 EnvironmentRpcStreamFailure<TTag>,
854 EnvironmentSupervisor.EnvironmentSupervisor | R
855 >)
856 : options.transform(stream);
857 },
858 });
860​
861export function createEnvironmentRpcCommand<
862 R,
863 ER,
864 TTag extends EnvironmentUnaryRpcTag,
865 Input extends EnvironmentRpcInput<TTag> = EnvironmentRpcInput<TTag>,
866>(
867 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
868 options: {
869 readonly label: string;
870 readonly tag: TTag;
871 readonly execute?: (
872 input: Input,
873 ) => Effect.Effect<
874 EnvironmentRpcSuccess<TTag>,
875 EnvironmentRpcFailure<TTag> | EnvironmentRpcUnavailableError,
876 EnvironmentSupervisor.EnvironmentSupervisor | EnvironmentRegistry.EnvironmentRegistry
877 >;
878 readonly scheduler?: AtomCommandScheduler;
879 readonly concurrency?: AtomCommandConcurrency<{
880 readonly environmentId: EnvironmentIdType;
881 readonly input: NoInfer<Input>;
882 }>;
883 readonly onSuccess?: (
884 target: {
885 readonly environmentId: EnvironmentIdType;
886 readonly input: NoInfer<Input>;
887 },
888 registry: AtomRegistry.AtomRegistry,
889 result: EnvironmentRpcSuccess<TTag>,
890 ) => Effect.Effect<void, never, R>;
891 readonly onSettled?: (
892 target: {
893 readonly environmentId: EnvironmentIdType;
894 readonly input: NoInfer<Input>;
895 },
896 registry: AtomRegistry.AtomRegistry,
897 ) => Effect.Effect<void, never, R>;
898 },
899) {
900 const permissions = createCommandPermissions(runtime, options.tag);
901 const command = createEnvironmentCommand(runtime, {
902 label: options.label,
903 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
904 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
905 execute: (input: Input, registry, environmentId) => {
906 const target = {
907 environmentId,
908 input,
909 };
910 // Routing requires consent on the origin as well as the actual destination.
911 // The transport check below deliberately checks the destination again.
912 return permissions.authorize(registry, environmentId, input).pipe(
913 Effect.andThen(() => options.execute?.(input) ?? requestGuarded(options.tag, input)),
914 Effect.provideService(RpcPermissionGuard, {
915 authorize: (id, method, payload) =>
916 createCommandPermissions(runtime, method).authorize(registry, id, payload),
917 }),
918 Effect.tap((result) => options.onSuccess?.(target, registry, result) ?? Effect.void),
919 Effect.ensuring(options.onSettled?.(target, registry) ?? Effect.void),
920 );
921 },
922 });
923 return {
924 ...command,
925 requiredScopes: permissions.requiredScopes,
926 permissionAtom: permissions.permissionAtom,
927 };