ticlo-tsdb 0.1.0 → 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.
package/dist/rawFile.js CHANGED
@@ -1,10 +1,10 @@
1
1
  const RAW_HEADER_BYTES = 32;
2
2
  const RAW_RECORD_BYTES = 16; // [ts: f64, val: f64]
3
3
  const RAW_MAGIC = 0x57524e54; // 'TNRW'
4
- const SPARSE_STRIDE = 256;
5
- const VAL_IDX_HEADER_BYTES = 16;
6
- const VAL_IDX_ENTRY_BYTES = 16; // [ts: f64, offset: f64]
4
+ const RAW_VERSION = 1;
5
+ const VAL_CHUNK_HEADER_BYTES = 32; // [magic: u32, version: u32, recordCount: f64, minTs: f64, maxTs: f64]
7
6
  const VAL_MAGIC = 0x4c564e54; // 'TNVL'
7
+ const VAL_VERSION = 2;
8
8
  const VAL_RECORD_HEADER_BYTES = 16; // [ts: f64, len: u32, flags: u32]
9
9
  const VALUE_FLAG_ENCODED = 0;
10
10
  const VALUE_FLAG_STRING = 1;
@@ -18,511 +18,1014 @@ const textEncoder = new TextEncoder();
18
18
  const textDecoder = new TextDecoder();
