opencode/app/packages/function/src/api.ts

175 lines
5.1 KiB
TypeScript
Raw Normal View History

2025-05-24 02:17:45 +08:00
import { DurableObject } from "cloudflare:workers"
2025-05-24 12:27:52 +08:00
import { randomUUID } from "node:crypto"
2025-05-24 02:17:45 +08:00
import { Resource } from "sst"
type Bindings = {
2025-05-24 04:41:16 +08:00
SYNC_SERVER: DurableObjectNamespace
2025-05-24 02:17:45 +08:00
}
export class SyncServer extends DurableObject {
private files: Map<string, string> = new Map()
2025-05-24 12:27:52 +08:00
private shareID?: string
2025-05-24 02:17:45 +08:00
2025-05-24 04:41:16 +08:00
constructor(ctx: DurableObjectState, env: Bindings) {
2025-05-24 02:17:45 +08:00
super(ctx, env)
this.ctx.blockConcurrencyWhile(async () => {
this.files = await this.ctx.storage.list()
})
}
async fetch(req: Request) {
console.log("SyncServer subscribe")
const webSocketPair = new WebSocketPair()
const [client, server] = Object.values(webSocketPair)
this.ctx.acceptWebSocket(server)
setTimeout(() => {
2025-05-24 02:40:28 +08:00
this.files.forEach((content, key) =>
server.send(JSON.stringify({ key, content })),
2025-05-24 02:17:45 +08:00
)
}, 0)
return new Response(null, {
status: 101,
webSocket: client,
})
}
2025-05-24 12:27:52 +08:00
async webSocketMessage(ws, message) {}
async webSocketClose(ws, code, reason, wasClean) {
ws.close(code, "Durable Object is closing WebSocket")
}
async publish(key: string, content: string) {
this.files.set(key, content)
await this.ctx.storage.put(key, content)
const clients = this.ctx.getWebSockets()
console.log("SyncServer publish", key, "to", clients.length, "subscribers")
clients.forEach((client) => client.send(JSON.stringify({ key, content })))
}
async setShareID(shareID: string) {
this.shareID = shareID
}
async getShareID() {
return this.shareID
}
async clear() {
await this.ctx.storage.deleteAll()
this.files.clear()
}
2025-05-24 02:17:45 +08:00
}
export default {
async fetch(request: Request, env: Bindings, ctx: ExecutionContext) {
const url = new URL(request.url)
if (request.method === "GET" && url.pathname === "/") {
return new Response("Hello, world!", {
headers: { "Content-Type": "text/plain" },
})
}
if (request.method === "POST" && url.pathname.endsWith("/share_create")) {
const body = await request.json()
2025-05-24 04:14:03 +08:00
const sessionID = body.sessionID
2025-05-24 02:17:45 +08:00
2025-05-24 12:27:52 +08:00
// Get existing shareID
const id = env.SYNC_SERVER.idFromName(sessionID)
const stub = env.SYNC_SERVER.get(id)
let shareID = await stub.getShareID()
if (!shareID) {
shareID = randomUUID()
await stub.setShareID(shareID)
}
// Store session ID
await Resource.Bucket.put(`${shareID}/session/id`, sessionID)
2025-05-24 02:17:45 +08:00
2025-05-24 04:14:03 +08:00
return new Response(JSON.stringify({ shareID }), {
2025-05-24 02:17:45 +08:00
headers: { "Content-Type": "application/json" },
})
}
if (request.method === "POST" && url.pathname.endsWith("/share_delete")) {
const body = await request.json()
2025-05-24 04:14:03 +08:00
const sessionID = body.sessionID
const shareID = body.shareID
2025-05-24 12:27:52 +08:00
// Delete from bucket
await Resource.Bucket.delete(`${shareID}/session/id`)
// Delete from durable object
const id = env.SYNC_SERVER.idFromName(sessionID)
const stub = env.SYNC_SERVER.get(id)
await stub.clear()
2025-05-24 02:17:45 +08:00
return new Response(JSON.stringify({}), {
headers: { "Content-Type": "application/json" },
})
}
if (request.method === "POST" && url.pathname.endsWith("/share_sync")) {
const body = await request.json()
2025-05-24 04:14:03 +08:00
const sessionID = body.sessionID
const shareID = body.shareID
2025-05-24 12:27:52 +08:00
const key = body.key
2025-05-24 02:17:45 +08:00
const content = body.content
2025-05-24 02:40:28 +08:00
// validate key
2025-05-24 04:34:02 +08:00
if (
!key.startsWith(`session/info/${sessionID}`) &&
!key.startsWith(`session/message/${sessionID}/`)
)
2025-05-24 02:40:28 +08:00
return new Response("Error: Invalid key", { status: 400 })
2025-05-24 02:17:45 +08:00
2025-05-24 12:27:52 +08:00
const ret = await Resource.Bucket.get(`${shareID}/session/id`)
2025-05-24 02:17:45 +08:00
if (!ret)
return new Response("Error: Session not shared", { status: 400 })
// send message to server
const id = env.SYNC_SERVER.idFromName(sessionID)
const stub = env.SYNC_SERVER.get(id)
2025-05-24 02:40:28 +08:00
await stub.publish(key, content)
2025-05-24 02:17:45 +08:00
// store message
2025-05-24 12:27:52 +08:00
await Resource.Bucket.put(`${shareID}/${key}.json`, content)
2025-05-24 02:17:45 +08:00
return new Response(JSON.stringify({}), {
headers: { "Content-Type": "application/json" },
})
}
if (request.method === "GET" && url.pathname.endsWith("/share_poll")) {
// Expect to receive a WebSocket Upgrade request.
// If there is one, accept the request and return a WebSocket Response.
const upgradeHeader = request.headers.get("Upgrade")
if (!upgradeHeader || upgradeHeader !== "websocket") {
return new Response("Error: Upgrade header is required", {
status: 426,
})
}
// get query parameters
2025-05-24 04:14:03 +08:00
const shareID = url.searchParams.get("shareID")
2025-05-24 02:17:45 +08:00
if (!shareID)
return new Response("Error: Share ID is required", { status: 400 })
// Get session ID
2025-05-24 12:27:52 +08:00
const sessionID = await Resource.Bucket.get(`${shareID}/session/id`).then(
(res) => res?.text(),
)
console.log("sessionID", sessionID)
if (!sessionID)
2025-05-24 02:17:45 +08:00
return new Response("Error: Session not shared", { status: 400 })
// subscribe to server
const id = env.SYNC_SERVER.idFromName(sessionID)
const stub = env.SYNC_SERVER.get(id)
return stub.fetch(request)
}
},
}