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

runtime.ts

786 lines25.9 KB

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