@opencensus/core
Advanced tools
Comparing version 0.0.8 to 0.0.9
@@ -0,1 +1,16 @@ | ||
/** | ||
* 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 * as types from './types'; | ||
@@ -38,8 +53,2 @@ /** | ||
debug(message: any, ...args: any[]): void; | ||
/** | ||
* Logger silly function. | ||
* @param message menssage silly to log in console | ||
* @param args arguments to log in console | ||
*/ | ||
silly(message: any, ...args: any[]): void; | ||
} | ||
@@ -46,0 +55,0 @@ /** |
@@ -85,13 +85,4 @@ "use strict"; | ||
} | ||
/** | ||
* Logger silly function. | ||
* @param message menssage silly to log in console | ||
* @param args arguments to log in console | ||
*/ | ||
// tslint:disable-next-line:no-any | ||
silly(message, ...args) { | ||
this.logger.silly(util.format(message, ...args)); | ||
} | ||
} | ||
ConsoleLogger.LEVELS = ['silent', 'error', 'warn', 'info', 'debug', 'silly']; | ||
ConsoleLogger.LEVELS = ['silent', 'error', 'warn', 'info', 'debug']; | ||
exports.ConsoleLogger = ConsoleLogger; | ||
@@ -98,0 +89,0 @@ /** |
@@ -19,3 +19,4 @@ /** | ||
export interface Logger { | ||
level: string; | ||
/** Logger verbosity level. If omitted, `debug` level is assumed. */ | ||
level?: string; | ||
error: LogFunction; | ||
@@ -25,3 +26,2 @@ warn: LogFunction; | ||
debug: LogFunction; | ||
silly: LogFunction; | ||
} | ||
@@ -28,0 +28,0 @@ /** Defines an logger options interface. */ |
@@ -0,1 +1,16 @@ | ||
/** | ||
* 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. | ||
*/ | ||
export declare const version: string; |
@@ -18,2 +18,3 @@ /** | ||
import { Measurement, View } from '../stats/types'; | ||
import { TagKey, TagValue } from '../tags/types'; | ||
import * as modelTypes from '../trace/model/types'; | ||
@@ -64,3 +65,8 @@ import * as types from './types'; | ||
*/ | ||
onRecord(views: View[], measurement: Measurement): void; | ||
onRecord(views: View[], measurement: Measurement, tags: Map<TagKey, TagValue>): void; | ||
/** | ||
* Starts the Console exporter that polls Metric from Metrics library and | ||
* shows in the log console.. | ||
*/ | ||
start(): void; | ||
} |
@@ -79,7 +79,14 @@ "use strict"; | ||
*/ | ||
onRecord(views, measurement) { | ||
onRecord(views, measurement, tags) { | ||
console.log(`Measurement recorded: ${measurement.measure.name}`); | ||
} | ||
/** | ||
* Starts the Console exporter that polls Metric from Metrics library and | ||
* shows in the log console.. | ||
*/ | ||
start() { | ||
// TODO(mayurkale): dependency with PR#253. | ||
} | ||
} | ||
exports.ConsoleStatsExporter = ConsoleStatsExporter; | ||
//# sourceMappingURL=console-exporter.js.map |
@@ -0,1 +1,16 @@ | ||
/** | ||
* 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 * as configTypes from '../trace/config/types'; | ||
@@ -39,7 +54,7 @@ import * as modelTypes from '../trace/model/types'; | ||
/** Reset the buffer timeout */ | ||
private resetBufferTimeout(); | ||
private resetBufferTimeout; | ||
/** Start the buffer timeout, when finished calls flush method */ | ||
private setBufferTimeout(); | ||
private setBufferTimeout; | ||
/** Send the trace queue to all exporters */ | ||
private flush(); | ||
private flush; | ||
} |
@@ -17,2 +17,3 @@ /** | ||
import { Measurement, View } from '../stats/types'; | ||
import { TagKey, TagValue } from '../tags/types'; | ||
import * as configTypes from '../trace/config/types'; | ||
@@ -35,2 +36,3 @@ import * as modelTypes from '../trace/model/types'; | ||
* Is called whenever a new view is registered | ||
* @deprecated since version 0.0.9 - use {@link start} instead | ||
* @param view The registered view | ||
@@ -41,7 +43,13 @@ */ | ||
* Is called whenever a new measurement is recorded. | ||
* @deprecated since version 0.0.9 - use {@link start} instead | ||
* @param views The views related to the measurement | ||
* @param measurement The recorded measurement | ||
*/ | ||
onRecord(views: View[], measurement: Measurement): void; | ||
onRecord(views: View[], measurement: Measurement, tags: Map<TagKey, TagValue>): void; | ||
/** | ||
* Starts the exporter that polls Metric from Metrics library and send | ||
* batched data to backend. | ||
*/ | ||
start(): void; | ||
} | ||
export declare type ExporterConfig = configTypes.BufferConfig; |
@@ -24,2 +24,5 @@ /** | ||
export * from './common/types'; | ||
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 * from './trace/model/tracer'; | ||
@@ -30,3 +33,2 @@ export * from './trace/sampler/sampler'; | ||
export * from './exporters/console-exporter'; | ||
export * from './stats/stats'; | ||
export * from './stats/view'; | ||
@@ -36,5 +38,16 @@ export * from './stats/recorder'; | ||
export * from './stats/metric-utils'; | ||
export * from './tags/tag-map'; | ||
export * from './resource/resource'; | ||
export * from './stats/types'; | ||
export * from './tags/types'; | ||
export * from './resource/types'; | ||
import * as logger from './common/console-logger'; | ||
export { logger }; | ||
export * from './common/version'; | ||
export * from './metrics/metrics'; | ||
export * from './metrics/metric-registry'; | ||
export * from './metrics/gauges/derived-gauge'; | ||
export * from './metrics/gauges/gauge'; | ||
import { Stats } from './stats/types'; | ||
declare const globalStats: Stats; | ||
export { globalStats }; |
@@ -21,2 +21,5 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
__export(require("./trace/model/types")); | ||
const types_1 = require("./metrics/export/types"); | ||
exports.MetricDescriptorType = types_1.MetricDescriptorType; | ||
// classes | ||
@@ -34,3 +37,2 @@ // domain models impls | ||
// classes | ||
__export(require("./stats/stats")); | ||
__export(require("./stats/view")); | ||
@@ -40,2 +42,4 @@ __export(require("./stats/recorder")); | ||
__export(require("./stats/metric-utils")); | ||
__export(require("./tags/tag-map")); | ||
__export(require("./resource/resource")); | ||
// interfaces | ||
@@ -48,2 +52,12 @@ __export(require("./stats/types")); | ||
__export(require("./common/version")); | ||
// METRICS CLASSES | ||
__export(require("./metrics/metrics")); | ||
__export(require("./metrics/metric-registry")); | ||
// GAUGES CLASSES | ||
__export(require("./metrics/gauges/derived-gauge")); | ||
__export(require("./metrics/gauges/gauge")); | ||
// Stats singleton instance | ||
const stats_1 = require("./stats/stats"); | ||
const globalStats = stats_1.BaseStats.instance; | ||
exports.globalStats = globalStats; | ||
//# sourceMappingURL=index.js.map |
@@ -0,1 +1,16 @@ | ||
/** | ||
* Copyright 2018 Google LLC | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
import { Namespace as CLSNamespace } from 'continuation-local-storage'; | ||
@@ -2,0 +17,0 @@ export declare function createNamespace(): CLSNamespace; |
@@ -0,1 +1,16 @@ | ||
/** | ||
* Copyright 2018 Google LLC | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
export declare function randomSpanId(): string; |
@@ -98,3 +98,3 @@ /** | ||
*/ | ||
SUMMARY = 7, | ||
SUMMARY = 7 | ||
} | ||
@@ -227,3 +227,3 @@ /** Properties of a LabelKey associated with a MetricDescriptor. */ | ||
*/ | ||
readonly exemplar: Exemplar; | ||
readonly exemplar?: Exemplar; | ||
} | ||
@@ -312,1 +312,23 @@ /** | ||
} | ||
/** | ||
* Keeps a set of MetricProducer that is used by exporters to determine the | ||
* metrics that need to be exported. | ||
*/ | ||
export interface MetricProducerManager { | ||
/** Adds the MetricProducer to the manager */ | ||
add(metricProducer: MetricProducer): void; | ||
/** Removes the MetricProducer to the manager */ | ||
remove(metricProducer: MetricProducer): void; | ||
/** Clears all MetricProducers */ | ||
removeAll(): void; | ||
/** Gets all registered MetricProducers that should be exported */ | ||
getAllMetricProducer(): Set<MetricProducer>; | ||
} | ||
/** | ||
* A MetricProducer producer that can be registered for exporting using | ||
* MetricProducerManager. | ||
*/ | ||
export interface MetricProducer { | ||
/** Gets a collection of produced Metric`s to be exported */ | ||
getMetrics(): Metric[]; | ||
} |
@@ -0,1 +1,16 @@ | ||
/** | ||
* 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 { LabelKey, LabelValue, Metric, MetricDescriptorType } from '../export/types'; | ||
@@ -2,0 +17,0 @@ import * as types from '../gauges/types'; |
@@ -18,2 +18,3 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const time_util_1 = require("../../common/time-util"); | ||
const validations_1 = require("../../common/validations"); | ||
@@ -131,3 +132,3 @@ const utils_1 = require("../utils"); | ||
} | ||
const [seconds, nanos] = process.hrtime(); | ||
const timestamp = time_util_1.getTimestampWithProcessHRTime(); | ||
return { | ||
@@ -137,5 +138,3 @@ descriptor: this.metricDescriptor, | ||
labelValues: gaugeEntry.labelValues, | ||
points: [ | ||
{ value: gaugeEntry.extractor(), timestamp: { seconds, nanos } } | ||
] | ||
points: [{ value: gaugeEntry.extractor(), timestamp }] | ||
})) | ||
@@ -142,0 +141,0 @@ }; |
@@ -0,1 +1,16 @@ | ||
/** | ||
* 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 { LabelKey, LabelValue, Metric, MetricDescriptorType, TimeSeries, Timestamp } from '../export/types'; | ||
@@ -65,3 +80,3 @@ import * as types from '../gauges/types'; | ||
*/ | ||
private registerTimeSeries(labelValues); | ||
private registerTimeSeries; | ||
/** | ||
@@ -68,0 +83,0 @@ * Provides a Metric with one or more TimeSeries. |
@@ -18,2 +18,3 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const time_util_1 = require("../../common/time-util"); | ||
const validations_1 = require("../../common/validations"); | ||
@@ -113,6 +114,6 @@ const utils_1 = require("../utils"); | ||
} | ||
const [seconds, nanos] = process.hrtime(); | ||
const timestamp = time_util_1.getTimestampWithProcessHRTime(); | ||
return { | ||
descriptor: this.metricDescriptor, | ||
timeseries: Array.from(this.registeredPoints, ([_, point]) => point.getTimeSeries({ seconds, nanos })) | ||
timeseries: Array.from(this.registeredPoints, ([_, point]) => point.getTimeSeries(timestamp)) | ||
}; | ||
@@ -119,0 +120,0 @@ } |
@@ -0,4 +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 { MeasureUnit } from '../stats/types'; | ||
import { MetricProducer } from './export/metric-producer'; | ||
import { LabelKey } from './export/types'; | ||
import { LabelKey, MetricProducer } from './export/types'; | ||
import { DerivedGauge } from './gauges/derived-gauge'; | ||
@@ -72,3 +86,3 @@ import { Gauge } from './gauges/gauge'; | ||
*/ | ||
private registerMetric(name, meter); | ||
private registerMetric; | ||
/** | ||
@@ -75,0 +89,0 @@ * Gets a metric producer for registry. |
@@ -19,3 +19,3 @@ "use strict"; | ||
const validations_1 = require("../common/validations"); | ||
const metric_producer_1 = require("./export/metric-producer"); | ||
const base_metric_producer_1 = require("./export/base-metric-producer"); | ||
const types_1 = require("./export/types"); | ||
@@ -139,3 +139,3 @@ const derived_gauge_1 = require("./gauges/derived-gauge"); | ||
*/ | ||
class MetricProducerForRegistry extends metric_producer_1.MetricProducer { | ||
class MetricProducerForRegistry extends base_metric_producer_1.BaseMetricProducer { | ||
constructor(registeredMetrics) { | ||
@@ -142,0 +142,0 @@ super(); |
@@ -16,12 +16,13 @@ /** | ||
*/ | ||
import { MetricProducerManager } from './export/types'; | ||
import { MetricRegistry } from './metric-registry'; | ||
/** | ||
* Class for accessing the default MetricsComponent. | ||
*/ | ||
export declare class Metrics { | ||
private static readonly METRIC_REGISTRY; | ||
/** | ||
* Returns the global MetricRegistry. | ||
* | ||
* @return {MetricRegistry}. | ||
*/ | ||
private static readonly METRIC_COMPONENT; | ||
/** @return {MetricProducerManager} The global MetricProducerManager. */ | ||
static getMetricProducerManager(): MetricProducerManager; | ||
/** @return {MetricRegistry} The global MetricRegistry. */ | ||
static getMetricRegistry(): MetricRegistry; | ||
private static newMetricRegistry(); | ||
} |
@@ -18,18 +18,19 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const metric_registry_1 = require("./metric-registry"); | ||
const metric_producer_manager_1 = require("./export/metric-producer-manager"); | ||
const metric_component_1 = require("./metric-component"); | ||
/** | ||
* Class for accessing the default MetricsComponent. | ||
*/ | ||
class Metrics { | ||
/** | ||
* Returns the global MetricRegistry. | ||
* | ||
* @return {MetricRegistry}. | ||
*/ | ||
/** @return {MetricProducerManager} The global MetricProducerManager. */ | ||
static getMetricProducerManager() { | ||
return metric_producer_manager_1.metricProducerManagerInstance; | ||
} | ||
/** @return {MetricRegistry} The global MetricRegistry. */ | ||
static getMetricRegistry() { | ||
return Metrics.METRIC_REGISTRY; | ||
return Metrics.METRIC_COMPONENT.getMetricRegistry(); | ||
} | ||
static newMetricRegistry() { | ||
return new metric_registry_1.MetricRegistry(); | ||
} | ||
} | ||
Metrics.METRIC_REGISTRY = Metrics.newMetricRegistry(); | ||
Metrics.METRIC_COMPONENT = new metric_component_1.MetricsComponent(); | ||
exports.Metrics = Metrics; | ||
//# sourceMappingURL=metrics.js.map |
@@ -0,1 +1,16 @@ | ||
/** | ||
* 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 { Resource } from './types'; | ||
@@ -13,4 +28,4 @@ /** | ||
private static readonly LABEL_KEY_VALUE_SPLITTER; | ||
private static readonly ENV_TYPE; | ||
private static readonly ENV_LABEL_MAP; | ||
private static ENV_TYPE; | ||
private static ENV_LABEL_MAP; | ||
private static readonly ERROR_MESSAGE_INVALID_CHARS; | ||
@@ -43,3 +58,3 @@ private static readonly ERROR_MESSAGE_INVALID_VALUE; | ||
*/ | ||
private static parseResourceType(rawEnvType); | ||
private static parseResourceType; | ||
/** | ||
@@ -57,3 +72,3 @@ * Creates a label map from the OC_RESOURCE_LABELS environment variable. | ||
*/ | ||
private static parseResourceLabels(rawEnvLabels); | ||
private static parseResourceLabels; | ||
/** | ||
@@ -67,3 +82,3 @@ * Returns a new, merged Resource by merging two resources. In case of | ||
*/ | ||
private static merge(resource, otherResource); | ||
private static merge; | ||
/** | ||
@@ -76,3 +91,3 @@ * Determines whether the given String is a valid printable ASCII string with | ||
*/ | ||
private static isValid(name); | ||
private static isValid; | ||
/** | ||
@@ -85,3 +100,5 @@ * Determines whether the given String is a valid printable ASCII string with | ||
*/ | ||
private static isValidAndNotEmpty(name); | ||
private static isValidAndNotEmpty; | ||
/** TEST_ONLY */ | ||
static setup(): void; | ||
} |
@@ -146,2 +146,9 @@ "use strict"; | ||
} | ||
/** TEST_ONLY */ | ||
static setup() { | ||
CoreResource.ENV_TYPE = | ||
CoreResource.parseResourceType(process.env.OC_RESOURCE_TYPE); | ||
CoreResource.ENV_LABEL_MAP = | ||
CoreResource.parseResourceLabels(process.env.OC_RESOURCE_LABELS); | ||
} | ||
} | ||
@@ -148,0 +155,0 @@ // Type, label keys, and label values should not exceed 256 characters. |
@@ -37,3 +37,3 @@ /** | ||
*/ | ||
private dropNegativeBucketBounds(bucketBoundaries); | ||
private dropNegativeBucketBounds; | ||
/** | ||
@@ -43,3 +43,3 @@ * Gets initial list of bucket counters | ||
*/ | ||
private getBucketCounts(buckets); | ||
private getBucketCounts; | ||
/** | ||
@@ -50,3 +50,3 @@ * Checks boundaries order and duplicates | ||
*/ | ||
private validateBoundary(current, next); | ||
private validateBoundary; | ||
} |
@@ -16,5 +16,5 @@ /** | ||
*/ | ||
import { MetricProducer } from '../metrics/export/metric-producer'; | ||
import { BaseMetricProducer } from '../metrics/export/base-metric-producer'; | ||
import { Metric } from '../metrics/export/types'; | ||
import { Stats } from './stats'; | ||
import { Stats } from './types'; | ||
/** | ||
@@ -24,3 +24,3 @@ * A MetricProducer producer that can be registered for exporting using | ||
*/ | ||
export declare class MetricProducerForStats extends MetricProducer { | ||
export declare class MetricProducerForStats extends BaseMetricProducer { | ||
private statsManager; | ||
@@ -27,0 +27,0 @@ /** |
@@ -18,3 +18,3 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
const metric_producer_1 = require("../metrics/export/metric-producer"); | ||
const base_metric_producer_1 = require("../metrics/export/base-metric-producer"); | ||
/** | ||
@@ -24,3 +24,3 @@ * A MetricProducer producer that can be registered for exporting using | ||
*/ | ||
class MetricProducerForStats extends metric_producer_1.MetricProducer { | ||
class MetricProducerForStats extends base_metric_producer_1.BaseMetricProducer { | ||
/** | ||
@@ -27,0 +27,0 @@ * @param statsManager The stats |
@@ -17,3 +17,4 @@ /** | ||
import { LabelValue, MetricDescriptor } from '../metrics/export/types'; | ||
import { Tags, View } from './types'; | ||
import { TagValue } from '../tags/types'; | ||
import { View } from './types'; | ||
/** Utils to convert Stats data models to Metric data models */ | ||
@@ -27,3 +28,3 @@ export declare class MetricUtils { | ||
*/ | ||
private static getType(measure, aggregation); | ||
private static getType; | ||
/** | ||
@@ -36,7 +37,7 @@ * Gets a MetricDescriptor for given view. | ||
/** | ||
* Converts tags to label values. | ||
* @param tags | ||
* Converts tag values to label values. | ||
* @param tagValues | ||
* @returns {LabelValue[]} List of label values | ||
*/ | ||
static tagsToLabelValues(tags: Tags): LabelValue[]; | ||
static tagValuesToLabelValues(tagValues: TagValue[]): LabelValue[]; | ||
} |
@@ -63,3 +63,2 @@ "use strict"; | ||
static viewToMetricDescriptor(view) { | ||
// TODO(mayurkale): add description | ||
return { | ||
@@ -70,14 +69,14 @@ name: view.name, | ||
type: MetricUtils.getType(view.measure, view.aggregation), | ||
labelKeys: view.getColumns().map(tag => ({ key: tag, description: '' })) | ||
labelKeys: view.getColumns().map( | ||
// TODO(mayurkale): add description | ||
tagKey => ({ key: tagKey.name, description: '' })) | ||
}; | ||
} | ||
/** | ||
* Converts tags to label values. | ||
* @param tags | ||
* Converts tag values to label values. | ||
* @param tagValues | ||
* @returns {LabelValue[]} List of label values | ||
*/ | ||
static tagsToLabelValues(tags) { | ||
return Object.keys(tags).map(key => { | ||
return { value: tags[key] }; | ||
}); | ||
static tagValuesToLabelValues(tagValues) { | ||
return tagValues.map((tagValue) => ({ value: tagValue ? tagValue.value : null })); | ||
} | ||
@@ -84,0 +83,0 @@ } |
@@ -16,9 +16,12 @@ /** | ||
*/ | ||
import { TagKey, TagValue } from '../tags/types'; | ||
import { AggregationData, Measurement } from './types'; | ||
export declare class Recorder { | ||
static addMeasurement(aggregationData: AggregationData, measurement: Measurement): AggregationData; | ||
private static addToDistribution(distributionData, value); | ||
private static addToSum(sumData, value); | ||
private static addToCount(countData, value); | ||
private static addToLastValue(lastValueData, value); | ||
/** Gets the tag values from tags and columns */ | ||
static getTagValues(tags: Map<TagKey, TagValue>, columns: TagKey[]): TagValue[]; | ||
private static addToDistribution; | ||
private static addToSum; | ||
private static addToCount; | ||
private static addToLastValue; | ||
} |
@@ -19,2 +19,3 @@ "use strict"; | ||
const types_1 = require("./types"); | ||
const UNKNOWN_TAG_VALUE = null; | ||
class Recorder { | ||
@@ -37,2 +38,7 @@ static addMeasurement(aggregationData, measurement) { | ||
} | ||
/** Gets the tag values from tags and columns */ | ||
static getTagValues(tags, columns) { | ||
return columns.map((tagKey) => (tags.get(tagKey) || | ||
/** replace not found key values by null. */ UNKNOWN_TAG_VALUE)); | ||
} | ||
static addToDistribution(distributionData, value) { | ||
@@ -39,0 +45,0 @@ distributionData.count += 1; |
@@ -19,4 +19,6 @@ /** | ||
import { Metric } from '../metrics/export/types'; | ||
import { AggregationType, Measure, Measurement, MeasureUnit, View } from './types'; | ||
export declare class Stats { | ||
import { TagMap } from '../tags/tag-map'; | ||
import { TagKey } from '../tags/types'; | ||
import { AggregationType, Measure, Measurement, MeasureUnit, Stats, View } from './types'; | ||
export declare class BaseStats implements Stats { | ||
/** A list of Stats exporters */ | ||
@@ -28,2 +30,4 @@ private statsEventListeners; | ||
private logger; | ||
/** Singleton instance */ | ||
private static singletonInstance; | ||
/** | ||
@@ -34,5 +38,6 @@ * Creates stats | ||
constructor(logger?: typeof defaultLogger); | ||
/** Gets the stats instance. */ | ||
static readonly instance: Stats; | ||
/** | ||
* Registers a view to listen to new measurements in its measure. Prefer using | ||
* the method createView() that creates an already registered view. | ||
* Registers a view to listen to new measurements in its measure. | ||
* @param view The view to be registered | ||
@@ -42,3 +47,3 @@ */ | ||
/** | ||
* Creates and registers a view. | ||
* Creates a view. | ||
* @param name The view name | ||
@@ -52,3 +57,3 @@ * @param measure The view measure | ||
*/ | ||
createView(name: string, measure: Measure, aggregation: AggregationType, tagKeys: string[], description: string, bucketBoundaries?: number[]): View; | ||
createView(name: string, measure: Measure, aggregation: AggregationType, tagKeys: TagKey[], description: string, bucketBoundaries?: number[]): View; | ||
/** | ||
@@ -79,3 +84,3 @@ * Registers an exporter to send stats data to a service. | ||
*/ | ||
private hasNegativeValue(measurements); | ||
private hasNegativeValue; | ||
/** | ||
@@ -89,4 +94,11 @@ * Gets a collection of produced Metric`s to be exported. | ||
* @param measurements A list of measurements to record | ||
* @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. | ||
*/ | ||
record(...measurements: Measurement[]): void; | ||
record(measurements: Measurement[], tags?: TagMap): void; | ||
/** | ||
* Remove all registered Views and exporters from the stats. | ||
*/ | ||
clear(): void; | ||
} |
@@ -19,5 +19,8 @@ "use strict"; | ||
const defaultLogger = require("../common/console-logger"); | ||
const metrics_1 = require("../metrics/metrics"); | ||
const tag_map_1 = require("../tags/tag-map"); | ||
const metric_producer_1 = require("./metric-producer"); | ||
const types_1 = require("./types"); | ||
const view_1 = require("./view"); | ||
class Stats { | ||
class BaseStats { | ||
/** | ||
@@ -33,6 +36,13 @@ * Creates stats | ||
this.logger = logger.logger(); | ||
// Create a new MetricProducerForStats and register it to | ||
// MetricProducerManager when Stats is initialized. | ||
const metricProducer = new metric_producer_1.MetricProducerForStats(this); | ||
metrics_1.Metrics.getMetricProducerManager().add(metricProducer); | ||
} | ||
/** Gets the stats instance. */ | ||
static get instance() { | ||
return this.singletonInstance || (this.singletonInstance = new this()); | ||
} | ||
/** | ||
* Registers a view to listen to new measurements in its measure. Prefer using | ||
* the method createView() that creates an already registered view. | ||
* Registers a view to listen to new measurements in its measure. | ||
* @param view The view to be registered | ||
@@ -54,3 +64,3 @@ */ | ||
/** | ||
* Creates and registers a view. | ||
* Creates a view. | ||
* @param name The view name | ||
@@ -66,3 +76,2 @@ * @param measure The view measure | ||
const view = new view_1.BaseView(name, measure, aggregation, tagKeys, description, bucketBoundaries); | ||
this.registerView(view); | ||
return view; | ||
@@ -81,2 +90,3 @@ } | ||
} | ||
exporter.start(); | ||
} | ||
@@ -118,3 +128,3 @@ /** | ||
for (const view of this.registeredViews[measureName]) { | ||
metrics.push(view.getMetric()); | ||
metrics.push(view.getMetric(view.startTime)); | ||
} | ||
@@ -127,4 +137,7 @@ } | ||
* @param measurements A list of measurements to record | ||
* @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. | ||
*/ | ||
record(...measurements) { | ||
record(measurements, tags) { | ||
if (this.hasNegativeValue(measurements)) { | ||
@@ -135,2 +148,6 @@ this.logger.warn(`Dropping measurments ${measurements}, value to record | ||
} | ||
if (!tags) { | ||
// TODO(mayurkale): read tags current execution context | ||
tags = new tag_map_1.TagMap(); | ||
} | ||
for (const measurement of measurements) { | ||
@@ -143,12 +160,19 @@ const views = this.registeredViews[measurement.measure.name]; | ||
for (const view of views) { | ||
view.recordMeasurement(measurement); | ||
view.recordMeasurement(measurement, tags); | ||
} | ||
// Notifies all exporters | ||
for (const exporter of this.statsEventListeners) { | ||
exporter.onRecord(views, measurement); | ||
exporter.onRecord(views, measurement, tags.tags); | ||
} | ||
} | ||
} | ||
/** | ||
* Remove all registered Views and exporters from the stats. | ||
*/ | ||
clear() { | ||
this.registeredViews = {}; | ||
this.statsEventListeners = []; | ||
} | ||
} | ||
exports.Stats = Stats; | ||
exports.BaseStats = BaseStats; | ||
//# sourceMappingURL=stats.js.map |
@@ -16,6 +16,61 @@ /** | ||
*/ | ||
import { StatsEventListener } from '../exporters/types'; | ||
import { Metric } from '../metrics/export/types'; | ||
/** Tags are maps of names -> values */ | ||
export interface Tags { | ||
[key: string]: string; | ||
import { TagMap } from '../tags/tag-map'; | ||
import { TagKey, TagValue } from '../tags/types'; | ||
/** Main interface for stats. */ | ||
export interface Stats { | ||
/** | ||
* Creates a view. | ||
* @param name The view name | ||
* @param measure The view measure | ||
* @param aggregation The view aggregation type | ||
* @param tagKeys The view columns (tag keys) | ||
* @param description The view description | ||
* @param bucketBoundaries The view bucket boundaries for a distribution | ||
* aggregation type | ||
*/ | ||
createView(name: string, measure: Measure, aggregation: AggregationType, tagKeys: TagKey[], description: string, bucketBoundaries?: number[]): View; | ||
/** | ||
* Registers a view to listen to new measurements in its measure. | ||
* @param view The view to be registered | ||
*/ | ||
registerView(view: View): void; | ||
/** | ||
* Creates a measure of type Double. | ||
* @param name The measure name | ||
* @param unit The measure unit | ||
* @param description The measure description | ||
*/ | ||
createMeasureDouble(name: string, unit: MeasureUnit, description?: string): Measure; | ||
/** | ||
* Creates a measure of type Int64. Values must be integers up to | ||
* Number.MAX_SAFE_INTERGER. | ||
* @param name The measure name | ||
* @param unit The measure unit | ||
* @param description The measure description | ||
*/ | ||
createMeasureInt64(name: string, unit: MeasureUnit, description?: string): Measure; | ||
/** | ||
* Updates all views with the new measurements. | ||
* @param measurements A list of measurements to record | ||
* @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. | ||
*/ | ||
record(measurements: Measurement[], tags?: TagMap): void; | ||
/** | ||
* Remove all registered Views and exporters from the stats. | ||
*/ | ||
clear(): void; | ||
/** | ||
* Gets a collection of produced Metric`s to be exported. | ||
* @returns {Metric[]} List of metrics | ||
*/ | ||
getMetrics(): Metric[]; | ||
/** | ||
* Registers an exporter to send stats data to a service. | ||
* @param exporter An stats exporter | ||
*/ | ||
registerExporter(exporter: StatsEventListener): void; | ||
} | ||
@@ -54,3 +109,3 @@ /** | ||
MS = "ms", | ||
NS = "ns", | ||
NS = "ns" | ||
} | ||
@@ -60,3 +115,3 @@ /** Describes the types of a Measure. It can be Int64 or a Double type. */ | ||
INT64 = "INT64", | ||
DOUBLE = "DOUBLE", | ||
DOUBLE = "DOUBLE" | ||
} | ||
@@ -72,4 +127,2 @@ /** Describes a data point to be collected for a Measure. */ | ||
readonly value: number; | ||
/** The tags to which the value is applied */ | ||
readonly tags: Tags; | ||
} | ||
@@ -108,13 +161,14 @@ /** | ||
* @param measurement The measurement to record | ||
* @param tags The tags to which the value is applied | ||
*/ | ||
recordMeasurement(measurement: Measurement): void; | ||
recordMeasurement(measurement: Measurement, tags: TagMap): void; | ||
/** | ||
* Returns a snapshot of an AggregationData for that tags/labels values. | ||
* @param tags The desired data's tags | ||
* @param tagValues The desired data's tag values. | ||
*/ | ||
getSnapshot(tags: Tags): AggregationData; | ||
getSnapshot(tagValues: TagValue[]): AggregationData; | ||
/** Gets the view's tag keys */ | ||
getColumns(): string[]; | ||
getColumns(): TagKey[]; | ||
/** Gets view`s metric */ | ||
getMetric(): Metric; | ||
getMetric(start: number): Metric; | ||
} | ||
@@ -129,3 +183,3 @@ /** | ||
LAST_VALUE = 2, | ||
DISTRIBUTION = 3, | ||
DISTRIBUTION = 3 | ||
} | ||
@@ -136,4 +190,4 @@ /** Defines how data is collected and aggregated */ | ||
readonly type: AggregationType; | ||
/** The tags/labels that this AggregationData collects and aggregates */ | ||
readonly tags: Tags; | ||
/** The tagValues that this AggregationData collects and aggregates */ | ||
readonly tagValues: TagValue[]; | ||
/** The latest timestamp a new data point was recorded */ | ||
@@ -140,0 +194,0 @@ timestamp: number; |
@@ -18,3 +18,5 @@ /** | ||
import { Metric } from '../metrics/export/types'; | ||
import { AggregationData, AggregationType, Measure, Measurement, Tags, View } from './types'; | ||
import { TagMap } from '../tags/tag-map'; | ||
import { TagKey, TagValue } from '../tags/types'; | ||
import { AggregationData, AggregationType, Measure, Measurement, View } from './types'; | ||
export declare class BaseView implements View { | ||
@@ -36,3 +38,3 @@ /** | ||
*/ | ||
private rows; | ||
private tagValueAggregationMap; | ||
/** | ||
@@ -76,5 +78,5 @@ * A list of tag keys that represents the possible column labels | ||
*/ | ||
constructor(name: string, measure: Measure, aggregation: AggregationType, tagsKeys: string[], description: string, bucketBoundaries?: number[], logger?: typeof defaultLogger); | ||
constructor(name: string, measure: Measure, aggregation: AggregationType, tagsKeys: TagKey[], description: string, bucketBoundaries?: number[], logger?: typeof defaultLogger); | ||
/** Gets the view's tag keys */ | ||
getColumns(): string[]; | ||
getColumns(): TagKey[]; | ||
/** | ||
@@ -86,24 +88,21 @@ * Records a measurement in the proper view's row. This method is used by | ||
* @param measurement The measurement to record | ||
* @param tags The tags to which the value is applied | ||
*/ | ||
recordMeasurement(measurement: Measurement): void; | ||
recordMeasurement(measurement: Measurement, tags: TagMap): void; | ||
/** | ||
* Encodes a Tags object into a key sorted string. | ||
* @param tags The tags to encode | ||
* Encodes a TagValue object into a value sorted string. | ||
* @param tagValues The tagValues to encode | ||
*/ | ||
private encodeTags(tags); | ||
private encodeTagValues; | ||
/** | ||
* Checks if tag keys and values have only printable characters. | ||
* @param tags The tags to be checked | ||
*/ | ||
private invalidTags(tags); | ||
/** | ||
* Creates an empty aggregation data for a given tags. | ||
* @param tags The tags for that aggregation data | ||
* @param tagValues The tags for that aggregation data | ||
*/ | ||
private createAggregationData(tags); | ||
private createAggregationData; | ||
/** | ||
* Gets view`s metric | ||
* @param start The start timestamp in epoch milliseconds | ||
* @returns {Metric} | ||
*/ | ||
getMetric(): Metric; | ||
getMetric(start: number): Metric; | ||
/** | ||
@@ -115,3 +114,3 @@ * Converts snapshot to point | ||
*/ | ||
private toPoint(timestamp, data); | ||
private toPoint; | ||
/** | ||
@@ -122,3 +121,5 @@ * Returns a snapshot of an AggregationData for that tags/labels values. | ||
*/ | ||
getSnapshot(tags: Tags): AggregationData; | ||
getSnapshot(tagValues: TagValue[]): AggregationData; | ||
/** Determines whether the given TagKeys are valid. */ | ||
private validateTagKeys; | ||
} |
@@ -19,3 +19,5 @@ "use strict"; | ||
const defaultLogger = require("../common/console-logger"); | ||
const time_util_1 = require("../common/time-util"); | ||
const types_1 = require("../metrics/export/types"); | ||
const validation_1 = require("../tags/validation"); | ||
const bucket_boundaries_1 = require("./bucket-boundaries"); | ||
@@ -26,5 +28,2 @@ const metric_utils_1 = require("./metric-utils"); | ||
const RECORD_SEPARATOR = String.fromCharCode(30); | ||
const UNIT_SEPARATOR = String.fromCharCode(31); | ||
// String that has only printable characters | ||
const invalidString = /[^\u0020-\u007e]/; | ||
class BaseView { | ||
@@ -50,3 +49,3 @@ /** | ||
*/ | ||
this.rows = {}; | ||
this.tagValueAggregationMap = {}; | ||
/** true if the view was registered */ | ||
@@ -61,3 +60,3 @@ this.registered = false; | ||
this.measure = measure; | ||
this.columns = tagsKeys; | ||
this.columns = this.validateTagKeys(tagsKeys); | ||
this.aggregation = aggregation; | ||
@@ -78,47 +77,28 @@ this.startTime = Date.now(); | ||
* @param measurement The measurement to record | ||
* @param tags The tags to which the value is applied | ||
*/ | ||
recordMeasurement(measurement) { | ||
// Checks if measurement has valid tags | ||
if (this.invalidTags(measurement.tags)) { | ||
return; | ||
recordMeasurement(measurement, tags) { | ||
const tagValues = recorder_1.Recorder.getTagValues(tags.tags, this.columns); | ||
const encodedTags = this.encodeTagValues(tagValues); | ||
if (!this.tagValueAggregationMap[encodedTags]) { | ||
this.tagValueAggregationMap[encodedTags] = | ||
this.createAggregationData(tagValues); | ||
} | ||
// Checks if measurement has all tags in views | ||
for (const tagKey of this.columns) { | ||
if (!Object.keys(measurement.tags).some((key) => key === tagKey)) { | ||
return; | ||
} | ||
} | ||
const encodedTags = this.encodeTags(measurement.tags); | ||
if (!this.rows[encodedTags]) { | ||
this.rows[encodedTags] = this.createAggregationData(measurement.tags); | ||
} | ||
recorder_1.Recorder.addMeasurement(this.rows[encodedTags], measurement); | ||
recorder_1.Recorder.addMeasurement(this.tagValueAggregationMap[encodedTags], measurement); | ||
} | ||
/** | ||
* Encodes a Tags object into a key sorted string. | ||
* @param tags The tags to encode | ||
* Encodes a TagValue object into a value sorted string. | ||
* @param tagValues The tagValues to encode | ||
*/ | ||
encodeTags(tags) { | ||
return Object.keys(tags) | ||
encodeTagValues(tagValues) { | ||
return tagValues.map((tagValue) => tagValue ? tagValue.value : null) | ||
.sort() | ||
.map(tagKey => { | ||
return tagKey + UNIT_SEPARATOR + tags[tagKey]; | ||
}) | ||
.join(RECORD_SEPARATOR); | ||
} | ||
/** | ||
* Checks if tag keys and values have only printable characters. | ||
* @param tags The tags to be checked | ||
*/ | ||
invalidTags(tags) { | ||
return Object.keys(tags).some(tagKey => { | ||
return invalidString.test(tagKey) || invalidString.test(tags[tagKey]); | ||
}); | ||
} | ||
/** | ||
* Creates an empty aggregation data for a given tags. | ||
* @param tags The tags for that aggregation data | ||
* @param tagValues The tags for that aggregation data | ||
*/ | ||
createAggregationData(tags) { | ||
const aggregationMetadata = { tags, timestamp: Date.now() }; | ||
createAggregationData(tagValues) { | ||
const aggregationMetadata = { tagValues, timestamp: Date.now() }; | ||
const { buckets, bucketCounts } = this.bucketBoundaries; | ||
@@ -140,10 +120,10 @@ const bucketsCopy = Object.assign([], buckets); | ||
* Gets view`s metric | ||
* @param start The start timestamp in epoch milliseconds | ||
* @returns {Metric} | ||
*/ | ||
getMetric() { | ||
getMetric(start) { | ||
const { type } = this.metricDescriptor; | ||
let startTimestamp; | ||
// The moment when this point was recorded. | ||
const [currentSeconds, currentNanos] = process.hrtime(); | ||
const now = { seconds: currentSeconds, nanos: currentNanos }; | ||
const now = time_util_1.getTimestampWithProcessHRTime(); | ||
switch (type) { | ||
@@ -155,11 +135,9 @@ case types_1.MetricDescriptorType.GAUGE_INT64: | ||
default: | ||
const [seconds, nanos] = process.hrtime(); | ||
// TODO (mayurkale): This should be set when create Cumulative view. | ||
startTimestamp = { seconds, nanos }; | ||
startTimestamp = time_util_1.timestampFromMillis(start); | ||
} | ||
const timeseries = []; | ||
Object.keys(this.rows).forEach(key => { | ||
const { tags } = this.rows[key]; | ||
const labelValues = metric_utils_1.MetricUtils.tagsToLabelValues(tags); | ||
const point = this.toPoint(now, this.getSnapshot(tags)); | ||
Object.keys(this.tagValueAggregationMap).forEach(key => { | ||
const { tagValues } = this.tagValueAggregationMap[key]; | ||
const labelValues = metric_utils_1.MetricUtils.tagValuesToLabelValues(tagValues); | ||
const point = this.toPoint(now, this.getSnapshot(tagValues)); | ||
if (startTimestamp) { | ||
@@ -190,3 +168,4 @@ timeseries.push({ startTimestamp, labelValues, points: [point] }); | ||
bucketOptions: { explicit: { bounds: data.buckets } }, | ||
buckets: data.bucketCounts | ||
// Bucket without an Exemplar. | ||
buckets: data.bucketCounts.map(bucketCount => ({ count: bucketCount })) | ||
}; | ||
@@ -204,7 +183,21 @@ } | ||
*/ | ||
getSnapshot(tags) { | ||
return this.rows[this.encodeTags(tags)]; | ||
getSnapshot(tagValues) { | ||
return this.tagValueAggregationMap[this.encodeTagValues(tagValues)]; | ||
} | ||
/** Determines whether the given TagKeys are valid. */ | ||
validateTagKeys(tagKeys) { | ||
const tagKeysCopy = Object.assign([], tagKeys); | ||
tagKeysCopy.forEach((tagKey) => { | ||
if (!validation_1.isValidTagKey(tagKey)) { | ||
throw new Error(`Invalid TagKey name: ${tagKey}`); | ||
} | ||
}); | ||
const tagKeysSet = new Set(tagKeysCopy.map(tagKey => tagKey.name)); | ||
if (tagKeysSet.size !== tagKeysCopy.length) { | ||
throw new Error('Columns have duplicate'); | ||
} | ||
return tagKeysCopy; | ||
} | ||
} | ||
exports.BaseView = BaseView; | ||
//# sourceMappingURL=view.js.map |
@@ -33,4 +33,2 @@ /** | ||
samplingRate?: number; | ||
/** Determines the ignored (or blacklisted) URLs */ | ||
ignoreUrls?: Array<string | RegExp>; | ||
/** A logger object */ | ||
@@ -40,2 +38,4 @@ logger?: Logger; | ||
propagation?: Propagation; | ||
/** Trace Parameters */ | ||
traceParams?: TraceParams; | ||
} | ||
@@ -70,2 +70,16 @@ /** Available configuration options. */ | ||
} | ||
/** Global configuration of trace service */ | ||
export interface TraceParams { | ||
/** | ||
* numberOfAnnontationEventsPerSpan is number of annotation events per | ||
* span | ||
*/ | ||
numberOfAnnontationEventsPerSpan?: number; | ||
/** numberOfMessageEventsPerSpan is number of message events per span */ | ||
numberOfMessageEventsPerSpan?: number; | ||
/** numberOfAttributesPerSpan is number of attributes per span */ | ||
numberOfAttributesPerSpan?: number; | ||
/** numberOfLinksPerSpan is number of links per span */ | ||
numberOfLinksPerSpan?: number; | ||
} | ||
export declare type Config = TracingConfig & TracerConfig & BufferConfig; |
@@ -28,2 +28,4 @@ import { Logger } from '../../common/types'; | ||
protected basedir: string; | ||
/** plugin options */ | ||
protected options: types.PluginConfig; | ||
/** | ||
@@ -39,5 +41,6 @@ * Constructs a new BasePlugin instance. | ||
* @param version module version description | ||
* @param options plugin options | ||
* @param basedir module absolute path | ||
*/ | ||
private setPluginContext(moduleExports, tracer, version, basedir?); | ||
private setPluginContext; | ||
/** | ||
@@ -53,5 +56,6 @@ * Method that enables the instrumentation patch. | ||
* @param version version of the current instaled module to patch | ||
* @param options plugin options | ||
* @param basedir module absolute path | ||
*/ | ||
enable<T>(moduleExports: T, tracer: modelTypes.Tracer, version: string, basedir: string): any; | ||
enable<T>(moduleExports: T, tracer: modelTypes.Tracer, version: string, options: types.PluginConfig, basedir: string): any; | ||
/** Method to disable the instrumentation */ | ||
@@ -71,7 +75,7 @@ disable(): void; | ||
*/ | ||
private loadInternalFiles(); | ||
private loadInternalFiles; | ||
/** | ||
* Load internal files from a module and set internalFilesExports | ||
*/ | ||
private loadInternalModuleFiles(extraModulesList, basedir); | ||
private loadInternalModuleFiles; | ||
} |
@@ -34,7 +34,8 @@ "use strict"; | ||
* @param version module version description | ||
* @param options plugin options | ||
* @param basedir module absolute path | ||
*/ | ||
setPluginContext( | ||
// tslint:disable-next-line:no-any | ||
moduleExports, tracer, version, basedir) { | ||
// tslint:disable-next-line:no-any | ||
moduleExports, tracer, version, options, basedir) { | ||
this.moduleExports = moduleExports; | ||
@@ -45,2 +46,3 @@ this.tracer = tracer; | ||
this.logger = tracer.logger; | ||
this.options = options; | ||
this.internalFilesExports = this.loadInternalFiles(); | ||
@@ -58,8 +60,9 @@ } | ||
* @param version version of the current instaled module to patch | ||
* @param options plugin options | ||
* @param basedir module absolute path | ||
*/ | ||
enable( | ||
// tslint:disable-next-line:no-any | ||
moduleExports, tracer, version, basedir) { | ||
this.setPluginContext(moduleExports, tracer, version, basedir); | ||
// tslint:disable-next-line:no-any | ||
moduleExports, tracer, version, options, basedir) { | ||
this.setPluginContext(moduleExports, tracer, version, options, basedir); | ||
return this.applyPatch(); | ||
@@ -66,0 +69,0 @@ } |
@@ -25,8 +25,16 @@ /** | ||
* @param version version of the current instaled module to patch | ||
* @param options plugin options | ||
* @param basedir module absolute path | ||
*/ | ||
enable(moduleExports: any, tracer: Tracer, version: string, basedir?: string): any; | ||
enable(moduleExports: any, tracer: Tracer, version: string, options: PluginConfig, basedir?: string): any; | ||
/** Method to disable the instrumentation */ | ||
disable(): void; | ||
} | ||
export declare type PluginConfig = { | ||
[key: string]: any; | ||
}; | ||
export declare type NamedPluginConfig = { | ||
module: string; | ||
config: PluginConfig; | ||
}; | ||
/** | ||
@@ -38,2 +46,5 @@ * Type PluginNames: each key should be the name of the module to trace, | ||
export declare type PluginNames = { | ||
[pluginName: string]: string | NamedPluginConfig; | ||
}; | ||
export declare type PluginInternalFilesVersion = { | ||
[pluginName: string]: string; | ||
@@ -46,3 +57,3 @@ }; | ||
export declare type PluginInternalFiles = { | ||
[versions: string]: PluginNames; | ||
[versions: string]: PluginInternalFilesVersion; | ||
}; |
@@ -0,1 +1,16 @@ | ||
/** | ||
* 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 { SpanBase } from './span-base'; | ||
@@ -37,3 +52,3 @@ import * as types from './types'; | ||
*/ | ||
startChildSpan(name: string, kind: string, parentSpanId?: string): types.Span; | ||
startChildSpan(name: string, kind: types.SpanKind, parentSpanId?: string): types.Span; | ||
} |
@@ -22,2 +22,3 @@ "use strict"; | ||
const span_base_1 = require("./span-base"); | ||
const types = require("./types"); | ||
/** Defines a root span */ | ||
@@ -45,4 +46,6 @@ class RootSpan extends span_base_1.SpanBase { | ||
this.spansLocal = []; | ||
this.kind = context && context.kind ? context.kind : null; | ||
this.kind = | ||
context && context.kind ? context.kind : types.SpanKind.UNSPECIFIED; | ||
this.logger = tracer.logger || logger.logger(); | ||
this.activeTraceParams = tracer.activeTraceParams; | ||
} | ||
@@ -49,0 +52,0 @@ /** Gets span list from rootspan instance. */ |
@@ -17,2 +17,3 @@ /** | ||
import { Logger } from '../../common/types'; | ||
import * as configTypes from '../config/types'; | ||
import * as types from './types'; | ||
@@ -49,13 +50,23 @@ /** Defines a base model for spans. */ | ||
/** Kind of span. */ | ||
kind: string; | ||
kind: types.SpanKind; | ||
/** A final status for this span */ | ||
status: number; | ||
status: types.Status; | ||
/** set isRootSpan */ | ||
readonly abstract isRootSpan: boolean; | ||
abstract readonly isRootSpan: boolean; | ||
/** Trace Parameters */ | ||
activeTraceParams: configTypes.TraceParams; | ||
/** The number of dropped attributes. */ | ||
droppedAttributesCount: number; | ||
/** The number of dropped links. */ | ||
droppedLinksCount: number; | ||
/** The number of dropped annotations. */ | ||
droppedAnnotationsCount: number; | ||
/** The number of dropped message events. */ | ||
droppedMessageEventsCount: number; | ||
/** Constructs a new SpanBaseModel instance. */ | ||
constructor(); | ||
/** Gets the trace ID. */ | ||
readonly abstract traceId: string; | ||
abstract readonly traceId: string; | ||
/** Gets the trace state */ | ||
readonly abstract traceState: types.TraceState; | ||
abstract readonly traceState: types.TraceState; | ||
/** Indicates if span was started. */ | ||
@@ -102,3 +113,3 @@ readonly started: boolean; | ||
*/ | ||
addLink(traceId: string, spanId: string, type: string, attributes?: types.Attributes): void; | ||
addLink(traceId: string, spanId: string, type: types.LinkType, attributes?: types.Attributes): void; | ||
/** | ||
@@ -110,3 +121,9 @@ * Adds a message event to the span. | ||
*/ | ||
addMessageEvent(type: string, id: string, timestamp?: number): void; | ||
addMessageEvent(type: types.MessageEventType, id: string, timestamp?: number): void; | ||
/** | ||
* Sets a status to the span. | ||
* @param code The canonical status code. | ||
* @param message optional A developer-facing error message. | ||
*/ | ||
setStatus(code: types.CanonicalCode, message?: string): void; | ||
/** Starts the span. */ | ||
@@ -113,0 +130,0 @@ start(): void; |
@@ -5,2 +5,6 @@ "use strict"; | ||
const util_1 = require("../../internal/util"); | ||
const types = require("./types"); | ||
const STATUS_OK = { | ||
code: types.CanonicalCode.OK | ||
}; | ||
/** Defines a base model for spans. */ | ||
@@ -32,3 +36,13 @@ class SpanBase { | ||
/** Kind of span. */ | ||
this.kind = null; | ||
this.kind = types.SpanKind.UNSPECIFIED; | ||
/** A final status for this span */ | ||
this.status = STATUS_OK; | ||
/** The number of dropped attributes. */ | ||
this.droppedAttributesCount = 0; | ||
/** The number of dropped links. */ | ||
this.droppedLinksCount = 0; | ||
/** The number of dropped annotations. */ | ||
this.droppedAnnotationsCount = 0; | ||
/** The number of dropped message events. */ | ||
this.droppedMessageEventsCount = 0; | ||
this.className = this.constructor.name; | ||
@@ -93,2 +107,11 @@ this.id = util_1.randomSpanId(); | ||
addAttribute(key, value) { | ||
if (this.attributes[key]) { | ||
delete this.attributes[key]; | ||
} | ||
if (Object.keys(this.attributes).length >= | ||
this.activeTraceParams.numberOfAttributesPerSpan) { | ||
this.droppedAttributesCount++; | ||
const attributeKeyToDelete = Object.keys(this.attributes).shift(); | ||
delete this.attributes[attributeKeyToDelete]; | ||
} | ||
this.attributes[key] = value; | ||
@@ -103,2 +126,7 @@ } | ||
addAnnotation(description, attributes, timestamp = 0) { | ||
if (this.annotations.length >= | ||
this.activeTraceParams.numberOfAnnontationEventsPerSpan) { | ||
this.annotations.shift(); | ||
this.droppedAnnotationsCount++; | ||
} | ||
this.annotations.push({ | ||
@@ -118,2 +146,6 @@ 'description': description, | ||
addLink(traceId, spanId, type, attributes) { | ||
if (this.links.length >= this.activeTraceParams.numberOfLinksPerSpan) { | ||
this.links.shift(); | ||
this.droppedLinksCount++; | ||
} | ||
this.links.push({ | ||
@@ -133,2 +165,7 @@ 'traceId': traceId, | ||
addMessageEvent(type, id, timestamp = 0) { | ||
if (this.messageEvents.length >= | ||
this.activeTraceParams.numberOfMessageEventsPerSpan) { | ||
this.messageEvents.shift(); | ||
this.droppedMessageEventsCount++; | ||
} | ||
this.messageEvents.push({ | ||
@@ -140,2 +177,10 @@ 'type': type, | ||
} | ||
/** | ||
* Sets a status to the span. | ||
* @param code The canonical status code. | ||
* @param message optional A developer-facing error message. | ||
*/ | ||
setStatus(code, message) { | ||
this.status = { code, message }; | ||
} | ||
/** Starts the span. */ | ||
@@ -142,0 +187,0 @@ start() { |
@@ -0,1 +1,16 @@ | ||
/** | ||
* 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 { SpanBase } from './span-base'; | ||
@@ -2,0 +17,0 @@ import * as types from './types'; |
@@ -33,2 +33,3 @@ "use strict"; | ||
this.parentSpanId = root.id; | ||
this.activeTraceParams = this.root.activeTraceParams; | ||
} | ||
@@ -35,0 +36,0 @@ /** Gets trace id of span. */ |
@@ -0,5 +1,20 @@ | ||
/** | ||
* 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. | ||
*/ | ||
/// <reference types="node" /> | ||
/// <reference types="mocha" /> | ||
import * as loggerTypes from '../../common/types'; | ||
import * as configTypes from '../config/types'; | ||
import { TraceParams } from '../config/types'; | ||
import { Propagation } from '../propagation/types'; | ||
@@ -28,2 +43,4 @@ import * as samplerTypes from '../sampler/types'; | ||
logger: loggerTypes.Logger; | ||
/** A configuration object for trace parameters */ | ||
activeTraceParams: TraceParams; | ||
/** Constructs a new TraceImpl instance. */ | ||
@@ -69,4 +86,4 @@ constructor(); | ||
unregisterSpanEventListener(listener: types.SpanEventListener): void; | ||
private notifyStartSpan(root); | ||
private notifyEndSpan(root); | ||
private notifyStartSpan; | ||
private notifyEndSpan; | ||
/** Clears the current root span. */ | ||
@@ -77,6 +94,6 @@ clearCurrentTrace(): void; | ||
* @param name The span name. | ||
* @param type The span type. | ||
* @param kind optional The span kind. | ||
* @param parentSpanId The parent span ID. | ||
*/ | ||
startChildSpan(name?: string, type?: string): types.Span; | ||
startChildSpan(name?: string, kind?: types.SpanKind): types.Span; | ||
/** | ||
@@ -83,0 +100,0 @@ * Binds the trace context to the given function. |
@@ -40,2 +40,3 @@ "use strict"; | ||
this.clearCurrentTrace(); | ||
this.activeTraceParams = {}; | ||
} | ||
@@ -65,2 +66,12 @@ /** Gets the current root span. */ | ||
this.sampler = sampler_1.SamplerBuilder.getSampler(config.samplingRate); | ||
if (config.traceParams) { | ||
this.activeTraceParams.numberOfAnnontationEventsPerSpan = | ||
sampler_1.TraceParamsBuilder.getNumberOfAnnotationEventsPerSpan(config.traceParams); | ||
this.activeTraceParams.numberOfAttributesPerSpan = | ||
sampler_1.TraceParamsBuilder.getNumberOfAttributesPerSpan(config.traceParams); | ||
this.activeTraceParams.numberOfMessageEventsPerSpan = | ||
sampler_1.TraceParamsBuilder.getNumberOfMessageEventsPerSpan(config.traceParams); | ||
this.activeTraceParams.numberOfLinksPerSpan = | ||
sampler_1.TraceParamsBuilder.getNumberOfLinksPerSpan(config.traceParams); | ||
} | ||
return this; | ||
@@ -102,5 +113,6 @@ } | ||
const aRoot = new root_span_1.RootSpan(this, options); | ||
const sampleDecision = propagatedSample ? | ||
propagatedSample : | ||
this.sampler.shouldSample(aRoot.traceId); | ||
let sampleDecision = propagatedSample; | ||
if (!sampleDecision) { | ||
sampleDecision = this.sampler.shouldSample(aRoot.traceId); | ||
} | ||
if (sampleDecision) { | ||
@@ -189,6 +201,6 @@ this.currentRootSpan = aRoot; | ||
* @param name The span name. | ||
* @param type The span type. | ||
* @param kind optional The span kind. | ||
* @param parentSpanId The parent span ID. | ||
*/ | ||
startChildSpan(name, type) { | ||
startChildSpan(name, kind) { | ||
let newSpan = null; | ||
@@ -199,3 +211,3 @@ if (!this.currentRootSpan) { | ||
else { | ||
newSpan = this.currentRootSpan.startChildSpan(name, type); | ||
newSpan = this.currentRootSpan.startChildSpan(name, kind); | ||
} | ||
@@ -202,0 +214,0 @@ return newSpan; |
@@ -1,3 +0,1 @@ | ||
/// <reference types="node" /> | ||
/// <reference types="mocha" /> | ||
/** | ||
@@ -18,2 +16,3 @@ * Copyright 2018, OpenCensus Authors | ||
*/ | ||
/// <reference types="node" /> | ||
import * as loggerTypes from '../../common/types'; | ||
@@ -29,2 +28,146 @@ import * as configTypes from '../config/types'; | ||
} | ||
/** | ||
* The status of a Span by providing a standard CanonicalCode in conjunction | ||
* with an optional descriptive message. | ||
*/ | ||
export interface Status { | ||
/** The canonical code of this message. */ | ||
code: CanonicalCode; | ||
/** A developer-facing error message. */ | ||
message?: string; | ||
} | ||
/** An enumeration of canonical status codes. */ | ||
export declare enum CanonicalCode { | ||
/** | ||
* Not an error; returned on success | ||
*/ | ||
OK = 0, | ||
/** | ||
* The operation was cancelled (typically by the caller). | ||
*/ | ||
CANCELLED = 1, | ||
/** | ||
* Unknown error. An example of where this error may be returned is | ||
* if a status value received from another address space belongs to | ||
* an error-space that is not known in this address space. Also | ||
* errors raised by APIs that do not return enough error information | ||
* may be converted to this error. | ||
*/ | ||
UNKNOWN = 2, | ||
/** | ||
* Client specified an invalid argument. Note that this differs | ||
* from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments | ||
* that are problematic regardless of the state of the system | ||
* (e.g., a malformed file name). | ||
*/ | ||
INVALID_ARGUMENT = 3, | ||
/** | ||
* Deadline expired before operation could complete. For operations | ||
* that change the state of the system, this error may be returned | ||
* even if the operation has completed successfully. For example, a | ||
* successful response from a server could have been delayed long | ||
* enough for the deadline to expire. | ||
*/ | ||
DEADLINE_EXCEEDED = 4, | ||
/** | ||
* Some requested entity (e.g., file or directory) was not found. | ||
*/ | ||
NOT_FOUND = 5, | ||
/** | ||
* Some entity that we attempted to create (e.g., file or directory) | ||
* already exists. | ||
*/ | ||
ALREADY_EXISTS = 6, | ||
/** | ||
* The caller does not have permission to execute the specified | ||
* operation. PERMISSION_DENIED must not be used for rejections | ||
* caused by exhausting some resource (use RESOURCE_EXHAUSTED | ||
* instead for those errors). PERMISSION_DENIED must not be | ||
* used if the caller can not be identified (use UNAUTHENTICATED | ||
* instead for those errors). | ||
*/ | ||
PERMISSION_DENIED = 7, | ||
/** | ||
* Some resource has been exhausted, perhaps a per-user quota, or | ||
* perhaps the entire file system is out of space. | ||
*/ | ||
RESOURCE_EXHAUSTED = 8, | ||
/** | ||
* Operation was rejected because the system is not in a state | ||
* required for the operation's execution. For example, directory | ||
* to be deleted may be non-empty, an rmdir operation is applied to | ||
* a non-directory, etc. | ||
* | ||
* A litmus test that may help a service implementor in deciding | ||
* between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: | ||
* | ||
* - Use UNAVAILABLE if the client can retry just the failing call. | ||
* - Use ABORTED if the client should retry at a higher-level | ||
* (e.g., restarting a read-modify-write sequence). | ||
* - Use FAILED_PRECONDITION if the client should not retry until | ||
* the system state has been explicitly fixed. E.g., if an "rmdir" | ||
* fails because the directory is non-empty, FAILED_PRECONDITION | ||
* should be returned since the client should not retry unless | ||
* they have first fixed up the directory by deleting files from it. | ||
* - Use FAILED_PRECONDITION if the client performs conditional | ||
* REST Get/Update/Delete on a resource and the resource on the | ||
* server does not match the condition. E.g., conflicting | ||
* read-modify-write on the same resource. | ||
*/ | ||
FAILED_PRECONDITION = 9, | ||
/** | ||
* The operation was aborted, typically due to a concurrency issue | ||
* like sequencer check failures, transaction aborts, etc. | ||
* | ||
* See litmus test above for deciding between FAILED_PRECONDITION, | ||
* ABORTED, and UNAVAILABLE. | ||
*/ | ||
ABORTED = 10, | ||
/** | ||
* Operation was attempted past the valid range. E.g., seeking or | ||
* reading past end of file. | ||
* | ||
* Unlike INVALID_ARGUMENT, this error indicates a problem that may | ||
* be fixed if the system state changes. For example, a 32-bit file | ||
* system will generate INVALID_ARGUMENT if asked to read at an | ||
* offset that is not in the range [0,2^32-1], but it will generate | ||
* OUT_OF_RANGE if asked to read from an offset past the current | ||
* file size. | ||
* | ||
* There is a fair bit of overlap between FAILED_PRECONDITION and | ||
* OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific | ||
* error) when it applies so that callers who are iterating through | ||
* a space can easily look for an OUT_OF_RANGE error to detect when | ||
* they are done. | ||
*/ | ||
OUT_OF_RANGE = 11, | ||
/** | ||
* Operation is not implemented or not supported/enabled in this service. | ||
*/ | ||
UNIMPLEMENTED = 12, | ||
/** | ||
* Internal errors. Means some invariants expected by underlying | ||
* system has been broken. If you see one of these errors, | ||
* something is very broken. | ||
*/ | ||
INTERNAL = 13, | ||
/** | ||
* The service is currently unavailable. This is a most likely a | ||
* transient condition and may be corrected by retrying with | ||
* a backoff. | ||
* | ||
* See litmus test above for deciding between FAILED_PRECONDITION, | ||
* ABORTED, and UNAVAILABLE. | ||
*/ | ||
UNAVAILABLE = 14, | ||
/** | ||
* Unrecoverable data loss or corruption. | ||
*/ | ||
DATA_LOSS = 15, | ||
/** | ||
* The request does not have valid authentication credentials for the | ||
* operation. | ||
*/ | ||
UNAUTHENTICATED = 16 | ||
} | ||
/** A text annotation with a set of attributes. */ | ||
@@ -44,5 +187,12 @@ export interface Annotation { | ||
/** Indicates whether the message was sent or received. */ | ||
type: string; | ||
type: MessageEventType; | ||
/** An identifier for the MessageEvent's message. */ | ||
id: string; | ||
/** The number of uncompressed bytes sent or received. */ | ||
uncompressedSize?: number; | ||
/** | ||
* The number of compressed bytes sent or received. If zero or | ||
* undefined, assumed to be the same size as uncompressed. | ||
*/ | ||
compressedSize?: number; | ||
} | ||
@@ -59,3 +209,3 @@ /** | ||
/** The relationship of the current span relative to the linked. */ | ||
type: string; | ||
type: LinkType; | ||
/** A set of attributes on the link. */ | ||
@@ -71,3 +221,3 @@ attributes: Attributes; | ||
/** Span kind */ | ||
kind?: string; | ||
kind?: SpanKind; | ||
} | ||
@@ -92,2 +242,44 @@ export declare type TraceState = string; | ||
} | ||
/** An event describing a message sent/received between Spans. */ | ||
export declare enum MessageEventType { | ||
/** Unknown event type. */ | ||
UNSPECIFIED = 0, | ||
/** Indicates a sent message. */ | ||
SENT = 1, | ||
/** Indicates a received message. */ | ||
RECEIVED = 2 | ||
} | ||
/** | ||
* Type of span. Can be used to specify additional relationships between spans | ||
* in addition to a parent/child relationship. | ||
*/ | ||
export declare enum SpanKind { | ||
/** Unspecified */ | ||
UNSPECIFIED = 0, | ||
/** | ||
* Indicates that the span covers server-side handling of an RPC or other | ||
* remote network request. | ||
*/ | ||
SERVER = 1, | ||
/** | ||
* Indicates that the span covers the client-side wrapper around an RPC or | ||
* other remote request. | ||
*/ | ||
CLIENT = 2 | ||
} | ||
/** | ||
* Type of link. The relationship of the current span relative to the linked | ||
* span. | ||
*/ | ||
export declare enum LinkType { | ||
/** | ||
* The relationship of the two spans is unknown, or known but other | ||
* than parent-child. | ||
*/ | ||
UNSPECIFIED = 0, | ||
/** The linked span is a child of the current span. */ | ||
CHILD_LINKED_SPAN = 1, | ||
/** The linked span is a parent of the current span. */ | ||
PARENT_LINKED_SPAN = 2 | ||
} | ||
/** Interface for Span */ | ||
@@ -104,7 +296,7 @@ export interface Span { | ||
/** Kind of span. */ | ||
kind: string; | ||
kind: SpanKind; | ||
/** An object to log information to */ | ||
logger: loggerTypes.Logger; | ||
/** A final status for this span */ | ||
status: number; | ||
status: Status; | ||
/** A set of attributes, each in the format [KEY]:[VALUE] */ | ||
@@ -145,2 +337,12 @@ attributes: Attributes; | ||
readonly spanContext: SpanContext; | ||
/** Trace Parameters */ | ||
activeTraceParams: configTypes.TraceParams; | ||
/** The number of dropped attributes. */ | ||
droppedAttributesCount: number; | ||
/** The number of dropped links. */ | ||
droppedLinksCount: number; | ||
/** The number of dropped annotations. */ | ||
droppedAnnotationsCount: number; | ||
/** The number of dropped message events. */ | ||
droppedMessageEventsCount: number; | ||
/** | ||
@@ -166,3 +368,3 @@ * Adds an atribute to the span. | ||
*/ | ||
addLink(traceId: string, spanId: string, type: string, attributes?: Attributes): void; | ||
addLink(traceId: string, spanId: string, type: LinkType, attributes?: Attributes): void; | ||
/** | ||
@@ -174,3 +376,9 @@ * Adds a message event to the span. | ||
*/ | ||
addMessageEvent(type: string, id: string, timestamp?: number): void; | ||
addMessageEvent(type: MessageEventType, id: string, timestamp?: number): void; | ||
/** | ||
* Sets a status to the span. | ||
* @param code The canonical status code. | ||
* @param message optional A developer-facing error message. | ||
*/ | ||
setStatus(code: CanonicalCode, message?: string): void; | ||
/** Starts a span. */ | ||
@@ -188,3 +396,3 @@ start(): void; | ||
/** Starts a new Span instance in the RootSpan instance */ | ||
startChildSpan(name: string, type: string): Span; | ||
startChildSpan(name: string, kind: SpanKind): Span; | ||
} | ||
@@ -199,2 +407,4 @@ /** Interface for Tracer */ | ||
logger: loggerTypes.Logger; | ||
/** A configuration object for trace parameters */ | ||
activeTraceParams: configTypes.TraceParams; | ||
/** A propagation instance */ | ||
@@ -240,3 +450,3 @@ readonly propagation: Propagation; | ||
*/ | ||
startChildSpan(name?: string, type?: string, parentSpanId?: string): Span; | ||
startChildSpan(name?: string, type?: SpanKind, parentSpanId?: string): Span; | ||
/** | ||
@@ -243,0 +453,0 @@ * Binds the trace context to the given function. |
@@ -18,2 +18,182 @@ "use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
/** An enumeration of canonical status codes. */ | ||
var CanonicalCode; | ||
(function (CanonicalCode) { | ||
/** | ||
* Not an error; returned on success | ||
*/ | ||
CanonicalCode[CanonicalCode["OK"] = 0] = "OK"; | ||
/** | ||
* The operation was cancelled (typically by the caller). | ||
*/ | ||
CanonicalCode[CanonicalCode["CANCELLED"] = 1] = "CANCELLED"; | ||
/** | ||
* Unknown error. An example of where this error may be returned is | ||
* if a status value received from another address space belongs to | ||
* an error-space that is not known in this address space. Also | ||
* errors raised by APIs that do not return enough error information | ||
* may be converted to this error. | ||
*/ | ||
CanonicalCode[CanonicalCode["UNKNOWN"] = 2] = "UNKNOWN"; | ||
/** | ||
* Client specified an invalid argument. Note that this differs | ||
* from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments | ||
* that are problematic regardless of the state of the system | ||
* (e.g., a malformed file name). | ||
*/ | ||
CanonicalCode[CanonicalCode["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT"; | ||
/** | ||
* Deadline expired before operation could complete. For operations | ||
* that change the state of the system, this error may be returned | ||
* even if the operation has completed successfully. For example, a | ||
* successful response from a server could have been delayed long | ||
* enough for the deadline to expire. | ||
*/ | ||
CanonicalCode[CanonicalCode["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED"; | ||
/** | ||
* Some requested entity (e.g., file or directory) was not found. | ||
*/ | ||
CanonicalCode[CanonicalCode["NOT_FOUND"] = 5] = "NOT_FOUND"; | ||
/** | ||
* Some entity that we attempted to create (e.g., file or directory) | ||
* already exists. | ||
*/ | ||
CanonicalCode[CanonicalCode["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS"; | ||
/** | ||
* The caller does not have permission to execute the specified | ||
* operation. PERMISSION_DENIED must not be used for rejections | ||
* caused by exhausting some resource (use RESOURCE_EXHAUSTED | ||
* instead for those errors). PERMISSION_DENIED must not be | ||
* used if the caller can not be identified (use UNAUTHENTICATED | ||
* instead for those errors). | ||
*/ | ||
CanonicalCode[CanonicalCode["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED"; | ||
/** | ||
* Some resource has been exhausted, perhaps a per-user quota, or | ||
* perhaps the entire file system is out of space. | ||
*/ | ||
CanonicalCode[CanonicalCode["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED"; | ||
/** | ||
* Operation was rejected because the system is not in a state | ||
* required for the operation's execution. For example, directory | ||
* to be deleted may be non-empty, an rmdir operation is applied to | ||
* a non-directory, etc. | ||
* | ||
* A litmus test that may help a service implementor in deciding | ||
* between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: | ||
* | ||
* - Use UNAVAILABLE if the client can retry just the failing call. | ||
* - Use ABORTED if the client should retry at a higher-level | ||
* (e.g., restarting a read-modify-write sequence). | ||
* - Use FAILED_PRECONDITION if the client should not retry until | ||
* the system state has been explicitly fixed. E.g., if an "rmdir" | ||
* fails because the directory is non-empty, FAILED_PRECONDITION | ||
* should be returned since the client should not retry unless | ||
* they have first fixed up the directory by deleting files from it. | ||
* - Use FAILED_PRECONDITION if the client performs conditional | ||
* REST Get/Update/Delete on a resource and the resource on the | ||
* server does not match the condition. E.g., conflicting | ||
* read-modify-write on the same resource. | ||
*/ | ||
CanonicalCode[CanonicalCode["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION"; | ||
/** | ||
* The operation was aborted, typically due to a concurrency issue | ||
* like sequencer check failures, transaction aborts, etc. | ||
* | ||
* See litmus test above for deciding between FAILED_PRECONDITION, | ||
* ABORTED, and UNAVAILABLE. | ||
*/ | ||
CanonicalCode[CanonicalCode["ABORTED"] = 10] = "ABORTED"; | ||
/** | ||
* Operation was attempted past the valid range. E.g., seeking or | ||
* reading past end of file. | ||
* | ||
* Unlike INVALID_ARGUMENT, this error indicates a problem that may | ||
* be fixed if the system state changes. For example, a 32-bit file | ||
* system will generate INVALID_ARGUMENT if asked to read at an | ||
* offset that is not in the range [0,2^32-1], but it will generate | ||
* OUT_OF_RANGE if asked to read from an offset past the current | ||
* file size. | ||
* | ||
* There is a fair bit of overlap between FAILED_PRECONDITION and | ||
* OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific | ||
* error) when it applies so that callers who are iterating through | ||
* a space can easily look for an OUT_OF_RANGE error to detect when | ||
* they are done. | ||
*/ | ||
CanonicalCode[CanonicalCode["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE"; | ||
/** | ||
* Operation is not implemented or not supported/enabled in this service. | ||
*/ | ||
CanonicalCode[CanonicalCode["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED"; | ||
/** | ||
* Internal errors. Means some invariants expected by underlying | ||
* system has been broken. If you see one of these errors, | ||
* something is very broken. | ||
*/ | ||
CanonicalCode[CanonicalCode["INTERNAL"] = 13] = "INTERNAL"; | ||
/** | ||
* The service is currently unavailable. This is a most likely a | ||
* transient condition and may be corrected by retrying with | ||
* a backoff. | ||
* | ||
* See litmus test above for deciding between FAILED_PRECONDITION, | ||
* ABORTED, and UNAVAILABLE. | ||
*/ | ||
CanonicalCode[CanonicalCode["UNAVAILABLE"] = 14] = "UNAVAILABLE"; | ||
/** | ||
* Unrecoverable data loss or corruption. | ||
*/ | ||
CanonicalCode[CanonicalCode["DATA_LOSS"] = 15] = "DATA_LOSS"; | ||
/** | ||
* The request does not have valid authentication credentials for the | ||
* operation. | ||
*/ | ||
CanonicalCode[CanonicalCode["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED"; | ||
})(CanonicalCode = exports.CanonicalCode || (exports.CanonicalCode = {})); | ||
/** An event describing a message sent/received between Spans. */ | ||
var MessageEventType; | ||
(function (MessageEventType) { | ||
/** Unknown event type. */ | ||
MessageEventType[MessageEventType["UNSPECIFIED"] = 0] = "UNSPECIFIED"; | ||
/** Indicates a sent message. */ | ||
MessageEventType[MessageEventType["SENT"] = 1] = "SENT"; | ||
/** Indicates a received message. */ | ||
MessageEventType[MessageEventType["RECEIVED"] = 2] = "RECEIVED"; | ||
})(MessageEventType = exports.MessageEventType || (exports.MessageEventType = {})); | ||
/** | ||
* Type of span. Can be used to specify additional relationships between spans | ||
* in addition to a parent/child relationship. | ||
*/ | ||
var SpanKind; | ||
(function (SpanKind) { | ||
/** Unspecified */ | ||
SpanKind[SpanKind["UNSPECIFIED"] = 0] = "UNSPECIFIED"; | ||
/** | ||
* Indicates that the span covers server-side handling of an RPC or other | ||
* remote network request. | ||
*/ | ||
SpanKind[SpanKind["SERVER"] = 1] = "SERVER"; | ||
/** | ||
* Indicates that the span covers the client-side wrapper around an RPC or | ||
* other remote request. | ||
*/ | ||
SpanKind[SpanKind["CLIENT"] = 2] = "CLIENT"; | ||
})(SpanKind = exports.SpanKind || (exports.SpanKind = {})); | ||
/** | ||
* Type of link. The relationship of the current span relative to the linked | ||
* span. | ||
*/ | ||
var LinkType; | ||
(function (LinkType) { | ||
/** | ||
* The relationship of the two spans is unknown, or known but other | ||
* than parent-child. | ||
*/ | ||
LinkType[LinkType["UNSPECIFIED"] = 0] = "UNSPECIFIED"; | ||
/** The linked span is a child of the current span. */ | ||
LinkType[LinkType["CHILD_LINKED_SPAN"] = 1] = "CHILD_LINKED_SPAN"; | ||
/** The linked span is a parent of the current span. */ | ||
LinkType[LinkType["PARENT_LINKED_SPAN"] = 2] = "PARENT_LINKED_SPAN"; | ||
})(LinkType = exports.LinkType || (exports.LinkType = {})); | ||
//# sourceMappingURL=types.js.map |
@@ -16,2 +16,3 @@ /** | ||
*/ | ||
import { TraceParams } from '../config/types'; | ||
import { Sampler } from './types'; | ||
@@ -58,1 +59,16 @@ /** Sampler that samples every trace. */ | ||
} | ||
/** Default Limit for Annotations per span */ | ||
export declare const DEFAULT_SPAN_MAX_NUM_ANNOTATIONS = 32; | ||
/** Default limit for Message events per span */ | ||
export declare const DEFAULT_SPAN_MAX_NUM_MESSAGE_EVENTS = 128; | ||
/** Default limit for Attributes per span */ | ||
export declare const DEFAULT_SPAN_MAX_NUM_ATTRIBUTES = 32; | ||
/** Default limit for Links per span */ | ||
export declare const DEFAULT_SPAN_MAX_NUM_LINKS = 32; | ||
/** Builder Class of TraceParams */ | ||
export declare class TraceParamsBuilder { | ||
static getNumberOfAnnotationEventsPerSpan(traceParameters: TraceParams): number; | ||
static getNumberOfAttributesPerSpan(traceParameters: TraceParams): number; | ||
static getNumberOfMessageEventsPerSpan(traceParameters: TraceParams): number; | ||
static getNumberOfLinksPerSpan(traceParameters: TraceParams): number; | ||
} |
@@ -94,2 +94,37 @@ "use strict"; | ||
exports.SamplerBuilder = SamplerBuilder; | ||
/** Default Limit for Annotations per span */ | ||
exports.DEFAULT_SPAN_MAX_NUM_ANNOTATIONS = 32; | ||
/** Default limit for Message events per span */ | ||
exports.DEFAULT_SPAN_MAX_NUM_MESSAGE_EVENTS = 128; | ||
/** Default limit for Attributes per span */ | ||
exports.DEFAULT_SPAN_MAX_NUM_ATTRIBUTES = 32; | ||
/** Default limit for Links per span */ | ||
exports.DEFAULT_SPAN_MAX_NUM_LINKS = 32; | ||
/** Builder Class of TraceParams */ | ||
class TraceParamsBuilder { | ||
static getNumberOfAnnotationEventsPerSpan(traceParameters) { | ||
return traceParameters.numberOfAnnontationEventsPerSpan > | ||
exports.DEFAULT_SPAN_MAX_NUM_ANNOTATIONS ? | ||
exports.DEFAULT_SPAN_MAX_NUM_ANNOTATIONS : | ||
traceParameters.numberOfAnnontationEventsPerSpan; | ||
} | ||
static getNumberOfAttributesPerSpan(traceParameters) { | ||
return traceParameters.numberOfAttributesPerSpan > | ||
exports.DEFAULT_SPAN_MAX_NUM_ATTRIBUTES ? | ||
exports.DEFAULT_SPAN_MAX_NUM_ATTRIBUTES : | ||
traceParameters.numberOfAttributesPerSpan; | ||
} | ||
static getNumberOfMessageEventsPerSpan(traceParameters) { | ||
return traceParameters.numberOfMessageEventsPerSpan > | ||
exports.DEFAULT_SPAN_MAX_NUM_MESSAGE_EVENTS ? | ||
exports.DEFAULT_SPAN_MAX_NUM_MESSAGE_EVENTS : | ||
traceParameters.numberOfMessageEventsPerSpan; | ||
} | ||
static getNumberOfLinksPerSpan(traceParameters) { | ||
return traceParameters.numberOfLinksPerSpan > exports.DEFAULT_SPAN_MAX_NUM_LINKS ? | ||
exports.DEFAULT_SPAN_MAX_NUM_LINKS : | ||
traceParameters.numberOfLinksPerSpan; | ||
} | ||
} | ||
exports.TraceParamsBuilder = TraceParamsBuilder; | ||
//# sourceMappingURL=sampler.js.map |
{ | ||
"name": "@opencensus/core", | ||
"version": "0.0.8", | ||
"version": "0.0.9", | ||
"description": "OpenCensus is a toolkit for collecting application performance and behavior data.", | ||
@@ -9,8 +9,10 @@ "main": "build/src/index.js", | ||
"scripts": { | ||
"test": "nyc -x '**/test/**' --reporter=html --reporter=text mocha 'build/test/**/*.js'", | ||
"test": "nyc mocha build/test/**/*.js", | ||
"codecov": "nyc report --reporter=json && codecov -f coverage/*.json", | ||
"clean": "rimraf build/*", | ||
"check": "gts check", | ||
"compile": "tsc -p .", | ||
"compile:release": "tsc -p tsconfig-release.json", | ||
"fix": "gts fix", | ||
"prepare": "npm run compile", | ||
"prepare": "npm run compile:release", | ||
"pretest": "npm run compile", | ||
@@ -23,3 +25,5 @@ "posttest": "npm run check" | ||
"tracing", | ||
"profiling" | ||
"profiling", | ||
"metrics", | ||
"stats" | ||
], | ||
@@ -50,2 +54,3 @@ "author": "Google Inc.", | ||
"@types/uuid": "^3.4.3", | ||
"codecov": "^3.1.0", | ||
"gts": "^0.9.0", | ||
@@ -55,5 +60,5 @@ "intercept-stdout": "^0.1.2", | ||
"ncp": "^2.0.0", | ||
"nyc": "11.6.0", | ||
"nyc": "13.1.0", | ||
"ts-node": "^7.0.1", | ||
"typescript": "~2.6.1" | ||
"typescript": "~2.9.0" | ||
}, | ||
@@ -60,0 +65,0 @@ "dependencies": { |
@@ -17,3 +17,3 @@ # OpenCensus Core Node.js | ||
#### Set up a new Stats manager instance. | ||
#### Get the global Stats manager instance. | ||
@@ -23,9 +23,6 @@ To enable metrics, we’ll import a few items from OpenCensus Core package. | ||
```javascript | ||
const { Stats, MeasureUnit, AggregationType } = require('@opencensus/core'); | ||
const { globalStats, MeasureUnit, AggregationType, TagMap } = require('@opencensus/core'); | ||
// Create the Stats manager | ||
const stats = new Stats(); | ||
// The latency in milliseconds | ||
const mLatencyMs = stats.createMeasureDouble( | ||
const mLatencyMs = globalStats.createMeasureDouble( | ||
"repl/latency", | ||
@@ -42,7 +39,8 @@ MeasureUnit.MS, | ||
```javascript | ||
const methodTagKey = "method"; | ||
const statusTagKey = "status"; | ||
const errorTagKey = "error"; | ||
const methodTagKey = { name: "method" }; | ||
const statusTagKey = { name: "status" }; | ||
const errorTagKey = { name: "error" }; | ||
const latencyView = stats.createView( | ||
// Create & Register the view. | ||
const latencyView = globalStats.createView( | ||
"demo/latency", | ||
@@ -57,2 +55,3 @@ mLatencyMs, | ||
); | ||
globalStats.registerView(latencyView); | ||
``` | ||
@@ -62,15 +61,15 @@ | ||
Now we will record the desired metrics. To do so, we will use ```stats.record()``` and pass in measurements. | ||
Now we will record the desired metrics. To do so, we will use ```globalStats.record()``` and pass in measurements. | ||
```javascript | ||
const [_, startNanoseconds] = process.hrtime(); | ||
const tags = {method: "repl", status: "OK"}; | ||
const tags = new TagMap(); | ||
tags.set(methodTagKey, { value: "REPL" }); | ||
tags.set(statusTagKey, { value: "OK" }); | ||
stats.record({ | ||
globalStats.record([{ | ||
measure: mLatencyMs, | ||
tags, | ||
value: sinceInMilliseconds(startNanoseconds) | ||
}); | ||
}], tags); | ||
function sinceInMilliseconds(startNanoseconds) { | ||
@@ -82,2 +81,15 @@ const [_, endNanoseconds] = process.hrtime(); | ||
Measures can be of type `Int64` or `DOUBLE`, created by calling `createMeasureInt64` and `createMeasureDouble` respectively. Its units can be: | ||
| MeasureUnit | Usage | | ||
| ----------- | ----- | | ||
| `UNIT` | for general counts | | ||
| `BYTE` | bytes | | ||
| `KBYTE` | Kbytes | | ||
| `SEC` | seconds | | ||
| `MS` | millisecond | | ||
| `NS` | nanosecond | | ||
Views can have agregations of type `SUM`, `LAST_VALUE`, `COUNT` and `DISTRIBUTION`. To know more about Stats core concepts, please visit: [https://opencensus.io/core-concepts/metrics/](https://opencensus.io/core-concepts/metrics/) | ||
See [Quickstart/Metrics](https://opencensus.io/quickstart/nodejs/metrics/) for a full example of registering and collecting metrics. | ||
@@ -84,0 +96,0 @@ |
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
New author
Supply chain riskA new npm collaborator published a version of the package for the first time. New collaborators are usually benign additions to a project, but do indicate a change to the security surface area of a package.
Found 1 instance in 1 package
286684
99
7086
109
0
15
7