@hot-updater/plugin-core 1.0.0-rc.2 → 1.0.0-rc.21

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 (290) hide show
  1. package/README.md +33 -0
  2. package/dist/baseCandidateKey.cjs +50 -0
  3. package/dist/baseCandidateKey.d.cts +27 -0
  4. package/dist/baseCandidateKey.d.mts +27 -0
  5. package/dist/baseCandidateKey.mjs +49 -0
  6. package/dist/bundleStorageLayout.cjs +7 -0
  7. package/dist/bundleStorageLayout.d.cts +5 -1
  8. package/dist/bundleStorageLayout.d.mts +5 -1
  9. package/dist/bundleStorageLayout.mjs +7 -1
  10. package/dist/contentType.cjs +9 -0
  11. package/dist/contentType.d.cts +4 -0
  12. package/dist/contentType.d.mts +4 -0
  13. package/dist/contentType.mjs +7 -0
  14. package/dist/coreApi.d.cts +131 -0
  15. package/dist/coreApi.d.mts +131 -0
  16. package/dist/createStorageAdapter.cjs +8 -0
  17. package/dist/createStorageAdapter.d.cts +9 -0
  18. package/dist/createStorageAdapter.d.mts +9 -0
  19. package/dist/createStorageAdapter.mjs +7 -0
  20. package/dist/database/adapter.cjs +61 -0
  21. package/dist/database/adapter.d.cts +200 -0
  22. package/dist/database/adapter.d.mts +200 -0
  23. package/dist/database/adapter.mjs +55 -0
  24. package/dist/database/distinct.cjs +88 -0
  25. package/dist/database/distinct.d.cts +18 -0
  26. package/dist/database/distinct.d.mts +18 -0
  27. package/dist/database/distinct.mjs +85 -0
  28. package/dist/database/memoryAdapter.cjs +107 -0
  29. package/dist/database/memoryAdapter.d.cts +14 -0
  30. package/dist/database/memoryAdapter.d.mts +14 -0
  31. package/dist/database/memoryAdapter.mjs +107 -0
  32. package/dist/database/values.cjs +114 -0
  33. package/dist/database/values.d.cts +17 -0
  34. package/dist/database/values.d.mts +17 -0
  35. package/dist/database/values.mjs +104 -0
  36. package/dist/database/verifyAdapter.cjs +137 -0
  37. package/dist/database/verifyAdapter.d.cts +37 -0
  38. package/dist/database/verifyAdapter.d.mts +37 -0
  39. package/dist/database/verifyAdapter.mjs +136 -0
  40. package/dist/databaseErrors.cjs +30 -0
  41. package/dist/databaseErrors.d.cts +21 -0
  42. package/dist/databaseErrors.d.mts +21 -0
  43. package/dist/databaseErrors.mjs +28 -0
  44. package/dist/databaseJsonValue.cjs +6 -0
  45. package/dist/databaseJsonValue.d.cts +9 -2
  46. package/dist/databaseJsonValue.d.mts +9 -2
  47. package/dist/databaseJsonValue.mjs +6 -0
  48. package/dist/databaseMetadata.cjs +4 -4
  49. package/dist/databaseMetadata.mjs +3 -3
  50. package/dist/databaseRows.cjs +6 -12
  51. package/dist/databaseRows.d.cts +1 -1
  52. package/dist/databaseRows.d.mts +1 -1
  53. package/dist/databaseRows.mjs +1 -7
  54. package/dist/engine/core/schema.cjs +279 -0
  55. package/dist/engine/core/schema.d.cts +312 -0
  56. package/dist/engine/core/schema.d.mts +312 -0
  57. package/dist/engine/core/schema.mjs +277 -0
  58. package/dist/engine/createEngine.cjs +72 -0
  59. package/dist/engine/createEngine.d.cts +45 -0
  60. package/dist/engine/createEngine.d.mts +45 -0
  61. package/dist/engine/createEngine.mjs +72 -0
  62. package/dist/engine/database/aggregateBatching.cjs +627 -0
  63. package/dist/engine/database/aggregateBatching.mjs +626 -0
  64. package/dist/engine/database/cursor.cjs +42 -0
  65. package/dist/engine/database/cursor.mjs +38 -0
  66. package/dist/engine/database/database.cjs +68 -0
  67. package/dist/engine/database/database.mjs +68 -0
  68. package/dist/engine/database/engine.cjs +37 -0
  69. package/dist/engine/database/engine.mjs +37 -0
  70. package/dist/engine/database/engineAggregates.cjs +120 -0
  71. package/dist/engine/database/engineAggregates.mjs +117 -0
  72. package/dist/engine/database/engineReads.cjs +182 -0
  73. package/dist/engine/database/engineReads.d.cts +10 -0
  74. package/dist/engine/database/engineReads.d.mts +10 -0
  75. package/dist/engine/database/engineReads.mjs +181 -0
  76. package/dist/engine/database/engineTransaction.cjs +399 -0
  77. package/dist/engine/database/engineTransaction.d.cts +18 -0
  78. package/dist/engine/database/engineTransaction.d.mts +18 -0
  79. package/dist/engine/database/engineTransaction.mjs +398 -0
  80. package/dist/engine/database/fence.cjs +156 -0
  81. package/dist/engine/database/fence.d.cts +41 -0
  82. package/dist/engine/database/fence.d.mts +41 -0
  83. package/dist/engine/database/fence.mjs +149 -0
  84. package/dist/engine/database/kv/kvAdapter.cjs +293 -0
  85. package/dist/engine/database/kv/kvAdapter.d.cts +116 -0
  86. package/dist/engine/database/kv/kvAdapter.d.mts +116 -0
  87. package/dist/engine/database/kv/kvAdapter.mjs +292 -0
  88. package/dist/engine/database/readMeter.cjs +80 -0
  89. package/dist/engine/database/readMeter.d.cts +34 -0
  90. package/dist/engine/database/readMeter.d.mts +34 -0
  91. package/dist/engine/database/readMeter.mjs +79 -0
  92. package/dist/engine/database/resolveSchema.cjs +197 -0
  93. package/dist/engine/database/resolveSchema.d.cts +35 -0
  94. package/dist/engine/database/resolveSchema.d.mts +35 -0
  95. package/dist/engine/database/resolveSchema.mjs +195 -0
  96. package/dist/engine/database/retention.cjs +100 -0
  97. package/dist/engine/database/retention.mjs +98 -0
  98. package/dist/engine/database/sql/sqlAdapter.cjs +290 -0
  99. package/dist/engine/database/sql/sqlAdapter.d.cts +45 -0
  100. package/dist/engine/database/sql/sqlAdapter.d.mts +45 -0
  101. package/dist/engine/database/sql/sqlAdapter.mjs +288 -0
  102. package/dist/engine/database/sql/sqlSchema.cjs +175 -0
  103. package/dist/engine/database/sql/sqlSchema.d.cts +45 -0
  104. package/dist/engine/database/sql/sqlSchema.d.mts +45 -0
  105. package/dist/engine/database/sql/sqlSchema.mjs +169 -0
  106. package/dist/engine/db/coreDatabase.cjs +94 -0
  107. package/dist/engine/db/coreDatabase.d.cts +78 -0
  108. package/dist/engine/db/coreDatabase.d.mts +78 -0
  109. package/dist/engine/db/coreDatabase.mjs +86 -0
  110. package/dist/engine/db/engineMigrator.cjs +53 -0
  111. package/dist/engine/db/engineMigrator.mjs +53 -0
  112. package/dist/engine/db/engineSql.cjs +26 -0
  113. package/dist/engine/db/engineSql.d.cts +16 -0
  114. package/dist/engine/db/engineSql.d.mts +16 -0
  115. package/dist/engine/db/engineSql.mjs +25 -0
  116. package/dist/engine/db/engineSqlMigrator.cjs +67 -0
  117. package/dist/engine/db/engineSqlMigrator.d.cts +21 -0
  118. package/dist/engine/db/engineSqlMigrator.d.mts +21 -0
  119. package/dist/engine/db/engineSqlMigrator.mjs +67 -0
  120. package/dist/engine/db/fixedMigratorShared.cjs +12 -0
  121. package/dist/engine/db/fixedMigratorShared.mjs +11 -0
  122. package/dist/engine/db/schemaSettings.cjs +63 -0
  123. package/dist/engine/db/schemaSettings.d.cts +7 -0
  124. package/dist/engine/db/schemaSettings.d.mts +7 -0
  125. package/dist/engine/db/schemaSettings.mjs +62 -0
  126. package/dist/engine/db/settingsMigrator.cjs +94 -0
  127. package/dist/engine/db/settingsMigrator.d.cts +25 -0
  128. package/dist/engine/db/settingsMigrator.d.mts +25 -0
  129. package/dist/engine/db/settingsMigrator.mjs +91 -0
  130. package/dist/engine/db/types.d.cts +78 -0
  131. package/dist/engine/db/types.d.mts +78 -0
  132. package/dist/index.cjs +97 -49
  133. package/dist/index.d.cts +46 -22
  134. package/dist/index.d.mts +46 -22
  135. package/dist/index.mjs +32 -17
  136. package/dist/node_modules/.pnpm/verkit@0.4.0/node_modules/verkit/dist/comparison-DenM3wCn.cjs +0 -5
  137. package/dist/node_modules/.pnpm/verkit@0.4.0/node_modules/verkit/dist/comparison-DenM3wCn.mjs +1 -5
  138. package/dist/node_modules/.pnpm/verkit@0.4.0/node_modules/verkit/dist/range-DvX-Y6iv.cjs +8 -0
  139. package/dist/node_modules/.pnpm/verkit@0.4.0/node_modules/verkit/dist/range-DvX-Y6iv.mjs +9 -2
  140. package/dist/node_modules/.pnpm/verkit@0.4.0/node_modules/verkit/dist/set-CC5YeoYX.cjs +4 -0
  141. package/dist/node_modules/.pnpm/verkit@0.4.0/node_modules/verkit/dist/set-CC5YeoYX.mjs +4 -1
  142. package/dist/node_modules/.pnpm/verkit@0.4.0/node_modules/verkit/dist/version-CQ98ZBpL.cjs +0 -5
  143. package/dist/node_modules/.pnpm/verkit@0.4.0/node_modules/verkit/dist/version-CQ98ZBpL.mjs +2 -6
  144. package/dist/releaseCatalogCompiler.cjs +27 -26
  145. package/dist/releaseCatalogCompiler.d.cts +1 -2
  146. package/dist/releaseCatalogCompiler.d.mts +2 -3
  147. package/dist/releaseCatalogCompiler.mjs +5 -9
  148. package/dist/releaseCatalogMutation.cjs +0 -292
  149. package/dist/releaseCatalogMutation.d.cts +4 -45
  150. package/dist/releaseCatalogMutation.d.mts +4 -45
  151. package/dist/releaseCatalogMutation.mjs +1 -288
  152. package/dist/releaseManagement.cjs +0 -221
  153. package/dist/releaseManagement.d.cts +4 -28
  154. package/dist/releaseManagement.d.mts +4 -28
  155. package/dist/releaseManagement.mjs +1 -216
  156. package/dist/remoteBundleSigning.d.cts +2 -2
  157. package/dist/remoteBundleSigning.d.mts +2 -2
  158. package/dist/serverPlugin/busy.cjs +36 -0
  159. package/dist/serverPlugin/busy.d.cts +12 -0
  160. package/dist/serverPlugin/busy.d.mts +12 -0
  161. package/dist/serverPlugin/busy.mjs +36 -0
  162. package/dist/serverPlugin/configError.cjs +7 -0
  163. package/dist/serverPlugin/configError.d.cts +7 -0
  164. package/dist/serverPlugin/configError.d.mts +7 -0
  165. package/dist/serverPlugin/configError.mjs +7 -0
  166. package/dist/serverPlugin/coreReads.d.cts +48 -0
  167. package/dist/serverPlugin/coreReads.d.mts +48 -0
  168. package/dist/serverPlugin/databaseHandle.d.cts +105 -0
  169. package/dist/serverPlugin/databaseHandle.d.mts +105 -0
  170. package/dist/serverPlugin/definePlugin.cjs +5 -0
  171. package/dist/serverPlugin/definePlugin.d.cts +130 -0
  172. package/dist/serverPlugin/definePlugin.d.mts +130 -0
  173. package/dist/serverPlugin/definePlugin.mjs +5 -0
  174. package/dist/serverPlugin/definitions.d.cts +76 -0
  175. package/dist/serverPlugin/definitions.d.mts +76 -0
  176. package/dist/serverPlugin/errors.cjs +37 -0
  177. package/dist/serverPlugin/errors.d.cts +29 -0
  178. package/dist/serverPlugin/errors.d.mts +29 -0
  179. package/dist/serverPlugin/errors.mjs +32 -0
  180. package/dist/serverPlugin/schema.cjs +24 -0
  181. package/dist/serverPlugin/schema.d.cts +90 -0
  182. package/dist/serverPlugin/schema.d.mts +90 -0
  183. package/dist/serverPlugin/schema.mjs +23 -0
  184. package/dist/types/databaseConfig.cjs +5 -0
  185. package/dist/types/databaseConfig.d.cts +68 -0
  186. package/dist/types/databaseConfig.d.mts +68 -0
  187. package/dist/types/databaseConfig.mjs +5 -0
  188. package/dist/types/databaseOperations.d.cts +5 -180
  189. package/dist/types/databaseOperations.d.mts +5 -180
  190. package/dist/types/databaseRows.d.cts +5 -56
  191. package/dist/types/databaseRows.d.mts +5 -56
  192. package/dist/types/index.cjs +2 -0
  193. package/dist/types/index.d.cts +31 -97
  194. package/dist/types/index.d.mts +31 -97
  195. package/dist/types/index.mjs +2 -1
  196. package/dist/types/models.d.cts +14 -0
  197. package/dist/types/models.d.mts +14 -0
  198. package/dist/types/public.d.cts +4 -3
  199. package/dist/types/public.d.mts +4 -3
  200. package/dist/uuidv7.cjs +3 -3
  201. package/dist/uuidv7.d.cts +1 -1
  202. package/dist/uuidv7.d.mts +1 -1
  203. package/dist/uuidv7.mjs +1 -1
  204. package/package.json +10 -7
  205. package/dist/calculatePagination.cjs +0 -25
  206. package/dist/calculatePagination.d.cts +0 -12
  207. package/dist/calculatePagination.d.mts +0 -12
  208. package/dist/calculatePagination.mjs +0 -25
  209. package/dist/compressionFormat.cjs +0 -62
  210. package/dist/compressionFormat.d.cts +0 -33
  211. package/dist/compressionFormat.d.mts +0 -33
  212. package/dist/compressionFormat.mjs +0 -58
  213. package/dist/createDatabasePlugin.cjs +0 -920
  214. package/dist/createDatabasePlugin.d.cts +0 -28
  215. package/dist/createDatabasePlugin.d.mts +0 -28
  216. package/dist/createDatabasePlugin.mjs +0 -916
  217. package/dist/createStoragePlugin.cjs +0 -8
  218. package/dist/createStoragePlugin.d.cts +0 -9
  219. package/dist/createStoragePlugin.d.mts +0 -9
  220. package/dist/createStoragePlugin.mjs +0 -7
  221. package/dist/databaseClient.cjs +0 -117
  222. package/dist/databaseClient.d.cts +0 -32
  223. package/dist/databaseClient.d.mts +0 -32
  224. package/dist/databaseClient.mjs +0 -114
  225. package/dist/databaseClientReads.cjs +0 -115
  226. package/dist/databaseClientReads.mjs +0 -113
  227. package/dist/databaseClientUpdates.cjs +0 -40
  228. package/dist/databaseClientUpdates.d.cts +0 -11
  229. package/dist/databaseClientUpdates.d.mts +0 -11
  230. package/dist/databaseClientUpdates.mjs +0 -38
  231. package/dist/databasePluginCrud.cjs +0 -88
  232. package/dist/databasePluginCrud.d.cts +0 -4
  233. package/dist/databasePluginCrud.d.mts +0 -4
  234. package/dist/databasePluginCrud.mjs +0 -87
  235. package/dist/databasePluginCrudValidation.d.cts +0 -6
  236. package/dist/databasePluginCrudValidation.d.mts +0 -6
  237. package/dist/databasePluginCrudValidationErrors.cjs +0 -11
  238. package/dist/databasePluginCrudValidationErrors.d.cts +0 -9
  239. package/dist/databasePluginCrudValidationErrors.d.mts +0 -9
  240. package/dist/databasePluginCrudValidationErrors.mjs +0 -11
  241. package/dist/databasePluginCrudValidationFields.cjs +0 -321
  242. package/dist/databasePluginCrudValidationFields.d.cts +0 -1
  243. package/dist/databasePluginCrudValidationFields.d.mts +0 -1
  244. package/dist/databasePluginCrudValidationFields.mjs +0 -309
  245. package/dist/databasePluginCrudValidationMutations.cjs +0 -107
  246. package/dist/databasePluginCrudValidationMutations.d.cts +0 -1
  247. package/dist/databasePluginCrudValidationMutations.d.mts +0 -1
  248. package/dist/databasePluginCrudValidationMutations.mjs +0 -100
  249. package/dist/databasePluginCrudValidationQueries.cjs +0 -103
  250. package/dist/databasePluginCrudValidationQueries.d.cts +0 -2
  251. package/dist/databasePluginCrudValidationQueries.d.mts +0 -2
  252. package/dist/databasePluginCrudValidationQueries.mjs +0 -97
  253. package/dist/databasePluginCrudValidationRows.cjs +0 -55
  254. package/dist/databasePluginCrudValidationRows.d.cts +0 -1
  255. package/dist/databasePluginCrudValidationRows.d.mts +0 -1
  256. package/dist/databasePluginCrudValidationRows.mjs +0 -53
  257. package/dist/databasePluginTransaction.cjs +0 -7
  258. package/dist/databasePluginTransaction.mjs +0 -7
  259. package/dist/insightsContract.cjs +0 -157
  260. package/dist/insightsContract.d.cts +0 -11
  261. package/dist/insightsContract.d.mts +0 -11
  262. package/dist/insightsContract.mjs +0 -153
  263. package/dist/internal.cjs +0 -6
  264. package/dist/internal.d.cts +0 -10
  265. package/dist/internal.d.mts +0 -10
  266. package/dist/internal.mjs +0 -3
  267. package/dist/paginateBundles.cjs +0 -53
  268. package/dist/paginateBundles.d.cts +0 -13
  269. package/dist/paginateBundles.d.mts +0 -13
  270. package/dist/paginateBundles.mjs +0 -53
  271. package/dist/queryBundles.cjs +0 -34
  272. package/dist/queryBundles.d.cts +0 -9
  273. package/dist/queryBundles.d.mts +0 -9
  274. package/dist/queryBundles.mjs +0 -32
  275. package/dist/requestBundleCache.cjs +0 -22
  276. package/dist/requestBundleCache.d.cts +0 -8
  277. package/dist/requestBundleCache.d.mts +0 -8
  278. package/dist/requestBundleCache.mjs +0 -22
  279. package/dist/types/database.d.cts +0 -5
  280. package/dist/types/database.d.mts +0 -5
  281. package/dist/types/databaseFields.cjs +0 -105
  282. package/dist/types/databaseFields.d.cts +0 -13
  283. package/dist/types/databaseFields.d.mts +0 -13
  284. package/dist/types/databaseFields.mjs +0 -105
  285. package/dist/types/databasePlugin.d.cts +0 -298
  286. package/dist/types/databasePlugin.d.mts +0 -298
  287. package/dist/types/databaseQuery.d.cts +0 -46
  288. package/dist/types/databaseQuery.d.mts +0 -46
  289. package/dist/types/internal.d.cts +0 -8
  290. package/dist/types/internal.d.mts +0 -8
