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.
package/dist/series.js CHANGED
@@ -165,6 +165,58 @@ export class NumericSeries {
165
165
  get hasDirtyData() {
166
166
  return this.dirty;
167
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
+ }
168
220
  async open() {
169
221
  if (this.meta.config.raw.enabled) {
170
222
  this.rawFile = await this.store.openNumericRaw(this.meta);
@@ -444,6 +496,29 @@ export class NumericSeries {
444
496
  }
445
497
  return { firstSlotId: startId, data: out, count };
446
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
+ }
447
522
  getFinestEnabledTier() {
448
523
  for (let i = 0; i < ROLLUP_TIERS_FINEST_TO_COARSEST.length; ++i) {
449
524
  const state = this.tiers[ROLLUP_TIERS_FINEST_TO_COARSEST[i]];
@@ -452,7 +527,7 @@ export class NumericSeries {
452
527
  }
453
528
  return null;
454
529
  }
455
- selectServingTier(parsed, startMs) {
530
+ selectServingTier(parsed, startMs, endMs) {
456
531
  let partialMatch = null;
457
532
  for (let i = 0; i < ROLLUP_TIERS_COARSEST_TO_FINEST.length; ++i) {
458
533
  const tier = ROLLUP_TIERS_COARSEST_TO_FINEST[i];
@@ -469,8 +544,9 @@ export class NumericSeries {
469
544
  if (minCoveredTs <= startMs) {
470
545
  return state;
471
546
  }
472
- if (!partialMatch)
547
+ if (minCoveredTs <= endMs && !partialMatch) {
473
548
  partialMatch = state;
549
+ }
474
550
  }
475
551
  return partialMatch;
476
552
  }
@@ -741,7 +817,7 @@ export class NumericSeries {
741
817
  timezone,
742
818
  };
743
819
  }
744
- const finest = this.getFinestEnabledTier();
820
+ const finest = this.selectFallbackTier(startMs, endMs);
745
821
  if (!finest) {
746
822
  return {
747
823
  timestamps: new Float64Array(0),
@@ -787,7 +863,7 @@ export class NumericSeries {
787
863
  // 2. Rollup query mode (`interval === undefined` -> auto, or explicit interval).
788
864
  const resolvedInterval = options.interval === undefined ? selectAutoInterval(startMs, endMs) : options.interval;
789
865
  const parsedInterval = parseInterval(resolvedInterval);
790
- const servingTier = this.selectServingTier(parsedInterval, startMs);
866
+ const servingTier = this.selectServingTier(parsedInterval, startMs, endMs);
791
867
  if (servingTier) {
792
868
  const res = await this.queryTierAsBuckets(servingTier, startMs, endMs, parsedInterval, rollup);
793
869
  return {
@@ -833,7 +909,7 @@ export class NumericSeries {
833
909
  };
834
910
  }
835
911
  // Rule #6: raw is disabled and no dense tier divides targetInterval -> fallback + optional memory hybrid.
836
- const finest = this.getFinestEnabledTier();
912
+ const finest = this.selectFallbackTier(startMs, endMs);
837
913
  if (!finest) {
838
914
  return {
839
915
  timestamps: new Float64Array(0),
@@ -937,6 +1013,18 @@ export class ValueSeries {
937
1013
  get hasDirtyData() {
938
1014
  return this.pending.length > 0;
939
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
+ }
940
1028
  async open() {
941
1029
  this.file = await this.store.openValueRaw(this.meta);
942
1030
  }
@@ -1003,7 +1091,6 @@ export class ValueSeries {
1003
1091
  async query(options) {
1004
1092
  const startMs = toEpochMs(options.start);
1005
1093
  const endMs = toEpochMs(options.end);
1006
- const order = options.order ?? 'asc';
1007
1094
  const timezone = this.calendar.timezone;
1008
1095
  if (endMs < startMs) {
1009
1096
  return { points: [], truncated: false, timezone };
@@ -1015,24 +1102,7 @@ export class ValueSeries {
1015
1102
  pendingMatches.push(item);
1016
1103
  }
1017
1104
  }
1018
- if (order === 'desc') {
1019
- pendingMatches.reverse();
1020
- if (options.limit !== undefined && options.limit >= 0 && pendingMatches.length >= options.limit) {
1021
- return {
1022
- points: pendingMatches.slice(0, options.limit),
1023
- truncated: pendingMatches.length > options.limit || this.file.recordCount > 0,
1024
- timezone,
1025
- };
1026
- }
1027
- const remainingLimit = options.limit !== undefined && options.limit >= 0 ? options.limit - pendingMatches.length : undefined;
1028
- const diskRes = await this.file.readRange(startMs, endMs, remainingLimit, 'desc');
1029
- return {
1030
- points: pendingMatches.concat(this.decodeRecords(diskRes.records)),
1031
- truncated: diskRes.truncated,
1032
- timezone,
1033
- };
1034
- }
1035
- const diskRes = await this.file.readRange(startMs, endMs, options.limit, 'asc');
1105
+ const diskRes = await this.file.readRange(startMs, endMs, options.limit);
1036
1106
  const diskPoints = this.decodeRecords(diskRes.records);
1037
1107
  if (diskRes.truncated || pendingMatches.length === 0) {
1038
1108
  return { points: diskPoints, truncated: diskRes.truncated, timezone };
package/dist/store.d.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  import type { StorageBackend } from './backend.ts';
2
- import type { EncodedValueRecord, RollupTier, SeriesMeta } from './types.ts';
2
+ import type { ChunkSizeOptions, EncodedValueRecord, RollupTier, SeriesMeta, StorageChunkInfo } from './types.ts';
3
3
  export interface RollupTierStore {
4
4
  readonly hasData: boolean;
5
5
  readonly baseSlotId: number;
6
6
  readonly slotCount: number;
7
7
  readonly endSlotId: number;
8
+ readonly byteSize?: number;
8
9
  open(): Promise<void>;
9
10
  readLastSlot(): Promise<{
10
11
  slotId: number;
@@ -17,10 +18,13 @@ export interface RollupTierStore {
17
18
  count: number;
18
19
  }>;
19
20
  compact(keepFromSlotId: number): Promise<void>;
21
+ listChunks?(): ReadonlyArray<StorageChunkInfo>;
22
+ dropChunks?(chunkIds: ReadonlyArray<number>): Promise<void>;
20
23
  close(): Promise<void>;
21
24
  }
22
25
  export interface NumericRawStore {
23
26
  readonly recordCount: number;
27
+ readonly byteSize?: number;
24
28
  open(): Promise<void>;
25
29
  appendBatch(interleaved: Float64Array, count: number): Promise<void>;
26
30
  readRange(startMs: number, endMs: number, limit?: number, stripNaN?: boolean): Promise<{
@@ -34,16 +38,22 @@ export interface NumericRawStore {
34
38
  value: number;
35
39
  } | null>;
36
40
  compact(minTsKeep?: number, maxRecords?: number): Promise<void>;
41
+ listChunks?(): ReadonlyArray<StorageChunkInfo>;
42
+ dropChunks?(chunkIds: ReadonlyArray<number>): Promise<void>;
37
43
  close(): Promise<void>;
38
44
  }
39
45
  export interface ValueRawStore {
40
46
  readonly recordCount: number;
47
+ readonly byteSize?: number;
41
48
  open(): Promise<void>;
42
49
  appendBatch(entries: ReadonlyArray<EncodedValueRecord>): Promise<void>;
43
- readRange(startMs: number, endMs: number, limit?: number, order?: 'asc' | 'desc'): Promise<{
50
+ readRange(startMs: number, endMs: number, limit?: number): Promise<{
44
51
  records: EncodedValueRecord[];
45
52
  truncated: boolean;
46
53
  }>;
54
+ compact?(minTsKeep?: number, maxRecords?: number): Promise<void>;
55
+ listChunks?(): ReadonlyArray<StorageChunkInfo>;
56
+ dropChunks?(chunkIds: ReadonlyArray<number>): Promise<void>;
47
57
  close(): Promise<void>;
48
58
  }
49
59
  export interface TsdbStore {
@@ -58,7 +68,8 @@ export interface TsdbStore {
58
68
  }
59
69
  export declare class FileTsdbStore implements TsdbStore {
60
70
  private readonly backend;
61
- constructor(backend: StorageBackend);
71
+ private readonly chunkSize;
72
+ constructor(backend: StorageBackend, chunkSize?: ChunkSizeOptions);
62
73
  open(): Promise<void>;
63
74
  readCatalog<T>(): Promise<T | null>;
64
75
  writeCatalog(catalog: unknown): Promise<void>;
package/dist/store.js CHANGED
@@ -1,10 +1,13 @@
1
1
  import { NumericRawFile, ValueRawFile } from './rawFile.js';
2
+ import { resolveChunkSizes } from './retention.js';
2
3
  import { RollupFile } from './rollupFile.js';
3
4
  const CATALOG_PATH = 'catalog.json';
4
5
  export class FileTsdbStore {
5
6
  backend;
6
- constructor(backend) {
7
+ chunkSize;
8
+ constructor(backend, chunkSize) {
7
9
  this.backend = backend;
10
+ this.chunkSize = resolveChunkSizes(chunkSize);
8
11
  }
9
12
  async open() {
10
13
  await this.backend.ensureDir('');
@@ -17,19 +20,19 @@ export class FileTsdbStore {
17
20
  }
18
21
  async openNumericRaw(meta) {
19
22
  await this.backend.ensureDir(`series/${meta.dirKey}`);
20
- const file = new NumericRawFile(this.backend, `series/${meta.dirKey}/raw.bin`);
23
+ const file = new NumericRawFile(this.backend, `series/${meta.dirKey}/raw`, this.chunkSize.rawNumericChunkBytes);
21
24
  await file.open();
22
25
  return file;
23
26
  }
24
27
  async openRollupTier(meta, tier) {
25
28
  await this.backend.ensureDir(`series/${meta.dirKey}`);
26
- const file = new RollupFile(this.backend, `series/${meta.dirKey}/rollup_${tier}.bin`, tier);
29
+ const file = new RollupFile(this.backend, `series/${meta.dirKey}/rollup_${tier}`, tier, this.chunkSize.rollupChunkSlots);
27
30
  await file.open();
28
31
  return file;
29
32
  }
30
33
  async openValueRaw(meta) {
31
34
  await this.backend.ensureDir(`series/${meta.dirKey}`);
32
- const file = new ValueRawFile(this.backend, `series/${meta.dirKey}/val.bin`, `series/${meta.dirKey}/val.idx`);
35
+ const file = new ValueRawFile(this.backend, `series/${meta.dirKey}/val`, this.chunkSize.rawValueChunkBytes);
33
36
  await file.open();
34
37
  return file;
35
38
  }
package/dist/types.d.ts CHANGED
@@ -70,6 +70,39 @@ export interface EncodedValueRecord {
70
70
  /** Raw string when `isString` is true, codec-encoded text when false, or `null` for `undefined`. */
71
71
  payload: string | null;
72
72
  }
73
+ export interface StorageLimitOptions {
74
+ /** Total byte limit across all numeric/boolean series raw stores. */
75
+ rawNumericMaxBytes?: number;
76
+ /** Total byte limit across all non-numeric (`value`) series raw stores. */
77
+ rawValueMaxBytes?: number;
78
+ /** Total byte limit across all rollup tiers (`15s`, `5m`, `1h`, `1d`) combined. */
79
+ rollupMaxBytes?: number;
80
+ /** Target fraction of max size to trim down to when limit is exceeded (default: 0.7, range (0, 1)). */
81
+ trimTargetRatio?: number;
82
+ /** Minimum interval in ms between automatic size checks during flush (default: 0). */
83
+ checkIntervalMs?: number;
84
+ }
85
+ export interface ChunkSizeOptions {
86
+ /** Target max byte size per numeric raw chunk file (default: 65536). */
87
+ rawNumericChunkBytes?: number;
88
+ /** Target byte size threshold per value raw chunk file (default: 65536). */
89
+ rawValueChunkBytes?: number;
90
+ /** Maximum slots per rollup chunk file (default: 512). */
91
+ rollupChunkSlots?: number;
92
+ }
93
+ export interface StorageChunkInfo {
94
+ id: number;
95
+ minKey: number;
96
+ maxKey: number;
97
+ byteSize: number;
98
+ count: number;
99
+ }
100
+ export interface StorageUsageStats {
101
+ rawNumericBytes: number;
102
+ rawValueBytes: number;
103
+ rollupBytes: number;
104
+ rollupTierBytes: Record<RollupTier, number>;
105
+ }
73
106
  export interface TsdbOptions {
74
107
  dir?: string;
75
108
  backend?: StorageBackend;
@@ -79,6 +112,8 @@ export interface TsdbOptions {
79
112
  weekStartsOn?: 0 | 1;
80
113
  flushIntervalMs?: number;
81
114
  defaultSeriesConfig?: Partial<Omit<SeriesConfig, 'kind'>>;
115
+ storageLimits?: StorageLimitOptions;
116
+ chunkSize?: ChunkSizeOptions;
82
117
  }
83
118
  export interface NumericQueryOptions {
84
119
  start: TimestampInput;
@@ -114,7 +149,6 @@ export interface ValueQueryOptions {
114
149
  start: TimestampInput;
115
150
  end: TimestampInput;
116
151
  limit?: number;
117
- order?: 'asc' | 'desc';
118
152
  }
119
153
  export interface ValuePoint {
120
154
  ts: number;
package/package.json CHANGED
@@ -1,12 +1,16 @@
1
1
  {
2
2
  "name": "ticlo-tsdb",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "High-performance embedded TypeScript time-series database with configurable dense rollups",
5
5
  "license": "MPL-2.0",
6
6
  "author": {
7
7
  "name": "Rick Zhou",
8
8
  "email": "rinick@gmail.com"
9
9
  },
10
+ "files": [
11
+ "dist",
12
+ "README.md"
13
+ ],
10
14
  "type": "module",
11
15
  "main": "./dist/index.js",
12
16
  "module": "./dist/index.js",
@@ -17,13 +21,6 @@
17
21
  "default": "./dist/index.js"
18
22
  }
19
23
  },
20
- "files": [
21
- "dist",
22
- "README.md"
23
- ],
24
- "engines": {
25
- "node": ">=24.0.0"
26
- },
27
24
  "scripts": {
28
25
  "build": "tsgo -p tsconfig.build.json",
29
26
  "test": "node --test test/*.test.ts",
@@ -34,5 +31,8 @@
34
31
  "devDependencies": {
35
32
  "@types/node": "^26.5.0",
36
33
  "@typescript/native-preview": "7.0.0-dev.20260707.2"
34
+ },
35
+ "engines": {
36
+ "node": ">=24.0.0"
37
37
  }
38
38
  }