refactor: atomic, DRY, and logging improvements across codebase
- Split llmModerationClient.ts (2170 lines) into 5 focused sub-modules - Split aiAnalyzer.ts (1282 lines) into 4 modular pipelines - Split messages.db.ts (826 lines) into 5 domain-specific modules - Moved shared schema to @bete/shared, eliminated backend duplication - Added createChildLogger to all voice-recording and AI moderation modules - Extracted tryCommandThenFallback, normalizeMediaState, DEFAULT_VOICE_STATUS - Created shared pagination.ts utility, eliminated 5+ cursor-pagination duplications - Created shared messageMapper.ts for row mapping - Standardized backend error handling with asyncHandler - Added frontend createLogger utility and useAsyncAction hook - Added structured logging to frontend hooks, socket, and API client Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
b68789fffc
commit
07032ab521
@@ -7,6 +7,10 @@ import {
|
||||
skipMedia,
|
||||
stopMedia,
|
||||
} from "../../../shared/api/client";
|
||||
import { useAsyncAction } from "../../../shared/hooks/useAsyncAction.js";
|
||||
import { createLogger } from "../../../shared/lib/logger.js";
|
||||
|
||||
const logger = createLogger("use-media-control");
|
||||
|
||||
const emptyMediaState: MediaState = {
|
||||
playing: false,
|
||||
@@ -17,8 +21,7 @@ const emptyMediaState: MediaState = {
|
||||
|
||||
export function useMediaControl() {
|
||||
const [mediaState, setMediaState] = useState<MediaState>(emptyMediaState);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { loading, error, execute, clearError } = useAsyncAction();
|
||||
|
||||
const refreshMedia = useCallback(async () => {
|
||||
const state = await getMediaStatus();
|
||||
@@ -28,71 +31,62 @@ export function useMediaControl() {
|
||||
|
||||
const enqueue = useCallback(
|
||||
async (source: string, mode: "music" | "screen") => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const state = await queueMedia(source, mode);
|
||||
setMediaState(state);
|
||||
return state;
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
setError(message);
|
||||
throw err;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
const result = await execute(() => queueMedia(source, mode));
|
||||
if (result) {
|
||||
setMediaState(result);
|
||||
logger.info("Media queued", { source, mode });
|
||||
} else {
|
||||
logger.error("Failed to queue media", { source, mode });
|
||||
}
|
||||
return result;
|
||||
},
|
||||
[],
|
||||
[execute],
|
||||
);
|
||||
|
||||
const skip = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const state = await skipMedia();
|
||||
setMediaState(state);
|
||||
return state;
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
setError(message);
|
||||
throw err;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
const result = await execute(() => skipMedia());
|
||||
if (result) {
|
||||
setMediaState(result);
|
||||
logger.info("Media skipped");
|
||||
} else {
|
||||
logger.error("Failed to skip media");
|
||||
}
|
||||
}, []);
|
||||
return result;
|
||||
}, [execute]);
|
||||
|
||||
const stop = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const state = await stopMedia();
|
||||
setMediaState(state);
|
||||
return state;
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
setError(message);
|
||||
throw err;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
const result = await execute(() => stopMedia());
|
||||
if (result) {
|
||||
setMediaState(result);
|
||||
logger.info("Media stopped");
|
||||
} else {
|
||||
logger.error("Failed to stop media");
|
||||
}
|
||||
}, []);
|
||||
return result;
|
||||
}, [execute]);
|
||||
|
||||
const setVolume = useCallback(async (volume: number) => {
|
||||
setError(null);
|
||||
try {
|
||||
const state = await setMediaVolume(volume);
|
||||
setMediaState(state);
|
||||
return state;
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
setError(message);
|
||||
throw err;
|
||||
}
|
||||
}, []);
|
||||
const setVolume = useCallback(
|
||||
async (volume: number) => {
|
||||
clearError();
|
||||
try {
|
||||
const state = await setMediaVolume(volume);
|
||||
setMediaState(state);
|
||||
logger.info("Volume set", { volume });
|
||||
return state;
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
logger.error("Failed to set volume", { volume, error: message });
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
[clearError],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
refreshMedia().catch((err) =>
|
||||
setError(err instanceof Error ? err.message : String(err)),
|
||||
logger.error("Failed to refresh media state on mount", {
|
||||
error: String(err),
|
||||
}),
|
||||
);
|
||||
}, [refreshMedia]);
|
||||
|
||||
|
||||
@@ -8,6 +8,10 @@ import {
|
||||
getVoiceChannels,
|
||||
getVoiceStatus,
|
||||
} from "../../../shared/api/client";
|
||||
import { useAsyncAction } from "../../../shared/hooks/useAsyncAction.js";
|
||||
import { createLogger } from "../../../shared/lib/logger.js";
|
||||
|
||||
const logger = createLogger("use-voice-control");
|
||||
|
||||
export function useVoiceControl() {
|
||||
const [guilds, setGuilds] = useState<Guild[]>([]);
|
||||
@@ -19,15 +23,14 @@ export function useVoiceControl() {
|
||||
activeChannelId: null,
|
||||
activeChannelName: null,
|
||||
});
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const { loading, error, execute, clearError } = useAsyncAction();
|
||||
|
||||
const refreshGuilds = useCallback(async () => {
|
||||
setError(null);
|
||||
clearError();
|
||||
const nextGuilds = await getGuilds();
|
||||
setGuilds(nextGuilds);
|
||||
return nextGuilds;
|
||||
}, []);
|
||||
}, [clearError]);
|
||||
|
||||
const refreshVoiceStatus = useCallback(async () => {
|
||||
const status = await getVoiceStatus();
|
||||
@@ -55,44 +58,39 @@ export function useVoiceControl() {
|
||||
return channels;
|
||||
}, []);
|
||||
|
||||
const joinVoice = useCallback(async (guildId: string, channelId: string) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const status = await connectVoice(guildId, channelId);
|
||||
setVoiceStatus(status);
|
||||
return status;
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
setError(message);
|
||||
throw err;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
const joinVoice = useCallback(
|
||||
async (guildId: string, channelId: string) => {
|
||||
const result = await execute(() => connectVoice(guildId, channelId));
|
||||
if (result) {
|
||||
setVoiceStatus(result);
|
||||
logger.info("Connected to voice", { guildId, channelId });
|
||||
} else {
|
||||
logger.error("Failed to connect to voice", { guildId, channelId });
|
||||
}
|
||||
return result;
|
||||
},
|
||||
[execute],
|
||||
);
|
||||
|
||||
const leaveVoice = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const status = await disconnectVoice();
|
||||
setVoiceStatus(status);
|
||||
return status;
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
setError(message);
|
||||
throw err;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
const result = await execute(() => disconnectVoice());
|
||||
if (result) {
|
||||
setVoiceStatus(result);
|
||||
logger.info("Disconnected from voice");
|
||||
} else {
|
||||
logger.error("Failed to disconnect from voice");
|
||||
}
|
||||
}, []);
|
||||
return result;
|
||||
}, [execute]);
|
||||
|
||||
useEffect(() => {
|
||||
refreshGuilds().catch((err) =>
|
||||
setError(err instanceof Error ? err.message : String(err)),
|
||||
logger.error("Failed to refresh guilds on mount", { error: String(err) }),
|
||||
);
|
||||
refreshVoiceStatus().catch((err) =>
|
||||
setError(err instanceof Error ? err.message : String(err)),
|
||||
logger.error("Failed to refresh voice status on mount", {
|
||||
error: String(err),
|
||||
}),
|
||||
);
|
||||
}, [refreshGuilds, refreshVoiceStatus]);
|
||||
|
||||
|
||||
@@ -5,6 +5,9 @@ import {
|
||||
reanalyzeErrorBatch,
|
||||
reanalyzeMessage,
|
||||
} from "../../../shared/api/client";
|
||||
import { createLogger } from "../../../shared/lib/logger.js";
|
||||
|
||||
const logger = createLogger("use-messages");
|
||||
|
||||
const PAGE_SIZE = 100;
|
||||
|
||||
@@ -54,6 +57,7 @@ export function useMessages() {
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
setError(message);
|
||||
logger.error("Failed to fetch messages", { guildId, error: message });
|
||||
throw err;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
@@ -72,6 +76,9 @@ export function useMessages() {
|
||||
setMessages((prev) => [...prev, ...result.data]);
|
||||
setCursor(result.nextCursor);
|
||||
setHasMore(!!result.nextCursor);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
logger.error("Failed to load more messages", { error: message });
|
||||
} finally {
|
||||
setLoadingMore(false);
|
||||
}
|
||||
@@ -106,6 +113,8 @@ export function useMessages() {
|
||||
prev.map((message) => (message.id === id ? snapshot : message)),
|
||||
);
|
||||
}
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
logger.error("Failed to reanalyze message", { id, error: message });
|
||||
throw err;
|
||||
}
|
||||
}, []);
|
||||
@@ -124,10 +133,17 @@ export function useMessages() {
|
||||
: message,
|
||||
),
|
||||
);
|
||||
const { count } = await reanalyzeErrorBatch({
|
||||
guildId: currentGuild.current ?? undefined,
|
||||
});
|
||||
return count;
|
||||
try {
|
||||
const { count } = await reanalyzeErrorBatch({
|
||||
guildId: currentGuild.current ?? undefined,
|
||||
});
|
||||
logger.info("Reanalyze all errors complete", { count });
|
||||
return count;
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
logger.error("Failed to reanalyze error batch", { error: message });
|
||||
throw err;
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
// ─── Shared HTTP client — all API endpoints in one file ──────────────────────
|
||||
|
||||
import type { MessageRecord, PageResult } from "@bete/shared";
|
||||
import { createLogger } from "../lib/logger.js";
|
||||
|
||||
const logger = createLogger("api");
|
||||
|
||||
const BE_API_URL = import.meta.env.VITE_BE_API_URL || "http://localhost:3001";
|
||||
const BE_WS_URL = import.meta.env.VITE_BE_WS_URL || "ws://localhost:3001";
|
||||
@@ -20,6 +23,8 @@ class ApiError extends Error {
|
||||
export async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const password = localStorage.getItem("admin-password");
|
||||
const url = path.startsWith("http") ? path : `${BE_API_URL}${path}`;
|
||||
logger.debug("Request", { method: init?.method ?? "GET", url });
|
||||
|
||||
const res = await fetch(url, {
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
@@ -38,10 +43,13 @@ export async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
} catch {
|
||||
// ignore parse errors
|
||||
}
|
||||
logger.error("Request failed", { url, status: res.status, code, message });
|
||||
throw new ApiError(code, message, res.status);
|
||||
}
|
||||
|
||||
return res.json() as Promise<T>;
|
||||
const result = (await res.json()) as T;
|
||||
logger.debug("Response", { url, status: res.status });
|
||||
return result;
|
||||
}
|
||||
|
||||
export function getWebSocketURL(): string {
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
// ─── Generic async action state hook ──────────────────────────────────────
|
||||
|
||||
import { useCallback, useState } from "react";
|
||||
|
||||
interface AsyncActionState {
|
||||
loading: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export function useAsyncAction() {
|
||||
const [state, setState] = useState<AsyncActionState>({
|
||||
loading: false,
|
||||
error: null,
|
||||
});
|
||||
|
||||
const execute = useCallback(
|
||||
async <T>(fn: () => Promise<T>): Promise<T | null> => {
|
||||
setState({ loading: true, error: null });
|
||||
try {
|
||||
const result = await fn();
|
||||
setState({ loading: false, error: null });
|
||||
return result;
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
setState({ loading: false, error: message });
|
||||
return null;
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const clearError = useCallback(() => {
|
||||
setState((prev) => ({ ...prev, error: null }));
|
||||
}, []);
|
||||
|
||||
return { ...state, execute, clearError };
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
// ─── Audio playback hook — receives PCM from WebSocket and plays through Web Audio API ──
|
||||
import { useCallback, useRef, useState } from "react";
|
||||
import { createLogger } from "../lib/logger.js";
|
||||
|
||||
const logger = createLogger("use-audio-playback");
|
||||
|
||||
const SAMPLE_RATE = 24000;
|
||||
const CHANNELS = 1;
|
||||
@@ -15,56 +18,64 @@ export function useAudioPlayback() {
|
||||
const handleIncomingPcm = useCallback(
|
||||
(data: { userId: string; pcm: string }) => {
|
||||
// Decode base64 PCM data
|
||||
const binaryString = atob(data.pcm);
|
||||
const bytes = new Uint8Array(binaryString.length);
|
||||
for (let i = 0; i < binaryString.length; i++) {
|
||||
bytes[i] = binaryString.charCodeAt(i);
|
||||
}
|
||||
const int16Array = new Int16Array(bytes.buffer);
|
||||
try {
|
||||
const binaryString = atob(data.pcm);
|
||||
const bytes = new Uint8Array(binaryString.length);
|
||||
for (let i = 0; i < binaryString.length; i++) {
|
||||
bytes[i] = binaryString.charCodeAt(i);
|
||||
}
|
||||
const int16Array = new Int16Array(bytes.buffer);
|
||||
|
||||
// Calculate audio levels for visualization
|
||||
let sum = 0;
|
||||
for (const sample of int16Array) sum += Math.abs(sample / 32768);
|
||||
const average = int16Array.length ? sum / int16Array.length : 0;
|
||||
setLevels((prev) =>
|
||||
prev.map((_, index) =>
|
||||
Math.max(
|
||||
0.04,
|
||||
average *
|
||||
(0.5 + Math.sin(index * 0.6 + Date.now() / 140) * 0.35 + 0.65) *
|
||||
5,
|
||||
// Calculate audio levels for visualization
|
||||
let sum = 0;
|
||||
for (const sample of int16Array) sum += Math.abs(sample / 32768);
|
||||
const average = int16Array.length ? sum / int16Array.length : 0;
|
||||
setLevels((prev) =>
|
||||
prev.map((_, index) =>
|
||||
Math.max(
|
||||
0.04,
|
||||
average *
|
||||
(0.5 + Math.sin(index * 0.6 + Date.now() / 140) * 0.35 + 0.65) *
|
||||
5,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
);
|
||||
|
||||
const audioContext = audioContextRef.current;
|
||||
if (!isListening || !audioContext) return;
|
||||
const audioContext = audioContextRef.current;
|
||||
if (!isListening || !audioContext) return;
|
||||
|
||||
// Convert to float32 for Web Audio API
|
||||
const float32Array = new Float32Array(int16Array.length);
|
||||
for (let i = 0; i < int16Array.length; i++)
|
||||
float32Array[i] = int16Array[i] / 32768;
|
||||
// Convert to float32 for Web Audio API
|
||||
const float32Array = new Float32Array(int16Array.length);
|
||||
for (let i = 0; i < int16Array.length; i++)
|
||||
float32Array[i] = int16Array[i] / 32768;
|
||||
|
||||
const audioBuffer = audioContext.createBuffer(
|
||||
CHANNELS,
|
||||
float32Array.length,
|
||||
SAMPLE_RATE,
|
||||
);
|
||||
audioBuffer.getChannelData(0).set(float32Array);
|
||||
const audioBuffer = audioContext.createBuffer(
|
||||
CHANNELS,
|
||||
float32Array.length,
|
||||
SAMPLE_RATE,
|
||||
);
|
||||
audioBuffer.getChannelData(0).set(float32Array);
|
||||
|
||||
const source = audioContext.createBufferSource();
|
||||
source.buffer = audioBuffer;
|
||||
source.connect(audioContext.destination);
|
||||
const source = audioContext.createBufferSource();
|
||||
source.buffer = audioBuffer;
|
||||
source.connect(audioContext.destination);
|
||||
|
||||
// Schedule playback per user to avoid overlaps
|
||||
const currentTime = audioContext.currentTime;
|
||||
let nextStart = userTimelinesRef.current.get(data.userId) || 0;
|
||||
if (nextStart < currentTime) nextStart = currentTime + 0.05;
|
||||
source.start(nextStart);
|
||||
userTimelinesRef.current.set(
|
||||
data.userId,
|
||||
nextStart + audioBuffer.duration,
|
||||
);
|
||||
// Schedule playback per user to avoid overlaps
|
||||
const currentTime = audioContext.currentTime;
|
||||
let nextStart = userTimelinesRef.current.get(data.userId) || 0;
|
||||
if (nextStart < currentTime) nextStart = currentTime + 0.05;
|
||||
source.start(nextStart);
|
||||
userTimelinesRef.current.set(
|
||||
data.userId,
|
||||
nextStart + audioBuffer.duration,
|
||||
);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
logger.error("Failed to decode PCM audio", {
|
||||
userId: data.userId,
|
||||
error: message,
|
||||
});
|
||||
}
|
||||
},
|
||||
[isListening],
|
||||
);
|
||||
@@ -74,6 +85,7 @@ export function useAudioPlayback() {
|
||||
await audioContextRef.current?.suspend();
|
||||
userTimelinesRef.current.clear();
|
||||
setIsListening(false);
|
||||
logger.info("Audio playback paused");
|
||||
return;
|
||||
}
|
||||
const AudioContextCtor =
|
||||
@@ -85,6 +97,7 @@ export function useAudioPlayback() {
|
||||
});
|
||||
await audioContextRef.current.resume();
|
||||
setIsListening(true);
|
||||
logger.info("Audio playback started");
|
||||
}, [isListening]);
|
||||
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
// ─── Client-side structured logger ────────────────────────────────────────
|
||||
|
||||
const LOG_PREFIX = "[Bete]";
|
||||
|
||||
export function createLogger(context: string) {
|
||||
const prefix = `${LOG_PREFIX} [${context}]`;
|
||||
|
||||
return {
|
||||
debug: (msg: string, data?: Record<string, unknown>) => {
|
||||
if (import.meta.env.DEV) console.debug(prefix, msg, data ?? "");
|
||||
},
|
||||
info: (msg: string, data?: Record<string, unknown>) => {
|
||||
console.info(prefix, msg, data ?? "");
|
||||
},
|
||||
warn: (msg: string, data?: Record<string, unknown>) => {
|
||||
console.warn(prefix, msg, data ?? "");
|
||||
},
|
||||
error: (msg: string, data?: Record<string, unknown>) => {
|
||||
console.error(prefix, msg, data ?? "");
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
// ─── WebSocket singleton with reconnect, typed events, and observable status ─
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { createLogger } from "../lib/logger.js";
|
||||
|
||||
const logger = createLogger("socket");
|
||||
|
||||
export type WsStatus = "connecting" | "connected" | "disconnected" | "error";
|
||||
|
||||
@@ -26,6 +29,7 @@ export interface WsHandlers {
|
||||
let _wsInstance: WebSocket | null = null;
|
||||
let _reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let _closed = false;
|
||||
let _reconnectAttempts = 0;
|
||||
const _listeners = new Set<WsHandlers>();
|
||||
const _statusCallbacks = new Set<(s: WsStatus) => void>();
|
||||
|
||||
@@ -41,12 +45,23 @@ function doConnect(): WebSocket {
|
||||
const ws = new WebSocket(url);
|
||||
ws.binaryType = "arraybuffer";
|
||||
dispatchStatus("connecting");
|
||||
logger.info("Connecting", { url });
|
||||
|
||||
ws.addEventListener("open", () => dispatchStatus("connected"));
|
||||
ws.addEventListener("error", () => dispatchStatus("error"));
|
||||
ws.addEventListener("close", () => {
|
||||
ws.addEventListener("open", () => {
|
||||
_reconnectAttempts = 0;
|
||||
dispatchStatus("connected");
|
||||
logger.info("Connected");
|
||||
});
|
||||
ws.addEventListener("error", () => {
|
||||
dispatchStatus("error");
|
||||
logger.error("WebSocket error");
|
||||
});
|
||||
ws.addEventListener("close", (event) => {
|
||||
dispatchStatus("disconnected");
|
||||
logger.info("Disconnected", { code: event.code, reason: event.reason });
|
||||
if (!_closed && _listeners.size > 0) {
|
||||
_reconnectAttempts++;
|
||||
logger.warn("Reconnecting", { attempt: _reconnectAttempts });
|
||||
_reconnectTimer = setTimeout(() => doReconnect(), 2500);
|
||||
}
|
||||
});
|
||||
@@ -108,7 +123,9 @@ function doConnect(): WebSocket {
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// ignore malformed messages
|
||||
logger.error("Failed to parse message", {
|
||||
raw: event.data.slice(0, 200),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user