lease.test.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. /**
  2. * Lease Module Tests
  3. *
  4. * TDD: RED phase - tests for lease budget slicing mechanism
  5. */
  6. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  7. // Mock resolveSystemTimezone before importing lease module
  8. vi.mock("@/lib/utils/timezone", () => ({
  9. resolveSystemTimezone: vi.fn(async () => "Asia/Shanghai"),
  10. }));
  11. import { resolveSystemTimezone } from "@/lib/utils/timezone";
  12. describe("lease module", () => {
  13. const nowMs = 1706400000000; // 2024-01-28 00:00:00 UTC
  14. beforeEach(() => {
  15. vi.useFakeTimers();
  16. vi.setSystemTime(new Date(nowMs));
  17. });
  18. afterEach(() => {
  19. vi.useRealTimers();
  20. });
  21. describe("LeaseWindow type", () => {
  22. it("should support 5h, daily, weekly, monthly periods", async () => {
  23. const { LeaseWindow } = await import("@/lib/rate-limit/lease");
  24. const windows: (typeof LeaseWindow)[number][] = ["5h", "daily", "weekly", "monthly"];
  25. expect(windows).toHaveLength(4);
  26. });
  27. });
  28. describe("LeaseEntityType type", () => {
  29. it("should support key, user, provider entity types", async () => {
  30. const { LeaseEntityType } = await import("@/lib/rate-limit/lease");
  31. const types: (typeof LeaseEntityType)[number][] = ["key", "user", "provider"];
  32. expect(types).toHaveLength(3);
  33. });
  34. });
  35. describe("BudgetLease interface", () => {
  36. it("should contain required fields", async () => {
  37. const { createBudgetLease } = await import("@/lib/rate-limit/lease");
  38. const lease = createBudgetLease({
  39. entityType: "key",
  40. entityId: 123,
  41. window: "daily",
  42. resetMode: "fixed",
  43. resetTime: "18:00",
  44. snapshotAtMs: nowMs,
  45. currentUsage: 50,
  46. limitAmount: 100,
  47. remainingBudget: 2.5,
  48. ttlSeconds: 3600,
  49. });
  50. expect(lease.entityType).toBe("key");
  51. expect(lease.entityId).toBe(123);
  52. expect(lease.window).toBe("daily");
  53. expect(lease.resetMode).toBe("fixed");
  54. expect(lease.resetTime).toBe("18:00");
  55. expect(lease.snapshotAtMs).toBe(nowMs);
  56. expect(lease.currentUsage).toBe(50);
  57. expect(lease.limitAmount).toBe(100);
  58. expect(lease.remainingBudget).toBe(2.5);
  59. expect(lease.ttlSeconds).toBe(3600);
  60. });
  61. });
  62. describe("buildLeaseKey", () => {
  63. it("should build key lease key with window", async () => {
  64. const { buildLeaseKey } = await import("@/lib/rate-limit/lease");
  65. expect(buildLeaseKey("key", 123, "5h")).toBe("lease:key:123:5h");
  66. expect(buildLeaseKey("key", 456, "daily")).toBe("lease:key:456:daily");
  67. expect(buildLeaseKey("key", 789, "weekly")).toBe("lease:key:789:weekly");
  68. expect(buildLeaseKey("key", 101, "monthly")).toBe("lease:key:101:monthly");
  69. });
  70. it("should build provider lease key with window", async () => {
  71. const { buildLeaseKey } = await import("@/lib/rate-limit/lease");
  72. expect(buildLeaseKey("provider", 1, "5h")).toBe("lease:provider:1:5h");
  73. expect(buildLeaseKey("provider", 2, "daily")).toBe("lease:provider:2:daily");
  74. });
  75. it("should build user lease key with window", async () => {
  76. const { buildLeaseKey } = await import("@/lib/rate-limit/lease");
  77. expect(buildLeaseKey("user", 100, "monthly")).toBe("lease:user:100:monthly");
  78. });
  79. });
  80. describe("getLeaseTimeRange", () => {
  81. it("should return 5h rolling window range", async () => {
  82. const { getLeaseTimeRange } = await import("@/lib/rate-limit/lease");
  83. const range = await getLeaseTimeRange("5h");
  84. expect(range.endTime.getTime()).toBe(nowMs);
  85. expect(range.startTime.getTime()).toBe(nowMs - 5 * 60 * 60 * 1000);
  86. });
  87. it("should return daily rolling window range (24h)", async () => {
  88. const { getLeaseTimeRange } = await import("@/lib/rate-limit/lease");
  89. const range = await getLeaseTimeRange("daily", "00:00", "rolling");
  90. expect(range.endTime.getTime()).toBe(nowMs);
  91. expect(range.startTime.getTime()).toBe(nowMs - 24 * 60 * 60 * 1000);
  92. });
  93. it("should return daily fixed window range with custom reset time", async () => {
  94. const { getLeaseTimeRange } = await import("@/lib/rate-limit/lease");
  95. const range = await getLeaseTimeRange("daily", "18:00", "fixed");
  96. // Should calculate based on fixed reset time
  97. expect(range.endTime.getTime()).toBe(nowMs);
  98. expect(range.startTime.getTime()).toBeLessThan(nowMs);
  99. });
  100. it("should return weekly natural window range", async () => {
  101. const { getLeaseTimeRange } = await import("@/lib/rate-limit/lease");
  102. const range = await getLeaseTimeRange("weekly");
  103. expect(range.endTime.getTime()).toBe(nowMs);
  104. // Should start from Monday 00:00
  105. expect(range.startTime.getTime()).toBeLessThan(nowMs);
  106. });
  107. it("should return monthly natural window range", async () => {
  108. const { getLeaseTimeRange } = await import("@/lib/rate-limit/lease");
  109. const range = await getLeaseTimeRange("monthly");
  110. expect(range.endTime.getTime()).toBe(nowMs);
  111. // Should start from 1st of month 00:00
  112. expect(range.startTime.getTime()).toBeLessThan(nowMs);
  113. });
  114. });
  115. describe("getLeaseTtlSeconds", () => {
  116. it("should return 5h TTL for 5h window", async () => {
  117. const { getLeaseTtlSeconds } = await import("@/lib/rate-limit/lease");
  118. const ttl = await getLeaseTtlSeconds("5h");
  119. expect(ttl).toBe(5 * 3600);
  120. });
  121. it("should return 24h TTL for daily rolling window", async () => {
  122. const { getLeaseTtlSeconds } = await import("@/lib/rate-limit/lease");
  123. const ttl = await getLeaseTtlSeconds("daily", "00:00", "rolling");
  124. expect(ttl).toBe(24 * 3600);
  125. });
  126. it("should return dynamic TTL for daily fixed window", async () => {
  127. const { getLeaseTtlSeconds } = await import("@/lib/rate-limit/lease");
  128. const ttl = await getLeaseTtlSeconds("daily", "18:00", "fixed");
  129. // Should be positive and less than 24h
  130. expect(ttl).toBeGreaterThan(0);
  131. expect(ttl).toBeLessThanOrEqual(24 * 3600);
  132. });
  133. it("should return dynamic TTL for weekly window", async () => {
  134. const { getLeaseTtlSeconds } = await import("@/lib/rate-limit/lease");
  135. const ttl = await getLeaseTtlSeconds("weekly");
  136. // Should be positive and less than 7 days
  137. expect(ttl).toBeGreaterThan(0);
  138. expect(ttl).toBeLessThanOrEqual(7 * 24 * 3600);
  139. });
  140. it("should return dynamic TTL for monthly window", async () => {
  141. const { getLeaseTtlSeconds } = await import("@/lib/rate-limit/lease");
  142. const ttl = await getLeaseTtlSeconds("monthly");
  143. // Should be positive and less than 31 days
  144. expect(ttl).toBeGreaterThan(0);
  145. expect(ttl).toBeLessThanOrEqual(31 * 24 * 3600);
  146. });
  147. });
  148. describe("calculateLeaseSlice", () => {
  149. it("should calculate slice as percentage of limit", async () => {
  150. const { calculateLeaseSlice } = await import("@/lib/rate-limit/lease");
  151. // limit=100, percent=0.05 -> slice=5
  152. const slice = calculateLeaseSlice({
  153. limitAmount: 100,
  154. currentUsage: 0,
  155. percent: 0.05,
  156. });
  157. expect(slice).toBe(5);
  158. });
  159. it("should not exceed remaining budget (limit - usage)", async () => {
  160. const { calculateLeaseSlice } = await import("@/lib/rate-limit/lease");
  161. // limit=100, usage=98, percent=0.05 -> remaining=2, slice=min(5,2)=2
  162. const slice = calculateLeaseSlice({
  163. limitAmount: 100,
  164. currentUsage: 98,
  165. percent: 0.05,
  166. });
  167. expect(slice).toBe(2);
  168. });
  169. it("should respect capUsd if provided", async () => {
  170. const { calculateLeaseSlice } = await import("@/lib/rate-limit/lease");
  171. // limit=1000, percent=0.05 -> 50, but cap=3 -> slice=3
  172. const slice = calculateLeaseSlice({
  173. limitAmount: 1000,
  174. currentUsage: 0,
  175. percent: 0.05,
  176. capUsd: 3,
  177. });
  178. expect(slice).toBe(3);
  179. });
  180. it("should return 0 when usage exceeds limit", async () => {
  181. const { calculateLeaseSlice } = await import("@/lib/rate-limit/lease");
  182. const slice = calculateLeaseSlice({
  183. limitAmount: 100,
  184. currentUsage: 105,
  185. percent: 0.05,
  186. });
  187. expect(slice).toBe(0);
  188. });
  189. it("should return 0 when usage equals limit", async () => {
  190. const { calculateLeaseSlice } = await import("@/lib/rate-limit/lease");
  191. const slice = calculateLeaseSlice({
  192. limitAmount: 100,
  193. currentUsage: 100,
  194. percent: 0.05,
  195. });
  196. expect(slice).toBe(0);
  197. });
  198. it("should round to 4 decimal places", async () => {
  199. const { calculateLeaseSlice } = await import("@/lib/rate-limit/lease");
  200. const slice = calculateLeaseSlice({
  201. limitAmount: 33.333333,
  202. currentUsage: 0,
  203. percent: 0.05,
  204. });
  205. // 33.333333 * 0.05 = 1.6666666...
  206. expect(slice).toBe(1.6667);
  207. });
  208. });
  209. describe("serializeLease / deserializeLease", () => {
  210. it("should serialize lease to JSON string", async () => {
  211. const { createBudgetLease, serializeLease } = await import("@/lib/rate-limit/lease");
  212. const lease = createBudgetLease({
  213. entityType: "key",
  214. entityId: 123,
  215. window: "daily",
  216. resetMode: "fixed",
  217. resetTime: "18:00",
  218. snapshotAtMs: nowMs,
  219. currentUsage: 50,
  220. limitAmount: 100,
  221. remainingBudget: 2.5,
  222. ttlSeconds: 3600,
  223. });
  224. const json = serializeLease(lease);
  225. expect(typeof json).toBe("string");
  226. const parsed = JSON.parse(json);
  227. expect(parsed.entityType).toBe("key");
  228. expect(parsed.remainingBudget).toBe(2.5);
  229. });
  230. it("should deserialize JSON string to lease", async () => {
  231. const { createBudgetLease, deserializeLease, serializeLease } = await import(
  232. "@/lib/rate-limit/lease"
  233. );
  234. const original = createBudgetLease({
  235. entityType: "provider",
  236. entityId: 456,
  237. window: "weekly",
  238. resetMode: "fixed",
  239. resetTime: "00:00",
  240. snapshotAtMs: nowMs,
  241. currentUsage: 25,
  242. limitAmount: 200,
  243. remainingBudget: 10,
  244. ttlSeconds: 86400,
  245. });
  246. const json = serializeLease(original);
  247. const restored = deserializeLease(json);
  248. expect(restored).not.toBeNull();
  249. expect(restored?.entityType).toBe("provider");
  250. expect(restored?.entityId).toBe(456);
  251. expect(restored?.remainingBudget).toBe(10);
  252. });
  253. it("should return null for invalid JSON", async () => {
  254. const { deserializeLease } = await import("@/lib/rate-limit/lease");
  255. const result = deserializeLease("invalid json");
  256. expect(result).toBeNull();
  257. });
  258. it("should return null for incomplete lease data", async () => {
  259. const { deserializeLease } = await import("@/lib/rate-limit/lease");
  260. const result = deserializeLease(JSON.stringify({ entityType: "key" }));
  261. expect(result).toBeNull();
  262. });
  263. });
  264. describe("isLeaseExpired", () => {
  265. it("should return true when TTL has passed", async () => {
  266. const { createBudgetLease, isLeaseExpired } = await import("@/lib/rate-limit/lease");
  267. const lease = createBudgetLease({
  268. entityType: "key",
  269. entityId: 123,
  270. window: "daily",
  271. resetMode: "fixed",
  272. resetTime: "00:00",
  273. snapshotAtMs: nowMs - 3700 * 1000, // Created 3700s ago
  274. currentUsage: 50,
  275. limitAmount: 100,
  276. remainingBudget: 2.5,
  277. ttlSeconds: 3600, // 1 hour TTL
  278. });
  279. expect(isLeaseExpired(lease)).toBe(true);
  280. });
  281. it("should return false when TTL has not passed", async () => {
  282. const { createBudgetLease, isLeaseExpired } = await import("@/lib/rate-limit/lease");
  283. const lease = createBudgetLease({
  284. entityType: "key",
  285. entityId: 123,
  286. window: "daily",
  287. resetMode: "fixed",
  288. resetTime: "00:00",
  289. snapshotAtMs: nowMs - 1800 * 1000, // Created 1800s ago
  290. currentUsage: 50,
  291. limitAmount: 100,
  292. remainingBudget: 2.5,
  293. ttlSeconds: 3600, // 1 hour TTL
  294. });
  295. expect(isLeaseExpired(lease)).toBe(false);
  296. });
  297. });
  298. });
  299. /**
  300. * Lease Module Timezone Consistency Tests
  301. *
  302. * Verify that lease module delegates to time-utils correctly
  303. * and produces consistent timezone behavior
  304. */
  305. describe("lease timezone consistency", () => {
  306. beforeEach(() => {
  307. vi.useFakeTimers();
  308. vi.clearAllMocks();
  309. });
  310. afterEach(() => {
  311. vi.useRealTimers();
  312. });
  313. describe("getLeaseTimeRange timezone behavior", () => {
  314. it("should use configured timezone for daily fixed window", async () => {
  315. const { getLeaseTimeRange } = await import("@/lib/rate-limit/lease");
  316. // 2024-01-15 02:00:00 UTC = 2024-01-15 10:00:00 Shanghai
  317. const utcTime = new Date("2024-01-15T02:00:00.000Z");
  318. vi.setSystemTime(utcTime);
  319. vi.mocked(resolveSystemTimezone).mockResolvedValue("Asia/Shanghai");
  320. // Reset at 08:00 Shanghai, we've passed it
  321. const range = await getLeaseTimeRange("daily", "08:00", "fixed");
  322. // Window starts at 08:00 Shanghai = 00:00 UTC
  323. expect(range.startTime.toISOString()).toBe("2024-01-15T00:00:00.000Z");
  324. expect(range.endTime.toISOString()).toBe("2024-01-15T02:00:00.000Z");
  325. });
  326. it("should use configured timezone for weekly window", async () => {
  327. const { getLeaseTimeRange } = await import("@/lib/rate-limit/lease");
  328. // 2024-01-17 00:00:00 UTC = Wednesday 08:00 Shanghai
  329. const utcTime = new Date("2024-01-17T00:00:00.000Z");
  330. vi.setSystemTime(utcTime);
  331. vi.mocked(resolveSystemTimezone).mockResolvedValue("Asia/Shanghai");
  332. const range = await getLeaseTimeRange("weekly");
  333. // Monday 00:00 Shanghai = Sunday 16:00 UTC
  334. expect(range.startTime.toISOString()).toBe("2024-01-14T16:00:00.000Z");
  335. });
  336. it("should use configured timezone for monthly window", async () => {
  337. const { getLeaseTimeRange } = await import("@/lib/rate-limit/lease");
  338. // 2024-01-15 00:00:00 UTC = 2024-01-15 08:00 Shanghai
  339. const utcTime = new Date("2024-01-15T00:00:00.000Z");
  340. vi.setSystemTime(utcTime);
  341. vi.mocked(resolveSystemTimezone).mockResolvedValue("Asia/Shanghai");
  342. const range = await getLeaseTimeRange("monthly");
  343. // Jan 1 00:00 Shanghai = Dec 31 16:00 UTC
  344. expect(range.startTime.toISOString()).toBe("2023-12-31T16:00:00.000Z");
  345. });
  346. it("should ignore timezone for rolling windows (5h)", async () => {
  347. const { getLeaseTimeRange } = await import("@/lib/rate-limit/lease");
  348. const utcTime = new Date("2024-01-15T12:00:00.000Z");
  349. vi.setSystemTime(utcTime);
  350. vi.mocked(resolveSystemTimezone).mockResolvedValue("America/New_York");
  351. const range = await getLeaseTimeRange("5h");
  352. // 5h is always rolling, timezone doesn't matter
  353. expect(range.startTime.toISOString()).toBe("2024-01-15T07:00:00.000Z");
  354. expect(range.endTime.toISOString()).toBe("2024-01-15T12:00:00.000Z");
  355. });
  356. it("should ignore timezone for daily rolling window", async () => {
  357. const { getLeaseTimeRange } = await import("@/lib/rate-limit/lease");
  358. const utcTime = new Date("2024-01-15T12:00:00.000Z");
  359. vi.setSystemTime(utcTime);
  360. vi.mocked(resolveSystemTimezone).mockResolvedValue("Europe/London");
  361. const range = await getLeaseTimeRange("daily", "08:00", "rolling");
  362. // Daily rolling is 24h back, timezone doesn't matter
  363. expect(range.startTime.toISOString()).toBe("2024-01-14T12:00:00.000Z");
  364. expect(range.endTime.toISOString()).toBe("2024-01-15T12:00:00.000Z");
  365. });
  366. });
  367. describe("getLeaseTtlSeconds timezone behavior", () => {
  368. it("should calculate TTL based on configured timezone for daily fixed", async () => {
  369. const { getLeaseTtlSeconds } = await import("@/lib/rate-limit/lease");
  370. // 2024-01-15 02:00:00 UTC = 2024-01-15 10:00:00 Shanghai
  371. const utcTime = new Date("2024-01-15T02:00:00.000Z");
  372. vi.setSystemTime(utcTime);
  373. vi.mocked(resolveSystemTimezone).mockResolvedValue("Asia/Shanghai");
  374. // Next reset at 08:00 Shanghai tomorrow = 22 hours away
  375. const ttl = await getLeaseTtlSeconds("daily", "08:00", "fixed");
  376. expect(ttl).toBe(22 * 3600);
  377. });
  378. it("should calculate TTL based on configured timezone for weekly", async () => {
  379. const { getLeaseTtlSeconds } = await import("@/lib/rate-limit/lease");
  380. // 2024-01-17 00:00:00 UTC = Wednesday 08:00 Shanghai
  381. const utcTime = new Date("2024-01-17T00:00:00.000Z");
  382. vi.setSystemTime(utcTime);
  383. vi.mocked(resolveSystemTimezone).mockResolvedValue("Asia/Shanghai");
  384. // Next Monday 00:00 Shanghai = 112 hours away
  385. const ttl = await getLeaseTtlSeconds("weekly");
  386. expect(ttl).toBe(112 * 3600);
  387. });
  388. it("should return fixed TTL for rolling windows", async () => {
  389. const { getLeaseTtlSeconds } = await import("@/lib/rate-limit/lease");
  390. vi.mocked(resolveSystemTimezone).mockResolvedValue("Pacific/Auckland");
  391. expect(await getLeaseTtlSeconds("5h")).toBe(5 * 3600);
  392. expect(await getLeaseTtlSeconds("daily", "08:00", "rolling")).toBe(24 * 3600);
  393. });
  394. });
  395. describe("cross-module consistency", () => {
  396. it("should produce same results as time-utils for daily fixed", async () => {
  397. const { getLeaseTimeRange, getLeaseTtlSeconds } = await import("@/lib/rate-limit/lease");
  398. const { getTimeRangeForPeriod, getTTLForPeriod } = await import(
  399. "@/lib/rate-limit/time-utils"
  400. );
  401. const utcTime = new Date("2024-01-15T02:00:00.000Z");
  402. vi.setSystemTime(utcTime);
  403. vi.mocked(resolveSystemTimezone).mockResolvedValue("Asia/Shanghai");
  404. const leaseRange = await getLeaseTimeRange("daily", "08:00", "fixed");
  405. const timeUtilsRange = await getTimeRangeForPeriod("daily", "08:00");
  406. expect(leaseRange.startTime.toISOString()).toBe(timeUtilsRange.startTime.toISOString());
  407. expect(leaseRange.endTime.toISOString()).toBe(timeUtilsRange.endTime.toISOString());
  408. const leaseTtl = await getLeaseTtlSeconds("daily", "08:00", "fixed");
  409. const timeUtilsTtl = await getTTLForPeriod("daily", "08:00");
  410. expect(leaseTtl).toBe(timeUtilsTtl);
  411. });
  412. it("should produce same results as time-utils for weekly", async () => {
  413. const { getLeaseTimeRange, getLeaseTtlSeconds } = await import("@/lib/rate-limit/lease");
  414. const { getTimeRangeForPeriod, getTTLForPeriod } = await import(
  415. "@/lib/rate-limit/time-utils"
  416. );
  417. const utcTime = new Date("2024-01-17T00:00:00.000Z");
  418. vi.setSystemTime(utcTime);
  419. vi.mocked(resolveSystemTimezone).mockResolvedValue("Asia/Shanghai");
  420. const leaseRange = await getLeaseTimeRange("weekly");
  421. const timeUtilsRange = await getTimeRangeForPeriod("weekly");
  422. expect(leaseRange.startTime.toISOString()).toBe(timeUtilsRange.startTime.toISOString());
  423. const leaseTtl = await getLeaseTtlSeconds("weekly");
  424. const timeUtilsTtl = await getTTLForPeriod("weekly");
  425. expect(leaseTtl).toBe(timeUtilsTtl);
  426. });
  427. it("should produce same results as time-utils for monthly", async () => {
  428. const { getLeaseTimeRange, getLeaseTtlSeconds } = await import("@/lib/rate-limit/lease");
  429. const { getTimeRangeForPeriod, getTTLForPeriod } = await import(
  430. "@/lib/rate-limit/time-utils"
  431. );
  432. const utcTime = new Date("2024-01-15T00:00:00.000Z");
  433. vi.setSystemTime(utcTime);
  434. vi.mocked(resolveSystemTimezone).mockResolvedValue("Asia/Shanghai");
  435. const leaseRange = await getLeaseTimeRange("monthly");
  436. const timeUtilsRange = await getTimeRangeForPeriod("monthly");
  437. expect(leaseRange.startTime.toISOString()).toBe(timeUtilsRange.startTime.toISOString());
  438. const leaseTtl = await getLeaseTtlSeconds("monthly");
  439. const timeUtilsTtl = await getTTLForPeriod("monthly");
  440. expect(leaseTtl).toBe(timeUtilsTtl);
  441. });
  442. });
  443. });