feat: Complete zCode CLI X with Telegram bot integration

- Add full Telegram bot functionality with Z.AI API integration
- Implement 4 tools: Bash, FileEdit, WebSearch, Git
- Add 3 agents: Code Reviewer, Architect, DevOps Engineer
- Add 6 skills for common coding tasks
- Add systemd service file for 24/7 operation
- Add nginx configuration for HTTPS webhook
- Add comprehensive documentation
- Implement WebSocket server for real-time updates
- Add logging system with Winston
- Add environment validation

🤖 zCode CLI X - Agentic coder with Z.AI + Telegram integration
This commit is contained in:
admin
2026-05-05 09:01:26 +00:00
Unverified
parent 4a7035dd92
commit 875c7f9b91
24688 changed files with 3224957 additions and 221 deletions

View File

@@ -0,0 +1,45 @@
import { MetricOptions, ValueType } from '@opentelemetry/api';
import { View } from './view/View';
/**
* Supported types of metric instruments.
*/
export declare enum InstrumentType {
COUNTER = "COUNTER",
GAUGE = "GAUGE",
HISTOGRAM = "HISTOGRAM",
UP_DOWN_COUNTER = "UP_DOWN_COUNTER",
OBSERVABLE_COUNTER = "OBSERVABLE_COUNTER",
OBSERVABLE_GAUGE = "OBSERVABLE_GAUGE",
OBSERVABLE_UP_DOWN_COUNTER = "OBSERVABLE_UP_DOWN_COUNTER"
}
/**
* An internal interface describing the instrument.
*
* This is intentionally distinguished from the public MetricDescriptor (a.k.a. InstrumentDescriptor)
* which may not contains internal fields like metric advice.
*/
export interface InstrumentDescriptor {
readonly name: string;
readonly description: string;
readonly unit: string;
readonly type: InstrumentType;
readonly valueType: ValueType;
/**
* @experimental
*
* This is intentionally not using the API's type as it's only available from @opentelemetry/api 1.7.0 and up.
* In SDK 2.0 we'll be able to bump the minimum API version and remove this workaround.
*/
readonly advice: {
/**
* Hint the explicit bucket boundaries for SDK if the metric has been
* aggregated with a HistogramAggregator.
*/
explicitBucketBoundaries?: number[];
};
}
export declare function createInstrumentDescriptor(name: string, type: InstrumentType, options?: MetricOptions): InstrumentDescriptor;
export declare function createInstrumentDescriptorWithView(view: View, instrument: InstrumentDescriptor): InstrumentDescriptor;
export declare function isDescriptorCompatibleWith(descriptor: InstrumentDescriptor, otherDescriptor: InstrumentDescriptor): boolean;
export declare function isValidName(name: string): boolean;
//# sourceMappingURL=InstrumentDescriptor.d.ts.map

View File

@@ -0,0 +1,69 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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 { ValueType, diag } from '@opentelemetry/api';
import { equalsCaseInsensitive } from './utils';
/**
* Supported types of metric instruments.
*/
export var InstrumentType;
(function (InstrumentType) {
InstrumentType["COUNTER"] = "COUNTER";
InstrumentType["GAUGE"] = "GAUGE";
InstrumentType["HISTOGRAM"] = "HISTOGRAM";
InstrumentType["UP_DOWN_COUNTER"] = "UP_DOWN_COUNTER";
InstrumentType["OBSERVABLE_COUNTER"] = "OBSERVABLE_COUNTER";
InstrumentType["OBSERVABLE_GAUGE"] = "OBSERVABLE_GAUGE";
InstrumentType["OBSERVABLE_UP_DOWN_COUNTER"] = "OBSERVABLE_UP_DOWN_COUNTER";
})(InstrumentType || (InstrumentType = {}));
export function createInstrumentDescriptor(name, type, options) {
var _a, _b, _c, _d;
if (!isValidName(name)) {
diag.warn("Invalid metric name: \"" + name + "\". The metric name should be a ASCII string with a length no greater than 255 characters.");
}
return {
name: name,
type: type,
description: (_a = options === null || options === void 0 ? void 0 : options.description) !== null && _a !== void 0 ? _a : '',
unit: (_b = options === null || options === void 0 ? void 0 : options.unit) !== null && _b !== void 0 ? _b : '',
valueType: (_c = options === null || options === void 0 ? void 0 : options.valueType) !== null && _c !== void 0 ? _c : ValueType.DOUBLE,
advice: (_d = options === null || options === void 0 ? void 0 : options.advice) !== null && _d !== void 0 ? _d : {},
};
}
export function createInstrumentDescriptorWithView(view, instrument) {
var _a, _b;
return {
name: (_a = view.name) !== null && _a !== void 0 ? _a : instrument.name,
description: (_b = view.description) !== null && _b !== void 0 ? _b : instrument.description,
type: instrument.type,
unit: instrument.unit,
valueType: instrument.valueType,
advice: instrument.advice,
};
}
export function isDescriptorCompatibleWith(descriptor, otherDescriptor) {
// Names are case-insensitive strings.
return (equalsCaseInsensitive(descriptor.name, otherDescriptor.name) &&
descriptor.unit === otherDescriptor.unit &&
descriptor.type === otherDescriptor.type &&
descriptor.valueType === otherDescriptor.valueType);
}
// ASCII string with a length no greater than 255 characters.
// NB: the first character counted separately from the rest.
var NAME_REGEXP = /^[a-z][a-z0-9_.\-/]{0,254}$/i;
export function isValidName(name) {
return name.match(NAME_REGEXP) != null;
}
//# sourceMappingURL=InstrumentDescriptor.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,71 @@
import { Context, Attributes, UpDownCounter, Counter, Histogram, Observable, ObservableCallback, ObservableCounter, ObservableGauge, ObservableUpDownCounter } from '@opentelemetry/api';
import { InstrumentDescriptor } from './InstrumentDescriptor';
import { ObservableRegistry } from './state/ObservableRegistry';
import { AsyncWritableMetricStorage, WritableMetricStorage } from './state/WritableMetricStorage';
import { Gauge } from './types';
export declare class SyncInstrument {
private _writableMetricStorage;
protected _descriptor: InstrumentDescriptor;
constructor(_writableMetricStorage: WritableMetricStorage, _descriptor: InstrumentDescriptor);
protected _record(value: number, attributes?: Attributes, context?: Context): void;
}
/**
* The class implements {@link UpDownCounter} interface.
*/
export declare class UpDownCounterInstrument extends SyncInstrument implements UpDownCounter {
/**
* Increment value of counter by the input. Inputs may be negative.
*/
add(value: number, attributes?: Attributes, ctx?: Context): void;
}
/**
* The class implements {@link Counter} interface.
*/
export declare class CounterInstrument extends SyncInstrument implements Counter {
/**
* Increment value of counter by the input. Inputs may not be negative.
*/
add(value: number, attributes?: Attributes, ctx?: Context): void;
}
/**
* The class implements {@link Gauge} interface.
*/
export declare class GaugeInstrument extends SyncInstrument implements Gauge {
/**
* Records a measurement.
*/
record(value: number, attributes?: Attributes, ctx?: Context): void;
}
/**
* The class implements {@link Histogram} interface.
*/
export declare class HistogramInstrument extends SyncInstrument implements Histogram {
/**
* Records a measurement. Value of the measurement must not be negative.
*/
record(value: number, attributes?: Attributes, ctx?: Context): void;
}
export declare class ObservableInstrument implements Observable {
private _observableRegistry;
/** @internal */
_metricStorages: AsyncWritableMetricStorage[];
/** @internal */
_descriptor: InstrumentDescriptor;
constructor(descriptor: InstrumentDescriptor, metricStorages: AsyncWritableMetricStorage[], _observableRegistry: ObservableRegistry);
/**
* @see {Observable.addCallback}
*/
addCallback(callback: ObservableCallback): void;
/**
* @see {Observable.removeCallback}
*/
removeCallback(callback: ObservableCallback): void;
}
export declare class ObservableCounterInstrument extends ObservableInstrument implements ObservableCounter {
}
export declare class ObservableGaugeInstrument extends ObservableInstrument implements ObservableGauge {
}
export declare class ObservableUpDownCounterInstrument extends ObservableInstrument implements ObservableUpDownCounter {
}
export declare function isObservableInstrument(it: unknown): it is ObservableInstrument;
//# sourceMappingURL=Instruments.d.ts.map

View File

@@ -0,0 +1,183 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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.
*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
import { context as contextApi, diag, ValueType, } from '@opentelemetry/api';
import { millisToHrTime } from '@opentelemetry/core';
var SyncInstrument = /** @class */ (function () {
function SyncInstrument(_writableMetricStorage, _descriptor) {
this._writableMetricStorage = _writableMetricStorage;
this._descriptor = _descriptor;
}
SyncInstrument.prototype._record = function (value, attributes, context) {
if (attributes === void 0) { attributes = {}; }
if (context === void 0) { context = contextApi.active(); }
if (typeof value !== 'number') {
diag.warn("non-number value provided to metric " + this._descriptor.name + ": " + value);
return;
}
if (this._descriptor.valueType === ValueType.INT &&
!Number.isInteger(value)) {
diag.warn("INT value type cannot accept a floating-point value for " + this._descriptor.name + ", ignoring the fractional digits.");
value = Math.trunc(value);
// ignore non-finite values.
if (!Number.isInteger(value)) {
return;
}
}
this._writableMetricStorage.record(value, attributes, context, millisToHrTime(Date.now()));
};
return SyncInstrument;
}());
export { SyncInstrument };
/**
* The class implements {@link UpDownCounter} interface.
*/
var UpDownCounterInstrument = /** @class */ (function (_super) {
__extends(UpDownCounterInstrument, _super);
function UpDownCounterInstrument() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Increment value of counter by the input. Inputs may be negative.
*/
UpDownCounterInstrument.prototype.add = function (value, attributes, ctx) {
this._record(value, attributes, ctx);
};
return UpDownCounterInstrument;
}(SyncInstrument));
export { UpDownCounterInstrument };
/**
* The class implements {@link Counter} interface.
*/
var CounterInstrument = /** @class */ (function (_super) {
__extends(CounterInstrument, _super);
function CounterInstrument() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Increment value of counter by the input. Inputs may not be negative.
*/
CounterInstrument.prototype.add = function (value, attributes, ctx) {
if (value < 0) {
diag.warn("negative value provided to counter " + this._descriptor.name + ": " + value);
return;
}
this._record(value, attributes, ctx);
};
return CounterInstrument;
}(SyncInstrument));
export { CounterInstrument };
/**
* The class implements {@link Gauge} interface.
*/
var GaugeInstrument = /** @class */ (function (_super) {
__extends(GaugeInstrument, _super);
function GaugeInstrument() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Records a measurement.
*/
GaugeInstrument.prototype.record = function (value, attributes, ctx) {
this._record(value, attributes, ctx);
};
return GaugeInstrument;
}(SyncInstrument));
export { GaugeInstrument };
/**
* The class implements {@link Histogram} interface.
*/
var HistogramInstrument = /** @class */ (function (_super) {
__extends(HistogramInstrument, _super);
function HistogramInstrument() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Records a measurement. Value of the measurement must not be negative.
*/
HistogramInstrument.prototype.record = function (value, attributes, ctx) {
if (value < 0) {
diag.warn("negative value provided to histogram " + this._descriptor.name + ": " + value);
return;
}
this._record(value, attributes, ctx);
};
return HistogramInstrument;
}(SyncInstrument));
export { HistogramInstrument };
var ObservableInstrument = /** @class */ (function () {
function ObservableInstrument(descriptor, metricStorages, _observableRegistry) {
this._observableRegistry = _observableRegistry;
this._descriptor = descriptor;
this._metricStorages = metricStorages;
}
/**
* @see {Observable.addCallback}
*/
ObservableInstrument.prototype.addCallback = function (callback) {
this._observableRegistry.addCallback(callback, this);
};
/**
* @see {Observable.removeCallback}
*/
ObservableInstrument.prototype.removeCallback = function (callback) {
this._observableRegistry.removeCallback(callback, this);
};
return ObservableInstrument;
}());
export { ObservableInstrument };
var ObservableCounterInstrument = /** @class */ (function (_super) {
__extends(ObservableCounterInstrument, _super);
function ObservableCounterInstrument() {
return _super !== null && _super.apply(this, arguments) || this;
}
return ObservableCounterInstrument;
}(ObservableInstrument));
export { ObservableCounterInstrument };
var ObservableGaugeInstrument = /** @class */ (function (_super) {
__extends(ObservableGaugeInstrument, _super);
function ObservableGaugeInstrument() {
return _super !== null && _super.apply(this, arguments) || this;
}
return ObservableGaugeInstrument;
}(ObservableInstrument));
export { ObservableGaugeInstrument };
var ObservableUpDownCounterInstrument = /** @class */ (function (_super) {
__extends(ObservableUpDownCounterInstrument, _super);
function ObservableUpDownCounterInstrument() {
return _super !== null && _super.apply(this, arguments) || this;
}
return ObservableUpDownCounterInstrument;
}(ObservableInstrument));
export { ObservableUpDownCounterInstrument };
export function isObservableInstrument(it) {
return it instanceof ObservableInstrument;
}
//# sourceMappingURL=Instruments.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,47 @@
import { Meter as IMeter, MetricOptions, Histogram, Counter, UpDownCounter, ObservableGauge, ObservableCounter, ObservableUpDownCounter, BatchObservableCallback, Observable } from '@opentelemetry/api';
import { MeterSharedState } from './state/MeterSharedState';
import { Gauge } from './types';
/**
* This class implements the {@link IMeter} interface.
*/
export declare class Meter implements IMeter {
private _meterSharedState;
constructor(_meterSharedState: MeterSharedState);
/**
* Create a {@link Gauge} instrument.
*/
createGauge(name: string, options?: MetricOptions): Gauge;
/**
* Create a {@link Histogram} instrument.
*/
createHistogram(name: string, options?: MetricOptions): Histogram;
/**
* Create a {@link Counter} instrument.
*/
createCounter(name: string, options?: MetricOptions): Counter;
/**
* Create a {@link UpDownCounter} instrument.
*/
createUpDownCounter(name: string, options?: MetricOptions): UpDownCounter;
/**
* Create a {@link ObservableGauge} instrument.
*/
createObservableGauge(name: string, options?: MetricOptions): ObservableGauge;
/**
* Create a {@link ObservableCounter} instrument.
*/
createObservableCounter(name: string, options?: MetricOptions): ObservableCounter;
/**
* Create a {@link ObservableUpDownCounter} instrument.
*/
createObservableUpDownCounter(name: string, options?: MetricOptions): ObservableUpDownCounter;
/**
* @see {@link Meter.addBatchObservableCallback}
*/
addBatchObservableCallback(callback: BatchObservableCallback, observables: Observable[]): void;
/**
* @see {@link Meter.removeBatchObservableCallback}
*/
removeBatchObservableCallback(callback: BatchObservableCallback, observables: Observable[]): void;
}
//# sourceMappingURL=Meter.d.ts.map

View File

@@ -0,0 +1,96 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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 { createInstrumentDescriptor, InstrumentType, } from './InstrumentDescriptor';
import { CounterInstrument, GaugeInstrument, HistogramInstrument, ObservableCounterInstrument, ObservableGaugeInstrument, ObservableUpDownCounterInstrument, UpDownCounterInstrument, } from './Instruments';
/**
* This class implements the {@link IMeter} interface.
*/
var Meter = /** @class */ (function () {
function Meter(_meterSharedState) {
this._meterSharedState = _meterSharedState;
}
/**
* Create a {@link Gauge} instrument.
*/
Meter.prototype.createGauge = function (name, options) {
var descriptor = createInstrumentDescriptor(name, InstrumentType.GAUGE, options);
var storage = this._meterSharedState.registerMetricStorage(descriptor);
return new GaugeInstrument(storage, descriptor);
};
/**
* Create a {@link Histogram} instrument.
*/
Meter.prototype.createHistogram = function (name, options) {
var descriptor = createInstrumentDescriptor(name, InstrumentType.HISTOGRAM, options);
var storage = this._meterSharedState.registerMetricStorage(descriptor);
return new HistogramInstrument(storage, descriptor);
};
/**
* Create a {@link Counter} instrument.
*/
Meter.prototype.createCounter = function (name, options) {
var descriptor = createInstrumentDescriptor(name, InstrumentType.COUNTER, options);
var storage = this._meterSharedState.registerMetricStorage(descriptor);
return new CounterInstrument(storage, descriptor);
};
/**
* Create a {@link UpDownCounter} instrument.
*/
Meter.prototype.createUpDownCounter = function (name, options) {
var descriptor = createInstrumentDescriptor(name, InstrumentType.UP_DOWN_COUNTER, options);
var storage = this._meterSharedState.registerMetricStorage(descriptor);
return new UpDownCounterInstrument(storage, descriptor);
};
/**
* Create a {@link ObservableGauge} instrument.
*/
Meter.prototype.createObservableGauge = function (name, options) {
var descriptor = createInstrumentDescriptor(name, InstrumentType.OBSERVABLE_GAUGE, options);
var storages = this._meterSharedState.registerAsyncMetricStorage(descriptor);
return new ObservableGaugeInstrument(descriptor, storages, this._meterSharedState.observableRegistry);
};
/**
* Create a {@link ObservableCounter} instrument.
*/
Meter.prototype.createObservableCounter = function (name, options) {
var descriptor = createInstrumentDescriptor(name, InstrumentType.OBSERVABLE_COUNTER, options);
var storages = this._meterSharedState.registerAsyncMetricStorage(descriptor);
return new ObservableCounterInstrument(descriptor, storages, this._meterSharedState.observableRegistry);
};
/**
* Create a {@link ObservableUpDownCounter} instrument.
*/
Meter.prototype.createObservableUpDownCounter = function (name, options) {
var descriptor = createInstrumentDescriptor(name, InstrumentType.OBSERVABLE_UP_DOWN_COUNTER, options);
var storages = this._meterSharedState.registerAsyncMetricStorage(descriptor);
return new ObservableUpDownCounterInstrument(descriptor, storages, this._meterSharedState.observableRegistry);
};
/**
* @see {@link Meter.addBatchObservableCallback}
*/
Meter.prototype.addBatchObservableCallback = function (callback, observables) {
this._meterSharedState.observableRegistry.addBatchCallback(callback, observables);
};
/**
* @see {@link Meter.removeBatchObservableCallback}
*/
Meter.prototype.removeBatchObservableCallback = function (callback, observables) {
this._meterSharedState.observableRegistry.removeBatchCallback(callback, observables);
};
return Meter;
}());
export { Meter };
//# sourceMappingURL=Meter.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,58 @@
import { MeterProvider as IMeterProvider, Meter as IMeter, MeterOptions } from '@opentelemetry/api';
import { IResource } from '@opentelemetry/resources';
import { MetricReader } from './export/MetricReader';
import { ForceFlushOptions, ShutdownOptions } from './types';
import { View } from './view/View';
/**
* MeterProviderOptions provides an interface for configuring a MeterProvider.
*/
export interface MeterProviderOptions {
/** Resource associated with metric telemetry */
resource?: IResource;
views?: View[];
readers?: MetricReader[];
/**
* Merge resource with {@link Resource.default()}?
* Default: {@code true}
*/
mergeResourceWithDefaults?: boolean;
}
/**
* This class implements the {@link MeterProvider} interface.
*/
export declare class MeterProvider implements IMeterProvider {
private _sharedState;
private _shutdown;
constructor(options?: MeterProviderOptions);
/**
* Get a meter with the configuration of the MeterProvider.
*/
getMeter(name: string, version?: string, options?: MeterOptions): IMeter;
/**
* Register a {@link MetricReader} to the meter provider. After the
* registration, the MetricReader can start metrics collection.
*
* <p> NOTE: {@link MetricReader} instances MUST be added before creating any instruments.
* A {@link MetricReader} instance registered later may receive no or incomplete metric data.
*
* @param metricReader the metric reader to be registered.
*
* @deprecated This method will be removed in SDK 2.0. Please use
* {@link MeterProviderOptions.readers} via the {@link MeterProvider} constructor instead
*/
addMetricReader(metricReader: MetricReader): void;
/**
* Shut down the MeterProvider and all registered
* MetricReaders.
*
* Returns a promise which is resolved when all flushes are complete.
*/
shutdown(options?: ShutdownOptions): Promise<void>;
/**
* Notifies all registered MetricReaders to flush any buffered data.
*
* Returns a promise which is resolved when all flushes are complete.
*/
forceFlush(options?: ForceFlushOptions): Promise<void>;
}
//# sourceMappingURL=MeterProvider.d.ts.map

View File

