@jam-overture/loom 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (290) hide show
  1. package/README.md +3 -1
  2. package/dist/application/application.d.ts +109 -0
  3. package/dist/application/application.js +97 -0
  4. package/dist/application/memory.d.ts +20 -0
  5. package/dist/application/memory.js +79 -0
  6. package/dist/application/store.d.ts +101 -0
  7. package/dist/application/store.js +25 -0
  8. package/dist/audience/audience.d.ts +36 -0
  9. package/dist/audience/audience.js +41 -0
  10. package/dist/cli/templates.js +19 -0
  11. package/dist/data/plan.js +0 -0
  12. package/dist/data/resolution.d.ts +23 -1
  13. package/dist/data/resolve.d.ts +30 -3
  14. package/dist/data/resolve.js +11 -3
  15. package/dist/ids.d.ts +10 -0
  16. package/dist/ids.js +11 -1
  17. package/dist/index.d.ts +1 -0
  18. package/dist/index.js +1 -0
  19. package/dist/patch.d.ts +54 -0
  20. package/dist/patch.js +44 -0
  21. package/dist/project/closing.d.ts +51 -0
  22. package/dist/project/closing.js +53 -0
  23. package/dist/project/memory.d.ts +20 -0
  24. package/dist/project/memory.js +97 -0
  25. package/dist/project/project.d.ts +90 -0
  26. package/dist/project/project.js +91 -0
  27. package/dist/project/store.d.ts +135 -0
  28. package/dist/project/store.js +41 -0
  29. package/dist/registered.d.ts +64 -0
  30. package/dist/registered.js +118 -0
  31. package/dist/render/behaviour-adjust.d.ts +11 -19
  32. package/dist/render/behaviour-adjust.js +75 -21
  33. package/dist/render/behaviour-present.d.ts +8 -0
  34. package/dist/render/behaviour-present.js +57 -6
  35. package/dist/render/behaviour.d.ts +98 -17
  36. package/dist/render/behaviour.js +91 -26
  37. package/dist/render/control-name.d.ts +68 -0
  38. package/dist/render/control-name.js +37 -0
  39. package/dist/render/diagnostics.d.ts +72 -0
  40. package/dist/render/diagnostics.js +7 -0
  41. package/dist/render/index.d.ts +2 -0
  42. package/dist/render/index.js +2 -0
  43. package/dist/render/reads.d.ts +11 -0
  44. package/dist/render/reads.js +12 -1
  45. package/dist/render/render.js +102 -7
  46. package/dist/render/slots.d.ts +52 -0
  47. package/dist/render/slots.js +24 -0
  48. package/dist/render/theme.d.ts +54 -1
  49. package/dist/render/theme.js +23 -1
  50. package/dist/render/unshown.d.ts +152 -0
  51. package/dist/render/unshown.js +80 -0
  52. package/dist/runtime/analysis.d.ts +94 -9
  53. package/dist/runtime/analysis.js +54 -9
  54. package/dist/runtime/assessment.d.ts +36 -2
  55. package/dist/runtime/assessment.js +27 -2
  56. package/dist/runtime/checks.d.ts +148 -0
  57. package/dist/runtime/checks.js +112 -0
  58. package/dist/runtime/disposition.d.ts +96 -0
  59. package/dist/runtime/disposition.js +46 -0
  60. package/dist/runtime/gate.js +22 -0
  61. package/dist/runtime/index.d.ts +3 -0
  62. package/dist/runtime/index.js +3 -0
  63. package/dist/runtime/irreversibility.d.ts +64 -0
  64. package/dist/runtime/irreversibility.js +45 -0
  65. package/dist/runtime/pipeline.d.ts +43 -0
  66. package/dist/runtime/pipeline.js +10 -2
  67. package/dist/runtime/policy-change.d.ts +93 -0
  68. package/dist/runtime/policy-change.js +299 -0
  69. package/dist/runtime/policy-log.d.ts +406 -0
  70. package/dist/runtime/policy-log.js +285 -0
  71. package/dist/runtime/reversibility.d.ts +11 -9
  72. package/dist/runtime/stakes.d.ts +129 -1
  73. package/dist/runtime/stakes.js +240 -26
  74. package/dist/runtime/vocabulary.d.ts +164 -7
  75. package/dist/runtime/vocabulary.js +181 -8
  76. package/dist/sdk/audit.d.ts +174 -3
  77. package/dist/sdk/audit.js +176 -17
  78. package/dist/sdk/catalogue.d.ts +9 -1
  79. package/dist/sdk/conformance.d.ts +37 -3
  80. package/dist/sdk/conformance.js +25 -4
  81. package/dist/sdk/definition.d.ts +65 -0
  82. package/dist/sdk/definition.js +22 -0
  83. package/dist/sdk/registry.d.ts +29 -2
  84. package/dist/sdk/registry.js +63 -1
  85. package/dist/signals/action-change.d.ts +507 -0
  86. package/dist/signals/action-change.js +265 -0
  87. package/dist/signals/action.d.ts +331 -0
  88. package/dist/signals/action.js +182 -0
  89. package/dist/signals/applied-window.contract.d.ts +23 -0
  90. package/dist/signals/applied-window.contract.js +160 -0
  91. package/dist/signals/arriving.d.ts +210 -0
  92. package/dist/signals/arriving.js +133 -0
  93. package/dist/signals/audiences.d.ts +528 -0
  94. package/dist/signals/audiences.js +255 -0
  95. package/dist/signals/broadcast.d.ts +8 -2
  96. package/dist/signals/broadcast.js +58 -8
  97. package/dist/signals/change.d.ts +378 -0
  98. package/dist/signals/change.js +327 -0
  99. package/dist/signals/collect.d.ts +41 -0
  100. package/dist/signals/collect.js +88 -7
  101. package/dist/signals/copy-change.d.ts +553 -0
  102. package/dist/signals/copy-change.js +377 -0
  103. package/dist/signals/copy.d.ts +337 -0
  104. package/dist/signals/copy.js +211 -0
  105. package/dist/signals/counters.d.ts +46 -0
  106. package/dist/signals/counters.js +102 -0
  107. package/dist/signals/deliver.d.ts +23 -4
  108. package/dist/signals/deliver.js +34 -6
  109. package/dist/signals/deployment-change.d.ts +371 -0
  110. package/dist/signals/deployment-change.js +268 -0
  111. package/dist/signals/deployment.d.ts +265 -0
  112. package/dist/signals/deployment.js +152 -0
  113. package/dist/signals/door.d.ts +92 -0
  114. package/dist/signals/door.js +53 -0
  115. package/dist/signals/fold.d.ts +10 -0
  116. package/dist/signals/fold.js +5 -1
  117. package/dist/signals/form-action.d.ts +302 -0
  118. package/dist/signals/form-action.js +169 -0
  119. package/dist/signals/form-copy.d.ts +523 -0
  120. package/dist/signals/form-copy.js +346 -0
  121. package/dist/signals/forms.d.ts +247 -0
  122. package/dist/signals/forms.js +147 -0
  123. package/dist/signals/funnel-change.d.ts +548 -0
  124. package/dist/signals/funnel-change.js +361 -0
  125. package/dist/signals/funnel.d.ts +532 -0
  126. package/dist/signals/funnel.js +216 -0
  127. package/dist/signals/health.d.ts +497 -0
  128. package/dist/signals/health.js +361 -0
  129. package/dist/signals/index.d.ts +41 -0
  130. package/dist/signals/index.js +41 -0
  131. package/dist/signals/ingest.d.ts +56 -1
  132. package/dist/signals/ingest.js +91 -1
  133. package/dist/signals/journal.d.ts +11 -0
  134. package/dist/signals/kinds.d.ts +8 -6
  135. package/dist/signals/kinds.js +14 -6
  136. package/dist/signals/library-action.d.ts +430 -0
  137. package/dist/signals/library-action.js +336 -0
  138. package/dist/signals/library-change.d.ts +477 -0
  139. package/dist/signals/library-change.js +335 -0
  140. package/dist/signals/library-copy-change.d.ts +498 -0
  141. package/dist/signals/library-copy-change.js +476 -0
  142. package/dist/signals/library-pace.d.ts +319 -0
  143. package/dist/signals/library-pace.js +305 -0
  144. package/dist/signals/library-reach-change.d.ts +636 -0
  145. package/dist/signals/library-reach-change.js +534 -0
  146. package/dist/signals/library-reach.d.ts +377 -0
  147. package/dist/signals/library-reach.js +227 -0
  148. package/dist/signals/library-word-reach-change.d.ts +567 -0
  149. package/dist/signals/library-word-reach-change.js +568 -0
  150. package/dist/signals/library.d.ts +306 -0
  151. package/dist/signals/library.js +178 -0
  152. package/dist/signals/memory.d.ts +9 -0
  153. package/dist/signals/memory.js +105 -14
  154. package/dist/signals/migrate.d.ts +17 -2
  155. package/dist/signals/migrate.js +122 -5
  156. package/dist/signals/notice.d.ts +334 -0
  157. package/dist/signals/notice.js +228 -0
  158. package/dist/signals/pace-change.d.ts +501 -0
  159. package/dist/signals/pace-change.js +310 -0
  160. package/dist/signals/pace.d.ts +296 -0
  161. package/dist/signals/pace.js +291 -0
  162. package/dist/signals/page-views.d.ts +365 -0
  163. package/dist/signals/page-views.js +218 -0
  164. package/dist/signals/parts.d.ts +344 -0
  165. package/dist/signals/parts.js +273 -0
  166. package/dist/signals/postgres.d.ts +16 -2
  167. package/dist/signals/postgres.js +390 -87
  168. package/dist/signals/progress.d.ts +212 -0
  169. package/dist/signals/progress.js +150 -0
  170. package/dist/signals/ratios.d.ts +108 -0
  171. package/dist/signals/ratios.js +40 -0
  172. package/dist/signals/reach.d.ts +309 -0
  173. package/dist/signals/reach.js +93 -0
  174. package/dist/signals/readable.d.ts +34 -0
  175. package/dist/signals/readable.js +34 -0
  176. package/dist/signals/readership.d.ts +381 -0
  177. package/dist/signals/readership.js +308 -0
  178. package/dist/signals/region-pages.d.ts +173 -0
  179. package/dist/signals/region-pages.js +62 -0
  180. package/dist/signals/region.d.ts +287 -0
  181. package/dist/signals/region.js +198 -0
  182. package/dist/signals/retention.d.ts +141 -0
  183. package/dist/signals/retention.js +58 -0
  184. package/dist/signals/rollup.d.ts +67 -3
  185. package/dist/signals/rollup.js +0 -0
  186. package/dist/signals/schema.d.ts +432 -1
  187. package/dist/signals/schema.js +157 -3
  188. package/dist/signals/signal.d.ts +237 -11
  189. package/dist/signals/signal.js +70 -10
  190. package/dist/signals/silence-census.d.ts +205 -0
  191. package/dist/signals/silence-census.js +87 -0
  192. package/dist/signals/silences.d.ts +848 -0
  193. package/dist/signals/silences.js +753 -0
  194. package/dist/signals/tally.d.ts +140 -11
  195. package/dist/signals/window-figures.d.ts +148 -0
  196. package/dist/signals/window-figures.js +42 -0
  197. package/dist/signals/window.d.ts +866 -0
  198. package/dist/signals/window.js +693 -0
  199. package/dist/signals/words.d.ts +24 -0
  200. package/dist/signals/words.js +24 -0
  201. package/dist/store/index.d.ts +19 -0
  202. package/dist/store/index.js +19 -0
  203. package/dist/store/memory.d.ts +2 -1
  204. package/dist/store/memory.js +48 -12
  205. package/dist/store/migrate.d.ts +80 -0
  206. package/dist/store/migrate.js +259 -7
  207. package/dist/store/postgres-applications.d.ts +4 -0
  208. package/dist/store/postgres-applications.js +197 -0
  209. package/dist/store/postgres-holds.d.ts +10 -1
  210. package/dist/store/postgres-holds.js +116 -101
  211. package/dist/store/postgres-policy-log.d.ts +14 -0
  212. package/dist/store/postgres-policy-log.js +240 -0
  213. package/dist/store/postgres-projects.d.ts +4 -0
  214. package/dist/store/postgres-projects.js +217 -0
  215. package/dist/store/postgres.d.ts +16 -1
  216. package/dist/store/postgres.js +59 -9
  217. package/dist/store/replay.d.ts +102 -1
  218. package/dist/store/replay.js +190 -19
  219. package/dist/store/reseed.d.ts +238 -0
  220. package/dist/store/reseed.js +308 -0
  221. package/dist/store/schema.d.ts +450 -2
  222. package/dist/store/schema.js +141 -5
  223. package/dist/store/store.d.ts +29 -6
  224. package/dist/submit/resolve.js +2 -1
  225. package/dist/telemetry/calibration.d.ts +25 -0
  226. package/dist/telemetry/calibration.js +27 -1
  227. package/dist/telemetry/event.d.ts +391 -33
  228. package/dist/telemetry/event.js +84 -20
  229. package/dist/telemetry/index.d.ts +1 -0
  230. package/dist/telemetry/index.js +1 -0
  231. package/dist/telemetry/journal.d.ts +72 -3
  232. package/dist/telemetry/journal.js +9 -0
  233. package/dist/telemetry/lookup.d.ts +27 -0
  234. package/dist/telemetry/lookup.js +18 -0
  235. package/dist/telemetry/memory.js +23 -0
  236. package/dist/telemetry/migrate.js +22 -1
  237. package/dist/telemetry/postgres.d.ts +10 -1
  238. package/dist/telemetry/postgres.js +172 -90
  239. package/dist/telemetry/remeasure.d.ts +78 -0
  240. package/dist/telemetry/remeasure.js +83 -0
  241. package/dist/telemetry/retention.d.ts +2 -2
  242. package/dist/telemetry/schema.d.ts +17 -0
  243. package/dist/telemetry/schema.js +27 -1
  244. package/dist/telemetry/sink.d.ts +2 -2
  245. package/dist/testing/application-contract.d.ts +14 -0
  246. package/dist/testing/application-contract.js +270 -0
  247. package/dist/testing/contracts.d.ts +12 -7
  248. package/dist/testing/contracts.js +12 -7
  249. package/dist/testing/definitions.d.ts +78 -0
  250. package/dist/testing/definitions.js +134 -9
  251. package/dist/testing/doubles.d.ts +103 -0
  252. package/dist/testing/doubles.js +143 -0
  253. package/dist/testing/index.d.ts +2 -2
  254. package/dist/testing/index.js +2 -2
  255. package/dist/testing/journal-contract.js +140 -2
  256. package/dist/testing/model-contract.d.ts +110 -0
  257. package/dist/testing/model-contract.js +150 -0
  258. package/dist/testing/policy-log-contract.d.ts +26 -0
  259. package/dist/testing/policy-log-contract.js +344 -0
  260. package/dist/testing/project-contract.d.ts +14 -0
  261. package/dist/testing/project-contract.js +266 -0
  262. package/dist/testing/reader-signal-contract.d.ts +27 -2
  263. package/dist/testing/reader-signal-contract.js +475 -5
  264. package/dist/testing/store-contract.d.ts +7 -1
  265. package/dist/testing/store-contract.js +84 -3
  266. package/dist/theme/apply.d.ts +20 -1
  267. package/dist/theme/apply.js +5 -3
  268. package/dist/theme/derive.d.ts +22 -0
  269. package/dist/theme/derive.js +54 -1
  270. package/dist/theme/library.js +1 -1
  271. package/dist/theme/measure.d.ts +34 -0
  272. package/dist/theme/measure.js +30 -1
  273. package/dist/theme/palettes.js +7 -7
  274. package/dist/theme/ramp.d.ts +64 -0
  275. package/dist/theme/ramp.js +114 -0
  276. package/dist/theme/registry.d.ts +9 -0
  277. package/dist/theme/registry.js +11 -1
  278. package/dist/theme/separation.d.ts +97 -3
  279. package/dist/theme/separation.js +75 -0
  280. package/dist/tree/compare.d.ts +9 -0
  281. package/dist/tree/compare.js +18 -0
  282. package/dist/write/computed.d.ts +60 -0
  283. package/dist/write/computed.js +61 -0
  284. package/dist/write/held.d.ts +59 -0
  285. package/dist/write/index.d.ts +5 -2
  286. package/dist/write/index.js +5 -2
  287. package/dist/write/reseed.d.ts +151 -0
  288. package/dist/write/reseed.js +184 -0
  289. package/dist/write/revert.js +2 -16
  290. package/package.json +98 -19
