Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@
import static org.assertj.core.api.Assertions.assertThat;

import com.palantir.tracing.Tracer;
import com.palantir.tracing.api.Span;
import java.io.ByteArrayOutputStream;
import javax.ws.rs.core.StreamingOutput;
import org.junit.Test;
Expand All@@ -32,14 +33,16 @@ public void testWrappingStreamingOutput_streamingOutputTraceIsIsolated() throws
Tracer.startSpan("inside"); // never completed
});
streamingOutput.write(new ByteArrayOutputStream());
assertThat(Tracer.completeSpan().get().getOperation()).isEqualTo("outside");
Tracer.completeSpan().map(Span::getOperation)
.ifPresent(op -> assertThat(op).isEqualTo("outside"));
}

@Test
public void testWrappingStreamingOutput_traceStateIsCapturedAtConstructionTime() throws Exception {
Tracer.startSpan("before-construction");
StreamingOutput streamingOutput = JaxRsTracers.wrap(os -> {
assertThat(Tracer.completeSpan().get().getOperation()).isEqualTo("streaming-output");
Tracer.completeSpan().map(Span::getOperation)
.ifPresent(op -> assertThat(op).isEqualTo("streaming-output"));
});
Tracer.startSpan("after-construction");
streamingOutput.write(new ByteArrayOutputStream());
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -104,7 +104,7 @@ public <T, E extends Throwable> T withTrace(Tracers.ThrowingCallable<T, E> inner

Optional<Trace> originalTrace = Tracer.copyTrace();

Tracer.setTrace(new Trace(isObservable, traceId));
Tracer.setTrace(Trace.create(isObservable, traceId));
if (parentSpanId != null) {
Tracer.startSpan(operation, parentSpanId, SpanType.LOCAL);
} else {
Expand Down
232 changes: 232 additions & 0 deletions tracing/src/main/java/com/palantir/tracing/ImmutableEmptyDeque.java
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
/*
* (c) Copyright 2019 Palantir Technologies Inc. All rights reserved.
*
* 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.
*/

package com.palantir.tracing;

import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.Iterator;
import java.util.NoSuchElementException;

final class ImmutableEmptyDeque<E> implements Deque<E> {

private static final Object[] EMPTY_ARRAY = new Object[0];
private static final ImmutableEmptyDeque<?> EMPTY_DEQUE = new ImmutableEmptyDeque<>();

ImmutableEmptyDeque() {}

@SuppressWarnings("unchecked")
static <E> Deque<E> instance() {
return (Deque<E>) EMPTY_DEQUE;
}

private static UnsupportedOperationException cannotModify() {
return new UnsupportedOperationException("cannot modify immutable empty deque");
}

@Override
public boolean isEmpty() {
return true;
}

@Override
public int size() {
return 0;
}

@Override
public boolean equals(Object obj) {
return this == obj || this.getClass() == obj.getClass();
}

@Override
public int hashCode() {
return 0;
}

@Override
public String toString() {
return "[]";
}

@Override
public Iterator<E> iterator() {
return Collections.emptyIterator();
}

@Override
public Iterator<E> descendingIterator() {
return Collections.emptyIterator();
}

@Override
public Object[] toArray() {
return EMPTY_ARRAY;
}

@Override
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] array) {
return (T[]) EMPTY_ARRAY;
}

@Override
public boolean add(E element) {
throw cannotModify();
}

@Override
public boolean addAll(Collection<? extends E> collection) {
throw cannotModify();
}

@Override
public void addFirst(E element) {
throw cannotModify();
}

@Override
public void addLast(E element) {
throw cannotModify();
}

@Override
public void clear() {
throw cannotModify();
}

@Override
public boolean contains(Object obj) {
return false;
}

@Override
public boolean containsAll(Collection<?> collection) {
return false;
}

@Override
public E element() {
throw new NoSuchElementException();
}

@Override
public E getFirst() {
throw new NoSuchElementException();
}

@Override
public E getLast() {
throw new NoSuchElementException();
}

@Override
public boolean offer(E element) {
throw cannotModify();
}

@Override
public boolean offerFirst(E element) {
throw cannotModify();
}

@Override
public boolean offerLast(E element) {
throw cannotModify();
}

@Override
public E peek() {
return null;
}

@Override
public E peekFirst() {
return null;
}

@Override
public E peekLast() {
return null;
}

@Override
public E poll() {
return null;
}

@Override
public E pollFirst() {
return null;
}

@Override
public E pollLast() {
return null;
}

@Override
public E pop() {
throw cannotModify();
}

@Override
public void push(E element) {
throw cannotModify();
}

@Override
public E remove() {
throw cannotModify();
}

@Override
public boolean remove(Object obj) {
throw cannotModify();
}

@Override
public boolean removeAll(Collection<?> collection) {
throw cannotModify();
}

@Override
public E removeFirst() {
throw cannotModify();
}

@Override
public boolean removeFirstOccurrence(Object obj) {
throw cannotModify();
}

@Override
public E removeLast() {
throw cannotModify();
}

@Override
public boolean removeLastOccurrence(Object obj) {
throw cannotModify();
}

@Override
public boolean retainAll(Collection<?> collection) {
throw cannotModify();
}

}
14 changes: 9 additions & 5 deletions tracing/src/main/java/com/palantir/tracing/Trace.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,20 +34,23 @@ public final class Trace {
private final boolean isObservable;
private final String traceId;

private Trace(ArrayDeque<OpenSpan> stack, boolean isObservable, String traceId) {
private Trace(Deque<OpenSpan> stack, boolean isObservable, String traceId) {
checkArgument(!traceId.isEmpty(), "traceId must be non-empty");

this.stack = stack;
this.isObservable = isObservable;
this.traceId = traceId;
}

Trace(boolean isObservable, String traceId) {
this(new ArrayDeque<>(), isObservable, traceId);
static Trace create(boolean isObservable, String traceId) {
Deque<OpenSpan> deque = isObservable ? new ArrayDeque<>() : ImmutableEmptyDeque.instance();
return new Trace(deque, isObservable, traceId);
}

void push(OpenSpan span) {
stack.push(span);
if (isObservable) {
stack.push(span);
}
}

Optional<OpenSpan> top() {
Expand DownExpand Up@@ -79,7 +82,8 @@ String getTraceId() {

/** Returns a copy of this Trace which can be independently mutated. */
Trace deepCopy() {
return new Trace(new ArrayDeque<>(stack), isObservable, traceId);
Deque<OpenSpan> deque = isObservable ? new ArrayDeque<>(stack) : ImmutableEmptyDeque.instance();
return new Trace(deque, isObservable, traceId);
}

@Override
Expand Down
29 changes: 26 additions & 3 deletions tracing/src/main/java/com/palantir/tracing/Tracer.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@
import static com.palantir.logsafe.Preconditions.checkNotNull;
import static com.palantir.logsafe.Preconditions.checkState;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.errorprone.annotations.CheckReturnValue;
import com.palantir.logsafe.SafeArg;
Expand DownExpand Up@@ -48,6 +49,16 @@ public final class Tracer {

private static final Logger log = LoggerFactory.getLogger(Tracer.class);

/**
* No-op span used internally to avoid allocating when trace is unobservable.
*/
private static final OpenSpan NOOP_SPAN = OpenSpan.builder()
.type(SpanType.LOCAL)
.operation("noop")
.parentSpanId(Optional.empty())
.spanId("noop")
.build();

private Tracer() {}

// Thread-safe since thread-local
Expand All@@ -68,7 +79,7 @@ private Tracer() {}
private static Trace createTrace(Observability observability, String traceId) {
checkArgument(!Strings.isNullOrEmpty(traceId), "traceId must be non-empty");
boolean observable = shouldObserve(observability);
return new Trace(observable, traceId);
return Trace.create(observable, traceId);
}

private static boolean shouldObserve(Observability observability) {
Expand All@@ -94,7 +105,6 @@ public static void initTrace(Optional<Boolean> isObservable, String traceId) {
Observability observability = isObservable
.map(value -> Boolean.TRUE.equals(value) ? Observability.SAMPLE : Observability.DO_NOT_SAMPLE)
.orElse(Observability.UNDECIDED);

setTrace(createTrace(observability, traceId));
}

Expand All@@ -111,6 +121,10 @@ public static void initTrace(Observability observability, String traceId) {
*/
public static OpenSpan startSpan(String operation, String parentSpanId, SpanType type) {
Trace current = getOrCreateCurrentTrace();
if (!current.isObservable()) {
return NOOP_SPAN;
}

checkState(current.isEmpty(),
"Cannot start a span with explicit parent if the current thread's trace is non-empty");
checkArgument(!Strings.isNullOrEmpty(parentSpanId), "parentSpanId must be non-empty");
Expand DownExpand Up@@ -139,12 +153,16 @@ public static OpenSpan startSpan(String operation) {
}

private static OpenSpan startSpanInternal(String operation, SpanType type) {
Trace trace = getOrCreateCurrentTrace();
if (!trace.isObservable()) {
return NOOP_SPAN;
}

OpenSpan.Builder spanBuilder = OpenSpan.builder()
.operation(operation)
.spanId(Tracers.randomId())
.type(type);

Trace trace = getOrCreateCurrentTrace();
Optional<OpenSpan> prevState = trace.top();
// Avoid lambda allocation in hot paths
if (prevState.isPresent()) {
Expand DownExpand Up@@ -304,6 +322,11 @@ public static void setSampler(TraceSampler sampler) {
Tracer.sampler = sampler;
}

@VisibleForTesting
static TraceSampler getSampler() {
return Tracer.sampler;
}

/** Returns true if there is an active trace on this thread. */
public static boolean hasTraceId() {
return currentTrace.get() != null;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
[improvement] Avoid trace ID and span allocations when not observing by schlosna · Pull Request #168 · palantir/tracing-java · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@
import static org.assertj.core.api.Assertions.assertThat;

import com.palantir.tracing.Tracer;
import com.palantir.tracing.api.Span;
import java.io.ByteArrayOutputStream;
import javax.ws.rs.core.StreamingOutput;
import org.junit.Test;
Expand All@@ -32,14 +33,16 @@ public void testWrappingStreamingOutput_streamingOutputTraceIsIsolated() throws
Tracer.startSpan("inside"); // never completed
});
streamingOutput.write(new ByteArrayOutputStream());
assertThat(Tracer.completeSpan().get().getOperation()).isEqualTo("outside");
Tracer.completeSpan().map(Span::getOperation)
.ifPresent(op -> assertThat(op).isEqualTo("outside"));
}

@Test
public void testWrappingStreamingOutput_traceStateIsCapturedAtConstructionTime() throws Exception {
Tracer.startSpan("before-construction");
StreamingOutput streamingOutput = JaxRsTracers.wrap(os -> {
assertThat(Tracer.completeSpan().get().getOperation()).isEqualTo("streaming-output");
Tracer.completeSpan().map(Span::getOperation)
.ifPresent(op -> assertThat(op).isEqualTo("streaming-output"));
});
Tracer.startSpan("after-construction");
streamingOutput.write(new ByteArrayOutputStream());
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -104,7 +104,7 @@ public <T, E extends Throwable> T withTrace(Tracers.ThrowingCallable<T, E> inner

Optional<Trace> originalTrace = Tracer.copyTrace();

Tracer.setTrace(new Trace(isObservable, traceId));
Tracer.setTrace(Trace.create(isObservable, traceId));
if (parentSpanId != null) {
Tracer.startSpan(operation, parentSpanId, SpanType.LOCAL);
} else {
Expand Down
232 changes: 232 additions & 0 deletions tracing/src/main/java/com/palantir/tracing/ImmutableEmptyDeque.java
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
/*
* (c) Copyright 2019 Palantir Technologies Inc. All rights reserved.
*
* 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.
*/

package com.palantir.tracing;

import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.Iterator;
import java.util.NoSuchElementException;

final class ImmutableEmptyDeque<E> implements Deque<E> {

private static final Object[] EMPTY_ARRAY = new Object[0];
private static final ImmutableEmptyDeque<?> EMPTY_DEQUE = new ImmutableEmptyDeque<>();

ImmutableEmptyDeque() {}

@SuppressWarnings("unchecked")
static <E> Deque<E> instance() {
return (Deque<E>) EMPTY_DEQUE;
}

private static UnsupportedOperationException cannotModify() {
return new UnsupportedOperationException("cannot modify immutable empty deque");
}

@Override
public boolean isEmpty() {
return true;
}

@Override
public int size() {
return 0;
}

@Override
public boolean equals(Object obj) {
return this == obj || this.getClass() == obj.getClass();
}

@Override
public int hashCode() {
return 0;
}

@Override
public String toString() {
return "[]";
}

@Override
public Iterator<E> iterator() {
return Collections.emptyIterator();
}

@Override
public Iterator<E> descendingIterator() {
return Collections.emptyIterator();
}

@Override
public Object[] toArray() {
return EMPTY_ARRAY;
}

@Override
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] array) {
return (T[]) EMPTY_ARRAY;
}

@Override
public boolean add(E element) {
throw cannotModify();
}

@Override
public boolean addAll(Collection<? extends E> collection) {
throw cannotModify();
}

@Override
public void addFirst(E element) {
throw cannotModify();
}

@Override
public void addLast(E element) {
throw cannotModify();
}

@Override
public void clear() {
throw cannotModify();
}

@Override
public boolean contains(Object obj) {
return false;
}

@Override
public boolean containsAll(Collection<?> collection) {
return false;
}

@Override
public E element() {
throw new NoSuchElementException();
}

@Override
public E getFirst() {
throw new NoSuchElementException();
}

@Override
public E getLast() {
throw new NoSuchElementException();
}

@Override
public boolean offer(E element) {
throw cannotModify();
}

@Override
public boolean offerFirst(E element) {
throw cannotModify();
}

@Override
public boolean offerLast(E element) {
throw cannotModify();
}

@Override
public E peek() {
return null;
}

@Override
public E peekFirst() {
return null;
}

@Override
public E peekLast() {
return null;
}

@Override
public E poll() {
return null;
}

@Override
public E pollFirst() {
return null;
}

@Override
public E pollLast() {
return null;
}

@Override
public E pop() {
throw cannotModify();
}

@Override
public void push(E element) {
throw cannotModify();
}

@Override
public E remove() {
throw cannotModify();
}

@Override
public boolean remove(Object obj) {
throw cannotModify();
}

@Override
public boolean removeAll(Collection<?> collection) {
throw cannotModify();
}

@Override
public E removeFirst() {
throw cannotModify();
}

@Override
public boolean removeFirstOccurrence(Object obj) {
throw cannotModify();
}

@Override
public E removeLast() {
throw cannotModify();
}

@Override
public boolean removeLastOccurrence(Object obj) {
throw cannotModify();
}

@Override
public boolean retainAll(Collection<?> collection) {
throw cannotModify();
}

}
14 changes: 9 additions & 5 deletions tracing/src/main/java/com/palantir/tracing/Trace.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,20 +34,23 @@ public final class Trace {
private final boolean isObservable;
private final String traceId;

private Trace(ArrayDeque<OpenSpan> stack, boolean isObservable, String traceId) {
private Trace(Deque<OpenSpan> stack, boolean isObservable, String traceId) {
checkArgument(!traceId.isEmpty(), "traceId must be non-empty");

this.stack = stack;
this.isObservable = isObservable;
this.traceId = traceId;
}

Trace(boolean isObservable, String traceId) {
this(new ArrayDeque<>(), isObservable, traceId);
static Trace create(boolean isObservable, String traceId) {
Deque<OpenSpan> deque = isObservable ? new ArrayDeque<>() : ImmutableEmptyDeque.instance();
return new Trace(deque, isObservable, traceId);
}

void push(OpenSpan span) {
stack.push(span);
if (isObservable) {
stack.push(span);
}
}

Optional<OpenSpan> top() {
Expand DownExpand Up@@ -79,7 +82,8 @@ String getTraceId() {

/** Returns a copy of this Trace which can be independently mutated. */
Trace deepCopy() {
return new Trace(new ArrayDeque<>(stack), isObservable, traceId);
Deque<OpenSpan> deque = isObservable ? new ArrayDeque<>(stack) : ImmutableEmptyDeque.instance();
return new Trace(deque, isObservable, traceId);
}

@Override
Expand Down
29 changes: 26 additions & 3 deletions tracing/src/main/java/com/palantir/tracing/Tracer.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@
import static com.palantir.logsafe.Preconditions.checkNotNull;
import static com.palantir.logsafe.Preconditions.checkState;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.errorprone.annotations.CheckReturnValue;
import com.palantir.logsafe.SafeArg;
Expand DownExpand Up@@ -48,6 +49,16 @@ public final class Tracer {

private static final Logger log = LoggerFactory.getLogger(Tracer.class);

/**
* No-op span used internally to avoid allocating when trace is unobservable.
*/
private static final OpenSpan NOOP_SPAN = OpenSpan.builder()
.type(SpanType.LOCAL)
.operation("noop")
.parentSpanId(Optional.empty())
.spanId("noop")
.build();

private Tracer() {}

// Thread-safe since thread-local
Expand All@@ -68,7 +79,7 @@ private Tracer() {}
private static Trace createTrace(Observability observability, String traceId) {
checkArgument(!Strings.isNullOrEmpty(traceId), "traceId must be non-empty");
boolean observable = shouldObserve(observability);
return new Trace(observable, traceId);
return Trace.create(observable, traceId);
}

private static boolean shouldObserve(Observability observability) {
Expand All@@ -94,7 +105,6 @@ public static void initTrace(Optional<Boolean> isObservable, String traceId) {
Observability observability = isObservable
.map(value -> Boolean.TRUE.equals(value) ? Observability.SAMPLE : Observability.DO_NOT_SAMPLE)
.orElse(Observability.UNDECIDED);

setTrace(createTrace(observability, traceId));
}

Expand All@@ -111,6 +121,10 @@ public static void initTrace(Observability observability, String traceId) {
*/
public static OpenSpan startSpan(String operation, String parentSpanId, SpanType type) {
Trace current = getOrCreateCurrentTrace();
if (!current.isObservable()) {
return NOOP_SPAN;
}

checkState(current.isEmpty(),
"Cannot start a span with explicit parent if the current thread's trace is non-empty");
checkArgument(!Strings.isNullOrEmpty(parentSpanId), "parentSpanId must be non-empty");
Expand DownExpand Up@@ -139,12 +153,16 @@ public static OpenSpan startSpan(String operation) {
}

private static OpenSpan startSpanInternal(String operation, SpanType type) {
Trace trace = getOrCreateCurrentTrace();
if (!trace.isObservable()) {
return NOOP_SPAN;
}

OpenSpan.Builder spanBuilder = OpenSpan.builder()
.operation(operation)
.spanId(Tracers.randomId())
.type(type);

Trace trace = getOrCreateCurrentTrace();
Optional<OpenSpan> prevState = trace.top();
// Avoid lambda allocation in hot paths
if (prevState.isPresent()) {
Expand DownExpand Up@@ -304,6 +322,11 @@ public static void setSampler(TraceSampler sampler) {
Tracer.sampler = sampler;
}

@VisibleForTesting
static TraceSampler getSampler() {
return Tracer.sampler;
}

/** Returns true if there is an active trace on this thread. */
public static boolean hasTraceId() {
return currentTrace.get() != null;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [improvement] Avoid trace ID and span allocations when not observing by schlosna · Pull Request #168 · palantir/tracing-java · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@
import static org.assertj.core.api.Assertions.assertThat;

import com.palantir.tracing.Tracer;
import com.palantir.tracing.api.Span;
import java.io.ByteArrayOutputStream;
import javax.ws.rs.core.StreamingOutput;
import org.junit.Test;
Expand All@@ -32,14 +33,16 @@ public void testWrappingStreamingOutput_streamingOutputTraceIsIsolated() throws
Tracer.startSpan("inside"); // never completed
});
streamingOutput.write(new ByteArrayOutputStream());
assertThat(Tracer.completeSpan().get().getOperation()).isEqualTo("outside");
Tracer.completeSpan().map(Span::getOperation)
.ifPresent(op -> assertThat(op).isEqualTo("outside"));
}

@Test
public void testWrappingStreamingOutput_traceStateIsCapturedAtConstructionTime() throws Exception {
Tracer.startSpan("before-construction");
StreamingOutput streamingOutput = JaxRsTracers.wrap(os -> {
assertThat(Tracer.completeSpan().get().getOperation()).isEqualTo("streaming-output");
Tracer.completeSpan().map(Span::getOperation)
.ifPresent(op -> assertThat(op).isEqualTo("streaming-output"));
});
Tracer.startSpan("after-construction");
streamingOutput.write(new ByteArrayOutputStream());
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -104,7 +104,7 @@ public <T, E extends Throwable> T withTrace(Tracers.ThrowingCallable<T, E> inner

Optional<Trace> originalTrace = Tracer.copyTrace();

Tracer.setTrace(new Trace(isObservable, traceId));
Tracer.setTrace(Trace.create(isObservable, traceId));
if (parentSpanId != null) {
Tracer.startSpan(operation, parentSpanId, SpanType.LOCAL);
} else {
Expand Down
232 changes: 232 additions & 0 deletions tracing/src/main/java/com/palantir/tracing/ImmutableEmptyDeque.java
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
/*
* (c) Copyright 2019 Palantir Technologies Inc. All rights reserved.
*
* 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.
*/

package com.palantir.tracing;

import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.Iterator;
import java.util.NoSuchElementException;

final class ImmutableEmptyDeque<E> implements Deque<E> {

private static final Object[] EMPTY_ARRAY = new Object[0];
private static final ImmutableEmptyDeque<?> EMPTY_DEQUE = new ImmutableEmptyDeque<>();

ImmutableEmptyDeque() {}

@SuppressWarnings("unchecked")
static <E> Deque<E> instance() {
return (Deque<E>) EMPTY_DEQUE;
}

private static UnsupportedOperationException cannotModify() {
return new UnsupportedOperationException("cannot modify immutable empty deque");
}

@Override
public boolean isEmpty() {
return true;
}

@Override
public int size() {
return 0;
}

@Override
public boolean equals(Object obj) {
return this == obj || this.getClass() == obj.getClass();
}

@Override
public int hashCode() {
return 0;
}

@Override
public String toString() {
return "[]";
}

@Override
public Iterator<E> iterator() {
return Collections.emptyIterator();
}

@Override
public Iterator<E> descendingIterator() {
return Collections.emptyIterator();
}

@Override
public Object[] toArray() {
return EMPTY_ARRAY;
}

@Override
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] array) {
return (T[]) EMPTY_ARRAY;
}

@Override
public boolean add(E element) {
throw cannotModify();
}

@Override
public boolean addAll(Collection<? extends E> collection) {
throw cannotModify();
}

@Override
public void addFirst(E element) {
throw cannotModify();
}

@Override
public void addLast(E element) {
throw cannotModify();
}

@Override
public void clear() {
throw cannotModify();
}

@Override
public boolean contains(Object obj) {
return false;
}

@Override
public boolean containsAll(Collection<?> collection) {
return false;
}

@Override
public E element() {
throw new NoSuchElementException();
}

@Override
public E getFirst() {
throw new NoSuchElementException();
}

@Override
public E getLast() {
throw new NoSuchElementException();
}

@Override
public boolean offer(E element) {
throw cannotModify();
}

@Override
public boolean offerFirst(E element) {
throw cannotModify();
}

@Override
public boolean offerLast(E element) {
throw cannotModify();
}

@Override
public E peek() {
return null;
}

@Override
public E peekFirst() {
return null;
}

@Override
public E peekLast() {
return null;
}

@Override
public E poll() {
return null;
}

@Override
public E pollFirst() {
return null;
}

@Override
public E pollLast() {
return null;
}

@Override
public E pop() {
throw cannotModify();
}

@Override
public void push(E element) {
throw cannotModify();
}

@Override
public E remove() {
throw cannotModify();
}

@Override
public boolean remove(Object obj) {
throw cannotModify();
}

@Override
public boolean removeAll(Collection<?> collection) {
throw cannotModify();
}

@Override
public E removeFirst() {
throw cannotModify();
}

@Override
public boolean removeFirstOccurrence(Object obj) {
throw cannotModify();
}

@Override
public E removeLast() {
throw cannotModify();
}

@Override
public boolean removeLastOccurrence(Object obj) {
throw cannotModify();
}

@Override
public boolean retainAll(Collection<?> collection) {
throw cannotModify();
}

}
14 changes: 9 additions & 5 deletions tracing/src/main/java/com/palantir/tracing/Trace.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,20 +34,23 @@ public final class Trace {
private final boolean isObservable;
private final String traceId;

private Trace(ArrayDeque<OpenSpan> stack, boolean isObservable, String traceId) {
private Trace(Deque<OpenSpan> stack, boolean isObservable, String traceId) {
checkArgument(!traceId.isEmpty(), "traceId must be non-empty");

this.stack = stack;
this.isObservable = isObservable;
this.traceId = traceId;
}

Trace(boolean isObservable, String traceId) {
this(new ArrayDeque<>(), isObservable, traceId);
static Trace create(boolean isObservable, String traceId) {
Deque<OpenSpan> deque = isObservable ? new ArrayDeque<>() : ImmutableEmptyDeque.instance();
return new Trace(deque, isObservable, traceId);
}

void push(OpenSpan span) {
stack.push(span);
if (isObservable) {
stack.push(span);
}
}

Optional<OpenSpan> top() {
Expand DownExpand Up@@ -79,7 +82,8 @@ String getTraceId() {

/** Returns a copy of this Trace which can be independently mutated. */
Trace deepCopy() {
return new Trace(new ArrayDeque<>(stack), isObservable, traceId);
Deque<OpenSpan> deque = isObservable ? new ArrayDeque<>(stack) : ImmutableEmptyDeque.instance();
return new Trace(deque, isObservable, traceId);
}

@Override
Expand Down
29 changes: 26 additions & 3 deletions tracing/src/main/java/com/palantir/tracing/Tracer.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@
import static com.palantir.logsafe.Preconditions.checkNotNull;
import static com.palantir.logsafe.Preconditions.checkState;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.errorprone.annotations.CheckReturnValue;
import com.palantir.logsafe.SafeArg;
Expand DownExpand Up@@ -48,6 +49,16 @@ public final class Tracer {

private static final Logger log = LoggerFactory.getLogger(Tracer.class);

/**
* No-op span used internally to avoid allocating when trace is unobservable.
*/
private static final OpenSpan NOOP_SPAN = OpenSpan.builder()
.type(SpanType.LOCAL)
.operation("noop")
.parentSpanId(Optional.empty())
.spanId("noop")
.build();

private Tracer() {}

// Thread-safe since thread-local
Expand All@@ -68,7 +79,7 @@ private Tracer() {}
private static Trace createTrace(Observability observability, String traceId) {
checkArgument(!Strings.isNullOrEmpty(traceId), "traceId must be non-empty");
boolean observable = shouldObserve(observability);
return new Trace(observable, traceId);
return Trace.create(observable, traceId);
}

private static boolean shouldObserve(Observability observability) {
Expand All@@ -94,7 +105,6 @@ public static void initTrace(Optional<Boolean> isObservable, String traceId) {
Observability observability = isObservable
.map(value -> Boolean.TRUE.equals(value) ? Observability.SAMPLE : Observability.DO_NOT_SAMPLE)
.orElse(Observability.UNDECIDED);

setTrace(createTrace(observability, traceId));
}

Expand All@@ -111,6 +121,10 @@ public static void initTrace(Observability observability, String traceId) {
*/
public static OpenSpan startSpan(String operation, String parentSpanId, SpanType type) {
Trace current = getOrCreateCurrentTrace();
if (!current.isObservable()) {
return NOOP_SPAN;
}

checkState(current.isEmpty(),
"Cannot start a span with explicit parent if the current thread's trace is non-empty");
checkArgument(!Strings.isNullOrEmpty(parentSpanId), "parentSpanId must be non-empty");
Expand DownExpand Up@@ -139,12 +153,16 @@ public static OpenSpan startSpan(String operation) {
}

private static OpenSpan startSpanInternal(String operation, SpanType type) {
Trace trace = getOrCreateCurrentTrace();
if (!trace.isObservable()) {
return NOOP_SPAN;
}

OpenSpan.Builder spanBuilder = OpenSpan.builder()
.operation(operation)
.spanId(Tracers.randomId())
.type(type);

Trace trace = getOrCreateCurrentTrace();
Optional<OpenSpan> prevState = trace.top();
// Avoid lambda allocation in hot paths
if (prevState.isPresent()) {
Expand DownExpand Up@@ -304,6 +322,11 @@ public static void setSampler(TraceSampler sampler) {
Tracer.sampler = sampler;
}

@VisibleForTesting
static TraceSampler getSampler() {
return Tracer.sampler;
}

/** Returns true if there is an active trace on this thread. */
public static boolean hasTraceId() {
return currentTrace.get() != null;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [improvement] Avoid trace ID and span allocations when not observing by schlosna · Pull Request #168 · palantir/tracing-java · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@
import static org.assertj.core.api.Assertions.assertThat;

import com.palantir.tracing.Tracer;
import com.palantir.tracing.api.Span;
import java.io.ByteArrayOutputStream;
import javax.ws.rs.core.StreamingOutput;
import org.junit.Test;
Expand All@@ -32,14 +33,16 @@ public void testWrappingStreamingOutput_streamingOutputTraceIsIsolated() throws
Tracer.startSpan("inside"); // never completed
});
streamingOutput.write(new ByteArrayOutputStream());
assertThat(Tracer.completeSpan().get().getOperation()).isEqualTo("outside");
Tracer.completeSpan().map(Span::getOperation)
.ifPresent(op -> assertThat(op).isEqualTo("outside"));
}

@Test
public void testWrappingStreamingOutput_traceStateIsCapturedAtConstructionTime() throws Exception {
Tracer.startSpan("before-construction");
StreamingOutput streamingOutput = JaxRsTracers.wrap(os -> {
assertThat(Tracer.completeSpan().get().getOperation()).isEqualTo("streaming-output");
Tracer.completeSpan().map(Span::getOperation)
.ifPresent(op -> assertThat(op).isEqualTo("streaming-output"));
});
Tracer.startSpan("after-construction");
streamingOutput.write(new ByteArrayOutputStream());
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -104,7 +104,7 @@ public <T, E extends Throwable> T withTrace(Tracers.ThrowingCallable<T, E> inner

Optional<Trace> originalTrace = Tracer.copyTrace();

Tracer.setTrace(new Trace(isObservable, traceId));
Tracer.setTrace(Trace.create(isObservable, traceId));
if (parentSpanId != null) {
Tracer.startSpan(operation, parentSpanId, SpanType.LOCAL);
} else {
Expand Down
232 changes: 232 additions & 0 deletions tracing/src/main/java/com/palantir/tracing/ImmutableEmptyDeque.java
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
/*
* (c) Copyright 2019 Palantir Technologies Inc. All rights reserved.
*
* 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.
*/

package com.palantir.tracing;

import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.Iterator;
import java.util.NoSuchElementException;

final class ImmutableEmptyDeque<E> implements Deque<E> {

private static final Object[] EMPTY_ARRAY = new Object[0];
private static final ImmutableEmptyDeque<?> EMPTY_DEQUE = new ImmutableEmptyDeque<>();

ImmutableEmptyDeque() {}

@SuppressWarnings("unchecked")
static <E> Deque<E> instance() {
return (Deque<E>) EMPTY_DEQUE;
}

private static UnsupportedOperationException cannotModify() {
return new UnsupportedOperationException("cannot modify immutable empty deque");
}

@Override
public boolean isEmpty() {
return true;
}

@Override
public int size() {
return 0;
}

@Override
public boolean equals(Object obj) {
return this == obj || this.getClass() == obj.getClass();
}

@Override
public int hashCode() {
return 0;
}

@Override
public String toString() {
return "[]";
}

@Override
public Iterator<E> iterator() {
return Collections.emptyIterator();
}

@Override
public Iterator<E> descendingIterator() {
return Collections.emptyIterator();
}

@Override
public Object[] toArray() {
return EMPTY_ARRAY;
}

@Override
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] array) {
return (T[]) EMPTY_ARRAY;
}

@Override
public boolean add(E element) {
throw cannotModify();
}

@Override
public boolean addAll(Collection<? extends E> collection) {
throw cannotModify();
}

@Override
public void addFirst(E element) {
throw cannotModify();
}

@Override
public void addLast(E element) {
throw cannotModify();
}

@Override
public void clear() {
throw cannotModify();
}

@Override
public boolean contains(Object obj) {
return false;
}

@Override
public boolean containsAll(Collection<?> collection) {
return false;
}

@Override
public E element() {
throw new NoSuchElementException();
}

@Override
public E getFirst() {
throw new NoSuchElementException();
}

@Override
public E getLast() {
throw new NoSuchElementException();
}

@Override
public boolean offer(E element) {
throw cannotModify();
}

@Override
public boolean offerFirst(E element) {
throw cannotModify();
}

@Override
public boolean offerLast(E element) {
throw cannotModify();
}

@Override
public E peek() {
return null;
}

@Override
public E peekFirst() {
return null;
}

@Override
public E peekLast() {
return null;
}

@Override
public E poll() {
return null;
}

@Override
public E pollFirst() {
return null;
}

@Override
public E pollLast() {
return null;
}

@Override
public E pop() {
throw cannotModify();
}

@Override
public void push(E element) {
throw cannotModify();
}

@Override
public E remove() {
throw cannotModify();
}

@Override
public boolean remove(Object obj) {
throw cannotModify();
}

@Override
public boolean removeAll(Collection<?> collection) {
throw cannotModify();
}

@Override
public E removeFirst() {
throw cannotModify();
}

@Override
public boolean removeFirstOccurrence(Object obj) {
throw cannotModify();
}

@Override
public E removeLast() {
throw cannotModify();
}

@Override
public boolean removeLastOccurrence(Object obj) {
throw cannotModify();
}

@Override
public boolean retainAll(Collection<?> collection) {
throw cannotModify();
}

}
14 changes: 9 additions & 5 deletions tracing/src/main/java/com/palantir/tracing/Trace.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,20 +34,23 @@ public final class Trace {
private final boolean isObservable;
private final String traceId;

private Trace(ArrayDeque<OpenSpan> stack, boolean isObservable, String traceId) {
private Trace(Deque<OpenSpan> stack, boolean isObservable, String traceId) {
checkArgument(!traceId.isEmpty(), "traceId must be non-empty");

this.stack = stack;
this.isObservable = isObservable;
this.traceId = traceId;
}

Trace(boolean isObservable, String traceId) {
this(new ArrayDeque<>(), isObservable, traceId);
static Trace create(boolean isObservable, String traceId) {
Deque<OpenSpan> deque = isObservable ? new ArrayDeque<>() : ImmutableEmptyDeque.instance();
return new Trace(deque, isObservable, traceId);
}

void push(OpenSpan span) {
stack.push(span);
if (isObservable) {
stack.push(span);
}
}

Optional<OpenSpan> top() {
Expand DownExpand Up@@ -79,7 +82,8 @@ String getTraceId() {

/** Returns a copy of this Trace which can be independently mutated. */
Trace deepCopy() {
return new Trace(new ArrayDeque<>(stack), isObservable, traceId);
Deque<OpenSpan> deque = isObservable ? new ArrayDeque<>(stack) : ImmutableEmptyDeque.instance();
return new Trace(deque, isObservable, traceId);
}

@Override
Expand Down
29 changes: 26 additions & 3 deletions tracing/src/main/java/com/palantir/tracing/Tracer.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@
import static com.palantir.logsafe.Preconditions.checkNotNull;
import static com.palantir.logsafe.Preconditions.checkState;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.errorprone.annotations.CheckReturnValue;
import com.palantir.logsafe.SafeArg;
Expand DownExpand Up@@ -48,6 +49,16 @@ public final class Tracer {

private static final Logger log = LoggerFactory.getLogger(Tracer.class);

/**
* No-op span used internally to avoid allocating when trace is unobservable.
*/
private static final OpenSpan NOOP_SPAN = OpenSpan.builder()
.type(SpanType.LOCAL)
.operation("noop")
.parentSpanId(Optional.empty())
.spanId("noop")
.build();

private Tracer() {}

// Thread-safe since thread-local
Expand All@@ -68,7 +79,7 @@ private Tracer() {}
private static Trace createTrace(Observability observability, String traceId) {
checkArgument(!Strings.isNullOrEmpty(traceId), "traceId must be non-empty");
boolean observable = shouldObserve(observability);
return new Trace(observable, traceId);
return Trace.create(observable, traceId);
}

private static boolean shouldObserve(Observability observability) {
Expand All@@ -94,7 +105,6 @@ public static void initTrace(Optional<Boolean> isObservable, String traceId) {
Observability observability = isObservable
.map(value -> Boolean.TRUE.equals(value) ? Observability.SAMPLE : Observability.DO_NOT_SAMPLE)
.orElse(Observability.UNDECIDED);

setTrace(createTrace(observability, traceId));
}

Expand All@@ -111,6 +121,10 @@ public static void initTrace(Observability observability, String traceId) {
*/
public static OpenSpan startSpan(String operation, String parentSpanId, SpanType type) {
Trace current = getOrCreateCurrentTrace();
if (!current.isObservable()) {
return NOOP_SPAN;
}

checkState(current.isEmpty(),
"Cannot start a span with explicit parent if the current thread's trace is non-empty");
checkArgument(!Strings.isNullOrEmpty(parentSpanId), "parentSpanId must be non-empty");
Expand DownExpand Up@@ -139,12 +153,16 @@ public static OpenSpan startSpan(String operation) {
}

private static OpenSpan startSpanInternal(String operation, SpanType type) {
Trace trace = getOrCreateCurrentTrace();
if (!trace.isObservable()) {
return NOOP_SPAN;
}

OpenSpan.Builder spanBuilder = OpenSpan.builder()
.operation(operation)
.spanId(Tracers.randomId())
.type(type);

Trace trace = getOrCreateCurrentTrace();
Optional<OpenSpan> prevState = trace.top();
// Avoid lambda allocation in hot paths
if (prevState.isPresent()) {
Expand DownExpand Up@@ -304,6 +322,11 @@ public static void setSampler(TraceSampler sampler) {
Tracer.sampler = sampler;
}

@VisibleForTesting
static TraceSampler getSampler() {
return Tracer.sampler;
}

/** Returns true if there is an active trace on this thread. */
public static boolean hasTraceId() {
return currentTrace.get() != null;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' [improvement] Avoid trace ID and span allocations when not observing by schlosna · Pull Request #168 · palantir/tracing-java · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@
import static org.assertj.core.api.Assertions.assertThat;

import com.palantir.tracing.Tracer;
import com.palantir.tracing.api.Span;
import java.io.ByteArrayOutputStream;
import javax.ws.rs.core.StreamingOutput;
import org.junit.Test;
Expand All@@ -32,14 +33,16 @@ public void testWrappingStreamingOutput_streamingOutputTraceIsIsolated() throws
Tracer.startSpan("inside"); // never completed
});
streamingOutput.write(new ByteArrayOutputStream());
assertThat(Tracer.completeSpan().get().getOperation()).isEqualTo("outside");
Tracer.completeSpan().map(Span::getOperation)
.ifPresent(op -> assertThat(op).isEqualTo("outside"));
}

@Test
public void testWrappingStreamingOutput_traceStateIsCapturedAtConstructionTime() throws Exception {
Tracer.startSpan("before-construction");
StreamingOutput streamingOutput = JaxRsTracers.wrap(os -> {
assertThat(Tracer.completeSpan().get().getOperation()).isEqualTo("streaming-output");
Tracer.completeSpan().map(Span::getOperation)
.ifPresent(op -> assertThat(op).isEqualTo("streaming-output"));
});
Tracer.startSpan("after-construction");
streamingOutput.write(new ByteArrayOutputStream());
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -104,7 +104,7 @@ public <T, E extends Throwable> T withTrace(Tracers.ThrowingCallable<T, E> inner

Optional<Trace> originalTrace = Tracer.copyTrace();

Tracer.setTrace(new Trace(isObservable, traceId));
Tracer.setTrace(Trace.create(isObservable, traceId));
if (parentSpanId != null) {
Tracer.startSpan(operation, parentSpanId, SpanType.LOCAL);
} else {
Expand Down
232 changes: 232 additions & 0 deletions tracing/src/main/java/com/palantir/tracing/ImmutableEmptyDeque.java
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
/*
* (c) Copyright 2019 Palantir Technologies Inc. All rights reserved.
*
* 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.
*/

package com.palantir.tracing;

import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.Iterator;
import java.util.NoSuchElementException;

final class ImmutableEmptyDeque<E> implements Deque<E> {

private static final Object[] EMPTY_ARRAY = new Object[0];
private static final ImmutableEmptyDeque<?> EMPTY_DEQUE = new ImmutableEmptyDeque<>();

ImmutableEmptyDeque() {}

@SuppressWarnings("unchecked")
static <E> Deque<E> instance() {
return (Deque<E>) EMPTY_DEQUE;
}

private static UnsupportedOperationException cannotModify() {
return new UnsupportedOperationException("cannot modify immutable empty deque");
}

@Override
public boolean isEmpty() {
return true;
}

@Override
public int size() {
return 0;
}

@Override
public boolean equals(Object obj) {
return this == obj || this.getClass() == obj.getClass();
}

@Override
public int hashCode() {
return 0;
}

@Override
public String toString() {
return "[]";
}

@Override
public Iterator<E> iterator() {
return Collections.emptyIterator();
}

@Override
public Iterator<E> descendingIterator() {
return Collections.emptyIterator();
}

@Override
public Object[] toArray() {
return EMPTY_ARRAY;
}

@Override
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] array) {
return (T[]) EMPTY_ARRAY;
}

@Override
public boolean add(E element) {
throw cannotModify();
}

@Override
public boolean addAll(Collection<? extends E> collection) {
throw cannotModify();
}

@Override
public void addFirst(E element) {
throw cannotModify();
}

@Override
public void addLast(E element) {
throw cannotModify();
}

@Override
public void clear() {
throw cannotModify();
}

@Override
public boolean contains(Object obj) {
return false;
}

@Override
public boolean containsAll(Collection<?> collection) {
return false;
}

@Override
public E element() {
throw new NoSuchElementException();
}

@Override
public E getFirst() {
throw new NoSuchElementException();
}

@Override
public E getLast() {
throw new NoSuchElementException();
}

@Override
public boolean offer(E element) {
throw cannotModify();
}

@Override
public boolean offerFirst(E element) {
throw cannotModify();
}

@Override
public boolean offerLast(E element) {
throw cannotModify();
}

@Override
public E peek() {
return null;
}

@Override
public E peekFirst() {
return null;
}

@Override
public E peekLast() {
return null;
}

@Override
public E poll() {
return null;
}

@Override
public E pollFirst() {
return null;
}

@Override
public E pollLast() {
return null;
}

@Override
public E pop() {
throw cannotModify();
}

@Override
public void push(E element) {
throw cannotModify();
}

@Override
public E remove() {
throw cannotModify();
}

@Override
public boolean remove(Object obj) {
throw cannotModify();
}

@Override
public boolean removeAll(Collection<?> collection) {
throw cannotModify();
}

@Override
public E removeFirst() {
throw cannotModify();
}

@Override
public boolean removeFirstOccurrence(Object obj) {
throw cannotModify();
}

@Override
public E removeLast() {
throw cannotModify();
}

@Override
public boolean removeLastOccurrence(Object obj) {
throw cannotModify();
}

@Override
public boolean retainAll(Collection<?> collection) {
throw cannotModify();
}

}
14 changes: 9 additions & 5 deletions tracing/src/main/java/com/palantir/tracing/Trace.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,20 +34,23 @@ public final class Trace {
private final boolean isObservable;
private final String traceId;

private Trace(ArrayDeque<OpenSpan> stack, boolean isObservable, String traceId) {
private Trace(Deque<OpenSpan> stack, boolean isObservable, String traceId) {
checkArgument(!traceId.isEmpty(), "traceId must be non-empty");

this.stack = stack;
this.isObservable = isObservable;
this.traceId = traceId;
}

Trace(boolean isObservable, String traceId) {
this(new ArrayDeque<>(), isObservable, traceId);
static Trace create(boolean isObservable, String traceId) {
Deque<OpenSpan> deque = isObservable ? new ArrayDeque<>() : ImmutableEmptyDeque.instance();
return new Trace(deque, isObservable, traceId);
}

void push(OpenSpan span) {
stack.push(span);
if (isObservable) {
stack.push(span);
}
}

Optional<OpenSpan> top() {
Expand DownExpand Up@@ -79,7 +82,8 @@ String getTraceId() {

/** Returns a copy of this Trace which can be independently mutated. */
Trace deepCopy() {
return new Trace(new ArrayDeque<>(stack), isObservable, traceId);
Deque<OpenSpan> deque = isObservable ? new ArrayDeque<>(stack) : ImmutableEmptyDeque.instance();
return new Trace(deque, isObservable, traceId);
}

@Override
Expand Down
29 changes: 26 additions & 3 deletions tracing/src/main/java/com/palantir/tracing/Tracer.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@
import static com.palantir.logsafe.Preconditions.checkNotNull;
import static com.palantir.logsafe.Preconditions.checkState;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.errorprone.annotations.CheckReturnValue;
import com.palantir.logsafe.SafeArg;
Expand DownExpand Up@@ -48,6 +49,16 @@ public final class Tracer {

private static final Logger log = LoggerFactory.getLogger(Tracer.class);

/**
* No-op span used internally to avoid allocating when trace is unobservable.
*/
private static final OpenSpan NOOP_SPAN = OpenSpan.builder()
.type(SpanType.LOCAL)
.operation("noop")
.parentSpanId(Optional.empty())
.spanId("noop")
.build();

private Tracer() {}

// Thread-safe since thread-local
Expand All@@ -68,7 +79,7 @@ private Tracer() {}
private static Trace createTrace(Observability observability, String traceId) {
checkArgument(!Strings.isNullOrEmpty(traceId), "traceId must be non-empty");
boolean observable = shouldObserve(observability);
return new Trace(observable, traceId);
return Trace.create(observable, traceId);
}

private static boolean shouldObserve(Observability observability) {
Expand All@@ -94,7 +105,6 @@ public static void initTrace(Optional<Boolean> isObservable, String traceId) {
Observability observability = isObservable
.map(value -> Boolean.TRUE.equals(value) ? Observability.SAMPLE : Observability.DO_NOT_SAMPLE)
.orElse(Observability.UNDECIDED);

setTrace(createTrace(observability, traceId));
}

Expand All@@ -111,6 +121,10 @@ public static void initTrace(Observability observability, String traceId) {
*/
public static OpenSpan startSpan(String operation, String parentSpanId, SpanType type) {
Trace current = getOrCreateCurrentTrace();
if (!current.isObservable()) {
return NOOP_SPAN;
}

checkState(current.isEmpty(),
"Cannot start a span with explicit parent if the current thread's trace is non-empty");
checkArgument(!Strings.isNullOrEmpty(parentSpanId), "parentSpanId must be non-empty");
Expand DownExpand Up@@ -139,12 +153,16 @@ public static OpenSpan startSpan(String operation) {
}

private static OpenSpan startSpanInternal(String operation, SpanType type) {
Trace trace = getOrCreateCurrentTrace();
if (!trace.isObservable()) {
return NOOP_SPAN;
}

OpenSpan.Builder spanBuilder = OpenSpan.builder()
.operation(operation)
.spanId(Tracers.randomId())
.type(type);

Trace trace = getOrCreateCurrentTrace();
Optional<OpenSpan> prevState = trace.top();
// Avoid lambda allocation in hot paths
if (prevState.isPresent()) {
Expand DownExpand Up@@ -304,6 +322,11 @@ public static void setSampler(TraceSampler sampler) {
Tracer.sampler = sampler;
}

@VisibleForTesting
static TraceSampler getSampler() {
return Tracer.sampler;
}

/** Returns true if there is an active trace on this thread. */
public static boolean hasTraceId() {
return currentTrace.get() != null;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [improvement] Avoid trace ID and span allocations when not observing by schlosna · Pull Request #168 · palantir/tracing-java · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@
import static org.assertj.core.api.Assertions.assertThat;

import com.palantir.tracing.Tracer;
import com.palantir.tracing.api.Span;
import java.io.ByteArrayOutputStream;
import javax.ws.rs.core.StreamingOutput;
import org.junit.Test;
Expand All@@ -32,14 +33,16 @@ public void testWrappingStreamingOutput_streamingOutputTraceIsIsolated() throws
Tracer.startSpan("inside"); // never completed
});
streamingOutput.write(new ByteArrayOutputStream());
assertThat(Tracer.completeSpan().get().getOperation()).isEqualTo("outside");
Tracer.completeSpan().map(Span::getOperation)
.ifPresent(op -> assertThat(op).isEqualTo("outside"));
}

@Test
public void testWrappingStreamingOutput_traceStateIsCapturedAtConstructionTime() throws Exception {
Tracer.startSpan("before-construction");
StreamingOutput streamingOutput = JaxRsTracers.wrap(os -> {
assertThat(Tracer.completeSpan().get().getOperation()).isEqualTo("streaming-output");
Tracer.completeSpan().map(Span::getOperation)
.ifPresent(op -> assertThat(op).isEqualTo("streaming-output"));
});
Tracer.startSpan("after-construction");
streamingOutput.write(new ByteArrayOutputStream());
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -104,7 +104,7 @@ public <T, E extends Throwable> T withTrace(Tracers.ThrowingCallable<T, E> inner

Optional<Trace> originalTrace = Tracer.copyTrace();

Tracer.setTrace(new Trace(isObservable, traceId));
Tracer.setTrace(Trace.create(isObservable, traceId));
if (parentSpanId != null) {
Tracer.startSpan(operation, parentSpanId, SpanType.LOCAL);
} else {
Expand Down
232 changes: 232 additions & 0 deletions tracing/src/main/java/com/palantir/tracing/ImmutableEmptyDeque.java
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
/*
* (c) Copyright 2019 Palantir Technologies Inc. All rights reserved.
*
* 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.
*/

package com.palantir.tracing;

import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.Iterator;
import java.util.NoSuchElementException;

final class ImmutableEmptyDeque<E> implements Deque<E> {

private static final Object[] EMPTY_ARRAY = new Object[0];
private static final ImmutableEmptyDeque<?> EMPTY_DEQUE = new ImmutableEmptyDeque<>();

ImmutableEmptyDeque() {}

@SuppressWarnings("unchecked")
static <E> Deque<E> instance() {
return (Deque<E>) EMPTY_DEQUE;
}

private static UnsupportedOperationException cannotModify() {
return new UnsupportedOperationException("cannot modify immutable empty deque");
}

@Override
public boolean isEmpty() {
return true;
}

@Override
public int size() {
return 0;
}

@Override
public boolean equals(Object obj) {
return this == obj || this.getClass() == obj.getClass();
}

@Override
public int hashCode() {
return 0;
}

@Override
public String toString() {
return "[]";
}

@Override
public Iterator<E> iterator() {
return Collections.emptyIterator();
}

@Override
public Iterator<E> descendingIterator() {
return Collections.emptyIterator();
}

@Override
public Object[] toArray() {
return EMPTY_ARRAY;
}

@Override
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] array) {
return (T[]) EMPTY_ARRAY;
}

@Override
public boolean add(E element) {
throw cannotModify();
}

@Override
public boolean addAll(Collection<? extends E> collection) {
throw cannotModify();
}

@Override
public void addFirst(E element) {
throw cannotModify();
}

@Override
public void addLast(E element) {
throw cannotModify();
}

@Override
public void clear() {
throw cannotModify();
}

@Override
public boolean contains(Object obj) {
return false;
}

@Override
public boolean containsAll(Collection<?> collection) {
return false;
}

@Override
public E element() {
throw new NoSuchElementException();
}

@Override
public E getFirst() {
throw new NoSuchElementException();
}

@Override
public E getLast() {
throw new NoSuchElementException();
}

@Override
public boolean offer(E element) {
throw cannotModify();
}

@Override
public boolean offerFirst(E element) {
throw cannotModify();
}

@Override
public boolean offerLast(E element) {
throw cannotModify();
}

@Override
public E peek() {
return null;
}

@Override
public E peekFirst() {
return null;
}

@Override
public E peekLast() {
return null;
}

@Override
public E poll() {
return null;
}

@Override
public E pollFirst() {
return null;
}

@Override
public E pollLast() {
return null;
}

@Override
public E pop() {
throw cannotModify();
}

@Override
public void push(E element) {
throw cannotModify();
}

@Override
public E remove() {
throw cannotModify();
}

@Override
public boolean remove(Object obj) {
throw cannotModify();
}

@Override
public boolean removeAll(Collection<?> collection) {
throw cannotModify();
}

@Override
public E removeFirst() {
throw cannotModify();
}

@Override
public boolean removeFirstOccurrence(Object obj) {
throw cannotModify();
}

@Override
public E removeLast() {
throw cannotModify();
}

@Override
public boolean removeLastOccurrence(Object obj) {
throw cannotModify();
}

@Override
public boolean retainAll(Collection<?> collection) {
throw cannotModify();
}

}
14 changes: 9 additions & 5 deletions tracing/src/main/java/com/palantir/tracing/Trace.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,20 +34,23 @@ public final class Trace {
private final boolean isObservable;
private final String traceId;

private Trace(ArrayDeque<OpenSpan> stack, boolean isObservable, String traceId) {
private Trace(Deque<OpenSpan> stack, boolean isObservable, String traceId) {
checkArgument(!traceId.isEmpty(), "traceId must be non-empty");

this.stack = stack;
this.isObservable = isObservable;
this.traceId = traceId;
}

Trace(boolean isObservable, String traceId) {
this(new ArrayDeque<>(), isObservable, traceId);
static Trace create(boolean isObservable, String traceId) {
Deque<OpenSpan> deque = isObservable ? new ArrayDeque<>() : ImmutableEmptyDeque.instance();
return new Trace(deque, isObservable, traceId);
}

void push(OpenSpan span) {
stack.push(span);
if (isObservable) {
stack.push(span);
}
}

Optional<OpenSpan> top() {
Expand DownExpand Up@@ -79,7 +82,8 @@ String getTraceId() {

/** Returns a copy of this Trace which can be independently mutated. */
Trace deepCopy() {
return new Trace(new ArrayDeque<>(stack), isObservable, traceId);
Deque<OpenSpan> deque = isObservable ? new ArrayDeque<>(stack) : ImmutableEmptyDeque.instance();
return new Trace(deque, isObservable, traceId);
}

@Override
Expand Down
29 changes: 26 additions & 3 deletions tracing/src/main/java/com/palantir/tracing/Tracer.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@
import static com.palantir.logsafe.Preconditions.checkNotNull;
import static com.palantir.logsafe.Preconditions.checkState;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.errorprone.annotations.CheckReturnValue;
import com.palantir.logsafe.SafeArg;
Expand DownExpand Up@@ -48,6 +49,16 @@ public final class Tracer {

private static final Logger log = LoggerFactory.getLogger(Tracer.class);

/**
* No-op span used internally to avoid allocating when trace is unobservable.
*/
private static final OpenSpan NOOP_SPAN = OpenSpan.builder()
.type(SpanType.LOCAL)
.operation("noop")
.parentSpanId(Optional.empty())
.spanId("noop")
.build();

private Tracer() {}

// Thread-safe since thread-local
Expand All@@ -68,7 +79,7 @@ private Tracer() {}
private static Trace createTrace(Observability observability, String traceId) {
checkArgument(!Strings.isNullOrEmpty(traceId), "traceId must be non-empty");
boolean observable = shouldObserve(observability);
return new Trace(observable, traceId);
return Trace.create(observable, traceId);
}

private static boolean shouldObserve(Observability observability) {
Expand All@@ -94,7 +105,6 @@ public static void initTrace(Optional<Boolean> isObservable, String traceId) {
Observability observability = isObservable
.map(value -> Boolean.TRUE.equals(value) ? Observability.SAMPLE : Observability.DO_NOT_SAMPLE)
.orElse(Observability.UNDECIDED);

setTrace(createTrace(observability, traceId));
}

Expand All@@ -111,6 +121,10 @@ public static void initTrace(Observability observability, String traceId) {
*/
public static OpenSpan startSpan(String operation, String parentSpanId, SpanType type) {
Trace current = getOrCreateCurrentTrace();
if (!current.isObservable()) {
return NOOP_SPAN;
}

checkState(current.isEmpty(),
"Cannot start a span with explicit parent if the current thread's trace is non-empty");
checkArgument(!Strings.isNullOrEmpty(parentSpanId), "parentSpanId must be non-empty");
Expand DownExpand Up@@ -139,12 +153,16 @@ public static OpenSpan startSpan(String operation) {
}

private static OpenSpan startSpanInternal(String operation, SpanType type) {
Trace trace = getOrCreateCurrentTrace();
if (!trace.isObservable()) {
return NOOP_SPAN;
}

OpenSpan.Builder spanBuilder = OpenSpan.builder()
.operation(operation)
.spanId(Tracers.randomId())
.type(type);

Trace trace = getOrCreateCurrentTrace();
Optional<OpenSpan> prevState = trace.top();
// Avoid lambda allocation in hot paths
if (prevState.isPresent()) {
Expand DownExpand Up@@ -304,6 +322,11 @@ public static void setSampler(TraceSampler sampler) {
Tracer.sampler = sampler;
}

@VisibleForTesting
static TraceSampler getSampler() {
return Tracer.sampler;
}

/** Returns true if there is an active trace on this thread. */
public static boolean hasTraceId() {
return currentTrace.get() != null;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [improvement] Avoid trace ID and span allocations when not observing by schlosna · Pull Request #168 · palantir/tracing-java · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@
import static org.assertj.core.api.Assertions.assertThat;

import com.palantir.tracing.Tracer;
import com.palantir.tracing.api.Span;
import java.io.ByteArrayOutputStream;
import javax.ws.rs.core.StreamingOutput;
import org.junit.Test;
Expand All@@ -32,14 +33,16 @@ public void testWrappingStreamingOutput_streamingOutputTraceIsIsolated() throws
Tracer.startSpan("inside"); // never completed
});
streamingOutput.write(new ByteArrayOutputStream());
assertThat(Tracer.completeSpan().get().getOperation()).isEqualTo("outside");
Tracer.completeSpan().map(Span::getOperation)
.ifPresent(op -> assertThat(op).isEqualTo("outside"));
}

@Test
public void testWrappingStreamingOutput_traceStateIsCapturedAtConstructionTime() throws Exception {
Tracer.startSpan("before-construction");
StreamingOutput streamingOutput = JaxRsTracers.wrap(os -> {
assertThat(Tracer.completeSpan().get().getOperation()).isEqualTo("streaming-output");
Tracer.completeSpan().map(Span::getOperation)
.ifPresent(op -> assertThat(op).isEqualTo("streaming-output"));
});
Tracer.startSpan("after-construction");
streamingOutput.write(new ByteArrayOutputStream());
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -104,7 +104,7 @@ public <T, E extends Throwable> T withTrace(Tracers.ThrowingCallable<T, E> inner

Optional<Trace> originalTrace = Tracer.copyTrace();

Tracer.setTrace(new Trace(isObservable, traceId));
Tracer.setTrace(Trace.create(isObservable, traceId));
if (parentSpanId != null) {
Tracer.startSpan(operation, parentSpanId, SpanType.LOCAL);
} else {
Expand Down
232 changes: 232 additions & 0 deletions tracing/src/main/java/com/palantir/tracing/ImmutableEmptyDeque.java
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
/*
* (c) Copyright 2019 Palantir Technologies Inc. All rights reserved.
*
* 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.
*/

package com.palantir.tracing;

import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.Iterator;
import java.util.NoSuchElementException;

final class ImmutableEmptyDeque<E> implements Deque<E> {

private static final Object[] EMPTY_ARRAY = new Object[0];
private static final ImmutableEmptyDeque<?> EMPTY_DEQUE = new ImmutableEmptyDeque<>();

ImmutableEmptyDeque() {}

@SuppressWarnings("unchecked")
static <E> Deque<E> instance() {
return (Deque<E>) EMPTY_DEQUE;
}

private static UnsupportedOperationException cannotModify() {
return new UnsupportedOperationException("cannot modify immutable empty deque");
}

@Override
public boolean isEmpty() {
return true;
}

@Override
public int size() {
return 0;
}

@Override
public boolean equals(Object obj) {
return this == obj || this.getClass() == obj.getClass();
}

@Override
public int hashCode() {
return 0;
}

@Override
public String toString() {
return "[]";
}

@Override
public Iterator<E> iterator() {
return Collections.emptyIterator();
}

@Override
public Iterator<E> descendingIterator() {
return Collections.emptyIterator();
}

@Override
public Object[] toArray() {
return EMPTY_ARRAY;
}

@Override
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] array) {
return (T[]) EMPTY_ARRAY;
}

@Override
public boolean add(E element) {
throw cannotModify();
}

@Override
public boolean addAll(Collection<? extends E> collection) {
throw cannotModify();
}

@Override
public void addFirst(E element) {
throw cannotModify();
}

@Override
public void addLast(E element) {
throw cannotModify();
}

@Override
public void clear() {
throw cannotModify();
}

@Override
public boolean contains(Object obj) {
return false;
}

@Override
public boolean containsAll(Collection<?> collection) {
return false;
}

@Override
public E element() {
throw new NoSuchElementException();
}

@Override
public E getFirst() {
throw new NoSuchElementException();
}

@Override
public E getLast() {
throw new NoSuchElementException();
}

@Override
public boolean offer(E element) {
throw cannotModify();
}

@Override
public boolean offerFirst(E element) {
throw cannotModify();
}

@Override
public boolean offerLast(E element) {
throw cannotModify();
}

@Override
public E peek() {
return null;
}

@Override
public E peekFirst() {
return null;
}

@Override
public E peekLast() {
return null;
}

@Override
public E poll() {
return null;
}

@Override
public E pollFirst() {
return null;
}

@Override
public E pollLast() {
return null;
}

@Override
public E pop() {
throw cannotModify();
}

@Override
public void push(E element) {
throw cannotModify();
}

@Override
public E remove() {
throw cannotModify();
}

@Override
public boolean remove(Object obj) {
throw cannotModify();
}

@Override
public boolean removeAll(Collection<?> collection) {
throw cannotModify();
}

@Override
public E removeFirst() {
throw cannotModify();
}

@Override
public boolean removeFirstOccurrence(Object obj) {
throw cannotModify();
}

@Override
public E removeLast() {
throw cannotModify();
}

@Override
public boolean removeLastOccurrence(Object obj) {
throw cannotModify();
}

@Override
public boolean retainAll(Collection<?> collection) {
throw cannotModify();
}

}
14 changes: 9 additions & 5 deletions tracing/src/main/java/com/palantir/tracing/Trace.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,20 +34,23 @@ public final class Trace {
private final boolean isObservable;
private final String traceId;

private Trace(ArrayDeque<OpenSpan> stack, boolean isObservable, String traceId) {
private Trace(Deque<OpenSpan> stack, boolean isObservable, String traceId) {
checkArgument(!traceId.isEmpty(), "traceId must be non-empty");

this.stack = stack;
this.isObservable = isObservable;
this.traceId = traceId;
}

Trace(boolean isObservable, String traceId) {
this(new ArrayDeque<>(), isObservable, traceId);
static Trace create(boolean isObservable, String traceId) {
Deque<OpenSpan> deque = isObservable ? new ArrayDeque<>() : ImmutableEmptyDeque.instance();
return new Trace(deque, isObservable, traceId);
}

void push(OpenSpan span) {
stack.push(span);
if (isObservable) {
stack.push(span);
}
}

Optional<OpenSpan> top() {
Expand DownExpand Up@@ -79,7 +82,8 @@ String getTraceId() {

/** Returns a copy of this Trace which can be independently mutated. */
Trace deepCopy() {
return new Trace(new ArrayDeque<>(stack), isObservable, traceId);
Deque<OpenSpan> deque = isObservable ? new ArrayDeque<>(stack) : ImmutableEmptyDeque.instance();
return new Trace(deque, isObservable, traceId);
}

@Override
Expand Down
29 changes: 26 additions & 3 deletions tracing/src/main/java/com/palantir/tracing/Tracer.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@
import static com.palantir.logsafe.Preconditions.checkNotNull;
import static com.palantir.logsafe.Preconditions.checkState;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.errorprone.annotations.CheckReturnValue;
import com.palantir.logsafe.SafeArg;
Expand DownExpand Up@@ -48,6 +49,16 @@ public final class Tracer {

private static final Logger log = LoggerFactory.getLogger(Tracer.class);

/**
* No-op span used internally to avoid allocating when trace is unobservable.
*/
private static final OpenSpan NOOP_SPAN = OpenSpan.builder()
.type(SpanType.LOCAL)
.operation("noop")
.parentSpanId(Optional.empty())
.spanId("noop")
.build();

private Tracer() {}

// Thread-safe since thread-local
Expand All@@ -68,7 +79,7 @@ private Tracer() {}
private static Trace createTrace(Observability observability, String traceId) {
checkArgument(!Strings.isNullOrEmpty(traceId), "traceId must be non-empty");
boolean observable = shouldObserve(observability);
return new Trace(observable, traceId);
return Trace.create(observable, traceId);
}

private static boolean shouldObserve(Observability observability) {
Expand All@@ -94,7 +105,6 @@ public static void initTrace(Optional<Boolean> isObservable, String traceId) {
Observability observability = isObservable
.map(value -> Boolean.TRUE.equals(value) ? Observability.SAMPLE : Observability.DO_NOT_SAMPLE)
.orElse(Observability.UNDECIDED);

setTrace(createTrace(observability, traceId));
}

Expand All@@ -111,6 +121,10 @@ public static void initTrace(Observability observability, String traceId) {
*/
public static OpenSpan startSpan(String operation, String parentSpanId, SpanType type) {
Trace current = getOrCreateCurrentTrace();
if (!current.isObservable()) {
return NOOP_SPAN;
}

checkState(current.isEmpty(),
"Cannot start a span with explicit parent if the current thread's trace is non-empty");
checkArgument(!Strings.isNullOrEmpty(parentSpanId), "parentSpanId must be non-empty");
Expand DownExpand Up@@ -139,12 +153,16 @@ public static OpenSpan startSpan(String operation) {
}

private static OpenSpan startSpanInternal(String operation, SpanType type) {
Trace trace = getOrCreateCurrentTrace();
if (!trace.isObservable()) {
return NOOP_SPAN;
}

OpenSpan.Builder spanBuilder = OpenSpan.builder()
.operation(operation)
.spanId(Tracers.randomId())
.type(type);

Trace trace = getOrCreateCurrentTrace();
Optional<OpenSpan> prevState = trace.top();
// Avoid lambda allocation in hot paths
if (prevState.isPresent()) {
Expand DownExpand Up@@ -304,6 +322,11 @@ public static void setSampler(TraceSampler sampler) {
Tracer.sampler = sampler;
}

@VisibleForTesting
static TraceSampler getSampler() {
return Tracer.sampler;
}

/** Returns true if there is an active trace on this thread. */
public static boolean hasTraceId() {
return currentTrace.get() != null;
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); [improvement] Avoid trace ID and span allocations when not observing by schlosna · Pull Request #168 · palantir/tracing-java · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@
import static org.assertj.core.api.Assertions.assertThat;

import com.palantir.tracing.Tracer;
import com.palantir.tracing.api.Span;
import java.io.ByteArrayOutputStream;
import javax.ws.rs.core.StreamingOutput;
import org.junit.Test;
Expand All@@ -32,14 +33,16 @@ public void testWrappingStreamingOutput_streamingOutputTraceIsIsolated() throws
Tracer.startSpan("inside"); // never completed
});
streamingOutput.write(new ByteArrayOutputStream());
assertThat(Tracer.completeSpan().get().getOperation()).isEqualTo("outside");
Tracer.completeSpan().map(Span::getOperation)
.ifPresent(op -> assertThat(op).isEqualTo("outside"));
}

@Test
public void testWrappingStreamingOutput_traceStateIsCapturedAtConstructionTime() throws Exception {
Tracer.startSpan("before-construction");
StreamingOutput streamingOutput = JaxRsTracers.wrap(os -> {
assertThat(Tracer.completeSpan().get().getOperation()).isEqualTo("streaming-output");
Tracer.completeSpan().map(Span::getOperation)
.ifPresent(op -> assertThat(op).isEqualTo("streaming-output"));
});
Tracer.startSpan("after-construction");
streamingOutput.write(new ByteArrayOutputStream());
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -104,7 +104,7 @@ public <T, E extends Throwable> T withTrace(Tracers.ThrowingCallable<T, E> inner

Optional<Trace> originalTrace = Tracer.copyTrace();

Tracer.setTrace(new Trace(isObservable, traceId));
Tracer.setTrace(Trace.create(isObservable, traceId));
if (parentSpanId != null) {
Tracer.startSpan(operation, parentSpanId, SpanType.LOCAL);
} else {
Expand Down
232 changes: 232 additions & 0 deletions tracing/src/main/java/com/palantir/tracing/ImmutableEmptyDeque.java
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
/*
* (c) Copyright 2019 Palantir Technologies Inc. All rights reserved.
*
* 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.
*/

package com.palantir.tracing;

import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.Iterator;
import java.util.NoSuchElementException;

final class ImmutableEmptyDeque<E> implements Deque<E> {

private static final Object[] EMPTY_ARRAY = new Object[0];
private static final ImmutableEmptyDeque<?> EMPTY_DEQUE = new ImmutableEmptyDeque<>();

ImmutableEmptyDeque() {}

@SuppressWarnings("unchecked")
static <E> Deque<E> instance() {
return (Deque<E>) EMPTY_DEQUE;
}

private static UnsupportedOperationException cannotModify() {
return new UnsupportedOperationException("cannot modify immutable empty deque");
}

@Override
public boolean isEmpty() {
return true;
}

@Override
public int size() {
return 0;
}

@Override
public boolean equals(Object obj) {
return this == obj || this.getClass() == obj.getClass();
}

@Override
public int hashCode() {
return 0;
}

@Override
public String toString() {
return "[]";
}

@Override
public Iterator<E> iterator() {
return Collections.emptyIterator();
}

@Override
public Iterator<E> descendingIterator() {
return Collections.emptyIterator();
}

@Override
public Object[] toArray() {
return EMPTY_ARRAY;
}

@Override
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] array) {
return (T[]) EMPTY_ARRAY;
}

@Override
public boolean add(E element) {
throw cannotModify();
}

@Override
public boolean addAll(Collection<? extends E> collection) {
throw cannotModify();
}

@Override
public void addFirst(E element) {
throw cannotModify();
}

@Override
public void addLast(E element) {
throw cannotModify();
}

@Override
public void clear() {
throw cannotModify();
}

@Override
public boolean contains(Object obj) {
return false;
}

@Override
public boolean containsAll(Collection<?> collection) {
return false;
}

@Override
public E element() {
throw new NoSuchElementException();
}

@Override
public E getFirst() {
throw new NoSuchElementException();
}

@Override
public E getLast() {
throw new NoSuchElementException();
}

@Override
public boolean offer(E element) {
throw cannotModify();
}

@Override
public boolean offerFirst(E element) {
throw cannotModify();
}

@Override
public boolean offerLast(E element) {
throw cannotModify();
}

@Override
public E peek() {
return null;
}

@Override
public E peekFirst() {
return null;
}

@Override
public E peekLast() {
return null;
}

@Override
public E poll() {
return null;
}

@Override
public E pollFirst() {
return null;
}

@Override
public E pollLast() {
return null;
}

@Override
public E pop() {
throw cannotModify();
}

@Override
public void push(E element) {
throw cannotModify();
}

@Override
public E remove() {
throw cannotModify();
}

@Override
public boolean remove(Object obj) {
throw cannotModify();
}

@Override
public boolean removeAll(Collection<?> collection) {
throw cannotModify();
}

@Override
public E removeFirst() {
throw cannotModify();
}

@Override
public boolean removeFirstOccurrence(Object obj) {
throw cannotModify();
}

@Override
public E removeLast() {
throw cannotModify();
}

@Override
public boolean removeLastOccurrence(Object obj) {
throw cannotModify();
}

@Override
public boolean retainAll(Collection<?> collection) {
throw cannotModify();
}

}
14 changes: 9 additions & 5 deletions tracing/src/main/java/com/palantir/tracing/Trace.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -34,20 +34,23 @@ public final class Trace {
private final boolean isObservable;
private final String traceId;

private Trace(ArrayDeque<OpenSpan> stack, boolean isObservable, String traceId) {
private Trace(Deque<OpenSpan> stack, boolean isObservable, String traceId) {
checkArgument(!traceId.isEmpty(), "traceId must be non-empty");

this.stack = stack;
this.isObservable = isObservable;
this.traceId = traceId;
}

Trace(boolean isObservable, String traceId) {
this(new ArrayDeque<>(), isObservable, traceId);
static Trace create(boolean isObservable, String traceId) {
Deque<OpenSpan> deque = isObservable ? new ArrayDeque<>() : ImmutableEmptyDeque.instance();
return new Trace(deque, isObservable, traceId);
}

void push(OpenSpan span) {
stack.push(span);
if (isObservable) {
stack.push(span);
}
}

Optional<OpenSpan> top() {
Expand DownExpand Up@@ -79,7 +82,8 @@ String getTraceId() {

/** Returns a copy of this Trace which can be independently mutated. */
Trace deepCopy() {
return new Trace(new ArrayDeque<>(stack), isObservable, traceId);
Deque<OpenSpan> deque = isObservable ? new ArrayDeque<>(stack) : ImmutableEmptyDeque.instance();
return new Trace(deque, isObservable, traceId);
}

@Override
Expand Down
29 changes: 26 additions & 3 deletions tracing/src/main/java/com/palantir/tracing/Tracer.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@
import static com.palantir.logsafe.Preconditions.checkNotNull;
import static com.palantir.logsafe.Preconditions.checkState;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.errorprone.annotations.CheckReturnValue;
import com.palantir.logsafe.SafeArg;
Expand DownExpand Up@@ -48,6 +49,16 @@ public final class Tracer {

private static final Logger log = LoggerFactory.getLogger(Tracer.class);

/**
* No-op span used internally to avoid allocating when trace is unobservable.
*/
private static final OpenSpan NOOP_SPAN = OpenSpan.builder()
.type(SpanType.LOCAL)
.operation("noop")
.parentSpanId(Optional.empty())
.spanId("noop")
.build();

private Tracer() {}

// Thread-safe since thread-local
Expand All@@ -68,7 +79,7 @@ private Tracer() {}
private static Trace createTrace(Observability observability, String traceId) {
checkArgument(!Strings.isNullOrEmpty(traceId), "traceId must be non-empty");
boolean observable = shouldObserve(observability);
return new Trace(observable, traceId);
return Trace.create(observable, traceId);
}

private static boolean shouldObserve(Observability observability) {
Expand All@@ -94,7 +105,6 @@ public static void initTrace(Optional<Boolean> isObservable, String traceId) {
Observability observability = isObservable
.map(value -> Boolean.TRUE.equals(value) ? Observability.SAMPLE : Observability.DO_NOT_SAMPLE)
.orElse(Observability.UNDECIDED);

setTrace(createTrace(observability, traceId));
}

Expand All@@ -111,6 +121,10 @@ public static void initTrace(Observability observability, String traceId) {
*/
public static OpenSpan startSpan(String operation, String parentSpanId, SpanType type) {
Trace current = getOrCreateCurrentTrace();
if (!current.isObservable()) {
return NOOP_SPAN;
}

checkState(current.isEmpty(),
"Cannot start a span with explicit parent if the current thread's trace is non-empty");
checkArgument(!Strings.isNullOrEmpty(parentSpanId), "parentSpanId must be non-empty");
Expand DownExpand Up@@ -139,12 +153,16 @@ public static OpenSpan startSpan(String operation) {
}

private static OpenSpan startSpanInternal(String operation, SpanType type) {
Trace trace = getOrCreateCurrentTrace();
if (!trace.isObservable()) {
return NOOP_SPAN;
}

OpenSpan.Builder spanBuilder = OpenSpan.builder()
.operation(operation)
.spanId(Tracers.randomId())
.type(type);

Trace trace = getOrCreateCurrentTrace();
Optional<OpenSpan> prevState = trace.top();
// Avoid lambda allocation in hot paths
if (prevState.isPresent()) {
Expand DownExpand Up@@ -304,6 +322,11 @@ public static void setSampler(TraceSampler sampler) {
Tracer.sampler = sampler;
}

@VisibleForTesting
static TraceSampler getSampler() {
return Tracer.sampler;
}

/** Returns true if there is an active trace on this thread. */
public static boolean hasTraceId() {
return currentTrace.get() != null;
Expand Down
Loading