@backstage/backend-defaults 0.18.1-next.1 → 0.18.1-next.3
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 +19 -0
- package/config.schema.json +4 -0
- package/dist/CreateBackend.cjs.js +1 -0
- package/dist/CreateBackend.cjs.js.map +1 -1
- package/dist/alpha/entrypoints/connections/connectionsServiceFactory.cjs.js +25 -0
- package/dist/alpha/entrypoints/connections/connectionsServiceFactory.cjs.js.map +1 -0
- package/dist/alpha.cjs.js +2 -0
- package/dist/alpha.cjs.js.map +1 -1
- package/dist/alpha.d.ts +9 -1
- package/dist/{package.json.cjs.js → backend-defaults/package.json.cjs.js} +1 -1
- package/dist/connections-node/src/DefaultConnectionsService.cjs.js +133 -0
- package/dist/connections-node/src/DefaultConnectionsService.cjs.js.map +1 -0
- package/dist/connections-node/src/lookup.cjs.js +11 -0
- package/dist/connections-node/src/lookup.cjs.js.map +1 -0
- package/dist/connections-node/src/lookupStrategies.cjs.js +30 -0
- package/dist/connections-node/src/lookupStrategies.cjs.js.map +1 -0
- package/dist/entrypoints/database/DatabaseManager.cjs.js +1 -1
- package/dist/entrypoints/database/DatabaseManager.cjs.js.map +1 -1
- package/dist/entrypoints/database/connectors/mysql.cjs.js +1 -0
- package/dist/entrypoints/database/connectors/mysql.cjs.js.map +1 -1
- package/dist/entrypoints/database/connectors/postgres.cjs.js +19 -2
- package/dist/entrypoints/database/connectors/postgres.cjs.js.map +1 -1
- package/dist/entrypoints/urlReader/lib/GoogleGcsUrlReader.cjs.js +1 -1
- package/package.json +7 -6
- /package/dist/{package.json.cjs.js.map → backend-defaults/package.json.cjs.js.map} +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
# @backstage/backend-defaults
|
|
2
2
|
|
|
3
|
+
## 0.18.1-next.3
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- f6054ac: Backends created with `createBackend` now provide the experimental connections service by default. Custom backends can install `connectionsServiceFactory` from `@backstage/backend-defaults/alpha`.
|
|
8
|
+
- bd1ff39: Fixed AWS RDS IAM authentication tokens being reused after their signing credentials expire, which could cause database connection failures when using temporary AWS credentials.
|
|
9
|
+
- Updated dependencies
|
|
10
|
+
- @backstage/backend-plugin-api@1.11.0-next.2
|
|
11
|
+
- @backstage/backend-app-api@1.8.0-next.2
|
|
12
|
+
|
|
13
|
+
## 0.18.1-next.2
|
|
14
|
+
|
|
15
|
+
### Patch Changes
|
|
16
|
+
|
|
17
|
+
- a6bc5e4: Stopped issuing periodic per-plugin database keepalive queries by default and changed the default minimum PostgreSQL and MySQL connection pool size to zero. Idle connections can now be retired after the configured timeout, while explicitly configured pool minimums are preserved. Set `backend.database.keepalive: true` to continue issuing the periodic queries.
|
|
18
|
+
- Updated dependencies
|
|
19
|
+
- @backstage/cli-node@0.3.5-next.1
|
|
20
|
+
- @backstage/integration@2.1.3-next.1
|
|
21
|
+
|
|
3
22
|
## 0.18.1-next.1
|
|
4
23
|
|
|
5
24
|
### Patch Changes
|
package/config.schema.json
CHANGED
|
@@ -1053,6 +1053,10 @@
|
|
|
1053
1053
|
"type": "string",
|
|
1054
1054
|
"description": "Database name prefix override"
|
|
1055
1055
|
},
|
|
1056
|
+
"keepalive": {
|
|
1057
|
+
"type": "boolean",
|
|
1058
|
+
"description": "Whether to run a query every minute for each plugin database client to keep its connections active. Defaults to false."
|
|
1059
|
+
},
|
|
1056
1060
|
"schemaPrefix": {
|
|
1057
1061
|
"type": "string",
|
|
1058
1062
|
"description": "Prefix for schema names when using pluginDivisionMode: schema.",
|
|
@@ -52,6 +52,7 @@ const defaultServiceFactories = [
|
|
|
52
52
|
alpha.actionsServiceFactory,
|
|
53
53
|
alpha.metricsServiceFactory,
|
|
54
54
|
alpha.tracingServiceFactory,
|
|
55
|
+
alpha.connectionsServiceFactory,
|
|
55
56
|
// Unexported alpha services kept around for compatibility reasons
|
|
56
57
|
instanceMetadataServiceFactory.instanceMetadataServiceFactory
|
|
57
58
|
];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CreateBackend.cjs.js","sources":["../src/CreateBackend.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 { Backend, createSpecializedBackend } from '@backstage/backend-app-api';\nimport { ServiceFactory } from '@backstage/backend-plugin-api';\nimport { auditorServiceFactory } from '@backstage/backend-defaults/auditor';\nimport { authServiceFactory } from '@backstage/backend-defaults/auth';\nimport { cacheServiceFactory } from '@backstage/backend-defaults/cache';\nimport { databaseServiceFactory } from '@backstage/backend-defaults/database';\nimport { discoveryServiceFactory } from '@backstage/backend-defaults/discovery';\nimport { httpAuthServiceFactory } from '@backstage/backend-defaults/httpAuth';\nimport { httpRouterServiceFactory } from '@backstage/backend-defaults/httpRouter';\nimport { lifecycleServiceFactory } from '@backstage/backend-defaults/lifecycle';\nimport { loggerServiceFactory } from '@backstage/backend-defaults/logger';\nimport { permissionsServiceFactory } from '@backstage/backend-defaults/permissions';\nimport { permissionsRegistryServiceFactory } from '@backstage/backend-defaults/permissionsRegistry';\nimport { rootConfigServiceFactory } from '@backstage/backend-defaults/rootConfig';\nimport { rootHealthServiceFactory } from '@backstage/backend-defaults/rootHealth';\nimport { rootHttpRouterServiceFactory } from '@backstage/backend-defaults/rootHttpRouter';\nimport { rootLifecycleServiceFactory } from '@backstage/backend-defaults/rootLifecycle';\nimport { rootLoggerServiceFactory } from '@backstage/backend-defaults/rootLogger';\nimport { rootSystemMetadataServiceFactory } from '@backstage/backend-defaults/rootSystemMetadata';\nimport { schedulerServiceFactory } from '@backstage/backend-defaults/scheduler';\nimport { urlReaderServiceFactory } from '@backstage/backend-defaults/urlReader';\nimport { userInfoServiceFactory } from '@backstage/backend-defaults/userInfo';\nimport { eventsServiceFactory } from '@backstage/plugin-events-node';\nimport {\n actionsRegistryServiceFactory,\n actionsServiceFactory,\n metricsServiceFactory,\n tracingServiceFactory,\n} from '@backstage/backend-defaults/alpha';\nimport { instanceMetadataServiceFactory } from './alpha/entrypoints/instanceMetadata/instanceMetadataServiceFactory';\n\n/** @public */\nexport const defaultServiceFactories: ServiceFactory[] = [\n auditorServiceFactory,\n authServiceFactory,\n cacheServiceFactory,\n rootConfigServiceFactory,\n databaseServiceFactory,\n discoveryServiceFactory,\n httpAuthServiceFactory,\n httpRouterServiceFactory,\n lifecycleServiceFactory,\n loggerServiceFactory,\n permissionsServiceFactory,\n permissionsRegistryServiceFactory,\n rootHealthServiceFactory,\n rootHttpRouterServiceFactory,\n rootLifecycleServiceFactory,\n rootLoggerServiceFactory,\n rootSystemMetadataServiceFactory,\n schedulerServiceFactory,\n userInfoServiceFactory,\n urlReaderServiceFactory,\n eventsServiceFactory,\n\n // alpha services\n actionsRegistryServiceFactory,\n actionsServiceFactory,\n metricsServiceFactory,\n tracingServiceFactory,\n\n // Unexported alpha services kept around for compatibility reasons\n instanceMetadataServiceFactory,\n];\n\n/** @public */\nexport interface CreateBackendOptions {\n /**\n * The globally unique identifier of this specific Backstage backend\n * instance.\n *\n * If omitted, a UUID is generated. Any provided value must not be used by\n * any other backend instance, including after this instance has stopped.\n */\n instanceId?: string;\n}\n\n/**\n * @public\n */\nexport function createBackend(options: CreateBackendOptions = {}): Backend {\n return createSpecializedBackend({\n defaultServiceFactories,\n instanceId: options.instanceId,\n });\n}\n"],"names":["auditorServiceFactory","authServiceFactory","cacheServiceFactory","rootConfigServiceFactory","databaseServiceFactory","discoveryServiceFactory","httpAuthServiceFactory","httpRouterServiceFactory","lifecycleServiceFactory","loggerServiceFactory","permissionsServiceFactory","permissionsRegistryServiceFactory","rootHealthServiceFactory","rootHttpRouterServiceFactory","rootLifecycleServiceFactory","rootLoggerServiceFactory","rootSystemMetadataServiceFactory","schedulerServiceFactory","userInfoServiceFactory","urlReaderServiceFactory","eventsServiceFactory","actionsRegistryServiceFactory","actionsServiceFactory","metricsServiceFactory","tracingServiceFactory","instanceMetadataServiceFactory","createSpecializedBackend"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"CreateBackend.cjs.js","sources":["../src/CreateBackend.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 { Backend, createSpecializedBackend } from '@backstage/backend-app-api';\nimport { ServiceFactory } from '@backstage/backend-plugin-api';\nimport { auditorServiceFactory } from '@backstage/backend-defaults/auditor';\nimport { authServiceFactory } from '@backstage/backend-defaults/auth';\nimport { cacheServiceFactory } from '@backstage/backend-defaults/cache';\nimport { databaseServiceFactory } from '@backstage/backend-defaults/database';\nimport { discoveryServiceFactory } from '@backstage/backend-defaults/discovery';\nimport { httpAuthServiceFactory } from '@backstage/backend-defaults/httpAuth';\nimport { httpRouterServiceFactory } from '@backstage/backend-defaults/httpRouter';\nimport { lifecycleServiceFactory } from '@backstage/backend-defaults/lifecycle';\nimport { loggerServiceFactory } from '@backstage/backend-defaults/logger';\nimport { permissionsServiceFactory } from '@backstage/backend-defaults/permissions';\nimport { permissionsRegistryServiceFactory } from '@backstage/backend-defaults/permissionsRegistry';\nimport { rootConfigServiceFactory } from '@backstage/backend-defaults/rootConfig';\nimport { rootHealthServiceFactory } from '@backstage/backend-defaults/rootHealth';\nimport { rootHttpRouterServiceFactory } from '@backstage/backend-defaults/rootHttpRouter';\nimport { rootLifecycleServiceFactory } from '@backstage/backend-defaults/rootLifecycle';\nimport { rootLoggerServiceFactory } from '@backstage/backend-defaults/rootLogger';\nimport { rootSystemMetadataServiceFactory } from '@backstage/backend-defaults/rootSystemMetadata';\nimport { schedulerServiceFactory } from '@backstage/backend-defaults/scheduler';\nimport { urlReaderServiceFactory } from '@backstage/backend-defaults/urlReader';\nimport { userInfoServiceFactory } from '@backstage/backend-defaults/userInfo';\nimport { eventsServiceFactory } from '@backstage/plugin-events-node';\nimport {\n actionsRegistryServiceFactory,\n actionsServiceFactory,\n metricsServiceFactory,\n tracingServiceFactory,\n connectionsServiceFactory,\n} from '@backstage/backend-defaults/alpha';\nimport { instanceMetadataServiceFactory } from './alpha/entrypoints/instanceMetadata/instanceMetadataServiceFactory';\n\n/** @public */\nexport const defaultServiceFactories: ServiceFactory[] = [\n auditorServiceFactory,\n authServiceFactory,\n cacheServiceFactory,\n rootConfigServiceFactory,\n databaseServiceFactory,\n discoveryServiceFactory,\n httpAuthServiceFactory,\n httpRouterServiceFactory,\n lifecycleServiceFactory,\n loggerServiceFactory,\n permissionsServiceFactory,\n permissionsRegistryServiceFactory,\n rootHealthServiceFactory,\n rootHttpRouterServiceFactory,\n rootLifecycleServiceFactory,\n rootLoggerServiceFactory,\n rootSystemMetadataServiceFactory,\n schedulerServiceFactory,\n userInfoServiceFactory,\n urlReaderServiceFactory,\n eventsServiceFactory,\n\n // alpha services\n actionsRegistryServiceFactory,\n actionsServiceFactory,\n metricsServiceFactory,\n tracingServiceFactory,\n connectionsServiceFactory,\n\n // Unexported alpha services kept around for compatibility reasons\n instanceMetadataServiceFactory,\n];\n\n/** @public */\nexport interface CreateBackendOptions {\n /**\n * The globally unique identifier of this specific Backstage backend\n * instance.\n *\n * If omitted, a UUID is generated. Any provided value must not be used by\n * any other backend instance, including after this instance has stopped.\n */\n instanceId?: string;\n}\n\n/**\n * @public\n */\nexport function createBackend(options: CreateBackendOptions = {}): Backend {\n return createSpecializedBackend({\n defaultServiceFactories,\n instanceId: options.instanceId,\n });\n}\n"],"names":["auditorServiceFactory","authServiceFactory","cacheServiceFactory","rootConfigServiceFactory","databaseServiceFactory","discoveryServiceFactory","httpAuthServiceFactory","httpRouterServiceFactory","lifecycleServiceFactory","loggerServiceFactory","permissionsServiceFactory","permissionsRegistryServiceFactory","rootHealthServiceFactory","rootHttpRouterServiceFactory","rootLifecycleServiceFactory","rootLoggerServiceFactory","rootSystemMetadataServiceFactory","schedulerServiceFactory","userInfoServiceFactory","urlReaderServiceFactory","eventsServiceFactory","actionsRegistryServiceFactory","actionsServiceFactory","metricsServiceFactory","tracingServiceFactory","connectionsServiceFactory","instanceMetadataServiceFactory","createSpecializedBackend"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDO,MAAM,uBAAA,GAA4C;AAAA,EACvDA,6BAAA;AAAA,EACAC,uBAAA;AAAA,EACAC,yBAAA;AAAA,EACAC,mCAAA;AAAA,EACAC,+BAAA;AAAA,EACAC,iCAAA;AAAA,EACAC,+BAAA;AAAA,EACAC,mCAAA;AAAA,EACAC,iCAAA;AAAA,EACAC,2BAAA;AAAA,EACAC,qCAAA;AAAA,EACAC,qDAAA;AAAA,EACAC,mCAAA;AAAA,EACAC,2CAAA;AAAA,EACAC,yCAAA;AAAA,EACAC,mCAAA;AAAA,EACAC,mDAAA;AAAA,EACAC,iCAAA;AAAA,EACAC,+BAAA;AAAA,EACAC,iCAAA;AAAA,EACAC,qCAAA;AAAA;AAAA,EAGAC,mCAAA;AAAA,EACAC,2BAAA;AAAA,EACAC,2BAAA;AAAA,EACAC,2BAAA;AAAA,EACAC,+BAAA;AAAA;AAAA,EAGAC;AACF;AAiBO,SAAS,aAAA,CAAc,OAAA,GAAgC,EAAC,EAAY;AACzE,EAAA,OAAOC,sCAAA,CAAyB;AAAA,IAC9B,uBAAA;AAAA,IACA,YAAY,OAAA,CAAQ;AAAA,GACrB,CAAA;AACH;;;"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var backendPluginApi = require('@backstage/backend-plugin-api');
|
|
4
|
+
var alpha = require('@backstage/backend-plugin-api/alpha');
|
|
5
|
+
var DefaultConnectionsService = require('../../../connections-node/src/DefaultConnectionsService.cjs.js');
|
|
6
|
+
|
|
7
|
+
const connectionsServiceFactory = backendPluginApi.createServiceFactory({
|
|
8
|
+
service: alpha.connectionsServiceRef,
|
|
9
|
+
deps: {
|
|
10
|
+
pluginMetadata: backendPluginApi.coreServices.pluginMetadata,
|
|
11
|
+
rootLogger: backendPluginApi.coreServices.rootLogger,
|
|
12
|
+
logger: backendPluginApi.coreServices.logger,
|
|
13
|
+
config: backendPluginApi.coreServices.rootConfig
|
|
14
|
+
},
|
|
15
|
+
async createRootContext({ rootLogger, config }) {
|
|
16
|
+
return DefaultConnectionsService.DefaultConnectionsService.create({ logger: rootLogger, config });
|
|
17
|
+
},
|
|
18
|
+
async factory({ logger, pluginMetadata }, connectionsService) {
|
|
19
|
+
const pluginId = pluginMetadata.getId();
|
|
20
|
+
return connectionsService.forPlugin(pluginId, { logger });
|
|
21
|
+
}
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
exports.connectionsServiceFactory = connectionsServiceFactory;
|
|
25
|
+
//# sourceMappingURL=connectionsServiceFactory.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connectionsServiceFactory.cjs.js","sources":["../../../../src/alpha/entrypoints/connections/connectionsServiceFactory.ts"],"sourcesContent":["/*\n * Copyright 2026 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 coreServices,\n createServiceFactory,\n} from '@backstage/backend-plugin-api';\nimport { connectionsServiceRef } from '@backstage/backend-plugin-api/alpha';\nimport { DefaultConnectionsService } from '@backstage/connections-node';\n\n/**\n * Creates the default plugin-scoped connections service.\n *\n * @alpha\n */\nexport const connectionsServiceFactory = createServiceFactory({\n service: connectionsServiceRef,\n deps: {\n pluginMetadata: coreServices.pluginMetadata,\n rootLogger: coreServices.rootLogger,\n logger: coreServices.logger,\n config: coreServices.rootConfig,\n },\n async createRootContext({ rootLogger, config }) {\n return DefaultConnectionsService.create({ logger: rootLogger, config });\n },\n\n async factory({ logger, pluginMetadata }, connectionsService) {\n const pluginId = pluginMetadata.getId();\n return connectionsService.forPlugin(pluginId, { logger });\n },\n});\n"],"names":["createServiceFactory","connectionsServiceRef","coreServices","DefaultConnectionsService"],"mappings":";;;;;;AA4BO,MAAM,4BAA4BA,qCAAA,CAAqB;AAAA,EAC5D,OAAA,EAASC,2BAAA;AAAA,EACT,IAAA,EAAM;AAAA,IACJ,gBAAgBC,6BAAA,CAAa,cAAA;AAAA,IAC7B,YAAYA,6BAAA,CAAa,UAAA;AAAA,IACzB,QAAQA,6BAAA,CAAa,MAAA;AAAA,IACrB,QAAQA,6BAAA,CAAa;AAAA,GACvB;AAAA,EACA,MAAM,iBAAA,CAAkB,EAAE,UAAA,EAAY,QAAO,EAAG;AAC9C,IAAA,OAAOC,oDAA0B,MAAA,CAAO,EAAE,MAAA,EAAQ,UAAA,EAAY,QAAQ,CAAA;AAAA,EACxE,CAAA;AAAA,EAEA,MAAM,OAAA,CAAQ,EAAE,MAAA,EAAQ,cAAA,IAAkB,kBAAA,EAAoB;AAC5D,IAAA,MAAM,QAAA,GAAW,eAAe,KAAA,EAAM;AACtC,IAAA,OAAO,kBAAA,CAAmB,SAAA,CAAU,QAAA,EAAU,EAAE,QAAQ,CAAA;AAAA,EAC1D;AACF,CAAC;;"}
|
package/dist/alpha.cjs.js
CHANGED
|
@@ -4,6 +4,7 @@ var actionsRegistryServiceFactory = require('./alpha/entrypoints/actionsRegistry
|
|
|
4
4
|
var actionsServiceFactory = require('./alpha/entrypoints/actions/actionsServiceFactory.cjs.js');
|
|
5
5
|
var metricsServiceFactory = require('./alpha/entrypoints/metrics/metricsServiceFactory.cjs.js');
|
|
6
6
|
var tracingServiceFactory = require('./alpha/entrypoints/tracing/tracingServiceFactory.cjs.js');
|
|
7
|
+
var connectionsServiceFactory = require('./alpha/entrypoints/connections/connectionsServiceFactory.cjs.js');
|
|
7
8
|
|
|
8
9
|
|
|
9
10
|
|
|
@@ -11,4 +12,5 @@ exports.actionsRegistryServiceFactory = actionsRegistryServiceFactory.actionsReg
|
|
|
11
12
|
exports.actionsServiceFactory = actionsServiceFactory.actionsServiceFactory;
|
|
12
13
|
exports.metricsServiceFactory = metricsServiceFactory.metricsServiceFactory;
|
|
13
14
|
exports.tracingServiceFactory = tracingServiceFactory.tracingServiceFactory;
|
|
15
|
+
exports.connectionsServiceFactory = connectionsServiceFactory.connectionsServiceFactory;
|
|
14
16
|
//# sourceMappingURL=alpha.cjs.js.map
|
package/dist/alpha.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"alpha.cjs.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"alpha.cjs.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;"}
|
package/dist/alpha.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import * as _backstage_backend_plugin_api from '@backstage/backend-plugin-api';
|
|
2
2
|
import * as _backstage_backend_plugin_api_alpha from '@backstage/backend-plugin-api/alpha';
|
|
3
|
+
import * as _backstage_connections from '@backstage/connections';
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* @public
|
|
@@ -25,4 +26,11 @@ declare const metricsServiceFactory: _backstage_backend_plugin_api.ServiceFactor
|
|
|
25
26
|
*/
|
|
26
27
|
declare const tracingServiceFactory: _backstage_backend_plugin_api.ServiceFactory<_backstage_backend_plugin_api_alpha.TracingService, "plugin", "singleton">;
|
|
27
28
|
|
|
28
|
-
|
|
29
|
+
/**
|
|
30
|
+
* Creates the default plugin-scoped connections service.
|
|
31
|
+
*
|
|
32
|
+
* @alpha
|
|
33
|
+
*/
|
|
34
|
+
declare const connectionsServiceFactory: _backstage_backend_plugin_api.ServiceFactory<_backstage_connections.ConnectionsService, "plugin", "singleton">;
|
|
35
|
+
|
|
36
|
+
export { actionsRegistryServiceFactory, actionsServiceFactory, connectionsServiceFactory, metricsServiceFactory, tracingServiceFactory };
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var config = require('@backstage/connections/config');
|
|
4
|
+
var lookup = require('./lookup.cjs.js');
|
|
5
|
+
var lookupStrategies = require('./lookupStrategies.cjs.js');
|
|
6
|
+
var errors = require('@backstage/errors');
|
|
7
|
+
|
|
8
|
+
function getLookupStrategy(name) {
|
|
9
|
+
return lookupStrategies.lookupStrategies[name];
|
|
10
|
+
}
|
|
11
|
+
function connectionIdentityOf(strategy, connection) {
|
|
12
|
+
if (!strategy.identityField) {
|
|
13
|
+
return void 0;
|
|
14
|
+
}
|
|
15
|
+
const value = connection[strategy.identityField];
|
|
16
|
+
return typeof value === "string" ? value : void 0;
|
|
17
|
+
}
|
|
18
|
+
class PluginConnectionsService {
|
|
19
|
+
logger;
|
|
20
|
+
connections;
|
|
21
|
+
constructor(logger, connections) {
|
|
22
|
+
this.logger = logger;
|
|
23
|
+
this.connections = connections;
|
|
24
|
+
}
|
|
25
|
+
async find(options) {
|
|
26
|
+
const result = await this.findOptional(options);
|
|
27
|
+
if (!result) {
|
|
28
|
+
throw new errors.NotFoundError(
|
|
29
|
+
`Connection not found for type "${options.type}"`
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
return result;
|
|
33
|
+
}
|
|
34
|
+
async findOptional({
|
|
35
|
+
type,
|
|
36
|
+
query,
|
|
37
|
+
authMethods
|
|
38
|
+
}) {
|
|
39
|
+
const connectionType = lookup.getConnectionType(type);
|
|
40
|
+
const strategy = getLookupStrategy(connectionType.lookupStrategy);
|
|
41
|
+
const identity = strategy.identityFromQuery(query);
|
|
42
|
+
this.logger.debug(
|
|
43
|
+
`Finding connection of type "${type}"${identity ? ` matching ${strategy.identityField} "${identity}"` : ""}`
|
|
44
|
+
);
|
|
45
|
+
let connection;
|
|
46
|
+
if (identity !== void 0) {
|
|
47
|
+
connection = this.connections.find(
|
|
48
|
+
(c) => c.type === type && connectionIdentityOf(strategy, c) === identity
|
|
49
|
+
);
|
|
50
|
+
} else {
|
|
51
|
+
connection = this.connections.find((c) => c.type === type);
|
|
52
|
+
}
|
|
53
|
+
if (!connection) {
|
|
54
|
+
return void 0;
|
|
55
|
+
}
|
|
56
|
+
if (!authMethods) {
|
|
57
|
+
const { auth: _, ...info } = connection;
|
|
58
|
+
return info;
|
|
59
|
+
}
|
|
60
|
+
if (connection.auth.length === 0) {
|
|
61
|
+
throw new errors.NotAllowedError(
|
|
62
|
+
`Connection of type "${type}"${identity ? ` for ${strategy.identityField} "${identity}"` : ""} has no auth method available to this plugin`
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
const matchAuth = connectionType.matchAuth;
|
|
66
|
+
const selected = matchAuth ? matchAuth(connection.auth, query) : connection.auth[0];
|
|
67
|
+
if (!selected) {
|
|
68
|
+
return void 0;
|
|
69
|
+
}
|
|
70
|
+
if (!authMethods.includes(selected.method)) {
|
|
71
|
+
throw new errors.NotAllowedError(
|
|
72
|
+
`Connection not found for type "${type}" with auth method "${selected.method}"`
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
this.logger.debug(
|
|
76
|
+
`Selected connection of type "${type}"${identity ? ` for ${strategy.identityField} "${identity}"` : ""} using auth method "${selected.method}"`
|
|
77
|
+
);
|
|
78
|
+
return {
|
|
79
|
+
...connection,
|
|
80
|
+
auth: selected
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
class DefaultConnectionsService {
|
|
85
|
+
logger;
|
|
86
|
+
connections;
|
|
87
|
+
config;
|
|
88
|
+
constructor(logger, config) {
|
|
89
|
+
this.logger = logger;
|
|
90
|
+
this.config = config;
|
|
91
|
+
this.connections = [];
|
|
92
|
+
this.#registerConnectionsFromConfig();
|
|
93
|
+
}
|
|
94
|
+
static create(options) {
|
|
95
|
+
return new DefaultConnectionsService(options.logger, options.config);
|
|
96
|
+
}
|
|
97
|
+
#registerConnectionsFromConfig() {
|
|
98
|
+
this.connections.push(
|
|
99
|
+
...config.buildConnectionsFromConfig({
|
|
100
|
+
config: this.config,
|
|
101
|
+
logger: this.logger
|
|
102
|
+
})
|
|
103
|
+
);
|
|
104
|
+
if (this.connections.length === 0) {
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
this.logger.info(
|
|
108
|
+
`Loaded ${this.connections.length} connection${this.connections.length === 1 ? "" : "s"} from configuration`
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
#getConnectionsForPlugin(pluginId) {
|
|
112
|
+
return this.connections.flatMap((connection) => {
|
|
113
|
+
if (connection.match && !connection.match.plugins.includes(pluginId)) {
|
|
114
|
+
return [];
|
|
115
|
+
}
|
|
116
|
+
const pluginMatched = connection.auth.filter(
|
|
117
|
+
(a) => a.match?.plugins.includes(pluginId)
|
|
118
|
+
);
|
|
119
|
+
const unmatched = connection.auth.filter((a) => !a.match);
|
|
120
|
+
return [{ ...connection, auth: [...pluginMatched, ...unmatched] }];
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
forPlugin(pluginId, options) {
|
|
124
|
+
const logger = options?.logger ?? this.logger;
|
|
125
|
+
return new PluginConnectionsService(
|
|
126
|
+
logger,
|
|
127
|
+
this.#getConnectionsForPlugin(pluginId)
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
exports.DefaultConnectionsService = DefaultConnectionsService;
|
|
133
|
+
//# sourceMappingURL=DefaultConnectionsService.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"DefaultConnectionsService.cjs.js","sources":["../../../../connections-node/src/DefaultConnectionsService.ts"],"sourcesContent":["/*\n * Copyright 2026 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 */\nimport {\n LoggerService,\n RootConfigService,\n} from '@backstage/backend-plugin-api';\nimport type {\n Connection,\n ConnectionLookupStrategy,\n ConnectionsService,\n ConnectionTypeDefinition,\n ConnectionType,\n LookupConnectionType,\n} from '@backstage/connections';\nimport type { ConfiguredConnection } from '@backstage/connections/config';\nimport { buildConnectionsFromConfig } from '@backstage/connections/config';\nimport { getConnectionType } from './lookup';\nimport { lookupStrategies } from './lookupStrategies';\nimport { NotAllowedError, NotFoundError } from '@backstage/errors';\n\ntype ConnectionQuery<TType extends ConnectionType> =\n LookupConnectionType<TType> extends ConnectionTypeDefinition<\n infer TDefinition\n >\n ? TDefinition['query']\n : never;\n\nfunction getLookupStrategy<K extends ConnectionLookupStrategy>(\n name: K,\n): (typeof lookupStrategies)[K] {\n return lookupStrategies[name];\n}\n\n// The identity field name is only known at runtime, so the typed connection\n// object cannot be indexed directly; this helper contains the erased read.\nfunction connectionIdentityOf(\n strategy: { identityField?: string },\n connection: object,\n): string | undefined {\n if (!strategy.identityField) {\n return undefined;\n }\n const value = (connection as Record<string, unknown>)[strategy.identityField];\n return typeof value === 'string' ? value : undefined;\n}\n\nclass PluginConnectionsService implements ConnectionsService {\n private readonly logger: LoggerService;\n private readonly connections: ConfiguredConnection[];\n\n constructor(logger: LoggerService, connections: ConfiguredConnection[]) {\n this.logger = logger;\n this.connections = connections;\n }\n\n async find<\n TType extends ConnectionType,\n TAuthMethod extends LookupConnectionType<TType>['authMethods'][number]['method'],\n >(options: {\n type: TType;\n query: ConnectionQuery<TType>;\n authMethods?: readonly [TAuthMethod, ...TAuthMethod[]];\n }): Promise<\n Connection<TType, TAuthMethod> | Omit<Connection<TType>, 'auth'>\n > {\n const result = await this.findOptional(options);\n if (!result) {\n throw new NotFoundError(\n `Connection not found for type \"${options.type}\"`,\n );\n }\n return result;\n }\n\n private async findOptional<\n TType extends ConnectionType,\n TAuthMethod extends LookupConnectionType<TType>['authMethods'][number]['method'],\n >({\n type,\n query,\n authMethods,\n }: {\n type: TType;\n query: ConnectionQuery<TType>;\n authMethods?: readonly [TAuthMethod, ...TAuthMethod[]];\n }): Promise<\n Connection<TType, TAuthMethod> | Omit<Connection<TType>, 'auth'> | undefined\n > {\n const connectionType = getConnectionType(type);\n const strategy = getLookupStrategy(connectionType.lookupStrategy);\n const identity = strategy.identityFromQuery(query);\n\n this.logger.debug(\n `Finding connection of type \"${type}\"${\n identity ? ` matching ${strategy.identityField} \"${identity}\"` : ''\n }`,\n );\n\n let connection: ConfiguredConnection | undefined;\n if (identity !== undefined) {\n connection = this.connections.find(\n c => c.type === type && connectionIdentityOf(strategy, c) === identity,\n );\n } else {\n connection = this.connections.find(c => c.type === type);\n }\n\n if (!connection) {\n return undefined;\n }\n\n if (!authMethods) {\n const { auth: _, ...info } = connection;\n return info as Omit<Connection<TType>, 'auth'>;\n }\n\n if (connection.auth.length === 0) {\n throw new NotAllowedError(\n `Connection of type \"${type}\"${\n identity ? ` for ${strategy.identityField} \"${identity}\"` : ''\n } has no auth method available to this plugin`,\n );\n }\n\n const matchAuth = (connectionType as any).matchAuth as\n | ((authMethods: any[], query: any) => any | undefined)\n | undefined;\n\n const selected = matchAuth\n ? matchAuth(connection.auth, query)\n : connection.auth[0];\n\n if (!selected) {\n return undefined;\n }\n\n if (!(authMethods as readonly string[]).includes(selected.method)) {\n throw new NotAllowedError(\n `Connection not found for type \"${type}\" with auth method \"${selected.method}\"`,\n );\n }\n\n this.logger.debug(\n `Selected connection of type \"${type}\"${\n identity ? ` for ${strategy.identityField} \"${identity}\"` : ''\n } using auth method \"${selected.method}\"`,\n );\n\n return {\n ...connection,\n auth: selected,\n } as Connection<TType, TAuthMethod>;\n }\n}\n\n/** @public */\nexport class DefaultConnectionsService {\n private readonly logger: LoggerService;\n private readonly connections: ConfiguredConnection[];\n private readonly config: RootConfigService;\n\n private constructor(logger: LoggerService, config: RootConfigService) {\n this.logger = logger;\n this.config = config;\n this.connections = [];\n this.#registerConnectionsFromConfig();\n }\n\n static create(options: {\n logger: LoggerService;\n config: RootConfigService;\n }): DefaultConnectionsService {\n return new DefaultConnectionsService(options.logger, options.config);\n }\n\n #registerConnectionsFromConfig(): void {\n this.connections.push(\n ...buildConnectionsFromConfig({\n config: this.config,\n logger: this.logger,\n }),\n );\n\n if (this.connections.length === 0) {\n return;\n }\n\n this.logger.info(\n `Loaded ${this.connections.length} connection${\n this.connections.length === 1 ? '' : 's'\n } from configuration`,\n );\n }\n\n #getConnectionsForPlugin(pluginId: string): ConfiguredConnection[] {\n // Filter connections and auth methods by plugin scope. Auth entries\n // explicitly matched to this plugin are ordered before unscoped entries\n // so that plugin-specific credentials take precedence.\n return this.connections.flatMap(connection => {\n if (connection.match && !connection.match.plugins.includes(pluginId)) {\n return [];\n }\n\n const pluginMatched = connection.auth.filter(a =>\n a.match?.plugins.includes(pluginId),\n );\n const unmatched = connection.auth.filter(a => !a.match);\n\n return [{ ...connection, auth: [...pluginMatched, ...unmatched] }];\n });\n }\n\n forPlugin(\n pluginId: string,\n options?: {\n logger: LoggerService;\n },\n ): ConnectionsService {\n const logger = options?.logger ?? this.logger;\n return new PluginConnectionsService(\n logger,\n this.#getConnectionsForPlugin(pluginId),\n );\n }\n}\n"],"names":["lookupStrategies","NotFoundError","getConnectionType","NotAllowedError","buildConnectionsFromConfig"],"mappings":";;;;;;;AAwCA,SAAS,kBACP,IAAA,EAC8B;AAC9B,EAAA,OAAOA,kCAAiB,IAAI,CAAA;AAC9B;AAIA,SAAS,oBAAA,CACP,UACA,UAAA,EACoB;AACpB,EAAA,IAAI,CAAC,SAAS,aAAA,EAAe;AAC3B,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,MAAM,KAAA,GAAS,UAAA,CAAuC,QAAA,CAAS,aAAa,CAAA;AAC5E,EAAA,OAAO,OAAO,KAAA,KAAU,QAAA,GAAW,KAAA,GAAQ,MAAA;AAC7C;AAEA,MAAM,wBAAA,CAAuD;AAAA,EAC1C,MAAA;AAAA,EACA,WAAA;AAAA,EAEjB,WAAA,CAAY,QAAuB,WAAA,EAAqC;AACtE,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,WAAA,GAAc,WAAA;AAAA,EACrB;AAAA,EAEA,MAAM,KAGJ,OAAA,EAMA;AACA,IAAA,MAAM,MAAA,GAAS,MAAM,IAAA,CAAK,YAAA,CAAa,OAAO,CAAA;AAC9C,IAAA,IAAI,CAAC,MAAA,EAAQ;AACX,MAAA,MAAM,IAAIC,oBAAA;AAAA,QACR,CAAA,+BAAA,EAAkC,QAAQ,IAAI,CAAA,CAAA;AAAA,OAChD;AAAA,IACF;AACA,IAAA,OAAO,MAAA;AAAA,EACT;AAAA,EAEA,MAAc,YAAA,CAGZ;AAAA,IACA,IAAA;AAAA,IACA,KAAA;AAAA,IACA;AAAA,GACF,EAME;AACA,IAAA,MAAM,cAAA,GAAiBC,yBAAkB,IAAI,CAAA;AAC7C,IAAA,MAAM,QAAA,GAAW,iBAAA,CAAkB,cAAA,CAAe,cAAc,CAAA;AAChE,IAAA,MAAM,QAAA,GAAW,QAAA,CAAS,iBAAA,CA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 -0,0 +1,11 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var connections = require('@backstage/connections');
|
|
4
|
+
|
|
5
|
+
const connectionTypesMap = new Map(Object.entries(connections.connectionTypes));
|
|
6
|
+
function getConnectionType(key) {
|
|
7
|
+
return connectionTypesMap.get(key);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
exports.getConnectionType = getConnectionType;
|
|
11
|
+
//# sourceMappingURL=lookup.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lookup.cjs.js","sources":["../../../../connections-node/src/lookup.ts"],"sourcesContent":["/*\n * Copyright 2026 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 */\nimport {\n LookupConnectionType,\n ConnectionType,\n connectionTypes,\n} from '@backstage/connections';\n\nconst connectionTypesMap = new Map(Object.entries(connectionTypes));\n\nexport function getConnectionType<T extends ConnectionType>(\n key: T,\n): LookupConnectionType<T> {\n return connectionTypesMap.get(key) as LookupConnectionType<T>;\n}\n\nexport function isConnectionType(\n value: string | undefined,\n): value is ConnectionType {\n if (!value) return false;\n\n return connectionTypesMap.has(value);\n}\n"],"names":["connectionTypes"],"mappings":";;;;AAqBA,MAAM,qBAAqB,IAAI,GAAA,CAAI,MAAA,CAAO,OAAA,CAAQA,2BAAe,CAAC,CAAA;AAE3D,SAAS,kBACd,GAAA,EACyB;AACzB,EAAA,OAAO,kBAAA,CAAmB,IAAI,GAAG,CAAA;AACnC;;"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var errors = require('@backstage/errors');
|
|
4
|
+
|
|
5
|
+
const lookupStrategies = {
|
|
6
|
+
host: {
|
|
7
|
+
identityField: "host",
|
|
8
|
+
identityFromQuery(query) {
|
|
9
|
+
const { url } = query;
|
|
10
|
+
try {
|
|
11
|
+
return new URL(url).host;
|
|
12
|
+
} catch {
|
|
13
|
+
throw new errors.InputError(
|
|
14
|
+
`Invalid url "${url}" passed to ConnectionsService.find`
|
|
15
|
+
);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
// AWS has no identity field to match against — all accounts live under a
|
|
20
|
+
// single connection. Account selection is handled entirely by the
|
|
21
|
+
// connection type's matchAuth implementation.
|
|
22
|
+
aws: {
|
|
23
|
+
identityFromQuery() {
|
|
24
|
+
return void 0;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
exports.lookupStrategies = lookupStrategies;
|
|
30
|
+
//# sourceMappingURL=lookupStrategies.cjs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"lookupStrategies.cjs.js","sources":["../../../../connections-node/src/lookupStrategies.ts"],"sourcesContent":["/*\n * Copyright 2026 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 */\nimport { InputError } from '@backstage/errors';\nimport type { ConnectionLookupStrategy } from '@backstage/connections';\n\n// The concrete strategy is only known at runtime, so definitions receive the\n// query with its type erased and narrow it to their own query shape.\ntype ConnectionLookupStrategyDefinition = {\n identityField?: string;\n identityFromQuery(query: unknown): string | undefined;\n};\n\n/**\n * The definitions of all lookup strategies, keyed by the `lookupStrategy` of\n * each connection type. Each definition knows how to derive the identity to\n * match connections against from the query passed to `ConnectionsService.find`.\n *\n * The `identityField` of each strategy is mirrored by the `identityFields` map\n * in the config pipeline of the `@backstage/connections` package; keep the two\n * in sync when adding or changing strategies.\n *\n * @internal\n */\nexport const lookupStrategies: Record<\n ConnectionLookupStrategy,\n ConnectionLookupStrategyDefinition\n> = {\n host: {\n identityField: 'host',\n identityFromQuery(query) {\n const { url } = query as { url: string };\n try {\n return new URL(url).host;\n } catch {\n throw new InputError(\n `Invalid url \"${url}\" passed to ConnectionsService.find`,\n );\n }\n },\n },\n // AWS has no identity field to match against — all accounts live under a\n // single connection. Account selection is handled entirely by the\n // connection type's matchAuth implementation.\n aws: {\n identityFromQuery() {\n return undefined;\n },\n },\n};\n"],"names":["InputError"],"mappings":";;;;AAoCO,MAAM,gBAAA,GAGT;AAAA,EACF,IAAA,EAAM;AAAA,IACJ,aAAA,EAAe,MAAA;AAAA,IACf,kBAAkB,KAAA,EAAO;AACvB,MAAA,MAAM,EAAE,KAAI,GAAI,KAAA;AAChB,MAAA,IAAI;AACF,QAAA,OAAO,IAAI,GAAA,CAAI,GAAG,CAAA,CAAE,IAAA;AAAA,MACtB,CAAA,CAAA,MAAQ;AACN,QAAA,MAAM,IAAIA,iBAAA;AAAA,UACR,gBAAgB,GAAG,CAAA,mCAAA;AAAA,SACrB;AAAA,MACF;AAAA,IACF;AAAA,GACF;AAAA;AAAA;AAAA;AAAA,EAIA,GAAA,EAAK;AAAA,IACH,iBAAA,GAAoB;AAClB,MAAA,OAAO,MAAA;AAAA,IACT;AAAA;AAEJ;;"}
|
|
@@ -116,7 +116,7 @@ class DatabaseManagerImpl {
|
|
|
116
116
|
}
|
|
117
117
|
const clientPromise = connector.getClient(pluginId, deps);
|
|
118
118
|
this.databaseCache.set(pluginId, clientPromise);
|
|
119
|
-
if (process.env.NODE_ENV !== "test") {
|
|
119
|
+
if (this.config.getOptionalBoolean("keepalive") && process.env.NODE_ENV !== "test") {
|
|
120
120
|
clientPromise.then(
|
|
121
121
|
(client) => this.startKeepaliveLoop(pluginId, client, deps.logger)
|
|
122
122
|
);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DatabaseManager.cjs.js","sources":["../../../src/entrypoints/database/DatabaseManager.ts"],"sourcesContent":["/*\n * Copyright 2021 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 DatabaseService,\n LifecycleService,\n LoggerService,\n RootConfigService,\n RootLifecycleService,\n RootLoggerService,\n} from '@backstage/backend-plugin-api';\nimport { Config } from '@backstage/config';\nimport { stringifyError } from '@backstage/errors';\nimport { Knex } from 'knex';\nimport { MysqlConnector } from './connectors/mysql';\nimport { PgConnector } from './connectors/postgres';\nimport { Sqlite3Connector } from './connectors/sqlite3';\nimport { Connector } from './types';\n\n/**\n * Provides a config lookup path for a plugin's config block.\n */\nfunction pluginPath(pluginId: string): string {\n return `plugin.${pluginId}`;\n}\n\n/**\n * Creation options for {@link DatabaseManager}.\n *\n * @public\n */\nexport type DatabaseManagerOptions = {\n migrations?: DatabaseService['migrations'];\n rootLogger?: RootLoggerService;\n rootLifecycle?: RootLifecycleService;\n};\n\n/**\n * Testable implementation class for {@link DatabaseManager} below.\n */\nexport class DatabaseManagerImpl {\n private readonly config: Config;\n private readonly connectors: Record<string, Connector>;\n private readonly options?: DatabaseManagerOptions;\n private readonly databaseCache: Map<string, Promise<Knex>>;\n private readonly keepaliveIntervals: Map<string, NodeJS.Timeout>;\n\n constructor(\n config: Config,\n connectors: Record<string, Connector>,\n options?: DatabaseManagerOptions,\n databaseCache: Map<string, Promise<Knex>> = new Map(),\n keepaliveIntervals: Map<string, NodeJS.Timeout> = new Map(),\n ) {\n this.config = config;\n this.connectors = connectors;\n this.options = options;\n this.databaseCache = databaseCache;\n this.keepaliveIntervals = keepaliveIntervals;\n // If a rootLifecycle service was provided, register a shutdown hook to\n // clean up any database connections.\n if (options?.rootLifecycle !== undefined) {\n options.rootLifecycle.addShutdownHook(async () => {\n await this.shutdown({ logger: options.rootLogger });\n });\n }\n }\n\n /**\n * Generates a DatabaseService for consumption by plugins.\n *\n * @param pluginId - The plugin that the database manager should be created for. Plugin names\n * should be unique as they are used to look up database config overrides under\n * `backend.database.plugin`.\n */\n forPlugin(\n pluginId: string,\n deps: {\n logger: LoggerService;\n lifecycle: LifecycleService;\n },\n ): DatabaseService {\n const client = this.getClientType(pluginId).client;\n const connector = this.connectors[client];\n if (!connector) {\n throw new Error(\n `Unsupported database client type '${client}' specified for plugin '${pluginId}'`,\n );\n }\n const getClient = () => this.getDatabase(pluginId, connector, deps);\n\n const skip =\n this.options?.migrations?.skip ??\n this.config.getOptionalBoolean(`plugin.${pluginId}.skipMigrations`) ??\n this.config.getOptionalBoolean('skipMigrations') ??\n false;\n\n return { getClient, migrations: { skip } };\n }\n\n /**\n * Destroys all known connections.\n */\n private async shutdown(deps?: { logger?: LoggerService }): Promise<void> {\n const pluginIds = Array.from(this.databaseCache.keys());\n await Promise.allSettled(\n pluginIds.map(async pluginId => {\n // We no longer need to keep connections alive.\n clearInterval(this.keepaliveIntervals.get(pluginId));\n\n const connection = await this.databaseCache.get(pluginId);\n if (connection) {\n if (connection.client.config.includes('sqlite3')) {\n return; // sqlite3 does not support destroy, it hangs\n }\n await connection.destroy().catch((error: unknown) => {\n deps?.logger?.error(\n `Problem closing database connection for ${pluginId}: ${stringifyError(\n error,\n )}`,\n );\n });\n }\n }),\n );\n\n const connectors = new Set(Object.values(this.connectors));\n await Promise.all(\n Array.from(connectors, async connector => {\n try {\n await connector.shutdown?.();\n } catch (error) {\n deps?.logger?.error(\n `Problem closing database connector: ${stringifyError(error)}`,\n );\n }\n }),\n );\n }\n\n /**\n * Provides the client type which should be used for a given plugin.\n *\n * The client type is determined by plugin specific config if present.\n * Otherwise the base client is used as the fallback.\n *\n * @param pluginId - Plugin to get the client type for\n * @returns Object with client type returned as `client` and boolean\n * representing whether or not the client was overridden as\n * `overridden`\n */\n private getClientType(pluginId: string): {\n client: string;\n overridden: boolean;\n } {\n const pluginClient = this.config.getOptionalString(\n `${pluginPath(pluginId)}.client`,\n );\n\n const baseClient = this.config.getString('client');\n const client = pluginClient ?? baseClient;\n return {\n client,\n overridden: client !== baseClient,\n };\n }\n\n /**\n * Provides a scoped Knex client for a plugin as per application config.\n *\n * @param pluginId - Plugin to get a Knex client for\n * @returns Promise which resolves to a scoped Knex database client for a\n * plugin\n */\n private async getDatabase(\n pluginId: string,\n connector: Connector,\n deps: {\n logger: LoggerService;\n lifecycle: LifecycleService;\n },\n ): Promise<Knex> {\n if (this.databaseCache.has(pluginId)) {\n return this.databaseCache.get(pluginId)!;\n }\n\n const clientPromise = connector.getClient(pluginId, deps);\n this.databaseCache.set(pluginId, clientPromise);\n\n if (process.env.NODE_ENV !== 'test') {\n clientPromise.then(client =>\n this.startKeepaliveLoop(pluginId, client, deps.logger),\n );\n }\n\n return clientPromise;\n }\n\n private startKeepaliveLoop(\n pluginId: string,\n client: Knex,\n logger: LoggerService,\n ): void {\n let lastKeepaliveFailed = false;\n\n this.keepaliveIntervals.set(\n pluginId,\n setInterval(() => {\n // During testing it can happen that the environment is torn down and\n // this client is `undefined`, but this interval is still run.\n client?.raw('select 1').then(\n () => {\n lastKeepaliveFailed = false;\n },\n (error: unknown) => {\n if (!lastKeepaliveFailed) {\n lastKeepaliveFailed = true;\n logger.warn(\n `Database keepalive failed for plugin ${pluginId}, ${stringifyError(\n error,\n )}`,\n );\n }\n },\n );\n }, 60 * 1000),\n );\n }\n}\n\n// NOTE: This class looks odd but is kept around for API compatibility reasons\n/**\n * Manages database connections for Backstage backend plugins.\n *\n * @public\n * @remarks\n *\n * The database manager allows the user to set connection and client settings on\n * a per pluginId basis by defining a database config block under\n * `plugin.<pluginId>` in addition to top level defaults. Optionally, a user may\n * set `prefix` which is used to prefix generated database names if config is\n * not provided.\n */\nexport class DatabaseManager {\n /**\n * Creates a {@link DatabaseManager} from `backend.database` config.\n *\n * @param config - The loaded application configuration.\n * @param options - An optional configuration object.\n */\n static fromConfig(\n config: RootConfigService,\n options?: DatabaseManagerOptions,\n ): DatabaseManager {\n const databaseConfig = config.getConfig('backend.database');\n const prefix =\n databaseConfig.getOptionalString('prefix') || 'backstage_plugin_';\n const schemaPrefix = databaseConfig.getOptionalString('schemaPrefix') || '';\n\n // Validate schemaPrefix contains only safe PostgreSQL identifier characters\n if (schemaPrefix && !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(schemaPrefix)) {\n throw new Error(\n `Invalid schemaPrefix \"${schemaPrefix}\". ` +\n `Schema prefix must start with a letter or underscore and contain only letters, numbers, and underscores.`,\n );\n }\n\n return new DatabaseManager(\n new DatabaseManagerImpl(\n databaseConfig,\n {\n pg: new PgConnector(databaseConfig, prefix, schemaPrefix),\n sqlite3: new Sqlite3Connector(databaseConfig),\n 'better-sqlite3': new Sqlite3Connector(databaseConfig),\n mysql: new MysqlConnector(databaseConfig, prefix),\n mysql2: new MysqlConnector(databaseConfig, prefix),\n },\n options,\n ),\n );\n }\n\n private readonly impl: DatabaseManagerImpl;\n\n private constructor(impl: DatabaseManagerImpl) {\n this.impl = impl;\n }\n\n /**\n * Generates a DatabaseService for consumption by plugins.\n *\n * @param pluginId - The plugin that the database manager should be created for. Plugin names\n * should be unique as they are used to look up database config overrides under\n * `backend.database.plugin`.\n */\n forPlugin(\n pluginId: string,\n deps: {\n logger: LoggerService;\n lifecycle: LifecycleService;\n },\n ): DatabaseService {\n return this.impl.forPlugin(pluginId, deps);\n }\n}\n"],"names":["stringifyError","PgConnector","Sqlite3Connector","MysqlConnector"],"mappings":";;;;;;;AAmCA,SA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BAAA,CAA2B,IAAA,CAAK,YAAY,CAAA,EAAG;AAClE,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,yBAAyB,YAAY,CAAA,2GAAA;AAAA,OAEvC;AAAA,IACF;AAEA,IAAA,OAAO,IAAI,eAAA;AAAA,MACT,IAAI,mBAAA;AAAA,QACF,cAAA;AAAA,QACA;AAAA,UACE,EAAA,EAAI,IAAIC,oBAAA,CAAY,cAAA,EAAgB,QAAQ,YAAY,CAAA;AAAA,UACxD,OAAA,EAAS,IAAIC,wBAAA,CAAiB,cAAc,CAAA;AAAA,UAC5C,gBAAA,EAAkB,IAAIA,wBAAA,CAAiB,cAAc,CAAA;AAAA,UACrD,KAAA,EAAO,IAAIC,oBAAA,CAAe,cAAA,EAAgB,MAAM,CAAA;AAAA,UAChD,MAAA,EAAQ,IAAIA,oBAAA,CAAe,cAAA,EAAgB,MAAM;AAAA,SACnD;AAAA,QACA;AAAA;AACF,KACF;AAAA,EACF;AAAA,EAEiB,IAAA;AAAA,EAET,YAAY,IAAA,EAA2B;AAC7C,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,SAAA,CACE,UACA,IAAA,EAIiB;AACjB,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,SAAA,CAAU,QAAA,EAAU,IAAI,CAAA;AAAA,EAC3C;AACF;;;"}
|
|
1
|
+
{"version":3,"file":"DatabaseManager.cjs.js","sources":["../../../src/entrypoints/database/DatabaseManager.ts"],"sourcesContent":["/*\n * Copyright 2021 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 DatabaseService,\n LifecycleService,\n LoggerService,\n RootConfigService,\n RootLifecycleService,\n RootLoggerService,\n} from '@backstage/backend-plugin-api';\nimport { Config } from '@backstage/config';\nimport { stringifyError } from '@backstage/errors';\nimport { Knex } from 'knex';\nimport { MysqlConnector } from './connectors/mysql';\nimport { PgConnector } from './connectors/postgres';\nimport { Sqlite3Connector } from './connectors/sqlite3';\nimport { Connector } from './types';\n\n/**\n * Provides a config lookup path for a plugin's config block.\n */\nfunction pluginPath(pluginId: string): string {\n return `plugin.${pluginId}`;\n}\n\n/**\n * Creation options for {@link DatabaseManager}.\n *\n * @public\n */\nexport type DatabaseManagerOptions = {\n migrations?: DatabaseService['migrations'];\n rootLogger?: RootLoggerService;\n rootLifecycle?: RootLifecycleService;\n};\n\n/**\n * Testable implementation class for {@link DatabaseManager} below.\n */\nexport class DatabaseManagerImpl {\n private readonly config: Config;\n private readonly connectors: Record<string, Connector>;\n private readonly options?: DatabaseManagerOptions;\n private readonly databaseCache: Map<string, Promise<Knex>>;\n private readonly keepaliveIntervals: Map<string, NodeJS.Timeout>;\n\n constructor(\n config: Config,\n connectors: Record<string, Connector>,\n options?: DatabaseManagerOptions,\n databaseCache: Map<string, Promise<Knex>> = new Map(),\n keepaliveIntervals: Map<string, NodeJS.Timeout> = new Map(),\n ) {\n this.config = config;\n this.connectors = connectors;\n this.options = options;\n this.databaseCache = databaseCache;\n this.keepaliveIntervals = keepaliveIntervals;\n // If a rootLifecycle service was provided, register a shutdown hook to\n // clean up any database connections.\n if (options?.rootLifecycle !== undefined) {\n options.rootLifecycle.addShutdownHook(async () => {\n await this.shutdown({ logger: options.rootLogger });\n });\n }\n }\n\n /**\n * Generates a DatabaseService for consumption by plugins.\n *\n * @param pluginId - The plugin that the database manager should be created for. Plugin names\n * should be unique as they are used to look up database config overrides under\n * `backend.database.plugin`.\n */\n forPlugin(\n pluginId: string,\n deps: {\n logger: LoggerService;\n lifecycle: LifecycleService;\n },\n ): DatabaseService {\n const client = this.getClientType(pluginId).client;\n const connector = this.connectors[client];\n if (!connector) {\n throw new Error(\n `Unsupported database client type '${client}' specified for plugin '${pluginId}'`,\n );\n }\n const getClient = () => this.getDatabase(pluginId, connector, deps);\n\n const skip =\n this.options?.migrations?.skip ??\n this.config.getOptionalBoolean(`plugin.${pluginId}.skipMigrations`) ??\n this.config.getOptionalBoolean('skipMigrations') ??\n false;\n\n return { getClient, migrations: { skip } };\n }\n\n /**\n * Destroys all known connections.\n */\n private async shutdown(deps?: { logger?: LoggerService }): Promise<void> {\n const pluginIds = Array.from(this.databaseCache.keys());\n await Promise.allSettled(\n pluginIds.map(async pluginId => {\n clearInterval(this.keepaliveIntervals.get(pluginId));\n const connection = await this.databaseCache.get(pluginId);\n if (connection) {\n if (connection.client.config.includes('sqlite3')) {\n return; // sqlite3 does not support destroy, it hangs\n }\n await connection.destroy().catch((error: unknown) => {\n deps?.logger?.error(\n `Problem closing database connection for ${pluginId}: ${stringifyError(\n error,\n )}`,\n );\n });\n }\n }),\n );\n\n const connectors = new Set(Object.values(this.connectors));\n await Promise.all(\n Array.from(connectors, async connector => {\n try {\n await connector.shutdown?.();\n } catch (error) {\n deps?.logger?.error(\n `Problem closing database connector: ${stringifyError(error)}`,\n );\n }\n }),\n );\n }\n\n /**\n * Provides the client type which should be used for a given plugin.\n *\n * The client type is determined by plugin specific config if present.\n * Otherwise the base client is used as the fallback.\n *\n * @param pluginId - Plugin to get the client type for\n * @returns Object with client type returned as `client` and boolean\n * representing whether or not the client was overridden as\n * `overridden`\n */\n private getClientType(pluginId: string): {\n client: string;\n overridden: boolean;\n } {\n const pluginClient = this.config.getOptionalString(\n `${pluginPath(pluginId)}.client`,\n );\n\n const baseClient = this.config.getString('client');\n const client = pluginClient ?? baseClient;\n return {\n client,\n overridden: client !== baseClient,\n };\n }\n\n /**\n * Provides a scoped Knex client for a plugin as per application config.\n *\n * @param pluginId - Plugin to get a Knex client for\n * @returns Promise which resolves to a scoped Knex database client for a\n * plugin\n */\n private async getDatabase(\n pluginId: string,\n connector: Connector,\n deps: {\n logger: LoggerService;\n lifecycle: LifecycleService;\n },\n ): Promise<Knex> {\n if (this.databaseCache.has(pluginId)) {\n return this.databaseCache.get(pluginId)!;\n }\n\n const clientPromise = connector.getClient(pluginId, deps);\n this.databaseCache.set(pluginId, clientPromise);\n\n if (\n this.config.getOptionalBoolean('keepalive') &&\n process.env.NODE_ENV !== 'test'\n ) {\n clientPromise.then(client =>\n this.startKeepaliveLoop(pluginId, client, deps.logger),\n );\n }\n\n return clientPromise;\n }\n\n private startKeepaliveLoop(\n pluginId: string,\n client: Knex,\n logger: LoggerService,\n ): void {\n let lastKeepaliveFailed = false;\n\n this.keepaliveIntervals.set(\n pluginId,\n setInterval(() => {\n client?.raw('select 1').then(\n () => {\n lastKeepaliveFailed = false;\n },\n (error: unknown) => {\n if (!lastKeepaliveFailed) {\n lastKeepaliveFailed = true;\n logger.warn(\n `Database keepalive failed for plugin ${pluginId}, ${stringifyError(\n error,\n )}`,\n );\n }\n },\n );\n }, 60 * 1000),\n );\n }\n}\n\n// NOTE: This class looks odd but is kept around for API compatibility reasons\n/**\n * Manages database connections for Backstage backend plugins.\n *\n * @public\n * @remarks\n *\n * The database manager allows the user to set connection and client settings on\n * a per pluginId basis by defining a database config block under\n * `plugin.<pluginId>` in addition to top level defaults. Optionally, a user may\n * set `prefix` which is used to prefix generated database names if config is\n * not provided.\n */\nexport class DatabaseManager {\n /**\n * Creates a {@link DatabaseManager} from `backend.database` config.\n *\n * @param config - The loaded application configuration.\n * @param options - An optional configuration object.\n */\n static fromConfig(\n config: RootConfigService,\n options?: DatabaseManagerOptions,\n ): DatabaseManager {\n const databaseConfig = config.getConfig('backend.database');\n const prefix =\n databaseConfig.getOptionalString('prefix') || 'backstage_plugin_';\n const schemaPrefix = databaseConfig.getOptionalString('schemaPrefix') || '';\n\n // Validate schemaPrefix contains only safe PostgreSQL identifier characters\n if (schemaPrefix && !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(schemaPrefix)) {\n throw new Error(\n `Invalid schemaPrefix \"${schemaPrefix}\". ` +\n `Schema prefix must start with a letter or underscore and contain only letters, numbers, and underscores.`,\n );\n }\n\n return new DatabaseManager(\n new DatabaseManagerImpl(\n databaseConfig,\n {\n pg: new PgConnector(databaseConfig, prefix, schemaPrefix),\n sqlite3: new Sqlite3Connector(databaseConfig),\n 'better-sqlite3': new Sqlite3Connector(databaseConfig),\n mysql: new MysqlConnector(databaseConfig, prefix),\n mysql2: new MysqlConnector(databaseConfig, prefix),\n },\n options,\n ),\n );\n }\n\n private readonly impl: DatabaseManagerImpl;\n\n private constructor(impl: DatabaseManagerImpl) {\n this.impl = impl;\n }\n\n /**\n * Generates a DatabaseService for consumption by plugins.\n *\n * @param pluginId - The plugin that the database manager should be created for. Plugin names\n * should be unique as they are used to look up database config overrides under\n * `backend.database.plugin`.\n */\n forPlugin(\n pluginId: string,\n deps: {\n logger: LoggerService;\n lifecycle: LifecycleService;\n },\n ): DatabaseService {\n return this.impl.forPlugin(pluginId, deps);\n }\n}\n"],"names":["stringifyError","PgConnector","Sqlite3Connector","MysqlConnector"],"mappings":";;;;;;;AAmCA,SAAS,WAAW,QAAA,EAA0B;AAC5C,EAAA,OAAO,UAAU,QAAQ,CAAA,CAAA;AAC3B;AAgBO,MAAM,mBAAA,CAAoB;AAAA,EACd,MAAA;AAAA,EACA,UAAA;AAAA,EACA,OAAA;AAAA,EACA,aAAA;AAAA,EACA,kBAAA;AAAA,EAEjB,WAAA,CACE,MAAA,EACA,UAAA,EACA,OAAA,EACA,aAAA,mBAA4C,IAAI,GAAA,EAAI,EACpD,kBAAA,mBAAkD,IAAI,GAAA,EAAI,EAC1D;AACA,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,UAAA,GAAa,UAAA;AAClB,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AACf,IAAA,IAAA,CAAK,aAAA,GAAgB,aAA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Ae,cAAA,EAAgB,MAAM,CAAA;AAAA,UAChD,MAAA,EAAQ,IAAIA,oBAAA,CAAe,cAAA,EAAgB,MAAM;AAAA,SACnD;AAAA,QACA;AAAA;AACF,KACF;AAAA,EACF;AAAA,EAEiB,IAAA;AAAA,EAET,YAAY,IAAA,EAA2B;AAC7C,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,SAAA,CACE,UACA,IAAA,EAIiB;AACjB,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,SAAA,CAAU,QAAA,EAAU,IAAI,CAAA;AAAA,EAC3C;AACF;;;"}
|
|
@@ -23,6 +23,7 @@ function createMysqlDatabaseClient(dbConfig, overrides) {
|
|
|
23
23
|
}
|
|
24
24
|
function buildMysqlDatabaseConfig(dbConfig, overrides) {
|
|
25
25
|
return mergeDatabaseConfig.mergeDatabaseConfig(
|
|
26
|
+
{ pool: { min: 0 } },
|
|
26
27
|
dbConfig.get(),
|
|
27
28
|
{
|
|
28
29
|
connection: getMysqlConnectionConfig(dbConfig, !!overrides),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mysql.cjs.js","sources":["../../../../src/entrypoints/database/connectors/mysql.ts"],"sourcesContent":["/*\n * Copyright 2020 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 { LifecycleService, LoggerService } from '@backstage/backend-plugin-api';\nimport { Config, ConfigReader } from '@backstage/config';\nimport { InputError } from '@backstage/errors';\nimport { JsonObject } from '@backstage/types';\nimport knexFactory, { Knex } from 'knex';\nimport { merge, omit } from 'lodash';\nimport limiterFactory from 'p-limit';\nimport yn from 'yn';\nimport { Connector } from '../types';\nimport defaultNameOverride from './defaultNameOverride';\nimport { mergeDatabaseConfig } from './mergeDatabaseConfig';\n\n// Limits the number of concurrent DDL operations to 1\nconst ddlLimiter = limiterFactory(1);\n\n/**\n * Creates a knex mysql database connection\n *\n * @param dbConfig - The database config\n * @param overrides - Additional options to merge with the config\n */\nexport function createMysqlDatabaseClient(\n dbConfig: Config,\n overrides?: Knex.Config,\n) {\n const knexConfig = buildMysqlDatabaseConfig(dbConfig, overrides);\n const database = knexFactory(knexConfig);\n return database;\n}\n\n/**\n * Builds a knex mysql database connection\n *\n * @param dbConfig - The database config\n * @param overrides - Additional options to merge with the config\n */\nexport function buildMysqlDatabaseConfig(\n dbConfig: Config,\n overrides?: Knex.Config,\n) {\n return mergeDatabaseConfig(\n dbConfig.get(),\n {\n connection: getMysqlConnectionConfig(dbConfig, !!overrides),\n useNullAsDefault: true,\n },\n overrides,\n );\n}\n\n/**\n * Gets the mysql connection config\n *\n * @param dbConfig - The database config\n * @param parseConnectionString - Flag to explicitly control connection string parsing\n */\nexport function getMysqlConnectionConfig(\n dbConfig: Config,\n parseConnectionString?: boolean,\n): Knex.MySqlConnectionConfig | string {\n const connection = dbConfig.get('connection') as any;\n const isConnectionString =\n typeof connection === 'string' || connection instanceof String;\n const autoParse = typeof parseConnectionString !== 'boolean';\n\n const shouldParseConnectionString = autoParse\n ? isConnectionString\n : parseConnectionString && isConnectionString;\n\n return shouldParseConnectionString\n ? parseMysqlConnectionString(connection as string)\n : connection;\n}\n\n/**\n * Parses a mysql connection string.\n *\n * e.g. mysql://examplename:somepassword@examplehost:3306/dbname\n * @param connectionString - The mysql connection string\n */\nexport function parseMysqlConnectionString(\n connectionString: string,\n): Knex.MySqlConnectionConfig {\n try {\n const {\n protocol,\n username,\n password,\n port,\n hostname,\n pathname,\n searchParams,\n } = new URL(connectionString);\n\n if (protocol !== 'mysql:') {\n throw new Error(`Unknown protocol ${protocol}`);\n } else if (!username || !password) {\n throw new Error(`Missing username/password`);\n } else if (!pathname.match(/^\\/[^/]+$/)) {\n throw new Error(`Expected single path segment`);\n }\n\n const result: Knex.MySqlConnectionConfig = {\n user: username,\n password,\n host: hostname,\n port: Number(port || 3306),\n database: decodeURIComponent(pathname.substring(1)),\n };\n\n const ssl = searchParams.get('ssl');\n if (ssl) {\n result.ssl = ssl;\n }\n\n const debug = searchParams.get('debug');\n if (debug) {\n result.debug = yn(debug);\n }\n\n return result;\n } catch (e) {\n throw new InputError(\n `Error while parsing MySQL connection string, ${e}`,\n e,\n );\n }\n}\n\n/**\n * Creates the missing mysql database if it does not exist\n *\n * @param dbConfig - The database config\n * @param databases - The names of the databases to create\n */\nexport async function ensureMysqlDatabaseExists(\n dbConfig: Config,\n ...databases: Array<string>\n) {\n const admin = createMysqlDatabaseClient(dbConfig, {\n connection: {\n database: null as unknown as string,\n },\n pool: {\n min: 0,\n acquireTimeoutMillis: 10000,\n },\n });\n\n try {\n const ensureDatabase = async (database: string) => {\n await admin.raw(`CREATE DATABASE IF NOT EXISTS ??`, [database]);\n };\n await Promise.all(\n databases.map(async database => {\n // For initial setup we use a smaller timeout but several retries. Given that this\n // is a separate connection pool we should never really run into issues with connection\n // acquisition timeouts, but we do anyway. This might be a bug in knex or some other dependency.\n let lastErr: Error | undefined = undefined;\n for (let i = 0; i < 3; i++) {\n try {\n return await ddlLimiter(() => ensureDatabase(database));\n } catch (err) {\n lastErr = err;\n }\n await new Promise(resolve => setTimeout(resolve, 100));\n }\n throw lastErr;\n }),\n );\n } finally {\n await admin.destroy();\n }\n}\n\n/**\n * Drops the given mysql databases.\n *\n * @param dbConfig - The database config\n * @param databases - The names of the databases to create\n */\nexport async function dropMysqlDatabase(\n dbConfig: Config,\n ...databases: Array<string>\n) {\n const admin = createMysqlDatabaseClient(dbConfig, {\n connection: {\n database: null as unknown as string,\n },\n pool: {\n min: 0,\n acquireTimeoutMillis: 10000,\n },\n });\n\n try {\n const dropDatabase = async (database: string) => {\n await admin.raw(`DROP DATABASE ??`, [database]);\n };\n await Promise.all(\n databases.map(async database => {\n return await ddlLimiter(() => dropDatabase(database));\n }),\n );\n } finally {\n await admin.destroy();\n }\n}\n\n/**\n * Provides a config lookup path for a plugin's config block.\n */\nfunction pluginPath(pluginId: string): string {\n return `plugin.${pluginId}`;\n}\n\nfunction normalizeConnection(\n connection: Knex.StaticConnectionConfig | JsonObject | string | undefined,\n): Partial<Knex.StaticConnectionConfig> {\n if (typeof connection === 'undefined' || connection === null) {\n return {};\n }\n\n return typeof connection === 'string' || connection instanceof String\n ? parseMysqlConnectionString(connection as string)\n : connection;\n}\n\nexport class MysqlConnector implements Connector {\n private readonly config: Config;\n private readonly prefix: string;\n\n constructor(config: Config, prefix: string) {\n this.config = config;\n this.prefix = prefix;\n }\n\n async getClient(\n pluginId: string,\n _deps: {\n logger: LoggerService;\n lifecycle: LifecycleService;\n },\n ): Promise<Knex> {\n const pluginConfig = new ConfigReader(\n this.getConfigForPlugin(pluginId) as JsonObject,\n );\n\n const databaseName = this.getDatabaseName(pluginId);\n if (databaseName && this.getEnsureExistsConfig(pluginId)) {\n try {\n await ensureMysqlDatabaseExists(pluginConfig, databaseName);\n } catch (error) {\n throw new Error(\n `Failed to connect to the database to make sure that '${databaseName}' exists, ${error}`,\n );\n }\n }\n\n const pluginDivisionMode = this.getPluginDivisionModeConfig();\n if (pluginDivisionMode !== 'database') {\n throw new Error(\n `The MySQL driver does not support plugin division mode '${pluginDivisionMode}'`,\n );\n }\n\n const databaseClientOverrides = mergeDatabaseConfig(\n {},\n this.getDatabaseOverrides(pluginId),\n );\n\n const client = createMysqlDatabaseClient(\n pluginConfig,\n databaseClientOverrides,\n );\n\n return client;\n }\n\n /**\n * Provides the canonical database name for a given plugin.\n *\n * This method provides the effective database name which is determined using\n * global and plugin specific database config. If no explicit database name,\n * this method will provide a generated name which is the pluginId prefixed\n * with 'backstage_plugin_'.\n *\n * @param pluginId - Lookup the database name for given plugin\n * @returns String representing the plugin's database name\n */\n private getDatabaseName(pluginId: string): string | undefined {\n const connection = this.getConnectionConfig(pluginId);\n const databaseName = (connection as Knex.ConnectionConfig)?.database;\n return databaseName ?? `${this.prefix}${pluginId}`;\n }\n\n /**\n * Provides the client type which should be used for a given plugin.\n *\n * The client type is determined by plugin specific config if present.\n * Otherwise the base client is used as the fallback.\n *\n * @param pluginId - Plugin to get the client type for\n * @returns Object with client type returned as `client` and boolean\n * representing whether or not the client was overridden as\n * `overridden`\n */\n private getClientType(pluginId: string): {\n client: string;\n overridden: boolean;\n } {\n const pluginClient = this.config.getOptionalString(\n `${pluginPath(pluginId)}.client`,\n );\n\n const baseClient = this.config.getString('client');\n const client = pluginClient ?? baseClient;\n return {\n client,\n overridden: client !== baseClient,\n };\n }\n\n private getRoleConfig(pluginId: string): string | undefined {\n return (\n this.config.getOptionalString(`${pluginPath(pluginId)}.role`) ??\n this.config.getOptionalString('role')\n );\n }\n\n /**\n * Provides the knexConfig which should be used for a given plugin.\n *\n * @param pluginId - Plugin to get the knexConfig for\n * @returns The merged knexConfig value or undefined if it isn't specified\n */\n private getAdditionalKnexConfig(pluginId: string): JsonObject | undefined {\n const pluginConfig = this.config\n .getOptionalConfig(`${pluginPath(pluginId)}.knexConfig`)\n ?.get<JsonObject>();\n\n const baseConfig = this.config\n .getOptionalConfig('knexConfig')\n ?.get<JsonObject>();\n\n return merge(baseConfig, pluginConfig);\n }\n\n private getEnsureExistsConfig(pluginId: string): boolean {\n const baseConfig = this.config.getOptionalBoolean('ensureExists') ?? true;\n return (\n this.config.getOptionalBoolean(`${pluginPath(pluginId)}.ensureExists`) ??\n baseConfig\n );\n }\n\n private getPluginDivisionModeConfig(): string {\n return this.config.getOptionalString('pluginDivisionMode') ?? 'database';\n }\n\n /**\n * Provides a Knex connection plugin config by combining base and plugin\n * config.\n *\n * This method provides a baseConfig for a plugin database connector. If the\n * client type has not been overridden, the global connection config will be\n * included with plugin specific config as the base. Values from the plugin\n * connection take precedence over the base. Base database name is omitted\n * unless `pluginDivisionMode` is set to `schema`.\n */\n private getConnectionConfig(pluginId: string): Knex.StaticConnectionConfig {\n const { overridden } = this.getClientType(pluginId);\n\n let baseConnection = normalizeConnection(this.config.get('connection'));\n\n // Databases cannot be shared unless the `pluginDivisionMode` is set to `schema`. The\n // `database` property from the base connection is omitted unless `pluginDivisionMode`\n // is set to `schema`.\n if (this.getPluginDivisionModeConfig() !== 'schema') {\n baseConnection = omit(baseConnection, 'database');\n }\n\n // get and normalize optional plugin specific database connection\n const connection = normalizeConnection(\n this.config.getOptional(`${pluginPath(pluginId)}.connection`),\n );\n\n return {\n // include base connection if client type has not been overridden\n ...(overridden ? {} : baseConnection),\n ...connection,\n } as Knex.StaticConnectionConfig;\n }\n\n /**\n * Provides a Knex database config for a given plugin.\n *\n * This method provides a Knex configuration object along with the plugin's\n * client type.\n *\n * @param pluginId - The plugin that the database config should correspond with\n */\n private getConfigForPlugin(pluginId: string): Knex.Config {\n const { client } = this.getClientType(pluginId);\n const role = this.getRoleConfig(pluginId);\n\n return {\n ...this.getAdditionalKnexConfig(pluginId),\n client,\n connection: this.getConnectionConfig(pluginId),\n ...(role && { role }),\n };\n }\n\n /**\n * Provides a partial `Knex.Config`• database name override for a given plugin.\n *\n * @param pluginId - Target plugin to get database name override\n * @returns Partial `Knex.Config` with database name override\n */\n private getDatabaseOverrides(pluginId: string): Knex.Config {\n const databaseName = this.getDatabaseName(pluginId);\n return databaseName ? defaultNameOverride(databaseName) : {};\n }\n}\n"],"names":["limiterFactory","knexFactory","mergeDatabaseConfig","yn","InputError","ConfigReader","merge","omit","defaultNameOverride"],"mappings":";;;;;;;;;;;;;;;;;AA6BA,MAAM,UAAA,GAAaA,gCAAe,CAAC,CAAA;AAQ5B,SAAS,yBAAA,CACd,UACA,SAAA,EACA;AACA,EAAA,MAAM,UAAA,GAAa,wBAAA,CAAyB,QAAA,EAAU,SAAS,CAAA;AAC/D,EAAA,MAAM,Q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AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQQ,qBAAqB,QAAA,EAA+B;AAC1D,IAAA,MAAM,YAAA,GAAe,IAAA,CAAK,eAAA,CAAgB,QAAQ,CAAA;AAClD,IAAA,OAAO,YAAA,GAAeC,2BAAA,CAAoB,YAAY,CAAA,GAAI,EAAC;AAAA,EAC7D;AACF;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"mysql.cjs.js","sources":["../../../../src/entrypoints/database/connectors/mysql.ts"],"sourcesContent":["/*\n * Copyright 2020 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 { LifecycleService, LoggerService } from '@backstage/backend-plugin-api';\nimport { Config, ConfigReader } from '@backstage/config';\nimport { InputError } from '@backstage/errors';\nimport { JsonObject } from '@backstage/types';\nimport knexFactory, { Knex } from 'knex';\nimport { merge, omit } from 'lodash';\nimport limiterFactory from 'p-limit';\nimport yn from 'yn';\nimport { Connector } from '../types';\nimport defaultNameOverride from './defaultNameOverride';\nimport { mergeDatabaseConfig } from './mergeDatabaseConfig';\n\n// Limits the number of concurrent DDL operations to 1\nconst ddlLimiter = limiterFactory(1);\n\n/**\n * Creates a knex mysql database connection\n *\n * @param dbConfig - The database config\n * @param overrides - Additional options to merge with the config\n */\nexport function createMysqlDatabaseClient(\n dbConfig: Config,\n overrides?: Knex.Config,\n) {\n const knexConfig = buildMysqlDatabaseConfig(dbConfig, overrides);\n const database = knexFactory(knexConfig);\n return database;\n}\n\n/**\n * Builds a knex mysql database connection\n *\n * @param dbConfig - The database config\n * @param overrides - Additional options to merge with the config\n */\nexport function buildMysqlDatabaseConfig(\n dbConfig: Config,\n overrides?: Knex.Config,\n) {\n return mergeDatabaseConfig(\n { pool: { min: 0 } },\n dbConfig.get(),\n {\n connection: getMysqlConnectionConfig(dbConfig, !!overrides),\n useNullAsDefault: true,\n },\n overrides,\n );\n}\n\n/**\n * Gets the mysql connection config\n *\n * @param dbConfig - The database config\n * @param parseConnectionString - Flag to explicitly control connection string parsing\n */\nexport function getMysqlConnectionConfig(\n dbConfig: Config,\n parseConnectionString?: boolean,\n): Knex.MySqlConnectionConfig | string {\n const connection = dbConfig.get('connection') as any;\n const isConnectionString =\n typeof connection === 'string' || connection instanceof String;\n const autoParse = typeof parseConnectionString !== 'boolean';\n\n const shouldParseConnectionString = autoParse\n ? isConnectionString\n : parseConnectionString && isConnectionString;\n\n return shouldParseConnectionString\n ? parseMysqlConnectionString(connection as string)\n : connection;\n}\n\n/**\n * Parses a mysql connection string.\n *\n * e.g. mysql://examplename:somepassword@examplehost:3306/dbname\n * @param connectionString - The mysql connection string\n */\nexport function parseMysqlConnectionString(\n connectionString: string,\n): Knex.MySqlConnectionConfig {\n try {\n const {\n protocol,\n username,\n password,\n port,\n hostname,\n pathname,\n searchParams,\n } = new URL(connectionString);\n\n if (protocol !== 'mysql:') {\n throw new Error(`Unknown protocol ${protocol}`);\n } else if (!username || !password) {\n throw new Error(`Missing username/password`);\n } else if (!pathname.match(/^\\/[^/]+$/)) {\n throw new Error(`Expected single path segment`);\n }\n\n const result: Knex.MySqlConnectionConfig = {\n user: username,\n password,\n host: hostname,\n port: Number(port || 3306),\n database: decodeURIComponent(pathname.substring(1)),\n };\n\n const ssl = searchParams.get('ssl');\n if (ssl) {\n result.ssl = ssl;\n }\n\n const debug = searchParams.get('debug');\n if (debug) {\n result.debug = yn(debug);\n }\n\n return result;\n } catch (e) {\n throw new InputError(\n `Error while parsing MySQL connection string, ${e}`,\n e,\n );\n }\n}\n\n/**\n * Creates the missing mysql database if it does not exist\n *\n * @param dbConfig - The database config\n * @param databases - The names of the databases to create\n */\nexport async function ensureMysqlDatabaseExists(\n dbConfig: Config,\n ...databases: Array<string>\n) {\n const admin = createMysqlDatabaseClient(dbConfig, {\n connection: {\n database: null as unknown as string,\n },\n pool: {\n min: 0,\n acquireTimeoutMillis: 10000,\n },\n });\n\n try {\n const ensureDatabase = async (database: string) => {\n await admin.raw(`CREATE DATABASE IF NOT EXISTS ??`, [database]);\n };\n await Promise.all(\n databases.map(async database => {\n // For initial setup we use a smaller timeout but several retries. Given that this\n // is a separate connection pool we should never really run into issues with connection\n // acquisition timeouts, but we do anyway. This might be a bug in knex or some other dependency.\n let lastErr: Error | undefined = undefined;\n for (let i = 0; i < 3; i++) {\n try {\n return await ddlLimiter(() => ensureDatabase(database));\n } catch (err) {\n lastErr = err;\n }\n await new Promise(resolve => setTimeout(resolve, 100));\n }\n throw lastErr;\n }),\n );\n } finally {\n await admin.destroy();\n }\n}\n\n/**\n * Drops the given mysql databases.\n *\n * @param dbConfig - The database config\n * @param databases - The names of the databases to create\n */\nexport async function dropMysqlDatabase(\n dbConfig: Config,\n ...databases: Array<string>\n) {\n const admin = createMysqlDatabaseClient(dbConfig, {\n connection: {\n database: null as unknown as string,\n },\n pool: {\n min: 0,\n acquireTimeoutMillis: 10000,\n },\n });\n\n try {\n const dropDatabase = async (database: string) => {\n await admin.raw(`DROP DATABASE ??`, [database]);\n };\n await Promise.all(\n databases.map(async database => {\n return await ddlLimiter(() => dropDatabase(database));\n }),\n );\n } finally {\n await admin.destroy();\n }\n}\n\n/**\n * Provides a config lookup path for a plugin's config block.\n */\nfunction pluginPath(pluginId: string): string {\n return `plugin.${pluginId}`;\n}\n\nfunction normalizeConnection(\n connection: Knex.StaticConnectionConfig | JsonObject | string | undefined,\n): Partial<Knex.StaticConnectionConfig> {\n if (typeof connection === 'undefined' || connection === null) {\n return {};\n }\n\n return typeof connection === 'string' || connection instanceof String\n ? parseMysqlConnectionString(connection as string)\n : connection;\n}\n\nexport class MysqlConnector implements Connector {\n private readonly config: Config;\n private readonly prefix: string;\n\n constructor(config: Config, prefix: string) {\n this.config = config;\n this.prefix = prefix;\n }\n\n async getClient(\n pluginId: string,\n _deps: {\n logger: LoggerService;\n lifecycle: LifecycleService;\n },\n ): Promise<Knex> {\n const pluginConfig = new ConfigReader(\n this.getConfigForPlugin(pluginId) as JsonObject,\n );\n\n const databaseName = this.getDatabaseName(pluginId);\n if (databaseName && this.getEnsureExistsConfig(pluginId)) {\n try {\n await ensureMysqlDatabaseExists(pluginConfig, databaseName);\n } catch (error) {\n throw new Error(\n `Failed to connect to the database to make sure that '${databaseName}' exists, ${error}`,\n );\n }\n }\n\n const pluginDivisionMode = this.getPluginDivisionModeConfig();\n if (pluginDivisionMode !== 'database') {\n throw new Error(\n `The MySQL driver does not support plugin division mode '${pluginDivisionMode}'`,\n );\n }\n\n const databaseClientOverrides = mergeDatabaseConfig(\n {},\n this.getDatabaseOverrides(pluginId),\n );\n\n const client = createMysqlDatabaseClient(\n pluginConfig,\n databaseClientOverrides,\n );\n\n return client;\n }\n\n /**\n * Provides the canonical database name for a given plugin.\n *\n * This method provides the effective database name which is determined using\n * global and plugin specific database config. If no explicit database name,\n * this method will provide a generated name which is the pluginId prefixed\n * with 'backstage_plugin_'.\n *\n * @param pluginId - Lookup the database name for given plugin\n * @returns String representing the plugin's database name\n */\n private getDatabaseName(pluginId: string): string | undefined {\n const connection = this.getConnectionConfig(pluginId);\n const databaseName = (connection as Knex.ConnectionConfig)?.database;\n return databaseName ?? `${this.prefix}${pluginId}`;\n }\n\n /**\n * Provides the client type which should be used for a given plugin.\n *\n * The client type is determined by plugin specific config if present.\n * Otherwise the base client is used as the fallback.\n *\n * @param pluginId - Plugin to get the client type for\n * @returns Object with client type returned as `client` and boolean\n * representing whether or not the client was overridden as\n * `overridden`\n */\n private getClientType(pluginId: string): {\n client: string;\n overridden: boolean;\n } {\n const pluginClient = this.config.getOptionalString(\n `${pluginPath(pluginId)}.client`,\n );\n\n const baseClient = this.config.getString('client');\n const client = pluginClient ?? baseClient;\n return {\n client,\n overridden: client !== baseClient,\n };\n }\n\n private getRoleConfig(pluginId: string): string | undefined {\n return (\n this.config.getOptionalString(`${pluginPath(pluginId)}.role`) ??\n this.config.getOptionalString('role')\n );\n }\n\n /**\n * Provides the knexConfig which should be used for a given plugin.\n *\n * @param pluginId - Plugin to get the knexConfig for\n * @returns The merged knexConfig value or undefined if it isn't specified\n */\n private getAdditionalKnexConfig(pluginId: string): JsonObject | undefined {\n const pluginConfig = this.config\n .getOptionalConfig(`${pluginPath(pluginId)}.knexConfig`)\n ?.get<JsonObject>();\n\n const baseConfig = this.config\n .getOptionalConfig('knexConfig')\n ?.get<JsonObject>();\n\n return merge(baseConfig, pluginConfig);\n }\n\n private getEnsureExistsConfig(pluginId: string): boolean {\n const baseConfig = this.config.getOptionalBoolean('ensureExists') ?? true;\n return (\n this.config.getOptionalBoolean(`${pluginPath(pluginId)}.ensureExists`) ??\n baseConfig\n );\n }\n\n private getPluginDivisionModeConfig(): string {\n return this.config.getOptionalString('pluginDivisionMode') ?? 'database';\n }\n\n /**\n * Provides a Knex connection plugin config by combining base and plugin\n * config.\n *\n * This method provides a baseConfig for a plugin database connector. If the\n * client type has not been overridden, the global connection config will be\n * included with plugin specific config as the base. Values from the plugin\n * connection take precedence over the base. Base database name is omitted\n * unless `pluginDivisionMode` is set to `schema`.\n */\n private getConnectionConfig(pluginId: string): Knex.StaticConnectionConfig {\n const { overridden } = this.getClientType(pluginId);\n\n let baseConnection = normalizeConnection(this.config.get('connection'));\n\n // Databases cannot be shared unless the `pluginDivisionMode` is set to `schema`. The\n // `database` property from the base connection is omitted unless `pluginDivisionMode`\n // is set to `schema`.\n if (this.getPluginDivisionModeConfig() !== 'schema') {\n baseConnection = omit(baseConnection, 'database');\n }\n\n // get and normalize optional plugin specific database connection\n const connection = normalizeConnection(\n this.config.getOptional(`${pluginPath(pluginId)}.connection`),\n );\n\n return {\n // include base connection if client type has not been overridden\n ...(overridden ? {} : baseConnection),\n ...connection,\n } as Knex.StaticConnectionConfig;\n }\n\n /**\n * Provides a Knex database config for a given plugin.\n *\n * This method provides a Knex configuration object along with the plugin's\n * client type.\n *\n * @param pluginId - The plugin that the database config should correspond with\n */\n private getConfigForPlugin(pluginId: string): Knex.Config {\n const { client } = this.getClientType(pluginId);\n const role = this.getRoleConfig(pluginId);\n\n return {\n ...this.getAdditionalKnexConfig(pluginId),\n client,\n connection: this.getConnectionConfig(pluginId),\n ...(role && { role }),\n };\n }\n\n /**\n * Provides a partial `Knex.Config`• database name override for a given plugin.\n *\n * @param pluginId - Target plugin to get database name override\n * @returns Partial `Knex.Config` with database name override\n */\n private getDatabaseOverrides(pluginId: string): Knex.Config {\n const databaseName = this.getDatabaseName(pluginId);\n return databaseName ? defaultNameOverride(databaseName) : {};\n }\n}\n"],"names":["limiterFactory","knexFactory","mergeDatabaseConfig","yn","InputError","ConfigReader","merge","omit","defaultNameOverride"],"mappings":";;;;;;;;;;;;;;;;;AA6BA,MAAM,UAAA,GAAaA,gCAAe,CAAC,CAAA;AAQ5B,SAAS,yBAAA,CACd,UACA,SAAA,EACA;AACA,EAAA,MAAM,UAAA,GAAa,wBAAA,CAAyB,QAAA,EAAU,SAAS,CAAA;AAC/D,EAAA,MAAM,QAAA,GAAWC,6BAAY,UAAU,CAAA;AACvC,EAAA,OAAO,QAAA;AACT;AAQO,SAAS,wBAAA,CACd,UACA,SAAA,EACA;AACA,EAAA,OAAOC,uCAAA;AAAA,IACL,EAAE,IAAA,EAAM,EAAE,GAAA,EAAK,GAAE,EAAE;AAAA,IACnB,SAAS,GAAA,EAAI;AAAA,IACb;AAAA,MACE,UAAA,EAAY,wBAAA,CAAyB,QAAA,EAAU,CAAC,CAAC,SAAS,CAAA;AAAA,MAC1D,gBAAA,EAAkB;AAAA,KACpB;AAAA,IACA;AAAA,GACF;AACF;AAQO,SAAS,wBAAA,CACd,UACA,qBAAA,EACqC;AACrC,EAAA,MAAM,UAAA,GAAa,QAAA,CAAS,GAAA,CAAI,YAAY,CAAA;AAC5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AK,2BAAA,EAA4B,KAAM,QAAA,EAAU;AACnD,MAAA,cAAA,GAAiBC,WAAA,CAAK,gBAAgB,UAAU,CAAA;AAAA,IAClD;AAGA,IAAA,MAAM,UAAA,GAAa,mBAAA;AAAA,MACjB,KAAK,MAAA,CAAO,WAAA,CAAY,GAAG,UAAA,CAAW,QAAQ,CAAC,CAAA,WAAA,CAAa;AAAA,KAC9D;AAEA,IAAA,OAAO;AAAA;AAAA,MAEL,GAAI,UAAA,GAAa,EAAC,GAAI,cAAA;AAAA,MACtB,GAAG;AAAA,KACL;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUQ,mBAAmB,QAAA,EAA+B;AACxD,IAAA,MAAM,EAAE,MAAA,EAAO,GAAI,IAAA,CAAK,cAAc,QAAQ,CAAA;AAC9C,IAAA,MAAM,IAAA,GAAO,IAAA,CAAK,aAAA,CAAc,QAAQ,CAAA;AAExC,IAAA,OAAO;AAAA,MACL,GAAG,IAAA,CAAK,uBAAA,CAAwB,QAAQ,CAAA;AAAA,MACxC,MAAA;AAAA,MACA,UAAA,EAAY,IAAA,CAAK,mBAAA,CAAoB,QAAQ,CAAA;AAAA,MAC7C,GAAI,IAAA,IAAQ,EAAE,IAAA;AAAK,KACrB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQQ,qBAAqB,QAAA,EAA+B;AAC1D,IAAA,MAAM,YAAA,GAAe,IAAA,CAAK,eAAA,CAAgB,QAAQ,CAAA;AAClD,IAAA,OAAO,YAAA,GAAeC,2BAAA,CAAoB,YAAY,CAAA,GAAI,EAAC;AAAA,EAC7D;AACF;;;;;;;"}
|
|
@@ -195,6 +195,7 @@ async function createPgDatabaseClient(dbConfig, overrides) {
|
|
|
195
195
|
}
|
|
196
196
|
async function buildPgDatabaseConfig(dbConfig, overrides) {
|
|
197
197
|
const config$1 = mergeDatabaseConfig.mergeDatabaseConfig(
|
|
198
|
+
{ pool: { min: 0 } },
|
|
198
199
|
dbConfig.get(),
|
|
199
200
|
{
|
|
200
201
|
connection: getPgConnectionConfig(dbConfig, !!overrides),
|
|
@@ -341,6 +342,7 @@ async function buildCloudSqlConfig(config) {
|
|
|
341
342
|
}
|
|
342
343
|
async function buildRdsPgConfig(config) {
|
|
343
344
|
const { Signer } = require("@aws-sdk/rds-signer");
|
|
345
|
+
const { fromNodeProviderChain } = require("@aws-sdk/credential-providers");
|
|
344
346
|
let hostname;
|
|
345
347
|
let port;
|
|
346
348
|
let username;
|
|
@@ -365,13 +367,28 @@ async function buildRdsPgConfig(config) {
|
|
|
365
367
|
config.get("connection"),
|
|
366
368
|
["type", "region"]
|
|
367
369
|
);
|
|
368
|
-
const
|
|
370
|
+
const credentialsProvider = fromNodeProviderChain();
|
|
369
371
|
const tokenTtlMs = 15 * 60 * 1e3;
|
|
370
372
|
const renewalOffsetMs = 60 * 1e3;
|
|
371
373
|
async function getConnectionConfig() {
|
|
372
374
|
try {
|
|
375
|
+
let credentials = await credentialsProvider();
|
|
376
|
+
if (credentials.expiration && credentials.expiration.getTime() <= Date.now() + renewalOffsetMs) {
|
|
377
|
+
credentials = await credentialsProvider({ forceRefresh: true });
|
|
378
|
+
}
|
|
379
|
+
const signer = new Signer({
|
|
380
|
+
hostname,
|
|
381
|
+
port,
|
|
382
|
+
username,
|
|
383
|
+
region,
|
|
384
|
+
credentials
|
|
385
|
+
});
|
|
386
|
+
const tokenIssuedAt = Date.now();
|
|
373
387
|
const password = await signer.getAuthToken();
|
|
374
|
-
const tokenExpiration =
|
|
388
|
+
const tokenExpiration = Math.min(
|
|
389
|
+
tokenIssuedAt + tokenTtlMs,
|
|
390
|
+
credentials.expiration?.getTime() ?? Infinity
|
|
391
|
+
) - renewalOffsetMs;
|
|
375
392
|
return {
|
|
376
393
|
...sanitizedConnection,
|
|
377
394
|
password,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres.cjs.js","sources":["../../../../src/entrypoints/database/connectors/postgres.ts"],"sourcesContent":["/*\n * Copyright 2020 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 { LifecycleService, LoggerService } from '@backstage/backend-plugin-api';\nimport {\n Config,\n ConfigReader,\n readDurationFromConfig,\n} from '@backstage/config';\nimport { ForwardedError } from '@backstage/errors';\nimport {\n durationToMilliseconds,\n HumanDuration,\n JsonObject,\n} from '@backstage/types';\nimport knexFactory, { Knex } from 'knex';\nimport { merge, omit } from 'lodash';\nimport limiterFactory from 'p-limit';\nimport { Client } from 'pg';\nimport { Connector } from '../types';\nimport { mergeDatabaseConfig } from './mergeDatabaseConfig';\nimport format from 'pg-format';\nimport { TokenCredential } from '@azure/identity';\n\n// Limits the number of concurrent DDL operations to 1\nconst ddlLimiter = limiterFactory(1);\n\nconst cloudSqlConnectorMaxAttempts = 3;\nconst cloudSqlConnectorInitialRetryDelayMs = 200;\nconst cloudSqlConnectorRetryableErrorCodes = new Set([\n 'EAI_AGAIN',\n 'ECONNREFUSED',\n 'ECONNRESET',\n 'EHOSTUNREACH',\n 'ENETUNREACH',\n 'EPIPE',\n 'ETIMEDOUT',\n 'UND_ERR_CONNECT_TIMEOUT',\n]);\n\nasync function retryWithExponentialBackoff<T>(\n operation: () => Promise<T>,\n options: {\n maxAttempts: number;\n initialDelayMs: number;\n shouldRetry: (error: unknown) => boolean;\n },\n): Promise<T> {\n for (let attempt = 1; ; attempt++) {\n try {\n return await operation();\n } catch (error) {\n if (attempt >= options.maxAttempts || !options.shouldRetry(error)) {\n throw error;\n }\n const maxDelay = options.initialDelayMs * 2 ** (attempt - 1);\n const delay = Math.random() * maxDelay;\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n }\n}\n\nfunction isCloudSqlConnectorRetryableError(error: unknown): boolean {\n let current = error;\n const seen = new Set<unknown>();\n\n while (current && typeof current === 'object' && !seen.has(current)) {\n seen.add(current);\n const errorRecord = current as Record<string, unknown>;\n const code = errorRecord.code;\n if (\n typeof code === 'string' &&\n cloudSqlConnectorRetryableErrorCodes.has(code)\n ) {\n return true;\n }\n\n let status = errorRecord.status;\n if (typeof status !== 'number') {\n status = errorRecord.statusCode;\n }\n if (typeof status !== 'number') {\n const response = errorRecord.response;\n status =\n response && typeof response === 'object'\n ? (response as Record<string, unknown>).status\n : undefined;\n }\n if (\n typeof status === 'number' &&\n (status === 408 || status === 429 || (status >= 500 && status <= 599))\n ) {\n return true;\n }\n\n current = errorRecord.cause;\n }\n\n return false;\n}\n\nexport class PgAdminPool {\n private client?: Promise<Knex>;\n private destruction?: Promise<void>;\n private readonly destructionErrors: unknown[] = [];\n private idleTimer?: NodeJS.Timeout;\n private readonly operations = new Set<Promise<unknown>>();\n private isShutdown = false;\n\n constructor(\n private readonly createClient: () => Promise<Knex>,\n private readonly idleTimeoutMillis: number,\n ) {}\n\n async run<T>(operation: (client: Knex) => Promise<T> | T): Promise<T> {\n if (this.isShutdown) {\n throw new Error('PostgreSQL admin pool is shut down');\n }\n\n clearTimeout(this.idleTimer);\n this.idleTimer = undefined;\n\n const operationPromise = this.runOperation(operation);\n this.operations.add(operationPromise);\n try {\n return await operationPromise;\n } finally {\n this.operations.delete(operationPromise);\n this.scheduleIdleDestroy();\n }\n }\n\n async shutdown(): Promise<void> {\n this.isShutdown = true;\n clearTimeout(this.idleTimer);\n this.idleTimer = undefined;\n\n await Promise.allSettled(this.operations);\n await this.destroyClient().catch(() => {});\n if (this.destructionErrors.length > 0) {\n throw new AggregateError(\n this.destructionErrors,\n 'Failed to destroy PostgreSQL admin pool clients',\n );\n }\n }\n\n async invalidate(): Promise<void> {\n clearTimeout(this.idleTimer);\n this.idleTimer = undefined;\n\n await Promise.allSettled(this.operations);\n await this.destroyClient();\n }\n\n private async runOperation<T>(\n operation: (client: Knex) => Promise<T> | T,\n ): Promise<T> {\n if (this.destruction) {\n await this.destruction;\n }\n if (this.isShutdown) {\n throw new Error('PostgreSQL admin pool is shut down');\n }\n\n let clientPromise = this.client;\n if (!clientPromise) {\n clientPromise = this.createClient();\n this.client = clientPromise;\n void clientPromise.catch(() => {\n if (this.client === clientPromise) {\n this.client = undefined;\n }\n });\n }\n return operation(await clientPromise);\n }\n\n private scheduleIdleDestroy(): void {\n if (this.isShutdown || this.operations.size > 0) {\n return;\n }\n\n const timer = setTimeout(() => {\n if (this.idleTimer === timer) {\n this.idleTimer = undefined;\n void this.destroyClient().catch(() => {});\n }\n }, this.idleTimeoutMillis);\n timer.unref();\n this.idleTimer = timer;\n }\n\n private destroyClient(): Promise<void> {\n if (this.destruction) {\n return this.destruction;\n }\n\n const clientPromise = this.client;\n this.client = undefined;\n if (!clientPromise) {\n return Promise.resolve();\n }\n\n const destruction = clientPromise.then(\n client => client.destroy(),\n () => undefined,\n );\n this.destruction = destruction;\n void destruction.then(\n () => {\n if (this.destruction === destruction) {\n this.destruction = undefined;\n }\n },\n error => {\n if (this.destruction === destruction) {\n this.destruction = undefined;\n this.destructionErrors.push(error);\n }\n },\n );\n return destruction;\n }\n}\n\n/**\n * Creates a knex postgres database connection\n *\n * @param dbConfig - The database config\n * @param overrides - Additional options to merge with the config\n */\nexport async function createPgDatabaseClient(\n dbConfig: Config,\n overrides?: Knex.Config,\n) {\n const knexConfig = await buildPgDatabaseConfig(dbConfig, overrides);\n const database = knexFactory(knexConfig);\n\n const role = dbConfig.getOptionalString('role');\n\n if (role) {\n database.client.pool.on(\n 'createSuccess',\n async (_event: number, pgClient: Client) => {\n const query = format('SET ROLE %I', role);\n await pgClient.query(query);\n },\n );\n }\n return database;\n}\n\n/**\n * Builds a knex postgres database connection\n *\n * @param dbConfig - The database config\n * @param overrides - Additional options to merge with the config\n */\nexport async function buildPgDatabaseConfig(\n dbConfig: Config,\n overrides?: Knex.Config,\n) {\n const config = mergeDatabaseConfig(\n dbConfig.get(),\n {\n connection: getPgConnectionConfig(dbConfig, !!overrides),\n useNullAsDefault: true,\n },\n overrides,\n );\n const mergedConfigReader = new ConfigReader(config);\n\n if (config.connection.type === 'default' || !config.connection.type) {\n const connectionValue = config.connection;\n const sanitizedConnection =\n typeof connectionValue === 'string' || connectionValue instanceof String\n ? connectionValue\n : // connection is an object, omit config-only props\n omit(connectionValue as Record<string, unknown>, [\n 'type',\n 'instance',\n 'tokenCredential',\n ]);\n\n return {\n ...config,\n connection: sanitizedConnection,\n };\n }\n\n switch (config.connection.type) {\n case 'azure':\n return buildAzurePgConfig(mergedConfigReader);\n case 'cloudsql':\n return buildCloudSqlConfig(mergedConfigReader);\n case 'rds':\n return buildRdsPgConfig(mergedConfigReader);\n default:\n throw new Error(`Unknown connection type: ${config.connection.type}`);\n }\n}\n\n/* Note: the following type definition is intentionally duplicated in\n * /packages/backend-defaults/config.d.ts so the clientSecret property\n * can be annotated with \"@visibility secret\" there.\n */\nexport type AzureTokenCredentialConfig = {\n /**\n * How early before an access token expires to refresh it with a new one.\n * Defaults to 5 minutes\n * Supported formats:\n * - A string in the format of '1d', '2 seconds' etc. as supported by the `ms`\n * library.\n * - A standard ISO formatted duration string, e.g. 'P2DT6H' or 'PT1M'.\n * - An object with individual units (in plural) as keys, e.g. `{ days: 2, hours: 6 }`.\n */\n tokenRenewableOffsetTime?: string | HumanDuration;\n /**\n * The client ID of a user-assigned managed identity.\n * If not provided, the system-assigned managed identity is used.\n */\n clientId?: string;\n clientSecret?: string;\n tenantId?: string;\n};\n\nexport async function buildAzurePgConfig(config: Config): Promise<Knex.Config> {\n const {\n DefaultAzureCredential,\n ManagedIdentityCredential,\n ClientSecretCredential,\n } = require('@azure/identity');\n\n const tokenConfig = config.getOptionalConfig('connection.tokenCredential');\n\n const tokenRenewableOffsetTime = durationToMilliseconds(\n tokenConfig?.has('tokenRenewableOffsetTime')\n ? readDurationFromConfig(tokenConfig, { key: 'tokenRenewableOffsetTime' })\n : { minutes: 5 },\n );\n\n const clientId = tokenConfig?.getOptionalString('clientId');\n const tenantId = tokenConfig?.getOptionalString('tenantId');\n const clientSecret = tokenConfig?.getOptionalString('clientSecret');\n let credential: TokenCredential;\n\n /**\n * Determine which TokenCredential to use based on provided config\n * 1. If clientId, tenantId and clientSecret are provided, use ClientSecretCredential\n * 2. If only clientId is provided, use ManagedIdentityCredential with user-assigned identity\n * 3. Otherwise, use DefaultAzureCredential (which may use system-assigned identity among other methods)\n */\n if (clientId && tenantId && clientSecret) {\n credential = new ClientSecretCredential(tenantId, clientId, clientSecret);\n } else if (clientId) {\n credential = new ManagedIdentityCredential(clientId);\n } else {\n credential = new DefaultAzureCredential();\n }\n\n const rawConfig = config.get() as Record<string, unknown>;\n\n const normalized = normalizeConnection(rawConfig.connection as any);\n const sanitizedConnection = omit(normalized, [\n 'type',\n 'instance',\n 'tokenCredential',\n ]) as Partial<Knex.StaticConnectionConfig>;\n\n async function getConnectionConfig() {\n const token = await credential.getToken(\n 'https://ossrdbms-aad.database.windows.net/.default',\n );\n\n if (!token) {\n throw new Error(\n 'Failed to acquire Azure access token for database authentication',\n );\n }\n\n const connectionConfig = {\n ...sanitizedConnection,\n password: token.token,\n expirationChecker: () =>\n /* return true if the token is within the renewable offset time */\n token.expiresOnTimestamp - tokenRenewableOffsetTime <= Date.now(),\n };\n\n return connectionConfig;\n }\n\n return {\n ...(rawConfig as Record<string, unknown>),\n connection: getConnectionConfig,\n };\n}\n\n/**\n * Builds a PostgreSQL configuration for Cloud SQL.\n *\n * Transient failures during connector initialization are retried up to three\n * times with jittered exponential backoff. Configuration and authorization\n * failures are returned immediately.\n */\nexport async function buildCloudSqlConfig(\n config: Config,\n): Promise<Knex.Config> {\n const client = config.getOptionalString('client');\n\n if (client && client !== 'pg') {\n throw new Error('Cloud SQL only supports the pg client');\n }\n\n const instance = config.getOptionalString('connection.instance');\n if (!instance) {\n throw new Error('Missing instance connection name for Cloud SQL');\n }\n\n const {\n Connector: CloudSqlConnector,\n IpAddressTypes,\n AuthTypes,\n } = require('@google-cloud/cloud-sql-connector') as typeof import('@google-cloud/cloud-sql-connector');\n\n type IpType = (typeof IpAddressTypes)[keyof typeof IpAddressTypes];\n const ipTypeRaw = config.getOptionalString('connection.ipAddressType');\n\n let ipType: IpType | undefined;\n if (ipTypeRaw !== undefined) {\n if (\n !(Object.values(IpAddressTypes) as Array<string | number>).includes(\n ipTypeRaw as any,\n )\n ) {\n throw new Error(\n `Invalid connection.ipAddressType: ${ipTypeRaw}; valid values: ${Object.values(\n IpAddressTypes,\n ).join(', ')}`,\n );\n }\n ipType = ipTypeRaw as unknown as IpType;\n }\n\n /**\n * Retry only transient connector initialization failures. A fresh connector\n * is required because a failed initialization may be cached by the client.\n */\n const clientOpts = await retryWithExponentialBackoff(\n async () => {\n const connector = new CloudSqlConnector();\n return connector.getOptions({\n instanceConnectionName: instance,\n ipType: ipType ?? IpAddressTypes.PUBLIC,\n authType: AuthTypes.IAM,\n });\n },\n {\n maxAttempts: cloudSqlConnectorMaxAttempts,\n initialDelayMs: cloudSqlConnectorInitialRetryDelayMs,\n shouldRetry: isCloudSqlConnectorRetryableError,\n },\n );\n\n const rawConfig = config.get() as Record<string, unknown>;\n const normalized = normalizeConnection(rawConfig.connection as any);\n const sanitizedConnection = omit(normalized, [\n 'type',\n 'instance',\n ]) as Partial<Knex.StaticConnectionConfig>;\n\n return {\n ...(rawConfig as Record<string, unknown>),\n client: 'pg',\n connection: {\n ...sanitizedConnection,\n ...clientOpts,\n },\n };\n}\n\nexport async function buildRdsPgConfig(config: Config): Promise<Knex.Config> {\n const { Signer } =\n require('@aws-sdk/rds-signer') as typeof import('@aws-sdk/rds-signer');\n\n let hostname: string;\n let port: number;\n let username: string;\n try {\n hostname = config.getString('connection.host');\n port = config.getNumber('connection.port');\n username = config.getString('connection.user');\n } catch (err) {\n throw new ForwardedError(\n 'AWS RDS IAM auth: missing required database connection config — make sure connection.host, connection.port, and connection.user are set and any environment variables they reference are set',\n err,\n );\n }\n const region =\n config.getOptionalString('connection.region') ??\n process.env.AWS_REGION ??\n process.env.AWS_DEFAULT_REGION;\n if (!region) {\n throw new Error(\n 'Missing region for AWS RDS IAM auth: set connection.region or the AWS_REGION environment variable',\n );\n }\n\n const rawConfig = config.get() as Record<string, unknown>;\n const sanitizedConnection = omit(\n config.get('connection') as Record<string, unknown>,\n ['type', 'region'],\n ) as Partial<Knex.StaticConnectionConfig>;\n\n const signer = new Signer({ hostname, port, username, region });\n\n // RDS IAM auth tokens are valid for 15 minutes. Renew 1 minute early so\n // that pooled connections are refreshed before the token actually expires.\n const tokenTtlMs = 15 * 60 * 1000;\n const renewalOffsetMs = 60 * 1000;\n\n async function getConnectionConfig() {\n try {\n const password = await signer.getAuthToken();\n const tokenExpiration = Date.now() + tokenTtlMs - renewalOffsetMs;\n return {\n ...sanitizedConnection,\n password,\n expirationChecker: () => tokenExpiration <= Date.now(),\n };\n } catch (err) {\n throw new ForwardedError(\n `AWS RDS IAM auth token acquisition failed for ${username}@${hostname}:${port}`,\n err,\n );\n }\n }\n\n return {\n ...(rawConfig as Record<string, unknown>),\n connection: getConnectionConfig,\n };\n}\n\n/**\n * Gets the postgres connection config\n *\n * @param dbConfig - The database config\n * @param parseConnectionString - Flag to explicitly control connection string parsing\n */\nexport function getPgConnectionConfig(\n dbConfig: Config,\n parseConnectionString?: boolean,\n): Knex.PgConnectionConfig | string {\n const connection = dbConfig.get('connection') as any;\n const isConnectionString =\n typeof connection === 'string' || connection instanceof String;\n const autoParse = typeof parseConnectionString !== 'boolean';\n\n const shouldParseConnectionString = autoParse\n ? isConnectionString\n : parseConnectionString && isConnectionString;\n\n return shouldParseConnectionString\n ? parsePgConnectionString(connection as string)\n : connection;\n}\n\n/**\n * Parses a connection string using pg-connection-string\n *\n * @param connectionString - The postgres connection string\n */\nexport function parsePgConnectionString(connectionString: string) {\n const parse = requirePgConnectionString();\n return parse(connectionString);\n}\n\nfunction requirePgConnectionString() {\n try {\n return require('pg-connection-string').parse;\n } catch (e) {\n throw new ForwardedError(\"Postgres: Install 'pg-connection-string'\", e);\n }\n}\n\nconst PG_DATABASE_ADMIN_OVERRIDES: Knex.Config = {\n connection: { database: 'postgres' },\n pool: { min: 0, max: 1, acquireTimeoutMillis: 10000 },\n};\n\nconst PG_SCHEMA_ADMIN_OVERRIDES: Knex.Config = {\n pool: { min: 0, max: 1, acquireTimeoutMillis: 10000 },\n};\n\n/**\n * Creates the missing Postgres database if it does not exist\n *\n * @param dbConfig - The database config\n * @param databases - The name of the databases to create\n */\nexport async function ensurePgDatabaseExists(\n dbConfig: Config,\n ...databases: Array<string>\n) {\n await Promise.all(\n databases.map(async database => {\n return retryPgAdminOperation(() =>\n ddlLimiter(async () => {\n const admin = await createPgDatabaseClient(\n dbConfig,\n PG_DATABASE_ADMIN_OVERRIDES,\n );\n try {\n await ensurePgDatabase(admin, database);\n } finally {\n await admin.destroy();\n }\n }),\n );\n }),\n );\n}\n\nasync function ensurePgDatabase(admin: Knex, database: string): Promise<void> {\n const result = await admin\n .from('pg_database')\n .where('datname', database)\n .count<Record<string, { count: string }>>();\n\n if (parseInt(result[0].count, 10) === 0) {\n await admin.raw(`CREATE DATABASE ??`, [database]);\n }\n}\n\nasync function retryPgAdminOperation(\n operation: () => Promise<void>,\n): Promise<void> {\n // For initial setup we use a smaller timeout but several retries. Given that this\n // is a separate connection pool we should never really run into issues with connection\n // acquisition timeouts, but we do anyway. This might be a bug in knex or some other dependency.\n const maxAttempts = 3;\n for (let attempt = 1; ; attempt++) {\n try {\n return await operation();\n } catch (error) {\n if (attempt >= maxAttempts) {\n throw error;\n }\n await new Promise(resolve => setTimeout(resolve, 100));\n }\n }\n}\n\nasync function ensurePgSchema(\n admin: Knex,\n role: string | undefined,\n schema: string,\n): Promise<void> {\n if (role) {\n await admin.raw(`CREATE SCHEMA IF NOT EXISTS ?? AUTHORIZATION ??`, [\n schema,\n role,\n ]);\n } else {\n await admin.raw(`CREATE SCHEMA IF NOT EXISTS ??`, [schema]);\n }\n}\n\n/**\n * Creates the missing Postgres schema if it does not exist\n *\n * @param dbConfig - The database config\n * @param schemas - The name of the schemas to create\n */\nexport async function ensurePgSchemaExists(\n dbConfig: Config,\n ...schemas: Array<string>\n): Promise<void> {\n const admin = await createPgDatabaseClient(dbConfig);\n const role = dbConfig.getOptionalString('role');\n\n try {\n await Promise.all(\n schemas.map(schema =>\n ddlLimiter(() => ensurePgSchema(admin, role, schema)),\n ),\n );\n } finally {\n await admin.destroy();\n }\n}\n\n/**\n * Drops the Postgres databases.\n *\n * @param dbConfig - The database config\n * @param databases - The name of the databases to drop\n */\nexport async function dropPgDatabase(\n dbConfig: Config,\n ...databases: Array<string>\n) {\n const admin = await createPgDatabaseClient(dbConfig);\n try {\n await Promise.all(\n databases.map(async database => {\n await ddlLimiter(() => admin.raw(`DROP DATABASE ??`, [database]));\n }),\n );\n } finally {\n await admin.destroy();\n }\n}\n\n/**\n * Provides a config lookup path for a plugin's config block.\n */\nfunction pluginPath(pluginId: string): string {\n return `plugin.${pluginId}`;\n}\n\nfunction normalizeConnection(\n connection: Knex.StaticConnectionConfig | JsonObject | string | undefined,\n): Partial<Knex.StaticConnectionConfig> {\n if (typeof connection === 'undefined' || connection === null) {\n return {};\n }\n\n return typeof connection === 'string' || connection instanceof String\n ? parsePgConnectionString(connection as string)\n : connection;\n}\n\n/**\n * The computed configuration for a plugin's postgres database connection.\n */\nexport interface PgPluginDatabaseConfig {\n /** The database client type (e.g. 'pg') */\n client: string;\n /** Whether the client type was overridden at the plugin level */\n clientOverridden: boolean;\n /** The optional role to set on connections */\n role: string | undefined;\n /** Additional knex configuration merged from base and plugin config */\n additionalKnexConfig: JsonObject | undefined;\n /** Whether to ensure the database exists */\n ensureExists: boolean;\n /** Whether to ensure the schema exists */\n ensureSchemaExists: boolean;\n /** The plugin division mode ('database' or 'schema') */\n pluginDivisionMode: string;\n /** The connection configuration */\n connection: Knex.PgConnectionConfig;\n /** The database name, if any */\n databaseName: string | undefined;\n /** The schema name, if using schema division mode */\n schemaName: string | undefined;\n /** Database client overrides including schema overrides if applicable */\n databaseClientOverrides: Knex.Config;\n /** The full knex config for the plugin */\n knexConfig: Knex.Config;\n}\n\n/**\n * Computes all postgres database configuration for a plugin from the provided config.\n *\n * @param config - The database config object\n * @param pluginId - The plugin ID to compute config for\n * @param prefix - The database name prefix (e.g. 'backstage_plugin_')\n * @returns All computed configuration values for the plugin\n */\nexport function computePgPluginConfig(\n config: Config,\n pluginId: string,\n prefix: string,\n schemaPrefix: string = '',\n): PgPluginDatabaseConfig {\n // Client type\n const pluginClient = config.getOptionalString(\n `${pluginPath(pluginId)}.client`,\n );\n const baseClient = config.getString('client');\n const client = pluginClient ?? baseClient;\n const clientOverridden = client !== baseClient;\n\n // Role\n const role =\n config.getOptionalString(`${pluginPath(pluginId)}.role`) ??\n config.getOptionalString('role');\n\n // Additional knex config\n const pluginKnexConfig = config\n .getOptionalConfig(`${pluginPath(pluginId)}.knexConfig`)\n ?.get<JsonObject>();\n const baseKnexConfig = config\n .getOptionalConfig('knexConfig')\n ?.get<JsonObject>();\n const additionalKnexConfig = merge(baseKnexConfig, pluginKnexConfig);\n\n // Ensure exists flags\n const baseEnsureExists = config.getOptionalBoolean('ensureExists') ?? true;\n const ensureExists =\n config.getOptionalBoolean(`${pluginPath(pluginId)}.ensureExists`) ??\n baseEnsureExists;\n\n const baseEnsureSchemaExists =\n config.getOptionalBoolean('ensureSchemaExists') ?? false;\n const ensureSchemaExists =\n config.getOptionalBoolean(\n `${pluginPath(pluginId)}.getEnsureSchemaExistsConfig`,\n ) ?? baseEnsureSchemaExists;\n\n // Plugin division mode\n const pluginDivisionMode =\n config.getOptionalString('pluginDivisionMode') ?? 'database';\n\n // Connection config\n let baseConnection = normalizeConnection(config.get('connection'));\n\n // Databases cannot be shared unless the `pluginDivisionMode` is set to `schema`.\n // The `database` property from the base connection is omitted unless\n // `pluginDivisionMode` is set to `schema`.\n if (pluginDivisionMode !== 'schema') {\n baseConnection = omit(baseConnection, 'database');\n }\n\n // Get and normalize optional plugin specific database connection\n const pluginConnection = normalizeConnection(\n config.getOptional(`${pluginPath(pluginId)}.connection`),\n );\n\n (\n baseConnection as Knex.PgConnectionConfig\n ).application_name ||= `backstage_plugin_${pluginId}`;\n\n const connection = {\n // Include base connection if client type has not been overridden\n ...(clientOverridden ? {} : baseConnection),\n ...pluginConnection,\n } as Knex.PgConnectionConfig;\n\n // Database name\n const connectionDatabaseName = (connection as Knex.ConnectionConfig)\n ?.database;\n let databaseName: string | undefined;\n\n if (pluginDivisionMode === 'schema') {\n // `pluginDivisionMode` as `schema` should use overridden databaseName if supplied\n // or fallback to default knex database\n databaseName = connectionDatabaseName;\n } else {\n // All other supported databases should fallback to an auto-prefixed name\n databaseName = connectionDatabaseName ?? `${prefix}${pluginId}`;\n }\n\n // Database client overrides\n let databaseClientOverrides: Knex.Config = {};\n let schemaName: string | undefined;\n\n if (databaseName) {\n databaseClientOverrides = { connection: { database: databaseName } };\n }\n if (pluginDivisionMode === 'schema') {\n schemaName = `${schemaPrefix}${pluginId}`;\n\n if (Buffer.byteLength(schemaName, 'utf8') > 63) {\n throw new Error(\n `PostgreSQL schema name \"${schemaName}\" exceeds the 63-byte limit. ` +\n `Consider using a shorter schemaPrefix (current: \"${schemaPrefix}\") or ` +\n `plugin ID (current: \"${pluginId}\").`,\n );\n }\n\n databaseClientOverrides = mergeDatabaseConfig({}, databaseClientOverrides, {\n searchPath: [schemaName],\n });\n }\n\n // Full knex config for plugin\n const knexConfig: Knex.Config = {\n ...additionalKnexConfig,\n client,\n connection,\n ...(role && { role }),\n };\n\n return {\n client,\n clientOverridden,\n role,\n additionalKnexConfig,\n ensureExists,\n ensureSchemaExists,\n pluginDivisionMode,\n connection,\n databaseName,\n schemaName,\n databaseClientOverrides,\n knexConfig,\n };\n}\n\nexport class PgConnector implements Connector {\n private readonly config: Config;\n private readonly prefix: string;\n private readonly schemaPrefix: string;\n private readonly databaseEnsureCache = new Map<string, Promise<void>>();\n private readonly customEnsureDatabaseExists?: typeof ensurePgDatabaseExists;\n private readonly databaseAdminPool: PgAdminPool;\n private readonly schemaAdminPool: PgAdminPool;\n\n constructor(\n config: Config,\n prefix: string,\n schemaPrefix: string,\n options: {\n ensureDatabaseExists?: typeof ensurePgDatabaseExists;\n createAdminClient?: (overrides: Knex.Config) => Promise<Knex>;\n adminPoolIdleTimeoutMillis?: number;\n } = {},\n ) {\n this.config = config;\n this.prefix = prefix;\n this.schemaPrefix = schemaPrefix;\n this.customEnsureDatabaseExists = options.ensureDatabaseExists;\n\n const createAdminClient =\n options.createAdminClient ??\n ((overrides: Knex.Config) =>\n createPgDatabaseClient(this.config, overrides));\n const idleTimeoutMillis = options.adminPoolIdleTimeoutMillis ?? 10_000;\n this.databaseAdminPool = new PgAdminPool(\n () => createAdminClient(PG_DATABASE_ADMIN_OVERRIDES),\n idleTimeoutMillis,\n );\n this.schemaAdminPool = new PgAdminPool(\n () => createAdminClient(PG_SCHEMA_ADMIN_OVERRIDES),\n idleTimeoutMillis,\n );\n }\n\n private async ensureDatabase(databaseName: string): Promise<void> {\n let promise = this.databaseEnsureCache.get(databaseName);\n if (!promise) {\n promise = this.customEnsureDatabaseExists\n ? this.customEnsureDatabaseExists(this.config, databaseName)\n : retryPgAdminOperation(() =>\n ddlLimiter(() =>\n this.runAdminOperation(this.databaseAdminPool, admin =>\n ensurePgDatabase(admin, databaseName),\n ),\n ),\n );\n this.databaseEnsureCache.set(databaseName, promise);\n }\n\n try {\n await promise;\n } catch (error) {\n if (this.databaseEnsureCache.get(databaseName) === promise) {\n this.databaseEnsureCache.delete(databaseName);\n }\n throw error;\n }\n }\n\n private async runAdminOperation<T>(\n pool: PgAdminPool,\n operation: (client: Knex) => Promise<T>,\n ): Promise<T> {\n try {\n return await pool.run(operation);\n } catch (error) {\n await pool.invalidate().catch(() => {});\n throw error;\n }\n }\n\n async shutdown(): Promise<void> {\n const results = await Promise.allSettled([\n this.databaseAdminPool.shutdown(),\n this.schemaAdminPool.shutdown(),\n ]);\n const errors = results\n .filter(\n (result): result is PromiseRejectedResult =>\n result.status === 'rejected',\n )\n .map(result => result.reason);\n if (errors.length === 1) {\n throw errors[0];\n }\n if (errors.length > 1) {\n throw new AggregateError(\n errors,\n 'Failed to shut down PostgreSQL admin pools',\n );\n }\n }\n\n async getClient(\n pluginId: string,\n _deps: {\n logger: LoggerService;\n lifecycle: LifecycleService;\n },\n ): Promise<Knex> {\n const pluginDbConfig = computePgPluginConfig(\n this.config,\n pluginId,\n this.prefix,\n this.schemaPrefix,\n );\n\n if (pluginDbConfig.databaseName && pluginDbConfig.ensureExists) {\n try {\n await this.ensureDatabase(pluginDbConfig.databaseName);\n } catch (error) {\n throw new Error(\n `Failed to connect to the database to make sure that '${pluginDbConfig.databaseName}' exists, ${error}`,\n );\n }\n }\n\n if (pluginDbConfig.pluginDivisionMode === 'schema') {\n if (pluginDbConfig.ensureSchemaExists || pluginDbConfig.ensureExists) {\n try {\n await ddlLimiter(() =>\n this.runAdminOperation(this.schemaAdminPool, admin =>\n ensurePgSchema(\n admin,\n this.config.getOptionalString('role'),\n pluginDbConfig.schemaName!,\n ),\n ),\n );\n } catch (error) {\n throw new Error(\n `Failed to connect to the database to make sure that schema for plugin '${pluginId}' exists, ${error}`,\n );\n }\n }\n }\n\n const client = createPgDatabaseClient(\n this.config,\n mergeDatabaseConfig(\n pluginDbConfig.knexConfig,\n pluginDbConfig.databaseClientOverrides,\n ),\n );\n\n return client;\n }\n}\n"],"names":["limiterFactory","knexFactory","format","config","mergeDatabaseConfig","ConfigReader","omit","durationToMilliseconds","readDurationFromConfig","ForwardedError","merge"],"mappings":";;;;;;;;;;;;;;;;;AAsCA,MAAM,UAAA,GAAaA,gCAAe,CAAC,CAAA;AAEnC,MAAM,4BAAA,GAA+B,CAAA;AACrC,MAAM,oCAAA,GAAuC,GAAA;AAC7C,MAAM,o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AAc;AACpE,QAAA,IAAI;AACF,UAAA,MAAM,UAAA;AAAA,YAAW,MACf,IAAA,CAAK,iBAAA;AAAA,cAAkB,IAAA,CAAK,eAAA;AAAA,cAAiB,CAAA,KAAA,KAC3C,cAAA;AAAA,gBACE,KAAA;AAAA,gBACA,IAAA,CAAK,MAAA,CAAO,iBAAA,CAAkB,MAAM,CAAA;AAAA,gBACpC,cAAA,CAAe;AAAA;AACjB;AACF,WACF;AAAA,QACF,SAAS,KAAA,EAAO;AACd,UAAA,MAAM,IAAI,KAAA;AAAA,YACR,CAAA,uEAAA,EAA0E,QAAQ,CAAA,UAAA,EAAa,KAAK,CAAA;AAAA,WACtG;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAEA,IAAA,MAAM,MAAA,GAAS,sBAAA;AAAA,MACb,IAAA,CAAK,MAAA;AAAA,MACLA,uCAAA;AAAA,QACE,cAAA,CAAe,UAAA;AAAA,QACf,cAAA,CAAe;AAAA;AACjB,KACF;AAEA,IAAA,OAAO,MAAA;AAAA,EACT;AACF;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"postgres.cjs.js","sources":["../../../../src/entrypoints/database/connectors/postgres.ts"],"sourcesContent":["/*\n * Copyright 2020 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 { LifecycleService, LoggerService } from '@backstage/backend-plugin-api';\nimport {\n Config,\n ConfigReader,\n readDurationFromConfig,\n} from '@backstage/config';\nimport { ForwardedError } from '@backstage/errors';\nimport {\n durationToMilliseconds,\n HumanDuration,\n JsonObject,\n} from '@backstage/types';\nimport knexFactory, { Knex } from 'knex';\nimport { merge, omit } from 'lodash';\nimport limiterFactory from 'p-limit';\nimport { Client } from 'pg';\nimport { Connector } from '../types';\nimport { mergeDatabaseConfig } from './mergeDatabaseConfig';\nimport format from 'pg-format';\nimport { TokenCredential } from '@azure/identity';\n\n// Limits the number of concurrent DDL operations to 1\nconst ddlLimiter = limiterFactory(1);\n\nconst cloudSqlConnectorMaxAttempts = 3;\nconst cloudSqlConnectorInitialRetryDelayMs = 200;\nconst cloudSqlConnectorRetryableErrorCodes = new Set([\n 'EAI_AGAIN',\n 'ECONNREFUSED',\n 'ECONNRESET',\n 'EHOSTUNREACH',\n 'ENETUNREACH',\n 'EPIPE',\n 'ETIMEDOUT',\n 'UND_ERR_CONNECT_TIMEOUT',\n]);\n\nasync function retryWithExponentialBackoff<T>(\n operation: () => Promise<T>,\n options: {\n maxAttempts: number;\n initialDelayMs: number;\n shouldRetry: (error: unknown) => boolean;\n },\n): Promise<T> {\n for (let attempt = 1; ; attempt++) {\n try {\n return await operation();\n } catch (error) {\n if (attempt >= options.maxAttempts || !options.shouldRetry(error)) {\n throw error;\n }\n const maxDelay = options.initialDelayMs * 2 ** (attempt - 1);\n const delay = Math.random() * maxDelay;\n await new Promise(resolve => setTimeout(resolve, delay));\n }\n }\n}\n\nfunction isCloudSqlConnectorRetryableError(error: unknown): boolean {\n let current = error;\n const seen = new Set<unknown>();\n\n while (current && typeof current === 'object' && !seen.has(current)) {\n seen.add(current);\n const errorRecord = current as Record<string, unknown>;\n const code = errorRecord.code;\n if (\n typeof code === 'string' &&\n cloudSqlConnectorRetryableErrorCodes.has(code)\n ) {\n return true;\n }\n\n let status = errorRecord.status;\n if (typeof status !== 'number') {\n status = errorRecord.statusCode;\n }\n if (typeof status !== 'number') {\n const response = errorRecord.response;\n status =\n response && typeof response === 'object'\n ? (response as Record<string, unknown>).status\n : undefined;\n }\n if (\n typeof status === 'number' &&\n (status === 408 || status === 429 || (status >= 500 && status <= 599))\n ) {\n return true;\n }\n\n current = errorRecord.cause;\n }\n\n return false;\n}\n\nexport class PgAdminPool {\n private client?: Promise<Knex>;\n private destruction?: Promise<void>;\n private readonly destructionErrors: unknown[] = [];\n private idleTimer?: NodeJS.Timeout;\n private readonly operations = new Set<Promise<unknown>>();\n private isShutdown = false;\n\n constructor(\n private readonly createClient: () => Promise<Knex>,\n private readonly idleTimeoutMillis: number,\n ) {}\n\n async run<T>(operation: (client: Knex) => Promise<T> | T): Promise<T> {\n if (this.isShutdown) {\n throw new Error('PostgreSQL admin pool is shut down');\n }\n\n clearTimeout(this.idleTimer);\n this.idleTimer = undefined;\n\n const operationPromise = this.runOperation(operation);\n this.operations.add(operationPromise);\n try {\n return await operationPromise;\n } finally {\n this.operations.delete(operationPromise);\n this.scheduleIdleDestroy();\n }\n }\n\n async shutdown(): Promise<void> {\n this.isShutdown = true;\n clearTimeout(this.idleTimer);\n this.idleTimer = undefined;\n\n await Promise.allSettled(this.operations);\n await this.destroyClient().catch(() => {});\n if (this.destructionErrors.length > 0) {\n throw new AggregateError(\n this.destructionErrors,\n 'Failed to destroy PostgreSQL admin pool clients',\n );\n }\n }\n\n async invalidate(): Promise<void> {\n clearTimeout(this.idleTimer);\n this.idleTimer = undefined;\n\n await Promise.allSettled(this.operations);\n await this.destroyClient();\n }\n\n private async runOperation<T>(\n operation: (client: Knex) => Promise<T> | T,\n ): Promise<T> {\n if (this.destruction) {\n await this.destruction;\n }\n if (this.isShutdown) {\n throw new Error('PostgreSQL admin pool is shut down');\n }\n\n let clientPromise = this.client;\n if (!clientPromise) {\n clientPromise = this.createClient();\n this.client = clientPromise;\n void clientPromise.catch(() => {\n if (this.client === clientPromise) {\n this.client = undefined;\n }\n });\n }\n return operation(await clientPromise);\n }\n\n private scheduleIdleDestroy(): void {\n if (this.isShutdown || this.operations.size > 0) {\n return;\n }\n\n const timer = setTimeout(() => {\n if (this.idleTimer === timer) {\n this.idleTimer = undefined;\n void this.destroyClient().catch(() => {});\n }\n }, this.idleTimeoutMillis);\n timer.unref();\n this.idleTimer = timer;\n }\n\n private destroyClient(): Promise<void> {\n if (this.destruction) {\n return this.destruction;\n }\n\n const clientPromise = this.client;\n this.client = undefined;\n if (!clientPromise) {\n return Promise.resolve();\n }\n\n const destruction = clientPromise.then(\n client => client.destroy(),\n () => undefined,\n );\n this.destruction = destruction;\n void destruction.then(\n () => {\n if (this.destruction === destruction) {\n this.destruction = undefined;\n }\n },\n error => {\n if (this.destruction === destruction) {\n this.destruction = undefined;\n this.destructionErrors.push(error);\n }\n },\n );\n return destruction;\n }\n}\n\n/**\n * Creates a knex postgres database connection\n *\n * @param dbConfig - The database config\n * @param overrides - Additional options to merge with the config\n */\nexport async function createPgDatabaseClient(\n dbConfig: Config,\n overrides?: Knex.Config,\n) {\n const knexConfig = await buildPgDatabaseConfig(dbConfig, overrides);\n const database = knexFactory(knexConfig);\n\n const role = dbConfig.getOptionalString('role');\n\n if (role) {\n database.client.pool.on(\n 'createSuccess',\n async (_event: number, pgClient: Client) => {\n const query = format('SET ROLE %I', role);\n await pgClient.query(query);\n },\n );\n }\n return database;\n}\n\n/**\n * Builds a knex postgres database connection\n *\n * @param dbConfig - The database config\n * @param overrides - Additional options to merge with the config\n */\nexport async function buildPgDatabaseConfig(\n dbConfig: Config,\n overrides?: Knex.Config,\n) {\n const config = mergeDatabaseConfig(\n { pool: { min: 0 } },\n dbConfig.get(),\n {\n connection: getPgConnectionConfig(dbConfig, !!overrides),\n useNullAsDefault: true,\n },\n overrides,\n );\n const mergedConfigReader = new ConfigReader(config);\n\n if (config.connection.type === 'default' || !config.connection.type) {\n const connectionValue = config.connection;\n const sanitizedConnection =\n typeof connectionValue === 'string' || connectionValue instanceof String\n ? connectionValue\n : // connection is an object, omit config-only props\n omit(connectionValue as Record<string, unknown>, [\n 'type',\n 'instance',\n 'tokenCredential',\n ]);\n\n return {\n ...config,\n connection: sanitizedConnection,\n };\n }\n\n switch (config.connection.type) {\n case 'azure':\n return buildAzurePgConfig(mergedConfigReader);\n case 'cloudsql':\n return buildCloudSqlConfig(mergedConfigReader);\n case 'rds':\n return buildRdsPgConfig(mergedConfigReader);\n default:\n throw new Error(`Unknown connection type: ${config.connection.type}`);\n }\n}\n\n/* Note: the following type definition is intentionally duplicated in\n * /packages/backend-defaults/config.d.ts so the clientSecret property\n * can be annotated with \"@visibility secret\" there.\n */\nexport type AzureTokenCredentialConfig = {\n /**\n * How early before an access token expires to refresh it with a new one.\n * Defaults to 5 minutes\n * Supported formats:\n * - A string in the format of '1d', '2 seconds' etc. as supported by the `ms`\n * library.\n * - A standard ISO formatted duration string, e.g. 'P2DT6H' or 'PT1M'.\n * - An object with individual units (in plural) as keys, e.g. `{ days: 2, hours: 6 }`.\n */\n tokenRenewableOffsetTime?: string | HumanDuration;\n /**\n * The client ID of a user-assigned managed identity.\n * If not provided, the system-assigned managed identity is used.\n */\n clientId?: string;\n clientSecret?: string;\n tenantId?: string;\n};\n\nexport async function buildAzurePgConfig(config: Config): Promise<Knex.Config> {\n const {\n DefaultAzureCredential,\n ManagedIdentityCredential,\n ClientSecretCredential,\n } = require('@azure/identity');\n\n const tokenConfig = config.getOptionalConfig('connection.tokenCredential');\n\n const tokenRenewableOffsetTime = durationToMilliseconds(\n tokenConfig?.has('tokenRenewableOffsetTime')\n ? readDurationFromConfig(tokenConfig, { key: 'tokenRenewableOffsetTime' })\n : { minutes: 5 },\n );\n\n const clientId = tokenConfig?.getOptionalString('clientId');\n const tenantId = tokenConfig?.getOptionalString('tenantId');\n const clientSecret = tokenConfig?.getOptionalString('clientSecret');\n let credential: TokenCredential;\n\n /**\n * Determine which TokenCredential to use based on provided config\n * 1. If clientId, tenantId and clientSecret are provided, use ClientSecretCredential\n * 2. If only clientId is provided, use ManagedIdentityCredential with user-assigned identity\n * 3. Otherwise, use DefaultAzureCredential (which may use system-assigned identity among other methods)\n */\n if (clientId && tenantId && clientSecret) {\n credential = new ClientSecretCredential(tenantId, clientId, clientSecret);\n } else if (clientId) {\n credential = new ManagedIdentityCredential(clientId);\n } else {\n credential = new DefaultAzureCredential();\n }\n\n const rawConfig = config.get() as Record<string, unknown>;\n\n const normalized = normalizeConnection(rawConfig.connection as any);\n const sanitizedConnection = omit(normalized, [\n 'type',\n 'instance',\n 'tokenCredential',\n ]) as Partial<Knex.StaticConnectionConfig>;\n\n async function getConnectionConfig() {\n const token = await credential.getToken(\n 'https://ossrdbms-aad.database.windows.net/.default',\n );\n\n if (!token) {\n throw new Error(\n 'Failed to acquire Azure access token for database authentication',\n );\n }\n\n const connectionConfig = {\n ...sanitizedConnection,\n password: token.token,\n expirationChecker: () =>\n /* return true if the token is within the renewable offset time */\n token.expiresOnTimestamp - tokenRenewableOffsetTime <= Date.now(),\n };\n\n return connectionConfig;\n }\n\n return {\n ...(rawConfig as Record<string, unknown>),\n connection: getConnectionConfig,\n };\n}\n\n/**\n * Builds a PostgreSQL configuration for Cloud SQL.\n *\n * Transient failures during connector initialization are retried up to three\n * times with jittered exponential backoff. Configuration and authorization\n * failures are returned immediately.\n */\nexport async function buildCloudSqlConfig(\n config: Config,\n): Promise<Knex.Config> {\n const client = config.getOptionalString('client');\n\n if (client && client !== 'pg') {\n throw new Error('Cloud SQL only supports the pg client');\n }\n\n const instance = config.getOptionalString('connection.instance');\n if (!instance) {\n throw new Error('Missing instance connection name for Cloud SQL');\n }\n\n const {\n Connector: CloudSqlConnector,\n IpAddressTypes,\n AuthTypes,\n } = require('@google-cloud/cloud-sql-connector') as typeof import('@google-cloud/cloud-sql-connector');\n\n type IpType = (typeof IpAddressTypes)[keyof typeof IpAddressTypes];\n const ipTypeRaw = config.getOptionalString('connection.ipAddressType');\n\n let ipType: IpType | undefined;\n if (ipTypeRaw !== undefined) {\n if (\n !(Object.values(IpAddressTypes) as Array<string | number>).includes(\n ipTypeRaw as any,\n )\n ) {\n throw new Error(\n `Invalid connection.ipAddressType: ${ipTypeRaw}; valid values: ${Object.values(\n IpAddressTypes,\n ).join(', ')}`,\n );\n }\n ipType = ipTypeRaw as unknown as IpType;\n }\n\n /**\n * Retry only transient connector initialization failures. A fresh connector\n * is required because a failed initialization may be cached by the client.\n */\n const clientOpts = await retryWithExponentialBackoff(\n async () => {\n const connector = new CloudSqlConnector();\n return connector.getOptions({\n instanceConnectionName: instance,\n ipType: ipType ?? IpAddressTypes.PUBLIC,\n authType: AuthTypes.IAM,\n });\n },\n {\n maxAttempts: cloudSqlConnectorMaxAttempts,\n initialDelayMs: cloudSqlConnectorInitialRetryDelayMs,\n shouldRetry: isCloudSqlConnectorRetryableError,\n },\n );\n\n const rawConfig = config.get() as Record<string, unknown>;\n const normalized = normalizeConnection(rawConfig.connection as any);\n const sanitizedConnection = omit(normalized, [\n 'type',\n 'instance',\n ]) as Partial<Knex.StaticConnectionConfig>;\n\n return {\n ...(rawConfig as Record<string, unknown>),\n client: 'pg',\n connection: {\n ...sanitizedConnection,\n ...clientOpts,\n },\n };\n}\n\nexport async function buildRdsPgConfig(config: Config): Promise<Knex.Config> {\n const { Signer } =\n require('@aws-sdk/rds-signer') as typeof import('@aws-sdk/rds-signer');\n const { fromNodeProviderChain } =\n require('@aws-sdk/credential-providers') as typeof import('@aws-sdk/credential-providers');\n\n let hostname: string;\n let port: number;\n let username: string;\n try {\n hostname = config.getString('connection.host');\n port = config.getNumber('connection.port');\n username = config.getString('connection.user');\n } catch (err) {\n throw new ForwardedError(\n 'AWS RDS IAM auth: missing required database connection config — make sure connection.host, connection.port, and connection.user are set and any environment variables they reference are set',\n err,\n );\n }\n const region =\n config.getOptionalString('connection.region') ??\n process.env.AWS_REGION ??\n process.env.AWS_DEFAULT_REGION;\n if (!region) {\n throw new Error(\n 'Missing region for AWS RDS IAM auth: set connection.region or the AWS_REGION environment variable',\n );\n }\n\n const rawConfig = config.get() as Record<string, unknown>;\n const sanitizedConnection = omit(\n config.get('connection') as Record<string, unknown>,\n ['type', 'region'],\n ) as Partial<Knex.StaticConnectionConfig>;\n\n const credentialsProvider = fromNodeProviderChain();\n\n // A token cannot outlive the credentials used to sign it. Renew the cached\n // connection settings one minute before either expiration.\n const tokenTtlMs = 15 * 60 * 1000;\n const renewalOffsetMs = 60 * 1000;\n\n async function getConnectionConfig() {\n try {\n let credentials = await credentialsProvider();\n // The SDK may return its cached credentials while refreshing them in the\n // background. Wait for a refresh if they are already inside our margin.\n if (\n credentials.expiration &&\n credentials.expiration.getTime() <= Date.now() + renewalOffsetMs\n ) {\n credentials = await credentialsProvider({ forceRefresh: true });\n }\n const signer = new Signer({\n hostname,\n port,\n username,\n region,\n credentials,\n });\n const tokenIssuedAt = Date.now();\n const password = await signer.getAuthToken();\n const tokenExpiration =\n Math.min(\n tokenIssuedAt + tokenTtlMs,\n credentials.expiration?.getTime() ?? Infinity,\n ) - renewalOffsetMs;\n return {\n ...sanitizedConnection,\n password,\n expirationChecker: () => tokenExpiration <= Date.now(),\n };\n } catch (err) {\n throw new ForwardedError(\n `AWS RDS IAM auth token acquisition failed for ${username}@${hostname}:${port}`,\n err,\n );\n }\n }\n\n return {\n ...(rawConfig as Record<string, unknown>),\n connection: getConnectionConfig,\n };\n}\n\n/**\n * Gets the postgres connection config\n *\n * @param dbConfig - The database config\n * @param parseConnectionString - Flag to explicitly control connection string parsing\n */\nexport function getPgConnectionConfig(\n dbConfig: Config,\n parseConnectionString?: boolean,\n): Knex.PgConnectionConfig | string {\n const connection = dbConfig.get('connection') as any;\n const isConnectionString =\n typeof connection === 'string' || connection instanceof String;\n const autoParse = typeof parseConnectionString !== 'boolean';\n\n const shouldParseConnectionString = autoParse\n ? isConnectionString\n : parseConnectionString && isConnectionString;\n\n return shouldParseConnectionString\n ? parsePgConnectionString(connection as string)\n : connection;\n}\n\n/**\n * Parses a connection string using pg-connection-string\n *\n * @param connectionString - The postgres connection string\n */\nexport function parsePgConnectionString(connectionString: string) {\n const parse = requirePgConnectionString();\n return parse(connectionString);\n}\n\nfunction requirePgConnectionString() {\n try {\n return require('pg-connection-string').parse;\n } catch (e) {\n throw new ForwardedError(\"Postgres: Install 'pg-connection-string'\", e);\n }\n}\n\nconst PG_DATABASE_ADMIN_OVERRIDES: Knex.Config = {\n connection: { database: 'postgres' },\n pool: { min: 0, max: 1, acquireTimeoutMillis: 10000 },\n};\n\nconst PG_SCHEMA_ADMIN_OVERRIDES: Knex.Config = {\n pool: { min: 0, max: 1, acquireTimeoutMillis: 10000 },\n};\n\n/**\n * Creates the missing Postgres database if it does not exist\n *\n * @param dbConfig - The database config\n * @param databases - The name of the databases to create\n */\nexport async function ensurePgDatabaseExists(\n dbConfig: Config,\n ...databases: Array<string>\n) {\n await Promise.all(\n databases.map(async database => {\n return retryPgAdminOperation(() =>\n ddlLimiter(async () => {\n const admin = await createPgDatabaseClient(\n dbConfig,\n PG_DATABASE_ADMIN_OVERRIDES,\n );\n try {\n await ensurePgDatabase(admin, database);\n } finally {\n await admin.destroy();\n }\n }),\n );\n }),\n );\n}\n\nasync function ensurePgDatabase(admin: Knex, database: string): Promise<void> {\n const result = await admin\n .from('pg_database')\n .where('datname', database)\n .count<Record<string, { count: string }>>();\n\n if (parseInt(result[0].count, 10) === 0) {\n await admin.raw(`CREATE DATABASE ??`, [database]);\n }\n}\n\nasync function retryPgAdminOperation(\n operation: () => Promise<void>,\n): Promise<void> {\n // For initial setup we use a smaller timeout but several retries. Given that this\n // is a separate connection pool we should never really run into issues with connection\n // acquisition timeouts, but we do anyway. This might be a bug in knex or some other dependency.\n const maxAttempts = 3;\n for (let attempt = 1; ; attempt++) {\n try {\n return await operation();\n } catch (error) {\n if (attempt >= maxAttempts) {\n throw error;\n }\n await new Promise(resolve => setTimeout(resolve, 100));\n }\n }\n}\n\nasync function ensurePgSchema(\n admin: Knex,\n role: string | undefined,\n schema: string,\n): Promise<void> {\n if (role) {\n await admin.raw(`CREATE SCHEMA IF NOT EXISTS ?? AUTHORIZATION ??`, [\n schema,\n role,\n ]);\n } else {\n await admin.raw(`CREATE SCHEMA IF NOT EXISTS ??`, [schema]);\n }\n}\n\n/**\n * Creates the missing Postgres schema if it does not exist\n *\n * @param dbConfig - The database config\n * @param schemas - The name of the schemas to create\n */\nexport async function ensurePgSchemaExists(\n dbConfig: Config,\n ...schemas: Array<string>\n): Promise<void> {\n const admin = await createPgDatabaseClient(dbConfig);\n const role = dbConfig.getOptionalString('role');\n\n try {\n await Promise.all(\n schemas.map(schema =>\n ddlLimiter(() => ensurePgSchema(admin, role, schema)),\n ),\n );\n } finally {\n await admin.destroy();\n }\n}\n\n/**\n * Drops the Postgres databases.\n *\n * @param dbConfig - The database config\n * @param databases - The name of the databases to drop\n */\nexport async function dropPgDatabase(\n dbConfig: Config,\n ...databases: Array<string>\n) {\n const admin = await createPgDatabaseClient(dbConfig);\n try {\n await Promise.all(\n databases.map(async database => {\n await ddlLimiter(() => admin.raw(`DROP DATABASE ??`, [database]));\n }),\n );\n } finally {\n await admin.destroy();\n }\n}\n\n/**\n * Provides a config lookup path for a plugin's config block.\n */\nfunction pluginPath(pluginId: string): string {\n return `plugin.${pluginId}`;\n}\n\nfunction normalizeConnection(\n connection: Knex.StaticConnectionConfig | JsonObject | string | undefined,\n): Partial<Knex.StaticConnectionConfig> {\n if (typeof connection === 'undefined' || connection === null) {\n return {};\n }\n\n return typeof connection === 'string' || connection instanceof String\n ? parsePgConnectionString(connection as string)\n : connection;\n}\n\n/**\n * The computed configuration for a plugin's postgres database connection.\n */\nexport interface PgPluginDatabaseConfig {\n /** The database client type (e.g. 'pg') */\n client: string;\n /** Whether the client type was overridden at the plugin level */\n clientOverridden: boolean;\n /** The optional role to set on connections */\n role: string | undefined;\n /** Additional knex configuration merged from base and plugin config */\n additionalKnexConfig: JsonObject | undefined;\n /** Whether to ensure the database exists */\n ensureExists: boolean;\n /** Whether to ensure the schema exists */\n ensureSchemaExists: boolean;\n /** The plugin division mode ('database' or 'schema') */\n pluginDivisionMode: string;\n /** The connection configuration */\n connection: Knex.PgConnectionConfig;\n /** The database name, if any */\n databaseName: string | undefined;\n /** The schema name, if using schema division mode */\n schemaName: string | undefined;\n /** Database client overrides including schema overrides if applicable */\n databaseClientOverrides: Knex.Config;\n /** The full knex config for the plugin */\n knexConfig: Knex.Config;\n}\n\n/**\n * Computes all postgres database configuration for a plugin from the provided config.\n *\n * @param config - The database config object\n * @param pluginId - The plugin ID to compute config for\n * @param prefix - The database name prefix (e.g. 'backstage_plugin_')\n * @returns All computed configuration values for the plugin\n */\nexport function computePgPluginConfig(\n config: Config,\n pluginId: string,\n prefix: string,\n schemaPrefix: string = '',\n): PgPluginDatabaseConfig {\n // Client type\n const pluginClient = config.getOptionalString(\n `${pluginPath(pluginId)}.client`,\n );\n const baseClient = config.getString('client');\n const client = pluginClient ?? baseClient;\n const clientOverridden = client !== baseClient;\n\n // Role\n const role =\n config.getOptionalString(`${pluginPath(pluginId)}.role`) ??\n config.getOptionalString('role');\n\n // Additional knex config\n const pluginKnexConfig = config\n .getOptionalConfig(`${pluginPath(pluginId)}.knexConfig`)\n ?.get<JsonObject>();\n const baseKnexConfig = config\n .getOptionalConfig('knexConfig')\n ?.get<JsonObject>();\n const additionalKnexConfig = merge(baseKnexConfig, pluginKnexConfig);\n\n // Ensure exists flags\n const baseEnsureExists = config.getOptionalBoolean('ensureExists') ?? true;\n const ensureExists =\n config.getOptionalBoolean(`${pluginPath(pluginId)}.ensureExists`) ??\n baseEnsureExists;\n\n const baseEnsureSchemaExists =\n config.getOptionalBoolean('ensureSchemaExists') ?? false;\n const ensureSchemaExists =\n config.getOptionalBoolean(\n `${pluginPath(pluginId)}.getEnsureSchemaExistsConfig`,\n ) ?? baseEnsureSchemaExists;\n\n // Plugin division mode\n const pluginDivisionMode =\n config.getOptionalString('pluginDivisionMode') ?? 'database';\n\n // Connection config\n let baseConnection = normalizeConnection(config.get('connection'));\n\n // Databases cannot be shared unless the `pluginDivisionMode` is set to `schema`.\n // The `database` property from the base connection is omitted unless\n // `pluginDivisionMode` is set to `schema`.\n if (pluginDivisionMode !== 'schema') {\n baseConnection = omit(baseConnection, 'database');\n }\n\n // Get and normalize optional plugin specific database connection\n const pluginConnection = normalizeConnection(\n config.getOptional(`${pluginPath(pluginId)}.connection`),\n );\n\n (\n baseConnection as Knex.PgConnectionConfig\n ).application_name ||= `backstage_plugin_${pluginId}`;\n\n const connection = {\n // Include base connection if client type has not been overridden\n ...(clientOverridden ? {} : baseConnection),\n ...pluginConnection,\n } as Knex.PgConnectionConfig;\n\n // Database name\n const connectionDatabaseName = (connection as Knex.ConnectionConfig)\n ?.database;\n let databaseName: string | undefined;\n\n if (pluginDivisionMode === 'schema') {\n // `pluginDivisionMode` as `schema` should use overridden databaseName if supplied\n // or fallback to default knex database\n databaseName = connectionDatabaseName;\n } else {\n // All other supported databases should fallback to an auto-prefixed name\n databaseName = connectionDatabaseName ?? `${prefix}${pluginId}`;\n }\n\n // Database client overrides\n let databaseClientOverrides: Knex.Config = {};\n let schemaName: string | undefined;\n\n if (databaseName) {\n databaseClientOverrides = { connection: { database: databaseName } };\n }\n if (pluginDivisionMode === 'schema') {\n schemaName = `${schemaPrefix}${pluginId}`;\n\n if (Buffer.byteLength(schemaName, 'utf8') > 63) {\n throw new Error(\n `PostgreSQL schema name \"${schemaName}\" exceeds the 63-byte limit. ` +\n `Consider using a shorter schemaPrefix (current: \"${schemaPrefix}\") or ` +\n `plugin ID (current: \"${pluginId}\").`,\n );\n }\n\n databaseClientOverrides = mergeDatabaseConfig({}, databaseClientOverrides, {\n searchPath: [schemaName],\n });\n }\n\n // Full knex config for plugin\n const knexConfig: Knex.Config = {\n ...additionalKnexConfig,\n client,\n connection,\n ...(role && { role }),\n };\n\n return {\n client,\n clientOverridden,\n role,\n additionalKnexConfig,\n ensureExists,\n ensureSchemaExists,\n pluginDivisionMode,\n connection,\n databaseName,\n schemaName,\n databaseClientOverrides,\n knexConfig,\n };\n}\n\nexport class PgConnector implements Connector {\n private readonly config: Config;\n private readonly prefix: string;\n private readonly schemaPrefix: string;\n private readonly databaseEnsureCache = new Map<string, Promise<void>>();\n private readonly customEnsureDatabaseExists?: typeof ensurePgDatabaseExists;\n private readonly databaseAdminPool: PgAdminPool;\n private readonly schemaAdminPool: PgAdminPool;\n\n constructor(\n config: Config,\n prefix: string,\n schemaPrefix: string,\n options: {\n ensureDatabaseExists?: typeof ensurePgDatabaseExists;\n createAdminClient?: (overrides: Knex.Config) => Promise<Knex>;\n adminPoolIdleTimeoutMillis?: number;\n } = {},\n ) {\n this.config = config;\n this.prefix = prefix;\n this.schemaPrefix = schemaPrefix;\n this.customEnsureDatabaseExists = options.ensureDatabaseExists;\n\n const createAdminClient =\n options.createAdminClient ??\n ((overrides: Knex.Config) =>\n createPgDatabaseClient(this.config, overrides));\n const idleTimeoutMillis = options.adminPoolIdleTimeoutMillis ?? 10_000;\n this.databaseAdminPool = new PgAdminPool(\n () => createAdminClient(PG_DATABASE_ADMIN_OVERRIDES),\n idleTimeoutMillis,\n );\n this.schemaAdminPool = new PgAdminPool(\n () => createAdminClient(PG_SCHEMA_ADMIN_OVERRIDES),\n idleTimeoutMillis,\n );\n }\n\n private async ensureDatabase(databaseName: string): Promise<void> {\n let promise = this.databaseEnsureCache.get(databaseName);\n if (!promise) {\n promise = this.customEnsureDatabaseExists\n ? this.customEnsureDatabaseExists(this.config, databaseName)\n : retryPgAdminOperation(() =>\n ddlLimiter(() =>\n this.runAdminOperation(this.databaseAdminPool, admin =>\n ensurePgDatabase(admin, databaseName),\n ),\n ),\n );\n this.databaseEnsureCache.set(databaseName, promise);\n }\n\n try {\n await promise;\n } catch (error) {\n if (this.databaseEnsureCache.get(databaseName) === promise) {\n this.databaseEnsureCache.delete(databaseName);\n }\n throw error;\n }\n }\n\n private async runAdminOperation<T>(\n pool: PgAdminPool,\n operation: (client: Knex) => Promise<T>,\n ): Promise<T> {\n try {\n return await pool.run(operation);\n } catch (error) {\n await pool.invalidate().catch(() => {});\n throw error;\n }\n }\n\n async shutdown(): Promise<void> {\n const results = await Promise.allSettled([\n this.databaseAdminPool.shutdown(),\n this.schemaAdminPool.shutdown(),\n ]);\n const errors = results\n .filter(\n (result): result is PromiseRejectedResult =>\n result.status === 'rejected',\n )\n .map(result => result.reason);\n if (errors.length === 1) {\n throw errors[0];\n }\n if (errors.length > 1) {\n throw new AggregateError(\n errors,\n 'Failed to shut down PostgreSQL admin pools',\n );\n }\n }\n\n async getClient(\n pluginId: string,\n _deps: {\n logger: LoggerService;\n lifecycle: LifecycleService;\n },\n ): Promise<Knex> {\n const pluginDbConfig = computePgPluginConfig(\n this.config,\n pluginId,\n this.prefix,\n this.schemaPrefix,\n );\n\n if (pluginDbConfig.databaseName && pluginDbConfig.ensureExists) {\n try {\n await this.ensureDatabase(pluginDbConfig.databaseName);\n } catch (error) {\n throw new Error(\n `Failed to connect to the database to make sure that '${pluginDbConfig.databaseName}' exists, ${error}`,\n );\n }\n }\n\n if (pluginDbConfig.pluginDivisionMode === 'schema') {\n if (pluginDbConfig.ensureSchemaExists || pluginDbConfig.ensureExists) {\n try {\n await ddlLimiter(() =>\n this.runAdminOperation(this.schemaAdminPool, admin =>\n ensurePgSchema(\n admin,\n this.config.getOptionalString('role'),\n pluginDbConfig.schemaName!,\n ),\n ),\n );\n } catch (error) {\n throw new Error(\n `Failed to connect to the database to make sure that schema for plugin '${pluginId}' exists, ${error}`,\n );\n }\n }\n }\n\n const client = createPgDatabaseClient(\n this.config,\n mergeDatabaseConfig(\n pluginDbConfig.knexConfig,\n pluginDbConfig.databaseClientOverrides,\n ),\n );\n\n return client;\n }\n}\n"],"names":["limiterFactory","knexFactory","format","config","mergeDatabaseConfig","ConfigReader","omit","durationToMilliseconds","readDurationFromConfig","ForwardedError","merge"],"mappings":";;;;;;;;;;;;;;;;;AAsCA,MAAM,UAAA,GAAaA,gCAAe,CAAC,CAAA;AAEnC,MAAM,4BAAA,GAA+B,CAAA;AACrC,MAAM,oCAAA,GAAuC,GAAA;AAC7C,MAAM,oCAAA,uBAA2C,GAAA,CAAI;AAAA,EACnD,WAAA;AAAA,EACA,cAAA;AAAA,EACA,YAAA;AAAA,EACA,cAAA;AAAA,EACA,aAAA;AAAA,EACA,OAAA;AAAA,EACA,WAAA;AAAA,EACA;AACF,CA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AAA,IAAI,cAAA,CAAe,YAAA,IAAgB,cAAA,CAAe,YAAA,EAAc;AAC9D,MAAA,IAAI;AACF,QAAA,MAAM,IAAA,CAAK,cAAA,CAAe,cAAA,CAAe,YAAY,CAAA;AAAA,MACvD,SAAS,KAAA,EAAO;AACd,QAAA,MAAM,IAAI,KAAA;AAAA,UACR,CAAA,qDAAA,EAAwD,cAAA,CAAe,YAAY,CAAA,UAAA,EAAa,KAAK,CAAA;AAAA,SACvG;AAAA,MACF;AAAA,IACF;AAEA,IAAA,IAAI,cAAA,CAAe,uBAAuB,QAAA,EAAU;AAClD,MAAA,IAAI,cAAA,CAAe,kBAAA,IAAsB,cAAA,CAAe,YAAA,EAAc;AACpE,QAAA,IAAI;AACF,UAAA,MAAM,UAAA;AAAA,YAAW,MACf,IAAA,CAAK,iBAAA;AAAA,cAAkB,IAAA,CAAK,eAAA;AAAA,cAAiB,CAAA,KAAA,KAC3C,cAAA;AAAA,gBACE,KAAA;AAAA,gBACA,IAAA,CAAK,MAAA,CAAO,iBAAA,CAAkB,MAAM,CAAA;AAAA,gBACpC,cAAA,CAAe;AAAA;AACjB;AACF,WACF;AAAA,QACF,SAAS,KAAA,EAAO;AACd,UAAA,MAAM,IAAI,KAAA;AAAA,YACR,CAAA,uEAAA,EAA0E,QAAQ,CAAA,UAAA,EAAa,KAAK,CAAA;AAAA,WACtG;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAEA,IAAA,MAAM,MAAA,GAAS,sBAAA;AAAA,MACb,IAAA,CAAK,MAAA;AAAA,MACLA,uCAAA;AAAA,QACE,cAAA,CAAe,UAAA;AAAA,QACf,cAAA,CAAe;AAAA;AACjB,KACF;AAEA,IAAA,OAAO,MAAA;AAAA,EACT;AACF;;;;;;;;;;;"}
|
|
@@ -4,7 +4,7 @@ var GoogleCloud = require('@google-cloud/storage');
|
|
|
4
4
|
var getRawBody = require('raw-body');
|
|
5
5
|
var integration = require('@backstage/integration');
|
|
6
6
|
var ReadUrlResponseFactory = require('./ReadUrlResponseFactory.cjs.js');
|
|
7
|
-
var _package = require('../../../package.json.cjs.js');
|
|
7
|
+
var _package = require('../../../backend-defaults/package.json.cjs.js');
|
|
8
8
|
var errors = require('@backstage/errors');
|
|
9
9
|
var posix = require('node:path/posix');
|
|
10
10
|
var util = require('./util.cjs.js');
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@backstage/backend-defaults",
|
|
3
|
-
"version": "0.18.1-next.
|
|
3
|
+
"version": "0.18.1-next.3",
|
|
4
4
|
"description": "Backend defaults used by Backstage backend apps",
|
|
5
5
|
"backstage": {
|
|
6
6
|
"role": "node-library"
|
|
@@ -226,14 +226,15 @@
|
|
|
226
226
|
"@aws-sdk/types": "^3.347.0",
|
|
227
227
|
"@azure/identity": "^4.0.0",
|
|
228
228
|
"@azure/storage-blob": "^12.5.0",
|
|
229
|
-
"@backstage/backend-app-api": "1.8.0-next.
|
|
229
|
+
"@backstage/backend-app-api": "1.8.0-next.2",
|
|
230
230
|
"@backstage/backend-dev-utils": "0.1.7",
|
|
231
|
-
"@backstage/backend-plugin-api": "1.11.0-next.
|
|
232
|
-
"@backstage/cli-node": "0.3.5-next.
|
|
231
|
+
"@backstage/backend-plugin-api": "1.11.0-next.2",
|
|
232
|
+
"@backstage/cli-node": "0.3.5-next.1",
|
|
233
233
|
"@backstage/config": "1.3.10-next.0",
|
|
234
234
|
"@backstage/config-loader": "1.11.4-next.0",
|
|
235
|
+
"@backstage/connections": "0.4.1-next.0",
|
|
235
236
|
"@backstage/errors": "1.3.2-next.0",
|
|
236
|
-
"@backstage/integration": "2.1.3-next.
|
|
237
|
+
"@backstage/integration": "2.1.3-next.1",
|
|
237
238
|
"@backstage/integration-aws-node": "0.2.3-next.0",
|
|
238
239
|
"@backstage/plugin-auth-node": "0.7.7-next.1",
|
|
239
240
|
"@backstage/plugin-events-node": "0.4.27-next.1",
|
|
@@ -294,7 +295,7 @@
|
|
|
294
295
|
},
|
|
295
296
|
"devDependencies": {
|
|
296
297
|
"@aws-sdk/util-stream-node": "^3.350.0",
|
|
297
|
-
"@backstage/backend-test-utils": "1.11.8-next.
|
|
298
|
+
"@backstage/backend-test-utils": "1.11.8-next.2",
|
|
298
299
|
"@backstage/cli": "0.36.7-next.0",
|
|
299
300
|
"@google-cloud/cloud-sql-connector": "^1.4.0",
|
|
300
301
|
"@types/archiver": "^7.0.0",
|
|
File without changes
|