ActivityPub-federated video streaming platform using P2P directly in your web browser
Fix reloading config
Chocobozzzf199054ce6e3
diff --git a/server/core/helpers/decache.ts b/server/core/helpers/decache.tsindex 4543c41c1d..b8bf789936 100644--- a/server/core/helpers/decache.ts+++ b/server/core/helpers/decache.ts@@ -18,18 +18,6 @@ export function decachePlugin (require: NodeJS.Require, libraryPath: string) {})}-export function decacheModule (require: NodeJS.Require, name: string) {- const moduleName = find(require, name)-- if (!moduleName) return-- searchCache(require, moduleName, function (mod) {- delete require.cache[mod.id]-- removeCachedPath(mod.path)- })-}-// ---------------------------------------------------------------------------// Private// ---------------------------------------------------------------------------diff --git a/server/core/initializers/checker-after-init.ts b/server/core/initializers/checker-after-init.tsindex 39aa98de54..11e313dfa2 100644--- a/server/core/initializers/checker-after-init.ts+++ b/server/core/initializers/checker-after-init.ts@@ -2,7 +2,6 @@ import { uniqify } from '@peertube/peertube-core-utils'import { getFFmpegVersion } from '@peertube/peertube-ffmpeg'import { VideoRedundancyConfigFilter } from '@peertube/peertube-models'import { isProdInstance } from '@peertube/peertube-node-utils'-import config from 'config'import { readFileSync, writeFileSync } from 'fs'import { basename } from 'path'import { URL } from 'url'@@ -13,7 +12,7 @@ import { logger } from '../helpers/logger.js'import { ApplicationModel, getServerActor } from '../models/application/application.js'import { OAuthClientModel } from '../models/oauth/oauth-client.js'import { UserModel } from '../models/user/user.js'-import { CONFIG, getLocalConfigFilePath, isEmailEnabled, reloadConfig } from './config.js'+import { CONFIG, getConfigModule, getLocalConfigFilePath, isEmailEnabled, reloadConfig } from './config.js'import { WEBSERVER } from './constants.js'async function checkActivityPubUrls () {@@ -21,6 +20,8 @@ async function checkActivityPubUrls () {const parsed = new URL(actor.url)if (WEBSERVER.HOST !== parsed.host) {+ const config = getConfigModule()+const NODE_ENV = config.util.getEnv('NODE_ENV')const NODE_CONFIG_DIR = config.util.getEnv('NODE_CONFIG_DIR')@@ -36,7 +37,7 @@ async function checkActivityPubUrls () {// Some checks on configuration files or throw if there is an errorfunction checkConfig () {- const configFiles = config.util.getConfigSources().map(s => s.name).join(' -> ')+ const configFiles = getConfigModule().util.getConfigSources().map(s => s.name).join(' -> ')logger.info('Using following configuration file hierarchy: %s.', configFiles)checkRemovedConfigKeys()@@ -113,6 +114,8 @@ export {// ---------------------------------------------------------------------------function checkRemovedConfigKeys () {+ const config = getConfigModule()+// Moved configuration keysif (config.has('services.csp-logger')) {logger.warn('services.csp-logger configuration has been renamed to csp.report_uri. Please update your configuration file.')@@ -218,7 +221,7 @@ function checkRemoteRedundancyConfig () {function checkStorageConfig () {// Check storage directory locationsif (isProdInstance()) {- const configStorage = config.get<{ [name: string]: string }>('storage')+ const configStorage = getConfigModule().get<{ [name: string]: string }>('storage')for (const key of Object.keys(configStorage)) {if (configStorage[key].startsWith('storage/')) {diff --git a/server/core/initializers/checker-before-init.ts b/server/core/initializers/checker-before-init.tsindex 9589dfec19..adbcae229c 100644--- a/server/core/initializers/checker-before-init.ts+++ b/server/core/initializers/checker-before-init.ts@@ -1,12 +1,14 @@import { promisify0 } from '@peertube/peertube-core-utils'-import config from 'config'import { parseSemVersion } from '../helpers/core-utils.js'import { logger } from '../helpers/logger.js'+import { getConfigModule } from './config.js'// ONLY USE CORE MODULES IN THIS FILE!// Check the config filesexport function checkMissedConfig () {+ const config = getConfigModule()+const required = ['listen.port','listen.hostname',diff --git a/server/core/initializers/config.ts b/server/core/initializers/config.tsindex c0c74277a5..a06fca0938 100644--- a/server/core/initializers/config.ts+++ b/server/core/initializers/config.ts@@ -9,17 +9,126 @@ import {VideoRedundancyConfigFilter,VideosRedundancyStrategy} from '@peertube/peertube-models'-import { buildPath, root } from '@peertube/peertube-node-utils'+import { buildPath } from '@peertube/peertube-node-utils'import { TranscriptionEngineName, WhisperBuiltinModelName } from '@peertube/peertube-transcription'-import { decacheModule } from '@server/helpers/decache.js'import bytes from 'bytes'-import { type Config } from 'config'-import { createRequire } from 'module'-import { dirname, join } from 'path'+import { Load, Util, type ConfigSource } from 'config/lib/util.js'+import { basename, dirname, join } from 'path'import { parseBytes, parseDurationToMs } from '../helpers/core-utils.js'-const require = createRequire(import.meta.url)-let config: Config = require('config')+type ConfigInstance = {+ get: <T>(property: string) => T+ has: (property: string) => boolean+ util: {+ getConfigSources: () => ConfigSource[]+ getEnv: (varName: string) => string+ }+}++// Reimplement the bootstrap of the `config` module singleton, so we can rebuild the configuration+// on reload without having to purge the CommonJS require cache+function loadConfig (): ConfigInstance {+ // `environments` is optional at runtime, but is typed as a required argument by the config module+ const load = Load.fromEnvironment(undefined)++ const additional: { name: string, config: any }[] = []+ let envConfig: any = {}+ let cmdLineConfig: any = {}++ load.setEnv('CONFIG_DIR', load.options.configDir)++ if (process.env.NODE_CONFIG) {+ try {+ envConfig = JSON.parse(process.env.NODE_CONFIG)+ } catch {+ console.error('The $NODE_CONFIG environment variable is malformed JSON')+ }++ additional.push({ name: '$NODE_CONFIG', config: envConfig })+ }++ const cmdLineArg = load.getCmdLineArg('NODE_CONFIG')+ if (cmdLineArg) {+ try {+ cmdLineConfig = JSON.parse(cmdLineArg)+ } catch {+ console.error('The --NODE_CONFIG={json} command line argument is malformed JSON')+ }++ additional.push({ name: '--NODE_CONFIG argument', config: cmdLineConfig })+ }++ // Place the mixed NODE_CONFIG into the environment+ load.setEnv('NODE_CONFIG', JSON.stringify(Util.extendDeep({}, envConfig, cmdLineConfig)))++ load.scan(additional)++ runStrictnessChecks(load)++ if (!load.initParam('SUPPRESS_NO_CONFIG_WARNING') && Object.keys(load.config).length === 0) {+ console.error('WARNING: No configurations found in configuration directory: ' + load.options.configDir)+ console.error('WARNING: To disable this warning set SUPPRESS_NO_CONFIG_WARNING in the environment.')+ }++ // Ensure the configuration cannot be accidentally mutated at runtime+ if (!load.initParam('ALLOW_CONFIG_MUTATIONS', false)) {+ Util.makeImmutable(load.config)+ }++ return {+ get: <T>(property: string): T => {+ const value = Util.getPath(load.config, property)+ if (value === undefined) throw new Error(`Configuration property "${property}" is not defined`)++ return value+ },+ has: (property: string): boolean => Util.getPath(load.config, property) !== undefined,+ util: {+ getConfigSources: () => load.getSources(),+ getEnv: (varName: string) => load.getEnv(varName)+ }+ }+}++// Warn (or throw if NODE_CONFIG_STRICT_MODE is set) when NODE_ENV/NODE_APP_INSTANCE match no config file+// See https://github.com/node-config/node-config/wiki/Strict-Mode+function runStrictnessChecks (load: Load) {+ if (load.initParam('SUPPRESS_STRICTNESS_CHECK')) return++ const sourceFilenames = load.getSources().map(s => basename(s.name))++ const warnOrThrow = (message: string) => {+ const beStrict = process.env.NODE_CONFIG_STRICT_MODE+ const prefix = beStrict ? 'FATAL: ' : 'WARNING: '+ const seeURL = 'See https://github.com/node-config/node-config/wiki/Strict-Mode'++ console.error(prefix + message)+ console.error(prefix + seeURL)++ if ([ 'true', '1' ].includes(beStrict)) throw new Error(prefix + message + ' ' + seeURL)+ }++ for (const env of load.options.nodeEnv) {+ // Anchored regex to avoid false positives, so `test` does not match `contest.yaml`+ const anyFileMatchesEnv = sourceFilenames.some(filename => new RegExp(`^${env}[.-]`).test(filename))++ // development is special cased because it's the default value+ if (env && env !== 'development' && !anyFileMatchesEnv) {+ warnOrThrow(`${load.getEnv('nodeEnv')} value of '${env}' did not match any deployment config file names.`)+ }++ if (env === 'default' || env === 'local') {+ warnOrThrow(`${load.getEnv('nodeEnv')} value of '${env}' is ambiguous.`)+ }+ }++ const appInstance = load.options.appInstance+ if (appInstance && !sourceFilenames.some(filename => filename.includes(appInstance))) {+ warnOrThrow(`NODE_APP_INSTANCE value of '${appInstance}' did not match any instance config file names.`)+ }+}++let config = loadConfig()const configChangedHandlers: Function[] = []@@ -1275,7 +1384,7 @@ function getLocalConfigFilePath () {return join(localConfigDir, filename + '.json')}-function getConfigModule (): Config {+function getConfigModule (): ConfigInstance {return config}@@ -1315,31 +1424,7 @@ function buildVideosRedundancy (objs: any[]): VideosRedundancyStrategy[] {}export function reloadConfig () {- function getConfigDirectories () {- if (process.env.NODE_CONFIG_DIR) {- return process.env.NODE_CONFIG_DIR.split(':')- }-- return [ join(root(), 'config') ]- }-- function purge () {- const directories = getConfigDirectories()-- for (const fileName in require.cache) {- if (directories.some(dir => fileName.includes(dir)) === false) {- continue- }-- delete require.cache[fileName]- }-- decacheModule(require, 'config')- }-- purge()-- config = require('config')+ config = loadConfig()for (const configChangedHandler of configChangedHandlers) {configChangedHandler()