marketing-touch-fixture.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. import { createHash } from "node:crypto";
  2. import type { IncomingMessage, ServerResponse } from "node:http";
  3. import { createMarketingTouchAssets } from "./marketing-touch-assets.js";
  4. import { createMarketingAssetGate } from "./marketing-touch-asset-gate.js";
  5. import { createTelemetryReportFixture } from "./telemetry-report-fixture.js";
  6. export async function createMarketingTouchFixture() {
  7. const { png, zip, assets } = await createMarketingTouchAssets();
  8. const assetGate = createMarketingAssetGate();
  9. const hash = (bytes: Buffer) => createHash("sha256").update(bytes).digest("hex");
  10. const events: unknown[] = [];
  11. const handleTelemetry = createTelemetryReportFixture();
  12. let held = true;
  13. let claimed = false;
  14. let claimFailure: unknown = null;
  15. let popupVisible = true;
  16. let actionDelivery: { campaign_id: string; [key: string]: unknown } | null = null;
  17. let actionSequence = 0;
  18. const waiters: Array<() => void> = [];
  19. const queryWaiters: Array<() => void> = [];
  20. let queryHeld = false;
  21. const requests: string[] = [];
  22. const requestDetails: Array<{
  23. method: string;
  24. path: string;
  25. seq: string | null;
  26. timestamp: number;
  27. headers: {
  28. deviceMid: string | string[] | undefined;
  29. language: string | string[] | undefined;
  30. appVersion: string | string[] | undefined;
  31. authenticated: boolean;
  32. };
  33. }> = [];
  34. let generation = 0;
  35. let overrideDeliveries: unknown[] | null = null;
  36. let queryStatus = 200;
  37. let reportStatus = 200;
  38. let video = Buffer.alloc(0);
  39. const text = (content: string) => ({ format: "plaintext", content, style: null });
  40. const close = { text: text("Close campaign"), action: { type: "close" } };
  41. return {
  42. stop() {
  43. assetGate.reset();
  44. waiters.splice(0).forEach((done) => done());
  45. queryWaiters.splice(0).forEach((done) => done());
  46. },
  47. async handle(req: IncomingMessage, res: ServerResponse) {
  48. const url = new URL(req.url ?? "/", "http://localhost");
  49. const path = url.pathname;
  50. const json = (value: unknown, status = 200) => {
  51. res.writeHead(status, { "Content-Type": "application/json" });
  52. res.end(JSON.stringify(value));
  53. };
  54. const assetControl = assetGate.control(path);
  55. if (await handleTelemetry(req, res)) return true;
  56. if (assetControl) {
  57. json(assetControl);
  58. return true;
  59. }
  60. if (path === "/__e2e/marketing/state") {
  61. json({ events, requests, requestDetails, pendingQueries: queryWaiters.length });
  62. return true;
  63. }
  64. if (path.startsWith("/__e2e/marketing/query-")) {
  65. if (path.endsWith("/query-hold")) queryHeld = true;
  66. else if (path.endsWith("/query-release-one")) queryWaiters.shift()?.();
  67. else if (path.endsWith("/query-release-all")) {
  68. queryHeld = false;
  69. queryWaiters.splice(0).forEach((done) => done());
  70. } else return false;
  71. json({ ok: true });
  72. return true;
  73. }
  74. if (path === "/__e2e/marketing/assets") {
  75. json(
  76. Object.fromEntries(
  77. Object.entries(assets).map(([key, asset]) => [
  78. key,
  79. { src: `http://${req.headers.host}${asset.path}`, sha256: hash(asset.bytes) },
  80. ]),
  81. ),
  82. );
  83. return true;
  84. }
  85. if (path === "/__e2e/marketing/reset") {
  86. const chunks: Buffer[] = [];
  87. for await (const chunk of req) chunks.push(Buffer.from(chunk));
  88. const options = JSON.parse(Buffer.concat(chunks).toString() || "{}");
  89. // 旧用例挂起的 claim 不能在 reset 后改写下一用例的服务端投放。
  90. generation++;
  91. assetGate.reset();
  92. queryHeld = false;
  93. queryWaiters.splice(0).forEach((done) => done());
  94. waiters.splice(0).forEach((done) => done());
  95. held = options.held === true;
  96. claimed = options.banner !== true;
  97. popupVisible = options.popup === true;
  98. claimFailure = null;
  99. actionDelivery = null;
  100. overrideDeliveries = Array.isArray(options.deliveries) ? options.deliveries : null;
  101. queryStatus = 200;
  102. reportStatus = 200;
  103. events.length = 0;
  104. requests.length = 0;
  105. requestDetails.length = 0;
  106. json({ ok: true });
  107. return true;
  108. }
  109. if (path === "/__e2e/marketing/faults") {
  110. const body: Buffer[] = [];
  111. for await (const chunk of req) body.push(Buffer.from(chunk));
  112. const options = JSON.parse(Buffer.concat(body).toString() || "{}");
  113. queryStatus = options.queryStatus ?? 200;
  114. reportStatus = options.reportStatus ?? 200;
  115. json({ ok: true });
  116. return true;
  117. }
  118. if (path === "/__e2e/marketing/claim-failure") {
  119. const body: Buffer[] = [];
  120. for await (const chunk of req) body.push(Buffer.from(chunk));
  121. claimFailure = JSON.parse(Buffer.concat(body).toString());
  122. claimed = false;
  123. actionDelivery = null;
  124. held = false;
  125. json({ ok: true });
  126. return true;
  127. }
  128. if (path === "/__e2e/marketing/rich-delivery" || path === "/__e2e/marketing/video-banner") {
  129. const body: Buffer[] = [];
  130. for await (const chunk of req) body.push(Buffer.from(chunk));
  131. const data = JSON.parse(Buffer.concat(body).toString());
  132. const campaignId = `rich-${++actionSequence}`;
  133. const origin = `http://${req.headers.host}`;
  134. if (path.endsWith("video-banner")) {
  135. video = Buffer.from(data.video, "base64");
  136. actionDelivery = {
  137. campaign_id: campaignId,
  138. resource_position: "banner",
  139. priority: 100,
  140. banner: {
  141. background: {
  142. type: "video",
  143. video: {
  144. src: { src: `${origin}/marketing-assets/banner.mp4`, sha256: hash(video) },
  145. fallback: { src: `${origin}/marketing-assets/banner.png`, sha256: hash(png) },
  146. },
  147. },
  148. buttons: [
  149. close,
  150. {
  151. text: text("Copy video"),
  152. action: { type: "copy_text", args: { text: "Video copied" } },
  153. },
  154. ],
  155. },
  156. };
  157. } else {
  158. actionDelivery = {
  159. campaign_id: campaignId,
  160. resource_position: "popup",
  161. priority: 100,
  162. popup: data,
  163. };
  164. }
  165. json({ campaignId });
  166. return true;
  167. }
  168. if (path === "/marketing-assets/banner.mp4") {
  169. res.writeHead(200, { "Content-Type": "video/mp4" });
  170. res.end(video);
  171. return true;
  172. }
  173. if (path === "/__e2e/marketing/bundle-banner") {
  174. const origin = `http://${req.headers.host}`;
  175. const campaignId = `bundle-banner-${++actionSequence}`;
  176. actionDelivery = {
  177. campaign_id: campaignId,
  178. resource_position: "banner",
  179. priority: 100,
  180. banner: {
  181. background: {
  182. type: "bundle",
  183. bundle: {
  184. bundle: { src: `${origin}/marketing-assets/hero.zip`, sha256: hash(zip) },
  185. entry: "index.html",
  186. },
  187. args: {
  188. planName: "E2E Bundle Banner",
  189. amountValue: "321",
  190. amountUnit: "tokens",
  191. benefits: ["Banner resource"],
  192. },
  193. },
  194. buttons: [
  195. { ...close, text: { ...text(""), format: "" } },
  196. {
  197. text: text(""),
  198. action: { type: "copy_text", args: { text: "Bundle banner copied" } },
  199. },
  200. ],
  201. },
  202. };
  203. json({ campaignId });
  204. return true;
  205. }
  206. if (
  207. path === "/__e2e/marketing/action-delivery" ||
  208. path === "/__e2e/marketing/html-delivery"
  209. ) {
  210. const body: Buffer[] = [];
  211. for await (const chunk of req) body.push(Buffer.from(chunk));
  212. const action = JSON.parse(Buffer.concat(body).toString());
  213. const campaignId = `action-test-${++actionSequence}`;
  214. actionDelivery = {
  215. campaign_id: campaignId,
  216. resource_position: "popup",
  217. priority: 100,
  218. popup: {
  219. title: text(`E2E actions ${campaignId}`),
  220. description: path.endsWith("html-delivery")
  221. ? { format: "html", content: action }
  222. : text("Action fixture"),
  223. buttons: path.endsWith("html-delivery")
  224. ? [
  225. {
  226. ...close,
  227. theme: {
  228. variant: "outline",
  229. class: "rounded-lg font-semibold",
  230. style: "font-weight:400;color:var(--color-foreground);position:fixed",
  231. },
  232. },
  233. ]
  234. : [{ text: text("Run action"), action }, close],
  235. },
  236. };
  237. json({ ok: true, campaignId });
  238. return true;
  239. }
  240. if (path === "/__e2e/marketing/release") {
  241. held = false;
  242. waiters.splice(0).forEach((done) => done());
  243. json({ ok: true });
  244. return true;
  245. }
  246. if (path === "/__e2e/marketing/redeliver-banner") {
  247. claimed = false;
  248. json({ ok: true });
  249. return true;
  250. }
  251. if (path === "/__e2e/marketing/redeliver-popup") {
  252. popupVisible = true;
  253. json({ ok: true });
  254. return true;
  255. }
  256. if (
  257. path.startsWith("/api/v1/marketing/") ||
  258. path.startsWith("/marketing-assets/") ||
  259. path.startsWith("/api/v1/zcode-plan/billing/")
  260. ) {
  261. requests.push(path);
  262. requestDetails.push({
  263. method: req.method ?? "GET",
  264. path,
  265. seq: url.searchParams.get("seq"),
  266. timestamp: Date.now(),
  267. headers: {
  268. deviceMid: req.headers["x-device-mid"],
  269. language: req.headers["x-client-language"],
  270. appVersion: req.headers["x-zcode-app-version"],
  271. authenticated: Boolean(req.headers.authorization),
  272. },
  273. });
  274. }
  275. const staticAsset = Object.values(assets).find((asset) => asset.path === path);
  276. if (staticAsset) {
  277. await assetGate.wait();
  278. res.writeHead(200, { "Content-Type": staticAsset.type });
  279. res.end(staticAsset.bytes);
  280. return true;
  281. }
  282. if (path === "/api/v1/marketing/touch/action") {
  283. const body: Buffer[] = [];
  284. for await (const chunk of req) body.push(Buffer.from(chunk));
  285. const event = JSON.parse(Buffer.concat(body).toString());
  286. events.push(event);
  287. if (reportStatus !== 200) {
  288. json({ code: reportStatus, data: { message: "E2E report fault" } }, reportStatus);
  289. return true;
  290. }
  291. if (event.campaign_id === actionDelivery?.campaign_id) actionDelivery = null;
  292. // 是否继续投放由服务端 fixture 决定;重新下发保留原 campaign_id。
  293. if (event.campaign_id === "independent") popupVisible = false;
  294. if (event.campaign_id === "banner-1") claimed = true;
  295. json({ code: 0 });
  296. return true;
  297. }
  298. if (path === "/api/v1/marketing/touch") {
  299. if (queryStatus !== 200) {
  300. json({ code: queryStatus, data: { message: "E2E query fault" } }, queryStatus);
  301. return true;
  302. }
  303. const origin = `http://${req.headers.host}`;
  304. const hero = {
  305. type: "bundle",
  306. bundle: {
  307. bundle: { src: `${origin}/marketing-assets/hero.zip`, sha256: hash(zip) },
  308. entry: "index.html",
  309. },
  310. args: {
  311. planName: "E2E Weekend",
  312. amountValue: "100",
  313. amountUnit: "tokens",
  314. benefits: ["Fixture benefit"],
  315. },
  316. };
  317. const result = {
  318. layout: "v1",
  319. title: text("E2E claim succeeded"),
  320. description: { format: "html", content: "<p><b>E2E result</b></p>" },
  321. hero,
  322. buttons: [close],
  323. };
  324. const snapshot = {
  325. code: 0,
  326. data: {
  327. server_time: Math.floor(Date.now() / 1000),
  328. language: req.headers["x-client-language"] === "zh-CN" ? "zh-CN" : "en-US",
  329. deliveries:
  330. overrideDeliveries ??
  331. (actionDelivery
  332. ? [actionDelivery]
  333. : [
  334. ...(!claimed
  335. ? [
  336. {
  337. campaign_id: "banner-1",
  338. resource_position: "banner",
  339. priority: 90,
  340. banner: {
  341. background: {
  342. type: "image",
  343. image: {
  344. default: {
  345. src: `${origin}/marketing-assets/banner.png`,
  346. sha256: hash(png),
  347. },
  348. },
  349. },
  350. buttons: [
  351. { ...close, text: { ...text(""), format: "" } },
  352. {
  353. text: { ...text(""), format: "" },
  354. action: {
  355. type: "claim_zcode_plan",
  356. args: { plan_id: "weekend-plan-e2e" },
  357. },
  358. },
  359. ],
  360. success_popup: result,
  361. },
  362. },
  363. ]
  364. : []),
  365. ...(popupVisible
  366. ? [
  367. {
  368. campaign_id: "independent",
  369. resource_position: "popup",
  370. priority: 100,
  371. popup: { ...result, title: text("E2E independent popup"), hero: null },
  372. },
  373. ]
  374. : []),
  375. ]),
  376. },
  377. };
  378. // 在操作前冻结响应;释放时不重新计算投放,才能复现真实迟到快照。
  379. if (queryHeld) await new Promise<void>((done) => queryWaiters.push(done));
  380. json(snapshot);
  381. return true;
  382. }
  383. if (path === "/api/v1/zcode-plan/billing/claim") {
  384. const requestGeneration = generation;
  385. if (held) await new Promise<void>((done) => waiters.push(done));
  386. if (requestGeneration !== generation) {
  387. json({ code: 409, data: { message: "Fixture case reset" } });
  388. return true;
  389. }
  390. claimed = true;
  391. if (claimFailure) {
  392. json(claimFailure);
  393. claimFailure = null;
  394. return true;
  395. }
  396. }
  397. return false;
  398. },
  399. };
  400. }