🌳
pt0/deployF/k8sF/getApisF.mts
1import * as _ from 'lodash-es'
2import { KubernetesObjectApi, KubeConfig, type RequestContext } from '@kubernetes/client-node'
4import { getKlusterCtx, type KlusterCfg } from './ctxF/klusterCtxF.mts'
13export const getKubeApis = async (props: {cluster_name?: string, kubeTlsInsecure?: boolean} = {}) => {
14 const {cluster_name, kubeTlsInsecure} = getKlusterCtx(props) as KlusterCfg
15 assertDefined(cluster_name, {props})
17 const kubeConfig = new KubeConfig()
18 const clusterCfgPath = getKubeConfigPath(cluster_name)
20 const cfgExists = await fileExists(clusterCfgPath)
21 assertTruthy(cfgExists, {clusterCfgPath: absPathToPtPath(clusterCfgPath)})
23 let klusterCfgStr = await read1File(clusterCfgPath)
24 klusterCfgStr = await rewriteKcHostForLan({klusterCfgStr, cluster_name})
26 kubeConfig.loadFromString(klusterCfgStr)
28 if (kubeTlsInsecure) {
29 _.each(kubeConfig.clusters, (cluster) => {
30 (cluster as {skipTLSVerify?: boolean}).skipTLSVerify = true
31 })
32 }
33 const observableOf = <T,>(v: T) => ({toPromise: () => Promise.resolve(v)})
34 const timeoutMs = getKubeTimeoutSec(cluster_name) * 1000
35 const timeoutMiddleware = {
36 pre: (ctx: RequestContext) => { ctx.setSignal(AbortSignal.timeout(timeoutMs)); return observableOf(ctx) },
37 post: (rsp: unknown) => observableOf(rsp),
38 }
40 // Patch makeApiClient so ALL clients (CoreV1Api, BatchV1Api, etc.) get the timeout,
41 // not just objectApi. Without this, makeApiClient-created clients hang ~75s on TCP
42 // ETIMEDOUT because KubeConfig.makeApiClient creates a fresh Configuration with empty middleware[].
43 const origMakeApiClient = kubeConfig.makeApiClient.bind(kubeConfig)
44 kubeConfig.makeApiClient = function<T extends new (...a: any[]) => any>(apiClientType: T): InstanceType<T> {
45 const client = origMakeApiClient(apiClientType as any) as any
46 client.configuration?.middleware?.push(timeoutMiddleware)
47 return client
48 } as any
50 const objectApi = KubernetesObjectApi.makeApiClient(kubeConfig)
52 return {objectApi, kubeConfig}