@zyno-io/ts-server-foundation 26.729.1927 → 26.731.113

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 (112) hide show
  1. package/dist/src/app/base.d.ts +2 -1
  2. package/dist/src/app/base.d.ts.map +1 -1
  3. package/dist/src/app/base.js +19 -4
  4. package/dist/src/app/base.js.map +1 -1
  5. package/dist/src/app/index.js +1 -1
  6. package/dist/src/di/container.js +1 -1
  7. package/dist/src/helpers/index.d.ts +1 -0
  8. package/dist/src/helpers/index.d.ts.map +1 -1
  9. package/dist/src/helpers/index.js +1 -0
  10. package/dist/src/helpers/index.js.map +1 -1
  11. package/dist/src/helpers/utils/timer.d.ts +3 -0
  12. package/dist/src/helpers/utils/timer.d.ts.map +1 -0
  13. package/dist/src/helpers/utils/timer.js +12 -0
  14. package/dist/src/helpers/utils/timer.js.map +1 -0
  15. package/dist/src/http/base.js +3 -3
  16. package/dist/src/http/base.js.map +1 -1
  17. package/dist/src/http/decorators.d.ts +12 -0
  18. package/dist/src/http/decorators.d.ts.map +1 -1
  19. package/dist/src/http/decorators.js +24 -1
  20. package/dist/src/http/decorators.js.map +1 -1
  21. package/dist/src/http/index.js +1 -1
  22. package/dist/src/http/response.js +1 -1
  23. package/dist/src/http/router.d.ts +16 -2
  24. package/dist/src/http/router.d.ts.map +1 -1
  25. package/dist/src/http/router.js +119 -28
  26. package/dist/src/http/router.js.map +1 -1
  27. package/dist/src/http/static-files.d.ts +4 -3
  28. package/dist/src/http/static-files.d.ts.map +1 -1
  29. package/dist/src/http/static-files.js +12 -4
  30. package/dist/src/http/static-files.js.map +1 -1
  31. package/dist/src/index.js +1 -1
  32. package/dist/src/services/index.js +1 -1
  33. package/dist/src/services/mesh-client/index.d.ts +3 -1
  34. package/dist/src/services/mesh-client/index.d.ts.map +1 -1
  35. package/dist/src/services/mesh-client/index.js +6 -2
  36. package/dist/src/services/mesh-client/index.js.map +1 -1
  37. package/dist/src/services/mesh-client/mesh-client-redis-registry.d.ts +53 -7
  38. package/dist/src/services/mesh-client/mesh-client-redis-registry.d.ts.map +1 -1
  39. package/dist/src/services/mesh-client/mesh-client-redis-registry.js +862 -61
  40. package/dist/src/services/mesh-client/mesh-client-redis-registry.js.map +1 -1
  41. package/dist/src/services/mesh-client/mesh-client-registry.d.ts +17 -6
  42. package/dist/src/services/mesh-client/mesh-client-registry.d.ts.map +1 -1
  43. package/dist/src/services/mesh-client/mesh-client-registry.js +43 -2
  44. package/dist/src/services/mesh-client/mesh-client-registry.js.map +1 -1
  45. package/dist/src/services/mesh-client/mesh-client-service.d.ts +115 -48
  46. package/dist/src/services/mesh-client/mesh-client-service.d.ts.map +1 -1
  47. package/dist/src/services/mesh-client/mesh-client-service.js +790 -101
  48. package/dist/src/services/mesh-client/mesh-client-service.js.map +1 -1
  49. package/dist/src/services/mesh-client/mesh-srpc-link-controller.d.ts +129 -17
  50. package/dist/src/services/mesh-client/mesh-srpc-link-controller.d.ts.map +1 -1
  51. package/dist/src/services/mesh-client/mesh-srpc-link-controller.js +1615 -126
  52. package/dist/src/services/mesh-client/mesh-srpc-link-controller.js.map +1 -1
  53. package/dist/src/services/mesh-client/mesh-srpc-remote-connection.d.ts +38 -6
  54. package/dist/src/services/mesh-client/mesh-srpc-remote-connection.d.ts.map +1 -1
  55. package/dist/src/services/mesh-client/mesh-srpc-remote-connection.js +192 -27
  56. package/dist/src/services/mesh-client/mesh-srpc-remote-connection.js.map +1 -1
  57. package/dist/src/services/mesh-client/mesh-srpc-server.d.ts +57 -8
  58. package/dist/src/services/mesh-client/mesh-srpc-server.d.ts.map +1 -1
  59. package/dist/src/services/mesh-client/mesh-srpc-server.js +479 -131
  60. package/dist/src/services/mesh-client/mesh-srpc-server.js.map +1 -1
  61. package/dist/src/services/mesh-client/types.d.ts +77 -6
  62. package/dist/src/services/mesh-client/types.d.ts.map +1 -1
  63. package/dist/src/services/mesh-client/types.js +1 -1
  64. package/dist/src/services/mesh-client/types.js.map +1 -1
  65. package/dist/src/services/mesh-link/auth.d.ts +36 -2
  66. package/dist/src/services/mesh-link/auth.d.ts.map +1 -1
  67. package/dist/src/services/mesh-link/auth.js +97 -21
  68. package/dist/src/services/mesh-link/auth.js.map +1 -1
  69. package/dist/src/services/mesh-link/index.d.ts +2 -2
  70. package/dist/src/services/mesh-link/index.d.ts.map +1 -1
  71. package/dist/src/services/mesh-link/index.js +5 -2
  72. package/dist/src/services/mesh-link/index.js.map +1 -1
  73. package/dist/src/services/mesh-link/peer.d.ts +26 -1
  74. package/dist/src/services/mesh-link/peer.d.ts.map +1 -1
  75. package/dist/src/services/mesh-link/peer.js +220 -26
  76. package/dist/src/services/mesh-link/peer.js.map +1 -1
  77. package/dist/src/services/mesh-link/protocol.d.ts +16 -3
  78. package/dist/src/services/mesh-link/protocol.d.ts.map +1 -1
  79. package/dist/src/services/mesh-link/protocol.js +8 -4
  80. package/dist/src/services/mesh-link/protocol.js.map +1 -1
  81. package/dist/src/services/mesh-link/runtime.d.ts +57 -4
  82. package/dist/src/services/mesh-link/runtime.d.ts.map +1 -1
  83. package/dist/src/services/mesh-link/runtime.js +557 -67
  84. package/dist/src/services/mesh-link/runtime.js.map +1 -1
  85. package/dist/src/services/mesh.d.ts +72 -28
  86. package/dist/src/services/mesh.d.ts.map +1 -1
  87. package/dist/src/services/mesh.js +587 -278
  88. package/dist/src/services/mesh.js.map +1 -1
  89. package/dist/src/srpc/SrpcByteStream.d.ts +21 -2
  90. package/dist/src/srpc/SrpcByteStream.d.ts.map +1 -1
  91. package/dist/src/srpc/SrpcByteStream.js +271 -61
  92. package/dist/src/srpc/SrpcByteStream.js.map +1 -1
  93. package/dist/src/srpc/SrpcClient.d.ts +57 -13
  94. package/dist/src/srpc/SrpcClient.d.ts.map +1 -1
  95. package/dist/src/srpc/SrpcClient.js +558 -120
  96. package/dist/src/srpc/SrpcClient.js.map +1 -1
  97. package/dist/src/srpc/SrpcServer.d.ts +59 -4
  98. package/dist/src/srpc/SrpcServer.d.ts.map +1 -1
  99. package/dist/src/srpc/SrpcServer.js +683 -80
  100. package/dist/src/srpc/SrpcServer.js.map +1 -1
  101. package/dist/src/srpc/index.js +1 -1
  102. package/dist/src/srpc/observer.js +1 -1
  103. package/dist/src/srpc/types.d.ts +37 -6
  104. package/dist/src/srpc/types.d.ts.map +1 -1
  105. package/dist/src/srpc/types.js +12 -1
  106. package/dist/src/srpc/types.js.map +1 -1
  107. package/docs/content/getting-started.md +22 -20
  108. package/docs/content/http.md +38 -1
  109. package/docs/content/mesh-client.md +175 -53
  110. package/docs/content/mesh-service.md +64 -229
  111. package/docs/content/srpc.md +33 -10
  112. package/package.json +7 -7
@@ -1,28 +1,41 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MeshClientRedisRegistry = void 0;
3
+ exports.__tsfTypeAliases = exports.MeshClientRedisRegistry = void 0;
4
4
  exports.destroyClientRedis = destroyClientRedis;
5
5
  const tslib_1 = require("tslib");
6
6
  const _a = tslib_1.__importStar(require("@zyno-io/ts-server-foundation/type-metadata-runtime"));
7
+ const node_crypto_1 = require("node:crypto");
7
8
  const lifecycle_1 = require("../../helpers/redis/lifecycle");
8
9
  const redis_1 = require("../../helpers/redis/redis");
9
- const __tsf_metadata_type = _a.createCompactMetadataRegistryV1("[1,[{\"kind\":6},{\"kind\":7},{\"kind\":2},{\"kind\":22,\"type\":{\"kind\":12,\"types\":[{\"kind\":18,\"types\":[{\"kind\":20,\"name\":\"status\",\"type\":{\"kind\":10,\"literal\":\"ok\"},\"optional\":false},{\"kind\":20,\"name\":\"supersededNodeId\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":5}]},\"optional\":false}]},{\"kind\":18,\"types\":[{\"kind\":20,\"name\":\"status\",\"type\":{\"kind\":10,\"literal\":\"conflict\"},\"optional\":false},{\"kind\":20,\"name\":\"ownerNodeId\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":5}]},\"optional\":false}]}],\"typeName\":\"RegisterResult\"}},{\"kind\":22,\"type\":{\"kind\":8}},{\"kind\":22,\"type\":{\"kind\":3}}]]", []);
10
+ const __tsf_metadata_type = _a.createCompactMetadataRegistryV1("[1,[{\"kind\":6},{\"kind\":7},{\"kind\":8},{\"kind\":22,\"type\":{\"kind\":12,\"types\":[{\"kind\":18,\"types\":[{\"kind\":20,\"name\":\"status\",\"type\":{\"kind\":10,\"literal\":\"ok\"},\"optional\":false},{\"kind\":20,\"name\":\"supersededNodeId\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":5}]},\"optional\":false},{\"kind\":20,\"name\":\"supersededConnectionId\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true}]},{\"kind\":18,\"types\":[{\"kind\":20,\"name\":\"status\",\"type\":{\"kind\":10,\"literal\":\"conflict\"},\"optional\":false},{\"kind\":20,\"name\":\"ownerNodeId\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":5}]},\"optional\":false}]}],\"typeName\":\"RegisterResult\"}},{\"kind\":22,\"type\":{\"kind\":8}},{\"kind\":2},{\"kind\":22,\"type\":{\"kind\":3}},{\"kind\":12,\"types\":[{\"kind\":10,\"literal\":\"active\"},{\"kind\":10,\"literal\":\"pending\"}],\"typeName\":\"MeshClientRegistrationState\"},{\"kind\":22,\"type\":{\"kind\":12,\"types\":[{\"kind\":8},{\"kind\":10,\"literal\":\"previous-changed\"}],\"typeName\":\"MeshClientClaimCommitResult\"}},{\"kind\":18,\"typeName\":\"MeshClientRedisRegistryOptions\",\"types\":[{\"kind\":20,\"name\":\"maxClientIdBytes\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"maxMetadataBytes\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"maxClientsPerNode\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"scanBatchSize\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"cleanupBatchSize\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"maxAuthReplayPrincipals\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"maxAuthNoncesPerPrincipal\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"maxOrphanItems\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"maxOrphanBytes\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true}]}]]", []);
10
11
  // --- Lua Scripts ---
11
12
  // Safety-net TTL for all client registry keys. Primary cleanup is via
12
13
  // unregister/cleanupNode; this only matters if ALL nodes crash without
13
14
  // graceful shutdown and no leader ever runs cleanup.
14
15
  const KEY_TTL_SECONDS = 86400; // 24 hours
16
+ const CLAIM_TTL_MS = 30000;
17
+ const ORPHAN_TTL_SECONDS = 3600;
18
+ const ORPHAN_CLAIM_MS = 30000;
19
+ const MAX_ORPHAN_CLAIM_SCAN = 100;
20
+ const MAX_CLAIMS_PER_NODE = 8192;
21
+ const DEFAULT_MAX_CLIENT_ID_BYTES = 1024;
22
+ const DEFAULT_MAX_METADATA_BYTES = 64 * 1024;
23
+ const DEFAULT_MAX_CLIENTS_PER_NODE = 10000;
24
+ const DEFAULT_SCAN_BATCH_SIZE = 256;
25
+ const DEFAULT_CLEANUP_BATCH_SIZE = 256;
26
+ const DEFAULT_MAX_AUTH_REPLAY_PRINCIPALS = 4096;
27
+ const DEFAULT_MAX_AUTH_NONCES_PER_PRINCIPAL = 256;
28
+ const DEFAULT_MAX_ORPHAN_ITEMS = 4096;
29
+ const DEFAULT_MAX_ORPHAN_BYTES = 64 * 1024 * 1024;
15
30
  // REGISTER atomically registers a client, optionally moving it between nodes.
