Retire removed accounts instead of deleting them
Removing an account had no path at all, so a dead session could only be left running or hand-edited out of the database. The first cut deleted the account and everything it owned, which threw away conversations and media that are worth keeping. Retire instead: keep the row and every row it produced, destroy the stored cookies and Matrix token. Wiping the credentials is what makes sending and syncing impossible rather than merely disabled — isEnabledAccount requires a verified status, so no runtime ever starts, and no session survives for anything to use. setActive, markLoginRequired and the background credential refresh now skip retired accounts so none of them quietly revives one; re-importing a session deliberately does. Keeping the content visible needed more than keeping the rows. Conversations and media are only served from running runtimes, so a retired account's history would have disappeared from the dashboard regardless. Media already reads the account content table for every listed account. Conversations now have an archive path that reads the stored ActiveChat payloads directly. Every write path refuses a retired conversation with a 409: send-reply, both suggest endpoints, share-media, shareable-media and all read-state writes. Lazy-loading detail is skipped too — the fallback chat service belongs to a different account, so it would sync the wrong session and write the wrong cache. Archived detail derives conversation state from the transcript alone for the same reason. Migration 32 rebuilds reddit_accounts to admit the new status, with foreign keys off and a foreign_key_check before they are restored, as migration 11 does. Two migration tests rewound user_version by counting back from the head, which silently breaks whenever a migration is appended; they now target absolute versions. Conversations never opened before removal keep only their summary. Message history is lazy-loaded on first open and there is no session left to fetch the rest with. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3f60f7f665
commit
a9cea7ed18
16 files changed
+433
-97
No files matched your search
@@ -1,6 +1,12 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
|
||||
export type RedditAccountStatus = 'verified' | 'login-required' | 'disabled' | 'legacy-unassigned';
|
||||
export type RedditAccountStatus =
|
||||
| 'verified'
|
||||
| 'login-required'
|
||||
| 'disabled'
|
||||
| 'legacy-unassigned'
|
||||
/** Retired by the operator: content is kept and readable, credentials are gone. */
|
||||
| 'removed';
|
||||
|
||||
export interface RedditAccountPublicRecord {
|
||||
accountId: string;
|
||||
@@ -12,6 +18,7 @@ export interface RedditAccountPublicRecord {
|
||||
updatedAt: number;
|
||||
lastVerifiedAt: number | null;
|
||||
lastImportedAt: number | null;
|
||||
removedAt: number | null;
|
||||
}
|
||||
|
||||
/** Private credential-bearing record. Never return this from a web API. */
|
||||
@@ -41,29 +48,16 @@ type AccountRow = {
|
||||
updated_at: number;
|
||||
last_verified_at: number | null;
|
||||
last_imported_at: number | null;
|
||||
removed_at: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Tables whose foreign key to `reddit_accounts` predates cascading deletes,
|
||||
* ordered children first so each delete leaves no dangling composite reference.
|
||||
*/
|
||||
const ACCOUNT_OWNED_TABLES = [
|
||||
'conversation_outcomes',
|
||||
'successful_messages',
|
||||
'delivery_outbox',
|
||||
'sent_messages',
|
||||
'conversation_states',
|
||||
'activity_log',
|
||||
'processed_posts',
|
||||
] as const;
|
||||
|
||||
export class RedditAccountsRepository {
|
||||
constructor(private readonly db: Database.Database) {}
|
||||
|
||||
listPublic(): RedditAccountPublicRecord[] {
|
||||
const rows = this.db.prepare(`
|
||||
SELECT account_id, reddit_username, matrix_user_id, status, is_active,
|
||||
created_at, updated_at, last_verified_at, last_imported_at
|
||||
created_at, updated_at, last_verified_at, last_imported_at, removed_at
|
||||
FROM reddit_accounts
|
||||
ORDER BY is_active DESC, reddit_username COLLATE NOCASE, account_id
|
||||
`).all() as AccountRow[];
|
||||
@@ -80,7 +74,7 @@ export class RedditAccountsRepository {
|
||||
getActive(): RedditAccountPublicRecord[] {
|
||||
const rows = this.db.prepare(`
|
||||
SELECT account_id, reddit_username, matrix_user_id, status, is_active,
|
||||
created_at, updated_at, last_verified_at, last_imported_at
|
||||
created_at, updated_at, last_verified_at, last_imported_at, removed_at
|
||||
FROM reddit_accounts
|
||||
WHERE is_active = 1 AND status != 'legacy-unassigned'
|
||||
ORDER BY reddit_username COLLATE NOCASE, account_id
|
||||
@@ -113,7 +107,8 @@ export class RedditAccountsRepository {
|
||||
matrix_credentials_json = excluded.matrix_credentials_json,
|
||||
updated_at = excluded.updated_at,
|
||||
last_verified_at = excluded.last_verified_at,
|
||||
last_imported_at = excluded.last_imported_at
|
||||
last_imported_at = excluded.last_imported_at,
|
||||
removed_at = NULL
|
||||
`).run({ ...input, now });
|
||||
return publicFromPrivate(this.getRequired(input.accountId));
|
||||
}
|
||||
@@ -129,7 +124,7 @@ export class RedditAccountsRepository {
|
||||
return this.db.prepare(`
|
||||
UPDATE reddit_accounts
|
||||
SET matrix_credentials_json = ?, updated_at = ?, last_verified_at = ?
|
||||
WHERE account_id = ? AND status != 'legacy-unassigned'
|
||||
WHERE account_id = ? AND status NOT IN ('legacy-unassigned', 'removed')
|
||||
`).run(matrixCredentialsJson, now, now, accountId).changes === 1;
|
||||
}
|
||||
|
||||
@@ -138,32 +133,31 @@ export class RedditAccountsRepository {
|
||||
return this.db.prepare(`
|
||||
UPDATE reddit_accounts
|
||||
SET is_active = ?, status = ?, updated_at = ?
|
||||
WHERE account_id = ? AND status != 'legacy-unassigned'
|
||||
WHERE account_id = ? AND status NOT IN ('legacy-unassigned', 'removed')
|
||||
`).run(active ? 1 : 0, status, now, accountId).changes === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the account and everything it owns. Account-scoped tables added
|
||||
* after the ownership migration cascade on their own, but the tables that
|
||||
* migration created reference `reddit_accounts` with no delete action, so
|
||||
* their rows are cleared explicitly — children before parents — or SQLite
|
||||
* would refuse the delete.
|
||||
* Retire the account. Everything it collected stays — the row survives so
|
||||
* conversations and media keep an owner — but the stored credentials are
|
||||
* destroyed, which is what makes a later send or sync impossible rather
|
||||
* than merely disabled.
|
||||
*/
|
||||
delete(accountId: string): boolean {
|
||||
retire(accountId: string, now: number = Date.now()): boolean {
|
||||
requireText(accountId, 'accountId');
|
||||
return this.db.transaction((id: string) => {
|
||||
for (const table of ACCOUNT_OWNED_TABLES) {
|
||||
this.db.prepare(`DELETE FROM ${table} WHERE account_id = ?`).run(id);
|
||||
}
|
||||
return this.db.prepare('DELETE FROM reddit_accounts WHERE account_id = ?').run(id).changes === 1;
|
||||
})(accountId);
|
||||
return this.db.prepare(`
|
||||
UPDATE reddit_accounts
|
||||
SET status = 'removed', is_active = 0, cookies_json = '[]', matrix_credentials_json = '{}',
|
||||
removed_at = ?, updated_at = ?
|
||||
WHERE account_id = ? AND status NOT IN ('legacy-unassigned', 'removed')
|
||||
`).run(now, now, accountId).changes === 1;
|
||||
}
|
||||
|
||||
markLoginRequired(accountId: string, now: number = Date.now()): boolean {
|
||||
return this.db.prepare(`
|
||||
UPDATE reddit_accounts
|
||||
SET status = 'login-required', updated_at = ?
|
||||
WHERE account_id = ? AND status != 'legacy-unassigned'
|
||||
WHERE account_id = ? AND status NOT IN ('legacy-unassigned', 'removed')
|
||||
`).run(now, accountId).changes === 1;
|
||||
}
|
||||
|
||||
@@ -185,6 +179,7 @@ function mapPublicAccount(row: AccountRow): RedditAccountPublicRecord {
|
||||
updatedAt: row.updated_at,
|
||||
lastVerifiedAt: row.last_verified_at,
|
||||
lastImportedAt: row.last_imported_at,
|
||||
removedAt: row.removed_at,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+41
-3
@@ -5,6 +5,9 @@ import fs from 'fs';
|
||||
|
||||
export const LEGACY_UNASSIGNED_ACCOUNT_ID = '__legacy_unassigned__';
|
||||
|
||||
/** Migrations that replace a table other tables reference by foreign key. */
|
||||
const FOREIGN_KEY_REBUILD_VERSIONS = new Set([11, 32]);
|
||||
|
||||
export function createDatabase(config: Pick<Config, 'database'>): Database.Database {
|
||||
const dbPath = config.database.path === ':memory:'
|
||||
? ':memory:'
|
||||
@@ -772,6 +775,40 @@ export function runMigrations(db: Database.Database): void {
|
||||
ON learning_evaluation_runs(created_at DESC);
|
||||
`);
|
||||
},
|
||||
// Removing an account retires it rather than deleting it: the content it
|
||||
// collected stays readable and attributed, so the row has to survive with
|
||||
// a status that keeps it out of every runtime and sending path.
|
||||
() => db.exec(`
|
||||
CREATE TABLE reddit_accounts_with_removed (
|
||||
account_id TEXT PRIMARY KEY,
|
||||
reddit_username TEXT NOT NULL,
|
||||
matrix_user_id TEXT UNIQUE,
|
||||
status TEXT NOT NULL CHECK(status IN (
|
||||
'verified', 'login-required', 'disabled', 'legacy-unassigned', 'removed'
|
||||
)),
|
||||
is_active INTEGER NOT NULL DEFAULT 1 CHECK(is_active IN (0, 1)),
|
||||
cookies_json TEXT NOT NULL,
|
||||
matrix_credentials_json TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
last_verified_at INTEGER,
|
||||
last_imported_at INTEGER,
|
||||
removed_at INTEGER
|
||||
);
|
||||
INSERT INTO reddit_accounts_with_removed (
|
||||
account_id, reddit_username, matrix_user_id, status, is_active,
|
||||
cookies_json, matrix_credentials_json, created_at, updated_at,
|
||||
last_verified_at, last_imported_at, removed_at
|
||||
) SELECT
|
||||
account_id, reddit_username, matrix_user_id, status, is_active,
|
||||
cookies_json, matrix_credentials_json, created_at, updated_at,
|
||||
last_verified_at, last_imported_at, NULL
|
||||
FROM reddit_accounts;
|
||||
DROP TABLE reddit_accounts;
|
||||
ALTER TABLE reddit_accounts_with_removed RENAME TO reddit_accounts;
|
||||
CREATE INDEX idx_reddit_accounts_username ON reddit_accounts(reddit_username COLLATE NOCASE);
|
||||
CREATE INDEX idx_reddit_accounts_active ON reddit_accounts(is_active, status);
|
||||
`),
|
||||
];
|
||||
|
||||
let currentVersion = db.pragma('user_version', { simple: true }) as number;
|
||||
@@ -782,9 +819,10 @@ export function runMigrations(db: Database.Database): void {
|
||||
for (let index = currentVersion; index < migrations.length; index += 1) {
|
||||
const version = index + 1;
|
||||
// SQLite cannot rebuild a referenced table while FK enforcement is on.
|
||||
// Migration 11 replaces the account-produced table graph atomically, then
|
||||
// validates it before foreign-key enforcement is restored.
|
||||
const rebuildsForeignKeyGraph = version === 11;
|
||||
// Migration 11 replaces the account-produced table graph atomically and
|
||||
// migration 32 rebuilds `reddit_accounts` itself; both validate the graph
|
||||
// before foreign-key enforcement is restored.
|
||||
const rebuildsForeignKeyGraph = FOREIGN_KEY_REBUILD_VERSIONS.has(version);
|
||||
if (rebuildsForeignKeyGraph) db.pragma('foreign_keys = OFF');
|
||||
try {
|
||||
db.transaction(() => {
|
||||
|
||||
Reference in new issue
Block a user