feedbackService.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. import { basename, join } from "node:path";
  2. import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
  3. import type { ApiClient, FeedbackDeviceInfo } from "@zcode/shared";
  4. import {
  5. buildRuntimeZCodeApiUrl,
  6. ZCODE_BUILD_TIME,
  7. ZCODE_COMMIT,
  8. ZCODE_VERSION,
  9. } from "@zcode/shared";
  10. import { Emitter } from "@zcode/rpc";
  11. import { arch, platform, release, type as osType } from "node:os";
  12. import type { ICredentialService } from "../credential/credential.js";
  13. import type { IOAuthService } from "../oauth/oauth.js";
  14. import type { FeedbackUploadProgress, IFeedbackService } from "./feedback.js";
  15. import { FeedbackHttpClient, FeedbackUploadCanceledError } from "./feedbackHttpClient.js";
  16. import { cleanupLogArchive, prepareCompactLogArchive } from "./compactLogArchive.js";
  17. import { getFeedbackAttachmentDir } from "../paths.js";
  18. import { FeedbackLocalTicketStore } from "#src/feedback/feedbackLocalTicketStore.js";
  19. const ZCODE_JWT_TOKEN_KEY = "zcodejwttoken";
  20. export interface CreateFeedbackServiceOptions {
  21. credentialService: ICredentialService;
  22. oauthService: IOAuthService;
  23. apiClient: ApiClient;
  24. getDeviceMid?: () => string | undefined;
  25. apiBaseUrl?: string;
  26. createFullLogArchive?: (
  27. sourceDir: string,
  28. options?: {
  29. onProgress?: (event: { processedBytes: number; totalBytes: number }) => void;
  30. },
  31. ) => Promise<{ path: string; size: number }>;
  32. revealPath?: (path: string) => Promise<void>;
  33. }
  34. function resolveApiBaseUrl(explicit?: string): string {
  35. return (
  36. explicit?.trim() ||
  37. process.env.ZCODE_FEEDBACK_API_BASE?.trim() ||
  38. buildRuntimeZCodeApiUrl(process.env, "/api/v1")
  39. );
  40. }
  41. function buildDeviceSnapshot(): FeedbackDeviceInfo {
  42. return {
  43. appVersion: ZCODE_VERSION,
  44. buildCommitId: ZCODE_COMMIT,
  45. buildTime: ZCODE_BUILD_TIME,
  46. nodeVersion: process.version,
  47. osType: osType(),
  48. osPlatform: platform(),
  49. osRelease: release(),
  50. // node:os.version() 在 macOS 上是完整 Darwin kernel 字符串,超过后端 os_version VARCHAR(64) 会写库失败。
  51. osVersion: release(),
  52. osArch: arch(),
  53. };
  54. }
  55. export function createFeedbackService(options: CreateFeedbackServiceOptions): IFeedbackService {
  56. const apiBaseUrl = resolveApiBaseUrl(options.apiBaseUrl);
  57. function getHostDeviceMid(): string | undefined {
  58. return options.getDeviceMid?.()?.trim() || undefined;
  59. }
  60. function requireHostDeviceMid(): string {
  61. const deviceMid = getHostDeviceMid();
  62. if (!deviceMid) {
  63. throw new Error("Missing feedback device_mid");
  64. }
  65. return deviceMid;
  66. }
  67. async function getZcodeJwtToken(): Promise<string | undefined> {
  68. return (await options.credentialService.load(ZCODE_JWT_TOKEN_KEY))?.trim() || undefined;
  69. }
  70. async function hasZcodeJwtToken(): Promise<boolean> {
  71. return Boolean(await getZcodeJwtToken());
  72. }
  73. const httpClient = new FeedbackHttpClient({
  74. baseUrl: apiBaseUrl,
  75. apiClient: options.apiClient,
  76. getAuthHeaders: async () => {
  77. const headers: Record<string, string> = {};
  78. const deviceMid = getHostDeviceMid();
  79. // feedback 的 device_mid 必须复用宿主 deviceMid(与 provider 请求头、远控同一身份);
  80. // 不单独生成 fb_ 身份,否则同一台机器在不同系统里会被拆成两个设备。
  81. if (deviceMid) {
  82. headers["X-Device-Mid"] = deviceMid;
  83. }
  84. const jwtToken = await getZcodeJwtToken();
  85. if (jwtToken) {
  86. headers.Authorization = `Bearer ${jwtToken}`;
  87. }
  88. return headers;
  89. },
  90. });
  91. const localTicketStore = new FeedbackLocalTicketStore();
  92. const uploadProgressEmitters = new Map<string, Emitter<FeedbackUploadProgress>>();
  93. const activeUploadControllers = new Map<string, AbortController>();
  94. const activeCreateControllers = new Map<string, AbortController>();
  95. function getUploadProgressEmitter(id: string): Emitter<FeedbackUploadProgress> {
  96. const current = uploadProgressEmitters.get(id);
  97. if (current) return current;
  98. const emitter = new Emitter<FeedbackUploadProgress>({
  99. onDidRemoveLastListener: () => {
  100. uploadProgressEmitters.delete(id);
  101. emitter.dispose();
  102. },
  103. });
  104. uploadProgressEmitters.set(id, emitter);
  105. return emitter;
  106. }
  107. return {
  108. create: async (input, createOptions) => {
  109. const device = input.device ?? buildDeviceSnapshot();
  110. const operationId = createOptions?.operationId?.trim();
  111. const controller = new AbortController();
  112. if (operationId) {
  113. // UI 取消创建工单时不能只关闭弹窗;host 需要能按 operationId
  114. // 找到当前 HTTP 请求并 abort,避免“正在连接反馈服务”永久悬挂。
  115. activeCreateControllers.get(operationId)?.abort();
  116. activeCreateControllers.set(operationId, controller);
  117. }
  118. try {
  119. const ticket = await httpClient.create(
  120. {
  121. ...input,
  122. device,
  123. },
  124. {
  125. signal: controller.signal,
  126. },
  127. );
  128. if (!(await hasZcodeJwtToken())) {
  129. await localTicketStore.upsert(requireHostDeviceMid(), ticket);
  130. }
  131. return ticket;
  132. } finally {
  133. if (operationId && activeCreateControllers.get(operationId) === controller) {
  134. activeCreateControllers.delete(operationId);
  135. }
  136. }
  137. },
  138. cancelCreate: async (operationId) => {
  139. const key = operationId.trim();
  140. if (!key) return;
  141. activeCreateControllers.get(key)?.abort();
  142. },
  143. list: async (query) => {
  144. if (await hasZcodeJwtToken()) {
  145. return httpClient.list(query);
  146. }
  147. const items = await localTicketStore.list(requireHostDeviceMid(), query);
  148. return { items, total: items.length };
  149. },
  150. get: (id) => httpClient.get(id),
  151. comment: (id, body) => httpClient.comment(id, body),
  152. uploadAttachment: async (id, kind, file) => {
  153. const filename = file.filename ?? basename(file.path);
  154. const contentType = file.contentType ?? (kind === "image" ? "image/png" : "application/zip");
  155. return httpClient.uploadFile(id, kind, file.path, filename, contentType, {
  156. messageId: file.messageId,
  157. });
  158. },
  159. uploadAttachmentWithProgress: async (id, kind, file, progressId) => {
  160. const filename = file.filename ?? basename(file.path);
  161. const contentType = file.contentType ?? (kind === "image" ? "image/png" : "application/zip");
  162. const emitter = getUploadProgressEmitter(progressId);
  163. emitter.fire({
  164. id: progressId,
  165. phase: "preparing",
  166. uploadedBytes: 0,
  167. totalBytes: 0,
  168. });
  169. const controller = new AbortController();
  170. activeUploadControllers.set(progressId, controller);
  171. return httpClient
  172. .uploadFile(id, kind, file.path, filename, contentType, {
  173. messageId: file.messageId,
  174. signal: controller.signal,
  175. onUploadProgress: (event) => {
  176. emitter.fire({
  177. id: progressId,
  178. phase: event.uploadedBytes >= event.totalBytes ? "complete" : "uploading",
  179. uploadedBytes: event.uploadedBytes,
  180. totalBytes: event.totalBytes,
  181. });
  182. },
  183. })
  184. .catch((error) => {
  185. if (error instanceof FeedbackUploadCanceledError) {
  186. emitter.fire({
  187. id: progressId,
  188. phase: "canceled",
  189. uploadedBytes: 0,
  190. totalBytes: 0,
  191. });
  192. }
  193. throw error;
  194. })
  195. .finally(() => {
  196. activeUploadControllers.delete(progressId);
  197. });
  198. },
  199. cancelUpload: async (progressId) => {
  200. activeUploadControllers.get(progressId)?.abort();
  201. },
  202. onDynamicUploadProgress: (id) => getUploadProgressEmitter(id).event,
  203. uploadAttachmentData: async (id, kind, file) => {
  204. const attachmentRootDir = getFeedbackAttachmentDir();
  205. await mkdir(attachmentRootDir, { recursive: true });
  206. const tempDir = await mkdtemp(join(attachmentRootDir, "attachment-"));
  207. // 附件名来自 renderer,不能作为本地相对路径使用。
  208. const filename = basename(file.filename.replaceAll("\\", "/")) || "attachment";
  209. const tempPath = join(tempDir, "content");
  210. try {
  211. await writeFile(tempPath, Buffer.from(file.dataBase64, "base64"));
  212. return await httpClient.uploadFile(id, kind, tempPath, filename, file.contentType, {
  213. messageId: file.messageId,
  214. });
  215. } finally {
  216. await rm(tempDir, { recursive: true, force: true }).catch(() => {});
  217. }
  218. },
  219. attachLogsFromExport: async (id, attachOptions) => {
  220. const archive = await prepareCompactLogArchive({
  221. full: attachOptions?.full,
  222. createFullArchive: options.createFullLogArchive,
  223. });
  224. try {
  225. return await httpClient.uploadFile(
  226. id,
  227. "log",
  228. archive.path,
  229. basename(archive.path),
  230. "application/zip",
  231. );
  232. } finally {
  233. await cleanupLogArchive(archive.path);
  234. }
  235. },
  236. getDeviceSnapshot: async () => buildDeviceSnapshot(),
  237. prepareCompactLogArchive: async (archiveOptions) => {
  238. const progressId = archiveOptions?.progressId;
  239. const progressEmitter = progressId ? getUploadProgressEmitter(progressId) : null;
  240. return prepareCompactLogArchive({
  241. full: archiveOptions?.full,
  242. createFullArchive: options.createFullLogArchive,
  243. onProgress: progressEmitter
  244. ? (event) => {
  245. progressEmitter.fire({
  246. id: progressId!,
  247. phase: "preparing",
  248. uploadedBytes: event.processedBytes,
  249. totalBytes: event.totalBytes,
  250. });
  251. }
  252. : undefined,
  253. });
  254. },
  255. cleanupPreparedLogArchive: (path) => cleanupLogArchive(path),
  256. revealLogArchive: async (path) => {
  257. if (options.revealPath) {
  258. await options.revealPath(path);
  259. return;
  260. }
  261. },
  262. };
  263. }