Skip to content

Commit 446407c

Browse files
authored
Merge pull request #315 from pathsim/refactor/unify-backend-resolver
Unify backend resolution + surface dropped stream frames
2 parents 94fdcd6 + ddee894 commit 446407c

4 files changed

Lines changed: 31 additions & 40 deletions

File tree

‎src/lib/pyodide/backend/flask/backend.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -387,7 +387,8 @@ export class FlaskBackend extends AbstractBackend {
387387
try {
388388
this.streamState.onData(JSON.parse(msg.value as string));
389389
} catch {
390-
// Ignore parse errors
390+
// Surface (don't silently drop) a corrupt stream frame.
391+
this.stderrCallback?.('[stream] dropped an unparseable data frame\n');
391392
}
392393
}
393394
break;

‎src/lib/pyodide/backend/index.ts‎

Lines changed: 25 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -38,54 +38,47 @@ import { backendState } from './state';
3838
import { consoleStore } from '$lib/stores/console';
3939

4040
/**
41-
* Initialize backend from URL parameters.
42-
* Reads `?backend=flask` and `?host=...` from the current URL.
43-
* Call this early in page mount, before any backend usage.
41+
* Resolve and initialize the execution backend at startup.
42+
*
43+
* Single entry point replacing the old `initBackendFromUrl` + `autoDetectBackend`
44+
* pair (which were both awaited and could each switch+init independently).
45+
* Precedence:
46+
* 1. `?backend=flask[&host=...]` URL override — explicit wins.
47+
* 2. Same-origin Flask server (pip-package mode), detected via `/api/health`.
48+
* 3. Default: Pyodide (created lazily by `getBackend()` on first use).
49+
* Only switches/initializes a Flask backend; the Pyodide default needs no work
50+
* here (it initializes on first `init()`/`exec()`).
4451
*/
45-
export async function initBackendFromUrl(): Promise<void> {
52+
export async function resolveBackend(): Promise<void> {
4653
if (typeof window === 'undefined') return;
4754
const params = new URLSearchParams(window.location.search);
48-
const backendParam = params.get('backend');
49-
const hostParam = params.get('host');
5055

51-
if (backendParam === 'flask') {
52-
if (hostParam) {
53-
setFlaskHost(hostParam);
54-
}
56+
// 1. Explicit URL override.
57+
if (params.get('backend') === 'flask') {
58+
const host = params.get('host');
59+
if (host) setFlaskHost(host);
5560
switchBackend('flask');
5661
await init();
62+
return;
5763
}
58-
}
59-
60-
/**
61-
* Auto-detect if a Flask backend is available at the same origin.
62-
* Used when the frontend is served by the Flask server (pip package mode).
63-
* URL parameters take precedence — if `?backend=` is set, auto-detection is skipped.
64-
*/
65-
export async function autoDetectBackend(): Promise<void> {
66-
if (typeof window === 'undefined') return;
67-
68-
// URL params override auto-detection
69-
const params = new URLSearchParams(window.location.search);
70-
if (params.has('backend')) return;
7164

65+
// 2. Auto-detect a same-origin Flask server.
7266
try {
7367
const response = await fetch('/api/health', {
7468
method: 'GET',
7569
signal: AbortSignal.timeout(2000)
7670
});
77-
if (response.ok) {
78-
const data = await response.json();
79-
if (data.status === 'ok') {
80-
setFlaskHost(window.location.origin);
81-
switchBackend('flask');
82-
// Run full init — sets up callbacks, logs progress, initializes worker
83-
await init();
84-
}
71+
if (response.ok && (await response.json())?.status === 'ok') {
72+
setFlaskHost(window.location.origin);
73+
switchBackend('flask');
74+
await init();
75+
return;
8576
}
8677
} catch {
87-
// No Flask backend at same origin — will use Pyodide
78+
// No Flask backend at same origin — fall through to the Pyodide default.
8879
}
80+
81+
// 3. Default: Pyodide (lazy).
8982
}
9083

9184
// Alias for backward compatibility

‎src/lib/pyodide/backend/pyodide/backend.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@ interface StreamState {
3333
export class PyodideBackend extends AbstractBackend {
3434
private worker: Worker | null = null;
3535
private pendingRequests = new Map<string, PendingRequest>();
36-
private isInitializing = false;
3736

3837
private streamState: StreamState = {
3938
id: null,
@@ -66,7 +65,6 @@ export class PyodideBackend extends AbstractBackend {
6665
error: null,
6766
progress: PROGRESS_MESSAGES.STARTING_WORKER
6867
}));
69-
this.isInitializing = true;
7068

7169
try {
7270
this.worker = new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' });
@@ -291,7 +289,6 @@ export class PyodideBackend extends AbstractBackend {
291289
loading: false,
292290
progress: STATUS_MESSAGES.READY
293291
}));
294-
this.isInitializing = false;
295292
break;
296293

297294
case 'progress':
@@ -341,7 +338,8 @@ export class PyodideBackend extends AbstractBackend {
341338
try {
342339
this.streamState.onData(JSON.parse(response.value));
343340
} catch {
344-
// Ignore parse errors
341+
// Surface (don't silently drop) a corrupt stream frame.
342+
this.stderrCallback?.('[stream] dropped an unparseable data frame\n');
345343
}
346344
}
347345
break;

‎src/routes/+page.svelte‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@
4747
import type { MenuItemType } from '$lib/components/ContextMenu.svelte';
4848
import { pyodideState, simulationState, initPyodide, stopSimulation, continueStreamingSimulation, stageMutations, resetSimulation } from '$lib/pyodide/bridge';
4949
import { pendingMutationCount } from '$lib/pyodide/mutationQueue';
50-
import { initBackendFromUrl, autoDetectBackend } from '$lib/pyodide/backend';
50+
import { resolveBackend } from '$lib/pyodide/backend';
5151
import { runGraphStreamingSimulation, validateGraphSimulation, exportToPython } from '$lib/pyodide/pathsimRunner';
5252
import { consoleStore } from '$lib/stores/console';
5353
import { newGraph, saveFile, saveAsFile, setupAutoSave, clearAutoSave, debouncedAutoSave, openImportDialog, importFromUrl, currentFileName, loadGraphFile, listRecentFiles, openRecentFile, removeRecentFile } from '$lib/schema/fileOps';
@@ -598,8 +598,7 @@
598598
seedPreloadedToolboxes();
599599
backendReady = (async () => {
600600
try {
601-
await autoDetectBackend();
602-
await initBackendFromUrl();
601+
await resolveBackend();
603602
await initPyodide();
604603
statusText = 'Loading toolboxes...';
605604
await bootstrapToolboxes();

0 commit comments

Comments
 (0)