@humanonlyweb/create-nuxtflare 0.2.4 → 0.2.5

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 (42) hide show
  1. package/README.md +0 -22
  2. package/dist/cli.js +2 -1
  3. package/dist/template/.github/workflows/ci.yml +19 -14
  4. package/dist/template/CLAUDE.md +3 -3
  5. package/dist/template/app/components/totp-setup.vue +18 -13
  6. package/dist/template/app/composables/use-account.ts +7 -5
  7. package/dist/template/app/composables/use-auth.ts +11 -7
  8. package/dist/template/app/pages/account.vue +2 -1
  9. package/dist/template/nuxt.config.ts +5 -2
  10. package/dist/template/package.json +3 -2
  11. package/dist/template/public/_headers +6 -0
  12. package/dist/template/server/api/account/index.delete.ts +1 -1
  13. package/dist/template/server/api/auth/logout-everywhere.post.ts +1 -1
  14. package/dist/template/server/api/auth/logout.post.ts +3 -11
  15. package/dist/template/server/api/auth/register.post.ts +11 -3
  16. package/dist/template/server/api/auth/verify/send.post.ts +11 -4
  17. package/dist/template/server/app/identity/lockout.ts +10 -5
  18. package/dist/template/server/app/identity/service.ts +50 -16
  19. package/dist/template/server/app/identity/sessions.ts +2 -1
  20. package/dist/template/server/app/identity/totp.test.ts +1 -0
  21. package/dist/template/server/app/identity/totp.ts +16 -6
  22. package/dist/template/server/app/identity/verification.ts +29 -7
  23. package/dist/template/server/core/app-layer.ts +3 -2
  24. package/dist/template/server/core/db/atomic-d1.ts +12 -6
  25. package/dist/template/server/core/db/atomic.ts +36 -25
  26. package/dist/template/server/core/db/migrations.ts +11 -0
  27. package/dist/template/server/core/db/migrator.ts +0 -10
  28. package/dist/template/server/core/db/session-d1.ts +56 -0
  29. package/dist/template/server/core/db/session.test.ts +97 -0
  30. package/dist/template/server/core/db/session.ts +171 -0
  31. package/dist/template/server/core/http/handle.ts +13 -3
  32. package/dist/template/server/core/http/session.ts +49 -1
  33. package/dist/template/server/core/platform/app-config.ts +2 -0
  34. package/dist/template/server/core/platform/database.ts +39 -22
  35. package/dist/template/server/middleware/01-user-session.ts +11 -2
  36. package/dist/template/server/plugins/page-csp.ts +1 -1
  37. package/dist/template/server/plugins/sessions.ts +16 -4
  38. package/dist/template/server/test/kit.ts +4 -0
  39. package/dist/template/shared/utils/auth.ts +1 -0
  40. package/dist/template/wrangler.json +3 -0
  41. package/package.json +1 -1
  42. /package/dist/template/app/components/{qr-code.vue → qr-code.client.vue} +0 -0
@@ -3,6 +3,7 @@ import { Cache, Context, DateTime, Effect, Layer, Schema } from 'effect'
3
3
  import type { EmailStatus } from '#shared/utils/auth'
4
4
 
5
5
  import { AtomicBatch, type Statement } from '#server/core/db/atomic'
6
+ import { CurrentDbSession } from '#server/core/db/session'
6
7
  import { Database } from '#server/core/platform/database'
7
8
  import { IdGenerator } from '#server/core/platform/id-generator'
8
9
 
