|
| 1 | +import { afterAll, beforeEach, describe, expect, mock, test } from 'bun:test' |
| 2 | +import { NextRequest } from 'next/server' |
| 3 | + |
| 4 | +import type { TrackEventFn } from '@codebuff/common/types/contracts/analytics' |
| 5 | +import type { GetUserInfoFromApiKeyFn } from '@codebuff/common/types/contracts/database' |
| 6 | +import type { |
| 7 | + Logger, |
| 8 | + LoggerWithContextFn, |
| 9 | +} from '@codebuff/common/types/contracts/logger' |
| 10 | + |
| 11 | +const insertedRows: unknown[] = [] |
| 12 | + |
| 13 | +const onConflictDoNothingMock = mock(() => Promise.resolve()) |
| 14 | +const valuesMock = mock((row: unknown) => { |
| 15 | + insertedRows.push(row) |
| 16 | + return { onConflictDoNothing: onConflictDoNothingMock } |
| 17 | +}) |
| 18 | +const insertMock = mock(() => ({ values: valuesMock })) |
| 19 | + |
| 20 | +mock.module('@codebuff/internal/db', () => ({ |
| 21 | + default: { |
| 22 | + insert: insertMock, |
| 23 | + }, |
| 24 | +})) |
| 25 | + |
| 26 | +mock.module('@codebuff/internal/db/schema', () => ({ |
| 27 | + adImpression: {}, |
| 28 | +})) |
| 29 | + |
| 30 | +const { postAds } = await import('../_post') |
| 31 | + |
| 32 | +describe('/api/v1/ads POST endpoint', () => { |
| 33 | + let logger: Logger |
| 34 | + let loggerWithContext: LoggerWithContextFn |
| 35 | + let trackEvent: TrackEventFn |
| 36 | + |
| 37 | + const getUserInfoFromApiKey: GetUserInfoFromApiKeyFn = async ({ |
| 38 | + apiKey, |
| 39 | + }) => { |
| 40 | + if (apiKey !== 'test-key') return null |
| 41 | + return { |
| 42 | + id: 'user-123', |
| 43 | + email: 'test@example.com', |
| 44 | + discord_id: null, |
| 45 | + } as Awaited<ReturnType<GetUserInfoFromApiKeyFn>> |
| 46 | + } |
| 47 | + |
| 48 | + beforeEach(() => { |
| 49 | + insertedRows.length = 0 |
| 50 | + insertMock.mockClear() |
| 51 | + valuesMock.mockClear() |
| 52 | + onConflictDoNothingMock.mockClear() |
| 53 | + |
| 54 | + logger = { |
| 55 | + error: mock(() => {}), |
| 56 | + warn: mock(() => {}), |
| 57 | + info: mock(() => {}), |
| 58 | + debug: mock(() => {}), |
| 59 | + } |
| 60 | + loggerWithContext = mock(() => logger) |
| 61 | + trackEvent = mock(() => {}) |
| 62 | + }) |
| 63 | + |
| 64 | + afterAll(() => { |
| 65 | + mock.restore() |
| 66 | + }) |
| 67 | + |
| 68 | + function createRequest(body: Record<string, unknown>) { |
| 69 | + return new NextRequest('http://localhost:3000/api/v1/ads', { |
| 70 | + method: 'POST', |
| 71 | + headers: { |
| 72 | + Authorization: 'Bearer test-key', |
| 73 | + 'Content-Type': 'application/json', |
| 74 | + 'User-Agent': 'CodebuffCLI/1.0', |
| 75 | + 'X-Forwarded-For': '203.0.113.10', |
| 76 | + }, |
| 77 | + body: JSON.stringify(body), |
| 78 | + }) |
| 79 | + } |
| 80 | + |
| 81 | + test('falls back from Gravity to ZeroClick to Carbon', async () => { |
| 82 | + const upstreamUrls: string[] = [] |
| 83 | + const fetchMock = mock( |
| 84 | + async (url: string | URL | Request): Promise<Response> => { |
| 85 | + const urlString = String(url) |
| 86 | + upstreamUrls.push(urlString) |
| 87 | + |
| 88 | + if (urlString.includes('server.trygravity.ai')) { |
| 89 | + return new Response(null, { status: 204 }) |
| 90 | + } |
| 91 | + |
| 92 | + if (urlString.includes('zeroclick.dev')) { |
| 93 | + return Response.json([]) |
| 94 | + } |
| 95 | + |
| 96 | + if (urlString.includes('srv.buysellads.com')) { |
| 97 | + return Response.json({ |
| 98 | + ads: [ |
| 99 | + { |
| 100 | + statlink: '//srv.buysellads.com/click', |
| 101 | + statimp: '//srv.buysellads.com/imp', |
| 102 | + description: 'Carbon fallback ad', |
| 103 | + company: 'Carbon Co', |
| 104 | + callToAction: 'Try it', |
| 105 | + image: 'https://example.com/carbon.png', |
| 106 | + }, |
| 107 | + ], |
| 108 | + }) |
| 109 | + } |
| 110 | + |
| 111 | + return new Response('unexpected upstream', { status: 500 }) |
| 112 | + }, |
| 113 | + ) |
| 114 | + |
| 115 | + const response = await postAds({ |
| 116 | + req: createRequest({ |
| 117 | + provider: 'gravity', |
| 118 | + messages: [], |
| 119 | + sessionId: 'session-123', |
| 120 | + userAgent: 'Mozilla/5.0', |
| 121 | + }), |
| 122 | + getUserInfoFromApiKey, |
| 123 | + logger, |
| 124 | + loggerWithContext, |
| 125 | + trackEvent, |
| 126 | + fetch: fetchMock as unknown as typeof globalThis.fetch, |
| 127 | + serverEnv: { |
| 128 | + GRAVITY_API_KEY: 'gravity-key', |
| 129 | + ZEROCLICK_API_KEY: 'zeroclick-key', |
| 130 | + CARBON_ZONE_KEY: 'carbon-zone', |
| 131 | + CB_ENVIRONMENT: 'prod', |
| 132 | + }, |
| 133 | + }) |
| 134 | + |
| 135 | + expect(response.status).toBe(200) |
| 136 | + expect(upstreamUrls[0]).toContain('server.trygravity.ai') |
| 137 | + expect(upstreamUrls[1]).toContain('zeroclick.dev') |
| 138 | + expect(upstreamUrls[2]).toContain('srv.buysellads.com') |
| 139 | + |
| 140 | + const body = await response.json() |
| 141 | + expect(body.provider).toBe('carbon') |
| 142 | + expect(body.ads).toHaveLength(1) |
| 143 | + expect(body.ads[0]).toMatchObject({ |
| 144 | + adText: 'Carbon fallback ad', |
| 145 | + title: 'Carbon Co', |
| 146 | + clickUrl: 'https://srv.buysellads.com/click', |
| 147 | + impUrl: 'https://srv.buysellads.com/imp', |
| 148 | + }) |
| 149 | + |
| 150 | + expect(insertedRows).toHaveLength(1) |
| 151 | + expect(insertedRows[0]).toMatchObject({ |
| 152 | + user_id: 'user-123', |
| 153 | + provider: 'carbon', |
| 154 | + ad_text: 'Carbon fallback ad', |
| 155 | + imp_url: 'https://srv.buysellads.com/imp', |
| 156 | + }) |
| 157 | + }) |
| 158 | + |
| 159 | + test('skips unconfigured providers and still reaches Carbon', async () => { |
| 160 | + const upstreamUrls: string[] = [] |
| 161 | + const fetchMock = mock( |
| 162 | + async (url: string | URL | Request): Promise<Response> => { |
| 163 | + const urlString = String(url) |
| 164 | + upstreamUrls.push(urlString) |
| 165 | + |
| 166 | + if (urlString.includes('server.trygravity.ai')) { |
| 167 | + return new Response(null, { status: 204 }) |
| 168 | + } |
| 169 | + |
| 170 | + if (urlString.includes('srv.buysellads.com')) { |
| 171 | + return Response.json({ |
| 172 | + ads: [ |
| 173 | + { |
| 174 | + statlink: '//srv.buysellads.com/click', |
| 175 | + statimp: '//srv.buysellads.com/imp', |
| 176 | + description: 'Carbon fallback ad', |
| 177 | + company: 'Carbon Co', |
| 178 | + }, |
| 179 | + ], |
| 180 | + }) |
| 181 | + } |
| 182 | + |
| 183 | + return new Response('unexpected upstream', { status: 500 }) |
| 184 | + }, |
| 185 | + ) |
| 186 | + |
| 187 | + const response = await postAds({ |
| 188 | + req: createRequest({ |
| 189 | + provider: 'gravity', |
| 190 | + messages: [], |
| 191 | + userAgent: 'Mozilla/5.0', |
| 192 | + }), |
| 193 | + getUserInfoFromApiKey, |
| 194 | + logger, |
| 195 | + loggerWithContext, |
| 196 | + trackEvent, |
| 197 | + fetch: fetchMock as unknown as typeof globalThis.fetch, |
| 198 | + serverEnv: { |
| 199 | + GRAVITY_API_KEY: 'gravity-key', |
| 200 | + CARBON_ZONE_KEY: 'carbon-zone', |
| 201 | + CB_ENVIRONMENT: 'prod', |
| 202 | + }, |
| 203 | + }) |
| 204 | + |
| 205 | + expect(response.status).toBe(200) |
| 206 | + expect(upstreamUrls.some((url) => url.includes('zeroclick.dev'))).toBe( |
| 207 | + false, |
| 208 | + ) |
| 209 | + |
| 210 | + const body = await response.json() |
| 211 | + expect(body.provider).toBe('carbon') |
| 212 | + expect(body.ads).toHaveLength(1) |
| 213 | + }) |
| 214 | +}) |
0 commit comments