Skip to content

Commit

Permalink
feat: implement hono and cleanup peer server DO
Browse files Browse the repository at this point in the history
  • Loading branch information
dallen4 committed Sep 2, 2024
1 parent 8ef7e6a commit 762b0b1
Show file tree
Hide file tree
Showing 8 changed files with 155 additions and 137 deletions.
3 changes: 3 additions & 0 deletions worker/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,8 @@
"@cloudflare/workers-types": "^4.20231121.0",
"typescript": "^5.0.4",
"wrangler": "^3.0.0"
},
"dependencies": {
"hono": "^4.5.9"
}
}
20 changes: 20 additions & 0 deletions worker/src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export enum AppHeaders {
ContentType = 'content-type',
IpAddress = 'cf-connecting-ip',
}

export enum ContentType {
Plaintext = 'text/plain',
FormData = 'application/x-www-form-urlencoded',
Json = 'application/json',
}

export enum PeerJsRoutes {
Index = '/',
PeerJs = '/peerjs',
GenerateId = '/peerjs/id',
}

export enum DeadropRoutes {
Drop = '/drop',
}
95 changes: 24 additions & 71 deletions worker/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,82 +1,35 @@
const WELCOME_TEXT =
'{"name":"PeerJS Server","description":"A server side element to broker connections between PeerJS clients.","website":"https://peerjs.com/"}';
const HEARTBEAT = '{"type":"HEARTBEAT"}';
const OPEN = '{"type":"OPEN"}';
const ID_TAKEN =
'{"type":"ID-TAKEN","payload":{"msg":"ID is taken"}}';
import { PeerServerDO } from './lib/durable_objects';
import { cors, tracing } from './lib/middleware';
import { hono } from './lib/http/core';
import { PeerJsRoutes } from './constants';

