ot-gateway 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/VERSION +1 -1
  2. package/apps/gateway/src/main.mjs +821 -233
  3. package/apps/web/out/404/index.html +1 -0
  4. package/apps/web/out/404.html +1 -1
  5. package/apps/web/out/__next.__PAGE__.txt +28 -26
  6. package/apps/web/out/__next._full.txt +23 -21
  7. package/apps/web/out/__next._tree.txt +2 -2
  8. package/apps/web/out/_next/static/chunks/0-tykl1ek9eef.js +1 -0
  9. package/apps/web/out/_next/static/chunks/0_9hphsk8elkz.js +1 -0
  10. package/apps/web/out/_next/static/chunks/10i96w66fwhkr.js +31 -0
  11. package/apps/web/out/_next/static/chunks/2-12vm-gmodvi.css +1 -0
  12. package/apps/web/out/_next/static/chunks/2hhp92plmhxim.js +1 -0
  13. package/apps/web/out/_next/static/chunks/2r_w-j--qdreu.js +22 -0
  14. package/apps/web/out/_next/static/chunks/2t90haogl_st8.js +1 -0
  15. package/apps/web/out/_next/static/chunks/2vp-i92uyys5d.js +1 -0
  16. package/apps/web/out/_next/static/chunks/3k0dufyi1j19w.js +12 -0
  17. package/apps/web/out/_not-found/__next._full.txt +21 -19
  18. package/apps/web/out/_not-found/__next._not-found.__PAGE__.txt +27 -25
  19. package/apps/web/out/_not-found/__next._tree.txt +2 -2
  20. package/apps/web/out/_not-found/index.html +1 -0
  21. package/apps/web/out/_not-found/index.txt +22 -0
  22. package/apps/web/out/index.html +1 -1
  23. package/apps/web/out/index.txt +23 -21
  24. package/apps/web/out/messages/__next._full.txt +27 -0
  25. package/apps/web/out/messages/__next._tree.txt +4 -0
  26. package/apps/web/out/messages/__next.messages.__PAGE__.txt +33 -0
  27. package/apps/web/out/messages/index.html +1 -0
  28. package/apps/web/out/messages/index.txt +27 -0
  29. package/apps/web/out/points/__next._full.txt +27 -0
  30. package/apps/web/out/points/__next._tree.txt +4 -0
  31. package/apps/web/out/points/__next.points.__PAGE__.txt +33 -0
  32. package/apps/web/out/points/index.html +1 -0
  33. package/apps/web/out/points/index.txt +27 -0
  34. package/apps/web/out/settings/__next._full.txt +27 -0
  35. package/apps/web/out/settings/__next._tree.txt +4 -0
  36. package/apps/web/out/settings/__next.settings.__PAGE__.txt +33 -0
  37. package/apps/web/out/settings/index.html +1 -0
  38. package/apps/web/out/settings/index.txt +27 -0
  39. package/examples/gateway.json +37 -37
  40. package/package.json +1 -1
  41. package/packaging/compose.yaml +1 -1
  42. package/apps/web/out/_next/static/chunks/0csls39kpdzgy.js +0 -22
  43. package/apps/web/out/_next/static/chunks/162tvyao0-i49.js +0 -12
  44. package/apps/web/out/_next/static/chunks/29-6f2cs5ih9t.css +0 -1
  45. package/apps/web/out/_next/static/chunks/3oyy-mvhhfmq3.js +0 -31
  46. package/apps/web/out/_not-found.html +0 -1
  47. package/apps/web/out/_not-found.txt +0 -20
  48. /package/apps/web/out/_next/static/{s63QEywZ_oAqimFgcqV1S → XiBzAo3f0YeQ4E_ciqAE_}/_buildManifest.js +0 -0
  49. /package/apps/web/out/_next/static/{s63QEywZ_oAqimFgcqV1S → XiBzAo3f0YeQ4E_ciqAE_}/_clientMiddlewareManifest.js +0 -0
  50. /package/apps/web/out/_next/static/{s63QEywZ_oAqimFgcqV1S → XiBzAo3f0YeQ4E_ciqAE_}/_ssgManifest.js +0 -0
@@ -40,9 +40,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
40
40
  mod
41
41
  ));
42
42
 
