@opencensus/core
Advanced tools
Comparing version 0.0.9 to 0.0.10
@@ -23,3 +23,3 @@ /** | ||
static LEVELS: string[]; | ||
level: string; | ||
level?: string; | ||
/** | ||
@@ -32,3 +32,3 @@ * Constructs a new ConsoleLogger instance | ||
* Logger error function. | ||
* @param message menssage erro to log in console | ||
* @param message message error to log in console | ||
* @param args arguments to log in console | ||
@@ -39,3 +39,3 @@ */ | ||
* Logger warning function. | ||
* @param message menssage warning to log in console | ||
* @param message message warning to log in console | ||
* @param args arguments to log in console | ||
@@ -46,3 +46,3 @@ */ | ||
* Logger info function. | ||
* @param message menssage info to log in console | ||
* @param message message info to log in console | ||
* @param args arguments to log in console | ||
@@ -53,3 +53,3 @@ */ | ||
* Logger debug function. | ||
* @param message menssage debug to log in console | ||
* @param message message debug to log in console | ||
* @param args arguments to log in console | ||
@@ -64,3 +64,3 @@ */ | ||
*/ | ||
declare const logger: (options?: string | number | types.LoggerOptions) => types.Logger; | ||
declare const logger: (options?: string | number | types.LoggerOptions | undefined) => types.Logger; | ||
export { logger }; |
@@ -45,3 +45,4 @@ "use strict"; | ||
} | ||
this.level = opt.level; | ||
if (opt.level) | ||
this.level = opt.level; | ||
this.logger = | ||
@@ -52,3 +53,3 @@ logDriver({ levels: ConsoleLogger.LEVELS, level: opt.level || 'silent' }); | ||
* Logger error function. | ||
* @param message menssage erro to log in console | ||
* @param message message error to log in console | ||
* @param args arguments to log in console | ||
@@ -62,3 +63,3 @@ */ | ||
* Logger warning function. | ||
* @param message menssage warning to log in console | ||
* @param message message warning to log in console | ||
* @param args arguments to log in console | ||
@@ -72,3 +73,3 @@ */ | ||
* Logger info function. | ||
* @param message menssage info to log in console | ||
* @param message message info to log in console | ||
* @param args arguments to log in console | ||
@@ -82,3 +83,3 @@ */ | ||
* Logger debug function. | ||
* @param message menssage debug to log in console | ||
* @param message message debug to log in console | ||
* @param args arguments to log in console | ||
@@ -85,0 +86,0 @@ */ |
/** | ||
* Copyright 2019, OpenCensus Authors | ||
* | ||
* Licensed under the Apache License, Version 2.0 the "License"; | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
@@ -6,0 +6,0 @@ * You may obtain a copy of the License at |
@@ -5,3 +5,3 @@ "use strict"; | ||
* | ||
* Licensed under the Apache License, Version 2.0 the "License"; | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
@@ -8,0 +8,0 @@ * You may obtain a copy of the License at |
@@ -17,3 +17,3 @@ /** | ||
export declare type LogFunction = (message: any, ...args: any[]) => void; | ||
/** Defines an logger interface. */ | ||
/** Defines a logger interface. */ | ||
export interface Logger { | ||
@@ -27,5 +27,5 @@ /** Logger verbosity level. If omitted, `debug` level is assumed. */ | ||
} | ||
/** Defines an logger options interface. */ | ||
/** Defines a logger options interface. */ | ||
export interface LoggerOptions { | ||
level?: string; | ||
} |
@@ -19,7 +19,15 @@ "use strict"; | ||
// Load the package details. Note that the `require` is performed at runtime, | ||
// which means the source files will be in the `/build` directory, so the | ||
// package path is relative to that location. | ||
const pjson = require('../../../package.json'); | ||
// which means package.json will be relative to the location of this file. | ||
// If this file has been compiled, it will be in the `/build` directory, so the | ||
// package path is relative to that location. Otherwise, it will be relative | ||
// to the original .ts file. | ||
let pjson; | ||
try { | ||
pjson = require('../../../package.json'); | ||
} | ||
catch (_a) { | ||
pjson = require('../../package.json'); | ||
} | ||
// Export the core package version | ||
exports.version = pjson.version; | ||
//# sourceMappingURL=version.js.map |
@@ -20,6 +20,6 @@ /** | ||
import * as modelTypes from '../trace/model/types'; | ||
import * as types from './types'; | ||
import { Exporter, ExporterConfig, StatsEventListener } from './types'; | ||
/** Do not send span data */ | ||
export declare class NoopExporter implements types.Exporter { | ||
logger: loggerTypes.Logger; | ||
export declare class NoopExporter implements Exporter { | ||
logger?: loggerTypes.Logger; | ||
onStartSpan(root: modelTypes.RootSpan): void; | ||
@@ -30,5 +30,5 @@ onEndSpan(root: modelTypes.RootSpan): void; | ||
/** Format and sends span data to the console. */ | ||
export declare class ConsoleExporter implements types.Exporter { | ||
export declare class ConsoleExporter implements Exporter { | ||
/** Buffer object to store the spans. */ | ||
private logger; | ||
private logger?; | ||
private buffer; | ||
@@ -38,5 +38,5 @@ /** | ||
* @param config Exporter configuration object to create a console log | ||
* exporter. | ||
* exporter. | ||
*/ | ||
constructor(config: types.ExporterConfig); | ||
constructor(config: ExporterConfig); | ||
onStartSpan(root: modelTypes.RootSpan): void; | ||
@@ -50,3 +50,3 @@ /** | ||
* Sends the spans information to the console. | ||
* @param rootSpans | ||
* @param rootSpans A list of root spans to publish. | ||
*/ | ||
@@ -56,3 +56,3 @@ publish(rootSpans: modelTypes.RootSpan[]): Promise<void>; | ||
/** Exporter that receives stats data and shows in the log console. */ | ||
export declare class ConsoleStatsExporter implements types.StatsEventListener { | ||
export declare class ConsoleStatsExporter implements StatsEventListener { | ||
/** | ||
@@ -68,2 +68,3 @@ * Event called when a view is registered | ||
* @param measurement recorded measurement | ||
* @param tags The tags to which the value is applied | ||
*/ | ||
@@ -76,2 +77,4 @@ onRecord(views: View[], measurement: Measurement, tags: Map<TagKey, TagValue>): void; | ||
start(): void; | ||
/** Stops the exporter. */ | ||
stop(): void; | ||
} |
@@ -33,3 +33,3 @@ "use strict"; | ||
* @param config Exporter configuration object to create a console log | ||
* exporter. | ||
* exporter. | ||
*/ | ||
@@ -50,3 +50,3 @@ constructor(config) { | ||
* Sends the spans information to the console. | ||
* @param rootSpans | ||
* @param rootSpans A list of root spans to publish. | ||
*/ | ||
@@ -80,2 +80,3 @@ publish(rootSpans) { | ||
* @param measurement recorded measurement | ||
* @param tags The tags to which the value is applied | ||
*/ | ||
@@ -92,4 +93,6 @@ onRecord(views, measurement, tags) { | ||
} | ||
/** Stops the exporter. */ | ||
stop() { } | ||
} | ||
exports.ConsoleStatsExporter = ConsoleStatsExporter; | ||
//# sourceMappingURL=console-exporter.js.map |
@@ -19,2 +19,4 @@ "use strict"; | ||
const logger = require("../common/console-logger"); | ||
const DEFAULT_BUFFER_SIZE = 100; | ||
const DEFAULT_BUFFER_TIMEOUT = 20000; | ||
/** Controls the sending of traces to exporters. */ | ||
@@ -36,4 +38,8 @@ class ExporterBuffer { | ||
this.logger = config.logger || logger.logger(); | ||
this.bufferSize = config.bufferSize; | ||
this.bufferTimeout = config.bufferTimeout; | ||
this.bufferSize = isNaN(Number(config.bufferSize)) ? | ||
DEFAULT_BUFFER_SIZE : | ||
Number(config.bufferSize); | ||
this.bufferTimeout = isNaN(Number(config.bufferTimeout)) ? | ||
DEFAULT_BUFFER_TIMEOUT : | ||
Number(config.bufferTimeout); | ||
return this; | ||
@@ -40,0 +46,0 @@ } |
@@ -44,2 +44,3 @@ /** | ||
* @param measurement The recorded measurement | ||
* @param tags The tags to which the value is applied | ||
*/ | ||
@@ -52,3 +53,5 @@ onRecord(views: View[], measurement: Measurement, tags: Map<TagKey, TagValue>): void; | ||
start(): void; | ||
/** Stops the exporter. */ | ||
stop(): void; | ||
} | ||
export declare type ExporterConfig = configTypes.BufferConfig; |
@@ -25,4 +25,3 @@ /** | ||
export * from './metrics/gauges/types'; | ||
import { Metric, MetricDescriptor, TimeSeries, MetricDescriptorType, LabelKey, LabelValue, Point as TimeSeriesPoint, DistributionValue, BucketOptions, Bucket as DistributionBucket, SummaryValue, Explicit, Exemplar, Timestamp, Snapshot, ValueAtPercentile, MetricProducerManager, MetricProducer } from './metrics/export/types'; | ||
export { Metric, MetricDescriptor, TimeSeries, MetricDescriptorType, LabelKey, LabelValue, TimeSeriesPoint, DistributionValue, BucketOptions, DistributionBucket, SummaryValue, Explicit, Exemplar, Timestamp, Snapshot, ValueAtPercentile, MetricProducerManager, MetricProducer }; | ||
export { Metric, MetricDescriptor, TimeSeries, MetricDescriptorType, LabelKey, LabelValue, Point as TimeSeriesPoint, DistributionValue, BucketOptions, Bucket as DistributionBucket, SummaryValue, Explicit, Exemplar, Timestamp, Snapshot, ValueAtPercentile, MetricProducerManager, MetricProducer } from './metrics/export/types'; | ||
export * from './trace/model/tracer'; | ||
@@ -38,5 +37,8 @@ export * from './trace/sampler/sampler'; | ||
export * from './tags/tag-map'; | ||
export * from './tags/tagger'; | ||
export * from './tags/propagation/binary-serializer'; | ||
export * from './tags/propagation/text-format'; | ||
export * from './resource/resource'; | ||
export * from './stats/types'; | ||
export * from './tags/types'; | ||
export { TagKey, TagValue, TagMetadata, TagTtl } from './tags/types'; | ||
export * from './resource/types'; | ||
@@ -43,0 +45,0 @@ import * as logger from './common/console-logger'; |
@@ -22,3 +22,3 @@ "use strict"; | ||
__export(require("./trace/model/types")); | ||
const types_1 = require("./metrics/export/types"); | ||
var types_1 = require("./metrics/export/types"); | ||
exports.MetricDescriptorType = types_1.MetricDescriptorType; | ||
@@ -42,5 +42,10 @@ // classes | ||
__export(require("./tags/tag-map")); | ||
__export(require("./tags/tagger")); | ||
__export(require("./tags/propagation/binary-serializer")); | ||
__export(require("./tags/propagation/text-format")); | ||
__export(require("./resource/resource")); | ||
// interfaces | ||
__export(require("./stats/types")); | ||
var types_2 = require("./tags/types"); | ||
exports.TagTtl = types_2.TagTtl; | ||
// logger | ||
@@ -47,0 +52,0 @@ const logger = require("./common/console-logger"); |
@@ -27,3 +27,3 @@ "use strict"; | ||
/** The duration between start and end of the clock. */ | ||
this.diff = null; | ||
this.diff = [0, 0]; | ||
this.startTimeLocal = new Date(); | ||
@@ -43,3 +43,3 @@ this.hrtimeLocal = process.hrtime(); | ||
if (!this.endedLocal) { | ||
return null; | ||
return 0; | ||
} | ||
@@ -58,7 +58,6 @@ const ns = this.diff[0] * 1e9 + this.diff[1]; | ||
get endTime() { | ||
let result = null; | ||
if (this.ended) { | ||
result = new Date(this.startTime.getTime() + this.duration); | ||
return new Date(this.startTime.getTime() + this.duration); | ||
} | ||
return result; | ||
return new Date(); | ||
} | ||
@@ -65,0 +64,0 @@ /** Indicates if the clock was ended. */ |
@@ -22,6 +22,9 @@ "use strict"; | ||
const shimmer = require("shimmer"); | ||
const wrappedSymbol = Symbol('context_wrapped'); | ||
const WRAPPED = Symbol('context_wrapped'); | ||
/** A map of AsyncResource IDs to Context objects. */ | ||
let contexts = {}; | ||
let current = {}; | ||
// Create the hook. | ||
asyncHook.createHook({ init, before, destroy }).enable(); | ||
// A list of well-known EventEmitter methods that add event listeners. | ||
const EVENT_EMITTER_METHODS = ['addListener', 'on', 'once', 'prependListener', 'prependOnceListener']; | ||
@@ -52,2 +55,5 @@ class AsyncHooksNamespace { | ||
current = {}; | ||
if (oldContext['current_tag_map']) { | ||
current['current_tag_map'] = oldContext['current_tag_map']; | ||
} | ||
const res = fn(); | ||
@@ -61,3 +67,3 @@ current = oldContext; | ||
// tslint:disable-next-line:no-any | ||
if (cb[wrappedSymbol] || !current) { | ||
if (cb[WRAPPED] || !current) { | ||
return cb; | ||
@@ -74,3 +80,3 @@ } | ||
// tslint:disable-next-line:no-any | ||
contextWrapper[wrappedSymbol] = true; | ||
contextWrapper[WRAPPED] = true; | ||
Object.defineProperty(contextWrapper, 'length', { | ||
@@ -104,5 +110,7 @@ enumerable: false, | ||
// AsyncWrap Hooks | ||
/** init is called during object construction. */ | ||
function init(uid, provider, parentUid, parentHandle) { | ||
contexts[uid] = current; | ||
} | ||
/** before is called just before the resource's callback is called. */ | ||
function before(uid) { | ||
@@ -113,2 +121,6 @@ if (contexts[uid]) { | ||
} | ||
/** | ||
* destroy is called when the object is no longer used, so also delete | ||
* its entry in the map. | ||
*/ | ||
function destroy(uid) { | ||
@@ -115,0 +127,0 @@ delete contexts[uid]; |
@@ -29,1 +29,2 @@ /** | ||
export declare function getNamespace(): CLS.Namespace; | ||
export declare const contextManager: CLS.Namespace; |
@@ -18,9 +18,6 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
// Original file from Stackdriver Trace Agent for Node.js | ||
// https://github.com/GoogleCloudPlatform/cloud-trace-nodejs | ||
const CLS = require("continuation-local-storage"); | ||
const semver = require("semver"); | ||
const useAsyncHooks = semver.satisfies(process.version, '>=8'); //&& | ||
// !!process.env.GCLOUD_TRACE_NEW_CONTEXT; | ||
const cls = useAsyncHooks ? require('./cls-ah') : CLS; | ||
const cls = useAsyncHooks ? require('./cls-ah') : require('continuation-local-storage'); | ||
const TRACE_NAMESPACE = 'opencensus.io'; | ||
@@ -46,2 +43,3 @@ /** | ||
exports.getNamespace = getNamespace; | ||
exports.contextManager = createNamespace(); | ||
//# sourceMappingURL=cls.js.map |
/** | ||
* Copyright 2018 Google LLC | ||
* Copyright 2018, OpenCensus Authors | ||
* | ||
@@ -31,3 +31,3 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
* | ||
* @param {string} str The Character to be validated. | ||
* @param {string} ch The Character to be validated. | ||
* @returns {boolean} Whether the Character is printable. | ||
@@ -34,0 +34,0 @@ */ |
"use strict"; | ||
/** | ||
* Copyright 2018 Google LLC | ||
* Copyright 2018, OpenCensus Authors | ||
* | ||
@@ -41,3 +41,3 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
* | ||
* @param {string} str The Character to be validated. | ||
* @param {string} ch The Character to be validated. | ||
* @returns {boolean} Whether the Character is printable. | ||
@@ -44,0 +44,0 @@ */ |
/** | ||
* Copyright 2018 Google LLC | ||
* Copyright 2018, OpenCensus Authors | ||
* | ||
@@ -4,0 +4,0 @@ * Licensed under the Apache License, Version 2.0 (the "License"); |
"use strict"; | ||
/** | ||
* Copyright 2018 Google LLC | ||
* Copyright 2018, OpenCensus Authors | ||
* | ||
@@ -5,0 +5,0 @@ * Licensed under the Apache License, Version 2.0 (the "License"); |
/** | ||
* Copyright 2018, OpenCensus Authors | ||
* | ||
* Licensed under the Apache License, Version 2.0 the "License"; | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
@@ -6,0 +6,0 @@ * You may obtain a copy of the License at |
@@ -5,3 +5,3 @@ "use strict"; | ||
* | ||
* Licensed under the Apache License, Version 2.0 the "License"; | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
@@ -8,0 +8,0 @@ * You may obtain a copy of the License at |
/** | ||
* Copyright 2019, OpenCensus Authors | ||
* | ||
* Licensed under the Apache License, Version 2.0 the "License"; | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
@@ -6,0 +6,0 @@ * You may obtain a copy of the License at |
@@ -5,3 +5,3 @@ "use strict"; | ||
* | ||
* Licensed under the Apache License, Version 2.0 the "License"; | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
@@ -35,3 +35,4 @@ * You may obtain a copy of the License at | ||
* | ||
* @param {MetricProducer} The MetricProducer to be added to the manager. | ||
* @param {MetricProducer} metricProducer The MetricProducer to be added to | ||
* the manager. | ||
*/ | ||
@@ -47,3 +48,4 @@ add(metricProducer) { | ||
* | ||
* @param {MetricProducer} The MetricProducer to be removed from the manager. | ||
* @param {MetricProducer} metricProducer The MetricProducer to be removed | ||
* from the manager. | ||
*/ | ||
@@ -50,0 +52,0 @@ remove(metricProducer) { |
/** | ||
* Copyright 2018, OpenCensus Authors | ||
* | ||
* Licensed under the Apache License, Version 2.0 the "License"; | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
@@ -6,0 +6,0 @@ * You may obtain a copy of the License at |
@@ -5,3 +5,3 @@ "use strict"; | ||
* | ||
* Licensed under the Apache License, Version 2.0 the "License"; | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
@@ -8,0 +8,0 @@ * You may obtain a copy of the License at |
@@ -56,3 +56,3 @@ /** | ||
private registeredPoints; | ||
private extractor; | ||
private extractor?; | ||
private static readonly LABEL_VALUE; | ||
@@ -110,3 +110,3 @@ private static readonly LABEL_VALUES; | ||
*/ | ||
getMetric(): Metric; | ||
getMetric(): Metric | null; | ||
} |
@@ -86,3 +86,3 @@ /** | ||
*/ | ||
getMetric(): Metric; | ||
getMetric(): Metric | null; | ||
} | ||
@@ -89,0 +89,0 @@ /** |
@@ -16,3 +16,4 @@ /** | ||
*/ | ||
import { Metric, TimeSeries, Timestamp } from '../export/types'; | ||
import { MeasureUnit } from '../../stats/types'; | ||
import { LabelKey, LabelValue, Metric, TimeSeries, Timestamp } from '../export/types'; | ||
export interface Meter { | ||
@@ -24,3 +25,3 @@ /** | ||
*/ | ||
getMetric(): Metric; | ||
getMetric(): Metric | null; | ||
} | ||
@@ -48,1 +49,12 @@ export interface Point { | ||
} | ||
/** Options for every metric added to the MetricRegistry. */ | ||
export interface MetricOptions { | ||
/** The description of the metric. */ | ||
readonly description?: string; | ||
/** The unit of the metric. */ | ||
readonly unit?: MeasureUnit; | ||
/** The list of the label keys. */ | ||
readonly labelKeys?: LabelKey[]; | ||
/** The map of constant labels for the Metric. */ | ||
readonly constantLabels?: Map<LabelKey, LabelValue>; | ||
} |
/** | ||
* Copyright 2019, OpenCensus Authors | ||
* | ||
* Licensed under the Apache License, Version 2.0 the "License"; | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
@@ -6,0 +6,0 @@ * You may obtain a copy of the License at |
@@ -5,3 +5,3 @@ "use strict"; | ||
* | ||
* Licensed under the Apache License, Version 2.0 the "License"; | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
@@ -8,0 +8,0 @@ * You may obtain a copy of the License at |
@@ -16,6 +16,6 @@ /** | ||
*/ | ||
import { MeasureUnit } from '../stats/types'; | ||
import { LabelKey, MetricProducer } from './export/types'; | ||
import { MetricProducer } from './export/types'; | ||
import { DerivedGauge } from './gauges/derived-gauge'; | ||
import { Gauge } from './gauges/gauge'; | ||
import { MetricOptions } from './gauges/types'; | ||
/** | ||
@@ -28,6 +28,6 @@ * Creates and manages application's set of metrics. | ||
private static readonly NAME; | ||
private static readonly DESCRIPTION; | ||
private static readonly UNIT; | ||
private static readonly LABEL_KEY; | ||
private static readonly LABEL_KEYS; | ||
private static readonly DEFAULT_DESCRIPTION; | ||
private static readonly DEFAULT_UNIT; | ||
private static readonly DEFAULT_LABEL_KEYS; | ||
constructor(); | ||
@@ -40,8 +40,6 @@ /** | ||
* @param {string} name The name of the metric. | ||
* @param {string} description The description of the metric. | ||
* @param {MeasureUnit} unit The unit of the metric. | ||
* @param {LabelKey[]} labelKeys The list of the label keys. | ||
* @param {MetricOptions} options The options for the metric. | ||
* @returns {Gauge} A Int64 Gauge metric. | ||
*/ | ||
addInt64Gauge(name: string, description: string, unit: MeasureUnit, labelKeys: LabelKey[]): Gauge; | ||
addInt64Gauge(name: string, options?: MetricOptions): Gauge; | ||
/** | ||
@@ -53,8 +51,6 @@ * Builds a new double gauge to be added to the registry. This is more | ||
* @param {string} name The name of the metric. | ||
* @param {string} description The description of the metric. | ||
* @param {MeasureUnit} unit The unit of the metric. | ||
* @param {LabelKey[]} labelKeys The list of the label keys. | ||
* @param {MetricOptions} options The options for the metric. | ||
* @returns {Gauge} A Double Gauge metric. | ||
*/ | ||
addDoubleGauge(name: string, description: string, unit: MeasureUnit, labelKeys: LabelKey[]): Gauge; | ||
addDoubleGauge(name: string, options?: MetricOptions): Gauge; | ||
/** | ||
@@ -66,8 +62,6 @@ * Builds a new derived Int64 gauge to be added to the registry. This is more | ||
* @param {string} name The name of the metric. | ||
* @param {string} description The description of the metric. | ||
* @param {MeasureUnit} unit The unit of the metric. | ||
* @param {LabelKey[]} labelKeys The list of the label keys. | ||
* @param {MetricOptions} options The options for the metric. | ||
* @returns {DerivedGauge} A Int64 DerivedGauge metric. | ||
*/ | ||
addDerivedInt64Gauge(name: string, description: string, unit: MeasureUnit, labelKeys: LabelKey[]): DerivedGauge; | ||
addDerivedInt64Gauge(name: string, options?: MetricOptions): DerivedGauge; | ||
/** | ||
@@ -79,8 +73,6 @@ * Builds a new derived double gauge to be added to the registry. This is more | ||
* @param {string} name The name of the metric. | ||
* @param {string} description The description of the metric. | ||
* @param {MeasureUnit} unit The unit of the metric. | ||
* @param {LabelKey[]} labelKeys The list of the label keys. | ||
* @param {MetricOptions} options The options for the metric. | ||
* @returns {DerivedGauge} A Double DerivedGauge metric. | ||
*/ | ||
addDerivedDoubleGauge(name: string, description: string, unit: MeasureUnit, labelKeys: LabelKey[]): DerivedGauge; | ||
addDerivedDoubleGauge(name: string, options?: MetricOptions): DerivedGauge; | ||
/** | ||
@@ -87,0 +79,0 @@ * Registers metric to register. |
@@ -19,4 +19,5 @@ "use strict"; | ||
const validations_1 = require("../common/validations"); | ||
const types_1 = require("../stats/types"); | ||
const base_metric_producer_1 = require("./export/base-metric-producer"); | ||
const types_1 = require("./export/types"); | ||
const types_2 = require("./export/types"); | ||
const derived_gauge_1 = require("./gauges/derived-gauge"); | ||
@@ -38,11 +39,13 @@ const gauge_1 = require("./gauges/gauge"); | ||
* @param {string} name The name of the metric. | ||
* @param {string} description The description of the metric. | ||
* @param {MeasureUnit} unit The unit of the metric. | ||
* @param {LabelKey[]} labelKeys The list of the label keys. | ||
* @param {MetricOptions} options The options for the metric. | ||
* @returns {Gauge} A Int64 Gauge metric. | ||
*/ | ||
addInt64Gauge(name, description, unit, labelKeys) { | ||
validations_1.validateArrayElementsNotNull(validations_1.validateNotNull(labelKeys, MetricRegistry.LABEL_KEYS), MetricRegistry.LABEL_KEY); | ||
addInt64Gauge(name, options) { | ||
const description = (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; | ||
const unit = (options && options.unit) || MetricRegistry.DEFAULT_UNIT; | ||
const labelKeys = (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; | ||
// TODO (mayurkale): Add support for constantLabels | ||
validations_1.validateArrayElementsNotNull(labelKeys, MetricRegistry.LABEL_KEY); | ||
const labelKeysCopy = Object.assign([], labelKeys); | ||
const int64Gauge = new gauge_1.Gauge(validations_1.validateNotNull(name, MetricRegistry.NAME), validations_1.validateNotNull(description, MetricRegistry.DESCRIPTION), validations_1.validateNotNull(unit, MetricRegistry.UNIT), types_1.MetricDescriptorType.GAUGE_INT64, labelKeysCopy); | ||
const int64Gauge = new gauge_1.Gauge(validations_1.validateNotNull(name, MetricRegistry.NAME), description, unit, types_2.MetricDescriptorType.GAUGE_INT64, labelKeysCopy); | ||
this.registerMetric(name, int64Gauge); | ||
@@ -57,11 +60,13 @@ return int64Gauge; | ||
* @param {string} name The name of the metric. | ||
* @param {string} description The description of the metric. | ||
* @param {MeasureUnit} unit The unit of the metric. | ||
* @param {LabelKey[]} labelKeys The list of the label keys. | ||
* @param {MetricOptions} options The options for the metric. | ||
* @returns {Gauge} A Double Gauge metric. | ||
*/ | ||
addDoubleGauge(name, description, unit, labelKeys) { | ||
validations_1.validateArrayElementsNotNull(validations_1.validateNotNull(labelKeys, MetricRegistry.LABEL_KEYS), MetricRegistry.LABEL_KEY); | ||
addDoubleGauge(name, options) { | ||
const description = (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; | ||
const unit = (options && options.unit) || MetricRegistry.DEFAULT_UNIT; | ||
const labelKeys = (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; | ||
// TODO (mayurkale): Add support for constantLabels | ||
validations_1.validateArrayElementsNotNull(labelKeys, MetricRegistry.LABEL_KEY); | ||
const labelKeysCopy = Object.assign([], labelKeys); | ||
const doubleGauge = new gauge_1.Gauge(validations_1.validateNotNull(name, MetricRegistry.NAME), validations_1.validateNotNull(description, MetricRegistry.DESCRIPTION), validations_1.validateNotNull(unit, MetricRegistry.UNIT), types_1.MetricDescriptorType.GAUGE_DOUBLE, labelKeysCopy); | ||
const doubleGauge = new gauge_1.Gauge(validations_1.validateNotNull(name, MetricRegistry.NAME), description, unit, types_2.MetricDescriptorType.GAUGE_DOUBLE, labelKeysCopy); | ||
this.registerMetric(name, doubleGauge); | ||
@@ -76,11 +81,13 @@ return doubleGauge; | ||
* @param {string} name The name of the metric. | ||
* @param {string} description The description of the metric. | ||
* @param {MeasureUnit} unit The unit of the metric. | ||
* @param {LabelKey[]} labelKeys The list of the label keys. | ||
* @param {MetricOptions} options The options for the metric. | ||
* @returns {DerivedGauge} A Int64 DerivedGauge metric. | ||
*/ | ||
addDerivedInt64Gauge(name, description, unit, labelKeys) { | ||
validations_1.validateArrayElementsNotNull(validations_1.validateNotNull(labelKeys, MetricRegistry.LABEL_KEYS), MetricRegistry.LABEL_KEY); | ||
addDerivedInt64Gauge(name, options) { | ||
const description = (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; | ||
const unit = (options && options.unit) || MetricRegistry.DEFAULT_UNIT; | ||
const labelKeys = (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; | ||
// TODO (mayurkale): Add support for constantLabels | ||
validations_1.validateArrayElementsNotNull(labelKeys, MetricRegistry.LABEL_KEY); | ||
const labelKeysCopy = Object.assign([], labelKeys); | ||
const derivedInt64Gauge = new derived_gauge_1.DerivedGauge(validations_1.validateNotNull(name, MetricRegistry.NAME), validations_1.validateNotNull(description, MetricRegistry.DESCRIPTION), validations_1.validateNotNull(unit, MetricRegistry.UNIT), types_1.MetricDescriptorType.GAUGE_INT64, labelKeysCopy); | ||
const derivedInt64Gauge = new derived_gauge_1.DerivedGauge(validations_1.validateNotNull(name, MetricRegistry.NAME), description, unit, types_2.MetricDescriptorType.GAUGE_INT64, labelKeysCopy); | ||
this.registerMetric(name, derivedInt64Gauge); | ||
@@ -95,11 +102,13 @@ return derivedInt64Gauge; | ||
* @param {string} name The name of the metric. | ||
* @param {string} description The description of the metric. | ||
* @param {MeasureUnit} unit The unit of the metric. | ||
* @param {LabelKey[]} labelKeys The list of the label keys. | ||
* @param {MetricOptions} options The options for the metric. | ||
* @returns {DerivedGauge} A Double DerivedGauge metric. | ||
*/ | ||
addDerivedDoubleGauge(name, description, unit, labelKeys) { | ||
validations_1.validateArrayElementsNotNull(validations_1.validateNotNull(labelKeys, MetricRegistry.LABEL_KEYS), MetricRegistry.LABEL_KEY); | ||
addDerivedDoubleGauge(name, options) { | ||
const description = (options && options.description) || MetricRegistry.DEFAULT_DESCRIPTION; | ||
const unit = (options && options.unit) || MetricRegistry.DEFAULT_UNIT; | ||
const labelKeys = (options && options.labelKeys) || MetricRegistry.DEFAULT_LABEL_KEYS; | ||
// TODO (mayurkale): Add support for constantLabels | ||
validations_1.validateArrayElementsNotNull(labelKeys, MetricRegistry.LABEL_KEY); | ||
const labelKeysCopy = Object.assign([], labelKeys); | ||
const derivedDoubleGauge = new derived_gauge_1.DerivedGauge(validations_1.validateNotNull(name, MetricRegistry.NAME), validations_1.validateNotNull(description, MetricRegistry.DESCRIPTION), validations_1.validateNotNull(unit, MetricRegistry.UNIT), types_1.MetricDescriptorType.GAUGE_DOUBLE, labelKeysCopy); | ||
const derivedDoubleGauge = new derived_gauge_1.DerivedGauge(validations_1.validateNotNull(name, MetricRegistry.NAME), description, unit, types_2.MetricDescriptorType.GAUGE_DOUBLE, labelKeysCopy); | ||
this.registerMetric(name, derivedDoubleGauge); | ||
@@ -130,6 +139,6 @@ return derivedDoubleGauge; | ||
MetricRegistry.NAME = 'name'; | ||
MetricRegistry.DESCRIPTION = 'description'; | ||
MetricRegistry.UNIT = 'unit'; | ||
MetricRegistry.LABEL_KEY = 'labelKey'; | ||
MetricRegistry.LABEL_KEYS = 'labelKeys'; | ||
MetricRegistry.DEFAULT_DESCRIPTION = ''; | ||
MetricRegistry.DEFAULT_UNIT = types_1.MeasureUnit.UNIT; | ||
MetricRegistry.DEFAULT_LABEL_KEYS = []; | ||
exports.MetricRegistry = MetricRegistry; | ||
@@ -139,6 +148,2 @@ /** | ||
* exporting using MetricProducerManager. | ||
* | ||
* TODO (mayurkale): Add MetricProducerManager, that Keeps a set of | ||
* MetricProducer that is used by exporters to determine the metrics that | ||
* need to be exported. | ||
*/ | ||
@@ -156,5 +161,7 @@ class MetricProducerForRegistry extends base_metric_producer_1.BaseMetricProducer { | ||
getMetrics() { | ||
return Array.from(this.registeredMetrics, ([_, meter]) => meter.getMetric()); | ||
return Array.from(this.registeredMetrics.values()) | ||
.map(meter => meter.getMetric()) | ||
.filter(meter => !!meter); | ||
} | ||
} | ||
//# sourceMappingURL=metric-registry.js.map |
@@ -45,5 +45,7 @@ "use strict"; | ||
static mergeResources(resources) { | ||
let currentResource; | ||
for (const resource of resources) { | ||
currentResource = this.merge(currentResource, resource); | ||
if (resources.length === 0) | ||
return { type: 'global', labels: {} }; | ||
let currentResource = resources[0]; | ||
for (let i = 1; i < resources.length; i++) { | ||
currentResource = this.merge(currentResource, resources[i]); | ||
} | ||
@@ -62,9 +64,8 @@ return currentResource; | ||
static parseResourceType(rawEnvType) { | ||
if (rawEnvType) { | ||
if (!CoreResource.isValidAndNotEmpty(rawEnvType)) { | ||
throw new Error(`Type ${CoreResource.ERROR_MESSAGE_INVALID_CHARS}`); | ||
} | ||
return rawEnvType.trim(); | ||
if (!rawEnvType) | ||
return null; | ||
if (!CoreResource.isValidAndNotEmpty(rawEnvType)) { | ||
throw new Error(`Type ${CoreResource.ERROR_MESSAGE_INVALID_CHARS}`); | ||
} | ||
return null; | ||
return rawEnvType.trim(); | ||
} | ||
@@ -84,22 +85,22 @@ /** | ||
static parseResourceLabels(rawEnvLabels) { | ||
if (!rawEnvLabels) | ||
return {}; | ||
const labels = {}; | ||
if (rawEnvLabels) { | ||
const rawLabels = rawEnvLabels.split(this.COMMA_SEPARATOR, -1); | ||
for (const rawLabel of rawLabels) { | ||
const keyValuePair = rawLabel.split(this.LABEL_KEY_VALUE_SPLITTER, -1); | ||
if (keyValuePair.length !== 2) { | ||
continue; | ||
} | ||
let [key, value] = keyValuePair; | ||
// Leading and trailing whitespaces are trimmed. | ||
key = key.trim(); | ||
value = value.trim().split('^"|"$').join(''); | ||
if (!CoreResource.isValidAndNotEmpty(key)) { | ||
throw new Error(`Label key ${CoreResource.ERROR_MESSAGE_INVALID_CHARS}`); | ||
} | ||
if (!CoreResource.isValid(value)) { | ||
throw new Error(`Label value ${CoreResource.ERROR_MESSAGE_INVALID_VALUE}`); | ||
} | ||
labels[key] = value; | ||
const rawLabels = rawEnvLabels.split(this.COMMA_SEPARATOR, -1); | ||
for (const rawLabel of rawLabels) { | ||
const keyValuePair = rawLabel.split(this.LABEL_KEY_VALUE_SPLITTER, -1); | ||
if (keyValuePair.length !== 2) { | ||
continue; | ||
} | ||
let [key, value] = keyValuePair; | ||
// Leading and trailing whitespaces are trimmed. | ||
key = key.trim(); | ||
value = value.trim().split('^"|"$').join(''); | ||
if (!CoreResource.isValidAndNotEmpty(key)) { | ||
throw new Error(`Label key ${CoreResource.ERROR_MESSAGE_INVALID_CHARS}`); | ||
} | ||
if (!CoreResource.isValid(value)) { | ||
throw new Error(`Label value ${CoreResource.ERROR_MESSAGE_INVALID_VALUE}`); | ||
} | ||
labels[key] = value; | ||
} | ||
@@ -147,3 +148,3 @@ return labels; | ||
static isValidAndNotEmpty(name) { | ||
return name && name.length > 0 && CoreResource.isValid(name); | ||
return name.length > 0 && CoreResource.isValid(name); | ||
} | ||
@@ -150,0 +151,0 @@ /** TEST_ONLY */ |
@@ -21,3 +21,3 @@ /** | ||
*/ | ||
readonly type: string; | ||
readonly type: string | null; | ||
/** | ||
@@ -24,0 +24,0 @@ * A dictionary of labels with string keys and values that provide information |
@@ -36,6 +36,6 @@ /** | ||
* Converts tag values to label values. | ||
* @param tagValues | ||
* @param tagValues the list of tag values | ||
* @returns {LabelValue[]} List of label values | ||
*/ | ||
static tagValuesToLabelValues(tagValues: TagValue[]): LabelValue[]; | ||
static tagValuesToLabelValues(tagValues: Array<TagValue | null>): LabelValue[]; | ||
} |
@@ -75,3 +75,3 @@ "use strict"; | ||
* Converts tag values to label values. | ||
* @param tagValues | ||
* @param tagValues the list of tag values | ||
* @returns {LabelValue[]} List of label values | ||
@@ -78,0 +78,0 @@ */ |
@@ -19,5 +19,7 @@ /** | ||
export declare class Recorder { | ||
static addMeasurement(aggregationData: AggregationData, measurement: Measurement): AggregationData; | ||
static addMeasurement(aggregationData: AggregationData, measurement: Measurement, attachments?: { | ||
[key: string]: string; | ||
}): AggregationData; | ||
/** Gets the tag values from tags and columns */ | ||
static getTagValues(tags: Map<TagKey, TagValue>, columns: TagKey[]): TagValue[]; | ||
static getTagValues(tags: Map<TagKey, TagValue>, columns: TagKey[]): Array<TagValue | null>; | ||
private static addToDistribution; | ||
@@ -24,0 +26,0 @@ private static addToSum; |
@@ -21,3 +21,3 @@ "use strict"; | ||
class Recorder { | ||
static addMeasurement(aggregationData, measurement) { | ||
static addMeasurement(aggregationData, measurement, attachments) { | ||
aggregationData.timestamp = Date.now(); | ||
@@ -29,3 +29,3 @@ const value = measurement.measure.type === types_1.MeasureType.DOUBLE ? | ||
case types_1.AggregationType.DISTRIBUTION: | ||
return this.addToDistribution(aggregationData, value); | ||
return this.addToDistribution(aggregationData, value, attachments); | ||
case types_1.AggregationType.SUM: | ||
@@ -44,3 +44,3 @@ return this.addToSum(aggregationData, value); | ||
} | ||
static addToDistribution(distributionData, value) { | ||
static addToDistribution(distributionData, value, attachments) { | ||
distributionData.count += 1; | ||
@@ -51,3 +51,6 @@ let bucketIndex = distributionData.buckets.findIndex(bucket => bucket > value); | ||
} | ||
distributionData.bucketCounts[bucketIndex] += 1; | ||
if (distributionData.bucketCounts && | ||
distributionData.bucketCounts.length > bucketIndex) { | ||
distributionData.bucketCounts[bucketIndex] += 1; | ||
} | ||
if (distributionData.count === 1) { | ||
@@ -64,2 +67,12 @@ distributionData.mean = value; | ||
distributionData.stdDeviation = Math.sqrt(distributionData.sumOfSquaredDeviation / distributionData.count); | ||
// No implicit recording for exemplars - if there are no attachments | ||
// (contextual information), don't record exemplars. | ||
if (attachments && distributionData.exemplars && | ||
distributionData.exemplars.length > bucketIndex) { | ||
distributionData.exemplars[bucketIndex] = { | ||
value, | ||
timestamp: distributionData.timestamp, | ||
attachments | ||
}; | ||
} | ||
return distributionData; | ||
@@ -66,0 +79,0 @@ } |
@@ -18,2 +18,3 @@ /** | ||
import { StatsEventListener } from '../exporters/types'; | ||
import * as cls from '../internal/cls'; | ||
import { Metric } from '../metrics/export/types'; | ||
@@ -32,2 +33,4 @@ import { TagMap } from '../tags/tag-map'; | ||
private static singletonInstance; | ||
/** Manage context automatic propagation */ | ||
private contextManager; | ||
/** | ||
@@ -52,4 +55,4 @@ * Creates stats | ||
* @param description The view description | ||
* @param bucketBoundaries The view bucket boundaries for a distribution | ||
* aggregation type | ||
* @param bucketBoundaries An optional The view bucket boundaries for a | ||
* distribution aggregation type | ||
*/ | ||
@@ -63,6 +66,12 @@ createView(name: string, measure: Measure, aggregation: AggregationType, tagKeys: TagKey[], description: string, bucketBoundaries?: number[]): View; | ||
/** | ||
* Unregisters an exporter. It should be called whenever the exporter is not | ||
* needed anymore. | ||
* @param exporter An stats exporter | ||
*/ | ||
unregisterExporter(exporter: StatsEventListener): void; | ||
/** | ||
* Creates a measure of type Double. | ||
* @param name The measure name | ||
* @param unit The measure unit | ||
* @param description The measure description | ||
* @param description An optional measure description | ||
*/ | ||
@@ -75,3 +84,3 @@ createMeasureDouble(name: string, unit: MeasureUnit, description?: string): Measure; | ||
* @param unit The measure unit | ||
* @param description The measure description | ||
* @param description An optional measure description | ||
*/ | ||
@@ -94,6 +103,11 @@ createMeasureInt64(name: string, unit: MeasureUnit, description?: string): Measure; | ||
* @param tags optional The tags to which the value is applied. | ||
* tags could either be explicitly passed to the method, or implicitly | ||
* read from current execution context. | ||
* tags could either be explicitly passed to the method, or implicitly | ||
* read from current execution context. | ||
* @param attachments optional The contextual information associated with an | ||
* example value. THe contextual information is represented as key - value | ||
* string pairs. | ||
*/ | ||
record(measurements: Measurement[], tags?: TagMap): void; | ||
record(measurements: Measurement[], tags?: TagMap, attachments?: { | ||
[key: string]: string; | ||
}): void; | ||
/** | ||
@@ -103,2 +117,12 @@ * Remove all registered Views and exporters from the stats. | ||
clear(): void; | ||
/** | ||
* Enters the scope of code where the given `TagMap` is in the current context | ||
* (replacing the previous `TagMap`). | ||
* @param tags The TagMap to be set to the current context. | ||
* @param fn Callback function. | ||
* @returns The callback return. | ||
*/ | ||
withTagContext<T>(tags: TagMap, fn: cls.Func<T>): T; | ||
/** Gets the current tag context. */ | ||
getCurrentTagContext(): TagMap; | ||
} |
@@ -19,4 +19,5 @@ "use strict"; | ||
const defaultLogger = require("../common/console-logger"); | ||
const cls = require("../internal/cls"); | ||
const metrics_1 = require("../metrics/metrics"); | ||
const tag_map_1 = require("../tags/tag-map"); | ||
const tagger = require("../tags/tagger"); | ||
const metric_producer_1 = require("./metric-producer"); | ||
@@ -36,2 +37,3 @@ const types_1 = require("./types"); | ||
this.logger = logger.logger(); | ||
this.contextManager = cls.getNamespace(); | ||
// Create a new MetricProducerForStats and register it to | ||
@@ -70,4 +72,4 @@ // MetricProducerManager when Stats is initialized. | ||
* @param description The view description | ||
* @param bucketBoundaries The view bucket boundaries for a distribution | ||
* aggregation type | ||
* @param bucketBoundaries An optional The view bucket boundaries for a | ||
* distribution aggregation type | ||
*/ | ||
@@ -92,6 +94,17 @@ createView(name, measure, aggregation, tagKeys, description, bucketBoundaries) { | ||
/** | ||
* Unregisters an exporter. It should be called whenever the exporter is not | ||
* needed anymore. | ||
* @param exporter An stats exporter | ||
*/ | ||
unregisterExporter(exporter) { | ||
if (exporter) { | ||
this.statsEventListeners = this.statsEventListeners.filter(currentExporter => currentExporter !== exporter); | ||
exporter.stop(); | ||
} | ||
} | ||
/** | ||
* Creates a measure of type Double. | ||
* @param name The measure name | ||
* @param unit The measure unit | ||
* @param description The measure description | ||
* @param description An optional measure description | ||
*/ | ||
@@ -106,3 +119,3 @@ createMeasureDouble(name, unit, description) { | ||
* @param unit The measure unit | ||
* @param description The measure description | ||
* @param description An optional measure description | ||
*/ | ||
@@ -137,6 +150,9 @@ createMeasureInt64(name, unit, description) { | ||
* @param tags optional The tags to which the value is applied. | ||
* tags could either be explicitly passed to the method, or implicitly | ||
* read from current execution context. | ||
* tags could either be explicitly passed to the method, or implicitly | ||
* read from current execution context. | ||
* @param attachments optional The contextual information associated with an | ||
* example value. THe contextual information is represented as key - value | ||
* string pairs. | ||
*/ | ||
record(measurements, tags) { | ||
record(measurements, tags, attachments) { | ||
if (this.hasNegativeValue(measurements)) { | ||
@@ -148,4 +164,4 @@ this.logger.warn(`Dropping measurments ${measurements}, value to record | ||
if (!tags) { | ||
// TODO(mayurkale): read tags current execution context | ||
tags = new tag_map_1.TagMap(); | ||
// Record against implicit (current) context | ||
tags = this.getCurrentTagContext(); | ||
} | ||
@@ -159,3 +175,3 @@ for (const measurement of measurements) { | ||
for (const view of views) { | ||
view.recordMeasurement(measurement, tags); | ||
view.recordMeasurement(measurement, tags, attachments); | ||
} | ||
@@ -175,4 +191,18 @@ // Notifies all exporters | ||
} | ||
/** | ||
* Enters the scope of code where the given `TagMap` is in the current context | ||
* (replacing the previous `TagMap`). | ||
* @param tags The TagMap to be set to the current context. | ||
* @param fn Callback function. | ||
* @returns The callback return. | ||
*/ | ||
withTagContext(tags, fn) { | ||
return tagger.withTagContext(this.contextManager, tags, fn); | ||
} | ||
/** Gets the current tag context. */ | ||
getCurrentTagContext() { | ||
return tagger.getCurrentTagContext(this.contextManager); | ||
} | ||
} | ||
exports.BaseStats = BaseStats; | ||
//# sourceMappingURL=stats.js.map |
@@ -17,2 +17,3 @@ /** | ||
import { StatsEventListener } from '../exporters/types'; | ||
import * as cls from '../internal/cls'; | ||
import { Metric } from '../metrics/export/types'; | ||
@@ -31,3 +32,3 @@ import { TagMap } from '../tags/tag-map'; | ||
* @param bucketBoundaries The view bucket boundaries for a distribution | ||
* aggregation type | ||
* aggregation type | ||
*/ | ||
@@ -59,6 +60,11 @@ createView(name: string, measure: Measure, aggregation: AggregationType, tagKeys: TagKey[], description: string, bucketBoundaries?: number[]): View; | ||
* @param tags optional The tags to which the value is applied. | ||
* tags could either be explicitly passed to the method, or implicitly | ||
* read from current execution context. | ||
* tags could either be explicitly passed to the method, or implicitly | ||
* read from current execution context. | ||
* @param attachments optional The contextual information associated with an | ||
* example value. The contextual information is represented as key - value | ||
* string pairs. | ||
*/ | ||
record(measurements: Measurement[], tags?: TagMap): void; | ||
record(measurements: Measurement[], tags?: TagMap, attachments?: { | ||
[key: string]: string; | ||
}): void; | ||
/** | ||
@@ -78,2 +84,18 @@ * Remove all registered Views and exporters from the stats. | ||
registerExporter(exporter: StatsEventListener): void; | ||
/** | ||
* Unregisters an exporter. It should be called whenever the exporter is not | ||
* needed anymore. | ||
* @param exporter An stats exporter | ||
*/ | ||
unregisterExporter(exporter: StatsEventListener): void; | ||
/** | ||
* Enters the scope of code where the given `TagMap` is in the current context | ||
* (replacing the previous `TagMap`). | ||
* @param tags The TagMap to be set to the current context. | ||
* @param fn Callback function. | ||
* @returns The callback return. | ||
*/ | ||
withTagContext<T>(tags: TagMap, fn: cls.Func<T>): T; | ||
/** Gets the current tag context. */ | ||
getCurrentTagContext(): TagMap; | ||
} | ||
@@ -152,3 +174,3 @@ /** | ||
*/ | ||
endTime: number; | ||
endTime?: number; | ||
/** true if the view was registered */ | ||
@@ -163,4 +185,9 @@ registered: boolean; | ||
* @param tags The tags to which the value is applied | ||
* @param attachments optional The contextual information associated with an | ||
* example value. THe contextual information is represented as key - value | ||
* string pairs. | ||
*/ | ||
recordMeasurement(measurement: Measurement, tags: TagMap): void; | ||
recordMeasurement(measurement: Measurement, tags: TagMap, attachments?: { | ||
[key: string]: string; | ||
}): void; | ||
/** | ||
@@ -170,3 +197,3 @@ * Returns a snapshot of an AggregationData for that tags/labels values. | ||
*/ | ||
getSnapshot(tagValues: TagValue[]): AggregationData; | ||
getSnapshot(tagValues: Array<TagValue | null>): AggregationData; | ||
/** Gets the view's tag keys */ | ||
@@ -192,3 +219,3 @@ getColumns(): TagKey[]; | ||
/** The tagValues that this AggregationData collects and aggregates */ | ||
readonly tagValues: TagValue[]; | ||
readonly tagValues: Array<TagValue | null>; | ||
/** The latest timestamp a new data point was recorded */ | ||
@@ -248,4 +275,24 @@ timestamp: number; | ||
bucketCounts?: number[]; | ||
/** If the distribution does not have a histogram, then omit this field. */ | ||
exemplars?: StatsExemplar[]; | ||
} | ||
/** | ||
* Exemplars are example points that may be used to annotate aggregated | ||
* Distribution values. They are metadata that gives information about a | ||
* particular value added to a Distribution bucket. | ||
*/ | ||
export interface StatsExemplar { | ||
/** | ||
* Value of the exemplar point. It determines which bucket the exemplar | ||
* belongs to. | ||
*/ | ||
readonly value: number; | ||
/** The observation (sampling) time of the above value. */ | ||
readonly timestamp: number; | ||
/** Contextual information about the example value. */ | ||
readonly attachments: { | ||
[key: string]: string; | ||
}; | ||
} | ||
export declare type Bucket = number; | ||
export declare type AggregationData = SumData | CountData | LastValueData | DistributionData; |
@@ -21,2 +21,6 @@ /** | ||
import { AggregationData, AggregationType, Measure, Measurement, View } from './types'; | ||
/** | ||
* A View specifies an aggregation and a set of tag keys. The aggregation will | ||
* be broken down by the unique set of matching tag values for each measure. | ||
*/ | ||
export declare class BaseView implements View { | ||
@@ -51,3 +55,3 @@ /** | ||
/** The bucket boundaries in a Distribution Aggregation */ | ||
private bucketBoundaries; | ||
private bucketBoundaries?; | ||
/** | ||
@@ -61,3 +65,3 @@ * Cache a MetricDescriptor to avoid converting View to MetricDescriptor | ||
*/ | ||
endTime: number; | ||
endTime?: number; | ||
/** true if the view was registered */ | ||
@@ -76,3 +80,3 @@ registered: boolean; | ||
* @param bucketBoundaries The view bucket boundaries for a distribution | ||
* aggregation type | ||
* aggregation type | ||
* @param logger | ||
@@ -90,4 +94,9 @@ */ | ||
* @param tags The tags to which the value is applied | ||
* @param attachments optional The contextual information associated with an | ||
* example value. The contextual information is represented as key - value | ||
* string pairs. | ||
*/ | ||
recordMeasurement(measurement: Measurement, tags: TagMap): void; | ||
recordMeasurement(measurement: Measurement, tags: TagMap, attachments?: { | ||
[key: string]: string; | ||
}): void; | ||
/** | ||
@@ -121,5 +130,7 @@ * Encodes a TagValue object into a value sorted string. | ||
*/ | ||
getSnapshot(tagValues: TagValue[]): AggregationData; | ||
getSnapshot(tagValues: Array<TagValue | null>): AggregationData; | ||
/** Returns a Bucket with count and examplar (if present) */ | ||
private getMetricBucket; | ||
/** Determines whether the given TagKeys are valid. */ | ||
private validateTagKeys; | ||
} |
@@ -27,2 +27,6 @@ "use strict"; | ||
const RECORD_SEPARATOR = String.fromCharCode(30); | ||
/** | ||
* A View specifies an aggregation and a set of tag keys. The aggregation will | ||
* be broken down by the unique set of matching tag values for each measure. | ||
*/ | ||
class BaseView { | ||
@@ -38,3 +42,3 @@ /** | ||
* @param bucketBoundaries The view bucket boundaries for a distribution | ||
* aggregation type | ||
* aggregation type | ||
* @param logger | ||
@@ -62,3 +66,5 @@ */ | ||
this.startTime = Date.now(); | ||
this.bucketBoundaries = new bucket_boundaries_1.BucketBoundaries(bucketBoundaries); | ||
if (bucketBoundaries) { | ||
this.bucketBoundaries = new bucket_boundaries_1.BucketBoundaries(bucketBoundaries); | ||
} | ||
this.metricDescriptor = metric_utils_1.MetricUtils.viewToMetricDescriptor(this); | ||
@@ -77,4 +83,7 @@ } | ||
* @param tags The tags to which the value is applied | ||
* @param attachments optional The contextual information associated with an | ||
* example value. The contextual information is represented as key - value | ||
* string pairs. | ||
*/ | ||
recordMeasurement(measurement, tags) { | ||
recordMeasurement(measurement, tags, attachments) { | ||
const tagValues = recorder_1.Recorder.getTagValues(tags.tags, this.columns); | ||
@@ -86,3 +95,3 @@ const encodedTags = this.encodeTagValues(tagValues); | ||
} | ||
recorder_1.Recorder.addMeasurement(this.tagValueAggregationMap[encodedTags], measurement); | ||
recorder_1.Recorder.addMeasurement(this.tagValueAggregationMap[encodedTags], measurement, attachments); | ||
} | ||
@@ -104,8 +113,9 @@ /** | ||
const aggregationMetadata = { tagValues, timestamp: Date.now() }; | ||
const { buckets, bucketCounts } = this.bucketBoundaries; | ||
const bucketsCopy = Object.assign([], buckets); | ||
const bucketCountsCopy = Object.assign([], bucketCounts); | ||
switch (this.aggregation) { | ||
case types_2.AggregationType.DISTRIBUTION: | ||
return Object.assign({}, aggregationMetadata, { type: types_2.AggregationType.DISTRIBUTION, startTime: this.startTime, count: 0, sum: 0, mean: null, stdDeviation: null, sumOfSquaredDeviation: null, buckets: bucketsCopy, bucketCounts: bucketCountsCopy }); | ||
const { buckets, bucketCounts } = this.bucketBoundaries; | ||
const bucketsCopy = Object.assign([], buckets); | ||
const bucketCountsCopy = Object.assign([], bucketCounts); | ||
const exemplars = new Array(bucketCounts.length); | ||
return Object.assign({}, aggregationMetadata, { type: types_2.AggregationType.DISTRIBUTION, startTime: this.startTime, count: 0, sum: 0, mean: 0, stdDeviation: 0, sumOfSquaredDeviation: 0, buckets: bucketsCopy, bucketCounts: bucketCountsCopy, exemplars }); | ||
case types_2.AggregationType.SUM: | ||
@@ -116,3 +126,3 @@ return Object.assign({}, aggregationMetadata, { type: types_2.AggregationType.SUM, value: 0 }); | ||
default: | ||
return Object.assign({}, aggregationMetadata, { type: types_2.AggregationType.LAST_VALUE, value: undefined }); | ||
return Object.assign({}, aggregationMetadata, { type: types_2.AggregationType.LAST_VALUE, value: 0 }); | ||
} | ||
@@ -130,9 +140,5 @@ } | ||
const now = time_util_1.getTimestampWithProcessHRTime(); | ||
switch (type) { | ||
case types_1.MetricDescriptorType.GAUGE_INT64: | ||
case types_1.MetricDescriptorType.GAUGE_DOUBLE: | ||
startTimestamp = null; | ||
break; | ||
default: | ||
startTimestamp = time_util_1.timestampFromMillis(start); | ||
if (type !== types_1.MetricDescriptorType.GAUGE_INT64 && | ||
type !== types_1.MetricDescriptorType.GAUGE_DOUBLE) { | ||
startTimestamp = time_util_1.timestampFromMillis(start); | ||
} | ||
@@ -162,4 +168,11 @@ const timeseries = []; | ||
if (data.type === types_2.AggregationType.DISTRIBUTION) { | ||
// TODO: Add examplar transition | ||
const { count, sum, sumOfSquaredDeviation } = data; | ||
const { count, sum, sumOfSquaredDeviation, exemplars } = data; | ||
const buckets = []; | ||
if (data.bucketCounts) { | ||
for (let bucket = 0; bucket < data.bucketCounts.length; bucket++) { | ||
const bucketCount = data.bucketCounts[bucket]; | ||
const statsExemplar = exemplars ? exemplars[bucket] : undefined; | ||
buckets.push(this.getMetricBucket(bucketCount, statsExemplar)); | ||
} | ||
} | ||
value = { | ||
@@ -169,5 +182,4 @@ count, | ||
sumOfSquaredDeviation, | ||
buckets, | ||
bucketOptions: { explicit: { bounds: data.buckets } }, | ||
// Bucket without an Exemplar. | ||
buckets: data.bucketCounts.map(bucketCount => ({ count: bucketCount })) | ||
}; | ||
@@ -188,2 +200,18 @@ } | ||
} | ||
/** Returns a Bucket with count and examplar (if present) */ | ||
getMetricBucket(bucketCount, statsExemplar) { | ||
if (statsExemplar) { | ||
// Bucket with an Exemplar. | ||
return { | ||
count: bucketCount, | ||
exemplar: { | ||
value: statsExemplar.value, | ||
timestamp: time_util_1.timestampFromMillis(statsExemplar.timestamp), | ||
attachments: statsExemplar.attachments | ||
} | ||
}; | ||
} | ||
// Bucket with no Exemplar. | ||
return { count: bucketCount }; | ||
} | ||
/** Determines whether the given TagKeys are valid. */ | ||
@@ -197,3 +225,3 @@ validateTagKeys(tagKeys) { | ||
}); | ||
const tagKeysSet = new Set(tagKeysCopy.map(tagKey => tagKey.name)); | ||
const tagKeysSet = new Set(tagKeysCopy.map((tagKey) => tagKey.name)); | ||
if (tagKeysSet.size !== tagKeysCopy.length) { | ||
@@ -200,0 +228,0 @@ throw new Error('Columns have duplicate'); |
/** | ||
* Copyright 2019, OpenCensus Authors | ||
* | ||
* Licensed under the Apache License, Version 2.0 the "License"; | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
@@ -16,12 +16,28 @@ * You may obtain a copy of the License at | ||
*/ | ||
import { TagKey, TagValue } from './types'; | ||
/** TagMap is maps of TagKey -> TagValue */ | ||
import { TagKey, TagMetadata, TagValue, TagValueWithMetadata } from './types'; | ||
/** TagMap is maps of TagKey -> TagValueWithMetadata */ | ||
export declare class TagMap { | ||
private readonly registeredTags; | ||
/** Adds the key/value pair regardless of whether the key is present. */ | ||
set(tagKey: TagKey, tagValue: TagValue): void; | ||
/** Deletes a tag from the map if the key is in the map. */ | ||
/** | ||
* Adds the key/value pair regardless of whether the key is present. | ||
* @param tagKey The TagKey which will be set. | ||
* @param tagValue The TagValue to set for the given key. | ||
* @param tagMetadata The TagMetadata associated with this Tag. | ||
*/ | ||
set(tagKey: TagKey, tagValue: TagValue, tagMetadata?: TagMetadata): void; | ||
/** | ||
* Deletes a tag from the map if the key is in the map. | ||
* @param tagKey The TagKey which will be removed. | ||
*/ | ||
delete(tagKey: TagKey): void; | ||
/** Gets the tags map. */ | ||
/** Gets the tags map without metadata. */ | ||
readonly tags: Map<TagKey, TagValue>; | ||
/** Gets the tags map with metadata. */ | ||
readonly tagsWithMetadata: Map<TagKey, TagValueWithMetadata>; | ||
/** | ||
* Constructs a new TagValueWithMetadata using tagValue and tagMetadata. | ||
* For backwards-compatibility this method still produces propagating Tags | ||
* (UNLIMITED_PROPAGATION) if tagMetadata is not provided or missing. | ||
*/ | ||
private getValueWithMetadata; | ||
} |
@@ -5,3 +5,3 @@ "use strict"; | ||
* | ||
* Licensed under the Apache License, Version 2.0 the "License"; | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
@@ -19,11 +19,20 @@ * You may obtain a copy of the License at | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const types_1 = require("./types"); | ||
const validation_1 = require("./validation"); | ||
/** TagMap is maps of TagKey -> TagValue */ | ||
const UNLIMITED_PROPAGATION_MD = { | ||
tagTtl: types_1.TagTtl.UNLIMITED_PROPAGATION | ||
}; | ||
/** TagMap is maps of TagKey -> TagValueWithMetadata */ | ||
class TagMap { | ||
constructor() { | ||
// A map mapping TagKey to to its respective TagValue. | ||
// A map mapping TagKey to to its respective TagValueWithMetadata. | ||
this.registeredTags = new Map(); | ||
} | ||
/** Adds the key/value pair regardless of whether the key is present. */ | ||
set(tagKey, tagValue) { | ||
/** | ||
* Adds the key/value pair regardless of whether the key is present. | ||
* @param tagKey The TagKey which will be set. | ||
* @param tagValue The TagValue to set for the given key. | ||
* @param tagMetadata The TagMetadata associated with this Tag. | ||
*/ | ||
set(tagKey, tagValue, tagMetadata) { | ||
if (!validation_1.isValidTagKey(tagKey)) { | ||
@@ -35,14 +44,46 @@ throw new Error(`Invalid TagKey name: ${tagKey.name}`); | ||
} | ||
this.registeredTags.set(tagKey, tagValue); | ||
let existingKey; | ||
for (const key of this.registeredTags.keys()) { | ||
if (key.name === tagKey.name) { | ||
existingKey = key; | ||
break; | ||
} | ||
} | ||
if (existingKey) | ||
this.registeredTags.delete(existingKey); | ||
const valueWithMetadata = this.getValueWithMetadata(tagValue, tagMetadata); | ||
this.registeredTags.set(tagKey, valueWithMetadata); | ||
} | ||
/** Deletes a tag from the map if the key is in the map. */ | ||
/** | ||
* Deletes a tag from the map if the key is in the map. | ||
* @param tagKey The TagKey which will be removed. | ||
*/ | ||
delete(tagKey) { | ||
this.registeredTags.delete(tagKey); | ||
} | ||
/** Gets the tags map. */ | ||
/** Gets the tags map without metadata. */ | ||
get tags() { | ||
const tagsWithoutMetadata = new Map(); | ||
for (const [tagKey, valueWithMetadata] of this.registeredTags) { | ||
tagsWithoutMetadata.set(tagKey, valueWithMetadata.tagValue); | ||
} | ||
return tagsWithoutMetadata; | ||
} | ||
/** Gets the tags map with metadata. */ | ||
get tagsWithMetadata() { | ||
return this.registeredTags; | ||
} | ||
/** | ||
* Constructs a new TagValueWithMetadata using tagValue and tagMetadata. | ||
* For backwards-compatibility this method still produces propagating Tags | ||
* (UNLIMITED_PROPAGATION) if tagMetadata is not provided or missing. | ||
*/ | ||
getValueWithMetadata(tagValue, tagMetadata) { | ||
if (tagMetadata) { | ||
return { tagValue, tagMetadata }; | ||
} | ||
return { tagValue, tagMetadata: UNLIMITED_PROPAGATION_MD }; | ||
} | ||
} | ||
exports.TagMap = TagMap; | ||
//# sourceMappingURL=tag-map.js.map |
@@ -26,1 +26,32 @@ /** | ||
} | ||
/** TagValueWithMetadata holds a TagValue and a TagMetadata. */ | ||
export interface TagValueWithMetadata { | ||
/** The tag value */ | ||
readonly tagValue: TagValue; | ||
/** The metadata for the tag */ | ||
readonly tagMetadata: TagMetadata; | ||
} | ||
/** | ||
* TagMetadata contains properties associated with a Tag. | ||
* Anytime a sender serializes a tag, sends it over the wire and receiver | ||
* deserializes the tag then the tag is considered to have travelled one hop. | ||
* There could be one or more proxy(ies) between sender and receiver. Proxies | ||
* are treated as transparent entities and they do not create additional hops. | ||
*/ | ||
export interface TagMetadata { | ||
/** | ||
* For now, only special values of TagTtl are supported. In future, | ||
* additional properties may be added to address specific situations. | ||
*/ | ||
readonly tagTtl: number; | ||
} | ||
/** TagTtl is an integer that represents number of hops a tag can propagate */ | ||
export declare enum TagTtl { | ||
/** | ||
* NO_PROPAGATION is considered to have local scope and is used within the | ||
* process it created. | ||
*/ | ||
NO_PROPAGATION = 0, | ||
/** UNLIMITED_PROPAGATION can propagate unlimited hops. */ | ||
UNLIMITED_PROPAGATION = -1 | ||
} |
@@ -18,2 +18,13 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
/** TagTtl is an integer that represents number of hops a tag can propagate */ | ||
var TagTtl; | ||
(function (TagTtl) { | ||
/** | ||
* NO_PROPAGATION is considered to have local scope and is used within the | ||
* process it created. | ||
*/ | ||
TagTtl[TagTtl["NO_PROPAGATION"] = 0] = "NO_PROPAGATION"; | ||
/** UNLIMITED_PROPAGATION can propagate unlimited hops. */ | ||
TagTtl[TagTtl["UNLIMITED_PROPAGATION"] = -1] = "UNLIMITED_PROPAGATION"; | ||
})(TagTtl = exports.TagTtl || (exports.TagTtl = {})); | ||
//# sourceMappingURL=types.js.map |
/** | ||
* Copyright 2019, OpenCensus Authors | ||
* | ||
* Licensed under the Apache License, Version 2.0 the "License"; | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
@@ -6,0 +6,0 @@ * You may obtain a copy of the License at |
@@ -5,3 +5,3 @@ "use strict"; | ||
* | ||
* Licensed under the Apache License, Version 2.0 the "License"; | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
@@ -8,0 +8,0 @@ * You may obtain a copy of the License at |
@@ -18,2 +18,3 @@ /** | ||
import { Exporter } from '../../exporters/types'; | ||
import { Stats } from '../../stats/types'; | ||
import { PluginNames } from '../instrumentation/types'; | ||
@@ -68,2 +69,4 @@ import { Propagation } from '../propagation/types'; | ||
logger?: Logger; | ||
/** An instance of a stats */ | ||
stats?: Stats; | ||
} | ||
@@ -70,0 +73,0 @@ /** Global configuration of trace service */ |
@@ -0,2 +1,18 @@ | ||
/** | ||
* Copyright 2018, OpenCensus Authors | ||
* | ||
* 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 { Logger } from '../../common/types'; | ||
import { Stats } from '../../stats/types'; | ||
import * as modelTypes from '../model/types'; | ||
@@ -30,2 +46,4 @@ import * as types from './types'; | ||
protected options: types.PluginConfig; | ||
/** A stats object. */ | ||
protected stats?: Stats; | ||
/** | ||
@@ -43,2 +61,3 @@ * Constructs a new BasePlugin instance. | ||
* @param basedir module absolute path | ||
* @param stats a stats instance | ||
*/ | ||
@@ -57,5 +76,6 @@ private setPluginContext; | ||
* @param options plugin options | ||
* @param basedir module absolute path | ||
* @param basedir an optional module absolute path | ||
* @param stats an optional stats instance | ||
*/ | ||
enable<T>(moduleExports: T, tracer: modelTypes.Tracer, version: string, options: types.PluginConfig, basedir: string): any; | ||
enable<T>(moduleExports: T, tracer: modelTypes.Tracer, version: string, options: types.PluginConfig, basedir?: string, stats?: Stats): any; | ||
/** Method to disable the instrumentation */ | ||
@@ -62,0 +82,0 @@ disable(): void; |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
/** | ||
@@ -18,4 +17,6 @@ * Copyright 2018, OpenCensus Authors | ||
*/ | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const path = require("path"); | ||
const semver = require("semver"); | ||
const noop_logger_1 = require("../../common/noop-logger"); | ||
/** This class represent the base to patch plugin. */ | ||
@@ -28,2 +29,4 @@ class BasePlugin { | ||
constructor(moduleName) { | ||
/** a logger */ | ||
this.logger = noop_logger_1.noopLogger; | ||
this.moduleName = moduleName; | ||
@@ -38,12 +41,15 @@ } | ||
* @param basedir module absolute path | ||
* @param stats a stats instance | ||
*/ | ||
setPluginContext( | ||
// tslint:disable-next-line:no-any | ||
moduleExports, tracer, version, options, basedir) { | ||
moduleExports, tracer, version, options, basedir, stats) { | ||
this.moduleExports = moduleExports; | ||
this.tracer = tracer; | ||
this.version = version; | ||
this.basedir = basedir; | ||
if (basedir) | ||
this.basedir = basedir; | ||
this.logger = tracer.logger; | ||
this.options = options; | ||
this.stats = stats; | ||
this.internalFilesExports = this.loadInternalFiles(); | ||
@@ -62,8 +68,7 @@ } | ||
* @param options plugin options | ||
* @param basedir module absolute path | ||
* @param basedir an optional module absolute path | ||
* @param stats an optional stats instance | ||
*/ | ||
enable( | ||
// tslint:disable-next-line:no-any | ||
moduleExports, tracer, version, options, basedir) { | ||
this.setPluginContext(moduleExports, tracer, version, options, basedir); | ||
enable(moduleExports, tracer, version, options, basedir, stats) { | ||
this.setPluginContext(moduleExports, tracer, version, options, basedir, stats); | ||
return this.applyPatch(); | ||
@@ -79,3 +84,3 @@ } | ||
loadInternalFiles() { | ||
let result = null; | ||
let result = {}; | ||
if (this.internalFileList) { | ||
@@ -91,3 +96,3 @@ this.logger.debug('loadInternalFiles %o', this.internalFileList); | ||
}); | ||
if (!result) { | ||
if (Object.keys(result).length === 0) { | ||
this.logger.debug('No internal file could be loaded for %s@%s', this.moduleName, this.version); | ||
@@ -94,0 +99,0 @@ } |
@@ -16,2 +16,3 @@ /** | ||
*/ | ||
import { Stats } from '../../stats/types'; | ||
import { Tracer } from '../model/types'; | ||
@@ -27,5 +28,6 @@ /** Interface Plugin to apply patch. */ | ||
* @param options plugin options | ||
* @param basedir module absolute path | ||
* @param basedir an optional module absolute path | ||
* @param stats an optional stats instance | ||
*/ | ||
enable(moduleExports: any, tracer: Tracer, version: string, options: PluginConfig, basedir?: string): any; | ||
enable<T>(moduleExports: T, tracer: Tracer, version: string, options: PluginConfig, basedir?: string, stats?: Stats): T; | ||
/** Method to disable the instrumentation */ | ||
@@ -32,0 +34,0 @@ disable(): void; |
@@ -27,11 +27,18 @@ /** | ||
/** Its trace state. */ | ||
private traceStateLocal; | ||
private traceStateLocal?; | ||
/** set isRootSpan = true */ | ||
readonly isRootSpan: boolean; | ||
/** A number of children. */ | ||
private numberOfChildrenLocal; | ||
/** | ||
* Constructs a new RootSpanImpl instance. | ||
* @param tracer A tracer object. | ||
* @param context A trace options object to build the root span. | ||
* @param name The displayed name for the new span. | ||
* @param kind The kind of new span. | ||
* @param traceId The trace Id. | ||
* @param parentSpanId The id of the parent span, or empty if the new span is | ||
* a root span. | ||
* @param traceState An optional traceState. | ||
*/ | ||
constructor(tracer: types.Tracer, context?: types.TraceOptions); | ||
constructor(tracer: types.Tracer, name: string, kind: types.SpanKind, traceId: string, parentSpanId: string, traceState?: types.TraceState); | ||
/** Gets span list from rootspan instance. */ | ||
@@ -42,3 +49,5 @@ readonly spans: types.Span[]; | ||
/** Gets trace state from rootspan instance */ | ||
readonly traceState: types.TraceState; | ||
readonly traceState: types.TraceState | undefined; | ||
/** Gets the number of child span created for this span. */ | ||
readonly numberOfChildren: number; | ||
/** Starts a rootspan instance. */ | ||
@@ -50,7 +59,6 @@ start(): void; | ||
* Starts a new child span in the root span. | ||
* @param name Span name. | ||
* @param kind Span kind. | ||
* @param parentSpanId Span parent ID. | ||
* @param nameOrOptions Span name string or SpanOptions object. | ||
* @param kind Span kind if not using SpanOptions object. | ||
*/ | ||
startChildSpan(name: string, kind: types.SpanKind, parentSpanId?: string): types.Span; | ||
startChildSpan(nameOrOptions?: string | types.SpanOptions, kind?: types.SpanKind): types.Span; | ||
} |
@@ -18,7 +18,6 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const uuid = require("uuid"); | ||
const logger = require("../../common/console-logger"); | ||
const no_record_span_1 = require("./no-record/no-record-span"); | ||
const span_1 = require("./span"); | ||
const span_base_1 = require("./span-base"); | ||
const types = require("./types"); | ||
/** Defines a root span */ | ||
@@ -29,5 +28,10 @@ class RootSpan extends span_base_1.SpanBase { | ||
* @param tracer A tracer object. | ||
* @param context A trace options object to build the root span. | ||
* @param name The displayed name for the new span. | ||
* @param kind The kind of new span. | ||
* @param traceId The trace Id. | ||
* @param parentSpanId The id of the parent span, or empty if the new span is | ||
* a root span. | ||
* @param traceState An optional traceState. | ||
*/ | ||
constructor(tracer, context) { | ||
constructor(tracer, name, kind, traceId, parentSpanId, traceState) { | ||
super(); | ||
@@ -37,16 +41,13 @@ /** set isRootSpan = true */ | ||
this.tracer = tracer; | ||
this.traceIdLocal = | ||
context && context.spanContext && context.spanContext.traceId ? | ||
context.spanContext.traceId : | ||
(uuid.v4().split('-').join('')); | ||
this.name = context && context.name ? context.name : 'undefined'; | ||
if (context && context.spanContext) { | ||
this.parentSpanId = context.spanContext.spanId || ''; | ||
this.traceStateLocal = context.spanContext.traceState; | ||
this.traceIdLocal = traceId; | ||
this.name = name; | ||
this.kind = kind; | ||
this.parentSpanId = parentSpanId; | ||
if (traceState) { | ||
this.traceStateLocal = traceState; | ||
} | ||
this.spansLocal = []; | ||
this.kind = | ||
context && context.kind ? context.kind : types.SpanKind.UNSPECIFIED; | ||
this.logger = tracer.logger || logger.logger(); | ||
this.activeTraceParams = tracer.activeTraceParams; | ||
this.numberOfChildrenLocal = 0; | ||
} | ||
@@ -65,2 +66,6 @@ /** Gets span list from rootspan instance. */ | ||
} | ||
/** Gets the number of child span created for this span. */ | ||
get numberOfChildren() { | ||
return this.numberOfChildrenLocal; | ||
} | ||
/** Starts a rootspan instance. */ | ||
@@ -89,25 +94,25 @@ start() { | ||
* Starts a new child span in the root span. | ||
* @param name Span name. | ||
* @param kind Span kind. | ||
* @param parentSpanId Span parent ID. | ||
* @param nameOrOptions Span name string or SpanOptions object. | ||
* @param kind Span kind if not using SpanOptions object. | ||
*/ | ||
startChildSpan(name, kind, parentSpanId) { | ||
startChildSpan(nameOrOptions, kind) { | ||
if (this.ended) { | ||
this.logger.debug('calling %s.startSpan() on ended %s %o', this.className, this.className, { id: this.id, name: this.name, kind: this.kind }); | ||
return null; | ||
return new no_record_span_1.NoRecordSpan(); | ||
} | ||
if (!this.started) { | ||
this.logger.debug('calling %s.startSpan() on un-started %s %o', this.className, this.className, { id: this.id, name: this.name, kind: this.kind }); | ||
return null; | ||
return new no_record_span_1.NoRecordSpan(); | ||
} | ||
const newSpan = new span_1.Span(this); | ||
if (name) { | ||
newSpan.name = name; | ||
} | ||
if (kind) { | ||
newSpan.kind = kind; | ||
} | ||
newSpan.start(); | ||
this.spansLocal.push(newSpan); | ||
return newSpan; | ||
this.numberOfChildrenLocal++; | ||
const child = new span_1.Span(this); | ||
const spanName = typeof nameOrOptions === 'object' ? nameOrOptions.name : nameOrOptions; | ||
const spanKind = typeof nameOrOptions === 'object' ? nameOrOptions.kind : kind; | ||
if (spanName) | ||
child.name = spanName; | ||
if (spanKind) | ||
child.kind = spanKind; | ||
child.start(); | ||
this.spansLocal.push(child); | ||
return child; | ||
} | ||
@@ -114,0 +119,0 @@ } |
@@ -69,3 +69,3 @@ /** | ||
/** Gets the trace state */ | ||
abstract readonly traceState: types.TraceState; | ||
abstract readonly traceState: types.TraceState | undefined; | ||
/** Indicates if span was started. */ | ||
@@ -118,4 +118,7 @@ readonly started: boolean; | ||
* @param timestamp A time in milliseconds. Defaults to Date.now() | ||
* @param uncompressedSize The number of uncompressed bytes sent or received | ||
* @param compressedSize The number of compressed bytes sent or received. If | ||
* zero or undefined, assumed to be the same size as uncompressed. | ||
*/ | ||
addMessageEvent(type: types.MessageEventType, id: string, timestamp?: number): void; | ||
addMessageEvent(type: types.MessageEventType, id: number, timestamp?: number, uncompressedSize?: number, compressedSize?: number): void; | ||
/** | ||
@@ -122,0 +125,0 @@ * Sets a status to the span. |
"use strict"; | ||
/** | ||
* Copyright 2018, OpenCensus Authors | ||
* | ||
* 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. | ||
*/ | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const noop_logger_1 = require("../../common/noop-logger"); | ||
const clock_1 = require("../../internal/clock"); | ||
@@ -13,4 +29,2 @@ const util_1 = require("../../internal/util"); | ||
constructor() { | ||
/** The clock used to mesure the beginning and ending of a span */ | ||
this.clock = null; | ||
/** Indicates if this span was started */ | ||
@@ -23,2 +37,4 @@ this.startedLocal = false; | ||
this.truncated = false; | ||
/** An object to log information to */ | ||
this.logger = noop_logger_1.noopLogger; | ||
/** A set of attributes, each in the format [KEY]:[VALUE] */ | ||
@@ -32,6 +48,8 @@ this.attributes = {}; | ||
this.links = []; | ||
/** If the parent span is in another process. */ | ||
this.remoteParent = false; | ||
/** The span ID of this span's parent. If it's a root span, must be empty */ | ||
this.parentSpanId = null; | ||
this.parentSpanId = ''; | ||
/** The resource name of the span */ | ||
this.name = null; | ||
this.name = 'span'; | ||
/** Kind of span. */ | ||
@@ -41,2 +59,4 @@ this.kind = types.SpanKind.UNSPECIFIED; | ||
this.status = STATUS_OK; | ||
/** Trace Parameters */ | ||
this.activeTraceParams = {}; | ||
/** The number of dropped attributes. */ | ||
@@ -68,3 +88,3 @@ this.droppedAttributesCount = 0; | ||
this.logger.debug('calling startTime() on null clock'); | ||
return null; | ||
return new Date(); | ||
} | ||
@@ -80,3 +100,3 @@ return this.clock.startTime; | ||
this.logger.debug('calling endTime() on null clock'); | ||
return null; | ||
return new Date(); | ||
} | ||
@@ -92,3 +112,3 @@ return this.clock.endTime; | ||
this.logger.debug('calling duration() on null clock'); | ||
return null; | ||
return 0; | ||
} | ||
@@ -119,3 +139,5 @@ return this.clock.duration; | ||
const attributeKeyToDelete = Object.keys(this.attributes).shift(); | ||
delete this.attributes[attributeKeyToDelete]; | ||
if (attributeKeyToDelete) { | ||
delete this.attributes[attributeKeyToDelete]; | ||
} | ||
} | ||
@@ -138,3 +160,3 @@ this.attributes[key] = value; | ||
'description': description, | ||
'attributes': attributes, | ||
'attributes': attributes || {}, | ||
'timestamp': timestamp ? timestamp : Date.now(), | ||
@@ -159,3 +181,3 @@ }); | ||
'type': type, | ||
'attributes': attributes | ||
'attributes': attributes || {} | ||
}); | ||
@@ -168,4 +190,7 @@ } | ||
* @param timestamp A time in milliseconds. Defaults to Date.now() | ||
* @param uncompressedSize The number of uncompressed bytes sent or received | ||
* @param compressedSize The number of compressed bytes sent or received. If | ||
* zero or undefined, assumed to be the same size as uncompressed. | ||
*/ | ||
addMessageEvent(type, id, timestamp = 0) { | ||
addMessageEvent(type, id, timestamp = 0, uncompressedSize, compressedSize) { | ||
if (this.messageEvents.length >= | ||
@@ -177,5 +202,7 @@ this.activeTraceParams.numberOfMessageEventsPerSpan) { | ||
this.messageEvents.push({ | ||
'type': type, | ||
'id': id, | ||
'timestamp': timestamp ? timestamp : Date.now(), | ||
type, | ||
id, | ||
timestamp: timestamp ? timestamp : Date.now(), | ||
uncompressedSize, | ||
compressedSize, | ||
}); | ||
@@ -182,0 +209,0 @@ } |
@@ -30,3 +30,3 @@ /** | ||
readonly traceId: string; | ||
readonly traceState: string; | ||
readonly traceState: types.TraceState | undefined; | ||
/** Starts the span instance. */ | ||
@@ -33,0 +33,0 @@ start(): void; |
@@ -35,4 +35,2 @@ /** | ||
private eventListenersLocal; | ||
/** A list of ended root spans */ | ||
private endedTraces; | ||
/** Bit to represent whether trace is sampled or not. */ | ||
@@ -70,7 +68,5 @@ private readonly IS_SAMPLED; | ||
startRootSpan<T>(options: types.TraceOptions, fn: (root: types.RootSpan) => T): T; | ||
/** Notifies listeners of the span start. */ | ||
onStartSpan(root: types.RootSpan): void; | ||
/** | ||
* Is called when a span is ended. | ||
* @param root The ended span. | ||
*/ | ||
/** Notifies listeners of the span end. */ | ||
onEndSpan(root: types.RootSpan): void; | ||
@@ -93,7 +89,6 @@ /** | ||
* Starts a span. | ||
* @param name The span name. | ||
* @param kind optional The span kind. | ||
* @param parentSpanId The parent span ID. | ||
* @param nameOrOptions Span name string or SpanOptions object. | ||
* @param kind Span kind if not using SpanOptions object. | ||
*/ | ||
startChildSpan(name?: string, kind?: types.SpanKind): types.Span; | ||
startChildSpan(nameOrOptions?: string | types.SpanOptions, kind?: types.SpanKind): types.Span; | ||
/** | ||
@@ -112,5 +107,7 @@ * Binds the trace context to the given function. | ||
* @param emitter An event emitter whose handlers should have | ||
* the trace context binded to them. | ||
* the trace context binded to them. | ||
*/ | ||
wrapEmitter(emitter: NodeJS.EventEmitter): void; | ||
/** Determine whether to sample request or not. */ | ||
private makeSamplingDecision; | ||
} |
@@ -18,6 +18,11 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const uuid = require("uuid"); | ||
const logger = require("../../common/console-logger"); | ||
const cls = require("../../internal/cls"); | ||
const noop_propagation_1 = require("../propagation/noop-propagation"); | ||
const sampler_1 = require("../sampler/sampler"); | ||
const no_record_root_span_1 = require("./no-record/no-record-root-span"); | ||
const no_record_span_1 = require("./no-record/no-record-span"); | ||
const root_span_1 = require("./root-span"); | ||
const types = require("./types"); | ||
/** | ||
@@ -31,5 +36,2 @@ * This class represent a tracer. | ||
this.eventListenersLocal = []; | ||
/** A list of ended root spans */ | ||
// @ts-ignore | ||
this.endedTraces = []; | ||
/** Bit to represent whether trace is sampled or not. */ | ||
@@ -40,3 +42,3 @@ this.IS_SAMPLED = 0x1; | ||
this.activeLocal = false; | ||
this.contextManager = cls.createNamespace(); | ||
this.contextManager = cls.getNamespace(); | ||
this.clearCurrentTrace(); | ||
@@ -57,3 +59,6 @@ this.activeTraceParams = {}; | ||
get propagation() { | ||
return this.config ? this.config.propagation : null; | ||
if (this.config && this.config.propagation) { | ||
return this.config.propagation; | ||
} | ||
return noop_propagation_1.noopPropagation; | ||
} | ||
@@ -68,3 +73,4 @@ /** | ||
this.logger = this.config.logger || logger.logger(); | ||
this.sampler = sampler_1.SamplerBuilder.getSampler(config.samplingRate); | ||
this.sampler = | ||
sampler_1.SamplerBuilder.getSampler(config.samplingRate || sampler_1.DEFAULT_SAMPLING_RATE); | ||
if (config.traceParams) { | ||
@@ -102,24 +108,26 @@ this.activeTraceParams.numberOfAnnontationEventsPerSpan = | ||
return this.contextManager.runAndReturn((root) => { | ||
let newRoot = null; | ||
let traceId; | ||
if (options && options.spanContext && options.spanContext.traceId) { | ||
traceId = options.spanContext.traceId; | ||
} | ||
else { | ||
// New root span. | ||
traceId = uuid.v4().split('-').join(''); | ||
} | ||
const name = options && options.name ? options.name : 'span'; | ||
const kind = options && options.kind ? options.kind : types.SpanKind.UNSPECIFIED; | ||
let parentSpanId = ''; | ||
let traceState; | ||
if (options && options.spanContext) { | ||
// New child span. | ||
parentSpanId = options.spanContext.spanId || ''; | ||
traceState = options.spanContext.traceState; | ||
} | ||
if (this.active) { | ||
let propagatedSample = null; | ||
// if there is a context propagation, keep the decistion | ||
if (options && options.spanContext) { | ||
if (options.spanContext.options) { | ||
propagatedSample = | ||
((options.spanContext.options & this.IS_SAMPLED) !== 0); | ||
} | ||
if (!propagatedSample) { | ||
options.spanContext = null; | ||
} | ||
} | ||
const aRoot = new root_span_1.RootSpan(this, options); | ||
let sampleDecision = propagatedSample; | ||
if (!sampleDecision) { | ||
sampleDecision = this.sampler.shouldSample(aRoot.traceId); | ||
} | ||
const sampleDecision = this.makeSamplingDecision(options, traceId); | ||
if (sampleDecision) { | ||
this.currentRootSpan = aRoot; | ||
aRoot.start(); | ||
newRoot = aRoot; | ||
const rootSpan = new root_span_1.RootSpan(this, name, kind, traceId, parentSpanId, traceState); | ||
this.currentRootSpan = rootSpan; | ||
rootSpan.start(); | ||
return fn(rootSpan); | ||
} | ||
@@ -130,30 +138,31 @@ } | ||
} | ||
return fn(newRoot); | ||
const noRecordRootSpan = new no_record_root_span_1.NoRecordRootSpan(this, name, kind, traceId, parentSpanId, traceState); | ||
this.currentRootSpan = noRecordRootSpan; | ||
return fn(noRecordRootSpan); | ||
}); | ||
} | ||
/** Notifies listeners of the span start. */ | ||
onStartSpan(root) { | ||
if (this.active) { | ||
if (!root) { | ||
return this.logger.debug('cannot start trace - no active trace found'); | ||
} | ||
if (this.currentRootSpan !== root) { | ||
this.logger.debug('currentRootSpan != root on notifyStart. Need more investigation.'); | ||
} | ||
this.notifyStartSpan(root); | ||
if (!this.active) | ||
return; | ||
if (!root) { | ||
return this.logger.debug('cannot start trace - no active trace found'); | ||
} | ||
if (this.currentRootSpan !== root) { | ||
this.logger.debug('currentRootSpan != root on notifyStart. Need more investigation.'); | ||
} | ||
this.notifyStartSpan(root); | ||
} | ||
/** | ||
* Is called when a span is ended. | ||
* @param root The ended span. | ||
*/ | ||
/** Notifies listeners of the span end. */ | ||
onEndSpan(root) { | ||
if (this.active) { | ||
if (!root) { | ||
return this.logger.debug('cannot end trace - no active trace found'); | ||
} | ||
if (this.currentRootSpan !== root) { | ||
this.logger.debug('currentRootSpan != root on notifyEnd. Need more investigation.'); | ||
} | ||
this.notifyEndSpan(root); | ||
if (!this.active) | ||
return; | ||
if (!root) { | ||
this.logger.debug('cannot end trace - no active trace found'); | ||
return; | ||
} | ||
if (this.currentRootSpan !== root) { | ||
this.logger.debug('currentRootSpan != root on notifyEnd. Need more investigation.'); | ||
} | ||
this.notifyEndSpan(root); | ||
} | ||
@@ -186,16 +195,13 @@ /** | ||
notifyEndSpan(root) { | ||
if (this.active) { | ||
this.logger.debug('starting to notify listeners the end of rootspans'); | ||
if (this.eventListenersLocal && this.eventListenersLocal.length > 0) { | ||
for (const listener of this.eventListenersLocal) { | ||
listener.onEndSpan(root); | ||
} | ||
this.logger.debug('starting to notify listeners the end of rootspans'); | ||
if (this.eventListenersLocal && this.eventListenersLocal.length > 0) { | ||
for (const listener of this.eventListenersLocal) { | ||
listener.onEndSpan(root); | ||
} | ||
} | ||
else { | ||
this.logger.debug('this tracer is inactivate cant notify endspan'); | ||
} | ||
} | ||
/** Clears the current root span. */ | ||
clearCurrentTrace() { | ||
// TODO: Remove null reference and ts-ignore check. | ||
//@ts-ignore | ||
this.currentRootSpan = null; | ||
@@ -205,15 +211,11 @@ } | ||
* Starts a span. | ||
* @param name The span name. | ||
* @param kind optional The span kind. | ||
* @param parentSpanId The parent span ID. | ||
* @param nameOrOptions Span name string or SpanOptions object. | ||
* @param kind Span kind if not using SpanOptions object. | ||
*/ | ||
startChildSpan(name, kind) { | ||
let newSpan = null; | ||
startChildSpan(nameOrOptions, kind) { | ||
if (!this.currentRootSpan) { | ||
this.logger.debug('no current trace found - must start a new root span first'); | ||
return new no_record_span_1.NoRecordSpan(); | ||
} | ||
else { | ||
newSpan = this.currentRootSpan.startChildSpan(name, kind); | ||
} | ||
return newSpan; | ||
return this.currentRootSpan.startChildSpan(nameOrOptions, kind); | ||
} | ||
@@ -239,3 +241,3 @@ /** | ||
* @param emitter An event emitter whose handlers should have | ||
* the trace context binded to them. | ||
* the trace context binded to them. | ||
*/ | ||
@@ -249,4 +251,25 @@ wrapEmitter(emitter) { | ||
} | ||
/** Determine whether to sample request or not. */ | ||
makeSamplingDecision(options, traceId) { | ||
// If users set a specific sampler in the TraceOptions, use it. | ||
if (options && options.samplingRate !== undefined && | ||
options.samplingRate !== null) { | ||
return sampler_1.SamplerBuilder.getSampler(options.samplingRate) | ||
.shouldSample(traceId); | ||
} | ||
let propagatedSample = null; | ||
// if there is a context propagation, keep the decision | ||
if (options && options.spanContext && options.spanContext.options) { | ||
propagatedSample = | ||
((options.spanContext.options & this.IS_SAMPLED) !== 0); | ||
} | ||
let sampleDecision = !!propagatedSample; | ||
if (!sampleDecision) { | ||
// Use the default global sampler | ||
sampleDecision = this.sampler.shouldSample(traceId); | ||
} | ||
return sampleDecision; | ||
} | ||
} | ||
exports.CoreTracer = CoreTracer; | ||
//# sourceMappingURL=tracer.js.map |
@@ -186,4 +186,9 @@ /** | ||
type: MessageEventType; | ||
/** An identifier for the MessageEvent's message. */ | ||
id: string; | ||
/** | ||
* An identifier for the MessageEvent's message that can be used to match | ||
* SENT and RECEIVED MessageEvents. Message event ids should start with 1 for | ||
* both sent and received messages and increment by 1 for each message | ||
* sent/received. | ||
*/ | ||
id: number; | ||
/** The number of uncompressed bytes sent or received. */ | ||
@@ -219,3 +224,14 @@ uncompressedSize?: number; | ||
kind?: SpanKind; | ||
/** Determines the sampling rate. Ranges from 0.0 to 1.0 */ | ||
samplingRate?: number; | ||
} | ||
/** Defines the span options */ | ||
export interface SpanOptions { | ||
/** Span name */ | ||
name: string; | ||
/** Span kind */ | ||
kind?: SpanKind; | ||
/** Span parent ID */ | ||
parentSpanId?: string; | ||
} | ||
export declare type TraceState = string; | ||
@@ -310,3 +326,3 @@ /** Defines the span context */ | ||
/** Trace state associated with span */ | ||
readonly traceState: TraceState; | ||
readonly traceState?: TraceState; | ||
/** Indicates if span was started. */ | ||
@@ -369,4 +385,7 @@ readonly started: boolean; | ||
* @param timestamp A timestamp for this event. | ||
* @param uncompressedSize The number of uncompressed bytes sent or received. | ||
* @param compressedSize The number of compressed bytes sent or received. If | ||
* zero or undefined, assumed to be the same size as uncompressed. | ||
*/ | ||
addMessageEvent(type: MessageEventType, id: string, timestamp?: number): void; | ||
addMessageEvent(type: MessageEventType, id: number, timestamp?: number, uncompressedSize?: number, compressedSize?: number): void; | ||
/** | ||
@@ -389,4 +408,8 @@ * Sets a status to the span. | ||
readonly spans: Span[]; | ||
/** Gets the number of child span created for this span. */ | ||
readonly numberOfChildren: number; | ||
/** Starts a new Span instance in the RootSpan instance */ | ||
startChildSpan(name: string, kind: SpanKind): Span; | ||
startChildSpan(name?: string, kind?: SpanKind): Span; | ||
startChildSpan(options?: SpanOptions): Span; | ||
startChildSpan(nameOrOptions?: string | SpanOptions, kind?: SpanKind): Span; | ||
} | ||
@@ -439,7 +462,8 @@ /** Interface for Tracer */ | ||
* @param name Span name | ||
* @param type Span type | ||
* @param parentSpanId Parent SpanId | ||
* @param kind Span kind | ||
* @param options Span Options | ||
* @returns The new Span instance started | ||
*/ | ||
startChildSpan(name?: string, type?: SpanKind, parentSpanId?: string): Span; | ||
startChildSpan(name?: string, kind?: SpanKind): Span; | ||
startChildSpan(options?: SpanOptions): Span; | ||
/** | ||
@@ -458,5 +482,5 @@ * Binds the trace context to the given function. | ||
* @param emitter An event emitter whose handlers should have | ||
* the trace context binded to them. | ||
* the trace context binded to them. | ||
*/ | ||
wrapEmitter(emitter: NodeJS.EventEmitter): void; | ||
} |
@@ -58,2 +58,7 @@ /** | ||
} | ||
/** | ||
* The default sampler is a Probability sampler with the probability set to | ||
* 1/10000. | ||
*/ | ||
export declare const DEFAULT_SAMPLING_RATE = 0.0001; | ||
/** Default Limit for Annotations per span */ | ||
@@ -60,0 +65,0 @@ export declare const DEFAULT_SPAN_MAX_NUM_ANNOTATIONS = 32; |
@@ -94,2 +94,7 @@ "use strict"; | ||
exports.SamplerBuilder = SamplerBuilder; | ||
/** | ||
* The default sampler is a Probability sampler with the probability set to | ||
* 1/10000. | ||
*/ | ||
exports.DEFAULT_SAMPLING_RATE = 0.0001; | ||
/** Default Limit for Annotations per span */ | ||
@@ -106,23 +111,31 @@ exports.DEFAULT_SPAN_MAX_NUM_ANNOTATIONS = 32; | ||
static getNumberOfAnnotationEventsPerSpan(traceParameters) { | ||
return traceParameters.numberOfAnnontationEventsPerSpan > | ||
exports.DEFAULT_SPAN_MAX_NUM_ANNOTATIONS ? | ||
exports.DEFAULT_SPAN_MAX_NUM_ANNOTATIONS : | ||
traceParameters.numberOfAnnontationEventsPerSpan; | ||
if (!traceParameters.numberOfAnnontationEventsPerSpan || | ||
traceParameters.numberOfAnnontationEventsPerSpan > | ||
exports.DEFAULT_SPAN_MAX_NUM_ANNOTATIONS) { | ||
return exports.DEFAULT_SPAN_MAX_NUM_ANNOTATIONS; | ||
} | ||
return traceParameters.numberOfAnnontationEventsPerSpan; | ||
} | ||
static getNumberOfAttributesPerSpan(traceParameters) { | ||
return traceParameters.numberOfAttributesPerSpan > | ||
exports.DEFAULT_SPAN_MAX_NUM_ATTRIBUTES ? | ||
exports.DEFAULT_SPAN_MAX_NUM_ATTRIBUTES : | ||
traceParameters.numberOfAttributesPerSpan; | ||
if (!traceParameters.numberOfAttributesPerSpan || | ||
traceParameters.numberOfAttributesPerSpan > | ||
exports.DEFAULT_SPAN_MAX_NUM_ATTRIBUTES) { | ||
return exports.DEFAULT_SPAN_MAX_NUM_ATTRIBUTES; | ||
} | ||
return traceParameters.numberOfAttributesPerSpan; | ||
} | ||
static getNumberOfMessageEventsPerSpan(traceParameters) { | ||
return traceParameters.numberOfMessageEventsPerSpan > | ||
exports.DEFAULT_SPAN_MAX_NUM_MESSAGE_EVENTS ? | ||
exports.DEFAULT_SPAN_MAX_NUM_MESSAGE_EVENTS : | ||
traceParameters.numberOfMessageEventsPerSpan; | ||
if (!traceParameters.numberOfMessageEventsPerSpan || | ||
traceParameters.numberOfMessageEventsPerSpan > | ||
exports.DEFAULT_SPAN_MAX_NUM_MESSAGE_EVENTS) { | ||
return exports.DEFAULT_SPAN_MAX_NUM_MESSAGE_EVENTS; | ||
} | ||
return traceParameters.numberOfMessageEventsPerSpan; | ||
} | ||
static getNumberOfLinksPerSpan(traceParameters) { | ||
return traceParameters.numberOfLinksPerSpan > exports.DEFAULT_SPAN_MAX_NUM_LINKS ? | ||
exports.DEFAULT_SPAN_MAX_NUM_LINKS : | ||
traceParameters.numberOfLinksPerSpan; | ||
if (!traceParameters.numberOfLinksPerSpan || | ||
traceParameters.numberOfLinksPerSpan > exports.DEFAULT_SPAN_MAX_NUM_LINKS) { | ||
return exports.DEFAULT_SPAN_MAX_NUM_LINKS; | ||
} | ||
return traceParameters.numberOfLinksPerSpan; | ||
} | ||
@@ -129,0 +142,0 @@ } |
@@ -26,5 +26,5 @@ /** | ||
* @returns a boolean. True if the traceId is in probability | ||
* False if the traceId is not in probability. | ||
* False if the traceId is not in probability. | ||
*/ | ||
shouldSample(traceId: string): boolean; | ||
} |
{ | ||
"name": "@opencensus/core", | ||
"version": "0.0.9", | ||
"version": "0.0.10", | ||
"description": "OpenCensus is a toolkit for collecting application performance and behavior data.", | ||
@@ -9,3 +9,3 @@ "main": "build/src/index.js", | ||
"scripts": { | ||
"test": "nyc mocha build/test/**/*.js", | ||
"test": "nyc ts-mocha -p ./tsconfig.json test/**/*.ts", | ||
"codecov": "nyc report --reporter=json && codecov -f coverage/*.json", | ||
@@ -18,3 +18,2 @@ "clean": "rimraf build/*", | ||
"prepare": "npm run compile:release", | ||
"pretest": "npm run compile", | ||
"posttest": "npm run check" | ||
@@ -43,2 +42,13 @@ }, | ||
], | ||
"nyc": { | ||
"extension": [ | ||
".ts", | ||
".tsx" | ||
], | ||
"exclude": [ | ||
"**/*.d.ts", | ||
"build/**/**/*.js" | ||
], | ||
"all": true | ||
}, | ||
"publishConfig": { | ||
@@ -52,3 +62,3 @@ "access": "public" | ||
"@types/once": "^1.4.0", | ||
"@types/semver": "^5.5.0", | ||
"@types/semver": "^6.0.0", | ||
"@types/shimmer": "^1.0.1", | ||
@@ -59,6 +69,6 @@ "@types/uuid": "^3.4.3", | ||
"intercept-stdout": "^0.1.2", | ||
"mocha": "^5.0.4", | ||
"ncp": "^2.0.0", | ||
"nyc": "13.1.0", | ||
"ts-node": "^7.0.1", | ||
"mocha": "^6.0.0", | ||
"nyc": "13.3.0", | ||
"ts-mocha": "^6.0.0", | ||
"ts-node": "^8.0.0", | ||
"typescript": "~2.9.0" | ||
@@ -69,3 +79,3 @@ }, | ||
"log-driver": "^1.2.7", | ||
"semver": "^5.5.0", | ||
"semver": "^6.0.0", | ||
"shimmer": "^1.2.0", | ||
@@ -72,0 +82,0 @@ "uuid": "^3.2.1" |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
346284
117
8582
+ Addedsemver@6.3.1(transitive)
Updatedsemver@^6.0.0