config-manager.ts 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. import parseISO from 'date-fns/parseISO';
  2. import loggerFactory from '~/utils/logger';
  3. import ConfigModel from '../models/config';
  4. import S2sMessage from '../models/vo/s2s-message';
  5. import { S2sMessagingService } from './s2s-messaging/base';
  6. import { S2sMessageHandlable } from './s2s-messaging/handlable';
  7. import ConfigLoader, { ConfigObject } from './config-loader';
  8. const logger = loggerFactory('growi:service:ConfigManager');
  9. const KEYS_FOR_LOCAL_STRATEGY_USE_ONLY_ENV_OPTION = [
  10. 'security:passport-local:isEnabled',
  11. ];
  12. const KEYS_FOR_SAML_USE_ONLY_ENV_OPTION = [
  13. 'security:passport-saml:isEnabled',
  14. 'security:passport-saml:entryPoint',
  15. 'security:passport-saml:issuer',
  16. 'security:passport-saml:cert',
  17. ];
  18. const KEYS_FOR_FIEL_UPLOAD_USE_ONLY_ENV_OPTION = [
  19. 'app:fileUploadType',
  20. ];
  21. const KEYS_FOR_GCS_USE_ONLY_ENV_OPTION = [
  22. 'gcs:apiKeyJsonPath',
  23. 'gcs:bucket',
  24. 'gcs:uploadNamespace',
  25. ];
  26. export default class ConfigManager implements S2sMessageHandlable {
  27. private configLoader: ConfigLoader = new ConfigLoader();
  28. private s2sMessagingService?: S2sMessagingService;
  29. private configObject: ConfigObject = { fromDB: null, fromEnvVars: null };
  30. private configKeys: any[] = [];
  31. private lastLoadedAt?: Date;
  32. /**
  33. * load configs from the database and the environment variables
  34. */
  35. async loadConfigs(): Promise<void> {
  36. this.configObject = await this.configLoader.load();
  37. logger.debug('ConfigManager#loadConfigs', this.configObject);
  38. // cache all config keys
  39. this.reloadConfigKeys();
  40. this.lastLoadedAt = new Date();
  41. }
  42. /**
  43. * Set S2sMessagingServiceDelegator instance
  44. * @param s2sMessagingService
  45. */
  46. setS2sMessagingService(s2sMessagingService: S2sMessagingService): void {
  47. this.s2sMessagingService = s2sMessagingService;
  48. }
  49. /**
  50. * get a config specified by namespace & key
  51. *
  52. * Basically, this searches a specified config from configs loaded from the database at first
  53. * and then from configs loaded from the environment variables.
  54. *
  55. * In some case, this search method changes.
  56. *
  57. * the followings are the meanings of each special return value.
  58. * - null: a specified config is not set.
  59. * - undefined: a specified config does not exist.
  60. */
  61. getConfig(namespace, key) {
  62. let value;
  63. if (this.shouldSearchedFromEnvVarsOnly(namespace, key)) {
  64. value = this.searchOnlyFromEnvVarConfigs(namespace, key);
  65. }
  66. else {
  67. value = this.defaultSearch(namespace, key);
  68. }
  69. logger.debug(key, value);
  70. return value;
  71. }
  72. /**
  73. * get a config specified by namespace and regular expression
  74. */
  75. getConfigByRegExp(namespace, regexp) {
  76. const result = {};
  77. for (const key of this.configKeys) {
  78. if (regexp.test(key)) {
  79. result[key] = this.getConfig(namespace, key);
  80. }
  81. }
  82. return result;
  83. }
  84. /**
  85. * get a config specified by namespace and prefix
  86. */
  87. getConfigByPrefix(namespace, prefix) {
  88. const regexp = new RegExp(`^${prefix}`);
  89. return this.getConfigByRegExp(namespace, regexp);
  90. }
  91. /**
  92. * generate an array of config keys from this.configObject
  93. */
  94. getConfigKeys() {
  95. // type: fromDB, fromEnvVars
  96. const types = Object.keys(this.configObject);
  97. let namespaces: string[] = [];
  98. let keys: string[] = [];
  99. for (const type of types) {
  100. if (this.configObject[type] != null) {
  101. // ns: crowi, markdown, notification
  102. namespaces = [...namespaces, ...Object.keys(this.configObject[type])];
  103. }
  104. }
  105. // remove duplicates
  106. namespaces = [...new Set(namespaces)];
  107. for (const type of types) {
  108. for (const ns of namespaces) {
  109. if (this.configObject[type][ns] != null) {
  110. keys = [...keys, ...Object.keys(this.configObject[type][ns])];
  111. }
  112. }
  113. }
  114. // remove duplicates
  115. keys = [...new Set(keys)];
  116. return keys;
  117. }
  118. reloadConfigKeys() {
  119. this.configKeys = this.getConfigKeys();
  120. }
  121. /**
  122. * get a config specified by namespace & key from configs loaded from the database
  123. *
  124. * **Do not use this unless absolutely necessary. Use getConfig instead.**
  125. */
  126. getConfigFromDB(namespace, key) {
  127. return this.searchOnlyFromDBConfigs(namespace, key);
  128. }
  129. /**
  130. * get a config specified by namespace & key from configs loaded from the environment variables
  131. *
  132. * **Do not use this unless absolutely necessary. Use getConfig instead.**
  133. */
  134. getConfigFromEnvVars(namespace, key) {
  135. return this.searchOnlyFromEnvVarConfigs(namespace, key);
  136. }
  137. /**
  138. * update configs in the same namespace
  139. *
  140. * Specified values are encoded by convertInsertValue.
  141. * In it, an empty string is converted to null that indicates a config is not set.
  142. *
  143. * For example:
  144. * ```
  145. * updateConfigsInTheSameNamespace(
  146. * 'some namespace',
  147. * {
  148. * 'some key 1': 'value 1',
  149. * 'some key 2': 'value 2',
  150. * ...
  151. * }
  152. * );
  153. * ```
  154. */
  155. async updateConfigsInTheSameNamespace(namespace, configs, withoutPublishingS2sMessage) {
  156. const queries: any[] = [];
  157. for (const key of Object.keys(configs)) {
  158. queries.push({
  159. updateOne: {
  160. filter: { ns: namespace, key },
  161. update: { ns: namespace, key, value: this.convertInsertValue(configs[key]) },
  162. upsert: true,
  163. },
  164. });
  165. }
  166. await ConfigModel.bulkWrite(queries);
  167. await this.loadConfigs();
  168. // publish updated date after reloading
  169. if (this.s2sMessagingService != null && !withoutPublishingS2sMessage) {
  170. this.publishUpdateMessage();
  171. }
  172. }
  173. /**
  174. * return whether the specified namespace/key should be retrieved only from env vars
  175. */
  176. shouldSearchedFromEnvVarsOnly(namespace, key) {
  177. return (namespace === 'crowi' && (
  178. // local strategy
  179. (
  180. KEYS_FOR_LOCAL_STRATEGY_USE_ONLY_ENV_OPTION.includes(key)
  181. && this.defaultSearch('crowi', 'security:passport-local:useOnlyEnvVarsForSomeOptions')
  182. )
  183. // saml strategy
  184. || (
  185. KEYS_FOR_SAML_USE_ONLY_ENV_OPTION.includes(key)
  186. && this.defaultSearch('crowi', 'security:passport-saml:useOnlyEnvVarsForSomeOptions')
  187. )
  188. // file upload option
  189. || (
  190. KEYS_FOR_FIEL_UPLOAD_USE_ONLY_ENV_OPTION.includes(key)
  191. && this.searchOnlyFromEnvVarConfigs('crowi', 'app:useOnlyEnvVarForFileUploadType')
  192. )
  193. // gcs option
  194. || (
  195. KEYS_FOR_GCS_USE_ONLY_ENV_OPTION.includes(key)
  196. && this.searchOnlyFromEnvVarConfigs('crowi', 'gcs:useOnlyEnvVarsForSomeOptions')
  197. )
  198. ));
  199. }
  200. /*
  201. * All of the methods below are private APIs.
  202. */
  203. /**
  204. * search a specified config from configs loaded from the database at first
  205. * and then from configs loaded from the environment variables
  206. */
  207. defaultSearch(namespace, key) {
  208. // does not exist neither in db nor in env vars
  209. if (!this.configExistsInDB(namespace, key) && !this.configExistsInEnvVars(namespace, key)) {
  210. logger.debug(`${namespace}.${key} does not exist neither in db nor in env vars`);
  211. return undefined;
  212. }
  213. // only exists in db
  214. if (this.configExistsInDB(namespace, key) && !this.configExistsInEnvVars(namespace, key)) {
  215. logger.debug(`${namespace}.${key} only exists in db`);
  216. return this.configObject.fromDB[namespace][key];
  217. }
  218. // only exists env vars
  219. if (!this.configExistsInDB(namespace, key) && this.configExistsInEnvVars(namespace, key)) {
  220. logger.debug(`${namespace}.${key} only exists in env vars`);
  221. return this.configObject.fromEnvVars[namespace][key];
  222. }
  223. // exists both in db and in env vars [db > env var]
  224. if (this.configExistsInDB(namespace, key) && this.configExistsInEnvVars(namespace, key)) {
  225. if (this.configObject.fromDB[namespace][key] !== null) {
  226. logger.debug(`${namespace}.${key} exists both in db and in env vars. loaded from db`);
  227. return this.configObject.fromDB[namespace][key];
  228. }
  229. /* eslint-disable-next-line no-else-return */
  230. else {
  231. logger.debug(`${namespace}.${key} exists both in db and in env vars. loaded from env vars`);
  232. return this.configObject.fromEnvVars[namespace][key];
  233. }
  234. }
  235. }
  236. /**
  237. * search a specified config from configs loaded from the database
  238. */
  239. searchOnlyFromDBConfigs(namespace, key) {
  240. if (!this.configExistsInDB(namespace, key)) {
  241. return undefined;
  242. }
  243. return this.configObject.fromDB[namespace][key];
  244. }
  245. /**
  246. * search a specified config from configs loaded from the environment variables
  247. */
  248. searchOnlyFromEnvVarConfigs(namespace, key) {
  249. if (!this.configExistsInEnvVars(namespace, key)) {
  250. return undefined;
  251. }
  252. return this.configObject.fromEnvVars[namespace][key];
  253. }
  254. /**
  255. * check whether a specified config exists in configs loaded from the database
  256. */
  257. configExistsInDB(namespace, key) {
  258. if (this.configObject.fromDB[namespace] === undefined) {
  259. return false;
  260. }
  261. return this.configObject.fromDB[namespace][key] !== undefined;
  262. }
  263. /**
  264. * check whether a specified config exists in configs loaded from the environment variables
  265. */
  266. configExistsInEnvVars(namespace, key) {
  267. if (this.configObject.fromEnvVars[namespace] === undefined) {
  268. return false;
  269. }
  270. return this.configObject.fromEnvVars[namespace][key] !== undefined;
  271. }
  272. convertInsertValue(value) {
  273. return JSON.stringify(value === '' ? null : value);
  274. }
  275. async publishUpdateMessage() {
  276. const s2sMessage = new S2sMessage('configUpdated', { updatedAt: new Date() });
  277. try {
  278. await this.s2sMessagingService?.publish(s2sMessage);
  279. }
  280. catch (e) {
  281. logger.error('Failed to publish update message with S2sMessagingService: ', e.message);
  282. }
  283. }
  284. /**
  285. * @inheritdoc
  286. */
  287. shouldHandleS2sMessage(s2sMessage) {
  288. const { eventName, updatedAt } = s2sMessage;
  289. if (eventName !== 'configUpdated' || updatedAt == null) {
  290. return false;
  291. }
  292. return this.lastLoadedAt == null || this.lastLoadedAt < parseISO(s2sMessage.updatedAt);
  293. }
  294. /**
  295. * @inheritdoc
  296. */
  297. async handleS2sMessage(s2sMessage) {
  298. logger.info('Reload configs by pubsub notification');
  299. return this.loadConfigs();
  300. }
  301. }