-
Notifications
You must be signed in to change notification settings - Fork 98
/
ClientServerCompositeMetadataRouteExample.ts
228 lines (208 loc) · 5.69 KB
/
ClientServerCompositeMetadataRouteExample.ts
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
/*
* Copyright 2021-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
ErrorCodes,
OnExtensionSubscriber,
OnNextSubscriber,
OnTerminalSubscriber,
Payload,
RSocket,
RSocketConnector,
RSocketError,
RSocketServer,
} from "rsocket-core";
import { TcpClientTransport } from "rsocket-tcp-client";
import { TcpServerTransport } from "rsocket-tcp-server";
import {
decodeCompositeMetadata,
decodeRoutes,
encodeCompositeMetadata,
encodeRoute,
WellKnownMimeType,
} from "rsocket-composite-metadata";
import { exit } from "process";
import MESSAGE_RSOCKET_ROUTING = WellKnownMimeType.MESSAGE_RSOCKET_ROUTING;
import Logger from "./shared/logger";
let serverCloseable;
function mapMetaData(payload: Payload) {
const mappedMetaData = new Map<string, any>();
if (payload.metadata) {
const decodedCompositeMetaData = decodeCompositeMetadata(payload.metadata);
for (let metaData of decodedCompositeMetaData) {
switch (metaData.mimeType) {
case MESSAGE_RSOCKET_ROUTING.toString(): {
const tags = [];
for (let decodedRoute of decodeRoutes(metaData.content)) {
tags.push(decodedRoute);
}
const joinedRoute = tags.join(".");
mappedMetaData.set(MESSAGE_RSOCKET_ROUTING.toString(), joinedRoute);
}
}
}
}
return mappedMetaData;
}
class EchoService {
handleEchoRequestResponse(
responderStream: OnTerminalSubscriber &
OnNextSubscriber &
OnExtensionSubscriber,
payload: Payload
) {
const timeout = setTimeout(
() =>
responderStream.onNext(
{
data: Buffer.concat([Buffer.from("Echo: "), payload.data]),
},
true
),
1000
);
return {
cancel: () => {
clearTimeout(timeout);
console.log("cancelled");
},
onExtension: () => {
console.log("Received Extension request");
},
};
}
}
function makeServer() {
return new RSocketServer({
transport: new TcpServerTransport({
listenOptions: {
port: 9090,
host: "127.0.0.1",
},
}),
acceptor: {
accept: async () => ({
requestResponse: (
payload: Payload,
responderStream: OnTerminalSubscriber &
OnNextSubscriber &
OnExtensionSubscriber
) => {
const echoService = new EchoService();
const mappedMetaData = mapMetaData(payload);
const defaultSusbcriber = {
cancel() {
console.log("cancelled");
},
onExtension() {},
};
const route = mappedMetaData.get(MESSAGE_RSOCKET_ROUTING.toString());
if (!route) {
responderStream.onError(
new RSocketError(
ErrorCodes.REJECTED,
"Composite metadata did not include routing information."
)
);
return defaultSusbcriber;
}
switch (route) {
case "EchoService.echo": {
return echoService.handleEchoRequestResponse(
responderStream,
payload
);
}
default: {
responderStream.onError(
new RSocketError(
ErrorCodes.REJECTED,
"The encoded route was unknown by the server."
)
);
return defaultSusbcriber;
}
}
},
}),
},
});
}
function makeConnector() {
return new RSocketConnector({
transport: new TcpClientTransport({
connectionOptions: {
host: "127.0.0.1",
port: 9090,
},
}),
});
}
async function requestResponse(rsocket: RSocket, route?: string) {
let compositeMetaData = undefined;
if (route) {
const encodedRoute = encodeRoute(route);
const map = new Map<WellKnownMimeType, Buffer>();
map.set(MESSAGE_RSOCKET_ROUTING, encodedRoute);
compositeMetaData = encodeCompositeMetadata(map);
}
return new Promise((resolve, reject) => {
return rsocket.requestResponse(
{
data: Buffer.from("Hello World"),
metadata: compositeMetaData,
},
{
onError: (e) => {
reject(e);
},
onNext: (payload, isComplete) => {
Logger.info(
`payload[data: ${payload.data}; metadata: ${payload.metadata}]|${isComplete}`
);
resolve(payload);
},
onComplete: () => {},
onExtension: () => {},
}
);
});
}
async function main() {
const server = makeServer();
const connector = makeConnector();
serverCloseable = await server.bind();
const rsocket = await connector.connect();
// this request will pass
await requestResponse(rsocket, "EchoService.echo");
// this request will reject (unknown route)
try {
await requestResponse(rsocket, "UnknownService.unknown");
} catch (e) {
Logger.error(e);
}
// this request will reject (no routing data)
try {
await requestResponse(rsocket);
} catch (e) {
Logger.error(e);
}
}
main()
.then(() => exit())
.catch((error: Error) => {
console.error(error);
exit(1);
});