@mark1russell7/service 0.8.18 → 0.8.20

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 (332) hide show
  1. package/README.md +19 -0
  2. package/build/backoff.d.ts +44 -2
  3. package/build/{builder-zO48Vgoj.d.ts → builder.d.ts} +14 -101
  4. package/build/builder.js +499 -0
  5. package/build/builder.js.map +1 -0
  6. package/build/{call-context-DDhcVvn5.d.ts → call-context.d.ts} +3 -4
  7. package/build/channel.d.ts +1 -1
  8. package/build/{core-BSzt4RI2.d.ts → client/core.d.ts} +32 -61
  9. package/build/{machine-BhVeHr_m.js → client/core.js} +4 -153
  10. package/build/client/core.js.map +1 -0
  11. package/build/{dial-ChwIcvd4.d.ts → client/dial.d.ts} +3 -4
  12. package/build/client/dial.js +52 -0
  13. package/build/client/dial.js.map +1 -0
  14. package/build/client/machine.js +29 -0
  15. package/build/client/machine.js.map +1 -0
  16. package/build/client/meets.d.ts +35 -0
  17. package/build/client/meets.js +78 -0
  18. package/build/client/meets.js.map +1 -0
  19. package/build/clock.d.ts +1 -1
  20. package/build/conformance.d.ts +122 -0
  21. package/build/conformance.js +470 -0
  22. package/build/conformance.js.map +1 -0
  23. package/build/contract.d.ts +28 -0
  24. package/build/contract.js +184 -0
  25. package/build/contract.js.map +1 -0
  26. package/build/description.d.ts +161 -0
  27. package/build/description.js +11 -0
  28. package/build/description.js.map +1 -0
  29. package/build/drains.js +35 -0
  30. package/build/drains.js.map +1 -0
  31. package/build/events.d.ts +25 -0
  32. package/build/fakes.d.ts +43 -0
  33. package/build/fakes.js +93 -0
  34. package/build/fakes.js.map +1 -0
  35. package/build/grpc/client.d.ts +153 -0
  36. package/build/grpc/client.js +474 -0
  37. package/build/grpc/client.js.map +1 -0
  38. package/build/grpc/connection.d.ts +97 -0
  39. package/build/grpc/connection.js +59 -0
  40. package/build/grpc/connection.js.map +1 -0
  41. package/build/grpc/machine.d.ts +12 -0
  42. package/build/grpc/machine.js +149 -0
  43. package/build/grpc/machine.js.map +1 -0
  44. package/build/grpc/meets.d.ts +14 -0
  45. package/build/grpc/meets.js +105 -0
  46. package/build/grpc/meets.js.map +1 -0
  47. package/build/grpc/starting.d.ts +33 -0
  48. package/build/grpc/starting.js +89 -0
  49. package/build/grpc/starting.js.map +1 -0
  50. package/build/grpc.d.ts +9 -303
  51. package/build/grpc.js +7 -854
  52. package/build/health.d.ts +93 -0
  53. package/build/health.js +223 -0
  54. package/build/health.js.map +1 -0
  55. package/build/heartbeat.d.ts +1 -1
  56. package/build/host/discovery.d.ts +61 -0
  57. package/build/host/discovery.js +113 -0
  58. package/build/host/discovery.js.map +1 -0
  59. package/build/host/env.d.ts +14 -0
  60. package/build/host/env.js +57 -0
  61. package/build/host/env.js.map +1 -0
  62. package/build/host/fakes.d.ts +82 -0
  63. package/build/host/fakes.js +239 -0
  64. package/build/host/fakes.js.map +1 -0
  65. package/build/host/group.d.ts +142 -0
  66. package/build/host/group.js +517 -0
  67. package/build/host/group.js.map +1 -0
  68. package/build/host/install.d.ts +96 -0
  69. package/build/host/install.js +330 -0
  70. package/build/host/install.js.map +1 -0
  71. package/build/host/lock.d.ts +78 -0
  72. package/build/host/lock.js +190 -0
  73. package/build/host/lock.js.map +1 -0
  74. package/build/host/logs.d.ts +26 -0
  75. package/build/host/logs.js +48 -0
  76. package/build/host/logs.js.map +1 -0
  77. package/build/host/node.d.ts +14 -0
  78. package/build/host/node.js +309 -0
  79. package/build/host/node.js.map +1 -0
  80. package/build/{ports-B1ayTL-j.d.ts → host/ports.d.ts} +15 -16
  81. package/build/host/ports.js +17 -0
  82. package/build/host/ports.js.map +1 -0
  83. package/build/host/probes.d.ts +51 -0
  84. package/build/host/probes.js +139 -0
  85. package/build/host/probes.js.map +1 -0
  86. package/build/host/processes.d.ts +32 -0
  87. package/build/host/processes.js +63 -0
  88. package/build/host/processes.js.map +1 -0
  89. package/build/host/render.d.ts +84 -0
  90. package/build/host/render.js +235 -0
  91. package/build/host/render.js.map +1 -0
  92. package/build/host/watch.d.ts +90 -0
  93. package/build/host/watch.js +165 -0
  94. package/build/host/watch.js.map +1 -0
  95. package/build/host.d.ts +13 -671
  96. package/build/host.js +12 -2126
  97. package/build/http/answers.js +29 -0
  98. package/build/http/answers.js.map +1 -0
  99. package/build/http/fake-server.js +61 -0
  100. package/build/http/fake-server.js.map +1 -0
  101. package/build/http/outcome.d.ts +115 -0
  102. package/build/http/outcome.js +325 -0
  103. package/build/http/outcome.js.map +1 -0
  104. package/build/http/probes.d.ts +83 -0
  105. package/build/http/probes.js +232 -0
  106. package/build/http/probes.js.map +1 -0
  107. package/build/http/transport.d.ts +165 -0
  108. package/build/http/transport.js +517 -0
  109. package/build/http/transport.js.map +1 -0
  110. package/build/http-client/client.d.ts +121 -0
  111. package/build/http-client/client.js +330 -0
  112. package/build/http-client/client.js.map +1 -0
  113. package/build/http-client/connection.d.ts +78 -0
  114. package/build/http-client/connection.js +54 -0
  115. package/build/http-client/connection.js.map +1 -0
  116. package/build/http-client/machine.d.ts +14 -0
  117. package/build/http-client/machine.js +109 -0
  118. package/build/http-client/machine.js.map +1 -0
  119. package/build/http-client/meets.d.ts +11 -0
  120. package/build/http-client/meets.js +74 -0
  121. package/build/http-client/meets.js.map +1 -0
  122. package/build/http-client/session.d.ts +87 -0
  123. package/build/http-client/session.js +99 -0
  124. package/build/http-client/session.js.map +1 -0
  125. package/build/http-client/starting.d.ts +25 -0
  126. package/build/http-client/starting.js +65 -0
  127. package/build/http-client/starting.js.map +1 -0
  128. package/build/http-client.d.ts +9 -330
  129. package/build/http-client.js +8 -707
  130. package/build/http.d.ts +5 -353
  131. package/build/http.js +3 -1086
  132. package/build/identity.d.ts +16 -0
  133. package/build/identity.js +44 -0
  134. package/build/identity.js.map +1 -0
  135. package/build/index.d.ts +35 -412
  136. package/build/index.js +24 -3277
  137. package/build/knobs.d.ts +1 -0
  138. package/build/{knobs-BJcz6m01.js → knobs.js} +2 -34
  139. package/build/knobs.js.map +1 -0
  140. package/build/latch.d.ts +29 -0
  141. package/build/latch.js +122 -0
  142. package/build/latch.js.map +1 -0
  143. package/build/{rules-HyFCBStQ.d.ts → law.d.ts} +19 -37
  144. package/build/law.js +149 -0
  145. package/build/law.js.map +1 -0
  146. package/build/lifecycle.d.ts +144 -0
  147. package/build/lifecycle.js +411 -0
  148. package/build/lifecycle.js.map +1 -0
  149. package/build/limiter/machine.d.ts +40 -0
  150. package/build/limiter/machine.js +279 -0
  151. package/build/limiter/machine.js.map +1 -0
  152. package/build/{policy-CBcK2XGg.d.ts → limiter/policy.d.ts} +28 -29
  153. package/build/{policy-UYALkqVq.js → limiter/policy.js} +10 -9
  154. package/build/limiter/policy.js.map +1 -0
  155. package/build/{limiter-Cm8nC-Gd.d.ts → limiter/quota.d.ts} +50 -76
  156. package/build/{limiter-Bgy6Gmvl.js → limiter/quota.js} +32 -425
  157. package/build/limiter/quota.js.map +1 -0
  158. package/build/{store-DFwFKrsB.d.ts → limiter/store.d.ts} +10 -11
  159. package/build/limiter/store.js +145 -0
  160. package/build/limiter/store.js.map +1 -0
  161. package/build/limiter.d.ts +4 -3
  162. package/build/limiter.js +4 -2
  163. package/build/lint.d.ts +152 -0
  164. package/build/lint.js +576 -0
  165. package/build/lint.js.map +1 -0
  166. package/build/logger.d.ts +71 -0
  167. package/build/logger.js +183 -0
  168. package/build/logger.js.map +1 -0
  169. package/build/machines.d.ts +41 -0
  170. package/build/machines.js +451 -0
  171. package/build/machines.js.map +1 -0
  172. package/build/metrics.d.ts +53 -0
  173. package/build/metrics.js +111 -0
  174. package/build/metrics.js.map +1 -0
  175. package/build/mongodb/client.d.ts +131 -0
  176. package/build/mongodb/client.js +388 -0
  177. package/build/mongodb/client.js.map +1 -0
  178. package/build/mongodb/connection.d.ts +112 -0
  179. package/build/mongodb/connection.js +12 -0
  180. package/build/mongodb/connection.js.map +1 -0
  181. package/build/mongodb/machine.d.ts +14 -0
  182. package/build/mongodb/machine.js +122 -0
  183. package/build/mongodb/machine.js.map +1 -0
  184. package/build/mongodb/meets.d.ts +15 -0
  185. package/build/mongodb/meets.js +103 -0
  186. package/build/mongodb/meets.js.map +1 -0
  187. package/build/mongodb/starting.d.ts +29 -0
  188. package/build/mongodb/starting.js +77 -0
  189. package/build/mongodb/starting.js.map +1 -0
  190. package/build/mongodb.d.ts +8 -296
  191. package/build/mongodb.js +7 -682
  192. package/build/operation.d.ts +27 -0
  193. package/build/{operation-DF73RZOI.js → operation.js} +2 -2
  194. package/build/operation.js.map +1 -0
  195. package/build/otel.d.ts +2 -2
  196. package/build/pg/client.d.ts +96 -0
  197. package/build/pg/client.js +277 -0
  198. package/build/pg/client.js.map +1 -0
  199. package/build/pg/connection.d.ts +75 -0
  200. package/build/pg/connection.js +11 -0
  201. package/build/pg/connection.js.map +1 -0
  202. package/build/pg/machine.d.ts +13 -0
  203. package/build/pg/machine.js +111 -0
  204. package/build/pg/machine.js.map +1 -0
  205. package/build/pg/meets.d.ts +14 -0
  206. package/build/pg/meets.js +83 -0
  207. package/build/pg/meets.js.map +1 -0
  208. package/build/pg/starting.d.ts +26 -0
  209. package/build/pg/starting.js +62 -0
  210. package/build/pg/starting.js.map +1 -0
  211. package/build/pg.d.ts +8 -219
  212. package/build/pg.js +7 -525
  213. package/build/poller.d.ts +9 -0
  214. package/build/poller.js +152 -0
  215. package/build/poller.js.map +1 -0
  216. package/build/process.d.ts +114 -0
  217. package/build/process.js +170 -0
  218. package/build/process.js.map +1 -0
  219. package/build/profiles.d.ts +68 -0
  220. package/build/profiles.js +120 -0
  221. package/build/profiles.js.map +1 -0
  222. package/build/{queue-DXdw1vLO.d.ts → queue.d.ts} +16 -29
  223. package/build/queue.js +279 -0
  224. package/build/queue.js.map +1 -0
  225. package/build/rabbitmq/client.d.ts +144 -0
  226. package/build/rabbitmq/client.js +426 -0
  227. package/build/rabbitmq/client.js.map +1 -0
  228. package/build/rabbitmq/connection.d.ts +91 -0
  229. package/build/rabbitmq/connection.js +15 -0
  230. package/build/rabbitmq/connection.js.map +1 -0
  231. package/build/rabbitmq/machine.d.ts +13 -0
  232. package/build/rabbitmq/machine.js +159 -0
  233. package/build/rabbitmq/machine.js.map +1 -0
  234. package/build/rabbitmq/meets.d.ts +12 -0
  235. package/build/rabbitmq/meets.js +96 -0
  236. package/build/rabbitmq/meets.js.map +1 -0
  237. package/build/rabbitmq/starting.d.ts +27 -0
  238. package/build/rabbitmq/starting.js +67 -0
  239. package/build/rabbitmq/starting.js.map +1 -0
  240. package/build/rabbitmq.d.ts +8 -283
  241. package/build/rabbitmq.js +7 -742
  242. package/build/redis/client.d.ts +86 -0
  243. package/build/redis/client.js +285 -0
  244. package/build/redis/client.js.map +1 -0
  245. package/build/redis/connection.d.ts +57 -0
  246. package/build/redis/connection.js +11 -0
  247. package/build/redis/connection.js.map +1 -0
  248. package/build/redis/limiter.d.ts +43 -0
  249. package/build/redis/limiter.js +164 -0
  250. package/build/redis/limiter.js.map +1 -0
  251. package/build/redis/machine.d.ts +12 -0
  252. package/build/redis/machine.js +144 -0
  253. package/build/redis/machine.js.map +1 -0
  254. package/build/redis/meets.d.ts +11 -0
  255. package/build/redis/meets.js +75 -0
  256. package/build/redis/meets.js.map +1 -0
  257. package/build/redis/operations.d.ts +5 -0
  258. package/build/redis/operations.js +114 -0
  259. package/build/redis/operations.js.map +1 -0
  260. package/build/redis.d.ts +10 -207
  261. package/build/redis.js +9 -771
  262. package/build/requests.d.ts +66 -0
  263. package/build/requests.js +279 -0
  264. package/build/requests.js.map +1 -0
  265. package/build/retrier.d.ts +62 -0
  266. package/build/{retrier-Dnjhvxol.js → retrier.js} +2 -2
  267. package/build/retrier.js.map +1 -0
  268. package/build/routes.d.ts +35 -0
  269. package/build/routes.js +77 -0
  270. package/build/routes.js.map +1 -0
  271. package/build/rules.d.ts +19 -2
  272. package/build/stops.d.ts +51 -0
  273. package/build/stops.js +86 -0
  274. package/build/stops.js.map +1 -0
  275. package/build/testing.d.ts +8 -270
  276. package/build/testing.js +4 -1027
  277. package/build/testing.js.map +1 -1
  278. package/build/timing.d.ts +63 -0
  279. package/build/{timing-DZl36uXs.js → timing.js} +2 -2
  280. package/build/timing.js.map +1 -0
  281. package/build/units.d.ts +17 -0
  282. package/build/units.js +236 -0
  283. package/build/units.js.map +1 -0
  284. package/build/watchdog.d.ts +34 -0
  285. package/build/watchdog.js +53 -0
  286. package/build/watchdog.js.map +1 -0
  287. package/build/websocket/client.d.ts +136 -0
  288. package/build/websocket/client.js +422 -0
  289. package/build/websocket/client.js.map +1 -0
  290. package/build/websocket/connection.d.ts +83 -0
  291. package/build/websocket/connection.js +57 -0
  292. package/build/websocket/connection.js.map +1 -0
  293. package/build/websocket/machine.d.ts +12 -0
  294. package/build/websocket/machine.js +155 -0
  295. package/build/websocket/machine.js.map +1 -0
  296. package/build/websocket/meets.d.ts +14 -0
  297. package/build/websocket/meets.js +92 -0
  298. package/build/websocket/meets.js.map +1 -0
  299. package/build/websocket/starting.d.ts +25 -0
  300. package/build/websocket/starting.js +69 -0
  301. package/build/websocket/starting.js.map +1 -0
  302. package/build/websocket.d.ts +9 -264
  303. package/build/websocket.js +8 -774
  304. package/build/worker.d.ts +92 -0
  305. package/build/worker.js +153 -0
  306. package/build/worker.js.map +1 -0
  307. package/package.json +4 -3
  308. package/build/backoff-QTRGfkEK.d.ts +0 -45
  309. package/build/clock-DpVgpY4h.d.ts +0 -2
  310. package/build/grpc.js.map +0 -1
  311. package/build/host.js.map +0 -1
  312. package/build/http-client.js.map +0 -1
  313. package/build/http.js.map +0 -1
  314. package/build/index.js.map +0 -1
  315. package/build/knobs-BJcz6m01.js.map +0 -1
  316. package/build/lifecycle-D0J-zwZF.d.ts +0 -374
  317. package/build/limiter-Bgy6Gmvl.js.map +0 -1
  318. package/build/logger-B6drv9w0.d.ts +0 -488
  319. package/build/machine-BhVeHr_m.js.map +0 -1
  320. package/build/mongodb.js.map +0 -1
  321. package/build/operation-DF73RZOI.js.map +0 -1
  322. package/build/pg.js.map +0 -1
  323. package/build/policy-UYALkqVq.js.map +0 -1
  324. package/build/process-7R9M29wN.js +0 -437
  325. package/build/process-7R9M29wN.js.map +0 -1
  326. package/build/rabbitmq.js.map +0 -1
  327. package/build/redis.js.map +0 -1
  328. package/build/requests-DD2ALv0_.js +0 -583
  329. package/build/requests-DD2ALv0_.js.map +0 -1
  330. package/build/retrier-Dnjhvxol.js.map +0 -1
  331. package/build/timing-DZl36uXs.js.map +0 -1
  332. package/build/websocket.js.map +0 -1
