navi-hey 1.0.0 → 1.1.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.
Files changed (62) hide show
  1. package/bin/navi.js +3 -3
  2. package/lib/{factories → background}/JobFactory.js +2 -2
  3. package/lib/{registry → background}/JobRegistry.js +17 -0
  4. package/lib/{registry → background}/JobRegistryInstance.js +42 -1
  5. package/lib/{models → background}/Worker.js +5 -3
  6. package/lib/{factories → background}/WorkerFactory.js +2 -2
  7. package/lib/{registry → background}/WorkersRegistryInstance.js +1 -1
  8. package/lib/{models → enqueuers}/ActionEnqueuer.js +4 -1
  9. package/lib/{models → enqueuers}/AssetRequestEnqueuer.js +6 -2
  10. package/lib/exceptions/ConflictError.js +14 -0
  11. package/lib/{models → jobs}/ActionProcessingJob.js +4 -4
  12. package/lib/{models → jobs}/AssetDownloadJob.js +6 -6
  13. package/lib/{models → jobs}/HtmlParseJob.js +6 -6
  14. package/lib/{models → jobs}/ResourceRequestJob.js +11 -11
  15. package/lib/models/ResourceRequest.js +5 -2
  16. package/lib/models/ResourceRequestAction.js +6 -3
  17. package/lib/models/WebConfig.js +5 -1
  18. package/lib/registry/LogRegistry.js +146 -0
  19. package/lib/registry/LogRegistryInstance.js +156 -0
  20. package/lib/serializers/JobIndexSerializer.js +10 -3
  21. package/lib/serializers/LogSerializer.js +26 -0
  22. package/lib/server/EngineContinueRequestHandler.js +34 -0
  23. package/lib/server/EnginePauseRequestHandler.js +34 -0
  24. package/lib/server/EngineRestartRequestHandler.js +34 -0
  25. package/lib/server/EngineShutdownRequestHandler.js +29 -0
  26. package/lib/server/EngineStartRequestHandler.js +34 -0
  27. package/lib/server/EngineStatusRequestHandler.js +27 -0
  28. package/lib/server/EngineStopRequestHandler.js +34 -0
  29. package/lib/server/JobLogsRequestHandler.js +39 -0
  30. package/lib/server/JobRequestHandler.js +1 -1
  31. package/lib/server/JobRetryRequestHandler.js +40 -0
  32. package/lib/server/JobsFilter.js +55 -0
  33. package/lib/server/JobsRequestHandler.js +5 -2
  34. package/lib/server/LogsRequestHandler.js +55 -0
  35. package/lib/server/RouteRegister.js +40 -7
  36. package/lib/server/Router.js +43 -25
  37. package/lib/server/SettingsRequestHandler.js +34 -0
  38. package/lib/server/StatsRequestHandler.js +2 -2
  39. package/lib/server/WebServer.js +28 -8
  40. package/lib/services/Application.js +138 -84
  41. package/lib/services/ApplicationInstance.js +272 -0
  42. package/lib/services/Client.js +22 -18
  43. package/lib/services/Engine.js +51 -6
  44. package/lib/services/EngineEvents.js +42 -0
  45. package/lib/services/FailureChecker.js +4 -4
  46. package/lib/services/WorkersAllocator.js +2 -2
  47. package/lib/utils/HtmlElementParser.js +5 -4
  48. package/lib/utils/HtmlParser.js +4 -4
  49. package/lib/utils/PromiseAggregator.js +11 -5
  50. package/lib/utils/logging/BufferedLogger.js +8 -0
  51. package/lib/utils/logging/LogBuffer.js +25 -5
  52. package/lib/utils/logging/LogBufferCollection.js +56 -0
  53. package/lib/utils/logging/LogContext.js +51 -0
  54. package/lib/utils/logging/LogFilter.js +34 -0
  55. package/package.json +1 -1
  56. package/static/assets/index-BfggoMvd.js +11 -0
  57. package/static/assets/{index-DBkz-poX.css → index-CuWjW0sT.css} +1 -1
  58. package/static/index.html +2 -2
  59. /package/lib/{models → background}/Job.js +0 -0
  60. /package/lib/{registry → background}/WorkersRegistry.js +0 -0
  61. /package/lib/{models → enqueuers}/ActionsEnqueuer.js +0 -0
  62. /package/lib/{factories → factory}/Factory.js +0 -0
