@bli-cockpit/telemetry-core 0.1.86 → 0.1.87

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,8 +1,32 @@
1
- /** In-object manifest. Legacy objects without this exact prefix remain raw. */
2
- export declare const EVIDENCE_ENCODING_MANIFEST: Buffer<ArrayBuffer>;
1
+ /**
2
+ * The one framing for stored and staged evidence (BLI-23334 added zstd and brotli beside gzip).
3
+ * An object is legacy raw bytes, or one of three exact manifests followed by that codec's stream.
4
+ * `docs/architecture/upload-compression.md` is the design and the reader list.
5
+ */
6
+ export type EvidenceCodec = "gzip" | "zstd" | "br";
7
+ /** Preference order when both sides support more than one. */
8
+ export declare const EVIDENCE_CODEC_PREFERENCE: readonly EvidenceCodec[];
9
+ /** In-object manifest for gzip. Legacy objects without one of the manifests remain raw. */
10
+ export declare const EVIDENCE_ENCODING_MANIFEST: Buffer<ArrayBufferLike>;
11
+ export declare const EVIDENCE_MANIFESTS: Readonly<Record<EvidenceCodec, Buffer>>;
3
12
  export declare const MAX_DECODED_EVIDENCE_BYTES: number;
4
- export declare function encodeEvidenceBytes(bytes: Uint8Array): Buffer;
5
- export declare function decodeEvidenceBytes(bytes: Uint8Array): Buffer;
6
- export declare function encodeEvidenceBody(body: Buffer | ReadableStream<Uint8Array>): Buffer | ReadableStream<Uint8Array>;
13
+ /** Measured on 3 MiB transcript chunks (docs/architecture/upload-compression.md): 0.4 points off zstd-19 at 22 times the speed. */
14
+ export declare const EVIDENCE_ZSTD_LEVEL = 9;
15
+ /** The fallback when Node has no zstd: 1.4 points behind zstd-9, still 90 MB/s. */
16
+ export declare const EVIDENCE_BROTLI_QUALITY = 6;
17
+ /** Whether this Node can encode and decode zstd (22.15+ or 23.8+). */
18
+ export declare function zstdAvailable(): boolean;
19
+ /** The codec a writer with no negotiation should use: zstd when this runtime has it, else gzip. */
20
+ export declare function bestLocalCodec(): EvidenceCodec;
21
+ /** The codec's stream of `bytes`, without the manifest. */
22
+ export declare function compressEvidenceBytes(bytes: Uint8Array, codec: EvidenceCodec): Buffer;
23
+ /** Decodes one codec's stream (no manifest), refusing output past `maxOutputLength`. */
24
+ export declare function decompressEvidenceBytes(bytes: Uint8Array, codec: EvidenceCodec, maxOutputLength?: number): Buffer;
25
+ /** Manifest + the codec's stream. gzip is the default so a writer opts in to a newer codec. */
26
+ export declare function encodeEvidenceBytes(bytes: Uint8Array, codec?: EvidenceCodec): Buffer;
27
+ /** Which manifest `head` starts with, or null for a legacy raw object (or fewer bytes than a manifest). */
28
+ export declare function evidenceCodecOf(head: Uint8Array): EvidenceCodec | null;
29
+ export declare function decodeEvidenceBytes(bytes: Uint8Array, maxOutputLength?: number): Buffer;
30
+ export declare function encodeEvidenceBody(body: Buffer | ReadableStream<Uint8Array>, codec?: EvidenceCodec): Buffer | ReadableStream<Uint8Array>;
7
31
  /** Lazy opening keeps read failures inside the caller's normal stream cleanup. */
8
32
  export declare function decodeEvidenceStream(body: ReadableStream<Uint8Array>): ReadableStream<Uint8Array>;
