Refactor: Make stream termination more robust

This commit is contained in:
2025-09-27 03:58:44 -07:00
parent 9b6d2a4c48
commit 02eaf94c49

View File

@@ -172,15 +172,15 @@ export class MyDurableObject {
async stream({ apiKey, body, provider }) { async stream({ apiKey, body, provider }) {
try { try {
if (provider === 'openai') await this.streamOpenAI({ apiKey, body }); const providerMap = { openai: this.streamOpenAI, google: this.streamGoogle };
else if (provider === 'google') await this.streamGoogle({ apiKey, body }); await (providerMap[provider] || this.streamOpenRouter).call(this, { apiKey, body });
else await this.streamOpenRouter({ apiKey, body });
if (this.phase === 'running') this.stop();
} catch (e) { } catch (e) {
if (this.phase === 'running') { if (this.phase === 'running') {
const msg = String(e?.message || 'stream_failed'); const msg = String(e?.message || 'stream_failed');
if (!((e && e.name === 'AbortError') || /abort/i.test(msg))) this.fail(msg); if (!((e && e.name === 'AbortError') || /abort/i.test(msg))) this.fail(msg);
} }
} finally {
if (this.phase === 'running') this.stop();
} }
} }
@@ -261,7 +261,7 @@ export class MyDurableObject {
} }
fail(message) { fail(message) {
if (this.phase === 'error') return; if (this.phase !== 'running') return;
this.flush(true); this.flush(true);
this.phase = 'error'; this.phase = 'error';
this.error = String(message || 'stream_failed'); this.error = String(message || 'stream_failed');