ot-gateway 0.8.1 → 0.9.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.
@@ -51787,7 +51787,12 @@ var MqttSettings = Schema_exports.Struct({
51787
51787
  clientId: Schema_exports.optionalKey(ConnectString),
51788
51788
  username: Schema_exports.optionalKey(ConnectString),
51789
51789
  /** Name of the environment variable holding the password. Never inline secrets. */
51790
- passwordEnv: Schema_exports.optionalKey(Schema_exports.String)
51790
+ passwordEnv: Schema_exports.optionalKey(Schema_exports.String),
51791
+ /**
51792
+ * The MQTT spoken: `auto` dials with MQTT 5 and falls back to 3.1.1 for a
51793
+ * broker that refuses it; `5` or `3.1.1` speak only that.
51794
+ */
51795
+ version: Schema_exports.Literals(["auto", "5", "3.1.1"]).pipe(Schema_exports.withDecodingDefaultKey(Effect_exports.succeed("auto")))
51791
51796
  });
51792
51797
  var loopbackIpv4 = new RegExp(`^127(\\.${octet}){3}$`);
51793
51798
  var isLoopbackHost = (hostname3) => {
@@ -58109,14 +58114,20 @@ var makeFrameReader = (maximumPacketSize = Number.POSITIVE_INFINITY) => {
58109
58114
  };
58110
58115
  var encodeConnect = (connect2) => {
58111
58116
  const flags = (connect2.username === void 0 ? 0 : 128) | (connect2.password === void 0 ? 0 : 64) | (connect2.will?.retain === true ? 32 : 0) | (connect2.will?.qos ?? 0) << 3 | (connect2.will === void 0 ? 0 : 4) | (connect2.cleanStart ? 2 : 0);
58112
- const body = new Writer2().string("MQTT").byte(5).byte(flags).u16(connect2.keepAliveSeconds).bytes(
58113
- encodeProperties((w) => {
58114
- w.byte(Property.SessionExpiryInterval).u32(connect2.sessionExpirySeconds);
58115
- if (connect2.maximumPacketSize !== void 0) w.byte(Property.MaximumPacketSize).u32(connect2.maximumPacketSize);
58116
- })
58117
- ).string(connect2.clientId);
58117
+ const v5 = (connect2.protocolVersion ?? 5) === 5;
58118
+ const body = new Writer2().string("MQTT").byte(v5 ? 5 : 4).byte(flags).u16(connect2.keepAliveSeconds);
58119
+ if (v5) {
58120
+ body.bytes(
58121
+ encodeProperties((w) => {
58122
+ w.byte(Property.SessionExpiryInterval).u32(connect2.sessionExpirySeconds);
58123
+ if (connect2.maximumPacketSize !== void 0) w.byte(Property.MaximumPacketSize).u32(connect2.maximumPacketSize);
58124
+ })
58125
+ );
58126
+ }
58127
+ body.string(connect2.clientId);
58118
58128
  if (connect2.will !== void 0) {
58119
- body.bytes(encodeProperties((w) => w.byte(Property.PayloadFormatIndicator).byte(1))).string(connect2.will.topic).binary(encoder9.encode(connect2.will.payload));
58129
+ if (v5) body.bytes(encodeProperties((w) => w.byte(Property.PayloadFormatIndicator).byte(1)));
58130
+ body.string(connect2.will.topic).binary(encoder9.encode(connect2.will.payload));
58120
58131
  }
58121
58132
  if (connect2.username !== void 0) body.string(connect2.username);
58122
58133
  if (connect2.password !== void 0) body.binary(encoder9.encode(connect2.password));
@@ -58125,16 +58136,17 @@ var encodeConnect = (connect2) => {
58125
58136
  var decodeConnect = (body) => decodeWith2(body, (r) => {
58126
58137
  const protocol = r.string();
58127
58138
  const level = r.byte();
58128
- if (protocol !== "MQTT" || level !== 5) {
58139
+ if (protocol !== "MQTT" || level !== 5 && level !== 4) {
58129
58140
  throw new MqttCodecError({ message: `unsupported protocol ${protocol} level ${level}` });
58130
58141
  }
58142
+ const v5 = level === 5;
58131
58143
  const flags = r.byte();
58132
58144
  const keepAliveSeconds = r.u16();
58133
- const properties = r.properties();
58145
+ const properties = v5 ? r.properties() : /* @__PURE__ */ new Map();
58134
58146
  const clientId = r.string();
58135
58147
  let will;
58136
58148
  if ((flags & 4) !== 0) {
58137
- r.properties();
58149
+ if (v5) r.properties();
58138
58150
  const topic = r.string();
58139
58151
  const payload = decoder4.decode(r.binary());
58140
58152
  will = { topic, payload, qos: flags >> 3 & 1 ? 1 : 0, retain: (flags & 32) !== 0 };
@@ -58144,6 +58156,7 @@ var decodeConnect = (body) => decodeWith2(body, (r) => {
58144
58156
  const expiry = properties.get(Property.SessionExpiryInterval);
58145
58157
  const maximumPacketSize = properties.get(Property.MaximumPacketSize);
58146
58158
  return {
58159
+ protocolVersion: v5 ? 5 : 4,
58147
58160
  clientId,
58148
58161
  keepAliveSeconds,
58149
58162
  cleanStart: (flags & 2) !== 0,
@@ -58154,26 +58167,39 @@ var decodeConnect = (body) => decodeWith2(body, (r) => {
58154
58167
  ...will === void 0 ? {} : { will }
58155
58168
  };
58156
58169
  });
58157
- var decodeConnack = (body) => decodeWith2(body, (r) => ({
58158
- sessionPresent: (r.byte() & 1) !== 0,
58159
- reasonCode: r.byte(),
58160
- properties: r.remaining > 0 ? r.properties() : /* @__PURE__ */ new Map()
58161
- }));
58162
- var encodeConnack = (reasonCode, properties = /* @__PURE__ */ new Map()) => packet(
58163
- PacketType.CONNACK,
58164
- 0,
58165
- new Writer2().byte(0).byte(reasonCode).bytes(
58166
- encodeProperties((w) => {
58167
- for (const [id2, value4] of properties) {
58168
- w.byte(id2);
58169
- const kind = propertyKinds[id2];
58170
- if (kind === "u16") w.u16(value4);
58171
- else if (kind === "u32") w.u32(value4);
58172
- else w.byte(value4);
58173
- }
58174
- })
58175
- ).toBytes()
58176
- );
58170
+ var returnCodeReasons = { 1: 132, 2: 133, 3: 136, 4: 134, 5: 135 };
58171
+ var reasonReturnCodes = { 132: 1, 133: 2, 136: 3, 134: 4, 135: 5 };
58172
+ var decodeConnack = (body, version2 = 5) => decodeWith2(body, (r) => {
58173
+ const sessionPresent = (r.byte() & 1) !== 0;
58174
+ const code = r.byte();
58175
+ if (version2 === 4) {
58176
+ return { sessionPresent, reasonCode: code === 0 ? 0 : returnCodeReasons[code] ?? 128, properties: /* @__PURE__ */ new Map() };
58177
+ }
58178
+ return { sessionPresent, reasonCode: code, properties: r.remaining > 0 ? r.properties() : /* @__PURE__ */ new Map() };
58179
+ });
58180
+ var refusesProtocolLevel = (connack) => connack.reasonCode === 132 || connack.reasonCode === 1;
58181
+ var encodeConnack = (reasonCode, properties = /* @__PURE__ */ new Map(), version2 = 5) => {
58182
+ if (version2 === 4) {
58183
+ const returnCode = reasonCode === 0 ? 0 : reasonReturnCodes[reasonCode] ?? 3;
58184
+ return packet(PacketType.CONNACK, 0, Uint8Array.of(0, returnCode));
58185
+ }
58186
+ return packet(
58187
+ PacketType.CONNACK,
58188
+ 0,
58189
+ new Writer2().byte(0).byte(reasonCode).bytes(
58190
+ encodeProperties((w) => {
58191
+ for (const [id2, value4] of properties) {
58192
+ w.byte(id2);
58193
+ const kind = propertyKinds[id2];
58194
+ if (kind === "u16") w.u16(value4);
58195
+ else if (kind === "u32") w.u32(value4);
58196
+ else w.byte(value4);
58197
+ }
58198
+ })
58199
+ ).toBytes()
58200
+ );
58201
+ };
58202
+ var encodeUnsupportedLevelConnack = () => packet(PacketType.CONNACK, 0, Uint8Array.of(0, 1));
58177
58203
  var connackReasonName = (code) => ({
58178
58204
  128: "unspecified error",
58179
58205
  129: "malformed packet",
@@ -58190,9 +58216,13 @@ var connackReasonName = (code) => ({
58190
58216
  151: "quota exceeded",
58191
58217
  159: "connection rate exceeded"
58192
58218
  })[code] ?? `reason code 0x${code.toString(16)}`;
58193
- var encodePublish = (publish2) => {
58219
+ var encodePublish = (publish2, version2 = 5) => {
58194
58220
  const body = new Writer2().string(publish2.topic);
58195
58221
  if (publish2.qos > 0) body.u16(publish2.packetId ?? 0);
58222
+ if (version2 === 4) {
58223
+ body.bytes(publish2.payload);
58224
+ return packet(PacketType.PUBLISH, publish2.qos << 1 | (publish2.retain ? 1 : 0), body.toBytes());
58225
+ }
58196
58226
  body.bytes(
58197
58227
  encodeProperties((w) => {
58198
58228
  w.byte(Property.PayloadFormatIndicator).byte(1);
@@ -58205,12 +58235,12 @@ var encodePublish = (publish2) => {
58205
58235
  ).bytes(publish2.payload);
58206
58236
  return packet(PacketType.PUBLISH, publish2.qos << 1 | (publish2.retain ? 1 : 0), body.toBytes());
58207
58237
  };
58208
- var decodePublish = (flags, body) => decodeWith2(body, (r) => {
58238
+ var decodePublish = (flags, body, version2 = 5) => decodeWith2(body, (r) => {
58209
58239
  const qos = flags >> 1 & 3;
58210
58240
  if (qos > 1) throw new MqttCodecError({ message: `QoS ${qos} is not supported` });
58211
58241
  const topic = r.string();
58212
58242
  const packetId = qos > 0 ? r.u16() : void 0;
58213
- const properties = r.properties();
58243
+ const properties = version2 === 5 ? r.properties() : /* @__PURE__ */ new Map();
58214
58244
  const expiry = properties.get(Property.MessageExpiryInterval);
58215
58245
  const responseTopic = properties.get(Property.ResponseTopic);
58216
58246
  const correlationData = properties.get(Property.CorrelationData);
@@ -58227,29 +58257,34 @@ var decodePublish = (flags, body) => decodeWith2(body, (r) => {
58227
58257
  });
58228
58258
  var pubackRefusesMessage = (reasonCode) => reasonCode === 135 || reasonCode === 144 || reasonCode === 149 || reasonCode === 153;
58229
58259
  var decodePuback = (body) => decodeWith2(body, (r) => ({ packetId: r.u16(), reasonCode: r.remaining > 0 ? r.byte() : 0 }));
58230
- var encodePuback = (packetId, reasonCode = 0) => packet(
58260
+ var encodePuback = (packetId, reasonCode = 0, version2 = 5) => version2 === 4 ? packet(PacketType.PUBACK, 0, new Writer2().u16(packetId).toBytes()) : packet(
58231
58261
  PacketType.PUBACK,
58232
58262
  0,
58233
58263
  new Writer2().u16(packetId).byte(reasonCode).bytes(encodeProperties(() => {
58234
58264
  })).toBytes()
58235
58265
  );
58236
- var encodeSubscribe = (subscribe2) => {
58237
- const body = new Writer2().u16(subscribe2.packetId).bytes(encodeProperties(() => {
58266
+ var encodeSubscribe = (subscribe2, version2 = 5) => {
58267
+ const body = new Writer2().u16(subscribe2.packetId);
58268
+ if (version2 === 5) body.bytes(encodeProperties(() => {
58238
58269
  }));
58239
58270
  for (const { filter: filter14, qos, retainAsPublished, noLocal } of subscribe2.subscriptions) {
58240
- body.string(filter14).byte(qos | (noLocal === true ? 4 : 0) | (retainAsPublished === true ? 8 : 0));
58271
+ const options3 = version2 === 5 ? qos | (noLocal === true ? 4 : 0) | (retainAsPublished === true ? 8 : 0) : qos;
58272
+ body.string(filter14).byte(options3);
58241
58273
  }
58242
58274
  return packet(PacketType.SUBSCRIBE, 2, body.toBytes());
58243
58275
  };
58244
- var decodeSubscribe = (body) => decodeWith2(body, (r) => {
58276
+ var decodeSubscribe = (body, version2 = 5) => decodeWith2(body, (r) => {
58245
58277
  const packetId = r.u16();
58246
- r.properties();
58278
+ if (version2 === 5) r.properties();
58247
58279
  const subscriptions = [];
58248
58280
  while (r.remaining > 0) {
58249
58281
  const filter14 = r.string();
58250
58282
  const options3 = r.byte();
58251
58283
  const qos = options3 & 3;
58252
58284
  if (qos > 1) throw new MqttCodecError({ message: `QoS ${qos} is not supported` });
58285
+ if (version2 === 4 && (options3 & 252) !== 0) {
58286
+ throw new MqttCodecError({ message: "reserved bits set in a subscription's options" });
58287
+ }
58253
58288
  subscriptions.push({
58254
58289
  filter: filter14,
58255
58290
  qos: qos === 1 ? 1 : 0,
@@ -58260,15 +58295,16 @@ var decodeSubscribe = (body) => decodeWith2(body, (r) => {
58260
58295
  if (subscriptions.length === 0) throw new MqttCodecError({ message: "SUBSCRIBE without a topic filter" });
58261
58296
  return { packetId, subscriptions };
58262
58297
  });
58263
- var encodeSuback = (suback) => packet(
58264
- PacketType.SUBACK,
58265
- 0,
58266
- new Writer2().u16(suback.packetId).bytes(encodeProperties(() => {
58267
- })).bytes(Uint8Array.from(suback.reasonCodes)).toBytes()
58268
- );
58269
- var decodeSuback = (body) => decodeWith2(body, (r) => {
58298
+ var encodeSuback = (suback, version2 = 5) => {
58299
+ const body = new Writer2().u16(suback.packetId);
58300
+ if (version2 === 5) body.bytes(encodeProperties(() => {
58301
+ }));
58302
+ const codes3 = version2 === 5 ? suback.reasonCodes : suback.reasonCodes.map((code) => code >= 128 ? 128 : code);
58303
+ return packet(PacketType.SUBACK, 0, body.bytes(Uint8Array.from(codes3)).toBytes());
58304
+ };
58305
+ var decodeSuback = (body, version2 = 5) => decodeWith2(body, (r) => {
58270
58306
  const packetId = r.u16();
58271
- r.properties();
58307
+ if (version2 === 5) r.properties();
58272
58308
  return { packetId, reasonCodes: [...r.rest()] };
58273
58309
  });
58274
58310
  var topicMatches = (filter14, topic) => {
@@ -58285,7 +58321,7 @@ var topicMatches = (filter14, topic) => {
58285
58321
  };
58286
58322
  var encodePingreq = () => Uint8Array.of(PacketType.PINGREQ << 4, 0);
58287
58323
  var encodePingresp = () => Uint8Array.of(PacketType.PINGRESP << 4, 0);
58288
- var encodeDisconnect = (reasonCode = 0) => reasonCode === 0 ? Uint8Array.of(PacketType.DISCONNECT << 4, 0) : packet(PacketType.DISCONNECT, 0, Uint8Array.of(reasonCode, 0));
58324
+ var encodeDisconnect = (reasonCode = 0, version2 = 5) => reasonCode === 0 || version2 === 4 ? Uint8Array.of(PacketType.DISCONNECT << 4, 0) : packet(PacketType.DISCONNECT, 0, Uint8Array.of(reasonCode, 0));
58289
58325
  var decodeDisconnect = (body) => decodeWith2(body, (r) => {
58290
58326
  const reasonCode = r.remaining > 0 ? r.byte() : 0;
58291
58327
  const reason = r.remaining > 0 ? r.properties().get(Property.ReasonString) : void 0;
@@ -58302,6 +58338,8 @@ var MqttRejected = class extends Schema_exports.TaggedError()("MqttRejected", {
58302
58338
  message: Schema_exports.String
58303
58339
  }) {
58304
58340
  };
58341
+ var MqttDowngrade = class extends Schema_exports.TaggedError()("MqttDowngrade", {}) {
58342
+ };
58305
58343
  var MqttPublishError = class extends Schema_exports.TaggedError()("MqttPublishError", {
58306
58344
  topic: Schema_exports.String,
58307
58345
  reason: Schema_exports.Literals(["unavailable", "rejected"]),
@@ -58334,7 +58372,11 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58334
58372
  const maxDelay = Duration_exports.toMillis(Duration_exports.fromInputUnsafe(options3.reconnectDelay?.max ?? "15 seconds"));
58335
58373
  const connected = yield* Latch_exports.make(false);
58336
58374
  const firstDialDone = yield* Latch_exports.make(false);
58375
+ const firstDial = Deferred_exports.makeUnsafe();
58337
58376
  let session;
58377
+ let version2 = options3.protocolVersion === "3.1.1" ? 4 : 5;
58378
+ let lastTurn = Deferred_exports.makeUnsafe();
58379
+ Deferred_exports.doneUnsafe(lastTurn, Effect_exports.void);
58338
58380
  const runSession = (onConnected) => Effect_exports.scoped(
58339
58381
  Effect_exports.gen(function* () {
58340
58382
  const { pull } = yield* socket.reader;
@@ -58352,10 +58394,13 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58352
58394
  ),
58353
58395
  Deferred_exports.await(closed)
58354
58396
  );
58355
- const protocolError = (reasonCode, message) => write2(encodeDisconnect(reasonCode)).pipe(
58356
- Effect_exports.timeoutOrElse({ duration: "1 second", orElse: () => Effect_exports.void }),
58357
- Effect_exports.catchTag("MqttConnectionError", () => Effect_exports.void),
58358
- Effect_exports.andThen(Effect_exports.fail(new MqttConnectionError({ message })))
58397
+ const protocolError = (reasonCode, message) => (
58398
+ // 3.1.1 has no reason to send, and its DISCONNECT discards the will: there, only close (3.1.1 §4.8).
58399
+ (version2 === 4 ? Effect_exports.void : write2(encodeDisconnect(reasonCode))).pipe(
58400
+ Effect_exports.timeoutOrElse({ duration: "1 second", orElse: () => Effect_exports.void }),
58401
+ Effect_exports.catchTag("MqttConnectionError", () => Effect_exports.void),
58402
+ Effect_exports.andThen(Effect_exports.fail(new MqttConnectionError({ message })))
58403
+ )
58359
58404
  );
58360
58405
  const frames = makeFrameReader(maximumPacketSize);
58361
58406
  const nextPacket = Effect_exports.gen(function* () {
@@ -58381,8 +58426,10 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58381
58426
  (error2) => Effect_exports.fail(new MqttConnectionError({ message: describeSocketError(error2) }))
58382
58427
  )
58383
58428
  );
58429
+ const dialedWith = version2;
58384
58430
  yield* write2(
58385
58431
  encodeConnect({
58432
+ protocolVersion: dialedWith,
58386
58433
  clientId: options3.clientId,
58387
58434
  keepAliveSeconds,
58388
58435
  cleanStart: true,
@@ -58398,7 +58445,7 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58398
58445
  if (packet2.type !== PacketType.CONNACK) {
58399
58446
  return yield* new MqttConnectionError({ message: `expected CONNACK, got packet type ${packet2.type}` });
58400
58447
  }
58401
- const decoded = decodeConnack(packet2.body);
58448
+ const decoded = decodeConnack(packet2.body, dialedWith);
58402
58449
  if (Result_exports.isFailure(decoded)) {
58403
58450
  return yield* new MqttConnectionError({ message: `unreadable CONNACK: ${decoded.failure.message}` });
58404
58451
  }
@@ -58409,6 +58456,16 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58409
58456
  orElse: () => Effect_exports.fail(new MqttConnectionError({ message: "no CONNACK in time" }))
58410
58457
  })
58411
58458
  );
58459
+ if (dialedWith === 5 && refusesProtocolLevel(connack)) {
58460
+ if (options3.protocolVersion === "5") {
58461
+ return yield* new MqttRejected({
58462
+ reasonCode: 132,
58463
+ message: "broker refused the connection: it does not speak MQTT 5 (set mqtt.version to 3.1.1 or auto)"
58464
+ });
58465
+ }
58466
+ version2 = 4;
58467
+ return yield* new MqttDowngrade();
58468
+ }
58412
58469
  if (connack.reasonCode >= 128) {
58413
58470
  return yield* new MqttRejected({
58414
58471
  reasonCode: connack.reasonCode,
@@ -58422,11 +58479,23 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58422
58479
  if (props.get(Property.MaximumPacketSize) === 0) {
58423
58480
  return yield* protocolError(130, "broker sent Maximum Packet Size 0 in CONNACK, a protocol error");
58424
58481
  }
58482
+ const receiveMaximum = Math.min(numberProperty(props, Property.ReceiveMaximum, 65535), 1e3);
58483
+ const announcedPacketSize = props.get(Property.MaximumPacketSize);
58484
+ const effectiveKeepAlive = numberProperty(props, Property.ServerKeepAlive, keepAliveSeconds);
58425
58485
  const current = {
58486
+ version: dialedWith,
58487
+ info: {
58488
+ protocolVersion: dialedWith === 5 ? "5" : "3.1.1",
58489
+ receiveMaximum,
58490
+ maximumQoS: numberProperty(props, Property.MaximumQoS, 2) === 0 ? 0 : 1,
58491
+ retainAvailable: numberProperty(props, Property.RetainAvailable, 1) === 1,
58492
+ ...typeof announcedPacketSize === "number" ? { maximumPacketSize: announcedPacketSize } : {},
58493
+ keepAliveSeconds: effectiveKeepAlive
58494
+ },
58426
58495
  write: write2,
58427
58496
  inflight: /* @__PURE__ */ new Map(),
58428
58497
  // Receive Maximum bounds unacknowledged QoS 1 publishes (§3.2.2.3.3).
58429
- inflightLimit: yield* Semaphore_exports.make(Math.min(numberProperty(props, Property.ReceiveMaximum, 65535), 1e3)),
58498
+ inflightLimit: yield* Semaphore_exports.make(receiveMaximum),
58430
58499
  maximumQoS: numberProperty(props, Property.MaximumQoS, 2) === 0 ? 0 : 1,
58431
58500
  retainAvailable: numberProperty(props, Property.RetainAvailable, 1) === 1,
58432
58501
  maximumPacketSize: numberProperty(props, Property.MaximumPacketSize, Number.POSITIVE_INFINITY),
@@ -58435,7 +58504,6 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58435
58504
  pubackTimeouts: 0,
58436
58505
  droppedForSilence: false
58437
58506
  };
58438
- const effectiveKeepAlive = numberProperty(props, Property.ServerKeepAlive, keepAliveSeconds);
58439
58507
  const pingSeconds = effectiveKeepAlive > 0 ? effectiveKeepAlive : keepAliveSeconds;
58440
58508
  yield* Effect_exports.addFinalizer(
58441
58509
  (exit3) => Effect_exports.gen(function* () {
@@ -58468,6 +58536,7 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58468
58536
  yield* Effect_exports.logInfo("connected to MQTT broker").pipe(
58469
58537
  Effect_exports.annotateLogs({
58470
58538
  keepAlive: effectiveKeepAlive,
58539
+ ...dialedWith === 4 ? { mqtt: "3.1.1" } : {},
58471
58540
  ...failedBefore > 0 ? { failedDials: failedBefore } : {}
58472
58541
  })
58473
58542
  );
@@ -58476,7 +58545,7 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58476
58545
  if (subscriptions.length > 0) {
58477
58546
  const packetId = current.nextPacketId;
58478
58547
  current.nextPacketId = packetId % 65535 + 1;
58479
- yield* write2(encodeSubscribe({ packetId, subscriptions }));
58548
+ yield* write2(encodeSubscribe({ packetId, subscriptions }, dialedWith));
58480
58549
  }
58481
58550
  let lastReceived = yield* monotonicMillis;
58482
58551
  const readLoop2 = Effect_exports.gen(function* () {
@@ -58499,12 +58568,12 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58499
58568
  return yield* new MqttConnectionError({ message: `broker disconnected: ${reason}` });
58500
58569
  }
58501
58570
  case PacketType.PUBLISH: {
58502
- const publish3 = decodePublish(packet2.flags, packet2.body);
58571
+ const publish3 = decodePublish(packet2.flags, packet2.body, dialedWith);
58503
58572
  if (Result_exports.isFailure(publish3)) {
58504
58573
  return yield* protocolError(129, `unreadable PUBLISH: ${publish3.failure.message}`);
58505
58574
  }
58506
58575
  const { topic, payload, retain, packetId, messageExpirySeconds, responseTopic, correlationData } = publish3.success;
58507
- if (packetId !== void 0) yield* write2(encodePuback(packetId));
58576
+ if (packetId !== void 0) yield* write2(encodePuback(packetId, 0, dialedWith));
58508
58577
  if (options3.onMessage !== void 0) {
58509
58578
  yield* options3.onMessage({
58510
58579
  topic,
@@ -58518,7 +58587,7 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58518
58587
  break;
58519
58588
  }
58520
58589
  case PacketType.SUBACK: {
58521
- const suback = decodeSuback(packet2.body);
58590
+ const suback = decodeSuback(packet2.body, dialedWith);
58522
58591
  const refused = Result_exports.isSuccess(suback) ? subscriptions.filter((_, index2) => (suback.success.reasonCodes[index2] ?? 128) >= 128) : subscriptions;
58523
58592
  if (refused.length > 0) {
58524
58593
  yield* Effect_exports.logError(
@@ -58570,15 +58639,21 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58570
58639
  });
58571
58640
  while (true) {
58572
58641
  let connectedAt;
58573
- yield* runSession((at) => {
58642
+ const outcome = yield* runSession((at) => {
58574
58643
  connectedAt = at;
58644
+ Deferred_exports.doneUnsafe(firstDial, Effect_exports.void);
58575
58645
  unreachable = void 0;
58576
58646
  const dials = failedDials;
58577
58647
  failedDials = 0;
58578
58648
  return dials;
58579
58649
  }).pipe(
58580
58650
  Effect_exports.catchTags({
58581
- MqttRejected: (error2) => countConnect3("rejected").pipe(
58651
+ MqttDowngrade: () => Effect_exports.as(
58652
+ Effect_exports.logInfo("MQTT broker does not speak MQTT 5, connecting with MQTT 3.1.1"),
58653
+ "redial"
58654
+ ),
58655
+ MqttRejected: (error2) => Effect_exports.sync(() => Deferred_exports.doneUnsafe(firstDial, Effect_exports.fail(error2))).pipe(
58656
+ Effect_exports.andThen(countConnect3("rejected")),
58582
58657
  Effect_exports.andThen(
58583
58658
  dialFailed(
58584
58659
  `rejected ${error2.reasonCode}`,
@@ -58588,7 +58663,8 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58588
58663
  )
58589
58664
  )
58590
58665
  ),
58591
- MqttConnectionError: (error2) => connectedAt !== void 0 ? Effect_exports.logWarning("MQTT connection lost").pipe(Effect_exports.annotateLogs({ error: error2.message })) : countConnect3("failed").pipe(
58666
+ MqttConnectionError: (error2) => connectedAt !== void 0 ? Effect_exports.logWarning("MQTT connection lost").pipe(Effect_exports.annotateLogs({ error: error2.message })) : Effect_exports.sync(() => Deferred_exports.doneUnsafe(firstDial, Effect_exports.fail(error2))).pipe(
58667
+ Effect_exports.andThen(countConnect3("failed")),
58592
58668
  Effect_exports.andThen(
58593
58669
  dialFailed(
58594
58670
  "unreachable",
@@ -58600,6 +58676,7 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58600
58676
  )
58601
58677
  })
58602
58678
  );
58679
+ if (outcome === "redial") continue;
58603
58680
  yield* Latch_exports.open(firstDialDone);
58604
58681
  const heldFor = connectedAt === void 0 ? 0 : (yield* monotonicMillis) - connectedAt;
58605
58682
  failures = heldFor >= stableConnectionMs ? 0 : failures + 1;
@@ -58611,16 +58688,26 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58611
58688
  let sent = false;
58612
58689
  let blameless = false;
58613
58690
  let used;
58691
+ const previousTurn = lastTurn;
58692
+ const turn = Deferred_exports.makeUnsafe();
58693
+ lastTurn = turn;
58694
+ const passTurn = Effect_exports.sync(() => Deferred_exports.doneUnsafe(turn, Effect_exports.void));
58614
58695
  return Effect_exports.gen(function* () {
58615
58696
  const rejected3 = (message) => new MqttPublishError({ topic, reason: "rejected", message });
58616
58697
  const problem = topicProblem(topic);
58617
58698
  if (problem !== void 0) return yield* rejected3(problem);
58618
- yield* (options3.waitForConnection === false ? firstDialDone : connected).await.pipe(
58619
- Effect_exports.timeoutOrElse({
58620
- duration: publishTimeout,
58621
- orElse: () => Effect_exports.fail(new MqttConnectionError({ message: "not connected to the broker" }))
58622
- })
58623
- );
58699
+ const notConnected = () => new MqttConnectionError({ message: "not connected to the broker" });
58700
+ const withinPublishTimeout = Effect_exports.timeoutOrElse({
58701
+ duration: publishTimeout,
58702
+ orElse: () => Effect_exports.fail(notConnected())
58703
+ });
58704
+ if (options3.waitForConnection === false) {
58705
+ yield* firstDialDone.await.pipe(withinPublishTimeout);
58706
+ if (session === void 0) return yield* notConnected();
58707
+ yield* Deferred_exports.await(previousTurn).pipe(withinPublishTimeout);
58708
+ } else {
58709
+ yield* Deferred_exports.await(previousTurn).pipe(Effect_exports.andThen(connected.await), withinPublishTimeout);
58710
+ }
58624
58711
  const current = session;
58625
58712
  if (current === void 0) return yield* new MqttConnectionError({ message: "not connected to the broker" });
58626
58713
  used = current;
@@ -58632,11 +58719,11 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58632
58719
  const bytes3 = encoder10.encode(payload);
58633
58720
  const correlation = publishOptions.correlationData === void 0 ? {} : { correlationData: publishOptions.correlationData };
58634
58721
  if (qos === 0) {
58635
- const packet2 = encodePublish({ topic, payload: bytes3, qos: 0, retain, ...correlation });
58722
+ const packet2 = encodePublish({ topic, payload: bytes3, qos: 0, retain, ...correlation }, current.version);
58636
58723
  if (packet2.length > current.maximumPacketSize) {
58637
58724
  return yield* rejected3(`message exceeds the broker's ${current.maximumPacketSize} byte limit`);
58638
58725
  }
58639
- return yield* current.write(packet2);
58726
+ return yield* current.write(packet2).pipe(Effect_exports.ensuring(passTurn));
58640
58727
  }
58641
58728
  const reasonCode = yield* Semaphore_exports.withPermit(
58642
58729
  current.inflightLimit,
@@ -58644,14 +58731,17 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58644
58731
  let packetId = current.nextPacketId;
58645
58732
  while (current.inflight.has(packetId)) packetId = packetId % 65535 + 1;
58646
58733
  current.nextPacketId = packetId % 65535 + 1;
58647
- const packet2 = encodePublish({ topic, payload: bytes3, qos: 1, retain, packetId, ...correlation });
58734
+ const packet2 = encodePublish(
58735
+ { topic, payload: bytes3, qos: 1, retain, packetId, ...correlation },
58736
+ current.version
58737
+ );
58648
58738
  if (packet2.length > current.maximumPacketSize) {
58649
58739
  return yield* rejected3(`message exceeds the broker's ${current.maximumPacketSize} byte limit`);
58650
58740
  }
58651
58741
  const acked = yield* Deferred_exports.make();
58652
58742
  current.inflight.set(packetId, acked);
58653
58743
  return yield* Effect_exports.gen(function* () {
58654
- yield* current.write(packet2);
58744
+ yield* current.write(packet2).pipe(Effect_exports.ensuring(passTurn));
58655
58745
  sent = true;
58656
58746
  return yield* Deferred_exports.await(acked);
58657
58747
  }).pipe(Effect_exports.ensuring(Effect_exports.sync(() => current.inflight.delete(packetId))));
@@ -58680,6 +58770,7 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58680
58770
  return yield* new MqttPublishError({ topic, reason: "unavailable", message });
58681
58771
  }
58682
58772
  }).pipe(
58773
+ Effect_exports.ensuring(passTurn),
58683
58774
  Effect_exports.catchTag(
58684
58775
  "MqttConnectionError",
58685
58776
  (error2) => Effect_exports.fail(
@@ -58693,7 +58784,12 @@ var makeMqttClient = Effect_exports.fn("makeMqttClient")(function* (socket, opti
58693
58784
  )
58694
58785
  );
58695
58786
  });
58696
- const client = { publish: publish2, isConnected: Effect_exports.sync(() => session !== void 0) };
58787
+ const client = {
58788
+ publish: publish2,
58789
+ isConnected: Effect_exports.sync(() => session !== void 0),
58790
+ connection: Effect_exports.sync(() => session?.info),
58791
+ firstDial: Deferred_exports.await(firstDial)
58792
+ };
58697
58793
  yield* Effect_exports.forkScoped(connectionLoop);
58698
58794
  return client;
58699
58795
  });
@@ -58791,6 +58887,7 @@ var MqttPublisher = (settings, options3 = {}) => Layer_exports.effect(
58791
58887
  const client = yield* makeMqttClient(socket, {
58792
58888
  ...clientOptions,
58793
58889
  clientId: settings.clientId ?? `ot-gateway-${hostname()}`,
58890
+ protocolVersion: settings.version,
58794
58891
  ...settings.username === void 0 ? {} : { username: settings.username },
58795
58892
  ...password === void 0 ? {} : { password },
58796
58893
  ...health === void 0 ? {} : { will: { topic: health.topic, payload: offlinePayload("connection-lost"), qos: 1, retain: true } },
@@ -58835,6 +58932,7 @@ var MqttPublisher = (settings, options3 = {}) => Layer_exports.effect(
58835
58932
 
58836
58933
  // ../../packages/mqtt/src/TestBroker.ts
58837
58934
  var makeBrokerControl = () => ({
58935
+ speaksMqtt5: true,
58838
58936
  connackReason: 0,
58839
58937
  connackProperties: /* @__PURE__ */ new Map(),
58840
58938
  ackPublishes: true,
@@ -58862,15 +58960,18 @@ var deliver = (subscriber, message, onSubscribe) => {
58862
58960
  if (packetId !== void 0) subscriber.nextPacketId = packetId % 65535 + 1;
58863
58961
  Queue_exports.offerUnsafe(
58864
58962
  subscriber.outgoing,
58865
- encodePublish({
58866
- topic: message.topic,
58867
- payload: encoder11.encode(message.payload),
58868
- qos,
58869
- retain,
58870
- ...packetId === void 0 ? {} : { packetId },
58871
- ...message.responseTopic === void 0 ? {} : { responseTopic: message.responseTopic },
58872
- ...message.correlationData === void 0 ? {} : { correlationData: message.correlationData }
58873
- })
58963
+ encodePublish(
58964
+ {
58965
+ topic: message.topic,
58966
+ payload: encoder11.encode(message.payload),
58967
+ qos,
58968
+ retain,
58969
+ ...packetId === void 0 ? {} : { packetId },
58970
+ ...message.responseTopic === void 0 ? {} : { responseTopic: message.responseTopic },
58971
+ ...message.correlationData === void 0 ? {} : { correlationData: message.correlationData }
58972
+ },
58973
+ subscriber.version
58974
+ )
58874
58975
  );
58875
58976
  };
58876
58977
  var accept = (control, message) => {
@@ -58894,6 +58995,7 @@ var serveConnection2 = (control) => Effect_exports.fnUntraced(
58894
58995
  let will;
58895
58996
  const subscriber = {
58896
58997
  clientId: void 0,
58998
+ version: 5,
58897
58999
  subscriptions: [],
58898
59000
  outgoing: yield* Queue_exports.unbounded(),
58899
59001
  nextPacketId: 1
@@ -58918,10 +59020,16 @@ var serveConnection2 = (control) => Effect_exports.fnUntraced(
58918
59020
  switch (split4.type) {
58919
59021
  case PacketType.CONNECT: {
58920
59022
  const connect2 = decodeConnect(split4.body);
59023
+ const unsupported3 = Result_exports.isFailure(connect2) ? connect2.failure.message.startsWith("unsupported protocol") : false;
59024
+ if (unsupported3 || Result_exports.isSuccess(connect2) && connect2.success.protocolVersion === 5 && !control.speaksMqtt5) {
59025
+ yield* writer.write(encodeUnsupportedLevelConnack());
59026
+ return;
59027
+ }
58921
59028
  if (Result_exports.isFailure(connect2)) return;
58922
59029
  const { password, ...rest } = connect2.success;
58923
59030
  control.connects.push({ ...rest, hasPassword: password !== void 0 });
58924
- yield* writer.write(encodeConnack(control.connackReason, control.connackProperties));
59031
+ subscriber.version = connect2.success.protocolVersion ?? 5;
59032
+ yield* writer.write(encodeConnack(control.connackReason, control.connackProperties, subscriber.version));
58925
59033
  if (control.connackReason >= 128) return;
58926
59034
  clientId = connect2.success.clientId;
58927
59035
  subscriber.clientId = clientId;
@@ -58930,7 +59038,7 @@ var serveConnection2 = (control) => Effect_exports.fnUntraced(
58930
59038
  break;
58931
59039
  }
58932
59040
  case PacketType.PUBLISH: {
58933
- const publish2 = decodePublish(split4.flags, split4.body);
59041
+ const publish2 = decodePublish(split4.flags, split4.body, subscriber.version);
58934
59042
  if (Result_exports.isFailure(publish2) || clientId === void 0) return;
58935
59043
  const { topic, qos, retain, packetId, responseTopic, correlationData } = publish2.success;
58936
59044
  const payload = decoder5.decode(publish2.success.payload);
@@ -58947,19 +59055,22 @@ var serveConnection2 = (control) => Effect_exports.fnUntraced(
58947
59055
  });
58948
59056
  }
58949
59057
  if (qos === 1 && packetId !== void 0 && control.ackPublishes) {
58950
- yield* writer.write(encodePuback(packetId, reasonCode));
59058
+ yield* writer.write(encodePuback(packetId, reasonCode, subscriber.version));
58951
59059
  }
58952
59060
  break;
58953
59061
  }
58954
59062
  case PacketType.SUBSCRIBE: {
58955
- const subscribe2 = decodeSubscribe(split4.body);
59063
+ const subscribe2 = decodeSubscribe(split4.body, subscriber.version);
58956
59064
  if (Result_exports.isFailure(subscribe2) || clientId === void 0) return;
58957
59065
  subscriber.subscriptions.push(...subscribe2.success.subscriptions);
58958
59066
  yield* writer.write(
58959
- encodeSuback({
58960
- packetId: subscribe2.success.packetId,
58961
- reasonCodes: subscribe2.success.subscriptions.map((subscription) => subscription.qos)
58962
- })
59067
+ encodeSuback(
59068
+ {
59069
+ packetId: subscribe2.success.packetId,
59070
+ reasonCodes: subscribe2.success.subscriptions.map((subscription) => subscription.qos)
59071
+ },
59072
+ subscriber.version
59073
+ )
58963
59074
  );
58964
59075
  const fresh2 = { ...subscriber, subscriptions: [...subscribe2.success.subscriptions] };
58965
59076
  for (const message of control.retainedMessages.values()) deliver(fresh2, message, true);
@@ -58986,7 +59097,7 @@ var serveConnection2 = (control) => Effect_exports.fnUntraced(
58986
59097
  split4 = frames.next();
58987
59098
  }
58988
59099
  if (split4._tag === "TooLarge") {
58989
- yield* writer.write(encodeDisconnect(149));
59100
+ if (subscriber.version === 5) yield* writer.write(encodeDisconnect(149));
58990
59101
  return;
58991
59102
  }
58992
59103
  if (split4._tag === "Invalid") return;
@@ -59145,7 +59256,8 @@ var demoConfig = (example, directory, options3) => {
59145
59256
  ...options3.public === void 0 ? {} : {
59146
59257
  mqtt: {
59147
59258
  url: `mqtt://${options3.public.broker.host}:${options3.public.broker.port}`,
59148
- clientId: `ot-gateway-${site}`
59259
+ clientId: `ot-gateway-${site}`,
59260
+ version: "auto"
59149
59261
  }
59150
59262
  },
59151
59263
  ...buffer4 === void 0 ? {} : { buffer: { ...buffer4, path: `${directory}/buffer.sqlite` } },
@@ -71389,6 +71501,104 @@ var statusReport = Effect_exports.fn("statusReport")(function* (url, options3 =
71389
71501
  yield* Console_exports.log(options3.json === true ? JSON.stringify(status3, null, 2) : formatStatus(status3));
71390
71502
  });
71391
71503
 
71504
+ // src/Broker.ts
71505
+ var DIAL_TIMEOUT = "15 seconds";
71506
+ var ROUND_TRIP_TIMEOUT = "5 seconds";
71507
+ var BrokerCommandError = class extends Schema_exports.TaggedError()("BrokerCommandError", {
71508
+ message: Schema_exports.String
71509
+ }) {
71510
+ };
71511
+ var randomSuffix = Effect_exports.map(Random_exports.nextIntBetween(0, 16777215), (value4) => value4.toString(16).padStart(6, "0"));
71512
+ var brokerClient = Effect_exports.fn("brokerClient")(function* (settings, role, options3 = {}) {
71513
+ const address = yield* parseBrokerUrl(settings.url);
71514
+ const password = settings.passwordEnv === void 0 ? void 0 : yield* Config_exports.Redacted(settings.passwordEnv);
71515
+ const openTimeout2 = "10 seconds";
71516
+ 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 });
71517
+ return yield* makeMqttClient(socket, {
71518
+ ...options3,
71519
+ clientId: `ot-gateway-${role}-${yield* randomSuffix}`,
71520
+ protocolVersion: settings.version,
71521
+ ...settings.username === void 0 ? {} : { username: settings.username },
71522
+ ...password === void 0 ? {} : { password }
71523
+ });
71524
+ });
71525
+ var firstDialOf = (client, url) => client.firstDial.pipe(
71526
+ Effect_exports.timeoutOrElse({
71527
+ duration: DIAL_TIMEOUT,
71528
+ orElse: () => Effect_exports.fail(new MqttConnectionError({ message: `no answer within ${DIAL_TIMEOUT}` }))
71529
+ }),
71530
+ Effect_exports.mapError((error2) => new BrokerCommandError({ message: `could not connect to ${url}: ${error2.message}` }))
71531
+ );
71532
+ var brokerWarnings = (info2, roundTripMs, topic) => [
71533
+ ...info2.protocolVersion === "3.1.1" ? [
71534
+ "MQTT 3.1.1: the broker announces no limits, commands get no correlation data and messages no expiry (docs/configuration.md, mqtt.version)"
71535
+ ] : [],
71536
+ ...info2.retainAvailable ? [] : ["the broker keeps no retained messages: $meta and health reach only clients connected at the time"],
71537
+ ...info2.maximumQoS === 0 ? ["the broker allows QoS 0 only: nothing confirms that a message arrived, so the buffer cannot help"] : [],
71538
+ ...roundTripMs === void 0 ? [
71539
+ `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`
71540
+ ] : []
71541
+ ];
71542
+ var checkBroker = Effect_exports.fn("checkBroker")(function* (config) {
71543
+ const topic = `${config.site}/${config.building}/$gateway/${config.id}/check/${yield* randomSuffix}`;
71544
+ const payload = "ot-gateway broker check";
71545
+ const received = yield* Deferred_exports.make();
71546
+ const client = yield* brokerClient(config.mqtt, "check", {
71547
+ subscriptions: [{ filter: topic, qos: 1 }],
71548
+ onMessage: (message) => message.topic === topic ? Effect_exports.flatMap(
71549
+ Effect_exports.clockWith((clock) => clock.currentTimeMillis),
71550
+ (now2) => Deferred_exports.succeed(received, now2)
71551
+ ).pipe(Effect_exports.asVoid) : Effect_exports.void
71552
+ });
71553
+ yield* firstDialOf(client, config.mqtt.url);
71554
+ const info2 = yield* client.connection;
71555
+ if (info2 === void 0) {
71556
+ return yield* new BrokerCommandError({ message: `connected to ${config.mqtt.url}, then lost the connection` });
71557
+ }
71558
+ const sentAt = yield* Effect_exports.clockWith((clock) => clock.currentTimeMillis);
71559
+ yield* client.publish(topic, payload, { qos: 1 }).pipe(
71560
+ Effect_exports.mapError(
71561
+ (error2) => new BrokerCommandError({ message: `${config.mqtt.url} did not take a message: ${error2.message}` })
71562
+ )
71563
+ );
71564
+ const arrivedAt = yield* Deferred_exports.await(received).pipe(Effect_exports.timeoutOption(ROUND_TRIP_TIMEOUT));
71565
+ const roundTripMs = Option_exports.match(arrivedAt, {
71566
+ onNone: () => void 0,
71567
+ onSome: (at) => Math.max(0, at - sentAt)
71568
+ });
71569
+ const report = {
71570
+ ok: true,
71571
+ broker: config.mqtt.url,
71572
+ ...info2,
71573
+ ...roundTripMs === void 0 ? {} : { roundTripMs },
71574
+ roundTripTopic: topic,
71575
+ warnings: brokerWarnings(info2, roundTripMs, topic)
71576
+ };
71577
+ return report;
71578
+ }, Effect_exports.scoped);
71579
+ var sizeText = (bytes3) => bytes3 >= 1024 * 1024 ? `${Math.round(bytes3 / 1024 / 1024)} MiB` : bytes3 >= 1024 ? `${Math.round(bytes3 / 1024)} KiB` : `${bytes3} B`;
71580
+ var formatBrokerReport = (report) => [
71581
+ `${report.broker}: connected with MQTT ${report.protocolVersion}`,
71582
+ ` allows QoS ${report.maximumQoS}, ${report.retainAvailable ? "retained messages" : "NO retained messages"}, ${report.receiveMaximum} in flight, ${report.maximumPacketSize === void 0 ? "packets of any size" : `packets up to ${sizeText(report.maximumPacketSize)}`}, keep-alive ${report.keepAliveSeconds} s`,
71583
+ report.roundTripMs === void 0 ? ` round trip: NO ANSWER within ${ROUND_TRIP_TIMEOUT}` : ` round trip: ${report.roundTripMs} ms (QoS 1, through ${report.roundTripTopic})`,
71584
+ ...report.warnings.map((warning) => ` warning: ${warning}`)
71585
+ ].join("\n");
71586
+ var publishOnce = Effect_exports.fn("publishOnce")(function* (config, topic, payload, options3) {
71587
+ const client = yield* brokerClient(config.mqtt, "publish");
71588
+ yield* firstDialOf(client, config.mqtt.url);
71589
+ yield* client.publish(topic, payload, { qos: options3.qos, retain: options3.retain }).pipe(Effect_exports.mapError((error2) => new BrokerCommandError({ message: `${topic}: ${error2.message}` })));
71590
+ return {
71591
+ ok: true,
71592
+ broker: config.mqtt.url,
71593
+ topic,
71594
+ bytes: new TextEncoder().encode(payload).length,
71595
+ qos: options3.qos,
71596
+ retain: options3.retain,
71597
+ cleared: options3.retain && payload === ""
71598
+ };
71599
+ }, Effect_exports.scoped);
71600
+ 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" : ""})`;
71601
+
71392
71602
  // src/Watch.ts
71393
71603
  var MAX_PAYLOAD = 300;
71394
71604
  var watchFilter = (config) => `${config.site}/${config.building}/#`;
@@ -71400,16 +71610,8 @@ var formatMessage2 = (message, at) => {
71400
71610
  return `${time2} ${message.retain ? "retained " : ""}${message.topic} ${payload}`;
71401
71611
  };
71402
71612
  var watch3 = Effect_exports.fn("watch")(function* (config, options3 = {}) {
71403
- const address = yield* parseBrokerUrl(config.mqtt.url);
71404
- const password = config.mqtt.passwordEnv === void 0 ? void 0 : yield* Config_exports.Redacted(config.mqtt.passwordEnv);
71405
71613
  const filter14 = options3.topic ?? watchFilter(config);
71406
- const openTimeout2 = "10 seconds";
71407
- 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 });
71408
- const suffix = (yield* Random_exports.nextIntBetween(0, 16777215)).toString(16).padStart(6, "0");
71409
- yield* makeMqttClient(socket, {
71410
- clientId: `ot-gateway-watch-${suffix}`,
71411
- ...config.mqtt.username === void 0 ? {} : { username: config.mqtt.username },
71412
- ...password === void 0 ? {} : { password },
71614
+ yield* brokerClient(config.mqtt, "watch", {
71413
71615
  subscriptions: [{ filter: filter14, qos: 0, retainAsPublished: true }],
71414
71616
  onConnect: () => Console_exports.error(
71415
71617
  `watching ${filter14} on ${config.mqtt.url} (${options3.seconds === void 0 ? "Ctrl-C to stop" : `for ${options3.seconds} s`})`
@@ -76508,6 +76710,65 @@ var watchCommand = Command_exports.make(
76508
76710
  { command: "ot-gateway watch --seconds 10", description: "Ten seconds of it, then stop" }
76509
76711
  ])
76510
76712
  );
76713
+ var brokerCommand = Command_exports.make(
76714
+ "broker",
76715
+ { config: configPath, json: jsonFlag },
76716
+ ({ config, json: json3 }) => loadConfig(config).pipe(
76717
+ Effect_exports.flatMap(checkBroker),
76718
+ Effect_exports.flatMap((report) => json3 ? printJson(report) : Console_exports.log(formatBrokerReport(report))),
76719
+ jsonFailure(json3, { path: config })
76720
+ )
76721
+ ).pipe(
76722
+ Command_exports.withDescription(
76723
+ "Connect to the config's broker: the MQTT it speaks (5 or 3.1.1), what it allows, and a message there and back"
76724
+ ),
76725
+ Command_exports.withExamples([
76726
+ { command: "ot-gateway broker", description: "Check the broker in ot-gateway.json" },
76727
+ { command: "ot-gateway broker /etc/ot-gateway/gateway.json --json", description: "Another config, as JSON" }
76728
+ ])
76729
+ );
76730
+ var publishCommand = Command_exports.make(
76731
+ "publish",
76732
+ {
76733
+ topic: Argument_exports.String("topic").pipe(Argument_exports.withDescription("The topic, without wildcards")),
76734
+ payload: Argument_exports.String("payload").pipe(
76735
+ Argument_exports.withDescription("The message; empty when left out"),
76736
+ Argument_exports.withDefault("")
76737
+ ),
76738
+ config: Flag_exports.String("config").pipe(
76739
+ Flag_exports.withDescription("Path of the gateway's JSON config"),
76740
+ Flag_exports.withDefault("ot-gateway.json")
76741
+ ),
76742
+ retain: Flag_exports.Boolean("retain").pipe(
76743
+ Flag_exports.withDescription(
76744
+ "Ask the broker to keep it for later subscribers; an empty retained message clears the topic"
76745
+ ),
76746
+ Flag_exports.withDefault(false)
76747
+ ),
76748
+ qos: Flag_exports.ChoiceWithValue("qos", [
76749
+ ["0", 0],
76750
+ ["1", 1]
76751
+ ]).pipe(
76752
+ Flag_exports.withDescription("0 sends and forgets, 1 waits until the broker confirmed it"),
76753
+ Flag_exports.withDefault(1)
76754
+ ),
76755
+ json: jsonFlag
76756
+ },
76757
+ ({ topic, payload, config, retain, qos, json: json3 }) => loadConfig(config).pipe(
76758
+ Effect_exports.flatMap((decoded) => publishOnce(decoded, topic, payload, { retain, qos })),
76759
+ Effect_exports.flatMap((result4) => json3 ? printJson(result4) : Console_exports.log(formatPublished(result4))),
76760
+ jsonFailure(json3, { topic })
76761
+ )
76762
+ ).pipe(
76763
+ Command_exports.withDescription("Send one message to the config's broker, as the gateway's user"),
76764
+ Command_exports.withExamples([
76765
+ { command: "ot-gateway publish my-site/main/test hello", description: "A message, QoS 1" },
76766
+ {
76767
+ command: "ot-gateway publish 'my-site/main/old-device/temp/$meta' --retain",
76768
+ description: "Clear a retained message the broker keeps for a device that is gone"
76769
+ }
76770
+ ])
76771
+ );
76511
76772
  var status2 = Command_exports.make(
76512
76773
  "status",
76513
76774
  {
@@ -76528,6 +76789,7 @@ var rootDescription = [
76528
76789
  " import <list> --dry-run --json check a points list, row by row",
76529
76790
  " init <folder> --dry-run --json the folder init would write (with --site, --broker, --points <list>)",
76530
76791
  " check --json every mistake in a config, with its path",
76792
+ " broker --json the broker: MQTT version, limits, a round trip",
76531
76793
  " status --json the running gateway, device by device"
76532
76794
  ].join("\n");
76533
76795
  var cli = Command_exports.make("ot-gateway").pipe(
@@ -76542,6 +76804,8 @@ var cli = Command_exports.make("ot-gateway").pipe(
76542
76804
  points,
76543
76805
  profiles,
76544
76806
  watchCommand,
76807
+ brokerCommand,
76808
+ publishCommand,
76545
76809
  status2
76546
76810
  ])
76547
76811
  );
@@ -76555,6 +76819,8 @@ var subcommands = /* @__PURE__ */ new Set([
76555
76819
  "points",
76556
76820
  "profiles",
76557
76821
  "watch",
76822
+ "broker",
76823
+ "publish",
76558
76824
  "status"
76559
76825
  ]);
76560
76826
  var toCliArgs = (argv) => {