opencode_offline/packages/function/src/api.ts

189 lines
5.6 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
2025-05-31 02:40:53 +08:00
type Env = {
2025-05-28 03:20:43 +08:00
SYNC_SERVER: DurableObjectNamespace<SyncServer>
2025-05-31 02:40:53 +08:00
Bucket: R2Bucket
2025-05-24 02:17:45 +08:00
}
2025-05-31 02:40:53 +08:00
export class SyncServer extends DurableObject<Env> {
constructor(ctx: DurableObjectState, env: Env) {
2025-05-31 01:58:46 +08:00
super(ctx, env)
}
async fetch() {
2025-05-24 02:17:45 +08:00
console.log("SyncServer subscribe")
const webSocketPair = new WebSocketPair()
const [client, server] = Object.values(webSocketPair)
this.ctx.acceptWebSocket(server)
2025-05-31 02:40:53 +08:00
const data = await this.ctx.storage.list()
for (const [key, content] of data.entries()) {
server.send(JSON.stringify({ key, content }))
}
2025-05-24 02:17:45 +08:00
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")
}
2025-05-31 01:58:46 +08:00
async publish(secret: string, key: string, content: any) {
if (secret !== (await this.getSecret())) throw new Error("Invalid secret")
const sessionID = await this.getSessionID()
if (
!key.startsWith(`session/info/${sessionID}`) &&
!key.startsWith(`session/message/${sessionID}/`)
)
return new Response("Error: Invalid key", { status: 400 })
// store message
2025-05-31 02:40:53 +08:00
await this.env.Bucket.put(`share/${key}.json`, JSON.stringify(content), {
httpMetadata: {
contentType: "application/json",
},
})
await this.ctx.storage.put(key, content)
2025-05-24 12:27:52 +08:00
const clients = this.ctx.getWebSockets()
console.log("SyncServer publish", key, "to", clients.length, "subscribers")
2025-05-31 02:40:53 +08:00
for (const client of clients) {
client.send(JSON.stringify({ key, content }))
}
2025-05-24 12:27:52 +08:00
}
2025-05-31 01:58:46 +08:00
public async share(sessionID: string) {
let secret = await this.getSecret()
if (secret) return secret
secret = randomUUID()
await this.ctx.storage.put("secret", secret)
await this.ctx.storage.put("sessionID", sessionID)
return secret
}
2025-06-08 13:17:54 +08:00
public async messages() {
const data = await this.ctx.storage.list()
const messages = []
for (const [key, content] of data.entries()) {
messages.push({ key, content })
}
return messages
}
2025-05-31 01:58:46 +08:00
private async getSecret() {
return this.ctx.storage.get<string>("secret")
2025-05-24 12:27:52 +08:00
}
2025-05-31 01:58:46 +08:00
private async getSessionID() {
return this.ctx.storage.get<string>("sessionID")
2025-05-24 12:27:52 +08:00
}
2025-05-31 01:58:46 +08:00
async clear(secret: string) {
await this.assertSecret(secret)
2025-05-24 12:27:52 +08:00
await this.ctx.storage.deleteAll()
}
2025-05-31 01:58:46 +08:00
private async assertSecret(secret: string) {
if (secret !== (await this.getSecret())) throw new Error("Invalid secret")
}
static shortName(id: string) {
return id.substring(id.length - 8)
}
2025-05-24 02:17:45 +08:00
}
export default {
2025-05-31 02:40:53 +08:00
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
2025-05-24 02:17:45 +08:00
const url = new URL(request.url)
2025-05-28 03:20:43 +08:00
const splits = url.pathname.split("/")
const method = splits[1]
2025-05-24 02:17:45 +08:00
2025-05-28 03:20:43 +08:00
if (request.method === "GET" && method === "") {
2025-05-24 02:17:45 +08:00
return new Response("Hello, world!", {
headers: { "Content-Type": "text/plain" },
})
}
2025-05-28 03:20:43 +08:00
if (request.method === "POST" && method === "share_create") {
const body = await request.json<any>()
2025-05-24 04:14:03 +08:00
const sessionID = body.sessionID
2025-05-31 01:58:46 +08:00
const short = SyncServer.shortName(sessionID)
const id = env.SYNC_SERVER.idFromName(short)
2025-05-24 12:27:52 +08:00
const stub = env.SYNC_SERVER.get(id)
2025-05-31 01:58:46 +08:00
const secret = await stub.share(sessionID)
return new Response(
JSON.stringify({
secret,
url: "https://dev.opencode.ai/s?id=" + short,
}),
{
headers: { "Content-Type": "application/json" },
},
)
2025-05-24 02:17:45 +08:00
}
2025-05-28 03:20:43 +08:00
if (request.method === "POST" && method === "share_delete") {
const body = await request.json<any>()
2025-05-24 04:14:03 +08:00
const sessionID = body.sessionID
2025-05-31 01:58:46 +08:00
const secret = body.secret
const id = env.SYNC_SERVER.idFromName(SyncServer.shortName(sessionID))
2025-05-24 12:27:52 +08:00
const stub = env.SYNC_SERVER.get(id)
2025-05-31 01:58:46 +08:00
await stub.clear(secret)
2025-05-24 02:17:45 +08:00
return new Response(JSON.stringify({}), {
headers: { "Content-Type": "application/json" },
})
}
2025-05-28 03:20:43 +08:00
if (request.method === "POST" && method === "share_sync") {
2025-05-31 01:58:46 +08:00
const body = await request.json<{
sessionID: string
secret: string
key: string
content: any
}>()
const name = SyncServer.shortName(body.sessionID)
const id = env.SYNC_SERVER.idFromName(name)
2025-05-24 02:17:45 +08:00
const stub = env.SYNC_SERVER.get(id)
2025-05-31 01:58:46 +08:00
await stub.publish(body.secret, body.key, body.content)
2025-05-24 02:17:45 +08:00
return new Response(JSON.stringify({}), {
headers: { "Content-Type": "application/json" },
})
}
2025-05-28 03:20:43 +08:00
if (request.method === "GET" && method === "share_poll") {
2025-05-24 02:17:45 +08:00
const upgradeHeader = request.headers.get("Upgrade")
if (!upgradeHeader || upgradeHeader !== "websocket") {
return new Response("Error: Upgrade header is required", {
status: 426,
})
}
2025-05-31 01:58:46 +08:00
const id = url.searchParams.get("id")
2025-05-31 02:40:53 +08:00
console.log("share_poll", id)
2025-05-31 01:58:46 +08:00
if (!id)
2025-05-27 06:54:11 +08:00
return new Response("Error: Share ID is required", { status: 400 })
2025-05-31 01:58:46 +08:00
const stub = env.SYNC_SERVER.get(env.SYNC_SERVER.idFromName(id))
2025-05-24 02:17:45 +08:00
return stub.fetch(request)
}
2025-06-08 13:17:54 +08:00
if (request.method === "GET" && method === "share_messages") {
const id = url.searchParams.get("id")
console.log("share_messages", id)
if (!id)
return new Response("Error: Share ID is required", { status: 400 })
const stub = env.SYNC_SERVER.get(env.SYNC_SERVER.idFromName(id))
const messages = await stub.messages()
return new Response(JSON.stringify({ messages }), {
headers: { "Content-Type": "application/json" },
})
}
2025-05-24 02:17:45 +08:00
},
}