refactor(session): share SQLite routing checks and record validation
One ENOENT helper, one routing-database check owned by the store, one routing-record reader that validates identity, and one publication failure wrapper replace the copies spread across the store and the service.
This commit is contained in:
1 parent
92d1100c24
commit
ed2b030a84
2 files changed
+49
-53
No files matched your search
@@ -13,7 +13,7 @@ import type { SessionAccess, SessionPersistenceCreateOptions, SessionPersistence
|
||||
import { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type { SessionHeader } from '@deepseek-ai/dsh-session'
|
||||
import { publishNewFileWin32, ensureDurableDirectoryWin32 } from './win32.ts'
|
||||
import { SqliteLogs } from './sqlite.ts'
|
||||
import { SqliteLogs, isAbsent } from './sqlite.ts'
|
||||
import { SessionWriteLease } from './lease.ts'
|
||||
import { sessionDir } from './paths.ts'
|
||||
import { LegacySessionMigration } from './migration.ts'
|
||||
@@ -80,20 +80,15 @@ export class TracePersistence extends SessionPersistence {
|
||||
return join(this.directory, `${createHash('sha256').update(id).digest('hex')}.json`)
|
||||
}
|
||||
|
||||
private parseMarker(text: string, path: string) {
|
||||
try { return marker.parse(JSON.parse(text)) }
|
||||
/** Decode one routing record and require it to name `id` in the configured database. */
|
||||
private readMarker(text: string, path: string, id: SessionId): void {
|
||||
let stored: z.infer<typeof marker>
|
||||
try { stored = marker.parse(JSON.parse(text)) }
|
||||
catch (error: unknown) {
|
||||
throw new HarnessError(`Stored Segment routing record is invalid: ${path}`, 'SESSION_STORAGE_CORRUPT', { cause: error })
|
||||
}
|
||||
}
|
||||
|
||||
private async assertRoutingDatabase(): Promise<void> {
|
||||
if (await this.sqlite.hasDatabase()) return
|
||||
let names: string[]
|
||||
try { names = await readdir(this.directory) }
|
||||
catch (error: unknown) { if (isAbsent(error)) return; throw error }
|
||||
if (names.some(name => name.endsWith('.json'))) {
|
||||
throw new HarnessError('The Segment database is missing but routing records remain; restore the database before creating Sessions', 'SESSION_STORAGE_MISSING')
|
||||
if (stored.id !== id || stored.database !== this.sqlite.path) {
|
||||
throw new HarnessError('Recorded Segment storage differs from the configured database; restore the original configuration', 'SESSION_STORAGE_IDENTITY')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,14 +97,11 @@ export class TracePersistence extends SessionPersistence {
|
||||
try { text = await readFile(this.markerPath(id), 'utf8') }
|
||||
catch (error: unknown) {
|
||||
if (!isAbsent(error)) throw error
|
||||
await this.assertRoutingDatabase()
|
||||
await this.sqlite.assertRoutingDatabase()
|
||||
return this.sqlite.stat(id, signal)
|
||||
}
|
||||
const selected = this.parseMarker(text, this.markerPath(id))
|
||||
await this.assertRoutingDatabase()
|
||||
if (selected.id !== id || selected.database !== this.sqlite.path) {
|
||||
throw new HarnessError('Recorded Segment storage differs from the configured database; restore the original configuration', 'SESSION_STORAGE_IDENTITY')
|
||||
}
|
||||
this.readMarker(text, this.markerPath(id), id)
|
||||
await this.sqlite.assertRoutingDatabase()
|
||||
const snapshot = await this.sqlite.stat(id, signal)
|
||||
if (snapshot === undefined) {
|
||||
if (!await this.sqlite.hasDatabase()) {
|
||||
@@ -130,8 +122,7 @@ export class TracePersistence extends SessionPersistence {
|
||||
else await mkdir(this.directory, { recursive: true, mode: 0o700 })
|
||||
const path = this.markerPath(id)
|
||||
try {
|
||||
const stored = this.parseMarker(await readFile(path, 'utf8'), path)
|
||||
if (stored.id !== id || stored.database !== this.sqlite.path) throw new HarnessError('Stored routing identity differs', 'SESSION_STORAGE_IDENTITY')
|
||||
this.readMarker(await readFile(path, 'utf8'), path, id)
|
||||
await this.syncDirectory()
|
||||
this.publishedRoutes.add(id)
|
||||
return
|
||||
@@ -146,8 +137,7 @@ export class TracePersistence extends SessionPersistence {
|
||||
else await link(temporary, path)
|
||||
} catch (error: unknown) {
|
||||
if (error !== null && typeof error === 'object' && 'code' in error && error.code === 'EEXIST') {
|
||||
const stored = this.parseMarker(await readFile(path, 'utf8'), path)
|
||||
if (stored.id !== id || stored.database !== this.sqlite.path) throw new HarnessError('Stored routing identity differs', 'SESSION_STORAGE_IDENTITY')
|
||||
this.readMarker(await readFile(path, 'utf8'), path, id)
|
||||
} else throw error
|
||||
}
|
||||
await this.syncDirectory()
|
||||
@@ -165,7 +155,7 @@ export class TracePersistence extends SessionPersistence {
|
||||
options?.signal?.throwIfAborted()
|
||||
const snapshot = materializeCreateHeader(header)
|
||||
await this.start()
|
||||
await this.assertRoutingDatabase()
|
||||
await this.sqlite.assertRoutingDatabase()
|
||||
// SQLite rejects an existing row itself; only the retained JSONL identity needs this check.
|
||||
if (await this.jsonl.hasStoredJsonl(snapshot.id)) throw new SessionAlreadyExistsError(snapshot.id)
|
||||
return this.sqlite.create(snapshot, options)
|
||||
@@ -186,7 +176,7 @@ export class TracePersistence extends SessionPersistence {
|
||||
|
||||
async list(options?: SessionPersistenceListOptions) {
|
||||
options?.signal?.throwIfAborted()
|
||||
await this.assertRoutingDatabase()
|
||||
await this.sqlite.assertRoutingDatabase()
|
||||
// Routing records publish after their commit, so reading them first guarantees each one's row is in the later scan.
|
||||
let names: string[] = []
|
||||
try { names = await this.listLimit(async () => {
|
||||
@@ -212,7 +202,3 @@ export class TracePersistence extends SessionPersistence {
|
||||
|
||||
async flush(): Promise<void> { await this.sqlite.flush() }
|
||||
}
|
||||
|
||||
function isAbsent(error: unknown): boolean {
|
||||
return error !== null && typeof error === 'object' && 'code' in error && error.code === 'ENOENT'
|
||||
}
|
||||
@@ -59,6 +59,15 @@ const segmentRow = z.union([
|
||||
type Metadata = z.infer<typeof metadata>
|
||||
type Segment = z.infer<typeof segmentRow>
|
||||
|
||||
/**
|
||||
* Whether a filesystem rejection reports a missing path.
|
||||
* @param error - rejected value from a `node:fs` operation.
|
||||
* @returns true for `ENOENT`.
|
||||
*/
|
||||
export function isAbsent(error: unknown): boolean {
|
||||
return error !== null && typeof error === 'object' && 'code' in error && error.code === 'ENOENT'
|
||||
}
|
||||
|
||||
/** Normalize one rejected value for error causes and close-failure aggregation. */
|
||||
function asError(error: unknown): Error {
|
||||
/* v8 ignore next -- rejected values are normally Error; normalize a hostile rejection. */
|
||||
@@ -149,28 +158,26 @@ export class SqliteLogs {
|
||||
})
|
||||
}
|
||||
|
||||
private async assertNewDatabase(): Promise<void> {
|
||||
/**
|
||||
* Refuse to use or create a database while routing records claim one that is missing.
|
||||
* @returns resolves when the database file exists or no routing record requires it.
|
||||
*/
|
||||
async assertRoutingDatabase(): Promise<void> {
|
||||
if (this.ready !== undefined || await this.databaseFileExists()) return
|
||||
let records: string[]
|
||||
try { records = await readdir(join(this.legacyRoot, '.segments')) }
|
||||
catch (error: unknown) {
|
||||
if (error !== null && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') return
|
||||
if (isAbsent(error)) return
|
||||
throw error
|
||||
}
|
||||
if (!records.some(record => record.endsWith('.json'))) return
|
||||
// Another initializer may have created the database while routing records were read.
|
||||
try { await stat(this.path) }
|
||||
catch (error: unknown) {
|
||||
if (error === null || typeof error !== 'object' || !('code' in error) || error.code !== 'ENOENT') throw error
|
||||
throw new HarnessError('The Segment database is missing but routing records remain; restore the database before writing', 'SESSION_STORAGE_MISSING')
|
||||
}
|
||||
if (await this.databaseFileExists()) return
|
||||
throw new HarnessError('The Segment database is missing but routing records remain; restore the database before using Sessions', 'SESSION_STORAGE_MISSING')
|
||||
}
|
||||
|
||||
private async initialize(): Promise<DatabaseSync> {
|
||||
try { await stat(this.path) }
|
||||
catch (error: unknown) {
|
||||
if (error !== null && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') await this.assertNewDatabase()
|
||||
else throw error
|
||||
}
|
||||
await this.assertRoutingDatabase()
|
||||
await this.ensureDirectory(dirname(this.path))
|
||||
// Retain the routing directory before the first Session commit.
|
||||
await this.ensureDirectory(join(this.legacyRoot, '.segments'))
|
||||
@@ -407,7 +414,7 @@ export class SqliteLogs {
|
||||
this.creating.add(meta.id)
|
||||
try {
|
||||
if (await this.stat(meta.id) !== undefined) throw new SessionAlreadyExistsError(meta.id)
|
||||
if (!await this.exists()) await this.assertNewDatabase()
|
||||
await this.assertRoutingDatabase()
|
||||
this.check()
|
||||
options?.signal?.throwIfAborted()
|
||||
this.pendingCreates.set(meta.id, { header: meta, inheritedCount, head: segmentId(randomUUID()) })
|
||||
@@ -488,9 +495,14 @@ export class SqliteLogs {
|
||||
const insert = this.statement(db, 'INSERT INTO events (segment_uuid, seq, payload) VALUES (?, ?, ?)')
|
||||
for (const [seq, payload] of payloads.entries()) insert.run(head, seq, payload)
|
||||
})
|
||||
try { await this.published(header.id) }
|
||||
await this.route(header.id)
|
||||
}
|
||||
|
||||
/** Publish routing after a commit; the committed rows stay authoritative when publication fails. */
|
||||
private async route(id: SessionId): Promise<void> {
|
||||
try { await this.published(id) }
|
||||
catch (error: unknown) {
|
||||
throw new HarnessError('Legacy Session committed, but routing publication failed; reopen the Session',
|
||||
throw new HarnessError('Session history committed, but routing publication failed; close and reopen the Session',
|
||||
'SESSION_STORAGE_PUBLICATION', { cause: error })
|
||||
}
|
||||
}
|
||||
@@ -656,8 +668,7 @@ export class SqliteLogs {
|
||||
for (const [index, payload] of payloads.entries()) insert.run(row.tail_segment_uuid, start + index, payload)
|
||||
})
|
||||
this.pendingCreates.delete(header.id)
|
||||
try { await this.published(header.id) }
|
||||
catch (error: unknown) { throw new HarnessError('Events committed, but routing publication failed; close and reopen the Session', 'SESSION_STORAGE_PUBLICATION', { cause: error }) }
|
||||
await this.route(header.id)
|
||||
}
|
||||
|
||||
private ensureRow(db: DatabaseSync, header: SessionHeader): Metadata {
|
||||
@@ -690,11 +701,7 @@ export class SqliteLogs {
|
||||
const db = await this.database()
|
||||
this.transaction(db, () => { this.ensureRow(db, header) })
|
||||
this.pendingCreates.delete(header.id)
|
||||
try { await this.published(header.id) }
|
||||
catch (error: unknown) {
|
||||
throw new HarnessError('Session committed, but routing publication failed; close and reopen the Session',
|
||||
'SESSION_STORAGE_PUBLICATION', { cause: error })
|
||||
}
|
||||
await this.route(header.id)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -722,15 +729,18 @@ export class SqliteLogs {
|
||||
revision: SessionPersistenceRevision(`${row.tail_segment_uuid}:${row.event_count}`) }
|
||||
}
|
||||
|
||||
private async exists(): Promise<boolean> {
|
||||
if (this.ready !== undefined) return true
|
||||
private async databaseFileExists(): Promise<boolean> {
|
||||
try { await stat(this.path); return true }
|
||||
catch (error: unknown) {
|
||||
if (error !== null && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') return false
|
||||
if (isAbsent(error)) return false
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private async exists(): Promise<boolean> {
|
||||
return this.ready !== undefined || this.databaseFileExists()
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the configured database file exists without opening or creating it.
|
||||
* @returns true when the database file exists.
|
||||
|
||||
Reference in new issue
Block a user