@oceanprotocol/lib 9.0.0-next.8 → 9.0.0

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.
@@ -1,15 +1,112 @@
1
1
  import { type Libp2p, type Libp2pOptions } from 'libp2p';
2
+ import { type Multiaddr } from '@multiformats/multiaddr';
2
3
  import { Signer } from 'ethers';
3
4
  import { StorageObject, FileInfo, ComputeJob, ComputeOutput, ComputeAlgorithm, ComputeAsset, ComputeEnvironment, ProviderInitialize, ProviderComputeInitializeResults, UserCustomParameters, ComputeResourceRequest, ComputeJobMetadata, PolicyServerInitializeCommand, PolicyServerPassthroughCommand, dockerRegistryAuth, DownloadResponse, ComputeResultStream, NodeStatus, NodeComputeJob, PersistentStorageAccessList, PersistentStorageBucket, PersistentStorageCreateBucketRequest, PersistentStorageDeleteFileResponse, PersistentStorageFileEntry, PersistentStorageObject, PersistentStorageUpdateBucketResponse, ServiceJob, ServiceJobListed, ServiceListFilters, ServiceRestartParams, ServiceTemplatePublic, ServiceStartParams, ServicePayment, OceanNode, SignerOrAuthTokenOrSignature } from '../../@types/index.js';
4
5
  import { NodeLogEntry } from '../../@types/Provider.js';
5
6
  import { type DDO, type ValidateMetadata } from '@oceanprotocol/ddo-js';
6
7
  import { CID } from 'multiformats/cid';
7
8
  export declare const OCEAN_P2P_PROTOCOL = "/ocean/nodes/1.0.0";
9
+ /**
10
+ * Which tier of {@link P2pProvider.resolvePeer} produced an address set.
11
+ *
12
+ * Returned rather than merely logged because it is the only way to see whether the
13
+ * peer store is earning its keep. An address now lives there as long as the DHT
14
+ * provider record that names it, and the whole point of that was to move resolutions
15
+ * out of the `dht` lane and into `peer-store`; without provenance that is an argument
16
+ * rather than a measurement.
17
+ */
18
+ export type PeerAddressSource = 'connection' | 'peer-store' | 'dht' | 'none';
19
+ /** One answer from {@link P2pProvider.resolvePeer}. */
20
+ export interface ResolvedPeer {
21
+ /**
22
+ * Addresses for the peer: deduplicated, and ordered so a direct public address is
23
+ * tried before a private one and both before anything relayed.
24
+ */
25
+ addresses: Multiaddr[];
26
+ /** The tier that produced `addresses`, or `'none'` when nothing did. */
27
+ source: PeerAddressSource;
28
+ /** True when this answer came from the resolution cache instead of a fresh lookup. */
29
+ cached: boolean;
30
+ }
31
+ /**
32
+ * What went wrong with a P2P operation, as a value.
33
+ *
34
+ * Retry decisions used to be made by testing error *messages* for substrings, which
35
+ * is fragile in a way this file has already paid for: an unrelated error had to have
36
+ * its wording chosen so that it would not accidentally look retryable. A closed set
37
+ * of types cannot be tripped that way.
38
+ *
39
+ * - `resolve_failed` — no address for the peer, from any tier. Nothing was dialled.
40
+ * - `dial_failed` — there were addresses and the transport did not deliver: the dial
41
+ * was refused, or a connection or stream died under the command. Also covers the
42
+ * peer reporting that *it* could not reach the node the command was addressed to.
43
+ * - `protocol_failed` — the exchange itself failed: the peer answered with an error
44
+ * envelope, or answered something this protocol cannot use.
45
+ * - `timeout` — a deadline expired: the caller's signal, a dial budget, or the
46
+ * per-frame idle budget.
47
+ * - `peer_mismatch` — a dial succeeded and the peer on the other end is not the peer
48
+ * that was asked for.
49
+ */
50
+ export type P2pErrorType = 'resolve_failed' | 'dial_failed' | 'protocol_failed' | 'timeout' | 'peer_mismatch';
51
+ /**
52
+ * A P2P failure carrying its {@link P2pErrorType}.
53
+ *
54
+ * Extends `Error` and keeps the message text the untyped code produced, so existing
55
+ * handling — `instanceof Error`, logging, message matching — is unaffected; `type` is
56
+ * additional information, not a replacement for any of it.
57
+ */
58
+ export declare class P2pError extends Error {
59
+ /** What kind of failure this is. */
60
+ readonly type: P2pErrorType;
61
+ /** The peer the operation concerned, when one was known. */
62
+ readonly peerId?: string;
63
+ /**
64
+ * The reply body, when the failure was reported by the peer inside an otherwise
65
+ * well-formed response. Kept so an exhausted retry budget can hand the caller the
66
+ * same object the untyped code returned, instead of raising where it used to return.
67
+ */
68
+ readonly peerResponse?: {
69
+ value: unknown;
70
+ };
71
+ constructor(type: P2pErrorType, message: string, options?: {
72
+ cause?: unknown;
73
+ peerId?: string;
74
+ peerResponse?: {
75
+ value: unknown;
76
+ };
77
+ });
78
+ }
79
+ /**
80
+ * Classifies a thrown value.
81
+ *
82
+ * Errors raised inside this file are already typed, so they answer for themselves;
83
+ * everything else is recognised by its constructor name, which libp2p sets on every
84
+ * error it defines and which — unlike a message — is part of its API.
85
+ *
86
+ * The fallback is `protocol_failed`, and that choice is deliberate: it is the type
87
+ * that is *not* retried. An unrecognised failure gets one attempt rather than six, so
88
+ * a new error from a dependency cannot turn into a retry storm on upgrade.
89
+ */
90
+ export declare function classifyP2pError(err: unknown): P2pErrorType;
91
+ export declare function isRetryableP2pError(type: P2pErrorType): boolean;
8
92
  /**
9
93
  * Optional request payload sent as LP frames after the command JSON; ends with an empty LP frame.
10
94
  * This mirrors ocean-node's `p2pStreamBody` mechanism introduced for true streaming uploads.
11
95
  */
