Files
herdrMario/mod/ovis-composer/storage.js
T
2026-11-19 11:06:12 +01:00

360 lines
11 KiB
JavaScript

// storage.js - what the composer keeps between runs.
//
// The store is injected: `store = { get(key): unknown, set(key, value): void }`.
// The view (Task 8) hands it `{ get: shared, set: setShared }` from the
// `herdr` module. `shared()` is app-wide and persisted in
// ~/.config/herdr-app/shared.json, so the history is the same in every pane
// and outlives the app. `localStorage` would be per mod copy - per pane - and
// would not outlive a restart.
//
// The queue has to outlive a crash in the middle of a send: Task 5's `drain`
// marks the entry `sending` BEFORE the send goes on the wire and hands the
// state to the caller through `ctx.onState`, so the caller writes it down at
// once. After a restart the composer loads the queue and turns `sending` into
// `uncertain` (the `restart` action of state.js) - the message may have
// reached the agent, so it is never sent again on its own.
//
// Reading never throws: a key that was never written, a value that is not a
// list, a store that is not there - the composer always gets a list to show.
// Writing rubbish does not throw either, but it does not write: the stored
// list stays as it was, so a bug in the caller cannot wipe the history. A
// store that cannot be written to at all throws - the queue on disk is what
// keeps a crash from sending a message twice, so that must not pass quietly.
//
// What comes back is checked: an entry that lost a field on the way to the
// disk is dropped, not handed to the view. A queue entry without a moment
// (`createdAt`) would make state.js throw, and one with a state it does not
// know would wait for ever - and a cut entry that came back would be sent
// again.
/**
* @typedef {object} Store
* @property {(key:string) => unknown} get
* @property {(key:string, value:unknown) => unknown} set
*
* @typedef {object} HistoryEntry
* @property {string} id
* @property {string} text
* @property {number} at
* @property {string} agent
* @property {string} space
* @property {string} spaceName
* @property {string} tab
* @property {string} pane
* @property {string|null} machine
* @property {string[]} attachments
* @property {"sent"|"queued"|"failed"} outcome
*
* @typedef {object} FavoriteEntry
* @property {string} id
* @property {string} text
* @property {number} at
* @property {string} agent
* @property {"history"|"manual"} source
*
* @typedef {object} QueueEntry
* @property {string} id
* @property {string} text
* @property {"queued"|"sending"|"held"|"uncertain"} state
* @property {number} createdAt
* @property {string} [reason]
*/
/** The states a queue entry may be in (the ones state.js knows). */
const QUEUE_STATES = new Set(["queued", "sending", "held", "uncertain"]);
/** The keys the composer writes into the shared store. */
export const KEYS = {
history: "ovis-composer.history",
favorites: "ovis-composer.favorites",
usage: "ovis-composer.usage",
/** The queue is per agent: `ovis-composer.queue:<agent>`. */
queue: "ovis-composer.queue",
};
/** How many entries the history keeps. */
export const HISTORY_LIMIT = 500;
/** How many entries the favourites keep. */
export const FAVORITES_LIMIT = 100;
/**
* The key of one agent's queue.
*
* @param {string} agent
* @returns {string}
*/
export function queueKey(agent) {
return `${KEYS.queue}:${agent}`;
}
/**
* The history of the sent messages.
*
* The list is chronological - the oldest entry first, the newest last - and
* the oldest entries drop out when the list grows over the limit.
*
* @param {Store} store
* @returns {HistoryEntry[]}
*/
export function loadHistory(store) {
return readList(store, KEYS.history, HISTORY_LIMIT, isTextEntry);
}
/**
* @param {Store} store
* @param {HistoryEntry[]} items
* @returns {void}
*/
export function saveHistory(store, items) {
writeList(store, KEYS.history, items, HISTORY_LIMIT, isTextEntry);
}
/**
* The favourites - the texts the person marked, kept apart from the history
* so they outlive a cleared history.
*
* @param {Store} store
* @returns {FavoriteEntry[]}
*/
export function loadFavorites(store) {
return readList(store, KEYS.favorites, FAVORITES_LIMIT, isTextEntry);
}
/**
* @param {Store} store
* @param {FavoriteEntry[]} items
* @returns {void}
*/
export function saveFavorites(store, items) {
writeList(store, KEYS.favorites, items, FAVORITES_LIMIT, isTextEntry);
}
/**
* The queue of one agent - the messages that wait for their turn.
*
* The state is what it was when it was written: an entry that was on the wire
* (`sending`) is still `sending` here after a restart, and the composer
* turns it into `uncertain` (state.js, the `restart` action). The queue is
* never sent again on its own.
*
* @param {Store} store
* @param {string} agent
* @returns {QueueEntry[]}
*/
export function loadQueue(store, agent) {
return readList(store, queueKey(agent), 0, isQueueEntry);
}
/**
* @param {Store} store
* @param {string} agent
* @param {QueueEntry[]} items
* @returns {void}
*/
export function saveQueue(store, agent, items) {
if (typeof agent !== "string" || agent === "") return;
writeList(store, queueKey(agent), items, 0, isQueueEntry);
}
/**
* How often each command was used - the numbers the ranking of the
* suggestions breaks its ties with (`suggest.rank` reads `item.uses`).
*
* The key is the key of the catalog (`catalog.js`): the name of the command
* without the slash - "review", not "/review" - because that is the name
* `suggest.rank` compares.
*
* @param {Store} store
* @returns {Record<string, number>}
*/
export function loadUsage(store) {
const raw = read(store, KEYS.usage);
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
const counts = {};
for (const [key, value] of Object.entries(raw)) {
if (typeof value === "number" && Number.isFinite(value) && value >= 0) counts[key] = value;
}
return counts;
}
/**
* @param {Store} store
* @param {Record<string, number>} counts - the key of the catalog, without
* the slash: "review", not "/review"
* @returns {void}
*/
export function saveUsage(store, counts) {
if (!counts || typeof counts !== "object" || Array.isArray(counts)) return;
const clean = {};
for (const [key, value] of Object.entries(counts)) {
if (typeof value === "number" && Number.isFinite(value) && value >= 0) clean[key] = value;
}
// Counts that are not counts are rubbish - they do not wipe the counters
// that are there. An empty map on purpose still clears them.
if (Object.keys(counts).length > 0 && Object.keys(clean).length === 0) return;
write(store, KEYS.usage, clean);
}
/**
* Read a list, dropping what is not a list, what is not an entry and what the
* limit leaves out. The oldest entries drop out - the list is chronological.
*
* @param {Store} store
* @param {string} key
* @param {number} limit - 0 for a list without a limit
* @param {(entry:Record<string, unknown>) => boolean} isValid
* @returns {any[]}
*/
function readList(store, key, limit, isValid) {
const list = toList(read(store, key), isValid);
if (!list) return [];
return limit > 0 ? list.slice(-limit) : list;
}
/**
* Write a list, dropping what is not an entry and what the limit leaves out.
*
* @param {Store} store
* @param {string} key
* @param {unknown} items
* @param {number} limit - 0 for a list without a limit
* @param {(entry:Record<string, unknown>) => boolean} isValid
* @returns {void}
*/
function writeList(store, key, items, limit, isValid) {
const source = listSource(items);
// Rubbish in - nothing is written, so the stored list stays as it was.
if (!source) return;
const list = toList(source, isValid) ?? [];
// A list that lost every entry is rubbish, not an empty list - writing it
// would wipe what is there.
if (source.length > 0 && list.length === 0) return;
write(store, key, limit > 0 ? list.slice(-limit) : list);
}
/**
* The list in a value, or nothing when the value is not a list. The entries
* that are not entries of this kind are rubbish and go.
*
* The entries keep the shape the caller wrote - what a history entry and what
* a queue entry look like is the caller's business, not the store's.
*
* @param {unknown} value
* @param {(entry:Record<string, unknown>) => boolean} isValid
* @returns {any[]|null}
*/
function toList(value, isValid) {
const source = listSource(value);
if (!source) return null;
return source.filter((entry) => isEntry(entry, isValid));
}
/**
* Is this an entry of the kind the list holds? An entry that lost a field on
* the way to the disk does not come back - the view and the state model would
* have to guess what is missing.
*
* @param {unknown} entry
* @param {(entry:Record<string, unknown>) => boolean} isValid
* @returns {boolean}
*/
function isEntry(entry, isValid) {
if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return false;
return isValid(/** @type {Record<string, unknown>} */ (entry));
}
/**
* An entry the view can show - a history entry and a favourite have the same
* shape: a text and a moment.
*
* @param {Record<string, unknown>} entry
* @returns {boolean}
*/
function isTextEntry(entry) {
return isText(entry.id) && isText(entry.text) && isTime(entry.at);
}
/**
* A queue entry the state model can take.
*
* `createdAt` is what state.js insists on - without it the model throws - and
* the state has to be one it knows: an entry with a state of its own would
* wait for ever, and one that lost its state could be sent a second time.
*
* @param {Record<string, unknown>} entry
* @returns {boolean}
*/
function isQueueEntry(entry) {
return (
isText(entry.id) &&
isText(entry.text) &&
isTime(entry.createdAt) &&
QUEUE_STATES.has(entry.state)
);
}
/** Is this a text? */
function isText(value) {
return typeof value === "string";
}
/** Is this a moment in time (epoch ms)? */
function isTime(value) {
return typeof value === "number" && Number.isFinite(value);
}
/**
* The list a value holds: the value itself, or the `items` of the envelope
* the design wrote down (`{ items: [ … ] }`).
*
* @param {unknown} value
* @returns {unknown[]|null}
*/
function listSource(value) {
if (Array.isArray(value)) return value;
if (!value || typeof value !== "object") return null;
const envelope = /** @type {{items?: unknown}} */ (value);
return Array.isArray(envelope.items) ? envelope.items : null;
}
/**
* Read a value from the store. A store that fails gives nothing.
*
* @param {Store} store
* @param {string} key
* @returns {unknown}
*/
function read(store, key) {
try {
if (!store || typeof store.get !== "function") return null;
const value = store.get(key);
return value ?? null;
} catch {
return null;
}
}
/**
* Write a value into the store. A store that cannot be written to throws -
* the queue on disk is what keeps a crash from sending a message twice.
*
* @param {Store} store
* @param {string} key
* @param {unknown} value
* @returns {void}
*/
function write(store, key, value) {
if (!store || typeof store.set !== "function") {
throw new TypeError(`brak magazynu dla klucza ${key}`);
}
store.set(key, value);
}