@@ -0,0 +1,156 @@
1
+ import { BufferedLogger } from '../utils/logging/BufferedLogger.js';
2
+ import { LogBufferCollection } from '../utils/logging/LogBufferCollection.js';
3
+ import { LogFilter } from '../utils/logging/LogFilter.js';
4
+ import { Logger } from '../utils/logging/Logger.js';
5
+ import { LoggerGroup } from '../utils/logging/LoggerGroup.js';
6
+
7
+ /**
8
+ * Holds a LoggerGroup (Logger + BufferedLogger) for the LogRegistry singleton.
9
+ * Exposes debug/info/warn/error methods that fan out to both outputs, and filtered
10
+ * log queries via LogFilter. Not exported directly; accessed only via LogRegistry.
11
+ * @author darthjee
12
+ */
13
+ class LogRegistryInstance {
14
+ #bufferedLogger;
15
+ #loggerGroup;
16
+ #jobLogs;
17
+ #workerLogs;
18
+
19
+ /**
20
+ * Creates a new LogRegistryInstance.
21
+ * @param {object} [options={}] - Options for the loggers.
22
+ * @param {string} [options.level] - Log level threshold.
23
+ * @param {number} [options.retention=100] - Maximum number of logs to retain.
24
+ */
25
+ constructor({ level, retention } = {}) {
26
+ this.#bufferedLogger = new BufferedLogger(level, retention);
27
+ this.#loggerGroup = new LoggerGroup([Logger.default(), this.#bufferedLogger]);
28
+ this.#jobLogs = new LogBufferCollection(retention);
29
+ this.#workerLogs = new LogBufferCollection(retention);
30
+ }
31
+
32
+ /**
33
+ * Returns the underlying BufferedLogger instance.
34
+ * @returns {BufferedLogger}
35
+ */
36
+ get bufferedLogger() {
37
+ return this.#bufferedLogger;
38
+ }
39
+
40
+ /**
41
+ * Logs a debug message to both the console and the buffer.
42
+ * @param {string} message - The message to log.
43
+ * @param {object} [attributes={}] - Optional structured metadata.
44
+ * @returns {void}
45
+ */
46
+ debug(message, attributes = {}) {
47
+ this.#dispatch('debug', message, attributes);
48
+ }
49
+
50
+ /**
51
+ * Logs an error message to both the console and the buffer.
52
+ * @param {string} message - The message to log.
53
+ * @param {object} [attributes={}] - Optional structured metadata.
54
+ * @returns {void}
55
+ */
56
+ error(message, attributes = {}) {
57
+ this.#dispatch('error', message, attributes);
58
+ }
59
+
60
+ /**
61
+ * Gets a specific log by ID.
62
+ * @param {number} id
63
+ * @returns {import('../utils/logging/Log.js').Log|undefined}
64
+ */
65
+ getLogById(id) {
66
+ return this.#bufferedLogger.getLogById(id);
67
+ }
68
+
69
+ /**
70
+ * Gets logs in chronological order (oldest first), optionally filtered to entries newer than lastId.
71
+ * @param {object} [options={}]
72
+ * @param {number|string} [options.lastId] - When provided, returns only logs newer than this ID.
73
+ * Returns an empty array if the ID is not found.
74
+ * @returns {Array<import('../utils/logging/Log.js').Log>}
75
+ */
76
+ getLogs({ lastId } = {}) {
77
+ return new LogFilter(this.bufferedLogger.getLogs()).filter({ lastId });
78
+ }
79
+
80
+ /**
81
+ * Gets logs stored in the per-job buffer for the given job ID,
82
+ * optionally filtered to entries newer than lastId.
83
+ * @param {string|number} jobId
84
+ * @param {object} [options={}]
85
+ * @param {number|string} [options.lastId] - When provided, returns only logs newer than this ID.
86
+ * @returns {Array<import('../utils/logging/Log.js').Log>}
87
+ */
88
+ getLogsByJobId(jobId, { lastId } = {}) {
89
+ return new LogFilter(this.#jobLogs.getLogs(jobId)).filter({ lastId });
90
+ }
91
+
92
+ /**
93
+ * Gets logs stored in the per-worker buffer for the given worker ID.
94
+ * @param {string|number} workerId
95
+ * @returns {Array<import('../utils/logging/Log.js').Log>}
96
+ */
97
+ getLogsByWorkerId(workerId) {
98
+ return this.#workerLogs.getLogs(workerId);
99
+ }
100
+
101
+ /**
102
+ * Gets logs filtered by level.
103
+ * @param {string} level
104
+ * @returns {Array<import('../utils/logging/Log.js').Log>}
105
+ */
106
+ getLogsByLevel(level) {
107
+ return this.#bufferedLogger.getLogsByLevel(level);
108
+ }
109
+
110
+ /**
111
+ * Returns all logs as plain JSON objects.
112
+ * @returns {Array<object>}
113
+ */
114
+ getLogsJSON() {
115
+ return this.#bufferedLogger.getLogsJSON();
116
+ }
117
+
118
+ /**
119
+ * Logs an info message to both the console and the buffer.
120
+ * @param {string} message - The message to log.
121
+ * @param {object} [attributes={}] - Optional structured metadata.
122
+ * @returns {void}
123
+ */
124
+ info(message, attributes = {}) {
125
+ this.#dispatch('info', message, attributes);
126
+ }
127
+
128
+ /**
129
+ * Logs a warn message to both the console and the buffer.
130
+ * @param {string} message - The message to log.
131
+ * @param {object} [attributes={}] - Optional structured metadata.
132
+ * @returns {void}
133
+ */
134
+ warn(message, attributes = {}) {
135
+ this.#dispatch('warn', message, attributes);
136
+ }
137
+
138
+ /**
139
+ * Fans out the log call to the logger group and, if a new log was buffered,
140
+ * routes it to the per-job and per-worker collections based on attributes.
141
+ * @param {string} level
142
+ * @param {string} message
143
+ * @param {object} attributes
144
+ * @returns {void}
145
+ */
146
+ #dispatch(level, message, attributes) {
147
+ const before = this.#bufferedLogger.latestLog;
148
+ this.#loggerGroup[level](message, attributes);
149
+ const log = this.#bufferedLogger.latestLog;
150
+ if (log === before) return;
151
+ if (attributes.jobId !== undefined) this.#jobLogs.push(attributes.jobId, log);
152
+ if (attributes.workerId !== undefined) this.#workerLogs.push(attributes.workerId, log);
153
+ }
154
+ }
155
+
156
+ export { LogRegistryInstance };
@@ -6,20 +6,27 @@ import { Serializer } from './Serializer.js';
6
6
  */