@@ -0,0 +1,206 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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.
*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
import { diag, createNoopMeter, } from '@opentelemetry/api';
import { Resource } from '@opentelemetry/resources';
import { MeterProviderSharedState } from './state/MeterProviderSharedState';
import { MetricCollector } from './state/MetricCollector';
/**
* @param mergeWithDefaults
* @param providedResource
*/
function prepareResource(mergeWithDefaults, providedResource) {
var resource = providedResource !== null && providedResource !== void 0 ? providedResource : Resource.empty();
if (mergeWithDefaults) {
return Resource.default().merge(resource);
}
return resource;
}
/**
* This class implements the {@link MeterProvider} interface.
*/
var MeterProvider = /** @class */ (function () {
function MeterProvider(options) {
var e_1, _a, e_2, _b;
var _c;
this._shutdown = false;
this._sharedState = new MeterProviderSharedState(prepareResource((_c = options === null || options === void 0 ? void 0 : options.mergeResourceWithDefaults) !== null && _c !== void 0 ? _c : true, options === null || options === void 0 ? void 0 : options.resource));
if ((options === null || options === void 0 ? void 0 : options.views) != null && options.views.length > 0) {
try {
for (var _d = __values(options.views), _e = _d.next(); !_e.done; _e = _d.next()) {
var view = _e.value;
this._sharedState.viewRegistry.addView(view);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
}
finally { if (e_1) throw e_1.error; }
}
}
if ((options === null || options === void 0 ? void 0 : options.readers) != null && options.readers.length > 0) {
try {
for (var _f = __values(options.readers), _g = _f.next(); !_g.done; _g = _f.next()) {
var metricReader = _g.value;
this.addMetricReader(metricReader);
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
}
finally { if (e_2) throw e_2.error; }
}
}
}
/**
* Get a meter with the configuration of the MeterProvider.
*/
MeterProvider.prototype.getMeter = function (name, version, options) {
if (version === void 0) { version = ''; }
if (options === void 0) { options = {}; }
// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#meter-creation
if (this._shutdown) {
diag.warn('A shutdown MeterProvider cannot provide a Meter');
return createNoopMeter();
}
return this._sharedState.getMeterSharedState({
name: name,
version: version,
schemaUrl: options.schemaUrl,
}).meter;
};
/**
* Register a {@link MetricReader} to the meter provider. After the
* registration, the MetricReader can start metrics collection.
*
* <p> NOTE: {@link MetricReader} instances MUST be added before creating any instruments.
* A {@link MetricReader} instance registered later may receive no or incomplete metric data.
*
* @param metricReader the metric reader to be registered.
*
* @deprecated This method will be removed in SDK 2.0. Please use
* {@link MeterProviderOptions.readers} via the {@link MeterProvider} constructor instead
*/
MeterProvider.prototype.addMetricReader = function (metricReader) {
var collector = new MetricCollector(this._sharedState, metricReader);
metricReader.setMetricProducer(collector);
this._sharedState.metricCollectors.push(collector);
};
/**
* Shut down the MeterProvider and all registered
* MetricReaders.
*
* Returns a promise which is resolved when all flushes are complete.
*/
MeterProvider.prototype.shutdown = function (options) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (this._shutdown) {
diag.warn('shutdown may only be called once per MeterProvider');
return [2 /*return*/];
}
this._shutdown = true;
return [4 /*yield*/, Promise.all(this._sharedState.metricCollectors.map(function (collector) {
return collector.shutdown(options);
}))];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
/**
* Notifies all registered MetricReaders to flush any buffered data.
*
* Returns a promise which is resolved when all flushes are complete.
*/
MeterProvider.prototype.forceFlush = function (options) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// do not flush after shutdown
if (this._shutdown) {
diag.warn('invalid attempt to force flush after MeterProvider shutdown');
return [2 /*return*/];
}
return [4 /*yield*/, Promise.all(this._sharedState.metricCollectors.map(function (collector) {
return collector.forceFlush(options);
}))];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
return MeterProvider;
}());
export { MeterProvider };
//# sourceMappingURL=MeterProvider.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,33 @@
import { ObservableResult, Attributes, ValueType, BatchObservableResult, Observable } from '@opentelemetry/api';
import { AttributeHashMap } from './state/HashMap';
import { ObservableInstrument } from './Instruments';
/**
* The class implements {@link ObservableResult} interface.
*/
export declare class ObservableResultImpl implements ObservableResult {
private _instrumentName;
private _valueType;
/**
* @internal
*/
_buffer: AttributeHashMap<number>;
constructor(_instrumentName: string, _valueType: ValueType);
/**
* Observe a measurement of the value associated with the given attributes.
*/
observe(value: number, attributes?: Attributes): void;
}
/**
* The class implements {@link BatchObservableCallback} interface.
*/
export declare class BatchObservableResultImpl implements BatchObservableResult {
/**
* @internal
*/
_buffer: Map<ObservableInstrument, AttributeHashMap<number>>;
/**
* Observe a measurement of the value associated with the given attributes.
*/
observe(metric: Observable, value: number, attributes?: Attributes): void;
}
//# sourceMappingURL=ObservableResult.d.ts.map

View File

@@ -0,0 +1,94 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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 { diag, ValueType, } from '@opentelemetry/api';
import { AttributeHashMap } from './state/HashMap';
import { isObservableInstrument } from './Instruments';
/**
* The class implements {@link ObservableResult} interface.
*/
var ObservableResultImpl = /** @class */ (function () {
function ObservableResultImpl(_instrumentName, _valueType) {
this._instrumentName = _instrumentName;
this._valueType = _valueType;
/**
* @internal
*/
this._buffer = new AttributeHashMap();
}
/**
* Observe a measurement of the value associated with the given attributes.
*/
ObservableResultImpl.prototype.observe = function (value, attributes) {
if (attributes === void 0) { attributes = {}; }
if (typeof value !== 'number') {
diag.warn("non-number value provided to metric " + this._instrumentName + ": " + value);
return;
}
if (this._valueType === ValueType.INT && !Number.isInteger(value)) {
diag.warn("INT value type cannot accept a floating-point value for " + this._instrumentName + ", ignoring the fractional digits.");
value = Math.trunc(value);
// ignore non-finite values.
if (!Number.isInteger(value)) {
return;
}
}
this._buffer.set(attributes, value);
};
return ObservableResultImpl;
}());
export { ObservableResultImpl };
/**
* The class implements {@link BatchObservableCallback} interface.
*/
var BatchObservableResultImpl = /** @class */ (function () {
function BatchObservableResultImpl() {
/**
* @internal
*/
this._buffer = new Map();
}
/**
* Observe a measurement of the value associated with the given attributes.
*/
BatchObservableResultImpl.prototype.observe = function (metric, value, attributes) {
if (attributes === void 0) { attributes = {}; }
if (!isObservableInstrument(metric)) {
return;
}
var map = this._buffer.get(metric);
if (map == null) {
map = new AttributeHashMap();
this._buffer.set(metric, map);
}
if (typeof value !== 'number') {
diag.warn("non-number value provided to metric " + metric._descriptor.name + ": " + value);
return;
}
if (metric._descriptor.valueType === ValueType.INT &&
!Number.isInteger(value)) {
diag.warn("INT value type cannot accept a floating-point value for " + metric._descriptor.name + ", ignoring the fractional digits.");
value = Math.trunc(value);
// ignore non-finite values.
if (!Number.isInteger(value)) {
return;
}
}
map.set(attributes, value);
};
return BatchObservableResultImpl;
}());
export { BatchObservableResultImpl };
//# sourceMappingURL=ObservableResult.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,14 @@
import { HrTime } from '@opentelemetry/api';
import { AggregationTemporality } from '../export/AggregationTemporality';
import { MetricData, MetricDescriptor } from '../export/MetricData';
import { Maybe } from '../utils';
import { AggregatorKind, Aggregator, AccumulationRecord } from './types';
/** Basic aggregator for None which keeps no recorded value. */
export declare class DropAggregator implements Aggregator<undefined> {
kind: AggregatorKind.DROP;
createAccumulation(): undefined;
merge(_previous: undefined, _delta: undefined): undefined;
diff(_previous: undefined, _current: undefined): undefined;
toMetricData(_descriptor: MetricDescriptor, _aggregationTemporality: AggregationTemporality, _accumulationByAttributes: AccumulationRecord<undefined>[], _endTime: HrTime): Maybe<MetricData>;
}
//# sourceMappingURL=Drop.d.ts.map

View File

@@ -0,0 +1,37 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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 { AggregatorKind } from './types';
/** Basic aggregator for None which keeps no recorded value. */
var DropAggregator = /** @class */ (function () {
function DropAggregator() {
this.kind = AggregatorKind.DROP;
}
DropAggregator.prototype.createAccumulation = function () {
return undefined;
};
DropAggregator.prototype.merge = function (_previous, _delta) {
return undefined;
};
DropAggregator.prototype.diff = function (_previous, _current) {
return undefined;
};
DropAggregator.prototype.toMetricData = function (_descriptor, _aggregationTemporality, _accumulationByAttributes, _endTime) {
return undefined;
};
return DropAggregator;
}());
export { DropAggregator };
//# sourceMappingURL=Drop.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"Drop.js","sourceRoot":"","sources":["../../../src/aggregator/Drop.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAMH,OAAO,EAAE,cAAc,EAAkC,MAAM,SAAS,CAAC;AAEzE,+DAA+D;AAC/D;IAAA;QACE,SAAI,GAAwB,cAAc,CAAC,IAAI,CAAC;IAsBlD,CAAC;IApBC,2CAAkB,GAAlB;QACE,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,8BAAK,GAAL,UAAM,SAAoB,EAAE,MAAiB;QAC3C,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,6BAAI,GAAJ,UAAK,SAAoB,EAAE,QAAmB;QAC5C,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,qCAAY,GAAZ,UACE,WAA6B,EAC7B,uBAA+C,EAC/C,yBAA0D,EAC1D,QAAgB;QAEhB,OAAO,SAAS,CAAC;IACnB,CAAC;IACH,qBAAC;AAAD,CAAC,AAvBD,IAuBC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { HrTime } from '@opentelemetry/api';\nimport { AggregationTemporality } from '../export/AggregationTemporality';\nimport { MetricData, MetricDescriptor } from '../export/MetricData';\nimport { Maybe } from '../utils';\nimport { AggregatorKind, Aggregator, AccumulationRecord } from './types';\n\n/** Basic aggregator for None which keeps no recorded value. */\nexport class DropAggregator implements Aggregator<undefined> {\n kind: AggregatorKind.DROP = AggregatorKind.DROP;\n\n createAccumulation() {\n return undefined;\n }\n\n merge(_previous: undefined, _delta: undefined) {\n return undefined;\n }\n\n diff(_previous: undefined, _current: undefined) {\n return undefined;\n }\n\n toMetricData(\n _descriptor: MetricDescriptor,\n _aggregationTemporality: AggregationTemporality,\n _accumulationByAttributes: AccumulationRecord<undefined>[],\n _endTime: HrTime\n ): Maybe<MetricData> {\n return undefined;\n }\n}\n"]}

View File

@@ -0,0 +1,176 @@
import { Accumulation, AccumulationRecord, Aggregator, AggregatorKind, ExponentialHistogram } from './types';
import { ExponentialHistogramMetricData, MetricDescriptor } from '../export/MetricData';
import { HrTime } from '@opentelemetry/api';
import { Maybe } from '../utils';
import { AggregationTemporality } from '../export/AggregationTemporality';
import { Buckets } from './exponential-histogram/Buckets';
import { Mapping } from './exponential-histogram/mapping/types';
/**
* Internal value type for ExponentialHistogramAggregation.
* Differs from the exported type as undefined sum/min/max complicate arithmetic
* performed by this aggregation, but are required to be undefined in the exported types.
*/
interface InternalHistogram extends ExponentialHistogram {
hasMinMax: boolean;
min: number;
max: number;
sum: number;
}
export declare class ExponentialHistogramAccumulation implements Accumulation {
startTime: HrTime;
private _maxSize;
private _recordMinMax;
private _sum;
private _count;
private _zeroCount;
private _min;
private _max;
private _positive;
private _negative;
private _mapping;
constructor(startTime?: HrTime, _maxSize?: number, _recordMinMax?: boolean, _sum?: number, _count?: number, _zeroCount?: number, _min?: number, _max?: number, _positive?: Buckets, _negative?: Buckets, _mapping?: Mapping);
/**
* record updates a histogram with a single count
* @param {Number} value
*/
record(value: number): void;
/**
* Sets the start time for this accumulation
* @param {HrTime} startTime
*/
setStartTime(startTime: HrTime): void;
/**
* Returns the datapoint representation of this accumulation
* @param {HrTime} startTime
*/
toPointValue(): InternalHistogram;
/**
* @returns {Number} The sum of values recorded by this accumulation
*/
get sum(): number;
/**
* @returns {Number} The minimum value recorded by this accumulation
*/
get min(): number;
/**
* @returns {Number} The maximum value recorded by this accumulation
*/
get max(): number;
/**
* @returns {Number} The count of values recorded by this accumulation
*/
get count(): number;
/**
* @returns {Number} The number of 0 values recorded by this accumulation
*/
get zeroCount(): number;
/**
* @returns {Number} The scale used by this accumulation
*/
get scale(): number;
/**
* positive holds the positive values
* @returns {Buckets}
*/
get positive(): Buckets;
/**
* negative holds the negative values by their absolute value
* @returns {Buckets}
*/
get negative(): Buckets;
/**
* updateByIncr supports updating a histogram with a non-negative
* increment.
* @param value
* @param increment
*/
updateByIncrement(value: number, increment: number): void;
/**
* merge combines data from previous value into self
* @param {ExponentialHistogramAccumulation} previous
*/
merge(previous: ExponentialHistogramAccumulation): void;
/**
* diff subtracts other from self
* @param {ExponentialHistogramAccumulation} other
*/
diff(other: ExponentialHistogramAccumulation): void;
/**
* clone returns a deep copy of self
* @returns {ExponentialHistogramAccumulation}
*/
clone(): ExponentialHistogramAccumulation;
/**
* _updateBuckets maps the incoming value to a bucket index for the current
* scale. If the bucket index is outside of the range of the backing array,
* it will rescale the backing array and update the mapping for the new scale.
*/
private _updateBuckets;
/**
* _incrementIndexBy increments the count of the bucket specified by `index`.
* If the index is outside of the range [buckets.indexStart, buckets.indexEnd]
* the boundaries of the backing array will be adjusted and more buckets will
* be added if needed.
*/
private _incrementIndexBy;
/**
* grow resizes the backing array by doubling in size up to maxSize.
* This extends the array with a bunch of zeros and copies the
* existing counts to the same position.
*/
private _grow;
/**
* _changeScale computes how much downscaling is needed by shifting the
* high and low values until they are separated by no more than size.
*/
private _changeScale;
/**
* _downscale subtracts `change` from the current mapping scale.
*/
private _downscale;
/**
* _minScale is used by diff and merge to compute an ideal combined scale
*/
private _minScale;
/**
* _highLowAtScale is used by diff and merge to compute an ideal combined scale.
*/
private _highLowAtScale;
/**
* _mergeBuckets translates index values from another histogram and
* adds the values into the corresponding buckets of this histogram.
*/
private _mergeBuckets;
/**
* _diffBuckets translates index values from another histogram and
* subtracts the values in the corresponding buckets of this histogram.
*/
private _diffBuckets;
}
/**
* Aggregator for ExponentialHistogramAccumulations
*/
export declare class ExponentialHistogramAggregator implements Aggregator<ExponentialHistogramAccumulation> {
readonly _maxSize: number;
private readonly _recordMinMax;
kind: AggregatorKind.EXPONENTIAL_HISTOGRAM;
/**
* @param _maxSize Maximum number of buckets for each of the positive
* and negative ranges, exclusive of the zero-bucket.
* @param _recordMinMax If set to true, min and max will be recorded.
* Otherwise, min and max will not be recorded.
*/
constructor(_maxSize: number, _recordMinMax: boolean);
createAccumulation(startTime: HrTime): ExponentialHistogramAccumulation;
/**
* Return the result of the merge of two exponential histogram accumulations.
*/
merge(previous: ExponentialHistogramAccumulation, delta: ExponentialHistogramAccumulation): ExponentialHistogramAccumulation;
/**
* Returns a new DELTA aggregation by comparing two cumulative measurements.
*/
diff(previous: ExponentialHistogramAccumulation, current: ExponentialHistogramAccumulation): ExponentialHistogramAccumulation;
toMetricData(descriptor: MetricDescriptor, aggregationTemporality: AggregationTemporality, accumulationByAttributes: AccumulationRecord<ExponentialHistogramAccumulation>[], endTime: HrTime): Maybe<ExponentialHistogramMetricData>;
}
export {};
//# sourceMappingURL=ExponentialHistogram.d.ts.map

View File

