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/LICENSE +373 -0
- package/README.md +64 -2
- package/dist/backend.d.ts +41 -0
- package/dist/backend.js +207 -0
- package/dist/db.d.ts +56 -0
- package/dist/db.js +490 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +4 -0
- package/dist/memoryCache.d.ts +25 -0
- package/dist/memoryCache.js +89 -0
- package/dist/rawFile.d.ts +87 -0
- package/dist/rawFile.js +1031 -0
- package/dist/retention.d.ts +20 -0
- package/dist/retention.js +101 -0
- package/dist/rollupFile.d.ts +62 -0
- package/dist/rollupFile.js +527 -0
- package/dist/series.d.ts +74 -0
- package/dist/series.js +1223 -0
- package/dist/store.d.ts +80 -0
- package/dist/store.js +42 -0
- package/dist/time.d.ts +39 -0
- package/dist/time.js +459 -0
- package/dist/types.d.ts +162 -0
- package/dist/types.js +1 -0
- package/package.json +36 -4
package/dist/db.d.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { ServerCalendar } from './time.ts';
|
|
2
|
+
import type { NumericColumnResult, NumericQueryOptions, NumericQueryResult, SeriesConfig, SeriesMeta, StorageUsageStats, TimestampInput, TsdbOptions, ValueQueryOptions, ValueQueryResult } from './types.ts';
|
|
3
|
+
export declare class Tsdb {
|
|
4
|
+
readonly calendar: ServerCalendar;
|
|
5
|
+
private readonly store;
|
|
6
|
+
private readonly valueCodec;
|
|
7
|
+
private readonly options;
|
|
8
|
+
private readonly numericSeries;
|
|
9
|
+
private readonly valueSeries;
|
|
10
|
+
private readonly accountedNumeric;
|
|
11
|
+
private readonly accountedValue;
|
|
12
|
+
private readonly catalog;
|
|
13
|
+
private readonly trimTargetRatio;
|
|
14
|
+
private rawNumericBytes;
|
|
15
|
+
private rawValueBytes;
|
|
16
|
+
private readonly rollupTierBytes;
|
|
17
|
+
private nextRawNumericThreshold;
|
|
18
|
+
private nextRawValueThreshold;
|
|
19
|
+
private nextRollupThreshold;
|
|
20
|
+
private lastLimitCheckAtMs;
|
|
21
|
+
private enforceChain;
|
|
22
|
+
private flushTimer;
|
|
23
|
+
private closed;
|
|
24
|
+
private constructor();
|
|
25
|
+
static open(options: TsdbOptions): Promise<Tsdb>;
|
|
26
|
+
private loadSeriesInstance;
|
|
27
|
+
private syncNumericSeriesBytes;
|
|
28
|
+
private syncValueSeriesBytes;
|
|
29
|
+
private getTotalRollupBytes;
|
|
30
|
+
getStorageUsage(): StorageUsageStats;
|
|
31
|
+
createSeries(id: string, config: SeriesConfig): Promise<SeriesMeta>;
|
|
32
|
+
ensureSeries(id: string, config: SeriesConfig): Promise<SeriesMeta>;
|
|
33
|
+
hasSeries(id: string): boolean;
|
|
34
|
+
getSeriesMeta(id: string): SeriesMeta | undefined;
|
|
35
|
+
listSeries(): SeriesMeta[];
|
|
36
|
+
deleteSeries(id: string): Promise<void>;
|
|
37
|
+
write(id: string, ts: TimestampInput, value: unknown): void;
|
|
38
|
+
writeNumeric(id: string, ts: TimestampInput, value: number | boolean): void;
|
|
39
|
+
writeBatch(id: string, entries: ReadonlyArray<{
|
|
40
|
+
ts: TimestampInput;
|
|
41
|
+
value: unknown;
|
|
42
|
+
}>): void;
|
|
43
|
+
markInterruption(id: string, ts?: TimestampInput): void;
|
|
44
|
+
queryNumericColumns(id: string, options: NumericQueryOptions): Promise<NumericColumnResult>;
|
|
45
|
+
queryNumeric(id: string, options: NumericQueryOptions): Promise<NumericQueryResult>;
|
|
46
|
+
queryValues(id: string, options: ValueQueryOptions): Promise<ValueQueryResult>;
|
|
47
|
+
subscribe(id: string, listener: (ts: number, value: unknown) => void): () => void;
|
|
48
|
+
private flushDirtySeries;
|
|
49
|
+
private needsLimitCheck;
|
|
50
|
+
private maybeEnforceStorageLimits;
|
|
51
|
+
private scheduleEnforce;
|
|
52
|
+
private runEnforceStorageLimits;
|
|
53
|
+
enforceStorageLimits(force?: boolean): Promise<StorageUsageStats>;
|
|
54
|
+
flush(): Promise<void>;
|
|
55
|
+
close(): Promise<void>;
|
|
56
|
+
}
|
package/dist/db.js
ADDED
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
import { NodeFileBackend } from './backend.js';
|
|
2
|
+
import { computeTierTargets, planChunkEviction, resolveChunkSizes } from './retention.js';
|
|
3
|
+
import { normalizeSeriesConfig, NumericSeries, ValueSeries } from './series.js';
|
|
4
|
+
import { FileTsdbStore } from './store.js';
|
|
5
|
+
import { ServerCalendar, toEpochMs } from './time.js';
|
|
6
|
+
const ROLLUP_TIERS = ['15s', '5m', '1h', '1d'];
|
|
7
|
+
const defaultCodec = {
|
|
8
|
+
stringify: JSON.stringify,
|
|
9
|
+
parse: JSON.parse,
|
|
10
|
+
};
|
|
11
|
+
function makeDirKey(seq, id) {
|
|
12
|
+
const safe = id.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 32) || 's';
|
|
13
|
+
return `${seq}_${safe}`;
|
|
14
|
+
}
|
|
15
|
+
export class Tsdb {
|
|
16
|
+
calendar;
|
|
17
|
+
store;
|
|
18
|
+
valueCodec;
|
|
19
|
+
options;
|
|
20
|
+
numericSeries = new Map();
|
|
21
|
+
valueSeries = new Map();
|
|
22
|
+
accountedNumeric = new Map();
|
|
23
|
+
accountedValue = new Map();
|
|
24
|
+
catalog;
|
|
25
|
+
trimTargetRatio;
|
|
26
|
+
rawNumericBytes = 0;
|
|
27
|
+
rawValueBytes = 0;
|
|
28
|
+
rollupTierBytes = {
|
|
29
|
+
'15s': 0,
|
|
30
|
+
'5m': 0,
|
|
31
|
+
'1h': 0,
|
|
32
|
+
'1d': 0,
|
|
33
|
+
};
|
|
34
|
+
nextRawNumericThreshold;
|
|
35
|
+
nextRawValueThreshold;
|
|
36
|
+
nextRollupThreshold;
|
|
37
|
+
lastLimitCheckAtMs = 0;
|
|
38
|
+
enforceChain = Promise.resolve({
|
|
39
|
+
rawNumericBytes: 0,
|
|
40
|
+
rawValueBytes: 0,
|
|
41
|
+
rollupBytes: 0,
|
|
42
|
+
rollupTierBytes: { '15s': 0, '5m': 0, '1h': 0, '1d': 0 },
|
|
43
|
+
});
|
|
44
|
+
flushTimer = null;
|
|
45
|
+
closed = false;
|
|
46
|
+
constructor(store, options, catalog, trimTargetRatio) {
|
|
47
|
+
this.store = store;
|
|
48
|
+
this.valueCodec = options.valueCodec ?? defaultCodec;
|
|
49
|
+
this.options = options;
|
|
50
|
+
this.catalog = catalog;
|
|
51
|
+
this.calendar = new ServerCalendar(catalog.timezone, catalog.weekStartsOn);
|
|
52
|
+
this.trimTargetRatio = trimTargetRatio;
|
|
53
|
+
this.nextRawNumericThreshold = options.storageLimits?.rawNumericMaxBytes ?? Number.POSITIVE_INFINITY;
|
|
54
|
+
this.nextRawValueThreshold = options.storageLimits?.rawValueMaxBytes ?? Number.POSITIVE_INFINITY;
|
|
55
|
+
this.nextRollupThreshold = options.storageLimits?.rollupMaxBytes ?? Number.POSITIVE_INFINITY;
|
|
56
|
+
}
|
|
57
|
+
static async open(options) {
|
|
58
|
+
const trimTargetRatio = options.storageLimits?.trimTargetRatio ?? 0.7;
|
|
59
|
+
if (!(trimTargetRatio > 0 && trimTargetRatio < 1)) {
|
|
60
|
+
throw new Error(`Invalid storageLimits.trimTargetRatio: ${trimTargetRatio} (must be between 0 and 1 exclusive)`);
|
|
61
|
+
}
|
|
62
|
+
const resolvedChunkSize = resolveChunkSizes(options.chunkSize, options.storageLimits);
|
|
63
|
+
const store = options.store ??
|
|
64
|
+
(options.backend
|
|
65
|
+
? new FileTsdbStore(options.backend, resolvedChunkSize)
|
|
66
|
+
: options.dir
|
|
67
|
+
? new FileTsdbStore(new NodeFileBackend(options.dir), resolvedChunkSize)
|
|
68
|
+
: null);
|
|
69
|
+
if (!store) {
|
|
70
|
+
throw new Error('Tsdb.open requires `dir`, `backend`, or `store`');
|
|
71
|
+
}
|
|
72
|
+
await store.open();
|
|
73
|
+
let catalog = await store.readCatalog();
|
|
74
|
+
if (!catalog) {
|
|
75
|
+
const cal = new ServerCalendar(options.timezone, options.weekStartsOn ?? 1);
|
|
76
|
+
catalog = {
|
|
77
|
+
version: 1,
|
|
78
|
+
timezone: cal.timezone,
|
|
79
|
+
weekStartsOn: cal.weekStartsOn,
|
|
80
|
+
nextSeq: 1,
|
|
81
|
+
series: {},
|
|
82
|
+
};
|
|
83
|
+
await store.writeCatalog(catalog);
|
|
84
|
+
}
|
|
85
|
+
const db = new Tsdb(store, options, catalog, trimTargetRatio);
|
|
86
|
+
for (const meta of Object.values(catalog.series)) {
|
|
87
|
+
await db.loadSeriesInstance(meta);
|
|
88
|
+
}
|
|
89
|
+
const intervalMs = options.flushIntervalMs ?? 1000;
|
|
90
|
+
if (intervalMs > 0) {
|
|
91
|
+
db.flushTimer = setInterval(() => {
|
|
92
|
+
void db.flush();
|
|
93
|
+
}, intervalMs);
|
|
94
|
+
db.flushTimer.unref?.();
|
|
95
|
+
}
|
|
96
|
+
return db;
|
|
97
|
+
}
|
|
98
|
+
async loadSeriesInstance(meta) {
|
|
99
|
+
if (meta.config.kind === 'value') {
|
|
100
|
+
const s = new ValueSeries(meta, this.store, this.calendar, this.valueCodec);
|
|
101
|
+
await s.open();
|
|
102
|
+
this.valueSeries.set(meta.id, s);
|
|
103
|
+
this.syncValueSeriesBytes(s);
|
|
104
|
+
return s;
|
|
105
|
+
}
|
|
106
|
+
const s = new NumericSeries(meta, this.store, this.calendar);
|
|
107
|
+
await s.open();
|
|
108
|
+
this.numericSeries.set(meta.id, s);
|
|
109
|
+
this.syncNumericSeriesBytes(s);
|
|
110
|
+
return s;
|
|
111
|
+
}
|
|
112
|
+
syncNumericSeriesBytes(num) {
|
|
113
|
+
let prev = this.accountedNumeric.get(num.meta.id);
|
|
114
|
+
if (!prev) {
|
|
115
|
+
prev = { 'raw': 0, '15s': 0, '5m': 0, '1h': 0, '1d': 0 };
|
|
116
|
+
this.accountedNumeric.set(num.meta.id, prev);
|
|
117
|
+
}
|
|
118
|
+
const curRaw = num.getRawByteSize();
|
|
119
|
+
if (curRaw !== prev.raw) {
|
|
120
|
+
this.rawNumericBytes += curRaw - prev.raw;
|
|
121
|
+
prev.raw = curRaw;
|
|
122
|
+
}
|
|
123
|
+
for (let i = 0; i < ROLLUP_TIERS.length; ++i) {
|
|
124
|
+
const tier = ROLLUP_TIERS[i];
|
|
125
|
+
const curTier = num.getRollupByteSize(tier);
|
|
126
|
+
if (curTier !== prev[tier]) {
|
|
127
|
+
this.rollupTierBytes[tier] += curTier - prev[tier];
|
|
128
|
+
prev[tier] = curTier;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
syncValueSeriesBytes(val) {
|
|
133
|
+
const prev = this.accountedValue.get(val.meta.id) ?? 0;
|
|
134
|
+
const cur = val.getByteSize();
|
|
135
|
+
if (cur !== prev) {
|
|
136
|
+
this.rawValueBytes += cur - prev;
|
|
137
|
+
this.accountedValue.set(val.meta.id, cur);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
getTotalRollupBytes() {
|
|
141
|
+
return (this.rollupTierBytes['15s'] + this.rollupTierBytes['5m'] + this.rollupTierBytes['1h'] + this.rollupTierBytes['1d']);
|
|
142
|
+
}
|
|
143
|
+
getStorageUsage() {
|
|
144
|
+
const rollupTierBytes = {
|
|
145
|
+
'15s': this.rollupTierBytes['15s'],
|
|
146
|
+
'5m': this.rollupTierBytes['5m'],
|
|
147
|
+
'1h': this.rollupTierBytes['1h'],
|
|
148
|
+
'1d': this.rollupTierBytes['1d'],
|
|
149
|
+
};
|
|
150
|
+
return {
|
|
151
|
+
rawNumericBytes: this.rawNumericBytes,
|
|
152
|
+
rawValueBytes: this.rawValueBytes,
|
|
153
|
+
rollupBytes: rollupTierBytes['15s'] + rollupTierBytes['5m'] + rollupTierBytes['1h'] + rollupTierBytes['1d'],
|
|
154
|
+
rollupTierBytes,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
async createSeries(id, config) {
|
|
158
|
+
if (this.closed)
|
|
159
|
+
throw new Error('Tsdb is closed');
|
|
160
|
+
const existing = this.catalog.series[id];
|
|
161
|
+
if (existing) {
|
|
162
|
+
if (existing.config.kind !== config.kind) {
|
|
163
|
+
throw new Error(`Series "${id}" already exists with kind "${existing.config.kind}"`);
|
|
164
|
+
}
|
|
165
|
+
return existing;
|
|
166
|
+
}
|
|
167
|
+
const normalized = normalizeSeriesConfig(config, this.options.defaultSeriesConfig);
|
|
168
|
+
const meta = {
|
|
169
|
+
id,
|
|
170
|
+
dirKey: makeDirKey(this.catalog.nextSeq++, id),
|
|
171
|
+
config: normalized,
|
|
172
|
+
};
|
|
173
|
+
this.catalog.series[id] = meta;
|
|
174
|
+
await this.loadSeriesInstance(meta);
|
|
175
|
+
await this.store.writeCatalog(this.catalog);
|
|
176
|
+
return meta;
|
|
177
|
+
}
|
|
178
|
+
ensureSeries(id, config) {
|
|
179
|
+
const existing = this.catalog.series[id];
|
|
180
|
+
if (existing) {
|
|
181
|
+
if (existing.config.kind !== config.kind) {
|
|
182
|
+
return Promise.reject(new Error(`Series "${id}" already exists with kind "${existing.config.kind}"`));
|
|
183
|
+
}
|
|
184
|
+
return Promise.resolve(existing);
|
|
185
|
+
}
|
|
186
|
+
return this.createSeries(id, config);
|
|
187
|
+
}
|
|
188
|
+
hasSeries(id) {
|
|
189
|
+
return Object.hasOwn(this.catalog.series, id);
|
|
190
|
+
}
|
|
191
|
+
getSeriesMeta(id) {
|
|
192
|
+
return this.catalog.series[id];
|
|
193
|
+
}
|
|
194
|
+
listSeries() {
|
|
195
|
+
return Object.values(this.catalog.series);
|
|
196
|
+
}
|
|
197
|
+
async deleteSeries(id) {
|
|
198
|
+
const meta = this.catalog.series[id];
|
|
199
|
+
if (!meta)
|
|
200
|
+
return;
|
|
201
|
+
const num = this.numericSeries.get(id);
|
|
202
|
+
if (num) {
|
|
203
|
+
await num.close();
|
|
204
|
+
const prev = this.accountedNumeric.get(id);
|
|
205
|
+
if (prev) {
|
|
206
|
+
this.rawNumericBytes -= prev.raw;
|
|
207
|
+
for (let i = 0; i < ROLLUP_TIERS.length; ++i) {
|
|
208
|
+
const tier = ROLLUP_TIERS[i];
|
|
209
|
+
this.rollupTierBytes[tier] -= prev[tier];
|
|
210
|
+
}
|
|
211
|
+
this.accountedNumeric.delete(id);
|
|
212
|
+
}
|
|
213
|
+
this.numericSeries.delete(id);
|
|
214
|
+
}
|
|
215
|
+
const val = this.valueSeries.get(id);
|
|
216
|
+
if (val) {
|
|
217
|
+
await val.close();
|
|
218
|
+
const prev = this.accountedValue.get(id) ?? 0;
|
|
219
|
+
this.rawValueBytes -= prev;
|
|
220
|
+
this.accountedValue.delete(id);
|
|
221
|
+
this.valueSeries.delete(id);
|
|
222
|
+
}
|
|
223
|
+
delete this.catalog.series[id];
|
|
224
|
+
await this.store.writeCatalog(this.catalog);
|
|
225
|
+
await this.store.deleteSeriesData(meta);
|
|
226
|
+
}
|
|
227
|
+
write(id, ts, value) {
|
|
228
|
+
const tsMs = toEpochMs(ts);
|
|
229
|
+
const num = this.numericSeries.get(id);
|
|
230
|
+
if (num) {
|
|
231
|
+
if (typeof value !== 'number' && typeof value !== 'boolean') {
|
|
232
|
+
throw new Error(`Numeric series "${id}" requires number or boolean value`);
|
|
233
|
+
}
|
|
234
|
+
num.write(tsMs, value);
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
const val = this.valueSeries.get(id);
|
|
238
|
+
if (val) {
|
|
239
|
+
val.write(tsMs, value);
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
throw new Error(`Unknown series: ${id}`);
|
|
243
|
+
}
|
|
244
|
+
writeNumeric(id, ts, value) {
|
|
245
|
+
const num = this.numericSeries.get(id);
|
|
246
|
+
if (!num) {
|
|
247
|
+
throw new Error(`Unknown numeric series: ${id}`);
|
|
248
|
+
}
|
|
249
|
+
num.write(toEpochMs(ts), value);
|
|
250
|
+
}
|
|
251
|
+
writeBatch(id, entries) {
|
|
252
|
+
const num = this.numericSeries.get(id);
|
|
253
|
+
if (num) {
|
|
254
|
+
for (let i = 0; i < entries.length; ++i) {
|
|
255
|
+
const { ts, value } = entries[i];
|
|
256
|
+
num.write(toEpochMs(ts), value);
|
|
257
|
+
}
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
const val = this.valueSeries.get(id);
|
|
261
|
+
if (val) {
|
|
262
|
+
for (let i = 0; i < entries.length; ++i) {
|
|
263
|
+
const { ts, value } = entries[i];
|
|
264
|
+
val.write(toEpochMs(ts), value);
|
|
265
|
+
}
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
throw new Error(`Unknown series: ${id}`);
|
|
269
|
+
}
|
|
270
|
+
markInterruption(id, ts) {
|
|
271
|
+
const num = this.numericSeries.get(id);
|
|
272
|
+
if (!num) {
|
|
273
|
+
throw new Error(`Unknown numeric series: ${id}`);
|
|
274
|
+
}
|
|
275
|
+
num.markInterruption(ts !== undefined ? toEpochMs(ts) : undefined);
|
|
276
|
+
}
|
|
277
|
+
queryNumericColumns(id, options) {
|
|
278
|
+
const num = this.numericSeries.get(id);
|
|
279
|
+
if (!num) {
|
|
280
|
+
return Promise.reject(new Error(`Unknown numeric series: ${id}`));
|
|
281
|
+
}
|
|
282
|
+
return num.queryColumns(options);
|
|
283
|
+
}
|
|
284
|
+
queryNumeric(id, options) {
|
|
285
|
+
const num = this.numericSeries.get(id);
|
|
286
|
+
if (!num) {
|
|
287
|
+
return Promise.reject(new Error(`Unknown numeric series: ${id}`));
|
|
288
|
+
}
|
|
289
|
+
return num.query(options);
|
|
290
|
+
}
|
|
291
|
+
queryValues(id, options) {
|
|
292
|
+
const val = this.valueSeries.get(id);
|
|
293
|
+
if (!val) {
|
|
294
|
+
return Promise.reject(new Error(`Unknown value series: ${id}`));
|
|
295
|
+
}
|
|
296
|
+
return val.query(options);
|
|
297
|
+
}
|
|
298
|
+
subscribe(id, listener) {
|
|
299
|
+
const num = this.numericSeries.get(id);
|
|
300
|
+
if (num)
|
|
301
|
+
return num.subscribe(listener);
|
|
302
|
+
const val = this.valueSeries.get(id);
|
|
303
|
+
if (val)
|
|
304
|
+
return val.subscribe(listener);
|
|
305
|
+
throw new Error(`Unknown series: ${id}`);
|
|
306
|
+
}
|
|
307
|
+
async flushDirtySeries() {
|
|
308
|
+
const tasks = [];
|
|
309
|
+
for (const num of this.numericSeries.values()) {
|
|
310
|
+
if (num.hasDirtyData) {
|
|
311
|
+
tasks.push(num.flush().then(() => {
|
|
312
|
+
this.syncNumericSeriesBytes(num);
|
|
313
|
+
}));
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
for (const val of this.valueSeries.values()) {
|
|
317
|
+
if (val.hasDirtyData) {
|
|
318
|
+
tasks.push(val.flush().then(() => {
|
|
319
|
+
this.syncValueSeriesBytes(val);
|
|
320
|
+
}));
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
if (tasks.length > 0) {
|
|
324
|
+
await Promise.all(tasks);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
needsLimitCheck() {
|
|
328
|
+
const limits = this.options.storageLimits;
|
|
329
|
+
if (!limits)
|
|
330
|
+
return false;
|
|
331
|
+
return ((limits.rawNumericMaxBytes !== undefined && this.rawNumericBytes > this.nextRawNumericThreshold) ||
|
|
332
|
+
(limits.rawValueMaxBytes !== undefined && this.rawValueBytes > this.nextRawValueThreshold) ||
|
|
333
|
+
(limits.rollupMaxBytes !== undefined && this.getTotalRollupBytes() > this.nextRollupThreshold));
|
|
334
|
+
}
|
|
335
|
+
async maybeEnforceStorageLimits() {
|
|
336
|
+
if (!this.needsLimitCheck())
|
|
337
|
+
return;
|
|
338
|
+
const checkInterval = this.options.storageLimits?.checkIntervalMs ?? 0;
|
|
339
|
+
if (checkInterval > 0 && Date.now() - this.lastLimitCheckAtMs < checkInterval) {
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
await this.scheduleEnforce(false);
|
|
343
|
+
}
|
|
344
|
+
scheduleEnforce(force) {
|
|
345
|
+
this.enforceChain = this.enforceChain.then(() => this.runEnforceStorageLimits(force));
|
|
346
|
+
return this.enforceChain;
|
|
347
|
+
}
|
|
348
|
+
async runEnforceStorageLimits(force) {
|
|
349
|
+
const limits = this.options.storageLimits;
|
|
350
|
+
if (!limits)
|
|
351
|
+
return this.getStorageUsage();
|
|
352
|
+
this.lastLimitCheckAtMs = Date.now();
|
|
353
|
+
if (limits.rawNumericMaxBytes !== undefined &&
|
|
354
|
+
this.rawNumericBytes > (force ? limits.rawNumericMaxBytes : this.nextRawNumericThreshold)) {
|
|
355
|
+
const target = Math.floor(limits.rawNumericMaxBytes * this.trimTargetRatio);
|
|
356
|
+
const candidates = [];
|
|
357
|
+
for (const num of this.numericSeries.values()) {
|
|
358
|
+
const chunks = num.listRawChunks();
|
|
359
|
+
for (let i = 0; i < chunks.length; ++i) {
|
|
360
|
+
const c = chunks[i];
|
|
361
|
+
candidates.push({
|
|
362
|
+
owner: num,
|
|
363
|
+
id: c.id,
|
|
364
|
+
minKey: c.minKey,
|
|
365
|
+
maxKey: c.maxKey,
|
|
366
|
+
byteSize: c.byteSize,
|
|
367
|
+
isLastChunkOfOwner: i === chunks.length - 1,
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
const drops = planChunkEviction(candidates, this.rawNumericBytes, target);
|
|
372
|
+
if (drops.size > 0) {
|
|
373
|
+
const tasks = [];
|
|
374
|
+
for (const [num, ids] of drops) {
|
|
375
|
+
tasks.push(num.dropRawChunks(ids).then(() => {
|
|
376
|
+
this.syncNumericSeriesBytes(num);
|
|
377
|
+
}));
|
|
378
|
+
}
|
|
379
|
+
await Promise.all(tasks);
|
|
380
|
+
}
|
|
381
|
+
this.nextRawNumericThreshold =
|
|
382
|
+
this.rawNumericBytes > limits.rawNumericMaxBytes
|
|
383
|
+
? this.rawNumericBytes + Math.max(4096, Math.floor(limits.rawNumericMaxBytes * 0.1))
|
|
384
|
+
: limits.rawNumericMaxBytes;
|
|
385
|
+
}
|
|
386
|
+
if (limits.rawValueMaxBytes !== undefined &&
|
|
387
|
+
this.rawValueBytes > (force ? limits.rawValueMaxBytes : this.nextRawValueThreshold)) {
|
|
388
|
+
const target = Math.floor(limits.rawValueMaxBytes * this.trimTargetRatio);
|
|
389
|
+
const candidates = [];
|
|
390
|
+
for (const val of this.valueSeries.values()) {
|
|
391
|
+
const chunks = val.listChunks();
|
|
392
|
+
for (let i = 0; i < chunks.length; ++i) {
|
|
393
|
+
const c = chunks[i];
|
|
394
|
+
candidates.push({
|
|
395
|
+
owner: val,
|
|
396
|
+
id: c.id,
|
|
397
|
+
minKey: c.minKey,
|
|
398
|
+
maxKey: c.maxKey,
|
|
399
|
+
byteSize: c.byteSize,
|
|
400
|
+
isLastChunkOfOwner: i === chunks.length - 1,
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
const drops = planChunkEviction(candidates, this.rawValueBytes, target);
|
|
405
|
+
if (drops.size > 0) {
|
|
406
|
+
const tasks = [];
|
|
407
|
+
for (const [val, ids] of drops) {
|
|
408
|
+
tasks.push(val.dropChunks(ids).then(() => {
|
|
409
|
+
this.syncValueSeriesBytes(val);
|
|
410
|
+
}));
|
|
411
|
+
}
|
|
412
|
+
await Promise.all(tasks);
|
|
413
|
+
}
|
|
414
|
+
this.nextRawValueThreshold =
|
|
415
|
+
this.rawValueBytes > limits.rawValueMaxBytes
|
|
416
|
+
? this.rawValueBytes + Math.max(4096, Math.floor(limits.rawValueMaxBytes * 0.1))
|
|
417
|
+
: limits.rawValueMaxBytes;
|
|
418
|
+
}
|
|
419
|
+
if (limits.rollupMaxBytes !== undefined &&
|
|
420
|
+
this.getTotalRollupBytes() > (force ? limits.rollupMaxBytes : this.nextRollupThreshold)) {
|
|
421
|
+
const targetTotal = Math.floor(limits.rollupMaxBytes * this.trimTargetRatio);
|
|
422
|
+
const tierTargets = computeTierTargets(this.rollupTierBytes, targetTotal);
|
|
423
|
+
for (let ti = 0; ti < ROLLUP_TIERS.length; ++ti) {
|
|
424
|
+
const tier = ROLLUP_TIERS[ti];
|
|
425
|
+
const curTierBytes = this.rollupTierBytes[tier];
|
|
426
|
+
if (curTierBytes <= tierTargets[tier])
|
|
427
|
+
continue;
|
|
428
|
+
const candidates = [];
|
|
429
|
+
for (const num of this.numericSeries.values()) {
|
|
430
|
+
const chunks = num.listRollupChunks(tier);
|
|
431
|
+
for (let i = 0; i < chunks.length; ++i) {
|
|
432
|
+
const c = chunks[i];
|
|
433
|
+
candidates.push({
|
|
434
|
+
owner: num,
|
|
435
|
+
id: c.id,
|
|
436
|
+
minKey: c.minKey,
|
|
437
|
+
maxKey: c.maxKey,
|
|
438
|
+
byteSize: c.byteSize,
|
|
439
|
+
isLastChunkOfOwner: i === chunks.length - 1,
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
const drops = planChunkEviction(candidates, curTierBytes, tierTargets[tier]);
|
|
444
|
+
if (drops.size > 0) {
|
|
445
|
+
const tasks = [];
|
|
446
|
+
for (const [num, ids] of drops) {
|
|
447
|
+
tasks.push(num.dropRollupChunks(tier, ids).then(() => {
|
|
448
|
+
this.syncNumericSeriesBytes(num);
|
|
449
|
+
}));
|
|
450
|
+
}
|
|
451
|
+
await Promise.all(tasks);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
const afterTotal = this.getTotalRollupBytes();
|
|
455
|
+
this.nextRollupThreshold =
|
|
456
|
+
afterTotal > limits.rollupMaxBytes
|
|
457
|
+
? afterTotal + Math.max(4096, Math.floor(limits.rollupMaxBytes * 0.1))
|
|
458
|
+
: limits.rollupMaxBytes;
|
|
459
|
+
}
|
|
460
|
+
return this.getStorageUsage();
|
|
461
|
+
}
|
|
462
|
+
async enforceStorageLimits(force = true) {
|
|
463
|
+
await this.flushDirtySeries();
|
|
464
|
+
return this.scheduleEnforce(force);
|
|
465
|
+
}
|
|
466
|
+
async flush() {
|
|
467
|
+
await this.flushDirtySeries();
|
|
468
|
+
await this.maybeEnforceStorageLimits();
|
|
469
|
+
}
|
|
470
|
+
async close() {
|
|
471
|
+
if (this.closed)
|
|
472
|
+
return;
|
|
473
|
+
if (this.flushTimer) {
|
|
474
|
+
clearInterval(this.flushTimer);
|
|
475
|
+
this.flushTimer = null;
|
|
476
|
+
}
|
|
477
|
+
if (this.options.storageLimits) {
|
|
478
|
+
await this.flush();
|
|
479
|
+
await this.enforceChain;
|
|
480
|
+
}
|
|
481
|
+
const closes = [];
|
|
482
|
+
for (const num of this.numericSeries.values())
|
|
483
|
+
closes.push(num.close());
|
|
484
|
+
for (const val of this.valueSeries.values())
|
|
485
|
+
closes.push(val.close());
|
|
486
|
+
await Promise.all(closes);
|
|
487
|
+
await this.store.close?.();
|
|
488
|
+
this.closed = true;
|
|
489
|
+
}
|
|
490
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { Tsdb } from './db.ts';
|
|
2
|
+
export { MemoryBackend, NodeFileBackend } from './backend.ts';
|
|
3
|
+
export type { StorageBackend, StorageHandle } from './backend.ts';
|
|
4
|
+
export { FileTsdbStore } from './store.ts';
|
|
5
|
+
export type { NumericRawStore, RollupTierStore, TsdbStore, ValueRawStore } from './store.ts';
|
|
6
|
+
export { canTierServeInterval, parseInterval, selectAutoInterval, ServerCalendar, STANDARD_INTERVALS, TIER_STEP_MS, toEpochMs, } from './time.ts';
|
|
7
|
+
export type { ParsedInterval } from './time.ts';
|
|
8
|
+
export type { ChunkSizeOptions, EncodedValueRecord, IntervalString, IntervalUnit, MemoryCacheConfig, NormalizedMemoryCacheConfig, NormalizedRawConfig, NormalizedSeriesConfig, NormalizedTierConfig, NumericColumnResult, NumericPoint, NumericQueryOptions, NumericQueryResult, RawOption, RollupTier, RollupType, SeriesConfig, SeriesKind, SeriesMeta, StandardInterval, StorageChunkInfo, StorageLimitOptions, StorageUsageStats, TierOption, TimestampInput, TsdbOptions, ValueCodec, ValuePoint, ValueQueryOptions, ValueQueryResult, } from './types.ts';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { Tsdb } from './db.js';
|
|
2
|
+
export { MemoryBackend, NodeFileBackend } from './backend.js';
|
|
3
|
+
export { FileTsdbStore } from './store.js';
|
|
4
|
+
export { canTierServeInterval, parseInterval, selectAutoInterval, ServerCalendar, STANDARD_INTERVALS, TIER_STEP_MS, toEpochMs, } from './time.js';
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export declare class MemoryRingCache {
|
|
2
|
+
readonly capacity: number;
|
|
3
|
+
readonly maxAgeMs: number | undefined;
|
|
4
|
+
private readonly ts;
|
|
5
|
+
private readonly val;
|
|
6
|
+
private head;
|
|
7
|
+
private count;
|
|
8
|
+
constructor(capacity: number, maxAgeMs?: number);
|
|
9
|
+
get size(): number;
|
|
10
|
+
push(tsMs: number, value: number): void;
|
|
11
|
+
markGap(tsMs: number): void;
|
|
12
|
+
private pruneBefore;
|
|
13
|
+
getOldestTs(): number;
|
|
14
|
+
getNewestTs(): number;
|
|
15
|
+
/**
|
|
16
|
+
* Copy samples within [startMs, endMs] and optionally the latest sample strictly before startMs.
|
|
17
|
+
* NaN markers represent explicit data interruptions.
|
|
18
|
+
*/
|
|
19
|
+
copyRange(startMs: number, endMs: number): {
|
|
20
|
+
timestamps: Float64Array;
|
|
21
|
+
values: Float64Array;
|
|
22
|
+
length: number;
|
|
23
|
+
priorValue: number;
|
|
24
|
+
};
|
|
25
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
export class MemoryRingCache {
|
|
2
|
+
capacity;
|
|
3
|
+
maxAgeMs;
|
|
4
|
+
ts;
|
|
5
|
+
val;
|
|
6
|
+
head = 0;
|
|
7
|
+
count = 0;
|
|
8
|
+
constructor(capacity, maxAgeMs) {
|
|
9
|
+
this.capacity = Math.max(1, capacity);
|
|
10
|
+
this.maxAgeMs = maxAgeMs;
|
|
11
|
+
this.ts = new Float64Array(this.capacity);
|
|
12
|
+
this.val = new Float64Array(this.capacity);
|
|
13
|
+
}
|
|
14
|
+
get size() {
|
|
15
|
+
return this.count;
|
|
16
|
+
}
|
|
17
|
+
push(tsMs, value) {
|
|
18
|
+
const writeIdx = (this.head + this.count) % this.capacity;
|
|
19
|
+
if (this.count === this.capacity) {
|
|
20
|
+
this.head = (this.head + 1) % this.capacity;
|
|
21
|
+
}
|
|
22
|
+
else {
|
|
23
|
+
this.count++;
|
|
24
|
+
}
|
|
25
|
+
this.ts[writeIdx] = tsMs;
|
|
26
|
+
this.val[writeIdx] = value;
|
|
27
|
+
if (this.maxAgeMs !== undefined) {
|
|
28
|
+
this.pruneBefore(tsMs - this.maxAgeMs);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
markGap(tsMs) {
|
|
32
|
+
this.push(tsMs, Number.NaN);
|
|
33
|
+
}
|
|
34
|
+
pruneBefore(minTs) {
|
|
35
|
+
while (this.count > 0 && this.ts[this.head] < minTs) {
|
|
36
|
+
this.head = (this.head + 1) % this.capacity;
|
|
37
|
+
this.count--;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
getOldestTs() {
|
|
41
|
+
if (this.count === 0)
|
|
42
|
+
return Number.NaN;
|
|
43
|
+
return this.ts[this.head];
|
|
44
|
+
}
|
|
45
|
+
getNewestTs() {
|
|
46
|
+
if (this.count === 0)
|
|
47
|
+
return Number.NaN;
|
|
48
|
+
return this.ts[(this.head + this.count - 1) % this.capacity];
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Copy samples within [startMs, endMs] and optionally the latest sample strictly before startMs.
|
|
52
|
+
* NaN markers represent explicit data interruptions.
|
|
53
|
+
*/
|
|
54
|
+
copyRange(startMs, endMs) {
|
|
55
|
+
if (this.count === 0) {
|
|
56
|
+
return { timestamps: new Float64Array(0), values: new Float64Array(0), length: 0, priorValue: Number.NaN };
|
|
57
|
+
}
|
|
58
|
+
let priorValue = Number.NaN;
|
|
59
|
+
let firstIdx = -1;
|
|
60
|
+
let lastIdx = -1;
|
|
61
|
+
for (let i = 0; i < this.count; ++i) {
|
|
62
|
+
const idx = (this.head + i) % this.capacity;
|
|
63
|
+
const t = this.ts[idx];
|
|
64
|
+
if (t < startMs) {
|
|
65
|
+
priorValue = this.val[idx];
|
|
66
|
+
}
|
|
67
|
+
else if (t <= endMs) {
|
|
68
|
+
if (firstIdx < 0)
|
|
69
|
+
firstIdx = i;
|
|
70
|
+
lastIdx = i;
|
|
71
|
+
}
|
|
72
|
+
else {
|
|
73
|
+
break;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (firstIdx < 0) {
|
|
77
|
+
return { timestamps: new Float64Array(0), values: new Float64Array(0), length: 0, priorValue };
|
|
78
|
+
}
|
|
79
|
+
const len = lastIdx - firstIdx + 1;
|
|
80
|
+
const timestamps = new Float64Array(len);
|
|
81
|
+
const values = new Float64Array(len);
|
|
82
|
+
for (let i = 0; i < len; ++i) {
|
|
83
|
+
const idx = (this.head + firstIdx + i) % this.capacity;
|
|
84
|
+
timestamps[i] = this.ts[idx];
|
|
85
|
+
values[i] = this.val[idx];
|
|
86
|
+
}
|
|
87
|
+
return { timestamps, values, length: len, priorValue };
|
|
88
|
+
}
|
|
89
|
+
}
|