-
-
Notifications
You must be signed in to change notification settings - Fork 129
/
index.ts
248 lines (237 loc) · 7.71 KB
/
index.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
241
242
243
244
245
246
247
248
import { PubSub } from "graphql-subscriptions";
import { EventEmitter } from "events";
import createDebugger from "debug";
import { PostGraphilePlugin } from "postgraphile";
import PgGenericSubscriptionPlugin from "./PgGenericSubscriptionPlugin";
import PgSubscriptionResolverPlugin from "./PgSubscriptionResolverPlugin";
import * as pg from "pg";
const RECONNECT_BASE_DELAY = 100;
const RECONNECT_MAX_DELAY = 30000;
declare module "postgraphile" {
interface PostGraphileOptions {
simpleSubscriptions?: boolean;
subscriptionAuthorizationFunction?: string;
subscriptionEventEmitterMaxListeners?: number;
}
}
declare module "graphile-build" {
interface Options {
pubsub: PubSub;
}
}
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
const debugSubscriptions = createDebugger("postgraphile:subscriptions");
const plugin: PostGraphilePlugin = {
["cli:flags:add:schema"](addFlag) {
addFlag(
"-S, --simple-subscriptions",
"⚡️[experimental] add simple subscription support"
);
addFlag(
"--subscription-authorization-function [schemaDotFunctionName]",
"⚡️[experimental] PG function to call to check user is allowed to subscribe"
);
return addFlag;
},
["cli:library:options"](options, { config, cliOptions }) {
const {
simpleSubscriptions = false,
subscriptionAuthorizationFunction = null,
} = {
...config.options,
...cliOptions,
};
return {
...options,
simpleSubscriptions,
subscriptionAuthorizationFunction,
};
},
["postgraphile:options"](incomingOptions, { pgPool }) {
const eventEmitter = new EventEmitter();
if (incomingOptions.subscriptionEventEmitterMaxListeners != null) {
eventEmitter.setMaxListeners(
incomingOptions.subscriptionEventEmitterMaxListeners
);
}
const {
simpleSubscriptions,
subscriptionAuthorizationFunction,
} = incomingOptions;
const pubsub = new PubSub({
eventEmitter,
});
const handleNotification = function (msg: {
channel: string;
payload?: string;
}) {
let payload;
if (msg.payload) {
try {
payload = JSON.parse(msg.payload);
} catch (e) {
debugSubscriptions("Failed to parse payload JSON");
debugSubscriptions(e);
// ignore
}
}
pubsub.publish(msg.channel, payload);
};
let listeningClient: pg.PoolClient | null;
const cleanClient = function (client: pg.PoolClient) {
client.removeListener("notification", handleNotification);
clearInterval(client["keepAliveInterval"]);
delete client["keepAliveInterval"];
if (client === listeningClient) {
listeningClient = null;
}
};
const releaseClient = function (client: pg.PoolClient): void {
if (!client) {
return;
}
if (client) {
cleanClient(client);
client.release();
}
};
const listenToChannelWithClient = async function (
client: pg.PoolClient,
channel: string
): Promise<void> {
const sql = "LISTEN " + client.escapeIdentifier(channel);
await client.query(sql);
};
const unlistenFromChannelWithClient = async function (
client: pg.PoolClient,
channel: string
): Promise<void> {
const sql = "UNLISTEN " + client.escapeIdentifier(channel);
await client.query(sql);
};
const channelListenCount: { [key: string]: number } = {};
const listen = async function (channel: string) {
channelListenCount[channel] = (channelListenCount[channel] || 0) + 1;
if (channelListenCount[channel] === 1 && listeningClient) {
await listenToChannelWithClient(listeningClient, channel);
}
};
const unlisten = async function (channel: string) {
channelListenCount[channel] = (channelListenCount[channel] || 1) - 1;
if (channelListenCount[channel] === 0 && listeningClient) {
await unlistenFromChannelWithClient(listeningClient, channel);
}
};
const aL = eventEmitter.addListener;
eventEmitter.addListener = function (name, hook) {
if (typeof name === "string") {
listen(name).catch(e => {
// eslint-disable-next-line no-console
console.error("Error occurred when unlistening:", e.message);
});
}
return aL.call(this, name, hook);
};
const rL = eventEmitter.removeListener;
eventEmitter.removeListener = function (name, hook) {
if (typeof name === "string") {
unlisten(name).catch(e => {
// eslint-disable-next-line no-console
console.error("Error occurred when unlistening:", e.message);
});
}
return rL.call(this, name, hook);
};
const setupClient = async function (attempts = 0): Promise<void> {
if (attempts > 0 && attempts % 5 === 0) {
// eslint-disable-next-line no-console
console.warn(
`WARNING: @graphile/pg-pubsub cannot establish a connection to the server; reattempting with exponential backoff (attempt ${attempts})`
);
}
// Permanently check client out of the pool
let client: pg.PoolClient;
try {
client = await pgPool.connect();
} catch (e) {
// Exponential back-off
const delay = Math.floor(
Math.min(
RECONNECT_MAX_DELAY,
RECONNECT_BASE_DELAY * Math.random() * 2 ** attempts
)
);
await sleep(delay);
return setupClient(attempts + 1);
}
listeningClient = client;
listeningClient.addListener("notification", handleNotification);
// Every 25 seconds, send 'select 1' to keep the connection alive
client["keepAliveInterval"] = setInterval(() => {
client.query("select 1").catch(e => {
// eslint-disable-next-line no-console
console.error(
"Listen client keepalive error (will attempt reconnect):"
);
// eslint-disable-next-line no-console
console.error(e);
releaseClient(client);
if (!pgPool.ending) {
setupClient();
}
});
}, 25000);
const channels = Object.entries(channelListenCount)
.filter(([_channel, count]) => count > 0)
.map(([channel]) => channel);
try {
await Promise.all(
channels.map(channel => listenToChannelWithClient(client, channel))
);
} catch (e) {
// eslint-disable-next-line no-console
console.error(
`Error occurred when listening to channel; retrying after ${
attempts * 2
} seconds`
);
// eslint-disable-next-line no-console
console.error(e);
releaseClient(client);
if (!pgPool.ending) {
await sleep(attempts * 2000);
return setupClient(attempts + 1);
}
}
};
setupClient().catch(e => {
// eslint-disable-next-line no-console
console.error(
"Error occurred when trying to set up initial client. Current state is undefined. Suggest server restart.",
e
);
});
pgPool.on("remove", (client: pg.PoolClient) => {
if (client === listeningClient) {
cleanClient(client);
if (!pgPool.ending) {
setupClient();
}
}
});
return {
...incomingOptions,
graphileBuildOptions: {
...incomingOptions.graphileBuildOptions,
pubsub,
pgSubscriptionAuthorizationFunction: subscriptionAuthorizationFunction,
},
appendPlugins: [
...(incomingOptions.appendPlugins || []),
PgSubscriptionResolverPlugin,
...(simpleSubscriptions ? [PgGenericSubscriptionPlugin] : []),
],
};
},
};
export default plugin;