Skip to content

Commit

Permalink
Use new sdk time direcctly and indirectly for timetamps sent in SDK
Browse files Browse the repository at this point in the history
  • Loading branch information
bidetofevil committed Oct 24, 2023
1 parent 924a37b commit 92f623f
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 36 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public EmbraceOkHttp3ApplicationInterceptor() {

@Override
public Response intercept(Chain chain) throws IOException {
long startTime = System.currentTimeMillis();
long startTime = embrace.getSdkApi().getSdkCurrentTime();
Request request = chain.request();
try {
// we are not interested in response, just proceed
Expand All @@ -62,7 +62,7 @@ public Response intercept(Chain chain) throws IOException {
urlString,
HttpMethod.fromString(request.method()),
startTime,
System.currentTimeMillis(),
embrace.getSdkApi().getSdkCurrentTime(),
causeName(e, UNKNOWN_EXCEPTION),
causeMessage(e, UNKNOWN_MESSAGE),
request.header(embrace.getTraceIdHeader()),
Expand All @@ -84,7 +84,7 @@ public Response intercept(Chain chain) throws IOException {
urlString,
HttpMethod.fromString(request.method()),
startTime,
System.currentTimeMillis(),
embrace.getSdkApi().getSdkCurrentTime(),
errorType != null ? errorType : UNKNOWN_EXCEPTION,
errorMessage != null ? errorMessage : UNKNOWN_MESSAGE,
request.header(embrace.getTraceIdHeader()),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,10 @@ public Response intercept(Chain chain) throws IOException {
return chain.proceed(originalRequest);
}

long preRequestClockOffset = sdkClockOffset();
boolean networkSpanForwardingEnabled = embrace.getInternalInterface().isNetworkSpanForwardingEnabled();


String traceparent = null;
if (networkSpanForwardingEnabled && originalRequest.header(TRACEPARENT_HEADER_NAME) == null) {
traceparent = embrace.generateW3cTraceparent();
Expand All @@ -86,6 +88,7 @@ public Response intercept(Chain chain) throws IOException {
originalRequest : originalRequest.newBuilder().header(TRACEPARENT_HEADER_NAME, traceparent).build();

Response networkResponse = chain.proceed(request);
long postResponseClockOffset = sdkClockOffset();
Response.Builder responseBuilder = networkResponse.newBuilder().request(request);

Long contentLength = null;
Expand Down Expand Up @@ -152,12 +155,14 @@ public Response intercept(Chain chain) throws IOException {
networkCaptureData = getNetworkCaptureData(request, response);
}



embrace.recordNetworkRequest(
EmbraceNetworkRequest.fromCompletedRequest(
EmbraceHttpPathOverride.getURLString(new EmbraceOkHttp3PathOverrideRequest(request)),
HttpMethod.fromString(request.method()),
response.sentRequestAtMillis(),
response.receivedResponseAtMillis(),
response.sentRequestAtMillis() + preRequestClockOffset,
response.receivedResponseAtMillis() + postResponseClockOffset,
request.body() != null ? request.body().contentLength() : 0,
contentLength,
response.code(),
Expand Down Expand Up @@ -249,4 +254,12 @@ private byte[] getRequestBody(final Request request) {
}
return null;
}

/**
* Get the difference between the SDK clock time and the time System.currentTimeMillis() returns, which is used by OkHttp for
* determining client-side timestamps.
*/
private long sdkClockOffset() {
return embrace.getSdkApi().getSdkCurrentTime() - System.currentTimeMillis();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ internal class EmbraceOkHttp3InterceptorsTest {
every { mockEmbrace.isStarted } answers { isSDKStarted }
every { mockEmbrace.recordNetworkRequest(capture(capturedEmbraceNetworkRequest)) } answers { }
every { mockEmbrace.generateW3cTraceparent() } answers { GENERATED_TRACEPARENT }
every { mockEmbrace.sdkApi.getSdkCurrentTime() } answers { System.currentTimeMillis() }
every { mockEmbrace.internalInterface } answers { mockInternalInterface }
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@
import io.embrace.android.embracesdk.InternalApi;
import io.embrace.android.embracesdk.logging.InternalStaticEmbraceLogger;
import io.embrace.android.embracesdk.network.EmbraceNetworkRequest;
import io.embrace.android.embracesdk.utils.NetworkUtils;
import io.embrace.android.embracesdk.utils.exceptions.function.CheckedSupplier;
import kotlin.jvm.functions.Function0;

Expand All @@ -60,7 +59,7 @@
*/
@InternalApi
class EmbraceUrlConnectionOverride<T extends HttpURLConnection>
implements EmbraceUrlConnectionService, EmbraceSslUrlConnectionService {
implements EmbraceUrlConnectionService, EmbraceSslUrlConnectionService {

/**
* The content encoding HTTP header.
Expand Down Expand Up @@ -158,9 +157,9 @@ public EmbraceUrlConnectionOverride(@NonNull T connection, boolean enableWrapIoS
EmbraceUrlConnectionOverride(@NonNull T connection, boolean enableWrapIoStreams,
@NonNull Embrace embrace) {
this.connection = connection;
this.createdTime = System.currentTimeMillis();
this.enableWrapIoStreams = enableWrapIoStreams;
this.embrace = embrace;
this.createdTime = embrace.getSdkApi().getSdkCurrentTime();
this.callId = UUID.randomUUID().toString();
}

Expand Down Expand Up @@ -238,7 +237,7 @@ public int getContentLength() {
@TargetApi(24)
public long getContentLengthLong() {
return (shouldUncompressGzip() || Build.VERSION.SDK_INT < Build.VERSION_CODES.N) ?
-1 : this.connection.getContentLengthLong();
-1 : this.connection.getContentLengthLong();
}

@Override
Expand Down Expand Up @@ -299,17 +298,17 @@ public boolean shouldInterceptHeaderRetrieval(@Nullable String key) {
public String getHeaderField(int n) {
String key = this.connection.getHeaderFieldKey(n);
return retrieveHeaderField(key,
null,
() -> connection.getHeaderField(n)
null,
() -> connection.getHeaderField(n)
);
}

@Override
@Nullable
public String getHeaderField(@Nullable String name) {
return retrieveHeaderField(name,
null,
() -> connection.getHeaderField(name)
null,
() -> connection.getHeaderField(name)
);
}

Expand All @@ -318,16 +317,16 @@ public String getHeaderField(@Nullable String name) {
public String getHeaderFieldKey(int n) {
String key = this.connection.getHeaderFieldKey(n);
return retrieveHeaderField(key,
null,
() -> key
null,
() -> key
);
}

@Override
public long getHeaderFieldDate(@NonNull String name, long defaultValue) {
Long result = retrieveHeaderField(name,
defaultValue,
() -> connection.getHeaderFieldDate(name, defaultValue)
defaultValue,
() -> connection.getHeaderFieldDate(name, defaultValue)
);

return result != null ? result : defaultValue;
Expand All @@ -336,8 +335,8 @@ public long getHeaderFieldDate(@NonNull String name, long defaultValue) {
@Override
public int getHeaderFieldInt(@NonNull String name, int defaultValue) {
Integer result = retrieveHeaderField(name,
defaultValue,
() -> connection.getHeaderFieldInt(name, defaultValue)
defaultValue,
() -> connection.getHeaderFieldInt(name, defaultValue)
);

return result != null ? result : defaultValue;
Expand All @@ -348,9 +347,9 @@ public int getHeaderFieldInt(@NonNull String name, int defaultValue) {
@TargetApi(24)
public long getHeaderFieldLong(@NonNull String name, long defaultValue) {
Long result = retrieveHeaderField(name,
defaultValue,
() -> Build.VERSION.SDK_INT < Build.VERSION_CODES.N ? -1 :
this.connection.getHeaderFieldLong(name, defaultValue)
defaultValue,
() -> Build.VERSION.SDK_INT < Build.VERSION_CODES.N ? -1 :
this.connection.getHeaderFieldLong(name, defaultValue)

);
return result != null ? result : defaultValue;
Expand All @@ -359,7 +358,7 @@ public long getHeaderFieldLong(@NonNull String name, long defaultValue) {
@Override
@Nullable
public Map<String, List<String>> getHeaderFields() {
final long startTime = System.currentTimeMillis();
final long startTime = embrace.getSdkApi().getSdkCurrentTime();
cacheResponseData();
internalLogNetworkCall(startTime);
return headerFields.get();
Expand All @@ -372,7 +371,7 @@ private <R> R retrieveHeaderField(@Nullable String name,
if (name == null) {
return null;
}
long startTime = System.currentTimeMillis();
long startTime = embrace.getSdkApi().getSdkCurrentTime();
if (shouldInterceptHeaderRetrieval(name)) {
// Strip the content encoding and length headers, as we transparently ungzip the content
return defaultValue;
Expand Down Expand Up @@ -472,9 +471,9 @@ public String getRequestProperty(@NonNull String key) {
}

@Override
public int getResponseCode() throws IOException {
public int getResponseCode() {
identifyTraceId();
long startTime = System.currentTimeMillis();
long startTime = embrace.getSdkApi().getSdkCurrentTime();
cacheResponseData();
internalLogNetworkCall(startTime);
return responseCode.get();
Expand All @@ -484,7 +483,7 @@ public int getResponseCode() throws IOException {
@Nullable
public String getResponseMessage() throws IOException {
identifyTraceId();
long startTime = System.currentTimeMillis();
long startTime = embrace.getSdkApi().getSdkCurrentTime();
String responseMsg = this.connection.getResponseMessage();
cacheResponseData();
internalLogNetworkCall(startTime);
Expand Down Expand Up @@ -549,7 +548,7 @@ public boolean usingProxy() {
* ignored.
*/
synchronized void internalLogNetworkCall(long startTime) {
internalLogNetworkCall(startTime, System.currentTimeMillis(), false, null);
internalLogNetworkCall(startTime, embrace.getSdkApi().getSdkCurrentTime(), false, null);
}

/**
Expand Down Expand Up @@ -687,14 +686,13 @@ private CountingInputStreamWithCallback countingInputStream(InputStream inputStr
*
* @return true if we should decompress the response, false otherwise
* @see <a href="https://developer.android.com/reference/java/net/HttpURLConnection#performance">Android Docs</a>
* @see
* <a href="https://android.googlesource.com/platform/external/okhttp/+/master/okhttp/src/main/java/com/squareup/okhttp/internal/http/HttpEngine.java">Android Source Code</a>
* @see <a href="https://android.googlesource.com/platform/external/okhttp/+/master/okhttp/src/main/java/com/squareup/okhttp/internal/http/HttpEngine.java">Android Source Code</a>
*/
private boolean shouldUncompressGzip() {
String contentEncoding = this.connection.getContentEncoding();
return enableWrapIoStreams &&
contentEncoding != null &&
contentEncoding.equalsIgnoreCase("gzip");
contentEncoding != null &&
contentEncoding.equalsIgnoreCase("gzip");
}

private void identifyTraceId() {
Expand Down Expand Up @@ -794,7 +792,7 @@ public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
@Nullable
private InputStream getWrappedInputStream(InputStream connectionInputStream) {
identifyTraceId();
long startTime = System.currentTimeMillis();
long startTime = embrace.getSdkApi().getSdkCurrentTime();

InputStream in = null;
if (shouldUncompressGzip()) {
Expand All @@ -808,7 +806,7 @@ private InputStream getWrappedInputStream(InputStream connectionInputStream) {

if (in == null) {
in = enableWrapIoStreams ?
countingInputStream(new BufferedInputStream(connectionInputStream)) : connectionInputStream;
countingInputStream(new BufferedInputStream(connectionInputStream)) : connectionInputStream;
}

cacheResponseData();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,10 @@ internal object EmbraceCrashSamples {
fun triggerLongAnr() {
isSdkStarted()
checkAnrDetectionEnabled()
val start = System.currentTimeMillis()
val embrace = Embrace.getInstance()
val start = embrace.internalInterface.getSdkCurrentTime()
while (true) {
if (System.currentTimeMillis() - start >= LONG_ANR_LENGTH) {
if (embrace.internalInterface.getSdkCurrentTime() - start >= LONG_ANR_LENGTH) {
break
}
}
Expand Down

0 comments on commit 92f623f

Please sign in to comment.