Skip to content

Commit 815a8dc

Browse files
committed
chore(ci): blog sync
1 parent 0af5ff6 commit 815a8dc

File tree

1 file changed

+287
-0
lines changed

1 file changed

+287
-0
lines changed

data/blog/post-44.mdx

Lines changed: 287 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,287 @@
1+
---
2+
title: 使用字节的 TRAE 开发一个简单的 node 服务
3+
date: 2025-01-21T04:12:35Z
4+
slug: post-44
5+
author: chaseFunny:https://github.com/chaseFunny
6+
tags: ["AI","编辑器"]
7+
---
8+
9+
![ofXcwflHCsxf](https://blog-1304565468.cos.ap-shanghai.myqcloud.com/work/ofXcwflHCsxf.png)
10+
11+
大家好我是 luckySnail。在浏览流媒体的时候,发现都在推荐这个工具,字节刚刚发布了 AI 编辑器 - TRAE(The Real AI Engineer),真正的 AI 引擎吗?,必须赶紧体验一波,刚好想要开发一个小工具,希望它不要让我失望。偷偷说一下它已经让 windows 用户失望了,因为它目前仅支持 mac 电脑。你可以看冴羽的这篇了解TRAE:https://juejin.cn/post/7461825527059611686
12+
13+
## 初体验
14+
15+
让我们新建一个文件夹,为什么叫这个名字,接下来你就知道了。
16+
17+
![image-20250120234325232](https://blog-1304565468.cos.ap-shanghai.myqcloud.com/work/image-20250120234325232.png)
18+
19+
接下来我们要做一个工具来帮我监控我的公司项目是否都正常运行。如果出问题了,就需要赶紧通知我出事了,赶紧爬起来修 bug !
20+
21+
简单的梳理了一下需求,我使用了它的 builder 能力来初始化项目,提问:“我要做一个小的工具来帮我们监控我的公司项目是否都正常运行。如果出问题了,就需要赶紧通知我出事了,赶紧修 bug 。通知方式是邮箱通知,使用前端技术实现,我如何实现?我目前调研可以使用 Playwright 来做充分的网站可用性检测,使用nodemailer 来进行邮箱通知,由于 nodemailer 是必须 node 环境,所以你需要给我搭建一个 node 服务”,这里我是预先告诉了它如何实现,防止它给出不合理的实现方式。
22+
23+
然后它很快理解了我们的需求,并且搭建好了一个基础服务:
24+
25+
![image-20250121022615877](https://blog-1304565468.cos.ap-shanghai.myqcloud.com/work/image-20250121022615877.png)
26+
27+
启动项目后发现邮箱服务是有问题的,于是我把错误信息给它,然后问它为什么?如何修复?但是会出现:
28+
29+
![image-20250121011726558](https://blog-1304565468.cos.ap-shanghai.myqcloud.com/work/image-20250121011726558.png)
30+
31+
于是我只能切换 chat 模式,发现是正常的,我把问题和相关代码(使用引用能力)给到它。它也很快发现了问题,然后给出了解决的方法。
32+
33+
我模拟了一个网站出现问题的场景,然后我们可以看到当检查网站存在问题的时候,就会触发发送邮件的逻辑:
34+
35+
![image-20250121012111907](https://blog-1304565468.cos.ap-shanghai.myqcloud.com/work/image-20250121012111907.png)
36+
37+
到这里基本的流程算是跑通了,我们可以继续提问 AI,代码层面是否可以继续优化:
38+
39+
![image-20250121020151382](https://blog-1304565468.cos.ap-shanghai.myqcloud.com/work/image-20250121020151382.png)
40+
41+
它给出了一些比较好的建议,我们可以点击“全部接受”,然后先安装依赖,再次启动查看一下效果:
42+
43+
![image-20250121020340837](https://blog-1304565468.cos.ap-shanghai.myqcloud.com/work/image-20250121020340837.png)
44+
45+
这一次,它给出了更加细致的日志信息,但是我们发现最后一个 error 不太正常,我们问一下 AI 这个是否是正常日志,AI 发现了问题,并进行了修复,我们重启验证逻辑没有问题
46+
47+
![image-20250121020902787](https://blog-1304565468.cos.ap-shanghai.myqcloud.com/work/image-20250121020902787.png)
48+
49+
邮箱也收到了告警信息!
50+
51+
到这里其实基本的牛马已经做好了,它能够实时的帮我监控网站是否运行良好,保证服务异常及时通知到人。但是真正场景下,需要的不仅仅是网站正常加载,还有很多其他需要监控的东西。
52+
53+
下面我们来看看 AI 的代码水平怎么样吧!
54+
55+
```js
56+
const { chromium } = require("@playwright/test");
57+
const nodemailer = require("nodemailer");
58+
const cron = require("node-cron");
59+
const winston = require("winston"); // 添加日志库
60+
61+
// 配置日志
62+
const logger = winston.createLogger({
63+
format: winston.format.combine(winston.format.timestamp(), winston.format.json()),
64+
transports: [
65+
new winston.transports.File({ filename: "error.log", level: "error" }),
66+
new winston.transports.File({ filename: "combined.log" }),
67+
new winston.transports.Console(),
68+
],
69+
});
70+
71+
// 邮件配置
72+
const transporter = nodemailer.createTransport({
73+
host: "smtp.qq.com",
74+
port: 465, // 修改为465端口
75+
secure: true, // 设置为true
76+
auth: {
77+
user: "[email protected]", // 补充完整的QQ邮箱地址
78+
pass: "xxxx", // QQ邮箱授权码
79+
},
80+
});
81+
82+
// 要监控的网站列表
83+
const websites = [
84+
{
85+
name: "老鱼简历",
86+
url: "https://laoyujianli.com",
87+
checkElements: [".laoyu-page-container", ".new-index-page", ".template-item"],
88+
},
89+
{
90+
name: "编程导航",
91+
url: "https://codefather.cn",
92+
checkElements: [".ant-layout", ".user-name"],
93+
},
94+
{
95+
name: "面试鸭",
96+
url: "https://mianshiya.cn", // 移除多余的空格
97+
checkElements: ["#indexPage", ".ant-list-item", "#ccc"],
98+
retryCount: 3, // 添加重试次数
99+
retryDelay: 5000, // 重试延迟时间(毫秒)
100+
},
101+
];
102+
103+
// 浏览器实例管理
104+
let browserInstance = null;
105+
async function getBrowser() {
106+
if (!browserInstance) {
107+
browserInstance = await chromium.launch({
108+
timeout: 60000,
109+
});
110+
}
111+
return browserInstance;
112+
}
113+
114+
// 检查网站可用性
115+
async function checkWebsite(site) {
116+
const startTime = Date.now();
117+
const browser = await getBrowser();
118+
const context = await browser.newContext({
119+
userAgent:
120+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
121+
});
122+
123+
try {
124+
const page = await context.newPage();
125+
logger.info(`正在检查网站: ${site.name}`);
126+
127+
let lastError;
128+
// 添加重试机制
129+
for (let i = 0; i < (site.retryCount || 1); i++) {
130+
try {
131+
// 设置页面加载超时时间
132+
await page.goto(site.url, {
133+
timeout: 30000,
134+
waitUntil: "networkidle", // 等待网络空闲
135+
});
136+
137+
// 检查关键元素是否存在
138+
for (const selector of site.checkElements) {
139+
try {
140+
await page.waitForSelector(selector, { timeout: 5000 });
141+
} catch (elementError) {
142+
console.log(`元素 ${selector} 未找到,继续检查其他元素`);
143+
}
144+
}
145+
146+
console.log(`${site.name} 检查通过`);
147+
return { success: true };
148+
} catch (error) {
149+
lastError = error;
150+
if (i < (site.retryCount || 1) - 1) {
151+
console.log(`${site.name} 检查失败,等待 ${site.retryDelay || 5000}ms 后重试...`);
152+
await new Promise((resolve) => setTimeout(resolve, site.retryDelay || 5000));
153+
}
154+
}
155+
}
156+
157+
console.error(`${site.name} 检查失败:`, lastError.message);
158+
return {
159+
success: false,
160+
error: lastError.message,
161+
};
162+
} finally {
163+
await context.close(); // 只关闭 context,不关闭浏览器
164+
}
165+
}
166+
167+
// 添加进程退出时的清理
168+
process.on("SIGTERM", async () => {
169+
logger.info("服务正在关闭...");
170+
if (browserInstance) {
171+
await browserInstance.close();
172+
browserInstance = null;
173+
}
174+
process.exit(0);
175+
});
176+
177+
process.on("SIGINT", async () => {
178+
logger.info("服务正在关闭...");
179+
if (browserInstance) {
180+
await browserInstance.close();
181+
browserInstance = null;
182+
}
183+
process.exit(0);
184+
});
185+
186+
// 发送告警邮件
187+
async function sendAlertEmail(site, error) {
188+
const mailOptions = {
189+
from: "[email protected]", // 使用完整的发件人邮箱
190+
to: "[email protected]", // 使用完整的收件人邮箱
191+
subject: `🚨 网站异常告警: ${site.name}`,
192+
html: `
193+
<h2>网站监控告警</h2>
194+
<p><strong>网站名称:</strong> ${site.name}</p>
195+
<p><strong>网站地址:</strong> ${site.url}</p>
196+
<p><strong>错误信息:</strong> ${error}</p>
197+
<p><strong>发生时间:</strong> ${new Date().toLocaleString()}</p>
198+
`,
199+
};
200+
201+
try {
202+
await transporter.sendMail(mailOptions);
203+
console.log(`已发送告警邮件 - ${site.name}`);
204+
} catch (error) {
205+
console.error("发送邮件失败:", error);
206+
// 如果是认证错误,输出更详细的信息
207+
if (error.code === "EAUTH") {
208+
console.error("邮箱认证失败,请检查以下内容:");
209+
console.error("1. 确保QQ邮箱已开启SMTP服务");
210+
console.error("2. 确保使用的是正确的授权码而不是邮箱密码");
211+
console.error("3. 访问 https://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256 获取帮助");
212+
}
213+
}
214+
}
215+
216+
// 执行监控任务
217+
async function runMonitoring() {
218+
// 添加并发限制
219+
const concurrentLimit = 2;
220+
const chunks = [];
221+
for (let i = 0; i < websites.length; i += concurrentLimit) {
222+
chunks.push(websites.slice(i, i + concurrentLimit));
223+
}
224+
225+
for (const chunk of chunks) {
226+
await Promise.all(
227+
chunk.map(async (site) => {
228+
try {
229+
const result = await checkWebsite(site);
230+
if (!result.success) {
231+
await sendAlertEmail(site, result.error);
232+
}
233+
} catch (error) {
234+
logger.error(`监控任务执行失败 (${site.name}):`, {
235+
error: error.message,
236+
stack: error.stack,
237+
});
238+
}
239+
})
240+
);
241+
}
242+
}
243+
244+
// 添加优雅退出处理
245+
process.on("SIGTERM", async () => {
246+
logger.info("服务正在关闭...");
247+
if (browserInstance) {
248+
await browserInstance.close();
249+
}
250+
process.exit(0);
251+
});
252+
253+
// 设置定时任务,每5分钟执行一次监控
254+
cron.schedule("*/5 * * * *", () => {
255+
console.log("开始执行网站监控...");
256+
runMonitoring();
257+
});
258+
259+
// 立即执行一次监控
260+
console.log("启动网站监控服务...");
261+
runMonitoring();
262+
263+
```
264+
265+
你觉得写的怎么样呢?我觉得蛮好的:
266+
267+
- 代码逻辑清晰,每个函数都符合单一原则,开发中它也提醒我要把 websites 配置信息单独创建文件存储
268+
- 能够基于代码进行重构优化,使用社区流行的 winston 日志库来记录信息
269+
- 有重试,try catch 兜底逻辑
270+
271+
272+
273+
## 总结
274+
275+
1. TRAE 的 UI 和交互不输 cursor
276+
2. builder 模式下,提出一个需求,它能快速帮我拆解需求,生成项目,安装依赖,启动项目到最后的 web 预览。这对没有接触过编程的人更加友好
277+
3. 在有些时候,它也会乱说,明明有问题,但是硬说已经解决了!
278+
4. 连接不稳定,经常网络错误,这个非常影响开发体验
279+
5. 免费使用 claude 3.5 和 chatGpt 很香。
280+
6. 代码块右上角的一些能力非常好用,例如应用功能,能够智能的把相关的内容进行替换,然后通过 diff 清晰的让你知道你修改了什么
281+
7. 感觉模型深度链接了代码上下文,能给出和我目前项目相关的代码
282+
283+
284+
需要深度使用才能发现它更多使用场景!
285+
286+
---
287+
此文自动发布于:<a href="https://github.com/coderPerseus/blog/issues/44" target="_blank">github issues</a>

0 commit comments

Comments
 (0)