b3-format.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. "use strict";
  2. /**
  3. * Copyright 2018, OpenCensus Authors
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. Object.defineProperty(exports, "__esModule", { value: true });
  18. const crypto = require("crypto");
  19. const uuid = require("uuid");
  20. const X_B3_TRACE_ID = 'x-b3-traceid';
  21. const X_B3_SPAN_ID = 'x-b3-spanid';
  22. const X_B3_PARENT_SPAN_ID = 'x-x3-parentspanid';
  23. const X_B3_SAMPLED = 'x-b3-sampled';
  24. const SAMPLED_VALUE = 0x1;
  25. const NOT_SAMPLED_VALUE = 0x0;
  26. /** Propagates span context through B3 Format propagation. */
  27. class B3Format {
  28. /**
  29. * Gets the trace context from a request headers. If there is no trace context
  30. * in the headers, null is returned.
  31. * @param getter
  32. */
  33. extract(getter) {
  34. if (getter) {
  35. let opt = getter.getHeader(X_B3_SAMPLED);
  36. if (opt instanceof Array) {
  37. opt = opt[0];
  38. }
  39. const spanContext = {
  40. traceId: getter.getHeader(X_B3_TRACE_ID),
  41. spanId: getter.getHeader(X_B3_SPAN_ID),
  42. options: isNaN(Number(opt)) ? undefined : Number(opt)
  43. };
  44. return spanContext;
  45. }
  46. return null;
  47. }
  48. /**
  49. * Adds a trace context in a request headers.
  50. * @param setter
  51. * @param spanContext
  52. */
  53. inject(setter, spanContext) {
  54. if (setter) {
  55. setter.setHeader(X_B3_TRACE_ID, spanContext.traceId || 'undefined');
  56. setter.setHeader(X_B3_SPAN_ID, spanContext.spanId || 'undefined');
  57. if (spanContext && (spanContext.options & SAMPLED_VALUE) !== 0) {
  58. setter.setHeader(X_B3_SAMPLED, `${SAMPLED_VALUE}`);
  59. }
  60. else {
  61. setter.setHeader(X_B3_SAMPLED, `${NOT_SAMPLED_VALUE}`);
  62. }
  63. }
  64. }
  65. /**
  66. * Generate SpanContexts
  67. */
  68. generate() {
  69. return {
  70. traceId: uuid.v4().split('-').join(''),
  71. spanId: crypto.randomBytes(8).toString('hex'),
  72. options: SAMPLED_VALUE
  73. };
  74. }
  75. }
  76. exports.B3Format = B3Format;
  77. //# sourceMappingURL=b3-format.js.map