An open-source, self-hosted system for apps built with web technologies.
The System clears a Program's storage and measures it, and any storage area's size
zohayrslileh673ddb1facd8
diff --git a/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts b/source/client/core/link-manager/auth-manager/program-manager/program-manager.tsindex 2f87686..89d1bc8 100644--- a/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts+++ b/source/client/core/link-manager/auth-manager/program-manager/program-manager.ts@@ -135,6 +135,16 @@ export default class ProgramManager extends TheLink {)}+ public async clearStorage(subject: unknown, asker: string) {++ await this.$outbound.publishFirst("/clear-storage", subject, asker)+ }++ public async storageSize(subject: unknown) {++ return await this.$outbound.publishFirst("/storage-size", subject) as number+ }+public async forget(subject: unknown, asker: string) {return await this.$outbound.publishFirst("/forget-program", subject, asker)diff --git a/source/client/view/components/desktop-host/host.ts b/source/client/view/components/desktop-host/host.tsindex 988e278..f9a5fb0 100644--- a/source/client/view/components/desktop-host/host.ts+++ b/source/client/view/components/desktop-host/host.ts@@ -592,6 +592,10 @@ export default function host(authManager: AuthManager, pane: string, viewport: D// core serves this and a server half both.if (word === "program-exit-processes") return [await processManager.exitAll((await permittedProgram(args[0])).identity, pane)]+ if (word === "program-clear-storage") return [await programManager.clearStorage(address(await permittedProgram(args[0])), pane)]++ if (word === "program-storage-size") return [await programManager.storageSize(address(await permittedProgram(args[0])))]+if (word === "observe") {const half = args[2]diff --git a/source/libs/file-area.ts b/source/libs/file-area.tsindex 227150b..72c31d7 100644--- a/source/libs/file-area.ts+++ b/source/libs/file-area.ts@@ -77,6 +77,16 @@ export default class FileArea {mkdirSync(path, { recursive: true })}+ /** How many bytes the files beneath a directory hold; `0` when it does not exist. Links are not followed. */+ public size(joins: string[] = []) {++ const found = this.stat(joins)++ if (found && found.kind !== "directory") throw new Error(`${this.resolve(joins)} is not a Storage directory`)++ return found ? bytesBeneath(this.resolve(joins)) : 0+ }+public stat(joins: string[]): EntryStat | null {let found@@ -309,3 +319,19 @@ export type StorageReadOptions = [offset?: number, length?: number]export class MissingAreaEntryError extends Error { }export class NotFileError extends Error { }++function bytesBeneath(directory: string): number {++ let total = 0++ for (const entry of readdirSync(directory, { withFileTypes: true })) {++ const path = join(directory, entry.name)++ if (entry.isDirectory()) total += bytesBeneath(path)++ else if (entry.isFile()) total += lstatSync(path).size+ }++ return total+}diff --git a/source/server/core/link-manager/auth-manager/auth-manager.ts b/source/server/core/link-manager/auth-manager/auth-manager.tsindex 455087c..79e5821 100644--- a/source/server/core/link-manager/auth-manager/auth-manager.ts+++ b/source/server/core/link-manager/auth-manager/auth-manager.ts@@ -165,6 +165,7 @@ export default class AuthManager extends TheLink {if (operation === "clear") return area.clear(values)if (operation === "space") return area.space(values)+ if (operation === "size") return area.size(values)throw new Error(`System storage does not know "${operation}"`)}diff --git a/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts b/source/server/core/link-manager/auth-manager/process-manager/process-manager.tsindex a0a0ec6..29fff50 100644--- a/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts+++ b/source/server/core/link-manager/auth-manager/process-manager/process-manager.ts@@ -2487,6 +2487,10 @@ export default class ProcessManager extends TheLink {if (word === "program-exit-processes") return [await this.system.exitProgramProcesses(heldProgram(rest[0]), process.identity)]+ if (word === "program-clear-storage") return [await this.system.clearProgramStorage(heldProgram(rest[0]), process.identity)]++ if (word === "program-storage-size") return [this.system.programStorageSize(heldProgram(rest[0]))]+if (word === "observe") {const kind = rest[3]diff --git a/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts b/source/server/core/link-manager/auth-manager/program-manager/program-manager.tsindex 465c039..a4173ed 100644--- a/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts+++ b/source/server/core/link-manager/auth-manager/program-manager/program-manager.ts@@ -32,6 +32,9 @@ import shortIdentity from "@libs/short-identity"const maximumProcessesPerProgram = 20+/** What a Program keeps of its own in its storage, besides its store: emptied by clearing its storage. */+const programData = ["data", "cache", "database.sqlite", "database.sqlite-wal", "database.sqlite-shm"]+type Registration = {installed: booleantransitionOwnsIdentity?: boolean@@ -350,6 +353,18 @@ export default class ProgramManager extends TheLink {return this.installedAt(this.held(subject))}+ @Subscribe("/clear-storage")+ protected async clearStorageProgram(subject: unknown, asker?: unknown) {++ await this.clearStorage(this.held(subject), typeof asker === "string" ? asker : null)+ }++ @Subscribe("/storage-size")+ protected async storageSizeProgram(subject: unknown) {++ return this.storageSize(this.held(subject))+ }+@Subscribe("/pinned")protected async pinnedProgram(subject: unknown, operation: "get" | "pin" | "unpin") {@@ -888,6 +903,8 @@ export default class ProgramManager extends TheLink {if (operation === "space") return place.space(joins)+ if (operation === "size") return place.size(joins)+throw new Error(`The host does not know the storage operation "${operation}"`)}@@ -1255,6 +1272,35 @@ export default class ProgramManager extends TheLink {})}+ // What a Program keeps is emptied while it changes, so no Process of it starts and writes in the+ // middle. The store empties through itself, so whoever follows a key hears it go; the database+ // closes before its files go. What the owner decided and what the System recorded stay: the+ // Program's state and its logs.+ public async clearStorage(program: Program, asker: string | null = null) {++ await this.change(program.identity, async () => {++ const entry = this.find(program.identity)++ await this.authManager.processManager.exitAll(entry.identity, asker)++ // A store never written has nothing to empty, and opening it would make its file.+ if (this.opened.has(entry.identity) || existsSync(join(entry.program.storagePath, "store.sqlite"))) await this.storeOf(entry.program).clear()++ this.kept.get(entry.identity)?.close()++ this.kept.delete(entry.identity)++ for (const kept of programData) rmSync(join(entry.program.storagePath, kept), { recursive: true, force: true })+ })+ }++ /** How many bytes everything a Program keeps in the System holds, its logs and state included. */+ public storageSize(program: Program) {++ return new FileArea(program.storagePath, "this program's storage").size()+ }+// Uninstalling ends Processes and forgets the runtime entry: its handle ends as an exited// Process's does. Purge also removes its storage; otherwise a later install finds it.public async uninstall(program: Program, options: ProgramUninstallOptions = {}, asker: string | null = null, output: CommandOutput = () => undefined) {diff --git a/source/server/core/system.ts b/source/server/core/system.tsindex f71ff8d..c327bee 100644--- a/source/server/core/system.ts+++ b/source/server/core/system.ts@@ -196,6 +196,16 @@ export default class System {return this.programManager.runProcess(program, launch, watching, parent)}+ public clearProgramStorage(program: Program, asker: string | null = null) {++ return this.programManager.clearStorage(program, asker)+ }++ public programStorageSize(program: Program) {++ return this.programManager.storageSize(program)+ }+public exitProgramProcesses(program: Program, asker: string | null = null) {return this.processManager.exitAll(program.identity, asker)@@ -659,6 +669,7 @@ function operateArea(place: FileArea, operation: string, joins: string[], input?}if (operation === "space") return place.space(joins)+ if (operation === "size") return place.size(joins)throw new Error(`The host does not know the storage operation "${operation}"`)}diff --git a/tests/program-installation-lifecycle.test.ts b/tests/program-installation-lifecycle.test.tsindex 85be6a0..b45d21c 100644--- a/tests/program-installation-lifecycle.test.ts+++ b/tests/program-installation-lifecycle.test.ts@@ -18,7 +18,7 @@ function fixture(context: TestContext) {const announceHost = vi.fn()const auth = Object.assign(new TheLink(), {linkManager: { application: { storage: new FileManager(directory, "system"), icons: { system: "", defaultProgram: "" } } },- processManager: { processes: new Map(), exitAll, announceHost, announceSubject: vi.fn() }+ processManager: { processes: new Map(), exitAll, announceHost, announceSubject: vi.fn(async () => undefined) }}) as unknown as AuthManagerconst manager = new ProgramManager(auth)const definition = (installCommand = `node -e "process.stdout.write('preparing')"`, installLaunch?: true | Launch) => new Program({@@ -173,3 +173,36 @@ test("uninstalling ends the Program's Processes and forgets its handle; its dataexpect(manager.programs.has(program.identity)).toBe(false)expect(existsSync(home)).toBe(false)})++test("clearing storage ends the Program's Processes and empties what it keeps, keeping the owner's decisions and its logs", async context => {+ const { manager, exitAll, definition } = fixture(context)+ const entry = await manager.install(definition())+ const program = entry.program+ const address = { identity: program.identity, reference: program.reference }+ const storage = program.storagePath+ mkdirSync(join(storage, "data"), { recursive: true })+ writeFileSync(join(storage, "data", "note.txt"), "kept")+ mkdirSync(join(storage, "cache"), { recursive: true })+ writeFileSync(join(storage, "cache", "thumbnail.bin"), "1234")+ await manager.store(address, "set", "draft", "hello")+ manager.databaseOf(program).query("CREATE TABLE notes (title TEXT)")+ manager.logsOf(program).record("process", "server", "note", "it said something")+ const pinnedAt = await manager.pinned(program, "pin")+ const before = manager.storageSize(program)+ expect(before).toBeGreaterThan(8)++ await manager.clearStorage(program)++ expect(exitAll).toHaveBeenCalledWith(program.identity, null)+ expect(existsSync(join(storage, "data"))).toBe(false)+ expect(existsSync(join(storage, "cache"))).toBe(false)+ expect(existsSync(join(storage, "database.sqlite"))).toBe(false)+ expect(await manager.store(address, "get", "draft")).toBeUndefined()+ // What the owner decided, when it was installed, and what it said stay.+ expect(await manager.pinned(program, "get")).toBe(pinnedAt)+ expect(manager.installedAt(program)).toBe(entry.installedAt)+ expect(existsSync(join(storage, "logs.sqlite"))).toBe(true)+ expect(manager.storageSize(program)).toBeLessThan(before)+ // Its database opens again, empty.+ expect(() => manager.databaseOf(program).query("CREATE TABLE notes (title TEXT)")).not.toThrow()+})