16
31
  // KEYS[1] = clients hash, KEYS[2] = new node's set
17
32
  // ARGV[1] = clientId, ARGV[2] = nodeId, ARGV[3] = metadataJson,
18
33
  // ARGV[4] = hasMetadata ("1" or "0"), ARGV[5] = setKeyPrefix,
19
34
  // ARGV[6] = connectedAt, ARGV[7] = allowSupersede ("1" or "0"),
20
- // ARGV[8] = state ("active" or "pending")
35
+ // ARGV[8] = state ("active" or "pending"), ARGV[11] = stable generation ID
21
36
  //
22
- // Returns:
23
- // -1 = registered, no supersession (new client or re-register on same node)
24
- // -2 = conflict: another node owns this client and supersession not allowed
25
- // >=0 = registered, superseded from this nodeId
37
+ // Returns `{ supersededNodeId, supersededConnectionId }`. The connection ID
38
+ // is read from the old record in this same script, before ownership changes.
26
39
  const REGISTER_SCRIPT = `
27
40
  local clientsKey = KEYS[1]
28
41
  local newSetKey = KEYS[2]
@@ -36,23 +49,33 @@ local allowSupersede = ARGV[7] == "1"
36
49
  local state = ARGV[8]
37
50
  local connectionId = ARGV[9]
38
51
  local processId = ARGV[10]
52
+ local generationId = ARGV[11]
53
+ local maxClientsPerNode = tonumber(ARGV[12])
39
54
  local ttl = ${KEY_TTL_SECONDS}
40
55
 
56
+ if connectionId == "" then
57
+ return { -2, "" }
58
+ end
59
+
41
60
  -- Check if client already exists on a different node
42
61
  local supersededNodeId = -1
62
+ local supersededConnectionId = ""
63
+ local stableGenerationId = generationId
43
64
  local existing = redis.call("hget", clientsKey, clientId)
44
65
  if existing then
45
66
  local parsed = cjson.decode(existing)
46
67
  local oldNodeId = tostring(parsed.nodeId)
47
- if oldNodeId ~= nodeId then
48
- if not allowSupersede then
49
- return -2
50
- end
51
- -- Construct old node's set key and remove
52
- local oldSetKey = setKeyPrefix .. oldNodeId .. ":clients"
53
- redis.call("srem", oldSetKey, clientId)
54
- supersededNodeId = tonumber(oldNodeId)
68
+ if oldNodeId ~= nodeId or tostring(parsed.connectionId or "") ~= connectionId then
69
+ -- Direct register has no revocation acknowledgement. A caller that wants
70
+ -- takeover must use claim/fence/commit through MeshClientService;
71
+ -- publishing here would recreate the unsafe old handoff.
72
+ return { -2, "" }
55
73
  end
74
+ stableGenerationId = parsed.claimId or generationId
75
+ end
76
+
77
+ if redis.call("sismember", newSetKey, clientId) == 0 and redis.call("scard", newSetKey) >= maxClientsPerNode then
78
+ return { -3, "" }
56
79
  end
57
80
 
58
81
  -- Set in hash and add to new node's set
@@ -60,6 +83,7 @@ local value = cjson.encode({
60
83
  nodeId = tonumber(nodeId),
61
84
  connectedAt = connectedAt,
62
85
  state = state,
86
+ claimId = stableGenerationId,
63
87
  connectionId = connectionId,
64
88
  processId = processId,
65
89
  hasMetadata = hasMetadata,
@@ -72,8 +96,7 @@ redis.call("sadd", newSetKey, clientId)
72
96
  redis.call("expire", clientsKey, ttl)
73
97
  redis.call("expire", newSetKey, ttl)
74
98
 
75
- -- Return old nodeId if client was superseded from a different node, else -1
76
- return supersededNodeId
99
+ return { supersededNodeId, supersededConnectionId }
77
100
  `;
78
101
  // ACTIVATE promotes a same-node reservation from pending to active without
79
102
  // re-taking ownership if the client moved elsewhere in the meantime.
@@ -89,6 +112,10 @@ local hasMetadata = ARGV[4] == "1"
89
112
  local connectionId = ARGV[5]
90
113
  local ttl = ${KEY_TTL_SECONDS}
91
114
 
115
+ if connectionId == "" then
116
+ return 0
117
+ end
118
+
92
119
  local existing = redis.call("hget", clientsKey, clientId)
93
120
  if not existing then
94
121
  return 0
@@ -98,7 +125,7 @@ local parsed = cjson.decode(existing)
98
125
  if tostring(parsed.nodeId) ~= nodeId then
99
126
  return 0
100
127
  end
101
- if connectionId ~= "" and tostring(parsed.connectionId or "") ~= connectionId then
128
+ if tostring(parsed.connectionId or "") ~= connectionId then
102
129
  return 0
103
130
  end
104
131
 
