Skip to content

An open-source, self-hosted system for apps built with web technologies.

Implement storage and local window capabilities

zohayrslilehb35cb0cd9363
diff --git a/scripts/contracts/client-surface.ts b/scripts/contracts/client-surface.ts
index 5301322..07f59f6 100644
--- a/scripts/contracts/client-surface.ts
+++ b/scripts/contracts/client-surface.ts
@@ -92,6 +92,28 @@ const interrupted = first.move("bare", { x: 100, y: 110 }, { duration: 200, wait
await first.move("bare", { x: 120, y: 130 })
await assert.rejects(interrupted, /interrupted/)
+const following = first.follow("bare", "ordinary", transaction)
+const followRevision = represented(first, "bare:0").geometryAnimation!.revision
+first.reconcile(clients)
+assert.equal(represented(first, "bare:0").geometryAnimation!.revision, followRevision)
+first.complete("bare", "geometry", followRevision)
+await following
+assert.deepEqual(first.state("bare").position, first.state("ordinary").position)
+
+await first.move("ordinary", { x: 150, y: 160 })
+assert.deepEqual(first.state("bare").position, { x: 150, y: 160 })
+
+const unfollowing = first.unfollow("bare", transaction)
+const unfollowRevision = represented(first, "bare:0").geometryAnimation!.revision
+first.complete("bare", "geometry", unfollowRevision)
+await unfollowing
+assert.deepEqual(first.state("bare").position, { x: 120, y: 130 })
+
+await first.follow("bare", "ordinary")
+await first.move("bare", { x: 125, y: 135 })
+await first.move("ordinary", { x: 155, y: 165 })
+assert.deepEqual(first.state("bare").position, { x: 125, y: 135 })
+
const surfaceWaiting = first.addSurface("bare", visibility)
const surfaceRevision = surface(first, "bare:0").transition!.revision
first.complete("bare", "surface", surfaceRevision)
@@ -146,6 +168,8 @@ const calls: unknown[][] = []
const localWindow = {
state(identity: string) { return { position: identity === "target" ? { x: 70, y: 80 } : { x: 0, y: 0 } } },
move(identity: string, value: unknown, motion: Transaction | undefined) { calls.push(["move", identity, value, motion]) },
+ follow(identity: string, followed: string, motion: Transaction | undefined) { calls.push(["follow", identity, followed, motion]) },
+ unfollow(identity: string, motion: Transaction | undefined) { calls.push(["unfollow", identity, motion]) },
addSurface(identity: string, motion: Transaction) { calls.push(["add", identity, motion]) },
removeSurface(identity: string, motion: Transaction) { calls.push(["remove", identity, motion]) }
}
@@ -182,11 +206,15 @@ assert(Array.isArray(parentAnswer))
const retainedParent = parentAnswer[0] as { identity: string }
assert.equal(retainedParent.identity, parent.identity)
await request("windowLocalMove", requesterAddress, { x: 70, y: 80 })
+await request("windowLocalFollow", requesterAddress, targetAddress, visibility)
+await request("windowLocalUnfollow", requesterAddress, visibility)
await request("windowLocalSurfaceAdd", requesterAddress, undefined, visibility)
await request("windowLocalSurfaceRemove", requesterAddress, undefined, visibility)
assert.deepEqual(calls, [
["move", "requester", { x: 70, y: 80 }, undefined],
+ ["follow", "requester", "target", visibility],
+ ["unfollow", "requester", visibility],
["add", "requester", visibility],
["remove", "requester", visibility]
])
diff --git a/scripts/contracts/storage.ts b/scripts/contracts/storage.ts
index 93454ce..d106b8b 100644
--- a/scripts/contracts/storage.ts
+++ b/scripts/contracts/storage.ts
@@ -1,5 +1,5 @@
import assert from "node:assert/strict"
-import { mkdirSync, mkdtempSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"
+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join, resolve } from "node:path"
import FileArea, { FileSystem } from "@libs/file-area"
@@ -21,7 +21,7 @@ try {
}).storage
assert.equal(await systemStorage.call(authManager, "path", []), home.path)
- assert.equal(await systemStorage.call(authManager, "resolve", ["..", "outside"]), outside)
+ assert.equal(await systemStorage.call(authManager, "path", ["..", "outside"]), outside)
mkdirSync(join(root, "kept"), { recursive: true })
mkdirSync(join(root, "nested"), { recursive: true })
@@ -32,6 +32,27 @@ try {
assert.deepEqual(readdirSync(join(root, "nested")), [])
assert.deepEqual(readdirSync(join(root, "kept")), ["value.txt"])
+
+ storage.create(["created"])
+ await storage.write(["created", "value.txt"], new Blob(["storage"]).stream(), undefined, false)
+ await storage.append(["created", "value.txt"], new Blob([" file"]).stream())
+ assert.equal(readFileSync(join(root, "created", "value.txt"), "utf8"), "storage file")
+ assert.equal(await new Response(storage.stream(["created", "value.txt"], [8, 4])).text(), "file")
+ assert.deepEqual(storage.list([], [true]), [
+ { kind: "storage", path: ["created"] },
+ { kind: "file", path: ["created", "value.txt"] },
+ { kind: "storage", path: ["kept"] },
+ { kind: "file", path: ["kept", "value.txt"] },
+ { kind: "storage", path: ["nested"] }
+ ])
+ assert.ok(storage.space().capacity > 0)
+
+ const changes = storage.watch(["created"])
+ const changed = changes.next()
+ await new Promise(resolve => setTimeout(resolve, 10))
+ writeFileSync(join(root, "created", "watched.txt"), "changed")
+ assert.match((await changed).value?.event ?? "", /^(change|rename)$/)
+ await changes.return(undefined)
assert.throws(() => storage.resolve(["..", "outside"]), /configured directory/)
mkdirSync(outside, { recursive: true })
diff --git a/scripts/contracts/uploads.ts b/scripts/contracts/uploads.ts
index 379e68a..8c3d125 100644
--- a/scripts/contracts/uploads.ts
+++ b/scripts/contracts/uploads.ts
@@ -15,9 +15,8 @@ try {
const upload = uploads.stat(file)
assert(upload)
- assert.equal(upload.file, file)
- assert.equal(upload.type, "text/plain")
assert.equal(upload.size, 13)
+ assert.equal(typeof upload.modifiedAt, "number")
assert.equal(await readFile(uploads.path(file), "utf8"), "hello uploads")
assert.equal(uploads.stat("00000000-0000-0000-0000-000000000000.txt"), null)
assert.throws(() => uploads.stat("../outside.txt"), /not an upload file/)
@@ -36,7 +35,7 @@ try {
const written = await uploads.write(extension, content, signal)
const upload = uploads.stat(written)
assert(upload)
- return upload
+ return { file: written, ...upload }
}
}
}
@@ -55,13 +54,15 @@ try {
assert.equal(response.status, 200)
const created = await response.json()
- assert.equal(created.type, "application/json")
+ assert.equal(created.file.endsWith(".json"), true)
+ assert.equal(created.size, 14)
+ assert.equal(typeof created.modifiedAt, "number")
const described = await view.request(`http://system/uploads/${created.file}/stat`)
const downloaded = await view.request(`http://system/uploads/${created.file}`)
assert.equal(described.status, 200)
assert.equal(downloaded.status, 200)
- assert.deepEqual(await described.json(), created)
+ assert.deepEqual(await described.json(), { size: created.size, modifiedAt: created.modifiedAt })
assert.deepEqual(JSON.parse(await downloaded.text()), { ready: true })
assert.equal((await view.request("http://system/uploads/not-a-key")).status, 400)
assert.equal((await view.request("http://system/uploads/00000000-0000-0000-0000-000000000000.txt")).status, 404)
diff --git a/source/client/core/application.ts b/source/client/core/application.ts
index 024dc49..a101e33 100644
--- a/source/client/core/application.ts
+++ b/source/client/core/application.ts
@@ -3,7 +3,7 @@ import { type ProxyOutcome, type ProxyRequest, type ProxyResponse, proxyMediaTyp
import { storageMediaType, type StorageRequest } from "@server/core/protocol/storage"
import { frame, frameBlob, unframe } from "@libs/framing"
import messagepack from "@the-link/messagepack"
-import type { Upload } from "@phreshos/core"
+import type { FileStat, Upload } from "@phreshos/core"
export default class Application {
@@ -66,7 +66,7 @@ export default class Application {
return response.body
}
- public async uploadStat(file: string): Promise<Upload | null> {
+ public async uploadStat(file: string): Promise<FileStat | null> {
const response = await fetch(`${this.doors.uploads}/${encodeURIComponent(file)}/stat`)
@@ -120,18 +120,23 @@ export default class Application {
}
}
- public async storageStream(request: StorageTarget, authorization: string, signal?: AbortSignal) {
+ public async storageStream(request: StorageTarget, authorization: string, signal?: AbortSignal, options: { offset?: number, length?: number } = {}) {
- const response = await this.storage({ ...request, operation: "stream" }, null, authorization, signal)
+ const response = await this.storage({ ...request, operation: "stream", ...options }, null, authorization, signal)
if (!response.body) throw new Error("The storage response has no body")
return response.body
}
- public async storageWrite(request: StorageTarget, body: ClientBody, authorization: string, signal?: AbortSignal) {
+ public async storageWrite(request: StorageTarget, body: ClientBody, authorization: string, signal?: AbortSignal, overwrite = true) {
- await this.storage({ ...request, operation: "write" }, body, authorization, signal)
+ await this.storage({ ...request, operation: "write", overwrite }, body, authorization, signal)
+ }
+
+ public async storageAppend(request: StorageTarget, body: ClientBody, authorization: string, signal?: AbortSignal) {
+
+ await this.storage({ ...request, operation: "append" }, body, authorization, signal)
}
private async storage(request: StorageRequest, body: ClientBody | null, authorization: string, signal?: AbortSignal) {
diff --git a/source/client/core/link-manager/auth-manager/auth-manager.ts b/source/client/core/link-manager/auth-manager/auth-manager.ts
index 26ed83a..ad14217 100644
--- a/source/client/core/link-manager/auth-manager/auth-manager.ts
+++ b/source/client/core/link-manager/auth-manager/auth-manager.ts
@@ -1,5 +1,5 @@
import { AuthManagerSnapshot } from "@server/core/link-manager/auth-manager/auth-manager"
-import { Intercept } from "@the-link/core/decorators"
+import { Intercept, Subscribe } from "@the-link/core/decorators"
import ProcessManager from "./process-manager/process-manager"
import ProgramManager from "./program-manager/program-manager"
import DialogManager from "./dialog-manager"
@@ -11,6 +11,8 @@ import {
type PermissionRequest
} from "@phreshos/core"
import ShellManager from "./shell-manager"
+import StreamRelay from "@client/core/link-manager/stream-relay"
+import { type StorageChange } from "@phreshos/core"
export default class AuthManager extends TheLink {
@@ -28,6 +30,8 @@ export default class AuthManager extends TheLink {
public readonly shellManager: ShellManager
+ private readonly storageChanges = new StreamRelay("Storage changes", storageChange)
+
public constructor(linkManager: LinkManager, authorization: string, payload: AuthManagerSnapshot) {
super()
@@ -61,9 +65,25 @@ export default class AuthManager extends TheLink {
this.linkManager.emitToSession(`/auth${event}`, this.authorization, ...values)
}
- public async storage(operation: string, values: string[]) {
+ public async storage(operation: string, path: string[], input?: unknown) {
+
+ return await this.$outbound.publishFirst("/storage", operation, path, input)
+ }
+
+ public watchStorage(target: StorageWatchTarget) {
+
+ return this.storageChanges.open(
+
+ stream => this.$outbound.publishFirst("/storage-watch", stream, target),
+
+ stream => this.$outbound.publish("/storage-watch-cancel", stream)
+ )
+ }
+
+ @Subscribe("/storage-change")
+ protected storageChange(stream: string, value: unknown) {
- return await this.$outbound.publishFirst("/storage", operation, values)
+ this.storageChanges.receive(stream, value)
}
public async uploadsPath() {
@@ -111,3 +131,19 @@ export default class AuthManager extends TheLink {
this.disconnectFrom(this.linkManager, "/auth")
}
}
+
+export type StorageWatchTarget =
+ | Readonly<{ scope: "system", path: string[], recursive: boolean }>
+ | Readonly<{ scope: "program", program: { identity: string, reference: string }, area: "data" | "cache", path: string[], recursive: boolean }>
+
+function storageChange(value: unknown): StorageChange {
+
+ const change = value as Partial<StorageChange> | null
+
+ if (!change || (change.event !== "change" && change.event !== "rename") || change.path !== null && typeof change.path !== "string") {
+
+ throw new Error("The System returned an invalid Storage change")
+ }
+
+ return Object.freeze({ event: change.event, path: change.path })
+}
diff --git a/source/client/view/components/desktop-host/client-process-boundary.ts b/source/client/view/components/desktop-host/client-process-boundary.ts
index 1c72618..ae0f583 100644
--- a/source/client/view/components/desktop-host/client-process-boundary.ts
+++ b/source/client/view/components/desktop-host/client-process-boundary.ts
@@ -607,6 +607,54 @@ export default class ClientProcessBoundary extends TheLink {
iterator = operation[Symbol.asyncIterator]()
}
+ else if (args[0] === "storage-watch") {
+
+ const scope = args[1]
+
+ const path = storagePath(scope === "program" ? args[4] : args[2])
+
+ const options = storageWatchOptions(scope === "program" ? args[5] : args[3])
+
+ if (scope === "system") {
+
+ const resolved = await this.authManager.storage("path", path)
+
+ if (typeof resolved !== "string") throw new Error("The System returned an invalid Storage path")
+
+ await this.systemAccess.requireStorage(resolved, "read")
+
+ iterator = this.authManager.watchStorage({ scope, path, recursive: options.recursive })[Symbol.asyncIterator]()
+ }
+
+ else if (scope === "program") {
+
+ if (!isHandleAddress(args[2])) throw new Error("A Program handle is required")
+
+ if (args[3] !== "data" && args[3] !== "cache") throw new Error("A Program Storage area is data or cache")
+
+ const program = this.authManager.programManager.programs.get(args[2].identity)
+
+ if (!program || program.reference !== args[2].reference) throw new Error("The Program represented by this handle does not exist")
+
+ await this.systemAccess.program(program)
+
+ iterator = this.authManager.watchStorage({
+
+ scope,
+
+ program: args[2],
+
+ area: args[3],
+
+ path,
+
+ recursive: options.recursive
+
+ })[Symbol.asyncIterator]()
+ }
+
+ else throw new Error("A Storage watch scope is system or program")
+ }
else {
if (args[0] !== "install" && args[0] !== "uninstall" && args[0] !== "run") throw new Error(`The desktop does not know the stream operation "${String(args[0])}"`)
@@ -938,6 +986,26 @@ export default class ClientProcessBoundary extends TheLink {
}
+function storagePath(value: unknown) {
+
+ if (!Array.isArray(value) || value.some(part => typeof part !== "string")) throw new Error("A Storage path is a list of names")
+
+ return value as string[]
+}
+
+function storageWatchOptions(value: unknown) {
+
+ if (value === undefined) return { recursive: false }
+
+ if (!value || typeof value !== "object") throw new Error("Storage watch options must be an object")
+
+ const recursive = (value as { recursive?: unknown }).recursive
+
+ if (recursive !== undefined && typeof recursive !== "boolean") throw new Error("Storage recursive must be boolean")
+
+ return { recursive: recursive === true }
+}
+
function runEvent(authManager: AuthManager, value: unknown) {
const event = value as { event?: unknown, process?: SdkProcessSource } | null
diff --git a/source/client/view/components/desktop-host/host.ts b/source/client/view/components/desktop-host/host.ts
index 505d193..1890fc2 100644
--- a/source/client/view/components/desktop-host/host.ts
+++ b/source/client/view/components/desktop-host/host.ts
@@ -769,6 +769,47 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
return []
}
+ if (word === "windowLocalMinimize") {
+
+ const target = localProcess(args[0])
+ requireLocalWindowLayer(target.client!.window.layer)
+
+ if (typeof args[1] !== "boolean") throw new Error("Local Window minimize takes a boolean state")
+
+ await localWindow.minimize(target.identity, args[1], visualTransaction(args[2]))
+
+ return []
+ }
+
+ if (word === "windowLocalFollow") {
+
+ const target = localProcess(args[0])
+ requireLocalWindowLayer(target.client!.window.layer)
+ const followed = await permittedProcess(args[1])
+ clientOf(followed)
+ await localWindow.follow(target.identity, followed.identity, visualTransaction(args[2]))
+
+ return []
+ }
+
+ if (word === "windowLocalUnfollow") {
+
+ const target = localProcess(args[0])
+ requireLocalWindowLayer(target.client!.window.layer)
+ await localWindow.unfollow(target.identity, visualTransaction(args[1]))
+
+ return []
+ }
+
+ if (word === "windowLocalRaise") {
+
+ const target = localProcess(args[0])
+ requireLocalWindowLayer(target.client!.window.layer)
+ localWindow.raise(target.identity)
+
+ return []
+ }
+
if (word === "changeTitle") {
await clientOf(await permittedProcess(args[0])).window.changeTitle(String(args[1] ?? ""))
@@ -816,18 +857,18 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
const program = await permittedProgram(args[0])
- if (operation === "path" || operation === "resolve") {
+ if (operation === "path" || operation === "name") {
const path = await programManager.area(address(program), word, operation, args.slice(2))
- if (typeof path !== "string") throw new Error("The System returned an invalid Storage path")
+ if (typeof path !== "string") throw new Error("The System returned invalid Storage text")
- await access.requireStorage(path)
+ if (operation === "path") await access.requireStorage(path)
return [path]
}
- if (operation === "stream" || operation === "write") {
+ if (operation === "stream" || operation === "write" || operation === "append") {
const joins = args[2]
@@ -839,11 +880,24 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
try {
- if (operation === "write") {
+ if (operation === "write" || operation === "append") {
if (!clientBody(args[3])) throw new Error("Writing takes bytes")
- await authManager.linkManager.application.storageWrite(request, args[3], authManager.authorization, controller.signal)
+ if (operation === "append") await authManager.linkManager.application.storageAppend(request, args[3], authManager.authorization, controller.signal)
+
+ else await authManager.linkManager.application.storageWrite(
+
+ request,
+
+ args[3],
+
+ authManager.authorization,
+
+ controller.signal,
+
+ storageWriteOptions(args[5]).overwrite
+ )
control.close()
@@ -852,7 +906,16 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
const body = controlled(
- await authManager.linkManager.application.storageStream(request, authManager.authorization, controller.signal),
+ await authManager.linkManager.application.storageStream(
+
+ request,
+
+ authManager.authorization,
+
+ controller.signal,
+
+ storageReadOptions(args[5])
+ ),
controller,
@@ -888,47 +951,40 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
if (word === "host-storage") {
const operation = String(args[0])
- const paths = args.slice(1)
-
- if (paths.some(path => typeof path !== "string")) throw new Error("A storage path is a list of names")
-
- if (operation === "path") {
+ const paths = args[1]
- const path = await authManager.storage(operation, [])
-
- if (typeof path !== "string") throw new Error("The System returned an invalid Storage path")
-
- await access.requireStorage(path)
-
- return [path]
- }
+ if (!Array.isArray(paths) || paths.some(path => typeof path !== "string")) throw new Error("A Storage path is a list of names")
- const path = await authManager.storage("resolve", paths as string[])
+ const path = await authManager.storage("path", paths)
if (typeof path !== "string") throw new Error("The System returned an invalid Storage path")
- if (operation === "resolve") {
+ if (operation === "path" || operation === "name") {
await access.requireStorage(path)
- return [path]
+ return [await authManager.storage(operation, paths, args[2])]
}
- const required = operation === "delete" || operation === "clear" ? "delete" : "read"
+ const required = operation === "delete-storage" || operation === "delete-file" || operation === "clear"
+ ? "delete"
+ : operation === "create"
+ ? "write"
+ : "read"
await access.requireStorage(path, required)
- return [await authManager.storage(operation, paths as string[])]
+ return [await authManager.storage(operation, paths, args[2])]
}
- if (word === "host-storage-stream" || word === "host-storage-write") {
+ if (word === "host-storage-stream" || word === "host-storage-write" || word === "host-storage-append") {
const path = args[0]
if (!Array.isArray(path) || path.some(part => typeof part !== "string")) throw new Error("A storage path is a list of names")
- const writing = word === "host-storage-write"
- const resolved = await authManager.storage("resolve", path)
+ const writing = word !== "host-storage-stream"
+ const resolved = await authManager.storage("path", path)
if (typeof resolved !== "string") throw new Error("The System returned an invalid Storage path")
@@ -941,13 +997,35 @@ export default function host(authManager: AuthManager, pane: string, desktop: ()
if (writing) {
if (!clientBody(args[1])) throw new Error("Writing takes bytes")
- await authManager.linkManager.application.storageWrite(request, args[1], authManager.authorization, controller.signal)
+ if (word === "host-storage-append") await authManager.linkManager.application.storageAppend(request, args[1], authManager.authorization, controller.signal)
+
+ else await authManager.linkManager.application.storageWrite(
+
+ request,
+
+ args[1],
+
+ authManager.authorization,
+
+ controller.signal,
+
+ storageWriteOptions(args[3]).overwrite
+ )
control.close()
return []
}
const body = controlled(
- await authManager.linkManager.application.storageStream(request, authManager.authorization, controller.signal),
+ await authManager.linkManager.application.storageStream(
+
+ request,
+
+ authManager.authorization,
+
+ controller.signal,
+
+ storageReadOptions(args[3])
+ ),
controller,
control
)
@@ -1158,6 +1236,36 @@ function clientBody(value: unknown): value is ClientBody {
return value instanceof Blob || value instanceof ReadableStream
}
+function storageReadOptions(value: unknown) {
+
+ if (value === undefined) return {}
+
+ if (!value || typeof value !== "object") throw new Error("Storage read options must be an object")
+
+ const options = value as { offset?: unknown, length?: unknown }
+
+ if (options.offset !== undefined && (!Number.isSafeInteger(options.offset) || (options.offset as number) < 0)) throw new Error("A Storage read offset must be a non-negative safe integer")
+
+ if (options.length !== undefined && (!Number.isSafeInteger(options.length) || (options.length as number) < 0)) throw new Error("A Storage read length must be a non-negative safe integer")
+
+ if (typeof options.offset === "number" && typeof options.length === "number" && !Number.isSafeInteger(options.offset + options.length)) throw new Error("A Storage byte range must use safe integers")
+
+ return { offset: options.offset as number | undefined, length: options.length as number | undefined }
+}
+
+function storageWriteOptions(value: unknown) {
+
+ if (value === undefined) return { overwrite: true }
+
+ if (!value || typeof value !== "object") throw new Error("Storage write options must be an object")
+
+ const overwrite = (value as { overwrite?: unknown }).overwrite
+
+ if (overwrite !== undefined && typeof overwrite !== "boolean") throw new Error("Storage overwrite must be boolean")
+
+ return { overwrite: overwrite !== false }
+}
+
function cancellation(value: unknown, operation: string) {
if (!(value instanceof MessagePort)) throw new Error(`${operation} needs a cancellation channel`)
diff --git a/source/client/view/components/desktop-host/local-window.ts b/source/client/view/components/desktop-host/local-window.ts
index c113ca4..fb64a67 100644
--- a/source/client/view/components/desktop-host/local-window.ts
+++ b/source/client/view/components/desktop-host/local-window.ts
@@ -24,6 +24,7 @@ export type LocalWindowState = WindowState & Readonly<{
depth: number
surface: LocalSurfaceState | null
geometryAnimation: LocalAnimation | null
+ minimizeAnimation: LocalAnimation | null
}>
/** The only interface through which an iframe changes its local representation. */
@@ -32,12 +33,14 @@ export interface LocalWindowHost {
move(identity: string, position: Position, transaction?: Transaction): Promise<void>
resize(identity: string, size: Size, transaction?: Transaction): Promise<void>
geometry(identity: string, geometry: WindowGeometry, transaction?: Transaction): Promise<void>
- minimize(identity: string, minimized: boolean): void
+ minimize(identity: string, minimized: boolean, transaction?: Transaction): Promise<void>
+ follow(identity: string, target: string, transaction?: Transaction): Promise<void>
+ unfollow(identity: string, transaction?: Transaction): Promise<void>
title(identity: string, title: string): void
raise(identity: string): void
addSurface(identity: string, transaction?: Transaction): Promise<void>
removeSurface(identity: string, transaction?: Transaction): Promise<void>
- complete(identity: string, kind: "geometry" | "surface", revision: number): void
+ complete(identity: string, kind: "geometry" | "minimize" | "surface", revision: number): void
release(identity: string): void
}
diff --git a/source/client/view/components/window-manager/local-windows.ts b/source/client/view/components/window-manager/local-windows.ts
index 3635ed2..4ab4b7a 100644
--- a/source/client/view/components/window-manager/local-windows.ts
+++ b/source/client/view/components/window-manager/local-windows.ts
@@ -16,6 +16,7 @@ export default class LocalWindows implements LocalWindowHost {
private readonly authoritative = new Map<string, string>()
private readonly waiting = new Map<string, WaitingAnimation>()
private readonly readers = new Map<string, LocalGeometryReader>()
+ private readonly following = new Map<string, FollowingWindow>()
private revision = 0
private changed: (windows: ReadonlyMap<string, LocalWindowState>) => void = () => undefined
@@ -39,6 +40,8 @@ export default class LocalWindows implements LocalWindowHost {
this.cancel(identity, "geometry", "The local Window representation was removed")
+ this.cancel(identity, "minimize", "The local Window representation was removed")
+
this.cancel(identity, "surface", "The local Window representation was removed")
}
@@ -62,6 +65,15 @@ export default class LocalWindows implements LocalWindowHost {
this.authoritative.set(identity, signature)
}
+ const liveIdentities = new Set(this.live.values())
+
+ for (const [identity, relation] of this.following) {
+
+ if (!liveIdentities.has(identity) || !liveIdentities.has(relation.target)) this.following.delete(identity)
+ }
+
+ projectFollowing(next, this.following, (identity, kind) => this.cancel(identity, kind, "The followed Window changed"))
+
this.publish(next)
}
@@ -72,6 +84,10 @@ export default class LocalWindows implements LocalWindowHost {
next.delete(identity)
this.readers.delete(identity)
this.authoritative.delete(identity)
+ this.following.delete(identity)
+
+ for (const [follower, relation] of this.following) if (relation.target === identity) this.following.delete(follower)
+
this.publish(next)
}
@@ -101,31 +117,89 @@ export default class LocalWindows implements LocalWindowHost {
public move(process: string, position: WindowState["position"], transaction?: Transaction) {
- const state = this.existing(process).state
- return this.geometry(process, { position, size: state.size }, transaction)
+ const { identity, state } = this.existing(process)
+ this.following.delete(identity)
+ return this.changeGeometry(identity, { position, size: state.size }, transaction)
}
public resize(process: string, size: WindowState["size"], transaction?: Transaction) {
- const state = this.existing(process).state
- return this.geometry(process, { position: state.position, size }, transaction)
+ const { identity, state } = this.existing(process)
+ this.following.delete(identity)
+ return this.changeGeometry(identity, { position: state.position, size }, transaction)
}
public geometry(process: string, value: WindowGeometry, transaction?: Transaction) {
- const { identity, state } = this.existing(process)
- if (JSON.stringify([state.position, state.size]) === JSON.stringify([value.position, value.size])) return Promise.resolve()
+ const { identity } = this.existing(process)
+ this.following.delete(identity)
+ return this.changeGeometry(identity, value, transaction)
+ }
- this.cancel(identity, "geometry")
- const animation = transaction ? { revision: ++this.revision, transaction } : null
- this.replace(identity, { ...state, position: value.position, size: value.size, geometryAnimation: animation })
- return this.waitFor(identity, "geometry", animation)
+ public minimize(process: string, minimized: boolean, transaction?: Transaction) {
+
+ const { identity } = this.existing(process)
+ this.following.delete(identity)
+ return this.changeMinimized(identity, minimized, transaction)
}
- public minimize(process: string, minimized: boolean) {
+ public follow(process: string, targetProcess: string, transaction?: Transaction) {
- const { identity, state } = this.existing(process)
- this.replace(identity, { ...state, minimized })
+ const follower = this.existing(process)
+ const target = this.existing(targetProcess)
+
+ if (follower.identity === target.identity) throw new Error("A local Window cannot follow itself")
+
+ for (let identity: string | undefined = target.identity; identity; identity = this.following.get(identity)?.target) {
+
+ if (identity === follower.identity) throw new Error("Local Windows cannot form a following cycle")
+ }
+
+ const current = this.following.get(follower.identity)
+
+ if (current?.target === target.identity) return Promise.resolve()
+
+ this.following.set(follower.identity, {
+
+ target: target.identity,
+
+ restore: current?.restore ?? {
+
+ position: follower.state.position,
+
+ size: follower.state.size,
+
+ minimized: follower.state.minimized
+ }
+ })
+
+ const targetState = this.presented(target.identity, target.state)
+
+ return Promise.all([
+
+ this.changeGeometry(follower.identity, { position: targetState.position, size: targetState.size }, transaction),
+
+ this.changeMinimized(follower.identity, targetState.minimized, transaction)
+
+ ]).then(() => undefined)
+ }
+
+ public unfollow(process: string, transaction?: Transaction) {
+
+ const { identity } = this.existing(process)
+ const relation = this.following.get(identity)
+
+ if (!relation) return Promise.resolve()
+
+ this.following.delete(identity)
+
+ return Promise.all([
+
+ this.changeGeometry(identity, { position: relation.restore.position, size: relation.restore.size }, transaction),
+
+ this.changeMinimized(identity, relation.restore.minimized, transaction)
+
+ ]).then(() => undefined)
}
public title(process: string, title: string) {
@@ -169,12 +243,18 @@ export default class LocalWindows implements LocalWindowHost {
const identity = this.live.get(process)
if (!identity) return
const state = this.windows.get(identity)
- const animation = kind === "geometry" ? state?.geometryAnimation : state?.surface?.transition
+ const animation = kind === "geometry"
+ ? state?.geometryAnimation
+ : kind === "minimize"
+ ? state?.minimizeAnimation
+ : state?.surface?.transition
if (!state || animation?.revision !== revision) return
this.replace(identity, kind === "geometry"
? { ...state, geometryAnimation: null }
- : { ...state, surface: state.surface?.visible ? { ...state.surface, transition: null } : null })
+ : kind === "minimize"
+ ? { ...state, minimizeAnimation: null }
+ : { ...state, surface: state.surface?.visible ? { ...state.surface, transition: null } : null })
const key = animationKey(identity, kind)
const waiting = this.waiting.get(key)
@@ -189,12 +269,15 @@ export default class LocalWindows implements LocalWindowHost {
const identity = this.live.get(process)
if (!identity) return
this.cancel(identity, "geometry", "The local Window representation was removed")
+ this.cancel(identity, "minimize", "The local Window representation was removed")
this.cancel(identity, "surface", "The local Window representation was removed")
const client = this.client(process)
if (!client) return
this.authoritative.set(identity, authoritativeSignature(client))
+ this.following.delete(identity)
this.replace(identity, localState(client))
+ this.projectFollowers(identity)
}
private existing(process: string) {
@@ -213,6 +296,59 @@ export default class LocalWindows implements LocalWindowHost {
this.publish(next)
}
+ private changeGeometry(identity: string, value: WindowGeometry, transaction?: Transaction, project = true) {
+
+ const state = this.windows.get(identity)
+ if (!state) throw new Error("This Client has no local Window representation")
+ if (JSON.stringify([state.position, state.size]) === JSON.stringify([value.position, value.size])) return Promise.resolve()
+
+ this.cancel(identity, "geometry")
+ const animation = transaction ? { revision: ++this.revision, transaction } : null
+ this.replace(identity, { ...state, position: value.position, size: value.size, geometryAnimation: animation })
+ if (project) this.projectFollowers(identity, transaction)
+ return this.waitFor(identity, "geometry", animation)
+ }
+
+ private changeMinimized(identity: string, minimized: boolean, transaction?: Transaction, project = true) {
+
+ const state = this.windows.get(identity)
+ if (!state) throw new Error("This Client has no local Window representation")
+ if (state.minimized === minimized) return Promise.resolve()
+
+ this.cancel(identity, "minimize")
+ const animation = transaction ? { revision: ++this.revision, transaction } : null
+ this.replace(identity, { ...state, minimized, minimizeAnimation: animation })
+ if (project) this.projectFollowers(identity, transaction)
+ return this.waitFor(identity, "minimize", animation)
+ }
+
+ private projectFollowers(target: string, transaction?: Transaction, visited = new Set<string>()) {
+
+ if (visited.has(target)) return
+ visited.add(target)
+
+ const targetState = this.windows.get(target)
+ if (!targetState) return
+
+ const selected = transaction ? { ...transaction, wait: false } : undefined
+
+ for (const [identity, relation] of this.following) {
+
+ if (relation.target !== target) continue
+
+ void this.changeGeometry(identity, { position: targetState.position, size: targetState.size }, selected, false)
+ void this.changeMinimized(identity, targetState.minimized, selected, false)
+ this.projectFollowers(identity, selected, visited)
+ }
+ }
+
+ private presented(identity: string, state: LocalWindowState) {
+
+ const geometry = this.readers.get(identity)?.()
+
+ return geometry ? { ...state, position: geometry.position, size: geometry.size } : state
+ }
+
private publish(next: ReadonlyMap<string, LocalWindowState>) {
this.windows = next
@@ -238,7 +374,7 @@ export default class LocalWindows implements LocalWindowHost {
}
}
-type AnimationKind = "geometry" | "surface"
+type AnimationKind = "geometry" | "minimize" | "surface"
interface WaitingAnimation {
revision: number
@@ -246,6 +382,15 @@ interface WaitingAnimation {
reject: (error: Error) => void
}
+interface FollowingWindow {
+ target: string
+ restore: Readonly<{
+ position: WindowState["position"]
+ size: WindowState["size"]
+ minimized: boolean
+ }>
+}
+
function animationKey(identity: string, kind: AnimationKind) {
return `${identity}:${kind}`
@@ -264,7 +409,8 @@ function localState(client: ClientState): LocalWindowState {
location: window.location,
depth: window.depth,
surface: null,
- geometryAnimation: null
+ geometryAnimation: null,
+ minimizeAnimation: null
}
}
@@ -280,7 +426,8 @@ function projectAuthoritative(local: LocalWindowState, client: ClientState, repl
layer: window.layer,
location: window.location,
depth: window.depth,
- geometryAnimation: replaceGeometry ? null : local.geometryAnimation
+ geometryAnimation: replaceGeometry ? null : local.geometryAnimation,
+ minimizeAnimation: local.minimizeAnimation
}
}
@@ -319,3 +466,48 @@ function frontmost(windows: ReadonlyMap<string, LocalWindowState>, layer: LocalW
}
return best?.[0] ?? null
}
+
+function projectFollowing(
+ windows: Map<string, LocalWindowState>,
+ following: ReadonlyMap<string, FollowingWindow>,
+ changed: (identity: string, kind: "geometry" | "minimize") => void
+) {
+
+ const projected = new Set<string>()
+
+ function project(identity: string, stack = new Set<string>()): LocalWindowState | undefined {
+
+ const state = windows.get(identity)
+ const relation = following.get(identity)
+
+ if (!state || !relation) return state
+ if (stack.has(identity)) return state
+
+ stack.add(identity)
+ const target = project(relation.target, stack)
+ stack.delete(identity)
+
+ if (!target) return state
+
+ const geometryChanged = JSON.stringify([state.position, state.size]) !== JSON.stringify([target.position, target.size])
+ const minimizedChanged = state.minimized !== target.minimized
+
+ if (geometryChanged) changed(identity, "geometry")
+ if (minimizedChanged) changed(identity, "minimize")
+
+ const next = {
+ ...state,
+ position: target.position,
+ size: target.size,
+ minimized: target.minimized,
+ geometryAnimation: geometryChanged ? target.geometryAnimation : state.geometryAnimation,
+ minimizeAnimation: minimizedChanged ? target.minimizeAnimation : state.minimizeAnimation
+ }
+
+ windows.set(identity, next)
+ projected.add(identity)
+ return next
+ }
+
+ for (const identity of following.keys()) if (!projected.has(identity)) project(identity)
+}
diff --git a/source/client/view/components/window-manager/window-manager.ts b/source/client/view/components/window-manager/window-manager.ts
index 545fe76..35fd28e 100644
--- a/source/client/view/components/window-manager/window-manager.ts
+++ b/source/client/view/components/window-manager/window-manager.ts
@@ -236,7 +236,7 @@ export default function useWindows(authManager: AuthManager) {
if (!window || window.layer !== "window") return
- localWindow.minimize(process.identity, minimized)
+ void localWindow.minimize(process.identity, minimized)
commit(window.minimize(minimized))
diff --git a/source/client/view/structure/desktop/desktop.tsx b/source/client/view/structure/desktop/desktop.tsx
index d9f962d..95cfef2 100644
--- a/source/client/view/structure/desktop/desktop.tsx
+++ b/source/client/view/structure/desktop/desktop.tsx
@@ -131,6 +131,8 @@ export default function Workspace() {
geometryAnimation={local.geometryAnimation}
+ minimizeAnimation={local.minimizeAnimation}
+
onLocalAnimationComplete={(kind, revision) => windows.localWindow.complete(record.identity, kind, revision)}
onLocalRepresentation={windows.localWindow.represent}
diff --git a/source/client/view/structure/desktop/windows/process-window.tsx b/source/client/view/structure/desktop/windows/process-window.tsx
index 38beedb..f5d5923 100644
--- a/source/client/view/structure/desktop/windows/process-window.tsx
+++ b/source/client/view/structure/desktop/windows/process-window.tsx
@@ -17,7 +17,7 @@ const settleDelay = 80
* props so memoization can see which process actually changed even though
* the peer deliberately keeps each Process instance alive and mutates it.
*/
-export default memo(function ({ identity, record, assetId, client, title, icon, position, size, localSurface, geometryAnimation, onLocalAnimationComplete, onLocalRepresentation, paintSurfaceSize, depth, active, minimized, closing, stopping, entering, bare, door, programAccess, theme, onFrame, onFrameLoad, onReady, onRaise, onMinimize, onFill, onClose, onClosed, onUnavailable, onMove, onResize, onSnap }: ProcessWindowProps) {
+export default memo(function ({ identity, record, assetId, client, title, icon, position, size, localSurface, geometryAnimation, minimizeAnimation, onLocalAnimationComplete, onLocalRepresentation, paintSurfaceSize, depth, active, minimized, closing, stopping, entering, bare, door, programAccess, theme, onFrame, onFrameLoad, onReady, onRaise, onMinimize, onFill, onClose, onClosed, onUnavailable, onMove, onResize, onSnap }: ProcessWindowProps) {
const activate = useCallback(() => onRaise(record), [onRaise, record])
@@ -102,6 +102,8 @@ export default memo(function ({ identity, record, assetId, client, title, icon,
geometryAnimation={geometryAnimation}
+ minimizeAnimation={minimizeAnimation}
+
onLocalAnimationComplete={onLocalAnimationComplete}
onLocalRepresentation={represent}
@@ -212,7 +214,9 @@ interface ProcessWindowProps {
geometryAnimation: LocalAnimation | null
- onLocalAnimationComplete: (kind: "geometry" | "surface", revision: number) => void
+ minimizeAnimation: LocalAnimation | null
+
+ onLocalAnimationComplete: (kind: "geometry" | "minimize" | "surface", revision: number) => void
onLocalRepresentation: (identity: string, reader: LocalGeometryReader | null) => void
diff --git a/source/client/view/structure/desktop/windows/window.tsx b/source/client/view/structure/desktop/windows/window.tsx
index 90b2fa4..d20adc6 100644
--- a/source/client/view/structure/desktop/windows/window.tsx
+++ b/source/client/view/structure/desktop/windows/window.tsx
@@ -1,6 +1,6 @@
import { ComponentProps, PointerEvent as ReactPointerEvent, ReactNode, useLayoutEffect, useRef, useState } from "react"
import { useReducedMotion } from "@libs/react-motion"
-import { enterSurface, prepareSurfaceEntrance, restSurface } from "@client/view/appearance/surface-presence"
+import { enterSurface, leaveSurface, prepareSurfaceEntrance, restSurface } from "@client/view/appearance/surface-presence"
import WindowPanel from "./window-panel"
import { absoluteWindowGeometry, resolveWindowGeometry, resolveWindowValue, wholeWindowGeometry, windowPaintInsets, type WindowRegion, type WindowSurfaceSize } from "@client/view/components/window-manager/window-geometry"
import { type Position, type Size, type WindowGeometry } from "@phreshos/core"
@@ -52,7 +52,7 @@ const surfacePose = {
closing: { scale: 0.86, y: 12 }
}
-export default function ({ title, icon, children, onClose, onClosed, onMinimize, onMaximize, onActivate, onUnavailable, onMove, onResize, onSnap, onLocalAnimationComplete, onLocalRepresentation, onFocusCapture, active = false, bare = false, closing = false, stopping = false, minimized = false, animateEntrance = true, position = { x: 0, y: 0 }, size = { width: 520, height: 340 }, localSurface, geometryAnimation, paintSurfaceSize = { width: 0, height: 0 }, minWidth = 260, minHeight = 160, className, style, ...props }: WindowProps) {
+export default function ({ title, icon, children, onClose, onClosed, onMinimize, onMaximize, onActivate, onUnavailable, onMove, onResize, onSnap, onLocalAnimationComplete, onLocalRepresentation, onFocusCapture, active = false, bare = false, closing = false, stopping = false, minimized = false, animateEntrance = true, position = { x: 0, y: 0 }, size = { width: 520, height: 340 }, localSurface, geometryAnimation, minimizeAnimation, paintSurfaceSize = { width: 0, height: 0 }, minWidth = 260, minHeight = 160, className, style, ...props }: WindowProps) {
const frame = useRef<HTMLDivElement>(null)
@@ -325,11 +325,42 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,
if (minimized) onUnavailable?.("minimize")
- // Bare, hiding is hiding: the visibility changes and nothing
- // travels. There is no taskbar for it to drift toward — a
- // program in `under` or `over` is not listed — so the drift
- // would be motion toward nowhere.
- if (bare || reducedMotion) {
+ if (bare) {
+
+ const revision = minimizeAnimation?.revision
+ const transaction = minimizeAnimation?.transaction
+
+ if (!transaction) {
+
+ restSurface(surfaceElement.current)
+ gsap.set(surfaceElement.current, { visibility: minimized ? "hidden" : "visible" })
+
+ if (revision !== undefined) onLocalAnimationComplete?.("minimize", revision)
+
+ return
+ }
+
+ if (!minimized) {
+
+ prepareSurfaceEntrance(surfaceElement.current, reducedMotion)
+ gsap.set(surfaceElement.current, { visibility: "visible" })
+ }
+
+ const complete = function () {
+
+ if (minimized) gsap.set(surfaceElement.current, { visibility: "hidden" })
+
+ onLocalAnimationComplete?.("minimize", revision!)
+ }
+
+ const animation = minimized
+ ? leaveSurface(surfaceElement.current, reducedMotion, { ...transaction, onComplete: complete })
+ : enterSurface(surfaceElement.current, reducedMotion, { ...transaction, onComplete: complete })
+
+ return () => { animation?.kill() }
+ }
+
+ if (reducedMotion) {
gsap.set(surfaceElement.current, { ...surfacePose.resting, visibility: minimized ? "hidden" : "visible" })
@@ -349,7 +380,7 @@ export default function ({ title, icon, children, onClose, onClosed, onMinimize,
return () => { animation.kill() }
- }, [minimized])
+ }, [minimized, minimizeAnimation?.revision])
// Closing is a handshake: the exit plays, onClosed reports the
// element may be unmounted.
@@ -818,7 +849,9 @@ interface WindowProps extends Omit<ComponentProps<"div">, "title"> {
geometryAnimation?: LocalAnimation | null
- onLocalAnimationComplete?: (kind: "geometry" | "surface", revision: number) => void
+ minimizeAnimation?: LocalAnimation | null
+
+ onLocalAnimationComplete?: (kind: "geometry" | "minimize" | "surface", revision: number) => void
onLocalRepresentation?: (reader: LocalGeometryReader | null) => void
diff --git a/source/libs/file-area.ts b/source/libs/file-area.ts
index c7a367f..f7974ca 100644
--- a/source/libs/file-area.ts
+++ b/source/libs/file-area.ts
@@ -1,7 +1,7 @@
-import { createReadStream, createWriteStream, lstatSync, mkdirSync, readdirSync, renameSync, rmSync, statSync } from "node:fs"
+import { createReadStream, createWriteStream, linkSync, lstatSync, mkdirSync, readdirSync, renameSync, rmSync, statfsSync, statSync } from "node:fs"
import { randomUUID } from "node:crypto"
-import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"
-import { rm } from "node:fs/promises"
+import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"
+import { rm, watch as watchPath } from "node:fs/promises"
import { Readable } from "node:stream"
import { pipeline } from "node:stream/promises"
import { type ReadableStream as NodeReadableStream } from "node:stream/web"
@@ -52,6 +52,18 @@ export default class FileArea {
return path
}
+ public name(joins: string[] = []) {
+
+ const path = this.resolve(joins)
+
+ return basename(path) || path
+ }
+
+ public create(joins: string[] = []) {
+
+ mkdirSync(this.resolve(joins), { recursive: true })
+ }
+
public clear(joins: string[] = []) {
const path = this.resolve(joins)
@@ -90,9 +102,44 @@ export default class FileArea {
return { kind: "other", modifiedAt }
}
- public list(joins: string[]) {
+ public list(joins: string[], options: StorageListOptions = []) {
+
+ const [recursive = false, configuredDepth] = options
+
+ if (configuredDepth !== undefined && (!Number.isSafeInteger(configuredDepth) || configuredDepth < 0)) {
+
+ throw new Error("A Storage list depth must be a non-negative safe integer")
+ }
+
+ if (configuredDepth !== undefined && !recursive) throw new Error("A Storage list depth requires recursive listing")
+
+ const depth = recursive ? configuredDepth ?? Number.POSITIVE_INFINITY : 1
+
+ const entries: StorageEntry[] = []
+
+ this.collect(joins, [], depth, entries)
+
+ return entries
+ }
+
+ private collect(joins: string[], relative: string[], depth: number, entries: StorageEntry[]) {
+
+ if (depth === 0) return
+
+ for (const name of readdirSync(this.resolve([...joins, ...relative])).sort()) {
+
+ const path = [...relative, name]
+
+ const found = this.stat([...joins, ...path])
+
+ if (!found) continue
+
+ if (found.kind === "other") throw new Error(`${this.resolve([...joins, ...path])} is neither a file nor a Storage directory`)
+
+ entries.push({ kind: found.kind === "directory" ? "storage" : "file", path })
- return readdirSync(this.resolve(joins)).sort()
+ if (found.kind === "directory" && depth > 1) this.collect(joins, path, depth - 1, entries)
+ }
}
public delete(joins: string[]) {
@@ -102,7 +149,7 @@ export default class FileArea {
rmSync(this.resolve(joins), { recursive: true, force: true })
}
- public stream(joins: string[]) {
+ public stream(joins: string[], options: StorageReadOptions = []) {
const found = this.stat(joins)
@@ -110,10 +157,25 @@ export default class FileArea {
if (found.kind !== "file") throw new NotFileError(`${joins.join("/")} is not a file`)
- return Readable.toWeb(createReadStream(this.resolve(joins))) as ReadableStream<Uint8Array>
+ const [offset = 0, length] = options
+
+ if (!Number.isSafeInteger(offset) || offset < 0) throw new Error("A Storage read offset must be a non-negative safe integer")
+
+ if (length !== undefined && (!Number.isSafeInteger(length) || length < 0)) throw new Error("A Storage read length must be a non-negative safe integer")
+
+ if (length !== undefined && !Number.isSafeInteger(offset + length)) throw new Error("A Storage byte range must use safe integers")
+
+ if (length === 0) return new ReadableStream<Uint8Array>({ start(controller) { controller.close() } })
+
+ return Readable.toWeb(createReadStream(this.resolve(joins), {
+
+ start: offset,
+
+ ...(length === undefined ? {} : { end: offset + length - 1 })
+ })) as ReadableStream<Uint8Array>
}
- public async write(joins: string[], content: ReadableStream<Uint8Array> | null, signal?: AbortSignal) {
+ public async write(joins: string[], content: ReadableStream<Uint8Array> | null, signal?: AbortSignal, overwrite = true) {
if (joins.length === 0) throw new Error("Writing takes a file name and what to write")
@@ -136,7 +198,14 @@ export default class FileArea {
{ signal }
)
- renameSync(temporary, path)
+ if (overwrite) renameSync(temporary, path)
+
+ else {
+
+ linkSync(temporary, path)
+
+ rmSync(temporary, { force: true })
+ }
}
catch (exception) {
@@ -146,6 +215,45 @@ export default class FileArea {
throw exception
}
}
+
+ public async append(joins: string[], content: ReadableStream<Uint8Array> | null, signal?: AbortSignal) {
+
+ if (joins.length === 0) throw new Error("Appending takes a file name and what to append")
+
+ if (!content) throw new Error("Appending takes a byte stream")
+
+ const path = this.resolve(joins)
+
+ mkdirSync(dirname(path), { recursive: true })
+
+ await pipeline(
+
+ Readable.fromWeb(content as unknown as NodeReadableStream<Uint8Array>),
+
+ createWriteStream(path, { flags: "a" }),
+
+ { signal }
+ )
+ }
+
+ public space(joins: string[] = []) {
+
+ const value = statfsSync(this.resolve(joins))
+
+ const capacity = value.blocks * value.bsize
+
+ const available = value.bavail * value.bsize
+
+ return { capacity, available, used: capacity - value.bfree * value.bsize }
+ }
+
+ public async *watch(joins: string[] = [], recursive = false, signal?: AbortSignal) {
+
+ for await (const change of watchPath(this.resolve(joins), { recursive, signal })) {
+
+ yield { event: change.eventType, path: change.filename === null ? null : String(change.filename) } as const
+ }
+ }
}
/** Native filesystem access resolved from one entry point without confinement. */
@@ -182,6 +290,17 @@ export interface OtherStat {
modifiedAt: number
}
+export interface StorageEntry {
+
+ kind: "storage" | "file"
+
+ path: string[]
+}
+
+export type StorageListOptions = [recursive?: boolean, depth?: number]
+
+export type StorageReadOptions = [offset?: number, length?: number]
+
export class MissingAreaEntryError extends Error { }
export class NotFileError extends Error { }
diff --git a/source/server/core/link-manager/auth-manager/auth-manager.ts b/source/server/core/link-manager/auth-manager/auth-manager.ts
index 31c08d3..8da78e5 100644
--- a/source/server/core/link-manager/auth-manager/auth-manager.ts
+++ b/source/server/core/link-manager/auth-manager/auth-manager.ts
@@ -11,6 +11,8 @@ import ShellManager from "./shell-manager"
export default class AuthManager extends TheLink {
+ private readonly storageWatches = new Map<string, AbortController>()
+
public readonly linkManager: LinkManager
public readonly programManager: ProgramManager
@@ -83,7 +85,7 @@ export default class AuthManager extends TheLink {
const file = await this.uploads.write(extension, content, signal)
- return this.uploads.stat(file)!
+ return { file, ...this.uploads.stat(file)! }
}
/** Perform a server-side request after the desktop door proves authorization. */
@@ -94,30 +96,108 @@ export default class AuthManager extends TheLink {
return fetch(input, init)
}
- public streamArea(authorization: unknown, program: unknown, area: "data" | "cache", path: string[]) {
+ public streamArea(authorization: unknown, program: unknown, area: "data" | "cache", path: string[], options: [offset?: number, length?: number] = []) {
this.verify(authorization)
- return this.programManager.streamArea(program, area, path)
+ return this.programManager.streamArea(program, area, path, options)
}
@Connect("/storage")
- protected async storage(operation: unknown, values: unknown) {
+ protected async storage(operation: unknown, values: unknown, input?: unknown) {
if (typeof operation !== "string" || !Array.isArray(values) || values.some(value => typeof value !== "string")) throw new Error("A System storage operation is invalid")
const area = this.linkManager.application.home
- if (operation === "path") return area.path
- if (operation === "resolve") return area.resolve(values)
- if (operation === "stat") return area.stat(values)
- if (operation === "list") return area.list(values)
- if (operation === "delete") return area.delete(values)
+ if (operation === "path") return area.resolve(values)
+ if (operation === "name") return area.name(values)
+ if (operation === "create") return area.create(values)
+
+ if (operation === "stat-storage" || operation === "stat-file") {
+
+ const found = area.stat(values)
+
+ if (!found) return null
+
+ if (operation === "stat-storage") {
+
+ if (found.kind !== "directory") throw new Error(`${area.resolve(values)} is not a Storage directory`)
+
+ return { modifiedAt: found.modifiedAt }
+ }
+
+ if (found.kind !== "file") throw new Error(`${area.resolve(values)} is not a file`)
+
+ return { size: found.size, modifiedAt: found.modifiedAt }
+ }
+
+ if (operation === "list") {
+
+ const options = storageListOptions(input)
+
+ return area.list(values, [options.recursive, options.depth])
+ }
+
+ if (operation === "delete-storage" || operation === "delete-file") {
+
+ const found = area.stat(values)
+
+ if (found && operation === "delete-storage" && found.kind !== "directory") throw new Error(`${area.resolve(values)} is not a Storage directory`)
+
+ if (found && operation === "delete-file" && found.kind !== "file") throw new Error(`${area.resolve(values)} is not a file`)
+
+ return area.delete(values)
+ }
+
if (operation === "clear") return area.clear(values)
+ if (operation === "space") return area.space(values)
throw new Error(`System storage does not know "${operation}"`)
}
+ @Connect("/storage-watch")
+ protected async watchStorage(stream: unknown, target: unknown) {
+
+ if (typeof stream !== "string" || !stream) throw new Error("A Storage watch needs an identity")
+
+ const request = storageWatchTarget(target)
+
+ const connection = this.connection()
+
+ const key = `${connection}:${stream}`
+
+ if (this.storageWatches.has(key)) throw new Error("A Storage watch identity must be unique")
+
+ const controller = new AbortController()
+
+ const signal = AbortSignal.any([controller.signal, this.connectionSignal()])
+
+ this.storageWatches.set(key, controller)
+
+ try {
+
+ const operation = request.scope === "system"
+ ? this.linkManager.application.home.watch(request.path, request.recursive, signal)
+ : this.programManager.watchArea(request.program, request.area, request.path, request.recursive, signal)
+
+ for await (const change of operation) await this.publishToConnection(connection, "/storage-change", stream, change)
+ }
+
+ finally {
+
+ this.storageWatches.delete(key)
+ }
+ }
+
+ @Subscribe("/storage-watch-cancel")
+ protected cancelStorageWatch(stream: unknown) {
+
+ if (typeof stream !== "string") return
+
+ this.storageWatches.get(`${this.connection()}:${stream}`)?.abort()
+ }
+
@Connect("/uploads/path")
protected async uploadsPath() {
@@ -199,11 +279,18 @@ export default class AuthManager extends TheLink {
if (typeof request === "string" && typeof process === "string") await this.processManager.cancelPermission(process, request)
}
- public async writeArea(authorization: unknown, program: unknown, area: "data" | "cache", path: string[], content: ReadableStream<Uint8Array> | null, signal?: AbortSignal) {
+ public async writeArea(authorization: unknown, program: unknown, area: "data" | "cache", path: string[], content: ReadableStream<Uint8Array> | null, signal?: AbortSignal, overwrite = true) {
this.verify(authorization)
- await this.programManager.writeArea(program, area, path, content, signal)
+ await this.programManager.writeArea(program, area, path, content, signal, overwrite)
+ }
+
+ public async appendArea(authorization: unknown, program: unknown, area: "data" | "cache", path: string[], content: ReadableStream<Uint8Array> | null, signal?: AbortSignal) {
+
+ this.verify(authorization)
+
+ await this.programManager.appendArea(program, area, path, content, signal)
}
// A targeted client observation belongs to one authorized desktop
@@ -244,6 +331,41 @@ export default class AuthManager extends TheLink {
}
}
+function storageListOptions(value: unknown) {
+
+ if (value === undefined) return { recursive: false, depth: undefined }
+
+ if (!value || typeof value !== "object") throw new Error("Storage list options must be an object")
+
+ const options = value as { recursive?: unknown, depth?: unknown }
+
+ if (options.recursive !== undefined && typeof options.recursive !== "boolean") throw new Error("Storage recursive must be boolean")
+
+ if (options.depth !== undefined && (!Number.isSafeInteger(options.depth) || (options.depth as number) < 0)) throw new Error("Storage depth must be a non-negative safe integer")
+
+ if (options.depth !== undefined && options.recursive !== true) throw new Error("A Storage list depth requires recursive listing")
+
+ return { recursive: options.recursive === true, depth: options.depth as number | undefined }
+}
+
+function storageWatchTarget(value: unknown) {
+
+ if (!value || typeof value !== "object") throw new Error("A Storage watch target is required")
+
+ const target = value as { scope?: unknown, path?: unknown, recursive?: unknown, program?: unknown, area?: unknown }
+
+ if ((target.scope !== "system" && target.scope !== "program") || !Array.isArray(target.path) || target.path.some(part => typeof part !== "string") || typeof target.recursive !== "boolean") {
+
+ throw new Error("A Storage watch target is invalid")
+ }
+
+ if (target.scope === "system") return { scope: "system" as const, path: target.path as string[], recursive: target.recursive }
+
+ if ((target.area !== "data" && target.area !== "cache") || !target.program || typeof target.program !== "object") throw new Error("A Program Storage watch target is invalid")
+
+ return { scope: "program" as const, program: target.program, area: target.area as "data" | "cache", path: target.path as string[], recursive: target.recursive }
+}
+
export interface AuthManagerSnapshot {
username: string | null
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.ts
index afca76c..4249aa8 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
@@ -705,9 +705,20 @@ export default class ProgramManager extends TheLink {
const place = this.areaOf(program, area)
- const joins = args.map(String)
+ const joins = storagePath(args[0])
- if (operation === "path") return place.path
+ const input = args[1]
+
+ if (operation === "path") return place.resolve(joins)
+
+ if (operation === "name") return place.name(joins)
+
+ if (operation === "create") {
+
+ place.create(joins)
+
+ return undefined
+ }
if (operation === "clear") {
@@ -716,32 +727,71 @@ export default class ProgramManager extends TheLink {
return undefined
}
- if (operation === "stat") return place.stat(joins)
+ if (operation === "stat-storage" || operation === "stat-file") {
+
+ const found = place.stat(joins)
+
+ if (!found) return null
+
+ if (operation === "stat-storage") {
+
+ if (found.kind !== "directory") throw new Error(`${place.resolve(joins)} is not a Storage directory`)
+
+ return { modifiedAt: found.modifiedAt }
+ }
+
+ if (found.kind !== "file") throw new Error(`${place.resolve(joins)} is not a file`)
+
+ return { size: found.size, modifiedAt: found.modifiedAt }
+ }
// Sorted, so two runs of the same program see the same order and
// a program showing a list does not have to sort it again.
- if (operation === "list") return place.list(joins)
+ if (operation === "list") {
+
+ const options = storageListOptions(input)
+
+ return place.list(joins, [options.recursive, options.depth])
+ }
// Removing a place is `clear`, and one act with two names is how
// a program empties everything meaning to remove one thing.
- if (operation === "delete") {
+ if (operation === "delete-storage" || operation === "delete-file") {
+
+ const found = place.stat(joins)
+
+ if (found && operation === "delete-storage" && found.kind !== "directory") throw new Error(`${place.resolve(joins)} is not a Storage directory`)
+
+ if (found && operation === "delete-file" && found.kind !== "file") throw new Error(`${place.resolve(joins)} is not a file`)
place.delete(joins)
return undefined
}
+ if (operation === "space") return place.space(joins)
+
throw new Error(`The host does not know the storage operation "${operation}"`)
}
- public streamArea(subject: unknown, area: Area, joins: string[]) {
+ public streamArea(subject: unknown, area: Area, joins: string[], options: [offset?: number, length?: number] = []) {
+
+ return this.areaOf(this.held(subject), area).stream(joins, options)
+ }
+
+ public async writeArea(subject: unknown, area: Area, joins: string[], content: ReadableStream<Uint8Array> | null, signal?: AbortSignal, overwrite = true) {
- return this.areaOf(this.held(subject), area).stream(joins)
+ await this.areaOf(this.held(subject), area).write(joins, content, signal, overwrite)
}
- public async writeArea(subject: unknown, area: Area, joins: string[], content: ReadableStream<Uint8Array> | null, signal?: AbortSignal) {
+ public async appendArea(subject: unknown, area: Area, joins: string[], content: ReadableStream<Uint8Array> | null, signal?: AbortSignal) {
- await this.areaOf(this.held(subject), area).write(joins, content, signal)
+ await this.areaOf(this.held(subject), area).append(joins, content, signal)
+ }
+
+ public watchArea(subject: unknown, area: Area, joins: string[], recursive: boolean, signal?: AbortSignal) {
+
+ return this.areaOf(this.held(subject), area).watch(joins, recursive, signal)
}
// ── Installing and uninstalling ──────────────────────────────────
@@ -1459,6 +1509,32 @@ export type Options = Record<string, string>
// process of it.
export type Area = "data" | "cache"
+function storagePath(value: unknown) {
+
+ if (value === undefined) return []
+
+ if (!Array.isArray(value) || value.some(part => typeof part !== "string")) throw new Error("A Storage path is a list of names")
+
+ return value as string[]
+}
+
+function storageListOptions(value: unknown) {
+
+ if (value === undefined) return { recursive: false, depth: undefined }
+
+ if (!value || typeof value !== "object") throw new Error("Storage list options must be an object")
+
+ const options = value as { recursive?: unknown, depth?: unknown }
+
+ if (options.recursive !== undefined && typeof options.recursive !== "boolean") throw new Error("Storage recursive must be boolean")
+
+ if (options.depth !== undefined && (!Number.isSafeInteger(options.depth) || (options.depth as number) < 0)) throw new Error("Storage depth must be a non-negative safe integer")
+
+ if (options.depth !== undefined && options.recursive !== true) throw new Error("A Storage list depth requires recursive listing")
+
+ return { recursive: options.recursive === true, depth: options.depth as number | undefined }
+}
+
// Someone listening to a process from outside it. Given at launch
// because that is when the child's pipes are decided, and they cannot be
// decided twice.
diff --git a/source/server/core/protocol/storage.ts b/source/server/core/protocol/storage.ts
index be23fe4..aa0aebf 100644
--- a/source/server/core/protocol/storage.ts
+++ b/source/server/core/protocol/storage.ts
@@ -1,9 +1,12 @@
export const storageMediaType = "application/x-storage-stream"
type StorageOperation = Readonly<{
- operation: "stream" | "write"
path: string[]
-}>
+}> & (
+ | Readonly<{ operation: "stream", offset?: number, length?: number }>
+ | Readonly<{ operation: "write", overwrite?: boolean }>
+ | Readonly<{ operation: "append" }>
+)
export type ProgramAddress = Readonly<{
identity: string
diff --git a/source/server/core/upload-manager.ts b/source/server/core/upload-manager.ts
index 19fdcb3..edf03a4 100644
--- a/source/server/core/upload-manager.ts
+++ b/source/server/core/upload-manager.ts
@@ -5,7 +5,7 @@ import { randomUUID } from "node:crypto"
import { Readable } from "node:stream"
import { pipeline } from "node:stream/promises"
import { type ReadableStream as NodeReadableStream } from "node:stream/web"
-import { isUploadFile, type Upload } from "@phreshos/core"
+import { isUploadFile, type FileStat } from "@phreshos/core"
export const uploadLimit = 1024 * 1024 * 1024
@@ -101,7 +101,7 @@ export default class UploadManager {
return file
}
- public stat(file: string): Upload | null {
+ public stat(file: string): FileStat | null {
let stat
@@ -114,36 +114,7 @@ export default class UploadManager {
if (!stat.isFile()) throw new Error("That upload key does not identify a file")
- return { file, type: mediaType(file), size: stat.size, time: Math.round(stat.mtimeMs) }
+ return { size: stat.size, modifiedAt: Math.round(stat.mtimeMs) }
}
}
-
-function mediaType(file: string) {
-
- return types[file.slice(file.lastIndexOf(".") + 1)] ?? null
-}
-
-const types: Readonly<Record<string, string>> = {
- avif: "image/avif",
- bin: "application/octet-stream",
- bmp: "image/bmp",
- css: "text/css",
- csv: "text/csv",
- gif: "image/gif",
- gz: "application/gzip",
- html: "text/html",
- jpeg: "image/jpeg",
- jpg: "image/jpeg",
- js: "text/javascript",
- json: "application/json",
- mp3: "audio/mpeg",
- mp4: "video/mp4",
- pdf: "application/pdf",
- png: "image/png",
- svg: "image/svg+xml",
- txt: "text/plain",
- wasm: "application/wasm",
- webp: "image/webp",
- zip: "application/zip"
-}
diff --git a/source/server/view/http/storage.ts b/source/server/view/http/storage.ts
index aa83b81..f1e4bb5 100644
--- a/source/server/view/http/storage.ts
+++ b/source/server/view/http/storage.ts
@@ -49,8 +49,8 @@ export default function (application: Application) {
await request.body.cancel()
const body = metadata.scope === "system"
- ? application.home.stream(path)
- : authManager.streamArea(authorization, metadata.program, metadata.area, path)
+ ? application.home.stream(path, [metadata.offset, metadata.length])
+ : authManager.streamArea(authorization, metadata.program, metadata.area, path, [metadata.offset, metadata.length])
return new Response(body, {
@@ -63,8 +63,15 @@ export default function (application: Application) {
})
}
- if (metadata.scope === "system") await application.home.write(path, request.body, context.req.raw.signal)
- else await authManager.writeArea(authorization, metadata.program, metadata.area, path, request.body, context.req.raw.signal)
+ if (metadata.operation === "append") {
+
+ if (metadata.scope === "system") await application.home.append(path, request.body, context.req.raw.signal)
+ else await authManager.appendArea(authorization, metadata.program, metadata.area, path, request.body, context.req.raw.signal)
+ }
+
+ else if (metadata.scope === "system") await application.home.write(path, request.body, context.req.raw.signal, metadata.overwrite)
+
+ else await authManager.writeArea(authorization, metadata.program, metadata.area, path, request.body, context.req.raw.signal, metadata.overwrite)
return new Response(null, { status: 204 })
}
@@ -99,9 +106,20 @@ function validate(request: StorageRequest) {
if (request.scope === "program" && !isProgramAddress(request.program)) throw new Error("A Program storage request needs a Program handle")
if (request.scope === "program" && request.area !== "data" && request.area !== "cache") throw new Error("A storage area is data or cache")
- if (request.operation !== "stream" && request.operation !== "write") throw new Error("A storage operation is stream or write")
+ if (request.operation !== "stream" && request.operation !== "write" && request.operation !== "append") throw new Error("A storage operation is stream, write, or append")
if (!Array.isArray(request.path) || request.path.some(part => typeof part !== "string")) throw new Error("A storage path is a list of names")
+
+ if (request.operation === "stream") {
+
+ if (request.offset !== undefined && (!Number.isSafeInteger(request.offset) || request.offset < 0)) throw new Error("A Storage read offset must be a non-negative safe integer")
+
+ if (request.length !== undefined && (!Number.isSafeInteger(request.length) || request.length < 0)) throw new Error("A Storage read length must be a non-negative safe integer")
+
+ if (request.offset !== undefined && request.length !== undefined && !Number.isSafeInteger(request.offset + request.length)) throw new Error("A Storage byte range must use safe integers")
+ }
+
+ if (request.operation === "write" && request.overwrite !== undefined && typeof request.overwrite !== "boolean") throw new Error("Storage overwrite must be boolean")
}
function isProgramAddress(value: unknown): value is { identity: string, reference: string } {