Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

perf(world): load a world's index metadata without materializing its document

nirholasb67092fcca78
diff --git a/api/_lib/world-store.js b/api/_lib/world-store.js
index a376bed94..914e68bf8 100644
--- a/api/_lib/world-store.js
+++ b/api/_lib/world-store.js
@@ -160,6 +160,25 @@ export function createWorldStore(backend) {
};
}
+ // Load a world's index metadata WITHOUT materializing its document. Callers
+ // that only need the concurrency/ownership columns (the save permission gate)
+ // use this so a 2 MB build does not cost an R2 GET plus a full JSON.parse on
+ // every autosave. Returns null when the world has never been saved.
+ async function loadWorldMeta(worldId) {
+ assertWorldId(worldId);
+ const row = await backend.readRow(worldId);
+ if (!row) return null;
+ return {
+ worldId,
+ schemaVersion: Number(row.schema_version),
+ version: Number(row.doc_version),
+ etag: row.etag,
+ size: row.size_bytes,
+ ownerId: row.owner_id ?? null,
+ updatedAt: row.updated_at,
+ };
+ }
+
// Persist a world document. Throws TooLargeError or ConflictError.
// ifMatch — the etag the caller last read (see concurrency notes above).
// writer — the principal recorded as updated_by (account id or 'service').
@@ -233,7 +252,7 @@ export function createWorldStore(backend) {
return true;
}
- return { loadWorld, saveWorld, deleteWorld };
+ return { loadWorld, loadWorldMeta, saveWorld, deleteWorld };
}
// ── default backend: Postgres index + R2 blob ────────────────────────────────
@@ -310,5 +329,6 @@ export const postgresR2Backend = {
const defaultStore = createWorldStore(postgresR2Backend);
export const loadWorld = defaultStore.loadWorld;
+export const loadWorldMeta = defaultStore.loadWorldMeta;
export const saveWorld = defaultStore.saveWorld;
export const deleteWorld = defaultStore.deleteWorld;
diff --git a/api/world/[action].js b/api/world/[action].js
index 148840f4a..74cd18e64 100644
--- a/api/world/[action].js
+++ b/api/world/[action].js
@@ -1,4 +1,4 @@
-// api/world/[action] — the generic per-world persistence service (T3).
+// api/world/[action]: the generic per-world persistence service (T3).
//
// GET /api/world/load?worldId=<id>
// Public. Returns the world's current document + concurrency metadata, or
@@ -10,7 +10,7 @@
// token (Authorization: Bearer <world-service-token>); a browser session may
// write subject to the per-world permission model (world-store.canWriteWorld,
// the hook T16 tightens). `ifMatch` carries the etag the caller last read for
-// optimistic concurrency — a stale etag returns 409.
+// optimistic concurrency, so a stale etag returns 409.
//
// Storage lives in api/_lib/world-store.js (Postgres index + R2 blob offload).
@@ -21,6 +21,7 @@ import { resolveAccount } from '../_lib/account-auth.js';
import { verifyWorldServiceToken } from '../_lib/world-service-auth.js';
import {
loadWorld,
+ loadWorldMeta,
saveWorld,
canWriteWorld,
isValidWorldId,
@@ -30,6 +31,8 @@ import {
MAX_DOC_BYTES,
} from '../_lib/world-store.js';
+const BODY_ERROR_CODES = { 413: 'payload_too_large', 415: 'unsupported_media_type' };
+
function actionOf(req) {
return (req.query?.action || new URL(req.url, 'http://x').pathname.split('/').pop() || '').toLowerCase();
}
@@ -92,7 +95,13 @@ async function handleSave(req, res) {
try {
body = await readJson(req, MAX_DOC_BYTES + 1024);
} catch (err) {
- return error(res, err.status || 400, 'validation_error', err.message || 'invalid body');
+ // readJson signals an over-cap body as 413 and a non-JSON content-type as
+ // 415. Labelling either one `validation_error` left a client unable to tell
+ // "your build is too big" from "your JSON is malformed", so each status
+ // keeps the house error code its own status already implies.
+ const status = err.status || 400;
+ const code = BODY_ERROR_CODES[status] || 'validation_error';
+ return error(res, status, code, err.message || 'invalid body');
}
const { worldId, doc, ifMatch, owner } = body || {};
@@ -105,10 +114,12 @@ async function handleSave(req, res) {
}
// Permission gate. Service writes are always allowed; user writes depend on the
- // world's current owner. We need the existing owner to decide, so peek first —
- // loadWorld returns null for a brand-new world (unowned → first writer allowed).
+ // world's current owner, so peek at the index row first. loadWorldMeta reads
+ // only the index columns (never the body), which keeps a builder's autosave to
+ // one cheap lookup instead of re-downloading and re-parsing the whole prior
+ // document. It returns null for a brand-new world (unowned, first writer allowed).
if (!service) {
- const existing = await loadWorld(worldId);
+ const existing = await loadWorldMeta(worldId);
const allowed = canWriteWorld({
isService: false,
account: account.userId,
diff --git a/tests/world-store.test.js b/tests/world-store.test.js
index 6199571cf..aced16a5f 100644
--- a/tests/world-store.test.js
+++ b/tests/world-store.test.js
@@ -17,6 +17,7 @@ import {
TooLargeError,
INLINE_MAX_BYTES,
MAX_DOC_BYTES,
+ SCHEMA_VERSION,
} from '../api/_lib/world-store.js';
import { verifyWorldServiceToken } from '../api/_lib/world-service-auth.js';
@@ -212,6 +213,59 @@ describe('world-store: large-doc R2 offload', () => {
});
});
+// The save permission gate (api/world/[action].js) only needs the owner column,
+// so it reads metadata rather than the whole document. These lock in that the
+// cheap read returns the same index values loadWorld does and never touches the
+// blob store — the regression that would silently restore an R2 GET plus a 2 MB
+// JSON.parse on every autosave of a large build.
+describe('world-store: loadWorldMeta', () => {
+ let backend;
+ let store;
+ beforeEach(() => {
+ backend = makeBackend();
+ store = createWorldStore(backend);
+ });
+
+ it('returns null for a world that has never been saved', async () => {
+ expect(await store.loadWorldMeta('never-saved')).toBeNull();
+ });
+
+ it('reports the same index values as loadWorld, without the doc', async () => {
+ const saved = await store.saveWorld({ worldId: 'coinA', doc: { theme: 'forest' }, writer: 'alice', owner: 'alice' });
+ const meta = await store.loadWorldMeta('coinA');
+
+ expect(meta).toEqual({
+ worldId: 'coinA',
+ schemaVersion: SCHEMA_VERSION,
+ version: saved.version,
+ etag: saved.etag,
+ size: saved.size,
+ ownerId: 'alice',
+ updatedAt: saved.updatedAt,
+ });
+ expect(meta.doc).toBeUndefined();
+ });
+
+ it('never fetches the offloaded blob for a large world', async () => {
+ await store.saveWorld({ worldId: 'big', doc: { blob: 'x'.repeat(INLINE_MAX_BYTES + 1024) }, writer: 's', owner: 'alice' });
+ let blobReads = 0;
+ const readBlob = backend.readBlob;
+ backend.readBlob = (key) => { blobReads += 1; return readBlob(key); };
+
+ const meta = await store.loadWorldMeta('big');
+ expect(meta.ownerId).toBe('alice');
+ expect(blobReads).toBe(0);
+
+ // The full read still needs it, which is exactly why the gate uses the cheap one.
+ await store.loadWorld('big');
+ expect(blobReads).toBe(1);
+ });
+
+ it('rejects an invalid world id instead of hitting storage', async () => {
+ await expect(store.loadWorldMeta('../etc/passwd')).rejects.toThrow();
+ });
+});
+
describe('world-store: deleteWorld', () => {
it('removes the index row and any offloaded blob', async () => {
const backend = makeBackend();