total-usage-semantics.test.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. /**
  2. * total-usage-semantics tests
  3. *
  4. * Verify that total usage reads in display paths use ALL_TIME_MAX_AGE_DAYS (Infinity)
  5. * to skip the date filter entirely, querying all-time data.
  6. *
  7. * Key insight: The usage/quota aggregation functions default maxAgeDays to 365.
  8. * For display purposes (showing "total" usage), we want all-time semantics, which
  9. * means passing Infinity to skip the date filter.
  10. *
  11. * IMPORTANT: This test only covers DISPLAY paths. Enforcement paths (RateLimitService)
  12. * are intentionally NOT modified.
  13. */
  14. import { beforeEach, describe, expect, it, vi } from "vitest";
  15. // All-time max age constant - Infinity means no date filter
  16. const ALL_TIME_MAX_AGE_DAYS = Infinity;
  17. // Mock functions
  18. const getSessionMock = vi.fn();
  19. const sumUserTotalCostMock = vi.fn();
  20. const sumKeyQuotaCostsByIdMock = vi.fn();
  21. const sumUserQuotaCostsMock = vi.fn();
  22. const sumUserCostInTimeRangeMock = vi.fn();
  23. const getTimeRangeForPeriodMock = vi.fn();
  24. const getTimeRangeForPeriodWithModeMock = vi.fn();
  25. const getKeySessionCountMock = vi.fn();
  26. const getUserSessionCountMock = vi.fn();
  27. const findUserByIdMock = vi.fn();
  28. // Mock modules
  29. vi.mock("@/lib/auth", () => ({
  30. getSession: () => getSessionMock(),
  31. }));
  32. vi.mock("@/repository/statistics", () => ({
  33. sumUserCostInTimeRange: (...args: unknown[]) => sumUserCostInTimeRangeMock(...args),
  34. sumUserTotalCost: (...args: unknown[]) => sumUserTotalCostMock(...args),
  35. sumKeyQuotaCostsById: (...args: unknown[]) => sumKeyQuotaCostsByIdMock(...args),
  36. sumUserQuotaCosts: (...args: unknown[]) => sumUserQuotaCostsMock(...args),
  37. }));
  38. vi.mock("@/lib/rate-limit/time-utils", () => ({
  39. getTimeRangeForPeriod: (...args: unknown[]) => getTimeRangeForPeriodMock(...args),
  40. getTimeRangeForPeriodWithMode: (...args: unknown[]) => getTimeRangeForPeriodWithModeMock(...args),
  41. }));
  42. vi.mock("@/lib/session-tracker", () => ({
  43. SessionTracker: {
  44. getKeySessionCount: (...args: unknown[]) => getKeySessionCountMock(...args),
  45. getUserSessionCount: (...args: unknown[]) => getUserSessionCountMock(...args),
  46. },
  47. }));
  48. vi.mock("@/repository/user", () => ({
  49. findUserById: (...args: unknown[]) => findUserByIdMock(...args),
  50. }));
  51. vi.mock("@/lib/logger", () => ({
  52. logger: {
  53. trace: vi.fn(),
  54. debug: vi.fn(),
  55. info: vi.fn(),
  56. warn: vi.fn(),
  57. error: vi.fn(),
  58. },
  59. }));
  60. vi.mock("next-intl/server", () => ({
  61. getTranslations: vi.fn(() => (key: string) => key),
  62. }));
  63. describe("total-usage-semantics", () => {
  64. beforeEach(() => {
  65. vi.clearAllMocks();
  66. // Default time range mocks
  67. const now = new Date();
  68. const defaultRange = { startTime: now, endTime: now };
  69. getTimeRangeForPeriodMock.mockResolvedValue(defaultRange);
  70. getTimeRangeForPeriodWithModeMock.mockResolvedValue(defaultRange);
  71. // Default cost mocks
  72. sumUserTotalCostMock.mockResolvedValue(0);
  73. sumUserCostInTimeRangeMock.mockResolvedValue(0);
  74. getKeySessionCountMock.mockResolvedValue(0);
  75. getUserSessionCountMock.mockResolvedValue(0);
  76. const emptyCosts = {
  77. cost5h: 0,
  78. costDaily: 0,
  79. costWeekly: 0,
  80. costMonthly: 0,
  81. costTotal: 0,
  82. };
  83. sumKeyQuotaCostsByIdMock.mockResolvedValue(emptyCosts);
  84. sumUserQuotaCostsMock.mockResolvedValue(emptyCosts);
  85. });
  86. describe("getMyQuota in my-usage.ts", () => {
  87. it("should call sumKeyQuotaCostsById with ALL_TIME_MAX_AGE_DAYS for key total cost", async () => {
  88. // Setup session mock
  89. getSessionMock.mockResolvedValue({
  90. key: {
  91. id: 1,
  92. key: "test-key-hash",
  93. name: "Test Key",
  94. dailyResetTime: "00:00",
  95. dailyResetMode: "fixed",
  96. limit5hUsd: null,
  97. limitDailyUsd: null,
  98. limitWeeklyUsd: null,
  99. limitMonthlyUsd: null,
  100. limitTotalUsd: null,
  101. limitConcurrentSessions: null,
  102. providerGroup: null,
  103. isEnabled: true,
  104. expiresAt: null,
  105. },
  106. user: {
  107. id: 1,
  108. name: "Test User",
  109. dailyResetTime: "00:00",
  110. dailyResetMode: "fixed",
  111. limit5hUsd: null,
  112. dailyQuota: null,
  113. limitWeeklyUsd: null,
  114. limitMonthlyUsd: null,
  115. limitTotalUsd: null,
  116. limitConcurrentSessions: null,
  117. rpm: null,
  118. providerGroup: null,
  119. isEnabled: true,
  120. expiresAt: null,
  121. allowedModels: [],
  122. allowedClients: [],
  123. },
  124. });
  125. // Import and call the function
  126. const { getMyQuota } = await import("@/actions/my-usage");
  127. await getMyQuota();
  128. expect(sumKeyQuotaCostsByIdMock).toHaveBeenCalledWith(
  129. 1,
  130. expect.any(Object),
  131. ALL_TIME_MAX_AGE_DAYS,
  132. null
  133. );
  134. });
  135. it("should call sumUserQuotaCosts with ALL_TIME_MAX_AGE_DAYS for user total cost", async () => {
  136. // Setup session mock
  137. getSessionMock.mockResolvedValue({
  138. key: {
  139. id: 1,
  140. key: "test-key-hash",
  141. name: "Test Key",
  142. dailyResetTime: "00:00",
  143. dailyResetMode: "fixed",
  144. limit5hUsd: null,
  145. limitDailyUsd: null,
  146. limitWeeklyUsd: null,
  147. limitMonthlyUsd: null,
  148. limitTotalUsd: null,
  149. limitConcurrentSessions: null,
  150. providerGroup: null,
  151. isEnabled: true,
  152. expiresAt: null,
  153. },
  154. user: {
  155. id: 1,
  156. name: "Test User",
  157. dailyResetTime: "00:00",
  158. dailyResetMode: "fixed",
  159. limit5hUsd: null,
  160. dailyQuota: null,
  161. limitWeeklyUsd: null,
  162. limitMonthlyUsd: null,
  163. limitTotalUsd: null,
  164. limitConcurrentSessions: null,
  165. rpm: null,
  166. providerGroup: null,
  167. isEnabled: true,
  168. expiresAt: null,
  169. allowedModels: [],
  170. allowedClients: [],
  171. },
  172. });
  173. // Import and call the function
  174. const { getMyQuota } = await import("@/actions/my-usage");
  175. await getMyQuota();
  176. expect(sumUserQuotaCostsMock).toHaveBeenCalledWith(
  177. 1,
  178. expect.any(Object),
  179. ALL_TIME_MAX_AGE_DAYS,
  180. null
  181. );
  182. });
  183. });
  184. describe("getUserAllLimitUsage in users.ts", () => {
  185. it("should call sumUserTotalCost with ALL_TIME_MAX_AGE_DAYS", async () => {
  186. // Setup session mock
  187. getSessionMock.mockResolvedValue({
  188. user: {
  189. id: 1,
  190. role: "admin",
  191. },
  192. });
  193. // Setup user mock
  194. findUserByIdMock.mockResolvedValue({
  195. id: 1,
  196. name: "Test User",
  197. dailyResetTime: "00:00",
  198. dailyResetMode: "fixed",
  199. limit5hUsd: null,
  200. dailyQuota: null,
  201. limitWeeklyUsd: null,
  202. limitMonthlyUsd: null,
  203. limitTotalUsd: null,
  204. });
  205. // Import and call the function
  206. const { getUserAllLimitUsage } = await import("@/actions/users");
  207. await getUserAllLimitUsage(1);
  208. // Verify sumUserTotalCost was called with Infinity (all-time)
  209. // 3rd arg is user.costResetAt (undefined when not set on mock user)
  210. const calls = sumUserTotalCostMock.mock.calls;
  211. expect(calls.length).toBe(1);
  212. expect(calls[0][0]).toBe(1);
  213. expect(calls[0][1]).toBe(Infinity);
  214. });
  215. });
  216. describe("ALL_TIME_MAX_AGE_DAYS constant value", () => {
  217. it("should be Infinity for all-time semantics", () => {
  218. expect(ALL_TIME_MAX_AGE_DAYS).toBe(Infinity);
  219. });
  220. });
  221. });