1
>
/*---------------------------------------------------------------------------------------------
requestStore.ts
2
>
* Copyright (c) Microsoft Corporation. All rights reserved.
3
>
* Licensed under the MIT License. See License.txt in the project root for license information.
4
>
*--------------------------------------------------------------------------------------------*/
5
>
6
>
import { timeout } from '../../../base/common/async.js';
7
>
import { CancellationTokenSource } from '../../../base/common/cancellation.js';
8
>
import { Emitter } from '../../../base/common/event.js';
9
>
import { Disposable, dispose, IDisposable, toDisposable } from '../../../base/common/lifecycle.js';
10
>
import { ILogService } from '../../log/common/log.js';
11
>
12
>
/**
13
>
* A helper class to track requests that have replies. Using this it's easy to implement an event
14
>
* that accepts a reply.
15
>
*/
16
>
export class RequestStore<T, RequestArgs> extends Disposable {
17
>
private _lastRequestId = 0;
18
>
private readonly _timeout: number;
19
>
private _pendingRequests: Map<number, (resolved: T) => void> = new Map();
20
>
private _pendingRequestDisposables: Map<number, IDisposable[]> = new Map();
21
>
22
>
private readonly _onCreateRequest = this._register(new Emitter<RequestArgs & { requestId: number }>());
23
>
readonly onCreateRequest = this._onCreateRequest.event;
24
>
25
>
/**
26
>
* @param timeout How long in ms to allow requests to go unanswered for, undefined will use the
27
>
* default (15 seconds).
28
>
*/
29
>
constructor(
30
>
timeout: number | undefined,
31
>
@ILogService private readonly _logService: ILogService
32
>
) {
33
>
super();
34
>
this._timeout = timeout === undefined ? 15000 : timeout;
35
>
this._register(toDisposable(() => {
36
>
for (const d of this._pendingRequestDisposables.values()) {
37
dispose(d);
38
}
40
>
}
41
>
42
>
/**
43
>
* Creates a request.
44
>
* @param args The arguments to pass to the onCreateRequest event.
45
>
*/
46
>
createRequest(args: RequestArgs): Promise<T> {
47
return new Promise<T>((resolve, reject) => {
48
const requestId = ++this._lastRequestId;