index.ts 9.4 KB

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