|
| 1 | +import chokidar, { type FSWatcher } from "chokidar"; |
| 2 | +import { existsSync, statSync } from "node:fs"; |
| 3 | +import type { IncomingMessage, ServerResponse } from "node:http"; |
| 4 | +import { isAbsolute, relative } from "node:path"; |
| 5 | + |
| 6 | +import { isFileBrowserExcludedPath } from "../generated/reference-common.js"; |
| 7 | +import { resolveUserPath } from "../generated/resolve-file.js"; |
| 8 | +import { getGitMetadataWatchPaths } from "../generated/workspace-status.js"; |
| 9 | +import { json } from "./helpers.js"; |
| 10 | + |
| 11 | +interface FileBrowserChangeEvent { |
| 12 | + type: "ready" | "changed"; |
| 13 | + dirPath: string; |
| 14 | + reason: "files" | "git" | "initial"; |
| 15 | + timestamp: number; |
| 16 | +} |
| 17 | + |
| 18 | +interface WatchEntry { |
| 19 | + dirPath: string; |
| 20 | + subscribers: Map<ServerResponse, string>; |
| 21 | + contentWatcher: FSWatcher | null; |
| 22 | + gitWatcher: FSWatcher | null; |
| 23 | + debounceTimer: ReturnType<typeof setTimeout> | null; |
| 24 | +} |
| 25 | + |
| 26 | +const HEARTBEAT_MS = 30_000; |
| 27 | +const DEBOUNCE_MS = 180; |
| 28 | +const watchers = new Map<string, WatchEntry>(); |
| 29 | + |
| 30 | +function serialize(event: FileBrowserChangeEvent): string { |
| 31 | + return `data: ${JSON.stringify(event)}\n\n`; |
| 32 | +} |
| 33 | + |
| 34 | +function isExcludedPath(path: string, root: string): boolean { |
| 35 | + const rel = relative(root, path).replace(/\\/g, "/"); |
| 36 | + if (!rel || rel.startsWith("..") || isAbsolute(rel)) return false; |
| 37 | + return isFileBrowserExcludedPath(rel); |
| 38 | +} |
| 39 | + |
| 40 | +function isValidDirectory(dirPath: string): boolean { |
| 41 | + try { |
| 42 | + return existsSync(dirPath) && statSync(dirPath).isDirectory(); |
| 43 | + } catch { |
| 44 | + return false; |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +function broadcast(entry: WatchEntry, reason: FileBrowserChangeEvent["reason"]): void { |
| 49 | + for (const [res, clientDirPath] of entry.subscribers) { |
| 50 | + const payload = serialize({ |
| 51 | + type: "changed", |
| 52 | + dirPath: clientDirPath, |
| 53 | + reason, |
| 54 | + timestamp: Date.now(), |
| 55 | + }); |
| 56 | + try { |
| 57 | + res.write(payload); |
| 58 | + } catch { |
| 59 | + entry.subscribers.delete(res); |
| 60 | + } |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +function scheduleBroadcast(entry: WatchEntry, reason: "files" | "git"): void { |
| 65 | + if (entry.debounceTimer) clearTimeout(entry.debounceTimer); |
| 66 | + entry.debounceTimer = setTimeout(() => { |
| 67 | + entry.debounceTimer = null; |
| 68 | + broadcast(entry, reason); |
| 69 | + }, DEBOUNCE_MS); |
| 70 | +} |
| 71 | + |
| 72 | +function closeWatcher(entry: WatchEntry): void { |
| 73 | + if (entry.debounceTimer) clearTimeout(entry.debounceTimer); |
| 74 | + void entry.contentWatcher?.close(); |
| 75 | + void entry.gitWatcher?.close(); |
| 76 | + watchers.delete(entry.dirPath); |
| 77 | +} |
| 78 | + |
| 79 | +function releaseSubscriber(entry: WatchEntry, res: ServerResponse): void { |
| 80 | + entry.subscribers.delete(res); |
| 81 | + if (entry.subscribers.size === 0) closeWatcher(entry); |
| 82 | +} |
| 83 | + |
| 84 | +function ensureWatcher(dirPath: string): WatchEntry { |
| 85 | + const existing = watchers.get(dirPath); |
| 86 | + if (existing) return existing; |
| 87 | + |
| 88 | + const entry: WatchEntry = { |
| 89 | + dirPath, |
| 90 | + subscribers: new Map(), |
| 91 | + contentWatcher: null, |
| 92 | + gitWatcher: null, |
| 93 | + debounceTimer: null, |
| 94 | + }; |
| 95 | + |
| 96 | + entry.contentWatcher = chokidar.watch(dirPath, { |
| 97 | + ignoreInitial: true, |
| 98 | + persistent: true, |
| 99 | + ignored: (path) => isExcludedPath(path, dirPath), |
| 100 | + awaitWriteFinish: { |
| 101 | + stabilityThreshold: 120, |
| 102 | + pollInterval: 30, |
| 103 | + }, |
| 104 | + }); |
| 105 | + entry.contentWatcher.on("all", () => scheduleBroadcast(entry, "files")); |
| 106 | + entry.contentWatcher.on("error", () => scheduleBroadcast(entry, "files")); |
| 107 | + |
| 108 | + const gitWatchPaths = getGitMetadataWatchPaths(dirPath); |
| 109 | + if (gitWatchPaths.length > 0) { |
| 110 | + entry.gitWatcher = chokidar.watch(gitWatchPaths, { |
| 111 | + ignoreInitial: true, |
| 112 | + persistent: true, |
| 113 | + awaitWriteFinish: { |
| 114 | + stabilityThreshold: 80, |
| 115 | + pollInterval: 30, |
| 116 | + }, |
| 117 | + }); |
| 118 | + entry.gitWatcher.on("all", () => scheduleBroadcast(entry, "git")); |
| 119 | + entry.gitWatcher.on("error", () => scheduleBroadcast(entry, "git")); |
| 120 | + } |
| 121 | + |
| 122 | + watchers.set(dirPath, entry); |
| 123 | + return entry; |
| 124 | +} |
| 125 | + |
| 126 | +export function handleFileBrowserStreamRequest(req: IncomingMessage, res: ServerResponse, url: URL): boolean { |
| 127 | + if (url.pathname !== "/api/reference/files/stream" || req.method !== "GET") return false; |
| 128 | + |
| 129 | + const rawDirPaths = url.searchParams.getAll("dirPath"); |
| 130 | + if (rawDirPaths.length === 0) { |
| 131 | + json(res, { error: "Missing dirPath parameter" }, 400); |
| 132 | + return true; |
| 133 | + } |
| 134 | + |
| 135 | + const dirPaths: string[] = []; |
| 136 | + const clientDirPaths: string[] = []; |
| 137 | + for (const rawDirPath of rawDirPaths) { |
| 138 | + const dirPath = resolveUserPath(rawDirPath); |
| 139 | + if (!isValidDirectory(dirPath)) { |
| 140 | + json(res, { error: "Invalid directory path" }, 400); |
| 141 | + return true; |
| 142 | + } |
| 143 | + if (!dirPaths.includes(dirPath)) { |
| 144 | + dirPaths.push(dirPath); |
| 145 | + clientDirPaths.push(rawDirPath); |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + const entries = dirPaths.map((dirPath) => ensureWatcher(dirPath)); |
| 150 | + res.writeHead(200, { |
| 151 | + "Content-Type": "text/event-stream", |
| 152 | + "Cache-Control": "no-cache", |
| 153 | + Connection: "keep-alive", |
| 154 | + }); |
| 155 | + res.setTimeout(0); |
| 156 | + for (let i = 0; i < entries.length; i++) { |
| 157 | + const entry = entries[i]!; |
| 158 | + const clientDirPath = clientDirPaths[i] ?? entry.dirPath; |
| 159 | + res.write(serialize({ |
| 160 | + type: "ready", |
| 161 | + dirPath: clientDirPath, |
| 162 | + reason: "initial", |
| 163 | + timestamp: Date.now(), |
| 164 | + })); |
| 165 | + entry.subscribers.set(res, clientDirPath); |
| 166 | + } |
| 167 | + |
| 168 | + const heartbeat = setInterval(() => { |
| 169 | + try { |
| 170 | + res.write(": heartbeat\n\n"); |
| 171 | + } catch { |
| 172 | + for (const entry of entries) releaseSubscriber(entry, res); |
| 173 | + clearInterval(heartbeat); |
| 174 | + } |
| 175 | + }, HEARTBEAT_MS); |
| 176 | + |
| 177 | + res.on("close", () => { |
| 178 | + clearInterval(heartbeat); |
| 179 | + for (const entry of entries) releaseSubscriber(entry, res); |
| 180 | + }); |
| 181 | + return true; |
| 182 | +} |
0 commit comments