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