Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 | 19x 19x 1x 1x 18x 25x 14x 14x 9x 9x 2x 2x 18x 1x 1x 17x 17x 17x 21x 4x 17x 3x 14x 5x 9x 5x 4x 2x 1x 1x 1x 6x 1x 1x 5x 3x 1x 1x 2x 6x 1x 1x 5x 6x 2x 1x 1x 1x 2x 1x 1x 1x 1x | // SPDX-FileCopyrightText: 2025-2026 Anaconda, Inc
// SPDX-License-Identifier: Apache-2.0
import { Configuration } from './config.js';
import { ResourceAttributes } from './attributes.js';
import { AnacondaMetrics, CounterArgs, HistogramArgs } from './metrics.js';
import { AnacondaTrace } from './traces.js';
import { AnacondaLogging, type ATelLogger, EventArgs } from './logging.js';
import { localTimeString as lts } from './common.js';
import { type AttrMap, type CarrierMap, type ASpan, TraceArgs, type Signal } from './types.js';
import {
__initialized,
__metrics,
__tracing,
__logging,
__setInitialized,
__setMetrics,
__setTracing,
__setLogging
} from './signals-state.js';
/**
* Initializes telemetry signals such as metrics and traces based on the provided configuration.
*
* @param config - The telemetry configuration object.
* @param attributes - Resource attributes to associate with telemetry data.
* @param signalTypes - An array of signal types to initialize (e.g., "metrics", "tracing"). Defaults to ["metrics"].
*
* @returns true is successful, otherwise false.
*
* @remarks
* - If telemetry has already been initialized, this function does nothing.
* - Currently, only metrics initialization is implemented; tracing is a placeholder.
* - Unknown signal types will trigger a warning in the console.
*/
export function initializeTelemetry(config: Configuration,
attributes: ResourceAttributes,
signalTypes: Array<Signal> = ["metrics"]): boolean {
console.debug(`${lts()} > *** initializeTelemetry called...`)
if (__initialized) {
console.debug(`${lts()} > *** already initialized, returning true.`)
return true // If already initialized, do nothing.
}
for (const signalType of signalTypes) {
switch (signalType) {
case "metrics":
__setMetrics(new AnacondaMetrics(config, attributes))
break;
case "tracing":
__setTracing(new AnacondaTrace(config, attributes))
break
case "logging":
__setLogging(new AnacondaLogging(config, attributes))
break;
// default:
// console.warn(`${lts()} > *** WARNING: Unknown signal type: ${signalType}`)
// break
}
}
if (!__metrics && !__tracing && !__logging) {
console.warn(`${lts()} > *** WARNING: No telemetry signals initialized. Ensure at least one signal type is specified.`)
return false
}
__setInitialized(true) // Mark as initialized
console.debug(`${lts()} > *** initializeTelemetry finished.`)
return true
}
/**
* Function used to change the endpoint or authorization token or both for a signal type.
*
* @param signal - Either 'metrics', 'tracing', or 'logging' to select which connection to change.
* @param args - Arguments object of possible connection changes. Must have ___at least___ one that is defined.
* @param args.endpoint - The new endpoint for the specific signal.
* @param args.authToken - The new authorization token for the connection to use.
* @param args.certFile - The certificate file for mTLS.
* @param args.userId - The new userId or 'undefined'.
*
* @returns - true if successful, false if it failed.
*
* @remarks
* - Should be called from an async method with await, if not consequences are:
* * If changing endpoints data around the change MAY end up in either endpoint or both.
* * Order of other telemetry may be different than expected.
* - This method does not throw.
*/
export async function changeSignalConnection(signal: Signal, args:
{ endpoint?: URL,
authToken?: string,
certFile?: string,
userId?: string
}): Promise<boolean> {
if (!__initialized) {
return false
}
if (args.endpoint === undefined && args.authToken === undefined && args.certFile === undefined) {
return false
}
if (signal === 'metrics') {
return await __metrics?.changeConnection(args.endpoint, args.authToken, args.certFile, args.userId) ?? false
} else if (signal === 'tracing') {
return await __tracing?.changeConnection(args.endpoint, args.authToken, args.certFile, args.userId) ?? false
} else {
return await __logging?.changeConnection(args.endpoint, args.authToken, args.certFile, args.userId) ?? false
}
}
/**
* Records a value in a histogram metric with optional attributes.
*
* @param args - An argument list object where the `name` field is required.
*
* The args is an object defined by (in any order):
* ```
* {
* name: string = ""; Required; Not supplying a name will result in no value being recorded.
* value: number = 0; Required; This field will be recorded as the value.
* attributes?: AttrMap = {}; Optional; Attributes for the value metric.
* }
* ```
*
* @returns `true` if the histogram was recorded successfully, `false` if metrics are not initialized.
*
* @example
* ```typescript
* recordHistogram({name: "validName", value: 42.0, attributes: { "name": "Value" }})
* ```
*/
export function recordHistogram(args: HistogramArgs): boolean {
if (!__metrics) {
console.warn("*** WARNING: Metrics not initialized. Call initializeTelemetry first.")
return false
}
return __metrics.recordHistogram(args); // Call the recordHistogram method on the AnacondaMetrics instance
}
/**
* Increments a named counter by a specified value and optional attributes.
*
* @param args - An argument list object where the `name` field is required.
*
* The args is an object defined by (in any order):
*
* ```
* {
* name: string = ""; Required; Not supplying a name will result in no value being recorded.
* by?: number = 1; Optional; Not supplying this field will result in the counter being incremented by `1`.
* forceUpDownCounter?: boolean = false; Optional; Counters by default are incrementing only, set to `true` to force an updown counter.
* attributes?: AttrMap = {}; Optional; Attributes for the counter metric.
* }
* ```
*
* @returns `true` if the counter was incremented successfully, `false` if metrics are not initialized.
*
* @example
* ```typescript
* // Creates a incrementing only counter set to `1` or increments an existing counter by `1`.
* incrementCounter({name: "validName"})
*
* // Creates a incrementing and decrementing counter set to `1` or increments an existing counter by `1`.
* incrementCounter({forceUpDown: true, name: "upDownValidName", attributes: {"name": "value"}})
*
* // Creates a incrementing and decrementing counter set to `5` or increments an existing counter by `5`.
* incrementCounter({by: 5, name: "newCounter", forceUpDown: true})
* ```
*/
export function incrementCounter(args: CounterArgs): boolean {
if (!__metrics) {
console.warn("*** WARNING: Metrics not initialized. Call initializeTelemetry first.")
return false
}
return __metrics.incrementCounter(args); // Call the incrementCounter method on the AnacondaMetrics instance
}
/**
* Decrements the specified counter by a given value.
*
* @param args - An argument list object where the `name` field is required.
*
* The args is an object defined by (in any order):
*
* ```
* {
* name: string = ""; Required; Not supplying a name will result in no value being recorded.
* by?: number = 1; Optional; Not supplying this field will result in the counter being incremented by `1`.
* forceUpDownCounter?: boolean = true; Optional; Reguardless of this value, an up down counter will be created.
* attributes?: AttrMap = {}; Optional; Attributes for the counter metric.
* }
* ```
*
* @returns `true` if the counter was decremented successfully, `false` if metrics are not initialized.
*
* @example
* ```typescript
* // Creates an up down counter set to -2, or decrements the already created counter by `2`.
* decrementCounter({name: "validName", by: 2, attributes: {"name": "value"}})
* ```
*/
export function decrementCounter(args: CounterArgs): boolean {
if (!__metrics) {
console.warn("*** WARNING: Metrics not initialized. Call initializeTelemetry first.")
return false
}
return __metrics.decrementCounter(args); // Call the decrementCounter method on the AnacondaMetrics instance
}
/**
* Create the parent or child tracing span object (ASpan) used to send trace events. The object `end()`
* must be called before the trace span can be sent to the collector.
*
* @param name - Name for the span object.
* @param args - Optional: Arguments for the function (see below)
* @param args.attributes - Attributes payload to attach to the trace span.
* @param args.carrier - This is a OTel carrier that can be recieved via message or HTTP headers from another
* process or source. If unsure don't include this argument. This is the parent when the
* parent is "remote" (i.e. client/server or across processes).
* @param args.parentObject - This is used as the parent for the new trace span like a carrier but in-process.
*
* @remarks
* This method does not throw any known exceptions.
*
* @example
* ```typescript
* const span = getTrace(name: "mySpanName", {attributes: { feature: "makeMoney" }})
* span.addEvent({ name: "MyEventName", attributes: { foo: "bar" }})
* span.end()
* ```
* @returns The ASpan object if successful, or undefined if not initialized.
*/
export function getTrace(name: string, args: {
attributes?: AttrMap,
carrier?: CarrierMap,
parentObject?: ASpan
} | undefined = undefined): ASpan | undefined {
if (!__tracing) {
console.warn("*** WARNING: Tracing is not initialized. Call initializeTelemetry first.")
return undefined
}
return __tracing.getTrace(name, args?.attributes, args?.carrier, args?.parentObject)
}
/**
* This method will ignore any export time intervals and will immediately flush cached data in memory
* to the collector. Use sparingly but ALWAYS use it before your application exits.
*
* @remarks
* This method does not throw any known exceptions. Export failures (e.g., 404 errors) are logged
* as warnings instead of crashing the application, matching the Python SDK behavior.
*/
export async function flushAllSignals(): Promise<void> {
await Promise.all([
__tracing?.flush(),
__metrics?.flush(),
__logging?.flush()
].filter(Boolean))
}
/**
* This returns a singleton logger use to log events and regular logging message to OTel.
*
* @remarks
* This method does not throw any known exceptions.
*
* @returns The ATelLogger object if logging is initialized, otherwise 'undefined'.
*/
export function getATelLogger(): ATelLogger | undefined {
if (!__logging) {
console.warn("*** WARNING: Logging is not initialized. Call initializeTelemetry first.")
return undefined
}
return __logging.getLogger()
}
/**
* Use this method to send named events to the OTel collector as logging message. Do not use
* a name of '__LOG__', as this is uised for regular logging messages for debug.
*
* @param args.eventName - The name of the event being sent. Sending "" causes no errors but
* would be meaningless on the collector side.
* @param args.payload - Any Record<string,any> that will be converted to a JSON string
* payload to send to the collector.
* @param args.attributes - Attributes payload to attach to the log message.
*
* @remarks
* This method does not throw any known exceptions.
*
* @example
* ```typescript
* sendEvent({
* name: "LOGGED_IN",
* payload: {
* key1: "",
* key2: {
* subKey1: ""
* }
* },
* attributes: {}
* })
* ```
* @returns false if the logging is NOT initialized, true if the send attempt was successful.
* Actual sending happens in the background asynchonously.
*/
export function sendEvent(args: EventArgs): boolean {
if (!__logging) {
console.warn("*** WARNING: Logging is not initialized. Call initializeTelemetry first.")
return false
}
__logging.sendEvent(args)
return true
}
|