@@ -1,26 +1,109 @@
1
- import { gzipSync, gunzipSync } from "node:zlib";
2
- /** In-object manifest. Legacy objects without this exact prefix remain raw. */
3
- export const EVIDENCE_ENCODING_MANIFEST = Buffer.from('TOWER-EVIDENCE\n{"version":1,"encoding":"gzip"}\n');
1
+ import * as zlib from "node:zlib";
2
+ import { pipeline, Readable } from "node:stream";
3
+ /** Preference order when both sides support more than one. */
4
+ export const EVIDENCE_CODEC_PREFERENCE = ["zstd", "br", "gzip"];
5
+ function manifestFor(codec) {
6
+ return Buffer.from(`TOWER-EVIDENCE\n{"version":1,"encoding":"${codec}"}\n`);
7
+ }
8
+ /** In-object manifest for gzip. Legacy objects without one of the manifests remain raw. */
9
+ export const EVIDENCE_ENCODING_MANIFEST = manifestFor("gzip");
10
+ export const EVIDENCE_MANIFESTS = {
11
+ gzip: EVIDENCE_ENCODING_MANIFEST,
12
+ zstd: manifestFor("zstd"),
13
+ br: manifestFor("br"),
14
+ };
4
15
  export const MAX_DECODED_EVIDENCE_BYTES = 512 * 1024 * 1024;
