Ghost/ghost/adapter-manager/lib/AdapterManager.js

162 lines
5.4 KiB
JavaScript
Raw Permalink Normal View History

const path = require('path');
const errors = require('@tryghost/errors');
/**
* @typedef { function(new: Adapter, object) } AdapterConstructor
*/
/**
* @typedef {object} Adapter
* @prop {string[]} requiredFns
*/
module.exports = class AdapterManager {
/**
* @param {object} config
* @param {string[]} config.pathsToAdapters The paths to check, e.g. ['content/adapters', 'core/server/adapters']
* @param {(path: string) => AdapterConstructor} config.loadAdapterFromPath A function to load adapters, e.g. global.require
*/
constructor({pathsToAdapters, loadAdapterFromPath}) {
/**
* @private
* @type {Object.<string, AdapterConstructor>}
*/
this.baseClasses = {};
/**
* @private
* @type {Object.<string, Object.<string, Adapter>>}
*/
this.instanceCache = {};
/**
* @private
* @type {string[]}
*/
this.pathsToAdapters = pathsToAdapters;
/**
* @private
* @type {(path: string) => AdapterConstructor}
*/
this.loadAdapterFromPath = loadAdapterFromPath;
}
/**
* Register an adapter type and the corresponding base class. Must be called before requesting adapters of that type
*
* @param {string} type The name for the type of adapter
* @param {AdapterConstructor} BaseClass The class from which all adapters of this type must extend
*/
registerAdapter(type, BaseClass) {
this.instanceCache[type] = {};
this.baseClasses[type] = BaseClass;
}
Fixed configUtils and adapter cache issues in E2E tests (#16167) no issue There are a couple of issues with resetting the Ghost instance between E2E test files: These issues came to the surface because of new tests written in https://github.com/TryGhost/Ghost/pull/16117 **1. configUtils.restore does not work correctly** `config.reset()` is a callback based method. On top of that, it doesn't really work reliably (https://github.com/indexzero/nconf/issues/93) What kinda happens, is that you first call `config.reset` but immediately after you correcty reset the config using the `config.set` calls afterwards. But since `config.reset` is async, that reset will happen after all those sets, and the end result is that it isn't reset correctly. This mainly caused issues in the new updated images tests, which were updating the config `imageOptimization.contentImageSizes`, which is a deeply nested config value. Maybe some references to objects are reused in nconf that cause this issue? Wrapping `config.reset()` in a promise does fix the issue. **2. Adapters cache not reset between tests** At the start of each test, we set `paths:contentPath` to a nice new temporary directory. But if a previous test already requests a localStorage adapter, that adapter would have been created and in the constructor `paths:contentPath` would have been passed. That same instance will be reused in the next test run. So it won't read the new config again. To fix this, we need to reset the adapter instances between E2E tests. How was this visible? Test uploads were stored in the actual git repository, and not in a temporary directory. When writing the new image upload tests, this also resulted in unreliable test runs because some image names were already taken (from previous test runs). **3. Old 2E2 test Ghost server not stopped** Sometimes we still need access to the frontend test server using `getAgentsWithFrontend`. But that does start a new Ghost server which is actually listening for HTTP traffic. This could result in a fatal error in tests because the port is already in use. The issue is that old E2E tests also start a HTTP server, but they don't stop the server. When you used the old `startGhost` util, it would check if a server was already running and stop it first. The new `getAgentsWithFrontend` now also has the same functionality to fix that issue.
2023-01-30 16:06:20 +03:00
/**
* Force recreation of all instances instead of reusing cached instances. Use when editing config file during tests.
*/
clearInstanceCache() {
for (const key of Object.keys(this.instanceCache)) {
this.instanceCache[key] = {};
}
}
/**
* getAdapter
*
* @param {string} adapterName The name of the type of adapter, e.g. "storage" or "scheduling", optionally including the feature, e.g. "storage:files"
* @param {string} adapterClassName The active adapter instance class name e.g. "LocalFileStorage"
* @param {object} [config] The config the adapter could be instantiated with
*
* @returns {Adapter} The resolved and instantiated adapter
*/
getAdapter(adapterName, adapterClassName, config) {
if (!adapterName || !adapterClassName) {
throw new errors.IncorrectUsageError({
message: 'getAdapter must be called with a adapterName and a adapterClassName.'
});
}
let adapterType;
if (adapterName.includes(':')) {
[adapterType] = adapterName.split(':');
} else {
adapterType = adapterName;
}
Fixed configUtils and adapter cache issues in E2E tests (#16167) no issue There are a couple of issues with resetting the Ghost instance between E2E test files: These issues came to the surface because of new tests written in https://github.com/TryGhost/Ghost/pull/16117 **1. configUtils.restore does not work correctly** `config.reset()` is a callback based method. On top of that, it doesn't really work reliably (https://github.com/indexzero/nconf/issues/93) What kinda happens, is that you first call `config.reset` but immediately after you correcty reset the config using the `config.set` calls afterwards. But since `config.reset` is async, that reset will happen after all those sets, and the end result is that it isn't reset correctly. This mainly caused issues in the new updated images tests, which were updating the config `imageOptimization.contentImageSizes`, which is a deeply nested config value. Maybe some references to objects are reused in nconf that cause this issue? Wrapping `config.reset()` in a promise does fix the issue. **2. Adapters cache not reset between tests** At the start of each test, we set `paths:contentPath` to a nice new temporary directory. But if a previous test already requests a localStorage adapter, that adapter would have been created and in the constructor `paths:contentPath` would have been passed. That same instance will be reused in the next test run. So it won't read the new config again. To fix this, we need to reset the adapter instances between E2E tests. How was this visible? Test uploads were stored in the actual git repository, and not in a temporary directory. When writing the new image upload tests, this also resulted in unreliable test runs because some image names were already taken (from previous test runs). **3. Old 2E2 test Ghost server not stopped** Sometimes we still need access to the frontend test server using `getAgentsWithFrontend`. But that does start a new Ghost server which is actually listening for HTTP traffic. This could result in a fatal error in tests because the port is already in use. The issue is that old E2E tests also start a HTTP server, but they don't stop the server. When you used the old `startGhost` util, it would check if a server was already running and stop it first. The new `getAgentsWithFrontend` now also has the same functionality to fix that issue.
2023-01-30 16:06:20 +03:00
const adapterCache = this.instanceCache[adapterType];
if (!adapterCache) {
throw new errors.NotFoundError({
message: `Unknown adapter type ${adapterType}. Please register adapter.`
});
}
// @NOTE: example cache key value 'email:newsletters:custom-newsletter-adapter'
const adapterCacheKey = `${adapterName}:${adapterClassName}`;
if (adapterCache[adapterCacheKey]) {
return adapterCache[adapterCacheKey];
}
/** @type AdapterConstructor */
let Adapter;
for (const pathToAdapters of this.pathsToAdapters) {
const pathToAdapter = path.join(pathToAdapters, adapterType, adapterClassName);
try {
Adapter = this.loadAdapterFromPath(pathToAdapter);
if (Adapter) {
break;
}
} catch (err) {
// Catch runtime errors
if (err.code !== 'MODULE_NOT_FOUND') {
throw new errors.IncorrectUsageError({err});
}
// Catch missing dependencies BUT NOT missing adapter
if (!err.message.includes(pathToAdapter)) {
throw new errors.IncorrectUsageError({
message: `You are missing dependencies in your adapter ${pathToAdapter}`,
err
});
}
}
}
if (!Adapter) {
throw new errors.IncorrectUsageError({
message: `Unable to find ${adapterType} adapter ${adapterClassName} in ${this.pathsToAdapters}.`
});
}
const adapter = new Adapter(config);
if (!(adapter instanceof this.baseClasses[adapterType])) {
if (Object.getPrototypeOf(Adapter).name !== this.baseClasses[adapterType].name) {
throw new errors.IncorrectUsageError({
message: `${adapterType} adapter ${adapterClassName} does not inherit from the base class.`
});
}
}
if (!adapter.requiredFns) {
throw new errors.IncorrectUsageError({
message: `${adapterType} adapter ${adapterClassName} does not have the requiredFns.`
});
}
for (const requiredFn of adapter.requiredFns) {
if (typeof adapter[requiredFn] !== 'function') {
throw new errors.IncorrectUsageError({
message: `${adapterType} adapter ${adapterClassName} is missing the ${requiredFn} method.`
});
}
}
adapterCache[adapterCacheKey] = adapter;
return adapter;
}
};