ot-gateway 0.11.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 (48) hide show
  1. package/VERSION +1 -1
  2. package/apps/gateway/src/main.mjs +452 -145
  3. package/apps/web/out/404/index.html +1 -1
  4. package/apps/web/out/404.html +1 -1
  5. package/apps/web/out/__next.__PAGE__.txt +6 -6
  6. package/apps/web/out/__next._full.txt +6 -6
  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/2-12vm-gmodvi.css +1 -0
  11. package/apps/web/out/_next/static/chunks/2hhp92plmhxim.js +1 -0
  12. package/apps/web/out/_next/static/chunks/2t90haogl_st8.js +1 -0
  13. package/apps/web/out/_next/static/chunks/2vp-i92uyys5d.js +1 -0
  14. package/apps/web/out/_next/static/chunks/3k0dufyi1j19w.js +12 -0
  15. package/apps/web/out/_not-found/__next._full.txt +4 -4
  16. package/apps/web/out/_not-found/__next._not-found.__PAGE__.txt +4 -4
  17. package/apps/web/out/_not-found/__next._tree.txt +2 -2
  18. package/apps/web/out/_not-found/index.html +1 -1
  19. package/apps/web/out/_not-found/index.txt +4 -4
  20. package/apps/web/out/index.html +1 -1
  21. package/apps/web/out/index.txt +6 -6
  22. package/apps/web/out/messages/__next._full.txt +6 -6
  23. package/apps/web/out/messages/__next._tree.txt +2 -2
  24. package/apps/web/out/messages/__next.messages.__PAGE__.txt +6 -6
  25. package/apps/web/out/messages/index.html +1 -1
  26. package/apps/web/out/messages/index.txt +6 -6
  27. package/apps/web/out/points/__next._full.txt +6 -6
  28. package/apps/web/out/points/__next._tree.txt +2 -2
  29. package/apps/web/out/points/__next.points.__PAGE__.txt +6 -6
  30. package/apps/web/out/points/index.html +1 -1
  31. package/apps/web/out/points/index.txt +6 -6
  32. package/apps/web/out/settings/__next._full.txt +6 -6
  33. package/apps/web/out/settings/__next._tree.txt +2 -2
  34. package/apps/web/out/settings/__next.settings.__PAGE__.txt +6 -6
  35. package/apps/web/out/settings/index.html +1 -1
  36. package/apps/web/out/settings/index.txt +6 -6
  37. package/package.json +1 -1
  38. package/packaging/compose.yaml +1 -1
  39. package/apps/web/out/_next/static/chunks/03_syxbyimnor.js +0 -1
  40. package/apps/web/out/_next/static/chunks/1-_c1aqhwim5t.css +0 -1
  41. package/apps/web/out/_next/static/chunks/1bh2-eknm9t8k.js +0 -1
  42. package/apps/web/out/_next/static/chunks/259s9pubapqip.js +0 -1
  43. package/apps/web/out/_next/static/chunks/25dqruymh00rk.js +0 -1
  44. package/apps/web/out/_next/static/chunks/3b0ql-jh_xg_k.js +0 -12
  45. package/apps/web/out/_next/static/chunks/3o5cr1y-sws-u.js +0 -1
  46. /package/apps/web/out/_next/static/{r5hL3CDxDJkHMarR92YKm → XiBzAo3f0YeQ4E_ciqAE_}/_buildManifest.js +0 -0
  47. /package/apps/web/out/_next/static/{r5hL3CDxDJkHMarR92YKm → XiBzAo3f0YeQ4E_ciqAE_}/_clientMiddlewareManifest.js +0 -0
  48. /package/apps/web/out/_next/static/{r5hL3CDxDJkHMarR92YKm → XiBzAo3f0YeQ4E_ciqAE_}/_ssgManifest.js +0 -0
