Repository navigation
Expand file tree
/
Copy pathbase.ts
More file actions
342 lines (299 loc) · 11.7 KB
/
Copy pathbase.ts
File metadata and controls
342 lines (299 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import {
AccountClaimRequestSchema,
LegacyPasswordCredentialSchema,
PasswordTokenSchema,
PrivateProfileSchema,
} from '@cfp/shared/schemas';
import type {
AccountClaimRequest,
LegacyPasswordCredential,
PasswordToken,
PrivateProfile,
} from '@cfp/shared/schemas';
import type { PrivateIndices, PrivateStore, PrivateStoreTx } from './interface.js';
/**
* Shared in-memory state and logic for both PrivateStore backends.
*
* Subclasses implement readRaw() and writeRaw() to fetch/persist the
* serialized .jsonl content. The rest of the interface is handled here.
*/
export abstract class BasePrivateStore implements PrivateStore {
protected profiles: Map<string, PrivateProfile> = new Map();
protected legacyPasswords: Map<string, LegacyPasswordCredential> = new Map();
protected passwordTokens: Map<string, PasswordToken> = new Map();
protected claimRequests: Map<string, AccountClaimRequest> = new Map();
readonly indices: PrivateIndices = {
byEmail: new Map(),
byUnsubscribeToken: new Map(),
legacyPasswordByPersonId: this.legacyPasswords,
};
/** Fetch the raw bytes of a .jsonl file by key. Return null if absent. */
protected abstract readRaw(key: string): Promise<string | null>;
/** Atomically write raw bytes to a .jsonl file by key. */
protected abstract writeRaw(key: string, content: string): Promise<void>;
async load(): Promise<void> {
await Promise.all([
this.loadProfiles(),
this.loadLegacyPasswords(),
this.loadPasswordTokens(),
this.loadClaimRequests(),
]);
this.rebuildIndices();
}
private async loadProfiles(): Promise<void> {
const raw = await this.readRaw('profiles.jsonl');
this.profiles = parseJsonl(raw, PrivateProfileSchema);
}
private async loadLegacyPasswords(): Promise<void> {
const raw = await this.readRaw('legacy-passwords.jsonl');
const loaded = parseJsonl(raw, LegacyPasswordCredentialSchema);
this.legacyPasswords = loaded;
// Update the indices reference since legacyPasswords Map is replaced
(this.indices as { legacyPasswordByPersonId: Map<string, LegacyPasswordCredential> }).legacyPasswordByPersonId =
this.legacyPasswords;
}
private async loadClaimRequests(): Promise<void> {
const raw = await this.readRaw('account-claim-requests.jsonl');
this.claimRequests = parseJsonl(raw, AccountClaimRequestSchema, 'id');
}
private async loadPasswordTokens(): Promise<void> {
const raw = await this.readRaw('password-tokens.jsonl');
this.passwordTokens = parseJsonl(raw, PasswordTokenSchema, 'tokenHash');
}
private rebuildIndices(): void {
this.indices.byEmail.clear();
this.indices.byUnsubscribeToken.clear();
for (const profile of this.profiles.values()) {
this.indices.byEmail.set(profile.email.toLowerCase(), profile.personId);
const token = profile.newsletter?.unsubscribeToken;
if (token) {
this.indices.byUnsubscribeToken.set(token, profile.personId);
}
}
}
async getProfile(personId: string): Promise<PrivateProfile | null> {
return this.profiles.get(personId) ?? null;
}
async putProfile(profile: PrivateProfile): Promise<void> {
const parsed = PrivateProfileSchema.parse(profile);
this.profiles.set(parsed.personId, parsed);
this.rebuildIndices();
await this.flushProfiles();
}
async deleteProfile(personId: string): Promise<void> {
this.profiles.delete(personId);
this.rebuildIndices();
await this.flushProfiles();
}
async findPersonIdByEmail(email: string): Promise<string | null> {
return this.indices.byEmail.get(email.toLowerCase()) ?? null;
}
async *listAllProfiles(): AsyncIterable<PrivateProfile> {
for (const profile of this.profiles.values()) {
yield profile;
}
}
async getLegacyPassword(personId: string): Promise<LegacyPasswordCredential | null> {
return this.legacyPasswords.get(personId) ?? null;
}
async putLegacyPassword(cred: LegacyPasswordCredential): Promise<void> {
const parsed = LegacyPasswordCredentialSchema.parse(cred);
this.legacyPasswords.set(parsed.personId, parsed);
await this.flushLegacyPasswords();
}
async deleteLegacyPassword(personId: string): Promise<void> {
this.legacyPasswords.delete(personId);
await this.flushLegacyPasswords();
}
async countLegacyPasswords(): Promise<number> {
return this.legacyPasswords.size;
}
async getPasswordToken(tokenHash: string): Promise<PasswordToken | null> {
return this.passwordTokens.get(tokenHash) ?? null;
}
async putPasswordToken(token: PasswordToken): Promise<void> {
const parsed = PasswordTokenSchema.parse(token);
this.passwordTokens.set(parsed.tokenHash, parsed);
await this.flushPasswordTokens();
}
async deletePasswordToken(tokenHash: string): Promise<void> {
this.passwordTokens.delete(tokenHash);
await this.flushPasswordTokens();
}
async getClaimRequest(requestId: string): Promise<AccountClaimRequest | null> {
return this.claimRequests.get(requestId) ?? null;
}
async putClaimRequest(req: AccountClaimRequest): Promise<void> {
const parsed = AccountClaimRequestSchema.parse(req);
this.claimRequests.set(parsed.id, parsed);
await this.flushClaimRequests();
}
async listOpenClaimRequests(): Promise<AccountClaimRequest[]> {
return [...this.claimRequests.values()].filter((r) => r.status === 'open');
}
async listAllClaimRequests(): Promise<AccountClaimRequest[]> {
return [...this.claimRequests.values()];
}
async readBlob(key: string): Promise<string | null> {
return this.readRaw(key);
}
async writeBlob(key: string, content: string): Promise<void> {
return this.writeRaw(key, content);
}
async transact<T>(handler: (tx: PrivateStoreTx) => Promise<T>): Promise<T> {
// Snapshot current state so we can roll back if the handler throws
const profilesSnapshot = new Map(this.profiles);
const legacySnapshot = new Map(this.legacyPasswords);
const claimRequestsSnapshot = new Map(this.claimRequests);
const passwordTokensSnapshot = new Map(this.passwordTokens);
// Staged mutations applied only in-memory during the handler
const stagedProfilePuts: Map<string, PrivateProfile> = new Map();
const stagedProfileDeletes: Set<string> = new Set();
const stagedLegacyPuts: Map<string, LegacyPasswordCredential> = new Map();
const stagedLegacyDeletes: Set<string> = new Set();
const stagedClaimRequestPuts: Map<string, AccountClaimRequest> = new Map();
const stagedPersonPurges: Set<string> = new Set();
const tx: PrivateStoreTx = {
putProfile: (profile) => {
const parsed = PrivateProfileSchema.parse(profile);
stagedProfilePuts.set(parsed.personId, parsed);
stagedProfileDeletes.delete(parsed.personId);
},
deleteProfile: (personId) => {
stagedProfileDeletes.add(personId);
stagedProfilePuts.delete(personId);
},
putLegacyPassword: (cred) => {
const parsed = LegacyPasswordCredentialSchema.parse(cred);
stagedLegacyPuts.set(parsed.personId, parsed);
stagedLegacyDeletes.delete(parsed.personId);
},
deleteLegacyPassword: (personId) => {
stagedLegacyDeletes.add(personId);
stagedLegacyPuts.delete(personId);
},
putClaimRequest: (req) => {
const parsed = AccountClaimRequestSchema.parse(req);
stagedClaimRequestPuts.set(parsed.id, parsed);
},
deletePersonData: (personId) => {
stagedPersonPurges.add(personId);
stagedProfilePuts.delete(personId);
stagedLegacyPuts.delete(personId);
},
};
let result: T;
try {
result = await handler(tx);
} catch (err) {
// Handler threw: leave in-memory state unchanged
this.profiles = profilesSnapshot;
this.legacyPasswords = legacySnapshot;
this.claimRequests = claimRequestsSnapshot;
this.passwordTokens = passwordTokensSnapshot;
this.rebuildIndices();
throw err;
}
// Handler succeeded — apply staged mutations
for (const [id, profile] of stagedProfilePuts) {
this.profiles.set(id, profile);
}
for (const id of stagedProfileDeletes) {
this.profiles.delete(id);
}
for (const [id, cred] of stagedLegacyPuts) {
this.legacyPasswords.set(id, cred);
}
for (const id of stagedLegacyDeletes) {
this.legacyPasswords.delete(id);
}
for (const [id, req] of stagedClaimRequestPuts) {
this.claimRequests.set(id, req);
}
for (const personId of stagedPersonPurges) {
this.profiles.delete(personId);
this.legacyPasswords.delete(personId);
for (const [id, req] of this.claimRequests) {
if (req.claimedPersonId === personId || req.requesterPersonId === personId) this.claimRequests.delete(id);
}
for (const [hash, token] of this.passwordTokens) {
if (token.personId === personId) this.passwordTokens.delete(hash);
}
}
this.rebuildIndices();
// Flush to backend
const flushOps: Promise<void>[] = [];
const purging = stagedPersonPurges.size > 0;
if (purging || stagedProfilePuts.size > 0 || stagedProfileDeletes.size > 0) {
flushOps.push(this.flushProfiles());
}
if (purging || stagedLegacyPuts.size > 0 || stagedLegacyDeletes.size > 0) {
flushOps.push(this.flushLegacyPasswords());
}
if (purging || stagedClaimRequestPuts.size > 0) {
flushOps.push(this.flushClaimRequests());
}
if (purging) {
flushOps.push(this.flushPasswordTokens());
}
try {
await Promise.all(flushOps);
} catch (err) {
// Flush failed — in-memory is ahead of storage. Restore snapshot and
// rebuild indices. Log loudly; a reconciliation script will fix state.
this.profiles = profilesSnapshot;
this.legacyPasswords = legacySnapshot;
this.claimRequests = claimRequestsSnapshot;
this.passwordTokens = passwordTokensSnapshot;
this.rebuildIndices();
throw new PrivateStoreError(
'private_store_unavailable',
'Failed to flush private store after successful transaction',
err,
);
}
return result;
}
protected async flushProfiles(): Promise<void> {
const lines = [...this.profiles.values()].map((p) => JSON.stringify(p)).join('\n');
await this.writeRaw('profiles.jsonl', lines ? lines + '\n' : '');
}
protected async flushLegacyPasswords(): Promise<void> {
const lines = [...this.legacyPasswords.values()].map((p) => JSON.stringify(p)).join('\n');
await this.writeRaw('legacy-passwords.jsonl', lines ? lines + '\n' : '');
}
protected async flushClaimRequests(): Promise<void> {
const lines = [...this.claimRequests.values()].map((r) => JSON.stringify(r)).join('\n');
await this.writeRaw('account-claim-requests.jsonl', lines ? lines + '\n' : '');
}
protected async flushPasswordTokens(): Promise<void> {
const lines = [...this.passwordTokens.values()].map((t) => JSON.stringify(t)).join('\n');
await this.writeRaw('password-tokens.jsonl', lines ? lines + '\n' : '');
}
}
function parseJsonl<T>(
raw: string | null,
schema: { parse: (input: unknown) => T },
keyField: 'personId' | 'id' | 'tokenHash' = 'personId',
): Map<string, T> {
const map = new Map<string, T>();
if (!raw) return map;
for (const line of raw.split('\n')) {
const trimmed = line.trim();
if (!trimmed) continue;
const record = schema.parse(JSON.parse(trimmed));
const keyed = record as Record<string, unknown>;
map.set(keyed[keyField] as string, record);
}
return map;
}
export class PrivateStoreError extends Error {
readonly code: string;
override readonly cause: unknown;
constructor(code: string, message: string, cause?: unknown) {
super(message);
this.name = 'PrivateStoreError';
this.code = code;
this.cause = cause;
}
}