327 lines
15 KiB
JavaScript
327 lines
15 KiB
JavaScript
const { test } = require('node:test')
|
|
const assert = require('node:assert/strict')
|
|
const fs = require('node:fs')
|
|
const path = require('node:path')
|
|
const ts = require('typescript')
|
|
|
|
// 房间号是云端录制的前提:宿主没有绑定房间,服务端就不会发起合流录制,
|
|
// 回放随之丢失。这里验证房间号可以从引擎返回值 / 引擎实例兜底得到,
|
|
// 而不是只依赖 CallKit Store 里可能晚一拍或被清空的 ROOM_ID。
|
|
const source = fs.readFileSync(path.join(__dirname, '../src/main.ts'), 'utf8')
|
|
const ast = ts.createSourceFile('main.ts', source, ts.ScriptTarget.Latest, true)
|
|
const names = new Set([
|
|
'normalizeRoomId', 'normalizeRoomScalar', 'normalizeRoomPair', 'extractRoomFromEngineResult',
|
|
'currentCallEngine', 'readRoomIdFromEngine', 'handleEngineRoomEvent', 'bindEngineRoomEvents',
|
|
'readRoomId', 'observeRoomId', 'emitRoomId', 'roomBindingResult', 'recordingResult',
|
|
])
|
|
const declarations = ast.statements.filter(node => ts.isFunctionDeclaration(node) && names.has(node.name?.text))
|
|
assert.equal(declarations.length, names.size)
|
|
const compiled = ts.transpileModule(declarations.map(node => node.getText(ast)).join('\n'), {
|
|
compilerOptions: { target: ts.ScriptTarget.ES2022 },
|
|
}).outputText
|
|
|
|
function harness(options = {}) {
|
|
return new Function('options', `${compiled}
|
|
let activeConfig = {userID:'doctor_1',targetUserId:'patient_1',diagnosisId:501};
|
|
let endNotified=false, notice={value:''};
|
|
let emittedRoomId='', pendingRoomId='', boundRoomId='', roomBindingSentAt=0, roomBindingAttempts=0;
|
|
let engineRoomEventsBound=null;
|
|
let now=100000;
|
|
const Date=class extends globalThis.Date { constructor(...args){super(...(args.length?args:[now]))} static now(){return now} };
|
|
const events=[];
|
|
const emit=event=>events.push(event);
|
|
const StoreName={CALL:'call'}, NAME={ROOM_ID:'roomId'};
|
|
const TUIStore={getData(){return options.store}};
|
|
const TUICallKitAPI={getTUICallEngineInstance(){ if(options.engineThrows) throw new Error('no engine'); return options.engine }};
|
|
return {
|
|
events, extractRoomFromEngineResult, readRoomId, observeRoomId, emitRoomId, roomBindingResult,
|
|
bindEngineRoomEvents,
|
|
advance(ms){now+=ms}, bound:()=>boundRoomId, pending:()=>pendingRoomId, notice:()=>notice.value,
|
|
end(){endNotified=true},
|
|
}`)(options)
|
|
}
|
|
|
|
test('engine call result yields the room id, including nested and string forms', () => {
|
|
const h = harness()
|
|
assert.equal(h.extractRoomFromEngineResult({ roomID: 1666328191 }), '1666328191')
|
|
assert.equal(h.extractRoomFromEngineResult({ roomID: 0, strRoomID: 'room-abc' }), 'room-abc')
|
|
assert.equal(h.extractRoomFromEngineResult({ data: { roomId: '42' } }), '42')
|
|
assert.equal(h.extractRoomFromEngineResult({ roomID: 0 }), '')
|
|
assert.equal(h.extractRoomFromEngineResult({ roomID: {} }), '')
|
|
assert.equal(h.extractRoomFromEngineResult(null), '')
|
|
assert.equal(h.extractRoomFromEngineResult('1234'), '')
|
|
})
|
|
|
|
function trtcEngine(room, params) {
|
|
return { getTRTCCloudInstance: () => ({ enterRoomParams: params, _room: room }) }
|
|
}
|
|
|
|
test('the joined TRTC room wins over stale Store data, with Store fallback only without an engine', () => {
|
|
const joined = { isJoined: true, roomId: '123' }
|
|
assert.equal(harness({ store: '77', engine: trtcEngine(joined, { roomId: 123 }) }).readRoomId(), '123')
|
|
assert.equal(harness({ store: '77', engine: null }).readRoomId(), '77')
|
|
assert.equal(harness({ store: 0, engine: trtcEngine(joined, { roomId: 123 }) }).readRoomId(), '123')
|
|
assert.equal(harness({ store: undefined, engine: trtcEngine({ isJoined: true }, { strRoomId: 'str-room' }) }).readRoomId(), 'str-room')
|
|
assert.equal(harness({ store: 0, engine: trtcEngine({ isJoined: true, roomId: 456 }, undefined) }).readRoomId(), '456')
|
|
// The previous call's room lingers on the TRTC instance after leaving: never bind it to the next call.
|
|
assert.equal(harness({ store: 0, engine: trtcEngine({ isJoined: false, roomId: '123' }, { roomId: 123 }) }).readRoomId(), '')
|
|
assert.equal(harness({ store: '123', engine: trtcEngine({ isJoined: false }, { roomId: 123 }) }).readRoomId(), '')
|
|
assert.equal(harness({ store: 0, engine: trtcEngine(undefined, { roomId: 123 }) }).readRoomId(), '')
|
|
assert.equal(harness({ store: '', engine: { getTRTCCloudInstance: () => null } }).readRoomId(), '')
|
|
assert.equal(harness({ store: '', engine: { getTRTCCloudInstance() { throw new Error('gone') } } }).readRoomId(), '')
|
|
assert.equal(harness({ store: '', engine: { _roomId: 123 } }).readRoomId(), '')
|
|
assert.equal(harness({ store: '', engineThrows: true }).readRoomId(), '')
|
|
assert.equal(harness({ store: '', engine: null }).readRoomId(), '')
|
|
})
|
|
|
|
test('the installed TRTCCloud wrapper exposes each call room on its inner v5 instance', () => {
|
|
const inner = { _room: { isJoined: true, roomId: '901' }, enterRoomParams: { roomId: 901 } }
|
|
const engine = { getTRTCCloudInstance: () => ({ _trtc: inner }) }
|
|
const h = harness({ store: 0, engine })
|
|
assert.equal(h.readRoomId(), '901')
|
|
|
|
// TRTC keeps the previous enter parameters after leaving the room.
|
|
inner._room.isJoined = false
|
|
assert.equal(h.readRoomId(), '')
|
|
inner.enterRoomParams = { roomId: 902 }
|
|
inner._room = { isJoined: true, roomId: '902' }
|
|
assert.equal(h.readRoomId(), '902')
|
|
})
|
|
|
|
test('engine call events bind the room even when the Store never learns it', () => {
|
|
const registered = []
|
|
const handlers = new Map()
|
|
const engine = { on: (event, handler) => { registered.push(event); handlers.set(event, handler) } }
|
|
const h = harness({ store: 0, engine })
|
|
h.bindEngineRoomEvents()
|
|
h.bindEngineRoomEvents()
|
|
assert.deepEqual(registered, ['onCallBegin', 'onCallReceived', 'onCallEnd'])
|
|
|
|
handlers.get('onCallBegin')({ roomID: 1643002506, strRoomID: '', callMediaType: 2, callRole: 1 })
|
|
assert.equal(h.events.length, 1)
|
|
assert.equal(h.events[0].event, 'room')
|
|
assert.equal(h.events[0].roomId, '1643002506')
|
|
h.roomBindingResult('1643002506', true, '')
|
|
// The matching onCallEnd is a no-op once bound; payloads without a room are ignored.
|
|
handlers.get('onCallEnd')({ roomID: 1643002506, reason: 'hangup' })
|
|
handlers.get('onCallBegin')({ callMediaType: 2 })
|
|
assert.equal(h.events.length, 1)
|
|
h.end()
|
|
handlers.get('onCallBegin')({ roomID: 7 })
|
|
assert.equal(h.events.length, 1)
|
|
|
|
// Engines without an event API, or none at all, are tolerated.
|
|
harness({ store: 0, engine: {} }).bindEngineRoomEvents()
|
|
harness({ store: 0, engine: null }).bindEngineRoomEvents()
|
|
harness({ store: 0, engineThrows: true }).bindEngineRoomEvents()
|
|
})
|
|
|
|
test('a room learned from calls() is bound once and retried with backoff until acknowledged', () => {
|
|
const h = harness({ store: 0, engine: null })
|
|
assert.equal(h.observeRoomId(h.extractRoomFromEngineResult({ roomID: 900 }) || h.readRoomId()), false)
|
|
assert.deepEqual(h.events.map(e => e.event), ['room'])
|
|
assert.equal(h.events[0].roomId, '900')
|
|
assert.equal(h.events[0].diagnosisId, 501)
|
|
|
|
// Polling the same room inside the backoff window does not spam the host.
|
|
h.observeRoomId('900')
|
|
h.emitRoomId()
|
|
assert.equal(h.events.length, 1)
|
|
|
|
// A failed bind keeps the room pending; after the backoff it is sent again.
|
|
h.roomBindingResult('900', false, '合流录制未启动')
|
|
assert.equal(h.pending(), '900')
|
|
assert.equal(h.bound(), '')
|
|
h.advance(2000)
|
|
h.observeRoomId('900')
|
|
assert.equal(h.events.length, 2)
|
|
|
|
h.roomBindingResult('900', true, '')
|
|
assert.equal(h.bound(), '900')
|
|
assert.equal(h.observeRoomId('900'), true)
|
|
assert.equal(h.events.length, 2)
|
|
// A different room after binding is reported as a mismatch, never re-bound.
|
|
assert.equal(h.observeRoomId('901'), false)
|
|
assert.equal(h.events.length, 2)
|
|
})
|
|
|
|
test('empty room ids and finished calls never emit a bind request', () => {
|
|
const h = harness({ store: 0, engine: null })
|
|
assert.equal(h.observeRoomId(''), false)
|
|
assert.equal(h.observeRoomId('0'), false)
|
|
assert.equal(h.emitRoomId(), false)
|
|
h.end()
|
|
assert.equal(h.observeRoomId('900'), false)
|
|
assert.equal(h.events.length, 0)
|
|
})
|
|
|
|
test('an unsolicited or ended-call binding acknowledgement cannot stop room discovery', () => {
|
|
const h = harness()
|
|
h.roomBindingResult('old-room', true, 'old acknowledgement')
|
|
assert.equal(h.bound(), '')
|
|
assert.equal(h.notice(), '')
|
|
h.observeRoomId('current-room')
|
|
h.end()
|
|
h.roomBindingResult('current-room', true, 'late acknowledgement')
|
|
assert.equal(h.bound(), '')
|
|
})
|
|
|
|
function callCycleHarness() {
|
|
const cycleNames = new Set(['startVideo', 'handleStatusChanged', 'pollRoomId', 'notifyHangup'])
|
|
const cycleSource = ast.statements
|
|
.filter(node => ts.isFunctionDeclaration(node) && cycleNames.has(node.name?.text))
|
|
.map(node => node.getText(ast)).join('\n')
|
|
const cycleCompiled = ts.transpileModule(cycleSource, {
|
|
compilerOptions: { target: ts.ScriptTarget.ES2022 },
|
|
}).outputText
|
|
return new Function(`${compiled}\n${cycleCompiled}
|
|
let activeConfig={SDKAppID:1,userID:'doctor_1',targetUserId:'patient_1',diagnosisId:501};
|
|
let endNotified=true, starting=false, hangupNotification=null, contextGeneration=1, callCycleGeneration=0;
|
|
let emittedRoomId='', pendingRoomId='', boundRoomId='', roomBindingSentAt=0, roomBindingAttempts=0;
|
|
let engineRoomEventsBound=null, chat=null, autoTranscriptionAttemptedGeneration=-1, autoLocalRecordingAttemptedGeneration=-1;
|
|
const phase={value:'ready'}, statusText={value:''}, mode={value:'chat'}, notice={value:''};
|
|
const transcriptionState={value:'idle'}, transcriptionError={value:''}, localRecordingState={value:'idle'};
|
|
let transcriptionSessionId='', transcriptionStorageReady=false, transcriptionFinalized=false;
|
|
let transcriptionFinalizeRequested=false, transcriptionHadInterruption=false, transcriberRunning=false, transcriberRobotId='';
|
|
let localRecordingSessionId='', localRecordingMimeType='';
|
|
const acknowledgedSegmentIds=new Set(), pendingSegments=new Map();
|
|
const clearLiveCaptions=()=>{}, appendVideoCallStatus=()=>{}, nextTick=async()=>{}, unsubscribeTranscriber=()=>{};
|
|
let transcriptionGeneration=0;
|
|
const patientFrameCapture={cancel(){}}, tongueScreenshot={cancel(){}};
|
|
const startTranscription=async()=>{}, startLocalRecording=async()=>{};
|
|
const stopTranscription=async()=>{}, stopLocalRecording=async()=>{};
|
|
const safeErrorMessage=(error)=>error.message;
|
|
let now=100000, onInit=()=>{};
|
|
const Date=class extends globalThis.Date { static now(){return now} };
|
|
const timers=[];
|
|
const window={setTimeout(callback, delay){timers.push({callback, at:now+delay})}};
|
|
const events=[], calls=[], emit=event=>events.push(event);
|
|
const inner={_room:{isJoined:false}, enterRoomParams:{roomId:0}};
|
|
const engine={getTRTCCloudInstance:()=>({_trtc:inner})};
|
|
const StoreName={CALL:'call'}, NAME={ROOM_ID:'roomId'}, TUICallType={VIDEO_CALL:2};
|
|
let storeRoomId=0;
|
|
const TUIStore={getData:()=>storeRoomId};
|
|
const TUICallKitAPI={
|
|
init:async()=>onInit(), getTUICallEngineInstance:()=>engine,
|
|
calls(params){
|
|
handleStatusChanged({newStatus:'dialing-c2c'});
|
|
return new Promise(resolve=>calls.push({params,resolve}));
|
|
},
|
|
};
|
|
return {
|
|
events, calls, startVideo, roomBindingResult, bound:()=>boundRoomId,
|
|
onInit(callback){onInit=callback},
|
|
updateStore(roomId){storeRoomId=roomId;emitRoomId()},
|
|
engineEvent:handleEngineRoomEvent,
|
|
join(roomId){inner._room={isJoined:true,roomId};inner.enterRoomParams={roomId}},
|
|
end(){inner._room.isJoined=false;handleStatusChanged({newStatus:'idle'})},
|
|
advance(ms){
|
|
now+=ms;
|
|
const due=timers.filter(timer=>timer.at<=now);
|
|
for(const timer of due){timers.splice(timers.indexOf(timer),1);timer.callback()}
|
|
},
|
|
};
|
|
`)()
|
|
}
|
|
|
|
const flushPromises = () => new Promise(resolve => setImmediate(resolve))
|
|
|
|
test('three calls in one open page each bind their room while calls() and Store stay pending', async () => {
|
|
const h = callCycleHarness()
|
|
const pendingCalls = []
|
|
for (const room of [901, 902, 903]) {
|
|
pendingCalls.push(h.startVideo())
|
|
await flushPromises()
|
|
assert.equal(h.calls.length, room - 900)
|
|
// The SDK has dispatched but neither resolved calls() nor emitted a room event.
|
|
assert.equal(h.events.filter(e => e.event === 'room').length, room - 901)
|
|
h.join(room)
|
|
h.advance(250)
|
|
await flushPromises()
|
|
const binding = h.events.filter(e => e.event === 'room').at(-1)
|
|
assert.equal(binding.roomId, String(room))
|
|
assert.equal(binding.diagnosisId, 501)
|
|
h.roomBindingResult(String(room), true, '')
|
|
assert.equal(h.bound(), String(room))
|
|
h.end()
|
|
await flushPromises()
|
|
}
|
|
assert.deepEqual(h.events.filter(e => e.event === 'room').map(e => e.roomId), ['901', '902', '903'])
|
|
// Delayed SDK completions after hangup must not report rooms or restore dialing.
|
|
const eventCount = h.events.length
|
|
h.calls.forEach((call, index) => call.resolve({ roomID: 901 + index }))
|
|
await Promise.all(pendingCalls)
|
|
assert.equal(h.events.length, eventCount)
|
|
})
|
|
|
|
test('redial ignores previous completion and acknowledgement, retries only the new room', async () => {
|
|
const h = callCycleHarness()
|
|
const first = h.startVideo()
|
|
await flushPromises()
|
|
h.join(901)
|
|
h.advance(250)
|
|
await flushPromises()
|
|
h.roomBindingResult('901', true, '')
|
|
h.end()
|
|
await flushPromises()
|
|
|
|
h.onInit(() => h.roomBindingResult('901', true, 'late first-call acknowledgement'))
|
|
const second = h.startVideo()
|
|
await flushPromises()
|
|
assert.equal(h.bound(), '')
|
|
h.calls[0].resolve({ roomID: 901 })
|
|
await first
|
|
h.join(902)
|
|
h.advance(250)
|
|
await flushPromises()
|
|
h.roomBindingResult('901', true, '')
|
|
assert.equal(h.bound(), '')
|
|
h.roomBindingResult('902', false, 'temporary failure')
|
|
h.advance(2000)
|
|
await flushPromises()
|
|
assert.deepEqual(h.events.filter(e => e.event === 'room').map(e => e.roomId), ['901', '902', '902'])
|
|
h.roomBindingResult('902', true, '')
|
|
assert.equal(h.bound(), '902')
|
|
h.end()
|
|
await flushPromises()
|
|
h.advance(20000)
|
|
await flushPromises()
|
|
h.calls[1].resolve()
|
|
await second
|
|
assert.equal(h.events.filter(e => e.event === 'room').length, 3)
|
|
})
|
|
|
|
for (const oldStoreArrivesAfterJoin of [false, true]) {
|
|
test(`old SDK completion cannot bind its Store room to a redial (joined=${oldStoreArrivesAfterJoin})`, async () => {
|
|
const h = callCycleHarness()
|
|
const first = h.startVideo()
|
|
await flushPromises()
|
|
h.join(901)
|
|
h.advance(250)
|
|
await flushPromises()
|
|
h.roomBindingResult('901', true, '')
|
|
h.end()
|
|
await flushPromises()
|
|
|
|
const second = h.startVideo()
|
|
await flushPromises()
|
|
if (oldStoreArrivesAfterJoin) h.join(902)
|
|
// CallKit updates ROOM_ID before the outer calls() Promise resolves. Its
|
|
// Store watcher must not relabel the previous room as this call's room.
|
|
h.updateStore(901)
|
|
h.engineEvent({ roomID: 901 })
|
|
h.calls[0].resolve()
|
|
await first
|
|
h.join(902)
|
|
h.advance(250)
|
|
await flushPromises()
|
|
assert.deepEqual(h.events.filter(e => e.event === 'room').map(e => e.roomId), ['901', '902'])
|
|
h.roomBindingResult('902', true, '')
|
|
assert.equal(h.bound(), '902')
|
|
h.end()
|
|
await flushPromises()
|
|
h.calls[1].resolve()
|
|
await second
|
|
})
|
|
}
|