@@ -0,0 +1,627 @@
1
+ const require_schema = require("../../serverPlugin/schema.cjs");
2
+ const require_errors = require("../../serverPlugin/errors.cjs");
3
+ require("../../database/adapter.cjs");
4
+ const require_values = require("../../database/values.cjs");
5
+ const require_engineAggregates = require("./engineAggregates.cjs");
6
+ //#region src/engine/database/aggregateBatching.ts
7
+ /** Log rows spread over 8 tables, each its own DynamoDB partition. */
8
+ const LOG_TABLES = [
9
+ 0,
10
+ 1,
11
+ 2,
12
+ 3,
13
+ 4,
14
+ 5,
15
+ 6,
16
+ 7
17
+ ].map((at) => `aggregate_log_${at}`);
18
+ const LEASE_TABLE = "aggregate_lease";
19
+ const LEASE = { id: "compaction" };
20
+ /** How long a compaction holds the lease before another process may take it. */
21
+ const LEASE_MS = 3e4;
22
+ /**
23
+ * Default windows: log mode compacts every 60 seconds, since reads compact
24
+ * first; memory mode flushes every 15, since its window is what a crash
25
+ * loses.
26
+ */
27
+ const WINDOW_MS = {
28
+ log: 6e4,
29
+ memory: 15e3
30
+ };
31
+ /** Log rows a compaction reads from each log table for one group. */
32
+ const LOG_PAGE = 200;
33
+ /**
34
+ * Groups one compaction applies: after a commit, so the request that runs
35
+ * it waits for one group; before a read; and on flush.
36
+ */
37
+ const GROUPS = {
38
+ commit: 1,
39
+ read: 8,
40
+ flush: 256
41
+ };
42
+ /** Tries per write after a conflict or a transient error. */
43
+ const ATTEMPTS = 5;
44
+ /** Aggregate rows a memory buffer holds before a commit waits for a flush. */
45
+ const MAX_BUFFERED = 1e4;
46
+ const log = require_schema.defineTable({
47
+ id: {
48
+ type: "string",
49
+ maxLength: 32
50
+ },
51
+ /** One committed transaction's changes, one entry per aggregate row. */
52
+ changes: { type: "string" }
53
+ }, {
54
+ key: ["id"],
55
+ indexes: { oldest: {
56
+ eq: [],
57
+ sort: ["id"]
58
+ } }
59
+ });
60
+ /**
61
+ * Held by `holder` until `until`; the next compaction is due at `next`.
62
+ * `applied` lists the log rows a compaction has applied and not yet deleted,
63
+ * as `[log table's index, id]` pairs, so no compaction applies them again.
64
+ */
65
+ const lease = require_schema.defineTable({
66
+ id: {
67
+ type: "string",
68
+ maxLength: 16
69
+ },
70
+ holder: {
71
+ type: "string",
72
+ maxLength: 32
73
+ },
74
+ until: { type: "integer" },
75
+ next: { type: "integer" },
76
+ applied: { type: "string" }
77
+ }, { key: ["id"] });
78
+ /** The log and lease tables; an engine that batches has them in its schema. */
79
+ const aggregateBatchingModule = {
80
+ id: "aggregateBatching",
81
+ schema: {
82
+ ...Object.fromEntries(LOG_TABLES.map((table) => [table, log])),
83
+ [LEASE_TABLE]: lease
84
+ }
85
+ };
86
+ const shapeOf = (model) => model.definition;
87
+ const isBatched = (model) => model?.definition.kind === "aggregate" && shapeOf(model).batched === true;
88
+ const valuesOf = ({ deltas, sketches }) => ({
89
+ ...deltas,
90
+ ...sketches
91
+ });
92
+ /**
93
+ * Merges `values` into the change for `key`'s identity as `tx.aggregate`
94
+ * does: deltas add up and sketches merge. One constant `shardBy` keys each
95
+ * identity to one entry; the write picks the shard.
96
+ */
97
+ const merge = (into, model, key, values) => require_engineAggregates.recordAggregate(into, model, Object.fromEntries(shapeOf(model).key.map((field, at) => [field, key[at]])), values, "");
98
+ const mergeAll = (into, changes) => {
99
+ for (const change of changes) merge(into, change.model, change.key, valuesOf(change));
100
+ return into;
101
+ };
102
+ /** A row's metrics as values to merge: counters, gauges, and the sketches it has. */
103
+ const metricsOf = (model, row) => {
104
+ const { counters, gauges, distinct } = shapeOf(model);
105
+ return Object.fromEntries([...[...counters, ...gauges].map((name) => [name, Number(row[name] ?? 0)]), ...distinct.flatMap((name) => row[name] === null || row[name] === void 0 ? [] : [[name, row[name]]])]);
106
+ };
107
+ /** A shard row before its first change: every metric zero or empty. */
108
+ const blank = (model, key) => {
109
+ const { counters, gauges, distinct } = shapeOf(model);
110
+ return Object.fromEntries([
111
+ ...model.table.key.map((column, at) => [column, key[at]]),
112
+ ...[...counters, ...gauges].map((name) => [name, 0]),
113
+ ...distinct.map((name) => [name, null]),
114
+ ["_v", 0]
115
+ ]);
116
+ };
117
+ /** Whether a change needs its row: sketches merge, and a gauge may reach zero. */
118
+ const rewrites = ({ model, deltas, sketches }) => Object.keys(sketches).length > 0 || shapeOf(model).gauges.some((gauge) => (deltas[gauge] ?? 0) !== 0);
119
+ const increment = ({ model, deltas }, key) => Object.values(deltas).some((delta) => delta !== 0) ? {
120
+ type: "increment",
121
+ table: model.table,
122
+ key,
123
+ by: deltas,
124
+ init: blank(model, key)
125
+ } : void 0;
126
+ /**
127
+ * The guarded write that merges `change` into `current`: insert, patch, or
128
+ * delete at zero. Unlike a transaction's, a gauge may go below zero here: a
129
+ * shard row holds one writer's net changes, and reads sum every shard.
130
+ */
131
+ const rewrite = (change, key, current) => {
132
+ const { model } = change;
133
+ const { table } = model;
134
+ const { counters, gauges, distinct } = shapeOf(model);
135
+ const base = current ?? blank(model, key);
136
+ const sum = mergeAll(/* @__PURE__ */ new Map(), [change]);
137
+ merge(sum, model, key, metricsOf(model, base));
138
+ const set = valuesOf([...sum.values()][0]);
139
+ if (current && Object.keys(set).every((name) => current[name] === set[name])) return void 0;
140
+ const row = {
141
+ ...base,
142
+ ...set
143
+ };
144
+ const zero = distinct.length === 0 && [...counters, ...gauges].every((name) => Number(row[name]) === 0);
145
+ if (current === null) return zero ? void 0 : {
146
+ type: "insert",
147
+ table,
148
+ row
149
+ };
150
+ const guard = { v: Number(current["_v"]) };
151
+ return zero ? {
152
+ type: "delete",
153
+ table,
154
+ key,
155
+ guard,
156
+ previous: current
157
+ } : {
158
+ type: "patch",
159
+ table,
160
+ key,
161
+ set,
162
+ guard,
163
+ previous: current
164
+ };
165
+ };
166
+ /**
167
+ * The write for each change on its shard: a blind increment that creates
168
+ * the row for counters, and a guarded rewrite for gauges and sketches, whose
169
+ * rows are read in one batch per table.
170
+ */
171
+ const compile = async (adapter, changes, shard) => {
172
+ const keys = changes.map(({ model, key }) => [...key.slice(0, -1), shard(model)]);
173
+ const reads = /* @__PURE__ */ new Map();
174
+ changes.forEach((change, at) => {
175
+ if (rewrites(change)) reads.set(change.model, [...reads.get(change.model) ?? [], at]);
176
+ });
177
+ const current = /* @__PURE__ */ new Map();
178
+ await Promise.all([...reads].map(async ([model, positions]) => {
179
+ const rows = await adapter.get(model.table, positions.map((at) => keys[at]));
180
+ positions.forEach((at, index) => current.set(at, rows[index] ?? null));
181
+ }));
182
+ return changes.map((change, at) => current.has(at) ? rewrite(change, keys[at], current.get(at)) : increment(change, keys[at]));
183
+ };
184
+ const isOp = (op) => op !== void 0;
185
+ const sleep = (attempt) => new Promise((resolve) => setTimeout(resolve, Math.min(250, 5 * 2 ** attempt) * Math.random()));
186
+ /** Runs of one character, where shorter: a sparse sketch packs into a few. */
187
+ const pack = (text) => {
188
+ const runs = (text.match(/(.)\1*/gsu) ?? []).flatMap((run) => [run[0], run.length]);
189
+ return JSON.stringify(runs).length < JSON.stringify(text).length ? runs : text;
190
+ };
191
+ const unpack = (value) => Array.isArray(value) ? value.map((item, at) => at % 2 ? "" : item.repeat(value[at + 1])).join("") : value;
192
+ /** Raw deflate of `text` as base64, where the runtime has `CompressionStream`. */
193
+ const deflate = async (text) => {
194
+ if (typeof CompressionStream === "undefined") return void 0;
195
+ const stream = new Blob([text]).stream().pipeThrough(new CompressionStream("deflate-raw"));
196
+ let binary = "";
197
+ for (const byte of new Uint8Array(await new Response(stream).arrayBuffer())) binary += String.fromCharCode(byte);
198
+ return btoa(binary);
199
+ };
200
+ const inflate = (base64) => new Response(new Blob([Uint8Array.from(atob(base64), (char) => char.charCodeAt(0))]).stream().pipeThrough(new DecompressionStream("deflate-raw"))).text();
201
+ /**
202
+ * A log row's `changes`: entries of a table, an identity, and values, as
203
+ * JSON, or `z` and its deflate where shorter, so a row stays under the 1 KB
204
+ * that DynamoDB bills as one unit.
205
+ */
206
+ const encode = async (changes) => {
207
+ const json = JSON.stringify({
208
+ v: 1,
209
+ c: [...changes].map(({ model, key, deltas, sketches }) => {
210
+ const packed = Object.entries(sketches).map(([name, sketch]) => [name, pack(sketch)]);
211
+ const values = {
212
+ ...deltas,
213
+ ...Object.fromEntries(packed)
214
+ };
215
+ return [
216
+ model.table.name,
217
+ key.slice(0, -1),
218
+ values
219
+ ];
220
+ })
221
+ });
222
+ const zipped = await deflate(json);
223
+ return zipped !== void 0 && zipped.length < json.length ? `z${zipped}` : json;
224
+ };
225
+ /**
226
+ * Batches changes to aggregates declared `batched`. A transaction records
227
+ * them without writing their rows; once it commits, "memory" mode keeps
228
+ * them in this process until its timer flushes them, and "log" mode has
229
+ * written them as one log row in the same atomic write, which a compaction
230
+ * later merges into the aggregates and deletes, atomically again, so each
231
+ * applies exactly once. One lease row keeps compactions one at a time.
232
+ */
233
+ const createAggregateBatches = ({ engine, adapter, schema, batching: { mode = "log", windowMs = WINDOW_MS[mode] }, now }) => {
234
+ if (!schema.models.has(LEASE_TABLE)) throw new require_errors.DatabaseTransactionError("An engine that batches aggregates needs aggregateBatchingModule in its schema.");
235
+ const holder = crypto.randomUUID().replaceAll("-", "");
236
+ const table = (name) => schema.models.get(name).table;
237
+ const warned = /* @__PURE__ */ new Set();
238
+ const warn = (what) => (error) => {
239
+ if (warned.has(what)) return;
240
+ warned.add(what);
241
+ console.warn(`[hot-updater] Aggregate ${what} failed.`, error);
242
+ };
243
+ /** A log row's changes, or undefined when it names an aggregate or metric this schema lacks. */
244
+ const decode = async (text) => {
245
+ const changes = /* @__PURE__ */ new Map();
246
+ try {
247
+ const json = text.startsWith("z") ? await inflate(text.slice(1)) : text;
248
+ const { c } = JSON.parse(json);
249
+ for (const [name, identity, values] of c) {
250
+ const model = schema.models.get(name);
251
+ if (!isBatched(model)) return void 0;
252
+ const unpacked = Object.entries(values).map(([metric, value]) => [metric, unpack(value)]);
253
+ merge(changes, model, [...identity, 0], Object.fromEntries(unpacked));
254
+ }
255
+ } catch (error) {
256
+ warn("log decoding")(error);
257
+ return;
258
+ }
259
+ return changes;
260
+ };
261
+ /**
262
+ * Writes changes in atomic chunks within `fits`, and returns the ones it
263
+ * could not apply. A write whose outcome is unknown is dropped, never
264
+ * resent, so no change applies twice.
265
+ */
266
+ const apply = async (changes, shard) => {
267
+ let rest = changes;
268
+ let ops = [];
269
+ let read = true;
270
+ for (let failures = 0; rest.length > 0 && failures < ATTEMPTS;) try {
271
+ if (read) ops = await compile(adapter, rest, shard);
272
+ let size = rest.length;
273
+ const chunk = () => ops.slice(0, size).filter(isOp);
274
+ while (size > 1 && !adapter.fits(chunk())) size = Math.ceil(size / 2);
275
+ let result = { ok: true };
276
+ if (chunk().length > 0) result = await adapter.write(chunk()).catch((error) => {
277
+ warn("flush")(error);
278
+ return { ok: true };
279
+ });
280
+ read = !result.ok && !("retry" in result);
281
+ if (result.ok) {
282
+ rest = rest.slice(size);
283
+ ops = ops.slice(size);
284
+ failures = 0;
285
+ } else {
286
+ failures += 1;
287
+ if (!read) await sleep(failures);
288
+ }
289
+ } catch (error) {
290
+ warn("flush")(error);
291
+ return rest;
292
+ }
293
+ return rest;
294
+ };
295
+ let buffer = /* @__PURE__ */ new Map();
296
+ let timer;
297
+ let flushing;
298
+ const shards = /* @__PURE__ */ new Map();
299
+ /** Each process writes its own shard, so flushes of two processes rarely meet. */
300
+ const processShard = (model) => {
301
+ if (!shards.has(model)) shards.set(model, Math.floor(Math.random() * shapeOf(model).shards));
302
+ return shards.get(model);
303
+ };
304
+ const schedule = () => {
305
+ if (timer !== void 0 || buffer.size === 0) return;
306
+ timer = setTimeout(() => {
307
+ timer = void 0;
308
+ flushBuffer();
309
+ }, windowMs);
310
+ timer.unref?.();
311
+ };
312
+ /** Never rejects: what it cannot apply goes back into the buffer. */
313
+ const flushBuffer = () => flushing ??= (async () => {
314
+ clearTimeout(timer);
315
+ timer = void 0;
316
+ const pending = [...buffer.values()];
317
+ buffer = /* @__PURE__ */ new Map();
318
+ mergeAll(buffer, await apply(pending, processShard));
319
+ })().catch(warn("flush")).finally(() => {
320
+ flushing = void 0;
321
+ schedule();
322
+ });
323
+ let nextDue = 0;
324
+ let compacting;
325
+ /** Log rows this process read, by `[log table's index, id]`, for the deletes after a group. */
326
+ const known = /* @__PURE__ */ new Map();
327
+ const idOf = (shard, id) => JSON.stringify([shard, id]);
328
+ /** The lease row as stored once `set` is written over it. */
329
+ const leaseOp = (held, set) => {
330
+ const next = {
331
+ ...held,
332
+ ...set,
333
+ _v: Number(held._v) + 1
334
+ };
335
+ return {
336
+ op: {
337
+ type: "patch",
338
+ table: table(LEASE_TABLE),
339
+ key: [LEASE.id],
340
+ set,
341
+ guard: { v: Number(held._v) },
342
+ previous: held
343
+ },
344
+ next
345
+ };
346
+ };
347
+ /** The lease row as stored after this process takes it, or undefined when it is held or not due. */
348
+ const takeLease = (force) => engine.transaction(async (tx) => {
349
+ const at = now();
350
+ const held = await tx.findOne(LEASE_TABLE, LEASE);
351
+ const fields = {
352
+ holder,
353
+ until: at + LEASE_MS
354
+ };
355
+ if (held === null) {
356
+ const row = {
357
+ ...LEASE,
358
+ ...fields,
359
+ next: 0,
360
+ applied: "[]"
361
+ };
362
+ tx.create(LEASE_TABLE, row);
363
+ return {
364
+ ...row,
365
+ _v: 0
366
+ };
367
+ }
368
+ nextDue = Number(held.next);
369
+ if (held.holder !== holder && Number(held.until) > at || !force && nextDue > at) return void 0;
370
+ tx.update(LEASE_TABLE, held, fields);
371
+ return {
372
+ ...held,
373
+ ...fields,
374
+ _v: Number(held._v) + 1
375
+ };
376
+ });
377
+ /**
378
+ * Writes `ops` once, retrying transient errors; true when it committed.
379
+ * A conflict leaves its log rows for the next compaction; a write whose
380
+ * outcome is unknown throws, and the next compaction reads what it did.
381
+ */
382
+ const commit = async (ops) => {
383
+ for (let failures = 0; failures < ATTEMPTS; failures += 1) {
384
+ const result = await adapter.write(ops);
385
+ if (result.ok) return true;
386
+ if (!("retry" in result)) return false;
387
+ await sleep(failures);
388
+ }
389
+ return false;
390
+ };
391
+ /** Deletes the log rows `held` lists as applied, in parallel writes; true once none is left. */
392
+ const deleteApplied = async (held) => {
393
+ const applied = JSON.parse(String(held.applied));
394
+ await Promise.all(LOG_TABLES.map(async (name, shard) => {
395
+ const ids = applied.flatMap(([at, id]) => at === shard && !known.has(idOf(at, id)) ? [id] : []);
396
+ if (ids.length === 0) return;
397
+ const rows = await adapter.get(table(name), ids.map((id) => [id]));
398
+ for (const row of rows) if (row) known.set(idOf(shard, row.id), row);
399
+ }));
400
+ const rows = applied.flatMap(([shard, id]) => {
401
+ const row = known.get(idOf(shard, id));
402
+ return row === void 0 ? [] : [{
403
+ shard,
404
+ row
405
+ }];
406
+ });
407
+ if (adapter.deleteConsumed && await Promise.all(LOG_TABLES.map((name, at) => {
408
+ const own = rows.flatMap(({ shard, row }) => shard === at ? [row] : []);
409
+ return own.length > 0 && adapter.deleteConsumed(table(name), own);
410
+ })).then(() => true, (error) => (warn("log cleanup")(error), false))) {
411
+ for (const [shard, id] of applied) known.delete(idOf(shard, id));
412
+ return true;
413
+ }
414
+ const deletes = rows.map(({ shard, row }) => {
415
+ const guard = { v: Number(row["_v"]) };
416
+ return {
417
+ type: "delete",
418
+ table: table(LOG_TABLES[shard]),
419
+ key: [String(row.id)],
420
+ guard,
421
+ previous: row
422
+ };
423
+ });
424
+ let size = deletes.length;
425
+ while (size > 1 && !adapter.fits(deletes.slice(0, size))) size = Math.ceil(size / 2);
426
+ const chunks = [];
427
+ for (let at = 0; at < deletes.length; at += size) chunks.push(deletes.slice(at, at + size));
428
+ if ((await Promise.all(chunks.map(commit))).includes(false)) return false;
429
+ for (const [shard, id] of applied) known.delete(idOf(shard, id));
430
+ return true;
431
+ };
432
+ /**
433
+ * The oldest pending log rows this schema can read, a page from each
434
+ * table; `more` when a page was full, so more may wait.
435
+ */
436
+ const readLogs = async () => {
437
+ let more = false;
438
+ return {
439
+ logs: (await Promise.all(LOG_TABLES.map(async (name, shard) => {
440
+ const page = await engine.reads.findMany(name, {
441
+ index: "oldest",
442
+ limit: LOG_PAGE
443
+ });
444
+ more ||= page.next !== void 0;
445
+ return (await Promise.all(page.rows.map(async (row) => ({
446
+ shard,
447
+ row,
448
+ changes: await decode(String(row.changes))
449
+ })))).flatMap(({ changes, ...entry }) => changes === void 0 ? [] : [{
450
+ ...entry,
451
+ changes
452
+ }]);
453
+ }))).flat().sort((left, right) => require_values.compareUtf8(String(left.row.id), String(right.row.id))),
454
+ more
455
+ };
456
+ };
457
+ const rowsFor = async (changes) => (await compile(adapter, changes, () => 0)).filter(isOp);
458
+ /**
459
+ * Applies the oldest pending log rows whose merged changes fit in one
460
+ * atomic write with the lease, which lists them as applied; the rows are
461
+ * deleted after it. A log row too large for one write applies in parts,
462
+ * keeping the rest in it. Returns the lease after the write and how many
463
+ * log rows it applied whole, or undefined when a conflict stopped it.
464
+ */
465
+ const applyGroup = async (held, logs) => {
466
+ for (let count = logs.length; count > 0; count = Math.floor(count / 2)) {
467
+ const batch = logs.slice(0, count);
468
+ const changes = mergeAll(/* @__PURE__ */ new Map(), batch.flatMap((entry) => [...entry.changes.values()]));
469
+ const applied = batch.map(({ shard, row }) => [shard, row.id]);
470
+ const lease = leaseOp(held, { applied: JSON.stringify(applied) });
471
+ const ops = [...await rowsFor([...changes.values()]), lease.op];
472
+ if (!adapter.fits(ops)) continue;
473
+ for (const { shard, row } of batch) known.set(idOf(shard, row.id), row);
474
+ return await commit(ops) ? {
475
+ held: lease.next,
476
+ count
477
+ } : void 0;
478
+ }
479
+ const [{ shard, row, changes }] = logs;
480
+ const name = LOG_TABLES[shard];
481
+ const entries = [...changes.values()];
482
+ for (let take = entries.length - 1; take > 0; take = Math.floor(take / 2)) {
483
+ const kept = {
484
+ type: "patch",
485
+ table: table(name),
486
+ key: [String(row.id)],
487
+ set: { changes: await encode(entries.slice(take)) },
488
+ guard: { v: Number(row["_v"]) },
489
+ previous: row
490
+ };
491
+ const lease = leaseOp(held, {});
492
+ const ops = [
493
+ ...await rowsFor(entries.slice(0, take)),
494
+ kept,
495
+ lease.op
496
+ ];
497
+ if (adapter.fits(ops)) return await commit(ops) ? {
498
+ held: lease.next,
499
+ count: 0
500
+ } : void 0;
501
+ }
502
+ throw new require_errors.DatabaseTransactionError(`${name}: one aggregate change does not fit in one write.`);
503
+ };
504
+ /**
505
+ * Applies up to `groups` groups under the lease, deleting each group's log
506
+ * rows before the next; the next compaction is due at once when some are
507
+ * left. The lease release clears the applied list once its rows are gone.
508
+ */
509
+ const run = async (force, groups) => {
510
+ let held = await takeLease(force);
511
+ if (held === void 0) return;
512
+ let pending = true;
513
+ let clear = false;
514
+ try {
515
+ for (let group = 0;; group += 1) {
516
+ clear = await deleteApplied(held);
517
+ if (!clear || !pending || group === groups) break;
518
+ const { logs, more } = await readLogs();
519
+ if (logs.length === 0) {
520
+ pending = false;
521
+ break;
522
+ }
523
+ const applied = await applyGroup(held, logs);
524
+ if (applied === void 0) break;
525
+ [held, clear] = [applied.held, false];
526
+ pending = more || applied.count < logs.length;
527
+ }
528
+ } finally {
529
+ nextDue = now() + (pending ? 0 : windowMs);
530
+ const set = {
531
+ until: 0,
532
+ next: nextDue,
533
+ ...clear ? { applied: "[]" } : {}
534
+ };
535
+ await commit([leaseOp(held, set).op]);
536
+ known.clear();
537
+ }
538
+ };
539
+ /** One compaction at a time in this process; never rejects. */
540
+ const compact = (force, groups) => compacting ??= run(force, groups).catch(warn("compaction")).finally(() => {
541
+ compacting = void 0;
542
+ });
543
+ let checking;
544
+ /** Whether any log row waits; reads at once share one check. */
545
+ const hasPending = () => checking ??= Promise.all(LOG_TABLES.map((name) => engine.reads.findMany(name, {
546
+ index: "oldest",
547
+ limit: 1
548
+ }))).then((pages) => pages.some((page) => page.rows.length > 0)).finally(() => {
549
+ checking = void 0;
550
+ });
551
+ /** Takes a committed transaction's changes; never rejects, since the transaction already committed. */
552
+ const committed = async (changes) => {
553
+ if (mode === "log") {
554
+ if (now() >= nextDue) await compact(false, GROUPS.commit);
555
+ return;
556
+ }
557
+ mergeAll(buffer, changes.values());
558
+ schedule();
559
+ if (buffer.size >= MAX_BUFFERED) await flushBuffer();
560
+ };
561
+ const flush = async () => {
562
+ await flushBuffer();
563
+ if (mode === "log" && await hasPending()) await compact(true, GROUPS.flush);
564
+ };
565
+ return {
566
+ async transaction(fn) {
567
+ let changes = /* @__PURE__ */ new Map();
568
+ const result = await engine.transaction(async (tx) => {
569
+ const attempt = /* @__PURE__ */ new Map();
570
+ changes = attempt;
571
+ let open = true;
572
+ let failure;
573
+ const aggregate = (name, identity, values, options) => {
574
+ const model = schema.models.get(name);
575
+ if (!isBatched(model)) return tx.aggregate(name, identity, values, options);
576
+ try {
577
+ if (!open) throw new require_errors.DatabaseTransactionError("The transaction has ended.");
578
+ require_engineAggregates.recordAggregate(attempt, model, identity, values, options?.shardBy);
579
+ } catch (error) {
580
+ failure ??= { error };
581
+ throw error;
582
+ }
583
+ };
584
+ try {
585
+ const value = await fn({
586
+ ...tx,
587
+ aggregate
588
+ });
589
+ if (failure) throw failure.error;
590
+ if (mode === "log" && attempt.size > 0) {
591
+ const id = `${now().toString(36).padStart(9, "0")}${holder.slice(0, 8)}${crypto.randomUUID().slice(0, 8)}`;
592
+ const shard = Math.floor(Math.random() * LOG_TABLES.length);
593
+ const merged = mergeAll(/* @__PURE__ */ new Map(), attempt.values());
594
+ tx.create(LOG_TABLES[shard], {
595
+ id,
596
+ changes: await encode(merged.values())
597
+ });
598
+ }
599
+ return value;
600
+ } finally {
601
+ open = false;
602
+ }
603
+ });
604
+ if (changes.size > 0) await committed(changes);
605
+ return result;
606
+ },
607
+ async beforeRead(name) {
608
+ if (!isBatched(schema.models.get(name))) return;
609
+ if (buffer.size > 0 || flushing !== void 0) await flushBuffer();
610
+ if (mode === "log") {
611
+ if (await hasPending().catch((error) => {
612
+ warn("read")(error);
613
+ return false;
614
+ })) await compact(true, GROUPS.read);
615
+ }
616
+ },
617
+ flush,
618
+ async dispose() {
619
+ clearTimeout(timer);
620
+ timer = void 0;
621
+ await flush();
622
+ }
623
+ };
624
+ };
625
+ //#endregion
626
+ exports.aggregateBatchingModule = aggregateBatchingModule;
627
+ exports.createAggregateBatches = createAggregateBatches;