diff --git a/AGENTS.md b/AGENTS.md index 48bc212f..2508322a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -256,6 +256,7 @@ Everything in our registry has a `nanoforge.manifest.json` and a name `@scope/na - The e2e server reads its registry from `/.registry` (`REGISTRY_DIR`, written by `prepare-workspace.mjs`). A test that publishes a version there, installs a user plugin (`.data/plugins`) or a package (`nanoforge.packages*.json`, `tsconfig.json` paths) puts everything back (see `e2e/marketplace.spec.ts`). - `nanoforge.manifest.json` is a build input of turbo (it was not until 2026-10-01: a manifest-only change kept the old bundle). - After changing a plugin manifest, rebuild it: `tooling/example-plugin` is not rebuilt by the editor build filter (`pnpm --filter @nanoforge-dev/editor-example-plugin build`). +- **Server streams and the idle sweep:** when a subscription answers `error`, `RpcClient` deletes it for good (no retry, silent without `onError`). A stream keyed by a project (`fs.changes`, `projects.model`) errors with `NOT_FOUND` once the server's idle sweep closed the project, so give it an `onError` that, on `NOT_FOUND`, reopens the project (`ClientProject._reopen`: `recent` then `open`) and subscribes again (`ProjectFs.reattach`). It gives up and fires `ClientProject.onDidLose` on a definite answer: no recent entry, another id or trust, `NOT_FOUND`/`FORBIDDEN`/`UNAUTHORIZED` from a request of the reopen, or the project lost again while catching up or within 30 s of the last reopen. Any other failure (offline, timeout) leaves it to try again on the next loss. Nothing listens to `onDidLose` yet, so the tab stays as it was (the project page should show its "not open anymore" screen). A copy the server opened for a reopen given up stays open until the session's tabs are gone and the sweep runs: the projects contract has no close. - **Installing folders and the file watcher:** a folder that appears through a rename is missed by the server's watcher (its content never reaches the client's file list, so the catalog does not see a new package). `installItem` writes files in place, the manifest last. - **API features:** nothing of the NanoForge API beyond sign-in and projects is called unless listed in `API_FEATURES` (`settings`, `registry`). The real API (`../api`, read-only for us) has a registry (`../api/docs/registry.md`, the source of truth: align `docs/api/registry.md` with it, and `libs/registry` in the CLI repository) and no settings yet. - **Account plugin list:** `plugins.account` is an account setting, and a local editor's account document lives on its own machine (no sign-in): the list does not travel between machines yet. Don't describe it as cross-machine. diff --git a/packages/project/src/fs/project-fs.ts b/packages/project/src/fs/project-fs.ts index b992a210..95ea5d2e 100644 --- a/packages/project/src/fs/project-fs.ts +++ b/packages/project/src/fs/project-fs.ts @@ -3,8 +3,10 @@ import { DisposableStore, Emitter, type Event, + MutableDisposable, type Observable, ObservableValue, + errorCodeOf, } from '@nanoforge-dev/editor-kernel'; import { type FileChange, @@ -18,6 +20,10 @@ import type { ContentCache, TreeCache } from '../cache/cache.type'; import { sha1Hex } from '../cache/sha1'; const decoder = new TextDecoder(); +/** Stats of a remote change batch on their way at once (a checkout touches thousands). */ +const CONCURRENT_STATS = 16; +/** Cache lookups on their way at once: each one is a read of the browser's storage and a hash. */ +const CONCURRENT_LOOKUPS = 32; /** Hides files from the whole editor (see the server's file system). */ export const NFIGNORE_FILE = '.nfignore'; @@ -34,6 +40,41 @@ const sameContent = (a: FileEntry, b: FileEntry): boolean => const sameEntry = (a: FileEntry, b: FileEntry): boolean => a.kind === b.kind && a.size === b.size && a.mtime === b.mtime && a.hash === b.hash; +const parentOf = (path: string): string => path.slice(0, Math.max(0, path.lastIndexOf('/'))); + +/** Entries by path, and the paths in each folder: listing a folder reads only its own. */ +class FileTree extends Map { + private readonly _children = new Map>(); + + override set(path: string, entry: FileEntry): this { + if (!this.has(path)) { + const parent = parentOf(path); + const siblings = this._children.get(parent) ?? new Set(); + this._children.set(parent, siblings.add(path)); + } + return super.set(path, entry); + } + + override delete(path: string): boolean { + if (!super.delete(path)) return false; + const parent = parentOf(path); + const siblings = this._children.get(parent); + siblings?.delete(path); + if (!siblings?.size) this._children.delete(parent); + return true; + } + + override clear(): void { + super.clear(); + this._children.clear(); + } + + /** Paths whose parent folder is `path` (in the order they joined the tree). */ + childPaths(path: string): Iterable { + return this._children.get(path) ?? []; + } +} + /** * Files of the open project. The tree is loaded once (cached for fast startup), then kept in * sync by the server change stream. Contents come from the local cache, keyed by the hash the @@ -42,10 +83,14 @@ const sameEntry = (a: FileEntry, b: FileEntry): boolean => */ export class ProjectFs implements Disposable { private readonly _fs: RpcApi; - private readonly _tree = new Map(); + private readonly _tree = new FileTree(); private readonly _ready = new ObservableValue(false); private readonly _onDidChange = new Emitter(); private readonly _store = new DisposableStore(); + private readonly _changes = this._store.add(new MutableDisposable()); + private readonly _onDidLose = new Emitter(); + /** Bumped by `reattach`: a refusal of a request sent before it is old news. */ + private _attached = 0; private _treeSave: ReturnType | undefined; /** * Ticks at each change of the tree. A reply only updates the paths nothing changed since its @@ -61,6 +106,12 @@ export class ProjectFs implements Disposable { /** Batched changes (from the server watcher and this client's own writes). */ readonly onDidChange: Event = this._onDidChange.event; + /** + * The server does not have the project open anymore (the idle sweep closed it while this tab + * was away): the change stream is gone, and calls fail until it is opened again (`reattach`). + * @internal for `ClientProject`, which opens it again. + */ + readonly onDidLose: Event = this._onDidLose.event; constructor( readonly projectId: string, @@ -80,15 +131,25 @@ export class ProjectFs implements Disposable { async initialize(): Promise { const cached = await this._treeCache.load(); for (const entry of cached ?? []) this._tree.set(entry.path, entry); + this._subscribe(); this._store.add( - this._rpc.subscribe( - FsContract, - 'changes', - { project: this.projectId }, - ({ changes }) => void this._applyRemote(changes), - ), + this._rpc.onDidReconnect(() => { + const attached = this._attached; + this.refresh().catch((error: unknown) => { + if (attached === this._attached) this._lost(error); + }); + }), ); - this._store.add(this._rpc.onDidReconnect(() => void this.refresh().catch(() => undefined))); + await this.refresh(); + } + + /** + * Once the server has the project open again: follows its changes again and catches up. + * @internal for `ClientProject`, which opens it again. + */ + async reattach(): Promise { + this._attached++; + this._subscribe(); await this.refresh(); } @@ -139,14 +200,8 @@ export class ProjectFs implements Disposable { /** Direct children of a directory, from the tree. */ children(path: string): FileEntry[] { - const prefix = path ? `${path}/` : ''; - return [...this._tree.values()] - .filter( - (entry) => - entry.path.startsWith(prefix) && - !entry.path.slice(prefix.length).includes('/') && - entry.path !== path, - ) + return [...this._tree.childPaths(path)] + .map((child) => this._tree.get(child)!) .sort((a, b) => a.kind === b.kind ? a.path.localeCompare(b.path) : a.kind === 'directory' ? -1 : 1, ); @@ -275,8 +330,24 @@ export class ProjectFs implements Disposable { } this._store.dispose(); this._onDidChange.dispose(); + this._onDidLose.dispose(); } + /** The client drops a stream the server refused: a new one replaces it. */ + private _subscribe(): void { + this._changes.value = this._rpc.subscribe( + FsContract, + 'changes', + { project: this.projectId }, + ({ changes }) => void this._applyRemote(changes), + { onError: this._lost }, + ); + } + + private readonly _lost = (error: unknown): void => { + if (errorCodeOf(error) === 'NOT_FOUND') this._onDidLose.fire(); + }; + private async _applyRemote(changes: readonly FileChange[]): Promise { const relevant: FileChange[] = []; /** @@ -295,24 +366,35 @@ export class ProjectFs implements Disposable { /** * Every change is checked with a stat, deletions included: events come late and out of order * (the echo of a deletion after the file was made again), the stat tells what is there now. + * A few stats are on their way at once; their answers are applied in the batch's order. */ - for (const change of changes) { + const stats: Promise<{ sent: number; entry: FileEntry | null }>[] = []; + const stat = (path: string) => { const sent = this._clock; - const entry = await this._fs - .stat({ project: this.projectId, path: change.path }) - .catch(() => null); + return this._fs + .stat({ project: this.projectId, path }) + .catch(() => null) + .then((entry) => ({ sent, entry })); + }; + /** Removals of this batch: the stats sent with them are not older than them. */ + const own = new Set(); + for (const [index, change] of changes.entries()) { + while (stats.length < Math.min(changes.length, index + CONCURRENT_STATS)) + stats.push(stat(changes[stats.length]!.path)); + const { sent, entry } = await stats[index]!; if (!entry) { - if (change.type !== 'deleted' || this._changedSince(change.path, sent)) continue; + if (change.type !== 'deleted' || this._changedSince(change.path, sent, own)) continue; const prefix = `${change.path}/`; if (![...this._tree.keys()].some((key) => key === change.path || key.startsWith(prefix))) continue; this._removeFromTree(change.path); + own.add(this._clock); relevant.push(change); continue; } const previous = before.get(change.path) ?? this._tree.get(change.path); /** A newer update already has the path: a read's is still told, a save told itself. */ - if (!this._changedSince(change.path, sent)) this._setEntry(change.path, entry); + if (!this._changedSince(change.path, sent, own)) this._setEntry(change.path, entry); const now = this._tree.get(change.path); /** A save's own echo is absorbed once; any other content lands and forgets the save. */ const saved = this._saved.get(change.path); @@ -337,14 +419,17 @@ export class ProjectFs implements Disposable { const found = new Map(); const cached = new Map(); const ask: { path: string; knownHash?: string }[] = []; - /** Cache lookups run together: each one is a read of the browser's storage. */ - const lookups = await Promise.all( - paths.map(async (path) => { + const lookups: { path: string; known?: FileEntry; bytes?: Uint8Array }[] = []; + let next = 0; + const lookup = async () => { + for (let index = next++; index < paths.length; index = next++) { + const path = paths[index]!; const known = this._tree.get(path); const bytes = known?.hash ? await this._contents.get(known.hash) : undefined; - return { path, known, bytes }; - }), - ); + lookups[index] = { path, known, bytes }; + } + }; + await Promise.all(Array.from({ length: Math.min(CONCURRENT_LOOKUPS, paths.length) }, lookup)); for (const { path, known, bytes } of lookups) { if (known?.hash && bytes) { if (!fresh) { @@ -422,15 +507,19 @@ export class ProjectFs implements Disposable { this._changedAt.set(path, ++this._clock); } - /** Whether the tree changed at `path` (or removed a folder holding it) after tick `sent`. */ - private _changedSince(path: string, sent: number): boolean { - return (this._changedAt.get(path) ?? 0) > sent || this._removedSince(path, sent); + /** + * Whether the tree changed at `path` (or removed a folder holding it) after tick `sent`, + * removals at the `ignored` ticks aside. + */ + private _changedSince(path: string, sent: number, ignored?: ReadonlySet): boolean { + return (this._changedAt.get(path) ?? 0) > sent || this._removedSince(path, sent, ignored); } /** Whether `path`, or a folder holding it, left the tree after tick `sent`. */ - private _removedSince(path: string, sent: number): boolean { + private _removedSince(path: string, sent: number, ignored?: ReadonlySet): boolean { for (let at = path; ; at = at.slice(0, at.lastIndexOf('/'))) { - if ((this._removedAt.get(at) ?? 0) > sent) return true; + const removed = this._removedAt.get(at) ?? 0; + if (removed > sent && !ignored?.has(removed)) return true; if (!at.includes('/')) return false; } } diff --git a/packages/project/src/service/client-project.ts b/packages/project/src/service/client-project.ts index 00f9a34a..62811bab 100644 --- a/packages/project/src/service/client-project.ts +++ b/packages/project/src/service/client-project.ts @@ -2,10 +2,14 @@ import { type AppInfo, type Disposable, DisposableStore, + Emitter, type EngineLibProvider, + type Event, + MutableDisposable, type Observable, ObservableValue, derived, + errorCodeOf, } from '@nanoforge-dev/editor-kernel'; import { type ProjectModel, ProjectsContract } from '@nanoforge-dev/editor-protocol'; import type { RpcClient } from '@nanoforge-dev/editor-rpc'; @@ -29,18 +33,37 @@ export const memoryCacheFactory = (): CacheFactory => { return { contents: () => contents, tree: () => new MemoryTreeCache() }; }; +/** Answers that say the project can't be opened again here (others may pass: offline, timeout). */ +const DEFINITE = new Set(['NOT_FOUND', 'FORBIDDEN', 'UNAUTHORIZED']); + /** A project opened in this editor window. */ export class ClientProject implements Disposable, EngineLibProvider { private readonly _store = new DisposableStore(); private readonly _model: ObservableValue; + private readonly _modelStream = this._store.add(new MutableDisposable()); + private readonly _onDidLose = new Emitter(); + private _reopening: Promise | undefined; + /** When the last reopen began: a project lost again right after it is given up. */ + private _reopenedAt = -Infinity; + /** Given up or disposed: nothing is opened again. */ + private _done = false; + /** Lost again while the reopen was following the project again. */ + private _lostAgain = false; readonly fs: ProjectFs; /** Apps as the kernel sees them (engine lib gating). */ readonly apps: Observable; + /** + * The server closed the project and it can't be opened again here (no recent entry, another id + * or trust, a refused request, or lost again at once): the tab should say it is not open + * anymore. Fires once. A failure that may pass (offline, timeout) waits for the next loss. + * @internal for the project page. + */ + readonly onDidLose: Event = this._onDidLose.event; constructor( initial: ProjectModel, - rpc: RpcClient, + private readonly _rpc: RpcClient, caches: CacheFactory, /** * Whether its code may run here. An untrusted local folder is open in restricted mode: its @@ -50,15 +73,12 @@ export class ClientProject implements Disposable, EngineLibProvider { ) { this._model = new ObservableValue(initial); this.fs = this._store.add( - new ProjectFs(initial.id, rpc, caches.contents(initial.id), caches.tree(initial.id)), + new ProjectFs(initial.id, _rpc, caches.contents(initial.id), caches.tree(initial.id)), ); const lease = caches.opened?.(initial.id); if (lease) this._store.add(lease); - this._store.add( - rpc.subscribe(ProjectsContract, 'model', { id: initial.id }, (model) => - this._model.set(model), - ), - ); + this._subscribeModel(); + this._store.add(this.fs.onDidLose(() => void this._reopen())); this.apps = derived([this._model], (model) => model.apps.map((app) => ({ id: app.id, @@ -78,6 +98,74 @@ export class ClientProject implements Disposable, EngineLibProvider { } dispose(): void { + this._done = true; this._store.dispose(); + this._onDidLose.dispose(); + } + + private _subscribeModel(): void { + this._modelStream.value = this._rpc.subscribe( + ProjectsContract, + 'model', + { id: this.id }, + (model) => this._model.set(model), + { + onError: (error) => { + if (errorCodeOf(error) === 'NOT_FOUND') void this._reopen(); + }, + }, + ); + } + + /** + * The server closed the project (idle sweep) while this tab was away: opens it again from its + * recent entry and follows it again. Ids are stable, so the tab goes on as it was. The server + * decides the trust; a project that comes back with another id or trust than this tab runs + * with is given up, so the tab never runs code under a trust it was not opened with. Once at a + * time: the stream errors and the reconnect's refresh all report it. + */ + private _reopen(): Promise { + if (this._done) return Promise.resolve(); + if (this._reopening) { + this._lostAgain = true; + return this._reopening; + } + /** The sweep closes a project after 30 minutes unused: lost again so soon, it stays lost. */ + if (Date.now() - this._reopenedAt < 30_000) { + this._giveUp(); + return Promise.resolve(); + } + this._reopening = (async () => { + this._reopenedAt = Date.now(); + const api = this._rpc.api(ProjectsContract); + const known = (await api.recent(null)).find((project) => project.id === this.id); + if (this._done) return; + if (!known) return this._giveUp(); + const opened = await api.open(known.ref); + if (this._done) return; + /** + * shortcut: the server copy opened here stays open (the contract has no close, and the + * session holds it); the sweep frees it once the tab is gone. Add a close when it matters. + */ + if (opened.id !== this.id || opened.trusted !== this.trusted) return this._giveUp(); + /** What was told before the open was the same loss. */ + this._lostAgain = false; + this._subscribeModel(); + await this.fs.reattach(); + if (this._lostAgain && !this._done) this._giveUp(); + })() + .catch((error: unknown) => { + if (this._done) return; + if (DEFINITE.has(errorCodeOf(error) ?? '')) return this._giveUp(); + /** It may pass: the next reconnect's refusal tries again. */ + this._reopenedAt = -Infinity; + }) + .finally(() => (this._reopening = undefined)); + return this._reopening; + } + + private _giveUp(): void { + this._done = true; + this._onDidLose.fire(); } } diff --git a/packages/project/test/fs/project-fs-races.spec.ts b/packages/project/test/fs/project-fs-races.spec.ts index cdc68fa7..dc39ac2b 100644 --- a/packages/project/test/fs/project-fs-races.spec.ts +++ b/packages/project/test/fs/project-fs-races.spec.ts @@ -53,8 +53,11 @@ const fakeServer = (initial: Record) => { })), rest: [], }), + mkdir: ({ path }: { path: string }) => + Promise.resolve({ path, kind: 'directory', size: 0, mtime: 1 } as FileEntry), delete: ({ path }: { path: string }) => { - files.delete(path); + for (const file of [...files.keys()]) + if (file === path || file.startsWith(`${path}/`)) files.delete(file); return Promise.resolve({ trashPath: `.trash/${path}` }); }, write: ({ path, content }: { path: string; content: string }) => { @@ -278,6 +281,41 @@ describe('ProjectFs races', () => { fs.dispose(); }); + it('checks a large change batch 16 stats at a time, and tells it in its order', async () => { + const server = fakeServer({}); + const fs = await open(server, new MemoryContentCache()); + const paths = Array.from({ length: 40 }, (_, index) => `f${index}.ts`); + const answers = paths.map(() => held()); + server.stats.push(...answers.map((answer) => answer.promise)); + const changes: FileChange[] = []; + const subscription = fs.onDidChange((batch) => changes.push(...batch)); + server.change(paths.map((path) => ({ type: 'created', path, kind: 'file' }))); + await settle(); + expect(server.stats).toHaveLength(40 - 16); + for (const [index, answer] of [...answers.entries()].reverse()) + answer.release(fileEntry(paths[index]!, 'x')); + await settle(); + expect(changes.map((change) => change.path)).toEqual(paths); + subscription.dispose(); + fs.dispose(); + }); + + it('keeps a file a batch made in a folder the same batch saw deleted', async () => { + const server = fakeServer({}); + const folder: FileEntry = { path: 'dist', kind: 'directory', size: 0, mtime: 1 }; + server.lists.push(Promise.resolve([folder])); + const fs = await open(server, new MemoryContentCache()); + server.stats.push(Promise.resolve(null), Promise.resolve(fileEntry('dist/a.js', 'a'))); + server.change([ + { type: 'deleted', path: 'dist', kind: 'directory' }, + { type: 'created', path: 'dist/a.js', kind: 'file' }, + ]); + await settle(); + expect(fs.entry('dist')).toBeUndefined(); + expect(fs.entry('dist/a.js')?.hash).toBe(sha1('a')); + fs.dispose(); + }); + it('tells an outside change back to what the editor saved', async () => { const server = fakeServer({ 'a.ts': 'old' }); const fs = await open(server, new MemoryContentCache()); @@ -354,6 +392,72 @@ describe('ProjectFs races', () => { fs.dispose(); }); + it('looks up at most 32 cached files at once, and gives them in their order', async () => { + const texts = Object.fromEntries(Array.from({ length: 100 }, (_, i) => [`f${i}.ts`, `${i}`])); + const server = fakeServer(texts); + const memory = new MemoryContentCache(); + for (const text of Object.values(texts)) await memory.set(sha1(text), encoder.encode(text)); + let inFlight = 0; + let peak = 0; + const contents: ContentCache = { + get: async (hash) => { + peak = Math.max(peak, ++inFlight); + await new Promise((resolve) => setTimeout(resolve, Math.random() * 3)); + inFlight--; + return memory.get(hash); + }, + set: (hash, bytes) => memory.set(hash, bytes), + }; + const fs = await open(server, contents); + const read = await fs.readMany(Object.keys(texts)); + expect(peak).toBe(32); + expect([...read.keys()]).toEqual(Object.keys(texts)); + fs.dispose(); + }); + + it('lists the children of a folder as a scan of the whole tree would', async () => { + /** What `children` gave when it filtered the whole tree. */ + const scan = (fs: ProjectFs, path: string) => { + const prefix = path ? `${path}/` : ''; + return fs.entries + .filter( + (entry) => + entry.path.startsWith(prefix) && + !entry.path.slice(prefix.length).includes('/') && + entry.path !== path, + ) + .sort((a, b) => + a.kind === b.kind ? a.path.localeCompare(b.path) : a.kind === 'directory' ? -1 : 1, + ); + }; + /** The listing has no folder entries: a folder's files are still its children. */ + const server = fakeServer({ 'b.ts': 'b', 'a/y.ts': 'y', 'a/x.ts': 'x', 'a/k/z.ts': 'z' }); + const fs = await open(server, new MemoryContentCache()); + const check = () => { + for (const path of ['', 'a', 'a/k', 'missing']) + expect(fs.children(path)).toEqual(scan(fs, path)); + }; + check(); + expect(fs.children('a').map((entry) => entry.path)).toEqual(['a/x.ts', 'a/y.ts']); + await fs.mkdir('a/k'); + await fs.write('a/w.ts', 'w'); + check(); + await fs.delete('a/k'); + check(); + server.files.set('c.ts', 'c'); + server.files.delete('a/x.ts'); + server.change([ + { type: 'created', path: 'c.ts', kind: 'file' }, + { type: 'deleted', path: 'a/x.ts', kind: 'file' }, + ]); + await settle(); + check(); + expect(fs.children('').map((entry) => entry.path)).toEqual(['b.ts', 'c.ts']); + await fs.refresh(); + check(); + fs.dispose(); + }); + it('saves without waiting for the content cache', async () => { const server = fakeServer({ 'a.ts': 'old' }); const stuck: ContentCache = { diff --git a/packages/project/test/fs/project-fs.spec.ts b/packages/project/test/fs/project-fs.spec.ts index 4b32e8aa..b7ba726d 100644 --- a/packages/project/test/fs/project-fs.spec.ts +++ b/packages/project/test/fs/project-fs.spec.ts @@ -1,4 +1,12 @@ -import { cpSync, mkdtempSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'; +import { + cpSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + utimesSync, + writeFileSync, +} from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; @@ -155,4 +163,37 @@ describe('ProjectFs', () => { writeFileSync(file, text); await project.fs.refresh(); }); + + it('opens the project again after the idle sweep closed it while the tab was away', async () => { + const project = service.current.get()!; + /** The sweep closes a project no socket holds: the tab's socket is gone meanwhile. */ + editor.projects.sweep(() => false, -1); + expect(editor.projects.openIds).toEqual([]); + (rpc as unknown as { _socket: { close(): void } })._socket.close(); + await waitFor(() => editor.projects.openIds.includes(project.id), 3000); + expect(editor.projects.openIds).toEqual([project.id]); + + const changes: FileChange[] = []; + const subscription = project.fs.onDidChange((batch) => changes.push(...batch)); + /** Server watcher initial scan. */ + await new Promise((resolve) => setTimeout(resolve, 300)); + writeFileSync(join(workspace, 'pong/apps/client/src/after-sweep.ts'), '// outside\n'); + await waitFor(() => changes.length > 0); + subscription.dispose(); + expect(changes).toEqual([ + { type: 'created', path: 'apps/client/src/after-sweep.ts', kind: 'file' }, + ]); + await expect( + project.fs.write('apps/client/src/after-sweep.ts', '// saved\n'), + ).resolves.toMatchObject({ path: 'apps/client/src/after-sweep.ts' }); + rmSync(join(workspace, 'pong/apps/client/src/after-sweep.ts')); + + /** The model follows the project again too. */ + const manifest = join(workspace, 'pong/package.json'); + const original = readFileSync(manifest, 'utf8'); + writeFileSync(manifest, original.replace('"pong-network"', '"pong-after-sweep"')); + await waitFor(() => project.model.get().name === 'pong-after-sweep'); + writeFileSync(manifest, original); + expect(project.model.get().name).toBe('pong-after-sweep'); + }); }); diff --git a/packages/project/test/service/client-project.spec.ts b/packages/project/test/service/client-project.spec.ts new file mode 100644 index 00000000..813b2a6f --- /dev/null +++ b/packages/project/test/service/client-project.spec.ts @@ -0,0 +1,242 @@ +import { describe, expect, it, vi } from 'vitest'; + +import { + type ProjectModel, + ProjectsContract, + type RecentProject, +} from '@nanoforge-dev/editor-protocol'; +import { type RpcClient, RpcError } from '@nanoforge-dev/editor-rpc'; + +import { ClientProject, memoryCacheFactory } from '../../src/service/client-project'; + +const MODEL: ProjectModel = { id: 'p', name: 'p', location: '/p', apps: [], diagnostics: [] }; +const RECENT: RecentProject = { + id: 'p', + name: 'p', + location: '/p', + ref: { path: '/p' }, + openedAt: new Date(0), +}; + +type OnError = (error: RpcError) => void; + +/** An RPC client whose streams the test refuses, and whose `recent` and `open` it gives. */ +const fakeRpc = (projects: { + recent: () => Promise; + open: () => Promise<{ id: string; name: string; trusted: boolean }>; +}) => { + const streams: Record = { changes: [], model: [] }; + /** Every new `fs.changes` stream after the first is refused at once. */ + let refuseNewStreams = false; + /** Answers of `fs.list` the test holds back, in call order (else an empty tree). */ + const lists: Promise<[]>[] = []; + let reconnected: (() => void) | undefined; + const rpc = { + api: (contract: unknown) => + contract === ProjectsContract + ? projects + : { list: () => lists.shift() ?? Promise.resolve([]) }, + subscribe: ( + _contract: unknown, + topic: string, + _params: unknown, + _onEvent: unknown, + handlers: { onError: OnError }, + ) => { + streams[topic]!.push(handlers.onError); + if (topic === 'changes' && refuseNewStreams && streams.changes!.length > 1) + queueMicrotask(() => handlers.onError(new RpcError('NOT_FOUND', 'Project p is not open'))); + return { dispose: () => undefined }; + }, + onDidReconnect: (listener: () => void) => { + reconnected = listener; + return { dispose: () => undefined }; + }, + } as unknown as RpcClient; + return { + rpc, + streams, + lists, + refuseNewStreams: () => (refuseNewStreams = true), + reconnect: () => reconnected?.(), + /** The server's sweep closed the project: its change stream is refused. */ + lose: () => streams.changes!.at(-1)!(new RpcError('NOT_FOUND', 'Project p is not open')), + }; +}; + +const settle = () => new Promise((resolve) => setTimeout(resolve, 20)); + +const start = async (server: ReturnType, trusted = false) => { + const project = new ClientProject(MODEL, server.rpc, memoryCacheFactory(), trusted); + await project.fs.initialize(); + const lost = vi.fn(); + project.onDidLose(lost); + return { project, lost }; +}; + +describe('ClientProject reopen', () => { + it('opens a project the server closed again, and follows it again', async () => { + const projects = { + recent: vi.fn(() => Promise.resolve([RECENT])), + open: vi.fn(() => Promise.resolve({ id: 'p', name: 'p', trusted: false })), + }; + const server = fakeRpc(projects); + const { project, lost } = await start(server); + server.lose(); + await settle(); + expect(projects.open).toHaveBeenCalledWith({ path: '/p' }); + expect(server.streams.changes).toHaveLength(2); + expect(server.streams.model).toHaveLength(2); + expect(lost).not.toHaveBeenCalled(); + project.dispose(); + }); + + it('gives up a project that comes back with another trust', async () => { + const projects = { + recent: vi.fn(() => Promise.resolve([RECENT])), + open: vi.fn(() => Promise.resolve({ id: 'p', name: 'p', trusted: true })), + }; + const server = fakeRpc(projects); + const { project, lost } = await start(server); + server.lose(); + await settle(); + expect(lost).toHaveBeenCalledOnce(); + expect(server.streams.changes).toHaveLength(1); + project.dispose(); + }); + + it('gives up a project the recent list does not have, without opening anything', async () => { + const projects = { + recent: vi.fn(() => Promise.resolve([])), + open: vi.fn(() => Promise.resolve({ id: 'p', name: 'p', trusted: false })), + }; + const server = fakeRpc(projects); + const { project, lost } = await start(server); + server.lose(); + await settle(); + expect(projects.open).not.toHaveBeenCalled(); + expect(lost).toHaveBeenCalledOnce(); + project.dispose(); + }); + + it('gives up when the open fails', async () => { + const projects = { + recent: vi.fn(() => Promise.resolve([RECENT])), + open: vi.fn(() => Promise.reject(new RpcError('NOT_FOUND', 'No project directory at /p'))), + }; + const server = fakeRpc(projects); + const { project, lost } = await start(server); + server.lose(); + await settle(); + expect(lost).toHaveBeenCalledOnce(); + project.dispose(); + }); + + it('opens nothing once disposed during the reopen', async () => { + let answer!: (recent: RecentProject[]) => void; + const projects = { + recent: vi.fn(() => new Promise((resolve) => (answer = resolve))), + open: vi.fn(() => Promise.resolve({ id: 'p', name: 'p', trusted: false })), + }; + const server = fakeRpc(projects); + const { project, lost } = await start(server); + server.lose(); + await settle(); + project.dispose(); + answer([RECENT]); + await settle(); + expect(projects.open).not.toHaveBeenCalled(); + expect(lost).not.toHaveBeenCalled(); + }); + + it('opens a project lost again and again only once', async () => { + const projects = { + recent: vi.fn(() => Promise.resolve([RECENT])), + open: vi.fn(() => Promise.resolve({ id: 'p', name: 'p', trusted: false })), + }; + const server = fakeRpc(projects); + server.refuseNewStreams(); + const { project, lost } = await start(server); + server.lose(); + await settle(); + server.lose(); + server.lose(); + await settle(); + expect(projects.open).toHaveBeenCalledOnce(); + expect(lost).toHaveBeenCalledOnce(); + project.dispose(); + }); + + it('tries again on the next loss when the open may pass', async () => { + const projects = { + recent: vi.fn(() => Promise.resolve([RECENT])), + open: vi + .fn() + .mockRejectedValueOnce(new RpcError('UNAVAILABLE', 'Editor server unreachable')) + .mockResolvedValue({ id: 'p', name: 'p', trusted: false }), + }; + const server = fakeRpc(projects); + const { project, lost } = await start(server); + server.lose(); + await settle(); + expect(lost).not.toHaveBeenCalled(); + server.lose(); + await settle(); + expect(projects.open).toHaveBeenCalledTimes(2); + expect(server.streams.changes).toHaveLength(2); + expect(lost).not.toHaveBeenCalled(); + project.dispose(); + }); + + it('gives up a project lost again within 30 s of its reopen, not later', async () => { + const now = vi.spyOn(Date, 'now').mockReturnValue(1_000_000); + const projects = { + recent: vi.fn(() => Promise.resolve([RECENT])), + open: vi.fn(() => Promise.resolve({ id: 'p', name: 'p', trusted: false })), + }; + const later = fakeRpc(projects); + const first = await start(later); + later.lose(); + await settle(); + now.mockReturnValue(1_000_000 + 31_000); + later.lose(); + await settle(); + expect(projects.open).toHaveBeenCalledTimes(2); + expect(first.lost).not.toHaveBeenCalled(); + first.project.dispose(); + + projects.open.mockClear(); + now.mockReturnValue(2_000_000); + const soon = fakeRpc(projects); + const second = await start(soon); + soon.lose(); + await settle(); + now.mockReturnValue(2_000_000 + 29_000); + soon.lose(); + await settle(); + expect(projects.open).toHaveBeenCalledOnce(); + expect(second.lost).toHaveBeenCalledOnce(); + second.project.dispose(); + now.mockRestore(); + }); + + it('takes no refusal of a request sent before the reopen for a new loss', async () => { + const projects = { + recent: vi.fn(() => Promise.resolve([RECENT])), + open: vi.fn(() => Promise.resolve({ id: 'p', name: 'p', trusted: false })), + }; + const server = fakeRpc(projects); + const { project, lost } = await start(server); + let refuse!: (error: RpcError) => void; + server.lists.push(new Promise<[]>((_resolve, reject) => (refuse = reject))); + /** The reconnect's refresh is on its way when the stream reports the loss. */ + server.reconnect(); + server.lose(); + await settle(); + refuse(new RpcError('NOT_FOUND', 'Project p is not open')); + await settle(); + expect(projects.open).toHaveBeenCalledOnce(); + expect(lost).not.toHaveBeenCalled(); + project.dispose(); + }); +});