api/env: add subscribe() for dynamic reloads

This commit is contained in:
jj 2025-07-19 15:21:57 +00:00
parent c8b2fe44c8
commit 5908e9da15
No known key found for this signature in database
2 changed files with 35 additions and 1 deletions

View File

@ -1,5 +1,5 @@
import { getVersion } from "@imput/version-info";
import { loadEnvs, validateEnvs } from "./core/env.js";
import { loadEnvs, validateEnvs, onEnvChanged } from "./core/env.js";
const version = await getVersion();
@ -18,12 +18,20 @@ export const updateEnv = (newEnv) => {
newEnv.tunnelPort = env.tunnelPort;
for (const key in env) {
if (key === 'subscribe') {
continue;
}
if (String(env[key]) !== String(newEnv[key])) {
changes.push(key);
}
env[key] = newEnv[key];
}
if (changes.length) {
onEnvChanged(changes);
}
return changes;
}

View File

@ -10,6 +10,30 @@ import { Green, Yellow } from "../misc/console-text.js";
const forceLocalProcessingOptions = ["never", "session", "always"];
const youtubeHlsOptions = ["never", "key", "always"];
const changeCallbacks = {};
export const onEnvChanged = (changes) => {
for (const key of changes) {
if (changeCallbacks[key]) {
changeCallbacks[key].map(fn => {
try { fn() } catch {}
});
}
}
}
const subscribe = (keys, fn) => {
keys = [keys].flat();
for (const key of keys) {
if (key in currentEnv && key !== 'subscribe') {
changeCallbacks[key] ??= [];
changeCallbacks[key].push(fn);
fn();
} else throw `invalid env key ${key}`;
}
}
export const loadEnvs = (env = process.env) => {
const allServices = new Set(Object.keys(services));
const disabledServices = env.DISABLED_SERVICES?.split(',') || [];
@ -87,6 +111,8 @@ export const loadEnvs = (env = process.env) => {
envFile: env.API_ENV_FILE,
envRemoteReloadInterval: 300,
subscribe,
};
}