From e39924ebb9ac3e6a4b13773a21246837feb7edde Mon Sep 17 00:00:00 2001 From: Sunil Pai Date: Fri, 14 Jun 2024 08:23:55 +0100 Subject: [PATCH] use DurableObject from cloudflare:workers Discovered that we can use cloudflare:workers if we add it to serverDependenciesToBundle in remix.config.js. Rewrote the ChatRoom DO to use that. --- app/durableObjects/ChatRoom.server.ts | 13 ++++--------- remix.config.js | 4 +++- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/app/durableObjects/ChatRoom.server.ts b/app/durableObjects/ChatRoom.server.ts index 854d2420..f112bcca 100644 --- a/app/durableObjects/ChatRoom.server.ts +++ b/app/durableObjects/ChatRoom.server.ts @@ -11,6 +11,8 @@ import { assertNonNullable } from '~/utils/assertNonNullable' import getUsername from '~/utils/getUsername.server' import { handleErrors } from '~/utils/handleErrors.server' +import { DurableObject } from 'cloudflare:workers' + type Session = { heartbeatTimeout: ReturnType | null webSocket?: WebSocket @@ -28,7 +30,7 @@ type Session = { // ChatRoom implements a Durable Object that coordinates an individual chat room. Participants // connect to the room using WebSockets, and the room broadcasts messages from each participant // to all others. -export class ChatRoom implements DurableObject { +export class ChatRoom extends DurableObject { /** * WebSocket objects for each client, along with some metadata */ @@ -42,15 +44,8 @@ export class ChatRoom implements DurableObject { lastTimestamp: number = 0 stateSyncInterval: ReturnType | null = null - // We'd like to use Cloudflare's fancy RPC Durable Objects - // but currently we can't figure out a way to mark cloudflare:workers - // as an external when remix compiles it. Until then, let's match the - // newer style member names .ctx and .env - ctx: DurableObjectState - env: Env constructor(ctx: DurableObjectState, env: Env) { - this.ctx = ctx - this.env = env + super(ctx, env) // check for previous sessions. this.ctx.blockConcurrencyWhile(async () => { this.sessions = (await this.ctx.storage.get('sessions')) ?? [] diff --git a/remix.config.js b/remix.config.js index d2473fcb..c5d23a18 100644 --- a/remix.config.js +++ b/remix.config.js @@ -4,7 +4,9 @@ module.exports = { ignoredRouteFiles: ['**/.*'], server: './server.ts', serverConditions: ['worker'], - serverDependenciesToBundle: [/^(?!__STATIC_CONTENT_MANIFEST).*$/], + serverDependenciesToBundle: [ + /^(?!__STATIC_CONTENT_MANIFEST|cloudflare:workers).*$/, + ], serverMainFields: ['browser', 'module', 'main'], serverMinify: true, serverModuleFormat: 'esm',