Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

feat(network): add retry and threshold interceptor (#1664)

Wenzhao Hu5791d4d5b4d2
diff --git a/.vscode/settings.json b/.vscode/settings.json
index 9d72325396..7a6eeac0f4 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -40,6 +40,7 @@
"Hiragino",
"Hlookup",
"hoverable",
+ "IHTTP",
"ilvl",
"IRPC",
"Jamo",
@@ -91,6 +92,7 @@
"viewports",
"vlookup",
"wendellhu",
+ "XHRHTTP",
"Xingkai",
"Xinwei",
"Xlookup",
diff --git a/packages/network/package.json b/packages/network/package.json
index c2699d310e..c7e7feb11f 100644
--- a/packages/network/package.json
+++ b/packages/network/package.json
@@ -53,6 +53,9 @@
"npm": ">=8.0.0"
},
"scripts": {
+ "test": "vitest run",
+ "test:watch": "vitest",
+ "coverage": "vitest run --coverage",
"lint:types": "tsc --noEmit",
"build": "tsc && vite build"
},
diff --git a/packages/network/src/index.ts b/packages/network/src/index.ts
index bcb946091e..674a27ea3f 100644
--- a/packages/network/src/index.ts
+++ b/packages/network/src/index.ts
@@ -27,3 +27,6 @@ export {
WebSocketService,
} from './services/web-socket/web-socket.service';
export type { IRequestParams, IPostRequestParams } from './services/http/http.service';
+export type { HTTPHandlerFn, HTTPInterceptorFn, HTTPInterceptorFnFactory } from './services/http/interceptor';
+export { retryInterceptor } from './services/http/interceptors/retry-interceptor';
+export { ThresholdInterceptorFactory } from './services/http/interceptors/threshold-interceptor';
diff --git a/packages/network/src/services/http/__testing__/http-testing-utils.ts b/packages/network/src/services/http/__testing__/http-testing-utils.ts
new file mode 100644
index 0000000000..307db23350
--- /dev/null
+++ b/packages/network/src/services/http/__testing__/http-testing-utils.ts
@@ -0,0 +1,102 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* eslint-disable ts/no-explicit-any */
+/* eslint-disable ts/no-this-alias */
+
+import type { Observer } from 'rxjs';
+import { Observable, Subject } from 'rxjs';
+import { Disposable } from '@univerjs/core';
+
+import { Injector } from '@wendellhu/redi';
+import { IHTTPImplementation } from '../implementations/implementation';
+import type { HTTPRequest } from '../request';
+import type { HTTPEvent, HTTPResponse, HTTPResponseError } from '../response';
+import { HTTPService } from '../http.service';
+
+/**
+ * A mocked HTTP implementation service for testing purposes. Besides methods in the interface, it
+ * provides several public methods to control the process of http request.
+ */
+export class MockHTTPImplementation extends Disposable implements IHTTPImplementation {
+ private readonly _newRequest$ = new Subject<HTTPRequest>();
+ readonly newRequest$ = this._newRequest$.asObservable();
+
+ private readonly _handlers: Map<number, IMockHTTPHandler> = new Map();
+
+ override dispose(): void {
+ super.dispose();
+ this._newRequest$.complete();
+ }
+
+ send(request: HTTPRequest): Observable<HTTPEvent<any>> {
+ return new Observable((observer: Observer<HTTPEvent<any>>) => {
+ const service = this;
+ const handler: IMockHTTPHandler = {
+ emitResponse: (response) => {
+ observer.next(response);
+ removeHandler();
+ },
+ emitError: (error) => {
+ observer.error(error);
+ removeHandler();
+ },
+ };
+
+ function removeHandler() {
+ service._handlers.delete(request.uid);
+ }
+
+ this._handlers.set(request.uid, handler);
+ this._newRequest$.next(request);
+ });
+ }
+
+ /**
+ * Get a handler to interact with the request.
+ * @param uid the request's unique identifier
+ * @returns the handler for the request
+ */
+ getHandler(uid: number): IMockHTTPHandler {
+ const handler = this._handlers.get(uid);
+ if (!handler) {
+ throw new Error(`[MockHTTPImplementation]: no handler found for ${uid}!`);
+ }
+
+ return handler;
+ }
+}
+
+export interface IMockHTTPHandler {
+ /**
+ * Emit a response event to the observer.
+ */
+ emitResponse<T>(response: HTTPResponse<T>): void;
+
+ /**
+ * Emit an error event to the observer.
+ */
+ emitError(error: HTTPResponseError): void;
+}
+
+export function createHTTPTestBed() {
+ const injector = new Injector();
+
+ injector.add([HTTPService]);
+ injector.add([IHTTPImplementation, { useClass: MockHTTPImplementation }]);
+
+ return { injector };
+}
diff --git a/packages/network/src/services/http/http.service.ts b/packages/network/src/services/http/http.service.ts
index 28e6ffbb28..d1cc08e6dd 100644
--- a/packages/network/src/services/http/http.service.ts
+++ b/packages/network/src/services/http/http.service.ts
@@ -29,40 +29,58 @@ import type { HTTPRequestMethod } from './request';
import { HTTPRequest } from './request';
import type { HTTPEvent, HTTPResponseError } from './response';
import { HTTPResponse } from './response';
+import type { HTTPHandlerFn, HTTPInterceptorFn, RequestPipe } from './interceptor';
export interface IRequestParams {
- body?: any;
/** Query params. These params would be append to the url before the request is sent. */
params?: { [param: string]: string | number | boolean };
+
+ /** Query headers. */
headers?: { [key: string]: string | number | boolean };
+ /** Expected types of the response data. */
responseType?: HTTPResponseType;
withCredentials?: boolean;
}
export interface IPostRequestParams extends IRequestParams {
- body?: any;
+ body?: unknown;
}
-type HTTPHandlerFn = (request: HTTPRequest) => Observable<HTTPEvent<unknown>>;
-type HTTPInterceptorFn = (request: HTTPRequest, next: HTTPHandlerFn) => Observable<HTTPEvent<unknown>>;
-type RequestPipe<T> = (req: HTTPRequest, finalHandlerFn: HTTPHandlerFn) => Observable<HTTPEvent<T>>;
-
/**
* Register an HTTP interceptor. Interceptor could modify requests, responses, headers or errors.
*/
export interface IHTTPInterceptor {
+ /** The priority of the interceptor. The higher the value, the earlier the interceptor is called. */
priority?: number;
+ /** The interceptor function. */
interceptor: HTTPInterceptorFn;
}
+/**
+ * This service provides http request methods and allows to register http interceptors.
+ *
+ * You can use interceptors to:
+ *
+ * 1. modify requests (headers included) before they are sent, or modify responses before they are returned to the caller.
+ * 2. thresholding, logging, caching, etc.
+ * 3. authentication, authorization, etc.
+ */
export class HTTPService extends Disposable {
private _interceptors: IHTTPInterceptor[] = [];
+
+ // eslint-disable-next-line ts/no-explicit-any
private _pipe: Nullable<RequestPipe<any>>;
constructor(@IHTTPImplementation private readonly _http: IHTTPImplementation) {
super();
}
+ /**
+ * Register an HTTP interceptor.
+ *
+ * @param interceptor the http interceptor
+ * @returns a disposable handler to remove the interceptor
+ */
registerHTTPInterceptor(interceptor: IHTTPInterceptor): IDisposable {
if (this._interceptors.indexOf(interceptor) !== -1) {
throw new Error('[HTTPService]: The interceptor has already been registered!');
@@ -108,9 +126,10 @@ export class HTTPService extends Disposable {
params,
withCredentials: options?.withCredentials ?? false, // default value for withCredentials is false by MDN
responseType: options?.responseType ?? 'json',
- body: options?.body,
+ body: (method === 'GET') ? undefined : (options as IPostRequestParams)?.body,
});
+ // eslint-disable-next-line ts/no-explicit-any
const events$: Observable<HTTPEvent<any>> = of(request).pipe(
concatMap((request) => this._runInterceptorsAndImplementation(request))
);
@@ -125,6 +144,7 @@ export class HTTPService extends Disposable {
throw new Error(`${(result as HTTPResponseError).error}`);
}
+ // eslint-disable-next-line ts/no-explicit-any
private _runInterceptorsAndImplementation(request: HTTPRequest): Observable<HTTPEvent<any>> {
// In this method we first call all interceptors and finally the HTTP implementation.
// And the HTTP response will be passed back through the interceptor chain.
diff --git a/packages/network/src/services/http/implementations/implementation.ts b/packages/network/src/services/http/implementations/implementation.ts
index 919c514390..2dfe11806a 100644
--- a/packages/network/src/services/http/implementations/implementation.ts
+++ b/packages/network/src/services/http/implementations/implementation.ts
@@ -24,7 +24,11 @@ import type { HTTPEvent } from '../response';
* HTTP service could be implemented differently on platforms.
*/
export interface IHTTPImplementation {
- // There may be stream response so the return value is an observable.
+ /**
+ * Send a request. The result would be returned in an observable for possible stream response.
+ * @param request the request to be sent
+ */
+ // eslint-disable-next-line ts/no-explicit-any
send(request: HTTPRequest): Observable<HTTPEvent<any>>;
}
-export const IHTTPImplementation = createIdentifier<IHTTPImplementation>('univer-pro.network.http-implementation');
+export const IHTTPImplementation = createIdentifier<IHTTPImplementation>('network.http-implementation');
diff --git a/packages/network/src/services/http/implementations/xhr.ts b/packages/network/src/services/http/implementations/xhr.ts
index 8f475ebcec..134f28cd49 100644
--- a/packages/network/src/services/http/implementations/xhr.ts
+++ b/packages/network/src/services/http/implementations/xhr.ts
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+/* eslint-disable ts/no-explicit-any */
+
import type { Nullable } from '@univerjs/core';
import type { Observer } from 'rxjs';
import { Observable } from 'rxjs';
@@ -26,7 +28,7 @@ import { HTTPResponse, HTTPResponseError, ResponseHeader } from '../response';
import type { IHTTPImplementation } from './implementation';
/**
- * A HTTP implementation using XHR. XHR could only be async.
+ * A HTTP implementation using XHR. HTTP service provided by this service could only be async (we do not support sync XHR now).
*/
export class XHRHTTPImplementation implements IHTTPImplementation {
send(request: HTTPRequest): Observable<HTTPEvent<any>> {
diff --git a/packages/network/src/services/http/interceptor.ts b/packages/network/src/services/http/interceptor.ts
new file mode 100644
index 0000000000..82833d582f
--- /dev/null
+++ b/packages/network/src/services/http/interceptor.ts
@@ -0,0 +1,49 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Observable } from 'rxjs';
+
+import type { IAccessor } from '@wendellhu/redi';
+import type { HTTPRequest } from './request';
+import type { HTTPEvent } from './response';
+
+export type HTTPHandlerFn = (request: HTTPRequest) => Observable<HTTPEvent<unknown>>;
+
+/**
+ * HTTP interceptor function. When the interceptor is called, it would receive a request object and a next function.
+ *
+ * @param request The `request` could be been modified by interceptors whose priority is higher than the current interceptor.
+ *
+ * @param next When the interceptor decides to pass the request to the next interceptor, it should call the `next` function with
+ * the request.
+ * The `next` function would return an `Observable`. The current interceptor should subscribe to it and emit the messages
+ * from next interceptor to the previous interceptor.
+ *
+ * @returns An `Observable` that emits the response of the request. It would be subscribed by the previous interceptor.
+ *
+ * An interceptor the logs the request and response would look like this:
+ * @example
+ * function logInterceptor(request: HTTPRequest, next: HTTPHandlerFn): Observable<HTTPEvent<unknown>> {
+ * console.log('Request:', request);
+ * return next(request).pipe(cat(response => console.log('Response:', response)));
+ * }
+ */
+export type HTTPInterceptorFn = (request: HTTPRequest, next: HTTPHandlerFn) => Observable<HTTPEvent<unknown>>;
+
+export type RequestPipe<T> = (req: HTTPRequest, finalHandlerFn: HTTPHandlerFn) => Observable<HTTPEvent<T>>;
+
+// eslint-disable-next-line ts/no-explicit-any
+export type HTTPInterceptorFnFactory = (accessor: IAccessor, params?: any) => HTTPInterceptorFn;
diff --git a/packages/network/src/services/http/interceptors/__tests__/retry-interceptor.spec.ts b/packages/network/src/services/http/interceptors/__tests__/retry-interceptor.spec.ts
new file mode 100644
index 0000000000..96ebb4cc2b
--- /dev/null
+++ b/packages/network/src/services/http/interceptors/__tests__/retry-interceptor.spec.ts
@@ -0,0 +1,116 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vitest } from 'vitest';
+
+import type { Injector } from '@wendellhu/redi';
+import { HTTPService } from '../../http.service';
+import { createHTTPTestBed, type MockHTTPImplementation } from '../../__testing__/http-testing-utils';
+import { IHTTPImplementation } from '../../implementations/implementation';
+import { HTTPResponse, HTTPResponseError } from '../../response';
+import { HTTPHeaders } from '../../headers';
+import { retryInterceptor } from '../retry-interceptor';
+import { __TEST_ONLY_RESET_REQUEST_UID_DO_NOT_USE_IN_PRODUCTION } from '../../request';
+
+describe('test "HTTPRetryInterceptor"', () => {
+ let httpService: HTTPService;
+ let httpImplementation: MockHTTPImplementation;
+ let injector: Injector;
+
+ beforeEach(() => {
+ injector = createHTTPTestBed().injector;
+ httpService = injector.get(HTTPService);
+ httpImplementation = injector.get(IHTTPImplementation) as MockHTTPImplementation;
+
+ vitest.useFakeTimers();
+ });
+
+ afterEach(() => {
+ injector.dispose();
+
+ __TEST_ONLY_RESET_REQUEST_UID_DO_NOT_USE_IN_PRODUCTION();
+
+ vitest.useRealTimers();
+ });
+
+ function emitError(uid: number) {
+ httpImplementation.getHandler(uid).emitError(new HTTPResponseError({
+ headers: new HTTPHeaders(),
+ status: 500,
+ statusText: 'Internal Server Error',
+ error: new Error('mocked error'),
+ }));
+ }
+
+ function emitSuccess(uid: number) {
+ httpImplementation.getHandler(uid).emitResponse(new HTTPResponse({
+ headers: new HTTPHeaders(),
+ status: 200,
+ statusText: 'Request Succeeded',
+ body: {
+ text: 'Succeeded',
+ },
+ }));
+ }
+
+ it('should retry the request for 3 times until success', () => new Promise<void>((done) => {
+ httpService.registerHTTPInterceptor({
+ priority: 0,
+ interceptor: retryInterceptor,
+ });
+
+ const request = httpService.get('http://example.com');
+ request.then((response) => {
+ expect(response.body).toEqual({ text: 'Succeeded' });
+ done();
+ });
+
+ emitError(0);
+ vitest.advanceTimersByTime(1200);
+
+ emitError(0);
+ vitest.advanceTimersByTime(1200);
+
+ emitError(0);
+ vitest.advanceTimersByTime(1200);
+
+ emitSuccess(0);
+ }));
+
+ it('should throw error after attempt for 3 times', () => new Promise<void>((done) => {
+ httpService.registerHTTPInterceptor({
+ priority: 0,
+ interceptor: retryInterceptor,
+ });
+
+ const request = httpService.get('http://example.com');
+ request.then(() => {
+ // done();
+ }).catch((error: HTTPResponseError) => {
+ expect(error.status).toBe(500);
+ done();
+ });
+
+ emitError(0);
+ vitest.advanceTimersByTime(1200);
+ emitError(0);
+ vitest.advanceTimersByTime(1200);
+ emitError(0);
+ vitest.advanceTimersByTime(1200);
+ emitError(0);
+ vitest.advanceTimersByTime(1200);
+ }));
+});
diff --git a/packages/network/src/services/http/interceptors/__tests__/threshold-interceptor.spec.ts b/packages/network/src/services/http/interceptors/__tests__/threshold-interceptor.spec.ts
new file mode 100644
index 0000000000..52576ad2b3
--- /dev/null
+++ b/packages/network/src/services/http/interceptors/__tests__/threshold-interceptor.spec.ts
@@ -0,0 +1,105 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vitest } from 'vitest';
+import type { Injector } from '@wendellhu/redi';
+import { HTTPService } from '../../http.service';
+import { createHTTPTestBed, type MockHTTPImplementation } from '../../__testing__/http-testing-utils';
+import { IHTTPImplementation } from '../../implementations/implementation';
+import { __TEST_ONLY_RESET_REQUEST_UID_DO_NOT_USE_IN_PRODUCTION } from '../../request';
+import { ThresholdInterceptorFactory } from '../threshold-interceptor';
+import { HTTPHeaders } from '../../headers';
+import { HTTPResponse } from '../../response';
+
+describe('test "HTTPThresholdInterceptor"', () => {
+ let httpService: HTTPService;
+ let httpImplementation: MockHTTPImplementation;
+ let injector: Injector;
+
+ beforeEach(() => {
+ injector = createHTTPTestBed().injector;
+ httpService = injector.get(HTTPService);
+ httpImplementation = injector.get(IHTTPImplementation) as MockHTTPImplementation;
+
+ vitest.useFakeTimers();
+ });
+
+ afterEach(() => {
+ injector.dispose();
+
+ __TEST_ONLY_RESET_REQUEST_UID_DO_NOT_USE_IN_PRODUCTION();
+
+ vitest.useRealTimers();
+ });
+
+ function emitSuccess(uid: number) {
+ httpImplementation.getHandler(uid).emitResponse(new HTTPResponse({
+ headers: new HTTPHeaders(),
+ status: 200,
+ statusText: 'Request Succeeded',
+ body: {
+ text: 'Succeeded',
+ },
+ }));
+ }
+
+ it('should control parallel requests', () => {
+ httpService.registerHTTPInterceptor({
+ priority: 20,
+ interceptor: injector.invoke(ThresholdInterceptorFactory),
+ });
+
+ const _request1 = httpService.get('http://example.com');
+ const _request2 = httpService.get('http://example.com');
+
+ // due to threshold, the second request should not be sent
+ const _handler1 = httpImplementation.getHandler(0);
+ expect(() => httpImplementation.getHandler(1)).toThrowError();
+
+ // when the first request is completed, the second request should be sent
+ emitSuccess(0);
+ const _handler2 = httpImplementation.getHandler(1);
+
+ // let the second request get completed
+ emitSuccess(1);
+
+ // when the third request is sent, it should not be threshold
+ const _request3 = httpService.get('http://example.com');
+ const _handler3 = httpImplementation.getHandler(2);
+ emitSuccess(2);
+ });
+
+ it('should support threshold params', () => {
+ httpService.registerHTTPInterceptor({
+ priority: 20,
+ interceptor: injector.invoke(ThresholdInterceptorFactory, { maxParallel: 2 }),
+ });
+
+ const _request1 = httpService.get('http://example.com');
+ const _request2 = httpService.get('http://example.com');
+
+ // since the threshold is 2, the second should be sent simultaneously
+ const _handler1 = httpImplementation.getHandler(0);
+ const _handler2 = httpImplementation.getHandler(1);
+
+ emitSuccess(0);
+ emitSuccess(1);
+ });
+});
+
+it('should work', () => {
+ expect(1).toBe(1);
+});
diff --git a/packages/network/src/services/http/interceptors/retry-interceptor.ts b/packages/network/src/services/http/interceptors/retry-interceptor.ts
new file mode 100644
index 0000000000..56ed1f13cd
--- /dev/null
+++ b/packages/network/src/services/http/interceptors/retry-interceptor.ts
@@ -0,0 +1,41 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { delay, of, throwError } from 'rxjs';
+import { concatMap, retryWhen } from 'rxjs/operators';
+import type { HTTPInterceptorFn } from '../interceptor';
+
+const MAX_RETRY_ATTEMPTS = 2;
+const DELAY_INTERVAL = 1000;
+
+// TODO@wzhudev: should fix these deprecated warning here
+
+export const retryInterceptor: HTTPInterceptorFn = (request, next) => {
+ return next(request).pipe(
+ retryWhen((errors) => {
+ return errors.pipe(
+ concatMap((error, index) => {
+ if (index > MAX_RETRY_ATTEMPTS) {
+ return throwError(error);
+ }
+
+ return of(error);
+ }),
+ delay(DELAY_INTERVAL)
+ );
+ })
+ );
+};
diff --git a/packages/network/src/services/http/interceptors/threshold-interceptor.ts b/packages/network/src/services/http/interceptors/threshold-interceptor.ts
new file mode 100644
index 0000000000..e33bbc7c8b
--- /dev/null
+++ b/packages/network/src/services/http/interceptors/threshold-interceptor.ts
@@ -0,0 +1,62 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IAccessor } from '@wendellhu/redi';
+import { Observable } from 'rxjs';
+import { remove } from '@univerjs/core';
+import type { HTTPInterceptorFnFactory } from '../interceptor';
+
+export interface IThresholdInterceptorFactoryParams {
+ maxParallel?: number;
+}
+
+type HandlerFn = () => void;
+export const ThresholdInterceptorFactory: HTTPInterceptorFnFactory = (_accessor: IAccessor, params?: IThresholdInterceptorFactoryParams) => {
+ /**
+ * The local variable to store handles.
+ */
+ const handlers: HandlerFn[] = [];
+ const ongoingHandlers = new Set<HandlerFn>();
+
+ const tick = (): void => {
+ while (ongoingHandlers.size < (params?.maxParallel ?? 1) && handlers.length > 0) {
+ const handler = handlers.shift()!;
+ ongoingHandlers.add(handler);
+ handler();
+ }
+ };
+
+ return (request, next) => {
+ return new Observable((observer) => {
+ const handler = () => next(request).subscribe({
+ next: (event) => observer.next(event),
+ error: (err) => observer.next(err),
+ complete: () => observer.complete(),
+ });
+
+ const teardown = () => {
+ ongoingHandlers.delete(handler);
+ remove(handlers, handler);
+ tick();
+ };
+
+ handlers.push(handler);
+ tick();
+
+ return teardown;
+ });
+ };
+};
diff --git a/packages/network/src/services/http/request.ts b/packages/network/src/services/http/request.ts
index 68b26cbe66..1059823ad7 100644
--- a/packages/network/src/services/http/request.ts
+++ b/packages/network/src/services/http/request.ts
@@ -22,6 +22,7 @@ import type { HTTPParams } from './params';
export type HTTPRequestMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
export interface IHTTPRequestParams {
+ // eslint-disable-next-line ts/no-explicit-any
body?: any;
headers: HTTPHeaders;
params?: HTTPParams;
@@ -29,18 +30,18 @@ export interface IHTTPRequestParams {
withCredentials: boolean;
}
-export class HTTPRequest {
- get headers(): HTTPHeaders {
- return this.requestParams!.headers;
- }
+let HTTPRequestUID = 0;
- get withCredentials(): boolean {
- return this.requestParams!.withCredentials;
- }
+export function __TEST_ONLY_RESET_REQUEST_UID_DO_NOT_USE_IN_PRODUCTION() {
+ HTTPRequestUID = 0;
+}
- get responseType(): string {
- return this.requestParams!.responseType;
- }
+export class HTTPRequest {
+ get headers(): HTTPHeaders { return this.requestParams!.headers; }
+ get withCredentials(): boolean { return this.requestParams!.withCredentials; }
+ get responseType(): string { return this.requestParams!.responseType; }
+
+ readonly uid = HTTPRequestUID++;
constructor(
readonly method: HTTPRequestMethod,