-
Notifications
You must be signed in to change notification settings - Fork 265
/
subscription-handshake-link.ts
240 lines (195 loc) · 8.59 KB
/
subscription-handshake-link.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
229
230
231
232
233
234
235
236
237
238
239
240
/*!
* Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
import { ApolloLink, Observable, Operation, FetchResult } from "apollo-link";
import { rootLogger } from "./utils";
import * as Paho from './vendor/paho-mqtt';
import { ApolloError } from "apollo-client";
import { FieldNode } from "graphql";
import { getMainDefinition } from "apollo-utilities";
const logger = rootLogger.extend('subscriptions');
const mqttLogger = logger.extend('mqtt');
type SubscriptionExtension = {
mqttConnections: MqttConnectionInfo[],
newSubscriptions: NewSubscriptions,
}
type MqttConnectionInfo = {
client: string,
url: string,
topics: string[],
};
type NewSubscriptions = {
[key: string]: {
topic: string,
expireTime: number,
}
};
type ClientObservers = {
client: any,
observers: Set<ZenObservable.Observer<any>>,
}
export const CONTROL_EVENTS_KEY = '@@controlEvents';
export class SubscriptionHandshakeLink extends ApolloLink {
private subsInfoContextKey: string;
private topicObservers: Map<string, Set<ZenObservable.Observer<any>>> = new Map();
private clientObservers: Map<string, ClientObservers> = new Map();
constructor(subsInfoContextKey) {
super();
this.subsInfoContextKey = subsInfoContextKey;
}
request(operation: Operation): Observable<FetchResult> | null {
const {
[this.subsInfoContextKey]: subsInfo,
controlMessages: { [CONTROL_EVENTS_KEY]: controlEvents } = { [CONTROL_EVENTS_KEY]: undefined }
} = operation.getContext();
const {
extensions: {
subscription: { newSubscriptions, mqttConnections }
} = { subscription: { newSubscriptions: {}, mqttConnections: [] } },
errors = [],
}: {
extensions?: {
subscription: SubscriptionExtension
},
errors: any[]
} = subsInfo;
if (errors && errors.length) {
return new Observable(observer => {
observer.error(new ApolloError({
errorMessage: 'Error during subscription handshake',
extraInfo: { errors },
graphQLErrors: errors
}));
return () => { };
});
}
const newSubscriptionTopics = Object.keys(newSubscriptions).map(subKey => newSubscriptions[subKey].topic);
const existingTopicsWithObserver = new Set(newSubscriptionTopics.filter(t => this.topicObservers.has(t)));
const newTopics = new Set(newSubscriptionTopics.filter(t => !existingTopicsWithObserver.has(t)));
return new Observable<FetchResult>(observer => {
existingTopicsWithObserver.forEach(t => {
this.topicObservers.get(t).add(observer);
const anObserver = Array.from(this.topicObservers.get(t)).find(() => true);
const [clientId] = Array.from(this.clientObservers).find(([, { observers }]) => observers.has(anObserver));
this.clientObservers.get(clientId).observers.add(observer);
});
const newTopicsConnectionInfo = mqttConnections
.filter(c => c.topics.some(t => newTopics.has(t)))
.map(({ topics, ...rest }) => ({
...rest,
topics: topics.filter(t => newTopics.has(t))
} as MqttConnectionInfo));
this.connectNewClients(newTopicsConnectionInfo, observer, operation);
return () => {
const clientsForCurrentObserver = Array.from(this.clientObservers).filter(([, { observers }]) => observers.has(observer));
clientsForCurrentObserver.forEach(([clientId]) => this.clientObservers.get(clientId).observers.delete(observer));
this.clientObservers.forEach(({ observers, client }) => {
if (observers.size === 0) {
if (client.isConnected()) {
client.disconnect();
}
this.clientObservers.delete(client.clientId);
}
});
this.clientObservers = new Map(
Array.from(this.clientObservers).filter(([, { observers }]) => observers.size > 0)
);
this.topicObservers.forEach(observers => observers.delete(observer));
this.topicObservers = new Map(
Array.from(this.topicObservers)
.filter(([, observers]) => observers.size > 0)
);
};
}).filter(data => {
const { extensions: { controlMsgType = undefined } = {} } = data;
const isControlMsg = typeof controlMsgType !== 'undefined';
return controlEvents === true || !isControlMsg;
});
}
async connectNewClients(connectionInfo: MqttConnectionInfo[], observer: ZenObservable.Observer<FetchResult>, operation: Operation) {
const { query } = operation;
const selectionNames = (getMainDefinition(query).selectionSet.selections as FieldNode[]).map(({ name: { value } }) => value);
const result = Promise.all(connectionInfo.map(c => this.connectNewClient(c, observer, selectionNames)));
const data = selectionNames.reduce(
(acc, name) => (acc[name] = acc[name] || null, acc),
{}
);
observer.next({
data,
extensions: {
controlMsgType: 'CONNECTED',
controlMsgInfo: {
connectionInfo,
},
}
});
return result
};
async connectNewClient(connectionInfo: MqttConnectionInfo, observer: ZenObservable.Observer<FetchResult>, selectionNames: string[]) {
const { client: clientId, url, topics } = connectionInfo;
const client: any = new Paho.Client(url, clientId);
client.trace = mqttLogger.bind(null, clientId);
client.onConnectionLost = ({ errorCode, ...args }) => {
if (errorCode !== 0) {
topics.forEach(t => {
if (this.topicObservers.has(t)) {
this.topicObservers.get(t).forEach(observer => observer.error({ ...args, permanent: true }));
}
});
}
topics.forEach(t => this.topicObservers.delete(t));
};
(client as any).onMessageArrived = ({ destinationName, payloadString }) => this.onMessage(destinationName, payloadString, selectionNames);
await new Promise((resolve, reject) => {
client.connect({
useSSL: url.indexOf('wss://') === 0,
mqttVersion: 3,
onSuccess: () => resolve(client),
onFailure: reject,
});
});
await this.subscribeToTopics(client, topics, observer);
return client;
}
subscribeToTopics<T>(client, topics: string[], observer: ZenObservable.Observer<T>) {
return Promise.all(topics.map(topic => this.subscribeToTopic(client, topic, observer)));
}
subscribeToTopic<T>(client, topic: string, observer: ZenObservable.Observer<T>) {
return new Promise((resolve, reject) => {
(client as any).subscribe(topic, {
onSuccess: () => {
if (!this.topicObservers.has(topic)) {
this.topicObservers.set(topic, new Set());
}
if (!this.clientObservers.has(client.clientId)) {
this.clientObservers.set(client.clientId, { client, observers: new Set() });
}
this.topicObservers.get(topic).add(observer);
this.clientObservers.get(client.clientId).observers.add(observer);
resolve(topic);
},
onFailure: reject,
});
});
}
onMessage = (topic: string, message: string, selectionNames: string[]) => {
const parsedMessage = JSON.parse(message);
const observers = this.topicObservers.get(topic);
const data = selectionNames.reduce(
(acc, name) => (acc[name] = acc[name] || null, acc),
parsedMessage.data || {}
);
logger('Message received', { data, topic, observers });
observers.forEach(observer => {
try {
observer.next({
...parsedMessage,
...{ data },
})
} catch (err) {
logger(err);
}
});
}
}