fix(core): enforce bridge PID ownership
This commit is contained in:
3 files changed
+463
-36
No files matched your search
@@ -19,10 +19,15 @@ const log = createLogger('Bridge');
|
|||||||
export class Bridge implements BridgeInterface {
|
export class Bridge implements BridgeInterface {
|
||||||
readonly identity: IdentityService;
|
readonly identity: IdentityService;
|
||||||
private pids_ = new Set<number>();
|
private pids_ = new Set<number>();
|
||||||
|
/** Packet senders keyed by their owning QQ process. Keeping the sender and
|
||||||
|
* PID together is what makes disconnect fallback deterministic: a sender
|
||||||
|
* can never outlive the PID that supplied it. */
|
||||||
|
private readonly packetClientsByPid_ = new Map<number, PacketSender>();
|
||||||
readonly events = new BridgeEventBus();
|
readonly events = new BridgeEventBus();
|
||||||
readonly apis: ApiHub;
|
readonly apis: ApiHub;
|
||||||
private readonly pipeline: IncomingPacketPipeline;
|
private readonly pipeline: IncomingPacketPipeline;
|
||||||
private packetClient_: PacketSender | null = null;
|
private packetClient_: PacketSender | null = null;
|
||||||
|
private packetClientPid_: number | null = null;
|
||||||
private static readonly UPLOADED_FILE_CACHE_MAX = 1024;
|
private static readonly UPLOADED_FILE_CACHE_MAX = 1024;
|
||||||
private uploadedFileMeta_ = new Map<string, UploadedFileMeta>();
|
private uploadedFileMeta_ = new Map<string, UploadedFileMeta>();
|
||||||
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
|
private clientSeq_ = 100000000 + (Date.now() % 1000000000);
|
||||||
@@ -91,12 +96,28 @@ export class Bridge implements BridgeInterface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
dispose(): void {
|
dispose(): void {
|
||||||
this.identity.close();
|
this.pids_.clear();
|
||||||
this.events.clear();
|
this.packetClientsByPid_.clear();
|
||||||
|
this.packetClient_ = null;
|
||||||
|
this.packetClientPid_ = null;
|
||||||
|
try {
|
||||||
|
this.identity.close();
|
||||||
|
} finally {
|
||||||
|
// A close failure must remain visible to the caller, but must not leave
|
||||||
|
// event subscribers attached to a Bridge that Manager already removed.
|
||||||
|
this.events.clear();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Legacy two-step setter retained for external compatibility. It assigns
|
||||||
|
* the sender to the most recently attached PID when one exists. New
|
||||||
|
* BridgeManager code uses bindPid() for an atomic transition. */
|
||||||
setPacketClient(client: PacketSender): void {
|
setPacketClient(client: PacketSender): void {
|
||||||
this.packetClient_ = client;
|
this.packetClient_ = client;
|
||||||
|
const pids = [...this.pids_];
|
||||||
|
const pid = pids.length > 0 ? pids[pids.length - 1]! : null;
|
||||||
|
this.packetClientPid_ = pid;
|
||||||
|
if (pid !== null) this.packetClientsByPid_.set(pid, client);
|
||||||
}
|
}
|
||||||
|
|
||||||
registerCmd(cmd: string, parser: CmdParser): void {
|
registerCmd(cmd: string, parser: CmdParser): void {
|
||||||
@@ -107,17 +128,54 @@ export class Bridge implements BridgeInterface {
|
|||||||
return this.pipeline.handlesCmd(cmd);
|
return this.pipeline.handlesCmd(cmd);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Attach a process without a sender. Retained for compatibility; the
|
||||||
|
* manager uses bindPid() for the atomic PID+sender transition. Re-attaching
|
||||||
|
* deliberately refreshes recency. */
|
||||||
attachPid(pid: number): void {
|
attachPid(pid: number): void {
|
||||||
|
this.pids_.delete(pid);
|
||||||
this.pids_.add(pid);
|
this.pids_.add(pid);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Atomically attach a process and make its sender the active sender.
|
||||||
|
* Set insertion order is the recency order used for fallback. */
|
||||||
|
bindPid(pid: number, client: PacketSender): void {
|
||||||
|
this.attachPid(pid);
|
||||||
|
this.packetClientsByPid_.set(pid, client);
|
||||||
|
this.packetClient_ = client;
|
||||||
|
this.packetClientPid_ = pid;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @internal BridgeManager lookup used when an incoming packet is the first
|
||||||
|
* observation that a live PID changed UIN. */
|
||||||
|
packetClientForPid(pid: number): PacketSender | null {
|
||||||
|
return this.packetClientsByPid_.get(pid) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
detachPid(pid: number): void {
|
detachPid(pid: number): void {
|
||||||
this.pids_.delete(pid);
|
this.pids_.delete(pid);
|
||||||
|
this.packetClientsByPid_.delete(pid);
|
||||||
|
|
||||||
|
if (this.packetClientPid_ !== pid) {
|
||||||
|
// An unscoped legacy sender cannot be associated with a particular PID.
|
||||||
|
// It is safe to retain while another PID exists, but never after the
|
||||||
|
// Bridge becomes empty.
|
||||||
|
if (this.pids_.size === 0) {
|
||||||
|
this.packetClient_ = null;
|
||||||
|
this.packetClientPid_ = null;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.selectFallbackPacketClient(pid);
|
||||||
}
|
}
|
||||||
hasPid(pid: number): boolean { return this.pids_.has(pid); }
|
hasPid(pid: number): boolean { return this.pids_.has(pid); }
|
||||||
get empty(): boolean { return this.pids_.size === 0; }
|
get empty(): boolean { return this.pids_.size === 0; }
|
||||||
get activePid(): number | null {
|
get activePid(): number | null {
|
||||||
for (const pid of this.pids_) return pid;
|
if (this.packetClientPid_ !== null && this.pids_.has(this.packetClientPid_)) {
|
||||||
return null;
|
return this.packetClientPid_;
|
||||||
|
}
|
||||||
|
const pids = [...this.pids_];
|
||||||
|
return pids.length > 0 ? pids[pids.length - 1]! : null;
|
||||||
}
|
}
|
||||||
onPacket(pkt: PacketInfo): void {
|
onPacket(pkt: PacketInfo): void {
|
||||||
this.pipeline.process(pkt);
|
this.pipeline.process(pkt);
|
||||||
@@ -180,6 +238,36 @@ export class Bridge implements BridgeInterface {
|
|||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private selectFallbackPacketClient(detachedPid: number): void {
|
||||||
|
const pids = [...this.pids_];
|
||||||
|
for (let index = pids.length - 1; index >= 0; index -= 1) {
|
||||||
|
const fallbackPid = pids[index]!;
|
||||||
|
const fallback = this.packetClientsByPid_.get(fallbackPid);
|
||||||
|
if (!fallback) continue;
|
||||||
|
|
||||||
|
this.packetClient_ = fallback;
|
||||||
|
this.packetClientPid_ = fallbackPid;
|
||||||
|
log.debug(
|
||||||
|
'packet sender fallback: UIN=%s detached PID=%d fallback PID=%d',
|
||||||
|
this.identity.uin,
|
||||||
|
detachedPid,
|
||||||
|
fallbackPid,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.packetClient_ = null;
|
||||||
|
this.packetClientPid_ = null;
|
||||||
|
if (this.pids_.size > 0) {
|
||||||
|
log.warn(
|
||||||
|
'packet sender unavailable after PID detach: UIN=%s detached PID=%d remaining PIDs=%d',
|
||||||
|
this.identity.uin,
|
||||||
|
detachedPid,
|
||||||
|
this.pids_.size,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
|
async resolveUserUid(uin: number, groupId?: number): Promise<string> {
|
||||||
return this.identity.resolveUid(uin, groupId);
|
return this.identity.resolveUid(uin, groupId);
|
||||||
}
|
}
|
||||||
@@ -224,4 +312,3 @@ export interface ClientKeyInfo {
|
|||||||
}
|
}
|
||||||
export { AiVoiceChatType };
|
export { AiVoiceChatType };
|
||||||
export type { AiVoiceCategory, StrangerStatus };
|
export type { AiVoiceCategory, StrangerStatus };
|
||||||
|
|
||||||
@@ -17,7 +17,6 @@ const log = createLogger('Bridge');
|
|||||||
export class BridgeManager {
|
export class BridgeManager {
|
||||||
private sessions_ = new Map<string, QQSession>();
|
private sessions_ = new Map<string, QQSession>();
|
||||||
private pidToUin_ = new Map<number, string>();
|
private pidToUin_ = new Map<number, string>();
|
||||||
private pidPacketClients_ = new Map<number, PacketSender>();
|
|
||||||
|
|
||||||
private sessionStartedListeners_: SessionStartedCallback[] = [];
|
private sessionStartedListeners_: SessionStartedCallback[] = [];
|
||||||
private sessionClosedListeners_: SessionClosedCallback[] = [];
|
private sessionClosedListeners_: SessionClosedCallback[] = [];
|
||||||
@@ -55,33 +54,16 @@ export class BridgeManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
onPidDisconnected(pid: number): void {
|
onPidDisconnected(pid: number): void {
|
||||||
this.pidPacketClients_.delete(pid);
|
|
||||||
const uin = this.pidToUin_.get(pid);
|
const uin = this.pidToUin_.get(pid);
|
||||||
if (!uin) return;
|
if (!uin) return;
|
||||||
|
|
||||||
this.pidToUin_.delete(pid);
|
this.detachPidFromSession(pid, uin);
|
||||||
const session = this.sessions_.get(uin);
|
|
||||||
if (!session) return;
|
|
||||||
|
|
||||||
session.bridge.detachPid(pid);
|
|
||||||
if (session.bridge.empty) {
|
|
||||||
this.sessions_.delete(uin);
|
|
||||||
log.debug('session closed: UIN=%s', uin);
|
|
||||||
// Fire before dispose() so listeners can still read bridge.identity.
|
|
||||||
this.fireSessionClosed(uin, session.bridge);
|
|
||||||
session.bridge.dispose();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
|
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
|
||||||
if (!isRealUin(uin)) return;
|
if (!isRealUin(uin)) return;
|
||||||
|
|
||||||
this.pidPacketClients_.set(pid, packetClient);
|
const { session, created } = this.bindPid(pid, uin, packetClient, 'login');
|
||||||
|
|
||||||
const { session, created } = this.ensureSession(uin);
|
|
||||||
session.bridge.attachPid(pid);
|
|
||||||
session.bridge.setPacketClient(packetClient);
|
|
||||||
this.pidToUin_.set(pid, uin);
|
|
||||||
|
|
||||||
if (created) {
|
if (created) {
|
||||||
log.debug('session started: UIN=%s', uin);
|
log.debug('session started: UIN=%s', uin);
|
||||||
@@ -93,17 +75,13 @@ export class BridgeManager {
|
|||||||
if (!pkt.uin || !isRealUin(pkt.uin)) return;
|
if (!pkt.uin || !isRealUin(pkt.uin)) return;
|
||||||
const uin = pkt.uin;
|
const uin = pkt.uin;
|
||||||
|
|
||||||
// Ensure session exists
|
// A packet may be the first trustworthy observation that a live PID moved
|
||||||
const { session, created } = this.ensureSession(uin);
|
// to another UIN. Apply the exact same ownership transition as login so a
|
||||||
|
// PID can never remain attached to two Bridges.
|
||||||
// Attach PID if known
|
const client = pkt.pid > 0 ? this.packetClientForPid(pkt.pid) : null;
|
||||||
if (pkt.pid && this.pidPacketClients_.has(pkt.pid)) {
|
const { session, created } = client
|
||||||
session.bridge.attachPid(pkt.pid);
|
? this.bindPid(pkt.pid, uin, client, 'packet')
|
||||||
this.pidToUin_.set(pkt.pid, uin);
|
: this.ensureSession(uin);
|
||||||
|
|
||||||
const client = this.pidPacketClients_.get(pkt.pid);
|
|
||||||
if (client) session.bridge.setPacketClient(client);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Notify session started on first real packet
|
// Notify session started on first real packet
|
||||||
if (created) {
|
if (created) {
|
||||||
@@ -115,6 +93,91 @@ export class BridgeManager {
|
|||||||
session.bridge.onPacket(pkt);
|
session.bridge.onPacket(pkt);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Bind PID + sender as one state transition. If the PID changed accounts,
|
||||||
|
* the old Bridge is fully detached (and, when empty, closed) before the new
|
||||||
|
* Bridge is created. */
|
||||||
|
private bindPid(
|
||||||
|
pid: number,
|
||||||
|
uin: string,
|
||||||
|
packetClient: PacketSender,
|
||||||
|
source: 'login' | 'packet',
|
||||||
|
): { session: QQSession; created: boolean } {
|
||||||
|
const previousUin = this.pidToUin_.get(pid);
|
||||||
|
if (previousUin && previousUin !== uin) {
|
||||||
|
log.warn(
|
||||||
|
'PID ownership changed: PID=%d UIN=%s -> UIN=%s source=%s',
|
||||||
|
pid,
|
||||||
|
previousUin,
|
||||||
|
uin,
|
||||||
|
source,
|
||||||
|
);
|
||||||
|
this.detachPidFromSession(pid, previousUin);
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = this.ensureSession(uin);
|
||||||
|
result.session.bridge.bindPid(pid, packetClient);
|
||||||
|
this.pidToUin_.set(pid, uin);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private packetClientForPid(pid: number): PacketSender | null {
|
||||||
|
const uin = this.pidToUin_.get(pid);
|
||||||
|
if (!uin) return null;
|
||||||
|
|
||||||
|
const session = this.sessions_.get(uin);
|
||||||
|
if (!session) {
|
||||||
|
const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`;
|
||||||
|
log.error(message);
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
const packetClient = session.bridge.packetClientForPid(pid);
|
||||||
|
if (packetClient) return packetClient;
|
||||||
|
|
||||||
|
const message = `BridgeManager invariant violated: PID=${pid} has no sender in UIN=${uin} session`;
|
||||||
|
log.error(message);
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
private detachPidFromSession(pid: number, uin: string): void {
|
||||||
|
const mappedUin = this.pidToUin_.get(pid);
|
||||||
|
if (mappedUin !== uin) {
|
||||||
|
const message = `BridgeManager invariant violated: PID=${pid} detach expected UIN=${uin}, mapped UIN=${mappedUin ?? 'none'}`;
|
||||||
|
log.error(message);
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
const session = this.sessions_.get(uin);
|
||||||
|
if (!session) {
|
||||||
|
const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`;
|
||||||
|
log.error(message);
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!session.bridge.hasPid(pid)) {
|
||||||
|
const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge does not own the PID`;
|
||||||
|
log.error(message);
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
if (!session.bridge.packetClientForPid(pid)) {
|
||||||
|
const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge has no sender for the PID`;
|
||||||
|
log.error(message);
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validation is complete. Mutate both sides only after the ownership
|
||||||
|
// invariant is known to hold, so a fail-fast error preserves the evidence.
|
||||||
|
this.pidToUin_.delete(pid);
|
||||||
|
session.bridge.detachPid(pid);
|
||||||
|
if (!session.bridge.empty) return;
|
||||||
|
|
||||||
|
this.sessions_.delete(uin);
|
||||||
|
log.debug('session closed: UIN=%s', uin);
|
||||||
|
// Fire before dispose() so listeners can still read bridge.identity.
|
||||||
|
this.fireSessionClosed(uin, session.bridge);
|
||||||
|
session.bridge.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
private ensureSession(uin: string): { session: QQSession; created: boolean } {
|
private ensureSession(uin: string): { session: QQSession; created: boolean } {
|
||||||
let session = this.sessions_.get(uin);
|
let session = this.sessions_.get(uin);
|
||||||
if (session) return { session, created: false };
|
if (session) return { session, created: false };
|
||||||
|
|||||||
@@ -0,0 +1,277 @@
|
|||||||
|
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
|
||||||
|
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||||
|
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { BridgeManager } from '../src/bridge/manager';
|
||||||
|
|
||||||
|
const OK_RESULT: SendPacketResult = {
|
||||||
|
success: true,
|
||||||
|
gotResponse: true,
|
||||||
|
errorCode: 0,
|
||||||
|
errorMessage: '',
|
||||||
|
responseData: Buffer.alloc(0),
|
||||||
|
};
|
||||||
|
|
||||||
|
function makeSender() {
|
||||||
|
const sendPacket = vi.fn<PacketSender['sendPacket']>(async () => OK_RESULT);
|
||||||
|
return {
|
||||||
|
client: { sendPacket } satisfies PacketSender,
|
||||||
|
sendPacket,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function packet(pid: number, uin: string): PacketInfo {
|
||||||
|
return {
|
||||||
|
pid,
|
||||||
|
uin,
|
||||||
|
serviceCmd: 'Test.Unhandled',
|
||||||
|
seqId: 1,
|
||||||
|
retCode: 0,
|
||||||
|
fromClient: false,
|
||||||
|
body: Buffer.alloc(0),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('BridgeManager PID ownership', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.spyOn(IdentityService, 'openForUin')
|
||||||
|
.mockImplementation((uin) => IdentityService.memory(uin));
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('detaches a PID from its old UIN before starting its replacement session', () => {
|
||||||
|
const manager = new BridgeManager();
|
||||||
|
const first = makeSender();
|
||||||
|
const second = makeSender();
|
||||||
|
const lifecycle: string[] = [];
|
||||||
|
manager.addSessionStartedListener((uin) => lifecycle.push(`started:${uin}`));
|
||||||
|
manager.addSessionClosedListener((uin) => lifecycle.push(`closed:${uin}`));
|
||||||
|
|
||||||
|
manager.onHookLogin(101, '10001', first.client);
|
||||||
|
const oldBridge = manager.getSession('10001')!.bridge;
|
||||||
|
const dispose = vi.spyOn(oldBridge, 'dispose');
|
||||||
|
|
||||||
|
manager.onHookLogin(101, '20002', second.client);
|
||||||
|
|
||||||
|
expect(lifecycle).toEqual([
|
||||||
|
'started:10001',
|
||||||
|
'closed:10001',
|
||||||
|
'started:20002',
|
||||||
|
]);
|
||||||
|
expect(manager.getSession('10001')).toBeNull();
|
||||||
|
expect(oldBridge.hasPid(101)).toBe(false);
|
||||||
|
expect(dispose).toHaveBeenCalledOnce();
|
||||||
|
expect(manager.getSession('20002')!.bridge.hasPid(101)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps a multi-PID UIN alive and falls back to the remaining sender', async () => {
|
||||||
|
const manager = new BridgeManager();
|
||||||
|
const first = makeSender();
|
||||||
|
const second = makeSender();
|
||||||
|
const closed = vi.fn();
|
||||||
|
manager.addSessionClosedListener(closed);
|
||||||
|
|
||||||
|
manager.onHookLogin(101, '10001', first.client);
|
||||||
|
manager.onHookLogin(202, '10001', second.client);
|
||||||
|
const bridge = manager.getSession('10001')!.bridge;
|
||||||
|
|
||||||
|
expect(bridge.activePid).toBe(202);
|
||||||
|
await bridge.sendRawPacket('Test.BeforeDisconnect', new Uint8Array([1]));
|
||||||
|
expect(second.sendPacket).toHaveBeenCalledOnce();
|
||||||
|
expect(first.sendPacket).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
manager.onPidDisconnected(202);
|
||||||
|
|
||||||
|
expect(manager.getSession('10001')!.bridge).toBe(bridge);
|
||||||
|
expect(bridge.activePid).toBe(101);
|
||||||
|
expect(closed).not.toHaveBeenCalled();
|
||||||
|
await bridge.sendRawPacket('Test.AfterDisconnect', new Uint8Array([2]));
|
||||||
|
expect(first.sendPacket).toHaveBeenCalledOnce();
|
||||||
|
expect(second.sendPacket).toHaveBeenCalledOnce();
|
||||||
|
|
||||||
|
manager.onPidDisconnected(101);
|
||||||
|
expect(manager.getSession('10001')).toBeNull();
|
||||||
|
expect(closed).toHaveBeenCalledOnce();
|
||||||
|
await expect(bridge.sendRawPacket('Test.NoSender', new Uint8Array([3])))
|
||||||
|
.resolves.toMatchObject({
|
||||||
|
success: false,
|
||||||
|
gotResponse: false,
|
||||||
|
errorCode: -1,
|
||||||
|
errorMessage: 'no packet sender attached',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('prefers the most recently rebound live PID, then falls back by recency', async () => {
|
||||||
|
const manager = new BridgeManager();
|
||||||
|
const first = makeSender();
|
||||||
|
const second = makeSender();
|
||||||
|
const third = makeSender();
|
||||||
|
const reboundFirst = makeSender();
|
||||||
|
const started = vi.fn();
|
||||||
|
manager.addSessionStartedListener(started);
|
||||||
|
|
||||||
|
manager.onHookLogin(101, '10001', first.client);
|
||||||
|
manager.onHookLogin(202, '10001', second.client);
|
||||||
|
manager.onHookLogin(303, '10001', third.client);
|
||||||
|
manager.onHookLogin(101, '10001', reboundFirst.client);
|
||||||
|
const bridge = manager.getSession('10001')!.bridge;
|
||||||
|
|
||||||
|
expect(started).toHaveBeenCalledOnce();
|
||||||
|
expect(bridge.activePid).toBe(101);
|
||||||
|
await bridge.sendRawPacket('Test.Rebound', new Uint8Array([1]));
|
||||||
|
expect(reboundFirst.sendPacket).toHaveBeenCalledOnce();
|
||||||
|
|
||||||
|
manager.onPidDisconnected(101);
|
||||||
|
expect(bridge.activePid).toBe(303);
|
||||||
|
await bridge.sendRawPacket('Test.Fallback', new Uint8Array([2]));
|
||||||
|
expect(third.sendPacket).toHaveBeenCalledOnce();
|
||||||
|
|
||||||
|
manager.onPidDisconnected(303);
|
||||||
|
expect(bridge.activePid).toBe(202);
|
||||||
|
await bridge.sendRawPacket('Test.SecondFallback', new Uint8Array([3]));
|
||||||
|
expect(second.sendPacket).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('applies the same ownership transition when a packet reveals a new UIN', async () => {
|
||||||
|
const manager = new BridgeManager();
|
||||||
|
const sender = makeSender();
|
||||||
|
const lifecycle: string[] = [];
|
||||||
|
manager.addSessionStartedListener((uin) => lifecycle.push(`started:${uin}`));
|
||||||
|
manager.addSessionClosedListener((uin) => lifecycle.push(`closed:${uin}`));
|
||||||
|
|
||||||
|
manager.onHookLogin(101, '10001', sender.client);
|
||||||
|
manager.onPacket(packet(101, '20002'));
|
||||||
|
|
||||||
|
expect(lifecycle).toEqual([
|
||||||
|
'started:10001',
|
||||||
|
'closed:10001',
|
||||||
|
'started:20002',
|
||||||
|
]);
|
||||||
|
expect(manager.getSession('10001')).toBeNull();
|
||||||
|
const replacement = manager.getSession('20002')!.bridge;
|
||||||
|
expect(replacement.hasPid(101)).toBe(true);
|
||||||
|
await replacement.sendRawPacket('Test.AfterPacketRebind', new Uint8Array([1]));
|
||||||
|
expect(sender.sendPacket).toHaveBeenCalledOnce();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps the old UIN alive when its active PID moves and a fallback remains', async () => {
|
||||||
|
const manager = new BridgeManager();
|
||||||
|
const fallback = makeSender();
|
||||||
|
const moving = makeSender();
|
||||||
|
const rebound = makeSender();
|
||||||
|
const lifecycle: string[] = [];
|
||||||
|
manager.addSessionStartedListener((uin) => lifecycle.push(`started:${uin}`));
|
||||||
|
manager.addSessionClosedListener((uin) => lifecycle.push(`closed:${uin}`));
|
||||||
|
|
||||||
|
manager.onHookLogin(101, '10001', fallback.client);
|
||||||
|
manager.onHookLogin(202, '10001', moving.client);
|
||||||
|
const oldBridge = manager.getSession('10001')!.bridge;
|
||||||
|
expect(oldBridge.activePid).toBe(202);
|
||||||
|
|
||||||
|
manager.onHookLogin(202, '20002', rebound.client);
|
||||||
|
|
||||||
|
expect(lifecycle).toEqual(['started:10001', 'started:20002']);
|
||||||
|
expect(manager.getSession('10001')!.bridge).toBe(oldBridge);
|
||||||
|
expect(oldBridge.hasPid(202)).toBe(false);
|
||||||
|
expect(oldBridge.activePid).toBe(101);
|
||||||
|
await oldBridge.sendRawPacket('Test.OldUinFallback', new Uint8Array([1]));
|
||||||
|
expect(fallback.sendPacket).toHaveBeenCalledOnce();
|
||||||
|
|
||||||
|
const newBridge = manager.getSession('20002')!.bridge;
|
||||||
|
expect(newBridge.activePid).toBe(202);
|
||||||
|
await newBridge.sendRawPacket('Test.NewUinSender', new Uint8Array([2]));
|
||||||
|
expect(rebound.sendPacket).toHaveBeenCalledOnce();
|
||||||
|
|
||||||
|
manager.onPidDisconnected(202);
|
||||||
|
expect(lifecycle).toEqual([
|
||||||
|
'started:10001',
|
||||||
|
'started:20002',
|
||||||
|
'closed:20002',
|
||||||
|
]);
|
||||||
|
manager.onPidDisconnected(101);
|
||||||
|
expect(lifecycle).toEqual([
|
||||||
|
'started:10001',
|
||||||
|
'started:20002',
|
||||||
|
'closed:20002',
|
||||||
|
'closed:10001',
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not emit another started edge when a PID joins an existing UIN', async () => {
|
||||||
|
const manager = new BridgeManager();
|
||||||
|
const first = makeSender();
|
||||||
|
const second = makeSender();
|
||||||
|
const reboundFirst = makeSender();
|
||||||
|
const started = vi.fn();
|
||||||
|
const closed = vi.fn();
|
||||||
|
manager.addSessionStartedListener(started);
|
||||||
|
manager.addSessionClosedListener(closed);
|
||||||
|
|
||||||
|
manager.onHookLogin(101, '10001', first.client);
|
||||||
|
manager.onHookLogin(202, '20002', second.client);
|
||||||
|
const targetBridge = manager.getSession('20002')!.bridge;
|
||||||
|
|
||||||
|
manager.onHookLogin(101, '20002', reboundFirst.client);
|
||||||
|
|
||||||
|
expect(started).toHaveBeenCalledTimes(2);
|
||||||
|
expect(closed).toHaveBeenCalledOnce();
|
||||||
|
expect(closed).toHaveBeenCalledWith('10001', expect.anything());
|
||||||
|
expect(manager.getSession('10001')).toBeNull();
|
||||||
|
expect(manager.getSession('20002')!.bridge).toBe(targetBridge);
|
||||||
|
expect(targetBridge.activePid).toBe(101);
|
||||||
|
|
||||||
|
manager.onPidDisconnected(101);
|
||||||
|
expect(targetBridge.activePid).toBe(202);
|
||||||
|
await targetBridge.sendRawPacket('Test.ExistingTargetFallback', new Uint8Array([1]));
|
||||||
|
expect(second.sendPacket).toHaveBeenCalledOnce();
|
||||||
|
expect(closed).toHaveBeenCalledOnce();
|
||||||
|
|
||||||
|
manager.onPidDisconnected(202);
|
||||||
|
expect(closed).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('emits exactly one started/closed pair per real lifecycle', () => {
|
||||||
|
const manager = new BridgeManager();
|
||||||
|
const sender = makeSender();
|
||||||
|
const started = vi.fn();
|
||||||
|
const closed = vi.fn();
|
||||||
|
manager.addSessionStartedListener(started);
|
||||||
|
manager.addSessionClosedListener(closed);
|
||||||
|
|
||||||
|
manager.onHookLogin(101, '10001', sender.client);
|
||||||
|
manager.onHookLogin(101, '10001', sender.client);
|
||||||
|
manager.onPacket(packet(101, '10001'));
|
||||||
|
manager.onPacket(packet(101, '10001'));
|
||||||
|
|
||||||
|
expect(started).toHaveBeenCalledOnce();
|
||||||
|
manager.onPidDisconnected(101);
|
||||||
|
manager.onPidDisconnected(101);
|
||||||
|
expect(closed).toHaveBeenCalledOnce();
|
||||||
|
|
||||||
|
manager.onHookLogin(101, '10001', sender.client);
|
||||||
|
manager.onPidDisconnected(101);
|
||||||
|
expect(started).toHaveBeenCalledTimes(2);
|
||||||
|
expect(closed).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fails fast when Manager ownership references a PID whose Bridge sender is missing', () => {
|
||||||
|
const manager = new BridgeManager();
|
||||||
|
const sender = makeSender();
|
||||||
|
manager.onHookLogin(101, '10001', sender.client);
|
||||||
|
|
||||||
|
// Deliberately violate the private ownership invariant through Bridge's
|
||||||
|
// compatibility surface: Manager still maps PID 101 to this UIN, while
|
||||||
|
// Bridge no longer owns either the PID or its sender.
|
||||||
|
manager.getSession('10001')!.bridge.detachPid(101);
|
||||||
|
|
||||||
|
expect(() => manager.onPacket(packet(101, '10001'))).toThrowError(
|
||||||
|
'BridgeManager invariant violated: PID=101 has no sender in UIN=10001 session',
|
||||||
|
);
|
||||||
|
expect(() => manager.onPidDisconnected(101)).toThrowError(
|
||||||
|
'BridgeManager invariant violated: PID=101 is mapped to UIN=10001, but Bridge does not own the PID',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user