-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
689be49
commit daed24a
Showing
3 changed files
with
75 additions
and
49 deletions.
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
import type { Logger } from '@graphql-mesh/types'; | ||
import { trace, type Context, type ContextManager } from '@opentelemetry/api'; | ||
import type { PromiseOrValue } from 'graphql-yoga'; | ||
|
||
type Node = { | ||
ctx: Context; | ||
previous?: Node; | ||
}; | ||
|
||
export class OtelContextStack { | ||
#root: Node; | ||
#current: Node; | ||
|
||
constructor(root: Context) { | ||
this.#root = { ctx: root }; | ||
this.#current = this.#root; | ||
} | ||
|
||
get current(): Context { | ||
return this.#current.ctx; | ||
} | ||
|
||
get root(): Context { | ||
return this.#root.ctx; | ||
} | ||
|
||
push = (ctx: Context) => { | ||
this.#current = { ctx, previous: this.#current }; | ||
}; | ||
|
||
pop = () => { | ||
this.#current = this.#current.previous ?? this.#root; | ||
}; | ||
|
||
toString() { | ||
let node: Node | undefined = this.#current; | ||
const names = []; | ||
while (node != undefined) { | ||
names.push((trace.getSpan(node.ctx) as unknown as { name: string }).name); | ||
node = node.previous; | ||
} | ||
return names.join(' -> '); | ||
} | ||
} | ||
|
||
export function getContextManager( | ||
logger: Logger, | ||
useContextManager: boolean, | ||
contextManager?: false | ContextManager, | ||
): PromiseOrValue<ContextManager | false | undefined> { | ||
if (contextManager != undefined) { | ||
return contextManager; | ||
} | ||
|
||
return import('@opentelemetry/context-async-hooks') | ||
.then((module) => new module.AsyncLocalStorageContextManager()) | ||
.catch((err) => { | ||
if ((err as any).code === 'ERR_MODULE_NOT_FOUND') { | ||
if (useContextManager) { | ||
logger.error( | ||
"AsyncLocalContext is not available: can't initialize context manager. Either disable context manager usage by providing `useContextManager: false` option or a context manager in the `contextManager` option.", | ||
); | ||
} | ||
return undefined; | ||
} else { | ||
throw err; | ||
} | ||
}); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters