@yielded/auth-persistence 0.1.0-beta.7

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 (526) hide show
  1. package/README.md +21 -0
  2. package/dist/Drizzle.d.mts +28 -0
  3. package/dist/Drizzle.mjs +28 -0
  4. package/dist/DrizzleD1.d.mts +963 -0
  5. package/dist/DrizzleD1.mjs +29 -0
  6. package/dist/DrizzleD1.mjs.map +1 -0
  7. package/dist/DrizzleLibsql.d.mts +2284 -0
  8. package/dist/DrizzleLibsql.mjs +92 -0
  9. package/dist/DrizzleLibsql.mjs.map +1 -0
  10. package/dist/DrizzleMysql2.d.mts +1820 -0
  11. package/dist/DrizzleMysql2.mjs +55 -0
  12. package/dist/DrizzleMysql2.mjs.map +1 -0
  13. package/dist/DrizzlePglite.d.mts +1826 -0
  14. package/dist/DrizzlePglite.mjs +53 -0
  15. package/dist/DrizzlePglite.mjs.map +1 -0
  16. package/dist/DrizzlePostgres.d.mts +1826 -0
  17. package/dist/DrizzlePostgres.mjs +53 -0
  18. package/dist/DrizzlePostgres.mjs.map +1 -0
  19. package/dist/DrizzleSqliteBun.d.mts +2279 -0
  20. package/dist/DrizzleSqliteBun.mjs +70 -0
  21. package/dist/DrizzleSqliteBun.mjs.map +1 -0
  22. package/dist/DrizzleSqliteDo.d.mts +2329 -0
  23. package/dist/DrizzleSqliteDo.mjs +105 -0
  24. package/dist/DrizzleSqliteDo.mjs.map +1 -0
  25. package/dist/DrizzleSqliteNode.d.mts +2279 -0
  26. package/dist/DrizzleSqliteNode.mjs +70 -0
  27. package/dist/DrizzleSqliteNode.mjs.map +1 -0
  28. package/dist/DrizzleSqliteWasm.d.mts +2282 -0
  29. package/dist/DrizzleSqliteWasm.mjs +70 -0
  30. package/dist/DrizzleSqliteWasm.mjs.map +1 -0
  31. package/dist/drizzle/D1BatchStatements.d.mts +11 -0
  32. package/dist/drizzle/D1BatchStatements.mjs +8 -0
  33. package/dist/drizzle/D1BatchStatements.mjs.map +1 -0
  34. package/dist/drizzle/PasswordPreparedPostconditions.mjs +12 -0
  35. package/dist/drizzle/PasswordPreparedPostconditions.mjs.map +1 -0
  36. package/dist/drizzle/SuppliedService.d.mts +10 -0
  37. package/dist/drizzle/d1-emails.d.mts +62 -0
  38. package/dist/drizzle/d1-emails.mjs +580 -0
  39. package/dist/drizzle/d1-emails.mjs.map +1 -0
  40. package/dist/drizzle/d1-generated-statement.d.mts +2 -0
  41. package/dist/drizzle/d1-generated-statement.mjs +79 -0
  42. package/dist/drizzle/d1-generated-statement.mjs.map +1 -0
  43. package/dist/drizzle/d1-identity.d.mts +31 -0
  44. package/dist/drizzle/d1-identity.mjs +119 -0
  45. package/dist/drizzle/d1-identity.mjs.map +1 -0
  46. package/dist/drizzle/d1-oauth.d.mts +301 -0
  47. package/dist/drizzle/d1-oauth.mjs +76 -0
  48. package/dist/drizzle/d1-oauth.mjs.map +1 -0
  49. package/dist/drizzle/d1-passkey.d.mts +51 -0
  50. package/dist/drizzle/d1-passkey.mjs +95 -0
  51. package/dist/drizzle/d1-passkey.mjs.map +1 -0
  52. package/dist/drizzle/d1-password-prepared.d.mts +25 -0
  53. package/dist/drizzle/d1-password-prepared.mjs +461 -0
  54. package/dist/drizzle/d1-password-prepared.mjs.map +1 -0
  55. package/dist/drizzle/d1-passwords.d.mts +87 -0
  56. package/dist/drizzle/d1-passwords.mjs +1004 -0
  57. package/dist/drizzle/d1-passwords.mjs.map +1 -0
  58. package/dist/drizzle/d1-phone.d.mts +26 -0
  59. package/dist/drizzle/d1-phone.mjs +30 -0
  60. package/dist/drizzle/d1-phone.mjs.map +1 -0
  61. package/dist/drizzle/d1-planning.d.mts +12 -0
  62. package/dist/drizzle/d1-planning.mjs +43 -0
  63. package/dist/drizzle/d1-planning.mjs.map +1 -0
  64. package/dist/drizzle/d1-proofs.d.mts +80 -0
  65. package/dist/drizzle/d1-proofs.mjs +830 -0
  66. package/dist/drizzle/d1-proofs.mjs.map +1 -0
  67. package/dist/drizzle/d1-sessions.d.mts +67 -0
  68. package/dist/drizzle/d1-sessions.mjs +966 -0
  69. package/dist/drizzle/d1-sessions.mjs.map +1 -0
  70. package/dist/drizzle/d1-totp.d.mts +26 -0
  71. package/dist/drizzle/d1-totp.mjs +27 -0
  72. package/dist/drizzle/d1-totp.mjs.map +1 -0
  73. package/dist/drizzle/email-model.d.mts +354 -0
  74. package/dist/drizzle/email-model.mjs +21 -0
  75. package/dist/drizzle/email-model.mjs.map +1 -0
  76. package/dist/drizzle/email-registration.d.mts +30 -0
  77. package/dist/drizzle/email-registration.mjs +238 -0
  78. package/dist/drizzle/email-registration.mjs.map +1 -0
  79. package/dist/drizzle/email-sql.d.mts +4 -0
  80. package/dist/drizzle/email-sql.mjs +9 -0
  81. package/dist/drizzle/email-sql.mjs.map +1 -0
  82. package/dist/drizzle/email-target.d.mts +20 -0
  83. package/dist/drizzle/email-target.mjs +72 -0
  84. package/dist/drizzle/email-target.mjs.map +1 -0
  85. package/dist/drizzle/model.d.mts +250 -0
  86. package/dist/drizzle/model.mjs +58 -0
  87. package/dist/drizzle/model.mjs.map +1 -0
  88. package/dist/drizzle/mysql-emails.d.mts +71 -0
  89. package/dist/drizzle/mysql-emails.mjs +38 -0
  90. package/dist/drizzle/mysql-emails.mjs.map +1 -0
  91. package/dist/drizzle/mysql-identity.d.mts +22 -0
  92. package/dist/drizzle/mysql-identity.mjs +94 -0
  93. package/dist/drizzle/mysql-identity.mjs.map +1 -0
  94. package/dist/drizzle/mysql-password-prepared.d.mts +30 -0
  95. package/dist/drizzle/mysql-password-prepared.mjs +16 -0
  96. package/dist/drizzle/mysql-password-prepared.mjs.map +1 -0
  97. package/dist/drizzle/mysql-passwords.d.mts +86 -0
  98. package/dist/drizzle/mysql-passwords.mjs +38 -0
  99. package/dist/drizzle/mysql-passwords.mjs.map +1 -0
  100. package/dist/drizzle/mysql-proofs.d.mts +75 -0
  101. package/dist/drizzle/mysql-proofs.mjs +23 -0
  102. package/dist/drizzle/mysql-proofs.mjs.map +1 -0
  103. package/dist/drizzle/mysql-sessions.d.mts +237 -0
  104. package/dist/drizzle/mysql-sessions.mjs +53 -0
  105. package/dist/drizzle/mysql-sessions.mjs.map +1 -0
  106. package/dist/drizzle/mysql.d.mts +70 -0
  107. package/dist/drizzle/mysql.mjs +218 -0
  108. package/dist/drizzle/mysql.mjs.map +1 -0
  109. package/dist/drizzle/oauth-accounts.mjs +358 -0
  110. package/dist/drizzle/oauth-accounts.mjs.map +1 -0
  111. package/dist/drizzle/oauth-connected-access.mjs +210 -0
  112. package/dist/drizzle/oauth-connected-access.mjs.map +1 -0
  113. package/dist/drizzle/oauth-connected-collection.mjs +202 -0
  114. package/dist/drizzle/oauth-connected-collection.mjs.map +1 -0
  115. package/dist/drizzle/oauth-connected-custody.mjs +146 -0
  116. package/dist/drizzle/oauth-connected-custody.mjs.map +1 -0
  117. package/dist/drizzle/oauth-connected-drivers.mjs +76 -0
  118. package/dist/drizzle/oauth-connected-drivers.mjs.map +1 -0
  119. package/dist/drizzle/oauth-connected-flow.mjs +247 -0
  120. package/dist/drizzle/oauth-connected-flow.mjs.map +1 -0
  121. package/dist/drizzle/oauth-connected-input.mjs +103 -0
  122. package/dist/drizzle/oauth-connected-input.mjs.map +1 -0
  123. package/dist/drizzle/oauth-connected-maintenance.mjs +214 -0
  124. package/dist/drizzle/oauth-connected-maintenance.mjs.map +1 -0
  125. package/dist/drizzle/oauth-connected-management.mjs +228 -0
  126. package/dist/drizzle/oauth-connected-management.mjs.map +1 -0
  127. package/dist/drizzle/oauth-connected-model.d.mts +278 -0
  128. package/dist/drizzle/oauth-connected-model.mjs +22 -0
  129. package/dist/drizzle/oauth-connected-model.mjs.map +1 -0
  130. package/dist/drizzle/oauth-connected-reference.d.mts +17 -0
  131. package/dist/drizzle/oauth-connected-reference.mjs +53 -0
  132. package/dist/drizzle/oauth-connected-reference.mjs.map +1 -0
  133. package/dist/drizzle/oauth-connected-settlement.mjs +117 -0
  134. package/dist/drizzle/oauth-connected-settlement.mjs.map +1 -0
  135. package/dist/drizzle/oauth-connected-state.d.mts +14 -0
  136. package/dist/drizzle/oauth-connected-state.mjs +422 -0
  137. package/dist/drizzle/oauth-connected-state.mjs.map +1 -0
  138. package/dist/drizzle/oauth-connected-target.d.mts +753 -0
  139. package/dist/drizzle/oauth-connected-target.mjs +91 -0
  140. package/dist/drizzle/oauth-connected-target.mjs.map +1 -0
  141. package/dist/drizzle/oauth-drivers.mjs +51 -0
  142. package/dist/drizzle/oauth-drivers.mjs.map +1 -0
  143. package/dist/drizzle/oauth-flow.d.mts +5 -0
  144. package/dist/drizzle/oauth-flow.mjs +253 -0
  145. package/dist/drizzle/oauth-flow.mjs.map +1 -0
  146. package/dist/drizzle/oauth-input.mjs +127 -0
  147. package/dist/drizzle/oauth-input.mjs.map +1 -0
  148. package/dist/drizzle/oauth-model.d.mts +463 -0
  149. package/dist/drizzle/oauth-model.mjs +49 -0
  150. package/dist/drizzle/oauth-model.mjs.map +1 -0
  151. package/dist/drizzle/oauth-mysql.mjs +8 -0
  152. package/dist/drizzle/oauth-mysql.mjs.map +1 -0
  153. package/dist/drizzle/oauth-owner.d.mts +4 -0
  154. package/dist/drizzle/oauth-owner.mjs +10 -0
  155. package/dist/drizzle/oauth-owner.mjs.map +1 -0
  156. package/dist/drizzle/oauth-registration.d.mts +6 -0
  157. package/dist/drizzle/oauth-registration.mjs +374 -0
  158. package/dist/drizzle/oauth-registration.mjs.map +1 -0
  159. package/dist/drizzle/oauth-state.mjs +107 -0
  160. package/dist/drizzle/oauth-state.mjs.map +1 -0
  161. package/dist/drizzle/oauth-target.d.mts +111 -0
  162. package/dist/drizzle/oauth-target.mjs +246 -0
  163. package/dist/drizzle/oauth-target.mjs.map +1 -0
  164. package/dist/drizzle/passkey-drivers.mjs +34 -0
  165. package/dist/drizzle/passkey-drivers.mjs.map +1 -0
  166. package/dist/drizzle/passkey-kernel.mjs +8 -0
  167. package/dist/drizzle/passkey-kernel.mjs.map +1 -0
  168. package/dist/drizzle/passkey-model.d.mts +272 -0
  169. package/dist/drizzle/passkey-model.mjs +34 -0
  170. package/dist/drizzle/passkey-model.mjs.map +1 -0
  171. package/dist/drizzle/passkey-registration-ceremony-model.d.mts +50 -0
  172. package/dist/drizzle/passkey-registration-ceremony-model.mjs +18 -0
  173. package/dist/drizzle/passkey-registration-ceremony-model.mjs.map +1 -0
  174. package/dist/drizzle/passkey-state.mjs +7 -0
  175. package/dist/drizzle/passkey-state.mjs.map +1 -0
  176. package/dist/drizzle/passkey-target.d.mts +9 -0
  177. package/dist/drizzle/passkey-target.mjs +7 -0
  178. package/dist/drizzle/passkey-target.mjs.map +1 -0
  179. package/dist/drizzle/passkey-write-drivers.mjs +32 -0
  180. package/dist/drizzle/passkey-write-drivers.mjs.map +1 -0
  181. package/dist/drizzle/passkey-write-model.d.mts +190 -0
  182. package/dist/drizzle/passkey-write-model.mjs +13 -0
  183. package/dist/drizzle/passkey-write-model.mjs.map +1 -0
  184. package/dist/drizzle/passkey-write-target.d.mts +11 -0
  185. package/dist/drizzle/passkey-write-target.mjs +7 -0
  186. package/dist/drizzle/passkey-write-target.mjs.map +1 -0
  187. package/dist/drizzle/password-model.d.mts +329 -0
  188. package/dist/drizzle/password-model.mjs +23 -0
  189. package/dist/drizzle/password-model.mjs.map +1 -0
  190. package/dist/drizzle/password-prepared-model.d.mts +94 -0
  191. package/dist/drizzle/password-prepared-model.mjs +11 -0
  192. package/dist/drizzle/password-prepared-model.mjs.map +1 -0
  193. package/dist/drizzle/password-prepared-sql.mjs +390 -0
  194. package/dist/drizzle/password-prepared-sql.mjs.map +1 -0
  195. package/dist/drizzle/password-prepared-state.mjs +104 -0
  196. package/dist/drizzle/password-prepared-state.mjs.map +1 -0
  197. package/dist/drizzle/password-prepared-target.d.mts +12 -0
  198. package/dist/drizzle/password-prepared-target.mjs +56 -0
  199. package/dist/drizzle/password-prepared-target.mjs.map +1 -0
  200. package/dist/drizzle/password-registration.d.mts +19 -0
  201. package/dist/drizzle/password-registration.mjs +135 -0
  202. package/dist/drizzle/password-registration.mjs.map +1 -0
  203. package/dist/drizzle/password-sql.d.mts +5 -0
  204. package/dist/drizzle/password-sql.mjs +9 -0
  205. package/dist/drizzle/password-sql.mjs.map +1 -0
  206. package/dist/drizzle/password-target.d.mts +17 -0
  207. package/dist/drizzle/password-target.mjs +61 -0
  208. package/dist/drizzle/password-target.mjs.map +1 -0
  209. package/dist/drizzle/pg-emails.d.mts +72 -0
  210. package/dist/drizzle/pg-emails.mjs +38 -0
  211. package/dist/drizzle/pg-emails.mjs.map +1 -0
  212. package/dist/drizzle/pg-password-prepared.d.mts +31 -0
  213. package/dist/drizzle/pg-password-prepared.mjs +16 -0
  214. package/dist/drizzle/pg-password-prepared.mjs.map +1 -0
  215. package/dist/drizzle/pg-passwords.d.mts +87 -0
  216. package/dist/drizzle/pg-passwords.mjs +38 -0
  217. package/dist/drizzle/pg-passwords.mjs.map +1 -0
  218. package/dist/drizzle/pg-proofs.d.mts +76 -0
  219. package/dist/drizzle/pg-proofs.mjs +22 -0
  220. package/dist/drizzle/pg-proofs.mjs.map +1 -0
  221. package/dist/drizzle/pg-sessions.d.mts +238 -0
  222. package/dist/drizzle/pg-sessions.mjs +53 -0
  223. package/dist/drizzle/pg-sessions.mjs.map +1 -0
  224. package/dist/drizzle/pg.d.mts +81 -0
  225. package/dist/drizzle/pg.mjs +290 -0
  226. package/dist/drizzle/pg.mjs.map +1 -0
  227. package/dist/drizzle/phone-model.d.mts +115 -0
  228. package/dist/drizzle/phone-model.mjs +39 -0
  229. package/dist/drizzle/phone-model.mjs.map +1 -0
  230. package/dist/drizzle/phone-state.mjs +16 -0
  231. package/dist/drizzle/phone-state.mjs.map +1 -0
  232. package/dist/drizzle/phone-target.d.mts +17 -0
  233. package/dist/drizzle/phone-target.mjs +170 -0
  234. package/dist/drizzle/phone-target.mjs.map +1 -0
  235. package/dist/drizzle/proof-model.d.mts +286 -0
  236. package/dist/drizzle/proof-model.mjs +17 -0
  237. package/dist/drizzle/proof-model.mjs.map +1 -0
  238. package/dist/drizzle/proof-sql.d.mts +4 -0
  239. package/dist/drizzle/proof-sql.mjs +8 -0
  240. package/dist/drizzle/proof-sql.mjs.map +1 -0
  241. package/dist/drizzle/proof-target.d.mts +12 -0
  242. package/dist/drizzle/proof-target.mjs +36 -0
  243. package/dist/drizzle/proof-target.mjs.map +1 -0
  244. package/dist/drizzle/query-operations.mjs +26 -0
  245. package/dist/drizzle/query-operations.mjs.map +1 -0
  246. package/dist/drizzle/session-model.d.mts +200 -0
  247. package/dist/drizzle/session-model.mjs +20 -0
  248. package/dist/drizzle/session-model.mjs.map +1 -0
  249. package/dist/drizzle/session-sql.mjs +8 -0
  250. package/dist/drizzle/session-sql.mjs.map +1 -0
  251. package/dist/drizzle/session-target.d.mts +28 -0
  252. package/dist/drizzle/session-target.mjs +47 -0
  253. package/dist/drizzle/session-target.mjs.map +1 -0
  254. package/dist/drizzle/sqlite-emails.mjs +45 -0
  255. package/dist/drizzle/sqlite-emails.mjs.map +1 -0
  256. package/dist/drizzle/sqlite-identity.mjs +91 -0
  257. package/dist/drizzle/sqlite-identity.mjs.map +1 -0
  258. package/dist/drizzle/sqlite-password-prepared.mjs +21 -0
  259. package/dist/drizzle/sqlite-password-prepared.mjs.map +1 -0
  260. package/dist/drizzle/sqlite-passwords.mjs +49 -0
  261. package/dist/drizzle/sqlite-passwords.mjs.map +1 -0
  262. package/dist/drizzle/sqlite-proofs.mjs +29 -0
  263. package/dist/drizzle/sqlite-proofs.mjs.map +1 -0
  264. package/dist/drizzle/sqlite-sessions.mjs +74 -0
  265. package/dist/drizzle/sqlite-sessions.mjs.map +1 -0
  266. package/dist/drizzle/sqlite.d.mts +78 -0
  267. package/dist/drizzle/sqlite.mjs +217 -0
  268. package/dist/drizzle/sqlite.mjs.map +1 -0
  269. package/dist/drizzle/standalone-guard.mjs +19 -0
  270. package/dist/drizzle/standalone-guard.mjs.map +1 -0
  271. package/dist/drizzle/step-up-model.d.mts +65 -0
  272. package/dist/drizzle/step-up-model.mjs +9 -0
  273. package/dist/drizzle/step-up-model.mjs.map +1 -0
  274. package/dist/drizzle/step-up-state.mjs +32 -0
  275. package/dist/drizzle/step-up-state.mjs.map +1 -0
  276. package/dist/drizzle/totp-model.d.mts +84 -0
  277. package/dist/drizzle/totp-model.mjs +13 -0
  278. package/dist/drizzle/totp-model.mjs.map +1 -0
  279. package/dist/drizzle/totp-state.d.mts +38 -0
  280. package/dist/drizzle/totp-state.mjs +287 -0
  281. package/dist/drizzle/totp-state.mjs.map +1 -0
  282. package/dist/drizzle/totp-target.d.mts +17 -0
  283. package/dist/drizzle/totp-target.mjs +81 -0
  284. package/dist/drizzle/totp-target.mjs.map +1 -0
  285. package/dist/drizzle/transaction-execution.d.mts +4 -0
  286. package/dist/drizzle/transaction-execution.mjs +11 -0
  287. package/dist/drizzle/transaction-execution.mjs.map +1 -0
  288. package/dist/drizzle/transaction-mysql.mjs +46 -0
  289. package/dist/drizzle/transaction-mysql.mjs.map +1 -0
  290. package/dist/drizzle/transaction-owner.d.mts +2 -0
  291. package/dist/drizzle/transaction-owner.mjs +8 -0
  292. package/dist/drizzle/transaction-owner.mjs.map +1 -0
  293. package/dist/index.d.mts +5 -0
  294. package/dist/index.mjs +5 -0
  295. package/dist/internal/configuration.d.mts +174 -0
  296. package/dist/internal/configuration.mjs +7 -0
  297. package/dist/internal/configuration.mjs.map +1 -0
  298. package/dist/internal/drizzle-migrations.mjs +19 -0
  299. package/dist/internal/drizzle-migrations.mjs.map +1 -0
  300. package/dist/internal/drizzle-postgres.mjs +39 -0
  301. package/dist/internal/drizzle-postgres.mjs.map +1 -0
  302. package/dist/internal/drizzle-sqlite.mjs +37 -0
  303. package/dist/internal/drizzle-sqlite.mjs.map +1 -0
  304. package/dist/internal/email-kernel.d.mts +13 -0
  305. package/dist/internal/email-kernel.mjs +487 -0
  306. package/dist/internal/email-kernel.mjs.map +1 -0
  307. package/dist/internal/mapping-error.d.mts +11 -0
  308. package/dist/internal/mapping-error.mjs +30 -0
  309. package/dist/internal/mapping-error.mjs.map +1 -0
  310. package/dist/internal/passkey/admission.d.mts +7 -0
  311. package/dist/internal/passkey/admission.mjs +216 -0
  312. package/dist/internal/passkey/admission.mjs.map +1 -0
  313. package/dist/internal/passkey/credentials.d.mts +6 -0
  314. package/dist/internal/passkey/credentials.mjs +249 -0
  315. package/dist/internal/passkey/credentials.mjs.map +1 -0
  316. package/dist/internal/passkey/enrollment.mjs +138 -0
  317. package/dist/internal/passkey/enrollment.mjs.map +1 -0
  318. package/dist/internal/passkey/flow.d.mts +10 -0
  319. package/dist/internal/passkey/flow.mjs +452 -0
  320. package/dist/internal/passkey/flow.mjs.map +1 -0
  321. package/dist/internal/passkey/management.mjs +231 -0
  322. package/dist/internal/passkey/management.mjs.map +1 -0
  323. package/dist/internal/passkey/registration-ceremony.d.mts +9 -0
  324. package/dist/internal/passkey/registration-ceremony.mjs +129 -0
  325. package/dist/internal/passkey/registration-ceremony.mjs.map +1 -0
  326. package/dist/internal/passkey/registration-custody.d.mts +2 -0
  327. package/dist/internal/passkey/registration-custody.mjs +52 -0
  328. package/dist/internal/passkey/registration-custody.mjs.map +1 -0
  329. package/dist/internal/passkey/registration-write.mjs +211 -0
  330. package/dist/internal/passkey/registration-write.mjs.map +1 -0
  331. package/dist/internal/passkey/state.d.mts +5 -0
  332. package/dist/internal/passkey/state.mjs +234 -0
  333. package/dist/internal/passkey/state.mjs.map +1 -0
  334. package/dist/internal/passkey/target.d.mts +19 -0
  335. package/dist/internal/passkey/target.mjs +190 -0
  336. package/dist/internal/passkey/target.mjs.map +1 -0
  337. package/dist/internal/passkey/write-state.mjs +345 -0
  338. package/dist/internal/passkey/write-state.mjs.map +1 -0
  339. package/dist/internal/passkey/write-target.mjs +192 -0
  340. package/dist/internal/passkey/write-target.mjs.map +1 -0
  341. package/dist/internal/passkey-kernel.mjs +49 -0
  342. package/dist/internal/passkey-kernel.mjs.map +1 -0
  343. package/dist/internal/passkeys.mjs +367 -0
  344. package/dist/internal/passkeys.mjs.map +1 -0
  345. package/dist/internal/password-kernel.d.mts +13 -0
  346. package/dist/internal/password-kernel.mjs +704 -0
  347. package/dist/internal/password-kernel.mjs.map +1 -0
  348. package/dist/internal/persistence.mjs +289 -0
  349. package/dist/internal/persistence.mjs.map +1 -0
  350. package/dist/internal/phone-kernel.mjs +434 -0
  351. package/dist/internal/phone-kernel.mjs.map +1 -0
  352. package/dist/internal/proof-kernel.d.mts +9 -0
  353. package/dist/internal/proof-kernel.mjs +619 -0
  354. package/dist/internal/proof-kernel.mjs.map +1 -0
  355. package/dist/internal/query-operations.d.mts +3 -0
  356. package/dist/internal/registration.mjs +65 -0
  357. package/dist/internal/registration.mjs.map +1 -0
  358. package/dist/internal/session-kernel.mjs +737 -0
  359. package/dist/internal/session-kernel.mjs.map +1 -0
  360. package/dist/internal/sql-persistence.d.mts +11 -0
  361. package/dist/internal/sql-persistence.mjs +37 -0
  362. package/dist/internal/sql-persistence.mjs.map +1 -0
  363. package/dist/internal/sql-query.mjs +207 -0
  364. package/dist/internal/sql-query.mjs.map +1 -0
  365. package/dist/internal/sql-table.d.mts +37 -0
  366. package/dist/internal/sql-table.mjs +71 -0
  367. package/dist/internal/sql-table.mjs.map +1 -0
  368. package/dist/internal/storage-mapping.mjs +687 -0
  369. package/dist/internal/storage-mapping.mjs.map +1 -0
  370. package/dist/internal/storage-tables.d.mts +914 -0
  371. package/dist/internal/storage-tables.mjs +387 -0
  372. package/dist/internal/storage-tables.mjs.map +1 -0
  373. package/dist/internal/storage-validation.mjs +58 -0
  374. package/dist/internal/storage-validation.mjs.map +1 -0
  375. package/dist/internal/transaction-execution-kernel.d.mts +18 -0
  376. package/dist/internal/transaction-execution-kernel.mjs +118 -0
  377. package/dist/internal/transaction-execution-kernel.mjs.map +1 -0
  378. package/dist/internal/transaction-kernel.d.mts +7 -0
  379. package/dist/internal/transaction-kernel.mjs +260 -0
  380. package/dist/internal/transaction-kernel.mjs.map +1 -0
  381. package/package.json +1 -0
  382. package/src/Drizzle.ts +378 -0
  383. package/src/DrizzleD1.ts +136 -0
  384. package/src/DrizzleLibsql.ts +301 -0
  385. package/src/DrizzleMysql2.ts +184 -0
  386. package/src/DrizzlePglite.ts +174 -0
  387. package/src/DrizzlePostgres.ts +174 -0
  388. package/src/DrizzleSqliteBun.ts +258 -0
  389. package/src/DrizzleSqliteDo.ts +473 -0
  390. package/src/DrizzleSqliteNode.ts +259 -0
  391. package/src/DrizzleSqliteWasm.ts +263 -0
  392. package/src/drizzle/D1BatchStatements.ts +10 -0
  393. package/src/drizzle/PasswordPreparedPostconditions.ts +30 -0
  394. package/src/drizzle/SuppliedService.ts +10 -0
  395. package/src/drizzle/d1-emails.ts +1829 -0
  396. package/src/drizzle/d1-generated-statement.ts +129 -0
  397. package/src/drizzle/d1-identity.ts +375 -0
  398. package/src/drizzle/d1-oauth.ts +340 -0
  399. package/src/drizzle/d1-passkey.ts +373 -0
  400. package/src/drizzle/d1-password-prepared.ts +1270 -0
  401. package/src/drizzle/d1-passwords.ts +2656 -0
  402. package/src/drizzle/d1-phone.ts +96 -0
  403. package/src/drizzle/d1-planning.ts +104 -0
  404. package/src/drizzle/d1-proofs.ts +2305 -0
  405. package/src/drizzle/d1-sessions.ts +2857 -0
  406. package/src/drizzle/d1-totp.ts +78 -0
  407. package/src/drizzle/email-model.ts +516 -0
  408. package/src/drizzle/email-registration.ts +698 -0
  409. package/src/drizzle/email-sql.ts +24 -0
  410. package/src/drizzle/email-target.ts +243 -0
  411. package/src/drizzle/model.ts +463 -0
  412. package/src/drizzle/mysql-emails.ts +321 -0
  413. package/src/drizzle/mysql-identity.ts +324 -0
  414. package/src/drizzle/mysql-password-prepared.ts +204 -0
  415. package/src/drizzle/mysql-passwords.ts +339 -0
  416. package/src/drizzle/mysql-proofs.ts +181 -0
  417. package/src/drizzle/mysql-sessions.ts +741 -0
  418. package/src/drizzle/mysql.ts +687 -0
  419. package/src/drizzle/oauth-accounts.ts +804 -0
  420. package/src/drizzle/oauth-connected-access.ts +354 -0
  421. package/src/drizzle/oauth-connected-collection.ts +324 -0
  422. package/src/drizzle/oauth-connected-custody.ts +277 -0
  423. package/src/drizzle/oauth-connected-drivers.ts +465 -0
  424. package/src/drizzle/oauth-connected-flow.ts +441 -0
  425. package/src/drizzle/oauth-connected-input.ts +127 -0
  426. package/src/drizzle/oauth-connected-maintenance.ts +345 -0
  427. package/src/drizzle/oauth-connected-management.ts +365 -0
  428. package/src/drizzle/oauth-connected-model.ts +347 -0
  429. package/src/drizzle/oauth-connected-reference.ts +112 -0
  430. package/src/drizzle/oauth-connected-settlement.ts +226 -0
  431. package/src/drizzle/oauth-connected-state.ts +845 -0
  432. package/src/drizzle/oauth-connected-target.ts +264 -0
  433. package/src/drizzle/oauth-drivers.ts +569 -0
  434. package/src/drizzle/oauth-flow.ts +462 -0
  435. package/src/drizzle/oauth-input.ts +201 -0
  436. package/src/drizzle/oauth-model.ts +617 -0
  437. package/src/drizzle/oauth-mysql.ts +10 -0
  438. package/src/drizzle/oauth-owner.ts +29 -0
  439. package/src/drizzle/oauth-registration.ts +640 -0
  440. package/src/drizzle/oauth-state.ts +215 -0
  441. package/src/drizzle/oauth-target.ts +750 -0
  442. package/src/drizzle/passkey-drivers.ts +385 -0
  443. package/src/drizzle/passkey-kernel.ts +3 -0
  444. package/src/drizzle/passkey-model.ts +353 -0
  445. package/src/drizzle/passkey-registration-ceremony-model.ts +69 -0
  446. package/src/drizzle/passkey-state.ts +3 -0
  447. package/src/drizzle/passkey-target.ts +23 -0
  448. package/src/drizzle/passkey-write-drivers.ts +395 -0
  449. package/src/drizzle/passkey-write-model.ts +271 -0
  450. package/src/drizzle/passkey-write-target.ts +9 -0
  451. package/src/drizzle/password-model.ts +491 -0
  452. package/src/drizzle/password-prepared-model.ts +259 -0
  453. package/src/drizzle/password-prepared-sql.ts +1191 -0
  454. package/src/drizzle/password-prepared-state.ts +231 -0
  455. package/src/drizzle/password-prepared-target.ts +160 -0
  456. package/src/drizzle/password-registration.ts +374 -0
  457. package/src/drizzle/password-sql.ts +12 -0
  458. package/src/drizzle/password-target.ts +224 -0
  459. package/src/drizzle/pg-emails.ts +321 -0
  460. package/src/drizzle/pg-password-prepared.ts +205 -0
  461. package/src/drizzle/pg-passwords.ts +338 -0
  462. package/src/drizzle/pg-proofs.ts +191 -0
  463. package/src/drizzle/pg-sessions.ts +750 -0
  464. package/src/drizzle/pg.ts +984 -0
  465. package/src/drizzle/phone-model.ts +190 -0
  466. package/src/drizzle/phone-state.ts +21 -0
  467. package/src/drizzle/phone-target.ts +472 -0
  468. package/src/drizzle/proof-model.ts +398 -0
  469. package/src/drizzle/proof-sql.ts +9 -0
  470. package/src/drizzle/proof-target.ts +122 -0
  471. package/src/drizzle/query-operations.ts +37 -0
  472. package/src/drizzle/session-model.ts +370 -0
  473. package/src/drizzle/session-sql.ts +13 -0
  474. package/src/drizzle/session-target.ts +338 -0
  475. package/src/drizzle/sqlite-emails.ts +366 -0
  476. package/src/drizzle/sqlite-identity.ts +344 -0
  477. package/src/drizzle/sqlite-password-prepared.ts +260 -0
  478. package/src/drizzle/sqlite-passwords.ts +497 -0
  479. package/src/drizzle/sqlite-proofs.ts +202 -0
  480. package/src/drizzle/sqlite-sessions.ts +971 -0
  481. package/src/drizzle/sqlite.ts +705 -0
  482. package/src/drizzle/standalone-guard.ts +38 -0
  483. package/src/drizzle/step-up-model.ts +128 -0
  484. package/src/drizzle/step-up-state.ts +139 -0
  485. package/src/drizzle/totp-model.ts +92 -0
  486. package/src/drizzle/totp-state.ts +525 -0
  487. package/src/drizzle/totp-target.ts +308 -0
  488. package/src/drizzle/transaction-execution.ts +12 -0
  489. package/src/drizzle/transaction-mysql.ts +104 -0
  490. package/src/drizzle/transaction-owner.ts +10 -0
  491. package/src/index.ts +4 -0
  492. package/src/internal/configuration.ts +282 -0
  493. package/src/internal/drizzle-migrations.ts +30 -0
  494. package/src/internal/drizzle-postgres.ts +81 -0
  495. package/src/internal/drizzle-sqlite.ts +79 -0
  496. package/src/internal/email-kernel.ts +1532 -0
  497. package/src/internal/mapping-error.ts +36 -0
  498. package/src/internal/passkey/admission.ts +362 -0
  499. package/src/internal/passkey/credentials.ts +511 -0
  500. package/src/internal/passkey/enrollment.ts +326 -0
  501. package/src/internal/passkey/flow.ts +1062 -0
  502. package/src/internal/passkey/management.ts +422 -0
  503. package/src/internal/passkey/registration-ceremony.ts +283 -0
  504. package/src/internal/passkey/registration-custody.ts +91 -0
  505. package/src/internal/passkey/registration-write.ts +426 -0
  506. package/src/internal/passkey/state.ts +354 -0
  507. package/src/internal/passkey/target.ts +586 -0
  508. package/src/internal/passkey/write-state.ts +681 -0
  509. package/src/internal/passkey/write-target.ts +452 -0
  510. package/src/internal/passkey-kernel.ts +102 -0
  511. package/src/internal/passkeys.ts +597 -0
  512. package/src/internal/password-kernel.ts +2122 -0
  513. package/src/internal/persistence.ts +590 -0
  514. package/src/internal/phone-kernel.ts +843 -0
  515. package/src/internal/proof-kernel.ts +1949 -0
  516. package/src/internal/query-operations.ts +26 -0
  517. package/src/internal/registration.ts +160 -0
  518. package/src/internal/session-kernel.ts +2210 -0
  519. package/src/internal/sql-persistence.ts +45 -0
  520. package/src/internal/sql-query.ts +298 -0
  521. package/src/internal/sql-table.ts +89 -0
  522. package/src/internal/storage-mapping.ts +706 -0
  523. package/src/internal/storage-tables.ts +408 -0
  524. package/src/internal/storage-validation.ts +117 -0
  525. package/src/internal/transaction-execution-kernel.ts +317 -0
  526. package/src/internal/transaction-kernel.ts +582 -0
