@lokalise/fastify-bullboard-plugin 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2023 Lokalise
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,41 @@
1
+ # bull-board
2
+
3
+ Bull-board is a dashboard which provided a UI built on top of BullMQ or BullMQ Pro to help you visualize
4
+ your queues and their jobs.
5
+ It gives you the possibility of visualizing what's happening with each job in your queues, their status and some actions
6
+ that will enable you to get the job done.
7
+
8
+ Internally, we are using an open source library, [bull-board](https://github.com/felixmosh/bull-board), which provides
9
+ all the functionalities we mentioned above.
10
+
11
+ ## Adding bullboard to your app
12
+
13
+ Register a bullboard plugin in your fastify app:
14
+
15
+ ```ts
16
+ import fastify from 'fastify'
17
+ import { bullBoard, basicAuth } from '@lokalise/fastify-bullboard-plugin'
18
+ import { Queue } from 'bullmq'
19
+
20
+ const app = fastify()
21
+
22
+ await app.register(basicAuth, {
23
+ config: {
24
+ isEnabled: true,
25
+ username: 'username',
26
+ password: 'pass',
27
+ },
28
+ enableList: new Set(['/bull']),
29
+ })
30
+
31
+ await app.register(bullBoard, {
32
+ queueConstructor: Queue, // can be QueuePro if bullmq-pro is used
33
+ redisInstances: [
34
+ new Redis({
35
+ // some redis config
36
+ }),
37
+ ],
38
+ basePath: '/bull',
39
+ refreshIntervalInSeconds: config.bullBoard.refreshIntervalInSeconds,
40
+ })
41
+ ```
package/package.json ADDED
@@ -0,0 +1,76 @@
1
+ {
2
+ "name": "@lokalise/fastify-bullboard-plugin",
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "engines": {
6
+ "node": ">=20.13.0"
7
+ },
8
+ "license": "Apache-2.0",
9
+ "main": "./dist/index.js",
10
+ "module": "./dist/index.js",
11
+ "types": "./dist/index.d.ts",
12
+ "exports": {
13
+ ".": "./dist/index.js",
14
+ "./package.json": "./package.json"
15
+ },
16
+ "scripts": {
17
+ "build": "rimraf dist && tsc --project tsconfig.build.json",
18
+ "lint": "biome check . && tsc",
19
+ "lint:fix": "biome check --write",
20
+ "test": "vitest run",
21
+ "test:ci": "vitest run --coverage",
22
+ "prepublishOnly": "npm run build",
23
+ "package-version": "echo $npm_package_version",
24
+ "postversion": "biome check --write package.json"
25
+ },
26
+ "dependencies": {
27
+ "@bull-board/api": "^6.11.0",
28
+ "@bull-board/fastify": "^6.11.0",
29
+ "@fastify/auth": "^5.0.2",
30
+ "@fastify/basic-auth": "^6.2.0"
31
+ },
32
+ "peerDependencies": {
33
+ "@lokalise/background-jobs-common": ">=12.6.0"
34
+ },
35
+ "devDependencies": {
36
+ "@biomejs/biome": "^2.0.6",
37
+ "@lokalise/background-jobs-common": "^12.6.0",
38
+ "@lokalise/biome-config": "^3.0.0",
39
+ "@types/node": "^24.0.12",
40
+ "@vitest/coverage-v8": "^3.2.4",
41
+ "@fastify/awilix": "^8.0.0",
42
+ "@fastify/schedule": "^6.0.0",
43
+ "@lokalise/fastify-extras": "^27.4.0",
44
+ "@lokalise/node-core": "^14.1.0",
45
+ "awilix": "^12.0.5",
46
+ "awilix-manager": "^6.1.0",
47
+ "bullmq": "5.56.9",
48
+ "cross-env": "^10.0.0",
49
+ "fastify": "^5.4.0",
50
+ "fastify-graceful-shutdown": "^4.0.1",
51
+ "fastify-metrics": "^12.1.0",
52
+ "fastify-plugin": "^5.0.1",
53
+ "ioredis": "^5.6.1",
54
+ "pino": "^9.7.0",
55
+ "toad-scheduler": "^3.0.1",
56
+ "ts-deepmerge": "^7.0.3",
57
+ "pino-pretty": "^13.0.0",
58
+ "typescript": "5.8.3",
59
+ "vitest": "^3.2.4"
60
+ },
61
+ "keywords": [
62
+ "fastify",
63
+ "bullboard",
64
+ "bull",
65
+ "dashboard",
66
+ "plugin"
67
+ ],
68
+ "homepage": "https://github.com/lokalise/shared-ts-libs",
69
+ "repository": {
70
+ "type": "git",
71
+ "url": "git://github.com/lokalise/shared-ts-libs.git"
72
+ },
73
+ "publishConfig": {
74
+ "access": "public"
75
+ }
76
+ }
@@ -0,0 +1,79 @@
1
+ import fastify, { type FastifyInstance } from 'fastify'
2
+ import { beforeAll, describe, expect } from 'vitest'
3
+
4
+ import { basicAuth } from './basicAuth.js'
5
+
6
+ const skippedEndpoint = '/skipAuth'
7
+ const enabledEndpoint = '/'
8
+
9
+ async function initApp(authEnabled: boolean) {
10
+ const app = fastify()
11
+ await app.register(basicAuth, {
12
+ config: { isEnabled: authEnabled, username: 'test', password: 'test' },
13
+ enableList: new Set([enabledEndpoint]),
14
+ })
15
+
16
+ app.route({
17
+ method: 'GET',
18
+ url: '/',
19
+ handler: (_req, reply) => {
20
+ return reply.status(200).send({ hello: 'world' })
21
+ },
22
+ })
23
+
24
+ app.route({
25
+ method: 'GET',
26
+ url: skippedEndpoint,
27
+ handler: (_req, reply) => {
28
+ return reply.status(200).send({ hello: 'my friend' })
29
+ },
30
+ })
31
+
32
+ await app.ready()
33
+ return app
34
+ }
35
+
36
+ describe('basicAuth', () => {
37
+ let app: FastifyInstance
38
+
39
+ afterAll(async () => {
40
+ await app.close()
41
+ })
42
+
43
+ const performRequest = async (path: string) => app.inject().get(path).end()
44
+
45
+ describe('auth enabled', () => {
46
+ beforeAll(async () => {
47
+ app = await initApp(true)
48
+ })
49
+
50
+ it('returns 401 on not skipped endpoints', async () => {
51
+ const response = await performRequest('/')
52
+ expect(response.statusCode).toBe(401)
53
+ })
54
+
55
+ it('works on skipped endpoints', async () => {
56
+ const response = await performRequest(skippedEndpoint)
57
+ expect(response.statusCode).toBe(200)
58
+ expect(response.json()).toEqual({ hello: 'my friend' })
59
+ })
60
+ })
61
+
62
+ describe('auth disabled', () => {
63
+ beforeAll(async () => {
64
+ app = await initApp(false)
65
+ })
66
+
67
+ it('works on not skipped endpoints', async () => {
68
+ const response = await performRequest('/')
69
+ expect(response.statusCode).toBe(200)
70
+ expect(response.json()).toEqual({ hello: 'world' })
71
+ })
72
+
73
+ it('works on skipped endpoints', async () => {
74
+ const response = await performRequest(skippedEndpoint)
75
+ expect(response.statusCode).toBe(200)
76
+ expect(response.json()).toEqual({ hello: 'my friend' })
77
+ })
78
+ })
79
+ })
@@ -0,0 +1,67 @@
1
+ import type { FastifyAuthFunction } from '@fastify/auth'
2
+ import fastifyAuth from '@fastify/auth'
3
+ import fastifyBasicAuth from '@fastify/basic-auth'
4
+ import { AuthFailedError } from '@lokalise/node-core'
5
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'
6
+ import fp from 'fastify-plugin'
7
+
8
+ export type AuthConfig = {
9
+ isEnabled: boolean
10
+ username: string
11
+ password: string
12
+ }
13
+
14
+ type BasicAuthOptions = {
15
+ config: AuthConfig
16
+ enableList: Set<string>
17
+ }
18
+
19
+ function validate(config: AuthConfig) {
20
+ return (
21
+ username: string,
22
+ password: string,
23
+ _req: FastifyRequest,
24
+ _reply: FastifyReply,
25
+ done: (err?: Error) => void,
26
+ ) => {
27
+ if (username === config.username && password === config.password) {
28
+ done()
29
+ } else {
30
+ done(new AuthFailedError())
31
+ }
32
+ }
33
+ }
34
+
35
+ function enableListAuthHandler(enableList: Set<string>): FastifyAuthFunction {
36
+ return (req, _res, done) => {
37
+ if (req.routeOptions.url && !enableList.has(req.routeOptions.url)) {
38
+ return done()
39
+ }
40
+
41
+ return done(new AuthFailedError())
42
+ }
43
+ }
44
+
45
+ async function plugin(fastify: FastifyInstance, pluginOptions: BasicAuthOptions): Promise<void> {
46
+ if (!pluginOptions.config.isEnabled) {
47
+ return
48
+ }
49
+
50
+ await fastify.register(fastifyAuth)
51
+ await fastify.register(fastifyBasicAuth, {
52
+ validate: validate(pluginOptions.config),
53
+ authenticate: true,
54
+ })
55
+
56
+ fastify.after(() => {
57
+ fastify.addHook(
58
+ 'onRequest',
59
+ fastify.auth([enableListAuthHandler(pluginOptions.enableList), fastify.basicAuth]),
60
+ )
61
+ })
62
+ }
63
+
64
+ export const basicAuth = fp<BasicAuthOptions>(plugin, {
65
+ fastify: '>=4.0.0',
66
+ name: 'basic-auth',
67
+ })
@@ -0,0 +1,67 @@
1
+ import { Queue } from 'bullmq'
2
+ import fastify, { type FastifyInstance } from 'fastify'
3
+ import { beforeAll, expect } from 'vitest'
4
+ import { type BullBoardOptions, bullBoard, type QueueProConstructor } from './bullBoard.js'
5
+
6
+ const QueuePro: QueueProConstructor = Queue as QueueProConstructor
7
+
8
+ async function initApp(options: BullBoardOptions) {
9
+ const app = fastify()
10
+
11
+ await app.register(bullBoard, options)
12
+
13
+ await app.ready()
14
+ return app
15
+ }
16
+
17
+ describe('bull board', () => {
18
+ let app: FastifyInstance
19
+
20
+ afterAll(async () => {
21
+ await app.close()
22
+ })
23
+
24
+ describe('refresh disabled', () => {
25
+ beforeAll(async () => {
26
+ app = await initApp({
27
+ queueConstructor: QueuePro,
28
+ redisInstances: [],
29
+ basePath: '/test-disabled',
30
+ })
31
+ })
32
+
33
+ it('works', async () => {
34
+ const response = await app.inject().get('/test-disabled').end()
35
+
36
+ expect(response.statusCode).toBe(200)
37
+ expect(response.body.toLowerCase()).includes('<!doctype html>')
38
+ expect(response.body.toLowerCase()).includes('<title>bull dashboard</title>')
39
+
40
+ expect(app.scheduler).toBeUndefined()
41
+ })
42
+ })
43
+
44
+ describe('refresh enabled', () => {
45
+ beforeAll(async () => {
46
+ app = await initApp({
47
+ queueConstructor: Queue,
48
+ redisInstances: [],
49
+ basePath: '/test-enabled',
50
+ refreshIntervalInSeconds: 1,
51
+ })
52
+ })
53
+
54
+ it('works', async () => {
55
+ const response = await app.inject().get('/test-enabled').end()
56
+
57
+ expect(response.statusCode).toBe(200)
58
+ expect(response.body.toLowerCase()).includes('<!doctype html>')
59
+ expect(response.body.toLowerCase()).includes('<title>bull dashboard</title>')
60
+
61
+ expect(app.scheduler).toBeDefined()
62
+ const jobs = app.scheduler.getAllJobs()
63
+ expect(jobs).toHaveLength(1)
64
+ expect(jobs[0]!.id).toBe('bull-board-queues-update')
65
+ })
66
+ })
67
+ })
@@ -0,0 +1,112 @@
1
+ import { constants as httpConstants } from 'node:http2'
2
+ import { createBullBoard } from '@bull-board/api'
3
+ // @ts-ignore
4
+ import { BullMQAdapter } from '@bull-board/api/bullMQAdapter.js'
5
+ import { FastifyAdapter } from '@bull-board/fastify'
6
+ import fastifySchedule from '@fastify/schedule'
7
+ import {
8
+ backgroundJobProcessorGetActiveQueueIds,
9
+ QUEUE_GROUP_DELIMITER,
10
+ } from '@lokalise/background-jobs-common'
11
+ import { resolveGlobalErrorLogObject } from '@lokalise/node-core'
12
+ import type { Queue, QueueOptions, RedisConnection } from 'bullmq'
13
+ import type { FastifyInstance } from 'fastify'
14
+ import fp from 'fastify-plugin'
15
+ import type { Redis } from 'ioredis'
16
+ import { AsyncTask, SimpleIntervalJob } from 'toad-scheduler'
17
+
18
+ export type BullBoardOptions = {
19
+ queueConstructor: QueueProConstructor | QueueConstructor
20
+ redisInstances: Redis[]
21
+ basePath: string
22
+ refreshIntervalInSeconds?: number
23
+ }
24
+
25
+ function containStatusCode(error: Error): error is Error & { statusCode: number } {
26
+ return Object.hasOwn(error, 'statusCode')
27
+ }
28
+
29
+ const bullBoardErrorHandler = (error: Error) => {
30
+ const status = containStatusCode(error)
31
+ ? error.statusCode
32
+ : httpConstants.HTTP_STATUS_INTERNAL_SERVER_ERROR
33
+ return {
34
+ status: status,
35
+ body: { message: error.message, details: error.stack },
36
+ }
37
+ }
38
+
39
+ export interface QueueProConstructor {
40
+ new (name: string, opts?: Record<string, unknown>): Queue
41
+ }
42
+
43
+ export interface QueueConstructor {
44
+ new (name: string, opts?: QueueOptions, Connection?: typeof RedisConnection): Queue
45
+ }
46
+
47
+ async function getCurrentQueues(
48
+ redisInstances: Redis[],
49
+ queueConstructor: QueueProConstructor | QueueConstructor,
50
+ ): Promise<BullMQAdapter[]> {
51
+ const queueIds = await Promise.all(
52
+ redisInstances.map((redis) => backgroundJobProcessorGetActiveQueueIds(redis)),
53
+ )
54
+
55
+ return queueIds
56
+ .flatMap((ids, index) =>
57
+ // biome-ignore lint/style/noNonNullAssertion: Should exist
58
+ ids.map((id) => new queueConstructor(id, { connection: redisInstances[index]! })),
59
+ )
60
+ .map((queue) => new BullMQAdapter(queue, { delimiter: QUEUE_GROUP_DELIMITER }))
61
+ }
62
+
63
+ async function scheduleUpdates(
64
+ fastify: FastifyInstance,
65
+ bullBoard: ReturnType<typeof createBullBoard>,
66
+ pluginOptions: BullBoardOptions,
67
+ ) {
68
+ const { refreshIntervalInSeconds, redisInstances, queueConstructor } = pluginOptions
69
+
70
+ if (!refreshIntervalInSeconds || refreshIntervalInSeconds <= 0) return
71
+
72
+ const refreshTask = new AsyncTask(
73
+ 'Bull-board - update queues',
74
+ async () => {
75
+ fastify.log.debug({ refreshIntervalInSeconds }, 'Bull-dashboard -> updating queues')
76
+ bullBoard.replaceQueues(await getCurrentQueues(redisInstances, queueConstructor))
77
+ },
78
+ (e) => fastify.log.error(resolveGlobalErrorLogObject(e)),
79
+ )
80
+
81
+ await fastify.register(fastifySchedule)
82
+ fastify.scheduler.addSimpleIntervalJob(
83
+ new SimpleIntervalJob({ seconds: refreshIntervalInSeconds }, refreshTask, {
84
+ id: 'bull-board-queues-update',
85
+ preventOverrun: true,
86
+ }),
87
+ )
88
+ }
89
+
90
+ const plugin = async (fastify: FastifyInstance, pluginOptions: BullBoardOptions) => {
91
+ const { basePath, redisInstances, queueConstructor } = pluginOptions
92
+
93
+ const serverAdapter = new FastifyAdapter()
94
+ const bullBoard = createBullBoard({
95
+ queues: await getCurrentQueues(redisInstances, queueConstructor),
96
+ serverAdapter,
97
+ })
98
+ // biome-ignore lint/suspicious/noExplicitAny: bull-board is not exporting this type
99
+ serverAdapter.setErrorHandler(bullBoardErrorHandler as any)
100
+ serverAdapter.setBasePath(basePath)
101
+
102
+ await fastify.register(serverAdapter.registerPlugin(), {
103
+ prefix: basePath,
104
+ })
105
+
106
+ await scheduleUpdates(fastify, bullBoard, pluginOptions)
107
+ }
108
+
109
+ export const bullBoard = fp<BullBoardOptions>(plugin, {
110
+ fastify: '>=4.0.0',
111
+ name: 'bull-board',
112
+ })
@@ -0,0 +1,127 @@
1
+ import { type ErrorReporter, InternalError, PublicNonRecoverableError } from '@lokalise/node-core'
2
+ import fastify, { type FastifyInstance, type RouteHandlerMethod } from 'fastify'
3
+ import { pino } from 'pino'
4
+ import { afterAll, describe, expect, it, type MockInstance, vi } from 'vitest'
5
+
6
+ import { FakeErrorReporter } from '../test/FakeErrorReporter.js'
7
+ import { errorReporterPlugin } from './errorReporterPlugin.js'
8
+
9
+ async function initApp(routeHandler: RouteHandlerMethod, errorReporter: ErrorReporter) {
10
+ const app = fastify({
11
+ logger: true,
12
+ })
13
+ await app.register(errorReporterPlugin, { errorReporter })
14
+
15
+ app.route({
16
+ method: 'GET',
17
+ url: '/',
18
+ handler: routeHandler,
19
+ })
20
+
21
+ await app.ready()
22
+ return app
23
+ }
24
+
25
+ describe('errorHandlerPlugin', () => {
26
+ let app: FastifyInstance
27
+
28
+ afterAll(async () => {
29
+ await app.close()
30
+ })
31
+
32
+ const performRequest = async () => app.inject().get('/').end()
33
+
34
+ it('generic errors are reported', async () => {
35
+ const fakeErrorReporter = new FakeErrorReporter()
36
+ const error = new Error('Generic error')
37
+ let logSpy: MockInstance | undefined
38
+ app = await initApp((req) => {
39
+ logSpy = vi.spyOn(req.log, 'error')
40
+ throw error
41
+ }, fakeErrorReporter)
42
+
43
+ await performRequest()
44
+
45
+ expect(fakeErrorReporter.calls).length(1)
46
+ expect(fakeErrorReporter.calls[0]).toEqual({ error })
47
+ expect(logSpy).toHaveBeenCalledWith({
48
+ message: error.message,
49
+ error: pino.stdSerializers.err({
50
+ name: error.name,
51
+ message: error.message,
52
+ stack: error.stack,
53
+ }),
54
+ })
55
+ })
56
+
57
+ it('internal errors are reported', async () => {
58
+ const fakeErrorReporter = new FakeErrorReporter()
59
+ const error = new InternalError({
60
+ message: 'Internal error',
61
+ errorCode: 'INTERNAL_ERROR',
62
+ })
63
+ let logSpy: MockInstance | undefined
64
+ app = await initApp((req) => {
65
+ logSpy = vi.spyOn(req.log, 'error')
66
+ throw error
67
+ }, fakeErrorReporter)
68
+
69
+ await performRequest()
70
+
71
+ expect(fakeErrorReporter.calls).length(1)
72
+ expect(fakeErrorReporter.calls[0]).toEqual({ error })
73
+ expect(logSpy).toHaveBeenCalledWith({
74
+ message: error.message,
75
+ code: error.errorCode,
76
+ details: error.details ? JSON.stringify(error.details) : undefined,
77
+ error: pino.stdSerializers.err({
78
+ name: error.name,
79
+ message: error.message,
80
+ stack: error.stack,
81
+ }),
82
+ })
83
+ })
84
+
85
+ it('5xx errors are reported', async () => {
86
+ const fakeErrorReporter = new FakeErrorReporter()
87
+ const error = new PublicNonRecoverableError({
88
+ httpStatusCode: 500,
89
+ message: 'Internal error',
90
+ errorCode: 'INTERNAL_ERROR',
91
+ })
92
+ let logSpy: MockInstance | undefined
93
+ app = await initApp((req) => {
94
+ logSpy = vi.spyOn(req.log, 'error')
95
+ throw error
96
+ }, fakeErrorReporter)
97
+
98
+ await performRequest()
99
+
100
+ expect(fakeErrorReporter.calls).length(1)
101
+ expect(fakeErrorReporter.calls[0]).toEqual({ error })
102
+ expect(logSpy).toHaveBeenCalledWith({
103
+ message: error.message,
104
+ error: pino.stdSerializers.err({
105
+ name: error.name,
106
+ message: error.message,
107
+ stack: error.stack,
108
+ }),
109
+ })
110
+ })
111
+
112
+ it('4xx erros are ignored', async () => {
113
+ const fakeErrorReporter = new FakeErrorReporter()
114
+ const error = new PublicNonRecoverableError({
115
+ httpStatusCode: 400,
116
+ message: 'test',
117
+ errorCode: 'TEST',
118
+ })
119
+ app = await initApp(() => {
120
+ throw error
121
+ }, fakeErrorReporter)
122
+
123
+ await performRequest()
124
+
125
+ expect(fakeErrorReporter.calls).length(0)
126
+ })
127
+ })
@@ -0,0 +1,73 @@
1
+ import { constants as httpConstants } from 'node:http2'
2
+
3
+ import type { ErrorReporter } from '@lokalise/node-core'
4
+ import {
5
+ isError,
6
+ isInternalError,
7
+ isObject,
8
+ isPublicNonRecoverableError,
9
+ } from '@lokalise/node-core'
10
+ import type { FastifyInstance } from 'fastify'
11
+ import fp from 'fastify-plugin'
12
+ import { pino } from 'pino'
13
+
14
+ export type ErrorReporterOptions = {
15
+ errorReporter: ErrorReporter
16
+ }
17
+
18
+ function resolveLogObject(error: unknown): Record<string, unknown> {
19
+ if (isInternalError(error)) {
20
+ return {
21
+ message: error.message,
22
+ code: error.errorCode,
23
+ details: error.details ? JSON.stringify(error.details) : undefined,
24
+ error: pino.stdSerializers.err({
25
+ name: error.name,
26
+ message: error.message,
27
+ stack: error.stack,
28
+ }),
29
+ }
30
+ }
31
+ if (isError(error)) {
32
+ return {
33
+ message: error.message,
34
+ error: pino.stdSerializers.err({
35
+ name: error.name,
36
+ message: error.message,
37
+ stack: error.stack,
38
+ }),
39
+ }
40
+ }
41
+
42
+ return {
43
+ message: isObject(error) ? error.message : JSON.stringify(error),
44
+ error,
45
+ }
46
+ }
47
+
48
+ function plugin(
49
+ fastify: FastifyInstance,
50
+ pluginOptions: ErrorReporterOptions,
51
+ next: (err?: Error) => void,
52
+ ) {
53
+ fastify.addHook('onError', (request, _reply, error, done) => {
54
+ let statusCode = error.statusCode ?? httpConstants.HTTP_STATUS_INTERNAL_SERVER_ERROR
55
+ if (isPublicNonRecoverableError(error)) {
56
+ statusCode = error.httpStatusCode
57
+ }
58
+
59
+ if (statusCode >= httpConstants.HTTP_STATUS_INTERNAL_SERVER_ERROR) {
60
+ request.log.error(resolveLogObject(error))
61
+ pluginOptions.errorReporter.report({ error })
62
+ }
63
+
64
+ done()
65
+ })
66
+
67
+ next()
68
+ }
69
+
70
+ export const errorReporterPlugin = fp<ErrorReporterOptions>(plugin, {
71
+ fastify: '>=4.0.0',
72
+ name: 'error-reporter',
73
+ })
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export { type AuthConfig, basicAuth } from './basicAuth.js'
2
+ export { type BullBoardOptions, bullBoard, type QueueProConstructor } from './bullBoard.js'
3
+ export { type ErrorReporterOptions, errorReporterPlugin } from './errorReporterPlugin.js'
@@ -0,0 +1,18 @@
1
+ import type { ErrorReport } from '@lokalise/fastify-extras'
2
+ import type { ErrorReporter } from '@lokalise/node-core'
3
+
4
+ export class FakeErrorReporter implements ErrorReporter {
5
+ private _calls: ErrorReport[] = []
6
+
7
+ report(errorReport: ErrorReport): void {
8
+ this._calls.push(errorReport)
9
+ }
10
+
11
+ clean(): void {
12
+ this._calls = []
13
+ }
14
+
15
+ get calls(): ErrorReport[] {
16
+ return this._calls
17
+ }
18
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "extends": ["./tsconfig.json", "@lokalise/tsconfig/build-public-lib"],
3
+ "include": ["src/**/*"],
4
+ "exclude": ["src/**/*.spec.ts", "src/**/*.test.ts"]
5
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "extends": "@lokalise/tsconfig/tsc",
3
+ "include": ["src/**/*", "vitest.config.ts"],
4
+ "compilerOptions": {
5
+ "types": ["vitest/globals"]
6
+ }
7
+ }
@@ -0,0 +1,22 @@
1
+ import { defineConfig } from 'vitest/config'
2
+
3
+ // biome-ignore lint/style/noDefaultExport: vite expects default export
4
+ export default defineConfig({
5
+ test: {
6
+ globals: true,
7
+ watch: false,
8
+ restoreMocks: true,
9
+ pool: 'threads',
10
+ coverage: {
11
+ provider: 'v8',
12
+ include: ['src/**/*.ts'],
13
+ exclude: ['src/index.ts'],
14
+ thresholds: {
15
+ lines: 84,
16
+ functions: 80,
17
+ branches: 86,
18
+ statements: 84,
19
+ },
20
+ },
21
+ },
22
+ })