refactor(metadata): metadata source query service (#2718)
This commit is contained in:
@@ -0,0 +1,104 @@
|
||||
import {HttpErrorResponse} from '@angular/common/http';
|
||||
import {of, throwError} from 'rxjs';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
|
||||
import type {AuthService} from '../../shared/service/auth.service';
|
||||
import {sseResponse, sseStream} from '../testing/query-testing';
|
||||
import {postSseJson} from './query-transport';
|
||||
|
||||
interface Chunk {
|
||||
readonly id: number;
|
||||
}
|
||||
|
||||
async function collect(events: AsyncIterable<Chunk>): Promise<Chunk[]> {
|
||||
const collected: Chunk[] = [];
|
||||
for await (const event of events) {
|
||||
collected.push(event);
|
||||
}
|
||||
return collected;
|
||||
}
|
||||
|
||||
describe('postSseJson', () => {
|
||||
const ensureAccessToken = vi.fn((options: {forceRefresh?: boolean} = {}) =>
|
||||
of(options.forceRefresh ? 'refreshed-token' : 'token-123'));
|
||||
const auth = {ensureAccessToken} as unknown as AuthService;
|
||||
let fetchStub: ReturnType<typeof vi.spyOn>;
|
||||
|
||||
beforeEach(() => {
|
||||
ensureAccessToken.mockClear();
|
||||
fetchStub = vi.spyOn(globalThis, 'fetch');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('posts the body with a bearer token and reads the streamed events', async () => {
|
||||
fetchStub.mockResolvedValue(sseResponse(sseStream(['data:{"id":1}\n\n'])));
|
||||
|
||||
const events = await postSseJson<Chunk>(auth, '/stream', '{"q":1}', new AbortController().signal);
|
||||
|
||||
expect(await collect(events)).toEqual([{id: 1}]);
|
||||
const [url, init] = fetchStub.mock.calls[0];
|
||||
expect(url).toBe('/stream');
|
||||
expect(init?.method).toBe('POST');
|
||||
expect(init?.body).toBe('{"q":1}');
|
||||
expect(init?.headers).toEqual({
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer token-123',
|
||||
});
|
||||
});
|
||||
|
||||
it('refreshes the token once and retries when the request is rejected as unauthenticated', async () => {
|
||||
fetchStub
|
||||
.mockResolvedValueOnce(new Response(null, {status: 401}))
|
||||
.mockResolvedValueOnce(sseResponse(sseStream(['data:{"id":2}\n\n'])));
|
||||
|
||||
const events = await postSseJson<Chunk>(auth, '/stream', '{}', new AbortController().signal);
|
||||
|
||||
expect(await collect(events)).toEqual([{id: 2}]);
|
||||
expect(ensureAccessToken).toHaveBeenNthCalledWith(2, {forceRefresh: true});
|
||||
expect(fetchStub.mock.calls[1][1]?.headers).toEqual({
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer refreshed-token',
|
||||
});
|
||||
});
|
||||
|
||||
it('fails with the http status when the retried request is still rejected', async () => {
|
||||
fetchStub.mockResolvedValue(new Response(null, {status: 401, statusText: 'Unauthorized'}));
|
||||
|
||||
await expect(postSseJson(auth, '/stream', '{}', new AbortController().signal))
|
||||
.rejects.toMatchObject({status: 401, statusText: 'Unauthorized'});
|
||||
expect(fetchStub).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('fails with the http status rather than a bare message', async () => {
|
||||
fetchStub.mockResolvedValue(new Response(null, {status: 503, statusText: 'Unavailable'}));
|
||||
|
||||
const failure = await postSseJson(auth, '/stream', '{}', new AbortController().signal).catch((error: unknown) => error);
|
||||
|
||||
expect(failure).toBeInstanceOf(HttpErrorResponse);
|
||||
expect(failure).toMatchObject({status: 503, url: '/stream'});
|
||||
expect(fetchStub).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('passes the abort signal to the request', async () => {
|
||||
const controller = new AbortController();
|
||||
fetchStub.mockImplementation((_url: unknown, init?: RequestInit) => {
|
||||
controller.abort();
|
||||
return init?.signal?.aborted
|
||||
? Promise.reject(new DOMException('Aborted', 'AbortError'))
|
||||
: Promise.resolve(sseResponse(sseStream(['data:{"id":3}\n\n'])));
|
||||
});
|
||||
|
||||
await expect(postSseJson(auth, '/stream', '{}', controller.signal)).rejects.toThrow('Aborted');
|
||||
});
|
||||
|
||||
it('fails when the token cannot be obtained', async () => {
|
||||
ensureAccessToken.mockReturnValueOnce(throwError(() => new Error('No refresh token available')));
|
||||
|
||||
await expect(postSseJson(auth, '/stream', '{}', new AbortController().signal))
|
||||
.rejects.toThrow('No refresh token available');
|
||||
expect(fetchStub).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,8 @@
|
||||
import {HttpErrorResponse} from '@angular/common/http';
|
||||
import {Observable} from 'rxjs';
|
||||
import {HttpClient, HttpErrorResponse} from '@angular/common/http';
|
||||
import {firstValueFrom, lastValueFrom, Observable, takeUntil} from 'rxjs';
|
||||
|
||||
import type {AuthService} from '../../shared/service/auth.service';
|
||||
import {readSseJson} from './sse';
|
||||
|
||||
export function retryTransientQueryError(failureCount: number, error: unknown): boolean {
|
||||
if (failureCount >= 2) {
|
||||
@@ -28,3 +31,44 @@ export function abortSignal(signal: AbortSignal): Observable<void> {
|
||||
return () => signal.removeEventListener('abort', onAbort);
|
||||
});
|
||||
}
|
||||
|
||||
export function toAbortablePromise<T>(source: Observable<T>, signal: AbortSignal): Promise<T> {
|
||||
return lastValueFrom(source.pipe(takeUntil(abortSignal(signal))));
|
||||
}
|
||||
|
||||
export function httpGet<T>(http: HttpClient, url: string, signal: AbortSignal): Promise<T> {
|
||||
return toAbortablePromise(http.get<T>(url), signal);
|
||||
}
|
||||
|
||||
export async function postSseJson<T>(
|
||||
auth: AuthService,
|
||||
url: string,
|
||||
body: string,
|
||||
signal: AbortSignal,
|
||||
): Promise<AsyncIterable<T>> {
|
||||
const send = async (options: {forceRefresh?: boolean} = {}) => {
|
||||
const token = await firstValueFrom(auth.ensureAccessToken(options));
|
||||
return fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`,
|
||||
},
|
||||
body,
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
let response = await send();
|
||||
if (response.status === 401) {
|
||||
await response.body?.cancel();
|
||||
response = await send({forceRefresh: true});
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
await response.body?.cancel();
|
||||
throw new HttpErrorResponse({status: response.status, statusText: response.statusText, url});
|
||||
}
|
||||
|
||||
return readSseJson<T>(response);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import {describe, expect, it} from 'vitest';
|
||||
|
||||
import {sseResponse, sseStream} from '../testing/query-testing';
|
||||
import {readSseJson} from './sse';
|
||||
|
||||
interface Chunk {
|
||||
readonly id: number;
|
||||
}
|
||||
|
||||
async function collect(chunks: readonly string[]): Promise<Chunk[]> {
|
||||
const events: Chunk[] = [];
|
||||
for await (const event of readSseJson<Chunk>(sseResponse(sseStream(chunks)))) {
|
||||
events.push(event);
|
||||
}
|
||||
return events;
|
||||
}
|
||||
|
||||
describe('readSseJson', () => {
|
||||
it('reads one event per chunk', async () => {
|
||||
expect(await collect(['data:{"id":1}\n\n', 'data:{"id":2}\n\n'])).toEqual([{id: 1}, {id: 2}]);
|
||||
});
|
||||
|
||||
it('reads two events arriving in one chunk', async () => {
|
||||
expect(await collect(['data:{"id":1}\n\ndata:{"id":2}\n\n'])).toEqual([{id: 1}, {id: 2}]);
|
||||
});
|
||||
|
||||
it('reads one event split across chunks', async () => {
|
||||
expect(await collect(['data:{"id', '":1}\n\n'])).toEqual([{id: 1}]);
|
||||
});
|
||||
|
||||
it('reads a trailing event that has no final newline', async () => {
|
||||
expect(await collect(['data:{"id":1}\n\n', 'data:{"id":2}'])).toEqual([{id: 1}, {id: 2}]);
|
||||
});
|
||||
|
||||
it('skips an empty data line', async () => {
|
||||
expect(await collect(['data:\n\n', 'data:{"id":1}\n\n'])).toEqual([{id: 1}]);
|
||||
});
|
||||
|
||||
it('throws when a payload is not JSON', async () => {
|
||||
await expect(collect(['data:not-json\n\n'])).rejects.toThrow(SyntaxError);
|
||||
});
|
||||
|
||||
it('throws when the response has no body', async () => {
|
||||
const events = readSseJson<Chunk>(new Response(null, {status: 204}));
|
||||
await expect(events[Symbol.asyncIterator]().next()).rejects.toThrow('Response body is null');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
async function* readLines(reader: ReadableStreamDefaultReader<Uint8Array>): AsyncIterable<string> {
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
|
||||
try {
|
||||
for (;;) {
|
||||
const {done, value} = await reader.read();
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
|
||||
buffer += decoder.decode(value, {stream: true});
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop() ?? '';
|
||||
yield* lines;
|
||||
}
|
||||
|
||||
yield buffer;
|
||||
} finally {
|
||||
await reader.cancel().catch(() => undefined);
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
export async function* readSseJson<T>(response: Response): AsyncIterable<T> {
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) {
|
||||
throw new Error('Response body is null');
|
||||
}
|
||||
|
||||
for await (const line of readLines(reader)) {
|
||||
if (!line.startsWith('data:')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const payload = line.slice(5).trim();
|
||||
if (payload !== '') {
|
||||
const parsed: T = JSON.parse(payload);
|
||||
yield parsed;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,12 @@ import {provideHttpClient} from '@angular/common/http';
|
||||
import {provideHttpClientTesting} from '@angular/common/http/testing';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {provideTanStackQuery, QueryClient, QueryObserver} from '@tanstack/angular-query-experimental';
|
||||
import {of, type Observable} from 'rxjs';
|
||||
|
||||
interface AuthServiceStub {
|
||||
token: WritableSignal<string | null>;
|
||||
getInternalAccessToken: () => string | null;
|
||||
ensureAccessToken: (options?: {forceRefresh?: boolean}) => Observable<string>;
|
||||
}
|
||||
|
||||
export interface QueryClientHarness {
|
||||
@@ -19,6 +21,7 @@ export function createAuthServiceStub(initialToken: string | null = 'token-123')
|
||||
return {
|
||||
token,
|
||||
getInternalAccessToken: () => token(),
|
||||
ensureAccessToken: () => of(token() ?? ''),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -87,3 +90,19 @@ export async function flushQueryAsync(rounds = 5): Promise<void> {
|
||||
TestBed.flushEffects();
|
||||
appRef.tick();
|
||||
}
|
||||
|
||||
export function sseStream(chunks: readonly string[]): ReadableStream<Uint8Array> {
|
||||
const encoder = new TextEncoder();
|
||||
return new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
for (const chunk of chunks) {
|
||||
controller.enqueue(encoder.encode(chunk));
|
||||
}
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function sseResponse(body: ReadableStream<Uint8Array>, status = 200): Response {
|
||||
return new Response(body, {status, headers: {'Content-Type': 'text/event-stream'}});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user