@@ -0,0 +1,240 @@
1
+ import { and, asc, desc, eq, gt, lt } from "drizzle-orm";
2
+ import { DEFAULT_APPLICATION_ID } from "../application/application.js";
3
+ import { cursorPosition, pageEnds } from "../paging.js";
4
+ import { err, ok } from "../result.js";
5
+ import { policyShapeOf } from "../runtime/policy-fingerprint.js";
6
+ import { clampPolicyRevisionLimit, MAX_POLICY_REVISION_LIMIT, parsePolicyRevision, policyProvenanceOf, recordOutcomeOf, } from "../runtime/policy-log.js";
7
+ import { isUniqueViolation, unavailable } from "./driver.js";
8
+ import { loomPolicyRevisions } from "./schema.js";
9
+ /**
10
+ * The policy's own log, backed by Postgres (0022).
11
+ *
12
+ * The counterpart `memoryPolicyLog` was always going to need, and for a sharper
13
+ * reason than the hold store's: a policy log that lived in a process would be
14
+ * reset by every deployment, which is precisely when a policy is most likely to
15
+ * have changed. A `Map` cannot record the one event this log exists to record.
16
+ *
17
+ * **There is no transaction here, and that is the point of the composite primary
18
+ * key.** The write reads the head, computes the next revision and inserts it; two
19
+ * writers racing at the same head both compute `N + 1` and the database refuses
20
+ * the second. `loom_revisions` gets its ordering guarantee the same way, and
21
+ * `store.ts` says so. A `SELECT … FOR UPDATE` could not have served here anyway:
22
+ * the first revision of a policy has no row to lock.
23
+ *
24
+ * A refused insert is reported as `out-of-date` against the head as it is *now*,
25
+ * which is the truth the caller needs rather than the one it raced against.
26
+ */
27
+ /**
28
+ * A row on the way out, checked rather than cast.
29
+ *
30
+ * `policy` was written by whatever version of the code was running then, and a
31
+ * policy revision is among the longest-lived documents in the system: a log kept
32
+ * across a year of deployments is exactly what makes a calibration window
33
+ * legible, which is the whole reason to keep one.
34
+ */
35
+ const toRevision = (row) => parsePolicyRevision({
36
+ policyId: row.policyId,
37
+ revision: row.revision,
38
+ fingerprint: row.fingerprint,
39
+ policy: row.policy,
40
+ actor: row.actor,
41
+ recordedAt: row.recordedAt,
42
+ ...(row.note === null ? {} : { note: row.note }),
43
+ });
44
+ /**
45
+ * `null` and an absent key are one thing on the way back in and two things in
46
+ * the type, which is what `toRevision` spreads around: a `text` column with no
47
+ * value reads as `null`, and `exactOptionalPropertyTypes` distinguishes that
48
+ * from a key the shape does not have.
49
+ */
50
+ const newest = async (db, project, policyId) => {
51
+ try {
52
+ const rows = await db
53
+ .select()
54
+ .from(loomPolicyRevisions)
55
+ .where(and(eq(loomPolicyRevisions.applicationId, project), eq(loomPolicyRevisions.policyId, policyId)))
56
+ .orderBy(desc(loomPolicyRevisions.revision))
57
+ .limit(1);
58
+ const row = rows[0];
59
+ return row === undefined ? ok(undefined) : toRevision(row);
60
+ }
61
+ catch (cause) {
62
+ return err(unavailable(cause, `could not read the policy ${policyId}`));
63
+ }
64
+ };
65
+ /**
66
+ * Every query is filtered by the project this handle speaks for (0260), and
67
+ * every write sets it.
68
+ *
69
+ * Without it `judgedUnder` would resolve a fingerprint against every policy
70
+ * revision the deployment holds, and answer with another project's policy text
71
+ * whenever two happened to fingerprint alike — which is a change reported as
72
+ * judged under rules it was never judged under.
73
+ */
74
+ export const postgresPolicyLog = (db, scope = {}) => {
75
+ const project = scope.application ?? DEFAULT_APPLICATION_ID;
76
+ const mine = (...rest) => and(eq(loomPolicyRevisions.applicationId, project), ...rest);
77
+ return {
78
+ record: async (request) => {
79
+ const policyId = request.policy.policyId;
80
+ /**
81
+ * Outside the `try`, because `newest` is total: the only statement here that
82
+ * can collide is the insert, and a narrow `try` is what lets the `catch`
83
+ * below say *a unique violation on this insert means somebody else recorded*
84
+ * rather than guessing which of two statements threw.
85
+ */
86
+ const head = await newest(db, project, policyId);
87
+ if (!head.ok)
88
+ return head;
89
+ const racedAgainst = head.value?.revision ?? 0;
90
+ const outcome = recordOutcomeOf(request, head.value);
91
+ if (!outcome.ok || outcome.value.outcome === "unchanged")
92
+ return outcome;
93
+ const revision = outcome.value.revision;
94
+ try {
95
+ await db.insert(loomPolicyRevisions).values({
96
+ applicationId: project,
97
+ policyId: revision.policyId,
98
+ revision: revision.revision,
99
+ fingerprint: revision.fingerprint,
100
+ policy: revision.policy,
101
+ actor: revision.actor,
102
+ recordedAt: revision.recordedAt,
103
+ note: revision.note ?? null,
104
+ });
105
+ return ok(outcome.value);
106
+ }
107
+ catch (cause) {
108
+ /**
109
+ * Somebody else recorded between the read and the insert, so this is the
110
+ * staleness `recordOutcomeOf` could not see: the head was right when it was
111
+ * read and wrong by the time the row was written.
112
+ *
113
+ * `expected` is the head this call actually proceeded from rather than
114
+ * whatever the caller named — a caller that passed no `expectedRevision`
115
+ * still raced against a revision, and reporting `0` for it would say the
116
+ * caller believed the log was empty. `current` is re-read, because
117
+ * re-reading is what the caller has to do next and the number it lost to is
118
+ * of no use to it.
119
+ */
120
+ if (isUniqueViolation(cause)) {
121
+ const current = await newest(db, project, policyId);
122
+ return err({
123
+ code: "out-of-date",
124
+ policyId,
125
+ expected: racedAgainst,
126
+ current: current.ok && current.value !== undefined ? current.value.revision : racedAgainst,
127
+ });
128
+ }
129
+ return err(unavailable(cause, `could not record a revision of ${policyId}`));
130
+ }
131
+ },
132
+ current: async (policyId) => {
133
+ const head = await newest(db, project, policyId);
134
+ if (!head.ok)
135
+ return head;
136
+ return head.value === undefined
137
+ ? err({ code: "no-such-policy", policyId })
138
+ : ok(head.value);
139
+ },
140
+ revisions: async (policyId, request) => {
141
+ const direction = request?.direction ?? "newer";
142
+ const limit = clampPolicyRevisionLimit(request?.limit);
143
+ const from = cursorPosition(request?.cursor);
144
+ /**
145
+ * "No policy" and "a policy at some revision" are different answers, and
146
+ * the head read is what separates them — a page that came back empty because
147
+ * the cursor was at the end is not a name nobody has recorded.
148
+ */
149
+ const head = await newest(db, project, policyId);
150
+ if (!head.ok)
151
+ return head;
152
+ if (head.value === undefined)
153
+ return err({ code: "no-such-policy", policyId });
154
+ try {
155
+ /**
156
+ * `older` scans descending so the newest page costs one seek on the
157
+ * primary key rather than a walk from the start, then the rows are put
158
+ * back in ascending order — the contract's promise that a page's order
159
+ * never depends on which end it came from.
160
+ */
161
+ const rows = await db
162
+ .select()
163
+ .from(loomPolicyRevisions)
164
+ .where(mine(eq(loomPolicyRevisions.policyId, policyId), from === undefined
165
+ ? undefined
166
+ : direction === "older"
167
+ ? lt(loomPolicyRevisions.revision, from)
168
+ : gt(loomPolicyRevisions.revision, from)))
169
+ .orderBy(direction === "older"
170
+ ? desc(loomPolicyRevisions.revision)
171
+ : asc(loomPolicyRevisions.revision))
172
+ /** One extra row answers "is there another page" without a count. */
173
+ .limit(limit + 1);
174
+ const taken = direction === "older" ? rows.slice(0, limit).reverse() : rows.slice(0, limit);
175
+ const revisions = [];
176
+ for (const row of taken) {
177
+ const parsed = toRevision(row);
178
+ if (!parsed.ok)
179
+ return parsed;
180
+ revisions.push(parsed.value);
181
+ }
182
+ return ok({
183
+ revisions,
184
+ ...pageEnds(revisions.map((entry) => entry.revision), direction, { beyond: rows.length > limit, resumed: from !== undefined }),
185
+ });
186
+ }
187
+ catch (cause) {
188
+ return err(unavailable(cause, `could not read the history of ${policyId}`));
189
+ }
190
+ },
191
+ /**
192
+ * The seek the fingerprint column exists for. Two statements rather than one:
193
+ * the matches come off the index, and the shapes are only read when nothing
194
+ * matched — so the ordinary answer costs one indexed read and the explanation
195
+ * of a miss costs a second that a hit never pays for.
196
+ */
197
+ judgedUnder: async (policyId, fingerprint) => {
198
+ try {
199
+ const matched = await db
200
+ .select()
201
+ .from(loomPolicyRevisions)
202
+ .where(mine(eq(loomPolicyRevisions.policyId, policyId), eq(loomPolicyRevisions.fingerprint, fingerprint)))
203
+ .orderBy(asc(loomPolicyRevisions.revision))
204
+ /**
205
+ * Bounded like every read in Loom, and the bound cannot change the
206
+ * answer: one match is `recorded`, and two or more is `ambiguous`
207
+ * whether or not the list is complete, because the verdict is *nothing
208
+ * can say which* either way. Oldest first, so a truncated list is the
209
+ * beginning of the range rather than an arbitrary slice of it.
210
+ */
211
+ .limit(MAX_POLICY_REVISION_LIMIT);
212
+ const matches = [];
213
+ for (const row of matched) {
214
+ const parsed = toRevision(row);
215
+ if (!parsed.ok)
216
+ return parsed;
217
+ matches.push(parsed.value);
218
+ }
219
+ if (matches.length > 0)
220
+ return ok(policyProvenanceOf(policyId, fingerprint, matches, []));
221
+ const held = await db
222
+ .selectDistinct({ fingerprint: loomPolicyRevisions.fingerprint })
223
+ .from(loomPolicyRevisions)
224
+ .where(and(eq(loomPolicyRevisions.applicationId, project), eq(loomPolicyRevisions.policyId, policyId)))
225
+ /**
226
+ * Bounded for the same reason, and again without cost to the answer:
227
+ * `heldShapes` only has to separate *nothing was recorded under this
228
+ * name* from *everything recorded here came from another build*, and one
229
+ * row settles that.
230
+ */
231
+ .limit(MAX_POLICY_REVISION_LIMIT);
232
+ return ok(policyProvenanceOf(policyId, fingerprint, [], held.map((row) => policyShapeOf(row.fingerprint))));
233
+ }
234
+ catch (cause) {
235
+ return err(unavailable(cause, `could not resolve a policy fingerprint for ${policyId}`));
236
+ }
237
+ },
238
+ };
239
+ };
240
+ //# sourceMappingURL=postgres-policy-log.js.map
@@ -0,0 +1,4 @@
1
+ import { type ProjectStore } from "../project/store.js";
2
+ import type { LoomDatabase } from "./database.js";
3
+ export declare const postgresProjectStore: (db: LoomDatabase) => ProjectStore;
4
+ //# sourceMappingURL=postgres-projects.d.ts.map
@@ -0,0 +1,217 @@
1
+ import { and, asc, eq, isNull } from "drizzle-orm";
2
+ import { applyPatch } from "../patch.js";
3
+ import { projectSchema } from "../project/project.js";
4
+ import { matchesListing } from "../project/store.js";
5
+ import { err, ok } from "../result.js";
6
+ import { isUniqueViolation, unavailable } from "./driver.js";
7
+ import { loomProjects } from "./schema.js";
8
+ /**
9
+ * The projects a deployment has, backed by Postgres (0022).
10
+ *
11
+ * The one store here that is not scoped by a project, for the obvious reason:
12
+ * it holds them. Every other store takes a `StoreScope` and filters on it; this
13
+ * one is what that scope's id refers to, so a handle for it would have nothing
14
+ * to be scoped by.
15
+ *
16
+ * Like the others, the database handle is injected rather than opened here —
17
+ * choosing a driver, a pooler and a connection lifetime belongs to the host,
18
+ * and injecting it is what lets the tests run this exact code against an
19
+ * embedded Postgres rather than against a double that agrees with them.
20
+ */
21
+ /**
22
+ * A row on the way out, checked rather than cast.
23
+ *
24
+ * `closed_at` is the one nullable column, and it comes out **absent rather than
25
+ * `null`** so that *this is open* has one spelling rather than two for every
26
+ * caller to check (0289, and 0274 made the same choice about `folded_at`).
27
+ */
28
+ const toProject = (row) => {
29
+ const parsed = projectSchema.safeParse({
30
+ projectId: row.projectId,
31
+ name: row.name,
32
+ createdAt: row.createdAt,
33
+ ...(row.repository === null ? {} : { repository: row.repository }),
34
+ ...(row.closedAt === null ? {} : { closedAt: row.closedAt }),
35
+ });
36
+ return parsed.success
37
+ ? ok(parsed.data)
38
+ : err({
39
+ code: "unreadable",
40
+ projectId: row.projectId,
41
+ detail: parsed.error.issues[0]?.message ?? "invalid",
42
+ });
43
+ };
44
+ export const postgresProjectStore = (db) => ({
45
+ create: async (project) => {
46
+ try {
47
+ await db.insert(loomProjects).values({
48
+ projectId: project.projectId,
49
+ name: project.name,
50
+ createdAt: project.createdAt,
51
+ repository: project.repository ?? null,
52
+ });
53
+ return ok(project);
54
+ }
55
+ catch (cause) {
56
+ /**
57
+ * The key is what makes *already taken* a fact the database establishes
58
+ * rather than a check this code races against — the same argument the
59
+ * hold store makes about its primary key, and it matters more here: the
60
+ * loser of a race between two people registering the same project would
61
+ * otherwise silently take ownership of the winner's rows.
62
+ */
63
+ /**
64
+ * Two unique constraints can raise this now: the primary key, and the
65
+ * partial index on `repository` (0292).
66
+ *
67
+ * Which one is **asked** rather than guessed. Deciding from what the
68
+ * caller passed would misreport an id collision as a taken repository
69
+ * whenever both were set, and parsing the driver's message is not
70
+ * portable across the two drivers this runs on. The extra read happens
71
+ * only on the error path, where one more round trip costs nothing.
72
+ */
73
+ if (isUniqueViolation(cause)) {
74
+ const existing = await db
75
+ .select({ projectId: loomProjects.projectId })
76
+ .from(loomProjects)
77
+ .where(eq(loomProjects.projectId, project.projectId))
78
+ .limit(1);
79
+ if (existing[0] !== undefined) {
80
+ return err({ code: "already-exists", projectId: project.projectId });
81
+ }
82
+ return project.repository === undefined
83
+ ? err({ code: "already-exists", projectId: project.projectId })
84
+ : err({ code: "repository-taken", repository: project.repository });
85
+ }
86
+ return err(unavailable(cause, `could not create project ${project.projectId}`));
87
+ }
88
+ },
89
+ get: async (projectId) => {
90
+ try {
91
+ const rows = await db
92
+ .select()
93
+ .from(loomProjects)
94
+ .where(eq(loomProjects.projectId, projectId))
95
+ .limit(1);
96
+ const row = rows[0];
97
+ return row === undefined ? err({ code: "not-found", projectId }) : toProject(row);
98
+ }
99
+ catch (cause) {
100
+ return err(unavailable(cause, `could not read project ${projectId}`));
101
+ }
102
+ },
103
+ list: async (listing) => {
104
+ try {
105
+ /**
106
+ * Ordered in the statement rather than after it, so the order is the
107
+ * database's job and an index can serve it. `created_at` is an ISO string,
108
+ * which sorts lexicographically into chronological order — that is the
109
+ * property the format is chosen for, and `projectSchema` requires it.
110
+ */
111
+ const rows = await db.select().from(loomProjects).orderBy(asc(loomProjects.createdAt));
112
+ const projects = [];
113
+ for (const row of rows) {
114
+ const project = toProject(row);
115
+ if (!project.ok)
116
+ return project;
117
+ /**
118
+ * Filtered here rather than in the statement, so that the one rule
119
+ * about what `closed` means is the one function both stores call. A
120
+ * `WHERE` would be a second copy of a three-case rule.
121
+ */
122
+ if (matchesListing(project.value.closedAt, listing))
123
+ projects.push(project.value);
124
+ }
125
+ return ok(projects);
126
+ }
127
+ catch (cause) {
128
+ return err(unavailable(cause, "could not list projects"));
129
+ }
130
+ },
131
+ /**
132
+ * Read, merge, parse, write — rather than setting the columns given.
133
+ *
134
+ * The first draft set them directly, and the shared contract caught what that
135
+ * costs: `text` accepts an empty string and `projectSchema` does not, so a
136
+ * rename to `""` was written happily and then could not be read back at all.
137
+ * The row was corrupt, and the store that had refused the same call was the
138
+ * one in a `Map`. Parsing the merged project is what makes the two stores
139
+ * agree about what a project is, rather than about what fits in a column.
140
+ *
141
+ * The read and the write are not in one transaction, which is a real race and
142
+ * an acceptable one: two people renaming one project at the same instant get
143
+ * last-write-wins on a display name. Nothing downstream keys on it.
144
+ */
145
+ rename: async (projectId, to) => {
146
+ try {
147
+ const rows = await db
148
+ .select()
149
+ .from(loomProjects)
150
+ .where(eq(loomProjects.projectId, projectId))
151
+ .limit(1);
152
+ const row = rows[0];
153
+ if (row === undefined)
154
+ return err({ code: "not-found", projectId });
155
+ const current = toProject(row);
156
+ if (!current.ok)
157
+ return current;
158
+ const next = projectSchema.safeParse(applyPatch(current.value, to));
159
+ if (!next.success) {
160
+ return err({
161
+ code: "unreadable",
162
+ projectId,
163
+ detail: next.error.issues[0]?.message ?? "invalid",
164
+ });
165
+ }
166
+ await db
167
+ .update(loomProjects)
168
+ .set({ name: next.data.name })
169
+ .where(eq(loomProjects.projectId, projectId));
170
+ return ok(next.data);
171
+ }
172
+ catch (cause) {
173
+ return err(unavailable(cause, `could not rename project ${projectId}`));
174
+ }
175
+ },
176
+ /**
177
+ * Idempotent in the statement: the `WHERE` refuses a row that is already
178
+ * closed, so the instant cannot move because somebody pressed twice (0289).
179
+ */
180
+ close: async (projectId, at) => {
181
+ try {
182
+ await db
183
+ .update(loomProjects)
184
+ .set({ closedAt: at })
185
+ .where(and(eq(loomProjects.projectId, projectId), isNull(loomProjects.closedAt)));
186
+ const rows = await db
187
+ .select()
188
+ .from(loomProjects)
189
+ .where(eq(loomProjects.projectId, projectId))
190
+ .limit(1);
191
+ const row = rows[0];
192
+ return row === undefined ? err({ code: "not-found", projectId }) : toProject(row);
193
+ }
194
+ catch (cause) {
195
+ return err(unavailable(cause, `could not close project ${projectId}`));
196
+ }
197
+ },
198
+ reopen: async (projectId) => {
199
+ try {
200
+ await db
201
+ .update(loomProjects)
202
+ .set({ closedAt: null })
203
+ .where(eq(loomProjects.projectId, projectId));
204
+ const rows = await db
205
+ .select()
206
+ .from(loomProjects)
207
+ .where(eq(loomProjects.projectId, projectId))
208
+ .limit(1);
209
+ const row = rows[0];
210
+ return row === undefined ? err({ code: "not-found", projectId }) : toProject(row);
211
+ }
212
+ catch (cause) {
213
+ return err(unavailable(cause, `could not reopen project ${projectId}`));
214
+ }
215
+ },
216
+ });
217
+ //# sourceMappingURL=postgres-projects.js.map
@@ -1,8 +1,23 @@
1
+ import { type StoreScope } from "../application/application.js";
1
2
  import type { LoomDatabase } from "./database.js";
