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,87 @@
1
+ /**
2
+ * Job is the abstract base class for all units of work processed by a Worker.
3
+ * Subclasses must implement the `perform` method.
4
+ * @author darthjee
5
+ */
6
+ class Job {
7
+ #attempts;
8
+ #readyBy;
9
+
10
+ /**
11
+ * Creates a new Job instance.
12
+ * @param {object} params - The parameters for creating a Job instance.
13
+ * @param {string} params.id - The unique identifier for this job.
14
+ */
15
+ constructor({ id }) {
16
+ this.id = id;
17
+ this.#attempts = 0;
18
+ this.#readyBy = 0;
19
+ }
20
+
21
+ /**
22
+ * Performs the job. Must be overridden by subclasses.
23
+ * @throws {Error} Always throws — subclasses must implement this method.
24
+ * @returns {Promise} A promise that resolves when the job is complete.
25
+ */
26
+ async perform() {
27
+ throw new Error('You must implement the perform method in a subclass');
28
+ }
29
+
30
+ /**
31
+ * Returns the timestamp after which the job is eligible for retry.
32
+ * @returns {number} The readyBy timestamp in milliseconds.
33
+ */
34
+ get readyBy() {
35
+ return this.#readyBy;
36
+ }
37
+
38
+ /**
39
+ * Sets the cooldown duration in milliseconds after which the job is eligible for retry.
40
+ * Stores the absolute timestamp (Date.now() + ms) internally.
41
+ * @param {number} ms - Cooldown duration in milliseconds. Use a negative value to mark ready immediately.
42
+ * @returns {void}
43
+ */
44
+ applyCooldown(ms) {
45
+ this.#readyBy = Date.now() + ms;
46
+ }
47
+
48
+ /**
49
+ * Checks whether the job's cooldown period has elapsed relative to the given time.
50
+ * @param {number} currentTime - The current timestamp in milliseconds.
51
+ * @returns {boolean} True if the job can be retried at the given time.
52
+ */
53
+ isReadyBy(currentTime) {
54
+ return currentTime >= this.#readyBy;
55
+ }
56
+
57
+ /**
58
+ * Checks if the job has been exhausted (i.e., has reached the maximum number of attempts).
59
+ * @returns {boolean} True if the job is exhausted, false otherwise.
60
+ */
61
+ exhausted() {
62
+ return this.#attempts >= 3;
63
+ }
64
+
65
+ /**
66
+ * Returns the number of failed attempts so far.
67
+ * @returns {number} The current attempt count.
68
+ * @protected
69
+ */
70
+ get _attempts() {
71
+ return this.#attempts;
72
+ }
73
+
74
+ /**
75
+ * Handles a failed job attempt.
76
+ * @param {Error} error - The error that caused the job to fail.
77
+ * @throws {Error} Re-throws the error after recording the failure.
78
+ * @protected
79
+ */
80
+ _fail(error) {
81
+ this.#attempts += 1;
82
+ this.lastError = error;
83
+ throw error;
84
+ }
85
+ }
86
+
87
+ export { Job };
@@ -0,0 +1,43 @@
1
+ import { PathResolver } from './PathResolver.js';
2
+
3
+ /**
4
+ * Applies a parameters map to a ResponseWrapper, resolving path expressions
5
+ * against the wrapper to extract values from the parsed body or headers.
6
+ *
7
+ * When the parameters map is empty, the originating request parameters of the response
8
+ * item are returned (or an empty object if none exist).
9
+ * When the parameters map has entries, each value is a path expression
10
+ * (e.g. `parsedBody.id`, `headers['page']`) resolved against the wrapper.
11
+ * @author darthjee
12
+ */
13
+ class ParametersMapper {
14
+ #resolvers;
15
+
16
+ /**
17
+ * @param {object} [parametersMap={}] Key-value map where each key is the
18
+ * destination variable name and its value is a path expression to resolve
19
+ * against the ResponseWrapper (e.g. `parsedBody.id`, `headers['page']`).
20
+ */
21
+ constructor(parametersMap = {}) {
22
+ this.#resolvers = Object.entries(parametersMap).map(
23
+ ([dest, pathExpr]) => [dest, PathResolver.fromExpression(pathExpr)]
24
+ );
25
+ }
26
+
27
+ /**
28
+ * Applies the parameters map to the given ResponseWrapper item.
29
+ * @param {object} item A ResponseWrapper or plain object exposing the
30
+ * properties referenced by the path expressions.
31
+ * @returns {object} The transformed variables object.
32
+ * @throws {MissingMappingVariable} If a path expression cannot be resolved.
33
+ */
34
+ map(item) {
35
+ if (this.#resolvers.length === 0) return item.parameters ?? {};
36
+
37
+ return Object.fromEntries(this.#resolvers.map(([dest, resolver]) => {
38
+ return [dest, resolver.resolve(item)];
39
+ }));
40
+ }
41
+ }
42
+
43
+ export { ParametersMapper };
@@ -0,0 +1,77 @@
1
+ import { PathSegmentTraverser } from './PathSegmentTraverser.js';
2
+
3
+ /**
4
+ * Resolves dot/bracket-notation path expressions against an object.
5
+ *
6
+ * Supports expressions such as `parsedBody.id`, `headers['page']`,
7
+ * and `parsedBody.nested.key`. Throws when a segment cannot be resolved.
8
+ *
9
+ * @example
10
+ * const resolver = PathResolver.fromExpression('parsedBody.id');
11
+ * resolver.resolve({ parsedBody: { id: 42 }, headers: {} }); // → 42
12
+ *
13
+ * @example
14
+ * const resolver = PathResolver.fromExpression("headers['x-next-page']");
15
+ * resolver.resolve({ parsedBody: {}, headers: { 'x-next-page': '3' } }); // → '3'
16
+ * @author darthjee
17
+ */
18
+ class PathResolver {
19
+ /** @type {RegExp} Pattern for parsing path segments. */
20
+ static #SEGMENT_PATTERN = /(?:^|\.)([\w]+)|\['([^']+)'\]|\["([^"]+)"\]/g;
21
+
22
+ #segments;
23
+ #pathExpr;
24
+
25
+ /**
26
+ * @param {Array<string>} segments The parsed path segments.
27
+ * @param {string} pathExpr The original path expression string.
28
+ * @example
29
+ * const resolver = new PathResolver(['parsedBody', 'id'], 'parsedBody.id');
30
+ * resolver.resolve({ parsedBody: { id: 42 }, headers: {} }); // → 42
31
+ */
32
+ constructor(segments, pathExpr) {
33
+ this.#segments = segments;
34
+ this.#pathExpr = pathExpr;
35
+ }
36
+
37
+ /**
38
+ * Resolves the path against the given object.
39
+ * @param {object} obj The object to resolve against.
40
+ * @returns {*} The resolved value.
41
+ * @throws {MissingMappingVariable} If any segment of the path is missing.
42
+ */
43
+ resolve(obj) {
44
+ const traverser = new PathSegmentTraverser(obj, this.#pathExpr);
45
+
46
+ for (const segment of this.#segments) {
47
+ traverser.traverse(segment);
48
+ }
49
+
50
+ return traverser.value;
51
+ }
52
+
53
+ /**
54
+ * Creates a PathResolver by parsing a path expression string.
55
+ * @param {string} pathExpr The path expression
56
+ * (e.g. `parsedBody.id`, `headers['page']`).
57
+ * @returns {PathResolver} A new PathResolver instance.
58
+ */
59
+ static fromExpression(pathExpr) {
60
+ const segments = PathResolver.#parsePathSegments(pathExpr);
61
+ return new PathResolver(segments, pathExpr);
62
+ }
63
+
64
+ /**
65
+ * Parses a path expression string into an array of property segments.
66
+ * Handles dot notation and bracket notation with single or double quotes.
67
+ * @param {string} pathExpr The path expression
68
+ * (e.g. `parsedBody.id`, `headers['page']`).
69
+ * @returns {Array<string>} The array of path segments.
70
+ */
71
+ static #parsePathSegments(pathExpr) {
72
+ return [...pathExpr.matchAll(PathResolver.#SEGMENT_PATTERN)]
73
+ .map((match) => match[1] ?? match[2] ?? match[3]);
74
+ }
75
+ }
76
+
77
+ export { PathResolver };
@@ -0,0 +1,82 @@
1
+ import { MissingMappingVariable } from '../exceptions/MissingMappingVariable.js';
2
+
3
+ /**
4
+ * Traverses an object one path segment at a time, throwing when
5
+ * the segment cannot be resolved.
6
+ *
7
+ * @example
8
+ * const traverser = new PathSegmentTraverser(wrapper, 'parsedBody.id');
9
+ * traverser.traverse('parsedBody'); // advances to wrapper.parsedBody
10
+ * traverser.traverse('id'); // advances to wrapper.parsedBody.id
11
+ * traverser.value; // → the resolved value
12
+ * @author darthjee
13
+ */
14
+ class PathSegmentTraverser {
15
+ #current;
16
+ #pathExpr;
17
+
18
+ /**
19
+ * @param {object} root The starting object to traverse.
20
+ * @param {string} pathExpr The full path expression, used in error messages.
21
+ */
22
+ constructor(root, pathExpr) {
23
+ this.#current = root;
24
+ this.#pathExpr = pathExpr;
25
+ }
26
+
27
+ /**
28
+ * The current resolved value after all traversals.
29
+ * @returns {*} The current value.
30
+ */
31
+ get value() {
32
+ return this.#current;
33
+ }
34
+
35
+ /**
36
+ * Advances one segment along the path.
37
+ * @param {string} segment The property name to access.
38
+ * @returns {void}
39
+ * @throws {MissingMappingVariable} If the segment cannot be resolved.
40
+ */
41
+ traverse(segment) {
42
+ this.#ensureObject();
43
+ this.#ensureKey(segment);
44
+
45
+ this.#current = this.#current[segment];
46
+ }
47
+
48
+ /**
49
+ * Ensures the current value is a non-null object.
50
+ * @returns {void}
51
+ * @throws {MissingMappingVariable} If the current value is not an object.
52
+ */
53
+ #ensureObject() {
54
+ if (!this.#isTraversable()) {
55
+ throw new MissingMappingVariable(this.#pathExpr);
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Checks whether the current value is a non-null object that can be traversed.
61
+ * @returns {boolean} True if the current value is traversable.
62
+ */
63
+ #isTraversable() {
64
+ return this.#current !== null
65
+ && this.#current !== undefined
66
+ && typeof this.#current === 'object';
67
+ }
68
+
69
+ /**
70
+ * Ensures the given segment exists on the current object.
71
+ * @param {string} segment The property name to check.
72
+ * @returns {void}
73
+ * @throws {MissingMappingVariable} If the segment is not present.
74
+ */
75
+ #ensureKey(segment) {
76
+ if (!(segment in this.#current)) {
77
+ throw new MissingMappingVariable(this.#pathExpr);
78
+ }
79
+ }
80
+ }
81
+
82
+ export { PathSegmentTraverser };
@@ -0,0 +1,47 @@
1
+ import { ResourceRequest } from './ResourceRequest.js';
2
+
3
+ /**
4
+ * Resource class represents a resource with a name and associated resource requests.
5
+ * @author darthjee
6
+ */
7
+ class Resource {
8
+ /**
9
+ * Represents a resource with a name and associated resource requests.
10
+ * @param {object} params - The parameters for creating a Resource instance.
11
+ * @param {string} params.name - The name of the resource.
12
+ * @param {Array} params.resourceRequests - The resource requests associated with the resource.
13
+ */
14
+ constructor({ name, resourceRequests }) {
15
+ this.name = name;
16
+ this.resourceRequests = resourceRequests;
17
+ }
18
+
19
+ /**
20
+ * Creates a Resource instance from a plain object.
21
+ * @param {object} obj - The plain object representing a resource.
22
+ * @param {string} obj.name - The name of the resource.
23
+ * @param {string} [obj.client] - The name of the client to use for requests from this resource.
24
+ * @param {Array<{url: string, status: number}>} obj.resourceRequests -
25
+ * The resource requests associated with the resource.
26
+ * @returns {Resource} A new Resource instance.
27
+ */
28
+ static fromObject(obj) {
29
+ return new Resource({
30
+ name: obj.name,
31
+ resourceRequests: ResourceRequest.fromList(obj.resourceRequests, { clientName: obj.client })
32
+ });
33
+ }
34
+
35
+ /**
36
+ * Creates a list of Resource instances from a plain object.
37
+ * @param {object} object - The plain object representing multiple resources.
38
+ * @returns {Array<Resource>} A list of Resource instances.
39
+ */
40
+ static fromListObject(object) {
41
+ return Object.entries(object).map(([resourceName, requests]) => {
42
+ return Resource.fromObject({ name: resourceName, resourceRequests: requests});
43
+ });
44
+ }
45
+ }
46
+
47
+ export { Resource };
@@ -0,0 +1,80 @@
1
+ import { ActionsEnqueuer } from './ActionsEnqueuer.js';
2
+ import { ResourceRequestAction } from './ResourceRequestAction.js';
3
+
4
+ /**
5
+ * ResourceRequest represents a request to a specific URL with an expected status code.
6
+ * @author darthjee
7
+ */
8
+ class ResourceRequest {
9
+ #clientName;
10
+
11
+ /**
12
+ * @param {object} attributes ResourceRequest attributes
13
+ * @param {string} attributes.url The URL to request.
14
+ * @param {number} attributes.status The expected status code of the response.
15
+ * @param {string} [attributes.clientName] The name of the client to use for this request.
16
+ * @param {Array} [attributes.actions=[]] List of raw action config objects.
17
+ */
18
+ constructor({ url, status, clientName, actions = [] }) {
19
+ this.url = url;
20
+ this.status = status;
21
+ this.#clientName = clientName;
22
+ this.actions = ResourceRequestAction.fromList(actions);
23
+ }
24
+
25
+ /**
26
+ * Returns the name of the client associated with this request,
27
+ * as inherited from the parent Resource's client attribute.
28
+ * @returns {string|undefined} The client name, or undefined if not set.
29
+ */
30
+ get clientName() {
31
+ return this.#clientName;
32
+ }
33
+
34
+ /**
35
+ * Enqueues one ActionProcessingJob per action associated with the resource request.
36
+ * Returns immediately if there are no actions.
37
+ * @param {ResponseWrapper} responseWrapper The ResponseWrapper for the HTTP response.
38
+ * @returns {void}
39
+ */
40
+ enqueueActions(responseWrapper) {
41
+ if (this.actions.length === 0) return;
42
+
43
+ const itemWrappers = responseWrapper.toItemWrappers();
44
+ new ActionsEnqueuer(this.actions, itemWrappers).enqueue();
45
+ }
46
+
47
+ /**
48
+ * Returns the URL with every {:placeholder} token replaced by the
49
+ * corresponding value from the parameters object.
50
+ * Tokens with no matching key are left unchanged.
51
+ * @param {object} [parameters={}] Key-value map of URL parameters.
52
+ * @returns {string} The resolved URL.
53
+ */
54
+ resolveUrl(parameters = {}) {
55
+ return this.url.replace(/\{:(\w+)\}/g, (_, key) => parameters[key] ?? `{:${key}}`);
56
+ }
57
+
58
+ /**
59
+ * Returns true if the URL template contains any {:placeholder} tokens,
60
+ * indicating that parameter substitution is required before the request can be made.
61
+ * @returns {boolean} true if the URL requires parameters, false otherwise.
62
+ */
63
+ needsParams() {
64
+ return /\{:\w+\}/.test(this.url);
65
+ }
66
+
67
+ /**
68
+ * Creates a list of ResourceRequest instances from an array of objects.
69
+ * @param {Array<{ url: string, status: number }>} array list of objects with attributes to create a new ResourceRequest
70
+ * @param {object} [options={}] optional options to assign to each ResourceRequest
71
+ * @param {string} [options.clientName] optional client name to assign to each ResourceRequest
72
+ * @returns {Array<ResourceRequest>} list of ResourceRequest instances
73
+ */
74
+ static fromList(array, { clientName } = {}) {
75
+ return array.map((attrs) => new ResourceRequest({ ...attrs, clientName }));
76
+ }
77
+ }
78
+
79
+ export { ResourceRequest };
80
+
@@ -0,0 +1,73 @@
1
+ import { ParametersMapper } from './ParametersMapper.js';
2
+ import { MissingActionResource } from '../exceptions/MissingActionResource.js';
3
+ import { JobRegistry as DefaultJobRegistry } from '../registry/JobRegistry.js';
4
+ import { ResourceRegistry as DefaultResourceRegistry } from '../registry/ResourceRegistry.js';
5
+ import { Logger } from '../utils/logging/Logger.js';
6
+
7
+ /**
8
+ * Represents a single action to execute after a successful resource request response.
9
+ *
10
+ * Each action holds a reference to a resource name and an optional parameters
11
+ * map that extracts response fields into job parameters via path expressions.
12
+ * When executed, it looks up the target resource and enqueues one
13
+ * ResourceRequestJob per ResourceRequest in that resource, passing the
14
+ * mapped variables as job parameters.
15
+ * @author darthjee
16
+ */
17
+ class ResourceRequestAction {
18
+ #mapper;
19
+ #jobRegistry;
20
+ #resourceRegistry;
21
+
22
+ /**
23
+ * @param {object} attributes Action attributes.
24
+ * @param {string} attributes.resource Name of the resource to act upon.
25
+ * @param {object} [attributes.parameters={}] Key-value map where keys are destination
26
+ * variable names and values are path expressions (e.g. `parsedBody.id`, `headers['page']`).
27
+ * @param {object} [attributes.jobRegistry=JobRegistry] The job registry to enqueue jobs to.
28
+ * @param {object} [attributes.resourceRegistry=ResourceRegistry] The resource registry to look up resources.
29
+ * @throws {MissingActionResource} If resource is absent or falsy.
30
+ */
31
+ constructor({ resource, parameters = {}, jobRegistry = DefaultJobRegistry, resourceRegistry = DefaultResourceRegistry }) {
32
+ if (!resource) throw new MissingActionResource();
33
+ this.resource = resource;
34
+ this.#mapper = new ParametersMapper(parameters);
35
+ this.#jobRegistry = jobRegistry;
36
+ this.#resourceRegistry = resourceRegistry;
37
+ }
38
+
39
+ /**
40
+ * Maps the response wrapper to variables, looks up the target resource, and
41
+ * enqueues one ResourceRequestJob per ResourceRequest in that resource.
42
+ * @param {ResponseWrapper} responseWrapper A ResponseWrapper instance exposing
43
+ * parsedBody and headers.
44
+ * @returns {void}
45
+ */
46
+ execute(responseWrapper) {
47
+ const vars = this.#mapper.map(responseWrapper);
48
+ const resource = this.#resourceRegistry.getItem(this.resource);
49
+
50
+ for (const resourceRequest of resource.resourceRequests) {
51
+ this.#jobRegistry.enqueue('ResourceRequestJob', { resourceRequest, parameters: vars });
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Creates a list of ResourceRequestAction instances from an array of raw config objects.
57
+ * Entries that fail to construct (e.g. missing resource) are logged and skipped.
58
+ * @param {Array<object>} [array=[]] Raw action config entries.
59
+ * @returns {Array<ResourceRequestAction>} Valid action instances.
60
+ */
61
+ static fromList(array = []) {
62
+ return array.flatMap((attrs) => {
63
+ try {
64
+ return [new ResourceRequestAction(attrs)];
65
+ } catch (error) {
66
+ Logger.error(`Skipping action: ${error}`);
67
+ return [];
68
+ }
69
+ });
70
+ }
71
+ }
72
+
73
+ export { ResourceRequestAction };
@@ -0,0 +1,61 @@
1
+ import { Job } from './Job.js';
2
+ import { ResponseWrapper } from './ResponseWrapper.js';
3
+ import { Logger } from '../utils/logging/Logger.js';
4
+
5
+ /**
6
+ * ResourceRequestJob is a Job that performs an HTTP request for a ResourceRequest.
7
+ * @author darthjee
8
+ */
9
+ class ResourceRequestJob extends Job {
10
+ #resourceRequest;
11
+ #parameters;
12
+ #clients;
13
+ #client;
14
+
15
+ /**
16
+ * Creates a new ResourceRequestJob instance.
17
+ * @param {object} params - The parameters for creating a ResourceRequestJob instance.
18
+ * @param {string} params.id - The unique identifier for this job.
19
+ * @param {ResourceRequest} params.resourceRequest - The resource request associated with this job.
20
+ * @param {object} params.parameters - Additional parameters for the request.
21
+ * @param {ClientRegistry} params.clients - Clients registry to be used in a request.
22
+ */
23
+ constructor({ id, resourceRequest, parameters, clients }) {
24
+ super({ id });
25
+ this.#resourceRequest = resourceRequest;
26
+ this.#parameters = parameters;
27
+ this.#clients = clients;
28
+ }
29
+
30
+ /**
31
+ * Performs the HTTP request for the resource request.
32
+ * @returns {Promise} A promise that resolves with the HTTP response.
33
+ */
34
+ async perform() {
35
+ Logger.info(`ResourceRequestJob #${this.id} performing`);
36
+ try {
37
+ this.lastError = undefined;
38
+ const response = await this.#getClient().perform(this.#resourceRequest, this.#parameters);
39
+ const wrapper = new ResponseWrapper(response, this.#parameters);
40
+ this.#resourceRequest.enqueueActions(wrapper);
41
+ return response;
42
+ } catch (error) {
43
+ Logger.error(`Job #${this.id} failed: ${error}`);
44
+ this._fail(error);
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Gets the client associated with this job's resource request.
50
+ * @returns {Client} The client associated with this job's resource request.
51
+ * @private
52
+ */
53
+ #getClient() {
54
+ if (!this.#client) {
55
+ this.#client = this.#clients.getClient(this.#resourceRequest.clientName);
56
+ }
57
+ return this.#client;
58
+ }
59
+ }
60
+
61
+ export { ResourceRequestJob };
@@ -0,0 +1,36 @@
1
+ import { InvalidResponseBody } from '../exceptions/InvalidResponseBody.js';
2
+
3
+ /**
4
+ * Parses a raw JSON response body string into a JavaScript value.
5
+ *
6
+ * Parsing is intentionally kept separate from normalisation (array vs object)
7
+ * and from action dispatching — each concern lives in its own class.
8
+ * @author darthjee
9
+ */
10
+ class ResponseParser {
11
+ #raw;
12
+
13
+ /**
14
+ * @param {string} raw The raw response body string.
15
+ */
16
+ constructor(raw) {
17
+ this.#raw = raw;
18
+ }
19
+
20
+ /**
21
+ * Parses the raw body and returns the resulting JavaScript value.
22
+ * The return value may be an object, an array, or any other valid JSON type.
23
+ * Normalisation to an array is the caller's responsibility.
24
+ * @returns {*} The parsed value.
25
+ * @throws {InvalidResponseBody} If the body cannot be parsed as JSON.
26
+ */
27
+ parse() {
28
+ try {
29
+ return JSON.parse(this.#raw);
30
+ } catch (cause) {
31
+ throw new InvalidResponseBody(this.#raw, cause);
32
+ }
33
+ }
34
+ }
35
+
36
+ export { ResponseParser };
@@ -0,0 +1,86 @@
1
+ import { ResponseParser } from './ResponseParser.js';
2
+
3
+ /**
4
+ * Wraps an HTTP response object, providing convenient access to the
5
+ * parsed JSON body and response headers for use in parameter mapping.
6
+ *
7
+ * Can represent either a full response or a per-item view where
8
+ * `parsedBody` is a single element from the response array.
9
+ * @author darthjee
10
+ */
11
+ class ResponseWrapper {
12
+ #response;
13
+ #parsedBody;
14
+ #headers;
15
+ #parameters;
16
+
17
+ /**
18
+ * @param {object} response The raw HTTP response object (e.g. from axios).
19
+ * @param {string} response.data The raw response body string.
20
+ * @param {object} response.headers The response headers map.
21
+ * @param {object} [parameters={}] The parameters used in the originating request.
22
+ */
23
+ constructor(response, parameters = {}) {
24
+ this.#response = response;
25
+ this.#headers = response.headers;
26
+ this.#parameters = parameters;
27
+ }
28
+
29
+ /**
30
+ * Returns the lazily-parsed JSON body of the response.
31
+ * The result is cached after the first call.
32
+ * @returns {*} The parsed response body.
33
+ */
34
+ get parsedBody() {
35
+ if (this.#parsedBody === undefined) {
36
+ this.#parsedBody = new ResponseParser(this.#response.data).parse();
37
+ }
38
+
39
+ return this.#parsedBody;
40
+ }
41
+
42
+ /**
43
+ * Returns the response headers map.
44
+ * @returns {object} The raw headers from the HTTP response.
45
+ */
46
+ get headers() {
47
+ return this.#headers;
48
+ }
49
+
50
+ /**
51
+ * Returns the parameters of the originating request.
52
+ * @returns {object} The request parameters.
53
+ */
54
+ get parameters() {
55
+ return this.#parameters;
56
+ }
57
+
58
+ /**
59
+ * Returns an array of per-item ResponseWrapper instances.
60
+ * If the parsed body is an array, one wrapper is created per element.
61
+ * If it is a single object, a single-element array is returned.
62
+ * Each per-item wrapper shares the same headers as this wrapper.
63
+ * @returns {Array<ResponseWrapper>} List of per-item wrappers.
64
+ */
65
+ toItemWrappers() {
66
+ const body = this.parsedBody;
67
+ const items = Array.isArray(body) ? body : [body];
68
+
69
+ return items.map((item) => ResponseWrapper.#fromItem(item, this.#headers, this.#parameters));
70
+ }
71
+
72
+ /**
73
+ * Creates a per-item ResponseWrapper with a pre-parsed body, shared headers and parameters.
74
+ * @param {*} parsedBody The already-parsed item value.
75
+ * @param {object} headers The response headers to share.
76
+ * @param {object} parameters The request parameters to share.
77
+ * @returns {ResponseWrapper} A wrapper whose parsedBody is the given item.
78
+ */
79
+ static #fromItem(parsedBody, headers, parameters) {
80
+ const wrapper = new ResponseWrapper({ data: null, headers }, parameters);
81
+ wrapper.#parsedBody = parsedBody;
82
+ return wrapper;
83
+ }
84
+ }
85
+
86
+ export { ResponseWrapper };
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Represents the web server configuration.
3
+ * @author darthjee
4
+ */
5
+ class WebConfig {
6
+ /**
7
+ * @param {object} config - Configuration object.
8
+ * @param {number} config.port - The port number to listen on.
9
+ */
10
+ constructor({ port }) {
11
+ this.port = port;
12
+ }
13
+ }
14
+
15
+ export { WebConfig };