|
| 1 | +import { buildPrometheusRequest, runPromqlQuery } from '@/controllers/promql'; |
| 2 | + |
| 3 | +const mockFetch = jest.mocked(global.fetch); |
| 4 | + |
| 5 | +const respond = (status: number, body: unknown) => |
| 6 | + mockFetch.mockResolvedValueOnce( |
| 7 | + new Response(JSON.stringify(body), { status }), |
| 8 | + ); |
| 9 | + |
| 10 | +const matrix = { |
| 11 | + resultType: 'matrix', |
| 12 | + result: [{ metric: { job: 'api' }, values: [[1700000000, '1']] }], |
| 13 | +}; |
| 14 | + |
| 15 | +const prometheus = { kind: 'prometheus' as const, host: 'http://prom:9090' }; |
| 16 | +const range = { |
| 17 | + kind: 'range' as const, |
| 18 | + expr: 'up', |
| 19 | + startSec: 1700000000, |
| 20 | + endSec: 1700003600, |
| 21 | + stepSec: 60, |
| 22 | +}; |
| 23 | + |
| 24 | +const requestedUrl = () => new URL(String(mockFetch.mock.calls[0][0])); |
| 25 | + |
| 26 | +describe('buildPrometheusRequest', () => { |
| 27 | + const host = |
| 28 | + 'http://user:p%40ss@vm:8481/select/0/prometheus?extra_label=env%3Dprod&limit=50&step=15s'; |
| 29 | + |
| 30 | + it('replaces host-pinned params it sets and keeps the rest', () => { |
| 31 | + const { url } = buildPrometheusRequest(host, '/api/v1/query_range', { |
| 32 | + step: '60', |
| 33 | + 'match[]': ['up', 'down'], |
| 34 | + limit: [], |
| 35 | + }); |
| 36 | + |
| 37 | + const sent = new URL(url); |
| 38 | + expect(`${sent.origin}${sent.pathname}`).toBe( |
| 39 | + 'http://vm:8481/select/0/prometheus/api/v1/query_range', |
| 40 | + ); |
| 41 | + expect(sent.searchParams.get('extra_label')).toBe('env=prod'); |
| 42 | + expect(sent.searchParams.getAll('step')).toEqual(['60']); |
| 43 | + expect(sent.searchParams.getAll('match[]')).toEqual(['up', 'down']); |
| 44 | + expect(sent.searchParams.has('limit')).toBe(false); |
| 45 | + }); |
| 46 | + |
| 47 | + it('moves host credentials into a Basic auth header next to the given headers', () => { |
| 48 | + const { url, headers, redactedTarget } = buildPrometheusRequest( |
| 49 | + host, |
| 50 | + '/api/v1/query', |
| 51 | + {}, |
| 52 | + { 'X-Extra': '1' }, |
| 53 | + ); |
| 54 | + |
| 55 | + expect(url).not.toContain('user'); |
| 56 | + expect(headers).toEqual({ |
| 57 | + Authorization: `Basic ${Buffer.from('user:p@ss').toString('base64')}`, |
| 58 | + 'X-Extra': '1', |
| 59 | + }); |
| 60 | + expect(redactedTarget).toBe( |
| 61 | + 'http://vm:8481/select/0/prometheus/api/v1/query', |
| 62 | + ); |
| 63 | + }); |
| 64 | + |
| 65 | + it('throws on a host that is not http(s)', () => { |
| 66 | + expect(() => |
| 67 | + buildPrometheusRequest('prometheus:9090', '/api/v1/query', {}), |
| 68 | + ).toThrow(/http\(s\)/); |
| 69 | + }); |
| 70 | +}); |
| 71 | + |
| 72 | +describe('runPromqlQuery', () => { |
| 73 | + afterEach(() => { |
| 74 | + mockFetch.mockReset(); |
| 75 | + }); |
| 76 | + |
| 77 | + it('sends a range query to a Prometheus endpoint and returns its data', async () => { |
| 78 | + respond(200, { status: 'success', data: matrix }); |
| 79 | + |
| 80 | + await expect(runPromqlQuery(prometheus, range)).resolves.toEqual(matrix); |
| 81 | + |
| 82 | + const url = requestedUrl(); |
| 83 | + expect(`${url.origin}${url.pathname}`).toBe( |
| 84 | + 'http://prom:9090/api/v1/query_range', |
| 85 | + ); |
| 86 | + expect(Object.fromEntries(url.searchParams)).toEqual({ |
| 87 | + query: 'up', |
| 88 | + start: '1700000000', |
| 89 | + end: '1700003600', |
| 90 | + step: '60', |
| 91 | + }); |
| 92 | + }); |
| 93 | + |
| 94 | + const clickhouseHttp = { |
| 95 | + kind: 'clickhouse-http' as const, |
| 96 | + connection: { host: 'http://ch:8123', username: 'default', password: 'pw' }, |
| 97 | + databaseName: 'default', |
| 98 | + tableName: 'metrics', |
| 99 | + }; |
| 100 | + const instant = { kind: 'instant' as const, expr: 'up', timeSec: 1700000000 }; |
| 101 | + const emptyVector = { |
| 102 | + status: 'success', |
| 103 | + data: { resultType: 'vector', result: [] }, |
| 104 | + }; |
| 105 | + |
| 106 | + it("sends an instant query to ClickHouse's Prometheus API with the table, limits and credentials", async () => { |
| 107 | + respond(200, emptyVector); |
| 108 | + |
| 109 | + await runPromqlQuery(clickhouseHttp, instant); |
| 110 | + |
| 111 | + const url = requestedUrl(); |
| 112 | + expect(url.pathname).toBe('/prometheus/api/v1/query'); |
| 113 | + expect(Object.fromEntries(url.searchParams)).toMatchObject({ |
| 114 | + max_execution_time: '30', |
| 115 | + max_result_rows: '100000', |
| 116 | + query: 'up', |
| 117 | + time: '1700000000', |
| 118 | + database: 'default', |
| 119 | + table: 'metrics', |
| 120 | + }); |
| 121 | + expect(mockFetch.mock.calls[0][1]?.headers).toMatchObject({ |
| 122 | + 'X-ClickHouse-User': 'default', |
| 123 | + 'X-ClickHouse-Key': 'pw', |
| 124 | + }); |
| 125 | + }); |
| 126 | + |
| 127 | + it('gives each query on one ClickHouse backend its own query ID', async () => { |
| 128 | + respond(200, emptyVector); |
| 129 | + respond(200, emptyVector); |
| 130 | + |
| 131 | + await Promise.all([ |
| 132 | + runPromqlQuery(clickhouseHttp, instant), |
| 133 | + runPromqlQuery(clickhouseHttp, instant), |
| 134 | + ]); |
| 135 | + |
| 136 | + const queryIds = mockFetch.mock.calls.map(([, init]) => |
| 137 | + new Headers(init?.headers).get('X-ClickHouse-Query-Id'), |
| 138 | + ); |
| 139 | + expect(queryIds[0]).toBeTruthy(); |
| 140 | + expect(queryIds[0]).not.toBe(queryIds[1]); |
| 141 | + }); |
| 142 | + |
| 143 | + it('reports a rejected expression as a user error', async () => { |
| 144 | + respond(400, { |
| 145 | + status: 'error', |
| 146 | + errorType: 'bad_data', |
| 147 | + error: 'parse error: unexpected end of input', |
| 148 | + }); |
| 149 | + |
| 150 | + await expect(runPromqlQuery(prometheus, range)).rejects.toMatchObject({ |
| 151 | + message: 'parse error: unexpected end of input', |
| 152 | + category: 'user', |
| 153 | + }); |
| 154 | + }); |
| 155 | + |
| 156 | + it.each([ |
| 157 | + ['a 5xx', 503, 'internal'], |
| 158 | + ['a timeout', 400, 'timeout'], |
| 159 | + ])('reports %s as a server error', async (_, status, errorType) => { |
| 160 | + respond(status, { status: 'error', errorType, error: 'failed' }); |
| 161 | + |
| 162 | + await expect(runPromqlQuery(prometheus, range)).rejects.toMatchObject({ |
| 163 | + category: 'server', |
| 164 | + }); |
| 165 | + }); |
| 166 | + |
| 167 | + it('reports an unreachable endpoint as a server error, without its credentials', async () => { |
| 168 | + mockFetch.mockRejectedValueOnce(new TypeError('fetch failed')); |
| 169 | + |
| 170 | + await expect( |
| 171 | + runPromqlQuery({ ...prometheus, host: 'http://u:p@prom:9090' }, range), |
| 172 | + ).rejects.toMatchObject({ |
| 173 | + message: |
| 174 | + 'Failed to reach Prometheus at http://prom:9090/api/v1/query_range', |
| 175 | + category: 'server', |
| 176 | + }); |
| 177 | + }); |
| 178 | + |
| 179 | + it('rejects a range query over the resolution cap before sending it', async () => { |
| 180 | + await expect( |
| 181 | + runPromqlQuery(prometheus, { ...range, stepSec: 0.1 }), |
| 182 | + ).rejects.toMatchObject({ category: 'user' }); |
| 183 | + expect(mockFetch).not.toHaveBeenCalled(); |
| 184 | + }); |
| 185 | +}); |
0 commit comments