19
19
  export class NumericRawFile {
20
20
  backend;
21
- relPath;
22
- handle = null;
23
- recordCount = 0;
24
- sparseTs = [];
25
- minTs = Number.NaN;
26
- maxTs = Number.NaN;
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;
27
31
  headerBuf = new ArrayBuffer(RAW_HEADER_BYTES);
28
32
  headerU8 = new Uint8Array(this.headerBuf);
29
33
  headerView = new DataView(this.headerBuf);
30
- constructor(backend, relPath) {
34
+ constructor(backend, relPrefix, chunkBytes = 65_536) {
31
35
  this.backend = backend;
32
- this.relPath = relPath;
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`;
33
50
  }
34
51
  async open() {
35
- if (this.handle)
52
+ if (this.opened)
36
53
  return;
37
- this.handle = await this.backend.open(this.relPath);
38
- const size = await this.handle.size();
39
- if (size < RAW_HEADER_BYTES) {
40
- this.recordCount = 0;
41
- this.sparseTs = [];
42
- this.minTs = Number.NaN;
43
- this.maxTs = Number.NaN;
44
- await this.writeHeader();
45
- return;
46
- }
47
- const readBytes = await this.handle.read(this.headerU8, 0, RAW_HEADER_BYTES, 0);
48
- if (readBytes < RAW_HEADER_BYTES || this.headerView.getUint32(0, true) !== RAW_MAGIC) {
49
- throw new Error(`Corrupt raw file header: ${this.relPath}`);
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
+ }
50
106
  }
51
- this.recordCount = this.headerView.getFloat64(8, true);
52
- const maxFromSize = Math.floor((size - RAW_HEADER_BYTES) / RAW_RECORD_BYTES);
53
- if (this.recordCount > maxFromSize) {
54
- this.recordCount = maxFromSize;
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;
55
117
  }
56
- await this.rebuildSparseIndex();
118
+ this._recordCount = totalRecs;
119
+ this._byteSize = totalBytes;
57
120
  }
58
- async writeHeader() {
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) {
59
131
  this.headerU8.fill(0);
60
132
  this.headerView.setUint32(0, RAW_MAGIC, true);
61
- this.headerView.setUint32(4, 1, true);
62
- this.headerView.setFloat64(8, this.recordCount, true);
63
- await this.handle.write(this.headerU8, 0, RAW_HEADER_BYTES, 0);
64
- }
65
- async rebuildSparseIndex() {
66
- this.sparseTs = [];
67
- if (this.recordCount <= 0) {
68
- this.minTs = Number.NaN;
69
- this.maxTs = Number.NaN;
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);
70
144
  return;
71
145
  }
72
- const tmp = new ArrayBuffer(16);
73
- const u8 = new Uint8Array(tmp);
74
- const dv = new DataView(tmp);
75
- for (let idx = 0; idx < this.recordCount; idx += SPARSE_STRIDE) {
76
- await this.handle.read(u8, 0, 8, RAW_HEADER_BYTES + idx * RAW_RECORD_BYTES);
77
- this.sparseTs.push(dv.getFloat64(0, true));
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);
78
152
  }
79
- this.minTs = this.sparseTs[0];
80
- await this.handle.read(u8, 0, 8, RAW_HEADER_BYTES + (this.recordCount - 1) * RAW_RECORD_BYTES);
81
- this.maxTs = dv.getFloat64(0, true);
153
+ await handle.write(new Uint8Array(scratch), 0, byteLen, position);
82
154
  }
83
- findSparseBlockStart(tsMs) {
84
- const arr = this.sparseTs;
85
- let lo = 0;
86
- let hi = arr.length - 1;
87
- let blockIdx = 0;
88
- while (lo <= hi) {
89
- const mid = (lo + hi) >>> 1;
90
- if (arr[mid] <= tsMs) {
91
- blockIdx = mid;
92
- lo = mid + 1;
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;
93
219
  }
94
220
  else {
95
- hi = mid - 1;
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;
96
234
  }
97
235
  }
98
- return blockIdx * SPARSE_STRIDE;
236
+ if (manifestDirty) {
237
+ await this.writeManifest();
238
+ }
99
239
  }
100
- findSparseBlockEnd(tsMs) {
101
- const arr = this.sparseTs;
240
+ findFirstChunkAtOrAfter(startMs) {
102
241
  let lo = 0;
103
- let hi = arr.length - 1;
104
- let blockIdx = arr.length;
242
+ let hi = this.chunks.length - 1;
243
+ let idx = this.chunks.length;
105
244
  while (lo <= hi) {
106
245
  const mid = (lo + hi) >>> 1;
107
- if (arr[mid] > tsMs) {
108
- blockIdx = mid;
246
+ if (this.chunks[mid].maxTs >= startMs) {
247
+ idx = mid;
109
248
  hi = mid - 1;
110
249
  }
111
250
  else {
112
251
  lo = mid + 1;
113
252
  }
114
253
  }
115
- return Math.min(this.recordCount, blockIdx * SPARSE_STRIDE);
116
- }
117
- async appendBatch(interleaved, count) {
118
- if (count <= 0)
119
- return;
120
- if (!this.handle)
121
- await this.open();
122
- const startIdx = this.recordCount;
123
- for (let i = 0; i < count; ++i) {
124
- const idx = startIdx + i;
125
- if (idx % SPARSE_STRIDE === 0) {
126
- this.sparseTs.push(interleaved[i * 2]);
127
- }
128
- }
129
- if (startIdx === 0) {
130
- this.minTs = interleaved[0];
131
- }
132
- this.maxTs = interleaved[(count - 1) * 2];
133
- const byteLen = count * RAW_RECORD_BYTES;
134
- const pos = RAW_HEADER_BYTES + startIdx * RAW_RECORD_BYTES;
135
- if (IS_LITTLE_ENDIAN) {
136
- const bytes = new Uint8Array(interleaved.buffer, interleaved.byteOffset, byteLen);
137
- await this.handle.write(bytes, 0, byteLen, pos);
138
- }
139
- else {
140
- const scratch = new ArrayBuffer(byteLen);
141
- const dv = new DataView(scratch);
142
- for (let i = 0; i < count * 2; ++i) {
143
- dv.setFloat64(i * 8, interleaved[i], true);
144
- }
145
- await this.handle.write(new Uint8Array(scratch), 0, byteLen, pos);
146
- }
147
- this.recordCount = startIdx + count;
148
- await this.writeHeader();
254
+ return idx;
149
255
  }
150
256
  async readRange(startMs, endMs, limit, stripNaN = true) {
151
- if (!this.handle)
257
+ if (!this.opened)
152
258
  await this.open();
153
- if (this.recordCount === 0 || endMs < this.minTs || startMs > this.maxTs) {
259
+ if (this.chunks.length === 0 ||
260
+ endMs < this.chunks[0].minTs ||
261
+ startMs > this.chunks[this.chunks.length - 1].maxTs) {
154
262
  return { timestamps: new Float64Array(0), values: new Float64Array(0), length: 0, truncated: false };
155
263
  }
156
- const approxStart = this.findSparseBlockStart(startMs);
157
- const approxEnd = this.findSparseBlockEnd(endMs);
158
- const readCount = approxEnd - approxStart;
159
- if (readCount <= 0) {
160
- return { timestamps: new Float64Array(0), values: new Float64Array(0), length: 0, truncated: false };
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 };
161
267
  }
162
- const byteLen = readCount * RAW_RECORD_BYTES;
163
- const buf = new ArrayBuffer(byteLen);
164
- const bytesRead = await this.handle.read(new Uint8Array(buf), 0, byteLen, RAW_HEADER_BYTES + approxStart * RAW_RECORD_BYTES);
165
- const actualRecords = Math.floor(bytesRead / RAW_RECORD_BYTES);
166
- let pairs;
167
- if (IS_LITTLE_ENDIAN) {
168
- pairs = new Float64Array(buf, 0, actualRecords * 2);
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 };
169
271
  }
170
- else {
171
- const dv = new DataView(buf);
172
- pairs = new Float64Array(new ArrayBuffer(actualRecords * RAW_RECORD_BYTES));
173
- for (let i = 0; i < actualRecords * 2; ++i) {
174
- pairs[i] = dv.getFloat64(i * 8, true);
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);
175
287
  }
176
- }
177
- // Binary search exact first >= startMs and last <= endMs inside pairs.
178
- let lo = 0;
179
- let hi = actualRecords - 1;
180
- let firstIdx = actualRecords;
181
- while (lo <= hi) {
182
- const mid = (lo + hi) >>> 1;
183
- if (pairs[mid * 2] >= startMs) {
184
- firstIdx = mid;
185
- hi = mid - 1;
288
+ finally {
289
+ if (!isActive)
290
+ await handle.close();
186
291
  }
187
- else {
188
- lo = mid + 1;
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);
189
306
  }
307
+ if (truncated)
308
+ break;
190
309
  }
191
- if (firstIdx >= actualRecords || pairs[firstIdx * 2] > endMs) {
192
- return { timestamps: new Float64Array(0), values: new Float64Array(0), length: 0, truncated: false };
193
- }
194
- lo = firstIdx;
195
- hi = actualRecords - 1;
196
- let lastIdx = firstIdx - 1;
197
- while (lo <= hi) {
198
- const mid = (lo + hi) >>> 1;
199
- if (pairs[mid * 2] <= endMs) {
200
- lastIdx = mid;
201
- lo = mid + 1;
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);
202
331
  }
203
- else {
204
- hi = mid - 1;
332
+ finally {
333
+ if (!isActive)
334
+ await handle.close();
205
335
  }
206
- }
207
- let len = lastIdx - firstIdx + 1;
208
- let truncated = false;
209
- if (!stripNaN) {
210
- if (limit !== undefined && limit >= 0 && len > limit) {
211
- len = limit;
212
- truncated = true;
213
- }
214
- const timestamps = new Float64Array(len);
215
- const values = new Float64Array(len);
216
- for (let i = 0; i < len; ++i) {
217
- const base = (firstIdx + i) * 2;
218
- timestamps[i] = pairs[base];
219
- values[i] = pairs[base + 1];
220
- }
221
- return { timestamps, values, length: len, truncated };
222
- }
223
- let validCount = 0;
224
- for (let i = firstIdx; i <= lastIdx; ++i) {
225
- if (!Number.isNaN(pairs[i * 2 + 1]))
226
- validCount++;
227
- }
228
- if (limit !== undefined && limit >= 0 && validCount > limit) {
229
- validCount = limit;
230
- truncated = true;
231
- }
232
- const timestamps = new Float64Array(validCount);
233
- const values = new Float64Array(validCount);
234
- let pos = 0;
235
- for (let i = firstIdx; i <= lastIdx && pos < validCount; ++i) {
236
- const v = pairs[i * 2 + 1];
237
- if (!Number.isNaN(v)) {
238
- timestamps[pos] = pairs[i * 2];
239
- values[pos] = v;
240
- pos++;
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;
241
341
  }
242
342
  }
243
- return { timestamps, values, length: validCount, truncated };
343
+ return false;
244
344
  }
245
345
  async readLastBefore(tsMs, inclusive = false) {
246
- if (!this.handle)
346
+ if (!this.opened)
247
347
  await this.open();
248
- if (this.recordCount === 0)
249
- return null;
250
- const cmpLimit = inclusive ? tsMs : tsMs - 1;
251
- if (cmpLimit < this.minTs)
348
+ if (this.chunks.length === 0)
252
349
  return null;
253
- const approxStart = this.findSparseBlockStart(cmpLimit);
254
- const readCount = Math.min(SPARSE_STRIDE, this.recordCount - approxStart);
255
- if (readCount <= 0)
256
- return null;
257
- const byteLen = readCount * RAW_RECORD_BYTES;
258
- const buf = new ArrayBuffer(byteLen);
259
- await this.handle.read(new Uint8Array(buf), 0, byteLen, RAW_HEADER_BYTES + approxStart * RAW_RECORD_BYTES);
260
- const dv = new DataView(buf);
261
- for (let i = readCount - 1; i >= 0; --i) {
262
- const recTs = dv.getFloat64(i * RAW_RECORD_BYTES, true);
263
- if (inclusive ? recTs <= tsMs : recTs < tsMs) {
264
- return { ts: recTs, value: dv.getFloat64(i * RAW_RECORD_BYTES + 8, true) };
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
+ }
265
372
  }
266
373
  }
267
374
  return null;
268
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
+ }
269
414
  async compact(minTsKeep, maxRecords) {
270
- if (!this.handle)
415
+ if (!this.opened)
271
416
  await this.open();
272
- if (this.recordCount === 0)
417
+ if (this._recordCount === 0)
273
418
  return;
274
- let dropCount = 0;
275
- if (maxRecords !== undefined && maxRecords >= 0 && this.recordCount > maxRecords) {
276
- dropCount = Math.max(dropCount, this.recordCount - maxRecords);
277
- }
278
- if (minTsKeep !== undefined && this.minTs < minTsKeep) {
279
- const blockStart = this.findSparseBlockStart(minTsKeep);
280
- const readCount = Math.min(SPARSE_STRIDE, this.recordCount - blockStart);
281
- const byteLen = readCount * RAW_RECORD_BYTES;
282
- const buf = new ArrayBuffer(byteLen);
283
- await this.handle.read(new Uint8Array(buf), 0, byteLen, RAW_HEADER_BYTES + blockStart * RAW_RECORD_BYTES);
284
- const dv = new DataView(buf);
285
- let firstKeep = blockStart + readCount;
286
- for (let i = 0; i < readCount; ++i) {
287
- if (dv.getFloat64(i * RAW_RECORD_BYTES, true) >= minTsKeep) {
288
- firstKeep = blockStart + i;
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;
289
456
  break;
290
457
  }
291
458
  }
292
- dropCount = Math.max(dropCount, firstKeep);
459
+ dropInHead = Math.max(dropInHead, firstKeep);
293
460
  }
294
- if (dropCount <= 0)
461
+ if (dropInHead <= 0)
295
462
  return;
296
- if (dropCount >= this.recordCount) {
297
- this.recordCount = 0;
298
- this.sparseTs = [];
299
- this.minTs = Number.NaN;
300
- this.maxTs = Number.NaN;
301
- await this.writeHeader();
302
- await this.handle.truncate(RAW_HEADER_BYTES);
463
+ if (dropInHead >= head.recordCount) {
464
+ await this.dropChunks([head.id]);
303
465
  return;
304
466
  }
305
- const keepCount = this.recordCount - dropCount;
306
- const keepBytes = keepCount * RAW_RECORD_BYTES;
307
- const buf = new Uint8Array(new ArrayBuffer(keepBytes));
308
- await this.handle.read(buf, 0, keepBytes, RAW_HEADER_BYTES + dropCount * RAW_RECORD_BYTES);
309
- await this.handle.write(buf, 0, keepBytes, RAW_HEADER_BYTES);
310
- this.recordCount = keepCount;
311
- await this.writeHeader();
312
- await this.handle.truncate(RAW_HEADER_BYTES + keepBytes);
313
- await this.rebuildSparseIndex();
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();
314
488
  }
315
489
  async close() {
316
- if (this.handle) {
317
- await this.handle.close();
318
- this.handle = null;
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;
319
497
  }
320
498
  }
321
499
  }
322
500
  export class ValueRawFile {
323
501
  backend;
324
- dataPath;
325
- idxPath;
326
- dataHandle = null;
327
- idxHandle = null;
328
- recordCount = 0;
329
- dataBytes = 0;
330
- idxTimestamps = [];
331
- idxOffsets = [];
332
- constructor(backend, dataPath, idxPath) {
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) {
333
516
  this.backend = backend;
334
- this.dataPath = dataPath;
335
- this.idxPath = idxPath;
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`;
336
531
  }
337
532
  async open() {
338
- if (this.dataHandle && this.idxHandle)
533
+ if (this.opened)
339
534
  return;
340
- this.dataHandle = await this.backend.open(this.dataPath);
341
- this.idxHandle = await this.backend.open(this.idxPath);
342
- this.dataBytes = await this.dataHandle.size();
343
- const idxSize = await this.idxHandle.size();
344
- if (idxSize < VAL_IDX_HEADER_BYTES) {
345
- this.recordCount = 0;
346
- this.idxTimestamps = [];
347
- this.idxOffsets = [];
348
- await this.writeIdxHeader();
349
- return;
350
- }
351
- const headerBuf = new ArrayBuffer(VAL_IDX_HEADER_BYTES);
352
- const dv = new DataView(headerBuf);
353
- await this.idxHandle.read(new Uint8Array(headerBuf), 0, VAL_IDX_HEADER_BYTES, 0);
354
- if (dv.getUint32(0, true) !== VAL_MAGIC) {
355
- throw new Error(`Corrupt value index header: ${this.idxPath}`);
356
- }
357
- this.recordCount = Math.min(dv.getFloat64(8, true), Math.floor((idxSize - VAL_IDX_HEADER_BYTES) / VAL_IDX_ENTRY_BYTES));
358
- this.idxTimestamps = new Array(this.recordCount);
359
- this.idxOffsets = new Array(this.recordCount);
360
- if (this.recordCount > 0) {
361
- const entriesLen = this.recordCount * VAL_IDX_ENTRY_BYTES;
362
- const entriesBuf = new ArrayBuffer(entriesLen);
363
- await this.idxHandle.read(new Uint8Array(entriesBuf), 0, entriesLen, VAL_IDX_HEADER_BYTES);
364
- const edv = new DataView(entriesBuf);
365
- for (let i = 0; i < this.recordCount; ++i) {
366
- this.idxTimestamps[i] = edv.getFloat64(i * VAL_IDX_ENTRY_BYTES, true);
367
- this.idxOffsets[i] = edv.getFloat64(i * VAL_IDX_ENTRY_BYTES + 8, true);
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
+ }
368
597
  }
369
598
  }
599
+ this.recomputeTotals();
600
+ this.activeDirtyForManifest = false;
601
+ this.opened = true;
370
602
  }
371
- async writeIdxHeader() {
372
- const buf = new ArrayBuffer(VAL_IDX_HEADER_BYTES);
373
- const dv = new DataView(buf);
374
- dv.setUint32(0, VAL_MAGIC, true);
375
- dv.setUint32(4, 1, true);
376
- dv.setFloat64(8, this.recordCount, true);
377
- await this.idxHandle.write(new Uint8Array(buf), 0, VAL_IDX_HEADER_BYTES, 0);
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;
378
644
  }
379
645
  async appendBatch(entries) {
380
646
  if (entries.length === 0)
381
647
  return;
382
- if (!this.dataHandle || !this.idxHandle)
648
+ if (!this.opened)
383
649
  await this.open();
384
650
  const encodedChunks = new Array(entries.length);
385
651
  const flagsArr = new Uint8Array(entries.length);
386
- let totalDataBytes = 0;
652
+ const recSizes = new Uint32Array(entries.length);
387
653
  for (let i = 0; i < entries.length; ++i) {
388
654
  const entry = entries[i];
389
655
  if (!entry.isString && entry.payload === null) {
390
656
  flagsArr[i] = VALUE_FLAG_UNDEFINED;
391
657
  encodedChunks[i] = null;
392
- totalDataBytes += VAL_RECORD_HEADER_BYTES;
658
+ recSizes[i] = VAL_RECORD_HEADER_BYTES;
393
659
  }
394
660
  else {
395
661
  flagsArr[i] = entry.isString ? VALUE_FLAG_STRING : VALUE_FLAG_ENCODED;
396
662
  const chunk = textEncoder.encode(entry.payload ?? '');
397
663
  encodedChunks[i] = chunk;
398
- totalDataBytes += VAL_RECORD_HEADER_BYTES + chunk.byteLength;
664
+ recSizes[i] = VAL_RECORD_HEADER_BYTES + chunk.byteLength;
399
665
  }
400
666
  }
401
- const dataBuf = new ArrayBuffer(totalDataBytes);
402
- const dataU8 = new Uint8Array(dataBuf);
403
- const dataDv = new DataView(dataBuf);
404
- const idxBuf = new ArrayBuffer(entries.length * VAL_IDX_ENTRY_BYTES);
405
- const idxDv = new DataView(idxBuf);
406
- let localPos = 0;
407
- const baseDataPos = this.dataBytes;
408
- for (let i = 0; i < entries.length; ++i) {
409
- const { ts } = entries[i];
410
- const payload = encodedChunks[i];
411
- const payloadLen = payload ? payload.byteLength : 0;
412
- const recordOffset = baseDataPos + localPos;
413
- dataDv.setFloat64(localPos, ts, true);
414
- dataDv.setUint32(localPos + 8, payloadLen, true);
415
- dataDv.setUint32(localPos + 12, flagsArr[i], true);
416
- if (payload && payloadLen > 0) {
417
- dataU8.set(payload, localPos + VAL_RECORD_HEADER_BYTES);
418
- }
419
- localPos += VAL_RECORD_HEADER_BYTES + payloadLen;
420
- idxDv.setFloat64(i * VAL_IDX_ENTRY_BYTES, ts, true);
421
- idxDv.setFloat64(i * VAL_IDX_ENTRY_BYTES + 8, recordOffset, true);
422
- this.idxTimestamps.push(ts);
423
- this.idxOffsets.push(recordOffset);
424
- }
425
- await this.dataHandle.write(dataU8, 0, totalDataBytes, baseDataPos);
426
- await this.idxHandle.write(new Uint8Array(idxBuf), 0, entries.length * VAL_IDX_ENTRY_BYTES, VAL_IDX_HEADER_BYTES + this.recordCount * VAL_IDX_ENTRY_BYTES);
427
- this.dataBytes = baseDataPos + totalDataBytes;
428
- this.recordCount += entries.length;
429
- await this.writeIdxHeader();
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
+ }
430
743
  }
