Files
hose-use/src/core/http/script-engine-client.ts
T

113 lines
3.0 KiB
TypeScript

import ky from "ky";
import type { CorpConfig } from "../config/types.js";
import { createAuthClient } from "./factory.js";
import { AuthenticationError } from "../errors.js";
import {
resolveCorpCluster,
fetchHoseToken,
EKB_BASE_URL,
} from "./unity-client.js";
export const SCRIPT_ENGINE_BASE_URL = "https://piper.ekuaibao.com";
// 兼容历史常量名
export const PIPER_BASE_URL = SCRIPT_ENGINE_BASE_URL;
// 内存缓存
const scriptEngineMemoryCache = new Map<
string,
{ jwt: string; hoseToken: string; expiresAt: number }
>();
function isExpired(entry: { expiresAt: number }, refreshTtl: number): boolean {
return Date.now() >= entry.expiresAt - refreshTtl * 1000;
}
export async function fetchEasoJwt(
accessToken: string,
corpId: string,
staffId: string,
baseUrl: string = EKB_BASE_URL
): Promise<string> {
const response = await ky
.get(`${baseUrl}/api/engine/realm/$EASO/actions/jwt`, {
searchParams: { corpId },
headers: {
accesstoken: accessToken,
corpid: corpId,
staffid: staffId,
},
})
.json<{ id?: string; value?: string }>();
const token = response.id || response.value;
if (!token) {
throw new AuthenticationError("Failed to fetch EASO JWT");
}
return token;
}
/**
* 获取工作流脚本执行引擎客户端 (Workflow Script Engine Client / Piper Client)
* 适用于 MVEL、Python 等工作流代码节点的在线执行与调试
*/
export async function getScriptEngineClient(
corp: CorpConfig,
platformId: string
): Promise<ReturnType<typeof createAuthClient>> {
const refreshTtl = corp.auth?.refreshTtl ?? 300;
const cacheKey = `${corp.id}:${platformId}:script-engine`;
// 检查内存缓存
const mem = scriptEngineMemoryCache.get(cacheKey);
if (mem && !isExpired(mem, refreshTtl)) {
return createAuthClient({
prefixUrl: SCRIPT_ENGINE_BASE_URL,
getHeaders: () => ({
Authorization: `Bearer ${mem.jwt}`,
platformid: platformId,
}),
onUnauthorized: () => {
scriptEngineMemoryCache.delete(cacheKey);
},
});
}
const corpId = corp.corpId || corp.credentials.corpId;
const staffId = corp.staffId || corp.credentials.staffId;
const environment = resolveCorpCluster(corp);
const baseUrl = corp.baseUrl || EKB_BASE_URL;
// 重新换取
const hoseToken = await fetchHoseToken(
corp.credentials.accessToken,
corpId,
environment
);
const easoJwt = await fetchEasoJwt(
corp.credentials.accessToken,
corpId,
staffId,
baseUrl
);
const entry = {
jwt: easoJwt,
hoseToken,
expiresAt: Date.now() + 2 * 60 * 60 * 1000, // 2小时
};
scriptEngineMemoryCache.set(cacheKey, entry);
return createAuthClient({
prefixUrl: SCRIPT_ENGINE_BASE_URL,
getHeaders: () => ({
Authorization: `Bearer ${easoJwt}`,
platformid: platformId,
hoseaccesstoken: hoseToken,
}),
onUnauthorized: () => {
scriptEngineMemoryCache.delete(cacheKey);
},
});
}