feat: switch to a central singleton handler

This also adds support for Headscale TLS installations
This commit is contained in:
Aarnav Tale
2025-03-17 22:21:16 -04:00
parent 43e06987ad
commit 6108de52e7
35 changed files with 339 additions and 399 deletions
+1 -12
View File
@@ -1,22 +1,11 @@
import type { HostInfo } from '~/types';
import { TimedCache } from '~server/ws/cache';
import { hp_agentRequest, hp_getAgentCache } from '~server/ws/data';
import { hp_getAgents } from '~server/ws/socket';
import { hp_getConfig } from './loader';
import type { HeadplaneConfig } from './parser';
import { hp_agentRequest } from '~server/ws/data';
export interface AppContext {
context: HeadplaneConfig;
hp_agentRequest: typeof hp_agentRequest;
agents: string[];
agentData?: TimedCache<HostInfo>;
}
export default function appContext(): AppContext {
return {
context: hp_getConfig(),
hp_agentRequest,
agents: [...hp_getAgents().keys()],
agentData: hp_getAgentCache(),
};
}
+85
View File
@@ -0,0 +1,85 @@
import type { Configuration } from 'openid-client';
import type { Agent } from 'undici';
import type { WebSocket } from 'ws';
import type { HostInfo } from '~/types';
import type { HeadplaneConfig } from '~server/context/parser';
import type { Logger } from '~server/utils/log';
import type { TimedCache } from '~server/ws/cache';
// This is a stupid workaround for how the Remix import context works
// Even though they run in the same Node instance, they have different
// contexts which means importing this in the app code will not work
// because it will be a different instance of the module.
//
// Instead we can rely on globalThis to share the module between the
// different contexts and use some helper functions to make it easier.
// As a part of this global module, we also define all our singletons
// here in order to avoid polluting the global scope and instead just using
// the `__headplane_server_context` object.
interface ServerContext {
config: HeadplaneConfig;
singletons: ServerSingletons;
}
interface ServerSingletons {
api_agent: Agent;
logger: Logger;
oidc_client: Configuration;
ws_agents: Map<string, WebSocket>;
ws_agent_data: TimedCache<HostInfo>;
ws_fetch_data: (nodeList: string[]) => Promise<void>;
}
// These declarations are separate to prevent the Remix context
// from modifying the globalThis object and causing issues with
// the server context.
declare namespace globalThis {
let __headplane_server_context: {
[K in keyof ServerContext]: ServerContext[K] | null | object;
};
}
// We need to check if the context is already initialized and set a default
// value. This is fine as a side-effect since it's just setting up a framework
// for the object to get modified later.
if (!globalThis.__headplane_server_context) {
globalThis.__headplane_server_context = {
config: null,
singletons: {},
};
}
declare global {
const __headplane_server_context: ServerContext;
}
export function hp_getConfig(): HeadplaneConfig {
return __headplane_server_context.config;
}
export function hp_setConfig(config: HeadplaneConfig): void {
__headplane_server_context.config = config;
}
export function hp_getSingleton<T extends keyof ServerSingletons>(
key: T,
): ServerSingletons[T] {
if (!__headplane_server_context.singletons[key]) {
throw new Error(`Singleton ${key} not initialized`);
}
return __headplane_server_context.singletons[key];
}
export function hp_getSingletonUnsafe<T extends keyof ServerSingletons>(
key: T,
): ServerSingletons[T] | undefined {
return __headplane_server_context.singletons[key];
}
export function hp_setSingleton<
T extends ServerSingletons[keyof ServerSingletons],
>(key: keyof ServerSingletons, value: T): void {
(__headplane_server_context.singletons[key] as T) = value;
}
-21
View File
@@ -1,21 +0,0 @@
import { HeadplaneConfig } from './parser';
declare global {
const __cookie_context: {
cookie_secret: string;
cookie_secure: boolean;
};
const __hs_context: {
url: string;
config_path?: string;
config_strict?: boolean;
};
const __oidc_context: {
valid: boolean;
secret: string;
};
let __integration_context: HeadplaneConfig['integration'];
}
+26 -59
View File
@@ -2,32 +2,14 @@ import { constants, access, readFile } from 'node:fs/promises';
import { env } from 'node:process';
import { type } from 'arktype';
import dotenv from 'dotenv';
import { Agent } from 'undici';
import { parseDocument } from 'yaml';
import { getOidcSecret, testOidc } from '~/utils/oidc';
import log, { hpServer_loadLogger } from '~server/utils/log';
import { testOidc } from '~/utils/oidc';
import log, { hp_loadLogger } from '~server/utils/log';
import mutex from '~server/utils/mutex';
import { hp_setConfig, hp_setSingleton } from './global';
import { HeadplaneConfig, coalesceConfig, validateConfig } from './parser';
declare namespace globalThis {
let __cookie_context: {
cookie_secret: string;
cookie_secure: boolean;
};
let __hs_context: {
url: string;
config_path?: string;
config_strict?: boolean;
};
let __oidc_context: {
valid: boolean;
secret: string;
};
let __integration_context: HeadplaneConfig['integration'];
}
const envBool = type('string | undefined').pipe((v) => {
return ['1', 'true', 'yes', 'on'].includes(v?.toLowerCase() ?? '');
});
@@ -39,30 +21,12 @@ const rootEnvs = type({
}).onDeepUndeclaredKey('reject');
const HEADPLANE_DEFAULT_CONFIG_PATH = '/etc/headplane/config.yaml';
let runtimeConfig: HeadplaneConfig | undefined = undefined;
const runtimeLock = mutex();
// We need to acquire here to ensure that the configuration is loaded
// properly. We can't request a configuration if its in the process
// of being updated.
export function hp_getConfig() {
runtimeLock.acquire();
if (!runtimeConfig) {
runtimeLock.release();
// This shouldn't be possible, we NEED to have a configuration
throw new Error('Configuration not loaded');
}
const config = runtimeConfig;
runtimeLock.release();
return config;
}
// hp_loadConfig should ONLY be called when we explicitly need to reload
// the configuration. This should be done when the configuration file
// changes and we ignore environment variable changes.
//
// To read the config hp_getConfig should be used.
// TODO: File watching for hp_loadConfig()
export async function hp_loadConfig() {
runtimeLock.acquire();
@@ -84,7 +48,7 @@ export async function hp_loadConfig() {
}
// Load our debug based logger before ANYTHING
hpServer_loadLogger(envs.HEADPLANE_DEBUG_LOG);
await hp_loadLogger(envs.HEADPLANE_DEBUG_LOG);
if (envs.HEADPLANE_CONFIG_PATH) {
path = envs.HEADPLANE_CONFIG_PATH;
}
@@ -133,28 +97,31 @@ export async function hp_loadConfig() {
if (!result) {
log.error('CFGX', 'OIDC configuration failed validation, disabling');
}
globalThis.__oidc_context = {
valid: result,
secret: getOidcSecret() ?? '',
};
}
}
globalThis.__cookie_context = {
cookie_secret: config.server.cookie_secret,
cookie_secure: config.server.cookie_secure,
};
if (config.headscale.tls_cert_path) {
log.debug('CFGX', 'Attempting to load supplied Headscale TLS cert');
try {
const data = await readFile(config.headscale.tls_cert_path, 'utf8');
log.info('CFGX', 'Headscale TLS cert loaded successfully');
hp_setSingleton(
'api_agent',
new Agent({
connect: {
ca: data.trim(),
},
}),
);
} catch (error) {
log.error('CFGX', 'Failed to load Headscale TLS cert');
log.debug('CFGX', 'Error Details: %o', error);
}
} else {
hp_setSingleton('api_agent', new Agent());
}
globalThis.__hs_context = {
url: config.headscale.url,
config_path: config.headscale.config_path,
config_strict: config.headscale.config_strict,
};
globalThis.__integration_context = config.integration;
runtimeConfig = config;
hp_setConfig(config);
runtimeLock.release();
}