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

runtime.ts

785 lines25.8 KB

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