-
Notifications
You must be signed in to change notification settings - Fork 16
/
server.js
316 lines (263 loc) · 6.94 KB
/
server.js
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
'use strict';
const fs = require('fs')
const path = require('path')
const {Module} = require('./lib/mod')
const PipePair = require('./lib/pipe')
const PDK = require('./pdk')
const entities = ['Service', 'Consumer', 'Route', 'Plugin', 'Credential', 'MemoryStats']
const MSG_RET = 'ret'
const ERROR_NAME = 'PluginServerError'
const VALID_EXTENSIONS = new Set([
'.js',
'.ts',
'.node',
'.cjs',
''
])
class PluginServerError extends Error {
get name () {
return ERROR_NAME
}
constructor(...args) {
super(...args)
Error.captureStackTrace(this, this.constructor)
}
}
class Server {
get Error() {
return PluginServerError
}
static get Error() {
return PluginServerError
}
constructor(pluginDir, logger, expireTtl) {
this.pluginDir = pluginDir
this.logger = logger
this.plugins = new Map()
this.instances = new Map()
this.instanceID = 0
this.events = new Map()
this.eventID = 0
if (pluginDir) {
this.loadPlugins()
}
this.clearExpiredPluginsTimer = this.clearExpiredPlugins(expireTtl || 60)
}
loadPlugins() {
if (!this.pluginDir) {
throw new PluginServerError('plugin server is not initialized, call SetPluginDir first')
}
const files = fs.readdirSync(this.pluginDir)
for (const file of files) {
if (file.startsWith('.')) continue
if (/node_modules/.test(file)) continue
const file_path = require.resolve(path.join(this.pluginDir, file))
const {name, ext} = path.parse(file_path)
if (!name) continue
if (!VALID_EXTENSIONS.has(ext)) continue
const plugin = this.plugins.get(name)
if (plugin) {
this.logger.warn(
`plugin "${name}" is already loaded from ${plugin.path}, ` +
`trying to load from ${file_path}`
)
continue
}
try {
const mod = new Module(name, file_path)
this.plugins.set(mod.name, mod)
this.logger.debug(`loaded plugin "${mod.name}" from ${file_path}`)
} catch (ex) {
this.logger.warn(`error loading plugin "${name}" from ${file_path}: ${ex.stack}`)
}
};
}
clearExpiredPlugins(ttl) {
return setInterval(() => {
for (const [id, instance] of this.instances.entries()) {
if (instance.isExpired()) {
this.logger.debug(`cleanup instance #iid of ${instance.name}`)
this.instances.delete(id)
}
}
}, ttl)
}
close() {
clearInterval(this.clearExpiredPluginsTimer)
}
async SetPluginDir(dir) {
try {
await fs.promises.stat(dir)
} catch (err) {
if (err.code !== 'ENOENT') throw err
throw new PluginServerError(`${dir} does not exists`)
}
this.pluginDir = dir
this.loadPlugins()
return 'ok'
}
// RPC method
async GetStatus() {
const pluginStatus = Object.create(null)
for (const [name, plugin] of this.plugins.entries()) {
const instances = []
for (const iid in this.instances) {
instances.push(await this.InstanceStatus(iid))
}
pluginStatus[name] = {
Name: name,
Modtime: plugin.getMTime(),
LoadTime: plugin.getLoadTime(),
Instances: instances,
LastStartInstance: plugin.getLastStartInstanceTime(),
LastCloseInstance: plugin.getLastCloseInstanceTime(),
}
}
return {
Pid: process.pid,
Plugins: pluginStatus
}
}
// RPC method
async GetPluginInfo(name) {
const plugin = this.plugins.get(name)
if (!name || !plugin) {
throw new PluginServerError(`${name} not initizlied`)
}
return {
Name: name,
Version: plugin.getVersion(),
Phases: plugin.getPhases(),
Priority: plugin.getPriority(),
Schema: {
name: name,
fields: [{
config: {
type: 'record',
fields: plugin.getSchema(),
}
}],
},
}
}
// RPC method
async StartInstance(cfg) {
const name = cfg.Name
const plugin = this.plugins.get(name)
if (!plugin) {
throw new PluginServerError(`${name} not initizlied`)
}
const config = JSON.parse(cfg.Config)
const iid = this.instanceID++
this.instances.set(iid, plugin.new(config))
this.logger.info(`instance #${iid} of ${name} started`)
return {
Name: name,
Id: iid,
Config: config,
StartTime: Date.now() / 1000,
}
}
// RPC method
async InstanceStatus(iid) {
const ins = this.instances.get(iid)
if (!ins) {
// Note: Kong expect the error to start with "no plugin instance"
throw new PluginServerError(`no plugin instance #${iid}`)
}
return {
Name: ins.getName(),
Id: iid,
Config: ins.getConfig(),
StartTime: ins.getStartTime(),
}
}
// RPC method
async CloseInstance(iid) {
let ins = this.instances.get(iid)
if (!ins) {
// Note: Kong expect the error to start with "no plugin instance"
throw new PluginServerError(`no plugin instance #${iid}`)
}
ins.close()
this.instances.delete(iid)
return {
Name: ins.getName(),
Id: iid,
Config: ins.getConfig(),
}
}
// RPC method
async HandleEvent(event) {
const iid = event.InstanceId
const ins = this.instances.get(iid)
if (!ins) {
// Note: Kong expect the error to start with "no plugin instance"
throw new PluginServerError(`no plugin instance #${iid}`)
}
ins.resetExpireTs()
const phase = event.EventName
const eid = this.eventID++
const [ch, childCh] = new PipePair().getPair()
this.events.set(eid, ch)
// https://snyk.io/blog/nodejs-how-even-quick-async-functions-can-block-the-event-loop-starve-io/
setImmediate(async () => {
try {
await ins.executePhase(phase, new PDK(childCh).kong)
} catch(ex){
this.logger.warn(
`unhandled exception in ${ins.name}.${phase} on instance #${iid}: ${ex}`
)
}
childCh.put(MSG_RET)
})
const r = await ch.get()
ins.resetExpireTs()
return {
Data: r,
EventId: eid,
}
}
async step(data, isError) {
const din = data.Data
const eid = data.EventId
const ch = this.events.get(eid)
if (!ch) {
throw new PluginServerError(`event id ${eid} not found`)
}
if (isError) {
await ch.put([ undefined, din ])
} else {
await ch.put([ din, undefined ])
}
const ret = await ch.get()
if (ret === MSG_RET) this.events.delete(eid)
return {
Data: ret,
EventId: eid
}
}
// RPC method
async Step(data) {
return this.step(data, false)
}
// RPC method
async StepError(err) {
return this.step(err, true)
}
// RPC method
async StepMultiMap(data) {
return this.step(data, false)
}
getLogger() {
return this.logger
}
getPlugins() {
return this.plugins
}
}
// Generate other RPC methods
for (const entity of entities) {
Server.prototype['Step' + entity] = Server.prototype.Step
}
module.exports = Server