Files

192 lines
5.8 KiB
JavaScript

'use strict';
window.AssistantEvents = {
connect({ id, cursor = 0, api, onEvents, onChange, onAuth, onRemoved, isActive = () => true }) {
let disposed = false,
controller = null,
retryTimer = null,
pollTimer = null,
probeTimer = null,
failures = 0,
backoff = 0,
polling = false,
pollInFlight = false,
delivery = Promise.resolve();
const lifetime = new AbortController();
const alive = () => !disposed && isActive();
function auth(error) {
if (error.status === 404) {
dispose();
onRemoved?.();
return true;
}
if (error.status === 401 || error.status === 403) {
dispose();
onAuth?.(error);
return true;
}
return false;
}
function consume(events) {
const work = delivery
.catch(() => {})
.then(async () => {
if (!alive()) return;
const fresh = [];
let next = cursor;
for (const e of events) {
if (e.conversationId !== id || !Number.isSafeInteger(e.seq) || e.seq <= next) continue;
if (e.seq !== next + 1) throw new Error('事件序列不连续');
next = e.seq;
fresh.push(e);
}
if (fresh.length) {
await onChange();
if (!alive()) return;
onEvents(fresh);
cursor = next;
}
});
delivery = work;
return work;
}
async function catchUp() {
let more = true;
while (alive() && more) {
const batch = await api(
'/assistant/conversations/' + id + '/events?after=' + cursor,
undefined,
{ signal: lifetime.signal },
);
if (!alive()) return;
await consume(batch.events);
more = batch.hasMore;
}
}
function beginPolling() {
if (!alive()) return;
clearTimeout(probeTimer);
probeTimer = setTimeout(() => {
if (alive()) void stream();
}, 60000);
if (polling) return;
polling = true;
const poll = async () => {
if (pollInFlight) return;
pollInFlight = true;
try {
await catchUp();
} catch (e) {
if (auth(e)) return;
if (e.status === 400) {
cursor = 0;
await onChange();
}
} finally {
pollInFlight = false;
if (alive() && polling) pollTimer = setTimeout(poll, 3000);
}
};
void poll();
}
async function stream() {
if (!alive()) return;
controller?.abort();
const mine = new AbortController();
controller = mine;
let buffer = '',
idleTimer;
const resetIdle = () => {
clearTimeout(idleTimer);
idleTimer = setTimeout(() => mine.abort(), 45000);
};
resetIdle();
try {
const response = await fetch(
'/api/assistant/conversations/' + id + '/stream?after=' + cursor,
{
credentials: 'same-origin',
signal: mine.signal,
headers: cursor ? { 'Last-Event-ID': String(cursor) } : {},
},
);
if (!response.ok)
throw Object.assign(new Error('事件连接失败'), { status: response.status });
if (!/^text\/event-stream/.test(response.headers.get('content-type') || ''))
throw new Error('事件协议无效');
polling = false;
clearTimeout(pollTimer);
clearTimeout(probeTimer);
const reader = response.body.getReader(),
decoder = new TextDecoder();
resetIdle();
while (alive()) {
const { done, value } = await reader.read();
if (done) break;
resetIdle();
buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, '\n');
if (buffer.length > 256 * 1024) throw new Error('事件数据超过限制');
let end;
while ((end = buffer.indexOf('\n\n')) >= 0) {
const frame = buffer.slice(0, end);
buffer = buffer.slice(end + 2);
const type = frame
.split('\n')
.find((l) => l.startsWith('event:'))
?.slice(6)
.trim();
const data = frame
.split('\n')
.filter((l) => l.startsWith('data:'))
.map((l) => l.slice(5).trimStart())
.join('\n');
if (type === 'auth_required')
throw Object.assign(new Error('登录或权限已变化'), { status: 401 });
if (type === 'conversation_removed')
throw Object.assign(new Error('会话已移入回收站或删除'), { status: 404 });
if (type === 'conversation_updated') {
await onChange();
continue;
}
if (type === 'stream_error') throw new Error('事件服务暂不可用');
if (type === 'assistant_event' && data) {
await consume([JSON.parse(data)]);
failures = 0;
backoff = 0;
}
}
}
if (alive()) throw new Error('事件连接中断');
} catch (error) {
if (!alive() || controller !== mine || auth(error)) return;
mine.abort();
failures++;
const delays = [1000, 2000, 4000, 8000, 15000];
if (failures >= 3) {
beginPolling();
} else
retryTimer = setTimeout(
() => void stream(),
delays[Math.min(backoff++, delays.length - 1)],
);
} finally {
clearTimeout(idleTimer);
}
}
function dispose() {
disposed = true;
controller?.abort();
lifetime.abort();
clearTimeout(retryTimer);
clearTimeout(pollTimer);
clearTimeout(probeTimer);
}
void stream();
return {
dispose,
get cursor() {
return cursor;
},
};
},
};