@@ -0,0 +1,86 @@
1
+ import { CheckOptions, Client, ClientJoin, ClientKnobs, ClientOptions, ClientSpec, ClientStep, DialFn, RetryKnobs, SendOptions, Sent, retryBackoff } from "../client/core.js";
2
+ import { ConnectionFactory } from "./connection.js";
3
+ import { Extent, Quantity } from "@mark1russell7/quantity";
4
+ /**
5
+ * These are the knobs of the client, each a time, by the names of the ordering law where the law
6
+ * has them. The runtime has no defaults, thus each knob is necessary, and a bound that nobody gives
7
+ * is "infinite", not zero. The knobs that each client has come from the core.
8
+ */
9
+ export interface RedisKnobs extends ClientKnobs, RetryKnobs {
10
+ /** This time bounds a try to connect, until the TCP connection exists (`connectTimeout`). */
11
+ readonly connect_bound: Quantity;
12
+ /** This time bounds each command, the handshake commands too (`commandTimeout`). */
13
+ readonly request_timeout: Quantity;
14
+ /** This time destroys a socket that gives no data while a command waits (`socketTimeout`). */
15
+ readonly driver_writeoff_time: Extent;
16
+ /** This time is the interval of the in-band watchdog: a PING on the connection of the application. */
17
+ readonly heartbeat_interval: Extent;
18
+ /** This time bounds each PING of the watchdog. */
19
+ readonly heartbeat_timeout: Quantity;
20
+ /** This time is how long the client tries to connect again before it stops. The watchdog then starts it again. */
21
+ readonly client_retry_window: Extent;
22
+ /** This time is the first delay before a new try to connect. The delay doubles after each try. */
23
+ readonly retry_base: Quantity;
24
+ /** This time is the most that one delay can be, before its jitter. */
25
+ readonly retry_cap: Quantity;
26
+ /** This time bounds the close of the client at the shutdown: a QUIT, then a disconnect. */
27
+ readonly close_bound: Quantity;
28
+ /** This time is the age at which the client replaces its connection. The client supports only "infinite". */
29
+ readonly max_connection_age: Extent;
30
+ }
31
+ /** A Redis client spec is the declaration of one Redis client: where it connects, and its knobs. */
32
+ export interface RedisClientSpec extends ClientSpec<RedisKnobs> {
33
+ readonly db?: number | undefined;
34
+ readonly username?: string | undefined;
35
+ /** This count is the number of PINGs in sequence without an answer that make the watchdog connect again. */
36
+ readonly heartbeatMisses: number;
37
+ }
38
+ /** These options make a client. Without them, it uses ioredis, the real clock and `Math.random`. */
39
+ export interface RedisClientOptions extends ClientOptions<ConnectionFactory> {
40
+ readonly random?: (() => number) | undefined;
41
+ /**
42
+ * This function waits one turn of the event loop. The watchdog waits it before it counts a miss,
43
+ * thus a reply that is in the socket is read first. Without it, the client uses `setImmediate`.
44
+ */
45
+ readonly turn?: (() => Promise<void>) | undefined;
46
+ }
47
+ /**
48
+ * A join is one generation of the connection, at its `ready` (D1, D2). The prober joins its kernel
49
+ * records to the server's view of the connection through it. A join holds the server's id of the
50
+ * connection, and the local address and port of the socket.
51
+ */
52
+ export interface Join extends ClientJoin {
53
+ /** This number is the reply of CLIENT ID, or null when the server gave none. */
54
+ readonly clientId: number | null;
55
+ }
56
+ /** A Redis client is a dependency of a service: its declaration, its handle, its checks and its commands. */
57
+ export interface RedisClient extends Client<ClientStep, Join> {
58
+ /** This text is the state of the connection, as ioredis names it, or "none" before the connect. */
59
+ readonly status: string;
60
+ /**
61
+ * This method sends a command, and gives its outcome in three values. The client sends again
62
+ * only an idempotent operation, one time at most, after an outcome that is not certain. The
63
+ * second try stays in the bound of the request. The client does not send again an operation that
64
+ * the table does not name.
65
+ */
66
+ send<T = unknown>(command: string, args?: ReadonlyArray<string | number>, options?: SendOptions): Promise<Sent<T>>;
67
+ }
68
+ /** This function gives the problems of a spec: the knobs that the client cannot use. */
69
+ export declare const specProblems: (name: string, spec: RedisClientSpec) => string[];
70
+ /** This dial function opens a TCP connection, sends an inline PING, and waits for +PONG. */
71
+ export declare const tcpDial: DialFn;
72
+ /**
73
+ * This function makes a Redis client. It is a dependency of a service, with ioredis under it:
74
+ * - It sets each timer of ioredis from the declaration, and it does not let ioredis send a command
75
+ * again (R5 §8).
76
+ * - It tells the outcome of a command in three values, and it settles each command in flight as
77
+ * indeterminate when its connection closes (C8, C10).
78
+ * - It records the server's id of each connection at `ready` (D1).
79
+ * - A watchdog sends a PING in the band of the connection, and it connects again after the misses
80
+ * of the declaration. It also starts a client that stopped (principle 19).
81
+ *
82
+ * The outcomes, the second try, the commands in flight, the bounded close and the checks come
83
+ * from the core of the clients. This entry gives what ioredis does in its own way.
84
+ */
85
+ export declare const redisClient: (name: string, spec: RedisClientSpec, options?: RedisClientOptions) => RedisClient;
86
+ export { type CheckOptions, type ClientStep, type DialFn, type Sent, retryBackoff };
@@ -0,0 +1,285 @@
1
+ import { backoffDelay } from "../backoff.js";
2
+ import { realClock } from "../clock.js";
3
+ import { attachClient, clientBounds, clientProblems, clientRecorder, dialCheck, finiteMs, inFlight, localStateCheck, message, missesProblems, ms, notSent, operationTable, readyWait, retryBackoff, retryProblems, roundTripCheck, sendWithReissue, socketEnds, stepChecks, timeProblems, withinBound } from "../client/core.js";
4
+ import { helloDial } from "../client/dial.js";
5
+ import { heartbeat } from "../heartbeat.js";
6
+ import { heartbeatDetection } from "../timing.js";
7
+ import { ioredis } from "./connection.js";
8
+ import { meetings } from "./meets.js";
9
+ import { REDIS_OPERATIONS, commandName } from "./operations.js";
10
+ // src/redis/client.ts
11
+ /** This function gives the problems of a spec: the knobs that the client cannot use. */
12
+ const specProblems = (name, spec) => {
13
+ const problems = [];
14
+ const { knobs } = spec;
15
+ problems.push(...missesProblems(name, spec.heartbeatMisses, "watchdog"));
16
+ if (knobs.max_connection_age.value !== "infinite") problems.push(`${name} cannot replace its connection at an age: max_connection_age must be "infinite"`);
17
+ problems.push(...timeProblems(name, knobs));
18
+ if (ms(knobs.request_timeout) <= 0) problems.push(`${name}'s request_timeout is not above zero: each command must have a bound`);
19
+ if (ms(knobs.heartbeat_timeout) <= 0) problems.push(`${name}'s heartbeat_timeout is not above zero`);
20
+ problems.push(...retryProblems(name, knobs));
21
+ return problems;
22
+ };
23
+ /** This dial function opens a TCP connection, sends an inline PING, and waits for +PONG. */
24
+ const tcpDial = helloDial("PING\r\n", (received) => {
25
+ const reply = received.toString();
26
+ if (!reply.includes("\r\n")) return "more";
27
+ return reply.startsWith("+PONG") ? null : /* @__PURE__ */ new Error(`the reply was ${reply.trim()}`);
28
+ });
29
+ /**
30
+ * This function makes a Redis client. It is a dependency of a service, with ioredis under it:
31
+ * - It sets each timer of ioredis from the declaration, and it does not let ioredis send a command
32
+ * again (R5 §8).
33
+ * - It tells the outcome of a command in three values, and it settles each command in flight as
34
+ * indeterminate when its connection closes (C8, C10).
35
+ * - It records the server's id of each connection at `ready` (D1).
36
+ * - A watchdog sends a PING in the band of the connection, and it connects again after the misses
37
+ * of the declaration. It also starts a client that stopped (principle 19).
38
+ *
39
+ * The outcomes, the second try, the commands in flight, the bounded close and the checks come
40
+ * from the core of the clients. This entry gives what ioredis does in its own way.
41
+ */
42
+ const redisClient = (name, spec, options = {}) => {
43
+ const problems = specProblems(name, spec);
44
+ if (problems.length > 0) throw new Error(problems.join("; "));
45
+ const { knobs } = spec;
46
+ const clock = options.clock ?? realClock;
47
+ const random = options.random ?? Math.random;
48
+ const create = options.create ?? ioredis;
49
+ const dial = options.dial ?? tcpDial;
50
+ const turn = options.turn ?? (() => new Promise((resolve) => setImmediate(resolve)));
51
+ const operations = operationTable(REDIS_OPERATIONS, spec.operations);
52
+ const requestTimeout = ms(knobs.request_timeout);
53
+ const detection = heartbeatDetection(knobs.heartbeat_interval, knobs.heartbeat_timeout, spec.heartbeatMisses);
54
+ const backoff = retryBackoff(knobs);
55
+ let connection = null;
56
+ let status = "none";
57
+ let closing = false;
58
+ const joins = [];
59
+ const flight = inFlight();
60
+ const readied = readyWait(clock, () => connection?.status === "ready");
61
+ const listeners = [];
62
+ const record = clientRecorder(options.record, clock, name);
63
+ let retrySince = null;
64
+ const retryStrategy = (times) => {
65
+ const now = clock.now();
66
+ retrySince ??= now;
67
+ if (now - retrySince > ms(knobs.client_retry_window)) {
68
+ record(status, status, "retry.window-ended");
69
+ return null;
70
+ }
71
+ return Math.round(backoffDelay(backoff, times, random));
72
+ };
73
+ const connectionOptions = {
74
+ host: spec.host,
75
+ port: spec.port,
76
+ ...spec.db === void 0 ? {} : { db: spec.db },
77
+ ...spec.username === void 0 ? {} : { username: spec.username },
78
+ ...spec.password === void 0 ? {} : { password: spec.password },
79
+ lazyConnect: true,
80
+ connectTimeout: ms(knobs.connect_bound),
81
+ commandTimeout: requestTimeout,
82
+ socketTimeout: finiteMs(knobs.driver_writeoff_time),
83
+ keepAlive: finiteMs(knobs.keepalive_idle) ?? false,
84
+ enableOfflineQueue: false,
85
+ autoResendUnfulfilledCommands: false,
86
+ maxRetriesPerRequest: null,
87
+ enableReadyCheck: true,
88
+ connectionName: name,
89
+ retryStrategy
90
+ };
91
+ /** This function gives the outcome of a failed command: a reply of the server, a command that did not leave the client, or neither. */
92
+ const failed = (error) => {
93
+ const text = message(error);
94
+ if (error instanceof Error && error.name === "ReplyError") return {
95
+ outcome: "error",
96
+ error: text,
97
+ reply: true
98
+ };
99
+ if (/isn't writeable|enableOfflineQueue/i.test(text)) return notSent(text);
100
+ return {
101
+ outcome: "indeterminate",
102
+ error: text
103
+ };
104
+ };
105
+ const onReady = async () => {
106
+ retrySince = null;
107
+ const c = connection;
108
+ if (c === null) return;
109
+ const generation = joins.length + 1;
110
+ const at = clock.now();
111
+ const socket = c.stream;
112
+ let clientId = null;
113
+ try {
114
+ const reply = await c.call("CLIENT", "ID");
115
+ clientId = typeof reply === "number" ? reply : Number(reply);
116
+ if (!Number.isFinite(clientId)) clientId = null;
117
+ } catch {
118
+ clientId = null;
119
+ }
120
+ if (connection !== c || c.status !== "ready") return;
121
+ joins.push({
122
+ generation,
123
+ at,
124
+ clientId,
125
+ ...socketEnds(socket)
126
+ });
127
+ record("ready", "ready", "join", `generation ${generation}, client id ${clientId ?? "unknown"}`);
128
+ readied.wake();
129
+ };
130
+ const onStatus = (to) => () => {
131
+ const from = status;
132
+ status = to;
133
+ record(from, to, `status.${to}`);
134
+ if (to === "close" || to === "end") flight.settleAll(`the connection closed with the command in flight (${from})`);
135
+ if (to === "ready") onReady();
136
+ };
137
+ const watch = (c) => {
138
+ for (const state of [
139
+ "connecting",
140
+ "connect",
141
+ "ready",
142
+ "close",
143
+ "reconnecting",
144
+ "end"
145
+ ]) {
146
+ const listener = onStatus(state);
147
+ c.on(state, listener);
148
+ listeners.push([state, listener]);
149
+ }
150
+ const onError = (error) => record(status, status, "error", message(error));
151
+ c.on("error", onError);
152
+ listeners.push(["error", onError]);
153
+ };
154
+ const attempt = (command, args, signal) => {
155
+ const c = connection;
156
+ if (c === null) return Promise.resolve(notSent(`${name} has not connected`));
157
+ if (c.status !== "ready") return Promise.resolve(notSent(`${name} is ${c.status}, not ready: the command did not leave the client`));
158
+ if (signal?.aborted) return Promise.resolve(notSent("the caller aborted the command before it left the client"));
159
+ return flight.track(signal, "the caller abandoned the command after it was sent", (settle) => {
160
+ c.call(command, ...args).then((value) => settle({
161
+ outcome: "ok",
162
+ value
163
+ }), (error) => settle(failed(error)));
164
+ });
165
+ };
166
+ const send = (command, args = [], sendOptions = {}) => sendWithReissue({
167
+ clock,
168
+ bound: requestTimeout,
169
+ operation: operations[commandName(command, args)],
170
+ options: sendOptions,
171
+ attempt: (signal) => attempt(command, args, signal),
172
+ beforeAgain: (left, signal) => readied.wait(left, signal),
173
+ onReissue: () => record(status, status, "command.reissue", commandName(command, args))
174
+ });
175
+ let watchdog = null;
176
+ const startWatchdog = () => heartbeat({
177
+ interval: ms(knobs.heartbeat_interval),
178
+ timeout: ms(knobs.heartbeat_timeout),
179
+ misses: spec.heartbeatMisses,
180
+ clock,
181
+ turn,
182
+ overlap: true,
183
+ due: () => {
184
+ const c = connection;
185
+ if (c === null || closing) return false;
186
+ if (c.status === "end") {
187
+ record(status, status, "watchdog.revive");
188
+ retrySince = null;
189
+ c.connect().catch(() => {});
190
+ return false;
191
+ }
192
+ return c.status === "ready";
193
+ },
194
+ ping: (signal) => attempt("PING", [], signal).then((result) => result.outcome === "ok" || result.outcome === "error" && result.reply),
195
+ live: () => connection?.status === "ready" && !closing,
196
+ onMiss: (misses) => record(status, status, "watchdog.miss", `${misses} of ${spec.heartbeatMisses}`),
197
+ onDead: () => {
198
+ record(status, status, "watchdog.reconnect");
199
+ connection?.disconnect(true);
200
+ }
201
+ });
202
+ const handle = {
203
+ async connect(signal) {
204
+ closing = false;
205
+ const c = await create(connectionOptions);
206
+ connection = c;
207
+ watch(c);
208
+ if (signal.aborted) throw new Error(`${name}: the service stopped before the connect`);
209
+ await c.connect().catch((error) => record(status, status, "connect.failed", message(error)));
210
+ watchdog?.stop();
211
+ watchdog = startWatchdog();
212
+ },
213
+ async close() {
214
+ closing = true;
215
+ watchdog?.stop();
216
+ watchdog = null;
217
+ const c = connection;
218
+ if (c === null) return;
219
+ const startedClose = clock.now();
220
+ if (!await withinBound(clock, ms(knobs.close_bound), c.quit())) record(status, status, "close.bound");
221
+ if (c.status !== "end") c.disconnect(false);
222
+ const ended = (within) => c.status === "end" ? Promise.resolve() : new Promise((resolve) => {
223
+ let stop = () => {};
224
+ const end = () => {
225
+ c.off("end", end);
226
+ stop();
227
+ resolve();
228
+ };
229
+ c.on("end", end);
230
+ stop = clock.after(Math.max(0, within), end);
231
+ });
232
+ await ended(ms(knobs.close_bound) - (clock.now() - startedClose));
233
+ if (c.status !== "end") {
234
+ record(status, status, "close.destroy");
235
+ c.stream?.destroy?.();
236
+ await ended(0);
237
+ }
238
+ for (const [event, listener] of listeners) c.off(event, listener);
239
+ listeners.length = 0;
240
+ flight.settleAll("the client closed with the command in flight");
241
+ status = "end";
242
+ }
243
+ };
244
+ const declaration = {
245
+ system: spec.system,
246
+ knobs: {
247
+ connect_bound: knobs.connect_bound,
248
+ request_timeout: knobs.request_timeout,
249
+ driver_writeoff_time: knobs.driver_writeoff_time,
250
+ keepalive_idle: knobs.keepalive_idle,
251
+ heartbeat_interval: knobs.heartbeat_interval,
252
+ heartbeat_timeout: knobs.heartbeat_timeout,
253
+ heartbeat_detection_time: detection,
254
+ client_retry_window: knobs.client_retry_window,
255
+ retry_base: knobs.retry_base,
256
+ retry_cap: knobs.retry_cap,
257
+ close_bound: knobs.close_bound,
258
+ max_connection_age: knobs.max_connection_age,
259
+ retrans_giveup_time: knobs.retrans_giveup_time
260
+ },
261
+ operations
262
+ };
263
+ const checks = (checkOptions) => stepChecks(name, checkOptions, {
264
+ "local-state": localStateCheck(() => connection?.status === "ready"),
265
+ "round-trip": roundTripCheck((sendOptions) => send("PING", [], sendOptions)),
266
+ dial: dialCheck(dial, spec.host, spec.port)
267
+ });
268
+ return {
269
+ name,
270
+ declaration,
271
+ handle,
272
+ meets: meetings(name, knobs, detection),
273
+ get status() {
274
+ return connection === null ? "none" : connection.status;
275
+ },
276
+ joins,
277
+ send,
278
+ checks,
279
+ attach: (svc, checkOptions) => attachClient(svc, name, declaration, handle, checks(checkOptions)),
280
+ problems: (description) => clientProblems(name, description, clientBounds(knobs))
281
+ };
282
+ };
283
+ export { redisClient, retryBackoff, specProblems, tcpDial };
284
+
285
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","names":[],"sources":["../../src/redis/client.ts"],"sourcesContent":["import type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport { backoffDelay } from \"../backoff.ts\";\nimport type { Cancel } from \"../clock.ts\";\nimport { realClock } from \"../clock.ts\";\nimport type { Attempt, CheckOptions, Client, ClientJoin, ClientKnobs, ClientOptions, ClientSpec, ClientStep, DialFn, RetryKnobs, SendOptions, Sent } from \"../client/core.ts\";\nimport {\n attachClient,\n clientBounds,\n clientProblems,\n clientRecorder,\n dialCheck,\n finiteMs,\n inFlight,\n localStateCheck,\n message,\n missesProblems,\n ms,\n notSent,\n operationTable,\n readyWait,\n retryBackoff,\n retryProblems,\n roundTripCheck,\n sendWithReissue,\n socketEnds,\n stepChecks,\n timeProblems,\n withinBound,\n} from \"../client/core.ts\";\nimport { helloDial } from \"../client/dial.ts\";\nimport type { Dependency } from \"../description.ts\";\nimport type { Heartbeat } from \"../heartbeat.ts\";\nimport { heartbeat } from \"../heartbeat.ts\";\nimport type { DependencyHandle } from \"../lifecycle.ts\";\nimport { heartbeatDetection } from \"../timing.ts\";\nimport type { ConnectionFactory, RedisConnection, RedisConnectionOptions } from \"./connection.ts\";\nimport { ioredis } from \"./connection.ts\";\nimport { meetings } from \"./meets.ts\";\nimport { REDIS_OPERATIONS, commandName } from \"./operations.ts\";\n\n// the three outcomes, the send options and the checks moved to the core of the clients: this entry keeps them for the users of 0.5\nexport type { CheckOptions, ClientStep, DialFn, SendOptions, Sent } from \"../client/core.ts\";\n// the backoff of the tries to connect moved to the core, for RabbitMQ too: this entry keeps it for the users of 0.5\nexport { retryBackoff } from \"../client/core.ts\";\n\n/**\n * These are the knobs of the client, each a time, by the names of the ordering law where the law\n * has them. The runtime has no defaults, thus each knob is necessary, and a bound that nobody gives\n * is \"infinite\", not zero. The knobs that each client has come from the core.\n */\nexport interface RedisKnobs extends ClientKnobs, RetryKnobs {\n /** This time bounds a try to connect, until the TCP connection exists (`connectTimeout`). */\n readonly connect_bound: Quantity;\n /** This time bounds each command, the handshake commands too (`commandTimeout`). */\n readonly request_timeout: Quantity;\n /** This time destroys a socket that gives no data while a command waits (`socketTimeout`). */\n readonly driver_writeoff_time: Extent;\n /** This time is the interval of the in-band watchdog: a PING on the connection of the application. */\n readonly heartbeat_interval: Extent;\n /** This time bounds each PING of the watchdog. */\n readonly heartbeat_timeout: Quantity;\n /** This time is how long the client tries to connect again before it stops. The watchdog then starts it again. */\n readonly client_retry_window: Extent;\n /** This time is the first delay before a new try to connect. The delay doubles after each try. */\n readonly retry_base: Quantity;\n /** This time is the most that one delay can be, before its jitter. */\n readonly retry_cap: Quantity;\n /** This time bounds the close of the client at the shutdown: a QUIT, then a disconnect. */\n readonly close_bound: Quantity;\n /** This time is the age at which the client replaces its connection. The client supports only \"infinite\". */\n readonly max_connection_age: Extent;\n}\n\n/** A Redis client spec is the declaration of one Redis client: where it connects, and its knobs. */\nexport interface RedisClientSpec extends ClientSpec<RedisKnobs> {\n readonly db?: number | undefined;\n readonly username?: string | undefined;\n /** This count is the number of PINGs in sequence without an answer that make the watchdog connect again. */\n readonly heartbeatMisses: number;\n}\n\n/** These options make a client. Without them, it uses ioredis, the real clock and `Math.random`. */\nexport interface RedisClientOptions extends ClientOptions<ConnectionFactory> {\n readonly random?: (() => number) | undefined;\n /**\n * This function waits one turn of the event loop. The watchdog waits it before it counts a miss,\n * thus a reply that is in the socket is read first. Without it, the client uses `setImmediate`.\n */\n readonly turn?: (() => Promise<void>) | undefined;\n}\n\n/**\n * A join is one generation of the connection, at its `ready` (D1, D2). The prober joins its kernel\n * records to the server's view of the connection through it. A join holds the server's id of the\n * connection, and the local address and port of the socket.\n */\nexport interface Join extends ClientJoin {\n /** This number is the reply of CLIENT ID, or null when the server gave none. */\n readonly clientId: number | null;\n}\n\n/** A Redis client is a dependency of a service: its declaration, its handle, its checks and its commands. */\nexport interface RedisClient extends Client<ClientStep, Join> {\n /** This text is the state of the connection, as ioredis names it, or \"none\" before the connect. */\n readonly status: string;\n /**\n * This method sends a command, and gives its outcome in three values. The client sends again\n * only an idempotent operation, one time at most, after an outcome that is not certain. The\n * second try stays in the bound of the request. The client does not send again an operation that\n * the table does not name.\n */\n send<T = unknown>(command: string, args?: ReadonlyArray<string | number>, options?: SendOptions): Promise<Sent<T>>;\n}\n\n/** This function gives the problems of a spec: the knobs that the client cannot use. */\nexport const specProblems = (name: string, spec: RedisClientSpec): string[] => {\n const problems: string[] = [];\n const { knobs } = spec;\n problems.push(...missesProblems(name, spec.heartbeatMisses, \"watchdog\"));\n if (knobs.max_connection_age.value !== \"infinite\")\n problems.push(`${name} cannot replace its connection at an age: max_connection_age must be \"infinite\"`);\n problems.push(...timeProblems(name, knobs));\n if (ms(knobs.request_timeout) <= 0) problems.push(`${name}'s request_timeout is not above zero: each command must have a bound`);\n if (ms(knobs.heartbeat_timeout) <= 0) problems.push(`${name}'s heartbeat_timeout is not above zero`);\n problems.push(...retryProblems(name, knobs));\n return problems;\n};\n\n/** This dial function opens a TCP connection, sends an inline PING, and waits for +PONG. */\nexport const tcpDial: DialFn = helloDial(\"PING\\r\\n\", (received) => {\n const reply = received.toString();\n if (!reply.includes(\"\\r\\n\")) return \"more\";\n return reply.startsWith(\"+PONG\") ? null : new Error(`the reply was ${reply.trim()}`);\n});\n\n/**\n * This function makes a Redis client. It is a dependency of a service, with ioredis under it:\n * - It sets each timer of ioredis from the declaration, and it does not let ioredis send a command\n * again (R5 §8).\n * - It tells the outcome of a command in three values, and it settles each command in flight as\n * indeterminate when its connection closes (C8, C10).\n * - It records the server's id of each connection at `ready` (D1).\n * - A watchdog sends a PING in the band of the connection, and it connects again after the misses\n * of the declaration. It also starts a client that stopped (principle 19).\n *\n * The outcomes, the second try, the commands in flight, the bounded close and the checks come\n * from the core of the clients. This entry gives what ioredis does in its own way.\n */\nexport const redisClient = (name: string, spec: RedisClientSpec, options: RedisClientOptions = {}): RedisClient => {\n const problems = specProblems(name, spec);\n if (problems.length > 0) throw new Error(problems.join(\"; \"));\n const { knobs } = spec;\n const clock = options.clock ?? realClock;\n const random = options.random ?? Math.random;\n const create = options.create ?? ioredis;\n const dial = options.dial ?? tcpDial;\n const turn = options.turn ?? (() => new Promise<void>((resolve) => setImmediate(resolve)));\n const operations = operationTable(REDIS_OPERATIONS, spec.operations);\n const requestTimeout = ms(knobs.request_timeout);\n const detection = heartbeatDetection(knobs.heartbeat_interval, knobs.heartbeat_timeout, spec.heartbeatMisses);\n const backoff = retryBackoff(knobs);\n\n let connection: RedisConnection | null = null;\n let status = \"none\";\n let closing = false;\n const joins: Join[] = [];\n // the commands that the client wrote while the connection was ready: a close settles each one\n const flight = inFlight();\n // the commands that wait for a ready connection before their second try\n const readied = readyWait(clock, () => connection?.status === \"ready\");\n const listeners: Array<[string, (...args: unknown[]) => void]> = [];\n\n const record = clientRecorder(options.record, clock, name);\n\n // the delays of the tries to connect (`retryBackoff`), and none after the retry window. The\n // watchdog starts the client again after that\n let retrySince: number | null = null;\n const retryStrategy = (times: number): number | null => {\n const now = clock.now();\n retrySince ??= now;\n if (now - retrySince > ms(knobs.client_retry_window)) {\n record(status, status, \"retry.window-ended\");\n return null;\n }\n return Math.round(backoffDelay(backoff, times, random));\n };\n\n const connectionOptions: RedisConnectionOptions = {\n host: spec.host,\n port: spec.port,\n ...(spec.db === undefined ? {} : { db: spec.db }),\n ...(spec.username === undefined ? {} : { username: spec.username }),\n ...(spec.password === undefined ? {} : { password: spec.password }),\n lazyConnect: true,\n connectTimeout: ms(knobs.connect_bound),\n commandTimeout: requestTimeout,\n // ioredis reads undefined as no socket timeout, and false as no keepalive\n socketTimeout: finiteMs(knobs.driver_writeoff_time),\n keepAlive: finiteMs(knobs.keepalive_idle) ?? false,\n enableOfflineQueue: false,\n autoResendUnfulfilledCommands: false,\n maxRetriesPerRequest: null,\n enableReadyCheck: true,\n connectionName: name,\n retryStrategy,\n };\n\n /** This function gives the outcome of a failed command: a reply of the server, a command that did not leave the client, or neither. */\n const failed = (error: unknown): Attempt => {\n const text = message(error);\n if (error instanceof Error && error.name === \"ReplyError\") return { outcome: \"error\", error: text, reply: true };\n if (/isn't writeable|enableOfflineQueue/i.test(text)) return notSent(text);\n return { outcome: \"indeterminate\", error: text };\n };\n\n const onReady = async (): Promise<void> => {\n retrySince = null;\n const c = connection;\n if (c === null) return;\n const generation = joins.length + 1;\n const at = clock.now();\n const socket = c.stream;\n let clientId: number | null = null;\n try {\n const reply = await c.call(\"CLIENT\", \"ID\");\n clientId = typeof reply === \"number\" ? reply : Number(reply);\n if (!Number.isFinite(clientId)) clientId = null;\n } catch {\n clientId = null;\n }\n // a connection that closed before its reply is a generation that never served\n if (connection !== c || c.status !== \"ready\") return;\n joins.push({ generation, at, clientId, ...socketEnds(socket) });\n record(\"ready\", \"ready\", \"join\", `generation ${generation}, client id ${clientId ?? \"unknown\"}`);\n readied.wake();\n };\n\n const onStatus = (to: string) => (): void => {\n const from = status;\n status = to;\n record(from, to, `status.${to}`);\n // the lower layer gave up the connection: each command in flight learns it now (C10)\n if (to === \"close\" || to === \"end\") flight.settleAll(`the connection closed with the command in flight (${from})`);\n if (to === \"ready\") void onReady();\n };\n\n const watch = (c: RedisConnection): void => {\n for (const state of [\"connecting\", \"connect\", \"ready\", \"close\", \"reconnecting\", \"end\"]) {\n const listener = onStatus(state);\n c.on(state, listener);\n listeners.push([state, listener]);\n }\n // an error of the connection comes before its close, which settles the commands: here it is only recorded\n const onError = (error: unknown): void => record(status, status, \"error\", message(error));\n c.on(\"error\", onError);\n listeners.push([\"error\", onError]);\n };\n\n const attempt = (command: string, args: ReadonlyArray<string | number>, signal?: AbortSignal): Promise<Attempt> => {\n const c = connection;\n if (c === null) return Promise.resolve(notSent(`${name} has not connected`));\n // ioredis has no offline queue here: a command while the client is not ready fails at once, before it leaves the client\n if (c.status !== \"ready\") return Promise.resolve(notSent(`${name} is ${c.status}, not ready: the command did not leave the client`));\n if (signal?.aborted) return Promise.resolve(notSent(\"the caller aborted the command before it left the client\"));\n return flight.track(signal, \"the caller abandoned the command after it was sent\", (settle) => {\n c.call(command, ...args).then(\n (value) => settle({ outcome: \"ok\", value }),\n (error: unknown) => settle(failed(error)),\n );\n });\n };\n\n const send = <T>(command: string, args: ReadonlyArray<string | number> = [], sendOptions: SendOptions = {}): Promise<Sent<T>> =>\n sendWithReissue({\n clock,\n bound: requestTimeout,\n operation: operations[commandName(command, args)],\n options: sendOptions,\n attempt: (signal) => attempt(command, args, signal) as Promise<Attempt<T>>,\n // ioredis connects again by itself: the second try waits for a ready connection, in the time that is left\n beforeAgain: (left, signal) => readied.wait(left, signal),\n onReissue: () => record(status, status, \"command.reissue\", commandName(command, args)),\n });\n\n // the watchdog: a heartbeat of PINGs on the connection of the application, each interval from the\n // start of the one before. A reply, an error reply too, is an answer. It waits one turn of the\n // event loop before it counts a miss, thus a slow loop is not a silent server. It acts only on a\n // ready connection, thus it never closes a connection in the middle of a new attempt\n let watchdog: Heartbeat | null = null;\n const startWatchdog = (): Heartbeat =>\n heartbeat({\n interval: ms(knobs.heartbeat_interval),\n timeout: ms(knobs.heartbeat_timeout),\n misses: spec.heartbeatMisses,\n clock,\n turn,\n // a PING starts at each tick, also while an earlier PING waits\n overlap: true,\n due: () => {\n const c = connection;\n if (c === null || closing) return false;\n if (c.status === \"end\") {\n // the retry window ended: the watchdog starts the client again\n record(status, status, \"watchdog.revive\");\n retrySince = null;\n c.connect().catch(() => {});\n return false;\n }\n return c.status === \"ready\";\n },\n ping: (signal) =>\n attempt(\"PING\", [], signal).then((result) => result.outcome === \"ok\" || (result.outcome === \"error\" && result.reply)),\n live: () => connection?.status === \"ready\" && !closing,\n onMiss: (misses) => record(status, status, \"watchdog.miss\", `${misses} of ${spec.heartbeatMisses}`),\n onDead: () => {\n record(status, status, \"watchdog.reconnect\");\n connection?.disconnect(true);\n },\n });\n\n const handle: DependencyHandle = {\n async connect(signal) {\n closing = false;\n const c = await create(connectionOptions);\n connection = c;\n watch(c);\n if (signal.aborted) throw new Error(`${name}: the service stopped before the connect`);\n // a server that is down at the start does not stop the startup: the client connects again in\n // the background, and its checks keep readiness tripped until it is ready (readiness is earned)\n await c.connect().catch((error: unknown) => record(status, status, \"connect.failed\", message(error)));\n watchdog?.stop();\n watchdog = startWatchdog();\n },\n async close() {\n closing = true;\n watchdog?.stop();\n watchdog = null;\n const c = connection;\n if (c === null) return;\n // a QUIT lets the replies in flight arrive. A silent server never answers it, thus the close has its bound\n const startedClose = clock.now();\n if (!(await withinBound(clock, ms(knobs.close_bound), c.quit()))) record(status, status, \"close.bound\");\n // a client that is not ready refuses the QUIT at once, and then it connects again: the close stops it\n if (c.status !== \"end\") c.disconnect(false);\n // ioredis is at `end` when its socket closes, a moment after the reply: the close waits for it, in its bound\n const ended = (within: number): Promise<void> =>\n c.status === \"end\"\n ? Promise.resolve()\n : new Promise<void>((resolve) => {\n let stop: Cancel = () => {};\n const end = (): void => {\n c.off(\"end\", end);\n stop();\n resolve();\n };\n c.on(\"end\", end);\n stop = clock.after(Math.max(0, within), end);\n });\n await ended(ms(knobs.close_bound) - (clock.now() - startedClose));\n // a disconnect only half-closes the socket, and a silent server never closes its half: the bound destroys it\n if (c.status !== \"end\") {\n record(status, status, \"close.destroy\");\n c.stream?.destroy?.();\n await ended(0);\n }\n for (const [event, listener] of listeners) c.off(event, listener);\n listeners.length = 0;\n flight.settleAll(\"the client closed with the command in flight\");\n status = \"end\";\n },\n };\n\n const declaration: Omit<Dependency, \"name\"> = {\n system: spec.system,\n knobs: {\n connect_bound: knobs.connect_bound,\n request_timeout: knobs.request_timeout,\n driver_writeoff_time: knobs.driver_writeoff_time,\n keepalive_idle: knobs.keepalive_idle,\n heartbeat_interval: knobs.heartbeat_interval,\n heartbeat_timeout: knobs.heartbeat_timeout,\n heartbeat_detection_time: detection,\n client_retry_window: knobs.client_retry_window,\n retry_base: knobs.retry_base,\n retry_cap: knobs.retry_cap,\n close_bound: knobs.close_bound,\n max_connection_age: knobs.max_connection_age,\n retrans_giveup_time: knobs.retrans_giveup_time,\n },\n operations,\n };\n\n const checks = (checkOptions: CheckOptions) =>\n stepChecks<ClientStep>(name, checkOptions, {\n // the state of the client, without a round trip\n \"local-state\": localStateCheck(() => connection?.status === \"ready\"),\n // a PING on the connection of the application: blind to nothing that the application meets\n \"round-trip\": roundTripCheck((sendOptions) => send(\"PING\", [], sendOptions)),\n // a new connection each time: it finds a server that refuses connections, but not a stalled connection of the application\n dial: dialCheck(dial, spec.host, spec.port),\n });\n\n return {\n name,\n declaration,\n handle,\n meets: meetings(name, knobs, detection),\n get status() {\n return connection === null ? \"none\" : connection.status;\n },\n joins,\n send,\n checks,\n attach: (svc, checkOptions) => attachClient(svc, name, declaration, handle, checks(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;GACP,MAAM,MAAM,GAAG,MAAM,WAAW,KAAK,MAAM,IAAI,IAAI,aAAa;GAEhE,IAAI,EAAE,WAAW,OAAO;IACtB,OAAO,QAAQ,QAAQ,eAAe;IACtC,EAAE,QAAQ,UAAU;IACpB,MAAM,MAAM,CAAC;GACf;GACA,KAAK,MAAM,CAAC,OAAO,aAAa,WAAW,EAAE,IAAI,OAAO,QAAQ;GAChE,UAAU,SAAS;GACnB,OAAO,UAAU,8CAA8C;GAC/D,SAAS;EACX;CACF;CAEA,MAAM,cAAwC;EAC5C,QAAQ,KAAK;EACb,OAAO;GACL,eAAe,MAAM;GACrB,iBAAiB,MAAM;GACvB,sBAAsB,MAAM;GAC5B,gBAAgB,MAAM;GACtB,oBAAoB,MAAM;GAC1B,mBAAmB,MAAM;GACzB,0BAA0B;GAC1B,qBAAqB,MAAM;GAC3B,YAAY,MAAM;GAClB,WAAW,MAAM;GACjB,aAAa,MAAM;GACnB,oBAAoB,MAAM;GAC1B,qBAAqB,MAAM;EAC7B;EACA;CACF;CAEA,MAAM,UAAU,iBACd,WAAuB,MAAM,cAAc;EAEzC,eAAe,sBAAsB,YAAY,WAAW,OAAO;EAEnE,cAAc,gBAAgB,gBAAgB,KAAK,QAAQ,CAAC,GAAG,WAAW,CAAC;EAE3E,MAAM,UAAU,MAAM,KAAK,MAAM,KAAK,IAAI;CAC5C,CAAC;CAEH,OAAO;EACL;EACA;EACA;EACA,OAAO,SAAS,MAAM,OAAO,SAAS;EACtC,IAAI,SAAS;GACX,OAAO,eAAe,OAAO,SAAS,WAAW;EACnD;EACA;EACA;EACA;EACA,SAAS,KAAK,iBAAiB,aAAa,KAAK,MAAM,aAAa,QAAQ,OAAO,YAAY,CAAC;EAChG,WAAW,gBAAgB,eAAe,MAAM,aAAa,aAAa,KAAK,CAAC;CAClF;AACF"}
@@ -0,0 +1,57 @@
1
+ import { ClientSocket, Factory } from "../client/core.js";
2
+ /**
3
+ * A Redis connection is the part of an ioredis client that the wrapper uses. An ioredis 6 client has
4
+ * each part. A fake for tests has them too. Thus the package depends on no type of ioredis.
5
+ */
6
+ export interface RedisConnection {
7
+ /** This text is the state of the client: wait, connecting, connect, ready, close, reconnecting or end. */
8
+ readonly status: string;
9
+ /** This socket is the socket of the current connection, when there is one. */
10
+ readonly stream?: RedisSocket | undefined;
11
+ connect(): Promise<void>;
12
+ /** This method sends one command, and gives the reply. */
13
+ call(command: string, ...args: Array<string | number>): Promise<unknown>;
14
+ quit(): Promise<unknown>;
15
+ /** This method closes the connection at once. With `true`, the client then connects again. */
16
+ disconnect(reconnect?: boolean): void;
17
+ on(event: string, listener: (...args: unknown[]) => void): unknown;
18
+ off(event: string, listener: (...args: unknown[]) => void): unknown;
19
+ }
20
+ /** A Redis socket is the socket of a client in the core: the join of the prober and the bounded close read it. */
21
+ export type RedisSocket = ClientSocket;
22
+ /**
23
+ * These are the options that the wrapper gives ioredis. Each one comes from the declaration. The
24
+ * wrapper sets each option that has an effect on a timer or on a send again, thus no default of
25
+ * ioredis decides one.
26
+ */
27
+ export interface RedisConnectionOptions {
28
+ readonly host: string;
29
+ readonly port: number;
30
+ readonly db?: number | undefined;
31
+ readonly username?: string | undefined;
32
+ readonly password?: string | undefined;
33
+ /** The wrapper connects in its own step of the startup. */
34
+ readonly lazyConnect: true;
35
+ readonly connectTimeout: number;
36
+ readonly commandTimeout: number;
37
+ /** This time destroys a socket that gives no data while a command waits. Undefined is no bound. */
38
+ readonly socketTimeout: number | undefined;
39
+ /** This time is the idle time of TCP keepalive. False is no keepalive. */
40
+ readonly keepAlive: number | false;
41
+ /** A command while the client is not ready fails at once: it did not reach the server. */
42
+ readonly enableOfflineQueue: false;
43
+ /** The client does not send again a command that can have reached the server. */
44
+ readonly autoResendUnfulfilledCommands: false;
45
+ readonly maxRetriesPerRequest: null;
46
+ readonly enableReadyCheck: true;
47
+ readonly connectionName: string;
48
+ /** This function gives the delay before the next try to connect, or null to stop. */
49
+ readonly retryStrategy: (times: number) => number | null;
50
+ }
51
+ /** A connection factory makes the connection of the client from its options. */
52
+ export type ConnectionFactory = Factory<RedisConnectionOptions, RedisConnection>;
53
+ /**
54
+ * This factory makes an ioredis client. It loads ioredis only when a client connects, thus a
55
+ * service that does not use Redis does not need ioredis.
56
+ */
57
+ export declare const ioredis: ConnectionFactory;
@@ -0,0 +1,11 @@
1
+ // src/redis/connection.ts
2
+ /**
3
+ * This factory makes an ioredis client. It loads ioredis only when a client connects, thus a
4
+ * service that does not use Redis does not need ioredis.
5
+ */
6
+ const ioredis = async (options) => {
7
+ return new (await (import("ioredis"))).default(options);
8
+ };
9
+ export { ioredis };
10
+
11
+ //# sourceMappingURL=connection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connection.js","names":[],"sources":["../../src/redis/connection.ts"],"sourcesContent":["import type { ClientSocket, Factory } from \"../client/core.ts\";\n\n/**\n * A Redis connection is the part of an ioredis client that the wrapper uses. An ioredis 6 client has\n * each part. A fake for tests has them too. Thus the package depends on no type of ioredis.\n */\nexport interface RedisConnection {\n /** This text is the state of the client: wait, connecting, connect, ready, close, reconnecting or end. */\n readonly status: string;\n /** This socket is the socket of the current connection, when there is one. */\n readonly stream?: RedisSocket | undefined;\n connect(): Promise<void>;\n /** This method sends one command, and gives the reply. */\n call(command: string, ...args: Array<string | number>): Promise<unknown>;\n quit(): Promise<unknown>;\n /** This method closes the connection at once. With `true`, the client then connects again. */\n disconnect(reconnect?: boolean): void;\n on(event: string, listener: (...args: unknown[]) => void): unknown;\n off(event: string, listener: (...args: unknown[]) => void): unknown;\n}\n\n/** A Redis socket is the socket of a client in the core: the join of the prober and the bounded close read it. */\nexport type RedisSocket = ClientSocket;\n\n/**\n * These are the options that the wrapper gives ioredis. Each one comes from the declaration. The\n * wrapper sets each option that has an effect on a timer or on a send again, thus no default of\n * ioredis decides one.\n */\nexport interface RedisConnectionOptions {\n readonly host: string;\n readonly port: number;\n readonly db?: number | undefined;\n readonly username?: string | undefined;\n readonly password?: string | undefined;\n /** The wrapper connects in its own step of the startup. */\n readonly lazyConnect: true;\n readonly connectTimeout: number;\n readonly commandTimeout: number;\n /** This time destroys a socket that gives no data while a command waits. Undefined is no bound. */\n readonly socketTimeout: number | undefined;\n /** This time is the idle time of TCP keepalive. False is no keepalive. */\n readonly keepAlive: number | false;\n /** A command while the client is not ready fails at once: it did not reach the server. */\n readonly enableOfflineQueue: false;\n /** The client does not send again a command that can have reached the server. */\n readonly autoResendUnfulfilledCommands: false;\n readonly maxRetriesPerRequest: null;\n readonly enableReadyCheck: true;\n readonly connectionName: string;\n /** This function gives the delay before the next try to connect, or null to stop. */\n readonly retryStrategy: (times: number) => number | null;\n}\n\n/** A connection factory makes the connection of the client from its options. */\nexport type ConnectionFactory = Factory<RedisConnectionOptions, RedisConnection>;\n\n/**\n * This factory makes an ioredis client. It loads ioredis only when a client connects, thus a\n * service that does not use Redis does not need ioredis.\n */\nexport const ioredis: ConnectionFactory = async (options) => {\n const loaded = (await import(\"ioredis\")) as unknown as {\n readonly default: new (options: RedisConnectionOptions) => RedisConnection;\n };\n return new loaded.default(options);\n};\n"],"mappings":";;;;;AA6DA,MAAa,UAA6B,OAAO,YAAY;CAI3D,OAAO,KAAI,OAHW,OAAO,YAAA,CAGX,QAAQ,OAAO;AACnC"}
@@ -0,0 +1,43 @@
1
+ import { Clock } from "../clock.js";
2
+ import { LimiterStore } from "../limiter/store.js";
3
+ import { RedisClient } from "./client.js";
4
+ /**
5
+ * This script decides one take in one atomic step of Redis. It does the arithmetic of `decide`, and
6
+ * it reads `TIME` of the server, the one clock of all replicas. A test can give the time in its place.
7
+ * - KEYS[1] is the state of the key. KEYS[2] is the index of the limiter, a sorted set of its keys
8
+ * by the time at which each key is free.
9
+ * - ARGV is the type of the rule, its two numbers, the cap of keys and the key. Then it has the
10
+ * time or "", and the units of the take. The store refuses a take over the capacity before the script, thus the units
11
+ * are at most the capacity.
12
+ * - The state of a bucket is its full time. The state of a window is the time of each take in it.
13
+ * - The state expires at its free time (PX), and the index lets the cap count only busy keys.
14
+ * - The reply is `{1, remaining}`, or `{0, retryAfter, cause}` with the time as text. Redis gives
15
+ * each Lua number as a whole number, thus the fraction of a millisecond goes as text.
16
+ */
17
+ export declare const LIMITER_SCRIPT = "\nlocal kind = ARGV[1]\nlocal a = tonumber(ARGV[2])\nlocal b = tonumber(ARGV[3])\nlocal cap = tonumber(ARGV[4])\nlocal member = ARGV[5]\nlocal units = tonumber(ARGV[7])\nlocal now\nif ARGV[6] == '' then\n local t = redis.call('TIME')\n now = tonumber(t[1]) * 1000 + tonumber(t[2]) / 1000\nelse\n now = tonumber(ARGV[6])\nend\nlocal TOL = 1e-6\nlocal function num(x) return string.format('%.6f', x) end\nlocal raw = redis.call('GET', KEYS[1])\nlocal full = nil\nlocal stamps = nil\nif raw then\n if kind == 'token-bucket' then\n full = tonumber(raw)\n else\n stamps = {}\n for x in string.gmatch(raw, '[^,]+') do stamps[#stamps + 1] = tonumber(x) end\n end\nend\nlocal function freeAt()\n if kind == 'token-bucket' then return full end\n if #stamps == 0 then return -math.huge end\n return stamps[#stamps] + b\nend\nif raw and freeAt() <= now then\n redis.call('DEL', KEYS[1])\n redis.call('ZREM', KEYS[2], member)\n raw = nil\n full = nil\n stamps = nil\nend\nif not raw then\n if redis.call('ZCARD', KEYS[2]) >= cap then\n redis.call('ZREMRANGEBYSCORE', KEYS[2], '-inf', num(now))\n if redis.call('ZCARD', KEYS[2]) >= cap then\n local first = redis.call('ZRANGE', KEYS[2], 0, 0, 'WITHSCORES')\n return {0, num(tonumber(first[2]) - now), 'cap'}\n end\n end\nend\nlocal remaining\nlocal state\nif kind == 'token-bucket' then\n local span = a * b\n local base = now\n if full and full > now then base = full end\n local nxt = base + a * units\n if nxt - now > span + TOL then\n return {0, num(nxt - span - now), 'limit'}\n end\n remaining = math.floor((span - (nxt - now)) / a + TOL)\n if remaining < 0 then remaining = 0 end\n full = nxt\n state = num(full)\nelse\n local live = {}\n for _, stamp in ipairs(stamps or {}) do\n if stamp + b > now + TOL then live[#live + 1] = stamp end\n end\n if #live + units > a then\n return {0, num(live[#live + units - a] + b - now), 'limit'}\n end\n for _ = 1, units do live[#live + 1] = now end\n remaining = a - #live\n stamps = live\n local parts = {}\n for i, stamp in ipairs(live) do parts[i] = num(stamp) end\n state = table.concat(parts, ',')\nend\nlocal free = freeAt()\nlocal ttl = math.ceil(free - now)\nif ttl < 1 then ttl = 1 end\nredis.call('SET', KEYS[1], state, 'PX', ttl)\nredis.call('ZADD', KEYS[2], num(free), member)\nif redis.call('PTTL', KEYS[2]) < ttl then redis.call('PEXPIRE', KEYS[2], ttl) end\nreturn {1, remaining}\n";
18
+ /** These options make a store of a limiter in Redis. */
19
+ export interface RedisLimiterOptions {
20
+ /** This text starts the name of each key of the store in Redis, for example `limit:`. It has no braces. */
21
+ readonly prefix: string;
22
+ /**
23
+ * This clock replaces `TIME` of the server, for a test that compares the store with `decide`. Without
24
+ * it, the script reads `TIME`, thus each replica gets the one clock of the store.
25
+ */
26
+ readonly clock?: Clock | undefined;
27
+ }
28
+ /** A Redis client part is the part of a Redis client that the store uses: `send`. */
29
+ export type RedisSender = Pick<RedisClient, "send">;
30
+ /**
31
+ * This function makes a store that the replicas share, in Redis 7. Each take is one `EVAL` of
32
+ * `LIMITER_SCRIPT`, with all of its units. The client does not send it again, because a second take
33
+ * counts two times.
34
+ * - The names of the keys have the limiter in braces, a hash tag. Thus the state and the index of a
35
+ * limiter are in one slot of a Redis Cluster.
36
+ * - Each state expires at the time that the key is free, thus the eviction is exact, as in the memory
37
+ * store. The index of the limiter bounds the count of busy keys to `maxKeys`.
38
+ * - A reply of an error, an outcome that is not certain, or a reply of another shape rejects the
39
+ * take of the store. `keyedLimiter` then applies the `onStoreFailure` of the spec.
40
+ * - `TIME` is the wall clock of the Redis host, not a monotonic clock. Thus a step of that clock
41
+ * moves the counts of each key. The replicas still share one clock.
42
+ */
43
+ export declare const redisLimiterStore: (client: RedisSender, options: RedisLimiterOptions) => LimiterStore;