Files
puter/src/backend/controllers/fs/sharedFolderWrites.http.test.ts
T
Daniel Salazar 9ff224e22f
Backend Tests / changes (push) Canceled after 0s
Backend Tests / typecheck (push) Canceled after 0s
Backend Tests / test shard 1/4 (push) Canceled after 0s
Backend Tests / test shard 2/4 (push) Canceled after 0s
Backend Tests / test shard 3/4 (push) Canceled after 0s
Backend Tests / test shard 4/4 (push) Canceled after 0s
Backend Tests / test (main) (push) Canceled after 0s
Backend Tests / coverage (push) Canceled after 0s
Maintain Release Merge PR / update-release-pr (push) Canceled after 0s
Notify HeyPuter / notify (push) Canceled after 0s
release-please / release-please (push) Canceled after 0s
perf(backend): cut sequential round trips on auth, fs, driver, event and site paths (#4259)
Pipeline
- CORS preflights send Access-Control-Max-Age: browsers stop re-preflighting authed calls every 5 s.
- `req.ua` is parsed on first read instead of on every request.
- JSON `rawBody` reuses the parsed buffer instead of copying it.
- `emitAndWait` returns early when nothing listens: no span or closure per unlistened driver call.
- SQLBatcher sends a lone query on the next tick while fewer than 8 flushes are in flight, and
  waits `maxTimeInQueue` as before otherwise. Lone reads skip the 10/30 ms wait; batching under
  load is unchanged.

Auth and permissions
- Token-to-actor auth starts the user, session and app lookups together and checks them in the
  same order: fewer sequential Redis round trips per authed request.
- get-user-app-token and check-app reuse the resolved app row. getOrCreateApp skips the re-select
  after its own insert and doesn't wait on the cache write for replica rows.
- getOrCreateApp reads the race winner from the primary when its insert loses, so it no longer
  hands out a session that was never written.
- whoami runs the email check and the OIDC/taskbar/team lookups in parallel; key order unchanged.
- OIDC providers are memoized once every discovery succeeds, with one discovery fetch in flight
  per URL, and the Apple key is parsed once.
- gui-token and sync-cookie use `req.actor.user` instead of re-reading the user.
- listSessions batches app lookups. App icon probes run together, and the original-icon probe
  skips the lineage fallback.
- Default-granted permissions are answered from config before the scan cache, and exploded
  options are deduped: one less Redis read per /drivers/call.
- ACL resolves ancestors lazily (owners and full-access tokens skip them) and scans the node
  first, then the ancestors concurrently on a miss.

Filesystem
- Missing-path lineage lookups run 10 at a time: batch-upload path resolution drops from about
  1.3 s to about 40 ms per 100 new files.
- MySQL single-file inserts return the row built from the written values, falling back to the
  primary read: one less primary round trip per new file.
- Batch thumbnails are stored with one UPDATE per chunk (200 rows or 4M chars), with a per-row
  fallback.
- storage.quota.bonus listeners run concurrently next to the usage SUM, and the payload carries
  `userUuid`: quota checks and /df no longer serialize the listener reads.
- readdir cache backfill is one pipeline instead of 3xN SETEX.
- Profile reads skip the lineage fallback; the own profile is read alongside the user lookup.
- Legacy /stat runs is_empty (new `hasChildrenByParentUid`), owner and thumbnail concurrently.
- Downloads and the video proxy pipe through `pipeToResponse`: aborts release the storage stream
  at once with no extra 'close' listeners, and the video proxy no longer crashes on a mid-stream
  upstream error.
- mkdir looks up target and parent together.
- Upload completion reuses the session from the access check (status is still re-read before
  completing), and multipart signing reads it once.
- Moving a shared file to Trash skips two lookups that always returned the entry itself.

Drivers and events
- Subscription resolvers run concurrently and are folded in registration order.
- SubdomainDriver and WorkerDriver overlap independent lookups.
- The events "anyone subscribed?" check is one Redis pipeline when the region is warm.
- Handler publish overlaps the count with the size check.
- Broadcast flushes peers concurrently over a keep-alive agent, so a slow peer no longer delays
  cross-region invalidations to the others.

Sites, share and AI
- Hosted sites resolve the owner first, then the app and root together. Site config loads only
  on 404s. The hosted-app query selects only the columns it uses and moves into AppStore.
- shareFlags asks about the plan only when an item is shared by link only.
- Share listings run the count, teams and plan reads alongside their page query.
- Claude attachment cleanup no longer blocks the response.
- New util `awaitLater` for promises started early and awaited later.
2026-10-17 12:03:35 -07:00

281 lines
10 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
* Copyright (C) 2024-present Puter Technologies Inc.
*
* This file is part of Puter.
*
* Puter is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import {
createTestUser,
setupPuterTestEnv,
type PuterTestEnv,
} from '../../testUtil.js';
// A recipient addresses the owner's entries by a masked `/<owner>/<uuid>/<name>`
// path. Routes that create an entry have no row to resolve, so they unmask it
// themselves before the ACL check runs against the result.
describe('writes inside a folder shared with write', () => {
let env: PuterTestEnv;
beforeAll(async () => {
env = await setupPuterTestEnv();
}, 180_000);
afterAll(async () => {
await env?.shutdown();
});
const post = async (route: string, token: string, body: unknown) => {
const res = await fetch(new URL(route, env.apiOrigin), {
method: 'POST',
headers: {
'content-type': 'application/json',
authorization: `Bearer ${token}`,
},
body: JSON.stringify(body),
});
const text = await res.text();
return {
status: res.status,
json: text ? (JSON.parse(text) as Record<string, unknown>) : null,
};
};
const makeUser = () =>
createTestUser(env.server, {
username: `sfw${Math.random().toString(36).slice(2, 9)}`,
password: 'puter-test-user-password',
});
/** `/<owner>/SharedDir` with `note.txt`, shared `write` with a recipient. */
const shareAFolder = async () => {
const owner = await makeUser();
const recipient = await makeUser();
const dir = await post('/mkdir', owner.token, {
path: `/${owner.username}/SharedDir`,
});
await post('/touch', owner.token, {
path: `/${owner.username}/SharedDir/note.txt`,
});
const note = await post('/stat', owner.token, {
path: `/${owner.username}/SharedDir/note.txt`,
});
await post('/share', owner.token, {
recipients: [recipient.username],
items: [{ uid: dir.json!.uid }],
mode: 'write',
});
return {
owner,
recipient,
realDir: `/${owner.username}/SharedDir`,
maskedDir: `/${owner.username}/${dir.json!.uid}/SharedDir`,
noteUid: note.json!.uid as string,
};
};
const ownerListing = async (s: { owner: { token: string; username: string } }) => {
const res = await post('/readdir', s.owner.token, {
path: `/${s.owner.username}/SharedDir`,
});
return (res.json as unknown as Array<{ name: string }>).map(
(entry) => entry.name,
);
};
// `{parent, path}` is the shape puter.js sends — the GUI's "New Folder".
it('mkdir accepts a masked parent', async () => {
const s = await shareAFolder();
const made = await post('/mkdir', s.recipient.token, {
parent: s.maskedDir,
path: 'New Folder',
});
expect(made.status).toBe(200);
expect(made.json).toMatchObject({
name: 'New Folder',
is_dir: true,
// Anchored to the share root the request came through, so the
// recipient can navigate into what they just made.
path: `${s.maskedDir}/New Folder`,
});
expect(await ownerListing(s)).toContain('New Folder');
}, 180_000);
it('mkdir accepts a masked absolute path', async () => {
const s = await shareAFolder();
const made = await post('/mkdir', s.recipient.token, {
path: `${s.maskedDir}/Reports`,
});
expect(made.status).toBe(200);
expect(await ownerListing(s)).toContain('Reports');
}, 180_000);
it('touch accepts a masked path', async () => {
const s = await shareAFolder();
const touched = await post('/touch', s.recipient.token, {
path: `${s.maskedDir}/from-recipient.txt`,
});
expect(touched.status).toBe(200);
expect(await ownerListing(s)).toContain('from-recipient.txt');
}, 180_000);
it('touch still expands a tilde path', async () => {
const s = await shareAFolder();
const touched = await post('/touch', s.owner.token, {
path: '~/SharedDir/from-tilde.txt',
});
expect(touched.status).toBe(200);
expect(await ownerListing(s)).toContain('from-tilde.txt');
}, 180_000);
// Addressed to the owner, so it carries the path the owner can resolve.
it('publishes the owner’s real path on events about their entries', async () => {
const s = await shareAFolder();
const seen: Array<Record<string, unknown>> = [];
const emit = env.server.clients.event.emit.bind(
env.server.clients.event,
);
vi.spyOn(env.server.clients.event, 'emit').mockImplementation(
((name: string, payload: Record<string, unknown>, meta: unknown) => {
if (name.startsWith('outer.gui.item.')) {
seen.push(payload);
}
return emit(
name as never,
payload as never,
meta as never,
);
}) as never,
);
const moved = await post('/move', s.recipient.token, {
source: s.noteUid,
destination: s.maskedDir,
new_name: 'renamed.txt',
});
expect(moved.status).toBe(200);
const ownerId = (await env.server.stores.user.getByUsername(
s.owner.username,
))!.id;
const event = seen.find(
(payload) =>
(payload.response as { uid?: string })?.uid === s.noteUid,
);
expect(event?.user_id_list).toEqual([ownerId]);
expect(event?.response).toMatchObject({
path: `${s.realDir}/renamed.txt`,
dirpath: s.realDir,
});
// The recipient's own response stays masked.
expect(
(moved.json!.moved as { path: string }).path,
).toBe(`${s.maskedDir}/renamed.txt`);
}, 180_000);
// The thumbnail update is scoped to the writer's own rows, so a file the
// owner ends up owning keeps none, while the writer's own file in the same
// batch gets its thumbnail.
it('batchWrite stores thumbnails on the writer’s own files only', async () => {
const s = await shareAFolder();
const png =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';
const ownPath = `/${s.recipient.username}/Documents/own.png`;
const written = await post('/fs/batchWrite', s.recipient.token, [
{
fileMetadata: { path: `${s.maskedDir}/shared.png`, size: 1 },
fileContent: 'a',
thumbnailData: png,
},
{
fileMetadata: { path: ownPath, size: 1 },
fileContent: 'b',
thumbnailData: png,
},
]);
expect(written.status).toBe(200);
const stored = async (path: string) =>
env.server.stores.fsEntry.getEntryByUuidFromPrimary(
(await env.server.stores.fsEntry.getEntryByPath(path))!.uuid,
);
expect((await stored(`${s.realDir}/shared.png`))?.thumbnail).toBeNull();
expect((await stored(ownPath))?.thumbnail).toMatch(/^s3:\/\//);
}, 180_000);
// The recipient only knows the masked path, so refusals name entries the
// way the recipient addressed them.
it('keeps the owner’s real path out of error messages', async () => {
const s = await shareAFolder();
await post('/touch', s.owner.token, {
path: `${s.realDir}/other.txt`,
});
const cases = [
{
res: await post('/fs/stat', s.recipient.token, {
path: `${s.maskedDir}/missing.txt`,
}),
status: 404,
message: 'Subject does not exist',
},
{
res: await post('/fs/mkdir', s.recipient.token, {
path: `${s.maskedDir}/note.txt`,
}),
status: 409,
message: 'An entry named `note.txt` already exists',
},
{
res: await post('/fs/mkdir', s.recipient.token, {
path: `${s.maskedDir}/missing/child`,
}),
status: 404,
message: 'Parent path does not exist: missing',
},
{
res: await post('/fs/rename', s.recipient.token, {
uid: s.noteUid,
new_name: 'other.txt',
}),
status: 409,
message: 'An entry named `other.txt` already exists',
},
{
res: await post('/mkdir', s.recipient.token, {
path: `${s.maskedDir}/note.txt`,
}),
status: 409,
message: 'An entry named `note.txt` already exists',
},
];
for (const { res, status, message } of cases) {
expect(res.status).toBe(status);
expect(res.json!.message).toBe(message);
expect(JSON.stringify(res.json)).not.toContain(s.realDir);
}
}, 180_000);
});