| 508 | * @internal |
| 509 | */ |
| 510 | export const make = (options: Options) => { |
| 511 | let closed = false |
| 512 | let current = new Proxy(options) |
| 513 | // Retired proxy processes still running commands |
| 514 | const retired = new Set<Proxy>() |
| 515 | const get = () => { |
| 516 | if (current.exited) { |
| 517 | current = new Proxy(options) |
| 518 | } else if (current.credentials !== credentials()) { |
| 519 | // The application changed its credentials, so its commands must not |
| 520 | // run with the old ones |
| 521 | const previous = current |
| 522 | current = new Proxy(options) |
| 523 | retired.add(previous) |
| 524 | previous.retire() |
| 525 | } |
| 526 | for (const proxy of retired) { |
| 527 | if (proxy.exited) retired.delete(proxy) |
| 528 | } |
| 529 | return current |
| 530 | } |
| 531 | const toError = toStartError(options) |
| 532 | // Waits, interruptibly, for a proxy process that is ready to take spawns. |
| 533 | // Nothing has been sent while waiting, so interruption has nothing to undo. |
| 534 | const ready: Effect.Effect<Proxy, PlatformError.PlatformError> = Effect.suspend(() => { |
| 535 | if (closed) { |
| 536 | return Effect.fail(PlatformError.systemError({ |
| 537 | _tag: "BadResource", |
| 538 | module: "ChildProcess", |
| 539 | method: "spawn", |
| 540 | description: "The layerProxyProcess layer has been released" |
| 541 | })) |
| 542 | } |
| 543 | const proxy = get() |
| 544 | return Deferred.await(proxy.started).pipe( |
| 545 | Effect.as(proxy), |
| 546 | // Retired by a credential change while starting, so wait for its replacement |
| 547 | Effect.catch((error) => proxy.retired ? ready : Effect.fail(toError(error))) |
| 548 | ) |
| 549 | }) |
| 550 | return { |
| 551 | prepareSpawn: Effect.map( |
| 552 | ready, |
| 553 | (proxy): SpawnProcess => (command, args, options, halfOpen) => proxy.spawn(command, args, options, halfOpen) |
| 554 | ), |
| 555 | /** Waits for the first proxy process to be ready. */ |
| 556 | ready: Effect.suspend(() => Effect.mapError(Deferred.await(current.started), toError)), |
| 557 | currentPid: Effect.sync(() => |
| 558 | !closed && current.ready && !current.exited && current.pid !== undefined |
| 559 | ? Option.some(ProcessId(current.pid)) |
| 560 | : Option.none() |
| 561 | ), |
| 562 | close: Effect.suspend(() => { |
| 563 | closed = true |
| 564 | return Effect.forEach([current, ...retired], (proxy) => proxy.close, { concurrency: "unbounded", discard: true }) |
| 565 | }) |
| 566 | } |
| 567 | } |