8000 GitHub - hviana/surreal-fs: SurrealDB file system. It saves files in 64KB chunks, allowing you to organize files into directories. You can control the KB/s rate for saving and reading files, impose rate limits, set user space limits, and limit concurrent operationsβ€”useful for controlling uploads/downloads. It utilizes the Web Streams API. Β· GitHub
[go: up one dir, main page]

Skip to content

About

SurrealDB file system. It saves files in 64KB chunks, allowing you to organize files into directories. You can control the KB/s rate for saving and reading files, impose rate limits, set user space limits, and limit concurrent operationsβ€”useful for controlling uploads/downloads. It utilizes the Web Streams API.

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

Β 

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ—„οΈ SurrealFS

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.


✨ Highlights

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

πŸ“ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                        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       β”‚                                β”‚       β”‚
β”‚  β”‚   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                                β”‚       β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸš€ Quick Start

Installation

import { SurrealFS } from "jsr:@hviana/surreal-fs";

Setup

// 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 GC

Save a file

const 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}`);
}

Read a file

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);
}

Delete a file

await fs.delete({
  path: ["users", "user_42", "documents", "report.pdf"],
});

πŸ“š Full API Reference

constructor(db: Surreal)

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);

init(): Promise<void>

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")

save(options: SaveOptions): Promise<FileStatus | File>

Upload a file to SurrealDB.

Parameters β€” SaveOptions

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

SaveControlResult

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

Examples

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(options: ReadOptions): Promise<File | FileStatus | null>

Read a single file. Returns a File with a lazy ReadableStream for the content.

Parameters β€” ReadOptions

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)

ReadControlResult

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)

Examples

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),
    },
  });
}

readDir(options: ReadOptions): Promise<DirList>

List all files under a directory prefix, with cursor-based pagination.

Return value β€” DirList

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

Examples

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(options: ReadOptions): Promise<void | FileStatus>

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);
}

deleteDir(options: ReadOptions): Promise<FileStatus[]>

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`);
}

setMetadata(path: string[], metadata: Record<string, any>): Promise<void>

Update the metadata of an existing file. Max 60 KB.

await fs.setMetadata(
  ["reports", "q4.pdf"],
  {
    reviewed: true,
    reviewer: "Bob",
    tags: ["finance", "quarterly"],
  },
);

getMetadata(path: string[]): Promise<Record<string, any> | undefined>

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"]

pathToURIComponent(path: string[]): string

Encode a path array into a URI-safe string.

fs.pathToURIComponent(["users", "cafΓ© owner", "photo.jpg"]);
// β†’ "users/caf%C3%A9%20owner/photo.jpg"

URIComponentToPath(uri: string): string[]

Decode a URI string back into a path array.

fs.URIComponentToPath("users/caf%C3%A9%20owner/photo.jpg");
// β†’ ["users", "cafΓ© owner", "photo.jpg"]

getAllFilesStatuses(): FileStatus[]

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`);
}

onFileProgress: (status: FileStatus) => void

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}`);
  }
};

getSaveConcurrencyMap() / getReadConcurrencyMap()

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 }

Static Helpers

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!);

πŸ”’ Concurrency Control Deep Dive

The control callback is the single point of policy enforcement. It receives the file path and the current concurrency map, and returns limits.

Multi-factor concurrency

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,
});

How identifiers work

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)

🧹 Garbage Collector

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

πŸ—ƒοΈ Database Schema

surreal_fs_files

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

surreal_fs_chunks

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

Indexes

-- 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;

🌊 Streaming Pipeline

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.)

πŸ’‘ Recipes

Multi-tenant file server

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 });
});

Progress monitoring

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;
  }
};

Backup all files in a directory

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"],
);

πŸ” SHA3-512 Content Hash

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.

Why SHA3-512 and not WebCrypto?

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.

Accessing the hash

// 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);
}

Standalone usage of Sha3_512

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.

Verifying a download

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!");
  }
}

⏭️ Range Reads (skip)

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

Behaviour

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.

Examples

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_000 reads a single chunk before the stream starts producing output.


πŸ“„ License

MIT β€” Created by Henrique Emanoel Viana

About

SurrealDB file system. It saves files in 64KB chunks, allowing you to organize files into directories. You can control the KB/s rate for saving and reading files, impose rate limits, set user space limits, and limit concurrent operationsβ€”useful for controlling uploads/downloads. It utilizes the Web Streams API.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0