navi-hey 0.4.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 (77) hide show
  1. package/bin/navi.js +9 -0
  2. package/lib/exceptions/AppError.js +13 -0
  3. package/lib/exceptions/ClientNotFound.js +16 -0
  4. package/lib/exceptions/ConfigurationFileNotFound.js +10 -0
  5. package/lib/exceptions/ConfigurationFileNotProvided.js +10 -0
  6. package/lib/exceptions/InvalidResponseBody.js +19 -0
  7. package/lib/exceptions/ItemNotFound.js +16 -0
  8. package/lib/exceptions/LockedByOtherWorker.js +14 -0
  9. package/lib/exceptions/MissingActionResource.js +13 -0
  10. package/lib/exceptions/MissingClientsConfig.js +14 -0
  11. package/lib/exceptions/MissingMappingVariable.js +17 -0
  12. package/lib/exceptions/MissingResourceConfig.js +14 -0
  13. package/lib/exceptions/MissingTopLevelConfgKey.js +15 -0
  14. package/lib/exceptions/NullResponse.js +13 -0
  15. package/lib/exceptions/RequestFailed.js +16 -0
  16. package/lib/exceptions/ResourceNotFound.js +16 -0
  17. package/lib/factories/Factory.js +79 -0
  18. package/lib/factories/JobFactory.js +82 -0
  19. package/lib/factories/WorkerFactory.js +35 -0
  20. package/lib/models/ActionEnqueuer.js +34 -0
  21. package/lib/models/ActionProcessingJob.js +51 -0
  22. package/lib/models/ActionsEnqueuer.js +42 -0
  23. package/lib/models/Config.js +68 -0
  24. package/lib/models/Job.js +87 -0
  25. package/lib/models/ParametersMapper.js +43 -0
  26. package/lib/models/PathResolver.js +77 -0
  27. package/lib/models/PathSegmentTraverser.js +82 -0
  28. package/lib/models/Resource.js +47 -0
  29. package/lib/models/ResourceRequest.js +80 -0
  30. package/lib/models/ResourceRequestAction.js +73 -0
  31. package/lib/models/ResourceRequestJob.js +61 -0
  32. package/lib/models/ResponseParser.js +36 -0
  33. package/lib/models/ResponseWrapper.js +86 -0
  34. package/lib/models/WebConfig.js +15 -0
  35. package/lib/models/Worker.js +57 -0
  36. package/lib/models/WorkersConfig.js +18 -0
  37. package/lib/registry/ClientRegistry.js +92 -0
  38. package/lib/registry/JobRegistry.js +125 -0
  39. package/lib/registry/JobRegistryInstance.js +149 -0
  40. package/lib/registry/NamedRegistry.js +73 -0
  41. package/lib/registry/ResourceRegistry.js +91 -0
  42. package/lib/registry/WorkersRegistry.js +106 -0
  43. package/lib/registry/WorkersRegistryInstance.js +139 -0
  44. package/lib/server/RequestHandler.js +15 -0
  45. package/lib/server/RouteRegister.js +27 -0
  46. package/lib/server/Router.js +44 -0
  47. package/lib/server/StatsRequestHandler.js +31 -0
  48. package/lib/server/WebServer.js +45 -0
  49. package/lib/services/Application.js +113 -0
  50. package/lib/services/ArgumentsParser.js +36 -0
  51. package/lib/services/Client.js +108 -0
  52. package/lib/services/ConfigLoader.js +75 -0
  53. package/lib/services/ConfigParser.js +131 -0
  54. package/lib/services/Engine.js +67 -0
  55. package/lib/services/WorkersAllocator.js +74 -0
  56. package/lib/utils/EnvResolver.js +53 -0
  57. package/lib/utils/PromiseAggregator.js +37 -0
  58. package/lib/utils/ResourceRequestCollector.js +35 -0
  59. package/lib/utils/collections/Collection.js +17 -0
  60. package/lib/utils/collections/IdentifyableCollection.js +86 -0
  61. package/lib/utils/collections/Queue.js +45 -0
  62. package/lib/utils/collections/SortedArrayMerger.js +84 -0
  63. package/lib/utils/collections/SortedArraySearcher.js +101 -0
  64. package/lib/utils/collections/SortedCollection.js +169 -0
  65. package/lib/utils/generators/IdGenerator.js +79 -0
  66. package/lib/utils/generators/IncrementalIdGenerator.js +25 -0
  67. package/lib/utils/generators/UUidGenerator.js +49 -0
  68. package/lib/utils/index.js +2 -0
  69. package/lib/utils/logging/BaseLogger.js +93 -0
  70. package/lib/utils/logging/BufferedLogger.js +91 -0
  71. package/lib/utils/logging/ConsoleLogger.js +19 -0
  72. package/lib/utils/logging/Log.js +70 -0
  73. package/lib/utils/logging/LogBuffer.js +101 -0
  74. package/lib/utils/logging/LogFactory.js +32 -0
  75. package/lib/utils/logging/Logger.js +134 -0
  76. package/lib/utils/logging/LoggerGroup.js +100 -0
  77. package/package.json +78 -0
