Skip to content

Commit

Permalink
perf: 简化vercel部署流程,添加自动同步环境变量脚本
Browse files Browse the repository at this point in the history
  • Loading branch information
TBXark committed Nov 14, 2024
1 parent f419bf6 commit 463cf14
Show file tree
Hide file tree
Showing 9 changed files with 73 additions and 34 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -152,4 +152,5 @@ wrangler.toml
/dist/index.cjs
/dist/index.d.ts
/dist/src
/packages/**/dist
/packages/**/dist
.env*.local
5 changes: 3 additions & 2 deletions doc/cn/VERCEL.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

### 自动部署

[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FTBXark%2FChatGPT-Telegram-Workers&env=UPSTASH_REDIS_REST_URL,UPSTASH_REDIS_REST_TOKEN,VERCEL_DOMAIN,TELEGRAM_AVAILABLE_TOKENS&project-name=chatgpt-telegram-workers&repository-name=ChatGPT-Telegram-Workers&demo-title=ChatGPT-Telegram-Workers&demo-description=Deploy%20your%20own%20Telegram%20ChatGPT%20bot%20on%20Cloudflare%20Workers%20with%20ease.&demo-url=https%3A%2F%2Fchatgpt-telegram-workers.vercel.app)
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FTBXark%2FChatGPT-Telegram-Workers&env=UPSTASH_REDIS_REST_URL,UPSTASH_REDIS_REST_TOKEN,TELEGRAM_AVAILABLE_TOKENS&project-name=chatgpt-telegram-workers&repository-name=ChatGPT-Telegram-Workers&demo-title=ChatGPT-Telegram-Workers&demo-description=Deploy%20your%20own%20Telegram%20ChatGPT%20bot%20on%20Cloudflare%20Workers%20with%20ease.&demo-url=https%3A%2F%2Fchatgpt-telegram-workers.vercel.app)

### 手动部署