@@ -51476,6 +51476,10 @@ var mqttConnects = Metric_exports.counter("ot_gateway_mqtt_connects", {
51476
51476
  description: "Connection attempts to the MQTT broker, by outcome",
51477
51477
  incremental: true
51478
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
+ });
51479
51483
  var mqttConnected = Metric_exports.gauge("ot_gateway_mqtt_connected", {
51480
51484
  description: "Whether the gateway is connected to the MQTT broker",
51481
51485
  attributes: { unit: "{connection}" }
@@ -51615,6 +51619,9 @@ var toDeviceUnits = (value4, scaling) => {
51615
51619
  };
51616
51620
  var label = (level) => level.length <= 64 ? level : `${level.slice(0, 64)}\u2026`;
51617
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;
51618
51625
  var makeCommandGuard = (options3) => {
51619
51626
  const writeTimeout = options3.writeTimeout ?? "10 seconds";
51620
51627
  const maxAgeMillis = Duration_exports.toMillis(Duration_exports.fromInputUnsafe(options3.maxAge ?? "10 seconds"));
@@ -51664,15 +51671,29 @@ var makeCommandGuard = (options3) => {
51664
51671
  )
51665
51672
  );
51666
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
+ });
51667
51687
  const handle = Effect_exports.fn("Command")(function* (command) {
51668
51688
  const publisher = yield* Publisher;
51669
51689
  const levels = command.topic.startsWith(prefix) ? command.topic.slice(prefix.length).split("/") : [];
51670
51690
  const [deviceId = "", pointId = "", suffix] = levels;
51671
51691
  if (levels.length !== 3 || suffix !== "$set") return;
51672
- const device = options3.devices.find((candidate) => candidate.id === deviceId);
51673
51692
  const ids = { device: label(deviceId), point: label(pointId) };
51674
51693
  yield* Effect_exports.annotateCurrentSpan({ "ot_gateway.device": ids.device, "ot_gateway.point": ids.point });
51675
- 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");
51676
51697
  options3.onOutcome?.(ids, outcome);
51677
51698
  const annotations2 = { ...ids, payload: command.payload.slice(0, 200) };
51678
51699
  yield* Metric_exports.update(
@@ -51682,9 +51703,14 @@ var makeCommandGuard = (options3) => {
51682
51703
  }),
51683
51704
  1
51684
51705
  );
51685
- yield* outcome.status === "written" ? Effect_exports.logInfo("command written").pipe(Effect_exports.annotateLogs(annotations2)) : Effect_exports.logWarning(`command ${outcome.status}`).pipe(
51686
- Effect_exports.annotateLogs({ ...annotations2, reason: outcome.reason, message: outcome.message })
51687
- );
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;
51688
51714
  const ts = yield* Clock_exports.currentTimeMillis;
51689
51715
  const result4 = outcome.status === "written" ? { status: "written", value: outcome.value } : outcome;
51690
51716
  yield* publisher.publish(`${command.topic}/result`, JSON.stringify({ ...result4, ts }), {
@@ -52997,6 +53023,8 @@ var metaPayload = (point, publish2) => JSON.stringify({
52997
53023
  publish: publish2,
52998
53024
  semantics: point.semantics
52999
53025
  });
53026
+ var nothing = void 0;
53027
+ var PUBLISH_CONCURRENCY = 16;
53000
53028
  var retryPolicy = {
53001
53029
  schedule: Schedule_exports.exponential("200 millis").pipe(Schedule_exports.jittered),
53002
53030
  times: 4
@@ -53070,13 +53098,16 @@ var runDevice = Effect_exports.fn("runDevice")(function* (ctx, driver) {
53070
53098
  yield* publishRecovered(options3?.retain === true ? "metadata" : "values");
53071
53099
  });
53072
53100
  const unpublishedMeta = new Set(driver.points);
53073
- const publishMeta = Effect_exports.forEach(
53074
- [...unpublishedMeta],
53075
- (point) => publishPoint(metaTopic(topicFor(point.id)), metaPayload(point, policyOf(point.id)), { retain: true }).pipe(
53076
- Effect_exports.catchTag("PublishError", skipRefused),
53077
- Effect_exports.andThen(Effect_exports.sync(() => unpublishedMeta.delete(point)))
53078
- ),
53079
- { 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
+ )
53080
53111
  ).pipe(
53081
53112
  // The device is still read: its health is independent of the broker's.
53082
53113
  Effect_exports.catchTag(
@@ -53097,13 +53128,18 @@ var runDevice = Effect_exports.fn("runDevice")(function* (ctx, driver) {
53097
53128
  Effect_exports.annotateLogs({ point: pointId, raw: String(raw3) })
53098
53129
  );
53099
53130
  });
53100
- const handleReading = Effect_exports.fnUntraced(function* (reading, polledSince) {
53131
+ const decideReading = Effect_exports.fnUntraced(function* (reading, polledSince) {
53101
53132
  const point = points2.get(reading.pointId);
53102
- if (point === void 0) return;
53133
+ if (point === void 0) return nothing;
53103
53134
  if (polledSince === void 0) pushedAt.set(point.id, yield* Clock_exports.monotonicTimeNanos);
53104
- else if ((pushedAt.get(point.id) ?? -1n) >= polledSince) return;
53135
+ else if ((pushedAt.get(point.id) ?? -1n) >= polledSince) return nothing;
53105
53136
  const value4 = typeof reading.value === "number" ? applyScaling(reading.value, point.scaling) : reading.value;
53106
- 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
+ }
53107
53143
  if (nonFinitePoints.delete(point.id)) {
53108
53144
  yield* Effect_exports.logInfo("point delivers numbers again").pipe(Effect_exports.annotateLogs({ point: point.id }));
53109
53145
  }
@@ -53116,33 +53152,40 @@ var runDevice = Effect_exports.fn("runDevice")(function* (ctx, driver) {
53116
53152
  const policy2 = policyOf(point.id);
53117
53153
  switch (policy2.mode) {
53118
53154
  case "sample": {
53119
- if (policy2.intervalMs === void 0) {
53120
- yield* send(point.id, message);
53121
- return;
53122
- }
53155
+ if (policy2.intervalMs === void 0) return { pointId: point.id, message };
53123
53156
  latest.set(point.id, message);
53124
53157
  fresh2.add(point.id);
53125
- return;
53158
+ return nothing;
53126
53159
  }
53127
53160
  case "aggregate": {
53128
53161
  const atMono = yield* monotonicMillis;
53129
53162
  windows.set(point.id, addReading(windows.get(point.id) ?? openWindow(atMono), value4, atMono, reading.timestamp));
53130
- return;
53163
+ return nothing;
53131
53164
  }
53132
53165
  case "change": {
53133
53166
  const atMono = yield* monotonicMillis;
53134
53167
  const sentAt = lastSentAt.get(point.id);
53135
53168
  const quietTooLong = policy2.maxSilenceMs !== void 0 && sentAt !== void 0 && atMono - sentAt >= policy2.maxSilenceMs;
53136
53169
  if (!quietTooLong && !exceedsDeadband(Option_exports.fromUndefinedOr(last2.get(point.id)), value4, policy2.deadband)) {
53137
- return yield* Metric_exports.update(counters.suppressed, 1);
53170
+ yield* Metric_exports.update(counters.suppressed, 1);
53171
+ return nothing;
53138
53172
  }
53139
- if (!(yield* send(point.id, message))) return;
53140
- last2.set(point.id, value4);
53141
- lastSentAt.set(point.id, atMono);
53142
- 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
+ };
53143
53181
  }
53144
53182
  }
53145
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
+ });
53146
53189
  let unavailable2;
53147
53190
  const send = Effect_exports.fnUntraced(function* (pointId, message) {
53148
53191
  if (unavailable2 !== void 0) return false;
@@ -53153,15 +53196,30 @@ var runDevice = Effect_exports.fn("runDevice")(function* (ctx, driver) {
53153
53196
  if (sent) yield* Metric_exports.update(counters.published, 1);
53154
53197
  return sent;
53155
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
+ });
53156
53211
  const closeWindows = Effect_exports.fnUntraced(function* (intervalMs, endMs) {
53157
53212
  const atMono = yield* monotonicMillis;
53213
+ let failed;
53158
53214
  for (const point of driver.points) {
53159
53215
  const policy2 = policyOf(point.id);
53160
53216
  if (windowIntervalMs(policy2) !== intervalMs) continue;
53161
53217
  if (policy2.mode === "sample") {
53162
53218
  const message = latest.get(point.id);
53163
- if (message === void 0 || !fresh2.delete(point.id)) continue;
53164
- 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);
53165
53223
  continue;
53166
53224
  }
53167
53225
  const window2 = windows.get(point.id);
@@ -53169,8 +53227,11 @@ var runDevice = Effect_exports.fn("runDevice")(function* (ctx, driver) {
53169
53227
  const closed = closeWindow(window2, atMono, endMs, intervalMs, point.unit);
53170
53228
  windows.set(point.id, closed.next);
53171
53229
  if (closed.message === void 0 || closed.message.count === 0 && deviceProblem !== void 0) continue;
53172
- 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;
53173
53233
  }
53234
+ if (failed !== void 0) return yield* failed;
53174
53235
  });
53175
53236
  const interruptWindows = Effect_exports.gen(function* () {
53176
53237
  if (windows.size === 0) return;
@@ -53179,6 +53240,11 @@ var runDevice = Effect_exports.fn("runDevice")(function* (ctx, driver) {
53179
53240
  });
53180
53241
  const handling = yield* Semaphore_exports.make(1);
53181
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
+ };
53182
53248
  const deadline = (stage) => Effect_exports.timeoutOrElse({
53183
53249
  duration: deadlineMs,
53184
53250
  orElse: () => Effect_exports.fail(
@@ -53186,7 +53252,7 @@ var runDevice = Effect_exports.fn("runDevice")(function* (ctx, driver) {
53186
53252
  device: driver.deviceId,
53187
53253
  stage,
53188
53254
  timeoutMs: deadlineMs,
53189
- message: `${stage === "poll-cycle" ? "polling cycle" : "pushed value"} did not finish within ${deadlineMs} ms`
53255
+ message: `${stageNames[stage]} did not finish within ${deadlineMs} ms`
53190
53256
  })
53191
53257
  )
53192
53258
  });
@@ -53205,10 +53271,19 @@ var runDevice = Effect_exports.fn("runDevice")(function* (ctx, driver) {
53205
53271
  const failedPublish = yield* handling.withPermit(
53206
53272
  Effect_exports.gen(function* () {
53207
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 = [];
53208
53282
  for (const reading of readings) {
53209
- const handled = yield* Effect_exports.result(handleReading(reading, polledSince));
53210
- if (Result_exports.isFailure(handled)) unavailable2 ??= handled.failure;
53283
+ const decided = yield* decideReading(reading, polledSince);
53284
+ if (decided !== void 0) outgoing.push(decided);
53211
53285
  }
53286
+ yield* Effect_exports.forEach(outgoing, publishOutgoing, { concurrency: PUBLISH_CONCURRENCY, discard: true });
53212
53287
  return unavailable2;
53213
53288
  }).pipe(
53214
53289
  // Also when the cycle's deadline interrupts it: pushed values and closing windows must not skip publishing.
@@ -56123,6 +56198,9 @@ var makeBacnetDriverFromClient = Effect_exports.fn("makeBacnetDriverFromClient")
56123
56198
  let multipleRecheckAt = 0;
56124
56199
  let reprobing = false;
56125
56200
  let cleanCycles = 0;
56201
+ let refusedAt;
56202
+ let largestAnswered = 0;
56203
+ const shrinksLogged = /* @__PURE__ */ new Set();
56126
56204
  let lostCycles = 0;
56127
56205
  let nextBroadcastAt = 0;
56128
56206
  let broadcastBackoffMs = LOCATE_BACKOFF.firstMs;
@@ -56141,6 +56219,9 @@ var makeBacnetDriverFromClient = Effect_exports.fn("makeBacnetDriverFromClient")
56141
56219
  multiple = true;
56142
56220
  reprobing = false;
56143
56221
  cleanCycles = 0;
56222
+ refusedAt = void 0;
56223
+ largestAnswered = 0;
56224
+ shrinksLogged.clear();
56144
56225
  lostCycles = 0;
56145
56226
  broadcastBackoffMs = LOCATE_BACKOFF.firstMs;
56146
56227
  isolated.clear();
@@ -56257,6 +56338,10 @@ var makeBacnetDriverFromClient = Effect_exports.fn("makeBacnetDriverFromClient")
56257
56338
  Effect_exports.annotateLogs({ reason: why, askingAgainInSeconds: RECHECK_MS / 1e3 })
56258
56339
  );
56259
56340
  });
56341
+ const shrinkFrom = (refused) => {
56342
+ const answered = largestAnswered < refused ? largestAnswered : 1;
56343
+ batchSize = Math.max(1, Math.floor(refused / 2), answered);
56344
+ };
56260
56345
  const readBatch = (target, batch) => client.readPropertyMultiple(target, specificationsOf(batch)).pipe(
56261
56346
  Effect_exports.map((results2) => ({ _tag: "Results", results: results2 })),
56262
56347
  Effect_exports.catchTags({
@@ -56302,6 +56387,7 @@ var makeBacnetDriverFromClient = Effect_exports.fn("makeBacnetDriverFromClient")
56302
56387
  reprobing = false;
56303
56388
  yield* Effect_exports.log("device answers ReadPropertyMultiple again");
56304
56389
  }
56390
+ largestAnswered = Math.max(largestAnswered, batch.length);
56305
56391
  const timestamp = yield* Clock_exports.currentTimeMillis;
56306
56392
  const byKey = /* @__PURE__ */ new Map();
56307
56393
  for (const result4 of results2) {
@@ -56398,23 +56484,26 @@ var makeBacnetDriverFromClient = Effect_exports.fn("makeBacnetDriverFromClient")
56398
56484
  continue;
56399
56485
  case "Refused": {
56400
56486
  const { error: error2 } = answer3;
56401
- const full = batch.length === batchSize && batchSize > 1;
56487
+ const several = batch.length > 1;
56402
56488
  const refusal = refusalOf(error2);
56403
56489
  switch (refusal) {
56404
56490
  case "unsupported":
56405
56491
  yield* downgrade(error2.message);
56406
56492
  continue;
56407
56493
  case "too-large":
56408
- if (!full) break;
56409
- 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);
56410
56497
  shrunk = true;
56498
+ if (shrinksLogged.has(batchSize)) continue;
56499
+ shrinksLogged.add(batchSize);
56411
56500
  yield* Effect_exports.log("answer too large for the device, reading fewer points per request").pipe(
56412
56501
  Effect_exports.annotateLogs({ batchSize })
56413
56502
  );
56414
56503
  continue;
56415
56504
  case "busy":
56416
- if (full && outOfRoom(error2)) {
56417
- batchSize = Math.max(1, Math.floor(batchSize / 2));
56505
+ if (several && outOfRoom(error2)) {
56506
+ shrinkFrom(batch.length);
56418
56507
  shrunk = true;
56419
56508
  }
56420
56509
  stop.busy = new DeviceBusy({ message: error2.message });
@@ -56440,14 +56529,15 @@ var makeBacnetDriverFromClient = Effect_exports.fn("makeBacnetDriverFromClient")
56440
56529
  return { outcomes, requests, shrunk, ...stop };
56441
56530
  });
56442
56531
  const regrow = (shrunk) => Effect_exports.suspend(() => {
56443
- if (shrunk || !multiple || batchSize >= largestBatch) {
56532
+ const ceiling = refusedAt === void 0 ? largestBatch : Math.min(largestBatch, refusedAt - 1);
56533
+ if (shrunk || !multiple || batchSize >= ceiling) {
56444
56534
  cleanCycles = 0;
56445
56535
  return Effect_exports.void;
56446
56536
  }
56447
56537
  cleanCycles++;
56448
56538
  if (cleanCycles < REGROW_AFTER_CYCLES) return Effect_exports.void;
56449
56539
  cleanCycles = 0;
56450
- 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));
56451
56541
  return Effect_exports.log("trying more points per request again").pipe(Effect_exports.annotateLogs({ batchSize }));
56452
56542
  });
56453
56543
  const report = (outcomes) => Effect_exports.forEach(
@@ -56519,6 +56609,8 @@ var makeBacnetDriverFromClient = Effect_exports.fn("makeBacnetDriverFromClient")
56519
56609
  const waitSeconds2 = Math.ceil((busyUntil - now2) / 1e3);
56520
56610
  return yield* fail19("protocol", `device is busy (${busyReason ?? "aborted"}); asking again in ${waitSeconds2} s`);
56521
56611
  }
56612
+ const wasLost = lostCycles > 0;
56613
+ const locatedBefore = location2;
56522
56614
  const target = yield* locate;
56523
56615
  const { outcomes, requests, shrunk, timedOut, busy } = yield* readPoints(target, polled);
56524
56616
  yield* report(outcomes);
@@ -56541,9 +56633,9 @@ var makeBacnetDriverFromClient = Effect_exports.fn("makeBacnetDriverFromClient")
56541
56633
  const reasons = [...new Set(outcomes.flatMap((outcome) => outcome._tag === "Failed" ? [outcome.reason] : []))];
56542
56634
  return yield* fail19("protocol", `no point could be read (${reasons.join(", ")})`);
56543
56635
  }
56544
- if (lostCycles > 0) {
56636
+ if (wasLost) {
56545
56637
  cov?.resync();
56546
- yield* Effect_exports.log("BACnet device answers again");
56638
+ if (target === locatedBefore) yield* Effect_exports.log("BACnet device answers again");
56547
56639
  }
56548
56640
  lostCycles = 0;
56549
56641
  yield* countPointFailures("not_read", notReadPoints);
@@ -58233,11 +58325,11 @@ var decodeConnect = (body) => decodeWith2(body, (r) => {
58233
58325
  if ((flags & 4) !== 0) {
58234
58326
  if (v5) r.properties();
58235
58327
  const topic = r.string();
58236
- const payload = decoder4.decode(r.binary());
58328
+ const payload = r.string();
58237
58329
  will = { topic, payload, qos: flags >> 3 & 1 ? 1 : 0, retain: (flags & 32) !== 0 };
58238
58330
  }
58239
58331
  const username = (flags & 128) !== 0 ? r.string() : void 0;
58240
- const password = (flags & 64) !== 0 ? decoder4.decode(r.binary()) : void 0;
58332
+ const password = (flags & 64) !== 0 ? r.string() : void 0;
58241
58333
  const expiry = properties.get(Property.SessionExpiryInterval);
58242
58334
  const maximumPacketSize = properties.get(Property.MaximumPacketSize);
58243
58335
  return {
@@ -58485,6 +58577,7 @@ var MqttPublishError = class extends Schema_exports.TaggedError()("MqttPublishEr
58485
58577
  };
58486
58578
  var stableConnectionMs = 3e4;
58487
58579
  var maxPubackTimeouts = 2;
58580
+ var SUBACK_TIMEOUT = Duration_exports.seconds(10);
58488
58581
  var defaultMaximumPacketSize = 1024 * 1024;
58489
58582
  var encoder10 = new TextEncoder();
58490
58583
  var lenientDecoder = new TextDecoder();
@@ -58493,6 +58586,7 @@ var numberProperty = (properties, id2, fallback) => {
58493
58586
  return typeof value4 === "number" ? value4 : fallback;
58494
58587
  };
58495
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);
58496
58590
  var topicProblem = (topic) => {
58497
58591
  if (topic.length === 0) return "topic is empty";
58498
58592
  if (topic.includes("+") || topic.includes("#")) return "topic contains a wildcard";
@@ -58678,10 +58772,25 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58678
58772
  );
58679
58773
  if (options3.onConnect !== void 0) yield* Effect_exports.forkScoped(options3.onConnect(client));
58680
58774
  const subscriptions = options3.subscriptions ?? [];
58775
+ const filters = subscriptions.map((subscription) => subscription.filter).join(", ");
58776
+ let pendingSubscribe;
58777
+ let subscribeMissed = false;
58681
58778
  if (subscriptions.length > 0) {
58682
58779
  const packetId = current.nextPacketId;
58683
58780
  current.nextPacketId = packetId % 65535 + 1;
58781
+ pendingSubscribe = packetId;
58684
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
+ );
58685
58794
  }
58686
58795
  let lastReceived = yield* monotonicMillis;
58687
58796
  const readLoop2 = Effect_exports.gen(function* () {
@@ -58724,7 +58833,19 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58724
58833
  }
58725
58834
  case PacketType.SUBACK: {
58726
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;
58727
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
+ }
58728
58849
  if (refused.length > 0) {
58729
58850
  yield* Effect_exports.logError(
58730
58851
  "MQTT broker refused a subscription; nothing published on it will arrive"
@@ -58936,6 +59057,20 @@ var MqttSettingsError = class extends Schema_exports.TaggedError()("MqttSettings
58936
59057
  message: Schema_exports.String
58937
59058
  }) {
58938
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
+ });
58939
59074
  var parseBrokerUrl = (url) => Effect_exports.gen(function* () {
58940
59075
  const parsed = URL.parse(url);
58941
59076
  if (parsed === null) return yield* new MqttSettingsError({ message: "mqtt.url is not a URL" });
@@ -58971,7 +59106,7 @@ var MqttPublisher = (settings, options3 = {}) => Layer_exports.effect(
58971
59106
  Publisher,
58972
59107
  Effect_exports.gen(function* () {
58973
59108
  const address = yield* parseBrokerUrl(settings.url);
58974
- const password = settings.passwordEnv === void 0 ? void 0 : yield* Config_exports.Redacted(settings.passwordEnv);
59109
+ const password = yield* readBrokerPassword(settings);
58975
59110
  const passwordWarning = mqttPasswordWarning(settings);
58976
59111
  if (passwordWarning !== void 0) {
58977
59112
  yield* Effect_exports.logWarning(passwordWarning).pipe(
@@ -59077,6 +59212,9 @@ var makeBrokerControl = () => ({
59077
59212
  pubackReason: 0,
59078
59213
  refusedTopics: /* @__PURE__ */ new Set(),
59079
59214
  answerPings: true,
59215
+ ackSubscribes: true,
59216
+ routeMessages: true,
59217
+ refusedFilters: /* @__PURE__ */ new Set(),
59080
59218
  connects: [],
59081
59219
  messages: [],
59082
59220
  retained: /* @__PURE__ */ new Map(),
@@ -59122,6 +59260,7 @@ var accept = (control, message) => {
59122
59260
  control.retained.set(message.topic, message.payload);
59123
59261
  control.retainedMessages.set(message.topic, message);
59124
59262
  }
59263
+ if (!control.routeMessages) return;
59125
59264
  for (const subscriber of control.subscribers) deliver(subscriber, message, false);
59126
59265
  };
59127
59266
  var serveConnection2 = (control) => Effect_exports.fnUntraced(
@@ -59200,17 +59339,24 @@ var serveConnection2 = (control) => Effect_exports.fnUntraced(
59200
59339
  case PacketType.SUBSCRIBE: {
59201
59340
  const subscribe2 = decodeSubscribe(split4.body, subscriber.version);
59202
59341
  if (Result_exports.isFailure(subscribe2) || clientId === void 0) return;
59203
- subscriber.subscriptions.push(...subscribe2.success.subscriptions);
59204
- yield* writer.write(
59205
- encodeSuback(
59206
- {
59207
- packetId: subscribe2.success.packetId,
59208
- reasonCodes: subscribe2.success.subscriptions.map((subscription) => subscription.qos)
59209
- },
59210
- subscriber.version
59211
- )
59342
+ const granted = subscribe2.success.subscriptions.filter(
59343
+ (subscription) => !control.refusedFilters.has(subscription.filter)
59212
59344
  );
59213
- 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] };
59214
59360
  for (const message of control.retainedMessages.values()) deliver(fresh2, message, true);
59215
59361
  subscriber.nextPacketId = fresh2.nextPacketId;
59216
59362
  break;
@@ -59557,7 +59703,8 @@ var draftDevices = (found, existing = []) => {
59557
59703
  };
59558
59704
  });
59559
59705
  };
59560
- 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);
59561
59708
  var hex = (bytes3) => Array.from(bytes3, (byte) => byte.toString(16).padStart(2, "0")).join(":");
59562
59709
  var sourceText = (source) => printable(
59563
59710
  formatInet(source.address) + (source.network === void 0 ? "" : ` (network ${source.network.network}, address ${hex(source.network.address)})`)
@@ -59668,7 +59815,9 @@ var draftPointsList = (drafts) => {
59668
59815
  var discoverToPointsList = Effect_exports.fn("discoverToPointsList")(function* (config, path, network, options3 = {}) {
59669
59816
  const fs = yield* FileSystem_exports.FileSystem;
59670
59817
  if (yield* fs.exists(path)) {
59671
- 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
+ });
59672
59821
  }
59673
59822
  const configured = new Set(config.devices.map((device) => device.id));
59674
59823
  const drafts = yield* discoverDrafts(config, network, options3);
@@ -59679,11 +59828,13 @@ var discoverToPointsList = Effect_exports.fn("discoverToPointsList")(function* (
59679
59828
  );
59680
59829
  }
59681
59830
  const points2 = fresh2.reduce((total, draft) => total + draft.points.length, 0);
59682
- 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.` });
59683
59832
  yield* fs.writeFileString(path, draftPointsList(fresh2), { flag: "wx" });
59684
59833
  yield* Console_exports.error(
59685
59834
  `wrote ${points2} point(s) of ${fresh2.length} device(s) to ${path}. Delete the rows you do not need, then: ot-gateway import ${path}`
59686
59835
  );
59836
+ const written = { path, devices: fresh2.length, points: points2 };
59837
+ return written;
59687
59838
  });
59688
59839
 
59689
59840
  // src/Suggest.ts
@@ -59719,16 +59870,19 @@ var PointsListError = class extends Schema_exports.TaggedError()("PointsListErro
59719
59870
  message: Schema_exports.String
59720
59871
  }) {
59721
59872
  };
59722
- var parseDelimited = (text4, separator) => {
59873
+ var readDelimited = (text4, separator) => {
59723
59874
  const body = text4.replace(/^/, "");
59724
59875
  const firstLine = body.split(/\r?\n/, 1)[0] ?? "";
59725
59876
  const delimiter = separator ?? [";", " ", ","].reduce(
59726
59877
  (best, candidate) => firstLine.split(candidate).length > firstLine.split(best).length ? candidate : best
59727
59878
  );
59728
- const rows = [];
59879
+ const records = [];
59729
59880
  let row = [];
59730
59881
  let field = "";
59731
59882
  let quoted = false;
59883
+ let line = 1;
59884
+ let rowLine = 1;
59885
+ let quoteLine = 1;
59732
59886
  for (let index2 = 0; index2 < body.length; index2++) {
59733
59887
  const char = body[index2];
59734
59888
  if (quoted) {
@@ -59736,24 +59890,36 @@ var parseDelimited = (text4, separator) => {
59736
59890
  field += '"';
59737
59891
  index2++;
59738
59892
  } else if (char === '"') quoted = false;
59739
- else field += char;
59740
- } else if (char === '"' && field === "") quoted = true;
59741
- 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) {
59742
59901
  row.push(field);
59743
59902
  field = "";
59744
59903
  } else if (char === "\n" || char === "\r") {
59745
59904
  if (char === "\r" && body[index2 + 1] === "\n") index2++;
59746
59905
  row.push(field);
59747
- rows.push(row);
59906
+ records.push({ line: rowLine, fields: row });
59748
59907
  row = [];
59749
59908
  field = "";
59909
+ line++;
59910
+ rowLine = line;
59750
59911
  } else field += char;
59751
59912
  }
59752
- if (field !== "" || row.length > 0) {
59913
+ if (field !== "" || row.length > 0 || quoted) {
59753
59914
  row.push(field);
59754
- rows.push(row);
59915
+ records.push({ line: rowLine, fields: row });
59755
59916
  }
59756
- 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);
59757
59923
  };
59758
59924
  var units = {
59759
59925
  w: "unit:W",
@@ -59813,6 +59979,29 @@ var columnAliases = {
59813
59979
  publish_interval_s: "publish_s",
59814
59980
  publish_every_s: "publish_s"
59815
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
+ ];
59816
60005
  var columnName = (header) => {
59817
60006
  const normal = header.trim().toLowerCase().replace(/[\s-]+/g, "_");
59818
60007
  return columnAliases[normal] ?? normal;
@@ -59974,11 +60163,15 @@ var namedPoints = Effect_exports.fnUntraced(function* (name, rows) {
59974
60163
  }
59975
60164
  return points2;
59976
60165
  });
59977
- var toDevice = Effect_exports.fnUntraced(function* (name, rows, taken) {
60166
+ var toDevice = Effect_exports.fnUntraced(function* (name, rows, inConfig, listed) {
59978
60167
  const id2 = slugify(name);
59979
60168
  if (id2 === "") return yield* fail17(`device "${name}": its name has no letters or digits`);
59980
- if (taken.has(id2)) return yield* fail17(`device id "${id2}" is already in the config`);
59981
- 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);
59982
60175
  const points2 = yield* namedPoints(name, rows);
59983
60176
  const intervalSeconds = yield* deviceNumber(name, rows, "interval_s");
59984
60177
  const pollIntervalMs2 = intervalSeconds === void 0 ? {} : { pollIntervalMs: Math.round(intervalSeconds * 1e3) };
@@ -60011,16 +60204,34 @@ var toDevice = Effect_exports.fnUntraced(function* (name, rows, taken) {
60011
60204
  return yield* fail17(`device "${name}": give it a host (Modbus TCP) or a device_instance (BACnet/IP)`);
60012
60205
  });
60013
60206
  var devicesFromPointsList = Effect_exports.fn("devicesFromPointsList")(function* (text4, existing = [], profiles2 = /* @__PURE__ */ new Map()) {
60014
- const [header, ...records] = parseDelimited(text4);
60015
- 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;
60016
60212
  const columns = header.map(columnName);
60017
60213
  for (const required2 of ["device", "point"]) {
60018
60214
  if (!columns.includes(required2)) {
60019
60215
  return yield* fail17(`the points list needs a "${required2}" column; its header has ${header.join(", ")}`);
60020
60216
  }
60021
60217
  }
60022
- const rows = records.map((fields, index2) => ({
60023
- 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,
60024
60235
  get: (column) => {
60025
60236
  const value4 = fields[columns.indexOf(column)]?.trim();
60026
60237
  return value4 === void 0 || value4 === "" ? void 0 : value4;
@@ -60032,8 +60243,9 @@ var devicesFromPointsList = Effect_exports.fn("devicesFromPointsList")(function*
60032
60243
  if (device === void 0) return yield* fail17(`line ${row.line}: no device`);
60033
60244
  byDevice.set(device, [...byDevice.get(device) ?? [], ...yield* expandProfile(row, profiles2)]);
60034
60245
  }
60035
- const taken = new Set(existing);
60036
- 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));
60037
60249
  });
60038
60250
 
60039
60251
  // src/Ede.ts
@@ -60060,8 +60272,12 @@ var edeToPointsList = Effect_exports.fn("edeToPointsList")(function* (text4) {
60060
60272
  const delimiter = [";", " ", ","].reduce(
60061
60273
  (best, candidate) => headerText.split(candidate).length > headerText.split(best).length ? candidate : best
60062
60274
  );
60063
- const [header = [], ...records] = parseDelimited(lines2.slice(start).join("\n"), delimiter);
60064
- 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);
60065
60281
  const column = (name) => columns.indexOf(name);
60066
60282
  const at = {
60067
60283
  device: column("deviceobjinstance"),
@@ -60079,8 +60295,9 @@ var edeToPointsList = Effect_exports.fn("edeToPointsList")(function* (text4) {
60079
60295
  if (index2 < 0) return yield* fail18(`the EDE header has no ${name} column`);
60080
60296
  }
60081
60297
  const objects = [];
60082
- for (const [index2, fields] of records.entries()) {
60083
- const line = start + index2 + 2;
60298
+ for (const record2 of records) {
60299
+ const line = start + record2.line;
60300
+ const fields = record2.fields;
60084
60301
  if ((fields[0] ?? "").trim().startsWith("#")) continue;
60085
60302
  const field = (position) => (fields[position] ?? "").trim();
60086
60303
  const device = Number(field(at.device));
@@ -60246,7 +60463,7 @@ var pointsListRules = [
60246
60463
  "CSV with a header row and one row per point; commas, semicolons or tabs, as the header line uses",
60247
60464
  "Column names in any order and case; spaces and - count as _; unknown columns are named and ignored",
60248
60465
  "A row with host is Modbus TCP, a row with device_instance is BACnet/IP; one list can hold both",
60249
- "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",
60250
60467
  "A row with a profile takes its registers from the profile; its other columns (unit, scale, byte_order, publish) still win",
60251
60468
  "A BACnet EDE file (the semicolon CSV engineering tools export) is read as a list too; points from-ede shows it as one",
60252
60469
  "Nothing is made writable: writes are set in the config, on purpose"
@@ -60747,7 +60964,7 @@ var devicesFrom = Effect_exports.fn("devicesFrom")(function* (source, answers, f
60747
60964
  }
60748
60965
  return usable;
60749
60966
  });
60750
- var runInit = Effect_exports.fn("runInit")(function* (path, flags = {}) {
60967
+ var runInit = Effect_exports.fn("runInit")(function* (path, flags = {}, lans = () => lanInterfaces(networkInterfaces2())) {
60751
60968
  const fs = yield* FileSystem_exports.FileSystem;
60752
60969
  const yes = flags.yes === true;
60753
60970
  if (flags.points !== void 0 && flags.devices !== void 0 && flags.devices !== "list") {
@@ -60762,8 +60979,12 @@ var runInit = Effect_exports.fn("runInit")(function* (path, flags = {}) {
60762
60979
  const building = yield* slug("building", flags.building, yes, "Building (the second)", "main");
60763
60980
  const answers = { site, building, brokerUrl: yield* brokerUrl(flags), login: yield* login(flags) };
60764
60981
  const source = flags.points === void 0 ? flags.devices ?? (yes ? "simulated" : yield* deviceSource) : "list";
60765
- const withNetwork = source === "discover" ? { ...answers, broadcastAddress: yield* broadcastAddress(lanInterfaces(networkInterfaces2()), flags) } : answers;
60766
- 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)}
60767
60988
  `;
60768
60989
  const config = yield* parseConfig2(text4);
60769
60990
  if (flags.dryRun === true) return config;
@@ -71783,7 +72004,7 @@ var BrokerCommandError = class extends Schema_exports.TaggedError()("BrokerComma
71783
72004
  var randomSuffix = Effect_exports.map(Random_exports.nextIntBetween(0, 16777215), (value4) => value4.toString(16).padStart(6, "0"));
71784
72005
  var brokerClient = Effect_exports.fn("brokerClient")(function* (settings, role, options3 = {}) {
71785
72006
  const address = yield* parseBrokerUrl(settings.url);
71786
- const password = settings.passwordEnv === void 0 ? void 0 : yield* Config_exports.Redacted(settings.passwordEnv);
72007
+ const password = yield* readBrokerPassword(settings);
71787
72008
  const openTimeout2 = "10 seconds";
71788
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 });
71789
72010
  return yield* makeMqttClient(socket, {
@@ -71808,6 +72029,7 @@ var firstDialOf = (client, url) => client.firstDial.pipe(
71808
72029
  )
71809
72030
  )
71810
72031
  );
72032
+ var topicRoot = (topic) => topic.split("/").slice(0, 2).join("/");
71811
72033
  var brokerWarnings = (info2, roundTripMs, topic) => [
71812
72034
  ...info2.protocolVersion === "3.1.1" ? [
71813
72035
  "MQTT 3.1.1: the broker announces no limits, commands get no correlation data and messages no expiry (docs/configuration.md, mqtt.version)"
@@ -71815,7 +72037,7 @@ var brokerWarnings = (info2, roundTripMs, topic) => [
71815
72037
  ...info2.retainAvailable ? [] : ["the broker keeps no retained messages: $meta and health reach only clients connected at the time"],
71816
72038
  ...info2.maximumQoS === 0 ? ["the broker allows QoS 0 only: nothing confirms that a message arrived, so the buffer cannot help"] : [],
71817
72039
  ...roundTripMs === void 0 ? [
71818
- `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)`
71819
72041
  ] : []
71820
72042
  ];
71821
72043
  var checkBroker = Effect_exports.fn("checkBroker")(function* (config) {
@@ -71846,7 +72068,7 @@ var checkBroker = Effect_exports.fn("checkBroker")(function* (config) {
71846
72068
  onSome: (at) => Math.max(0, at - sentAt)
71847
72069
  });
71848
72070
  const report = {
71849
- ok: true,
72071
+ ok: roundTripMs !== void 0,
71850
72072
  broker: config.mqtt.url,
71851
72073
  ...info2,
71852
72074
  ...roundTripMs === void 0 ? {} : { roundTripMs },
@@ -71862,21 +72084,27 @@ var formatBrokerReport = (report) => [
71862
72084
  report.roundTripMs === void 0 ? ` round trip: NO ANSWER within ${ROUND_TRIP_TIMEOUT}` : ` round trip: ${report.roundTripMs} ms (QoS 1, through ${report.roundTripTopic})`,
71863
72085
  ...report.warnings.map((warning) => ` warning: ${warning}`)
71864
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
+ });
71865
72090
  var publishOnce = Effect_exports.fn("publishOnce")(function* (config, topic, payload, options3) {
71866
72091
  const client = yield* brokerClient(config.mqtt, "publish");
71867
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;
71868
72095
  yield* client.publish(topic, payload, { qos: options3.qos, retain: options3.retain }).pipe(Effect_exports.mapError((error2) => new BrokerCommandError({ message: `${topic}: ${error2.message}` })));
71869
72096
  return {
71870
72097
  ok: true,
71871
72098
  broker: config.mqtt.url,
71872
72099
  topic,
71873
72100
  bytes: new TextEncoder().encode(payload).length,
71874
- qos: options3.qos,
72101
+ qos,
72102
+ ...qos === options3.qos ? {} : { requestedQos: options3.qos },
71875
72103
  retain: options3.retain,
71876
72104
  cleared: options3.retain && payload === ""
71877
72105
  };
71878
72106
  }, Effect_exports.scoped);
71879
- 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" : ""})`;
71880
72108
 
71881
72109
  // src/Watch.ts
71882
72110
  var MAX_PAYLOAD = 300;
@@ -71884,9 +72112,9 @@ var watchFilter = (config) => `${config.site}/${config.building}/#`;
71884
72112
  var twoDigits = (value4) => String(value4).padStart(2, "0");
71885
72113
  var formatMessage2 = (message, at) => {
71886
72114
  const time2 = `${twoDigits(at.getHours())}:${twoDigits(at.getMinutes())}:${twoDigits(at.getSeconds())}`;
71887
- const flat = message.payload.replace(/\s*\n\s*/g, " ");
72115
+ const flat = withoutControls(message.payload.replace(/\s*\n\s*/g, " ").replace(/[\t\r]/g, " "));
71888
72116
  const payload = flat.length > MAX_PAYLOAD ? `${flat.slice(0, MAX_PAYLOAD)}\u2026` : flat;
71889
- return `${time2} ${message.retain ? "retained " : ""}${message.topic} ${payload}`;
72117
+ return `${time2} ${message.retain ? "retained " : ""}${withoutControls(message.topic)} ${payload}`;
71890
72118
  };
71891
72119
  var messageRecord = (message, at) => {
71892
72120
  let payload = message.payload;
@@ -71898,7 +72126,7 @@ var messageRecord = (message, at) => {
71898
72126
  };
71899
72127
  var watch3 = Effect_exports.fn("watch")(function* (config, options3 = {}) {
71900
72128
  const filter14 = options3.topic ?? watchFilter(config);
71901
- yield* brokerClient(config.mqtt, "watch", {
72129
+ const client = yield* brokerClient(config.mqtt, "watch", {
71902
72130
  subscriptions: [{ filter: filter14, qos: 0, retainAsPublished: true }],
71903
72131
  onConnect: () => Console_exports.error(
71904
72132
  `watching ${filter14} on ${config.mqtt.url} (${options3.seconds === void 0 ? "Ctrl-C to stop" : `for ${options3.seconds} s`})`
@@ -71907,6 +72135,7 @@ var watch3 = Effect_exports.fn("watch")(function* (config, options3 = {}) {
71907
72135
  });
71908
72136
  yield* Console_exports.error(`connecting to ${config.mqtt.url}\u2026`);
71909
72137
  if (options3.seconds === void 0) return yield* Effect_exports.never;
72138
+ yield* firstDialOf(client, config.mqtt.url);
71910
72139
  yield* Effect_exports.sleep(Duration_exports.seconds(options3.seconds));
71911
72140
  }, Effect_exports.scoped);
71912
72141
 
@@ -72424,6 +72653,7 @@ var outboxMigrations = Migrator_exports.fromRecord({
72424
72653
  `;
72425
72654
  })
72426
72655
  });
72656
+ var withoutSpans = Effect_exports.withTracerEnabled(false);
72427
72657
  var makeOutbox = (sql) => {
72428
72658
  const countRows = SqlSchema_exports.findAll({
72429
72659
  Request: Schema_exports.Int,
@@ -72464,20 +72694,21 @@ var makeOutbox = (sql) => {
72464
72694
  );
72465
72695
  return {
72466
72696
  /** Rows with an id above `after` (0 for all of them). */
72467
- 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),
72468
72698
  append: (topic, payload, qos, createdAt) => sql`INSERT INTO outbox (topic, payload, qos, created_at) VALUES (${topic}, ${payload}, ${qos}, ${createdAt})`.pipe(
72469
- Effect_exports.asVoid
72699
+ Effect_exports.asVoid,
72700
+ withoutSpans
72470
72701
  ),
72471
72702
  /** The `limit` oldest rows with an id above `after`. */
72472
- oldest,
72703
+ oldest: (limit, after) => oldest(limit, after).pipe(withoutSpans),
72473
72704
  /** Delete the given rows; returns how many were still there. */
72474
- 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),
72475
72706
  /** Delete every row up to and including `id`. */
72476
- 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),
72477
72708
  /** Delete the `count` oldest rows with an id above `after`; returns how many were deleted. */
72478
- 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),
72479
72710
  /** Return free pages to the file system (new files use `auto_vacuum = INCREMENTAL`; elsewhere a no-op). */
72480
- vacuum: sql`PRAGMA incremental_vacuum`.pipe(Effect_exports.asVoid)
72711
+ vacuum: sql`PRAGMA incremental_vacuum`.pipe(Effect_exports.asVoid, withoutSpans)
72481
72712
  };
72482
72713
  };
72483
72714
 
@@ -72552,12 +72783,13 @@ var openOnce = (path) => Effect_exports.gen(function* () {
72552
72783
  },
72553
72784
  MigrationError: (error2) => Effect_exports.fail(new BufferUnusable({ path, message: `migrations failed (${error2.kind}): ${error2.message}` }))
72554
72785
  }),
72786
+ withoutSpans,
72555
72787
  Effect_exports.onExit((exit3) => Exit_exports.isFailure(exit3) ? Scope_exports.close(scope3, exit3) : Effect_exports.void)
72556
72788
  );
72557
72789
  const sql = yield* opened;
72558
72790
  return {
72559
72791
  outbox: makeOutbox(sql),
72560
- backup: (destination) => Effect_exports.asVoid(sql.backup(destination)),
72792
+ backup: (destination) => Effect_exports.asVoid(sql.backup(destination)).pipe(withoutSpans),
72561
72793
  identity: yield* fileIdentity(path),
72562
72794
  close: Scope_exports.close(scope3, Exit_exports.void)
72563
72795
  };
@@ -74759,6 +74991,7 @@ import { fileURLToPath as fileURLToPath5 } from "node:url";
74759
74991
  var RECENT_COMMANDS = 50;
74760
74992
  var MAX_TOPICS = 2e3;
74761
74993
  var MAX_PAYLOAD2 = 2e3;
74994
+ var MAX_TOPIC_LENGTH = 512;
74762
74995
  var MAX_CONNECTIONS = 32;
74763
74996
  var ValueMessage = Schema_exports.fromJsonString(
74764
74997
  Schema_exports.Struct({ value: Schema_exports.Union([Schema_exports.Number, Schema_exports.Boolean]), ts: Schema_exports.Number })
@@ -74783,7 +75016,7 @@ var makeStatusState = (config, health, since, host) => {
74783
75016
  const attributes = { site: config.site, building: config.building };
74784
75017
  return {
74785
75018
  recordPublish: (topic, payload, message) => {
74786
- if (!topic.startsWith(prefix)) return;
75019
+ if (!topic.startsWith(prefix) || topic.length > MAX_TOPIC_LENGTH) return;
74787
75020
  if (message.retained && payload === "") {
74788
75021
  latest.delete(topic);
74789
75022
  return;
@@ -75078,6 +75311,7 @@ var rollup = (rows) => {
75078
75311
  }
75079
75312
  return [...minutes2.values()];
75080
75313
  };
75314
+ var withoutSpans2 = Effect_exports.withTracerEnabled(false);
75081
75315
  var makeStore2 = (sql) => {
75082
75316
  const bucketsOf = (table2, query3) => SqlSchema_exports.findAll({
75083
75317
  Request: Schema_exports.Void,
@@ -75093,7 +75327,7 @@ var makeStore2 = (sql) => {
75093
75327
  FROM minutes
75094
75328
  WHERE device = ${query3.device} AND point = ${query3.point} AND minute >= ${query3.from} AND minute < ${query3.to}
75095
75329
  GROUP BY b ORDER BY b`
75096
- })(void 0);
75330
+ })(void 0).pipe(withoutSpans2);
75097
75331
  return {
75098
75332
  /** Store a batch of reads and merge them into the minute rollups, in one transaction. */
75099
75333
  write: (rows) => sql.withTransaction(
@@ -75114,7 +75348,7 @@ var makeStore2 = (sql) => {
75114
75348
  count = minutes.count + excluded.count`;
75115
75349
  }
75116
75350
  })
75117
- ),
75351
+ ).pipe(withoutSpans2),
75118
75352
  /** One point's buckets from every read (`readings`) or from the rollups (`minutes`). */
75119
75353
  buckets: bucketsOf,
75120
75354
  /** Delete reads older than `rawBefore` and rollups older than `minutesBefore` (Unix ms). */
@@ -75122,7 +75356,7 @@ var makeStore2 = (sql) => {
75122
75356
  yield* sql`DELETE FROM readings WHERE ts < ${rawBefore}`;
75123
75357
  yield* sql`DELETE FROM minutes WHERE minute < ${minutesBefore}`;
75124
75358
  yield* sql`PRAGMA incremental_vacuum`;
75125
- })
75359
+ }).pipe(withoutSpans2)
75126
75360
  };
75127
75361
  };
75128
75362
 
@@ -75131,6 +75365,8 @@ var MAX_PENDING2 = 2e4;
75131
75365
  var DEFAULT_BUCKETS = 300;
75132
75366
  var MAX_BUCKETS = 2e3;
75133
75367
  var HOUR_MS = 36e5;
75368
+ var DEFAULT_FLUSH_EVERY_MS = 3e4;
75369
+ var TICK_MS = 5e3;
75134
75370
  var isCorrupt2 = (error2) => {
75135
75371
  const cause = error2.reason.cause;
75136
75372
  if (typeof cause !== "object" || cause === null || !("errcode" in cause) || typeof cause.errcode !== "number") {
@@ -75159,35 +75395,41 @@ var openStore = (path, scope3) => Effect_exports.gen(function* () {
75159
75395
  Effect_exports.catchTags({
75160
75396
  SqlError: (error2) => Effect_exports.fail({ corrupt: isCorrupt2(error2), message: error2.message }),
75161
75397
  MigrationError: (error2) => Effect_exports.fail({ corrupt: true, message: `migrations failed: ${error2.message}` })
75162
- })
75398
+ }),
75399
+ withoutSpans2
75163
75400
  );
75164
- 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) {
75165
75417
  const fs = yield* FileSystem_exports.FileSystem;
75166
75418
  const paths = yield* Path_exports.Path;
75167
- const scope3 = yield* Effect_exports.scope;
75168
75419
  const made = yield* fs.makeDirectory(paths.dirname(path), { recursive: true }).pipe(Effect_exports.result);
75169
75420
  if (Result_exports.isFailure(made)) return { reason: `cannot create the directory: ${made.failure.message}` };
75170
- const first = yield* openStore(path, yield* Scope_exports.fork(scope3)).pipe(Effect_exports.result);
75171
- 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 };
75172
75423
  if (!first.failure.corrupt) return { reason: first.failure.message };
75173
- const stamp = new Date(yield* Clock_exports.currentTimeMillis).toISOString().replace(/[:.]/g, "-");
75174
- const aside = `${path}.corrupt-${stamp}`;
75175
- for (const suffix of ["", "-wal", "-shm"]) {
75176
- const moved = yield* Effect_exports.result(
75177
- Effect_exports.flatMap(
75178
- fs.exists(path + suffix),
75179
- (exists2) => exists2 ? fs.rename(path + suffix, aside + suffix) : Effect_exports.void
75180
- )
75181
- );
75182
- if (Result_exports.isFailure(moved)) {
75183
- return { reason: `${first.failure.message}; moving it aside failed: ${moved.failure.message}` };
75184
- }
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}` };
75185
75427
  }
75186
75428
  yield* Effect_exports.logError("history file was unusable, moved it aside and started a new one").pipe(
75187
- Effect_exports.annotateLogs({ path, movedTo: aside, error: first.failure.message })
75429
+ Effect_exports.annotateLogs({ path, movedTo: moved.success, error: first.failure.message })
75188
75430
  );
75189
- const again = yield* openStore(path, yield* Scope_exports.fork(scope3)).pipe(Effect_exports.result);
75190
- 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 };
75191
75433
  });
75192
75434
  var unavailable = (message) => Effect_exports.fail(new HistoryUnavailable({ message }));
75193
75435
  var disabled = (reason) => ({
@@ -75196,8 +75438,9 @@ var disabled = (reason) => ({
75196
75438
  series: () => unavailable(`the gateway keeps no history: ${reason}`)
75197
75439
  });
75198
75440
  var openHistory = (settings, options3 = {}) => Effect_exports.gen(function* () {
75199
- const opened = yield* open5(settings.path);
75200
- 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)) {
75201
75444
  yield* Metric_exports.update(historyDisabled, 1);
75202
75445
  yield* Effect_exports.logError("history not kept: its file could not be opened").pipe(
75203
75446
  Effect_exports.annotateLogs({ path: settings.path, error: opened.reason })
@@ -75205,7 +75448,11 @@ var openHistory = (settings, options3 = {}) => Effect_exports.gen(function* () {
75205
75448
  return disabled(opened.reason);
75206
75449
  }
75207
75450
  yield* Metric_exports.update(historyDisabled, 0);
75208
- 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);
75209
75456
  let pending = [];
75210
75457
  let dropped = 0;
75211
75458
  let failing = false;
@@ -75214,15 +75461,47 @@ var openHistory = (settings, options3 = {}) => Effect_exports.gen(function* () {
75214
75461
  dropped += rows.length - MAX_PENDING2;
75215
75462
  return rows.slice(rows.length - MAX_PENDING2);
75216
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
+ });
75217
75495
  const flush2 = Effect_exports.gen(function* () {
75218
75496
  if (dropped > 0) {
75219
75497
  yield* Metric_exports.update(historyDropped, dropped);
75220
75498
  dropped = 0;
75221
75499
  }
75222
- if (pending.length === 0) return;
75500
+ const target = current;
75501
+ if (target === void 0 || pending.length === 0) return;
75223
75502
  const batch = pending;
75224
75503
  pending = [];
75225
- const written = yield* Effect_exports.result(store.write(batch));
75504
+ const written = yield* Effect_exports.result(target.store.write(batch));
75226
75505
  if (Result_exports.isSuccess(written)) {
75227
75506
  yield* Metric_exports.update(historyWritten, batch.length);
75228
75507
  if (failing) {
@@ -75233,25 +75512,37 @@ var openHistory = (settings, options3 = {}) => Effect_exports.gen(function* () {
75233
75512
  }
75234
75513
  yield* Metric_exports.update(Metric_exports.withAttributes(historyFailures, { operation: "write" }), 1);
75235
75514
  pending = keepAtMost([...batch, ...pending]);
75515
+ if (isCorrupt2(written.failure) && (yield* replaceCorrupt(target, written.failure))) return;
75236
75516
  if (!failing) {
75237
75517
  failing = true;
75238
75518
  yield* Effect_exports.logWarning("history cannot write; keeping the latest reads in memory until it can").pipe(
75239
75519
  Effect_exports.annotateLogs({ path: settings.path, error: written.failure.message })
75240
75520
  );
75241
75521
  }
75242
- });
75522
+ }).pipe(Semaphore_exports.withPermit(permit));
75243
75523
  const prune = Effect_exports.gen(function* () {
75524
+ const target = current;
75525
+ if (target === void 0) return;
75244
75526
  const now2 = yield* Clock_exports.currentTimeMillis;
75245
- 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));
75246
75528
  if (Result_exports.isFailure(pruned)) {
75247
75529
  yield* Metric_exports.update(Metric_exports.withAttributes(historyFailures, { operation: "prune" }), 1);
75530
+ if (isCorrupt2(pruned.failure) && (yield* replaceCorrupt(target, pruned.failure))) return;
75248
75531
  yield* Effect_exports.logWarning("history could not delete old reads").pipe(
75249
75532
  Effect_exports.annotateLogs({ path: settings.path, error: pruned.failure.message })
75250
75533
  );
75251
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;
75252
75544
  });
75253
- const flushEvery = Duration_exports.millis(options3.flushEveryMs ?? 5e3);
75254
- 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);
75255
75546
  yield* prune.pipe(
75256
75547
  Effect_exports.repeat(Schedule_exports.spaced(Duration_exports.millis(HOUR_MS))),
75257
75548
  Effect_exports.delay("1 minute"),
@@ -75261,21 +75552,32 @@ var openHistory = (settings, options3 = {}) => Effect_exports.gen(function* () {
75261
75552
  return {
75262
75553
  sink: {
75263
75554
  record: (device, point, value4, ts) => {
75555
+ if (off !== void 0) return;
75264
75556
  pending.push({ device, point, ts, value: typeof value4 === "boolean" ? value4 ? 1 : 0 : value4 });
75265
75557
  if (pending.length > MAX_PENDING2 + MAX_PENDING2 / 10) pending = keepAtMost(pending);
75266
75558
  }
75267
75559
  },
75268
75560
  series: (query3) => Effect_exports.gen(function* () {
75561
+ const buckets = query3.buckets ?? DEFAULT_BUCKETS;
75562
+ const fineMs = stepFor(query3.from, query3.to, buckets, 1e3);
75269
75563
  const now2 = yield* Clock_exports.currentTimeMillis;
75270
- const raw3 = query3.from >= now2 - RAW_MS;
75271
- 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);
75272
75566
  const from = raw3 ? query3.from : Math.floor(query3.from / MINUTE_MS) * MINUTE_MS;
75273
- const rows = yield* store.buckets(raw3 ? "readings" : "minutes", { ...query3, from, stepMs }).pipe(
75274
- Effect_exports.tapError(() => Metric_exports.update(Metric_exports.withAttributes(historyFailures, { operation: "read" }), 1)),
75275
- Effect_exports.catchTags({
75276
- SqlError: (error2) => unavailable(`history could not be read: ${error2.message}`),
75277
- SchemaError: (error2) => unavailable(`history holds rows it cannot read: ${error2.message}`)
75278
- })
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") })
75279
75581
  );
75280
75582
  return {
75281
75583
  device: query3.device,
@@ -76866,6 +77168,7 @@ var check2 = Command_exports.make(
76866
77168
  jsonFailure(json4, { path: config })
76867
77169
  )
76868
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;
76869
77172
  var discoverCommand = Command_exports.make(
76870
77173
  "discover",
76871
77174
  {
@@ -76882,10 +77185,10 @@ var discoverCommand = Command_exports.make(
76882
77185
  ),
76883
77186
  json: jsonFlag
76884
77187
  },
76885
- // 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.
76886
77189
  ({ config, pointsList, address, json: json4 }) => Effect_exports.flatMap(loadConfig(config), (decoded) => {
76887
77190
  const options3 = { address: Option_exports.getOrUndefined(address) };
76888
- 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);
76889
77192
  }).pipe(jsonFailure(json4, { path: config }))
76890
77193
  ).pipe(
76891
77194
  Command_exports.withDescription(
@@ -77159,13 +77462,17 @@ var watchCommand = Command_exports.make(
77159
77462
  { command: "ot-gateway watch --seconds 10 --json", description: "The same as JSON lines, for scripts and agents" }
77160
77463
  ])
77161
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
+ });
77162
77469
  var brokerCommand = Command_exports.make(
77163
77470
  "broker",
77164
77471
  { config: configPath, json: jsonFlag },
77165
77472
  ({ config, json: json4 }) => loadConfig(config).pipe(
77166
77473
  Effect_exports.flatMap(checkBroker),
77167
- Effect_exports.flatMap((report) => json4 ? printJson(report) : Console_exports.log(formatBrokerReport(report))),
77168
- jsonFailure(json4, { path: config })
77474
+ jsonFailure(json4, { path: config }),
77475
+ Effect_exports.flatMap(brokerOutcome(json4))
77169
77476
  )
77170
77477
  ).pipe(
77171
77478
  Command_exports.withDescription(