diff options
Diffstat (limited to 'packages/taler-util/src/observability.ts')
-rw-r--r-- | packages/taler-util/src/observability.ts | 46 |
1 files changed, 41 insertions, 5 deletions
diff --git a/packages/taler-util/src/observability.ts b/packages/taler-util/src/observability.ts index 198dcbe6e..f40967c52 100644 --- a/packages/taler-util/src/observability.ts +++ b/packages/taler-util/src/observability.ts @@ -14,9 +14,17 @@ GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> */ -import { ObservabilityEvent } from "./index.js"; -import { HttpRequestLibrary, HttpRequestOptions, HttpResponse } from "./http-common.js"; -import { ObservabilityEventType } from "./notifications.js" +import { + AbsoluteTime, + CancellationToken, + ObservabilityEvent, +} from "./index.js"; +import { + HttpRequestLibrary, + HttpRequestOptions, + HttpResponse, +} from "./http-common.js"; +import { ObservabilityEventType } from "./notifications.js"; import { getErrorDetailFromException } from "./errors.js"; /** @@ -27,22 +35,48 @@ export interface ObservabilityContext { observe(evt: ObservabilityEvent): void; } +let seqId = 1000; + export class ObservableHttpClientLibrary implements HttpRequestLibrary { + private readonly currentRequest = new Map<string, CancellationToken.Source>(); constructor( private impl: HttpRequestLibrary, private oc: ObservabilityContext, - ) { } + ) {} + + public cancelRequest(id: string) { + const cancelator = this.currentRequest.get(id); + if (!cancelator) return; + cancelator.cancel(); + } + async fetch( url: string, opt?: HttpRequestOptions | undefined, ): Promise<HttpResponse> { + const id = `req-${seqId}`; + seqId = seqId + 1; + + const cancelator = CancellationToken.create(); + if (opt?.cancellationToken) { + opt.cancellationToken.onCancelled(cancelator.cancel); + } + this.currentRequest.set(id, cancelator); + this.oc.observe({ + id, + when: AbsoluteTime.now(), type: ObservabilityEventType.HttpFetchStart, url: url, }); + + const optsWithCancel = opt ?? {}; + optsWithCancel.cancellationToken = cancelator.token; try { - const res = await this.impl.fetch(url, opt); + const res = await this.impl.fetch(url, optsWithCancel); this.oc.observe({ + id, + when: AbsoluteTime.now(), type: ObservabilityEventType.HttpFetchFinishSuccess, url, status: res.status, @@ -50,6 +84,8 @@ export class ObservableHttpClientLibrary implements HttpRequestLibrary { return res; } catch (e) { this.oc.observe({ + id, + when: AbsoluteTime.now(), type: ObservabilityEventType.HttpFetchFinishError, url, error: getErrorDetailFromException(e), |