2
3
  import { type TreeStore } from "./store.js";
3
4
  export * from "./database.js";
4
5
  export * from "./migrate.js";
5
6
  export * from "./postgres-holds.js";
7
+ export * from "./postgres-policy-log.js";
8
+ export * from "./postgres-applications.js";
9
+ export * from "./postgres-projects.js";
6
10
  export * from "./schema.js";
7
- export declare const postgresTreeStore: (db: LoomDatabase) => TreeStore;
11
+ /**
12
+ * Every query below is filtered by the project this handle speaks for (0260),
13
+ * and every write sets it. There is no path through this module that reads or
14
+ * writes a row belonging to another project, which is the one property a
15
+ * governance surface cannot get wrong (0220): *a hold listing that spanned two
16
+ * apps would put one app's changes in another's queue.*
17
+ *
18
+ * The scope is a constructor argument rather than a parameter on each method,
19
+ * so no signature in `@jam-overture/loom/store` changed and spanning two
20
+ * projects is unexpressible rather than merely forbidden.
21
+ */
22
+ export declare const postgresTreeStore: (db: LoomDatabase, scope?: StoreScope) => TreeStore;
8
23
  //# sourceMappingURL=postgres.d.ts.map
@@ -1,5 +1,6 @@
1
1
  import { and, asc, desc, eq, gt, lt } from "drizzle-orm";
