index.ts 9.9 KB

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