ticlo-tsdb 0.0.0-stage → 0.2.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.
@@ -0,0 +1,1031 @@
1
+ const RAW_HEADER_BYTES = 32;
2
+ const RAW_RECORD_BYTES = 16; // [ts: f64, val: f64]
3
+ const RAW_MAGIC = 0x57524e54; // 'TNRW'
4
+ const RAW_VERSION = 1;
5
+ const VAL_CHUNK_HEADER_BYTES = 32; // [magic: u32, version: u32, recordCount: f64, minTs: f64, maxTs: f64]
6
+ const VAL_MAGIC = 0x4c564e54; // 'TNVL'
7
+ const VAL_VERSION = 2;
8
+ const VAL_RECORD_HEADER_BYTES = 16; // [ts: f64, len: u32, flags: u32]
9
+ const VALUE_FLAG_ENCODED = 0;
10
+ const VALUE_FLAG_STRING = 1;
11
+ const VALUE_FLAG_UNDEFINED = 2;
12
+ const IS_LITTLE_ENDIAN = (() => {
13
+ const buf = new ArrayBuffer(4);
14
+ new Uint32Array(buf)[0] = 0x01020304;
15
+ return new Uint8Array(buf)[0] === 0x04;
16
+ })();
17
+ const textEncoder = new TextEncoder();
18
+ const textDecoder = new TextDecoder();
19
+ export class NumericRawFile {
20
+ backend;
21
+ relPrefix;
22
+ maxRecordsPerChunk;
23
+ chunks = [];
24
+ nextChunkId = 1;
25
+ activeHandle = null;
26
+ activeChunkId = -1;
27
+ activeDirtyForManifest = false;
28
+ _recordCount = 0;
29
+ _byteSize = 0;
30
+ opened = false;
31
+ headerBuf = new ArrayBuffer(RAW_HEADER_BYTES);
32
+ headerU8 = new Uint8Array(this.headerBuf);
33
+ headerView = new DataView(this.headerBuf);
34
+ constructor(backend, relPrefix, chunkBytes = 65_536) {
35
+ this.backend = backend;
36
+ this.relPrefix = relPrefix;
37
+ this.maxRecordsPerChunk = Math.max(1, Math.floor((chunkBytes - RAW_HEADER_BYTES) / RAW_RECORD_BYTES));
38
+ }
39
+ get recordCount() {
40
+ return this._recordCount;
41
+ }
42
+ get byteSize() {
43
+ return this._byteSize;
44
+ }
45
+ get manifestPath() {
46
+ return `${this.relPrefix}.manifest.json`;
47
+ }
48
+ chunkPath(id) {
49
+ return `${this.relPrefix}_${id}.bin`;
50
+ }
51
+ async open() {
52
+ if (this.opened)
53
+ return;
54
+ const manifest = await this.backend.readJson(this.manifestPath);
55
+ if (manifest) {
56
+ if (manifest.version !== RAW_VERSION) {
57
+ throw new Error(`Incompatible numeric raw manifest: ${this.manifestPath}`);
58
+ }
59
+ this.nextChunkId = Math.max(1, manifest.nextChunkId);
60
+ this.chunks = manifest.chunks.map((c) => ({ ...c }));
61
+ // Reconcile only the active (last) chunk from disk for crash safety.
62
+ const last = this.chunks[this.chunks.length - 1];
63
+ if (last) {
64
+ const handle = await this.backend.open(this.chunkPath(last.id));
65
+ const size = await handle.size();
66
+ if (size >= RAW_HEADER_BYTES) {
67
+ const readBytes = await handle.read(this.headerU8, 0, RAW_HEADER_BYTES, 0);
68
+ if (readBytes < RAW_HEADER_BYTES ||
69
+ this.headerView.getUint32(0, true) !== RAW_MAGIC ||
70
+ this.headerView.getUint32(4, true) !== RAW_VERSION) {
71
+ throw new Error(`Corrupt raw file header: ${this.chunkPath(last.id)}`);
72
+ }
73
+ const hdrCount = this.headerView.getFloat64(8, true);
74
+ const maxFromSize = Math.floor((size - RAW_HEADER_BYTES) / RAW_RECORD_BYTES);
75
+ const reconciledCount = Math.min(hdrCount, maxFromSize);
76
+ if (reconciledCount > 0) {
77
+ if (reconciledCount === hdrCount) {
78
+ last.minTs = this.headerView.getFloat64(16, true);
79
+ last.maxTs = this.headerView.getFloat64(24, true);
80
+ }
81
+ else {
82
+ const tmp = new ArrayBuffer(8);
83
+ const dv = new DataView(tmp);
84
+ await handle.read(new Uint8Array(tmp), 0, 8, RAW_HEADER_BYTES);
85
+ last.minTs = dv.getFloat64(0, true);
86
+ await handle.read(new Uint8Array(tmp), 0, 8, RAW_HEADER_BYTES + (reconciledCount - 1) * RAW_RECORD_BYTES);
87
+ last.maxTs = dv.getFloat64(0, true);
88
+ }
89
+ last.recordCount = reconciledCount;
90
+ last.byteSize = RAW_HEADER_BYTES + reconciledCount * RAW_RECORD_BYTES;
91
+ this.activeHandle = handle;
92
+ this.activeChunkId = last.id;
93
+ }
94
+ else {
95
+ await handle.close();
96
+ await this.backend.remove(this.chunkPath(last.id));
97
+ this.chunks.pop();
98
+ }
99
+ }
100
+ else {
101
+ await handle.close();
102
+ await this.backend.remove(this.chunkPath(last.id));
103
+ this.chunks.pop();
104
+ }
105
+ }
106
+ }
107
+ this.recomputeTotals();
108
+ this.activeDirtyForManifest = false;
109
+ this.opened = true;
110
+ }
111
+ recomputeTotals() {
112
+ let totalRecs = 0;
113
+ let totalBytes = 0;
114
+ for (let i = 0; i < this.chunks.length; ++i) {
115
+ totalRecs += this.chunks[i].recordCount;
116
+ totalBytes += this.chunks[i].byteSize;
117
+ }
118
+ this._recordCount = totalRecs;
119
+ this._byteSize = totalBytes;
120
+ }
121
+ async writeManifest() {
122
+ const data = {
123
+ version: RAW_VERSION,
124
+ nextChunkId: this.nextChunkId,
125
+ chunks: this.chunks,
126
+ };
127
+ await this.backend.writeJsonAtomic(this.manifestPath, data);
128
+ this.activeDirtyForManifest = false;
129
+ }
130
+ async writeChunkHeader(handle, chunk) {
131
+ this.headerU8.fill(0);
132
+ this.headerView.setUint32(0, RAW_MAGIC, true);
133
+ this.headerView.setUint32(4, RAW_VERSION, true);
134
+ this.headerView.setFloat64(8, chunk.recordCount, true);
135
+ this.headerView.setFloat64(16, chunk.minTs, true);
136
+ this.headerView.setFloat64(24, chunk.maxTs, true);
137
+ await handle.write(this.headerU8, 0, RAW_HEADER_BYTES, 0);
138
+ }
139
+ async writePairs(handle, position, interleaved, recordOffset, count) {
140
+ const byteLen = count * RAW_RECORD_BYTES;
141
+ if (IS_LITTLE_ENDIAN) {
142
+ const bytes = new Uint8Array(interleaved.buffer, interleaved.byteOffset + recordOffset * RAW_RECORD_BYTES, byteLen);
143
+ await handle.write(bytes, 0, byteLen, position);
144
+ return;
145
+ }
146
+ const scratch = new ArrayBuffer(byteLen);
147
+ const dv = new DataView(scratch);
148
+ const baseFloat = recordOffset * 2;
149
+ const totalFloats = count * 2;
150
+ for (let i = 0; i < totalFloats; ++i) {
151
+ dv.setFloat64(i * 8, interleaved[baseFloat + i], true);
152
+ }
153
+ await handle.write(new Uint8Array(scratch), 0, byteLen, position);
154
+ }
155
+ async ensureActiveHandle(chunkId) {
156
+ if (this.activeHandle && this.activeChunkId === chunkId) {
157
+ return this.activeHandle;
158
+ }
159
+ if (this.activeHandle) {
160
+ await this.activeHandle.close();
161
+ this.activeHandle = null;
162
+ this.activeChunkId = -1;
163
+ }
164
+ this.activeHandle = await this.backend.open(this.chunkPath(chunkId));
165
+ this.activeChunkId = chunkId;
166
+ return this.activeHandle;
167
+ }
168
+ async readChunkPairs(handle, recordCount) {
169
+ const byteLen = recordCount * RAW_RECORD_BYTES;
170
+ const buf = new ArrayBuffer(byteLen);
171
+ const bytesRead = await handle.read(new Uint8Array(buf), 0, byteLen, RAW_HEADER_BYTES);
172
+ const actualRecords = Math.floor(bytesRead / RAW_RECORD_BYTES);
173
+ if (IS_LITTLE_ENDIAN) {
174
+ return new Float64Array(buf, 0, actualRecords * 2);
175
+ }
176
+ const dv = new DataView(buf);
177
+ const pairs = new Float64Array(new ArrayBuffer(actualRecords * RAW_RECORD_BYTES));
178
+ for (let i = 0; i < actualRecords * 2; ++i) {
179
+ pairs[i] = dv.getFloat64(i * 8, true);
180
+ }
181
+ return pairs;
182
+ }
183
+ async appendBatch(interleaved, count) {
184
+ if (count <= 0)
185
+ return;
186
+ if (!this.opened)
187
+ await this.open();
188
+ let offset = 0;
189
+ let manifestDirty = false;
190
+ while (offset < count) {
191
+ const last = this.chunks[this.chunks.length - 1];
192
+ const space = last ? this.maxRecordsPerChunk - last.recordCount : 0;
193
+ if (space <= 0) {
194
+ if (this.activeHandle) {
195
+ await this.activeHandle.close();
196
+ this.activeHandle = null;
197
+ this.activeChunkId = -1;
198
+ }
199
+ const take = Math.min(count - offset, this.maxRecordsPerChunk);
200
+ const newId = this.nextChunkId++;
201
+ const handle = await this.backend.open(this.chunkPath(newId));
202
+ this.activeHandle = handle;
203
+ this.activeChunkId = newId;
204
+ const chunk = {
205
+ id: newId,
206
+ recordCount: take,
207
+ minTs: interleaved[offset * 2],
208
+ maxTs: interleaved[(offset + take - 1) * 2],
209
+ byteSize: RAW_HEADER_BYTES + take * RAW_RECORD_BYTES,
210
+ };
211
+ await this.writePairs(handle, RAW_HEADER_BYTES, interleaved, offset, take);
212
+ await this.writeChunkHeader(handle, chunk);
213
+ this.chunks.push(chunk);
214
+ this._recordCount += take;
215
+ this._byteSize += chunk.byteSize;
216
+ offset += take;
217
+ manifestDirty = true;
218
+ this.activeDirtyForManifest = false;
219
+ }
220
+ else {
221
+ const take = Math.min(count - offset, space);
222
+ const handle = await this.ensureActiveHandle(last.id);
223
+ const pos = RAW_HEADER_BYTES + last.recordCount * RAW_RECORD_BYTES;
224
+ await this.writePairs(handle, pos, interleaved, offset, take);
225
+ last.recordCount += take;
226
+ last.maxTs = interleaved[(offset + take - 1) * 2];
227
+ const addBytes = take * RAW_RECORD_BYTES;
228
+ last.byteSize += addBytes;
229
+ await this.writeChunkHeader(handle, last);
230
+ this._recordCount += take;
231
+ this._byteSize += addBytes;
232
+ offset += take;
233
+ this.activeDirtyForManifest = true;
234
+ }
235
+ }
236
+ if (manifestDirty) {
237
+ await this.writeManifest();
238
+ }
239
+ }
240
+ findFirstChunkAtOrAfter(startMs) {
241
+ let lo = 0;
242
+ let hi = this.chunks.length - 1;
243
+ let idx = this.chunks.length;
244
+ while (lo <= hi) {
245
+ const mid = (lo + hi) >>> 1;
246
+ if (this.chunks[mid].maxTs >= startMs) {
247
+ idx = mid;
248
+ hi = mid - 1;
249
+ }
250
+ else {
251
+ lo = mid + 1;
252
+ }
253
+ }
254
+ return idx;
255
+ }
256
+ async readRange(startMs, endMs, limit, stripNaN = true) {
257
+ if (!this.opened)
258
+ await this.open();
259
+ if (this.chunks.length === 0 ||
260
+ endMs < this.chunks[0].minTs ||
261
+ startMs > this.chunks[this.chunks.length - 1].maxTs) {
262
+ return { timestamps: new Float64Array(0), values: new Float64Array(0), length: 0, truncated: false };
263
+ }
264
+ if (limit === 0) {
265
+ const hasAny = await this.hasMatchingRecord(startMs, endMs, stripNaN);
266
+ return { timestamps: new Float64Array(0), values: new Float64Array(0), length: 0, truncated: hasAny };
267
+ }
268
+ const startChunkIdx = this.findFirstChunkAtOrAfter(startMs);
269
+ if (startChunkIdx >= this.chunks.length || this.chunks[startChunkIdx].minTs > endMs) {
270
+ return { timestamps: new Float64Array(0), values: new Float64Array(0), length: 0, truncated: false };
271
+ }
272
+ const tsParts = [];
273
+ const valParts = [];
274
+ let truncated = false;
275
+ const hasLimit = limit !== undefined && limit >= 0;
276
+ for (let ci = startChunkIdx; ci < this.chunks.length; ++ci) {
277
+ const chunk = this.chunks[ci];
278
+ if (chunk.minTs > endMs)
279
+ break;
280
+ if (chunk.maxTs < startMs || chunk.recordCount === 0)
281
+ continue;
282
+ const isActive = chunk.id === this.activeChunkId && this.activeHandle !== null;
283
+ const handle = isActive ? this.activeHandle : await this.backend.open(this.chunkPath(chunk.id));
284
+ let pairs;
285
+ try {
286
+ pairs = await this.readChunkPairs(handle, chunk.recordCount);
287
+ }
288
+ finally {
289
+ if (!isActive)
290
+ await handle.close();
291
+ }
292
+ const actualRecords = pairs.length >>> 1;
293
+ const [firstIdx, lastIdx] = findBoundsInPairs(pairs, actualRecords, startMs, endMs);
294
+ if (lastIdx < firstIdx)
295
+ continue;
296
+ for (let i = firstIdx; i <= lastIdx; ++i) {
297
+ const v = pairs[i * 2 + 1];
298
+ if (stripNaN && Number.isNaN(v))
299
+ continue;
300
+ if (hasLimit && tsParts.length >= limit) {
301
+ truncated = true;
302
+ break;
303
+ }
304
+ tsParts.push(pairs[i * 2]);
305
+ valParts.push(v);
306
+ }
307
+ if (truncated)
308
+ break;
309
+ }
310
+ const len = tsParts.length;
311
+ return {
312
+ timestamps: Float64Array.from(tsParts),
313
+ values: Float64Array.from(valParts),
314
+ length: len,
315
+ truncated,
316
+ };
317
+ }
318
+ async hasMatchingRecord(startMs, endMs, stripNaN) {
319
+ const startChunkIdx = this.findFirstChunkAtOrAfter(startMs);
320
+ for (let ci = startChunkIdx; ci < this.chunks.length; ++ci) {
321
+ const chunk = this.chunks[ci];
322
+ if (chunk.minTs > endMs)
323
+ break;
324
+ if (chunk.maxTs < startMs || chunk.recordCount === 0)
325
+ continue;
326
+ const isActive = chunk.id === this.activeChunkId && this.activeHandle !== null;
327
+ const handle = isActive ? this.activeHandle : await this.backend.open(this.chunkPath(chunk.id));
328
+ let pairs;
329
+ try {
330
+ pairs = await this.readChunkPairs(handle, chunk.recordCount);
331
+ }
332
+ finally {
333
+ if (!isActive)
334
+ await handle.close();
335
+ }
336
+ const actualRecords = pairs.length >>> 1;
337
+ const [firstIdx, lastIdx] = findBoundsInPairs(pairs, actualRecords, startMs, endMs);
338
+ for (let i = firstIdx; i <= lastIdx; ++i) {
339
+ if (!stripNaN || !Number.isNaN(pairs[i * 2 + 1]))
340
+ return true;
341
+ }
342
+ }
343
+ return false;
344
+ }
345
+ async readLastBefore(tsMs, inclusive = false) {
346
+ if (!this.opened)
347
+ await this.open();
348
+ if (this.chunks.length === 0)
349
+ return null;
350
+ for (let ci = this.chunks.length - 1; ci >= 0; --ci) {
351
+ const chunk = this.chunks[ci];
352
+ if (chunk.recordCount === 0)
353
+ continue;
354
+ if (inclusive ? chunk.minTs > tsMs : chunk.minTs >= tsMs)
355
+ continue;
356
+ const isActive = chunk.id === this.activeChunkId && this.activeHandle !== null;
357
+ const handle = isActive ? this.activeHandle : await this.backend.open(this.chunkPath(chunk.id));
358
+ let pairs;
359
+ try {
360
+ pairs = await this.readChunkPairs(handle, chunk.recordCount);
361
+ }
362
+ finally {
363
+ if (!isActive)
364
+ await handle.close();
365
+ }
366
+ const actualRecords = pairs.length >>> 1;
367
+ for (let i = actualRecords - 1; i >= 0; --i) {
368
+ const recTs = pairs[i * 2];
369
+ if (inclusive ? recTs <= tsMs : recTs < tsMs) {
370
+ return { ts: recTs, value: pairs[i * 2 + 1] };
371
+ }
372
+ }
373
+ }
374
+ return null;
375
+ }
376
+ listChunks() {
377
+ return this.chunks.map((c) => ({
378
+ id: c.id,
379
+ minKey: c.minTs,
380
+ maxKey: c.maxTs,
381
+ byteSize: c.byteSize,
382
+ count: c.recordCount,
383
+ }));
384
+ }
385
+ async dropChunks(chunkIds) {
386
+ if (!this.opened)
387
+ await this.open();
388
+ if (chunkIds.length === 0 || this.chunks.length === 0)
389
+ return;
390
+ const dropSet = new Set(chunkIds);
391
+ const remaining = [];
392
+ let droppedAny = false;
393
+ for (let i = 0; i < this.chunks.length; ++i) {
394
+ const c = this.chunks[i];
395
+ if (dropSet.has(c.id)) {
396
+ droppedAny = true;
397
+ if (c.id === this.activeChunkId && this.activeHandle) {
398
+ await this.activeHandle.close();
399
+ this.activeHandle = null;
400
+ this.activeChunkId = -1;
401
+ }
402
+ await this.backend.remove(this.chunkPath(c.id));
403
+ }
404
+ else {
405
+ remaining.push(c);
406
+ }
407
+ }
408
+ if (!droppedAny)
409
+ return;
410
+ this.chunks = remaining;
411
+ this.recomputeTotals();
412
+ await this.writeManifest();
413
+ }
414
+ async compact(minTsKeep, maxRecords) {
415
+ if (!this.opened)
416
+ await this.open();
417
+ if (this._recordCount === 0)
418
+ return;
419
+ let dropForMax = maxRecords !== undefined && maxRecords >= 0 ? Math.max(0, this._recordCount - maxRecords) : 0;
420
+ const wholeDrops = [];
421
+ for (let i = 0; i < this.chunks.length; ++i) {
422
+ const c = this.chunks[i];
423
+ const expiredByTime = minTsKeep !== undefined && c.maxTs < minTsKeep;
424
+ const expiredByMax = dropForMax >= c.recordCount;
425
+ if (expiredByTime || expiredByMax) {
426
+ wholeDrops.push(c.id);
427
+ dropForMax = Math.max(0, dropForMax - c.recordCount);
428
+ }
429
+ else {
430
+ break;
431
+ }
432
+ }
433
+ if (wholeDrops.length > 0) {
434
+ await this.dropChunks(wholeDrops);
435
+ }
436
+ if (this.chunks.length === 0)
437
+ return;
438
+ const head = this.chunks[0];
439
+ let dropInHead = Math.min(head.recordCount, dropForMax);
440
+ if (minTsKeep !== undefined && head.minTs < minTsKeep) {
441
+ const isActive = head.id === this.activeChunkId && this.activeHandle !== null;
442
+ const handle = isActive ? this.activeHandle : await this.backend.open(this.chunkPath(head.id));
443
+ let pairs;
444
+ try {
445
+ pairs = await this.readChunkPairs(handle, head.recordCount);
446
+ }
447
+ finally {
448
+ if (!isActive)
449
+ await handle.close();
450
+ }
451
+ const actualRecords = pairs.length >>> 1;
452
+ let firstKeep = actualRecords;
453
+ for (let i = 0; i < actualRecords; ++i) {
454
+ if (pairs[i * 2] >= minTsKeep) {
455
+ firstKeep = i;
456
+ break;
457
+ }
458
+ }
459
+ dropInHead = Math.max(dropInHead, firstKeep);
460
+ }
461
+ if (dropInHead <= 0)
462
+ return;
463
+ if (dropInHead >= head.recordCount) {
464
+ await this.dropChunks([head.id]);
465
+ return;
466
+ }
467
+ const isActive = head.id === this.activeChunkId && this.activeHandle !== null;
468
+ const handle = isActive ? this.activeHandle : await this.backend.open(this.chunkPath(head.id));
469
+ try {
470
+ const keepCount = head.recordCount - dropInHead;
471
+ const keepBytes = keepCount * RAW_RECORD_BYTES;
472
+ const buf = new Uint8Array(new ArrayBuffer(keepBytes));
473
+ await handle.read(buf, 0, keepBytes, RAW_HEADER_BYTES + dropInHead * RAW_RECORD_BYTES);
474
+ await handle.write(buf, 0, keepBytes, RAW_HEADER_BYTES);
475
+ const firstDv = new DataView(buf.buffer, buf.byteOffset, 8);
476
+ head.recordCount = keepCount;
477
+ head.minTs = firstDv.getFloat64(0, true);
478
+ head.byteSize = RAW_HEADER_BYTES + keepBytes;
479
+ await this.writeChunkHeader(handle, head);
480
+ await handle.truncate(head.byteSize);
481
+ }
482
+ finally {
483
+ if (!isActive)
484
+ await handle.close();
485
+ }
486
+ this.recomputeTotals();
487
+ await this.writeManifest();
488
+ }
489
+ async close() {
490
+ if (this.activeDirtyForManifest) {
491
+ await this.writeManifest();
492
+ }
493
+ if (this.activeHandle) {
494
+ await this.activeHandle.close();
495
+ this.activeHandle = null;
496
+ this.activeChunkId = -1;
497
+ }
498
+ }
499
+ }
500
+ export class ValueRawFile {
501
+ backend;
502
+ relPrefix;
503
+ targetChunkBytes;
504
+ chunks = [];
505
+ nextChunkId = 1;
506
+ activeHandle = null;
507
+ activeChunkId = -1;
508
+ activeDirtyForManifest = false;
509
+ _recordCount = 0;
510
+ _byteSize = 0;
511
+ opened = false;
512
+ headerBuf = new ArrayBuffer(VAL_CHUNK_HEADER_BYTES);
513
+ headerU8 = new Uint8Array(this.headerBuf);
514
+ headerView = new DataView(this.headerBuf);
515
+ constructor(backend, relPrefix, targetChunkBytes = 65_536) {
516
+ this.backend = backend;
517
+ this.relPrefix = relPrefix;
518
+ this.targetChunkBytes = Math.max(128, Math.floor(targetChunkBytes));
519
+ }
520
+ get recordCount() {
521
+ return this._recordCount;
522
+ }
523
+ get byteSize() {
524
+ return this._byteSize;
525
+ }
526
+ get manifestPath() {
527
+ return `${this.relPrefix}.manifest.json`;
528
+ }
529
+ chunkPath(id) {
530
+ return `${this.relPrefix}_${id}.bin`;
531
+ }
532
+ async open() {
533
+ if (this.opened)
534
+ return;
535
+ const manifest = await this.backend.readJson(this.manifestPath);
536
+ if (manifest) {
537
+ if (manifest.version !== VAL_VERSION) {
538
+ throw new Error(`Incompatible value raw manifest: ${this.manifestPath}`);
539
+ }
540
+ this.nextChunkId = Math.max(1, manifest.nextChunkId);
541
+ this.chunks = manifest.chunks.map((c) => ({ ...c }));
542
+ // Reconcile only the active (last) chunk from disk for crash safety.
543
+ const last = this.chunks[this.chunks.length - 1];
544
+ if (last) {
545
+ const handle = await this.backend.open(this.chunkPath(last.id));
546
+ const size = await handle.size();
547
+ if (size >= VAL_CHUNK_HEADER_BYTES) {
548
+ const readBytes = await handle.read(this.headerU8, 0, VAL_CHUNK_HEADER_BYTES, 0);
549
+ if (readBytes < VAL_CHUNK_HEADER_BYTES ||
550
+ this.headerView.getUint32(0, true) !== VAL_MAGIC ||
551
+ this.headerView.getUint32(4, true) !== VAL_VERSION) {
552
+ throw new Error(`Corrupt value chunk header: ${this.chunkPath(last.id)}`);
553
+ }
554
+ const bodyLen = size - VAL_CHUNK_HEADER_BYTES;
555
+ const bodyBuf = new ArrayBuffer(bodyLen);
556
+ await handle.read(new Uint8Array(bodyBuf), 0, bodyLen, VAL_CHUNK_HEADER_BYTES);
557
+ const dv = new DataView(bodyBuf);
558
+ let pos = 0;
559
+ let count = 0;
560
+ let minTs = Number.NaN;
561
+ let maxTs = Number.NaN;
562
+ while (pos + VAL_RECORD_HEADER_BYTES <= bodyLen) {
563
+ const recTs = dv.getFloat64(pos, true);
564
+ const payloadLen = dv.getUint32(pos + 8, true);
565
+ if (pos + VAL_RECORD_HEADER_BYTES + payloadLen > bodyLen)
566
+ break;
567
+ if (count === 0)
568
+ minTs = recTs;
569
+ maxTs = recTs;
570
+ count++;
571
+ pos += VAL_RECORD_HEADER_BYTES + payloadLen;
572
+ }
573
+ if (count > 0) {
574
+ const validByteSize = VAL_CHUNK_HEADER_BYTES + pos;
575
+ last.recordCount = count;
576
+ last.minTs = minTs;
577
+ last.maxTs = maxTs;
578
+ last.byteSize = validByteSize;
579
+ if (validByteSize < size) {
580
+ await handle.truncate(validByteSize);
581
+ await this.writeChunkHeader(handle, last);
582
+ }
583
+ this.activeHandle = handle;
584
+ this.activeChunkId = last.id;
585
+ }
586
+ else {
587
+ await handle.close();
588
+ await this.backend.remove(this.chunkPath(last.id));
589
+ this.chunks.pop();
590
+ }
591
+ }
592
+ else {
593
+ await handle.close();
594
+ await this.backend.remove(this.chunkPath(last.id));
595
+ this.chunks.pop();
596
+ }
597
+ }
598
+ }
599
+ this.recomputeTotals();
600
+ this.activeDirtyForManifest = false;
601
+ this.opened = true;
602
+ }
603
+ recomputeTotals() {
604
+ let totalRecs = 0;
605
+ let totalBytes = 0;
606
+ for (let i = 0; i < this.chunks.length; ++i) {
607
+ totalRecs += this.chunks[i].recordCount;
608
+ totalBytes += this.chunks[i].byteSize;
609
+ }
610
+ this._recordCount = totalRecs;
611
+ this._byteSize = totalBytes;
612
+ }
613
+ async writeManifest() {
614
+ const data = {
615
+ version: VAL_VERSION,
616
+ targetChunkBytes: this.targetChunkBytes,
617
+ nextChunkId: this.nextChunkId,
618
+ chunks: this.chunks,
619
+ };
620
+ await this.backend.writeJsonAtomic(this.manifestPath, data);
621
+ this.activeDirtyForManifest = false;
622
+ }
623
+ async writeChunkHeader(handle, chunk) {
624
+ this.headerU8.fill(0);
625
+ this.headerView.setUint32(0, VAL_MAGIC, true);
626
+ this.headerView.setUint32(4, VAL_VERSION, true);
627
+ this.headerView.setFloat64(8, chunk.recordCount, true);
628
+ this.headerView.setFloat64(16, chunk.minTs, true);
629
+ this.headerView.setFloat64(24, chunk.maxTs, true);
630
+ await handle.write(this.headerU8, 0, VAL_CHUNK_HEADER_BYTES, 0);
631
+ }
632
+ async ensureActiveHandle(chunkId) {
633
+ if (this.activeHandle && this.activeChunkId === chunkId) {
634
+ return this.activeHandle;
635
+ }
636
+ if (this.activeHandle) {
637
+ await this.activeHandle.close();
638
+ this.activeHandle = null;
639
+ this.activeChunkId = -1;
640
+ }
641
+ this.activeHandle = await this.backend.open(this.chunkPath(chunkId));
642
+ this.activeChunkId = chunkId;
643
+ return this.activeHandle;
644
+ }
645
+ async appendBatch(entries) {
646
+ if (entries.length === 0)
647
+ return;
648
+ if (!this.opened)
649
+ await this.open();
650
+ const encodedChunks = new Array(entries.length);
651
+ const flagsArr = new Uint8Array(entries.length);
652
+ const recSizes = new Uint32Array(entries.length);
653
+ for (let i = 0; i < entries.length; ++i) {
654
+ const entry = entries[i];
655
+ if (!entry.isString && entry.payload === null) {
656
+ flagsArr[i] = VALUE_FLAG_UNDEFINED;
657
+ encodedChunks[i] = null;
658
+ recSizes[i] = VAL_RECORD_HEADER_BYTES;
659
+ }
660
+ else {
661
+ flagsArr[i] = entry.isString ? VALUE_FLAG_STRING : VALUE_FLAG_ENCODED;
662
+ const chunk = textEncoder.encode(entry.payload ?? '');
663
+ encodedChunks[i] = chunk;
664
+ recSizes[i] = VAL_RECORD_HEADER_BYTES + chunk.byteLength;
665
+ }
666
+ }
667
+ let offset = 0;
668
+ let manifestDirty = false;
669
+ while (offset < entries.length) {
670
+ const last = this.chunks[this.chunks.length - 1];
671
+ const canAppendToLast = last !== undefined && last.byteSize < this.targetChunkBytes;
672
+ let end = offset;
673
+ let batchBytes = 0;
674
+ const baseBytes = canAppendToLast ? last.byteSize : VAL_CHUNK_HEADER_BYTES;
675
+ while (end < entries.length) {
676
+ const nextBytes = batchBytes + recSizes[end];
677
+ if (end > offset && baseBytes + nextBytes > this.targetChunkBytes) {
678
+ break;
679
+ }
680
+ batchBytes = nextBytes;
681
+ end++;
682
+ if (baseBytes + batchBytes >= this.targetChunkBytes) {
683
+ break;
684
+ }
685
+ }
686
+ const dataBuf = new ArrayBuffer(batchBytes);
687
+ const dataU8 = new Uint8Array(dataBuf);
688
+ const dataDv = new DataView(dataBuf);
689
+ let localPos = 0;
690
+ for (let i = offset; i < end; ++i) {
691
+ const payload = encodedChunks[i];
692
+ const payloadLen = payload ? payload.byteLength : 0;
693
+ dataDv.setFloat64(localPos, entries[i].ts, true);
694
+ dataDv.setUint32(localPos + 8, payloadLen, true);
695
+ dataDv.setUint32(localPos + 12, flagsArr[i], true);
696
+ if (payload && payloadLen > 0) {
697
+ dataU8.set(payload, localPos + VAL_RECORD_HEADER_BYTES);
698
+ }
699
+ localPos += VAL_RECORD_HEADER_BYTES + payloadLen;
700
+ }
701
+ const takeCount = end - offset;
702
+ if (canAppendToLast) {
703
+ const handle = await this.ensureActiveHandle(last.id);
704
+ await handle.write(dataU8, 0, batchBytes, last.byteSize);
705
+ last.recordCount += takeCount;
706
+ last.maxTs = entries[end - 1].ts;
707
+ last.byteSize += batchBytes;
708
+ await this.writeChunkHeader(handle, last);
709
+ this._recordCount += takeCount;
710
+ this._byteSize += batchBytes;
711
+ this.activeDirtyForManifest = true;
712
+ }
713
+ else {
714
+ if (this.activeHandle) {
715
+ await this.activeHandle.close();
716
+ this.activeHandle = null;
717
+ this.activeChunkId = -1;
718
+ }
719
+ const newId = this.nextChunkId++;
720
+ const handle = await this.backend.open(this.chunkPath(newId));
721
+ this.activeHandle = handle;
722
+ this.activeChunkId = newId;
723
+ const chunk = {
724
+ id: newId,
725
+ recordCount: takeCount,
726
+ minTs: entries[offset].ts,
727
+ maxTs: entries[end - 1].ts,
728
+ byteSize: VAL_CHUNK_HEADER_BYTES + batchBytes,
729
+ };
730
+ await handle.write(dataU8, 0, batchBytes, VAL_CHUNK_HEADER_BYTES);
731
+ await this.writeChunkHeader(handle, chunk);
732
+ this.chunks.push(chunk);
733
+ this._recordCount += takeCount;
734
+ this._byteSize += chunk.byteSize;
735
+ manifestDirty = true;
736
+ this.activeDirtyForManifest = false;
737
+ }
738
+ offset = end;
739
+ }
740
+ if (manifestDirty) {
741
+ await this.writeManifest();
742
+ }
743
+ }
744
+ findFirstChunkAtOrAfter(startMs) {
745
+ let lo = 0;
746
+ let hi = this.chunks.length - 1;
747
+ let idx = this.chunks.length;
748
+ while (lo <= hi) {
749
+ const mid = (lo + hi) >>> 1;
750
+ if (this.chunks[mid].maxTs >= startMs) {
751
+ idx = mid;
752
+ hi = mid - 1;
753
+ }
754
+ else {
755
+ lo = mid + 1;
756
+ }
757
+ }
758
+ return idx;
759
+ }
760
+ findLastChunkAtOrBefore(endMs) {
761
+ let lo = 0;
762
+ let hi = this.chunks.length - 1;
763
+ let idx = -1;
764
+ while (lo <= hi) {
765
+ const mid = (lo + hi) >>> 1;
766
+ if (this.chunks[mid].minTs <= endMs) {
767
+ idx = mid;
768
+ lo = mid + 1;
769
+ }
770
+ else {
771
+ hi = mid - 1;
772
+ }
773
+ }
774
+ return idx;
775
+ }
776
+ async readChunkBody(chunk) {
777
+ const bodyLen = Math.max(0, chunk.byteSize - VAL_CHUNK_HEADER_BYTES);
778
+ const buf = new ArrayBuffer(bodyLen);
779
+ const u8 = new Uint8Array(buf);
780
+ if (bodyLen > 0) {
781
+ const isActive = chunk.id === this.activeChunkId && this.activeHandle !== null;
782
+ const handle = isActive ? this.activeHandle : await this.backend.open(this.chunkPath(chunk.id));
783
+ try {
784
+ await handle.read(u8, 0, bodyLen, VAL_CHUNK_HEADER_BYTES);
785
+ }
786
+ finally {
787
+ if (!isActive)
788
+ await handle.close();
789
+ }
790
+ }
791
+ return { u8, dv: new DataView(buf), bodyLen };
792
+ }
793
+ decodeRecordAt(u8, dv, pos) {
794
+ const recTs = dv.getFloat64(pos, true);
795
+ const payloadLen = dv.getUint32(pos + 8, true);
796
+ const flags = dv.getUint32(pos + 12, true);
797
+ const nextPos = pos + VAL_RECORD_HEADER_BYTES + payloadLen;
798
+ if (flags === VALUE_FLAG_UNDEFINED) {
799
+ return { rec: { ts: recTs, isString: false, payload: null }, nextPos };
800
+ }
801
+ const text = payloadLen > 0 ? textDecoder.decode(u8.subarray(pos + VAL_RECORD_HEADER_BYTES, nextPos)) : '';
802
+ return {
803
+ rec: {
804
+ ts: recTs,
805
+ isString: flags === VALUE_FLAG_STRING,
806
+ payload: text,
807
+ },
808
+ nextPos,
809
+ };
810
+ }
811
+ async readRange(startMs, endMs, limit, order = 'asc') {
812
+ if (!this.opened)
813
+ await this.open();
814
+ if (this.chunks.length === 0)
815
+ return { records: [], truncated: false };
816
+ const firstChunkIdx = this.findFirstChunkAtOrAfter(startMs);
817
+ const lastChunkIdx = this.findLastChunkAtOrBefore(endMs);
818
+ if (firstChunkIdx > lastChunkIdx || firstChunkIdx >= this.chunks.length || lastChunkIdx < 0) {
819
+ return { records: [], truncated: false };
820
+ }
821
+ const hasLimit = limit !== undefined && limit >= 0;
822
+ const records = [];
823
+ let truncated = false;
824
+ if (order === 'asc') {
825
+ for (let ci = firstChunkIdx; ci <= lastChunkIdx; ++ci) {
826
+ const chunk = this.chunks[ci];
827
+ const { u8, dv, bodyLen } = await this.readChunkBody(chunk);
828
+ let pos = 0;
829
+ while (pos + VAL_RECORD_HEADER_BYTES <= bodyLen) {
830
+ const recTs = dv.getFloat64(pos, true);
831
+ const payloadLen = dv.getUint32(pos + 8, true);
832
+ if (recTs > endMs)
833
+ break;
834
+ if (recTs >= startMs) {
835
+ if (hasLimit && records.length >= limit) {
836
+ truncated = true;
837
+ break;
838
+ }
839
+ const decoded = this.decodeRecordAt(u8, dv, pos);
840
+ records.push(decoded.rec);
841
+ pos = decoded.nextPos;
842
+ }
843
+ else {
844
+ pos += VAL_RECORD_HEADER_BYTES + payloadLen;
845
+ }
846
+ }
847
+ if (truncated)
848
+ break;
849
+ }
850
+ return { records, truncated };
851
+ }
852
+ // Descending order: walk chunks backwards and matching offsets backwards.
853
+ for (let ci = lastChunkIdx; ci >= firstChunkIdx; --ci) {
854
+ const chunk = this.chunks[ci];
855
+ const { u8, dv, bodyLen } = await this.readChunkBody(chunk);
856
+ const matchOffsets = [];
857
+ let pos = 0;
858
+ while (pos + VAL_RECORD_HEADER_BYTES <= bodyLen) {
859
+ const recTs = dv.getFloat64(pos, true);
860
+ const payloadLen = dv.getUint32(pos + 8, true);
861
+ if (recTs > endMs)
862
+ break;
863
+ if (recTs >= startMs) {
864
+ matchOffsets.push(pos);
865
+ }
866
+ pos += VAL_RECORD_HEADER_BYTES + payloadLen;
867
+ }
868
+ for (let mi = matchOffsets.length - 1; mi >= 0; --mi) {
869
+ if (hasLimit && records.length >= limit) {
870
+ truncated = true;
871
+ break;
872
+ }
873
+ records.push(this.decodeRecordAt(u8, dv, matchOffsets[mi]).rec);
874
+ }
875
+ if (truncated)
876
+ break;
877
+ }
878
+ return { records, truncated };
879
+ }
880
+ listChunks() {
881
+ return this.chunks.map((c) => ({
882
+ id: c.id,
883
+ minKey: c.minTs,
884
+ maxKey: c.maxTs,
885
+ byteSize: c.byteSize,
886
+ count: c.recordCount,
887
+ }));
888
+ }
889
+ async dropChunks(chunkIds) {
890
+ if (!this.opened)
891
+ await this.open();
892
+ if (chunkIds.length === 0 || this.chunks.length === 0)
893
+ return;
894
+ const dropSet = new Set(chunkIds);
895
+ const remaining = [];
896
+ let droppedAny = false;
897
+ for (let i = 0; i < this.chunks.length; ++i) {
898
+ const c = this.chunks[i];
899
+ if (dropSet.has(c.id)) {
900
+ droppedAny = true;
901
+ if (c.id === this.activeChunkId && this.activeHandle) {
902
+ await this.activeHandle.close();
903
+ this.activeHandle = null;
904
+ this.activeChunkId = -1;
905
+ }
906
+ await this.backend.remove(this.chunkPath(c.id));
907
+ }
908
+ else {
909
+ remaining.push(c);
910
+ }
911
+ }
912
+ if (!droppedAny)
913
+ return;
914
+ this.chunks = remaining;
915
+ this.recomputeTotals();
916
+ await this.writeManifest();
917
+ }
918
+ async compact(minTsKeep, maxRecords) {
919
+ if (!this.opened)
920
+ await this.open();
921
+ if (this._recordCount === 0)
922
+ return;
923
+ let dropForMax = maxRecords !== undefined && maxRecords >= 0 ? Math.max(0, this._recordCount - maxRecords) : 0;
924
+ const wholeDrops = [];
925
+ for (let i = 0; i < this.chunks.length; ++i) {
926
+ const c = this.chunks[i];
927
+ const expiredByTime = minTsKeep !== undefined && c.maxTs < minTsKeep;
928
+ const expiredByMax = dropForMax >= c.recordCount;
929
+ if (expiredByTime || expiredByMax) {
930
+ wholeDrops.push(c.id);
931
+ dropForMax = Math.max(0, dropForMax - c.recordCount);
932
+ }
933
+ else {
934
+ break;
935
+ }
936
+ }
937
+ if (wholeDrops.length > 0) {
938
+ await this.dropChunks(wholeDrops);
939
+ }
940
+ if (this.chunks.length === 0)
941
+ return;
942
+ const head = this.chunks[0];
943
+ if (dropForMax <= 0 && (minTsKeep === undefined || head.minTs >= minTsKeep)) {
944
+ return;
945
+ }
946
+ const { u8, dv, bodyLen } = await this.readChunkBody(head);
947
+ let pos = 0;
948
+ let skipped = 0;
949
+ let newMinTs = Number.NaN;
950
+ while (pos + VAL_RECORD_HEADER_BYTES <= bodyLen) {
951
+ const recTs = dv.getFloat64(pos, true);
952
+ const payloadLen = dv.getUint32(pos + 8, true);
953
+ const needDropMax = skipped < dropForMax;
954
+ const needDropTs = minTsKeep !== undefined && recTs < minTsKeep;
955
+ if (needDropMax || needDropTs) {
956
+ skipped++;
957
+ pos += VAL_RECORD_HEADER_BYTES + payloadLen;
958
+ }
959
+ else {
960
+ newMinTs = recTs;
961
+ break;
962
+ }
963
+ }
964
+ if (skipped <= 0)
965
+ return;
966
+ const keepCount = head.recordCount - skipped;
967
+ if (keepCount <= 0 || pos >= bodyLen) {
968
+ await this.dropChunks([head.id]);
969
+ return;
970
+ }
971
+ const keepBody = u8.subarray(pos, bodyLen);
972
+ const isActive = head.id === this.activeChunkId && this.activeHandle !== null;
973
+ const handle = isActive ? this.activeHandle : await this.backend.open(this.chunkPath(head.id));
974
+ try {
975
+ await handle.write(keepBody, 0, keepBody.byteLength, VAL_CHUNK_HEADER_BYTES);
976
+ head.recordCount = keepCount;
977
+ head.minTs = newMinTs;
978
+ head.byteSize = VAL_CHUNK_HEADER_BYTES + keepBody.byteLength;
979
+ await this.writeChunkHeader(handle, head);
980
+ await handle.truncate(head.byteSize);
981
+ }
982
+ finally {
983
+ if (!isActive)
984
+ await handle.close();
985
+ }
986
+ this.recomputeTotals();
987
+ await this.writeManifest();
988
+ }
989
+ async close() {
990
+ if (this.activeDirtyForManifest) {
991
+ await this.writeManifest();
992
+ }
993
+ if (this.activeHandle) {
994
+ await this.activeHandle.close();
995
+ this.activeHandle = null;
996
+ this.activeChunkId = -1;
997
+ }
998
+ }
999
+ }
1000
+ function findBoundsInPairs(pairs, actualRecords, startMs, endMs) {
1001
+ let lo = 0;
1002
+ let hi = actualRecords - 1;
1003
+ let firstIdx = actualRecords;
1004
+ while (lo <= hi) {
1005
+ const mid = (lo + hi) >>> 1;
1006
+ if (pairs[mid * 2] >= startMs) {
1007
+ firstIdx = mid;
1008
+ hi = mid - 1;
1009
+ }
1010
+ else {
1011
+ lo = mid + 1;
1012
+ }
1013
+ }
1014
+ if (firstIdx >= actualRecords || pairs[firstIdx * 2] > endMs) {
1015
+ return [0, -1];
1016
+ }
1017
+ lo = firstIdx;
1018
+ hi = actualRecords - 1;
1019
+ let lastIdx = firstIdx - 1;
1020
+ while (lo <= hi) {
1021
+ const mid = (lo + hi) >>> 1;
1022
+ if (pairs[mid * 2] <= endMs) {
1023
+ lastIdx = mid;
1024
+ lo = mid + 1;
1025
+ }
1026
+ else {
1027
+ hi = mid - 1;
1028
+ }
1029
+ }
1030
+ return [firstIdx, lastIdx];
1031
+ }