431
- async readRange(startMs, endMs, limit, order = 'asc') {
432
- if (!this.dataHandle || !this.idxHandle)
433
- await this.open();
434
- if (this.recordCount === 0)
435
- return { records: [], truncated: false };
436
- const tsArr = this.idxTimestamps;
744
+ findFirstChunkAtOrAfter(startMs) {
437
745
  let lo = 0;
438
- let hi = tsArr.length - 1;
439
- let firstIdx = tsArr.length;
746
+ let hi = this.chunks.length - 1;
747
+ let idx = this.chunks.length;
440
748
  while (lo <= hi) {
441
749
  const mid = (lo + hi) >>> 1;
442
- if (tsArr[mid] >= startMs) {
443
- firstIdx = mid;
750
+ if (this.chunks[mid].maxTs >= startMs) {
751
+ idx = mid;
444
752
  hi = mid - 1;
445
753
  }
446
754
  else {
447
755
  lo = mid + 1;
448
756
  }
449
757
  }
450
- if (firstIdx >= tsArr.length || tsArr[firstIdx] > endMs) {
451
- return { records: [], truncated: false };
452
- }
453
- lo = firstIdx;
454
- hi = tsArr.length - 1;
455
- let lastIdx = firstIdx - 1;
758
+ return idx;
759
+ }
760
+ findLastChunkAtOrBefore(endMs) {
761
+ let lo = 0;
762
+ let hi = this.chunks.length - 1;
763
+ let idx = -1;
456
764
  while (lo <= hi) {
457
765
  const mid = (lo + hi) >>> 1;
458
- if (tsArr[mid] <= endMs) {
459
- lastIdx = mid;
766
+ if (this.chunks[mid].minTs <= endMs) {
767
+ idx = mid;
460
768
  lo = mid + 1;
461
769
  }
462
770
  else {
463
771
  hi = mid - 1;
464
772
  }
465
773
  }
466
- const total = lastIdx - firstIdx + 1;
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 = [];
467
823
  let truncated = false;
468
- let readStart = firstIdx;
469
- let readEnd = lastIdx;
470
- if (limit !== undefined && limit >= 0 && total > limit) {
471
- truncated = true;
472
- if (order === 'desc') {
473
- readStart = lastIdx - limit + 1;
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));
474
907
  }
475
908
  else {
476
- readEnd = firstIdx + limit - 1;
909
+ remaining.push(c);
477
910
  }
478
911
  }
479
- if (readEnd < readStart)
480
- return { records: [], truncated };
481
- const startByte = this.idxOffsets[readStart];
482
- const endByte = readEnd + 1 < this.recordCount ? this.idxOffsets[readEnd + 1] : this.dataBytes;
483
- const totalBytes = endByte - startByte;
484
- if (totalBytes <= 0)
485
- return { records: [], truncated };
486
- const buf = new ArrayBuffer(totalBytes);
487
- const u8 = new Uint8Array(buf);
488
- const dv = new DataView(buf);
489
- await this.dataHandle.read(u8, 0, totalBytes, startByte);
490
- const records = new Array(readEnd - readStart + 1);
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);
491
947
  let pos = 0;
492
- let outIdx = 0;
493
- while (pos < totalBytes && outIdx < records.length) {
948
+ let skipped = 0;
949
+ let newMinTs = Number.NaN;
950
+ while (pos + VAL_RECORD_HEADER_BYTES <= bodyLen) {
494
951
  const recTs = dv.getFloat64(pos, true);
495
952
  const payloadLen = dv.getUint32(pos + 8, true);
496
- const flags = dv.getUint32(pos + 12, true);
497
- if (flags === VALUE_FLAG_UNDEFINED) {
498
- records[outIdx++] = { ts: recTs, isString: false, payload: null };
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;
499
958
  }
500
959
  else {
501
- const text = payloadLen > 0
502
- ? textDecoder.decode(u8.subarray(pos + VAL_RECORD_HEADER_BYTES, pos + VAL_RECORD_HEADER_BYTES + payloadLen))
503
- : '';
504
- records[outIdx++] = {
505
- ts: recTs,
506
- isString: flags === VALUE_FLAG_STRING,
507
- payload: text,
508
- };
960
+ newMinTs = recTs;
961
+ break;
509
962
  }
510
- pos += VAL_RECORD_HEADER_BYTES + payloadLen;
511
963
  }
512
- if (outIdx < records.length)
513
- records.length = outIdx;
514
- if (order === 'desc')
515
- records.reverse();
516
- return { records, truncated };
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();
517
988
  }
518
989
  async close() {
519
- if (this.dataHandle) {
520
- await this.dataHandle.close();
521
- this.dataHandle = null;
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;
522
1009
  }
523
- if (this.idxHandle) {
524
- await this.idxHandle.close();
525
- this.idxHandle = null;
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;
526
1028
  }
527
1029
  }
1030
+ return [firstIdx, lastIdx];
528
1031
  }