12
96
  export type P2PRequestBodyStream = AsyncIterable<Uint8Array | ArrayBufferView | string>;
97
+ /**
98
+ * One provider of a CID, as returned by {@link P2pProvider.getProvidersForString}.
99
+ *
100
+ * `partial` is set on every record of a walk that ended before it finished — the
101
+ * results are real but the set is incomplete, and the reason is logged.
102
+ */
103
+ export type { Multiaddr } from '@multiformats/multiaddr';
104
+ export interface P2pProviderRecord {
105
+ id: string;
106
+ multiaddrs: Multiaddr[];
107
+ partial?: true;
108
+ error?: string;
109
+ }
13
110
  export interface P2PConfig {
14
111
  /**
15
112
  * Bootstrap peer multiaddrs for DHT peer discovery.
@@ -24,29 +121,76 @@ export interface P2PConfig {
24
121
  /** Base delay between retries in ms. Default: 1000 */
25
122
  retryDelay?: number;
26
123
  /**
27
- * Timeout for DHT peer lookup when dialing a bare peer ID, in ms. Default: 60000.
124
+ * Timeout for DHT peer lookup when dialing a bare peer ID, in ms. Default: 20000.
28
125
  * Intentionally separate from dialTimeout — DHT resolution needs more time than
29
126
  * a direct dial. Once a peer is found and connected, subsequent calls skip this.
127
+ * Composed with the operation's own signal, so the shorter of the two wins.
30
128
  */
31
129
  dhtLookupTimeout?: number;
32
130
  /**
33
- * Enable TCP transport in addition to WebSockets. Default: false.
34
- * Required in Node.js/Electron environments to reach nodes over plain TCP.
35
- * Do NOT enable in browser builds — TCP is not available in browsers.
131
+ * Idle timeout between two frames of a response body, in ms. Default: 60000.
132
+ * Separate from dialTimeout on purpose — a large download or a compute result can
133
+ * legitimately pause between chunks for far longer than a dial may take.
134
+ */
135
+ streamIdleTimeout?: number;
136
+ /**
137
+ * Maximum P2P commands in flight at once. Default: 8. Fanning out to more peers
138
+ * than this queues the surplus instead of burst-dialling past `maxConnections`.
139
+ */
140
+ maxConcurrentRequests?: number;
141
+ /**
142
+ * Ceiling on a buffered command reply, in bytes. Default: 67108864 (64 MiB).
143
+ * A reply past this fails instead of growing until the process runs out of memory.
144
+ */
145
+ maxBufferedCommandBytes?: number;
146
+ /**
147
+ * Ceiling on a buffered P2P download, in bytes. Default: 536870912 (512 MiB).
148
+ * `getDownloadUrl` returns the whole file as one `ArrayBuffer`, so this is the size
149
+ * of the largest file this transport can deliver. Raise it deliberately.
150
+ */
151
+ maxBufferedDownloadBytes?: number;
152
+ /**
153
+ * Enable TCP transport in addition to WebSockets.
154
+ * Defaults to `true` in Node.js/Electron and `false` in a browser or a Web /
155
+ * Service Worker, where TCP does not exist. Set it explicitly only to override
156
+ * that detection.
36
157
  */
37
158
  enableTcp?: boolean;
159
+ /**
160
+ * Maximum number of simultaneous libp2p connections. Default: 32.
161
+ * A client is not a crawler — raise this only if you fan out to many nodes at once.
162
+ */
163
+ maxConnections?: number;
38
164
  /**
39
165
  * Full libp2p node configuration. Fields provided here override ocean.js
40
- * defaults (transports, encrypters, services, connectionManager, etc.).
41
- * Unset fields keep ocean.js defaults.
166
+ * defaults (transports, encrypters, services, etc.). Unset fields keep ocean.js
167
+ * defaults.
168
+ *
169
+ * Three option bags are the exception and are merged **field by field** rather than
170
+ * replaced wholesale: `peerStore`, `connectionManager` and `connectionMonitor`. They
171
+ * are bags of independent values, so setting one field and losing the rest to a
172
+ * library default is never what a caller meant — and for `peerStore` it is actively
173
+ * harmful, since overriding `maxAddressAge` alone would drop `maxPeerAge` to a value
174
+ * *shorter* than it and evict peer entries while their addresses are still valid.
175
+ * Everything else is a whole subsystem and is replaced as stated.
42
176
  */
43
177
  libp2p?: Partial<Libp2pOptions>;
44
178
  /** Additional roles to be marked. Will be used in the future */
45
179
  additionalRoles?: string[];
46
180
  }
