Skip to content

Build your personal knowledge base with Trilium Notes

chore(core): integrate sync service and route

Elian Doranea0e3fd24862
diff --git a/apps/client-standalone/src/lightweight/browser_router.ts b/apps/client-standalone/src/lightweight/browser_router.ts
index b80aa09890..9a601e6200 100644
--- a/apps/client-standalone/src/lightweight/browser_router.ts
+++ b/apps/client-standalone/src/lightweight/browser_router.ts
@@ -11,6 +11,7 @@ export interface BrowserRequest {
path: string;
params: Record<string, string>;
query: Record<string, string | undefined>;
+ headers?: Record<string, string>;
body?: unknown;
}
diff --git a/apps/client-standalone/src/lightweight/browser_routes.ts b/apps/client-standalone/src/lightweight/browser_routes.ts
index 79ce8d07f7..35d3a5b5bf 100644
--- a/apps/client-standalone/src/lightweight/browser_routes.ts
+++ b/apps/client-standalone/src/lightweight/browser_routes.ts
@@ -4,13 +4,34 @@
*/
import { BootstrapDefinition } from '@triliumnext/commons';
-import { getContext, getSharedBootstrapItems, getSql, routes } from '@triliumnext/core';
+import { entity_changes, getContext, getSharedBootstrapItems, getSql, routes } from '@triliumnext/core';
import packageJson from '../../package.json' with { type: 'json' };
-import { type BrowserRequest,BrowserRouter } from './browser_router';
+import { type BrowserRequest, BrowserRouter } from './browser_router';
+
+/** Minimal response object used by apiResultHandler to capture the processed result. */
+interface ResultHandlerResponse {
+ headers: Record<string, string>;
+ result: unknown;
+ setHeader(name: string, value: string): void;
+}
type HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete';
+/**
+ * Creates an Express-like request object from a BrowserRequest.
+ */
+function toExpressLikeReq(req: BrowserRequest) {
+ return {
+ params: req.params,
+ query: req.query,
+ body: req.body,
+ headers: req.headers ?? {},
+ method: req.method,
+ get originalUrl() { return req.url; }
+ };
+}
+
/**
* Wraps a core route handler to work with the BrowserRouter.
* Core handlers expect an Express-like request object with params, query, and body.
@@ -20,12 +41,7 @@ type HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete';
function wrapHandler(handler: (req: any) => unknown, transactional: boolean) {
return (req: BrowserRequest) => {
return getContext().init(() => {
- // Create an Express-like request object
- const expressLikeReq = {
- params: req.params,
- query: req.query,
- body: req.body
- };
+ const expressLikeReq = toExpressLikeReq(req);
if (transactional) {
return getSql().transactional(() => handler(expressLikeReq));
}
@@ -44,6 +60,74 @@ function createApiRoute(router: BrowserRouter, transactional: boolean) {
};
}
+/**
+ * Low-level route registration matching the server's `route()` signature:
+ * route(method, path, middleware[], handler, resultHandler)
+ *
+ * In standalone mode:
+ * - Middleware (e.g. checkApiAuth) is skipped — there's no authentication.
+ * - The resultHandler is applied to post-process the result (entity conversion, status codes).
+ */
+function createRoute(router: BrowserRouter) {
+ return (method: HttpMethod, path: string, _middleware: any[], handler: (req: any) => unknown, resultHandler?: ((req: any, res: any, result: unknown) => unknown) | null) => {
+ router.register(method, path, (req: BrowserRequest) => {
+ return getContext().init(() => {
+ const expressLikeReq = toExpressLikeReq(req);
+ const result = getSql().transactional(() => handler(expressLikeReq));
+
+ if (resultHandler) {
+ // Create a minimal response object that captures what apiResultHandler sets.
+ const res = createResultHandlerResponse();
+ resultHandler(expressLikeReq, res, result);
+ return res.result;
+ }
+
+ return result;
+ });
+ });
+ };
+}
+
+/**
+ * Standalone apiResultHandler matching the server's behavior:
+ * - Converts Becca entities to POJOs
+ * - Handles [statusCode, response] tuple format
+ * - Sets trilium-max-entity-change-id (captured in response headers)
+ */
+function apiResultHandler(_req: any, res: ResultHandlerResponse, result: unknown) {
+ res.headers["trilium-max-entity-change-id"] = String(entity_changes.getMaxEntityChangeId());
+ result = routes.convertEntitiesToPojo(result);
+
+ if (Array.isArray(result) && result.length > 0 && Number.isInteger(result[0])) {
+ const [_statusCode, response] = result;
+ res.result = response;
+ } else if (result === undefined) {
+ res.result = "";
+ } else {
+ res.result = result;
+ }
+}
+
+/**
+ * No-op auth middleware for standalone — there's no authentication.
+ */
+function checkApiAuth() {
+ // No authentication in standalone mode.
+}
+
+/**
+ * Creates a minimal response-like object for the apiResultHandler.
+ */
+function createResultHandlerResponse(): ResultHandlerResponse {
+ return {
+ headers: {},
+ result: undefined,
+ setHeader(name: string, value: string) {
+ this.headers[name] = value;
+ }
+ };
+}
+
/**
* Register all API routes on the browser router using the shared builder.
*
@@ -52,8 +136,11 @@ function createApiRoute(router: BrowserRouter, transactional: boolean) {
export function registerRoutes(router: BrowserRouter): void {
const apiRoute = createApiRoute(router, true);
routes.buildSharedApiRoutes({
+ route: createRoute(router),
apiRoute,
- asyncApiRoute: createApiRoute(router, false)
+ asyncApiRoute: createApiRoute(router, false),
+ apiResultHandler,
+ checkApiAuth
});
apiRoute('get', '/bootstrap', bootstrapRoute);
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index f0a8e7f109..f6bd54b262 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -38,7 +38,6 @@ import scriptRoute from "./api/script.js";
import senderRoute from "./api/sender.js";
import setupApiRoute from "./api/setup.js";
import similarNotesRoute from "./api/similar_notes.js";
-import syncApiRoute from "./api/sync.js";
import systemInfoRoute from "./api/system_info.js";
import totp from './api/totp.js';
// API routes
@@ -86,8 +85,11 @@ function register(app: express.Application) {
apiRoute(GET, '/api/totp_recovery/used', recoveryCodes.getUsedRecoveryCodes);
routes.buildSharedApiRoutes({
+ route,
apiRoute,
- asyncApiRoute
+ asyncApiRoute,
+ apiResultHandler,
+ checkApiAuth: auth.checkApiAuth
});
route(PUT, "/api/notes/:noteId/file", [auth.checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], filesRoute.updateFile, apiResultHandler);
@@ -145,18 +147,6 @@ function register(app: express.Application) {
apiRoute(PST, "/api/password/change", passwordApiRoute.changePassword);
apiRoute(PST, "/api/password/reset", passwordApiRoute.resetPassword);
- asyncApiRoute(PST, "/api/sync/test", syncApiRoute.testSync);
- asyncApiRoute(PST, "/api/sync/now", syncApiRoute.syncNow);
- apiRoute(PST, "/api/sync/fill-entity-changes", syncApiRoute.fillEntityChanges);
- apiRoute(PST, "/api/sync/force-full-sync", syncApiRoute.forceFullSync);
- route(GET, "/api/sync/check", [auth.checkApiAuth], syncApiRoute.checkSync, apiResultHandler);
- route(GET, "/api/sync/changed", [auth.checkApiAuth], syncApiRoute.getChanged, apiResultHandler);
- route(PUT, "/api/sync/update", [auth.checkApiAuth], syncApiRoute.update, apiResultHandler);
- route(PST, "/api/sync/finished", [auth.checkApiAuth], syncApiRoute.syncFinished, apiResultHandler);
- route(PST, "/api/sync/check-entity-changes", [auth.checkApiAuth], syncApiRoute.checkEntityChanges, apiResultHandler);
- route(PST, "/api/sync/queue-sector/:entityName/:sector", [auth.checkApiAuth], syncApiRoute.queueSector, apiResultHandler);
- route(GET, "/api/sync/stats", [], syncApiRoute.getStats, apiResultHandler);
-
apiRoute(GET, "/api/metrics", metricsRoute.getMetrics);
apiRoute(GET, "/api/system-checks", systemInfoRoute.systemChecks);
diff --git a/apps/server/src/services/api-interface.ts b/apps/server/src/services/api-interface.ts
deleted file mode 100644
index 8d837c3b50..0000000000
--- a/apps/server/src/services/api-interface.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import type { OptionRow } from "@triliumnext/commons";
-
-/**
- * Response for /api/setup/status.
- */
-export interface SetupStatusResponse {
- syncVersion: number;
- schemaExists: boolean;
-}
-
-/**
- * Response for /api/setup/sync-seed.
- */
-export interface SetupSyncSeedResponse {
- syncVersion: number;
- options: OptionRow[];
-}
diff --git a/apps/server/src/services/sync.ts b/apps/server/src/services/sync.ts
index 3a0cb1a00c..52779dd03c 100644
--- a/apps/server/src/services/sync.ts
+++ b/apps/server/src/services/sync.ts
@@ -1,462 +1,2 @@
-import type { EntityChange, EntityChangeRecord, EntityRow } from "@triliumnext/commons";
-import { becca_loader, binary_utils, entity_constructor, getInstanceId, request, type CookieJar, type ExecOpts } from "@triliumnext/core";
-
-import becca from "../becca/becca.js";
-import appInfo from "./app_info.js";
-import cls from "./cls.js";
-import consistency_checks from "./consistency_checks.js";
-import contentHashService from "./content_hash.js";
-import dateUtils from "./date_utils.js";
-import entityChangesService from "./entity_changes.js";
-import log from "./log.js";
-import optionService from "./options.js";
-import setupService from "./setup.js";
-import sql from "./sql.js";
-import syncMutexService from "./sync_mutex.js";
-import syncOptions from "./sync_options.js";
-import syncUpdateService from "./sync_update.js";
-import { hmac, randomString, timeLimit } from "./utils.js";
-import ws from "./ws.js";
-
-let proxyToggle = true;
-
-let outstandingPullCount = 0;
-
-interface CheckResponse {
- maxEntityChangeId: number;
- entityHashes: Record<string, Record<string, string>>;
-}
-
-interface SyncResponse {
- instanceId: string;
- maxEntityChangeId: number;
-}
-
-interface ChangesResponse {
- entityChanges: EntityChangeRecord[];
- lastEntityChangeId: number;
- outstandingPullCount: number;
-}
-
-interface SyncContext {
- cookieJar: CookieJar;
- instanceId?: string;
-}
-
-async function sync() {
- try {
- return await syncMutexService.doExclusively(async () => {
- if (!syncOptions.isSyncSetup()) {
- return { success: false, errorCode: "NOT_CONFIGURED", message: "Sync not configured" };
- }
-
- let continueSync = false;
-
- do {
- const syncContext = await login();
-
- await pushChanges(syncContext);
-
- await pullChanges(syncContext);
-
- await pushChanges(syncContext);
-
- await syncFinished(syncContext);
-
- continueSync = await checkContentHash(syncContext);
- } while (continueSync);
-
- ws.syncFinished();
-
- return {
- success: true
- };
- });
- } catch (e: any) {
- // we're dynamically switching whether we're using proxy or not based on whether we encountered error with the current method
- proxyToggle = !proxyToggle;
-
- if (
- e.message?.includes("ECONNREFUSED") ||
- e.message?.includes("ERR_") || // node network errors
- e.message?.includes("Bad Gateway")
- ) {
- ws.syncFailed();
-
- log.info("No connection to sync server.");
-
- return {
- success: false,
- message: "No connection to sync server."
- };
- }
- log.info(`Sync failed: '${e.message}', stack: ${e.stack}`);
-
- ws.syncFailed();
-
- return {
- success: false,
- message: e.message
- };
-
- }
-}
-
-async function login() {
- if (!(await setupService.hasSyncServerSchemaAndSeed())) {
- await setupService.sendSeedToSyncServer();
- }
-
- return await doLogin();
-}
-
-async function doLogin(): Promise<SyncContext> {
- const timestamp = dateUtils.utcNowDateTime();
-
- const documentSecret = optionService.getOption("documentSecret");
- const hash = hmac(documentSecret, timestamp);
-
- const syncContext: SyncContext = { cookieJar: {} };
- const resp = await syncRequest<SyncResponse>(syncContext, "POST", "/api/login/sync", {
- timestamp,
- syncVersion: appInfo.syncVersion,
- hash
- });
-
- if (!resp) {
- throw new Error("Got no response.");
- }
-
- if (resp.instanceId === getInstanceId()) {
- throw new Error(
- `Sync server has instance ID '${resp.instanceId}' which is also local. This usually happens when the sync client is (mis)configured to sync with itself (URL points back to client) instead of the correct sync server.`
- );
- }
-
- syncContext.instanceId = resp.instanceId;
-
- const lastSyncedPull = getLastSyncedPull();
-
- // this is important in a scenario where we set up the sync by manually copying the document
- // lastSyncedPull then could be pretty off for the newly cloned client
- if (lastSyncedPull > resp.maxEntityChangeId) {
- log.info(`Lowering last synced pull from ${lastSyncedPull} to ${resp.maxEntityChangeId}`);
-
- setLastSyncedPull(resp.maxEntityChangeId);
- }
-
- return syncContext;
-}
-
-async function pullChanges(syncContext: SyncContext) {
- while (true) {
- const lastSyncedPull = getLastSyncedPull();
- const logMarkerId = randomString(10); // to easily pair sync events between client and server logs
- const changesUri = `/api/sync/changed?instanceId=${getInstanceId()}&lastEntityChangeId=${lastSyncedPull}&logMarkerId=${logMarkerId}`;
-
- const startDate = Date.now();
-
- const resp = await syncRequest<ChangesResponse>(syncContext, "GET", changesUri);
- if (!resp) {
- throw new Error("Request failed.");
- }
- const { entityChanges, lastEntityChangeId } = resp;
-
- outstandingPullCount = resp.outstandingPullCount;
-
- const pulledDate = Date.now();
-
- sql.transactional(() => {
- if (syncContext.instanceId) {
- syncUpdateService.updateEntities(entityChanges, syncContext.instanceId);
- }
-
- if (lastSyncedPull !== lastEntityChangeId) {
- setLastSyncedPull(lastEntityChangeId);
- }
- });
-
- if (entityChanges.length === 0) {
- break;
- } else {
- try {
- // https://github.com/zadam/trilium/issues/4310
- const sizeInKb = Math.round(JSON.stringify(resp).length / 1024);
-
- log.info(
- `Sync ${logMarkerId}: Pulled ${entityChanges.length} changes in ${sizeInKb} KB, starting at entityChangeId=${lastSyncedPull} in ${pulledDate - startDate}ms and applied them in ${Date.now() - pulledDate}ms, ${outstandingPullCount} outstanding pulls`
- );
- } catch (e: any) {
- log.error(`Error occurred ${e.message} ${e.stack}`);
- }
- }
- }
-
- log.info("Finished pull");
-}
-
-async function pushChanges(syncContext: SyncContext) {
- let lastSyncedPush: number | null | undefined = getLastSyncedPush();
-
- while (true) {
- const entityChanges = sql.getRows<EntityChange>("SELECT * FROM entity_changes WHERE isSynced = 1 AND id > ? LIMIT 1000", [lastSyncedPush]);
-
- if (entityChanges.length === 0) {
- log.info("Nothing to push");
-
- break;
- }
-
- const filteredEntityChanges = entityChanges.filter((entityChange) => {
- if (entityChange.instanceId === syncContext.instanceId) {
- // this may set lastSyncedPush beyond what's actually sent (because of size limit)
- // so this is applied to the database only if there's no actual update
- lastSyncedPush = entityChange.id;
-
- return false;
- }
- return true;
-
- });
-
- if (filteredEntityChanges.length === 0 && lastSyncedPush) {
- // there still might be more sync changes (because of batch limit), just all the current batch
- // has been filtered out
- setLastSyncedPush(lastSyncedPush);
-
- continue;
- }
-
- const entityChangesRecords = getEntityChangeRecords(filteredEntityChanges);
- const startDate = new Date();
-
- const logMarkerId = randomString(10); // to easily pair sync events between client and server logs
-
- await syncRequest(syncContext, "PUT", `/api/sync/update?logMarkerId=${logMarkerId}`, {
- entities: entityChangesRecords,
- instanceId: getInstanceId()
- });
-
- ws.syncPushInProgress();
-
- log.info(`Sync ${logMarkerId}: Pushing ${entityChangesRecords.length} sync changes in ${Date.now() - startDate.getTime()}ms`);
-
- lastSyncedPush = entityChangesRecords[entityChangesRecords.length - 1].entityChange.id;
-
- if (lastSyncedPush) {
- setLastSyncedPush(lastSyncedPush);
- }
- }
-}
-
-async function syncFinished(syncContext: SyncContext) {
- await syncRequest(syncContext, "POST", "/api/sync/finished");
-}
-
-async function checkContentHash(syncContext: SyncContext) {
- const resp = await syncRequest<CheckResponse>(syncContext, "GET", "/api/sync/check");
- if (!resp) {
- throw new Error("Got no response.");
- }
-
- const lastSyncedPullId = getLastSyncedPull();
-
- if (lastSyncedPullId < resp.maxEntityChangeId) {
- log.info(`There are some outstanding pulls (${lastSyncedPullId} vs. ${resp.maxEntityChangeId}), skipping content check.`);
-
- return true;
- }
-
- const notPushedSyncs = sql.getValue("SELECT EXISTS(SELECT 1 FROM entity_changes WHERE isSynced = 1 AND id > ?)", [getLastSyncedPush()]);
-
- if (notPushedSyncs) {
- log.info(`There's ${notPushedSyncs} outstanding pushes, skipping content check.`);
-
- return true;
- }
-
- const failedChecks = contentHashService.checkContentHashes(resp.entityHashes);
-
- if (failedChecks.length > 0) {
- // before re-queuing sectors, make sure the entity changes are correct
- consistency_checks.runEntityChangesChecks();
-
- await syncRequest(syncContext, "POST", `/api/sync/check-entity-changes`);
- }
-
- for (const { entityName, sector } of failedChecks) {
- entityChangesService.addEntityChangesForSector(entityName, sector);
-
- await syncRequest(syncContext, "POST", `/api/sync/queue-sector/${entityName}/${sector}`);
- }
-
- return failedChecks.length > 0;
-}
-
-const PAGE_SIZE = 1000000;
-
-interface SyncContext {
- cookieJar: CookieJar;
-}
-
-async function syncRequest<T extends {}>(syncContext: SyncContext, method: string, requestPath: string, _body?: {}) {
- const body = _body ? JSON.stringify(_body) : "";
-
- const timeout = syncOptions.getSyncTimeout();
-
- let response;
-
- const requestId = randomString(10);
- const pageCount = Math.max(1, Math.ceil(body.length / PAGE_SIZE));
-
- for (let pageIndex = 0; pageIndex < pageCount; pageIndex++) {
- const opts: ExecOpts = {
- method,
- url: syncOptions.getSyncServerHost() + requestPath,
- cookieJar: syncContext.cookieJar,
- timeout,
- paging: {
- pageIndex,
- pageCount,
- requestId
- },
- body: body.substr(pageIndex * PAGE_SIZE, Math.min(PAGE_SIZE, body.length - pageIndex * PAGE_SIZE)),
- proxy: proxyToggle ? syncOptions.getSyncProxy() : null
- };
-
- response = (await timeLimit(request.exec(opts), timeout)) as T;
- }
-
- return response;
-}
-
-function getEntityChangeRow(entityChange: EntityChange) {
- const { entityName, entityId } = entityChange;
-
- if (entityName === "note_reordering") {
- return sql.getMap("SELECT branchId, notePosition FROM branches WHERE parentNoteId = ? AND isDeleted = 0", [entityId]);
- }
- const primaryKey = entity_constructor.getEntityFromEntityName(entityName).primaryKeyName;
-
- if (!primaryKey) {
- throw new Error(`Unknown entity for entity change ${JSON.stringify(entityChange)}`);
- }
-
- const entityRow = sql.getRow<EntityRow>(/*sql*/`SELECT * FROM ${entityName} WHERE ${primaryKey} = ?`, [entityId]);
-
- if (!entityRow) {
- log.error(`Cannot find entity for entity change ${JSON.stringify(entityChange)}`);
- return null;
- }
-
- if (entityName === "blobs" && entityRow.content !== null) {
- if (typeof entityRow.content === "string") {
- entityRow.content = Buffer.from(entityRow.content, "utf-8");
- }
-
- if (entityRow.content) {
- entityRow.content = binary_utils.encodeBase64(entityRow.content);
- }
- }
-
-
- return entityRow;
-
-}
-
-function getEntityChangeRecords(entityChanges: EntityChange[]) {
- const records: EntityChangeRecord[] = [];
- let length = 0;
-
- for (const entityChange of entityChanges) {
- if (entityChange.isErased) {
- records.push({ entityChange });
-
- continue;
- }
-
- const entity = getEntityChangeRow(entityChange);
- if (!entity) {
- continue;
- }
-
- const record: EntityChangeRecord = { entityChange, entity };
-
- records.push(record);
-
- length += JSON.stringify(record).length;
-
- if (length > 1_000_000) {
- // each sync request/response should have at most ~1 MB.
- break;
- }
- }
-
- return records;
-}
-
-function getLastSyncedPull() {
- return parseInt(optionService.getOption("lastSyncedPull"));
-}
-
-function setLastSyncedPull(entityChangeId: number) {
- const lastSyncedPullOption = becca.getOption("lastSyncedPull");
-
- if (lastSyncedPullOption) {
- // might be null in initial sync when becca is not loaded
- lastSyncedPullOption.value = `${entityChangeId}`;
- }
-
- // this way we avoid updating entity_changes which otherwise means that we've never pushed all entity_changes
- sql.execute("UPDATE options SET value = ? WHERE name = ?", [entityChangeId, "lastSyncedPull"]);
-}
-
-function getLastSyncedPush() {
- const lastSyncedPush = parseInt(optionService.getOption("lastSyncedPush"));
-
- ws.setLastSyncedPush(lastSyncedPush);
-
- return lastSyncedPush;
-}
-
-function setLastSyncedPush(entityChangeId: number) {
- ws.setLastSyncedPush(entityChangeId);
-
- const lastSyncedPushOption = becca.getOption("lastSyncedPush");
-
- if (lastSyncedPushOption) {
- // might be null in initial sync when becca is not loaded
- lastSyncedPushOption.value = `${entityChangeId}`;
- }
-
- // this way we avoid updating entity_changes which otherwise means that we've never pushed all entity_changes
- sql.execute("UPDATE options SET value = ? WHERE name = ?", [entityChangeId, "lastSyncedPush"]);
-}
-
-function getMaxEntityChangeId() {
- return sql.getValue("SELECT COALESCE(MAX(id), 0) FROM entity_changes");
-}
-
-function getOutstandingPullCount() {
- return outstandingPullCount;
-}
-
-export function startSyncTimer() {
- becca_loader.beccaLoaded.then(() => {
- setInterval(cls.wrap(sync), 60000);
-
- // kickoff initial sync immediately, but should happen after initial consistency checks
- setTimeout(cls.wrap(sync), 5000);
-
- // called just so ws.setLastSyncedPush() is called
- getLastSyncedPush();
- });
-}
-
-export default {
- sync,
- login,
- getEntityChangeRecords,
- getOutstandingPullCount,
- getMaxEntityChangeId
-};
+import { sync } from "@triliumnext/core";
+export default sync;
diff --git a/apps/server/src/services/sync_options.ts b/apps/server/src/services/sync_options.ts
index 657c1b2149..20181899e8 100644
--- a/apps/server/src/services/sync_options.ts
+++ b/apps/server/src/services/sync_options.ts
@@ -1,34 +1,2 @@
-"use strict";
-
-import optionService from "./options.js";
-import config from "./config.js";
-import { normalizeUrl } from "./utils.js";
-
-/*
- * Primary configuration for sync is in the options (document), but we allow to override
- * these settings in config file. The reason for that is to avoid a mistake of loading a live/production
- * document with live sync settings in a dev/debug environment. Changes would then successfully propagate
- * to live sync server.
- */
-
-function get(name: keyof typeof config.Sync) {
- return (config["Sync"] && config["Sync"][name]) || optionService.getOption(name);
-}
-
-export default {
- // env variable is the easiest way to guarantee we won't overwrite prod data during development
- // after copying prod document/data directory
- getSyncServerHost: () => {
- const host = get("syncServerHost");
- return host ? normalizeUrl(host) : host;
- },
- isSyncSetup: () => {
- const syncServerHost = get("syncServerHost");
-
- // special value "disabled" is here to support a use case where the document is configured with sync server,
- // and we need to override it with config from config.ini
- return !!syncServerHost && syncServerHost !== "disabled";
- },
- getSyncTimeout: () => parseInt(get("syncServerTimeout")) || 120000,
- getSyncProxy: () => get("syncProxy")
-};
+import { sync_options } from "@triliumnext/core";
+export default sync_options;
diff --git a/apps/server/src/services/sync_update.ts b/apps/server/src/services/sync_update.ts
index 0e28f8b014..0259727254 100644
--- a/apps/server/src/services/sync_update.ts
+++ b/apps/server/src/services/sync_update.ts
@@ -1,170 +1,2 @@
-import type { EntityChange, EntityChangeRecord, EntityRow } from "@triliumnext/commons";
-import { entity_constructor, events as eventService } from "@triliumnext/core";
-
-import entityChangesService from "./entity_changes.js";
-import log from "./log.js";
-import sql from "./sql.js";
-import ws from "./ws.js";
-
-interface UpdateContext {
- alreadyErased: number;
- erased: number;
- updated: Record<string, string[]>;
-}
-
-function updateEntities(entityChanges: EntityChangeRecord[], instanceId: string) {
- if (entityChanges.length === 0) {
- return;
- }
-
- let atLeastOnePullApplied = false;
- const updateContext = {
- updated: {},
- alreadyUpdated: 0,
- erased: 0,
- alreadyErased: 0
- };
-
- for (const { entityChange, entity } of entityChanges) {
- const changeAppliedAlready = entityChange.changeId && !!sql.getValue("SELECT 1 FROM entity_changes WHERE changeId = ?", [entityChange.changeId]);
-
- if (changeAppliedAlready) {
- updateContext.alreadyUpdated++;
-
- continue;
- }
-
- if (!atLeastOnePullApplied) {
- // avoid spamming and send only for first
- ws.syncPullInProgress();
-
- atLeastOnePullApplied = true;
- }
-
- updateEntity(entityChange, entity, instanceId, updateContext);
- }
-
- logUpdateContext(updateContext);
-}
-
-function updateEntity(remoteEC: EntityChange, remoteEntityRow: EntityRow | undefined, instanceId: string, updateContext: UpdateContext) {
- if (!remoteEntityRow && remoteEC.entityName === "options") {
- return; // can be undefined for options with isSynced=false
- }
-
- const updated = remoteEC.entityName === "note_reordering"
- ? updateNoteReordering(remoteEC, remoteEntityRow, instanceId)
- : updateNormalEntity(remoteEC, remoteEntityRow, instanceId, updateContext);
-
- if (updated) {
- if (remoteEntityRow?.isDeleted) {
- eventService.emit(eventService.ENTITY_DELETE_SYNCED, {
- entityName: remoteEC.entityName,
- entityId: remoteEC.entityId
- });
- } else if (!remoteEC.isErased) {
- eventService.emit(eventService.ENTITY_CHANGE_SYNCED, {
- entityName: remoteEC.entityName,
- entityRow: remoteEntityRow
- });
- }
- }
-}
-
-function updateNormalEntity(remoteEC: EntityChange, remoteEntityRow: EntityRow | undefined, instanceId: string, updateContext: UpdateContext) {
- const localEC = sql.getRow<EntityChange | undefined>(/*sql*/`SELECT * FROM entity_changes WHERE entityName = ? AND entityId = ?`, [remoteEC.entityName, remoteEC.entityId]);
- const localECIsOlderOrSameAsRemote = localEC && localEC.utcDateChanged && remoteEC.utcDateChanged && localEC.utcDateChanged <= remoteEC.utcDateChanged;
-
- if (!localEC || localECIsOlderOrSameAsRemote) {
- if (remoteEC.isErased) {
- if (localEC?.isErased) {
- eraseEntity(remoteEC); // make sure it's erased anyway
- updateContext.alreadyErased++;
- } else {
- eraseEntity(remoteEC);
- updateContext.erased++;
- }
- } else {
- if (!remoteEntityRow) {
- throw new Error(`Empty entity row for: ${JSON.stringify(remoteEC)}`);
- }
-
- preProcessContent(remoteEC, remoteEntityRow);
-
- sql.replace(remoteEC.entityName, remoteEntityRow);
-
- updateContext.updated[remoteEC.entityName] = updateContext.updated[remoteEC.entityName] || [];
- updateContext.updated[remoteEC.entityName].push(remoteEC.entityId);
- }
-
- if (!localEC || localECIsOlderOrSameAsRemote || localEC.hash !== remoteEC.hash || localEC.isErased !== remoteEC.isErased) {
- entityChangesService.putEntityChangeWithInstanceId(remoteEC, instanceId);
- }
-
- return true;
- } else if ((localEC.hash !== remoteEC.hash || localEC.isErased !== remoteEC.isErased) && !localECIsOlderOrSameAsRemote) {
- // the change on our side is newer than on the other side, so the other side should update
- entityChangesService.putEntityChangeForOtherInstances(localEC);
-
- return false;
- }
-
- return false;
-}
-
-function preProcessContent(remoteEC: EntityChange, remoteEntityRow: EntityRow) {
- if (remoteEC.entityName === "blobs" && remoteEntityRow.content !== null) {
- // we always use a Buffer object which is different from normal saving - there we use a simple string type for
- // "string notes". The problem is that in general, it's not possible to detect whether a blob content
- // is string note or note (syncs can arrive out of order)
- if (typeof remoteEntityRow.content === "string") {
- remoteEntityRow.content = Buffer.from(remoteEntityRow.content, "base64");
-
- if (remoteEntityRow.content.byteLength === 0) {
- // there seems to be a bug which causes empty buffer to be stored as NULL which is then picked up as inconsistency
- // (possibly not a problem anymore with the newer better-sqlite3)
- remoteEntityRow.content = "";
- }
- }
- }
-}
-
-function updateNoteReordering(remoteEC: EntityChange, remoteEntityRow: EntityRow | undefined, instanceId: string) {
- if (!remoteEntityRow) {
- throw new Error(`Empty note_reordering body for: ${JSON.stringify(remoteEC)}`);
- }
-
- for (const key in remoteEntityRow) {
- sql.execute("UPDATE branches SET notePosition = ? WHERE branchId = ?", [remoteEntityRow[key as keyof EntityRow], key]);
- }
-
- entityChangesService.putEntityChangeWithInstanceId(remoteEC, instanceId);
-
- return true;
-}
-
-
-function eraseEntity(entityChange: EntityChange) {
- const { entityName, entityId } = entityChange;
-
- const entityNames = ["notes", "branches", "attributes", "revisions", "attachments", "blobs"];
-
- if (!entityNames.includes(entityName)) {
- log.error(`Cannot erase ${entityName} '${entityId}'.`);
- return;
- }
-
- const primaryKeyName = entity_constructor.getEntityFromEntityName(entityName).primaryKeyName;
-
- sql.execute(/*sql*/`DELETE FROM ${entityName} WHERE ${primaryKeyName} = ?`, [entityId]);
-}
-
-function logUpdateContext(updateContext: UpdateContext) {
- const message = JSON.stringify(updateContext).replaceAll('"', "").replaceAll(":", ": ").replaceAll(",", ", ");
-
- log.info(message.substr(1, message.length - 2));
-}
-
-export default {
- updateEntities
-};
+import { sync_update } from "@triliumnext/core";
+export default sync_update;
diff --git a/apps/server/src/services/utils.ts b/apps/server/src/services/utils.ts
index 56175e5027..38e41b9f42 100644
--- a/apps/server/src/services/utils.ts
+++ b/apps/server/src/services/utils.ts
@@ -85,10 +85,6 @@ export function constantTimeCompare(a: string | null | undefined, b: string | nu
return crypto.timingSafeEqual(bufA, bufB);
}
-export function sanitizeSqlIdentifier(str: string) {
- return str.replace(/[^A-Za-z0-9_]/g, "");
-}
-
export function toObject<T, K extends string | number | symbol, V>(array: T[], fn: (item: T) => [K, V]): Record<K, V> {
const obj: Record<K, V> = {} as Record<K, V>; // TODO: unsafe?
@@ -172,35 +168,6 @@ export function getNoteTitle(filePath: string, replaceUnderscoresWithSpaces: boo
return replaceUnderscoresWithSpaces ? basename.replace(/_/g, " ").trim() : basename;
}
-export function timeLimit<T>(promise: Promise<T>, limitMs: number, errorMessage?: string): Promise<T> {
- // TriliumNextTODO: since TS avoids this from ever happening – do we need this check?
- if (!promise || !promise.then) {
- // it's not actually a promise
- return promise;
- }
-
- // better stack trace if created outside of promise
- const errorTimeLimit = new Error(errorMessage || `Process exceeded time limit ${limitMs}`);
-
- return new Promise((res, rej) => {
- let resolved = false;
-
- promise
- .then((result) => {
- resolved = true;
-
- res(result);
- })
- .catch((error) => rej(error));
-
- setTimeout(() => {
- if (!resolved) {
- rej(errorTimeLimit);
- }
- }, limitMs);
- });
-}
-
/** @deprecated */
export function removeDiacritic(str: string) {
return coreUtils.removeDiacritic(str);
@@ -337,36 +304,6 @@ export function processStringOrBuffer(data: string | Buffer | null) {
}
}
-/**
- * Normalizes URL by removing trailing slashes and fixing double slashes.
- * Preserves the protocol (http://, https://) but removes trailing slashes from the rest.
- *
- * @param url The URL to normalize
- * @returns The normalized URL without trailing slashes
- */
-export function normalizeUrl(url: string | null | undefined): string | null | undefined {
- if (!url || typeof url !== 'string') {
- return url;
- }
-
- // Trim whitespace
- url = url.trim();
-
- if (!url) {
- return url;
- }
-
- // Fix double slashes (except in protocol) first
- url = url.replace(/([^:]\/)\/+/g, '$1');
-
- // Remove trailing slash, but preserve protocol
- if (url.endsWith('/') && !url.match(/^https?:\/\/$/)) {
- url = url.slice(0, -1);
- }
-
- return url;
-}
-
/**
* Normalizes a path pattern for custom request handlers.
* Ensures both trailing slash and non-trailing slash versions are handled.
@@ -455,6 +392,10 @@ export const randomSecureToken = coreUtils.randomSecureToken;
export const safeExtractMessageAndStackFromError = coreUtils.safeExtractMessageAndStackFromError;
/** @deprecated */
export const isEmptyOrWhitespace = coreUtils.isEmptyOrWhitespace;
+/** @deprecated */
+export const normalizeUrl = coreUtils.normalizeUrl;
+export const timeLimit = coreUtils.timeLimit;
+export const sanitizeSqlIdentifier = coreUtils.sanitizeSqlIdentifier;
export function waitForStreamToFinish(stream: any): Promise<void> {
return new Promise((resolve, reject) => {
@@ -487,7 +428,6 @@ export default {
newEntityId,
normalize,
normalizeCustomHandlerPattern,
- normalizeUrl,
quoteRegex,
randomSecureToken,
randomString,
@@ -495,10 +435,8 @@ export default {
removeFileExtension,
replaceAll,
safeExtractMessageAndStackFromError,
- sanitizeSqlIdentifier,
stripTags,
slugify,
- timeLimit,
toBase64,
toMap,
toObject,
diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.ts
index 926a517e33..c330518d82 100644
--- a/packages/commons/src/lib/server_api.ts
+++ b/packages/commons/src/lib/server_api.ts
@@ -1,5 +1,5 @@
import type { Locale } from "./i18n.js";
-import { AttachmentRow, AttributeRow, BranchRow, NoteRow, NoteType } from "./rows.js";
+import { AttachmentRow, AttributeRow, BranchRow, NoteRow, NoteType, OptionRow } from "./rows.js";
type Response = {
success: true,
@@ -341,3 +341,19 @@ export interface BootstrapDefinition {
iconRegistry: IconRegistry;
TRILIUM_SAFE_MODE: boolean;
}
+
+/**
+ * Response for /api/setup/status.
+ */
+export interface SetupStatusResponse {
+ syncVersion: number;
+ schemaExists: boolean;
+}
+
+/**
+ * Response for /api/setup/sync-seed.
+ */
+export interface SetupSyncSeedResponse {
+ syncVersion: number;
+ options: OptionRow[];
+}
diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.ts
index a299f3888f..64ece2e3c0 100644
--- a/packages/trilium-core/src/index.ts
+++ b/packages/trilium-core/src/index.ts
@@ -76,6 +76,9 @@ export * as sanitize from "./services/sanitizer";
export * as routes from "./routes";
export { default as ws } from "./services/ws";
export { default as request } from "./services/request";
+export { default as sync_options } from "./services/sync_options";
+export { default as sync_update } from "./services/sync_update";
+export { default as sync } from "./services/sync";
export type { RequestProvider, ExecOpts, CookieJar } from "./services/request";
export async function initializeCore({ dbConfig, executionContext, crypto, translations, messaging, request, extraAppInfo }: {
diff --git a/apps/server/src/routes/api/sync.ts b/packages/trilium-core/src/routes/api/sync.ts
similarity index 88%
rename from apps/server/src/routes/api/sync.ts
rename to packages/trilium-core/src/routes/api/sync.ts
index a4307382e9..ed0c5f85b3 100644
--- a/apps/server/src/routes/api/sync.ts
+++ b/packages/trilium-core/src/routes/api/sync.ts
@@ -1,20 +1,20 @@
import { type EntityChange, SyncTestResponse } from "@triliumnext/commons";
-import { ValidationError } from "@triliumnext/core";
import type { Request } from "express";
import { t } from "i18next";
import consistencyChecksService from "../../services/consistency_checks.js";
import contentHashService from "../../services/content_hash.js";
import entityChangesService from "../../services/entity_changes.js";
-import log from "../../services/log.js";
+import { getLog } from "../../services/log.js";
import optionService from "../../services/options.js";
-import sql from "../../services/sql.js";
+import { getSql } from "../../services/sql/index.js";
import sqlInit from "../../services/sql_init.js";
import syncService from "../../services/sync.js";
import syncOptions from "../../services/sync_options.js";
import syncUpdateService from "../../services/sync_update.js";
-import utils, { safeExtractMessageAndStackFromError } from "../../services/utils.js";
+import * as utils from "../../services/utils/index.js";
import ws from "../../services/ws.js";
+import { ValidationError } from "../../errors.js";
async function testSync(): Promise<SyncTestResponse> {
try {
@@ -30,7 +30,7 @@ async function testSync(): Promise<SyncTestResponse> {
return { success: true, message: t("test_sync.successful") };
} catch (e: unknown) {
- const [errMessage] = safeExtractMessageAndStackFromError(e);
+ const [errMessage] = utils.safeExtractMessageAndStackFromError(e);
return {
success: false,
message: errMessage
@@ -45,11 +45,11 @@ function getStats() {
}
const stats = {
- initialized: sql.getValue("SELECT value FROM options WHERE name = 'initialized'") === "true",
+ initialized: getSql().getValue("SELECT value FROM options WHERE name = 'initialized'") === "true",
outstandingPullCount: syncService.getOutstandingPullCount()
};
- log.info(`Returning sync stats: ${JSON.stringify(stats)}`);
+ getLog().info(`Returning sync stats: ${JSON.stringify(stats)}`);
return stats;
}
@@ -57,12 +57,12 @@ function getStats() {
function checkSync() {
return {
entityHashes: contentHashService.getEntityHashes(),
- maxEntityChangeId: sql.getValue("SELECT COALESCE(MAX(id), 0) FROM entity_changes WHERE isSynced = 1")
+ maxEntityChangeId: getSql().getValue("SELECT COALESCE(MAX(id), 0) FROM entity_changes WHERE isSynced = 1")
};
}
function syncNow() {
- log.info("Received request to trigger sync now.");
+ getLog().info("Received request to trigger sync now.");
// when explicitly asked for set in progress status immediately for faster user feedback
ws.syncPullInProgress();
@@ -73,14 +73,14 @@ function syncNow() {
function fillEntityChanges() {
entityChangesService.fillAllEntityChanges();
- log.info("Sync rows have been filled.");
+ getLog().info("Sync rows have been filled.");
}
function forceFullSync() {
optionService.setOption("lastSyncedPull", 0);
optionService.setOption("lastSyncedPush", 0);
- log.info("Forcing full sync.");
+ getLog().info("Forcing full sync.");
// not awaiting for the job to finish (will probably take a long time)
syncService.sync();
@@ -149,6 +149,7 @@ function getChanged(req: Request) {
const clientInstanceId = req.query.instanceId;
let filteredEntityChanges: EntityChange[] = [];
+ const sql = getSql();
do {
const entityChanges: EntityChange[] = sql.getRows<EntityChange>(
`
@@ -177,7 +178,7 @@ function getChanged(req: Request) {
if (entityChangeRecords.length > 0) {
lastEntityChangeId = entityChangeRecords[entityChangeRecords.length - 1].entityChange.id;
- log.info(`Returning ${entityChangeRecords.length} entity changes in ${Date.now() - startTime}ms`);
+ getLog().info(`Returning ${entityChangeRecords.length} entity changes in ${Date.now() - startTime}ms`);
}
return {
@@ -282,7 +283,7 @@ function update(req: Request) {
partialRequests[requestId].payload += req.body;
- log.info(`Receiving a partial request ${requestId}, page ${pageIndex + 1} out of ${pageCount} pages.`);
+ getLog().info(`Receiving a partial request ${requestId}, page ${pageIndex + 1} out of ${pageCount} pages.`);
if (pageIndex !== pageCount - 1) {
return;
@@ -293,13 +294,13 @@ function update(req: Request) {
const { entities, instanceId } = body;
- sql.transactional(() => syncUpdateService.updateEntities(entities, instanceId));
+ getSql().transactional(() => syncUpdateService.updateEntities(entities, instanceId));
}
setInterval(() => {
for (const key in partialRequests) {
if (Date.now() - partialRequests[key].createdAt > 20 * 60 * 1000) {
- log.info(`Cleaning up unfinished partial requests for ${key}`);
+ getLog().info(`Cleaning up unfinished partial requests for ${key}`);
delete partialRequests[key];
}
diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.ts
index c517e0b485..50b885def7 100644
--- a/packages/trilium-core/src/routes/index.ts
+++ b/packages/trilium-core/src/routes/index.ts
@@ -19,6 +19,7 @@ import recentChangesApiRoute from "./api/recent_changes";
import bulkActionRoute from "./api/bulk_action";
import searchRoute from "./api/search";
import specialNotesRoute from "./api/special_notes";
+import syncApiRoute from "./api/sync";
// TODO: Deduplicate with routes.ts
const GET = "get",
@@ -28,11 +29,14 @@ const GET = "get",
DEL = "delete";
interface SharedApiRoutesContext {
+ route: any;
apiRoute: any;
asyncApiRoute: any;
+ checkApiAuth: any;
+ apiResultHandler: any;
}
-export function buildSharedApiRoutes({ apiRoute, asyncApiRoute }: SharedApiRoutesContext) {
+export function buildSharedApiRoutes({ route, apiRoute, asyncApiRoute, checkApiAuth, apiResultHandler }: SharedApiRoutesContext) {
apiRoute(GET, '/api/tree', treeApiRoute.getTree);
apiRoute(PST, '/api/tree/load', treeApiRoute.load);
@@ -99,6 +103,18 @@ export function buildSharedApiRoutes({ apiRoute, asyncApiRoute }: SharedApiRoute
apiRoute(PUT, "/api/branches/:branchId/set-prefix", branchesApiRoute.setPrefix);
apiRoute(PUT, "/api/branches/set-prefix-batch", branchesApiRoute.setPrefixBatch);
+ asyncApiRoute(PST, "/api/sync/test", syncApiRoute.testSync);
+ asyncApiRoute(PST, "/api/sync/now", syncApiRoute.syncNow);
+ apiRoute(PST, "/api/sync/fill-entity-changes", syncApiRoute.fillEntityChanges);
+ apiRoute(PST, "/api/sync/force-full-sync", syncApiRoute.forceFullSync);
+ route(GET, "/api/sync/check", [checkApiAuth], syncApiRoute.checkSync, apiResultHandler);
+ route(GET, "/api/sync/changed", [checkApiAuth], syncApiRoute.getChanged, apiResultHandler);
+ route(PUT, "/api/sync/update", [checkApiAuth], syncApiRoute.update, apiResultHandler);
+ route(PST, "/api/sync/finished", [checkApiAuth], syncApiRoute.syncFinished, apiResultHandler);
+ route(PST, "/api/sync/check-entity-changes", [checkApiAuth], syncApiRoute.checkEntityChanges, apiResultHandler);
+ route(PST, "/api/sync/queue-sector/:entityName/:sector", [checkApiAuth], syncApiRoute.queueSector, apiResultHandler);
+ route(GET, "/api/sync/stats", [], syncApiRoute.getStats, apiResultHandler);
+
apiRoute(GET, "/api/quick-search/:searchString", searchRoute.quickSearch);
apiRoute(GET, "/api/search-note/:noteId", searchRoute.searchFromNote);
apiRoute(PST, "/api/search-and-execute-note/:noteId", searchRoute.searchAndExecute);
diff --git a/packages/trilium-core/src/services/setup.ts b/packages/trilium-core/src/services/setup.ts
new file mode 100644
index 0000000000..046738dbd6
--- /dev/null
+++ b/packages/trilium-core/src/services/setup.ts
@@ -0,0 +1,121 @@
+import syncService from "./sync.js";
+import { getLog } from "./log.js";
+import sqlInit from "./sql_init.js";
+import optionService from "./options.js";
+import syncOptions from "./sync_options.js";
+import appInfo from "./app_info.js";
+import { timeLimit } from "./utils/index.js";
+import becca from "../becca/becca.js";
+import type { SetupStatusResponse, SetupSyncSeedResponse } from "@triliumnext/commons";
+import request from "./request.js";
+
+async function hasSyncServerSchemaAndSeed() {
+ const response = await requestToSyncServer<SetupStatusResponse>("GET", "/api/setup/status");
+
+ if (response.syncVersion !== appInfo.syncVersion) {
+ throw new Error(
+ `Could not setup sync since local sync protocol version is ${appInfo.syncVersion} while remote is ${response.syncVersion}. To fix this issue, use same Trilium version on all instances.`
+ );
+ }
+
+ return response.schemaExists;
+}
+
+function triggerSync() {
+ getLog().info("Triggering sync.");
+
+ // it's ok to not wait for it here
+ syncService.sync().then((res) => {
+ if (res.success) {
+ sqlInit.setDbAsInitialized();
+ }
+ });
+}
+
+async function sendSeedToSyncServer() {
+ getLog().info("Initiating sync to server");
+
+ await requestToSyncServer<void>("POST", "/api/setup/sync-seed", {
+ options: getSyncSeedOptions(),
+ syncVersion: appInfo.syncVersion
+ });
+
+ // this is a completely new sync, need to reset counters. If this was not a new sync,
+ // the previous request would have failed.
+ optionService.setOption("lastSyncedPush", 0);
+ optionService.setOption("lastSyncedPull", 0);
+}
+
+async function requestToSyncServer<T>(method: string, path: string, body?: string | {}): Promise<T> {
+ const timeout = syncOptions.getSyncTimeout();
+
+ return (await timeLimit(
+ request.exec({
+ method,
+ url: syncOptions.getSyncServerHost() + path,
+ body,
+ proxy: syncOptions.getSyncProxy(),
+ timeout: timeout
+ }),
+ timeout
+ )) as T;
+}
+
+async function setupSyncFromSyncServer(syncServerHost: string, syncProxy: string, password: string) {
+ if (sqlInit.isDbInitialized()) {
+ return {
+ result: "failure",
+ error: "DB is already initialized."
+ };
+ }
+
+ const log = getLog();
+ try {
+ log.info("Getting document options FROM sync server.");
+
+ // the response is expected to contain documentId and documentSecret options
+ const resp = await request.exec<SetupSyncSeedResponse>({
+ method: "get",
+ url: `${syncServerHost}/api/setup/sync-seed`,
+ auth: { password },
+ proxy: syncProxy,
+ timeout: 30000 // seed request should not take long
+ });
+
+ if (resp.syncVersion !== appInfo.syncVersion) {
+ const message = `Could not setup sync since local sync protocol version is ${appInfo.syncVersion} while remote is ${resp.syncVersion}. To fix this issue, use same Trilium version on all instances.`;
+
+ log.error(message);
+
+ return {
+ result: "failure",
+ error: message
+ };
+ }
+
+ await sqlInit.createDatabaseForSync(resp.options, syncServerHost, syncProxy);
+
+ triggerSync();
+
+ return { result: "success" };
+ } catch (e: any) {
+ log.error(`Sync failed: '${e.message}', stack: ${e.stack}`);
+
+ return {
+ result: "failure",
+ error: e.message
+ };
+ }
+}
+
+function getSyncSeedOptions() {
+ return [becca.getOption("documentId"), becca.getOption("documentSecret")];
+}
+
+export default {
+ hasSyncServerSchemaAndSeed,
+ triggerSync,
+ sendSeedToSyncServer,
+ setupSyncFromSyncServer,
+ getSyncSeedOptions
+};
diff --git a/packages/trilium-core/src/services/sql_init.ts b/packages/trilium-core/src/services/sql_init.ts
index 6d3b509c3c..35b2933e28 100644
--- a/packages/trilium-core/src/services/sql_init.ts
+++ b/packages/trilium-core/src/services/sql_init.ts
@@ -11,4 +11,16 @@ function isDbInitialized() {
return true;
}
-export default { isDbInitialized };
+async function createDatabaseForSync(a: any, b: string, c: any) {
+ console.error("createDatabaseForSync is not implemented yet");
+}
+
+function setDbAsInitialized() {
+ // Noop.
+}
+
+function schemaExists() {
+ return true;
+}
+
+export default { isDbInitialized, createDatabaseForSync, setDbAsInitialized, schemaExists };
diff --git a/packages/trilium-core/src/services/sync.ts b/packages/trilium-core/src/services/sync.ts
new file mode 100644
index 0000000000..1cd56998f6
--- /dev/null
+++ b/packages/trilium-core/src/services/sync.ts
@@ -0,0 +1,470 @@
+import type { EntityChange, EntityChangeRecord, EntityRow } from "@triliumnext/commons";
+
+import becca from "../becca/becca.js";
+import appInfo from "./app_info.js";
+import * as cls from "./context.js";
+import consistency_checks from "./consistency_checks.js";
+import contentHashService from "./content_hash.js";
+import dateUtils from "./utils/date.js";
+import entityChangesService from "./entity_changes.js";
+import { getLog } from "./log.js";
+import optionService from "./options.js";
+import setupService from "./setup.js";
+import { getSql } from "./sql/index.js";
+import syncMutexService from "./sync_mutex.js";
+import syncOptions from "./sync_options.js";
+import syncUpdateService from "./sync_update.js";
+import { hmac, randomString, timeLimit } from "./utils/index.js";
+import ws from "./ws.js";
+import getInstanceId from "./instance_id.js";
+import request, { CookieJar, ExecOpts } from "./request.js";
+import entity_constructor from "../../src/becca/entity_constructor.js";
+import becca_loader from "../becca/becca_loader.js";
+import * as binary_utils from "./utils/binary.js";
+
+let proxyToggle = true;
+
+let outstandingPullCount = 0;
+
+interface CheckResponse {
+ maxEntityChangeId: number;
+ entityHashes: Record<string, Record<string, string>>;
+}
+
+interface SyncResponse {
+ instanceId: string;
+ maxEntityChangeId: number;
+}
+
+interface ChangesResponse {
+ entityChanges: EntityChangeRecord[];
+ lastEntityChangeId: number;
+ outstandingPullCount: number;
+}
+
+interface SyncContext {
+ cookieJar: CookieJar;
+ instanceId?: string;
+}
+
+async function sync() {
+ try {
+ return await syncMutexService.doExclusively(async () => {
+ if (!syncOptions.isSyncSetup()) {
+ return { success: false, errorCode: "NOT_CONFIGURED", message: "Sync not configured" };
+ }
+
+ let continueSync = false;
+
+ do {
+ const syncContext = await login();
+
+ await pushChanges(syncContext);
+
+ await pullChanges(syncContext);
+
+ await pushChanges(syncContext);
+
+ await syncFinished(syncContext);
+
+ continueSync = await checkContentHash(syncContext);
+ } while (continueSync);
+
+ ws.syncFinished();
+
+ return {
+ success: true
+ };
+ });
+ } catch (e: any) {
+ // we're dynamically switching whether we're using proxy or not based on whether we encountered error with the current method
+ proxyToggle = !proxyToggle;
+
+ const log = getLog();
+ if (
+ e.message?.includes("ECONNREFUSED") ||
+ e.message?.includes("ERR_") || // node network errors
+ e.message?.includes("Bad Gateway")
+ ) {
+ ws.syncFailed();
+
+ log.info("No connection to sync server.");
+
+ return {
+ success: false,
+ message: "No connection to sync server."
+ };
+ }
+ log.info(`Sync failed: '${e.message}', stack: ${e.stack}`);
+
+ ws.syncFailed();
+
+ return {
+ success: false,
+ message: e.message
+ };
+
+ }
+}
+
+async function login() {
+ if (!(await setupService.hasSyncServerSchemaAndSeed())) {
+ await setupService.sendSeedToSyncServer();
+ }
+
+ return await doLogin();
+}
+
+async function doLogin(): Promise<SyncContext> {
+ const timestamp = dateUtils.utcNowDateTime();
+
+ const documentSecret = optionService.getOption("documentSecret");
+ const hash = hmac(documentSecret, timestamp);
+
+ const syncContext: SyncContext = { cookieJar: {} };
+ const resp = await syncRequest<SyncResponse>(syncContext, "POST", "/api/login/sync", {
+ timestamp,
+ syncVersion: appInfo.syncVersion,
+ hash
+ });
+
+ if (!resp) {
+ throw new Error("Got no response.");
+ }
+
+ if (resp.instanceId === getInstanceId()) {
+ throw new Error(
+ `Sync server has instance ID '${resp.instanceId}' which is also local. This usually happens when the sync client is (mis)configured to sync with itself (URL points back to client) instead of the correct sync server.`
+ );
+ }
+
+ syncContext.instanceId = resp.instanceId;
+
+ const lastSyncedPull = getLastSyncedPull();
+
+ // this is important in a scenario where we set up the sync by manually copying the document
+ // lastSyncedPull then could be pretty off for the newly cloned client
+ if (lastSyncedPull > resp.maxEntityChangeId) {
+ getLog().info(`Lowering last synced pull from ${lastSyncedPull} to ${resp.maxEntityChangeId}`);
+
+ setLastSyncedPull(resp.maxEntityChangeId);
+ }
+
+ return syncContext;
+}
+
+async function pullChanges(syncContext: SyncContext) {
+ const log = getLog();
+
+ while (true) {
+ const lastSyncedPull = getLastSyncedPull();
+ const logMarkerId = randomString(10); // to easily pair sync events between client and server logs
+ const changesUri = `/api/sync/changed?instanceId=${getInstanceId()}&lastEntityChangeId=${lastSyncedPull}&logMarkerId=${logMarkerId}`;
+
+ const startDate = Date.now();
+
+ const resp = await syncRequest<ChangesResponse>(syncContext, "GET", changesUri);
+ if (!resp) {
+ throw new Error("Request failed.");
+ }
+ const { entityChanges, lastEntityChangeId } = resp;
+
+ outstandingPullCount = resp.outstandingPullCount;
+
+ const pulledDate = Date.now();
+
+ getSql().transactional(() => {
+ if (syncContext.instanceId) {
+ syncUpdateService.updateEntities(entityChanges, syncContext.instanceId);
+ }
+
+ if (lastSyncedPull !== lastEntityChangeId) {
+ setLastSyncedPull(lastEntityChangeId);
+ }
+ });
+
+ if (entityChanges.length === 0) {
+ break;
+ } else {
+ try {
+ // https://github.com/zadam/trilium/issues/4310
+ const sizeInKb = Math.round(JSON.stringify(resp).length / 1024);
+
+ log.info(
+ `Sync ${logMarkerId}: Pulled ${entityChanges.length} changes in ${sizeInKb} KB, starting at entityChangeId=${lastSyncedPull} in ${pulledDate - startDate}ms and applied them in ${Date.now() - pulledDate}ms, ${outstandingPullCount} outstanding pulls`
+ );
+ } catch (e: any) {
+ log.error(`Error occurred ${e.message} ${e.stack}`);
+ }
+ }
+ }
+
+ log.info("Finished pull");
+}
+
+async function pushChanges(syncContext: SyncContext) {
+ let lastSyncedPush: number | null | undefined = getLastSyncedPush();
+
+ while (true) {
+ const entityChanges = getSql().getRows<EntityChange>("SELECT * FROM entity_changes WHERE isSynced = 1 AND id > ? LIMIT 1000", [lastSyncedPush]);
+
+ if (entityChanges.length === 0) {
+ getLog().info("Nothing to push");
+
+ break;
+ }
+
+ const filteredEntityChanges = entityChanges.filter((entityChange) => {
+ if (entityChange.instanceId === syncContext.instanceId) {
+ // this may set lastSyncedPush beyond what's actually sent (because of size limit)
+ // so this is applied to the database only if there's no actual update
+ lastSyncedPush = entityChange.id;
+
+ return false;
+ }
+ return true;
+
+ });
+
+ if (filteredEntityChanges.length === 0 && lastSyncedPush) {
+ // there still might be more sync changes (because of batch limit), just all the current batch
+ // has been filtered out
+ setLastSyncedPush(lastSyncedPush);
+
+ continue;
+ }
+
+ const entityChangesRecords = getEntityChangeRecords(filteredEntityChanges);
+ const startDate = new Date();
+
+ const logMarkerId = randomString(10); // to easily pair sync events between client and server logs
+
+ await syncRequest(syncContext, "PUT", `/api/sync/update?logMarkerId=${logMarkerId}`, {
+ entities: entityChangesRecords,
+ instanceId: getInstanceId()
+ });
+
+ ws.syncPushInProgress();
+
+ getLog().info(`Sync ${logMarkerId}: Pushing ${entityChangesRecords.length} sync changes in ${Date.now() - startDate.getTime()}ms`);
+
+ lastSyncedPush = entityChangesRecords[entityChangesRecords.length - 1].entityChange.id;
+
+ if (lastSyncedPush) {
+ setLastSyncedPush(lastSyncedPush);
+ }
+ }
+}
+
+async function syncFinished(syncContext: SyncContext) {
+ await syncRequest(syncContext, "POST", "/api/sync/finished");
+}
+
+async function checkContentHash(syncContext: SyncContext) {
+ const resp = await syncRequest<CheckResponse>(syncContext, "GET", "/api/sync/check");
+ if (!resp) {
+ throw new Error("Got no response.");
+ }
+
+ const lastSyncedPullId = getLastSyncedPull();
+ const log = getLog();
+
+ if (lastSyncedPullId < resp.maxEntityChangeId) {
+ log.info(`There are some outstanding pulls (${lastSyncedPullId} vs. ${resp.maxEntityChangeId}), skipping content check.`);
+
+ return true;
+ }
+
+ const notPushedSyncs = getSql().getValue("SELECT EXISTS(SELECT 1 FROM entity_changes WHERE isSynced = 1 AND id > ?)", [getLastSyncedPush()]);
+
+ if (notPushedSyncs) {
+ log.info(`There's ${notPushedSyncs} outstanding pushes, skipping content check.`);
+
+ return true;
+ }
+
+ const failedChecks = contentHashService.checkContentHashes(resp.entityHashes);
+
+ if (failedChecks.length > 0) {
+ // before re-queuing sectors, make sure the entity changes are correct
+ consistency_checks.runEntityChangesChecks();
+
+ await syncRequest(syncContext, "POST", `/api/sync/check-entity-changes`);
+ }
+
+ for (const { entityName, sector } of failedChecks) {
+ entityChangesService.addEntityChangesForSector(entityName, sector);
+
+ await syncRequest(syncContext, "POST", `/api/sync/queue-sector/${entityName}/${sector}`);
+ }
+
+ return failedChecks.length > 0;
+}
+
+const PAGE_SIZE = 1000000;
+
+interface SyncContext {
+ cookieJar: CookieJar;
+}
+
+async function syncRequest<T extends {}>(syncContext: SyncContext, method: string, requestPath: string, _body?: {}) {
+ const body = _body ? JSON.stringify(_body) : "";
+
+ const timeout = syncOptions.getSyncTimeout();
+
+ let response;
+
+ const requestId = randomString(10);
+ const pageCount = Math.max(1, Math.ceil(body.length / PAGE_SIZE));
+
+ for (let pageIndex = 0; pageIndex < pageCount; pageIndex++) {
+ const opts: ExecOpts = {
+ method,
+ url: syncOptions.getSyncServerHost() + requestPath,
+ cookieJar: syncContext.cookieJar,
+ timeout,
+ paging: {
+ pageIndex,
+ pageCount,
+ requestId
+ },
+ body: body.substr(pageIndex * PAGE_SIZE, Math.min(PAGE_SIZE, body.length - pageIndex * PAGE_SIZE)),
+ proxy: proxyToggle ? syncOptions.getSyncProxy() : null
+ };
+
+ response = (await timeLimit(request.exec(opts), timeout)) as T;
+ }
+
+ return response;
+}
+
+function getEntityChangeRow(entityChange: EntityChange) {
+ const { entityName, entityId } = entityChange;
+
+ if (entityName === "note_reordering") {
+ return getSql().getMap("SELECT branchId, notePosition FROM branches WHERE parentNoteId = ? AND isDeleted = 0", [entityId]);
+ }
+ const primaryKey = entity_constructor.getEntityFromEntityName(entityName).primaryKeyName;
+
+ if (!primaryKey) {
+ throw new Error(`Unknown entity for entity change ${JSON.stringify(entityChange)}`);
+ }
+
+ const entityRow = getSql().getRow<EntityRow>(/*sql*/`SELECT * FROM ${entityName} WHERE ${primaryKey} = ?`, [entityId]);
+
+ if (!entityRow) {
+ getLog().error(`Cannot find entity for entity change ${JSON.stringify(entityChange)}`);
+ return null;
+ }
+
+ if (entityName === "blobs" && entityRow.content !== null) {
+ if (typeof entityRow.content === "string") {
+ entityRow.content = Buffer.from(entityRow.content, "utf-8");
+ }
+
+ if (entityRow.content) {
+ entityRow.content = binary_utils.encodeBase64(entityRow.content);
+ }
+ }
+
+
+ return entityRow;
+
+}
+
+function getEntityChangeRecords(entityChanges: EntityChange[]) {
+ const records: EntityChangeRecord[] = [];
+ let length = 0;
+
+ for (const entityChange of entityChanges) {
+ if (entityChange.isErased) {
+ records.push({ entityChange });
+
+ continue;
+ }
+
+ const entity = getEntityChangeRow(entityChange);
+ if (!entity) {
+ continue;
+ }
+
+ const record: EntityChangeRecord = { entityChange, entity };
+
+ records.push(record);
+
+ length += JSON.stringify(record).length;
+
+ if (length > 1_000_000) {
+ // each sync request/response should have at most ~1 MB.
+ break;
+ }
+ }
+
+ return records;
+}
+
+function getLastSyncedPull() {
+ return parseInt(optionService.getOption("lastSyncedPull"));
+}
+
+function setLastSyncedPull(entityChangeId: number) {
+ const lastSyncedPullOption = becca.getOption("lastSyncedPull");
+
+ if (lastSyncedPullOption) {
+ // might be null in initial sync when becca is not loaded
+ lastSyncedPullOption.value = `${entityChangeId}`;
+ }
+
+ // this way we avoid updating entity_changes which otherwise means that we've never pushed all entity_changes
+ getSql().execute("UPDATE options SET value = ? WHERE name = ?", [entityChangeId, "lastSyncedPull"]);
+}
+
+function getLastSyncedPush() {
+ const lastSyncedPush = parseInt(optionService.getOption("lastSyncedPush"));
+
+ ws.setLastSyncedPush(lastSyncedPush);
+
+ return lastSyncedPush;
+}
+
+function setLastSyncedPush(entityChangeId: number) {
+ ws.setLastSyncedPush(entityChangeId);
+
+ const lastSyncedPushOption = becca.getOption("lastSyncedPush");
+
+ if (lastSyncedPushOption) {
+ // might be null in initial sync when becca is not loaded
+ lastSyncedPushOption.value = `${entityChangeId}`;
+ }
+
+ // this way we avoid updating entity_changes which otherwise means that we've never pushed all entity_changes
+ getSql().execute("UPDATE options SET value = ? WHERE name = ?", [entityChangeId, "lastSyncedPush"]);
+}
+
+function getMaxEntityChangeId() {
+ return getSql().getValue("SELECT COALESCE(MAX(id), 0) FROM entity_changes");
+}
+
+function getOutstandingPullCount() {
+ return outstandingPullCount;
+}
+
+export function startSyncTimer() {
+ becca_loader.beccaLoaded.then(() => {
+ setInterval(cls.wrap(sync), 60000);
+
+ // kickoff initial sync immediately, but should happen after initial consistency checks
+ setTimeout(cls.wrap(sync), 5000);
+
+ // called just so ws.setLastSyncedPush() is called
+ getLastSyncedPush();
+ });
+}
+
+export default {
+ sync,
+ login,
+ getEntityChangeRecords,
+ getOutstandingPullCount,
+ getMaxEntityChangeId
+};
diff --git a/packages/trilium-core/src/services/sync_options.ts b/packages/trilium-core/src/services/sync_options.ts
new file mode 100644
index 0000000000..a94dbd12f1
--- /dev/null
+++ b/packages/trilium-core/src/services/sync_options.ts
@@ -0,0 +1,34 @@
+"use strict";
+
+import optionService from "./options.js";
+import config from "./config.js";
+import { normalizeUrl } from "./utils/index.js";
+
+/*
+ * Primary configuration for sync is in the options (document), but we allow to override
+ * these settings in config file. The reason for that is to avoid a mistake of loading a live/production
+ * document with live sync settings in a dev/debug environment. Changes would then successfully propagate
+ * to live sync server.
+ */
+
+function get(name: keyof typeof config.Sync) {
+ return (config["Sync"] && config["Sync"][name]) || optionService.getOption(name);
+}
+
+export default {
+ // env variable is the easiest way to guarantee we won't overwrite prod data during development
+ // after copying prod document/data directory
+ getSyncServerHost: () => {
+ const host = get("syncServerHost");
+ return host ? normalizeUrl(host) : host;
+ },
+ isSyncSetup: () => {
+ const syncServerHost = get("syncServerHost");
+
+ // special value "disabled" is here to support a use case where the document is configured with sync server,
+ // and we need to override it with config from config.ini
+ return !!syncServerHost && syncServerHost !== "disabled";
+ },
+ getSyncTimeout: () => parseInt(get("syncServerTimeout")) || 120000,
+ getSyncProxy: () => get("syncProxy")
+};
diff --git a/packages/trilium-core/src/services/sync_update.ts b/packages/trilium-core/src/services/sync_update.ts
new file mode 100644
index 0000000000..f3a52eff22
--- /dev/null
+++ b/packages/trilium-core/src/services/sync_update.ts
@@ -0,0 +1,171 @@
+import type { EntityChange, EntityChangeRecord, EntityRow } from "@triliumnext/commons";
+
+import entityChangesService from "./entity_changes.js";
+import { getLog } from "./log.js";
+import { getSql } from "./sql/index.js";
+import ws from "./ws.js";
+import { default as eventService } from "./events.js";
+import entity_constructor from "src/becca/entity_constructor.js";
+
+interface UpdateContext {
+ alreadyErased: number;
+ erased: number;
+ updated: Record<string, string[]>;
+}
+
+function updateEntities(entityChanges: EntityChangeRecord[], instanceId: string) {
+ if (entityChanges.length === 0) {
+ return;
+ }
+
+ let atLeastOnePullApplied = false;
+ const updateContext = {
+ updated: {},
+ alreadyUpdated: 0,
+ erased: 0,
+ alreadyErased: 0
+ };
+
+ for (const { entityChange, entity } of entityChanges) {
+ const changeAppliedAlready = entityChange.changeId && !!getSql().getValue("SELECT 1 FROM entity_changes WHERE changeId = ?", [entityChange.changeId]);
+
+ if (changeAppliedAlready) {
+ updateContext.alreadyUpdated++;
+
+ continue;
+ }
+
+ if (!atLeastOnePullApplied) {
+ // avoid spamming and send only for first
+ ws.syncPullInProgress();
+
+ atLeastOnePullApplied = true;
+ }
+
+ updateEntity(entityChange, entity, instanceId, updateContext);
+ }
+
+ logUpdateContext(updateContext);
+}
+
+function updateEntity(remoteEC: EntityChange, remoteEntityRow: EntityRow | undefined, instanceId: string, updateContext: UpdateContext) {
+ if (!remoteEntityRow && remoteEC.entityName === "options") {
+ return; // can be undefined for options with isSynced=false
+ }
+
+ const updated = remoteEC.entityName === "note_reordering"
+ ? updateNoteReordering(remoteEC, remoteEntityRow, instanceId)
+ : updateNormalEntity(remoteEC, remoteEntityRow, instanceId, updateContext);
+
+ if (updated) {
+ if (remoteEntityRow?.isDeleted) {
+ eventService.emit(eventService.ENTITY_DELETE_SYNCED, {
+ entityName: remoteEC.entityName,
+ entityId: remoteEC.entityId
+ });
+ } else if (!remoteEC.isErased) {
+ eventService.emit(eventService.ENTITY_CHANGE_SYNCED, {
+ entityName: remoteEC.entityName,
+ entityRow: remoteEntityRow
+ });
+ }
+ }
+}
+
+function updateNormalEntity(remoteEC: EntityChange, remoteEntityRow: EntityRow | undefined, instanceId: string, updateContext: UpdateContext) {
+ const localEC = getSql().getRow<EntityChange | undefined>(/*sql*/`SELECT * FROM entity_changes WHERE entityName = ? AND entityId = ?`, [remoteEC.entityName, remoteEC.entityId]);
+ const localECIsOlderOrSameAsRemote = localEC && localEC.utcDateChanged && remoteEC.utcDateChanged && localEC.utcDateChanged <= remoteEC.utcDateChanged;
+
+ if (!localEC || localECIsOlderOrSameAsRemote) {
+ if (remoteEC.isErased) {
+ if (localEC?.isErased) {
+ eraseEntity(remoteEC); // make sure it's erased anyway
+ updateContext.alreadyErased++;
+ } else {
+ eraseEntity(remoteEC);
+ updateContext.erased++;
+ }
+ } else {
+ if (!remoteEntityRow) {
+ throw new Error(`Empty entity row for: ${JSON.stringify(remoteEC)}`);
+ }
+
+ preProcessContent(remoteEC, remoteEntityRow);
+
+ getSql().replace(remoteEC.entityName, remoteEntityRow);
+
+ updateContext.updated[remoteEC.entityName] = updateContext.updated[remoteEC.entityName] || [];
+ updateContext.updated[remoteEC.entityName].push(remoteEC.entityId);
+ }
+
+ if (!localEC || localECIsOlderOrSameAsRemote || localEC.hash !== remoteEC.hash || localEC.isErased !== remoteEC.isErased) {
+ entityChangesService.putEntityChangeWithInstanceId(remoteEC, instanceId);
+ }
+
+ return true;
+ } else if ((localEC.hash !== remoteEC.hash || localEC.isErased !== remoteEC.isErased) && !localECIsOlderOrSameAsRemote) {
+ // the change on our side is newer than on the other side, so the other side should update
+ entityChangesService.putEntityChangeForOtherInstances(localEC);
+
+ return false;
+ }
+
+ return false;
+}
+
+function preProcessContent(remoteEC: EntityChange, remoteEntityRow: EntityRow) {
+ if (remoteEC.entityName === "blobs" && remoteEntityRow.content !== null) {
+ // we always use a Buffer object which is different from normal saving - there we use a simple string type for
+ // "string notes". The problem is that in general, it's not possible to detect whether a blob content
+ // is string note or note (syncs can arrive out of order)
+ if (typeof remoteEntityRow.content === "string") {
+ remoteEntityRow.content = Buffer.from(remoteEntityRow.content, "base64");
+
+ if (remoteEntityRow.content.byteLength === 0) {
+ // there seems to be a bug which causes empty buffer to be stored as NULL which is then picked up as inconsistency
+ // (possibly not a problem anymore with the newer better-sqlite3)
+ remoteEntityRow.content = "";
+ }
+ }
+ }
+}
+
+function updateNoteReordering(remoteEC: EntityChange, remoteEntityRow: EntityRow | undefined, instanceId: string) {
+ if (!remoteEntityRow) {
+ throw new Error(`Empty note_reordering body for: ${JSON.stringify(remoteEC)}`);
+ }
+
+ for (const key in remoteEntityRow) {
+ getSql().execute("UPDATE branches SET notePosition = ? WHERE branchId = ?", [remoteEntityRow[key as keyof EntityRow], key]);
+ }
+
+ entityChangesService.putEntityChangeWithInstanceId(remoteEC, instanceId);
+
+ return true;
+}
+
+
+function eraseEntity(entityChange: EntityChange) {
+ const { entityName, entityId } = entityChange;
+
+ const entityNames = ["notes", "branches", "attributes", "revisions", "attachments", "blobs"];
+
+ if (!entityNames.includes(entityName)) {
+ getLog().error(`Cannot erase ${entityName} '${entityId}'.`);
+ return;
+ }
+
+ const primaryKeyName = entity_constructor.getEntityFromEntityName(entityName).primaryKeyName;
+
+ getSql().execute(/*sql*/`DELETE FROM ${entityName} WHERE ${primaryKeyName} = ?`, [entityId]);
+}
+
+function logUpdateContext(updateContext: UpdateContext) {
+ const message = JSON.stringify(updateContext).replaceAll('"', "").replaceAll(":", ": ").replaceAll(",", ", ");
+
+ getLog().info(message.substr(1, message.length - 2));
+}
+
+export default {
+ updateEntities
+};
diff --git a/packages/trilium-core/src/services/utils/index.ts b/packages/trilium-core/src/services/utils/index.ts
index ba0ad517d1..74f47927a4 100644
--- a/packages/trilium-core/src/services/utils/index.ts
+++ b/packages/trilium-core/src/services/utils/index.ts
@@ -68,6 +68,65 @@ export function normalize(str: string) {
return removeDiacritic(str).toLowerCase();
}
+/**
+ * Normalizes URL by removing trailing slashes and fixing double slashes.
+ * Preserves the protocol (http://, https://) but removes trailing slashes from the rest.
+ *
+ * @param url The URL to normalize
+ * @returns The normalized URL without trailing slashes
+ */
+export function normalizeUrl(url: string | null | undefined): string | null | undefined {
+ if (!url || typeof url !== 'string') {
+ return url;
+ }
+
+ // Trim whitespace
+ url = url.trim();
+
+ if (!url) {
+ return url;
+ }
+
+ // Fix double slashes (except in protocol) first
+ url = url.replace(/([^:]\/)\/+/g, '$1');
+
+ // Remove trailing slash, but preserve protocol
+ if (url.endsWith('/') && !url.match(/^https?:\/\/$/)) {
+ url = url.slice(0, -1);
+ }
+
+ return url;
+}
+
+export function timeLimit<T>(promise: Promise<T>, limitMs: number, errorMessage?: string): Promise<T> {
+ // TriliumNextTODO: since TS avoids this from ever happening – do we need this check?
+ if (!promise || !promise.then) {
+ // it's not actually a promise
+ return promise;
+ }
+
+ // better stack trace if created outside of promise
+ const errorTimeLimit = new Error(errorMessage || `Process exceeded time limit ${limitMs}`);
+
+ return new Promise((res, rej) => {
+ let resolved = false;
+
+ promise
+ .then((result) => {
+ resolved = true;
+
+ res(result);
+ })
+ .catch((error) => rej(error));
+
+ setTimeout(() => {
+ if (!resolved) {
+ rej(errorTimeLimit);
+ }
+ }, limitMs);
+ });
+}
+
export function sanitizeAttributeName(origName: string) {
const fixedName = origName === "" ? "unnamed" : origName.replace(/[^\p{L}\p{N}_:]/gu, "_");
// any not allowed character should be replaced with underscore
@@ -75,6 +134,10 @@ export function sanitizeAttributeName(origName: string) {
return fixedName;
}
+export function sanitizeSqlIdentifier(str: string) {
+ return str.replace(/[^A-Za-z0-9_]/g, "");
+}
+
export function getContentDisposition(filename: string) {
const sanitizedFilename = sanitizeFileName(filename).trim() || "file";
const uriEncodedFilename = encodeURIComponent(sanitizedFilename);