opencode_offline/packages/function/src/api.ts

228 lines
6.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-07-03 21:58:25 +08:00
WEB_DOMAIN: string
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()
2025-06-19 04:20:05 +08:00
Array.from(data.entries())
.filter(([key, _]) => key.startsWith("session/"))
.map(([key, content]) => 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-07-02 06:57:08 +08:00
async publish(key: string, content: any) {
2025-05-31 01:58:46 +08:00
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-10 11:07:29 +08:00
public async getData() {
2025-06-08 13:17:54 +08:00
const data = await this.ctx.storage.list()
2025-06-19 04:20:05 +08:00
return Array.from(data.entries())
.filter(([key, _]) => key.startsWith("session/"))
.map(([key, content]) => ({ key, content }))
2025-06-08 13:17:54 +08:00
}
2025-07-02 06:57:08 +08:00
public async assertSecret(secret: string) {
if (secret !== (await this.getSecret())) throw new Error("Invalid secret")
}
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-07-02 06:57:08 +08:00
async clear() {
const sessionID = await this.getSessionID()
const list = await this.env.Bucket.list({
prefix: `session/message/${sessionID}/`,
limit: 1000,
})
for (const item of list.objects) {
await this.env.Bucket.delete(item.key)
}
await this.env.Bucket.delete(`session/info/${sessionID}`)
2025-05-24 12:27:52 +08:00
await this.ctx.storage.deleteAll()
}
2025-05-31 01:58:46 +08:00
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,
2025-07-03 21:58:25 +08:00
url: `https://${env.WEB_DOMAIN}/s/${short}`,
2025-05-31 01:58:46 +08:00
}),
{
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-07-02 06:57:08 +08:00
await stub.assertSecret(secret)
await stub.clear()
return new Response(JSON.stringify({}), {
headers: { "Content-Type": "application/json" },
})
}
if (request.method === "POST" && method === "share_delete_admin") {
const id = env.SYNC_SERVER.idFromName("oVF8Rsiv")
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" },
})
}
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-07-02 06:57:08 +08:00
await stub.assertSecret(body.secret)
await stub.publish(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
2025-06-10 11:07:29 +08:00
if (request.method === "GET" && method === "share_data") {
2025-06-08 13:17:54 +08:00
const id = url.searchParams.get("id")
2025-06-10 11:07:29 +08:00
console.log("share_data", id)
2025-06-08 13:17:54 +08:00
if (!id)
return new Response("Error: Share ID is required", { status: 400 })
const stub = env.SYNC_SERVER.get(env.SYNC_SERVER.idFromName(id))
2025-06-10 11:07:29 +08:00
const data = await stub.getData()
2025-06-10 11:37:32 +08:00
2025-06-10 11:07:29 +08:00
let info
2025-06-10 11:37:32 +08:00
const messages: Record<string, any> = {}
2025-06-10 11:07:29 +08:00
data.forEach((d) => {
const [root, type, ...splits] = d.key.split("/")
if (root !== "session") return
if (type === "info") {
info = d.content
return
}
if (type === "message") {
const [, messageID] = splits
messages[messageID] = d.content
}
})
2025-06-10 11:37:32 +08:00
return new Response(
JSON.stringify({
info,
messages,
}),
{
headers: { "Content-Type": "application/json" },
},
)
2025-06-08 13:17:54 +08:00
}
2025-05-24 02:17:45 +08:00
},
}