refactor(meeting-bot): split configured host wrapper

This commit is contained in:
Vincent Koc committed 2026-08-02 09:14:42 +08:00
1 parent 2506382bed
commit 8bbc19473e
2 files changed
+121 -95

No files matched your search

+111
View File
@@ -0,0 +1,111 @@
import { spawnSync } from "node:child_process";
import type { MeetingNodeHostOptions } from "./node-host.js";
export type MeetingConfiguredNodeHostOptions = Omit<
MeetingNodeHostOptions,
"assertAudioAvailable"
> & {
meetingLabel: string;
outputMentionsAudioDevice(output: string): boolean;
sharePrerequisiteDeadline: boolean;
systemProfilerCommand: string;
};
type MeetingConfiguredNodeHostDeps = {
asRecord(value: unknown): Record<string, unknown>;
createMeetingNodeHost(options: MeetingNodeHostOptions): {
handleCommand(paramsJSON?: string | null): Promise<string>;
};
};
function readSetupCommand(params: Record<string, unknown>, name: string): string[] {
const value = params[name];
if (
!Array.isArray(value) ||
value.length === 0 ||
value.some((entry) => typeof entry !== "string")
) {
throw new Error(`${name} must be a non-empty string array.`);
}
return value as string[];
}
export function createMeetingConfiguredNodeHostImpl(
options: MeetingConfiguredNodeHostOptions,
deps: MeetingConfiguredNodeHostDeps,
) {
const commandExists = (command: string, timeoutMs: number): boolean => {
const result = spawnSync("/bin/sh", ["-lc", 'command -v "$1" >/dev/null 2>&1', "sh", command], {
encoding: "utf8",
timeout: timeoutMs,
});
return result.status === 0;
};
const assertAudioAvailable = (
timeoutMs: number,
commands: readonly (readonly string[])[] = [
options.defaultAudioInputCommand,
options.defaultAudioOutputCommand,
],
) => {
if (process.platform !== "darwin") {
throw new Error(`${options.meetingLabel} talk-back with BlackHole 2ch is macOS-only`);
}
const deadline = Date.now() + timeoutMs;
const commandTimeout = () =>
options.sharePrerequisiteDeadline ? Math.max(1, deadline - Date.now()) : timeoutMs;
const result = spawnSync(options.systemProfilerCommand, ["SPAudioDataType"], {
encoding: "utf8",
timeout: commandTimeout(),
});
const stderr =
result.stderr ??
(result.error
? result.error instanceof Error
? result.error.message
: String(result.error)
: "");
const output = `${result.stdout ?? ""}\n${stderr}`;
if (
(typeof result.status === "number" ? result.status : result.error ? 1 : 0) !== 0 ||
!options.outputMentionsAudioDevice(output)
) {
throw new Error("BlackHole 2ch audio device not found on the node.");
}
for (const argv of commands) {
const command = argv[0];
if (
!command ||
(options.sharePrerequisiteDeadline && Date.now() >= deadline) ||
!commandExists(command, commandTimeout())
) {
throw new Error(`Configured audio command not found on the node: ${command || "<empty>"}`);
}
}
};
const host = deps.createMeetingNodeHost({ ...options, assertAudioAvailable });
return async (paramsJSON?: string | null): Promise<string> => {
if (paramsJSON) {
let raw: unknown;
try {
raw = JSON.parse(paramsJSON) as unknown;
} catch {
throw new Error(`${options.displayName} node host received malformed params JSON.`);
}
const params = deps.asRecord(raw);
if (params.action === "setup") {
const commands = [
readSetupCommand(params, "audioInputCommand"),
readSetupCommand(params, "audioOutputCommand"),
];
if (params.bargeInInputCommand !== undefined) {
commands.push(readSetupCommand(params, "bargeInInputCommand"));
}
assertAudioAvailable(10_000, commands);
return JSON.stringify({ ok: true });
}
}
return await host.handleCommand(paramsJSON);
};
}
+10 -95
View File
@@ -2,6 +2,10 @@ import { spawn, spawnSync, type ChildProcess } from "node:child_process";
import { randomUUID } from "node:crypto";
import { decodeMeetingAudioBase64 } from "./audio-base64.js";
import { terminateMeetingBridgeProcess } from "./bridge-process.js";
import {
createMeetingConfiguredNodeHostImpl,
type MeetingConfiguredNodeHostOptions,
} from "./configured-node-host.js";
import { MeetingNodeAudioPullWaiters } from "./node-audio-pull-waiters.js";
const NODE_BRIDGE_TERMINATION_GRACE_MS = 2_000;
@@ -63,13 +67,6 @@ export type MeetingNodeHostOptions = {
};
};
type MeetingConfiguredNodeHostOptions = Omit<MeetingNodeHostOptions, "assertAudioAvailable"> & {
meetingLabel: string;
outputMentionsAudioDevice(output: string): boolean;
sharePrerequisiteDeadline: boolean;
systemProfilerCommand: string;
};
function readStringArray(value: unknown): string[] | undefined {
if (!Array.isArray(value)) {
return undefined;
@@ -214,10 +211,10 @@ export function createMeetingNodeHost(options: MeetingNodeHostOptions): {
const stopSession = (
session: NodeBridgeSession,
options: { discardQueuedAudio?: boolean } = {},
stopOptions: { discardQueuedAudio?: boolean } = {},
): Promise<void> => {
session.stopping = true;
if (options.discardQueuedAudio) {
if (stopOptions.discardQueuedAudio) {
session.discardQueuedAudioOnStop = true;
if (session.terminalEvictionTimer) {
clearTimeout(session.terminalEvictionTimer);
@@ -739,91 +736,9 @@ export function createMeetingNodeHost(options: MeetingNodeHostOptions): {
};
}
function readSetupCommand(params: Record<string, unknown>, name: string): string[] {
const value = params[name];
if (
!Array.isArray(value) ||
value.length === 0 ||
value.some((entry) => typeof entry !== "string")
) {
throw new Error(`${name} must be a non-empty string array.`);
}
return value as string[];
}
export function createMeetingConfiguredNodeHost(options: MeetingConfiguredNodeHostOptions) {
const commandExists = (command: string, timeoutMs: number): boolean => {
const result = spawnSync("/bin/sh", ["-lc", 'command -v "$1" >/dev/null 2>&1', "sh", command], {
encoding: "utf8",
timeout: timeoutMs,
});
return result.status === 0;
};
const assertAudioAvailable = (
timeoutMs: number,
commands: readonly (readonly string[])[] = [
options.defaultAudioInputCommand,
options.defaultAudioOutputCommand,
],
) => {
if (process.platform !== "darwin") {
throw new Error(`${options.meetingLabel} talk-back with BlackHole 2ch is macOS-only`);
}
const deadline = Date.now() + timeoutMs;
const commandTimeout = () =>
options.sharePrerequisiteDeadline ? Math.max(1, deadline - Date.now()) : timeoutMs;
const result = spawnSync(options.systemProfilerCommand, ["SPAudioDataType"], {
encoding: "utf8",
timeout: commandTimeout(),
});
const stderr =
result.stderr ??
(result.error
? result.error instanceof Error
? result.error.message
: String(result.error)
: "");
const output = `${result.stdout ?? ""}\n${stderr}`;
if (
(typeof result.status === "number" ? result.status : result.error ? 1 : 0) !== 0 ||
!options.outputMentionsAudioDevice(output)
) {
throw new Error("BlackHole 2ch audio device not found on the node.");
}
for (const argv of commands) {
const command = argv[0];
if (
!command ||
(options.sharePrerequisiteDeadline && Date.now() >= deadline) ||
!commandExists(command, commandTimeout())
) {
throw new Error(`Configured audio command not found on the node: ${command || "<empty>"}`);
}
}
};
const host = createMeetingNodeHost({ ...options, assertAudioAvailable });
return async (paramsJSON?: string | null): Promise<string> => {
if (paramsJSON) {
let raw: unknown;
try {
raw = JSON.parse(paramsJSON) as unknown;
} catch {
throw new Error(`${options.displayName} node host received malformed params JSON.`);
}
const params = asRecord(raw);
if (params.action === "setup") {
const commands = [
readSetupCommand(params, "audioInputCommand"),
readSetupCommand(params, "audioOutputCommand"),
];
if (params.bargeInInputCommand !== undefined) {
commands.push(readSetupCommand(params, "bargeInInputCommand"));
}
assertAudioAvailable(10_000, commands);
return JSON.stringify({ ok: true });
}
}
return await host.handleCommand(paramsJSON);
};
return createMeetingConfiguredNodeHostImpl(options, {
asRecord,
createMeetingNodeHost,
});
}