Open History to see the last commit
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 Result from "effect/Result";
7import * as Stream from "effect/Stream";
8import * as SubscriptionRef from "effect/SubscriptionRef";
9import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
10
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 request,
20 runStream,
21 subscribe,
22} from "../rpc/client.ts";
23import { EnvironmentSupervisor } from "../connection/supervisor.ts";
24
25interface EnvironmentAtomOptions<Input, A, E, R> {
26 readonly label: string;
27 readonly execute: (input: Input) => Effect.Effect<A, E, R>;
28 readonly scheduler?: AtomCommandScheduler;
29 readonly concurrency?: AtomCommandConcurrency<{
30 readonly environmentId: EnvironmentIdType;
31 readonly input: Input;
32 }>;
33}
34
35interface EnvironmentCommandAtomOptions<Input, A, E, R> extends Omit<
36 EnvironmentAtomOptions<Input, A, E, R>,
37 "execute"
38> {
39 readonly execute: (
40 input: Input,
41 registry: AtomRegistry.AtomRegistry,
42 environmentId: EnvironmentIdType,
43 ) => Effect.Effect<A, E, R>;
44}
45
46interface EnvironmentQueryAtomOptions<Input, A, E, R> extends EnvironmentAtomOptions<
47 Input,
48 A,
49 E,
50 R
51> {
52 readonly staleTimeMs?: number;
53 readonly idleTtlMs?: number;
54 readonly refreshIntervalMs?: number;
55}
56
57interface EnvironmentSubscriptionAtomOptions<Input, A, E, R> {
58 readonly label: string;
59 readonly subscribe: (input: Input) => Stream.Stream<A, E, R>;
60 readonly idleTtlMs?: number;
61}
62
63export type SettledAsyncResult<A, E> = AsyncResult.Success<A, E> | AsyncResult.Failure<A, E>;
64
65export type AtomCommandResult<A, E> = SettledAsyncResult<A, E>;
66
67export type AtomCommandSuccess<R> = R extends AtomCommandResult<infer A, infer _E> ? A : never;
68
69export type AtomCommandFailure<R> = R extends AtomCommandResult<infer _A, infer E> ? E : never;
70
71export interface AtomCommandOptions {
72 readonly label?: string;
73 readonly reportFailure?: boolean;
74 readonly reportDefect?: boolean;
75}
76
77export interface AtomCommandReporter {
78 readonly warn: (message: string, cause: Cause.Cause<unknown>) => void;
79 readonly error: (message: string, cause: Cause.Cause<unknown>) => void;
80}
81
82export interface AtomCommand<W, A, E> {
83 readonly label: string;
84 readonly run: (registry: AtomRegistry.AtomRegistry, input: W) => Promise<AtomCommandResult<A, E>>;
85}
86
87export type AtomCommandConcurrency<W> =
88 /** Every invocation runs independently. */
89 | { readonly mode: "parallel" }
90 | {
91 /**
92 * `serial` preserves every invocation in FIFO order, `singleFlight` shares an active
93 * invocation, and `latest` coalesces queued invocations to the newest input.
94 */
95 readonly mode: "serial" | "singleFlight" | "latest";
96 readonly key: (input: W) => string;
97 };
98
99interface AtomCommandSchedulerState {
100 readonly serial: Map<string, Promise<unknown>>;
101 readonly singleFlight: Map<string, Promise<unknown>>;
102 readonly latest: Map<string, AtomCommandLatestLane>;
103}
104
105interface AtomCommandLatestBatch {
106 execute: () => Promise<AtomCommandResult<unknown, unknown>>;
107 readonly resolve: Array<(result: AtomCommandResult<unknown, unknown>) => void>;
108}
109
110interface AtomCommandLatestLane {
111 running: boolean;
112 pending: AtomCommandLatestBatch | undefined;
113}
114
115export interface AtomCommandScheduler {
116 readonly schedule: <W, A, E>(
117 registry: AtomRegistry.AtomRegistry,
118 concurrency: AtomCommandConcurrency<W>,
119 input: W,
120 execute: () => Promise<AtomCommandResult<A, E>>,
121 ) => Promise<AtomCommandResult<A, E>>;
122}
123
124async function settleAtomCommandResult<A, E>(
125 execute: () => Promise<AtomCommandResult<A, E>>,
126): Promise<AtomCommandResult<A, E>> {
127 try {
128 return await execute();
129 } catch (defect) {
130 return AsyncResult.failure(Cause.die(defect));
131 }
132}
133
134export function createAtomCommandScheduler(): AtomCommandScheduler {
135 const registryStates = new WeakMap<AtomRegistry.AtomRegistry, AtomCommandSchedulerState>();
136
137 const stateFor = (registry: AtomRegistry.AtomRegistry): AtomCommandSchedulerState => {
138 const existing = registryStates.get(registry);
139 if (existing !== undefined) {
140 return existing;
141 }
142 const state: AtomCommandSchedulerState = {
143 serial: new Map(),
144 singleFlight: new Map(),
145 latest: new Map(),
146 };
147 registryStates.set(registry, state);
148 return state;
149 };
150
151 return {
152 schedule: <W, A, E>(
153 registry: AtomRegistry.AtomRegistry,
154 concurrency: AtomCommandConcurrency<W>,
155 input: W,
156 execute: () => Promise<AtomCommandResult<A, E>>,
157 ): Promise<AtomCommandResult<A, E>> => {
158 if (concurrency.mode === "parallel") {
159 return execute();
160 }
161
162 const key = concurrency.key(input);
163 const state = stateFor(registry);
164 if (concurrency.mode === "singleFlight") {
165 const existing = state.singleFlight.get(key) as
166 | Promise<AtomCommandResult<A, E>>
167 | undefined;
168 if (existing !== undefined) {
169 return existing;
170 }
171 const current = execute();
172 state.singleFlight.set(key, current);
173 void current.then(
174 () => {
175 if (state.singleFlight.get(key) === current) {
176 state.singleFlight.delete(key);
177 }
178 },
179 () => {
180 if (state.singleFlight.get(key) === current) {
181 state.singleFlight.delete(key);
182 }
183 },
184 );
185 return current;
186 }
187
188 if (concurrency.mode === "serial") {
189 const previous = state.serial.get(key);
190 const current = previous === undefined ? execute() : previous.then(execute, execute);
191 state.serial.set(key, current);
192 void current.then(
193 () => {
194 if (state.serial.get(key) === current) {
195 state.serial.delete(key);
196 }
197 },
198 () => {
199 if (state.serial.get(key) === current) {
200 state.serial.delete(key);
201 }
202 },
203 );
204 return current;
205 }
206
207 let lane = state.latest.get(key);
208 if (lane === undefined) {
209 lane = { running: false, pending: undefined };
210 state.latest.set(key, lane);
211 }
212 const activeLane = lane;
213
214 const result = new Promise<AtomCommandResult<A, E>>((resolve) => {
215 if (activeLane.pending === undefined) {
216 activeLane.pending = {
217 execute: execute as () => Promise<AtomCommandResult<unknown, unknown>>,
218 resolve: [resolve as (result: AtomCommandResult<unknown, unknown>) => void],
219 };
220 return;
221 }
222 activeLane.pending.execute = execute as () => Promise<AtomCommandResult<unknown, unknown>>;
223 activeLane.pending.resolve.push(
224 resolve as (result: AtomCommandResult<unknown, unknown>) => void,
225 );
226 });
227
228 if (!activeLane.running) {
229 activeLane.running = true;
230 void (async () => {
231 while (activeLane.pending !== undefined) {
232 const batch = activeLane.pending;
233 activeLane.pending = undefined;
234 let batchResult: AtomCommandResult<unknown, unknown>;
235 try {
236 batchResult = await batch.execute();
237 } catch (defect) {
238 batchResult = AsyncResult.failure(Cause.die(defect));
239 }
240 for (const resolve of batch.resolve) {
241 resolve(batchResult);
242 }
243 }
244 activeLane.running = false;
245 if (state.latest.get(key) === activeLane) {
246 state.latest.delete(key);
247 }
248 })();
249 }
250
251 return result;
252 },
253 };
254}
255
256export async function runAtomCommand<W, A, E>(
257 registry: AtomRegistry.AtomRegistry,
258 command: AtomCommand<W, A, E>,
259 input: W,
260 options: AtomCommandOptions = {},
261 reporter: AtomCommandReporter = console,
262): Promise<AtomCommandResult<A, E>> {
263 const result = await settleAtomCommandResult(() => command.run(registry, input));
264 reportAtomCommandResult(result, { ...options, label: options.label ?? command.label }, reporter);
265 return result;
266}
267
268export function mapAtomCommandResult<A, E, B>(
269 result: AtomCommandResult<A, E>,
270 map: (value: A) => B,
271): AtomCommandResult<B, E> {
272 return result._tag === "Success"
273 ? AsyncResult.success(map(result.value))
274 : AsyncResult.failure(result.cause);
275}
276
277export function isAtomCommandInterrupted(result: AtomCommandResult<unknown, unknown>): boolean {
278 return result._tag === "Failure" && Cause.hasInterruptsOnly(result.cause);
279}
280
281export function squashAtomCommandFailure(result: {
282 readonly cause: Cause.Cause<unknown>;
283}): unknown {
284 return Cause.squash(result.cause);
285}
286
287export async function settleAsyncResult<A, E>(
288 execute: () => Promise<Exit.Exit<A, E>>,
289): Promise<SettledAsyncResult<A, E>> {
290 try {
291 return AsyncResult.fromExit(await execute());
292 } catch (defect) {
293 return AsyncResult.failure(Cause.die(defect));
294 }
295}
296
297export async function executeAtomCommand<A, E>(
298 execute: () => Promise<Exit.Exit<A, E>>,
299 options: AtomCommandOptions = {},
300 reporter: AtomCommandReporter = console,
301): Promise<AtomCommandResult<A, E>> {
302 const result = await settleAsyncResult(execute);
303 reportAtomCommandResult(result, options, reporter);
304 return result;
305}
306
307export async function executeAtomQuery<A, E>(
308 registry: AtomRegistry.AtomRegistry,
309 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
310 options: AtomCommandOptions = {},
311 reporter: AtomCommandReporter = console,
312): Promise<AtomCommandResult<A, E>> {
313 const query = Effect.scoped(
314 Effect.gen(function* () {
315 yield* AtomRegistry.mount(registry, atom);
316 return yield* AtomRegistry.getResult(registry, atom, {
317 suspendOnWaiting: true,
318 });
319 }),
320 );
321 return executeAtomCommand(() => Effect.runPromiseExit(query), options, reporter);
322}
323
324export function createRuntimeCommand<R, ER, W, A, E>(
325 runtime: Atom.AtomRuntime<R, ER>,
326 options: {
327 readonly label: string;
328 readonly execute: (input: W, registry: AtomRegistry.AtomRegistry) => Effect.Effect<A, E, R>;
329 readonly scheduler?: AtomCommandScheduler;
330 readonly concurrency?: AtomCommandConcurrency<W>;
331 },
332): AtomCommand<W, A, E | ER> {
333 const scheduler = options.scheduler ?? createAtomCommandScheduler();
334 const concurrency = options.concurrency ?? { mode: "parallel" as const };
335 return {
336 label: options.label,
337 run: (registry, input) =>
338 settleAtomCommandResult(() =>
339 scheduler.schedule(registry, concurrency, input, () => {
340 const atom = runtime
341 .atom(options.execute(input, registry))
342 .pipe(Atom.withLabel(options.label));
343 return executeAtomQuery(registry, atom, { reportDefect: false, reportFailure: false });
344 }),
345 ),
346 };
347}
348
349export function createRuntimeStreamCommand<R, ER, W, A, E>(
350 runtime: Atom.AtomRuntime<R, ER>,
351 options: {
352 readonly label: string;
353 readonly execute: (input: W, registry: AtomRegistry.AtomRegistry) => Stream.Stream<A, E, R>;
354 readonly scheduler?: AtomCommandScheduler;
355 readonly concurrency?: AtomCommandConcurrency<W>;
356 },
357): AtomCommand<W, A, E | ER | Cause.NoSuchElementError> {
358 const scheduler = options.scheduler ?? createAtomCommandScheduler();
359 const concurrency = options.concurrency ?? { mode: "parallel" as const };
360 return {
361 label: options.label,
362 run: (registry, input) =>
363 settleAtomCommandResult(() =>
364 scheduler.schedule(registry, concurrency, input, () => {
365 const atom = runtime
366 .atom(options.execute(input, registry))
367 .pipe(Atom.withLabel(options.label));
368 return executeAtomQuery(registry, atom, { reportDefect: false, reportFailure: false });
369 }),
370 ),
371 };
372}
373
374export function reportAtomCommandResult(
375 result: AtomCommandResult<unknown, unknown>,
376 options: AtomCommandOptions = {},
377 reporter: AtomCommandReporter = console,
378): void {
379 if (AsyncResult.isSuccess(result) || Cause.hasInterruptsOnly(result.cause)) {
380 return;
381 }
382
383 const label = options.label ?? "atom command";
384 if (Cause.hasDies(result.cause)) {
385 if (options.reportDefect ?? true) {
386 reporter.error(`[atom-command] ${label} defected`, result.cause);
387 }
388 } else if (options.reportFailure ?? true) {
389 reporter.warn(`[atom-command] ${label} failed`, result.cause);
390 }
391}
392
393export async function settlePromise<A>(
394 execute: () => Promise<A>,
395): Promise<AtomCommandResult<A, never>> {
396 try {
397 return AsyncResult.success(await execute());
398 } catch (defect) {
399 return AsyncResult.failure(Cause.die(defect));
400 }
401}
402
403export function environmentRpcKey<Input>(target: {
404 readonly environmentId: EnvironmentIdType;
405 readonly input: Input;
406}): string {
407 return JSON.stringify([target.environmentId, target.input]);
408}
409
410function parseEnvironmentRpcKey<Input>(key: string): {
411 readonly environmentId: EnvironmentIdType;
412 readonly input: Input;
413} {
414 const decoded = JSON.parse(key) as [EnvironmentIdType, Input];
415 return {
416 environmentId: EnvironmentId.make(decoded[0]),
417 input: decoded[1],
418 };
419}
420
421export function runInEnvironment<A, E, R>(
422 environmentId: EnvironmentIdType,
423 effect: Effect.Effect<A, E, R>,
424): Effect.Effect<
425 A,
426 E | EnvironmentNotRegisteredError,
427 EnvironmentRegistry | Exclude<R, EnvironmentSupervisor>
428> {
429 return EnvironmentRegistry.pipe(
430 Effect.flatMap((registry) => registry.run(environmentId, effect)),
431 );
432}
433
434export function runStreamInEnvironment<A, E, R>(
435 environmentId: EnvironmentIdType,
436 stream: Stream.Stream<A, E, R>,
437): Stream.Stream<
438 A,
439 E | EnvironmentNotRegisteredError,
440 EnvironmentRegistry | Exclude<R, EnvironmentSupervisor>
441> {
442 return Stream.unwrap(
443 EnvironmentRegistry.pipe(Effect.map((registry) => registry.runStream(environmentId, stream))),
444 );
445}
446
447export function followStreamInEnvironment<A, E, R>(
448 environmentId: EnvironmentIdType,
449 stream: Stream.Stream<A, E, R>,
450): Stream.Stream<A, E, EnvironmentRegistry | Exclude<R, EnvironmentSupervisor>> {
451 return Stream.unwrap(
452 EnvironmentRegistry.pipe(
453 Effect.map((registry) => registry.followStream(environmentId, stream)),
454 ),
455 );
456}
457
458function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
459 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
460 options: EnvironmentQueryAtomOptions<Input, A, E, EnvironmentSupervisor | R>,
461): (target: {
462 readonly environmentId: EnvironmentIdType;
463 readonly input: Input;
464}) => Atom.Atom<AsyncResult.AsyncResult<A, E | ER | Error>> {
465 const rpcGenerationAtom = Atom.family((environmentId: EnvironmentIdType) =>
466 runtime.atom(
467 followStreamInEnvironment(
468 environmentId,
469 Stream.unwrap(
470 EnvironmentSupervisor.pipe(
471 Effect.map((supervisor) =>
472 SubscriptionRef.changes(supervisor.state).pipe(
473 Stream.filterMap((state) =>
474 state.phase === "connected" ? Result.succeed(state.generation) : Result.failVoid,
475 ),
476 Stream.changes,
477 Stream.map<number, number | null>((generation) => generation),
478 ),
479 ),
480 ),
481 ),
482 ),
483 { initialValue: null },
484 ),
485 );
486 const family = Atom.family((key: string) => {
487 const target = parseEnvironmentRpcKey<Input>(key);
488 const idleTtlMs = options.idleTtlMs ?? 5 * 60_000;
489 const queryAtom = runtime
490 .atom((get) => {
491 const generation = Option.getOrNull(
492 AsyncResult.value(get(rpcGenerationAtom(target.environmentId))),
493 );
494 if (generation === null) {
495 return Effect.never;
496 }
497 return runInEnvironment(target.environmentId, options.execute(target.input));
498 })
499 .pipe(
500 Atom.swr({
501 staleTime: options.staleTimeMs ?? 30_000,
502 revalidateOnMount: true,
503 }),
504 Atom.setIdleTTL(idleTtlMs),
505 );
506 return (
507 options.refreshIntervalMs === undefined
508 ? queryAtom
509 : queryAtom.pipe(Atom.withRefresh(options.refreshIntervalMs))
510 ).pipe(Atom.setIdleTTL(idleTtlMs), Atom.withLabel(`${options.label}:${key}`));
511 });
512 return (target) => family(environmentRpcKey(target));
513}
514
515export function createEnvironmentSubscriptionAtomFamily<R, ER, Input, A, E>(
516 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
517 options: EnvironmentSubscriptionAtomOptions<Input, A, E, EnvironmentSupervisor | R>,
518) {
519 const family = Atom.family((key: string) => {
520 const target = parseEnvironmentRpcKey<Input>(key);
521 return runtime
522 .atom(followStreamInEnvironment(target.environmentId, options.subscribe(target.input)))
523 .pipe(
524 Atom.setIdleTTL(options.idleTtlMs ?? 5 * 60_000),
525 Atom.withLabel(`${options.label}:${key}`),
526 );
527 });
528 return (target: { readonly environmentId: EnvironmentIdType; readonly input: Input }) =>
529 family(environmentRpcKey(target));
530}
531
532export function createEnvironmentCommand<R, ER, Input, A, E>(
533 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
534 options: EnvironmentCommandAtomOptions<Input, A, E, EnvironmentSupervisor | R>,
535) {
536 return createRuntimeCommand(runtime, {
537 label: options.label,
538 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
539 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
540 execute: (target, registry) =>
541 runInEnvironment(
542 target.environmentId,
543 options.execute(target.input, registry, target.environmentId),
544 ),
545 });
546}
547
548function createEnvironmentStreamCommand<R, ER, Input, A, E>(
549 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
550 options: {
551 readonly label: string;
552 readonly execute: (input: Input) => Stream.Stream<A, E, EnvironmentSupervisor | R>;
553 readonly scheduler?: AtomCommandScheduler;
554 readonly concurrency?: AtomCommandConcurrency<{
555 readonly environmentId: EnvironmentIdType;
556 readonly input: Input;
557 }>;
558 },
559) {
560 return createRuntimeStreamCommand(runtime, {
561 label: options.label,
562 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
563 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
564 execute: (target) =>
565 runStreamInEnvironment(target.environmentId, options.execute(target.input)).pipe(
566 Stream.withSpan(options.label),
567 ),
568 });
569}
570
571export function createEnvironmentRpcQueryAtomFamily<R, ER, TTag extends EnvironmentUnaryRpcTag>(
572 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
573 options: {
574 readonly label: string;
575 readonly tag: TTag;
576 readonly staleTimeMs?: number;
577 readonly idleTtlMs?: number;
578 readonly refreshIntervalMs?: number;
579 },
580) {
581 return createEnvironmentQueryAtomFamily(runtime, {
582 label: options.label,
583 ...(options.staleTimeMs === undefined ? {} : { staleTimeMs: options.staleTimeMs }),
584 ...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),
585 ...(options.refreshIntervalMs === undefined
586 ? {}
587 : { refreshIntervalMs: options.refreshIntervalMs }),
588 execute: (input: EnvironmentRpcInput<TTag>) => request(options.tag, input),
589 });
590}
591
592export function createEnvironmentRpcSubscriptionAtomFamily<
593 R,
594 ER,
595 TTag extends EnvironmentSubscriptionRpcTag,
596 B = EnvironmentRpcStreamValue<TTag>,
597>(
598 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
599 options: {
600 readonly label: string;
601 readonly tag: TTag;
602 readonly idleTtlMs?: number;
603 readonly transform?: (
604 stream: Stream.Stream<
605 EnvironmentRpcStreamValue<TTag>,
606 EnvironmentRpcStreamFailure<TTag>,
607 EnvironmentSupervisor | R
608 >,
609 ) => Stream.Stream<B, EnvironmentRpcStreamFailure<TTag>, EnvironmentSupervisor | R>;
610 },
611) {
612 return createEnvironmentSubscriptionAtomFamily(runtime, {
613 label: options.label,
614 ...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),
615 subscribe: (input: EnvironmentRpcInput<TTag>) => {
616 const stream = subscribe(options.tag, input);
617 return options.transform === undefined
618 ? (stream as Stream.Stream<B, EnvironmentRpcStreamFailure<TTag>, EnvironmentSupervisor | R>)
619 : options.transform(stream);
620 },
621 });
622}
623
624export function createEnvironmentRpcCommand<R, ER, TTag extends EnvironmentUnaryRpcTag>(
625 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
626 options: {
627 readonly label: string;
628 readonly tag: TTag;
629 readonly scheduler?: AtomCommandScheduler;
630 readonly concurrency?: AtomCommandConcurrency<{
631 readonly environmentId: EnvironmentIdType;
632 readonly input: EnvironmentRpcInput<TTag>;
633 }>;
634 readonly onSuccess?: (
635 target: {
636 readonly environmentId: EnvironmentIdType;
637 readonly input: EnvironmentRpcInput<TTag>;
638 },
639 registry: AtomRegistry.AtomRegistry,
640 ) => Effect.Effect<void, never, R>;
641 readonly onSettled?: (
642 target: {
643 readonly environmentId: EnvironmentIdType;
644 readonly input: EnvironmentRpcInput<TTag>;
645 },
646 registry: AtomRegistry.AtomRegistry,
647 ) => Effect.Effect<void, never, R>;
648 },
649) {
650 return createEnvironmentCommand(runtime, {
651 label: options.label,
652 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
653 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
654 execute: (input: EnvironmentRpcInput<TTag>, registry, environmentId) => {
655 const target = {
656 environmentId,
657 input,
658 };
659 return request(options.tag, input).pipe(
660 Effect.tap(() => options.onSuccess?.(target, registry) ?? Effect.void),
661 Effect.ensuring(options.onSettled?.(target, registry) ?? Effect.void),
662 );
663 },
664 });
665}
666
667export function createEnvironmentRpcStreamCommand<
668 R,
669 ER,
670 TTag extends EnvironmentStreamCommandRpcTag,
671>(
672 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
673 options: {
674 readonly label: string;
675 readonly tag: TTag;
676 readonly scheduler?: AtomCommandScheduler;
677 readonly concurrency?: AtomCommandConcurrency<{
678 readonly environmentId: EnvironmentIdType;
679 readonly input: EnvironmentRpcInput<TTag>;
680 }>;
681 },
682) {
683 return createEnvironmentStreamCommand(runtime, {
684 label: options.label,
685 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
686 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
687 execute: (input: EnvironmentRpcInput<TTag>) => runStream(options.tag, input),
688 });
689}