7
7
  class JobIndexSerializer extends Serializer {
8
8
  /**
9
- * Serializes a single job instance into a `{ id, status, attempts, jobClass }` object.
9
+ * Serializes a single job instance into a `{ id, status, attempts, jobClass[, url] }` object.
10
+ * For `ResourceRequestJob` instances, the resolved URL is included as `url`.
10
11
  *
11
12
  * @param {object} job - A job instance.
12
13
  * @param {object} options - Serialization options.
13
14
  * @param {string} options.status - The status label to embed in the serialized object.
14
- * @returns {{ id: string, status: string, attempts: number, jobClass: string }} The serialized job data.
15
+ * @returns {{ id: string, status: string, attempts: number, jobClass: string, url?: string }} The serialized job data.
15
16
  */
16
17
  static _serializeObject(job, { status }) {
17
- return {
18
+ const result = {
18
19
  id: job.id,
19
20
  status,
20
21
  attempts: job._attempts,
21
22
  jobClass: job.constructor.name,
22
23
  };
24
+
25
+ if (job.constructor.name === 'ResourceRequestJob') {
26
+ result.url = job.arguments?.url;
27
+ }
28
+
29
+ return result;
23
30
  }
24
31
  }
25
32
 
@@ -0,0 +1,26 @@
1
+ import { Serializer } from './Serializer.js';
2
+
3
+ /**
4
+ * Serializes one or more Log instances into plain data objects.
5
+ * @augments Serializer
6
+ * @author darthjee
7
+ */
8
+ class LogSerializer extends Serializer {
9
+ /**
10
+ * Serializes a single Log instance.
11
+ *
12
+ * @param {import('../utils/logging/Log.js').Log} log - The log entry to serialize.
13
+ * @returns {{ id: number, level: string, message: string, attributes: object, timestamp: string }}
14
+ */
15
+ static _serializeObject(log) {
16
+ return {
17
+ id: log.id,
18
+ level: log.level,
19
+ message: log.message,
20
+ attributes: log.attributes,
21
+ timestamp: log.timestamp.toISOString(),
22
+ };
23
+ }
24
+ }
25
+
26
+ export { LogSerializer };
@@ -0,0 +1,34 @@
1
+ import { RequestHandler } from './RequestHandler.js';
2
+ import { ConflictError } from '../exceptions/ConflictError.js';
3
+ import { Application } from '../services/Application.js';
4
+
5
+ /**
6
+ * Handles PATCH /engine/continue requests.
7
+ * Returns 409 Conflict if the engine is not in 'paused' status.
8
+ * @author darthjee
9
+ */
10
+ class EngineContinueRequestHandler extends RequestHandler {
11
+ /**
12
+ * Creates a new EngineContinueRequestHandler instance.
13
+ */
14
+ constructor() {
15
+ super();
16
+ }
17
+
18
+ /**
19
+ * Resumes engine processing after a pause.
20
+ * @param {object} _req - The Express request object.
21
+ * @param {object} res - The Express response object.
22
+ * @returns {Promise<void>}
23
+ */
24
+ async handle(_req, res) {
25
+ if (!Application.isPaused()) {
26
+ throw new ConflictError();
27
+ }
28
+
29
+ await Application.continue();
30
+ res.json({ status: 'running' });
31
+ }
32
+ }
33
+
34
+ export { EngineContinueRequestHandler };
@@ -0,0 +1,34 @@
1
+ import { RequestHandler } from './RequestHandler.js';
2
+ import { ConflictError } from '../exceptions/ConflictError.js';
3
+ import { Application } from '../services/Application.js';
4
+
5
+ /**
6
+ * Handles PATCH /engine/pause requests.
7
+ * Returns 409 Conflict if the engine is not in 'running' status.
8
+ * @author darthjee
9
+ */
10
+ class EnginePauseRequestHandler extends RequestHandler {
11
+ /**
12
+ * Creates a new EnginePauseRequestHandler instance.
13
+ */
14
+ constructor() {
15
+ super();
16
+ }
17
+
18
+ /**
19
+ * Initiates engine pause. Responds immediately with the transitional status.
20
+ * @param {object} _req - The Express request object.
21
+ * @param {object} res - The Express response object.
22
+ * @returns {Promise<void>}
23
+ */
24
+ async handle(_req, res) {
25
+ if (!Application.isRunning()) {
26
+ throw new ConflictError();
27
+ }
28
+
29
+ Application.pause();
30
+ res.json({ status: 'pausing' });
31
+ }
32
+ }
33
+
34
+ export { EnginePauseRequestHandler };
@@ -0,0 +1,34 @@
1
+ import { RequestHandler } from './RequestHandler.js';
2
+ import { ConflictError } from '../exceptions/ConflictError.js';
3
+ import { Application } from '../services/Application.js';
4
+
5
+ /**
6
+ * Handles PATCH /engine/restart requests.
7
+ * Returns 409 Conflict if the engine is not in 'running' status.
8
+ * @author darthjee
9
+ */
10
+ class EngineRestartRequestHandler extends RequestHandler {
11
+ /**
12
+ * Creates a new EngineRestartRequestHandler instance.
13
+ */
14
+ constructor() {
15
+ super();
16
+ }
17
+
18
+ /**
19
+ * Initiates engine restart. Responds immediately with the transitional status.
20
+ * @param {object} _req - The Express request object.
21
+ * @param {object} res - The Express response object.
22
+ * @returns {Promise<void>}
23
+ */
24
+ async handle(_req, res) {
25
+ if (!Application.isRunning()) {
26
+ throw new ConflictError();
27
+ }
28
+
29
+ Application.restart();
30
+ res.json({ status: 'stopping' });
31
+ }
32
+ }
33
+
34
+ export { EngineRestartRequestHandler };
@@ -0,0 +1,29 @@
1
+ import { RequestHandler } from './RequestHandler.js';
2
+ import { Application } from '../services/Application.js';
3
+
4
+ /**
5
+ * Handles PATCH /engine/shutdown requests.
6
+ * Shuts down the web server and stops the engine.
7
+ * @author darthjee
8
+ */
9
+ class EngineShutdownRequestHandler extends RequestHandler {
10
+ /**
11
+ * Creates a new EngineShutdownRequestHandler instance.
12
+ */
13
+ constructor() {
14
+ super();
15
+ }
16
+
17
+ /**
18
+ * Initiates server shutdown. Responds immediately with the transitional status.
19
+ * @param {object} _req - The Express request object.
20
+ * @param {object} res - The Express response object.
21
+ * @returns {void}
22
+ */
23
+ handle(_req, res) {
24
+ Application.shutdown();
25
+ res.json({ status: 'stopping' });
26
+ }
27
+ }
28
+
29
+ export { EngineShutdownRequestHandler };
@@ -0,0 +1,34 @@
1
+ import { RequestHandler } from './RequestHandler.js';
2
+ import { ConflictError } from '../exceptions/ConflictError.js';
3
+ import { Application } from '../services/Application.js';
4
+
5
+ /**
6
+ * Handles PATCH /engine/start requests.
7
+ * Returns 409 Conflict if the engine is not in 'stopped' status.
8
+ * @author darthjee
9
+ */
10
+ class EngineStartRequestHandler extends RequestHandler {
11
+ /**
12
+ * Creates a new EngineStartRequestHandler instance.
13
+ */
14
+ constructor() {
15
+ super();
16
+ }
17
+
18
+ /**
19
+ * Starts engine processing from a stopped state, re-enqueueing initial jobs.
20
+ * @param {object} _req - The Express request object.
21
+ * @param {object} res - The Express response object.
22
+ * @returns {Promise<void>}
23
+ */
24
+ async handle(_req, res) {
25
+ if (!Application.isStopped()) {
26
+ throw new ConflictError();
27
+ }
28
+
29
+ await Application.start();
30
+ res.json({ status: 'running' });
31
+ }
32
+ }
33
+
34
+ export { EngineStartRequestHandler };
@@ -0,0 +1,27 @@
1
+ import { RequestHandler } from './RequestHandler.js';
2
+ import { Application } from '../services/Application.js';
3
+
4
+ /**
5
+ * Handles GET /engine/status requests.
6
+ * @author darthjee
7
+ */
8
+ class EngineStatusRequestHandler extends RequestHandler {
9
+ /**
10
+ * Creates a new EngineStatusRequestHandler instance.
11
+ */
12
+ constructor() {
13
+ super();
14
+ }
15
+
16
+ /**
17
+ * Responds with the current engine status.
18
+ * @param {object} _req - The Express request object.
19
+ * @param {object} res - The Express response object.
20
+ * @returns {void}
21
+ */
22
+ handle(_req, res) {
23
+ res.json({ status: Application.status() });
24
+ }
25
+ }
26
+
27
+ export { EngineStatusRequestHandler };
@@ -0,0 +1,34 @@
1
+ import { RequestHandler } from './RequestHandler.js';
2
+ import { ConflictError } from '../exceptions/ConflictError.js';
3
+ import { Application } from '../services/Application.js';
4
+
5
+ /**
6
+ * Handles PATCH /engine/stop requests.
7
+ * Returns 409 Conflict if the engine is not in 'running' status.
8
+ * @author darthjee
9
+ */
10
+ class EngineStopRequestHandler extends RequestHandler {
11
+ /**
12
+ * Creates a new EngineStopRequestHandler instance.
13
+ */
14
+ constructor() {
15
+ super();
16
+ }
17
+
18
+ /**
19
+ * Initiates engine stop. Responds immediately with the transitional status.
20
+ * @param {object} _req - The Express request object.
21
+ * @param {object} res - The Express response object.
22
+ * @returns {Promise<void>}
23
+ */
24
+ async handle(_req, res) {
25
+ if (!Application.isRunning()) {
26
+ throw new ConflictError();
27
+ }
28
+
29
+ Application.stop();
30
+ res.json({ status: 'stopping' });
31
+ }
32
+ }
33
+
34
+ export { EngineStopRequestHandler };
@@ -0,0 +1,39 @@
1
+ import { RequestHandler } from './RequestHandler.js';
2
+ import { LogRegistry } from '../registry/LogRegistry.js';
3
+ import { LogSerializer } from '../serializers/LogSerializer.js';
4
+
5
+ /**
6
+ * Handles GET /jobs/:job_id/logs.json requests.
7
+ * Returns a paginated list of log entries for the given job, optionally
8
+ * filtered to entries newer than last_id.
9
+ * An unknown job_id returns an empty array.
10
+ * @author darthjee
11
+ */
12
+ class JobLogsRequestHandler extends RequestHandler {
13
+ #pageSize;
14
+
15
+ /**
16
+ * Creates a new JobLogsRequestHandler.
17
+ * @param {object} [options={}]
18
+ * @param {number} [options.pageSize=20] - Maximum number of log entries to return.
19
+ */
20
+ constructor({ pageSize = 20 } = {}) {
21
+ super();
22
+ this.#pageSize = pageSize;
23
+ }
24
+
25
+ /**
26
+ * Responds with a paginated JSON array of log entries for the given job.
27
+ * @param {object} req - The Express request object.
28
+ * @param {object} res - The Express response object.
29
+ * @returns {void}
30
+ */
31
+ handle(req, res) {
32
+ const { job_id: jobId } = req.params;
33
+ const { last_id: lastId } = req.query;
34
+ const logs = LogRegistry.getLogsByJobId(jobId, { lastId });
35
+ res.json(LogSerializer.serialize(logs.slice(0, this.#pageSize)));
36
+ }
37
+ }
38
+
39
+ export { JobLogsRequestHandler };
@@ -1,6 +1,6 @@
1
1
  import { RequestHandler } from './RequestHandler.js';
2
+ import { JobRegistry } from '../background/JobRegistry.js';
2
3
  import { NotFoundError } from '../exceptions/NotFoundError.js';
3
- import { JobRegistry } from '../registry/JobRegistry.js';
4
4
  import { JobSerializer } from '../serializers/JobSerializer.js';
5
5
 
6
6
  /**
@@ -0,0 +1,40 @@
1
+ import { RequestHandler } from './RequestHandler.js';
2
+ import { JobRegistry } from '../background/JobRegistry.js';
3
+ import { ConflictError } from '../exceptions/ConflictError.js';
4
+ import { NotFoundError } from '../exceptions/NotFoundError.js';
5
+
6
+ const RETRYABLE_STATUSES = new Set(['failed', 'dead']);
7
+
8
+ /**
9
+ * Handles PATCH /jobs/:id/retry requests.
10
+ * Moves a failed or dead job directly to the retry queue.
11
+ * Returns 404 if the job does not exist, 409 if it is not in a retryable state.
12
+ * @author darthjee
13
+ */
14
+ class JobRetryRequestHandler extends RequestHandler {
15
+ /**
16
+ * Creates a new JobRetryRequestHandler instance.
17
+ */
18
+ constructor() {
19
+ super();
20
+ }
21
+
22
+ /**
23
+ * Retries the specified job by moving it to the retry queue.
24
+ * @param {object} req - The Express request object.
25
+ * @param {object} res - The Express response object.
26
+ * @returns {void}
27
+ */
28
+ handle(req, res) {
29
+ const { id } = req.params;
30
+ const result = JobRegistry.jobById(id);
31
+
32
+ if (!result) throw new NotFoundError('Job not found');
33
+ if (!RETRYABLE_STATUSES.has(result.status)) throw new ConflictError();
34
+
35
+ JobRegistry.retryJob(id);
36
+ res.json({ status: 'enqueued' });
37
+ }
38
+ }
39
+
40
+ export { JobRetryRequestHandler };
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Filters a job collection by one or more job classes.
3
+ * @author darthjee
4
+ */
5
+ class JobsFilter {
6
+ /**
7
+ * Creates a new JobsFilter instance.
8
+ * @param {object[]} jobs - The collection of jobs to filter.
9
+ * @param {object} [filters={}] - The filters object (e.g. `{ class: ['ResourceRequestJob'] }`).
10
+ */
11
+ constructor(jobs, filters = {}) {
12
+ this._jobs = jobs;
13
+ this._filters = filters;
14
+ }
15
+
16
+ /**
17
+ * Returns the filtered job list.
18
+ * When no class filter is provided, all jobs are returned unchanged.
19
+ * @returns {object[]} The filtered jobs.
20
+ */
21
+ filter() {
22
+ const classes = this.#normalizeClasses();
23
+
24
+ if (classes.length === 0) {
25
+ return this._jobs;
26
+ }
27
+
28
+ return this._jobs.filter((job) => this.#matchesClass(job, classes));
29
+ }
30
+
31
+ /**
32
+ * Returns true when the job's class is listed in the requested classes.
33
+ * @param {object} job - A job instance.
34
+ * @param {string[]} classes - The list of accepted class names.
35
+ * @returns {boolean}
36
+ */
37
+ #matchesClass(job, classes) {
38
+ return classes.includes(job.constructor.name);
39
+ }
40
+
41
+ /**
42
+ * Normalises the class filter value to an array.
43
+ * Express's qs parser collapses a single `filters[class][]=Foo` to a plain string.
44
+ * @returns {string[]} The normalised array of class names.
45
+ */
46
+ #normalizeClasses() {
47
+ const value = this._filters.class;
48
+
49
+ if (!value) return [];
50
+ if (Array.isArray(value)) return value;
51
+ return [value];
52
+ }
53
+ }
54
+
55
+ export { JobsFilter };
@@ -1,5 +1,6 @@
1
+ import { JobsFilter } from './JobsFilter.js';
1
2
  import { RequestHandler } from './RequestHandler.js';
2
- import { JobRegistry } from '../registry/JobRegistry.js';
3
+ import { JobRegistry } from '../background/JobRegistry.js';
3
4
  import { JobSerializer } from '../serializers/JobSerializer.js';
4
5
 
5
6
  /**
@@ -23,7 +24,9 @@ class JobsRequestHandler extends RequestHandler {
23
24
  handle(req, res) {
24
25
  const { status } = req.params;
25
26
  const jobs = JobRegistry.jobsByStatus(status);
26
- res.json(JobSerializer.serialize(jobs, { status, view: 'index' }));
27
+ const filters = req.query.filters || {};
28
+ const filteredJobs = new JobsFilter(jobs, filters).filter();
29
+ res.json(JobSerializer.serialize(filteredJobs, { status, view: 'index' }));
27
30
  }
28
31
  }
29
32
 
@@ -0,0 +1,55 @@
1
+ import { RequestHandler } from './RequestHandler.js';
2
+ import { LogRegistry } from '../registry/LogRegistry.js';
3
+ import { LogSerializer } from '../serializers/LogSerializer.js';
4
+
5
+ /**
6
+ * Handles GET /logs.json requests.
7
+ * Routes to per-job or per-worker buffers via optional `jobId` / `workerId` query params.
8
+ * Returns 400 when both params are present simultaneously.
9
+ * @author darthjee
10
+ */
11
+ class LogsRequestHandler extends RequestHandler {
12
+ #pageSize;
13
+
14
+ /**
15
+ * Creates a new LogsRequestHandler.
16
+ * @param {object} [options={}]
17
+ * @param {number} [options.pageSize=20] - Maximum number of log entries to return.
18
+ */
19
+ constructor({ pageSize = 20 } = {}) {
20
+ super();
21
+ this.#pageSize = pageSize;
22
+ }
23
+
24
+ /**
25
+ * Responds with a paginated JSON array of log entries.
26
+ * @param {object} req - The Express request object.
27
+ * @param {object} res - The Express response object.
28
+ * @returns {void}
29
+ */
30
+ handle(req, res) {
31
+ const { last_id: lastId, jobId, workerId } = req.query;
32
+
33
+ if (jobId && workerId) {
34
+ res.status(400).json({ error: 'Cannot specify both jobId and workerId' });
35
+ return;
36
+ }
37
+
38
+ if (jobId) {
39
+ const logs = LogRegistry.getLogsByJobId(jobId);
40
+ res.json(LogSerializer.serialize(logs.slice(0, this.#pageSize)));
41
+ return;
42
+ }
43
+
44
+ if (workerId) {
45
+ const logs = LogRegistry.getLogsByWorkerId(workerId);
46
+ res.json(LogSerializer.serialize(logs.slice(0, this.#pageSize)));
47
+ return;
48
+ }
49
+
50
+ const logs = LogRegistry.getLogs({ lastId });
51
+ res.json(LogSerializer.serialize(logs.slice(0, this.#pageSize)));
52
+ }
53
+ }
54
+
55
+ export { LogsRequestHandler };