mirror of
https://github.com/vrtmrz/obsidian-livesync.git
synced 2026-09-21 18:17:05 +00:00
Migrate LiveSync flows to provider-owned resources
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Run a finite operation with a flow-owned remote resource and release it
|
||||
* after either success or failure.
|
||||
*
|
||||
* Resource implementations make `dispose()` idempotent. This helper makes the
|
||||
* caller's ownership boundary explicit and prevents finite flows from leaking
|
||||
* a provider-owned resource when their operation rejects.
|
||||
*/
|
||||
export async function withOwnedRemoteResource<TResource extends { dispose(): Promise<void> }, TResult>(
|
||||
resource: TResource,
|
||||
operation: (ownedResource: TResource) => Promise<TResult>
|
||||
): Promise<TResult> {
|
||||
try {
|
||||
return await operation(resource);
|
||||
} finally {
|
||||
await resource.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { withOwnedRemoteResource } from "./ownedRemoteResource";
|
||||
|
||||
describe("flow-owned remote resources", () => {
|
||||
it("disposes a resource after a successful finite operation", async () => {
|
||||
const dispose = vi.fn(async () => undefined);
|
||||
const resource = { dispose };
|
||||
|
||||
await expect(
|
||||
withOwnedRemoteResource(resource, async (owned) => (owned === resource ? "done" : "wrong"))
|
||||
).resolves.toBe("done");
|
||||
|
||||
expect(dispose).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("disposes a resource when the finite operation rejects", async () => {
|
||||
const dispose = vi.fn(async () => undefined);
|
||||
const error = new Error("resource operation failed");
|
||||
|
||||
await expect(
|
||||
withOwnedRemoteResource({ dispose }, async () => {
|
||||
throw error;
|
||||
})
|
||||
).rejects.toBe(error);
|
||||
|
||||
expect(dispose).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,143 @@
|
||||
import {
|
||||
MILESTONE_DOCID,
|
||||
type EntryMilestoneInfo,
|
||||
type RemoteDBSettings,
|
||||
} from "@vrtmrz/livesync-commonlib/compat/common/types";
|
||||
import type { LiveSyncAbstractReplicator } from "@vrtmrz/livesync-commonlib/compat/replication/LiveSyncAbstractReplicator";
|
||||
import { LiveSyncCouchDBReplicator } from "@vrtmrz/livesync-commonlib/compat/replication/couchdb/LiveSyncReplicator";
|
||||
import { LiveSyncJournalReplicator } from "@vrtmrz/livesync-commonlib/compat/replication/journal/LiveSyncJournalReplicator";
|
||||
import {
|
||||
REMOTE_ADMINISTRATION_FAILURE_REASONS,
|
||||
REMOTE_ADMINISTRATION_OBSERVATION_KINDS,
|
||||
applyRemoteAdministrationMutation,
|
||||
milestoneSatisfiesRemoteAdministration,
|
||||
remoteAdministrationVerificationFailed,
|
||||
remoteAdministrationVerified,
|
||||
supportedCapability,
|
||||
type MilestoneRemoteAdministrationObservation,
|
||||
type RemoteAdministrationRequest,
|
||||
type RemoteAdministrationResult,
|
||||
type SupportedCapability,
|
||||
type RemoteAdministrationRunner,
|
||||
} from "@vrtmrz/livesync-commonlib/replication";
|
||||
|
||||
const JOURNAL_MILESTONE_PATH = "_00000000-milestone.json";
|
||||
|
||||
async function ensureLocalNodeIdentity(
|
||||
replicator: LiveSyncAbstractReplicator
|
||||
): Promise<RemoteAdministrationResult | undefined> {
|
||||
if (replicator.nodeid) {
|
||||
return undefined;
|
||||
}
|
||||
if ((await replicator.initializeDatabaseForReplication()) && replicator.nodeid) {
|
||||
return undefined;
|
||||
}
|
||||
return remoteAdministrationVerificationFailed(REMOTE_ADMINISTRATION_FAILURE_REASONS.LOCAL_IDENTITY_UNAVAILABLE);
|
||||
}
|
||||
|
||||
function observeMilestone(
|
||||
replicator: LiveSyncAbstractReplicator,
|
||||
milestone: EntryMilestoneInfo
|
||||
): MilestoneRemoteAdministrationObservation {
|
||||
return {
|
||||
kind: REMOTE_ADMINISTRATION_OBSERVATION_KINDS.MILESTONE,
|
||||
locked: !!milestone.locked,
|
||||
accepted: !!milestone.accepted_nodes?.includes(replicator.nodeid),
|
||||
nodeId: replicator.nodeid,
|
||||
};
|
||||
}
|
||||
|
||||
function resultFromMilestone(
|
||||
replicator: LiveSyncAbstractReplicator,
|
||||
request: RemoteAdministrationRequest,
|
||||
milestone: EntryMilestoneInfo | false | undefined
|
||||
): RemoteAdministrationResult {
|
||||
if (!milestone) {
|
||||
return remoteAdministrationVerificationFailed(REMOTE_ADMINISTRATION_FAILURE_REASONS.MILESTONE_NOT_FOUND);
|
||||
}
|
||||
const observation = observeMilestone(replicator, milestone);
|
||||
return milestoneSatisfiesRemoteAdministration(request.action, observation)
|
||||
? remoteAdministrationVerified(observation)
|
||||
: remoteAdministrationVerificationFailed(REMOTE_ADMINISTRATION_FAILURE_REASONS.POSTCONDITION_MISMATCH, {
|
||||
observation,
|
||||
});
|
||||
}
|
||||
|
||||
async function runCouchDBRemoteAdministration(
|
||||
replicator: LiveSyncAbstractReplicator,
|
||||
setting: RemoteDBSettings,
|
||||
request: RemoteAdministrationRequest
|
||||
): Promise<RemoteAdministrationResult> {
|
||||
const identityFailure = await ensureLocalNodeIdentity(replicator);
|
||||
if (identityFailure) return identityFailure;
|
||||
|
||||
await applyRemoteAdministrationMutation(replicator, setting, request.action);
|
||||
|
||||
const couchDBReplicator = replicator as LiveSyncCouchDBReplicator;
|
||||
let connection;
|
||||
try {
|
||||
connection = await couchDBReplicator.connectRemoteCouchDBWithSetting(
|
||||
setting,
|
||||
couchDBReplicator.isMobile(),
|
||||
true
|
||||
);
|
||||
} catch (error) {
|
||||
return remoteAdministrationVerificationFailed(REMOTE_ADMINISTRATION_FAILURE_REASONS.CONNECTION_FAILED, {
|
||||
detail: error,
|
||||
});
|
||||
}
|
||||
if (typeof connection === "string") {
|
||||
return remoteAdministrationVerificationFailed(REMOTE_ADMINISTRATION_FAILURE_REASONS.CONNECTION_FAILED, {
|
||||
detail: connection,
|
||||
});
|
||||
}
|
||||
|
||||
let milestone: EntryMilestoneInfo | undefined;
|
||||
let observationError: unknown;
|
||||
try {
|
||||
milestone = await connection.db.get<EntryMilestoneInfo>(MILESTONE_DOCID);
|
||||
} catch (error) {
|
||||
observationError = error;
|
||||
}
|
||||
try {
|
||||
await connection.close();
|
||||
} catch (error) {
|
||||
observationError ??= error;
|
||||
}
|
||||
if (observationError !== undefined) {
|
||||
return remoteAdministrationVerificationFailed(REMOTE_ADMINISTRATION_FAILURE_REASONS.MILESTONE_READ_FAILED, {
|
||||
detail: observationError,
|
||||
});
|
||||
}
|
||||
return resultFromMilestone(replicator, request, milestone);
|
||||
}
|
||||
|
||||
async function runObjectStorageRemoteAdministration(
|
||||
replicator: LiveSyncAbstractReplicator,
|
||||
setting: RemoteDBSettings,
|
||||
request: RemoteAdministrationRequest
|
||||
): Promise<RemoteAdministrationResult> {
|
||||
const identityFailure = await ensureLocalNodeIdentity(replicator);
|
||||
if (identityFailure) return identityFailure;
|
||||
|
||||
await applyRemoteAdministrationMutation(replicator, setting, request.action);
|
||||
|
||||
const journalReplicator = replicator as LiveSyncJournalReplicator;
|
||||
let milestone: EntryMilestoneInfo | false | undefined;
|
||||
try {
|
||||
milestone = await journalReplicator.client.downloadJson<EntryMilestoneInfo>(JOURNAL_MILESTONE_PATH);
|
||||
} catch (error) {
|
||||
return remoteAdministrationVerificationFailed(REMOTE_ADMINISTRATION_FAILURE_REASONS.MILESTONE_READ_FAILED, {
|
||||
detail: error,
|
||||
});
|
||||
}
|
||||
return resultFromMilestone(replicator, request, milestone);
|
||||
}
|
||||
|
||||
/** CouchDB mutation and milestone postcondition verification capability. */
|
||||
export const COUCHDB_REMOTE_ADMINISTRATION_CAPABILITY: SupportedCapability<RemoteAdministrationRunner> =
|
||||
supportedCapability(runCouchDBRemoteAdministration);
|
||||
|
||||
/** Object Storage mutation and milestone postcondition verification capability. */
|
||||
export const OBJECT_STORAGE_REMOTE_ADMINISTRATION_CAPABILITY: SupportedCapability<RemoteAdministrationRunner> =
|
||||
supportedCapability(runObjectStorageRemoteAdministration);
|
||||
@@ -0,0 +1,158 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { DEFAULT_SETTINGS, REMOTE_COUCHDB, REMOTE_MINIO } from "@vrtmrz/livesync-commonlib/compat/common/types";
|
||||
import {
|
||||
REMOTE_ADMINISTRATION_ACTIONS,
|
||||
REMOTE_ADMINISTRATION_FAILURE_REASONS,
|
||||
REMOTE_ADMINISTRATION_OBSERVATION_KINDS,
|
||||
REMOTE_ADMINISTRATION_RESULT_STATUSES,
|
||||
} from "@vrtmrz/livesync-commonlib/replication";
|
||||
import {
|
||||
COUCHDB_REMOTE_ADMINISTRATION_CAPABILITY,
|
||||
OBJECT_STORAGE_REMOTE_ADMINISTRATION_CAPABILITY,
|
||||
} from "./replicatorAdministration";
|
||||
|
||||
describe("central remote administration capabilities", () => {
|
||||
it("mutates CouchDB, verifies the requested postcondition, and closes only the owned connection", async () => {
|
||||
const rawDatabaseClose = vi.fn(async () => undefined);
|
||||
const close = vi.fn(async () => undefined);
|
||||
const database = {
|
||||
get: vi.fn(async () => ({ locked: true, accepted_nodes: ["node-1"] })),
|
||||
close: rawDatabaseClose,
|
||||
};
|
||||
const replicator = {
|
||||
nodeid: "node-1",
|
||||
initializeDatabaseForReplication: vi.fn(async () => true),
|
||||
isMobile: vi.fn(() => false),
|
||||
markRemoteLocked: vi.fn(async () => undefined),
|
||||
markRemoteResolved: vi.fn(async () => undefined),
|
||||
connectRemoteCouchDBWithSetting: vi.fn(async () => ({ db: database, close })),
|
||||
};
|
||||
const setting = { ...DEFAULT_SETTINGS, remoteType: REMOTE_COUCHDB };
|
||||
const capability = COUCHDB_REMOTE_ADMINISTRATION_CAPABILITY;
|
||||
|
||||
await expect(
|
||||
capability.run(replicator as never, setting, { action: REMOTE_ADMINISTRATION_ACTIONS.LOCK })
|
||||
).resolves.toEqual({
|
||||
status: REMOTE_ADMINISTRATION_RESULT_STATUSES.VERIFIED,
|
||||
observation: {
|
||||
kind: REMOTE_ADMINISTRATION_OBSERVATION_KINDS.MILESTONE,
|
||||
locked: true,
|
||||
accepted: true,
|
||||
nodeId: "node-1",
|
||||
},
|
||||
});
|
||||
|
||||
expect(replicator.markRemoteLocked).toHaveBeenCalledWith(setting, true, false);
|
||||
expect(close).toHaveBeenCalledOnce();
|
||||
expect(rawDatabaseClose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns a typed CouchDB failure when the observed milestone does not satisfy the action", async () => {
|
||||
const close = vi.fn(async () => undefined);
|
||||
const replicator = {
|
||||
nodeid: "node-1",
|
||||
initializeDatabaseForReplication: vi.fn(async () => true),
|
||||
isMobile: vi.fn(() => false),
|
||||
markRemoteLocked: vi.fn(async () => undefined),
|
||||
markRemoteResolved: vi.fn(async () => undefined),
|
||||
connectRemoteCouchDBWithSetting: vi.fn(async () => ({
|
||||
db: { get: vi.fn(async () => ({ locked: false, accepted_nodes: ["node-1"] })) },
|
||||
close,
|
||||
})),
|
||||
};
|
||||
const capability = COUCHDB_REMOTE_ADMINISTRATION_CAPABILITY;
|
||||
|
||||
const result = await capability.run(
|
||||
replicator as never,
|
||||
{ ...DEFAULT_SETTINGS, remoteType: REMOTE_COUCHDB },
|
||||
{
|
||||
action: REMOTE_ADMINISTRATION_ACTIONS.LOCK,
|
||||
}
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: REMOTE_ADMINISTRATION_RESULT_STATUSES.VERIFICATION_FAILED,
|
||||
reason: REMOTE_ADMINISTRATION_FAILURE_REASONS.POSTCONDITION_MISMATCH,
|
||||
observation: { kind: REMOTE_ADMINISTRATION_OBSERVATION_KINDS.MILESTONE, locked: false },
|
||||
});
|
||||
expect(close).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("does not mutate when initialisation succeeds without publishing a local node identity", async () => {
|
||||
const replicator = {
|
||||
nodeid: "",
|
||||
initializeDatabaseForReplication: vi.fn(async () => true),
|
||||
isMobile: vi.fn(() => false),
|
||||
markRemoteLocked: vi.fn(async () => undefined),
|
||||
markRemoteResolved: vi.fn(async () => undefined),
|
||||
connectRemoteCouchDBWithSetting: vi.fn(async () => "must not connect"),
|
||||
};
|
||||
const capability = COUCHDB_REMOTE_ADMINISTRATION_CAPABILITY;
|
||||
|
||||
await expect(
|
||||
capability.run(
|
||||
replicator as never,
|
||||
{ ...DEFAULT_SETTINGS, remoteType: REMOTE_COUCHDB },
|
||||
{ action: REMOTE_ADMINISTRATION_ACTIONS.MARK_RESOLVED }
|
||||
)
|
||||
).resolves.toEqual({
|
||||
status: REMOTE_ADMINISTRATION_RESULT_STATUSES.VERIFICATION_FAILED,
|
||||
reason: REMOTE_ADMINISTRATION_FAILURE_REASONS.LOCAL_IDENTITY_UNAVAILABLE,
|
||||
});
|
||||
expect(replicator.markRemoteResolved).not.toHaveBeenCalled();
|
||||
expect(replicator.connectRemoteCouchDBWithSetting).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("allows a CouchDB mutation exception to reject before verification", async () => {
|
||||
const failure = new Error("write failed");
|
||||
const replicator = {
|
||||
nodeid: "node-1",
|
||||
initializeDatabaseForReplication: vi.fn(async () => true),
|
||||
isMobile: vi.fn(() => false),
|
||||
markRemoteLocked: vi.fn(async () => {
|
||||
throw failure;
|
||||
}),
|
||||
markRemoteResolved: vi.fn(async () => undefined),
|
||||
connectRemoteCouchDBWithSetting: vi.fn(),
|
||||
};
|
||||
const capability = COUCHDB_REMOTE_ADMINISTRATION_CAPABILITY;
|
||||
|
||||
await expect(
|
||||
capability.run(
|
||||
replicator as never,
|
||||
{ ...DEFAULT_SETTINGS, remoteType: REMOTE_COUCHDB },
|
||||
{
|
||||
action: REMOTE_ADMINISTRATION_ACTIONS.UNLOCK,
|
||||
}
|
||||
)
|
||||
).rejects.toBe(failure);
|
||||
expect(replicator.connectRemoteCouchDBWithSetting).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("mutates Object Storage and verifies its milestone postcondition", async () => {
|
||||
const downloadJson = vi.fn(async () => ({ locked: false, accepted_nodes: ["node-1"] }));
|
||||
const replicator = {
|
||||
nodeid: "node-1",
|
||||
initializeDatabaseForReplication: vi.fn(async () => true),
|
||||
markRemoteLocked: vi.fn(async () => undefined),
|
||||
markRemoteResolved: vi.fn(async () => undefined),
|
||||
client: { downloadJson },
|
||||
};
|
||||
const setting = { ...DEFAULT_SETTINGS, remoteType: REMOTE_MINIO };
|
||||
const capability = OBJECT_STORAGE_REMOTE_ADMINISTRATION_CAPABILITY;
|
||||
|
||||
await expect(
|
||||
capability.run(replicator as never, setting, { action: REMOTE_ADMINISTRATION_ACTIONS.MARK_RESOLVED })
|
||||
).resolves.toEqual({
|
||||
status: REMOTE_ADMINISTRATION_RESULT_STATUSES.VERIFIED,
|
||||
observation: {
|
||||
kind: REMOTE_ADMINISTRATION_OBSERVATION_KINDS.MILESTONE,
|
||||
locked: false,
|
||||
accepted: true,
|
||||
nodeId: "node-1",
|
||||
},
|
||||
});
|
||||
expect(replicator.markRemoteResolved).toHaveBeenCalledWith(setting);
|
||||
expect(downloadJson).toHaveBeenCalledWith("_00000000-milestone.json");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
import type { RemoteDBSettings } from "@vrtmrz/livesync-commonlib/compat/common/types";
|
||||
|
||||
type EndpointProjection = readonly [kind: "url" | "invalid-url", value: string];
|
||||
|
||||
function projectEndpoint(value: string): EndpointProjection {
|
||||
try {
|
||||
const endpoint = new URL(value);
|
||||
endpoint.hash = "";
|
||||
endpoint.searchParams.sort();
|
||||
while (endpoint.pathname.length > 1 && endpoint.pathname.endsWith("/")) {
|
||||
endpoint.pathname = endpoint.pathname.slice(0, -1);
|
||||
}
|
||||
return ["url", endpoint.toString()];
|
||||
} catch {
|
||||
return ["invalid-url", value];
|
||||
}
|
||||
}
|
||||
|
||||
function projectHeaders(value: string): readonly (readonly [name: string, value: string])[] {
|
||||
const headers = new Map<string, string>();
|
||||
for (const line of value.split("\n")) {
|
||||
const [name, headerValue] = line.split(":", 2).map((part) => part.trim());
|
||||
if (name && headerValue) {
|
||||
headers.set(name, headerValue);
|
||||
}
|
||||
}
|
||||
return [...headers.entries()].sort(([leftName, leftValue], [rightName, rightValue]) => {
|
||||
const nameOrder = leftName.localeCompare(rightName);
|
||||
return nameOrder || leftValue.localeCompare(rightValue);
|
||||
});
|
||||
}
|
||||
|
||||
function projectRemoteSecurity(settings: RemoteDBSettings) {
|
||||
return settings.encrypt
|
||||
? ([
|
||||
"encrypted",
|
||||
settings.passphrase,
|
||||
settings.useDynamicIterationCount,
|
||||
settings.E2EEAlgorithm,
|
||||
settings.permitEmptyPassphrase,
|
||||
] as const)
|
||||
: (["plain"] as const);
|
||||
}
|
||||
|
||||
/**
|
||||
* Project the effective CouchDB connection settings to a private comparison identity.
|
||||
* The returned value can contain credentials and must not be logged, persisted, or displayed.
|
||||
*/
|
||||
export function getCouchDBReplicatorConfigurationIdentity(settings: RemoteDBSettings): string {
|
||||
const authentication = settings.useJWT
|
||||
? ([
|
||||
"jwt",
|
||||
settings.jwtAlgorithm,
|
||||
settings.jwtKey,
|
||||
settings.jwtKid,
|
||||
settings.jwtSub,
|
||||
settings.jwtExpDuration,
|
||||
] as const)
|
||||
: (["basic", settings.couchDB_USER, settings.couchDB_PASSWORD] as const);
|
||||
return JSON.stringify([
|
||||
"couchdb",
|
||||
projectEndpoint(settings.couchDB_URI),
|
||||
settings.couchDB_DBNAME,
|
||||
authentication,
|
||||
projectHeaders(settings.couchDB_CustomHeaders),
|
||||
settings.useRequestAPI,
|
||||
settings.disableRequestURI,
|
||||
projectRemoteSecurity(settings),
|
||||
settings.enableCompression,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Project the effective Object Storage connection settings to a private comparison identity.
|
||||
* The returned value can contain credentials and must not be logged, persisted, or displayed.
|
||||
*/
|
||||
export function getObjectStorageReplicatorConfigurationIdentity(settings: RemoteDBSettings): string {
|
||||
return JSON.stringify([
|
||||
"s3",
|
||||
projectEndpoint(settings.endpoint),
|
||||
settings.bucket,
|
||||
settings.bucketPrefix,
|
||||
settings.region,
|
||||
settings.accessKey,
|
||||
settings.secretKey,
|
||||
settings.forcePathStyle,
|
||||
settings.useCustomRequestHandler,
|
||||
projectHeaders(settings.bucketCustomHeaders),
|
||||
projectRemoteSecurity(settings),
|
||||
]);
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { ObsidianLiveSyncSettings } from "@vrtmrz/livesync-commonlib/compat/common/types";
|
||||
import { createNewVaultSettings } from "@vrtmrz/livesync-commonlib/settings";
|
||||
import {
|
||||
getCouchDBReplicatorConfigurationIdentity,
|
||||
getObjectStorageReplicatorConfigurationIdentity,
|
||||
} from "./replicatorConfigurationIdentity";
|
||||
|
||||
describe("active Replicator configuration identity", () => {
|
||||
function configuredSettings(overrides: Partial<ObsidianLiveSyncSettings> = {}): ObsidianLiveSyncSettings {
|
||||
return Object.assign(createNewVaultSettings(), {
|
||||
activeConfigurationId: "profile-a",
|
||||
couchDB_URI: "https://couch.example.test/base",
|
||||
couchDB_USER: "alice",
|
||||
couchDB_PASSWORD: "secret-a",
|
||||
couchDB_DBNAME: "vault",
|
||||
couchDB_CustomHeaders: "X-Second: two\nX-First: one",
|
||||
endpoint: "https://objects.example.test/base",
|
||||
accessKey: "alice",
|
||||
secretKey: "secret-a",
|
||||
bucket: "vault",
|
||||
bucketPrefix: "notes/",
|
||||
region: "auto",
|
||||
bucketCustomHeaders: "X-Second: two\nX-First: one",
|
||||
encrypt: true,
|
||||
passphrase: "encryption-a",
|
||||
useDynamicIterationCount: false,
|
||||
permitEmptyPassphrase: false,
|
||||
enableCompression: false,
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
it.each([
|
||||
["couchDB_URI", "https://other.example.test/base"],
|
||||
["couchDB_DBNAME", "other-vault"],
|
||||
["couchDB_USER", "bob"],
|
||||
["couchDB_PASSWORD", "secret-b"],
|
||||
["couchDB_CustomHeaders", "X-First: changed"],
|
||||
["useRequestAPI", true],
|
||||
["disableRequestURI", true],
|
||||
["encrypt", false],
|
||||
["passphrase", "encryption-b"],
|
||||
["useDynamicIterationCount", true],
|
||||
["E2EEAlgorithm", ""],
|
||||
["permitEmptyPassphrase", true],
|
||||
["enableCompression", true],
|
||||
] satisfies Array<[keyof ObsidianLiveSyncSettings, ObsidianLiveSyncSettings[keyof ObsidianLiveSyncSettings]]>)(
|
||||
"detects a CouchDB %s change",
|
||||
(key, value) => {
|
||||
const settings = configuredSettings();
|
||||
expect(getCouchDBReplicatorConfigurationIdentity({ ...settings, [key]: value })).not.toBe(
|
||||
getCouchDBReplicatorConfigurationIdentity(settings)
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
it("ignores persisted central profile identity when the effective connection settings match", () => {
|
||||
const settings = configuredSettings({ activeConfigurationId: "profile-a" });
|
||||
const otherProfile = { ...settings, activeConfigurationId: "profile-b" };
|
||||
|
||||
expect(getCouchDBReplicatorConfigurationIdentity(otherProfile)).toBe(
|
||||
getCouchDBReplicatorConfigurationIdentity(settings)
|
||||
);
|
||||
expect(getObjectStorageReplicatorConfigurationIdentity(otherProfile)).toBe(
|
||||
getObjectStorageReplicatorConfigurationIdentity(settings)
|
||||
);
|
||||
});
|
||||
|
||||
it("projects only the active CouchDB authentication mode", () => {
|
||||
const basic = configuredSettings({ useJWT: false, jwtKey: "inactive-a" });
|
||||
expect(getCouchDBReplicatorConfigurationIdentity({ ...basic, jwtKey: "inactive-b" })).toBe(
|
||||
getCouchDBReplicatorConfigurationIdentity(basic)
|
||||
);
|
||||
|
||||
const jwt = configuredSettings({
|
||||
useJWT: true,
|
||||
jwtAlgorithm: "HS256",
|
||||
jwtKey: "jwt-a",
|
||||
jwtKid: "kid-a",
|
||||
jwtSub: "subject-a",
|
||||
jwtExpDuration: 5,
|
||||
});
|
||||
expect(getCouchDBReplicatorConfigurationIdentity({ ...jwt, couchDB_PASSWORD: "inactive" })).toBe(
|
||||
getCouchDBReplicatorConfigurationIdentity(jwt)
|
||||
);
|
||||
expect(getCouchDBReplicatorConfigurationIdentity({ ...jwt, jwtKey: "jwt-b" })).not.toBe(
|
||||
getCouchDBReplicatorConfigurationIdentity(jwt)
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["endpoint", "https://other.example.test/base"],
|
||||
["bucket", "other-vault"],
|
||||
["bucketPrefix", "archive/"],
|
||||
["region", "eu-west-1"],
|
||||
["accessKey", "bob"],
|
||||
["secretKey", "secret-b"],
|
||||
["forcePathStyle", false],
|
||||
["useCustomRequestHandler", true],
|
||||
["bucketCustomHeaders", "X-First: changed"],
|
||||
["encrypt", false],
|
||||
["passphrase", "encryption-b"],
|
||||
["useDynamicIterationCount", true],
|
||||
["E2EEAlgorithm", ""],
|
||||
["permitEmptyPassphrase", true],
|
||||
] satisfies Array<[keyof ObsidianLiveSyncSettings, ObsidianLiveSyncSettings[keyof ObsidianLiveSyncSettings]]>)(
|
||||
"detects an Object Storage %s change",
|
||||
(key, value) => {
|
||||
const settings = configuredSettings();
|
||||
expect(getObjectStorageReplicatorConfigurationIdentity({ ...settings, [key]: value })).not.toBe(
|
||||
getObjectStorageReplicatorConfigurationIdentity(settings)
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
it("normalises endpoint and header representation without using the setup URI grammar", () => {
|
||||
const settings = configuredSettings();
|
||||
const couchIdentity = getCouchDBReplicatorConfigurationIdentity(settings);
|
||||
const objectStorageIdentity = getObjectStorageReplicatorConfigurationIdentity(settings);
|
||||
|
||||
expect(
|
||||
getCouchDBReplicatorConfigurationIdentity({
|
||||
...settings,
|
||||
couchDB_URI: "https://couch.example.test:443/base/",
|
||||
couchDB_CustomHeaders: "X-First: one\nX-Second: two",
|
||||
})
|
||||
).toBe(couchIdentity);
|
||||
expect(
|
||||
getObjectStorageReplicatorConfigurationIdentity({
|
||||
...settings,
|
||||
endpoint: "https://objects.example.test:443/base/",
|
||||
bucketCustomHeaders: "X-First: one\nX-Second: two",
|
||||
})
|
||||
).toBe(objectStorageIdentity);
|
||||
});
|
||||
|
||||
it("ignores inactive remote-security credentials", () => {
|
||||
const settings = configuredSettings({ encrypt: false, passphrase: "inactive-a" });
|
||||
|
||||
expect(
|
||||
getCouchDBReplicatorConfigurationIdentity({
|
||||
...settings,
|
||||
passphrase: "inactive-b",
|
||||
useDynamicIterationCount: !settings.useDynamicIterationCount,
|
||||
E2EEAlgorithm: "",
|
||||
permitEmptyPassphrase: !settings.permitEmptyPassphrase,
|
||||
})
|
||||
).toBe(getCouchDBReplicatorConfigurationIdentity(settings));
|
||||
expect(
|
||||
getObjectStorageReplicatorConfigurationIdentity({
|
||||
...settings,
|
||||
passphrase: "inactive-b",
|
||||
useDynamicIterationCount: !settings.useDynamicIterationCount,
|
||||
E2EEAlgorithm: "",
|
||||
permitEmptyPassphrase: !settings.permitEmptyPassphrase,
|
||||
})
|
||||
).toBe(getObjectStorageReplicatorConfigurationIdentity(settings));
|
||||
});
|
||||
|
||||
it("keeps malformed endpoints deterministic and scoped", () => {
|
||||
const settings = configuredSettings({ couchDB_URI: "not a URL", endpoint: "also not a URL" });
|
||||
|
||||
expect(() => getCouchDBReplicatorConfigurationIdentity(settings)).not.toThrow();
|
||||
expect(() => getObjectStorageReplicatorConfigurationIdentity(settings)).not.toThrow();
|
||||
expect(
|
||||
getCouchDBReplicatorConfigurationIdentity({ ...settings, couchDB_URI: "different invalid URL" })
|
||||
).not.toBe(getCouchDBReplicatorConfigurationIdentity(settings));
|
||||
const unrelatedPluginChange = { ...settings, displayLanguage: "ja" };
|
||||
expect(getObjectStorageReplicatorConfigurationIdentity(unrelatedPluginChange)).toBe(
|
||||
getObjectStorageReplicatorConfigurationIdentity(settings)
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
import { REMOTE_COUCHDB, REMOTE_MINIO } from "@vrtmrz/livesync-commonlib/compat/common/types";
|
||||
import {
|
||||
CAPABILITY_NOT_APPLICABLE,
|
||||
CENTRAL_REMOTE_REPLICATION_READINESS,
|
||||
REMOTE_RESOURCE_KINDS,
|
||||
REPLACE_SAME_KIND_REPLICATOR,
|
||||
defineReplicatorProviderDefinitions,
|
||||
supportedOpenReplicationContinuous,
|
||||
supportedOpenReplicationOneShot,
|
||||
supportedOpenReplicationUnattended,
|
||||
supportedStopActiveTransfer,
|
||||
supportedCapability,
|
||||
type ReplicatorProviderDefinitionMap,
|
||||
} from "@vrtmrz/livesync-commonlib/replication";
|
||||
import {
|
||||
LiveSyncCouchDBReplicator,
|
||||
type LiveSyncCouchDBReplicatorEnv,
|
||||
} from "@vrtmrz/livesync-commonlib/compat/replication/couchdb/LiveSyncReplicator";
|
||||
import { LiveSyncJournalReplicator } from "@vrtmrz/livesync-commonlib/compat/replication/journal/LiveSyncJournalReplicator";
|
||||
import type { LiveSyncJournalReplicatorEnv } from "@vrtmrz/livesync-commonlib/compat/replication/journal/LiveSyncJournalReplicatorEnv";
|
||||
import {
|
||||
getCouchDBReplicatorConfigurationIdentity,
|
||||
getObjectStorageReplicatorConfigurationIdentity,
|
||||
} from "./replicatorConfigurationIdentity";
|
||||
import {
|
||||
createCouchDBConnectionProbeFactory,
|
||||
createCouchDBPreferredTweakProbeFactory,
|
||||
createCouchDBSecuritySeedResourceFactory,
|
||||
createCouchDBSynchronisationInformationResourceFactory,
|
||||
createObjectStorageConnectionProbeFactory,
|
||||
createObjectStoragePreferredTweakProbeFactory,
|
||||
createObjectStorageSecuritySeedResourceFactory,
|
||||
} from "./replicatorResources";
|
||||
import {
|
||||
COUCHDB_REMOTE_ADMINISTRATION_CAPABILITY,
|
||||
OBJECT_STORAGE_REMOTE_ADMINISTRATION_CAPABILITY,
|
||||
} from "./replicatorAdministration";
|
||||
|
||||
export type CentralReplicatorProviderHost = LiveSyncCouchDBReplicatorEnv & LiveSyncJournalReplicatorEnv;
|
||||
|
||||
/** Build the complete central-remote provider policy for one LiveSync host. */
|
||||
export function createCentralReplicatorProviderDefinitions(
|
||||
host: CentralReplicatorProviderHost
|
||||
): ReplicatorProviderDefinitionMap {
|
||||
return defineReplicatorProviderDefinitions([REMOTE_COUCHDB, REMOTE_MINIO] as const, {
|
||||
[REMOTE_COUCHDB]: {
|
||||
kind: REMOTE_COUCHDB,
|
||||
diagnosticName: "CouchDB",
|
||||
readiness: CENTRAL_REMOTE_REPLICATION_READINESS,
|
||||
isConfigured: (settings) =>
|
||||
settings.remoteType === REMOTE_COUCHDB &&
|
||||
!!settings.couchDB_URI?.trim() &&
|
||||
!!settings.couchDB_DBNAME?.trim(),
|
||||
configurationIdentity: getCouchDBReplicatorConfigurationIdentity,
|
||||
sameKindReconciliation: REPLACE_SAME_KIND_REPLICATOR,
|
||||
create: () => Promise.resolve(new LiveSyncCouchDBReplicator(host)),
|
||||
remoteResources: {
|
||||
[REMOTE_RESOURCE_KINDS.CONNECTION]: supportedCapability(createCouchDBConnectionProbeFactory(host)),
|
||||
[REMOTE_RESOURCE_KINDS.PREFERRED_TWEAK]: supportedCapability(
|
||||
createCouchDBPreferredTweakProbeFactory(host)
|
||||
),
|
||||
[REMOTE_RESOURCE_KINDS.SECURITY_SEED]: supportedCapability(
|
||||
createCouchDBSecuritySeedResourceFactory(host)
|
||||
),
|
||||
[REMOTE_RESOURCE_KINDS.SYNCHRONISATION_INFORMATION]: supportedCapability(
|
||||
createCouchDBSynchronisationInformationResourceFactory(host)
|
||||
),
|
||||
},
|
||||
remoteAdministration: COUCHDB_REMOTE_ADMINISTRATION_CAPABILITY,
|
||||
userInitiatedOneShot: supportedOpenReplicationOneShot(),
|
||||
unattendedOneShot: supportedOpenReplicationUnattended(),
|
||||
continuous: supportedOpenReplicationContinuous(),
|
||||
stopActiveTransfer: supportedStopActiveTransfer(),
|
||||
},
|
||||
[REMOTE_MINIO]: {
|
||||
kind: REMOTE_MINIO,
|
||||
diagnosticName: "Object Storage",
|
||||
readiness: CENTRAL_REMOTE_REPLICATION_READINESS,
|
||||
isConfigured: (settings) =>
|
||||
settings.remoteType === REMOTE_MINIO && !!settings.endpoint?.trim() && !!settings.bucket?.trim(),
|
||||
configurationIdentity: getObjectStorageReplicatorConfigurationIdentity,
|
||||
sameKindReconciliation: REPLACE_SAME_KIND_REPLICATOR,
|
||||
create: () => Promise.resolve(new LiveSyncJournalReplicator(host)),
|
||||
remoteResources: {
|
||||
[REMOTE_RESOURCE_KINDS.CONNECTION]: supportedCapability(
|
||||
createObjectStorageConnectionProbeFactory(host)
|
||||
),
|
||||
[REMOTE_RESOURCE_KINDS.PREFERRED_TWEAK]: supportedCapability(
|
||||
createObjectStoragePreferredTweakProbeFactory(host)
|
||||
),
|
||||
[REMOTE_RESOURCE_KINDS.SECURITY_SEED]: supportedCapability(
|
||||
createObjectStorageSecuritySeedResourceFactory(host)
|
||||
),
|
||||
[REMOTE_RESOURCE_KINDS.SYNCHRONISATION_INFORMATION]: CAPABILITY_NOT_APPLICABLE,
|
||||
},
|
||||
remoteAdministration: OBJECT_STORAGE_REMOTE_ADMINISTRATION_CAPABILITY,
|
||||
userInitiatedOneShot: supportedOpenReplicationOneShot(),
|
||||
unattendedOneShot: supportedOpenReplicationUnattended(),
|
||||
continuous: CAPABILITY_NOT_APPLICABLE,
|
||||
stopActiveTransfer: supportedStopActiveTransfer(),
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { REMOTE_COUCHDB, REMOTE_MINIO } from "@vrtmrz/livesync-commonlib/compat/common/types";
|
||||
import { createNewVaultSettings } from "@vrtmrz/livesync-commonlib/settings";
|
||||
import {
|
||||
CAPABILITY_SUPPORT_KINDS,
|
||||
REMOTE_RESOURCE_KINDS,
|
||||
REPLACE_SAME_KIND_REPLICATOR,
|
||||
} from "@vrtmrz/livesync-commonlib/replication";
|
||||
|
||||
const constructorMocks = vi.hoisted(() => ({
|
||||
couchDB: vi.fn(),
|
||||
objectStorage: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@vrtmrz/livesync-commonlib/compat/replication/couchdb/LiveSyncReplicator", () => ({
|
||||
LiveSyncCouchDBReplicator: class {
|
||||
constructor(host: unknown) {
|
||||
constructorMocks.couchDB(host);
|
||||
}
|
||||
},
|
||||
}));
|
||||
vi.mock("@vrtmrz/livesync-commonlib/compat/replication/journal/LiveSyncJournalReplicator", () => ({
|
||||
LiveSyncJournalReplicator: class {
|
||||
constructor(host: unknown) {
|
||||
constructorMocks.objectStorage(host);
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
import { createCentralReplicatorProviderDefinitions } from "./replicatorProviders";
|
||||
|
||||
describe("central Replicator provider definitions", () => {
|
||||
it("composes CouchDB and Object Storage policies outside LiveSyncBaseCore", async () => {
|
||||
const host = {} as Parameters<typeof createCentralReplicatorProviderDefinitions>[0];
|
||||
const definitions = createCentralReplicatorProviderDefinitions(host);
|
||||
const couchDB = definitions.get(REMOTE_COUCHDB)!;
|
||||
const objectStorage = definitions.get(REMOTE_MINIO)!;
|
||||
|
||||
expect([...definitions.keys()]).toEqual([REMOTE_COUCHDB, REMOTE_MINIO]);
|
||||
expect(couchDB.sameKindReconciliation).toBe(REPLACE_SAME_KIND_REPLICATOR);
|
||||
expect(objectStorage.sameKindReconciliation).toBe(REPLACE_SAME_KIND_REPLICATOR);
|
||||
|
||||
expect(
|
||||
couchDB.isConfigured(
|
||||
Object.assign(createNewVaultSettings(), {
|
||||
remoteType: REMOTE_COUCHDB,
|
||||
couchDB_URI: "https://couch.example.test",
|
||||
couchDB_DBNAME: "vault",
|
||||
})
|
||||
)
|
||||
).toBe(true);
|
||||
expect(
|
||||
objectStorage.isConfigured(
|
||||
Object.assign(createNewVaultSettings(), {
|
||||
remoteType: REMOTE_MINIO,
|
||||
endpoint: "https://objects.example.test",
|
||||
bucket: "vault",
|
||||
})
|
||||
)
|
||||
).toBe(true);
|
||||
|
||||
await couchDB.create(createNewVaultSettings());
|
||||
await objectStorage.create(createNewVaultSettings());
|
||||
expect(constructorMocks.couchDB).toHaveBeenCalledWith(host);
|
||||
expect(constructorMocks.objectStorage).toHaveBeenCalledWith(host);
|
||||
});
|
||||
|
||||
it("rejects incomplete and wrong-kind settings before construction", () => {
|
||||
const definitions = createCentralReplicatorProviderDefinitions({} as never);
|
||||
const couchDB = definitions.get(REMOTE_COUCHDB)!;
|
||||
const objectStorage = definitions.get(REMOTE_MINIO)!;
|
||||
|
||||
expect(couchDB.isConfigured(Object.assign(createNewVaultSettings(), { remoteType: REMOTE_MINIO }))).toBe(false);
|
||||
expect(
|
||||
objectStorage.isConfigured(Object.assign(createNewVaultSettings(), { remoteType: REMOTE_COUCHDB }))
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("declares an exhaustive resource and administration catalogue for both central providers", () => {
|
||||
const definitions = createCentralReplicatorProviderDefinitions({} as never);
|
||||
const couchResources = definitions.get(REMOTE_COUCHDB)?.remoteResources;
|
||||
const objectResources = definitions.get(REMOTE_MINIO)?.remoteResources;
|
||||
|
||||
expect(Object.keys(couchResources ?? {}).sort()).toEqual(Object.values(REMOTE_RESOURCE_KINDS).sort());
|
||||
expect(Object.keys(objectResources ?? {}).sort()).toEqual(Object.values(REMOTE_RESOURCE_KINDS).sort());
|
||||
expect(couchResources?.[REMOTE_RESOURCE_KINDS.CONNECTION].kind).toBe(CAPABILITY_SUPPORT_KINDS.SUPPORTED);
|
||||
expect(couchResources?.[REMOTE_RESOURCE_KINDS.PREFERRED_TWEAK].kind).toBe(CAPABILITY_SUPPORT_KINDS.SUPPORTED);
|
||||
expect(couchResources?.[REMOTE_RESOURCE_KINDS.SECURITY_SEED].kind).toBe(CAPABILITY_SUPPORT_KINDS.SUPPORTED);
|
||||
expect(couchResources?.[REMOTE_RESOURCE_KINDS.SYNCHRONISATION_INFORMATION].kind).toBe(
|
||||
CAPABILITY_SUPPORT_KINDS.SUPPORTED
|
||||
);
|
||||
expect(objectResources?.[REMOTE_RESOURCE_KINDS.SECURITY_SEED].kind).toBe(CAPABILITY_SUPPORT_KINDS.SUPPORTED);
|
||||
expect(objectResources?.[REMOTE_RESOURCE_KINDS.SYNCHRONISATION_INFORMATION].kind).toBe(
|
||||
CAPABILITY_SUPPORT_KINDS.NOT_APPLICABLE
|
||||
);
|
||||
expect(definitions.get(REMOTE_COUCHDB)?.remoteAdministration.kind).toBe(CAPABILITY_SUPPORT_KINDS.SUPPORTED);
|
||||
expect(definitions.get(REMOTE_MINIO)?.remoteAdministration.kind).toBe(CAPABILITY_SUPPORT_KINDS.SUPPORTED);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,271 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { REMOTE_COUCHDB, REMOTE_MINIO } from "@vrtmrz/livesync-commonlib/compat/common/types";
|
||||
import type { ObsidianLiveSyncSettings } from "@vrtmrz/livesync-commonlib/compat/common/types";
|
||||
import { createNewVaultSettings } from "@vrtmrz/livesync-commonlib/settings";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
couchDB: [] as Array<{
|
||||
host: unknown;
|
||||
isMobile: ReturnType<typeof vi.fn>;
|
||||
connectRemoteCouchDBWithSetting: ReturnType<typeof vi.fn>;
|
||||
getRemoteStatus: ReturnType<typeof vi.fn>;
|
||||
getRemotePreferredTweakValues: ReturnType<typeof vi.fn>;
|
||||
getReplicationPBKDF2Salt: ReturnType<typeof vi.fn>;
|
||||
closeReplication: ReturnType<typeof vi.fn>;
|
||||
}>,
|
||||
objectStorage: [] as Array<{
|
||||
host: unknown;
|
||||
tryConnectRemote: ReturnType<typeof vi.fn>;
|
||||
getRemoteStatus: ReturnType<typeof vi.fn>;
|
||||
getRemotePreferredTweakValues: ReturnType<typeof vi.fn>;
|
||||
getReplicationPBKDF2Salt: ReturnType<typeof vi.fn>;
|
||||
closeReplication: ReturnType<typeof vi.fn>;
|
||||
}>,
|
||||
checkSyncInfo: vi.fn(async () => true),
|
||||
}));
|
||||
|
||||
vi.mock("@vrtmrz/livesync-commonlib/compat/pouchdb/negotiation", () => ({
|
||||
checkSyncInfo: mocks.checkSyncInfo,
|
||||
}));
|
||||
|
||||
vi.mock("@vrtmrz/livesync-commonlib/compat/replication/couchdb/LiveSyncReplicator", () => ({
|
||||
LiveSyncCouchDBReplicator: class {
|
||||
host: unknown;
|
||||
isMobile = vi.fn(() => false);
|
||||
connectRemoteCouchDBWithSetting = vi.fn();
|
||||
getRemoteStatus = vi.fn();
|
||||
getRemotePreferredTweakValues = vi.fn();
|
||||
getReplicationPBKDF2Salt = vi.fn();
|
||||
closeReplication = vi.fn();
|
||||
|
||||
constructor(host: unknown) {
|
||||
this.host = host;
|
||||
mocks.couchDB.push(this);
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@vrtmrz/livesync-commonlib/compat/replication/journal/LiveSyncJournalReplicator", () => ({
|
||||
LiveSyncJournalReplicator: class {
|
||||
host: unknown;
|
||||
tryConnectRemote = vi.fn();
|
||||
getRemoteStatus = vi.fn();
|
||||
getRemotePreferredTweakValues = vi.fn();
|
||||
getReplicationPBKDF2Salt = vi.fn();
|
||||
closeReplication = vi.fn();
|
||||
|
||||
constructor(host: unknown) {
|
||||
this.host = host;
|
||||
mocks.objectStorage.push(this);
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
import {
|
||||
createCouchDBConnectionProbeFactory,
|
||||
createCouchDBPreferredTweakProbeFactory,
|
||||
createCouchDBSecuritySeedResourceFactory,
|
||||
createCouchDBSynchronisationInformationResourceFactory,
|
||||
createObjectStorageConnectionProbeFactory,
|
||||
createObjectStoragePreferredTweakProbeFactory,
|
||||
createObjectStorageSecuritySeedResourceFactory,
|
||||
} from "./replicatorResources";
|
||||
|
||||
function createSettings(overrides: Partial<ObsidianLiveSyncSettings> = {}): ObsidianLiveSyncSettings {
|
||||
return Object.assign(createNewVaultSettings(), {
|
||||
remoteType: REMOTE_COUCHDB,
|
||||
couchDB_URI: "https://couch.example.test",
|
||||
couchDB_DBNAME: "vault",
|
||||
endpoint: "https://objects.example.test",
|
||||
bucket: "vault",
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
describe("replicator probe factories", () => {
|
||||
beforeEach(() => {
|
||||
mocks.couchDB.length = 0;
|
||||
mocks.objectStorage.length = 0;
|
||||
mocks.checkSyncInfo.mockReset().mockResolvedValue(true);
|
||||
});
|
||||
|
||||
it("binds a CouchDB connection probe to a shallow settings snapshot and closes its owned connection", async () => {
|
||||
const host = { name: "host" };
|
||||
const source = createSettings();
|
||||
const snapshot = { ...source };
|
||||
const probe = await createCouchDBConnectionProbeFactory(host as never)(source);
|
||||
const replicator = mocks.couchDB[0];
|
||||
const close = vi.fn(async () => undefined);
|
||||
const databaseClose = vi.fn(async () => undefined);
|
||||
replicator.isMobile.mockReturnValue(true);
|
||||
replicator.connectRemoteCouchDBWithSetting.mockResolvedValue({
|
||||
db: { close: databaseClose },
|
||||
info: {},
|
||||
close,
|
||||
});
|
||||
|
||||
source.couchDB_URI = "https://changed.example.test";
|
||||
expect(await probe.check({ createIfMissing: false, showResult: true })).toEqual({ ok: true });
|
||||
|
||||
expect(replicator.connectRemoteCouchDBWithSetting).toHaveBeenCalledWith(snapshot, true, false, false);
|
||||
expect(replicator.connectRemoteCouchDBWithSetting.mock.calls[0][0]).not.toBe(source);
|
||||
expect(close).toHaveBeenCalledOnce();
|
||||
expect(databaseClose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("maps a CouchDB connection error string and delegates status to the same snapshot", async () => {
|
||||
const source = createSettings();
|
||||
const snapshot = { ...source };
|
||||
const probe = await createCouchDBConnectionProbeFactory({} as never)(source);
|
||||
const replicator = mocks.couchDB[0];
|
||||
replicator.connectRemoteCouchDBWithSetting.mockResolvedValue("connection failed");
|
||||
|
||||
expect(await probe.check()).toEqual({ ok: false, reason: "connection failed" });
|
||||
|
||||
const status = { estimatedSize: 12 };
|
||||
replicator.getRemoteStatus.mockResolvedValue(status);
|
||||
source.couchDB_DBNAME = "changed-vault";
|
||||
expect(await probe.getStatus()).toBe(status);
|
||||
expect(replicator.getRemoteStatus).toHaveBeenCalledWith(snapshot);
|
||||
});
|
||||
|
||||
it("creates an unpublished Object Storage replicator for each probe and normalises connection results", async () => {
|
||||
const host = { name: "host" };
|
||||
const source = createSettings({ remoteType: REMOTE_MINIO });
|
||||
const snapshot = { ...source };
|
||||
const factory = createObjectStorageConnectionProbeFactory(host as never);
|
||||
const firstProbe = await factory(source);
|
||||
const secondProbe = await factory(source);
|
||||
expect(mocks.objectStorage).toHaveLength(2);
|
||||
|
||||
const firstReplicator = mocks.objectStorage[0];
|
||||
firstReplicator.tryConnectRemote.mockResolvedValue(true);
|
||||
source.endpoint = "https://changed.example.test";
|
||||
expect(await firstProbe.check()).toEqual({ ok: true });
|
||||
expect(firstReplicator.tryConnectRemote).toHaveBeenCalledWith(snapshot, false);
|
||||
|
||||
const secondReplicator = mocks.objectStorage[1];
|
||||
secondReplicator.tryConnectRemote.mockResolvedValue(false);
|
||||
expect(await secondProbe.check({ showResult: true })).toEqual({ ok: false });
|
||||
expect(secondReplicator.tryConnectRemote).toHaveBeenCalledWith(snapshot, true);
|
||||
|
||||
const error = new Error("storage offline");
|
||||
secondReplicator.tryConnectRemote.mockRejectedValue(error);
|
||||
expect(await secondProbe.check()).toEqual({ ok: false, reason: error });
|
||||
});
|
||||
|
||||
it("delegates Object Storage status and preferred-tweak reads to the trial snapshot", async () => {
|
||||
const source = createSettings({ remoteType: REMOTE_MINIO });
|
||||
const snapshot = { ...source };
|
||||
const connectionProbe = await createObjectStorageConnectionProbeFactory({} as never)(source);
|
||||
const preferredProbe = await createObjectStoragePreferredTweakProbeFactory({} as never)(source);
|
||||
const connectionReplicator = mocks.objectStorage[0];
|
||||
const preferredReplicator = mocks.objectStorage[1];
|
||||
const status = { estimatedSize: 42 };
|
||||
const preferred = { status: "unsupported" } as const;
|
||||
connectionReplicator.getRemoteStatus.mockResolvedValue(status);
|
||||
preferredReplicator.getRemotePreferredTweakValues.mockResolvedValue(preferred);
|
||||
|
||||
source.bucket = "changed-vault";
|
||||
expect(await connectionProbe.getStatus()).toBe(status);
|
||||
expect(await preferredProbe.read()).toBe(preferred);
|
||||
expect(connectionReplicator.getRemoteStatus).toHaveBeenCalledWith(snapshot);
|
||||
expect(preferredReplicator.getRemotePreferredTweakValues).toHaveBeenCalledWith(snapshot);
|
||||
});
|
||||
|
||||
it("shares one successful asynchronous disposal promise for every probe kind", async () => {
|
||||
const couchProbe = await createCouchDBPreferredTweakProbeFactory({} as never)(createSettings());
|
||||
const objectProbe = await createObjectStoragePreferredTweakProbeFactory({} as never)(
|
||||
createSettings({ remoteType: REMOTE_MINIO })
|
||||
);
|
||||
const couchReplicator = mocks.couchDB[0];
|
||||
const objectReplicator = mocks.objectStorage[0];
|
||||
|
||||
const couchDisposal = couchProbe.dispose();
|
||||
expect(couchProbe.dispose()).toBe(couchDisposal);
|
||||
const objectDisposal = objectProbe.dispose();
|
||||
expect(objectProbe.dispose()).toBe(objectDisposal);
|
||||
await Promise.all([couchDisposal, objectDisposal]);
|
||||
expect(couchReplicator.closeReplication).toHaveBeenCalledOnce();
|
||||
expect(objectReplicator.closeReplication).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("shares a rejected disposal promise and never retries closeReplication", async () => {
|
||||
const probe = await createObjectStorageConnectionProbeFactory({} as never)(
|
||||
createSettings({ remoteType: REMOTE_MINIO })
|
||||
);
|
||||
const replicator = mocks.objectStorage[0];
|
||||
const failure = new Error("close failed");
|
||||
replicator.closeReplication.mockImplementation(() => {
|
||||
throw failure;
|
||||
});
|
||||
|
||||
const disposal = probe.dispose();
|
||||
expect(probe.dispose()).toBe(disposal);
|
||||
await expect(disposal).rejects.toBe(failure);
|
||||
expect(replicator.closeReplication).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("reads the Security Seed from a settings snapshot and disposes its private Replicator", async () => {
|
||||
const couchSettings = createSettings();
|
||||
const couchSnapshot = { ...couchSettings };
|
||||
const objectSettings = createSettings({ remoteType: REMOTE_MINIO });
|
||||
const objectSnapshot = { ...objectSettings };
|
||||
const couchResource = await createCouchDBSecuritySeedResourceFactory({} as never)(couchSettings);
|
||||
const objectResource = await createObjectStorageSecuritySeedResourceFactory({} as never)(objectSettings);
|
||||
const couchReplicator = mocks.couchDB[0];
|
||||
const objectReplicator = mocks.objectStorage[0];
|
||||
const couchSeed = new Uint8Array([1]);
|
||||
const objectSeed = new Uint8Array([2]);
|
||||
couchReplicator.getReplicationPBKDF2Salt.mockResolvedValue(couchSeed);
|
||||
objectReplicator.getReplicationPBKDF2Salt.mockResolvedValue(objectSeed);
|
||||
|
||||
couchSettings.couchDB_URI = "https://changed.example.test";
|
||||
objectSettings.endpoint = "https://changed.example.test";
|
||||
await expect(couchResource.read()).resolves.toBe(couchSeed);
|
||||
await expect(objectResource.read()).resolves.toBe(objectSeed);
|
||||
expect(couchReplicator.getReplicationPBKDF2Salt).toHaveBeenCalledWith(couchSnapshot);
|
||||
expect(objectReplicator.getReplicationPBKDF2Salt).toHaveBeenCalledWith(objectSnapshot);
|
||||
|
||||
await Promise.all([couchResource.dispose(), objectResource.dispose()]);
|
||||
expect(couchReplicator.closeReplication).toHaveBeenCalledOnce();
|
||||
expect(objectReplicator.closeReplication).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("checks synchronisation information through an owned connection and disposes the private Replicator", async () => {
|
||||
const settings = createSettings();
|
||||
const snapshot = { ...settings };
|
||||
const resource = await createCouchDBSynchronisationInformationResourceFactory({} as never)(settings);
|
||||
const replicator = mocks.couchDB[0];
|
||||
const database = { close: vi.fn() };
|
||||
const close = vi.fn(async () => undefined);
|
||||
replicator.connectRemoteCouchDBWithSetting.mockResolvedValue({ db: database, close });
|
||||
|
||||
settings.couchDB_DBNAME = "changed-vault";
|
||||
await expect(resource.check()).resolves.toBe(true);
|
||||
expect(replicator.connectRemoteCouchDBWithSetting).toHaveBeenCalledWith(snapshot, false, true);
|
||||
expect(mocks.checkSyncInfo).toHaveBeenCalledWith(database);
|
||||
expect(close).toHaveBeenCalledOnce();
|
||||
expect(database.close).not.toHaveBeenCalled();
|
||||
|
||||
await resource.dispose();
|
||||
expect(replicator.closeReplication).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("closes the owned connection when synchronisation-information verification rejects", async () => {
|
||||
const resource = await createCouchDBSynchronisationInformationResourceFactory({} as never)(createSettings());
|
||||
const replicator = mocks.couchDB[0];
|
||||
const database = { close: vi.fn() };
|
||||
const close = vi.fn(async () => undefined);
|
||||
const failure = new Error("verification failed");
|
||||
replicator.connectRemoteCouchDBWithSetting.mockResolvedValue({ db: database, close });
|
||||
mocks.checkSyncInfo.mockRejectedValue(failure);
|
||||
|
||||
await expect(resource.check()).rejects.toBe(failure);
|
||||
expect(close).toHaveBeenCalledOnce();
|
||||
expect(database.close).not.toHaveBeenCalled();
|
||||
|
||||
await resource.dispose();
|
||||
expect(replicator.closeReplication).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { RemoteDBSettings } from "@vrtmrz/livesync-commonlib/compat/common/types";
|
||||
import type {
|
||||
ConnectionProbeFactory,
|
||||
RemoteConnectionProbe,
|
||||
RemoteConnectionProbeOptions,
|
||||
} from "@vrtmrz/livesync-commonlib/replication";
|
||||
import {
|
||||
LiveSyncCouchDBReplicator,
|
||||
type LiveSyncCouchDBReplicatorEnv,
|
||||
} from "@vrtmrz/livesync-commonlib/compat/replication/couchdb/LiveSyncReplicator";
|
||||
import { LiveSyncJournalReplicator } from "@vrtmrz/livesync-commonlib/compat/replication/journal/LiveSyncJournalReplicator";
|
||||
import type { LiveSyncJournalReplicatorEnv } from "@vrtmrz/livesync-commonlib/compat/replication/journal/LiveSyncJournalReplicatorEnv";
|
||||
import { createReplicatorDisposer, snapshotRemoteSettings } from "./shared";
|
||||
|
||||
export type ConnectionResourceHost = LiveSyncCouchDBReplicatorEnv & LiveSyncJournalReplicatorEnv;
|
||||
|
||||
function createCouchDBConnectionProbe(
|
||||
replicator: LiveSyncCouchDBReplicator,
|
||||
snapshot: RemoteDBSettings
|
||||
): RemoteConnectionProbe {
|
||||
const dispose = createReplicatorDisposer(replicator);
|
||||
return {
|
||||
check: async (options: RemoteConnectionProbeOptions = {}) => {
|
||||
const connection = await replicator.connectRemoteCouchDBWithSetting(
|
||||
snapshot,
|
||||
replicator.isMobile(),
|
||||
options.createIfMissing ?? true,
|
||||
false
|
||||
);
|
||||
if (typeof connection === "string") {
|
||||
return { ok: false, reason: connection };
|
||||
}
|
||||
try {
|
||||
return { ok: true };
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
},
|
||||
getStatus: () => replicator.getRemoteStatus(snapshot),
|
||||
dispose,
|
||||
};
|
||||
}
|
||||
|
||||
function createObjectStorageConnectionProbe(
|
||||
replicator: LiveSyncJournalReplicator,
|
||||
snapshot: RemoteDBSettings
|
||||
): RemoteConnectionProbe {
|
||||
const dispose = createReplicatorDisposer(replicator);
|
||||
return {
|
||||
check: async (options: RemoteConnectionProbeOptions = {}) => {
|
||||
try {
|
||||
const connected = await replicator.tryConnectRemote(snapshot, options.showResult ?? false);
|
||||
return connected ? { ok: true } : { ok: false };
|
||||
} catch (error) {
|
||||
return { ok: false, reason: error };
|
||||
}
|
||||
},
|
||||
getStatus: () => replicator.getRemoteStatus(snapshot),
|
||||
dispose,
|
||||
};
|
||||
}
|
||||
|
||||
/** Build an unpublished CouchDB connection resource for one host. */
|
||||
export function createCouchDBConnectionProbeFactory(host: ConnectionResourceHost): ConnectionProbeFactory {
|
||||
return (setting) => {
|
||||
const snapshot = snapshotRemoteSettings(setting);
|
||||
return Promise.resolve(createCouchDBConnectionProbe(new LiveSyncCouchDBReplicator(host), snapshot));
|
||||
};
|
||||
}
|
||||
|
||||
/** Build an unpublished Object Storage connection resource for one host. */
|
||||
export function createObjectStorageConnectionProbeFactory(host: ConnectionResourceHost): ConnectionProbeFactory {
|
||||
return (setting) => {
|
||||
const snapshot = snapshotRemoteSettings(setting);
|
||||
return Promise.resolve(createObjectStorageConnectionProbe(new LiveSyncJournalReplicator(host), snapshot));
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
export {
|
||||
createCouchDBConnectionProbeFactory,
|
||||
createObjectStorageConnectionProbeFactory,
|
||||
type ConnectionResourceHost,
|
||||
} from "./connection";
|
||||
export {
|
||||
createCouchDBPreferredTweakProbeFactory,
|
||||
createObjectStoragePreferredTweakProbeFactory,
|
||||
type PreferredTweakResourceHost,
|
||||
} from "./preferredTweak";
|
||||
export {
|
||||
createCouchDBSecuritySeedResourceFactory,
|
||||
createObjectStorageSecuritySeedResourceFactory,
|
||||
type SecuritySeedResourceHost,
|
||||
} from "./securitySeed";
|
||||
export { createCouchDBSynchronisationInformationResourceFactory } from "./synchronisationInformation";
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { RemoteDBSettings, RemotePreferredTweakResult } from "@vrtmrz/livesync-commonlib/compat/common/types";
|
||||
import type { PreferredTweakProbe, PreferredTweakProbeFactory } from "@vrtmrz/livesync-commonlib/replication";
|
||||
import {
|
||||
LiveSyncCouchDBReplicator,
|
||||
type LiveSyncCouchDBReplicatorEnv,
|
||||
} from "@vrtmrz/livesync-commonlib/compat/replication/couchdb/LiveSyncReplicator";
|
||||
import { LiveSyncJournalReplicator } from "@vrtmrz/livesync-commonlib/compat/replication/journal/LiveSyncJournalReplicator";
|
||||
import type { LiveSyncJournalReplicatorEnv } from "@vrtmrz/livesync-commonlib/compat/replication/journal/LiveSyncJournalReplicatorEnv";
|
||||
import { createReplicatorDisposer, snapshotRemoteSettings, type ResourceReplicator } from "./shared";
|
||||
|
||||
export type PreferredTweakResourceHost = LiveSyncCouchDBReplicatorEnv & LiveSyncJournalReplicatorEnv;
|
||||
|
||||
interface PreferredTweakReplicator extends ResourceReplicator {
|
||||
getRemotePreferredTweakValues(setting: RemoteDBSettings): Promise<RemotePreferredTweakResult>;
|
||||
}
|
||||
|
||||
function createPreferredTweakProbe(
|
||||
replicator: PreferredTweakReplicator,
|
||||
snapshot: RemoteDBSettings
|
||||
): PreferredTweakProbe {
|
||||
return {
|
||||
read: () => replicator.getRemotePreferredTweakValues(snapshot),
|
||||
dispose: createReplicatorDisposer(replicator),
|
||||
};
|
||||
}
|
||||
|
||||
/** Build an unpublished CouchDB preferred-tweak resource for one host. */
|
||||
export function createCouchDBPreferredTweakProbeFactory(host: PreferredTweakResourceHost): PreferredTweakProbeFactory {
|
||||
return (setting) => {
|
||||
const snapshot = snapshotRemoteSettings(setting);
|
||||
return Promise.resolve(createPreferredTweakProbe(new LiveSyncCouchDBReplicator(host), snapshot));
|
||||
};
|
||||
}
|
||||
|
||||
/** Build an unpublished Object Storage preferred-tweak resource for one host. */
|
||||
export function createObjectStoragePreferredTweakProbeFactory(
|
||||
host: PreferredTweakResourceHost
|
||||
): PreferredTweakProbeFactory {
|
||||
return (setting) => {
|
||||
const snapshot = snapshotRemoteSettings(setting);
|
||||
return Promise.resolve(createPreferredTweakProbe(new LiveSyncJournalReplicator(host), snapshot));
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { SecuritySeedResourceFactory } from "@vrtmrz/livesync-commonlib/replication";
|
||||
import {
|
||||
LiveSyncCouchDBReplicator,
|
||||
type LiveSyncCouchDBReplicatorEnv,
|
||||
} from "@vrtmrz/livesync-commonlib/compat/replication/couchdb/LiveSyncReplicator";
|
||||
import { LiveSyncJournalReplicator } from "@vrtmrz/livesync-commonlib/compat/replication/journal/LiveSyncJournalReplicator";
|
||||
import type { LiveSyncJournalReplicatorEnv } from "@vrtmrz/livesync-commonlib/compat/replication/journal/LiveSyncJournalReplicatorEnv";
|
||||
import { createReplicatorDisposer, snapshotRemoteSettings } from "./shared";
|
||||
|
||||
export type SecuritySeedResourceHost = LiveSyncCouchDBReplicatorEnv & LiveSyncJournalReplicatorEnv;
|
||||
|
||||
function createSecuritySeedResourceFactory(
|
||||
createReplicator: () => LiveSyncCouchDBReplicator | LiveSyncJournalReplicator
|
||||
): SecuritySeedResourceFactory {
|
||||
return (setting) => {
|
||||
const snapshot = snapshotRemoteSettings(setting);
|
||||
const replicator = createReplicator();
|
||||
return Promise.resolve({
|
||||
read: () => replicator.getReplicationPBKDF2Salt(snapshot),
|
||||
dispose: createReplicatorDisposer(replicator),
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
/** Build an unpublished CouchDB Security Seed resource for one host. */
|
||||
export function createCouchDBSecuritySeedResourceFactory(host: SecuritySeedResourceHost): SecuritySeedResourceFactory {
|
||||
return createSecuritySeedResourceFactory(() => new LiveSyncCouchDBReplicator(host));
|
||||
}
|
||||
|
||||
/** Build an unpublished Object Storage Security Seed resource for one host. */
|
||||
export function createObjectStorageSecuritySeedResourceFactory(
|
||||
host: SecuritySeedResourceHost
|
||||
): SecuritySeedResourceFactory {
|
||||
return createSecuritySeedResourceFactory(() => new LiveSyncJournalReplicator(host));
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { RemoteDBSettings } from "@vrtmrz/livesync-commonlib/compat/common/types";
|
||||
|
||||
export interface ResourceReplicator {
|
||||
closeReplication(): void | Promise<void>;
|
||||
}
|
||||
|
||||
/** Create one idempotent asynchronous disposer for a private Replicator. */
|
||||
export function createReplicatorDisposer(replicator: ResourceReplicator): () => Promise<void> {
|
||||
let disposal: Promise<void> | undefined;
|
||||
return () => {
|
||||
if (disposal === undefined) {
|
||||
disposal = Promise.resolve().then(() => replicator.closeReplication());
|
||||
}
|
||||
return disposal;
|
||||
};
|
||||
}
|
||||
|
||||
/** Fence a finite resource from later edits to its source settings object. */
|
||||
export function snapshotRemoteSettings(setting: RemoteDBSettings): RemoteDBSettings {
|
||||
return { ...setting };
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { SynchronisationInformationResourceFactory } from "@vrtmrz/livesync-commonlib/replication";
|
||||
import {
|
||||
LiveSyncCouchDBReplicator,
|
||||
type LiveSyncCouchDBReplicatorEnv,
|
||||
} from "@vrtmrz/livesync-commonlib/compat/replication/couchdb/LiveSyncReplicator";
|
||||
import { checkSyncInfo } from "@vrtmrz/livesync-commonlib/compat/pouchdb/negotiation";
|
||||
import { createReplicatorDisposer, snapshotRemoteSettings } from "./shared";
|
||||
|
||||
/** Build an owned CouchDB synchronisation-information verifier for one host. */
|
||||
export function createCouchDBSynchronisationInformationResourceFactory(
|
||||
host: LiveSyncCouchDBReplicatorEnv
|
||||
): SynchronisationInformationResourceFactory {
|
||||
return (setting) => {
|
||||
const snapshot = snapshotRemoteSettings(setting);
|
||||
const replicator = new LiveSyncCouchDBReplicator(host);
|
||||
return Promise.resolve({
|
||||
check: async () => {
|
||||
const connection = await replicator.connectRemoteCouchDBWithSetting(
|
||||
snapshot,
|
||||
replicator.isMobile(),
|
||||
true
|
||||
);
|
||||
if (typeof connection === "string") {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
return await checkSyncInfo(connection.db);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
},
|
||||
dispose: createReplicatorDisposer(replicator),
|
||||
});
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user