Repository navigation
Expand file tree
/
Copy pathsingle-unit.ts
More file actions
148 lines (136 loc) · 5.17 KB
/
Copy pathsingle-unit.ts
File metadata and controls
148 lines (136 loc) · 5.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
/**
* One opened JSON unit in `single` layout: the whole unit is one document at
* `<root>/<name>.json`. The in-memory state is authoritative; every write
* primitive mutates it and republishes the whole file atomically. Writes are
* NOT queued here — per the backend contract, write ordering belongs to the
* caller (the domain layer's write chain); this unit only guarantees that
* each single call publishes a complete, durable file. The `per-record`
* layout is a separate unit class in `per-record-unit.ts`.
* @module @deepseek-ai/dsh-storage-json/src/single-unit
*/
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import { StorageError } from '@deepseek-ai/dsh-storage'
import type { KvUnit, KvUnitDescriptor } from '@deepseek-ai/dsh-storage'
import { writeAtomic } from './atomic.ts'
import { parse, serialize } from './format.ts'
import type { UnitState } from './format.ts'
/**
* Open (load or lazily create) one `single`-layout unit under `root`: the
* unit file is `<root>/<name>.json`.
* @param descriptor - Static identity and shape of the unit.
* @param root - Absolute backend root directory.
* @param onClose - Backend callback releasing the unit's open-slot.
* @returns the opened unit.
*/
export async function openSingleUnit(
descriptor: KvUnitDescriptor,
root: string,
onClose: () => void,
): Promise<KvUnit> {
const path = join(root, `${descriptor.name}.json`)
let text: string | undefined
try {
text = await readFile(path, 'utf8')
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
// Missing file = empty unit; materialization defers to the first write.
}
const state: UnitState =
text === undefined
? {
version: descriptor.version,
global: null,
tables: new Map(descriptor.tables.map(table => [table, new Map<string, unknown>()])),
}
: parse(text, descriptor)
return new SingleJsonUnit(descriptor, path, state, onClose)
}
class SingleJsonUnit implements KvUnit {
private closed = false
/** In-flight publishes; close() drains them before releasing the unit. */
private readonly inFlight = new Set<Promise<void>>()
constructor(
private readonly descriptor: KvUnitDescriptor,
private readonly path: string,
private readonly state: UnitState,
private readonly onClose: () => void,
) {}
// oxlint-disable-next-line typescript/require-await -- async keeps the closed guard a rejection, not a synchronous throw
async loadAll(): Promise<{ tables: Record<string, Record<string, unknown>>; global: unknown }> {
this.assertOpen()
const tables: Record<string, Record<string, unknown>> = {}
for (const [table, records] of this.state.tables) {
tables[table] = Object.fromEntries(records)
}
return { tables, global: this.state.global }
}
async putRecord(table: string, key: string, value: unknown): Promise<void> {
this.assertOpen()
const records = this.records(table)
const hadKey = records.has(key)
const previous = records.get(key)
records.set(key, value)
// Roll back on a failed publish: memory is authoritative, so a rejected
// write must not survive in memory (or ride along with the next publish).
await this.publish().catch((error: unknown) => {
if (hadKey) records.set(key, previous)
else records.delete(key)
throw error
})
}
async deleteRecord(table: string, key: string): Promise<void> {
this.assertOpen()
const records = this.records(table)
if (!records.has(key)) return
const previous = records.get(key)
records.delete(key)
await this.publish().catch((error: unknown) => {
records.set(key, previous)
throw error
})
}
async setGlobal(value: unknown): Promise<void> {
this.assertOpen()
if (!this.descriptor.hasGlobal) {
throw new Error(`unit '${this.descriptor.name}' does not declare a global slot`)
}
const previous = this.state.global
this.state.global = value
await this.publish().catch((error: unknown) => {
this.state.global = previous
throw error
})
}
/* jscpd:ignore-start -- the two unit classes are standalone; the drain/guard lifecycle mirrors the shared KvUnit contract */
async close(): Promise<void> {
if (this.closed) {
await Promise.allSettled(this.inFlight)
return
}
this.closed = true
await Promise.allSettled(this.inFlight)
this.onClose()
}
private assertOpen(): void {
if (this.closed) {
throw new StorageError('closed', `unit '${this.descriptor.name}' is closed`)
}
}
/* jscpd:ignore-end */
private records(table: string): Map<string, unknown> {
const records = this.state.tables.get(table)
if (!records) {
throw new Error(`unit '${this.descriptor.name}' does not declare table '${table}'`)
}
return records
}
private publish(): Promise<void> {
const write = writeAtomic(this.path, serialize(this.descriptor.name, this.state))
this.inFlight.add(write)
// Swallow only on the tracking branch: the caller still awaits `write`
// itself, so rejections stay observed exactly once.
write.catch(() => {}).finally(() => this.inFlight.delete(write))
return write
}
}