-
Notifications
You must be signed in to change notification settings - Fork 73
/
messaging.server.listener.ts
182 lines (157 loc) · 6.01 KB
/
messaging.server.listener.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
import {
reader,
Event,
ContextProvider,
combineMiddlewares,
combineEffects,
createEffectContext,
useContext,
EventError,
} from '@marblejs/core';
import * as O from 'fp-ts/lib/Option';
import * as R from 'fp-ts/lib/Reader';
import { pipe } from 'fp-ts/lib/pipeable';
import { flow } from 'fp-ts/lib/function';
import { Observable, Subscription, Subject, of, zip, OperatorFunction} from 'rxjs';
import { map, publish, takeUntil, catchError, take, mergeMapTo } from 'rxjs/operators';
import {
TransportMessage,
TransportMessageTransformer,
TransportLayerConnection,
TransportLayer,
} from '../transport/transport.interface';
import { jsonTransformer } from '../transport/transport.transformer';
import { MsgEffect, MsgMiddlewareEffect, MsgErrorEffect, MsgOutputEffect } from '../effects/messaging.effects.interface';
import { inputLogger$, outputLogger$, errorLogger$ } from '../middlewares/messaging.eventLogger.middleware';
import { TransportLayerToken, ServerEventsToken } from './messaging.server.tokens';
import { AllServerEvents, ServerEvent } from './messaging.server.events';
type ProcessOperator = OperatorFunction<TransportMessage<any>, TransportMessage<any>>;
export interface MessagingListenerConfig {
effects?: MsgEffect<any, any>[];
middlewares?: MsgMiddlewareEffect<any, any>[];
error$?: MsgErrorEffect;
output$?: MsgOutputEffect;
msgTransformer?: TransportMessageTransformer<any>;
}
const defaultOutput$: MsgOutputEffect = msg$ => msg$.pipe(map(m => m.event));
const defaultError$: MsgErrorEffect = msg$ => msg$;
const defaultEffect$: MsgEffect = msg$ => msg$;
export const messagingListener = (config: MessagingListenerConfig = {}) => {
const {
effects = [defaultEffect$],
middlewares = [],
output$ = defaultOutput$,
error$ = defaultError$,
msgTransformer = jsonTransformer,
} = config;
const handleConnection = (
conn: TransportLayerConnection,
serverEventsSubject: Subject<AllServerEvents>,
ask: ContextProvider,
) => {
let effectsSub: Subscription;
const errorSubject = new Subject<Error>();
const combinedEffects = combineEffects(...effects);
const combinedMiddlewares = combineMiddlewares(inputLogger$, ...middlewares);
const ctx = createEffectContext({ ask, client: conn });
const toUnhandledErrorEvent = ({ name, message }: Error): Observable<Event> =>
of({ type: 'UNHANDLED_ERROR', error: { name, message } });
const decode = (msg: TransportMessage<Buffer>): TransportMessage<Event> => ({
...msg,
data: { ...msgTransformer.decode(msg.data), raw: msg },
});
const processMiddlewares: ProcessOperator = flow(
publish(msg$ => zip(
combinedMiddlewares(msg$.pipe(map(m => m.data)), ctx).pipe(
catchError(toUnhandledErrorEvent),
),
msg$,
)),
map(([data, msg]) => ({ ...msg, data } as TransportMessage<any>)),
);
const processEffects: ProcessOperator = flow(
publish(msg$ => zip(
combinedEffects(msg$.pipe(map(m => m.data)), ctx).pipe(
catchError(toUnhandledErrorEvent),
),
msg$,
)),
map(([data, msg]) => ({ ...msg, data } as TransportMessage<any>)),
);
const processOutput: ProcessOperator = flow(
publish(msg$ => zip(
outputLogger$(msg$.pipe(map(m => ({ event: m.data, initiator: m }))), ctx).pipe(
catchError(toUnhandledErrorEvent),
),
msg$,
)),
map(([data, msg]) => ({ ...msg, data } as TransportMessage<any>)),
publish(msg$ => zip(
output$(msg$.pipe(map(m => ({ event: m.data, initiator: m }))), ctx).pipe(
catchError(toUnhandledErrorEvent),
),
msg$,
)),
map(([data, msg]) => ({ ...msg, data } as TransportMessage<any>)),
);
const message$ = conn.message$.pipe(
map(decode),
processMiddlewares,
processEffects,
processOutput,
catchError((error: EventError) => {
const e$ = of({ event: error.event, error });
return errorLogger$(e$, ctx).pipe(
mergeMapTo(error$(e$, ctx)),
map(data => ({ data } as TransportMessage<any>)),
);
}),
);
const onSubscribeEffectsOutput = (conn: TransportLayerConnection) => (msg: TransportMessage<any>) => {
if (msg.replyTo) {
conn.emitMessage(msg.replyTo, {
data: msgTransformer.encode(msg.data),
correlationId: msg.correlationId,
raw: msg.raw,
});
}
}
const onSubscribeEffectsError = (errorSubject: Subject<Error>) => (error: Error) => {
errorSubject.next(error);
if (effectsSub.closed) { effectsSub = subscribeEffects(message$); }
}
const onSubscribeEffectsClose = () => {
effectsSub = subscribeEffects(message$);
}
const subscribeEffects = (input$: Observable<TransportMessage<any>>) => input$
.pipe(takeUntil(conn.close$))
.subscribe(
onSubscribeEffectsOutput(conn),
onSubscribeEffectsError(errorSubject),
onSubscribeEffectsClose,
);
conn.close$
.pipe(take(1))
.subscribe(() => serverEventsSubject.next(ServerEvent.close()));
conn.error$
.pipe(takeUntil(conn.close$))
.subscribe(error => serverEventsSubject.next(ServerEvent.error(error)));
effectsSub = subscribeEffects(message$);
};
const listen = (transportLayer: TransportLayer, ask: ContextProvider) => async () => {
const { host, channel } = transportLayer.config;
const serverEventsSubject = pipe(ask(ServerEventsToken), O.getOrElse(() => undefined as unknown as Subject<AllServerEvents>));
const connection = await transportLayer.connect({ isConsumer: true });
handleConnection(connection, serverEventsSubject, ask);
connection.status$
.pipe(takeUntil(connection.close$))
.subscribe(type => serverEventsSubject.next(ServerEvent.status(host,channel, type)));
return connection;
};
return pipe(reader, R.map(ask => {
const transportLayer = useContext(TransportLayerToken)(ask);
return {
listen: listen(transportLayer, ask),
}
}));
};