Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(uWebSockets): Add persistedRequest to context extra and deprecate uWS's stack allocated request #196

Merged
merged 5 commits into from
Jun 3, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
51 changes: 51 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -769,6 +769,57 @@ wsServer.on('connection', (socket, request) => {

</details>

<details id="uws-auth-handling">
<summary><a href="#uws-auth-handling">🔗</a> Server usage with <a href="https://github.com/uNetworking/uWebSockets.js">uWebSockets.js</a> and custom auth handling</summary>
enisdenjo marked this conversation as resolved.
Show resolved Hide resolved

```typescript
import uWS from 'uWebSockets.js'; // yarn add uWebSockets.js@uNetworking/uWebSockets.js#<tag>
import cookie from 'cookie';
import { makeBehavior, Request } from 'graphql-ws/lib/use/uWebSockets';
import { schema } from './my-graphql-schema';
import { validate } from './my-auth';

// your custom auth
class Forbidden extends Error {}
function handleAuth(request: Request) {
// do your auth on every subscription connect
const good = validate(request.headers['authorization']);
// or const { iDontApprove } = session(cookie.parse(request.headers.cookie));
if (!good) {
// throw a custom error to be handled
throw new Forbidden(':(');
}
}

uWS
.App()
.ws(
'/graphql',
makeBehavior({
schema,
onConnect: async (ctx) => {
// do your auth on every connect
await handleAuth(ctx.extra.request);
},
onSubscribe: async (ctx) => {
// or maybe on every subscribe
await handleAuth(ctx.extra.request);
},
onNext: async (ctx) => {
// haha why not on every result emission?
await handleAuth(ctx.extra.request);
},
}),
)
.listen(4000, (listenSocket) => {
if (listenSocket) {
console.log('Listening to port 4000');
}
});
```

</details>

<details id="express">
<summary><a href="#express">🔗</a> <a href="https://github.com/websockets/ws">ws</a> server usage with <a href="https://github.com/graphql/express-graphql">Express GraphQL</a></summary>

Expand Down
5 changes: 3 additions & 2 deletions src/tests/use.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,9 @@ for (const { tServer, startTServer } of tServers) {
expect((ctx.extra as UWSExtra).socket.constructor.name).toEqual(
'uWS.WebSocket',
);
expect((ctx.extra as UWSExtra).request.constructor.name).toEqual(
'uWS.HttpRequest',
expect((ctx.extra as UWSExtra).request).toBeInstanceOf(Object);
expect((ctx.extra as UWSExtra).request.headers).toBeInstanceOf(
Object,
);
} else if (tServer === 'ws') {
expect((ctx.extra as WSExtra).socket).toBeInstanceOf(ws);
Expand Down
31 changes: 21 additions & 10 deletions src/use/uWebSockets.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type * as uWS from 'uWebSockets.js';
import type http from 'http';
import { makeServer, ServerOptions } from '../server';

/**
Expand All @@ -10,12 +11,16 @@ export interface Extra {
/**
* The actual socket connection between the server and the client.
*/
readonly socket: uWS.WebSocket;
readonly socket: uWS.WebSocket & { upgradeReq: Request };
enisdenjo marked this conversation as resolved.
Show resolved Hide resolved
/**
* The initial HTTP request before the actual
* socket and connection is established.
*/
readonly request: uWS.HttpRequest;
readonly request: Request;
}

export interface Request {
headers: http.IncomingHttpHeaders;
enisdenjo marked this conversation as resolved.
Show resolved Hide resolved
}

interface Client {
Expand Down Expand Up @@ -70,18 +75,25 @@ export function makeBehavior<
upgrade(...args) {
behavior.upgrade?.(...args);
const [res, req, context] = args;
const upgradeReq: Request = {
headers: {},
};

req.forEach((key, value) => {
upgradeReq.headers[key] = value;
});

res.upgrade(
{ upgradeReq: req },
req.getHeader('sec-websocket-key'),
req.getHeader('sec-websocket-protocol'),
req.getHeader('sec-websocket-extensions'),
{ upgradeReq },
upgradeReq.headers['sec-websocket-key'] || '',
upgradeReq.headers['sec-websocket-protocol'] || '',
upgradeReq.headers['sec-websocket-extensions'] || '',
context,
);
},
open(...args) {
behavior.open?.(...args);
const [socket] = args;
const socket = args[0] as uWS.WebSocket & { upgradeReq: Request };

// prepare client object
const client: Client = {
Expand All @@ -95,10 +107,9 @@ export function makeBehavior<
},
};

const request = socket.upgradeReq as uWS.HttpRequest;
client.closed = server.opened(
{
protocol: request.getHeader('sec-websocket-protocol'),
protocol: socket.upgradeReq.headers['sec-websocket-protocol'] || '',
send: async (message) => {
// the socket might have been destroyed in the meantime
if (!clients.has(socket)) return;
Expand All @@ -115,7 +126,7 @@ export function makeBehavior<
},
onMessage: (cb) => (client.handleMessage = cb),
},
{ socket, request } as Extra & Partial<E>,
{ socket, request: socket.upgradeReq } as Extra & Partial<E>,
);

if (keepAlive > 0 && isFinite(keepAlive)) {
Expand Down