181
+ /**
182
+ * The process-wide `P2pProvider`. Every `BaseProvider` uses this one instance, so
183
+ * `setupP2P()` / `stopP2P()` mean the same thing no matter which provider object
184
+ * they were called on.
185
+ */
186
+ export declare function getSharedP2pProvider(): P2pProvider;
47
187
  export declare class P2pProvider {
48
- private p2pConfig;
49
- private libp2pNode;
188
+ private get p2pConfig();
189
+ private set p2pConfig(value);
190
+ private get appliedP2pConfig();
191
+ private set appliedP2pConfig(value);
192
+ private get libp2pNode();
193
+ private set libp2pNode(value);
50
194
  /**
51
195
  * Configure the internal libp2p node used for P2P transport.
52
196
  * Call this once before making P2P requests, e.g.:
@@ -56,23 +200,197 @@ export declare class P2pProvider {
56
200
  * provide DHT entry points so the peer can be located.
57
201
  */
58
202
  setupP2P(config: P2PConfig): Promise<void>;
203
+ /**
204
+ * The one place a peer's addresses come from: active connection, then peer store,
205
+ * then a DHT `findPeer` walk.
206
+ *
207
+ * There used to be two of these. `getConnection` resolved inline under one timeout
208
+ * policy, and the public `getMultiaddrFromPeerId` ran its own walk under another,
209
+ * returning whichever address happened to sit at index 0 of whichever tier answered
210
+ * — peer-store order is insertion order, so two callers asking about the same peer
211
+ * could get different addresses and a relayed one could beat a direct one. Both now
212
+ * come through here and share the dedup, the ordering and the cache.
213
+ *
214
+ * The tiers are ordered by cost and by confidence, and both agree: an open
215
+ * connection is free and proven, the peer store is a local read, and only the DHT
216
+ * costs a network walk. A tier only hands over to the next when it produced no
217
+ * address this runtime could actually dial — a browser handed nothing but TCP
218
+ * addresses has to keep looking, which is what `isDialable` decides — and what the
219
+ * earlier tier found is carried forward rather than discarded, so the answer is
220
+ * always a superset of what any one tier knew.
221
+ *
222
+ * Never throws for a peer it cannot find: an empty `addresses` with `source: 'none'`
223
+ * is the answer, and each caller decides what that means for it.
224
+ */
225
+ private resolvePeer;
226
+ /**
227
+ * Forgets what we know about how to reach `peerId`, so the next call resolves from
228
+ * the tiers again.
229
+ *
230
+ * This is the part of the cache that carries its weight. Serving an address that no
231
+ * longer reaches the peer is worse than not caching at all if there is no way to
232
+ * correct it, so every failure that proves an address wrong — a dial that did not
233
+ * connect, a connection that turned out to be a different peer — calls this. The
234
+ * negative entry goes too: an invalidation is a reason to look again, never a reason
235
+ * to stop looking.
236
+ */
237
+ invalidatePeerResolution(peerId: string): void;
238
+ /**
239
+ * Resolution counters: one lane per tier, plus cache hits, misses and
240
+ * invalidations. A copy, so a reader cannot mutate them.
241
+ *
242
+ * These are what makes the peer store's longer address lifetime observable. Its
243
+ * purpose was to move resolutions out of the `dht` lane and into `peer-store`, and
244
+ * to leave `miss` where a DHT provider record names a peer whose addresses have not
245
+ * been thrown away yet; a peer store holding addresses for too long would instead
246
+ * show up as peer-store hits followed by invalidations.
247
+ */
248
+ getPeerResolutionStats(): Record<string, number>;
249
+ /** Resets the resolution counters. A test seam; a running client never calls it. */
250
+ resetPeerResolutionStats(): void;
251
+ /**
252
+ * The address at which `peerId` is best reached, as a string with the peer id
253
+ * appended.
254
+ *
255
+ * Resolution is the shared one, so the list this picks from is deduplicated and
256
+ * ordered — a direct public address before a private one, and both before anything
257
+ * relayed — where it used to be whatever sat first in whichever tier answered.
258
+ */
59
259
  getMultiaddrFromPeerId(peerId: string): Promise<string>;
60
260
  /** Returns the underlying libp2p node instance, or null if P2P is not initialized. */
61
261
  getLibp2pNode(): Libp2p | null;
262
+ /**
263
+ * Tear the P2P layer down: close open connections, stop the libp2p node and clear
264
+ * it so nothing keeps the process alive.
265
+ *
266
+ * Long-lived Node.js consumers should call this on shutdown — an unstopped node
267
+ * holds sockets, timers and DHT state open indefinitely. (It holds no circuit-relay
268
+ * reservation to drop: ocean.js listens on nothing — `addresses: { listen: [] }` —
269
+ * so it never listens on `/p2p-circuit` and only ever *dials* through a relay.)
270
+ *
271
+ * Safe to call when P2P was never started, and safe to call more than once. A
272
+ * later P2P call lazily creates a fresh node from the same configuration.
273
+ */
274
+ stopP2P(): Promise<void>;
275
+ private tearDownLibp2p;
276
+ /** Alias for {@link stopP2P}, for callers that expect a `dispose()` convention. */
277
+ dispose(): Promise<void>;
62
278
  /** Returns all peers known to the peerStore (discovered via bootstrap, DHT, or connections). */
279
+ /**
280
+ * Every peer this client knows about, with what is currently true of the connection to
281
+ * it.
282
+ *
283
+ * The peer store answers the first half — who is known and at what addresses — and says
284
+ * nothing about the second, which is the half that decides whether a call to that peer
285
+ * will work. A peer can be in the store with three addresses and be unreachable; it can
286
+ * be connected over a circuit relay that will drop the connection after a byte budget;
287
+ * it can be connected only because *it* dialled *us*. None of that is visible from an
288
+ * address list.
289
+ *
290
+ * The connection fields are added to each entry, never replacing anything: `peerId` and
291
+ * `multiaddrs` are unchanged for every existing consumer.
292
+ */
63
293
  getDiscoveredNodes(): Promise<Array<{
64
294
  peerId: string;
65
295
  multiaddrs: string[];
296
+ /** Open connections to this peer right now. `0` means known but not connected. */
297
+ connections: number;
298
+ /** `inbound` when every connection was dialled by the peer, `outbound` when by us. */
299
+ direction?: 'inbound' | 'outbound' | 'mixed';
300
+ /** Transports in use, derived from the connected addresses. */
301
+ transports: string[];
302
+ /**
303
+ * True when *every* open connection is under a circuit-relay budget. Such a peer
304
+ * looks connected and can carry very little before the relay cuts it off.
305
+ */
306
+ limited: boolean;
66
307
  }>>;
308
+ /**
309
+ * Node-wide facts that decide whether P2P can do anything at all, as opposed to whether
310
+ * it is switched on.
311
+ *
312
+ * Separate from {@link getDiscoveredNodes} rather than folded into it because it answers
313
+ * a different question and returns one object rather than a list — and because widening
314
+ * that method's return type would be a breaking change for consumers that destructure
315
+ * its array elements.
316
+ *
317
+ * Every field is optional and absent rather than guessed when libp2p does not expose it:
318
+ * the routing table and the peer store lifetimes have no public accessor, so they are
319
+ * read defensively and simply not reported if the shape moves.
320
+ */
321
+ getP2pDiagnostics(): {
322
+ running: boolean;
323
+ peerId?: string;
324
+ connections: number;
325
+ /**
326
+ * Peers in the DHT routing table. This is the number that decides whether a lookup can
327
+ * start: a query against an empty table finds nothing regardless of how many
328
+ * connections are open, because a connection to a peer that does not speak the DHT
329
+ * protocol is not somewhere a walk can begin.
330
+ */
331
+ routingTablePeers?: number;
332
+ /** `client` or `server`. A library consumer is pinned to `client`. */
333
+ dhtMode?: string;
334
+ /**
335
+ * Peer store lifetimes **as the running node applies them**. Read off the node rather
336
+ * than from configuration, because they are fixed when the node is built: changing the
337
+ * configuration afterwards does nothing until the node is rebuilt, and nothing else
338
+ * would reveal that.
339
+ */
340
+ peerStore?: {
341
+ maxAddressAge?: number;
342
+ maxPeerAge?: number;
343
+ };
344
+ /** The resolution lanes, the same object {@link getPeerResolutionStats} returns. */
345
+ resolution: Record<string, number>;
346
+ };
67
347
  private bufToHex;
348
+ /**
349
+ * Handler for the `/ocean/client/*` protocols. We advertise them over identify so
350
+ * peers can tell what we are, but we do not serve inbound commands yet — so tear
351
+ * the inbound stream down in *both* directions immediately.
352
+ *
353
+ * `close()` is not enough: it closes only the writable end, and the readable end
354
+ * stays open until the remote closes its own writable end. That half-open stream
355
+ * keeps buffering whatever the peer sends until `maxReadBufferLength` forces a
356
+ * reset, and holds one of the `maxInboundStreams` slots for this protocol until
357
+ * then. `closeRead()` cannot fix it either — it needs muxer support for
358
+ * STOP_SENDING, and yamux's `sendCloseRead` is a no-op. So reset the stream: it is
359
+ * immediate, needs no timeout signal (nothing to flush, nothing to await), frees
360
+ * the slot on both sides and tells the peer accurately that we serve nothing here.
361
+ */
68
362
  private handleProtocolCommands;
69
363
  private getOrCreateLibp2pNode;
70
- private toUint8Array;
364
+ private createLibp2pNode;
71
365
  cidFromRawString(data: string): Promise<CID<unknown, 85, 18, 1>>;
72
- getProvidersForString(input: string, signal?: AbortSignal): Promise<Array<{
73
- id: string;
74
- multiaddrs: any[];
75
- }>>;
366
+ /**
367
+ * Providers of a CID derived from `input`, as found on the DHT.
368
+ *
369
+ * A walk that ends early — the signal fired, the deadline passed, routing failed —
370
+ * still yields whatever it found before that, and those results are usable, so they
371
+ * are returned rather than discarded. The failure is logged and every record from a
372
+ * cut-short walk is flagged `partial`, so an empty array with nothing logged means
373
+ * "no providers" while an empty array with a logged error means "the lookup broke".
374
+ */
375
+ getProvidersForString(input: string, signal?: AbortSignal): Promise<P2pProviderRecord[]>;
376
+ /**
377
+ * True when the page we are running in is itself served from a local origin,
378
+ * i.e. the barge / `http://localhost` development case, where dialing a
379
+ * loopback or LAN node is legitimate.
380
+ */
381
+ private isLocalPageOrigin;
382
+ /**
383
+ * Replaces libp2p's default dial gater, which refuses private and loopback
384
+ * addresses whenever the *browser* build is loaded. That build is also what a
385
+ * bundler picks for Node/Electron targets, so the default silently blocks
386
+ * plain-`ws` and local-node dials in environments that can perfectly well make
387
+ * them — which is why this override exists at all.
388
+ *
389
+ * So: allow everything outside a browser, allow local targets when the page
390
+ * itself is local, and only in a genuine remote browser page refuse loopback /
391
+ * private addresses, which are unreachable from there anyway.
392
+ */
393
+ private denyDialMultiaddr;
76
394
  private isDialable;
77
395
  /**
78
396
  * True when the multiaddr does not include the relay `p2p-circuit` protocol segment.
@@ -80,12 +398,104 @@ export declare class P2pProvider {
80
398
  */
81
399
  private isNotP2PCircuit;
82
400
  private peerIdFromMultiaddr;
401
+ /**
402
+ * Budget for a DHT walk. `dhtLookupTimeout` was documented and defaulted here from
403
+ * the start, but the line applying it was commented out — so a lookup silently ran
404
+ * on whatever signal the operation carried: the dial timeout, far too short for a
405
+ * multi-hop walk, or no signal at all, in which case kad-dht's own 180 s default
406
+ * applied. Composed with the operation signal when there is one, so whichever
407
+ * expires first wins.
408
+ */
409
+ private dhtLookupSignal;
410
+ /** Idle timeout between two frames of a response body. */
411
+ private streamIdleTimeoutMs;
412
+ private maxBufferedCommandBytes;
413
+ private maxBufferedDownloadBytes;
414
+ /**
415
+ * Retries one command may make in total, across every kind of failure.
416
+ *
417
+ * A single budget, and that is the point. There used to be two retry paths that each
418
+ * counted up to this number independently, and because one of them recursed from
419
+ * inside the other's `try`, a failing command could branch on both at every depth:
420
+ * with the default of five the worst case was 63 attempts, each preceded by a
421
+ * one-second sleep, rather than the six the value plainly reads as.
422
+ *
423
+ * Clamped like the concurrency limit, and for the same reason: a value that is not a
424
+ * usable finite number falls back to the default rather than producing a loop bound
425
+ * nobody intended.
426
+ */
427
+ private maxRetryAttempts;
428
+ /**
429
+ * How long to wait before retry `attempt` (1 for the first retry): the base delay
430
+ * doubled per attempt and capped, then jittered into the upper half of that window.
431
+ *
432
+ * Jitter is the load-bearing half. Every client that saw the same event — a node
433
+ * restarting, a relay dropping, a network blip across a fleet — otherwise computes
434
+ * the same delay from the same constant and comes back in lockstep, which is how a
435
+ * recovering node gets knocked over again by the retries of the clients that noticed
436
+ * it go down. Spreading the return turns one synchronised wave into a ramp.
437
+ *
438
+ * Only the upper half of the window is randomised, rather than all of it, because a
439
+ * retry also needs libp2p to finish tearing down the connection that just failed —
440
+ * the reason the untyped path slept a flat second before retrying. A draw near zero
441
+ * would put the next dial back inside that window.
442
+ */
443
+ private retryBackoffMs;
83
444
  private getConnection;
84
445
  private getNodePublicKey;
85
446
  protected getAuthorization(s: SignerOrAuthTokenOrSignature): string;
86
447
  private getSignedCommandParams;
448
+ /**
449
+ * Dial the peer, send the command, and read the first response frame.
450
+ *
451
+ * The process-wide concurrency gate is taken **here**, not in `sendP2pCommand`.
452
+ * `getDownloadUrl` and `getComputeResult` dial through this method directly and
453
+ * used to take no slot at all — precisely the long-lived bulk transfers that hold a
454
+ * connection for minutes, so a fan-out of 20 downloads still burst 20 simultaneous
455
+ * dials against a 32-connection budget of which ~24 are keep-alives.
456
+ *
457
+ * The slot is handed back to the caller as `release` rather than freed when this
458
+ * function returns. Callers MUST call `release()` once they are done with the response
459
+ * — from a generator's `finally` for a streaming reply, from a `finally` around the
460
+ * read loop for a buffered one. It is idempotent, so releasing twice is harmless.
461
+ *
462
+ * A listener on the stream's 'close' event releases it as well, and that is a
463
+ * leak-guard, not a hand-off. 'close' fires once the stream is finished in both
464
+ * directions, which for any reply small enough to fit in the read buffer — the common
465
+ * case — happens *before* the consumer has read a single frame, so it is usually the
466
+ * 'close' listener that frees the slot and not the consumer. What this gate therefore
467
+ * bounds is dials, streams and in-flight first frames, which is what protects the
468
+ * connection budget: measured peak inbound streams is exactly the limit at 1, 2 and 8
469
+ * across every heavy operation. It does not bound how many finished-but-undrained
470
+ * response bodies a caller may be holding — at a limit of 8, up to 11 consumers were
471
+ * observed iterating a body at once.
472
+ *
473
+ * Deliberately not the other way round. Releasing only from the consumer's `finally`
474
+ * would make the slot travel with the body, at the cost of two worse failures: a
475
+ * caller that holds a body while issuing another P2P call deadlocks against itself at
476
+ * low limits, and a response that is never iterated at all strands its slot for good.
477
+ */
87
478
  private dialAndStream;
479
+ /**
480
+ * Sends one command, retrying under a single policy keyed on the *type* of failure.
481
+ *
482
+ * What this replaces was two policies that did not know about each other: one tested
483
+ * the reply body for `Cannot connect to peer`, the other tested a caught error's
484
+ * message for `closed` or `reset`, and each recursed with its own delay. Because the
485
+ * first recursed from inside the `try` the second guards, a command could take both
486
+ * branches at every depth, so the attempt count compounded instead of adding up.
487
+ * Here there is one loop, one counter and one decision, taken on
488
+ * {@link classifyP2pError} rather than on the wording of a message.
489
+ *
490
+ * Each attempt goes through `dialAndStream` afresh, which is what gives it its own
491
+ * dial deadline — a retry must not inherit the expired budget of the attempt that
492
+ * just failed. The caller's own signal is the exception, deliberately: it is their
493
+ * deadline for the whole operation, so once it has fired there is nothing left to
494
+ * retry inside and the loop stops.
495
+ */
88
496
  private sendP2pCommand;
497
+ /** One attempt at a command. Retries are decided by `sendP2pCommand`. */
498
+ private attemptP2pCommand;
89
499
  /**
90
500
  * Returns node status via P2P STATUS command.
91
501
  * @param {OceanNode} nodeUri - multiaddr of the node
@@ -125,8 +535,14 @@ export declare class P2pProvider {
125
535
  * Sends a DOWNLOAD command to the peer via P2P, reads the binary stream
126
536
  * directly from the lpStream, and returns a DownloadResponse.
127
537
  * The node decrypts the service file and streams raw file data back.
538
+ *
539
+ * @param signal Cancels the whole operation, not just its start: it is honoured by the
540
+ * nonce round-trip, the dial, the first frame *and* every subsequent frame, so a
541
+ * transfer already in progress stops when it fires and the stream is reset so the
542
+ * peer stops sending. Optional — omitting it keeps the previous behaviour exactly,
543
+ * including the dial timeout that applies when no signal is supplied.
128
544
  */
129
- getDownloadUrl(did: string, serviceId: string, fileIndex: number, transferTxId: string, nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, policyServer?: any, userCustomParameters?: UserCustomParameters): Promise<DownloadResponse>;
545
+ getDownloadUrl(did: string, serviceId: string, fileIndex: number, transferTxId: string, nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, policyServer?: any, userCustomParameters?: UserCustomParameters, signal?: AbortSignal): Promise<DownloadResponse>;
130
546
  /**
131
547
  * Start a paid compute job via P2P.
132
548
  */
@@ -145,13 +561,48 @@ export declare class P2pProvider {
145
561
  computeStop(jobId: string, nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, agreementId?: string, signal?: AbortSignal): Promise<ComputeJob | ComputeJob[]>;
146
562
  /**
147
563
  * Get compute status via P2P.
148
- */
149
- computeStatus(nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, jobId?: string, agreementId?: string, signal?: AbortSignal): Promise<ComputeJob | ComputeJob[]>;
564
+ * @param {boolean} includeMetrics Owner-only runtime metrics (`runtimeMetrics`) on the
565
+ * returned job(s). To receive them, the node needs owner credentials: an auth token
566
+ * (`signerOrAuthToken` as a string) is ALWAYS sent, regardless of this flag; a `Signer`'s
567
+ * nonce+signature is only computed and sent when this flag is `true` (skipped otherwise
568
+ * to avoid an extra nonce round-trip on every plain status poll). Omitted (default): the
569
+ * node attaches metrics silently if valid owner credentials made it into the request
570
+ * (true automatically for token callers, false for `Signer` callers unless this flag is
571
+ * set), and returns exactly today's response otherwise. `true`: metrics are required —
572
+ * this method also computes the `Signer`'s signature, and the node answers 400/401 if
573
+ * credentials don't verify. `false`: metrics are never attached.
574
+ */
575
+ computeStatus(nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, jobId?: string, agreementId?: string, signal?: AbortSignal, includeMetrics?: boolean): Promise<NodeComputeJob | NodeComputeJob[]>;
150
576
  /**
151
577
  * Get compute result as an async generator of Uint8Array chunks via P2P.
152
578
  * Supports resumable downloads via `offset` (byte position to resume from).
579
+ *
580
+ * @param signal Cancels the whole operation, not just its start: it is honoured by the
581
+ * nonce round-trip, the dial, the first frame *and* every frame the returned
582
+ * generator reads, so a result already being transferred stops when it fires and the
583
+ * stream is reset so the peer stops sending. Optional — omitting it keeps the
584
+ * previous behaviour exactly.
585
+ */
586
+ getComputeResult(nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, jobId: string, index: number, offset?: number, signal?: AbortSignal): Promise<ComputeResultStream>;
587
+ /**
588
+ * Not available over P2P, and now says so instead of pretending otherwise.
589
+ *
590
+ * There is no URL to return. A peer answers `COMPUTE_GET_RESULT` with the result bytes
591
+ * themselves — the protocol carries no addressable location for them, so nothing this
592
+ * method could hand back would be fetchable. Use {@link getComputeResult}, which gives
593
+ * the same bytes as an async iterable of chunks, and takes an `offset` to resume with.
594
+ *
595
+ * What it did before: `COMPUTE_GET_RESULT` is one of the streaming commands, so
596
+ * `sendP2pCommand` returned an async generator, which the declared `Promise<string>`
597
+ * silently cast to a string. A caller got `typeof 'object'` with `Symbol.asyncIterator`
598
+ * on it, `fetch()` received the literal text `[object AsyncGenerator]`, and
599
+ * `url.startsWith(...)` threw a `TypeError`. It also dialled the peer and had it stream
600
+ * an entire result body that nothing would ever read.
601
+ *
602
+ * The declared type is unchanged: the HTTP transport does return a real URL here, and
603
+ * widening this to a union would force every consumer of the dispatching façade to
604
+ * narrow a type that is a plain string on the transport they actually use.
153
605
  */
154
- getComputeResult(nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, jobId: string, index: number, offset?: number): Promise<ComputeResultStream>;
155
606
  getComputeResultUrl(nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, jobId: string, index: number): Promise<string>;
156
607
  /**
157
608
  * Generate an auth token via P2P (auto-signs with Signer).
@@ -185,8 +636,11 @@ export declare class P2pProvider {
185
636
  PolicyServerPassthrough(nodeUri: OceanNode, request: PolicyServerPassthroughCommand, signal?: AbortSignal): Promise<any>;
186
637
  /**
187
638
  * Initialize Policy Server verification via P2P.
639
+ *
640
+ * A distinct command from the passthrough, so the signed message uses its own command
641
+ * string: `consumerAddress + nonce + "PolicyServerInitialize"`.
188
642
  */
189
- initializePSVerification(nodeUri: OceanNode, request: PolicyServerInitializeCommand, signal?: AbortSignal): Promise<any>;
643
+ initializePSVerification(nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, request: PolicyServerInitializeCommand, signal?: AbortSignal): Promise<any>;
190
644
  /**
191
645
  * Download node logs via P2P.
192
646
  */
@@ -219,7 +673,12 @@ export declare class P2pProvider {
219
673
  serviceStop(nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, serviceId: string, signal?: AbortSignal): Promise<ServiceJob[]>;
220
674
  serviceExtend(nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, serviceId: string, additionalDuration: number, payment: ServicePayment, signal?: AbortSignal): Promise<ServiceJob[]>;
221
675
  serviceRestart(nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, serviceId: string, params?: ServiceRestartParams, signal?: AbortSignal): Promise<ServiceJob[]>;
222
- getServiceStatus(nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, serviceId?: string, signal?: AbortSignal): Promise<ServiceJob[]>;
676
+ /**
677
+ * @param {boolean} includeMetrics Owner-only runtime metrics (`runtimeMetrics`) on the
678
+ * returned service(s). This command is already authenticated, so metrics are included
679
+ * BY DEFAULT (omitted / `undefined`); pass `false` to opt out.
680
+ */
681
+ getServiceStatus(nodeUri: OceanNode, signerOrAuthToken: SignerOrAuthTokenOrSignature, serviceId?: string, signal?: AbortSignal, includeMetrics?: boolean): Promise<ServiceJob[]>;
223
682
  /**
224
683
  * Node-wide service listing (SERVICE_LIST) via P2P. Authenticated but NOT owner-scoped:
225
684
  * any consumer identity sees every owner's services, listing-sanitized (no userData, no