@mxtommy/kip 4.5.0-beta.1 → 4.5.1

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.
Files changed (102) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +11 -7
  3. package/package.json +21 -8
  4. package/plugin/duckdb-parquet-storage.service.js +1182 -0
  5. package/plugin/history-series.service.js +439 -0
  6. package/plugin/index.js +705 -30
  7. package/plugin/openApi.json +253 -3
  8. package/plugin/plugin-auth.service.js +75 -0
  9. package/public/assets/help-docs/chartplotter.md +5 -18
  10. package/public/assets/help-docs/community.md +0 -3
  11. package/public/assets/help-docs/configuration.md +1 -1
  12. package/public/assets/help-docs/contact-us.md +0 -4
  13. package/public/assets/help-docs/dashboards.md +20 -18
  14. package/public/assets/help-docs/datainspector.md +7 -5
  15. package/public/assets/help-docs/history-api.md +116 -0
  16. package/public/assets/help-docs/menu.json +18 -6
  17. package/public/assets/help-docs/nodered-control-flows.md +125 -0
  18. package/public/assets/help-docs/putcontrols.md +101 -60
  19. package/public/assets/help-docs/welcome.md +6 -7
  20. package/public/assets/help-docs/widget-historical-series.md +66 -0
  21. package/public/assets/help-docs/zones.md +5 -10
  22. package/public/chunk-A6DQJFP4.js +16 -0
  23. package/public/chunk-B75MT7ND.js +1 -0
  24. package/public/{chunk-T6TFVZVM.js → chunk-CEB42O2C.js} +1 -1
  25. package/public/chunk-CHGXAEKT.js +2 -0
  26. package/public/chunk-D7VDX7ZF.js +5 -0
  27. package/public/{chunk-ZQER6AIQ.js → chunk-DEGYRCMI.js} +1 -1
  28. package/public/{chunk-M2B5OYGO.js → chunk-DEM56G4S.js} +1 -1
  29. package/public/chunk-DYTBBUMI.js +4 -0
  30. package/public/chunk-EQ2N7KDA.js +3 -0
  31. package/public/chunk-FNF7M3AE.js +1 -0
  32. package/public/chunk-IHURI4IH.js +5 -0
  33. package/public/{chunk-YIYYVDFO.js → chunk-IYRLINL7.js} +2 -2
  34. package/public/{chunk-5FEX27I4.js → chunk-JB4YVVNW.js} +1 -1
  35. package/public/chunk-JGGMFMY5.js +1 -0
  36. package/public/chunk-KPHICV76.js +5 -0
  37. package/public/{chunk-QZKCRH3H.js → chunk-KZ5DUKAX.js} +1 -1
  38. package/public/{chunk-HMOOTAEA.js → chunk-LQDSU4WS.js} +3 -3
  39. package/public/{chunk-IXQ7KIFY.js → chunk-MGPPVLZ7.js} +1 -1
  40. package/public/{chunk-QVCLOCEC.js → chunk-R7RQHWKJ.js} +1 -1
  41. package/public/chunk-RONXIZ2U.js +9 -0
  42. package/public/chunk-S72JTJPN.js +6 -0
  43. package/public/{chunk-KFFAA7DL.js → chunk-VCY32MWT.js} +8 -8
  44. package/public/chunk-YCEXTKGG.js +1 -0
  45. package/public/chunk-YKJKIWXO.js +6 -0
  46. package/public/chunk-ZV7IYYEQ.js +50 -0
  47. package/public/index.html +1 -1
  48. package/public/main-FQESQQV6.js +1 -0
  49. package/.github/ISSUE_TEMPLATE/bug_report.yml +0 -84
  50. package/.github/ISSUE_TEMPLATE/config.yml +0 -5
  51. package/.github/ISSUE_TEMPLATE/feature_request.yml +0 -35
  52. package/.github/copilot-instructions.md +0 -205
  53. package/.github/instructions/angular.instructions.md +0 -123
  54. package/.github/instructions/best-practices.instructions.md +0 -59
  55. package/.github/instructions/project.instructions.md +0 -432
  56. package/.github/workflows/ci.yml +0 -37
  57. package/docs/widget-schematic.md +0 -102
  58. package/images/ActionSidenav.png +0 -0
  59. package/images/ChartplotterMode.png +0 -0
  60. package/images/KIPDemo.png +0 -0
  61. package/images/KipBrightness-1024.png +0 -0
  62. package/images/KipConfig-Units-1024.png +0 -0
  63. package/images/KipConfig-display-1024x488.png +0 -0
  64. package/images/KipFreeboard-SK-1024.png +0 -0
  65. package/images/KipGaugeSample1-1024x545.png +0 -0
  66. package/images/KipGaugeSample2-1024x488.png +0 -0
  67. package/images/KipGaugeSample3-1024x508.png +0 -0
  68. package/images/KipNightMode-1024.png +0 -0
  69. package/images/KipWidgetConfig-layout-1024.png +0 -0
  70. package/images/KipWidgetConfig-paths-1024x488.png +0 -0
  71. package/images/Options.png +0 -0
  72. package/images/exterior_user_installs.png +0 -0
  73. package/images/formfactor.png +0 -0
  74. package/public/assets/help-docs/datasets.md +0 -95
  75. package/public/chunk-2OB7ZJBR.js +0 -3
  76. package/public/chunk-6GGJZDRE.js +0 -1
  77. package/public/chunk-6V4GGGXE.js +0 -2
  78. package/public/chunk-A5BW6BUM.js +0 -1
  79. package/public/chunk-DGE5YFPU.js +0 -5
  80. package/public/chunk-G6M3Z3BY.js +0 -53
  81. package/public/chunk-GMGZLXY7.js +0 -4
  82. package/public/chunk-GUZ3BDVZ.js +0 -2
  83. package/public/chunk-ICDGHQFP.js +0 -6
  84. package/public/chunk-JCNE4QHQ.js +0 -15
  85. package/public/chunk-K6XYUNG4.js +0 -8
  86. package/public/chunk-LGCQEN7V.js +0 -4
  87. package/public/chunk-O3JH7UTR.js +0 -1
  88. package/public/chunk-Q3USFT4F.js +0 -2
  89. package/public/chunk-VIKU7BH7.js +0 -1
  90. package/public/chunk-XMQPXXLW.js +0 -8
  91. package/public/main-4URMGBQS.js +0 -1
  92. package/rm-npmjs-beta.sh +0 -50
  93. package/tools/schematics/collection.json +0 -9
  94. package/tools/schematics/create-host2-widget/files/readme/README.md.template +0 -109
  95. package/tools/schematics/create-host2-widget/files/spec/widget-__name@dasherize__.component.spec.ts +0 -38
  96. package/tools/schematics/create-host2-widget/files/widget/widget-__name@dasherize__.component.html +0 -6
  97. package/tools/schematics/create-host2-widget/files/widget/widget-__name@dasherize__.component.scss +0 -5
  98. package/tools/schematics/create-host2-widget/files/widget/widget-__name@dasherize__.component.ts.template +0 -94
  99. package/tools/schematics/create-host2-widget/index.js +0 -138
  100. package/tools/schematics/create-host2-widget/schema.json +0 -89
  101. package/tools/schematics/create-host2-widget/test/create-host2-widget.spec.ts +0 -70
  102. package/tools/schematics/create-host2-widget/utils/formatting.js +0 -119
