context-utils.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright The OpenTelemetry Authors
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * https://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import { createContextKey } from '../context/context';
  17. import { NonRecordingSpan } from './NonRecordingSpan';
  18. import { ContextAPI } from '../api/context';
  19. /**
  20. * span key
  21. */
  22. const SPAN_KEY = createContextKey('OpenTelemetry Context Key SPAN');
  23. /**
  24. * Return the span if one exists
  25. *
  26. * @param context context to get span from
  27. */
  28. export function getSpan(context) {
  29. return context.getValue(SPAN_KEY) || undefined;
  30. }
  31. /**
  32. * Gets the span from the current context, if one exists.
  33. */
  34. export function getActiveSpan() {
  35. return getSpan(ContextAPI.getInstance().active());
  36. }
  37. /**
  38. * Set the span on a context
  39. *
  40. * @param context context to use as parent
  41. * @param span span to set active
  42. */
  43. export function setSpan(context, span) {
  44. return context.setValue(SPAN_KEY, span);
  45. }
  46. /**
  47. * Remove current span stored in the context
  48. *
  49. * @param context context to delete span from
  50. */
  51. export function deleteSpan(context) {
  52. return context.deleteValue(SPAN_KEY);
  53. }
  54. /**
  55. * Wrap span context in a NoopSpan and set as span in a new
  56. * context
  57. *
  58. * @param context context to set active span on
  59. * @param spanContext span context to be wrapped
  60. */
  61. export function setSpanContext(context, spanContext) {
  62. return setSpan(context, new NonRecordingSpan(spanContext));
  63. }
  64. /**
  65. * Get the span context of the span if it exists.
  66. *
  67. * @param context context to get values from
  68. */
  69. export function getSpanContext(context) {
  70. var _a;
  71. return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext();
  72. }
  73. //# sourceMappingURL=context-utils.js.map