5
- export function encodeEvidenceBytes(bytes) {
6
- return Buffer.concat([EVIDENCE_ENCODING_MANIFEST, gzipSync(bytes)]);
16
+ /** Measured on 3 MiB transcript chunks (docs/architecture/upload-compression.md): 0.4 points off zstd-19 at 22 times the speed. */
17
+ export const EVIDENCE_ZSTD_LEVEL = 9;
18
+ /** The fallback when Node has no zstd: 1.4 points behind zstd-9, still 90 MB/s. */
19
+ export const EVIDENCE_BROTLI_QUALITY = 6;
20
+ const MANIFEST_MAX_LENGTH = Math.max(...Object.values(EVIDENCE_MANIFESTS).map(manifest => manifest.length));
21
+ const zstd = zlib;
22
+ /** Whether this Node can encode and decode zstd (22.15+ or 23.8+). */
23
+ export function zstdAvailable() {
24
+ return typeof zstd.zstdCompressSync === "function" && typeof zstd.createZstdDecompress === "function";
25
+ }
26
+ /** The codec a writer with no negotiation should use: zstd when this runtime has it, else gzip. */
27
+ export function bestLocalCodec() {
28
+ return zstdAvailable() ? "zstd" : "gzip";
29
+ }
30
+ function zstdParams() {
31
+ return { params: { [zlib.constants["ZSTD_c_compressionLevel"]]: EVIDENCE_ZSTD_LEVEL } };
32
+ }
33
+ function brotliParams(sizeHint) {
34
+ return {
35
+ params: {
36
+ [zlib.constants.BROTLI_PARAM_QUALITY]: EVIDENCE_BROTLI_QUALITY,
37
+ [zlib.constants.BROTLI_PARAM_LGWIN]: 22,
38
+ ...(sizeHint === undefined ? {} : { [zlib.constants.BROTLI_PARAM_SIZE_HINT]: sizeHint }),
39
+ },
40
+ };
41
+ }
42
+ function requireZstd() {
43
+ if (!zstdAvailable())
44
+ throw new Error("evidence_codec_unsupported:zstd");
45
+ return zstd;
46
+ }
47
+ /** The codec's stream of `bytes`, without the manifest. */
48
+ export function compressEvidenceBytes(bytes, codec) {
49
+ if (codec === "zstd")
50
+ return requireZstd().zstdCompressSync(bytes, zstdParams());
51
+ if (codec === "br")
52
+ return zlib.brotliCompressSync(bytes, brotliParams(bytes.byteLength));
53
+ return zlib.gzipSync(bytes);
7
54
  }
8
- export function decodeEvidenceBytes(bytes) {
55
+ /** Decodes one codec's stream (no manifest), refusing output past `maxOutputLength`. */
56
+ export function decompressEvidenceBytes(bytes, codec, maxOutputLength = MAX_DECODED_EVIDENCE_BYTES) {
57
+ const limit = { maxOutputLength };
58
+ if (codec === "zstd")
59
+ return requireZstd().zstdDecompressSync(bytes, limit);
60
+ if (codec === "br")
61
+ return zlib.brotliDecompressSync(bytes, limit);
62
+ return zlib.gunzipSync(bytes, limit);
63
+ }
64
+ /** Manifest + the codec's stream. gzip is the default so a writer opts in to a newer codec. */
65
+ export function encodeEvidenceBytes(bytes, codec = "gzip") {
66
+ return Buffer.concat([EVIDENCE_MANIFESTS[codec], compressEvidenceBytes(bytes, codec)]);
67
+ }
68
+ /** Which manifest `head` starts with, or null for a legacy raw object (or fewer bytes than a manifest). */
69
+ export function evidenceCodecOf(head) {
70
+ const buffer = Buffer.from(head.buffer, head.byteOffset, Math.min(head.byteLength, MANIFEST_MAX_LENGTH));
71
+ for (const codec of EVIDENCE_CODEC_PREFERENCE) {
72
+ const manifest = EVIDENCE_MANIFESTS[codec];
73
+ if (buffer.length >= manifest.length && buffer.subarray(0, manifest.length).equals(manifest))
74
+ return codec;
75
+ }
76
+ return null;
77
+ }
78
+ export function decodeEvidenceBytes(bytes, maxOutputLength = MAX_DECODED_EVIDENCE_BYTES) {
9
79
  const buffer = Buffer.from(bytes);
10
- return buffer.subarray(0, EVIDENCE_ENCODING_MANIFEST.length).equals(EVIDENCE_ENCODING_MANIFEST)
11
- ? gunzipSync(buffer.subarray(EVIDENCE_ENCODING_MANIFEST.length), { maxOutputLength: MAX_DECODED_EVIDENCE_BYTES })
12
- : buffer;
80
+ const codec = evidenceCodecOf(buffer);
81
+ return codec === null
82
+ ? buffer
83
+ : decompressEvidenceBytes(buffer.subarray(EVIDENCE_MANIFESTS[codec].length), codec, maxOutputLength);
13
84
  }
14
- export function encodeEvidenceBody(body) {
85
+ function toWebStream(stream) {
86
+ return Readable.toWeb(stream);
87
+ }
88
+ /** The web stream through a Node transform; an error anywhere destroys the whole chain and surfaces on the result. */
89
+ function throughNodeStream(body, transform) {
90
+ const source = Readable.fromWeb(body);
91
+ return toWebStream(pipeline(source, transform, () => undefined));
92
+ }
93
+ export function encodeEvidenceBody(body, codec = "gzip") {
15
94
  if (Buffer.isBuffer(body))
16
- return encodeEvidenceBytes(body);
17
- const reader = body.pipeThrough(new CompressionStream("gzip")).getReader();
95
+ return encodeEvidenceBytes(body, codec);
96
+ const manifest = EVIDENCE_MANIFESTS[codec];
97
+ const compressed = codec === "gzip"
98
+ ? body.pipeThrough(new CompressionStream("gzip"))
99
+ : throughNodeStream(body, codec === "zstd" ? requireZstd().createZstdCompress(zstdParams()) : zlib.createBrotliCompress(brotliParams()));
100
+ const reader = compressed.getReader();
18
101
  let prefixSent = false;
19
102
  return new ReadableStream({
20
103
  async pull(controller) {
21
104
  if (!prefixSent) {
22
105
  prefixSent = true;
23
- controller.enqueue(EVIDENCE_ENCODING_MANIFEST);
106
+ controller.enqueue(manifest);
24
107
  return;
25
108
  }
26
109
  const next = await reader.read();
@@ -35,17 +118,19 @@ export function encodeEvidenceBody(body) {
35
118
  /** Look ahead only as far as the manifest, then decode with bounded residency. */
36
119
  async function openDecodedStream(reader) {
37
120
  let head = Buffer.alloc(0);
38
- while (head.length < EVIDENCE_ENCODING_MANIFEST.length) {
121
+ let couldBeManifest = true;
122
+ while (head.length < MANIFEST_MAX_LENGTH && couldBeManifest) {
39
123
  const next = await reader.read();
40
124
  if (next.done)
41
125
  break;
42
126
  head = Buffer.concat([head, next.value]);
43
- const prefixLength = Math.min(head.length, EVIDENCE_ENCODING_MANIFEST.length);
44
- if (!head.subarray(0, prefixLength).equals(EVIDENCE_ENCODING_MANIFEST.subarray(0, prefixLength)))
45
- break;
127
+ couldBeManifest = Object.values(EVIDENCE_MANIFESTS).some(manifest => {
128
+ const prefixLength = Math.min(head.length, manifest.length);
129
+ return head.subarray(0, prefixLength).equals(manifest.subarray(0, prefixLength));
130
+ });
46
131
  }
47
- const encoded = head.subarray(0, EVIDENCE_ENCODING_MANIFEST.length).equals(EVIDENCE_ENCODING_MANIFEST);
48
- let first = encoded ? head.subarray(EVIDENCE_ENCODING_MANIFEST.length) : head;
132
+ const codec = evidenceCodecOf(head);
133
+ let first = codec ? head.subarray(EVIDENCE_MANIFESTS[codec].length) : head;
49
134
  const remainder = new ReadableStream({
50
135
  async pull(controller) {
51
136
  if (first !== null) {
@@ -62,10 +147,13 @@ async function openDecodedStream(reader) {
62
147
  },
63
148
  cancel(reason) { return reader.cancel(reason); },
64
149
  });
65
- if (!encoded)
150
+ if (!codec)
66
151
  return remainder;
67
152
  let decodedBytes = 0;
68
- return remainder.pipeThrough(new DecompressionStream("gzip")).pipeThrough(new TransformStream({
153
+ const decoded = codec === "gzip"
154
+ ? remainder.pipeThrough(new DecompressionStream("gzip"))
155
+ : throughNodeStream(remainder, codec === "zstd" ? requireZstd().createZstdDecompress() : zlib.createBrotliDecompress());
156
+ return decoded.pipeThrough(new TransformStream({
69
157
  transform(chunk, controller) {
70
158
  decodedBytes += chunk.byteLength;
71
159
  if (decodedBytes > MAX_DECODED_EVIDENCE_BYTES)
@@ -245,6 +245,13 @@ export declare const RawEvidenceUploadDispositionSchema: z.ZodEnum<{
245
245
  conflict: "conflict";
246
246
  }>;
247
247
  export type RawEvidenceUploadDisposition = z.infer<typeof RawEvidenceUploadDispositionSchema>;
248
+ /** How a chunk's bytes are compressed on the wire (BLI-23334). `gzip` is what every collector speaks today; the door decodes all three. */
249
+ export declare const RawEvidenceUploadEncodingSchema: z.ZodEnum<{
250
+ gzip: "gzip";
251
+ zstd: "zstd";
252
+ br: "br";
253
+ }>;
254
+ export type RawEvidenceUploadEncoding = z.infer<typeof RawEvidenceUploadEncodingSchema>;
248
255
  export declare const RawEvidenceUploadBeginResponseObjectSchema: z.ZodObject<{
249
256
  object_key: z.ZodString;
250
257
  raw_evidence_pointer_id: z.ZodString;
@@ -291,7 +298,11 @@ export declare const RawEvidenceUploadChunkRequestSchema: z.ZodObject<{
291
298
  "ambient-raw-evidence-upload-chunk.v1": "ambient-raw-evidence-upload-chunk.v1";
292
299
  "ambient-raw-evidence-upload-chunk.v2": "ambient-raw-evidence-upload-chunk.v2";
293
300
  }>;
294
- encoding: z.ZodOptional<z.ZodLiteral<"gzip">>;
301
+ encoding: z.ZodOptional<z.ZodEnum<{
302
+ gzip: "gzip";
303
+ zstd: "zstd";
304
+ br: "br";
305
+ }>>;
295
306
  generated_at: z.ZodString;
296
307
  provenance: z.ZodObject<{
297
308
  capture_source: z.ZodEnum<{
@@ -102,6 +102,8 @@ export const RawEvidenceUploadDispositionSchema = z.enum([
102
102
  "already_committed",
103
103
  "conflict",
104
104
  ]);
105
+ /** How a chunk's bytes are compressed on the wire (BLI-23334). `gzip` is what every collector speaks today; the door decodes all three. */
106
+ export const RawEvidenceUploadEncodingSchema = z.enum(["gzip", "zstd", "br"]);
105
107
  export const RawEvidenceUploadBeginResponseObjectSchema = z
106
108
  .object({
107
109
  object_key: NonEmptyStringSchema,
@@ -128,7 +130,7 @@ export const RawEvidenceUploadBeginResponseSchema = z
128
130
  export const RawEvidenceUploadChunkRequestSchema = z
129
131
  .object({
130
132
  schema_version: z.enum(["ambient-raw-evidence-upload-chunk.v1", "ambient-raw-evidence-upload-chunk.v2"]),
131
- encoding: z.literal("gzip").optional(),
133
+ encoding: RawEvidenceUploadEncodingSchema.optional(),
132
134
  generated_at: IsoDateTimeSchema,
133
135
  provenance: CaptureProvenanceSchema,
134
136
  upload_id: NonEmptyStringSchema,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bli-cockpit/telemetry-core",
3
- "version": "0.1.86",
3
+ "version": "0.1.87",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",