43
- // ../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/constants.js
43
+ // ../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/constants.js
44
44
  var require_constants = __commonJS({
45
- "../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/constants.js"(exports, module) {
45
+ "../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/constants.js"(exports, module) {
46
46
  "use strict";
47
47
  var BINARY_TYPES = ["nodebuffer", "arraybuffer", "fragments"];
48
48
  var hasBlob = typeof Blob !== "undefined";
@@ -63,9 +63,9 @@ var require_constants = __commonJS({
63
63
  }
64
64
  });
65
65
 
66
- // ../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/buffer-util.js
66
+ // ../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/buffer-util.js
67
67
  var require_buffer_util = __commonJS({
68
- "../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/buffer-util.js"(exports, module) {
68
+ "../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/buffer-util.js"(exports, module) {
69
69
  "use strict";
70
70
  var { websocketMask, websocketUnmask } = __require("http");
71
71
  var { EMPTY_BUFFER } = require_constants();
@@ -148,9 +148,9 @@ var require_buffer_util = __commonJS({
148
148
  }
149
149
  });
150
150
 
151
- // ../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/limiter.js
151
+ // ../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/limiter.js
152
152
  var require_limiter = __commonJS({
153
- "../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/limiter.js"(exports, module) {
153
+ "../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/limiter.js"(exports, module) {
154
154
  "use strict";
155
155
  var kDone = /* @__PURE__ */ Symbol("kDone");
156
156
  var kRun = /* @__PURE__ */ Symbol("kRun");
@@ -198,9 +198,9 @@ var require_limiter = __commonJS({
198
198
  }
199
199
  });
200
200
 
201
- // ../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/permessage-deflate.js
201
+ // ../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/permessage-deflate.js
202
202
  var require_permessage_deflate = __commonJS({
203
- "../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/permessage-deflate.js"(exports, module) {
203
+ "../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/permessage-deflate.js"(exports, module) {
204
204
  "use strict";
205
205
  var zlib = __require("zlib");
206
206
  var bufferUtil = require_buffer_util();
@@ -581,9 +581,9 @@ var require_permessage_deflate = __commonJS({
581
581
  }
582
582
  });
583
583
 
584
- // ../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/validation.js
584
+ // ../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/validation.js
585
585
  var require_validation = __commonJS({
586
- "../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/validation.js"(exports, module) {
586
+ "../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/validation.js"(exports, module) {
587
587
  "use strict";
588
588
  var { isUtf8 } = __require("buffer");
589
589
  var { hasBlob } = require_constants();
@@ -782,9 +782,9 @@ var require_validation = __commonJS({
782
782
  }
783
783
  });
784
784
 
785
- // ../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/receiver.js
785
+ // ../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/receiver.js
786
786
  var require_receiver = __commonJS({
787
- "../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/receiver.js"(exports, module) {
787
+ "../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/receiver.js"(exports, module) {
788
788
  "use strict";
789
789
  var { Writable } = __require("stream");
790
790
  var PerMessageDeflate2 = require_permessage_deflate();
@@ -1194,6 +1194,7 @@ var require_receiver = __commonJS({
1194
1194
  unmask(data, this._mask);
1195
1195
  }
1196
1196
  }
1197
+ this._mask = void 0;
1197
1198
  if (this._opcode > 7) {
1198
1199
  this.controlMessage(data, cb);
1199
1200
  return;
@@ -1405,9 +1406,9 @@ var require_receiver = __commonJS({
1405
1406
  }
1406
1407
  });
1407
1408
 
1408
- // ../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/sender.js
1409
+ // ../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/sender.js
1409
1410
  var require_sender = __commonJS({
1410
- "../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/sender.js"(exports, module) {
1411
+ "../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/sender.js"(exports, module) {
1411
1412
  "use strict";
1412
1413
  var { Duplex: Duplex2 } = __require("stream");
1413
1414
  var { randomFillSync } = __require("crypto");
@@ -1901,9 +1902,9 @@ var require_sender = __commonJS({
1901
1902
  }
1902
1903
  });
1903
1904
 
1904
- // ../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/event-target.js
1905
+ // ../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/event-target.js
1905
1906
  var require_event_target = __commonJS({
1906
- "../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/event-target.js"(exports, module) {
1907
+ "../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/event-target.js"(exports, module) {
1907
1908
  "use strict";
1908
1909
  var { kForOnEventAttribute, kListener } = require_constants();
1909
1910
  var kCode = /* @__PURE__ */ Symbol("kCode");
@@ -2130,9 +2131,9 @@ var require_event_target = __commonJS({
2130
2131
  }
2131
2132
  });
2132
2133
 
2133
- // ../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/extension.js
2134
+ // ../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/extension.js
2134
2135
  var require_extension = __commonJS({
2135
- "../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/extension.js"(exports, module) {
2136
+ "../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/extension.js"(exports, module) {
2136
2137
  "use strict";
2137
2138
  var { tokenChars } = require_validation();
2138
2139
  function push(dest, name, elem) {
@@ -2283,14 +2284,15 @@ var require_extension = __commonJS({
2283
2284
  }
2284
2285
  });
2285
2286
 
2286
- // ../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/websocket.js
2287
+ // ../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/websocket.js
2287
2288
  var require_websocket = __commonJS({
2288
- "../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/websocket.js"(exports, module) {
2289
+ "../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/websocket.js"(exports, module) {
2289
2290
  "use strict";
2290
2291
  var EventEmitter = __require("events");
2291
2292
  var https = __require("https");
2292
2293
  var http2 = __require("http");
2293
2294
  var net = __require("net");
2295
+ var querystring = __require("querystring");
2294
2296
  var tls = __require("tls");
2295
2297
  var { randomBytes: randomBytes2, createHash } = __require("crypto");
2296
2298
  var { Duplex: Duplex2, Readable: Readable6 } = __require("stream");
@@ -2817,10 +2819,9 @@ var require_websocket = __commonJS({
2817
2819
  throw new SyntaxError(`Invalid URL: ${address}`);
2818
2820
  }
2819
2821
  }
2820
- if (parsedUrl.protocol === "http:") {
2821
- parsedUrl.protocol = "ws:";
2822
- } else if (parsedUrl.protocol === "https:") {
2823
- parsedUrl.protocol = "wss:";
2822
+ if (parsedUrl.protocol === "http:" || parsedUrl.protocol === "https:") {
2823
+ parsedUrl = new URL4(parsedUrl);
2824
+ parsedUrl.protocol = parsedUrl.protocol === "http:" ? "ws:" : "wss:";
2824
2825
  }
2825
2826
  websocket._url = parsedUrl.href;
2826
2827
  const isSecure = parsedUrl.protocol === "wss:";
@@ -2889,7 +2890,9 @@ var require_websocket = __commonJS({
2889
2890
  }
2890
2891
  }
2891
2892
  if (parsedUrl.username || parsedUrl.password) {
2892
- opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
2893
+ const username = querystring.unescape(parsedUrl.username);
2894
+ const password = querystring.unescape(parsedUrl.password);
2895
+ opts.auth = `${username}:${password}`;
2893
2896
  }
2894
2897
  if (isIpcUrl) {
2895
2898
  const i = opts.path.indexOf(":");
@@ -3094,8 +3097,13 @@ var require_websocket = __commonJS({
3094
3097
  function receiverOnConclude(code, reason) {
3095
3098
  const websocket = this[kWebSocket];
3096
3099
  websocket._closeFrameReceived = true;
3097
- websocket._closeMessage = reason;
3098
3100
  websocket._closeCode = code;
3101
+ if (reason.length === 0) {
3102
+ websocket._closeMessage = EMPTY_BUFFER;
3103
+ } else {
3104
+ websocket._closeMessage = Buffer.allocUnsafeSlow(reason.length);
3105
+ websocket._closeMessage.set(reason);
3106
+ }
3099
3107
  if (websocket._socket[kWebSocket] === void 0) return;
3100
3108
  websocket._socket.removeListener("data", socketOnData);
3101
3109
  process.nextTick(resume, websocket._socket);
@@ -3197,9 +3205,9 @@ var require_websocket = __commonJS({
3197
3205
  }
3198
3206
  });
3199
3207
 
3200
- // ../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/stream.js
3208
+ // ../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/stream.js
3201
3209
  var require_stream = __commonJS({
3202
- "../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/stream.js"(exports, module) {
3210
+ "../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/stream.js"(exports, module) {
3203
3211
  "use strict";
3204
3212
  var WebSocket3 = require_websocket();
3205
3213
  var { Duplex: Duplex2 } = __require("stream");
@@ -3295,9 +3303,9 @@ var require_stream = __commonJS({
3295
3303
  }
3296
3304
  });
3297
3305
 
3298
- // ../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/subprotocol.js
3306
+ // ../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/subprotocol.js
3299
3307
  var require_subprotocol = __commonJS({
3300
- "../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/subprotocol.js"(exports, module) {
3308
+ "../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/subprotocol.js"(exports, module) {
3301
3309
  "use strict";
3302
3310
  var { tokenChars } = require_validation();
3303
3311
  function parse9(header) {
@@ -3340,9 +3348,9 @@ var require_subprotocol = __commonJS({
3340
3348
  }
3341
3349
  });
3342
3350
 
3343
- // ../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/websocket-server.js
3351
+ // ../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/websocket-server.js
3344
3352
  var require_websocket_server = __commonJS({
3345
- "../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/lib/websocket-server.js"(exports, module) {
3353
+ "../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/lib/websocket-server.js"(exports, module) {
3346
3354
  "use strict";
3347
3355
  var EventEmitter = __require("events");
3348
3356
  var http2 = __require("http");
@@ -51203,7 +51211,7 @@ var closeWindow = (window2, atMono, toMs, intervalMs, unit) => {
51203
51211
  var Slug = Schema_exports.String.pipe(
51204
51212
  Schema_exports.check(
51205
51213
  Schema_exports.isPattern(/^[a-z0-9][a-z0-9_-]*$/, {
51206
- message: "Expected a slug: lowercase letters, digits, - and _, starting with a letter or digit (vienna-hq, not Vienna HQ)"
51214
+ message: "Expected a slug: lowercase letters, digits, - and _, starting with a letter or digit (site-1, not Site 1)"
51207
51215
  }),
51208
51216
  Schema_exports.isMaxLength(64)
51209
51217
  )
@@ -51468,6 +51476,10 @@ var mqttConnects = Metric_exports.counter("ot_gateway_mqtt_connects", {
51468
51476
  description: "Connection attempts to the MQTT broker, by outcome",
51469
51477
  incremental: true
51470
51478
  });
51479
+ var mqttSubscribes = Metric_exports.counter("ot_gateway_mqtt_subscribes", {
51480
+ description: "SUBSCRIBE packets sent to the MQTT broker, by outcome",
51481
+ incremental: true
51482
+ });
51471
51483
  var mqttConnected = Metric_exports.gauge("ot_gateway_mqtt_connected", {
51472
51484
  description: "Whether the gateway is connected to the MQTT broker",
51473
51485
  attributes: { unit: "{connection}" }
@@ -51607,6 +51619,9 @@ var toDeviceUnits = (value4, scaling) => {
51607
51619
  };
51608
51620
  var label = (level) => level.length <= 64 ? level : `${level.slice(0, 64)}\u2026`;
51609
51621
  var rejected = (reason, message) => ({ status: "rejected", reason, message });
51622
+ var isId = Schema_exports.is(Slug);
51623
+ var THROTTLED = /* @__PURE__ */ new Set(["unknown-point", "not-writable"]);
51624
+ var SUMMARY_INTERVAL_MS = 6e4;
51610
51625
  var makeCommandGuard = (options3) => {
51611
51626
  const writeTimeout = options3.writeTimeout ?? "10 seconds";
51612
51627
  const maxAgeMillis = Duration_exports.toMillis(Duration_exports.fromInputUnsafe(options3.maxAge ?? "10 seconds"));
@@ -51656,15 +51671,29 @@ var makeCommandGuard = (options3) => {
51656
51671
  )
51657
51672
  );
51658
51673
  });
51674
+ let throttle2;
51675
+ const logThrottled = Effect_exports.fnUntraced(function* (log3, annotations2) {
51676
+ const now2 = yield* monotonicMillis;
51677
+ if (throttle2 === void 0 || now2 - throttle2.loggedAt >= SUMMARY_INTERVAL_MS && throttle2.since === 0) {
51678
+ throttle2 = { loggedAt: now2, since: 0 };
51679
+ return yield* log3;
51680
+ }
51681
+ throttle2.since++;
51682
+ if (now2 - throttle2.loggedAt < SUMMARY_INTERVAL_MS) return;
51683
+ const rejectedSince = throttle2.since;
51684
+ throttle2 = { loggedAt: now2, since: 0 };
51685
+ yield* Effect_exports.logWarning("commands rejected").pipe(Effect_exports.annotateLogs({ ...annotations2, rejected: rejectedSince }));
51686
+ });
51659
51687
  const handle = Effect_exports.fn("Command")(function* (command) {
51660
51688
  const publisher = yield* Publisher;
51661
51689
  const levels = command.topic.startsWith(prefix) ? command.topic.slice(prefix.length).split("/") : [];
51662
51690
  const [deviceId = "", pointId = "", suffix] = levels;
51663
51691
  if (levels.length !== 3 || suffix !== "$set") return;
51664
- const device = options3.devices.find((candidate) => candidate.id === deviceId);
51665
51692
  const ids = { device: label(deviceId), point: label(pointId) };
51666
51693
  yield* Effect_exports.annotateCurrentSpan({ "ot_gateway.device": ids.device, "ot_gateway.point": ids.point });
51667
- const outcome = yield* decide(command, device, pointId);
51694
+ const wellFormed = isId(deviceId) && isId(pointId);
51695
+ const device = wellFormed ? options3.devices.find((candidate) => candidate.id === deviceId) : void 0;
51696
+ const outcome = wellFormed ? yield* decide(command, device, pointId) : rejected("unknown-point", "no such device or point");
51668
51697
  options3.onOutcome?.(ids, outcome);
51669
51698
  const annotations2 = { ...ids, payload: command.payload.slice(0, 200) };
51670
51699
  yield* Metric_exports.update(
@@ -51674,9 +51703,14 @@ var makeCommandGuard = (options3) => {
51674
51703
  }),
51675
51704
  1
51676
51705
  );
51677
- yield* outcome.status === "written" ? Effect_exports.logInfo("command written").pipe(Effect_exports.annotateLogs(annotations2)) : Effect_exports.logWarning(`command ${outcome.status}`).pipe(
51678
- Effect_exports.annotateLogs({ ...annotations2, reason: outcome.reason, message: outcome.message })
51679
- );
51706
+ if (outcome.status === "written") {
51707
+ yield* Effect_exports.logInfo("command written").pipe(Effect_exports.annotateLogs(annotations2));
51708
+ } else {
51709
+ const details = { ...annotations2, reason: outcome.reason, message: outcome.message };
51710
+ const log3 = Effect_exports.logWarning(`command ${outcome.status}`).pipe(Effect_exports.annotateLogs(details));
51711
+ yield* outcome.status === "rejected" && THROTTLED.has(outcome.reason) ? logThrottled(log3, details) : log3;
51712
+ }
51713
+ if (!wellFormed) return;
51680
51714
  const ts = yield* Clock_exports.currentTimeMillis;
51681
51715
  const result4 = outcome.status === "written" ? { status: "written", value: outcome.value } : outcome;
51682
51716
  yield* publisher.publish(`${command.topic}/result`, JSON.stringify({ ...result4, ts }), {
@@ -52989,6 +53023,8 @@ var metaPayload = (point, publish2) => JSON.stringify({
52989
53023
  publish: publish2,
52990
53024
  semantics: point.semantics
52991
53025
  });
53026
+ var nothing = void 0;
53027
+ var PUBLISH_CONCURRENCY = 16;
52992
53028
  var retryPolicy = {
52993
53029
  schedule: Schedule_exports.exponential("200 millis").pipe(Schedule_exports.jittered),
52994
53030
  times: 4
@@ -53062,13 +53098,16 @@ var runDevice = Effect_exports.fn("runDevice")(function* (ctx, driver) {
53062
53098
  yield* publishRecovered(options3?.retain === true ? "metadata" : "values");
53063
53099
  });
53064
53100
  const unpublishedMeta = new Set(driver.points);
53065
- const publishMeta = Effect_exports.forEach(
53066
- [...unpublishedMeta],
53067
- (point) => publishPoint(metaTopic(topicFor(point.id)), metaPayload(point, policyOf(point.id)), { retain: true }).pipe(
53068
- Effect_exports.catchTag("PublishError", skipRefused),
53069
- Effect_exports.andThen(Effect_exports.sync(() => unpublishedMeta.delete(point)))
53070
- ),
53071
- { discard: true }
53101
+ const publishMeta = Effect_exports.suspend(
53102
+ () => Effect_exports.forEach(
53103
+ [...unpublishedMeta],
53104
+ (point) => publishPoint(metaTopic(topicFor(point.id)), metaPayload(point, policyOf(point.id)), { retain: true }).pipe(
53105
+ Effect_exports.catchTag("PublishError", skipRefused),
53106
+ Effect_exports.andThen(Effect_exports.sync(() => unpublishedMeta.delete(point)))
53107
+ ),
53108
+ // A broker failure interrupts the others in flight; what did not get out is retried next cycle.
53109
+ { concurrency: PUBLISH_CONCURRENCY, discard: true }
53110
+ )
53072
53111
  ).pipe(
53073
53112
  // The device is still read: its health is independent of the broker's.
53074
53113
  Effect_exports.catchTag(
@@ -53089,13 +53128,18 @@ var runDevice = Effect_exports.fn("runDevice")(function* (ctx, driver) {
53089
53128
  Effect_exports.annotateLogs({ point: pointId, raw: String(raw3) })
53090
53129
  );
53091
53130
  });
53092
- const handleReading = Effect_exports.fnUntraced(function* (reading, polledSince) {
53131
+ const decideReading = Effect_exports.fnUntraced(function* (reading, polledSince) {
53093
53132
  const point = points2.get(reading.pointId);
53094
- if (point === void 0) return;
53133
+ if (point === void 0) return nothing;
53095
53134
  if (polledSince === void 0) pushedAt.set(point.id, yield* Clock_exports.monotonicTimeNanos);
53096
- else if ((pushedAt.get(point.id) ?? -1n) >= polledSince) return;
53135
+ else if ((pushedAt.get(point.id) ?? -1n) >= polledSince) return nothing;
53097
53136
  const value4 = typeof reading.value === "number" ? applyScaling(reading.value, point.scaling) : reading.value;
53098
- if (typeof value4 === "number" && !Number.isFinite(value4)) return yield* nonFinite(point.id, reading.value);
53137
+ if (typeof value4 === "number" && !Number.isFinite(value4)) {
53138
+ yield* nonFinite(point.id, reading.value);
53139
+ const window2 = windows.get(point.id);
53140
+ if (window2 !== void 0) windows.set(point.id, interruptWindow(window2, yield* monotonicMillis));
53141
+ return nothing;
53142
+ }
53099
53143
  if (nonFinitePoints.delete(point.id)) {
53100
53144
  yield* Effect_exports.logInfo("point delivers numbers again").pipe(Effect_exports.annotateLogs({ point: point.id }));
53101
53145
  }
@@ -53108,34 +53152,43 @@ var runDevice = Effect_exports.fn("runDevice")(function* (ctx, driver) {
53108
53152
  const policy2 = policyOf(point.id);
53109
53153
  switch (policy2.mode) {
53110
53154
  case "sample": {
53111
- if (policy2.intervalMs === void 0) {
53112
- yield* send(point.id, message);
53113
- return;
53114
- }
53155
+ if (policy2.intervalMs === void 0) return { pointId: point.id, message };
53115
53156
  latest.set(point.id, message);
53116
53157
  fresh2.add(point.id);
53117
- return;
53158
+ return nothing;
53118
53159
  }
53119
53160
  case "aggregate": {
53120
53161
  const atMono = yield* monotonicMillis;
53121
53162
  windows.set(point.id, addReading(windows.get(point.id) ?? openWindow(atMono), value4, atMono, reading.timestamp));
53122
- return;
53163
+ return nothing;
53123
53164
  }
53124
53165
  case "change": {
53125
53166
  const atMono = yield* monotonicMillis;
53126
53167
  const sentAt = lastSentAt.get(point.id);
53127
53168
  const quietTooLong = policy2.maxSilenceMs !== void 0 && sentAt !== void 0 && atMono - sentAt >= policy2.maxSilenceMs;
53128
53169
  if (!quietTooLong && !exceedsDeadband(Option_exports.fromUndefinedOr(last2.get(point.id)), value4, policy2.deadband)) {
53129
- return yield* Metric_exports.update(counters.suppressed, 1);
53170
+ yield* Metric_exports.update(counters.suppressed, 1);
53171
+ return nothing;
53130
53172
  }
53131
- if (!(yield* send(point.id, message))) return;
53132
- last2.set(point.id, value4);
53133
- lastSentAt.set(point.id, atMono);
53134
- return;
53173
+ return {
53174
+ pointId: point.id,
53175
+ message,
53176
+ onSent: () => {
53177
+ last2.set(point.id, value4);
53178
+ lastSentAt.set(point.id, atMono);
53179
+ }
53180
+ };
53135
53181
  }
53136
53182
  }
53137
53183
  });
53184
+ const handleReading = Effect_exports.fnUntraced(function* (reading, polledSince) {
53185
+ const outgoing = yield* decideReading(reading, polledSince);
53186
+ if (outgoing === void 0) return;
53187
+ if (yield* send(outgoing.pointId, outgoing.message)) outgoing.onSent?.();
53188
+ });
53189
+ let unavailable2;
53138
53190
  const send = Effect_exports.fnUntraced(function* (pointId, message) {
53191
+ if (unavailable2 !== void 0) return false;
53139
53192
  const sent = yield* publishPoint(pointTopic(topicFor(pointId)), JSON.stringify(message)).pipe(
53140
53193
  Effect_exports.as(true),
53141
53194
  Effect_exports.catchTag("PublishError", (error2) => Effect_exports.as(skipRefused(error2), false))
@@ -53143,15 +53196,30 @@ var runDevice = Effect_exports.fn("runDevice")(function* (ctx, driver) {
53143
53196
  if (sent) yield* Metric_exports.update(counters.published, 1);
53144
53197
  return sent;
53145
53198
  });
53199
+ const publishOutgoing = Effect_exports.fnUntraced(function* (outgoing) {
53200
+ const sent = yield* send(outgoing.pointId, outgoing.message).pipe(
53201
+ Effect_exports.catchTag(
53202
+ "PublishError",
53203
+ (error2) => Effect_exports.sync(() => {
53204
+ unavailable2 ??= error2;
53205
+ return false;
53206
+ })
53207
+ )
53208
+ );
53209
+ if (sent) outgoing.onSent?.();
53210
+ });
53146
53211
  const closeWindows = Effect_exports.fnUntraced(function* (intervalMs, endMs) {
53147
53212
  const atMono = yield* monotonicMillis;
53213
+ let failed;
53148
53214
  for (const point of driver.points) {
53149
53215
  const policy2 = policyOf(point.id);
53150
53216
  if (windowIntervalMs(policy2) !== intervalMs) continue;
53151
53217
  if (policy2.mode === "sample") {
53152
53218
  const message = latest.get(point.id);
53153
- if (message === void 0 || !fresh2.delete(point.id)) continue;
53154
- yield* send(point.id, message);
53219
+ if (message === void 0 || !fresh2.has(point.id) || failed !== void 0) continue;
53220
+ const sent2 = yield* Effect_exports.result(send(point.id, message));
53221
+ if (Result_exports.isFailure(sent2)) failed = sent2.failure;
53222
+ else fresh2.delete(point.id);
53155
53223
  continue;
53156
53224
  }
53157
53225
  const window2 = windows.get(point.id);
@@ -53159,8 +53227,11 @@ var runDevice = Effect_exports.fn("runDevice")(function* (ctx, driver) {
53159
53227
  const closed = closeWindow(window2, atMono, endMs, intervalMs, point.unit);
53160
53228
  windows.set(point.id, closed.next);
53161
53229
  if (closed.message === void 0 || closed.message.count === 0 && deviceProblem !== void 0) continue;
53162
- yield* send(point.id, closed.message);
53230
+ if (failed !== void 0) continue;
53231
+ const sent = yield* Effect_exports.result(send(point.id, closed.message));
53232
+ if (Result_exports.isFailure(sent)) failed = sent.failure;
53163
53233
  }
53234
+ if (failed !== void 0) return yield* failed;
53164
53235
  });
53165
53236
  const interruptWindows = Effect_exports.gen(function* () {
53166
53237
  if (windows.size === 0) return;
@@ -53169,6 +53240,11 @@ var runDevice = Effect_exports.fn("runDevice")(function* (ctx, driver) {
53169
53240
  });
53170
53241
  const handling = yield* Semaphore_exports.make(1);
53171
53242
  const deadlineMs = ctx.cycleTimeoutMs ?? defaultCycleTimeoutMs(ctx.pollIntervalMs);
53243
+ const stageNames = {
53244
+ "poll-cycle": "polling cycle",
53245
+ "pushed-value": "pushed value",
53246
+ "publish-window": "closing a window"
53247
+ };
53172
53248
  const deadline = (stage) => Effect_exports.timeoutOrElse({
53173
53249
  duration: deadlineMs,
53174
53250
  orElse: () => Effect_exports.fail(
@@ -53176,7 +53252,7 @@ var runDevice = Effect_exports.fn("runDevice")(function* (ctx, driver) {
53176
53252
  device: driver.deviceId,
53177
53253
  stage,
53178
53254
  timeoutMs: deadlineMs,
53179
- message: `${stage === "poll-cycle" ? "polling cycle" : "pushed value"} did not finish within ${deadlineMs} ms`
53255
+ message: `${stageNames[stage]} did not finish within ${deadlineMs} ms`
53180
53256
  })
53181
53257
  )
53182
53258
  });
@@ -53192,10 +53268,35 @@ var runDevice = Effect_exports.fn("runDevice")(function* (ctx, driver) {
53192
53268
  const readAt = yield* Clock_exports.currentTimeMillis;
53193
53269
  yield* Metric_exports.update(deviceLastSuccess, readAt / 1e3);
53194
53270
  yield* Effect_exports.annotateCurrentSpan("ot_gateway.readings", readings.length);
53195
- const published = yield* handling.withPermit(Effect_exports.forEach(readings, (reading) => handleReading(reading, polledSince), { discard: true })).pipe(Effect_exports.result);
53271
+ const failedPublish = yield* handling.withPermit(
53272
+ Effect_exports.gen(function* () {
53273
+ unavailable2 = void 0;
53274
+ if (new Set(readings.map((reading) => reading.pointId)).size < readings.length) {
53275
+ for (const reading of readings) {
53276
+ const handled = yield* Effect_exports.result(handleReading(reading, polledSince));
53277
+ if (Result_exports.isFailure(handled)) unavailable2 ??= handled.failure;
53278
+ }
53279
+ return unavailable2;
53280
+ }
53281
+ const outgoing = [];
53282
+ for (const reading of readings) {
53283
+ const decided = yield* decideReading(reading, polledSince);
53284
+ if (decided !== void 0) outgoing.push(decided);
53285
+ }
53286
+ yield* Effect_exports.forEach(outgoing, publishOutgoing, { concurrency: PUBLISH_CONCURRENCY, discard: true });
53287
+ return unavailable2;
53288
+ }).pipe(
53289
+ // Also when the cycle's deadline interrupts it: pushed values and closing windows must not skip publishing.
53290
+ Effect_exports.ensuring(
53291
+ Effect_exports.sync(() => {
53292
+ unavailable2 = void 0;
53293
+ })
53294
+ )
53295
+ )
53296
+ );
53196
53297
  ctx.health?.recordSuccess(driver.deviceId, readAt);
53197
53298
  yield* deviceRecovered;
53198
- if (Result_exports.isFailure(published)) return yield* published.failure;
53299
+ if (failedPublish !== void 0) return yield* failedPublish;
53199
53300
  yield* countCycle("ok");
53200
53301
  }).pipe(
53201
53302
  deadline("poll-cycle"),
@@ -53993,7 +54094,7 @@ var NativeSocket = class {
53993
54094
  // ../../node_modules/.pnpm/@effect+platform-node-shared@4.1.2_effect@4.1.2/node_modules/@effect/platform-node-shared/dist/NodeSocketServer.js
53994
54095
  import * as Net3 from "node:net";
53995
54096
 
53996
- // ../../node_modules/.pnpm/ws@8.22.1/node_modules/ws/wrapper.mjs
54097
+ // ../../node_modules/.pnpm/ws@8.22.2/node_modules/ws/wrapper.mjs
53997
54098
  var import_stream3 = __toESM(require_stream(), 1);
53998
54099
  var import_extension = __toESM(require_extension(), 1);
53999
54100
  var import_permessage_deflate = __toESM(require_permessage_deflate(), 1);
@@ -56097,6 +56198,9 @@ var makeBacnetDriverFromClient = Effect_exports.fn("makeBacnetDriverFromClient")
56097
56198
  let multipleRecheckAt = 0;
56098
56199
  let reprobing = false;
56099
56200
  let cleanCycles = 0;
56201
+ let refusedAt;
56202
+ let largestAnswered = 0;
56203
+ const shrinksLogged = /* @__PURE__ */ new Set();
56100
56204
  let lostCycles = 0;
56101
56205
  let nextBroadcastAt = 0;
56102
56206
  let broadcastBackoffMs = LOCATE_BACKOFF.firstMs;
@@ -56115,6 +56219,9 @@ var makeBacnetDriverFromClient = Effect_exports.fn("makeBacnetDriverFromClient")
56115
56219
  multiple = true;
56116
56220
  reprobing = false;
56117
56221
  cleanCycles = 0;
56222
+ refusedAt = void 0;
56223
+ largestAnswered = 0;
56224
+ shrinksLogged.clear();
56118
56225
  lostCycles = 0;
56119
56226
  broadcastBackoffMs = LOCATE_BACKOFF.firstMs;
56120
56227
  isolated.clear();
@@ -56231,6 +56338,10 @@ var makeBacnetDriverFromClient = Effect_exports.fn("makeBacnetDriverFromClient")
56231
56338
  Effect_exports.annotateLogs({ reason: why, askingAgainInSeconds: RECHECK_MS / 1e3 })
56232
56339
  );
56233
56340
  });
56341
+ const shrinkFrom = (refused) => {
56342
+ const answered = largestAnswered < refused ? largestAnswered : 1;
56343
+ batchSize = Math.max(1, Math.floor(refused / 2), answered);
56344
+ };
56234
56345
  const readBatch = (target, batch) => client.readPropertyMultiple(target, specificationsOf(batch)).pipe(
56235
56346
  Effect_exports.map((results2) => ({ _tag: "Results", results: results2 })),
56236
56347
  Effect_exports.catchTags({
@@ -56276,6 +56387,7 @@ var makeBacnetDriverFromClient = Effect_exports.fn("makeBacnetDriverFromClient")
56276
56387
  reprobing = false;
56277
56388
  yield* Effect_exports.log("device answers ReadPropertyMultiple again");
56278
56389
  }
56390
+ largestAnswered = Math.max(largestAnswered, batch.length);
56279
56391
  const timestamp = yield* Clock_exports.currentTimeMillis;
56280
56392
  const byKey = /* @__PURE__ */ new Map();
56281
56393
  for (const result4 of results2) {
@@ -56372,23 +56484,26 @@ var makeBacnetDriverFromClient = Effect_exports.fn("makeBacnetDriverFromClient")
56372
56484
  continue;
56373
56485
  case "Refused": {
56374
56486
  const { error: error2 } = answer3;
56375
- const full = batch.length === batchSize && batchSize > 1;
56487
+ const several = batch.length > 1;
56376
56488
  const refusal = refusalOf(error2);
56377
56489
  switch (refusal) {
56378
56490
  case "unsupported":
56379
56491
  yield* downgrade(error2.message);
56380
56492
  continue;
56381
56493
  case "too-large":
56382
- if (!full) break;
56383
- batchSize = Math.max(1, Math.floor(batchSize / 2));
56494
+ if (!several) break;
56495
+ refusedAt = Math.min(refusedAt ?? batch.length, batch.length);
56496
+ shrinkFrom(batch.length);
56384
56497
  shrunk = true;
56498
+ if (shrinksLogged.has(batchSize)) continue;
56499
+ shrinksLogged.add(batchSize);
56385
56500
  yield* Effect_exports.log("answer too large for the device, reading fewer points per request").pipe(
56386
56501
  Effect_exports.annotateLogs({ batchSize })
56387
56502
  );
56388
56503
  continue;
56389
56504
  case "busy":
56390
- if (full && outOfRoom(error2)) {
56391
- batchSize = Math.max(1, Math.floor(batchSize / 2));
56505
+ if (several && outOfRoom(error2)) {
56506
+ shrinkFrom(batch.length);
56392
56507
  shrunk = true;
56393
56508
  }
56394
56509
  stop.busy = new DeviceBusy({ message: error2.message });
@@ -56414,14 +56529,15 @@ var makeBacnetDriverFromClient = Effect_exports.fn("makeBacnetDriverFromClient")
56414
56529
  return { outcomes, requests, shrunk, ...stop };
56415
56530
  });
56416
56531
  const regrow = (shrunk) => Effect_exports.suspend(() => {
56417
- if (shrunk || !multiple || batchSize >= largestBatch) {
56532
+ const ceiling = refusedAt === void 0 ? largestBatch : Math.min(largestBatch, refusedAt - 1);
56533
+ if (shrunk || !multiple || batchSize >= ceiling) {
56418
56534
  cleanCycles = 0;
56419
56535
  return Effect_exports.void;
56420
56536
  }
56421
56537
  cleanCycles++;
56422
56538
  if (cleanCycles < REGROW_AFTER_CYCLES) return Effect_exports.void;
56423
56539
  cleanCycles = 0;
56424
- batchSize = Math.min(largestBatch, batchSize * 2);
56540
+ batchSize = refusedAt === void 0 ? Math.min(ceiling, batchSize * 2) : Math.min(batchSize * 2, Math.ceil((batchSize + ceiling) / 2));
56425
56541
  return Effect_exports.log("trying more points per request again").pipe(Effect_exports.annotateLogs({ batchSize }));
56426
56542
  });
56427
56543
  const report = (outcomes) => Effect_exports.forEach(
@@ -56493,6 +56609,8 @@ var makeBacnetDriverFromClient = Effect_exports.fn("makeBacnetDriverFromClient")
56493
56609
  const waitSeconds2 = Math.ceil((busyUntil - now2) / 1e3);
56494
56610
  return yield* fail19("protocol", `device is busy (${busyReason ?? "aborted"}); asking again in ${waitSeconds2} s`);
56495
56611
  }
56612
+ const wasLost = lostCycles > 0;
56613
+ const locatedBefore = location2;
56496
56614
  const target = yield* locate;
56497
56615
  const { outcomes, requests, shrunk, timedOut, busy } = yield* readPoints(target, polled);
56498
56616
  yield* report(outcomes);
@@ -56515,9 +56633,9 @@ var makeBacnetDriverFromClient = Effect_exports.fn("makeBacnetDriverFromClient")
56515
56633
  const reasons = [...new Set(outcomes.flatMap((outcome) => outcome._tag === "Failed" ? [outcome.reason] : []))];
56516
56634
  return yield* fail19("protocol", `no point could be read (${reasons.join(", ")})`);
56517
56635
  }
56518
- if (lostCycles > 0) {
56636
+ if (wasLost) {
56519
56637
  cov?.resync();
56520
- yield* Effect_exports.log("BACnet device answers again");
56638
+ if (target === locatedBefore) yield* Effect_exports.log("BACnet device answers again");
56521
56639
  }
56522
56640
  lostCycles = 0;
56523
56641
  yield* countPointFailures("not_read", notReadPoints);
@@ -58207,11 +58325,11 @@ var decodeConnect = (body) => decodeWith2(body, (r) => {
58207
58325
  if ((flags & 4) !== 0) {
58208
58326
  if (v5) r.properties();
58209
58327
  const topic = r.string();
58210
- const payload = decoder4.decode(r.binary());
58328
+ const payload = r.string();
58211
58329
  will = { topic, payload, qos: flags >> 3 & 1 ? 1 : 0, retain: (flags & 32) !== 0 };
58212
58330
  }
58213
58331
  const username = (flags & 128) !== 0 ? r.string() : void 0;
58214
- const password = (flags & 64) !== 0 ? decoder4.decode(r.binary()) : void 0;
58332
+ const password = (flags & 64) !== 0 ? r.string() : void 0;
58215
58333
  const expiry = properties.get(Property.SessionExpiryInterval);
58216
58334
  const maximumPacketSize = properties.get(Property.MaximumPacketSize);
58217
58335
  return {
@@ -58459,6 +58577,7 @@ var MqttPublishError = class extends Schema_exports.TaggedError()("MqttPublishEr
58459
58577
  };
58460
58578
  var stableConnectionMs = 3e4;
58461
58579
  var maxPubackTimeouts = 2;
58580
+ var SUBACK_TIMEOUT = Duration_exports.seconds(10);
58462
58581
  var defaultMaximumPacketSize = 1024 * 1024;
58463
58582
  var encoder10 = new TextEncoder();
58464
58583
  var lenientDecoder = new TextDecoder();
@@ -58467,6 +58586,7 @@ var numberProperty = (properties, id2, fallback) => {
58467
58586
  return typeof value4 === "number" ? value4 : fallback;
58468
58587
  };
58469
58588
  var countConnect3 = (outcome) => Metric_exports.update(Metric_exports.withAttributes(mqttConnects, { outcome }), 1);
58589
+ var countSubscribe = (outcome) => Metric_exports.update(Metric_exports.withAttributes(mqttSubscribes, { outcome }), 1);
58470
58590
  var topicProblem = (topic) => {
58471
58591
  if (topic.length === 0) return "topic is empty";
58472
58592
  if (topic.includes("+") || topic.includes("#")) return "topic contains a wildcard";
@@ -58652,10 +58772,25 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58652
58772
  );
58653
58773
  if (options3.onConnect !== void 0) yield* Effect_exports.forkScoped(options3.onConnect(client));
58654
58774
  const subscriptions = options3.subscriptions ?? [];
58775
+ const filters = subscriptions.map((subscription) => subscription.filter).join(", ");
58776
+ let pendingSubscribe;
58777
+ let subscribeMissed = false;
58655
58778
  if (subscriptions.length > 0) {
58656
58779
  const packetId = current.nextPacketId;
58657
58780
  current.nextPacketId = packetId % 65535 + 1;
58781
+ pendingSubscribe = packetId;
58658
58782
  yield* write2(encodeSubscribe({ packetId, subscriptions }, dialedWith));
58783
+ yield* Effect_exports.forkScoped(
58784
+ Effect_exports.gen(function* () {
58785
+ yield* Effect_exports.sleep(SUBACK_TIMEOUT);
58786
+ if (pendingSubscribe !== packetId) return;
58787
+ subscribeMissed = true;
58788
+ yield* countSubscribe("missing");
58789
+ yield* Effect_exports.logError(
58790
+ "MQTT broker did not answer the SUBSCRIBE; commands will not arrive on this connection"
58791
+ ).pipe(Effect_exports.annotateLogs({ filters }));
58792
+ })
58793
+ );
58659
58794
  }
58660
58795
  let lastReceived = yield* monotonicMillis;
58661
58796
  const readLoop2 = Effect_exports.gen(function* () {
@@ -58698,7 +58833,19 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58698
58833
  }
58699
58834
  case PacketType.SUBACK: {
58700
58835
  const suback = decodeSuback(packet2.body, dialedWith);
58836
+ if (pendingSubscribe === void 0 || Result_exports.isSuccess(suback) && suback.success.packetId !== pendingSubscribe) {
58837
+ yield* Effect_exports.logDebug("ignored a SUBACK that answers no pending SUBSCRIBE");
58838
+ break;
58839
+ }
58840
+ pendingSubscribe = void 0;
58701
58841
  const refused = Result_exports.isSuccess(suback) ? subscriptions.filter((_, index2) => (suback.success.reasonCodes[index2] ?? 128) >= 128) : subscriptions;
58842
+ const outcome = refused.length > 0 ? "refused" : "granted";
58843
+ yield* countSubscribe(outcome);
58844
+ if (subscribeMissed) {
58845
+ yield* Effect_exports.logInfo("MQTT broker answered the SUBSCRIBE late").pipe(
58846
+ Effect_exports.annotateLogs({ outcome })
58847
+ );
58848
+ }
58702
58849
  if (refused.length > 0) {
58703
58850
  yield* Effect_exports.logError(
58704
58851
  "MQTT broker refused a subscription; nothing published on it will arrive"
@@ -58910,6 +59057,20 @@ var MqttSettingsError = class extends Schema_exports.TaggedError()("MqttSettings
58910
59057
  message: Schema_exports.String
58911
59058
  }) {
58912
59059
  };
59060
+ var readBrokerPassword = (settings) => Effect_exports.gen(function* () {
59061
+ const name = settings.passwordEnv;
59062
+ if (name === void 0) return void 0;
59063
+ return yield* Config_exports.Redacted(name).pipe(
59064
+ Effect_exports.catchTag(
59065
+ "ConfigError",
59066
+ () => Effect_exports.fail(
59067
+ new MqttSettingsError({
59068
+ message: `${name} is not set: the config's mqtt.passwordEnv names it. Put the broker password in ot-gateway.env (${name}=...), or in /etc/ot-gateway/gateway.env under systemd.`
59069
+ })
59070
+ )
59071
+ )
59072
+ );
59073
+ });
58913
59074
  var parseBrokerUrl = (url) => Effect_exports.gen(function* () {
58914
59075
  const parsed = URL.parse(url);
58915
59076
  if (parsed === null) return yield* new MqttSettingsError({ message: "mqtt.url is not a URL" });
@@ -58945,7 +59106,7 @@ var MqttPublisher = (settings, options3 = {}) => Layer_exports.effect(
58945
59106
  Publisher,
58946
59107
  Effect_exports.gen(function* () {
58947
59108
  const address = yield* parseBrokerUrl(settings.url);
58948
- const password = settings.passwordEnv === void 0 ? void 0 : yield* Config_exports.Redacted(settings.passwordEnv);
59109
+ const password = yield* readBrokerPassword(settings);
58949
59110
  const passwordWarning = mqttPasswordWarning(settings);
58950
59111
  if (passwordWarning !== void 0) {
58951
59112
  yield* Effect_exports.logWarning(passwordWarning).pipe(
@@ -58954,7 +59115,7 @@ var MqttPublisher = (settings, options3 = {}) => Layer_exports.effect(
58954
59115
  }
58955
59116
  const openTimeout2 = options3.connectTimeout ?? "10 seconds";
58956
59117
  const socket = options3.network ? yield* options3.network.tcp({ host: address.host, port: address.port, openTimeout: openTimeout2 }) : address.tls ? yield* makeTls({ host: address.host, port: address.port, servername: address.host, openTimeout: openTimeout2 }) : yield* makeNet({ host: address.host, port: address.port, openTimeout: openTimeout2 });
58957
- const { health, network: _network, ...clientOptions } = options3;
59118
+ const { health, network: _network, onConnected, ...clientOptions } = options3;
58958
59119
  const retained = /* @__PURE__ */ new Map();
58959
59120
  let connection = 0;
58960
59121
  const publishRetained = Effect_exports.fnUntraced(function* (client2, topic, payload) {
@@ -58963,6 +59124,8 @@ var MqttPublisher = (settings, options3 = {}) => Layer_exports.effect(
58963
59124
  });
58964
59125
  const onConnect = Effect_exports.fnUntraced(function* (client2) {
58965
59126
  connection++;
59127
+ const info2 = yield* client2.connection;
59128
+ if (info2 !== void 0 && onConnected !== void 0) yield* onConnected(info2);
58966
59129
  if (health !== void 0) {
58967
59130
  yield* publishRetained(client2, health.topic, yield* health.online).pipe(
58968
59131
  Effect_exports.catchTag(
@@ -59049,6 +59212,9 @@ var makeBrokerControl = () => ({
59049
59212
  pubackReason: 0,
59050
59213
  refusedTopics: /* @__PURE__ */ new Set(),
59051
59214
  answerPings: true,
59215
+ ackSubscribes: true,
59216
+ routeMessages: true,
59217
+ refusedFilters: /* @__PURE__ */ new Set(),
59052
59218
  connects: [],
59053
59219
  messages: [],
59054
59220
  retained: /* @__PURE__ */ new Map(),
@@ -59094,6 +59260,7 @@ var accept = (control, message) => {
59094
59260
  control.retained.set(message.topic, message.payload);
59095
59261
  control.retainedMessages.set(message.topic, message);
59096
59262
  }
59263
+ if (!control.routeMessages) return;
59097
59264
  for (const subscriber of control.subscribers) deliver(subscriber, message, false);
59098
59265
  };
59099
59266
  var serveConnection2 = (control) => Effect_exports.fnUntraced(
@@ -59172,17 +59339,24 @@ var serveConnection2 = (control) => Effect_exports.fnUntraced(
59172
59339
  case PacketType.SUBSCRIBE: {
59173
59340
  const subscribe2 = decodeSubscribe(split4.body, subscriber.version);
59174
59341
  if (Result_exports.isFailure(subscribe2) || clientId === void 0) return;
59175
- subscriber.subscriptions.push(...subscribe2.success.subscriptions);
59176
- yield* writer.write(
59177
- encodeSuback(
59178
- {
59179
- packetId: subscribe2.success.packetId,
59180
- reasonCodes: subscribe2.success.subscriptions.map((subscription) => subscription.qos)
59181
- },
59182
- subscriber.version
59183
- )
59342
+ const granted = subscribe2.success.subscriptions.filter(
59343
+ (subscription) => !control.refusedFilters.has(subscription.filter)
59184
59344
  );
59185
- const fresh2 = { ...subscriber, subscriptions: [...subscribe2.success.subscriptions] };
59345
+ subscriber.subscriptions.push(...granted);
59346
+ if (control.ackSubscribes) {
59347
+ yield* writer.write(
59348
+ encodeSuback(
59349
+ {
59350
+ packetId: control.subackPacketId ?? subscribe2.success.packetId,
59351
+ reasonCodes: subscribe2.success.subscriptions.map(
59352
+ (subscription) => control.refusedFilters.has(subscription.filter) ? 135 : subscription.qos
59353
+ )
59354
+ },
59355
+ subscriber.version
59356
+ )
59357
+ );
59358
+ }
59359
+ const fresh2 = { ...subscriber, subscriptions: [...granted] };
59186
59360
  for (const message of control.retainedMessages.values()) deliver(fresh2, message, true);
59187
59361
  subscriber.nextPacketId = fresh2.nextPacketId;
59188
59362
  break;
@@ -59226,8 +59400,8 @@ var paceOf = (speed) => ({
59226
59400
  update: Schedule_exports.spaced(Math.max(50, Math.round(1e3 / speed)))
59227
59401
  });
59228
59402
  var rangeByUnit = {
59229
- "unit:DEG_C": [12, 24],
59230
- "unit:DEG_F": [54, 75],
59403
+ "unit:DEG_C": [25, 40],
59404
+ "unit:DEG_F": [77, 104],
59231
59405
  "unit:PERCENT_RelativeHumidity": [30, 60],
59232
59406
  "unit:PPM": [400, 1200],
59233
59407
  "unit:PA": [100, 400]
@@ -59529,7 +59703,8 @@ var draftDevices = (found, existing = []) => {
59529
59703
  };
59530
59704
  });
59531
59705
  };
59532
- var printable = (name) => name.replace(/[\p{Cc}\p{Cf}]/gu, "?").slice(0, 120);
59706
+ var withoutControls = (text4) => text4.replace(/[\p{Cc}\p{Cf}]/gu, "?");
59707
+ var printable = (name) => withoutControls(name).slice(0, 120);
59533
59708
  var hex = (bytes3) => Array.from(bytes3, (byte) => byte.toString(16).padStart(2, "0")).join(":");
59534
59709
  var sourceText = (source) => printable(
59535
59710
  formatInet(source.address) + (source.network === void 0 ? "" : ` (network ${source.network.network}, address ${hex(source.network.address)})`)
@@ -59640,7 +59815,9 @@ var draftPointsList = (drafts) => {
59640
59815
  var discoverToPointsList = Effect_exports.fn("discoverToPointsList")(function* (config, path, network, options3 = {}) {
59641
59816
  const fs = yield* FileSystem_exports.FileSystem;
59642
59817
  if (yield* fs.exists(path)) {
59643
- return yield* Console_exports.error(`${path} exists; give another file name, or move it away first. Nothing was written.`);
59818
+ return yield* new DiscoverError({
59819
+ message: `${path} exists; give another file name, or move it away first. Nothing was written.`
59820
+ });
59644
59821
  }
59645
59822
  const configured = new Set(config.devices.map((device) => device.id));
59646
59823
  const drafts = yield* discoverDrafts(config, network, options3);
@@ -59651,11 +59828,13 @@ var discoverToPointsList = Effect_exports.fn("discoverToPointsList")(function* (
59651
59828
  );
59652
59829
  }
59653
59830
  const points2 = fresh2.reduce((total, draft) => total + draft.points.length, 0);
59654
- if (points2 === 0) return yield* Console_exports.error(`no points to list; ${path} was not written.`);
59831
+ if (points2 === 0) return yield* new DiscoverError({ message: `no points to list; ${path} was not written.` });
59655
59832
  yield* fs.writeFileString(path, draftPointsList(fresh2), { flag: "wx" });
59656
59833
  yield* Console_exports.error(
59657
59834
  `wrote ${points2} point(s) of ${fresh2.length} device(s) to ${path}. Delete the rows you do not need, then: ot-gateway import ${path}`
59658
59835
  );
59836
+ const written = { path, devices: fresh2.length, points: points2 };
59837
+ return written;
59659
59838
  });
59660
59839
 
59661
59840
  // src/Suggest.ts
@@ -59691,16 +59870,19 @@ var PointsListError = class extends Schema_exports.TaggedError()("PointsListErro
59691
59870
  message: Schema_exports.String
59692
59871
  }) {
59693
59872
  };
59694
- var parseDelimited = (text4, separator) => {
59873
+ var readDelimited = (text4, separator) => {
59695
59874
  const body = text4.replace(/^/, "");
59696
59875
  const firstLine = body.split(/\r?\n/, 1)[0] ?? "";
59697
59876
  const delimiter = separator ?? [";", " ", ","].reduce(
59698
59877
  (best, candidate) => firstLine.split(candidate).length > firstLine.split(best).length ? candidate : best
59699
59878
  );
59700
- const rows = [];
59879
+ const records = [];
59701
59880
  let row = [];
59702
59881
  let field = "";
59703
59882
  let quoted = false;
59883
+ let line = 1;
59884
+ let rowLine = 1;
59885
+ let quoteLine = 1;
59704
59886
  for (let index2 = 0; index2 < body.length; index2++) {
59705
59887
  const char = body[index2];
59706
59888
  if (quoted) {
@@ -59708,24 +59890,36 @@ var parseDelimited = (text4, separator) => {
59708
59890
  field += '"';
59709
59891
  index2++;
59710
59892
  } else if (char === '"') quoted = false;
59711
- else field += char;
59712
- } else if (char === '"' && field === "") quoted = true;
59713
- else if (char === delimiter) {
59893
+ else {
59894
+ field += char;
59895
+ if (char === "\n" || char === "\r" && body[index2 + 1] !== "\n") line++;
59896
+ }
59897
+ } else if (char === '"' && field === "") {
59898
+ quoted = true;
59899
+ quoteLine = line;
59900
+ } else if (char === delimiter) {
59714
59901
  row.push(field);
59715
59902
  field = "";
59716
59903
  } else if (char === "\n" || char === "\r") {
59717
59904
  if (char === "\r" && body[index2 + 1] === "\n") index2++;
59718
59905
  row.push(field);
59719
- rows.push(row);
59906
+ records.push({ line: rowLine, fields: row });
59720
59907
  row = [];
59721
59908
  field = "";
59909
+ line++;
59910
+ rowLine = line;
59722
59911
  } else field += char;
59723
59912
  }
59724
- if (field !== "" || row.length > 0) {
59913
+ if (field !== "" || row.length > 0 || quoted) {
59725
59914
  row.push(field);
59726
- rows.push(row);
59915
+ records.push({ line: rowLine, fields: row });
59727
59916
  }
59728
- return rows.filter((fields) => fields.some((value4) => value4.trim() !== ""));
59917
+ const filled = records.filter((record2) => record2.fields.some((value4) => value4.trim() !== ""));
59918
+ return quoted ? Result_exports.fail({ line: quoteLine, records: filled }) : Result_exports.succeed(filled);
59919
+ };
59920
+ var parseDelimited = (text4, separator) => {
59921
+ const read3 = readDelimited(text4, separator);
59922
+ return (Result_exports.isSuccess(read3) ? read3.success : read3.failure.records).map((record2) => record2.fields);
59729
59923
  };
59730
59924
  var units = {
59731
59925
  w: "unit:W",
@@ -59785,6 +59979,29 @@ var columnAliases = {
59785
59979
  publish_interval_s: "publish_s",
59786
59980
  publish_every_s: "publish_s"
59787
59981
  };
59982
+ var readColumns = [
59983
+ "device",
59984
+ "point",
59985
+ "unit",
59986
+ "interval_s",
59987
+ "publish",
59988
+ "publish_s",
59989
+ "deadband",
59990
+ "scale",
59991
+ "offset",
59992
+ "host",
59993
+ "port",
59994
+ "unit_id",
59995
+ "profile",
59996
+ "register",
59997
+ "table",
59998
+ "type",
59999
+ "byte_order",
60000
+ "device_instance",
60001
+ "address",
60002
+ "object_type",
60003
+ "object_instance"
60004
+ ];
59788
60005
  var columnName = (header) => {
59789
60006
  const normal = header.trim().toLowerCase().replace(/[\s-]+/g, "_");
59790
60007
  return columnAliases[normal] ?? normal;
@@ -59946,11 +60163,15 @@ var namedPoints = Effect_exports.fnUntraced(function* (name, rows) {
59946
60163
  }
59947
60164
  return points2;
59948
60165
  });
59949
- var toDevice = Effect_exports.fnUntraced(function* (name, rows, taken) {
60166
+ var toDevice = Effect_exports.fnUntraced(function* (name, rows, inConfig, listed) {
59950
60167
  const id2 = slugify(name);
59951
60168
  if (id2 === "") return yield* fail17(`device "${name}": its name has no letters or digits`);
59952
- if (taken.has(id2)) return yield* fail17(`device id "${id2}" is already in the config`);
59953
- taken.add(id2);
60169
+ if (inConfig.has(id2)) return yield* fail17(`device id "${id2}" is already in the config`);
60170
+ const earlier = listed.get(id2);
60171
+ if (earlier !== void 0) {
60172
+ return yield* fail17(`"${earlier}" and "${name}" are the same device id "${id2}"; use one spelling`);
60173
+ }
60174
+ listed.set(id2, name);
59954
60175
  const points2 = yield* namedPoints(name, rows);
59955
60176
  const intervalSeconds = yield* deviceNumber(name, rows, "interval_s");
59956
60177
  const pollIntervalMs2 = intervalSeconds === void 0 ? {} : { pollIntervalMs: Math.round(intervalSeconds * 1e3) };
@@ -59983,16 +60204,34 @@ var toDevice = Effect_exports.fnUntraced(function* (name, rows, taken) {
59983
60204
  return yield* fail17(`device "${name}": give it a host (Modbus TCP) or a device_instance (BACnet/IP)`);
59984
60205
  });
59985
60206
  var devicesFromPointsList = Effect_exports.fn("devicesFromPointsList")(function* (text4, existing = [], profiles2 = /* @__PURE__ */ new Map()) {
59986
- const [header, ...records] = parseDelimited(text4);
59987
- if (header === void 0) return yield* fail17("the points list is empty");
60207
+ const read3 = readDelimited(text4);
60208
+ if (Result_exports.isFailure(read3)) return yield* fail17(`line ${read3.failure.line}: a quote opened here is never closed`);
60209
+ const [headerRecord, ...records] = read3.success;
60210
+ if (headerRecord === void 0) return yield* fail17("the points list is empty");
60211
+ const header = headerRecord.fields;
59988
60212
  const columns = header.map(columnName);
59989
60213
  for (const required2 of ["device", "point"]) {
59990
60214
  if (!columns.includes(required2)) {
59991
60215
  return yield* fail17(`the points list needs a "${required2}" column; its header has ${header.join(", ")}`);
59992
60216
  }
59993
60217
  }
59994
- const rows = records.map((fields, index2) => ({
59995
- line: index2 + 2,
60218
+ for (const [index2, column] of columns.entries()) {
60219
+ const first = columns.indexOf(column);
60220
+ if (readColumns.includes(column) && first !== index2) {
60221
+ return yield* fail17(
60222
+ `the header has both "${header[first]?.trim()}" and "${header[index2]?.trim()}", which are the same column`
60223
+ );
60224
+ }
60225
+ }
60226
+ for (const record2 of records) {
60227
+ if (record2.fields.slice(header.length).some((value4) => value4.trim() !== "")) {
60228
+ return yield* fail17(
60229
+ `line ${record2.line}: ${record2.fields.length} fields, but the header has ${header.length} columns; a value containing the delimiter (a decimal comma, say) needs quotes`
60230
+ );
60231
+ }
60232
+ }
60233
+ const rows = records.map(({ line, fields }) => ({
60234
+ line,
59996
60235
  get: (column) => {
59997
60236
  const value4 = fields[columns.indexOf(column)]?.trim();
59998
60237
  return value4 === void 0 || value4 === "" ? void 0 : value4;
@@ -60004,8 +60243,9 @@ var devicesFromPointsList = Effect_exports.fn("devicesFromPointsList")(function*
60004
60243
  if (device === void 0) return yield* fail17(`line ${row.line}: no device`);
60005
60244
  byDevice.set(device, [...byDevice.get(device) ?? [], ...yield* expandProfile(row, profiles2)]);
60006
60245
  }
60007
- const taken = new Set(existing);
60008
- return yield* Effect_exports.forEach(byDevice, ([name, deviceRows]) => toDevice(name, deviceRows, taken));
60246
+ const inConfig = new Set(existing);
60247
+ const listed = /* @__PURE__ */ new Map();
60248
+ return yield* Effect_exports.forEach(byDevice, ([name, deviceRows]) => toDevice(name, deviceRows, inConfig, listed));
60009
60249
  });
60010
60250
 
60011
60251
  // src/Ede.ts
@@ -60032,8 +60272,12 @@ var edeToPointsList = Effect_exports.fn("edeToPointsList")(function* (text4) {
60032
60272
  const delimiter = [";", " ", ","].reduce(
60033
60273
  (best, candidate) => headerText.split(candidate).length > headerText.split(best).length ? candidate : best
60034
60274
  );
60035
- const [header = [], ...records] = parseDelimited(lines2.slice(start).join("\n"), delimiter);
60036
- const columns = header.map(headerKey);
60275
+ const read3 = readDelimited(lines2.slice(start).join("\n"), delimiter);
60276
+ if (Result_exports.isFailure(read3)) {
60277
+ return yield* fail18(`EDE line ${start + read3.failure.line}: a quote opened here is never closed`);
60278
+ }
60279
+ const [headerRecord, ...records] = read3.success;
60280
+ const columns = (headerRecord?.fields ?? []).map(headerKey);
60037
60281
  const column = (name) => columns.indexOf(name);
60038
60282
  const at = {
60039
60283
  device: column("deviceobjinstance"),
@@ -60051,8 +60295,9 @@ var edeToPointsList = Effect_exports.fn("edeToPointsList")(function* (text4) {
60051
60295
  if (index2 < 0) return yield* fail18(`the EDE header has no ${name} column`);
60052
60296
  }
60053
60297
  const objects = [];
60054
- for (const [index2, fields] of records.entries()) {
60055
- const line = start + index2 + 2;
60298
+ for (const record2 of records) {
60299
+ const line = start + record2.line;
60300
+ const fields = record2.fields;
60056
60301
  if ((fields[0] ?? "").trim().startsWith("#")) continue;
60057
60302
  const field = (position) => (fields[position] ?? "").trim();
60058
60303
  const device = Number(field(at.device));
@@ -60218,7 +60463,7 @@ var pointsListRules = [
60218
60463
  "CSV with a header row and one row per point; commas, semicolons or tabs, as the header line uses",
60219
60464
  "Column names in any order and case; spaces and - count as _; unknown columns are named and ignored",
60220
60465
  "A row with host is Modbus TCP, a row with device_instance is BACnet/IP; one list can hold both",
60221
- "A decimal comma is read as a point",
60466
+ "A decimal comma is read as a point; a value that contains the delimiter (1,5 in a comma-separated list) goes in double quotes",
60222
60467
  "A row with a profile takes its registers from the profile; its other columns (unit, scale, byte_order, publish) still win",
60223
60468
  "A BACnet EDE file (the semicolon CSV engineering tools export) is read as a list too; points from-ede shows it as one",
60224
60469
  "Nothing is made writable: writes are set in the config, on purpose"
@@ -60262,7 +60507,7 @@ var describePointsListSchema = () => {
60262
60507
  };
60263
60508
  var templateRows = [
60264
60509
  {
60265
- device: "Main meter",
60510
+ device: "Energy meter",
60266
60511
  point: "Active power",
60267
60512
  unit: "kW",
60268
60513
  interval_s: "5",
@@ -60274,7 +60519,7 @@ var templateRows = [
60274
60519
  byte_order: "CDAB"
60275
60520
  },
60276
60521
  {
60277
- device: "Main meter",
60522
+ device: "Energy meter",
60278
60523
  point: "Energy",
60279
60524
  unit: "kWh",
60280
60525
  interval_s: "5",
@@ -60296,8 +60541,8 @@ var templateRows = [
60296
60541
  profile: "eastron-sdm630"
60297
60542
  },
60298
60543
  {
60299
- device: "AHU 2",
60300
- point: "Supply air temperature",
60544
+ device: "Heat pump",
60545
+ point: "Flow temperature",
60301
60546
  unit: "\xB0C",
60302
60547
  interval_s: "30",
60303
60548
  deadband: "0.2",
@@ -60306,8 +60551,8 @@ var templateRows = [
60306
60551
  object_instance: "1"
60307
60552
  },
60308
60553
  {
60309
- device: "AHU 2",
60310
- point: "Fan running",
60554
+ device: "Heat pump",
60555
+ point: "Compressor running",
60311
60556
  interval_s: "30",
60312
60557
  publish: "change",
60313
60558
  device_instance: "2001",
@@ -60559,22 +60804,22 @@ var simulatedDevice = {
60559
60804
  pollIntervalMs: 2e3,
60560
60805
  points: [
60561
60806
  {
60562
- id: "supply-air-temp",
60563
- name: "Simulated supply air temperature",
60807
+ id: "flow-temp",
60808
+ name: "Simulated flow temperature",
60564
60809
  unit: "unit:DEG_C",
60565
60810
  deadband: 0.2,
60566
60811
  waveform: "sine",
60567
- min: 16,
60568
- max: 22,
60812
+ min: 30,
60813
+ max: 38,
60569
60814
  periodSeconds: 60
60570
60815
  },
60571
60816
  {
60572
- id: "fan-speed",
60573
- name: "Simulated fan speed",
60574
- unit: "unit:PERCENT",
60817
+ id: "power",
60818
+ name: "Simulated power",
60819
+ unit: "unit:KiloW",
60575
60820
  waveform: "ramp",
60576
60821
  min: 0,
60577
- max: 100,
60822
+ max: 8,
60578
60823
  periodSeconds: 30
60579
60824
  }
60580
60825
  ]
@@ -60604,7 +60849,7 @@ var lanInterfaces = (interfaces) => Object.entries(interfaces).flatMap(
60604
60849
  return [{ name, address: info2.address, broadcast: broadcast2 }];
60605
60850
  })
60606
60851
  );
60607
- var slugMessage = "lowercase letters, digits, - and _, starting with a letter or digit (vienna-hq, not Vienna HQ)";
60852
+ var slugMessage = "lowercase letters, digits, - and _, starting with a letter or digit (site-1, not Site 1)";
60608
60853
  var validSlug = (value4) => Schema_exports.is(Slug)(value4) ? Effect_exports.succeed(value4) : Effect_exports.fail(slugMessage);
60609
60854
  var validBrokerUrl = (value4) => parseBrokerUrl(value4).pipe(
60610
60855
  Effect_exports.as(value4),
@@ -60719,7 +60964,7 @@ var devicesFrom = Effect_exports.fn("devicesFrom")(function* (source, answers, f
60719
60964
  }
60720
60965
  return usable;
60721
60966
  });
60722
- var runInit = Effect_exports.fn("runInit")(function* (path, flags = {}) {
60967
+ var runInit = Effect_exports.fn("runInit")(function* (path, flags = {}, lans = () => lanInterfaces(networkInterfaces2())) {
60723
60968
  const fs = yield* FileSystem_exports.FileSystem;
60724
60969
  const yes = flags.yes === true;
60725
60970
  if (flags.points !== void 0 && flags.devices !== void 0 && flags.devices !== "list") {
@@ -60734,8 +60979,12 @@ var runInit = Effect_exports.fn("runInit")(function* (path, flags = {}) {
60734
60979
  const building = yield* slug("building", flags.building, yes, "Building (the second)", "main");
60735
60980
  const answers = { site, building, brokerUrl: yield* brokerUrl(flags), login: yield* login(flags) };
60736
60981
  const source = flags.points === void 0 ? flags.devices ?? (yes ? "simulated" : yield* deviceSource) : "list";
60737
- const withNetwork = source === "discover" ? { ...answers, broadcastAddress: yield* broadcastAddress(lanInterfaces(networkInterfaces2()), flags) } : answers;
60738
- const text4 = `${JSON.stringify(initConfig(withNetwork, yield* devicesFrom(source, withNetwork, flags)), null, 2)}
60982
+ const network = (answersSoFar) => broadcastAddress(lans(), flags).pipe(Effect_exports.map((address) => ({ ...answersSoFar, broadcastAddress: address })));
60983
+ const beforeDevices = source === "discover" ? yield* network(answers) : { ...answers, broadcastAddress: flags.broadcast };
60984
+ const devices = yield* devicesFrom(source, beforeDevices, flags);
60985
+ const located = (device) => device.protocol !== "bacnet-ip" || "address" in device;
60986
+ const withNetwork = beforeDevices.broadcastAddress === void 0 && !devices.every(located) ? yield* network(beforeDevices) : beforeDevices;
60987
+ const text4 = `${JSON.stringify(initConfig(withNetwork, devices), null, 2)}
60739
60988
  `;
60740
60989
  const config = yield* parseConfig2(text4);
60741
60990
  if (flags.dryRun === true) return config;
@@ -71022,6 +71271,8 @@ var DeviceStatus = Schema_exports.Struct({
71022
71271
  /** Why the device is failing (the health topic's reason). */
71023
71272
  reason: Schema_exports.optionalKey(Schema_exports.String),
71024
71273
  lastSuccess: Schema_exports.optionalKey(Schema_exports.Number),
71274
+ /** How many points the config gives it, also when `points` is left out (`/api/status?points=none`). */
71275
+ pointCount: Schema_exports.Number,
71025
71276
  points: Schema_exports.Array(PointStatus)
71026
71277
  });
71027
71278
  var CommandStatus = Schema_exports.Struct({
@@ -71068,6 +71319,41 @@ var MessageStatus = Schema_exports.Struct({
71068
71319
  /** Messages on this topic since the gateway started. */
71069
71320
  count: Schema_exports.Number
71070
71321
  });
71322
+ var BrokerConnection = Schema_exports.Struct({
71323
+ protocolVersion: Schema_exports.Literals(["5", "3.1.1"]),
71324
+ maximumQoS: Schema_exports.Literals([0, 1]),
71325
+ retainAvailable: Schema_exports.Boolean,
71326
+ /** Seconds between pings, the broker's if it set one. */
71327
+ keepAliveSeconds: Schema_exports.Number,
71328
+ /** Unacknowledged QoS 1 publishes the gateway allows itself. */
71329
+ receiveMaximum: Schema_exports.Number,
71330
+ /** Bytes; absent when the broker announced no limit. */
71331
+ maximumPacketSize: Schema_exports.optionalKey(Schema_exports.Number)
71332
+ });
71333
+ var BrokerStatus = Schema_exports.Struct({
71334
+ url: Schema_exports.String,
71335
+ connected: Schema_exports.Boolean,
71336
+ /** Unix ms of the latest successful connect, and what the broker allowed then; absent before the first. */
71337
+ connectedAt: Schema_exports.optionalKey(Schema_exports.Number),
71338
+ connection: Schema_exports.optionalKey(BrokerConnection),
71339
+ /** Successful connects (the first one and every reconnect), and attempts that failed or the broker refused. */
71340
+ connects: Schema_exports.Number,
71341
+ failedConnects: Schema_exports.Number,
71342
+ /** Point values published, and messages that could not be published (without a buffer, those are lost). */
71343
+ published: Schema_exports.Number,
71344
+ publishFailures: Schema_exports.Number
71345
+ });
71346
+ var BufferStatus = Schema_exports.Struct({
71347
+ path: Schema_exports.String,
71348
+ rows: Schema_exports.Number,
71349
+ maxRows: Schema_exports.Number,
71350
+ dropped: Schema_exports.Number,
71351
+ written: Schema_exports.Number,
71352
+ delivered: Schema_exports.Number,
71353
+ droppedBy: Schema_exports.Record(Schema_exports.String, Schema_exports.Number),
71354
+ failures: Schema_exports.Number,
71355
+ disabled: Schema_exports.Boolean
71356
+ });
71071
71357
  var GatewayStatus = Schema_exports.Struct({
71072
71358
  site: Schema_exports.String,
71073
71359
  building: Schema_exports.String,
@@ -71075,25 +71361,52 @@ var GatewayStatus = Schema_exports.Struct({
71075
71361
  /** Unix ms when the gateway started, and when this snapshot was taken. */
71076
71362
  since: Schema_exports.Number,
71077
71363
  now: Schema_exports.Number,
71078
- broker: Schema_exports.Struct({ url: Schema_exports.String, connected: Schema_exports.Boolean }),
71079
- /**
71080
- * Absent without a `buffer` in the config. `rows` wait for the broker, out of `maxRows`; `dropped` counts the
71081
- * messages the buffer gave up on since the gateway started (overflow past `maxRows`, refused, unreadable, ...).
71082
- */
71083
- buffer: Schema_exports.optionalKey(
71084
- Schema_exports.Struct({ path: Schema_exports.String, rows: Schema_exports.Number, maxRows: Schema_exports.Number, dropped: Schema_exports.Number })
71085
- ),
71364
+ broker: BrokerStatus,
71365
+ /** Absent without a `buffer` in the config. */
71366
+ buffer: Schema_exports.optionalKey(BufferStatus),
71086
71367
  /** Absent until the host monitor's first sample. */
71087
71368
  host: Schema_exports.optionalKey(HostStatus),
71088
71369
  devices: Schema_exports.Array(DeviceStatus),
71089
71370
  /** The most recent commands, newest first. */
71090
71371
  commands: Schema_exports.Array(CommandStatus)
71091
71372
  });
71373
+ var PointReading = Schema_exports.Struct({
71374
+ device: Schema_exports.String,
71375
+ point: Schema_exports.String,
71376
+ value: Schema_exports.optionalKey(Schema_exports.Union([Schema_exports.Number, Schema_exports.Boolean])),
71377
+ ts: Schema_exports.optionalKey(Schema_exports.Number)
71378
+ });
71379
+ var PointReadings = Schema_exports.Struct({ readings: Schema_exports.Array(PointReading) });
71380
+ var MAX_VALUES_PER_REQUEST = 500;
71381
+ var ValuesQueryInvalid = class extends Schema_exports.TaggedError()(
71382
+ "ValuesQueryInvalid",
71383
+ { message: Schema_exports.String },
71384
+ { httpApiStatus: 400 }
71385
+ ) {
71386
+ };
71092
71387
  var Messages = Schema_exports.Struct({
71093
71388
  messages: Schema_exports.Array(MessageStatus),
71094
71389
  /** Topics left out because the gateway keeps at most this many. */
71095
71390
  droppedTopics: Schema_exports.Number
71096
71391
  });
71392
+ var PointInfo = Schema_exports.Struct({
71393
+ device: Schema_exports.String,
71394
+ id: Schema_exports.String,
71395
+ name: Schema_exports.String,
71396
+ unit: Schema_exports.optionalKey(Schema_exports.String),
71397
+ writable: Schema_exports.Boolean,
71398
+ /** The MQTT topic its values go to (`site/building/device/point`). */
71399
+ topic: Schema_exports.String,
71400
+ /** Where the gateway reads it, in the config's words: `holding 40 · float32 CDAB`, `analog-input 3 · present-value`. */
71401
+ source: Schema_exports.String,
71402
+ /** How its values go out: `every read`, `on change ≥ 0.5`, `aggregate every 15 min`. */
71403
+ publish: Schema_exports.String,
71404
+ limits: Schema_exports.optionalKey(Schema_exports.Struct({ min: Schema_exports.Number, max: Schema_exports.Number })),
71405
+ scaling: Schema_exports.optionalKey(Schema_exports.Struct({ factor: Schema_exports.Number, offset: Schema_exports.Number })),
71406
+ brick: Schema_exports.optionalKey(Schema_exports.String),
71407
+ haystack: Schema_exports.optionalKey(Schema_exports.Array(Schema_exports.String))
71408
+ });
71409
+ var PointCatalog = Schema_exports.Struct({ points: Schema_exports.Array(PointInfo) });
71097
71410
  var HistoryBucket = Schema_exports.Struct({
71098
71411
  t: Schema_exports.Number,
71099
71412
  min: Schema_exports.Number,
@@ -71122,7 +71435,36 @@ var HistoryQueryInvalid = class extends Schema_exports.TaggedError()(
71122
71435
  { httpApiStatus: 400 }
71123
71436
  ) {
71124
71437
  };
71125
- var StatusGroup = class extends HttpApiGroup_exports.make("status").add(HttpApiEndpoint_exports.get("status", "/api/status", { success: GatewayStatus })).add(HttpApiEndpoint_exports.get("messages", "/api/messages", { success: Messages })).add(
71438
+ var ConfigEntry = Schema_exports.Struct({ key: Schema_exports.String, value: Schema_exports.Json });
71439
+ var ConfigView = Schema_exports.Struct({
71440
+ sections: Schema_exports.Array(Schema_exports.Struct({ key: Schema_exports.String, entries: Schema_exports.Array(ConfigEntry) })),
71441
+ devices: Schema_exports.Array(
71442
+ Schema_exports.Struct({
71443
+ id: Schema_exports.String,
71444
+ protocol: Schema_exports.String,
71445
+ pointCount: Schema_exports.Number,
71446
+ entries: Schema_exports.Array(ConfigEntry)
71447
+ })
71448
+ )
71449
+ });
71450
+ var StatusGroup = class extends HttpApiGroup_exports.make("status").add(
71451
+ HttpApiEndpoint_exports.get("status", "/api/status", {
71452
+ query: {
71453
+ /** `none` leaves each device's `points` empty: health without every value, for a page that pages them. */
71454
+ points: Schema_exports.optional(Schema_exports.Literals(["all", "none"]))
71455
+ },
71456
+ success: GatewayStatus
71457
+ })
71458
+ ).add(
71459
+ HttpApiEndpoint_exports.get("values", "/api/values", {
71460
+ query: {
71461
+ /** Comma-separated `device/point` keys (ids are slugs, so neither has a comma or a slash). */
71462
+ points: Schema_exports.String
71463
+ },
71464
+ success: PointReadings,
71465
+ error: ValuesQueryInvalid
71466
+ })
71467
+ ).add(HttpApiEndpoint_exports.get("messages", "/api/messages", { success: Messages })).add(HttpApiEndpoint_exports.get("points", "/api/points", { success: PointCatalog })).add(HttpApiEndpoint_exports.get("config", "/api/config", { success: ConfigView })).add(
71126
71468
  HttpApiEndpoint_exports.get("history", "/api/history", {
71127
71469
  query: {
71128
71470
  device: Schema_exports.String,
@@ -71630,13 +71972,13 @@ var formatStatus = (status3) => {
71630
71972
  ...status3.devices.map((device) => {
71631
71973
  const lastRead = device.lastSuccess === void 0 ? "no read yet" : `read ${ago(status3.now - device.lastSuccess)} ago`;
71632
71974
  const reason = device.reason === void 0 ? "" : ` (${device.reason})`;
71633
- return ` ${device.id.padEnd(width3)} ${device.status.padEnd(8)} ${device.protocol}, ${device.points.length} point(s), ${lastRead}${reason}`;
71975
+ return ` ${device.id.padEnd(width3)} ${device.status.padEnd(8)} ${device.protocol}, ${device.pointCount} point(s), ${lastRead}${reason}`;
71634
71976
  })
71635
71977
  ].join("\n");
71636
71978
  };
71637
71979
  var advice = "Is the gateway running (ot-gateway run, or ot-gateway demo)? If its status page is elsewhere, pass --url.";
71638
- var fetchGatewayStatus = (url) => HttpApiClient_exports.make(OtGatewayApi, { baseUrl: url }).pipe(
71639
- Effect_exports.flatMap((client) => client.status.status()),
71980
+ var fetchGatewayStatus = (url, points2 = "all") => HttpApiClient_exports.make(OtGatewayApi, { baseUrl: url }).pipe(
71981
+ Effect_exports.flatMap((client) => client.status.status({ query: { points: points2 } })),
71640
71982
  Effect_exports.provide(FetchHttpClient_exports.layer),
71641
71983
  // Unreachable, a timeout or an answer that does not decode: the same advice for each.
71642
71984
  Effect_exports.mapError(
@@ -71648,7 +71990,7 @@ var fetchGatewayStatus = (url) => HttpApiClient_exports.make(OtGatewayApi, { bas
71648
71990
  })
71649
71991
  );
71650
71992
  var statusReport = Effect_exports.fn("statusReport")(function* (url, options3 = {}) {
71651
- const status3 = yield* fetchGatewayStatus(url);
71993
+ const status3 = yield* fetchGatewayStatus(url, options3.json === true ? "all" : "none");
71652
71994
  yield* options3.json === true ? printJson(status3) : Console_exports.log(formatStatus(status3));
71653
71995
  });
71654
71996
 
@@ -71662,7 +72004,7 @@ var BrokerCommandError = class extends Schema_exports.TaggedError()("BrokerComma
71662
72004
  var randomSuffix = Effect_exports.map(Random_exports.nextIntBetween(0, 16777215), (value4) => value4.toString(16).padStart(6, "0"));
71663
72005
  var brokerClient = Effect_exports.fn("brokerClient")(function* (settings, role, options3 = {}) {
71664
72006
  const address = yield* parseBrokerUrl(settings.url);
71665
- const password = settings.passwordEnv === void 0 ? void 0 : yield* Config_exports.Redacted(settings.passwordEnv);
72007
+ const password = yield* readBrokerPassword(settings);
71666
72008
  const openTimeout2 = "10 seconds";
71667
72009
  const socket = address.tls ? yield* makeTls({ host: address.host, port: address.port, servername: address.host, openTimeout: openTimeout2 }) : yield* makeNet({ host: address.host, port: address.port, openTimeout: openTimeout2 });
71668
72010
  return yield* makeMqttClient(socket, {
@@ -71687,6 +72029,7 @@ var firstDialOf = (client, url) => client.firstDial.pipe(
71687
72029
  )
71688
72030
  )
71689
72031
  );
72032
+ var topicRoot = (topic) => topic.split("/").slice(0, 2).join("/");
71690
72033
  var brokerWarnings = (info2, roundTripMs, topic) => [
71691
72034
  ...info2.protocolVersion === "3.1.1" ? [
71692
72035
  "MQTT 3.1.1: the broker announces no limits, commands get no correlation data and messages no expiry (docs/configuration.md, mqtt.version)"
@@ -71694,7 +72037,7 @@ var brokerWarnings = (info2, roundTripMs, topic) => [
71694
72037
  ...info2.retainAvailable ? [] : ["the broker keeps no retained messages: $meta and health reach only clients connected at the time"],
71695
72038
  ...info2.maximumQoS === 0 ? ["the broker allows QoS 0 only: nothing confirms that a message arrived, so the buffer cannot help"] : [],
71696
72039
  ...roundTripMs === void 0 ? [
71697
- `a message to ${topic} did not come back within ${ROUND_TRIP_TIMEOUT}: the broker's ACL may not let this user publish or subscribe there`
72040
+ `a message to ${topic} did not come back within ${ROUND_TRIP_TIMEOUT}: check the broker's access rules (ACL) for this user under ${topicRoot(topic)}/#; they must allow both publishing and subscribing there (the gateway subscribes for commands and its own retained messages)`
71698
72041
  ] : []
71699
72042
  ];
71700
72043
  var checkBroker = Effect_exports.fn("checkBroker")(function* (config) {
@@ -71725,7 +72068,7 @@ var checkBroker = Effect_exports.fn("checkBroker")(function* (config) {
71725
72068
  onSome: (at) => Math.max(0, at - sentAt)
71726
72069
  });
71727
72070
  const report = {
71728
- ok: true,
72071
+ ok: roundTripMs !== void 0,
71729
72072
  broker: config.mqtt.url,
71730
72073
  ...info2,
71731
72074
  ...roundTripMs === void 0 ? {} : { roundTripMs },
@@ -71741,21 +72084,27 @@ var formatBrokerReport = (report) => [
71741
72084
  report.roundTripMs === void 0 ? ` round trip: NO ANSWER within ${ROUND_TRIP_TIMEOUT}` : ` round trip: ${report.roundTripMs} ms (QoS 1, through ${report.roundTripTopic})`,
71742
72085
  ...report.warnings.map((warning) => ` warning: ${warning}`)
71743
72086
  ].join("\n");
72087
+ var roundTripFailure = (report) => new BrokerCommandError({
72088
+ message: `${report.broker}: a message to ${report.roundTripTopic} did not come back within ${ROUND_TRIP_TIMEOUT}; see the warning above`
72089
+ });
71744
72090
  var publishOnce = Effect_exports.fn("publishOnce")(function* (config, topic, payload, options3) {
71745
72091
  const client = yield* brokerClient(config.mqtt, "publish");
71746
72092
  yield* firstDialOf(client, config.mqtt.url);
72093
+ const connection = yield* client.connection;
72094
+ const qos = options3.qos === 1 && (connection?.maximumQoS ?? 1) === 1 ? 1 : 0;
71747
72095
  yield* client.publish(topic, payload, { qos: options3.qos, retain: options3.retain }).pipe(Effect_exports.mapError((error2) => new BrokerCommandError({ message: `${topic}: ${error2.message}` })));
71748
72096
  return {
71749
72097
  ok: true,
71750
72098
  broker: config.mqtt.url,
71751
72099
  topic,
71752
72100
  bytes: new TextEncoder().encode(payload).length,
71753
- qos: options3.qos,
72101
+ qos,
72102
+ ...qos === options3.qos ? {} : { requestedQos: options3.qos },
71754
72103
  retain: options3.retain,
71755
72104
  cleared: options3.retain && payload === ""
71756
72105
  };
71757
72106
  }, Effect_exports.scoped);
71758
- var formatPublished = (result4) => result4.cleared ? `cleared the retained message on ${result4.topic}` : `published ${result4.bytes} byte(s) to ${result4.topic} (QoS ${result4.qos}${result4.retain ? ", retained" : ""})`;
72107
+ var formatPublished = (result4) => result4.cleared ? `cleared the retained message on ${result4.topic}` : `published ${result4.bytes} byte(s) to ${result4.topic} (QoS ${result4.qos}${result4.requestedQos === void 0 ? "" : ": the broker allows QoS 0 only"}${result4.retain ? ", retained" : ""})`;
71759
72108
 
71760
72109
  // src/Watch.ts
71761
72110
  var MAX_PAYLOAD = 300;
@@ -71763,9 +72112,9 @@ var watchFilter = (config) => `${config.site}/${config.building}/#`;
71763
72112
  var twoDigits = (value4) => String(value4).padStart(2, "0");
71764
72113
  var formatMessage2 = (message, at) => {
71765
72114
  const time2 = `${twoDigits(at.getHours())}:${twoDigits(at.getMinutes())}:${twoDigits(at.getSeconds())}`;
71766
- const flat = message.payload.replace(/\s*\n\s*/g, " ");
72115
+ const flat = withoutControls(message.payload.replace(/\s*\n\s*/g, " ").replace(/[\t\r]/g, " "));
71767
72116
  const payload = flat.length > MAX_PAYLOAD ? `${flat.slice(0, MAX_PAYLOAD)}\u2026` : flat;
71768
- return `${time2} ${message.retain ? "retained " : ""}${message.topic} ${payload}`;
72117
+ return `${time2} ${message.retain ? "retained " : ""}${withoutControls(message.topic)} ${payload}`;
71769
72118
  };
71770
72119
  var messageRecord = (message, at) => {
71771
72120
  let payload = message.payload;
@@ -71777,7 +72126,7 @@ var messageRecord = (message, at) => {
71777
72126
  };
71778
72127
  var watch3 = Effect_exports.fn("watch")(function* (config, options3 = {}) {
71779
72128
  const filter14 = options3.topic ?? watchFilter(config);
71780
- yield* brokerClient(config.mqtt, "watch", {
72129
+ const client = yield* brokerClient(config.mqtt, "watch", {
71781
72130
  subscriptions: [{ filter: filter14, qos: 0, retainAsPublished: true }],
71782
72131
  onConnect: () => Console_exports.error(
71783
72132
  `watching ${filter14} on ${config.mqtt.url} (${options3.seconds === void 0 ? "Ctrl-C to stop" : `for ${options3.seconds} s`})`
@@ -71786,6 +72135,7 @@ var watch3 = Effect_exports.fn("watch")(function* (config, options3 = {}) {
71786
72135
  });
71787
72136
  yield* Console_exports.error(`connecting to ${config.mqtt.url}\u2026`);
71788
72137
  if (options3.seconds === void 0) return yield* Effect_exports.never;
72138
+ yield* firstDialOf(client, config.mqtt.url);
71789
72139
  yield* Effect_exports.sleep(Duration_exports.seconds(options3.seconds));
71790
72140
  }, Effect_exports.scoped);
71791
72141
 
@@ -72303,6 +72653,7 @@ var outboxMigrations = Migrator_exports.fromRecord({
72303
72653
  `;
72304
72654
  })
72305
72655
  });
72656
+ var withoutSpans = Effect_exports.withTracerEnabled(false);
72306
72657
  var makeOutbox = (sql) => {
72307
72658
  const countRows = SqlSchema_exports.findAll({
72308
72659
  Request: Schema_exports.Int,
@@ -72343,20 +72694,21 @@ var makeOutbox = (sql) => {
72343
72694
  );
72344
72695
  return {
72345
72696
  /** Rows with an id above `after` (0 for all of them). */
72346
- count: (after = 0) => Effect_exports.map(countRows(after), (rows) => rows[0]?.n ?? 0),
72697
+ count: (after = 0) => Effect_exports.map(countRows(after), (rows) => rows[0]?.n ?? 0).pipe(withoutSpans),
72347
72698
  append: (topic, payload, qos, createdAt) => sql`INSERT INTO outbox (topic, payload, qos, created_at) VALUES (${topic}, ${payload}, ${qos}, ${createdAt})`.pipe(
72348
- Effect_exports.asVoid
72699
+ Effect_exports.asVoid,
72700
+ withoutSpans
72349
72701
  ),
72350
72702
  /** The `limit` oldest rows with an id above `after`. */
72351
- oldest,
72703
+ oldest: (limit, after) => oldest(limit, after).pipe(withoutSpans),
72352
72704
  /** Delete the given rows; returns how many were still there. */
72353
- remove: (ids) => ids.length === 0 ? Effect_exports.succeed(0) : Effect_exports.map(removeRows(ids), (rows) => rows.length),
72705
+ remove: (ids) => ids.length === 0 ? Effect_exports.succeed(0) : Effect_exports.map(removeRows(ids), (rows) => rows.length).pipe(withoutSpans),
72354
72706
  /** Delete every row up to and including `id`. */
72355
- removeThrough: (id2) => sql`DELETE FROM outbox WHERE id <= ${id2}`.pipe(Effect_exports.asVoid),
72707
+ removeThrough: (id2) => sql`DELETE FROM outbox WHERE id <= ${id2}`.pipe(Effect_exports.asVoid, withoutSpans),
72356
72708
  /** Delete the `count` oldest rows with an id above `after`; returns how many were deleted. */
72357
- dropOldest: (count2, after) => Effect_exports.map(dropOldestRows({ count: count2, after }), (rows) => rows.length),
72709
+ dropOldest: (count2, after) => Effect_exports.map(dropOldestRows({ count: count2, after }), (rows) => rows.length).pipe(withoutSpans),
72358
72710
  /** Return free pages to the file system (new files use `auto_vacuum = INCREMENTAL`; elsewhere a no-op). */
72359
- vacuum: sql`PRAGMA incremental_vacuum`.pipe(Effect_exports.asVoid)
72711
+ vacuum: sql`PRAGMA incremental_vacuum`.pipe(Effect_exports.asVoid, withoutSpans)
72360
72712
  };
72361
72713
  };
72362
72714
 
@@ -72431,12 +72783,13 @@ var openOnce = (path) => Effect_exports.gen(function* () {
72431
72783
  },
72432
72784
  MigrationError: (error2) => Effect_exports.fail(new BufferUnusable({ path, message: `migrations failed (${error2.kind}): ${error2.message}` }))
72433
72785
  }),
72786
+ withoutSpans,
72434
72787
  Effect_exports.onExit((exit3) => Exit_exports.isFailure(exit3) ? Scope_exports.close(scope3, exit3) : Effect_exports.void)
72435
72788
  );
72436
72789
  const sql = yield* opened;
72437
72790
  return {
72438
72791
  outbox: makeOutbox(sql),
72439
- backup: (destination) => Effect_exports.asVoid(sql.backup(destination)),
72792
+ backup: (destination) => Effect_exports.asVoid(sql.backup(destination)).pipe(withoutSpans),
72440
72793
  identity: yield* fileIdentity(path),
72441
72794
  close: Scope_exports.close(scope3, Exit_exports.void)
72442
72795
  };
@@ -72502,6 +72855,8 @@ var monotonicMillis2 = Effect_exports.map(Clock_exports.monotonicTimeNanos, (nan
72502
72855
  var cannotOpen = "buffer file cannot be opened: running WITHOUT store-and-forward, values are lost while the broker is down";
72503
72856
  var makeBufferedPublisher = Effect_exports.fnUntraced(function* (settings, options3) {
72504
72857
  const inner = yield* Publisher;
72858
+ const ownAttributes = yield* Metric_exports.CurrentMetricAttributes;
72859
+ const setGauge = (gauge3, value4) => Metric_exports.update(gauge3, value4).pipe(Effect_exports.provideService(Metric_exports.CurrentMetricAttributes, ownAttributes));
72505
72860
  const batchSize = options3.batchSize ?? 100;
72506
72861
  const retryDelay = options3.retryDelay ?? "5 seconds";
72507
72862
  const checkInterval = options3.checkInterval ?? "30 seconds";
@@ -72522,20 +72877,20 @@ var makeBufferedPublisher = Effect_exports.fnUntraced(function* (settings, optio
72522
72877
  const setPending = Effect_exports.fnUntraced(function* (target, rows) {
72523
72878
  target.pending = Math.max(0, rows);
72524
72879
  if (target !== current) return;
72525
- yield* Metric_exports.update(bufferRows, target.pending);
72880
+ yield* setGauge(bufferRows, target.pending);
72526
72881
  if (target.pending > 0) yield* Latch_exports.open(hasRows);
72527
72882
  else yield* Latch_exports.close(hasRows);
72528
72883
  });
72529
72884
  const install = Effect_exports.fnUntraced(function* (database) {
72530
72885
  if (database === void 0) {
72531
72886
  current = void 0;
72532
- yield* Metric_exports.update(bufferDisabled, 1);
72533
- yield* Metric_exports.update(bufferRows, 0);
72887
+ yield* setGauge(bufferDisabled, 1);
72888
+ yield* setGauge(bufferRows, 0);
72534
72889
  return yield* Latch_exports.close(hasRows);
72535
72890
  }
72536
72891
  const target = makeStore(database, yield* database.outbox.count());
72537
72892
  current = target;
72538
- yield* Metric_exports.update(bufferDisabled, 0);
72893
+ yield* setGauge(bufferDisabled, 0);
72539
72894
  yield* setPending(target, target.pending);
72540
72895
  if (target.pending > 0) {
72541
72896
  yield* Effect_exports.logInfo("buffered messages waiting from a previous run").pipe(
@@ -74540,12 +74895,103 @@ var handleCause = (nodeResponse, originalResponse) => (originalCause) => flatMap
74540
74895
  return failCause4(headersSent ? combine2(originalCause, die2(originalResponse)) : cause);
74541
74896
  });
74542
74897
 
74898
+ // src/PointCatalog.ts
74899
+ var durationLabel = (ms) => {
74900
+ if (ms < 6e4) return `${Number((ms / 1e3).toFixed(1))} s`;
74901
+ if (ms < 36e5) return `${Number((ms / 6e4).toFixed(1))} min`;
74902
+ return `${Number((ms / 36e5).toFixed(1))} h`;
74903
+ };
74904
+ var publishLabel = (publish2) => {
74905
+ switch (publish2.mode) {
74906
+ case "sample":
74907
+ return publish2.intervalMs === void 0 ? "every read" : `latest, every ${durationLabel(publish2.intervalMs)}`;
74908
+ case "aggregate":
74909
+ return `aggregate every ${durationLabel(publish2.intervalMs)}`;
74910
+ case "change": {
74911
+ const change = publish2.deadband === void 0 || publish2.deadband === 0 ? "on change" : `on change \u2265 ${publish2.deadband}`;
74912
+ return publish2.maxSilenceMs === void 0 ? change : `${change}, at least every ${durationLabel(publish2.maxSilenceMs)}`;
74913
+ }
74914
+ }
74915
+ };
74916
+ var modbusSource = (point) => {
74917
+ const bit = point.bit === void 0 ? "" : ` bit ${point.bit}`;
74918
+ const order = point.table === "holding" || point.table === "input" ? ` ${point.byteOrder}` : "";
74919
+ return `${point.table} ${point.address}${bit} \xB7 ${point.dataType}${order}`;
74920
+ };
74921
+ var bacnetSource = (point) => `${point.objectType} ${point.instance} \xB7 ${point.property}${point.writable ? ` \xB7 priority ${point.priority}` : ""}`;
74922
+ var simulatedSource = (point) => point.waveform === "constant" ? `constant ${point.min}` : `${point.waveform} ${point.min} to ${point.max} \xB7 ${durationLabel(point.periodSeconds * 1e3)}`;
74923
+ var sourcedPoints = (device) => {
74924
+ switch (device.protocol) {
74925
+ case "modbus-tcp":
74926
+ return device.points.map((point) => [point, modbusSource(point)]);
74927
+ case "bacnet-ip":
74928
+ return device.points.map((point) => [point, bacnetSource(point)]);
74929
+ case "simulator":
74930
+ return device.points.map((point) => [point, simulatedSource(point)]);
74931
+ }
74932
+ };
74933
+ var pointCatalog = (config) => ({
74934
+ points: config.devices.flatMap(
74935
+ (device) => sourcedPoints(device).map(([point, source]) => {
74936
+ const semantics = point.semantics;
74937
+ return {
74938
+ device: device.id,
74939
+ id: point.id,
74940
+ name: point.name,
74941
+ ...point.unit === void 0 ? {} : { unit: point.unit },
74942
+ writable: point.writable,
74943
+ topic: pointTopic({ site: config.site, building: config.building, device: device.id, point: point.id }),
74944
+ source,
74945
+ publish: publishLabel(publishOf(device.publish, point)),
74946
+ ...point.limits === void 0 ? {} : { limits: point.limits },
74947
+ ...point.scaling === void 0 ? {} : { scaling: point.scaling },
74948
+ ...semantics?.brick === void 0 ? {} : { brick: semantics.brick },
74949
+ ...semantics?.haystack === void 0 ? {} : { haystack: semantics.haystack }
74950
+ };
74951
+ })
74952
+ )
74953
+ });
74954
+
74955
+ // src/ConfigView.ts
74956
+ var encodeConfig = Schema_exports.encodeSync(GatewayConfig);
74957
+ var asJson = Schema_exports.decodeUnknownSync(Schema_exports.Json);
74958
+ var isObject2 = (value4) => typeof value4 === "object" && value4 !== null && !Array.isArray(value4);
74959
+ var entriesOf = (object, skip2 = []) => Object.entries(object).filter(([key5]) => !skip2.includes(key5)).map(([key5, value4]) => ({ key: key5, value: value4 }));
74960
+ var configView = (config) => {
74961
+ const encoded = asJson(encodeConfig(config));
74962
+ if (!isObject2(encoded)) return { sections: [], devices: [] };
74963
+ const usesBacnet = config.devices.some((device) => device.protocol === "bacnet-ip");
74964
+ const top = Object.entries(encoded);
74965
+ const sections = [
74966
+ { key: "gateway", entries: top.filter(([, value4]) => !isObject2(value4) && !Array.isArray(value4)) },
74967
+ ...top.filter(([key5, value4]) => isObject2(value4) && (key5 !== "bacnet" || usesBacnet)).map(([key5, value4]) => ({ key: key5, entries: isObject2(value4) ? Object.entries(value4) : [] }))
74968
+ ].map((section) => ({
74969
+ key: section.key,
74970
+ entries: section.entries.map(([key5, value4]) => ({ key: key5, value: value4 }))
74971
+ }));
74972
+ const devices = config.devices.map((device, index2) => {
74973
+ const raw3 = Array.isArray(encoded["devices"]) ? encoded["devices"][index2] : void 0;
74974
+ return {
74975
+ id: device.id,
74976
+ protocol: device.protocol,
74977
+ pointCount: device.points.length,
74978
+ // The publish mode in words, as the Points tab shows it, and the default spelled out when the file has none.
74979
+ entries: [
74980
+ ...raw3 !== void 0 && isObject2(raw3) ? entriesOf(raw3, ["id", "protocol", "points", "publish"]) : [],
74981
+ { key: "publish", value: publishLabel(device.publish ?? everyRead) }
74982
+ ]
74983
+ };
74984
+ });
74985
+ return { sections, devices };
74986
+ };
74987
+
74543
74988
  // src/Status.ts
74544
74989
  import { createServer as createServer2 } from "node:http";
74545
74990
  import { fileURLToPath as fileURLToPath5 } from "node:url";
74546
74991
  var RECENT_COMMANDS = 50;
74547
74992
  var MAX_TOPICS = 2e3;
74548
74993
  var MAX_PAYLOAD2 = 2e3;
74994
+ var MAX_TOPIC_LENGTH = 512;
74549
74995
  var MAX_CONNECTIONS = 32;
74550
74996
  var ValueMessage = Schema_exports.fromJsonString(
74551
74997
  Schema_exports.Struct({ value: Schema_exports.Union([Schema_exports.Number, Schema_exports.Boolean]), ts: Schema_exports.Number })
@@ -74559,10 +75005,18 @@ var makeStatusState = (config, health, since, host) => {
74559
75005
  const latest = /* @__PURE__ */ new Map();
74560
75006
  const droppedTopics = /* @__PURE__ */ new Set();
74561
75007
  const commands2 = [];
75008
+ let broker;
75009
+ const catalog = pointCatalog(config);
75010
+ const settings = configView(config);
75011
+ const configured = new Set(catalog.points.map((point) => `${point.device}/${point.id}`));
75012
+ const lastRead = (key5) => {
75013
+ const payload = payloads.get(key5);
75014
+ return reads.get(key5) ?? Option_exports.getOrUndefined(payload === void 0 ? Option_exports.none() : decodeValue2(payload));
75015
+ };
74562
75016
  const attributes = { site: config.site, building: config.building };
74563
75017
  return {
74564
75018
  recordPublish: (topic, payload, message) => {
74565
- if (!topic.startsWith(prefix)) return;
75019
+ if (!topic.startsWith(prefix) || topic.length > MAX_TOPIC_LENGTH) return;
74566
75020
  if (message.retained && payload === "") {
74567
75021
  latest.delete(topic);
74568
75022
  return;
@@ -74581,6 +75035,9 @@ var makeStatusState = (config, health, since, host) => {
74581
75035
  reads.set(`${device}/${point}`, { value: value4, ts });
74582
75036
  }
74583
75037
  },
75038
+ recordBrokerConnection: (at, connection) => {
75039
+ broker = { at, connection };
75040
+ },
74584
75041
  recordCommand: (at, command, outcome) => {
74585
75042
  commands2.unshift({
74586
75043
  at,
@@ -74591,14 +75048,16 @@ var makeStatusState = (config, health, since, host) => {
74591
75048
  });
74592
75049
  if (commands2.length > RECENT_COMMANDS) commands2.length = RECENT_COMMANDS;
74593
75050
  },
74594
- snapshot: Effect_exports.gen(function* () {
75051
+ snapshot: (points2 = "all") => Effect_exports.gen(function* () {
74595
75052
  const now2 = yield* Clock_exports.currentTimeMillis;
74596
75053
  const connected = (yield* Metric_exports.value(Metric_exports.withAttributes(mqttConnected, attributes))).value === 1;
74597
75054
  const rows = (yield* Metric_exports.value(Metric_exports.withAttributes(bufferRows, attributes))).value;
74598
- let dropped = 0;
74599
- for (const reason of bufferDropReasons) {
74600
- dropped += (yield* Metric_exports.value(Metric_exports.withAttributes(bufferDropped, { ...attributes, reason }))).count;
74601
- }
75055
+ const disabled2 = (yield* Metric_exports.value(Metric_exports.withAttributes(bufferDisabled, attributes))).value === 1;
75056
+ const total = totals(yield* Metric_exports.snapshot, attributes);
75057
+ const droppedBy = Object.fromEntries(
75058
+ bufferDropReasons.map((reason) => [reason, total(bufferDropped.id, { reason })])
75059
+ );
75060
+ const dropped = Object.values(droppedBy).reduce((sum3, count2) => sum3 + count2, 0);
74602
75061
  const devices = config.devices.map((device) => {
74603
75062
  const state = health.devices.get(device.id) ?? { status: "starting" };
74604
75063
  return {
@@ -74608,10 +75067,9 @@ var makeStatusState = (config, health, since, host) => {
74608
75067
  pollIntervalMs: device.pollIntervalMs,
74609
75068
  ...state.reason === void 0 ? {} : { reason: state.reason },
74610
75069
  ...state.lastSuccess === void 0 ? {} : { lastSuccess: state.lastSuccess },
74611
- points: device.points.map((point) => {
74612
- const key5 = `${device.id}/${point.id}`;
74613
- const payload = payloads.get(key5);
74614
- const last2 = reads.get(key5) ?? Option_exports.getOrUndefined(payload === void 0 ? Option_exports.none() : decodeValue2(payload));
75070
+ pointCount: device.points.length,
75071
+ points: points2 === "none" ? [] : device.points.map((point) => {
75072
+ const last2 = lastRead(`${device.id}/${point.id}`);
74615
75073
  return {
74616
75074
  id: point.id,
74617
75075
  name: point.name,
@@ -74629,13 +75087,54 @@ var makeStatusState = (config, health, since, host) => {
74629
75087
  id: config.id,
74630
75088
  since,
74631
75089
  now: now2,
74632
- broker: { url: config.mqtt.url, connected },
74633
- ...config.buffer === void 0 ? {} : { buffer: { path: config.buffer.path, rows: Math.max(0, rows), maxRows: config.buffer.maxRows, dropped } },
75090
+ broker: {
75091
+ url: config.mqtt.url,
75092
+ connected,
75093
+ ...broker === void 0 ? {} : { connectedAt: broker.at, connection: broker.connection },
75094
+ connects: total(mqttConnects.id, { outcome: "ok" }),
75095
+ failedConnects: total(mqttConnects.id, { outcome: "failed" }) + total(mqttConnects.id, { outcome: "rejected" }),
75096
+ published: total(valuesPublished.id),
75097
+ publishFailures: total(publishFailures.id)
75098
+ },
75099
+ ...config.buffer === void 0 ? {} : {
75100
+ buffer: {
75101
+ path: config.buffer.path,
75102
+ rows: Math.max(0, rows),
75103
+ maxRows: config.buffer.maxRows,
75104
+ dropped,
75105
+ written: total(bufferWritten.id),
75106
+ delivered: total(bufferDrained.id),
75107
+ droppedBy,
75108
+ failures: total(bufferFailures.id),
75109
+ disabled: disabled2
75110
+ }
75111
+ },
74634
75112
  ...host === void 0 || sample === void 0 ? {} : { host: { version: host.version, node: process.versions.node, ...sample } },
74635
75113
  devices,
74636
75114
  commands: [...commands2]
74637
75115
  };
74638
75116
  }),
75117
+ values: (keys4) => Effect_exports.gen(function* () {
75118
+ const asked = keys4.split(",").filter((key5) => key5 !== "");
75119
+ if (asked.length > MAX_VALUES_PER_REQUEST) {
75120
+ return yield* new ValuesQueryInvalid({
75121
+ message: `${asked.length} points asked for, at most ${MAX_VALUES_PER_REQUEST} per request`
75122
+ });
75123
+ }
75124
+ const readings = asked.flatMap((key5) => {
75125
+ if (!configured.has(key5)) return [];
75126
+ const slash = key5.indexOf("/");
75127
+ const last2 = lastRead(key5);
75128
+ return [
75129
+ {
75130
+ device: key5.slice(0, slash),
75131
+ point: key5.slice(slash + 1),
75132
+ ...last2 === void 0 ? {} : { value: last2.value, ts: last2.ts }
75133
+ }
75134
+ ];
75135
+ });
75136
+ return { readings };
75137
+ }),
74639
75138
  messages: Effect_exports.sync(() => ({
74640
75139
  messages: [...latest.entries()].toSorted(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([topic, message]) => ({
74641
75140
  topic,
@@ -74646,9 +75145,21 @@ var makeStatusState = (config, health, since, host) => {
74646
75145
  count: message.count
74647
75146
  })),
74648
75147
  droppedTopics: droppedTopics.size
74649
- }))
75148
+ })),
75149
+ points: Effect_exports.succeed(catalog),
75150
+ config: Effect_exports.succeed(settings)
74650
75151
  };
74651
75152
  };
75153
+ var totals = (snapshots, scope3) => (id2, match9 = {}) => {
75154
+ const wanted = Object.entries({ ...scope3, ...match9 });
75155
+ let sum3 = 0;
75156
+ for (const snapshot3 of snapshots) {
75157
+ if (snapshot3.id !== id2 || snapshot3.type !== "Counter") continue;
75158
+ const attributes = snapshot3.attributes ?? {};
75159
+ if (wanted.every(([key5, value4]) => attributes[key5] === value4)) sum3 += Number(snapshot3.state.count);
75160
+ }
75161
+ return sum3;
75162
+ };
74652
75163
  var DEFAULT_HISTORY_MS = 36e5;
74653
75164
  var historyHandler = (config, history) => (request3) => Effect_exports.gen(function* () {
74654
75165
  if (history === void 0) {
@@ -74679,7 +75190,7 @@ var serveStatus = (settings, state, history = () => Effect_exports.fail(new Hist
74679
75190
  HttpApiBuilder_exports.group(
74680
75191
  OtGatewayApi,
74681
75192
  "status",
74682
- (handlers) => handlers.handle("status", () => state.snapshot).handle("messages", () => state.messages).handle("history", ({ query: query3 }) => history(query3))
75193
+ (handlers) => handlers.handle("status", ({ query: query3 }) => state.snapshot(query3.points)).handle("values", ({ query: query3 }) => state.values(query3.points)).handle("messages", () => state.messages).handle("points", () => state.points).handle("config", () => state.config).handle("history", ({ query: query3 }) => history(query3))
74683
75194
  )
74684
75195
  )
74685
75196
  );
@@ -74800,6 +75311,7 @@ var rollup = (rows) => {
74800
75311
  }
74801
75312
  return [...minutes2.values()];
74802
75313
  };
75314
+ var withoutSpans2 = Effect_exports.withTracerEnabled(false);
74803
75315
  var makeStore2 = (sql) => {
74804
75316
  const bucketsOf = (table2, query3) => SqlSchema_exports.findAll({
74805
75317
  Request: Schema_exports.Void,
@@ -74815,7 +75327,7 @@ var makeStore2 = (sql) => {
74815
75327
  FROM minutes
74816
75328
  WHERE device = ${query3.device} AND point = ${query3.point} AND minute >= ${query3.from} AND minute < ${query3.to}
74817
75329
  GROUP BY b ORDER BY b`
74818
- })(void 0);
75330
+ })(void 0).pipe(withoutSpans2);
74819
75331
  return {
74820
75332
  /** Store a batch of reads and merge them into the minute rollups, in one transaction. */
74821
75333
  write: (rows) => sql.withTransaction(
@@ -74836,7 +75348,7 @@ var makeStore2 = (sql) => {
74836
75348
  count = minutes.count + excluded.count`;
74837
75349
  }
74838
75350
  })
74839
- ),
75351
+ ).pipe(withoutSpans2),
74840
75352
  /** One point's buckets from every read (`readings`) or from the rollups (`minutes`). */
74841
75353
  buckets: bucketsOf,
74842
75354
  /** Delete reads older than `rawBefore` and rollups older than `minutesBefore` (Unix ms). */
@@ -74844,7 +75356,7 @@ var makeStore2 = (sql) => {
74844
75356
  yield* sql`DELETE FROM readings WHERE ts < ${rawBefore}`;
74845
75357
  yield* sql`DELETE FROM minutes WHERE minute < ${minutesBefore}`;
74846
75358
  yield* sql`PRAGMA incremental_vacuum`;
74847
- })
75359
+ }).pipe(withoutSpans2)
74848
75360
  };
74849
75361
  };
74850
75362
 
@@ -74853,6 +75365,8 @@ var MAX_PENDING2 = 2e4;
74853
75365
  var DEFAULT_BUCKETS = 300;
74854
75366
  var MAX_BUCKETS = 2e3;
74855
75367
  var HOUR_MS = 36e5;
75368
+ var DEFAULT_FLUSH_EVERY_MS = 3e4;
75369
+ var TICK_MS = 5e3;
74856
75370
  var isCorrupt2 = (error2) => {
74857
75371
  const cause = error2.reason.cause;
74858
75372
  if (typeof cause !== "object" || cause === null || !("errcode" in cause) || typeof cause.errcode !== "number") {
@@ -74881,35 +75395,41 @@ var openStore = (path, scope3) => Effect_exports.gen(function* () {
74881
75395
  Effect_exports.catchTags({
74882
75396
  SqlError: (error2) => Effect_exports.fail({ corrupt: isCorrupt2(error2), message: error2.message }),
74883
75397
  MigrationError: (error2) => Effect_exports.fail({ corrupt: true, message: `migrations failed: ${error2.message}` })
74884
- })
75398
+ }),
75399
+ withoutSpans2
74885
75400
  );
74886
- var open5 = Effect_exports.fnUntraced(function* (path) {
75401
+ var moveAside2 = Effect_exports.fnUntraced(function* (path) {
75402
+ const fs = yield* FileSystem_exports.FileSystem;
75403
+ const stamp = new Date(yield* Clock_exports.currentTimeMillis).toISOString().replace(/[:.]/g, "-");
75404
+ const aside = `${path}.corrupt-${stamp}`;
75405
+ for (const suffix of ["", "-wal", "-shm"]) {
75406
+ if (yield* fs.exists(path + suffix)) yield* fs.rename(path + suffix, aside + suffix);
75407
+ }
75408
+ return aside;
75409
+ });
75410
+ var openIn = Effect_exports.fnUntraced(function* (path, scope3) {
75411
+ const own = yield* Scope_exports.fork(scope3);
75412
+ const close4 = Scope_exports.close(own, Exit_exports.void);
75413
+ const store = yield* openStore(path, own).pipe(Effect_exports.tapError(() => close4));
75414
+ return { store, close: close4 };
75415
+ });
75416
+ var open5 = Effect_exports.fnUntraced(function* (path, scope3) {
74887
75417
  const fs = yield* FileSystem_exports.FileSystem;
74888
75418
  const paths = yield* Path_exports.Path;
74889
- const scope3 = yield* Effect_exports.scope;
74890
75419
  const made = yield* fs.makeDirectory(paths.dirname(path), { recursive: true }).pipe(Effect_exports.result);
74891
75420
  if (Result_exports.isFailure(made)) return { reason: `cannot create the directory: ${made.failure.message}` };
74892
- const first = yield* openStore(path, yield* Scope_exports.fork(scope3)).pipe(Effect_exports.result);
74893
- if (Result_exports.isSuccess(first)) return { store: first.success };
75421
+ const first = yield* openIn(path, scope3).pipe(Effect_exports.result);
75422
+ if (Result_exports.isSuccess(first)) return { opened: first.success };
74894
75423
  if (!first.failure.corrupt) return { reason: first.failure.message };
74895
- const stamp = new Date(yield* Clock_exports.currentTimeMillis).toISOString().replace(/[:.]/g, "-");
74896
- const aside = `${path}.corrupt-${stamp}`;
74897
- for (const suffix of ["", "-wal", "-shm"]) {
74898
- const moved = yield* Effect_exports.result(
74899
- Effect_exports.flatMap(
74900
- fs.exists(path + suffix),
74901
- (exists2) => exists2 ? fs.rename(path + suffix, aside + suffix) : Effect_exports.void
74902
- )
74903
- );
74904
- if (Result_exports.isFailure(moved)) {
74905
- return { reason: `${first.failure.message}; moving it aside failed: ${moved.failure.message}` };
74906
- }
75424
+ const moved = yield* Effect_exports.result(moveAside2(path));
75425
+ if (Result_exports.isFailure(moved)) {
75426
+ return { reason: `${first.failure.message}; moving it aside failed: ${moved.failure.message}` };
74907
75427
  }
74908
75428
  yield* Effect_exports.logError("history file was unusable, moved it aside and started a new one").pipe(
74909
- Effect_exports.annotateLogs({ path, movedTo: aside, error: first.failure.message })
75429
+ Effect_exports.annotateLogs({ path, movedTo: moved.success, error: first.failure.message })
74910
75430
  );
74911
- const again = yield* openStore(path, yield* Scope_exports.fork(scope3)).pipe(Effect_exports.result);
74912
- return Result_exports.isSuccess(again) ? { store: again.success } : { reason: again.failure.message };
75431
+ const again = yield* openIn(path, scope3).pipe(Effect_exports.result);
75432
+ return Result_exports.isSuccess(again) ? { opened: again.success } : { reason: again.failure.message };
74913
75433
  });
74914
75434
  var unavailable = (message) => Effect_exports.fail(new HistoryUnavailable({ message }));
74915
75435
  var disabled = (reason) => ({
@@ -74918,8 +75438,9 @@ var disabled = (reason) => ({
74918
75438
  series: () => unavailable(`the gateway keeps no history: ${reason}`)
74919
75439
  });
74920
75440
  var openHistory = (settings, options3 = {}) => Effect_exports.gen(function* () {
74921
- const opened = yield* open5(settings.path);
74922
- if (!("store" in opened)) {
75441
+ const files = yield* Scope_exports.fork(yield* Effect_exports.scope);
75442
+ const opened = yield* open5(settings.path, files);
75443
+ if (!("opened" in opened)) {
74923
75444
  yield* Metric_exports.update(historyDisabled, 1);
74924
75445
  yield* Effect_exports.logError("history not kept: its file could not be opened").pipe(
74925
75446
  Effect_exports.annotateLogs({ path: settings.path, error: opened.reason })
@@ -74927,7 +75448,11 @@ var openHistory = (settings, options3 = {}) => Effect_exports.gen(function* () {
74927
75448
  return disabled(opened.reason);
74928
75449
  }
74929
75450
  yield* Metric_exports.update(historyDisabled, 0);
74930
- const store = opened.store;
75451
+ const wrap = options3.wrapStore ?? ((store) => store);
75452
+ let current = { store: wrap(opened.opened.store), close: opened.opened.close };
75453
+ let off;
75454
+ let replacedAt;
75455
+ const permit = yield* Semaphore_exports.make(1);
74931
75456
  let pending = [];
74932
75457
  let dropped = 0;
74933
75458
  let failing = false;
@@ -74936,15 +75461,47 @@ var openHistory = (settings, options3 = {}) => Effect_exports.gen(function* () {
74936
75461
  dropped += rows.length - MAX_PENDING2;
74937
75462
  return rows.slice(rows.length - MAX_PENDING2);
74938
75463
  };
75464
+ const turnOff = Effect_exports.fnUntraced(function* (reason) {
75465
+ current = void 0;
75466
+ off = reason;
75467
+ pending = [];
75468
+ yield* Metric_exports.update(historyDisabled, 1);
75469
+ yield* Effect_exports.logError("history turned off: its corrupt file could not be replaced").pipe(
75470
+ Effect_exports.annotateLogs({ path: settings.path, error: reason })
75471
+ );
75472
+ });
75473
+ const replaceCorrupt = Effect_exports.fnUntraced(function* (target, error2) {
75474
+ const now2 = yield* monotonicMillis;
75475
+ if (replacedAt !== void 0 && now2 - replacedAt < HOUR_MS) return false;
75476
+ replacedAt = now2;
75477
+ current = void 0;
75478
+ yield* target.close;
75479
+ const moved = yield* Effect_exports.result(moveAside2(settings.path));
75480
+ if (Result_exports.isFailure(moved)) {
75481
+ yield* turnOff(`${error2.message}; moving it aside failed: ${moved.failure.message}`);
75482
+ return true;
75483
+ }
75484
+ const reopened = yield* open5(settings.path, files);
75485
+ if (!("opened" in reopened)) {
75486
+ yield* turnOff(reopened.reason);
75487
+ return true;
75488
+ }
75489
+ current = { store: wrap(reopened.opened.store), close: reopened.opened.close };
75490
+ yield* Effect_exports.logError(
75491
+ "history file went corrupt while the gateway ran, moved it aside and started a new one"
75492
+ ).pipe(Effect_exports.annotateLogs({ path: settings.path, movedTo: moved.success, error: error2.message }));
75493
+ return true;
75494
+ });
74939
75495
  const flush2 = Effect_exports.gen(function* () {
74940
75496
  if (dropped > 0) {
74941
75497
  yield* Metric_exports.update(historyDropped, dropped);
74942
75498
  dropped = 0;
74943
75499
  }
74944
- if (pending.length === 0) return;
75500
+ const target = current;
75501
+ if (target === void 0 || pending.length === 0) return;
74945
75502
  const batch = pending;
74946
75503
  pending = [];
74947
- const written = yield* Effect_exports.result(store.write(batch));
75504
+ const written = yield* Effect_exports.result(target.store.write(batch));
74948
75505
  if (Result_exports.isSuccess(written)) {
74949
75506
  yield* Metric_exports.update(historyWritten, batch.length);
74950
75507
  if (failing) {
@@ -74955,25 +75512,37 @@ var openHistory = (settings, options3 = {}) => Effect_exports.gen(function* () {
74955
75512
  }
74956
75513
  yield* Metric_exports.update(Metric_exports.withAttributes(historyFailures, { operation: "write" }), 1);
74957
75514
  pending = keepAtMost([...batch, ...pending]);
75515
+ if (isCorrupt2(written.failure) && (yield* replaceCorrupt(target, written.failure))) return;
74958
75516
  if (!failing) {
74959
75517
  failing = true;
74960
75518
  yield* Effect_exports.logWarning("history cannot write; keeping the latest reads in memory until it can").pipe(
74961
75519
  Effect_exports.annotateLogs({ path: settings.path, error: written.failure.message })
74962
75520
  );
74963
75521
  }
74964
- });
75522
+ }).pipe(Semaphore_exports.withPermit(permit));
74965
75523
  const prune = Effect_exports.gen(function* () {
75524
+ const target = current;
75525
+ if (target === void 0) return;
74966
75526
  const now2 = yield* Clock_exports.currentTimeMillis;
74967
- const pruned = yield* Effect_exports.result(store.prune(now2 - RAW_MS, now2 - settings.retentionDays * 864e5));
75527
+ const pruned = yield* Effect_exports.result(target.store.prune(now2 - RAW_MS, now2 - settings.retentionDays * 864e5));
74968
75528
  if (Result_exports.isFailure(pruned)) {
74969
75529
  yield* Metric_exports.update(Metric_exports.withAttributes(historyFailures, { operation: "prune" }), 1);
75530
+ if (isCorrupt2(pruned.failure) && (yield* replaceCorrupt(target, pruned.failure))) return;
74970
75531
  yield* Effect_exports.logWarning("history could not delete old reads").pipe(
74971
75532
  Effect_exports.annotateLogs({ path: settings.path, error: pruned.failure.message })
74972
75533
  );
74973
75534
  }
75535
+ }).pipe(Semaphore_exports.withPermit(permit));
75536
+ const flushEveryMs = options3.flushEveryMs ?? DEFAULT_FLUSH_EVERY_MS;
75537
+ const tickEvery = Duration_exports.millis(Math.min(TICK_MS, flushEveryMs));
75538
+ let attemptedAt = yield* monotonicMillis;
75539
+ const tick2 = Effect_exports.gen(function* () {
75540
+ const now2 = yield* monotonicMillis;
75541
+ if (now2 - attemptedAt < flushEveryMs && pending.length < MAX_PENDING2 / 2) return;
75542
+ attemptedAt = now2;
75543
+ yield* flush2;
74974
75544
  });
74975
- const flushEvery = Duration_exports.millis(options3.flushEveryMs ?? 5e3);
74976
- yield* flush2.pipe(Effect_exports.repeat(Schedule_exports.spaced(flushEvery)), Effect_exports.delay(flushEvery), Effect_exports.forkScoped);
75545
+ yield* tick2.pipe(Effect_exports.repeat(Schedule_exports.spaced(tickEvery)), Effect_exports.delay(tickEvery), Effect_exports.forkScoped);
74977
75546
  yield* prune.pipe(
74978
75547
  Effect_exports.repeat(Schedule_exports.spaced(Duration_exports.millis(HOUR_MS))),
74979
75548
  Effect_exports.delay("1 minute"),
@@ -74983,21 +75552,32 @@ var openHistory = (settings, options3 = {}) => Effect_exports.gen(function* () {
74983
75552
  return {
74984
75553
  sink: {
74985
75554
  record: (device, point, value4, ts) => {
75555
+ if (off !== void 0) return;
74986
75556
  pending.push({ device, point, ts, value: typeof value4 === "boolean" ? value4 ? 1 : 0 : value4 });
74987
75557
  if (pending.length > MAX_PENDING2 + MAX_PENDING2 / 10) pending = keepAtMost(pending);
74988
75558
  }
74989
75559
  },
74990
75560
  series: (query3) => Effect_exports.gen(function* () {
75561
+ const buckets = query3.buckets ?? DEFAULT_BUCKETS;
75562
+ const fineMs = stepFor(query3.from, query3.to, buckets, 1e3);
74991
75563
  const now2 = yield* Clock_exports.currentTimeMillis;
74992
- const raw3 = query3.from >= now2 - RAW_MS;
74993
- const stepMs = stepFor(query3.from, query3.to, query3.buckets ?? DEFAULT_BUCKETS, raw3 ? 1e3 : MINUTE_MS);
75564
+ const raw3 = fineMs < MINUTE_MS && query3.from >= now2 - RAW_MS;
75565
+ const stepMs = raw3 ? fineMs : stepFor(query3.from, query3.to, buckets, MINUTE_MS);
74994
75566
  const from = raw3 ? query3.from : Math.floor(query3.from / MINUTE_MS) * MINUTE_MS;
74995
- const rows = yield* store.buckets(raw3 ? "readings" : "minutes", { ...query3, from, stepMs }).pipe(
74996
- Effect_exports.tapError(() => Metric_exports.update(Metric_exports.withAttributes(historyFailures, { operation: "read" }), 1)),
74997
- Effect_exports.catchTags({
74998
- SqlError: (error2) => unavailable(`history could not be read: ${error2.message}`),
74999
- SchemaError: (error2) => unavailable(`history holds rows it cannot read: ${error2.message}`)
75000
- })
75567
+ const rows = yield* Effect_exports.gen(function* () {
75568
+ const target = current;
75569
+ if (target === void 0) return yield* unavailable(`the gateway keeps no history: ${off ?? "it is off"}`);
75570
+ return yield* target.store.buckets(raw3 ? "readings" : "minutes", { ...query3, from, stepMs }).pipe(
75571
+ Effect_exports.tapError(() => Metric_exports.update(Metric_exports.withAttributes(historyFailures, { operation: "read" }), 1)),
75572
+ Effect_exports.catchTags({
75573
+ SqlError: (error2) => unavailable(`history could not be read: ${error2.message}`),
75574
+ SchemaError: (error2) => unavailable(`history holds rows it cannot read: ${error2.message}`)
75575
+ })
75576
+ );
75577
+ }).pipe(
75578
+ Semaphore_exports.withPermit(permit),
75579
+ // The wait for a long write counts too: the status page gets an answer, not a hung request.
75580
+ Effect_exports.timeoutOrElse({ duration: "10 seconds", orElse: () => unavailable("history is busy, try again") })
75001
75581
  );
75002
75582
  return {
75003
75583
  device: query3.device,
@@ -76422,6 +77002,9 @@ var northbound = (config, health, options3, routing, status3, staleMeta) => {
76422
77002
  health: { topic: health.topic, online: health.online },
76423
77003
  // With a buffer, a value that cannot go out now is stored, so waiting for the broker would only stall reads.
76424
77004
  waitForConnection: config.buffer === void 0,
77005
+ ...status3 === void 0 ? {} : {
77006
+ onConnected: (connection) => Effect_exports.map(Clock_exports.currentTimeMillis, (at) => status3.recordBrokerConnection(at, connection))
77007
+ },
76425
77008
  ...options3.network === void 0 ? {} : { network: options3.network },
76426
77009
  subscriptions: [...commandSubscriptions, ...staleMeta.subscriptions],
76427
77010
  // A `$meta` topic is never a command topic (`.../$set`), so each message has one taker.
@@ -76585,6 +77168,7 @@ var check2 = Command_exports.make(
76585
77168
  jsonFailure(json4, { path: config })
76586
77169
  )
76587
77170
  ).pipe(Command_exports.withDescription("Validate a config without connecting to anything; lists every mistake with its path"));
77171
+ var pointsListOutcome = (json4) => (written) => json4 ? printJson({ ok: true, ...written }) : Effect_exports.void;
76588
77172
  var discoverCommand = Command_exports.make(
76589
77173
  "discover",
76590
77174
  {
@@ -76601,10 +77185,10 @@ var discoverCommand = Command_exports.make(
76601
77185
  ),
76602
77186
  json: jsonFlag
76603
77187
  },
76604
- // The draft is JSON already; --json makes a failure JSON too.
77188
+ // The draft is JSON already; --json makes a failure JSON too, and what --points-list wrote.
76605
77189
  ({ config, pointsList, address, json: json4 }) => Effect_exports.flatMap(loadConfig(config), (decoded) => {
76606
77190
  const options3 = { address: Option_exports.getOrUndefined(address) };
76607
- return Option_exports.isSome(pointsList) ? discoverToPointsList(decoded, pointsList.value, void 0, options3) : discover(decoded, void 0, options3);
77191
+ return Option_exports.isSome(pointsList) ? Effect_exports.flatMap(discoverToPointsList(decoded, pointsList.value, void 0, options3), pointsListOutcome(json4)) : discover(decoded, void 0, options3);
76608
77192
  }).pipe(jsonFailure(json4, { path: config }))
76609
77193
  ).pipe(
76610
77194
  Command_exports.withDescription(
@@ -76654,7 +77238,7 @@ var init2 = Command_exports.make(
76654
77238
  Argument_exports.optional,
76655
77239
  Argument_exports.map(Option_exports.getOrUndefined)
76656
77240
  ),
76657
- site: optionalFlag("site", "The site, the first topic segment (a slug: vienna-hq)"),
77241
+ site: optionalFlag("site", "The site, the first topic segment (a slug: site-1)"),
76658
77242
  building: optionalFlag("building", "The building, the second topic segment"),
76659
77243
  broker: optionalFlag("broker", "The MQTT broker URL, mqtts:// for TLS"),
76660
77244
  username: optionalFlag("username", "The broker username"),
@@ -76724,15 +77308,15 @@ var init2 = Command_exports.make(
76724
77308
  ),
76725
77309
  Command_exports.withExamples([
76726
77310
  {
76727
- command: "ot-gateway init vienna-hq",
76728
- description: "Make the folder vienna-hq and write the gateway's files in it"
77311
+ command: "ot-gateway init site-1",
77312
+ description: "Make the folder site-1 and write the gateway's files in it"
76729
77313
  },
76730
77314
  { command: "ot-gateway init .", description: "Write them in this folder" },
76731
77315
  {
76732
- command: "ot-gateway init vienna-hq --yes --site vienna-hq --broker mqtts://broker.example:8883 --points points.csv",
77316
+ command: "ot-gateway init site-1 --yes --site site-1 --broker mqtts://broker.example:8883 --points points.csv",
76733
77317
  description: "The same without questions, for scripts and agents"
76734
77318
  },
76735
- { command: "ot-gateway init vienna-hq --json --dry-run --site vienna-hq", description: "Only show it, as JSON" }
77319
+ { command: "ot-gateway init site-1 --json --dry-run --site site-1", description: "Only show it, as JSON" }
76736
77320
  ])
76737
77321
  );
76738
77322
  var importCommand = Command_exports.make(
@@ -76873,18 +77457,22 @@ var watchCommand = Command_exports.make(
76873
77457
  Command_exports.withDescription("Print what arrives at the config's broker under its site and building, as it arrives"),
76874
77458
  Command_exports.withExamples([
76875
77459
  { command: "ot-gateway watch", description: "Watch the broker in ot-gateway.json" },
76876
- { command: "ot-gateway watch --topic 'my-site/main/ahu-1/#'", description: "Only one device" },
77460
+ { command: "ot-gateway watch --topic 'site-1/building-a/heat-pump/#'", description: "Only one device" },
76877
77461
  { command: "ot-gateway watch --seconds 10", description: "Ten seconds of it, then stop" },
76878
77462
  { command: "ot-gateway watch --seconds 10 --json", description: "The same as JSON lines, for scripts and agents" }
76879
77463
  ])
76880
77464
  );
77465
+ var brokerOutcome = (json4) => Effect_exports.fnUntraced(function* (report) {
77466
+ yield* json4 ? printJson(report) : Console_exports.log(formatBrokerReport(report));
77467
+ if (!report.ok) return yield* roundTripFailure(report);
77468
+ });
76881
77469
  var brokerCommand = Command_exports.make(
76882
77470
  "broker",
76883
77471
  { config: configPath, json: jsonFlag },
76884
77472
  ({ config, json: json4 }) => loadConfig(config).pipe(
76885
77473
  Effect_exports.flatMap(checkBroker),
76886
- Effect_exports.flatMap((report) => json4 ? printJson(report) : Console_exports.log(formatBrokerReport(report))),
76887
- jsonFailure(json4, { path: config })
77474
+ jsonFailure(json4, { path: config }),
77475
+ Effect_exports.flatMap(brokerOutcome(json4))
76888
77476
  )
76889
77477
  ).pipe(
76890
77478
  Command_exports.withDescription(