Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 86 additions & 39 deletions pm-stack/aggregator/src/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ import { isObjectRef, validateAuthor } from "./comments.ts";
import type { ViewFilters } from "./views.ts";
import { validateViewFilters, validateViewName } from "./views.ts";
import type { DashAuthor, RefKey, SessionSource } from "./model.ts";
import { isRecord } from "./validate.ts";
import { isNonEmptyString, isRecord, parseIsoDate } from "./validate.ts";
import { archiveStoreBytes, quarantineUnreadableStore, quarantineWholeStore, type InvalidStoreRecord, type StoreArchive } from "./store-recovery.ts";

export type DashActionKind = "triage" | "status-request" | "session" | "preference";

Expand Down Expand Up @@ -121,6 +122,36 @@ export const VERBS_BY_KIND: Record<DashActionKind, readonly DashActionVerb[]> =
preference: ["set-delegation-default", "set-needs-order", "save-view", "rename-view", "delete-view", "set-default-view"],
};

const ACTION_KINDS = new Set<DashActionKind>(["triage", "status-request", "session", "preference"]);
const ACTION_STATES = new Set(["new", "applied", "rejected", "superseded"]);

function actionRecordProblem(value: unknown): string | null {
if (!isRecord(value)) return "record must be an object";
if (!isNonEmptyString(value.id)) return "id must be a non-empty string";
if (!isObjectRef(value.objectRef)) return "objectRef must be a non-empty ref string";
if (typeof value.kind !== "string" || !ACTION_KINDS.has(value.kind as DashActionKind)) {
return "kind must be triage, status-request, session, or preference";
}
const kind = value.kind as DashActionKind;
if (typeof value.verb !== "string" || !VERBS_BY_KIND[kind].includes(value.verb as DashActionVerb)) {
return "verb must be supported for the action kind";
}
if (parseIsoDate(value.createdAt) === null) return "createdAt must be a valid ISO date/time string";
if (!isRecord(value.payload)) return "payload must be an object";
if (!validateAuthor(value.author)) return "author must have a supported kind, id, and label";
if (typeof value.state !== "string" || !ACTION_STATES.has(value.state)) {
return "state must be new, applied, rejected, or superseded";
}
// Pre-token audit rows remain readable; when a token exists it must be
// a string so dedupe comparisons have their intended semantics.
if (value.clientToken !== undefined && !isNonEmptyString(value.clientToken)) {
return "clientToken must be a non-empty string when present";
}
// Historical payloads are intentionally only required to be records;
// individual verbs tolerate older payload shapes at their consumers.
return null;
}

