@timecho/node-red-node-iotdb 0.0.0-stage → 0.0.2

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.
@@ -0,0 +1,113 @@
1
+ 'use strict';
2
+ const { Worker } = require('node:worker_threads');
3
+ const path = require('node:path');
4
+ const { IotdbError } = require('./errors');
5
+ const { statementMode } = require('./values');
6
+
7
+ class SqlClient {
8
+ constructor(config, options = {}) {
9
+ this.config = config;
10
+ this.workerFactory = options.workerFactory || (config => new Worker(path.join(__dirname, 'sql-worker.js'), {
11
+ workerData: config, stdout: true, stderr: true,
12
+ env: { ...process.env, LOG_LEVEL: 'ERROR' },
13
+ resourceLimits: { maxOldGenerationSizeMb: 128 },
14
+ }));
15
+ this.closed = false;
16
+ this.worker = null;
17
+ this.queue = [];
18
+ this.active = false;
19
+ this.sequence = 0;
20
+ this.pending = new Map();
21
+ }
22
+
23
+ execute(sql, options = {}) {
24
+ if (this.closed) return Promise.reject(new IotdbError('CLOSED', 'Database configuration is closing'));
25
+ if (this.queue.length + Number(this.active) >= this.config.maxQueue) return Promise.reject(new IotdbError('QUEUE_FULL', 'Database request queue is full'));
26
+ let mode;
27
+ try { mode = statementMode(sql, options.mode || 'auto'); } catch (err) { return Promise.reject(err); }
28
+ return new Promise((resolve, reject) => {
29
+ this.queue.push({ sql, mode, maxRows: options.maxRows || 10000, maxBytes: options.maxBytes || 8388608,
30
+ timeoutMs: this.config.timeoutMs, expires: Date.now() + this.config.timeoutMs, resolve, reject });
31
+ this.drain();
32
+ });
33
+ }
34
+
35
+ async start() {
36
+ if (this.worker) return;
37
+ if (this.closed) throw new IotdbError('CLOSED', 'Database configuration is closing');
38
+ const worker = this.workerFactory(this.config);
39
+ this.worker = worker;
40
+ // SDK logging may contain SQL/server messages. Do not forward raw logs.
41
+ worker.stdout?.resume();
42
+ worker.stderr?.resume();
43
+ await new Promise((resolve, reject) => {
44
+ const timer = setTimeout(() => reject(new IotdbError('CONNECT_TIMEOUT', 'Database connection timed out', true)), this.config.connectTimeoutMs);
45
+ const finish = (err) => { clearTimeout(timer); err ? reject(err) : resolve(); };
46
+ worker.on('message', message => {
47
+ if (message.ready) return finish();
48
+ if (message.startupError) return finish(new IotdbError('CONNECT_FAILED', message.startupError.message));
49
+ const waiting = this.pending.get(message.id);
50
+ if (!waiting) return;
51
+ this.pending.delete(message.id);
52
+ clearTimeout(waiting.timer);
53
+ message.error ? waiting.reject(new IotdbError(message.error.code, message.error.message)) : waiting.resolve(message.result);
54
+ });
55
+ worker.on('error', error => { finish(error); this.failPending(new IotdbError('WORKER_ERROR', 'Database worker failed', true)); });
56
+ worker.on('exit', () => { finish(new IotdbError('WORKER_EXIT', 'Database worker stopped', true)); this.failPending(new IotdbError('WORKER_EXIT', 'Database worker stopped', true)); if (this.worker === worker) this.worker = null; });
57
+ });
58
+ }
59
+
60
+ request(job, timeoutMs) {
61
+ const id = ++this.sequence;
62
+ return new Promise((resolve, reject) => {
63
+ const timer = setTimeout(() => {
64
+ this.pending.delete(id);
65
+ reject(new IotdbError('REQUEST_TIMEOUT', 'Database request timed out; a write may have completed. It was not retried.', true));
66
+ }, timeoutMs);
67
+ this.pending.set(id, { resolve, reject, timer });
68
+ this.worker.postMessage({ ...job, resolve: undefined, reject: undefined, id });
69
+ });
70
+ }
71
+
72
+ async drain() {
73
+ if (this.active || this.closed) return;
74
+ this.active = true;
75
+ while (this.queue.length && !this.closed) {
76
+ const job = this.queue.shift();
77
+ try {
78
+ if (job.expires <= Date.now()) throw new IotdbError('QUEUE_TIMEOUT', 'Database request expired before execution');
79
+ await this.start();
80
+ if (this.closed) throw new IotdbError('CLOSED', 'Database configuration is closing');
81
+ job.resolve(await this.request(job, job.timeoutMs));
82
+ } catch (error) {
83
+ await this.stopWorker();
84
+ job.reject(error);
85
+ }
86
+ }
87
+ this.active = false;
88
+ }
89
+
90
+ failPending(error) {
91
+ for (const pending of this.pending.values()) { clearTimeout(pending.timer); pending.reject(error); }
92
+ this.pending.clear();
93
+ }
94
+
95
+ async stopWorker() {
96
+ const worker = this.worker;
97
+ this.worker = null;
98
+ this.failPending(new IotdbError('CLOSED', 'Database connection closed'));
99
+ if (worker) await worker.terminate();
100
+ }
101
+
102
+ async close() {
103
+ if (this.closed) return;
104
+ this.closed = true;
105
+ for (const job of this.queue.splice(0)) job.reject(new IotdbError('CLOSED', 'Database configuration is closing'));
106
+ if (this.worker && !this.active) {
107
+ try { await this.request({ action: 'close' }, 2000); } catch { /* terminate below */ }
108
+ }
109
+ await this.stopWorker();
110
+ }
111
+ }
112
+
113
+ module.exports = { SqlClient };
@@ -0,0 +1,68 @@
1
+ 'use strict';
2
+ // A worker owns its SDK connection. Terminating a timed-out worker also closes
3
+ // its sockets, without touching connections belonging to another config node.
4
+ const { parentPort, workerData } = require('node:worker_threads');
5
+ const { Session, TableSession } = require('@iotdb/client');
6
+ const { datasetShape, readRow, installBinaryCompatibility } = require('./sdk-compat');
7
+ const { IotdbError, safeError } = require('./errors');
8
+
9
+ const config = workerData;
10
+ const SessionType = config.model === 'table' ? TableSession : Session;
11
+ const session = new SessionType({
12
+ host: config.host, port: config.port,
13
+ username: config.username, password: config.password,
14
+ // This dialect option is used by the pinned official SDK's TableSessionPool.
15
+ sqlDialect: config.model, timezone: config.timezone || 'UTC', fetchSize: 512,
16
+ enableSSL: config.tls === true,
17
+ sslOptions: config.tls ? { rejectUnauthorized: true, ...(config.ca ? { ca: Buffer.from(config.ca) } : {}) } : undefined,
18
+ });
19
+ installBinaryCompatibility(session);
20
+
21
+ async function execute(job) {
22
+ if (job.mode === 'execute') {
23
+ await session.executeNonQueryStatement(job.sql);
24
+ return { payload: { success: true }, metadata: { operation: 'execute', model: config.model } };
25
+ }
26
+ const dataset = await session.executeQueryStatement(job.sql, job.timeoutMs);
27
+ try {
28
+ const shape = datasetShape(dataset);
29
+ const rows = [];
30
+ let bytes = 2;
31
+ while (await dataset.hasNext()) {
32
+ if (rows.length >= job.maxRows) throw new IotdbError('RESULT_LIMIT', `Query exceeds ${job.maxRows} rows; add a time predicate and LIMIT`);
33
+ const row = readRow(dataset, shape);
34
+ bytes += Buffer.byteLength(JSON.stringify(row)) + 1;
35
+ if (bytes > job.maxBytes) throw new IotdbError('RESULT_LIMIT', `Query exceeds ${job.maxBytes} bytes; narrow the query`);
36
+ rows.push(row);
37
+ }
38
+ return { payload: rows, metadata: { operation: 'query', model: config.model, columns: shape.outputColumns, rowCount: rows.length } };
39
+ } finally {
40
+ await dataset.close();
41
+ }
42
+ }
43
+
44
+ parentPort.on('message', async job => {
45
+ try {
46
+ if (job.action === 'close') {
47
+ await session.close();
48
+ parentPort.postMessage({ id: job.id, result: true });
49
+ parentPort.close();
50
+ } else {
51
+ parentPort.postMessage({ id: job.id, result: await execute(job) });
52
+ }
53
+ } catch (error) {
54
+ const safe = safeError(error, [config.password, job.sql]);
55
+ parentPort.postMessage({ id: job.id, error: { code: safe.code, message: safe.message } });
56
+ }
57
+ });
58
+
59
+ (async () => {
60
+ await session.open();
61
+ if (config.model === 'table' && config.database) {
62
+ await session.executeNonQueryStatement(`USE "${config.database.replace(/"/g, '""')}"`);
63
+ }
64
+ parentPort.postMessage({ ready: true });
65
+ })().catch(error => {
66
+ const safe = safeError(error, [config.password]);
67
+ parentPort.postMessage({ startupError: { code: safe.code, message: safe.message } });
68
+ });
@@ -0,0 +1,47 @@
1
+ 'use strict';
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const { createHash } = require('node:crypto');
5
+ const { IotdbError } = require('./errors');
6
+
7
+ // A durable, conservative restart interlock. Until recovery is certified for
8
+ // this server, a process/redeploy must not silently start the group at the tail.
9
+ // This is NOT an offset checkpoint or a promise of durable message delivery.
10
+ class SubscriptionState {
11
+ constructor(config) {
12
+ if (!config.stateDir || !path.isAbsolute(config.stateDir)) {
13
+ throw new IotdbError('STATE_DIR_REQUIRED', 'Subscription requires a persistent absolute state directory');
14
+ }
15
+ this.identity = { host: config.host, port: config.port, model: config.model,
16
+ topic: config.topic, groupId: config.groupId };
17
+ const key = createHash('sha256').update(JSON.stringify(this.identity)).digest('hex');
18
+ this.directory = config.stateDir;
19
+ this.file = path.join(this.directory, `${key}.json`);
20
+ this.consumerId = config.consumerId;
21
+ }
22
+
23
+ begin() {
24
+ let handle;
25
+ try {
26
+ fs.mkdirSync(this.directory, { recursive: true, mode: 0o700 });
27
+ handle = fs.openSync(this.file, 'wx', 0o600);
28
+ fs.writeFileSync(handle, JSON.stringify({ version: 1, identity: this.identity,
29
+ consumerId: this.consumerId, attemptedAt: new Date().toISOString(),
30
+ state: 'recovery-required-on-restart' }) + '\n');
31
+ fs.fsyncSync(handle);
32
+ fs.closeSync(handle); handle = undefined;
33
+ // Linux production target: persist the directory entry before network IO.
34
+ if (process.platform !== 'win32') {
35
+ const directory = fs.openSync(this.directory, 'r');
36
+ try { fs.fsyncSync(directory); } finally { fs.closeSync(directory); }
37
+ }
38
+ } catch (error) {
39
+ if (handle !== undefined) fs.closeSync(handle);
40
+ if (error.code === 'EEXIST') throw new IotdbError('RECOVERY_REQUIRED',
41
+ 'This topic/group has an earlier subscription attempt. Server close or inactivity can remove its progress. Reconcile and replay the data before explicitly starting a new subscription. See the recovery runbook.');
42
+ throw new IotdbError('STATE_WRITE_FAILED', 'Cannot persist subscription restart state; no subscription was started');
43
+ }
44
+ }
45
+ }
46
+
47
+ module.exports = { SubscriptionState };
package/lib/values.js ADDED
@@ -0,0 +1,43 @@
1
+ 'use strict';
2
+ const { IotdbError } = require('./errors');
3
+
4
+ function valueToJson(value, type) {
5
+ if (value === null || value === undefined) return null;
6
+ if (typeof value === 'bigint') return value.toString();
7
+ if (type === 'INT64' || type === 'TIMESTAMP') {
8
+ if (typeof value === 'number' && !Number.isSafeInteger(value)) {
9
+ throw new IotdbError('UNSAFE_INTEGER', 'The SDK returned an unsafe INT64/timestamp; refusing to emit a rounded result');
10
+ }
11
+ return String(value);
12
+ }
13
+ if (Buffer.isBuffer(value)) return `0x${value.toString('hex')}`;
14
+ if (type === 'BLOB') throw new IotdbError('SDK_INCOMPATIBLE', 'SDK did not preserve BLOB bytes; refusing a corrupted result');
15
+ if (typeof value === 'number' && !Number.isFinite(value)) return String(value);
16
+ if (value instanceof Date) return type === 'DATE' ? value.toISOString().slice(0, 10) : value.toISOString();
17
+ return value;
18
+ }
19
+
20
+ function uniqueColumns(names, types) {
21
+ const used = new Set();
22
+ return names.map((name, i) => {
23
+ let key = String(name);
24
+ let suffix = 2;
25
+ while (used.has(key)) key = `${name}#${suffix++}`;
26
+ used.add(key);
27
+ return { name, key, type: types[i] || 'UNKNOWN' };
28
+ });
29
+ }
30
+
31
+ function statementMode(sql, mode) {
32
+ if (typeof sql !== 'string' || !sql.trim() || Buffer.byteLength(sql) > 1024 * 1024) {
33
+ throw new IotdbError('INVALID_SQL', 'SQL must be a non-empty string of at most 1 MiB');
34
+ }
35
+ const leading = sql.replace(/^(?:\s|--[^\r\n]*(?:\r?\n|$)|\/\*[\s\S]*?\*\/)+/, '');
36
+ if (/^(?:USE\b|SET(?:\s|\/\*[\s\S]*?\*\/|--[^\r\n]*(?:\r?\n|$))+SQL_DIALECT\b)/i.test(leading)) {
37
+ throw new IotdbError('SESSION_STATE', 'Set the model/database in the server configuration; USE and SET SQL_DIALECT are not allowed on a shared session');
38
+ }
39
+ if (!['auto', 'query', 'execute'].includes(mode)) throw new IotdbError('INVALID_MODE', 'Mode must be auto, query or execute');
40
+ return mode === 'auto' ? (/^(SELECT|SHOW|LIST|COUNT|EXPLAIN|DESCRIBE|DESC)\b/i.test(leading) ? 'query' : 'execute') : mode;
41
+ }
42
+
43
+ module.exports = { valueToJson, uniqueColumns, statementMode };
@@ -0,0 +1,87 @@
1
+ <script type="text/javascript">
2
+ (function() {
3
+ const positive = function(v) { return Number.isInteger(Number(v)) && Number(v) > 0; };
4
+ RED.nodes.registerType('iotdb-server', {
5
+ category: 'config',
6
+ defaults: {
7
+ name: {value:''}, host:{value:'127.0.0.1',required:true}, port:{value:6667,required:true,validate:positive},
8
+ model:{value:'tree',required:true}, database:{value:''}, timestampPrecision:{value:'ms'},
9
+ timeoutMs:{value:15000,validate:positive}, connectTimeoutMs:{value:10000,validate:positive}, maxQueue:{value:32,validate:positive},
10
+ tls:{value:false}, caFile:{value:''}, javaPath:{value:''}, sdkClasspath:{value:''}
11
+ },
12
+ credentials: {username:{type:'text'},password:{type:'password'}},
13
+ label: function() { return this.name || this.host+':'+this.port+' ('+this.model+')'; },
14
+ oneditprepare: function() {
15
+ const update = function() { $('.iotdb-table-option').toggle($('#node-config-input-model').val()==='table'); $('.iotdb-tls-option').toggle($('#node-config-input-tls').prop('checked')); };
16
+ $('#node-config-input-model, #node-config-input-tls').on('change',update); update();
17
+ }
18
+ });
19
+ RED.nodes.registerType('iotdb-operator', {
20
+ category:'storage', color:'#8ec9d2', defaults:{name:{value:''},server:{value:'',type:'iotdb-server',required:true},mode:{value:'auto'},sql:{value:''},maxRows:{value:10000,validate:positive},maxBytes:{value:8388608,validate:positive}},
21
+ inputs:1,outputs:1,icon:'font-awesome/fa-database',align:'right',label:function(){return this.name || 'IoTDB SQL';}
22
+ });
23
+ RED.nodes.registerType('iotdb-consumer', {
24
+ category:'storage',color:'#8ec9d2',defaults:{name:{value:''},server:{value:'',type:'iotdb-server',required:true},topic:{value:'',required:true},groupId:{value:'',required:true},consumerId:{value:'',required:true},ackMode:{value:'manual'},pollMs:{value:1000,validate:positive},maxInFlight:{value:4,validate:positive},maxRows:{value:10000,validate:positive},maxBytes:{value:8388608,validate:positive}},
25
+ inputs:1,outputs:1,icon:'font-awesome/fa-rss',label:function(){return this.name || 'IoTDB consumer';},inputLabels:'ACK / pause / resume',outputLabels:'subscription records'
26
+ });
27
+ })();
28
+ </script>
29
+
30
+ <script type="text/html" data-template-name="iotdb-server">
31
+ <div class="form-row"><label for="node-config-input-name">Name / 名称</label><input type="text" id="node-config-input-name"></div>
32
+ <div class="form-row"><label for="node-config-input-host">Host / 地址</label><input type="text" id="node-config-input-host"></div>
33
+ <div class="form-row"><label for="node-config-input-port">Port / 端口</label><input type="number" id="node-config-input-port"></div>
34
+ <div class="form-row"><label for="node-config-input-username">User / 用户</label><input type="text" id="node-config-input-username" autocomplete="off"></div>
35
+ <div class="form-row"><label for="node-config-input-password">密码 Password</label><input type="password" id="node-config-input-password" autocomplete="new-password"></div>
36
+ <div class="form-row"><label for="node-config-input-model">Model / 模型</label><select id="node-config-input-model"><option value="tree">Tree / 树模型</option><option value="table">Table / 表模型</option></select></div>
37
+ <div class="form-row iotdb-table-option"><label for="node-config-input-database">Database / 库</label><input type="text" id="node-config-input-database" placeholder="Optional for fully qualified SQL"></div>
38
+ <div class="form-row"><label for="node-config-input-timestampPrecision">Time precision</label><select id="node-config-input-timestampPrecision"><option value="ms">ms / 毫秒</option><option value="us">us / 微秒</option><option value="ns">ns / 纳秒</option></select></div>
39
+ <div class="form-tips">时间精度须与服务端一致;此设置用于消息标注,不改变数据库精度。</div>
40
+ <div class="form-row"><label for="node-config-input-timeoutMs">Request ms</label><input type="number" id="node-config-input-timeoutMs"></div>
41
+ <div class="form-row"><label for="node-config-input-connectTimeoutMs">Connect ms</label><input type="number" id="node-config-input-connectTimeoutMs"></div>
42
+ <div class="form-row"><label for="node-config-input-maxQueue">Queue limit</label><input type="number" id="node-config-input-maxQueue"></div>
43
+ <div class="form-row"><label for="node-config-input-tls">SQL TLS</label><input type="checkbox" id="node-config-input-tls" style="width:auto"></div>
44
+ <div class="form-row iotdb-tls-option"><label for="node-config-input-caFile">CA file</label><input type="text" id="node-config-input-caFile" placeholder="Trusted CA PEM path on the Node-RED host"></div>
45
+ <div class="form-row"><label for="node-config-input-javaPath">Java</label><input type="text" id="node-config-input-javaPath" placeholder="java (subscription only)"></div>
46
+ <div class="form-row"><label for="node-config-input-sdkClasspath">SDK classpath</label><input type="text" id="node-config-input-sdkClasspath" placeholder="IOTDB_SUBSCRIPTION_CLASSPATH environment variable"></div>
47
+ </script>
48
+ <script type="text/html" data-template-name="iotdb-operator">
49
+ <div class="form-row"><label for="node-input-name">Name / 名称</label><input type="text" id="node-input-name"></div>
50
+ <div class="form-row"><label for="node-input-server">Server / 连接</label><input type="text" id="node-input-server"></div>
51
+ <div class="form-row"><label for="node-input-mode">Mode / 操作</label><select id="node-input-mode"><option value="auto">Auto / 自动</option><option value="query">Query / 查询</option><option value="execute">Execute / 写入与管理</option></select></div>
52
+ <div class="form-row"><label for="node-input-sql">SQL</label><textarea id="node-input-sql" rows="5" style="width:70%" placeholder="Leave empty to use msg.topic"></textarea></div>
53
+ <div class="form-row"><label for="node-input-maxRows">Max rows</label><input type="number" id="node-input-maxRows"></div>
54
+ <div class="form-row"><label for="node-input-maxBytes">Max bytes</label><input type="number" id="node-input-maxBytes"></div>
55
+ </script>
56
+ <script type="text/html" data-template-name="iotdb-consumer">
57
+ <div class="form-tips">开发预览:当前 TimechoDB 2.0.12.1 的订阅尚未通过持久恢复验收。断线或重部署后会停止并报告 RECOVERY_REQUIRED,避免自动从新起点跳过数据。暂不用于要求连续可靠交付的生产流程。</div>
58
+ <div class="form-row"><label for="node-input-name">Name / 名称</label><input type="text" id="node-input-name"></div>
59
+ <div class="form-row"><label for="node-input-server">Server / 连接</label><input type="text" id="node-input-server"></div>
60
+ <div class="form-row"><label for="node-input-topic">Topic / 主题</label><input type="text" id="node-input-topic"></div>
61
+ <div class="form-row"><label for="node-input-groupId">Consumer group</label><input type="text" id="node-input-groupId"></div>
62
+ <div class="form-row"><label for="node-input-consumerId">Consumer ID</label><input type="text" id="node-input-consumerId"></div>
63
+ <div class="form-row"><label for="node-input-ackMode">ACK / 确认</label><select id="node-input-ackMode"><option value="manual">Manual / 下游回送 ACK</option><option value="delivery">On delivery / 发送后确认</option></select></div>
64
+ <div class="form-tips">“发送后确认”仅表示消息已交给流程。需要处理成功后确认时,选择手动模式,将原 msg.iotdb.ackToken 回送本节点。</div>
65
+ <div class="form-row"><label for="node-input-pollMs">Poll timeout ms</label><input type="number" id="node-input-pollMs"></div>
66
+ <div class="form-row"><label for="node-input-maxInFlight">Pending batches</label><input type="number" id="node-input-maxInFlight"></div>
67
+ <div class="form-row"><label for="node-input-maxRows">Max batch rows</label><input type="number" id="node-input-maxRows"></div>
68
+ <div class="form-row"><label for="node-input-maxBytes">Max batch bytes</label><input type="number" id="node-input-maxBytes"></div>
69
+ </script>
70
+
71
+ <script type="text/html" data-help-name="iotdb-server">
72
+ <p>Shared Apache IoTDB / TimechoDB connection. Credentials are stored by Node-RED, separately from exported flow configuration. Configure one connection per model/database. The timestamp precision must match the server.</p>
73
+ <p>SQL uses the official Node.js client. Native subscription additionally needs Java 17+ and a matching official Java subscription SDK classpath. Native subscription TLS is not supported by this bridge; use a trusted network or encrypted tunnel. SQL TLS always verifies certificates.</p>
74
+ </script>
75
+ <script type="text/html" data-help-name="iotdb-operator">
76
+ <p>Executes the configured SQL, or <code>msg.topic</code> if the SQL field is empty. Query results replace <code>msg.payload</code> with an array of objects. Non-query success returns <code>{success:true}</code>. Other message fields are preserved.</p>
77
+ <p><code>msg.iotdb</code> includes operation, model, columns and row count. INT64 and timestamps use decimal strings; binary data uses <code>0x</code> hex. Duplicate column names receive #2, #3 suffixes. Row/byte limit violations fail the whole result without silently truncating.</p>
78
+ <p>SQL is executed literally, with no placeholder substitution or automatic write retry. Use explicit query/execute mode for SQL that automatic classification cannot identify. Configure database/model on the server node; shared-session USE/SET SQL_DIALECT are rejected. Route errors to Catch.</p>
79
+ </script>
80
+ <script type="text/html" data-help-name="iotdb-consumer">
81
+ <p>Consumes an existing record-format Topic through the official Java Pull Consumer. Tree/Table support depends on the exact server release and enabled capabilities. TsFile payloads are rejected without acknowledgement.</p>
82
+ <p><code>msg.payload</code> is an array of <code>{source,timestamp,values}</code>. The timestamp and INT64 fields are strings. <code>msg.iotdb</code> carries model, schemas, group, consumer and the opaque <code>ackToken</code>.</p>
83
+ <p>For manual acknowledgement, return the original <code>msg.iotdb.ackToken</code> to this node after all required downstream work succeeds; optionally set <code>msg.iotdb.action="ack"</code>. ACK inputs do not emit another data message. Use Complete to observe ACK completion, Catch for failures. Tokens become invalid after reconnection/redeployment; redelivered data has new tokens.</p>
84
+ <p><code>msg.iotdb.action="pause"</code> stops future polling while retaining the connection and heartbeat. An already-running poll may complete. <code>resume</code> resumes polling within that same live session. Bound pending batches protect memory.</p>
85
+ <p><b>Development preview: durable recovery is not certified.</b> TimechoDB 2.0.12.1 implicitly unsubscribes on consumer close/inactivity. A stable group ID alone does not retain progress. Connection loss stops this node with <code>RECOVERY_REQUIRED</code>; there is no automatic resubscription. A durable marker under the Node-RED user directory prevents a redeploy from silently reusing the group. The marker is not a data backup or offset checkpoint. See the recovery runbook before starting a new subscription.</p>
86
+ <p>Use idempotent downstream operations. Live-session redelivery and manual ACK work, but shutdown continuity is not guaranteed. Unsupported features/configuration stop consumption. One active consumer per topic/group is permitted by the current restart interlock.</p>
87
+ </script>
package/nodes/iotdb.js ADDED
@@ -0,0 +1,123 @@
1
+ 'use strict';
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const { SqlClient } = require('../lib/sql-client');
5
+ const { Consumer } = require('../lib/consumer');
6
+ const { IotdbError, integer, safeError } = require('../lib/errors');
7
+
8
+ module.exports = function (RED) {
9
+ function Server(config) {
10
+ RED.nodes.createNode(this, config);
11
+ this.consumers = new Set();
12
+ this.closed = false;
13
+ try {
14
+ const credentials = this.credentials || {};
15
+ if (!credentials.username || !credentials.password) throw new IotdbError('CREDENTIALS_REQUIRED', 'Set database username and password in the server credentials');
16
+ if (!['tree', 'table'].includes(config.model || 'tree')) throw new IotdbError('INVALID_MODEL', 'Model must be tree or table');
17
+ if (!['ms', 'us', 'ns'].includes(config.timestampPrecision || 'ms')) throw new IotdbError('INVALID_CONFIG', 'Timestamp precision must be ms, us or ns');
18
+ if (!config.host || /[\s\x00]/.test(config.host)) throw new IotdbError('INVALID_HOST', 'Set a valid host name or IP address');
19
+ this.options = {
20
+ host: config.host, port: integer(config.port, 6667, 1, 65535, 'port'),
21
+ username: credentials.username, password: credentials.password,
22
+ model: config.model || 'tree', database: config.database || '',
23
+ timestampPrecision: config.timestampPrecision || 'ms',
24
+ timeoutMs: integer(config.timeoutMs, 15000, 1000, 300000, 'request timeout'),
25
+ connectTimeoutMs: integer(config.connectTimeoutMs, 10000, 1000, 60000, 'connection timeout'),
26
+ maxQueue: integer(config.maxQueue, 32, 1, 1024, 'queue size'),
27
+ tls: config.tls === true, ca: config.tls && config.caFile ? fs.readFileSync(config.caFile) : undefined,
28
+ javaPath: config.javaPath || '', sdkClasspath: config.sdkClasspath || '',
29
+ };
30
+ this.sql = new SqlClient(this.options);
31
+ } catch (error) { this.configError = safeError(error, [this.credentials?.password]); }
32
+ this.on('close', (removed, done) => {
33
+ this.closed = true;
34
+ Promise.allSettled([...this.consumers].map(consumer => consumer.close()).concat(this.sql?.close() || []))
35
+ .then(() => done());
36
+ });
37
+ }
38
+ RED.nodes.registerType('iotdb-server', Server, { credentials: { username: { type: 'text' }, password: { type: 'password' } } });
39
+
40
+ function Operator(config) {
41
+ RED.nodes.createNode(this, config);
42
+ const node = this;
43
+ const server = RED.nodes.getNode(config.server);
44
+ let maxRows, maxBytes, invalid;
45
+ try {
46
+ maxRows = integer(config.maxRows, 10000, 1, 100000, 'maximum rows');
47
+ maxBytes = integer(config.maxBytes, 8388608, 1024, 67108864, 'maximum bytes');
48
+ } catch (err) { invalid = err; }
49
+ let closing = false;
50
+ node.on('input', async (msg, send, done) => {
51
+ send = send || node.send.bind(node);
52
+ done = done || (error => { if (error) node.error(error, msg); });
53
+ try {
54
+ if (closing || server?.closed) throw new IotdbError('CLOSED', 'Node is closing');
55
+ if (!server) throw new IotdbError('SERVER_REQUIRED', 'Select an IoTDB server');
56
+ if (server.configError || invalid) throw server.configError || invalid;
57
+ node.status({ fill: 'blue', shape: 'dot', text: 'executing' });
58
+ const result = await server.sql.execute(config.sql || msg.topic, { mode: config.mode || 'auto', maxRows, maxBytes });
59
+ if (closing) throw new IotdbError('CLOSED', 'Node closed during the request');
60
+ msg.payload = result.payload;
61
+ msg.iotdb = { ...result.metadata, timestampPrecision: server.options.timestampPrecision };
62
+ send(msg);
63
+ node.status({ fill: 'green', shape: 'dot', text: 'ready' });
64
+ done();
65
+ } catch (error) {
66
+ const safe = safeError(error, [server?.options?.password]);
67
+ node.status({ fill: 'red', shape: 'ring', text: safe.code });
68
+ msg.iotdb = { error: { code: safe.code, retryable: safe.retryable } };
69
+ done(safe);
70
+ }
71
+ });
72
+ node.on('close', () => { closing = true; node.status({}); });
73
+ }
74
+ RED.nodes.registerType('iotdb-operator', Operator);
75
+
76
+ function ConsumerNode(config) {
77
+ RED.nodes.createNode(this, config);
78
+ const node = this;
79
+ const server = RED.nodes.getNode(config.server);
80
+ let consumer, invalid;
81
+ try {
82
+ if (!server) throw new IotdbError('SERVER_REQUIRED', 'Select an IoTDB server');
83
+ if (server.configError) throw server.configError;
84
+ for (const key of ['topic', 'groupId', 'consumerId']) {
85
+ if (typeof config[key] !== 'string' || !/^[a-zA-Z0-9_][a-zA-Z0-9_-]{0,127}$/.test(config[key])) throw new IotdbError('INVALID_CONFIG', `${key} must be a stable identifier of 1–128 letters, digits, underscores or hyphens`);
86
+ }
87
+ if (!['manual', 'delivery'].includes(config.ackMode || 'manual')) throw new IotdbError('INVALID_CONFIG', 'ACK mode must be manual or delivery');
88
+ consumer = new Consumer({ ...server.options, topic: config.topic, groupId: config.groupId, consumerId: config.consumerId,
89
+ stateDir: RED.settings.userDir ? path.join(RED.settings.userDir, 'iotdb-subscriptions') : undefined,
90
+ ackMode: config.ackMode || 'manual',
91
+ pollMs: integer(config.pollMs, 1000, 100, 5000, 'poll timeout'),
92
+ maxInFlight: integer(config.maxInFlight, 4, 1, 64, 'maximum unacknowledged batches'),
93
+ maxRows: integer(config.maxRows, 10000, 1, 100000, 'maximum batch rows'),
94
+ maxBytes: integer(config.maxBytes, 8388608, 1024, 67108864, 'maximum batch bytes'),
95
+ });
96
+ server.consumers.add(consumer);
97
+ consumer.on('data', msg => node.send(msg));
98
+ consumer.on('failure', err => {
99
+ const error = safeError(err, [server.options.password]);
100
+ node.error(error, { topic: config.topic, iotdb: { model: server.options.model, error: { code: error.code, retryable: error.retryable } } });
101
+ });
102
+ consumer.on('status', ({ state, inFlight }) => node.status({ fill: state === 'error' ? 'red' : state === 'subscribed' ? 'green' : 'yellow', shape: state === 'subscribed' ? 'dot' : 'ring', text: `${state} (${inFlight})` }));
103
+ consumer.start();
104
+ } catch (error) { invalid = error; node.status({ fill: 'red', shape: 'ring', text: error.code || 'configuration error' }); }
105
+ node.on('input', async (msg, send, done) => {
106
+ done = done || (error => { if (error) node.error(error, msg); });
107
+ try {
108
+ if (invalid) throw invalid;
109
+ const action = msg.iotdb?.action || (msg.iotdb?.ackToken ? 'ack' : undefined);
110
+ if (action === 'ack') await consumer.ack(msg.iotdb.ackToken);
111
+ else if (action === 'pause') consumer.pause();
112
+ else if (action === 'resume') consumer.resume();
113
+ else throw new IotdbError('INVALID_ACTION', 'Use msg.iotdb.action = ack, pause or resume');
114
+ done();
115
+ } catch (error) { done(safeError(error, [server?.options?.password])); }
116
+ });
117
+ node.on('close', (removed, done) => {
118
+ Promise.resolve(consumer?.close()).catch(error => node.warn(safeError(error, [server?.options?.password]).message))
119
+ .finally(() => { server?.consumers.delete(consumer); node.status({}); done(); });
120
+ });
121
+ }
122
+ RED.nodes.registerType('iotdb-consumer', ConsumerNode);
123
+ };
package/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "@timecho/node-red-node-iotdb",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.2",
4
+ "description": "Node-RED SQL and native subscription nodes for Apache IoTDB and TimechoDB",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/iotdb-ecosystem/node-red-node-iotdb.git"
9
+ },
10
+ "engines": {
11
+ "node": ">=22.9.0"
12
+ },
13
+ "keywords": [
14
+ "node-red",
15
+ "iotdb",
16
+ "timechodb",
17
+ "timeseries",
18
+ "subscription"
19
+ ],
20
+ "node-red": {
21
+ "version": ">=4.1.0",
22
+ "nodes": {
23
+ "iotdb": "nodes/iotdb.js"
24
+ }
25
+ },
26
+ "files": [
27
+ "nodes/",
28
+ "lib/",
29
+ "bridge/src/",
30
+ "bridge/target/iotdb-bridge.jar",
31
+ "bridge/build.js",
32
+ "bridge/README.md",
33
+ "examples/",
34
+ "README.md",
35
+ "LICENSE",
36
+ "docs/operations.md",
37
+ "docs/compatibility.md",
38
+ "docs/production-readiness.md",
39
+ "docs/validation-report.md",
40
+ "docs/research/subscription-recovery-contract.md"
41
+ ],
42
+ "scripts": {
43
+ "test": "node --test test/*.test.js",
44
+ "test:integration": "node --test --test-concurrency=1 test/integration/*.test.js",
45
+ "test:acceptance": "node --test --test-concurrency=1 test/acceptance/*.test.js",
46
+ "test:server-contract": "node --test --test-concurrency=1 test/server-contract/*.test.js",
47
+ "build:bridge": "node bridge/build.js",
48
+ "check": "node --check nodes/iotdb.js && node --check lib/sql-client.js && node --check lib/bridge-client.js && node --check lib/consumer.js",
49
+ "pack:check": "npm pack --dry-run"
50
+ },
51
+ "dependencies": {
52
+ "@iotdb/client": "2.0.11"
53
+ },
54
+ "devDependencies": {
55
+ "node-red": "5.0.9",
56
+ "node-red-node-test-helper": "0.3.6"
57
+ },
58
+ "overrides": {
59
+ "body-parser": "1.20.9",
60
+ "multer": "2.5.0",
61
+ "npm": "11.21.2",
62
+ "minimatch": "11.0.1"
63
+ }
64
+ }