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
133 changes: 76 additions & 57 deletions apps/desktop/src/app/DesktopApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as Data from "effect/Data";
import * as Duration from "effect/Duration";
import { randomUUIDv4 } from "@threadlines/shared/uuid";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";

Expand Down Expand Up @@ -110,68 +111,78 @@ const fatalStartupCause = <E>(stage: string, cause: Cause.Cause<E>) =>
* the menus, tray, file protocol, updater and IPC handlers can be built while
* it boots. The window waits for those (see allowMainWindowOpen), not for this.
*/
const startBackend = Effect.gen(function* () {
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
const state = yield* DesktopState.DesktopState;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
yield* logBootstrapInfo("bootstrap start");
const startBackend = (shellEnvironmentFiber: Fiber.Fiber<void>) =>
Effect.gen(function* () {
const backendManager = yield* DesktopBackendManager.DesktopBackendManager;
const shutdown = yield* DesktopLifecycle.DesktopShutdown;
const state = yield* DesktopState.DesktopState;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
yield* logBootstrapInfo("bootstrap start");

if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) {
return yield* new DesktopDevelopmentBackendPortRequiredError();
}
if (environment.isDevelopment && Option.isNone(environment.configuredBackendPort)) {
return yield* new DesktopDevelopmentBackendPortRequiredError();
}

const settings = yield* desktopSettings.get;
const probeHosts = desktopBackendPortProbeHosts(settings.serverExposureMode);
const backendPortSelection = yield* resolveDesktopBackendPort({
configuredPort: environment.configuredBackendPort,
probeHosts,
}).pipe(
Effect.timeoutOrElse({
duration: BACKEND_PORT_DISCOVERY_TIMEOUT,
orElse: () => new DesktopBackendPortDiscoveryTimeoutError(),
}),
);
const backendPort = backendPortSelection.port;
yield* logBootstrapInfo(
backendPortSelection.selectedByScan
? "selected backend port via sequential scan"
: "using configured backend port",
{
port: backendPort,
...(backendPortSelection.selectedByScan ? { startPort: DEFAULT_DESKTOP_BACKEND_PORT } : {}),
},
);
const settings = yield* desktopSettings.get;
const probeHosts = desktopBackendPortProbeHosts(settings.serverExposureMode);
const backendPortSelection = yield* resolveDesktopBackendPort({
configuredPort: environment.configuredBackendPort,
probeHosts,
}).pipe(
Effect.timeoutOrElse({
duration: BACKEND_PORT_DISCOVERY_TIMEOUT,
orElse: () => new DesktopBackendPortDiscoveryTimeoutError(),
}),
);
const backendPort = backendPortSelection.port;
yield* logBootstrapInfo(
backendPortSelection.selectedByScan
? "selected backend port via sequential scan"
: "using configured backend port",
{
port: backendPort,
...(backendPortSelection.selectedByScan ? { startPort: DEFAULT_DESKTOP_BACKEND_PORT } : {}),
},
);

if (settings.serverExposureMode !== environment.defaultDesktopSettings.serverExposureMode) {
yield* logBootstrapInfo("bootstrap restoring persisted server exposure mode", {
mode: settings.serverExposureMode,
if (settings.serverExposureMode !== environment.defaultDesktopSettings.serverExposureMode) {
yield* logBootstrapInfo("bootstrap restoring persisted server exposure mode", {
mode: settings.serverExposureMode,
});
}
const serverExposureState = yield* serverExposure.configureFromSettings({
port: backendPort,
selectedByScan: backendPortSelection.selectedByScan,
});
}
const serverExposureState = yield* serverExposure.configureFromSettings({
port: backendPort,
selectedByScan: backendPortSelection.selectedByScan,
});
const backendConfig = yield* serverExposure.backendConfig;
yield* logBootstrapInfo("bootstrap resolved backend endpoint", {
baseUrl: backendConfig.httpBaseUrl.href,
});
if (serverExposureState.endpointUrl) {
yield* logBootstrapInfo("bootstrap enabled network access", {
endpointUrl: serverExposureState.endpointUrl,
const backendConfig = yield* serverExposure.backendConfig;
yield* logBootstrapInfo("bootstrap resolved backend endpoint", {
baseUrl: backendConfig.httpBaseUrl.href,
});
} else if (settings.serverExposureMode === "network-accessible") {
yield* logBootstrapWarning(
"bootstrap fell back to local-only because no advertised network host was available",
if (serverExposureState.endpointUrl) {
yield* logBootstrapInfo("bootstrap enabled network access", {
endpointUrl: serverExposureState.endpointUrl,
});
} else if (settings.serverExposureMode === "network-accessible") {
yield* logBootstrapWarning(
"bootstrap fell back to local-only because no advertised network host was available",
);
}

// Wait for the login-shell environment probe before spawning the backend
// (and before updates.configure below) so both see the recovered PATH.
// Race against shutdown so quitting while a slow shell probes exits promptly.
yield* Effect.raceFirst(
Fiber.join(shellEnvironmentFiber),
shutdown.awaitRequest.pipe(Effect.andThen(Fiber.interrupt(shellEnvironmentFiber))),
);
}

if (!(yield* Ref.get(state.quitting))) {
yield* backendManager.start;
yield* logBootstrapInfo("bootstrap backend start requested");
}
}).pipe(Effect.withSpan("desktop.bootstrap"));
if (!(yield* Ref.get(state.quitting))) {
yield* backendManager.start;
yield* logBootstrapInfo("bootstrap backend start requested");
}
}).pipe(Effect.withSpan("desktop.bootstrap"));

const startup = Effect.gen(function* () {
const appIdentity = yield* DesktopAppIdentity.DesktopAppIdentity;
Expand All @@ -181,14 +192,17 @@ const startup = Effect.gen(function* () {
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
const state = yield* DesktopState.DesktopState;
const updates = yield* DesktopUpdates.DesktopUpdates;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const statusIndicator = yield* DesktopStatusIndicator.DesktopStatusIndicator;
const background = yield* DesktopBackground.DesktopBackground;
const desktopWindow = yield* DesktopWindow.DesktopWindow;
const threadLinks = yield* DesktopThreadLinks.DesktopThreadLinks;

yield* shellEnvironment.installIntoProcess;
// Probe the login shell in parallel with Electron initialization and backend
// port discovery; joined in startBackend before spawning the server process.
const shellEnvironmentFiber = yield* Effect.forkChild(shellEnvironment.installIntoProcess);
yield* logStartupInfo("runtime logging configured", { logDir: environment.logDir });
yield* desktopSettings.load;

Expand All @@ -214,7 +228,12 @@ const startup = Effect.gen(function* () {
logStartupWarning("browser passkeys could not be enabled", { cause: String(cause) }),
),
);
yield* startBackend.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
yield* startBackend(shellEnvironmentFiber).pipe(
Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)),
);
if (yield* Ref.get(state.quitting)) {
return;
}
yield* applicationMenu.configure;
yield* statusIndicator.configure;
yield* background.configure;
Expand Down
112 changes: 92 additions & 20 deletions apps/desktop/src/app/DesktopObservability.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
Expand All @@ -13,6 +14,7 @@ import * as PlatformError from "effect/PlatformError";
import * as References from "effect/References";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Semaphore from "effect/Semaphore";
import * as Tracer from "effect/Tracer";
import { OtlpExporter, OtlpSerialization, OtlpTracer } from "effect/observability";
Expand All @@ -22,6 +24,8 @@ import * as DesktopEnvironment from "./DesktopEnvironment.ts";

const DESKTOP_LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
const DESKTOP_LOG_FILE_MAX_FILES = 10;
const DESKTOP_LOG_BATCH_WINDOW_MS = 25;
const DESKTOP_LOG_BATCH_MAX_BYTES = 16 * 1024;
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
const DESKTOP_TRACE_BATCH_WINDOW_MS = 200;

Expand Down Expand Up @@ -50,6 +54,7 @@ ignoreDevelopmentConsoleBrokenPipe(process.stderr);
export interface RotatingLogFileWriter {
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
readonly writeText: (chunk: string) => Effect.Effect<void>;
readonly flush: Effect.Effect<void>;
}

export interface DesktopBackendOutputLogShape {
Expand Down Expand Up @@ -162,10 +167,11 @@ const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(functio
}): Effect.fn.Return<
RotatingLogFileWriter,
DesktopLogFileWriterError,
FileSystem.FileSystem | Path.Path
FileSystem.FileSystem | Path.Path | Scope.Scope
> {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const writerScope = yield* Scope.Scope;
const maxBytes = input.maxBytes ?? DESKTOP_LOG_FILE_MAX_BYTES;
const maxFiles = input.maxFiles ?? DESKTOP_LOG_FILE_MAX_FILES;
const directory = path.dirname(input.filePath);
Expand All @@ -189,6 +195,10 @@ const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(functio
const withSuffix = (index: number) => `${input.filePath}.${index}`;
const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
const mutex = yield* Semaphore.make(1);
let pendingChunks: Array<Uint8Array> = [];
let pendingBytes = 0;
let flushTimer: Fiber.Fiber<void, never> | null = null;
let closed = false;

const pruneOverflowBackups = Effect.gen(function* () {
const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
Expand Down Expand Up @@ -224,38 +234,99 @@ const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(functio
),
);

const writeCombinedLocked = (combined: Uint8Array): Effect.Effect<void> =>
Effect.gen(function* () {
const beforeSize = yield* Ref.get(currentSize);
if (beforeSize > 0 && beforeSize + combined.byteLength > maxBytes) {
yield* rotate;
}

yield* fileSystem.writeFile(input.filePath, combined, { flag: "a" });
const afterSize = (yield* Ref.get(currentSize)) + combined.byteLength;
yield* Ref.set(currentSize, afterSize);

if (afterSize > maxBytes) {
yield* rotate;
}
}).pipe(
Effect.catch(() =>
refreshFileSize(fileSystem, input.filePath).pipe(
Effect.flatMap((size) => Ref.set(currentSize, size)),
),
),
);

const flushPending: Effect.Effect<void> = mutex.withPermits(1)(
Effect.gen(function* () {
if (pendingChunks.length === 0) {
return;
}
const chunks = pendingChunks;
const totalBytes = pendingBytes;
pendingChunks = [];
pendingBytes = 0;

let combined: Uint8Array;
if (chunks.length === 1) {
combined = chunks[0]!;
} else {
combined = new Uint8Array(totalBytes);
let offset = 0;
for (const chunk of chunks) {
combined.set(chunk, offset);
offset += chunk.byteLength;
}
}
yield* writeCombinedLocked(combined);
}).pipe(Effect.uninterruptible),
);

const flush: Effect.Effect<void> = Effect.gen(function* () {
const timer = flushTimer;
flushTimer = null;
if (timer !== null) {
yield* Fiber.interrupt(timer).pipe(Effect.ignore);
}
yield* flushPending;
});

const writeBytes = (chunk: Uint8Array): Effect.Effect<void> => {
if (chunk.byteLength === 0) return Effect.void;

return mutex.withPermits(1)(
Effect.gen(function* () {
const beforeSize = yield* Ref.get(currentSize);
if (beforeSize > 0 && beforeSize + chunk.byteLength > maxBytes) {
yield* rotate;
}
return Effect.gen(function* () {
pendingChunks.push(chunk);
pendingBytes += chunk.byteLength;

yield* fileSystem.writeFile(input.filePath, chunk, { flag: "a" });
const afterSize = (yield* Ref.get(currentSize)) + chunk.byteLength;
yield* Ref.set(currentSize, afterSize);
if (closed || pendingBytes >= DESKTOP_LOG_BATCH_MAX_BYTES) {
yield* flush;
return;
}

if (afterSize > maxBytes) {
yield* rotate;
}
}).pipe(
Effect.catch(() =>
refreshFileSize(fileSystem, input.filePath).pipe(
Effect.flatMap((size) => Ref.set(currentSize, size)),
if (flushTimer === null) {
flushTimer = yield* Effect.sleep(`${DESKTOP_LOG_BATCH_WINDOW_MS} millis`).pipe(
Effect.andThen(
Effect.gen(function* () {
flushTimer = null;
yield* flushPending;
}),
),
),
),
);
Effect.forkIn(writerScope),
);
}
});
};

yield* pruneOverflowBackups;
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
closed = true;
}).pipe(Effect.andThen(flush), Effect.ignore),
);

return {
writeBytes,
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
flush,
} satisfies RotatingLogFileWriter;
});

Expand Down Expand Up @@ -350,6 +421,7 @@ const backendOutputLogLayer = Layer.effect(
details: sanitizeLogValue(details),
},
});
yield* logFile.flush;
}),
writeOutputChunk: Effect.fn("desktop.observability.backendOutput.writeOutputChunk")(
function* (streamName, chunk) {
Expand Down
Loading
Loading