@@ -106,6 +133,7 @@ local value = cjson.encode({
106
133
  nodeId = parsed.nodeId,
107
134
  connectedAt = parsed.connectedAt,
108
135
  state = "active",
136
+ claimId = parsed.claimId,
109
137
  connectionId = parsed.connectionId,
110
138
  processId = parsed.processId,
111
139
  hasMetadata = hasMetadata,
@@ -120,10 +148,17 @@ return 1
120
148
  const UNREGISTER_SCRIPT = `
121
149
  local clientsKey = KEYS[1]
122
150
  local setKey = KEYS[2]
151
+ local claimsKey = KEYS[3]
152
+ local claimsIndexKey = KEYS[4]
153
+ local nodeClaimsKey = KEYS[5]
123
154
  local clientId = ARGV[1]
124
155
  local nodeId = ARGV[2]
125
156
  local connectionId = ARGV[3]
126
157
 
158
+ if connectionId == "" then
159
+ return 0
160
+ end
161
+
127
162
  local existing = redis.call("hget", clientsKey, clientId)
128
163
  if not existing then
129
164
  return 0
@@ -133,12 +168,21 @@ local parsed = cjson.decode(existing)
133
168
  if tostring(parsed.nodeId) ~= nodeId then
134
169
  return 0
135
170
  end
136
- if connectionId ~= "" and tostring(parsed.connectionId or "") ~= connectionId then
171
+ if tostring(parsed.connectionId or "") ~= connectionId then
137
172
  return 0
138
173
  end
139
174
 
140
175
  redis.call("hdel", clientsKey, clientId)
141
176
  redis.call("srem", setKey, clientId)
177
+ local claimRaw = redis.call("hget", claimsKey, clientId)
178
+ if claimRaw then
179
+ local claim = cjson.decode(claimRaw)
180
+ if tostring(claim.nodeId) == nodeId and tostring(claim.connectionId or "") == connectionId then
181
+ redis.call("hdel", claimsKey, clientId)
182
+ redis.call("zrem", claimsIndexKey, clientId)
183
+ redis.call("srem", nodeClaimsKey, clientId)
184
+ end
185
+ end
142
186
  return 1
143
187
  `;
144
188
  // UPDATE_METADATA atomically updates metadata only if the client is owned by the given node.
@@ -153,6 +197,10 @@ local hasMetadata = ARGV[4] == "1"
153
197
  local connectionId = ARGV[5]
154
198
  local ttl = ${KEY_TTL_SECONDS}
155
199
 
200
+ if connectionId == "" then
201
+ return 0
202
+ end
203
+
156
204
  local existing = redis.call("hget", clientsKey, clientId)
157
205
  if not existing then
158
206
  return 0
@@ -162,7 +210,7 @@ local parsed = cjson.decode(existing)
162
210
  if tostring(parsed.nodeId) ~= nodeId then
163
211
  return 0
164
212
  end
165
- if connectionId ~= "" and tostring(parsed.connectionId or "") ~= connectionId then
213
+ if tostring(parsed.connectionId or "") ~= connectionId then
166
214
  return 0
167
215
  end
168
216
 
@@ -170,6 +218,7 @@ local value = cjson.encode({
170
218
  nodeId = parsed.nodeId,
171
219
  connectedAt = parsed.connectedAt,
172
220
  state = parsed.state or "active",
221
+ claimId = parsed.claimId,
173
222
  connectionId = parsed.connectionId,
174
223
  processId = parsed.processId,
175
224
  hasMetadata = hasMetadata,
@@ -182,24 +231,132 @@ return 1
182
231
  const CLEANUP_NODE_SCRIPT = `
183
232
  local clientsKey = KEYS[1]
184
233
  local setKey = KEYS[2]
234
+ local nodeClaimsKey = KEYS[3]
235
+ local claimsKey = KEYS[4]
236
+ local claimsIndexKey = KEYS[5]
185
237
  local nodeId = ARGV[1]
238
+ local batchSize = tonumber(ARGV[2])
186
239
 
187
- local members = redis.call("smembers", setKey)
240
+ local members = redis.call("spop", setKey, batchSize)
188
241
  local removed = {}
189
242
 
190
243
  for _, clientId in ipairs(members) do
191
244
  local existing = redis.call("hget", clientsKey, clientId)
192
245
  if existing then
193
- local parsed = cjson.decode(existing)
194
- if tostring(parsed.nodeId) == nodeId then
246
+ local decoded, parsed = pcall(cjson.decode, existing)
247
+ if not decoded or type(parsed) ~= "table" then
195
248
  redis.call("hdel", clientsKey, clientId)
249
+ elseif tostring(parsed.nodeId) == nodeId then
250
+ redis.call("hdel", clientsKey, clientId)
251
+ -- Pending reservations never reached user-visible lifecycle
252
+ -- callbacks, so removing them must not manufacture an orphan.
253
+ if (parsed.state or "active") == "active" then
254
+ table.insert(removed, existing)
255
+ table.insert(removed, clientId)
256
+ end
257
+ end
258
+ end
259
+ end
260
+
261
+ for _, clientId in ipairs(redis.call("spop", nodeClaimsKey, batchSize)) do
262
+ redis.call("hdel", claimsKey, clientId)
263
+ redis.call("zrem", claimsIndexKey, clientId)
264
+ end
265
+ local done = redis.call("scard", setKey) == 0 and redis.call("scard", nodeClaimsKey) == 0
266
+ if done then
267
+ redis.call("del", setKey)
268
+ redis.call("del", nodeClaimsKey)
269
+ end
270
+ table.insert(removed, 1, done and "1" or "0")
271
+ return removed
272
+ `;
273
+ const CLEANUP_NODE_AND_ORPHAN_SCRIPT = `
274
+ local clientsKey = KEYS[1]
275
+ local setKey = KEYS[2]
276
+ local nodeClaimsKey = KEYS[3]
277
+ local claimsKey = KEYS[4]
278
+ local claimsIndexKey = KEYS[5]
279
+ local orphanKey = KEYS[6]
280
+ local orphanIndexKey = KEYS[7]
281
+ local orphanAccountingKey = KEYS[8]
282
+ local nodeId = ARGV[1]
283
+ local deliveryId = ARGV[2]
284
+ local batchSize = tonumber(ARGV[3])
285
+ local members = redis.call("srandmember", setKey, batchSize)
286
+ local removed = {}
287
+
288
+ for _, clientId in ipairs(members) do
289
+ local existing = redis.call("hget", clientsKey, clientId)
290
+ if existing then
291
+ local decoded, parsed = pcall(cjson.decode, existing)
292
+ if decoded and type(parsed) == "table" and tostring(parsed.nodeId) == nodeId and (parsed.state or "active") == "active" then
196
293
  table.insert(removed, existing)
197
294
  table.insert(removed, clientId)
198
295
  end
199
296
  end
200
297
  end
201
298
 
202
- redis.call("del", setKey)
299
+ if #removed > 0 then
300
+ local time = redis.call("time")
301
+ local nowMs = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)
302
+ if redis.call("exists", orphanAccountingKey) == 0 and redis.call("hlen", orphanKey) > 0 then
303
+ return { "FULL" }
304
+ end
305
+ local cursor = redis.call("hget", orphanAccountingKey, "sweepCursor") or "0"
306
+ local scan = redis.call("hscan", orphanKey, cursor, "COUNT", 100)
307
+ redis.call("hset", orphanAccountingKey, "sweepCursor", scan[1])
308
+ for scanIndex = 1, #scan[2], 2 do
309
+ local scanId = scan[2][scanIndex]
310
+ local scanRaw = scan[2][scanIndex + 1]
311
+ local decoded, scanItem = pcall(cjson.decode, scanRaw)
312
+ local valid = decoded and type(scanItem) == "table"
313
+ if not valid or tonumber(scanItem.expiresAt or 0) <= nowMs then
314
+ redis.call("hdel", orphanKey, scanId)
315
+ redis.call("zrem", orphanIndexKey, scanId)
316
+ redis.call("hincrby", orphanAccountingKey, "items", -1)
317
+ redis.call("hincrby", orphanAccountingKey, "bytes", -(valid and tonumber(scanItem.accountedBytes) or string.len(scanRaw)))
318
+ end
319
+ end
320
+ local orphanItem = {
321
+ nodeId = tonumber(nodeId),
322
+ records = removed,
323
+ expiresAt = nowMs + ${ORPHAN_TTL_SECONDS * 1000},
324
+ claimedUntil = 0,
325
+ claimToken = ""
326
+ }
327
+ orphanItem.accountedBytes = string.len(cjson.encode(orphanItem)) + 128
328
+ local orphan = cjson.encode(orphanItem)
329
+ local items = tonumber(redis.call("hget", orphanAccountingKey, "items")) or 0
330
+ local bytes = tonumber(redis.call("hget", orphanAccountingKey, "bytes")) or 0
331
+ if items + 1 > tonumber(ARGV[4]) or bytes + orphanItem.accountedBytes > tonumber(ARGV[5]) then
332
+ return { "FULL" }
333
+ end
334
+ redis.call("hset", orphanKey, deliveryId, orphan)
335
+ redis.call("zadd", orphanIndexKey, 0, deliveryId)
336
+ redis.call("hset", orphanAccountingKey, "items", items + 1, "bytes", bytes + orphanItem.accountedBytes)
337
+ end
338
+
339
+ for _, clientId in ipairs(members) do
340
+ redis.call("srem", setKey, clientId)
341
+ local existing = redis.call("hget", clientsKey, clientId)
342
+ if existing then
343
+ local decoded, parsed = pcall(cjson.decode, existing)
344
+ if not decoded or type(parsed) ~= "table" or tostring(parsed.nodeId) == nodeId then
345
+ redis.call("hdel", clientsKey, clientId)
346
+ end
347
+ end
348
+ end
349
+
350
+ for _, clientId in ipairs(redis.call("spop", nodeClaimsKey, batchSize)) do
351
+ redis.call("hdel", claimsKey, clientId)
352
+ redis.call("zrem", claimsIndexKey, clientId)
353
+ end
354
+ local done = redis.call("scard", setKey) == 0 and redis.call("scard", nodeClaimsKey) == 0
355
+ if done then
356
+ redis.call("del", setKey)
357
+ redis.call("del", nodeClaimsKey)
358
+ end
359
+ table.insert(removed, 1, done and "1" or "0")
203
360
  return removed
204
361
  `;
205
362
  const REFRESH_NODE_SCRIPT = `
@@ -212,16 +369,422 @@ if redis.call("exists", setKey) == 1 then
212
369
  end
213
370
  return 1
214
371
  `;
372
+ // CLAIM leaves the current active owner untouched and records a private,
373
+ // bounded reservation. This is the first half of a takeover: it prevents
374
+ // two contenders from both fencing the old generation while it remains the
375
+ // authoritative record for lookup and delivery.
376
+ const CLAIM_SCRIPT = `
377
+ local clientsKey = KEYS[1]
378
+ local claimsKey = KEYS[2]
379
+ local claimsIndexKey = KEYS[3]
380
+ local nodeClaimsKey = KEYS[4]
381
+ local clientId = ARGV[1]
382
+ local nodeId = ARGV[2]
383
+ local metadataJson = ARGV[3]
384
+ local hasMetadata = ARGV[4] == "1"
385
+ local state = ARGV[5]
386
+ local allowSupersede = ARGV[6] == "1"
387
+ local connectionId = ARGV[7]
388
+ local processId = ARGV[8]
389
+ local claimId = ARGV[9]
390
+ local connectedAt = tonumber(ARGV[10])
391
+ local claimSetKeyPrefix = ARGV[11]
392
+ local maxClientsPerNode = tonumber(ARGV[12])
393
+ local operationId = ARGV[13]
394
+ local requestFingerprint = ARGV[14]
395
+ local ttl = ${KEY_TTL_SECONDS}
396
+
397
+ if connectionId == "" then
398
+ return { "conflict", "" }
399
+ end
400
+
401
+ local time = redis.call("time")
402
+ local nowMs = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)
403
+ local expiredClaims = redis.call("zrangebyscore", claimsIndexKey, "-inf", nowMs, "LIMIT", 0, 100)
404
+ for _, expiredClientId in ipairs(expiredClaims) do
405
+ local rawExpired = redis.call("hget", claimsKey, expiredClientId)
406
+ if rawExpired then
407
+ local expiredClaim = cjson.decode(rawExpired)
408
+ redis.call("srem", claimSetKeyPrefix .. tostring(expiredClaim.nodeId) .. ":claims", expiredClientId)
409
+ end
410
+ redis.call("hdel", claimsKey, expiredClientId)
411
+ redis.call("zrem", claimsIndexKey, expiredClientId)
412
+ end
413
+
414
+ local existingClaim = redis.call("hget", claimsKey, clientId)
415
+ if existingClaim then
416
+ local claim = cjson.decode(existingClaim)
417
+ if tonumber(claim.expiresAt or 0) <= nowMs then
418
+ redis.call("hdel", claimsKey, clientId)
419
+ redis.call("zrem", claimsIndexKey, clientId)
420
+ redis.call("srem", claimSetKeyPrefix .. tostring(claim.nodeId) .. ":claims", clientId)
421
+ else
422
+ if claim.operationId == operationId and claim.requestFingerprint == requestFingerprint then
423
+ return { "ok", claim.claimId, claim.previous or "" }
424
+ end
425
+ local active = redis.call("hget", clientsKey, clientId)
426
+ if active then return { "conflict", active } end
427
+ return { "conflict", "" }
428
+ end
429
+ end
430
+
431
+ local previous = redis.call("hget", clientsKey, clientId)
432
+ local preimage = previous or ""
433
+ local expectCurrent = previous and true or false
434
+ if previous then
435
+ local parsed = cjson.decode(previous)
436
+ if parsed.connectionId == nil or tostring(parsed.connectionId) == "" then
437
+ return { "conflict", previous }
438
+ end
439
+ if tostring(parsed.nodeId) ~= nodeId and not allowSupersede then
440
+ return { "conflict", previous }
441
+ end
442
+ -- An exact retry by the current generation is an update, not a takeover.
443
+ if tostring(parsed.nodeId) == nodeId and tostring(parsed.connectionId or "") == connectionId then
444
+ previous = ""
445
+ end
446
+ end
447
+
448
+ if redis.call("sismember", nodeClaimsKey, clientId) == 0 and redis.call("scard", nodeClaimsKey) >= ${MAX_CLAIMS_PER_NODE} then
449
+ return { "capacity", "", "" }
450
+ end
451
+ local newSetKey = claimSetKeyPrefix .. nodeId .. ":clients"
452
+ if redis.call("sismember", newSetKey, clientId) == 0
453
+ and redis.call("scard", newSetKey) + redis.call("scard", nodeClaimsKey) >= maxClientsPerNode then
454
+ return { "node-capacity", "", "" }
455
+ end
456
+ redis.call("hset", claimsKey, clientId, cjson.encode({
457
+ claimId = claimId, nodeId = tonumber(nodeId), metadata = cjson.decode(metadataJson),
458
+ hasMetadata = hasMetadata, state = state, connectionId = connectionId,
459
+ processId = processId, connectedAt = connectedAt, expiresAt = nowMs + ${CLAIM_TTL_MS},
460
+ previous = previous, preimage = preimage, expectCurrent = expectCurrent,
461
+ operationId = operationId, requestFingerprint = requestFingerprint
462
+ }))
463
+ redis.call("zadd", claimsIndexKey, nowMs + ${CLAIM_TTL_MS}, clientId)
464
+ redis.call("sadd", nodeClaimsKey, clientId)
465
+ redis.call("expire", claimsKey, ttl)
466
+ redis.call("expire", claimsIndexKey, ttl)
467
+ redis.call("expire", nodeClaimsKey, ttl)
468
+ return { "ok", claimId, previous or "" }
469
+ `;
470
+ // COMMIT rejects any changed old generation, but accepts its exact absence after
471
+ // the acknowledged fence: unregister may have removed it before commit and must
472
+ // not leave a phantom claim. A stable-token mutation is reported for exact
473
+ // reconciliation; an unrelated reconnect is rejected without mutation.
474
+ const COMMIT_CLAIM_SCRIPT = `
475
+ local clientsKey = KEYS[1]
476
+ local claimsKey = KEYS[2]
477
+ local newSetKey = KEYS[3]
478
+ local claimsIndexKey = KEYS[4]
479
+ local nodeClaimsKey = KEYS[5]
480
+ local clientId = ARGV[1]
481
+ local nodeId = ARGV[2]
482
+ local claimId = ARGV[3]
483
+ local setKeyPrefix = ARGV[4]
484
+ local maxClientsPerNode = tonumber(ARGV[5])
485
+ local ttl = ${KEY_TTL_SECONDS}
486
+ local rawClaim = redis.call("hget", claimsKey, clientId)
487
+ if not rawClaim then
488
+ -- The atomic commit may have succeeded while its response was lost.
489
+ -- Only the exact persisted claim marker makes a retry successful.
490
+ local committed = redis.call("hget", clientsKey, clientId)
491
+ if not committed then return 0 end
492
+ local committedRecord = cjson.decode(committed)
493
+ if tostring(committedRecord.nodeId) == nodeId and committedRecord.claimId == claimId then return 1 end
494
+ return 0
495
+ end
496
+ local claim = cjson.decode(rawClaim)
497
+ if tostring(claim.nodeId) ~= nodeId or claim.claimId ~= claimId then return 0 end
498
+ local now = redis.call("time")
499
+ local nowMs = tonumber(now[1]) * 1000 + math.floor(tonumber(now[2]) / 1000)
500
+ if tonumber(claim.expiresAt or 0) <= nowMs then
501
+ redis.call("hdel", claimsKey, clientId)
502
+ redis.call("zrem", claimsIndexKey, clientId)
503
+ redis.call("srem", nodeClaimsKey, clientId)
504
+ return 0
505
+ end
506
+ local current = redis.call("hget", clientsKey, clientId)
507
+ local previous = claim.previous or ""
508
+ if previous == "" then
509
+ -- Same-generation retries still compare the exact captured record. A
510
+ -- metadata/state transition after CLAIM is not authorization to overwrite
511
+ -- that changed record.
512
+ local preimage = claim.preimage or ""
513
+ if preimage ~= "" then
514
+ if not current or current ~= preimage then return 0 end
515
+ elseif current then
516
+ return 0
517
+ end
518
+ else
519
+ local before = cjson.decode(previous)
520
+ if current and current ~= previous then
521
+ local currentParsed = cjson.decode(current)
522
+ -- Signal a mutation by the exact same stable generation. The caller
523
+ -- has already fenced that physical connection and may remove it with
524
+ -- REMOVE_CLAIM_PREVIOUS before retrying this exact claim. A reconnect
525
+ -- with any other token is never removed or overwritten.
526
+ if before.claimId and currentParsed.claimId == before.claimId
527
+ and tostring(before.nodeId) == tostring(currentParsed.nodeId)
528
+ and tostring(before.connectionId or "") == tostring(currentParsed.connectionId or "") then
529
+ return 2
530
+ end
531
+ return 0
532
+ end
533
+ -- The exact old generation may have synchronously unregistered while
534
+ -- acknowledging its fence. Absence is therefore safe; only a different
535
+ -- generation prevents this claim from committing.
536
+ redis.call("srem", setKeyPrefix .. tostring(before.nodeId) .. ":clients", clientId)
537
+ end
538
+ if redis.call("sismember", newSetKey, clientId) == 0 and redis.call("scard", newSetKey) >= maxClientsPerNode then
539
+ return 0
540
+ end
541
+ local value = cjson.encode({ nodeId = claim.nodeId, connectedAt = claim.connectedAt, state = claim.state, claimId = claim.claimId,
542
+ connectionId = claim.connectionId, processId = claim.processId, hasMetadata = claim.hasMetadata, metadata = claim.metadata })
543
+ redis.call("hset", clientsKey, clientId, value)
544
+ redis.call("sadd", newSetKey, clientId)
545
+ redis.call("hdel", claimsKey, clientId)
546
+ redis.call("zrem", claimsIndexKey, clientId)
547
+ redis.call("srem", nodeClaimsKey, clientId)
548
+ redis.call("expire", clientsKey, ttl)
549
+ redis.call("expire", newSetKey, ttl)
550
+ return 1
551
+ `;
552
+ const REMOVE_CLAIM_PREVIOUS_SCRIPT = `
553
+ local clientsKey = KEYS[1]
554
+ local claimsKey = KEYS[2]
555
+ local clientId = ARGV[1]
556
+ local nodeId = ARGV[2]
557
+ local claimId = ARGV[3]
558
+ local setKeyPrefix = ARGV[4]
559
+ local rawClaim = redis.call("hget", claimsKey, clientId)
560
+ if not rawClaim then return 0 end
561
+ local claim = cjson.decode(rawClaim)
562
+ if tostring(claim.nodeId) ~= nodeId or claim.claimId ~= claimId then return 0 end
563
+ local previous = claim.previous or ""
564
+ if previous == "" then return 0 end
565
+ local before = cjson.decode(previous)
566
+ local current = redis.call("hget", clientsKey, clientId)
567
+ if not current then return 1 end
568
+ if current ~= previous then
569
+ local currentParsed = cjson.decode(current)
570
+ if not before.claimId or currentParsed.claimId ~= before.claimId
571
+ or tostring(currentParsed.nodeId) ~= tostring(before.nodeId)
572
+ or tostring(currentParsed.connectionId or "") ~= tostring(before.connectionId or "") then
573
+ return 0
574
+ end
575
+ end
576
+ redis.call("hdel", clientsKey, clientId)
577
+ redis.call("srem", setKeyPrefix .. tostring(before.nodeId) .. ":clients", clientId)
578
+ return 1
579
+ `;
580
+ const REMOVE_CLAIM_RESULT_SCRIPT = `
581
+ local clientId = ARGV[1]
582
+ local nodeId = ARGV[2]
583
+ local claimId = ARGV[3]
584
+ local removed = 0
585
+ local committed = redis.call("hget", KEYS[1], clientId)
586
+ if committed then
587
+ local record = cjson.decode(committed)
588
+ if tostring(record.nodeId) == nodeId and record.claimId == claimId then
589
+ redis.call("hdel", KEYS[1], clientId)
590
+ redis.call("srem", KEYS[2], clientId)
591
+ removed = 1
592
+ end
593
+ end
594
+ local rawClaim = redis.call("hget", KEYS[3], clientId)
595
+ if rawClaim then
596
+ local claim = cjson.decode(rawClaim)
597
+ if tostring(claim.nodeId) == nodeId and claim.claimId == claimId then
598
+ redis.call("hdel", KEYS[3], clientId)
599
+ redis.call("zrem", KEYS[4], clientId)
600
+ redis.call("srem", KEYS[5], clientId)
601
+ removed = 1
602
+ end
603
+ end
604
+ return removed
605
+ `;
606
+ const ABORT_CLAIM_SCRIPT = `
607
+ local rawClaim = redis.call("hget", KEYS[1], ARGV[1])
608
+ if not rawClaim then return 0 end
609
+ local claim = cjson.decode(rawClaim)
610
+ if tostring(claim.nodeId) ~= ARGV[2] or claim.claimId ~= ARGV[3] then return 0 end
611
+ redis.call("hdel", KEYS[1], ARGV[1])
612
+ redis.call("zrem", KEYS[2], ARGV[1])
613
+ redis.call("srem", KEYS[3], ARGV[1])
614
+ return 1
615
+ `;
616
+ const CLAIM_ORPHAN_SCRIPT = `
617
+ local key = KEYS[1]
618
+ local indexKey = KEYS[2]
619
+ local accountingKey = KEYS[3]
620
+ local token = ARGV[1]
621
+ local time = redis.call("time")
622
+ local now = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)
623
+ if redis.call("exists", accountingKey) == 0 then return { "", "" } end
624
+ -- Sweep a bounded HSCAN slice on every drain attempt. This gives each
625
+ -- snapshot its own expiry rather than extending the whole queue's TTL when a
626
+ -- newer item is admitted.
627
+ local cursor = redis.call("hget", accountingKey, "sweepCursor") or "0"
628
+ local scan = redis.call("hscan", key, cursor, "COUNT", 100)
629
+ redis.call("hset", accountingKey, "sweepCursor", scan[1])
630
+ for index = 1, #scan[2], 2 do
631
+ local scanId = scan[2][index]
632
+ local scanRaw = scan[2][index + 1]
633
+ local decoded, scanItem = pcall(cjson.decode, scanRaw)
634
+ local valid = decoded and type(scanItem) == "table"
635
+ if not valid or tonumber(scanItem.expiresAt or 0) <= now then
636
+ redis.call("hdel", key, scanId)
637
+ redis.call("zrem", indexKey, scanId)
638
+ redis.call("hincrby", accountingKey, "items", -1)
639
+ redis.call("hincrby", accountingKey, "bytes", -(valid and tonumber(scanItem.accountedBytes) or string.len(scanRaw)))
640
+ end
641
+ end
642
+ if redis.call("hlen", key) == 0 then
643
+ redis.call("del", accountingKey)
644
+ return { "", "" }
645
+ end
646
+ local candidates = redis.call("zrangebyscore", indexKey, "-inf", now, "LIMIT", 0, ${MAX_ORPHAN_CLAIM_SCAN})
647
+ for _, id in ipairs(candidates) do
648
+ local raw = redis.call("hget", key, id)
649
+ if raw then
650
+ local decoded, item = pcall(cjson.decode, raw)
651
+ if not decoded or type(item) ~= "table" then
652
+ redis.call("hdel", key, id)
653
+ redis.call("zrem", indexKey, id)
654
+ redis.call("hincrby", accountingKey, "items", -1)
655
+ redis.call("hincrby", accountingKey, "bytes", -string.len(raw))
656
+ elseif tonumber(item.expiresAt or 0) <= now then
657
+ redis.call("hdel", key, id)
658
+ redis.call("zrem", indexKey, id)
659
+ redis.call("hincrby", accountingKey, "items", -1)
660
+ redis.call("hincrby", accountingKey, "bytes", -(tonumber(item.accountedBytes) or string.len(raw)))
661
+ elseif tonumber(item.claimedUntil or 0) <= now then
662
+ item.claimToken = token
663
+ item.claimedUntil = now + ${ORPHAN_CLAIM_MS}
664
+ local updated = cjson.encode(item)
665
+ redis.call("hset", key, id, updated)
666
+ redis.call("zadd", indexKey, item.claimedUntil, id)
667
+ return { id, updated }
668
+ end
669
+ else
670
+ redis.call("zrem", indexKey, id)
671
+ end
672
+ end
673
+ if redis.call("hlen", key) == 0 then redis.call("del", accountingKey) end
674
+ return { "", "" }
675
+ `;
676
+ const ACK_ORPHAN_SCRIPT = `
677
+ local raw = redis.call("hget", KEYS[1], ARGV[1])
678
+ if not raw then return 0 end
679
+ local item = cjson.decode(raw)
680
+ if item.claimToken ~= ARGV[2] then return 0 end
681
+ redis.call("hdel", KEYS[1], ARGV[1])
682
+ redis.call("zrem", KEYS[2], ARGV[1])
683
+ redis.call("hincrby", KEYS[3], "items", -1)
684
+ redis.call("hincrby", KEYS[3], "bytes", -(tonumber(item.accountedBytes) or string.len(raw)))
685
+ if redis.call("hlen", KEYS[1]) == 0 then redis.call("del", KEYS[3]) end
686
+ return 1
687
+ `;
688
+ const NACK_ORPHAN_SCRIPT = `
689
+ local raw = redis.call("hget", KEYS[1], ARGV[1])
690
+ if not raw then return 0 end
691
+ local item = cjson.decode(raw)
692
+ if item.claimToken ~= ARGV[2] then return 0 end
693
+ item.claimToken = ""
694
+ item.claimedUntil = 0
695
+ local updated = cjson.encode(item)
696
+ redis.call("hset", KEYS[1], ARGV[1], updated)
697
+ redis.call("zadd", KEYS[2], 0, ARGV[1])
698
+ return 1
699
+ `;
700
+ const ENQUEUE_ORPHAN_SCRIPT = `
701
+ local time = redis.call("time")
702
+ local now = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)
703
+ if redis.call("exists", KEYS[3]) == 0 and redis.call("hlen", KEYS[1]) > 0 then return 0 end
704
+ local cursor = redis.call("hget", KEYS[3], "sweepCursor") or "0"
705
+ local scan = redis.call("hscan", KEYS[1], cursor, "COUNT", 100)
706
+ redis.call("hset", KEYS[3], "sweepCursor", scan[1])
707
+ for index = 1, #scan[2], 2 do
708
+ local scanId = scan[2][index]
709
+ local scanRaw = scan[2][index + 1]
710
+ local decoded, scanItem = pcall(cjson.decode, scanRaw)
711
+ local valid = decoded and type(scanItem) == "table"
712
+ if not valid or tonumber(scanItem.expiresAt or 0) <= now then
713
+ redis.call("hdel", KEYS[1], scanId)
714
+ redis.call("zrem", KEYS[2], scanId)
715
+ redis.call("hincrby", KEYS[3], "items", -1)
716
+ redis.call("hincrby", KEYS[3], "bytes", -(valid and tonumber(scanItem.accountedBytes) or string.len(scanRaw)))
717
+ end
718
+ end
719
+ local itemTable = {
720
+ nodeId = tonumber(ARGV[2]),
721
+ clients = cjson.decode(ARGV[3]),
722
+ expiresAt = now + ${ORPHAN_TTL_SECONDS * 1000},
723
+ claimedUntil = 0,
724
+ claimToken = ""
725
+ }
726
+ itemTable.accountedBytes = string.len(cjson.encode(itemTable)) + 128
727
+ local item = cjson.encode(itemTable)
728
+ local old = redis.call("hget", KEYS[1], ARGV[1])
729
+ local items = tonumber(redis.call("hget", KEYS[3], "items")) or 0
730
+ local bytes = tonumber(redis.call("hget", KEYS[3], "bytes")) or 0
731
+ local oldItem = old and cjson.decode(old) or nil
732
+ local oldBytes = oldItem and (tonumber(oldItem.accountedBytes) or string.len(old)) or 0
733
+ local nextItems = items + (old and 0 or 1)
734
+ local nextBytes = bytes - oldBytes + itemTable.accountedBytes
735
+ if nextItems > tonumber(ARGV[4]) or nextBytes > tonumber(ARGV[5]) then return 0 end
736
+ redis.call("hset", KEYS[1], ARGV[1], item)
737
+ redis.call("zadd", KEYS[2], 0, ARGV[1])
738
+ redis.call("hset", KEYS[3], "items", nextItems, "bytes", nextBytes)
739
+ return 1
740
+ `;
741
+ const CONSUME_AUTH_NONCE_SCRIPT = `
742
+ local time = redis.call("time")
743
+ local now = tonumber(time[1]) * 1000 + math.floor(tonumber(time[2]) / 1000)
744
+ local expiresAt = tonumber(ARGV[2])
745
+ local principal = ARGV[3]
746
+ local maxPrincipals = tonumber(ARGV[4])
747
+ local maxNonces = tonumber(ARGV[5])
748
+ if not expiresAt or expiresAt <= now then return 0 end
749
+ redis.call("zremrangebyscore", KEYS[2], "-inf", now)
750
+ if redis.call("zscore", KEYS[2], principal) == false and redis.call("zcard", KEYS[2]) >= maxPrincipals then return 0 end
751
+ redis.call("zremrangebyscore", KEYS[1], "-inf", now)
752
+ if redis.call("zcard", KEYS[1]) >= maxNonces then return 0 end
753
+ if redis.call("zadd", KEYS[1], "NX", expiresAt, ARGV[1]) == 0 then return 0 end
754
+ local latest = redis.call("zrevrange", KEYS[1], 0, 0, "WITHSCORES")
755
+ local latestExpiry = tonumber(latest[2]) or expiresAt
756
+ redis.call("pexpire", KEYS[1], math.max(1, latestExpiry - now))
757
+ -- Do not let a short-lived nonce from one principal reduce the global index
758
+ -- TTL, nor let a new nonce shorten that principal's previously-live score.
759
+ local priorPrincipalExpiry = tonumber(redis.call("zscore", KEYS[2], principal)) or 0
760
+ local principalExpiry = math.max(priorPrincipalExpiry, latestExpiry)
761
+ redis.call("zadd", KEYS[2], principalExpiry, principal)
762
+ local globalLatest = redis.call("zrevrange", KEYS[2], 0, 0, "WITHSCORES")
763
+ local globalExpiry = tonumber(globalLatest[2]) or principalExpiry
764
+ redis.call("pexpire", KEYS[2], math.max(1, globalExpiry - now))
765
+ return 1
766
+ `;
215
767
  let clientRedis = null;
216
768
  function getClientRedis() {
217
769
  if (!clientRedis) {
218
770
  const { client, prefix } = (0, redis_1.createRedis)('MESH');
219
771
  client.defineCommand('MC_REGISTER', { lua: REGISTER_SCRIPT, numberOfKeys: 2 });
220
772
  client.defineCommand('MC_ACTIVATE', { lua: ACTIVATE_SCRIPT, numberOfKeys: 2 });
221
- client.defineCommand('MC_UNREGISTER', { lua: UNREGISTER_SCRIPT, numberOfKeys: 2 });
773
+ client.defineCommand('MC_UNREGISTER', { lua: UNREGISTER_SCRIPT, numberOfKeys: 5 });
222
774
  client.defineCommand('MC_UPDATE_METADATA', { lua: UPDATE_METADATA_SCRIPT, numberOfKeys: 1 });
223
- client.defineCommand('MC_CLEANUP_NODE', { lua: CLEANUP_NODE_SCRIPT, numberOfKeys: 2 });
775
+ client.defineCommand('MC_CLEANUP_NODE', { lua: CLEANUP_NODE_SCRIPT, numberOfKeys: 5 });
776
+ client.defineCommand('MC_CLEANUP_NODE_AND_ORPHAN', { lua: CLEANUP_NODE_AND_ORPHAN_SCRIPT, numberOfKeys: 8 });
224
777
  client.defineCommand('MC_REFRESH_NODE', { lua: REFRESH_NODE_SCRIPT, numberOfKeys: 2 });
778
+ client.defineCommand('MC_CLAIM', { lua: CLAIM_SCRIPT, numberOfKeys: 4 });
779
+ client.defineCommand('MC_COMMIT_CLAIM', { lua: COMMIT_CLAIM_SCRIPT, numberOfKeys: 5 });
780
+ client.defineCommand('MC_REMOVE_CLAIM_PREVIOUS', { lua: REMOVE_CLAIM_PREVIOUS_SCRIPT, numberOfKeys: 2 });
781
+ client.defineCommand('MC_ABORT_CLAIM', { lua: ABORT_CLAIM_SCRIPT, numberOfKeys: 3 });
782
+ client.defineCommand('MC_REMOVE_CLAIM_RESULT', { lua: REMOVE_CLAIM_RESULT_SCRIPT, numberOfKeys: 5 });
783
+ client.defineCommand('MC_CLAIM_ORPHAN', { lua: CLAIM_ORPHAN_SCRIPT, numberOfKeys: 3 });
784
+ client.defineCommand('MC_ACK_ORPHAN', { lua: ACK_ORPHAN_SCRIPT, numberOfKeys: 3 });
785
+ client.defineCommand('MC_NACK_ORPHAN', { lua: NACK_ORPHAN_SCRIPT, numberOfKeys: 3 });
786
+ client.defineCommand('MC_ENQUEUE_ORPHAN', { lua: ENQUEUE_ORPHAN_SCRIPT, numberOfKeys: 3 });
787
+ client.defineCommand('MC_CONSUME_AUTH_NONCE', { lua: CONSUME_AUTH_NONCE_SCRIPT, numberOfKeys: 2 });
225
788
  const nextClient = client;
226
789
  (0, lifecycle_1.registerRedisStateReset)(nextClient, () => {
227
790
  if (clientRedis?.client === nextClient)
@@ -241,8 +804,26 @@ let _MeshClientRedisRegistryMetadata_1;
241
804
  // --- MeshClientRedisRegistry ---
242
805
  class MeshClientRedisRegistry {
243
806
  key;
244
- constructor(key) {
807
+ maxClientIdBytes;
808
+ maxMetadataBytes;
809
+ maxClientsPerNode;
810
+ scanBatchSize;
811
+ cleanupBatchSize;
812
+ maxAuthReplayPrincipals;
813
+ maxAuthNoncesPerPrincipal;
814
+ maxOrphanItems;
815
+ maxOrphanBytes;
816
+ constructor(key, options = {}) {
245
817
  this.key = key;
818
+ this.maxClientIdBytes = configuredLimit(options.maxClientIdBytes, DEFAULT_MAX_CLIENT_ID_BYTES, 'maxClientIdBytes');
819
+ this.maxMetadataBytes = configuredLimit(options.maxMetadataBytes, DEFAULT_MAX_METADATA_BYTES, 'maxMetadataBytes');
820
+ this.maxClientsPerNode = configuredLimit(options.maxClientsPerNode, DEFAULT_MAX_CLIENTS_PER_NODE, 'maxClientsPerNode');
821
+ this.scanBatchSize = configuredLimit(options.scanBatchSize, DEFAULT_SCAN_BATCH_SIZE, 'scanBatchSize');
822
+ this.cleanupBatchSize = configuredLimit(options.cleanupBatchSize, DEFAULT_CLEANUP_BATCH_SIZE, 'cleanupBatchSize');
823
+ this.maxAuthReplayPrincipals = configuredLimit(options.maxAuthReplayPrincipals, DEFAULT_MAX_AUTH_REPLAY_PRINCIPALS, 'maxAuthReplayPrincipals');
824
+ this.maxAuthNoncesPerPrincipal = configuredLimit(options.maxAuthNoncesPerPrincipal, DEFAULT_MAX_AUTH_NONCES_PER_PRINCIPAL, 'maxAuthNoncesPerPrincipal');
825
+ this.maxOrphanItems = configuredLimit(options.maxOrphanItems, DEFAULT_MAX_ORPHAN_ITEMS, 'maxOrphanItems');
826
+ this.maxOrphanBytes = configuredLimit(options.maxOrphanBytes, DEFAULT_MAX_ORPHAN_BYTES, 'maxOrphanBytes');
246
827
  }
247
828
  clientsKey() {
248
829
  const { prefix } = getClientRedis();
@@ -256,6 +837,38 @@ class MeshClientRedisRegistry {
256
837
  const { prefix } = getClientRedis();
257
838
  return `${prefix}:mesh:${this.key}:node:`;
258
839
  }
840
+ nodeClaimsKey(nodeId) {
841
+ return `${this.nodeSetKeyPrefix()}${nodeId}:claims`;
842
+ }
843
+ claimsKey() {
844
+ const { prefix } = getClientRedis();
845
+ return `${prefix}:mesh:${this.key}:claims`;
846
+ }
847
+ claimsIndexKey() {
848
+ const { prefix } = getClientRedis();
849
+ return `${prefix}:mesh:${this.key}:claims:index`;
850
+ }
851
+ orphanedKey() {
852
+ const { prefix } = getClientRedis();
853
+ return `${prefix}:mesh:${this.key}:orphaned`;
854
+ }
855
+ orphanedIndexKey() {
856
+ const { prefix } = getClientRedis();
857
+ return `${prefix}:mesh:${this.key}:orphaned:index`;
858
+ }
859
+ orphanedAccountingKey() {
860
+ const { prefix } = getClientRedis();
861
+ return `${prefix}:mesh:${this.key}:orphaned:accounting`;
862
+ }
863
+ authNonceKey(principal) {
864
+ const { prefix } = getClientRedis();
865
+ const principalHash = (0, node_crypto_1.createHash)('sha256').update(principal).digest('hex');
866
+ return `${prefix}:mesh:${this.key}:auth-nonces:${principalHash}`;
867
+ }
868
+ authNoncePrincipalsKey() {
869
+ const { prefix } = getClientRedis();
870
+ return `${prefix}:mesh:${this.key}:auth-nonce-principals`;
871
+ }
259
872
  encodeMetadata(metadata) {
260
873
  if (metadata === undefined) {
261
874
  return { metadataJson: 'null', hasMetadata: '0' };
@@ -264,12 +877,19 @@ class MeshClientRedisRegistry {
264
877
  if (metadataJson === undefined) {
265
878
  throw new Error('Mesh client metadata must be JSON-serializable');
266
879
  }
880
+ if (Buffer.byteLength(metadataJson) > this.maxMetadataBytes) {
881
+ throw new Error(`Mesh client metadata exceeds the configured ${this.maxMetadataBytes}-byte limit`);
882
+ }
267
883
  return { metadataJson, hasMetadata: '1' };
268
884
  }
269
885
  async registerWithState(clientId, nodeId, metadata, allowSupersede, state, connectionId, processId) {
886
+ this.assertClientId(clientId);
270
887
  const { client } = getClientRedis();
271
888
  const encoded = this.encodeMetadata(metadata);
272
- const result = await client.MC_REGISTER(this.clientsKey(), this.nodeSetKey(nodeId), clientId, String(nodeId), encoded.metadataJson, encoded.hasMetadata, this.nodeSetKeyPrefix(), String(Date.now()), allowSupersede ? '1' : '0', state, connectionId ?? '', processId ?? '');
889
+ const [rawStatus, rawSupersededConnectionId] = await client.MC_REGISTER(this.clientsKey(), this.nodeSetKey(nodeId), clientId, String(nodeId), encoded.metadataJson, encoded.hasMetadata, this.nodeSetKeyPrefix(), String(Date.now()), allowSupersede ? '1' : '0', state, connectionId, processId ?? '', (0, node_crypto_1.randomUUID)(), String(this.maxClientsPerNode));
890
+ const result = Number(rawStatus);
891
+ if (result === -3)
892
+ throw new Error('Mesh client per-node registration limit reached');
273
893
  if (result === -2) {
274
894
  // Conflict: the owner may have disappeared between the script
275
895
  // result and this follow-up read, so ownerNodeId can be null.
@@ -277,41 +897,52 @@ class MeshClientRedisRegistry {
277
897
  const parsed = existing ? this.tryParse(existing) : undefined;
278
898
  return { status: 'conflict', ownerNodeId: parsed?.nodeId ?? null };
279
899
  }
280
- return { status: 'ok', supersededNodeId: result >= 0 ? result : null };
900
+ const supersededConnectionId = typeof rawSupersededConnectionId === 'string' && rawSupersededConnectionId.length > 0 ? rawSupersededConnectionId : undefined;
901
+ return {
902
+ status: 'ok',
903
+ supersededNodeId: result >= 0 ? result : null,
904
+ ...(supersededConnectionId ? { supersededConnectionId } : {})
905
+ };
281
906
  }
282
- async register(clientId, nodeId, metadata, allowSupersede = true, connectionId, processId) {
907
+ async register(clientId, nodeId, metadata, allowSupersede, connectionId, processId) {
283
908
  return this.registerWithState(clientId, nodeId, metadata, allowSupersede, 'active', connectionId, processId);
284
909
  }
285
- async reserve(clientId, nodeId, metadata, allowSupersede = true, connectionId, processId) {
910
+ async reserve(clientId, nodeId, metadata, allowSupersede, connectionId, processId) {
286
911
  return this.registerWithState(clientId, nodeId, metadata, allowSupersede, 'pending', connectionId, processId);
287
912
  }
288
913
  async activate(clientId, nodeId, metadata, connectionId) {
914
+ this.assertClientId(clientId);
289
915
  const { client } = getClientRedis();
290
916
  const encoded = this.encodeMetadata(metadata);
291
- const result = await client.MC_ACTIVATE(this.clientsKey(), this.nodeSetKey(nodeId), clientId, String(nodeId), encoded.metadataJson, encoded.hasMetadata, connectionId ?? '');
917
+ const result = await client.MC_ACTIVATE(this.clientsKey(), this.nodeSetKey(nodeId), clientId, String(nodeId), encoded.metadataJson, encoded.hasMetadata, connectionId);
292
918
  return result === 1;
293
919
  }
294
920
  async unregister(clientId, nodeId, connectionId) {
921
+ this.assertClientId(clientId);
295
922
  const { client } = getClientRedis();
296
- const result = await client.MC_UNREGISTER(this.clientsKey(), this.nodeSetKey(nodeId), clientId, String(nodeId), connectionId ?? '');
923
+ const result = await client.MC_UNREGISTER(this.clientsKey(), this.nodeSetKey(nodeId), this.claimsKey(), this.claimsIndexKey(), this.nodeClaimsKey(nodeId), clientId, String(nodeId), connectionId);
297
924
  return result === 1;
298
925
  }
299
926
  async updateMetadata(clientId, nodeId, metadata, connectionId) {
927
+ this.assertClientId(clientId);
300
928
  const { client } = getClientRedis();
301
929
  const encoded = this.encodeMetadata(metadata);
302
- const result = await client.MC_UPDATE_METADATA(this.clientsKey(), clientId, String(nodeId), encoded.metadataJson, encoded.hasMetadata, connectionId ?? '');
930
+ const result = await client.MC_UPDATE_METADATA(this.clientsKey(), clientId, String(nodeId), encoded.metadataJson, encoded.hasMetadata, connectionId);
303
931
  return result === 1;
304
932
  }
305
933
  tryParse(raw) {
306
934
  try {
307
935
  const parsed = JSON.parse(raw);
936
+ if (typeof parsed.connectionId !== 'string' || parsed.connectionId.length === 0)
937
+ return undefined;
308
938
  return {
309
939
  nodeId: parsed.nodeId,
310
940
  connectionId: parsed.connectionId,
311
941
  processId: parsed.processId,
312
942
  connectedAt: parsed.connectedAt,
313
943
  metadata: parsed.hasMetadata === false ? undefined : parsed.metadata,
314
- state: parsed.state ?? 'active'
944
+ state: parsed.state ?? 'active',
945
+ claimId: parsed.claimId
315
946
  };
316
947
  }
317
948
  catch {
@@ -331,7 +962,20 @@ class MeshClientRedisRegistry {
331
962
  metadata: parsed.metadata
332
963
  };
333
964
  }
965
+ toClientRecord(clientId, parsed) {
966
+ return {
967
+ clientId,
968
+ nodeId: parsed.nodeId,
969
+ connectionId: parsed.connectionId,
970
+ processId: parsed.processId,
971
+ connectedAt: parsed.connectedAt,
972
+ metadata: parsed.metadata,
973
+ state: parsed.state,
974
+ claimId: parsed.claimId
975
+ };
976
+ }
334
977
  async getClient(clientId) {
978
+ this.assertClientId(clientId);
335
979
  const { client } = getClientRedis();
336
980
  const raw = await client.hget(this.clientsKey(), clientId);
337
981
  if (!raw)
@@ -341,45 +985,109 @@ class MeshClientRedisRegistry {
341
985
  return undefined;
342
986
  return this.toRegisteredClient(clientId, parsed);
343
987
  }
344
- async listClients() {
988
+ async getClientIncludingPending(clientId) {
989
+ this.assertClientId(clientId);
345
990
  const { client } = getClientRedis();
346
- const all = await client.hgetall(this.clientsKey());
991
+ const raw = await client.hget(this.clientsKey(), clientId);
992
+ if (!raw)
993
+ return undefined;
994
+ const parsed = this.tryParse(raw);
995
+ return parsed ? this.toClientRecord(clientId, parsed) : undefined;
996
+ }
997
+ async listClients() {
347
998
  const results = [];
348
- for (const [clientId, raw] of Object.entries(all)) {
349
- const parsed = this.tryParse(raw);
350
- if (parsed) {
351
- const registered = this.toRegisteredClient(clientId, parsed);
352
- if (registered) {
353
- results.push(registered);
354
- }
999
+ const seen = new Set();
1000
+ let cursor = '0';
1001
+ do {
1002
+ const page = await this.listClientsPage(cursor);
1003
+ cursor = page.cursor;
1004
+ for (const registered of page.clients) {
1005
+ if (seen.has(registered.clientId))
1006
+ continue;
1007
+ seen.add(registered.clientId);
1008
+ results.push(registered);
355
1009
  }
356
- }
1010
+ } while (cursor !== undefined);
357
1011
  return results;
358
1012
  }
359
1013
  async listClientsForNode(nodeId) {
1014
+ const results = [];
1015
+ const seen = new Set();
1016
+ let cursor = '0';
1017
+ do {
1018
+ const page = await this.listClientsForNodePage(nodeId, cursor);
1019
+ cursor = page.cursor;
1020
+ for (const registered of page.clients) {
1021
+ if (seen.has(registered.clientId))
1022
+ continue;
1023
+ seen.add(registered.clientId);
1024
+ results.push(registered);
1025
+ }
1026
+ } while (cursor !== undefined);
1027
+ return results;
1028
+ }
1029
+ async listClientsPage(cursor = '0') {
1030
+ assertRedisCursor(cursor);
1031
+ const { client } = getClientRedis();
1032
+ const [nextCursor, entries] = await client.hscan(this.clientsKey(), cursor, 'COUNT', this.scanBatchSize);
1033
+ const clients = [];
1034
+ for (let i = 0; i < entries.length; i += 2) {
1035
+ const parsed = this.tryParse(entries[i + 1]);
1036
+ if (!parsed)
1037
+ continue;
1038
+ const registered = this.toRegisteredClient(entries[i], parsed);
1039
+ if (registered)
1040
+ clients.push(registered);
1041
+ }
1042
+ return { clients, ...(nextCursor === '0' ? {} : { cursor: nextCursor }) };
1043
+ }
1044
+ async listClientsForNodePage(nodeId, cursor = '0') {
1045
+ assertRedisCursor(cursor);
360
1046
  const { client } = getClientRedis();
361
- const clientIds = await client.smembers(this.nodeSetKey(nodeId));
362
- if (clientIds.length === 0)
363
- return [];
1047
+ const [nextCursor, clientIds] = await client.sscan(this.nodeSetKey(nodeId), cursor, 'COUNT', this.scanBatchSize);
1048
+ if (!clientIds.length) {
1049
+ return { clients: [], ...(nextCursor === '0' ? {} : { cursor: nextCursor }) };
1050
+ }
364
1051
  const values = await client.hmget(this.clientsKey(), ...clientIds);
365
- const results = [];
1052
+ const clients = [];
366
1053
  for (let i = 0; i < clientIds.length; i++) {
367
1054
  const raw = values[i];
368
- if (raw) {
369
- const parsed = this.tryParse(raw);
370
- if (parsed && parsed.nodeId === nodeId) {
371
- const registered = this.toRegisteredClient(clientIds[i], parsed);
372
- if (registered) {
373
- results.push(registered);
374
- }
375
- }
376
- }
1055
+ if (!raw)
1056
+ continue;
1057
+ const parsed = this.tryParse(raw);
1058
+ if (!parsed || parsed.nodeId !== nodeId)
1059
+ continue;
1060
+ const registered = this.toRegisteredClient(clientIds[i], parsed);
1061
+ if (registered)
1062
+ clients.push(registered);
377
1063
  }
378
- return results;
1064
+ return { clients, ...(nextCursor === '0' ? {} : { cursor: nextCursor }) };
379
1065
  }
380
1066
  async cleanupNode(nodeId) {
381
1067
  const { client } = getClientRedis();
382
- const result = await client.MC_CLEANUP_NODE(this.clientsKey(), this.nodeSetKey(nodeId), String(nodeId));
1068
+ const removed = [];
1069
+ let done = false;
1070
+ while (!done) {
1071
+ const result = await client.MC_CLEANUP_NODE(this.clientsKey(), this.nodeSetKey(nodeId), this.nodeClaimsKey(nodeId), this.claimsKey(), this.claimsIndexKey(), String(nodeId), String(this.cleanupBatchSize));
1072
+ done = result.shift() === '1';
1073
+ removed.push(...this.decodeRemovedRecords(result));
1074
+ }
1075
+ return removed;
1076
+ }
1077
+ async cleanupNodeAndEnqueueOrphaned(nodeId) {
1078
+ const { client } = getClientRedis();
1079
+ const removed = [];
1080
+ let done = false;
1081
+ while (!done) {
1082
+ const result = await client.MC_CLEANUP_NODE_AND_ORPHAN(this.clientsKey(), this.nodeSetKey(nodeId), this.nodeClaimsKey(nodeId), this.claimsKey(), this.claimsIndexKey(), this.orphanedKey(), this.orphanedIndexKey(), this.orphanedAccountingKey(), String(nodeId), (0, node_crypto_1.randomUUID)(), String(this.cleanupBatchSize), String(this.maxOrphanItems), String(this.maxOrphanBytes));
1083
+ if (result[0] === 'FULL')
1084
+ throw new Error('Mesh durable orphan queue is full');
1085
+ done = result.shift() === '1';
1086
+ removed.push(...this.decodeRemovedRecords(result));
1087
+ }
1088
+ return removed;
1089
+ }
1090
+ decodeRemovedRecords(result) {
383
1091
  // Result is alternating [json, clientId, json, clientId, ...]
384
1092
  const removed = [];
385
1093
  for (let i = 0; i < result.length; i += 2) {
@@ -401,9 +1109,102 @@ class MeshClientRedisRegistry {
401
1109
  const { client } = getClientRedis();
402
1110
  await client.MC_REFRESH_NODE(this.clientsKey(), this.nodeSetKey(nodeId), String(KEY_TTL_SECONDS));
403
1111
  }
404
- static __tsfType = _MeshClientRedisRegistryMetadata_1 = _a.decodeCompactMetadataV1("[1,{\"kind\":16,\"name\":\"MeshClientRedisRegistry\",\"typeName\":\"MeshClientRedisRegistry\",\"classType\":{\"$tsf\":0},\"properties\":[],\"methods\":[{\"name\":\"register\",\"parameters\":[{\"name\":\"clientId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false},{\"name\":\"nodeId\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false},{\"name\":\"metadata\",\"type\":{\"kind\":16,\"typeName\":\"TMeta\",\"classType\":{\"$tsf\":1}},\"optional\":false,\"default\":false},{\"name\":\"allowSupersede\",\"type\":{\"$tsfType\":2},\"optional\":true,\"default\":true},{\"name\":\"connectionId\",\"type\":{\"$tsfType\":0},\"optional\":true,\"default\":false},{\"name\":\"processId\",\"type\":{\"$tsfType\":0},\"optional\":true,\"default\":false}],\"returnType\":{\"$tsfType\":3}},{\"name\":\"reserve\",\"parameters\":[{\"name\":\"clientId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false},{\"name\":\"nodeId\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false},{\"name\":\"metadata\",\"type\":{\"kind\":16,\"typeName\":\"TMeta\",\"classType\":{\"$tsf\":1}},\"optional\":false,\"default\":false},{\"name\":\"allowSupersede\",\"type\":{\"$tsfType\":2},\"optional\":true,\"default\":true},{\"name\":\"connectionId\",\"type\":{\"$tsfType\":0},\"optional\":true,\"default\":false},{\"name\":\"processId\",\"type\":{\"$tsfType\":0},\"optional\":true,\"default\":false}],\"returnType\":{\"$tsfType\":3}},{\"name\":\"activate\",\"parameters\":[{\"name\":\"clientId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false},{\"name\":\"nodeId\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false},{\"name\":\"metadata\",\"type\":{\"kind\":16,\"typeName\":\"TMeta\",\"classType\":{\"$tsf\":1}},\"optional\":false,\"default\":false},{\"name\":\"connectionId\",\"type\":{\"$tsfType\":0},\"optional\":true,\"default\":false}],\"returnType\":{\"$tsfType\":4}},{\"name\":\"unregister\",\"parameters\":[{\"name\":\"clientId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false},{\"name\":\"nodeId\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false},{\"name\":\"connectionId\",\"type\":{\"$tsfType\":0},\"optional\":true,\"default\":false}],\"returnType\":{\"$tsfType\":4}},{\"name\":\"updateMetadata\",\"parameters\":[{\"name\":\"clientId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false},{\"name\":\"nodeId\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false},{\"name\":\"metadata\",\"type\":{\"kind\":16,\"typeName\":\"TMeta\",\"classType\":{\"$tsf\":1}},\"optional\":false,\"default\":false},{\"name\":\"connectionId\",\"type\":{\"$tsfType\":0},\"optional\":true,\"default\":false}],\"returnType\":{\"$tsfType\":4}},{\"name\":\"getClient\",\"parameters\":[{\"name\":\"clientId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false}],\"returnType\":{\"kind\":22,\"type\":{\"kind\":12,\"types\":[{\"kind\":18,\"typeName\":\"RegisteredClient\",\"types\":[{\"kind\":20,\"name\":\"clientId\",\"type\":{\"kind\":6},\"optional\":false},{\"kind\":20,\"name\":\"nodeId\",\"type\":{\"kind\":7},\"optional\":false},{\"kind\":20,\"name\":\"connectionId\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"processId\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"connectedAt\",\"type\":{\"kind\":7},\"optional\":false},{\"kind\":20,\"name\":\"metadata\",\"type\":{\"kind\":16,\"typeName\":\"TMeta\",\"classType\":{\"$tsf\":1}},\"optional\":false}]},{\"kind\":4}]}}},{\"name\":\"listClients\",\"parameters\":[],\"returnType\":{\"kind\":22,\"type\":{\"kind\":14,\"type\":{\"kind\":18,\"typeName\":\"RegisteredClient\",\"types\":[{\"kind\":20,\"name\":\"clientId\",\"type\":{\"kind\":6},\"optional\":false},{\"kind\":20,\"name\":\"nodeId\",\"type\":{\"kind\":7},\"optional\":false},{\"kind\":20,\"name\":\"connectionId\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"processId\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"connectedAt\",\"type\":{\"kind\":7},\"optional\":false},{\"kind\":20,\"name\":\"metadata\",\"type\":{\"kind\":16,\"typeName\":\"TMeta\",\"classType\":{\"$tsf\":1}},\"optional\":false}]}}}},{\"name\":\"listClientsForNode\",\"parameters\":[{\"name\":\"nodeId\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false}],\"returnType\":{\"kind\":22,\"type\":{\"kind\":14,\"type\":{\"kind\":18,\"typeName\":\"RegisteredClient\",\"types\":[{\"kind\":20,\"name\":\"clientId\",\"type\":{\"kind\":6},\"optional\":false},{\"kind\":20,\"name\":\"nodeId\",\"type\":{\"kind\":7},\"optional\":false},{\"kind\":20,\"name\":\"connectionId\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"processId\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"connectedAt\",\"type\":{\"kind\":7},\"optional\":false},{\"kind\":20,\"name\":\"metadata\",\"type\":{\"kind\":16,\"typeName\":\"TMeta\",\"classType\":{\"$tsf\":1}},\"optional\":false}]}}}},{\"name\":\"cleanupNode\",\"parameters\":[{\"name\":\"nodeId\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false}],\"returnType\":{\"kind\":22,\"type\":{\"kind\":14,\"type\":{\"kind\":18,\"typeName\":\"RegisteredClient\",\"types\":[{\"kind\":20,\"name\":\"clientId\",\"type\":{\"kind\":6},\"optional\":false},{\"kind\":20,\"name\":\"nodeId\",\"type\":{\"kind\":7},\"optional\":false},{\"kind\":20,\"name\":\"connectionId\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"processId\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"connectedAt\",\"type\":{\"kind\":7},\"optional\":false},{\"kind\":20,\"name\":\"metadata\",\"type\":{\"kind\":16,\"typeName\":\"TMeta\",\"classType\":{\"$tsf\":1}},\"optional\":false}]}}}},{\"name\":\"refreshNode\",\"parameters\":[{\"name\":\"nodeId\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false}],\"returnType\":{\"$tsfType\":5}}],\"hasConstructor\":true,\"constructorParameters\":[{\"name\":\"key\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false}]}]", [() => MeshClientRedisRegistry, () => (typeof TMeta !== "undefined" ? TMeta : (typeof exports !== "undefined" ? exports.TMeta : undefined))], __tsf_metadata_type);
1112
+ async claim(clientId, nodeId, metadata, state, allowSupersede, connectionId, processId, operationId = (0, node_crypto_1.randomUUID)()) {
1113
+ this.assertClientId(clientId);
1114
+ if (Buffer.byteLength(operationId) < 16 || Buffer.byteLength(operationId) > 256) {
1115
+ throw new Error('Mesh client claim operation ID is outside the configured range');
1116
+ }
1117
+ const { client } = getClientRedis();
1118
+ const encoded = this.encodeMetadata(metadata);
1119
+ const requestFingerprint = (0, node_crypto_1.createHash)('sha256')
1120
+ .update(JSON.stringify([nodeId, encoded.metadataJson, encoded.hasMetadata, state, allowSupersede, connectionId, processId ?? '']))
1121
+ .digest('hex');
1122
+ const [status, value, rawPrevious] = await client.MC_CLAIM(this.clientsKey(), this.claimsKey(), this.claimsIndexKey(), this.nodeClaimsKey(nodeId), clientId, String(nodeId), encoded.metadataJson, encoded.hasMetadata, state, allowSupersede ? '1' : '0', connectionId, processId ?? '', (0, node_crypto_1.randomUUID)(), String(Date.now()), this.nodeSetKeyPrefix(), String(this.maxClientsPerNode), operationId, requestFingerprint);
1123
+ if (status === 'capacity')
1124
+ throw new Error('Too many pending mesh client claims for one node');
1125
+ if (status === 'node-capacity')
1126
+ throw new Error('Mesh client per-node registration limit reached');
1127
+ if (status !== 'ok') {
1128
+ const parsed = value ? this.tryParse(value) : undefined;
1129
+ return { status: 'conflict', ownerNodeId: parsed?.nodeId ?? null };
1130
+ }
1131
+ const parsed = rawPrevious ? this.tryParse(rawPrevious) : undefined;
1132
+ const previous = parsed ? this.toClientRecord(clientId, parsed) : undefined;
1133
+ return { status: 'ok', claimId: value, ...(previous ? { previous } : {}) };
1134
+ }
1135
+ async commitClaim(clientId, nodeId, claimId) {
1136
+ const { client } = getClientRedis();
1137
+ const result = await client.MC_COMMIT_CLAIM(this.clientsKey(), this.claimsKey(), this.nodeSetKey(nodeId), this.claimsIndexKey(), this.nodeClaimsKey(nodeId), clientId, String(nodeId), claimId, this.nodeSetKeyPrefix(), String(this.maxClientsPerNode));
1138
+ return result === 1 ? true : result === 2 ? 'previous-changed' : false;
1139
+ }
1140
+ async removeClaimPrevious(clientId, nodeId, claimId) {
1141
+ const { client } = getClientRedis();
1142
+ return ((await client.MC_REMOVE_CLAIM_PREVIOUS(this.clientsKey(), this.claimsKey(), clientId, String(nodeId), claimId, this.nodeSetKeyPrefix())) === 1);
1143
+ }
1144
+ async abortClaim(clientId, nodeId, claimId) {
1145
+ const { client } = getClientRedis();
1146
+ return ((await client.MC_ABORT_CLAIM(this.claimsKey(), this.claimsIndexKey(), this.nodeClaimsKey(nodeId), clientId, String(nodeId), claimId)) ===
1147
+ 1);
1148
+ }
1149
+ async removeClaimResult(clientId, nodeId, claimId) {
1150
+ const { client } = getClientRedis();
1151
+ return ((await client.MC_REMOVE_CLAIM_RESULT(this.clientsKey(), this.nodeSetKey(nodeId), this.claimsKey(), this.claimsIndexKey(), this.nodeClaimsKey(nodeId), clientId, String(nodeId), claimId)) === 1);
1152
+ }
1153
+ async enqueueOrphaned(nodeId, clients) {
1154
+ if (!clients.length)
1155
+ return;
1156
+ const { client } = getClientRedis();
1157
+ for (let offset = 0; offset < clients.length; offset += this.cleanupBatchSize) {
1158
+ const admitted = await client.MC_ENQUEUE_ORPHAN(this.orphanedKey(), this.orphanedIndexKey(), this.orphanedAccountingKey(), (0, node_crypto_1.randomUUID)(), String(nodeId), JSON.stringify(clients.slice(offset, offset + this.cleanupBatchSize)), String(this.maxOrphanItems), String(this.maxOrphanBytes));
1159
+ if (admitted !== 1)
1160
+ throw new Error('Mesh durable orphan queue is full');
1161
+ }
1162
+ }
1163
+ async claimOrphaned(_claimerId) {
1164
+ const { client } = getClientRedis();
1165
+ const token = (0, node_crypto_1.randomUUID)();
1166
+ const [id, raw] = await client.MC_CLAIM_ORPHAN(this.orphanedKey(), this.orphanedIndexKey(), this.orphanedAccountingKey(), token);
1167
+ if (!id || !raw)
1168
+ return undefined;
1169
+ const item = JSON.parse(raw);
1170
+ const clients = item.clients ?? this.decodeRemovedRecords(item.records ?? []);
1171
+ return { id, nodeId: item.nodeId, clients, claimToken: token };
1172
+ }
1173
+ async ackOrphaned(id, claimToken) {
1174
+ const { client } = getClientRedis();
1175
+ return (await client.MC_ACK_ORPHAN(this.orphanedKey(), this.orphanedIndexKey(), this.orphanedAccountingKey(), id, claimToken)) === 1;
1176
+ }
1177
+ async nackOrphaned(id, claimToken) {
1178
+ const { client } = getClientRedis();
1179
+ return (await client.MC_NACK_ORPHAN(this.orphanedKey(), this.orphanedIndexKey(), this.orphanedAccountingKey(), id, claimToken)) === 1;
1180
+ }
1181
+ async consumeAuthNonce(principal, nonce, expiresAt) {
1182
+ if (!principal || !nonce || !Number.isSafeInteger(expiresAt))
1183
+ return false;
1184
+ const { client } = getClientRedis();
1185
+ const principalHash = (0, node_crypto_1.createHash)('sha256').update(principal).digest('hex');
1186
+ return ((await client.MC_CONSUME_AUTH_NONCE(this.authNonceKey(principal), this.authNoncePrincipalsKey(), nonce, String(expiresAt), principalHash, String(this.maxAuthReplayPrincipals), String(this.maxAuthNoncesPerPrincipal))) === 1);
1187
+ }
1188
+ assertClientId(clientId) {
1189
+ if (!clientId || Buffer.byteLength(clientId) > this.maxClientIdBytes) {
1190
+ throw new Error(`Mesh client ID must contain between 1 and ${this.maxClientIdBytes} UTF-8 bytes`);
1191
+ }
1192
+ }
1193
+ static __tsfType = _MeshClientRedisRegistryMetadata_1 = _a.decodeCompactMetadataV1("[1,{\"kind\":16,\"name\":\"MeshClientRedisRegistry\",\"typeName\":\"MeshClientRedisRegistry\",\"classType\":{\"$tsf\":0},\"properties\":[],\"methods\":[{\"name\":\"register\",\"parameters\":[{\"name\":\"clientId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false},{\"name\":\"nodeId\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false},{\"name\":\"metadata\",\"type\":{\"kind\":16,\"typeName\":\"TMeta\",\"classType\":{\"$tsf\":1}},\"optional\":false,\"default\":false},{\"name\":\"allowSupersede\",\"type\":{\"$tsfType\":2},\"optional\":false,\"default\":false},{\"name\":\"connectionId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false},{\"name\":\"processId\",\"type\":{\"$tsfType\":0},\"optional\":true,\"default\":false}],\"returnType\":{\"$tsfType\":3}},{\"name\":\"reserve\",\"parameters\":[{\"name\":\"clientId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false},{\"name\":\"nodeId\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false},{\"name\":\"metadata\",\"type\":{\"kind\":16,\"typeName\":\"TMeta\",\"classType\":{\"$tsf\":1}},\"optional\":false,\"default\":false},{\"name\":\"allowSupersede\",\"type\":{\"$tsfType\":2},\"optional\":false,\"default\":false},{\"name\":\"connectionId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false},{\"name\":\"processId\",\"type\":{\"$tsfType\":0},\"optional\":true,\"default\":false}],\"returnType\":{\"$tsfType\":3}},{\"name\":\"activate\",\"parameters\":[{\"name\":\"clientId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false},{\"name\":\"nodeId\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false},{\"name\":\"metadata\",\"type\":{\"kind\":16,\"typeName\":\"TMeta\",\"classType\":{\"$tsf\":1}},\"optional\":false,\"default\":false},{\"name\":\"connectionId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false}],\"returnType\":{\"$tsfType\":4}},{\"name\":\"unregister\",\"parameters\":[{\"name\":\"clientId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false},{\"name\":\"nodeId\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false},{\"name\":\"connectionId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false}],\"returnType\":{\"$tsfType\":4}},{\"name\":\"updateMetadata\",\"parameters\":[{\"name\":\"clientId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false},{\"name\":\"nodeId\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false},{\"name\":\"metadata\",\"type\":{\"kind\":16,\"typeName\":\"TMeta\",\"classType\":{\"$tsf\":1}},\"optional\":false,\"default\":false},{\"name\":\"connectionId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false}],\"returnType\":{\"$tsfType\":4}},{\"name\":\"getClient\",\"parameters\":[{\"name\":\"clientId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false}],\"returnType\":{\"kind\":22,\"type\":{\"kind\":12,\"types\":[{\"kind\":18,\"typeName\":\"RegisteredClient\",\"types\":[{\"kind\":20,\"name\":\"clientId\",\"type\":{\"kind\":6},\"optional\":false},{\"kind\":20,\"name\":\"nodeId\",\"type\":{\"kind\":7},\"optional\":false},{\"kind\":20,\"name\":\"connectionId\",\"type\":{\"kind\":6},\"optional\":false},{\"kind\":20,\"name\":\"processId\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"connectedAt\",\"type\":{\"kind\":7},\"optional\":false},{\"kind\":20,\"name\":\"metadata\",\"type\":{\"kind\":16,\"typeName\":\"TMeta\",\"classType\":{\"$tsf\":1}},\"optional\":false}]},{\"kind\":4}]}}},{\"name\":\"getClientIncludingPending\",\"parameters\":[{\"name\":\"clientId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false}],\"returnType\":{\"kind\":22,\"type\":{\"kind\":12,\"types\":[{\"kind\":18,\"typeName\":\"MeshClientRecord\",\"types\":[{\"kind\":20,\"name\":\"clientId\",\"type\":{\"kind\":6},\"optional\":false},{\"kind\":20,\"name\":\"nodeId\",\"type\":{\"kind\":7},\"optional\":false},{\"kind\":20,\"name\":\"connectionId\",\"type\":{\"kind\":6},\"optional\":false},{\"kind\":20,\"name\":\"processId\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"connectedAt\",\"type\":{\"kind\":7},\"optional\":false},{\"kind\":20,\"name\":\"metadata\",\"type\":{\"kind\":16,\"typeName\":\"TMeta\",\"classType\":{\"$tsf\":1}},\"optional\":false},{\"kind\":20,\"name\":\"state\",\"type\":{\"kind\":12,\"types\":[{\"kind\":10,\"literal\":\"active\"},{\"kind\":10,\"literal\":\"pending\"}],\"typeName\":\"MeshClientRegistrationState\"},\"optional\":false},{\"kind\":20,\"name\":\"claimId\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true}]},{\"kind\":4}]}}},{\"name\":\"listClients\",\"parameters\":[],\"returnType\":{\"kind\":22,\"type\":{\"kind\":14,\"type\":{\"kind\":18,\"typeName\":\"RegisteredClient\",\"types\":[{\"kind\":20,\"name\":\"clientId\",\"type\":{\"kind\":6},\"optional\":false},{\"kind\":20,\"name\":\"nodeId\",\"type\":{\"kind\":7},\"optional\":false},{\"kind\":20,\"name\":\"connectionId\",\"type\":{\"kind\":6},\"optional\":false},{\"kind\":20,\"name\":\"processId\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"connectedAt\",\"type\":{\"kind\":7},\"optional\":false},{\"kind\":20,\"name\":\"metadata\",\"type\":{\"kind\":16,\"typeName\":\"TMeta\",\"classType\":{\"$tsf\":1}},\"optional\":false}]}}}},{\"name\":\"listClientsForNode\",\"parameters\":[{\"name\":\"nodeId\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false}],\"returnType\":{\"kind\":22,\"type\":{\"kind\":14,\"type\":{\"kind\":18,\"typeName\":\"RegisteredClient\",\"types\":[{\"kind\":20,\"name\":\"clientId\",\"type\":{\"kind\":6},\"optional\":false},{\"kind\":20,\"name\":\"nodeId\",\"type\":{\"kind\":7},\"optional\":false},{\"kind\":20,\"name\":\"connectionId\",\"type\":{\"kind\":6},\"optional\":false},{\"kind\":20,\"name\":\"processId\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"connectedAt\",\"type\":{\"kind\":7},\"optional\":false},{\"kind\":20,\"name\":\"metadata\",\"type\":{\"kind\":16,\"typeName\":\"TMeta\",\"classType\":{\"$tsf\":1}},\"optional\":false}]}}}},{\"name\":\"listClientsPage\",\"parameters\":[{\"name\":\"cursor\",\"type\":{\"$tsfType\":5},\"optional\":true,\"default\":true}],\"returnType\":{\"kind\":22,\"type\":{\"kind\":16,\"typeName\":\"import('./types').MeshClientListPage\",\"classType\":{\"$tsf\":2},\"typeArguments\":[{\"kind\":16,\"typeName\":\"TMeta\",\"classType\":{\"$tsf\":1}}]}}},{\"name\":\"listClientsForNodePage\",\"parameters\":[{\"name\":\"nodeId\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false},{\"name\":\"cursor\",\"type\":{\"$tsfType\":5},\"optional\":true,\"default\":true}],\"returnType\":{\"kind\":22,\"type\":{\"kind\":16,\"typeName\":\"import('./types').MeshClientListPage\",\"classType\":{\"$tsf\":2},\"typeArguments\":[{\"kind\":16,\"typeName\":\"TMeta\",\"classType\":{\"$tsf\":1}}]}}},{\"name\":\"cleanupNode\",\"parameters\":[{\"name\":\"nodeId\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false}],\"returnType\":{\"kind\":22,\"type\":{\"kind\":14,\"type\":{\"kind\":18,\"typeName\":\"RegisteredClient\",\"types\":[{\"kind\":20,\"name\":\"clientId\",\"type\":{\"kind\":6},\"optional\":false},{\"kind\":20,\"name\":\"nodeId\",\"type\":{\"kind\":7},\"optional\":false},{\"kind\":20,\"name\":\"connectionId\",\"type\":{\"kind\":6},\"optional\":false},{\"kind\":20,\"name\":\"processId\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"connectedAt\",\"type\":{\"kind\":7},\"optional\":false},{\"kind\":20,\"name\":\"metadata\",\"type\":{\"kind\":16,\"typeName\":\"TMeta\",\"classType\":{\"$tsf\":1}},\"optional\":false}]}}}},{\"name\":\"cleanupNodeAndEnqueueOrphaned\",\"parameters\":[{\"name\":\"nodeId\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false}],\"returnType\":{\"kind\":22,\"type\":{\"kind\":14,\"type\":{\"kind\":18,\"typeName\":\"RegisteredClient\",\"types\":[{\"kind\":20,\"name\":\"clientId\",\"type\":{\"kind\":6},\"optional\":false},{\"kind\":20,\"name\":\"nodeId\",\"type\":{\"kind\":7},\"optional\":false},{\"kind\":20,\"name\":\"connectionId\",\"type\":{\"kind\":6},\"optional\":false},{\"kind\":20,\"name\":\"processId\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"connectedAt\",\"type\":{\"kind\":7},\"optional\":false},{\"kind\":20,\"name\":\"metadata\",\"type\":{\"kind\":16,\"typeName\":\"TMeta\",\"classType\":{\"$tsf\":1}},\"optional\":false}]}}}},{\"name\":\"refreshNode\",\"parameters\":[{\"name\":\"nodeId\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false}],\"returnType\":{\"$tsfType\":6}},{\"name\":\"claim\",\"parameters\":[{\"name\":\"clientId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false},{\"name\":\"nodeId\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false},{\"name\":\"metadata\",\"type\":{\"kind\":16,\"typeName\":\"TMeta\",\"classType\":{\"$tsf\":1}},\"optional\":false,\"default\":false},{\"name\":\"state\",\"type\":{\"$tsfType\":7},\"optional\":false,\"default\":false},{\"name\":\"allowSupersede\",\"type\":{\"$tsfType\":2},\"optional\":false,\"default\":false},{\"name\":\"connectionId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false},{\"name\":\"processId\",\"type\":{\"$tsfType\":0},\"optional\":true,\"default\":false},{\"name\":\"operationId\",\"type\":{\"$tsfType\":5},\"optional\":true,\"default\":true}],\"returnType\":{\"kind\":22,\"type\":{\"kind\":16,\"typeName\":\"import('./types').MeshClientClaim\",\"classType\":{\"$tsf\":3},\"typeArguments\":[{\"kind\":16,\"typeName\":\"TMeta\",\"classType\":{\"$tsf\":1}}]}}},{\"name\":\"commitClaim\",\"parameters\":[{\"name\":\"clientId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false},{\"name\":\"nodeId\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false},{\"name\":\"claimId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false}],\"returnType\":{\"$tsfType\":8}},{\"name\":\"removeClaimPrevious\",\"parameters\":[{\"name\":\"clientId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false},{\"name\":\"nodeId\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false},{\"name\":\"claimId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false}],\"returnType\":{\"$tsfType\":4}},{\"name\":\"abortClaim\",\"parameters\":[{\"name\":\"clientId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false},{\"name\":\"nodeId\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false},{\"name\":\"claimId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false}],\"returnType\":{\"$tsfType\":4}},{\"name\":\"removeClaimResult\",\"parameters\":[{\"name\":\"clientId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false},{\"name\":\"nodeId\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false},{\"name\":\"claimId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false}],\"returnType\":{\"$tsfType\":4}},{\"name\":\"enqueueOrphaned\",\"parameters\":[{\"name\":\"nodeId\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false},{\"name\":\"clients\",\"type\":{\"kind\":14,\"type\":{\"kind\":18,\"typeName\":\"RegisteredClient\",\"types\":[{\"kind\":20,\"name\":\"clientId\",\"type\":{\"kind\":6},\"optional\":false},{\"kind\":20,\"name\":\"nodeId\",\"type\":{\"kind\":7},\"optional\":false},{\"kind\":20,\"name\":\"connectionId\",\"type\":{\"kind\":6},\"optional\":false},{\"kind\":20,\"name\":\"processId\",\"type\":{\"kind\":12,\"types\":[{\"kind\":6},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"connectedAt\",\"type\":{\"kind\":7},\"optional\":false},{\"kind\":20,\"name\":\"metadata\",\"type\":{\"kind\":16,\"typeName\":\"TMeta\",\"classType\":{\"$tsf\":1}},\"optional\":false}]}},\"optional\":false,\"default\":false}],\"returnType\":{\"$tsfType\":6}},{\"name\":\"claimOrphaned\",\"parameters\":[{\"name\":\"_claimerId\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false}],\"returnType\":{\"kind\":22,\"type\":{\"kind\":12,\"types\":[{\"kind\":16,\"typeName\":\"import('./types').OrphanedClientDelivery\",\"classType\":{\"$tsf\":4},\"typeArguments\":[{\"kind\":16,\"typeName\":\"TMeta\",\"classType\":{\"$tsf\":1}}]},{\"kind\":4}]}}},{\"name\":\"ackOrphaned\",\"parameters\":[{\"name\":\"id\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false},{\"name\":\"claimToken\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false}],\"returnType\":{\"$tsfType\":4}},{\"name\":\"nackOrphaned\",\"parameters\":[{\"name\":\"id\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false},{\"name\":\"claimToken\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false}],\"returnType\":{\"$tsfType\":4}},{\"name\":\"consumeAuthNonce\",\"parameters\":[{\"name\":\"principal\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false},{\"name\":\"nonce\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false},{\"name\":\"expiresAt\",\"type\":{\"$tsfType\":1},\"optional\":false,\"default\":false}],\"returnType\":{\"$tsfType\":4}}],\"hasConstructor\":true,\"constructorParameters\":[{\"name\":\"key\",\"type\":{\"$tsfType\":0},\"optional\":false,\"default\":false},{\"name\":\"options\",\"type\":{\"$tsfType\":9},\"optional\":true,\"default\":true}]}]", [() => MeshClientRedisRegistry, () => (typeof TMeta !== "undefined" ? TMeta : (typeof exports !== "undefined" ? exports.TMeta : undefined)), () => Promise.resolve().then(() => tslib_1.__importStar(require('./types'))).MeshClientListPage, () => Promise.resolve().then(() => tslib_1.__importStar(require('./types'))).MeshClientClaim, () => Promise.resolve().then(() => tslib_1.__importStar(require('./types'))).OrphanedClientDelivery], __tsf_metadata_type);
405
1194
  }
406
1195
  exports.MeshClientRedisRegistry = MeshClientRedisRegistry;
407
1196
  _MeshClientRedisRegistryMetadata_1.classType = MeshClientRedisRegistry;
408
1197
  MeshClientRedisRegistry.__tsfType = _MeshClientRedisRegistryMetadata_1;
1198
+ function configuredLimit(value, fallback, name) {
1199
+ const resolved = value ?? fallback;
1200
+ if (!Number.isSafeInteger(resolved) || resolved < 1) {
1201
+ throw new Error(`Mesh client registry ${name} must be a positive integer`);
1202
+ }
1203
+ return resolved;
1204
+ }
1205
+ function assertRedisCursor(cursor) {
1206
+ if (!/^\d+$/.test(cursor))
1207
+ throw new Error('Mesh client registry cursor is invalid');
1208
+ }
1209
+ exports.__tsfTypeAliases = JSON.parse("[1,{\"MeshClientRedisRegistryOptions\":{\"kind\":18,\"typeName\":\"MeshClientRedisRegistryOptions\",\"types\":[{\"kind\":20,\"name\":\"maxClientIdBytes\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"maxMetadataBytes\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"maxClientsPerNode\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"scanBatchSize\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"cleanupBatchSize\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"maxAuthReplayPrincipals\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"maxAuthNoncesPerPrincipal\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"maxOrphanItems\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true},{\"kind\":20,\"name\":\"maxOrphanBytes\",\"type\":{\"kind\":12,\"types\":[{\"kind\":7},{\"kind\":4}]},\"optional\":true}]}}]")[1];
409
1210
  //# sourceMappingURL=mesh-client-redis-registry.js.map