Align single-file store with CultCache v1 snapshots

This commit is contained in:
Meta Vens 2026-05-16 08:53:07 +01:00
commit 434c0c006e
17 changed files with 892 additions and 53 deletions

View file

@ -9,6 +9,7 @@ import type {
CultCacheDocumentRegistry,
CultCacheDocumentValue,
CultCacheEnvelope,
CultCacheSchemaCatalogEntry,
CultCacheStoreRegistration,
} from "./types";
@ -21,6 +22,7 @@ type RegisteredDefinition = {
readonly definition: AnyCultCacheDocumentDefinition;
readonly global: boolean;
readonly formatter: CultCacheDocumentFormatter<unknown>;
readonly catalogEntry: CultCacheSchemaCatalogEntry;
nameAccessor?: (value: unknown) => string | undefined;
readonly indexAccessors: Map<string, (value: unknown) => string | undefined>;
};
@ -71,6 +73,7 @@ export class CultCache {
static readonly GLOBAL_KEY = "__global__";
readonly #definitions = new Map<string, RegisteredDefinition>();
readonly #schemaIdDefinitions = new Map<string, RegisteredDefinition>();
readonly #entries = new Map<string, HydratedEntry>();
readonly #typeEntryIds = new Map<string, Set<string>>();
readonly #nameToKeyMaps = new Map<string, Map<string, string>>();
@ -94,6 +97,7 @@ export class CultCache {
definition,
global: definition.global === true,
formatter: this.#createFormatter(definition),
catalogEntry: this.#createCatalogEntry(definition),
nameAccessor: undefined,
indexAccessors: new Map<string, (value: unknown) => string | undefined>(),
};
@ -110,6 +114,13 @@ export class CultCache {
}
this.#definitions.set(definition.type, registered);
for (const schemaId of registered.catalogEntry.compatibleSchemaIds ?? [registered.catalogEntry.schemaId]) {
const existingBySchema = this.#schemaIdDefinitions.get(schemaId);
if (existingBySchema && existingBySchema !== registered) {
throw new Error(`CultCache schema id "${schemaId}" is already registered for type "${existingBySchema.definition.type}".`);
}
this.#schemaIdDefinitions.set(schemaId, registered);
}
this.#rebuildDefinitionLookups(registered);
return definition;
}
@ -179,9 +190,13 @@ export class CultCache {
const entries = await registration.store.pullAll();
for (const entry of entries) {
const registered = this.#definitions.get(entry.type);
const registered = this.#resolveDefinitionForEnvelope(entry);
if (!registered) {
throw new Error(`No schema is registered for persisted document type "${entry.type}".`);
throw new Error(
entry.schemaId
? `No schema is registered for persisted schema id "${entry.schemaId}".`
: `No schema is registered for persisted document type "${entry.type}".`,
);
}
const payload = this.#cloneBytes(entry.payload);
@ -358,6 +373,8 @@ export class CultCache {
type: definition.type,
payload: this.#cloneBytes(payload),
storedAt: new Date().toISOString(),
schemaId: registered.catalogEntry.schemaId,
catalogEntry: registered.catalogEntry,
};
const route = this.#resolveRoute(definition.type);
@ -402,6 +419,8 @@ export class CultCache {
type: envelope.type,
payload,
storedAt: envelope.storedAt,
schemaId: envelope.schemaId ?? registered.catalogEntry.schemaId,
catalogEntry: envelope.catalogEntry ?? registered.catalogEntry,
};
const route = this.#resolveRoute(definition.type);
@ -511,6 +530,52 @@ export class CultCache {
};
}
#createCatalogEntry(definition: AnyCultCacheDocumentDefinition): CultCacheSchemaCatalogEntry {
const schemaName = definition.schemaName ?? definition.type;
const schemaVersion = definition.schemaVersion ?? `${schemaName}.v1`;
const canonicalSchemaJson = definition.canonicalSchemaJson ?? JSON.stringify({
schemaName,
schemaVersion,
members: [...(definition.members ?? [])]
.sort((left, right) => left.slot - right.slot)
.map((member) => ({
slot: member.slot,
name: member.memberName,
type: member.typeName,
isReference: member.isReference === true,
many: member.isMany === true,
targetSchemaName: member.targetSchemaName ?? null,
indexAlias: member.indexAlias ?? null,
isName: member.isName === true,
})),
});
const schemaId = definition.schemaId ?? schemaName;
const compatibleSchemaIds = [
...new Set([schemaId, ...(definition.compatibleSchemaIds ?? [])]),
];
return {
schemaId,
schemaName,
schemaVersion,
contentHash: definition.contentHash ?? schemaId,
canonicalSchemaJson,
compatibleSchemaIds,
members: [...(definition.members ?? [])]
.sort((left, right) => left.slot - right.slot)
.map((member) => ({
slot: member.slot,
memberName: member.memberName,
typeName: member.typeName,
isReference: member.isReference === true,
isMany: member.isMany === true,
targetSchemaName: member.targetSchemaName ?? null,
isName: member.isName === true,
indexAlias: member.indexAlias ?? null,
})),
};
}
#enumerateDefinitionIndexes(
definition: AnyCultCacheDocumentDefinition,
): Array<[string, AccessorInput]> {
@ -576,6 +641,14 @@ export class CultCache {
return registered;
}
#resolveDefinitionForEnvelope(entry: CultCacheEnvelope): RegisteredDefinition | undefined {
if (entry.schemaId) {
return this.#schemaIdDefinitions.get(entry.schemaId);
}
return this.#definitions.get(entry.type);
}
#resolveRoute(type: string): StoreRoute {
const typeSpecific = this.#stores.filter((registration) => registration.types.includes(type));
if (typeSpecific.length > 0) {
@ -618,6 +691,8 @@ export class CultCache {
const hydrated: HydratedEntry = {
...entry,
payload: this.#cloneBytes(entry.payload),
schemaId: entry.schemaId ?? registered.catalogEntry.schemaId,
catalogEntry: entry.catalogEntry ?? registered.catalogEntry,
value,
};
this.#entries.set(entryId, hydrated);
@ -769,6 +844,8 @@ export class CultCache {
type: entry.type,
payload: this.#cloneBytes(entry.payload),
storedAt: entry.storedAt,
schemaId: entry.schemaId,
catalogEntry: entry.catalogEntry,
};
}

View file

@ -12,6 +12,18 @@ export function defineDocumentType<TSchema extends CultCacheSchema>(
throw new Error("CultCache document types must declare a non-empty type.");
}
for (const [fieldName, fieldValue] of [
["schemaId", definition.schemaId],
["schemaName", definition.schemaName],
["schemaVersion", definition.schemaVersion],
["contentHash", definition.contentHash],
["canonicalSchemaJson", definition.canonicalSchemaJson],
] as const) {
if (fieldValue !== undefined && fieldValue.trim().length === 0) {
throw new Error(`CultCache document type "${definition.type}" declares an empty ${fieldName}.`);
}
}
if (definition.name !== undefined && typeof definition.name !== "string" && typeof definition.name !== "function") {
throw new Error(`CultCache document type "${definition.type}" declares an invalid name accessor.`);
}
@ -35,6 +47,25 @@ export function defineDocumentType<TSchema extends CultCacheSchema>(
}
}
if (definition.members) {
const seenSlots = new Set<number>();
for (const member of definition.members) {
if (!Number.isInteger(member.slot) || member.slot < 0) {
throw new Error(`CultCache document type "${definition.type}" declares an invalid schema member slot.`);
}
if (seenSlots.has(member.slot)) {
throw new Error(`CultCache document type "${definition.type}" declares duplicate schema member slot ${member.slot}.`);
}
seenSlots.add(member.slot);
if (!member.memberName || member.memberName.trim().length === 0) {
throw new Error(`CultCache document type "${definition.type}" declares a schema member with an empty name.`);
}
if (!member.typeName || member.typeName.trim().length === 0) {
throw new Error(`CultCache document type "${definition.type}" declares schema member "${member.memberName}" with an empty type.`);
}
}
}
return Object.freeze({ ...definition });
}

