Skip to content

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

Unify System communication boundaries

zohayrslileh02f1c4983c52
diff --git a/bun.lock b/bun.lock
index 52aaa7c..686585b 100644
--- a/bun.lock
+++ b/bun.lock
@@ -8,10 +8,9 @@
"@fontsource/roboto": "^5.3.0",
"@hono/node-server": "^2.1.1",
"@msgpack/msgpack": "^3.1.3",
- "@the-link/client": "^0.2.0",
"@the-link/core": "^0.2.0",
+ "@the-link/http": "^0.1.0",
"@the-link/react": "^0.2.0",
- "@the-link/server": "^0.2.0",
"cfonts": "^3.3.1",
"gsap": "^3.15.0",
"hono": "^4.13.2",
@@ -305,13 +304,11 @@
"@tailwindcss/vite": ["@tailwindcss/[email protected]", "", { "dependencies": { "@tailwindcss/node": "4.3.3", "@tailwindcss/oxide": "4.3.3", "tailwindcss": "4.3.3" }, "peerDependencies": { "vite": "^5.2.0 || ^6 || ^7 || ^8" } }, "sha512-yYU8cogLeSh/ms2jh8Fj7jaba/EWa7Ja6GoUqYZaraEuCI5YS6ms6ObZgjjedm+jm6XZjdNRWBpPP6Z86oOxcw=="],
- "@the-link/client": ["@the-link/[email protected]", "", { "dependencies": { "@the-link/core": "^0.2.0", "uuid": "^14.0.1" } }, "sha512-vMuGWKqJb1cCgtHy/w6+H3kN5qkrUFJFGPvBYGV/YvI1LtD/9K5iVxQutTZe1Efks3CwgiV/lbwJXl9FbA/QTg=="],
-
"@the-link/core": ["@the-link/[email protected]", "", { "dependencies": { "uuid": "^14.0.1" } }, "sha512-xUbgY24gn1id1uOM194PiWdgJMw8ApF/Ujjs8E7ENN9jEVJzriwGywF171WeFU7o3azj009HUjfvh7crafOGlA=="],
- "@the-link/react": ["@the-link/[email protected]", "", { "peerDependencies": { "@the-link/core": "^0.2.0", "react": "^19.2.0" } }, "sha512-HhWA3s1bWkrzee5IUs122AOvdkL21ckIbqFkg2nsTsBqHuS2XapfxIeZGJw+PVB3za9aC+wSEuTcLKH75WKgVg=="],
+ "@the-link/http": ["@the-link/[email protected]", "", { "dependencies": { "@the-link/core": "^0.2.0", "hono": "^4.13.2", "uuid": "^14.0.1" } }, "sha512-d1S6zYG6gLzMoQtjpDCX8ium0XQt01xDlXVgvPQBzA7Q3/P9dhknFPUewT58ngRCw42dSk16ylnu3EYSvpNdiQ=="],
- "@the-link/server": ["@the-link/[email protected]", "", { "dependencies": { "@the-link/core": "^0.2.0", "hono": "^4.13.2", "uuid": "^14.0.1" } }, "sha512-UJ4WTxDQ3gb9UKhcPwSiFNQ0FhoEuNUY7xk+qiji72uGKVsT13dzFueEVr4iKnwJ8h39g+phkeFeK+ekVHyvFw=="],
+ "@the-link/react": ["@the-link/[email protected]", "", { "peerDependencies": { "@the-link/core": "^0.2.0", "react": "^19.2.0" } }, "sha512-HhWA3s1bWkrzee5IUs122AOvdkL21ckIbqFkg2nsTsBqHuS2XapfxIeZGJw+PVB3za9aC+wSEuTcLKH75WKgVg=="],
"@types/adm-zip": ["@types/[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-RVVH7QvZYbN+ihqZ4kX/dMiowf6o+Jk1fNwiSdx0NahBJLU787zkULhGhJM8mf/obmLGmgdMM0bXsQTmyfbR7Q=="],
diff --git a/package.json b/package.json
index 14f1f32..341a73c 100644
--- a/package.json
+++ b/package.json
@@ -38,10 +38,9 @@
"@fontsource/roboto": "^5.3.0",
"@hono/node-server": "^2.1.1",
"@msgpack/msgpack": "^3.1.3",
- "@the-link/client": "^0.2.0",
"@the-link/core": "^0.2.0",
+ "@the-link/http": "^0.1.0",
"@the-link/react": "^0.2.0",
- "@the-link/server": "^0.2.0",
"cfonts": "^3.3.1",
"gsap": "^3.15.0",
"hono": "^4.13.2",
diff --git a/source/client/core/application.ts b/source/client/core/application.ts
index 98eb3e2..3f7aad3 100644
--- a/source/client/core/application.ts
+++ b/source/client/core/application.ts
@@ -1,4 +1,4 @@
-import { ClientLink } from "@the-link/client"
+import { HttpClient } from "@the-link/http/client"
import { type ProxyOutcome, type ProxyRequest, type ProxyResponse, proxyMediaType } from "@server/core/protocol/proxy"
import { storageMediaType, type StorageRequest } from "@server/core/protocol/storage"
import { frame, frameBlob, unframe } from "@libs/framing"
@@ -15,7 +15,7 @@ export default class Application {
public readonly doors: Doors
- public readonly clientLink: ClientLink
+ public readonly httpClient: HttpClient
public constructor(name: string, displayName: string, version: string, doors: Doors) {
@@ -27,11 +27,11 @@ export default class Application {
this.doors = doors
- this.clientLink = new ClientLink(this.doors.link)
+ this.httpClient = new HttpClient(this.doors.link)
- this.clientLink.setSerialize(messagepack.serialize)
+ this.httpClient.setSerialize(messagepack.serialize)
- this.clientLink.setDeserialize(messagepack.deserialize)
+ this.httpClient.setDeserialize(messagepack.deserialize)
}
// A finite browser body keeps its length, so HTTP/1 can stream it from its
diff --git a/source/client/core/link-manager/link-manager.ts b/source/client/core/link-manager/link-manager.ts
index 0df5712..545a45a 100644
--- a/source/client/core/link-manager/link-manager.ts
+++ b/source/client/core/link-manager/link-manager.ts
@@ -8,7 +8,7 @@ import { TheLink } from "@the-link/core"
import { Property } from "@the-link/core"
import Application from "../application"
import { v4 as uuidv4 } from "uuid"
-import { type Outcome, unwrap } from "@server/core/outcome"
+import { type RequestOutcome, unwrap } from "@libs/request-outcome"
export default class LinkManager extends TheLink {
@@ -16,15 +16,13 @@ export default class LinkManager extends TheLink {
public readonly sourceLink: TheLink
- public readonly connectionIdentity: string
-
/** Immediate unresolved System Appearance and future authoritative updates. */
public readonly appearance: Property<Appearance>
/** Complete effective local Desktop preferences and future updates. */
public readonly desktopPreferences: Property<DesktopPreferences>
- public constructor(application: Application, sourceLink: TheLink, payload: TransmittedLinkManager, connectionIdentity: string, desktopPreferences: DesktopPreferences) {
+ public constructor(application: Application, sourceLink: TheLink, payload: TransmittedLinkManager, desktopPreferences: DesktopPreferences) {
super()
@@ -32,8 +30,6 @@ export default class LinkManager extends TheLink {
this.sourceLink = sourceLink
- this.connectionIdentity = connectionIdentity
-
this.subscribeTo(this.sourceLink)
this.appearance = Property.consumer(this, payload.appearance.key, payload.appearance.value)
@@ -56,7 +52,7 @@ export default class LinkManager extends TheLink {
await this.sourceLink.$outbound.publish(event, responseUuid, ...values)
- const response = await this.sourceLink.$inbound.waitFirst<Outcome<unknown[]>>(responseUuid)
+ const response = await this.sourceLink.$inbound.waitFirst<RequestOutcome<unknown[]>>(responseUuid)
return unwrap(response)
}
@@ -85,6 +81,6 @@ export default class LinkManager extends TheLink {
public async sessionAuthenticate(authorization: string | null) {
- return await this.$outbound.publishFirst<[string, TransmittedAuthManager] | false>("/session-authenticate", this.connectionIdentity, authorization)
+ return await this.$outbound.publishFirst<[string, TransmittedAuthManager] | false>("/session-authenticate", authorization)
}
}
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 ae22002..ded8fa5 100644
--- a/source/client/view/components/desktop-host/client-process-boundary.ts
+++ b/source/client/view/components/desktop-host/client-process-boundary.ts
@@ -2,7 +2,7 @@ import AuthManager from "@client/core/link-manager/auth-manager/auth-manager"
import { TheLink } from "@the-link/core"
import host, { TransferredAnswer } from "./host"
import ClientTraffic from "./client-traffic"
-import { failed, succeeded } from "@server/core/outcome"
+import { failed, succeeded } from "@libs/request-outcome"
import { type TrafficKind } from "@server/core/link-manager/auth-manager/process-manager/process-traffic"
import { isServiceKey, type DesktopSurfaceSnapshot, type ServiceKey, type ShellOptions } from "@phreshos/core"
import { type LocalWindowHost } from "./local-window"
diff --git a/source/client/view/structure/structure.tsx b/source/client/view/structure/structure.tsx
index 2cf5dae..be90804 100644
--- a/source/client/view/structure/structure.tsx
+++ b/source/client/view/structure/structure.tsx
@@ -1,7 +1,6 @@
import { ReactTunnel } from "@the-link/react"
import { useProperty } from "@the-link/react"
import { TransmittedLinkManager } from "@server/core/link-manager/link-manager"
-import { SocketLink } from "@the-link/client"
import LinkManager from "@client/core/link-manager/link-manager"
import { AppearanceProvider, useResolveTheme } from "@phreshos/react-ui"
import Loading from "../components/loading"
@@ -48,22 +47,23 @@ function Desktop() {
const [connectionRevision, setConnectionRevision] = useState(0)
- const internal = ReactTunnel.useFactory(application.clientLink.$internal)
+ const subscribe = useCallback(function () {
- internal.useSubscribe("subscribe", useCallback(function (socketLink: SocketLink<[TransmittedLinkManager, string]>) {
+ return application.httpClient.onSubscribe<TransmittedLinkManager>(function (link) {
- const [payload, connectionIdentity] = socketLink.payload
+ const manager = new LinkManager(application, link, link.payload, preferences)
- const manager = new LinkManager(application, socketLink, payload, connectionIdentity, preferences)
+ link.$internal.subscribeOnce("unsubscribe", () => {
+ setLinkManager(current => current === manager ? null : current)
+ })
- socketLink.$internal.subscribeOnce("unsubscribe", () => {
- setLinkManager(current => current === manager ? null : current)
+ setLinkManager(manager)
})
+ }, [application, preferences])
- setLinkManager(manager)
- }, [application, preferences]))
+ useEffect(subscribe, [subscribe])
- const connection = usePromise(async () => application.clientLink.subscribe(), [application, connectionRevision])
+ const connection = usePromise(async () => application.httpClient.subscribe(), [application, connectionRevision])
if (connection.exception) return <FailedConnection
diff --git a/source/libs/request-outcome.ts b/source/libs/request-outcome.ts
new file mode 100644
index 0000000..c8aa950
--- /dev/null
+++ b/source/libs/request-outcome.ts
@@ -0,0 +1,30 @@
+/** Internal result envelope for a correlated request. */
+export type RequestOutcome<Result = unknown> =
+ | Readonly<{ success: true, result: Result }>
+ | Readonly<{ success: false, error: string }>
+
+export function succeeded<Result>(result: Result): RequestOutcome<Result> {
+
+ return { success: true, result }
+}
+
+export function failed(exception: unknown, disclose = true): RequestOutcome<never> {
+
+ return {
+
+ success: false,
+
+ error: disclose && exception instanceof Error ? exception.message : "An unknown exception occurred"
+ }
+}
+
+export function unwrap<Result>(outcome: RequestOutcome<Result>): Result {
+
+ if (!outcome || typeof outcome !== "object" || !("success" in outcome)) throw new Error("The boundary returned an invalid outcome")
+
+ if (outcome.success === true) return outcome.result
+
+ if (outcome.success !== false || !("error" in outcome) || typeof outcome.error !== "string") throw new Error("The boundary returned an invalid outcome")
+
+ throw new Error(outcome.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 82179d4..67d400e 100644
--- a/source/server/core/link-manager/auth-manager/auth-manager.ts
+++ b/source/server/core/link-manager/auth-manager/auth-manager.ts
@@ -56,6 +56,12 @@ export default class AuthManager extends TheLink {
if (!session) throw new Error("Unauthorized")
}
+ /** Identity of the connection currently invoking an authenticated operation. */
+ public connection() {
+
+ return this.linkManager.connection().identity
+ }
+
@Intercept("inbound")
protected authenticate(authorization: string, ...values: unknown[]) {
diff --git a/source/server/core/link-manager/auth-manager/process-manager/outside-questions.ts b/source/server/core/link-manager/auth-manager/process-manager/outside-questions.ts
index 48be901..afbfdc6 100644
--- a/source/server/core/link-manager/auth-manager/process-manager/outside-questions.ts
+++ b/source/server/core/link-manager/auth-manager/process-manager/outside-questions.ts
@@ -1,5 +1,5 @@
import { randomUUID } from "node:crypto"
-import type { Outcome } from "@server/core/outcome"
+import type { RequestOutcome } from "@libs/request-outcome"
import type ServerProcessBoundary from "./server-process-boundary"
/** Active questions from trusted System views that are not Program Endpoints. */
@@ -37,7 +37,7 @@ export default class OutsideQuestions {
})
}
- public answer(question: string, outcome: Outcome) {
+ public answer(question: string, outcome: RequestOutcome) {
const pending = this.take(question)
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.ts
index 6522a89..68b2cd4 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
@@ -12,7 +12,7 @@ import ServerProcessBoundary from "./server-process-boundary"
import ProcessTraffic, { type Half, type TrafficKind } from "./process-traffic"
import ClientProcessForwarder from "./client-process-forwarder"
import HostTraffic from "./host-traffic"
-import { failed, succeeded, type Outcome } from "@server/core/outcome"
+import { failed, succeeded, type RequestOutcome } from "@libs/request-outcome"
import { endpointReference, processReference } from "./endpoint-reference"
import EndpointEvents from "./endpoint-events"
import EndpointServices from "./endpoint-services"
@@ -583,14 +583,14 @@ export default class ProcessManager extends TheLink {
if (back.half === "outside") {
- this.outsideQuestions.answer(values[1], values[4] as Outcome)
+ this.outsideQuestions.answer(values[1], values[4] as RequestOutcome)
return true
}
const process = this.processes.get(back.identity)
- const outcome = values[4] as Outcome
+ const outcome = values[4] as RequestOutcome
if (answerer && process) {
@@ -1292,65 +1292,65 @@ export default class ProcessManager extends TheLink {
}
@Subscribe("/frame/own")
- protected ownClientFrame(connection: string, pane: string, owner: string) {
+ protected ownClientFrame(pane: string, owner: string) {
- this.ownClient(connection, pane, owner)
+ this.ownClient(this.authManager.connection(), pane, owner)
}
@Subscribe("/frame/release")
- protected releaseClientFrame(connection: string, pane: string, owner: string) {
+ protected releaseClientFrame(pane: string, owner: string) {
- this.releaseClient(connection, pane, owner)
+ this.releaseClient(this.authManager.connection(), pane, owner)
}
@Subscribe("/frame/subscribe")
- protected subscribeClientFrame(connection: string, pane: string, owner: string, subscription: string, kind: unknown, event: unknown) {
+ protected subscribeClientFrame(pane: string, owner: string, subscription: string, kind: unknown, event: unknown) {
if (kind !== "publish" || event !== null && typeof event !== "string") return
- this.registerClientSubscription(connection, pane, owner, subscription, event)
+ this.registerClientSubscription(this.authManager.connection(), pane, owner, subscription, event)
}
@Subscribe("/frame/unsubscribe")
- protected unsubscribeClientFrame(connection: string, pane: string, owner: string, subscription: string) {
+ protected unsubscribeClientFrame(pane: string, owner: string, subscription: string) {
- this.removeClientSubscription(connection, pane, owner, subscription)
+ this.removeClientSubscription(this.authManager.connection(), pane, owner, subscription)
}
@Subscribe("/frame/observe")
- protected observeClientFrame(connection: string, pane: string, owner: string, subscription: string, target: unknown, half: string, kind: unknown, event: unknown, reportImpossible: unknown) {
+ protected observeClientFrame(pane: string, owner: string, subscription: string, target: unknown, half: string, kind: unknown, event: unknown, reportImpossible: unknown) {
if (!isTrafficKind(kind)) return
if (event !== null && typeof event !== "string") return
- this.registerClientObservation(connection, pane, owner, subscription, target, half, kind, event, reportImpossible === true)
+ this.registerClientObservation(this.authManager.connection(), pane, owner, subscription, target, half, kind, event, reportImpossible === true)
}
@Subscribe("/frame/unobserve")
- protected unobserveClientFrame(connection: string, pane: string, owner: string, subscription: string) {
+ protected unobserveClientFrame(pane: string, owner: string, subscription: string) {
- this.removeClientObservation(connection, pane, owner, subscription)
+ this.removeClientObservation(this.authManager.connection(), pane, owner, subscription)
}
@Subscribe("/frame/follow")
- protected followClientFrame(connection: string, pane: string, owner: string, subscription: string, target: unknown, half: string, event: unknown, reportImpossible: unknown) {
+ protected followClientFrame(pane: string, owner: string, subscription: string, target: unknown, half: string, event: unknown, reportImpossible: unknown) {
if (event !== null && typeof event !== "string") return
- this.registerClientFollow(connection, pane, owner, subscription, target, half, event, reportImpossible === true)
+ this.registerClientFollow(this.authManager.connection(), pane, owner, subscription, target, half, event, reportImpossible === true)
}
@Subscribe("/frame/unfollow")
- protected unfollowClientFrame(connection: string, pane: string, owner: string, subscription: string) {
+ protected unfollowClientFrame(pane: string, owner: string, subscription: string) {
- this.removeClientFollow(connection, pane, owner, subscription)
+ this.removeClientFollow(this.authManager.connection(), pane, owner, subscription)
}
@Subscribe("/frame/service/follow")
- protected followClientService(connection: string, pane: string, owner: string, subscription: unknown, key: unknown, scope: unknown, event: unknown) {
+ protected followClientService(pane: string, owner: string, subscription: unknown, key: unknown, scope: unknown, event: unknown) {
- const boundary = this.clientForwarders.get(this.clientOwnerKey(connection, pane))
+ const boundary = this.clientForwarders.get(this.clientOwnerKey(this.authManager.connection(), pane))
if (boundary?.owner !== owner || typeof subscription !== "string" || !isServiceKey(key)) return
@@ -1362,15 +1362,15 @@ export default class ProcessManager extends TheLink {
}
@Subscribe("/frame/service/unfollow")
- protected unfollowClientService(connection: string, pane: string, owner: string, subscription: unknown) {
+ protected unfollowClientService(pane: string, owner: string, subscription: unknown) {
- const boundary = this.clientForwarders.get(this.clientOwnerKey(connection, pane))
+ const boundary = this.clientForwarders.get(this.clientOwnerKey(this.authManager.connection(), pane))
if (boundary?.owner === owner && typeof subscription === "string") boundary.unfollowService(subscription)
}
@Subscribe("/frame/log")
- protected logClientFrame(_connection: string, pane: string, kind: unknown, content: unknown) {
+ protected logClientFrame(pane: string, kind: unknown, content: unknown) {
if (typeof kind !== "string" || typeof content !== "string") return
@@ -2191,7 +2191,7 @@ export default class ProcessManager extends TheLink {
let stopExit: () => void = () => undefined
let stopEndpoint: () => void = () => undefined
- const finish = (outcome?: Outcome<unknown[]>) => {
+ const finish = (outcome?: RequestOutcome<unknown[]>) => {
if (!active) return
@@ -2352,7 +2352,9 @@ export default class ProcessManager extends TheLink {
// losing the session therefore removes the target's queued request even
// when the desktop can no longer send an explicit cancellation.
@Subscribe("/frame/ask")
- protected askClientFrame(connection: string, source: string, identity: string, values: unknown[]) {
+ protected askClientFrame(source: string, identity: string, values: unknown[]) {
+
+ const connection = this.authManager.connection()
const question = String(values[0])
@@ -2367,7 +2369,9 @@ export default class ProcessManager extends TheLink {
}
@Subscribe("/frame/service/ask")
- protected askClientService(connection: string, source: string, key: unknown, values: unknown[]) {
+ protected askClientService(source: string, key: unknown, values: unknown[]) {
+
+ const connection = this.authManager.connection()
if (!isServiceKey(key) || key.endpoint !== "server" || typeof values[0] !== "string" || typeof values[1] !== "string" || typeof values[2] !== "string") {
@@ -2389,9 +2393,9 @@ export default class ProcessManager extends TheLink {
}
@Subscribe("/frame/cancel")
- protected cancelClientFrame(connection: string, source: string, question: string) {
+ protected cancelClientFrame(source: string, question: string) {
- this.clientForwarders.get(this.clientOwnerKey(connection, source))?.cancel(question)
+ this.clientForwarders.get(this.clientOwnerKey(this.authManager.connection(), source))?.cancel(question)
}
// Where both roads meet: a question named by whoever is waiting for
@@ -2426,7 +2430,9 @@ export default class ProcessManager extends TheLink {
}
@Subscribe("/frame/end-end")
- protected async endEndClientFrame(connection: string, identity: string, values: unknown[]) {
+ protected async endEndClientFrame(identity: string, values: unknown[]) {
+
+ const connection = this.authManager.connection()
// The payload crosses The Link once as its native event tuple. The
// route still supplies the speaker; no nested wire format is needed.
diff --git a/source/server/core/link-manager/link-manager.ts b/source/server/core/link-manager/link-manager.ts
index 65b1a15..73a5895 100644
--- a/source/server/core/link-manager/link-manager.ts
+++ b/source/server/core/link-manager/link-manager.ts
@@ -6,6 +6,7 @@ import { Transmitted } from "@libs/messagepack"
import Application from "../application"
import { type Appearance } from "@phreshos/core"
import { type AuthenticationState, type RegistrationError } from "../authentication/authentication"
+import { AsyncLocalStorage } from "node:async_hooks"
export default class LinkManager extends TheLink {
@@ -14,6 +15,8 @@ export default class LinkManager extends TheLink {
/** Live desktop connections. Authentication sessions outlive these links. */
public readonly connections = new Map<string, Connection>()
+ private readonly connectionContext = new AsyncLocalStorage<Connection>()
+
public readonly authManager: AuthManager
/** Public, unresolved representation of authoritative System Appearance. */
@@ -34,22 +37,38 @@ export default class LinkManager extends TheLink {
public addConnection(link: TheLink) {
- const identity = crypto.randomUUID()
+ const connection = new Connection(this, link)
- this.connections.set(identity, { link, session: null })
+ this.connections.set(connection.identity, connection)
- return identity
+ return connection
}
- public async removeConnection(identity: string) {
+ public async removeConnection(connection: Connection) {
+
+ if (this.connections.get(connection.identity) !== connection) return
+
+ this.authManager.processManager.releaseConnection(connection.identity)
+
+ this.connections.delete(connection.identity)
- const connection = this.connections.get(identity)
+ if (connection.session && !this.connected(connection.session)) await this.application.authentication.disconnectSession(connection.session)
+ }
- this.authManager.processManager.releaseConnection(identity)
+ public receive(connection: Connection, event: string, ...values: unknown[]) {
- this.connections.delete(identity)
+ if (this.connections.get(connection.identity) !== connection) throw new Error("Connection not found")
- if (connection?.session && !this.connected(connection.session)) await this.application.authentication.disconnectSession(connection.session)
+ return this.connectionContext.run(connection, () => this.$inbound.publish(event, ...values))
+ }
+
+ public connection() {
+
+ const connection = this.connectionContext.getStore()
+
+ if (!connection || this.connections.get(connection.identity) !== connection) throw new Error("This operation requires a live connection")
+
+ return connection
}
@Subscribe("/owner/state")
@@ -104,11 +123,9 @@ export default class LinkManager extends TheLink {
}
@Subscribe("/session-authenticate")
- protected async sessionAuthenticate(connectionIdentity: string, authorization: string | null) {
+ protected async sessionAuthenticate(authorization: string | null) {
- const connection = this.connections.get(connectionIdentity)
-
- if (!connection) throw new Error("Connection not found")
+ const connection = this.connection()
if (!authorization) {
@@ -205,11 +222,18 @@ export type TransmittedLinkManager = Transmitted<LinkManager>
export type RegistrationResponse = { authorization: string } | { error: RegistrationError }
-interface Connection {
+export class Connection {
+
+ public readonly identity = crypto.randomUUID()
- link: TheLink
+ public session: string | null = null
- session: string | null
+ public constructor(private readonly manager: LinkManager, public readonly link: TheLink) {}
+
+ public publish(event: string, ...values: unknown[]) {
+
+ return this.manager.receive(this, event, ...values)
+ }
}
function isAuthorization(value: unknown): value is { version: 1, session: string } {
diff --git a/source/server/core/outcome.ts b/source/server/core/outcome.ts
deleted file mode 100644
index 25316f4..0000000
--- a/source/server/core/outcome.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { type Outcome } from "@phreshos/core"
-
-export type { Outcome } from "@phreshos/core"
-
-/** Wrap a successful boundary result, including `undefined`, without ambiguity. */
-export function succeeded<Result>(result: Result): Outcome<Result> {
-
- return { success: true, result }
-}
-
-/**
- * Normalize a thrown value at the boundary where it occurred.
- *
- * Arbitrary thrown values never become transport data. An Error may disclose
- * its message only where the caller is permitted to receive details.
- */
-export function failed(exception: unknown, disclose = true): Outcome<never> {
-
- return {
-
- success: false,
-
- error: disclose && exception instanceof Error ? exception.message : "An unknown exception occurred"
- }
-}
-
-/** Resolve a successful boundary outcome or reconstruct its failure locally. */
-export function unwrap<Result>(outcome: Outcome<Result>): Result {
-
- if (!outcome || typeof outcome !== "object" || !("success" in outcome)) throw new Error("The boundary returned an invalid outcome")
-
- // JSON omits an `undefined` property. Success is the known envelope fact;
- // reading its absent result reconstructs that valid `undefined` value.
- if (outcome.success === true) return outcome.result
-
- if (outcome.success !== false || !("error" in outcome) || typeof outcome.error !== "string") throw new Error("The boundary returned an invalid outcome")
-
- throw new Error(outcome.error)
-}
diff --git a/source/server/view/link.ts b/source/server/view/link.ts
index 0f901fb..5d3f52f 100644
--- a/source/server/view/link.ts
+++ b/source/server/view/link.ts
@@ -1,22 +1,22 @@
-import { ServerLink } from "@the-link/server"
+import { failed, succeeded } from "@libs/request-outcome"
import { upgradeWebSocket } from "@hono/node-server"
import Application from "@server/core/application"
+import { HttpServer } from "@the-link/http/server"
import messagepack from "@libs/messagepack"
-import { failed, succeeded } from "@server/core/outcome"
export default function (application: Application, debugging: boolean) {
- const serverLink = new ServerLink()
+ const http = new HttpServer()
- if (debugging) serverLink.enableDebugging()
+ if (debugging) http.enableDebugging()
- serverLink.setSerialize(messagepack.serialize)
+ http.setSerialize(messagepack.serialize)
- serverLink.setDeserialize(messagepack.deserialize)
+ http.setDeserialize(messagepack.deserialize)
- serverLink.onSubscribe(function (socketLink) {
+ http.onSubscribe(function (socketLink) {
- const connectionIdentity = application.linkManager.addConnection(socketLink)
+ const connection = application.linkManager.addConnection(socketLink)
const stopForwarding = socketLink.$inbound.forwardTo(async function (event, responseUuid: string | null, ...values: unknown[]) {
@@ -24,21 +24,14 @@ export default function (application: Application, debugging: boolean) {
// envelope. Route it once and do not manufacture an acknowledgement.
if (responseUuid === null) {
- const routed = connectionOwned(event) ? [values[0], connectionIdentity, ...values.slice(1)] : values
-
- application.linkManager.$inbound.publish(event, ...routed).catch(() => undefined)
+ connection.publish(event, ...values).catch(() => undefined)
return
}
try {
- // Every Client-frame operation is owned by this socket. Insert
- // the connection here, where it comes from the connection
- // itself and cannot be supplied by an iframe.
- const routed = connectionOwned(event) ? [values[0], connectionIdentity, ...values.slice(1)] : values
-
- const results = await application.linkManager.$inbound.publish(event, ...routed)
+ const results = await connection.publish(event, ...values)
await socketLink.$outbound.publish(responseUuid, succeeded(results))
}
@@ -51,20 +44,15 @@ export default function (application: Application, debugging: boolean) {
socketLink.$internal.subscribeOnce("unsubscribe", async function () {
- await application.linkManager.removeConnection(connectionIdentity)
+ await application.linkManager.removeConnection(connection)
stopForwarding()
})
- return [application.linkManager, connectionIdentity]
+ return application.linkManager
})
- serverLink.prepareConnection(upgradeWebSocket)
-
- return serverLink.app
-}
-
-function connectionOwned(event: string) {
+ http.prepareConnection(upgradeWebSocket)
- return event.startsWith("/auth/frame/") || event.startsWith("/auth/process/frame/")
+ return http.app
}