@mark1russell7/service 0.8.19 → 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 (331) hide show
  1. package/build/backoff.d.ts +44 -2
  2. package/build/{builder-zO48Vgoj.d.ts → builder.d.ts} +14 -101
  3. package/build/builder.js +499 -0
  4. package/build/builder.js.map +1 -0
  5. package/build/{call-context-DDhcVvn5.d.ts → call-context.d.ts} +3 -4
  6. package/build/channel.d.ts +1 -1
  7. package/build/{core-BSzt4RI2.d.ts → client/core.d.ts} +32 -61
  8. package/build/{machine-BhVeHr_m.js → client/core.js} +4 -153
  9. package/build/client/core.js.map +1 -0
  10. package/build/{dial-ChwIcvd4.d.ts → client/dial.d.ts} +3 -4
  11. package/build/client/dial.js +52 -0
  12. package/build/client/dial.js.map +1 -0
  13. package/build/client/machine.js +29 -0
  14. package/build/client/machine.js.map +1 -0
  15. package/build/client/meets.d.ts +35 -0
  16. package/build/client/meets.js +78 -0
  17. package/build/client/meets.js.map +1 -0
  18. package/build/clock.d.ts +1 -1
  19. package/build/conformance.d.ts +122 -0
  20. package/build/conformance.js +470 -0
  21. package/build/conformance.js.map +1 -0
  22. package/build/contract.d.ts +28 -0
  23. package/build/contract.js +184 -0
  24. package/build/contract.js.map +1 -0
  25. package/build/description.d.ts +161 -0
  26. package/build/description.js +11 -0
  27. package/build/description.js.map +1 -0
  28. package/build/drains.js +35 -0
  29. package/build/drains.js.map +1 -0
  30. package/build/events.d.ts +25 -0
  31. package/build/fakes.d.ts +43 -0
  32. package/build/fakes.js +93 -0
  33. package/build/fakes.js.map +1 -0
  34. package/build/grpc/client.d.ts +153 -0
  35. package/build/grpc/client.js +474 -0
  36. package/build/grpc/client.js.map +1 -0
  37. package/build/grpc/connection.d.ts +97 -0
  38. package/build/grpc/connection.js +59 -0
  39. package/build/grpc/connection.js.map +1 -0
  40. package/build/grpc/machine.d.ts +12 -0
  41. package/build/grpc/machine.js +149 -0
  42. package/build/grpc/machine.js.map +1 -0
  43. package/build/grpc/meets.d.ts +14 -0
  44. package/build/grpc/meets.js +105 -0
  45. package/build/grpc/meets.js.map +1 -0
  46. package/build/grpc/starting.d.ts +33 -0
  47. package/build/grpc/starting.js +89 -0
  48. package/build/grpc/starting.js.map +1 -0
  49. package/build/grpc.d.ts +9 -303
  50. package/build/grpc.js +7 -854
  51. package/build/health.d.ts +93 -0
  52. package/build/health.js +223 -0
  53. package/build/health.js.map +1 -0
  54. package/build/heartbeat.d.ts +1 -1
  55. package/build/host/discovery.d.ts +61 -0
  56. package/build/host/discovery.js +113 -0
  57. package/build/host/discovery.js.map +1 -0
  58. package/build/host/env.d.ts +14 -0
  59. package/build/host/env.js +57 -0
  60. package/build/host/env.js.map +1 -0
  61. package/build/host/fakes.d.ts +82 -0
  62. package/build/host/fakes.js +239 -0
  63. package/build/host/fakes.js.map +1 -0
  64. package/build/host/group.d.ts +142 -0
  65. package/build/host/group.js +517 -0
  66. package/build/host/group.js.map +1 -0
  67. package/build/host/install.d.ts +96 -0
  68. package/build/host/install.js +330 -0
  69. package/build/host/install.js.map +1 -0
  70. package/build/host/lock.d.ts +78 -0
  71. package/build/host/lock.js +190 -0
  72. package/build/host/lock.js.map +1 -0
  73. package/build/host/logs.d.ts +26 -0
  74. package/build/host/logs.js +48 -0
  75. package/build/host/logs.js.map +1 -0
  76. package/build/host/node.d.ts +14 -0
  77. package/build/host/node.js +309 -0
  78. package/build/host/node.js.map +1 -0
  79. package/build/{ports-B1ayTL-j.d.ts → host/ports.d.ts} +15 -16
  80. package/build/host/ports.js +17 -0
  81. package/build/host/ports.js.map +1 -0
  82. package/build/host/probes.d.ts +51 -0
  83. package/build/host/probes.js +139 -0
  84. package/build/host/probes.js.map +1 -0
  85. package/build/host/processes.d.ts +32 -0
  86. package/build/host/processes.js +63 -0
  87. package/build/host/processes.js.map +1 -0
  88. package/build/host/render.d.ts +84 -0
  89. package/build/host/render.js +235 -0
  90. package/build/host/render.js.map +1 -0
  91. package/build/host/watch.d.ts +90 -0
  92. package/build/host/watch.js +165 -0
  93. package/build/host/watch.js.map +1 -0
  94. package/build/host.d.ts +13 -671
  95. package/build/host.js +12 -2126
  96. package/build/http/answers.js +29 -0
  97. package/build/http/answers.js.map +1 -0
  98. package/build/http/fake-server.js +61 -0
  99. package/build/http/fake-server.js.map +1 -0
  100. package/build/http/outcome.d.ts +115 -0
  101. package/build/http/outcome.js +325 -0
  102. package/build/http/outcome.js.map +1 -0
  103. package/build/http/probes.d.ts +83 -0
  104. package/build/http/probes.js +232 -0
  105. package/build/http/probes.js.map +1 -0
  106. package/build/http/transport.d.ts +165 -0
  107. package/build/http/transport.js +517 -0
  108. package/build/http/transport.js.map +1 -0
  109. package/build/http-client/client.d.ts +121 -0
  110. package/build/http-client/client.js +330 -0
  111. package/build/http-client/client.js.map +1 -0
  112. package/build/http-client/connection.d.ts +78 -0
  113. package/build/http-client/connection.js +54 -0
  114. package/build/http-client/connection.js.map +1 -0
  115. package/build/http-client/machine.d.ts +14 -0
  116. package/build/http-client/machine.js +109 -0
  117. package/build/http-client/machine.js.map +1 -0
  118. package/build/http-client/meets.d.ts +11 -0
  119. package/build/http-client/meets.js +74 -0
  120. package/build/http-client/meets.js.map +1 -0
  121. package/build/http-client/session.d.ts +87 -0
  122. package/build/http-client/session.js +99 -0
  123. package/build/http-client/session.js.map +1 -0
  124. package/build/http-client/starting.d.ts +25 -0
  125. package/build/http-client/starting.js +65 -0
  126. package/build/http-client/starting.js.map +1 -0
  127. package/build/http-client.d.ts +9 -330
  128. package/build/http-client.js +8 -707
  129. package/build/http.d.ts +5 -353
  130. package/build/http.js +3 -1086
  131. package/build/identity.d.ts +16 -0
  132. package/build/identity.js +44 -0
  133. package/build/identity.js.map +1 -0
  134. package/build/index.d.ts +35 -412
  135. package/build/index.js +24 -3277
  136. package/build/knobs.d.ts +1 -0
  137. package/build/{knobs-BJcz6m01.js → knobs.js} +2 -34
  138. package/build/knobs.js.map +1 -0
  139. package/build/latch.d.ts +29 -0
  140. package/build/latch.js +122 -0
  141. package/build/latch.js.map +1 -0
  142. package/build/{rules-HyFCBStQ.d.ts → law.d.ts} +19 -37
  143. package/build/law.js +149 -0
  144. package/build/law.js.map +1 -0
  145. package/build/lifecycle.d.ts +144 -0
  146. package/build/lifecycle.js +411 -0
  147. package/build/lifecycle.js.map +1 -0
  148. package/build/limiter/machine.d.ts +40 -0
  149. package/build/limiter/machine.js +279 -0
  150. package/build/limiter/machine.js.map +1 -0
  151. package/build/{policy-CBcK2XGg.d.ts → limiter/policy.d.ts} +28 -29
  152. package/build/{policy-UYALkqVq.js → limiter/policy.js} +10 -9
  153. package/build/limiter/policy.js.map +1 -0
  154. package/build/{limiter-BNKnwzeY.d.ts → limiter/quota.d.ts} +32 -74
  155. package/build/{limiter-DrM0PQV9.js → limiter/quota.js} +3 -418
  156. package/build/limiter/quota.js.map +1 -0
  157. package/build/{store-DFwFKrsB.d.ts → limiter/store.d.ts} +10 -11
  158. package/build/limiter/store.js +145 -0
  159. package/build/limiter/store.js.map +1 -0
  160. package/build/limiter.d.ts +4 -3
  161. package/build/limiter.js +4 -2
  162. package/build/lint.d.ts +152 -0
  163. package/build/lint.js +576 -0
  164. package/build/lint.js.map +1 -0
  165. package/build/logger.d.ts +71 -0
  166. package/build/logger.js +183 -0
  167. package/build/logger.js.map +1 -0
  168. package/build/machines.d.ts +41 -0
  169. package/build/machines.js +451 -0
  170. package/build/machines.js.map +1 -0
  171. package/build/metrics.d.ts +53 -0
  172. package/build/metrics.js +111 -0
  173. package/build/metrics.js.map +1 -0
  174. package/build/mongodb/client.d.ts +131 -0
  175. package/build/mongodb/client.js +388 -0
  176. package/build/mongodb/client.js.map +1 -0
  177. package/build/mongodb/connection.d.ts +112 -0
  178. package/build/mongodb/connection.js +12 -0
  179. package/build/mongodb/connection.js.map +1 -0
  180. package/build/mongodb/machine.d.ts +14 -0
  181. package/build/mongodb/machine.js +122 -0
  182. package/build/mongodb/machine.js.map +1 -0
  183. package/build/mongodb/meets.d.ts +15 -0
  184. package/build/mongodb/meets.js +103 -0
  185. package/build/mongodb/meets.js.map +1 -0
  186. package/build/mongodb/starting.d.ts +29 -0
  187. package/build/mongodb/starting.js +77 -0
  188. package/build/mongodb/starting.js.map +1 -0
  189. package/build/mongodb.d.ts +8 -296
  190. package/build/mongodb.js +7 -682
  191. package/build/operation.d.ts +27 -0
  192. package/build/{operation-DF73RZOI.js → operation.js} +2 -2
  193. package/build/operation.js.map +1 -0
  194. package/build/otel.d.ts +2 -2
  195. package/build/pg/client.d.ts +96 -0
  196. package/build/pg/client.js +277 -0
  197. package/build/pg/client.js.map +1 -0
  198. package/build/pg/connection.d.ts +75 -0
  199. package/build/pg/connection.js +11 -0
  200. package/build/pg/connection.js.map +1 -0
  201. package/build/pg/machine.d.ts +13 -0
  202. package/build/pg/machine.js +111 -0
  203. package/build/pg/machine.js.map +1 -0
  204. package/build/pg/meets.d.ts +14 -0
  205. package/build/pg/meets.js +83 -0
  206. package/build/pg/meets.js.map +1 -0
  207. package/build/pg/starting.d.ts +26 -0
  208. package/build/pg/starting.js +62 -0
  209. package/build/pg/starting.js.map +1 -0
  210. package/build/pg.d.ts +8 -219
  211. package/build/pg.js +7 -525
  212. package/build/poller.d.ts +9 -0
  213. package/build/poller.js +152 -0
  214. package/build/poller.js.map +1 -0
  215. package/build/process.d.ts +114 -0
  216. package/build/process.js +170 -0
  217. package/build/process.js.map +1 -0
  218. package/build/profiles.d.ts +68 -0
  219. package/build/profiles.js +120 -0
  220. package/build/profiles.js.map +1 -0
  221. package/build/{queue-DXdw1vLO.d.ts → queue.d.ts} +16 -29
  222. package/build/queue.js +279 -0
  223. package/build/queue.js.map +1 -0
  224. package/build/rabbitmq/client.d.ts +144 -0
  225. package/build/rabbitmq/client.js +426 -0
  226. package/build/rabbitmq/client.js.map +1 -0
  227. package/build/rabbitmq/connection.d.ts +91 -0
  228. package/build/rabbitmq/connection.js +15 -0
  229. package/build/rabbitmq/connection.js.map +1 -0
  230. package/build/rabbitmq/machine.d.ts +13 -0
  231. package/build/rabbitmq/machine.js +159 -0
  232. package/build/rabbitmq/machine.js.map +1 -0
  233. package/build/rabbitmq/meets.d.ts +12 -0
  234. package/build/rabbitmq/meets.js +96 -0
  235. package/build/rabbitmq/meets.js.map +1 -0
  236. package/build/rabbitmq/starting.d.ts +27 -0
  237. package/build/rabbitmq/starting.js +67 -0
  238. package/build/rabbitmq/starting.js.map +1 -0
  239. package/build/rabbitmq.d.ts +8 -283
  240. package/build/rabbitmq.js +7 -742
  241. package/build/redis/client.d.ts +86 -0
  242. package/build/redis/client.js +285 -0
  243. package/build/redis/client.js.map +1 -0
  244. package/build/redis/connection.d.ts +57 -0
  245. package/build/redis/connection.js +11 -0
  246. package/build/redis/connection.js.map +1 -0
  247. package/build/redis/limiter.d.ts +43 -0
  248. package/build/redis/limiter.js +164 -0
  249. package/build/redis/limiter.js.map +1 -0
  250. package/build/redis/machine.d.ts +12 -0
  251. package/build/redis/machine.js +144 -0
  252. package/build/redis/machine.js.map +1 -0
  253. package/build/redis/meets.d.ts +11 -0
  254. package/build/redis/meets.js +75 -0
  255. package/build/redis/meets.js.map +1 -0
  256. package/build/redis/operations.d.ts +5 -0
  257. package/build/redis/operations.js +114 -0
  258. package/build/redis/operations.js.map +1 -0
  259. package/build/redis.d.ts +10 -207
  260. package/build/redis.js +9 -771
  261. package/build/requests.d.ts +66 -0
  262. package/build/requests.js +279 -0
  263. package/build/requests.js.map +1 -0
  264. package/build/retrier.d.ts +62 -0
  265. package/build/{retrier-Dnjhvxol.js → retrier.js} +2 -2
  266. package/build/retrier.js.map +1 -0
  267. package/build/routes.d.ts +35 -0
  268. package/build/routes.js +77 -0
  269. package/build/routes.js.map +1 -0
  270. package/build/rules.d.ts +19 -2
  271. package/build/stops.d.ts +51 -0
  272. package/build/stops.js +86 -0
  273. package/build/stops.js.map +1 -0
  274. package/build/testing.d.ts +8 -270
  275. package/build/testing.js +4 -1027
  276. package/build/testing.js.map +1 -1
  277. package/build/timing.d.ts +63 -0
  278. package/build/{timing-DZl36uXs.js → timing.js} +2 -2
  279. package/build/timing.js.map +1 -0
  280. package/build/units.d.ts +17 -0
  281. package/build/units.js +236 -0
  282. package/build/units.js.map +1 -0
  283. package/build/watchdog.d.ts +34 -0
  284. package/build/watchdog.js +53 -0
  285. package/build/watchdog.js.map +1 -0
  286. package/build/websocket/client.d.ts +136 -0
  287. package/build/websocket/client.js +422 -0
  288. package/build/websocket/client.js.map +1 -0
  289. package/build/websocket/connection.d.ts +83 -0
  290. package/build/websocket/connection.js +57 -0
  291. package/build/websocket/connection.js.map +1 -0
  292. package/build/websocket/machine.d.ts +12 -0
  293. package/build/websocket/machine.js +155 -0
  294. package/build/websocket/machine.js.map +1 -0
  295. package/build/websocket/meets.d.ts +14 -0
  296. package/build/websocket/meets.js +92 -0
  297. package/build/websocket/meets.js.map +1 -0
  298. package/build/websocket/starting.d.ts +25 -0
  299. package/build/websocket/starting.js +69 -0
  300. package/build/websocket/starting.js.map +1 -0
  301. package/build/websocket.d.ts +9 -264
  302. package/build/websocket.js +8 -774
  303. package/build/worker.d.ts +92 -0
  304. package/build/worker.js +153 -0
  305. package/build/worker.js.map +1 -0
  306. package/package.json +4 -3
  307. package/build/backoff-QTRGfkEK.d.ts +0 -45
  308. package/build/clock-DpVgpY4h.d.ts +0 -2
  309. package/build/grpc.js.map +0 -1
  310. package/build/host.js.map +0 -1
  311. package/build/http-client.js.map +0 -1
  312. package/build/http.js.map +0 -1
  313. package/build/index.js.map +0 -1
  314. package/build/knobs-BJcz6m01.js.map +0 -1
  315. package/build/lifecycle-D0J-zwZF.d.ts +0 -374
  316. package/build/limiter-DrM0PQV9.js.map +0 -1
  317. package/build/logger-B6drv9w0.d.ts +0 -488
  318. package/build/machine-BhVeHr_m.js.map +0 -1
  319. package/build/mongodb.js.map +0 -1
  320. package/build/operation-DF73RZOI.js.map +0 -1
  321. package/build/pg.js.map +0 -1
  322. package/build/policy-UYALkqVq.js.map +0 -1
  323. package/build/process-7R9M29wN.js +0 -437
  324. package/build/process-7R9M29wN.js.map +0 -1
  325. package/build/rabbitmq.js.map +0 -1
  326. package/build/redis.js.map +0 -1
  327. package/build/requests-DD2ALv0_.js +0 -583
  328. package/build/requests-DD2ALv0_.js.map +0 -1
  329. package/build/retrier-Dnjhvxol.js.map +0 -1
  330. package/build/timing-DZl36uXs.js.map +0 -1
  331. package/build/websocket.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"mongodb.js","names":["knob","t"],"sources":["../src/mongodb/connection.ts","../src/mongodb/meets.ts","../src/mongodb/client.ts","../src/mongodb/machine.ts","../src/mongodb/starting.ts"],"sourcesContent":["import type { Factory } from \"../client/core.ts\";\n\n/** A document is a BSON document as the driver gives it: a command, or the reply of the server. */\nexport type MongoDocument = Record<string, unknown>;\n\n/** A database is the part of a `Db` of the driver that the wrapper uses: `command` sends one command. */\nexport interface MongoDb {\n /** This method sends a command. Its signal ends the command, and an abort during the read closes the connection. */\n command(document: MongoDocument, options?: { readonly signal?: AbortSignal | undefined }): Promise<MongoDocument>;\n}\n\n/** A server is the part of a `ServerDescription` that the wrapper reads: its type, for example `RSPrimary`. */\nexport interface MongoServer {\n readonly type: string;\n}\n\n/** These are the events of the driver that the wrapper listens to, by name, with the fields that it reads. */\nexport interface MongoEvents {\n /** The view of the topology changed. A writable server is a primary, a standalone, a mongos or a load balancer. */\n topologyDescriptionChanged: { readonly newDescription: { readonly servers: ReadonlyMap<string, MongoServer> } };\n /** A connection of the pool finished its handshake. `connectionId` is the id that the pool gives. */\n connectionReady: { readonly connectionId: number | string; readonly address: string };\n /** A command went to a connection. `serverConnectionId` is the id that the server gave in its hello. */\n commandStarted: {\n readonly connectionId?: number | string | undefined;\n readonly address: string;\n readonly serverConnectionId?: bigint | number | null | undefined;\n };\n /** The pool of a server closed its connections, for example at the write-off of the server. */\n connectionPoolCleared: { readonly address: string; readonly interruptInUseConnections?: boolean | undefined };\n /** A hello of the monitor failed. `connectionId` is the address of the server. */\n serverHeartbeatFailed: { readonly connectionId: string; readonly failure: Error };\n /** An error of the topology. In Node, an error with no listener throws. */\n error: Error;\n}\n\n/** An event name is a name of `MongoEvents`. */\nexport type MongoEventName = keyof MongoEvents;\n\n/**\n * A driver client is the part of a `MongoClient` that the wrapper uses. A `MongoClient` of the\n * driver 7 has each part. A fake for tests has them too. Thus the package depends on no type of the driver.\n */\nexport interface MongoDriverClient {\n /** This method opens the topology and waits for a server to select. A failure closes the topology, and a later command opens it again. */\n connect(): Promise<unknown>;\n /** This method fails the commands in flight, sends `endSessions` to a selectable server, and closes the topology. */\n close(): Promise<void>;\n db(name: string): MongoDb;\n on<E extends MongoEventName>(event: E, listener: (payload: MongoEvents[E]) => void): unknown;\n off<E extends MongoEventName>(event: E, listener: (payload: MongoEvents[E]) => void): unknown;\n}\n\n/**\n * These are the options that the wrapper gives `MongoClient`. Each one comes from the declaration.\n * The wrapper sets each option that has an effect on a timer, thus no default of the driver decides\n * one. A knob of the driver at 0 has no timer. The wrapper writes \"infinite\" as 0, and it refuses a bound of 0.\n */\nexport interface MongoDriverOptions {\n /** The server shows this name in `$currentOp` and in its log, thus the prober can join on it too. */\n readonly appName: string;\n readonly replicaSet?: string | undefined;\n readonly auth?: { readonly username: string; readonly password: string } | undefined;\n readonly authSource?: string | undefined;\n readonly maxPoolSize: number;\n readonly minPoolSize: number;\n /** This time bounds the TCP connect and the handshake of each connection, and of the monitor. */\n readonly connectTimeoutMS: number;\n /** This time bounds a read on a connection that has a command in flight. At its end, the driver closes the connection. */\n readonly socketTimeoutMS: number;\n /** This time bounds the wait for a server to select, for each command and for `connect`. */\n readonly serverSelectionTimeoutMS: number;\n /** This time is the period of the monitor, and the wait of its streaming hello. */\n readonly heartbeatFrequencyMS: number;\n /** This time bounds a checkout from a full pool. 0 is no bound. */\n readonly waitQueueTimeoutMS: number;\n /** A checkout ends an idle connection older than this time. 0 is no limit. The driver has no timer for it. */\n readonly maxIdleTimeMS: number;\n /** This time is the idle time of TCP keepalive. The driver always turns keepalive on. Node truncates the time to whole seconds. */\n readonly keepAliveInitialDelay: number;\n /** The monitor streams its hello, as in the cells. Thus a silent server is written off at `connectTimeoutMS + heartbeatFrequencyMS`. */\n readonly serverMonitoringMode: \"stream\";\n /** The driver does not send a command again by itself. The core sends again only an idempotent operation. */\n readonly retryReads: false;\n readonly retryWrites: false;\n /** The driver emits `commandStarted`, which gives the id of the server for each connection (D1). */\n readonly monitorCommands: true;\n}\n\n/** These are the arguments of `new MongoClient(url, options)`. The URL gives only the hosts. */\nexport interface MongoConnectOptions {\n readonly url: string;\n readonly options: MongoDriverOptions;\n}\n\n/** A driver factory makes the client of the driver from its options. */\nexport type MongoFactory = Factory<MongoConnectOptions, MongoDriverClient>;\n\n/**\n * This factory makes a `MongoClient`. It loads the driver only when a client connects, thus a\n * service that does not use MongoDB does not need it. The specifier is a value, thus the package\n * needs no types of the driver. The driver gives `MongoClient` as a named export.\n */\nexport const nodeMongo: MongoFactory = async ({ url, options }) => {\n const specifier = \"mongodb\";\n const loaded = (await import(specifier)) as {\n readonly MongoClient: new (url: string, options: MongoDriverOptions) => MongoDriverClient;\n };\n return new loaded.MongoClient(url, options);\n};\n","import { quantity } from \"@mark1russell7/quantity\";\nimport type { Detector, Meeting } from \"../client/meets.ts\";\nimport { WHAT, immediate, keepaliveAnswered, keepaliveReset, keepaliveSilent, kernelGiveUp } from \"../client/meets.ts\";\nimport { ms } from \"../client/core.ts\";\nimport type { MongoKnobs } from \"./client.ts\";\n\n/**\n * This function gives the manifestations that a MongoDB client can meet, and the detectors of each,\n * from its knobs. The cells of S1 measured them on the driver 7.7.0 against mongod 9.0.4:\n * - The monitor writes off a silent server at `connectTimeoutMS + heartbeatFrequencyMS` after its last\n * answer: 40.002 s at the defaults, and 7 s for 5 s + 2 s. The driver then clears the pool, and\n * fails each command in flight. With `connectTimeoutMS` 0, nothing found a freeze in 60 s.\n * - At `tcp_retries2 = 5`, the kernel gave up at 12.936 s.\n * - A `keepAliveInitialDelay` of 27 s ended an idle stream at 37.255 s.\n *\n * The monitor tests the server, not each connection of the pool. Thus a write-off finds a failure of\n * the server in flight and idle, and a failure of one connection waits for its own detector.\n */\nexport const mongoMeetings = (name: string, knobs: MongoKnobs): Meeting[] => {\n const writeoffTime = quantity((ms(knobs.connect_bound) + ms(knobs.heartbeat_interval)) / 1000, \"s\");\n const writeoff = (situation: \"in flight\" | \"idle\"): Detector => ({\n by: \"driver_writeoff_time\",\n within: writeoffTime,\n situation,\n effect:\n situation === \"in flight\"\n ? `the monitor writes the server off, and the driver fails the command as indeterminate. ${name} goes to failing`\n : `the monitor writes the server off, and the driver closes each idle connection. ${name} goes to failing`,\n });\n const read: Detector = {\n by: \"request_timeout\",\n within: knobs.request_timeout,\n situation: \"in flight\",\n effect: \"the command fails with a timeout of the socket, as indeterminate, and the driver closes the connection\",\n };\n const idleExpiry: Detector = {\n by: \"pool_idle_expiry\",\n within: knobs.pool_idle_expiry,\n situation: \"idle\",\n effect: \"the next checkout ends the idle connection, thus no command gets the dead connection\",\n };\n const giveUp = kernelGiveUp(knobs.retrans_giveup_time, \"the command fails as indeterminate\");\n const silent = (manifestation: \"blackhole\" | \"freeze-host\"): Meeting => ({\n manifestation,\n what: WHAT[manifestation],\n detectors: [writeoff(\"in flight\"), read, giveUp, writeoff(\"idle\"), idleExpiry, keepaliveSilent(knobs.keepalive_idle)],\n });\n return [\n {\n manifestation: \"rst\",\n what: WHAT.rst,\n detectors: [\n immediate(\"in flight\", \"the command fails with ECONNRESET, and the driver clears the pool\"),\n {\n by: \"heartbeat_interval\",\n within: knobs.heartbeat_interval,\n situation: \"idle\",\n effect: \"the next answer of the monitor gets a reset, thus the driver writes the server off and clears the pool\",\n },\n idleExpiry,\n keepaliveReset(knobs.keepalive_idle),\n ],\n },\n {\n manifestation: \"fin\",\n what: WHAT.fin,\n detectors: [\n immediate(\"in flight\", \"the command fails: the connection closed\"),\n immediate(\"idle\", \"the stream of the monitor closes, thus the driver writes the server off and clears the pool\"),\n ],\n },\n silent(\"blackhole\"),\n silent(\"freeze-host\"),\n {\n manifestation: \"freeze-process\",\n what: WHAT[\"freeze-process\"],\n detectors: [writeoff(\"in flight\"), read, writeoff(\"idle\"), idleExpiry, keepaliveAnswered()],\n },\n {\n manifestation: \"app-stall\",\n what: \"the server stops its replies to commands for a time, for example behind a lock, and its monitor still answers\",\n detectors: [\n {\n by: \"statement_timeout\",\n within: knobs.statement_timeout,\n situation: \"in flight\",\n effect: \"the server ends the command with error 50 (MaxTimeMSExpired), a certain outcome, and the connection stays\",\n },\n read,\n idleExpiry,\n keepaliveAnswered(),\n ],\n },\n ];\n};\n","import type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport { realClock } from \"../clock.ts\";\nimport type { Attempt, CheckOptions, Client, ClientJoin, ClientKnobs, ClientOptions, ClientSpec, ClientStep, DialFn, SendOptions, Sent } from \"../client/core.ts\";\nimport {\n ageProblems,\n attachClient,\n clientBounds,\n clientProblems,\n clientRecorder,\n deadlineProblem,\n dialCheck,\n finiteMs,\n inFlight,\n keepaliveOnProblems,\n localStateCheck,\n message,\n ms,\n notSent,\n operationTable,\n orZero,\n poolProblems,\n roundTripCheck,\n sendWithReissue,\n stepChecks,\n timeProblems,\n wholeProblems,\n withinBound,\n zeroProblems,\n} from \"../client/core.ts\";\nimport type { Judge } from \"../client/dial.ts\";\nimport { helloDial } from \"../client/dial.ts\";\nimport type { Dependency } from \"../description.ts\";\nimport type { DependencyHandle } from \"../lifecycle.ts\";\nimport type { Operation } from \"../operation.ts\";\nimport type { MongoConnectOptions, MongoDocument, MongoDriverClient, MongoEventName, MongoEvents, MongoFactory } from \"./connection.ts\";\nimport { nodeMongo } from \"./connection.ts\";\nimport { mongoMeetings } from \"./meets.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. A bound that nobody gives is\n * \"infinite\", not zero. `MONGO_STARTING_KNOBS` gives a declaration from the cells of S1. The knobs\n * that each client has come from the core.\n */\nexport interface MongoKnobs extends ClientKnobs {\n /** This time bounds the TCP connect and the handshake of each connection (`connectTimeoutMS`). It also bounds the wait of the startup. */\n readonly connect_bound: Quantity;\n /** This time bounds a read of a command in flight (`socketTimeoutMS`). At its end, the driver closes the connection. */\n readonly request_timeout: Quantity;\n /**\n * This time is the deadline of each command on the server (`maxTimeMS`). The wrapper writes it in\n * each command. The server then ends the command with error 50, a certain outcome. \"infinite\" sends no deadline.\n */\n readonly statement_timeout: Extent;\n /** This time is the period of the monitor (`heartbeatFrequencyMS`). The driver takes 500 ms at least. */\n readonly heartbeat_interval: Quantity;\n /**\n * This time bounds the wait for a writable server (`serverSelectionTimeoutMS`). A command waits\n * through a failover in this time, thus it is the retry window of the client (O29).\n */\n readonly client_retry_window: Quantity;\n /** This time bounds a checkout from a full pool (`waitQueueTimeoutMS`). */\n readonly checkout_timeout: Extent;\n /** A checkout ends an idle connection older than this time (`maxIdleTimeMS`). The driver checks it only at a checkout. */\n readonly pool_idle_expiry: Extent;\n /** This time is the idle time of TCP keepalive (`keepAliveInitialDelay`), in whole seconds. The driver always turns keepalive on. */\n readonly keepalive_idle: Extent;\n /** The driver has no age for a connection, thus this knob must be \"infinite\". */\n readonly max_connection_age: Extent;\n /** This time bounds the close of the client at the shutdown. */\n readonly close_bound: Quantity;\n}\n\n/** A seed is one more host that the driver connects to first, for example a member of a replica set. */\nexport interface MongoSeed {\n readonly host: string;\n readonly port: number;\n}\n\n/** A MongoDB client spec is the declaration of one MongoDB client: where it connects, its pool, and its knobs. */\nexport interface MongoClientSpec extends ClientSpec<MongoKnobs> {\n /** This name is the database of the commands of the client. */\n readonly database: string;\n readonly username?: string | undefined;\n /** This name is the database of the user. The default of the driver is `database`, or `admin`. */\n readonly authSource?: string | undefined;\n readonly replicaSet?: string | undefined;\n /** These hosts are more seeds of the topology, after `host` and `port`. */\n readonly seeds?: readonly MongoSeed[] | undefined;\n /** These counts are the sizes of the pool of each server: at most `max` connections, and `min` that the driver keeps open. */\n readonly pool: { readonly max: number; readonly min: number };\n /**\n * These operations are the commands of the service, by name, with their idempotency. A command\n * name does not tell if a command changes a state, for example an `aggregate` with `$merge`. Thus\n * the client sends again only a command that this table names.\n */\n readonly operations?: Readonly<Record<string, Operation>> | undefined;\n}\n\n/** These options make a client. Without them, it uses the driver, the real clock, and a dial with a hello. */\nexport type MongoClientOptions = ClientOptions<MongoFactory>;\n\n/**\n * A join is one connection of the pool, when its handshake is done (D1, D2). The prober joins its\n * kernel records to the server's view of the connection through it. The driver gives no socket,\n * thus the local address and port are null. The server's view is the connection id of its hello.\n */\nexport interface MongoJoin extends ClientJoin {\n /** This text is the address of the server, as `host:port`. */\n readonly address: string;\n /** This number is the connection id that the server gave, from the first command on the connection. Null until that command. */\n readonly serverConnectionId: number | null;\n}\n\n/** The steps that the MongoDB client gives a check for. A pool of the driver has no checkout that the wrapper can use. */\nexport type MongoStep = ClientStep;\n\n/** A MongoDB client is a dependency of a service: its declaration, its handle, its checks and its commands. */\nexport interface MongoClient extends Client<MongoStep, MongoJoin> {\n /** This text is the state of the client, as `MONGO_CLIENT_MACHINE` names it. */\n readonly status: string;\n /**\n * This method sends a command to the database of the spec, and gives its outcome in three values.\n * `operation` names the command in the table of operations. The client sends again only an\n * idempotent operation, one time at most, after an outcome that is not certain.\n */\n command(operation: string, document: MongoDocument, options?: SendOptions): Promise<Sent<MongoDocument>>;\n}\n\n/** The driver takes a period of the monitor of 500 ms at least. */\nconst LEAST_HEARTBEAT_MS = 500;\n\n/** This function gives the problems of a spec: the knobs that the driver cannot use. */\nexport const specProblems = (name: string, spec: MongoClientSpec): string[] => {\n const { knobs } = spec;\n const problems = [\n ...timeProblems(name, knobs),\n // the driver reads 0 as no timer, thus a bound of 0 is not a bound\n ...zeroProblems(name, \"the driver\", knobs, {\n bounded: [\"connect_bound\", \"request_timeout\", \"heartbeat_interval\", \"client_retry_window\", \"close_bound\"],\n open: [\"statement_timeout\", \"checkout_timeout\", \"pool_idle_expiry\"],\n }),\n // the options are whole milliseconds, and Node truncates the keepalive delay to whole seconds\n ...wholeProblems(name, knobs, {\n millis: [\"connect_bound\", \"request_timeout\", \"statement_timeout\", \"heartbeat_interval\", \"client_retry_window\", \"checkout_timeout\", \"pool_idle_expiry\"],\n seconds: [\"keepalive_idle\"],\n }),\n ...poolProblems(name, spec.pool),\n ];\n if (ms(knobs.heartbeat_interval) < LEAST_HEARTBEAT_MS)\n problems.push(`${name}'s heartbeat_interval is below 500 ms, the least that the driver takes`);\n problems.push(...keepaliveOnProblems(name, knobs, \"the driver\"), ...ageProblems(name, knobs, \"the driver has no age for a connection\"));\n return problems;\n};\n\n/** This function gives the arguments of `new MongoClient` from a spec. Each timer of the driver comes from the declaration. */\nexport const mongoOptions = (name: string, spec: MongoClientSpec): MongoConnectOptions => {\n const { knobs } = spec;\n const hosts = [{ host: spec.host, port: spec.port }, ...(spec.seeds ?? [])].map((seed) => `${seed.host}:${seed.port}`);\n return {\n url: `mongodb://${hosts.join(\",\")}/`,\n options: {\n appName: name,\n ...(spec.replicaSet === undefined ? {} : { replicaSet: spec.replicaSet }),\n ...(spec.username === undefined ? {} : { auth: { username: spec.username, password: spec.password ?? \"\" } }),\n ...(spec.authSource === undefined ? {} : { authSource: spec.authSource }),\n maxPoolSize: spec.pool.max,\n minPoolSize: spec.pool.min,\n connectTimeoutMS: ms(knobs.connect_bound),\n socketTimeoutMS: ms(knobs.request_timeout),\n serverSelectionTimeoutMS: ms(knobs.client_retry_window),\n heartbeatFrequencyMS: ms(knobs.heartbeat_interval),\n waitQueueTimeoutMS: orZero(knobs.checkout_timeout),\n maxIdleTimeMS: orZero(knobs.pool_idle_expiry),\n keepAliveInitialDelay: ms(knobs.keepalive_idle),\n serverMonitoringMode: \"stream\",\n retryReads: false,\n retryWrites: false,\n monitorCommands: true,\n },\n };\n};\n\n/**\n * The bytes of an OP_MSG with the command `{ hello: 1, $db: \"admin\" }`. They are a header of 16\n * bytes with the op code 2013, the flags, a section of kind 0, and the BSON document. The server answers a\n * hello before the authentication, thus the dial needs no password.\n */\nexport const HELLO: Uint8Array = Uint8Array.of(\n // the header: the length 52, the request id 1, the response to 0, the op code 2013\n 52, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0xdd, 0x07, 0, 0,\n // the flags, and the section of kind 0\n 0, 0, 0, 0, 0,\n // the document: its length 31, the int32 `hello` 1, the string `$db` \"admin\", and its end\n 31, 0, 0, 0,\n 0x10, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0, 1, 0, 0, 0,\n 0x02, 0x24, 0x64, 0x62, 0, 6, 0, 0, 0, 0x61, 0x64, 0x6d, 0x69, 0x6e, 0,\n 0,\n);\n\n/** The sizes of the values of the BSON types that a hello reply holds, by type. A null size has a length prefix. */\nconst FIXED: Readonly<Record<number, number>> = { 0x01: 8, 0x07: 12, 0x08: 1, 0x09: 8, 0x0a: 0, 0x10: 4, 0x11: 8, 0x12: 8, 0x13: 16 };\n\n/** This function gives the value of `ok` at the top of a BSON document, or an error. */\nconst okOf = (doc: Buffer): number | Error => {\n let at = 4;\n while (at < doc.length - 1) {\n const type = doc[at]!;\n const end = doc.indexOf(0, at + 1);\n if (end < 0) return new Error(\"the hello reply has a field with no end\");\n const key = doc.toString(\"latin1\", at + 1, end);\n at = end + 1;\n if (key === \"ok\") {\n if (type === 0x01) return doc.readDoubleLE(at);\n if (type === 0x10) return doc.readInt32LE(at);\n return new Error(`the ok of the hello reply has the BSON type ${type}`);\n }\n const fixed = FIXED[type];\n if (fixed !== undefined) at += fixed;\n else if (type === 0x02) at += 4 + doc.readInt32LE(at);\n else if (type === 0x03 || type === 0x04) at += doc.readInt32LE(at);\n else if (type === 0x05) at += 5 + doc.readInt32LE(at);\n else return new Error(`the hello reply has the BSON type ${type}, which the dial does not read`);\n }\n return new Error(\"the hello reply has no ok\");\n};\n\n/**\n * This judge reads the answer to the hello. It waits for the whole message. The message must be an\n * OP_MSG with a section of kind 0, and its document must have `ok` 1.\n */\nexport const helloJudge: Judge = (received) => {\n if (received.length < 4) return \"more\";\n const length = received.readInt32LE(0);\n if (length < 26 || length > 48 * 1024 * 1024) return new Error(`the answer to the hello has a length of ${length}`);\n if (received.length < length) return \"more\";\n const opCode = received.readInt32LE(12);\n if (opCode !== 2013) return new Error(`the answer to the hello has the op code ${opCode}, not 2013`);\n if (received[20] !== 0) return new Error(\"the answer to the hello has no section of kind 0\");\n const ok = okOf(received.subarray(21, length));\n if (ok instanceof Error) return ok;\n return ok === 1 ? null : new Error(`the hello reply has ok ${ok}`);\n};\n\n/** This dial function opens a TCP connection, sends a hello, and waits for its reply. The server opens no session for it. */\nexport const helloCommandDial: DialFn = helloDial(HELLO, helloJudge);\n\n/** These errors tell that the command did not leave the client: no server, a full pool, a cleared pool, or a closed client. */\nconst NOT_SENT = new Set([\n \"MongoServerSelectionError\",\n \"MongoWaitQueueTimeoutError\",\n \"MongoPoolClearedError\",\n \"MongoPoolClosedError\",\n \"MongoServerClosedError\",\n \"MongoTopologyClosedError\",\n \"MongoNotConnectedError\",\n \"MongoClientClosedError\",\n]);\n\n/**\n * These codes of the server tell that the server interrupted the command. The causes are its\n * shutdown, a step down, or a change of the state of the replica set. A part of the command can have applied.\n */\nconst INTERRUPTED = new Set([91, 189, 11600, 11602]);\n\n/** The writable servers: a primary, a standalone, a mongos, and a load balancer. */\nconst WRITABLE = new Set([\"RSPrimary\", \"Standalone\", \"Mongos\", \"LoadBalancer\"]);\n\n/** This function gives the outcome of a reply. A write concern error tells that the write can roll back, thus it is not certain. */\nconst replyOutcome = (reply: MongoDocument): Attempt<MongoDocument> => {\n const concern = reply[\"writeConcernError\"] as { code?: unknown; errmsg?: unknown } | undefined;\n if (concern === undefined || concern === null) return { outcome: \"ok\", value: reply };\n return { outcome: \"indeterminate\", error: `write concern ${String(concern.code)} ${String(concern.errmsg)}` };\n};\n\n/**\n * This function gives the outcome of a failure of the driver. The driver names each error class,\n * thus the wrapper reads the name, and depends on no class of the driver:\n * - A failure before the command left the client is certain: it did not apply.\n * - An error of the server is certain, except an interruption, which can leave a part applied.\n * - A write concern error, a network error after the handshake, and a timeout of the socket are not certain.\n */\nexport const failureOutcome = (error: unknown): Attempt<never> => {\n const text = message(error);\n const { name, code, beforeHandshake } = (typeof error === \"object\" && error !== null ? error : {}) as {\n name?: unknown;\n code?: unknown;\n beforeHandshake?: unknown;\n };\n if (typeof name === \"string\" && NOT_SENT.has(name)) return notSent(text);\n // a network error of a new connection, before its handshake: the command did not go to it\n if (name === \"MongoNetworkError\" && beforeHandshake === true) return notSent(text);\n if (name === \"MongoServerError\" && typeof code === \"number\") {\n const said = `${code} ${text}`;\n return INTERRUPTED.has(code) ? { outcome: \"indeterminate\", error: said } : { outcome: \"error\", error: said, reply: true };\n }\n return { outcome: \"indeterminate\", error: text };\n};\n\n/** This function gives the host and the port of an address `host:port`. */\nconst endsOf = (address: string): { readonly host: string | null; readonly port: number | null } => {\n const at = address.lastIndexOf(\":\");\n const port = Number(address.slice(at + 1));\n return at < 0 || !Number.isInteger(port) ? { host: address, port: null } : { host: address.slice(0, at), port };\n};\n\n/**\n * This function makes a MongoDB client, a dependency of a service over a `MongoClient`.\n * - It sets each timer of the driver from the declaration, and it turns off the retries of the driver.\n * The client sends again only an idempotent operation of its table.\n * - It tells the outcome of a command in three values, from the name of each error of the driver.\n * - It writes the deadline of the server in each command (`maxTimeMS`), thus the server ends a slow command first (O07).\n * - It gives the state from the view of the topology: ready while a server is writable.\n * - It listens to each error of the driver. In Node, an error with no listener throws, and library code does not end the process (A5).\n * - It records the connection id of the server for each connection of the pool (D1).\n *\n * The outcomes, the second try, the commands in flight, the bounded close and the checks come from\n * the core of the clients. This entry gives what the driver does in its own way.\n */\nexport const mongoClient = (name: string, spec: MongoClientSpec, options: MongoClientOptions = {}): MongoClient => {\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 create = options.create ?? nodeMongo;\n const dial = options.dial ?? helloCommandDial;\n const operations = operationTable({}, spec.operations);\n const deadline = finiteMs(knobs.statement_timeout);\n // a command waits for a writable server in the retry window, then it reads in the request bound\n const callBound = ms(knobs.client_retry_window) + ms(knobs.request_timeout);\n\n let driver: MongoDriverClient | null = null;\n let status = \"none\";\n const joins: MongoJoin[] = [];\n // the index in `joins` of each connection, by its address and the id that the pool gives\n const joined = new Map<string, number>();\n const flight = inFlight();\n\n const emit = clientRecorder(options.record, clock, name);\n const record = (on: string, to: string = status, detail?: string): void => {\n const from = status;\n status = to;\n emit(from, to, on, detail);\n };\n const closing = (): boolean => status === \"closing\" || status === \"end\";\n\n // the state is the view of the topology: a writable server makes the client ready. The close ignores the topology\n const onTopology = (event: MongoEvents[\"topologyDescriptionChanged\"]): void => {\n const writable = [...event.newDescription.servers.values()].some((server) => WRITABLE.has(server.type));\n if (writable && (status === \"connecting\" || status === \"failing\")) record(\"topology.writable\", \"ready\");\n else if (!writable && status === \"ready\") record(\"topology.unwritable\", \"failing\");\n };\n const onReady = (event: MongoEvents[\"connectionReady\"]): void => {\n const generation = joins.length + 1;\n const { host, port } = endsOf(event.address);\n joined.set(`${event.address}#${String(event.connectionId)}`, joins.length);\n joins.push({\n generation,\n at: clock.now(),\n address: event.address,\n serverConnectionId: null,\n localAddress: null,\n localPort: null,\n remoteAddress: host,\n remotePort: port,\n });\n record(\"join\", status, `generation ${generation}, ${event.address}`);\n };\n // the hello of a connection gives the id of the server, and the driver gives it only in the events of a command\n const onStarted = (event: MongoEvents[\"commandStarted\"]): void => {\n const index = joined.get(`${event.address}#${String(event.connectionId)}`);\n const id = event.serverConnectionId;\n if (index === undefined || id === null || id === undefined) return;\n joined.delete(`${event.address}#${String(event.connectionId)}`);\n joins[index] = { ...joins[index]!, serverConnectionId: Number(id) };\n };\n const onCleared = (event: MongoEvents[\"connectionPoolCleared\"]): void =>\n record(\"pool.cleared\", status, `${event.address}${event.interruptInUseConnections === true ? \", with the commands in flight\" : \"\"}`);\n const onHeartbeat = (event: MongoEvents[\"serverHeartbeatFailed\"]): void =>\n record(\"heartbeat.failed\", status, `${event.connectionId}: ${message(event.failure)}`);\n // after the end, the listener only keeps the error from a throw\n const onError = (error: Error): void => {\n if (status !== \"end\") record(\"client.error\", status, message(error));\n };\n const listeners: ReadonlyArray<readonly [MongoEventName, (payload: never) => void]> = [\n [\"topologyDescriptionChanged\", onTopology],\n [\"connectionReady\", onReady],\n [\"commandStarted\", onStarted],\n [\"connectionPoolCleared\", onCleared],\n [\"serverHeartbeatFailed\", onHeartbeat],\n ];\n\n /** This function makes one try of a command. The driver selects a server, checks out a connection, and sends the command. */\n const attempt = (document: MongoDocument, signal: AbortSignal | undefined): Promise<Attempt<MongoDocument>> => {\n const c = driver;\n if (c === null) return Promise.resolve(notSent(`${name} has not connected`));\n if (closing()) return Promise.resolve(notSent(`${name} is ${status}: 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 // the deadline of the server goes in the command. The driver adds maxTimeMS only with timeoutMS, which the wrapper does not use\n const sent = deadline === undefined || \"maxTimeMS\" in document ? document : { ...document, maxTimeMS: deadline };\n return flight.track(signal, \"the caller abandoned the command after it went to the driver\", (settle) => {\n c.db(spec.database)\n .command(sent, signal === undefined ? {} : { signal })\n .then(\n (reply) => settle(replyOutcome(reply)),\n (error: unknown) => settle(failureOutcome(error)),\n );\n });\n };\n\n const command = (operation: string, document: MongoDocument, sendOptions: SendOptions = {}): Promise<Sent<MongoDocument>> =>\n sendWithReissue({\n clock,\n bound: callBound,\n operation: operations[operation],\n options: sendOptions,\n // the second try waits in the selection of a server, thus it needs no wait before it\n attempt: (signal) => attempt(document, signal),\n onReissue: () => record(\"command.reissue\", status, operation),\n });\n\n const handle: DependencyHandle = {\n async connect(signal) {\n record(\"status.connecting\", \"connecting\");\n const c = await create(mongoOptions(name, spec));\n driver = c;\n for (const [event, listener] of listeners) c.on(event, listener as never);\n c.on(\"error\", onError);\n if (signal.aborted) throw new Error(`${name}: the service stopped before the connect`);\n // the driver waits for a server in client_retry_window. The startup waits connect_bound at most, and the connect goes on.\n // A server that is down does not stop the startup: the checks keep readiness tripped until a server is writable\n const connecting = c.connect().then(\n () => undefined,\n (error: unknown) => {\n if (!closing() && status !== \"ready\") record(\"connect.failed\", \"failing\", message(error));\n },\n );\n await withinBound(clock, ms(knobs.connect_bound), connecting);\n if (status === \"connecting\") record(\"connect.failed\", \"failing\", \"no writable server in connect_bound\");\n },\n async close() {\n const c = driver;\n if (c === null || closing()) return;\n record(\"close.request\", \"closing\");\n // the close of the driver fails the commands in flight, then waits for endSessions. Behind a\n // black hole that wait has no bound. The driver gives no socket, thus the bound cannot destroy one\n if (!(await withinBound(clock, ms(knobs.close_bound), c.close()))) record(\"close.bound\", status, \"the close of the driver goes on\");\n flight.settleAll(\"the client closed with the command in flight\");\n for (const [event, listener] of listeners) c.off(event, listener as never);\n // the error listener stays: a socket that closes later can emit an error, and with no listener it throws\n record(\"status.end\", \"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 statement_timeout: knobs.statement_timeout,\n heartbeat_interval: knobs.heartbeat_interval,\n client_retry_window: knobs.client_retry_window,\n // the stream of the monitor times out at connectTimeoutMS + heartbeatFrequencyMS: the driver then\n // marks the server unknown, clears its pool and fails the commands in flight. The cells measured 7 s for 5 s + 2 s\n driver_writeoff_time: { value: (ms(knobs.connect_bound) + ms(knobs.heartbeat_interval)) / 1000, unit: \"s\" },\n checkout_timeout: knobs.checkout_timeout,\n pool_idle_expiry: knobs.pool_idle_expiry,\n keepalive_idle: knobs.keepalive_idle,\n // the driver sends nothing on an idle connection of the pool, thus its keepalive is the only refresh of an idle flow (O03)\n idle_refresh_interval: knobs.keepalive_idle,\n max_connection_age: knobs.max_connection_age,\n close_bound: knobs.close_bound,\n retrans_giveup_time: knobs.retrans_giveup_time,\n },\n operations,\n };\n\n const checks = (checkOptions: CheckOptions<MongoStep>) =>\n stepChecks<MongoStep>(name, checkOptions, {\n // the view of the topology, without a round trip: the monitor keeps it current\n \"local-state\": localStateCheck(() => status === \"ready\"),\n // a ping through the pool of the application\n \"round-trip\": roundTripCheck((sendOptions) => command(\"check\", { ping: 1 }, sendOptions)),\n // a new connection each time, with a hello and no session\n dial: dialCheck(dial, spec.host, spec.port),\n });\n\n return {\n name,\n declaration,\n handle,\n meets: mongoMeetings(name, knobs),\n get status() {\n return status;\n },\n joins,\n command,\n checks,\n attach: (svc, checkOptions) => attachClient(svc, name, declaration, handle, checks(checkOptions)),\n problems(description) {\n // O07: the server must end a slow command first, with a certain error\n const late = deadlineProblem(name, knobs.request_timeout, knobs.statement_timeout, \"command\");\n return [...clientProblems(name, description, clientBounds(knobs)), ...(late === null ? [] : [late])];\n },\n };\n};\n","import type { Machine } from \"@mark1russell7/algebra\";\nimport { clientKnob as knob, closeTimer, transition as t } from \"../client/machine.ts\";\n\n/** The states where the driver exists and serves. */\nconst SERVING = [\"connecting\", \"ready\", \"failing\"] as const;\nconst OPEN = [...SERVING, \"closing\"] as const;\n\n/**\n * The MongoDB client of the service as a `mark1russell7.machine/1` document. It is the topology as\n * the wrapper sees it, not one connection: the document `mongodb-node` of `@mark1russell7/machines`\n * gives the monitor and each connection. The state is the view of the topology:\n * - `ready`: a server is writable: a primary, a standalone, a mongos, or a load balancer.\n * - `failing`: no server is writable, or the startup found none in `connect_bound`. The monitor\n * goes on, and a command waits for a writable server in `client_retry_window`.\n *\n * A connection that closes and a pool that the driver clears do not change the state by themselves.\n * The write-off of a server changes the view of the topology, and that changes the state. A test\n * records the transitions of the client and replays them against this document.\n */\nexport const MONGO_CLIENT_MACHINE: Machine = {\n format: \"mark1russell7.machine/1\",\n id: \"service.machine.mongodb-client\",\n title: \"The MongoDB client of the service, over a MongoClient of the driver 7\",\n layer: \"driver\",\n version: \"0.1.0\",\n sources: [{ ref: \"packages/service/src/mongodb (the client implements this document)\", rung: \"implemented\" }],\n states: {\n none: { initial: true, note: \"the client exists, and its MongoClient does not\" },\n connecting: { note: \"the monitor looks for the servers of the topology\" },\n ready: { note: \"a server is writable. A dead idle connection stays hidden until the monitor writes the server off\" },\n failing: { note: \"no server is writable. A command waits for one in client_retry_window\" },\n closing: { note: \"the close of the driver: it fails the commands in flight, sends endSessions, and closes the topology\" },\n end: { final: true, note: \"the service closed the client\" },\n },\n events: {\n \"status.connecting\": { kind: \"local\" },\n \"topology.writable\": { kind: \"rx\", note: \"the view of the topology has a writable server\" },\n \"topology.unwritable\": { kind: \"rx\", note: \"the view of the topology has no writable server, for example after a write-off or a step down\" },\n join: { kind: \"rx\", note: \"a connection of the pool finished its handshake (D1). The id of the server comes with its first command\" },\n \"connect.failed\": { kind: \"local\", note: \"the startup found no writable server in connect_bound, or the connect of the driver failed\" },\n \"pool.cleared\": { kind: \"rx\", note: \"the driver cleared the pool of a server, and with a write-off also failed its commands in flight\" },\n \"heartbeat.failed\": { kind: \"rx\", note: \"a hello of the monitor failed\" },\n \"client.error\": { kind: \"rx\", note: \"an error event of the driver\" },\n \"command.reissue\": { kind: \"local\" },\n \"close.request\": { kind: \"local\" },\n \"close.bound\": { kind: \"timer\", note: \"the close of the driver goes on after the bound, in the background\" },\n \"close.destroy\": { kind: \"local\", note: \"the client never records it: the driver gives no socket that the bound can destroy\" },\n \"status.end\": { kind: \"local\" },\n },\n knobs: {\n connect_bound: knob(\"connectTimeoutMS\"),\n close_bound: knob(\"close.bound\"),\n },\n timers: {\n connect_timeout: {\n duration: { knob: \"connect_bound\", unit: \"s\" },\n arms: [\"enter:connecting\"],\n cancels: [\"topology.writable\", \"connect.failed\"],\n fires: \"connect.failed\",\n note: \"the startup stops its wait, and the connect of the driver goes on in client_retry_window\",\n },\n close: closeTimer(),\n },\n transitions: [\n t(\"connect\", \"none\", \"status.connecting\", \"connecting\"),\n t(\"writable\", [\"connecting\", \"failing\"], \"topology.writable\", \"ready\"),\n t(\"unwritable\", \"ready\", \"topology.unwritable\", \"failing\"),\n t(\"connect-failed\", [\"connecting\", \"failing\"], \"connect.failed\", \"failing\", { timer: \"connect_timeout\" }),\n ...OPEN.map((state) => t(`join-${state}`, state, \"join\", state)),\n ...OPEN.map((state) => t(`pool-cleared-${state}`, state, \"pool.cleared\", state)),\n ...OPEN.map((state) => t(`heartbeat-failed-${state}`, state, \"heartbeat.failed\", state)),\n ...OPEN.map((state) => t(`client-error-${state}`, state, \"client.error\", state)),\n ...OPEN.map((state) => t(`reissue-${state}`, state, \"command.reissue\", state)),\n t(\"close\", [...SERVING], \"close.request\", \"closing\"),\n t(\"close-bound\", \"closing\", \"close.bound\", \"closing\", { timer: \"close\" }),\n t(\"end\", \"closing\", \"status.end\", \"end\"),\n ],\n};\n","import { STARTING_POLL } from \"../client/core.ts\";\nimport type { Poll } from \"../timing.ts\";\nimport type { MongoKnobs } from \"./client.ts\";\n\n/**\n * This poll is the poll of the checks that `MONGO_STARTING_KNOBS` fits. It is `STARTING_POLL` of\n * the core: each 5 s with a jitter of 20 %, and a timeout of 4 s (B6, O12). The poll does not depend on the driver.\n */\nexport const MONGO_STARTING_POLL: Poll = STARTING_POLL;\n\n/**\n * These knobs are a declaration to start from, from what the cells of S1 measured on the driver\n * 7.7.0 on Node 24.21.0 against mongod 9.0.4. The runtime has no defaults: a service gives these\n * knobs, or its own. Each value holds the borders that the cells measured:\n * - `connect_bound` 5 s and `heartbeat_interval` 2 s: the write-off of a silent server came 7 s after\n * its last answer, and the cells T01.border-off.75 and .76 held. At the defaults it came at 40.002 s.\n * - `request_timeout` 9.5 s: in the slowest poll of 10 s (O13). At the defaults the driver has no\n * bound on a read, and only the write-off ends the command.\n * - `statement_timeout` 9 s: below `request_timeout`, thus the server ends a slow command first,\n * with error 50 (O07).\n * - `client_retry_window` 30 s: after an election, the first write took 17 s to 18 s, and the band\n * ended at 26.58 s (T11.defaults.10). The default of the driver, 30 s, holds that band.\n * - `checkout_timeout` 5 s: a full pool fails a checkout in a startup budget. At the defaults the wait has no bound.\n * - `pool_idle_expiry` 10 s: no cell measured it. It is the bound of O03 and O01 that the pg client\n * uses: below a router that forgets an idle flow at 12 s. The driver applies it at the next checkout.\n * - `keepalive_idle` 30 s: the driver always turns keepalive on, at 120 s by default. This value\n * refreshes a held idle connection through the NAT forms of the cells (240 s and 350 s).\n * - `max_connection_age` \"infinite\": the driver has no age for a connection.\n * - `close_bound` 2 s: behind a black hole the close of the driver waits for `endSessions`.\n * - `retrans_giveup_time` 924.6 s: the give-up of Linux at `tcp_retries2 = 15`. The cells measured 12.936 s at `tcp_retries2 = 5`.\n */\nexport const MONGO_STARTING_KNOBS: MongoKnobs = {\n connect_bound: { value: 5, unit: \"s\" },\n request_timeout: { value: 9.5, unit: \"s\" },\n statement_timeout: { value: 9, unit: \"s\" },\n heartbeat_interval: { value: 2, unit: \"s\" },\n client_retry_window: { value: 30, unit: \"s\" },\n checkout_timeout: { value: 5, unit: \"s\" },\n pool_idle_expiry: { value: 10, unit: \"s\" },\n keepalive_idle: { value: 30, unit: \"s\" },\n max_connection_age: { value: \"infinite\", unit: \"s\" },\n close_bound: { value: 2, unit: \"s\" },\n retrans_giveup_time: { value: 924.6, unit: \"s\" },\n};\n"],"mappings":";;;;;;;;;AAuGA,MAAa,YAA0B,OAAO,EAAE,KAAK,cAAc;CAKjE,OAAO,KAAI,OAHW,OAAO,YAAA,CAGX,YAAY,KAAK,OAAO;AAC5C;;;;;;;;;;;;;;AC3FA,MAAa,iBAAiB,MAAc,UAAiC;CAC3E,MAAM,eAAe,UAAU,GAAG,MAAM,aAAa,IAAI,GAAG,MAAM,kBAAkB,KAAK,KAAM,GAAG;CAClG,MAAM,YAAY,eAA+C;EAC/D,IAAI;EACJ,QAAQ;EACR;EACA,QACE,cAAc,cACV,yFAAyF,KAAK,oBAC9F,kFAAkF,KAAK;CAC/F;CACA,MAAM,OAAiB;EACrB,IAAI;EACJ,QAAQ,MAAM;EACd,WAAW;EACX,QAAQ;CACV;CACA,MAAM,aAAuB;EAC3B,IAAI;EACJ,Q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WAAE,WAAW,SAAS,OAAO,mBAAmB,KAAK,CAAC;EAC7EA,WAAE,SAAS,CAAC,GAAG,OAAO,GAAG,iBAAiB,SAAS;EACnDA,WAAE,eAAe,WAAW,eAAe,WAAW,EAAE,OAAO,QAAQ,CAAC;EACxEA,WAAE,OAAO,WAAW,cAAc,KAAK;CACzC;AACF;;;;;;ACrEA,MAAa,sBAA4B;;;;;;;;;;;;;;;;;;;;;;AAuBzC,MAAa,uBAAmC;CAC9C,eAAe;EAAE,OAAO;EAAG,MAAM;CAAI;CACrC,iBAAiB;EAAE,OAAO;EAAK,MAAM;CAAI;CACzC,mBAAmB;EAAE,OAAO;EAAG,MAAM;CAAI;CACzC,oBAAoB;EAAE,OAAO;EAAG,MAAM;CAAI;CAC1C,qBAAqB;EAAE,OAAO;EAAI,MAAM;CAAI;CAC5C,kBAAkB;EAAE,OAAO;EAAG,MAAM;CAAI;CACxC,kBAAkB;EAAE,OAAO;EAAI,MAAM;CAAI;CACzC,gBAAgB;EAAE,OAAO;EAAI,MAAM;CAAI;CACvC,oBAAoB;EAAE,OAAO;EAAY,MAAM;CAAI;CACnD,aAAa;EAAE,OAAO;EAAG,MAAM;CAAI;CACnC,qBAAqB;EAAE,OAAO;EAAO,MAAM;CAAI;AACjD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"operation-DF73RZOI.js","names":[],"sources":["../src/operation.ts"],"sourcesContent":["import type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport { compare, convertible } from \"@mark1russell7/quantity\";\n\n/**\n * This type tells if an operation can go again after a failure. It is a property of the\n * operation, not of the dependency. One Redis client sends a GET, which is safe to send again. It\n * also sends an INCR, which counts two times when it goes again after a timeout. Each operation\n * declares its idempotency:\n * - `true`: a second issue has the same effect. Examples are an HTTP GET or PUT, a SELECT, a\n * Redis GET or SET, and a write that the server removes when it is a copy.\n * - `false`: the client does not send it again after it can have reached the server.\n * - keyed: the server keeps a key for a window, as with an `Idempotency-Key` header, and it\n * ignores a copy in that window. A copy after the window is a second operation. Thus the\n * window is a timer, and it must be longer than all retries of the operation.\n */\nexport type Idempotency = boolean | { readonly key: string; readonly window: Extent };\n\n/** An operation is an endpoint that the service calls or serves, a command, or a query. */\nexport interface Operation {\n readonly idempotent: Idempotency;\n}\n\n/**\n * This function tells if an operation can go again `since` its first issue. An idempotent\n * operation can always go again, and other operations cannot. A keyed operation can go again\n * while the server keeps its key.\n */\nexport const mayReissue = (operation: Operation, since: Quantity): boolean => {\n const { idempotent } = operation;\n if (typeof idempotent === \"boolean\") return idempotent;\n return compare(since, idempotent.window) < 0;\n};\n\n/** This function gives the problems in the declaration of an operation that `describe()` refuses. */\nexport const operationProblems = (owner: string, name: string, operation: Operation): string[] => {\n const { idempotent } = operation;\n if (typeof idempotent === \"boolean\") return [];\n const problems: string[] = [];\n if (idempotent.key.trim().length === 0) problems.push(`${owner}'s ${name} names no key`);\n if (!convertible(idempotent.window.unit, \"s\"))\n problems.push(`${owner}'s ${name} holds its key for a span that is not a time`);\n return problems;\n};\n"],"mappings":";;;;;;;AA2BA,MAAa,cAAc,WAAsB,UAA6B;CAC5E,MAAM,EAAE,eAAe;CACvB,IAAI,OAAO,eAAe,WAAW,OAAO;CAC5C,OAAO,QAAQ,OAAO,WAAW,MAAM,IAAI;AAC7C;;AAGA,MAAa,qBAAqB,OAAe,MAAc,cAAmC;CAChG,MAAM,EAAE,eAAe;CACvB,IAAI,OAAO,eAAe,WAAW,OAAO,CAAC;CAC7C,MAAM,WAAqB,CAAC;CAC5B,IAAI,WAAW,IAAI,KAAK,CAAC,CAAC,WAAW,GAAG,SAAS,KAAK,GAAG,MAAM,KAAK,KAAK,cAAc;CACvF,IAAI,CAAC,YAAY,WAAW,OAAO,MAAM,GAAG,GAC1C,SAAS,KAAK,GAAG,MAAM,KAAK,KAAK,6CAA6C;CAChF,OAAO;AACT"}