export class PeerServerDO implements DurableObject {
constructor(private state: DurableObjectState, private env: Env) {
this.state.setWebSocketAutoResponse(
new WebSocketRequestResponsePair(HEARTBEAT, HEARTBEAT),
);
}
const WELCOME_TEXT = JSON.stringify({
name: 'PeerJS Server',
description:
'A server side element to broker connections between PeerJS clients.',
website: 'https://peerjs.com/',
});

async fetch(request: Request) {
const url = new URL(request.url);
const app = hono();

const id = url.searchParams.get('id');
const token = url.searchParams.get('token');
app.use(cors());
app.use(tracing());

if (!id || !token) return new Response(null, { status: 400 });
app.get(PeerJsRoutes.Index, (c) => c.text(WELCOME_TEXT));

const [wsclient, wsserver] = Object.values(new WebSocketPair());
app.get(PeerJsRoutes.PeerJs, (c) => {
const url = new URL(c.req.url);

const existingWss = this.state.getWebSockets(id);
const objId = c.env.PEER_SERVER.idFromName(url.host);
const stub = c.env.PEER_SERVER.get(objId);

if (
existingWss.length > 0 &&
existingWss[0].deserializeAttachment().token !== token
) {
wsserver.accept();
wsserver.send(ID_TAKEN);
wsserver.close(1008, 'ID is taken');
return new Response(null, { webSocket: wsclient, status: 101 });
} else {
existingWss.forEach((ws) => ws.close(1000));
}
return stub.fetch(c.req.raw);
});

this.state.acceptWebSocket(wsserver, [id]);
wsserver.serializeAttachment({ id, token });
wsserver.send(OPEN);

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

webSocketMessage(
ws: WebSocket,
message: string,
): void | Promise<void> {
const msg = JSON.parse(message);
const dstWs = this.state.getWebSockets(msg.dst)[0];

msg.src = ws.deserializeAttachment().id;

dstWs.send(JSON.stringify(msg));
}
}
app.get(PeerJsRoutes.GenerateId, (c) => c.text(crypto.randomUUID()));

export default {
async fetch(request: Request, env: Env) {
const url = new URL(request.url);

switch (url.pathname) {
case '/':
return new Response(WELCOME_TEXT);
case '/peerjs':
let objId = env.PEER_SERVER.idFromName(url.host);
let stub = env.PEER_SERVER.get(objId);
return stub.fetch(request);
case '/peerjs/id':
return new Response(crypto.randomUUID(), {
status: 200,
headers: {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*',
},
});
default:
return new Response(null, { status: 404 });
}
},
fetch: app.fetch,
};

export { PeerServerDO };
57 changes: 57 additions & 0 deletions worker/src/lib/durable_objects.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
const HEARTBEAT = JSON.stringify({ type: 'HEARTBEAT' });
const OPEN = JSON.stringify({ type: 'OPEN' });
const ID_TAKEN = JSON.stringify({
type: 'ID-TAKEN',
payload: { msg: 'ID is taken' },
});

export class PeerServerDO implements DurableObject {
constructor(private state: DurableObjectState, private env: Env) {
this.state.setWebSocketAutoResponse(
new WebSocketRequestResponsePair(HEARTBEAT, HEARTBEAT),
);
}

async fetch(request: Request) {
const url = new URL(request.url);

const id = url.searchParams.get('id');
const token = url.searchParams.get('token');

if (!id || !token) return new Response(null, { status: 400 });

const [wsclient, wsserver] = Object.values(new WebSocketPair());

const existingWss = this.state.getWebSockets(id);

if (
existingWss.length > 0 &&
existingWss[0].deserializeAttachment().token !== token
) {
wsserver.accept();
wsserver.send(ID_TAKEN);
wsserver.close(1008, 'ID is taken');
return new Response(null, { webSocket: wsclient, status: 101 });
} else {
existingWss.forEach((ws) => ws.close(1000));
}

this.state.acceptWebSocket(wsserver, [id]);
wsserver.serializeAttachment({ id, token });
wsserver.send(OPEN);

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

webSocketMessage(
ws: WebSocket,
message: string,
): void | Promise<void> {
const msg = JSON.parse(message);
const dstWs = this.state.getWebSockets(msg.dst)[0];

msg.src = ws.deserializeAttachment().id;

dstWs.send(JSON.stringify(msg));
}
}
14 changes: 14 additions & 0 deletions worker/src/lib/http/core.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { Hono, MiddlewareHandler } from 'hono';

export type HonoCtx = {
Bindings: Env;
Variables: {
requestId: string;
ipAddress?: string;
error?: boolean;
};
};

export type Middleware = MiddlewareHandler<HonoCtx>;

export const hono = () => new Hono<HonoCtx>();
24 changes: 24 additions & 0 deletions worker/src/lib/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { cors as baseCors } from 'hono/cors';
import { AppHeaders } from '../constants';
import { Middleware } from './http/core';

export const tracing = (): Middleware => async (c, next) => {
c.set('requestId', crypto.randomUUID());

const ipAddress = c.req.header(AppHeaders.IpAddress)! as string;
c.set('ipAddress', ipAddress);

await next();
};

export const cors = (): Middleware =>
baseCors({
origin: [
'https://deadrop.io',
'https://*nieky-allens-projects.vercel.app',
'https://*nieky.vercel.app',
],
allowHeaders: ['Content-Type', 'Authorization', 'Set-Cookie'],
allowMethods: ['GET', 'HEAD', 'OPTIONS'],
credentials: true,
});
74 changes: 8 additions & 66 deletions worker/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,30 +1,21 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"paths": {
"@shared/*": ["../shared/*"]
},

/* Visit https://aka.ms/tsconfig.json to read more about this file */

/* Projects */
// "incremental": true, /* Enable incremental compilation */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
"incremental": true /* Enable incremental compilation */,

/* Language and Environment */
"target": "es2021" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
"lib": [
"es2021"
] /* Specify a set of bundled library declaration files that describe the target runtime environment. */,
"jsx": "react" /* Specify what JSX code is generated. */,
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
// "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */

/* Modules */
"module": "es2022" /* Specify what module code is generated. */,
// "rootDir": "./", /* Specify the root folder within your source files. */
Expand All @@ -36,70 +27,21 @@
"types": [
"@cloudflare/workers-types"
] /* Specify type package names to be included without being referenced in a source file. */,
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
"resolveJsonModule": true /* Enable importing .json files */,
// "noResolve": true, /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */

/* JavaScript Support */
"allowJs": true /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */,
"checkJs": false /* Enable error reporting in type-checked JavaScript files. */,
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */

/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
"allowJs": false /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */,
"noEmit": true /* Disable emitting files from a compilation. */,
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

/* Interop Constraints */
"isolatedModules": true /* Ensure that each file can be safely transpiled without relying on other imports. */,
"allowSyntheticDefaultImports": true /* Allow 'import x from y' when a module doesn't have a default export. */,
// "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */,
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */,
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,

/* Type Checking */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied `any` type.. */
// "strictNullChecks": true, /* When type checking, take into account `null` and `undefined`. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when `this` is given the type `any`. */
// "useUnknownInCatchVariables": true, /* Type catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when a local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */

/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
}
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6337,6 +6337,11 @@ hoist-non-react-statics@^3.3.1, hoist-non-react-statics@^3.3.2:
dependencies:
react-is "^16.7.0"

hono@^4.5.9:
version "4.5.9"
resolved "https://registry.yarnpkg.com/hono/-/hono-4.5.9.tgz#2627c55c4c97ae826973dddac857ba4476fde6c6"
integrity sha512-zz8ktqMDRrZETjxBrv8C5PQRFbrTRCLNVAjD1SNQyOzv4VjmX68Uxw83xQ6oxdAB60HiWnGEatiKA8V3SZLDkQ==

[email protected]:
version "1.2.0"
resolved "https://registry.yarnpkg.com/html-dom-parser/-/html-dom-parser-1.2.0.tgz#8f689b835982ffbf245eda99730e92b8462c111e"
Expand Down

0 comments on commit 762b0b1

Please sign in to comment.