@@ -0,0 +1,525 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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.
*/
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
import { AggregatorKind, } from './types';
import { DataPointType, } from '../export/MetricData';
import { diag } from '@opentelemetry/api';
import { InstrumentType } from '../InstrumentDescriptor';
import { Buckets } from './exponential-histogram/Buckets';
import { getMapping } from './exponential-histogram/mapping/getMapping';
import { nextGreaterSquare } from './exponential-histogram/util';
// HighLow is a utility class used for computing a common scale for
// two exponential histogram accumulations
var HighLow = /** @class */ (function () {
function HighLow(low, high) {
this.low = low;
this.high = high;
}
HighLow.combine = function (h1, h2) {
return new HighLow(Math.min(h1.low, h2.low), Math.max(h1.high, h2.high));
};
return HighLow;
}());
var MAX_SCALE = 20;
var DEFAULT_MAX_SIZE = 160;
var MIN_MAX_SIZE = 2;
var ExponentialHistogramAccumulation = /** @class */ (function () {
function ExponentialHistogramAccumulation(startTime, _maxSize, _recordMinMax, _sum, _count, _zeroCount, _min, _max, _positive, _negative, _mapping) {
if (startTime === void 0) { startTime = startTime; }
if (_maxSize === void 0) { _maxSize = DEFAULT_MAX_SIZE; }
if (_recordMinMax === void 0) { _recordMinMax = true; }
if (_sum === void 0) { _sum = 0; }
if (_count === void 0) { _count = 0; }
if (_zeroCount === void 0) { _zeroCount = 0; }
if (_min === void 0) { _min = Number.POSITIVE_INFINITY; }
if (_max === void 0) { _max = Number.NEGATIVE_INFINITY; }
if (_positive === void 0) { _positive = new Buckets(); }
if (_negative === void 0) { _negative = new Buckets(); }
if (_mapping === void 0) { _mapping = getMapping(MAX_SCALE); }
this.startTime = startTime;
this._maxSize = _maxSize;
this._recordMinMax = _recordMinMax;
this._sum = _sum;
this._count = _count;
this._zeroCount = _zeroCount;
this._min = _min;
this._max = _max;
this._positive = _positive;
this._negative = _negative;
this._mapping = _mapping;
if (this._maxSize < MIN_MAX_SIZE) {
diag.warn("Exponential Histogram Max Size set to " + this._maxSize + ", changing to the minimum size of: " + MIN_MAX_SIZE);
this._maxSize = MIN_MAX_SIZE;
}
}
/**
* record updates a histogram with a single count
* @param {Number} value
*/
ExponentialHistogramAccumulation.prototype.record = function (value) {
this.updateByIncrement(value, 1);
};
/**
* Sets the start time for this accumulation
* @param {HrTime} startTime
*/
ExponentialHistogramAccumulation.prototype.setStartTime = function (startTime) {
this.startTime = startTime;
};
/**
* Returns the datapoint representation of this accumulation
* @param {HrTime} startTime
*/
ExponentialHistogramAccumulation.prototype.toPointValue = function () {
return {
hasMinMax: this._recordMinMax,
min: this.min,
max: this.max,
sum: this.sum,
positive: {
offset: this.positive.offset,
bucketCounts: this.positive.counts(),
},
negative: {
offset: this.negative.offset,
bucketCounts: this.negative.counts(),
},
count: this.count,
scale: this.scale,
zeroCount: this.zeroCount,
};
};
Object.defineProperty(ExponentialHistogramAccumulation.prototype, "sum", {
/**
* @returns {Number} The sum of values recorded by this accumulation
*/
get: function () {
return this._sum;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ExponentialHistogramAccumulation.prototype, "min", {
/**
* @returns {Number} The minimum value recorded by this accumulation
*/
get: function () {
return this._min;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ExponentialHistogramAccumulation.prototype, "max", {
/**
* @returns {Number} The maximum value recorded by this accumulation
*/
get: function () {
return this._max;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ExponentialHistogramAccumulation.prototype, "count", {
/**
* @returns {Number} The count of values recorded by this accumulation
*/
get: function () {
return this._count;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ExponentialHistogramAccumulation.prototype, "zeroCount", {
/**
* @returns {Number} The number of 0 values recorded by this accumulation
*/
get: function () {
return this._zeroCount;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ExponentialHistogramAccumulation.prototype, "scale", {
/**
* @returns {Number} The scale used by this accumulation
*/
get: function () {
if (this._count === this._zeroCount) {
// all zeros! scale doesn't matter, use zero
return 0;
}
return this._mapping.scale;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ExponentialHistogramAccumulation.prototype, "positive", {
/**
* positive holds the positive values
* @returns {Buckets}
*/
get: function () {
return this._positive;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ExponentialHistogramAccumulation.prototype, "negative", {
/**
* negative holds the negative values by their absolute value
* @returns {Buckets}
*/
get: function () {
return this._negative;
},
enumerable: false,
configurable: true
});
/**
* updateByIncr supports updating a histogram with a non-negative
* increment.
* @param value
* @param increment
*/
ExponentialHistogramAccumulation.prototype.updateByIncrement = function (value, increment) {
// NaN does not fall into any bucket, is not zero and should not be counted,
// NaN is never greater than max nor less than min, therefore return as there's nothing for us to do.
if (Number.isNaN(value)) {
return;
}
if (value > this._max) {
this._max = value;
}
if (value < this._min) {
this._min = value;
}
this._count += increment;
if (value === 0) {
this._zeroCount += increment;
return;
}
this._sum += value * increment;
if (value > 0) {
this._updateBuckets(this._positive, value, increment);
}
else {
this._updateBuckets(this._negative, -value, increment);
}
};
/**
* merge combines data from previous value into self
* @param {ExponentialHistogramAccumulation} previous
*/
ExponentialHistogramAccumulation.prototype.merge = function (previous) {
if (this._count === 0) {
this._min = previous.min;
this._max = previous.max;
}
else if (previous.count !== 0) {
if (previous.min < this.min) {
this._min = previous.min;
}
if (previous.max > this.max) {
this._max = previous.max;
}
}
this.startTime = previous.startTime;
this._sum += previous.sum;
this._count += previous.count;
this._zeroCount += previous.zeroCount;
var minScale = this._minScale(previous);
this._downscale(this.scale - minScale);
this._mergeBuckets(this.positive, previous, previous.positive, minScale);
this._mergeBuckets(this.negative, previous, previous.negative, minScale);
};
/**
* diff subtracts other from self
* @param {ExponentialHistogramAccumulation} other
*/
ExponentialHistogramAccumulation.prototype.diff = function (other) {
this._min = Infinity;
this._max = -Infinity;
this._sum -= other.sum;
this._count -= other.count;
this._zeroCount -= other.zeroCount;
var minScale = this._minScale(other);
this._downscale(this.scale - minScale);
this._diffBuckets(this.positive, other, other.positive, minScale);
this._diffBuckets(this.negative, other, other.negative, minScale);
};
/**
* clone returns a deep copy of self
* @returns {ExponentialHistogramAccumulation}
*/
ExponentialHistogramAccumulation.prototype.clone = function () {
return new ExponentialHistogramAccumulation(this.startTime, this._maxSize, this._recordMinMax, this._sum, this._count, this._zeroCount, this._min, this._max, this.positive.clone(), this.negative.clone(), this._mapping);
};
/**
* _updateBuckets maps the incoming value to a bucket index for the current
* scale. If the bucket index is outside of the range of the backing array,
* it will rescale the backing array and update the mapping for the new scale.
*/
ExponentialHistogramAccumulation.prototype._updateBuckets = function (buckets, value, increment) {
var index = this._mapping.mapToIndex(value);
// rescale the mapping if needed
var rescalingNeeded = false;
var high = 0;
var low = 0;
if (buckets.length === 0) {
buckets.indexStart = index;
buckets.indexEnd = buckets.indexStart;
buckets.indexBase = buckets.indexStart;
}
else if (index < buckets.indexStart &&
buckets.indexEnd - index >= this._maxSize) {
rescalingNeeded = true;
low = index;
high = buckets.indexEnd;
}
else if (index > buckets.indexEnd &&
index - buckets.indexStart >= this._maxSize) {
rescalingNeeded = true;
low = buckets.indexStart;
high = index;
}
// rescale and compute index at new scale
if (rescalingNeeded) {
var change = this._changeScale(high, low);
this._downscale(change);
index = this._mapping.mapToIndex(value);
}
this._incrementIndexBy(buckets, index, increment);
};
/**
* _incrementIndexBy increments the count of the bucket specified by `index`.
* If the index is outside of the range [buckets.indexStart, buckets.indexEnd]
* the boundaries of the backing array will be adjusted and more buckets will
* be added if needed.
*/
ExponentialHistogramAccumulation.prototype._incrementIndexBy = function (buckets, index, increment) {
if (increment === 0) {
// nothing to do for a zero increment, can happen during a merge operation
return;
}
if (buckets.length === 0) {
buckets.indexStart = buckets.indexEnd = buckets.indexBase = index;
}
if (index < buckets.indexStart) {
var span = buckets.indexEnd - index;
if (span >= buckets.backing.length) {
this._grow(buckets, span + 1);
}
buckets.indexStart = index;
}
else if (index > buckets.indexEnd) {
var span = index - buckets.indexStart;
if (span >= buckets.backing.length) {
this._grow(buckets, span + 1);
}
buckets.indexEnd = index;
}
var bucketIndex = index - buckets.indexBase;
if (bucketIndex < 0) {
bucketIndex += buckets.backing.length;
}
buckets.incrementBucket(bucketIndex, increment);
};
/**
* grow resizes the backing array by doubling in size up to maxSize.
* This extends the array with a bunch of zeros and copies the
* existing counts to the same position.
*/
ExponentialHistogramAccumulation.prototype._grow = function (buckets, needed) {
var size = buckets.backing.length;
var bias = buckets.indexBase - buckets.indexStart;
var oldPositiveLimit = size - bias;
var newSize = nextGreaterSquare(needed);
if (newSize > this._maxSize) {
newSize = this._maxSize;
}
var newPositiveLimit = newSize - bias;
buckets.backing.growTo(newSize, oldPositiveLimit, newPositiveLimit);
};
/**
* _changeScale computes how much downscaling is needed by shifting the
* high and low values until they are separated by no more than size.
*/
ExponentialHistogramAccumulation.prototype._changeScale = function (high, low) {
var change = 0;
while (high - low >= this._maxSize) {
high >>= 1;
low >>= 1;
change++;
}
return change;
};
/**
* _downscale subtracts `change` from the current mapping scale.
*/
ExponentialHistogramAccumulation.prototype._downscale = function (change) {
if (change === 0) {
return;
}
if (change < 0) {
// Note: this should be impossible. If we get here it's because
// there is a bug in the implementation.
throw new Error("impossible change of scale: " + this.scale);
}
var newScale = this._mapping.scale - change;
this._positive.downscale(change);
this._negative.downscale(change);
this._mapping = getMapping(newScale);
};
/**
* _minScale is used by diff and merge to compute an ideal combined scale
*/
ExponentialHistogramAccumulation.prototype._minScale = function (other) {
var minScale = Math.min(this.scale, other.scale);
var highLowPos = HighLow.combine(this._highLowAtScale(this.positive, this.scale, minScale), this._highLowAtScale(other.positive, other.scale, minScale));
var highLowNeg = HighLow.combine(this._highLowAtScale(this.negative, this.scale, minScale), this._highLowAtScale(other.negative, other.scale, minScale));
return Math.min(minScale - this._changeScale(highLowPos.high, highLowPos.low), minScale - this._changeScale(highLowNeg.high, highLowNeg.low));
};
/**
* _highLowAtScale is used by diff and merge to compute an ideal combined scale.
*/
ExponentialHistogramAccumulation.prototype._highLowAtScale = function (buckets, currentScale, newScale) {
if (buckets.length === 0) {
return new HighLow(0, -1);
}
var shift = currentScale - newScale;
return new HighLow(buckets.indexStart >> shift, buckets.indexEnd >> shift);
};
/**
* _mergeBuckets translates index values from another histogram and
* adds the values into the corresponding buckets of this histogram.
*/
ExponentialHistogramAccumulation.prototype._mergeBuckets = function (ours, other, theirs, scale) {
var theirOffset = theirs.offset;
var theirChange = other.scale - scale;
for (var i = 0; i < theirs.length; i++) {
this._incrementIndexBy(ours, (theirOffset + i) >> theirChange, theirs.at(i));
}
};
/**
* _diffBuckets translates index values from another histogram and
* subtracts the values in the corresponding buckets of this histogram.
*/
ExponentialHistogramAccumulation.prototype._diffBuckets = function (ours, other, theirs, scale) {
var theirOffset = theirs.offset;
var theirChange = other.scale - scale;
for (var i = 0; i < theirs.length; i++) {
var ourIndex = (theirOffset + i) >> theirChange;
var bucketIndex = ourIndex - ours.indexBase;
if (bucketIndex < 0) {
bucketIndex += ours.backing.length;
}
ours.decrementBucket(bucketIndex, theirs.at(i));
}
ours.trim();
};
return ExponentialHistogramAccumulation;
}());
export { ExponentialHistogramAccumulation };
/**
* Aggregator for ExponentialHistogramAccumulations
*/
var ExponentialHistogramAggregator = /** @class */ (function () {
/**
* @param _maxSize Maximum number of buckets for each of the positive
* and negative ranges, exclusive of the zero-bucket.
* @param _recordMinMax If set to true, min and max will be recorded.
* Otherwise, min and max will not be recorded.
*/
function ExponentialHistogramAggregator(_maxSize, _recordMinMax) {
this._maxSize = _maxSize;
this._recordMinMax = _recordMinMax;
this.kind = AggregatorKind.EXPONENTIAL_HISTOGRAM;
}
ExponentialHistogramAggregator.prototype.createAccumulation = function (startTime) {
return new ExponentialHistogramAccumulation(startTime, this._maxSize, this._recordMinMax);
};
/**
* Return the result of the merge of two exponential histogram accumulations.
*/
ExponentialHistogramAggregator.prototype.merge = function (previous, delta) {
var result = delta.clone();
result.merge(previous);
return result;
};
/**
* Returns a new DELTA aggregation by comparing two cumulative measurements.
*/
ExponentialHistogramAggregator.prototype.diff = function (previous, current) {
var result = current.clone();
result.diff(previous);
return result;
};
ExponentialHistogramAggregator.prototype.toMetricData = function (descriptor, aggregationTemporality, accumulationByAttributes, endTime) {
return {
descriptor: descriptor,
aggregationTemporality: aggregationTemporality,
dataPointType: DataPointType.EXPONENTIAL_HISTOGRAM,
dataPoints: accumulationByAttributes.map(function (_a) {
var _b = __read(_a, 2), attributes = _b[0], accumulation = _b[1];
var pointValue = accumulation.toPointValue();
// determine if instrument allows negative values.
var allowsNegativeValues = descriptor.type === InstrumentType.GAUGE ||
descriptor.type === InstrumentType.UP_DOWN_COUNTER ||
descriptor.type === InstrumentType.OBSERVABLE_GAUGE ||
descriptor.type === InstrumentType.OBSERVABLE_UP_DOWN_COUNTER;
return {
attributes: attributes,
startTime: accumulation.startTime,
endTime: endTime,
value: {
min: pointValue.hasMinMax ? pointValue.min : undefined,
max: pointValue.hasMinMax ? pointValue.max : undefined,
sum: !allowsNegativeValues ? pointValue.sum : undefined,
positive: {
offset: pointValue.positive.offset,
bucketCounts: pointValue.positive.bucketCounts,
},
negative: {
offset: pointValue.negative.offset,
bucketCounts: pointValue.negative.bucketCounts,
},
count: pointValue.count,
scale: pointValue.scale,
zeroCount: pointValue.zeroCount,
},
};
}),
};
};
return ExponentialHistogramAggregator;
}());
export { ExponentialHistogramAggregator };
//# sourceMappingURL=ExponentialHistogram.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,59 @@
import { Accumulation, AccumulationRecord, Aggregator, AggregatorKind } from './types';
import { HistogramMetricData, MetricDescriptor } from '../export/MetricData';
import { HrTime } from '@opentelemetry/api';
import { Maybe } from '../utils';
import { AggregationTemporality } from '../export/AggregationTemporality';
/**
* Internal value type for HistogramAggregation.
* Differs from the exported type as undefined sum/min/max complicate arithmetic
* performed by this aggregation, but are required to be undefined in the exported types.
*/
interface InternalHistogram {
buckets: {
boundaries: number[];
counts: number[];
};
sum: number;
count: number;
hasMinMax: boolean;
min: number;
max: number;
}
export declare class HistogramAccumulation implements Accumulation {
startTime: HrTime;
private readonly _boundaries;
private _recordMinMax;
private _current;
constructor(startTime: HrTime, _boundaries: number[], _recordMinMax?: boolean, _current?: InternalHistogram);
record(value: number): void;
setStartTime(startTime: HrTime): void;
toPointValue(): InternalHistogram;
}
/**
* Basic aggregator which observes events and counts them in pre-defined buckets
* and provides the total sum and count of all observations.
*/
export declare class HistogramAggregator implements Aggregator<HistogramAccumulation> {
private readonly _boundaries;
private readonly _recordMinMax;
kind: AggregatorKind.HISTOGRAM;
/**
* @param _boundaries sorted upper bounds of recorded values.
* @param _recordMinMax If set to true, min and max will be recorded. Otherwise, min and max will not be recorded.
*/
constructor(_boundaries: number[], _recordMinMax: boolean);
createAccumulation(startTime: HrTime): HistogramAccumulation;
/**
* Return the result of the merge of two histogram accumulations. As long as one Aggregator
* instance produces all Accumulations with constant boundaries we don't need to worry about
* merging accumulations with different boundaries.
*/
merge(previous: HistogramAccumulation, delta: HistogramAccumulation): HistogramAccumulation;
/**
* Returns a new DELTA aggregation by comparing two cumulative measurements.
*/
diff(previous: HistogramAccumulation, current: HistogramAccumulation): HistogramAccumulation;
toMetricData(descriptor: MetricDescriptor, aggregationTemporality: AggregationTemporality, accumulationByAttributes: AccumulationRecord<HistogramAccumulation>[], endTime: HrTime): Maybe<HistogramMetricData>;
}
export {};
//# sourceMappingURL=Histogram.d.ts.map

View File

@@ -0,0 +1,200 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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.
*/
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
import { AggregatorKind, } from './types';
import { DataPointType, } from '../export/MetricData';
import { InstrumentType } from '../InstrumentDescriptor';
import { binarySearchUB } from '../utils';
function createNewEmptyCheckpoint(boundaries) {
var counts = boundaries.map(function () { return 0; });
counts.push(0);
return {
buckets: {
boundaries: boundaries,
counts: counts,
},
sum: 0,
count: 0,
hasMinMax: false,
min: Infinity,
max: -Infinity,
};
}
var HistogramAccumulation = /** @class */ (function () {
function HistogramAccumulation(startTime, _boundaries, _recordMinMax, _current) {
if (_recordMinMax === void 0) { _recordMinMax = true; }
if (_current === void 0) { _current = createNewEmptyCheckpoint(_boundaries); }
this.startTime = startTime;
this._boundaries = _boundaries;
this._recordMinMax = _recordMinMax;
this._current = _current;
}
HistogramAccumulation.prototype.record = function (value) {
// NaN does not fall into any bucket, is not zero and should not be counted,
// NaN is never greater than max nor less than min, therefore return as there's nothing for us to do.
if (Number.isNaN(value)) {
return;
}
this._current.count += 1;
this._current.sum += value;
if (this._recordMinMax) {
this._current.min = Math.min(value, this._current.min);
this._current.max = Math.max(value, this._current.max);
this._current.hasMinMax = true;
}
var idx = binarySearchUB(this._boundaries, value);
this._current.buckets.counts[idx] += 1;
};
HistogramAccumulation.prototype.setStartTime = function (startTime) {
this.startTime = startTime;
};
HistogramAccumulation.prototype.toPointValue = function () {
return this._current;
};
return HistogramAccumulation;
}());
export { HistogramAccumulation };
/**
* Basic aggregator which observes events and counts them in pre-defined buckets
* and provides the total sum and count of all observations.
*/
var HistogramAggregator = /** @class */ (function () {
/**
* @param _boundaries sorted upper bounds of recorded values.
* @param _recordMinMax If set to true, min and max will be recorded. Otherwise, min and max will not be recorded.
*/
function HistogramAggregator(_boundaries, _recordMinMax) {
this._boundaries = _boundaries;
this._recordMinMax = _recordMinMax;
this.kind = AggregatorKind.HISTOGRAM;
}
HistogramAggregator.prototype.createAccumulation = function (startTime) {
return new HistogramAccumulation(startTime, this._boundaries, this._recordMinMax);
};
/**
* Return the result of the merge of two histogram accumulations. As long as one Aggregator
* instance produces all Accumulations with constant boundaries we don't need to worry about
* merging accumulations with different boundaries.
*/
HistogramAggregator.prototype.merge = function (previous, delta) {
var previousValue = previous.toPointValue();
var deltaValue = delta.toPointValue();
var previousCounts = previousValue.buckets.counts;
var deltaCounts = deltaValue.buckets.counts;
var mergedCounts = new Array(previousCounts.length);
for (var idx = 0; idx < previousCounts.length; idx++) {
mergedCounts[idx] = previousCounts[idx] + deltaCounts[idx];
}
var min = Infinity;
var max = -Infinity;
if (this._recordMinMax) {
if (previousValue.hasMinMax && deltaValue.hasMinMax) {
min = Math.min(previousValue.min, deltaValue.min);
max = Math.max(previousValue.max, deltaValue.max);
}
else if (previousValue.hasMinMax) {
min = previousValue.min;
max = previousValue.max;
}
else if (deltaValue.hasMinMax) {
min = deltaValue.min;
max = deltaValue.max;
}
}
return new HistogramAccumulation(previous.startTime, previousValue.buckets.boundaries, this._recordMinMax, {
buckets: {
boundaries: previousValue.buckets.boundaries,
counts: mergedCounts,
},
count: previousValue.count + deltaValue.count,
sum: previousValue.sum + deltaValue.sum,
hasMinMax: this._recordMinMax &&
(previousValue.hasMinMax || deltaValue.hasMinMax),
min: min,
max: max,
});
};
/**
* Returns a new DELTA aggregation by comparing two cumulative measurements.
*/
HistogramAggregator.prototype.diff = function (previous, current) {
var previousValue = previous.toPointValue();
var currentValue = current.toPointValue();
var previousCounts = previousValue.buckets.counts;
var currentCounts = currentValue.buckets.counts;
var diffedCounts = new Array(previousCounts.length);
for (var idx = 0; idx < previousCounts.length; idx++) {
diffedCounts[idx] = currentCounts[idx] - previousCounts[idx];
}
return new HistogramAccumulation(current.startTime, previousValue.buckets.boundaries, this._recordMinMax, {
buckets: {
boundaries: previousValue.buckets.boundaries,
counts: diffedCounts,
},
count: currentValue.count - previousValue.count,
sum: currentValue.sum - previousValue.sum,
hasMinMax: false,
min: Infinity,
max: -Infinity,
});
};
HistogramAggregator.prototype.toMetricData = function (descriptor, aggregationTemporality, accumulationByAttributes, endTime) {
return {
descriptor: descriptor,
aggregationTemporality: aggregationTemporality,
dataPointType: DataPointType.HISTOGRAM,
dataPoints: accumulationByAttributes.map(function (_a) {
var _b = __read(_a, 2), attributes = _b[0], accumulation = _b[1];
var pointValue = accumulation.toPointValue();
// determine if instrument allows negative values.
var allowsNegativeValues = descriptor.type === InstrumentType.GAUGE ||
descriptor.type === InstrumentType.UP_DOWN_COUNTER ||
descriptor.type === InstrumentType.OBSERVABLE_GAUGE ||
descriptor.type === InstrumentType.OBSERVABLE_UP_DOWN_COUNTER;
return {
attributes: attributes,
startTime: accumulation.startTime,
endTime: endTime,
value: {
min: pointValue.hasMinMax ? pointValue.min : undefined,
max: pointValue.hasMinMax ? pointValue.max : undefined,
sum: !allowsNegativeValues ? pointValue.sum : undefined,
buckets: pointValue.buckets,
count: pointValue.count,
},
};
}),
};
};
return HistogramAggregator;
}());
export { HistogramAggregator };
//# sourceMappingURL=Histogram.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,34 @@
import { Accumulation, AccumulationRecord, Aggregator, AggregatorKind, LastValue } from './types';
import { HrTime } from '@opentelemetry/api';
import { GaugeMetricData, MetricDescriptor } from '../export/MetricData';
import { Maybe } from '../utils';
import { AggregationTemporality } from '../export/AggregationTemporality';
export declare class LastValueAccumulation implements Accumulation {
startTime: HrTime;
private _current;
sampleTime: HrTime;
constructor(startTime: HrTime, _current?: number, sampleTime?: HrTime);
record(value: number): void;
setStartTime(startTime: HrTime): void;
toPointValue(): LastValue;
}
/** Basic aggregator which calculates a LastValue from individual measurements. */
export declare class LastValueAggregator implements Aggregator<LastValueAccumulation> {
kind: AggregatorKind.LAST_VALUE;
createAccumulation(startTime: HrTime): LastValueAccumulation;
/**
* Returns the result of the merge of the given accumulations.
*
* Return the newly captured (delta) accumulation for LastValueAggregator.
*/
merge(previous: LastValueAccumulation, delta: LastValueAccumulation): LastValueAccumulation;
/**
* Returns a new DELTA aggregation by comparing two cumulative measurements.
*
* A delta aggregation is not meaningful to LastValueAggregator, just return
* the newly captured (delta) accumulation for LastValueAggregator.
*/
diff(previous: LastValueAccumulation, current: LastValueAccumulation): LastValueAccumulation;
toMetricData(descriptor: MetricDescriptor, aggregationTemporality: AggregationTemporality, accumulationByAttributes: AccumulationRecord<LastValueAccumulation>[], endTime: HrTime): Maybe<GaugeMetricData>;
}
//# sourceMappingURL=LastValue.d.ts.map

View File

@@ -0,0 +1,110 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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.
*/
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
import { AggregatorKind, } from './types';
import { millisToHrTime, hrTimeToMicroseconds } from '@opentelemetry/core';
import { DataPointType, } from '../export/MetricData';
var LastValueAccumulation = /** @class */ (function () {
function LastValueAccumulation(startTime, _current, sampleTime) {
if (_current === void 0) { _current = 0; }
if (sampleTime === void 0) { sampleTime = [0, 0]; }
this.startTime = startTime;
this._current = _current;
this.sampleTime = sampleTime;
}
LastValueAccumulation.prototype.record = function (value) {
this._current = value;
this.sampleTime = millisToHrTime(Date.now());
};
LastValueAccumulation.prototype.setStartTime = function (startTime) {
this.startTime = startTime;
};
LastValueAccumulation.prototype.toPointValue = function () {
return this._current;
};
return LastValueAccumulation;
}());
export { LastValueAccumulation };
/** Basic aggregator which calculates a LastValue from individual measurements. */
var LastValueAggregator = /** @class */ (function () {
function LastValueAggregator() {
this.kind = AggregatorKind.LAST_VALUE;
}
LastValueAggregator.prototype.createAccumulation = function (startTime) {
return new LastValueAccumulation(startTime);
};
/**
* Returns the result of the merge of the given accumulations.
*
* Return the newly captured (delta) accumulation for LastValueAggregator.
*/
LastValueAggregator.prototype.merge = function (previous, delta) {
// nanoseconds may lose precisions.
var latestAccumulation = hrTimeToMicroseconds(delta.sampleTime) >=
hrTimeToMicroseconds(previous.sampleTime)
? delta
: previous;
return new LastValueAccumulation(previous.startTime, latestAccumulation.toPointValue(), latestAccumulation.sampleTime);
};
/**
* Returns a new DELTA aggregation by comparing two cumulative measurements.
*
* A delta aggregation is not meaningful to LastValueAggregator, just return
* the newly captured (delta) accumulation for LastValueAggregator.
*/
LastValueAggregator.prototype.diff = function (previous, current) {
// nanoseconds may lose precisions.
var latestAccumulation = hrTimeToMicroseconds(current.sampleTime) >=
hrTimeToMicroseconds(previous.sampleTime)
? current
: previous;
return new LastValueAccumulation(current.startTime, latestAccumulation.toPointValue(), latestAccumulation.sampleTime);
};
LastValueAggregator.prototype.toMetricData = function (descriptor, aggregationTemporality, accumulationByAttributes, endTime) {
return {
descriptor: descriptor,
aggregationTemporality: aggregationTemporality,
dataPointType: DataPointType.GAUGE,
dataPoints: accumulationByAttributes.map(function (_a) {
var _b = __read(_a, 2), attributes = _b[0], accumulation = _b[1];
return {
attributes: attributes,
startTime: accumulation.startTime,
endTime: endTime,
value: accumulation.toPointValue(),
};
}),
};
};
return LastValueAggregator;
}());
export { LastValueAggregator };
//# sourceMappingURL=LastValue.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,32 @@
import { Sum, AggregatorKind, Aggregator, Accumulation, AccumulationRecord } from './types';
import { HrTime } from '@opentelemetry/api';
import { MetricDescriptor, SumMetricData } from '../export/MetricData';
import { Maybe } from '../utils';
import { AggregationTemporality } from '../export/AggregationTemporality';
export declare class SumAccumulation implements Accumulation {
startTime: HrTime;
monotonic: boolean;
private _current;
reset: boolean;
constructor(startTime: HrTime, monotonic: boolean, _current?: number, reset?: boolean);
record(value: number): void;
setStartTime(startTime: HrTime): void;
toPointValue(): Sum;
}
/** Basic aggregator which calculates a Sum from individual measurements. */
export declare class SumAggregator implements Aggregator<SumAccumulation> {
monotonic: boolean;
kind: AggregatorKind.SUM;
constructor(monotonic: boolean);
createAccumulation(startTime: HrTime): SumAccumulation;
/**
* Returns the result of the merge of the given accumulations.
*/
merge(previous: SumAccumulation, delta: SumAccumulation): SumAccumulation;
/**
* Returns a new DELTA aggregation by comparing two cumulative measurements.
*/
diff(previous: SumAccumulation, current: SumAccumulation): SumAccumulation;
toMetricData(descriptor: MetricDescriptor, aggregationTemporality: AggregationTemporality, accumulationByAttributes: AccumulationRecord<SumAccumulation>[], endTime: HrTime): Maybe<SumMetricData>;
}
//# sourceMappingURL=Sum.d.ts.map

View File

@@ -0,0 +1,114 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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.
*/
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
import { AggregatorKind, } from './types';
import { DataPointType, } from '../export/MetricData';
var SumAccumulation = /** @class */ (function () {
function SumAccumulation(startTime, monotonic, _current, reset) {
if (_current === void 0) { _current = 0; }
if (reset === void 0) { reset = false; }
this.startTime = startTime;
this.monotonic = monotonic;
this._current = _current;
this.reset = reset;
}
SumAccumulation.prototype.record = function (value) {
if (this.monotonic && value < 0) {
return;
}
this._current += value;
};
SumAccumulation.prototype.setStartTime = function (startTime) {
this.startTime = startTime;
};
SumAccumulation.prototype.toPointValue = function () {
return this._current;
};
return SumAccumulation;
}());
export { SumAccumulation };
/** Basic aggregator which calculates a Sum from individual measurements. */
var SumAggregator = /** @class */ (function () {
function SumAggregator(monotonic) {
this.monotonic = monotonic;
this.kind = AggregatorKind.SUM;
}
SumAggregator.prototype.createAccumulation = function (startTime) {
return new SumAccumulation(startTime, this.monotonic);
};
/**
* Returns the result of the merge of the given accumulations.
*/
SumAggregator.prototype.merge = function (previous, delta) {
var prevPv = previous.toPointValue();
var deltaPv = delta.toPointValue();
if (delta.reset) {
return new SumAccumulation(delta.startTime, this.monotonic, deltaPv, delta.reset);
}
return new SumAccumulation(previous.startTime, this.monotonic, prevPv + deltaPv);
};
/**
* Returns a new DELTA aggregation by comparing two cumulative measurements.
*/
SumAggregator.prototype.diff = function (previous, current) {
var prevPv = previous.toPointValue();
var currPv = current.toPointValue();
/**
* If the SumAggregator is a monotonic one and the previous point value is
* greater than the current one, a reset is deemed to be happened.
* Return the current point value to prevent the value from been reset.
*/
if (this.monotonic && prevPv > currPv) {
return new SumAccumulation(current.startTime, this.monotonic, currPv, true);
}
return new SumAccumulation(current.startTime, this.monotonic, currPv - prevPv);
};
SumAggregator.prototype.toMetricData = function (descriptor, aggregationTemporality, accumulationByAttributes, endTime) {
return {
descriptor: descriptor,
aggregationTemporality: aggregationTemporality,
dataPointType: DataPointType.SUM,
dataPoints: accumulationByAttributes.map(function (_a) {
var _b = __read(_a, 2), attributes = _b[0], accumulation = _b[1];
return {
attributes: attributes,
startTime: accumulation.startTime,
endTime: endTime,
value: accumulation.toPointValue(),
};
}),
isMonotonic: this.monotonic,
};
};
return SumAggregator;
}());
export { SumAggregator };
//# sourceMappingURL=Sum.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,133 @@
export declare class Buckets {
backing: BucketsBacking;
indexBase: number;
indexStart: number;
indexEnd: number;
/**
* The term index refers to the number of the exponential histogram bucket
* used to determine its boundaries. The lower boundary of a bucket is
* determined by base ** index and the upper boundary of a bucket is
* determined by base ** (index + 1). index values are signed to account
* for values less than or equal to 1.
*
* indexBase is the index of the 0th position in the
* backing array, i.e., backing[0] is the count
* in the bucket with index `indexBase`.
*
* indexStart is the smallest index value represented
* in the backing array.
*
* indexEnd is the largest index value represented in
* the backing array.
*/
constructor(backing?: BucketsBacking, indexBase?: number, indexStart?: number, indexEnd?: number);
/**
* Offset is the bucket index of the smallest entry in the counts array
* @returns {number}
*/
get offset(): number;
/**
* Buckets is a view into the backing array.
* @returns {number}
*/
get length(): number;
/**
* An array of counts, where count[i] carries the count
* of the bucket at index (offset+i). count[i] is the count of
* values greater than base^(offset+i) and less than or equal to
* base^(offset+i+1).
* @returns {number} The logical counts based on the backing array
*/
counts(): number[];
/**
* At returns the count of the bucket at a position in the logical
* array of counts.
* @param position
* @returns {number}
*/
at(position: number): number;
/**
* incrementBucket increments the backing array index by `increment`
* @param bucketIndex
* @param increment
*/
incrementBucket(bucketIndex: number, increment: number): void;
/**
* decrementBucket decrements the backing array index by `decrement`
* if decrement is greater than the current value, it's set to 0.
* @param bucketIndex
* @param decrement
*/
decrementBucket(bucketIndex: number, decrement: number): void;
/**
* trim removes leading and / or trailing zero buckets (which can occur
* after diffing two histos) and rotates the backing array so that the
* smallest non-zero index is in the 0th position of the backing array
*/
trim(): void;
/**
* downscale first rotates, then collapses 2**`by`-to-1 buckets.
* @param by
*/
downscale(by: number): void;
/**
* Clone returns a deep copy of Buckets
* @returns {Buckets}
*/
clone(): Buckets;
/**
* _rotate shifts the backing array contents so that indexStart ==
* indexBase to simplify the downscale logic.
*/
private _rotate;
/**
* _relocateBucket adds the count in counts[src] to counts[dest] and
* resets count[src] to zero.
*/
private _relocateBucket;
}
/**
* BucketsBacking holds the raw buckets and some utility methods to
* manage them.
*/
declare class BucketsBacking {
private _counts;
constructor(_counts?: number[]);
/**
* length returns the physical size of the backing array, which
* is >= buckets.length()
*/
get length(): number;
/**
* countAt returns the count in a specific bucket
*/
countAt(pos: number): number;
/**
* growTo grows a backing array and copies old entries
* into their correct new positions.
*/
growTo(newSize: number, oldPositiveLimit: number, newPositiveLimit: number): void;
/**
* reverse the items in the backing array in the range [from, limit).
*/
reverse(from: number, limit: number): void;
/**
* emptyBucket empties the count from a bucket, for
* moving into another.
*/
emptyBucket(src: number): number;
/**
* increments a bucket by `increment`
*/
increment(bucketIndex: number, increment: number): void;
/**
* decrements a bucket by `decrement`
*/
decrement(bucketIndex: number, decrement: number): void;
/**
* clone returns a deep copy of BucketsBacking
*/
clone(): BucketsBacking;
}
export {};
//# sourceMappingURL=Buckets.d.ts.map

View File

@@ -0,0 +1,315 @@
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
/*
* Copyright The OpenTelemetry 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
*
* https://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.
*/
var Buckets = /** @class */ (function () {
/**
* The term index refers to the number of the exponential histogram bucket
* used to determine its boundaries. The lower boundary of a bucket is
* determined by base ** index and the upper boundary of a bucket is
* determined by base ** (index + 1). index values are signed to account
* for values less than or equal to 1.
*
* indexBase is the index of the 0th position in the
* backing array, i.e., backing[0] is the count
* in the bucket with index `indexBase`.
*
* indexStart is the smallest index value represented
* in the backing array.
*
* indexEnd is the largest index value represented in
* the backing array.
*/
function Buckets(backing, indexBase, indexStart, indexEnd) {
if (backing === void 0) { backing = new BucketsBacking(); }
if (indexBase === void 0) { indexBase = 0; }
if (indexStart === void 0) { indexStart = 0; }
if (indexEnd === void 0) { indexEnd = 0; }
this.backing = backing;
this.indexBase = indexBase;
this.indexStart = indexStart;
this.indexEnd = indexEnd;
}
Object.defineProperty(Buckets.prototype, "offset", {
/**
* Offset is the bucket index of the smallest entry in the counts array
* @returns {number}
*/
get: function () {
return this.indexStart;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Buckets.prototype, "length", {
/**
* Buckets is a view into the backing array.
* @returns {number}
*/
get: function () {
if (this.backing.length === 0) {
return 0;
}
if (this.indexEnd === this.indexStart && this.at(0) === 0) {
return 0;
}
return this.indexEnd - this.indexStart + 1;
},
enumerable: false,
configurable: true
});
/**
* An array of counts, where count[i] carries the count
* of the bucket at index (offset+i). count[i] is the count of
* values greater than base^(offset+i) and less than or equal to
* base^(offset+i+1).
* @returns {number} The logical counts based on the backing array
*/
Buckets.prototype.counts = function () {
var _this = this;
return Array.from({ length: this.length }, function (_, i) { return _this.at(i); });
};
/**
* At returns the count of the bucket at a position in the logical
* array of counts.
* @param position
* @returns {number}
*/
Buckets.prototype.at = function (position) {
var bias = this.indexBase - this.indexStart;
if (position < bias) {
position += this.backing.length;
}
position -= bias;
return this.backing.countAt(position);
};
/**
* incrementBucket increments the backing array index by `increment`
* @param bucketIndex
* @param increment
*/
Buckets.prototype.incrementBucket = function (bucketIndex, increment) {
this.backing.increment(bucketIndex, increment);
};
/**
* decrementBucket decrements the backing array index by `decrement`
* if decrement is greater than the current value, it's set to 0.
* @param bucketIndex
* @param decrement
*/
Buckets.prototype.decrementBucket = function (bucketIndex, decrement) {
this.backing.decrement(bucketIndex, decrement);
};
/**
* trim removes leading and / or trailing zero buckets (which can occur
* after diffing two histos) and rotates the backing array so that the
* smallest non-zero index is in the 0th position of the backing array
*/
Buckets.prototype.trim = function () {
for (var i = 0; i < this.length; i++) {
if (this.at(i) !== 0) {
this.indexStart += i;
break;
}
else if (i === this.length - 1) {
//the entire array is zeroed out
this.indexStart = this.indexEnd = this.indexBase = 0;
return;
}
}
for (var i = this.length - 1; i >= 0; i--) {
if (this.at(i) !== 0) {
this.indexEnd -= this.length - i - 1;
break;
}
}
this._rotate();
};
/**
* downscale first rotates, then collapses 2**`by`-to-1 buckets.
* @param by
*/
Buckets.prototype.downscale = function (by) {
this._rotate();
var size = 1 + this.indexEnd - this.indexStart;
var each = 1 << by;
var inpos = 0;
var outpos = 0;
for (var pos = this.indexStart; pos <= this.indexEnd;) {
var mod = pos % each;
if (mod < 0) {
mod += each;
}
for (var i = mod; i < each && inpos < size; i++) {
this._relocateBucket(outpos, inpos);
inpos++;
pos++;
}
outpos++;
}
this.indexStart >>= by;
this.indexEnd >>= by;
this.indexBase = this.indexStart;
};
/**
* Clone returns a deep copy of Buckets
* @returns {Buckets}
*/
Buckets.prototype.clone = function () {
return new Buckets(this.backing.clone(), this.indexBase, this.indexStart, this.indexEnd);
};
/**
* _rotate shifts the backing array contents so that indexStart ==
* indexBase to simplify the downscale logic.
*/
Buckets.prototype._rotate = function () {
var bias = this.indexBase - this.indexStart;
if (bias === 0) {
return;
}
else if (bias > 0) {
this.backing.reverse(0, this.backing.length);
this.backing.reverse(0, bias);
this.backing.reverse(bias, this.backing.length);
}
else {
// negative bias, this can happen when diffing two histograms
this.backing.reverse(0, this.backing.length);
this.backing.reverse(0, this.backing.length + bias);
}
this.indexBase = this.indexStart;
};
/**
* _relocateBucket adds the count in counts[src] to counts[dest] and
* resets count[src] to zero.
*/
Buckets.prototype._relocateBucket = function (dest, src) {
if (dest === src) {
return;
}
this.incrementBucket(dest, this.backing.emptyBucket(src));
};
return Buckets;
}());
export { Buckets };
/**
* BucketsBacking holds the raw buckets and some utility methods to
* manage them.
*/
var BucketsBacking = /** @class */ (function () {
function BucketsBacking(_counts) {
if (_counts === void 0) { _counts = [0]; }
this._counts = _counts;
}
Object.defineProperty(BucketsBacking.prototype, "length", {
/**
* length returns the physical size of the backing array, which
* is >= buckets.length()
*/
get: function () {
return this._counts.length;
},
enumerable: false,
configurable: true
});
/**
* countAt returns the count in a specific bucket
*/
BucketsBacking.prototype.countAt = function (pos) {
return this._counts[pos];
};
/**
* growTo grows a backing array and copies old entries
* into their correct new positions.
*/
BucketsBacking.prototype.growTo = function (newSize, oldPositiveLimit, newPositiveLimit) {
var tmp = new Array(newSize).fill(0);
tmp.splice.apply(tmp, __spreadArray([newPositiveLimit,
this._counts.length - oldPositiveLimit], __read(this._counts.slice(oldPositiveLimit)), false));
tmp.splice.apply(tmp, __spreadArray([0, oldPositiveLimit], __read(this._counts.slice(0, oldPositiveLimit)), false));
this._counts = tmp;
};
/**
* reverse the items in the backing array in the range [from, limit).
*/
BucketsBacking.prototype.reverse = function (from, limit) {
var num = Math.floor((from + limit) / 2) - from;
for (var i = 0; i < num; i++) {
var tmp = this._counts[from + i];
this._counts[from + i] = this._counts[limit - i - 1];
this._counts[limit - i - 1] = tmp;
}
};
/**
* emptyBucket empties the count from a bucket, for
* moving into another.
*/
BucketsBacking.prototype.emptyBucket = function (src) {
var tmp = this._counts[src];
this._counts[src] = 0;
return tmp;
};
/**
* increments a bucket by `increment`
*/
BucketsBacking.prototype.increment = function (bucketIndex, increment) {
this._counts[bucketIndex] += increment;
};
/**
* decrements a bucket by `decrement`
*/
BucketsBacking.prototype.decrement = function (bucketIndex, decrement) {
if (this._counts[bucketIndex] >= decrement) {
this._counts[bucketIndex] -= decrement;
}
else {
// this should not happen, but we're being defensive against
// negative counts.
this._counts[bucketIndex] = 0;
}
};
/**
* clone returns a deep copy of BucketsBacking
*/
BucketsBacking.prototype.clone = function () {
return new BucketsBacking(__spreadArray([], __read(this._counts), false));
};
return BucketsBacking;
}());
//# sourceMappingURL=Buckets.js.map

View File

@@ -0,0 +1,31 @@
import { Mapping } from './types';
/**
* ExponentMapping implements exponential mapping functions for
* scales <=0. For scales > 0 LogarithmMapping should be used.
*/
export declare class ExponentMapping implements Mapping {
private readonly _shift;
constructor(scale: number);
/**
* Maps positive floating point values to indexes corresponding to scale
* @param value
* @returns {number} index for provided value at the current scale
*/
mapToIndex(value: number): number;
/**
* Returns the lower bucket boundary for the given index for scale
*
* @param index
* @returns {number}
*/
lowerBoundary(index: number): number;
/**
* The scale used by this mapping
* @returns {number}
*/
get scale(): number;
private _minNormalLowerBoundaryIndex;
private _maxNormalLowerBoundaryIndex;
private _rightShift;
}
//# sourceMappingURL=ExponentMapping.d.ts.map

View File

@@ -0,0 +1,91 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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 ieee754 from './ieee754';
import * as util from '../util';
import { MappingError } from './types';
/**
* ExponentMapping implements exponential mapping functions for
* scales <=0. For scales > 0 LogarithmMapping should be used.
*/
var ExponentMapping = /** @class */ (function () {
function ExponentMapping(scale) {
this._shift = -scale;
}
/**
* Maps positive floating point values to indexes corresponding to scale
* @param value
* @returns {number} index for provided value at the current scale
*/
ExponentMapping.prototype.mapToIndex = function (value) {
if (value < ieee754.MIN_VALUE) {
return this._minNormalLowerBoundaryIndex();
}
var exp = ieee754.getNormalBase2(value);
// In case the value is an exact power of two, compute a
// correction of -1. Note, we are using a custom _rightShift
// to accommodate a 52-bit argument, which the native bitwise
// operators do not support
var correction = this._rightShift(ieee754.getSignificand(value) - 1, ieee754.SIGNIFICAND_WIDTH);
return (exp + correction) >> this._shift;
};
/**
* Returns the lower bucket boundary for the given index for scale
*
* @param index
* @returns {number}
*/
ExponentMapping.prototype.lowerBoundary = function (index) {
var minIndex = this._minNormalLowerBoundaryIndex();
if (index < minIndex) {
throw new MappingError("underflow: " + index + " is < minimum lower boundary: " + minIndex);
}
var maxIndex = this._maxNormalLowerBoundaryIndex();
if (index > maxIndex) {
throw new MappingError("overflow: " + index + " is > maximum lower boundary: " + maxIndex);
}
return util.ldexp(1, index << this._shift);
};
Object.defineProperty(ExponentMapping.prototype, "scale", {
/**
* The scale used by this mapping
* @returns {number}
*/
get: function () {
if (this._shift === 0) {
return 0;
}
return -this._shift;
},
enumerable: false,
configurable: true
});
ExponentMapping.prototype._minNormalLowerBoundaryIndex = function () {
var index = ieee754.MIN_NORMAL_EXPONENT >> this._shift;
if (this._shift < 2) {
index--;
}
return index;
};
ExponentMapping.prototype._maxNormalLowerBoundaryIndex = function () {
return ieee754.MAX_NORMAL_EXPONENT >> this._shift;
};
ExponentMapping.prototype._rightShift = function (value, shift) {
return Math.floor(value * Math.pow(2, -shift));
};
return ExponentMapping;
}());
export { ExponentMapping };
//# sourceMappingURL=ExponentMapping.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ExponentMapping.js","sourceRoot":"","sources":["../../../../../src/aggregator/exponential-histogram/mapping/ExponentMapping.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,KAAK,OAAO,MAAM,WAAW,CAAC;AACrC,OAAO,KAAK,IAAI,MAAM,SAAS,CAAC;AAChC,OAAO,EAAW,YAAY,EAAE,MAAM,SAAS,CAAC;AAEhD;;;GAGG;AACH;IAGE,yBAAY,KAAa;QACvB,IAAI,CAAC,MAAM,GAAG,CAAC,KAAK,CAAC;IACvB,CAAC;IAED;;;;OAIG;IACH,oCAAU,GAAV,UAAW,KAAa;QACtB,IAAI,KAAK,GAAG,OAAO,CAAC,SAAS,EAAE;YAC7B,OAAO,IAAI,CAAC,4BAA4B,EAAE,CAAC;SAC5C;QAED,IAAM,GAAG,GAAG,OAAO,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;QAE1C,wDAAwD;QACxD,4DAA4D;QAC5D,6DAA6D;QAC7D,2BAA2B;QAC3B,IAAM,UAAU,GAAG,IAAI,CAAC,WAAW,CACjC,OAAO,CAAC,cAAc,CAAC,KAAK,CAAC,GAAG,CAAC,EACjC,OAAO,CAAC,iBAAiB,CAC1B,CAAC;QAEF,OAAO,CAAC,GAAG,GAAG,UAAU,CAAC,IAAI,IAAI,CAAC,MAAM,CAAC;IAC3C,CAAC;IAED;;;;;OAKG;IACH,uCAAa,GAAb,UAAc,KAAa;QACzB,IAAM,QAAQ,GAAG,IAAI,CAAC,4BAA4B,EAAE,CAAC;QACrD,IAAI,KAAK,GAAG,QAAQ,EAAE;YACpB,MAAM,IAAI,YAAY,CACpB,gBAAc,KAAK,sCAAiC,QAAU,CAC/D,CAAC;SACH;QACD,IAAM,QAAQ,GAAG,IAAI,CAAC,4BAA4B,EAAE,CAAC;QACrD,IAAI,KAAK,GAAG,QAAQ,EAAE;YACpB,MAAM,IAAI,YAAY,CACpB,eAAa,KAAK,sCAAiC,QAAU,CAC9D,CAAC;SACH;QAED,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,IAAI,IAAI,CAAC,MAAM,CAAC,CAAC;IAC7C,CAAC;IAMD,sBAAI,kCAAK;QAJT;;;WAGG;aACH;YACE,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE;gBACrB,OAAO,CAAC,CAAC;aACV;YACD,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC;QACtB,CAAC;;;OAAA;IAEO,sDAA4B,GAApC;QACE,IAAI,KAAK,GAAG,OAAO,CAAC,mBAAmB,IAAI,IAAI,CAAC,MAAM,CAAC;QACvD,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE;YACnB,KAAK,EAAE,CAAC;SACT;QAED,OAAO,KAAK,CAAC;IACf,CAAC;IAEO,sDAA4B,GAApC;QACE,OAAO,OAAO,CAAC,mBAAmB,IAAI,IAAI,CAAC,MAAM,CAAC;IACpD,CAAC;IAEO,qCAAW,GAAnB,UAAoB,KAAa,EAAE,KAAa;QAC9C,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;IACjD,CAAC;IACH,sBAAC;AAAD,CAAC,AAjFD,IAiFC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport * as ieee754 from './ieee754';\nimport * as util from '../util';\nimport { Mapping, MappingError } from './types';\n\n/**\n * ExponentMapping implements exponential mapping functions for\n * scales <=0. For scales > 0 LogarithmMapping should be used.\n */\nexport class ExponentMapping implements Mapping {\n private readonly _shift: number;\n\n constructor(scale: number) {\n this._shift = -scale;\n }\n\n /**\n * Maps positive floating point values to indexes corresponding to scale\n * @param value\n * @returns {number} index for provided value at the current scale\n */\n mapToIndex(value: number): number {\n if (value < ieee754.MIN_VALUE) {\n return this._minNormalLowerBoundaryIndex();\n }\n\n const exp = ieee754.getNormalBase2(value);\n\n // In case the value is an exact power of two, compute a\n // correction of -1. Note, we are using a custom _rightShift\n // to accommodate a 52-bit argument, which the native bitwise\n // operators do not support\n const correction = this._rightShift(\n ieee754.getSignificand(value) - 1,\n ieee754.SIGNIFICAND_WIDTH\n );\n\n return (exp + correction) >> this._shift;\n }\n\n /**\n * Returns the lower bucket boundary for the given index for scale\n *\n * @param index\n * @returns {number}\n */\n lowerBoundary(index: number): number {\n const minIndex = this._minNormalLowerBoundaryIndex();\n if (index < minIndex) {\n throw new MappingError(\n `underflow: ${index} is < minimum lower boundary: ${minIndex}`\n );\n }\n const maxIndex = this._maxNormalLowerBoundaryIndex();\n if (index > maxIndex) {\n throw new MappingError(\n `overflow: ${index} is > maximum lower boundary: ${maxIndex}`\n );\n }\n\n return util.ldexp(1, index << this._shift);\n }\n\n /**\n * The scale used by this mapping\n * @returns {number}\n */\n get scale(): number {\n if (this._shift === 0) {\n return 0;\n }\n return -this._shift;\n }\n\n private _minNormalLowerBoundaryIndex(): number {\n let index = ieee754.MIN_NORMAL_EXPONENT >> this._shift;\n if (this._shift < 2) {\n index--;\n }\n\n return index;\n }\n\n private _maxNormalLowerBoundaryIndex(): number {\n return ieee754.MAX_NORMAL_EXPONENT >> this._shift;\n }\n\n private _rightShift(value: number, shift: number): number {\n return Math.floor(value * Math.pow(2, -shift));\n }\n}\n"]}

View File

@@ -0,0 +1,32 @@
import { Mapping } from './types';
/**
* LogarithmMapping implements exponential mapping functions for scale > 0.
* For scales <= 0 the exponent mapping should be used.
*/
export declare class LogarithmMapping implements Mapping {
private readonly _scale;
private readonly _scaleFactor;
private readonly _inverseFactor;
constructor(scale: number);
/**
* Maps positive floating point values to indexes corresponding to scale
* @param value
* @returns {number} index for provided value at the current scale
*/
mapToIndex(value: number): number;
/**
* Returns the lower bucket boundary for the given index for scale
*
* @param index
* @returns {number}
*/
lowerBoundary(index: number): number;
/**
* The scale used by this mapping
* @returns {number}
*/
get scale(): number;
private _minNormalLowerBoundaryIndex;
private _maxNormalLowerBoundaryIndex;
}
//# sourceMappingURL=LogarithmMapping.d.ts.map

View File

@@ -0,0 +1,97 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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 ieee754 from './ieee754';
import * as util from '../util';
import { MappingError } from './types';
/**
* LogarithmMapping implements exponential mapping functions for scale > 0.
* For scales <= 0 the exponent mapping should be used.
*/
var LogarithmMapping = /** @class */ (function () {
function LogarithmMapping(scale) {
this._scale = scale;
this._scaleFactor = util.ldexp(Math.LOG2E, scale);
this._inverseFactor = util.ldexp(Math.LN2, -scale);
}
/**
* Maps positive floating point values to indexes corresponding to scale
* @param value
* @returns {number} index for provided value at the current scale
*/
LogarithmMapping.prototype.mapToIndex = function (value) {
if (value <= ieee754.MIN_VALUE) {
return this._minNormalLowerBoundaryIndex() - 1;
}
// exact power of two special case
if (ieee754.getSignificand(value) === 0) {
var exp = ieee754.getNormalBase2(value);
return (exp << this._scale) - 1;
}
// non-power of two cases. use Math.floor to round the scaled logarithm
var index = Math.floor(Math.log(value) * this._scaleFactor);
var maxIndex = this._maxNormalLowerBoundaryIndex();
if (index >= maxIndex) {
return maxIndex;
}
return index;
};
/**
* Returns the lower bucket boundary for the given index for scale
*
* @param index
* @returns {number}
*/
LogarithmMapping.prototype.lowerBoundary = function (index) {
var maxIndex = this._maxNormalLowerBoundaryIndex();
if (index >= maxIndex) {
if (index === maxIndex) {
return 2 * Math.exp((index - (1 << this._scale)) / this._scaleFactor);
}
throw new MappingError("overflow: " + index + " is > maximum lower boundary: " + maxIndex);
}
var minIndex = this._minNormalLowerBoundaryIndex();
if (index <= minIndex) {
if (index === minIndex) {
return ieee754.MIN_VALUE;
}
else if (index === minIndex - 1) {
return Math.exp((index + (1 << this._scale)) / this._scaleFactor) / 2;
}
throw new MappingError("overflow: " + index + " is < minimum lower boundary: " + minIndex);
}
return Math.exp(index * this._inverseFactor);
};
Object.defineProperty(LogarithmMapping.prototype, "scale", {
/**
* The scale used by this mapping
* @returns {number}
*/
get: function () {
return this._scale;
},
enumerable: false,
configurable: true
});
LogarithmMapping.prototype._minNormalLowerBoundaryIndex = function () {
return ieee754.MIN_NORMAL_EXPONENT << this._scale;
};
LogarithmMapping.prototype._maxNormalLowerBoundaryIndex = function () {
return ((ieee754.MAX_NORMAL_EXPONENT + 1) << this._scale) - 1;
};
return LogarithmMapping;
}());
export { LogarithmMapping };
//# sourceMappingURL=LogarithmMapping.js.map

View File

@@ -0,0 +1,10 @@
import { Mapping } from './types';
/**
* getMapping returns an appropriate mapping for the given scale. For scales -10
* to 0 the underlying type will be ExponentMapping. For scales 1 to 20 the
* underlying type will be LogarithmMapping.
* @param scale a number in the range [-10, 20]
* @returns {Mapping}
*/
export declare function getMapping(scale: number): Mapping;
//# sourceMappingURL=getMapping.d.ts.map

View File

@@ -0,0 +1,41 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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 { ExponentMapping } from './ExponentMapping';
import { LogarithmMapping } from './LogarithmMapping';
import { MappingError } from './types';
var MIN_SCALE = -10;
var MAX_SCALE = 20;
var PREBUILT_MAPPINGS = Array.from({ length: 31 }, function (_, i) {
if (i > 10) {
return new LogarithmMapping(i - 10);
}
return new ExponentMapping(i - 10);
});
/**
* getMapping returns an appropriate mapping for the given scale. For scales -10
* to 0 the underlying type will be ExponentMapping. For scales 1 to 20 the
* underlying type will be LogarithmMapping.
* @param scale a number in the range [-10, 20]
* @returns {Mapping}
*/
export function getMapping(scale) {
if (scale > MAX_SCALE || scale < MIN_SCALE) {
throw new MappingError("expected scale >= " + MIN_SCALE + " && <= " + MAX_SCALE + ", got: " + scale);
}
// mappings are offset by 10. scale -10 is at position 0 and scale 20 is at 30
return PREBUILT_MAPPINGS[scale + 10];
}
//# sourceMappingURL=getMapping.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"getMapping.js","sourceRoot":"","sources":["../../../../../src/aggregator/exponential-histogram/mapping/getMapping.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,YAAY,EAAW,MAAM,SAAS,CAAC;AAEhD,IAAM,SAAS,GAAG,CAAC,EAAE,CAAC;AACtB,IAAM,SAAS,GAAG,EAAE,CAAC;AACrB,IAAM,iBAAiB,GAAG,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,UAAC,CAAC,EAAE,CAAC;IACxD,IAAI,CAAC,GAAG,EAAE,EAAE;QACV,OAAO,IAAI,gBAAgB,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC;KACrC;IACD,OAAO,IAAI,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC;AACrC,CAAC,CAAC,CAAC;AAEH;;;;;;GAMG;AACH,MAAM,UAAU,UAAU,CAAC,KAAa;IACtC,IAAI,KAAK,GAAG,SAAS,IAAI,KAAK,GAAG,SAAS,EAAE;QAC1C,MAAM,IAAI,YAAY,CACpB,uBAAqB,SAAS,eAAU,SAAS,eAAU,KAAO,CACnE,CAAC;KACH;IACD,8EAA8E;IAC9E,OAAO,iBAAiB,CAAC,KAAK,GAAG,EAAE,CAAC,CAAC;AACvC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { ExponentMapping } from './ExponentMapping';\nimport { LogarithmMapping } from './LogarithmMapping';\nimport { MappingError, Mapping } from './types';\n\nconst MIN_SCALE = -10;\nconst MAX_SCALE = 20;\nconst PREBUILT_MAPPINGS = Array.from({ length: 31 }, (_, i) => {\n if (i > 10) {\n return new LogarithmMapping(i - 10);\n }\n return new ExponentMapping(i - 10);\n});\n\n/**\n * getMapping returns an appropriate mapping for the given scale. For scales -10\n * to 0 the underlying type will be ExponentMapping. For scales 1 to 20 the\n * underlying type will be LogarithmMapping.\n * @param scale a number in the range [-10, 20]\n * @returns {Mapping}\n */\nexport function getMapping(scale: number): Mapping {\n if (scale > MAX_SCALE || scale < MIN_SCALE) {\n throw new MappingError(\n `expected scale >= ${MIN_SCALE} && <= ${MAX_SCALE}, got: ${scale}`\n );\n }\n // mappings are offset by 10. scale -10 is at position 0 and scale 20 is at 30\n return PREBUILT_MAPPINGS[scale + 10];\n}\n"]}

View File

@@ -0,0 +1,41 @@
/**
* The functions and constants in this file allow us to interact
* with the internal representation of an IEEE 64-bit floating point
* number. We need to work with all 64-bits, thus, care needs to be
* taken when working with Javascript's bitwise operators (<<, >>, &,
* |, etc) as they truncate operands to 32-bits. In order to work around
* this we work with the 64-bits as two 32-bit halves, perform bitwise
* operations on them independently, and combine the results (if needed).
*/
export declare const SIGNIFICAND_WIDTH = 52;
/**
* MIN_NORMAL_EXPONENT is the minimum exponent of a normalized
* floating point: -1022.
*/
export declare const MIN_NORMAL_EXPONENT: number;
/**
* MAX_NORMAL_EXPONENT is the maximum exponent of a normalized
* floating point: 1023.
*/
export declare const MAX_NORMAL_EXPONENT = 1023;
/**
* MIN_VALUE is the smallest normal number
*/
export declare const MIN_VALUE: number;
/**
* getNormalBase2 extracts the normalized base-2 fractional exponent.
* This returns k for the equation f x 2**k where f is
* in the range [1, 2). Note that this function is not called for
* subnormal numbers.
* @param {number} value - the value to determine normalized base-2 fractional
* exponent for
* @returns {number} the normalized base-2 exponent
*/
export declare function getNormalBase2(value: number): number;
/**
* GetSignificand returns the 52 bit (unsigned) significand as a signed value.
* @param {number} value - the floating point number to extract the significand from
* @returns {number} The 52-bit significand
*/
export declare function getSignificand(value: number): number;
//# sourceMappingURL=ieee754.d.ts.map

View File

@@ -0,0 +1,89 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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.
*/
/**
* The functions and constants in this file allow us to interact
* with the internal representation of an IEEE 64-bit floating point
* number. We need to work with all 64-bits, thus, care needs to be
* taken when working with Javascript's bitwise operators (<<, >>, &,
* |, etc) as they truncate operands to 32-bits. In order to work around
* this we work with the 64-bits as two 32-bit halves, perform bitwise
* operations on them independently, and combine the results (if needed).
*/
export var SIGNIFICAND_WIDTH = 52;
/**
* EXPONENT_MASK is set to 1 for the hi 32-bits of an IEEE 754
* floating point exponent: 0x7ff00000.
*/
var EXPONENT_MASK = 0x7ff00000;
/**
* SIGNIFICAND_MASK is the mask for the significand portion of the hi 32-bits
* of an IEEE 754 double-precision floating-point value: 0xfffff
*/
var SIGNIFICAND_MASK = 0xfffff;
/**
* EXPONENT_BIAS is the exponent bias specified for encoding
* the IEEE 754 double-precision floating point exponent: 1023
*/
var EXPONENT_BIAS = 1023;
/**
* MIN_NORMAL_EXPONENT is the minimum exponent of a normalized
* floating point: -1022.
*/
export var MIN_NORMAL_EXPONENT = -EXPONENT_BIAS + 1;
/**
* MAX_NORMAL_EXPONENT is the maximum exponent of a normalized
* floating point: 1023.
*/
export var MAX_NORMAL_EXPONENT = EXPONENT_BIAS;
/**
* MIN_VALUE is the smallest normal number
*/
export var MIN_VALUE = Math.pow(2, -1022);
/**
* getNormalBase2 extracts the normalized base-2 fractional exponent.
* This returns k for the equation f x 2**k where f is
* in the range [1, 2). Note that this function is not called for
* subnormal numbers.
* @param {number} value - the value to determine normalized base-2 fractional
* exponent for
* @returns {number} the normalized base-2 exponent
*/
export function getNormalBase2(value) {
var dv = new DataView(new ArrayBuffer(8));
dv.setFloat64(0, value);
// access the raw 64-bit float as 32-bit uints
var hiBits = dv.getUint32(0);
var expBits = (hiBits & EXPONENT_MASK) >> 20;
return expBits - EXPONENT_BIAS;
}
/**
* GetSignificand returns the 52 bit (unsigned) significand as a signed value.
* @param {number} value - the floating point number to extract the significand from
* @returns {number} The 52-bit significand
*/
export function getSignificand(value) {
var dv = new DataView(new ArrayBuffer(8));
dv.setFloat64(0, value);
// access the raw 64-bit float as two 32-bit uints
var hiBits = dv.getUint32(0);
var loBits = dv.getUint32(4);
// extract the significand bits from the hi bits and left shift 32 places note:
// we can't use the native << operator as it will truncate the result to 32-bits
var significandHiBits = (hiBits & SIGNIFICAND_MASK) * Math.pow(2, 32);
// combine the hi and lo bits and return
return significandHiBits + loBits;
}
//# sourceMappingURL=ieee754.js.map

View File

@@ -0,0 +1,13 @@
export declare class MappingError extends Error {
}
/**
* The mapping interface is used by the exponential histogram to determine
* where to bucket values. The interface is implemented by ExponentMapping,
* used for scales [-10, 0] and LogarithmMapping, used for scales [1, 20].
*/
export interface Mapping {
mapToIndex(value: number): number;
lowerBoundary(index: number): number;
get scale(): number;
}
//# sourceMappingURL=types.d.ts.map

View File

@@ -0,0 +1,39 @@
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
/*
* Copyright The OpenTelemetry 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
*
* https://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.
*/
var MappingError = /** @class */ (function (_super) {
__extends(MappingError, _super);
function MappingError() {
return _super !== null && _super.apply(this, arguments) || this;
}
return MappingError;
}(Error));
export { MappingError };
//# sourceMappingURL=types.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/aggregator/exponential-histogram/mapping/types.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;GAcG;AACH;IAAkC,gCAAK;IAAvC;;IAAyC,CAAC;IAAD,mBAAC;AAAD,CAAC,AAA1C,CAAkC,KAAK,GAAG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport class MappingError extends Error {}\n\n/**\n * The mapping interface is used by the exponential histogram to determine\n * where to bucket values. The interface is implemented by ExponentMapping,\n * used for scales [-10, 0] and LogarithmMapping, used for scales [1, 20].\n */\nexport interface Mapping {\n mapToIndex(value: number): number;\n lowerBoundary(index: number): number;\n get scale(): number;\n}\n"]}

View File

@@ -0,0 +1,23 @@
/**
* Note: other languages provide this as a built in function. This is
* a naive, but functionally correct implementation. This is used sparingly,
* when creating a new mapping in a running application.
*
* ldexp returns frac × 2**exp. With the following special cases:
* ldexp(±0, exp) = ±0
* ldexp(±Inf, exp) = ±Inf
* ldexp(NaN, exp) = NaN
* @param frac
* @param exp
* @returns {number}
*/
export declare function ldexp(frac: number, exp: number): number;
/**
* Computes the next power of two that is greater than or equal to v.
* This implementation more efficient than, but functionally equivalent
* to Math.pow(2, Math.ceil(Math.log(x)/Math.log(2))).
* @param v
* @returns {number}
*/
export declare function nextGreaterSquare(v: number): number;
//# sourceMappingURL=util.d.ts.map

View File

@@ -0,0 +1,58 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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.
*/
/**
* Note: other languages provide this as a built in function. This is
* a naive, but functionally correct implementation. This is used sparingly,
* when creating a new mapping in a running application.
*
* ldexp returns frac × 2**exp. With the following special cases:
* ldexp(±0, exp) = ±0
* ldexp(±Inf, exp) = ±Inf
* ldexp(NaN, exp) = NaN
* @param frac
* @param exp
* @returns {number}
*/
export function ldexp(frac, exp) {
if (frac === 0 ||
frac === Number.POSITIVE_INFINITY ||
frac === Number.NEGATIVE_INFINITY ||
Number.isNaN(frac)) {
return frac;
}
return frac * Math.pow(2, exp);
}
/**
* Computes the next power of two that is greater than or equal to v.
* This implementation more efficient than, but functionally equivalent
* to Math.pow(2, Math.ceil(Math.log(x)/Math.log(2))).
* @param v
* @returns {number}
*/
export function nextGreaterSquare(v) {
// The following expression computes the least power-of-two
// that is >= v. There are a number of tricky ways to
// do this, see https://stackoverflow.com/questions/466204/rounding-up-to-next-power-of-2
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
//# sourceMappingURL=util.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"util.js","sourceRoot":"","sources":["../../../../src/aggregator/exponential-histogram/util.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,KAAK,CAAC,IAAY,EAAE,GAAW;IAC7C,IACE,IAAI,KAAK,CAAC;QACV,IAAI,KAAK,MAAM,CAAC,iBAAiB;QACjC,IAAI,KAAK,MAAM,CAAC,iBAAiB;QACjC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,EAClB;QACA,OAAO,IAAI,CAAC;KACb;IACD,OAAO,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;AACjC,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAAC,CAAS;IACzC,2DAA2D;IAC3D,sDAAsD;IACtD,yFAAyF;IACzF,CAAC,EAAE,CAAC;IACJ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACZ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACZ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACZ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACZ,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;IACb,CAAC,EAAE,CAAC;IACJ,OAAO,CAAC,CAAC;AACX,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Note: other languages provide this as a built in function. This is\n * a naive, but functionally correct implementation. This is used sparingly,\n * when creating a new mapping in a running application.\n *\n * ldexp returns frac × 2**exp. With the following special cases:\n * ldexp(±0, exp) = ±0\n * ldexp(±Inf, exp) = ±Inf\n * ldexp(NaN, exp) = NaN\n * @param frac\n * @param exp\n * @returns {number}\n */\nexport function ldexp(frac: number, exp: number): number {\n if (\n frac === 0 ||\n frac === Number.POSITIVE_INFINITY ||\n frac === Number.NEGATIVE_INFINITY ||\n Number.isNaN(frac)\n ) {\n return frac;\n }\n return frac * Math.pow(2, exp);\n}\n\n/**\n * Computes the next power of two that is greater than or equal to v.\n * This implementation more efficient than, but functionally equivalent\n * to Math.pow(2, Math.ceil(Math.log(x)/Math.log(2))).\n * @param v\n * @returns {number}\n */\nexport function nextGreaterSquare(v: number): number {\n // The following expression computes the least power-of-two\n // that is >= v. There are a number of tricky ways to\n // do this, see https://stackoverflow.com/questions/466204/rounding-up-to-next-power-of-2\n v--;\n v |= v >> 1;\n v |= v >> 2;\n v |= v >> 4;\n v |= v >> 8;\n v |= v >> 16;\n v++;\n return v;\n}\n"]}

View File

@@ -0,0 +1,7 @@
export { DropAggregator } from './Drop';
export { HistogramAccumulation, HistogramAggregator } from './Histogram';
export { ExponentialHistogramAccumulation, ExponentialHistogramAggregator, } from './ExponentialHistogram';
export { LastValueAccumulation, LastValueAggregator } from './LastValue';
export { SumAccumulation, SumAggregator } from './Sum';
export { Aggregator } from './types';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,21 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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 { DropAggregator } from './Drop';
export { HistogramAccumulation, HistogramAggregator } from './Histogram';
export { ExponentialHistogramAccumulation, ExponentialHistogramAggregator, } from './ExponentialHistogram';
export { LastValueAccumulation, LastValueAggregator } from './LastValue';
export { SumAccumulation, SumAggregator } from './Sum';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/aggregator/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,QAAQ,CAAC;AACxC,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AACzE,OAAO,EACL,gCAAgC,EAChC,8BAA8B,GAC/B,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AACzE,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { DropAggregator } from './Drop';\nexport { HistogramAccumulation, HistogramAggregator } from './Histogram';\nexport {\n ExponentialHistogramAccumulation,\n ExponentialHistogramAggregator,\n} from './ExponentialHistogram';\nexport { LastValueAccumulation, LastValueAggregator } from './LastValue';\nexport { SumAccumulation, SumAggregator } from './Sum';\nexport { Aggregator } from './types';\n"]}

View File

@@ -0,0 +1,110 @@
import { HrTime, Attributes } from '@opentelemetry/api';
import { AggregationTemporality } from '../export/AggregationTemporality';
import { MetricData, MetricDescriptor } from '../export/MetricData';
import { Maybe } from '../utils';
/** The kind of aggregator. */
export declare enum AggregatorKind {
DROP = 0,
SUM = 1,
LAST_VALUE = 2,
HISTOGRAM = 3,
EXPONENTIAL_HISTOGRAM = 4
}
/** DataPoint value type for SumAggregation. */
export declare type Sum = number;
/** DataPoint value type for LastValueAggregation. */
export declare type LastValue = number;
/** DataPoint value type for HistogramAggregation. */
export interface Histogram {
/**
* Buckets are implemented using two different arrays:
* - boundaries: contains every finite bucket boundary, which are inclusive upper bounds
* - counts: contains event counts for each bucket
*
* Note that we'll always have n+1 buckets, where n is the number of boundaries.
* This is because we need to count events that are higher than the upper boundary.
*
* Example: if we measure the values: [5, 30, 5, 40, 5, 15, 15, 15, 25]
* with the boundaries [ 10, 20, 30 ], we will have the following state:
*
* buckets: {
* boundaries: [10, 20, 30],
* counts: [3, 3, 2, 1],
* }
*/
buckets: {
boundaries: number[];
counts: number[];
};
sum?: number;
count: number;
min?: number;
max?: number;
}
/** DataPoint value type for ExponentialHistogramAggregation. */
export interface ExponentialHistogram {
count: number;
sum?: number;
scale: number;
zeroCount: number;
positive: {
offset: number;
bucketCounts: number[];
};
negative: {
offset: number;
bucketCounts: number[];
};
min?: number;
max?: number;
}
/**
* An Aggregator accumulation state.
*/
export interface Accumulation {
setStartTime(startTime: HrTime): void;
record(value: number): void;
}
export declare type AccumulationRecord<T> = [Attributes, T];
/**
* Base interface for aggregators. Aggregators are responsible for holding
* aggregated values and taking a snapshot of these values upon export.
*/
export interface Aggregator<T> {
/** The kind of the aggregator. */
kind: AggregatorKind;
/**
* Create a clean state of accumulation.
*/
createAccumulation(startTime: HrTime): T;
/**
* Returns the result of the merge of the given accumulations.
*
* This should always assume that the accumulations do not overlap and merge together for a new
* cumulative report.
*
* @param previous the previously captured accumulation
* @param delta the newly captured (delta) accumulation
* @returns the result of the merge of the given accumulations
*/
merge(previous: T, delta: T): T;
/**
* Returns a new DELTA aggregation by comparing two cumulative measurements.
*
* @param previous the previously captured accumulation
* @param current the newly captured (cumulative) accumulation
* @returns The resulting delta accumulation
*/
diff(previous: T, current: T): T;
/**
* Returns the {@link MetricData} that this {@link Aggregator} will produce.
*
* @param descriptor the metric descriptor.
* @param aggregationTemporality the temporality of the resulting {@link MetricData}
* @param accumulationByAttributes the array of attributes and accumulation pairs.
* @param endTime the end time of the metric data.
* @return the {@link MetricData} that this {@link Aggregator} will produce.
*/
toMetricData(descriptor: MetricDescriptor, aggregationTemporality: AggregationTemporality, accumulationByAttributes: AccumulationRecord<T>[], endTime: HrTime): Maybe<MetricData>;
}
//# sourceMappingURL=types.d.ts.map

View File

@@ -0,0 +1,25 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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.
*/
/** The kind of aggregator. */
export var AggregatorKind;
(function (AggregatorKind) {
AggregatorKind[AggregatorKind["DROP"] = 0] = "DROP";
AggregatorKind[AggregatorKind["SUM"] = 1] = "SUM";
AggregatorKind[AggregatorKind["LAST_VALUE"] = 2] = "LAST_VALUE";
AggregatorKind[AggregatorKind["HISTOGRAM"] = 3] = "HISTOGRAM";
AggregatorKind[AggregatorKind["EXPONENTIAL_HISTOGRAM"] = 4] = "EXPONENTIAL_HISTOGRAM";
})(AggregatorKind || (AggregatorKind = {}));
//# sourceMappingURL=types.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/aggregator/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAOH,8BAA8B;AAC9B,MAAM,CAAN,IAAY,cAMX;AAND,WAAY,cAAc;IACxB,mDAAI,CAAA;IACJ,iDAAG,CAAA;IACH,+DAAU,CAAA;IACV,6DAAS,CAAA;IACT,qFAAqB,CAAA;AACvB,CAAC,EANW,cAAc,KAAd,cAAc,QAMzB","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { HrTime, Attributes } from '@opentelemetry/api';\nimport { AggregationTemporality } from '../export/AggregationTemporality';\nimport { MetricData, MetricDescriptor } from '../export/MetricData';\nimport { Maybe } from '../utils';\n\n/** The kind of aggregator. */\nexport enum AggregatorKind {\n DROP,\n SUM,\n LAST_VALUE,\n HISTOGRAM,\n EXPONENTIAL_HISTOGRAM,\n}\n\n/** DataPoint value type for SumAggregation. */\nexport type Sum = number;\n\n/** DataPoint value type for LastValueAggregation. */\nexport type LastValue = number;\n\n/** DataPoint value type for HistogramAggregation. */\nexport interface Histogram {\n /**\n * Buckets are implemented using two different arrays:\n * - boundaries: contains every finite bucket boundary, which are inclusive upper bounds\n * - counts: contains event counts for each bucket\n *\n * Note that we'll always have n+1 buckets, where n is the number of boundaries.\n * This is because we need to count events that are higher than the upper boundary.\n *\n * Example: if we measure the values: [5, 30, 5, 40, 5, 15, 15, 15, 25]\n * with the boundaries [ 10, 20, 30 ], we will have the following state:\n *\n * buckets: {\n *\tboundaries: [10, 20, 30],\n *\tcounts: [3, 3, 2, 1],\n * }\n */\n buckets: {\n boundaries: number[];\n counts: number[];\n };\n sum?: number;\n count: number;\n min?: number;\n max?: number;\n}\n\n/** DataPoint value type for ExponentialHistogramAggregation. */\nexport interface ExponentialHistogram {\n count: number;\n sum?: number;\n scale: number;\n zeroCount: number;\n positive: {\n offset: number;\n bucketCounts: number[];\n };\n negative: {\n offset: number;\n bucketCounts: number[];\n };\n min?: number;\n max?: number;\n}\n\n/**\n * An Aggregator accumulation state.\n */\nexport interface Accumulation {\n setStartTime(startTime: HrTime): void;\n record(value: number): void;\n}\n\nexport type AccumulationRecord<T> = [Attributes, T];\n\n/**\n * Base interface for aggregators. Aggregators are responsible for holding\n * aggregated values and taking a snapshot of these values upon export.\n */\nexport interface Aggregator<T> {\n /** The kind of the aggregator. */\n kind: AggregatorKind;\n\n /**\n * Create a clean state of accumulation.\n */\n createAccumulation(startTime: HrTime): T;\n\n /**\n * Returns the result of the merge of the given accumulations.\n *\n * This should always assume that the accumulations do not overlap and merge together for a new\n * cumulative report.\n *\n * @param previous the previously captured accumulation\n * @param delta the newly captured (delta) accumulation\n * @returns the result of the merge of the given accumulations\n */\n merge(previous: T, delta: T): T;\n\n /**\n * Returns a new DELTA aggregation by comparing two cumulative measurements.\n *\n * @param previous the previously captured accumulation\n * @param current the newly captured (cumulative) accumulation\n * @returns The resulting delta accumulation\n */\n diff(previous: T, current: T): T;\n\n /**\n * Returns the {@link MetricData} that this {@link Aggregator} will produce.\n *\n * @param descriptor the metric descriptor.\n * @param aggregationTemporality the temporality of the resulting {@link MetricData}\n * @param accumulationByAttributes the array of attributes and accumulation pairs.\n * @param endTime the end time of the metric data.\n * @return the {@link MetricData} that this {@link Aggregator} will produce.\n */\n toMetricData(\n descriptor: MetricDescriptor,\n aggregationTemporality: AggregationTemporality,\n accumulationByAttributes: AccumulationRecord<T>[],\n endTime: HrTime\n ): Maybe<MetricData>;\n}\n"]}

View File

@@ -0,0 +1,14 @@
import { Context, HrTime, Attributes } from '@opentelemetry/api';
import { FixedSizeExemplarReservoirBase } from './ExemplarReservoir';
/**
* AlignedHistogramBucketExemplarReservoir takes the same boundaries
* configuration of a Histogram. This algorithm keeps the last seen measurement
* that falls within a histogram bucket.
*/
export declare class AlignedHistogramBucketExemplarReservoir extends FixedSizeExemplarReservoirBase {
private _boundaries;
constructor(boundaries: number[]);
private _findBucketIndex;
offer(value: number, timestamp: HrTime, attributes: Attributes, ctx: Context): void;
}
//# sourceMappingURL=AlignedHistogramBucketExemplarReservoir.d.ts.map

View File

@@ -0,0 +1,59 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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.
*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
import { FixedSizeExemplarReservoirBase } from './ExemplarReservoir';
/**
* AlignedHistogramBucketExemplarReservoir takes the same boundaries
* configuration of a Histogram. This algorithm keeps the last seen measurement
* that falls within a histogram bucket.
*/
var AlignedHistogramBucketExemplarReservoir = /** @class */ (function (_super) {
__extends(AlignedHistogramBucketExemplarReservoir, _super);
function AlignedHistogramBucketExemplarReservoir(boundaries) {
var _this = _super.call(this, boundaries.length + 1) || this;
_this._boundaries = boundaries;
return _this;
}
AlignedHistogramBucketExemplarReservoir.prototype._findBucketIndex = function (value, _timestamp, _attributes, _ctx) {
for (var i = 0; i < this._boundaries.length; i++) {
if (value <= this._boundaries[i]) {
return i;
}
}
return this._boundaries.length;
};
AlignedHistogramBucketExemplarReservoir.prototype.offer = function (value, timestamp, attributes, ctx) {
var index = this._findBucketIndex(value, timestamp, attributes, ctx);
this._reservoirStorage[index].offer(value, timestamp, attributes, ctx);
};
return AlignedHistogramBucketExemplarReservoir;
}(FixedSizeExemplarReservoirBase));
export { AlignedHistogramBucketExemplarReservoir };
//# sourceMappingURL=AlignedHistogramBucketExemplarReservoir.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"AlignedHistogramBucketExemplarReservoir.js","sourceRoot":"","sources":["../../../src/exemplar/AlignedHistogramBucketExemplarReservoir.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;AAGH,OAAO,EAAE,8BAA8B,EAAE,MAAM,qBAAqB,CAAC;AAErE;;;;GAIG;AACH;IAA6D,2DAA8B;IAEzF,iDAAY,UAAoB;QAAhC,YACE,kBAAM,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC,SAE7B;QADC,KAAI,CAAC,WAAW,GAAG,UAAU,CAAC;;IAChC,CAAC;IAEO,kEAAgB,GAAxB,UACE,KAAa,EACb,UAAkB,EAClB,WAAuB,EACvB,IAAa;QAEb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YAChD,IAAI,KAAK,IAAI,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE;gBAChC,OAAO,CAAC,CAAC;aACV;SACF;QACD,OAAO,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC;IACjC,CAAC;IAED,uDAAK,GAAL,UACE,KAAa,EACb,SAAiB,EACjB,UAAsB,EACtB,GAAY;QAEZ,IAAM,KAAK,GAAG,IAAI,CAAC,gBAAgB,CAAC,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,GAAG,CAAC,CAAC;QACvE,IAAI,CAAC,iBAAiB,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,GAAG,CAAC,CAAC;IACzE,CAAC;IACH,8CAAC;AAAD,CAAC,AA9BD,CAA6D,8BAA8B,GA8B1F","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, HrTime, Attributes } from '@opentelemetry/api';\nimport { FixedSizeExemplarReservoirBase } from './ExemplarReservoir';\n\n/**\n * AlignedHistogramBucketExemplarReservoir takes the same boundaries\n * configuration of a Histogram. This algorithm keeps the last seen measurement\n * that falls within a histogram bucket.\n */\nexport class AlignedHistogramBucketExemplarReservoir extends FixedSizeExemplarReservoirBase {\n private _boundaries: number[];\n constructor(boundaries: number[]) {\n super(boundaries.length + 1);\n this._boundaries = boundaries;\n }\n\n private _findBucketIndex(\n value: number,\n _timestamp: HrTime,\n _attributes: Attributes,\n _ctx: Context\n ) {\n for (let i = 0; i < this._boundaries.length; i++) {\n if (value <= this._boundaries[i]) {\n return i;\n }\n }\n return this._boundaries.length;\n }\n\n offer(\n value: number,\n timestamp: HrTime,\n attributes: Attributes,\n ctx: Context\n ): void {\n const index = this._findBucketIndex(value, timestamp, attributes, ctx);\n this._reservoirStorage[index].offer(value, timestamp, attributes, ctx);\n }\n}\n"]}

View File

@@ -0,0 +1,6 @@
import { Context, HrTime, Attributes } from '@opentelemetry/api';
import { ExemplarFilter } from './ExemplarFilter';
export declare class AlwaysSampleExemplarFilter implements ExemplarFilter {
shouldSample(_value: number, _timestamp: HrTime, _attributes: Attributes, _ctx: Context): boolean;
}
//# sourceMappingURL=AlwaysSampleExemplarFilter.d.ts.map

View File

@@ -0,0 +1,25 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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.
*/
var AlwaysSampleExemplarFilter = /** @class */ (function () {
function AlwaysSampleExemplarFilter() {
}
AlwaysSampleExemplarFilter.prototype.shouldSample = function (_value, _timestamp, _attributes, _ctx) {
return true;
};
return AlwaysSampleExemplarFilter;
}());
export { AlwaysSampleExemplarFilter };
//# sourceMappingURL=AlwaysSampleExemplarFilter.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"AlwaysSampleExemplarFilter.js","sourceRoot":"","sources":["../../../src/exemplar/AlwaysSampleExemplarFilter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAKH;IAAA;IASA,CAAC;IARC,iDAAY,GAAZ,UACE,MAAc,EACd,UAAkB,EAClB,WAAuB,EACvB,IAAa;QAEb,OAAO,IAAI,CAAC;IACd,CAAC;IACH,iCAAC;AAAD,CAAC,AATD,IASC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, HrTime, Attributes } from '@opentelemetry/api';\nimport { ExemplarFilter } from './ExemplarFilter';\n\nexport class AlwaysSampleExemplarFilter implements ExemplarFilter {\n shouldSample(\n _value: number,\n _timestamp: HrTime,\n _attributes: Attributes,\n _ctx: Context\n ): boolean {\n return true;\n }\n}\n"]}

View File

@@ -0,0 +1,15 @@
import { HrTime, Attributes } from '@opentelemetry/api';
/**
* A representation of an exemplar, which is a sample input measurement.
* Exemplars also hold information about the environment when the measurement
* was recorded, for example the span and trace ID of the active span when the
* exemplar was recorded.
*/
export declare type Exemplar = {
filteredAttributes: Attributes;
value: number;
timestamp: HrTime;
spanId?: string;
traceId?: string;
};
//# sourceMappingURL=Exemplar.d.ts.map

View File

@@ -0,0 +1,17 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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 {};
//# sourceMappingURL=Exemplar.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"Exemplar.js","sourceRoot":"","sources":["../../../src/exemplar/Exemplar.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { HrTime, Attributes } from '@opentelemetry/api';\n\n/**\n * A representation of an exemplar, which is a sample input measurement.\n * Exemplars also hold information about the environment when the measurement\n * was recorded, for example the span and trace ID of the active span when the\n * exemplar was recorded.\n */\nexport type Exemplar = {\n // The set of key/value pairs that were filtered out by the aggregator, but\n // recorded alongside the original measurement. Only key/value pairs that were\n // filtered out by the aggregator should be included\n filteredAttributes: Attributes;\n\n // The value of the measurement that was recorded.\n value: number;\n\n // timestamp is the exact time when this exemplar was recorded\n timestamp: HrTime;\n\n // (Optional) Span ID of the exemplar trace.\n // span_id may be missing if the measurement is not recorded inside a trace\n // or if the trace is not sampled.\n spanId?: string;\n\n // (Optional) Trace ID of the exemplar trace.\n // trace_id may be missing if the measurement is not recorded inside a trace\n // or if the trace is not sampled.\n traceId?: string;\n};\n"]}

View File

@@ -0,0 +1,18 @@
import { Context, HrTime, Attributes } from '@opentelemetry/api';
/**
* This interface represents a ExemplarFilter. Exemplar filters are
* used to filter measurements before attempting to store them in a
* reservoir.
*/
export interface ExemplarFilter {
/**
* Returns whether or not a reservoir should attempt to filter a measurement.
*
* @param value The value of the measurement
* @param timestamp A timestamp that best represents when the measurement was taken
* @param attributes The complete set of Attributes of the measurement
* @param ctx The Context of the measurement
*/
shouldSample(value: number, timestamp: HrTime, attributes: Attributes, ctx: Context): boolean;
}
//# sourceMappingURL=ExemplarFilter.d.ts.map

View File

@@ -0,0 +1,17 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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 {};
//# sourceMappingURL=ExemplarFilter.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ExemplarFilter.js","sourceRoot":"","sources":["../../../src/exemplar/ExemplarFilter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, HrTime, Attributes } from '@opentelemetry/api';\n\n/**\n * This interface represents a ExemplarFilter. Exemplar filters are\n * used to filter measurements before attempting to store them in a\n * reservoir.\n */\nexport interface ExemplarFilter {\n /**\n * Returns whether or not a reservoir should attempt to filter a measurement.\n *\n * @param value The value of the measurement\n * @param timestamp A timestamp that best represents when the measurement was taken\n * @param attributes The complete set of Attributes of the measurement\n * @param ctx The Context of the measurement\n */\n shouldSample(\n value: number,\n timestamp: HrTime,\n attributes: Attributes,\n ctx: Context\n ): boolean;\n}\n"]}

View File

@@ -0,0 +1,43 @@
import { Context, HrTime, Attributes } from '@opentelemetry/api';
import { Exemplar } from './Exemplar';
/**
* An interface for an exemplar reservoir of samples.
*/
export interface ExemplarReservoir {
/** Offers a measurement to be sampled. */
offer(value: number, timestamp: HrTime, attributes: Attributes, ctx: Context): void;
/**
* Returns accumulated Exemplars and also resets the reservoir
* for the next sampling period
*
* @param pointAttributes The attributes associated with metric point.
*
* @returns a list of {@link Exemplar}s. Returned exemplars contain the attributes that were filtered out by the
* aggregator, but recorded alongside the original measurement.
*/
collect(pointAttributes: Attributes): Exemplar[];
}
declare class ExemplarBucket {
private value;
private attributes;
private timestamp;
private spanId?;
private traceId?;
private _offered;
offer(value: number, timestamp: HrTime, attributes: Attributes, ctx: Context): void;
collect(pointAttributes: Attributes): Exemplar | null;
}
export declare abstract class FixedSizeExemplarReservoirBase implements ExemplarReservoir {
protected _reservoirStorage: ExemplarBucket[];
protected _size: number;
constructor(size: number);
abstract offer(value: number, timestamp: HrTime, attributes: Attributes, ctx: Context): void;
maxSize(): number;
/**
* Resets the reservoir
*/
protected reset(): void;
collect(pointAttributes: Attributes): Exemplar[];
}
export {};
//# sourceMappingURL=ExemplarReservoir.d.ts.map

View File

@@ -0,0 +1,91 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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 { isSpanContextValid, trace, } from '@opentelemetry/api';
var ExemplarBucket = /** @class */ (function () {
function ExemplarBucket() {
this.value = 0;
this.attributes = {};
this.timestamp = [0, 0];
this._offered = false;
}
ExemplarBucket.prototype.offer = function (value, timestamp, attributes, ctx) {
this.value = value;
this.timestamp = timestamp;
this.attributes = attributes;
var spanContext = trace.getSpanContext(ctx);
if (spanContext && isSpanContextValid(spanContext)) {
this.spanId = spanContext.spanId;
this.traceId = spanContext.traceId;
}
this._offered = true;
};
ExemplarBucket.prototype.collect = function (pointAttributes) {
if (!this._offered)
return null;
var currentAttributes = this.attributes;
// filter attributes
Object.keys(pointAttributes).forEach(function (key) {
if (pointAttributes[key] === currentAttributes[key]) {
delete currentAttributes[key];
}
});
var retVal = {
filteredAttributes: currentAttributes,
value: this.value,
timestamp: this.timestamp,
spanId: this.spanId,
traceId: this.traceId,
};
this.attributes = {};
this.value = 0;
this.timestamp = [0, 0];
this.spanId = undefined;
this.traceId = undefined;
this._offered = false;
return retVal;
};
return ExemplarBucket;
}());
var FixedSizeExemplarReservoirBase = /** @class */ (function () {
function FixedSizeExemplarReservoirBase(size) {
this._size = size;
this._reservoirStorage = new Array(size);
for (var i = 0; i < this._size; i++) {
this._reservoirStorage[i] = new ExemplarBucket();
}
}
FixedSizeExemplarReservoirBase.prototype.maxSize = function () {
return this._size;
};
/**
* Resets the reservoir
*/
FixedSizeExemplarReservoirBase.prototype.reset = function () { };
FixedSizeExemplarReservoirBase.prototype.collect = function (pointAttributes) {
var exemplars = [];
this._reservoirStorage.forEach(function (storageItem) {
var res = storageItem.collect(pointAttributes);
if (res !== null) {
exemplars.push(res);
}
});
this.reset();
return exemplars;
};
return FixedSizeExemplarReservoirBase;
}());
export { FixedSizeExemplarReservoirBase };
//# sourceMappingURL=ExemplarReservoir.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,6 @@
import { Context, HrTime, Attributes } from '@opentelemetry/api';
import { ExemplarFilter } from './ExemplarFilter';
export declare class NeverSampleExemplarFilter implements ExemplarFilter {
shouldSample(_value: number, _timestamp: HrTime, _attributes: Attributes, _ctx: Context): boolean;
}
//# sourceMappingURL=NeverSampleExemplarFilter.d.ts.map

View File

@@ -0,0 +1,25 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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.
*/
var NeverSampleExemplarFilter = /** @class */ (function () {
function NeverSampleExemplarFilter() {
}
NeverSampleExemplarFilter.prototype.shouldSample = function (_value, _timestamp, _attributes, _ctx) {
return false;
};
return NeverSampleExemplarFilter;
}());
export { NeverSampleExemplarFilter };
//# sourceMappingURL=NeverSampleExemplarFilter.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"NeverSampleExemplarFilter.js","sourceRoot":"","sources":["../../../src/exemplar/NeverSampleExemplarFilter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAKH;IAAA;IASA,CAAC;IARC,gDAAY,GAAZ,UACE,MAAc,EACd,UAAkB,EAClB,WAAuB,EACvB,IAAa;QAEb,OAAO,KAAK,CAAC;IACf,CAAC;IACH,gCAAC;AAAD,CAAC,AATD,IASC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, HrTime, Attributes } from '@opentelemetry/api';\nimport { ExemplarFilter } from './ExemplarFilter';\n\nexport class NeverSampleExemplarFilter implements ExemplarFilter {\n shouldSample(\n _value: number,\n _timestamp: HrTime,\n _attributes: Attributes,\n _ctx: Context\n ): boolean {\n return false;\n }\n}\n"]}

View File

@@ -0,0 +1,16 @@
import { Context, HrTime, Attributes } from '@opentelemetry/api';
import { FixedSizeExemplarReservoirBase } from './ExemplarReservoir';
/**
* Fixed size reservoir that uses equivalent of naive reservoir sampling
* algorithm to accept measurements.
*
*/
export declare class SimpleFixedSizeExemplarReservoir extends FixedSizeExemplarReservoirBase {
private _numMeasurementsSeen;
constructor(size: number);
private getRandomInt;
private _findBucketIndex;
offer(value: number, timestamp: HrTime, attributes: Attributes, ctx: Context): void;
reset(): void;
}
//# sourceMappingURL=SimpleFixedSizeExemplarReservoir.d.ts.map

View File

@@ -0,0 +1,66 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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.
*/
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
import { FixedSizeExemplarReservoirBase } from './ExemplarReservoir';
/**
* Fixed size reservoir that uses equivalent of naive reservoir sampling
* algorithm to accept measurements.
*
*/
var SimpleFixedSizeExemplarReservoir = /** @class */ (function (_super) {
__extends(SimpleFixedSizeExemplarReservoir, _super);
function SimpleFixedSizeExemplarReservoir(size) {
var _this = _super.call(this, size) || this;
_this._numMeasurementsSeen = 0;
return _this;
}
SimpleFixedSizeExemplarReservoir.prototype.getRandomInt = function (min, max) {
//[min, max)
return Math.floor(Math.random() * (max - min) + min);
};
SimpleFixedSizeExemplarReservoir.prototype._findBucketIndex = function (_value, _timestamp, _attributes, _ctx) {
if (this._numMeasurementsSeen < this._size)
return this._numMeasurementsSeen++;
var index = this.getRandomInt(0, ++this._numMeasurementsSeen);
return index < this._size ? index : -1;
};
SimpleFixedSizeExemplarReservoir.prototype.offer = function (value, timestamp, attributes, ctx) {
var index = this._findBucketIndex(value, timestamp, attributes, ctx);
if (index !== -1) {
this._reservoirStorage[index].offer(value, timestamp, attributes, ctx);
}
};
SimpleFixedSizeExemplarReservoir.prototype.reset = function () {
this._numMeasurementsSeen = 0;
};
return SimpleFixedSizeExemplarReservoir;
}(FixedSizeExemplarReservoirBase));
export { SimpleFixedSizeExemplarReservoir };
//# sourceMappingURL=SimpleFixedSizeExemplarReservoir.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"SimpleFixedSizeExemplarReservoir.js","sourceRoot":"","sources":["../../../src/exemplar/SimpleFixedSizeExemplarReservoir.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;AAGH,OAAO,EAAE,8BAA8B,EAAE,MAAM,qBAAqB,CAAC;AAErE;;;;GAIG;AACH;IAAsD,oDAA8B;IAElF,0CAAY,IAAY;QAAxB,YACE,kBAAM,IAAI,CAAC,SAEZ;QADC,KAAI,CAAC,oBAAoB,GAAG,CAAC,CAAC;;IAChC,CAAC;IAEO,uDAAY,GAApB,UAAqB,GAAW,EAAE,GAAW;QAC3C,YAAY;QACZ,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,GAAG,GAAG,CAAC,GAAG,GAAG,CAAC,CAAC;IACvD,CAAC;IAEO,2DAAgB,GAAxB,UACE,MAAc,EACd,UAAkB,EAClB,WAAuB,EACvB,IAAa;QAEb,IAAI,IAAI,CAAC,oBAAoB,GAAG,IAAI,CAAC,KAAK;YACxC,OAAO,IAAI,CAAC,oBAAoB,EAAE,CAAC;QACrC,IAAM,KAAK,GAAG,IAAI,CAAC,YAAY,CAAC,CAAC,EAAE,EAAE,IAAI,CAAC,oBAAoB,CAAC,CAAC;QAChE,OAAO,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACzC,CAAC;IAED,gDAAK,GAAL,UACE,KAAa,EACb,SAAiB,EACjB,UAAsB,EACtB,GAAY;QAEZ,IAAM,KAAK,GAAG,IAAI,CAAC,gBAAgB,CAAC,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,GAAG,CAAC,CAAC;QACvE,IAAI,KAAK,KAAK,CAAC,CAAC,EAAE;YAChB,IAAI,CAAC,iBAAiB,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,KAAK,EAAE,SAAS,EAAE,UAAU,EAAE,GAAG,CAAC,CAAC;SACxE;IACH,CAAC;IAEQ,gDAAK,GAAd;QACE,IAAI,CAAC,oBAAoB,GAAG,CAAC,CAAC;IAChC,CAAC;IACH,uCAAC;AAAD,CAAC,AAvCD,CAAsD,8BAA8B,GAuCnF","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context, HrTime, Attributes } from '@opentelemetry/api';\nimport { FixedSizeExemplarReservoirBase } from './ExemplarReservoir';\n\n/**\n * Fixed size reservoir that uses equivalent of naive reservoir sampling\n * algorithm to accept measurements.\n *\n */\nexport class SimpleFixedSizeExemplarReservoir extends FixedSizeExemplarReservoirBase {\n private _numMeasurementsSeen: number;\n constructor(size: number) {\n super(size);\n this._numMeasurementsSeen = 0;\n }\n\n private getRandomInt(min: number, max: number) {\n //[min, max)\n return Math.floor(Math.random() * (max - min) + min);\n }\n\n private _findBucketIndex(\n _value: number,\n _timestamp: HrTime,\n _attributes: Attributes,\n _ctx: Context\n ) {\n if (this._numMeasurementsSeen < this._size)\n return this._numMeasurementsSeen++;\n const index = this.getRandomInt(0, ++this._numMeasurementsSeen);\n return index < this._size ? index : -1;\n }\n\n offer(\n value: number,\n timestamp: HrTime,\n attributes: Attributes,\n ctx: Context\n ): void {\n const index = this._findBucketIndex(value, timestamp, attributes, ctx);\n if (index !== -1) {\n this._reservoirStorage[index].offer(value, timestamp, attributes, ctx);\n }\n }\n\n override reset() {\n this._numMeasurementsSeen = 0;\n }\n}\n"]}

View File

@@ -0,0 +1,6 @@
import { Context, HrTime, Attributes } from '@opentelemetry/api';
import { ExemplarFilter } from './ExemplarFilter';
export declare class WithTraceExemplarFilter implements ExemplarFilter {
shouldSample(value: number, timestamp: HrTime, attributes: Attributes, ctx: Context): boolean;
}
//# sourceMappingURL=WithTraceExemplarFilter.d.ts.map

View File

@@ -0,0 +1,29 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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 { isSpanContextValid, trace, TraceFlags, } from '@opentelemetry/api';
var WithTraceExemplarFilter = /** @class */ (function () {
function WithTraceExemplarFilter() {
}
WithTraceExemplarFilter.prototype.shouldSample = function (value, timestamp, attributes, ctx) {
var spanContext = trace.getSpanContext(ctx);
if (!spanContext || !isSpanContextValid(spanContext))
return false;
return spanContext.traceFlags & TraceFlags.SAMPLED ? true : false;
};
return WithTraceExemplarFilter;
}());
export { WithTraceExemplarFilter };
//# sourceMappingURL=WithTraceExemplarFilter.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"WithTraceExemplarFilter.js","sourceRoot":"","sources":["../../../src/exemplar/WithTraceExemplarFilter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAGL,kBAAkB,EAClB,KAAK,EACL,UAAU,GAEX,MAAM,oBAAoB,CAAC;AAG5B;IAAA;IAWA,CAAC;IAVC,8CAAY,GAAZ,UACE,KAAa,EACb,SAAiB,EACjB,UAAsB,EACtB,GAAY;QAEZ,IAAM,WAAW,GAAG,KAAK,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC;QAC9C,IAAI,CAAC,WAAW,IAAI,CAAC,kBAAkB,CAAC,WAAW,CAAC;YAAE,OAAO,KAAK,CAAC;QACnE,OAAO,WAAW,CAAC,UAAU,GAAG,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC;IACpE,CAAC;IACH,8BAAC;AAAD,CAAC,AAXD,IAWC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n Context,\n HrTime,\n isSpanContextValid,\n trace,\n TraceFlags,\n Attributes,\n} from '@opentelemetry/api';\nimport { ExemplarFilter } from './ExemplarFilter';\n\nexport class WithTraceExemplarFilter implements ExemplarFilter {\n shouldSample(\n value: number,\n timestamp: HrTime,\n attributes: Attributes,\n ctx: Context\n ): boolean {\n const spanContext = trace.getSpanContext(ctx);\n if (!spanContext || !isSpanContextValid(spanContext)) return false;\n return spanContext.traceFlags & TraceFlags.SAMPLED ? true : false;\n }\n}\n"]}

View File

@@ -0,0 +1,9 @@
export { Exemplar } from './Exemplar';
export { ExemplarFilter } from './ExemplarFilter';
export { AlwaysSampleExemplarFilter } from './AlwaysSampleExemplarFilter';
export { NeverSampleExemplarFilter } from './NeverSampleExemplarFilter';
export { WithTraceExemplarFilter } from './WithTraceExemplarFilter';
export { ExemplarReservoir, FixedSizeExemplarReservoirBase, } from './ExemplarReservoir';
export { AlignedHistogramBucketExemplarReservoir } from './AlignedHistogramBucketExemplarReservoir';
export { SimpleFixedSizeExemplarReservoir } from './SimpleFixedSizeExemplarReservoir';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,22 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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 { AlwaysSampleExemplarFilter } from './AlwaysSampleExemplarFilter';
export { NeverSampleExemplarFilter } from './NeverSampleExemplarFilter';
export { WithTraceExemplarFilter } from './WithTraceExemplarFilter';
export { FixedSizeExemplarReservoirBase, } from './ExemplarReservoir';
export { AlignedHistogramBucketExemplarReservoir } from './AlignedHistogramBucketExemplarReservoir';
export { SimpleFixedSizeExemplarReservoir } from './SimpleFixedSizeExemplarReservoir';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/exemplar/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AACxE,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EAEL,8BAA8B,GAC/B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,uCAAuC,EAAE,MAAM,2CAA2C,CAAC;AACpG,OAAO,EAAE,gCAAgC,EAAE,MAAM,oCAAoC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport { Exemplar } from './Exemplar';\nexport { ExemplarFilter } from './ExemplarFilter';\nexport { AlwaysSampleExemplarFilter } from './AlwaysSampleExemplarFilter';\nexport { NeverSampleExemplarFilter } from './NeverSampleExemplarFilter';\nexport { WithTraceExemplarFilter } from './WithTraceExemplarFilter';\nexport {\n ExemplarReservoir,\n FixedSizeExemplarReservoirBase,\n} from './ExemplarReservoir';\nexport { AlignedHistogramBucketExemplarReservoir } from './AlignedHistogramBucketExemplarReservoir';\nexport { SimpleFixedSizeExemplarReservoir } from './SimpleFixedSizeExemplarReservoir';\n"]}

View File

@@ -0,0 +1,14 @@
import { InstrumentType } from '../InstrumentDescriptor';
import { Aggregation } from '../view/Aggregation';
import { AggregationTemporality } from './AggregationTemporality';
/**
* Aggregation selector based on metric instrument types.
*/
export declare type AggregationSelector = (instrumentType: InstrumentType) => Aggregation;
/**
* Aggregation temporality selector based on metric instrument types.
*/
export declare type AggregationTemporalitySelector = (instrumentType: InstrumentType) => AggregationTemporality;
export declare const DEFAULT_AGGREGATION_SELECTOR: AggregationSelector;
export declare const DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR: AggregationTemporalitySelector;
//# sourceMappingURL=AggregationSelector.d.ts.map

View File

@@ -0,0 +1,20 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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 { Aggregation } from '../view/Aggregation';
import { AggregationTemporality } from './AggregationTemporality';
export var DEFAULT_AGGREGATION_SELECTOR = function (_instrumentType) { return Aggregation.Default(); };
export var DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = function (_instrumentType) { return AggregationTemporality.CUMULATIVE; };
//# sourceMappingURL=AggregationSelector.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"AggregationSelector.js","sourceRoot":"","sources":["../../../src/export/AggregationSelector.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAgBlE,MAAM,CAAC,IAAM,4BAA4B,GACvC,UAAA,eAAe,IAAI,OAAA,WAAW,CAAC,OAAO,EAAE,EAArB,CAAqB,CAAC;AAC3C,MAAM,CAAC,IAAM,wCAAwC,GACnD,UAAA,eAAe,IAAI,OAAA,sBAAsB,CAAC,UAAU,EAAjC,CAAiC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { InstrumentType } from '../InstrumentDescriptor';\nimport { Aggregation } from '../view/Aggregation';\nimport { AggregationTemporality } from './AggregationTemporality';\n\n/**\n * Aggregation selector based on metric instrument types.\n */\nexport type AggregationSelector = (\n instrumentType: InstrumentType\n) => Aggregation;\n\n/**\n * Aggregation temporality selector based on metric instrument types.\n */\nexport type AggregationTemporalitySelector = (\n instrumentType: InstrumentType\n) => AggregationTemporality;\n\nexport const DEFAULT_AGGREGATION_SELECTOR: AggregationSelector =\n _instrumentType => Aggregation.Default();\nexport const DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR: AggregationTemporalitySelector =\n _instrumentType => AggregationTemporality.CUMULATIVE;\n"]}

View File

@@ -0,0 +1,8 @@
/**
* AggregationTemporality indicates the way additive quantities are expressed.
*/
export declare enum AggregationTemporality {
DELTA = 0,
CUMULATIVE = 1
}
//# sourceMappingURL=AggregationTemporality.d.ts.map

View File

@@ -0,0 +1,24 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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.
*/
/**
* AggregationTemporality indicates the way additive quantities are expressed.
*/
export var AggregationTemporality;
(function (AggregationTemporality) {
AggregationTemporality[AggregationTemporality["DELTA"] = 0] = "DELTA";
AggregationTemporality[AggregationTemporality["CUMULATIVE"] = 1] = "CUMULATIVE";
})(AggregationTemporality || (AggregationTemporality = {}));
//# sourceMappingURL=AggregationTemporality.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"AggregationTemporality.js","sourceRoot":"","sources":["../../../src/export/AggregationTemporality.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH;;GAEG;AACH,MAAM,CAAN,IAAY,sBAGX;AAHD,WAAY,sBAAsB;IAChC,qEAAK,CAAA;IACL,+EAAU,CAAA;AACZ,CAAC,EAHW,sBAAsB,KAAtB,sBAAsB,QAGjC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * AggregationTemporality indicates the way additive quantities are expressed.\n */\nexport enum AggregationTemporality {\n DELTA,\n CUMULATIVE,\n}\n"]}

View File

@@ -0,0 +1,6 @@
import { InstrumentType } from '../InstrumentDescriptor';
/**
* Cardinality Limit selector based on metric instrument types.
*/
export declare type CardinalitySelector = (instrumentType: InstrumentType) => number;
//# sourceMappingURL=CardinalitySelector.d.ts.map

View File

@@ -0,0 +1,17 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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 {};
//# sourceMappingURL=CardinalitySelector.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"CardinalitySelector.js","sourceRoot":"","sources":["../../../src/export/CardinalitySelector.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { InstrumentType } from '../InstrumentDescriptor';\n/**\n * Cardinality Limit selector based on metric instrument types.\n */\nexport type CardinalitySelector = (instrumentType: InstrumentType) => number;\n"]}

View File

@@ -0,0 +1,27 @@
import { ExportResult } from '@opentelemetry/core';
import { InstrumentType } from '../InstrumentDescriptor';
import { AggregationTemporality } from './AggregationTemporality';
import { ResourceMetrics } from './MetricData';
import { PushMetricExporter } from './MetricExporter';
import { AggregationTemporalitySelector } from './AggregationSelector';
interface ConsoleMetricExporterOptions {
temporalitySelector?: AggregationTemporalitySelector;
}
/**
* This is an implementation of {@link PushMetricExporter} that prints metrics to the
* console. This class can be used for diagnostic purposes.
*
* NOTE: This {@link PushMetricExporter} is intended for diagnostics use only, output rendered to the console may change at any time.
*/
export declare class ConsoleMetricExporter implements PushMetricExporter {
protected _shutdown: boolean;
protected _temporalitySelector: AggregationTemporalitySelector;
constructor(options?: ConsoleMetricExporterOptions);
export(metrics: ResourceMetrics, resultCallback: (result: ExportResult) => void): void;
forceFlush(): Promise<void>;
selectAggregationTemporality(_instrumentType: InstrumentType): AggregationTemporality;
shutdown(): Promise<void>;
private static _sendMetrics;
}
export {};
//# sourceMappingURL=ConsoleMetricExporter.d.ts.map

View File

@@ -0,0 +1,97 @@
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
/*
* Copyright The OpenTelemetry 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
*
* https://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 { ExportResultCode } from '@opentelemetry/core';
import { DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR, } from './AggregationSelector';
/**
* This is an implementation of {@link PushMetricExporter} that prints metrics to the
* console. This class can be used for diagnostic purposes.
*
* NOTE: This {@link PushMetricExporter} is intended for diagnostics use only, output rendered to the console may change at any time.
*/
/* eslint-disable no-console */
var ConsoleMetricExporter = /** @class */ (function () {
function ConsoleMetricExporter(options) {
var _a;
this._shutdown = false;
this._temporalitySelector =
(_a = options === null || options === void 0 ? void 0 : options.temporalitySelector) !== null && _a !== void 0 ? _a : DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR;
}
ConsoleMetricExporter.prototype.export = function (metrics, resultCallback) {
if (this._shutdown) {
// If the exporter is shutting down, by spec, we need to return FAILED as export result
setImmediate(resultCallback, { code: ExportResultCode.FAILED });
return;
}
return ConsoleMetricExporter._sendMetrics(metrics, resultCallback);
};
ConsoleMetricExporter.prototype.forceFlush = function () {
return Promise.resolve();
};
ConsoleMetricExporter.prototype.selectAggregationTemporality = function (_instrumentType) {
return this._temporalitySelector(_instrumentType);
};
ConsoleMetricExporter.prototype.shutdown = function () {
this._shutdown = true;
return Promise.resolve();
};
ConsoleMetricExporter._sendMetrics = function (metrics, done) {
var e_1, _a, e_2, _b;
try {
for (var _c = __values(metrics.scopeMetrics), _d = _c.next(); !_d.done; _d = _c.next()) {
var scopeMetrics = _d.value;
try {
for (var _e = (e_2 = void 0, __values(scopeMetrics.metrics)), _f = _e.next(); !_f.done; _f = _e.next()) {
var metric = _f.value;
console.dir({
descriptor: metric.descriptor,
dataPointType: metric.dataPointType,
dataPoints: metric.dataPoints,
}, { depth: null });
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
}
finally { if (e_2) throw e_2.error; }
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
}
finally { if (e_1) throw e_1.error; }
}
done({ code: ExportResultCode.SUCCESS });
};
return ConsoleMetricExporter;
}());
export { ConsoleMetricExporter };
//# sourceMappingURL=ConsoleMetricExporter.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ConsoleMetricExporter.js","sourceRoot":"","sources":["../../../src/export/ConsoleMetricExporter.ts"],"names":[],"mappings":";;;;;;;;;;;AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAgB,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAKrE,OAAO,EAEL,wCAAwC,GACzC,MAAM,uBAAuB,CAAC;AAM/B;;;;;GAKG;AAEH,+BAA+B;AAC/B;IAIE,+BAAY,OAAsC;;QAHxC,cAAS,GAAG,KAAK,CAAC;QAI1B,IAAI,CAAC,oBAAoB;YACvB,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,mBAAmB,mCAAI,wCAAwC,CAAC;IAC7E,CAAC;IAED,sCAAM,GAAN,UACE,OAAwB,EACxB,cAA8C;QAE9C,IAAI,IAAI,CAAC,SAAS,EAAE;YAClB,uFAAuF;YACvF,YAAY,CAAC,cAAc,EAAE,EAAE,IAAI,EAAE,gBAAgB,CAAC,MAAM,EAAE,CAAC,CAAC;YAChE,OAAO;SACR;QAED,OAAO,qBAAqB,CAAC,YAAY,CAAC,OAAO,EAAE,cAAc,CAAC,CAAC;IACrE,CAAC;IAED,0CAAU,GAAV;QACE,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAED,4DAA4B,GAA5B,UACE,eAA+B;QAE/B,OAAO,IAAI,CAAC,oBAAoB,CAAC,eAAe,CAAC,CAAC;IACpD,CAAC;IAED,wCAAQ,GAAR;QACE,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAEc,kCAAY,GAA3B,UACE,OAAwB,EACxB,IAAoC;;;YAEpC,KAA2B,IAAA,KAAA,SAAA,OAAO,CAAC,YAAY,CAAA,gBAAA,4BAAE;gBAA5C,IAAM,YAAY,WAAA;;oBACrB,KAAqB,IAAA,oBAAA,SAAA,YAAY,CAAC,OAAO,CAAA,CAAA,gBAAA,4BAAE;wBAAtC,IAAM,MAAM,WAAA;wBACf,OAAO,CAAC,GAAG,CACT;4BACE,UAAU,EAAE,MAAM,CAAC,UAAU;4BAC7B,aAAa,EAAE,MAAM,CAAC,aAAa;4BACnC,UAAU,EAAE,MAAM,CAAC,UAAU;yBAC9B,EACD,EAAE,KAAK,EAAE,IAAI,EAAE,CAChB,CAAC;qBACH;;;;;;;;;aACF;;;;;;;;;QAED,IAAI,CAAC,EAAE,IAAI,EAAE,gBAAgB,CAAC,OAAO,EAAE,CAAC,CAAC;IAC3C,CAAC;IACH,4BAAC;AAAD,CAAC,AAxDD,IAwDC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { ExportResult, ExportResultCode } from '@opentelemetry/core';\nimport { InstrumentType } from '../InstrumentDescriptor';\nimport { AggregationTemporality } from './AggregationTemporality';\nimport { ResourceMetrics } from './MetricData';\nimport { PushMetricExporter } from './MetricExporter';\nimport {\n AggregationTemporalitySelector,\n DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR,\n} from './AggregationSelector';\n\ninterface ConsoleMetricExporterOptions {\n temporalitySelector?: AggregationTemporalitySelector;\n}\n\n/**\n * This is an implementation of {@link PushMetricExporter} that prints metrics to the\n * console. This class can be used for diagnostic purposes.\n *\n * NOTE: This {@link PushMetricExporter} is intended for diagnostics use only, output rendered to the console may change at any time.\n */\n\n/* eslint-disable no-console */\nexport class ConsoleMetricExporter implements PushMetricExporter {\n protected _shutdown = false;\n protected _temporalitySelector: AggregationTemporalitySelector;\n\n constructor(options?: ConsoleMetricExporterOptions) {\n this._temporalitySelector =\n options?.temporalitySelector ?? DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR;\n }\n\n export(\n metrics: ResourceMetrics,\n resultCallback: (result: ExportResult) => void\n ): void {\n if (this._shutdown) {\n // If the exporter is shutting down, by spec, we need to return FAILED as export result\n setImmediate(resultCallback, { code: ExportResultCode.FAILED });\n return;\n }\n\n return ConsoleMetricExporter._sendMetrics(metrics, resultCallback);\n }\n\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n\n selectAggregationTemporality(\n _instrumentType: InstrumentType\n ): AggregationTemporality {\n return this._temporalitySelector(_instrumentType);\n }\n\n shutdown(): Promise<void> {\n this._shutdown = true;\n return Promise.resolve();\n }\n\n private static _sendMetrics(\n metrics: ResourceMetrics,\n done: (result: ExportResult) => void\n ): void {\n for (const scopeMetrics of metrics.scopeMetrics) {\n for (const metric of scopeMetrics.metrics) {\n console.dir(\n {\n descriptor: metric.descriptor,\n dataPointType: metric.dataPointType,\n dataPoints: metric.dataPoints,\n },\n { depth: null }\n );\n }\n }\n\n done({ code: ExportResultCode.SUCCESS });\n }\n}\n"]}

View File

@@ -0,0 +1,30 @@
import { ExportResult } from '@opentelemetry/core';
import { InstrumentType } from '../InstrumentDescriptor';
import { AggregationTemporality } from './AggregationTemporality';
import { ResourceMetrics } from './MetricData';
import { PushMetricExporter } from './MetricExporter';
/**
* In-memory Metrics Exporter is a Push Metric Exporter
* which accumulates metrics data in the local memory and
* allows to inspect it (useful for e.g. unit tests).
*/
export declare class InMemoryMetricExporter implements PushMetricExporter {
protected _shutdown: boolean;
protected _aggregationTemporality: AggregationTemporality;
private _metrics;
constructor(aggregationTemporality: AggregationTemporality);
/**
* @inheritedDoc
*/
export(metrics: ResourceMetrics, resultCallback: (result: ExportResult) => void): void;
/**
* Returns all the collected resource metrics
* @returns ResourceMetrics[]
*/
getMetrics(): ResourceMetrics[];
forceFlush(): Promise<void>;
reset(): void;
selectAggregationTemporality(_instrumentType: InstrumentType): AggregationTemporality;
shutdown(): Promise<void>;
}
//# sourceMappingURL=InMemoryMetricExporter.d.ts.map

View File

@@ -0,0 +1,63 @@
/*
* Copyright The OpenTelemetry 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
*
* https://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 { ExportResultCode } from '@opentelemetry/core';
/**
* In-memory Metrics Exporter is a Push Metric Exporter
* which accumulates metrics data in the local memory and
* allows to inspect it (useful for e.g. unit tests).
*/
var InMemoryMetricExporter = /** @class */ (function () {
function InMemoryMetricExporter(aggregationTemporality) {
this._shutdown = false;
this._metrics = [];
this._aggregationTemporality = aggregationTemporality;
}
/**
* @inheritedDoc
*/
InMemoryMetricExporter.prototype.export = function (metrics, resultCallback) {
// Avoid storing metrics when exporter is shutdown
if (this._shutdown) {
setTimeout(function () { return resultCallback({ code: ExportResultCode.FAILED }); }, 0);
return;
}
this._metrics.push(metrics);
setTimeout(function () { return resultCallback({ code: ExportResultCode.SUCCESS }); }, 0);
};
/**
* Returns all the collected resource metrics
* @returns ResourceMetrics[]
*/
InMemoryMetricExporter.prototype.getMetrics = function () {
return this._metrics;
};
InMemoryMetricExporter.prototype.forceFlush = function () {
return Promise.resolve();
};
InMemoryMetricExporter.prototype.reset = function () {
this._metrics = [];
};
InMemoryMetricExporter.prototype.selectAggregationTemporality = function (_instrumentType) {
return this._aggregationTemporality;
};
InMemoryMetricExporter.prototype.shutdown = function () {
this._shutdown = true;
return Promise.resolve();
};
return InMemoryMetricExporter;
}());
export { InMemoryMetricExporter };
//# sourceMappingURL=InMemoryMetricExporter.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"InMemoryMetricExporter.js","sourceRoot":"","sources":["../../../src/export/InMemoryMetricExporter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAOvD;;;;GAIG;AACH;IAKE,gCAAY,sBAA8C;QAJhD,cAAS,GAAG,KAAK,CAAC;QAEpB,aAAQ,GAAsB,EAAE,CAAC;QAGvC,IAAI,CAAC,uBAAuB,GAAG,sBAAsB,CAAC;IACxD,CAAC;IAED;;OAEG;IACH,uCAAM,GAAN,UACE,OAAwB,EACxB,cAA8C;QAE9C,kDAAkD;QAClD,IAAI,IAAI,CAAC,SAAS,EAAE;YAClB,UAAU,CAAC,cAAM,OAAA,cAAc,CAAC,EAAE,IAAI,EAAE,gBAAgB,CAAC,MAAM,EAAE,CAAC,EAAjD,CAAiD,EAAE,CAAC,CAAC,CAAC;YACvE,OAAO;SACR;QAED,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAC5B,UAAU,CAAC,cAAM,OAAA,cAAc,CAAC,EAAE,IAAI,EAAE,gBAAgB,CAAC,OAAO,EAAE,CAAC,EAAlD,CAAkD,EAAE,CAAC,CAAC,CAAC;IAC1E,CAAC;IAED;;;OAGG;IACI,2CAAU,GAAjB;QACE,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;IAED,2CAAU,GAAV;QACE,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAED,sCAAK,GAAL;QACE,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAC;IACrB,CAAC;IAED,6DAA4B,GAA5B,UACE,eAA+B;QAE/B,OAAO,IAAI,CAAC,uBAAuB,CAAC;IACtC,CAAC;IAED,yCAAQ,GAAR;QACE,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IACH,6BAAC;AAAD,CAAC,AApDD,IAoDC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ExportResultCode } from '@opentelemetry/core';\nimport { ExportResult } from '@opentelemetry/core';\nimport { InstrumentType } from '../InstrumentDescriptor';\nimport { AggregationTemporality } from './AggregationTemporality';\nimport { ResourceMetrics } from './MetricData';\nimport { PushMetricExporter } from './MetricExporter';\n\n/**\n * In-memory Metrics Exporter is a Push Metric Exporter\n * which accumulates metrics data in the local memory and\n * allows to inspect it (useful for e.g. unit tests).\n */\nexport class InMemoryMetricExporter implements PushMetricExporter {\n protected _shutdown = false;\n protected _aggregationTemporality: AggregationTemporality;\n private _metrics: ResourceMetrics[] = [];\n\n constructor(aggregationTemporality: AggregationTemporality) {\n this._aggregationTemporality = aggregationTemporality;\n }\n\n /**\n * @inheritedDoc\n */\n export(\n metrics: ResourceMetrics,\n resultCallback: (result: ExportResult) => void\n ): void {\n // Avoid storing metrics when exporter is shutdown\n if (this._shutdown) {\n setTimeout(() => resultCallback({ code: ExportResultCode.FAILED }), 0);\n return;\n }\n\n this._metrics.push(metrics);\n setTimeout(() => resultCallback({ code: ExportResultCode.SUCCESS }), 0);\n }\n\n /**\n * Returns all the collected resource metrics\n * @returns ResourceMetrics[]\n */\n public getMetrics(): ResourceMetrics[] {\n return this._metrics;\n }\n\n forceFlush(): Promise<void> {\n return Promise.resolve();\n }\n\n reset() {\n this._metrics = [];\n }\n\n selectAggregationTemporality(\n _instrumentType: InstrumentType\n ): AggregationTemporality {\n return this._aggregationTemporality;\n }\n\n shutdown(): Promise<void> {\n this._shutdown = true;\n return Promise.resolve();\n }\n}\n"]}

View File

@@ -0,0 +1,138 @@
import { HrTime, Attributes, ValueType } from '@opentelemetry/api';
import { InstrumentationScope } from '@opentelemetry/core';
import { IResource } from '@opentelemetry/resources';
import { InstrumentType } from '../InstrumentDescriptor';
import { AggregationTemporality } from './AggregationTemporality';
import { Histogram, ExponentialHistogram } from '../aggregator/types';
export interface MetricDescriptor {
readonly name: string;
readonly description: string;
readonly unit: string;
/**
* @deprecated exporter should avoid depending on the type of the instrument
* as their resulting aggregator can be re-mapped with views.
*/
readonly type: InstrumentType;
readonly valueType: ValueType;
}
/**
* Basic metric data fields.
*/
interface BaseMetricData {
readonly descriptor: MetricDescriptor;
readonly aggregationTemporality: AggregationTemporality;
/**
* DataPointType of the metric instrument.
*/
readonly dataPointType: DataPointType;
}
/**
* Represents a metric data aggregated by either a LastValueAggregation or
* SumAggregation.
*/
export interface SumMetricData extends BaseMetricData {
readonly dataPointType: DataPointType.SUM;
readonly dataPoints: DataPoint<number>[];
readonly isMonotonic: boolean;
}
export interface GaugeMetricData extends BaseMetricData {
readonly dataPointType: DataPointType.GAUGE;
readonly dataPoints: DataPoint<number>[];
}
/**
* Represents a metric data aggregated by a HistogramAggregation.
*/
export interface HistogramMetricData extends BaseMetricData {
readonly dataPointType: DataPointType.HISTOGRAM;
readonly dataPoints: DataPoint<Histogram>[];
}
/**
* Represents a metric data aggregated by a ExponentialHistogramAggregation.
*/
export interface ExponentialHistogramMetricData extends BaseMetricData {
readonly dataPointType: DataPointType.EXPONENTIAL_HISTOGRAM;
readonly dataPoints: DataPoint<ExponentialHistogram>[];
}
/**
* Represents an aggregated metric data.
*/
export declare type MetricData = SumMetricData | GaugeMetricData | HistogramMetricData | ExponentialHistogramMetricData;
export interface ScopeMetrics {
scope: InstrumentationScope;
metrics: MetricData[];
}
export interface ResourceMetrics {
resource: IResource;
scopeMetrics: ScopeMetrics[];
}
/**
* Represents the collection result of the metrics. If there are any
* non-critical errors in the collection, like throwing in a single observable
* callback, these errors are aggregated in the {@link CollectionResult.errors}
* array and other successfully collected metrics are returned.
*/
export interface CollectionResult {
/**
* Collected metrics.
*/
resourceMetrics: ResourceMetrics;
/**
* Arbitrary JavaScript exception values.
*/
errors: unknown[];
}
/**
* The aggregated point data type.
*/
export declare enum DataPointType {
/**
* A histogram data point contains a histogram statistics of collected
* values with a list of explicit bucket boundaries and statistics such
* as min, max, count, and sum of all collected values.
*/
HISTOGRAM = 0,
/**
* An exponential histogram data point contains a histogram statistics of
* collected values where bucket boundaries are automatically calculated
* using an exponential function, and statistics such as min, max, count,
* and sum of all collected values.
*/
EXPONENTIAL_HISTOGRAM = 1,
/**
* A gauge metric data point has only a single numeric value.
*/
GAUGE = 2,
/**
* A sum metric data point has a single numeric value and a
* monotonicity-indicator.
*/
SUM = 3
}
/**
* Represents an aggregated point data with start time, end time and their
* associated attributes and points.
*/
export interface DataPoint<T> {
/**
* The start epoch timestamp of the DataPoint, usually the time when
* the metric was created when the preferred AggregationTemporality is
* CUMULATIVE, or last collection time otherwise.
*/
readonly startTime: HrTime;
/**
* The end epoch timestamp when data were collected, usually it represents
* the moment when `MetricReader.collect` was called.
*/
readonly endTime: HrTime;
/**
* The attributes associated with this DataPoint.
*/
readonly attributes: Attributes;
/**
* The value for this DataPoint. The type of the value is indicated by the
* {@link DataPointType}.
*/
readonly value: T;
}
export {};
//# sourceMappingURL=MetricData.d.ts.map

Some files were not shown because too many files have changed in this diff Show More