2
2
  import { z } from "zod";
3
+ import { DEFAULT_APPLICATION_ID } from "../application/application.js";
3
4
  import { proposalIdSchema, treeIdSchema } from "../ids.js";
4
5
  import { cursorPosition, pageEnds } from "../paging.js";
5
6
  import { provenanceSchema } from "../runtime/proposal.js";
@@ -13,6 +14,9 @@ import { anchorBound, anchorResumes, clampListingLimit, clampRevisionLimit, } fr
13
14
  export * from "./database.js";
14
15
  export * from "./migrate.js";
15
16
  export * from "./postgres-holds.js";
17
+ export * from "./postgres-policy-log.js";
18
+ export * from "./postgres-applications.js";
19
+ export * from "./postgres-projects.js";
16
20
  export * from "./schema.js";
17
21
  /**
18
22
  * The store, backed by Postgres (0022).
@@ -40,6 +44,15 @@ const parseStored = (document, treeId) => {
40
44
  detail: `stored tree ${treeId} did not parse: ${parsed.error.code}`,
41
45
  });
42
46
  };
47
+ /**
48
+ * What the log's stamp has to be to be read back.
49
+ *
50
+ * Named and shared because two reads now depend on it — a revision page and a
51
+ * tree listing's `changedAt` — and a column holding text is a column two
52
+ * readers could disagree about. One schema is what stops a listing publishing a
53
+ * string the revision it came from would have refused.
54
+ */
55
+ const appliedAtSchema = z.string().datetime();
43
56
  /**
44
57
  * A log row, validated on the way out. The delta and the provenance were stored
45
58
  * as JSON by whatever version of the code was running at the time, so reading
@@ -52,7 +65,7 @@ const storedRevisionSchema = z.object({
52
65
  proposalId: proposalIdSchema,
53
66
  delta: treeDeltaSchema,
54
67
  provenance: provenanceSchema,
55
- appliedAt: z.string().datetime(),
68
+ appliedAt: appliedAtSchema,
56
69
  /** Null on every row written before the column existed (0029), and on every change nobody had to allow. */