export interface DashActionPayload {
/** snooze horizon (ISO). */
until?: string;
Expand Down Expand Up @@ -458,11 +489,15 @@ export function newClientToken(): string {

export class ActionsStore {
private actions: DashAction[] = [];
private fileExtras: Record<string, unknown> = {};
private loadPromise: Promise<void> | null = null;
private writeChain: Promise<void> = Promise.resolve();
private writeSeq = 0;

constructor(private readonly file: string) {}
constructor(
private readonly file: string,
private readonly archive: StoreArchive = archiveStoreBytes,
) {}

// The load is memoized as a single promise (#1509): the old
// loaded-flag version let concurrent first callers proceed before
Expand All @@ -480,12 +515,13 @@ export class ActionsStore {
// original bytes to <file>.corrupt-<timestamp>, start empty, and
// log loudly — the next persist then writes a fresh valid file and
// never touches the quarantined copy.
let raw: string;
let raw: Buffer;
try {
raw = await readFile(this.file, "utf8");
raw = await readFile(this.file);
} catch (err) {
if ((err as { code?: unknown })?.code === "ENOENT") {
this.actions = []; // no store yet — the first write creates it
this.fileExtras = {};
return;
}
// #2980: a non-ENOENT read failure (EACCES, a transient I/O error,
Expand All @@ -494,57 +530,68 @@ export class ActionsStore {
// like the corrupt case below — quarantine the original bytes
// before starting empty, and log loudly — so the next persist
// cannot silently overwrite history the read never saw.
this.actions = [];
const quarantined = `${this.file}.corrupt-${new Date().toISOString().replace(/[:.]/g, "-")}`;
let quarantined: string;
try {
await rename(this.file, quarantined);
console.error(
`[actions] WARNING: actions store ${this.file} could not be read (${err instanceof Error ? err.message : String(err)}); ` +
`quarantined the original bytes to ${quarantined} and started empty. ` +
`The quarantined file holds the prior audit history — do not delete it.`,
);
quarantined = await quarantineUnreadableStore(this.file);
} catch (renameErr) {
console.error(
`[actions] WARNING: actions store ${this.file} could not be read (${err instanceof Error ? err.message : String(err)}) ` +
`and could not be quarantined (${renameErr instanceof Error ? renameErr.message : String(renameErr)}); starting empty — ` +
`the next persist will overwrite it, so copy it aside now to preserve the audit history.`,
throw new Error(
`[actions] refusing to continue because ${this.file} could not be read or quarantined: ${renameErr instanceof Error ? renameErr.message : String(renameErr)}`,
{ cause: err },
);
}
this.actions = [];
this.fileExtras = {};
console.error(
`[actions] WARNING: actions store ${this.file} could not be read (${err instanceof Error ? err.message : String(err)}); ` +
`quarantined the original to ${quarantined} and started empty. The quarantined item holds the prior audit history — do not delete it.`,
);
return;
}

let parsed: unknown;
try {
const parsed: unknown = JSON.parse(raw);
if (typeof parsed !== "object" || parsed === null || !Array.isArray((parsed as ActionsFile).actions)) {
throw new Error("store file does not have the expected { actions: [...] } shape");
}
this.actions = (parsed as ActionsFile).actions.filter(
(a) => isRecord(a) && typeof a.id === "string" && isRecord(a.payload),
);
parsed = JSON.parse(raw.toString("utf8"));
} catch (err) {
const quarantined = await quarantineWholeStore(this.file, raw, this.archive);
this.actions = [];
const quarantined = `${this.file}.corrupt-${new Date().toISOString().replace(/[:.]/g, "-")}`;
try {
await rename(this.file, quarantined);
console.error(
`[actions] WARNING: actions store ${this.file} is unparseable (${err instanceof Error ? err.message : String(err)}); ` +
`quarantined the original bytes to ${quarantined} and started empty. ` +
`The quarantined file holds the prior audit history — do not delete it.`,
);
} catch (renameErr) {
console.error(
`[actions] WARNING: actions store ${this.file} is unparseable (${err instanceof Error ? err.message : String(err)}) ` +
`and could not be quarantined (${renameErr instanceof Error ? renameErr.message : String(renameErr)}); starting empty — ` +
`the next persist will overwrite it, so copy it aside now to preserve the audit history.`,
);
}
this.fileExtras = {};
console.error(`[actions] WARNING: actions store ${this.file} is unparseable (${err instanceof Error ? err.message : String(err)}); quarantined original bytes to ${quarantined} and started empty.`);
return;
}
if (!isRecord(parsed) || !Array.isArray(parsed.actions)) {
const quarantined = await quarantineWholeStore(this.file, raw, this.archive);
this.actions = [];
this.fileExtras = {};
console.error(`[actions] WARNING: actions store ${this.file} has the wrong envelope shape; quarantined original bytes to ${quarantined} and started empty.`);
return;
}

this.fileExtras = Object.fromEntries(Object.entries(parsed).filter(([key]) => key !== "version" && key !== "actions"));
const valid: DashAction[] = [];
const invalid: InvalidStoreRecord[] = [];
parsed.actions.forEach((action, index) => {
const reason = actionRecordProblem(action);
if (reason) invalid.push({ index, reason });
else valid.push(action as DashAction);
});
this.actions = valid;
if (invalid.length > 0) {
const quarantined = await this.archive(this.file, raw, invalid);
console.error(
`[actions] WARNING: quarantined ${invalid.length} malformed record(s) from ${this.file}; ` +
`original bytes: ${quarantined}; index/reason diagnostics: ${quarantined}.diagnostics.json.`,
);
// Do not rewrite the active audit log until the original bytes and
// the per-record diagnostics are durable.
await this.persist();
}
}

// Serialized persists + unique temp path per write - see
// CommentsStore.persist (#1509).
private persist(): Promise<void> {
const run = this.writeChain.then(async () => {
const data: ActionsFile = { version: 1, actions: this.actions };
const data = { ...this.fileExtras, version: 1 as const, actions: this.actions };
await mkdir(dirname(this.file), { recursive: true });
const tmp = `${this.file}.tmp-${process.pid}-${++this.writeSeq}`;
await writeFile(tmp, JSON.stringify(data, null, 2));
Expand Down
130 changes: 92 additions & 38 deletions pm-stack/aggregator/src/comments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,51 @@ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import type { DashAuthor, DashComment, DashCommentKind, RefKey } from "./model.ts";
import { refUrl } from "./model.ts";
import { archiveStoreBytes, quarantineUnreadableStore, quarantineWholeStore, type InvalidStoreRecord, type StoreArchive } from "./store-recovery.ts";
import { isNonEmptyString, isRecord, parseIsoDate } from "./validate.ts";

export interface CommentsFile {
version: 1;
comments: DashComment[];
}

const GH_REF = /^[\w.-]+\/[\w.-]+#\d+$/;
const COMMENT_KINDS = new Set<DashCommentKind>(["message", "note", "github"]);

function commentRecordProblem(value: unknown): string | null {
if (!isRecord(value)) return "record must be an object";
if (!isNonEmptyString(value.id)) return "id must be a non-empty string";
if (!isObjectRef(value.objectRef)) return "objectRef must be a non-empty ref string";
if (typeof value.kind !== "string" || !COMMENT_KINDS.has(value.kind as DashCommentKind)) {
return "kind must be message, note, or github";
}
if (parseIsoDate(value.createdAt) === null) return "createdAt must be a valid ISO date/time string";
if (!validateAuthor(value.author)) return "author must have a supported kind, id, and label";
if (typeof value.body !== "string") return "body must be a string";
if (
value.kind === "message" &&
value.triageState !== undefined &&
value.triageState !== "new" &&
value.triageState !== "triaged"
) {
return "message triageState must be new or triaged";
}
if (value.kind === "github") {
if (value.githubRef !== undefined && (typeof value.githubRef !== "string" || !GH_REF.test(value.githubRef))) {
return "githubRef must be owner/repo#N";
}
if (
value.githubState !== undefined &&
value.githubState !== "pending" &&
value.githubState !== "posted" &&
value.githubState !== "failed"
) {
return "githubState must be pending, posted, or failed";
}
if (value.githubState === "pending" && value.githubRef === undefined) return "pending github comments require githubRef";
}
return null;
}

export function isObjectRef(s: unknown): s is string {
return typeof s === "string" && s.length > 0 && s.length <= 300 && !/\s/.test(s);
Expand Down Expand Up @@ -96,11 +134,15 @@ export function newCommentId(now = new Date()): string {

export class CommentsStore {
private comments: DashComment[] = [];
private fileExtras: Record<string, unknown> = {};
private loadPromise: Promise<void> | null = null;
private writeChain: Promise<void> = Promise.resolve();
private writeSeq = 0;

constructor(private readonly file: string) {}
constructor(
private readonly file: string,
private readonly archive: StoreArchive = archiveStoreBytes,
) {}

// The load is memoized as a single promise (#1509): the old
// loaded-flag version let concurrent first callers proceed before
Expand All @@ -118,12 +160,13 @@ export class CommentsStore {
// original bytes to <file>.corrupt-<timestamp>, start empty, and
// log loudly — the next persist then writes a fresh valid file and
// never touches the quarantined copy.
let raw: string;
let raw: Buffer;
try {
raw = await readFile(this.file, "utf8");
raw = await readFile(this.file);
} catch (err) {
if ((err as { code?: unknown })?.code === "ENOENT") {
this.comments = []; // no store yet — the first write creates it
this.fileExtras = {};
return;
}
// #2980: a non-ENOENT read failure (EACCES, a transient I/O error,
Expand All @@ -132,49 +175,60 @@ export class CommentsStore {
// like the corrupt case below — quarantine the original bytes
// before starting empty, and log loudly — so the next persist
// cannot silently overwrite history the read never saw.
this.comments = [];
const quarantined = `${this.file}.corrupt-${new Date().toISOString().replace(/[:.]/g, "-")}`;
let quarantined: string;
try {
await rename(this.file, quarantined);
console.error(
`[comments] WARNING: comments store ${this.file} could not be read (${err instanceof Error ? err.message : String(err)}); ` +
`quarantined the original bytes to ${quarantined} and started empty. ` +
`The quarantined file holds the prior audit history — do not delete it.`,
);
quarantined = await quarantineUnreadableStore(this.file);
} catch (renameErr) {
console.error(
`[comments] WARNING: comments store ${this.file} could not be read (${err instanceof Error ? err.message : String(err)}) ` +
`and could not be quarantined (${renameErr instanceof Error ? renameErr.message : String(renameErr)}); starting empty — ` +
`the next persist will overwrite it, so copy it aside now to preserve the audit history.`,
throw new Error(
`[comments] refusing to continue because ${this.file} could not be read or quarantined: ${renameErr instanceof Error ? renameErr.message : String(renameErr)}`,
{ cause: err },
);
}
this.comments = [];
this.fileExtras = {};
console.error(
`[comments] WARNING: comments store ${this.file} could not be read (${err instanceof Error ? err.message : String(err)}); ` +
`quarantined the original to ${quarantined} and started empty. The quarantined item holds the prior audit history — do not delete it.`,
);
return;
}

let parsed: unknown;
try {
const parsed: unknown = JSON.parse(raw);
if (typeof parsed !== "object" || parsed === null || !Array.isArray((parsed as CommentsFile).comments)) {
throw new Error("store file does not have the expected { comments: [...] } shape");
}
this.comments = (parsed as CommentsFile).comments.filter(
(c) => typeof c === "object" && c !== null && typeof (c as DashComment).id === "string",
);
parsed = JSON.parse(raw.toString("utf8"));
} catch (err) {
const quarantined = await quarantineWholeStore(this.file, raw, this.archive);
this.comments = [];
const quarantined = `${this.file}.corrupt-${new Date().toISOString().replace(/[:.]/g, "-")}`;
try {
await rename(this.file, quarantined);
console.error(
`[comments] WARNING: comments store ${this.file} is unparseable (${err instanceof Error ? err.message : String(err)}); ` +
`quarantined the original bytes to ${quarantined} and started empty. ` +
`The quarantined file holds the prior audit history — do not delete it.`,
);
} catch (renameErr) {
console.error(
`[comments] WARNING: comments store ${this.file} is unparseable (${err instanceof Error ? err.message : String(err)}) ` +
`and could not be quarantined (${renameErr instanceof Error ? renameErr.message : String(renameErr)}); starting empty — ` +
`the next persist will overwrite it, so copy it aside now to preserve the audit history.`,
);
}
this.fileExtras = {};
console.error(`[comments] WARNING: comments store ${this.file} is unparseable (${err instanceof Error ? err.message : String(err)}); quarantined original bytes to ${quarantined} and started empty.`);
return;
}
if (!isRecord(parsed) || !Array.isArray(parsed.comments)) {
const quarantined = await quarantineWholeStore(this.file, raw, this.archive);
this.comments = [];
this.fileExtras = {};
console.error(`[comments] WARNING: comments store ${this.file} has the wrong envelope shape; quarantined original bytes to ${quarantined} and started empty.`);
return;
}

this.fileExtras = Object.fromEntries(Object.entries(parsed).filter(([key]) => key !== "version" && key !== "comments"));
const valid: DashComment[] = [];
const invalid: InvalidStoreRecord[] = [];
parsed.comments.forEach((comment, index) => {
const reason = commentRecordProblem(comment);
if (reason) invalid.push({ index, reason });
else valid.push(comment as DashComment);
});
this.comments = valid;
if (invalid.length > 0) {
const quarantined = await this.archive(this.file, raw, invalid);
console.error(
`[comments] WARNING: quarantined ${invalid.length} malformed record(s) from ${this.file}; ` +
`original bytes: ${quarantined}; index/reason diagnostics: ${quarantined}.diagnostics.json.`,
);
// The exact source bytes and diagnostics are durable before this
// atomic rewrite removes malformed rows from the active store.
await this.persist();
}
}

Expand All @@ -188,7 +242,7 @@ export class CommentsStore {
// does not poison the chain for later writes.
private persist(): Promise<void> {
const run = this.writeChain.then(async () => {
const data: CommentsFile = { version: 1, comments: this.comments };
const data = { ...this.fileExtras, version: 1 as const, comments: this.comments };
await mkdir(dirname(this.file), { recursive: true });
const tmp = `${this.file}.tmp-${process.pid}-${++this.writeSeq}`;
await writeFile(tmp, JSON.stringify(data, null, 2));
Expand Down
Loading
Loading