ticlo-tsdb 0.1.0 → 0.3.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.
@@ -32,68 +32,172 @@ export function makeGapSlotsBuffer(numSlots) {
32
32
  }
33
33
  export class RollupFile {
34
34
  tier;
35
- relPath;
35
+ relPrefix;
36
36
  backend;
37
- handle = null;
38
- baseSlotId = 0;
39
- slotCount = 0;
40
- hasData = false;
37
+ slotsPerChunk;
38
+ chunks = [];
39
+ nextChunkId = 1;
40
+ activeHandle = null;
41
+ activeChunkId = -1;
42
+ activeDirtyForManifest = false;
43
+ _byteSize = 0;
44
+ opened = false;
41
45
  headerBuf = new ArrayBuffer(ROLLUP_HEADER_BYTES);
42
46
  headerU8 = new Uint8Array(this.headerBuf);
43
47
  headerView = new DataView(this.headerBuf);
44
- constructor(backend, relPath, tier) {
48
+ constructor(backend, relPrefix, tier, slotsPerChunk = 512) {
45
49
  this.backend = backend;
46
- this.relPath = relPath;
50
+ this.relPrefix = relPrefix;
47
51
  this.tier = tier;
52
+ this.slotsPerChunk = Math.max(1, Math.floor(slotsPerChunk));
53
+ }
54
+ get hasData() {
55
+ return this.chunks.length > 0;
56
+ }
57
+ get baseSlotId() {
58
+ return this.chunks.length > 0 ? this.chunks[0].baseSlotId : 0;
48
59
  }
49
60
  get endSlotId() {
50
- return this.baseSlotId + this.slotCount;
61
+ const last = this.chunks[this.chunks.length - 1];
62
+ return last ? last.baseSlotId + last.slotCount : 0;
63
+ }
64
+ get slotCount() {
65
+ return this.chunks.length > 0 ? this.endSlotId - this.baseSlotId : 0;
66
+ }
67
+ get byteSize() {
68
+ return this._byteSize;
69
+ }
70
+ get manifestPath() {
71
+ return `${this.relPrefix}.manifest.json`;
72
+ }
73
+ chunkPath(id) {
74
+ return `${this.relPrefix}_${id}.bin`;
75
+ }
76
+ chunkBucket(slotId) {
77
+ return Math.floor(slotId / this.slotsPerChunk);
51
78
  }
52
79
  async open() {
53
- if (this.handle)
54
- return;
55
- this.handle = await this.backend.open(this.relPath);
56
- const fileSize = await this.handle.size();
57
- if (fileSize < ROLLUP_HEADER_BYTES) {
58
- this.baseSlotId = 0;
59
- this.slotCount = 0;
60
- this.hasData = false;
61
- await this.writeHeader();
80
+ if (this.opened)
62
81
  return;
82
+ const manifest = await this.backend.readJson(this.manifestPath);
83
+ if (manifest) {
84
+ if (manifest.version !== VERSION || manifest.tier !== this.tier) {
85
+ throw new Error(`Incompatible rollup manifest: ${this.manifestPath}`);
86
+ }
87
+ if (manifest.chunks.length > 0) {
88
+ this.slotsPerChunk = Math.max(1, manifest.slotsPerChunk);
89
+ }
90
+ this.nextChunkId = Math.max(1, manifest.nextChunkId);
91
+ this.chunks = manifest.chunks.map((c) => ({ ...c }));
92
+ this.chunks.sort((a, b) => a.baseSlotId - b.baseSlotId);
93
+ // Reconcile only the active (last) chunk from disk for crash safety.
94
+ const last = this.chunks[this.chunks.length - 1];
95
+ if (last) {
96
+ const handle = await this.backend.open(this.chunkPath(last.id));
97
+ const fileSize = await handle.size();
98
+ if (fileSize >= ROLLUP_HEADER_BYTES) {
99
+ const hdr = await this.readChunkHeader(handle, this.chunkPath(last.id));
100
+ const maxSlotsFromSize = Math.floor((fileSize - ROLLUP_HEADER_BYTES) / ROLLUP_SLOT_BYTES);
101
+ const reconciledCount = Math.min(hdr.slotCount, maxSlotsFromSize);
102
+ last.baseSlotId = hdr.baseSlotId;
103
+ last.slotCount = reconciledCount;
104
+ last.byteSize = ROLLUP_HEADER_BYTES + reconciledCount * ROLLUP_SLOT_BYTES;
105
+ this.activeHandle = handle;
106
+ this.activeChunkId = last.id;
107
+ }
108
+ else {
109
+ await handle.close();
110
+ await this.backend.remove(this.chunkPath(last.id));
111
+ this.chunks.pop();
112
+ }
113
+ }
63
114
  }
64
- const readBytes = await this.handle.read(this.headerU8, 0, ROLLUP_HEADER_BYTES, 0);
115
+ let totalBytes = 0;
116
+ for (let i = 0; i < this.chunks.length; ++i) {
117
+ totalBytes += this.chunks[i].byteSize;
118
+ }
119
+ this._byteSize = totalBytes;
120
+ this.activeDirtyForManifest = false;
121
+ this.opened = true;
122
+ }
123
+ async writeManifest() {
124
+ const data = {
125
+ version: VERSION,
126
+ tier: this.tier,
127
+ slotsPerChunk: this.slotsPerChunk,
128
+ nextChunkId: this.nextChunkId,
129
+ chunks: this.chunks,
130
+ };
131
+ await this.backend.writeJsonAtomic(this.manifestPath, data);
132
+ this.activeDirtyForManifest = false;
133
+ }
134
+ async readChunkHeader(handle, relPath) {
135
+ const readBytes = await handle.read(this.headerU8, 0, ROLLUP_HEADER_BYTES, 0);
65
136
  if (readBytes < ROLLUP_HEADER_BYTES || this.headerView.getUint32(0, true) !== MAGIC) {
66
- throw new Error(`Corrupt rollup file header: ${this.relPath}`);
137
+ throw new Error(`Corrupt rollup file header: ${relPath}`);
67
138
  }
68
139
  const version = this.headerView.getUint16(4, true);
69
140
  const tierCode = this.headerView.getUint16(6, true);
70
141
  if (version !== VERSION || tierCode !== TIER_CODE[this.tier]) {
71
- throw new Error(`Incompatible rollup file header: ${this.relPath}`);
72
- }
73
- this.baseSlotId = this.headerView.getFloat64(16, true);
74
- this.slotCount = this.headerView.getFloat64(24, true);
75
- const maxSlotsFromSize = Math.floor((fileSize - ROLLUP_HEADER_BYTES) / ROLLUP_SLOT_BYTES);
76
- if (this.slotCount > maxSlotsFromSize) {
77
- this.slotCount = maxSlotsFromSize;
142
+ throw new Error(`Incompatible rollup file header: ${relPath}`);
78
143
  }
79
- this.hasData = this.slotCount > 0;
144
+ return {
145
+ baseSlotId: this.headerView.getFloat64(16, true),
146
+ slotCount: this.headerView.getFloat64(24, true),
147
+ };
80
148
  }
81
- async writeHeader() {
149
+ async writeChunkHeader(handle, baseSlotId, slotCount) {
82
150
  this.headerU8.fill(0);
83
151
  this.headerView.setUint32(0, MAGIC, true);
84
152
  this.headerView.setUint16(4, VERSION, true);
85
153
  this.headerView.setUint16(6, TIER_CODE[this.tier], true);
86
154
  this.headerView.setUint32(8, ROLLUP_SLOT_BYTES, true);
87
- this.headerView.setFloat64(16, this.baseSlotId, true);
88
- this.headerView.setFloat64(24, this.slotCount, true);
89
- await this.handle.write(this.headerU8, 0, ROLLUP_HEADER_BYTES, 0);
155
+ this.headerView.setFloat64(16, baseSlotId, true);
156
+ this.headerView.setFloat64(24, slotCount, true);
157
+ await handle.write(this.headerU8, 0, ROLLUP_HEADER_BYTES, 0);
158
+ }
159
+ async ensureActiveHandle(chunkId) {
160
+ if (this.activeHandle && this.activeChunkId === chunkId) {
161
+ return this.activeHandle;
162
+ }
163
+ if (this.activeHandle) {
164
+ await this.activeHandle.close();
165
+ this.activeHandle = null;
166
+ this.activeChunkId = -1;
167
+ }
168
+ this.activeHandle = await this.backend.open(this.chunkPath(chunkId));
169
+ this.activeChunkId = chunkId;
170
+ return this.activeHandle;
171
+ }
172
+ findChunkForBucket(bucketIdx) {
173
+ // Fast path: check active/last chunk first.
174
+ const lastIdx = this.chunks.length - 1;
175
+ if (lastIdx >= 0 && this.chunkBucket(this.chunks[lastIdx].baseSlotId) === bucketIdx) {
176
+ return lastIdx;
177
+ }
178
+ let lo = 0;
179
+ let hi = lastIdx;
180
+ while (lo <= hi) {
181
+ const mid = (lo + hi) >>> 1;
182
+ const mb = this.chunkBucket(this.chunks[mid].baseSlotId);
183
+ if (mb === bucketIdx)
184
+ return mid;
185
+ if (mb < bucketIdx)
186
+ lo = mid + 1;
187
+ else
188
+ hi = mid - 1;
189
+ }
190
+ return -1;
90
191
  }
91
192
  async readLastSlot() {
92
- if (!this.handle)
193
+ if (!this.opened)
93
194
  await this.open();
94
- if (!this.hasData || this.slotCount <= 0)
195
+ if (!this.hasData)
196
+ return null;
197
+ const last = this.chunks[this.chunks.length - 1];
198
+ if (last.slotCount <= 0)
95
199
  return null;
96
- const lastSlotId = this.baseSlotId + this.slotCount - 1;
200
+ const lastSlotId = last.baseSlotId + last.slotCount - 1;
97
201
  const res = await this.readSlotRange(lastSlotId, lastSlotId);
98
202
  if (res.count === 0)
99
203
  return null;
@@ -102,58 +206,151 @@ export class RollupFile {
102
206
  async writeSlots(startSlotId, data, numSlots) {
103
207
  if (numSlots <= 0)
104
208
  return;
105
- if (!this.handle)
209
+ if (!this.opened)
106
210
  await this.open();
107
- if (!this.hasData) {
108
- this.baseSlotId = startSlotId;
109
- this.slotCount = 0;
110
- this.hasData = true;
111
- }
112
- else if (startSlotId < this.baseSlotId) {
113
- // Shift existing slots forward if an older slot is written (unlikely in real-time mode, safe fallback).
114
- const prependCount = this.baseSlotId - startSlotId;
115
- const existingBytes = this.slotCount * ROLLUP_SLOT_BYTES;
211
+ let manifestDirty = false;
212
+ let cursor = startSlotId;
213
+ const end = startSlotId + numSlots;
214
+ let srcSlotOffset = 0;
215
+ while (cursor < end) {
216
+ const bucketIdx = this.chunkBucket(cursor);
217
+ const bucketEnd = (bucketIdx + 1) * this.slotsPerChunk;
218
+ const writeEnd = Math.min(end, bucketEnd);
219
+ const count = writeEnd - cursor;
220
+ const sliceData = srcSlotOffset === 0 && count === numSlots
221
+ ? data
222
+ : data.subarray(srcSlotOffset * ROLLUP_SLOT_FLOATS, (srcSlotOffset + count) * ROLLUP_SLOT_FLOATS);
223
+ const chunkIdx = this.findChunkForBucket(bucketIdx);
224
+ if (chunkIdx >= 0) {
225
+ const chunk = this.chunks[chunkIdx];
226
+ const isLast = chunkIdx === this.chunks.length - 1;
227
+ const handle = isLast
228
+ ? await this.ensureActiveHandle(chunk.id)
229
+ : await this.backend.open(this.chunkPath(chunk.id));
230
+ try {
231
+ const grew = await this.writeIntoChunk(handle, chunk, cursor, sliceData, count);
232
+ if (grew) {
233
+ if (isLast) {
234
+ this.activeDirtyForManifest = true;
235
+ }
236
+ else {
237
+ manifestDirty = true;
238
+ }
239
+ }
240
+ }
241
+ finally {
242
+ if (!isLast) {
243
+ await handle.close();
244
+ }
245
+ }
246
+ }
247
+ else {
248
+ // Create a new chunk aligned to this bucket boundary.
249
+ const isNewLast = this.chunks.length === 0 || bucketIdx > this.chunkBucket(this.chunks[this.chunks.length - 1].baseSlotId);
250
+ if (isNewLast && this.activeHandle) {
251
+ await this.activeHandle.close();
252
+ this.activeHandle = null;
253
+ this.activeChunkId = -1;
254
+ }
255
+ const newId = this.nextChunkId++;
256
+ const handle = await this.backend.open(this.chunkPath(newId));
257
+ try {
258
+ const byteSize = ROLLUP_HEADER_BYTES + count * ROLLUP_SLOT_BYTES;
259
+ const chunk = {
260
+ id: newId,
261
+ baseSlotId: cursor,
262
+ slotCount: count,
263
+ byteSize,
264
+ };
265
+ await this.writeAlignedFloats(handle, ROLLUP_HEADER_BYTES, sliceData, count);
266
+ await this.writeChunkHeader(handle, chunk.baseSlotId, chunk.slotCount);
267
+ if (isNewLast) {
268
+ this.chunks.push(chunk);
269
+ this.activeHandle = handle;
270
+ this.activeChunkId = newId;
271
+ }
272
+ else {
273
+ // Historical bucket insert: place in sorted order and close handle.
274
+ let insertAt = this.chunks.length;
275
+ for (let i = 0; i < this.chunks.length; ++i) {
276
+ if (this.chunks[i].baseSlotId > chunk.baseSlotId) {
277
+ insertAt = i;
278
+ break;
279
+ }
280
+ }
281
+ this.chunks.splice(insertAt, 0, chunk);
282
+ }
283
+ this._byteSize += byteSize;
284
+ manifestDirty = true;
285
+ }
286
+ finally {
287
+ if (!isNewLast) {
288
+ await handle.close();
289
+ }
290
+ }
291
+ }
292
+ cursor = writeEnd;
293
+ srcSlotOffset += count;
294
+ }
295
+ if (manifestDirty) {
296
+ await this.writeManifest();
297
+ }
298
+ }
299
+ async writeIntoChunk(handle, chunk, startSlotId, data, numSlots) {
300
+ const oldEnd = chunk.baseSlotId + chunk.slotCount;
301
+ let headerChanged = false;
302
+ if (startSlotId < chunk.baseSlotId) {
303
+ const prependCount = chunk.baseSlotId - startSlotId;
304
+ const existingBytes = chunk.slotCount * ROLLUP_SLOT_BYTES;
116
305
  if (existingBytes > 0) {
117
306
  const existingBuf = new Uint8Array(new ArrayBuffer(existingBytes));
118
- await this.handle.read(existingBuf, 0, existingBytes, ROLLUP_HEADER_BYTES);
119
- await this.handle.write(existingBuf, 0, existingBytes, ROLLUP_HEADER_BYTES + prependCount * ROLLUP_SLOT_BYTES);
307
+ await handle.read(existingBuf, 0, existingBytes, ROLLUP_HEADER_BYTES);
308
+ await handle.write(existingBuf, 0, existingBytes, ROLLUP_HEADER_BYTES + prependCount * ROLLUP_SLOT_BYTES);
120
309
  }
121
310
  if (prependCount > numSlots) {
122
311
  const gap = makeGapSlotsBuffer(prependCount - numSlots);
123
- await this.writeAlignedFloats(ROLLUP_HEADER_BYTES + numSlots * ROLLUP_SLOT_BYTES, gap, prependCount - numSlots);
312
+ await this.writeAlignedFloats(handle, ROLLUP_HEADER_BYTES + numSlots * ROLLUP_SLOT_BYTES, gap, prependCount - numSlots);
124
313
  }
125
- this.baseSlotId = startSlotId;
126
- this.slotCount += prependCount;
314
+ chunk.baseSlotId = startSlotId;
315
+ chunk.slotCount += prependCount;
316
+ headerChanged = true;
127
317
  }
128
- else if (startSlotId > this.endSlotId) {
129
- // Fill missed slots between endSlotId and startSlotId with interruption (NaN) markers.
130
- const gapCount = startSlotId - this.endSlotId;
131
- const chunkSlots = Math.min(gapCount, 4096);
132
- const gapChunk = makeGapSlotsBuffer(chunkSlots);
133
- let cursor = this.endSlotId;
318
+ else if (startSlotId > oldEnd) {
319
+ const gapCount = startSlotId - oldEnd;
320
+ const batchSlots = Math.min(gapCount, 512);
321
+ const gapChunk = makeGapSlotsBuffer(batchSlots);
322
+ let cursor = oldEnd;
134
323
  let remaining = gapCount;
135
324
  while (remaining > 0) {
136
- const batch = Math.min(remaining, chunkSlots);
137
- const offset = ROLLUP_HEADER_BYTES + (cursor - this.baseSlotId) * ROLLUP_SLOT_BYTES;
138
- await this.writeAlignedFloats(offset, gapChunk, batch);
325
+ const batch = Math.min(remaining, batchSlots);
326
+ const offset = ROLLUP_HEADER_BYTES + (cursor - chunk.baseSlotId) * ROLLUP_SLOT_BYTES;
327
+ await this.writeAlignedFloats(handle, offset, gapChunk, batch);
139
328
  cursor += batch;
140
329
  remaining -= batch;
141
330
  }
142
- this.slotCount = startSlotId - this.baseSlotId;
331
+ chunk.slotCount = startSlotId - chunk.baseSlotId;
332
+ headerChanged = true;
143
333
  }
144
- const writeOffset = ROLLUP_HEADER_BYTES + (startSlotId - this.baseSlotId) * ROLLUP_SLOT_BYTES;
145
- await this.writeAlignedFloats(writeOffset, data, numSlots);
334
+ const writeOffset = ROLLUP_HEADER_BYTES + (startSlotId - chunk.baseSlotId) * ROLLUP_SLOT_BYTES;
335
+ await this.writeAlignedFloats(handle, writeOffset, data, numSlots);
146
336
  const newEnd = startSlotId + numSlots;
147
- if (newEnd > this.endSlotId) {
148
- this.slotCount = newEnd - this.baseSlotId;
337
+ if (newEnd > chunk.baseSlotId + chunk.slotCount) {
338
+ chunk.slotCount = newEnd - chunk.baseSlotId;
339
+ headerChanged = true;
340
+ }
341
+ if (headerChanged) {
342
+ const newByteSize = ROLLUP_HEADER_BYTES + chunk.slotCount * ROLLUP_SLOT_BYTES;
343
+ this._byteSize += newByteSize - chunk.byteSize;
344
+ chunk.byteSize = newByteSize;
345
+ await this.writeChunkHeader(handle, chunk.baseSlotId, chunk.slotCount);
149
346
  }
150
- await this.writeHeader();
347
+ return headerChanged;
151
348
  }
152
- async writeAlignedFloats(position, data, numSlots) {
349
+ async writeAlignedFloats(handle, position, data, numSlots) {
153
350
  const byteLen = numSlots * ROLLUP_SLOT_BYTES;
154
351
  if (IS_LITTLE_ENDIAN) {
155
352
  const bytes = new Uint8Array(data.buffer, data.byteOffset, byteLen);
156
- await this.handle.write(bytes, 0, byteLen, position);
353
+ await handle.write(bytes, 0, byteLen, position);
157
354
  return;
158
355
  }
159
356
  const scratch = new ArrayBuffer(byteLen);
@@ -162,69 +359,169 @@ export class RollupFile {
162
359
  for (let i = 0; i < floats; ++i) {
163
360
  dv.setFloat64(i * 8, data[i], true);
164
361
  }
165
- await this.handle.write(new Uint8Array(scratch), 0, byteLen, position);
362
+ await handle.write(new Uint8Array(scratch), 0, byteLen, position);
363
+ }
364
+ async readChunkSlice(handle, chunk, fromSlotId, count, out, outSlotOffset) {
365
+ const byteLen = count * ROLLUP_SLOT_BYTES;
366
+ const offset = ROLLUP_HEADER_BYTES + (fromSlotId - chunk.baseSlotId) * ROLLUP_SLOT_BYTES;
367
+ if (IS_LITTLE_ENDIAN) {
368
+ const bytes = new Uint8Array(out.buffer, out.byteOffset + outSlotOffset * ROLLUP_SLOT_BYTES, byteLen);
369
+ await handle.read(bytes, 0, byteLen, offset);
370
+ return;
371
+ }
372
+ const buf = new ArrayBuffer(byteLen);
373
+ const bytesRead = await handle.read(new Uint8Array(buf), 0, byteLen, offset);
374
+ const actualCount = Math.floor(bytesRead / ROLLUP_SLOT_BYTES);
375
+ const dv = new DataView(buf);
376
+ const floats = actualCount * ROLLUP_SLOT_FLOATS;
377
+ const baseFloat = outSlotOffset * ROLLUP_SLOT_FLOATS;
378
+ for (let i = 0; i < floats; ++i) {
379
+ out[baseFloat + i] = dv.getFloat64(i * 8, true);
380
+ }
166
381
  }
167
382
  async readSlotRange(fromSlotId, toSlotIdInclusive) {
168
- if (!this.handle)
383
+ if (!this.opened)
169
384
  await this.open();
170
- if (!this.hasData || this.slotCount <= 0 || toSlotIdInclusive < this.baseSlotId || fromSlotId >= this.endSlotId) {
385
+ if (!this.hasData || toSlotIdInclusive < this.baseSlotId || fromSlotId >= this.endSlotId) {
171
386
  return { firstSlotId: 0, data: new Float64Array(0), count: 0 };
172
387
  }
173
388
  const clampedFrom = Math.max(fromSlotId, this.baseSlotId);
174
389
  const clampedTo = Math.min(toSlotIdInclusive, this.endSlotId - 1);
175
- const count = clampedTo - clampedFrom + 1;
176
- if (count <= 0) {
390
+ const totalCount = clampedTo - clampedFrom + 1;
391
+ if (totalCount <= 0) {
177
392
  return { firstSlotId: 0, data: new Float64Array(0), count: 0 };
178
393
  }
179
- const byteLen = count * ROLLUP_SLOT_BYTES;
180
- const buf = new ArrayBuffer(byteLen);
181
- const u8 = new Uint8Array(buf);
182
- const offset = ROLLUP_HEADER_BYTES + (clampedFrom - this.baseSlotId) * ROLLUP_SLOT_BYTES;
183
- const bytesRead = await this.handle.read(u8, 0, byteLen, offset);
184
- const actualCount = Math.floor(bytesRead / ROLLUP_SLOT_BYTES);
185
- if (IS_LITTLE_ENDIAN) {
186
- return {
187
- firstSlotId: clampedFrom,
188
- data: new Float64Array(buf, 0, actualCount * ROLLUP_SLOT_FLOATS),
189
- count: actualCount,
190
- };
394
+ const out = makeGapSlotsBuffer(totalCount);
395
+ // Binary search first chunk with chunkEnd > clampedFrom.
396
+ let lo = 0;
397
+ let hi = this.chunks.length - 1;
398
+ let startIdx = this.chunks.length;
399
+ while (lo <= hi) {
400
+ const mid = (lo + hi) >>> 1;
401
+ const c = this.chunks[mid];
402
+ if (c.baseSlotId + c.slotCount > clampedFrom) {
403
+ startIdx = mid;
404
+ hi = mid - 1;
405
+ }
406
+ else {
407
+ lo = mid + 1;
408
+ }
191
409
  }
192
- const dv = new DataView(buf);
193
- const out = new Float64Array(new ArrayBuffer(actualCount * ROLLUP_SLOT_BYTES));
194
- const floats = actualCount * ROLLUP_SLOT_FLOATS;
195
- for (let i = 0; i < floats; ++i) {
196
- out[i] = dv.getFloat64(i * 8, true);
410
+ for (let i = startIdx; i < this.chunks.length; ++i) {
411
+ const chunk = this.chunks[i];
412
+ if (chunk.baseSlotId > clampedTo)
413
+ break;
414
+ const cFrom = Math.max(clampedFrom, chunk.baseSlotId);
415
+ const cTo = Math.min(clampedTo, chunk.baseSlotId + chunk.slotCount - 1);
416
+ const cCount = cTo - cFrom + 1;
417
+ if (cCount <= 0)
418
+ continue;
419
+ const isActive = chunk.id === this.activeChunkId && this.activeHandle !== null;
420
+ const handle = isActive ? this.activeHandle : await this.backend.open(this.chunkPath(chunk.id));
421
+ try {
422
+ await this.readChunkSlice(handle, chunk, cFrom, cCount, out, cFrom - clampedFrom);
423
+ }
424
+ finally {
425
+ if (!isActive) {
426
+ await handle.close();
427
+ }
428
+ }
429
+ }
430
+ return { firstSlotId: clampedFrom, data: out, count: totalCount };
431
+ }
432
+ listChunks() {
433
+ return this.chunks.map((c) => ({
434
+ id: c.id,
435
+ minKey: c.baseSlotId,
436
+ maxKey: c.baseSlotId + c.slotCount - 1,
437
+ byteSize: c.byteSize,
438
+ count: c.slotCount,
439
+ }));
440
+ }
441
+ async dropChunks(chunkIds) {
442
+ if (!this.opened)
443
+ await this.open();
444
+ if (chunkIds.length === 0 || this.chunks.length === 0)
445
+ return;
446
+ const dropSet = new Set(chunkIds);
447
+ const remaining = [];
448
+ let droppedAny = false;
449
+ for (let i = 0; i < this.chunks.length; ++i) {
450
+ const c = this.chunks[i];
451
+ if (dropSet.has(c.id)) {
452
+ droppedAny = true;
453
+ if (c.id === this.activeChunkId && this.activeHandle) {
454
+ await this.activeHandle.close();
455
+ this.activeHandle = null;
456
+ this.activeChunkId = -1;
457
+ }
458
+ this._byteSize -= c.byteSize;
459
+ await this.backend.remove(this.chunkPath(c.id));
460
+ }
461
+ else {
462
+ remaining.push(c);
463
+ }
197
464
  }
198
- return { firstSlotId: clampedFrom, data: out, count: actualCount };
465
+ if (!droppedAny)
466
+ return;
467
+ this.chunks = remaining;
468
+ await this.writeManifest();
199
469
  }
200
470
  async compact(keepFromSlotId) {
201
- if (!this.handle)
471
+ if (!this.opened)
202
472
  await this.open();
203
473
  if (!this.hasData || keepFromSlotId <= this.baseSlotId)
204
474
  return;
205
- if (keepFromSlotId >= this.endSlotId) {
206
- this.baseSlotId = 0;
207
- this.slotCount = 0;
208
- this.hasData = false;
209
- await this.writeHeader();
210
- await this.handle.truncate(ROLLUP_HEADER_BYTES);
211
- return;
475
+ const wholeDrops = [];
476
+ for (let i = 0; i < this.chunks.length; ++i) {
477
+ const c = this.chunks[i];
478
+ if (c.baseSlotId + c.slotCount <= keepFromSlotId) {
479
+ wholeDrops.push(c.id);
480
+ }
481
+ else {
482
+ break;
483
+ }
484
+ }
485
+ if (wholeDrops.length > 0) {
486
+ await this.dropChunks(wholeDrops);
212
487
  }
213
- const dropCount = keepFromSlotId - this.baseSlotId;
214
- const keepCount = this.slotCount - dropCount;
488
+ if (this.chunks.length === 0)
489
+ return;
490
+ const head = this.chunks[0];
491
+ if (head.baseSlotId >= keepFromSlotId)
492
+ return;
493
+ const dropCount = keepFromSlotId - head.baseSlotId;
494
+ const keepCount = head.slotCount - dropCount;
215
495
  const keepBytes = keepCount * ROLLUP_SLOT_BYTES;
216
- const buf = new Uint8Array(new ArrayBuffer(keepBytes));
217
- await this.handle.read(buf, 0, keepBytes, ROLLUP_HEADER_BYTES + dropCount * ROLLUP_SLOT_BYTES);
218
- await this.handle.write(buf, 0, keepBytes, ROLLUP_HEADER_BYTES);
219
- this.baseSlotId = keepFromSlotId;
220
- this.slotCount = keepCount;
221
- await this.writeHeader();
222
- await this.handle.truncate(ROLLUP_HEADER_BYTES + keepBytes);
496
+ const isActive = head.id === this.activeChunkId && this.activeHandle !== null;
497
+ const handle = isActive ? this.activeHandle : await this.backend.open(this.chunkPath(head.id));
498
+ try {
499
+ const buf = new Uint8Array(new ArrayBuffer(keepBytes));
500
+ await handle.read(buf, 0, keepBytes, ROLLUP_HEADER_BYTES + dropCount * ROLLUP_SLOT_BYTES);
501
+ await handle.write(buf, 0, keepBytes, ROLLUP_HEADER_BYTES);
502
+ head.baseSlotId = keepFromSlotId;
503
+ head.slotCount = keepCount;
504
+ const newByteSize = ROLLUP_HEADER_BYTES + keepBytes;
505
+ this._byteSize += newByteSize - head.byteSize;
506
+ head.byteSize = newByteSize;
507
+ await this.writeChunkHeader(handle, head.baseSlotId, head.slotCount);
508
+ await handle.truncate(newByteSize);
509
+ }
510
+ finally {
511
+ if (!isActive) {
512
+ await handle.close();
513
+ }
514
+ }
515
+ await this.writeManifest();
223
516
  }
224
517
  async close() {
225
- if (this.handle) {
226
- await this.handle.close();
227
- this.handle = null;
518
+ if (this.activeDirtyForManifest) {
519
+ await this.writeManifest();
520
+ }
521
+ if (this.activeHandle) {
522
+ await this.activeHandle.close();
523
+ this.activeHandle = null;
524
+ this.activeChunkId = -1;
228
525
  }
229
526
  }
230
527
  }
package/dist/series.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { TsdbStore } from './store.ts';
2
2
  import { ServerCalendar } from './time.ts';
3
- import type { NormalizedSeriesConfig, NumericColumnResult, NumericQueryOptions, NumericQueryResult, SeriesConfig, SeriesMeta, ValueCodec, ValueQueryOptions, ValueQueryResult } from './types.ts';
3
+ import type { NormalizedSeriesConfig, NumericColumnResult, NumericQueryOptions, NumericQueryResult, RollupTier, SeriesConfig, SeriesMeta, StorageChunkInfo, ValueCodec, ValueQueryOptions, ValueQueryResult } from './types.ts';
4
4
  export declare function normalizeSeriesConfig(config: SeriesConfig, defaults?: Partial<Omit<SeriesConfig, 'kind'>>): NormalizedSeriesConfig;
5
5
  export declare class NumericSeries {
6
6
  readonly meta: SeriesMeta;
@@ -21,6 +21,13 @@ export declare class NumericSeries {
21
21
  private readonly listeners;
22
22
  constructor(meta: SeriesMeta, store: TsdbStore, calendar: ServerCalendar);
23
23
  get hasDirtyData(): boolean;
24
+ getRawByteSize(): number;
25
+ getRollupByteSize(tier: RollupTier): number;
26
+ getActiveRollupTiers(): RollupTier[];
27
+ listRawChunks(): ReadonlyArray<StorageChunkInfo>;
28
+ listRollupChunks(tier: RollupTier): ReadonlyArray<StorageChunkInfo>;
29
+ dropRawChunks(chunkIds: ReadonlyArray<number>): Promise<void>;
30
+ dropRollupChunks(tier: RollupTier, chunkIds: ReadonlyArray<number>): Promise<void>;
24
31
  open(): Promise<void>;
25
32
  subscribe(listener: (ts: number, value: number | boolean) => void): () => void;
26
33
  write(tsMs: number, input: number | boolean): void;
@@ -30,6 +37,7 @@ export declare class NumericSeries {
30
37
  private getTierMinSlotId;
31
38
  private getTierMaxSlotId;
32
39
  private readTierSlots;
40
+ private selectFallbackTier;
33
41
  private getFinestEnabledTier;
34
42
  private selectServingTier;
35
43
  private readMergedRaw;
@@ -52,6 +60,9 @@ export declare class ValueSeries {
52
60
  private readonly listeners;
53
61
  constructor(meta: SeriesMeta, store: TsdbStore, calendar: ServerCalendar, codec: ValueCodec);
54
62
  get hasDirtyData(): boolean;
63
+ getByteSize(): number;
64
+ listChunks(): ReadonlyArray<StorageChunkInfo>;
65
+ dropChunks(chunkIds: ReadonlyArray<number>): Promise<void>;
55
66
  open(): Promise<void>;
56
67
  subscribe(listener: (ts: number, value: unknown) => void): () => void;
57
68
  write(tsMs: number, value: unknown): void;