@@ -0,0 +1,1182 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DuckDbParquetStorageService = void 0;
4
+ const fs_1 = require("fs");
5
+ const path_1 = require("path");
6
+ const node_api_1 = require("@duckdb/node-api");
7
+ const parquetjs_1 = require("@dsnp/parquetjs");
8
+ /**
9
+ * Provides DuckDB storage and Parquet flush support for captured history samples.
10
+ */
11
+ class DuckDbParquetStorageService {
12
+ config = {
13
+ engine: 'duckdb-parquet',
14
+ databaseFile: 'plugin-config-data/kip/historicalData/kip-history.duckdb',
15
+ parquetDirectory: 'plugin-config-data/kip/historicalData/parquet',
16
+ flushIntervalMs: 30_000
17
+ };
18
+ // 8 hour job interval (8 hours)
19
+ static EIGHT_HOURS_INTERVAL = 8 * 60 * 60 * 1000;
20
+ vacuumJob = null;
21
+ // 4 hour job interval (4 hours)
22
+ static FOUR_HOURS_INTERVAL = 4 * 60 * 60 * 1000;
23
+ pruneJob = null;
24
+ // Stale series cleanup interval (6 months)
25
+ static STALE_SERIES_AGE_MS = 180 * 24 * 60 * 60 * 1000; // 6 months
26
+ staleSeriesCleanupJob = null;
27
+ static PRUNE_BATCH_SIZE = 10_000;
28
+ logger = {
29
+ debug: () => undefined,
30
+ error: () => undefined
31
+ };
32
+ db = null;
33
+ connection = null;
34
+ pendingRows = [];
35
+ pendingRangesBySeriesId = new Map();
36
+ lastInitError = null;
37
+ lifecycleToken = 0;
38
+ initialized = false;
39
+ maintenanceInProgress = false;
40
+ flushInProgress = false;
41
+ /**
42
+ * Sets logger callbacks used by the storage service.
43
+ *
44
+ * @param {TLogger} logger Logger implementation from plugin runtime.
45
+ * @returns {void}
46
+ *
47
+ * @example
48
+ * storage.setLogger({ debug: console.log, error: console.error });
49
+ */
50
+ setLogger(logger) {
51
+ this.logger = logger;
52
+ }
53
+ /**
54
+ * Applies the fixed storage backend configuration.
55
+ *
56
+ * @returns {IDuckDbParquetStorageConfig} Fixed storage configuration.
57
+ *
58
+ * @example
59
+ * const cfg = storage.configure();
60
+ * console.log(cfg.engine);
61
+ */
62
+ configure() {
63
+ this.initialized = false;
64
+ this.config = {
65
+ engine: 'duckdb-parquet',
66
+ databaseFile: 'plugin-config-data/kip/historicalData/kip-history.duckdb',
67
+ parquetDirectory: 'plugin-config-data/kip/historicalData/parquet',
68
+ flushIntervalMs: 30_000
69
+ };
70
+ return this.config;
71
+ }
72
+ /**
73
+ * Initializes DuckDB storage if DuckDB engine is selected.
74
+ *
75
+ * @returns {Promise<boolean>} True when DuckDB is initialized and ready.
76
+ *
77
+ * @example
78
+ * const ready = await storage.initialize();
79
+ */
80
+ async initialize() {
81
+ if (!this.isDuckDbParquetEnabled()) {
82
+ return false;
83
+ }
84
+ this.initialized = false;
85
+ this.lifecycleToken += 1;
86
+ try {
87
+ const dbPath = (0, path_1.resolve)(this.config.databaseFile);
88
+ (0, fs_1.mkdirSync)((0, path_1.dirname)(dbPath), { recursive: true });
89
+ (0, fs_1.mkdirSync)((0, path_1.resolve)(this.config.parquetDirectory), { recursive: true });
90
+ this.db = await node_api_1.DuckDBInstance.create(dbPath);
91
+ this.connection = await this.db.connect();
92
+ await this.createCoreTables();
93
+ await this.runSql('CREATE INDEX IF NOT EXISTS idx_history_series_scope_ts ON history_samples(series_id, ts_ms)');
94
+ await this.runSql('CREATE INDEX IF NOT EXISTS idx_history_series_scope_id ON history_series(series_id)');
95
+ await this.runSql('CREATE INDEX IF NOT EXISTS idx_history_samples_scope_context_path_ts ON history_samples(context, path, ts_ms)');
96
+ await this.runSql('CREATE INDEX IF NOT EXISTS idx_history_samples_scope_ts_path ON history_samples(ts_ms, path)');
97
+ await this.runSql('CREATE INDEX IF NOT EXISTS idx_history_samples_scope_ts_context ON history_samples(ts_ms, context)');
98
+ this.logger.debug(`[SERIES STORAGE] DuckDB initialized at ${dbPath}`);
99
+ this.lastInitError = null;
100
+ this.initialized = true;
101
+ // Start VACUUM job
102
+ this.startVacuumJob();
103
+ // Start prune job
104
+ this.startPruneJob();
105
+ // Start stale series cleanup job
106
+ this.startStaleSeriesCleanupJob();
107
+ return true;
108
+ }
109
+ catch (error) {
110
+ const message = error?.message ?? String(error);
111
+ this.lastInitError = message;
112
+ this.logger.error(`[SERIES STORAGE] DuckDB initialization failed: ${message}`);
113
+ this.logger.error('[SERIES STORAGE] DuckDB Node API is required. Install runtime dependency with: npm i @duckdb/node-api in the installed plugin directory, then restart Signal K.');
114
+ this.connection = null;
115
+ this.db = null;
116
+ this.pendingRows = [];
117
+ this.pendingRangesBySeriesId.clear();
118
+ this.initialized = false;
119
+ this.stopVacuumJob();
120
+ return false;
121
+ }
122
+ }
123
+ /**
124
+ * Starts VACUUM job for DuckDB.
125
+ */
126
+ startVacuumJob() {
127
+ this.stopVacuumJob();
128
+ if (!this.isDuckDbParquetReady() || !this.connection)
129
+ return;
130
+ this.vacuumJob = setInterval(() => {
131
+ if (this.shouldSkipMaintenance()) {
132
+ return;
133
+ }
134
+ void this.runWithMaintenanceLock('vacuum', async () => {
135
+ this.logger.debug('[SERIES STORAGE] Running scheduled DuckDB VACUUM');
136
+ await this.runSql('VACUUM;');
137
+ }).catch(err => {
138
+ this.logger.error(`[SERIES STORAGE] VACUUM failed: ${err?.message ?? err}`);
139
+ });
140
+ }, DuckDbParquetStorageService.EIGHT_HOURS_INTERVAL);
141
+ this.vacuumJob.unref?.();
142
+ }
143
+ /**
144
+ * Stops the scheduled VACUUM job if running.
145
+ */
146
+ stopVacuumJob() {
147
+ if (this.vacuumJob) {
148
+ clearInterval(this.vacuumJob);
149
+ this.vacuumJob = null;
150
+ }
151
+ }
152
+ /**
153
+ * Starts the prune job for expired and orphaned samples.
154
+ */
155
+ startPruneJob() {
156
+ this.stopPruneJob();
157
+ if (!this.isDuckDbParquetReady() || !this.connection)
158
+ return;
159
+ this.pruneJob = setInterval(async () => {
160
+ if (this.shouldSkipMaintenance()) {
161
+ return;
162
+ }
163
+ try {
164
+ await this.runWithMaintenanceLock('prune', async () => {
165
+ this.logger.debug('[SERIES STORAGE] Running scheduled prune of expired and orphaned samples');
166
+ const expired = await this.pruneExpiredSamples(Date.now(), this.lifecycleToken);
167
+ const orphaned = await this.pruneOrphanedSamples(this.lifecycleToken);
168
+ this.logger.debug(`[SERIES STORAGE] Pruned ${expired} expired and ${orphaned} orphaned samples`);
169
+ });
170
+ }
171
+ catch (err) {
172
+ this.logger.error(`[SERIES STORAGE] Prune failed: ${err?.message ?? err}`);
173
+ }
174
+ }, DuckDbParquetStorageService.FOUR_HOURS_INTERVAL);
175
+ this.pruneJob.unref?.();
176
+ }
177
+ /**
178
+ * Stops the scheduled prune job if running.
179
+ */
180
+ stopPruneJob() {
181
+ if (this.pruneJob) {
182
+ clearInterval(this.pruneJob);
183
+ this.pruneJob = null;
184
+ }
185
+ }
186
+ /**
187
+ * Starts the scheduled job to delete series not reconciled in the last 6 months.
188
+ */
189
+ startStaleSeriesCleanupJob() {
190
+ this.stopStaleSeriesCleanupJob();
191
+ if (!this.isDuckDbParquetReady() || !this.connection)
192
+ return;
193
+ this.staleSeriesCleanupJob = setInterval(async () => {
194
+ if (this.shouldSkipMaintenance()) {
195
+ return;
196
+ }
197
+ try {
198
+ await this.runWithMaintenanceLock('stale-cleanup', async () => {
199
+ const cutoff = Date.now() - DuckDbParquetStorageService.STALE_SERIES_AGE_MS;
200
+ this.logger.debug(`[SERIES STORAGE] Running scheduled stale series cleanup (cutoff: ${new Date(cutoff).toISOString()})`);
201
+ const deleted = await this.deleteStaleSeries(cutoff);
202
+ if (deleted > 0) {
203
+ this.logger.debug(`[SERIES STORAGE] Deleted ${deleted} series not reconciled in the last 6 months`);
204
+ }
205
+ });
206
+ }
207
+ catch (err) {
208
+ this.logger.error(`[SERIES STORAGE] Stale series cleanup failed: ${err?.message ?? err}`);
209
+ }
210
+ }, DuckDbParquetStorageService.EIGHT_HOURS_INTERVAL);
211
+ this.staleSeriesCleanupJob.unref?.();
212
+ }
213
+ /**
214
+ * Deletes series not reconciled since the given cutoff timestamp.
215
+ * @param {number} cutoffMs - Milliseconds since epoch; series with reconcile_ts < cutoffMs will be deleted.
216
+ * @returns {Promise<number>} Number of deleted series.
217
+ *
218
+ * @example
219
+ * const deleted = await storage.deleteStaleSeries(Date.now() - 180 * 24 * 60 * 60 * 1000);
220
+ */
221
+ async deleteStaleSeries(cutoffMs) {
222
+ if (!this.isDuckDbParquetEnabled() || !this.connection) {
223
+ return 0;
224
+ }
225
+ // Find series to delete
226
+ const rows = await this.querySql(`
227
+ SELECT series_id FROM history_series
228
+ WHERE reconcile_ts IS NULL OR reconcile_ts < ${Math.trunc(cutoffMs)}
229
+ `);
230
+ const ids = rows.map(r => r.series_id);
231
+ if (ids.length === 0)
232
+ return 0;
233
+ for (const id of ids) {
234
+ await this.deleteSeriesDefinition(id);
235
+ }
236
+ return ids.length;
237
+ }
238
+ /**
239
+ * Stops the scheduled stale series cleanup job if running.
240
+ */
241
+ stopStaleSeriesCleanupJob() {
242
+ if (this.staleSeriesCleanupJob) {
243
+ clearInterval(this.staleSeriesCleanupJob);
244
+ this.staleSeriesCleanupJob = null;
245
+ }
246
+ }
247
+ shouldSkipMaintenance() {
248
+ if (!this.isDuckDbParquetReady() || !this.connection) {
249
+ return true;
250
+ }
251
+ if (this.maintenanceInProgress || this.flushInProgress) {
252
+ return true;
253
+ }
254
+ if (this.pendingRows.length > 0) {
255
+ return true;
256
+ }
257
+ return false;
258
+ }
259
+ async runWithMaintenanceLock(label, task) {
260
+ if (this.maintenanceInProgress) {
261
+ this.logger.debug(`[SERIES STORAGE] Skipping ${label} (maintenance already running)`);
262
+ return;
263
+ }
264
+ this.maintenanceInProgress = true;
265
+ const startedAt = Date.now();
266
+ try {
267
+ await task();
268
+ const elapsedMs = Date.now() - startedAt;
269
+ this.logger.debug(`[SERIES STORAGE] ${label} completed in ${elapsedMs}ms`);
270
+ }
271
+ finally {
272
+ this.maintenanceInProgress = false;
273
+ }
274
+ }
275
+ /**
276
+ * Returns the active storage configuration.
277
+ *
278
+ * @returns {IDuckDbParquetStorageConfig} Current storage configuration.
279
+ *
280
+ * @example
281
+ * const cfg = storage.getConfig();
282
+ */
283
+ getConfig() {
284
+ return this.config;
285
+ }
286
+ /**
287
+ * Returns last DuckDB initialization error when initialization failed.
288
+ *
289
+ * @returns {string | null} Initialization error text or null.
290
+ *
291
+ * @example
292
+ * const err = storage.getLastInitError();
293
+ */
294
+ getLastInitError() {
295
+ return this.lastInitError;
296
+ }
297
+ /**
298
+ * Indicates whether DuckDB/Parquet mode is selected.
299
+ *
300
+ * @returns {boolean} True when the selected engine is `duckdb-parquet`.
301
+ *
302
+ * @example
303
+ * if (storage.isDuckDbParquetEnabled()) {
304
+ * console.log('DuckDB mode enabled');
305
+ * }
306
+ */
307
+ isDuckDbParquetEnabled() {
308
+ return this.config.engine === 'duckdb-parquet';
309
+ }
310
+ /**
311
+ * Indicates whether DuckDB/Parquet mode is initialized and ready.
312
+ *
313
+ * @returns {boolean} True when DuckDB mode is selected and an active connection exists.
314
+ *
315
+ * @example
316
+ * if (storage.isDuckDbParquetReady()) {
317
+ * console.log('DuckDB ready');
318
+ * }
319
+ */
320
+ isDuckDbParquetReady() {
321
+ return this.isDuckDbParquetEnabled() && this.initialized && this.connection !== null;
322
+ }
323
+ /**
324
+ * Returns the current storage lifecycle token.
325
+ *
326
+ * The token changes whenever a new initialization attempt starts and can be
327
+ * used by callers to scope async stop operations (flush/close) so stale work
328
+ * does not affect a newer startup session.
329
+ *
330
+ * @returns {number} Current lifecycle token.
331
+ *
332
+ * @example
333
+ * const token = storage.getLifecycleToken();
334
+ */
335
+ getLifecycleToken() {
336
+ return this.lifecycleToken;
337
+ }
338
+ /**
339
+ * Adds a captured sample row to the pending storage queue.
340
+ *
341
+ * @param {IRecordedSample} sample Captured sample metadata and value.
342
+ * @returns {void}
343
+ *
344
+ * @example
345
+ * storage.enqueueSample(sample);
346
+ */
347
+ enqueueSample(sample) {
348
+ if (!this.isDuckDbParquetReady()) {
349
+ return;
350
+ }
351
+ this.pendingRows.push(sample);
352
+ const rangeKey = sample.seriesId;
353
+ const existing = this.pendingRangesBySeriesId.get(rangeKey);
354
+ if (!existing) {
355
+ this.pendingRangesBySeriesId.set(rangeKey, {
356
+ seriesId: sample.seriesId,
357
+ minTs: sample.timestamp,
358
+ maxTs: sample.timestamp
359
+ });
360
+ return;
361
+ }
362
+ this.pendingRangesBySeriesId.set(rangeKey, {
363
+ seriesId: existing.seriesId,
364
+ minTs: Math.min(existing.minTs, sample.timestamp),
365
+ maxTs: Math.max(existing.maxTs, sample.timestamp)
366
+ });
367
+ }
368
+ /**
369
+ * Flushes queued samples into DuckDB and exports changed ranges to Parquet chunks.
370
+ *
371
+ * @returns {Promise<{inserted: number; exported: number}>} Number of inserted rows and exported parquet files.
372
+ *
373
+ * @example
374
+ * const result = await storage.flush();
375
+ */
376
+ async flush(expectedLifecycleToken) {
377
+ if (expectedLifecycleToken !== undefined && expectedLifecycleToken !== this.lifecycleToken) {
378
+ return { inserted: 0, exported: 0 };
379
+ }
380
+ if (!this.isDuckDbParquetEnabled() || !this.connection || this.pendingRows.length === 0) {
381
+ return { inserted: 0, exported: 0 };
382
+ }
383
+ if (this.flushInProgress) {
384
+ return { inserted: 0, exported: 0 };
385
+ }
386
+ this.flushInProgress = true;
387
+ const rows = this.pendingRows;
388
+ const ranges = new Map(this.pendingRangesBySeriesId);
389
+ this.pendingRows = [];
390
+ this.pendingRangesBySeriesId.clear();
391
+ const startedAt = Date.now();
392
+ try {
393
+ await this.insertRows(rows);
394
+ let exported = 0;
395
+ for (const range of ranges.values()) {
396
+ await this.exportSeriesRange(range.seriesId, range.minTs, range.maxTs);
397
+ exported += 1;
398
+ }
399
+ const elapsedMs = Date.now() - startedAt;
400
+ this.logger.debug(`[SERIES STORAGE] flush inserted=${rows.length} exported=${exported} durationMs=${elapsedMs}`);
401
+ return { inserted: rows.length, exported };
402
+ }
403
+ catch (error) {
404
+ this.pendingRows = [...rows, ...this.pendingRows];
405
+ ranges.forEach((range, rangeKey) => {
406
+ const current = this.pendingRangesBySeriesId.get(rangeKey);
407
+ if (!current) {
408
+ this.pendingRangesBySeriesId.set(rangeKey, range);
409
+ return;
410
+ }
411
+ this.pendingRangesBySeriesId.set(rangeKey, {
412
+ seriesId: current.seriesId,
413
+ minTs: Math.min(current.minTs, range.minTs),
414
+ maxTs: Math.max(current.maxTs, range.maxTs)
415
+ });
416
+ });
417
+ throw error;
418
+ }
419
+ finally {
420
+ this.flushInProgress = false;
421
+ }
422
+ }
423
+ /**
424
+ * Returns persisted series definitions from DuckDB.
425
+ *
426
+ * @returns {Promise<ISeriesDefinition[]>} Stored series definitions.
427
+ *
428
+ * @example
429
+ * const series = await storage.getSeriesDefinitions();
430
+ */
431
+ async getSeriesDefinitions() {
432
+ if (!this.isDuckDbParquetEnabled() || !this.connection) {
433
+ return [];
434
+ }
435
+ const rows = await this.querySql(`
436
+ SELECT
437
+ series_id,
438
+ dataset_uuid,
439
+ owner_widget_uuid,
440
+ owner_widget_selector,
441
+ path,
442
+ source,
443
+ context,
444
+ time_scale,
445
+ period,
446
+ retention_duration_ms,
447
+ sample_time,
448
+ enabled,
449
+ methods_json
450
+ FROM history_series
451
+ ORDER BY series_id ASC
452
+ `);
453
+ return rows.map(row => ({
454
+ seriesId: row.series_id,
455
+ datasetUuid: row.dataset_uuid,
456
+ ownerWidgetUuid: row.owner_widget_uuid,
457
+ ownerWidgetSelector: row.owner_widget_selector ?? undefined,
458
+ path: row.path,
459
+ source: row.source ?? undefined,
460
+ context: row.context ?? undefined,
461
+ timeScale: row.time_scale ?? undefined,
462
+ period: this.toNumberOrUndefined(row.period),
463
+ retentionDurationMs: this.toNumberOrUndefined(row.retention_duration_ms),
464
+ sampleTime: this.toNumberOrUndefined(row.sample_time),
465
+ enabled: this.toBoolean(row.enabled),
466
+ methods: this.parseMethods(row.methods_json)
467
+ }));
468
+ }
469
+ /**
470
+ * Persists one series definition in DuckDB.
471
+ *
472
+ * @param {ISeriesDefinition} series Series definition to persist.
473
+ * @returns {Promise<void>}
474
+ *
475
+ * @example
476
+ * await storage.upsertSeriesDefinition(series);
477
+ */
478
+ async upsertSeriesDefinition(series) {
479
+ if (!this.isDuckDbParquetEnabled() || !this.connection) {
480
+ return;
481
+ }
482
+ await this.runSql(`DELETE FROM history_series WHERE series_id = ${this.escape(series.seriesId)}`);
483
+ await this.runSql(`
484
+ INSERT INTO history_series (
485
+ series_id,
486
+ dataset_uuid,
487
+ owner_widget_uuid,
488
+ owner_widget_selector,
489
+ path,
490
+ source,
491
+ context,
492
+ time_scale,
493
+ period,
494
+ retention_duration_ms,
495
+ sample_time,
496
+ enabled,
497
+ methods_json
498
+ ) VALUES (
499
+ ${this.escape(series.seriesId)},
500
+ ${this.escape(series.datasetUuid)},
501
+ ${this.escape(series.ownerWidgetUuid)},
502
+ ${this.nullableString(series.ownerWidgetSelector)},
503
+ ${this.escape(series.path)},
504
+ ${this.nullableString(series.source)},
505
+ ${this.nullableString(series.context)},
506
+ ${this.nullableString(series.timeScale)},
507
+ ${this.nullableNumber(series.period)},
508
+ ${this.nullableNumber(series.retentionDurationMs)},
509
+ ${this.nullableNumber(series.sampleTime)},
510
+ ${series.enabled === false ? 'FALSE' : 'TRUE'},
511
+ ${this.nullableString(series.methods ? JSON.stringify(series.methods) : null)}
512
+ )
513
+ `);
514
+ }
515
+ /**
516
+ * Deletes one persisted series definition in DuckDB.
517
+ *
518
+ * @param {string} seriesId Series identifier.
519
+ * @returns {Promise<void>}
520
+ *
521
+ * @example
522
+ * await storage.deleteSeriesDefinition('series-1');
523
+ */
524
+ async deleteSeriesDefinition(seriesId) {
525
+ if (!this.isDuckDbParquetEnabled() || !this.connection) {
526
+ return;
527
+ }
528
+ await this.runSql(`DELETE FROM history_series WHERE series_id = ${this.escape(seriesId)}`);
529
+ }
530
+ /**
531
+ * Replaces persisted series definitions with desired set.
532
+ *
533
+ * @param {ISeriesDefinition[]} series Full desired series set.
534
+ * @returns {Promise<void>}
535
+ *
536
+ * @example
537
+ * await storage.replaceSeriesDefinitions(series);
538
+ */
539
+ async replaceSeriesDefinitions(series) {
540
+ if (!this.isDuckDbParquetEnabled() || !this.connection) {
541
+ return;
542
+ }
543
+ await this.runSql('DELETE FROM history_series');
544
+ for (const item of series) {
545
+ await this.upsertSeriesDefinition(item);
546
+ }
547
+ }
548
+ /**
549
+ * Removes persisted samples that are older than each series retention window.
550
+ *
551
+ * @param {number} [nowMs=Date.now()] Current timestamp in milliseconds used to compute per-series cutoffs.
552
+ * @param {number} [expectedLifecycleToken] Optional lifecycle token guard to skip stale sweeps.
553
+ * @returns {Promise<number>} Number of deleted sample rows.
554
+ *
555
+ * @example
556
+ * const removed = await storage.pruneExpiredSamples();
557
+ */
558
+ async pruneExpiredSamples(nowMs = Date.now(), expectedLifecycleToken) {
559
+ if (expectedLifecycleToken !== undefined && expectedLifecycleToken !== this.lifecycleToken) {
560
+ return 0;
561
+ }
562
+ if (!this.isDuckDbParquetEnabled() || !this.connection) {
563
+ return 0;
564
+ }
565
+ const anchorMs = Math.trunc(Number.isFinite(nowMs) ? nowMs : Date.now());
566
+ const whereClause = `
567
+ EXISTS (
568
+ SELECT 1
569
+ FROM history_series AS hs
570
+ WHERE hs.series_id = history_samples.series_id
571
+ AND hs.retention_duration_ms IS NOT NULL
572
+ AND hs.retention_duration_ms > 0
573
+ AND history_samples.ts_ms < (${anchorMs} - hs.retention_duration_ms)
574
+ )
575
+ `;
576
+ let removedRows = 0;
577
+ while (true) {
578
+ const batch = await this.querySql(`
579
+ SELECT rowid
580
+ FROM history_samples
581
+ WHERE ${whereClause}
582
+ LIMIT ${DuckDbParquetStorageService.PRUNE_BATCH_SIZE}
583
+ `);
584
+ if (batch.length === 0) {
585
+ break;
586
+ }
587
+ const rowIds = batch.map(row => Math.trunc(Number(row.rowid))).filter(Number.isFinite);
588
+ if (rowIds.length === 0) {
589
+ break;
590
+ }
591
+ await this.runSql(`
592
+ DELETE FROM history_samples
593
+ WHERE rowid IN (${rowIds.join(', ')})
594
+ `);
595
+ removedRows += rowIds.length;
596
+ if (rowIds.length < DuckDbParquetStorageService.PRUNE_BATCH_SIZE) {
597
+ break;
598
+ }
599
+ }
600
+ return removedRows;
601
+ }
602
+ /**
603
+ * Removes persisted samples that no longer have a matching series definition.
604
+ *
605
+ * @param {number} [expectedLifecycleToken] Optional lifecycle token guard to skip stale sweeps.
606
+ * @returns {Promise<number>} Number of deleted orphan sample rows.
607
+ *
608
+ * @example
609
+ * const removed = await storage.pruneOrphanedSamples();
610
+ */
611
+ async pruneOrphanedSamples(expectedLifecycleToken) {
612
+ if (expectedLifecycleToken !== undefined && expectedLifecycleToken !== this.lifecycleToken) {
613
+ return 0;
614
+ }
615
+ if (!this.isDuckDbParquetEnabled() || !this.connection) {
616
+ return 0;
617
+ }
618
+ const whereClause = `
619
+ NOT EXISTS (
620
+ SELECT 1
621
+ FROM history_series AS hs
622
+ WHERE hs.series_id = history_samples.series_id
623
+ )
624
+ `;
625
+ let removedRows = 0;
626
+ while (true) {
627
+ const batch = await this.querySql(`
628
+ SELECT rowid
629
+ FROM history_samples
630
+ WHERE ${whereClause}
631
+ LIMIT ${DuckDbParquetStorageService.PRUNE_BATCH_SIZE}
632
+ `);
633
+ if (batch.length === 0) {
634
+ break;
635
+ }
636
+ const rowIds = batch.map(row => Math.trunc(Number(row.rowid))).filter(Number.isFinite);
637
+ if (rowIds.length === 0) {
638
+ break;
639
+ }
640
+ await this.runSql(`
641
+ DELETE FROM history_samples
642
+ WHERE rowid IN (${rowIds.join(', ')})
643
+ `);
644
+ removedRows += rowIds.length;
645
+ if (rowIds.length < DuckDbParquetStorageService.PRUNE_BATCH_SIZE) {
646
+ break;
647
+ }
648
+ }
649
+ return removedRows;
650
+ }
651
+ /**
652
+ * Lists known history paths from persisted samples.
653
+ *
654
+ * @returns {Promise<string[]>} Ordered path names.
655
+ *
656
+ * @example
657
+ * const paths = await storage.getStoredPaths();
658
+ */
659
+ async getStoredPaths(query) {
660
+ if (!this.isDuckDbParquetEnabled() || !this.connection) {
661
+ return [];
662
+ }
663
+ const nowMs = Date.now();
664
+ const range = this.resolveRange(nowMs, query?.from, query?.to, query?.duration);
665
+ const rows = await this.querySql(`
666
+ SELECT DISTINCT path AS value
667
+ FROM history_samples
668
+ WHERE path IS NOT NULL
669
+ AND ts_ms >= ${Math.trunc(range.fromMs)}
670
+ AND ts_ms <= ${Math.trunc(range.toMs)}
671
+ ORDER BY value ASC
672
+ `);
673
+ return rows.map(row => row.value).filter(Boolean);
674
+ }
675
+ /**
676
+ * Lists known history contexts from persisted samples.
677
+ *
678
+ * @returns {Promise<string[]>} Ordered context names.
679
+ *
680
+ * @example
681
+ * const contexts = await storage.getStoredContexts();
682
+ */
683
+ async getStoredContexts(query) {
684
+ if (!this.isDuckDbParquetEnabled() || !this.connection) {
685
+ return [];
686
+ }
687
+ const nowMs = Date.now();
688
+ const range = this.resolveRange(nowMs, query?.from, query?.to, query?.duration);
689
+ const rows = await this.querySql(`
690
+ SELECT DISTINCT context AS value
691
+ FROM history_samples
692
+ WHERE context IS NOT NULL
693
+ AND ts_ms >= ${Math.trunc(range.fromMs)}
694
+ AND ts_ms <= ${Math.trunc(range.toMs)}
695
+ ORDER BY value ASC
696
+ `);
697
+ return rows.map(row => row.value).filter(Boolean);
698
+ }
699
+ /**
700
+ * Queries history values directly from DuckDB in History API-compatible shape.
701
+ *
702
+ * @param {IHistoryQueryParams} query Incoming history values query parameters.
703
+ * @returns {Promise<IHistoryValuesResponse | null>} History payload when DuckDB is ready, otherwise null.
704
+ *
705
+ * @example
706
+ * const result = await storage.getValues({ paths: 'navigation.speedOverGround:avg', duration: 'PT1H' });
707
+ */
708
+ async getValues(query) {
709
+ if (!this.isDuckDbParquetEnabled() || !this.connection) {
710
+ return null;
711
+ }
712
+ const nowMs = Date.now();
713
+ const requested = this.parseRequestedPaths(query.paths);
714
+ if (requested.length === 0) {
715
+ return null;
716
+ }
717
+ const range = this.resolveRange(nowMs, query.from, query.to, query.duration);
718
+ const context = query.context ?? 'vessels.self';
719
+ const resolutionMs = this.resolveResolutionMs(query.resolution);
720
+ const uniquePaths = Array.from(new Set(requested.map(item => item.path)));
721
+ const rowsByPath = await this.selectRowsForPaths(uniquePaths, context, range.fromMs, range.toMs);
722
+ const timestampRows = new Map();
723
+ for (let index = 0; index < requested.length; index += 1) {
724
+ const item = requested[index];
725
+ const rows = rowsByPath.get(item.path) ?? [];
726
+ const transformed = this.applyMethod(item, rows);
727
+ const merged = this.downsampleIfNeeded(transformed, resolutionMs, item.method ?? 'avg');
728
+ merged.forEach(entry => {
729
+ const row = timestampRows.get(entry.timestamp) ?? Array.from({ length: requested.length }, () => null);
730
+ row[index] = entry.value;
731
+ timestampRows.set(entry.timestamp, row);
732
+ });
733
+ }
734
+ const data = Array.from(timestampRows.entries())
735
+ .sort((left, right) => left[0] - right[0])
736
+ .map(([timestamp, values]) => [new Date(timestamp).toISOString(), ...values]);
737
+ return {
738
+ context,
739
+ range: {
740
+ from: new Date(range.fromMs).toISOString(),
741
+ to: new Date(range.toMs).toISOString()
742
+ },
743
+ values: requested.map(item => ({
744
+ path: item.path,
745
+ method: item.method ?? 'avg'
746
+ })),
747
+ data
748
+ };
749
+ }
750
+ /**
751
+ * Closes open storage resources.
752
+ *
753
+ * @returns {Promise<void>}
754
+ *
755
+ * @example
756
+ * await storage.close();
757
+ */
758
+ async close(expectedLifecycleToken) {
759
+ if (expectedLifecycleToken !== undefined && expectedLifecycleToken !== this.lifecycleToken) {
760
+ return;
761
+ }
762
+ this.initialized = false;
763
+ this.stopPruneJob();
764
+ this.stopStaleSeriesCleanupJob();
765
+ if (!this.connection) {
766
+ this.db = null;
767
+ return;
768
+ }
769
+ const connection = this.connection;
770
+ const db = this.db;
771
+ this.connection = null;
772
+ try {
773
+ connection.disconnectSync();
774
+ }
775
+ catch {
776
+ // ignore disconnect failures during shutdown
777
+ }
778
+ try {
779
+ db?.closeSync();
780
+ }
781
+ catch {
782
+ // ignore close failures during shutdown
783
+ }
784
+ this.db = null;
785
+ }
786
+ async createCoreTables() {
787
+ await this.runSql(`
788
+ CREATE TABLE IF NOT EXISTS history_samples (
789
+ series_id VARCHAR,
790
+ dataset_uuid VARCHAR,
791
+ owner_widget_uuid VARCHAR,
792
+ path VARCHAR,
793
+ context VARCHAR,
794
+ source VARCHAR,
795
+ ts_ms BIGINT,
796
+ value DOUBLE
797
+ )
798
+ `);
799
+ await this.runSql(`
800
+ CREATE TABLE IF NOT EXISTS history_series (
801
+ series_id VARCHAR NOT NULL,
802
+ dataset_uuid VARCHAR NOT NULL,
803
+ owner_widget_uuid VARCHAR NOT NULL,
804
+ owner_widget_selector VARCHAR,
805
+ path VARCHAR NOT NULL,
806
+ source VARCHAR,
807
+ context VARCHAR,
808
+ time_scale VARCHAR,
809
+ period INTEGER,
810
+ retention_duration_ms BIGINT,
811
+ sample_time INTEGER,
812
+ enabled BOOLEAN,
813
+ methods_json VARCHAR,
814
+ reconcile_ts BIGINT,
815
+ PRIMARY KEY (series_id)
816
+ )
817
+ `);
818
+ }
819
+ async insertRows(rows) {
820
+ if (rows.length === 0) {
821
+ return;
822
+ }
823
+ const valuesSql = rows
824
+ .map(sample => `(${this.escape(sample.seriesId)}, ${this.escape(sample.datasetUuid)}, ${this.escape(sample.ownerWidgetUuid)}, ${this.escape(sample.path)}, ${this.escape(sample.context)}, ${this.escape(sample.source)}, ${Math.trunc(sample.timestamp)}, ${Number(sample.value)})`)
825
+ .join(',\n');
826
+ const sql = `
827
+ INSERT INTO history_samples (
828
+ series_id,
829
+ dataset_uuid,
830
+ owner_widget_uuid,
831
+ path,
832
+ context,
833
+ source,
834
+ ts_ms,
835
+ value
836
+ ) VALUES ${valuesSql}
837
+ `;
838
+ await this.runSql(sql);
839
+ }
840
+ async exportSeriesRange(seriesId, fromMs, toMs) {
841
+ const baseDir = (0, path_1.resolve)(this.config.parquetDirectory);
842
+ const seriesDir = (0, path_1.join)(baseDir, this.safePath(seriesId));
843
+ (0, fs_1.mkdirSync)(seriesDir, { recursive: true });
844
+ const filePath = (0, path_1.join)(seriesDir, `${fromMs}-${toMs}.parquet`);
845
+ const rows = await this.querySql(`
846
+ SELECT
847
+ series_id,
848
+ dataset_uuid,
849
+ owner_widget_uuid,
850
+ path,
851
+ context,
852
+ source,
853
+ ts_ms,
854
+ value
855
+ FROM history_samples
856
+ WHERE series_id = ${this.escape(seriesId)}
857
+ AND ts_ms >= ${Math.trunc(fromMs)}
858
+ AND ts_ms <= ${Math.trunc(toMs)}
859
+ ORDER BY ts_ms
860
+ `);
861
+ if (rows.length === 0) {
862
+ return;
863
+ }
864
+ const schema = new parquetjs_1.ParquetSchema({
865
+ series_id: { type: 'UTF8' },
866
+ dataset_uuid: { type: 'UTF8' },
867
+ owner_widget_uuid: { type: 'UTF8' },
868
+ path: { type: 'UTF8' },
869
+ context: { type: 'UTF8' },
870
+ source: { type: 'UTF8', optional: true },
871
+ ts_ms: { type: 'INT64' },
872
+ ts: { type: 'TIMESTAMP_MILLIS' },
873
+ value: { type: 'DOUBLE' }
874
+ });
875
+ const writer = await parquetjs_1.ParquetWriter.openFile(schema, filePath);
876
+ try {
877
+ for (const row of rows) {
878
+ const timestampMs = this.toNumberOrUndefined(row.ts_ms);
879
+ const numericValue = this.toNumberOrUndefined(row.value);
880
+ if (timestampMs === undefined || numericValue === undefined) {
881
+ continue;
882
+ }
883
+ await writer.appendRow({
884
+ series_id: row.series_id,
885
+ dataset_uuid: row.dataset_uuid,
886
+ owner_widget_uuid: row.owner_widget_uuid,
887
+ path: row.path,
888
+ context: row.context,
889
+ source: row.source ?? undefined,
890
+ ts_ms: Math.trunc(timestampMs),
891
+ ts: new Date(timestampMs),
892
+ value: numericValue
893
+ });
894
+ }
895
+ }
896
+ finally {
897
+ await writer.close();
898
+ }
899
+ }
900
+ async runSql(sql) {
901
+ if (!this.connection) {
902
+ throw new Error('DuckDB connection is not initialized');
903
+ }
904
+ await this.connection.run(sql);
905
+ }
906
+ async querySql(sql) {
907
+ if (!this.connection) {
908
+ throw new Error('DuckDB connection is not initialized');
909
+ }
910
+ const result = await this.connection.runAndReadAll(sql);
911
+ return result.getRowObjectsJson();
912
+ }
913
+ async selectRowsForPaths(paths, context, fromMs, toMs) {
914
+ const rowsByPath = new Map();
915
+ if (paths.length === 0) {
916
+ return rowsByPath;
917
+ }
918
+ const pathFilter = paths.map(path => this.escape(path)).join(', ');
919
+ const sql = `
920
+ SELECT path, ts_ms, value
921
+ FROM history_samples
922
+ WHERE context = ${this.escape(context)}
923
+ AND path IN (${pathFilter})
924
+ AND ts_ms >= ${Math.trunc(fromMs)}
925
+ AND ts_ms <= ${Math.trunc(toMs)}
926
+ ORDER BY path ASC, ts_ms ASC
927
+ `;
928
+ const rows = await this.querySql(sql);
929
+ rows.forEach(row => {
930
+ const list = rowsByPath.get(row.path) ?? [];
931
+ list.push({ ts_ms: Number(row.ts_ms), value: Number(row.value) });
932
+ rowsByPath.set(row.path, list);
933
+ });
934
+ return rowsByPath;
935
+ }
936
+ parseRequestedPaths(paths) {
937
+ return String(paths)
938
+ .split(',')
939
+ .map(item => item.trim())
940
+ .filter(Boolean)
941
+ .map(raw => {
942
+ const [pathToken, maybeMethod, maybePeriod] = raw.split(':');
943
+ const path = this.normalizePathIdentifier(pathToken);
944
+ const method = this.parseMethod(maybeMethod);
945
+ const parsedPeriod = maybePeriod !== undefined ? Number(maybePeriod) : undefined;
946
+ return {
947
+ path,
948
+ method,
949
+ period: Number.isFinite(parsedPeriod) ? parsedPeriod : undefined
950
+ };
951
+ });
952
+ }
953
+ parseMethod(value) {
954
+ if (!value)
955
+ return undefined;
956
+ const normalized = value.toLowerCase();
957
+ if (normalized === 'min' || normalized === 'max' || normalized === 'avg' || normalized === 'sma' || normalized === 'ema') {
958
+ return normalized;
959
+ }
960
+ return undefined;
961
+ }
962
+ normalizePathIdentifier(path) {
963
+ const trimmed = String(path).trim();
964
+ if (!trimmed) {
965
+ return '';
966
+ }
967
+ if (trimmed.startsWith('vessels.self.')) {
968
+ return trimmed.slice('vessels.self.'.length);
969
+ }
970
+ if (trimmed.startsWith('self.')) {
971
+ return trimmed.slice('self.'.length);
972
+ }
973
+ return trimmed;
974
+ }
975
+ resolveRange(nowMs, from, to, duration) {
976
+ const toMs = to ? Date.parse(to) : nowMs;
977
+ if (!Number.isFinite(toMs)) {
978
+ throw new Error('Invalid to date-time. Expected an ISO 8601 date-time string.');
979
+ }
980
+ const fromMs = from ? Date.parse(from) : toMs - this.parseDurationMs(duration);
981
+ if (!Number.isFinite(fromMs)) {
982
+ throw new Error('Invalid from date-time. Expected an ISO 8601 date-time string.');
983
+ }
984
+ return { fromMs, toMs };
985
+ }
986
+ parseDurationMs(duration) {
987
+ if (duration === undefined || duration === null) {
988
+ return 60 * 60_000;
989
+ }
990
+ if (typeof duration === 'number' && Number.isFinite(duration) && duration > 0) {
991
+ return duration;
992
+ }
993
+ if (typeof duration === 'number') {
994
+ throw new Error('Invalid duration. Expected a positive number of milliseconds or an ISO 8601 duration (e.g. PT10M).');
995
+ }
996
+ const value = String(duration).trim();
997
+ if (/^\d+(\.\d+)?$/.test(value)) {
998
+ const parsedMs = Number(value);
999
+ if (Number.isFinite(parsedMs) && parsedMs > 0) {
1000
+ return parsedMs;
1001
+ }
1002
+ throw new Error('Invalid duration. Expected a positive number of milliseconds or an ISO 8601 duration (e.g. PT10M).');
1003
+ }
1004
+ const iso = /^PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?$/i.exec(value);
1005
+ if (!iso) {
1006
+ throw new Error('Invalid duration. Expected a positive number of milliseconds or an ISO 8601 duration (e.g. PT10M).');
1007
+ }
1008
+ const hours = Number(iso[1] || 0);
1009
+ const minutes = Number(iso[2] || 0);
1010
+ const seconds = Number(iso[3] || 0);
1011
+ const totalMs = (((hours * 60) + minutes) * 60 + seconds) * 1000;
1012
+ if (totalMs <= 0) {
1013
+ throw new Error('Invalid duration. Expected a positive number of milliseconds or an ISO 8601 duration (e.g. PT10M).');
1014
+ }
1015
+ return totalMs;
1016
+ }
1017
+ resolveResolutionMs(resolution) {
1018
+ if (resolution === undefined || resolution === null) {
1019
+ return 0;
1020
+ }
1021
+ if (typeof resolution === 'number') {
1022
+ if (!Number.isFinite(resolution) || resolution <= 0) {
1023
+ throw new Error('Invalid resolution. Expected a positive number of seconds or an ISO 8601 duration (e.g. PT10S).');
1024
+ }
1025
+ return Math.max(1, Math.trunc(resolution * 1000));
1026
+ }
1027
+ const value = String(resolution).trim();
1028
+ if (!value) {
1029
+ throw new Error('Invalid resolution. Expected a positive number of seconds or an ISO 8601 duration (e.g. PT10S).');
1030
+ }
1031
+ if (/^\d+(\.\d+)?$/.test(value)) {
1032
+ const parsedSeconds = Number(value);
1033
+ if (!Number.isFinite(parsedSeconds) || parsedSeconds <= 0) {
1034
+ throw new Error('Invalid resolution. Expected a positive number of seconds or an ISO 8601 duration (e.g. PT10S).');
1035
+ }
1036
+ return Math.max(1, Math.trunc(parsedSeconds * 1000));
1037
+ }
1038
+ try {
1039
+ return this.parseDurationMs(value);
1040
+ }
1041
+ catch {
1042
+ throw new Error('Invalid resolution. Expected a positive number of seconds or an ISO 8601 duration (e.g. PT10S).');
1043
+ }
1044
+ }
1045
+ applyMethod(request, rows) {
1046
+ if (rows.length === 0)
1047
+ return [];
1048
+ const method = request.method ?? 'avg';
1049
+ if (method === 'min' || method === 'max' || method === 'avg') {
1050
+ return rows.map(entry => ({ timestamp: Number(entry.ts_ms), value: Number(entry.value) }));
1051
+ }
1052
+ if (method === 'sma') {
1053
+ const period = Math.max(1, request.period ?? 5);
1054
+ return rows.map((entry, index) => {
1055
+ const start = Math.max(0, index - period + 1);
1056
+ const window = rows.slice(start, index + 1);
1057
+ const sum = window.reduce((acc, item) => acc + Number(item.value), 0);
1058
+ return {
1059
+ timestamp: Number(entry.ts_ms),
1060
+ value: sum / window.length
1061
+ };
1062
+ });
1063
+ }
1064
+ const period = Math.max(1, request.period ?? 5);
1065
+ const multiplier = 2 / (period + 1);
1066
+ let previous = null;
1067
+ return rows.map(entry => {
1068
+ const value = Number(entry.value);
1069
+ if (previous === null) {
1070
+ previous = value;
1071
+ }
1072
+ else {
1073
+ previous = ((value - previous) * multiplier) + previous;
1074
+ }
1075
+ return {
1076
+ timestamp: Number(entry.ts_ms),
1077
+ value: previous
1078
+ };
1079
+ });
1080
+ }
1081
+ downsampleIfNeeded(values, resolutionMs, method) {
1082
+ if (resolutionMs <= 0 || values.length === 0) {
1083
+ return values;
1084
+ }
1085
+ const buckets = new Map();
1086
+ values.forEach(entry => {
1087
+ if (!Number.isFinite(entry.value)) {
1088
+ return;
1089
+ }
1090
+ const bucket = Math.floor(entry.timestamp / resolutionMs) * resolutionMs;
1091
+ const list = buckets.get(bucket) ?? [];
1092
+ list.push(entry.value);
1093
+ buckets.set(bucket, list);
1094
+ });
1095
+ return Array.from(buckets.entries())
1096
+ .sort((left, right) => left[0] - right[0])
1097
+ .map(([timestamp, list]) => {
1098
+ const value = this.aggregateBucket(list, method);
1099
+ return {
1100
+ timestamp,
1101
+ value
1102
+ };
1103
+ });
1104
+ }
1105
+ aggregateBucket(values, method) {
1106
+ if (values.length === 0) {
1107
+ return null;
1108
+ }
1109
+ if (method === 'min') {
1110
+ return Math.min(...values);
1111
+ }
1112
+ if (method === 'max') {
1113
+ return Math.max(...values);
1114
+ }
1115
+ const sum = values.reduce((acc, value) => acc + value, 0);
1116
+ return sum / values.length;
1117
+ }
1118
+ safePath(value) {
1119
+ return value.replace(/[^a-zA-Z0-9._-]/g, '_');
1120
+ }
1121
+ escape(value) {
1122
+ return `'${String(value).replace(/'/g, "''")}'`;
1123
+ }
1124
+ nullableString(value) {
1125
+ if (value === undefined || value === null || value === '') {
1126
+ return 'NULL';
1127
+ }
1128
+ return this.escape(value);
1129
+ }
1130
+ nullableNumber(value) {
1131
+ if (value === undefined || value === null || !Number.isFinite(value)) {
1132
+ return 'NULL';
1133
+ }
1134
+ return String(Math.trunc(value));
1135
+ }
1136
+ parseMethods(value) {
1137
+ if (!value)
1138
+ return undefined;
1139
+ try {
1140
+ const parsed = JSON.parse(value);
1141
+ if (!Array.isArray(parsed))
1142
+ return undefined;
1143
+ const methods = parsed.filter(entry => entry === 'min' || entry === 'max' || entry === 'avg' || entry === 'sma' || entry === 'ema');
1144
+ return methods.length > 0 ? methods : undefined;
1145
+ }
1146
+ catch {
1147
+ return undefined;
1148
+ }
1149
+ }
1150
+ toNumberOrUndefined(value) {
1151
+ if (value === undefined || value === null) {
1152
+ return undefined;
1153
+ }
1154
+ if (typeof value === 'bigint') {
1155
+ return Number(value);
1156
+ }
1157
+ const parsed = Number(value);
1158
+ return Number.isFinite(parsed) ? parsed : undefined;
1159
+ }
1160
+ toBoolean(value) {
1161
+ if (typeof value === 'boolean') {
1162
+ return value;
1163
+ }
1164
+ if (typeof value === 'bigint') {
1165
+ return value !== 0n;
1166
+ }
1167
+ if (typeof value === 'number') {
1168
+ return value !== 0;
1169
+ }
1170
+ if (typeof value === 'string') {
1171
+ const normalized = value.trim().toLowerCase();
1172
+ if (normalized === 'true' || normalized === '1') {
1173
+ return true;
1174
+ }
1175
+ if (normalized === 'false' || normalized === '0') {
1176
+ return false;
1177
+ }
1178
+ }
1179
+ return Boolean(value);
1180
+ }
1181
+ }
1182
+ exports.DuckDbParquetStorageService = DuckDbParquetStorageService;