|
| 1 | +/* |
| 2 | + * Copyright The OpenTelemetry Authors |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +package io.opentelemetry.javaagent.instrumentation.activejhttp; |
| 7 | + |
| 8 | +import static io.opentelemetry.javaagent.instrumentation.activejhttp.ActivejHttpServerConnectionSingletons.instrumenter; |
| 9 | + |
| 10 | +import io.activej.http.HttpRequest; |
| 11 | +import io.activej.http.HttpResponse; |
| 12 | +import io.activej.promise.Promise; |
| 13 | +import io.activej.promise.SettablePromise; |
| 14 | +import io.opentelemetry.context.Context; |
| 15 | +import io.opentelemetry.context.Scope; |
| 16 | + |
| 17 | +public class PromiseWrapper { |
| 18 | + |
| 19 | + public static Promise<HttpResponse> wrap( |
| 20 | + Promise<HttpResponse> promise, HttpRequest httpRequest, Context context) { |
| 21 | + SettablePromise<HttpResponse> settablePromise = new SettablePromise<>(); |
| 22 | + promise |
| 23 | + .whenResult( |
| 24 | + result -> { |
| 25 | + Exception error = null; |
| 26 | + try (Scope ignored = context.makeCurrent()) { |
| 27 | + settablePromise.set(result); |
| 28 | + } catch (RuntimeException exception) { |
| 29 | + error = exception; |
| 30 | + settablePromise.setException( |
| 31 | + new RuntimeException("Context management failed", exception)); |
| 32 | + } finally { |
| 33 | + instrumenter().end(context, httpRequest, result, error); |
| 34 | + } |
| 35 | + }) |
| 36 | + .whenException( |
| 37 | + throwable -> { |
| 38 | + try (Scope ignored = context.makeCurrent()) { |
| 39 | + settablePromise.setException(throwable); |
| 40 | + } catch (RuntimeException exception) { |
| 41 | + settablePromise.setException( |
| 42 | + new RuntimeException("Context management failed", exception)); |
| 43 | + } finally { |
| 44 | + instrumenter().end(context, httpRequest, null, throwable); |
| 45 | + } |
| 46 | + }); |
| 47 | + return settablePromise; |
| 48 | + } |
| 49 | + |
| 50 | + private PromiseWrapper() {} |
| 51 | +} |
0 commit comments