@ipab/cli 0.1.0-rc.6 → 0.1.0-rc.8

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.
Files changed (150) hide show
  1. package/README.md +96 -34
  2. package/dist/app-authoring.d.ts +5 -0
  3. package/dist/app-authoring.d.ts.map +1 -1
  4. package/dist/app-authoring.js +6 -45
  5. package/dist/app-authoring.js.map +1 -1
  6. package/dist/app-prebuild.d.ts +18 -0
  7. package/dist/app-prebuild.d.ts.map +1 -1
  8. package/dist/app-prebuild.js +46 -0
  9. package/dist/app-prebuild.js.map +1 -1
  10. package/dist/app-templates.d.ts +0 -1
  11. package/dist/app-templates.d.ts.map +1 -1
  12. package/dist/app-templates.js +6 -45
  13. package/dist/app-templates.js.map +1 -1
  14. package/dist/builtins/skill.ipab.car +0 -0
  15. package/dist/builtins/template.bundle-viewer.car +0 -0
  16. package/dist/builtins/template.check.car +0 -0
  17. package/dist/builtins/template.node.car +0 -0
  18. package/dist/builtins/template.web-app.car +0 -0
  19. package/dist/builtins.d.ts.map +1 -1
  20. package/dist/builtins.js +1 -39
  21. package/dist/builtins.js.map +1 -1
  22. package/dist/cli.d.ts +1 -0
  23. package/dist/cli.d.ts.map +1 -1
  24. package/dist/cli.js +668 -221
  25. package/dist/cli.js.map +1 -1
  26. package/dist/config.d.ts +1 -1
  27. package/dist/config.d.ts.map +1 -1
  28. package/dist/config.js +9 -4
  29. package/dist/config.js.map +1 -1
  30. package/dist/context.d.ts +20 -0
  31. package/dist/context.d.ts.map +1 -1
  32. package/dist/context.js +31 -2
  33. package/dist/context.js.map +1 -1
  34. package/dist/errors.d.ts +1 -8
  35. package/dist/errors.d.ts.map +1 -1
  36. package/dist/errors.js +1 -20
  37. package/dist/errors.js.map +1 -1
  38. package/dist/host-error.d.ts +9 -0
  39. package/dist/host-error.d.ts.map +1 -0
  40. package/dist/host-error.js +21 -0
  41. package/dist/host-error.js.map +1 -0
  42. package/dist/ipc.d.ts +2 -1
  43. package/dist/ipc.d.ts.map +1 -1
  44. package/dist/ipc.js +61 -3
  45. package/dist/ipc.js.map +1 -1
  46. package/dist/kubo-install.js +1 -1
  47. package/dist/kubo-install.js.map +1 -1
  48. package/dist/kubo-peers.d.ts.map +1 -1
  49. package/dist/kubo-peers.js +2 -1
  50. package/dist/kubo-peers.js.map +1 -1
  51. package/dist/kubo-topology.d.ts +19 -0
  52. package/dist/kubo-topology.d.ts.map +1 -0
  53. package/dist/kubo-topology.js +105 -0
  54. package/dist/kubo-topology.js.map +1 -0
  55. package/dist/kubo.d.ts +10 -0
  56. package/dist/kubo.d.ts.map +1 -1
  57. package/dist/kubo.js +96 -15
  58. package/dist/kubo.js.map +1 -1
  59. package/dist/runtime.d.ts.map +1 -1
  60. package/dist/runtime.js +6 -3
  61. package/dist/runtime.js.map +1 -1
  62. package/dist/skill-definition.d.ts +6 -0
  63. package/dist/skill-definition.d.ts.map +1 -0
  64. package/dist/skill-definition.js +38 -0
  65. package/dist/skill-definition.js.map +1 -0
  66. package/dist/skill-source.d.ts +5 -0
  67. package/dist/skill-source.d.ts.map +1 -0
  68. package/dist/skill-source.js +12 -0
  69. package/dist/skill-source.js.map +1 -0
  70. package/dist/skills.d.ts +84 -0
  71. package/dist/skills.d.ts.map +1 -0
  72. package/dist/skills.js +736 -0
  73. package/dist/skills.js.map +1 -0
  74. package/dist/space-path.d.ts +3 -0
  75. package/dist/space-path.d.ts.map +1 -0
  76. package/dist/space-path.js +17 -0
  77. package/dist/space-path.js.map +1 -0
  78. package/dist/space.d.ts +16 -4
  79. package/dist/space.d.ts.map +1 -1
  80. package/dist/space.js +155 -18
  81. package/dist/space.js.map +1 -1
  82. package/dist/state-storage.js +1 -1
  83. package/dist/state-storage.js.map +1 -1
  84. package/dist/state.d.ts +2 -0
  85. package/dist/state.d.ts.map +1 -1
  86. package/dist/state.js +32 -13
  87. package/dist/state.js.map +1 -1
  88. package/dist/swarm-files.d.ts +2 -2
  89. package/dist/swarm-files.d.ts.map +1 -1
  90. package/dist/swarm-files.js +4 -4
  91. package/dist/swarm-files.js.map +1 -1
  92. package/dist/swarm-meta.d.ts +14 -0
  93. package/dist/swarm-meta.d.ts.map +1 -0
  94. package/dist/swarm-meta.js +65 -0
  95. package/dist/swarm-meta.js.map +1 -0
  96. package/dist/swarm-observations.d.ts +40 -0
  97. package/dist/swarm-observations.d.ts.map +1 -0
  98. package/dist/swarm-observations.js +262 -0
  99. package/dist/swarm-observations.js.map +1 -0
  100. package/dist/swarm.d.ts +172 -6
  101. package/dist/swarm.d.ts.map +1 -1
  102. package/dist/swarm.js +1106 -132
  103. package/dist/swarm.js.map +1 -1
  104. package/dist/template-paths.d.ts +7 -0
  105. package/dist/template-paths.d.ts.map +1 -0
  106. package/dist/template-paths.js +23 -0
  107. package/dist/template-paths.js.map +1 -0
  108. package/dist/template-presentation.d.ts +20 -0
  109. package/dist/template-presentation.d.ts.map +1 -0
  110. package/dist/template-presentation.js +133 -0
  111. package/dist/template-presentation.js.map +1 -0
  112. package/dist/template-source.d.ts +2 -1
  113. package/dist/template-source.d.ts.map +1 -1
  114. package/dist/template-source.js +7 -1
  115. package/dist/template-source.js.map +1 -1
  116. package/dist/templates.d.ts +11 -0
  117. package/dist/templates.d.ts.map +1 -0
  118. package/dist/templates.js +53 -0
  119. package/dist/templates.js.map +1 -0
  120. package/package.json +7 -6
  121. package/src/app-authoring.ts +30 -55
  122. package/src/app-prebuild.ts +61 -0
  123. package/src/app-templates.ts +8 -72
  124. package/src/builtins.ts +2 -48
  125. package/src/cli.ts +830 -247
  126. package/src/config.ts +12 -4
  127. package/src/context.ts +60 -2
  128. package/src/errors.ts +1 -25
  129. package/src/host-error.ts +26 -0
  130. package/src/ipc.ts +82 -2
  131. package/src/kubo-install.ts +1 -1
  132. package/src/kubo-peers.ts +2 -3
  133. package/src/kubo-topology.ts +135 -0
  134. package/src/kubo.ts +134 -25
  135. package/src/runtime.ts +6 -2
  136. package/src/skill-definition.ts +53 -0
  137. package/src/skill-source.ts +15 -0
  138. package/src/skills.ts +1005 -0
  139. package/src/space-path.ts +30 -0
  140. package/src/space.ts +216 -33
  141. package/src/state-storage.ts +1 -1
  142. package/src/state.ts +38 -13
  143. package/src/swarm-files.ts +4 -2
  144. package/src/swarm-meta.ts +90 -0
  145. package/src/swarm-observations.ts +374 -0
  146. package/src/swarm.ts +1637 -193
  147. package/src/template-paths.ts +43 -0
  148. package/src/template-presentation.ts +151 -0
  149. package/src/template-source.ts +9 -2
  150. package/src/templates.ts +77 -0
