A resilient, chunked file system built on SurrealDB.
Store, stream, and manage files of any size using SurrealDB as the backend β with 64 KB chunked storage, configurable rate limiting, multi-factor concurrency control, and a crash-resilient garbage collector.
| Feature | Description |
|---|---|
| π¦ Chunked storage | Files split into 64 KB chunks across a dedicated table |
| π Atomic replacement | Old file data is removed only after a new upload fully commits |
| π§Ή Garbage collector | Incomplete uploads/deletes are cleaned up automatically on init |
| π¦ Rate limiting | Configurable KB/s via TransformStream (no delay) β converted to 64 KB chunks/s internally |
| π Concurrency control | Multi-factor maps keyed by path sub-elements β separate maps for uploads and downloads |
| π Directory semantics | Hierarchical path arrays with cursor-based pagination for listings |
| π SHA3-512 integrity | Hash computed iteratively per chunk during upload β no memory blow-up |
| βοΈ Range reads (skip) | Stream from any byte offset β jump to middle / end / beginning without reading earlier chunks |
| π Web-standard APIs | ReadableStream, TransformStream, TextEncoder, crypto.randomUUID |
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β SurrealFS β
β β
β save() read() readDir() delete() deleteDir() β
β β β β β β β
β βΌ βΌ βΌ βΌ βΌ β
β ββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Control Callback β β
β β β’ Access check β β
β β β’ Rate limit (KB/s) β β
β β β’ Concurrency identifiers β β
β β β’ Size / extension limits β β
β ββββββββββββββββββββββββββββββββββββββββββββββββ β
β β β
β ββββββββββββββββββββββ΄βββββββββββββββββββββ β
β β TransformStream Pipeline β β
β β Input β Chunking (64KB) β Throttle β β
β βββββββββββββββββββββββββββββββββββββββββββ β
β β β
β βββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββ β
β β SurrealDB β β
β β β β
β β surreal_fs_files surreal_fs_chunks β β
β β ββββββββββββββββ βββββββββββββββββββ β β
β β β uri (UNIQUE)β β upload_id β β β
β β β path[] ββββββββββΆβ chunk_index β β β
β β β size β β data β β β
β β β metadata β βββββββββββββββββββ β β
β β β upload_id β β β
β β β status β β β
β β ββββββββββββββββ β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββ β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
import { SurrealFS } from "jsr:@hviana/surreal-fs";// 1. Connect to SurrealDB
const db = new Surreal();
await db.connect("http://localhost:8000/rpc");
await db.signin({ username: "root", password: "root" });
await db.use({ namespace: "myapp", database: "production" });
// 2. Create and initialise SurrealFS
const fs = new SurrealFS(db);
await fs.init(); // Creates tables, indexes, and runs GCconst result = await fs.save({
path: ["users", "user_42", "documents", "report.pdf"],
content: pdfBytes, // Uint8Array, ReadableStream, or string
metadata: { author: "Alice", version: 3 },
});
if ("size" in result) {
console.log(`Saved ${result.size} bytes`);
console.log(`SHA3-512: ${(result as any).hash}`);
}const file = await fs.read({
path: ["users", "user_42", "documents", "report.pdf"],
});
if (file && "content" in file && file.content) {
// Stream directly to the client
return new Response(file.content, {
headers: { "Content-Type": "application/pdf" },
});
// β or β read into memory
const bytes = await SurrealFS.readStream(file.content);
}await fs.delete({
path: ["users", "user_42", "documents", "report.pdf"],
});Create a new SurrealFS instance. The db parameter must be an already-connected
SurrealDB client.
const db = new Surreal();
await db.connect("http://localhost:8000/rpc");
await db.signin({ username: "root", password: "root" });
await db.use({ namespace: "test", database: "test" });
const fs = new SurrealFS(db);Idempotently create the required tables and indexes, then run the garbage collector. Must be called once before any other method. Safe to call on every server startup.
await fs.init();
// Tables created (if not exist):
// β’ surreal_fs_files β file metadata
// β’ surreal_fs_chunks β 64 KB data chunks
//
// Indexes created:
// β’ idx_sfs_files_uri (UNIQUE on uri)
// β’ idx_sfs_files_status (on status)
// β’ idx_sfs_chunks_upload (UNIQUE on upload_id + chunk_index)
// β’ idx_sfs_chunks_upload_id (on upload_id)
//
// Garbage collector cleans up:
// β’ Interrupted uploads (status = "saving")
// β’ Interrupted replacements (pending_upload_id set)
// β’ Interrupted deletions (status = "deleting")Upload a file to SurrealDB.
| Field | Type | Required | Description |
|---|---|---|---|
path |
string[] |
β | Hierarchical path identifying the file |
content |
ReadableStream | Uint8Array | string |
β | File content |
metadata |
Record<string, any> |
β | Arbitrary metadata (max 60 KB) |
control |
(path, saveConcurrencyMap) => SaveControlResult |
β | Access & rate control callback |
| Field | Type | Default | Description |
|---|---|---|---|
accessAllowed |
boolean |
true |
Allow or deny this operation |
kbytesPerSecond |
number |
MAX_SAFE_INTEGER |
Write throughput in KB/s (internally converted to 64 KB chunks/s) |
concurrencyIdentifiers |
string[] |
[] |
Concurrency map keys |
maxFileSizeBytes |
number |
MAX_SAFE_INTEGER |
File size cap |
allowedExtensions |
string[] |
[] |
Empty = all allowed |
Basic save (string content):
await fs.save({
path: ["configs", "app.json"],
content: JSON.stringify({ theme: "dark", lang: "en" }),
});Save with stream content:
const response = await fetch("https://example.com/large-file.zip");
await fs.save({
path: ["downloads", "archive.zip"],
content: response.body!, // ReadableStream
metadata: { source: "https://example.com/large-file.zip" },
});Save with full control:
const result = await fs.save({
path: ["company_abc", "project_x", "assets", "logo.png"],
content: logoBytes,
metadata: { uploadedBy: "user_42", mimeType: "image/png" },
control: (path, concurrencyMap) => {
const companyId = path[0]; // "company_abc"
const projectId = `${path[0]}/${path[1]}`; // "company_abc/project_x"
return {
accessAllowed: userHasPermission(companyId),
kbytesPerSecond: 6400, // ~6.4 MB/s (β100 chunks/s)
concurrencyIdentifiers: [companyId, projectId],
maxFileSizeBytes: 50 * 1024 * 1024, // 50 MB
allowedExtensions: ["png", "jpg", "webp", "svg"],
};
},
});
if ("status" in result && result.status === "error") {
console.error("Upload failed:", result.msg);
} else {
console.log("Upload OK, size:", (result as any).size);
}Atomic file replacement:
// If logo.png already exists, the old chunks are kept until the
// new upload completes, then they are removed in the background.
// If the server crashes mid-upload, the GC cleans up on next init().
await fs.save({
path: ["company_abc", "project_x", "assets", "logo.png"],
content: newLogoBytes,
});Read a single file. Returns a File with a lazy ReadableStream for the
content.
| Field | Type | Required | Description |
|---|---|---|---|
path |
string[] |
β | Path to the file |
control |
(path, readConcurrencyMap) => ReadControlResult |
β | Access & rate control callback |
skip |
number |
β | Byte offset to start streaming from (see Range reads) |
| Field | Type | Default | Description |
|---|---|---|---|
accessAllowed |
boolean |
true |
Allow or deny |
kbytesPerSecond |
number |
MAX_SAFE_INTEGER |
Read throughput in KB/s (internally converted to 64 KB chunks/s) |
concurrencyIdentifiers |
string[] |
[] |
Concurrency map keys |
maxPageSize |
number |
1000 |
Entries per page (for readDir) |
cursor |
any |
undefined |
Pagination cursor (for readDir) |
Basic read:
const file = await fs.read({
path: ["users", "user_42", "documents", "report.pdf"],
});
if (!file) {
console.log("File not found");
} else if ("status" in file) {
console.log("File is busy:", file.status, file.msg);
} else {
console.log("Path:", file.path);
console.log("Size:", file.size, "bytes");
console.log("Metadata:", file.metadata);
const bytes = await SurrealFS.readStream(file.content!);
}Read as string:
const file = await fs.read({ path: ["configs", "app.json"] });
if (file && "content" in file && file.content) {
const json = await SurrealFS.readStreamAsString(file.content);
const config = JSON.parse(json);
console.log(config.theme); // "dark"
}Rate-limited read:
const file = await fs.read({
path: ["videos", "presentation.mp4"],
control: (path, map) => ({
accessAllowed: true,
kbytesPerSecond: 2048, // ~2 MB/s (β32 chunks/s)
concurrencyIdentifiers: ["video-streaming"],
}),
});Serve as HTTP response (Deno / web framework):
async function handleDownload(req: Request): Promise<Response> {
const file = await fs.read({
path: ["public", "assets", "hero.jpg"],
});
if (!file || "status" in file) {
return new Response("Not found", { status: 404 });
}
return new Response(file.content, {
headers: {
"Content-Type": "image/jpeg",
"Content-Length": String(file.size),
},
});
}List all files under a directory prefix, with cursor-based pagination.
| Field | Type | Description |
|---|---|---|
files |
(File | FileStatus)[] |
Files and in-progress operations |
size |
number |
Total byte size |
cursor |
any | undefined |
Pass to the next call for the next page |
List a directory:
const listing = await fs.readDir({
path: ["company_abc", "project_x"],
});
for (const entry of listing.files) {
if ("status" in entry) {
console.log(
`[${entry.status}] ${entry.URIComponent} (${entry.progress} bytes)`,
);
} else {
console.log(`${entry.URIComponent} β ${entry.size} bytes`);
}
}
console.log("Total size:", listing.size, "bytes");Paginated listing:
let cursor: any = undefined;
let page = 1;
do {
const listing = await fs.readDir({
path: ["company_abc"],
control: (_path, _map) => ({
accessAllowed: true,
maxPageSize: 50,
cursor, // pass the cursor from the previous page
}),
});
console.log(`--- Page ${page} (${listing.files.length} files) ---`);
for (const f of listing.files) {
if (!("status" in f)) console.log(f.URIComponent);
}
cursor = listing.cursor;
page++;
} while (cursor);List root (all files):
const everything = await fs.readDir({ path: [] });
console.log(`Total files: ${everything.files.length}`);Delete a single file and all its chunks.
const result = await fs.delete({
path: ["users", "user_42", "temp", "draft.txt"],
});
if (result) {
console.error("Delete failed:", result.msg);
}Recursively delete all files under a directory.
const errors = await fs.deleteDir({
path: ["users", "user_42", "temp"],
});
if (errors.length > 0) {
console.warn(`${errors.length} files could not be deleted`);
}Update the metadata of an existing file. Max 60 KB.
await fs.setMetadata(
["reports", "q4.pdf"],
{
reviewed: true,
reviewer: "Bob",
tags: ["finance", "quarterly"],
},
);Retrieve the metadata of an existing file.
const meta = await fs.getMetadata(["reports", "q4.pdf"]);
console.log(meta?.reviewer); // "Bob"
console.log(meta?.tags); // ["finance", "quarterly"]Encode a path array into a URI-safe string.
fs.pathToURIComponent(["users", "cafΓ© owner", "photo.jpg"]);
// β "users/caf%C3%A9%20owner/photo.jpg"Decode a URI string back into a path array.
fs.URIComponentToPath("users/caf%C3%A9%20owner/photo.jpg");
// β ["users", "cafΓ© owner", "photo.jpg"]Get a snapshot of all in-progress operations.
const statuses = fs.getAllFilesStatuses();
for (const s of statuses) {
console.log(`${s.status}: ${s.URIComponent} β ${s.progress} bytes`);
}Callback fired whenever an operation makes progress or completes.
fs.onFileProgress = (status) => {
const pct = status.progress; // bytes processed
console.log(`[${status.status}] ${status.URIComponent}: ${pct} bytes`);
if (status.msg) {
console.log(` Message: ${status.msg}`);
}
};Inspect the current concurrency counters for debugging.
console.log("Active uploads:", fs.getSaveConcurrencyMap());
// { "company_abc": 2, "company_abc/project_x": 1 }
console.log("Active downloads:", fs.getReadConcurrencyMap());
// { "video-streaming": 5 }SurrealFS.readStream(stream) β Consume a stream into Uint8Array:
const bytes = await SurrealFS.readStream(file.content!);SurrealFS.readStreamAsString(stream) β Consume a stream into a UTF-8
string:
const text = await SurrealFS.readStreamAsString(file.content!);The control callback is the single point of policy enforcement. It receives
the file path and the current concurrency map, and returns limits.
const saveControl = (
path: string[],
concurrencyMap: Record<string, number | undefined>,
) => {
const userId = path[0]; // e.g. "user_42"
const tenantId = path[1]; // e.g. "company_abc"
// Check current load
const userUploads = concurrencyMap[userId] ?? 0;
const tenantUploads = concurrencyMap[tenantId] ?? 0;
return {
accessAllowed: userUploads < 5 && tenantUploads < 20,
kbytesPerSecond: tenantUploads > 10 ? 1600 : 6400, // ~25 vs ~100 chunks/s
concurrencyIdentifiers: [userId, tenantId],
maxFileSizeBytes: 100 * 1024 * 1024,
allowedExtensions: [],
};
};
await fs.save({
path: ["user_42", "company_abc", "data.csv"],
content: csvStream,
control: saveControl,
});Operation starts:
concurrencyMap["user_42"] 1 β 2
concurrencyMap["company_abc"] 3 β 4
Operation ends:
concurrencyMap["user_42"] 2 β 1
concurrencyMap["company_abc"] 4 β 3
Last operation for "user_42" ends:
concurrencyMap["user_42"] 1 β (deleted)
The GC runs automatically when you call init(). It handles three scenarios:
| Scenario | Cause | Action |
|---|---|---|
| Interrupted new upload | Server crash during first save | Delete chunks + file record |
| Interrupted replacement | Server crash during overwrite | Delete new (pending) chunks, keep old file intact |
| Interrupted deletion | Server crash during delete | Finish deleting chunks + file record |
// The GC is resilient: if init() crashes too, running it again
// will simply pick up where it left off. No data is lost.
const fs = new SurrealFS(db);
await fs.init(); // β GC runs here, concurrently| Column | Type | Description |
|---|---|---|
uri |
string |
URI-encoded path (UNIQUE index) |
path |
array<string> |
Original path array |
size |
int |
Total file size in bytes |
metadata |
object |
User-defined metadata |
hash |
string |
SHA3-512 digest of the file (128 hex chars) |
upload_id |
string |
UUID of the current active chunk set |
pending_upload_id |
option<string> |
UUID of an in-progress replacement |
status |
string |
"complete", "saving", or "deleting" |
created_at |
datetime |
Row creation time |
updated_at |
datetime |
Last modification time |
| Column | Type | Description |
|---|---|---|
upload_id |
string |
Links to a file's upload cycle |
chunk_index |
int |
1-based chunk ordering |
data |
bytes |
Raw 64 KB chunk |
-- Files
DEFINE INDEX idx_sfs_files_uri ON surreal_fs_files FIELDS uri UNIQUE;
DEFINE INDEX idx_sfs_files_status ON surreal_fs_files FIELDS status;
-- Chunks
DEFINE INDEX idx_sfs_chunks_upload ON surreal_fs_chunks FIELDS upload_id, chunk_index UNIQUE;
DEFINE INDEX idx_sfs_chunks_upload_id ON surreal_fs_chunks FIELDS upload_id;Uploads flow through a TransformStream pipeline β no delay() calls anywhere:
Input (ReadableStream | Uint8Array | string)
β
βΌ
ββββββββββββββββββββββββββββ
β Chunking TransformStream β β Splits into exact 64 KB pieces
ββββββββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββββ
β Throttle TransformStream β β Enforces chunks/second limit
ββββββββββββββββββββββββββββ
β
βΌ
reader.read() loop β INSERT into surreal_fs_chunks
Downloads use a pull-based ReadableStream piped through the same throttle
transform:
surreal_fs_chunks (cursor-based fetch, 1 row at a time)
β
βΌ
ββββββββββββββββββββββββββββ
β Source ReadableStream β β pull() fetches next chunk from DB
ββββββββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββββ
β Throttle TransformStream β β Enforces chunks/second limit
ββββββββββββββββββββββββββββ
β
βΌ
Consumer (Response body, file writer, etc.)
import { serve } from "https://deno.land/std/http/mod.ts";
const tenantLimits: Record<string, number> = {
free: 10 * 1024 * 1024, // 10 MB
pro: 500 * 1024 * 1024, // 500 MB
enterprise: 10 * 1024 * 1024 * 1024, // 10 GB
};
const uploadControl = (
path: string[],
map: Record<string, number | undefined>,
) => {
const tenantId = path[0];
const plan = getTenantPlan(tenantId); // your lookup function
return {
accessAllowed: true,
kbytesPerSecond: plan === "free" ? 1024 : 16384, // ~16 vs ~256 chunks/s
concurrencyIdentifiers: [tenantId],
maxFileSizeBytes: tenantLimits[plan] ?? tenantLimits.free,
allowedExtensions: [],
};
};
serve(async (req) => {
const url = new URL(req.url);
if (req.method === "PUT") {
const path = url.pathname.split("/").filter(Boolean);
const result = await fs.save({
path,
content: req.body!,
control: uploadControl,
});
return Response.json(result);
}
if (req.method === "GET") {
const path = url.pathname.split("/").filter(Boolean);
const file = await fs.read({ path });
if (!file || "status" in file) {
return new Response("Not found", { status: 404 });
}
return new Response(file.content, {
headers: { "Content-Length": String(file.size) },
});
}
return new Response("Method not allowed", { status: 405 });
});fs.onFileProgress = (status) => {
switch (status.status) {
case "saving":
console.log(
`β¬οΈ Uploading ${status.URIComponent}: ${status.progress} bytes`,
);
break;
case "deleting":
console.log(
`ποΈ Deleting ${status.URIComponent}: ${status.progress} bytes freed`,
);
break;
case "error":
console.error(`β Error on ${status.URIComponent}: ${status.msg}`);
break;
}
};async function backupDir(srcPath: string[], destPath: string[]) {
const listing = await fs.readDir({ path: srcPath });
for (const entry of listing.files) {
if ("status" in entry) continue; // skip in-progress files
const bytes = await SurrealFS.readStream(entry.content!);
const relativePath = entry.path.slice(srcPath.length);
await fs.save({
path: [...destPath, ...relativePath],
content: bytes,
metadata: { ...entry.metadata, backedUpAt: new Date().toISOString() },
});
}
}
await backupDir(
["company_abc", "production"],
["company_abc", "backups", "2025-01-15"],
);Every successful upload computes a SHA3-512 digest of the file content and stores it alongside the file metadata. The digest is computed iteratively as chunks flow through the upload pipeline β the library never materialises the entire payload in memory, so gigabyte-scale uploads hash in constant space.
The hash is exposed on every read and listing, and the Sha3_512 class is
exported so you can reuse it anywhere in your app.
crypto.subtle does not implement SHA3 (Keccak) in any runtime. Instead of
depending on a runtime-specific native API, SurrealFS ships its own
zero-dependency SHA3-512 port (faithfully adapted from
emn178/js-sha3). The implementation uses
only portable TypeScript and works identically on Deno, Node.js, Bun, and the
browser.
// After a save
const result = await fs.save({ path: ["docs", "spec.pdf"], content: bytes });
if ("hash" in result) {
console.log(result.hash); // 128 lowercase hex chars
}
// On read
const file = await fs.read({ path: ["docs", "spec.pdf"] });
if (file && "hash" in file) {
console.log("Stored hash:", file.hash);
}
// In a directory listing
const { files } = await fs.readDir({ path: ["docs"] });
for (const f of files) {
if (!("status" in f)) console.log(f.URIComponent, "β", f.hash);
}import { Sha3_512 } from "jsr:@hviana/surreal-fs";
const h = new Sha3_512();
h.update(new TextEncoder().encode("hello, "));
h.update(new TextEncoder().encode("world"));
console.log(h.hex());
// "840006653e9ac9e95117a15c915caab81662918e925de9e004f774ff82d7079a40d4d27b1b372657c61d46d470304c88c788b3a4527ad074d1dccbee5dbaa99a"| Method | Description |
|---|---|
new Sha3_512() |
Create a fresh hasher. |
.update(bytes: Uint8Array) |
Absorb more bytes. May be called repeatedly. |
.hex(): string |
Finalise and return 128-char lowercase hex digest. |
β οΈ After.hex()the instance is sealed β further.update()calls throw.
const file = await fs.read({ path: ["docs", "spec.pdf"] });
if (file && "content" in file && file.content && file.hash) {
const verifier = new Sha3_512();
for await (const chunk of file.content as any) verifier.update(chunk);
if (verifier.hex() !== file.hash) {
throw new Error("Integrity check failed!");
}
}The read() method accepts an optional skip parameter that starts the
content stream at an arbitrary byte offset. This is a true range read β
chunks before the skip point are never loaded from the database.
File (bytes): ββββββββββββ¬βββββββββββ¬βββββββββββ¬βββββββββββ¬ββββββ
β chunk 1 β chunk 2 β chunk 3 β chunk 4 β β¦ β
β 64 KB β 64 KB β 64 KB β 64 KB β β
ββββββββββββ΄βββββββββββ΄βββββββββββ΄βββββββββββ΄ββββββ
β² skip = 150 000
β
Start stream here:
β’ chunk_index starts at 3
β’ first chunk sliced from offset (150000 mod 65536) = 18 928
β’ chunks 1 & 2 are never fetched
skip value |
Behaviour |
|---|---|
0 or undefined |
Stream the full file (default). |
0 < skip < size |
Start streaming at byte skip. |
skip >= size |
Clamped to size β empty stream. |
skip < 0 |
Treated as 0. |
The reported file.size and file.hash always refer to the full file β
they do not change based on the skip offset.
Jump to the middle of a large video:
const file = await fs.read({
path: ["videos", "movie.mp4"],
skip: Math.floor(fileSize / 2),
});
for await (const chunk of file!.content as any) {
// Playback starts at the halfway point.
}Read only the last 1 KB (file trailer):
const meta = await fs.getMetadata(["archives", "big.zip"]);
const size = (await fs.read({ path: ["archives", "big.zip"] }))!.size!;
const tail = await fs.read({
path: ["archives", "big.zip"],
skip: Math.max(0, size - 1024),
});
const bytes = await SurrealFS.readStream(tail!.content!);Resume an interrupted download:
const downloaded = bytesAlreadyOnDisk(); // your bookkeeping
const file = await fs.read({
path: ["releases", "installer.bin"],
skip: downloaded,
});
// Continue streaming from exactly where you left off.HTTP Range: bytes=START- handling:
async function handleRange(req: Request, path: string[]): Promise<Response> {
const range = req.headers.get("Range") ?? "";
const match = range.match(/^bytes=(\d+)-/);
const skip = match ? Number(match[1]) : 0;
const file = await fs.read({ path, skip });
if (!file || "status" in file) {
return new Response("Not found", { status: 404 });
}
const total = file.size;
const status = skip > 0 ? 206 : 200;
return new Response(file.content, {
status,
headers: {
"Accept-Ranges": "bytes",
"Content-Length": String(total - skip),
...(skip > 0 &&
{ "Content-Range": `bytes ${skip}-${total - 1}/${total}` }),
},
});
}π‘ The skip is chunk-aware: only the chunk containing the starting byte and everything after it is ever fetched. For a 10 GB file,
skip = 9_000_000_000reads a single chunk before the stream starts producing output.
MIT β Created by Henrique Emanoel Viana