Expand All @@ -14,4 +14,5 @@ pnpm deploy:vercel
```

1. pnpm deploy:vercel 过程中可能需要登陆Vercel账号
2. 首次部署由于缺少环境变量,页面会报错,需要手动前往Vercel控制台添加环境变量,然后重新部署生效
2. 首次部署由于缺少环境变量,页面会报错,需要手动前往Vercel控制台添加环境变量,然后重新部署生效
3. 你可以复用cloudflare workers的`wrangler.toml`配置文件,只需要执行`pnpm run vercel:syncenv`即可同步环境变量到Vercel, vercel修改环境变量后需要重新部署才能生效
5 changes: 3 additions & 2 deletions doc/en/VERCEL.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ The sample code provided in `/packages/app/vercel` can complete the Vercel deplo

### Automatic Deployment

[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FTBXark%2FChatGPT-Telegram-Workers&env=UPSTASH_REDIS_REST_URL,UPSTASH_REDIS_REST_TOKEN,VERCEL_DOMAIN,TELEGRAM_AVAILABLE_TOKENS&project-name=chatgpt-telegram-workers&repository-name=ChatGPT-Telegram-Workers&demo-title=ChatGPT-Telegram-Workers&demo-description=Deploy%20your%20own%20Telegram%20ChatGPT%20bot%20on%20Cloudflare%20Workers%20with%20ease.&demo-url=https%3A%2F%2Fchatgpt-telegram-workers.vercel.app)
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FTBXark%2FChatGPT-Telegram-Workers&env=UPSTASH_REDIS_REST_URL,UPSTASH_REDIS_REST_TOKEN,TELEGRAM_AVAILABLE_TOKENS&project-name=chatgpt-telegram-workers&repository-name=ChatGPT-Telegram-Workers&demo-title=ChatGPT-Telegram-Workers&demo-description=Deploy%20your%20own%20Telegram%20ChatGPT%20bot%20on%20Cloudflare%20Workers%20with%20ease.&demo-url=https%3A%2F%2Fchatgpt-telegram-workers.vercel.app)

### Manual deployment

Expand All @@ -13,4 +13,5 @@ pnpm install
pnpm deploy:vercel
```
1. You may need to log in to your Vercel account during the pnpm deploy:vercel process.
2. For the first deployment, due to missing environment variables, the page will report errors. You need to manually go to the Vercel console to add environment variables, and then redeploy to take effect.
2. For the first deployment, due to missing environment variables, the page will report errors. You need to manually go to the Vercel console to add environment variables, and then redeploy to take effect.
3. You can reuse the `wrangler.toml` configuration file of Cloudflare Workers, just need to execute `pnpm run vercel:syncenv` to synchronize environment variables to Vercel. After Vercel modifies the environment variables, a redeployment is required for them to take effect.
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"deploy:workersnext": "pnpm run build:workersnext && TOML_PATH=$INIT_CWD/wrangler.toml pnpm --filter @chatgpt-telegram-workers/workers-next deploy",
"deploy:vercel": "pnpm run build:vercel && vercel --prod",
"start:local": "pnpm run build:local && CONFIG_PATH=$INIT_CWD/config.json TOML_PATH=$INIT_CWD/wrangler.toml pnpm --filter @chatgpt-telegram-workers/local start",
"vercel:syncenv": "tsx scripts/vercel-sync-env.ts && vercel --prod",
"clean": "pnpm -r run clean",
"wrangler": "wrangler"
},
Expand All @@ -58,6 +59,7 @@
"vite-plugin-dts": "^4.3.0",
"wrangler": "^3.86.1",
"vercel": "^39.0.0",
"toml": "^3.0.0",
"tsx": "^4.19.2"
}
}
3 changes: 2 additions & 1 deletion packages/apps/vercel/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"types": "./dist/index.d.ts",
"scripts": {
"build": "pnpm vite build",
"clean": "rm -rf dist"
"clean": "rm -rf dist",
"sync": "tsx src/sync.ts"
},
"dependencies": {
"@chatgpt-telegram-workers/core": "workspace:*",
Expand Down
24 changes: 18 additions & 6 deletions packages/apps/vercel/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ export default async function (request: VercelRequest, response: VercelResponse)
const {
UPSTASH_REDIS_REST_URL = '',
UPSTASH_REDIS_REST_TOKEN = '',
VERCEL_DOMAIN = '',
VERCEL_PROJECT_PRODUCTION_URL = '',
} = process.env;
for (const [KEY, VALUE] of Object.entries({ UPSTASH_REDIS_REST_URL, UPSTASH_REDIS_REST_TOKEN, VERCEL_DOMAIN })) {
for (const [KEY, VALUE] of Object.entries({ UPSTASH_REDIS_REST_URL, UPSTASH_REDIS_REST_TOKEN })) {
if (!VALUE) {
response.status(500).send({
response.status(500).json({
error: `${KEY} is required`,
message: 'Set environment variables and redeploy',
});
Expand All @@ -29,7 +29,16 @@ export default async function (request: VercelRequest, response: VercelResponse)
if (request.body) {
body = JSON.stringify(request.body);
}
const newReq = new Request(VERCEL_DOMAIN + request.url, {
if (request.url === '/vercel/debug') {
response.status(200).json({
message: 'OK',
base: VERCEL_PROJECT_PRODUCTION_URL,
});
return;
}
const url = `https://${VERCEL_PROJECT_PRODUCTION_URL}${request.url}`;
console.log(`Forwarding request to ${url}`);
const newReq = new Request(url, {
method: request.method,
headers: Object.entries(request.headers).reduce((acc, [key, value]) => {
if (value === undefined) {
Expand All @@ -47,11 +56,14 @@ export default async function (request: VercelRequest, response: VercelResponse)
body,
});
const res = await router.fetch(newReq);
for (const [key, value] of res.headers.entries()) {
response.setHeader(key, value);
}
response.status(res.status).send(await res.text());
} catch (e) {
response.status(500).send(JSON.stringify({
response.status(500).json({
message: (e as Error).message,
stack: (e as Error).stack,
}, null, 2));
});
}
}
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 0 additions & 22 deletions scripts/gen-vercel-env.ts

This file was deleted.

40 changes: 40 additions & 0 deletions scripts/vercel-sync-env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { execSync } from 'node:child_process';
import fs from 'node:fs/promises';
import { parse } from 'toml';

async function main() {
const {
TOML_PATH = 'wrangler.toml',
VERCEL_ENV = 'production',
VERCEL_BIN = './node_modules/.bin/vercel',
} = process.env;

const envs = execSync(`${VERCEL_BIN} env ls ${VERCEL_ENV}`, {
encoding: 'utf-8',
}).trim().split('\n').map(l => l.trim()).slice(1).map(l => l.split(/\s+/)[0]).map(l => l.replace(/[^\x20-\x7E]/g, '').replace(/\[\d+m/g, ''));
const usedKeys = new Set<string>();
usedKeys.add('UPSTASH_REDIS_REST_URL');
usedKeys.add('UPSTASH_REDIS_REST_TOKEN');
const { vars } = parse(await fs.readFile(TOML_PATH, 'utf-8'));
for (const [key, value] of Object.entries(vars)) {
try {
usedKeys.add(key);
execSync(`${VERCEL_BIN} env add ${key} ${VERCEL_ENV} --force`, {
input: `${value}`,
encoding: 'utf-8',
});
} catch (e) {
console.error(e);
}
}
for (const key of envs) {
if (!usedKeys.has(key)) {
console.log(`Delete ${key}?)`);
execSync(`${VERCEL_BIN} env rm ${key} ${VERCEL_ENV}`, {
encoding: 'utf-8',
});
}
}
}

main().catch(console.error);

0 comments on commit 463cf14

Please sign in to comment.