Download backend/src/persistence.ts from HuggingFaceSwarms/scaling-swarms: direct link, hf CLI and curl.
- Browser
- Download file 6.52 kB
-
https://huggingface.co/spaces/HuggingFaceSwarms/scaling-swarms/resolve/main/backend/src/persistence.ts
- Command line
-
hf download hf://spaces/HuggingFaceSwarms/scaling-swarms/backend/src/persistence.ts
-
curl -L -o persistence.ts https://huggingface.co/spaces/HuggingFaceSwarms/scaling-swarms/resolve/main/backend/src/persistence.ts
6.52 kB
| import { existsSync, readFileSync } from "fs"; | |
| import { join } from "path"; | |
| import * as Y from "yjs"; | |
| import { getDataDir, docPath, sanitizeName, atomicWriteFileSync } from "./utils.js"; | |
| import { | |
| isHfStorageEnabled, | |
| getDatasetId, | |
| setUserToken, | |
| pullDocument, | |
| pullPublishedAssets, | |
| schedulePush, | |
| recordLocalSave, | |
| recordLocalSaveError, | |
| } from "./hf-storage.js"; | |
| const DEFAULT_DOC_NAME = "default"; | |
| const SAVE_DEBOUNCE_MS = 2000; | |
| const saveTimers = new Map<string, { timer: ReturnType<typeof setTimeout>; ydoc: Y.Doc }>(); | |
| const lastSaveTimestamp = new Map<string, number>(); | |
| function saveNow(documentName: string, ydoc: Y.Doc) { | |
| try { | |
| const state = Y.encodeStateAsUpdate(ydoc); | |
| const buf = Buffer.from(state); | |
| atomicWriteFileSync(docPath(documentName), buf); | |
| lastSaveTimestamp.set(documentName, Date.now()); | |
| recordLocalSave(documentName); | |
| console.log(`[persist] saved "${documentName}": ${buf.length} bytes`); | |
| if (isHfStorageEnabled()) { | |
| schedulePush(documentName, buf); | |
| } | |
| } catch (err) { | |
| // A failed local save is the most dangerous silent failure | |
| // because the WS layer already ack'd the edit to the client, | |
| // who therefore sees "Saved" while nothing is on disk. Push | |
| // the error into the status tracker so the SyncIndicator can | |
| // flip to "Local save failed" within a few seconds. | |
| recordLocalSaveError(documentName, err); | |
| console.error(`[persist] failed to save "${documentName}":`, (err as Error).message); | |
| } | |
| } | |
| /** @internal - exported for testing */ | |
| export function debouncedSave(documentName: string, ydoc: Y.Doc) { | |
| const existing = saveTimers.get(documentName); | |
| if (existing) clearTimeout(existing.timer); | |
| // A reloaded document is a new Y.Doc; the unloaded one's pending | |
| // state must reach the disk rather than be dropped with its timer. | |
| if (existing && existing.ydoc !== ydoc) saveNow(documentName, existing.ydoc); | |
| const timer = setTimeout(() => { | |
| saveTimers.delete(documentName); | |
| saveNow(documentName, ydoc); | |
| }, SAVE_DEBOUNCE_MS); | |
| saveTimers.set(documentName, { timer, ydoc }); | |
| } | |
| /** | |
| * Immediately persist every doc whose debounced save hasn't fired | |
| * yet. Called on graceful shutdown BEFORE flushAll(): the last | |
| * keystrokes may still be sitting in a 2s debounce window, and | |
| * flushAll() only pushes what already reached the local disk. | |
| * Skipping this used to lose up to SAVE_DEBOUNCE_MS of edits on | |
| * every SIGTERM (i.e. every HF Space restart). | |
| */ | |
| export function flushLocalSaves() { | |
| const pending = [...saveTimers.entries()]; | |
| saveTimers.clear(); | |
| for (const [name, entry] of pending) { | |
| clearTimeout(entry.timer); | |
| saveNow(name, entry.ydoc); | |
| } | |
| } | |
| /** | |
| * Write a document's pending save now. Hocuspocus calls its store hook | |
| * right before unloading a document whose last connection closed; if | |
| * the save were still debounced, a reconnect within the debounce window | |
| * would load the stale disk copy into a fresh Y.Doc. | |
| */ | |
| export function flushSave(documentName: string) { | |
| const pending = saveTimers.get(documentName); | |
| if (!pending) return; | |
| clearTimeout(pending.timer); | |
| saveTimers.delete(documentName); | |
| saveNow(documentName, pending.ydoc); | |
| } | |
| /** Reset debounce state between tests */ | |
| export function resetSaveTimers() { | |
| for (const entry of saveTimers.values()) clearTimeout(entry.timer); | |
| saveTimers.clear(); | |
| lastSaveTimestamp.clear(); | |
| } | |
| /** | |
| * Load a doc snapshot: local disk first, then the HF dataset. | |
| * | |
| * Fail-closed contract: this function only returns `null` when we | |
| * POSITIVELY know the doc doesn't exist anywhere (no local file, | |
| * and the dataset answered 404). If the local file exists but can't | |
| * be read, or the HF pull fails for any other reason, it THROWS. | |
| * Hocuspocus then refuses to load the document and closes the | |
| * connections - the client stays on "Offline" and keeps retrying. | |
| * That's the only safe answer: silently returning `null` would | |
| * start an editing session on an empty doc whose first save would | |
| * overwrite the real article, locally and then in the dataset. | |
| */ | |
| export async function loadDocState(documentName: string): Promise<Buffer | null> { | |
| const p = docPath(documentName); | |
| if (existsSync(p)) { | |
| // No try/catch: a file that exists but can't be read is a disk | |
| // problem, not a missing doc. Let it throw. | |
| const buf = readFileSync(p); | |
| console.log(`[persist] fetch "${documentName}" from disk: ${buf.length} bytes`); | |
| return buf; | |
| } | |
| console.log(`[persist] fetch "${documentName}": no file on disk`); | |
| // No dataset means deliberate local-only mode. Missing credentials for | |
| // a configured dataset must instead fail closed inside pullDocument. | |
| if (!getDatasetId()) return null; | |
| // Throws on anything that isn't a definitive 404 (see pullDocument). | |
| const data = await pullDocument(documentName); | |
| if (!data) return null; | |
| const buf = Buffer.from(data); | |
| try { | |
| atomicWriteFileSync(p, buf); | |
| console.log(`[persist] pulled "${documentName}" from HF: ${buf.length} bytes`); | |
| } catch (err) { | |
| // Local caching failed but we DO have the data - serve it. | |
| // The next debouncedSave will retry the disk write and surface | |
| // the error through the status tracker if it persists. | |
| console.error(`[persist] failed to cache pulled "${documentName}":`, (err as Error).message); | |
| } | |
| return buf; | |
| } | |
| let _publishedRestored = false; | |
| let _restoreInProgress: Promise<void> | null = null; | |
| export async function ensurePublishedRestored(token?: string): Promise<void> { | |
| const DATA_DIR = getDataDir(); | |
| if (_publishedRestored) return; | |
| if (!getDatasetId()) return; | |
| const publishedPath = join(DATA_DIR, "published", sanitizeName(DEFAULT_DOC_NAME), "index.html"); | |
| if (existsSync(publishedPath)) { | |
| _publishedRestored = true; | |
| return; | |
| } | |
| if (_restoreInProgress) { | |
| await _restoreInProgress; | |
| return; | |
| } | |
| if (token) setUserToken(token); | |
| _restoreInProgress = (async () => { | |
| try { | |
| const found = await pullPublishedAssets(DEFAULT_DOC_NAME, DATA_DIR); | |
| if (found) { | |
| _publishedRestored = true; | |
| console.log("[server] restored published article from HF dataset"); | |
| } | |
| } catch (err) { | |
| console.warn("[server] failed to restore published:", (err as Error).message); | |
| } finally { | |
| _restoreInProgress = null; | |
| } | |
| })(); | |
| await _restoreInProgress; | |
| } | |
| /** Reset restore state between tests */ | |
| export function resetPublishedRestored() { | |
| _publishedRestored = false; | |
| _restoreInProgress = null; | |
| } | |