@@ -123,7 +124,7 @@ export class Sessions extends Context.Service<
123
124
  if (updates.length > 0) {
124
125
  const persist = atomic.run(updates).pipe(Effect.catch((error) => Effect.logWarning(`Session activity update failed: ${error.message}`)))
125
126
  if (options?.waitUntil) {
126
- const fiber = yield* Effect.forkDetach(persist)
127
+ const fiber = yield* Effect.forkDetach(persist.pipe(Effect.provideService(CurrentDbSession, undefined)))
127
128
  options.waitUntil(
128
129
  new Promise<void>((resolve) => {
129
130
  fiber.addObserver(() => resolve())
@@ -68,6 +68,7 @@ describe('totp explicit state machine', () => {
68
68
 
69
69
  const enabled = await run(Totp.use((t) => t.security(user.id)))
70
70
  expect(enabled).toEqual({ status: 'enabled', recoveryCodesLeft: 8 })
71
+ expect((await run(Identity.use((id) => id.me(user.id)))).totpRecoveryCodesLeft).toBe(8)
71
72
 
72
73
  // Login now requires explicit 2FA challenge
73
74
  const outcome = await run(Identity.use((id) => id.login({ identity: 'alice', password: 'correct-password' })))
@@ -40,7 +40,10 @@ const UserTotpRow = Schema.Struct({
40
40
  totp_last_step: Schema.Finite,
41
41
  })
42
42
 
43
- const CountRow = Schema.Struct({ n: Schema.Finite })
43
+ const SecurityRow = Schema.Struct({
44
+ totp_status: Schema.Literals(['off', 'pending', 'enabled']),
45
+ recovery_codes_left: Schema.Finite,
46
+ })
44
47
 
45
48
  const ChallengePayload = Schema.fromJsonString(
46
49
  Schema.Struct({
@@ -147,13 +150,20 @@ export class Totp extends Context.Service<
147
150
 
148
151
  const security = Effect.fn('Totp.security')(function* (userId: string) {
149
152
  yield* assertFeatureOn()
150
- const user = yield* loadUser(userId)
151
- const left = yield* db
152
- .first(CountRow, `SELECT COUNT(*) AS n FROM totp_recovery_codes WHERE user_id = ? AND status = 'unused'`, [userId])
153
+ const row = yield* db
154
+ .first(
155
+ SecurityRow,
156
+ `SELECT
157
+ u.totp_status,
158
+ (SELECT COUNT(*) FROM totp_recovery_codes rc WHERE rc.user_id = u.id AND rc.status = 'unused') AS recovery_codes_left
159
+ FROM users u
160
+ WHERE u.id = ?`,
161
+ [userId],
162
+ )
153
163
  .pipe(Effect.orDie)
154
164
  return {
155
- status: user?.totp_status ?? 'off',
156
- recoveryCodesLeft: left?.n ?? 0,
165
+ status: row?.totp_status ?? 'off',
166
+ recoveryCodesLeft: row?.recovery_codes_left ?? 0,
157
167
  } satisfies TotpSecurity
158
168
  })
159
169
 
@@ -1,10 +1,12 @@
1
1
  import { Context, DateTime, Effect, Layer, Schema } from 'effect'
2
2
 
3
3
  import type { RateLimited } from '#shared/domain/errors'
4
+ import type { EmailStatus } from '#shared/utils/auth'
4
5
 
5
6
  import { EmailRenderer } from '#server/app/notifications/render'
6
7
  import { verificationEmail } from '#server/app/notifications/templates'
7
8
  import { AtomicBatch, assertPreviousChanged } from '#server/core/db/atomic'
9
+ import { CurrentDbSession } from '#server/core/db/session'
8
10
  import { AppConfig } from '#server/core/platform/app-config'
9
11
  import { nowIso } from '#server/core/platform/clock'
10
12
  import { Database } from '#server/core/platform/database'
@@ -31,10 +33,17 @@ const TokenRow = Schema.Struct({
31
33
  expires_at: Schema.String,
32
34
  })
33
35
 
36
+ export interface SendVerificationOptions {
37
+ /** Skips the `SELECT users` lookup when the caller already has the freshly created/loaded user. */
38
+ readonly user?: { readonly id: string; readonly email: string; readonly emailStatus: EmailStatus }
39
+ /** Defers email rendering and delivery off the HTTP response critical path. */
40
+ readonly waitUntil?: (promise: Promise<unknown>) => void
41
+ }
42
+
34
43
  export class EmailVerification extends Context.Service<
35
44
  EmailVerification,
36
45
  {
37
- readonly send: (userId: string) => Effect.Effect<void, RateLimited>
46
+ readonly send: (userId: string, options?: SendVerificationOptions) => Effect.Effect<void, RateLimited>
38
47
  readonly confirm: (token: string) => Effect.Effect<{ readonly userId: string }, Unauthorized>
39
48
  }
40
49
  >()('app/identity/EmailVerification') {
@@ -51,8 +60,10 @@ export class EmailVerification extends Context.Service<
51
60
  const limiter = yield* RateLimiter
52
61
  const sessions = yield* Sessions
53
62
 
54
- const send = Effect.fn('EmailVerification.send')(function* (userId: string) {
55
- const user = yield* db.first(UserRow, `SELECT id, email, email_status FROM users WHERE id = ?`, [userId]).pipe(Effect.orDie)
63
+ const send = Effect.fn('EmailVerification.send')(function* (userId: string, options?: SendVerificationOptions) {
64
+ const user = options?.user
65
+ ? { id: options.user.id, email: options.user.email, email_status: options.user.emailStatus }
66
+ : yield* db.first(UserRow, `SELECT id, email, email_status FROM users WHERE id = ?`, [userId]).pipe(Effect.orDie)
56
67
  if (!user || user.email_status === 'verified') return
57
68
 
58
69
  yield* limiter.check('verify', yield* pii.index(user.email))
@@ -75,10 +86,21 @@ export class EmailVerification extends Context.Service<
75
86
  ])
76
87
  .pipe(Effect.orDie)
77
88
 
78
- const rendered = yield* renderer.render(verificationEmail(`${config.appUrl}/verify/${token}`, config.appName))
79
- yield* mailer
80
- .send({ to: user.email, ...rendered })
81
- .pipe(Effect.catch((error) => Effect.logWarning(`Verification email failed (${error._tag}): ${error.message}`)))
89
+ const deliver = renderer.render(verificationEmail(`${config.appUrl}/verify/${token}`, config.appName)).pipe(
90
+ Effect.flatMap((rendered) => mailer.send({ to: user.email, ...rendered })),
91
+ Effect.catch((error) => Effect.logWarning(`Verification email failed (${error._tag}): ${error.message}`)),
92
+ )
93
+
94
+ if (options?.waitUntil) {
95
+ const fiber = yield* Effect.forkDetach(deliver.pipe(Effect.provideService(CurrentDbSession, undefined)))
96
+ options.waitUntil(
97
+ new Promise<void>((resolve) => {
98
+ fiber.addObserver(() => resolve())
99
+ }),
100
+ )
101
+ } else {
102
+ yield* deliver
103
+ }
82
104
  })
83
105
 
84
106
  const confirm = Effect.fn('EmailVerification.confirm')(function* (token: string) {
@@ -5,6 +5,7 @@ import { Features } from '#server/app/features'
5
5
 
6
6
  import { AtomicBatchD1 } from './db/atomic-d1'
7
7
  import { MigratorLive } from './db/migrator'
8
+ import { DbSessionD1 } from './db/session-d1'
8
9
  import { AppConfig } from './platform/app-config'
9
10
  import { Database } from './platform/database'
10
11
  import { EmailAssets } from './platform/email-assets'
@@ -25,8 +26,8 @@ const Platform = Layer.mergeAll(Pii.layer, MailerCloudflare).pipe(
25
26
  Layer.provideMerge(Layer.mergeAll(PasswordHasher.layer, AppConfig.layer, IdGenerator.layer, Tokens.layer, Seal.layer, FetchHttpClient.layer, Bindings)),
26
27
  )
27
28
 
28
- /** Migrations run automatically on first build; feature layers sit above Foundation. */
29
- const Foundation = MigratorLive.pipe(Layer.provideMerge(Layer.mergeAll(Turnstile.layer, RateLimiterStrict).pipe(Layer.provideMerge(Platform))))
29
+ const Base = Layer.mergeAll(Turnstile.layer, RateLimiterStrict, DbSessionD1).pipe(Layer.provideMerge(Platform))
30
+ const Foundation = import.meta.dev ? MigratorLive.pipe(Layer.provideMerge(Base)) : Base
30
31
 
31
32
  export const AppLayer = Features.pipe(Layer.provideMerge(Foundation))
32
33
 
@@ -6,16 +6,22 @@ import { DatabaseError } from '#server/core/platform/database'
6
6
  import type { Applied } from './atomic'
7
7
 
8
8
  import { AtomicBatch } from './atomic'
9
+ import { CurrentDbSession } from './session'
9
10
 
10
11
  /** D1's `batch()` executes its statements in one implicit transaction: if any statement fails, none are kept. */
11
12
  export const AtomicBatchD1 = Layer.sync(AtomicBatch, () =>
12
13
  AtomicBatch.make((statements) =>
13
- Effect.tryPromise({
14
- try: async (): Promise<ReadonlyArray<Applied>> => {
15
- const results = await env.DB.batch(statements.map(({ sql, params = [] }) => env.DB.prepare(sql).bind(...params)))
16
- return results.map((result) => ({ changes: result.meta.changes }))
17
- },
18
- catch: (cause) => new DatabaseError({ sql: 'batch', message: cause instanceof Error ? cause.message : String(cause) }),
14
+ Effect.gen(function* () {
15
+ const session = yield* CurrentDbSession
16
+
17
+ return yield* Effect.tryPromise({
18
+ try: async (): Promise<ReadonlyArray<Applied>> => {
19
+ if (session) return session.batch(statements)
20
+ const results = await env.DB.batch(statements.map(({ sql, params = [] }) => env.DB.prepare(sql).bind(...params)))
21
+ return results.map((result) => ({ changes: result.meta.changes }))
22
+ },
23
+ catch: (cause) => new DatabaseError({ sql: 'batch', message: cause instanceof Error ? cause.message : String(cause) }),
24
+ })
19
25
  }),
20
26
  ),
21
27
  )
@@ -5,6 +5,8 @@ import { Context, Effect, Layer, Schema, Semaphore } from 'effect'
5
5
  import { DatabaseError } from '#server/core/platform/database'
6
6
  import { readKey } from '#shared/utils/unknown'
7
7
 
8
+ import { CurrentDbSession } from './session'
9
+
8
10
  type Param = string | number | boolean | null | undefined
9
11
 
10
12
  export interface Statement {
@@ -52,32 +54,41 @@ export class AtomicBatch extends Context.Service<
52
54
  static readonly layerFor = (db: Db0) => {
53
55
  const lock = Semaphore.makeUnsafe(1)
54
56
  const run = (statements: ReadonlyArray<Statement>) =>
55
- lock.withPermit(
56
- Effect.tryPromise({
57
- try: async () => {
58
- await db.exec('BEGIN')
59
- try {
60
- const applied: Applied[] = []
61
- for (const { sql, params = [] } of statements) {
62
- // Transaction statements execute sequentially on one SQLite connection.
63
- // oxlint-disable-next-line eslint/no-await-in-loop
64
- const result = await db
65
- .prepare(sql)
66
- .bind(...params)
67
- .run()
68
- const changes = readKey(result, 'changes')
69
- applied.push({ changes: typeof changes === 'number' || typeof changes === 'bigint' ? Number(changes) : 0 })
57
+ Effect.gen(function* () {
58
+ const session = yield* CurrentDbSession
59
+ if (session) {
60
+ return yield* Effect.tryPromise({
61
+ try: () => session.batch(statements),
62
+ catch: failure,
63
+ })
64
+ }
65
+ return yield* lock.withPermit(
66
+ Effect.tryPromise({
67
+ try: async () => {
68
+ await db.exec('BEGIN')
69
+ try {
70
+ const applied: Applied[] = []
71
+ for (const { sql, params = [] } of statements) {
72
+ // Transaction statements execute sequentially on one SQLite connection.
73
+ // oxlint-disable-next-line eslint/no-await-in-loop
74
+ const result = await db
75
+ .prepare(sql)
76
+ .bind(...params)
77
+ .run()
78
+ const changes = readKey(result, 'changes')
79
+ applied.push({ changes: typeof changes === 'number' || typeof changes === 'bigint' ? Number(changes) : 0 })
80
+ }
81
+ await db.exec('COMMIT')
82
+ return applied
83
+ } catch (error) {
84
+ await db.exec('ROLLBACK')
85
+ throw error
70
86
  }
71
- await db.exec('COMMIT')
72
- return applied
73
- } catch (error) {
74
- await db.exec('ROLLBACK')
75
- throw error
76
- }
77
- },
78
- catch: failure,
79
- }),
80
- )
87
+ },
88
+ catch: failure,
89
+ }),
90
+ )
91
+ })
81
92
 
82
93
  return Layer.succeed(AtomicBatch, AtomicBatch.make(run))
83
94
  }
@@ -153,4 +153,15 @@ export const migrations: ReadonlyArray<Migration> = [
153
153
  `CREATE INDEX idx_admin_audit_created ON admin_audit (created_at DESC)`,
154
154
  ],
155
155
  },
156
+ {
157
+ id: '0002_performance_indexes',
158
+ statements: [
159
+ `CREATE INDEX idx_users_unverified_cleanup ON users (created_at)
160
+ WHERE email_status = 'unverified' AND google_sub IS NULL AND github_id IS NULL`,
161
+ `CREATE INDEX idx_login_failures_locked_until ON login_failures (locked_until)
162
+ WHERE status = 'locked'`,
163
+ `CREATE INDEX idx_login_failures_counting_updated ON login_failures (updated_at)
164
+ WHERE status = 'counting'`,
165
+ ],
166
+ },
156
167
  ]
@@ -7,20 +7,10 @@ import { AtomicBatch } from './atomic'
7
7
  import { migrations } from './migrations'
8
8
 
9
9
  const Applied = Schema.Struct({ id: Schema.String })
10
-
11
- /**
12
- * After a deploy, several Worker isolates can start at once and race to apply a new migration.
13
- * Losers retry briefly and observe the winner's `_migrations` record; genuinely broken migrations fail fast.
14
- */
15
10
  const RACE_RETRY = Schedule.exponential('100 millis').pipe(Schedule.jittered)
16
11
 
17
- /**
18
- * Applies pending migrations automatically in local `nuxt dev` so local work stays zero-config.
19
- * Production Workers skip cold-start DDL writes — apply migrations at deploy time via `bun run db:migrate:remote`.
20
- */
21
12
  export const MigratorLive = Layer.effectDiscard(
22
13
  Effect.gen(function* () {
23
- if (!import.meta.dev) return
24
14
  const db = yield* Database
25
15
  const atomic = yield* AtomicBatch
26
16
  yield* db.run(`CREATE TABLE IF NOT EXISTS _migrations (id TEXT PRIMARY KEY, applied_at TEXT NOT NULL)`)
@@ -0,0 +1,56 @@
1
+ import { env } from 'cloudflare:workers'
2
+ import { Effect, Layer } from 'effect'
3
+
4
+ import { AppConfig } from '#server/core/platform/app-config'
5
+
6
+ import type { Applied } from './atomic'
7
+
8
+ import { DbSession } from './session'
9
+
10
+ /**
11
+ * Cloudflare D1 Sessions API adapter (`env.DB.withSession`).
12
+ * Activated only when `runtimeConfig.d1Sessions` (`NUXT_D1_SESSIONS=true`) is enabled.
13
+ */
14
+ export const DbSessionD1 = Layer.effect(
15
+ DbSession,
16
+ Effect.gen(function* () {
17
+ const config = yield* AppConfig
18
+ if (!config.d1Sessions) {
19
+ return DbSession.of({
20
+ enabled: false,
21
+ withSession: (effect) => effect,
22
+ })
23
+ }
24
+
25
+ return DbSession.make((anchor) => {
26
+ const session = env.DB.withSession(anchor._tag === 'Bookmark' ? anchor.bookmark : anchor.constraint)
27
+ return {
28
+ all: async (sql, params) => {
29
+ const result = await session
30
+ .prepare(sql)
31
+ .bind(...params)
32
+ .all()
33
+ return result.results
34
+ },
35
+ first: async (sql, params) => {
36
+ const row = await session
37
+ .prepare(sql)
38
+ .bind(...params)
39
+ .first()
40
+ return row ?? undefined
41
+ },
42
+ run: async (sql, params) => {
43
+ await session
44
+ .prepare(sql)
45
+ .bind(...params)
46
+ .run()
47
+ },
48
+ batch: async (statements): Promise<ReadonlyArray<Applied>> => {
49
+ const results = await session.batch(statements.map(({ sql, params = [] }) => session.prepare(sql).bind(...params)))
50
+ return results.map((result) => ({ changes: result.meta.changes }))
51
+ },
52
+ getBookmark: () => session.getBookmark(),
53
+ }
54
+ })
55
+ }),
56
+ )
@@ -0,0 +1,97 @@
1
+ import { createDatabase } from 'db0'
2
+ import nodeSqlite from 'db0/connectors/node-sqlite'
3
+ import { Effect, Layer, Schema } from 'effect'
4
+ import { describe, expect, it } from 'vitest'
5
+
6
+ import { AtomicBatch, assertPreviousChanged } from '#server/core/db/atomic'
7
+ import { DbSession, type SessionAnchor, resolveAnchor, withDbSession } from '#server/core/db/session'
8
+ import { Database } from '#server/core/platform/database'
9
+ import { Conflict } from '#shared/domain/errors'
10
+
11
+ const ItemRow = Schema.Struct({
12
+ id: Schema.String,
13
+ label: Schema.String,
14
+ })
15
+
16
+ const makeHarness = async (enabled: boolean) => {
17
+ const db = createDatabase(nodeSqlite({ name: ':memory:' }))
18
+ await db.exec(`CREATE TABLE items (id TEXT PRIMARY KEY, label TEXT NOT NULL)`)
19
+ const anchors: SessionAnchor[] = []
20
+ const layer = Layer.mergeAll(
21
+ Database.layerFor(db),
22
+ AtomicBatch.layerFor(db),
23
+ DbSession.layerFor(db, {
24
+ enabled,
25
+ onOpen: (anchor) => anchors.push(anchor),
26
+ }),
27
+ )
28
+ const run = <A, E>(program: Effect.Effect<A, E, Layer.Success<typeof layer>>) => Effect.runPromise(program.pipe(Effect.provide(layer)))
29
+ return { run, anchors }
30
+ }
31
+
32
+ describe('DbSession / withDbSession', () => {
33
+ it('resolves explicit anchors with first-primary taking precedence over bookmarks', () => {
34
+ expect(resolveAnchor(undefined)).toEqual({ _tag: 'Constraint', constraint: 'first-unconstrained' })
35
+ expect(resolveAnchor('bm-42')).toEqual({ _tag: 'Bookmark', bookmark: 'bm-42' })
36
+ expect(resolveAnchor('bm-42', 'first-unconstrained')).toEqual({ _tag: 'Bookmark', bookmark: 'bm-42' })
37
+ expect(resolveAnchor('bm-42', 'first-primary')).toEqual({ _tag: 'Constraint', constraint: 'first-primary' })
38
+ })
39
+
40
+ it('acts as a zero-overhead passthrough when disabled', async () => {
41
+ const { run, anchors } = await makeHarness(false)
42
+ const bookmarks: string[] = []
43
+
44
+ const rows = await run(
45
+ withDbSession(
46
+ Effect.gen(function* () {
47
+ const db = yield* Database
48
+ yield* db.run(`INSERT INTO items (id, label) VALUES (?, ?)`, ['1', 'alpha'])
49
+ return yield* db.all(ItemRow, `SELECT id, label FROM items`)
50
+ }),
51
+ { bookmark: 'bm-1', onBookmark: (next) => bookmarks.push(next) },
52
+ ),
53
+ )
54
+
55
+ expect(rows).toEqual([{ id: '1', label: 'alpha' }])
56
+ expect(anchors).toEqual([])
57
+ expect(bookmarks).toEqual([])
58
+ })
59
+
60
+ it('routes Database and AtomicBatch queries through the active session and emits bookmarks even on typed failures', async () => {
61
+ const { run, anchors } = await makeHarness(true)
62
+ const bookmarks: string[] = []
63
+
64
+ const created = await run(
65
+ withDbSession(
66
+ Effect.gen(function* () {
67
+ const atomic = yield* AtomicBatch
68
+ const db = yield* Database
69
+ yield* atomic.runGuarded('insert_failed', [{ sql: `INSERT INTO items (id, label) VALUES (?, ?)`, params: ['1', 'one'] }, assertPreviousChanged])
70
+ return yield* db.first(ItemRow, `SELECT id, label FROM items WHERE id = ?`, ['1'])
71
+ }),
72
+ { onBookmark: (next) => bookmarks.push(next) },
73
+ ),
74
+ )
75
+
76
+ expect(created).toEqual({ id: '1', label: 'one' })
77
+ expect(anchors).toEqual([{ _tag: 'Constraint', constraint: 'first-unconstrained' }])
78
+ expect(bookmarks).toHaveLength(1)
79
+
80
+ // Subsequent request anchored on the returned bookmark still emits an updated bookmark even on typed failure.
81
+ const failed = await run(
82
+ withDbSession(
83
+ Effect.gen(function* () {
84
+ const db = yield* Database
85
+ yield* db.first(ItemRow, `SELECT id, label FROM items WHERE id = ?`, ['1'])
86
+ return yield* new Conflict({ message: 'already exists' })
87
+ }),
88
+ { bookmark: bookmarks[0], onBookmark: (next) => bookmarks.push(next) },
89
+ ).pipe(Effect.result),
90
+ )
91
+
92
+ expect(failed._tag).toBe('Failure')
93
+ expect(anchors[1]).toEqual({ _tag: 'Bookmark', bookmark: bookmarks[0]! })
94
+ expect(bookmarks).toHaveLength(2)
95
+ expect(bookmarks[1]).not.toBe(bookmarks[0])
96
+ })
97
+ })
@@ -0,0 +1,171 @@
1
+ import type { Database as Db0 } from 'db0'
2
+
3
+ import { Context, Effect, Layer } from 'effect'
4
+
5
+ import { readKey } from '#shared/utils/unknown'
6
+
7
+ import type { Applied, Statement } from './atomic'
8
+
9
+ export type DbParam = string | number | boolean | null | undefined
10
+
11
+ /** Initial D1 routing constraint when no client bookmark is supplied. */
12
+ export type SessionConstraint = 'first-primary' | 'first-unconstrained'
13
+
14
+ /** Explicit D1 session anchor: either a prior bookmark or a fresh consistency constraint. */
15
+ export type SessionAnchor = { readonly _tag: 'Bookmark'; readonly bookmark: string } | { readonly _tag: 'Constraint'; readonly constraint: SessionConstraint }
16
+
17
+ export const resolveAnchor = (bookmark: string | undefined, constraint: SessionConstraint = 'first-unconstrained'): SessionAnchor =>
18
+ constraint === 'first-primary'
19
+ ? { _tag: 'Constraint', constraint: 'first-primary' }
20
+ : bookmark
21
+ ? { _tag: 'Bookmark', bookmark }
22
+ : { _tag: 'Constraint', constraint }
23
+
24
+ export interface DbSessionHandle {
25
+ readonly all: (sql: string, params: ReadonlyArray<DbParam>) => Promise<ReadonlyArray<unknown>>
26
+ readonly first: (sql: string, params: ReadonlyArray<DbParam>) => Promise<unknown>
27
+ readonly run: (sql: string, params: ReadonlyArray<DbParam>) => Promise<void>
28
+ readonly batch: (statements: ReadonlyArray<Statement>) => Promise<ReadonlyArray<Applied>>
29
+ readonly getBookmark: () => string | null
30
+ }
31
+
32
+ /**
33
+ * Fiber-local active D1 session. Automatically used by `Database` and `AtomicBatch` when set.
34
+ * Detached background work (`waitUntil`) should clear this reference so it never races with the request bookmark.
35
+ */
36
+ export const CurrentDbSession = Context.Reference<DbSessionHandle | undefined>('app/db/CurrentDbSession', {
37
+ defaultValue: () => undefined,
38
+ })
39
+
40
+ export interface WithSessionOptions {
41
+ /** Bookmark from a prior request (cookie or `x-d1-bookmark` header) for read-your-writes consistency. */
42
+ readonly bookmark?: string | undefined
43
+ /** Initial routing constraint when no bookmark is supplied, or `'first-primary'` to force primary routing. Defaults to `'first-unconstrained'`. */
44
+ readonly constraint?: SessionConstraint | undefined
45
+ /** Invoked after the effect settles whenever the session produced a bookmark. */
46
+ readonly onBookmark?: ((bookmark: string) => void) | undefined
47
+ }
48
+
49
+ /**
50
+ * Optional Cloudflare D1 Sessions API (`env.DB.withSession`) port for global read replication.
51
+ * Disabled by default (`d1Sessions: false`); when enabled, all `Database` and `AtomicBatch` calls inside
52
+ * `withDbSession` share one sequentially consistent session and emit an updated bookmark.
53
+ */
54
+ export class DbSession extends Context.Service<
55
+ DbSession,
56
+ {
57
+ readonly enabled: boolean
58
+ readonly withSession: <A, E, R>(effect: Effect.Effect<A, E, R>, options?: WithSessionOptions) => Effect.Effect<A, E, R>
59
+ }
60
+ >()('app/platform/DbSession') {
61
+ static readonly disabled = Layer.succeed(
62
+ DbSession,
63
+ DbSession.of({
64
+ enabled: false,
65
+ withSession: (effect) => effect,
66
+ }),
67
+ )
68
+
69
+ static readonly make = (open: (anchor: SessionAnchor) => DbSessionHandle) =>
70
+ DbSession.of({
71
+ enabled: true,
72
+ withSession: (effect, options) =>
73
+ Effect.suspend(() => {
74
+ const handle = open(resolveAnchor(options?.bookmark, options?.constraint))
75
+ return effect.pipe(
76
+ Effect.provideService(CurrentDbSession, handle),
77
+ Effect.ensuring(
78
+ Effect.sync(() => {
79
+ const next = handle.getBookmark()
80
+ if (next && options?.onBookmark) options.onBookmark(next)
81
+ }),
82
+ ),
83
+ )
84
+ }),
85
+ })
86
+
87
+ /** Test/SQLite adapter over `db0`: runs queries against local SQLite and emits synthetic monotonic bookmarks. */
88
+ static readonly layerFor = (
89
+ db: Db0,
90
+ options: {
91
+ readonly enabled?: boolean
92
+ readonly onOpen?: (anchor: SessionAnchor) => void
93
+ } = {},
94
+ ) => {
95
+ if (options.enabled === false) return DbSession.disabled
96
+ let txQueue: Promise<unknown> = Promise.resolve()
97
+ const serializeTx = <A>(work: () => Promise<A>): Promise<A> => {
98
+ const next = txQueue.then(work, work)
99
+ txQueue = next.then(
100
+ () => undefined,
101
+ () => undefined,
102
+ )
103
+ return next
104
+ }
105
+ let version = 0
106
+ return Layer.succeed(
107
+ DbSession,
108
+ DbSession.make((anchor) => {
109
+ options.onOpen?.(anchor)
110
+ let bookmark: string | null = anchor._tag === 'Bookmark' ? anchor.bookmark : null
111
+ const touch = () => {
112
+ version += 1
113
+ bookmark = `sqlite-bm-${version}`
114
+ }
115
+ return {
116
+ all: async (sql, params) => {
117
+ const rows = await db
118
+ .prepare(sql)
119
+ .bind(...params)
120
+ .all()
121
+ touch()
122
+ return rows
123
+ },
124
+ first: async (sql, params) => {
125
+ const row = await db
126
+ .prepare(sql)
127
+ .bind(...params)
128
+ .get()
129
+ touch()
130
+ return row
131
+ },
132
+ run: async (sql, params) => {
133
+ await db
134
+ .prepare(sql)
135
+ .bind(...params)
136
+ .run()
137
+ touch()
138
+ },
139
+ batch: (statements) =>
140
+ serializeTx(async () => {
141
+ await db.exec('BEGIN')
142
+ try {
143
+ const applied: Applied[] = []
144
+ for (const { sql, params = [] } of statements) {
145
+ // Transaction statements execute sequentially on one SQLite connection.
146
+ // oxlint-disable-next-line eslint/no-await-in-loop
147
+ const result = await db
148
+ .prepare(sql)
149
+ .bind(...params)
150
+ .run()
151
+ const changes = readKey(result, 'changes')
152
+ applied.push({ changes: typeof changes === 'number' || typeof changes === 'bigint' ? Number(changes) : 0 })
153
+ }
154
+ await db.exec('COMMIT')
155
+ touch()
156
+ return applied
157
+ } catch (error) {
158
+ await db.exec('ROLLBACK')
159
+ throw error
160
+ }
161
+ }),
162
+ getBookmark: () => bookmark,
163
+ }
164
+ }),
165
+ )
166
+ }
167
+ }
168
+
169
+ /** Runs `effect` inside a D1 read-replication session when `d1Sessions` is enabled; no-op passthrough otherwise. */
170
+ export const withDbSession = <A, E, R>(effect: Effect.Effect<A, E, R>, options?: WithSessionOptions): Effect.Effect<A, E, R | DbSession> =>
171
+ DbSession.use((sessions) => sessions.withSession(effect, options))