@rapidmx/web-client 0.34.0 → 0.36.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/apps/escrow/matters/[uid].tsx +4 -3
- package/apps/shared/calendar/calendarLiveUpdates.ts +2 -5
- package/apps/shared/calendar/sealedEvents.ts +80 -0
- package/apps/shared/components/admin/settings/EncryptionPolicyForm.tsx +61 -3
- package/apps/shared/components/contacts/ContactsSidebar.tsx +5 -1
- package/apps/shared/components/contacts/contactCardData.ts +8 -4
- package/apps/shared/components/layout/KeyEnrollmentGate.tsx +23 -1
- package/apps/shared/components/layout/SharedMailboxKeyManager.tsx +91 -0
- package/apps/shared/components/layout/UnlockPromptProvider.tsx +34 -0
- package/apps/shared/components/mail/ConversationList.tsx +1 -1
- package/apps/shared/components/mail/MessageDetailPane.tsx +91 -20
- package/apps/shared/components/mail/compose/draftResume.ts +28 -3
- package/apps/shared/components/mail/compose/quotedBody.ts +31 -15
- package/apps/shared/components/mail/invite/inviteStore.ts +7 -1
- package/apps/shared/components/mail/layout/MailShell.tsx +2 -0
- package/apps/shared/components/mail/reading/MessageBody.tsx +4 -1
- package/apps/shared/components/mail/reading/bodyContent.ts +27 -17
- package/apps/shared/components/mail/reading/conversationPrint.ts +7 -5
- package/apps/shared/components/mail/reading/useMessageActions.ts +4 -1
- package/apps/shared/components/settings/KeyExportSetting.tsx +170 -0
- package/apps/shared/components/settings/PolicyLockedNotice.tsx +23 -0
- package/apps/shared/components/settings/ZeroAccessSetting.tsx +117 -0
- package/apps/shared/live/useFolderLiveUpdates.ts +59 -0
- package/apps/shared/mail/decryptedMessages.ts +11 -3
- package/apps/shared/mail/outbox/sendJob.ts +2 -2
- package/apps/shared/mail/outbox/sendOutcomes.ts +1 -3
- package/apps/shared/mail/reportNotices.ts +3 -1
- package/apps/shared/mail/zeroAccessSource.ts +27 -0
- package/apps/shared/search/LocalIndexLifecycle.tsx +31 -0
- package/apps/shared/search/localIndexBuilder.ts +27 -1
- package/apps/shared/search/localIndexRpcClient.ts +8 -4
- package/apps/shared/search/localIndexSchema.ts +2 -2
- package/apps/shared/search/localIndexTransport.ts +2 -1
- package/apps/shared/search/localIndexWorker.ts +6 -4
- package/apps/shared/search/zeroAccessIndexSync.ts +487 -0
- package/apps/www/calendar/index.tsx +180 -58
- package/apps/www/contacts/index.tsx +58 -2
- package/apps/www/index.tsx +10 -3
- package/apps/www/settings/encryption/index.tsx +5 -0
- package/apps/www/settings/privacy/index.tsx +2 -1
- package/apps/www/tasks/index.tsx +42 -0
- package/dist/apps/escrow/matters/[uid].js +2 -2
- package/dist/apps/shared/calendar/calendarLiveUpdates.js +2 -5
- package/dist/apps/shared/calendar/sealedEvents.d.ts +13 -0
- package/dist/apps/shared/calendar/sealedEvents.js +54 -0
- package/dist/apps/shared/components/admin/settings/EncryptionPolicyForm.js +18 -2
- package/dist/apps/shared/components/contacts/ContactsSidebar.d.ts +3 -1
- package/dist/apps/shared/components/contacts/ContactsSidebar.js +2 -2
- package/dist/apps/shared/components/contacts/contactCardData.d.ts +2 -2
- package/dist/apps/shared/components/contacts/contactCardData.js +8 -4
- package/dist/apps/shared/components/layout/KeyEnrollmentGate.js +21 -2
- package/dist/apps/shared/components/layout/SharedMailboxKeyManager.d.ts +15 -0
- package/dist/apps/shared/components/layout/SharedMailboxKeyManager.js +72 -0
- package/dist/apps/shared/components/layout/UnlockPromptProvider.d.ts +3 -0
- package/dist/apps/shared/components/layout/UnlockPromptProvider.js +32 -0
- package/dist/apps/shared/components/mail/ConversationList.js +1 -1
- package/dist/apps/shared/components/mail/MessageDetailPane.js +73 -17
- package/dist/apps/shared/components/mail/compose/draftResume.d.ts +2 -0
- package/dist/apps/shared/components/mail/compose/draftResume.js +28 -3
- package/dist/apps/shared/components/mail/compose/quotedBody.d.ts +4 -3
- package/dist/apps/shared/components/mail/compose/quotedBody.js +28 -15
- package/dist/apps/shared/components/mail/invite/inviteStore.js +6 -1
- package/dist/apps/shared/components/mail/layout/MailShell.js +2 -1
- package/dist/apps/shared/components/mail/reading/MessageBody.js +4 -1
- package/dist/apps/shared/components/mail/reading/bodyContent.d.ts +4 -2
- package/dist/apps/shared/components/mail/reading/bodyContent.js +27 -16
- package/dist/apps/shared/components/mail/reading/conversationPrint.d.ts +3 -2
- package/dist/apps/shared/components/mail/reading/conversationPrint.js +7 -5
- package/dist/apps/shared/components/mail/reading/useMessageActions.js +4 -1
- package/dist/apps/shared/components/settings/KeyExportSetting.d.ts +13 -0
- package/dist/apps/shared/components/settings/KeyExportSetting.js +88 -0
- package/dist/apps/shared/components/settings/PolicyLockedNotice.d.ts +11 -0
- package/dist/apps/shared/components/settings/PolicyLockedNotice.js +9 -0
- package/dist/apps/shared/components/settings/ZeroAccessSetting.d.ts +14 -0
- package/dist/apps/shared/components/settings/ZeroAccessSetting.js +71 -0
- package/dist/apps/shared/live/useFolderLiveUpdates.d.ts +19 -0
- package/dist/apps/shared/live/useFolderLiveUpdates.js +41 -0
- package/dist/apps/shared/mail/decryptedMessages.d.ts +1 -1
- package/dist/apps/shared/mail/decryptedMessages.js +11 -3
- package/dist/apps/shared/mail/outbox/sendJob.js +2 -2
- package/dist/apps/shared/mail/outbox/sendOutcomes.js +1 -3
- package/dist/apps/shared/mail/reportNotices.js +3 -1
- package/dist/apps/shared/mail/zeroAccessSource.d.ts +8 -0
- package/dist/apps/shared/mail/zeroAccessSource.js +26 -0
- package/dist/apps/shared/search/LocalIndexLifecycle.d.ts +2 -0
- package/dist/apps/shared/search/LocalIndexLifecycle.js +28 -0
- package/dist/apps/shared/search/localIndexBuilder.d.ts +5 -0
- package/dist/apps/shared/search/localIndexBuilder.js +24 -2
- package/dist/apps/shared/search/localIndexRpcClient.d.ts +1 -1
- package/dist/apps/shared/search/localIndexRpcClient.js +6 -4
- package/dist/apps/shared/search/localIndexSchema.d.ts +1 -1
- package/dist/apps/shared/search/localIndexSchema.js +2 -2
- package/dist/apps/shared/search/localIndexTransport.d.ts +2 -1
- package/dist/apps/shared/search/localIndexWorker.d.ts +2 -0
- package/dist/apps/shared/search/localIndexWorker.js +4 -4
- package/dist/apps/shared/search/zeroAccessIndexSync.d.ts +71 -0
- package/dist/apps/shared/search/zeroAccessIndexSync.js +382 -0
- package/dist/apps/www/calendar/index.js +48 -22
- package/dist/apps/www/contacts/index.js +49 -3
- package/dist/apps/www/index.js +10 -3
- package/dist/apps/www/settings/encryption/index.js +3 -1
- package/dist/apps/www/settings/privacy/index.js +1 -1
- package/dist/apps/www/tasks/index.js +29 -1
- package/dist/lib/admin/escrowAccessRequestsApi.d.ts +6 -0
- package/dist/lib/calendar/calendarApi.d.ts +6 -0
- package/dist/lib/calendar/inviteApi.js +27 -5
- package/dist/lib/calendar/sealedInvites.d.ts +11 -0
- package/dist/lib/calendar/sealedInvites.js +28 -0
- package/dist/lib/crypto/keyExport.d.ts +54 -0
- package/dist/lib/crypto/keyExport.js +161 -0
- package/dist/lib/crypto/keySession.d.ts +45 -1
- package/dist/lib/crypto/keySession.js +93 -2
- package/dist/lib/crypto/keyvaultApi.d.ts +88 -3
- package/dist/lib/crypto/keyvaultApi.js +32 -0
- package/dist/lib/crypto/messageSecurity.d.ts +30 -1
- package/dist/lib/crypto/messageSecurity.js +80 -4
- package/dist/lib/crypto/mime.d.ts +5 -0
- package/dist/lib/crypto/mime.js +25 -0
- package/dist/lib/crypto/sharedMailboxKeys.d.ts +50 -0
- package/dist/lib/crypto/sharedMailboxKeys.js +264 -0
- package/dist/lib/crypto/zeroAccessKey.d.ts +32 -0
- package/dist/lib/crypto/zeroAccessKey.js +66 -0
- package/dist/lib/mail/conversationsApi.d.ts +6 -0
- package/dist/lib/mail/mailApi.d.ts +30 -2
- package/dist/lib/mail/mailApi.js +5 -1
- package/dist/lib/mail/pushClient.d.ts +10 -3
- package/dist/lib/mail/pushClient.js +18 -4
- package/dist/lib/search/zeroAccessIndexApi.d.ts +81 -0
- package/dist/lib/search/zeroAccessIndexApi.js +35 -0
- package/dist/lib/tasks/tasksApi.d.ts +1 -0
- package/dist/lib/tasks/tasksApi.js +3 -0
- package/lib/admin/escrowAccessRequestsApi.ts +6 -0
- package/lib/calendar/calendarApi.ts +3 -0
- package/lib/calendar/inviteApi.ts +28 -5
- package/lib/calendar/sealedInvites.ts +33 -0
- package/lib/crypto/keyExport.ts +229 -0
- package/lib/crypto/keySession.ts +117 -3
- package/lib/crypto/keyvaultApi.ts +125 -3
- package/lib/crypto/messageSecurity.ts +110 -3
- package/lib/crypto/mime.ts +26 -0
- package/lib/crypto/sharedMailboxKeys.ts +324 -0
- package/lib/crypto/zeroAccessKey.ts +97 -0
- package/lib/mail/conversationsApi.ts +3 -0
- package/lib/mail/mailApi.ts +33 -3
- package/lib/mail/pushClient.ts +18 -4
- package/lib/search/zeroAccessIndexApi.ts +119 -0
- package/lib/tasks/tasksApi.ts +4 -0
- package/package.json +3 -3
|
@@ -251,11 +251,13 @@ async function removeLocalEntityImpl(mailboxUid: string, entityUid: string): Pro
|
|
|
251
251
|
|
|
252
252
|
/** Re-points one indexed message at its new folder (archive, cancel-scheduled-send) so `folder:`-scoped
|
|
253
253
|
* local searches stay correct. Same no-op/never-rejects rules as `removeLocalEntityImpl()`. */
|
|
254
|
-
async function moveLocalEntityImpl(mailboxUid: string, entityUid: string, folderUid: string): Promise<void> {
|
|
254
|
+
async function moveLocalEntityImpl(mailboxUid: string, entityUid: string, folderUid: string, entityVersion?: string): Promise<void> {
|
|
255
255
|
if (!initializedMailboxes.has(mailboxUid)) {
|
|
256
256
|
return;
|
|
257
257
|
}
|
|
258
|
-
await call("moveEntity", { mailboxUid, entityUid, folderUid } satisfies MoveEntityParams).catch(
|
|
258
|
+
await call("moveEntity", { mailboxUid, entityUid, folderUid, ...(entityVersion !== undefined ? { entityVersion } : {}) } satisfies MoveEntityParams).catch(
|
|
259
|
+
() => undefined,
|
|
260
|
+
);
|
|
259
261
|
}
|
|
260
262
|
|
|
261
263
|
function getIndexedVersionsImpl(mailboxUid: string, entityUids: string[]): Promise<Record<string, string>> {
|
|
@@ -410,8 +412,10 @@ export function removeLocalEntity(mailboxUid: string, entityUid: string): Promis
|
|
|
410
412
|
|
|
411
413
|
/** Re-points one indexed message at its new folder (archive, cancel-scheduled-send) so `folder:`-scoped
|
|
412
414
|
* local searches stay correct. Same no-op/never-rejects rules as `removeLocalEntity()`. */
|
|
413
|
-
export function moveLocalEntity(mailboxUid: string, entityUid: string, folderUid: string): Promise<void> {
|
|
414
|
-
return
|
|
415
|
+
export function moveLocalEntity(mailboxUid: string, entityUid: string, folderUid: string, entityVersion?: string): Promise<void> {
|
|
416
|
+
return entityVersion !== undefined
|
|
417
|
+
? currentTransport.moveEntity(mailboxUid, entityUid, folderUid, entityVersion)
|
|
418
|
+
: currentTransport.moveEntity(mailboxUid, entityUid, folderUid);
|
|
415
419
|
}
|
|
416
420
|
|
|
417
421
|
export function getIndexedVersions(mailboxUid: string, entityUids: string[]): Promise<Record<string, string>> {
|
|
@@ -121,8 +121,8 @@ export const UPSERT_ENTITY_SQL = `
|
|
|
121
121
|
INSERT INTO entities (entity_type, entity_uid, mailbox_uid, folder_uid, date_for_sort, participants, flags, has_attachments, subject, body, attachment_text, byte_size, entity_version)
|
|
122
122
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
123
123
|
ON CONFLICT(entity_uid) DO UPDATE SET
|
|
124
|
-
folder_uid = excluded.folder_uid, date_for_sort = excluded.date_for_sort, participants = excluded.participants,
|
|
125
|
-
flags = excluded.flags, has_attachments = excluded.has_attachments, subject = excluded.subject,
|
|
124
|
+
folder_uid = COALESCE(excluded.folder_uid, entities.folder_uid), date_for_sort = excluded.date_for_sort, participants = excluded.participants,
|
|
125
|
+
flags = CASE WHEN excluded.flags = '' THEN entities.flags ELSE excluded.flags END, has_attachments = excluded.has_attachments, subject = excluded.subject,
|
|
126
126
|
body = excluded.body, attachment_text = excluded.attachment_text, byte_size = excluded.byte_size,
|
|
127
127
|
entity_version = excluded.entity_version
|
|
128
128
|
`;
|
|
@@ -59,7 +59,8 @@ export interface LocalIndexTransport {
|
|
|
59
59
|
/** Drops one indexed entity. */
|
|
60
60
|
removeEntity(mailboxUid: string, entityUid: string): Promise<void>;
|
|
61
61
|
/** Re-points one indexed entity at its new folder. */
|
|
62
|
-
|
|
62
|
+
/** `entityVersion`, when given, is recorded with the folder (a transport that can't record it leaves the row's version cleared). */
|
|
63
|
+
moveEntity(mailboxUid: string, entityUid: string, folderUid: string, entityVersion?: string): Promise<void>;
|
|
63
64
|
/** The indexed version marker (`Message.version` + folder) currently stored for each of the given entity uids. */
|
|
64
65
|
indexedVersions(mailboxUid: string, entityUids: string[]): Promise<Record<string, string>>;
|
|
65
66
|
/** Removes indexed rows outside `keepEntityUids` (and `since`/`options.folderUids`'s own scope). Returns how many rows were pruned. */
|
|
@@ -124,6 +124,8 @@ export interface MoveEntityParams {
|
|
|
124
124
|
mailboxUid: string;
|
|
125
125
|
entityUid: string;
|
|
126
126
|
folderUid: string;
|
|
127
|
+
/** Recorded as the row's `entity_version`; cleared (the row then counts as changed) when absent. */
|
|
128
|
+
entityVersion?: string;
|
|
127
129
|
}
|
|
128
130
|
|
|
129
131
|
export interface IndexedVersionsParams {
|
|
@@ -636,9 +638,9 @@ async function removeEntity(connection: OpenConnection, entityUid: string): Prom
|
|
|
636
638
|
|
|
637
639
|
/** Re-points an indexed message at a new folder in place (archive, cancel-scheduled-send). Clears
|
|
638
640
|
* `entity_version` so the next build pass re-validates the row against the server. */
|
|
639
|
-
async function moveEntity(connection: OpenConnection, entityUid: string, folderUid: string): Promise<void> {
|
|
640
|
-
for await (const stmt of connection.sqlite3.statements(connection.db, "UPDATE entities SET folder_uid = ?, entity_version =
|
|
641
|
-
connection.sqlite3.bind_collection(stmt, [folderUid, entityUid]);
|
|
641
|
+
async function moveEntity(connection: OpenConnection, entityUid: string, folderUid: string, entityVersion?: string): Promise<void> {
|
|
642
|
+
for await (const stmt of connection.sqlite3.statements(connection.db, "UPDATE entities SET folder_uid = ?, entity_version = ? WHERE entity_uid = ?")) {
|
|
643
|
+
connection.sqlite3.bind_collection(stmt, [folderUid, entityVersion ?? null, entityUid]);
|
|
642
644
|
await connection.sqlite3.step(stmt);
|
|
643
645
|
}
|
|
644
646
|
}
|
|
@@ -871,7 +873,7 @@ export async function handleRequest(method: LocalIndexRequest["method"], params:
|
|
|
871
873
|
}
|
|
872
874
|
case "moveEntity": {
|
|
873
875
|
const p = params as MoveEntityParams;
|
|
874
|
-
return runExclusive(p.mailboxUid, () => withConnection(p.mailboxUid, (c) => moveEntity(c, p.entityUid, p.folderUid)));
|
|
876
|
+
return runExclusive(p.mailboxUid, () => withConnection(p.mailboxUid, (c) => moveEntity(c, p.entityUid, p.folderUid, p.entityVersion)));
|
|
875
877
|
}
|
|
876
878
|
case "indexedVersions": {
|
|
877
879
|
const p = params as IndexedVersionsParams;
|
|
@@ -0,0 +1,487 @@
|
|
|
1
|
+
///////////////////////////////////////////////////////////////////////////////
|
|
2
|
+
// Copyright (C) 2026 Jean-Philippe Steinmetz
|
|
3
|
+
// SPDX-License-Identifier: MPL-2.0
|
|
4
|
+
///////////////////////////////////////////////////////////////////////////////
|
|
5
|
+
/**
|
|
6
|
+
* Keeps this device's local search index (Tier 2) in step with a zero-access mailbox's server index (`specs/search.md` §7-8): the
|
|
7
|
+
* server extracted every message's text at delivery and stores it only encrypted to the mailbox's zero-access key, as one sealed
|
|
8
|
+
* entry per message until a client compacts a closed week into a segment. A sync pass reads the manifest; imports each segment it
|
|
9
|
+
* hasn't imported in its current generation, newest weeks first (the worker's byte budget evicts the oldest); imports the pending entries
|
|
10
|
+
* written since its last pass (the live tail, asked from a little before then, skipping what it has); and compacts a few closed weeks
|
|
11
|
+
* that still have pending entries - it decrypts them and the week's current segment, merges them, seals the result to the mailbox's
|
|
12
|
+
* active zero-access key and uploads it as the next generation. A lost race (`409`) is left to the next pass.
|
|
13
|
+
*
|
|
14
|
+
* A segment (format version 1, `specs/search.md` §16) is gzipped JSON `{ v: 1, documents }` of the same documents the entries carry, so
|
|
15
|
+
* everything is imported through `indexLocalEntities()` - no new storage primitive, on web and on tauri alike.
|
|
16
|
+
*
|
|
17
|
+
* **Client segments (Source C).** End-to-end mail never reaches the server readable, so the server has nothing to index for it: the local
|
|
18
|
+
* index builder (`localIndexBuilder.ts`) decrypts it on one device and uploads what it built with `uploadClientDocuments()`, as `origin:
|
|
19
|
+
* "client"` segments sealed to the same zero-access key, merged into the week's current one. Every device imports them
|
|
20
|
+
* (`importClientSegments()`, run by the builder before it decrypts anything and by each sync pass), so end-to-end mail is decrypted for
|
|
21
|
+
* search once per mailbox rather than once per device - a row imported at the message's current version is not decrypted again.
|
|
22
|
+
*
|
|
23
|
+
* Nothing here ever sends the server anything it can read: entries are decrypted on this device, and a segment is sealed before upload.
|
|
24
|
+
*/
|
|
25
|
+
import { fromBase64, toBase64 } from "../../../lib/crypto/encoding.js";
|
|
26
|
+
import type { UnlockedKeys } from "../../../lib/crypto/keySession.js";
|
|
27
|
+
import { decryptEnvelopedDataWithKeys, encryptForRecipients } from "../../../lib/crypto/smime.js";
|
|
28
|
+
import {
|
|
29
|
+
getSearchIndexManifest,
|
|
30
|
+
getSearchIndexSegment,
|
|
31
|
+
type IndexSegment,
|
|
32
|
+
listSearchIndexEntries,
|
|
33
|
+
type SegmentManifest,
|
|
34
|
+
putSearchIndexSegment,
|
|
35
|
+
type SealedIndexEntry,
|
|
36
|
+
type ZeroAccessIndexDocument,
|
|
37
|
+
} from "../../../lib/search/zeroAccessIndexApi.js";
|
|
38
|
+
import { ApiRequestError, type ApiClient } from "../../../lib/util/api.js";
|
|
39
|
+
import { getLocalCoverage, indexLocalEntities } from "./localIndexRpcClient.js";
|
|
40
|
+
import type { LocalIndexEntity } from "./localIndexSchema.js";
|
|
41
|
+
|
|
42
|
+
/** The segment format this client writes and reads. */
|
|
43
|
+
export const SEGMENT_SCHEMA_VERSION = 1;
|
|
44
|
+
|
|
45
|
+
/** How far before its last pass the live tail asks again, so an entry committed late is never skipped. */
|
|
46
|
+
export const TAIL_OVERLAP_MS = 10 * 60 * 1000;
|
|
47
|
+
|
|
48
|
+
/** At most this many weeks are compacted per pass, so a large backlog is worked through over several passes. */
|
|
49
|
+
export const MAX_COMPACTIONS_PER_PASS = 4;
|
|
50
|
+
|
|
51
|
+
/** Entities handed to the worker per call. */
|
|
52
|
+
const IMPORT_BATCH = 200;
|
|
53
|
+
|
|
54
|
+
/** How many times `uploadClientDocuments()` re-reads a week's client segment after another device replaced it first. */
|
|
55
|
+
export const CLIENT_UPLOAD_ATTEMPTS = 3;
|
|
56
|
+
|
|
57
|
+
/** What a sync pass remembers between passes, per mailbox (`localStorage`): which segment generations it imported and when its live tail
|
|
58
|
+
* last ran. Forgotten whenever the local index is found empty (a new device, a sign-out, a destroyed index). */
|
|
59
|
+
interface SyncState {
|
|
60
|
+
/** `weekId:origin` -> the ETag imported. */
|
|
61
|
+
segments: Record<string, string>;
|
|
62
|
+
/** ISO 8601: when the last live-tail pass started. */
|
|
63
|
+
tailSince?: string;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** What a pass did, for the caller's logging and tests. */
|
|
67
|
+
export interface ZeroAccessSyncResult {
|
|
68
|
+
segmentsImported: number;
|
|
69
|
+
/** Client segments (end-to-end mail other devices indexed) imported. */
|
|
70
|
+
clientSegmentsImported: number;
|
|
71
|
+
entriesImported: number;
|
|
72
|
+
weeksCompacted: number;
|
|
73
|
+
/** Entries or segments that wouldn't decrypt with this device's keys (a key it doesn't have) - left as they are. */
|
|
74
|
+
unreadable: number;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const stateKey = (mailboxUid: string): string => `rapidmx:za-index-sync:${mailboxUid}`;
|
|
78
|
+
|
|
79
|
+
function loadState(mailboxUid: string): SyncState {
|
|
80
|
+
try {
|
|
81
|
+
const raw = localStorage.getItem(stateKey(mailboxUid));
|
|
82
|
+
const parsed: unknown = raw ? JSON.parse(raw) : undefined;
|
|
83
|
+
if (parsed && typeof parsed === "object" && typeof (parsed as SyncState).segments === "object") {
|
|
84
|
+
return parsed as SyncState;
|
|
85
|
+
}
|
|
86
|
+
} catch {
|
|
87
|
+
// Storage unavailable or corrupt: start over, which only costs a re-import.
|
|
88
|
+
}
|
|
89
|
+
return { segments: {} };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function saveState(mailboxUid: string, state: SyncState): void {
|
|
93
|
+
try {
|
|
94
|
+
localStorage.setItem(stateKey(mailboxUid), JSON.stringify(state));
|
|
95
|
+
} catch {
|
|
96
|
+
// Not remembered: the next pass imports again, which is idempotent (entities are upserted).
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Forgets what a pass remembered for `mailboxUid` (e.g. when its local index is destroyed). */
|
|
101
|
+
export function forgetZeroAccessSync(mailboxUid: string): void {
|
|
102
|
+
try {
|
|
103
|
+
localStorage.removeItem(stateKey(mailboxUid));
|
|
104
|
+
} catch {
|
|
105
|
+
// Nothing to forget.
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function transform(bytes: Uint8Array, stream: CompressionStream | DecompressionStream): Promise<Uint8Array> {
|
|
110
|
+
const output = new Blob([bytes as BlobPart]).stream().pipeThrough(stream);
|
|
111
|
+
return new Uint8Array(await new Response(output).arrayBuffer());
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const gunzip = (bytes: Uint8Array): Promise<Uint8Array> => transform(bytes, new DecompressionStream("gzip"));
|
|
115
|
+
const gzip = (bytes: Uint8Array): Promise<Uint8Array> => transform(bytes, new CompressionStream("gzip"));
|
|
116
|
+
|
|
117
|
+
/** The keys that open what the server sealed for this mailbox. */
|
|
118
|
+
type ZeroAccessKeys = NonNullable<UnlockedKeys["zeroAccessKeys"]>;
|
|
119
|
+
|
|
120
|
+
/** Decrypts and gunzips `der` with `keys` and parses the JSON inside - `undefined` when no key opens it or it isn't JSON. */
|
|
121
|
+
async function openSealedJson(der: Uint8Array, keys: ZeroAccessKeys): Promise<unknown> {
|
|
122
|
+
try {
|
|
123
|
+
return JSON.parse(new TextDecoder().decode(await gunzip(await decryptEnvelopedDataWithKeys(der, keys))));
|
|
124
|
+
} catch {
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function isDocument(value: unknown): value is ZeroAccessIndexDocument {
|
|
130
|
+
const doc = value as ZeroAccessIndexDocument | undefined;
|
|
131
|
+
return !!doc && doc.v === 1 && typeof doc.messageUid === "string" && typeof doc.subject === "string" && typeof doc.body === "string";
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** A document as a row of the local index. Folder and flags aren't in the document - the builder records the folder
|
|
135
|
+
* (`localIndexBuilder.ts`), and the upsert keeps what is already there. */
|
|
136
|
+
export function documentEntity(mailboxUid: string, doc: ZeroAccessIndexDocument): LocalIndexEntity {
|
|
137
|
+
const participants: string = (doc.participants ?? []).join(" ");
|
|
138
|
+
const attachmentText: string = [...(doc.attachmentNames ?? []), ...(doc.attachmentText ?? [])].join("\n");
|
|
139
|
+
return {
|
|
140
|
+
entityType: "message",
|
|
141
|
+
entityUid: doc.messageUid,
|
|
142
|
+
mailboxUid,
|
|
143
|
+
dateForSort: new Date(Number.isFinite(doc.dateForSort) ? doc.dateForSort : 0).toISOString(),
|
|
144
|
+
participants,
|
|
145
|
+
flags: "",
|
|
146
|
+
hasAttachments: (doc.attachmentNames ?? []).length > 0,
|
|
147
|
+
subject: doc.subject,
|
|
148
|
+
body: doc.body,
|
|
149
|
+
attachmentText,
|
|
150
|
+
byteSize: doc.subject.length + doc.body.length + attachmentText.length + participants.length,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function importDocuments(mailboxUid: string, docs: ZeroAccessIndexDocument[]): Promise<void> {
|
|
155
|
+
for (let i = 0; i < docs.length; i += IMPORT_BATCH) {
|
|
156
|
+
await indexLocalEntities(
|
|
157
|
+
mailboxUid,
|
|
158
|
+
docs.slice(i, i + IMPORT_BATCH).map((doc) => documentEntity(mailboxUid, doc)),
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** The documents of a segment generation that pass `accept`, or `undefined` when it won't open or is a format this client doesn't read. */
|
|
164
|
+
async function readSegmentAs<T>(
|
|
165
|
+
mailboxUid: string,
|
|
166
|
+
segment: IndexSegment,
|
|
167
|
+
keys: ZeroAccessKeys,
|
|
168
|
+
accept: (value: unknown) => value is T,
|
|
169
|
+
client?: ApiClient,
|
|
170
|
+
): Promise<T[] | undefined> {
|
|
171
|
+
if (segment.schemaVersion !== SEGMENT_SCHEMA_VERSION) {
|
|
172
|
+
return undefined;
|
|
173
|
+
}
|
|
174
|
+
const bundle = (await openSealedJson(await getSearchIndexSegment(mailboxUid, segment, client), keys)) as { v?: number; documents?: unknown[] } | undefined;
|
|
175
|
+
return bundle?.v === SEGMENT_SCHEMA_VERSION && Array.isArray(bundle.documents) ? bundle.documents.filter(accept) : undefined;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const readSegment = (mailboxUid: string, segment: IndexSegment, keys: ZeroAccessKeys, client?: ApiClient): Promise<ZeroAccessIndexDocument[] | undefined> =>
|
|
179
|
+
readSegmentAs(mailboxUid, segment, keys, isDocument, client);
|
|
180
|
+
|
|
181
|
+
/** `documents` gzipped and sealed to `key` as a segment file, base64. */
|
|
182
|
+
async function sealSegment(documents: unknown[], key: ZeroAccessKeys[number]): Promise<string> {
|
|
183
|
+
const file = await gzip(new TextEncoder().encode(JSON.stringify({ v: SEGMENT_SCHEMA_VERSION, documents })));
|
|
184
|
+
return toBase64(await encryptForRecipients(file, [key.certDer]));
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** One document of a client segment: a local index row of an end-to-end message, as the device that decrypted it built it. */
|
|
188
|
+
export interface ClientIndexDocument {
|
|
189
|
+
v: 1;
|
|
190
|
+
messageUid: string;
|
|
191
|
+
folderUid?: string;
|
|
192
|
+
/** ISO 8601. */
|
|
193
|
+
dateForSort: string;
|
|
194
|
+
participants: string;
|
|
195
|
+
flags: string;
|
|
196
|
+
hasAttachments: boolean;
|
|
197
|
+
subject?: string;
|
|
198
|
+
body?: string;
|
|
199
|
+
attachmentText?: string;
|
|
200
|
+
/** The message's version when it was decrypted (`localIndexBuilder.ts`'s `versionOf()`). */
|
|
201
|
+
entityVersion?: string;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function isClientDocument(value: unknown): value is ClientIndexDocument {
|
|
205
|
+
const doc = value as ClientIndexDocument | undefined;
|
|
206
|
+
return !!doc && doc.v === 1 && typeof doc.messageUid === "string" && typeof doc.dateForSort === "string" && typeof doc.participants === "string";
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** A local index row as a client segment document. */
|
|
210
|
+
export function clientDocument(entity: LocalIndexEntity): ClientIndexDocument {
|
|
211
|
+
return {
|
|
212
|
+
v: 1,
|
|
213
|
+
messageUid: entity.entityUid,
|
|
214
|
+
folderUid: entity.folderUid,
|
|
215
|
+
dateForSort: entity.dateForSort,
|
|
216
|
+
participants: entity.participants,
|
|
217
|
+
flags: entity.flags,
|
|
218
|
+
hasAttachments: entity.hasAttachments,
|
|
219
|
+
subject: entity.subject,
|
|
220
|
+
body: entity.body,
|
|
221
|
+
attachmentText: entity.attachmentText,
|
|
222
|
+
entityVersion: entity.entityVersion,
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** A client segment document as a row of the local index. */
|
|
227
|
+
export function clientDocumentEntity(mailboxUid: string, doc: ClientIndexDocument): LocalIndexEntity {
|
|
228
|
+
const text: number = [doc.subject, doc.body, doc.attachmentText, doc.participants].reduce((total, value) => total + (value?.length ?? 0), 0);
|
|
229
|
+
return {
|
|
230
|
+
entityType: "message",
|
|
231
|
+
entityUid: doc.messageUid,
|
|
232
|
+
mailboxUid,
|
|
233
|
+
...(doc.folderUid !== undefined ? { folderUid: doc.folderUid } : {}),
|
|
234
|
+
dateForSort: doc.dateForSort,
|
|
235
|
+
participants: doc.participants,
|
|
236
|
+
flags: typeof doc.flags === "string" ? doc.flags : "",
|
|
237
|
+
hasAttachments: doc.hasAttachments === true,
|
|
238
|
+
...(doc.subject !== undefined ? { subject: doc.subject } : {}),
|
|
239
|
+
...(doc.body !== undefined ? { body: doc.body } : {}),
|
|
240
|
+
...(doc.attachmentText !== undefined ? { attachmentText: doc.attachmentText } : {}),
|
|
241
|
+
byteSize: text,
|
|
242
|
+
...(doc.entityVersion !== undefined ? { entityVersion: doc.entityVersion } : {}),
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** The ISO 8601 week (UTC) of `date`, as `YYYY-Www` - the week a message's segment is filed under (restapi's `isoWeekId()`). */
|
|
247
|
+
export function isoWeekId(date: Date): string {
|
|
248
|
+
const day = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
|
|
249
|
+
// The Thursday of this ISO week decides its year (weeks start on Monday; getUTCDay() has Sunday as 0).
|
|
250
|
+
const weekday: number = day.getUTCDay() || 7;
|
|
251
|
+
day.setUTCDate(day.getUTCDate() + 4 - weekday);
|
|
252
|
+
const yearStart = new Date(Date.UTC(day.getUTCFullYear(), 0, 1));
|
|
253
|
+
const week: number = Math.ceil(((day.getTime() - yearStart.getTime()) / 86_400_000 + 1) / 7);
|
|
254
|
+
return `${day.getUTCFullYear()}-W${String(week).padStart(2, "0")}`;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** The sync state, started over when the local index is empty (nothing remembered in it is there any more). */
|
|
258
|
+
async function currentState(mailboxUid: string): Promise<SyncState> {
|
|
259
|
+
return (await getLocalCoverage(mailboxUid)).indexedCount === 0 ? { segments: {} } : loadState(mailboxUid);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Imports the client segments of `mailboxUid` (end-to-end mail indexed by another device - see this module's comment) not yet imported in
|
|
264
|
+
* their current generation, newest week first: how many. `manifest` saves reading it again; `generation` is the calling build pass's (see
|
|
265
|
+
* `GenerationParams`). Segments this device can't open are skipped.
|
|
266
|
+
*/
|
|
267
|
+
export async function importClientSegments(
|
|
268
|
+
mailboxUid: string,
|
|
269
|
+
unlocked: UnlockedKeys,
|
|
270
|
+
client?: ApiClient,
|
|
271
|
+
{ manifest, generation }: { manifest?: SegmentManifest; generation?: number } = {},
|
|
272
|
+
): Promise<number> {
|
|
273
|
+
const keys: ZeroAccessKeys | undefined = unlocked.zeroAccessKeys;
|
|
274
|
+
if (!keys?.length) {
|
|
275
|
+
return 0;
|
|
276
|
+
}
|
|
277
|
+
const segments: IndexSegment[] = (manifest ?? (await getSearchIndexManifest(mailboxUid, client))).segments.filter((segment) => segment.origin === "client");
|
|
278
|
+
const state: SyncState = await currentState(mailboxUid);
|
|
279
|
+
let imported = 0;
|
|
280
|
+
for (const segment of segments.sort((a, b) => b.weekId.localeCompare(a.weekId))) {
|
|
281
|
+
const key = `${segment.weekId}:${segment.origin}`;
|
|
282
|
+
if (state.segments[key] === segment.etag) {
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
const docs = await readSegmentAs(mailboxUid, segment, keys, isClientDocument, client);
|
|
286
|
+
if (!docs) {
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
for (let i = 0; i < docs.length; i += IMPORT_BATCH) {
|
|
290
|
+
await indexLocalEntities(
|
|
291
|
+
mailboxUid,
|
|
292
|
+
docs.slice(i, i + IMPORT_BATCH).map((doc) => clientDocumentEntity(mailboxUid, doc)),
|
|
293
|
+
generation,
|
|
294
|
+
);
|
|
295
|
+
}
|
|
296
|
+
state.segments[key] = segment.etag;
|
|
297
|
+
saveState(mailboxUid, state);
|
|
298
|
+
imported++;
|
|
299
|
+
}
|
|
300
|
+
return imported;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Uploads end-to-end messages this device just decrypted and indexed (`entities`) to `mailboxUid`'s client segments, one per ISO week of
|
|
305
|
+
* `dateForSort`, each merged by message into the week's current segment and sealed to the active zero-access key: how many weeks were
|
|
306
|
+
* written. A week whose current segment this device can't read is left alone (merging would drop what is in it), as is one that already
|
|
307
|
+
* holds every document at the same version. Another device replacing a week first (`409`) is retried with its generation, up to
|
|
308
|
+
* `CLIENT_UPLOAD_ATTEMPTS` times. Does nothing without unlocked zero-access keys.
|
|
309
|
+
*/
|
|
310
|
+
export async function uploadClientDocuments(mailboxUid: string, unlocked: UnlockedKeys, entities: LocalIndexEntity[], client?: ApiClient): Promise<number> {
|
|
311
|
+
const keys: ZeroAccessKeys | undefined = unlocked.zeroAccessKeys;
|
|
312
|
+
if (!keys?.length || entities.length === 0) {
|
|
313
|
+
return 0;
|
|
314
|
+
}
|
|
315
|
+
const weeks = new Map<string, ClientIndexDocument[]>();
|
|
316
|
+
for (const entity of entities) {
|
|
317
|
+
const weekId: string = isoWeekId(new Date(entity.dateForSort));
|
|
318
|
+
weeks.set(weekId, [...(weeks.get(weekId) ?? []), clientDocument(entity)]);
|
|
319
|
+
}
|
|
320
|
+
const state: SyncState = loadState(mailboxUid);
|
|
321
|
+
let written = 0;
|
|
322
|
+
let manifest: SegmentManifest | undefined;
|
|
323
|
+
for (const [weekId, docs] of weeks) {
|
|
324
|
+
for (let attempt = 0; attempt < CLIENT_UPLOAD_ATTEMPTS; attempt++) {
|
|
325
|
+
manifest ??= await getSearchIndexManifest(mailboxUid, client);
|
|
326
|
+
const current: IndexSegment | undefined = manifest.segments.find((segment) => segment.origin === "client" && segment.weekId === weekId);
|
|
327
|
+
const previous: ClientIndexDocument[] | undefined = current ? await readSegmentAs(mailboxUid, current, keys, isClientDocument, client) : [];
|
|
328
|
+
if (!previous) {
|
|
329
|
+
break;
|
|
330
|
+
}
|
|
331
|
+
const merged = new Map<string, ClientIndexDocument>(previous.map((doc) => [doc.messageUid, doc]));
|
|
332
|
+
if (docs.every((doc) => merged.has(doc.messageUid) && merged.get(doc.messageUid)!.entityVersion === doc.entityVersion)) {
|
|
333
|
+
break;
|
|
334
|
+
}
|
|
335
|
+
for (const doc of docs) {
|
|
336
|
+
merged.set(doc.messageUid, doc);
|
|
337
|
+
}
|
|
338
|
+
try {
|
|
339
|
+
const stored = await putSearchIndexSegment(
|
|
340
|
+
mailboxUid,
|
|
341
|
+
weekId,
|
|
342
|
+
{
|
|
343
|
+
expectedGeneration: current?.generation ?? 0,
|
|
344
|
+
segment: await sealSegment([...merged.values()], keys[0]),
|
|
345
|
+
keyFingerprint: keys[0].fingerprint,
|
|
346
|
+
schemaVersion: SEGMENT_SCHEMA_VERSION,
|
|
347
|
+
origin: "client",
|
|
348
|
+
},
|
|
349
|
+
client,
|
|
350
|
+
);
|
|
351
|
+
// This device already holds every document of the new generation only if it held the previous one.
|
|
352
|
+
if (current && state.segments[`${weekId}:client`] === current.etag) {
|
|
353
|
+
state.segments[`${weekId}:client`] = stored.etag;
|
|
354
|
+
saveState(mailboxUid, state);
|
|
355
|
+
}
|
|
356
|
+
written++;
|
|
357
|
+
break;
|
|
358
|
+
} catch (err) {
|
|
359
|
+
if (!(err instanceof ApiRequestError && err.status === 409)) {
|
|
360
|
+
throw err;
|
|
361
|
+
}
|
|
362
|
+
manifest = undefined;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
return written;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** Every pending entry of `week` (or, without one, written since `since`), paged through. */
|
|
370
|
+
async function listAllEntries(mailboxUid: string, filter: { week?: string; since?: string }, client?: ApiClient): Promise<SealedIndexEntry[]> {
|
|
371
|
+
const entries: SealedIndexEntry[] = [];
|
|
372
|
+
let after: string | undefined;
|
|
373
|
+
do {
|
|
374
|
+
const page = await listSearchIndexEntries(mailboxUid, { ...filter, ...(after ? { after } : {}) }, client);
|
|
375
|
+
entries.push(...page.entries);
|
|
376
|
+
after = page.next;
|
|
377
|
+
} while (after);
|
|
378
|
+
return entries;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** The documents of `entries` that open, with the uids of those entries; how many didn't. */
|
|
382
|
+
async function openEntries(entries: SealedIndexEntry[], keys: ZeroAccessKeys): Promise<{ docs: ZeroAccessIndexDocument[]; uids: string[]; unreadable: number }> {
|
|
383
|
+
const docs: ZeroAccessIndexDocument[] = [];
|
|
384
|
+
const uids: string[] = [];
|
|
385
|
+
let unreadable = 0;
|
|
386
|
+
for (const entry of entries) {
|
|
387
|
+
const doc = await openSealedJson(fromBase64(entry.sealed), keys);
|
|
388
|
+
if (isDocument(doc)) {
|
|
389
|
+
docs.push(doc);
|
|
390
|
+
uids.push(entry.uid);
|
|
391
|
+
} else {
|
|
392
|
+
unreadable++;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
return { docs, uids, unreadable };
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* One sync pass for `mailboxUid` (see this module's comment). Does nothing without unlocked zero-access keys. Rejects when the manifest
|
|
400
|
+
* can't be read; any later failure ends the pass early with what it had done so far remembered.
|
|
401
|
+
*/
|
|
402
|
+
export async function syncZeroAccessIndex(mailboxUid: string, unlocked: UnlockedKeys, client?: ApiClient): Promise<ZeroAccessSyncResult> {
|
|
403
|
+
const result: ZeroAccessSyncResult = { segmentsImported: 0, clientSegmentsImported: 0, entriesImported: 0, weeksCompacted: 0, unreadable: 0 };
|
|
404
|
+
const keys: ZeroAccessKeys | undefined = unlocked.zeroAccessKeys;
|
|
405
|
+
if (!keys?.length) {
|
|
406
|
+
return result;
|
|
407
|
+
}
|
|
408
|
+
const manifest = await getSearchIndexManifest(mailboxUid, client);
|
|
409
|
+
let state: SyncState = await currentState(mailboxUid);
|
|
410
|
+
|
|
411
|
+
// Segments, newest week first.
|
|
412
|
+
const zeroAccessSegments: IndexSegment[] = manifest.segments.filter((segment) => segment.origin === "zero-access");
|
|
413
|
+
for (const segment of [...zeroAccessSegments].sort((a, b) => b.weekId.localeCompare(a.weekId))) {
|
|
414
|
+
const key = `${segment.weekId}:${segment.origin}`;
|
|
415
|
+
if (state.segments[key] === segment.etag) {
|
|
416
|
+
continue;
|
|
417
|
+
}
|
|
418
|
+
const docs = await readSegment(mailboxUid, segment, keys, client);
|
|
419
|
+
if (!docs) {
|
|
420
|
+
result.unreadable++;
|
|
421
|
+
continue;
|
|
422
|
+
}
|
|
423
|
+
await importDocuments(mailboxUid, docs);
|
|
424
|
+
state.segments[key] = segment.etag;
|
|
425
|
+
result.segmentsImported++;
|
|
426
|
+
saveState(mailboxUid, state);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// End-to-end mail other devices indexed.
|
|
430
|
+
saveState(mailboxUid, state);
|
|
431
|
+
result.clientSegmentsImported = await importClientSegments(mailboxUid, unlocked, client, { manifest });
|
|
432
|
+
state = loadState(mailboxUid);
|
|
433
|
+
|
|
434
|
+
// The live tail.
|
|
435
|
+
const tailStart = new Date().toISOString();
|
|
436
|
+
const since = state.tailSince ? new Date(new Date(state.tailSince).getTime() - TAIL_OVERLAP_MS).toISOString() : undefined;
|
|
437
|
+
const tail = await openEntries(await listAllEntries(mailboxUid, since ? { since } : {}, client), keys);
|
|
438
|
+
await importDocuments(mailboxUid, tail.docs);
|
|
439
|
+
result.entriesImported += tail.docs.length;
|
|
440
|
+
result.unreadable += tail.unreadable;
|
|
441
|
+
state.tailSince = tailStart;
|
|
442
|
+
saveState(mailboxUid, state);
|
|
443
|
+
|
|
444
|
+
// Compaction of closed weeks.
|
|
445
|
+
const active = keys[0];
|
|
446
|
+
for (const week of manifest.weeks.filter((w) => w.compactable && w.pendingEntries > 0).slice(0, MAX_COMPACTIONS_PER_PASS)) {
|
|
447
|
+
const current: IndexSegment | undefined = zeroAccessSegments.find((segment) => segment.weekId === week.weekId);
|
|
448
|
+
const previous: ZeroAccessIndexDocument[] | undefined = current ? await readSegment(mailboxUid, current, keys, client) : [];
|
|
449
|
+
if (!previous) {
|
|
450
|
+
// A generation this device can't read can't be folded into: leave the week to a device that can.
|
|
451
|
+
continue;
|
|
452
|
+
}
|
|
453
|
+
const pending = await openEntries(await listAllEntries(mailboxUid, { week: week.weekId }, client), keys);
|
|
454
|
+
if (pending.uids.length === 0) {
|
|
455
|
+
continue;
|
|
456
|
+
}
|
|
457
|
+
const merged = new Map<string, ZeroAccessIndexDocument>(previous.map((doc) => [doc.messageUid, doc]));
|
|
458
|
+
for (const doc of pending.docs) {
|
|
459
|
+
merged.set(doc.messageUid, doc);
|
|
460
|
+
}
|
|
461
|
+
try {
|
|
462
|
+
const stored = await putSearchIndexSegment(
|
|
463
|
+
mailboxUid,
|
|
464
|
+
week.weekId,
|
|
465
|
+
{
|
|
466
|
+
expectedGeneration: current?.generation ?? 0,
|
|
467
|
+
segment: await sealSegment([...merged.values()], active),
|
|
468
|
+
keyFingerprint: active.fingerprint,
|
|
469
|
+
schemaVersion: SEGMENT_SCHEMA_VERSION,
|
|
470
|
+
foldedEntryUids: pending.uids,
|
|
471
|
+
},
|
|
472
|
+
client,
|
|
473
|
+
);
|
|
474
|
+
// This device already holds every document of the new generation.
|
|
475
|
+
await importDocuments(mailboxUid, pending.docs);
|
|
476
|
+
state.segments[`${stored.weekId}:${stored.origin}`] = stored.etag;
|
|
477
|
+
saveState(mailboxUid, state);
|
|
478
|
+
result.weeksCompacted++;
|
|
479
|
+
} catch (err) {
|
|
480
|
+
// Another device compacted the week first: the next pass imports its generation.
|
|
481
|
+
if (!(err instanceof ApiRequestError && err.status === 409)) {
|
|
482
|
+
throw err;
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
return result;
|
|
487
|
+
}
|