fix timeout issue (maybe?)

This commit is contained in:
Schluffe committed 2026-10-16 12:01:43 +02:00
1 parent 95e4a879b9
commit b7f47531b7
7 files changed
+397 -5

No files matched your search

+28 -4
View File
@@ -6,6 +6,7 @@ import { computed, onBeforeUnmount, ref } from 'vue';
import NetworkSettings from './NetworkSettings.vue';
import { acceptAnswerCode, createAnswerCode, createOfferCode, createPeerConnection, fetchTurnOptions, iceConfiguration, getFingerprints, MAX_SIGNAL_LENGTH, STUN_PROVIDERS } from '../lib/webrtc.ts';
import { FILE_LIMIT, MEMORY_LIMIT, Transfer, validateMetadata } from '../lib/transfer.ts';
import { ConnectionDiagnostics } from '../lib/connection-diagnostics.ts';
type Step = 'idle' | 'gathering' | 'offer-ready' | 'answer-ready' | TransferState;
interface Session {
@@ -14,6 +15,7 @@ interface Session {
file: File | null;
controller: AbortController;
transfer: Transfer | null;
diagnostics: ConnectionDiagnostics;
timer?: ReturnType<typeof setTimeout>;
}
@@ -31,6 +33,8 @@ const incoming = ref<FileMetadata | null>(null);
const downloadUrl = ref('');
const choosing = ref(false);
const dragover = ref(false);
const diagnosticLines = ref<string[]>([]);
let latestDiagnostics: ConnectionDiagnostics | null = null;
const iceEndpoint = location.protocol === 'file:' ? '' : import.meta.env.VITE_ICE_ENDPOINT || '';
const defaultStun = location.protocol === 'file:' ? '' : import.meta.env.VITE_STUN_URL || '';
const settings = ref<NetworkSettingsModel>({ stunChoice: defaultStun ? 'custom' : 'pagequit', customStun: defaultStun, allowTurn: false, managedTurn: !!iceEndpoint, turnUrl: '', username: '', credential: '' });
@@ -64,13 +68,16 @@ function dispose() {
active = null;
if (!old) return;
clearTimeout(old.timer);
// Start the snapshot before aborting/closing anything; close the peer after
// stats resolve (bounded to 300 ms), so failure evidence remains available.
void old.diagnostics.finish(() => old.pc.close());
old.controller.abort();
old.transfer?.close();
old.pc.ondatachannel = old.pc.onconnectionstatechange = null;
old.pc.close();
}
function reset(keepNetwork = false) {
dispose(); revokeDownload(); clearTimeout(copyTimer);
latestDiagnostics = null; diagnosticLines.value = [];
managedCredentials.value = null;
if (!keepNetwork) settings.value.allowTurn = false;
inputCode.value = outputCode.value = error.value = '';
@@ -80,6 +87,7 @@ function reset(keepNetwork = false) {
}
function fail(session: Session, err: unknown) {
if (active !== session) return;
session.diagnostics.record('session failed');
dispose(); revokeDownload();
managedCredentials.value = null;
fps.value = incoming.value = null;
@@ -102,7 +110,7 @@ function attach(session: Session, channel: RTCDataChannel) {
}
session.transfer = new Transfer(channel, {
file: props.sending ? session.file : null,
onState: state => { if (active === session) step.value = state; },
onState: state => { if (active === session) { step.value = state; session.diagnostics.record(`transfer ${state}`); } },
onMeta: meta => { if (active === session) incoming.value = meta; },
onProgress: (bytes, size) => { if (active === session) progress.value = Math.min(99, Math.floor(bytes / Math.max(size, 1) * 100)); },
onComplete: ({ blob }) => {
@@ -131,7 +139,12 @@ function start() {
};
// Fetch managed credentials before gathering, while retaining normal cancellation.
const pc = createPeerConnection(iceEndpoint && options.managedTurn ? { ...options, allowTurn: false } : options);
const session: Session = { pc, options, file: file.value, controller: new AbortController(), transfer: null };
let diagnostics: ConnectionDiagnostics;
diagnostics = new ConnectionDiagnostics(pc, lines => {
if (latestDiagnostics === diagnostics) diagnosticLines.value = lines;
});
latestDiagnostics = diagnostics; diagnosticLines.value = [...diagnostics.lines];
const session: Session = { pc, options, file: file.value, controller: new AbortController(), transfer: null, diagnostics };
active = session;
session.timer = setTimeout(() => fail(session, new Error('Connection timed out. Start again with new codes.')), 5 * 60 * 1000);
pc.ondatachannel = event => attach(session, event.channel);
@@ -163,6 +176,8 @@ async function createCode() {
const code = props.sending ? await createOfferCode(session.pc, options) : await createAnswerCode(session.pc, pasted, options);
if (active !== session) return;
outputCode.value = code;
session.diagnostics.record(props.sending ? 'offer ready' : 'answer ready');
session.diagnostics.descriptions();
if (!props.sending) fps.value = getFingerprints(session.pc, options);
step.value = props.sending ? 'offer-ready' : 'answer-ready';
} catch (err) {
@@ -178,6 +193,9 @@ async function useAnswer() {
try {
await acceptAnswerCode(session.pc, inputCode.value, session.options);
if (active !== session) return;
session.diagnostics.record('answer applied');
session.diagnostics.descriptions();
void session.diagnostics.capture();
fps.value = getFingerprints(session.pc, session.options);
} catch (err) {
if (active !== session) return;
@@ -281,8 +299,14 @@ onBeforeUnmount(() => { dispose(); revokeDownload(); clearTimeout(copyTimer); })
<div v-if="progress > 0 || step === 'done'" class="progress" role="progressbar" :aria-valuenow="progress" aria-valuemin="0" aria-valuemax="100" aria-label="Transfer progress"><div :style="{ width: progress + '%' }"></div></div>
<p class="status" role="status">{{ status }}</p>
<p v-if="error" class="error" role="alert">{{ error }}</p>
<details v-if="diagnosticLines.length">
<summary>Connection diagnostics</summary>
<p class="status">Candidate types and check counters only; no addresses, connection codes, credentials or filenames. Missing counters appear as ?. These details remain available after failure.</p>
<label class="step" for="connection-diagnostics">Diagnostic log (select and copy)</label>
<textarea id="connection-diagnostics" :value="diagnosticLines.join('\n')" readonly rows="12" @focus="selectCode" />
</details>
<div v-if="downloadUrl && incoming" class="file-chip"><span>{{ incoming.name }}</span><a class="download" :href="downloadUrl" :download="incoming.name">Save file</a></div>
<button v-if="step !== 'idle'" @click="reset()">{{ busy ? 'Cancel connection' : 'Reset' }}</button>
<p class="status">Switching tabs cancels an active transfer. Keep this tab open until receipt is confirmed.</p>
<p class="status">Switching HellCon’s Send/Receive mode cancels the connection. You can switch to your messenger to copy and paste codes; keep this page open until receipt is confirmed.</p>
</div>
</template>
+107
View File
@@ -0,0 +1,107 @@
// Only allowlisted categories and numbers leave this module. Never retain raw
// SDP, candidate addresses/IDs, URLs, credentials, filenames or browser errors.
const candidateTypes = ['host', 'srflx', 'prflx', 'relay'] as const;
const protocols = ['udp', 'tcp'] as const;
const pairStates = ['frozen', 'waiting', 'in-progress', 'failed', 'succeeded'] as const;
const counters = ['requestsSent', 'requestsReceived', 'responsesSent', 'responsesReceived'] as const;
type StatsEntry = Record<string, unknown>;
type Stats = Pick<RTCStatsReport, 'forEach' | 'get'>;
const category = (value: unknown, allowed: readonly string[]) => typeof value === 'string' && allowed.includes(value) ? value : 'unknown';
const count = (value: unknown) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? String(value) : '?';
export function summarizeCandidates(sdp: string | undefined): string {
const counts = { host: 0, srflx: 0, prflx: 0, relay: 0, unknown: 0 };
for (const line of sdp?.split(/\r?\n/) ?? []) {
if (!line.startsWith('a=candidate:')) continue;
const type = category(line.match(/\styp\s+(\S+)/)?.[1], candidateTypes) as keyof typeof counts;
counts[type]++;
}
return Object.entries(counts).map(([type, n]) => `${type}=${n}`).join(' ') +
` end=${sdp?.split(/\r?\n/).includes('a=end-of-candidates') ? 'yes' : 'no'}`;
}
export function summarizeStats(stats: Stats): string[] {
const pairs: StatsEntry[] = [];
const selected = new Set<string>();
const candidates = { local: { host: 0, srflx: 0, prflx: 0, relay: 0, unknown: 0 }, remote: { host: 0, srflx: 0, prflx: 0, relay: 0, unknown: 0 } };
stats.forEach((entry: StatsEntry) => {
if (entry.type === 'transport' && typeof entry.selectedCandidatePairId === 'string') selected.add(entry.selectedCandidatePairId);
if (entry.type === 'candidate-pair') pairs.push(entry);
const side = entry.type === 'local-candidate' ? 'local' : entry.type === 'remote-candidate' ? 'remote' : null;
if (side) candidates[side][category(entry.candidateType, candidateTypes) as keyof typeof candidates.local]++;
});
const endpoint = (id: unknown) => {
const entry = typeof id === 'string' ? stats.get(id) as StatsEntry | undefined : undefined;
return `${category(entry?.candidateType, candidateTypes)}/${category(entry?.protocol, protocols)}`;
};
const lines = (['local', 'remote'] as const).map(side => `${side} stats: ` + Object.entries(candidates[side]).map(([type, n]) => `${type}=${n}`).join(' '));
lines.push(`pairs=${pairs.length}`);
// Put a selected route first, cap output on machines with many interfaces.
const isSelected = (pair: StatsEntry) => typeof pair.id === 'string' && selected.has(pair.id) || pair.selected === true;
pairs.sort((a, b) => Number(isSelected(b)) - Number(isSelected(a)));
for (const pair of pairs.slice(0, 12)) {
lines.push(`pair ${endpoint(pair.localCandidateId)} → ${endpoint(pair.remoteCandidateId)} ${category(pair.state, pairStates)}` +
` selected=${isSelected(pair)} nominated=${pair.nominated === true} ` + counters.map(key => `${key}=${count(pair[key])}`).join(' '));
}
if (pairs.length > 12) lines.push(`pairs omitted=${pairs.length - 12}`);
return lines;
}
export class ConnectionDiagnostics {
readonly lines: string[] = [];
private readonly started = performance.now();
private stopped = false;
private finishing: Promise<void> | undefined;
private readonly listeners: Array<[EventTarget, string, EventListener]> = [];
private readonly pc: RTCPeerConnection;
private readonly update: (lines: string[]) => void;
constructor(pc: RTCPeerConnection, update: (lines: string[]) => void) {
this.pc = pc; this.update = update;
const listen = (target: EventTarget, event: string, listener: EventListener) => {
target.addEventListener(event, listener);
this.listeners.push([target, event, listener]);
};
const state = () => {
this.record(`pc=${category(pc.connectionState, ['new', 'connecting', 'connected', 'disconnected', 'failed', 'closed'])} ice=${category(pc.iceConnectionState, ['new', 'checking', 'connected', 'completed', 'disconnected', 'failed', 'closed'])} gathering=${category(pc.iceGatheringState, ['new', 'gathering', 'complete'])}`);
};
for (const event of ['connectionstatechange', 'iceconnectionstatechange', 'icegatheringstatechange']) listen(pc, event, state);
listen(pc, 'icecandidateerror', event => this.record(`ICE server error=${count((event as RTCPeerConnectionIceErrorEvent).errorCode)}`));
if (typeof document !== 'undefined') {
const visibility = () => this.record(`page=${category(document.visibilityState, ['visible', 'hidden'])}`);
listen(document, 'visibilitychange', visibility);
visibility();
}
state();
}
record(message: string) {
if (this.stopped) return;
this.lines.push(`${((performance.now() - this.started) / 1000).toFixed(1)}s ${message}`);
this.lines.splice(0, Math.max(0, this.lines.length - 80));
this.update([...this.lines]);
}
descriptions() {
this.record(`local code: ${summarizeCandidates(this.pc.localDescription?.sdp)}`);
this.record(`remote code: ${summarizeCandidates(this.pc.remoteDescription?.sdp)}`);
}
async capture() {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
const stats = await Promise.race([
this.pc.getStats(),
new Promise<null>(resolve => { timer = setTimeout(() => resolve(null), 300); }),
]);
if (stats) for (const line of summarizeStats(stats)) this.record(line);
else this.record('stats unavailable: deadline');
} catch { this.record('stats unavailable'); }
finally { clearTimeout(timer); }
}
// Request final stats while the connection is alive. Always close, even when
// getStats rejects or hangs. Reset can start a new session during this wait.
finish(close: () => void) {
return this.finishing ??= this.capture().finally(() => {
this.stopped = true;
for (const [target, event, listener] of this.listeners) target.removeEventListener(event, listener);
close();
});
}
}