cache-contract-audit.mjs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. // Local diagnostic: transpile the real cache service, using synthetic identity
  2. // and in-memory storage. No application bundle, server, network or real session.
  3. import assert from 'node:assert/strict';
  4. import { execFileSync } from 'node:child_process';
  5. import vm from 'node:vm';
  6. import ts from 'typescript';
  7. import { firstValueFrom, of } from 'rxjs';
  8. import * as rxjs from 'rxjs';
  9. const servicePath = new URL('../../projects/xiaoshu-mobile/src/app/core/home-daily-cache.service.ts', import.meta.url);
  10. // Keep the original failure reproducible after the service has been fixed.
  11. const compiled = ts.transpileModule(execFileSync('git',['show','0e371fd:projects/xiaoshu-mobile/src/app/core/home-daily-cache.service.ts'],{encoding:'utf8'}), {
  12. compilerOptions: {
  13. target: ts.ScriptTarget.ES2022,
  14. module: ts.ModuleKind.CommonJS,
  15. experimentalDecorators: true,
  16. },
  17. }).outputText;
  18. const STORAGE_KEY = 'xiaoshu.learning.homeDaily.v1';
  19. const morning = '2026-11-14T01:00:00.000Z';
  20. const afternoon = '2026-11-14T07:00:00.000Z';
  21. const identity = '20|1|2026-11-14';
  22. const oldPage = {
  23. items: [], dates: [],
  24. summary: { total: 0, completed: 0, due: 0, today: 0, income: 0 },
  25. legacyReviewSync: { state: 'current' },
  26. };
  27. function fixture(value) {
  28. const storage = new Map([[STORAGE_KEY, JSON.stringify({
  29. identity, values: { review: { value, updatedAt: morning } },
  30. })]]);
  31. class LocalDate extends Date {
  32. constructor(...args) { super(...(args.length ? args : [afternoon])); }
  33. static now() { return Date.parse(afternoon); }
  34. }
  35. const session = {
  36. user: () => ({ userId: 20, groupId: 1 }),
  37. token: () => 'isolated-cache-audit-fixture',
  38. };
  39. const sandbox = {
  40. exports: {}, Date: LocalDate,
  41. localStorage: {
  42. getItem: key => storage.get(key) ?? null,
  43. setItem: (key, item) => storage.set(key, item),
  44. removeItem: key => storage.delete(key),
  45. },
  46. require: name => {
  47. if (name === '@angular/core') return {
  48. Injectable: () => target => target,
  49. inject: token => {
  50. if (token === 'SessionService') return session;
  51. if (token === 'NgZone') return {};
  52. throw new Error(`Unexpected injection: ${token}`);
  53. },
  54. NgZone: 'NgZone',
  55. };
  56. if (name === 'rxjs') return rxjs;
  57. if (name === './session.service') return { SessionService: 'SessionService' };
  58. if (name === './teacher-today-review.service') return { beijingToday: () => '2026-11-14' };
  59. throw new Error(`Unexpected module: ${name}`);
  60. },
  61. };
  62. vm.runInNewContext(compiled, sandbox, { filename: servicePath.pathname });
  63. return new sandbox.exports.HomeDailyCacheService();
  64. }
  65. const reports = [];
  66. {
  67. const cache = fixture(oldPage);
  68. let fetches = 0;
  69. const snapshot = await firstValueFrom(cache.load('review', () => {
  70. fetches++;
  71. return of({ ...oldPage, view: 'home', legacyReviewSync: { state: 'snapshot' } });
  72. }));
  73. assert.equal(fetches, 0);
  74. assert.equal(snapshot.value.legacyReviewSync.state, 'current');
  75. assert.equal(snapshot.value.view, undefined);
  76. reports.push({
  77. case: 'same-day cache from old release bypasses new home endpoint',
  78. fetches, retainedLegacyReviewSyncState: snapshot.value.legacyReviewSync.state,
  79. hasNewHomeView: snapshot.value.view === 'home',
  80. implication: 'HomePage reviewSyncNotice requires snapshot state, so this cached response does not show the new notice.',
  81. });
  82. }
  83. {
  84. const cache = fixture({
  85. ...oldPage, view: 'home',
  86. legacyReviewSync: { state: 'snapshot', lastSuccessAt: morning },
  87. syncStatus: { state: 'current', lastSuccessAt: morning },
  88. });
  89. let fetches = 0;
  90. const fetch = () => {
  91. fetches++;
  92. return of({ ...oldPage, view: 'home', legacyReviewSync: { state: 'snapshot' }, syncStatus: { state: 'delayed' } });
  93. };
  94. const snapshot = await firstValueFrom(cache.load('review', fetch));
  95. assert.equal(fetches, 0);
  96. assert.equal(snapshot.value.syncStatus.state, 'current');
  97. assert.equal(snapshot.updatedAt, morning);
  98. const forced = await firstValueFrom(cache.load('review', fetch, true));
  99. assert.equal(fetches, 1);
  100. assert.equal(forced.value.syncStatus.state, 'delayed');
  101. assert.equal(forced.updatedAt, afternoon);
  102. reports.push({
  103. case: 'same-day cached sync status stays current until forced reload',
  104. simulatedNow: afternoon, cachedAt: snapshot.updatedAt,
  105. ordinaryFetches: 0, ordinaryState: snapshot.value.syncStatus.state,
  106. forcedFetches: fetches, forcedState: forced.value.syncStatus.state,
  107. implication: 'The stored sync status describes the morning read, not a live check at the later visit.',
  108. });
  109. }
  110. console.log(JSON.stringify({
  111. scope: 'Historical baseline 0e371fd service/cache contract only; no network, production identity, business writes or production-cause inference.',
  112. passed: reports.length, reports,
  113. }, null, 2));