2021-04-05 22:18:19 +00:00
|
|
|
// Copyright 2021 Signal Messenger, LLC
|
|
|
|
// SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
|
|
|
|
import { join } from 'path';
|
|
|
|
import { Worker } from 'worker_threads';
|
2021-09-16 21:54:06 +00:00
|
|
|
import { format } from 'util';
|
2022-03-29 17:06:42 +00:00
|
|
|
import { app } from 'electron';
|
2021-04-05 22:18:19 +00:00
|
|
|
|
2021-09-16 21:54:06 +00:00
|
|
|
import { strictAssert } from '../util/assert';
|
2021-09-08 20:39:14 +00:00
|
|
|
import { explodePromise } from '../util/explodePromise';
|
2021-09-16 21:54:06 +00:00
|
|
|
import type { LoggerType } from '../types/Logging';
|
2023-10-10 23:19:11 +00:00
|
|
|
import { SqliteErrorKind } from './errors';
|
2024-07-22 18:16:33 +00:00
|
|
|
import type {
|
|
|
|
ServerReadableDirectInterface,
|
|
|
|
ServerWritableDirectInterface,
|
|
|
|
} from './Interface';
|
2021-09-08 20:39:14 +00:00
|
|
|
|
2021-08-09 22:04:17 +00:00
|
|
|
const MIN_TRACE_DURATION = 40;
|
2021-04-14 19:43:11 +00:00
|
|
|
|
2024-07-22 18:16:33 +00:00
|
|
|
const WORKER_COUNT = 4;
|
|
|
|
|
2021-09-16 21:54:06 +00:00
|
|
|
export type InitializeOptions = Readonly<{
|
2023-10-10 23:55:32 +00:00
|
|
|
appVersion: string;
|
2021-09-16 21:54:06 +00:00
|
|
|
configDir: string;
|
|
|
|
key: string;
|
|
|
|
logger: LoggerType;
|
|
|
|
}>;
|
2021-04-05 22:18:19 +00:00
|
|
|
|
2021-09-16 21:54:06 +00:00
|
|
|
export type WorkerRequest = Readonly<
|
2021-04-05 22:18:19 +00:00
|
|
|
| {
|
2021-09-16 21:54:06 +00:00
|
|
|
type: 'init';
|
|
|
|
options: Omit<InitializeOptions, 'logger'>;
|
2024-07-22 18:16:33 +00:00
|
|
|
isPrimary: boolean;
|
2021-04-05 22:18:19 +00:00
|
|
|
}
|
|
|
|
| {
|
2024-07-22 18:16:33 +00:00
|
|
|
type: 'close' | 'removeDB';
|
2021-04-05 22:18:19 +00:00
|
|
|
}
|
2021-07-10 00:43:36 +00:00
|
|
|
| {
|
2024-07-22 18:16:33 +00:00
|
|
|
type: 'sqlCall:read';
|
|
|
|
method: keyof ServerReadableDirectInterface;
|
|
|
|
args: ReadonlyArray<unknown>;
|
2021-07-10 00:43:36 +00:00
|
|
|
}
|
2021-04-05 22:18:19 +00:00
|
|
|
| {
|
2024-07-22 18:16:33 +00:00
|
|
|
type: 'sqlCall:write';
|
|
|
|
method: keyof ServerWritableDirectInterface;
|
2022-11-17 00:29:15 +00:00
|
|
|
args: ReadonlyArray<unknown>;
|
2021-09-16 21:54:06 +00:00
|
|
|
}
|
|
|
|
>;
|
|
|
|
|
|
|
|
export type WrappedWorkerRequest = Readonly<{
|
|
|
|
seq: number;
|
|
|
|
request: WorkerRequest;
|
|
|
|
}>;
|
|
|
|
|
|
|
|
export type WrappedWorkerLogEntry = Readonly<{
|
|
|
|
type: 'log';
|
|
|
|
level: 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace';
|
|
|
|
args: ReadonlyArray<unknown>;
|
|
|
|
}>;
|
|
|
|
|
|
|
|
export type WrappedWorkerResponse =
|
|
|
|
| Readonly<{
|
|
|
|
type: 'response';
|
|
|
|
seq: number;
|
|
|
|
error: string | undefined;
|
2023-10-10 23:19:11 +00:00
|
|
|
errorKind: SqliteErrorKind | undefined;
|
2021-09-16 21:54:06 +00:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
|
|
response: any;
|
|
|
|
}>
|
|
|
|
| WrappedWorkerLogEntry;
|
2021-04-05 22:18:19 +00:00
|
|
|
|
|
|
|
type PromisePair<T> = {
|
|
|
|
resolve: (response: T) => void;
|
|
|
|
reject: (error: Error) => void;
|
|
|
|
};
|
|
|
|
|
2023-03-02 17:59:18 +00:00
|
|
|
type KnownErrorResolverType = Readonly<{
|
|
|
|
kind: SqliteErrorKind;
|
|
|
|
resolve: (err: Error) => void;
|
|
|
|
}>;
|
|
|
|
|
2024-07-22 18:16:33 +00:00
|
|
|
type CreateWorkerResultType = Readonly<{
|
|
|
|
worker: Worker;
|
|
|
|
onExit: Promise<void>;
|
|
|
|
}>;
|
|
|
|
|
|
|
|
type PoolEntry = {
|
|
|
|
readonly worker: Worker;
|
|
|
|
load: number;
|
|
|
|
};
|
|
|
|
|
2021-04-05 22:18:19 +00:00
|
|
|
export class MainSQL {
|
2024-07-22 18:16:33 +00:00
|
|
|
private readonly pool = new Array<PoolEntry>();
|
|
|
|
|
|
|
|
private pauseWaiters: Array<() => void> | undefined;
|
2021-04-05 22:18:19 +00:00
|
|
|
|
2021-04-08 23:27:41 +00:00
|
|
|
private isReady = false;
|
|
|
|
|
|
|
|
private onReady: Promise<void> | undefined;
|
|
|
|
|
2024-07-22 18:16:33 +00:00
|
|
|
private readonly onExit: Promise<unknown>;
|
2021-04-05 22:18:19 +00:00
|
|
|
|
2023-03-02 17:59:18 +00:00
|
|
|
// Promise resolve callbacks for corruption and readonly errors.
|
|
|
|
private errorResolvers = new Array<KnownErrorResolverType>();
|
2021-09-08 20:39:14 +00:00
|
|
|
|
2021-04-05 22:18:19 +00:00
|
|
|
private seq = 0;
|
|
|
|
|
2021-09-16 21:54:06 +00:00
|
|
|
private logger?: LoggerType;
|
|
|
|
|
2021-04-05 22:18:19 +00:00
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
|
|
private onResponse = new Map<number, PromisePair<any>>();
|
|
|
|
|
2023-07-15 00:52:20 +00:00
|
|
|
private shouldTimeQueries = false;
|
|
|
|
|
2021-04-05 22:18:19 +00:00
|
|
|
constructor() {
|
2024-07-22 18:16:33 +00:00
|
|
|
const exitPromises = new Array<Promise<void>>();
|
|
|
|
for (let i = 0; i < WORKER_COUNT; i += 1) {
|
|
|
|
const { worker, onExit } = this.createWorker();
|
|
|
|
this.pool.push({ worker, load: 0 });
|
2021-09-08 20:39:14 +00:00
|
|
|
|
2024-07-22 18:16:33 +00:00
|
|
|
exitPromises.push(onExit);
|
|
|
|
}
|
|
|
|
this.onExit = Promise.all(exitPromises);
|
2021-04-05 22:18:19 +00:00
|
|
|
}
|
|
|
|
|
2021-09-16 21:54:06 +00:00
|
|
|
public async initialize({
|
2023-10-10 23:55:32 +00:00
|
|
|
appVersion,
|
2021-09-16 21:54:06 +00:00
|
|
|
configDir,
|
|
|
|
key,
|
|
|
|
logger,
|
|
|
|
}: InitializeOptions): Promise<void> {
|
2021-04-08 23:27:41 +00:00
|
|
|
if (this.isReady || this.onReady) {
|
|
|
|
throw new Error('Already initialized');
|
|
|
|
}
|
|
|
|
|
2023-07-15 00:52:20 +00:00
|
|
|
this.shouldTimeQueries = Boolean(process.env.TIME_QUERIES);
|
|
|
|
|
2021-09-16 21:54:06 +00:00
|
|
|
this.logger = logger;
|
|
|
|
|
2024-07-22 18:16:33 +00:00
|
|
|
this.onReady = (async () => {
|
|
|
|
const primary = this.pool[0];
|
|
|
|
const rest = this.pool.slice(1);
|
|
|
|
|
|
|
|
await this.send(primary, {
|
|
|
|
type: 'init',
|
|
|
|
options: { appVersion, configDir, key },
|
|
|
|
isPrimary: true,
|
|
|
|
});
|
|
|
|
|
|
|
|
await Promise.all(
|
|
|
|
rest.map(worker =>
|
|
|
|
this.send(worker, {
|
|
|
|
type: 'init',
|
|
|
|
options: { appVersion, configDir, key },
|
|
|
|
isPrimary: false,
|
|
|
|
})
|
|
|
|
)
|
|
|
|
);
|
|
|
|
})();
|
2021-04-08 23:27:41 +00:00
|
|
|
|
|
|
|
await this.onReady;
|
|
|
|
|
|
|
|
this.onReady = undefined;
|
|
|
|
this.isReady = true;
|
2021-04-05 22:18:19 +00:00
|
|
|
}
|
|
|
|
|
2024-07-22 18:16:33 +00:00
|
|
|
public pauseWriteAccess(): void {
|
|
|
|
strictAssert(this.pauseWaiters == null, 'Already paused');
|
|
|
|
|
|
|
|
this.pauseWaiters = [];
|
|
|
|
}
|
|
|
|
|
|
|
|
public resumeWriteAccess(): void {
|
|
|
|
const { pauseWaiters } = this;
|
|
|
|
strictAssert(pauseWaiters != null, 'Not paused');
|
|
|
|
this.pauseWaiters = undefined;
|
|
|
|
|
|
|
|
for (const waiter of pauseWaiters) {
|
|
|
|
waiter();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-08 20:39:14 +00:00
|
|
|
public whenCorrupted(): Promise<Error> {
|
2023-03-02 17:59:18 +00:00
|
|
|
const { promise, resolve } = explodePromise<Error>();
|
|
|
|
this.errorResolvers.push({ kind: SqliteErrorKind.Corrupted, resolve });
|
|
|
|
return promise;
|
|
|
|
}
|
|
|
|
|
|
|
|
public whenReadonly(): Promise<Error> {
|
|
|
|
const { promise, resolve } = explodePromise<Error>();
|
|
|
|
this.errorResolvers.push({ kind: SqliteErrorKind.Readonly, resolve });
|
|
|
|
return promise;
|
2021-09-08 20:39:14 +00:00
|
|
|
}
|
|
|
|
|
2021-04-05 22:18:19 +00:00
|
|
|
public async close(): Promise<void> {
|
2021-04-08 23:27:41 +00:00
|
|
|
if (!this.isReady) {
|
|
|
|
throw new Error('Not initialized');
|
|
|
|
}
|
|
|
|
|
2024-07-22 18:16:33 +00:00
|
|
|
await this.terminate({ type: 'close' });
|
2021-04-05 22:18:19 +00:00
|
|
|
await this.onExit;
|
|
|
|
}
|
|
|
|
|
2021-07-10 00:43:36 +00:00
|
|
|
public async removeDB(): Promise<void> {
|
2024-07-22 18:16:33 +00:00
|
|
|
await this.terminate({ type: 'removeDB' });
|
2021-07-10 00:43:36 +00:00
|
|
|
}
|
|
|
|
|
2024-07-22 18:16:33 +00:00
|
|
|
public async sqlRead<Method extends keyof ServerReadableDirectInterface>(
|
2022-11-17 00:29:15 +00:00
|
|
|
method: Method,
|
2024-07-22 18:16:33 +00:00
|
|
|
...args: Parameters<ServerReadableDirectInterface[Method]>
|
|
|
|
): Promise<ReturnType<ServerReadableDirectInterface[Method]>> {
|
2022-11-14 19:35:37 +00:00
|
|
|
type SqlCallResult = Readonly<{
|
2024-07-22 18:16:33 +00:00
|
|
|
result: ReturnType<ServerReadableDirectInterface[Method]>;
|
2022-11-14 19:35:37 +00:00
|
|
|
duration: number;
|
|
|
|
}>;
|
|
|
|
|
2024-07-22 18:16:33 +00:00
|
|
|
// pageMessages runs over several queries and needs to have access to
|
|
|
|
// the same temporary table.
|
|
|
|
const isPaging = method === 'pageMessages';
|
|
|
|
|
|
|
|
const entry = isPaging ? this.pool.at(-1) : this.getWorker();
|
|
|
|
strictAssert(entry != null, 'Must have a pool entry');
|
|
|
|
|
|
|
|
const { result, duration } = await this.send<SqlCallResult>(entry, {
|
|
|
|
type: 'sqlCall:read',
|
2021-04-26 22:01:22 +00:00
|
|
|
method,
|
|
|
|
args,
|
|
|
|
});
|
|
|
|
|
2024-07-22 18:16:33 +00:00
|
|
|
this.traceDuration(method, duration);
|
|
|
|
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
public async sqlWrite<Method extends keyof ServerWritableDirectInterface>(
|
|
|
|
method: Method,
|
|
|
|
...args: Parameters<ServerWritableDirectInterface[Method]>
|
|
|
|
): Promise<ReturnType<ServerWritableDirectInterface[Method]>> {
|
|
|
|
type Result = ReturnType<ServerWritableDirectInterface[Method]>;
|
|
|
|
type SqlCallResult = Readonly<{
|
|
|
|
result: Result;
|
|
|
|
duration: number;
|
|
|
|
}>;
|
|
|
|
|
|
|
|
while (this.pauseWaiters != null) {
|
|
|
|
const { promise, resolve } = explodePromise<void>();
|
|
|
|
this.pauseWaiters.push(resolve);
|
|
|
|
// eslint-disable-next-line no-await-in-loop
|
|
|
|
await promise;
|
2023-07-15 00:52:20 +00:00
|
|
|
}
|
2024-07-22 18:16:33 +00:00
|
|
|
|
|
|
|
// Special case since we need to broadcast this to every pool entry.
|
|
|
|
if (method === 'removeDB') {
|
|
|
|
return (await this.removeDB()) as Result;
|
2021-04-26 22:01:22 +00:00
|
|
|
}
|
|
|
|
|
2024-07-22 18:16:33 +00:00
|
|
|
const primary = this.pool[0];
|
|
|
|
|
|
|
|
const { result, duration } = await this.send<SqlCallResult>(primary, {
|
|
|
|
type: 'sqlCall:write',
|
|
|
|
method,
|
|
|
|
args,
|
|
|
|
});
|
|
|
|
|
|
|
|
this.traceDuration(method, duration);
|
|
|
|
|
2021-04-26 22:01:22 +00:00
|
|
|
return result;
|
2021-04-05 22:18:19 +00:00
|
|
|
}
|
|
|
|
|
2024-07-22 18:16:33 +00:00
|
|
|
private async send<Response>(
|
|
|
|
entry: PoolEntry,
|
|
|
|
request: WorkerRequest
|
|
|
|
): Promise<Response> {
|
|
|
|
if (request.type === 'sqlCall:read' || request.type === 'sqlCall:write') {
|
|
|
|
if (this.onReady) {
|
|
|
|
await this.onReady;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!this.isReady) {
|
|
|
|
throw new Error('Not initialized');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-04-05 22:18:19 +00:00
|
|
|
const { seq } = this;
|
2024-07-22 18:16:33 +00:00
|
|
|
// eslint-disable-next-line no-bitwise
|
|
|
|
this.seq = (this.seq + 1) >>> 0;
|
2021-04-05 22:18:19 +00:00
|
|
|
|
2023-03-02 17:59:18 +00:00
|
|
|
const { promise: result, resolve, reject } = explodePromise<Response>();
|
|
|
|
this.onResponse.set(seq, { resolve, reject });
|
2021-04-05 22:18:19 +00:00
|
|
|
|
|
|
|
const wrappedRequest: WrappedWorkerRequest = {
|
|
|
|
seq,
|
|
|
|
request,
|
|
|
|
};
|
2024-07-22 18:16:33 +00:00
|
|
|
entry.worker.postMessage(wrappedRequest);
|
|
|
|
|
|
|
|
try {
|
|
|
|
// eslint-disable-next-line no-param-reassign
|
|
|
|
entry.load += 1;
|
|
|
|
return await result;
|
|
|
|
} finally {
|
|
|
|
// eslint-disable-next-line no-param-reassign
|
|
|
|
entry.load -= 1;
|
|
|
|
}
|
|
|
|
}
|
2021-04-05 22:18:19 +00:00
|
|
|
|
2024-07-22 18:16:33 +00:00
|
|
|
private async terminate(request: WorkerRequest): Promise<void> {
|
|
|
|
const primary = this.pool[0];
|
|
|
|
const rest = this.pool.slice(1);
|
|
|
|
|
|
|
|
// Terminate non-primary workers first
|
|
|
|
await Promise.all(rest.map(worker => this.send(worker, request)));
|
|
|
|
|
|
|
|
// Primary last
|
|
|
|
await this.send(primary, request);
|
2021-04-05 22:18:19 +00:00
|
|
|
}
|
2023-03-02 17:59:18 +00:00
|
|
|
|
2023-10-10 23:19:11 +00:00
|
|
|
private onError(errorKind: SqliteErrorKind, error: Error): void {
|
2023-03-02 17:59:18 +00:00
|
|
|
if (errorKind === SqliteErrorKind.Unknown) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const resolvers = new Array<(error: Error) => void>();
|
|
|
|
this.errorResolvers = this.errorResolvers.filter(entry => {
|
|
|
|
if (entry.kind === errorKind) {
|
|
|
|
resolvers.push(entry.resolve);
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
});
|
|
|
|
|
|
|
|
for (const resolve of resolvers) {
|
|
|
|
resolve(error);
|
|
|
|
}
|
|
|
|
}
|
2024-07-22 18:16:33 +00:00
|
|
|
|
|
|
|
private traceDuration(method: string, duration: number): void {
|
|
|
|
if (this.shouldTimeQueries && !app.isPackaged) {
|
|
|
|
const twoDecimals = Math.round(100 * duration) / 100;
|
|
|
|
this.logger?.info(`MainSQL query: ${method}, duration=${twoDecimals}ms`);
|
|
|
|
}
|
|
|
|
if (duration > MIN_TRACE_DURATION) {
|
|
|
|
strictAssert(this.logger !== undefined, 'Logger not initialized');
|
|
|
|
this.logger.info(
|
|
|
|
`MainSQL: slow query ${method} duration=${Math.round(duration)}ms`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private createWorker(): CreateWorkerResultType {
|
|
|
|
const scriptPath = join(app.getAppPath(), 'ts', 'sql', 'mainWorker.js');
|
|
|
|
|
|
|
|
const worker = new Worker(scriptPath);
|
|
|
|
|
|
|
|
worker.on('message', (wrappedResponse: WrappedWorkerResponse) => {
|
|
|
|
if (wrappedResponse.type === 'log') {
|
|
|
|
const { level, args } = wrappedResponse;
|
|
|
|
strictAssert(this.logger !== undefined, 'Logger not initialized');
|
|
|
|
this.logger[level](`MainSQL: ${format(...args)}`);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const { seq, error, errorKind, response } = wrappedResponse;
|
|
|
|
|
|
|
|
const pair = this.onResponse.get(seq);
|
|
|
|
this.onResponse.delete(seq);
|
|
|
|
if (!pair) {
|
|
|
|
throw new Error(`Unexpected worker response with seq: ${seq}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (error) {
|
|
|
|
const errorObj = new Error(error);
|
|
|
|
this.onError(errorKind ?? SqliteErrorKind.Unknown, errorObj);
|
|
|
|
|
|
|
|
pair.reject(errorObj);
|
|
|
|
} else {
|
|
|
|
pair.resolve(response);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
const { promise: onExit, resolve: resolveOnExit } = explodePromise<void>();
|
|
|
|
worker.once('exit', resolveOnExit);
|
|
|
|
|
|
|
|
return { worker, onExit };
|
|
|
|
}
|
|
|
|
|
|
|
|
// Find first pool entry with minimal load
|
|
|
|
private getWorker(): PoolEntry {
|
|
|
|
let min = this.pool[0];
|
|
|
|
for (const entry of this.pool) {
|
|
|
|
if (min && min.load < entry.load) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
min = entry;
|
|
|
|
}
|
|
|
|
return min;
|
|
|
|
}
|
2021-04-05 22:18:19 +00:00
|
|
|
}
|