@@ -0,0 +1,2305 @@
1
+ /* oxlint-disable no-explicit-any -- D1 planning bridges consumer Drizzle tables to Effect SQL statements. */
2
+ import type { D1Client } from "@effect/sql-d1/D1Client";
3
+ import {
4
+ coordinateCommit,
5
+ CurrentCommitJournal,
6
+ hasCommitScope,
7
+ type CommitJournal,
8
+ type PreparedCommit,
9
+ LifecycleHooks,
10
+ HookConfigurationError,
11
+ } from "@yielded/auth/Hooks";
12
+ import { reportPersistenceFailure } from "@yielded/auth/Persistence";
13
+ import {
14
+ type ProofCompletionPlan,
15
+ ProofBinding,
16
+ type ProofAttemptDecision,
17
+ type ProofCleanupResult,
18
+ type ProofCompletionDecision,
19
+ type ProofDeliveryOutcome,
20
+ type ProofVersion,
21
+ type ProofBudget,
22
+ type ProofPolicy,
23
+ ProofPersistence,
24
+ type PrepareProofCommit,
25
+ type ProofDeliveryClaim,
26
+ ProofRequestConflict,
27
+ ProofUnavailable,
28
+ } from "@yielded/auth/Proofs";
29
+ import {
30
+ and,
31
+ count,
32
+ eq,
33
+ gte,
34
+ inArray,
35
+ isNull,
36
+ lte,
37
+ notExists,
38
+ or,
39
+ sql,
40
+ type AnyRelations,
41
+ type SQL,
42
+ type Table,
43
+ } from "drizzle-orm";
44
+ import type { EffectDrizzleQueryError } from "drizzle-orm/effect-core";
45
+ import type { EffectSQLiteD1Database } from "drizzle-orm/effect-d1";
46
+ import type { AnySQLiteTable } from "drizzle-orm/sqlite-core";
47
+ import { Cause, Effect, Schema, Context } from "effect";
48
+ import type { Statement } from "effect/unstable/sql/Statement";
49
+
50
+ import { balancedD1And } from "./d1-generated-statement";
51
+ import { CurrentD1PlanningDatabase, makeD1Owner } from "./d1-planning";
52
+ import { D1BatchStatements } from "./D1BatchStatements";
53
+ import { column, PersistenceMappingError, isMappedConstraintConflict, updateValues } from "./model";
54
+ import {
55
+ type D1ProofPersistenceMapping,
56
+ requiredProofConstraints,
57
+ type ProofAction,
58
+ type ProofAuthorityInput,
59
+ type ProofCommandDecision,
60
+ type ProofContinuationRecord,
61
+ type ProofPersistenceMapping,
62
+ type ProofScopeKeys,
63
+ type ProofScopeKind,
64
+ } from "./proof-model";
65
+
66
+ type PlanPrepare<Method extends (...args: any[]) => any, A> = (
67
+ value: Parameters<Parameters<Method>[1]>[0],
68
+ journal: CommitJournal,
69
+ ) => PreparedCommit<A>;
70
+
71
+ type Database = EffectSQLiteD1Database<AnyRelations> & { readonly $client: D1Client };
72
+ type Mapping = D1ProofPersistenceMapping<
73
+ Table,
74
+ Table,
75
+ Table,
76
+ Table,
77
+ Table,
78
+ Table,
79
+ Table,
80
+ Table,
81
+ Table,
82
+ Table,
83
+ Table,
84
+ unknown
85
+ >;
86
+ interface Planned<A> {
87
+ readonly receipt: A;
88
+ readonly statements: ReadonlyArray<Statement<any>>;
89
+ readonly retryable?: (cause: unknown) => boolean;
90
+ readonly journalGuard?: PreparedCommit<void>;
91
+ readonly postconditions?: ReadonlyArray<Statement<any>>;
92
+ }
93
+
94
+ const unavailable = () => ProofUnavailable.make({});
95
+
96
+ const everyFailureMatches = (
97
+ cause: Cause.Cause<unknown>,
98
+ classify: ((cause: unknown) => boolean) | undefined,
99
+ ): boolean =>
100
+ classify !== undefined &&
101
+ cause.reasons.length > 0 &&
102
+ cause.reasons.every((reason) => Cause.isFailReason(reason) && classify(Cause.fail(reason.error)));
103
+
104
+ const conflict = () => ProofRequestConflict.make({});
105
+
106
+ const validConstraints = (mapping: Mapping) =>
107
+ Object.entries(requiredProofConstraints).every(
108
+ ([key, value]) => mapping.constraints[key as keyof typeof requiredProofConstraints] === value,
109
+ );
110
+
111
+ const canonicalBinding = Schema.encodeSync(Schema.fromJsonString(ProofBinding));
112
+
113
+ const sameBinding = (left: ProofBinding, right: ProofBinding) =>
114
+ canonicalBinding(left) === canonicalBinding(right);
115
+
116
+ const containsFailure = (failure: unknown, predicate: (value: unknown) => boolean): boolean => {
117
+ const seen = new Set<unknown>();
118
+ const pending: Array<unknown> = [failure];
119
+
120
+ for (let inspected = 0; inspected < 32 && pending.length > 0; inspected++) {
121
+ const current = pending.shift();
122
+
123
+ if (current === undefined || current === null || seen.has(current)) continue;
124
+ seen.add(current);
125
+ if (predicate(current)) return true;
126
+ if (Cause.isCause(current)) {
127
+ for (const reason of current.reasons) {
128
+ if (Cause.isFailReason(reason)) pending.push(reason.error);
129
+ else if (Cause.isDieReason(reason)) pending.push(reason.defect);
130
+ }
131
+ continue;
132
+ }
133
+ if (typeof current !== "object") continue;
134
+
135
+ const wrapped = current as {
136
+ readonly cause?: unknown;
137
+ readonly reason?: unknown;
138
+ readonly message?: unknown;
139
+ };
140
+
141
+ if (wrapped.cause !== undefined) pending.push(wrapped.cause);
142
+ if (wrapped.reason !== undefined) pending.push(wrapped.reason);
143
+ if (wrapped.message !== undefined) pending.push(wrapped.message);
144
+ }
145
+
146
+ return false;
147
+ };
148
+
149
+ // Match only the native workerd/D1 SQLite diagnostic. Query wrappers may echo
150
+ // marker parameters, which is not evidence that the guard ran and rolled back.
151
+ const isGuardFailure = (cause: unknown, marker: string) => {
152
+ const path = `$[${marker.replaceAll("'", "''")}]`;
153
+ const nativeMessage = `bad JSON path: '${path}': SQLITE_ERROR`;
154
+
155
+ return containsFailure(
156
+ cause,
157
+ (value) => value === nativeMessage || value === `D1_ERROR: ${nativeMessage}`,
158
+ );
159
+ };
160
+
161
+ type AdapterFailure = PersistenceMappingError | EffectDrizzleQueryError;
162
+
163
+ const statement = Effect.fn(function* (query: {
164
+ readonly toSQL: () => { readonly sql: string; readonly params: unknown[] };
165
+ }) {
166
+ const database = yield* CurrentD1PlanningDatabase;
167
+ const rendered = query.toSQL();
168
+
169
+ return database.$client.unsafe(rendered.sql, rendered.params);
170
+ });
171
+
172
+ const readEngineNowMillis = Effect.fn("Drizzle.readEngineNowMillis")(function* (mapping: Mapping) {
173
+ const database = yield* CurrentD1PlanningDatabase;
174
+
175
+ return yield* database
176
+ .select({ value: mapping.d1.engineNowMillis.as("engine_now_millis") })
177
+ .from(sql`(select 1)`)
178
+ .pipe(
179
+ Effect.flatMap((rows) => {
180
+ const value = Number(rows[0]?.value);
181
+
182
+ return Number.isFinite(value) ? Effect.succeed(value) : Effect.fail(unavailable());
183
+ }),
184
+ );
185
+ });
186
+
187
+ const driverValues = (values: object, entries: ReadonlyArray<readonly [string, unknown]>) => ({
188
+ ...values,
189
+ ...Object.fromEntries(entries),
190
+ });
191
+
192
+ const assertion = Effect.fn(function* (condition: SQL, marker: string) {
193
+ const database = yield* CurrentD1PlanningDatabase;
194
+
195
+ return yield* statement(
196
+ database
197
+ .select({
198
+ ok: sql`case when ${condition} then 1 else json_extract('[]', ${`$[${marker}]`}) end`.as(
199
+ "ok",
200
+ ),
201
+ })
202
+ .from(sql`(select 1)`),
203
+ );
204
+ });
205
+
206
+ const allocateVersion = (
207
+ mapping: Mapping,
208
+ ): Effect.Effect<ProofVersion, ProofUnavailable | PersistenceMappingError> =>
209
+ mapping.allocateVersion !== undefined
210
+ ? mapping.allocateVersion
211
+ : mapping.allocateVersionSync === undefined
212
+ ? Effect.fail(unavailable())
213
+ : Effect.try({
214
+ try: mapping.allocateVersionSync,
215
+ catch: (cause) => new PersistenceMappingError({ operation: "mapping", cause }),
216
+ });
217
+
218
+ const requestColumns = (mapping: Mapping) => ({
219
+ moduleId: column(mapping.request.table, mapping.request.moduleId),
220
+ requestId: column(mapping.request.table, mapping.request.requestId),
221
+ fingerprint: column(mapping.request.table, mapping.request.fingerprint),
222
+ proofId: column(mapping.request.table, mapping.request.proofId),
223
+ retentionUntil: column(mapping.request.table, mapping.request.retentionUntil),
224
+ });
225
+
226
+ const seriesColumns = (mapping: Mapping) => ({
227
+ moduleId: column(mapping.series.table, mapping.series.moduleId),
228
+ purpose: column(mapping.series.table, mapping.series.purpose),
229
+ scopeKey: column(mapping.series.table, mapping.series.scopeKey),
230
+ activeProofId: column(mapping.series.table, mapping.series.activeProofId),
231
+ lastIssueAt: column(mapping.series.table, mapping.series.lastIssueAt),
232
+ version: column(mapping.series.table, mapping.series.version),
233
+ });
234
+
235
+ const generationColumns = (mapping: Mapping) => ({
236
+ moduleId: column(mapping.generation.table, mapping.generation.moduleId),
237
+ purpose: column(mapping.generation.table, mapping.generation.purpose),
238
+ proofId: column(mapping.generation.table, mapping.generation.proofId),
239
+ seriesKey: column(mapping.generation.table, mapping.generation.seriesKey),
240
+ deliveryId: column(mapping.generation.table, mapping.generation.deliveryId),
241
+ verifierKeyId: column(mapping.generation.table, mapping.generation.verifierKeyId),
242
+ verifierDigest: column(mapping.generation.table, mapping.generation.verifierDigest),
243
+ expiresAt: column(mapping.generation.table, mapping.generation.expiresAt),
244
+ version: column(mapping.generation.table, mapping.generation.version),
245
+ state: column(mapping.generation.table, mapping.generation.state),
246
+ sendCount: column(mapping.generation.table, mapping.generation.sendCount),
247
+ deliveryState: column(mapping.generation.table, mapping.generation.deliveryState),
248
+ claimVersion: column(mapping.generation.table, mapping.generation.claimVersion),
249
+ claimDeadline: column(mapping.generation.table, mapping.generation.claimDeadline),
250
+ retryAt: column(mapping.generation.table, mapping.generation.retryAt),
251
+ deliveryRetryMillis: column(mapping.generation.table, mapping.generation.deliveryRetryMillis),
252
+ retentionUntil: column(mapping.generation.table, mapping.generation.retentionUntil),
253
+ });
254
+
255
+ const continuationColumns = (mapping: Mapping) => ({
256
+ moduleId: column(mapping.continuation.table, mapping.continuation.moduleId),
257
+ continuationId: column(mapping.continuation.table, mapping.continuation.continuationId),
258
+ digest: column(mapping.continuation.table, mapping.continuation.digest),
259
+ consumed: column(mapping.continuation.table, mapping.continuation.consumed),
260
+ retentionUntil: column(mapping.continuation.table, mapping.continuation.retentionUntil),
261
+ });
262
+
263
+ const scopeColumns = (mapping: Mapping) => ({
264
+ moduleId: column(mapping.rateScope.table, mapping.rateScope.moduleId),
265
+ purpose: column(mapping.rateScope.table, mapping.rateScope.purpose),
266
+ action: column(mapping.rateScope.table, mapping.rateScope.action),
267
+ scopeKind: column(mapping.rateScope.table, mapping.rateScope.scopeKind),
268
+ scopeKey: column(mapping.rateScope.table, mapping.rateScope.scopeKey),
269
+ });
270
+
271
+ const abuseColumns = (mapping: Mapping) => ({
272
+ moduleId: column(mapping.abuseEvent.table, mapping.abuseEvent.moduleId),
273
+ purpose: column(mapping.abuseEvent.table, mapping.abuseEvent.purpose),
274
+ action: column(mapping.abuseEvent.table, mapping.abuseEvent.action),
275
+ scopeKind: column(mapping.abuseEvent.table, mapping.abuseEvent.scopeKind),
276
+ scopeKey: column(mapping.abuseEvent.table, mapping.abuseEvent.scopeKey),
277
+ commandId: column(mapping.abuseEvent.table, mapping.abuseEvent.commandId),
278
+ occurredAt: column(mapping.abuseEvent.table, mapping.abuseEvent.occurredAt),
279
+ retentionUntil: column(mapping.abuseEvent.table, mapping.abuseEvent.retentionUntil),
280
+ });
281
+
282
+ const failureColumns = (mapping: Mapping) => ({
283
+ moduleId: column(mapping.failureEvent.table, mapping.failureEvent.moduleId),
284
+ purpose: column(mapping.failureEvent.table, mapping.failureEvent.purpose),
285
+ seriesKey: column(mapping.failureEvent.table, mapping.failureEvent.seriesKey),
286
+ commandId: column(mapping.failureEvent.table, mapping.failureEvent.commandId),
287
+ occurredAt: column(mapping.failureEvent.table, mapping.failureEvent.occurredAt),
288
+ retentionUntil: column(mapping.failureEvent.table, mapping.failureEvent.retentionUntil),
289
+ });
290
+
291
+ const commandColumns = (mapping: Mapping) => ({
292
+ moduleId: column(mapping.command.table, mapping.command.moduleId),
293
+ commandId: column(mapping.command.table, mapping.command.commandId),
294
+ decision: column(mapping.command.table, mapping.command.decision),
295
+ retentionUntil: column(mapping.command.table, mapping.command.retentionUntil),
296
+ });
297
+
298
+ interface ScopeEntry {
299
+ readonly kind: ProofScopeKind;
300
+ readonly key: string;
301
+ readonly budget: ProofBudget;
302
+ }
303
+
304
+ const scopeEntries = (
305
+ keys: ProofScopeKeys,
306
+ binding: ProofBinding,
307
+ action: ProofAction,
308
+ policy: ProofPolicy,
309
+ ) => {
310
+ const suffix = action === "issue" ? "Issues" : "Attempts";
311
+ const simple = action === "issue" ? "issues" : "attempts";
312
+
313
+ const entries: ScopeEntry[] = [
314
+ { kind: "action", key: "*", budget: policy.abuse[`action${suffix}`] },
315
+ { kind: "identifier", key: keys.identifier, budget: policy.abuse[simple] },
316
+ ];
317
+
318
+ if (binding._tag !== "Identifier")
319
+ entries.push({ kind: "subject", key: keys.subject, budget: policy.abuse[`subject${suffix}`] });
320
+
321
+ return entries;
322
+ };
323
+
324
+ const scopeCondition = (
325
+ mapping: Mapping,
326
+ moduleId: string,
327
+ purpose: any,
328
+ action: ProofAction,
329
+ entry: ScopeEntry,
330
+ ) => {
331
+ const c = abuseColumns(mapping);
332
+
333
+ return sql`(select count(*) from ${mapping.abuseEvent.table} where ${c.moduleId} = ${sql.param(moduleId, c.moduleId)} and ${c.purpose} = ${sql.param(purpose, c.purpose)} and ${c.action} = ${sql.param(action, c.action)} and ${c.scopeKind} = ${sql.param(entry.kind, c.scopeKind)} and ${c.scopeKey} = ${sql.param(entry.key, c.scopeKey)} and ${c.occurredAt} >= ${mapping.d1.engineInstantMinus(entry.budget.windowMillis)}) < ${entry.budget.limit}`;
334
+ };
335
+
336
+ const failureCondition = (
337
+ mapping: Mapping,
338
+ moduleId: string,
339
+ purpose: any,
340
+ seriesKey: string,
341
+ policy: ProofPolicy,
342
+ ) => {
343
+ const c = failureColumns(mapping);
344
+
345
+ return sql`(select count(*) from ${mapping.failureEvent.table} where ${c.moduleId} = ${sql.param(moduleId, c.moduleId)} and ${c.purpose} = ${sql.param(purpose, c.purpose)} and ${c.seriesKey} = ${sql.param(seriesKey, c.seriesKey)} and ${c.occurredAt} >= ${mapping.d1.engineInstantMinus(policy.abuse.attempts.windowMillis)}) < ${policy.maximumFailedAttempts}`;
346
+ };
347
+
348
+ const readScopeAdmission = Effect.fn("DrizzleD1Proof.readScopeAdmission")(function* (
349
+ mapping: Mapping,
350
+ moduleId: string,
351
+ purpose: any,
352
+ action: ProofAction,
353
+ entries: ReadonlyArray<ScopeEntry>,
354
+ now: number,
355
+ ) {
356
+ const database = yield* CurrentD1PlanningDatabase;
357
+
358
+ const c = abuseColumns(mapping);
359
+ const admitted: ScopeEntry[] = [];
360
+
361
+ for (const entry of entries) {
362
+ const rows = yield* database
363
+ .select({ total: count() })
364
+ .from(mapping.abuseEvent.table)
365
+ .where(
366
+ and(
367
+ eq(c.moduleId, moduleId),
368
+ eq(c.purpose, purpose),
369
+ eq(c.action, action),
370
+ eq(c.scopeKind, entry.kind),
371
+ eq(c.scopeKey, entry.key),
372
+ gte(c.occurredAt, mapping.encodeInstant(now - entry.budget.windowMillis)),
373
+ ),
374
+ );
375
+
376
+ if (Number(rows[0]?.total ?? 0) < entry.budget.limit) admitted.push(entry);
377
+ }
378
+
379
+ return admitted;
380
+ });
381
+
382
+ const authority = Effect.fn("DrizzleD1Proof.authority")(function* (
383
+ mapping: Mapping,
384
+ moduleId: string,
385
+ purpose: any,
386
+ binding: ProofBinding,
387
+ ) {
388
+ const database = yield* CurrentD1PlanningDatabase;
389
+
390
+ let nativeSubjectId: unknown | undefined;
391
+ let subjectCurrent = true;
392
+ const parts: SQL[] = [];
393
+
394
+ if (binding._tag !== "Identifier") {
395
+ if (
396
+ mapping.authority.subject === undefined ||
397
+ mapping.authority.credential === undefined ||
398
+ mapping.authority.subjectId === undefined
399
+ )
400
+ return yield* unavailable();
401
+ nativeSubjectId = yield* mapping.authority.subjectId.toNative(binding.revision.subjectId);
402
+ const subject = mapping.authority.subject;
403
+ const id = column(subject.table, subject.id);
404
+ const status = column(subject.table, subject.status);
405
+ const revision = column(subject.table, subject.securityRevision);
406
+
407
+ const subjectRows = yield* database
408
+ .select()
409
+ .from(subject.table)
410
+ .where(eq(id, nativeSubjectId))
411
+ .limit(1);
412
+
413
+ const subjectRow = subjectRows[0];
414
+
415
+ subjectCurrent =
416
+ subjectRow !== undefined &&
417
+ subject.isActiveStatus(subjectRow[subject.status]) &&
418
+ subjectRow[subject.securityRevision] === binding.revision.securityRevision;
419
+ parts.push(
420
+ sql`exists(select 1 from ${subject.table} where ${id} = ${sql.param(nativeSubjectId, id)} and ${status} = ${sql.param(subject.d1ActiveStatusValue, status)} and ${revision} = ${sql.param(binding.revision.securityRevision, revision)})`,
421
+ );
422
+ }
423
+ const identifier = mapping.authority.identifier;
424
+ const namespace = column(identifier.table, identifier.namespace);
425
+ const value = column(identifier.table, identifier.value);
426
+
427
+ const identifierRows = yield* database
428
+ .select()
429
+ .from(identifier.table)
430
+ .where(and(eq(namespace, binding.identifier.namespace), eq(value, binding.identifier.value)));
431
+
432
+ const input: ProofAuthorityInput<unknown> = {
433
+ moduleId,
434
+ purpose,
435
+ binding,
436
+ ...(nativeSubjectId === undefined ? {} : { nativeSubjectId }),
437
+ };
438
+
439
+ const identifierCurrent = identifier.isCurrent(input, identifierRows);
440
+
441
+ parts.push(identifier.d1CurrentCondition(input));
442
+ let credentialsCurrent = true;
443
+
444
+ if (binding._tag !== "Identifier") {
445
+ const credential = mapping.authority.credential!;
446
+ const owner = column(credential.table, credential.subjectId);
447
+ const id = column(credential.table, credential.credentialId);
448
+ const revision = column(credential.table, credential.revision);
449
+
450
+ const status =
451
+ credential.status === undefined ? undefined : column(credential.table, credential.status);
452
+
453
+ const expected = [...binding.revision.credentials].sort((a, b) =>
454
+ a.credentialId.localeCompare(b.credentialId),
455
+ );
456
+
457
+ const rows =
458
+ expected.length === 0
459
+ ? []
460
+ : yield* database
461
+ .select()
462
+ .from(credential.table)
463
+ .where(
464
+ and(
465
+ eq(owner, nativeSubjectId),
466
+ inArray(
467
+ id,
468
+ expected.map((item) => item.credentialId),
469
+ ),
470
+ ),
471
+ );
472
+
473
+ const actual = rows
474
+ .map((row: any) => ({
475
+ id: row[credential.credentialId],
476
+ revision: row[credential.revision],
477
+ active:
478
+ credential.status === undefined ||
479
+ credential.isActiveStatus?.(row[credential.status]) === true,
480
+ }))
481
+ .sort((a: any, b: any) => String(a.id).localeCompare(String(b.id)));
482
+
483
+ credentialsCurrent =
484
+ actual.length === expected.length &&
485
+ actual.every(
486
+ (row: any, index: number) =>
487
+ row.active &&
488
+ row.id === expected[index]?.credentialId &&
489
+ row.revision === expected[index]?.revision,
490
+ );
491
+ for (const expectedCredential of expected)
492
+ parts.push(
493
+ sql`exists(select 1 from ${credential.table} where ${owner} = ${sql.param(nativeSubjectId, owner)} and ${id} = ${sql.param(expectedCredential.credentialId, id)} and ${revision} = ${sql.param(expectedCredential.revision, revision)}${status === undefined ? sql`` : sql` and ${status} = ${sql.param(credential.d1ActiveStatusValue, status)}`})`,
494
+ );
495
+ }
496
+
497
+ return {
498
+ current: subjectCurrent && identifierCurrent && credentialsCurrent,
499
+ condition: balancedD1And(...parts) ?? sql`1 = 1`,
500
+ };
501
+ });
502
+
503
+ const anchorStatements = Effect.fn(function* (
504
+ mapping: Mapping,
505
+ moduleId: string,
506
+ purpose: any,
507
+ action: ProofAction,
508
+ entries: ReadonlyArray<ScopeEntry>,
509
+ seriesKey: string,
510
+ seriesVersion: ProofVersion,
511
+ includeSeries: boolean,
512
+ ) {
513
+ const database = yield* CurrentD1PlanningDatabase;
514
+
515
+ return [
516
+ ...(yield* Effect.forEach(
517
+ entries,
518
+ Effect.fn(function* (entry) {
519
+ return yield* statement(
520
+ database
521
+ .insert(mapping.rateScope.table)
522
+ .values(
523
+ mapping.rateScope.encodeInsert({
524
+ moduleId,
525
+ purpose,
526
+ action,
527
+ scopeKind: entry.kind,
528
+ scopeKey: entry.key,
529
+ }),
530
+ )
531
+ .onConflictDoNothing(),
532
+ );
533
+ }),
534
+ )),
535
+ ...(includeSeries
536
+ ? [
537
+ yield* statement(
538
+ database
539
+ .insert(mapping.series.table)
540
+ .values(
541
+ mapping.series.encodeInsert({
542
+ moduleId,
543
+ purpose,
544
+ scopeKey: seriesKey,
545
+ version: seriesVersion,
546
+ }),
547
+ )
548
+ .onConflictDoNothing(),
549
+ ),
550
+ ]
551
+ : []),
552
+ ];
553
+ });
554
+
555
+ const insertScopeStatements = Effect.fn(function* (
556
+ mapping: Mapping,
557
+ moduleId: string,
558
+ purpose: any,
559
+ action: ProofAction,
560
+ commandId: string,
561
+ entries: ReadonlyArray<ScopeEntry>,
562
+ now: number,
563
+ retentionUntil: number,
564
+ marker: string,
565
+ ) {
566
+ const database = yield* CurrentD1PlanningDatabase;
567
+
568
+ return (yield* Effect.forEach(
569
+ entries,
570
+ Effect.fn(function* (entry) {
571
+ return [
572
+ yield* assertion(scopeCondition(mapping, moduleId, purpose, action, entry), marker),
573
+ yield* statement(
574
+ database.insert(mapping.abuseEvent.table).values(
575
+ driverValues(
576
+ mapping.abuseEvent.encodeInsert({
577
+ moduleId,
578
+ purpose,
579
+ action,
580
+ scopeKind: entry.kind,
581
+ scopeKey: entry.key,
582
+ commandId,
583
+ occurredAtMillis: now,
584
+ retentionUntilMillis: retentionUntil,
585
+ }),
586
+ [
587
+ [mapping.abuseEvent.occurredAt, mapping.d1.engineNow],
588
+ [
589
+ mapping.abuseEvent.retentionUntil,
590
+ mapping.d1.engineInstantPlus(retentionUntil - now),
591
+ ],
592
+ ],
593
+ ),
594
+ ),
595
+ ),
596
+ ];
597
+ }),
598
+ )).flat();
599
+ });
600
+
601
+ const readSeries = Effect.fn("Drizzle.readSeries")(function* (
602
+ mapping: Mapping,
603
+ moduleId: string,
604
+ purpose: any,
605
+ key: string,
606
+ ) {
607
+ const database = yield* CurrentD1PlanningDatabase;
608
+
609
+ const c = seriesColumns(mapping);
610
+
611
+ return yield* database
612
+ .select()
613
+ .from(mapping.series.table)
614
+ .where(and(eq(c.moduleId, moduleId), eq(c.purpose, purpose), eq(c.scopeKey, key)))
615
+ .limit(1);
616
+ });
617
+
618
+ const readGeneration = Effect.fn("Drizzle.readGeneration")(function* (
619
+ mapping: Mapping,
620
+ moduleId: string,
621
+ proofId: string,
622
+ ) {
623
+ const database = yield* CurrentD1PlanningDatabase;
624
+
625
+ const c = generationColumns(mapping);
626
+
627
+ return yield* database
628
+ .select()
629
+ .from(mapping.generation.table)
630
+ .where(and(eq(c.moduleId, moduleId), eq(c.proofId, proofId)))
631
+ .limit(1);
632
+ });
633
+
634
+ const commandInsert = Effect.fn(function* (
635
+ mapping: Mapping,
636
+ moduleId: string,
637
+ commandId: string,
638
+ kind: "attempt" | "complete",
639
+ decision: ProofCommandDecision,
640
+ retentionUntil: number,
641
+ nativeRetention?: SQL,
642
+ ) {
643
+ const database = yield* CurrentD1PlanningDatabase;
644
+
645
+ return yield* statement(
646
+ database.insert(mapping.command.table).values(
647
+ driverValues(
648
+ mapping.command.encodeInsert({
649
+ moduleId,
650
+ commandId,
651
+ kind,
652
+ decision,
653
+ retentionUntilMillis: retentionUntil,
654
+ }),
655
+ nativeRetention === undefined ? [] : [[mapping.command.retentionUntil, nativeRetention]],
656
+ ),
657
+ ),
658
+ );
659
+ });
660
+
661
+ const issuePlan = Effect.fn("Drizzle.issuePlan")(function* <A>(
662
+ mapping: Mapping,
663
+ input: Parameters<ProofPersistence["Service"]["issue"]>[0],
664
+ prepare: PlanPrepare<ProofPersistence["Service"]["issue"], A>,
665
+ ) {
666
+ const database = yield* CurrentD1PlanningDatabase;
667
+ const journal = yield* CurrentCommitJournal;
668
+
669
+ const keys = mapping.scopeKeys({
670
+ moduleId: input.record.moduleId,
671
+ purpose: input.record.purpose,
672
+ binding: input.record.binding,
673
+ });
674
+
675
+ const current = yield* authority(
676
+ mapping,
677
+ input.record.moduleId,
678
+ input.record.purpose,
679
+ input.record.binding,
680
+ );
681
+
682
+ const now = yield* readEngineNowMillis(mapping);
683
+ const retentionUntil = now + input.policy.requestRetentionMillis;
684
+ const rc = requestColumns(mapping);
685
+
686
+ const existingRequest = (yield* database
687
+ .select()
688
+ .from(mapping.request.table)
689
+ .where(and(eq(rc.moduleId, input.record.moduleId), eq(rc.requestId, input.record.requestId)))
690
+ .limit(1))[0];
691
+
692
+ if (existingRequest !== undefined) {
693
+ const retained = yield* mapping.decodeInstant(existingRequest[mapping.request.retentionUntil]);
694
+
695
+ if (retained > now) {
696
+ if (existingRequest[mapping.request.fingerprint] !== input.record.fingerprint)
697
+ return yield* conflict();
698
+ const receipt = yield* mapping.request.decodeReceipt(existingRequest);
699
+
700
+ return {
701
+ receipt: prepare({ _tag: "Existing", receipt }, journal) as PreparedCommit<A>,
702
+ statements: [],
703
+ };
704
+ }
705
+ }
706
+ const scopes = scopeEntries(keys, input.record.binding, "issue", input.policy);
707
+
708
+ const initiallyAdmitted = yield* readScopeAdmission(
709
+ mapping,
710
+ input.record.moduleId,
711
+ input.record.purpose,
712
+ "issue",
713
+ scopes,
714
+ now,
715
+ );
716
+
717
+ const actionOpen = initiallyAdmitted.some((entry) => entry.kind === "action");
718
+ const admitted = actionOpen ? initiallyAdmitted : [];
719
+
720
+ const existingSeries = actionOpen
721
+ ? (yield* readSeries(mapping, input.record.moduleId, input.record.purpose, keys.series))[0]
722
+ : undefined;
723
+
724
+ const seriesVersion = yield* allocateVersion(mapping);
725
+ const active = existingSeries?.[mapping.series.activeProofId] as string | null | undefined;
726
+
727
+ const lastIssue =
728
+ existingSeries?.[mapping.series.lastIssueAt] === null ||
729
+ existingSeries?.[mapping.series.lastIssueAt] === undefined
730
+ ? undefined
731
+ : yield* mapping.decodeInstant(existingSeries[mapping.series.lastIssueAt]);
732
+
733
+ const allowed =
734
+ current.current &&
735
+ input.eligible &&
736
+ admitted.length === scopes.length &&
737
+ input.record.issuedAtMillis <= now &&
738
+ input.record.expiresAtMillis > now &&
739
+ (input.supersedes === undefined || input.supersedes === active) &&
740
+ (lastIssue === undefined || now - lastIssue >= input.policy.abuse.resendCooldownMillis);
741
+
742
+ const receipt = {
743
+ requestId: input.record.requestId,
744
+ reference: {
745
+ proofId: input.record.proofId,
746
+ purpose: input.record.purpose,
747
+ keyId: input.record.verifier.keyId,
748
+ },
749
+ };
750
+
751
+ const prepared = prepare(
752
+ allowed ? { _tag: "Issued", record: input.record } : { _tag: "Suppressed", receipt },
753
+ journal,
754
+ );
755
+
756
+ const statements: Statement<any>[] = [];
757
+ const marker = `effect-auth-proof-guard:issue:${input.record.requestId}`;
758
+
759
+ if (existingRequest !== undefined)
760
+ statements.push(
761
+ yield* statement(
762
+ database
763
+ .delete(mapping.request.table)
764
+ .where(
765
+ and(
766
+ eq(rc.moduleId, input.record.moduleId),
767
+ eq(rc.requestId, input.record.requestId),
768
+ lte(rc.retentionUntil, mapping.d1.engineNow),
769
+ ),
770
+ ),
771
+ ),
772
+ );
773
+ statements.push(
774
+ yield* statement(
775
+ database.insert(mapping.request.table).values(
776
+ driverValues(
777
+ mapping.request.encodeInsert({
778
+ record: input.record,
779
+ createdAtMillis: now,
780
+ retentionUntilMillis: retentionUntil,
781
+ }),
782
+ [
783
+ [mapping.request.createdAt, mapping.d1.engineNow],
784
+ [
785
+ mapping.request.retentionUntil,
786
+ mapping.d1.engineInstantPlus(input.policy.requestRetentionMillis),
787
+ ],
788
+ ],
789
+ ),
790
+ ),
791
+ ),
792
+ ...(yield* anchorStatements(
793
+ mapping,
794
+ input.record.moduleId,
795
+ input.record.purpose,
796
+ "issue",
797
+ actionOpen ? scopes : scopes.slice(0, 1),
798
+ keys.series,
799
+ seriesVersion,
800
+ actionOpen,
801
+ )),
802
+ ...(yield* insertScopeStatements(
803
+ mapping,
804
+ input.record.moduleId,
805
+ input.record.purpose,
806
+ "issue",
807
+ input.record.requestId,
808
+ admitted,
809
+ now,
810
+ retentionUntil,
811
+ marker,
812
+ )),
813
+ );
814
+ if (allowed) {
815
+ const sc = seriesColumns(mapping);
816
+
817
+ const seriesCondition = and(
818
+ eq(sc.moduleId, input.record.moduleId),
819
+ eq(sc.purpose, input.record.purpose),
820
+ eq(sc.scopeKey, keys.series),
821
+ active === null || active === undefined
822
+ ? or(eq(sc.activeProofId, null), sql`${sc.activeProofId} is null`)
823
+ : eq(sc.activeProofId, active),
824
+ lastIssue === undefined
825
+ ? sql`1 = 1`
826
+ : lte(
827
+ sc.lastIssueAt,
828
+ mapping.d1.engineInstantMinus(input.policy.abuse.resendCooldownMillis),
829
+ ),
830
+ );
831
+
832
+ statements.push(
833
+ yield* assertion(
834
+ and(
835
+ current.condition,
836
+ sql`${mapping.d1.engineNowMillis} >= ${input.record.issuedAtMillis}`,
837
+ sql`${mapping.d1.engineNow} < ${sql.param(mapping.encodeInstant(input.record.expiresAtMillis), generationColumns(mapping).expiresAt)}`,
838
+ sql`exists(select 1 from ${mapping.series.table} where ${seriesCondition})`,
839
+ )!,
840
+ marker,
841
+ ),
842
+ );
843
+ if (active !== null && active !== undefined)
844
+ statements.push(
845
+ yield* statement(
846
+ database
847
+ .update(mapping.generation.table)
848
+ .set(updateValues([[mapping.generation.state, "superseded"]]))
849
+ .where(
850
+ and(
851
+ eq(generationColumns(mapping).moduleId, input.record.moduleId),
852
+ eq(generationColumns(mapping).proofId, active),
853
+ eq(generationColumns(mapping).state, "active"),
854
+ ),
855
+ ),
856
+ ),
857
+ );
858
+ statements.push(
859
+ yield* statement(
860
+ database.insert(mapping.generation.table).values(
861
+ driverValues(
862
+ mapping.generation.encodeInsert({
863
+ record: input.record,
864
+ seriesKey: keys.series,
865
+ retentionUntilMillis: retentionUntil,
866
+ state: "active",
867
+ deliveryState: "new",
868
+ policy: input.policy,
869
+ }),
870
+ [
871
+ [
872
+ mapping.generation.retentionUntil,
873
+ mapping.d1.engineInstantPlus(input.policy.requestRetentionMillis),
874
+ ],
875
+ ],
876
+ ),
877
+ ),
878
+ ),
879
+ yield* statement(
880
+ database
881
+ .update(mapping.series.table)
882
+ .set(
883
+ updateValues([
884
+ [mapping.series.activeProofId, input.record.proofId],
885
+ [mapping.series.lastIssueAt, mapping.d1.engineNow],
886
+ [mapping.series.version, seriesVersion],
887
+ ]),
888
+ )
889
+ .where(
890
+ and(
891
+ eq(sc.moduleId, input.record.moduleId),
892
+ eq(sc.purpose, input.record.purpose),
893
+ eq(sc.scopeKey, keys.series),
894
+ ),
895
+ ),
896
+ ),
897
+ );
898
+ }
899
+
900
+ return {
901
+ receipt: prepared as PreparedCommit<A>,
902
+ statements,
903
+ retryable: (cause: unknown) =>
904
+ isMappedConstraintConflict(mapping.isRequestConflict, cause) ||
905
+ isMappedConstraintConflict(mapping.isSeriesConflict, cause) ||
906
+ isGuardFailure(cause, marker),
907
+ };
908
+ });
909
+
910
+ const attemptPlan = Effect.fn("Drizzle.attemptPlan")(function* <A>(
911
+ mapping: Mapping,
912
+ input: Parameters<ProofPersistence["Service"]["attempt"]>[0],
913
+ prepare: PlanPrepare<ProofPersistence["Service"]["attempt"], A>,
914
+ ) {
915
+ const database = yield* CurrentD1PlanningDatabase;
916
+ const journal = yield* CurrentCommitJournal;
917
+
918
+ const keys = mapping.scopeKeys({
919
+ moduleId: input.moduleId,
920
+ purpose: input.purpose,
921
+ binding: input.binding,
922
+ });
923
+
924
+ const current = yield* authority(mapping, input.moduleId, input.purpose, input.binding);
925
+ const command = commandColumns(mapping);
926
+
927
+ const existingCommand = (yield* database
928
+ .select()
929
+ .from(mapping.command.table)
930
+ .where(and(eq(command.moduleId, input.moduleId), eq(command.commandId, input.continuationId)))
931
+ .limit(1))[0];
932
+
933
+ if (existingCommand !== undefined) {
934
+ if (existingCommand[mapping.command.decision] === "rejected")
935
+ return {
936
+ receipt: prepare({ _tag: "Rejected" }, journal) as PreparedCommit<A>,
937
+ statements: [],
938
+ };
939
+
940
+ return yield* unavailable();
941
+ }
942
+ const now = yield* readEngineNowMillis(mapping);
943
+ const scopes = scopeEntries(keys, input.binding, "attempt", input.policy);
944
+
945
+ const initiallyAdmitted = yield* readScopeAdmission(
946
+ mapping,
947
+ input.moduleId,
948
+ input.purpose,
949
+ "attempt",
950
+ scopes,
951
+ now,
952
+ );
953
+
954
+ const actionOpen = initiallyAdmitted.some((entry) => entry.kind === "action");
955
+ const admitted = actionOpen ? initiallyAdmitted : [];
956
+
957
+ const series = actionOpen
958
+ ? (yield* readSeries(mapping, input.moduleId, input.purpose, keys.series))[0]
959
+ : undefined;
960
+
961
+ const generation = (yield* readGeneration(mapping, input.moduleId, input.proofId))[0];
962
+ const fc = failureColumns(mapping);
963
+
964
+ const failureRows = yield* database
965
+ .select({ total: count() })
966
+ .from(mapping.failureEvent.table)
967
+ .where(
968
+ and(
969
+ eq(fc.moduleId, input.moduleId),
970
+ eq(fc.purpose, input.purpose),
971
+ eq(fc.seriesKey, keys.series),
972
+ gte(fc.occurredAt, mapping.encodeInstant(now - input.policy.abuse.attempts.windowMillis)),
973
+ ),
974
+ );
975
+
976
+ const failures = Number(failureRows[0]?.total ?? 0);
977
+
978
+ const storedBinding =
979
+ generation === undefined ? undefined : yield* mapping.generation.decodeBinding(generation);
980
+
981
+ const expires =
982
+ generation === undefined
983
+ ? undefined
984
+ : yield* mapping.decodeInstant(generation[mapping.generation.expiresAt]);
985
+
986
+ const currentGeneration =
987
+ generation !== undefined &&
988
+ generation[mapping.generation.purpose] === input.purpose &&
989
+ generation[mapping.generation.state] === "active" &&
990
+ series?.[mapping.series.activeProofId] === input.proofId &&
991
+ storedBinding !== undefined &&
992
+ sameBinding(storedBinding, input.binding) &&
993
+ expires !== undefined &&
994
+ expires > now;
995
+
996
+ const candidateMatches =
997
+ generation !== undefined &&
998
+ input.candidate !== undefined &&
999
+ generation[mapping.generation.verifierKeyId] === input.candidate.keyId &&
1000
+ generation[mapping.generation.verifierDigest] === input.candidate.digest;
1001
+
1002
+ const accepted =
1003
+ current.current &&
1004
+ currentGeneration &&
1005
+ candidateMatches &&
1006
+ admitted.length === scopes.length &&
1007
+ failures < input.policy.maximumFailedAttempts;
1008
+
1009
+ const retentionUntil = now + input.policy.requestRetentionMillis;
1010
+ const seriesVersion = yield* allocateVersion(mapping);
1011
+
1012
+ const statements: Statement<any>[] = [
1013
+ ...(yield* anchorStatements(
1014
+ mapping,
1015
+ input.moduleId,
1016
+ input.purpose,
1017
+ "attempt",
1018
+ actionOpen ? scopes : scopes.slice(0, 1),
1019
+ keys.series,
1020
+ seriesVersion,
1021
+ actionOpen,
1022
+ )),
1023
+ ...(yield* insertScopeStatements(
1024
+ mapping,
1025
+ input.moduleId,
1026
+ input.purpose,
1027
+ "attempt",
1028
+ input.continuationId,
1029
+ admitted,
1030
+ now,
1031
+ retentionUntil,
1032
+ `effect-auth-proof-guard:attempt:${input.continuationId}`,
1033
+ )),
1034
+ ];
1035
+
1036
+ const marker = `effect-auth-proof-guard:attempt:${input.continuationId}`;
1037
+
1038
+ if (!accepted) {
1039
+ const prepared = prepare({ _tag: "Rejected" }, journal) as PreparedCommit<A>;
1040
+
1041
+ if (
1042
+ admitted.length === scopes.length &&
1043
+ current.current &&
1044
+ currentGeneration &&
1045
+ !candidateMatches &&
1046
+ failures < input.policy.maximumFailedAttempts
1047
+ ) {
1048
+ const gc = generationColumns(mapping);
1049
+ const sc = seriesColumns(mapping);
1050
+
1051
+ statements.push(
1052
+ yield* assertion(
1053
+ and(
1054
+ current.condition,
1055
+ sql`exists(select 1 from ${mapping.series.table} where ${sc.moduleId} = ${sql.param(input.moduleId, sc.moduleId)} and ${sc.purpose} = ${sql.param(input.purpose, sc.purpose)} and ${sc.scopeKey} = ${sql.param(keys.series, sc.scopeKey)} and ${sc.activeProofId} = ${sql.param(input.proofId, sc.activeProofId)})`,
1056
+ sql`exists(select 1 from ${mapping.generation.table} where ${gc.moduleId} = ${sql.param(input.moduleId, gc.moduleId)} and ${gc.proofId} = ${sql.param(input.proofId, gc.proofId)} and ${gc.state} = 'active' and ${gc.expiresAt} > ${mapping.d1.engineNow})`,
1057
+ failureCondition(mapping, input.moduleId, input.purpose, keys.series, input.policy),
1058
+ )!,
1059
+ marker,
1060
+ ),
1061
+ yield* statement(
1062
+ database.insert(mapping.failureEvent.table).values(
1063
+ driverValues(
1064
+ mapping.failureEvent.encodeInsert({
1065
+ moduleId: input.moduleId,
1066
+ purpose: input.purpose,
1067
+ seriesKey: keys.series,
1068
+ commandId: input.continuationId,
1069
+ occurredAtMillis: now,
1070
+ retentionUntilMillis: retentionUntil,
1071
+ }),
1072
+ [
1073
+ [mapping.failureEvent.occurredAt, mapping.d1.engineNow],
1074
+ [
1075
+ mapping.failureEvent.retentionUntil,
1076
+ mapping.d1.engineInstantPlus(input.policy.requestRetentionMillis),
1077
+ ],
1078
+ ],
1079
+ ),
1080
+ ),
1081
+ ),
1082
+ );
1083
+ }
1084
+ statements.push(
1085
+ yield* commandInsert(
1086
+ mapping,
1087
+ input.moduleId,
1088
+ input.continuationId,
1089
+ "attempt",
1090
+ "rejected",
1091
+ retentionUntil,
1092
+ mapping.d1.engineInstantPlus(input.policy.requestRetentionMillis),
1093
+ ),
1094
+ );
1095
+
1096
+ return {
1097
+ receipt: prepared,
1098
+ statements,
1099
+ retryable: (cause: unknown) =>
1100
+ isMappedConstraintConflict(mapping.isCommandConflict, cause) ||
1101
+ isMappedConstraintConflict(mapping.isSeriesConflict, cause) ||
1102
+ isGuardFailure(cause, marker),
1103
+ };
1104
+ }
1105
+ const version = yield* allocateVersion(mapping);
1106
+ const continuationExpires = Math.min(expires!, now + input.policy.continuationLifetimeMillis);
1107
+
1108
+ const continuation: ProofContinuationRecord = {
1109
+ moduleId: input.moduleId,
1110
+ purpose: input.purpose,
1111
+ continuationId: input.continuationId,
1112
+ digest: input.continuationDigest,
1113
+ proofId: input.proofId,
1114
+ seriesKey: keys.series,
1115
+ binding: input.binding,
1116
+ expiresAtMillis: continuationExpires,
1117
+ version,
1118
+ };
1119
+
1120
+ const decision: ProofAttemptDecision = {
1121
+ _tag: "Accepted",
1122
+ continuation: {
1123
+ continuationId: input.continuationId,
1124
+ purpose: input.purpose,
1125
+ expiresAtMillis: continuationExpires,
1126
+ },
1127
+ };
1128
+
1129
+ const prepared = prepare(decision, journal) as PreparedCommit<A>;
1130
+ const gc = generationColumns(mapping);
1131
+ const sc = seriesColumns(mapping);
1132
+
1133
+ statements.push(
1134
+ yield* assertion(
1135
+ and(
1136
+ current.condition,
1137
+ failureCondition(mapping, input.moduleId, input.purpose, keys.series, input.policy),
1138
+ sql`exists(select 1 from ${mapping.series.table} where ${sc.moduleId} = ${sql.param(input.moduleId, sc.moduleId)} and ${sc.purpose} = ${sql.param(input.purpose, sc.purpose)} and ${sc.scopeKey} = ${sql.param(keys.series, sc.scopeKey)} and ${sc.activeProofId} = ${sql.param(input.proofId, sc.activeProofId)})`,
1139
+ sql`exists(select 1 from ${mapping.generation.table} where ${gc.moduleId} = ${sql.param(input.moduleId, gc.moduleId)} and ${gc.proofId} = ${sql.param(input.proofId, gc.proofId)} and ${gc.purpose} = ${sql.param(input.purpose, gc.purpose)} and ${gc.state} = 'active' and ${gc.verifierKeyId} = ${sql.param(input.candidate!.keyId, gc.verifierKeyId)} and ${gc.verifierDigest} = ${sql.param(input.candidate!.digest, gc.verifierDigest)} and ${gc.expiresAt} > ${mapping.d1.engineNow})`,
1140
+ )!,
1141
+ marker,
1142
+ ),
1143
+ yield* commandInsert(
1144
+ mapping,
1145
+ input.moduleId,
1146
+ input.continuationId,
1147
+ "attempt",
1148
+ "accepted",
1149
+ retentionUntil,
1150
+ mapping.d1.engineInstantPlus(input.policy.requestRetentionMillis),
1151
+ ),
1152
+ yield* statement(
1153
+ database
1154
+ .update(mapping.generation.table)
1155
+ .set(updateValues([[mapping.generation.state, "consumed"]]))
1156
+ .where(
1157
+ and(
1158
+ eq(gc.moduleId, input.moduleId),
1159
+ eq(gc.proofId, input.proofId),
1160
+ eq(gc.state, "active"),
1161
+ ),
1162
+ ),
1163
+ ),
1164
+ yield* statement(
1165
+ database.insert(mapping.continuation.table).values(
1166
+ driverValues(
1167
+ mapping.continuation.encodeInsert({
1168
+ ...continuation,
1169
+ retentionUntilMillis: retentionUntil,
1170
+ }),
1171
+ [
1172
+ [
1173
+ mapping.continuation.retentionUntil,
1174
+ mapping.d1.engineInstantPlus(input.policy.requestRetentionMillis),
1175
+ ],
1176
+ ],
1177
+ ),
1178
+ ),
1179
+ ),
1180
+ );
1181
+
1182
+ return {
1183
+ receipt: prepared,
1184
+ statements,
1185
+ retryable: (cause: unknown) =>
1186
+ isMappedConstraintConflict(mapping.isCommandConflict, cause) ||
1187
+ isMappedConstraintConflict(mapping.isSeriesConflict, cause) ||
1188
+ isGuardFailure(cause, marker),
1189
+ };
1190
+ });
1191
+
1192
+ const inspectD1Completion = Effect.fn("DrizzleD1Proof.inspectCompletion")(function* (
1193
+ mapping: Mapping,
1194
+ input: ProofCompletionPlan["input"],
1195
+ ) {
1196
+ const database = yield* CurrentD1PlanningDatabase;
1197
+
1198
+ const keys = mapping.scopeKeys({
1199
+ moduleId: input.moduleId,
1200
+ purpose: input.purpose,
1201
+ binding: input.binding,
1202
+ });
1203
+
1204
+ const current = yield* authority(mapping, input.moduleId, input.purpose, input.binding);
1205
+ const c = continuationColumns(mapping);
1206
+
1207
+ const row = (yield* database
1208
+ .select()
1209
+ .from(mapping.continuation.table)
1210
+ .where(and(eq(c.moduleId, input.moduleId), eq(c.continuationId, input.continuationId)))
1211
+ .limit(1))[0];
1212
+
1213
+ const now = yield* readEngineNowMillis(mapping);
1214
+ const record = row === undefined ? undefined : yield* mapping.continuation.decode(row);
1215
+
1216
+ const accepted =
1217
+ current.current &&
1218
+ record !== undefined &&
1219
+ record.moduleId === input.moduleId &&
1220
+ record.continuationId === input.continuationId &&
1221
+ record.purpose === input.purpose &&
1222
+ record.digest === input.continuationDigest &&
1223
+ record.seriesKey === keys.series &&
1224
+ sameBinding(record.binding, input.binding) &&
1225
+ row[mapping.continuation.consumed] === false &&
1226
+ record.expiresAtMillis > now;
1227
+
1228
+ const immutable = [
1229
+ mapping.continuation.moduleId,
1230
+ mapping.continuation.purpose,
1231
+ mapping.continuation.continuationId,
1232
+ mapping.continuation.digest,
1233
+ mapping.continuation.proofId,
1234
+ mapping.continuation.seriesKey,
1235
+ mapping.continuation.binding,
1236
+ mapping.continuation.expiresAt,
1237
+ mapping.continuation.version,
1238
+ mapping.continuation.retentionUntil,
1239
+ ];
1240
+
1241
+ const exact =
1242
+ row === undefined
1243
+ ? sql`false`
1244
+ : and(...immutable.map((key) => eq(column(mapping.continuation.table, key), row[key])))!;
1245
+
1246
+ return {
1247
+ accepted,
1248
+ record,
1249
+ row,
1250
+ columns: c,
1251
+ condition: and(
1252
+ current.condition,
1253
+ sql`exists(select 1 from ${mapping.continuation.table} where ${exact} and ${c.consumed} = ${sql.param(false, c.consumed)} and ${column(mapping.continuation.table, mapping.continuation.expiresAt)} > ${mapping.d1.engineNow})`,
1254
+ )!,
1255
+ appliedCondition:
1256
+ row === undefined
1257
+ ? sql`false`
1258
+ : sql`exists(select 1 from ${mapping.continuation.table} where ${exact} and ${c.consumed} = ${sql.param(true, c.consumed)} and ${column(mapping.continuation.table, mapping.continuation.expiresAt)} > ${mapping.d1.engineNow})`,
1259
+ };
1260
+ });
1261
+
1262
+ /** Read-only preflight plus its exact final-engine-time batch predicate. */
1263
+ export const checkD1ProofCompletion = Effect.fn("Drizzle.checkD1ProofCompletion")(function* (
1264
+ mapping: Mapping,
1265
+ input: ProofCompletionPlan["input"],
1266
+ ) {
1267
+ return yield* inspectD1Completion(mapping, input);
1268
+ });
1269
+
1270
+ const completionPlan = Effect.fn("Drizzle.completionPlan")(function* <A>(
1271
+ mapping: Mapping,
1272
+ input: Parameters<ProofPersistence["Service"]["complete"]>[0],
1273
+ prepare: PrepareProofCommit<ProofCompletionDecision, A>,
1274
+ ) {
1275
+ const database = yield* CurrentD1PlanningDatabase;
1276
+ const journal = yield* CurrentCommitJournal;
1277
+
1278
+ const inspected = yield* inspectD1Completion(mapping, input);
1279
+ const { accepted, record, columns: c } = inspected;
1280
+ const decision: ProofCompletionDecision = accepted ? "completed" : "rejected";
1281
+ const receipt = prepare(decision, journal) as PreparedCommit<A>;
1282
+
1283
+ if (!accepted) return { receipt, statements: [] };
1284
+
1285
+ const postconditions = [
1286
+ yield* assertion(
1287
+ and(
1288
+ inspected.appliedCondition,
1289
+ sql`exists(select 1 from ${mapping.command.table} where ${column(mapping.command.table, mapping.command.moduleId)} = ${sql.param(input.moduleId, column(mapping.command.table, mapping.command.moduleId))} and ${column(mapping.command.table, mapping.command.commandId)} = ${sql.param(input.continuationDigest, column(mapping.command.table, mapping.command.commandId))} and ${column(mapping.command.table, mapping.command.kind)} = ${sql.param("complete", column(mapping.command.table, mapping.command.kind))} and ${column(mapping.command.table, mapping.command.decision)} = ${sql.param("completed", column(mapping.command.table, mapping.command.decision))} and ${column(mapping.command.table, mapping.command.retentionUntil)} = ${sql.param(mapping.encodeInstant(record!.expiresAtMillis), column(mapping.command.table, mapping.command.retentionUntil))})`,
1290
+ )!,
1291
+ `effect-auth-proof-guard:complete:${input.continuationId}`,
1292
+ ),
1293
+ ];
1294
+
1295
+ const statements = [
1296
+ yield* assertion(
1297
+ inspected.condition,
1298
+ `effect-auth-proof-guard:complete:${input.continuationId}`,
1299
+ ),
1300
+ yield* statement(
1301
+ database
1302
+ .update(mapping.continuation.table)
1303
+ .set(updateValues([[mapping.continuation.consumed, true]]))
1304
+ .where(
1305
+ and(
1306
+ eq(c.moduleId, input.moduleId),
1307
+ eq(c.continuationId, input.continuationId),
1308
+ eq(c.digest, input.continuationDigest),
1309
+ eq(c.consumed, false),
1310
+ ),
1311
+ ),
1312
+ ),
1313
+ yield* commandInsert(
1314
+ mapping,
1315
+ input.moduleId,
1316
+ input.continuationDigest,
1317
+ "complete",
1318
+ "completed",
1319
+ record!.expiresAtMillis,
1320
+ ),
1321
+ ...postconditions,
1322
+ ];
1323
+
1324
+ return {
1325
+ receipt,
1326
+ statements,
1327
+ postconditions,
1328
+ retryable: (cause: unknown) =>
1329
+ isMappedConstraintConflict(mapping.isCommandConflict, cause) ||
1330
+ isGuardFailure(cause, `effect-auth-proof-guard:complete:${input.continuationId}`),
1331
+ };
1332
+ });
1333
+
1334
+ const makeProofPlans = (mapping: Mapping) => {
1335
+ const run = <A, E, R>(plan: Effect.Effect<Planned<A>, E, R>) =>
1336
+ Effect.gen(function* () {
1337
+ if (!validConstraints(mapping)) return yield* unavailable();
1338
+
1339
+ return yield* plan;
1340
+ });
1341
+
1342
+ return {
1343
+ issue: <A>(
1344
+ input: Parameters<ProofPersistence["Service"]["issue"]>[0],
1345
+ prepare: PlanPrepare<ProofPersistence["Service"]["issue"], A>,
1346
+ ) =>
1347
+ run(
1348
+ Effect.gen(function* () {
1349
+ return yield* issuePlan(mapping, input, prepare);
1350
+ }),
1351
+ ),
1352
+ attempt: <A>(
1353
+ input: Parameters<ProofPersistence["Service"]["attempt"]>[0],
1354
+ prepare: PlanPrepare<ProofPersistence["Service"]["attempt"], A>,
1355
+ ) =>
1356
+ run(
1357
+ Effect.gen(function* () {
1358
+ return yield* attemptPlan(mapping, input, prepare);
1359
+ }),
1360
+ ),
1361
+ complete: <A>(
1362
+ input: Parameters<ProofPersistence["Service"]["complete"]>[0],
1363
+ prepare: PlanPrepare<ProofPersistence["Service"]["complete"], A>,
1364
+ ) =>
1365
+ run(
1366
+ Effect.gen(function* () {
1367
+ return yield* completionPlan(mapping, input, prepare);
1368
+ }),
1369
+ ),
1370
+ claimDelivery: <A>(
1371
+ input: Parameters<ProofPersistence["Service"]["claimDelivery"]>[0],
1372
+ prepare: PlanPrepare<ProofPersistence["Service"]["claimDelivery"], A>,
1373
+ ) =>
1374
+ Effect.gen(function* () {
1375
+ const database = yield* CurrentD1PlanningDatabase;
1376
+
1377
+ return yield* run(
1378
+ Effect.gen(function* () {
1379
+ const journal = yield* CurrentCommitJournal;
1380
+
1381
+ const row = (yield* readGeneration(mapping, input.moduleId, input.proofId))[0];
1382
+ const now = yield* readEngineNowMillis(mapping);
1383
+ const c = generationColumns(mapping);
1384
+
1385
+ if (row === undefined)
1386
+ return { receipt: prepare({ _tag: "Declined" }, journal), statements: [] };
1387
+ const expires = yield* mapping.decodeInstant(row[mapping.generation.expiresAt]);
1388
+
1389
+ const claimDeadline =
1390
+ row[mapping.generation.claimDeadline] === null ||
1391
+ row[mapping.generation.claimDeadline] === undefined
1392
+ ? undefined
1393
+ : yield* mapping.decodeInstant(row[mapping.generation.claimDeadline]);
1394
+
1395
+ const retryAt =
1396
+ row[mapping.generation.retryAt] === null ||
1397
+ row[mapping.generation.retryAt] === undefined
1398
+ ? undefined
1399
+ : yield* mapping.decodeInstant(row[mapping.generation.retryAt]);
1400
+
1401
+ const state = row[mapping.generation.deliveryState] as string;
1402
+
1403
+ const expiredClaim =
1404
+ state === "claimed" && claimDeadline !== undefined && claimDeadline <= now;
1405
+
1406
+ const effectiveState = expiredClaim ? "ambiguous" : state;
1407
+
1408
+ const canClaim =
1409
+ row[mapping.generation.version] === input.version &&
1410
+ row[mapping.generation.deliveryId] === input.deliveryId &&
1411
+ row[mapping.generation.state] === "active" &&
1412
+ expires > now &&
1413
+ Number(row[mapping.generation.sendCount]) < input.policy.maximumDeliveryAttempts &&
1414
+ (effectiveState === "new" ||
1415
+ (effectiveState === "ambiguous" &&
1416
+ input.allowAmbiguousRetry &&
1417
+ (retryAt === undefined || retryAt <= now)));
1418
+
1419
+ if (!canClaim) {
1420
+ const statements = expiredClaim
1421
+ ? [
1422
+ yield* statement(
1423
+ database
1424
+ .update(mapping.generation.table)
1425
+ .set(updateValues([[mapping.generation.deliveryState, "ambiguous"]]))
1426
+ .where(
1427
+ and(
1428
+ eq(c.moduleId, input.moduleId),
1429
+ eq(c.proofId, input.proofId),
1430
+ eq(c.deliveryState, "claimed"),
1431
+ lte(c.claimDeadline, mapping.d1.engineNow),
1432
+ ),
1433
+ ),
1434
+ ),
1435
+ ]
1436
+ : [];
1437
+
1438
+ return { receipt: prepare({ _tag: "Declined" }, journal), statements };
1439
+ }
1440
+ const claimVersion = yield* allocateVersion(mapping);
1441
+ const decision: ProofDeliveryClaim = { _tag: "Claimed", claimVersion };
1442
+
1443
+ const condition = and(
1444
+ eq(c.moduleId, input.moduleId),
1445
+ eq(c.proofId, input.proofId),
1446
+ eq(c.version, input.version),
1447
+ eq(c.deliveryId, input.deliveryId),
1448
+ eq(c.state, "active"),
1449
+ sql`${c.expiresAt} > ${mapping.d1.engineNow}`,
1450
+ sql`${c.sendCount} < ${input.policy.maximumDeliveryAttempts}`,
1451
+ effectiveState === "new"
1452
+ ? eq(c.deliveryState, "new")
1453
+ : and(
1454
+ eq(c.deliveryState, "ambiguous"),
1455
+ or(sql`${c.retryAt} is null`, lte(c.retryAt, mapping.d1.engineNow)),
1456
+ ),
1457
+ )!;
1458
+
1459
+ return {
1460
+ receipt: prepare(decision, journal),
1461
+ statements: [
1462
+ yield* assertion(
1463
+ sql`exists(select 1 from ${mapping.generation.table} where ${condition})`,
1464
+ `effect-auth-proof-guard:claim:${input.proofId}`,
1465
+ ),
1466
+ yield* statement(
1467
+ database
1468
+ .update(mapping.generation.table)
1469
+ .set(
1470
+ updateValues([
1471
+ [
1472
+ mapping.generation.sendCount,
1473
+ Number(row[mapping.generation.sendCount]) + 1,
1474
+ ],
1475
+ [mapping.generation.deliveryState, "claimed"],
1476
+ [mapping.generation.claimVersion, claimVersion],
1477
+ [
1478
+ mapping.generation.claimDeadline,
1479
+ mapping.d1.engineInstantPlus(input.policy.deliveryClaimMillis),
1480
+ ],
1481
+ [
1482
+ mapping.generation.retryAt,
1483
+ mapping.d1.engineInstantPlus(input.policy.deliveryRetryMillis),
1484
+ ],
1485
+ ]),
1486
+ )
1487
+ .where(condition),
1488
+ ),
1489
+ ],
1490
+ retryable: (cause: unknown) =>
1491
+ isGuardFailure(cause, `effect-auth-proof-guard:claim:${input.proofId}`),
1492
+ };
1493
+ }),
1494
+ );
1495
+ }),
1496
+ settleDelivery: <A>(
1497
+ input: Parameters<ProofPersistence["Service"]["settleDelivery"]>[0],
1498
+ prepare: PlanPrepare<ProofPersistence["Service"]["settleDelivery"], A>,
1499
+ ) =>
1500
+ Effect.gen(function* () {
1501
+ const database = yield* CurrentD1PlanningDatabase;
1502
+
1503
+ return yield* run(
1504
+ Effect.gen(function* () {
1505
+ const journal = yield* CurrentCommitJournal;
1506
+
1507
+ const row = (yield* readGeneration(mapping, input.moduleId, input.proofId))[0];
1508
+ const receipt = prepare(undefined, journal);
1509
+
1510
+ if (
1511
+ row === undefined ||
1512
+ row[mapping.generation.version] !== input.version ||
1513
+ row[mapping.generation.deliveryId] !== input.deliveryId ||
1514
+ row[mapping.generation.claimVersion] !== input.claimVersion ||
1515
+ row[mapping.generation.deliveryState] !== "claimed"
1516
+ )
1517
+ return { receipt, statements: [] };
1518
+ const c = generationColumns(mapping);
1519
+ const outcome: ProofDeliveryOutcome = input.outcome;
1520
+
1521
+ const state =
1522
+ outcome._tag === "Accepted"
1523
+ ? "accepted"
1524
+ : outcome._tag === "DefiniteFailure"
1525
+ ? "failed"
1526
+ : "ambiguous";
1527
+
1528
+ const values: Array<readonly [string, unknown]> = [
1529
+ [mapping.generation.deliveryState, state],
1530
+ [mapping.generation.claimDeadline, null],
1531
+ ];
1532
+
1533
+ if (outcome._tag === "Ambiguous")
1534
+ values.push([
1535
+ mapping.generation.retryAt,
1536
+ mapping.d1.engineInstantPlus(Number(row[mapping.generation.deliveryRetryMillis])),
1537
+ ]);
1538
+ if (outcome._tag === "DefiniteFailure")
1539
+ values.push([mapping.generation.state, "cancelled"]);
1540
+
1541
+ const condition = and(
1542
+ eq(c.moduleId, input.moduleId),
1543
+ eq(c.proofId, input.proofId),
1544
+ eq(c.version, input.version),
1545
+ eq(c.deliveryId, input.deliveryId),
1546
+ eq(c.claimVersion, input.claimVersion),
1547
+ eq(c.deliveryState, "claimed"),
1548
+ );
1549
+
1550
+ const statements: Statement<any>[] = [
1551
+ yield* statement(
1552
+ database
1553
+ .update(mapping.generation.table)
1554
+ .set(updateValues(values))
1555
+ .where(condition),
1556
+ ),
1557
+ ];
1558
+
1559
+ if (outcome._tag === "DefiniteFailure") {
1560
+ const sc = seriesColumns(mapping);
1561
+
1562
+ statements.push(
1563
+ yield* statement(
1564
+ database
1565
+ .update(mapping.series.table)
1566
+ .set(updateValues([[mapping.series.activeProofId, null]]))
1567
+ .where(
1568
+ and(
1569
+ eq(sc.moduleId, input.moduleId),
1570
+ eq(sc.purpose, row[mapping.generation.purpose]),
1571
+ eq(sc.scopeKey, row[mapping.generation.seriesKey]),
1572
+ eq(sc.activeProofId, input.proofId),
1573
+ sql`exists(select 1 from ${mapping.generation.table} where ${c.moduleId} = ${sql.param(input.moduleId, c.moduleId)} and ${c.proofId} = ${sql.param(input.proofId, c.proofId)} and ${c.version} = ${sql.param(input.version, c.version)} and ${c.deliveryId} = ${sql.param(input.deliveryId, c.deliveryId)} and ${c.claimVersion} = ${sql.param(input.claimVersion, c.claimVersion)} and ${c.deliveryState} = 'failed' and ${c.state} = 'cancelled')`,
1574
+ ),
1575
+ ),
1576
+ ),
1577
+ );
1578
+ }
1579
+
1580
+ return { receipt, statements };
1581
+ }),
1582
+ );
1583
+ }),
1584
+ cancel: <A>(
1585
+ input: Parameters<ProofPersistence["Service"]["cancel"]>[0],
1586
+ prepare: PlanPrepare<ProofPersistence["Service"]["cancel"], A>,
1587
+ ) =>
1588
+ Effect.gen(function* () {
1589
+ const database = yield* CurrentD1PlanningDatabase;
1590
+
1591
+ return yield* run(
1592
+ Effect.gen(function* () {
1593
+ const journal = yield* CurrentCommitJournal;
1594
+
1595
+ const keys = mapping.scopeKeys({
1596
+ moduleId: input.moduleId,
1597
+ purpose: input.purpose,
1598
+ binding: input.binding,
1599
+ });
1600
+
1601
+ const current = yield* authority(mapping, input.moduleId, input.purpose, input.binding);
1602
+
1603
+ const series = (yield* readSeries(
1604
+ mapping,
1605
+ input.moduleId,
1606
+ input.purpose,
1607
+ keys.series,
1608
+ ))[0];
1609
+
1610
+ const receipt = prepare(undefined, journal);
1611
+ const active = series?.[mapping.series.activeProofId] as string | null | undefined;
1612
+
1613
+ if (!current.current || active === null || active === undefined)
1614
+ return { receipt, statements: [] };
1615
+ const generation = (yield* readGeneration(mapping, input.moduleId, active))[0];
1616
+
1617
+ const storedBinding =
1618
+ generation === undefined
1619
+ ? undefined
1620
+ : yield* mapping.generation.decodeBinding(generation);
1621
+
1622
+ if (storedBinding === undefined || !sameBinding(storedBinding, input.binding))
1623
+ return { receipt, statements: [] };
1624
+ const gc = generationColumns(mapping);
1625
+ const sc = seriesColumns(mapping);
1626
+ const marker = `effect-auth-proof-guard:cancel:${active}`;
1627
+
1628
+ return {
1629
+ receipt,
1630
+ statements: [
1631
+ yield* assertion(
1632
+ and(
1633
+ current.condition,
1634
+ sql`exists(select 1 from ${mapping.series.table} where ${sc.moduleId} = ${sql.param(input.moduleId, sc.moduleId)} and ${sc.purpose} = ${sql.param(input.purpose, sc.purpose)} and ${sc.scopeKey} = ${sql.param(keys.series, sc.scopeKey)} and ${sc.activeProofId} = ${sql.param(active, sc.activeProofId)})`,
1635
+ sql`exists(select 1 from ${mapping.generation.table} where ${gc.moduleId} = ${sql.param(input.moduleId, gc.moduleId)} and ${gc.proofId} = ${sql.param(active, gc.proofId)} and ${gc.state} = 'active')`,
1636
+ )!,
1637
+ marker,
1638
+ ),
1639
+ yield* statement(
1640
+ database
1641
+ .update(mapping.generation.table)
1642
+ .set(updateValues([[mapping.generation.state, "cancelled"]]))
1643
+ .where(
1644
+ and(
1645
+ eq(gc.moduleId, input.moduleId),
1646
+ eq(gc.proofId, active),
1647
+ eq(gc.state, "active"),
1648
+ ),
1649
+ ),
1650
+ ),
1651
+ yield* statement(
1652
+ database
1653
+ .update(mapping.series.table)
1654
+ .set(updateValues([[mapping.series.activeProofId, null]]))
1655
+ .where(
1656
+ and(
1657
+ eq(sc.moduleId, input.moduleId),
1658
+ eq(sc.purpose, input.purpose),
1659
+ eq(sc.scopeKey, keys.series),
1660
+ eq(sc.activeProofId, active),
1661
+ ),
1662
+ ),
1663
+ ),
1664
+ ],
1665
+ retryable: (cause: unknown) => isGuardFailure(cause, marker),
1666
+ };
1667
+ }),
1668
+ );
1669
+ }),
1670
+ cleanup: <A>(
1671
+ input: Parameters<ProofPersistence["Service"]["cleanup"]>[0],
1672
+ prepare: PlanPrepare<ProofPersistence["Service"]["cleanup"], A>,
1673
+ ) =>
1674
+ Effect.gen(function* () {
1675
+ const database = yield* CurrentD1PlanningDatabase;
1676
+
1677
+ return yield* run(
1678
+ Effect.gen(function* () {
1679
+ const journal = yield* CurrentCommitJournal;
1680
+
1681
+ const now = yield* readEngineNowMillis(mapping);
1682
+ const nativeNow = mapping.encodeInstant(now);
1683
+ const gc = generationColumns(mapping);
1684
+ const cc = continuationColumns(mapping);
1685
+ const rc = requestColumns(mapping);
1686
+ const ac = abuseColumns(mapping);
1687
+ const fc = failureColumns(mapping);
1688
+ const mc = commandColumns(mapping);
1689
+ const sc = seriesColumns(mapping);
1690
+ const rsc = scopeColumns(mapping);
1691
+ let remaining = input.limit;
1692
+ let hasMore = false;
1693
+
1694
+ const take = <A>(effect: Effect.Effect<ReadonlyArray<A>, AdapterFailure>) =>
1695
+ effect.pipe(
1696
+ Effect.map((rows) => {
1697
+ if (rows.length > remaining) hasMore = true;
1698
+ const selected = rows.slice(0, remaining);
1699
+
1700
+ remaining -= selected.length;
1701
+
1702
+ return selected;
1703
+ }),
1704
+ );
1705
+
1706
+ const continuations = yield* take(
1707
+ database
1708
+ .select({ continuationId: cc.continuationId })
1709
+ .from(mapping.continuation.table)
1710
+ .where(and(eq(cc.moduleId, input.moduleId), lte(cc.retentionUntil, nativeNow)))
1711
+ .limit(remaining + 1),
1712
+ );
1713
+
1714
+ const generations = yield* take(
1715
+ database
1716
+ .select({ proofId: gc.proofId })
1717
+ .from(mapping.generation.table)
1718
+ .where(and(eq(gc.moduleId, input.moduleId), lte(gc.retentionUntil, nativeNow)))
1719
+ .limit(remaining + 1),
1720
+ );
1721
+
1722
+ const requests = yield* take(
1723
+ database
1724
+ .select({ requestId: rc.requestId })
1725
+ .from(mapping.request.table)
1726
+ .where(and(eq(rc.moduleId, input.moduleId), lte(rc.retentionUntil, nativeNow)))
1727
+ .limit(remaining + 1),
1728
+ );
1729
+
1730
+ const abuse = yield* take(
1731
+ database
1732
+ .select({
1733
+ action: ac.action,
1734
+ scopeKind: ac.scopeKind,
1735
+ scopeKey: ac.scopeKey,
1736
+ commandId: ac.commandId,
1737
+ })
1738
+ .from(mapping.abuseEvent.table)
1739
+ .where(and(eq(ac.moduleId, input.moduleId), lte(ac.retentionUntil, nativeNow)))
1740
+ .limit(remaining + 1),
1741
+ );
1742
+
1743
+ const failures = yield* take(
1744
+ database
1745
+ .select({ seriesKey: fc.seriesKey, commandId: fc.commandId })
1746
+ .from(mapping.failureEvent.table)
1747
+ .where(and(eq(fc.moduleId, input.moduleId), lte(fc.retentionUntil, nativeNow)))
1748
+ .limit(remaining + 1),
1749
+ );
1750
+
1751
+ const commands = yield* take(
1752
+ database
1753
+ .select({ commandId: mc.commandId })
1754
+ .from(mapping.command.table)
1755
+ .where(and(eq(mc.moduleId, input.moduleId), lte(mc.retentionUntil, nativeNow)))
1756
+ .limit(remaining + 1),
1757
+ );
1758
+
1759
+ const series = yield* take(
1760
+ database
1761
+ .select({ purpose: sc.purpose, scopeKey: sc.scopeKey })
1762
+ .from(mapping.series.table)
1763
+ .where(
1764
+ and(
1765
+ eq(sc.moduleId, input.moduleId),
1766
+ isNull(sc.activeProofId),
1767
+ notExists(
1768
+ database
1769
+ .select({ one: sql`1` })
1770
+ .from(mapping.generation.table)
1771
+ .where(
1772
+ and(
1773
+ eq(gc.moduleId, sc.moduleId),
1774
+ eq(gc.purpose, sc.purpose),
1775
+ eq(gc.seriesKey, sc.scopeKey),
1776
+ ),
1777
+ ),
1778
+ ),
1779
+ notExists(
1780
+ database
1781
+ .select({ one: sql`1` })
1782
+ .from(mapping.failureEvent.table)
1783
+ .where(
1784
+ and(
1785
+ eq(fc.moduleId, sc.moduleId),
1786
+ eq(fc.purpose, sc.purpose),
1787
+ eq(fc.seriesKey, sc.scopeKey),
1788
+ ),
1789
+ ),
1790
+ ),
1791
+ ),
1792
+ )
1793
+ .limit(remaining + 1),
1794
+ );
1795
+
1796
+ const rateScopes = yield* take(
1797
+ database
1798
+ .select({
1799
+ purpose: rsc.purpose,
1800
+ action: rsc.action,
1801
+ scopeKind: rsc.scopeKind,
1802
+ scopeKey: rsc.scopeKey,
1803
+ })
1804
+ .from(mapping.rateScope.table)
1805
+ .where(
1806
+ and(
1807
+ eq(rsc.moduleId, input.moduleId),
1808
+ notExists(
1809
+ database
1810
+ .select({ one: sql`1` })
1811
+ .from(mapping.abuseEvent.table)
1812
+ .where(
1813
+ and(
1814
+ eq(ac.moduleId, rsc.moduleId),
1815
+ eq(ac.purpose, rsc.purpose),
1816
+ eq(ac.action, rsc.action),
1817
+ eq(ac.scopeKind, rsc.scopeKind),
1818
+ eq(ac.scopeKey, rsc.scopeKey),
1819
+ ),
1820
+ ),
1821
+ ),
1822
+ ),
1823
+ )
1824
+ .limit(remaining + 1),
1825
+ );
1826
+
1827
+ const marker = `effect-auth-proof-guard:cleanup:${input.moduleId}:${now}`;
1828
+ const statements: Statement<any>[] = [];
1829
+
1830
+ const guardedDelete = Effect.fn(function* (
1831
+ condition: SQL,
1832
+ query: { readonly toSQL: () => { sql: string; params: unknown[] } },
1833
+ ) {
1834
+ statements.push(yield* assertion(condition, marker), yield* statement(query));
1835
+ });
1836
+
1837
+ for (const row of continuations) {
1838
+ const condition = and(
1839
+ eq(cc.moduleId, input.moduleId),
1840
+ eq(cc.continuationId, row.continuationId),
1841
+ lte(cc.retentionUntil, mapping.d1.engineNow),
1842
+ )!;
1843
+
1844
+ yield* guardedDelete(
1845
+ sql`exists(select 1 from ${mapping.continuation.table} where ${condition})`,
1846
+ database.delete(mapping.continuation.table).where(condition),
1847
+ );
1848
+ }
1849
+ for (const row of generations) {
1850
+ const condition = and(
1851
+ eq(gc.moduleId, input.moduleId),
1852
+ eq(gc.proofId, row.proofId),
1853
+ lte(gc.retentionUntil, mapping.d1.engineNow),
1854
+ )!;
1855
+
1856
+ yield* guardedDelete(
1857
+ sql`exists(select 1 from ${mapping.generation.table} where ${condition})`,
1858
+ database
1859
+ .update(mapping.series.table)
1860
+ .set(updateValues([[mapping.series.activeProofId, null]]))
1861
+ .where(and(eq(sc.moduleId, input.moduleId), eq(sc.activeProofId, row.proofId))),
1862
+ );
1863
+ statements.push(
1864
+ yield* statement(database.delete(mapping.generation.table).where(condition)),
1865
+ );
1866
+ }
1867
+ for (const row of requests) {
1868
+ const condition = and(
1869
+ eq(rc.moduleId, input.moduleId),
1870
+ eq(rc.requestId, row.requestId),
1871
+ lte(rc.retentionUntil, mapping.d1.engineNow),
1872
+ )!;
1873
+
1874
+ yield* guardedDelete(
1875
+ sql`exists(select 1 from ${mapping.request.table} where ${condition})`,
1876
+ database.delete(mapping.request.table).where(condition),
1877
+ );
1878
+ }
1879
+ for (const row of abuse) {
1880
+ const condition = and(
1881
+ eq(ac.moduleId, input.moduleId),
1882
+ eq(ac.action, row.action),
1883
+ eq(ac.scopeKind, row.scopeKind),
1884
+ eq(ac.scopeKey, row.scopeKey),
1885
+ eq(ac.commandId, row.commandId),
1886
+ lte(ac.retentionUntil, mapping.d1.engineNow),
1887
+ )!;
1888
+
1889
+ yield* guardedDelete(
1890
+ sql`exists(select 1 from ${mapping.abuseEvent.table} where ${condition})`,
1891
+ database.delete(mapping.abuseEvent.table).where(condition),
1892
+ );
1893
+ }
1894
+ for (const row of failures) {
1895
+ const condition = and(
1896
+ eq(fc.moduleId, input.moduleId),
1897
+ eq(fc.seriesKey, row.seriesKey),
1898
+ eq(fc.commandId, row.commandId),
1899
+ lte(fc.retentionUntil, mapping.d1.engineNow),
1900
+ )!;
1901
+
1902
+ yield* guardedDelete(
1903
+ sql`exists(select 1 from ${mapping.failureEvent.table} where ${condition})`,
1904
+ database.delete(mapping.failureEvent.table).where(condition),
1905
+ );
1906
+ }
1907
+ for (const row of commands) {
1908
+ const condition = and(
1909
+ eq(mc.moduleId, input.moduleId),
1910
+ eq(mc.commandId, row.commandId),
1911
+ lte(mc.retentionUntil, mapping.d1.engineNow),
1912
+ )!;
1913
+
1914
+ yield* guardedDelete(
1915
+ sql`exists(select 1 from ${mapping.command.table} where ${condition})`,
1916
+ database.delete(mapping.command.table).where(condition),
1917
+ );
1918
+ }
1919
+ for (const row of series) {
1920
+ const condition = and(
1921
+ eq(sc.moduleId, input.moduleId),
1922
+ eq(sc.purpose, row.purpose),
1923
+ eq(sc.scopeKey, row.scopeKey),
1924
+ isNull(sc.activeProofId),
1925
+ notExists(
1926
+ database
1927
+ .select({ one: sql`1` })
1928
+ .from(mapping.generation.table)
1929
+ .where(
1930
+ and(
1931
+ eq(gc.moduleId, sc.moduleId),
1932
+ eq(gc.purpose, sc.purpose),
1933
+ eq(gc.seriesKey, sc.scopeKey),
1934
+ ),
1935
+ ),
1936
+ ),
1937
+ )!;
1938
+
1939
+ yield* guardedDelete(
1940
+ sql`exists(select 1 from ${mapping.series.table} where ${condition})`,
1941
+ database.delete(mapping.series.table).where(condition),
1942
+ );
1943
+ }
1944
+ for (const row of rateScopes) {
1945
+ const condition = and(
1946
+ eq(rsc.moduleId, input.moduleId),
1947
+ eq(rsc.purpose, row.purpose),
1948
+ eq(rsc.action, row.action),
1949
+ eq(rsc.scopeKind, row.scopeKind),
1950
+ eq(rsc.scopeKey, row.scopeKey),
1951
+ notExists(
1952
+ database
1953
+ .select({ one: sql`1` })
1954
+ .from(mapping.abuseEvent.table)
1955
+ .where(
1956
+ and(
1957
+ eq(ac.moduleId, rsc.moduleId),
1958
+ eq(ac.purpose, rsc.purpose),
1959
+ eq(ac.action, rsc.action),
1960
+ eq(ac.scopeKind, rsc.scopeKind),
1961
+ eq(ac.scopeKey, rsc.scopeKey),
1962
+ ),
1963
+ ),
1964
+ ),
1965
+ )!;
1966
+
1967
+ yield* guardedDelete(
1968
+ sql`exists(select 1 from ${mapping.rateScope.table} where ${condition})`,
1969
+ database.delete(mapping.rateScope.table).where(condition),
1970
+ );
1971
+ }
1972
+ // Removing the final history row can make an anchor eligible only after this
1973
+ // transaction/batch commits. One extra page lets the caller reclaim it.
1974
+ hasMore ||= generations.length > 0 || failures.length > 0 || abuse.length > 0;
1975
+ const result: ProofCleanupResult = { removed: input.limit - remaining, hasMore };
1976
+
1977
+ return {
1978
+ receipt: prepare(result, journal),
1979
+ statements,
1980
+ retryable: (cause: unknown) => isGuardFailure(cause, marker),
1981
+ };
1982
+ }),
1983
+ );
1984
+ }),
1985
+ };
1986
+ };
1987
+
1988
+ export const makeD1ProofPersistenceServices = <
1989
+ Rq extends AnySQLiteTable,
1990
+ S extends AnySQLiteTable,
1991
+ G extends AnySQLiteTable,
1992
+ Cn extends AnySQLiteTable,
1993
+ Rs extends AnySQLiteTable,
1994
+ A extends AnySQLiteTable,
1995
+ F extends AnySQLiteTable,
1996
+ C extends AnySQLiteTable,
1997
+ Sub extends AnySQLiteTable,
1998
+ I extends AnySQLiteTable,
1999
+ Cr extends AnySQLiteTable,
2000
+ NativeId,
2001
+ >(
2002
+ database: Database,
2003
+ mapping: D1ProofPersistenceMapping<Rq, S, G, Cn, Rs, A, F, C, Sub, I, Cr, NativeId>,
2004
+ ) =>
2005
+ Effect.gen(function* () {
2006
+ const hooks = yield* LifecycleHooks;
2007
+ const plans = makeProofPlans(mapping as unknown as Mapping);
2008
+
2009
+ const run = <Out, Err, Env>(plan: Effect.Effect<Planned<Out>, Err, Env>) =>
2010
+ Effect.gen(function* () {
2011
+ if (yield* hasCommitScope) return yield* unavailable();
2012
+
2013
+ return yield* executeStandalone(plan, 2);
2014
+ }).pipe(
2015
+ Effect.provideService(CurrentD1PlanningDatabase, database),
2016
+ Effect.provideService(LifecycleHooks, hooks),
2017
+ );
2018
+
2019
+ const service: ProofPersistence["Service"] = {
2020
+ issue: (input, prepare) => run(plans.issue(input, prepare)).pipe(translateIssueFailure),
2021
+ attempt: (input, prepare) => run(plans.attempt(input, prepare)).pipe(translateFailure),
2022
+ complete: (input, prepare) => run(plans.complete(input, prepare)).pipe(translateFailure),
2023
+ claimDelivery: (input, prepare) =>
2024
+ run(plans.claimDelivery(input, prepare)).pipe(translateFailure),
2025
+ settleDelivery: (input, prepare) =>
2026
+ run(plans.settleDelivery(input, prepare)).pipe(translateFailure),
2027
+ cancel: (input, prepare) => run(plans.cancel(input, prepare)).pipe(translateFailure),
2028
+ cleanup: (input, prepare) => run(plans.cleanup(input, prepare)).pipe(translateFailure),
2029
+ };
2030
+
2031
+ return { proofPersistence: service };
2032
+ });
2033
+
2034
+ type CoordinatorError<E> = E | ProofUnavailable | HookConfigurationError;
2035
+
2036
+ /**
2037
+ * Owns one proof transition plus application statements in one D1 batch. It
2038
+ * never replays the owner effect. A reserved guard or named race becomes
2039
+ * ProofUnavailable so the caller can retry the entire command with fresh secrets.
2040
+ */
2041
+ export function coordinateD1ProofPersistence<
2042
+ Rq extends AnySQLiteTable,
2043
+ S extends AnySQLiteTable,
2044
+ G extends AnySQLiteTable,
2045
+ Cn extends AnySQLiteTable,
2046
+ Rs extends AnySQLiteTable,
2047
+ Aev extends AnySQLiteTable,
2048
+ F extends AnySQLiteTable,
2049
+ C extends AnySQLiteTable,
2050
+ Sub extends AnySQLiteTable,
2051
+ I extends AnySQLiteTable,
2052
+ Cr extends AnySQLiteTable,
2053
+ NativeId,
2054
+ A,
2055
+ E,
2056
+ R,
2057
+ DatabaseError,
2058
+ DatabaseRequirements,
2059
+ >(
2060
+ acquire: Effect.Effect<Database, DatabaseError, DatabaseRequirements>,
2061
+ options: {
2062
+ readonly mapping: D1ProofPersistenceMapping<Rq, S, G, Cn, Rs, Aev, F, C, Sub, I, Cr, NativeId>;
2063
+ },
2064
+ body: Effect.Effect<A, E, R>,
2065
+ ): Effect.Effect<
2066
+ A,
2067
+ CoordinatorError<E> | DatabaseError,
2068
+ Exclude<R, ProofPersistence | D1BatchStatements> | LifecycleHooks | DatabaseRequirements
2069
+ > {
2070
+ return Effect.flatMap(acquire, (database) =>
2071
+ Effect.gen(function* () {
2072
+ const hooks = yield* LifecycleHooks;
2073
+
2074
+ if (yield* hasCommitScope) return yield* unavailable();
2075
+
2076
+ const result = yield* coordinateCommit(
2077
+ () =>
2078
+ Effect.gen(function* () {
2079
+ const statements: Statement<any>[] = [];
2080
+ let mutation: Planned<any> | undefined;
2081
+
2082
+ const nativeCollector = D1BatchStatements.of({
2083
+ append: (statement) => Effect.sync(() => statements.push(statement)),
2084
+ });
2085
+
2086
+ const owner = yield* makeD1Owner(unavailable()).pipe(
2087
+ Effect.provideService(D1BatchStatements, nativeCollector),
2088
+ );
2089
+
2090
+ const plans = makeProofPlans(options.mapping as unknown as Mapping);
2091
+
2092
+ const run = <Out, Err, Env>(plan: Effect.Effect<Planned<Out>, Err, Env>) =>
2093
+ coordinateCommit(
2094
+ () =>
2095
+ Effect.gen(function* () {
2096
+ const journal = yield* CurrentCommitJournal;
2097
+ const planned = yield* plan;
2098
+
2099
+ yield* owner.check;
2100
+ if (mutation !== undefined) return yield* unavailable();
2101
+ const guarded = { ...planned, journalGuard: journal.prepare(undefined) };
2102
+
2103
+ mutation = guarded;
2104
+ statements.push(...guarded.statements);
2105
+
2106
+ return guarded.receipt;
2107
+ }),
2108
+ { mode: "batch" },
2109
+ ).pipe(
2110
+ Effect.map((result) => result.value),
2111
+ Effect.provideService(CurrentD1PlanningDatabase, database),
2112
+ Effect.provideService(LifecycleHooks, hooks),
2113
+ );
2114
+
2115
+ const service: ProofPersistence["Service"] = {
2116
+ issue: (input, prepare) =>
2117
+ owner.run(run(plans.issue(input, prepare)).pipe(translateIssueFailure)),
2118
+ attempt: (input, prepare) =>
2119
+ owner.run(run(plans.attempt(input, prepare)).pipe(translateFailure)),
2120
+ complete: (input, prepare) =>
2121
+ owner.run(run(plans.complete(input, prepare)).pipe(translateFailure)),
2122
+ claimDelivery: (input, prepare) =>
2123
+ owner.run(run(plans.claimDelivery(input, prepare)).pipe(translateFailure)),
2124
+ settleDelivery: (input, prepare) =>
2125
+ owner.run(run(plans.settleDelivery(input, prepare)).pipe(translateFailure)),
2126
+ cancel: (input, prepare) =>
2127
+ owner.run(run(plans.cancel(input, prepare)).pipe(translateFailure)),
2128
+ cleanup: (input, prepare) =>
2129
+ owner.run(run(plans.cleanup(input, prepare)).pipe(translateFailure)),
2130
+ };
2131
+
2132
+ const provided = Context.make(ProofPersistence, service).pipe(
2133
+ Context.add(D1BatchStatements, owner.collector),
2134
+ );
2135
+
2136
+ const value = yield* owner.close(Effect.provideContext(body, provided));
2137
+
2138
+ if (mutation?.journalGuard !== undefined) {
2139
+ const status = yield* Effect.result(mutation.journalGuard.read);
2140
+
2141
+ if (status._tag === "Success" || status.failure._tag !== "CommitPending")
2142
+ return yield* unavailable();
2143
+ }
2144
+ yield* database.$client.batch(statements).pipe(
2145
+ Effect.catchCause((cause) =>
2146
+ Effect.failCause(
2147
+ Cause.map(cause, (error) =>
2148
+ everyFailureMatches(cause, mutation?.retryable) ? unavailable() : error,
2149
+ ),
2150
+ ),
2151
+ ),
2152
+ translateFailure,
2153
+ );
2154
+
2155
+ return value;
2156
+ }),
2157
+ { mode: "batch" },
2158
+ ).pipe(Effect.provideService(LifecycleHooks, hooks));
2159
+
2160
+ return result.value;
2161
+ }),
2162
+ );
2163
+ }
2164
+
2165
+ export interface D1ProtectedProofMutation {
2166
+ /** Conditional statements compiled by the owning method adapter. */
2167
+ readonly statements: ReadonlyArray<Statement<any>>;
2168
+ /** Postcondition proving the protected CAS and its invalidations all applied. */
2169
+ readonly appliedCondition: SQL;
2170
+ }
2171
+
2172
+ export interface D1CompiledProofCompletion<A> {
2173
+ readonly receipt: PreparedCommit<A>;
2174
+ readonly statements: ReadonlyArray<Statement<any>>;
2175
+ readonly postconditions?: ReadonlyArray<Statement<any>>;
2176
+ }
2177
+
2178
+ /** Private compiler seam for a future same-owner D1 password-reset batch. */
2179
+ export const compileD1ProofCompletionPlan = Effect.fn("Drizzle.compileD1ProofCompletionPlan")(
2180
+ function* <
2181
+ Rq extends AnySQLiteTable,
2182
+ S extends AnySQLiteTable,
2183
+ G extends AnySQLiteTable,
2184
+ Cn extends AnySQLiteTable,
2185
+ Rs extends AnySQLiteTable,
2186
+ Aev extends AnySQLiteTable,
2187
+ F extends AnySQLiteTable,
2188
+ C extends AnySQLiteTable,
2189
+ Sub extends AnySQLiteTable,
2190
+ I extends AnySQLiteTable,
2191
+ Cr extends AnySQLiteTable,
2192
+ NativeId,
2193
+ A,
2194
+ >(
2195
+ mapping: D1ProofPersistenceMapping<Rq, S, G, Cn, Rs, Aev, F, C, Sub, I, Cr, NativeId>,
2196
+ plan: ProofCompletionPlan,
2197
+ protectedMutation: D1ProtectedProofMutation,
2198
+ project: (decision: ProofCompletionDecision) => A,
2199
+ ) {
2200
+ const planned = yield* completionPlan<A>(
2201
+ mapping as unknown as Mapping,
2202
+ plan.input,
2203
+ (decision, activeJournal) => plan.prepare(decision, activeJournal, project),
2204
+ );
2205
+
2206
+ // A rejected completion has no protected mutation. For a predicted success,
2207
+ // preserve the fresh continuation/authority guard first, then prove the
2208
+ // method CAS before consuming the continuation and inserting its marker.
2209
+ if (planned.statements.length === 0) return planned;
2210
+ const [freshGuard, ...completionStatements] = planned.statements;
2211
+ const marker = `effect-auth-proof-guard:protected:${plan.input.continuationId}`;
2212
+
2213
+ return {
2214
+ receipt: planned.receipt,
2215
+ statements: [
2216
+ freshGuard!,
2217
+ ...protectedMutation.statements,
2218
+ yield* assertion(protectedMutation.appliedCondition, marker),
2219
+ ...completionStatements,
2220
+ ],
2221
+ postconditions: [
2222
+ yield* assertion(protectedMutation.appliedCondition, marker),
2223
+ ...(planned.postconditions ?? []),
2224
+ ],
2225
+ };
2226
+ },
2227
+ );
2228
+
2229
+ export type AnyD1ProofMapping = ProofPersistenceMapping<
2230
+ Table,
2231
+ Table,
2232
+ Table,
2233
+ Table,
2234
+ Table,
2235
+ Table,
2236
+ Table,
2237
+ Table,
2238
+ Table,
2239
+ Table,
2240
+ Table,
2241
+ unknown
2242
+ >;
2243
+
2244
+ const translateFailure = <A, E, R>(
2245
+ effect: Effect.Effect<A, E, R>,
2246
+ ): Effect.Effect<A, ProofUnavailable, R> =>
2247
+ reportPersistenceFailure(
2248
+ effect,
2249
+ (error) => Schema.is(ProofUnavailable)(error) || Schema.is(HookConfigurationError)(error),
2250
+ ).pipe(Effect.catchCause((cause) => Effect.failCause(Cause.map(cause, () => unavailable()))));
2251
+
2252
+ const translateIssueFailure = <A, E, R>(
2253
+ effect: Effect.Effect<A, E, R>,
2254
+ ): Effect.Effect<A, ProofUnavailable | ProofRequestConflict, R> =>
2255
+ reportPersistenceFailure(
2256
+ effect,
2257
+ (error) =>
2258
+ Schema.is(ProofUnavailable)(error) ||
2259
+ Schema.is(ProofRequestConflict)(error) ||
2260
+ Schema.is(HookConfigurationError)(error),
2261
+ ).pipe(
2262
+ Effect.catchCause((cause) =>
2263
+ Effect.failCause(
2264
+ Cause.map(cause, (error) =>
2265
+ Schema.is(ProofRequestConflict)(error) ? error : unavailable(),
2266
+ ),
2267
+ ),
2268
+ ),
2269
+ );
2270
+
2271
+ const executeStandalone = <A, E, R>(
2272
+ plan: Effect.Effect<Planned<A>, E, R>,
2273
+ retries = 2,
2274
+ ): Effect.Effect<
2275
+ A,
2276
+ | E
2277
+ | import("@yielded/auth/Hooks").HookConfigurationError
2278
+ | import("effect/unstable/sql/SqlError").SqlError,
2279
+ Exclude<R, CurrentCommitJournal> | CurrentD1PlanningDatabase | LifecycleHooks
2280
+ > =>
2281
+ Effect.suspend(() => {
2282
+ let retryable: ((cause: unknown) => boolean) | undefined;
2283
+
2284
+ const once = coordinateCommit(
2285
+ () =>
2286
+ Effect.gen(function* () {
2287
+ const database = yield* CurrentD1PlanningDatabase;
2288
+ const planned = yield* plan;
2289
+
2290
+ retryable = planned.retryable;
2291
+ yield* database.$client.batch(planned.statements);
2292
+
2293
+ return planned.receipt;
2294
+ }),
2295
+ { mode: "batch" },
2296
+ ).pipe(Effect.map((result) => result.value));
2297
+
2298
+ return once.pipe(
2299
+ Effect.catchCause((cause) =>
2300
+ retries > 0 && everyFailureMatches(cause, retryable)
2301
+ ? executeStandalone(plan, retries - 1)
2302
+ : Effect.failCause(cause),
2303
+ ),
2304
+ );
2305
+ });