@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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,98 @@
1
- # Temporary Holding Version
1
+ # @timecho/node-red-node-iotdb
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Node-RED nodes for Apache IoTDB and TimechoDB:统一的树/表模型 SQL 和原生订阅接口。
4
+
5
+ 当前包版本为 `0.0.2`。插件提供 SQL 操作和原生 Topic 订阅,并支持手动 ACK。订阅功能以服务端版本和模型为准,具体已验证范围见[兼容矩阵](docs/compatibility.md)。
6
+
7
+ 订阅连接失效时,consumer 报告 `RECOVERY_REQUIRED` 并停止拉取,旧 ACK token 随连接失效。持久化标记用于阻止同一 Topic/组在重启或重新部署时直接建立新消费起点;标记不保存消息或消费位点。恢复前请核对下游处理记录和数据库数据,再按[运行说明](docs/operations.md)处理。
8
+
9
+ SDK 可能把网络失败转为空批次;桥接层会检查连接状态,并在暂停或等待 ACK 时继续检查。接口行为与受控恢复测试记录见[调查材料](docs/research/subscription-recovery-contract.md)。
10
+
11
+ ## 三种节点
12
+
13
+ | 类型 | 作用 |
14
+ | --- | --- |
15
+ | `iotdb-server` | 共享配置:地址、模型、数据库、Node-RED credentials、超时和队列限制 |
16
+ | `iotdb-operator` | SQL 查询、写入和管理;支持固定 SQL 或 `msg.topic` |
17
+ | `iotdb-consumer` | 原生 Topic 消费;输入端接收 ACK / pause / resume |
18
+
19
+ 配置节点不占用画布。树、表各使用一个独立配置节点。数据写入和 Topic 管理由 operator 执行 SQL,首版不另外注册 write 或 ack 节点。
20
+
21
+ ## 安装
22
+
23
+ 要求 Node.js 22.9+、Node-RED 4.1+。在 Node-RED 用户目录安装指定版本,然后重启 Node-RED:
24
+
25
+ ```bash
26
+ cd ~/.node-red
27
+ npm install @timecho/node-red-node-iotdb@0.0.2
28
+ ```
29
+
30
+ 生产使用前应固定经验证的包版本,设置 Node-RED `credentialSecret`,并按 [部署说明](docs/operations.md) 配置身份验证与网络边界。
31
+
32
+ SQL 使用固定版本 `@iotdb/client@2.0.11`。SDK 的默认行迭代器会转换树模型时间戳、返回物理列顺序;本包用隔离且锁定版本的适配层保留原始整数与逻辑列映射。升级 SDK 前必须重跑兼容测试。客户端运行在受限 Worker 中;超时会终止该连接,**写入不会自动重试**,调用方需判断未知执行结果。
33
+
34
+ ## SQL 消息
35
+
36
+ 输入:
37
+
38
+ ```javascript
39
+ msg.topic = "SELECT temperature FROM root.factory.device01 LIMIT 100";
40
+ return msg;
41
+ ```
42
+
43
+ 查询输出 `msg.payload` 为对象数组;非查询成功为 `{success:true}`。原消息的其他字段保留,`msg.iotdb` 提供 operation、model、columns、rowCount、timestampPrecision。
44
+
45
+ - INT64、时间戳始终输出十进制字符串;NULL 保持 null;BLOB 使用 `0x` 十六进制;非有限浮点数使用字符串。
46
+ - 重复列名生成 `#2`、`#3` 后缀,原始列名及输出 key 均保留在 columns。
47
+ - 默认最多 10,000 行 / 8 MiB。超过边界时整个请求报错,不输出悄悄截断的结果。SQL 中应设置时间条件和 LIMIT。
48
+ - 模式 auto / query / execute。自动分类不明的 SQL 应手动指定模式。
49
+ - SQL 按原文执行;不提供占位符替换。不要直接拼接不可信输入。
50
+ - 共用连接不允许 `USE` 或 `SET SQL_DIALECT` 改变其他 operator 的模型/库;请编辑 server 配置。
51
+ - Catch 接收错误,Complete 在实际操作完成后触发。`msg.iotdb.error` 包含稳定错误分类。
52
+
53
+ ## 原生订阅
54
+
55
+ 服务端必须启用相应版本/模型的原生订阅。当前桥接需要 Java 17+ 和**与服务端相匹配的官方 Java SDK 及其依赖**;SDK 不随 npm 包分发。
56
+
57
+ ```bash
58
+ export IOTDB_SUBSCRIPTION_CLASSPATH='/path/to/approved-sdk/lib/*'
59
+ npm run build:bridge
60
+ ```
61
+
62
+ 编译需要 JDK 17+;已有编译产物的部署只需 Java 17+ 运行时。没有编译产物时会使用 Java 源文件启动,需要 JDK。桥接以私有标准输入/输出通信,凭据通过管道传递,未放入 Java 参数或原始日志。
63
+
64
+ 在 consumer 中选择已有 Topic,填写稳定 groupId 和 consumerId。表模型 Topic 支持版本与模式见兼容矩阵;`incremental` 依赖 IoTConsensus,且仅消费首次成功订阅后进入共识链路的写入。
65
+
66
+ ```javascript
67
+ // consumer 输出示意
68
+ {
69
+ topic: "temperature_topic",
70
+ payload: [{source: "root.factory.device01", timestamp: "1794133480573", values: {temperature: 25.5}}],
71
+ iotdb: {model: "tree", consumerGroupId: "alarms", consumerId: "worker1", ackToken: "opaque-token"}
72
+ }
73
+ ```
74
+
75
+ 默认手动 ACK:下游全部必要处理成功后,保留 `msg.iotdb.ackToken` 回送同一 consumer,可显式设置 `msg.iotdb.action = "ack"`。ACK 输入成功后不再发出数据消息,避免循环。多分支处理应在汇合成功后 ACK。
76
+
77
+ 树模型 `source` 为完整设备路径;表模型为 `database.table`,可以区分跨库同名表。如果 Topic 的列筛选排除了时间,`timestamp` 为 null。原生消息可能包含同一时间的部分列或重复记录;保留服务端原始记录,业务应按实际字段执行幂等处理。
78
+
79
+ `delivery` 模式在 `node.send()` 后提交,表示已交付流程,不能代表下游业务成功。未确认消息可能重投,业务需要幂等处理;没有端到端 exactly-once 保证。
80
+
81
+ `pause` 停止后续拉取,保留连接和心跳;已在执行的一次 poll 仍可能返回。`resume` 恢复同一存活会话内的拉取。达到待确认批次上限后自动停止新 poll。服务端会在 SDK close 时隐式取消订阅;连接失效后 consumer 停止自动拉取,旧 token 失效。同一 Topic/组同时使用一个 consumer。
82
+
83
+ 首版支持记录格式 Topic;TsFile 和不支持的数据类型会报错且不确认。超大批次失败后需调整 Topic 范围/批次限制;不会丢弃后继续。订阅桥接暂不支持原生 TLS,请使用受保护网络或加密隧道;SQL TLS 始终验证证书。
84
+
85
+ ## 开发验证
86
+
87
+ ```bash
88
+ npm ci
89
+ npm test
90
+ npm run check
91
+ # 环境中提供 IOTDB_TEST_PASSWORD、IOTDB_TEST_HOST、IOTDB_TEST_PORT
92
+ # 原生订阅测试还需 IOTDB_SUBSCRIPTION_CLASSPATH
93
+ npm run test:integration
94
+ npm run test:acceptance
95
+ npm pack --dry-run
96
+ ```
97
+
98
+ 集成测试会创建随机 `nr_test_` 命名空间、Topic 和消费组,并清理自己的资源。仅对获授权的测试数据库运行。未提供密码时数据库测试会跳过,跳过不等于通过。
@@ -0,0 +1,15 @@
1
+ # Native subscription bridge
2
+
3
+ `IotdbSubscriptionBridge` wraps official Tree/Table Pull Consumers, using `autoCommit(false)`. It is a child process with a private pipe protocol; it does not open a server socket.
4
+
5
+ Build with JDK 17+ and `IOTDB_SUBSCRIPTION_CLASSPATH` pointing to a compatible SDK and its dependencies. `node build.js` writes `target/iotdb-bridge.jar`. Vendor SDK jars are not redistributed. The class is also runnable with Java source-file mode on a JDK.
6
+
7
+ Input is one bounded tab-separated line: numeric request id, operation, then base64 UTF-8 arguments. Base64 is framing, not encryption; pipes stay local to the Node-RED process. Output is one JSON object per line. SDK stdout is redirected away from the protocol; the parent drains but does not expose raw SDK logging. Passwords travel only in the init pipe message.
8
+
9
+ Supported private operations: init, poll, health, ack, close; unsubscribe exists for explicit maintenance/test cleanup, and is not exposed as a Node-RED message action. TimechoDB 2.0.12.1 implicitly unsubscribes on CLOSE and inactivity. The bridge attempts NACK before close, but this does not preserve group progress. Each poll result is one ACK unit; a batch can contain multiple server messages. A commit failure retains its pending batch. The last 1024 successful tokens are remembered for duplicate ACK idempotence within the same process.
10
+
11
+ The SDK can return empty polls after a transport failure. The bridge checks the protected `getAvailableDataNodeIds()` extension point before/after poll and before ACK; a separate health command covers paused and backpressured consumers. An empty provider set becomes CONNECTION_LOST instead of a healthy empty batch. This is verified against the matching 2.0.12.1 SDK; it is not a general cluster recovery or durable-offset guarantee.
12
+
13
+ The private progress/seekbegin/seekend/seekat/seekafter/release commands support recovery research only. They are not Node-RED input actions or a certified recovery mechanism. `Consumer` persists a restart interlock and stops on connection loss rather than automatically creating a new group tail. See the production-readiness document and the failing release-acceptance tests.
14
+
15
+ Batch row/byte limits, max in-flight batches, bounded Java heap, bounded command queue, process deadlines, EOF cleanup and forced termination bound resource use. A received batch over the configured limit is never committed. The SDK may transiently allocate a batch before its size can be inspected; a JVM memory failure closes the bridge. Uncommitted data still requires explicit recovery; server group progress is not guaranteed to survive close.
@@ -0,0 +1,17 @@
1
+ 'use strict';
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const { spawnSync } = require('node:child_process');
5
+ const sdk = process.env.IOTDB_SUBSCRIPTION_CLASSPATH;
6
+ if (!sdk) throw new Error('Set IOTDB_SUBSCRIPTION_CLASSPATH to the matching official Java SDK and its dependencies');
7
+ const target = path.join(__dirname, 'target');
8
+ fs.mkdirSync(target, { recursive: true });
9
+ function run(command, args) {
10
+ const result = spawnSync(command, args, { stdio: 'inherit', windowsHide: true });
11
+ if (result.error) throw result.error;
12
+ if (result.status !== 0) process.exit(result.status || 1);
13
+ }
14
+ run(process.env.JAVAC || 'javac', ['--release', '17', '-encoding', 'UTF-8', '-cp', sdk, '-d', target, path.join(__dirname, 'src/IotdbSubscriptionBridge.java')]);
15
+ const classes = fs.readdirSync(target).filter(name => /^IotdbSubscriptionBridge(?:\$[\w$]+)?\.class$/.test(name)).sort();
16
+ run(process.env.JAR || 'jar', ['--create', '--file', path.join(target, 'iotdb-bridge.jar'), '--date=2026-01-01T00:00:00Z', ...classes.flatMap(name => ['-C', target, name])]);
17
+ console.log('Built bridge/target/iotdb-bridge.jar (SDK libraries are not bundled)');
@@ -0,0 +1,277 @@
1
+ import java.io.*;
2
+ import java.nio.charset.StandardCharsets;
3
+ import java.nio.ByteBuffer;
4
+ import java.time.Duration;
5
+ import java.util.*;
6
+
7
+ import org.apache.iotdb.session.subscription.consumer.ISubscriptionTreePullConsumer;
8
+ import org.apache.iotdb.session.subscription.consumer.ISubscriptionTablePullConsumer;
9
+ import org.apache.iotdb.session.subscription.consumer.tree.SubscriptionTreePullConsumerBuilder;
10
+ import org.apache.iotdb.session.subscription.consumer.tree.SubscriptionTreePullConsumer;
11
+ import org.apache.iotdb.session.subscription.consumer.table.SubscriptionTablePullConsumerBuilder;
12
+ import org.apache.iotdb.session.subscription.consumer.table.SubscriptionTablePullConsumer;
13
+ import org.apache.iotdb.session.subscription.payload.SubscriptionMessage;
14
+ import org.apache.iotdb.session.subscription.payload.SubscriptionRecordHandler.SubscriptionResultSet;
15
+ import org.apache.tsfile.write.record.Tablet;
16
+ import org.apache.tsfile.utils.Binary;
17
+ import org.apache.iotdb.rpc.subscription.payload.poll.TopicProgress;
18
+
19
+ /** Private pipe protocol. Never expose this process as a network service. */
20
+ public final class IotdbSubscriptionBridge {
21
+ // Protected SDK extension points let us explicitly NACK in-flight data before
22
+ // a graceful close. Otherwise server recycling can take ten minutes by default.
23
+ static final class ReleasingTreeConsumer extends SubscriptionTreePullConsumer {
24
+ ReleasingTreeConsumer(SubscriptionTreePullConsumerBuilder builder) { super(builder); }
25
+ void release(Iterable<SubscriptionMessage> messages) { super.nack(messages); }
26
+ boolean hasAvailableProvider() { return !super.getAvailableDataNodeIds().isEmpty(); }
27
+ }
28
+ static final class ReleasingTableConsumer extends SubscriptionTablePullConsumer {
29
+ ReleasingTableConsumer(SubscriptionTablePullConsumerBuilder builder) { super(builder); }
30
+ void release(Iterable<SubscriptionMessage> messages) { super.nack(messages); }
31
+ boolean hasAvailableProvider() { return !super.getAvailableDataNodeIds().isEmpty(); }
32
+ }
33
+ private ReleasingTreeConsumer tree;
34
+ private ReleasingTableConsumer table;
35
+ private String password = "";
36
+ private String topic;
37
+ private String model;
38
+ private int pollMs, maxInFlight, maxRows, maxBytes;
39
+ private final Map<String, List<SubscriptionMessage>> pending = new LinkedHashMap<>();
40
+ private final Set<Object> pendingContexts = new HashSet<>();
41
+ private final Set<String> committed = new LinkedHashSet<>();
42
+ private final Set<SubscriptionMessage> held = new LinkedHashSet<>();
43
+ private final PrintStream output = System.out;
44
+
45
+ private Object init(String[] fields) throws Exception {
46
+ if (tree != null || table != null) throw new IllegalStateException("ALREADY_OPEN");
47
+ if (fields.length != 16) throw new IllegalArgumentException("INVALID_INIT");
48
+ String host = fields[2];
49
+ int port = Integer.parseInt(fields[3]);
50
+ String user = fields[4];
51
+ password = fields[5];
52
+ model = fields[6];
53
+ topic = fields[7];
54
+ String group = fields[8], consumer = fields[9];
55
+ pollMs = Integer.parseInt(fields[10]);
56
+ maxInFlight = Integer.parseInt(fields[11]);
57
+ maxRows = Integer.parseInt(fields[12]);
58
+ maxBytes = Integer.parseInt(fields[13]);
59
+ int connectMs = Integer.parseInt(fields[14]);
60
+ String fileDir = fields[15];
61
+ if (model.equals("tree")) {
62
+ tree = new ReleasingTreeConsumer(new SubscriptionTreePullConsumerBuilder().host(host).port(port)
63
+ .username(user).password(password).consumerGroupId(group).consumerId(consumer)
64
+ .autoCommit(false).maxPollParallelism(1).connectionTimeoutInMs(connectMs)
65
+ .heartbeatIntervalMs(3000).endpointsSyncIntervalMs(10000)
66
+ .fileSaveDir(fileDir));
67
+ tree.open();
68
+ tree.subscribe(topic);
69
+ } else if (model.equals("table")) {
70
+ table = new ReleasingTableConsumer(new SubscriptionTablePullConsumerBuilder().host(host).port(port)
71
+ .username(user).password(password).consumerGroupId(group).consumerId(consumer)
72
+ .autoCommit(false).maxPollParallelism(1).connectionTimeoutInMs(connectMs)
73
+ .heartbeatIntervalMs(3000).endpointsSyncIntervalMs(10000)
74
+ .fileSaveDir(fileDir));
75
+ table.open();
76
+ table.subscribe(topic);
77
+ } else throw new IllegalArgumentException("INVALID_MODEL");
78
+ return Map.of("model", model, "topic", topic, "consumerId", consumer, "consumerGroupId", group);
79
+ }
80
+
81
+ private Object poll() throws Exception {
82
+ if (tree == null && table == null) throw new IllegalStateException("NOT_OPEN");
83
+ health();
84
+ if (pending.size() >= maxInFlight) return Map.of("blocked", true);
85
+ List<SubscriptionMessage> received = tree != null ? tree.poll(Duration.ofMillis(pollMs)) : table.poll(Duration.ofMillis(pollMs));
86
+ // The SDK can turn a failed network poll into an empty result. An empty
87
+ // provider set must not be reported to Node-RED as a healthy idle topic.
88
+ health();
89
+ held.addAll(received);
90
+ List<SubscriptionMessage> fresh = new ArrayList<>();
91
+ Set<Object> seen = new HashSet<>(pendingContexts);
92
+ long estimated = 0;
93
+ for (SubscriptionMessage message : received) {
94
+ if (seen.add(message.getCommitContext())) {
95
+ estimated += message.estimateSize();
96
+ if (estimated > maxBytes) throw new IllegalStateException("BATCH_LIMIT: subscription batch exceeds configured bytes; not committed");
97
+ fresh.add(message);
98
+ }
99
+ }
100
+ if (fresh.isEmpty()) return Map.of("empty", true);
101
+ List<Object> rows = new ArrayList<>();
102
+ Map<String, Object> schemas = new LinkedHashMap<>();
103
+ for (SubscriptionMessage message : fresh) {
104
+ // Record messages only. A TsFile/unsupported payload is never ACKed.
105
+ if (message.getMessageType() != 0) throw new IllegalStateException("UNSUPPORTED_PAYLOAD: configure a record/SessionDataSets topic");
106
+ for (var resultSet : message.getResultSets()) {
107
+ if (!(resultSet instanceof SubscriptionResultSet records)) throw new IllegalStateException("UNSUPPORTED_SDK: expected a subscription record result set");
108
+ Tablet tablet = records.getTablet();
109
+ String source = model.equals("tree") ? tablet.getDeviceId() : records.getDatabaseName() + "." + records.getTableName();
110
+ List<Object> columns = new ArrayList<>();
111
+ for (var schema : tablet.getSchemas()) columns.add(Map.of("name", schema.getMeasurementName(), "type", schema.getType().name()));
112
+ schemas.put(source, columns);
113
+ for (int r = 0; r < tablet.getRowSize(); r++) {
114
+ if (rows.size() >= maxRows) throw new IllegalStateException("BATCH_LIMIT: subscription batch exceeds configured rows; not committed");
115
+ Map<String, Object> values = new LinkedHashMap<>();
116
+ for (int c = 0; c < tablet.getSchemas().size(); c++) {
117
+ var schema = tablet.getSchemas().get(c);
118
+ values.put(schema.getMeasurementName(), tablet.isNull(r, c) ? null : convert(tablet.getValue(r, c), schema.getType().name()));
119
+ }
120
+ Map<String, Object> row = new LinkedHashMap<>();
121
+ row.put("source", source);
122
+ row.put("timestamp", records.isTimeSelected() ? Long.toString(tablet.getTimestamp(r)) : null);
123
+ row.put("values", values);
124
+ rows.add(row);
125
+ }
126
+ }
127
+ }
128
+ String token = UUID.randomUUID().toString();
129
+ Map<String, Object> result = Map.of("token", token, "rows", rows, "schemas", schemas, "messageCount", fresh.size());
130
+ if (json(result).getBytes(StandardCharsets.UTF_8).length > maxBytes) throw new IllegalStateException("BATCH_LIMIT: encoded batch exceeds configured bytes; not committed");
131
+ pending.put(token, fresh);
132
+ for (SubscriptionMessage message : fresh) pendingContexts.add(message.getCommitContext());
133
+ return result;
134
+ }
135
+
136
+ private Object ack(String token) throws Exception {
137
+ health();
138
+ if (committed.contains(token)) return Map.of("duplicate", true);
139
+ List<SubscriptionMessage> messages = pending.get(token);
140
+ if (messages == null) throw new IllegalArgumentException("UNKNOWN_ACK: expired or foreign acknowledgement token");
141
+ if (tree != null) tree.commitSync(messages); else table.commitSync(messages);
142
+ pending.remove(token);
143
+ held.removeAll(messages);
144
+ for (SubscriptionMessage message : messages) {
145
+ pendingContexts.remove(message.getCommitContext());
146
+ message.removeUserData();
147
+ }
148
+ committed.add(token);
149
+ if (committed.size() > 1024) committed.remove(committed.iterator().next());
150
+ return Map.of("committed", true);
151
+ }
152
+
153
+ private Object health() {
154
+ boolean available = tree != null ? tree.hasAvailableProvider() : table != null && table.hasAvailableProvider();
155
+ if (!available) throw new IllegalStateException("CONNECTION_LOST: no available subscription provider; recovery must be verified before resubscription");
156
+ return Map.of("available", true);
157
+ }
158
+
159
+ private void close() throws Exception {
160
+ // TimechoDB 2.0.12.1 implicitly unsubscribes on CLOSE, and on inactivity.
161
+ // NACK releases held messages but does not make group progress durable.
162
+ try {
163
+ if (!held.isEmpty()) {
164
+ if (tree != null) tree.release(held); else if (table != null) table.release(held);
165
+ }
166
+ } finally {
167
+ try { if (tree != null) tree.close(); }
168
+ finally { if (table != null) table.close(); pending.clear(); pendingContexts.clear(); held.clear(); }
169
+ }
170
+ }
171
+
172
+ private Object progress() throws Exception {
173
+ TopicProgress current = tree != null ? tree.positions(topic) : table.positions(topic);
174
+ TopicProgress committed = tree != null ? tree.committedPositions(topic) : table.committedPositions(topic);
175
+ ByteBuffer encoded = TopicProgress.serialize(current);
176
+ byte[] bytes = new byte[encoded.remaining()]; encoded.get(bytes);
177
+ return Map.of("current", String.valueOf(current), "committed", String.valueOf(committed), "checkpoint", Base64.getEncoder().encodeToString(bytes));
178
+ }
179
+
180
+ private static Object convert(Object value, String type) {
181
+ if (value == null) return null;
182
+ if (type.equals("INT64") || type.equals("TIMESTAMP")) return value.toString();
183
+ if (type.equals("DATE")) return value.toString();
184
+ if (value instanceof Binary binary) {
185
+ if (type.equals("BLOB")) return "0x" + HexFormat.of().formatHex(binary.getValues());
186
+ if (type.equals("TEXT") || type.equals("STRING")) return binary.getStringValue(StandardCharsets.UTF_8);
187
+ throw new IllegalArgumentException("UNSUPPORTED_TYPE: " + type);
188
+ }
189
+ if (value instanceof Float n && !Float.isFinite(n)) return n.toString();
190
+ if (value instanceof Double n && !Double.isFinite(n)) return n.toString();
191
+ if (value instanceof Number || value instanceof Boolean || value instanceof String) return value;
192
+ throw new IllegalArgumentException("UNSUPPORTED_TYPE: " + type);
193
+ }
194
+
195
+ private static String json(Object value) {
196
+ if (value == null) return "null";
197
+ if (value instanceof Boolean || value instanceof Number) return value.toString();
198
+ if (value instanceof Map<?, ?> map) {
199
+ StringJoiner joiner = new StringJoiner(",", "{", "}");
200
+ for (var entry : map.entrySet()) joiner.add(json(entry.getKey().toString()) + ":" + json(entry.getValue()));
201
+ return joiner.toString();
202
+ }
203
+ if (value instanceof Iterable<?> list) {
204
+ StringJoiner joiner = new StringJoiner(",", "[", "]");
205
+ for (Object element : list) joiner.add(json(element));
206
+ return joiner.toString();
207
+ }
208
+ StringBuilder out = new StringBuilder("\"");
209
+ for (char c : value.toString().toCharArray()) {
210
+ if (c == '"' || c == '\\') out.append('\\').append(c);
211
+ else if (c < 32) out.append(String.format("\\u%04x", (int) c));
212
+ else out.append(c);
213
+ }
214
+ return out.append('"').toString();
215
+ }
216
+
217
+ private void run() throws Exception {
218
+ // SDK loggers must never write to the protocol stream.
219
+ System.setOut(System.err);
220
+ BufferedReader input = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
221
+ try {
222
+ String line;
223
+ while ((line = input.readLine()) != null) {
224
+ if (line.length() > 65536) throw new IllegalArgumentException("REQUEST_LIMIT");
225
+ String[] fields = line.split("\t", -1);
226
+ int id = Integer.parseInt(fields[0]);
227
+ String action = fields[1];
228
+ try {
229
+ for (int i = 2; i < fields.length; i++) fields[i] = new String(Base64.getDecoder().decode(fields[i]), StandardCharsets.UTF_8);
230
+ Object result = switch (action) {
231
+ case "init" -> init(fields);
232
+ case "poll" -> poll();
233
+ case "health" -> health();
234
+ case "ack" -> ack(fields[2]);
235
+ case "release" -> {
236
+ int count = held.size();
237
+ if (tree != null) tree.release(held); else table.release(held);
238
+ held.clear(); pending.clear(); pendingContexts.clear();
239
+ yield Map.of("released", count);
240
+ }
241
+ case "progress" -> progress();
242
+ case "seekbegin" -> { if (tree != null) tree.seekToBeginning(topic); else table.seekToBeginning(topic); yield progress(); }
243
+ case "seekend" -> { if (tree != null) tree.seekToEnd(topic); else table.seekToEnd(topic); yield progress(); }
244
+ case "seekafter" -> {
245
+ TopicProgress checkpoint = TopicProgress.deserialize(ByteBuffer.wrap(Base64.getDecoder().decode(fields[2])));
246
+ if (tree != null) tree.seekAfter(topic, checkpoint); else table.seekAfter(topic, checkpoint);
247
+ yield progress();
248
+ }
249
+ case "seekat" -> {
250
+ TopicProgress checkpoint = TopicProgress.deserialize(ByteBuffer.wrap(Base64.getDecoder().decode(fields[2])));
251
+ if (tree != null) tree.seek(topic, checkpoint); else table.seek(topic, checkpoint);
252
+ yield progress();
253
+ }
254
+ case "unsubscribe" -> {
255
+ if (tree != null) tree.unsubscribe(topic); else if (table != null) table.unsubscribe(topic);
256
+ yield Map.of("unsubscribed", true);
257
+ }
258
+ case "close" -> { close(); yield Map.of("closed", true); }
259
+ default -> throw new IllegalArgumentException("INVALID_ACTION");
260
+ };
261
+ output.println(json(Map.of("id", id, "result", result)));
262
+ } catch (Throwable error) {
263
+ String detail = String.valueOf(error.getMessage());
264
+ if (!password.isEmpty()) detail = detail.replace(password, "[redacted]");
265
+ if (detail.length() > 600) detail = detail.substring(0, 600);
266
+ output.println(json(Map.of("id", id, "error", Map.of("code", "BRIDGE_ERROR", "message", detail))));
267
+ }
268
+ output.flush();
269
+ if (action.equals("close")) return;
270
+ }
271
+ } finally { close(); }
272
+ }
273
+
274
+ public static void main(String[] args) throws Exception {
275
+ new IotdbSubscriptionBridge().run();
276
+ }
277
+ }
Binary file
@@ -0,0 +1,27 @@
1
+ # 兼容矩阵
2
+
3
+ 公开包 `@timecho/node-red-node-iotdb@0.0.2`。下表功能验证基于 `0.1.0-rc.2` 的运行时代码,核验日期 2026-11-08;2026-11-19 对 TimechoDB 2.0.12.1 树/表订阅进行了重开场景测试。0.0.2 更新说明与仓库元数据,未改变插件运行逻辑;具体能力以服务端和模型对应的测试为准。
4
+
5
+ | 服务端 | 树模型 SQL | 表模型 SQL | 树模型订阅 | 表模型订阅 |
6
+ | --- | --- | --- | --- | --- |
7
+ | TimechoDB 2.0.12.1 / c05111d | Windows、Ubuntu 联调通过 | Windows、Ubuntu 联调通过 | snapshot / incremental、存活会话手动 ACK;断连后 consumer 返回 `RECOVERY_REQUIRED`,重开场景需核对数据 | snapshot / incremental、存活会话手动 ACK;断连后 consumer 返回 `RECOVERY_REQUIRED`,重开场景需核对数据 |
8
+ | Apache IoTDB 2.0.11 / 7c0de06 | Ubuntu 连隔离实例通过,包括 ns 时间戳 | Ubuntu 连隔离实例通过,包括 ns 时间戳 | 发行构建编译关闭;明确报错 | 发行构建编译关闭;明确报错 |
9
+
10
+ | 组件 | 当前环境 | 验证状态 |
11
+ | --- | --- | --- |
12
+ | Windows Node.js | 24.19.0 | 单元测试及 SQL 联调通过 |
13
+ | Ubuntu | 26.04 LTS / 7.2 GiB RAM | 作为开发与集成测试主机;通过 SSH 隧道连接 Windows 数据库 |
14
+ | Ubuntu Node.js | 22.22.1 | 21 项单元/Node-RED 测试和 18 项数据库集成测试通过 |
15
+ | Node-RED | 5.0.9 | 三类型注册、配置控件、真实查询流程、加密凭据和有界持续运行已测 |
16
+ | Java | Windows 21 / Ubuntu 17.0.20.1 | 编译和原生 Tree/Table Pull Consumer 桥接通过;企业 SDK 不随 npm 分发 |
17
+ | Node.js IoTDB SDK | 2.0.11 固定版本 | 适配层覆盖高精度时间、逻辑列映射和 BLOB;升级必须重测 |
18
+
19
+ 官方表模型文档说明 2.0.12.1 起支持 snapshot/incremental;incremental 仅适用于 IoTConsensus,需显式启用订阅。能力无法仅由产品名推断。节点在 SDK/服务端拒绝时明确报错,不以定时 SELECT 代替原生订阅。
20
+
21
+ TimechoDB 2.0.12.1 在 CLOSE 或不活跃清理时会取消订阅;本次同组重开测试中,插件报告 `RECOVERY_REQUIRED`,原生 SDK 在观察窗口内未返回未确认及停机期间的记录。当前节点遇到连接丢失时停止,并使用持久化标记阻止同 Topic/组被自动重建;该标记不是消费位点或数据备份。
22
+
23
+ `rc.2` 修复 SDK 空 poll 掩盖连接失效的问题,树/表等待 ACK 时的实际断网回归通过。发布验收直接测试插件 Consumer 的重启连续性;服务端 CLOSE 行为在独立 server-contract 用例中保留,客户端将来可以采用其他可靠机制满足目标。
24
+
25
+ 受控 WAL 重放研究用例通过,不代表过期 WAL、动态 Region、集群切换或多消费者恢复已获支持。SQL 原生 TLS 尚未做真实证书环境联调,订阅桥不支持原生 TLS。Node-RED 4.1、其他 Node.js/数据库版本以及集群部署均未认证。首轮持续运行只有 5 分钟,不能外推为日级稳定性或性能容量保证。
26
+
27
+ 详细证据见[验证报告](validation-report.md)和[验证范围](production-readiness.md)。发行包附带单独的干净安装报告及 SHA-256。