context.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. /** Get a key to uniquely identify a context value */
  17. export function createContextKey(description) {
  18. // The specification states that for the same input, multiple calls should
  19. // return different keys. Due to the nature of the JS dependency management
  20. // system, this creates problems where multiple versions of some package
  21. // could hold different keys for the same property.
  22. //
  23. // Therefore, we use Symbol.for which returns the same key for the same input.
  24. return Symbol.for(description);
  25. }
  26. class BaseContext {
  27. /**
  28. * Construct a new context which inherits values from an optional parent context.
  29. *
  30. * @param parentContext a context from which to inherit values
  31. */
  32. constructor(parentContext) {
  33. // for minification
  34. const self = this;
  35. self._currentContext = parentContext ? new Map(parentContext) : new Map();
  36. self.getValue = (key) => self._currentContext.get(key);
  37. self.setValue = (key, value) => {
  38. const context = new BaseContext(self._currentContext);
  39. context._currentContext.set(key, value);
  40. return context;
  41. };
  42. self.deleteValue = (key) => {
  43. const context = new BaseContext(self._currentContext);
  44. context._currentContext.delete(key);
  45. return context;
  46. };
  47. }
  48. }
  49. /** The root context is used as the default parent context when there is no active context */
  50. export const ROOT_CONTEXT = new BaseContext();
  51. //# sourceMappingURL=context.js.map