Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions apps/link-service/chaos/run.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ async function bringUp() {
*/
function createProbe(world) {
const pings = [], gaps = [];
let live = null, lastEventAt = 0, stopped = false, timer = null, inFlight = 0, liveReq = null;
let live = null, lastEventAt = 0, openedAt = 0, stopped = false, timer = null, inFlight = 0, liveReq = null;
const port = () => Number(new URL(world.app.origin()).port);
const host = () => world.app.host();
function call(path, { method = "GET", body = null, timeoutMs = 8000, port: at = port(), host: name = host() } = {}) {
Expand Down Expand Up @@ -180,6 +180,7 @@ function createProbe(world) {
res.on("close", () => closed("closed"));
});
liveReq = req;
openedAt = Date.now();
let done = false;
function closed() {
if (done) return;
Expand All @@ -198,7 +199,10 @@ function createProbe(world) {
const up = now - lastEventAt < 5000;
if (!up && downSince === null) downSince = Math.max(lastEventAt, now - 5000);
if (up && downSince !== null) { gaps.push({ from: downSince, to: now }); downSince = null; }
if (liveReq && now - lastEventAt > 20_000 && live) { liveReq.destroy(); }
// as the app does (src/lib/live-events.ts): a dial that sends nothing in LIVE_EVENTS_OPEN_MS (8 s) is dialled again,
// and a stream that went quiet after it sent something is dialled again after 20 s
const quietFor = now - Math.max(lastEventAt, openedAt);
if (liveReq && quietFor > (live ? 20_000 : 8_000)) { liveReq.destroy(); }
}, 250);
return {
start() { timer = setInterval(tick, 500); openLive(); },
Expand Down Expand Up @@ -336,5 +340,6 @@ if (!process.env.DUSK_CHAOS_DIR) {
} else {
process.env.DUSK_CHAOS_PARENT = String(process.pid);
for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => process.exit(130));
main().catch((error) => { console.error(error); process.exit(2); });
// the results are written by then; a socket or timer some scenario left open would otherwise hold the run until CI's job limit
main().then(() => process.exit(process.exitCode ?? 0), (error) => { console.error(error); process.exit(2); });
}
35 changes: 31 additions & 4 deletions apps/link-service/chaos/scenarios.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// things route around it) and answers { clearedAt, pass, note, sees }. run.mjs measures the rest.
import { createHash } from "node:crypto";
import { chmodSync } from "node:fs";
import { Agent as HttpsAgent, request as httpsRequest } from "node:https";
import { join } from "node:path";

import { createTunnelAgent } from "../agent.mjs";
Expand All @@ -27,17 +28,43 @@ async function failover(world, { kill = true } = {}) {
return { pass: moved !== home && moved !== null, note: `moved ${home} -> ${moved} in ${Math.round((workedAt - started) / 1000)} s`, clearedAt: started };
}

/** `count` more servers and apps on the default node, in this process: the agent's and the app's relay code each */
/** a fetch that keeps to one connection of its own. Node's built-in fetch shares one pool for the whole process, and the
* chaos workflow runs without installing packages, so this uses node:https. `close()` ends the connection. */
function fetchOverOwnConnection() {
const agent = new HttpsAgent({ keepAlive: true, maxSockets: 1 });
const ownFetch = (url, { method = "GET", headers = {}, body, signal } = {}) => new Promise((resolve, reject) => {
const request = httpsRequest(url, { method, headers, agent, signal }, (answer) => {
const chunks = [];
answer.on("data", (chunk) => chunks.push(chunk));
answer.on("error", reject);
answer.on("end", () => {
const noBody = [204, 205, 304].includes(answer.statusCode);
const answerHeaders = Object.entries(answer.headers).flatMap(([name, value]) => (Array.isArray(value) ? value.map((one) => [name, one]) : [[name, value]]));
resolve(new Response(noBody ? null : Buffer.concat(chunks), { status: answer.statusCode, headers: answerHeaders }));
});
});
request.on("error", reject);
request.end(body);
});
return { fetch: ownFetch, close: () => agent.destroy() };
}

/** `count` more servers and apps on the default node, in this process: the agent's and the app's relay code each. Each
* sets up its link over its own connection, so the node's front gives it its own address, as `count` machines would have:
* on one connection they would be one address, over the node's limit on new links an address may make in a minute. */
async function crowd(world, count) {
const base = world.url("contabo"), relay = createRelayClient({ base }), out = [];
const base = world.url("contabo"), out = [];
for (let i = 0; i < count; i += 1) {
const own = fetchOverOwnConnection();
const ownFetch = own.fetch;
const keys = newLinkKeys();
const made = await relay.create({ verifier: keys.verifier, appPub: keys.pub });
const made = await createRelayClient({ base, fetch: ownFetch }).create({ verifier: keys.verifier, appPub: keys.pub });
const vps = vpsTokenOf(keys.secret);
const post = (path, body) => fetch(`${base}/v1/sessions/${made.id}/${path}`, { method: "POST", headers: { authorization: `Bearer ${vps}`, "content-type": "application/json" }, body: JSON.stringify(body) });
const post = (path, body) => ownFetch(`${base}/v1/sessions/${made.id}/${path}`, { method: "POST", headers: { authorization: `Bearer ${vps}`, "content-type": "application/json" }, body: JSON.stringify(body) });
await post("claim", {});
const tunnel = { key: randomBytes(32).toString("base64url"), vps: randomBytes(32).toString("base64url"), app: randomBytes(32).toString("base64url") };
const done = await post("result", { sealed: seal(Buffer.alloc(32), made.id, Buffer.from("{}")), vpsPub: keys.pub, tunnel: { vps: sha256hex(tunnel.vps), app: sha256hex(tunnel.app) } });
await own.close();
if (!done.ok) throw new Error(`crowd link ${i} answered ${done.status}`);
const agent = createTunnelAgent({ base, id: made.id, key: tunnel.key, token: tunnel.vps, server: { host: "127.0.0.1", port: world.bot.port }, log: () => {} });
const running = agent.run();
Expand Down
15 changes: 15 additions & 0 deletions electron/held-until-released.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/** Calls `apply` with each value, but values delivered before `release()` wait and then apply in their order. */
export function heldUntilReleased(apply) {
let held = [];
return {
deliver(value) {
if (held) held.push(value);
else apply(value);
},
release() {
const waiting = held ?? [];
held = null;
for (const value of waiting) apply(value);
},
};
}
32 changes: 32 additions & 0 deletions electron/held-until-released.node-test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";

import { heldUntilReleased } from "./held-until-released.mjs";

test("values delivered before the release wait and then apply in order; later ones apply at once", () => {
const applied = [];
const states = heldUntilReleased((value) => applied.push(value));
states.deliver("restoring");
states.deliver("connected");
assert.deepEqual(applied, []);
states.release();
assert.deepEqual(applied, ["restoring", "connected"]);
states.deliver("signed-out");
assert.deepEqual(applied, ["restoring", "connected", "signed-out"]);
states.release();
assert.deepEqual(applied, ["restoring", "connected", "signed-out"]);
});

test("a launch restores the Cloud account while the local server starts, and applies its states only once the server is up", () => {
const main = readFileSync(new URL("./main.mjs", import.meta.url), "utf8");
const launch = main.indexOf("app.whenReady().then");
const restore = main.indexOf("cloudAccountStarted = ensureCloudAccount().start()", launch);
const serverWait = main.indexOf("const startup = startPackagedAlongsideVps", launch);
const serverMark = main.indexOf('startupTrace.mark(serverReady ? "server" : "server-failed")', launch);
const release = main.indexOf("accountStates.release()", launch);
assert.ok(launch > 0 && restore > launch && serverWait > restore, "the restore starts before the server is awaited");
assert.ok(release > serverMark, "account states apply after the server is up");
assert.equal(main.indexOf("cloudAccountStarted = ensureCloudAccount().start()", restore + 1), -1, "the restore starts once");
assert.match(main, /onState: state => accountStates\.deliver\(state\)/);
});
38 changes: 19 additions & 19 deletions electron/main.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ import { createOrganizationEntry, isOrganizationDeepLink, takeOrganizationDeepLi
import { FRAME_BY_DEFAULT, widenedBounds, windowBackground, windowChromeOptions } from "./window-chrome.mjs";
import { createAllWindowsClosedQuit } from "./window-all-closed.mjs";
import { createStartupScreen, expectedLoadMs, rememberLoad, startupDark } from "./startup-screen.mjs";
import { createStartupTrace } from "./startup-trace.mjs";
import { createStartupTrace } from "./startup-trace.mjs"; import { heldUntilReleased } from "./held-until-released.mjs";
import { devUserDataDir } from "./dev-defaults.mjs";
import { createDevServerChild, devOwnServerWanted, devServerConflictMessage, watchServerSource } from "./dev-server-child.mjs"; import { desktopLogDir } from "./dev-log-dir.mjs";
import { createSystemTray } from "./system-tray.mjs";
Expand Down Expand Up @@ -954,22 +954,24 @@ function ensureCloudAccount() {
// every browser sign-in (Google, Apple, a magic link) goes through the website with this app's sign-in code, so a new
// account gets the website's first steps there, and this app signs itself in when the website approves it
openBrowser: url => shell.openExternal(url), awaitingWake: () => cloudPower.awaiting(), appLinks: false,
onState: state => {
if (state?.account && state.status === "connected") desktopPrefs?.markSignedIn(); cloudSync.accountChanged(state.account?.id ?? null); rememberCloudHome(state);
rememberedHome = rememberedCloudHome(rememberedHome, state);
cloudPower.changed(); try { void oneHome.kick(); void homeWindow.changed(); announceAddedCloud(state); railChanged(); accountEnroll.onState(state); accountGate.changed(state); void botsElsewhere.remember(); void vpsCloudMove?.kick(); void vpsCloudMove?.signedInNow?.(); serverEnroll?.onState(state); } catch {}
// a server's install line that waited on the account: made at once now (vpsLink may not exist yet at launch)
try { if (state?.account && state.status === "connected") void vpsLink?.accountReady?.(); } catch {}
void includedX.onState(state); void includedPages.onState(state); void includedXIndex.onState(state); void includedArtifacts.onState(state); accounts.tell();
refreshCloudMenus();
announceCloudReady(state);
if (mainWindow && !mainWindow.isDestroyed() && mainWindow.webContents.mainFrame.url.startsWith(`${rendererOrigin()}/`) &&
!activeRemote(environmentsState) && !desktopRemoteAccess) mainWindow.webContents.send("cloud-account:state-changed", state);
},
onState: state => accountStates.deliver(state),
});
return cloudAccount;
}

const accountStates = heldUntilReleased(function applyAccountState(state) {
if (state?.account && state.status === "connected") desktopPrefs?.markSignedIn(); cloudSync.accountChanged(state.account?.id ?? null); rememberCloudHome(state);
rememberedHome = rememberedCloudHome(rememberedHome, state);
cloudPower.changed(); try { void oneHome.kick(); void homeWindow.changed(); announceAddedCloud(state); railChanged(); accountEnroll.onState(state); accountGate.changed(state); void botsElsewhere.remember(); void vpsCloudMove?.kick(); void vpsCloudMove?.signedInNow?.(); serverEnroll?.onState(state); } catch {}
// a server's install line that waited on the account: made at once now (vpsLink may not exist yet at launch)
try { if (state?.account && state.status === "connected") void vpsLink?.accountReady?.(); } catch {}
void includedX.onState(state); void includedPages.onState(state); void includedXIndex.onState(state); void includedArtifacts.onState(state); accounts.tell();
refreshCloudMenus();
announceCloudReady(state);
if (mainWindow && !mainWindow.isDestroyed() && mainWindow.webContents.mainFrame.url.startsWith(`${rendererOrigin()}/`) &&
!activeRemote(environmentsState) && !desktopRemoteAccess) mainWindow.webContents.send("cloud-account:state-changed", state);
});

/** The free trial's popup, at most once a day per notice across this computer's page and the Cloud's. */
let trialNotices = null;
function cloudTrialNotices() {
Expand Down Expand Up @@ -3522,6 +3524,9 @@ app.whenReady().then(async () => {
? cuaWanted.promise.then((wanted) => wanted ? startCua() : { mode: "unavailable", reason: "startup-failed" }).catch((e) => { console.error("[cua] start failed:", e); return { mode: "unavailable", reason: String(e) }; })
: Promise.resolve({ mode: "unavailable", reason: "unsupported-platform" });
if (app.isPackaged && !desktopRemoteAccess) prepareMainWindow();
// Fresh local use never makes a Cloud request; start only restores a grant, beside the server start: the first screen waits on it, and `accountStates` holds its states until that server is up.
if (accountApp() || accountGateNeeded()) { cloudAccountRestoring = true;
cloudAccountStarted = ensureCloudAccount().start().catch(() => {}).then(() => accountRing()?.start()).finally(() => { cloudAccountRestoring = false; }); }
if (desktopRemoteAccess) {
try {
desktopCompanionRelay = await startDesktopCompanionRelay({
Expand Down Expand Up @@ -3610,13 +3615,8 @@ app.whenReady().then(async () => {
} finally { localRuntimeStarting = null; }
}
startupTrace.mark(serverReady ? "server" : "server-failed"); if (!serverReady) skipCua();
if (desktopShutdownStarted) return;
if (desktopShutdownStarted) return; accountStates.release();
if (app.isPackaged && !desktopRemoteAccess) void ensureManagedDesktop().start().then(() => companyBackupSchedule.start()).catch(() => {});
// Fresh local use never makes a Cloud request; start only restores an existing grant.
if (accountApp() || accountGateNeeded()) {
cloudAccountRestoring = true;
cloudAccountStarted = ensureCloudAccount().start().catch(() => {}).then(() => accountRing()?.start()).finally(() => { cloudAccountRestoring = false; });
}
void cloudAccountStarted.then(() => { void oneHome.kick(); void homeWindow.refresh(); void vpsCloudMove?.kick(); if (cloudAccount) serverEnroll?.onState(cloudAccount.state()); void viaMacFollow(); }); void ownHome?.kick();
if (!desktopRemoteAccess && serverReady && companionEnabledAtRest() && !oneHome.away() && !ownHome?.away() && !cleanWorkspace.marker().frozen) {
// Retries stop once the person turns the phone off, starts it by hand or quits.
Expand Down
Loading
Loading