View file

@ -10,6 +10,8 @@ export type {
CultCacheDocumentFormatter,
CultCacheDocumentIndexDefinition,
CultCacheDocumentRegistry,
CultCacheSchemaCatalogEntry,
CultCacheSchemaCatalogMember,
CultCacheSchema,
CultCacheDocumentValue,
CultCacheEnvelope,

View file

@ -4,13 +4,22 @@ import { dirname, resolve } from "node:path";
import { decode, encode } from "@msgpack/msgpack";
import { z } from "zod";
import type { CacheBackingStore, CultCacheEnvelope, PushAllOptions } from "./types";
import type {
CacheBackingStore,
CultCacheEnvelope,
CultCacheSchemaCatalogEntry,
CultCacheSchemaCatalogMember,
PushAllOptions,
} from "./types";
const STORE_FORMAT_VERSION = "cultcache.store.v1";
const envelopeSchema = z.object({
key: z.string().min(1),
type: z.string().min(1),
payload: z.instanceof(Uint8Array),
storedAt: z.string().min(1),
schemaId: z.string().min(1).optional(),
});
const envelopeArraySchema = z.array(envelopeSchema);
@ -35,26 +44,54 @@ export class SingleFileMessagePackBackingStore implements CacheBackingStore {
async pullAll(): Promise<CultCacheEnvelope[]> {
try {
const data = await readFile(this.filePath);
const decoded = legacyEnvelopeArraySchema.parse(decode(data));
let repairedLegacyPayload = false;
const normalized = decoded.map((entry) => {
const payload = normalizePayload(entry.payload);
if (payload !== entry.payload) {
repairedLegacyPayload = true;
}
return {
...entry,
payload,
};
});
const parsed = envelopeArraySchema.parse(normalized) as CultCacheEnvelope[];
if (repairedLegacyPayload) {
await this.#writeAll(parsed);
if (data.length === 0) {
return [];
}
return parsed;
const decoded = decode(data);
const snapshot = decodeSnapshot(decoded);
if (snapshot) {
return snapshot.records.map((record) => {
const catalogEntry = snapshot.catalogBySchemaId.get(record.schemaId);
if (!catalogEntry) {
throw new Error(`CultCache persisted record "${record.key}" references missing schema id "${record.schemaId}".`);
}
return {
key: record.key,
type: catalogEntry.schemaName,
schemaId: record.schemaId,
catalogEntry,
payload: record.payload,
storedAt: record.storedAt,
};
});
}
const legacy = decodeLegacyEnvelopeArray(decoded);
if (legacy) {
let repairedLegacyPayload = false;
const normalized = legacy.map((entry) => {
const payload = normalizePayload(entry.payload);
if (payload !== entry.payload) {
repairedLegacyPayload = true;
}
return {
...entry,
payload,
};
});
const parsed = envelopeArraySchema.parse(normalized) as CultCacheEnvelope[];
if (repairedLegacyPayload) {
await this.#writeAll(parsed);
}
return parsed;
}
throw new Error(`CultCache file ${this.filePath} is not a recognized CultCache MessagePack store.`);
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code === "ENOENT") {
@ -128,7 +165,7 @@ export class SingleFileMessagePackBackingStore implements CacheBackingStore {
.slice(2)}`;
try {
await writeFile(tempPath, encode(entries));
await writeFile(tempPath, encode(encodeSnapshot(entries)));
await rename(tempPath, this.filePath);
} catch (error) {
await rm(tempPath, { force: true }).catch(() => undefined);
@ -137,6 +174,222 @@ export class SingleFileMessagePackBackingStore implements CacheBackingStore {
}
}
type PersistedRecord = {
key: string;
schemaId: string;
storedAt: string;
payload: Uint8Array;
};
type DecodedSnapshot = {
catalogBySchemaId: Map<string, CultCacheSchemaCatalogEntry>;
records: PersistedRecord[];
};
function encodeSnapshot(entries: CultCacheEnvelope[]): unknown[] {
const catalog = [...catalogEntriesFor(entries).values()]
.sort((left, right) => compareOrdinal(left.schemaName, right.schemaName));
const records = [...entries]
.sort((left, right) => compareOrdinal(left.key, right.key))
.map((entry) => [
entry.key,
schemaIdForEnvelope(entry),
entry.storedAt,
entry.payload,
]);
return [
STORE_FORMAT_VERSION,
catalog.map(encodeCatalogEntry),
records,
];
}
function catalogEntriesFor(entries: CultCacheEnvelope[]): Map<string, CultCacheSchemaCatalogEntry> {
const catalog = new Map<string, CultCacheSchemaCatalogEntry>();
for (const entry of entries) {
const schemaId = schemaIdForEnvelope(entry);
if (!catalog.has(schemaId)) {
catalog.set(schemaId, entry.catalogEntry ?? {
schemaId,
schemaName: entry.type,
schemaVersion: `${entry.type}.v1`,
contentHash: schemaId,
canonicalSchemaJson: JSON.stringify({
schemaName: entry.type,
schemaVersion: `${entry.type}.v1`,
members: [],
}),
compatibleSchemaIds: [schemaId],
members: [],
});
}
}
return catalog;
}
function schemaIdForEnvelope(entry: CultCacheEnvelope): string {
return entry.schemaId ?? entry.type;
}
function encodeCatalogEntry(entry: CultCacheSchemaCatalogEntry): unknown[] {
return [
entry.schemaId,
entry.schemaName,
entry.schemaVersion,
entry.contentHash,
entry.canonicalSchemaJson,
[...(entry.compatibleSchemaIds ?? [entry.schemaId])],
[...(entry.members ?? [])].map(encodeCatalogMember),
];
}
function encodeCatalogMember(member: CultCacheSchemaCatalogMember): unknown[] {
return [
member.slot,
member.memberName,
member.typeName,
member.isReference === true,
member.isMany === true,
member.targetSchemaName ?? null,
member.isName === true,
member.indexAlias ?? null,
];
}
function decodeSnapshot(decoded: unknown): DecodedSnapshot | undefined {
if (!Array.isArray(decoded) || decoded.length === 0 || decoded[0] !== STORE_FORMAT_VERSION) {
return undefined;
}
const catalogRaw = decoded[1];
const recordsRaw = decoded[2];
if (!Array.isArray(catalogRaw) || !Array.isArray(recordsRaw)) {
throw new Error("CultCache v1 snapshot must contain a schema catalog and record array.");
}
const catalogBySchemaId = new Map<string, CultCacheSchemaCatalogEntry>();
for (const entry of catalogRaw) {
const catalogEntry = decodeCatalogEntry(entry);
catalogBySchemaId.set(catalogEntry.schemaId, catalogEntry);
for (const compatibleSchemaId of catalogEntry.compatibleSchemaIds ?? []) {
catalogBySchemaId.set(compatibleSchemaId, catalogEntry);
}
}
const records = recordsRaw.map(decodeRecord);
return { catalogBySchemaId, records };
}
function decodeCatalogEntry(value: unknown): CultCacheSchemaCatalogEntry {
if (!Array.isArray(value)) {
throw new Error("CultCache schema catalog entries must be MessagePack arrays.");
}
const [
schemaId = "",
schemaName = "",
schemaVersion = "",
contentHash = "",
canonicalSchemaJson = "",
compatibleSchemaIds = [],
members = [],
] = value;
if (!isNonEmptyString(schemaId) || !isNonEmptyString(schemaName)) {
throw new Error("CultCache schema catalog entries must declare schemaId and schemaName.");
}
if (!Array.isArray(compatibleSchemaIds) || !compatibleSchemaIds.every(isNonEmptyString)) {
throw new Error(`CultCache schema catalog entry "${schemaId}" has invalid compatible schema ids.`);
}
if (!Array.isArray(members)) {
throw new Error(`CultCache schema catalog entry "${schemaId}" has invalid members.`);
}
return {
schemaId,
schemaName,
schemaVersion: isNonEmptyString(schemaVersion) ? schemaVersion : `${schemaName}.v1`,
contentHash: isNonEmptyString(contentHash) ? contentHash : schemaId,
canonicalSchemaJson: typeof canonicalSchemaJson === "string" ? canonicalSchemaJson : "",
compatibleSchemaIds,
members: members.map(decodeCatalogMember),
};
}
function decodeCatalogMember(value: unknown): CultCacheSchemaCatalogMember {
if (!Array.isArray(value)) {
throw new Error("CultCache schema catalog members must be MessagePack arrays.");
}
const [
slot = -1,
memberName = "",
typeName = "",
isReference = false,
isMany = false,
targetSchemaName = null,
isName = false,
indexAlias = null,
] = value;
if (!Number.isInteger(slot) || slot < 0 || !isNonEmptyString(memberName) || !isNonEmptyString(typeName)) {
throw new Error("CultCache schema catalog member has invalid slot, name, or type.");
}
return {
slot,
memberName,
typeName,
isReference: isReference === true,
isMany: isMany === true,
targetSchemaName: typeof targetSchemaName === "string" ? targetSchemaName : null,
isName: isName === true,
indexAlias: typeof indexAlias === "string" ? indexAlias : null,
};
}
function decodeRecord(value: unknown): PersistedRecord {
if (!Array.isArray(value)) {
throw new Error("CultCache persisted records must be MessagePack arrays.");
}
const [key = "", schemaId = "", storedAt = "", payload = new Uint8Array()] = value;
if (!isNonEmptyString(key) || !isNonEmptyString(schemaId) || !isNonEmptyString(storedAt)) {
throw new Error("CultCache persisted records must declare key, schemaId, and storedAt.");
}
return {
key,
schemaId,
storedAt,
payload: normalizePayload(payload),
};
}
function decodeLegacyEnvelopeArray(decoded: unknown): Array<{
key: string;
type: string;
payload: unknown;
storedAt: string;
schemaId?: string;
}> | undefined {
if (!Array.isArray(decoded)) {
return undefined;
}
return legacyEnvelopeArraySchema.parse(decoded) as Array<{
key: string;
type: string;
payload: unknown;
storedAt: string;
schemaId?: string;
}>;
}
function normalizePayload(payload: unknown): Uint8Array {
if (payload instanceof Uint8Array) {
return payload;
@ -161,3 +414,11 @@ function normalizePayload(payload: unknown): Uint8Array {
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function isNonEmptyString(value: unknown): value is string {
return typeof value === "string" && value.length > 0;
}
function compareOrdinal(left: string, right: string): number {
return left < right ? -1 : left > right ? 1 : 0;
}

View file

@ -18,6 +18,27 @@ export interface CultCacheDocumentFormatter<TValue> {
decode(payload: Uint8Array): TValue;
}
export interface CultCacheSchemaCatalogMember {
slot: number;
memberName: string;
typeName: string;
isReference?: boolean;
isMany?: boolean;
targetSchemaName?: string | null;
isName?: boolean;
indexAlias?: string | null;
}
export interface CultCacheSchemaCatalogEntry {
schemaId: string;
schemaName: string;
schemaVersion: string;
contentHash: string;
canonicalSchemaJson: string;
compatibleSchemaIds?: readonly string[];
members?: readonly CultCacheSchemaCatalogMember[];
}
export interface CultCacheDocumentIndexDefinition<TValue> {
name: string;
accessor: CultCacheDocumentAccessor<TValue>;
@ -26,7 +47,13 @@ export interface CultCacheDocumentIndexDefinition<TValue> {
export interface CultCacheDocumentDefinition<TSchema extends CultCacheSchema = CultCacheSchema> {
type: string;
schema: TSchema;
schemaId?: string;
schemaName?: string;
schemaVersion?: string;
contentHash?: string;
canonicalSchemaJson?: string;
compatibleSchemaIds?: readonly string[];
members?: readonly CultCacheSchemaCatalogMember[];
global?: boolean;
name?: CultCacheDocumentAccessor<InferCultCacheSchemaValue<TSchema>>;
indexes?:
@ -52,6 +79,8 @@ export interface CultCacheEnvelope {
type: string;
payload: Uint8Array;
storedAt: string;
schemaId?: string;
catalogEntry?: CultCacheSchemaCatalogEntry;
}
export interface PushAllOptions {