-
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #24 from sor4chi/feat/hibernation-websocket-example
feat: Hibernation Websocket API example
- Loading branch information
Showing
9 changed files
with
244 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
``` | ||
npm install | ||
npm run dev | ||
``` | ||
|
||
``` | ||
npm run deploy | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
{ | ||
"name": "hono-do-example-hibernatable-chat", | ||
"private": true, | ||
"version": "0.0.0", | ||
"scripts": { | ||
"lint": "eslint --fix --ext .ts,.tsx src", | ||
"lint:check": "eslint --ext .ts,.tsx src", | ||
"format": "prettier --write \"src/**/*.{ts,tsx}\"", | ||
"format:check": "prettier --check \"src/**/*.{ts,tsx}\"", | ||
"dev": "wrangler dev src/index.ts", | ||
"deploy": "wrangler deploy --minify src/index.ts" | ||
}, | ||
"dependencies": { | ||
"hono": "^3.6.0", | ||
"hono-do": "workspace:*" | ||
}, | ||
"devDependencies": { | ||
"@cloudflare/workers-types": "^4.20230821.0", | ||
"wrangler": "^3.7.0" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
import { generateHonoObject } from "hono-do"; | ||
|
||
function uuidv4() { | ||
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { | ||
const r = (Math.random() * 16) | 0, | ||
v = c == "x" ? r : (r & 0x3) | 0x8; | ||
return v.toString(16); | ||
}); | ||
} | ||
|
||
declare module "hono-do" { | ||
interface HonoObjectVars { | ||
messages: { | ||
timestamp: string; | ||
text: string; | ||
}[]; | ||
} | ||
} | ||
|
||
export const Chat = generateHonoObject("/chat", (app, state, vars) => { | ||
vars.messages = []; | ||
|
||
app.get("/messages", async (c) => c.json(vars.messages)); | ||
|
||
app.get("/websocket", async (c) => { | ||
if (c.req.header("Upgrade") === "websocket") { | ||
return await handleWebSocketUpgrade(); | ||
} | ||
return c.text("Not found", 404); | ||
}); | ||
|
||
async function handleWebSocketUpgrade() { | ||
const [client, server] = Object.values(new WebSocketPair()); | ||
const clientId = uuidv4(); | ||
state.acceptWebSocket(server); | ||
|
||
server.serializeAttachment({ clientId }); | ||
|
||
return new Response(null, { status: 101, webSocket: client }); | ||
} | ||
}); | ||
|
||
Chat.webSocketMessage(async (webSocket, msg, state, vars) => { | ||
const { clientId: senderClientId } = await webSocket.deserializeAttachment(); | ||
state.getWebSockets().forEach((ws) => { | ||
const { clientId } = ws.deserializeAttachment(); | ||
if (clientId === senderClientId) { | ||
return; | ||
} | ||
|
||
try { | ||
vars.messages.push(JSON.parse(msg.toString())); | ||
ws.send(msg.toString()); | ||
} catch (error) { | ||
ws.close(); | ||
} | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
import { Hono } from "hono"; | ||
|
||
import { Template } from "./template"; | ||
|
||
const app = new Hono<{ | ||
Bindings: { | ||
CHAT: DurableObjectNamespace; | ||
}; | ||
}>(); | ||
|
||
app.get("/", (c) => { | ||
return c.html(Template); | ||
}); | ||
|
||
app.all("/chat/*", (c) => { | ||
const id = c.env.CHAT.idFromName("chat"); | ||
const obj = c.env.CHAT.get(id); | ||
return obj.fetch(c.req.raw); | ||
}); | ||
|
||
export default app; | ||
export * from "./chat"; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
export const Template = /*html*/ ` | ||
<!DOCTYPE html> | ||
<body> | ||
<input type="text" id="text_input" /><br/> | ||
<button id="send_button">Send</button> <br/> | ||
<div id="output_div"></div> | ||
<script type="text/javascript"> | ||
let currentWebSocket = null; | ||
const hostname = window.location.host; | ||
const protocol = window.location.protocol; | ||
const wsProtocol = protocol === "https:" ? "wss:" : "ws:"; | ||
const outputDiv = document.getElementById('output_div'); | ||
const sendButton = document.getElementById('send_button'); | ||
const textInput = document.getElementById('text_input'); | ||
async function getMessages() { | ||
const res = await fetch(protocol + "//" + hostname + "/chat/messages"); | ||
const messages = await res.json(); | ||
return messages; | ||
} | ||
function insertMessage(message) { | ||
const span = document.createElement("span"); | ||
span.innerText = message.timestamp + ": "; | ||
const p = document.createElement("p"); | ||
p.innerText = message.text; | ||
p.prepend(span); | ||
outputDiv.appendChild(p); | ||
} | ||
window.onload = async () => { | ||
const messages = await getMessages(); | ||
messages.forEach(insertMessage); | ||
} | ||
function join() { | ||
const ws = new WebSocket(wsProtocol + "//" + hostname + "/chat/websocket"); | ||
let rejoined = false; | ||
const startTime = Date.now(); | ||
ws.addEventListener("open", event => { | ||
currentWebSocket = ws; | ||
}); | ||
ws.addEventListener("message", event => { | ||
insertMessage(JSON.parse(event.data)); | ||
}); | ||
ws.addEventListener("close", event => { | ||
console.log("WebSocket closed, reconnecting:", event.code, event.reason); | ||
rejoin(); | ||
}); | ||
ws.addEventListener("error", event => { | ||
console.log("WebSocket error, reconnecting:", event); | ||
rejoin(); | ||
}); | ||
const rejoin = async () => { | ||
if (!rejoined) { | ||
rejoined = true; | ||
currentWebSocket = null; | ||
let timeSinceLastJoin = Date.now() - startTime; | ||
if (timeSinceLastJoin < 5000) { | ||
await new Promise(resolve => setTimeout(resolve, 5000 - timeSinceLastJoin)); | ||
} | ||
join(); | ||
} | ||
} | ||
} | ||
sendButton.addEventListener("click", event => { | ||
const text = textInput.value; | ||
const now = new Date().toLocaleString("en-US", { hour: "numeric", minute: "numeric", hour12: true }); | ||
const message = { text, timestamp: now }; | ||
insertMessage(message); | ||
currentWebSocket.send(JSON.stringify(message)); | ||
textInput.value = ""; | ||
}); | ||
join(); | ||
</script> | ||
</body> | ||
</html> | ||
`.trim(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
{ | ||
"compilerOptions": { | ||
"target": "ESNext", | ||
"module": "ESNext", | ||
"moduleResolution": "node", | ||
"esModuleInterop": true, | ||
"strict": true, | ||
"lib": [ | ||
"esnext" | ||
], | ||
"types": [ | ||
"@cloudflare/workers-types" | ||
], | ||
"jsx": "react-jsx", | ||
"jsxImportSource": "hono/jsx" | ||
}, | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
name = "chat" | ||
compatibility_date = "2023-01-01" | ||
|
||
[durable_objects] | ||
bindings = [{ name = "CHAT", class_name = "Chat" }] | ||
|
||
[[migrations]] | ||
tag = "v1" | ||
new_classes = ["Chat"] |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.