Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add propagation interface #510

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Changes from 5 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 number Diff line number Diff line change
@@ -1,4 +1,4 @@
const {Request, Annotation} = require('zipkin');
const {Annotation} = require('zipkin');
const url = require('url');

function getPathnameFromPath(path) {
@@ -18,7 +18,7 @@ class ExpressHttpProxyInstrumentation {
const clientTraceId = this.tracer.createChildId();
this.tracer.setId(clientTraceId);

const proxyReqWithZipkinHeaders = Request.addZipkinHeaders(proxyReq, clientTraceId);
const proxyReqWithZipkinHeaders = this.tracer.injector(proxyReq);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd rather pass the clientTraceId explicitly instead of having the injector to know about the scope.

Object.defineProperty(serverReq, '_trace_id_proxy',
{configurable: false, get: () => clientTraceId});

Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
const {Request} = require('zipkin');
const {
recordConsumeStop, recordConsumeStart,
recordProducerStart, recordProducerStop
@@ -49,7 +48,7 @@ const instrumentKafkaJs = (kafkaJs, {tracer, remoteServiceName}) => {
id = recordProducerStart(tracer, 'send', remoteServiceName, {topic: params.topic});

const withTraceHeaders = Object.assign({}, params, {
messages: params.messages.map(msg => Request.addZipkinHeaders(msg, id))
messages: params.messages.map(msg => tracer.injector(msg))
});

promise = obj[prop](withTraceHeaders);
29 changes: 19 additions & 10 deletions packages/zipkin/index.d.ts
Original file line number Diff line number Diff line change
@@ -39,7 +39,8 @@ declare namespace zipkin {
localServiceName?: string,
localEndpoint?: model.Endpoint,
log?: Console,
defaultTags?: {}
defaultTags?: {},
propagation?: propagation.Propagation
});

/** Returns the current trace ID or a sentinel value indicating its absence. */
@@ -61,6 +62,11 @@ declare namespace zipkin {
recordLocalAddr(inetAddress: InetAddress): void;
recordBinary(key: string, value: boolean | string | number): void;
writeIdToConsole(message: any): void;
/** Extract propagation ctx from request */
extractId(readHeader: <T> (header: string) => option.IOption<T>): void;
Copy link
Contributor

@jcchavezs jcchavezs Sep 17, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I'd prefer to have the extractId to be actually an extractor like the injector.

Also, maybe read header can be an abstract getter, not necessarily tight to http headers (e.g. in GRPC it is metadata)?

/** Injector propagation ctx from request */
injector(request: any): object;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

injector can be for messaging too so I think it is better that we pass something like readHeader and call it setter and this return an object that performs the injection, does that make sense?


}

class TraceId {
@@ -271,14 +277,6 @@ declare namespace zipkin {
toInt(): number;
}

namespace HttpHeaders {
const TraceId: string;
const SpanId: string;
const ParentSpanId: string;
const Sampled: string;
const Flags: string;
}

interface Record {
traceId: TraceId;
timestamp: number;
@@ -339,6 +337,7 @@ declare namespace zipkin {
}

namespace Instrumentation {

class HttpServer {
constructor(args: {
tracer: Tracer,
@@ -357,7 +356,7 @@ declare namespace zipkin {
}

class HttpClient {
constructor(args: { tracer: Tracer, serviceName?: string, remoteServiceName?: string });
constructor(args: { tracer: Tracer, serviceName?: string, remoteServiceName?: string});

recordRequest<T>(
request: T,
@@ -368,6 +367,16 @@ declare namespace zipkin {
recordError(traceId: TraceId, error: Error): void;
}
}
namespace propagation {
interface Propagation {
extractor<T>(tracer: Tracer, readHeader: <T> (header: string) => option.IOption<T>): TraceId;
Copy link
Contributor

@jcchavezs jcchavezs Sep 17, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I understand correctly, we pass the tracer to the extractor? is this really needed?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In new tracing models we have propagation decoupled from tracer, I think we should follow similar pattern here.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

agree we should not couple these

injector<T, H>(req: T & { headers?: any }, traceId: TraceId): object;
}
class B3Propagation implements Propagation {
extractor<T>(tracer: Tracer, readHeader: <T> (header: string) => option.IOption<T>): TraceId;
injector<T, H>(req: T & { headers?: any }, traceId: TraceId): object;
}
}
}

export = zipkin;
7 changes: 0 additions & 7 deletions packages/zipkin/src/httpHeaders.js

This file was deleted.

3 changes: 1 addition & 2 deletions packages/zipkin/src/index.ts
Original file line number Diff line number Diff line change
@@ -7,7 +7,6 @@ export { default as randomTraceId } from './tracer/randomTraceId';
export { default as sampler } from './tracer/sampler';
export { default as TraceId } from './tracer/TraceId';

export { default as HttpHeaders } from './httpHeaders';
export { default as InetAddress } from './InetAddress';

export { default as BatchRecorder } from './batch-recorder';
@@ -16,7 +15,7 @@ export { default as ConsoleRecorder } from './console-recorder';
export { default as ExplicitContext } from './explicit-context';

export { default as Instrumentation } from './instrumentation';
export { default as Request } from './request';
export { default as B3Propagation } from './propagation/b3propagation';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

<3


export { default as jsonEncoder } from './jsonEncoder';
export { default as model } from './model';
5 changes: 1 addition & 4 deletions packages/zipkin/src/instrumentation/httpClient.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
const Annotation = require('../annotation');
const Request = require('../request');
const parseRequestUrl = require('../parseUrl');

function requiredArg(name) {
@@ -19,7 +18,6 @@ class HttpClientInstrumentation {

recordRequest(request, url, method) {
this.tracer.setId(this.tracer.createChildId());
const traceId = this.tracer.id;
const {path} = parseRequestUrl(url);

this.tracer.recordServiceName(this.serviceName);
@@ -33,8 +31,7 @@ class HttpClientInstrumentation {
serviceName: this.remoteServiceName
}));
}

return Request.addZipkinHeaders(request, traceId);
return this.tracer.injector(request);
}

recordResponse(traceId, statusCode) {
49 changes: 1 addition & 48 deletions packages/zipkin/src/instrumentation/httpServer.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,6 @@
const Annotation = require('../annotation');
const Header = require('../httpHeaders');
const InetAddress = require('../InetAddress');
const TraceId = require('../tracer/TraceId');
const parseRequestUrl = require('../parseUrl');
const {Some, None} = require('../option');

function stringToBoolean(str) {
return str === '1' || str === 'true';
}

function stringToIntOption(str) {
try {
return new Some(parseInt(str));
} catch (err) {
return None;
}
}

function containsRequiredHeaders(readHeader) {
return readHeader(Header.TraceId) !== None && readHeader(Header.SpanId) !== None;
}

function requiredArg(name) {
throw new Error(`HttpServerInstrumentation: Missing required argument ${name}.`);
@@ -38,34 +19,6 @@ class HttpServerInstrumentation {
this.port = port;
}

_createIdFromHeaders(readHeader) {
if (containsRequiredHeaders(readHeader)) {
const spanId = readHeader(Header.SpanId);
const parentId = spanId.map((sid) => {
const traceId = readHeader(Header.TraceId);
const parentSpanId = readHeader(Header.ParentSpanId);
const sampled = readHeader(Header.Sampled);
const flags = readHeader(Header.Flags).flatMap(stringToIntOption).getOrElse(0);
return new TraceId({
traceId: traceId.getOrElse(),
parentId: parentSpanId,
spanId: sid,
debug: flags === 1,
sampled: sampled.map(stringToBoolean),
});
});

return new Some(this.tracer.join(parentId.getOrElse()));
} else if (readHeader(Header.Flags) !== None || readHeader(Header.Sampled) !== None) {
const sampled = readHeader(Header.Sampled) === None
? None : readHeader(Header.Sampled).map(stringToBoolean);
const flags = readHeader(Header.Flags).flatMap(stringToIntOption).getOrElse(0);
return new Some(this.tracer.createRootId(sampled, flags === 1));
} else {
return new Some(this.tracer.createRootId());
}
}

spanNameFromRoute(method, route, code) { // eslint-disable-line class-methods-use-this
if (code > 299 && code < 400) return `${method} redirected`;
if (code === 404) return `${method} not_found`;
@@ -74,7 +27,7 @@ class HttpServerInstrumentation {
}

recordRequest(method, requestUrl, readHeader) {
this._createIdFromHeaders(readHeader).ifPresent(id => this.tracer.setId(id));
this.tracer.extractId(readHeader);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am really happy this becomes so simple now.

const {id} = this.tracer;
const {path} = parseRequestUrl(requestUrl);

75 changes: 75 additions & 0 deletions packages/zipkin/src/propagation/b3propagation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
const {Some, None} = require('../option');
const TraceId = require('../tracer/TraceId');

function stringToBoolean(str) {
return str === '1' || str === 'true';
}

function stringToIntOption(str) {
try {
return new Some(parseInt(str));
} catch (err) {
return None;
}
}

class B3Propagation {
constructor() {
this.headers = {
TraceId: 'X-B3-TraceId',
SpanId: 'X-B3-SpanId',
ParentSpanId: 'X-B3-ParentSpanId',
Sampled: 'X-B3-Sampled',
Flags: 'X-B3-Flags'
};
}

extractor(tracer, readHeader) {
if (readHeader(this.headers.TraceId) !== None && readHeader(this.headers.SpanId) !== None) {
const spanId = readHeader(this.headers.SpanId);
const parentId = spanId.map((sid) => {
const traceId = readHeader(this.headers.TraceId);
const parentSpanId = readHeader(this.headers.ParentSpanId);
const sampled = readHeader(this.headers.Sampled);
const flags = readHeader(this.headers.Flags).flatMap(stringToIntOption).getOrElse(0);
return new TraceId({
traceId: traceId.getOrElse(),
parentId: parentSpanId,
spanId: sid,
debug: flags === 1,
sampled: sampled.map(stringToBoolean),
});
});

return new Some(tracer.join(parentId.getOrElse()));
} else if (readHeader(this.headers.Flags) !== None
|| readHeader(this.headers.Sampled) !== None) {
const sampled = readHeader(this.headers.Sampled) === None
? None : readHeader(this.headers.Sampled).map(stringToBoolean);
const flags = readHeader(this.headers.Flags).flatMap(stringToIntOption).getOrElse(0);
return new Some(tracer.createRootId(sampled, flags === 1));
} else {
return new Some(tracer.createRootId());
}
}

injector(request, traceId) {
const headers = request.headers || {};
headers[this.headers.TraceId] = traceId.traceId;
headers[this.headers.SpanId] = traceId.spanId;

traceId.parentSpanId.ifPresent((psid) => {
headers[this.headers.ParentSpanId] = psid;
});
traceId.sampled.ifPresent((sampled) => {
headers[this.headers.Sampled] = sampled ? '1' : '0';
});

if (traceId.isDebug()) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In here, if `traceId.isDebug()) then you don't need to pass sampling.

headers[this.headers.Flags] = '1';
}
return headers;
}
}

module.exports = B3Propagation;
5 changes: 5 additions & 0 deletions packages/zipkin/src/propagation/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const B3Propagation = require('./b3propagation');

module.exports = {
B3Propagation
};
29 changes: 0 additions & 29 deletions packages/zipkin/src/request.js

This file was deleted.

15 changes: 14 additions & 1 deletion packages/zipkin/src/tracer/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

const isPromise = require('is-promise');
const {None, Some} = require('../option');
const {Sampler, alwaysSample} = require('./sampler');
@@ -8,6 +9,7 @@ const TraceId = require('./TraceId');
const randomTraceId = require('./randomTraceId');
const {now, hrtime} = require('../time');
const {Endpoint} = require('../model');
const {B3Propagation} = require('../propagation');


function requiredArg(name) {
@@ -37,13 +39,15 @@ class Tracer {
localEndpoint,
/* eslint-disable no-console */
log = console,
defaultTags
defaultTags,
propagation = new B3Propagation()
}) {
this.log = log;
this.recorder = recorder;
this.sampler = sampler;
this.traceId128Bit = traceId128Bit;
this.supportsJoin = supportsJoin;
this._propagation = propagation;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't know if a better approach is delete the extract and injector methods and only add a get propagation, this simplify the grpc-client implementation, thats need to know the propagation headers....

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would go for that instead.

if (localEndpoint) {
this._localEndpoint = localEndpoint;
} else {
@@ -265,6 +269,15 @@ class Tracer {
}
}
}

extractId(readHeader) {
this._propagation.extractor(this, readHeader).ifPresent(id => this.setId(id));
}

injector(request) {
const headers = this._propagation.injector(request, this.id);
return Object.assign({}, request, {headers});
}
}

module.exports = Tracer;
41 changes: 0 additions & 41 deletions packages/zipkin/test/request.test.js

This file was deleted.