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

runtime.ts

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