31 lines
951 B
TypeScript
31 lines
951 B
TypeScript
import fs from 'node:fs/promises';
|
|
import path from 'node:path';
|
|
import type { ControlPlaneState } from '../../src/shared/contracts';
|
|
import { createDefaultState } from './config';
|
|
|
|
export class StateStore {
|
|
constructor(private readonly statePath: string) {}
|
|
|
|
async read(): Promise<ControlPlaneState> {
|
|
await fs.mkdir(path.dirname(this.statePath), { recursive: true });
|
|
|
|
try {
|
|
const raw = await fs.readFile(this.statePath, 'utf8');
|
|
return JSON.parse(raw) as ControlPlaneState;
|
|
} catch (error) {
|
|
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
|
|
throw error;
|
|
}
|
|
|
|
const fallback = createDefaultState();
|
|
await this.write(fallback);
|
|
return fallback;
|
|
}
|
|
}
|
|
|
|
async write(state: ControlPlaneState): Promise<void> {
|
|
await fs.mkdir(path.dirname(this.statePath), { recursive: true });
|
|
await fs.writeFile(this.statePath, `${JSON.stringify(state, null, 2)}\n`, 'utf8');
|
|
}
|
|
}
|