来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
314 lines
9.4 KiB
JavaScript
314 lines
9.4 KiB
JavaScript
/**
|
|
* Configure CLB aideiver (lb-3g4yhjra):
|
|
* - HTTPS:443 + HTTP:80 (redirect)
|
|
* - / → two H5 :80
|
|
* - /api → two API :3001
|
|
*
|
|
* Usage: node server/scripts/tencent-clb-setup-aideiver.mjs
|
|
*/
|
|
import { loadTencentCredentials, tc3Request } from './tencent-lib.mjs';
|
|
|
|
const REGION = 'ap-nanjing';
|
|
const LB_ID = 'lb-3g4yhjra';
|
|
const CERT_ID = 'VkHZDj8B'; // xdjchuanhui.com
|
|
const DOMAINS = ['www.xdjchuanhui.com', 'xdjchuanhui.com'];
|
|
|
|
const H5 = [
|
|
{ InstanceId: 'ins-9zdly5wm', Port: 80, Weight: 10 }, // test-h5
|
|
{ InstanceId: 'ins-hvq9s3gi', Port: 80, Weight: 10 }, // test-h51
|
|
];
|
|
const API = [
|
|
{ InstanceId: 'ins-dn3v0znu', Port: 3001, Weight: 10 }, // test-api
|
|
{ InstanceId: 'ins-bzgxnhke', Port: 3001, Weight: 10 }, // test-api1
|
|
];
|
|
|
|
function sleep(ms) {
|
|
return new Promise((r) => setTimeout(r, ms));
|
|
}
|
|
|
|
async function clb(cred, action, payload) {
|
|
let lastErr;
|
|
for (let attempt = 1; attempt <= 12; attempt++) {
|
|
const json = await tc3Request({
|
|
...cred,
|
|
service: 'clb',
|
|
region: REGION,
|
|
version: '2018-03-17',
|
|
action,
|
|
payload,
|
|
});
|
|
if (!json.Response?.Error) return json.Response;
|
|
const e = json.Response.Error;
|
|
lastErr = new Error(`${action}: ${e.Code} ${e.Message}`);
|
|
if (
|
|
e.Code === 'FailedOperation.ResourceInOperating' ||
|
|
e.Code === 'ResourceInOperating' ||
|
|
/try later/i.test(e.Message || '')
|
|
) {
|
|
console.warn(` busy (${attempt}/12), wait...`);
|
|
await sleep(5000);
|
|
continue;
|
|
}
|
|
throw lastErr;
|
|
}
|
|
throw lastErr;
|
|
}
|
|
|
|
async function waitTask(cred, taskId) {
|
|
// CLB async APIs return TaskId separately; RequestId is NOT a TaskId.
|
|
if (!taskId || String(taskId).includes('-')) return; // UUID RequestId → skip
|
|
for (let i = 0; i < 60; i++) {
|
|
const r = await clb(cred, 'DescribeTaskStatus', { TaskId: String(taskId) });
|
|
// Docs: 0 success, 1 running, 2 failed
|
|
if (r.Status === 0) return;
|
|
if (r.Status === 2) throw new Error(`Task failed TaskId=${taskId}`);
|
|
await sleep(2000);
|
|
}
|
|
}
|
|
|
|
async function findListeners(cred) {
|
|
const r = await clb(cred, 'DescribeListeners', { LoadBalancerId: LB_ID });
|
|
return r.Listeners || [];
|
|
}
|
|
|
|
async function ensureHttpsListener(cred) {
|
|
const listeners = await findListeners(cred);
|
|
let https = listeners.find((l) => l.Protocol === 'HTTPS' && l.Port === 443);
|
|
if (https) {
|
|
console.log('HTTPS listener exists', https.ListenerId);
|
|
return https.ListenerId;
|
|
}
|
|
console.log('Creating HTTPS:443 listener...');
|
|
const r = await clb(cred, 'CreateListener', {
|
|
LoadBalancerId: LB_ID,
|
|
Ports: [443],
|
|
Protocol: 'HTTPS',
|
|
ListenerNames: ['https-443'],
|
|
Certificate: {
|
|
SSLMode: 'UNIDIRECTIONAL',
|
|
CertId: CERT_ID,
|
|
},
|
|
SniSwitch: 0,
|
|
HealthCheck: {
|
|
HealthSwitch: 1,
|
|
HttpCheckPath: '/',
|
|
HttpCheckMethod: 'HEAD',
|
|
HttpCode: 31,
|
|
IntervalTime: 5,
|
|
HealthNum: 2,
|
|
UnHealthNum: 3,
|
|
TimeOut: 3,
|
|
},
|
|
Scheduler: 'WRR',
|
|
});
|
|
await waitTask(cred, r.RequestId);
|
|
await sleep(3000);
|
|
const again = await findListeners(cred);
|
|
https = again.find((l) => l.Protocol === 'HTTPS' && l.Port === 443);
|
|
if (!https) throw new Error('HTTPS listener not found after create');
|
|
console.log('HTTPS listener', https.ListenerId);
|
|
return https.ListenerId;
|
|
}
|
|
|
|
async function ensureHttpListener(cred) {
|
|
const listeners = await findListeners(cred);
|
|
let http = listeners.find((l) => l.Protocol === 'HTTP' && l.Port === 80);
|
|
if (http) {
|
|
console.log('HTTP listener exists', http.ListenerId);
|
|
return http.ListenerId;
|
|
}
|
|
console.log('Creating HTTP:80 listener...');
|
|
const r = await clb(cred, 'CreateListener', {
|
|
LoadBalancerId: LB_ID,
|
|
Ports: [80],
|
|
Protocol: 'HTTP',
|
|
ListenerNames: ['http-80'],
|
|
HealthCheck: {
|
|
HealthSwitch: 1,
|
|
HttpCheckPath: '/',
|
|
HttpCheckMethod: 'HEAD',
|
|
HttpCode: 31,
|
|
IntervalTime: 5,
|
|
HealthNum: 2,
|
|
UnHealthNum: 3,
|
|
TimeOut: 3,
|
|
},
|
|
Scheduler: 'WRR',
|
|
});
|
|
await waitTask(cred, r.RequestId);
|
|
await sleep(3000);
|
|
const again = await findListeners(cred);
|
|
http = again.find((l) => l.Protocol === 'HTTP' && l.Port === 80);
|
|
if (!http) throw new Error('HTTP listener not found after create');
|
|
console.log('HTTP listener', http.ListenerId);
|
|
return http.ListenerId;
|
|
}
|
|
|
|
async function listRules(cred, listenerId) {
|
|
const r = await clb(cred, 'DescribeListeners', {
|
|
LoadBalancerId: LB_ID,
|
|
ListenerIds: [listenerId],
|
|
});
|
|
const listener = (r.Listeners || [])[0];
|
|
return listener?.Rules || [];
|
|
}
|
|
|
|
async function ensureRule(cred, listenerId, domain, url, healthPath, defaultServer = false) {
|
|
const rules = await listRules(cred, listenerId);
|
|
const existing = rules.find((x) => x.Domain === domain && x.Url === url);
|
|
if (existing) {
|
|
console.log(`Rule exists ${domain}${url}`, existing.LocationId);
|
|
return existing.LocationId;
|
|
}
|
|
console.log(`Creating rule ${domain}${url} ...`);
|
|
const r = await clb(cred, 'CreateRule', {
|
|
LoadBalancerId: LB_ID,
|
|
ListenerId: listenerId,
|
|
Rules: [
|
|
{
|
|
Domain: domain,
|
|
Url: url,
|
|
SessionExpireTime: 0,
|
|
HealthCheck: {
|
|
HealthSwitch: 1,
|
|
HttpCheckPath: healthPath,
|
|
HttpCheckMethod: 'GET',
|
|
HttpCode: 31,
|
|
IntervalTime: 5,
|
|
HealthNum: 2,
|
|
UnHealthNum: 3,
|
|
TimeOut: 3,
|
|
},
|
|
Scheduler: 'WRR',
|
|
ForwardType: 'HTTP',
|
|
DefaultServer: defaultServer,
|
|
},
|
|
],
|
|
});
|
|
await waitTask(cred, r.RequestId);
|
|
await sleep(3000);
|
|
const again = await listRules(cred, listenerId);
|
|
const created = again.find((x) => x.Domain === domain && x.Url === url);
|
|
if (!created) throw new Error(`Rule not found after create: ${domain}${url}`);
|
|
console.log(`Rule ${domain}${url}`, created.LocationId);
|
|
return created.LocationId;
|
|
}
|
|
|
|
async function ensureTargets(cred, listenerId, locationId, targets, label) {
|
|
const desc = await clb(cred, 'DescribeTargets', {
|
|
LoadBalancerId: LB_ID,
|
|
ListenerIds: [listenerId],
|
|
});
|
|
const listeners = desc.Listeners || [];
|
|
const loc =
|
|
listeners
|
|
.flatMap((l) => l.Rules || [])
|
|
.find((r) => r.LocationId === locationId) || null;
|
|
const current = new Set(
|
|
(loc?.Targets || []).map((t) => `${t.InstanceId}:${t.Port}`)
|
|
);
|
|
const missing = targets.filter((t) => !current.has(`${t.InstanceId}:${t.Port}`));
|
|
if (missing.length === 0) {
|
|
console.log(`Targets OK for ${label}`);
|
|
return;
|
|
}
|
|
console.log(`Registering ${missing.length} targets for ${label}...`);
|
|
const r = await clb(cred, 'RegisterTargets', {
|
|
LoadBalancerId: LB_ID,
|
|
ListenerId: listenerId,
|
|
LocationId: locationId,
|
|
Targets: missing.map((t) => ({
|
|
Type: 'CVM',
|
|
InstanceId: t.InstanceId,
|
|
Port: t.Port,
|
|
Weight: t.Weight,
|
|
})),
|
|
});
|
|
await waitTask(cred, r.TaskId || r.RequestId);
|
|
await sleep(5000);
|
|
console.log(`Registered targets for ${label}`);
|
|
}
|
|
|
|
async function tryAutoRewrite(cred, httpsListenerId, httpListenerId) {
|
|
try {
|
|
console.log('Enabling HTTP→HTTPS rewrite...');
|
|
const r = await clb(cred, 'AutoRewrite', {
|
|
LoadBalancerId: LB_ID,
|
|
ListenerId: httpsListenerId,
|
|
Domains: DOMAINS,
|
|
});
|
|
await waitTask(cred, r.RequestId);
|
|
console.log('AutoRewrite OK');
|
|
} catch (e) {
|
|
console.warn('AutoRewrite skipped:', e.message);
|
|
// Fallback: bind same H5 targets on HTTP / for both domains so 80 still serves
|
|
for (const domain of DOMAINS) {
|
|
const loc = await ensureRule(cred, httpListenerId, domain, '/', '/', domain === DOMAINS[0]);
|
|
await ensureTargets(cred, httpListenerId, loc, H5, `http ${domain}/`);
|
|
}
|
|
}
|
|
}
|
|
|
|
async function main() {
|
|
const { secretId, secretKey } = loadTencentCredentials();
|
|
const cred = { secretId, secretKey };
|
|
|
|
const httpsId = await ensureHttpsListener(cred);
|
|
const httpId = await ensureHttpListener(cred);
|
|
|
|
for (const domain of DOMAINS) {
|
|
const isPrimary = domain === DOMAINS[0];
|
|
const h5Loc = await ensureRule(cred, httpsId, domain, '/', '/', isPrimary);
|
|
await ensureTargets(cred, httpsId, h5Loc, H5, `https ${domain}/`);
|
|
|
|
const apiLoc = await ensureRule(cred, httpsId, domain, '/api', '/api/health', false);
|
|
await ensureTargets(cred, httpsId, apiLoc, API, `https ${domain}/api`);
|
|
}
|
|
|
|
await tryAutoRewrite(cred, httpsId, httpId);
|
|
|
|
const finalListeners = await findListeners(cred);
|
|
const targets = await clb(cred, 'DescribeTargets', { LoadBalancerId: LB_ID });
|
|
console.log('\n=== DONE ===');
|
|
console.log(
|
|
JSON.stringify(
|
|
{
|
|
listeners: finalListeners.map((l) => ({
|
|
id: l.ListenerId,
|
|
protocol: l.Protocol,
|
|
port: l.Port,
|
|
rules: (l.Rules || []).map((r) => ({
|
|
domain: r.Domain,
|
|
url: r.Url,
|
|
locationId: r.LocationId,
|
|
})),
|
|
})),
|
|
targetsSummary: (targets.Listeners || []).map((l) => ({
|
|
listener: l.ListenerId,
|
|
protocol: l.Protocol,
|
|
port: l.Port,
|
|
rules: (l.Rules || []).map((r) => ({
|
|
domain: r.Domain,
|
|
url: r.Url,
|
|
targets: (r.Targets || []).map((t) => ({
|
|
instance: t.InstanceId,
|
|
port: t.Port,
|
|
weight: t.Weight,
|
|
health: t.HealthStatus,
|
|
})),
|
|
})),
|
|
})),
|
|
dnsHint:
|
|
'CNAME www/xdjchuanhui.com -> lb-3g4yhjra-4f9thqng7wo1xvae.clb.nj-tencentclb.net',
|
|
},
|
|
null,
|
|
2
|
|
)
|
|
);
|
|
}
|
|
|
|
main().catch((e) => {
|
|
console.error(e);
|
|
process.exit(1);
|
|
});
|