index.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. /**
  2. * SQLite durable session-persistence backend. It maps each session header and
  3. * event to rows, and delegates write-path orchestration to
  4. * {@link PersistenceCoordinator}.
  5. * @module @deepseek-ai/dsh-session-persistence-sqlite
  6. */
  7. import { Context } from 'cordis'
  8. import z from 'schemastery'
  9. import { DatabaseSync } from 'node:sqlite'
  10. import { mkdir } from 'node:fs/promises'
  11. import { dirname, resolve } from 'node:path'
  12. import {
  13. SessionPersistence, PersistenceCoordinator,
  14. type PersistenceBackend, type StoredPrefix,
  15. } from '@deepseek-ai/dsh-session-persistence'
  16. import type { Session, SessionEvent, SurfaceEventType, SessionId, SessionHeader } from '@deepseek-ai/dsh-session'
  17. import {
  18. type JournalMode, openDatabase, rowToMeta, scanRows, type EventRow, type SessionRow,
  19. } from './schema.ts'
  20. export { SCHEMA_VERSION } from './schema.ts'
  21. /**
  22. * Serialize an event's surface-metadata fields for SQL binding. Both fields are
  23. * nullable TEXT columns — null when the event has no surface metadata (non-surface
  24. * events, events written before surface support).
  25. */
  26. function surfaceBindings(event: SessionEvent): [string | null, string | null] {
  27. const se = event as SessionEvent<SurfaceEventType>
  28. return [
  29. se.sourceEventSeqs ? JSON.stringify(se.sourceEventSeqs) : null,
  30. se.surfaceOp !== undefined ? JSON.stringify(se.surfaceOp) : null,
  31. ]
  32. }
  33. /** Plugin configuration. */
  34. export interface Config {
  35. /**
  36. * Filesystem path to the SQLite database file. The special value `:memory:`
  37. * opens an in-process database (tests); a file path is created (with parent
  38. * dirs) on construction.
  39. */
  40. path: string
  41. /**
  42. * SQLite `journal_mode` pragma. `wal` (the default) is the recorded
  43. * durability model; pick a rollback-journal mode (`delete`/`truncate`/
  44. * `persist`) on filesystems where WAL's shared-memory files do not work
  45. * (network mounts). See {@link JournalMode}.
  46. */
  47. journalMode?: JournalMode
  48. }
  49. /**
  50. * The SQLite persistence backend. Load as a plugin; it registers as
  51. * `ctx.sessionPersistence` and (via the coordinator) installs the write-path
  52. * listeners. Its torn-tail marker is the seq to delete from.
  53. */
  54. export class SessionPersistenceSqlite extends SessionPersistence implements PersistenceBackend<number> {
  55. static inject = ['sessions']
  56. static Config: z<Config> = z.object({
  57. path: z.string().required(),
  58. journalMode: z.union(['wal', 'delete', 'truncate', 'persist'] as const).default('wal'),
  59. })
  60. /**
  61. * Backend label for the coordinator's dispose diagnostics. Intentionally
  62. * shadows cordis `Service.name` (set to `'sessionPersistence'` by the base);
  63. * see the JSONL backend for why this does not affect service resolution.
  64. */
  65. override readonly name = 'session-persistence-sqlite'
  66. private db!: DatabaseSync
  67. private ready: Promise<void>
  68. private coordinator: PersistenceCoordinator<number>
  69. constructor(ctx: Context, public config: Config) {
  70. super(ctx)
  71. // Open asynchronously so directory creation does not block plugin apply;
  72. // every storage hook awaits the same readiness promise.
  73. this.ready = this.openDb(config.path, (config as Required<Config>).journalMode)
  74. this.coordinator = new PersistenceCoordinator<number>(this.ctx, this)
  75. }
  76. private async openDb(path: string, journalMode: JournalMode): Promise<void> {
  77. if (path !== ':memory:') {
  78. const abs = resolve(path)
  79. await mkdir(dirname(abs), { recursive: true, mode: 0o700 })
  80. this.db = openDatabase(abs, journalMode)
  81. } else {
  82. this.db = openDatabase(path, journalMode)
  83. }
  84. }
  85. // --- SessionPersistence service surface (delegated to the coordinator) ---
  86. create(meta: SessionHeader): Promise<void> {
  87. return this.coordinator.create(meta)
  88. }
  89. append(id: SessionId, events: readonly SessionEvent[]): Promise<void> {
  90. return this.coordinator.append(id, events)
  91. }
  92. load(id: SessionId): Promise<{ meta: SessionHeader; events: SessionEvent[] }> {
  93. return this.coordinator.load(id)
  94. }
  95. // One method serves both public `list` and the backend hook; delegating it to
  96. // the coordinator would call this hook recursively.
  97. /**
  98. * The per-session init promises, exposed for white-box tests that await a
  99. * specific session's onCreated (there is no public API to await one init).
  100. */
  101. get inits(): Map<Session, Promise<void>> {
  102. return this.coordinator.inits
  103. }
  104. // --- PersistenceBackend hooks (the SQLite storage primitives) ---
  105. /** Read a stored prefix by id (ids are globally unique — no scope to scan). */
  106. loadStored(id: SessionId): Promise<StoredPrefix<number> | undefined> {
  107. return this.readPrefix(id)
  108. }
  109. /** Read a stored prefix; `cwd` is ignored (the id is globally unique in SQLite). */
  110. loadLive(id: SessionId, _cwd: string | undefined): Promise<StoredPrefix<number> | undefined> {
  111. return this.readPrefix(id)
  112. }
  113. /**
  114. * Read a session's row + ordered events into a {@link StoredPrefix}. The
  115. * torn-tail marker is the seq from which a never-committed tail must be deleted
  116. * (`scanRows` already returns it as `number | undefined`).
  117. */
  118. private async readPrefix(id: SessionId): Promise<StoredPrefix<number> | undefined> {
  119. await this.ready
  120. const row = this.rowFor(id)
  121. if (row === undefined) return undefined
  122. const meta = rowToMeta(row)
  123. const eventRows = this.db
  124. .prepare('SELECT seq, type, time, data, source_event_seqs, surface_op FROM events WHERE session_id = ? ORDER BY seq')
  125. .all(id) as unknown as EventRow[]
  126. const { preserved, tornFrom } = scanRows(eventRows)
  127. return { meta, events: preserved, ...tornFrom !== undefined ? { tornMarker: tornFrom } : {} }
  128. }
  129. /**
  130. * Durably append a batch in ONE transaction: materialize the sessions row (if
  131. * lazy) and INSERT every event, or roll back entirely. The transaction is the
  132. * atomicity + durability boundary, so a mid-batch failure (a UNIQUE violation
  133. * on a duplicated seq) leaves the stored log untouched.
  134. */
  135. async appendBatch(meta: SessionHeader, events: readonly SessionEvent[], isMaterialized: boolean): Promise<void> {
  136. await this.ready
  137. const insertEvent = this.db.prepare(
  138. 'INSERT INTO events (session_id, seq, type, time, data, source_event_seqs, surface_op) VALUES (?, ?, ?, ?, ?, ?, ?)',
  139. )
  140. this.db.exec('BEGIN')
  141. try {
  142. if (!isMaterialized) this.writeRow(meta)
  143. for (const event of events) {
  144. const [surfaceSeqs, surfaceOp] = surfaceBindings(event)
  145. insertEvent.run(meta.id, event.seq, event.type, event.time, JSON.stringify(event.data), surfaceSeqs, surfaceOp)
  146. }
  147. this.db.exec('COMMIT')
  148. } catch (error) {
  149. this.db.exec('ROLLBACK')
  150. throw error
  151. }
  152. }
  153. /**
  154. * Make a crash repair durable in ONE transaction: DELETE the torn tail (from
  155. * `tornMarker`) and INSERT the synthetic `closers`. After COMMIT the stored rows
  156. * == the balanced log.
  157. */
  158. async commitRepair(meta: SessionHeader, tornMarker: number | undefined, closers: readonly SessionEvent[]): Promise<void> {
  159. await this.ready
  160. this.db.exec('BEGIN')
  161. try {
  162. if (tornMarker !== undefined) {
  163. this.db.prepare('DELETE FROM events WHERE session_id = ? AND seq >= ?').run(meta.id, tornMarker)
  164. }
  165. if (closers.length > 0) {
  166. const insertEvent = this.db.prepare(
  167. 'INSERT INTO events (session_id, seq, type, time, data, source_event_seqs, surface_op) VALUES (?, ?, ?, ?, ?, ?, ?)',
  168. )
  169. for (const event of closers) {
  170. const [surfaceSeqs, surfaceOp] = surfaceBindings(event)
  171. insertEvent.run(meta.id, event.seq, event.type, event.time, JSON.stringify(event.data), surfaceSeqs, surfaceOp)
  172. }
  173. }
  174. this.db.exec('COMMIT')
  175. } catch (error) {
  176. // The DELETE+INSERT cannot collide (a row at a closer's seq is preserved or
  177. // deleted as torn first); this rolls back a DB-level failure (disk full,
  178. // etc.), unreachable in test.
  179. /* v8 ignore start */
  180. this.db.exec('ROLLBACK')
  181. throw error
  182. /* v8 ignore stop */
  183. }
  184. }
  185. /** List all materialized sessions' metadata (every row is a materialized session). */
  186. async list(): Promise<SessionHeader[]> {
  187. await this.ready
  188. const rows = this.db
  189. .prepare('SELECT * FROM sessions')
  190. .all() as unknown as SessionRow[]
  191. return rows.map(rowToMeta)
  192. }
  193. /** Close the database handle (awaited by the coordinator's dispose, post-drain). */
  194. async close(): Promise<void> {
  195. await this.ready
  196. this.db.close()
  197. }
  198. // --- row helpers ---
  199. /** Fetch a session's row, or undefined if absent. */
  200. private rowFor(id: SessionId): SessionRow | undefined {
  201. return this.db.prepare('SELECT * FROM sessions WHERE id = ?').get(id) as unknown as SessionRow | undefined
  202. }
  203. /**
  204. * Insert-or-replace a session's metadata row. The only caller is the first
  205. * materializing `appendBatch`, so writing the row IS the materialization (its
  206. * existence is the signal `list` reads).
  207. */
  208. private writeRow(meta: SessionHeader): void {
  209. this.db.prepare(`
  210. INSERT INTO sessions (id, version, created_at, cwd, parent_session, seed_length)
  211. VALUES (?, ?, ?, ?, ?, ?)
  212. ON CONFLICT(id) DO UPDATE SET
  213. version = excluded.version,
  214. created_at = excluded.created_at,
  215. cwd = excluded.cwd,
  216. parent_session = excluded.parent_session,
  217. seed_length = excluded.seed_length
  218. `).run(
  219. meta.id,
  220. meta.version,
  221. meta.createdAt,
  222. meta.cwd ?? null,
  223. meta.parentSession ?? null,
  224. meta.seedLength ?? null,
  225. )
  226. }
  227. }
  228. export default SessionPersistenceSqlite