From 3f4049319b1951209ace8f03ea1e3a0311ef5b3e Mon Sep 17 00:00:00 2001 From: Dave Raffensperger Date: Thu, 21 Mar 2019 19:21:56 -0400 Subject: [PATCH] Pull in @opencensus/core types using `copytypes` npm script (#27) --- .../opencensus-web-types/src/common/types.ts | 34 ++ .../src/exporters/types.ts | 59 ++ packages/opencensus-web-types/src/index.ts | 10 + .../src/metrics/export/types.ts | 352 ++++++++++++ .../opencensus-web-types/src/stats/types.ts | 268 +++++++++ .../opencensus-web-types/src/tags/tag-map.ts | 46 ++ .../opencensus-web-types/src/tags/types.ts | 27 + .../src/tags/validation.ts | 42 ++ .../src/trace/config/types.ts | 90 +++ .../src/trace/instrumentation/types.ts | 68 +++ .../src/trace/model/types.ts | 528 ++++++++++++++++++ .../src/trace/propagation/types.ts | 40 ++ .../src/trace/sampler/types.ts | 32 ++ .../opencensus-web-types/src/trace/types.ts | 54 ++ 14 files changed, 1650 insertions(+) create mode 100644 packages/opencensus-web-types/src/common/types.ts create mode 100644 packages/opencensus-web-types/src/exporters/types.ts create mode 100644 packages/opencensus-web-types/src/metrics/export/types.ts create mode 100644 packages/opencensus-web-types/src/stats/types.ts create mode 100644 packages/opencensus-web-types/src/tags/tag-map.ts create mode 100644 packages/opencensus-web-types/src/tags/types.ts create mode 100644 packages/opencensus-web-types/src/tags/validation.ts create mode 100644 packages/opencensus-web-types/src/trace/config/types.ts create mode 100644 packages/opencensus-web-types/src/trace/instrumentation/types.ts create mode 100644 packages/opencensus-web-types/src/trace/model/types.ts create mode 100644 packages/opencensus-web-types/src/trace/propagation/types.ts create mode 100644 packages/opencensus-web-types/src/trace/sampler/types.ts create mode 100644 packages/opencensus-web-types/src/trace/types.ts diff --git a/packages/opencensus-web-types/src/common/types.ts b/packages/opencensus-web-types/src/common/types.ts new file mode 100644 index 00000000..f9acbf23 --- /dev/null +++ b/packages/opencensus-web-types/src/common/types.ts @@ -0,0 +1,34 @@ +/** + * Copyright 2019, 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. + */ + +// tslint:disable:no-any +export type LogFunction = (message: any, ...args: any[]) => void; + +/** Defines an logger interface. */ +export interface Logger { + /** Logger verbosity level. If omitted, `debug` level is assumed. */ + level?: string; + + error: LogFunction; + warn: LogFunction; + info: LogFunction; + debug: LogFunction; +} + +/** Defines an logger options interface. */ +export interface LoggerOptions { + level?: string; +} diff --git a/packages/opencensus-web-types/src/exporters/types.ts b/packages/opencensus-web-types/src/exporters/types.ts new file mode 100644 index 00000000..47be3572 --- /dev/null +++ b/packages/opencensus-web-types/src/exporters/types.ts @@ -0,0 +1,59 @@ +/** + * Copyright 2019, 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 {Measurement, View} from '../stats/types'; +import {TagKey, TagValue} from '../tags/types'; +import * as configTypes from '../trace/config/types'; +import * as modelTypes from '../trace/model/types'; + +/** Defines a trace exporter interface. */ +export interface Exporter extends modelTypes.SpanEventListener { + /** + * Sends a list of root spans to the service. + * @param rootSpans A list of root spans to publish. + */ + publish(rootSpans: modelTypes.RootSpan[]): Promise; +} + +/** + * An interface that describes the possible events that will be emitted from a + * Stats instance. Stats exporters should implement this interface. + */ +export interface StatsEventListener { + /** + * Is called whenever a new view is registered + * @deprecated since version 0.0.9 - use {@link start} instead + * @param view The registered view + */ + onRegisterView(view: View): void; + /** + * 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, + tags: Map): void; + + /** + * Starts the exporter that polls Metric from Metrics library and send + * batched data to backend. + */ + start(): void; +} + +export type ExporterConfig = configTypes.BufferConfig; diff --git a/packages/opencensus-web-types/src/index.ts b/packages/opencensus-web-types/src/index.ts index 392bda0d..8d29acb8 100644 --- a/packages/opencensus-web-types/src/index.ts +++ b/packages/opencensus-web-types/src/index.ts @@ -13,3 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + +export * from './common/types'; +export * from './exporters/types'; +export * from './node/types'; +export * from './trace/config/types'; +export * from './trace/instrumentation/types'; +export * from './trace/model/types'; +export * from './trace/propagation/types'; +export * from './trace/sampler/types'; +export * from './trace/types'; diff --git a/packages/opencensus-web-types/src/metrics/export/types.ts b/packages/opencensus-web-types/src/metrics/export/types.ts new file mode 100644 index 00000000..1d30263e --- /dev/null +++ b/packages/opencensus-web-types/src/metrics/export/types.ts @@ -0,0 +1,352 @@ +/** + * Copyright 2019, 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. + */ + + +/** Properties of a Metric which has one or more timeseries */ +export interface Metric { + /** + * The descriptor of the Metric. This is an optimization for network wire + * size, from data-model perspective a Metric contains always + * a MetricDescriptor. + * In case of a streaming RPC can be sent only + * the first time a metric is reported to save network traffic. + */ + readonly descriptor: MetricDescriptor; + /** + * One or more timeseries for a single metric, where each timeseries has + * one or more points. + */ + readonly timeseries: TimeSeries[]; +} + +/** Properties of a Metric type and its schema */ +export interface MetricDescriptor { + /** The metric type, including its DNS name prefix. It must be unique. */ + readonly name: string; + /** + * A detailed description of the metric, which can be used in documentation. + */ + readonly description: string; + /** + * The unit in which the metric value is reported. Follows the format + * described by http://unitsofmeasure.org/ucum.html. + */ + readonly unit: string; + /** MetricDescriptor type */ + readonly type: MetricDescriptorType; + /** The label keys associated with the metric descriptor. */ + readonly labelKeys: LabelKey[]; +} + +/** + * The kind of metric. It describes how the data is reported. + * + * A gauge is an instantaneous measurement of a value. + * + * A cumulative measurement is a value accumulated over a time interval. In + * a time series, cumulative measurements should have the same start time, + * increasing values and increasing end times, until an event resets the + * cumulative value to zero and sets a new start time for the following + * points. + */ +export enum MetricDescriptorType { + /** Do not use this default value. */ + UNSPECIFIED, + /** Integer gauge. The value can go both up and down. */ + GAUGE_INT64, + /** Floating point gauge. The value can go both up and down. */ + GAUGE_DOUBLE, + /** + * Distribution gauge measurement. The count and sum can go both up and + * down. Recorded values are always >= 0. + * Used in scenarios like a snapshot of time the current items in a queue + * have spent there. + */ + GAUGE_DISTRIBUTION, + /** + * Integer cumulative measurement. The value cannot decrease, if resets + * then the start_time should also be reset. + */ + CUMULATIVE_INT64, + /** + * Floating point cumulative measurement. The value cannot decrease, if + * resets then the start_time should also be reset. Recorded values are + * always >= 0. + */ + CUMULATIVE_DOUBLE, + /** + * Distribution cumulative measurement. The count and sum cannot decrease, + * if resets then the start_time should also be reset. + */ + CUMULATIVE_DISTRIBUTION, + /** + * Some frameworks implemented Histograms as a summary of observations + * (usually things like request durations and response sizes). While it + * also provides a total count of observations and a sum of all observed + * values, it calculates configurable percentiles over a sliding time + * window. This is not recommended, since it cannot be aggregated. + */ + SUMMARY +} + +/** Properties of a LabelKey associated with a MetricDescriptor. */ +export interface LabelKey { + /** The key for the label. */ + readonly key: string; + /** A human-readable description of what this label key represents. */ + readonly description: string; +} + +/** + * A collection of data points that describes the time-varying values + * of a metric. + */ +export interface TimeSeries { + /** + * Must be present for cumulative metrics. The time when the cumulative value + * was reset to zero. Exclusive. The cumulative value is over the time + * interval (start_timestamp, timestamp]. If not specified, the backend can + * use the previous recorded value. + */ + readonly startTimestamp?: Timestamp; + /** + * The set of label values that uniquely identify this timeseries. Applies to + * all points. The order of label values must match that of label keys in the + * metric descriptor. + */ + readonly labelValues: LabelValue[]; + /** + * The data points of this timeseries. Point.value type MUST match the + * MetricDescriptor.type. + */ + readonly points: Point[]; +} + +/** The LabelValue type. null value indicates an unset. */ +export interface LabelValue { + /** The value for the label. */ + readonly value: string|null; +} + +/** A timestamped measurement. */ +export interface Point { + /** + * The moment when this point was recorded. Inclusive. + * If not specified, the timestamp will be decided by the backend. + */ + readonly timestamp: Timestamp; + /** + * The actual point value. + * 64-bit integer or 64-bit double-precision floating-point number + * or distribution value + * or summary value. This is not recommended, since it cannot be aggregated. + */ + readonly value: number|DistributionValue|SummaryValue; +} + +/** + * Distribution contains summary statistics for a population of values. It + * optionally contains a histogram representing the distribution of those + * values across a set of buckets. + */ +export interface DistributionValue { + /** + * The number of values in the population. Must be non-negative. This value + * must equal the sum of the values in bucket_counts if a histogram is + * provided. + */ + readonly count: number; + /** + * The sum of the values in the population. If count is zero then this field + * must be zero. + */ + readonly sum: number; + /** + * The sum of squared deviations from the mean of the values in the + * population. For values x_i this is: + * + * Sum[i=1..n]((x_i - mean)^2) + * + * Knuth, "The Art of Computer Programming", Vol. 2, page 323, 3rd edition + * describes Welford's method for accumulating this sum in one pass. + * + * If count is zero then this field must be zero. + */ + readonly sumOfSquaredDeviation: number; + /** + * Don't change bucket boundaries within a TimeSeries if your backend doesn't + * support this. To save network bandwidth this field can be sent only the + * first time a metric is sent when using a streaming RPC. + */ + readonly bucketOptions: BucketOptions; + /** DistributionValue buckets */ + readonly buckets: Bucket[]; +} + +/** + * Properties of a BucketOptions. + * A Distribution may optionally contain a histogram of the values in the + * population. The bucket boundaries for that histogram are described by + * BucketOptions. + * + * If bucket_options has no type, then there is no histogram associated with + * the Distribution. + */ +export interface BucketOptions { + /** Bucket with explicit bounds. */ + readonly explicit: Explicit; +} + +/** + * Properties of an Explicit. + * Specifies a set of buckets with arbitrary upper-bounds. + * This defines size(bounds) + 1 (= N) buckets. The boundaries for bucket + * index i are: + * + * [0, bucket_bounds[i]) for i == 0 + * [bucket_bounds[i-1], bucket_bounds[i]) for 0 < i < N-1 + * [bucket_bounds[i-1], +infinity) for i == N-1 + */ +export interface Explicit { + /** The values must be strictly increasing and > 0. */ + readonly bounds: number[]; + // TODO: If OpenMetrics decides to support (a, b] intervals we should add + // support for these by defining a boolean value here which decides what + // type of intervals to use. +} + +/** Properties of a Bucket. */ +export interface Bucket { + /** + * The number of values in each bucket of the histogram, as described in + * bucket_bounds. + */ + readonly count: number; + /** + * If the distribution does not have a histogram, then omit this field. + */ + readonly exemplar?: Exemplar; +} + +/** + * 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 Exemplar { + /** + * 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: Timestamp; + /** Contextual information about the example value. */ + readonly attachments: {[key: string]: string}; +} + +/** + * The start_timestamp only applies to the count and sum in the SummaryValue. + */ +export interface SummaryValue { + /** + * The total number of recorded values since start_time. Optional since + * some systems don't expose this. + */ + readonly count: number; + /** + * The total sum of recorded values since start_time. Optional since some + * systems don't expose this. If count is zero then this field must be zero. + * This field must be unset if the sum is not available. + */ + readonly sum: number; + /** Values calculated over an arbitrary time window. */ + // TODO: Change it to required when Exemplar functionality will be added. + readonly snapshot?: Snapshot; +} + +/** + * The values in this message can be reset at arbitrary unknown times, with + * the requirement that all of them are reset at the same time. + */ +export interface Snapshot { + /** + * The number of values in the snapshot. Optional since some systems don't + * expose this. + */ + readonly count: number; + /** + * The sum of values in the snapshot. Optional since some systems don't + * expose this. If count is zero then this field must be zero or not set + * (if not supported). + */ + readonly sum: number; + /** + * A list of values at different percentiles of the distribution calculated + * from the current snapshot. The percentiles must be strictly increasing. + */ + readonly percentileValues: ValueAtPercentile[]; +} + +/** + * Represents the value at a given percentile of a distribution. + */ +export interface ValueAtPercentile { + /** The percentile of a distribution. Must be in the interval (0.0, 100.0]. */ + readonly percentile: number; + /** The value at the given percentile of a distribution. */ + readonly value: number; +} + +export interface Timestamp { + /** + * Represents seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + */ + seconds: number|null; + /** + * Non-negative fractions of a second at nanosecond resolution. Negative + * second values with fractions must still have non-negative nanos values + * that count forward in time. Must be from 0 to 999,999,999 + * inclusive. + */ + nanos: number|null; +} + +/** + * 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; +} + +/** + * 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[]; +} diff --git a/packages/opencensus-web-types/src/stats/types.ts b/packages/opencensus-web-types/src/stats/types.ts new file mode 100644 index 00000000..cc8eb85a --- /dev/null +++ b/packages/opencensus-web-types/src/stats/types.ts @@ -0,0 +1,268 @@ +/** + * Copyright 2019, 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 {StatsEventListener} from '../exporters/types'; +import {Metric} from '../metrics/export/types'; +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; +} + +/** + * Describes the type of the individual values/measurements recorded by an + * application. It includes information such as the type of measurement, the + * units of measurement and descriptive names for the data. This provides the + * fundamental type used for recording data. + */ +export interface Measure { + /** + * A string by which the measure will be referred to, e.g. + * "rpc_server_latency". Names MUST be unique within the library. + */ + readonly name: string; + /** Describes the measure, e.g. "RPC latency in seconds". */ + readonly description?: string; + /** + * Describes the unit used for the Measure. Follows the format described by + * http://unitsofmeasure.org/ucum.html. + */ + readonly unit: MeasureUnit; + /** The type used for this Measure. */ + readonly type: MeasureType; +} + +/** + * Describes the unit used for the Measure. Should follows the format described + * by http://unitsofmeasure.org/ucum.html. + */ +export enum MeasureUnit { + UNIT = '1', // for general counts + BYTE = 'by', // bytes + KBYTE = 'kb', // Kbytes + SEC = 's', // seconds + MS = 'ms', // millisecond + NS = 'ns' // nanosecond +} + +/** Describes the types of a Measure. It can be Int64 or a Double type. */ +export enum MeasureType { + INT64 = 'INT64', + DOUBLE = 'DOUBLE' +} + +/** Describes a data point to be collected for a Measure. */ +export interface Measurement { + /** The measure to which the value is applied */ + readonly measure: Measure; + /** + * The recorded value. If the measure has type INT64, value must be an integer + * up to Number.MAX_SAFE_INTERGER. + */ + readonly value: number; +} + +/** + * Defines how individual measurements are broken down by tags and aggregated. + */ +export interface View { + /** + * A string by which the View will be referred to, e.g. "rpc_latency". Names + * MUST be unique within the library. + */ + readonly name: string; + /** Describes the view, e.g. "RPC latency distribution" */ + readonly description: string; + /** The Measure to which this view is applied. */ + readonly measure: Measure; + /** + * An Aggregation describes how data collected is aggregated. + * There are four aggregation types: count, sum, lastValue and distirbution. + */ + readonly aggregation: AggregationType; + /** The start time for this view */ + readonly startTime: number; + /** + * The end time for this view - represents the last time a value was recorded + */ + endTime: number; + /** true if the view was registered */ + registered: boolean; + /** + * Records a measurement in the proper view's row. This method is used by + * Stats. User should prefer using Stats.record() instead. + * + * Measurements with measurement type INT64 will have its value truncated. + * @param measurement The measurement to record + * @param tags The tags to which the value is applied + */ + recordMeasurement(measurement: Measurement, tags: TagMap): void; + /** + * Returns a snapshot of an AggregationData for that tags/labels values. + * @param tagValues The desired data's tag values. + */ + getSnapshot(tagValues: TagValue[]): AggregationData; + /** Gets the view's tag keys */ + getColumns(): TagKey[]; + /** Gets view`s metric */ + getMetric(start: number): Metric; +} + +/** + * Informs the type of the aggregation. It can be: count, sum, lastValue or + * distribution. + */ +export enum AggregationType { + COUNT = 0, + SUM = 1, + LAST_VALUE = 2, + DISTRIBUTION = 3 +} + +/** Defines how data is collected and aggregated */ +export interface AggregationMetadata { + /** The aggregation type of the aggregation data */ + readonly type: AggregationType; + /** The tagValues that this AggregationData collects and aggregates */ + readonly tagValues: TagValue[]; + /** The latest timestamp a new data point was recorded */ + timestamp: number; +} + +/** + * Data collected and aggregated with this AggregationData will be summed + * up. + */ +export interface SumData extends AggregationMetadata { + type: AggregationType.SUM; + /** The current accumulated value */ + value: number; +} + +/** + * This AggregationData counts the number of measurements recorded. + */ +export interface CountData extends AggregationMetadata { + type: AggregationType.COUNT; + /** The current counted value */ + value: number; +} + +/** + * This AggregationData represents the last recorded value. This is useful + * when giving support to Gauges. + */ +export interface LastValueData extends AggregationMetadata { + type: AggregationType.LAST_VALUE; + /** The last recorded value */ + value: number; +} + +/** This AggregationData contains a histogram of the collected values. */ +export interface DistributionData extends AggregationMetadata { + type: AggregationType.DISTRIBUTION; + /** The first timestamp a datapoint was added */ + readonly startTime: number; + /** Get the total count of all recorded values in the histogram */ + count: number; + /** Sum of all recorded values in the histogram */ + sum: number; + /** Get the computed mean value of all recorded values in the histogram */ + mean: number; + /** + * Get the computed standard deviation of all recorded values in the + * histogram + */ + stdDeviation: number; + /** + * Get the computed sum of squared deviations of all recorded values in the + * histogram. + */ + sumOfSquaredDeviation: number; + /** Bucket distribution of the histogram */ + buckets: Bucket[]; + /** Buckets count */ + bucketCounts?: number[]; +} + +export type Bucket = number; +export type AggregationData = SumData|CountData|LastValueData|DistributionData; diff --git a/packages/opencensus-web-types/src/tags/tag-map.ts b/packages/opencensus-web-types/src/tags/tag-map.ts new file mode 100644 index 00000000..932ed517 --- /dev/null +++ b/packages/opencensus-web-types/src/tags/tag-map.ts @@ -0,0 +1,46 @@ +/** + * Copyright 2019, 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 {TagKey, TagValue} from './types'; +import {isValidTagKey, isValidTagValue} from './validation'; + +/** TagMap is maps of TagKey -> TagValue */ +export class TagMap { + // A map mapping TagKey to to its respective TagValue. + private readonly registeredTags: Map = new Map(); + + /** Adds the key/value pair regardless of whether the key is present. */ + set(tagKey: TagKey, tagValue: TagValue): void { + if (!isValidTagKey(tagKey)) { + throw new Error(`Invalid TagKey name: ${tagKey.name}`); + } + + if (!isValidTagValue(tagValue)) { + throw new Error(`Invalid TagValue: ${tagValue.value}`); + } + this.registeredTags.set(tagKey, tagValue); + } + + /** Deletes a tag from the map if the key is in the map. */ + delete(tagKey: TagKey): void { + this.registeredTags.delete(tagKey); + } + + /** Gets the tags map. */ + get tags() { + return this.registeredTags; + } +} diff --git a/packages/opencensus-web-types/src/tags/types.ts b/packages/opencensus-web-types/src/tags/types.ts new file mode 100644 index 00000000..71330dfe --- /dev/null +++ b/packages/opencensus-web-types/src/tags/types.ts @@ -0,0 +1,27 @@ +/** + * Copyright 2019, 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. + */ + +/** TagKey represents a tag key */ +export interface TagKey { + /** The name of the key. */ + readonly name: string; +} + +/** TagValue represents a tag value */ +export interface TagValue { + /** The value of a tag. */ + readonly value: string; +} diff --git a/packages/opencensus-web-types/src/tags/validation.ts b/packages/opencensus-web-types/src/tags/validation.ts new file mode 100644 index 00000000..1e4ca782 --- /dev/null +++ b/packages/opencensus-web-types/src/tags/validation.ts @@ -0,0 +1,42 @@ +/** + * Copyright 2019, 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 {TagKey, TagValue} from './types'; + +const nonPrintableCharsRegex = /[^\u0020-\u007e]/; +const TAG_KEY_MAX_LENGTH = 255; + +/** Determines whether the given String is a valid tag key. */ +export function isValidTagKey(tagKey: TagKey): boolean { + if (!tagKey || !tagKey.name) { + return false; + } + return isPrintableString(tagKey.name) && tagKey.name.length > 0 && + tagKey.name.length <= TAG_KEY_MAX_LENGTH; +} + +/** Determines whether the given String is a valid tag value. */ +export function isValidTagValue(tagValue: TagValue): boolean { + if (!tagValue || tagValue.value === null || tagValue.value === undefined) { + return false; + } + return isPrintableString(tagValue.value) && + tagValue.value.length <= TAG_KEY_MAX_LENGTH; +} + +function isPrintableString(name: string): boolean { + return !nonPrintableCharsRegex.test(name); +} diff --git a/packages/opencensus-web-types/src/trace/config/types.ts b/packages/opencensus-web-types/src/trace/config/types.ts new file mode 100644 index 00000000..581980c5 --- /dev/null +++ b/packages/opencensus-web-types/src/trace/config/types.ts @@ -0,0 +1,90 @@ +/** + * Copyright 2019, 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 {Exporter} from '../../exporters/types'; +import {PluginNames} from '../instrumentation/types'; +import {Propagation} from '../propagation/types'; + +/** Interface configuration for a buffer. */ +export interface BufferConfig { + /** Maximum size of a buffer. */ + bufferSize?: number; + /** Max time for a buffer can wait before being sent */ + bufferTimeout?: number; + /** A logger object */ + logger?: Logger; +} + +/** Defines tracer configuration parameters */ +export interface TracerConfig { + /** Determines the sampling rate. Ranges from 0.0 to 1.0 */ + samplingRate?: number; + /** A logger object */ + logger?: Logger; + /** A propagation instance */ + propagation?: Propagation; + /** Trace Parameters */ + traceParams?: TraceParams; +} + +/** Available configuration options. */ +export interface TracingConfig { + /** level of logger - 0:disable, 1: error, 2: warn, 3: info, 4: debug */ + logLevel?: number; + + /** + * The maximum number of characters reported on a label value. + */ + maximumLabelValueSize?: number; + + /** + * A list of trace instrumentations plugins to load. + * Each key is the name of the module to trace, and its + * value is the name of the package which has the plugin + * implementation. + * Ex.: + * plugins: { + * 'http': '@opencensus/opencensus-instrumentation-http', + * 'mongodb-core': '@opencensus/opencensus-instrumentation-mongodb-core', + * ... + * } + * Any user-provided value will be added to the default list. + * It will override any default plugin for the same key. + */ + plugins?: PluginNames; + /** An exporter object */ + exporter?: Exporter; + /** An instance of a logger */ + logger?: Logger; +} + +/** 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 type Config = TracingConfig&TracerConfig&BufferConfig; diff --git a/packages/opencensus-web-types/src/trace/instrumentation/types.ts b/packages/opencensus-web-types/src/trace/instrumentation/types.ts new file mode 100644 index 00000000..cf783b09 --- /dev/null +++ b/packages/opencensus-web-types/src/trace/instrumentation/types.ts @@ -0,0 +1,68 @@ +/** + * Copyright 2019, 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 {Tracer} from '../model/types'; + +/** Interface Plugin to apply patch. */ +export interface Plugin { + /** + * Method that enables the instrumentation patch. + * + * @param moduleExports nodejs module exports from the module to patch + * @param tracer a tracer instance + * @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: any, tracer: Tracer, version: string, + options: PluginConfig, + // tslint:disable-next-line:no-any + basedir?: string): any; + /** Method to disable the instrumentation */ + disable(): void; +} + +export type PluginConfig = { + // tslint:disable-next-line:no-any + [key: string]: any; +}; + +export type NamedPluginConfig = { + module: string; config: PluginConfig; +}; + +/** + * Type PluginNames: each key should be the name of the module to trace, + * and its value should be the name of the package which has the + * plugin implementation. + */ +export type PluginNames = { + [pluginName: string]: string|NamedPluginConfig; +}; + +export type PluginInternalFilesVersion = { + [pluginName: string]: string +}; + +/** + * Each key should be the name of the module to trace, and its value + * a mapping of a property name to a internal plugin file name. + */ +export type PluginInternalFiles = { + [versions: string]: PluginInternalFilesVersion; +}; diff --git a/packages/opencensus-web-types/src/trace/model/types.ts b/packages/opencensus-web-types/src/trace/model/types.ts new file mode 100644 index 00000000..3516bb84 --- /dev/null +++ b/packages/opencensus-web-types/src/trace/model/types.ts @@ -0,0 +1,528 @@ +/** + * Copyright 2019, 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 loggerTypes from '../../common/types'; +import {NodeJsEventEmitter} from '../../node/types'; +import * as configTypes from '../config/types'; +import {Propagation} from '../propagation/types'; +import * as samplerTypes from '../sampler/types'; + + + +/** Default type for functions */ +// tslint:disable:no-any +export type Func = (...args: any[]) => T; + +/** Maps a label to a string, number or boolean. */ +export interface Attributes { + [attributeKey: string]: string|number|boolean; +} + +/** + * 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 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. */ +export interface Annotation { + /** A user-supplied message describing the event. */ + description: string; + /** A timestamp for the event event. */ + timestamp: number; + /** A set of attributes on the annotation. */ + attributes: Attributes; +} + +/** An event describing a message sent/received between Spans. */ +export interface MessageEvent { + /** A timestamp for the event. */ + timestamp: number; + /** Indicates whether the message was sent or received. */ + 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; +} + +/** + * A pointer from the current span to another span in the same trace or in a + * different trace. + */ +export interface Link { + /** The trace ID for a trace within a project. */ + traceId: string; + /** The span ID for a span within a trace. */ + spanId: string; + /** The relationship of the current span relative to the linked. */ + type: LinkType; + /** A set of attributes on the link. */ + attributes: Attributes; +} + +/** Defines the trace options */ +export interface TraceOptions { + /** Root span name */ + name: string; + /** Trace context */ + spanContext?: SpanContext; + /** Span kind */ + kind?: SpanKind; +} + +export type TraceState = string; + +/** Defines the span context */ +export interface SpanContext { + /** Trace ID */ + traceId: string; + /** Span ID */ + spanId: string; + /** Options */ + options?: number; + /** TraceState */ + traceState?: TraceState; +} + +/** Defines an end span event listener */ +export interface SpanEventListener { + /** Happens when a span is ended */ + onStartSpan(span: RootSpan): void; + onEndSpan(span: RootSpan): void; +} + +/** An event describing a message sent/received between Spans. */ +export 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 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 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 */ +export interface Span { + /** The Span ID of this span */ + readonly id: string; + + /** If the parent span is in another process. */ + remoteParent: boolean; + + /** The span ID of this span's parent. If it's a root span, must be empty */ + parentSpanId: string; + + /** The resource name of the span */ + name: string; + + /** Kind of span. */ + kind: SpanKind; + + /** An object to log information to */ + logger: loggerTypes.Logger; + + /** A final status for this span */ + status: Status; + + /** A set of attributes, each in the format [KEY]:[VALUE] */ + attributes: Attributes; + + /** A text annotation with a set of attributes. */ + annotations: Annotation[]; + + /** An event describing a message sent/received between Spans. */ + messageEvents: MessageEvent[]; + + /** Pointers from the current span to another span */ + links: Link[]; + + /** true if span is a RootSpan */ + isRootSpan: boolean; + + /** Trace id asscoiated with span. */ + readonly traceId: string; + + /** Trace state associated with span */ + readonly traceState: TraceState; + + /** Indicates if span was started. */ + readonly started: boolean; + + /** Indicates if span was ended. */ + readonly ended: boolean; + + /** + * Gives a timestap that indicates the span's start time in RFC3339 UTC + * "Zulu" format. + */ + readonly startTime: Date; + + /** + * Gives a timestap that indicates the span's end time in RFC3339 UTC + * "Zulu" format. + */ + readonly endTime: Date; + + /** + * Gives a timestap that indicates the span's duration in RFC3339 UTC + * "Zulu" format. + */ + readonly duration: number; + + /** Gives the TraceContext of the span. */ + 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; + + /** + * Adds an atribute to the span. + * @param key Describes the value added. + * @param value The result of an operation. + */ + addAttribute(key: string, value: string|number|boolean): void; + + /** + * Adds an annotation to the span. + * @param description Describes the event. + * @param attributes A set of attributes on the annotation. + * @param timestamp A timestamp for this event. + */ + addAnnotation( + description: string, attributes?: Attributes, timestamp?: number): void; + + /** + * Adds a link to the span. + * @param traceId The trace ID for a trace within a project. + * @param spanId The span ID for a span within a trace. + * @param type The relationship of the current span relative to the linked. + * @param attributes A set of attributes on the link. + */ + addLink( + traceId: string, spanId: string, type: LinkType, + attributes?: Attributes): void; + + /** + * Adds a message event to the span. + * @param type The type of message event. + * @param id An identifier for the message event. + * @param timestamp A timestamp for this event. + */ + 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. */ + start(): void; + + /** Ends a span. */ + end(): void; + + /** Forces to end a span. */ + truncate(): void; +} + +/** Interface for RootSpan */ +export interface RootSpan extends Span { + /** Get the span list from RootSpan instance */ + readonly spans: Span[]; + + /** Starts a new Span instance in the RootSpan instance */ + startChildSpan(name: string, kind: SpanKind): Span; +} + + +/** Interface for Tracer */ +export interface Tracer extends SpanEventListener { + /** Get and set the currentRootSpan to tracer instance */ + currentRootSpan: RootSpan; + + /** A sampler that will decide if the span will be sampled or not */ + sampler: samplerTypes.Sampler; + + /** A configuration for starting the tracer */ + logger: loggerTypes.Logger; + + /** A configuration object for trace parameters */ + activeTraceParams: configTypes.TraceParams; + + /** A propagation instance */ + readonly propagation: Propagation; + + /** Get the eventListeners from tracer instance */ + readonly eventListeners: SpanEventListener[]; + + /** Get the active status from tracer instance */ + readonly active: boolean; + + /** + * Start a tracer instance + * @param config Configuration for tracer instace + * @returns A tracer instance started + */ + start(config: configTypes.TracerConfig): Tracer; + + /** Stop the tracer instance */ + stop(): Tracer; + + /** + * Start a new RootSpan to currentRootSpan + * @param options Options for tracer instance + * @param fn Callback function + * @returns The callback return + */ + startRootSpan(options: TraceOptions, fn: (root: RootSpan) => T): T; + + /** + * Register a OnEndSpanEventListener on the tracer instance + * @param listener An OnEndSpanEventListener instance + */ + registerSpanEventListener(listener: SpanEventListener): void; + + /** + * Unregisters an end span event listener. + * @param listener The listener to unregister. + */ + unregisterSpanEventListener(listener: SpanEventListener): void; + + /** Clear the currentRootSpan from tracer instance */ + clearCurrentTrace(): void; + + /** + * Start a new Span instance to the currentRootSpan + * @param name Span name + * @param type Span type + * @param parentSpanId Parent SpanId + * @returns The new Span instance started + */ + startChildSpan(name?: string, type?: SpanKind, parentSpanId?: string): Span; + + /** + * Binds the trace context to the given function. + * This is necessary in order to create child spans correctly in functions + * that are called asynchronously (for example, in a network response + * handler). + * @param fn A function to which to bind the trace context. + */ + wrap(fn: Func): Func; + + /** + * Binds the trace context to the given event emitter. + * This is necessary in order to create child spans correctly in event + * handlers. + * @param emitter An event emitter whose handlers should have + * the trace context binded to them. + */ + wrapEmitter(emitter: NodeJsEventEmitter): void; +} diff --git a/packages/opencensus-web-types/src/trace/propagation/types.ts b/packages/opencensus-web-types/src/trace/propagation/types.ts new file mode 100644 index 00000000..0955bf03 --- /dev/null +++ b/packages/opencensus-web-types/src/trace/propagation/types.ts @@ -0,0 +1,40 @@ +/** + * Copyright 2019, 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 {SpanContext} from '../model/types'; + +/** + * An transport and environment neutral API for getting request headers. + */ +export interface HeaderGetter { + getHeader(name: string): string|string[]|undefined; +} + +/** + * A transport and environment neutral API for setting headers. + */ +export interface HeaderSetter { + setHeader(name: string, value: string): void; +} + +/** + * Propagation interface + */ +export interface Propagation { + extract(getter: HeaderGetter): SpanContext|null; + inject(setter: HeaderSetter, spanContext: SpanContext): void; + generate(): SpanContext; +} diff --git a/packages/opencensus-web-types/src/trace/sampler/types.ts b/packages/opencensus-web-types/src/trace/sampler/types.ts new file mode 100644 index 00000000..e5ad83b8 --- /dev/null +++ b/packages/opencensus-web-types/src/trace/sampler/types.ts @@ -0,0 +1,32 @@ +/** + * Copyright 2019, 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. + */ + + +/** This interface represent a sampler . */ +export interface Sampler { + /** + * A string that uniquely describes the sampling behavior of this instance. + */ + readonly description: string; + + /** + * Checks if trace belong the sample. + * @param traceId Used to check the probability. + * @returns a boolean. True if the traceId is in probability + * False if the traceId is not in probability. + */ + shouldSample(traceId: string): boolean; +} diff --git a/packages/opencensus-web-types/src/trace/types.ts b/packages/opencensus-web-types/src/trace/types.ts new file mode 100644 index 00000000..df27a3fa --- /dev/null +++ b/packages/opencensus-web-types/src/trace/types.ts @@ -0,0 +1,54 @@ +/** + * Copyright 2019, 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 exportersTypes from '../exporters/types'; +import * as configTypes from './config/types'; +import * as modelTypes from './model/types'; + +/** Main interface for tracing. */ +export interface Tracing { + /** Object responsible for managing a trace. */ + readonly tracer: modelTypes.Tracer; + + /** Service to send collected traces to. */ + readonly exporter: exportersTypes.Exporter; + + /** Gets active status */ + active: boolean; + + /** + * Starts tracing. + * @param userConfig A configuration object to start tracing. + * @returns The started Tracing instance. + */ + start(userConfig?: configTypes.Config): Tracing; + + /** Stops tracing. */ + stop(): void; + + /** + * Registers an exporter to send the collected traces to. + * @param exporter The exporter to send the traces to. + * @returns The tracing object. + */ + registerExporter(exporter: exportersTypes.Exporter): Tracing; + + /** + * Unregisters an exporter. + * @param exporter The exporter to stop sending traces to. + */ + unregisterExporter(exporter: exportersTypes.Exporter): Tracing; +}