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

runtime.ts

711 lines23.3 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 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 }>;
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>;
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;
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;
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;
76​
77export interface AtomCommandReporter {
78 readonly warn: (message: string, cause: Cause.Cause<unknown>) => void;
79 readonly error: (message: string, cause: Cause.Cause<unknown>) => void;
81​
82export interface AtomCommand<W, A, E> {
83 readonly label: string;
84 readonly run: (registry: AtomRegistry.AtomRegistry, input: W) => Promise<AtomCommandResult<A, E>>;
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>;
104​
105interface AtomCommandLatestBatch {
106 execute: () => Promise<AtomCommandResult<unknown, unknown>>;
107 readonly resolve: Array<(result: AtomCommandResult<unknown, unknown>) => void>;
109​
110interface AtomCommandLatestLane {
111 running: boolean;
112 pending: AtomCommandLatestBatch | undefined;
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>>;
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 }
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 };
255​
256/** Runs one effect inside an existing command scheduler lane. */
257export function scheduleAtomCommandEffect<W, A, E, R>(
258 registry: AtomRegistry.AtomRegistry,
259 scheduler: AtomCommandScheduler,
260 concurrency: AtomCommandConcurrency<W>,
261 input: W,
262 effect: Effect.Effect<A, E, R>,
263): Effect.Effect<A, E, R> {
264 return Effect.gen(function* () {
265 const context = yield* Effect.context<R>();
266 const result = yield* Effect.promise((signal) =>
267 scheduler.schedule<W, A, E>(registry, concurrency, input, async () => {
268 const exit = await Effect.runPromiseExitWith(context)(effect, { signal });
269 return Exit.isSuccess(exit)
270 ? AsyncResult.success(exit.value)
271 : AsyncResult.failure(exit.cause);
272 }),
273 );
274 return result._tag === "Success" ? result.value : yield* Effect.failCause(result.cause);
275 });
277​
278export async function runAtomCommand<W, A, E>(
279 registry: AtomRegistry.AtomRegistry,
280 command: AtomCommand<W, A, E>,
281 input: W,
282 options: AtomCommandOptions = {},
283 reporter: AtomCommandReporter = console,
284): Promise<AtomCommandResult<A, E>> {
285 const result = await settleAtomCommandResult(() => command.run(registry, input));
286 reportAtomCommandResult(result, { ...options, label: options.label ?? command.label }, reporter);
287 return result;
289​
290export function mapAtomCommandResult<A, E, B>(
291 result: AtomCommandResult<A, E>,
292 map: (value: A) => B,
293): AtomCommandResult<B, E> {
294 return result._tag === "Success"
295 ? AsyncResult.success(map(result.value))
296 : AsyncResult.failure(result.cause);
298​
299export function isAtomCommandInterrupted(result: AtomCommandResult<unknown, unknown>): boolean {
300 return result._tag === "Failure" && Cause.hasInterruptsOnly(result.cause);
302​
303export function squashAtomCommandFailure(result: {
304 readonly cause: Cause.Cause<unknown>;
305}): unknown {
306 return Cause.squash(result.cause);
308​
309export async function settleAsyncResult<A, E>(
310 execute: () => Promise<Exit.Exit<A, E>>,
311): Promise<SettledAsyncResult<A, E>> {
312 try {
313 return AsyncResult.fromExit(await execute());
314 } catch (defect) {
315 return AsyncResult.failure(Cause.die(defect));
316 }
318​
319export async function executeAtomCommand<A, E>(
320 execute: () => Promise<Exit.Exit<A, E>>,
321 options: AtomCommandOptions = {},
322 reporter: AtomCommandReporter = console,
323): Promise<AtomCommandResult<A, E>> {
324 const result = await settleAsyncResult(execute);
325 reportAtomCommandResult(result, options, reporter);
326 return result;
328​
329export async function executeAtomQuery<A, E>(
330 registry: AtomRegistry.AtomRegistry,
331 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
332 options: AtomCommandOptions = {},
333 reporter: AtomCommandReporter = console,
334): Promise<AtomCommandResult<A, E>> {
335 const query = Effect.scoped(
336 Effect.gen(function* () {
337 yield* AtomRegistry.mount(registry, atom);
338 return yield* AtomRegistry.getResult(registry, atom, {
339 suspendOnWaiting: true,
340 });
341 }),
342 );
343 return executeAtomCommand(() => Effect.runPromiseExit(query), options, reporter);
345​
346export function createRuntimeCommand<R, ER, W, A, E>(
347 runtime: Atom.AtomRuntime<R, ER>,
348 options: {
349 readonly label: string;
350 readonly execute: (input: W, registry: AtomRegistry.AtomRegistry) => Effect.Effect<A, E, R>;
351 readonly scheduler?: AtomCommandScheduler;
352 readonly concurrency?: AtomCommandConcurrency<W>;
353 },
354): AtomCommand<W, A, E | ER> {
355 const scheduler = options.scheduler ?? createAtomCommandScheduler();
356 const concurrency = options.concurrency ?? { mode: "parallel" as const };
357 return {
358 label: options.label,
359 run: (registry, input) =>
360 settleAtomCommandResult(() =>
361 scheduler.schedule(registry, concurrency, input, () => {
362 const atom = runtime
363 .atom(options.execute(input, registry))
364 .pipe(Atom.withLabel(options.label));
365 return executeAtomQuery(registry, atom, { reportDefect: false, reportFailure: false });
366 }),
367 ),
368 };
370​
371export function createRuntimeStreamCommand<R, ER, W, A, E>(
372 runtime: Atom.AtomRuntime<R, ER>,
373 options: {
374 readonly label: string;
375 readonly execute: (input: W, registry: AtomRegistry.AtomRegistry) => Stream.Stream<A, E, R>;
376 readonly scheduler?: AtomCommandScheduler;
377 readonly concurrency?: AtomCommandConcurrency<W>;
378 },
379): AtomCommand<W, A, E | ER | Cause.NoSuchElementError> {
380 const scheduler = options.scheduler ?? createAtomCommandScheduler();
381 const concurrency = options.concurrency ?? { mode: "parallel" as const };
382 return {
383 label: options.label,
384 run: (registry, input) =>
385 settleAtomCommandResult(() =>
386 scheduler.schedule(registry, concurrency, input, () => {
387 const atom = runtime
388 .atom(options.execute(input, registry))
389 .pipe(Atom.withLabel(options.label));
390 return executeAtomQuery(registry, atom, { reportDefect: false, reportFailure: false });
391 }),
392 ),
393 };
395​
396export function reportAtomCommandResult(
397 result: AtomCommandResult<unknown, unknown>,
398 options: AtomCommandOptions = {},
399 reporter: AtomCommandReporter = console,
400): void {
401 if (AsyncResult.isSuccess(result) || Cause.hasInterruptsOnly(result.cause)) {
402 return;
403 }
404​
405 const label = options.label ?? "atom command";
406 if (Cause.hasDies(result.cause)) {
407 if (options.reportDefect ?? true) {
408 reporter.error(`[atom-command] ${label} defected`, result.cause);
409 }
410 } else if (options.reportFailure ?? true) {
411 reporter.warn(`[atom-command] ${label} failed`, result.cause);
412 }
414​
415export async function settlePromise<A>(
416 execute: () => Promise<A>,
417): Promise<AtomCommandResult<A, never>> {
418 try {
419 return AsyncResult.success(await execute());
420 } catch (defect) {
421 return AsyncResult.failure(Cause.die(defect));
422 }
424​
425export function environmentRpcKey<Input>(target: {
426 readonly environmentId: EnvironmentIdType;
427 readonly input: Input;
428}): string {
429 return JSON.stringify([target.environmentId, target.input]);
431​
432function parseEnvironmentRpcKey<Input>(key: string): {
433 readonly environmentId: EnvironmentIdType;
434 readonly input: Input;
435} {
436 const decoded = JSON.parse(key) as [EnvironmentIdType, Input];
437 return {
438 environmentId: EnvironmentId.make(decoded[0]),
439 input: decoded[1],
440 };
442​
443export function runInEnvironment<A, E, R>(
444 environmentId: EnvironmentIdType,
445 effect: Effect.Effect<A, E, R>,
446): Effect.Effect<
447 A,
448 E | EnvironmentNotRegisteredError,
449 EnvironmentRegistry | Exclude<R, EnvironmentSupervisor>
450> {
451 return EnvironmentRegistry.pipe(
452 Effect.flatMap((registry) => registry.run(environmentId, effect)),
453 );
455​
456export function runStreamInEnvironment<A, E, R>(
457 environmentId: EnvironmentIdType,
458 stream: Stream.Stream<A, E, R>,
459): Stream.Stream<
460 A,
461 E | EnvironmentNotRegisteredError,
462 EnvironmentRegistry | Exclude<R, EnvironmentSupervisor>
463> {
464 return Stream.unwrap(
465 EnvironmentRegistry.pipe(Effect.map((registry) => registry.runStream(environmentId, stream))),
466 );
468​
469export function followStreamInEnvironment<A, E, R>(
470 environmentId: EnvironmentIdType,
471 stream: Stream.Stream<A, E, R>,
472): Stream.Stream<A, E, EnvironmentRegistry | Exclude<R, EnvironmentSupervisor>> {
473 return Stream.unwrap(
474 EnvironmentRegistry.pipe(
475 Effect.map((registry) => registry.followStream(environmentId, stream)),
476 ),
477 );
479​
480export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
481 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
482 options: EnvironmentQueryAtomOptions<Input, A, E, EnvironmentSupervisor | R>,
483): (target: {
484 readonly environmentId: EnvironmentIdType;
485 readonly input: Input;
486}) => Atom.Atom<AsyncResult.AsyncResult<A, E | ER | Error>> {
487 const rpcGenerationAtom = Atom.family((environmentId: EnvironmentIdType) =>
488 runtime.atom(
489 followStreamInEnvironment(
490 environmentId,
491 Stream.unwrap(
492 EnvironmentSupervisor.pipe(
493 Effect.map((supervisor) =>
494 SubscriptionRef.changes(supervisor.state).pipe(
495 Stream.filterMap((state) =>
496 state.phase === "connected" ? Result.succeed(state.generation) : Result.failVoid,
497 ),
498 Stream.changes,
499 Stream.map<number, number | null>((generation) => generation),
500 ),
501 ),
502 ),
503 ),
504 ),
505 { initialValue: null },
506 ),
507 );
508 const family = Atom.family((key: string) => {
509 const target = parseEnvironmentRpcKey<Input>(key);
510 const idleTtlMs = options.idleTtlMs ?? 5 * 60_000;
511 const queryAtom = runtime
512 .atom((get) => {
513 const generation = Option.getOrNull(
514 AsyncResult.value(get(rpcGenerationAtom(target.environmentId))),
515 );
516 if (generation === null) {
517 return Effect.never;
518 }
519 return runInEnvironment(target.environmentId, options.execute(target.input));
520 })
521 .pipe(
522 Atom.swr({
523 staleTime: options.staleTimeMs ?? 30_000,
524 revalidateOnMount: true,
525 }),
526 Atom.setIdleTTL(idleTtlMs),
527 );
528 return (
529 options.refreshIntervalMs === undefined
530 ? queryAtom
531 : queryAtom.pipe(Atom.withRefresh(options.refreshIntervalMs))
532 ).pipe(Atom.setIdleTTL(idleTtlMs), Atom.withLabel(`${options.label}:${key}`));
533 });
534 return (target) => family(environmentRpcKey(target));
536​
537export function createEnvironmentSubscriptionAtomFamily<R, ER, Input, A, E>(
538 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
539 options: EnvironmentSubscriptionAtomOptions<Input, A, E, EnvironmentSupervisor | R>,
540) {
541 const family = Atom.family((key: string) => {
542 const target = parseEnvironmentRpcKey<Input>(key);
543 return runtime
544 .atom(followStreamInEnvironment(target.environmentId, options.subscribe(target.input)))
545 .pipe(
546 Atom.setIdleTTL(options.idleTtlMs ?? 5 * 60_000),
547 Atom.withLabel(`${options.label}:${key}`),
548 );
549 });
550 return (target: { readonly environmentId: EnvironmentIdType; readonly input: Input }) =>
551 family(environmentRpcKey(target));
553​
554export function createEnvironmentCommand<R, ER, Input, A, E>(
555 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
556 options: EnvironmentCommandAtomOptions<Input, A, E, EnvironmentSupervisor | R>,
557) {
558 return createRuntimeCommand(runtime, {
559 label: options.label,
560 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
561 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
562 execute: (target, registry) =>
563 runInEnvironment(
564 target.environmentId,
565 options.execute(target.input, registry, target.environmentId),
566 ),
567 });
569​
570function createEnvironmentStreamCommand<R, ER, Input, A, E>(
571 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
572 options: {
573 readonly label: string;
574 readonly execute: (input: Input) => Stream.Stream<A, E, EnvironmentSupervisor | R>;
575 readonly scheduler?: AtomCommandScheduler;
576 readonly concurrency?: AtomCommandConcurrency<{
577 readonly environmentId: EnvironmentIdType;
578 readonly input: Input;
579 }>;
580 },
581) {
582 return createRuntimeStreamCommand(runtime, {
583 label: options.label,
584 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
585 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
586 execute: (target) =>
587 runStreamInEnvironment(target.environmentId, options.execute(target.input)).pipe(
588 Stream.withSpan(options.label),
589 ),
590 });
592​
593export function createEnvironmentRpcQueryAtomFamily<R, ER, TTag extends EnvironmentUnaryRpcTag>(
594 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
595 options: {
596 readonly label: string;
597 readonly tag: TTag;
598 readonly staleTimeMs?: number;
599 readonly idleTtlMs?: number;
600 readonly refreshIntervalMs?: number;
601 },
602) {
603 return createEnvironmentQueryAtomFamily(runtime, {
604 label: options.label,
605 ...(options.staleTimeMs === undefined ? {} : { staleTimeMs: options.staleTimeMs }),
606 ...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),
607 ...(options.refreshIntervalMs === undefined
608 ? {}
609 : { refreshIntervalMs: options.refreshIntervalMs }),
610 execute: (input: EnvironmentRpcInput<TTag>) => request(options.tag, input),
611 });
613​
614export function createEnvironmentRpcSubscriptionAtomFamily<
615 R,
616 ER,
617 TTag extends EnvironmentSubscriptionRpcTag,
618 B = EnvironmentRpcStreamValue<TTag>,
619>(
620 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
621 options: {
622 readonly label: string;
623 readonly tag: TTag;
624 readonly idleTtlMs?: number;
625 readonly transform?: (
626 stream: Stream.Stream<
627 EnvironmentRpcStreamValue<TTag>,
628 EnvironmentRpcStreamFailure<TTag>,
629 EnvironmentSupervisor | R
630 >,
631 ) => Stream.Stream<B, EnvironmentRpcStreamFailure<TTag>, EnvironmentSupervisor | R>;
632 },
633) {
634 return createEnvironmentSubscriptionAtomFamily(runtime, {
635 label: options.label,
636 ...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),
637 subscribe: (input: EnvironmentRpcInput<TTag>) => {
638 const stream = subscribe(options.tag, input);
639 return options.transform === undefined
640 ? (stream as Stream.Stream<B, EnvironmentRpcStreamFailure<TTag>, EnvironmentSupervisor | R>)
641 : options.transform(stream);
642 },
643 });
645​
646export function createEnvironmentRpcCommand<R, ER, TTag extends EnvironmentUnaryRpcTag>(
647 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
648 options: {
649 readonly label: string;
650 readonly tag: TTag;
651 readonly scheduler?: AtomCommandScheduler;
652 readonly concurrency?: AtomCommandConcurrency<{
653 readonly environmentId: EnvironmentIdType;
654 readonly input: EnvironmentRpcInput<TTag>;
655 }>;
656 readonly onSuccess?: (
657 target: {
658 readonly environmentId: EnvironmentIdType;
659 readonly input: EnvironmentRpcInput<TTag>;
660 },
661 registry: AtomRegistry.AtomRegistry,
662 ) => Effect.Effect<void, never, R>;
663 readonly onSettled?: (
664 target: {
665 readonly environmentId: EnvironmentIdType;
666 readonly input: EnvironmentRpcInput<TTag>;
667 },
668 registry: AtomRegistry.AtomRegistry,
669 ) => Effect.Effect<void, never, R>;
670 },
671) {
672 return createEnvironmentCommand(runtime, {
673 label: options.label,
674 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
675 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
676 execute: (input: EnvironmentRpcInput<TTag>, registry, environmentId) => {
677 const target = {
678 environmentId,
679 input,
680 };
681 return request(options.tag, input).pipe(
682 Effect.tap(() => options.onSuccess?.(target, registry) ?? Effect.void),
683 Effect.ensuring(options.onSettled?.(target, registry) ?? Effect.void),
684 );
685 },
686 });
688​
689export function createEnvironmentRpcStreamCommand<
690 R,
691 ER,
692 TTag extends EnvironmentStreamCommandRpcTag,
693>(
694 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
695 options: {
696 readonly label: string;
697 readonly tag: TTag;
698 readonly scheduler?: AtomCommandScheduler;
699 readonly concurrency?: AtomCommandConcurrency<{
700 readonly environmentId: EnvironmentIdType;
701 readonly input: EnvironmentRpcInput<TTag>;
702 }>;
703 },
704) {
705 return createEnvironmentStreamCommand(runtime, {
706 label: options.label,
707 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
708 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
709 execute: (input: EnvironmentRpcInput<TTag>) => runStream(options.tag, input),
710 });