Skip to content

Commit

Permalink
Add websocket handler
Browse files Browse the repository at this point in the history
Signed-off-by: Marcos Candeia <[email protected]>
  • Loading branch information
mcandeia committed Dec 2, 2024
1 parent a99a82d commit 8ca66d5
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 15 deletions.
15 changes: 4 additions & 11 deletions examples/cf/counter-actor/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion examples/cf/counter-actor/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"wrangler": "^3.91.0"
},
"dependencies": {
"@deco/actors": "npm:@jsr/deco__actors@^0.14.0-beta.7",
"@deco/actors": "npm:@jsr/deco__actors@^0.14.0-beta.8",
"hono": "^4.6.12"
}
}
12 changes: 11 additions & 1 deletion examples/cf/counter-actor/src/counter.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ActorState } from "@deco/actors";
import { WatchTarget } from "@deco/actors/watch";
import { ChannelUpgrader, WatchTarget } from "@deco/actors/watch";

export class Counter {
private count: number;
Expand Down Expand Up @@ -34,4 +34,14 @@ export class Counter {
watch(): AsyncIterableIterator<number> {
return this.watchTarget.subscribe();
}
chan(name: string): ChannelUpgrader<string, string> {
return (async ({ send, recv }) => {
await send(`Hello ${name}`);
for await (const str of recv()) {
if (str === "PING") {
await send("PONG");
}
}
});
}
}
6 changes: 5 additions & 1 deletion examples/cf/counter-actor/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@ export { ActorDurableObject } from "@deco/actors/cf";
const app = new Hono<{ Bindings: Env }>();

const runtime = new ActorCfRuntime([Counter]);
app.use(withActors(runtime));
const mid = withActors(runtime)
app.use(async (ctx, next) => {
await mid(ctx, next);
console.log(await ctx.res.text())
});

app.get("/", (c) => c.text("Hello Cloudflare Workers!"));

Expand Down
13 changes: 12 additions & 1 deletion src/actors/runtimes/cf/fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,18 @@ export interface Env {

export class ActorCfRuntime implements ActorFetcher<Env> {
constructor(protected actorsConstructors: Array<ActorConstructor>) {
registerActors(actorsConstructors);
registerActors(actorsConstructors, () => {
const webSocketPair = new WebSocketPair();
const [client, server] = Object.values(webSocketPair);
return {
socket: server,
response: new Response(null, {
status: 101,
// @ts-ignore: webSocket is not part of the Response type
webSocket: client,
}),
};
});
}
fetch(request: Request, env?: Env | undefined): Promise<Response> | Response {
if (!env) {
Expand Down

0 comments on commit 8ca66d5

Please sign in to comment.