-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathindex.js
197 lines (170 loc) · 5.21 KB
/
index.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
// @ts-check
import { Worker } from 'node:worker_threads'
import { performance } from 'node:perf_hooks'
import { v4 as uuidv4 } from 'uuid'
import { waitForVariableToBeTrue } from './lib/utils.js'
/** @type {import('trifid-core/types').TrifidPlugin} */
export const factory = async (trifid) => {
const { config, logger, trifidEvents } = trifid
const { contentType, url, baseIri, graphName, unionDefaultGraph } = config
const queryLogLevel = config.queryLogLevel || 'debug'
if (!logger[queryLogLevel]) {
throw Error(`Invalid queryLogLevel: ${queryLogLevel}`)
}
/**
* Log a query, depending on the `queryLogLevel`.
* @param {string} msg Message to log
* @returns {void}
*/
const queryLogger = (msg) => logger[queryLogLevel](msg)
const queryTimeout = 30000
const workerUrl = new URL('./lib/worker.js', import.meta.url)
const worker = new Worker(workerUrl)
let ready = false
let stopWait = false
trifidEvents.on('close', async () => {
logger.debug('Got "close" event from Trifid ; closing worker…')
await worker.terminate()
logger.debug('Worker terminated')
})
worker.on('message', async (message) => {
const { type, data } = message
if (type === 'log') {
logger.debug(data)
}
if (type === 'ready') {
if (!data) {
logger.error('There was an error in the worker during initialization.')
}
ready = data
stopWait = true
}
})
worker.on('error', (error) => {
ready = false
logger.error(`Error from worker: ${error.message}`)
})
worker.on('exit', (code) => {
ready = false
logger.info(`Worker exited with code ${code}`)
})
worker.postMessage({
type: 'config',
data: {
contentType, url, baseIri, graphName, unionDefaultGraph,
},
})
/**
* Send the query to the worker and wait for the response.
*
* @param {string} query The SPARQL query
* @returns {Promise<{ response: string, contentType: string }>} The response and its content type
*/
const handleQuery = async (query) => {
return new Promise((resolve, reject) => {
if (!ready) {
return reject(new Error('Worker is not ready'))
}
const queryId = uuidv4()
const timeoutId = setTimeout(() => {
worker.off('message', messageHandler)
reject(new Error(`Query timed out after ${queryTimeout / 1000} seconds`))
}, queryTimeout)
worker.postMessage({
type: 'query',
data: {
queryId,
query,
},
})
const messageHandler = (message) => {
const { type, data } = message
if (type === 'query' && data.queryId === queryId) {
clearTimeout(timeoutId)
worker.off('message', messageHandler)
if (!data.success) {
reject(new Error(data.response))
return
}
resolve(data)
}
}
worker.on('message', messageHandler)
})
}
// Wait for the worker to become ready, so we can be sure it can handle queries
await waitForVariableToBeTrue(
() => stopWait,
30000,
20,
'Worker did not become ready within 30 seconds',
)
if (!ready) {
await worker.terminate()
logger.debug('Worker terminated')
throw new Error('Worker initialization error')
}
return {
defaultConfiguration: async () => {
return {
methods: ['GET', 'POST'],
paths: ['/query'],
}
},
routeHandler: async () => {
/**
* Query string type.
*
* @typedef {Object} QueryString
* @property {string} [query] The SPARQL query.
*/
/**
* Request body type.
* @typedef {Object} RequestBody
* @property {string} [query] The SPARQL query.
*/
/**
* Route handler.
* @param {import('fastify').FastifyRequest<{ Querystring: QueryString, Body: RequestBody}>} request Request.
* @param {import('fastify').FastifyReply} reply Reply.
*/
const handler = async (request, reply) => {
let query
const method = request.method
if (method === 'GET') {
query = request.query.query
} else if (method === 'POST') {
query = request.body.query
if (!query && request.body) {
query = request.body
if (typeof query !== 'string') {
query = JSON.stringify(query)
}
}
}
if (!query) {
reply.status(400).send('Missing query parameter')
return reply
}
queryLogger(`Received query via ${method}:\n${query}`)
try {
const start = performance.now()
const { response, contentType } = await handleQuery(query)
const end = performance.now()
const duration = end - start
reply.type(contentType)
reply.header('Server-Timing', `handler-fetch;dur=${duration};desc="Query execution time"`)
logger.debug(`Sending the following ${contentType} response:\n${response}`)
reply.status(200).send(response)
} catch (error) {
logger.error(error)
reply.status(500).send(error.message)
return reply
}
return reply
}
return handler
},
}
}
export default factory