summaryrefslogtreecommitdiffhomepage
path: root/app/packages/function/src/api.ts
blob: efe0c5625d823394ba633263934472a1f6348f91 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import { DurableObject } from "cloudflare:workers"
import {
  DurableObjectNamespace,
  ExecutionContext,
} from "@cloudflare/workers-types"
import { createHash } from "node:crypto"
import path from "node:path"
import { Resource } from "sst"

type Bindings = {
  SYNC_SERVER: DurableObjectNamespace<WebSocketHibernationServer>
}

export class SyncServer extends DurableObject {
  private files: Map<string, string> = new Map()

  constructor(ctx, env) {
    super(ctx, env)
    this.ctx.blockConcurrencyWhile(async () => {
      this.files = await this.ctx.storage.list()
    })
  }

  async publish(key: string, content: string) {
    console.log(
      "SyncServer publish",
      key,
      content,
      "to",
      this.ctx.getWebSockets().length,
      "subscribers",
    )
    this.files.set(key, content)
    await this.ctx.storage.put(key, content)

    this.ctx.getWebSockets().forEach((client) => {
      client.send(JSON.stringify({ key, content }))
    })
  }

  async webSocketMessage(ws, message) {
    if (message === "load_history") {
    }
  }

  async webSocketClose(ws, code, reason, wasClean) {
    ws.close(code, "Durable Object is closing WebSocket")
  }

  async fetch(req: Request) {
    console.log("SyncServer subscribe")

    // Creates two ends of a WebSocket connection.
    const webSocketPair = new WebSocketPair()
    const [client, server] = Object.values(webSocketPair)

    this.ctx.acceptWebSocket(server)

    setTimeout(() => {
      this.files.forEach((content, key) =>
        server.send(JSON.stringify({ key, content })),
      )
    }, 0)

    return new Response(null, {
      status: 101,
      webSocket: client,
    })
  }
}

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()
      const sessionID = body.session_id
      const shareID = createHash("sha256").update(sessionID).digest("hex")
      const infoFile = `${shareID}/info/${sessionID}.json`
      const ret = await Resource.Bucket.get(infoFile)
      if (ret)
        return new Response("Error: Session already sharing", { status: 400 })

      await Resource.Bucket.put(infoFile, "")

      return new Response(JSON.stringify({ share_id: shareID }), {
        headers: { "Content-Type": "application/json" },
      })
    }
    if (request.method === "POST" && url.pathname.endsWith("/share_delete")) {
      const body = await request.json()
      const sessionID = body.session_id
      const shareID = body.share_id
      const infoFile = `${shareID}/info/${sessionID}.json`
      await Resource.Bucket.delete(infoFile)
      return new Response(JSON.stringify({}), {
        headers: { "Content-Type": "application/json" },
      })
    }
    if (request.method === "POST" && url.pathname.endsWith("/share_sync")) {
      const body = await request.json()
      const sessionID = body.session_id
      const shareID = body.share_id
      const key = body.key
      const content = body.content

      // validate key
      if (!key.startsWith("info/") && !key.startsWith("message/"))
        return new Response("Error: Invalid key", { status: 400 })

      const infoFile = `${shareID}/info/${sessionID}.json`
      const ret = await Resource.Bucket.get(infoFile)
      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)
      await stub.publish(key, content)

      // store message
      await Resource.Bucket.put(`${shareID}/${key}`, content)

      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
      const shareID = url.searchParams.get("share_id")
      if (!shareID)
        return new Response("Error: Share ID is required", { status: 400 })

      // Get session ID
      const listRet = await Resource.Bucket.list({
        prefix: `${shareID}/info/`,
        delimiter: "/",
      })

      if (listRet.objects.length === 0)
        return new Response("Error: Session not shared", { status: 400 })
      if (listRet.objects.length > 1)
        return new Response("Error: Multiple sessions found", { status: 400 })
      const sessionID = path.parse(listRet.objects[0].key).name

      // subscribe to server
      const id = env.SYNC_SERVER.idFromName(sessionID)
      const stub = env.SYNC_SERVER.get(id)
      return stub.fetch(request)
    }
  },
}