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.
package/dist/series.js ADDED
@@ -0,0 +1,1223 @@
1
+ import { MemoryRingCache } from './memoryCache.js';
2
+ import { ROLLUP_SLOT_BYTES, ROLLUP_SLOT_FLOATS, SLOT_COUNT, SLOT_FINAL, SLOT_FIRST, SLOT_INITIAL, SLOT_MAX, SLOT_MIN, SLOT_SUM, } from './rollupFile.js';
3
+ import { canTierServeInterval, parseInterval, selectAutoInterval, TIER_STEP_MS, toEpochMs, } from './time.js';
4
+ const ROLLUP_TIERS_FINEST_TO_COARSEST = ['15s', '5m', '1h', '1d'];
5
+ const ROLLUP_TIERS_COARSEST_TO_FINEST = ['1d', '1h', '5m', '15s'];
6
+ const MAX_SYNTHETIC_GAP_SLOTS = 65_536;
7
+ function normalizeTier(option, defaultEnabled) {
8
+ if (option === undefined)
9
+ return { enabled: defaultEnabled };
10
+ if (typeof option === 'boolean')
11
+ return { enabled: option };
12
+ return { enabled: Boolean(option.enabled), retentionMs: option.retentionMs };
13
+ }
14
+ function normalizeRaw(option, defaultEnabled) {
15
+ if (option === undefined)
16
+ return { enabled: defaultEnabled };
17
+ if (typeof option === 'boolean')
18
+ return { enabled: option };
19
+ return { enabled: Boolean(option.enabled), retentionMs: option.retentionMs, maxRecords: option.maxRecords };
20
+ }
21
+ function normalizeMemoryCache(option, isNumeric) {
22
+ if (!isNumeric)
23
+ return { enabled: false, maxEntries: 0 };
24
+ if (option === undefined)
25
+ return { enabled: true, maxEntries: 1024, maxAgeMs: 10 * 60_000 };
26
+ if (typeof option === 'boolean')
27
+ return { enabled: option, maxEntries: 1024, maxAgeMs: 10 * 60_000 };
28
+ return {
29
+ enabled: Boolean(option.enabled),
30
+ maxEntries: Math.max(1, option.maxEntries ?? 1024),
31
+ maxAgeMs: option.maxAgeMs ?? 10 * 60_000,
32
+ };
33
+ }
34
+ export function normalizeSeriesConfig(config, defaults) {
35
+ const isNumeric = config.kind !== 'value';
36
+ return {
37
+ kind: config.kind,
38
+ raw: isNumeric
39
+ ? normalizeRaw(config.raw ?? defaults?.raw, true)
40
+ : {
41
+ enabled: true,
42
+ retentionMs: typeof config.raw === 'object' ? config.raw.retentionMs : undefined,
43
+ maxRecords: typeof config.raw === 'object' ? config.raw.maxRecords : undefined,
44
+ },
45
+ rollup15s: isNumeric ? normalizeTier(config.rollup15s ?? defaults?.rollup15s, false) : { enabled: false },
46
+ rollup5m: isNumeric ? normalizeTier(config.rollup5m ?? defaults?.rollup5m, false) : { enabled: false },
47
+ rollup1h: isNumeric ? normalizeTier(config.rollup1h ?? defaults?.rollup1h, true) : { enabled: false },
48
+ rollup1d: isNumeric ? normalizeTier(config.rollup1d ?? defaults?.rollup1d, true) : { enabled: false },
49
+ memoryCache: normalizeMemoryCache(config.memoryCache ?? defaults?.memoryCache, isNumeric),
50
+ };
51
+ }
52
+ function createTierState(tier, retentionMs) {
53
+ return {
54
+ tier,
55
+ file: null,
56
+ retentionMs,
57
+ openSlotId: Number.NaN,
58
+ openCount: 0,
59
+ openSum: Number.NaN,
60
+ openMin: Number.NaN,
61
+ openMax: Number.NaN,
62
+ openInitial: Number.NaN,
63
+ openFirst: Number.NaN,
64
+ openFinal: Number.NaN,
65
+ dirtyStartSlotId: Number.NaN,
66
+ dirtyCount: 0,
67
+ dirtyData: new Float64Array(new ArrayBuffer(64 * ROLLUP_SLOT_BYTES)),
68
+ diskEndSlotId: Number.NaN,
69
+ lastWriteWasReopenSlot: false,
70
+ };
71
+ }
72
+ function appendDirtySlot(state, slotId, count, sum, min, max, initial, first, finalVal) {
73
+ if (state.dirtyCount === 0) {
74
+ state.dirtyStartSlotId = slotId;
75
+ }
76
+ const neededFloats = (state.dirtyCount + 1) * ROLLUP_SLOT_FLOATS;
77
+ if (neededFloats > state.dirtyData.length) {
78
+ const nextCapFloats = Math.max(neededFloats, state.dirtyData.length * 2);
79
+ const nextBuf = new Float64Array(new ArrayBuffer(nextCapFloats * 8));
80
+ nextBuf.set(state.dirtyData.subarray(0, state.dirtyCount * ROLLUP_SLOT_FLOATS));
81
+ state.dirtyData = nextBuf;
82
+ }
83
+ const base = state.dirtyCount * ROLLUP_SLOT_FLOATS;
84
+ state.dirtyData[base + SLOT_COUNT] = count;
85
+ state.dirtyData[base + SLOT_SUM] = sum;
86
+ state.dirtyData[base + SLOT_MIN] = min;
87
+ state.dirtyData[base + SLOT_MAX] = max;
88
+ state.dirtyData[base + SLOT_INITIAL] = initial;
89
+ state.dirtyData[base + SLOT_FIRST] = first;
90
+ state.dirtyData[base + SLOT_FINAL] = finalVal;
91
+ state.dirtyCount++;
92
+ }
93
+ function writeOpenSlotToBuffer(state, target, floatOffset) {
94
+ target[floatOffset + SLOT_COUNT] = state.openCount;
95
+ target[floatOffset + SLOT_SUM] = state.openSum;
96
+ target[floatOffset + SLOT_MIN] = state.openMin;
97
+ target[floatOffset + SLOT_MAX] = state.openMax;
98
+ target[floatOffset + SLOT_INITIAL] = state.openInitial;
99
+ target[floatOffset + SLOT_FIRST] = state.openFirst;
100
+ target[floatOffset + SLOT_FINAL] = state.openFinal;
101
+ }
102
+ function extractRollupValue(rollup, hasActive, count, sum, min, max, initial, first, finalVal) {
103
+ switch (rollup) {
104
+ case 'count':
105
+ return hasActive ? count : 0;
106
+ case 'sum':
107
+ return count > 0 ? sum : Number.NaN;
108
+ case 'avg':
109
+ return count > 0 ? sum / count : Number.NaN;
110
+ case 'min':
111
+ case 'and':
112
+ return count > 0 ? min : Number.NaN;
113
+ case 'max':
114
+ case 'or':
115
+ return count > 0 ? max : Number.NaN;
116
+ case 'initial':
117
+ return hasActive ? initial : Number.NaN;
118
+ case 'final':
119
+ return hasActive ? finalVal : Number.NaN;
120
+ case 'first':
121
+ return count > 0 ? first : Number.NaN;
122
+ case 'delta':
123
+ return hasActive ? finalVal - initial : Number.NaN;
124
+ }
125
+ }
126
+ export class NumericSeries {
127
+ meta;
128
+ store;
129
+ calendar;
130
+ rawFile = null;
131
+ tiers = {};
132
+ activeTiers = [];
133
+ memoryCache;
134
+ pendingRaw = new Float64Array(new ArrayBuffer(256 * 16));
135
+ pendingRawCount = 0;
136
+ continuous = false;
137
+ lastTs = Number.NaN;
138
+ lastValue = Number.NaN;
139
+ flushChain = Promise.resolve();
140
+ dirty = false;
141
+ closed = false;
142
+ listeners = new Set();
143
+ constructor(meta, store, calendar) {
144
+ this.meta = meta;
145
+ this.store = store;
146
+ this.calendar = calendar;
147
+ const cfg = meta.config;
148
+ this.memoryCache = cfg.memoryCache.enabled
149
+ ? new MemoryRingCache(cfg.memoryCache.maxEntries, cfg.memoryCache.maxAgeMs)
150
+ : null;
151
+ const tierConfigs = [
152
+ ['15s', cfg.rollup15s],
153
+ ['5m', cfg.rollup5m],
154
+ ['1h', cfg.rollup1h],
155
+ ['1d', cfg.rollup1d],
156
+ ];
157
+ for (const [tier, tcfg] of tierConfigs) {
158
+ if (tcfg.enabled) {
159
+ const state = createTierState(tier, tcfg.retentionMs);
160
+ this.tiers[tier] = state;
161
+ this.activeTiers.push(state);
162
+ }
163
+ }
164
+ }
165
+ get hasDirtyData() {
166
+ return this.dirty;
167
+ }
168
+ getRawByteSize() {
169
+ return this.rawFile?.byteSize ?? 0;
170
+ }
171
+ getRollupByteSize(tier) {
172
+ return this.tiers[tier]?.file.byteSize ?? 0;
173
+ }
174
+ getActiveRollupTiers() {
175
+ return this.activeTiers.map((s) => s.tier);
176
+ }
177
+ listRawChunks() {
178
+ return this.rawFile?.listChunks?.() ?? [];
179
+ }
180
+ listRollupChunks(tier) {
181
+ return this.tiers[tier]?.file.listChunks?.() ?? [];
182
+ }
183
+ dropRawChunks(chunkIds) {
184
+ if (!this.rawFile?.dropChunks || chunkIds.length === 0)
185
+ return Promise.resolve();
186
+ this.flushChain = this.flushChain.then(() => this.rawFile.dropChunks(chunkIds));
187
+ return this.flushChain;
188
+ }
189
+ dropRollupChunks(tier, chunkIds) {
190
+ const state = this.tiers[tier];
191
+ if (!state?.file.dropChunks || chunkIds.length === 0)
192
+ return Promise.resolve();
193
+ this.flushChain = this.flushChain.then(async () => {
194
+ await state.file.dropChunks(chunkIds);
195
+ state.diskEndSlotId = state.file.hasData ? state.file.endSlotId : Number.NaN;
196
+ if (!state.file.hasData || (!Number.isNaN(state.openSlotId) && state.openSlotId < state.file.baseSlotId)) {
197
+ state.openSlotId = Number.NaN;
198
+ state.openCount = 0;
199
+ state.openSum = Number.NaN;
200
+ state.openMin = Number.NaN;
201
+ state.openMax = Number.NaN;
202
+ state.openInitial = Number.NaN;
203
+ state.openFirst = Number.NaN;
204
+ state.openFinal = Number.NaN;
205
+ state.lastWriteWasReopenSlot = false;
206
+ }
207
+ let anyHasOpen = false;
208
+ for (let i = 0; i < this.activeTiers.length; ++i) {
209
+ if (!Number.isNaN(this.activeTiers[i].openSlotId)) {
210
+ anyHasOpen = true;
211
+ break;
212
+ }
213
+ }
214
+ if (!anyHasOpen && (!this.rawFile || this.rawFile.recordCount === 0)) {
215
+ this.continuous = false;
216
+ }
217
+ });
218
+ return this.flushChain;
219
+ }
220
+ async open() {
221
+ if (this.meta.config.raw.enabled) {
222
+ this.rawFile = await this.store.openNumericRaw(this.meta);
223
+ }
224
+ for (let i = 0; i < this.activeTiers.length; ++i) {
225
+ const state = this.activeTiers[i];
226
+ state.file = await this.store.openRollupTier(this.meta, state.tier);
227
+ if (state.file.hasData) {
228
+ state.diskEndSlotId = state.file.endSlotId;
229
+ const last = await state.file.readLastSlot();
230
+ if (last) {
231
+ const d = last.data;
232
+ state.openSlotId = last.slotId;
233
+ state.openCount = d[SLOT_COUNT];
234
+ state.openSum = d[SLOT_SUM];
235
+ state.openMin = d[SLOT_MIN];
236
+ state.openMax = d[SLOT_MAX];
237
+ state.openInitial = d[SLOT_INITIAL];
238
+ state.openFirst = d[SLOT_FIRST];
239
+ state.openFinal = d[SLOT_FINAL];
240
+ state.lastWriteWasReopenSlot = true;
241
+ }
242
+ }
243
+ }
244
+ // Reopened process treats downtime until next write as a data interruption (continuous = false).
245
+ this.continuous = false;
246
+ }
247
+ subscribe(listener) {
248
+ this.listeners.add(listener);
249
+ return () => {
250
+ this.listeners.delete(listener);
251
+ };
252
+ }
253
+ write(tsMs, input) {
254
+ if (this.closed)
255
+ throw new Error(`Series "${this.meta.id}" is closed`);
256
+ const isBool = this.meta.config.kind === 'boolean';
257
+ const val = typeof input === 'boolean' ? (input ? 1 : 0) : input;
258
+ if (typeof val !== 'number' || Number.isNaN(val)) {
259
+ this.markInterruption(tsMs);
260
+ return;
261
+ }
262
+ if (!Number.isNaN(this.lastTs) && tsMs < this.lastTs) {
263
+ throw new Error(`Out-of-order timestamp for series "${this.meta.id}": ${tsMs} < ${this.lastTs}`);
264
+ }
265
+ if (this.memoryCache) {
266
+ this.memoryCache.push(tsMs, val);
267
+ }
268
+ if (this.rawFile) {
269
+ if ((this.pendingRawCount + 1) * 2 > this.pendingRaw.length) {
270
+ const next = new Float64Array(new ArrayBuffer(this.pendingRaw.length * 2 * 8));
271
+ next.set(this.pendingRaw.subarray(0, this.pendingRawCount * 2));
272
+ this.pendingRaw = next;
273
+ }
274
+ const pIdx = this.pendingRawCount * 2;
275
+ this.pendingRaw[pIdx] = tsMs;
276
+ this.pendingRaw[pIdx + 1] = val;
277
+ this.pendingRawCount++;
278
+ this.dirty = true;
279
+ }
280
+ for (let i = 0; i < this.activeTiers.length; ++i) {
281
+ const state = this.activeTiers[i];
282
+ const slotId = this.calendar.tierToSlotId(state.tier, tsMs);
283
+ if (slotId === state.openSlotId) {
284
+ if (state.openCount === 0) {
285
+ if (Number.isNaN(state.openInitial)) {
286
+ state.openInitial = val;
287
+ }
288
+ state.openCount = 1;
289
+ state.openSum = val;
290
+ state.openMin = val;
291
+ state.openMax = val;
292
+ state.openFirst = val;
293
+ state.openFinal = val;
294
+ }
295
+ else {
296
+ state.openCount++;
297
+ state.openSum += val;
298
+ if (val < state.openMin)
299
+ state.openMin = val;
300
+ if (val > state.openMax)
301
+ state.openMax = val;
302
+ state.openFinal = val;
303
+ }
304
+ state.lastWriteWasReopenSlot = false;
305
+ this.dirty = true;
306
+ continue;
307
+ }
308
+ // Crossing into a new slot.
309
+ if (!Number.isNaN(state.openSlotId)) {
310
+ if (slotId < state.openSlotId) {
311
+ throw new Error(`Out-of-order rollup slot for series "${this.meta.id}": ${slotId} < ${state.openSlotId}`);
312
+ }
313
+ if (!state.lastWriteWasReopenSlot) {
314
+ // Close current active openSlot into dirty buffer.
315
+ appendDirtySlot(state, state.openSlotId, state.openCount, state.openSum, state.openMin, state.openMax, state.openInitial, state.openFirst, state.openFinal);
316
+ if (this.continuous) {
317
+ const prevFinal = state.openFinal;
318
+ const gapSlots = slotId - state.openSlotId - 1;
319
+ const fillStart = gapSlots > MAX_SYNTHETIC_GAP_SLOTS ? slotId - MAX_SYNTHETIC_GAP_SLOTS : state.openSlotId + 1;
320
+ for (let s = fillStart; s < slotId; ++s) {
321
+ appendDirtySlot(state, s, 0, Number.NaN, Number.NaN, Number.NaN, prevFinal, Number.NaN, prevFinal);
322
+ }
323
+ }
324
+ }
325
+ state.lastWriteWasReopenSlot = false;
326
+ }
327
+ // Rule #2: if continuous, initial carries from previous final; if interrupted/fresh, initial = current val.
328
+ const initial = this.continuous ? this.lastValue : val;
329
+ state.openSlotId = slotId;
330
+ state.openCount = 1;
331
+ state.openSum = val;
332
+ state.openMin = val;
333
+ state.openMax = val;
334
+ state.openInitial = initial;
335
+ state.openFirst = val;
336
+ state.openFinal = val;
337
+ this.dirty = true;
338
+ }
339
+ this.continuous = true;
340
+ this.lastTs = tsMs;
341
+ this.lastValue = val;
342
+ if (this.listeners.size > 0) {
343
+ const emitted = isBool ? val !== 0 : val;
344
+ for (const listener of this.listeners) {
345
+ listener(tsMs, emitted);
346
+ }
347
+ }
348
+ }
349
+ markInterruption(tsMs) {
350
+ this.continuous = false;
351
+ this.lastValue = Number.NaN;
352
+ if (this.memoryCache && tsMs !== undefined) {
353
+ this.memoryCache.markGap(tsMs);
354
+ }
355
+ if (this.rawFile && tsMs !== undefined) {
356
+ if ((this.pendingRawCount + 1) * 2 > this.pendingRaw.length) {
357
+ const next = new Float64Array(new ArrayBuffer(this.pendingRaw.length * 2 * 8));
358
+ next.set(this.pendingRaw.subarray(0, this.pendingRawCount * 2));
359
+ this.pendingRaw = next;
360
+ }
361
+ const pIdx = this.pendingRawCount * 2;
362
+ this.pendingRaw[pIdx] = tsMs;
363
+ this.pendingRaw[pIdx + 1] = Number.NaN;
364
+ this.pendingRawCount++;
365
+ this.dirty = true;
366
+ }
367
+ if (tsMs !== undefined && (Number.isNaN(this.lastTs) || tsMs > this.lastTs)) {
368
+ this.lastTs = tsMs;
369
+ }
370
+ }
371
+ flush() {
372
+ this.flushChain = this.flushChain.then(() => this.flushInternal());
373
+ return this.flushChain;
374
+ }
375
+ async flushInternal() {
376
+ if (!this.dirty)
377
+ return;
378
+ this.dirty = false;
379
+ if (this.rawFile && this.pendingRawCount > 0) {
380
+ const count = this.pendingRawCount;
381
+ const batch = this.pendingRaw.subarray(0, count * 2);
382
+ // Copy slice before async write so concurrent writes can safely append into pendingRaw.
383
+ const copy = new Float64Array(new ArrayBuffer(count * 16));
384
+ copy.set(batch);
385
+ this.pendingRawCount = 0;
386
+ await this.rawFile.appendBatch(copy, count);
387
+ const rawCfg = this.meta.config.raw;
388
+ const minTsKeep = rawCfg.retentionMs !== undefined && !Number.isNaN(this.lastTs) ? this.lastTs - rawCfg.retentionMs : undefined;
389
+ if ((rawCfg.maxRecords !== undefined && this.rawFile.recordCount > Math.ceil(rawCfg.maxRecords * 1.25)) ||
390
+ (minTsKeep !== undefined && this.rawFile.recordCount > 256)) {
391
+ await this.rawFile.compact(minTsKeep, rawCfg.maxRecords);
392
+ }
393
+ }
394
+ for (let i = 0; i < this.activeTiers.length; ++i) {
395
+ const state = this.activeTiers[i];
396
+ const hasOpen = !Number.isNaN(state.openSlotId) && !state.lastWriteWasReopenSlot;
397
+ const dirtyCount = state.dirtyCount;
398
+ if (dirtyCount > 0 || hasOpen) {
399
+ if (dirtyCount > 0 && hasOpen && state.openSlotId === state.dirtyStartSlotId + dirtyCount) {
400
+ // Write dirty slots + openSlot together in one contiguous write, keeping openSlot live in memory.
401
+ const total = dirtyCount + 1;
402
+ const buf = new Float64Array(new ArrayBuffer(total * ROLLUP_SLOT_BYTES));
403
+ buf.set(state.dirtyData.subarray(0, dirtyCount * ROLLUP_SLOT_FLOATS));
404
+ writeOpenSlotToBuffer(state, buf, dirtyCount * ROLLUP_SLOT_FLOATS);
405
+ const startId = state.dirtyStartSlotId;
406
+ state.dirtyCount = 0;
407
+ state.dirtyStartSlotId = Number.NaN;
408
+ await state.file.writeSlots(startId, buf, total);
409
+ }
410
+ else {
411
+ if (dirtyCount > 0) {
412
+ const buf = new Float64Array(new ArrayBuffer(dirtyCount * ROLLUP_SLOT_BYTES));
413
+ buf.set(state.dirtyData.subarray(0, dirtyCount * ROLLUP_SLOT_FLOATS));
414
+ const startId = state.dirtyStartSlotId;
415
+ state.dirtyCount = 0;
416
+ state.dirtyStartSlotId = Number.NaN;
417
+ await state.file.writeSlots(startId, buf, dirtyCount);
418
+ }
419
+ if (hasOpen) {
420
+ const openBuf = new Float64Array(new ArrayBuffer(ROLLUP_SLOT_BYTES));
421
+ writeOpenSlotToBuffer(state, openBuf, 0);
422
+ await state.file.writeSlots(state.openSlotId, openBuf, 1);
423
+ }
424
+ }
425
+ state.diskEndSlotId = state.file.endSlotId;
426
+ }
427
+ if (state.retentionMs !== undefined && state.file.hasData && !Number.isNaN(this.lastTs)) {
428
+ const minSlotId = this.calendar.tierToSlotId(state.tier, this.lastTs - state.retentionMs);
429
+ const maxSlots = Math.max(1, Math.ceil(state.retentionMs / TIER_STEP_MS[state.tier]));
430
+ if (state.file.baseSlotId < minSlotId && minSlotId - state.file.baseSlotId > Math.ceil(maxSlots * 0.25)) {
431
+ await state.file.compact(minSlotId);
432
+ }
433
+ }
434
+ }
435
+ }
436
+ getTierMinSlotId(state) {
437
+ let minSlot = state.file.hasData ? state.file.baseSlotId : Number.POSITIVE_INFINITY;
438
+ if (state.dirtyCount > 0 && state.dirtyStartSlotId < minSlot) {
439
+ minSlot = state.dirtyStartSlotId;
440
+ }
441
+ if (!Number.isNaN(state.openSlotId) && state.openSlotId < minSlot) {
442
+ minSlot = state.openSlotId;
443
+ }
444
+ return minSlot;
445
+ }
446
+ getTierMaxSlotId(state) {
447
+ let maxSlot = state.file.hasData ? state.file.endSlotId - 1 : Number.NEGATIVE_INFINITY;
448
+ if (state.dirtyCount > 0) {
449
+ const dirtyEnd = state.dirtyStartSlotId + state.dirtyCount - 1;
450
+ if (dirtyEnd > maxSlot)
451
+ maxSlot = dirtyEnd;
452
+ }
453
+ if (!Number.isNaN(state.openSlotId) && state.openSlotId > maxSlot) {
454
+ maxSlot = state.openSlotId;
455
+ }
456
+ return maxSlot;
457
+ }
458
+ async readTierSlots(state, fromSlotId, toSlotIdInclusive) {
459
+ const minSlot = this.getTierMinSlotId(state);
460
+ const maxSlot = this.getTierMaxSlotId(state);
461
+ if (!Number.isFinite(minSlot) || !Number.isFinite(maxSlot) || toSlotIdInclusive < minSlot || fromSlotId > maxSlot) {
462
+ return { firstSlotId: 0, data: new Float64Array(0), count: 0 };
463
+ }
464
+ const startId = Math.max(fromSlotId, minSlot);
465
+ const endId = Math.min(toSlotIdInclusive, maxSlot);
466
+ const count = endId - startId + 1;
467
+ if (count <= 0) {
468
+ return { firstSlotId: 0, data: new Float64Array(0), count: 0 };
469
+ }
470
+ const out = new Float64Array(new ArrayBuffer(count * ROLLUP_SLOT_BYTES));
471
+ out.fill(Number.NaN);
472
+ for (let i = 0; i < count; ++i) {
473
+ out[i * ROLLUP_SLOT_FLOATS + SLOT_COUNT] = 0;
474
+ }
475
+ if (state.file.hasData && startId < state.file.endSlotId && endId >= state.file.baseSlotId) {
476
+ const diskRes = await state.file.readSlotRange(startId, endId);
477
+ if (diskRes.count > 0) {
478
+ const offsetSlots = diskRes.firstSlotId - startId;
479
+ out.set(diskRes.data.subarray(0, diskRes.count * ROLLUP_SLOT_FLOATS), offsetSlots * ROLLUP_SLOT_FLOATS);
480
+ }
481
+ }
482
+ if (state.dirtyCount > 0) {
483
+ const dirtyEnd = state.dirtyStartSlotId + state.dirtyCount - 1;
484
+ const ovStart = Math.max(startId, state.dirtyStartSlotId);
485
+ const ovEnd = Math.min(endId, dirtyEnd);
486
+ if (ovEnd >= ovStart) {
487
+ const srcOffset = (ovStart - state.dirtyStartSlotId) * ROLLUP_SLOT_FLOATS;
488
+ const dstOffset = (ovStart - startId) * ROLLUP_SLOT_FLOATS;
489
+ const len = (ovEnd - ovStart + 1) * ROLLUP_SLOT_FLOATS;
490
+ out.set(state.dirtyData.subarray(srcOffset, srcOffset + len), dstOffset);
491
+ }
492
+ }
493
+ if (!Number.isNaN(state.openSlotId) && state.openSlotId >= startId && state.openSlotId <= endId) {
494
+ const dstOffset = (state.openSlotId - startId) * ROLLUP_SLOT_FLOATS;
495
+ writeOpenSlotToBuffer(state, out, dstOffset);
496
+ }
497
+ return { firstSlotId: startId, data: out, count };
498
+ }
499
+ selectFallbackTier(startMs, endMs) {
500
+ let partialMatch = null;
501
+ for (let i = 0; i < ROLLUP_TIERS_FINEST_TO_COARSEST.length; ++i) {
502
+ const tier = ROLLUP_TIERS_FINEST_TO_COARSEST[i];
503
+ const state = this.tiers[tier];
504
+ if (!state)
505
+ continue;
506
+ const minSlot = this.getTierMinSlotId(state);
507
+ if (!Number.isFinite(minSlot)) {
508
+ if (!partialMatch)
509
+ partialMatch = state;
510
+ continue;
511
+ }
512
+ const minCoveredTs = this.calendar.tierSlotToUtcMs(tier, minSlot);
513
+ if (minCoveredTs <= startMs) {
514
+ return state;
515
+ }
516
+ if (minCoveredTs <= endMs && !partialMatch) {
517
+ partialMatch = state;
518
+ }
519
+ }
520
+ return partialMatch ?? this.getFinestEnabledTier();
521
+ }
522
+ getFinestEnabledTier() {
523
+ for (let i = 0; i < ROLLUP_TIERS_FINEST_TO_COARSEST.length; ++i) {
524
+ const state = this.tiers[ROLLUP_TIERS_FINEST_TO_COARSEST[i]];
525
+ if (state)
526
+ return state;
527
+ }
528
+ return null;
529
+ }
530
+ selectServingTier(parsed, startMs, endMs) {
531
+ let partialMatch = null;
532
+ for (let i = 0; i < ROLLUP_TIERS_COARSEST_TO_FINEST.length; ++i) {
533
+ const tier = ROLLUP_TIERS_COARSEST_TO_FINEST[i];
534
+ const state = this.tiers[tier];
535
+ if (!state || !canTierServeInterval(tier, parsed))
536
+ continue;
537
+ const minSlot = this.getTierMinSlotId(state);
538
+ if (!Number.isFinite(minSlot)) {
539
+ if (!partialMatch)
540
+ partialMatch = state;
541
+ continue;
542
+ }
543
+ const minCoveredTs = this.calendar.tierSlotToUtcMs(tier, minSlot);
544
+ if (minCoveredTs <= startMs) {
545
+ return state;
546
+ }
547
+ if (minCoveredTs <= endMs && !partialMatch) {
548
+ partialMatch = state;
549
+ }
550
+ }
551
+ return partialMatch;
552
+ }
553
+ async readMergedRaw(startMs, endMs, limit, stripNaN = true) {
554
+ const disk = this.rawFile
555
+ ? await this.rawFile.readRange(startMs, endMs, limit, stripNaN)
556
+ : { timestamps: new Float64Array(0), values: new Float64Array(0), length: 0, truncated: false };
557
+ if (disk.truncated || this.pendingRawCount === 0) {
558
+ return disk;
559
+ }
560
+ // Collect matching pending raw entries.
561
+ const pendStartIdx = lowerBoundInterleaved(this.pendingRaw, this.pendingRawCount, startMs);
562
+ const pendEndIdx = upperBoundInterleaved(this.pendingRaw, this.pendingRawCount, endMs);
563
+ const pendRawCount = Math.max(0, pendEndIdx - pendStartIdx);
564
+ if (pendRawCount === 0)
565
+ return disk;
566
+ let pendValid = 0;
567
+ if (stripNaN) {
568
+ for (let i = pendStartIdx; i < pendEndIdx; ++i) {
569
+ if (!Number.isNaN(this.pendingRaw[i * 2 + 1]))
570
+ pendValid++;
571
+ }
572
+ }
573
+ else {
574
+ pendValid = pendRawCount;
575
+ }
576
+ if (pendValid === 0)
577
+ return disk;
578
+ let total = disk.length + pendValid;
579
+ let truncated = false;
580
+ if (limit !== undefined && limit >= 0 && total > limit) {
581
+ total = limit;
582
+ truncated = true;
583
+ }
584
+ const timestamps = new Float64Array(total);
585
+ const values = new Float64Array(total);
586
+ const diskTake = Math.min(disk.length, total);
587
+ if (diskTake > 0) {
588
+ timestamps.set(disk.timestamps.subarray(0, diskTake), 0);
589
+ values.set(disk.values.subarray(0, diskTake), 0);
590
+ }
591
+ let pos = diskTake;
592
+ for (let i = pendStartIdx; i < pendEndIdx && pos < total; ++i) {
593
+ const v = this.pendingRaw[i * 2 + 1];
594
+ if (!stripNaN || !Number.isNaN(v)) {
595
+ timestamps[pos] = this.pendingRaw[i * 2];
596
+ values[pos] = v;
597
+ pos++;
598
+ }
599
+ }
600
+ return { timestamps, values, length: pos, truncated };
601
+ }
602
+ aggregateRawIntoBuckets(timestamps, values, length, initialPrior, startMs, endMs, interval, rollup) {
603
+ if (length === 0 && Number.isNaN(initialPrior)) {
604
+ return { timestamps: new Float64Array(0), values: new Float64Array(0), length: 0 };
605
+ }
606
+ const startBucket = this.calendar.floorInterval(startMs, interval);
607
+ const endBucket = this.calendar.floorInterval(endMs, interval);
608
+ // Pre-collect bucket start timestamps to size typed output arrays once.
609
+ const bucketStarts = [];
610
+ const bucketEnds = [];
611
+ for (let b = startBucket; b <= endBucket;) {
612
+ const nextB = this.calendar.nextInterval(b, interval);
613
+ bucketStarts.push(b);
614
+ bucketEnds.push(nextB);
615
+ b = nextB;
616
+ }
617
+ const numBuckets = bucketStarts.length;
618
+ const outTs = new Float64Array(numBuckets);
619
+ const outVal = new Float64Array(numBuckets);
620
+ let recIdx = 0;
621
+ let carriedVal = initialPrior;
622
+ let firstValidIdx = -1;
623
+ let lastValidIdx = -1;
624
+ for (let bi = 0; bi < numBuckets; ++bi) {
625
+ const bStart = bucketStarts[bi];
626
+ const bEnd = bucketEnds[bi];
627
+ let count = 0;
628
+ let sum = 0;
629
+ let min = Number.POSITIVE_INFINITY;
630
+ let max = Number.NEGATIVE_INFINITY;
631
+ let first = Number.NaN;
632
+ let finalVal = carriedVal;
633
+ let initial = carriedVal;
634
+ let hasActive = !Number.isNaN(carriedVal);
635
+ while (recIdx < length && timestamps[recIdx] < bEnd) {
636
+ const recTs = timestamps[recIdx];
637
+ const v = values[recIdx];
638
+ recIdx++;
639
+ if (Number.isNaN(v)) {
640
+ // Explicit interruption marker.
641
+ carriedVal = Number.NaN;
642
+ if (count === 0 && recTs === bStart) {
643
+ hasActive = false;
644
+ initial = Number.NaN;
645
+ finalVal = Number.NaN;
646
+ }
647
+ continue;
648
+ }
649
+ if (!hasActive) {
650
+ initial = v;
651
+ hasActive = true;
652
+ }
653
+ if (count === 0) {
654
+ sum = v;
655
+ min = v;
656
+ max = v;
657
+ first = v;
658
+ }
659
+ else {
660
+ sum += v;
661
+ if (v < min)
662
+ min = v;
663
+ if (v > max)
664
+ max = v;
665
+ }
666
+ count++;
667
+ finalVal = v;
668
+ carriedVal = v;
669
+ }
670
+ const v = extractRollupValue(rollup, hasActive, count, sum, min, max, initial, first, finalVal);
671
+ outTs[bi] = rollup === 'final' ? bEnd : bStart;
672
+ outVal[bi] = v;
673
+ if (hasActive || count > 0) {
674
+ if (firstValidIdx < 0)
675
+ firstValidIdx = bi;
676
+ lastValidIdx = bi;
677
+ }
678
+ }
679
+ if (firstValidIdx < 0) {
680
+ return { timestamps: new Float64Array(0), values: new Float64Array(0), length: 0 };
681
+ }
682
+ if (firstValidIdx === 0 && lastValidIdx === numBuckets - 1) {
683
+ return { timestamps: outTs, values: outVal, length: numBuckets };
684
+ }
685
+ const trimmedLen = lastValidIdx - firstValidIdx + 1;
686
+ return {
687
+ timestamps: outTs.slice(firstValidIdx, lastValidIdx + 1),
688
+ values: outVal.slice(firstValidIdx, lastValidIdx + 1),
689
+ length: trimmedLen,
690
+ };
691
+ }
692
+ async queryTierAsBuckets(state, startMs, endMs, targetInterval, rollup, clampFinalTo) {
693
+ const startBucket = this.calendar.floorInterval(startMs, targetInterval);
694
+ const endBucket = this.calendar.floorInterval(endMs, targetInterval);
695
+ const endNext = this.calendar.nextInterval(endBucket, targetInterval);
696
+ const fromSlotId = this.calendar.tierToSlotId(state.tier, startBucket);
697
+ const toSlotId = this.calendar.tierToSlotId(state.tier, endNext - 1);
698
+ const slotsRes = await this.readTierSlots(state, fromSlotId, toSlotId);
699
+ if (slotsRes.count === 0) {
700
+ return { timestamps: new Float64Array(0), values: new Float64Array(0), length: 0 };
701
+ }
702
+ const firstCoveredTs = this.calendar.tierSlotToUtcMs(state.tier, slotsRes.firstSlotId);
703
+ const lastCoveredTs = this.calendar.tierSlotToUtcMs(state.tier, slotsRes.firstSlotId + slotsRes.count - 1);
704
+ const clampedStartBucket = Math.max(startBucket, this.calendar.floorInterval(firstCoveredTs, targetInterval));
705
+ const clampedEndBucket = Math.min(endBucket, this.calendar.floorInterval(lastCoveredTs, targetInterval));
706
+ if (clampedEndBucket < clampedStartBucket) {
707
+ return { timestamps: new Float64Array(0), values: new Float64Array(0), length: 0 };
708
+ }
709
+ const bucketStarts = [];
710
+ const bucketEnds = [];
711
+ for (let b = clampedStartBucket; b <= clampedEndBucket;) {
712
+ const nextB = this.calendar.nextInterval(b, targetInterval);
713
+ bucketStarts.push(b);
714
+ bucketEnds.push(nextB);
715
+ b = nextB;
716
+ }
717
+ const numBuckets = bucketStarts.length;
718
+ const outTs = new Float64Array(numBuckets);
719
+ const outVal = new Float64Array(numBuckets);
720
+ const sData = slotsRes.data;
721
+ const sFirst = slotsRes.firstSlotId;
722
+ const sEnd = sFirst + slotsRes.count;
723
+ for (let bi = 0; bi < numBuckets; ++bi) {
724
+ const bStart = bucketStarts[bi];
725
+ const bEnd = bucketEnds[bi];
726
+ const slotFrom = Math.max(sFirst, this.calendar.tierToSlotId(state.tier, bStart));
727
+ const slotTo = Math.min(sEnd - 1, this.calendar.tierToSlotId(state.tier, bEnd - 1));
728
+ let hasActive = false;
729
+ let count = 0;
730
+ let sum = 0;
731
+ let min = Number.POSITIVE_INFINITY;
732
+ let max = Number.NEGATIVE_INFINITY;
733
+ let initial = Number.NaN;
734
+ let first = Number.NaN;
735
+ let finalVal = Number.NaN;
736
+ for (let sid = slotFrom; sid <= slotTo; ++sid) {
737
+ const base = (sid - sFirst) * ROLLUP_SLOT_FLOATS;
738
+ const sc = sData[base + SLOT_COUNT];
739
+ const sInit = sData[base + SLOT_INITIAL];
740
+ const sFinal = sData[base + SLOT_FINAL];
741
+ if (sc === 0 && Number.isNaN(sInit)) {
742
+ // Interruption slot.
743
+ continue;
744
+ }
745
+ if (!hasActive) {
746
+ initial = sInit;
747
+ hasActive = true;
748
+ }
749
+ finalVal = sFinal;
750
+ if (sc > 0) {
751
+ const sSum = sData[base + SLOT_SUM];
752
+ const sMin = sData[base + SLOT_MIN];
753
+ const sMax = sData[base + SLOT_MAX];
754
+ const sFirstVal = sData[base + SLOT_FIRST];
755
+ if (count === 0) {
756
+ sum = sSum;
757
+ min = sMin;
758
+ max = sMax;
759
+ first = sFirstVal;
760
+ }
761
+ else {
762
+ sum += sSum;
763
+ if (sMin < min)
764
+ min = sMin;
765
+ if (sMax > max)
766
+ max = sMax;
767
+ }
768
+ count += sc;
769
+ }
770
+ }
771
+ const rawTs = rollup === 'final' ? bEnd : bStart;
772
+ outTs[bi] = rollup === 'final' && clampFinalTo !== undefined && rawTs > clampFinalTo ? clampFinalTo : rawTs;
773
+ outVal[bi] = extractRollupValue(rollup, hasActive, count, sum, min, max, initial, first, finalVal);
774
+ }
775
+ return { timestamps: outTs, values: outVal, length: numBuckets };
776
+ }
777
+ async queryColumns(options) {
778
+ const startMs = toEpochMs(options.start);
779
+ const endMs = toEpochMs(options.end);
780
+ const timezone = this.calendar.timezone;
781
+ const rollup = options.rollup ?? 'avg';
782
+ const useMemoryCache = options.useMemoryCache !== false && this.memoryCache !== null;
783
+ if (endMs < startMs) {
784
+ return {
785
+ timestamps: new Float64Array(0),
786
+ values: new Float64Array(0),
787
+ length: 0,
788
+ interval: options.interval ?? null,
789
+ truncated: false,
790
+ timezone,
791
+ };
792
+ }
793
+ // 1. Raw query mode (`interval === null`).
794
+ if (options.interval === null) {
795
+ if (this.rawFile) {
796
+ const res = await this.readMergedRaw(startMs, endMs, options.limit);
797
+ return {
798
+ timestamps: res.timestamps,
799
+ values: res.values,
800
+ length: res.length,
801
+ interval: null,
802
+ truncated: res.truncated,
803
+ timezone,
804
+ };
805
+ }
806
+ // Raw disabled: serve from memoryCache (or fallback to finest dense tier + memoryCache hybrid).
807
+ const memOldest = useMemoryCache ? this.memoryCache.getOldestTs() : Number.NaN;
808
+ if (useMemoryCache && !Number.isNaN(memOldest) && memOldest <= startMs) {
809
+ const mem = this.memoryCache.copyRange(startMs, endMs);
810
+ const filtered = stripNaNMarkers(mem.timestamps, mem.values, mem.length, options.limit);
811
+ return {
812
+ timestamps: filtered.timestamps,
813
+ values: filtered.values,
814
+ length: filtered.length,
815
+ interval: null,
816
+ truncated: filtered.truncated,
817
+ timezone,
818
+ };
819
+ }
820
+ const finest = this.selectFallbackTier(startMs, endMs);
821
+ if (!finest) {
822
+ return {
823
+ timestamps: new Float64Array(0),
824
+ values: new Float64Array(0),
825
+ length: 0,
826
+ interval: null,
827
+ truncated: false,
828
+ timezone,
829
+ };
830
+ }
831
+ const fallbackParsed = parseInterval(finest.tier);
832
+ if (useMemoryCache && !Number.isNaN(memOldest) && memOldest <= endMs) {
833
+ const splitTs = memOldest;
834
+ const diskPart = splitTs > startMs
835
+ ? await this.queryTierAsBuckets(finest, startMs, splitTs - 1, fallbackParsed, rollup, splitTs)
836
+ : { timestamps: new Float64Array(0), values: new Float64Array(0), length: 0 };
837
+ const mem = this.memoryCache.copyRange(splitTs, endMs);
838
+ const memPart = stripNaNMarkers(mem.timestamps, mem.values, mem.length, undefined);
839
+ const combined = concatColumns(diskPart, memPart, options.limit);
840
+ return {
841
+ timestamps: combined.timestamps,
842
+ values: combined.values,
843
+ length: combined.length,
844
+ interval: null,
845
+ fallbackInterval: finest.tier,
846
+ hybridSplitTs: splitTs,
847
+ truncated: combined.truncated,
848
+ timezone,
849
+ };
850
+ }
851
+ const fallbackRes = await this.queryTierAsBuckets(finest, startMs, endMs, fallbackParsed, rollup);
852
+ const capped = applyLimitColumns(fallbackRes, options.limit);
853
+ return {
854
+ timestamps: capped.timestamps,
855
+ values: capped.values,
856
+ length: capped.length,
857
+ interval: null,
858
+ fallbackInterval: finest.tier,
859
+ truncated: capped.truncated,
860
+ timezone,
861
+ };
862
+ }
863
+ // 2. Rollup query mode (`interval === undefined` -> auto, or explicit interval).
864
+ const resolvedInterval = options.interval === undefined ? selectAutoInterval(startMs, endMs) : options.interval;
865
+ const parsedInterval = parseInterval(resolvedInterval);
866
+ const servingTier = this.selectServingTier(parsedInterval, startMs, endMs);
867
+ if (servingTier) {
868
+ const res = await this.queryTierAsBuckets(servingTier, startMs, endMs, parsedInterval, rollup);
869
+ return {
870
+ timestamps: res.timestamps,
871
+ values: res.values,
872
+ length: res.length,
873
+ interval: resolvedInterval,
874
+ truncated: false,
875
+ timezone,
876
+ };
877
+ }
878
+ // No dense tier divides targetInterval -> compute from raw if available.
879
+ if (this.rawFile) {
880
+ const rawData = await this.readMergedRaw(startMs, endMs, undefined, false);
881
+ let priorVal = Number.NaN;
882
+ if (this.tiers['1h']) {
883
+ const hourSlot = this.calendar.tierToSlotId('1h', startMs);
884
+ const hourStart = this.calendar.tierSlotToUtcMs('1h', hourSlot);
885
+ const beforeInHour = startMs > hourStart ? await this.readMergedRaw(hourStart, startMs - 1, undefined, false) : null;
886
+ if (beforeInHour && beforeInHour.length > 0) {
887
+ priorVal = beforeInHour.values[beforeInHour.length - 1];
888
+ }
889
+ else {
890
+ const prevHourRes = await this.readTierSlots(this.tiers['1h'], hourSlot - 1, hourSlot - 1);
891
+ if (prevHourRes.count > 0) {
892
+ priorVal = prevHourRes.data[SLOT_FINAL];
893
+ }
894
+ }
895
+ }
896
+ else {
897
+ const priorRec = await this.rawFile.readLastBefore(startMs, false);
898
+ if (priorRec)
899
+ priorVal = priorRec.value;
900
+ }
901
+ const res = this.aggregateRawIntoBuckets(rawData.timestamps, rawData.values, rawData.length, priorVal, startMs, endMs, parsedInterval, rollup);
902
+ return {
903
+ timestamps: res.timestamps,
904
+ values: res.values,
905
+ length: res.length,
906
+ interval: resolvedInterval,
907
+ truncated: false,
908
+ timezone,
909
+ };
910
+ }
911
+ // Rule #6: raw is disabled and no dense tier divides targetInterval -> fallback + optional memory hybrid.
912
+ const finest = this.selectFallbackTier(startMs, endMs);
913
+ if (!finest) {
914
+ return {
915
+ timestamps: new Float64Array(0),
916
+ values: new Float64Array(0),
917
+ length: 0,
918
+ interval: resolvedInterval,
919
+ truncated: false,
920
+ timezone,
921
+ };
922
+ }
923
+ const memOldest = useMemoryCache ? this.memoryCache.getOldestTs() : Number.NaN;
924
+ const memNewest = useMemoryCache ? this.memoryCache.getNewestTs() : Number.NaN;
925
+ if (useMemoryCache && !Number.isNaN(memOldest) && memNewest >= startMs && memOldest <= endMs) {
926
+ if (memOldest <= startMs) {
927
+ const mem = this.memoryCache.copyRange(startMs, endMs);
928
+ const res = this.aggregateRawIntoBuckets(mem.timestamps, mem.values, mem.length, mem.priorValue, startMs, endMs, parsedInterval, rollup);
929
+ return {
930
+ timestamps: res.timestamps,
931
+ values: res.values,
932
+ length: res.length,
933
+ interval: resolvedInterval,
934
+ truncated: false,
935
+ timezone,
936
+ };
937
+ }
938
+ const splitTs = this.calendar.ceilInterval(memOldest, parsedInterval);
939
+ if (splitTs <= endMs) {
940
+ const fallbackParsed = parseInterval(finest.tier);
941
+ const diskPart = splitTs > startMs
942
+ ? await this.queryTierAsBuckets(finest, startMs, splitTs - 1, fallbackParsed, rollup, splitTs)
943
+ : { timestamps: new Float64Array(0), values: new Float64Array(0), length: 0 };
944
+ const mem = this.memoryCache.copyRange(splitTs, endMs);
945
+ const memBuckets = this.aggregateRawIntoBuckets(mem.timestamps, mem.values, mem.length, mem.priorValue, splitTs, endMs, parsedInterval, rollup);
946
+ const combined = concatColumns(diskPart, memBuckets);
947
+ return {
948
+ timestamps: combined.timestamps,
949
+ values: combined.values,
950
+ length: combined.length,
951
+ interval: resolvedInterval,
952
+ fallbackInterval: finest.tier,
953
+ hybridSplitTs: splitTs,
954
+ truncated: false,
955
+ timezone,
956
+ };
957
+ }
958
+ }
959
+ const fallbackParsed = parseInterval(finest.tier);
960
+ const fallbackRes = await this.queryTierAsBuckets(finest, startMs, endMs, fallbackParsed, rollup);
961
+ return {
962
+ timestamps: fallbackRes.timestamps,
963
+ values: fallbackRes.values,
964
+ length: fallbackRes.length,
965
+ interval: resolvedInterval,
966
+ fallbackInterval: finest.tier,
967
+ truncated: false,
968
+ timezone,
969
+ };
970
+ }
971
+ async query(options) {
972
+ const cols = await this.queryColumns(options);
973
+ const points = new Array(cols.length);
974
+ for (let i = 0; i < cols.length; ++i) {
975
+ points[i] = { ts: cols.timestamps[i], value: cols.values[i] };
976
+ }
977
+ return {
978
+ points,
979
+ interval: cols.interval,
980
+ fallbackInterval: cols.fallbackInterval,
981
+ hybridSplitTs: cols.hybridSplitTs,
982
+ truncated: cols.truncated,
983
+ timezone: cols.timezone,
984
+ };
985
+ }
986
+ async close() {
987
+ await this.flush();
988
+ this.closed = true;
989
+ if (this.rawFile)
990
+ await this.rawFile.close();
991
+ for (let i = 0; i < this.activeTiers.length; ++i) {
992
+ await this.activeTiers[i].file.close();
993
+ }
994
+ }
995
+ }
996
+ export class ValueSeries {
997
+ meta;
998
+ store;
999
+ calendar;
1000
+ codec;
1001
+ file = null;
1002
+ pending = [];
1003
+ lastTs = Number.NaN;
1004
+ flushChain = Promise.resolve();
1005
+ closed = false;
1006
+ listeners = new Set();
1007
+ constructor(meta, store, calendar, codec) {
1008
+ this.meta = meta;
1009
+ this.store = store;
1010
+ this.calendar = calendar;
1011
+ this.codec = codec;
1012
+ }
1013
+ get hasDirtyData() {
1014
+ return this.pending.length > 0;
1015
+ }
1016
+ getByteSize() {
1017
+ return this.file?.byteSize ?? 0;
1018
+ }
1019
+ listChunks() {
1020
+ return this.file?.listChunks?.() ?? [];
1021
+ }
1022
+ dropChunks(chunkIds) {
1023
+ if (!this.file?.dropChunks || chunkIds.length === 0)
1024
+ return Promise.resolve();
1025
+ this.flushChain = this.flushChain.then(() => this.file.dropChunks(chunkIds));
1026
+ return this.flushChain;
1027
+ }
1028
+ async open() {
1029
+ this.file = await this.store.openValueRaw(this.meta);
1030
+ }
1031
+ subscribe(listener) {
1032
+ this.listeners.add(listener);
1033
+ return () => {
1034
+ this.listeners.delete(listener);
1035
+ };
1036
+ }
1037
+ write(tsMs, value) {
1038
+ if (this.closed)
1039
+ throw new Error(`Series "${this.meta.id}" is closed`);
1040
+ if (!Number.isNaN(this.lastTs) && tsMs < this.lastTs) {
1041
+ throw new Error(`Out-of-order timestamp for series "${this.meta.id}": ${tsMs} < ${this.lastTs}`);
1042
+ }
1043
+ this.lastTs = tsMs;
1044
+ this.pending.push({ ts: tsMs, value });
1045
+ for (const listener of this.listeners) {
1046
+ listener(tsMs, value);
1047
+ }
1048
+ }
1049
+ flush() {
1050
+ this.flushChain = this.flushChain.then(() => this.flushInternal());
1051
+ return this.flushChain;
1052
+ }
1053
+ async flushInternal() {
1054
+ if (this.pending.length === 0)
1055
+ return;
1056
+ const batch = this.pending;
1057
+ this.pending = [];
1058
+ const records = new Array(batch.length);
1059
+ for (let i = 0; i < batch.length; ++i) {
1060
+ const { ts, value } = batch[i];
1061
+ if (typeof value === 'string') {
1062
+ records[i] = { ts, isString: true, payload: value };
1063
+ }
1064
+ else if (value === undefined) {
1065
+ records[i] = { ts, isString: false, payload: null };
1066
+ }
1067
+ else {
1068
+ records[i] = { ts, isString: false, payload: this.codec.stringify(value) };
1069
+ }
1070
+ }
1071
+ await this.file.appendBatch(records);
1072
+ }
1073
+ decodeRecords(records) {
1074
+ const out = new Array(records.length);
1075
+ for (let i = 0; i < records.length; ++i) {
1076
+ const rec = records[i];
1077
+ let value;
1078
+ if (rec.isString) {
1079
+ value = rec.payload ?? '';
1080
+ }
1081
+ else if (rec.payload === null) {
1082
+ value = undefined;
1083
+ }
1084
+ else {
1085
+ value = this.codec.parse(rec.payload);
1086
+ }
1087
+ out[i] = { ts: rec.ts, value };
1088
+ }
1089
+ return out;
1090
+ }
1091
+ async query(options) {
1092
+ const startMs = toEpochMs(options.start);
1093
+ const endMs = toEpochMs(options.end);
1094
+ const order = options.order ?? 'asc';
1095
+ const timezone = this.calendar.timezone;
1096
+ if (endMs < startMs) {
1097
+ return { points: [], truncated: false, timezone };
1098
+ }
1099
+ const pendingMatches = [];
1100
+ for (let i = 0; i < this.pending.length; ++i) {
1101
+ const item = this.pending[i];
1102
+ if (item.ts >= startMs && item.ts <= endMs) {
1103
+ pendingMatches.push(item);
1104
+ }
1105
+ }
1106
+ if (order === 'desc') {
1107
+ pendingMatches.reverse();
1108
+ if (options.limit !== undefined && options.limit >= 0 && pendingMatches.length >= options.limit) {
1109
+ return {
1110
+ points: pendingMatches.slice(0, options.limit),
1111
+ truncated: pendingMatches.length > options.limit || this.file.recordCount > 0,
1112
+ timezone,
1113
+ };
1114
+ }
1115
+ const remainingLimit = options.limit !== undefined && options.limit >= 0 ? options.limit - pendingMatches.length : undefined;
1116
+ const diskRes = await this.file.readRange(startMs, endMs, remainingLimit, 'desc');
1117
+ return {
1118
+ points: pendingMatches.concat(this.decodeRecords(diskRes.records)),
1119
+ truncated: diskRes.truncated,
1120
+ timezone,
1121
+ };
1122
+ }
1123
+ const diskRes = await this.file.readRange(startMs, endMs, options.limit, 'asc');
1124
+ const diskPoints = this.decodeRecords(diskRes.records);
1125
+ if (diskRes.truncated || pendingMatches.length === 0) {
1126
+ return { points: diskPoints, truncated: diskRes.truncated, timezone };
1127
+ }
1128
+ const combined = diskPoints.concat(pendingMatches);
1129
+ let truncated = false;
1130
+ if (options.limit !== undefined && options.limit >= 0 && combined.length > options.limit) {
1131
+ combined.length = options.limit;
1132
+ truncated = true;
1133
+ }
1134
+ return { points: combined, truncated, timezone };
1135
+ }
1136
+ async close() {
1137
+ await this.flush();
1138
+ this.closed = true;
1139
+ if (this.file) {
1140
+ await this.file.close();
1141
+ }
1142
+ }
1143
+ }
1144
+ function lowerBoundInterleaved(pairs, count, tsMs) {
1145
+ let lo = 0;
1146
+ let hi = count;
1147
+ while (lo < hi) {
1148
+ const mid = (lo + hi) >>> 1;
1149
+ if (pairs[mid * 2] < tsMs)
1150
+ lo = mid + 1;
1151
+ else
1152
+ hi = mid;
1153
+ }
1154
+ return lo;
1155
+ }
1156
+ function upperBoundInterleaved(pairs, count, tsMs) {
1157
+ let lo = 0;
1158
+ let hi = count;
1159
+ while (lo < hi) {
1160
+ const mid = (lo + hi) >>> 1;
1161
+ if (pairs[mid * 2] <= tsMs)
1162
+ lo = mid + 1;
1163
+ else
1164
+ hi = mid;
1165
+ }
1166
+ return lo;
1167
+ }
1168
+ function stripNaNMarkers(timestamps, values, length, limit) {
1169
+ let valid = 0;
1170
+ for (let i = 0; i < length; ++i) {
1171
+ if (!Number.isNaN(values[i]))
1172
+ valid++;
1173
+ }
1174
+ let truncated = false;
1175
+ let outLen = valid;
1176
+ if (limit !== undefined && limit >= 0 && outLen > limit) {
1177
+ outLen = limit;
1178
+ truncated = true;
1179
+ }
1180
+ const outTs = new Float64Array(outLen);
1181
+ const outVal = new Float64Array(outLen);
1182
+ let pos = 0;
1183
+ for (let i = 0; i < length && pos < outLen; ++i) {
1184
+ if (!Number.isNaN(values[i])) {
1185
+ outTs[pos] = timestamps[i];
1186
+ outVal[pos] = values[i];
1187
+ pos++;
1188
+ }
1189
+ }
1190
+ return { timestamps: outTs, values: outVal, length: outLen, truncated };
1191
+ }
1192
+ function applyLimitColumns(cols, limit) {
1193
+ if (limit !== undefined && limit >= 0 && cols.length > limit) {
1194
+ return {
1195
+ timestamps: cols.timestamps.slice(0, limit),
1196
+ values: cols.values.slice(0, limit),
1197
+ length: limit,
1198
+ truncated: true,
1199
+ };
1200
+ }
1201
+ return { ...cols, truncated: false };
1202
+ }
1203
+ function concatColumns(a, b, limit) {
1204
+ let total = a.length + b.length;
1205
+ let truncated = false;
1206
+ if (limit !== undefined && limit >= 0 && total > limit) {
1207
+ total = limit;
1208
+ truncated = true;
1209
+ }
1210
+ const timestamps = new Float64Array(total);
1211
+ const values = new Float64Array(total);
1212
+ const takeA = Math.min(a.length, total);
1213
+ if (takeA > 0) {
1214
+ timestamps.set(a.timestamps.subarray(0, takeA), 0);
1215
+ values.set(a.values.subarray(0, takeA), 0);
1216
+ }
1217
+ const takeB = total - takeA;
1218
+ if (takeB > 0) {
1219
+ timestamps.set(b.timestamps.subarray(0, takeB), takeA);
1220
+ values.set(b.values.subarray(0, takeB), takeA);
1221
+ }
1222
+ return { timestamps, values, length: total, truncated };
1223
+ }