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

runtime.ts

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