solarwinds-apm
Version:
OpenTelemetry-based SolarWinds APM library
91 lines (88 loc) • 3.03 kB
JavaScript
/*
Copyright 2023-2025 SolarWinds Worldwide, LLC.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import { createContextKey, diag, } from "@opentelemetry/api";
/**
* Creates a global value shared between ESM and CommonJS contexts
*
* @param id - Descriptive unique ID for the global
* @param init - Initializer for the global if it needs to be
*
* @returns Shared global
*/
export function global(id, init) {
const key = Symbol.for(`solarwinds-apm / ${id}`);
let storage = Reflect.get(globalThis, key);
if (!storage) {
storage = init();
Reflect.defineProperty(globalThis, key, {
value: storage,
configurable: false,
enumerable: false,
writable: false,
});
}
return storage;
}
const GLOBAL_SPAN_STORAGE = global("span storage", () => new WeakMap());
function withSdkSpan(span, fallback, f) {
if ("setAttribute" in span && "attributes" in span) {
return f(span);
}
else {
diag.debug("span storage passed an invalid key", span);
return fallback;
}
}
/** Creates a new {@link ContextStorage} for the given ID */
export function contextStorage(id) {
const key = createContextKey(id);
return {
get: (ctx) => ctx.getValue(key),
set: (ctx, val) => ctx.setValue(key, val),
delete: (ctx) => ctx.deleteValue(key),
};
}
/** Creates a new {@link SpanStorage} for the given ID */
export function spanStorage(id) {
const key = Symbol.for(id);
return {
get: (span) => withSdkSpan(span, undefined, (span) => {
return GLOBAL_SPAN_STORAGE.get(span)?.get(key);
}),
set: (span, val) => withSdkSpan(span, false, (span) => {
const storage = GLOBAL_SPAN_STORAGE.get(span) ?? new Map();
storage.set(key, val);
GLOBAL_SPAN_STORAGE.set(span, storage);
return true;
}),
delete: (span) => withSdkSpan(span, false, (span) => {
const storage = GLOBAL_SPAN_STORAGE.get(span);
if (!storage) {
return false;
}
const deleted = storage.delete(key);
if (storage.size === 0) {
GLOBAL_SPAN_STORAGE.delete(span);
}
return deleted;
}),
};
}
export function cellStorage(id) {
return global(id, () => {
let resolve;
const promise = new Promise((r) => (resolve = r));
return Object.assign(promise, { resolve });
});
}
//# sourceMappingURL=storage.js.map