🌳
pt0/serverF/dbF/decompForkedKubeQsF.mts
1import { getEnvConf } from '../envConfF.mts'
4import { ptDir } from '../ptDirF.mts'
7import { qsToUriH } from '../qsToUriF.mts'
8import { chalkRed } from '../libChalkF.mts'
12import os from 'os'
13import * as _ from 'lodash-es'
18import type { DbConnInfo } from './dbTypesF.mts'
20const getForkedQs = ({secretName}: {secretName: string}) => {
21 if (secretName == disabledSecret) return
23 const secretVal = getPlainMappedSec(secretName as any)
24 guardQsSecExist({secretName, secretVal})
26 return secretVal
29export const decomposeForkedKubeQs = async ({qsName, dbFork}: {qsName: string, dbFork?: boolean | string}): Promise<DbConnInfo> => {
30 const secretsMapping = getEnvConf().secretsMapping || {}
31 const forkedQsName = secretsMapping[qsName] || qsName
33 const baseQs = getForkedQs({secretName: forkedQsName})
34 assertDefined(baseQs, {qsName})
36 throwIf(() => _.isBoolean(dbFork) && !dbFork)
38 const dbQs = baseQs
40 return {...await decomposeKubeQs(dbQs), qsName: forkedQsName}
43export const guardQsSecExist = ({secretName, secretVal}: {secretName: string, secretVal: string | undefined}) => {
44 if (secretVal) return
45 const secretPath = replaceStrict(secretsDir, ptDir + '/', '') + '/' + secretName
46 console.trace()
47 console.log(chalkRed(`
48Missing required secret: ${secretPath}
49- If you are trying to connect to an existing database:
50 please ask the db admin to send you their ${secretPath}
51- If you are setting up a new database:
52 please make sure ${secretPath} exists and is connectable
53`))
54 throw new PtErr('missingSecret', {secretName})
57export const decomposeKubeQs = async (dbQs: string): Promise<Omit<DbConnInfo, 'qsName'>> => {
60 const _urlObj = qsToUriH(dbQs as any)
62 const {password, username, svcName, host: hostWPort} = _urlObj
64 const svcInfo = await getReqSvcInfo(svcName)
66 const {cluster_name, ips, isCnPg} = svcInfo
67 let {enableSsl=false, nodePort, ptNodePortNo} = svcInfo
68 nodePort ||= ptNodePortNo
70 const hostname = ips[0]
72 const extIpPort = [hostname, nodePort].join(':')
74 let extQs = (() => {
75 const fromStr = `@${hostWPort}`
76 if (!runPgOnKlustCtx.getStore()) {
77 if (isDevPc || getInCluster() != cluster_name) {
78 return replaceStrict(dbQs, fromStr, `@${extIpPort}`)
79 }
80 }
81 if (isCnPg) return dbQs
82 return replaceStrict(dbQs, fromStr, `@${svcName}.default.svc.cluster.local:5432`)
83 })()
85 const addParams = enableSsl ? {sslmode: 'require'} : {}
86 extQs += addPgParams(addParams)
88 return {
89 ...svcInfo,
90 extQs, enableSsl,
91 dbQs, password, username, svcName,
92 nodePort, hostname,
93 }
96const addPgParams = (params: Record<string, any>) => {
97 params = {
98 application_name: os.hostname(),
99 ...params,
100 }
101 return '?' + new URLSearchParams(params)