Skip to content

Commit b554ad2

Browse files
authored
feat(server): signed ticket URLs for machine file media (#68279)
Co-authored-by: kommander <335157+kommander@users.noreply.github.com>
1 parent 6868da2 commit b554ad2

22 files changed

Lines changed: 592 additions & 42 deletions

File tree

‎packages/app/src/runtime/server/api.test.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
import { expect, test } from "bun:test"
2-
import { authFromToken, authTokenFromCredentials, createApiForServer, fileStreamUrl, machineFileStreamUrl } from "./api"
2+
import {
3+
authFromToken,
4+
authTokenFromCredentials,
5+
createApiForServer,
6+
fileStreamUrl,
7+
machineFileStreamUrl,
8+
serverRelativeUrl,
9+
} from "./api"
310

411
test.each([
512
[btoa("opencode:secret"), { password: "secret" }],
@@ -30,6 +37,16 @@ test("fileStreamUrl never puts a credential in a media URL", () => {
3037
)
3138
})
3239

40+
test("serverRelativeUrl keeps the server's base path for a ticketed read", () => {
41+
const url = "/api/experimental/machine/file/read?path=gpu%3A%2Fa.mp4&ticket=1.abc"
42+
expect(serverRelativeUrl({ url: "https://host.example:4096", password: "secret" }, url)).toBe(
43+
`https://host.example:4096${url}`,
44+
)
45+
expect(serverRelativeUrl({ url: "https://host.example/opencode", password: "secret" }, url)).toBe(
46+
`https://host.example/opencode${url}`,
47+
)
48+
})
49+
3350
test("only message and inbox reads ask for media refs, so other cross-origin requests stay unpreflighted", async () => {
3451
const requests: Array<{ path: string; headers: Headers }> = []
3552

‎packages/app/src/runtime/server/api.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ export function createApiForServer(input: { server: ServerConnection.HttpBase; f
4242
/**
4343
* The server's ranged read of one file, for media elements. They cannot send the Authorization header, and a credential
4444
* never goes in a DOM URL, so a server that needs a password has none: its media downloads through the API instead.
45+
* A machine file has a ticketed URL for that (see `machineFileStreamUrl`).
4546
*/
4647
export function fileStreamUrl(server: ServerConnection.HttpBase, input: { path: string; directory: string }) {
4748
if (server.password) return
@@ -56,11 +57,19 @@ export function fileStreamUrl(server: ServerConnection.HttpBase, input: { path:
5657
return url.href
5758
}
5859

59-
/** The ranged read of a file on a paired machine, for media elements; none with a password, as `fileStreamUrl`. */
60+
/**
61+
* The ranged read of a file on a paired machine, for media elements; none with a password, as `fileStreamUrl`. A
62+
* server with a password issues a URL carrying a ticket for that one path instead (`machine.file.ticket`).
63+
*/
6064
export function machineFileStreamUrl(server: ServerConnection.HttpBase, path: string) {
6165
if (server.password) return
6266

6367
return machineFileURL(server.url, path)
6468
}
6569

70+
/** A server-relative URL the server returned, such as a ticketed machine file read, under the server's base path. */
71+
export function serverRelativeUrl(server: ServerConnection.HttpBase, path: string) {
72+
return new URL(path.replace(/^\/+/, ""), server.url.endsWith("/") ? server.url : `${server.url}/`).href
73+
}
74+
6675
export type ServerApi = ReturnType<typeof createApiForServer>

‎packages/app/src/workspaces/files/content-machine.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,23 @@ describe("file content machine", () => {
189189
expect(transitionFileContent(step.state, succeeded(1, before)).state).toBe(step.state)
190190
})
191191

192+
test("content whose URL expired stays shown and the next plain load reads it again, unless it was reread", () => {
193+
const loaded = replay([requested(), succeeded(1, before)])
194+
const expired = transitionFileContent(loaded.state, { type: "content.expired", path: "a.ts", content: before })
195+
196+
expect(expired.effects).toEqual([])
197+
expect(entry(expired.state)).toEqual({ status: "ready", content: before, stale: true })
198+
expect(transitionFileContent(expired.state, requested()).effects).toEqual([
199+
{ type: "read", directory: "/repo", path: "a.ts", attempt: 2 },
200+
])
201+
202+
const reread = replay([requested(), succeeded(1, before), requested(true), succeeded(2, after)])
203+
204+
expect(transitionFileContent(reread.state, { type: "content.expired", path: "a.ts", content: before }).state).toBe(
205+
reread.state,
206+
)
207+
})
208+
192209
test("eviction forgets a loaded file and steps a refresh down to a first load", () => {
193210
const loaded = replay([
194211
requested(),

‎packages/app/src/workspaces/files/content-machine.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import type { FileState } from "./types"
44

55
// One normalized path's content lifecycle in the provider's directory. An unloaded or evicted file has no entry.
66
// `rerun` records a change reported while a read was in flight: that read's result is outdated, so one more read runs
7-
// when it settles. `stale` records a failed refresh, so the next plain load reads again. A read has no deadline of its
7+
// when it settles. `stale` records a failed refresh or content whose URL expired, so the next plain load reads again. A read has no deadline of its
88
// own: the transport gives up on a server that sends no response, which arrives here as `load.failed`, and a large file
99
// may download for as long as it needs.
1010
export type FileEntryState =
@@ -44,6 +44,8 @@ export type FileContentEvent =
4444
readonly opened: boolean
4545
}
4646
| { readonly type: "load.failed"; readonly path: string; readonly attempt: number; readonly error: string }
47+
// A streamed file's URL is about to stop working, such as a machine file's ticket expiring.
48+
| { readonly type: "content.expired"; readonly path: string; readonly content: FileContent }
4749
| { readonly type: "cache.evicted"; readonly paths: readonly string[] }
4850
| { readonly type: "scope.changed"; readonly directory: string }
4951
| { readonly type: "disposed" }
@@ -87,6 +89,8 @@ export function transitionFileContent(state: FileContentState, event: FileConten
8789

8890
if (event.type === "cache.evicted") return evict(state, event.paths)
8991

92+
if (event.type === "content.expired") return expire(state, event)
93+
9094
if (event.type === "load.requested") return request(state, event)
9195

9296
return complete(state, event)
@@ -199,6 +203,15 @@ function start(
199203
])
200204
}
201205

206+
// Content whose URL expired stays shown; the next plain load reads it again. Content since reread is left alone.
207+
function expire(state: ActiveState, event: Extract<FileContentEvent, { type: "content.expired" }>) {
208+
const entry = state.files[event.path]
209+
210+
if (entry?.status !== "ready" || entry.stale || entry.content !== event.content) return unchanged(state)
211+
212+
return changed(put(state, event.path, { ...entry, stale: true }))
213+
}
214+
202215
function put(state: ActiveState, path: string, entry: FileEntryState): ActiveState {
203216
return { ...state, files: { ...state.files, [path]: entry } }
204217
}

‎packages/app/src/workspaces/files/model.tsx‎

Lines changed: 43 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import { usePluginAttachment } from "@/runtime/plugin/host-apis"
1313
import { createPathHelpers } from "./path"
1414
import { artifactKind, artifactMime } from "@opencode/util/artifact"
1515
import { usePlatform } from "@/runtime/platform/platform"
16-
import { fileStreamUrl, machineFileStreamUrl } from "@/runtime/server/api"
16+
import { fileStreamUrl, machineFileStreamUrl, serverRelativeUrl } from "@/runtime/server/api"
1717
import { fileContentFromBytes, headStreamedFile, streamedFileContent, streamedKinds } from "./artifact"
1818
import { approxBytes, createFileContentCache } from "./content-cache"
1919
import {
@@ -225,7 +225,8 @@ export const { use: useFile, provider: FileProvider, context: FileContext } = cr
225225

226226
// Media plays from the server's ranged reads, so only a HEAD runs here, for the file's size. A failed HEAD has no
227227
// body; the full read that follows reports the server's error. The API's request queue bounds the download's wait
228-
// for a response, and its body may take as long as it needs. A file on a paired machine reads through the server.
228+
// for a response, and its body may take as long as it needs. A file on a paired machine reads through the server,
229+
// which with a password streams it from a URL carrying a ticket for that path; one it fails to issue downloads.
229230
const read = (file: string, request: { path: string; location: { directory: string } }, signal: AbortSignal) => {
230231
const machine = isMachinePath(file)
231232

@@ -235,17 +236,48 @@ export const { use: useFile, provider: FileProvider, context: FileContext } = cr
235236
: serverSDK.api.file.read(request, { signal })
236237
).then((data) => fileContentFromBytes(file, data))
237238

238-
const url = !streamedKinds.has(artifactKind(file))
239-
? undefined
240-
: machine
241-
? machineFileStreamUrl(serverSDK.http, file)
242-
: fileStreamUrl(serverSDK.http, { path: request.path, directory: request.location.directory })
239+
// When the URL's ticket expires, a minute early so a load near the end still gets a working one.
240+
let expires: number | undefined
243241

244-
if (!url) return download()
242+
const streamUrl = (): Promise<string | undefined> => {
243+
if (!streamedKinds.has(artifactKind(file))) return Promise.resolve(undefined)
245244

246-
return headStreamedFile(platform.fetch ?? fetch, url, signal).then((response) =>
247-
response.ok ? streamedFileContent(file, url, response) : download(),
248-
)
245+
if (!machine)
246+
return Promise.resolve(
247+
fileStreamUrl(serverSDK.http, { path: request.path, directory: request.location.directory }),
248+
)
249+
250+
if (!serverSDK.http.password) return Promise.resolve(machineFileStreamUrl(serverSDK.http, file))
251+
252+
return serverSDK.api.experimental.machine.file.ticket({ path: file }, { signal }).then(
253+
(ticket) => {
254+
expires = ticket.expires === undefined ? undefined : ticket.expires - 60_000
255+
256+
return serverRelativeUrl(serverSDK.http, ticket.url)
257+
},
258+
() => undefined,
259+
)
260+
}
261+
262+
return streamUrl().then((url) => {
263+
if (!url) return download()
264+
265+
return headStreamedFile(platform.fetch ?? fetch, url, signal).then((response) => {
266+
if (!response.ok) return download()
267+
268+
const content = streamedFileContent(file, url, response)
269+
270+
// A ticketed URL stops working when its ticket expires, so the content goes stale then: the next load reads
271+
// it again with a new ticket.
272+
if (expires !== undefined)
273+
setTimeout(
274+
() => dispatch({ type: "content.expired", path: file, content }),
275+
Math.max(0, expires - Date.now()),
276+
)
277+
278+
return content
279+
})
280+
})
249281
}
250282

251283
// Built-in and virtual skills register `skill://` (or legacy `/builtin/`) paths.

‎packages/client/src/effect/api/api.ts‎

Lines changed: 8 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/client/src/effect/generated/client.ts‎

Lines changed: 19 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/client/src/promise/generated/client.ts‎

Lines changed: 15 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/client/src/promise/generated/types.ts‎

Lines changed: 7 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)