package/build/pg.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"pg.js","names":["knob","t"],"sources":["../src/pg/connection.ts","../src/pg/meets.ts","../src/pg/client.ts","../src/pg/machine.ts","../src/pg/starting.ts"],"sourcesContent":["import type { ClientSocket, Factory } from \"../client/core.ts\";\n\n/** A pg socket is the socket of a client in the core: the join of the prober and the bounded close read it. */\nexport type PgSocket = ClientSocket;\n\n/** A query result is the part of a result of pg that the wrapper gives back. */\nexport interface PgResult<Row = Record<string, unknown>> {\n readonly rows: Row[];\n readonly rowCount: number | null;\n}\n\n/**\n * A pool client is the part of a `pg.PoolClient` that the wrapper uses. A pg 8 client has each part.\n * A fake for tests has them too. Thus the package depends on no type of pg.\n */\nexport interface PgPoolClient {\n /** This number is the id of the backend from BackendKeyData, which the server sends at the startup. */\n readonly processID?: number | null | undefined;\n /** This connection holds the socket of the client. */\n readonly connection?: { readonly stream?: PgSocket | undefined } | undefined;\n query(text: string, values?: readonly unknown[]): Promise<PgResult<never>>;\n /** This method gives the client back to the pool. With an error, the pool ends the client. */\n release(error?: Error | boolean): void;\n on(event: \"error\", listener: (error: Error) => void): unknown;\n off(event: \"error\", listener: (error: Error) => void): unknown;\n}\n\n/** A pool is the part of a `pg.Pool` that the wrapper uses. */\nexport interface PgPool {\n readonly totalCount: number;\n readonly idleCount: number;\n readonly waitingCount: number;\n connect(): Promise<PgPoolClient>;\n end(): Promise<void>;\n on(event: \"connect\" | \"remove\", listener: (client: PgPoolClient) => void): unknown;\n on(event: \"error\", listener: (error: Error, client: PgPoolClient) => void): unknown;\n off(event: \"connect\" | \"remove\", listener: (client: PgPoolClient) => void): unknown;\n off(event: \"error\", listener: (error: Error, client: PgPoolClient) => void): unknown;\n}\n\n/**\n * These are the options that the wrapper gives `pg.Pool`. Each one comes from the declaration. The\n * wrapper sets each option that has an effect on a timer, thus no default of pg decides one. A knob\n * of pg at 0 has no timer. The wrapper writes \"infinite\" as 0, and it refuses a bound of 0.\n */\nexport interface PgPoolOptions {\n readonly host: string;\n readonly port: number;\n readonly database?: string | undefined;\n readonly user?: string | undefined;\n readonly password?: string | undefined;\n /** The server shows this name in `pg_stat_activity`, thus the prober can join on it too. */\n readonly application_name: string;\n readonly max: number;\n readonly min: number;\n /** This time bounds the TCP connect, the startup and the authentication. It also bounds a checkout from a full pool. */\n readonly connectionTimeoutMillis: number;\n /** This time bounds each query on the client, from `client.query`. The client sends no cancel at its end. */\n readonly query_timeout: number;\n /** This time is the deadline of each statement on the server. The client sends it in the startup message. Undefined does not send it. */\n readonly statement_timeout: number | undefined;\n /** This time ends an idle client of the pool. 0 is no idle timer. */\n readonly idleTimeoutMillis: number;\n /** This time ends a client at this age from its connect, in whole seconds. 0 is no age. */\n readonly maxLifetimeSeconds: number;\n readonly keepAlive: boolean;\n /** This time is the idle time of TCP keepalive. Node truncates it to whole seconds. */\n readonly keepAliveInitialDelayMillis: number;\n /** The idle timer and the idle sockets do not keep the process alive (A14). The lifecycle holds the process. */\n readonly allowExitOnIdle: true;\n}\n\n/** A pool factory makes the pool of the client from its options. */\nexport type PoolFactory = Factory<PgPoolOptions, PgPool>;\n\n/**\n * This factory makes a `pg.Pool`. It loads pg only when a client connects, thus a service that does\n * not use PostgreSQL does not need pg. The specifier is a value, thus the package needs no types of pg.\n */\nexport const nodePostgres: PoolFactory = async (options) => {\n const specifier = \"pg\";\n const loaded = (await import(specifier)) as { readonly default: { readonly Pool: new (options: PgPoolOptions) => PgPool } };\n return new loaded.default.Pool(options);\n};\n","import type { Detector, Meeting } from \"../client/meets.ts\";\nimport { WHAT, immediate, keepaliveAnswered, keepaliveReset, keepaliveSilent, kernelGiveUp } from \"../client/meets.ts\";\nimport type { PgKnobs } from \"./client.ts\";\n\n/**\n * This function gives the manifestations that a pg client can meet, and the detectors of each, from\n * its knobs. The cells of S1 measured each one on node-postgres 8.23.1:\n * - A reset of a query gives ECONNRESET in 0.6 ms, and a FIN to an idle client gives EOF in 18 µs.\n * - A frozen server and a black hole have no detector in 60 s at the defaults: pg has no timer on a query and no keepalive.\n * - `query_timeout` ends a query in a black hole on time (9.503 s for 9.5 s).\n * - `statement_timeout` ends a slow statement on the server with ERROR 57014 (10.002 s for 10 s).\n *\n * pg has no watchdog and does not test an idle client. In place of a watchdog, the pool ends an\n * idle client at its idle timer. A later checkout then opens a new connection, which `connect_bound` bounds.\n */\nexport const pgMeetings = (name: string, knobs: PgKnobs): Meeting[] => {\n const query: Detector = {\n by: \"request_timeout\",\n within: knobs.request_timeout,\n situation: \"in flight\",\n effect: `the query fails as indeterminate, and ${name} gives the client back with an error, thus the pool ends it`,\n };\n const idleExpiry: Detector = {\n by: \"pool_idle_expiry\",\n within: knobs.pool_idle_expiry,\n situation: \"idle\",\n effect: \"the pool ends the idle client, thus no checkout gets the dead connection\",\n };\n const giveUp = kernelGiveUp(knobs.retrans_giveup_time, \"the query fails with its error\");\n const silent = (manifestation: \"blackhole\" | \"freeze-host\"): Meeting => ({\n manifestation,\n what: WHAT[manifestation],\n detectors: [query, giveUp, idleExpiry, keepaliveSilent(knobs.keepalive_idle)],\n });\n return [\n {\n manifestation: \"rst\",\n what: WHAT.rst,\n detectors: [\n immediate(\"in flight\", \"the query fails with ECONNRESET, and each new connect is refused\"),\n idleExpiry,\n keepaliveReset(knobs.keepalive_idle),\n ],\n },\n {\n manifestation: \"fin\",\n what: WHAT.fin,\n detectors: [\n immediate(\"in flight\", \"the query fails: 'Connection terminated unexpectedly'\"),\n immediate(\"idle\", \"the pool removes the idle client, and emits error\"),\n ],\n },\n silent(\"blackhole\"),\n silent(\"freeze-host\"),\n {\n manifestation: \"freeze-process\",\n what: WHAT[\"freeze-process\"],\n detectors: [query, idleExpiry, keepaliveAnswered()],\n },\n {\n manifestation: \"app-stall\",\n what: \"the server stops its replies for a time, for example behind a lock, and its kernel stays up\",\n detectors: [\n {\n by: \"statement_timeout\",\n within: knobs.statement_timeout,\n situation: \"in flight\",\n effect: \"the server ends the statement with ERROR 57014, a certain outcome, and the client stays\",\n },\n query,\n idleExpiry,\n keepaliveAnswered(),\n ],\n },\n ];\n};\n","import type { Extent, Quantity } from \"@mark1russell7/quantity\";\nimport { realClock } from \"../clock.ts\";\nimport type { Attempt, CheckOptions, Client, ClientJoin, ClientKnobs, ClientOptions, ClientSpec, ClientStep, DialFn, SendOptions, Sent } from \"../client/core.ts\";\nimport {\n attachClient,\n clientBounds,\n clientProblems,\n clientRecorder,\n deadlineProblem,\n dialCheck,\n finiteMs,\n inFlight,\n localStateCheck,\n message,\n ms,\n notSent,\n operationTable,\n orZero,\n poolProblems,\n roundTripCheck,\n sendWithReissue,\n socketEnds,\n stepChecks,\n timeProblems,\n wholeProblems,\n withinBound,\n zeroProblems,\n} from \"../client/core.ts\";\nimport { helloDial } from \"../client/dial.ts\";\nimport type { Dependency } from \"../description.ts\";\nimport type { DependencyHandle } from \"../lifecycle.ts\";\nimport type { Operation } from \"../operation.ts\";\nimport type { PgPool, PgPoolClient, PgPoolOptions, PgResult, PoolFactory } from \"./connection.ts\";\nimport { nodePostgres } from \"./connection.ts\";\nimport { pgMeetings } from \"./meets.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. A bound that nobody gives is\n * \"infinite\", not zero. `PG_STARTING_KNOBS` gives a declaration from the cells of S1. The knobs\n * that each client has come from the core.\n */\nexport interface PgKnobs extends ClientKnobs {\n /**\n * This time bounds a new connection (`connectionTimeoutMillis`): the TCP connect, the startup and\n * the authentication. The pool uses the same knob to bound a checkout from a full pool.\n * At the defaults pg has no bound, and the kernel gives up on the SYNs only after 131 s (A3, O15).\n */\n readonly connect_bound: Quantity;\n /** This time bounds each query on the client (`query_timeout`). pg sends no cancel at its end. */\n readonly request_timeout: Quantity;\n /**\n * This time is the deadline of each statement on the server (`statement_timeout`). The server then\n * ends the statement with ERROR 57014, a certain outcome. \"infinite\" sends no deadline.\n */\n readonly statement_timeout: Extent;\n /** This time ends an idle client of the pool (`idleTimeoutMillis`). The pool sends no test on an idle client. */\n readonly pool_idle_expiry: Extent;\n /** This time is the idle time of TCP keepalive, in whole seconds. Node then sends 10 probes 1 s apart. */\n readonly keepalive_idle: Extent;\n /** This time is the age at which the pool replaces a client (`maxLifetimeSeconds`), in whole seconds. */\n readonly max_connection_age: Extent;\n /** This time bounds the close of the pool at the shutdown: its end, then a destroy of each socket that stays. */\n readonly close_bound: Quantity;\n}\n\n/** A pg client spec is the declaration of one PostgreSQL client: where it connects, its pool, and its knobs. */\nexport interface PgClientSpec extends ClientSpec<PgKnobs> {\n readonly database?: string | undefined;\n readonly user?: string | undefined;\n /** These counts are the sizes of the pool: at most `max` clients, and an idle timer only above `min`. */\n readonly pool: { readonly max: number; readonly min: number };\n /**\n * These operations are the queries of the service, by name, with their idempotency. SQL text does\n * not tell if a statement changes a state, thus the client sends again only a query that this table names.\n */\n readonly operations?: Readonly<Record<string, Operation>> | undefined;\n}\n\n/** These options make a client. Without them, it uses pg, the real clock, and a dial with an SSLRequest. */\nexport type PgClientOptions = ClientOptions<PoolFactory>;\n\n/**\n * A join is one connection of the pool, at its connect (D1, D2). The prober joins its kernel records\n * to the server's view of the connection through it. The server's view is the process id of the backend.\n */\nexport interface PgJoin extends ClientJoin {\n /** This number is the process id of the backend, or null when the server gave none. Through a pooler, it is the id that the pooler gives. */\n readonly backendPid: number | null;\n}\n\n/** The steps that the pg client gives a check for: the steps of each client, and a checkout from the pool (B14). */\nexport type PgStep = ClientStep | \"checkout\";\n\n/** A pg client is a dependency of a service: its declaration, its handle, its checks and its queries. */\nexport interface PgClient extends Client<PgStep, PgJoin> {\n /** This text is the state of the client, as `PG_CLIENT_MACHINE` names it. */\n readonly status: string;\n /**\n * This method sends a query, and gives its outcome in three values. `operation` names the query\n * in the table of operations. The client sends again only an idempotent operation, one time at\n * most, after an outcome that is not certain. The second try stays in the bound of the request.\n */\n query<Row = Record<string, unknown>>(\n operation: string,\n text: string,\n values?: readonly unknown[],\n options?: SendOptions,\n ): Promise<Sent<PgResult<Row>>>;\n}\n\n/** This function gives the problems of a spec: the knobs that pg cannot use. */\nexport const specProblems = (name: string, spec: PgClientSpec): string[] => {\n const { knobs } = spec;\n return [\n ...timeProblems(name, knobs),\n // pg reads 0 as no timer, thus a bound of 0 is not a bound\n ...zeroProblems(name, \"pg\", knobs, {\n bounded: [\"connect_bound\", \"request_timeout\", \"close_bound\"],\n open: [\"statement_timeout\", \"pool_idle_expiry\", \"keepalive_idle\", \"max_connection_age\"],\n }),\n // Node truncates the keepalive delay to whole seconds, and pg takes the age in whole seconds\n ...wholeProblems(name, knobs, {\n millis: [\"connect_bound\", \"request_timeout\", \"statement_timeout\", \"pool_idle_expiry\"],\n seconds: [\"keepalive_idle\", \"max_connection_age\"],\n }),\n ...poolProblems(name, spec.pool),\n ];\n};\n\n/** This function gives the options of `pg.Pool` from a spec. Each timer of pg comes from the declaration. */\nexport const poolOptions = (name: string, spec: PgClientSpec): PgPoolOptions => {\n const { knobs } = spec;\n return {\n host: spec.host,\n port: spec.port,\n ...(spec.database === undefined ? {} : { database: spec.database }),\n ...(spec.user === undefined ? {} : { user: spec.user }),\n ...(spec.password === undefined ? {} : { password: spec.password }),\n application_name: name,\n max: spec.pool.max,\n min: spec.pool.min,\n connectionTimeoutMillis: ms(knobs.connect_bound),\n query_timeout: ms(knobs.request_timeout),\n statement_timeout: finiteMs(knobs.statement_timeout),\n idleTimeoutMillis: orZero(knobs.pool_idle_expiry),\n maxLifetimeSeconds: orZero(knobs.max_connection_age) / 1000,\n keepAlive: knobs.keepalive_idle.value !== \"infinite\",\n keepAliveInitialDelayMillis: orZero(knobs.keepalive_idle),\n allowExitOnIdle: true,\n };\n};\n\n/** The bytes of an SSLRequest: a length of 8, then the code 80877103. A server answers with one byte, S or N. */\nconst SSL_REQUEST = Uint8Array.of(0, 0, 0, 8, 0x04, 0xd2, 0x16, 0x2f);\n\n/**\n * This dial function opens a TCP connection, sends an SSLRequest, and waits for its one byte. The\n * server answers it before the authentication, thus the dial needs no password and opens no backend.\n */\nexport const sslRequestDial: DialFn = helloDial(SSL_REQUEST, (received) => {\n const answer = String.fromCharCode(received[0] ?? 0);\n return answer === \"S\" || answer === \"N\" ? null : new Error(`the answer to the SSLRequest was ${JSON.stringify(answer)}`);\n});\n\n/** A database error is an ErrorResponse of the server: pg gives its severity and its SQLSTATE code. */\nconst replyOf = (error: unknown): { readonly severity: string; readonly code: string } | null => {\n if (typeof error !== \"object\" || error === null) return null;\n const { severity, code } = error as { severity?: unknown; code?: unknown };\n return typeof severity === \"string\" && typeof code === \"string\" && /^[0-9A-Z]{5}$/.test(code) ? { severity, code } : null;\n};\n\n/**\n * This function makes a PostgreSQL client, a dependency of a service over a `pg.Pool`.\n * - It sets each timer of pg from the declaration. The driver sends nothing again by itself, and the client\n * sends again only an idempotent operation of its table.\n * - It tells the outcome of a query in three values. An ERROR of the server is certain. A FATAL\n * ends the session, thus its outcome is not certain.\n * - It gives back a client whose query has no certain outcome with an error. The pool then ends it,\n * thus an orphaned query does not hold the next checkout.\n * - It listens to each error of the pool and of a client that it holds. In Node, an error with no\n * listener throws, and library code does not end the process (A5).\n * - It records the process id of the backend of each connection (D1).\n *\n * The outcomes, the second try, the queries in flight, the bounded close and the checks come from\n * the core of the clients. This entry gives what pg does in its own way.\n */\nexport const pgClient = (name: string, spec: PgClientSpec, options: PgClientOptions = {}): PgClient => {\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 create = options.create ?? nodePostgres;\n const dial = options.dial ?? sslRequestDial;\n const operations = operationTable({}, spec.operations);\n const requestTimeout = ms(knobs.request_timeout);\n\n let pool: PgPool | null = null;\n let status = \"none\";\n const joins: PgJoin[] = [];\n // the clients of the pool whose socket did not close yet: the bound of the close destroys them\n const open = new Set<PgPoolClient>();\n // the queries in flight: the end of the close settles each one\n const flight = inFlight();\n\n const emit = clientRecorder(options.record, clock, name);\n // the state of the pg client is the outcome of its last connect: each record can move it\n const record = (on: string, to: string = status, detail?: string): void => {\n const from = status;\n status = to;\n emit(from, to, on, detail);\n };\n const closing = (): boolean => status === \"closing\" || status === \"end\";\n\n const onConnect = (client: PgPoolClient): void => {\n open.add(client);\n const generation = joins.length + 1;\n const pid = client.processID;\n joins.push({ generation, at: clock.now(), backendPid: typeof pid === \"number\" ? pid : null, ...socketEnds(client.connection?.stream) });\n record(\"join\", closing() ? status : \"ready\", `generation ${generation}, backend ${pid ?? \"unknown\"}`);\n };\n const onRemove = (client: PgPoolClient): void => {\n open.delete(client);\n record(\"client.removed\");\n };\n // an idle client failed. The pool removed it, and the next checkout opens a new connection\n // after the end, the listener only keeps the error from a throw\n const onPoolError = (error: Error): void => {\n if (status !== \"end\") record(\"client.error\", status, message(error));\n };\n\n /** This function records a failed checkout: a full pool at its bound, or a connect that failed. */\n const checkoutFailed = (error: unknown): void => {\n const text = message(error);\n if (/timeout exceeded when trying to connect/i.test(text)) record(\"checkout.timeout\", status, text);\n else record(\"connect.failed\", closing() ? status : \"failing\", text);\n };\n\n /** This function checks out a client, or gives the reason why the query cannot leave the client. */\n const checkout = (signal: AbortSignal | undefined): Promise<PgPoolClient | Attempt> => {\n const p = pool;\n if (p === null) return Promise.resolve(notSent(`${name} has not connected`));\n if (closing()) return Promise.resolve(notSent(`${name} is ${status}: the query did not leave the client`));\n if (signal?.aborted) return Promise.resolve(notSent(\"the caller aborted the query before it left the client\"));\n return new Promise((resolve) => {\n let done = false;\n const aborted = (): void => {\n done = true;\n resolve(notSent(\"the caller abandoned the query before it left the client\"));\n };\n signal?.addEventListener(\"abort\", aborted, { once: true });\n p.connect().then(\n (client) => {\n signal?.removeEventListener(\"abort\", aborted);\n // the caller left while the pool connected: the client goes back unused\n if (done) client.release();\n else resolve(client);\n },\n (error: unknown) => {\n signal?.removeEventListener(\"abort\", aborted);\n checkoutFailed(error);\n if (!done) resolve(notSent(message(error)));\n },\n );\n });\n };\n\n /** This function makes one try of a query: a checkout, the query, and the release. */\n const attempt = async (text: string, values: readonly unknown[] | undefined, signal: AbortSignal | undefined): Promise<Attempt> => {\n const got = await checkout(signal);\n if (!(\"release\" in got)) return got;\n const client = got;\n // a client that the application holds emits its own errors, and the pool does not listen to them\n const onClientError = (error: Error): void => record(\"client.error\", status, message(error));\n client.on(\"error\", onClientError);\n return flight.track(\n signal,\n \"the caller abandoned the query after it was sent\",\n (settle) => {\n client.query(text, values).then(\n (result) => settle({ outcome: \"ok\", value: { rows: result.rows, rowCount: result.rowCount } }),\n (error: unknown) => {\n const reply = replyOf(error);\n const said = reply === null ? message(error) : `${reply.code} ${message(error)}`;\n // an ERROR ends the statement and keeps the session. A FATAL or a PANIC ends the session, and the commit is not certain\n if (reply !== null && reply.severity === \"ERROR\") settle({ outcome: \"error\", error: said, reply: true });\n else settle({ outcome: \"indeterminate\", error: said }, error instanceof Error ? error : new Error(said));\n },\n );\n },\n (_value, cause) => {\n client.off(\"error\", onClientError);\n // pg keeps a query active on the server after its timeout: an error makes the pool end the client, and the end destroys the socket\n client.release(cause);\n },\n );\n };\n\n const query = <Row>(operation: string, text: string, values?: readonly unknown[], sendOptions: SendOptions = {}): Promise<Sent<PgResult<Row>>> =>\n sendWithReissue({\n clock,\n bound: requestTimeout,\n operation: operations[operation],\n options: sendOptions,\n attempt: (signal) => attempt(text, values, signal) as Promise<Attempt<PgResult<Row>>>,\n onReissue: () => record(\"command.reissue\", status, operation),\n });\n\n const handle: DependencyHandle = {\n async connect(signal) {\n record(\"status.connecting\", \"connecting\");\n const p = await create(poolOptions(name, spec));\n pool = p;\n p.on(\"connect\", onConnect);\n p.on(\"remove\", onRemove);\n p.on(\"error\", onPoolError);\n if (signal.aborted) throw new Error(`${name}: the service stopped before the connect`);\n // one checkout opens the first connection. A server that is down does not stop the startup:\n // the checks keep readiness tripped until a connect succeeds (readiness is earned)\n const first = await checkout(signal);\n if (\"release\" in first) first.release();\n },\n async close() {\n const p = pool;\n if (p === null || closing()) return;\n record(\"close.request\", \"closing\");\n if (!(await withinBound(clock, ms(knobs.close_bound), p.end()))) {\n // the end of a client sends Terminate and half-closes the socket. Behind a black hole the\n // socket never closes, and the pool waits with no bound: the bound destroys each socket\n record(\"close.bound\");\n for (const client of [...open]) client.connection?.stream?.destroy?.();\n record(\"close.destroy\", status, `${open.size} sockets`);\n }\n flight.settleAll(\"the client closed with the query in flight\");\n p.off(\"connect\", onConnect);\n p.off(\"remove\", onRemove);\n // the error listener stays: a socket that closes later emits an error, and with no listener it throws\n record(\"status.end\", \"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 statement_timeout: knobs.statement_timeout,\n pool_idle_expiry: knobs.pool_idle_expiry,\n keepalive_idle: knobs.keepalive_idle,\n // pg sends nothing on an idle connection, thus its keepalive is the only refresh of an idle flow (O03)\n idle_refresh_interval: knobs.keepalive_idle,\n max_connection_age: knobs.max_connection_age,\n close_bound: knobs.close_bound,\n retrans_giveup_time: knobs.retrans_giveup_time,\n },\n operations,\n };\n\n const checks = (checkOptions: CheckOptions<PgStep>) =>\n stepChecks<PgStep>(name, checkOptions, {\n // the outcome of the last connect, without a round trip. pg does not connect again by itself,\n // thus pair it with a check that uses the pool\n \"local-state\": localStateCheck(() => status === \"ready\"),\n // a checkout and its release, with no query: it finds a full pool and a connect that fails,\n // but the pool sends no test on an idle client, thus not a dead idle connection\n checkout: {\n ownConnection: true,\n run: async (signal) => {\n const got = await checkout(signal);\n if (!(\"release\" in got)) return \"error\";\n got.release();\n return \"ok\";\n },\n },\n // a SELECT 1 through the pool of the application\n \"round-trip\": roundTripCheck((sendOptions) => query(\"check\", \"SELECT 1\", [], sendOptions)),\n // a new connection each time, with no backend\n dial: dialCheck(dial, spec.host, spec.port),\n });\n\n return {\n name,\n declaration,\n handle,\n meets: pgMeetings(name, knobs),\n get status() {\n return status;\n },\n joins,\n query,\n checks,\n attach: (svc, checkOptions) => attachClient(svc, name, declaration, handle, checks(checkOptions)),\n problems(description) {\n // O07: the server must end a slow statement first, with a certain error\n const deadline = deadlineProblem(name, knobs.request_timeout, knobs.statement_timeout, \"statement\");\n return [...clientProblems(name, description, clientBounds(knobs)), ...(deadline === null ? [] : [deadline])];\n },\n };\n};\n","import type { Machine } from \"@mark1russell7/algebra\";\nimport { clientKnob as knob, closeTimer, transition as t } from \"../client/machine.ts\";\n\n/** The states where the pool exists and serves. */\nconst SERVING = [\"connecting\", \"ready\", \"failing\"] as const;\nconst OPEN = [...SERVING, \"closing\"] as const;\n\n/**\n * The pg client of the service as a `mark1russell7.machine/1` document. It is the pool as the\n * wrapper sees it, not one connection: the document `node-postgres` of `@mark1russell7/machines`\n * gives each client of the pool. The state is the outcome of the last connect:\n * - `ready`: the last connect of the pool succeeded.\n * - `failing`: the last connect failed. pg does not connect again by itself. The next checkout tries again.\n *\n * An idle client that fails and a client that the pool removes do not change the state. The pool\n * removed that client, and the next checkout opens a new connection. A test records the transitions\n * of the client and replays them against this document.\n */\nexport const PG_CLIENT_MACHINE: Machine = {\n format: \"mark1russell7.machine/1\",\n id: \"service.machine.pg-client\",\n title: \"The PostgreSQL client of the service, over a pool of node-postgres 8\",\n layer: \"driver\",\n version: \"0.1.0\",\n sources: [{ ref: \"packages/service/src/pg (the client implements this document)\", rung: \"implemented\" }],\n states: {\n none: { initial: true, note: \"the client exists, and its pool does not\" },\n connecting: { note: \"the first checkout of the startup opens the first connection\" },\n ready: { note: \"the last connect succeeded. A dead idle client stays hidden until the pool ends it or a query meets it\" },\n failing: { note: \"the last connect failed. A checkout of a full pool that times out does not change the state\" },\n closing: { note: \"the end of the pool: each idle client sends Terminate, and each held client goes at its release\" },\n end: { final: true, note: \"the service closed the client\" },\n },\n events: {\n \"status.connecting\": { kind: \"local\" },\n join: { kind: \"rx\", note: \"the first ReadyForQuery of a new connection, with the process id of its backend (D1)\" },\n \"connect.failed\": { kind: \"local\", note: \"a connect failed: its error, a close, a FATAL of the server, or connect_bound\" },\n \"checkout.timeout\": { kind: \"timer\", note: \"a checkout of a full pool waited connect_bound\" },\n \"client.error\": { kind: \"rx\", note: \"an error of an idle client, or of a client that the service holds\" },\n \"client.removed\": { kind: \"local\", note: \"the socket of a client of the pool closed\" },\n \"command.reissue\": { kind: \"local\" },\n \"close.request\": { kind: \"local\" },\n \"close.bound\": { kind: \"timer\" },\n \"close.destroy\": { kind: \"local\", note: \"the bound destroys each socket that a silent server does not close\" },\n \"status.end\": { kind: \"local\" },\n },\n knobs: {\n connect_bound: knob(\"connectionTimeoutMillis\"),\n close_bound: knob(\"close.bound\"),\n },\n timers: {\n connect_timeout: {\n duration: { knob: \"connect_bound\", unit: \"s\" },\n arms: [\"enter:connecting\"],\n cancels: [\"join\", \"connect.failed\"],\n fires: \"connect.failed\",\n note: \"pg-pool destroys the socket of the attempt: 'Connection terminated due to connection timeout'\",\n },\n close: closeTimer(),\n },\n transitions: [\n t(\"connect\", \"none\", \"status.connecting\", \"connecting\"),\n t(\"join\", [...SERVING], \"join\", \"ready\"),\n t(\"connect-failed\", [...SERVING], \"connect.failed\", \"failing\", { timer: \"connect_timeout\" }),\n // a checkout that is in flight at the close can still connect, or fail\n t(\"join-closing\", \"closing\", \"join\", \"closing\"),\n t(\"connect-failed-closing\", \"closing\", \"connect.failed\", \"closing\"),\n ...OPEN.map((state) => t(`checkout-timeout-${state}`, state, \"checkout.timeout\", state)),\n ...OPEN.map((state) => t(`client-error-${state}`, state, \"client.error\", state)),\n ...OPEN.map((state) => t(`removed-${state}`, state, \"client.removed\", state)),\n ...OPEN.map((state) => t(`reissue-${state}`, state, \"command.reissue\", state)),\n t(\"close\", [...SERVING], \"close.request\", \"closing\"),\n t(\"close-bound\", \"closing\", \"close.bound\", \"closing\", { timer: \"close\" }),\n t(\"close-destroy\", \"closing\", \"close.destroy\", \"closing\"),\n t(\"end\", \"closing\", \"status.end\", \"end\"),\n ],\n};\n","import { STARTING_POLL } from \"../client/core.ts\";\nimport type { Poll } from \"../timing.ts\";\nimport type { PgKnobs } from \"./client.ts\";\n\n/**\n * This poll is the poll of the checks that `PG_STARTING_KNOBS` fits. It is `STARTING_POLL` of the\n * core: each 5 s with a jitter of 20 %, and a timeout of 4 s (B6, O12). The poll does not depend on the driver.\n */\nexport const PG_STARTING_POLL: Poll = STARTING_POLL;\n\n/**\n * These knobs are a declaration to start from, from what the cells of S1 measured on node-postgres\n * 8.23.1 against PostgreSQL 17.11. The runtime has no defaults: a service gives these knobs, or its\n * own. Each value holds the borders that the cells measured:\n * - `connect_bound` 5 s: at the defaults pg has no bound, and the kernel gives up on the SYNs only\n * after 131 s. The timer of the pool fired 7 ms late at most. Thus 5 s is in a startup budget of 30 s (O15).\n * - `request_timeout` 9.5 s: the cells ended a query in a black hole at 9.503 s. That is in the slowest poll of 10 s (O13).\n * - `statement_timeout` 9 s: below `request_timeout`, thus the server ends a slow statement first,\n * with ERROR 57014 (O07). The cells measured that end 2 ms after the deadline.\n * - `pool_idle_expiry` 10 s: the idle timer of pg-pool at its defaults, measured at 10.004 s. It is\n * below a router that forgets an idle flow at 12 s (O03), and below a `client_idle_timeout` of PgBouncer at 12 s (O01).\n * - `keepalive_idle` 30 s: at the defaults pg has no keepalive. This value refreshes a held idle\n * connection through the NAT forms of the cells (240 s and 350 s).\n * - `max_connection_age` \"infinite\": no cell measured an age, thus the declaration gives none.\n * - `close_bound` 2 s: behind a black hole the end of the pool waits with no bound. The cells saw\n * the pool emit `remove` only when the socket closes.\n * - `retrans_giveup_time` 924.6 s: the give-up of Linux at `tcp_retries2 = 15`. The cells measured 3.120 s at `tcp_retries2 = 3`.\n */\nexport const PG_STARTING_KNOBS: PgKnobs = {\n connect_bound: { value: 5, unit: \"s\" },\n request_timeout: { value: 9.5, unit: \"s\" },\n statement_timeout: { value: 9, unit: \"s\" },\n pool_idle_expiry: { value: 10, unit: \"s\" },\n keepalive_idle: { value: 30, unit: \"s\" },\n max_connection_age: { value: \"infinite\", unit: \"s\" },\n close_bound: { value: 2, unit: \"s\" },\n retrans_giveup_time: { value: 924.6, unit: \"s\" },\n};\n"],"mappings":";;;;;;;AA+EA,MAAa,eAA4B,OAAO,YAAY;CAG1D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M;CAAI;CACnC,qBAAqB;EAAE,OAAO;EAAO,MAAM;CAAI;AACjD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"policy-UYALkqVq.js","names":["r"],"sources":["../src/limiter/policy.ts"],"sourcesContent":["import type { Quantity } from \"@mark1russell7/quantity\";\nimport { convertExact, convertible, rationals as r } from \"@mark1russell7/quantity\";\n\n/**\n * A token bucket gives each key a bucket of `burst` tokens. The bucket refills at `rate`, and each\n * take uses one token. Thus a key can make `burst` takes at once after an idle time, and then\n * `rate` takes in each unit of time.\n */\nexport interface TokenBucket {\n readonly type: \"token-bucket\";\n /** This rate is how fast the bucket refills: a count for each unit of time, for example `{ value: 10, unit: \"count/s\" }`. */\n readonly rate: Quantity;\n /** This count is the size of the bucket: the most takes in a sequence after an idle time. */\n readonly burst: Quantity;\n}\n\n/**\n * A sliding window gives each key at most `limit` takes in each `window`. Each take counts for one\n * window from its time, thus the window moves with the clock and has no fixed edges.\n */\nexport interface SlidingWindow {\n readonly type: \"sliding-window\";\n /** This count is the most takes of one key in one window. */\n readonly limit: Quantity;\n /** This time is the length of the window. */\n readonly window: Quantity;\n}\n\n/** A limit policy is the rule that a keyed limiter applies to each key, as data. It has no defaults. */\nexport type LimitPolicy = TokenBucket | SlidingWindow;\n\n/**\n * A store failure policy tells what a take does when a shared store fails. It has no default.\n * - `open`: the limiter lets the take in. The count is not known, thus `remaining` is 0.\n * - `closed`: the limiter refuses the take with the cause `store`. Its `retryAfter` is the longest\n * `retryAfter` of the policy (`longestRetryAfter`). Thus O29 and O30 apply to it too.\n */\nexport type StoreFailure = \"open\" | \"closed\";\n\n/**\n * A store spec tells where the counts of the keys are:\n * - `local`: in the memory of each replica. A limit L over N replicas is then L / N on each\n * replica. That sum holds only on average, when the balancer spreads the takes of each key evenly.\n * A local store does not fail, thus it has no `onStoreFailure`, and the limiter ignores one.\n * - `shared`: in a store that the replicas share, the dependency of that name. The store decides\n * each take in one atomic step, on its own clock. Thus the limit holds across the replicas.\n * `onStoreFailure` tells what a take does when the store fails.\n */\nexport type LimiterStoreSpec =\n | { readonly kind: \"local\" }\n | { readonly kind: \"shared\"; readonly dependency: string; readonly onStoreFailure: StoreFailure };\n\n/**\n * The eviction of a limiter bounds its keys. A store removes a key only when its state is equal to\n * the state of a new key. That is a bucket that is full again, or a window with no take in it.\n * Thus an eviction changes no decision.\n */\nexport interface LimiterEviction {\n /**\n * This count is the most keys that the store holds. At the cap, the store refuses a take of a new\n * key until a held key is idle for its span (`idleSpan`). A held key keeps its count.\n */\n readonly maxKeys: Quantity;\n}\n\n/** A limiter spec is the declaration of one keyed limiter. Each part is necessary, because the limiter has no defaults. */\nexport interface LimiterSpec {\n /** This text tells what the key of each take is, for example `tenant` or `principal`. The caller gives each key. */\n readonly key: string;\n readonly policy: LimitPolicy;\n readonly store: LimiterStoreSpec;\n readonly evict: LimiterEviction;\n}\n\n/** A limiter is a keyed limiter in the description of a service: its name and its spec. */\nexport interface Limiter extends LimiterSpec {\n readonly name: string;\n}\n\n/**\n * A wait cause tells why a take is refused for a time:\n * - `limit`: the key used its limit.\n * - `cap`: the store holds its cap of keys, and the key is new.\n * - `store`: the shared store failed, and its spec declares `onStoreFailure: \"closed\"`.\n */\nexport type WaitCause = \"limit\" | \"cap\" | \"store\";\n\n/**\n * A refusal cause tells why a take is refused: a wait cause, or `capacity`. The cause `capacity` is\n * a take whose units are over the capacity of the policy. No wait lets it in.\n */\nexport type RefusalCause = WaitCause | \"capacity\";\n\n/**\n * A permitted take used its units of its key. `remaining` is the count of units that the key can\n * take at this time.\n */\nexport interface Allowed {\n readonly allowed: true;\n readonly remaining: number;\n /** This text is the failure of a shared store, when `onStoreFailure: \"open\"` lets the take in. */\n readonly failure?: string | undefined;\n}\n\n/**\n * A wait refusal used nothing. `retryAfter` is the time until the limiter lets the same take in, when\n * no other take comes first. It is always above zero.\n */\nexport interface WaitRefused {\n readonly allowed: false;\n readonly cause: WaitCause;\n readonly retryAfter: Quantity;\n /** This text is the failure of a shared store, for the cause `store`. */\n readonly failure?: string | undefined;\n}\n\n/**\n * A capacity refusal used nothing, and the same take is refused at each time. Its `units` are over\n * the `capacity` of the policy: the `burst` of a bucket, or the `limit` of a window. A caller can\n * split the take into parts of at most `capacity` units.\n */\nexport interface CapacityRefused {\n readonly allowed: false;\n readonly cause: \"capacity\";\n readonly units: number;\n readonly capacity: number;\n}\n\n/**\n * A refused take used nothing. The cause tells the type: a `WaitRefused` has a `retryAfter`, and a\n * `CapacityRefused` has none. Thus a caller examines the cause before it reads `retryAfter`.\n */\nexport type Refused = WaitRefused | CapacityRefused;\n\n/** A decision is the answer of a limiter to one take. */\nexport type Decision = Allowed | Refused;\n\n/**\n * A limit rule is a policy in numbers, which a store applies: each time in milliseconds, and each\n * count as a number. A store in another process, for example a script of Redis, gets these numbers.\n */\nexport type LimitRule =\n | {\n readonly type: \"token-bucket\";\n /** This time is the refill of one token, in milliseconds. */\n readonly interval: number;\n readonly burst: number;\n }\n | {\n readonly type: \"sliding-window\";\n readonly limit: number;\n /** This time is the length of the window, in milliseconds. */\n readonly window: number;\n };\n\n/**\n * A key state is what a store keeps for one key:\n * - A token bucket keeps the time at which its bucket is full again (`full`, in milliseconds).\n * - A sliding window keeps the time of each permitted take in the window, the oldest first.\n */\nexport type KeyState =\n | { readonly type: \"token-bucket\"; readonly full: number }\n | { readonly type: \"sliding-window\"; readonly stamps: readonly number[] };\n\n/** A step is the decision of one take, and the state of its key after the take. A refusal keeps the count of the key. */\nexport interface TakeStep {\n readonly decision: Decision;\n readonly state: KeyState;\n}\n\n/**\n * This tolerance is one nanosecond, in milliseconds. A comparison of times permits it, because a\n * rate of 3 for each second gives an interval that floating point cannot hold exactly.\n */\nconst TOLERANCE = 1e-6;\n\n/** These checks of an amount are internal: the quota module uses them, and the entry does not export them. */\nexport const isCount = (amount: Quantity | undefined): boolean => amount !== undefined && convertible(amount.unit, \"count\");\nexport const isTime = (amount: Quantity | undefined): boolean => amount !== undefined && convertible(amount.unit, \"s\");\nconst isRate = (amount: Quantity | undefined): boolean => amount !== undefined && convertible(amount.unit, \"count/s\");\n/** This function tells if a unit converts, also for a unit that the quantity package does not know. */\nexport const safely = (test: (amount: Quantity | undefined) => boolean, amount: Quantity | undefined): boolean => {\n try {\n return test(amount);\n } catch {\n return false;\n }\n};\nexport const finiteAbove = (amount: Quantity): boolean => typeof amount.value === \"number\" && Number.isFinite(amount.value) && amount.value > 0;\nexport const wholeCount = (amount: Quantity): boolean => finiteAbove(amount) && Number.isInteger(r.toNumber(convertExact(r.fromNumber(amount.value), amount.unit, \"count\")));\n\n/** A loose policy is a policy from any source, with each part optional, for the check of its parts. */\ninterface LoosePolicy {\n readonly type?: string;\n readonly rate?: Quantity;\n readonly burst?: Quantity;\n readonly limit?: Quantity;\n readonly window?: Quantity;\n}\n\n/**\n * This function gives the problems of a limiter spec. `describe()` and `keyedLimiter` refuse a spec\n * with a problem. A part that is absent is a problem, because the limiter has no defaults.\n */\nexport const limiterProblems = (name: string, spec: Partial<LimiterSpec> | undefined): string[] => {\n const owner = `limiter ${name}`;\n if (spec === undefined || (spec as unknown) === null) return [`${owner} has no spec: a limiter has no defaults`];\n const problems: string[] = [];\n const missing = (part: string): void => {\n problems.push(`${owner} does not declare ${part}: a limiter has no defaults`);\n };\n if (typeof spec.key !== \"string\") missing(\"what its key is (key)\");\n else if (spec.key.trim().length === 0) problems.push(`${owner} names no key`);\n const policy = spec.policy as LoosePolicy | undefined;\n if (policy === undefined) missing(\"its policy (policy)\");\n else if (policy.type === \"token-bucket\") {\n if (policy.rate === undefined) missing(\"the rate of its bucket (policy.rate)\");\n else if (!safely(isRate, policy.rate)) problems.push(`${owner}'s rate is not a count for each unit of time, for example count/s`);\n else if (!finiteAbove(policy.rate)) problems.push(`${owner}'s rate is not a finite rate above zero`);\n if (policy.burst === undefined) missing(\"the size of its bucket (policy.burst)\");\n else if (!safely(isCount, policy.burst)) problems.push(`${owner}'s burst is not a count`);\n else if (!wholeCount(policy.burst)) problems.push(`${owner}'s burst is not a whole count above zero`);\n } else if (policy.type === \"sliding-window\") {\n if (policy.limit === undefined) missing(\"the limit of its window (policy.limit)\");\n else if (!safely(isCount, policy.limit)) problems.push(`${owner}'s limit is not a count`);\n else if (!wholeCount(policy.limit)) problems.push(`${owner}'s limit is not a whole count above zero`);\n if (policy.window === undefined) missing(\"the length of its window (policy.window)\");\n else if (!safely(isTime, policy.window)) problems.push(`${owner}'s window is not a time`);\n else if (!finiteAbove(policy.window)) problems.push(`${owner}'s window is not a finite time above zero`);\n } else problems.push(`${owner}'s policy ${String(policy.type)} is not \"token-bucket\" or \"sliding-window\"`);\n const store = spec.store as { kind?: string; dependency?: unknown; onStoreFailure?: unknown } | undefined;\n if (store === undefined) missing(`its store, { kind: \"local\" } or { kind: \"shared\", dependency, onStoreFailure } (store)`);\n else if (store.kind === \"shared\") {\n if (typeof store.dependency !== \"string\" || store.dependency.trim().length === 0)\n problems.push(`${owner}'s shared store names no dependency`);\n if (store.onStoreFailure === undefined) missing(`what a failure of its shared store does, \"open\" or \"closed\" (store.onStoreFailure)`);\n else if (store.onStoreFailure !== \"open\" && store.onStoreFailure !== \"closed\")\n problems.push(`${owner}'s onStoreFailure ${String(store.onStoreFailure)} is not \"open\" or \"closed\"`);\n } else if (store.kind !== \"local\") problems.push(`${owner}'s store ${String(store.kind)} is not \"local\" or \"shared\"`);\n const evict = spec.evict as Partial<LimiterEviction> | undefined;\n if (evict === undefined || evict.maxKeys === undefined) missing(\"the most keys that it holds (evict.maxKeys)\");\n else if (!safely(isCount, evict.maxKeys)) problems.push(`${owner}'s maxKeys is not a count`);\n else if (!wholeCount(evict.maxKeys)) problems.push(`${owner}'s maxKeys is not a whole count above zero: the count of keys has a bound`);\n return problems;\n};\n\n/** This function gives an amount in milliseconds, exactly where the units permit, as one number. */\nexport const milliseconds = (amount: Quantity): number => r.toNumber(convertExact(r.fromNumber(amount.value), amount.unit, \"ms\"));\n/** This function gives a count as one number. */\nexport const countOf = (amount: Quantity): number => r.toNumber(convertExact(r.fromNumber(amount.value), amount.unit, \"count\"));\n\n/**\n * This function gives the rule of a policy in numbers. The interval of a bucket is exact as a\n * rational, and it becomes one number only at the end. Thus 10 for each minute gives 6000 ms.\n */\nexport const limitRule = (policy: LimitPolicy): LimitRule => {\n if (policy.type === \"token-bucket\") {\n const perMs = convertExact(r.fromNumber(policy.rate.value), policy.rate.unit, \"count/ms\");\n return { type: \"token-bucket\", interval: r.toNumber(r.div(r.ONE, perMs)), burst: countOf(policy.burst) };\n }\n return { type: \"sliding-window\", limit: countOf(policy.limit), window: milliseconds(policy.window) };\n};\n\n/** This function gives a time in milliseconds as a quantity. */\nconst ms = (value: number): Quantity => ({ value, unit: \"ms\" });\n\n/**\n * This function gives the span after which an idle key is equal to a new key. That span is\n * `burst / rate` for a token bucket, and one window for a sliding window. A store can remove the key\n * after it, and no decision changes. It is also the longest `retryAfter` of a new key that the store\n * refuses at its cap.\n */\nexport const idleSpan = (policy: LimitPolicy): Quantity => {\n const rule = limitRule(policy);\n return ms(rule.type === \"token-bucket\" ? rule.interval * rule.burst : rule.window);\n};\n\n/**\n * This function gives the longest `retryAfter` of a refusal by the policy: one interval of the\n * bucket (`1 / rate`), or one window. A refusal at the cap of keys can be longer, up to `idleSpan`.\n */\nexport const longestRetryAfter = (policy: LimitPolicy): Quantity => {\n const rule = limitRule(policy);\n return ms(rule.type === \"token-bucket\" ? rule.interval : rule.window);\n};\n\n/**\n * This function gives a `retryAfter` in whole seconds, rounded up, as the header `Retry-After`\n * (RFC 9110) has it. A time over a whole second by less than one nanosecond rounds down to it,\n * because that part is an error of floating point.\n */\nexport const retryAfterSeconds = (retryAfter: Quantity): number => {\n const seconds = r.toNumber(convertExact(r.fromNumber(retryAfter.value), retryAfter.unit, \"s\"));\n return Math.max(0, Math.ceil(seconds - TOLERANCE / 1000));\n};\n\n/** This function gives the time at which a key state is equal to the state of a new key, in milliseconds. */\nexport const freeAt = (rule: LimitRule, state: KeyState): number => {\n if (state.type === \"token-bucket\") return state.full;\n const last = state.stamps[state.stamps.length - 1];\n return last === undefined ? Number.NEGATIVE_INFINITY : last + (rule.type === \"sliding-window\" ? rule.window : 0);\n};\n\n/** This function gives the capacity of a rule: the most units of one take. That is the `burst` of a bucket, or the `limit` of a window. */\nexport const capacityOf = (rule: LimitRule): number => (rule.type === \"token-bucket\" ? rule.burst : rule.limit);\n\n/**\n * This function gives the units of a take: 1 when they are absent. It throws for units that are not\n * a whole number of 1 or more, because such a take has no meaning.\n */\nexport const unitsOf = (units: number | undefined): number => {\n if (units === undefined) return 1;\n if (typeof units !== \"number\" || !Number.isSafeInteger(units) || units < 1)\n throw new RangeError(`the units of a take are a whole number of 1 or more, not ${String(units)}`);\n return units;\n};\n\n/** This function gives the capacity refusal of a take whose units are over the capacity of its rule, or `undefined`. */\nexport const overCapacity = (rule: LimitRule, units: number): CapacityRefused | undefined => {\n const capacity = capacityOf(rule);\n return units > capacity ? { allowed: false, cause: \"capacity\", units, capacity } : undefined;\n};\n\n/**\n * This function decides one take of `units` units (1 when absent) of a key at the time `now`, in\n * milliseconds, from the state of the key (`undefined` for a new key). It is the one decision of each\n * store in this process. A store in another process does the same arithmetic in its own atomic step.\n * - A take over the capacity of the rule (`capacityOf`) is refused with the cause `capacity`, and\n * the state does not change.\n * - A token bucket (GCRA): the store lets the take in when, with the take, the bucket is full\n * again in at most `burst` intervals. A refusal waits until `units` tokens are back.\n * - A sliding window: the store lets the take in when at most `limit - units` takes are in the\n * window. A refusal waits until enough of the oldest takes leave the window.\n * - A take of `units` units is the same as `units` takes of 1 at one time, when all of them are let in.\n */\nexport const decide = (rule: LimitRule, state: KeyState | undefined, now: number, units?: number): TakeStep => {\n const n = unitsOf(units);\n const over = overCapacity(rule, n);\n if (rule.type === \"token-bucket\") {\n const span = rule.interval * rule.burst;\n const full = state?.type === \"token-bucket\" ? Math.max(state.full, now) : now;\n if (over !== undefined) return { decision: over, state: { type: \"token-bucket\", full } };\n const next = full + rule.interval * n;\n if (next - now > span + TOLERANCE)\n return { decision: { allowed: false, retryAfter: ms(next - span - now), cause: \"limit\" }, state: { type: \"token-bucket\", full } };\n const remaining = Math.max(0, Math.floor((span - (next - now)) / rule.interval + TOLERANCE));\n return { decision: { allowed: true, remaining }, state: { type: \"token-bucket\", full: next } };\n }\n const held = state?.type === \"sliding-window\" ? state.stamps : [];\n // a take counts for one window from its time: it leaves the window at stamp + window\n const live = held.filter((stamp) => stamp + rule.window > now + TOLERANCE);\n if (over !== undefined) return { decision: over, state: { type: \"sliding-window\", stamps: live } };\n // the take fits when the oldest (live + n - limit) takes have left the window\n const excess = live.length + n - rule.limit;\n if (excess > 0)\n return { decision: { allowed: false, retryAfter: ms(live[excess - 1]! + rule.window - now), cause: \"limit\" }, state: { type: \"sliding-window\", stamps: live } };\n return {\n decision: { allowed: true, remaining: rule.limit - live.length - n },\n state: { type: \"sliding-window\", stamps: [...live, ...Array.from({ length: n }, () => now)] },\n };\n};\n"],"mappings":";;;;;;AA8KA,MAAM,YAAY;;AAGlB,MAAa,WAAW,WAA0C,WAAW,KAAA,KAAa,YAAY,OAAO,MAAM,OAAO;AAC1H,MAAa,UAAU,WAA0C,WAAW,KAAA,KAAa,YAAY,OAAO,MAAM,GAAG;AACrH,MAAM,UAAU,WAA0C,WAAW,KAAA,KAAa,YAAY,OAAO,MAAM,SAAS;;AAEpH,MAAa,UAAU,MAAiD,WAA0C;CAChH,IAAI;EACF,OAAO,KAAK,MAAM;CACpB,QAAQ;EACN,OAAO;CACT;AACF;AACA,MAAa,eAAe,WAA8B,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,OAAO,KAAK,KAAK,OAAO,QAAQ;AAC9I,MAAa,cAAc,WAA8B,YAAY,MAAM,KAAK,OAAO,UAAUA,UAAE,SAAS,aAAaA,UAAE,WAAW,OAAO,KAAK,GAAG,OAAO,MAAM,OAAO,CAAC,CAAC;;;;;AAe3K,MAAa,mBAAmB,MAAc,SAAqD;CACjG,MAAM,QAAQ,WAAW;CACzB,IAAI,SAAS,KAAA,K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