@deslop/deploy 0.1.1338 → 0.1.1343

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -3526,8 +3526,6 @@ SuccessImpl.prototype = SuccessProto;
3526
3526
  const succeed$11 = (success) => new SuccessImpl(success);
3527
3527
  /** @internal */
3528
3528
  const getSuccess$1 = (self) => isFailure$2(self) ? none$1 : some$2(self.success);
3529
- /** @internal */
3530
- const fromOption$3 = /*#__PURE__*/ dual(2, (self, onNone) => isNone$1(self) ? fail$12(onNone()) : succeed$11(self.value));
3531
3529
  // ../../node_modules/.pnpm/effect@4.1.4/node_modules/effect/dist/Order.js
3532
3530
  /**
3533
3531
  * Defines comparison functions for ordered values.
@@ -5685,39 +5683,6 @@ const succeed$10 = succeed$11;
5685
5683
  * @since 4.0.0
5686
5684
  */
5687
5685
  const fail$11 = fail$12;
5688
- /**
5689
- * Converts an `Option<A>` into a `Result<A, E>`.
5690
- *
5691
- * **When to use**
5692
- *
5693
- * Use when an existing `Option` should become a `Result`, preserving `Some` as
5694
- * success and turning `None` into a caller-provided failure.
5695
- *
5696
- * **Details**
5697
- *
5698
- * - `Some<A>` becomes `Success<A>`
5699
- * - `None` becomes `Failure<E>` using the provided function
5700
- * - Supports both data-first and data-last (piped) usage
5701
- *
5702
- * **Example** (Converting an Option to a Result)
5703
- *
5704
- * ```ts import.meta.vitest
5705
- * import { Option, Result } from "effect"
5706
- *
5707
- * Result.fromOption(Option.some(1), () => "missing") // => Result.succeed(1)
5708
- *
5709
- * Result.fromOption(Option.none(), () => "missing") // => Result.fail("missing")
5710
- * ```
5711
- *
5712
- * @see {@link getSuccess} to extract the success value as an Option
5713
- * @see {@link getFailure} to extract the failure value as an Option
5714
- * @see {@link fromNullishOr} to build a Result from nullable values
5715
- *
5716
- * @stability stable
5717
- * @category constructors
5718
- * @since 2.0.0
5719
- */
5720
- const fromOption$2 = fromOption$3;
5721
5686
  const try_$2 = (evaluate) => {
5722
5687
  if (isFunction(evaluate)) try {
5723
5688
  return succeed$10(evaluate());
@@ -12043,19 +12008,6 @@ const all$2 = (arg, options) => {
12043
12008
  return suspend$4(() => map$9(forEach$2(Object.entries(arg), ([key, effect]) => map$9(options?.mode === "result" ? result$2(effect) : effect, (value) => [key, value]), { concurrency: options?.concurrency }), Object.fromEntries));
12044
12009
  };
12045
12010
  /** @internal */
12046
- const findFirstFilter$1 = /*#__PURE__*/ dual((args) => isIterable(args[0]) && !isEffect$1(args[0]), (elements, filter) => suspend$4(() => {
12047
- const iterator = elements[Symbol.iterator]();
12048
- const next = iterator.next();
12049
- if (!next.done) return findFirstFilterLoop(iterator, 0, filter, next.value);
12050
- return succeed$9(none());
12051
- }));
12052
- const findFirstFilterLoop = (iterator, index, filter, value) => flatMap$5(filter(value, index), (result) => {
12053
- if (isSuccess$1(result)) return succeed$9(some$1(result.success));
12054
- const next = iterator.next();
12055
- if (!next.done) return findFirstFilterLoop(iterator, index + 1, filter, next.value);
12056
- return succeed$9(none());
12057
- });
12058
- /** @internal */
12059
12011
  const whileLoop$1 = /*#__PURE__*/ makePrimitive$1({
12060
12012
  op: "While",
12061
12013
  [contA](value, fiber) {
@@ -13431,6 +13383,51 @@ const filterInterruptors = causeFilterInterruptors;
13431
13383
  */
13432
13384
  const prettyErrors = causePrettyErrors;
13433
13385
  /**
13386
+ * Formats a `Cause` as a human-readable string for logging or debugging.
13387
+ *
13388
+ * **When to use**
13389
+ *
13390
+ * Use to render a whole cause as one human-readable string for logs or
13391
+ * diagnostics.
13392
+ *
13393
+ * **Details**
13394
+ *
13395
+ * Delegates to {@link prettyErrors} to convert each reason to an `Error`,
13396
+ * then joins their stack traces with newlines. Nested `Error.cause` chains
13397
+ * are rendered inline with indentation:
13398
+ *
13399
+ * ```text
13400
+ * ErrorName: message
13401
+ * at ...
13402
+ * at ... {
13403
+ * [cause]: NestedError: message
13404
+ * at ...
13405
+ * }
13406
+ * ```
13407
+ *
13408
+ * Span annotations are appended to the relevant stack frames when available.
13409
+ *
13410
+ * **Gotchas**
13411
+ *
13412
+ * Rendering an empty cause produces an empty string because there are no
13413
+ * errors to render.
13414
+ *
13415
+ * **Example** (Rendering a cause)
13416
+ *
13417
+ * ```ts import.meta.vitest
13418
+ * import { Cause } from "effect"
13419
+ *
13420
+ * Cause.pretty(Cause.fail("something went wrong")).includes("something went wrong") // => true
13421
+ * ```
13422
+ *
13423
+ * @see {@link prettyErrors} — get the individual `Error` instances
13424
+ *
13425
+ * @stability stable
13426
+ * @category formatting
13427
+ * @since 2.0.0
13428
+ */
13429
+ const pretty = causePretty;
13430
+ /**
13434
13431
  * Checks whether an arbitrary value is a `NoSuchElementError`.
13435
13432
  *
13436
13433
  * **Example** (Checking the runtime type)
@@ -18564,26 +18561,6 @@ const isEffect = isEffect$1;
18564
18561
  */
18565
18562
  const all$1 = all$2;
18566
18563
  /**
18567
- * Returns the first value that passes an effectful `FilterEffect`.
18568
- *
18569
- * **When to use**
18570
- *
18571
- * Use when you need to find the first element that satisfies an effectful
18572
- * filter returning a `Result`, which also transforms the matching element.
18573
- *
18574
- * **Details**
18575
- *
18576
- * The filter receives the element and index. Evaluation short-circuits on the
18577
- * first `Result.succeed` and returns the transformed value in `Option.some`.
18578
- *
18579
- * @see {@link findFirst} for the simpler effectful predicate-based variant
18580
- *
18581
- * @stability stable
18582
- * @category collecting
18583
- * @since 4.0.0
18584
- */
18585
- const findFirstFilter = findFirstFilter$1;
18586
- /**
18587
18564
  * Executes an effectful operation for each element in an `Iterable`.
18588
18565
  *
18589
18566
  * **When to use**
@@ -53879,30 +53856,31 @@ const make$55 = /*#__PURE__*/ sync(() => {
53879
53856
  });
53880
53857
  var PendingInvalidation = class extends (/*#__PURE__*/ Service$1()("effect/reactivity/Reactivity/PendingInvalidation")) {};
53881
53858
  /**
53882
- * Wraps an effect so the supplied keys are invalidated after the effect succeeds.
53859
+ * Runs an effect as a stream of query results tied to the supplied invalidation
53860
+ * keys.
53883
53861
  *
53884
- * **Gotchas**
53862
+ * **Details**
53885
53863
  *
53886
- * If the effect fails, the keys are not invalidated.
53864
+ * The effect runs initially and reruns whenever the keys are invalidated.
53887
53865
  *
53888
53866
  * @stability unstable
53889
53867
  * @category accessors
53890
53868
  * @since 4.0.0
53891
53869
  */
53892
- const mutation = /*#__PURE__*/ dual(2, (effect, keys) => Reactivity.use((_) => _.mutation(keys, effect)));
53870
+ const stream$3 = /*#__PURE__*/ dual(2, (effect, keys) => Reactivity.use((r) => r.query(keys, effect)).pipe(map$7(fromQueue), unwrap$4));
53893
53871
  /**
53894
- * Runs an effect as a stream of query results tied to the supplied invalidation
53895
- * keys.
53872
+ * Invalidates the supplied keys through the `Reactivity` service.
53896
53873
  *
53897
53874
  * **Details**
53898
53875
  *
53899
- * The effect runs initially and reruns whenever the keys are invalidated.
53876
+ * Registered queries for matching keys are rerun immediately, or collected until
53877
+ * the enclosing reactivity batch completes.
53900
53878
  *
53901
53879
  * @stability unstable
53902
53880
  * @category accessors
53903
53881
  * @since 4.0.0
53904
53882
  */
53905
- const stream$3 = /*#__PURE__*/ dual(2, (effect, keys) => Reactivity.use((r) => r.query(keys, effect)).pipe(map$7(fromQueue), unwrap$4));
53883
+ const invalidate = (keys) => Reactivity.use((r) => r.invalidate(keys));
53906
53884
  /**
53907
53885
  * The default layer that provides an in-memory `Reactivity` service.
53908
53886
  *
@@ -111774,7 +111752,7 @@ const void_ = (options) => {
111774
111752
  // ../../packages/runtime/src/server/store.ts
111775
111753
  const checkoutRoot = fnUntraced(function* (directory) {
111776
111754
  const path = yield* Path$1;
111777
- if (getOrElse$1(yield* option$1((yield* FileSystem).exists(path.join(directory, "pnpm-workspace.yaml"))), constFalse$1)) return some$1(directory);
111755
+ if (yield* (yield* FileSystem).exists(path.join(directory, "pnpm-workspace.yaml"))) return some$1(directory);
111778
111756
  if (path.dirname(directory) === directory) return none();
111779
111757
  return yield* checkoutRoot(path.dirname(directory));
111780
111758
  });
@@ -112065,16 +112043,27 @@ const updateRelease = fnUntraced(function* (name) {
112065
112043
  "--registry=https://registry.npmjs.org",
112066
112044
  `@deslop/${name}@${latest}`
112067
112045
  ]), "5 minutes");
112068
- const previous = yield* option$1(fs.readLink(path.join(root, "current")));
112069
- yield* activateRelease(name, path.join(directory, "node_modules", "@deslop", name));
112070
- yield* restartService(name);
112071
- const kept = [latest, ...toArray(map$13(previous, (link) => path.basename(path.resolve(link, "../../.."))))];
112046
+ const previous = yield* fs.readLink(path.join(root, "current"));
112047
+ yield* uninterruptible(gen(function* () {
112048
+ yield* activateRelease(name, path.join(directory, "node_modules", "@deslop", name));
112049
+ const restarted = yield* exit(restartService(name));
112050
+ if (isSuccess(restarted)) return;
112051
+ const restored = yield* exit(activateRelease(name, previous));
112052
+ return yield* AppError.make({
112053
+ cause: restarted.cause,
112054
+ message: `Restart failed: ${pretty(restarted.cause)}. ${match$3(restored, {
112055
+ onFailure: (cause) => `The previous current link could not be restored: ${pretty(cause)}`,
112056
+ onSuccess: constant("The previous current link was restored; service state is unknown")
112057
+ })}`
112058
+ });
112059
+ }));
112060
+ const kept = [latest, path.basename(path.resolve(root, previous, "../../.."))];
112072
112061
  yield* pipe(yield* fs.readDirectory(path.join(root, "releases")), difference(kept), forEach$1((entry) => fs.remove(path.join(root, "releases", entry), { recursive: true }), { concurrency: 1 }));
112073
112062
  return `Updated ${name} from ${running} to ${latest}\n`;
112074
112063
  });
112075
112064
  // ../../packages/runtime/src/server/cli.ts
112076
112065
  const DEFAULT_HOST = "127.0.0.1";
112077
- const TailnetSelf = Struct$2({ Self: Struct$2({ DNSName: String$6 }) });
112066
+ const TailnetSelf = Struct$2({ Self: Struct$2({ DNSName: NonEmptyString }) });
112078
112067
  const SETTINGS = {
112079
112068
  DOMAIN: {
112080
112069
  description: "Parent domain for Deslop apps; without it every caller is the developer",
@@ -112090,13 +112079,9 @@ const SETTINGS = {
112090
112079
  const configProvider = fnUntraced(function* (given, defaultPort) {
112091
112080
  const port = given["PORT"] ?? `${defaultPort}`;
112092
112081
  const name = yield* appName;
112093
- const tailnet = yield* pipe(executeProcess("tailscale", ["status", "--json"]), flatMap$3(decodeUnknownEffect(fromJsonString(TailnetSelf))), map$7((status) => replace(/\.$/u, "")(status.Self.DNSName)), timeout("5 seconds"), option$1);
112094
- const urls = match$8(fromUndefinedOr(given["DOMAIN"]), {
112095
- onNone: () => ({ APP_URL: pipe(tailnet, filter$7(isNonEmpty$1), match$8({
112096
- onNone: () => `http://localhost:${port}`,
112097
- onSome: (host) => `https://${host}:${port}`
112098
- })) }),
112099
- onSome: (domain) => ({
112082
+ const urls = yield* match$8(fromUndefinedOr(given["DOMAIN"]), {
112083
+ onNone: () => pipe(executeProcess("tailscale", ["status", "--json"]), flatMap$3(decodeUnknownEffect(fromJsonString(TailnetSelf))), map$7((status) => ({ APP_URL: `https://${replace(/\.$/u, "")(status.Self.DNSName)}:${port}` })), timeout("5 seconds")),
112084
+ onSome: (domain) => succeed$5({
112100
112085
  APP_URL: `https://${name}.${domain}`,
112101
112086
  AUTH_URL: `https://auth.${domain}`,
112102
112087
  GATEWAY_URL: `https://gateway.${domain}`,
@@ -112419,16 +112404,25 @@ const TIME_FRAME_DURATIONS = {
112419
112404
  function timeFrameDuration(frame) {
112420
112405
  return TIME_FRAME_DURATIONS[frame];
112421
112406
  }
112422
- const DateTimeUtcFromFiniteMillis = pipe(Finite, decodeTo(DateTimeUtc, {
112407
+ const DateTimeUtcFromFiniteMillis = pipe(Finite.check(isBetween({
112408
+ maximum: 864e13,
112409
+ minimum: -864e13
112410
+ })), decodeTo(DateTimeUtc, {
112423
112411
  decode: transform$3((value) => mapEpochMillis(makeUnsafe$5(0), () => value)),
112424
112412
  encode: transform$3(toEpochMillis)
112425
112413
  }));
112426
112414
  const DurationFromFiniteMillis = pipe(Finite, decodeTo(DurationFromMillis));
112427
- pipe(Finite, decodeTo(DateTimeUtc, {
112415
+ pipe(Finite.check(isBetween({
112416
+ maximum: 864e10,
112417
+ minimum: -864e10
112418
+ })), decodeTo(DateTimeUtc, {
112428
112419
  decode: transform$3((seconds) => mapEpochMillis(makeUnsafe$5(0), () => seconds * 1e3)),
112429
112420
  encode: transform$3((at) => toEpochMillis(at) / 1e3)
112430
112421
  }));
112431
- pipe(Int$1, decodeTo(DateTimeUtc, {
112422
+ pipe(Int$1.check(isBetween({
112423
+ maximum: 864e10,
112424
+ minimum: -864e10
112425
+ })), decodeTo(DateTimeUtc, {
112432
112426
  decode: transform$3((value) => makeUnsafe$5(value * 1e3)),
112433
112427
  encode: transform$3(toEpochSeconds)
112434
112428
  }));
@@ -112797,6 +112791,12 @@ const MachineHistory = Struct$2({
112797
112791
  time: DateTimeUtcFromFiniteMillis,
112798
112792
  worker: WorkerId
112799
112793
  });
112794
+ const VmStatPages = Struct$2({
112795
+ "Anonymous pages": FiniteFromString,
112796
+ "Pages occupied by compressor": FiniteFromString,
112797
+ "Pages purgeable": FiniteFromString,
112798
+ "Pages wired down": FiniteFromString
112799
+ });
112800
112800
  // src/rpcs/contracts.ts
112801
112801
  var PeerRpcAuth = class extends Service()("@deslop/deploy/rpcs/PeerRpcAuth", { error: AuthError }) {};
112802
112802
  var RpcContracts = class extends make$27(make$29("metrics.watch", {
@@ -113050,16 +113050,20 @@ function exitFailure(status) {
113050
113050
  return failureReason("exit-code", status, true);
113051
113051
  }
113052
113052
  function unitFailures(text) {
113053
- return pipe(trim(text), split$1(/\n\s*\n/u), filter$5(isNonEmpty$1), fromIterableWith((block) => {
113053
+ return pipe(trim(text), split$1(/\n\s*\n/u), filter$5(isNonEmpty$1), flatMap$6((block) => {
113054
113054
  const fields = pipe(block, split$1("\n"), filter$5(includes("=")), fromIterableWith((line) => {
113055
113055
  const [key, ...value] = split$1(line, "=");
113056
113056
  return [key, join$4(value, "=")];
113057
113057
  }));
113058
- return [UnitId.make(fields["Id"] ?? ""), {
113058
+ const id = fields["Id"] ?? "";
113059
+ const result = fields["Result"] ?? "";
113060
+ const status = parse$2(fields["ExecMainStatus"] ?? "");
113061
+ if (!isNonEmpty$1(id) || !isNonEmpty$1(result) || isNone(status) || !isNonEmpty$1(fields["ExecMainCode"] ?? "")) return [];
113062
+ return [[UnitId.make(id), {
113059
113063
  at: map$13(parse$2(replace(/^@/u, "")(fields["StateChangeTimestamp"] ?? "")), (seconds) => mapEpochMillis(makeUnsafe$5(0), () => seconds * 1e3)),
113060
- reason: failureReason(fields["Result"] ?? "", getOrElse$1(parse$2(fields["ExecMainStatus"] ?? ""), constant(0)), fields["ExecMainCode"] !== "0")
113061
- }];
113062
- }));
113064
+ reason: failureReason(result, getOrThrow$1(status), fields["ExecMainCode"] !== "0")
113065
+ }]];
113066
+ }), fromEntries);
113063
113067
  }
113064
113068
  // src/services/inventory/lib/launchd.ts
113065
113069
  function applicationBundle(path) {
@@ -113666,11 +113670,14 @@ function processStatus(status) {
113666
113670
  const at = getOrThrow$1(indexOf(":")(line));
113667
113671
  return [slice(0, at)(line), trim(slice(at + 1)(line))];
113668
113672
  }));
113673
+ function field(name) {
113674
+ return pipe(get$12(values, name), filter$7(isNonEmpty$1), getOrUndefined$1);
113675
+ }
113669
113676
  return {
113670
113677
  memory: decodeSync(ResidentMemoryFromKiB)(split$1(values["VmRSS"] ?? "", /\s+/u)[0] || "0"),
113671
113678
  name: values["Name"] ?? "",
113672
- parent: decodeSync(ProcessIdFromString)(values["PPid"] ?? ""),
113673
- pid: decodeSync(ProcessIdFromString)(values["Pid"] ?? "")
113679
+ parent: decodeUnknownSync(ProcessIdFromString)(field("PPid")),
113680
+ pid: decodeUnknownSync(ProcessIdFromString)(field("Pid"))
113674
113681
  };
113675
113682
  }
113676
113683
  function commandArgs(cmdline) {
@@ -113817,6 +113824,8 @@ function portOf(address) {
113817
113824
  function socketLine(line) {
113818
113825
  const fields = split$1(trim(line), /\s+/u);
113819
113826
  const address = fields[4] ?? "";
113827
+ const state = fields[1] ?? "";
113828
+ if (!contains$1(["tcp", "udp"], fields[0]) || !isNonEmpty$1(state) || !isNonEmpty$1(address)) return none();
113820
113829
  return map$13(portOf(address), (port) => ({
113821
113830
  address,
113822
113831
  port,
@@ -113825,7 +113834,7 @@ function socketLine(line) {
113825
113834
  pid
113826
113835
  }))),
113827
113836
  protocol: fields[0],
113828
- state: fields[1] ?? "listening"
113837
+ state
113829
113838
  }));
113830
113839
  }
113831
113840
  function lsofSocket(file) {
@@ -113930,59 +113939,65 @@ function probeSocket(listener, process) {
113930
113939
  return listener.protocol === "tcp" && listener.port >= 1024 && isSome(match$2(/^(?:127\.0\.0\.1|0\.0\.0\.0):/u)(listener.address)) && isNone(match$2(/^(?:postgres|redis|ssh|cloudflared|tailscaled|caddy)$/u)(process));
113931
113940
  }
113932
113941
  // src/services/inventory/service.ts
113933
- function portItems(sockets, worker, http, origin) {
113934
- return forEach$1(sockets, fnUntraced(function* (socket) {
113935
- const unit = yield* match$8(socket.process, {
113936
- onNone: () => succeedNone,
113937
- onSome: (match) => origin.unit(match.pid)
113938
- });
113939
- const process = yield* match$8(socket.process, {
113940
- onNone: () => succeedNone,
113941
- onSome: fnUntraced(function* (match) {
113942
+ function portItems(sockets, worker, http, source) {
113943
+ return gen(function* () {
113944
+ const metadata = fromIterable$5(yield* pipe(getSomes(map$10(sockets, (socket) => socket.process)), dedupeWith((left, right) => left.pid === right.pid), forEach$1(fnUntraced(function* (process) {
113945
+ return [process.pid, {
113946
+ cwd: yield* match(startsWith("node")(process.name), {
113947
+ onFalse: () => succeedNone,
113948
+ onTrue: () => source.cwd(process.pid)
113949
+ }),
113950
+ unit: yield* source.unit(process.pid)
113951
+ }];
113952
+ }), { concurrency: 8 })));
113953
+ return yield* forEach$1(sockets, fnUntraced(function* (socket) {
113954
+ const origin = flatMap$8(socket.process, (process) => get$8(metadata, process.pid));
113955
+ const unit = flatMap$8(origin, (process) => process.unit);
113956
+ const process = flatMap$8(socket.process, (match) => {
113942
113957
  if (!startsWith("node")(match.name)) return liftPredicate(match.name, isNonEmpty$1);
113943
- return pipe(yield* origin.cwd(match.pid), match$8({
113958
+ return pipe(flatMap$8(origin, (reading) => reading.cwd), match$8({
113944
113959
  onNone: () => match.name,
113945
113960
  onSome: (cwd) => socketProcess(match.name, cwd)
113946
113961
  }), liftPredicate(isNonEmpty$1));
113947
- })
113948
- });
113949
- const response = yield* match(probeSocket(socket, getOrElse$1(process, constant(""))), {
113950
- onFalse: () => succeed$5(none()),
113951
- onTrue: fnUntraced(function* () {
113952
- return yield* pipe(http.head(`http://127.0.0.1:${socket.port}/`, { headers: toHeaders(new NativeSpan({
113953
- annotations: empty$18(),
113954
- kind: "internal",
113955
- links: [],
113956
- name: "Deploy.probe",
113957
- parent: none(),
113958
- sampled: false,
113959
- startTime: 0n
113960
- })) }), map$7((value) => ({
113961
- http: true,
113962
- ui: value.status >= 200 && value.status < 400 && includes("text/html")(value.headers["content-type"] ?? "")
113963
- })), provideService$2(RequestInit, { redirect: "manual" }), provideService$2(TracerDisabledWhen, constTrue), timeout(millis(700)), option$1);
113964
- })
113965
- });
113966
- return InventoryItem.make({
113967
- address: some$1(socket.address),
113968
- detail: `${socket.address} · ${getOrElse$1(process, constant("process unavailable"))}`,
113969
- http: some$1(exists(response, (value) => value.http)),
113970
- id: ItemId.make(`${worker}:port:${socket.protocol}:${socket.address}`),
113971
- kind: "port",
113972
- name: socket.address,
113973
- port: some$1(socket.port),
113974
- process,
113975
- protocol: some$1(match(socket.protocol === "udp", {
113976
- onFalse: constant("tcp"),
113977
- onTrue: constant("udp")
113978
- })),
113979
- state: socket.state,
113980
- ui: some$1(exists(response, (value) => value.ui)),
113981
- unit,
113982
- url: none(),
113983
- worker
113984
- });
113985
- }), { concurrency: 8 });
113962
+ });
113963
+ const response = yield* match(probeSocket(socket, getOrElse$1(process, constant(""))), {
113964
+ onFalse: () => succeed$5(none()),
113965
+ onTrue: fnUntraced(function* () {
113966
+ return yield* pipe(http.head(`http://127.0.0.1:${socket.port}/`, { headers: toHeaders(new NativeSpan({
113967
+ annotations: empty$18(),
113968
+ kind: "internal",
113969
+ links: [],
113970
+ name: "Deploy.probe",
113971
+ parent: none(),
113972
+ sampled: false,
113973
+ startTime: 0n
113974
+ })) }), map$7((value) => ({
113975
+ http: true,
113976
+ ui: value.status >= 200 && value.status < 400 && includes("text/html")(value.headers["content-type"] ?? "")
113977
+ })), provideService$2(RequestInit, { redirect: "manual" }), provideService$2(TracerDisabledWhen, constTrue), timeout(millis(700)), option$1);
113978
+ })
113979
+ });
113980
+ return InventoryItem.make({
113981
+ address: some$1(socket.address),
113982
+ detail: `${socket.address} · ${getOrElse$1(process, constant("process unavailable"))}`,
113983
+ http: some$1(exists(response, (value) => value.http)),
113984
+ id: ItemId.make(`${worker}:port:${socket.protocol}:${socket.address}`),
113985
+ kind: "port",
113986
+ name: socket.address,
113987
+ port: some$1(socket.port),
113988
+ process,
113989
+ protocol: some$1(match(socket.protocol === "udp", {
113990
+ onFalse: constant("tcp"),
113991
+ onTrue: constant("udp")
113992
+ })),
113993
+ state: socket.state,
113994
+ ui: some$1(exists(response, (value) => value.ui)),
113995
+ unit,
113996
+ url: none(),
113997
+ worker
113998
+ });
113999
+ }), { concurrency: 8 });
114000
+ });
113986
114001
  }
113987
114002
  function collect(name, effect) {
113988
114003
  return pipe(effect, timeout(seconds(10)), withSpan("Inventory.collect", { attributes: { source: name } }), match$1({
@@ -114002,6 +114017,9 @@ function collect(name, effect) {
114002
114017
  })
114003
114018
  }));
114004
114019
  }
114020
+ function containerRows(listing) {
114021
+ return pipe(listing, split$1("\n"), filter$5(isNonEmpty$1), map$10((line) => decodeOption(fromJsonString(Container))(line)), getSomes);
114022
+ }
114005
114023
  var Inventory = class extends Service$1()("@deslop/deploy/services/inventory/service/Inventory") {
114006
114024
  static layer = effect(this, gen(function* () {
114007
114025
  const fs = yield* FileSystem;
@@ -114013,6 +114031,9 @@ var Inventory = class extends Service$1()("@deslop/deploy/services/inventory/ser
114013
114031
  message: cause.message
114014
114032
  })), provideService$2(ChildProcessSpawner, spawner));
114015
114033
  }
114034
+ function systemctlRows(args, row) {
114035
+ return pipe(command("systemctl", args), flatMap$3(decodeUnknownEffect(fromJsonString(ArraySchema(Unknown)))), map$7((rows) => getSomes(map$10(rows, (item) => decodeUnknownOption(row)(item)))));
114036
+ }
114016
114037
  const worker = yield* decodeEffect(WorkerId)(hostname());
114017
114038
  const selfProcess = yield* decodeEffect(ProcessId)(pid);
114018
114039
  const processState = yield* make$56(none());
@@ -114026,21 +114047,21 @@ var Inventory = class extends Service$1()("@deslop/deploy/services/inventory/ser
114026
114047
  onTrue: () => []
114027
114048
  });
114028
114049
  const listed = yield* all$1({
114029
- rows: flatMap$3(command("systemctl", [
114050
+ rows: systemctlRows([
114030
114051
  ...scopeFlags,
114031
114052
  "list-units",
114032
114053
  "--all",
114033
114054
  "--type=service",
114034
114055
  "--output=json",
114035
114056
  "--no-pager"
114036
- ]), decodeUnknownEffect(fromJsonString(ArraySchema(Unit)))),
114037
- timers: flatMap$3(command("systemctl", [
114057
+ ], Unit),
114058
+ timers: systemctlRows([
114038
114059
  ...scopeFlags,
114039
114060
  "list-timers",
114040
114061
  "--all",
114041
114062
  "--output=json",
114042
114063
  "--no-pager"
114043
- ]), decodeUnknownEffect(fromJsonString(ArraySchema(Timer))))
114064
+ ], Timer)
114044
114065
  }, { concurrency: "unbounded" });
114045
114066
  const scheduled = fromIterable$5(getSomes(map$10(listed.timers, (timer) => map$13(timer.activates, (unit) => [unit, map$13(timer.next, (next) => mapEpochMillis(next, Math.floor))]))));
114046
114067
  const failed = pipe(listed.rows, filter$5((row) => row.active === "failed"), map$10((row) => row.unit));
@@ -114080,13 +114101,13 @@ var Inventory = class extends Service$1()("@deslop/deploy/services/inventory/ser
114080
114101
  "--all",
114081
114102
  "--format",
114082
114103
  "{{json .}}"
114083
- ]), flatMap$3((text) => pipe(text, split$1("\n"), filter$5(isNonEmpty$1), forEach$1((line) => decodeEffect(fromJsonString(Container))(line), { concurrency: 1 }))), map$7((rows) => map$10(rows, (row) => InventoryItem.make({
114104
+ ]), map$7(containerRows), map$7((rows) => map$10(rows, (row) => InventoryItem.make({
114084
114105
  active: contains$1([
114085
114106
  "running",
114086
114107
  "restarting",
114087
114108
  "paused"
114088
114109
  ], row.State),
114089
- bindings: some$1([...map$10(fromIterable$8(matchAll(/traefik\.http\.services\.[^=,]+\.loadbalancer\.server\.port=([0-9]+)/gu)(getOrElse$1(row.Labels, constant("")))), (match) => ({
114110
+ bindings: some$1(filter$5([...map$10(fromIterable$8(matchAll(/traefik\.http\.services\.[^=,]+\.loadbalancer\.server\.port=([0-9]+)/gu)(getOrElse$1(row.Labels, constant("")))), (match) => ({
114090
114111
  address: "container",
114091
114112
  port: getOrElse$1(parse$2(match[1] ?? ""), constant(0)),
114092
114113
  protocol: "tcp"
@@ -114097,7 +114118,7 @@ var Inventory = class extends Service$1()("@deslop/deploy/services/inventory/ser
114097
114118
  onFalse: constant("tcp"),
114098
114119
  onTrue: constant("udp")
114099
114120
  })
114100
- }))]),
114121
+ }))], (binding) => binding.port > 0 && binding.port <= 65535)),
114101
114122
  detail: row.Status,
114102
114123
  health: match(includes("unhealthy")(row.Status) || isSome(match$2(/Exited \([1-9]/u)(row.Status)), {
114103
114124
  onFalse: () => match(row.State === "restarting", {
@@ -114134,23 +114155,30 @@ var Inventory = class extends Service$1()("@deslop/deploy/services/inventory/ser
114134
114155
  });
114135
114156
  const darwin = gen(function* () {
114136
114157
  const namedAgents = gen(function* () {
114137
- return getSomes(yield* forEach$1(launchAgents(yield* command("launchctl", ["list"])), fnUntraced(function* (agent) {
114158
+ const agents = launchAgents(yield* command("launchctl", ["list"]));
114159
+ const bundleNames = yield* make$71({
114160
+ capacity: agents.length + 1,
114161
+ lookup: fnUntraced(function* (bundle) {
114162
+ return yield* pipe(command("/usr/bin/plutil", [
114163
+ "-convert",
114164
+ "json",
114165
+ "-o",
114166
+ "-",
114167
+ `${bundle}/Contents/Info.plist`
114168
+ ]), flatMap$3(decodeEffect(fromJsonString(Struct$2({
114169
+ CFBundleDisplayName: optionalKey(Unknown),
114170
+ CFBundleName: optionalKey(Unknown)
114171
+ })))), map$7((fields) => pipe([fields.CFBundleDisplayName, fields.CFBundleName], filter$5(isString$1), map$10(trim), findFirst(isNonEmpty$1))), option$1, map$7(flatten$6));
114172
+ })
114173
+ });
114174
+ return getSomes(yield* forEach$1(agents, fnUntraced(function* (agent) {
114138
114175
  if (startsWith("deslop-")(agent.label)) return some$1(agent);
114139
114176
  const program = flatMap$8(yield* option$1(command("launchctl", ["print", `gui/${userInfo().uid}/${agent.label}`])), launchProgram);
114140
114177
  if (exists(program, systemProgram)) return none();
114141
114178
  return yield* pipe(program, flatMap$8(applicationBundle), match$8({
114142
114179
  onNone: () => succeedSome(agent),
114143
114180
  onSome: fnUntraced(function* (bundle) {
114144
- const name = yield* findFirstFilter(["CFBundleDisplayName", "CFBundleName"], (key) => pipe(command("/usr/bin/plutil", [
114145
- "-extract",
114146
- key,
114147
- "raw",
114148
- "-expect",
114149
- "string",
114150
- "-o",
114151
- "-",
114152
- `${bundle}/Contents/Info.plist`
114153
- ]), option$1, map$7((value) => pipe(value, map$13(trim), filter$7(isNonEmpty$1), fromOption$2(constUndefined)))));
114181
+ const name = yield* get$7(bundleNames, bundle);
114154
114182
  return some$1({
114155
114183
  ...agent,
114156
114184
  bundle: some$1(bundle),
@@ -114371,8 +114399,7 @@ var Inventory = class extends Service$1()("@deslop/deploy/services/inventory/ser
114371
114399
  return {
114372
114400
  refresh,
114373
114401
  run: fn("Inventory.run")(function* (input) {
114374
- yield* start(input);
114375
- yield* refresh;
114402
+ yield* onExit$1(start(input), () => refresh);
114376
114403
  }),
114377
114404
  snapshot: get$1(snapshot)
114378
114405
  };
@@ -114389,7 +114416,7 @@ const SERIES = {
114389
114416
  function counters(stat, uptime, time) {
114390
114417
  const values = decodeSync(CpuCounters)(pipe(stat, split$1("\n"), head, getOrElse$1(constant("")), trim, split$1(/\s+/u), drop$1(1), take$3(8)));
114391
114418
  return {
114392
- cpuIdle: millis(((values[3] ?? 0) + (values[4] ?? 0)) * 10),
114419
+ cpuIdle: millis((getOrThrow$1(get$11(values, 3)) + getOrThrow$1(get$11(values, 4))) * 10),
114393
114420
  cpuTotal: millis(sumAll(values) * 10),
114394
114421
  time,
114395
114422
  uptime: seconds(decodeSync(FiniteFromString)(split$1(uptime, " ")[0]))
@@ -114416,13 +114443,11 @@ function cpuCounters(cpus, uptime, time) {
114416
114443
  }
114417
114444
  function vmStatMemory(text, total) {
114418
114445
  const pages = fromEntries(getSomes(pipe(text, split$1("\n"), map$10((line) => map$13(match$2(/^"?([^":]+)"?:\s+([0-9]+)\.$/u)(trim(line)), (match) => [match[1] ?? "", match[2] ?? ""])))));
114419
- const page = decodeSync(FiniteFromString)(pipe(match$2(/page size of ([0-9]+) bytes/u)(text), map$13((match) => match[1] ?? ""), getOrElse$1(constant(""))));
114420
- function count(name) {
114421
- return decodeSync(FiniteFromString)(pages[name] ?? "");
114422
- }
114446
+ const page = decodeUnknownSync(FiniteFromString)(pipe(match$2(/page size of ([0-9]+) bytes/u)(text), flatMap$8(get$11(1)), getOrUndefined$1));
114447
+ const counts = decodeUnknownSync(VmStatPages)(pages);
114423
114448
  return {
114424
114449
  total,
114425
- used: clamp((count("Anonymous pages") - count("Pages purgeable") + count("Pages wired down") + count("Pages occupied by compressor")) * page, {
114450
+ used: clamp((counts["Anonymous pages"] - counts["Pages purgeable"] + counts["Pages wired down"] + counts["Pages occupied by compressor"]) * page, {
114426
114451
  maximum: total,
114427
114452
  minimum: 0
114428
114453
  })
@@ -114474,8 +114499,8 @@ function sample(current, memory, disk, previous, load) {
114474
114499
  return [fields[0], decodeSync(FiniteFromString)(fields[1] ?? "") * 1024];
114475
114500
  }));
114476
114501
  return reading(current, {
114477
- total: values["MemTotal:"] ?? 0,
114478
- used: (values["MemTotal:"] ?? 0) - (values["MemAvailable:"] ?? 0)
114502
+ total: decodeUnknownSync(Finite)(values["MemTotal:"]),
114503
+ used: decodeUnknownSync(Finite)(values["MemTotal:"]) - decodeUnknownSync(Finite)(values["MemAvailable:"])
114479
114504
  }, pipe(disk, match$8({
114480
114505
  onNone: () => [],
114481
114506
  onSome: diskRows
@@ -114761,11 +114786,14 @@ var Metrics = class extends Service$1()("@deslop/deploy/services/metrics/service
114761
114786
  const failure = yield* make$56(none());
114762
114787
  function walk(pending, found) {
114763
114788
  if (isReadonlyArrayEmpty(pending)) return succeed$5(found);
114764
- return pipe(pending, forEach$1((path) => option$1(map$7(fs.readDirectory(`${CGROUP}${path}`), (names) => pipe(names, filter$5((name) => isSome(match$2(/\.(?:slice|scope|service)$/u)(name))), map$10((name) => ({
114789
+ return pipe(pending, forEach$1((path) => pipe(fs.readDirectory(`${CGROUP}${path}`), catchTag("PlatformError", (cause) => {
114790
+ if (isTagged(cause.reason, "NotFound")) return succeed$5(empty$15());
114791
+ return fail$6(cause);
114792
+ }), map$7((names) => pipe(names, filter$5((name) => isSome(match$2(/\.(?:slice|scope|service)$/u)(name))), map$10((name) => ({
114765
114793
  app: appCgroup(`${path}/${name}`, names),
114766
114794
  path: CgroupPath.make(`${path}/${name}`)
114767
114795
  }))))), { concurrency: "unbounded" }), flatMap$3((levels) => {
114768
- const children = flatten$4(getSomes(levels));
114796
+ const children = flatten$4(levels);
114769
114797
  return walk(pipe(children, filter$5((child) => !child.app && isSome(match$2(/(?:\.slice|\/user@[0-9]+\.service)$/u)(child.path))), map$10((child) => child.path)), [...found, ...pipe(children, filter$5((child) => child.app), map$10((child) => child.path))]);
114770
114798
  }));
114771
114799
  }
@@ -115082,17 +115110,17 @@ var Fleet = class Fleet extends Service$1()("@deslop/deploy/services/fleet/servi
115082
115110
  exposure: input.name,
115083
115111
  worker: input.worker
115084
115112
  });
115085
- if (input.worker === localWorker) return yield* tap$2(exposures.expose(omit(input, ["worker"])), () => inventory.refresh);
115113
+ if (input.worker === localWorker) return yield* onExit$1(exposures.expose(omit(input, ["worker"])), () => inventory.refresh);
115086
115114
  return yield* remote(yield* selectedWorker(input.worker), (client) => client("exposures.apply", omit(input, ["worker"])));
115087
- }, tap$2(() => reactivity.invalidate(["deployInventory"])), asDeployError),
115115
+ }, onExit$1(() => reactivity.invalidate(["deployInventory"])), asDeployError),
115088
115116
  hide: fn("Fleet.hide")(function* (input) {
115089
115117
  yield* annotateCurrentSpan({
115090
115118
  exposure: input.name,
115091
115119
  worker: input.worker
115092
115120
  });
115093
- if (input.worker === localWorker) return yield* tap$2(exposures.hide(input.name), () => inventory.refresh);
115121
+ if (input.worker === localWorker) return yield* onExit$1(exposures.hide(input.name), () => inventory.refresh);
115094
115122
  return yield* remote(yield* selectedWorker(input.worker), (client) => client("exposures.remove", { name: input.name }));
115095
- }, tap$2(() => reactivity.invalidate(["deployInventory"])), asDeployError),
115123
+ }, onExit$1(() => reactivity.invalidate(["deployInventory"])), asDeployError),
115096
115124
  history: fn("Fleet.history")(function* (query) {
115097
115125
  yield* annotateCurrentSpan("minutes", toMinutes(query.minutes));
115098
115126
  return yield* metrics.read(query);
@@ -115103,7 +115131,7 @@ var Fleet = class Fleet extends Service$1()("@deslop/deploy/services/fleet/servi
115103
115131
  minutes: toMinutes(query.minutes),
115104
115132
  workers: workers.length + 1
115105
115133
  });
115106
- return [yield* metrics.read(query), ...yield* forEach$1(workers, (worker) => pipe(remote(worker, (client) => client("metrics.history", query)), timeout(seconds(2)), map$7((value) => ({
115134
+ yield* forEach$1(workers, (worker) => pipe(remote(worker, (client) => client("metrics.history", query)), timeout(seconds(2)), map$7((value) => ({
115107
115135
  ...value,
115108
115136
  worker: worker.name
115109
115137
  })), tapError$3((cause) => logWarning("A worker history could not be read", cause)), catch_$2(fnUntraced(function* (cause) {
@@ -115113,7 +115141,7 @@ var Fleet = class Fleet extends Service$1()("@deslop/deploy/services/fleet/servi
115113
115141
  stale: true,
115114
115142
  worker: worker.name
115115
115143
  };
115116
- })), tap$2((value) => update(lastMetrics, (all) => set$3(all, [worker.name, query.minutes], value)))), { concurrency: "unbounded" })];
115144
+ })), tap$2((value) => update(lastMetrics, (all) => set$3(all, [worker.name, query.minutes], value)))), { concurrency: "unbounded" });
115117
115145
  }),
115118
115146
  run: fn("Fleet.run")(function* (input) {
115119
115147
  yield* annotateCurrentSpan({
@@ -115122,7 +115150,7 @@ var Fleet = class Fleet extends Service$1()("@deslop/deploy/services/fleet/servi
115122
115150
  });
115123
115151
  if (input.worker === localWorker) return yield* inventory.run(omit(input, ["worker"]));
115124
115152
  return yield* remote(yield* selectedWorker(input.worker), (client) => client("inventory.start", omit(input, ["worker"])));
115125
- }, tap$2(() => reactivity.invalidate(["deployInventory"])), mapError$2((cause) => {
115153
+ }, onExit$1(() => reactivity.invalidate(["deployInventory"])), mapError$2((cause) => {
115126
115154
  if (is$2(DeployError)(cause)) return cause;
115127
115155
  return DeployError.make({
115128
115156
  cause,
@@ -115177,7 +115205,7 @@ const RpcHandlers = RpcContracts.toLayer(gen(function* () {
115177
115205
  capacity: size$4(SERIES),
115178
115206
  lookup: (minutes) => {
115179
115207
  const query = { minutes };
115180
- return pipe(fromEffect(fleet.current(query)), concat$1(fromEffect(fleet.metrics(query))), concat$1(merge$1(fromEffectSchedule(fleet.current(query), spaced(min$1(resolution(minutes), seconds(30)))), drain(fromEffectSchedule(fleet.metrics(query), spaced(clamp$1(resolution(minutes), {
115208
+ return pipe(fromEffect(fleet.current(query)), concat$1(fromEffect(andThen(fleet.metrics(query), fleet.current(query)))), concat$1(merge$1(fromEffectSchedule(fleet.current(query), spaced(min$1(resolution(minutes), seconds(30)))), drain(fromEffectSchedule(fleet.metrics(query), spaced(clamp$1(resolution(minutes), {
115181
115209
  maximum: seconds(30),
115182
115210
  minimum: seconds(5)
115183
115211
  })))))), share({
@@ -115189,19 +115217,16 @@ const RpcHandlers = RpcContracts.toLayer(gen(function* () {
115189
115217
  });
115190
115218
  return RpcContracts.of({
115191
115219
  "exposures.apply": fnUntraced(function* (input) {
115192
- const url = yield* exposures.expose(input);
115193
- yield* localInventory.refresh;
115194
- return url;
115195
- }, mutation(["deployInventory"])),
115220
+ return yield* onExit$1(exposures.expose(input), () => localInventory.refresh);
115221
+ }, onExit$1(() => invalidate(["deployInventory"]))),
115196
115222
  "exposures.expose": fleet.expose,
115197
115223
  "exposures.hide": fleet.hide,
115198
115224
  "exposures.remove": fnUntraced(function* (input) {
115199
- yield* exposures.hide(input.name);
115200
- yield* localInventory.refresh;
115201
- }, mutation(["deployInventory"])),
115225
+ yield* onExit$1(exposures.hide(input.name), () => localInventory.refresh);
115226
+ }, onExit$1(() => invalidate(["deployInventory"]))),
115202
115227
  "inventory.run": fleet.run,
115203
115228
  "inventory.snapshot": () => fleet.local,
115204
- "inventory.start": (input) => mutation(localInventory.run(input), ["deployInventory"]),
115229
+ "inventory.start": (input) => onExit$1(localInventory.run(input), () => invalidate(["deployInventory"])),
115205
115230
  "inventory.watch": () => inventory,
115206
115231
  "metrics.history": fleet.history,
115207
115232
  "metrics.watch": (query) => unwrap$4(get$7(metrics, query.minutes))
@@ -115385,7 +115410,7 @@ const ToolHandlers = ToolContracts.toLayer(map$7(Fleet, (fleet) => ToolContracts
115385
115410
  }),
115386
115411
  read_resource_history: fnUntraced(function* (input) {
115387
115412
  const value = yield* all$1({
115388
- machines: fleet.metrics({ minutes: input.minutes }),
115413
+ machines: andThen(fleet.metrics({ minutes: input.minutes }), fleet.current({ minutes: input.minutes })),
115389
115414
  snapshot: fleet.snapshot
115390
115415
  }, { concurrency: "unbounded" });
115391
115416
  yield* checkWorker(value.snapshot, input.worker);