@bli-cockpit/telemetry-core 0.1.85 → 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,
@@ -0,0 +1,41 @@
1
+ export declare const IMAGE_DESCRIPTION_STATE_FILENAME = "image-descriptions.json";
2
+ export declare const IMAGE_DESCRIPTION_STATE_SCHEMA = "cockpit-image-descriptions.v1";
3
+ /** Oldest keys leave first past this many (about 5 MB on disk). */
4
+ export declare const IMAGE_DESCRIPTION_STATE_MAX_KEYS = 150000;
5
+ /** Oldest failures leave first past this many. */
6
+ export declare const IMAGE_FAILED_STATE_MAX_KEYS = 5000;
7
+ /** A lock file older than this belongs to a writer that died. */
8
+ export declare const IMAGE_STATE_LOCK_STALE_MS = 30000;
9
+ export declare function imageStateKey(sha256: string): string;
10
+ export declare function imageDescriptionStatePath(stateDir: string): string;
11
+ /**
12
+ * An image the door answered about and could not describe (BLI-16979). The same bytes will meet the
13
+ * same answer, so the sender waits before it sends them again. Holds a reason label and times only.
14
+ */
15
+ export interface FailedImageRecord {
16
+ reason: string;
17
+ attempts: number;
18
+ /** Epoch milliseconds before which the image is not sent again. */
19
+ retry_after: number;
20
+ }
21
+ /** How long to leave an image alone after its Nth failed attempt. */
22
+ export declare function imageRetryDelayMs(attempts: number, permanent: boolean): number;
23
+ export interface ImageDescriptionState {
24
+ /** Keys already described, oldest first. */
25
+ described: string[];
26
+ failed: Record<string, FailedImageRecord>;
27
+ }
28
+ /** The state on disk. Missing is empty; unreadable or corrupt is empty and said out loud. */
29
+ export declare function readImageDescriptionState(stateDir: string): Promise<ImageDescriptionState>;
30
+ /**
31
+ * Both writers' entries survive: described keys are the union (the caller's order first, then keys
32
+ * only the disk has), and a failure the disk holds that the caller does not is kept unless that
33
+ * image is described by now. When both hold a failure the one with more attempts wins.
34
+ */
35
+ export declare function mergeImageDescriptionStates(mine: ImageDescriptionState, disk: ImageDescriptionState): ImageDescriptionState;
36
+ /**
37
+ * Read the file under the lock, let `next` build the new state from what is really on disk, and
38
+ * write it atomically. A lock that cannot be taken within five seconds is logged and the update
39
+ * still runs: a rare lost update costs a repeat send, a blocked describer would cost every image.
40
+ */
41
+ export declare function updateImageDescriptionState(stateDir: string, next: (disk: ImageDescriptionState) => ImageDescriptionState): Promise<ImageDescriptionState>;
@@ -0,0 +1,168 @@
1
+ /**
2
+ * The machine's record of which images the describe door has already answered for, shared by the
3
+ * two writers on one laptop: the 15-minute sync tick (collector) and the BLI Memory daemon, which
4
+ * describes a pasted image seconds after the turn ends (BLI-23328).
5
+ *
6
+ * One small file in the collector state directory. A key is the first 32 hex characters of the
7
+ * image's sha256; the file holds keys, failure labels and times only, never a description, a path
8
+ * or a byte. Because two processes now write it, every write is a read-merge-write under a lock
9
+ * file, renamed into place, so neither loses the other's entries. A lost or corrupt file costs at
10
+ * worst a repeat send, which the server answers "known" without a model call.
11
+ */
12
+ import fs from "node:fs/promises";
13
+ import path from "node:path";
14
+ export const IMAGE_DESCRIPTION_STATE_FILENAME = "image-descriptions.json";
15
+ export const IMAGE_DESCRIPTION_STATE_SCHEMA = "cockpit-image-descriptions.v1";
16
+ /** Oldest keys leave first past this many (about 5 MB on disk). */
17
+ export const IMAGE_DESCRIPTION_STATE_MAX_KEYS = 150_000;
18
+ /** Oldest failures leave first past this many. */
19
+ export const IMAGE_FAILED_STATE_MAX_KEYS = 5_000;
20
+ const KEY_CHARS = 32;
21
+ const LOCK_SUFFIX = ".lock";
22
+ /** A lock file older than this belongs to a writer that died. */
23
+ export const IMAGE_STATE_LOCK_STALE_MS = 30_000;
24
+ const LOCK_WAIT_MS = 5_000;
25
+ const LOCK_POLL_MS = 25;
26
+ const TAG = "[image-descriptions]";
27
+ export function imageStateKey(sha256) {
28
+ return sha256.slice(0, KEY_CHARS);
29
+ }
30
+ export function imageDescriptionStatePath(stateDir) {
31
+ return path.join(stateDir, IMAGE_DESCRIPTION_STATE_FILENAME);
32
+ }
33
+ const HOUR_MS = 3_600_000;
34
+ /** A refusal that repeats for the same bytes (a 4xx): a week, then a month. */
35
+ const PERMANENT_BACKOFF_MS = [7 * 24 * HOUR_MS, 30 * 24 * HOUR_MS];
36
+ /** A failure that may pass (the door or the model was down): 1 h, 6 h, 24 h, then 72 h. */
37
+ const TRANSIENT_BACKOFF_MS = [HOUR_MS, 6 * HOUR_MS, 24 * HOUR_MS, 72 * HOUR_MS];
38
+ /** How long to leave an image alone after its Nth failed attempt. */
39
+ export function imageRetryDelayMs(attempts, permanent) {
40
+ const steps = permanent ? PERMANENT_BACKOFF_MS : TRANSIENT_BACKOFF_MS;
41
+ return steps[Math.min(Math.max(attempts, 1), steps.length) - 1];
42
+ }
43
+ function isMissing(error) {
44
+ const code = error?.code;
45
+ return code === "ENOENT" || code === "ENOTDIR";
46
+ }
47
+ /** The state on disk. Missing is empty; unreadable or corrupt is empty and said out loud. */
48
+ export async function readImageDescriptionState(stateDir) {
49
+ let raw;
50
+ try {
51
+ raw = JSON.parse(await fs.readFile(imageDescriptionStatePath(stateDir), "utf8"));
52
+ }
53
+ catch (error) {
54
+ if (!isMissing(error)) {
55
+ console.error(TAG + " state file unreadable, starting from an empty list", JSON.stringify({ reason: "image_state_unreadable" }));
56
+ }
57
+ return { described: [], failed: {} };
58
+ }
59
+ const record = (raw && typeof raw === "object" ? raw : {});
60
+ const described = Array.isArray(record.described)
61
+ ? record.described.filter((key) => typeof key === "string" && key.length === KEY_CHARS)
62
+ : [];
63
+ const failed = {};
64
+ if (record.failed && typeof record.failed === "object" && !Array.isArray(record.failed)) {
65
+ for (const [key, value] of Object.entries(record.failed)) {
66
+ const entry = value;
67
+ if (key.length !== KEY_CHARS || !entry)
68
+ continue;
69
+ if (typeof entry.reason !== "string" || typeof entry.attempts !== "number" || typeof entry.retry_after !== "number")
70
+ continue;
71
+ failed[key] = { reason: entry.reason, attempts: entry.attempts, retry_after: entry.retry_after };
72
+ }
73
+ }
74
+ return { described, failed };
75
+ }
76
+ /**
77
+ * Both writers' entries survive: described keys are the union (the caller's order first, then keys
78
+ * only the disk has), and a failure the disk holds that the caller does not is kept unless that
79
+ * image is described by now. When both hold a failure the one with more attempts wins.
80
+ */
81
+ export function mergeImageDescriptionStates(mine, disk) {
82
+ const described = [...mine.described];
83
+ const known = new Set(described);
84
+ for (const key of disk.described) {
85
+ if (known.has(key))
86
+ continue;
87
+ known.add(key);
88
+ described.push(key);
89
+ }
90
+ const failed = {};
91
+ for (const [key, record] of Object.entries(mine.failed))
92
+ if (!known.has(key))
93
+ failed[key] = record;
94
+ for (const [key, record] of Object.entries(disk.failed)) {
95
+ if (known.has(key))
96
+ continue;
97
+ const have = failed[key];
98
+ if (!have || record.attempts > have.attempts)
99
+ failed[key] = record;
100
+ }
101
+ return { described, failed };
102
+ }
103
+ /**
104
+ * Read the file under the lock, let `next` build the new state from what is really on disk, and
105
+ * write it atomically. A lock that cannot be taken within five seconds is logged and the update
106
+ * still runs: a rare lost update costs a repeat send, a blocked describer would cost every image.
107
+ */
108
+ export async function updateImageDescriptionState(stateDir, next) {
109
+ await fs.mkdir(stateDir, { recursive: true });
110
+ const filePath = imageDescriptionStatePath(stateDir);
111
+ const release = await acquireStateLock(filePath + LOCK_SUFFIX);
112
+ try {
113
+ const built = next(await readImageDescriptionState(stateDir));
114
+ const kept = built.described.length > IMAGE_DESCRIPTION_STATE_MAX_KEYS
115
+ ? built.described.slice(built.described.length - IMAGE_DESCRIPTION_STATE_MAX_KEYS)
116
+ : built.described;
117
+ const failedEntries = Object.entries(built.failed).sort((a, b) => a[1].retry_after - b[1].retry_after);
118
+ const failed = Object.fromEntries(failedEntries.slice(Math.max(0, failedEntries.length - IMAGE_FAILED_STATE_MAX_KEYS)));
119
+ await writeAtomic(filePath, { schema_version: IMAGE_DESCRIPTION_STATE_SCHEMA, described: kept, failed });
120
+ return { described: kept, failed };
121
+ }
122
+ finally {
123
+ await release();
124
+ }
125
+ }
126
+ async function writeAtomic(filePath, value) {
127
+ const temp = `${filePath}.${process.pid}.${Math.random().toString(36).slice(2, 10)}.tmp`;
128
+ try {
129
+ await fs.writeFile(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
130
+ if (process.platform !== "win32")
131
+ await fs.chmod(temp, 0o600).catch(() => undefined);
132
+ await fs.rename(temp, filePath);
133
+ }
134
+ catch (error) {
135
+ await fs.rm(temp, { force: true }).catch(() => undefined);
136
+ throw error;
137
+ }
138
+ }
139
+ async function acquireStateLock(lockPath) {
140
+ const deadline = Date.now() + LOCK_WAIT_MS;
141
+ for (;;) {
142
+ try {
143
+ const handle = await fs.open(lockPath, "wx", 0o600);
144
+ await handle.close();
145
+ return async () => {
146
+ await fs.rm(lockPath, { force: true }).catch(() => undefined);
147
+ };
148
+ }
149
+ catch (error) {
150
+ const code = error?.code;
151
+ if (code !== "EEXIST" && code !== "EPERM" && code !== "EACCES") {
152
+ console.error(TAG + " state lock unavailable, updating without it", JSON.stringify({ reason: "image_state_lock_error", error_code: typeof code === "string" ? code : "unknown" }));
153
+ return async () => { };
154
+ }
155
+ }
156
+ const age = await fs.stat(lockPath).then((stat) => Date.now() - stat.mtimeMs).catch(() => null);
157
+ if (age !== null && age > IMAGE_STATE_LOCK_STALE_MS) {
158
+ console.error(TAG + " removing a stale state lock", JSON.stringify({ reason: "image_state_lock_stale", age_ms: Math.round(age) }));
159
+ await fs.rm(lockPath, { force: true }).catch(() => undefined);
160
+ continue;
161
+ }
162
+ if (Date.now() >= deadline) {
163
+ console.error(TAG + " state lock busy, updating without it", JSON.stringify({ reason: "image_state_lock_timeout", waited_ms: LOCK_WAIT_MS }));
164
+ return async () => { };
165
+ }
166
+ await new Promise((resolve) => setTimeout(resolve, LOCK_POLL_MS));
167
+ }
168
+ }
package/dist/index.d.ts CHANGED
@@ -11,6 +11,7 @@ export * from "./evidence-rules-fingerprint.js";
11
11
  export * from "./evidence-stubs.js";
12
12
  export * from "./evidence-transcripts.js";
13
13
  export * from "./evidence-upload.js";
14
+ export * from "./image-description-store.js";
14
15
  export * from "./image-descriptions.js";
15
16
  export * from "./image-marker-resolver.js";
16
17
  export * from "./transcript-images.js";
package/dist/index.js CHANGED
@@ -11,6 +11,7 @@ export * from "./evidence-rules-fingerprint.js";
11
11
  export * from "./evidence-stubs.js";
12
12
  export * from "./evidence-transcripts.js";
13
13
  export * from "./evidence-upload.js";
14
+ export * from "./image-description-store.js";
14
15
  export * from "./image-descriptions.js";
15
16
  export * from "./image-marker-resolver.js";
16
17
  export * from "./transcript-images.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bli-cockpit/telemetry-core",
3
- "version": "0.1.85",
3
+ "version": "0.1.87",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",