refactor: split monolith into 3 microservices (frontend, backend, discord-gateway)

- Extract services into services/{frontend,backend,discord-gateway}
- Create packages/shared/ for shared logger, errors, utils, types
- Setup Modular MVC pattern in backend (controller→service→repository)
- Setup event-driven architecture in discord-gateway with Redis pub/sub
- Move Docker files to infra/docker/ with per-service Dockerfiles
- Update docker-compose.yml to use Traefik-only routing (no port exposes)
- Update GitHub Actions deploy workflow for multi-service matrix build
- Fix all import paths and resolve type errors across all services
- All 3 services pass tsc --noEmit clean

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
MythEclipse
2026-06-01 21:44:29 +07:00
co-authored by Claude Opus 4.8
parent bda8304bb9
commit c48a0c5e3b
193 changed files with 16879 additions and 1158 deletions
@@ -0,0 +1,86 @@
// ─── Audio playback hook — receives PCM from WebSocket and plays through Web Audio API ──
import { useCallback, useRef, useState } from "react";
const SAMPLE_RATE = 24000;
const CHANNELS = 1;
export function useAudioPlayback() {
const [isListening, setIsListening] = useState(false);
const [levels, setLevels] = useState<number[]>(
Array.from({ length: 32 }, () => 0.04),
);
const audioContextRef = useRef<AudioContext | null>(null);
const userTimelinesRef = useRef(new Map<number, number>());
const handleIncomingPcm = useCallback(
(data: ArrayBuffer) => {
const headerView = new DataView(data, 0, 4);
const userIdHash = headerView.getInt32(0, true);
const audioData = data.slice(4);
const int16Array = new Int16Array(audioData);
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 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,
SAMPLE_RATE,
);
audioBuffer.getChannelData(0).set(float32Array);
const source = audioContext.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioContext.destination);
const currentTime = audioContext.currentTime;
let nextStart = userTimelinesRef.current.get(userIdHash) || 0;
if (nextStart < currentTime) nextStart = currentTime + 0.05;
source.start(nextStart);
userTimelinesRef.current.set(
userIdHash,
nextStart + audioBuffer.duration,
);
},
[isListening],
);
const toggleListening = useCallback(async () => {
if (isListening) {
await audioContextRef.current?.suspend();
userTimelinesRef.current.clear();
setIsListening(false);
return;
}
const AudioContextCtor =
window.AudioContext ||
(window as unknown as { webkitAudioContext: typeof AudioContext })
.webkitAudioContext;
audioContextRef.current ??= new AudioContextCtor({
sampleRate: SAMPLE_RATE,
});
await audioContextRef.current.resume();
setIsListening(true);
}, [isListening]);
return {
isListening,
levels,
handleIncomingPcm,
toggleListening,
audioContextRef,
};
}
@@ -0,0 +1,63 @@
// ─── Audio transmit hook — captures mic, encodes to PCM, sends via WebSocket ──
import { useCallback, useRef, useState } from "react";
const SAMPLE_RATE = 24000;
export function useAudioTransmit(socketRef: {
readonly current: WebSocket | null;
}) {
const [isStreaming, setIsStreaming] = useState(false);
const streamRef = useRef<MediaStream | null>(null);
const audioContextRef = useRef<AudioContext | null>(null);
const processorRef = useRef<ScriptProcessorNode | null>(null);
const stop = useCallback(() => {
setIsStreaming(false);
if (processorRef.current) {
processorRef.current.disconnect();
processorRef.current = null;
}
if (audioContextRef.current) {
audioContextRef.current.close();
audioContextRef.current = null;
}
if (streamRef.current) {
for (const track of streamRef.current.getTracks()) track.stop();
streamRef.current = null;
}
}, []);
const start = useCallback(async () => {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
streamRef.current = stream;
setIsStreaming(true);
const AudioContextCtor =
window.AudioContext ||
(window as unknown as { webkitAudioContext: typeof AudioContext })
.webkitAudioContext;
const audioContext = new AudioContextCtor({ sampleRate: SAMPLE_RATE });
audioContextRef.current = audioContext;
const source = audioContext.createMediaStreamSource(stream);
const processor = audioContext.createScriptProcessor(4096, 1, 1);
processorRef.current = processor;
source.connect(processor);
processor.connect(audioContext.destination);
processor.onaudioprocess = (event) => {
if (!socketRef.current || socketRef.current.readyState !== WebSocket.OPEN)
return;
const inputData = event.inputBuffer.getChannelData(0);
const pcmData = new Int16Array(inputData.length);
for (let i = 0; i < inputData.length; i++)
pcmData[i] = Math.max(-1, Math.min(1, inputData[i])) * 32767;
// BUG 2 FIX: slice() to create independent copy of the ArrayBuffer
socketRef.current.send(pcmData.buffer.slice(0));
};
}, [socketRef]);
const toggle = useCallback(async () => {
if (isStreaming) stop();
else await start();
}, [isStreaming, start, stop]);
return { isStreaming, toggle, stop, start };
}
@@ -0,0 +1,61 @@
// ─── Validated localStorage hook with shape checking ────────────────────────
import { useCallback, useState } from "react";
interface ShapeValidator<T> {
/** Returns true if the parsed value matches the expected shape */
validate: (value: unknown) => value is T;
/** Default value when storage is empty or invalid */
defaults: T;
}
export function useLocalStorage<T>(key: string, validator: ShapeValidator<T>) {
const [value, setValue] = useState<T>(() => loadStored(key, validator));
const update = useCallback(
(patch: T | ((prev: T) => T)) => {
setValue((prev) => {
const next =
typeof patch === "function" ? (patch as (prev: T) => T)(prev) : patch;
try {
localStorage.setItem(key, JSON.stringify(next));
} catch {
// ignore quota errors
}
return next;
});
},
[key],
);
return { value, setValue: update };
}
function loadStored<T>(key: string, validator: ShapeValidator<T>): T {
try {
const raw = localStorage.getItem(key);
if (!raw) return validator.defaults;
const parsed = JSON.parse(raw) as unknown;
if (validator.validate(parsed)) return parsed;
return validator.defaults;
} catch {
return validator.defaults;
}
}
// ─── Pre-built validators for common shapes ─────────────────────────────────
export function recordValidator(): ShapeValidator<Record<string, unknown>> {
return {
validate: (v): v is Record<string, unknown> =>
typeof v === "object" && v !== null && !Array.isArray(v),
defaults: {},
};
}
export function uiStateValidator(): ShapeValidator<Record<string, unknown>> {
return {
validate: (v): v is Record<string, unknown> =>
typeof v === "object" && v !== null && !Array.isArray(v),
defaults: { activeTab: "live" },
};
}
@@ -0,0 +1,19 @@
import { useCallback } from "react";
import type { UIState } from "../../entities/ui/types";
import { uiStateValidator, useLocalStorage } from "./useLocalStorage";
export function useUIState() {
const { value: uiState, setValue: setUIState } = useLocalStorage<UIState>(
"bete-dashboard-ui-state",
uiStateValidator(),
);
const patchUIState = useCallback(
(patch: Partial<UIState>) => {
setUIState((prev) => ({ ...prev, ...patch }));
},
[setUIState],
);
return { uiState, setUIState, patchUIState, loading: false, error: null };
}