-
Notifications
You must be signed in to change notification settings - Fork 96
/
index.ts
305 lines (248 loc) · 11.1 KB
/
index.ts
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
import asap from "asap-es";
import {BASE64_ENCODING, KEY_BYTES_32} from "fs-json-store-encryption-adapter/lib/private/constants";
import electronLog, {ElectronLog} from "electron-log";
import {EncryptionAdapter, KeyBasedPreset} from "fs-json-store-encryption-adapter";
import * as FsJsonStore from "fs-json-store";
import path from "path";
import {buildAccountFoldersResolver, patchMetadata} from "src/electron-main/database/util";
import {buildSerializer} from "./serialization";
import {Config} from "src/shared/model/options";
import {curryFunctionMembers} from "src/shared/util";
import {DATABASE_VERSION, DB_INSTANCE_PROP_NAME} from "./constants";
import {DB_DATA_CONTAINER_FIELDS, DbAccountPk, FsDb, FsDbAccount} from "src/shared/model/database";
import {generateDataSaltBase64, hrtimeDuration} from "src/electron-main/util";
import {LogLevel} from "src/shared/model/common";
import {ONE_KB_BYTES} from "src/shared/const";
const _logger = curryFunctionMembers(electronLog, __filename);
export class Database {
static buildEmptyDb(): FsDb {
return {
version: DATABASE_VERSION,
accounts: {},
};
}
static buildEmptyAccountMetadata(): FsDbAccount["metadata"] {
return {
latestEventId: "",
};
}
static buildEmptyAccount(): FsDbAccount {
return {
conversationEntries: Object.create(null), // eslint-disable-line @typescript-eslint/no-unsafe-assignment
mails: Object.create(null), // eslint-disable-line @typescript-eslint/no-unsafe-assignment
folders: Object.create(null), // eslint-disable-line @typescript-eslint/no-unsafe-assignment
contacts: Object.create(null), // eslint-disable-line @typescript-eslint/no-unsafe-assignment
metadata: Database.buildEmptyAccountMetadata(),
deletedPks: {
conversationEntries: [],
mails: [],
folders: [],
contacts: [],
},
};
}
static mergeAccount<TL extends DbAccountPk>(
sourceDb: DeepReadonly<Database>,
targetDb: DeepReadonly<Database>,
accountPk: TL,
): boolean {
// eslint-disable-next-line @typescript-eslint/unbound-method
const logger = curryFunctionMembers(_logger, nameof(Database.mergeAccount), `${sourceDb.options.file} => ${targetDb.options.file}`);
logger.verbose();
const sourceAccount = sourceDb.getAccount(accountPk);
const targetAccount = targetDb.getMutableAccount(accountPk) || targetDb.initEmptyAccount(accountPk);
let targetPatched = false;
if (!sourceAccount) {
throw new Error(`Failed to resolve the source account for merging into the target account`);
}
// inserting new/updated entities
for (const entityType of DB_DATA_CONTAINER_FIELDS) {
const patch = sourceAccount[entityType];
const patchSize = Object.keys(patch).length;
logger.verbose(`patch size (${entityType}):`, patchSize);
if (!patchSize) {
// skipping iteration as the patch is empty
continue;
}
Object.assign(
targetAccount[entityType],
patch,
);
targetPatched = true;
}
// removing entities
for (const entityType of DB_DATA_CONTAINER_FIELDS) {
const deletedPks = sourceAccount.deletedPks[entityType];
logger.verbose("removing entities count:", deletedPks.length);
for (const pk of deletedPks) {
delete targetAccount[entityType][pk];
targetPatched = true;
}
}
{ // patching metadata
const metadataPatched = patchMetadata(targetAccount.metadata, sourceAccount.metadata, "mergeAccount");
logger.verbose(`metadata patched:`, metadataPatched);
if (metadataPatched) {
targetPatched = true;
}
}
return targetPatched;
}
private readonly logger: ElectronLog;
private readonly saveToFileQueue = new asap();
private readonly serializer: ReturnType<typeof buildSerializer>;
private [DB_INSTANCE_PROP_NAME]: FsDb = Database.buildEmptyDb();
constructor(
public readonly options: Readonly<{
file: string;
encryption: Readonly<{
resolveKey: () => Promise<string>;
resolvePreset: () => Promise<KeyBasedPreset>;
}>;
dbCompression: () => Promise<Config["dbCompression2"]>;
}>
) {
this.serializer = buildSerializer(this.options.file);
this.logger = curryFunctionMembers(_logger, `[${path.basename(this.options.file)}]`);
}
get version(): FsDb["version"] {
return this.dbInstance.version;
}
get mergeId(): FsDb["mergeId"] {
return this.dbInstance.mergeId;
}
getMutableAccount<TL extends DbAccountPk>({login}: TL): FsDbAccount | undefined {
return this.getAccount({login}) as (FsDbAccount | undefined);
}
getAccount<TL extends DbAccountPk>({login}: TL): DeepReadonly<FsDbAccount | undefined> {
const account = this.dbInstance.accounts[login];
if (!account) {
return;
}
return account;
}
initEmptyAccount<TL extends DbAccountPk>({login}: TL): FsDbAccount {
const account = Database.buildEmptyAccount();
this.dbInstance.accounts[login] = account;
return account;
}
* [Symbol.iterator](): Iterator<{ account: DeepReadonly<FsDbAccount>; pk: DeepReadonly<DbAccountPk> }> {
this.logger.info("iterator()");
const {accounts} = this.dbInstance;
for (const pk of this.getPks()) {
const account = accounts[pk.login];
if (!account) {
throw new Error("Account resolving failed");
}
yield {pk, account};
}
}
deleteAccount<TL extends DbAccountPk>({login}: TL): void {
delete this.dbInstance.accounts[login];
}
async persisted(): Promise<boolean> {
// TODO get rid of "fs-json-store" use
return new FsJsonStore.Store<FsDb>({file: this.options.file}).readable();
}
async loadFromFile(): Promise<void> {
this.logger.info(nameof(Database.prototype.loadFromFile)); // eslint-disable-line @typescript-eslint/unbound-method
if (!(await this.persisted())) {
throw new Error(`${this.options.file} does not exist`);
}
const duration = hrtimeDuration();
this.dbInstance = await this.serializer.read(
await this.buildEncryptionAdapter(),
);
this.logStats(nameof(Database.prototype.loadFromFile), duration); // eslint-disable-line @typescript-eslint/unbound-method
}
async saveToFile(): Promise<void> {
this.logger.info(nameof(Database.prototype.saveToFile)); // eslint-disable-line @typescript-eslint/unbound-method
return this.saveToFileQueue.q(async () => {
const duration = hrtimeDuration();
const dataToStore: DeepReadonly<FsDb> = {
...this.dbInstance,
version: DATABASE_VERSION,
dataSaltBase64: generateDataSaltBase64(ONE_KB_BYTES * 100, ONE_KB_BYTES * 200),
};
await this.serializer.write(
await this.buildEncryptionAdapter(),
dataToStore,
await this.options.dbCompression(),
);
this.logStats(nameof(Database.prototype.saveToFile), duration); // eslint-disable-line @typescript-eslint/unbound-method
});
}
async setMergeIdAndSaveToFile(value: FsDb["mergeId"]): Promise<void> {
this.dbInstance.mergeId = value;
await this.saveToFile();
}
reset(): void {
this.dbInstance = Database.buildEmptyDb();
}
stat(): { records: number; conversationEntries: number; mails: number; folders: number; contacts: number } {
this.logger.info(nameof(Database.prototype.stat)); // eslint-disable-line @typescript-eslint/unbound-method
const stat = {records: 0, conversationEntries: 0, mails: 0, folders: 0, contacts: 0};
for (const {account} of this) {
const {conversationEntries, mails, folders, contacts} = this.accountStat(account, true);
stat.records++;
stat.conversationEntries += conversationEntries;
stat.mails += mails;
stat.folders += folders;
stat.contacts += contacts;
}
return stat;
}
accountStat(
account: DeepReadonly<FsDbAccount>,
includingSpam: boolean,
): { conversationEntries: number; mails: number; folders: number; contacts: number; unread: number } {
const {resolveFolderById} = buildAccountFoldersResolver(account, includingSpam);
return {
// TODO measure "Object.keys(...).length" speed and then try caching the "length" if needed
conversationEntries: Object.keys(account.conversationEntries).length,
mails: Object.keys(account.mails).length,
folders: Object.keys(account.folders).length,
contacts: Object.keys(account.contacts).length,
unread: Object.values(account.mails).reduce(
(accumulator, {mailFolderIds, unread}) => {
return mailFolderIds.some((id) => resolveFolderById({id})?.notify === 1)
? accumulator + Number(unread)
: accumulator;
},
0,
),
};
}
private logStats(
methodName: string,
methodDuration: ReturnType<typeof hrtimeDuration>,
logLevel: LogLevel = "verbose",
): void {
type dataToLogType = { methodTime: number; statTime: number } & Partial<ReturnType<typeof Database.prototype.stat>>;
const dataToLog: dataToLogType = (
(): dataToLogType => {
const methodTime = methodDuration.end(); // first of all
const statsDuration = hrtimeDuration(); // before the "stat()" called
const stat = logLevel === "debug" || logLevel === "verbose"
? this.stat()
: undefined;
const statTime = statsDuration.end(); // after the "stat()" called
return {methodTime, statTime, ...stat};
}
)();
// eslint-disable-next-line @typescript-eslint/unbound-method
this.logger[logLevel](`${methodName}.${nameof(Database.prototype.logStats)}: ${JSON.stringify(dataToLog, null, 2)}`);
}
private getPks(): Array<DeepReadonly<DbAccountPk>> {
return Object
.keys(this.dbInstance.accounts)
.map((login) => ({login}));
}
private async buildEncryptionAdapter(): Promise<EncryptionAdapter> {
const key = Buffer.from(await this.options.encryption.resolveKey(), BASE64_ENCODING);
if (key.length !== KEY_BYTES_32) {
throw new Error(`Invalid encryption key length, expected: ${KEY_BYTES_32}, actual: ${key.length}`);
}
return new EncryptionAdapter({key, preset: await this.options.encryption.resolvePreset()});
}
}