@@ -0,0 +1,106 @@
1
+ import { WorkersRegistryInstance } from './WorkersRegistryInstance.js';
2
+
3
+ /**
4
+ * WorkersRegistry is a static singleton facade for managing the application's worker pool.
5
+ *
6
+ * Call `WorkersRegistry.build(options)` once during application bootstrap.
7
+ * Use `WorkersRegistry.reset()` in tests to restore a clean state between examples.
8
+ * @author darthjee
9
+ */
10
+ class WorkersRegistry {
11
+ static #instance = null;
12
+
13
+ /**
14
+ * Creates and stores the singleton instance.
15
+ * @param {object} [options={}] - Forwarded to `WorkersRegistryInstance` constructor.
16
+ * @returns {WorkersRegistryInstance} The created instance.
17
+ * @throws {Error} If `build()` has already been called without a preceding `reset()`.
18
+ */
19
+ static build(options = {}) {
20
+ if (WorkersRegistry.#instance) {
21
+ throw new Error('WorkersRegistry.build() has already been called. Call reset() first.');
22
+ }
23
+ WorkersRegistry.#instance = new WorkersRegistryInstance(options);
24
+ return WorkersRegistry.#instance;
25
+ }
26
+
27
+ /**
28
+ * Destroys the singleton instance. Intended for test teardown.
29
+ * @returns {void}
30
+ */
31
+ static reset() {
32
+ WorkersRegistry.#instance = null;
33
+ }
34
+
35
+ /**
36
+ * Initializes the specified number of workers.
37
+ * @returns {void}
38
+ */
39
+ static initWorkers() {
40
+ return WorkersRegistry.#getInstance().initWorkers();
41
+ }
42
+
43
+ /**
44
+ * Sets a worker as busy.
45
+ * @param {string} id - The ID of the worker to set as busy.
46
+ * @returns {void}
47
+ */
48
+ static setBusy(id) {
49
+ return WorkersRegistry.#getInstance().setBusy(id);
50
+ }
51
+
52
+ /**
53
+ * Sets a worker as idle.
54
+ * @param {string} id - The ID of the worker to set as idle.
55
+ * @returns {void}
56
+ */
57
+ static setIdle(id) {
58
+ return WorkersRegistry.#getInstance().setIdle(id);
59
+ }
60
+
61
+ /**
62
+ * Checks if there is at least one busy worker.
63
+ * @returns {boolean} True if there is at least one busy worker, false otherwise.
64
+ */
65
+ static hasBusyWorker() {
66
+ return WorkersRegistry.#getInstance().hasBusyWorker();
67
+ }
68
+
69
+ /**
70
+ * Checks if there is at least one idle worker.
71
+ * @returns {boolean} True if there is at least one idle worker, false otherwise.
72
+ */
73
+ static hasIdleWorker() {
74
+ return WorkersRegistry.#getInstance().hasIdleWorker();
75
+ }
76
+
77
+ /**
78
+ * Gets an idle worker if available.
79
+ * @returns {Worker|null} An idle worker if available, or null if no idle workers are present.
80
+ */
81
+ static getIdleWorker() {
82
+ return WorkersRegistry.#getInstance().getIdleWorker();
83
+ }
84
+
85
+ /**
86
+ * Returns counts of workers in each state.
87
+ * @returns {{ idle: number, busy: number }} Counts of workers in each state.
88
+ */
89
+ static stats() {
90
+ return WorkersRegistry.#getInstance().stats();
91
+ }
92
+
93
+ /**
94
+ * Returns the singleton instance, throwing if not yet built.
95
+ * @returns {WorkersRegistryInstance} The singleton instance.
96
+ * @throws {Error} If `build()` has not been called.
97
+ */
98
+ static #getInstance() {
99
+ if (!WorkersRegistry.#instance) {
100
+ throw new Error('WorkersRegistry has not been built. Call WorkersRegistry.build() first.');
101
+ }
102
+ return WorkersRegistry.#instance;
103
+ }
104
+ }
105
+
106
+ export { WorkersRegistry };
@@ -0,0 +1,139 @@
1
+ import { WorkerFactory } from '../factories/WorkerFactory.js';
2
+ import { IdentifyableCollection } from '../utils/collections/IdentifyableCollection.js';
3
+
4
+ /**
5
+ * WorkersRegistryInstance manages the creation and tracking of Worker instances.
6
+ * @author darthjee
7
+ */
8
+ class WorkersRegistryInstance {
9
+ #factory;
10
+ #quantity;
11
+ #workers;
12
+ #busy;
13
+ #idle;
14
+
15
+ /**
16
+ * Creates a new WorkersRegistryInstance.
17
+ * @param {object} params - The parameters for creating a WorkersRegistryInstance.
18
+ * @param {WorkerFactory} [params.factory] - The factory for creating Worker instances (injected for testing).
19
+ * @param {number} params.quantity - The number of workers to be built.
20
+ * @param {IdentifyableCollection} [params.workers] - The collection of all workers (injected for testing).
21
+ * @param {IdentifyableCollection} [params.busy] - The collection of busy workers (injected for testing).
22
+ * @param {IdentifyableCollection} [params.idle] - The collection of idle workers (injected for testing).
23
+ * @param {object} [params.jobRegistry] - The job registry to inject into each Worker.
24
+ * @param {object} [params.workersRegistry] - The workers registry to inject into each Worker.
25
+ */
26
+ constructor({
27
+ quantity,
28
+ factory,
29
+ workers = new IdentifyableCollection(),
30
+ busy = new IdentifyableCollection(),
31
+ idle = new IdentifyableCollection(),
32
+ jobRegistry,
33
+ workersRegistry
34
+ }) {
35
+ this.#factory = factory || new WorkerFactory({ jobRegistry, workersRegistry });
36
+ this.#quantity = quantity;
37
+ this.#workers = workers;
38
+ this.#busy = busy;
39
+ this.#idle = idle;
40
+ }
41
+
42
+ /**
43
+ * Initializes the specified number of workers
44
+ *
45
+ * This method creates the workers and adds them to the internal workers list,
46
+ * marking them as idle.
47
+ * @returns {void}
48
+ */
49
+ initWorkers() {
50
+ for (let i = 0; i < this.#quantity; i++) {
51
+ this.#buildWorker();
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Sets a worker as busy.
57
+ * @param {string} workerId - The ID of the worker to set as busy.
58
+ * @returns {void}
59
+ */
60
+ setBusy(workerId) {
61
+ const worker = this.#workers.get(workerId);
62
+
63
+ if (worker) {
64
+ this.#idle.remove(workerId);
65
+ this.#busy.push(worker);
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Sets a worker as idle.
71
+ * @param {string} workerId - The ID of the worker to set as idle.
72
+ * @returns {void}
73
+ */
74
+ setIdle(workerId) {
75
+ const worker = this.#workers.get(workerId);
76
+
77
+ if (worker) {
78
+ this.#busy.remove(workerId);
79
+ this.#idle.push(worker);
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Checks if there is at least one busy worker.
85
+ * @returns {boolean} True if there is at least one busy worker, false otherwise.
86
+ */
87
+ hasBusyWorker() {
88
+ return this.#busy.hasAny();
89
+ }
90
+
91
+ /**
92
+ * Checks if there is at least one idle worker.
93
+ * @returns {boolean} True if there is at least one idle worker, false otherwise.
94
+ */
95
+ hasIdleWorker() {
96
+ return this.#idle.hasAny();
97
+ }
98
+
99
+ /**
100
+ * Gets an idle worker if available.
101
+ * @returns {Worker|null} An idle worker if available, or null if no idle workers are present.
102
+ */
103
+ getIdleWorker() {
104
+ if (!this.hasIdleWorker()) {
105
+ return null;
106
+ }
107
+ const workerId = this.#idle.byIndex(0).id;
108
+
109
+ this.setBusy(workerId);
110
+
111
+ return this.#workers.get(workerId);
112
+ }
113
+
114
+ /**
115
+ * Returns counts of workers in each state.
116
+ * @returns {{ idle: number, busy: number }} Counts of workers in each state.
117
+ */
118
+ stats() {
119
+ return {
120
+ idle: this.#idle.size(),
121
+ busy: this.#busy.size(),
122
+ };
123
+ }
124
+
125
+ /**
126
+ * Builds a new Worker with a unique UUID and adds it to the internal workers list.
127
+ * @returns {Worker} The newly created Worker instance.
128
+ */
129
+ #buildWorker() {
130
+ const worker = this.#factory.build();
131
+
132
+ this.#workers.push(worker);
133
+ this.#idle.push(worker);
134
+
135
+ return worker;
136
+ }
137
+ }
138
+
139
+ export { WorkersRegistryInstance };
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Base class for request handlers.
3
+ * @author darthjee
4
+ */
5
+ class RequestHandler {
6
+ /**
7
+ * Handles an incoming HTTP request.
8
+ * @param {object} _req - The Express request object.
9
+ * @param {object} _res - The Express response object.
10
+ * @returns {void}
11
+ */
12
+ handle(_req, _res) {}
13
+ }
14
+
15
+ export { RequestHandler };
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Registers a route on an Express router by binding the handler's handle method.
3
+ * @author darthjee
4
+ */
5
+ class RouteRegister {
6
+ #router;
7
+
8
+ /**
9
+ * @param {object} router - An Express Router instance.
10
+ */
11
+ constructor(router) {
12
+ this.#router = router;
13
+ }
14
+
15
+ /**
16
+ * Registers a GET route on the router.
17
+ * @param {object} params - Options for registering a route.
18
+ * @param {string} params.route - The route path (e.g. '/stats.json').
19
+ * @param {object} params.handler - The handler whose handle method is called.
20
+ * @returns {void}
21
+ */
22
+ register({ route, handler }) {
23
+ this.#router.get(route, (req, res) => handler.handle(req, res));
24
+ }
25
+ }
26
+
27
+ export { RouteRegister };
@@ -0,0 +1,44 @@
1
+ import path from 'path';
2
+ import { fileURLToPath } from 'url';
3
+ import express from 'express';
4
+ import { RouteRegister } from './RouteRegister.js';
5
+ import { StatsRequestHandler } from './StatsRequestHandler.js';
6
+
7
+ const { Router: ExpressRouter } = express;
8
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
9
+ const publicDir = path.join(__dirname, '../../public');
10
+
11
+ /**
12
+ * Builds the Express router with all application routes.
13
+ * @author darthjee
14
+ */
15
+ class Router {
16
+ /**
17
+ * Creates a new Router instance.
18
+ */
19
+ constructor() {}
20
+
21
+ /**
22
+ * Creates and returns an Express Router with all routes registered.
23
+ * @returns {object} An Express Router instance.
24
+ */
25
+ build() {
26
+ const router = ExpressRouter();
27
+ const register = new RouteRegister(router);
28
+
29
+ register.register({
30
+ route: '/stats.json',
31
+ handler: new StatsRequestHandler(),
32
+ });
33
+
34
+ router.use(express.static(publicDir));
35
+
36
+ router.use((_req, res) => {
37
+ res.sendFile(path.join(publicDir, 'index.html'));
38
+ });
39
+
40
+ return router;
41
+ }
42
+ }
43
+
44
+ export { Router };
@@ -0,0 +1,31 @@
1
+ import { RequestHandler } from './RequestHandler.js';
2
+ import { JobRegistry } from '../registry/JobRegistry.js';
3
+ import { WorkersRegistry } from '../registry/WorkersRegistry.js';
4
+
5
+ /**
6
+ * Handles GET /stats.json requests.
7
+ * @author darthjee
8
+ */
9
+ class StatsRequestHandler extends RequestHandler {
10
+ /**
11
+ * Creates a new StatsRequestHandler instance.
12
+ */
13
+ constructor() {
14
+ super();
15
+ }
16
+
17
+ /**
18
+ * Responds with combined job and worker stats.
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
+ res.json({
25
+ jobs: JobRegistry.stats(),
26
+ workers: WorkersRegistry.stats(),
27
+ });
28
+ }
29
+ }
30
+
31
+ export { StatsRequestHandler };
@@ -0,0 +1,45 @@
1
+ import express from 'express';
2
+ import { Router } from './Router.js';
3
+ import { Logger } from '../utils/logging/Logger.js';
4
+
5
+ /**
6
+ * Express web server for the Navi monitoring interface.
7
+ * @author darthjee
8
+ */
9
+ class WebServer {
10
+ #port;
11
+ #app;
12
+
13
+ /**
14
+ * @param {object} params - Options for initializing the WebServer.
15
+ * @param {number} params.port - Port to listen on.
16
+ */
17
+ constructor({ port }) {
18
+ this.#port = port;
19
+ this.#app = express();
20
+ this.#app.use(new Router().build());
21
+ }
22
+
23
+ /**
24
+ * Starts the Express server on the configured port.
25
+ * The returned http.Server can be used to close the server (e.g. in tests).
26
+ * @returns {http.Server} The http.Server instance.
27
+ */
28
+ start() {
29
+ Logger.info(`Listening to port ${this.#port}`);
30
+ return this.#app.listen(this.#port);
31
+ }
32
+
33
+ /**
34
+ * Factory method. Returns a WebServer when webConfig is present, null otherwise.
35
+ * @param {object} params - Options for building the WebServer.
36
+ * @param {object|null} params.webConfig - The web configuration object.
37
+ * @returns {WebServer|null} A WebServer instance if webConfig is provided, otherwise null.
38
+ */
39
+ static build({ webConfig }) {
40
+ if (!webConfig) return null;
41
+ return new WebServer({ port: webConfig.port });
42
+ }
43
+ }
44
+
45
+ export { WebServer };
@@ -0,0 +1,113 @@
1
+ import { Engine } from './Engine.js';
2
+ import { ConfigurationFileNotProvided } from '../exceptions/ConfigurationFileNotProvided.js';
3
+ import { JobFactory } from '../factories/JobFactory.js';
4
+ import { ActionProcessingJob } from '../models/ActionProcessingJob.js';
5
+ import { Config } from '../models/Config.js';
6
+ import { JobRegistry } from '../registry/JobRegistry.js';
7
+ import { WorkersRegistry } from '../registry/WorkersRegistry.js';
8
+ import { WebServer } from '../server/WebServer.js';
9
+ import { PromiseAggregator } from '../utils/PromiseAggregator.js';
10
+ import { ResourceRequestCollector } from '../utils/ResourceRequestCollector.js';
11
+
12
+ /**
13
+ * Application orchestrates the startup of Navi by loading configuration,
14
+ * building registries, and running the Engine loop together with the WebServer.
15
+ * @author darthjee
16
+ */
17
+ class Application {
18
+ #workers;
19
+
20
+ /**
21
+ * Creates a new Application instance.
22
+ * @param {object} [params={}] - Optional parameters for dependency injection.
23
+ * @param {IdentifyableCollection} [params.workers] - Workers collection (injected for testing).
24
+ */
25
+ constructor({ workers } = {}) {
26
+ this.#workers = workers;
27
+ }
28
+
29
+ /**
30
+ * Loads the configuration from the specified file path.
31
+ * @param {string} configPath - The path to the configuration file.
32
+ * @throws {ConfigurationFileNotProvided} If the configuration file path is not provided.
33
+ * @throws {ConfigurationFileNotFound} If the configuration file is not found at the specified path.
34
+ * @returns {void}
35
+ */
36
+ loadConfig(configPath) {
37
+ if (!configPath) {
38
+ throw new ConfigurationFileNotProvided();
39
+ }
40
+
41
+ // Load the configuration from the specified path.
42
+ this.config = Config.fromFile(configPath);
43
+ this.#initRegistries();
44
+ }
45
+
46
+ /**
47
+ * Starts the application by building the engine, web server, enqueueing initial jobs, and starting both.
48
+ * @returns {Promise<void>}
49
+ */
50
+ async run() {
51
+ const aggregator = new PromiseAggregator();
52
+
53
+ this.engine = this.buildEngine();
54
+ this.webServer = this.buildWebServer();
55
+ this.enqueueFirstJobs();
56
+
57
+ aggregator.add(this.webServer?.start());
58
+ aggregator.add(this.engine.start());
59
+
60
+ await aggregator.wait();
61
+ }
62
+
63
+ /**
64
+ * Builds and returns a new Engine instance wired to the current registries.
65
+ * @returns {Engine} The created Engine instance.
66
+ */
67
+ buildEngine() {
68
+ return new Engine();
69
+ }
70
+
71
+ /**
72
+ * Builds and returns a WebServer if web configuration is present, otherwise null.
73
+ * @returns {WebServer|null} The created WebServer instance or null.
74
+ */
75
+ buildWebServer() {
76
+ return WebServer.build({
77
+ webConfig: this.config.webConfig,
78
+ });
79
+ }
80
+
81
+ /**
82
+ * Enqueues all parameter-free ResourceRequests into the job registry.
83
+ * These are requests whose URLs contain no {:placeholder} tokens and can be
84
+ * processed immediately without any external parameters.
85
+ * @returns {void}
86
+ */
87
+ enqueueFirstJobs() {
88
+ new ResourceRequestCollector(this.config.resourceRegistry).requestsNeedingNoParams().forEach((resourceRequest) => {
89
+ JobRegistry.enqueue('ResourceRequestJob', { resourceRequest, parameters: {} });
90
+ });
91
+ }
92
+
93
+ /**
94
+ * Initializes the job factory, job registry, and workers registry from the loaded configuration.
95
+ * @returns {void}
96
+ */
97
+ #initRegistries() {
98
+ JobFactory.build('ResourceRequestJob', { attributes: { clients: this.config.clientRegistry } });
99
+ JobFactory.build('Action', { klass: ActionProcessingJob });
100
+
101
+ JobRegistry.build({ cooldown: this.config.workersConfig.retryCooldown });
102
+
103
+ WorkersRegistry.build({
104
+ workers: this.#workers,
105
+ jobRegistry: JobRegistry,
106
+ workersRegistry: WorkersRegistry,
107
+ ...this.config.workersConfig,
108
+ });
109
+ WorkersRegistry.initWorkers();
110
+ }
111
+ }
112
+
113
+ export { Application };
@@ -0,0 +1,36 @@
1
+ const DEFAULT_CONFIG_FILE = 'config/navi_config.yml';
2
+ const ARGUMENTS_CONFIG = {
3
+ options: {
4
+ config: { type: 'string', short: 'c', default: DEFAULT_CONFIG_FILE },
5
+ },
6
+ allowPositionals: false,
7
+ };
8
+
9
+ import { parseArgs } from 'node:util';
10
+
11
+ /**
12
+ * Parses CLI arguments and returns a structured options object.
13
+ * @author darthjee
14
+ */
15
+ class ArgumentsParser {
16
+ /**
17
+ * Parses command line arguments to extract CLI options.
18
+ *
19
+ * Supports:
20
+ * -c <path> Short form with a space-separated value
21
+ * --config=<path> Long form with an equals sign
22
+ *
23
+ * Falls back to DEFAULT_CONFIG_FILE when no option is provided.
24
+ *
25
+ * @param {string[]} args - Command line arguments (typically process.argv.slice(2))
26
+ * @returns {{ configFile: string }} Parsed options object with the config file path.
27
+ */
28
+ static parse(args) {
29
+ return parseArgs({
30
+ args: args,
31
+ ...ARGUMENTS_CONFIG
32
+ }).values;
33
+ }
34
+ }
35
+
36
+ export { ArgumentsParser, DEFAULT_CONFIG_FILE };
@@ -0,0 +1,108 @@
1
+ import axios from 'axios';
2
+ import { RequestFailed } from '../exceptions/RequestFailed.js';
3
+ import { EnvResolver } from '../utils/EnvResolver.js';
4
+ import { Logger } from '../utils/logging/Logger.js';
5
+
6
+ /**
7
+ * Client performs HTTP requests for resource paths using a configured base URL.
8
+ *
9
+ * It validates response status against the expected status from the resource request.
10
+ *
11
+ * @author darthjee
12
+ */
13
+ class Client {
14
+ /**
15
+ * @param {object} attributes Client attributes.
16
+ * @param {string} attributes.name Name identifying this client.
17
+ * @param {string} attributes.baseUrl Base URL used to build full request URLs.
18
+ * @param {number} [attributes.timeout] Optional request timeout in milliseconds.
19
+ * @param {object} [attributes.headers] Optional HTTP headers sent with every request.
20
+ */
21
+ constructor({ name, baseUrl, timeout = 5000, headers = {} }) {
22
+ this.name = name;
23
+ this.baseUrl = baseUrl;
24
+ this.timeout = timeout;
25
+ this.headers = headers;
26
+ }
27
+
28
+ /**
29
+ * Creates a Client instance from a plain configuration object.
30
+ *
31
+ * @param {string} name The name identifying the client.
32
+ * @param {object} config Client configuration object.
33
+ * @param {string} config.base_url Base URL for the client.
34
+ * @param {number} [config.timeout] Optional request timeout in milliseconds.
35
+ * @param {object} [config.headers] Optional HTTP headers. Values matching
36
+ * `$VAR` or `${VAR}` are resolved from `process.env` at parse time.
37
+ * @returns {Client} A new Client instance.
38
+ */
39
+ static fromObject(name, config) {
40
+ const headers = EnvResolver.resolveObject(config.headers || {});
41
+ return new Client({ name, baseUrl: config.base_url, timeout: config.timeout, headers });
42
+ }
43
+
44
+ /**
45
+ * Creates an array of Client instances from a map of client configurations.
46
+ *
47
+ * @param {object} object Map of client names to client configuration objects.
48
+ * @returns {Array<Client>} List of Client instances.
49
+ */
50
+ static fromListObject(object) {
51
+ return Object.entries(object).map(([name, config]) => Client.fromObject(name, config));
52
+ }
53
+
54
+ /**
55
+ * Performs the HTTP request and checks the response status.
56
+ * @param {ResourceRequest} resourceRequest Information about the URL path to request
57
+ * and the expected status code.
58
+ * @param {object} [parameters={}] Key-value map used to resolve {:placeholder} tokens in the URL.
59
+ * @returns {Promise<boolean>} Returns true if the response status matches the expected status.
60
+ * @throws {RequestFailed} Throws an error if the request fails or the status does not match.
61
+ */
62
+ async perform(resourceRequest, parameters = {}) {
63
+ const requestUrl = this.#buildUrl(resourceRequest.resolveUrl(parameters));
64
+ Logger.info(`[Client:${this.name}] Requesting ${requestUrl}`);
65
+ try {
66
+ return await this.#request(resourceRequest, requestUrl);
67
+ } catch (error) {
68
+ Logger.error(`Request failed: ${error}`);
69
+ if (error.response) {
70
+ throw new RequestFailed(error.response.status, requestUrl);
71
+ }
72
+ throw error;
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Performs the HTTP request and checks the response status.
78
+ * @param {ResourceRequest} resourceRequest Information about the URL path to request
79
+ * and the expected status code.
80
+ * @param {string} requestUrl The full URL for the request.
81
+ * @returns {Promise<boolean>} Returns true if the response status matches the expected status.
82
+ * @throws {RequestFailed} Throws an error if the response status does not match.
83
+ */
84
+ async #request(resourceRequest, requestUrl) {
85
+ const response = await axios.get(requestUrl, {
86
+ timeout: this.timeout,
87
+ responseType: 'text',
88
+ headers: this.headers,
89
+ });
90
+
91
+ if (response.status !== resourceRequest.status) {
92
+ throw new RequestFailed(response.status, requestUrl);
93
+ }
94
+
95
+ return response;
96
+ }
97
+
98
+ /**
99
+ * Builds the complete URL by combining base URL and resource URL path.
100
+ * @param {string} resourceUrl URL path from the resource request.
101
+ * @returns {string} The full URL.
102
+ */
103
+ #buildUrl(resourceUrl) {
104
+ return `${this.baseUrl}${resourceUrl}`;
105
+ }
106
+ }
107
+
108
+ export { Client };