useUsageEntitlement.test.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. import { BigModelUsageQuotaProvider } from "../../services/src/usage-stats/providers/bigmodelUsageQuotaProvider.js";
  2. import type { ReactElement } from "react";
  3. import type { Root } from "react-dom/client";
  4. import type { UsageEntitlementSnapshot, ZCodeAccountAccess } from "@zcode/shared";
  5. import { readCachedUsageEntitlementSnapshot } from "@/lib/usageEntitlementCache.js";
  6. import {
  7. buildEntitlementFreshnessKey,
  8. hasSharedEntitlementFailure,
  9. shouldDeferSharedEntitlementRefresh,
  10. readSharedEntitlementSnapshot,
  11. } from "@/lib/usageEntitlementRefreshPolicy.js";
  12. import type { IUsageStatsService, IServiceAccessor } from "@zcode/services";
  13. import { act, createElement } from "react";
  14. import { createRoot } from "react-dom/client";
  15. import { afterEach, describe, expect, it, vi } from "vitest";
  16. import {
  17. useUsageEntitlement,
  18. useUsageEntitlementWithService,
  19. withUsageEntitlementTimeout,
  20. } from "@/hooks/useUsageEntitlement.js";
  21. import { ServiceProvider } from "@/hooks/useServices.js";
  22. import {
  23. registerBaseWorkspaceServices,
  24. useRemoteWorkspaceSessionStore,
  25. } from "@/store/remoteWorkspaceSessionStore.js";
  26. const auth = vi.hoisted(() => ({
  27. state: undefined as undefined | { user: { id: string } | null; authSessionSeq: number },
  28. }));
  29. vi.mock("@/store/StoreProvider.js", () => ({
  30. useZCodeStoreWithDefault: (
  31. selector: (state: NonNullable<typeof auth.state>) => unknown,
  32. fallback: unknown,
  33. ) => (auth.state ? selector(auth.state) : fallback),
  34. }));
  35. function createMinimalElement(ownerDocument?: Document, tagName = "div"): Element {
  36. const element = {
  37. appendChild: (child: { parentNode?: unknown }) => {
  38. child.parentNode = element;
  39. return child;
  40. },
  41. childNodes: [] as unknown[],
  42. addEventListener: () => {},
  43. getAttribute: () => null,
  44. insertBefore: (child: { parentNode?: unknown }) => {
  45. child.parentNode = element;
  46. return child;
  47. },
  48. nodeName: tagName.toUpperCase(),
  49. nodeType: 1,
  50. ownerDocument,
  51. parentNode: null as unknown,
  52. removeAttribute: () => {},
  53. removeChild: (child: { parentNode?: unknown }) => {
  54. child.parentNode = null;
  55. return child;
  56. },
  57. removeEventListener: () => {},
  58. setAttribute: () => {},
  59. style: {},
  60. tagName: tagName.toUpperCase(),
  61. };
  62. return element as unknown as Element;
  63. }
  64. function installMinimalDom() {
  65. const storage = new Map<string, string>();
  66. const documentMock = {
  67. addEventListener: () => {},
  68. createElement: (tagName: string) =>
  69. createMinimalElement(documentMock as unknown as Document, tagName),
  70. createTextNode: (nodeValue: string) => ({
  71. nodeType: 3,
  72. nodeValue,
  73. ownerDocument: documentMock,
  74. parentNode: null,
  75. }),
  76. nodeType: 9,
  77. removeEventListener: () => {},
  78. visibilityState: "visible",
  79. } as unknown as Document;
  80. const windowMock = {
  81. addEventListener: () => {},
  82. clearInterval,
  83. clearTimeout,
  84. document: documentMock,
  85. HTMLIFrameElement: function HTMLIFrameElement() {},
  86. HTMLElement: function HTMLElement() {},
  87. localStorage: {
  88. getItem: (key: string) => storage.get(key) ?? null,
  89. removeItem: (key: string) => {
  90. storage.delete(key);
  91. },
  92. setItem: (key: string, value: string) => {
  93. storage.set(key, value);
  94. },
  95. },
  96. Node: function Node() {},
  97. removeEventListener: () => {},
  98. setInterval,
  99. setTimeout,
  100. };
  101. Object.defineProperty(globalThis, "document", {
  102. configurable: true,
  103. value: documentMock,
  104. });
  105. Object.defineProperty(globalThis, "window", {
  106. configurable: true,
  107. value: windowMock,
  108. });
  109. Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
  110. configurable: true,
  111. value: true,
  112. });
  113. return createMinimalElement(documentMock);
  114. }
  115. function createSnapshot(params: {
  116. organizationId: string;
  117. projectId: string;
  118. }): UsageEntitlementSnapshot {
  119. return {
  120. generatedAt: Date.now(),
  121. authenticated: true,
  122. context: {
  123. scope: "team",
  124. organizationId: params.organizationId,
  125. projectId: params.projectId,
  126. },
  127. provider: {
  128. id: "account:bigmodel-individual-coding-plan",
  129. name: "BigModel Coding Plan",
  130. },
  131. remaining: {
  132. count: params.projectId === "proj-a" ? 10 : 20,
  133. isShow: true,
  134. },
  135. subscription: null,
  136. quota: {
  137. level: null,
  138. limits: [],
  139. },
  140. };
  141. }
  142. function flushPromises() {
  143. return new Promise<void>((resolve) => {
  144. setTimeout(resolve, 0);
  145. });
  146. }
  147. afterEach(() => {
  148. auth.state = undefined;
  149. vi.restoreAllMocks();
  150. });
  151. describe("useUsageEntitlement timeout", () => {
  152. it("权益查询长时间不返回时进入失败路径", async () => {
  153. vi.useFakeTimers();
  154. try {
  155. const request = new Promise<string>(() => {});
  156. const result = withUsageEntitlementTimeout(request, 5);
  157. const assertion = expect(result).rejects.toThrow("usage_entitlement_request_timeout:5");
  158. await vi.advanceTimersByTimeAsync(5);
  159. await assertion;
  160. } finally {
  161. vi.useRealTimers();
  162. }
  163. });
  164. it("权益查询正常返回时清理超时计时器", async () => {
  165. vi.useFakeTimers();
  166. try {
  167. await expect(withUsageEntitlementTimeout(Promise.resolve("ok"), 5)).resolves.toBe("ok");
  168. expect(vi.getTimerCount()).toBe(0);
  169. } finally {
  170. vi.useRealTimers();
  171. }
  172. });
  173. });
  174. describe("useUsageEntitlement team context refresh", () => {
  175. it("远端 workspace 等待 services 时权益查询仍走 app-global base host", async () => {
  176. const baseGetEntitlementSnapshot = vi.fn(async () =>
  177. createSnapshot({ organizationId: "org-base", projectId: "proj-base" }),
  178. );
  179. const remoteGetEntitlementSnapshot = vi.fn(async () =>
  180. createSnapshot({ organizationId: "org-remote", projectId: "proj-remote" }),
  181. );
  182. const baseServices = {
  183. usageStatsService: { getEntitlementSnapshot: baseGetEntitlementSnapshot },
  184. } as unknown as IServiceAccessor;
  185. const remoteContextServices = {
  186. usageStatsService: { getEntitlementSnapshot: remoteGetEntitlementSnapshot },
  187. } as unknown as IServiceAccessor;
  188. registerBaseWorkspaceServices(baseServices);
  189. function Probe() {
  190. useUsageEntitlement({
  191. enabled: true,
  192. preferredProviderId: "account:bigmodel-individual-coding-plan",
  193. cacheKey: "base-host-routing",
  194. refreshOnMount: true,
  195. });
  196. return null;
  197. }
  198. const root: Root = createRoot(installMinimalDom());
  199. try {
  200. await act(async () => {
  201. root.render(
  202. createElement(ServiceProvider, { services: remoteContextServices }, createElement(Probe)),
  203. );
  204. await flushPromises();
  205. });
  206. } finally {
  207. await act(async () => {
  208. root.unmount();
  209. });
  210. useRemoteWorkspaceSessionStore.setState({ baseServices: null });
  211. }
  212. expect(baseGetEntitlementSnapshot).toHaveBeenCalledTimes(1);
  213. expect(remoteGetEntitlementSnapshot).not.toHaveBeenCalled();
  214. });
  215. it("Team Plan freshness key 变化后会重新请求新团队权益", async () => {
  216. const calls: Array<{ organizationId?: string | null; projectId?: string | null }> = [];
  217. const usageStatsService = {
  218. getEntitlementSnapshot: vi.fn(async (request) => {
  219. calls.push({
  220. organizationId: request.accountAccess?.organizationId,
  221. projectId: request.accountAccess?.projectId,
  222. });
  223. return createSnapshot({
  224. organizationId: request.accountAccess?.organizationId ?? "",
  225. projectId: request.accountAccess?.projectId ?? "",
  226. });
  227. }),
  228. };
  229. const services = {
  230. usageStatsService,
  231. } as unknown as IServiceAccessor;
  232. const accountAccessByProject = new Map<string, ZCodeAccountAccess>();
  233. function getTeamAccess(organizationId: string, projectId: string): ZCodeAccountAccess {
  234. const key = `${organizationId}:${projectId}`;
  235. const existing = accountAccessByProject.get(key);
  236. if (existing) return existing;
  237. const access: ZCodeAccountAccess = {
  238. type: "zhipu-account",
  239. family: "bigmodel",
  240. planKind: "team-coding-plan",
  241. productId: "product-team",
  242. organizationId,
  243. projectId,
  244. };
  245. accountAccessByProject.set(key, access);
  246. return access;
  247. }
  248. function Probe(props: { organizationId: string; projectId: string }) {
  249. useUsageEntitlement({
  250. enabled: true,
  251. preferredProviderId: "account:bigmodel-team-coding-plan",
  252. accountAccess: getTeamAccess(props.organizationId, props.projectId),
  253. allowDisabledPreferredProvider: true,
  254. requirePreferredProvider: true,
  255. allowEnvApiKey: false,
  256. cacheKey: `team:${props.organizationId}:${props.projectId}`,
  257. refreshOnMount: true,
  258. });
  259. return null;
  260. }
  261. function renderProbe(props: { organizationId: string; projectId: string }): ReactElement {
  262. return createElement(ServiceProvider, { services }, createElement(Probe, props));
  263. }
  264. const root: Root = createRoot(installMinimalDom());
  265. try {
  266. await act(async () => {
  267. root.render(renderProbe({ organizationId: "org-a", projectId: "proj-a" }));
  268. await flushPromises();
  269. });
  270. await act(async () => {
  271. root.render(renderProbe({ organizationId: "org-b", projectId: "proj-b" }));
  272. await flushPromises();
  273. });
  274. } finally {
  275. await act(async () => {
  276. root.unmount();
  277. });
  278. }
  279. expect(calls).toEqual([
  280. { organizationId: "org-a", projectId: "proj-a" },
  281. { organizationId: "org-b", projectId: "proj-b" },
  282. ]);
  283. });
  284. });
  285. describe("刷新失败保留已确认订阅", () => {
  286. it.each(["personal", "team"] as const)(
  287. "%s 真实订阅服务失败保留快照和退避,明确无套餐才清除",
  288. async (scope) => {
  289. let mode: "active" | "failure" | "unknown" | "none" = "active";
  290. const accountAccess: ZCodeAccountAccess =
  291. scope === "team"
  292. ? {
  293. type: "zhipu-account",
  294. family: "bigmodel",
  295. planKind: "team-coding-plan",
  296. organizationId: "org",
  297. projectId: "project",
  298. }
  299. : { type: "zhipu-account", family: "bigmodel", planKind: "individual-coding-plan" };
  300. const providerId = `account:bigmodel-${scope === "team" ? "team" : "individual"}-coding-plan`;
  301. const provider = new BigModelUsageQuotaProvider({
  302. env: { ZCODE_ENV: "production" },
  303. credentialService: { load: async () => "business" },
  304. accountRequestAuthService: {
  305. resolveAccessCurrent: vi.fn(),
  306. resolveCurrent: vi.fn(async () => ({ apiKey: "personal.secret" })),
  307. assertCurrent: vi.fn(),
  308. },
  309. apiClient: {
  310. request: vi.fn(async (url) => {
  311. if (mode === "failure") throw new Error("network offline");
  312. const subscription =
  313. String(url).includes("subscription/list") ||
  314. String(url).includes("querySubscribeDetail");
  315. // quota 始终失败,确认有效订阅仍可独立展示。
  316. if (!subscription) throw new Error("quota offline");
  317. const data =
  318. mode === "unknown"
  319. ? { invalid: true }
  320. : scope === "team"
  321. ? {
  322. hasSubscription: mode !== "none",
  323. status: "EFFECTIVE",
  324. memberGrantStatus: "VALID",
  325. productId: "coding",
  326. productName: "Team Coding",
  327. }
  328. : mode === "none"
  329. ? []
  330. : [
  331. {
  332. productId: "coding",
  333. productName: "GLM Coding Lite",
  334. status: "VALID",
  335. inCurrentPeriod: true,
  336. },
  337. ];
  338. return new Response(JSON.stringify({ success: true, data }));
  339. }),
  340. },
  341. });
  342. const getEntitlementSnapshot = vi.fn(() =>
  343. provider.getSnapshotForRequest({ preferredProviderId: providerId, accountAccess }),
  344. );
  345. const usageStatsService = { getEntitlementSnapshot } as unknown as IUsageStatsService;
  346. const cacheKey = `service-failure-${scope}`;
  347. const freshnessKey = buildEntitlementFreshnessKey({
  348. cacheKey,
  349. options: {
  350. includeSubscription: false,
  351. preferredProviderId: providerId,
  352. accountAccess,
  353. allowDisabledPreferredProvider: false,
  354. requirePreferredProvider: false,
  355. },
  356. });
  357. let state!: ReturnType<typeof useUsageEntitlementWithService>;
  358. function Probe() {
  359. state = useUsageEntitlementWithService(usageStatsService, {
  360. enabled: true,
  361. cacheKey,
  362. preferredProviderId: providerId,
  363. accountAccess,
  364. refreshOnMount: true,
  365. });
  366. return null;
  367. }
  368. const root = createRoot(installMinimalDom());
  369. try {
  370. await act(async () => {
  371. root.render(createElement(Probe));
  372. await flushPromises();
  373. });
  374. const confirmed = state.snapshot;
  375. expect(confirmed?.subscription?.details[0]?.productId).toBe("coding");
  376. for (const failure of ["failure", "unknown"] as const) {
  377. mode = failure;
  378. await act(async () => {
  379. await state.refresh({ force: true, reason: "manual" });
  380. });
  381. expect(state.snapshot).toEqual(confirmed);
  382. expect(state.error).toBeTruthy();
  383. expect(readCachedUsageEntitlementSnapshot({ cacheKey })).toEqual(confirmed);
  384. expect(hasSharedEntitlementFailure({ usageStatsService, freshnessKey })).toBe(true);
  385. expect(
  386. shouldDeferSharedEntitlementRefresh({
  387. usageStatsService,
  388. freshnessKey,
  389. now: Date.now(),
  390. }),
  391. ).toBe(true);
  392. }
  393. mode = "none";
  394. await act(async () => {
  395. await state.refresh({ force: true, reason: "manual" });
  396. });
  397. expect(state.error).toBeNull();
  398. expect(state.snapshot?.subscription).toBeNull();
  399. expect(state.snapshot?.unavailableReason).toBe("no_plan");
  400. expect(readCachedUsageEntitlementSnapshot({ cacheKey })?.subscription).toBeNull();
  401. expect(hasSharedEntitlementFailure({ usageStatsService, freshnessKey })).toBe(false);
  402. } finally {
  403. await act(async () => root.unmount());
  404. }
  405. },
  406. );
  407. it("手动刷新遇到 429 保留同一身份的套餐,并暴露错误;购买刷新传递失效标记", async () => {
  408. const snapshot = createSnapshot({ organizationId: "org", projectId: "project" });
  409. snapshot.subscription = {
  410. identityType: "unknown",
  411. identityMasked: null,
  412. details: [{ productId: "start", productName: "Start Plan" }],
  413. };
  414. const getEntitlementSnapshot = vi
  415. .fn()
  416. .mockResolvedValueOnce(snapshot)
  417. .mockRejectedValueOnce(new Error("HTTP 429"))
  418. .mockResolvedValue(snapshot);
  419. const services = {
  420. usageStatsService: { getEntitlementSnapshot },
  421. } as unknown as IServiceAccessor;
  422. registerBaseWorkspaceServices(services);
  423. let state!: ReturnType<typeof useUsageEntitlement>;
  424. function Probe() {
  425. state = useUsageEntitlement({
  426. enabled: true,
  427. cacheKey: "keep-confirmed-subscription",
  428. preferredProviderId: "account:bigmodel-start-plan",
  429. refreshOnMount: true,
  430. });
  431. return null;
  432. }
  433. const root = createRoot(installMinimalDom());
  434. try {
  435. await act(async () => {
  436. root.render(createElement(ServiceProvider, { services }, createElement(Probe)));
  437. await flushPromises();
  438. });
  439. await act(async () => {
  440. await state.refresh({ force: true, reason: "manual" });
  441. });
  442. expect(state.snapshot).toBe(snapshot);
  443. expect(state.error).toBe("HTTP 429");
  444. await act(async () => {
  445. await state.refresh({ force: true, reason: "purchase" });
  446. });
  447. expect(getEntitlementSnapshot.mock.lastCall?.[0]).toMatchObject({
  448. invalidateBalanceCache: true,
  449. });
  450. } finally {
  451. await act(async () => root.unmount());
  452. useRemoteWorkspaceSessionStore.setState({ baseServices: null });
  453. }
  454. });
  455. });
  456. describe("跨组件购买刷新代次", () => {
  457. it.each(["success", "failure"])("购买成功后忽略旧请求的 %s,隔离其他身份", async (outcome) => {
  458. const pending: Array<{
  459. resolve: (s: UsageEntitlementSnapshot) => void;
  460. reject: (e: Error) => void;
  461. }> = [];
  462. const service = {
  463. getEntitlementSnapshot: vi.fn(
  464. () =>
  465. new Promise<UsageEntitlementSnapshot>((resolve, reject) =>
  466. pending.push({ resolve, reject }),
  467. ),
  468. ),
  469. } as unknown as IUsageStatsService;
  470. const states: Array<ReturnType<typeof useUsageEntitlementWithService>> = [];
  471. const requestOptions = {
  472. includeSubscription: false,
  473. preferredProviderId: "account:bigmodel-start-plan",
  474. allowDisabledPreferredProvider: false,
  475. requirePreferredProvider: false,
  476. };
  477. const cacheKey = "purchase-generation";
  478. const freshnessKey = buildEntitlementFreshnessKey({ cacheKey, options: requestOptions });
  479. function Probe({ index }: { index: number }) {
  480. states[index] = useUsageEntitlementWithService(service, {
  481. ...requestOptions,
  482. preferredProviderId: index === 2 ? "other-provider" : requestOptions.preferredProviderId,
  483. cacheKey: index === 2 ? "other-identity" : cacheKey,
  484. });
  485. return null;
  486. }
  487. const root = createRoot(installMinimalDom());
  488. const fresh = createSnapshot({ organizationId: "org", projectId: "new" });
  489. fresh.subscription = {
  490. identityType: "unknown",
  491. identityMasked: null,
  492. details: [{ productId: "start", productName: "Start Plan" }],
  493. };
  494. const old = createSnapshot({ organizationId: "org", projectId: "old" });
  495. const other = createSnapshot({ organizationId: "other", projectId: "other" });
  496. try {
  497. await act(async () => {
  498. root.render(
  499. createElement(
  500. "div",
  501. null,
  502. ...[0, 1, 2].map((index) => createElement(Probe, { index, key: index })),
  503. ),
  504. );
  505. });
  506. let oldRequest!: Promise<void>;
  507. let otherRequest!: Promise<void>;
  508. let purchase!: Promise<void>;
  509. await act(async () => {
  510. oldRequest = states[0]!.refresh();
  511. otherRequest = states[2]!.refresh();
  512. });
  513. expect(pending).toHaveLength(2);
  514. await act(async () => {
  515. purchase = states[1]!.refresh({ reason: "purchase", force: true });
  516. });
  517. await act(async () => {
  518. pending[2]!.resolve(fresh);
  519. await purchase;
  520. });
  521. // 购买后的普通刷新也不能重新加入仍未完成的旧代次请求。
  522. let followUp!: Promise<void>;
  523. await act(async () => {
  524. followUp = states[1]!.refresh();
  525. });
  526. expect(pending).toHaveLength(4);
  527. await act(async () => {
  528. pending[3]!.resolve(fresh);
  529. await followUp;
  530. });
  531. await act(async () => {
  532. if (outcome === "success") pending[0]!.resolve(old);
  533. else pending[0]!.reject(new Error("old HTTP 429"));
  534. pending[1]!.resolve(other);
  535. await Promise.all([oldRequest, otherRequest]);
  536. });
  537. for (const state of states.slice(0, 2)) {
  538. expect(state.snapshot).toEqual(fresh);
  539. expect(state.error).toBeNull();
  540. expect(state.loading).toBe(false);
  541. }
  542. expect(states[2]!.snapshot).toEqual(other);
  543. expect(readCachedUsageEntitlementSnapshot({ cacheKey })).toEqual(fresh);
  544. expect(readSharedEntitlementSnapshot({ usageStatsService: service, freshnessKey })).toEqual(
  545. fresh,
  546. );
  547. expect(hasSharedEntitlementFailure({ usageStatsService: service, freshnessKey })).toBe(false);
  548. } finally {
  549. await act(async () => root.unmount());
  550. }
  551. });
  552. });
  553. it("禁用权益查询后旧响应不再发布共享快照或本地缓存", async () => {
  554. let finish!: (value: UsageEntitlementSnapshot) => void;
  555. const service = {
  556. getEntitlementSnapshot: vi.fn(
  557. () =>
  558. new Promise<UsageEntitlementSnapshot>((resolve) => {
  559. finish = resolve;
  560. }),
  561. ),
  562. } as unknown as IUsageStatsService;
  563. const cacheKey = "logout-late-entitlement";
  564. const options = {
  565. cacheKey,
  566. preferredProviderId: "account:bigmodel-team-coding-plan",
  567. refreshOnMount: true,
  568. };
  569. let state: ReturnType<typeof useUsageEntitlementWithService>;
  570. function Probe({ enabled }: { enabled: boolean }) {
  571. state = useUsageEntitlementWithService(service, { ...options, enabled });
  572. return null;
  573. }
  574. const root = createRoot(installMinimalDom());
  575. try {
  576. await act(async () => root.render(createElement(Probe, { enabled: true })));
  577. await act(async () => root.render(createElement(Probe, { enabled: false })));
  578. await act(async () =>
  579. finish(createSnapshot({ organizationId: "old-org", projectId: "old-project" })),
  580. );
  581. expect(state!.snapshot).toBeNull();
  582. expect(readCachedUsageEntitlementSnapshot({ cacheKey })).toBeNull();
  583. expect(
  584. readSharedEntitlementSnapshot({
  585. usageStatsService: service,
  586. freshnessKey: buildEntitlementFreshnessKey({
  587. cacheKey,
  588. options: {
  589. preferredProviderId: options.preferredProviderId,
  590. includeSubscription: false,
  591. allowDisabledPreferredProvider: false,
  592. requirePreferredProvider: false,
  593. },
  594. }),
  595. }),
  596. ).toBeNull();
  597. } finally {
  598. await act(async () => root.unmount());
  599. }
  600. });
  601. it.each(["logout", "account", "session"])(
  602. "%s:同服务的鉴权变化隔离旧权益及迟到响应",
  603. async (boundary) => {
  604. auth.state = { user: { id: "account-a" }, authSessionSeq: 1 };
  605. let finish!: (value: UsageEntitlementSnapshot) => void;
  606. const service = {
  607. getEntitlementSnapshot: vi.fn(
  608. () =>
  609. new Promise<UsageEntitlementSnapshot>((resolve) => {
  610. finish = resolve;
  611. }),
  612. ),
  613. } as unknown as IUsageStatsService;
  614. let state: ReturnType<typeof useUsageEntitlementWithService>;
  615. function Probe({ revision }: { revision: number }) {
  616. void revision;
  617. state = useUsageEntitlementWithService(service, {
  618. cacheKey: "auth-boundary",
  619. enabled: true,
  620. refreshOnMount: true,
  621. });
  622. return null;
  623. }
  624. const root = createRoot(installMinimalDom());
  625. try {
  626. await act(async () => root.render(createElement(Probe, { revision: 1 })));
  627. const completeOld = finish;
  628. if (boundary === "logout") auth.state.user = null;
  629. if (boundary === "account") auth.state.user = { id: "account-b" };
  630. if (boundary === "session") auth.state.authSessionSeq++;
  631. await act(async () => root.render(createElement(Probe, { revision: 2 })));
  632. await act(async () =>
  633. completeOld(createSnapshot({ organizationId: "old-org", projectId: "old-project" })),
  634. );
  635. expect(state!.snapshot).toBeNull();
  636. expect(
  637. readCachedUsageEntitlementSnapshot({ cacheKey: "auth-boundary:auth:account-a:1" }),
  638. ).toBeNull();
  639. if (boundary === "logout") expect(service.getEntitlementSnapshot).toHaveBeenCalledTimes(1);
  640. } finally {
  641. await act(async () => root.unmount());
  642. }
  643. },
  644. );