@powersync/service-rsocket-router 0.0.0-dev-20240620165206

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,67 @@
1
+ # Functional Source License, Version 1.1, Apache 2.0 Future License
2
+
3
+ ## Abbreviation
4
+
5
+ FSL-1.1-Apache-2.0
6
+
7
+ ## Notice
8
+
9
+ Copyright 2023-2024 Journey Mobile, Inc.
10
+
11
+ ## Terms and Conditions
12
+
13
+ ### Licensor ("We")
14
+
15
+ The party offering the Software under these Terms and Conditions.
16
+
17
+ ### The Software
18
+
19
+ The "Software" is each version of the software that we make available under these Terms and Conditions, as indicated by our inclusion of these Terms and Conditions with the Software.
20
+
21
+ ### License Grant
22
+
23
+ Subject to your compliance with this License Grant and the Patents, Redistribution and Trademark clauses below, we hereby grant you the right to use, copy, modify, create derivative works, publicly perform, publicly display and redistribute the Software for any Permitted Purpose identified below.
24
+
25
+ ### Permitted Purpose
26
+
27
+ A Permitted Purpose is any purpose other than a Competing Use. A Competing Use means making the Software available to others in a commercial product or service that:
28
+
29
+ 1. substitutes for the Software;
30
+ 2. substitutes for any other product or service we offer using the Software that exists as of the date we make the Software available; or
31
+ 3. offers the same or substantially similar functionality as the Software.
32
+
33
+ Permitted Purposes specifically include using the Software:
34
+
35
+ 1. for your internal use and access;
36
+ 2. for non-commercial education;
37
+ 3. for non-commercial research; and
38
+ 4. in connection with professional services that you provide to a licensee using the Software in accordance with these Terms and Conditions.
39
+
40
+ ### Patents
41
+
42
+ To the extent your use for a Permitted Purpose would necessarily infringe our patents, the license grant above includes a license under our patents. If you make a claim against any party that the Software infringes or contributes to the infringement of any patent, then your patent license to the Software ends immediately.
43
+
44
+ ### Redistribution
45
+
46
+ The Terms and Conditions apply to all copies, modifications and derivatives of the Software.
47
+ If you redistribute any copies, modifications or derivatives of the Software, you must include a copy of or a link to these Terms and Conditions and not remove any copyright notices provided in or with the Software.
48
+
49
+ ### Disclaimer
50
+
51
+ THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
52
+ IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES, EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
53
+
54
+ ### Trademarks
55
+
56
+ Except for displaying the License Details and identifying us as the origin of the Software, you have no right under these Terms and Conditions to use our trademarks, trade names, service marks or product names.
57
+
58
+ ## Grant of Future License
59
+
60
+ We hereby irrevocably grant you an additional license to use the Software under the Apache License, Version 2.0 that is effective on the second anniversary of the date we make the Software available. On or after that date, you may use the Software under the Apache License, Version 2.0, in which case the following will apply:
61
+
62
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
63
+ You may obtain a copy of the License at
64
+
65
+ http://www.apache.org/licenses/LICENSE-2.0
66
+
67
+ 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.
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # RSocket Micro Router
2
+
3
+ This package wraps the RSocket library to a router format compatible with endpoint definitions.
@@ -0,0 +1,4 @@
1
+ export * from './utils/BaseObserver.js';
2
+ export * from './router/ReactiveSocketRouter.js';
3
+ export * from './router/SocketRouterListener.js';
4
+ export * from './router/types.js';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export * from './utils/BaseObserver.js';
2
+ export * from './router/ReactiveSocketRouter.js';
3
+ export * from './router/SocketRouterListener.js';
4
+ export * from './router/types.js';
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,yBAAyB,CAAC;AACxC,cAAc,kCAAkC,CAAC;AACjD,cAAc,kCAAkC,CAAC;AACjD,cAAc,mBAAmB,CAAC"}
@@ -0,0 +1,26 @@
1
+ /// <reference types="node" resolution-mode="require"/>
2
+ /**
3
+ * This is a small Router wrapper which uses the RSocket lib
4
+ * to expose reactive websocket stream in an interface similar to
5
+ * other Journey micro routers.
6
+ */
7
+ import * as http from 'http';
8
+ import { Payload } from 'rsocket-core';
9
+ import { SocketRouterObserver } from './SocketRouterListener.js';
10
+ import { CommonParams, IReactiveStream, IReactiveStreamInput, ReactiveSocketRouterOptions, SocketResponder } from './types.js';
11
+ export declare class ReactiveSocketRouter<C> {
12
+ protected options?: ReactiveSocketRouterOptions<C> | undefined;
13
+ protected activeConnections: number;
14
+ constructor(options?: ReactiveSocketRouterOptions<C> | undefined);
15
+ reactiveStream<I, O>(path: string, stream: IReactiveStreamInput<I, O, C>): IReactiveStream<I, O, C>;
16
+ /**
17
+ * Apply a set of subscriptions to a raw http server. The specified path is used to tell
18
+ * the server on which path it should handle WebSocket upgrades
19
+ */
20
+ applyWebSocketEndpoints<I>(server: http.Server, params: CommonParams<C>): Promise<import("rsocket-core").Closeable>;
21
+ }
22
+ export declare function handleReactiveStream<Context>(context: Context, request: {
23
+ payload: Payload;
24
+ initialN: number;
25
+ responder: SocketResponder;
26
+ }, observer: SocketRouterObserver, params: CommonParams<Context>): Promise<void>;
@@ -0,0 +1,131 @@
1
+ import { RSocketServer } from 'rsocket-core';
2
+ import * as ws from 'ws';
3
+ import { SocketRouterObserver } from './SocketRouterListener.js';
4
+ import { RS_ENDPOINT_TYPE } from './types.js';
5
+ import { WebsocketServerTransport } from './transport/WebSocketServerTransport.js';
6
+ import { errors, logger } from '@powersync/lib-services-framework';
7
+ export class ReactiveSocketRouter {
8
+ constructor(options) {
9
+ this.options = options;
10
+ this.activeConnections = 0;
11
+ }
12
+ reactiveStream(path, stream) {
13
+ return {
14
+ ...stream,
15
+ type: RS_ENDPOINT_TYPE.STREAM,
16
+ path: path
17
+ };
18
+ }
19
+ /**
20
+ * Apply a set of subscriptions to a raw http server. The specified path is used to tell
21
+ * the server on which path it should handle WebSocket upgrades
22
+ */
23
+ applyWebSocketEndpoints(server, params) {
24
+ /**
25
+ * Use upgraded connections from the existing server.
26
+ * This follows a similar pattern to the Journey Micro
27
+ * web sockets router.
28
+ */
29
+ const wss = new ws.WebSocketServer({ noServer: true });
30
+ server.on('upgrade', (request, socket, head) => {
31
+ wss.handleUpgrade(request, socket, head, (ws) => {
32
+ wss.emit('connection', ws, request);
33
+ });
34
+ });
35
+ server.on('close', () => wss.close());
36
+ const transport = new WebsocketServerTransport({
37
+ wsCreator: () => wss
38
+ });
39
+ const rSocketServer = new RSocketServer({
40
+ transport,
41
+ acceptor: {
42
+ accept: async (payload) => {
43
+ const { max_concurrent_connections } = this.options ?? {};
44
+ if (max_concurrent_connections && this.activeConnections >= max_concurrent_connections) {
45
+ throw new errors.JourneyError({
46
+ code: '429',
47
+ description: `Maximum active concurrent connections limit has been reached`
48
+ });
49
+ }
50
+ // Throwing an exception in this context will be returned to the client side request
51
+ if (!payload.metadata) {
52
+ // Meta data is required for endpoint handler path matching
53
+ throw new errors.AuthorizationError('No context meta data provided');
54
+ }
55
+ const context = await params.contextProvider(payload.metadata);
56
+ return {
57
+ // RequestStream is currently the only supported connection type
58
+ requestStream: (payload, initialN, responder) => {
59
+ const observer = new SocketRouterObserver();
60
+ handleReactiveStream(context, { payload, initialN, responder }, observer, params).catch((ex) => {
61
+ logger.error(ex);
62
+ responder.onError(ex);
63
+ responder.onComplete();
64
+ });
65
+ this.activeConnections++;
66
+ return {
67
+ cancel: () => {
68
+ this.activeConnections--;
69
+ observer.triggerCancel();
70
+ },
71
+ onExtension: () => observer.triggerExtension(),
72
+ request: (n) => observer.triggerRequest(n)
73
+ };
74
+ }
75
+ };
76
+ }
77
+ }
78
+ });
79
+ Promise.resolve().then(() => {
80
+ // RSocket listens for this event before accepting connections
81
+ wss.emit('listening');
82
+ });
83
+ return rSocketServer.bind();
84
+ }
85
+ }
86
+ export async function handleReactiveStream(context, request, observer, params) {
87
+ const { payload, responder, initialN } = request;
88
+ const { metadata } = payload;
89
+ const exitWithError = (error) => {
90
+ responder.onError(error);
91
+ responder.onComplete();
92
+ };
93
+ if (!metadata) {
94
+ return exitWithError(new errors.ValidationError('Metadata is not provided'));
95
+ }
96
+ const meta = await params.metaDecoder(metadata);
97
+ const { path } = meta;
98
+ const route = params.endpoints.find((e) => e.path == path && e.type == RS_ENDPOINT_TYPE.STREAM);
99
+ if (!route) {
100
+ return exitWithError(new errors.ResourceNotFound('route', `No route for ${path} is configured`));
101
+ }
102
+ const { handler, authorize, validator, decoder = params.payloadDecoder } = route;
103
+ const requestPayload = await decoder(payload.data || undefined);
104
+ if (validator) {
105
+ const isValid = validator.validate(requestPayload);
106
+ if (!isValid.valid) {
107
+ return exitWithError(new errors.ValidationError(isValid.errors));
108
+ }
109
+ }
110
+ if (authorize) {
111
+ const isAuthorized = await authorize({ params: requestPayload, context, observer, responder });
112
+ if (!isAuthorized.authorized) {
113
+ return exitWithError(new errors.AuthorizationError(isAuthorized.errors));
114
+ }
115
+ }
116
+ try {
117
+ await handler({
118
+ params: requestPayload,
119
+ context,
120
+ observer,
121
+ responder,
122
+ initialN
123
+ });
124
+ }
125
+ catch (ex) {
126
+ logger.error(ex);
127
+ responder.onError(ex);
128
+ responder.onComplete();
129
+ }
130
+ }
131
+ //# sourceMappingURL=ReactiveSocketRouter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ReactiveSocketRouter.js","sourceRoot":"","sources":["../../src/router/ReactiveSocketRouter.ts"],"names":[],"mappings":"AAMA,OAAO,EAAW,aAAa,EAAE,MAAM,cAAc,CAAC;AACtD,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,EA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AAa,CAAC,IAAI,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,gBAAgB,IAAI,gBAAgB,CAAC,CAAC,CAAC;KAClG;IAED,MAAM,EAAE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,GAAG,MAAM,CAAC,cAAc,EAAE,GAAG,KAAK,CAAC;IACjF,MAAM,cAAc,GAAG,MAAM,OAAO,CAAC,OAAO,CAAC,IAAI,IAAI,SAAS,CAAC,CAAC;IAEhE,IAAI,SAAS,EAAE;QACb,MAAM,OAAO,GAAG,SAAS,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC;QACnD,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE;YAClB,OAAO,aAAa,CAAC,IAAI,MAAM,CAAC,eAAe,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC;SAClE;KACF;IAED,IAAI,SAAS,EAAE;QACb,MAAM,YAAY,GAAG,MAAM,SAAS,CAAC,EAAE,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAC,CAAC;QAC/F,IAAI,CAAC,YAAY,CAAC,UAAU,EAAE;YAC5B,OAAO,aAAa,CAAC,IAAI,MAAM,CAAC,kBAAkB,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC;SAC1E;KACF;IAED,IAAI;QACF,MAAM,OAAO,CAAC;YACZ,MAAM,EAAE,cAAc;YACtB,OAAO;YACP,QAAQ;YACR,SAAS;YACT,QAAQ;SACT,CAAC,CAAC;KACJ;IAAC,OAAO,EAAE,EAAE;QACX,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACjB,SAAS,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;QACtB,SAAS,CAAC,UAAU,EAAE,CAAC;KACxB;AACH,CAAC"}
@@ -0,0 +1,11 @@
1
+ import { BaseObserver } from '../utils/BaseObserver.js';
2
+ export interface SocketRouterListener {
3
+ cancel: () => void;
4
+ onExtension: () => void;
5
+ request: (n: number) => void;
6
+ }
7
+ export declare class SocketRouterObserver extends BaseObserver<SocketRouterListener> {
8
+ triggerCancel(): void;
9
+ triggerExtension(): void;
10
+ triggerRequest(n: number): void;
11
+ }
@@ -0,0 +1,13 @@
1
+ import { BaseObserver } from '../utils/BaseObserver.js';
2
+ export class SocketRouterObserver extends BaseObserver {
3
+ triggerCancel() {
4
+ this.iterateListeners((l) => l.cancel?.());
5
+ }
6
+ triggerExtension() {
7
+ this.iterateListeners((l) => l.onExtension?.());
8
+ }
9
+ triggerRequest(n) {
10
+ this.iterateListeners((l) => l.request?.(n));
11
+ }
12
+ }
13
+ //# sourceMappingURL=SocketRouterListener.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SocketRouterListener.js","sourceRoot":"","sources":["../../src/router/SocketRouterListener.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAQxD,MAAM,OAAO,oBAAqB,SAAQ,YAAkC;IAC1E,aAAa;QACX,IAAI,CAAC,gBAAgB,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;IAC7C,CAAC;IAED,gBAAgB;QACd,IAAI,CAAC,gBAAgB,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;IAClD,CAAC;IAED,cAAc,CAAC,CAAS;QACtB,IAAI,CAAC,gBAAgB,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IAC/C,CAAC;CACF"}
@@ -0,0 +1,19 @@
1
+ import { Closeable, Demultiplexer, DuplexConnection, Frame, FrameHandler, Multiplexer, Outbound, ServerTransport } from 'rsocket-core';
2
+ import * as WebSocket from 'ws';
3
+ export type SocketFactory = (options: SocketOptions) => WebSocket.WebSocketServer;
4
+ export type SocketOptions = {
5
+ host?: string;
6
+ port?: number;
7
+ };
8
+ export type ServerOptions = SocketOptions & {
9
+ wsCreator?: SocketFactory;
10
+ debug?: boolean;
11
+ };
12
+ export declare class WebsocketServerTransport implements ServerTransport {
13
+ private readonly host;
14
+ private readonly port;
15
+ private readonly factory;
16
+ constructor(options: ServerOptions);
17
+ bind(connectionAcceptor: (frame: Frame, connection: DuplexConnection) => Promise<void>, multiplexerDemultiplexerFactory: (frame: Frame, outbound: Outbound & Closeable) => Multiplexer & Demultiplexer & FrameHandler): Promise<Closeable>;
18
+ private connectServer;
19
+ }
@@ -0,0 +1,86 @@
1
+ /*
2
+ * Adapted from https://github.com/rsocket/rsocket-js/blob/1.0.x-alpha/packages/rsocket-websocket-client/src/WebsocketClientTransport.ts
3
+ * Copyright 2021-2022 the original author or authors.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { Deferred } from 'rsocket-core';
18
+ import * as WebSocket from 'ws';
19
+ import { WebsocketDuplexConnection } from './WebsocketDuplexConnection.js';
20
+ import { logger } from '@powersync/lib-services-framework';
21
+ const defaultFactory = (options) => {
22
+ return new WebSocket.WebSocketServer({
23
+ host: options.host,
24
+ port: options.port
25
+ });
26
+ };
27
+ export class WebsocketServerTransport {
28
+ constructor(options) {
29
+ this.host = options.host;
30
+ this.port = options.port;
31
+ this.factory = options.wsCreator ?? defaultFactory;
32
+ }
33
+ async bind(connectionAcceptor, multiplexerDemultiplexerFactory) {
34
+ const websocketServer = await this.connectServer();
35
+ const serverCloseable = new ServerCloseable(websocketServer);
36
+ const connectionListener = (websocket) => {
37
+ try {
38
+ websocket.binaryType = 'nodebuffer';
39
+ const duplex = WebSocket.createWebSocketStream(websocket);
40
+ WebsocketDuplexConnection.create(duplex, connectionAcceptor, multiplexerDemultiplexerFactory, websocket);
41
+ }
42
+ catch (ex) {
43
+ logger.error(`Could not create duplex connection`, ex);
44
+ if (websocket.readyState == websocket.OPEN) {
45
+ websocket.close();
46
+ }
47
+ }
48
+ };
49
+ const closeListener = (error) => {
50
+ serverCloseable.close(error);
51
+ };
52
+ websocketServer.addListener('connection', connectionListener);
53
+ websocketServer.addListener('close', closeListener);
54
+ websocketServer.addListener('error', closeListener);
55
+ return serverCloseable;
56
+ }
57
+ connectServer() {
58
+ return new Promise((resolve, reject) => {
59
+ const websocketServer = this.factory({
60
+ host: this.host,
61
+ port: this.port
62
+ });
63
+ const earlyCloseListener = (error) => {
64
+ reject(error);
65
+ };
66
+ websocketServer.addListener('close', earlyCloseListener);
67
+ websocketServer.addListener('error', earlyCloseListener);
68
+ websocketServer.addListener('listening', () => resolve(websocketServer));
69
+ });
70
+ }
71
+ }
72
+ class ServerCloseable extends Deferred {
73
+ constructor(server) {
74
+ super();
75
+ this.server = server;
76
+ }
77
+ close(error) {
78
+ if (this.done) {
79
+ super.close(error);
80
+ return;
81
+ }
82
+ // For this package's use case the server is externally closed
83
+ super.close();
84
+ }
85
+ }
86
+ //# sourceMappingURL=WebSocketServerTransport.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WebSocketServerTransport.js","sourceRoot":"","sources":["../../../src/router/transport/WebSocketServerTransport.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAEL,QAAQ,EAQT,MAAM,cAAc,CAAC;AACtB,OAAO,KAAK,SAAS,MAAM,IAAI,CAAC;AAChC,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,MAAM,EAAE,MAAM,mCAAmC,CAAC;AAc3D,MAAM,cAAc,GAAkB,CAAC,OAAsB,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AAC,CAAC;QAC9D,eAAe,CAAC,WAAW,CAAC,OAAO,EAAE,aAAa,CAAC,CAAC;QACpD,eAAe,CAAC,WAAW,CAAC,OAAO,EAAE,aAAa,CAAC,CAAC;QAEpD,OAAO,eAAe,CAAC;IACzB,CAAC;IAEO,aAAa;QACnB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACrC,MAAM,eAAe,GAAG,IAAI,CAAC,OAAO,CAAC;gBACnC,IAAI,EAAE,IAAI,CAAC,IAAI;gBACf,IAAI,EAAE,IAAI,CAAC,IAAI;aAChB,CAAC,CAAC;YAEH,MAAM,kBAAkB,GAAG,CAAC,KAAa,EAAE,EAAE;gBAC3C,MAAM,CAAC,KAAK,CAAC,CAAC;YAChB,CAAC,CAAC;YAEF,eAAe,CAAC,WAAW,CAAC,OAAO,EAAE,kBAAkB,CAAC,CAAC;YACzD,eAAe,CAAC,WAAW,CAAC,OAAO,EAAE,kBAAkB,CAAC,CAAC;YACzD,eAAe,CAAC,WAAW,CAAC,WAAW,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,CAAC;QAC3E,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAED,MAAM,eAAgB,SAAQ,QAAQ;IACpC,YAA6B,MAAiC;QAC5D,KAAK,EAAE,CAAC;QADmB,WAAM,GAAN,MAAM,CAA2B;IAE9D,CAAC;IAED,KAAK,CAAC,KAAa;QACjB,IAAI,IAAI,CAAC,IAAI,EAAE;YACb,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;YACnB,OAAO;SACR;QAED,8DAA8D;QAE9D,KAAK,CAAC,KAAK,EAAE,CAAC;IAChB,CAAC;CACF"}
@@ -0,0 +1,17 @@
1
+ /// <reference types="node" resolution-mode="require"/>
2
+ import { Closeable, Deferred, Demultiplexer, DuplexConnection, Frame, FrameHandler, Multiplexer, Outbound } from 'rsocket-core';
3
+ import { Duplex } from 'stream';
4
+ import WebSocket from 'ws';
5
+ export declare class WebsocketDuplexConnection extends Deferred implements DuplexConnection, Outbound {
6
+ private websocketDuplex;
7
+ private rawSocket;
8
+ readonly multiplexerDemultiplexer: Multiplexer & Demultiplexer & FrameHandler;
9
+ constructor(websocketDuplex: Duplex, frame: Frame, multiplexerDemultiplexerFactory: (frame: Frame, outbound: Outbound & Closeable) => Multiplexer & Demultiplexer & FrameHandler, rawSocket: WebSocket.WebSocket);
10
+ get availability(): number;
11
+ close(error?: Error): void;
12
+ send(frame: Frame): void;
13
+ private handleClosed;
14
+ private handleError;
15
+ private handleMessage;
16
+ static create(socket: Duplex, connectionAcceptor: (frame: Frame, connection: DuplexConnection) => Promise<void>, multiplexerDemultiplexerFactory: (frame: Frame, outbound: Outbound & Closeable) => Multiplexer & Demultiplexer & FrameHandler, rawSocket: WebSocket.WebSocket): void;
17
+ }
@@ -0,0 +1,105 @@
1
+ /*
2
+ * Adapted from https://github.com/rsocket/rsocket-js/blob/1.0.x-alpha/packages/rsocket-websocket-client/src/WebsocketDuplexConnection.ts
3
+ * Copyright 2021-2022 the original author or authors.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { logger } from '@powersync/lib-services-framework';
18
+ import { Deferred, deserializeFrame, serializeFrame } from 'rsocket-core';
19
+ export class WebsocketDuplexConnection extends Deferred {
20
+ constructor(websocketDuplex, frame, multiplexerDemultiplexerFactory, rawSocket) {
21
+ super();
22
+ this.websocketDuplex = websocketDuplex;
23
+ this.rawSocket = rawSocket;
24
+ this.handleClosed = (e) => {
25
+ this.close(new Error(e.reason || 'WebsocketDuplexConnection: Socket closed unexpectedly.'));
26
+ };
27
+ this.handleError = (e) => {
28
+ logger.error(`Error in WebSocket duplex connection: ${e}`);
29
+ this.close(e.error);
30
+ };
31
+ this.handleMessage = (buffer) => {
32
+ try {
33
+ const frame = deserializeFrame(buffer);
34
+ this.multiplexerDemultiplexer.handle(frame);
35
+ }
36
+ catch (error) {
37
+ this.close(error);
38
+ }
39
+ };
40
+ websocketDuplex.on('close', this.handleClosed);
41
+ websocketDuplex.on('error', this.handleError);
42
+ websocketDuplex.on('data', this.handleMessage);
43
+ this.multiplexerDemultiplexer = multiplexerDemultiplexerFactory(frame, this);
44
+ }
45
+ get availability() {
46
+ return this.websocketDuplex.destroyed ? 0 : 1;
47
+ }
48
+ close(error) {
49
+ if (this.done) {
50
+ super.close(error);
51
+ return;
52
+ }
53
+ this.websocketDuplex.removeAllListeners();
54
+ this.websocketDuplex.end();
55
+ super.close(error);
56
+ }
57
+ send(frame) {
58
+ if (this.done) {
59
+ return;
60
+ }
61
+ try {
62
+ const buffer = serializeFrame(frame);
63
+ // Work around for this issue
64
+ // https://github.com/websockets/ws/issues/1515
65
+ if (this.rawSocket.readyState == this.rawSocket.CLOSING || this.rawSocket.readyState == this.rawSocket.CLOSED) {
66
+ this.close(new Error('WebSocket is closing'));
67
+ return;
68
+ }
69
+ this.websocketDuplex.write(buffer);
70
+ }
71
+ catch (ex) {
72
+ this.close(new Error(ex.reason || `Could not write to WebSocket duplex connection: ${ex}`));
73
+ }
74
+ }
75
+ static create(socket, connectionAcceptor, multiplexerDemultiplexerFactory, rawSocket) {
76
+ socket.once('data', async (buffer) => {
77
+ let frame = undefined;
78
+ try {
79
+ frame = deserializeFrame(buffer);
80
+ if (!frame) {
81
+ throw new Error(`Unable to deserialize frame`);
82
+ }
83
+ }
84
+ catch (ex) {
85
+ logger.info(`Received error deserializing initial frame buffer. Skipping connection request.`, ex);
86
+ // The initial frame should always be parsable
87
+ return socket.end();
88
+ }
89
+ const connection = new WebsocketDuplexConnection(socket, frame, multiplexerDemultiplexerFactory, rawSocket);
90
+ if (connection.done) {
91
+ return;
92
+ }
93
+ try {
94
+ socket.pause();
95
+ await connectionAcceptor(frame, connection);
96
+ socket.resume();
97
+ }
98
+ catch (error) {
99
+ logger.info(`Error accepting connection:`, error);
100
+ connection.close(error);
101
+ }
102
+ });
103
+ }
104
+ }
105
+ //# sourceMappingURL=WebsocketDuplexConnection.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"WebsocketDuplexConnection.js","sourceRoot":"","sources":["../../../src/router/transport/WebsocketDuplexConnection.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,mCAAmC,CAAC;AAC3D,OAAO,EAEL,QAAQ,EAER,gBAAgB,EAMhB,cAAc,EACf,MAAM,cAAc,CAAC;AAItB,MAAM,OAAO,yBAA0B,SAAQ,QAAQ;IAGrD,YACU,eAAuB,EAC/B,KAAY,EACZ,+BAG+C,EACvC,SAA8B;QAEtC,KAAK,EAAE,CAAC;QARA,oBAAe,GAAf,eAAe,CAAQ;QAMvB,cAAS,GAAT,SAAS,CAAqB;QA+ChC,iBAAY,GAAG,CAAC,CAAuB,EAAQ,EAAE;YACvD,IAAI,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,CAAC,CAAC,MAAM,IAAI,wDAAwD,CAAC,CAAC,CAAC;QAC9F,CAAC,CAAC;QAEM,gBAAW,GAAG,CAAC,CAAuB,EAAQ,EAAE;YACtD,MAAM,CAAC,KAAK,CAAC,yCAAyC,CAAC,EAAE,CAAC,CAAC;YAC3D,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;QACtB,CAAC,CAAC;QAEM,kBAAa,GAAG,CAAC,MAAc,EAAQ,EAAE;YAC/C,IAAI;gBACF,MAAM,KAAK,GAAG,gBAAgB,CAAC,MAAM,CAAC,CAAC;gBACvC,IAAI,CAAC,wBAAwB,CAAC,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;CACF"}
@@ -0,0 +1,39 @@
1
+ /// <reference types="node" resolution-mode="require"/>
2
+ import * as t from 'ts-codec';
3
+ import { router } from '@powersync/lib-services-framework';
4
+ import { OnExtensionSubscriber, OnNextSubscriber, OnTerminalSubscriber } from 'rsocket-core';
5
+ import { SocketRouterObserver } from './SocketRouterListener.js';
6
+ export declare enum RS_ENDPOINT_TYPE {
7
+ STREAM = "stream"
8
+ }
9
+ export declare const RSocketRequestMeta: t.ObjectCodec<{
10
+ path: t.IdentityCodec<t.CodecType.String>;
11
+ }>;
12
+ export type RequestMeta = t.Decoded<typeof RSocketRequestMeta>;
13
+ export type ReactiveSocketRouterOptions<C> = {
14
+ max_concurrent_connections?: number;
15
+ };
16
+ export type SocketResponder = OnTerminalSubscriber & OnNextSubscriber & OnExtensionSubscriber;
17
+ export type CommonStreamPayload = {
18
+ observer: SocketRouterObserver;
19
+ responder: SocketResponder;
20
+ };
21
+ export type ReactiveStreamPayload<O> = CommonStreamPayload & {
22
+ initialN: number;
23
+ };
24
+ export type IReactiveStream<I = any, O = any, C = any> = Omit<router.Endpoint<I, O, C, router.EndpointHandlerPayload<I, C> & CommonStreamPayload, router.EndpointHandler<router.EndpointHandlerPayload<I, C> & ReactiveStreamPayload<O>, undefined>>, 'method'> & {
25
+ type: RS_ENDPOINT_TYPE.STREAM;
26
+ /**
27
+ * Decodes raw payload buffer to [I].
28
+ * Falls back to router level decoder if not specified.
29
+ */
30
+ decoder?: (rawData?: Buffer) => Promise<I>;
31
+ };
32
+ export type IReactiveStreamInput<I, O, C> = Omit<IReactiveStream<I, O, C>, 'path' | 'type' | 'method'>;
33
+ export type ReactiveEndpoint = IReactiveStream;
34
+ export type CommonParams<C> = {
35
+ endpoints: Array<ReactiveEndpoint>;
36
+ contextProvider: (metaData: Buffer) => Promise<C>;
37
+ metaDecoder: (meta: Buffer) => Promise<RequestMeta>;
38
+ payloadDecoder: (rawData?: Buffer) => Promise<any>;
39
+ };
@@ -0,0 +1,10 @@
1
+ import * as t from 'ts-codec';
2
+ export var RS_ENDPOINT_TYPE;
3
+ (function (RS_ENDPOINT_TYPE) {
4
+ // Other methods are supported by RSocket, but are not yet mapped here
5
+ RS_ENDPOINT_TYPE["STREAM"] = "stream";
6
+ })(RS_ENDPOINT_TYPE || (RS_ENDPOINT_TYPE = {}));
7
+ export const RSocketRequestMeta = t.object({
8
+ path: t.string
9
+ });
10
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/router/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,UAAU,CAAC;AAO9B,MAAM,CAAN,IAAY,gBAGX;AAHD,WAAY,gBAAgB;IAC1B,sEAAsE;IACtE,qCAAiB,CAAA;AACnB,CAAC,EAHW,gBAAgB,KAAhB,gBAAgB,QAG3B;AAED,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,CAAC;IACzC,IAAI,EAAE,CAAC,CAAC,MAAM;CACf,CAAC,CAAC"}
@@ -0,0 +1,9 @@
1
+ export declare class BaseObserver<T> {
2
+ protected listeners: {
3
+ [id: string]: Partial<T>;
4
+ };
5
+ constructor();
6
+ registerListener(listener: Partial<T>): () => void;
7
+ iterateListeners(cb: (listener: Partial<T>) => any): void;
8
+ iterateAsyncListeners(cb: (listener: Partial<T>) => Promise<any>): Promise<void>;
9
+ }
@@ -0,0 +1,24 @@
1
+ import { v4 as uuid } from 'uuid';
2
+ export class BaseObserver {
3
+ constructor() {
4
+ this.listeners = {};
5
+ }
6
+ registerListener(listener) {
7
+ const id = uuid();
8
+ this.listeners[id] = listener;
9
+ return () => {
10
+ delete this.listeners[id];
11
+ };
12
+ }
13
+ iterateListeners(cb) {
14
+ for (let i in this.listeners) {
15
+ cb(this.listeners[i]);
16
+ }
17
+ }
18
+ async iterateAsyncListeners(cb) {
19
+ for (let i in this.listeners) {
20
+ await cb(this.listeners[i]);
21
+ }
22
+ }
23
+ }
24
+ //# sourceMappingURL=BaseObserver.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"BaseObserver.js","sourceRoot":"","sources":["../../src/utils/BaseObserver.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,IAAI,IAAI,EAAE,MAAM,MAAM,CAAC;AAElC,MAAM,OAAO,YAAY;IAGvB;QACE,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;IACtB,CAAC;IAED,gBAAgB,CAAC,QAAoB;QACnC,MAAM,EAAE,GAAG,IAAI,EAAE,CAAC;QAClB,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC;QAC9B,OAAO,GAAG,EAAE;YACV,OAAO,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;QAC5B,CAAC,CAAC;IACJ,CAAC;IAED,gBAAgB,CAAC,EAAiC;QAChD,KAAK,IAAI,CAAC,IAAI,IAAI,CAAC,SAAS,EAAE;YAC5B,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;SACvB;IACH,CAAC;IAED,KAAK,CAAC,qBAAqB,CAAC,EAA0C;QACpE,KAAK,IAAI,CAAC,IAAI,IAAI,CAAC,SAAS,EAAE;YAC5B,MAAM,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;SAC7B;IACH,CAAC;CACF"}
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "@powersync/service-rsocket-router",
3
+ "repository": "https://github.com/powersync-ja/powersync-service",
4
+ "version": "0.0.0-dev-20240620165206",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "license": "FSL-1.1-Apache-2.0",
8
+ "publishConfig": {
9
+ "access": "public"
10
+ },
11
+ "files": [
12
+ "dist/**/*"
13
+ ],
14
+ "type": "module",
15
+ "dependencies": {
16
+ "rsocket-core": "1.0.0-alpha.3",
17
+ "ts-codec": "^1.2.2",
18
+ "uuid": "^9.0.1",
19
+ "ws": "^8.17.0",
20
+ "@powersync/lib-services-framework": "0.0.0-dev-20240620165206"
21
+ },
22
+ "devDependencies": {
23
+ "@types/uuid": "^9.0.4",
24
+ "@types/ws": "~8.2.0",
25
+ "bson": "^6.6.0",
26
+ "rsocket-websocket-client": "1.0.0-alpha.3",
27
+ "typescript": "~5.2.2",
28
+ "vitest": "^0.34.6"
29
+ },
30
+ "scripts": {
31
+ "clean": "rm -r ./dist && tsc -b --clean",
32
+ "build": "tsc -b",
33
+ "test": "vitest"
34
+ }
35
+ }