57
70
  answeredBy: z.string().nullable().optional(),
58
71
  });
@@ -74,12 +87,26 @@ const toStoredRevision = (row) => {
74
87
  const entry = rest;
75
88
  return answeredBy === null || answeredBy === undefined ? entry : { ...entry, answeredBy };
76
89
  };
77
- export const postgresTreeStore = (db) => {
90
+ /**
91
+ * Every query below is filtered by the project this handle speaks for (0260),
92
+ * and every write sets it. There is no path through this module that reads or
93
+ * writes a row belonging to another project, which is the one property a
94
+ * governance surface cannot get wrong (0220): *a hold listing that spanned two
95
+ * apps would put one app's changes in another's queue.*
96
+ *
97
+ * The scope is a constructor argument rather than a parameter on each method,
98
+ * so no signature in `@jam-overture/loom/store` changed and spanning two
99
+ * projects is unexpressible rather than merely forbidden.
100
+ */
101
+ export const postgresTreeStore = (db, scope = {}) => {
102
+ const project = scope.application ?? DEFAULT_APPLICATION_ID;
103
+ /** Every read starts here, so a query cannot forget the project by omission. */
104
+ const mine = (treeId) => and(eq(loomTrees.applicationId, project), eq(loomTrees.treeId, treeId));
78
105
  const readHead = async (treeId) => {
79
106
  const rows = await db
80
107
  .select({ document: loomTrees.document })
81
108
  .from(loomTrees)
82
- .where(eq(loomTrees.treeId, treeId))
109
+ .where(mine(treeId))
83
110
  .limit(1);
84
111
  const row = rows[0];
85
112
  return row === undefined
@@ -90,6 +117,7 @@ export const postgresTreeStore = (db) => {
90
117
  create: async (tree) => {
91
118
  try {
92
119
  await db.insert(loomTrees).values({
120
+ applicationId: project,
93
121
  treeId: tree.treeId,
94
122
  revision: tree.revision,
95
123
  document: tree,
@@ -120,7 +148,7 @@ export const postgresTreeStore = (db) => {
120
148
  const present = await db
121
149
  .select({ treeId: loomTrees.treeId, revision: loomTrees.revision })
122
150
  .from(loomTrees)
123
- .where(eq(loomTrees.treeId, treeId))
151
+ .where(mine(treeId))
124
152
  .limit(1);
125
153
  /** "No tree" and "a tree with no changes" are different answers. */
126
154
  const head = present[0];
@@ -135,7 +163,7 @@ export const postgresTreeStore = (db) => {
135
163
  const rows = await db
136
164
  .select()
137
165
  .from(loomRevisions)
138
- .where(and(eq(loomRevisions.treeId, treeId), from === undefined
166
+ .where(and(eq(loomRevisions.applicationId, project), eq(loomRevisions.treeId, treeId), from === undefined
139
167
  ? undefined
140
168
  : direction === "older"
141
169
  ? lt(loomRevisions.revision, from)
@@ -170,9 +198,22 @@ export const postgresTreeStore = (db) => {
170
198
  const limit = clampListingLimit(request?.limit);
171
199
  try {
172
200
  const rows = await db
173
- .select({ treeId: loomTrees.treeId, revision: loomTrees.revision })
201
+ .select({
202
+ treeId: loomTrees.treeId,
203
+ revision: loomTrees.revision,
204
+ changedAt: loomRevisions.appliedAt,
205
+ })
174
206
  .from(loomTrees)
175
- .where(request?.cursor === undefined ? undefined : gt(loomTrees.treeId, request.cursor))
207
+ /*
208
+ * The whole of the log's primary key, so this is a point lookup per
209
+ * listed tree rather than a scan: the row it finds is the one whose
210
+ * revision the snapshot is currently at, which is the newest entry by
211
+ * 0026's density. `leftJoin` rather than `innerJoin` because a tree at
212
+ * revision 0 has no entry at all, and an inner join would drop it from
213
+ * the listing — turning a missing stamp into a missing page.
214
+ */
215
+ .leftJoin(loomRevisions, and(eq(loomRevisions.applicationId, loomTrees.applicationId), eq(loomRevisions.treeId, loomTrees.treeId), eq(loomRevisions.revision, loomTrees.revision)))
216
+ .where(and(eq(loomTrees.applicationId, project), request?.cursor === undefined ? undefined : gt(loomTrees.treeId, request.cursor)))
176
217
  .orderBy(asc(loomTrees.treeId))
177
218
  /** One extra row answers "is there another page" without a count. */
178
219
  .limit(limit + 1);
@@ -182,6 +223,14 @@ export const postgresTreeStore = (db) => {
182
223
  trees: page.map((row) => ({
183
224
  treeId: treeIdSchema.parse(row.treeId),
184
225
  revision: row.revision,
226
+ /*
227
+ * Parsed rather than trusted, for the reason every other column
228
+ * read here is: the contract publishes this as a timestamp, and a
229
+ * column holding text can hold anything a writer put in it.
230
+ */
231
+ ...(row.changedAt === null
232
+ ? {}
233
+ : { changedAt: appliedAtSchema.parse(row.changedAt) }),
185
234
  })),
186
235
  cursor: rows.length > limit && last !== undefined ? last.treeId : null,
187
236
  };
@@ -204,7 +253,7 @@ export const postgresTreeStore = (db) => {
204
253
  const rows = await tx
205
254
  .select({ document: loomTrees.document })
206
255
  .from(loomTrees)
207
- .where(eq(loomTrees.treeId, treeId))
256
+ .where(mine(treeId))
208
257
  .for("update")
209
258
  .limit(1);
210
259
  const row = rows[0];
@@ -226,6 +275,7 @@ export const postgresTreeStore = (db) => {
226
275
  return err({ code: "delta-rejected", treeId, error: applied.error });
227
276
  }
228
277
  await tx.insert(loomRevisions).values({
278
+ applicationId: project,
229
279
  treeId,
230
280
  revision: applied.value.revision,
231
281
  proposalId: request.proposalId,
@@ -237,7 +287,7 @@ export const postgresTreeStore = (db) => {
237
287
  await tx
238
288
  .update(loomTrees)
239
289
  .set({ revision: applied.value.revision, document: applied.value })
240
- .where(and(eq(loomTrees.treeId, treeId), eq(loomTrees.revision, snapshot.value.revision)));
290
+ .where(and(mine(treeId), eq(loomTrees.revision, snapshot.value.revision)));
241
291
  return ok(applied.value);
242
292
  });
243
293
  }