package/src/config.ts CHANGED
@@ -3,11 +3,12 @@ import { join, resolve } from "node:path";
3
3
  import { CID } from "multiformats/cid";
4
4
  import { readContentConfiguration } from "@ipab/ipfs-store/node";
5
5
  import type { StoreConfiguration } from "@ipab/ipfs-store";
6
- import { HostError, object, syntax } from "./errors.js";
6
+ import { HostError, object, syntax } from "./host-error.js";
7
7
 
8
8
  export type ConfigKey =
9
9
  | "swarm.default"
10
10
  | "swarm.listen"
11
+ | "swarm.pivot"
11
12
  | "swarm.cacheTtl"
12
13
  | "swarm.forceRefresh"
13
14
  | "store.gateway"
@@ -33,6 +34,7 @@ export interface ConfigItem {
33
34
  export const defaults: Record<ConfigKey, ConfigValue> = {
34
35
  "swarm.default": null,
35
36
  "swarm.listen": "lan",
37
+ "swarm.pivot": false,
36
38
  "swarm.cacheTtl": 300,
37
39
  "swarm.forceRefresh": false,
38
40
  "store.gateway": null,
@@ -45,6 +47,7 @@ export const defaults: Record<ConfigKey, ConfigValue> = {
45
47
  };
46
48
  const environments: Partial<Record<ConfigKey, string>> = {
47
49
  "swarm.listen": "IPAB_SWARM_LISTEN",
50
+ "swarm.pivot": "IPAB_SWARM_PIVOT",
48
51
  "swarm.cacheTtl": "IPAB_SWARM_CACHE_TTL",
49
52
  "swarm.forceRefresh": "IPAB_SWARM_FORCE_REFRESH",
50
53
  "store.gateway": "IPAB_STORE_GATEWAY",
@@ -127,10 +130,15 @@ export function parseValue(
127
130
  if (key.startsWith("swarm.") && value === "default")
128
131
  return key === "swarm.cacheTtl" ||
129
132
  key === "swarm.forceRefresh" ||
133
+ key === "swarm.pivot" ||
130
134
  key === "swarm.listen"
131
135
  ? defaults[key]
132
136
  : null;
133
- if (key === "history.enabled" || key === "swarm.forceRefresh") {
137
+ if (
138
+ key === "history.enabled" ||
139
+ key === "swarm.forceRefresh" ||
140
+ key === "swarm.pivot"
141
+ ) {
134
142
  if (value === "true") return true;
135
143
  if (value === "false") return false;
136
144
  }
@@ -177,9 +185,9 @@ export function parseValue(
177
185
  "swarm.cacheTtl requires an integer number of seconds from 0 to 86400.",
178
186
  );
179
187
  }
180
- if (key === "swarm.forceRefresh") {
188
+ if (key === "swarm.forceRefresh" || key === "swarm.pivot") {
181
189
  if (typeof value === "boolean") return value;
182
- syntax("swarm.forceRefresh requires true or false.");
190
+ syntax(`${key} requires true or false.`);
183
191
  }
184
192
  if (key === "swarm.listen") {
185
193
  if (value === "lan" || value === "loopback") return value;
package/src/context.ts CHANGED
@@ -1,15 +1,36 @@
1
- import { HostError } from "./errors.js";
2
- import { CHUNK_BYTES, relativePath } from "./space.js";
1
+ import { HostError } from "./host-error.js";
2
+ import { CHUNK_BYTES, relativePath } from "./space-path.js";
3
3
 
4
4
  import type { BundleInspection } from "./context-types.js";
5
5
  export type { BundleInspection } from "./context-types.js";
6
6
 
7
7
  export interface AppContext {
8
8
  readonly appCid: string;
9
+ /** Opt into explicit Bundle results; exiting without submission cancels the session. */
10
+ beginOpenSession(
11
+ inputCid: string,
12
+ options?: { signal?: AbortSignal; supportedTypes?: readonly string[] },
13
+ ): Promise<void>;
14
+ cancelOpenSession(options?: { signal?: AbortSignal }): Promise<void>;
15
+ /** Retained until execution ends; unchanged files retain their exact UnixFS CIDs. */
16
+ deriveBundle(
17
+ inputCid: string,
18
+ replacements: Record<string, Uint8Array>,
19
+ options?: { signal?: AbortSignal },
20
+ ): Promise<string>;
21
+ /** Select an existing valid Bundle; only a successful process exit commits it. */
22
+ submitBundleResult(
23
+ cid: string,
24
+ options?: { signal?: AbortSignal },
25
+ ): Promise<void>;
9
26
  inspectBundle(
10
27
  reference: string,
11
28
  options?: { signal?: AbortSignal; swarm?: string },
12
29
  ): Promise<BundleInspection>;
30
+ readBlock(
31
+ cid: string,
32
+ options?: { signal?: AbortSignal; maxBytes?: number },
33
+ ): Promise<Uint8Array>;
13
34
  readFile(
14
35
  rootCid: string,
15
36
  path: string,
@@ -133,6 +154,34 @@ export function createContext(port: Port): {
133
154
  }
134
155
  };
135
156
  const context: AppContext = {
157
+ async beginOpenSession(inputCid, options = {}) {
158
+ await rpc(
159
+ "beginOpenSession",
160
+ {
161
+ inputCid,
162
+ ...(options.supportedTypes === undefined
163
+ ? {}
164
+ : { supportedTypes: options.supportedTypes }),
165
+ },
166
+ options.signal,
167
+ );
168
+ },
169
+ async cancelOpenSession(options = {}) {
170
+ await rpc("cancelOpenSession", null, options.signal);
171
+ },
172
+ async deriveBundle(inputCid, replacements, options = {}) {
173
+ const result = await rpc(
174
+ "deriveBundle",
175
+ { inputCid, replacements },
176
+ options.signal,
177
+ );
178
+ if (typeof result !== "string" || !result)
179
+ throw new HostError("Invalid derived Bundle response.");
180
+ return result;
181
+ },
182
+ async submitBundleResult(cid, options = {}) {
183
+ await rpc("submitBundleResult", { cid }, options.signal);
184
+ },
136
185
  async inspectBundle(reference, options = {}) {
137
186
  if (!reference || reference.length > 2048)
138
187
  throw new HostError(
@@ -166,6 +215,15 @@ export function createContext(port: Port): {
166
215
  throw new HostError("Invalid Bundle inspection response.");
167
216
  return data as BundleInspection;
168
217
  },
218
+ async readBlock(cid, options = {}) {
219
+ const maxBytes = options.maxBytes ?? 65536;
220
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 65536)
221
+ throw new HostError("Block read limit must be 1..65536 bytes.");
222
+ const result = await rpc("readBlock", { cid, maxBytes }, options.signal);
223
+ if (!(result instanceof Uint8Array) || result.byteLength > maxBytes)
224
+ throw new HostError("Invalid bounded block response.");
225
+ return result;
226
+ },
169
227
  get appCid() {
170
228
  if (!appCid)
171
229
  throw new HostError("IPAB context identity is not initialized.");
package/src/errors.ts CHANGED
@@ -1,23 +1,4 @@
1
- export class HostError extends Error {
2
- constructor(
3
- message: string,
4
- readonly exitCode = 1,
5
- readonly code = "OPERATION_FAILED",
6
- readonly phase = "state",
7
- ) {
8
- super(message);
9
- this.name = "HostError";
10
- }
11
- }
12
-
13
- export function syntax(message: string): never {
14
- throw new HostError(
15
- `${message} Run ipab --help.`,
16
- 2,
17
- "INVALID_ARGUMENT",
18
- "arguments",
19
- );
20
- }
1
+ export { HostError, object, syntax } from "./host-error.js";
21
2
 
22
3
  export function message(error: unknown): string {
23
4
  let text =
@@ -38,9 +19,4 @@ export function message(error: unknown): string {
38
19
  });
39
20
  }
40
21
 
41
- export function object(value: unknown, label: string): Record<string, unknown> {
42
- if (!value || typeof value !== "object" || Array.isArray(value))
43
- throw new HostError(`Invalid ${label}.`);
44
- return value as Record<string, unknown>;
45
- }
46
22
  import { ContentBundleError } from "@ipab/bundle";
@@ -0,0 +1,26 @@
1
+ export class HostError extends Error {
2
+ constructor(
3
+ message: string,
4
+ readonly exitCode = 1,
5
+ readonly code = "OPERATION_FAILED",
6
+ readonly phase = "state",
7
+ ) {
8
+ super(message);
9
+ this.name = "HostError";
10
+ }
11
+ }
12
+
13
+ export function syntax(message: string): never {
14
+ throw new HostError(
15
+ `${message} Run ipab --help.`,
16
+ 2,
17
+ "INVALID_ARGUMENT",
18
+ "arguments",
19
+ );
20
+ }
21
+
22
+ export function object(value: unknown, label: string): Record<string, unknown> {
23
+ if (!value || typeof value !== "object" || Array.isArray(value))
24
+ throw new HostError(`Invalid ${label}.`);
25
+ return value as Record<string, unknown>;
26
+ }
package/src/ipc.ts CHANGED
@@ -4,7 +4,12 @@ import { openBundle } from "@ipab/bundle";
4
4
  import { CID } from "multiformats/cid";
5
5
  import { HostError, message, object } from "./errors.js";
6
6
  import { requestFrame, type BundleInspection, type Reply } from "./context.js";
7
- import { CHUNK_BYTES, type OutputSpace, relativePath } from "./space.js";
7
+ import {
8
+ CHUNK_BYTES,
9
+ deriveBundle,
10
+ type OutputSpace,
11
+ relativePath,
12
+ } from "./space.js";
8
13
  import type { Ownership } from "./history.js";
9
14
 
10
15
  class ByteQueue implements AsyncIterable<Uint8Array> {
@@ -81,6 +86,7 @@ export class ContextServer {
81
86
  signal: AbortSignal,
82
87
  swarm?: string,
83
88
  ) => Promise<Pick<BundleInspection, "cid" | "targetCid" | "swarm">>,
89
+ readonly supportedTypes?: ReadonlySet<string>,
84
90
  ) {
85
91
  child.on("message", this.receive);
86
92
  }
@@ -122,8 +128,14 @@ export class ContextServer {
122
128
  if (controller.signal.aborted) {
123
129
  if (frame.operation === "read")
124
130
  await this.cancelRead(Number(result), controller.signal.reason);
125
- if (frame.operation === "link")
131
+ if (
132
+ ["link", "beginOpenSession", "cancelOpenSession"].includes(
133
+ frame.operation,
134
+ )
135
+ )
126
136
  this.output.fail(controller.signal.reason);
137
+ if (frame.operation === "submitBundleResult")
138
+ this.output.discardBundleResult();
127
139
  controller.signal.throwIfAborted();
128
140
  }
129
141
  return result;
@@ -159,6 +171,74 @@ export class ContextServer {
159
171
  ): Promise<unknown> {
160
172
  signal.throwIfAborted();
161
173
  if (operation === "identity") return this.appCid;
174
+ if (operation === "readBlock") {
175
+ const data = object(args, "block read request");
176
+ if (
177
+ typeof data.cid !== "string" ||
178
+ typeof data.maxBytes !== "number" ||
179
+ !Number.isSafeInteger(data.maxBytes) ||
180
+ data.maxBytes < 1 ||
181
+ data.maxBytes > 65536
182
+ )
183
+ throw new HostError("Block read limit must be 1..65536 bytes.");
184
+ const cid = CID.parse(data.cid);
185
+ if (cid.toV1().toString() !== data.cid)
186
+ throw new HostError("Block reads require an exact canonical CID.");
187
+ const bytes = await this.store.block.get(data.cid, { signal });
188
+ signal.throwIfAborted();
189
+ if (bytes.byteLength > data.maxBytes)
190
+ throw new HostError("Block exceeds the requested read limit.");
191
+ return bytes;
192
+ }
193
+ if (operation === "deriveBundle") {
194
+ const data = object(args, "Bundle derivation request");
195
+ if (typeof data.inputCid !== "string")
196
+ throw new HostError("Bundle derivation requires an exact input CID.");
197
+ return deriveBundle(
198
+ data.inputCid,
199
+ data.replacements,
200
+ this.store,
201
+ this.owner,
202
+ signal,
203
+ );
204
+ }
205
+ if (
206
+ ["beginOpenSession", "submitBundleResult", "cancelOpenSession"].includes(
207
+ operation,
208
+ )
209
+ ) {
210
+ let validSubmission = false;
211
+ try {
212
+ if (operation === "cancelOpenSession") this.output.cancelOpenSession();
213
+ else {
214
+ const data = object(args, "Bundle result request");
215
+ const cid =
216
+ operation === "beginOpenSession" ? data.inputCid : data.cid;
217
+ if (typeof cid !== "string") {
218
+ const error = new HostError("Bundle result requires an exact CID.");
219
+ this.output.fail(error);
220
+ throw error;
221
+ }
222
+ if (operation === "beginOpenSession")
223
+ await this.output.beginOpenSession(
224
+ cid,
225
+ signal,
226
+ this.supportedTypes,
227
+ data.supportedTypes,
228
+ );
229
+ else {
230
+ validSubmission = true;
231
+ await this.output.submitBundleResult(cid, signal);
232
+ }
233
+ }
234
+ signal.throwIfAborted();
235
+ return null;
236
+ } catch (error) {
237
+ if (!validSubmission) this.output.fail(error);
238
+ else if (signal.aborted) this.output.discardBundleResult();
239
+ throw error;
240
+ }
241
+ }
162
242
  if (operation === "inspectBundle") {
163
243
  const request = object(args, "Bundle inspection request");
164
244
  if (
@@ -847,7 +847,7 @@ export async function kuboBinary(
847
847
  [
848
848
  "id",
849
849
  "swarm connect",
850
- "swarm peering ls",
850
+ "diag datastore put",
851
851
  "dag import",
852
852
  "dag export",
853
853
  "pin add",
package/src/kubo-peers.ts CHANGED
@@ -22,9 +22,8 @@ export function advertisedIps(
22
22
  if (
23
23
  !item.internal &&
24
24
  item.family === "IPv4" &&
25
- /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.)/.test(
26
- item.address,
27
- )
25
+ !/^(?:0\.|127\.|169\.254\.)/.test(item.address) &&
26
+ Number(item.address.split(".")[0]) < 224
28
27
  )
29
28
  ips.add(item.address);
30
29
  }
@@ -0,0 +1,135 @@
1
+ import { object } from "./errors.js";
2
+ import type { PeeringPeer } from "./kubo-peering.js";
3
+
4
+ export function topologyConfig(
5
+ config: Record<string, unknown>,
6
+ pivot: boolean,
7
+ peers: readonly PeeringPeer[],
8
+ loopback: boolean,
9
+ ): Record<string, unknown> {
10
+ const swarm = object(config.Swarm, "Kubo Swarm configuration");
11
+ const addresses = peers
12
+ .flatMap(({ ID, Addrs }) => Addrs.map((address) => `${address}/p2p/${ID}`))
13
+ .sort();
14
+ return {
15
+ ...config,
16
+ Bootstrap: addresses,
17
+ Peering: { Peers: [] },
18
+ AutoConf: { Enabled: false },
19
+ AutoTLS: { Enabled: false },
20
+ AutoNAT: { ServiceMode: "disabled" },
21
+ Ipns: {
22
+ ...object(config.Ipns ?? {}, "Kubo IPNS configuration"),
23
+ DelegatedPublishers: [],
24
+ },
25
+ Routing: {
26
+ Type: pivot ? "dhtserver" : "dhtclient",
27
+ DelegatedRouters: [],
28
+ LoopbackAddressesOnLanDHT: loopback,
29
+ },
30
+ Internal: {
31
+ ...object(config.Internal ?? {}, "Kubo Internal configuration"),
32
+ // Private swarms cannot use public AutoNAT to activate their hop service.
33
+ // This is a role declaration, not a verified Internet reachability claim.
34
+ Libp2pForceReachability: pivot ? "public" : "private",
35
+ NonPublicAddrPublishing: true,
36
+ },
37
+ Discovery: { MDNS: { Enabled: false } },
38
+ Swarm: {
39
+ ...swarm,
40
+ EnableHolePunching: true,
41
+ RelayClient: {
42
+ Enabled: true,
43
+ // libp2p counts static entries before grouping candidates by PeerID.
44
+ // One entry per ID avoids a three-minute wait for duplicate candidates;
45
+ // Bootstrap supplies the complete address set to the same peerstore.
46
+ StaticRelays: peers
47
+ .flatMap(({ ID, Addrs }) =>
48
+ Addrs[0] ? [`${Addrs[0]}/p2p/${ID}`] : [],
49
+ )
50
+ .sort(),
51
+ },
52
+ RelayService: {
53
+ ...object(swarm.RelayService ?? {}, "Kubo relay service"),
54
+ Enabled: pivot,
55
+ },
56
+ },
57
+ };
58
+ }
59
+
60
+ export interface PivotCandidate {
61
+ addresses: string[];
62
+ failures: number;
63
+ retryAt: number;
64
+ probe: "success" | "failure" | "unknown";
65
+ probedAt: number | null;
66
+ error: string | null;
67
+ }
68
+
69
+ export class PivotCandidates {
70
+ private readonly candidates = new Map<string, PivotCandidate>();
71
+
72
+ reconcile(profiles: ReadonlyMap<string, readonly string[]>) {
73
+ for (const id of this.candidates.keys())
74
+ if (!profiles.has(id)) this.candidates.delete(id);
75
+ for (const [id, values] of profiles) {
76
+ const addresses = [...new Set(values)].sort();
77
+ const current = this.candidates.get(id);
78
+ if (JSON.stringify(current?.addresses) !== JSON.stringify(addresses))
79
+ this.candidates.set(id, {
80
+ addresses,
81
+ failures: 0,
82
+ retryAt: 0,
83
+ probe: "unknown",
84
+ probedAt: null,
85
+ error: null,
86
+ });
87
+ }
88
+ }
89
+
90
+ known(id: string): readonly string[] | undefined {
91
+ return this.candidates.get(id)?.addresses;
92
+ }
93
+
94
+ observations(): Map<string, PivotCandidate> {
95
+ return new Map(
96
+ [...this.candidates].map(([id, value]) => [
97
+ id,
98
+ { ...value, addresses: [...value.addresses] },
99
+ ]),
100
+ );
101
+ }
102
+
103
+ active(now = Date.now()): Map<string, readonly string[]> {
104
+ return new Map(
105
+ [...this.candidates]
106
+ .filter(([, value]) => value.addresses.length && value.retryAt <= now)
107
+ .map(([id, value]) => [id, value.addresses]),
108
+ );
109
+ }
110
+
111
+ result(
112
+ id: string,
113
+ healthy: boolean,
114
+ now = Date.now(),
115
+ random = Math.random(),
116
+ error: string | null = null,
117
+ ) {
118
+ const candidate = this.candidates.get(id);
119
+ if (!candidate) return;
120
+ candidate.probe = healthy ? "success" : "failure";
121
+ candidate.probedAt = now;
122
+ candidate.error = error;
123
+ if (healthy) {
124
+ candidate.failures = 0;
125
+ candidate.retryAt = 0;
126
+ } else {
127
+ candidate.failures++;
128
+ if (candidate.failures >= 3)
129
+ candidate.retryAt =
130
+ now +
131
+ Math.min(900_000, 60_000 * 2 ** Math.min(candidate.failures - 3, 4)) *
132
+ (0.8 + random * 0.4);
133
+ }
134
+ }
135
+ }