@oceanprotocol/lib 9.0.0-next.11 → 9.0.0-next.12

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.
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Length-prefixed framing for the Ocean P2P protocol: the four flow-control constants, the
3
+ * `lpStream` wrapper that applies them, and the frame reader that can tell a clean
4
+ * end-of-stream from a truncated one.
5
+ *
6
+ * These live in their own module because the four constants only make sense as a set —
7
+ * each is derived from the others, and changing one without the rest reintroduces the
8
+ * silent-discard failure they exist to prevent — and because everything here is about the
9
+ * wire, not about the provider that happens to speak it.
10
+ *
11
+ * Kept byte-for-byte in step with ocean-node's `components/P2P/lpFraming.ts`. Divergence
12
+ * between the two is not a style question: it is one peer reading a different number of
13
+ * bytes than the other one wrote.
14
+ */
15
+ import { lpStream } from '@libp2p/utils';
16
+ import type { Stream } from '@libp2p/interface';
17
+ /** The framed view of a stream that `lpFramedStream` returns. */
18
+ export type LpFramedStream = ReturnType<typeof lpStream>;
19
+ /**
20
+ * Largest length-prefixed frame either side of this protocol will accept.
21
+ *
22
+ * Handed to `lpStream()` as `maxDataLength`, which does two things. A peer declaring a bigger
23
+ * frame fails immediately with `InvalidDataLengthError`, and `lpStream` derives a
24
+ * `maxLengthLength` from it, which caps the length-prefix read — without that cap a peer sending
25
+ * an endless run of varint continuation bytes keeps the prefix loop reading one byte at a time
26
+ * forever.
27
+ *
28
+ * 4 MiB is not a new restriction: it is already the largest frame that can be read at all,
29
+ * because `lpStream`'s default read buffer is 4 MiB and a frame has to fit in the buffer whole
30
+ * before it can be handed over. What changes is the failure mode — a clear error about the
31
+ * declared length instead of an opaque buffer overflow — and that the limit now bounds the
32
+ * flow-control marks below rather than being an accident of a library default.
33
+ *
34
+ * Every frame this protocol emits in practice is far smaller: file and log chunks arrive at the
35
+ * source stream's high-water mark (16—64 KiB), and the largest single frames are whole-payload
36
+ * JSON writes such as a DDO or a status envelope.
37
+ */
38
+ export declare const LP_MAX_FRAME_BYTES: number;
39
+ /**
40
+ * `varint` bytes needed to encode `LP_MAX_FRAME_BYTES`, which is what `lpStream` derives as its
41
+ * `maxLengthLength`. Also the slack on a byte count kept outside `byteStream`: a frame's length
42
+ * prefix is consumed from the read buffer before the frame it belongs to is complete, so such a
43
+ * count can run this far — and no further — ahead of the buffer's real occupancy.
44
+ */
45
+ export declare const LP_MAX_LENGTH_PREFIX_BYTES = 4;
46
+ /**
47
+ * How much the transport may buffer on our behalf while reads are paused.
48
+ *
49
+ * Pausing reads is the only backpressure lever a libp2p stream has: it withholds the muxer's
50
+ * window updates, so the peer's send window drains and it stops. What it cannot do is stop
51
+ * bytes the peer already had permission to send, and those land in the stream's own buffer —
52
+ * which resets the stream if it passes `maxReadBufferLength`.
53
+ *
54
+ * The library's defaults make that reset a certainty rather than a safeguard: yamux lets its
55
+ * receive window double up to `MAX_STREAM_WINDOW` (16 MiB) on a stream that is being drained
56
+ * quickly, while `maxReadBufferLength` stops at 4 MiB. So pausing a stream that has been going
57
+ * fast — exactly the case where a consumer falls behind — resets it. Measured: a 40 MiB transfer
58
+ * died at frame 160 with `Read buffer length of 4194496 exceeded limit of 4194304, read status
59
+ * is paused`, and because an abort discards the stream buffer without ever dispatching it, the
60
+ * byte accounting saw nothing pending and read the truncation as a clean end.
61
+ *
62
+ * So the buffer is raised to the window it may have to absorb. Bytes only accumulate here while
63
+ * a consumer is behind, and the peer stops once its window is spent.
64
+ */
65
+ export declare const LP_PAUSE_BUFFER_BYTES: number;
66
+ /**
67
+ * Backlog at or below which a paused read loop may let the transport deliver again.
68
+ *
69
+ * Pausing while the consumer works on a frame is not on its own enough, because `resume()`
70
+ * dispatches *everything* the stream buffered while paused as a single `message` event: one
71
+ * cycle admits a whole flush and consumes one frame, so a consumer slower than its peer still
72
+ * accumulates without bound. A loop that has fallen behind therefore stays paused and drains
73
+ * what it is already holding, and only lets more in once the backlog is back below this mark.
74
+ *
75
+ * The value is not free to choose. It has to be at least one maximum-size frame plus its length
76
+ * prefix: while paused, the only way to make progress is to read a complete frame out of the
77
+ * backlog, so a lower mark could leave a loop paused on a backlog holding part of a frame with
78
+ * nothing to release it.
79
+ */
80
+ export declare const LP_RESUME_BELOW_BYTES: number;
81
+ /**
82
+ * Read-buffer ceiling for every length-prefixed stream in this protocol, and the ceiling on
83
+ * bytes retained per stream.
84
+ *
85
+ * It has to be passed explicitly. `lpStream()` otherwise defaults `maxBufferSize` to 4 MiB and,
86
+ * when an incoming message pushes the unread backlog past that, `byteStream`'s `message`
87
+ * listener discards the *entire* buffer and rejects its `hasBytes` deferred — which is a no-op
88
+ * when no read is pending, i.e. exactly while a consumer is working on a chunk it was just
89
+ * handed. The discard is therefore silent, and it desynchronises the frame parser: later reads
90
+ * take payload bytes for length prefixes and hand out corrupt, out-of-sequence frames. Verified
91
+ * in `@libp2p/utils` 7.3.2, `dist/src/stream-utils.js`.
92
+ *
93
+ * The size follows from the two marks above rather than being picked: a resume can flush a full
94
+ * pause buffer into the read buffer on top of a backlog that is already at the resume mark, so
95
+ * the ceiling has to clear `LP_PAUSE_BUFFER_BYTES + LP_RESUME_BELOW_BYTES` (20 MiB) with room
96
+ * for the frame in progress. 24 MiB does, and is only approached while a consumer is behind —
97
+ * the resume mark keeps the steady state near one frame.
98
+ */
99
+ export declare const LP_MAX_BUFFER_BYTES: number;
100
+ /**
101
+ * Wraps `stream` in the length-prefixed framing this protocol uses, and makes the stream itself
102
+ * safe to pause. Callers must go through this rather than calling `lpStream()` directly: the
103
+ * defaults it would otherwise take are what silently drop bytes under backpressure.
104
+ */
105
+ export declare function lpFramedStream(stream: Stream): ReturnType<typeof lpStream>;
106
+ /**
107
+ * Backpressure for a length-prefixed read loop: while the consumer is holding a frame, stop the
108
+ * transport dispatching `message` events, so the unread backlog cannot grow past
109
+ * `maxBufferSize` and be dropped. Bytes that arrive while paused are held by the stream itself
110
+ * and flushed on resume, and the muxer stops granting the sender window, so this is real
111
+ * end-to-end backpressure rather than local buffering.
112
+ *
113
+ * Guarded on `readStatus` because `pause()` and `resume()` throw `StreamStateError` once the
114
+ * readable end is closing or closed, which happens on the last frames of every transfer — as
115
+ * soon as the peer has closed its write side and the read buffer has drained.
116
+ */
117
+ export declare function pauseReads(stream: Stream): void;
118
+ /** Counterpart to `pauseReads`: let the transport deliver the next frame. */
119
+ export declare function resumeReads(stream: Stream): void;
120
+ /** Bytes `lpStream`'s default varint length-prefix takes for a frame of this size. */
121
+ export declare function lpPrefixLength(byteLength: number): number;
122
+ export declare function toFrameBytes(chunk: Uint8Array | {
123
+ subarray(): Uint8Array;
124
+ }): Uint8Array;
125
+ /**
126
+ * Length-prefixed frame reader that can tell a clean end-of-stream from a truncated
127
+ * transfer.
128
+ *
129
+ * `lpStream.read()` throws `UnexpectedEOFError` for *both*: the peer closing exactly
130
+ * between frames, and the peer declaring a 10-byte frame, sending 3 bytes and
131
+ * vanishing. Swallowing that error by type — which every read loop here used to do —
132
+ * hands a **truncated payload back as success**, so a cut-short download or compute
133
+ * result looks complete.
134
+ *
135
+ * The discriminator is bytes consumed, not the error's name or message. The message
136
+ * is ambiguous as well: a clean end and a frame cut off inside its varint length
137
+ * prefix both read `stream closed while reading 0/1 bytes`, verified against
138
+ * `@libp2p/utils` 7.3.2 over a real `streamPair`. Every byte the transport delivers
139
+ * arrives as a `message` event — the only path into `lpStream`'s internal buffer — so
140
+ * we count those, and count what fully-read frames account for. Equal totals mean the stream ended on a frame
141
+ * boundary: a clean end. Otherwise bytes arrived that never completed a frame, which
142
+ * is truncation and must propagate to the caller.
143
+ *
144
+ * Constraint on this accounting: the `lpStream` handed to the constructor must never
145
+ * be `unwrap()`ped while this reader is in use. `unwrap()` removes only
146
+ * `byteStream`'s own 'message' listener and then `unshift`s its internal buffer back
147
+ * onto the stream, which re-dispatches those bytes as a fresh 'message' event — our
148
+ * listener is still attached, so it would count them a second time, `pendingBytes`
149
+ * would go positive and `isCleanEnd` would report a clean end-of-stream as
150
+ * truncation. Nothing calls `unwrap()` today; anyone adding a call must detach this
151
+ * reader's listener first.
152
+ */
153
+ export declare class LpFrameReader {
154
+ private readonly lp;
155
+ private received;
156
+ private consumed;
157
+ /** Backlog size at the moment `byteStream` was seen to drop its whole read buffer. */
158
+ private discarded;
159
+ /** Set when the stream ends in an error, whether raised locally or by the peer. */
160
+ private closeError;
161
+ constructor(lp: ReturnType<typeof lpStream>, stream: Stream, maxBufferSize?: number);
162
+ /** Bytes delivered by the transport that are not yet part of a complete frame. */
163
+ get pendingBytes(): number;
164
+ read(options: {
165
+ signal: AbortSignal;
166
+ }): Promise<Uint8Array>;
167
+ /**
168
+ * True when `err` is the graceful end of the stream: an end-of-file thrown with
169
+ * every delivered byte already accounted for by a complete frame. A truncated
170
+ * frame throws the same error type but leaves bytes pending, and returns false.
171
+ */
172
+ isCleanEnd(err: unknown): boolean;
173
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The typed and serialized forms of a single compute-capability advertisement, and the
3
+ * bucketing rule used to keep the number of distinct advertisements small.
4
+ *
5
+ * This module is intentionally pure: no network access, no libp2p, no I/O. It only turns a
6
+ * typed capability into the exact byte string that gets hashed into a content id, and back
7
+ * (conceptually — there is no parser here, only the one-way serializer) again. Two independent
8
+ * codebases compute this same content id from the same rule — one when a compute provider
9
+ * announces what it can run, the other when a caller searches for a provider that can run
10
+ * something — so identical bytes matter more than almost anything else in this file. Nothing
11
+ * here should ever be "obviously equivalent" to what it replaces; it should be identical.
12
+ */
13
+ /** A single compute capability, in typed form — never a hash, never a raw JSON string. */
14
+ export type C2dCapability = {
15
+ /** Whether this is a free-tier or paid capability. */
16
+ free: boolean;
17
+ /**
18
+ * The resource being advertised or queried. Deliberately an open string, not a closed
19
+ * union or enum — `'cpu' | 'ram' | 'disk' | 'gpu'` are simply the resources known today.
20
+ * A compute engine can report any resource name and it serializes and buckets correctly
21
+ * without either side of a search needing to know about it in advance.
22
+ */
23
+ resource: string;
24
+ /**
25
+ * A positive integer, in the resource's own unit (cores for `cpu`, GB for `ram`/`disk`,
26
+ * boards or devices for an accelerator, ...). Never converted to a different unit anywhere
27
+ * in this module — the caller's unit is the serialized unit.
28
+ */
29
+ value: number;
30
+ };
31
+ /**
32
+ * The canonical byte-exact content string for a capability. This is the only thing that ever
33
+ * gets hashed to derive a content id, on either side of a search, and is therefore the single
34
+ * source of truth for it — nothing else in this package (or in a cooperating implementation
35
+ * elsewhere) should ever assemble this string by hand.
36
+ *
37
+ * The shape is `{"c2d":{"free":<boolean>,"<resource>":<integer>}}` — exactly two fields inside
38
+ * the wrapper, `free` first and the resource key second. That order is fixed explicitly below
39
+ * rather than left to however a JS engine would order the keys of an object literal: a resource
40
+ * name that happens to look like an array index (e.g. a purely numeric string) would otherwise
41
+ * be reordered ahead of `free` by the engine's own integer-key ordering rules, silently changing
42
+ * the bytes that get hashed. Building the string directly, field by field, makes that
43
+ * impossible.
44
+ *
45
+ * A multi-dimension request (e.g. `cpu` AND `ram`) is never expressed as a single wider string
46
+ * here — it is an intersection of one call to this function per dimension, handled by the
47
+ * caller.
48
+ */
49
+ export declare function c2dCapabilityContent(cap: C2dCapability): string;
50
+ /**
51
+ * Per-resource bucket-ladder overrides. Ships empty on purpose, and stays empty unless a
52
+ * concrete need for a coarser or differently-spaced ladder shows up for one specific resource.
53
+ *
54
+ * The default rule below — pure doubling, applied identically to every resource — needs no
55
+ * entry here to work for a resource neither side of a search has ever heard of, which is the
56
+ * entire point of keeping this table empty: a new resource type never requires touching this
57
+ * module. Adding an entry here changes what bytes get hashed for that resource, which is a
58
+ * breaking format change like any other, not a routine addition.
59
+ *
60
+ * A ladder, if one is ever added for a resource, must be a strictly ascending list of positive
61
+ * integers; `c2dBucketFor` picks the largest rung that is `<= value`.
62
+ */
63
+ export declare const C2D_BUCKET_OVERRIDES: Readonly<Record<string, readonly number[]>>;
64
+ /**
65
+ * Buckets `value` for `resource`, rounding **down**. Applies to every resource, known or
66
+ * unknown, with no table lookup required for the common case.
67
+ *
68
+ * Both the announce side and the query side of a search call this same function, and both
69
+ * round down: an announcer emits every bucket at or below its true maximum, and a search
70
+ * request is bucketed down to the nearest one it could plausibly find. That produces false
71
+ * positives (a query for `9` buckets to `8` and matches a provider whose real maximum is
72
+ * exactly `8`) and never false negatives (a provider is never excluded because its own bucket
73
+ * rounded below what it can actually do). Missing a capable provider is worse than finding one
74
+ * that turns out, on closer inspection, not to qualify — which is exactly why a caller must
75
+ * verify a candidate against its real capabilities before trusting a bucket match; the bucket
76
+ * is a coarse prefilter, not an answer by itself.
77
+ */
78
+ export declare function c2dBucketFor(resource: string, value: number): number;
@@ -4,3 +4,18 @@
4
4
  */
5
5
  export declare function sleep(ms: number): Promise<unknown>;
6
6
  export declare function isDefined(something: any): boolean;
7
+ /**
8
+ * Returns a copy of the payload with every credential field redacted, at any depth.
9
+ *
10
+ * This must not mutate its input: the caller still needs the real credentials to send the
11
+ * request, and credentials also show up nested (the free-form `policyServer` /
12
+ * `policyServerPassthrough` blobs), so we rebuild containers instead of writing into them.
13
+ *
14
+ * Only plain objects and arrays are walked - Buffers, typed arrays, Dates, streams and the
15
+ * like are passed through untouched.
16
+ *
17
+ * @param {any} value - the payload to redact
18
+ * @param {WeakSet<object>} seen - internal cycle guard
19
+ * @return {any} a redacted copy, safe to log
20
+ */
21
+ export declare function redactSensitiveFields(value: any, seen?: WeakSet<object>): any;
@@ -13,3 +13,4 @@ export * from './OrderUtils.js';
13
13
  export * from './Assets.js';
14
14
  export * from './Addresses.js';
15
15
  export * from './bytes.js';
16
+ export * from './C2dCapability.js';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@oceanprotocol/lib",
3
3
  "source": "./src/index.ts",
4
- "version": "9.0.0-next.11",
4
+ "version": "9.0.0-next.12",
5
5
  "description": "JavaScript client library for Ocean Protocol",
6
6
  "module": "./dist/lib.module.mjs",
7
7
  "type": "module",