@backstage/backend-test-utils 1.0.1-next.1 → 1.0.1-next.2
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/CHANGELOG.md +15 -0
- package/dist/backend-app-api/src/lib/DependencyGraph.cjs.js +182 -0
- package/dist/backend-app-api/src/lib/DependencyGraph.cjs.js.map +1 -0
- package/dist/backend-app-api/src/wiring/ServiceRegistry.cjs.js +240 -0
- package/dist/backend-app-api/src/wiring/ServiceRegistry.cjs.js.map +1 -0
- package/dist/cache/TestCaches.cjs.js +159 -0
- package/dist/cache/TestCaches.cjs.js.map +1 -0
- package/dist/cache/memcache.cjs.js +62 -0
- package/dist/cache/memcache.cjs.js.map +1 -0
- package/dist/cache/redis.cjs.js +62 -0
- package/dist/cache/redis.cjs.js.map +1 -0
- package/dist/cache/types.cjs.js +25 -0
- package/dist/cache/types.cjs.js.map +1 -0
- package/dist/database/TestDatabases.cjs.js +128 -0
- package/dist/database/TestDatabases.cjs.js.map +1 -0
- package/dist/database/mysql.cjs.js +188 -0
- package/dist/database/mysql.cjs.js.map +1 -0
- package/dist/database/postgres.cjs.js +143 -0
- package/dist/database/postgres.cjs.js.map +1 -0
- package/dist/database/sqlite.cjs.js +40 -0
- package/dist/database/sqlite.cjs.js.map +1 -0
- package/dist/database/types.cjs.js +68 -0
- package/dist/database/types.cjs.js.map +1 -0
- package/dist/filesystem/MockDirectory.cjs.js +152 -0
- package/dist/filesystem/MockDirectory.cjs.js.map +1 -0
- package/dist/index.cjs.js +25 -2327
- package/dist/index.cjs.js.map +1 -1
- package/dist/msw/registerMswTestHooks.cjs.js +10 -0
- package/dist/msw/registerMswTestHooks.cjs.js.map +1 -0
- package/dist/next/services/MockAuthService.cjs.js +111 -0
- package/dist/next/services/MockAuthService.cjs.js.map +1 -0
- package/dist/next/services/MockHttpAuthService.cjs.js +87 -0
- package/dist/next/services/MockHttpAuthService.cjs.js.map +1 -0
- package/dist/next/services/MockRootLoggerService.cjs.js +49 -0
- package/dist/next/services/MockRootLoggerService.cjs.js.map +1 -0
- package/dist/next/services/MockUserInfoService.cjs.js +26 -0
- package/dist/next/services/MockUserInfoService.cjs.js.map +1 -0
- package/dist/next/services/mockCredentials.cjs.js +148 -0
- package/dist/next/services/mockCredentials.cjs.js.map +1 -0
- package/dist/next/services/mockServices.cjs.js +294 -0
- package/dist/next/services/mockServices.cjs.js.map +1 -0
- package/dist/next/wiring/ServiceFactoryTester.cjs.js +61 -0
- package/dist/next/wiring/ServiceFactoryTester.cjs.js.map +1 -0
- package/dist/next/wiring/TestBackend.cjs.js +258 -0
- package/dist/next/wiring/TestBackend.cjs.js.map +1 -0
- package/dist/util/errorHandler.cjs.js +18 -0
- package/dist/util/errorHandler.cjs.js.map +1 -0
- package/dist/util/getDockerImageForName.cjs.js +8 -0
- package/dist/util/getDockerImageForName.cjs.js.map +1 -0
- package/dist/util/isDockerDisabledForTests.cjs.js +8 -0
- package/dist/util/isDockerDisabledForTests.cjs.js.map +1 -0
- package/package.json +8 -8
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# @backstage/backend-test-utils
|
|
2
2
|
|
|
3
|
+
## 1.0.1-next.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- fd6e6f4: build(deps): bump `cookie` from 0.6.0 to 0.7.0
|
|
8
|
+
- Updated dependencies
|
|
9
|
+
- @backstage/backend-app-api@1.0.1-next.1
|
|
10
|
+
- @backstage/backend-defaults@0.5.1-next.2
|
|
11
|
+
- @backstage/plugin-auth-node@0.5.3-next.1
|
|
12
|
+
- @backstage/backend-plugin-api@1.0.1-next.1
|
|
13
|
+
- @backstage/config@1.2.0
|
|
14
|
+
- @backstage/errors@1.2.4
|
|
15
|
+
- @backstage/types@1.1.1
|
|
16
|
+
- @backstage/plugin-events-node@0.4.1-next.1
|
|
17
|
+
|
|
3
18
|
## 1.0.1-next.1
|
|
4
19
|
|
|
5
20
|
### Patch Changes
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
class Node {
|
|
4
|
+
constructor(value, consumes, provides) {
|
|
5
|
+
this.value = value;
|
|
6
|
+
this.consumes = consumes;
|
|
7
|
+
this.provides = provides;
|
|
8
|
+
}
|
|
9
|
+
static from(input) {
|
|
10
|
+
return new Node(
|
|
11
|
+
input.value,
|
|
12
|
+
input.consumes ? new Set(input.consumes) : /* @__PURE__ */ new Set(),
|
|
13
|
+
input.provides ? new Set(input.provides) : /* @__PURE__ */ new Set()
|
|
14
|
+
);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
class CycleKeySet {
|
|
18
|
+
static from(nodes) {
|
|
19
|
+
return new CycleKeySet(nodes);
|
|
20
|
+
}
|
|
21
|
+
#nodeIds;
|
|
22
|
+
#cycleKeys;
|
|
23
|
+
constructor(nodes) {
|
|
24
|
+
this.#nodeIds = new Map(nodes.map((n, i) => [n.value, i]));
|
|
25
|
+
this.#cycleKeys = /* @__PURE__ */ new Set();
|
|
26
|
+
}
|
|
27
|
+
tryAdd(path) {
|
|
28
|
+
const cycleKey = this.#getCycleKey(path);
|
|
29
|
+
if (this.#cycleKeys.has(cycleKey)) {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
this.#cycleKeys.add(cycleKey);
|
|
33
|
+
return true;
|
|
34
|
+
}
|
|
35
|
+
#getCycleKey(path) {
|
|
36
|
+
return path.map((n) => this.#nodeIds.get(n)).sort().join(",");
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
class DependencyGraph {
|
|
40
|
+
static fromMap(nodes) {
|
|
41
|
+
return this.fromIterable(
|
|
42
|
+
Object.entries(nodes).map(([key, node]) => ({
|
|
43
|
+
value: String(key),
|
|
44
|
+
...node
|
|
45
|
+
}))
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
static fromIterable(nodeInputs) {
|
|
49
|
+
const nodes = new Array();
|
|
50
|
+
for (const nodeInput of nodeInputs) {
|
|
51
|
+
nodes.push(Node.from(nodeInput));
|
|
52
|
+
}
|
|
53
|
+
return new DependencyGraph(nodes);
|
|
54
|
+
}
|
|
55
|
+
#nodes;
|
|
56
|
+
#allProvided;
|
|
57
|
+
constructor(nodes) {
|
|
58
|
+
this.#nodes = nodes;
|
|
59
|
+
this.#allProvided = /* @__PURE__ */ new Set();
|
|
60
|
+
for (const node of this.#nodes.values()) {
|
|
61
|
+
for (const produced of node.provides) {
|
|
62
|
+
this.#allProvided.add(produced);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Find all nodes that consume dependencies that are not provided by any other node.
|
|
68
|
+
*/
|
|
69
|
+
findUnsatisfiedDeps() {
|
|
70
|
+
const unsatisfiedDependencies = [];
|
|
71
|
+
for (const node of this.#nodes.values()) {
|
|
72
|
+
const unsatisfied = Array.from(node.consumes).filter(
|
|
73
|
+
(id) => !this.#allProvided.has(id)
|
|
74
|
+
);
|
|
75
|
+
if (unsatisfied.length > 0) {
|
|
76
|
+
unsatisfiedDependencies.push({ value: node.value, unsatisfied });
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return unsatisfiedDependencies;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Detect the first circular dependency within the graph, returning the path of nodes that
|
|
83
|
+
* form a cycle, with the same node as the first and last element of the array.
|
|
84
|
+
*/
|
|
85
|
+
detectCircularDependency() {
|
|
86
|
+
return this.detectCircularDependencies().next().value;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Detect circular dependencies within the graph, returning the path of nodes that
|
|
90
|
+
* form a cycle, with the same node as the first and last element of the array.
|
|
91
|
+
*/
|
|
92
|
+
*detectCircularDependencies() {
|
|
93
|
+
const cycleKeys = CycleKeySet.from(this.#nodes);
|
|
94
|
+
for (const startNode of this.#nodes) {
|
|
95
|
+
const visited = /* @__PURE__ */ new Set();
|
|
96
|
+
const stack = new Array([
|
|
97
|
+
startNode,
|
|
98
|
+
[startNode.value]
|
|
99
|
+
]);
|
|
100
|
+
while (stack.length > 0) {
|
|
101
|
+
const [node, path] = stack.pop();
|
|
102
|
+
if (visited.has(node)) {
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
visited.add(node);
|
|
106
|
+
for (const consumed of node.consumes) {
|
|
107
|
+
const providerNodes = this.#nodes.filter(
|
|
108
|
+
(other) => other.provides.has(consumed)
|
|
109
|
+
);
|
|
110
|
+
for (const provider of providerNodes) {
|
|
111
|
+
if (provider === startNode) {
|
|
112
|
+
if (cycleKeys.tryAdd(path)) {
|
|
113
|
+
yield [...path, startNode.value];
|
|
114
|
+
}
|
|
115
|
+
break;
|
|
116
|
+
}
|
|
117
|
+
if (!visited.has(provider)) {
|
|
118
|
+
stack.push([provider, [...path, provider.value]]);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return void 0;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Traverses the dependency graph in topological order, calling the provided
|
|
128
|
+
* function for each node and waiting for it to resolve.
|
|
129
|
+
*
|
|
130
|
+
* The nodes are traversed in parallel, but in such a way that no node is
|
|
131
|
+
* visited before all of its dependencies.
|
|
132
|
+
*
|
|
133
|
+
* Dependencies of nodes that are not produced by any other nodes will be ignored.
|
|
134
|
+
*/
|
|
135
|
+
async parallelTopologicalTraversal(fn) {
|
|
136
|
+
const allProvided = this.#allProvided;
|
|
137
|
+
const producedSoFar = /* @__PURE__ */ new Set();
|
|
138
|
+
const waiting = new Set(this.#nodes.values());
|
|
139
|
+
const visited = /* @__PURE__ */ new Set();
|
|
140
|
+
const results = new Array();
|
|
141
|
+
let inFlight = 0;
|
|
142
|
+
async function processMoreNodes() {
|
|
143
|
+
if (waiting.size === 0) {
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
const nodesToProcess = [];
|
|
147
|
+
for (const node of waiting) {
|
|
148
|
+
let ready = true;
|
|
149
|
+
for (const consumed of node.consumes) {
|
|
150
|
+
if (allProvided.has(consumed) && !producedSoFar.has(consumed)) {
|
|
151
|
+
ready = false;
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
if (ready) {
|
|
156
|
+
nodesToProcess.push(node);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
for (const node of nodesToProcess) {
|
|
160
|
+
waiting.delete(node);
|
|
161
|
+
}
|
|
162
|
+
if (nodesToProcess.length === 0 && inFlight === 0) {
|
|
163
|
+
throw new Error("Circular dependency detected");
|
|
164
|
+
}
|
|
165
|
+
await Promise.all(nodesToProcess.map(processNode));
|
|
166
|
+
}
|
|
167
|
+
async function processNode(node) {
|
|
168
|
+
visited.add(node);
|
|
169
|
+
inFlight += 1;
|
|
170
|
+
const result = await fn(node.value);
|
|
171
|
+
results.push(result);
|
|
172
|
+
node.provides.forEach((produced) => producedSoFar.add(produced));
|
|
173
|
+
inFlight -= 1;
|
|
174
|
+
await processMoreNodes();
|
|
175
|
+
}
|
|
176
|
+
await processMoreNodes();
|
|
177
|
+
return results;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
exports.DependencyGraph = DependencyGraph;
|
|
182
|
+
//# sourceMappingURL=DependencyGraph.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"DependencyGraph.cjs.js","sources":["../../../../../backend-app-api/src/lib/DependencyGraph.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\ninterface NodeInput<T> {\n value: T;\n consumes?: Iterable<string>;\n provides?: Iterable<string>;\n}\n\n/** @internal */\nclass Node<T> {\n static from<T>(input: NodeInput<T>) {\n return new Node<T>(\n input.value,\n input.consumes ? new Set(input.consumes) : new Set(),\n input.provides ? new Set(input.provides) : new Set(),\n );\n }\n\n private constructor(\n readonly value: T,\n readonly consumes: Set<string>,\n readonly provides: Set<string>,\n ) {}\n}\n\n/** @internal */\nclass CycleKeySet<T> {\n static from<T>(nodes: Array<Node<T>>) {\n return new CycleKeySet<T>(nodes);\n }\n\n #nodeIds: Map<T, number>;\n #cycleKeys: Set<string>;\n\n private constructor(nodes: Array<Node<T>>) {\n this.#nodeIds = new Map(nodes.map((n, i) => [n.value, i]));\n this.#cycleKeys = new Set<string>();\n }\n\n tryAdd(path: T[]): boolean {\n const cycleKey = this.#getCycleKey(path);\n if (this.#cycleKeys.has(cycleKey)) {\n return false;\n }\n this.#cycleKeys.add(cycleKey);\n return true;\n }\n\n #getCycleKey(path: T[]): string {\n return path\n .map(n => this.#nodeIds.get(n)!)\n .sort()\n .join(',');\n }\n}\n\n/**\n * Internal helper to help validate and traverse a dependency graph.\n * @internal\n */\nexport class DependencyGraph<T> {\n static fromMap(\n nodes: Record<string, Omit<NodeInput<unknown>, 'value'>>,\n ): DependencyGraph<string> {\n return this.fromIterable(\n Object.entries(nodes).map(([key, node]) => ({\n value: String(key),\n ...node,\n })),\n );\n }\n\n static fromIterable<T>(\n nodeInputs: Iterable<NodeInput<T>>,\n ): DependencyGraph<T> {\n const nodes = new Array<Node<T>>();\n for (const nodeInput of nodeInputs) {\n nodes.push(Node.from(nodeInput));\n }\n\n return new DependencyGraph(nodes);\n }\n\n #nodes: Array<Node<T>>;\n #allProvided: Set<string>;\n\n private constructor(nodes: Array<Node<T>>) {\n this.#nodes = nodes;\n this.#allProvided = new Set();\n\n for (const node of this.#nodes.values()) {\n for (const produced of node.provides) {\n this.#allProvided.add(produced);\n }\n }\n }\n\n /**\n * Find all nodes that consume dependencies that are not provided by any other node.\n */\n findUnsatisfiedDeps(): Array<{ value: T; unsatisfied: string[] }> {\n const unsatisfiedDependencies = [];\n for (const node of this.#nodes.values()) {\n const unsatisfied = Array.from(node.consumes).filter(\n id => !this.#allProvided.has(id),\n );\n if (unsatisfied.length > 0) {\n unsatisfiedDependencies.push({ value: node.value, unsatisfied });\n }\n }\n return unsatisfiedDependencies;\n }\n\n /**\n * Detect the first circular dependency within the graph, returning the path of nodes that\n * form a cycle, with the same node as the first and last element of the array.\n */\n detectCircularDependency(): T[] | undefined {\n return this.detectCircularDependencies().next().value;\n }\n\n /**\n * Detect circular dependencies within the graph, returning the path of nodes that\n * form a cycle, with the same node as the first and last element of the array.\n */\n *detectCircularDependencies(): Generator<T[], undefined> {\n const cycleKeys = CycleKeySet.from(this.#nodes);\n\n for (const startNode of this.#nodes) {\n const visited = new Set<Node<T>>();\n const stack = new Array<[node: Node<T>, path: T[]]>([\n startNode,\n [startNode.value],\n ]);\n\n while (stack.length > 0) {\n const [node, path] = stack.pop()!;\n if (visited.has(node)) {\n continue;\n }\n visited.add(node);\n for (const consumed of node.consumes) {\n const providerNodes = this.#nodes.filter(other =>\n other.provides.has(consumed),\n );\n for (const provider of providerNodes) {\n if (provider === startNode) {\n if (cycleKeys.tryAdd(path)) {\n yield [...path, startNode.value];\n }\n\n break;\n }\n if (!visited.has(provider)) {\n stack.push([provider, [...path, provider.value]]);\n }\n }\n }\n }\n }\n return undefined;\n }\n\n /**\n * Traverses the dependency graph in topological order, calling the provided\n * function for each node and waiting for it to resolve.\n *\n * The nodes are traversed in parallel, but in such a way that no node is\n * visited before all of its dependencies.\n *\n * Dependencies of nodes that are not produced by any other nodes will be ignored.\n */\n async parallelTopologicalTraversal<TResult>(\n fn: (value: T) => Promise<TResult>,\n ): Promise<TResult[]> {\n const allProvided = this.#allProvided;\n const producedSoFar = new Set<string>();\n const waiting = new Set(this.#nodes.values());\n const visited = new Set<Node<T>>();\n const results = new Array<TResult>();\n let inFlight = 0; // Keep track of how many callbacks are in flight, so that we know if we got stuck\n\n // Find all nodes that have no dependencies that have not already been produced by visited nodes\n async function processMoreNodes() {\n if (waiting.size === 0) {\n return;\n }\n const nodesToProcess = [];\n for (const node of waiting) {\n let ready = true;\n for (const consumed of node.consumes) {\n if (allProvided.has(consumed) && !producedSoFar.has(consumed)) {\n ready = false;\n continue;\n }\n }\n if (ready) {\n nodesToProcess.push(node);\n }\n }\n\n for (const node of nodesToProcess) {\n waiting.delete(node);\n }\n\n if (nodesToProcess.length === 0 && inFlight === 0) {\n // We expect the caller to check for circular dependencies before\n // traversal, so this error should never happen\n throw new Error('Circular dependency detected');\n }\n\n await Promise.all(nodesToProcess.map(processNode));\n }\n\n // Process an individual node, and then add its produced dependencies to the set of available products\n async function processNode(node: Node<T>) {\n visited.add(node);\n inFlight += 1;\n\n const result = await fn(node.value);\n results.push(result);\n\n node.provides.forEach(produced => producedSoFar.add(produced));\n inFlight -= 1;\n await processMoreNodes();\n }\n\n await processMoreNodes();\n\n return results;\n }\n}\n"],"names":[],"mappings":";;AAuBA,MAAM,IAAQ,CAAA;AAAA,EASJ,WAAA,CACG,KACA,EAAA,QAAA,EACA,QACT,EAAA;AAHS,IAAA,IAAA,CAAA,KAAA,GAAA,KAAA,CAAA;AACA,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA,CAAA;AACA,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA,CAAA;AAAA,GACR;AAAA,EAZH,OAAO,KAAQ,KAAqB,EAAA;AAClC,IAAA,OAAO,IAAI,IAAA;AAAA,MACT,KAAM,CAAA,KAAA;AAAA,MACN,KAAA,CAAM,WAAW,IAAI,GAAA,CAAI,MAAM,QAAQ,CAAA,uBAAQ,GAAI,EAAA;AAAA,MACnD,KAAA,CAAM,WAAW,IAAI,GAAA,CAAI,MAAM,QAAQ,CAAA,uBAAQ,GAAI,EAAA;AAAA,KACrD,CAAA;AAAA,GACF;AAO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,KAAA,GAAA,KAAA,CAAA;AACR,YAAA,SAAA;AAAA,WACF;AAAA,SACF;AACA,QAAA,IAAI,KAAO,EAAA;AACT,UAAA,cAAA,CAAe,KAAK,IAAI,CAAA,CAAA;AAAA,SAC1B;AAAA,OACF;AAEA,MAAA,KAAA,MAAW,QAAQ,cAAgB,EAAA;AACjC,QAAA,OAAA,CAAQ,OAAO,IAAI,CAAA,CAAA;AAAA,OACrB;AAEA,MAAA,IAAI,cAAe,CAAA,MAAA,KAAW,CAAK,IAAA,QAAA,KAAa,CAAG,EAAA;AAGjD,QAAM,MAAA,IAAI,MAAM,8BAA8B,CAAA,CAAA;AAAA,OAChD;AAEA,MAAA,MAAM,OAAQ,CAAA,GAAA,CAAI,cAAe,CAAA,GAAA,CAAI,WAAW,CAAC,CAAA,CAAA;AAAA,KACnD;AAGA,IAAA,eAAe,YAAY,IAAe,EAAA;AACxC,MAAA,OAAA,CAAQ,IAAI,IAAI,CAAA,CAAA;AAChB,MAAY,QAAA,IAAA,CAAA,CAAA;AAEZ,MAAA,MAAM,MAAS,GAAA,MAAM,EAAG,CAAA,IAAA,CAAK,KAAK,CAAA,CAAA;AAClC,MAAA,OAAA,CAAQ,KAAK,MAAM,CAAA,CAAA;AAEnB,MAAA,IAAA,CAAK,SAAS,OAAQ,CAAA,CAAA,QAAA,KAAY,aAAc,CAAA,GAAA,CAAI,QAAQ,CAAC,CAAA,CAAA;AAC7D,MAAY,QAAA,IAAA,CAAA,CAAA;AACZ,MAAA,MAAM,gBAAiB,EAAA,CAAA;AAAA,KACzB;AAEA,IAAA,MAAM,gBAAiB,EAAA,CAAA;AAEvB,IAAO,OAAA,OAAA,CAAA;AAAA,GACT;AACF;;;;"}
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var backendPluginApi = require('@backstage/backend-plugin-api');
|
|
4
|
+
var errors = require('@backstage/errors');
|
|
5
|
+
var DependencyGraph = require('../lib/DependencyGraph.cjs.js');
|
|
6
|
+
|
|
7
|
+
function toInternalServiceFactory(factory) {
|
|
8
|
+
const f = factory;
|
|
9
|
+
if (f.$$type !== "@backstage/BackendFeature") {
|
|
10
|
+
throw new Error(`Invalid service factory, bad type '${f.$$type}'`);
|
|
11
|
+
}
|
|
12
|
+
if (f.version !== "v1") {
|
|
13
|
+
throw new Error(`Invalid service factory, bad version '${f.version}'`);
|
|
14
|
+
}
|
|
15
|
+
return f;
|
|
16
|
+
}
|
|
17
|
+
function createPluginMetadataServiceFactory(pluginId) {
|
|
18
|
+
return backendPluginApi.createServiceFactory({
|
|
19
|
+
service: backendPluginApi.coreServices.pluginMetadata,
|
|
20
|
+
deps: {},
|
|
21
|
+
factory: async () => ({ getId: () => pluginId })
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
class ServiceRegistry {
|
|
25
|
+
static create(factories) {
|
|
26
|
+
const factoryMap = /* @__PURE__ */ new Map();
|
|
27
|
+
for (const factory of factories) {
|
|
28
|
+
if (factory.service.multiton) {
|
|
29
|
+
const existing = factoryMap.get(factory.service.id) ?? [];
|
|
30
|
+
factoryMap.set(
|
|
31
|
+
factory.service.id,
|
|
32
|
+
existing.concat(toInternalServiceFactory(factory))
|
|
33
|
+
);
|
|
34
|
+
} else {
|
|
35
|
+
factoryMap.set(factory.service.id, [toInternalServiceFactory(factory)]);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
const registry = new ServiceRegistry(factoryMap);
|
|
39
|
+
registry.checkForCircularDeps();
|
|
40
|
+
return registry;
|
|
41
|
+
}
|
|
42
|
+
#providedFactories;
|
|
43
|
+
#loadedDefaultFactories;
|
|
44
|
+
#implementations;
|
|
45
|
+
#rootServiceImplementations = /* @__PURE__ */ new Map();
|
|
46
|
+
#addedFactoryIds = /* @__PURE__ */ new Set();
|
|
47
|
+
#instantiatedFactories = /* @__PURE__ */ new Set();
|
|
48
|
+
constructor(factories) {
|
|
49
|
+
this.#providedFactories = factories;
|
|
50
|
+
this.#loadedDefaultFactories = /* @__PURE__ */ new Map();
|
|
51
|
+
this.#implementations = /* @__PURE__ */ new Map();
|
|
52
|
+
}
|
|
53
|
+
#resolveFactory(ref, pluginId) {
|
|
54
|
+
if (ref.id === backendPluginApi.coreServices.pluginMetadata.id) {
|
|
55
|
+
return Promise.resolve([
|
|
56
|
+
toInternalServiceFactory(createPluginMetadataServiceFactory(pluginId))
|
|
57
|
+
]);
|
|
58
|
+
}
|
|
59
|
+
let resolvedFactory = this.#providedFactories.get(ref.id);
|
|
60
|
+
const { __defaultFactory: defaultFactory } = ref;
|
|
61
|
+
if (!resolvedFactory && !defaultFactory) {
|
|
62
|
+
return void 0;
|
|
63
|
+
}
|
|
64
|
+
if (!resolvedFactory) {
|
|
65
|
+
let loadedFactory = this.#loadedDefaultFactories.get(defaultFactory);
|
|
66
|
+
if (!loadedFactory) {
|
|
67
|
+
loadedFactory = Promise.resolve().then(() => defaultFactory(ref)).then(
|
|
68
|
+
(f) => toInternalServiceFactory(typeof f === "function" ? f() : f)
|
|
69
|
+
);
|
|
70
|
+
this.#loadedDefaultFactories.set(defaultFactory, loadedFactory);
|
|
71
|
+
}
|
|
72
|
+
resolvedFactory = loadedFactory.then(
|
|
73
|
+
(factory) => [factory],
|
|
74
|
+
(error) => {
|
|
75
|
+
throw new Error(
|
|
76
|
+
`Failed to instantiate service '${ref.id}' because the default factory loader threw an error, ${errors.stringifyError(
|
|
77
|
+
error
|
|
78
|
+
)}`
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
return Promise.resolve(resolvedFactory);
|
|
84
|
+
}
|
|
85
|
+
#checkForMissingDeps(factory, pluginId) {
|
|
86
|
+
const missingDeps = Object.values(factory.deps).filter((ref) => {
|
|
87
|
+
if (ref.id === backendPluginApi.coreServices.pluginMetadata.id) {
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
if (this.#providedFactories.get(ref.id)) {
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
if (ref.multiton) {
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
return !ref.__defaultFactory;
|
|
97
|
+
});
|
|
98
|
+
if (missingDeps.length) {
|
|
99
|
+
const missing = missingDeps.map((r) => `'${r.id}'`).join(", ");
|
|
100
|
+
throw new Error(
|
|
101
|
+
`Failed to instantiate service '${factory.service.id}' for '${pluginId}' because the following dependent services are missing: ${missing}`
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
checkForCircularDeps() {
|
|
106
|
+
const graph = DependencyGraph.DependencyGraph.fromIterable(
|
|
107
|
+
Array.from(this.#providedFactories).map(([serviceId, factories]) => ({
|
|
108
|
+
value: serviceId,
|
|
109
|
+
provides: [serviceId],
|
|
110
|
+
consumes: factories.flatMap(
|
|
111
|
+
(factory) => Object.values(factory.deps).map((d) => d.id)
|
|
112
|
+
)
|
|
113
|
+
}))
|
|
114
|
+
);
|
|
115
|
+
const circularDependencies = Array.from(graph.detectCircularDependencies());
|
|
116
|
+
if (circularDependencies.length) {
|
|
117
|
+
const cycles = circularDependencies.map((c) => c.map((id) => `'${id}'`).join(" -> ")).join("\n ");
|
|
118
|
+
throw new errors.ConflictError(`Circular dependencies detected:
|
|
119
|
+
${cycles}`);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
add(factory) {
|
|
123
|
+
const factoryId = factory.service.id;
|
|
124
|
+
if (factoryId === backendPluginApi.coreServices.pluginMetadata.id) {
|
|
125
|
+
throw new Error(
|
|
126
|
+
`The ${backendPluginApi.coreServices.pluginMetadata.id} service cannot be overridden`
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
if (this.#instantiatedFactories.has(factoryId)) {
|
|
130
|
+
throw new Error(
|
|
131
|
+
`Unable to set service factory with id ${factoryId}, service has already been instantiated`
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
if (factory.service.multiton) {
|
|
135
|
+
const newFactories = (this.#providedFactories.get(factoryId) ?? []).concat(toInternalServiceFactory(factory));
|
|
136
|
+
this.#providedFactories.set(factoryId, newFactories);
|
|
137
|
+
} else {
|
|
138
|
+
if (this.#addedFactoryIds.has(factoryId)) {
|
|
139
|
+
throw new Error(
|
|
140
|
+
`Duplicate service implementations provided for ${factoryId}`
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
this.#addedFactoryIds.add(factoryId);
|
|
144
|
+
this.#providedFactories.set(factoryId, [
|
|
145
|
+
toInternalServiceFactory(factory)
|
|
146
|
+
]);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
async initializeEagerServicesWithScope(scope, pluginId = "root") {
|
|
150
|
+
for (const [factory] of this.#providedFactories.values()) {
|
|
151
|
+
if (factory.service.scope === scope) {
|
|
152
|
+
if (scope === "root" && factory.initialization !== "lazy") {
|
|
153
|
+
await this.get(factory.service, pluginId);
|
|
154
|
+
} else if (scope === "plugin" && factory.initialization === "always") {
|
|
155
|
+
await this.get(factory.service, pluginId);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
get(ref, pluginId) {
|
|
161
|
+
this.#instantiatedFactories.add(ref.id);
|
|
162
|
+
const resolvedFactory = this.#resolveFactory(ref, pluginId);
|
|
163
|
+
if (!resolvedFactory) {
|
|
164
|
+
return ref.multiton ? Promise.resolve([]) : void 0;
|
|
165
|
+
}
|
|
166
|
+
return resolvedFactory.then((factories) => {
|
|
167
|
+
return Promise.all(
|
|
168
|
+
factories.map((factory) => {
|
|
169
|
+
if (factory.service.scope === "root") {
|
|
170
|
+
let existing = this.#rootServiceImplementations.get(factory);
|
|
171
|
+
if (!existing) {
|
|
172
|
+
this.#checkForMissingDeps(factory, pluginId);
|
|
173
|
+
const rootDeps = new Array();
|
|
174
|
+
for (const [name, serviceRef] of Object.entries(factory.deps)) {
|
|
175
|
+
if (serviceRef.scope !== "root") {
|
|
176
|
+
throw new Error(
|
|
177
|
+
`Failed to instantiate 'root' scoped service '${ref.id}' because it depends on '${serviceRef.scope}' scoped service '${serviceRef.id}'.`
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
const target = this.get(serviceRef, pluginId);
|
|
181
|
+
rootDeps.push(target.then((impl) => [name, impl]));
|
|
182
|
+
}
|
|
183
|
+
existing = Promise.all(rootDeps).then(
|
|
184
|
+
(entries) => factory.factory(Object.fromEntries(entries), void 0)
|
|
185
|
+
);
|
|
186
|
+
this.#rootServiceImplementations.set(factory, existing);
|
|
187
|
+
}
|
|
188
|
+
return existing;
|
|
189
|
+
}
|
|
190
|
+
let implementation = this.#implementations.get(factory);
|
|
191
|
+
if (!implementation) {
|
|
192
|
+
this.#checkForMissingDeps(factory, pluginId);
|
|
193
|
+
const rootDeps = new Array();
|
|
194
|
+
for (const [name, serviceRef] of Object.entries(factory.deps)) {
|
|
195
|
+
if (serviceRef.scope === "root") {
|
|
196
|
+
const target = this.get(serviceRef, pluginId);
|
|
197
|
+
rootDeps.push(target.then((impl) => [name, impl]));
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
implementation = {
|
|
201
|
+
context: Promise.all(rootDeps).then(
|
|
202
|
+
(entries) => factory.createRootContext?.(Object.fromEntries(entries))
|
|
203
|
+
).catch((error) => {
|
|
204
|
+
const cause = errors.stringifyError(error);
|
|
205
|
+
throw new Error(
|
|
206
|
+
`Failed to instantiate service '${ref.id}' because createRootContext threw an error, ${cause}`
|
|
207
|
+
);
|
|
208
|
+
}),
|
|
209
|
+
byPlugin: /* @__PURE__ */ new Map()
|
|
210
|
+
};
|
|
211
|
+
this.#implementations.set(factory, implementation);
|
|
212
|
+
}
|
|
213
|
+
let result = implementation.byPlugin.get(pluginId);
|
|
214
|
+
if (!result) {
|
|
215
|
+
const allDeps = new Array();
|
|
216
|
+
for (const [name, serviceRef] of Object.entries(factory.deps)) {
|
|
217
|
+
const target = this.get(serviceRef, pluginId);
|
|
218
|
+
allDeps.push(target.then((impl) => [name, impl]));
|
|
219
|
+
}
|
|
220
|
+
result = implementation.context.then(
|
|
221
|
+
(context) => Promise.all(allDeps).then(
|
|
222
|
+
(entries) => factory.factory(Object.fromEntries(entries), context)
|
|
223
|
+
)
|
|
224
|
+
).catch((error) => {
|
|
225
|
+
const cause = errors.stringifyError(error);
|
|
226
|
+
throw new Error(
|
|
227
|
+
`Failed to instantiate service '${ref.id}' for '${pluginId}' because the factory function threw an error, ${cause}`
|
|
228
|
+
);
|
|
229
|
+
});
|
|
230
|
+
implementation.byPlugin.set(pluginId, result);
|
|
231
|
+
}
|
|
232
|
+
return result;
|
|
233
|
+
})
|
|
234
|
+
);
|
|
235
|
+
}).then((results) => ref.multiton ? results : results[0]);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
exports.ServiceRegistry = ServiceRegistry;
|
|
240
|
+
//# sourceMappingURL=ServiceRegistry.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ServiceRegistry.cjs.js","sources":["../../../../../backend-app-api/src/wiring/ServiceRegistry.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ServiceFactory,\n ServiceRef,\n coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { ConflictError, stringifyError } from '@backstage/errors';\n// Direct internal import to avoid duplication\n// eslint-disable-next-line @backstage/no-forbidden-package-imports\nimport { InternalServiceFactory } from '@backstage/backend-plugin-api/src/services/system/types';\nimport { DependencyGraph } from '../lib/DependencyGraph';\n/**\n * Keep in sync with `@backstage/backend-plugin-api/src/services/system/types.ts`\n * @internal\n */\nexport type InternalServiceRef = ServiceRef<unknown> & {\n __defaultFactory?: (\n service: ServiceRef<unknown>,\n ) => Promise<ServiceFactory | (() => ServiceFactory)>;\n};\n\nfunction toInternalServiceFactory<TService, TScope extends 'plugin' | 'root'>(\n factory: ServiceFactory<TService, TScope>,\n): InternalServiceFactory<TService, TScope> {\n const f = factory as InternalServiceFactory<TService, TScope>;\n if (f.$$type !== '@backstage/BackendFeature') {\n throw new Error(`Invalid service factory, bad type '${f.$$type}'`);\n }\n if (f.version !== 'v1') {\n throw new Error(`Invalid service factory, bad version '${f.version}'`);\n }\n return f;\n}\n\nfunction createPluginMetadataServiceFactory(pluginId: string) {\n return createServiceFactory({\n service: coreServices.pluginMetadata,\n deps: {},\n factory: async () => ({ getId: () => pluginId }),\n });\n}\n\nexport class ServiceRegistry {\n static create(factories: Array<ServiceFactory>): ServiceRegistry {\n const factoryMap = new Map<string, InternalServiceFactory[]>();\n for (const factory of factories) {\n if (factory.service.multiton) {\n const existing = factoryMap.get(factory.service.id) ?? [];\n factoryMap.set(\n factory.service.id,\n existing.concat(toInternalServiceFactory(factory)),\n );\n } else {\n factoryMap.set(factory.service.id, [toInternalServiceFactory(factory)]);\n }\n }\n const registry = new ServiceRegistry(factoryMap);\n registry.checkForCircularDeps();\n return registry;\n }\n\n readonly #providedFactories: Map<string, InternalServiceFactory[]>;\n readonly #loadedDefaultFactories: Map<\n Function,\n Promise<InternalServiceFactory>\n >;\n readonly #implementations: Map<\n InternalServiceFactory,\n {\n context: Promise<unknown>;\n byPlugin: Map<string, Promise<unknown>>;\n }\n >;\n readonly #rootServiceImplementations = new Map<\n InternalServiceFactory,\n Promise<unknown>\n >();\n readonly #addedFactoryIds = new Set<string>();\n readonly #instantiatedFactories = new Set<string>();\n\n private constructor(factories: Map<string, InternalServiceFactory[]>) {\n this.#providedFactories = factories;\n this.#loadedDefaultFactories = new Map();\n this.#implementations = new Map();\n }\n\n #resolveFactory(\n ref: ServiceRef<unknown>,\n pluginId: string,\n ): Promise<InternalServiceFactory[]> | undefined {\n // Special case handling of the plugin metadata service, generating a custom factory for it each time\n if (ref.id === coreServices.pluginMetadata.id) {\n return Promise.resolve([\n toInternalServiceFactory(createPluginMetadataServiceFactory(pluginId)),\n ]);\n }\n\n let resolvedFactory:\n | Promise<InternalServiceFactory[]>\n | InternalServiceFactory[]\n | undefined = this.#providedFactories.get(ref.id);\n const { __defaultFactory: defaultFactory } = ref as InternalServiceRef;\n if (!resolvedFactory && !defaultFactory) {\n return undefined;\n }\n\n if (!resolvedFactory) {\n let loadedFactory = this.#loadedDefaultFactories.get(defaultFactory!);\n if (!loadedFactory) {\n loadedFactory = Promise.resolve()\n .then(() => defaultFactory!(ref))\n .then(f =>\n toInternalServiceFactory(typeof f === 'function' ? f() : f),\n );\n this.#loadedDefaultFactories.set(defaultFactory!, loadedFactory);\n }\n resolvedFactory = loadedFactory.then(\n factory => [factory],\n error => {\n throw new Error(\n `Failed to instantiate service '${\n ref.id\n }' because the default factory loader threw an error, ${stringifyError(\n error,\n )}`,\n );\n },\n );\n }\n\n return Promise.resolve(resolvedFactory);\n }\n\n #checkForMissingDeps(factory: InternalServiceFactory, pluginId: string) {\n const missingDeps = Object.values(factory.deps).filter(ref => {\n if (ref.id === coreServices.pluginMetadata.id) {\n return false;\n }\n if (this.#providedFactories.get(ref.id)) {\n return false;\n }\n if (ref.multiton) {\n return false;\n }\n\n return !(ref as InternalServiceRef).__defaultFactory;\n });\n\n if (missingDeps.length) {\n const missing = missingDeps.map(r => `'${r.id}'`).join(', ');\n throw new Error(\n `Failed to instantiate service '${factory.service.id}' for '${pluginId}' because the following dependent services are missing: ${missing}`,\n );\n }\n }\n\n checkForCircularDeps(): void {\n const graph = DependencyGraph.fromIterable(\n Array.from(this.#providedFactories).map(([serviceId, factories]) => ({\n value: serviceId,\n provides: [serviceId],\n consumes: factories.flatMap(factory =>\n Object.values(factory.deps).map(d => d.id),\n ),\n })),\n );\n const circularDependencies = Array.from(graph.detectCircularDependencies());\n\n if (circularDependencies.length) {\n const cycles = circularDependencies\n .map(c => c.map(id => `'${id}'`).join(' -> '))\n .join('\\n ');\n\n throw new ConflictError(`Circular dependencies detected:\\n ${cycles}`);\n }\n }\n\n add(factory: ServiceFactory) {\n const factoryId = factory.service.id;\n if (factoryId === coreServices.pluginMetadata.id) {\n throw new Error(\n `The ${coreServices.pluginMetadata.id} service cannot be overridden`,\n );\n }\n\n if (this.#instantiatedFactories.has(factoryId)) {\n throw new Error(\n `Unable to set service factory with id ${factoryId}, service has already been instantiated`,\n );\n }\n\n if (factory.service.multiton) {\n const newFactories = (\n this.#providedFactories.get(factoryId) ?? []\n ).concat(toInternalServiceFactory(factory));\n this.#providedFactories.set(factoryId, newFactories);\n } else {\n if (this.#addedFactoryIds.has(factoryId)) {\n throw new Error(\n `Duplicate service implementations provided for ${factoryId}`,\n );\n }\n\n this.#addedFactoryIds.add(factoryId);\n this.#providedFactories.set(factoryId, [\n toInternalServiceFactory(factory),\n ]);\n }\n }\n\n async initializeEagerServicesWithScope(\n scope: 'root' | 'plugin',\n pluginId: string = 'root',\n ) {\n for (const [factory] of this.#providedFactories.values()) {\n if (factory.service.scope === scope) {\n // Root-scoped services are eager by default, plugin-scoped are lazy by default\n if (scope === 'root' && factory.initialization !== 'lazy') {\n await this.get(factory.service, pluginId);\n } else if (scope === 'plugin' && factory.initialization === 'always') {\n await this.get(factory.service, pluginId);\n }\n }\n }\n }\n\n get<T, TInstances extends 'singleton' | 'multiton'>(\n ref: ServiceRef<T, 'plugin' | 'root', TInstances>,\n pluginId: string,\n ): Promise<TInstances extends 'multiton' ? T[] : T> | undefined {\n this.#instantiatedFactories.add(ref.id);\n\n const resolvedFactory = this.#resolveFactory(ref, pluginId);\n\n if (!resolvedFactory) {\n return ref.multiton\n ? (Promise.resolve([]) as\n | Promise<TInstances extends 'multiton' ? T[] : T>\n | undefined)\n : undefined;\n }\n\n return resolvedFactory\n .then(factories => {\n return Promise.all(\n factories.map(factory => {\n if (factory.service.scope === 'root') {\n let existing = this.#rootServiceImplementations.get(factory);\n if (!existing) {\n this.#checkForMissingDeps(factory, pluginId);\n const rootDeps = new Array<\n Promise<[name: string, impl: unknown]>\n >();\n\n for (const [name, serviceRef] of Object.entries(factory.deps)) {\n if (serviceRef.scope !== 'root') {\n throw new Error(\n `Failed to instantiate 'root' scoped service '${ref.id}' because it depends on '${serviceRef.scope}' scoped service '${serviceRef.id}'.`,\n );\n }\n const target = this.get(serviceRef, pluginId)!;\n rootDeps.push(target.then(impl => [name, impl]));\n }\n\n existing = Promise.all(rootDeps).then(entries =>\n factory.factory(Object.fromEntries(entries), undefined),\n );\n this.#rootServiceImplementations.set(factory, existing);\n }\n return existing as Promise<T>;\n }\n\n let implementation = this.#implementations.get(factory);\n if (!implementation) {\n this.#checkForMissingDeps(factory, pluginId);\n const rootDeps = new Array<\n Promise<[name: string, impl: unknown]>\n >();\n\n for (const [name, serviceRef] of Object.entries(factory.deps)) {\n if (serviceRef.scope === 'root') {\n const target = this.get(serviceRef, pluginId)!;\n rootDeps.push(target.then(impl => [name, impl]));\n }\n }\n\n implementation = {\n context: Promise.all(rootDeps)\n .then(entries =>\n factory.createRootContext?.(Object.fromEntries(entries)),\n )\n .catch(error => {\n const cause = stringifyError(error);\n throw new Error(\n `Failed to instantiate service '${ref.id}' because createRootContext threw an error, ${cause}`,\n );\n }),\n byPlugin: new Map(),\n };\n\n this.#implementations.set(factory, implementation);\n }\n\n let result = implementation.byPlugin.get(pluginId) as Promise<any>;\n if (!result) {\n const allDeps = new Array<\n Promise<[name: string, impl: unknown]>\n >();\n\n for (const [name, serviceRef] of Object.entries(factory.deps)) {\n const target = this.get(serviceRef, pluginId)!;\n allDeps.push(target.then(impl => [name, impl]));\n }\n\n result = implementation.context\n .then(context =>\n Promise.all(allDeps).then(entries =>\n factory.factory(Object.fromEntries(entries), context),\n ),\n )\n .catch(error => {\n const cause = stringifyError(error);\n throw new Error(\n `Failed to instantiate service '${ref.id}' for '${pluginId}' because the factory function threw an error, ${cause}`,\n );\n });\n implementation.byPlugin.set(pluginId, result);\n }\n return result;\n }),\n );\n })\n .then(results => (ref.multiton ? results : results[0]));\n }\n}\n"],"names":["createServiceFactory","coreServices","stringifyError","DependencyGraph","ConflictError"],"mappings":";;;;;;AAqCA,SAAS,yBACP,OAC0C,EAAA;AAC1C,EAAA,MAAM,CAAI,GAAA,OAAA,CAAA;AACV,EAAI,IAAA,CAAA,CAAE,WAAW,2BAA6B,EAAA;AAC5C,IAAA,MAAM,IAAI,KAAA,CAAM,CAAsC,mCAAA,EAAA,CAAA,CAAE,MAAM,CAAG,CAAA,CAAA,CAAA,CAAA;AAAA,GACnE;AACA,EAAI,IAAA,CAAA,CAAE,YAAY,IAAM,EAAA;AACtB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAyC,sCAAA,EAAA,CAAA,CAAE,OAAO,CAAG,CAAA,CAAA,CAAA,CAAA;AAAA,GACvE;AACA,EAAO,OAAA,CAAA,CAAA;AACT,CAAA;AAEA,SAAS,mCAAmC,QAAkB,EAAA;AAC5D,EAAA,OAAOA,qCAAqB,CAAA;AAAA,IAC1B,SAASC,6BAAa,CAAA,cAAA;AAAA,IACtB,MAAM,EAAC;AAAA,IACP,OAAS,EAAA,aAAa,EAAE,KAAA,EAAO,MAAM,QAAS,EAAA,CAAA;AAAA,GAC/C,CAAA,CAAA;AACH,CAAA;AAEO,MAAM,eAAgB,CAAA;AAAA,EAC3B,OAAO,OAAO,SAAmD,EAAA;AAC/D,IAAM,MAAA,UAAA,uBAAiB,GAAsC,EAAA,CAAA;AAC7D,IAAA,KAAA,MAAW,WAAW,SAAW,EAAA;AAC/B,MAAI,IAAA,OAAA,CAAQ,QAAQ,QAAU,EAAA;AAC5B,QAAA,MAAM,WAAW,UAAW,CAAA,GAAA,CAAI,QAAQ,OAAQ,CAAA,EAAE,KAAK,EAAC,CAAA;AACxD,QAAW,UAAA,CAAA,GAAA;AAAA,UACT,QAAQ,OAAQ,CAA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OAAA,MAAA,CAAA;AAAA,SACR,CAAA;AAAA,OACH,CAAA;AAAA,KACD,EACA,IAAK,CAAA,CAAA,OAAA,KAAY,IAAI,QAAW,GAAA,OAAA,GAAU,OAAQ,CAAA,CAAC,CAAE,CAAA,CAAA;AAAA,GAC1D;AACF;;;;"}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var Keyv = require('keyv');
|
|
4
|
+
var isDockerDisabledForTests = require('../util/isDockerDisabledForTests.cjs.js');
|
|
5
|
+
var memcache = require('./memcache.cjs.js');
|
|
6
|
+
var redis = require('./redis.cjs.js');
|
|
7
|
+
var types = require('./types.cjs.js');
|
|
8
|
+
|
|
9
|
+
function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
|
|
10
|
+
|
|
11
|
+
var Keyv__default = /*#__PURE__*/_interopDefaultCompat(Keyv);
|
|
12
|
+
|
|
13
|
+
class TestCaches {
|
|
14
|
+
instanceById;
|
|
15
|
+
supportedIds;
|
|
16
|
+
static defaultIds;
|
|
17
|
+
/**
|
|
18
|
+
* Creates an empty `TestCaches` instance, and sets up Jest to clean up all of
|
|
19
|
+
* its acquired resources after all tests finish.
|
|
20
|
+
*
|
|
21
|
+
* You typically want to create just a single instance like this at the top of
|
|
22
|
+
* your test file or `describe` block, and then call `init` many times on that
|
|
23
|
+
* instance inside the individual tests. Spinning up a "physical" cache
|
|
24
|
+
* instance takes a considerable amount of time, slowing down tests. But
|
|
25
|
+
* wiping the contents of an instance using `init` is very fast.
|
|
26
|
+
*/
|
|
27
|
+
static create(options) {
|
|
28
|
+
const ids = options?.ids;
|
|
29
|
+
const disableDocker = options?.disableDocker ?? isDockerDisabledForTests.isDockerDisabledForTests();
|
|
30
|
+
let testCacheIds;
|
|
31
|
+
if (ids) {
|
|
32
|
+
testCacheIds = ids;
|
|
33
|
+
} else if (TestCaches.defaultIds) {
|
|
34
|
+
testCacheIds = TestCaches.defaultIds;
|
|
35
|
+
} else {
|
|
36
|
+
testCacheIds = Object.keys(types.allCaches);
|
|
37
|
+
}
|
|
38
|
+
const supportedIds = testCacheIds.filter((id) => {
|
|
39
|
+
const properties = types.allCaches[id];
|
|
40
|
+
if (!properties) {
|
|
41
|
+
return false;
|
|
42
|
+
}
|
|
43
|
+
if (properties.connectionStringEnvironmentVariableName && process.env[properties.connectionStringEnvironmentVariableName]) {
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
if (!properties.dockerImageName) {
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
if (disableDocker) {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
return true;
|
|
53
|
+
});
|
|
54
|
+
const caches = new TestCaches(supportedIds);
|
|
55
|
+
if (supportedIds.length > 0) {
|
|
56
|
+
afterAll(async () => {
|
|
57
|
+
await caches.shutdown();
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
return caches;
|
|
61
|
+
}
|
|
62
|
+
static setDefaults(options) {
|
|
63
|
+
TestCaches.defaultIds = options.ids;
|
|
64
|
+
}
|
|
65
|
+
constructor(supportedIds) {
|
|
66
|
+
this.instanceById = /* @__PURE__ */ new Map();
|
|
67
|
+
this.supportedIds = supportedIds;
|
|
68
|
+
}
|
|
69
|
+
supports(id) {
|
|
70
|
+
return this.supportedIds.includes(id);
|
|
71
|
+
}
|
|
72
|
+
eachSupportedId() {
|
|
73
|
+
return this.supportedIds.map((id) => [id]);
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Returns a fresh, empty cache for the given driver.
|
|
77
|
+
*
|
|
78
|
+
* @param id - The ID of the cache to use, e.g. 'REDIS_7'
|
|
79
|
+
* @returns Cache connection properties
|
|
80
|
+
*/
|
|
81
|
+
async init(id) {
|
|
82
|
+
const properties = types.allCaches[id];
|
|
83
|
+
if (!properties) {
|
|
84
|
+
const candidates = Object.keys(types.allCaches).join(", ");
|
|
85
|
+
throw new Error(
|
|
86
|
+
`Unknown test cache ${id}, possible values are ${candidates}`
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
if (!this.supportedIds.includes(id)) {
|
|
90
|
+
const candidates = this.supportedIds.join(", ");
|
|
91
|
+
throw new Error(
|
|
92
|
+
`Unsupported test cache ${id} for this environment, possible values are ${candidates}`
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
let instance = this.instanceById.get(id);
|
|
96
|
+
if (!instance) {
|
|
97
|
+
instance = await this.initAny(properties);
|
|
98
|
+
this.instanceById.set(id, instance);
|
|
99
|
+
}
|
|
100
|
+
await instance.keyv.clear();
|
|
101
|
+
return {
|
|
102
|
+
store: instance.store,
|
|
103
|
+
connection: instance.connection,
|
|
104
|
+
keyv: instance.keyv
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
async initAny(properties) {
|
|
108
|
+
switch (properties.store) {
|
|
109
|
+
case "memcache":
|
|
110
|
+
return this.initMemcached(properties);
|
|
111
|
+
case "redis":
|
|
112
|
+
return this.initRedis(properties);
|
|
113
|
+
case "memory":
|
|
114
|
+
return {
|
|
115
|
+
store: "memory",
|
|
116
|
+
connection: "memory",
|
|
117
|
+
keyv: new Keyv__default.default(),
|
|
118
|
+
stop: async () => {
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
default:
|
|
122
|
+
throw new Error(`Unknown cache store '${properties.store}'`);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
async initMemcached(properties) {
|
|
126
|
+
const envVarName = properties.connectionStringEnvironmentVariableName;
|
|
127
|
+
if (envVarName) {
|
|
128
|
+
const connectionString = process.env[envVarName];
|
|
129
|
+
if (connectionString) {
|
|
130
|
+
return memcache.connectToExternalMemcache(connectionString);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return await memcache.startMemcachedContainer(properties.dockerImageName);
|
|
134
|
+
}
|
|
135
|
+
async initRedis(properties) {
|
|
136
|
+
const envVarName = properties.connectionStringEnvironmentVariableName;
|
|
137
|
+
if (envVarName) {
|
|
138
|
+
const connectionString = process.env[envVarName];
|
|
139
|
+
if (connectionString) {
|
|
140
|
+
return redis.connectToExternalRedis(connectionString);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return await redis.startRedisContainer(properties.dockerImageName);
|
|
144
|
+
}
|
|
145
|
+
async shutdown() {
|
|
146
|
+
const instances = [...this.instanceById.values()];
|
|
147
|
+
this.instanceById.clear();
|
|
148
|
+
await Promise.all(
|
|
149
|
+
instances.map(
|
|
150
|
+
({ stop }) => stop().catch((error) => {
|
|
151
|
+
console.warn(`TestCaches: Failed to stop container`, { error });
|
|
152
|
+
})
|
|
153
|
+
)
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
exports.TestCaches = TestCaches;
|
|
159
|
+
//# sourceMappingURL=TestCaches.cjs.js.map
|