|
| 1 | +jest.mock('@kilocode/web-shared/lib/config.server', () => ({ |
| 2 | + USAGE_INGEST_URL: 'https://usage.example.test/usage', |
| 3 | + USAGE_INGEST_PUBLISH_SECRET: 'synthetic-publisher-secret', |
| 4 | +})); |
| 5 | + |
| 6 | +import { afterEach, beforeEach, describe, expect, test } from '@jest/globals'; |
| 7 | +import { createServer } from 'node:http'; |
| 8 | +import { enqueueUsage, USAGE_ENQUEUE_TIMEOUT_MS } from './usage-publisher'; |
| 9 | +import type { UsageRecordRequest } from '@kilocode/usage-contracts'; |
| 10 | + |
| 11 | +const payload: UsageRecordRequest = { |
| 12 | + core: { |
| 13 | + id: '3f2504e0-4f89-11d3-9a0c-0305e82c3301', |
| 14 | + kilo_user_id: 'oauth/synthetic', |
| 15 | + cost: 1234, |
| 16 | + input_tokens: 10, |
| 17 | + output_tokens: 20, |
| 18 | + cache_write_tokens: 0, |
| 19 | + cache_hit_tokens: 0, |
| 20 | + created_at: '2026-08-05T10:11:12.945Z', |
| 21 | + provider: 'openrouter', |
| 22 | + model: 'synthetic-model', |
| 23 | + requested_model: 'synthetic-model', |
| 24 | + cache_discount: null, |
| 25 | + has_error: false, |
| 26 | + abuse_classification: 0, |
| 27 | + organization_id: null, |
| 28 | + inference_provider: null, |
| 29 | + project_id: null, |
| 30 | + }, |
| 31 | + metadata: { |
| 32 | + id: '3f2504e0-4f89-11d3-9a0c-0305e82c3301', |
| 33 | + message_id: 'msg-1', |
| 34 | + created_at: '2026-08-05T10:11:12.945Z', |
| 35 | + http_x_forwarded_for: null, |
| 36 | + http_x_vercel_ip_city: null, |
| 37 | + http_x_vercel_ip_country: null, |
| 38 | + http_x_vercel_ip_latitude: null, |
| 39 | + http_x_vercel_ip_longitude: null, |
| 40 | + http_x_vercel_ja4_digest: null, |
| 41 | + user_prompt_prefix: '🙂', |
| 42 | + system_prompt_prefix: null, |
| 43 | + system_prompt_length: null, |
| 44 | + http_user_agent: null, |
| 45 | + max_tokens: null, |
| 46 | + has_middle_out_transform: null, |
| 47 | + status_code: 200, |
| 48 | + upstream_id: null, |
| 49 | + finish_reason: 'stop', |
| 50 | + latency: null, |
| 51 | + moderation_latency: null, |
| 52 | + generation_time: null, |
| 53 | + is_byok: null, |
| 54 | + is_user_byok: false, |
| 55 | + streamed: null, |
| 56 | + cancelled: null, |
| 57 | + editor_name: null, |
| 58 | + api_kind: 'chat_completions', |
| 59 | + has_tools: null, |
| 60 | + machine_id: null, |
| 61 | + feature: null, |
| 62 | + session_id: null, |
| 63 | + mode: null, |
| 64 | + auto_model: null, |
| 65 | + reasoning_setting: 'medium', |
| 66 | + market_cost: null, |
| 67 | + is_free: null, |
| 68 | + abuse_delay: null, |
| 69 | + abuse_downgraded_from: null, |
| 70 | + }, |
| 71 | + prior_microdollar_usage: 0, |
| 72 | + posthog_distinct_id: null, |
| 73 | +}; |
| 74 | + |
| 75 | +const config = jest.requireMock<{ |
| 76 | + USAGE_INGEST_URL: string; |
| 77 | + USAGE_INGEST_PUBLISH_SECRET: string; |
| 78 | +}>('@kilocode/web-shared/lib/config.server'); |
| 79 | +const mockFetch = jest.fn<ReturnType<typeof fetch>, Parameters<typeof fetch>>(); |
| 80 | +const nativeFetch = globalThis.fetch; |
| 81 | +let warn: jest.SpiedFunction<typeof console.warn>; |
| 82 | + |
| 83 | +beforeEach(() => { |
| 84 | + config.USAGE_INGEST_URL = 'https://usage.example.test/usage'; |
| 85 | + config.USAGE_INGEST_PUBLISH_SECRET = 'synthetic-publisher-secret'; |
| 86 | + mockFetch.mockReset(); |
| 87 | + jest.spyOn(globalThis, 'fetch').mockImplementation(mockFetch); |
| 88 | + warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); |
| 89 | +}); |
| 90 | + |
| 91 | +afterEach(() => { |
| 92 | + jest.restoreAllMocks(); |
| 93 | +}); |
| 94 | + |
| 95 | +function expectUnavailableWarning(reason: string) { |
| 96 | + expect(warn.mock.calls).toEqual([ |
| 97 | + ['usage enqueue unavailable', { usageId: payload.core.id, kind: 'unavailable', reason }], |
| 98 | + ]); |
| 99 | + const logged = JSON.stringify(warn.mock.calls); |
| 100 | + expect(logged).not.toContain(config.USAGE_INGEST_URL); |
| 101 | + expect(logged).not.toContain(config.USAGE_INGEST_PUBLISH_SECRET); |
| 102 | + expect(logged).not.toMatch(/Bearer|sensitive|prompt|metadata/); |
| 103 | +} |
| 104 | + |
| 105 | +describe('enqueueUsage', () => { |
| 106 | + test('preserves the complete payload and ID with dedicated publisher authentication', async () => { |
| 107 | + const event = { |
| 108 | + ...payload, |
| 109 | + bouncer_usage_event: { request_id: 'synthetic-request', payload: { cost: 1234 } }, |
| 110 | + } satisfies UsageRecordRequest; |
| 111 | + const response = new Response(null, { status: 202 }); |
| 112 | + const read = jest.spyOn(response, 'text'); |
| 113 | + mockFetch.mockResolvedValue(response); |
| 114 | + const timeout = jest.spyOn(AbortSignal, 'timeout'); |
| 115 | + |
| 116 | + expect(await enqueueUsage(event)).toEqual({ kind: 'accepted' }); |
| 117 | + expect(mockFetch).toHaveBeenCalledTimes(1); |
| 118 | + expect(mockFetch).toHaveBeenCalledWith('https://usage.example.test/usage', { |
| 119 | + method: 'POST', |
| 120 | + headers: { |
| 121 | + 'content-type': 'application/json', |
| 122 | + Authorization: 'Bearer synthetic-publisher-secret', |
| 123 | + }, |
| 124 | + body: JSON.stringify(event), |
| 125 | + signal: expect.any(AbortSignal), |
| 126 | + cache: 'no-store', |
| 127 | + redirect: 'error', |
| 128 | + }); |
| 129 | + expect(timeout).toHaveBeenCalledWith(USAGE_ENQUEUE_TIMEOUT_MS); |
| 130 | + expect(read).not.toHaveBeenCalled(); |
| 131 | + expect(warn).not.toHaveBeenCalled(); |
| 132 | + }); |
| 133 | + |
| 134 | + test.each(['USAGE_INGEST_URL', 'USAGE_INGEST_PUBLISH_SECRET'] as const)( |
| 135 | + 'is disabled without %s and makes no network call', |
| 136 | + async key => { |
| 137 | + config[key] = ''; |
| 138 | + expect(await enqueueUsage(payload)).toEqual({ kind: 'disabled' }); |
| 139 | + expect(mockFetch).not.toHaveBeenCalled(); |
| 140 | + expect(warn).not.toHaveBeenCalled(); |
| 141 | + } |
| 142 | + ); |
| 143 | + |
| 144 | + test('contains a malformed configured URL through the request failure path', async () => { |
| 145 | + config.USAGE_INGEST_URL = 'malformed-sensitive-url'; |
| 146 | + expect(await enqueueUsage(payload)).toEqual({ kind: 'unavailable', reason: 'request_failed' }); |
| 147 | + expect(mockFetch).not.toHaveBeenCalled(); |
| 148 | + expectUnavailableWarning('request_failed'); |
| 149 | + }); |
| 150 | + |
| 151 | + test('uses the configured URL without an additional path, query or fragment policy', async () => { |
| 152 | + config.USAGE_INGEST_URL = 'https://usage.example.test/proxy/usage?fixture=synthetic#fragment'; |
| 153 | + mockFetch.mockResolvedValue(new Response(null, { status: 202 })); |
| 154 | + expect(await enqueueUsage(payload)).toEqual({ kind: 'accepted' }); |
| 155 | + expect(mockFetch).toHaveBeenCalledWith(config.USAGE_INGEST_URL, expect.any(Object)); |
| 156 | + }); |
| 157 | + |
| 158 | + test('preserves confirmed acceptance when unused response-body cleanup fails', async () => { |
| 159 | + const cancel = jest.fn(() => { |
| 160 | + throw new Error('sensitive cleanup error'); |
| 161 | + }); |
| 162 | + const body = new ReadableStream({ cancel }); |
| 163 | + mockFetch.mockResolvedValue(new Response(body, { status: 202 })); |
| 164 | + |
| 165 | + expect(await enqueueUsage(payload)).toEqual({ kind: 'accepted' }); |
| 166 | + // Allow a rejected cancellation promise to surface as an unhandled rejection. |
| 167 | + await new Promise<void>(resolve => setImmediate(resolve)); |
| 168 | + expect(cancel).toHaveBeenCalledTimes(1); |
| 169 | + expect(mockFetch).toHaveBeenCalledTimes(1); |
| 170 | + expect(warn).not.toHaveBeenCalled(); |
| 171 | + }); |
| 172 | + |
| 173 | + test.each([200, 204, 401, 503])( |
| 174 | + 'reports HTTP %i without retrying or reading its body', |
| 175 | + async status => { |
| 176 | + const response = new Response(status === 204 ? null : 'sensitive-upstream-body', { status }); |
| 177 | + const read = jest.spyOn(response, 'text'); |
| 178 | + const cancel = response.body ? jest.spyOn(response.body, 'cancel') : null; |
| 179 | + mockFetch.mockResolvedValue(response); |
| 180 | + const outcome = { kind: 'unavailable', reason: `http_${status}` }; |
| 181 | + expect(await enqueueUsage(payload)).toEqual(outcome); |
| 182 | + expect(mockFetch).toHaveBeenCalledTimes(1); |
| 183 | + expect(read).not.toHaveBeenCalled(); |
| 184 | + if (cancel) expect(cancel).toHaveBeenCalledTimes(1); |
| 185 | + expectUnavailableWarning(outcome.reason); |
| 186 | + } |
| 187 | + ); |
| 188 | + |
| 189 | + test('bounds a real HTTP request that never responds to two seconds', async () => { |
| 190 | + let requests = 0; |
| 191 | + const server = createServer(() => { |
| 192 | + requests++; |
| 193 | + }); |
| 194 | + try { |
| 195 | + await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); |
| 196 | + const address = server.address(); |
| 197 | + if (!address || typeof address === 'string') throw new Error('Missing fixture port'); |
| 198 | + config.USAGE_INGEST_URL = `http://127.0.0.1:${address.port}/usage`; |
| 199 | + mockFetch.mockImplementation(nativeFetch); |
| 200 | + const start = performance.now(); |
| 201 | + expect(await enqueueUsage(payload)).toEqual({ kind: 'unavailable', reason: 'timeout' }); |
| 202 | + const elapsed = performance.now() - start; |
| 203 | + expect(elapsed).toBeGreaterThanOrEqual(USAGE_ENQUEUE_TIMEOUT_MS - 100); |
| 204 | + expect(elapsed).toBeLessThan(USAGE_ENQUEUE_TIMEOUT_MS + 1_000); |
| 205 | + expect(requests).toBe(1); |
| 206 | + expect(mockFetch).toHaveBeenCalledTimes(1); |
| 207 | + expectUnavailableWarning('timeout'); |
| 208 | + } finally { |
| 209 | + server.closeAllConnections(); |
| 210 | + await new Promise<void>((resolve, reject) => |
| 211 | + server.close(error => (error ? reject(error) : resolve())) |
| 212 | + ); |
| 213 | + } |
| 214 | + }); |
| 215 | + |
| 216 | + test('contains network failures and emits only the ID and categorical outcome', async () => { |
| 217 | + const error = Object.assign(new Error('synthetic-publisher-secret sensitive prompt'), { |
| 218 | + name: 'sensitive-error-name', |
| 219 | + }); |
| 220 | + mockFetch.mockRejectedValue(error); |
| 221 | + expect(await enqueueUsage(payload)).toEqual({ |
| 222 | + kind: 'unavailable', |
| 223 | + reason: 'request_failed', |
| 224 | + }); |
| 225 | + expect(mockFetch).toHaveBeenCalledTimes(1); |
| 226 | + expectUnavailableWarning('request_failed'); |
| 227 | + }); |
| 228 | +}); |
0 commit comments