返回 CodeWhale
index.mjs
1 import { ThreadStore, createRuntimeClient } from "../../bridge-core/src/lib.mjs";
2 import { DingTalkBridge, createReplySender, readConfig } from "./lib.mjs";
3 import { mkdir, open, unlink } from "node:fs/promises";
4 import path from "node:path";
5
6 async function main() {
7 const config = readConfig();
8 if (process.argv.includes("--validate-config")) {
9 console.log("DingTalk bridge configuration is valid; no connection was opened.");
10 return;
11 }
12 const sdkWarning = console.warn.bind(console);
13 console.warn = () => sdkWarning("DingTalk SDK warning; connection state is retained.");
14 const { DWClient, TOPIC_ROBOT } = await import("dingtalk-stream");
15 const client = new DWClient({ clientId: config.clientId, clientSecret: config.clientSecret, debug: false, autoReconnect: true });
16 await mkdir(path.dirname(config.statePath), { recursive: true, mode: 0o700 });
17 const lockPath = `${config.statePath}.lock`;
18 const lock = await open(lockPath, "wx", 0o600);
19 let store;
20 try {
21 await lock.writeFile(String(process.pid));
22 await lock.sync();
23 store = await ThreadStore.open(config.statePath, { messageLimit: 2000, privateMode: true });
24 } catch (error) {
25 await lock.close();
26 await unlink(lockPath);
27 throw error;
28 }
29 const { runtimeJson, authHeaders } = createRuntimeClient(config);
30 const bridge = new DingTalkBridge({
31 config, store, runtimeJson, sendReply: createReplySender({ client }),
32 runtimeFetch: (route, signal) => fetch(`${config.runtimeUrl}${route}`, { headers: { ...authHeaders(), accept: "text/event-stream" }, signal: AbortSignal.any([signal, AbortSignal.timeout(60000)]) }),
33 report: (message) => console.error(message)
34 });
35 client.registerCallbackListener(TOPIC_ROBOT, async (frame) => {
36 try {
37 await bridge.accept(frame, () => client.socketCallBackResponse(frame.headers.messageId, { errcode: 0, errmsg: "ok" }));
38 } catch {
39 console.error("DingTalk message was not acknowledged; durable acceptance failed.");
40 }
41 });
42 let closing = false;
43 const shutdown = async () => {
44 if (closing) return;
45 closing = true;
46 client.disconnect();
47 await bridge.stop();
48 await lock.close();
49 await unlink(lockPath);
50 };
51 for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => { void shutdown().catch(() => { process.exitCode = 1; }); });
52 try {
53 await bridge.start();
54 if (!closing) await client.connect();
55 if (!closing) console.log("DingTalk Stream bridge started; SDK reconnect is enabled.");
56 } catch (error) {
57 await shutdown();
58 throw error;
59 }
60 }
61
62 main().catch(() => { console.error("DingTalk bridge startup failed. Check configuration, runtime availability and the state lock."); process.exitCode = 1; });
63
63 lines Plain Text