-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathReactiveSocketRouter.ts
More file actions
163 lines (139 loc) · 4.75 KB
/
ReactiveSocketRouter.ts
File metadata and controls
163 lines (139 loc) · 4.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
/**
* This is a small Router wrapper which uses the RSocket lib
* to expose reactive websocket stream in an interface similar to
* other journey micro routers.
*/
import * as micro from '@journeyapps-platform/micro';
import * as http from 'http';
import { Payload, RSocketServer } from 'rsocket-core';
import * as ws from 'ws';
import { SocketRouterObserver } from './SocketRouterListener.js';
import {
CommonParams,
IReactiveStream,
IReactiveStreamInput,
RS_ENDPOINT_TYPE,
ReactiveSocketRouterOptions,
SocketResponder
} from './types.js';
import { WebsocketServerTransport } from './transport/WebSocketServerTransport.js';
export class ReactiveSocketRouter<C> {
constructor(protected options?: ReactiveSocketRouterOptions<C>) {}
reactiveStream<I, O>(path: string, stream: IReactiveStreamInput<I, O, C>): IReactiveStream<I, O, C> {
return {
...stream,
type: RS_ENDPOINT_TYPE.STREAM,
path: path
};
}
/**
* Apply a set of subscriptions to a raw http server. The specified path is used to tell
* the server on which path it should handle WebSocket upgrades
*/
applyWebSocketEndpoints<I>(server: http.Server, params: CommonParams<C>) {
/**
* Use upgraded connections from the existing server.
* This follows a similar pattern to the Journey Micro
* web sockets router.
*/
const wss = new ws.WebSocketServer({ noServer: true });
server.on('upgrade', (request, socket, head) => {
wss.handleUpgrade(request, socket as any, head, (ws) => {
wss.emit('connection', ws, request);
});
});
server.on('close', () => wss.close());
const transport = new WebsocketServerTransport({
wsCreator: () => wss
});
const rSocketServer = new RSocketServer({
transport,
acceptor: {
accept: async (payload) => {
// Throwing an exception in this context will be returned to the client side request
if (!payload.metadata) {
// Meta data is required for endpoint handler path matching
throw new micro.errors.AuthorizationError('No context meta data provided');
}
const context = await params.contextProvider(payload.metadata!);
return {
// RequestStream is currently the only supported connection type
requestStream: (payload, initialN, responder) => {
const observer = new SocketRouterObserver();
handleReactiveStream(context, { payload, initialN, responder }, observer, params).catch((ex) => {
micro.logger.error(ex);
responder.onError(ex);
responder.onComplete();
});
return {
cancel: () => {
observer.triggerCancel();
},
onExtension: () => observer.triggerExtension(),
request: (n) => observer.triggerRequest(n)
};
}
};
}
}
});
Promise.resolve().then(() => {
// RSocket listens for this event before accepting connections
wss.emit('listening');
});
return rSocketServer.bind();
}
}
export async function handleReactiveStream<Context>(
context: Context,
request: {
payload: Payload;
initialN: number;
responder: SocketResponder;
},
observer: SocketRouterObserver,
params: CommonParams<Context>
) {
const { payload, responder, initialN } = request;
const { metadata } = payload;
const exitWithError = (error: any) => {
responder.onError(error);
responder.onComplete();
};
if (!metadata) {
return exitWithError(new micro.errors.ValidationError('Metadata is not provided'));
}
const meta = await params.metaDecoder(metadata);
const { path } = meta;
const route = params.endpoints.find((e) => e.path == path && e.type == RS_ENDPOINT_TYPE.STREAM);
if (!route) {
return exitWithError(new micro.errors.ResourceNotFound('route', `No route for ${path} is configured`));
}
const { handler, authorize, validator, decoder = params.payloadDecoder } = route;
const requestPayload = await decoder(payload.data || undefined);
if (validator) {
const isValid = validator.validate(requestPayload);
if (!isValid.valid) {
return exitWithError(new micro.errors.ValidationError(isValid.errors));
}
}
if (authorize) {
const isAuthorized = await authorize({ params: requestPayload, context, observer, responder });
if (!isAuthorized.authorized) {
return exitWithError(new micro.errors.AuthorizationError(isAuthorized.errors));
}
}
try {
await handler({
params: requestPayload,
context,
observer,
responder,
initialN
});
} catch (ex) {
micro.logger.error(ex);
responder.onError(ex);
responder.onComplete();
}
}