census-instrumentation / opencensus-java

A stats collection and distributed tracing framework
https://opencensus.io
Apache License 2.0
673 stars 202 forks source link

Use JAX-RS ContextResolver mechanism for TextFormat resolution #1831

Open dansiviter opened 5 years ago

dansiviter commented 5 years ago

Currently it requires manual registration for JaxrsContainerFilter to use different TextFormat implementations such as B3 Propagation. Using the javax.ws.rs.ext.ContextResolver mechanism might be better suited for this. Due to the way JaxrsContainerFilter it would require a delgated version of TextFormat unless is was restructured to use @PostConstruct:

@Context
private Providers providers;

private class DelegatedTextFormat extends TextFormat {
  private TextFormat delegate() {
    final ContextResolver<TextFormat> format = providers.getContextResolver(TextFormat.class, null);
    if (format != null) {
      return format.getContext(TextFormat.class);
    }
    return  getPropagationComponent().getTraceContextFormat();
  }

  @Override
  public List<String> fields() {
    return delegate().fields();
  }

  @Override
  public <C> void inject(SpanContext spanContext, C carrier, Setter<C> setter) {
    delegate().inject(spanContext, carrier, setter);
  }

  @Override
  public <C> SpanContext extract(C carrier, Getter<C> getter) throws SpanContextParseException {
    return delegate().extract(carrier, getter);
  }
}

Then we could simply use:

@Provider
public static class TextFormatResolver implements ContextResolver<TextFormat> {
  @Override
  public TextFormat getContext(Class<?> type) {
    return getPropagationComponent().getB3Format();
  }
}

Happy to have a go at the changes when I get some time if agreed that this is the way to go.

dansiviter commented 5 years ago

Just thought that this should also be the case for JaxrsClientFilter too.