An open-source, self-hosted system for apps built with web technologies.
A reloaded frame keeps what its new document sends before the frame finishes loading
zohayrslileh7589b5dab9ba
diff --git a/source/client/view/components/desktop-host/client-host.ts b/source/client/view/components/desktop-host/client-host.tsindex 8b47027..c4b797b 100644--- a/source/client/view/components/desktop-host/client-host.ts+++ b/source/client/view/components/desktop-host/client-host.ts@@ -181,68 +181,74 @@ export default function useClientHost(authManager: AuthManager, sources: Map<str}, [sources]))- const frame = useCallback(function (identity: string, element: HTMLIFrameElement | null) {+ // Each document in a frame gets its own lease: what the System forwards for an older one+ // never reaches it. Leases follow one another, in the order their documents began.+ const lease = useCallback(function (identity: string, element: HTMLIFrameElement) {- if (element) {+ const owner = crypto.randomUUID()- sources.set(identity, element)+ frameOwners.current.set(identity, owner)- boundaries.current.get(identity)?.release().catch(() => undefined)+ const previous = frameTasks.current.get(identity) ?? Promise.resolve()- boundaries.current.set(identity, new ClientProcessBoundary(identity, element, authManager, desktopViewport, windowActions, traffic, presentation))+ const task = previous.catch(() => undefined).then(async function () {- return- }+ const boundary = boundaries.current.get(identity)- sources.delete(identity)+ if (sources.get(identity) !== element || !boundary || boundary.element !== element) return- const boundary = boundaries.current.get(identity)+ try {- boundaries.current.delete(identity)+ await boundary.own(owner)- frameOwners.current.delete(identity)+ // The frame was replaced meanwhile: its boundary is gone, and so is this lease.+ if (sources.get(identity) !== element) await boundary.release()+ }- boundary?.release().catch(() => undefined)+ catch (error) { console.error(error) }+ })- }, [authManager, desktopViewport, windowActions, presentation, sources, traffic])+ frameTasks.current.set(identity, task)- const frameLoaded = useCallback(function (identity: string, element: HTMLIFrameElement) {+ task.finally(() => { if (frameTasks.current.get(identity) === task) frameTasks.current.delete(identity) }).catch(() => undefined)- const previous = frameTasks.current.get(identity) ?? Promise.resolve()+ }, [sources])- const task = previous.catch(() => undefined).then(async function () {+ const frame = useCallback(function (identity: string, element: HTMLIFrameElement | null) {- if (sources.get(identity) !== element) return+ if (element) {- const owner = crypto.randomUUID()+ sources.set(identity, element)- frameOwners.current.set(identity, owner)+ boundaries.current.get(identity)?.release().catch(() => undefined)- try {+ boundaries.current.set(identity, new ClientProcessBoundary(identity, element, authManager, desktopViewport, windowActions, traffic, presentation, () => lease(identity, element)))- const boundary = boundaries.current.get(identity)+ return+ }- if (!boundary || boundary.element !== element) return+ sources.delete(identity)- await boundary.own(owner)+ const boundary = boundaries.current.get(identity)- if (sources.get(identity) !== element || frameOwners.current.get(identity) !== owner) {+ boundaries.current.delete(identity)- await boundary.release()+ frameOwners.current.delete(identity)- return- }+ boundary?.release().catch(() => undefined)- }+ }, [authManager, desktopViewport, windowActions, presentation, sources, traffic, lease])- catch (error) { console.error(error) }- })+ // A document that runs the SDK announced itself before this; one that did not is leased here.+ const frameLoaded = useCallback(function (identity: string, element: HTMLIFrameElement) {- frameTasks.current.set(identity, task)+ const boundary = boundaries.current.get(identity)- task.finally(() => { if (frameTasks.current.get(identity) === task) frameTasks.current.delete(identity) }).catch(() => undefined)+ if (sources.get(identity) !== element || !boundary || boundary.element !== element) return- }, [authManager, sources])+ if (boundary.loaded()) lease(identity, element)++ }, [sources, lease])// The interface wall: an iframe's end-end relays to its process's// other end; its end-host terminates here, handled by the desktop —diff --git a/source/client/view/components/desktop-host/client-process-boundary.ts b/source/client/view/components/desktop-host/client-process-boundary.tsindex b976e74..31c0dd7 100644--- a/source/client/view/components/desktop-host/client-process-boundary.ts+++ b/source/client/view/components/desktop-host/client-process-boundary.ts@@ -79,7 +79,16 @@ export default class ClientProcessBoundary extends TheLink {private leased: string | null = null- public constructor(pane: string, element: HTMLIFrameElement, authManager: AuthManager, viewport: DesktopViewportHost, actions: DesktopWindowActions, traffic: ClientTraffic, presentation: PresentationHost) {+ /** How many documents have begun in the frame, so a lease asked for one never goes to the next. */+ private documents = 0++ /** A document announced itself since the frame last finished loading. */+ private announced = false++ /** Asks the host for a lease for the document that just began. */+ private readonly onDocument: () => void++ public constructor(pane: string, element: HTMLIFrameElement, authManager: AuthManager, viewport: DesktopViewportHost, actions: DesktopWindowActions, traffic: ClientTraffic, presentation: PresentationHost, onDocument: () => void) {super()@@ -97,6 +106,8 @@ export default class ClientProcessBoundary extends TheLink {this.presentation = presentation+ this.onDocument = onDocument+this.frame = new ClientFrame(element)this.systemAccess = new SystemAccess(authManager, pane)@@ -107,51 +118,83 @@ export default class ClientProcessBoundary extends TheLink {})}+ /**+ * Gives the current document its lease. Until it holds one, what the document sends waits here;+ * then it follows in order. A lease that arrives after a newer document began is left for that+ * document's own.+ */public async own(owner: string) {- // The iframe load event is the document lifecycle boundary. Preserve- // what the newly loading document already sent, discard everything- // retained for the previous document, then replay the preserved- // envelopes only after the new server-host lease exists.- const pending = this.pending.splice(0)+ const document = this.documents- this.relay.close(new Error("The Program's window was reloaded"))- this.relay = this.newRelay()+ await this.authManager.processManager.ownFrame(this.pane, owner)- this.presentation.begin(this.pane)+ this.leased = owner- this.resetEndpoint()+ if (document !== this.documents) return- this.owner = null+ this.owner = owner- try {+ this.hostRegistrations = Promise.resolve()++ for (const [subscription, description] of this.subscriptions) {- await this.authManager.processManager.ownFrame(this.pane, owner)+ if (directSubscription(description)) this.orderHostRegistration(+ () => this.authManager.processManager.subscribeFrame(this.pane, owner, subscription, description.kind, description.event)+ ).catch(() => undefined)}- catch (error) {+ for (const message of this.pending.splice(0)) this.receive(message)+ }++ /**+ * The frame finished loading a document. A document that runs the SDK has already announced+ * itself; one that did not (a page without it) ends the previous one only now. Returns whether+ * the document needs a lease.+ */+ public loaded() {- this.pending.unshift(...pending)+ if (this.announced) {- throw error+ this.announced = false++ return false}- this.owner = owner+ // What arrived without a lease belongs to the document that just loaded.+ const pending = this.pending.splice(0)- this.leased = owner+ this.leave()- this.hostRegistrations = Promise.resolve()+ this.pending.push(...pending)- for (const [subscription, description] of this.subscriptions) {+ return true+ }- if (directSubscription(description)) this.orderHostRegistration(- () => this.authManager.processManager.subscribeFrame(this.pane, owner, subscription, description.kind, description.event)- ).catch(() => undefined)- }+ /** A new document began in the frame: the previous one ends, and what follows is the new one's. */+ private begin() {++ this.announced = true++ this.leave()++ this.onDocument()+ }++ /** Ends what the frame's document held: its subscriptions, requests, and streams. */+ private leave() {++ this.documents++- pending.push(...this.pending.splice(0))+ this.relay.close(new Error("The Program's window was reloaded"))++ this.relay = this.newRelay()++ this.presentation.begin(this.pane)++ this.resetEndpoint()- for (const message of pending) this.receive(message)+ this.owner = null}public async release() {@@ -160,6 +203,8 @@ export default class ClientProcessBoundary extends TheLink {const owner = this.leased+ this.documents+++this.owner = nullthis.leased = null@@ -178,6 +223,15 @@ export default class ClientProcessBoundary extends TheLink {const [route, ...values] = message+ // Each document's SDK announces it first: messages from one frame arrive in order, so+ // everything before this was the previous document's, and everything after is this one's.+ if (route === "boundary" && values[0] === "document") {++ this.begin()++ return+ }+if (route === "boundary") {if (!this.owner) this.pending.push(message)diff --git a/tests/client-layer-permissions.test.ts b/tests/client-layer-permissions.test.tsindex 551618c..96245e1 100644--- a/tests/client-layer-permissions.test.ts+++ b/tests/client-layer-permissions.test.ts@@ -155,7 +155,7 @@ test("Client layer authorization validates explicit choices without reinterpretitest.each(restrictedLayers)("Client run streams authorize %s before creating an iterator", async layer => {const f = fixture()const boundary = new ClientProcessBoundary(f.process.identity, { contentWindow: null } as HTMLIFrameElement, f.auth,- { state: () => ({ size: { width: 100, height: 100 }, offset: { x: 0, y: 0 } }), move: () => undefined }, {} as never, {} as never, { begin: vi.fn(), cancelMoveGestures: vi.fn() } as never)+ { state: () => ({ size: { width: 100, height: 100 }, offset: { x: 0, y: 0 } }), move: () => undefined }, {} as never, {} as never, { begin: vi.fn(), cancelMoveGestures: vi.fn() } as never, () => undefined)const deliver = vi.spyOn(boundary, "deliver").mockResolvedValue()await boundary.own("frame")const program = { identity: f.program.identity, reference: f.program.reference }diff --git a/tests/client-process-boundary-lifecycle.test.ts b/tests/client-process-boundary-lifecycle.test.tsindex e95a739..741ee7f 100644--- a/tests/client-process-boundary-lifecycle.test.ts+++ b/tests/client-process-boundary-lifecycle.test.ts@@ -46,7 +46,8 @@ test("a Client question expectation survives initial iframe ownership", async (){ state: () => ({ size: { width: 800, height: 600 }, offset: { x: 0, y: 0 } }), move: () => undefined },{} as never,{} as ClientTraffic,- { begin() {} } as unknown as PresentationHost+ { begin() {} } as unknown as PresentationHost,+ () => undefined)const question = "client:process:question"@@ -85,7 +86,8 @@ test("a later Client request cannot overtake its Service subscription registrati{ state: () => ({ size: { width: 800, height: 600 }, offset: { x: 0, y: 0 } }), move: () => undefined },{} as never,{} as ClientTraffic,- { begin() {} } as unknown as PresentationHost+ { begin() {} } as unknown as PresentationHost,+ () => undefined)const address = { name: "browser-server", endpoint: "server" } as const@@ -130,7 +132,8 @@ test("a registered Service event is delivered without a second permission round-{ state: () => ({ size: { width: 800, height: 600 }, offset: { x: 0, y: 0 } }), move: () => undefined },{} as never,traffic,- { begin() {} } as unknown as PresentationHost+ { begin() {} } as unknown as PresentationHost,+ () => undefined)await boundary.own("document")@@ -142,3 +145,76 @@ test("a registered Service event is delivered without a second permission round-assert.deepEqual(sent, [["service-event", "service-subscription", { revision: 1 }]])})++/** A boundary as a frame that reloads sees it: each document announces itself, then is leased. */+function reloadingFrame() {++ const sent: unknown[][] = []+ const leases: string[] = []+ const element = {+ contentWindow: {+ postMessage(message: unknown[]) {++ sent.push(messagepack.deserialize(message[0] as Uint8Array) as unknown[])+ }+ }+ } as unknown as HTMLIFrameElement+ const authManager = {+ processManager: {+ async ownFrame(_pane: string, owner: string) { leases.push(owner) },+ async releaseFrame() {}+ }+ } as unknown as AuthManager+ let documents = 0+ const boundary: ClientProcessBoundary = new ClientProcessBoundary(+ "process",+ element,+ authManager,+ { state: () => ({ size: { width: 800, height: 600 }, offset: { x: 0, y: 0 } }), move: () => undefined },+ {} as never,+ {} as ClientTraffic,+ { begin() {}, cancelMoveGestures() {} } as unknown as PresentationHost,+ () => { boundary.own(`document ${++documents}`).catch(() => undefined) }+ )++ return { boundary, sent, leases }+}++const answer = (question: string) => ["answer", question, "public-question", "read", { success: true, result: 4 }] as const++test("a reloaded document keeps what it sent before its frame finished loading", async () => {++ const { boundary, sent, leases } = reloadingFrame()++ boundary.receive(["boundary", "document"])+ await vi.waitFor(() => assert.deepEqual(leases, ["document 1"]))+ assert.equal(boundary.loaded(), false)+ boundary.receive(["boundary", "expect", "old question"])++ // The page reloads: the new document asks before its load event.+ boundary.receive(["boundary", "document"])+ boundary.receive(["boundary", "expect", "new question"])+ await vi.waitFor(() => assert.deepEqual(leases, ["document 1", "document 2"]))+ assert.equal(boundary.loaded(), false)++ await boundary.deliver("end-end", ...answer("old question"))+ await boundary.deliver("end-end", ...answer("new question"))++ assert.deepEqual(sent, [["end-end", ...answer("new question")]])+})++test("a document that never announces itself ends the previous one when its frame loads", async () => {++ const { boundary, sent } = reloadingFrame()++ boundary.receive(["boundary", "document"])+ assert.equal(boundary.loaded(), false)+ await boundary.own("document 1")+ boundary.receive(["boundary", "expect", "old question"])++ // A page without the SDK replaces it.+ assert.equal(boundary.loaded(), true)++ await boundary.deliver("end-end", ...answer("old question"))+ assert.deepEqual(sent, [])+})diff --git a/tests/presentation.test.ts b/tests/presentation.test.tsindex bb4d5af..1e8d1a4 100644--- a/tests/presentation.test.ts+++ b/tests/presentation.test.ts@@ -126,9 +126,12 @@ test("a Client boundary initializes each new document exactly once", async () =>{ state: () => ({ size: { width: 1, height: 1 }, offset: { x: 0, y: 0 } }), move: () => undefined },{} as never,{} as never,- { begin(identity: string) { lifecycle.push(identity) }, cancelMoveGestures() {} } as never+ { begin(identity: string) { lifecycle.push(identity) }, cancelMoveGestures() {} } as never,+ () => undefined)+ boundary.receive(["boundary", "document"])await boundary.own("first-owner")+ boundary.receive(["boundary", "document"])await boundary.own("second-owner")await boundary.release()assert.deepEqual(lifecycle, ["requester", "requester"])