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,32 @@
import { HrTime } from '@opentelemetry/api';
import { Accumulation, Aggregator } from '../aggregator/types';
import { InstrumentDescriptor } from '../InstrumentDescriptor';
import { AttributesProcessor } from '../view/AttributesProcessor';
import { MetricStorage } from './MetricStorage';
import { MetricData } from '../export/MetricData';
import { Maybe } from '../utils';
import { MetricCollectorHandle } from './MetricCollector';
import { AttributeHashMap } from './HashMap';
import { AsyncWritableMetricStorage } from './WritableMetricStorage';
/**
* Internal interface.
*
* Stores and aggregates {@link MetricData} for asynchronous instruments.
*/
export declare class AsyncMetricStorage<T extends Maybe<Accumulation>> extends MetricStorage implements AsyncWritableMetricStorage {
private _attributesProcessor;
private _aggregationCardinalityLimit?;
private _deltaMetricStorage;
private _temporalMetricStorage;
constructor(_instrumentDescriptor: InstrumentDescriptor, aggregator: Aggregator<T>, _attributesProcessor: AttributesProcessor, collectorHandles: MetricCollectorHandle[], _aggregationCardinalityLimit?: number | undefined);
record(measurements: AttributeHashMap<number>, observationTime: HrTime): void;
/**
* Collects the metrics from this storage. The ObservableCallback is invoked
* during the collection.
*
* Note: This is a stateful operation and may reset any interval-related
* state for the MetricCollector.
*/
collect(collector: MetricCollectorHandle, collectionTime: HrTime): Maybe<MetricData>;
}
//# sourceMappingURL=AsyncMetricStorage.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.
*/
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 __());
};
})();
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 { MetricStorage } from './MetricStorage';
import { DeltaMetricProcessor } from './DeltaMetricProcessor';
import { TemporalMetricProcessor } from './TemporalMetricProcessor';
import { AttributeHashMap } from './HashMap';
/**
* Internal interface.
*
* Stores and aggregates {@link MetricData} for asynchronous instruments.
*/
var AsyncMetricStorage = /** @class */ (function (_super) {
__extends(AsyncMetricStorage, _super);
function AsyncMetricStorage(_instrumentDescriptor, aggregator, _attributesProcessor, collectorHandles, _aggregationCardinalityLimit) {
var _this = _super.call(this, _instrumentDescriptor) || this;
_this._attributesProcessor = _attributesProcessor;
_this._aggregationCardinalityLimit = _aggregationCardinalityLimit;
_this._deltaMetricStorage = new DeltaMetricProcessor(aggregator, _this._aggregationCardinalityLimit);
_this._temporalMetricStorage = new TemporalMetricProcessor(aggregator, collectorHandles);
return _this;
}
AsyncMetricStorage.prototype.record = function (measurements, observationTime) {
var _this = this;
var processed = new AttributeHashMap();
Array.from(measurements.entries()).forEach(function (_a) {
var _b = __read(_a, 2), attributes = _b[0], value = _b[1];
processed.set(_this._attributesProcessor.process(attributes), value);
});
this._deltaMetricStorage.batchCumulate(processed, observationTime);
};
/**
* Collects the metrics from this storage. The ObservableCallback is invoked
* during the collection.
*
* Note: This is a stateful operation and may reset any interval-related
* state for the MetricCollector.
*/
AsyncMetricStorage.prototype.collect = function (collector, collectionTime) {
var accumulations = this._deltaMetricStorage.collect();
return this._temporalMetricStorage.buildMetrics(collector, this._instrumentDescriptor, accumulations, collectionTime);
};
return AsyncMetricStorage;
}(MetricStorage));
export { AsyncMetricStorage };
//# sourceMappingURL=AsyncMetricStorage.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"AsyncMetricStorage.js","sourceRoot":"","sources":["../../../src/state/AsyncMetricStorage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMH,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAGpE,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAG7C;;;;GAIG;AACH;IACU,sCAAa;IAMrB,4BACE,qBAA2C,EAC3C,UAAyB,EACjB,oBAAyC,EACjD,gBAAyC,EACjC,4BAAqC;QAL/C,YAOE,kBAAM,qBAAqB,CAAC,SAS7B;QAbS,0BAAoB,GAApB,oBAAoB,CAAqB;QAEzC,kCAA4B,GAA5B,4BAA4B,CAAS;QAG7C,KAAI,CAAC,mBAAmB,GAAG,IAAI,oBAAoB,CACjD,UAAU,EACV,KAAI,CAAC,4BAA4B,CAClC,CAAC;QACF,KAAI,CAAC,sBAAsB,GAAG,IAAI,uBAAuB,CACvD,UAAU,EACV,gBAAgB,CACjB,CAAC;;IACJ,CAAC;IAED,mCAAM,GAAN,UAAO,YAAsC,EAAE,eAAuB;QAAtE,iBAMC;QALC,IAAM,SAAS,GAAG,IAAI,gBAAgB,EAAU,CAAC;QACjD,KAAK,CAAC,IAAI,CAAC,YAAY,CAAC,OAAO,EAAE,CAAC,CAAC,OAAO,CAAC,UAAC,EAAmB;gBAAnB,KAAA,aAAmB,EAAlB,UAAU,QAAA,EAAE,KAAK,QAAA;YAC5D,SAAS,CAAC,GAAG,CAAC,KAAI,CAAC,oBAAoB,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,KAAK,CAAC,CAAC;QACtE,CAAC,CAAC,CAAC;QACH,IAAI,CAAC,mBAAmB,CAAC,aAAa,CAAC,SAAS,EAAE,eAAe,CAAC,CAAC;IACrE,CAAC;IAED;;;;;;OAMG;IACH,oCAAO,GAAP,UACE,SAAgC,EAChC,cAAsB;QAEtB,IAAM,aAAa,GAAG,IAAI,CAAC,mBAAmB,CAAC,OAAO,EAAE,CAAC;QAEzD,OAAO,IAAI,CAAC,sBAAsB,CAAC,YAAY,CAC7C,SAAS,EACT,IAAI,CAAC,qBAAqB,EAC1B,aAAa,EACb,cAAc,CACf,CAAC;IACJ,CAAC;IACH,yBAAC;AAAD,CAAC,AArDD,CACU,aAAa,GAoDtB","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 { Accumulation, Aggregator } from '../aggregator/types';\nimport { InstrumentDescriptor } from '../InstrumentDescriptor';\nimport { AttributesProcessor } from '../view/AttributesProcessor';\nimport { MetricStorage } from './MetricStorage';\nimport { MetricData } from '../export/MetricData';\nimport { DeltaMetricProcessor } from './DeltaMetricProcessor';\nimport { TemporalMetricProcessor } from './TemporalMetricProcessor';\nimport { Maybe } from '../utils';\nimport { MetricCollectorHandle } from './MetricCollector';\nimport { AttributeHashMap } from './HashMap';\nimport { AsyncWritableMetricStorage } from './WritableMetricStorage';\n\n/**\n * Internal interface.\n *\n * Stores and aggregates {@link MetricData} for asynchronous instruments.\n */\nexport class AsyncMetricStorage<T extends Maybe<Accumulation>>\n extends MetricStorage\n implements AsyncWritableMetricStorage\n{\n private _deltaMetricStorage: DeltaMetricProcessor<T>;\n private _temporalMetricStorage: TemporalMetricProcessor<T>;\n\n constructor(\n _instrumentDescriptor: InstrumentDescriptor,\n aggregator: Aggregator<T>,\n private _attributesProcessor: AttributesProcessor,\n collectorHandles: MetricCollectorHandle[],\n private _aggregationCardinalityLimit?: number\n ) {\n super(_instrumentDescriptor);\n this._deltaMetricStorage = new DeltaMetricProcessor(\n aggregator,\n this._aggregationCardinalityLimit\n );\n this._temporalMetricStorage = new TemporalMetricProcessor(\n aggregator,\n collectorHandles\n );\n }\n\n record(measurements: AttributeHashMap<number>, observationTime: HrTime) {\n const processed = new AttributeHashMap<number>();\n Array.from(measurements.entries()).forEach(([attributes, value]) => {\n processed.set(this._attributesProcessor.process(attributes), value);\n });\n this._deltaMetricStorage.batchCumulate(processed, observationTime);\n }\n\n /**\n * Collects the metrics from this storage. The ObservableCallback is invoked\n * during the collection.\n *\n * Note: This is a stateful operation and may reset any interval-related\n * state for the MetricCollector.\n */\n collect(\n collector: MetricCollectorHandle,\n collectionTime: HrTime\n ): Maybe<MetricData> {\n const accumulations = this._deltaMetricStorage.collect();\n\n return this._temporalMetricStorage.buildMetrics(\n collector,\n this._instrumentDescriptor,\n accumulations,\n collectionTime\n );\n }\n}\n"]}

View File

@@ -0,0 +1,28 @@
import { Context, HrTime, Attributes } from '@opentelemetry/api';
import { Maybe } from '../utils';
import { Accumulation, Aggregator } from '../aggregator/types';
import { AttributeHashMap } from './HashMap';
/**
* Internal interface.
*
* Allows synchronous collection of metrics. This processor should allow
* allocation of new aggregation cells for metrics and convert cumulative
* recording to delta data points.
*/
export declare class DeltaMetricProcessor<T extends Maybe<Accumulation>> {
private _aggregator;
private _activeCollectionStorage;
private _cumulativeMemoStorage;
private _cardinalityLimit;
private _overflowAttributes;
private _overflowHashCode;
constructor(_aggregator: Aggregator<T>, aggregationCardinalityLimit?: number);
record(value: number, attributes: Attributes, _context: Context, collectionTime: HrTime): void;
batchCumulate(measurements: AttributeHashMap<number>, collectionTime: HrTime): void;
/**
* Returns a collection of delta metrics. Start time is the when first
* time event collected.
*/
collect(): AttributeHashMap<T>;
}
//# sourceMappingURL=DeltaMetricProcessor.d.ts.map

View File

@@ -0,0 +1,115 @@
/*
* 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 { hashAttributes } from '../utils';
import { AttributeHashMap } from './HashMap';
/**
* Internal interface.
*
* Allows synchronous collection of metrics. This processor should allow
* allocation of new aggregation cells for metrics and convert cumulative
* recording to delta data points.
*/
var DeltaMetricProcessor = /** @class */ (function () {
function DeltaMetricProcessor(_aggregator, aggregationCardinalityLimit) {
this._aggregator = _aggregator;
this._activeCollectionStorage = new AttributeHashMap();
// TODO: find a reasonable mean to clean the memo;
// https://github.com/open-telemetry/opentelemetry-specification/pull/2208
this._cumulativeMemoStorage = new AttributeHashMap();
this._overflowAttributes = { 'otel.metric.overflow': true };
this._cardinalityLimit = (aggregationCardinalityLimit !== null && aggregationCardinalityLimit !== void 0 ? aggregationCardinalityLimit : 2000) - 1;
this._overflowHashCode = hashAttributes(this._overflowAttributes);
}
DeltaMetricProcessor.prototype.record = function (value, attributes, _context, collectionTime) {
var _this = this;
var accumulation = this._activeCollectionStorage.get(attributes);
if (!accumulation) {
if (this._activeCollectionStorage.size >= this._cardinalityLimit) {
var overflowAccumulation = this._activeCollectionStorage.getOrDefault(this._overflowAttributes, function () { return _this._aggregator.createAccumulation(collectionTime); });
overflowAccumulation === null || overflowAccumulation === void 0 ? void 0 : overflowAccumulation.record(value);
return;
}
accumulation = this._aggregator.createAccumulation(collectionTime);
this._activeCollectionStorage.set(attributes, accumulation);
}
accumulation === null || accumulation === void 0 ? void 0 : accumulation.record(value);
};
DeltaMetricProcessor.prototype.batchCumulate = function (measurements, collectionTime) {
var _this = this;
Array.from(measurements.entries()).forEach(function (_a) {
var _b = __read(_a, 3), attributes = _b[0], value = _b[1], hashCode = _b[2];
var accumulation = _this._aggregator.createAccumulation(collectionTime);
accumulation === null || accumulation === void 0 ? void 0 : accumulation.record(value);
var delta = accumulation;
// Diff with recorded cumulative memo.
if (_this._cumulativeMemoStorage.has(attributes, hashCode)) {
// has() returned true, previous is present.
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
var previous = _this._cumulativeMemoStorage.get(attributes, hashCode);
delta = _this._aggregator.diff(previous, accumulation);
}
else {
// If the cardinality limit is reached, we need to change the attributes
if (_this._cumulativeMemoStorage.size >= _this._cardinalityLimit) {
attributes = _this._overflowAttributes;
hashCode = _this._overflowHashCode;
if (_this._cumulativeMemoStorage.has(attributes, hashCode)) {
var previous = _this._cumulativeMemoStorage.get(attributes, hashCode);
delta = _this._aggregator.diff(previous, accumulation);
}
}
}
// Merge with uncollected active delta.
if (_this._activeCollectionStorage.has(attributes, hashCode)) {
// has() returned true, previous is present.
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
var active = _this._activeCollectionStorage.get(attributes, hashCode);
delta = _this._aggregator.merge(active, delta);
}
// Save the current record and the delta record.
_this._cumulativeMemoStorage.set(attributes, accumulation, hashCode);
_this._activeCollectionStorage.set(attributes, delta, hashCode);
});
};
/**
* Returns a collection of delta metrics. Start time is the when first
* time event collected.
*/
DeltaMetricProcessor.prototype.collect = function () {
var unreportedDelta = this._activeCollectionStorage;
this._activeCollectionStorage = new AttributeHashMap();
return unreportedDelta;
};
return DeltaMetricProcessor;
}());
export { DeltaMetricProcessor };
//# sourceMappingURL=DeltaMetricProcessor.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,21 @@
import { Attributes } from '@opentelemetry/api';
export interface Hash<ValueType, HashCodeType> {
(value: ValueType): HashCodeType;
}
export declare class HashMap<KeyType, ValueType, HashCodeType> {
private _hash;
private _valueMap;
private _keyMap;
constructor(_hash: Hash<KeyType, HashCodeType>);
get(key: KeyType, hashCode?: HashCodeType): ValueType | undefined;
getOrDefault(key: KeyType, defaultFactory: () => ValueType): ValueType | undefined;
set(key: KeyType, value: ValueType, hashCode?: HashCodeType): void;
has(key: KeyType, hashCode?: HashCodeType): boolean;
keys(): IterableIterator<[KeyType, HashCodeType]>;
entries(): IterableIterator<[KeyType, ValueType, HashCodeType]>;
get size(): number;
}
export declare class AttributeHashMap<ValueType> extends HashMap<Attributes, ValueType, string> {
constructor();
}
//# sourceMappingURL=HashMap.d.ts.map

View File

@@ -0,0 +1,152 @@
/*
* 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 __());
};
})();
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 };
}
};
import { hashAttributes } from '../utils';
var HashMap = /** @class */ (function () {
function HashMap(_hash) {
this._hash = _hash;
this._valueMap = new Map();
this._keyMap = new Map();
}
HashMap.prototype.get = function (key, hashCode) {
hashCode !== null && hashCode !== void 0 ? hashCode : (hashCode = this._hash(key));
return this._valueMap.get(hashCode);
};
HashMap.prototype.getOrDefault = function (key, defaultFactory) {
var hash = this._hash(key);
if (this._valueMap.has(hash)) {
return this._valueMap.get(hash);
}
var val = defaultFactory();
if (!this._keyMap.has(hash)) {
this._keyMap.set(hash, key);
}
this._valueMap.set(hash, val);
return val;
};
HashMap.prototype.set = function (key, value, hashCode) {
hashCode !== null && hashCode !== void 0 ? hashCode : (hashCode = this._hash(key));
if (!this._keyMap.has(hashCode)) {
this._keyMap.set(hashCode, key);
}
this._valueMap.set(hashCode, value);
};
HashMap.prototype.has = function (key, hashCode) {
hashCode !== null && hashCode !== void 0 ? hashCode : (hashCode = this._hash(key));
return this._valueMap.has(hashCode);
};
HashMap.prototype.keys = function () {
var keyIterator, next;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
keyIterator = this._keyMap.entries();
next = keyIterator.next();
_a.label = 1;
case 1:
if (!(next.done !== true)) return [3 /*break*/, 3];
return [4 /*yield*/, [next.value[1], next.value[0]]];
case 2:
_a.sent();
next = keyIterator.next();
return [3 /*break*/, 1];
case 3: return [2 /*return*/];
}
});
};
HashMap.prototype.entries = function () {
var valueIterator, next;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
valueIterator = this._valueMap.entries();
next = valueIterator.next();
_a.label = 1;
case 1:
if (!(next.done !== true)) return [3 /*break*/, 3];
// next.value[0] here can not be undefined
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return [4 /*yield*/, [this._keyMap.get(next.value[0]), next.value[1], next.value[0]]];
case 2:
// next.value[0] here can not be undefined
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
_a.sent();
next = valueIterator.next();
return [3 /*break*/, 1];
case 3: return [2 /*return*/];
}
});
};
Object.defineProperty(HashMap.prototype, "size", {
get: function () {
return this._valueMap.size;
},
enumerable: false,
configurable: true
});
return HashMap;
}());
export { HashMap };
var AttributeHashMap = /** @class */ (function (_super) {
__extends(AttributeHashMap, _super);
function AttributeHashMap() {
return _super.call(this, hashAttributes) || this;
}
return AttributeHashMap;
}(HashMap));
export { AttributeHashMap };
//# sourceMappingURL=HashMap.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,19 @@
import { InstrumentationScope } from '@opentelemetry/core';
import { IResource } from '@opentelemetry/resources';
import { Aggregation, InstrumentType } from '..';
import { ViewRegistry } from '../view/ViewRegistry';
import { MeterSharedState } from './MeterSharedState';
import { MetricCollector, MetricCollectorHandle } from './MetricCollector';
/**
* An internal record for shared meter provider states.
*/
export declare class MeterProviderSharedState {
resource: IResource;
viewRegistry: ViewRegistry;
metricCollectors: MetricCollector[];
meterSharedStates: Map<string, MeterSharedState>;
constructor(resource: IResource);
getMeterSharedState(instrumentationScope: InstrumentationScope): MeterSharedState;
selectAggregations(instrumentType: InstrumentType): [MetricCollectorHandle, Aggregation][];
}
//# sourceMappingURL=MeterProviderSharedState.d.ts.map

View File

@@ -0,0 +1,70 @@
/*
* 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 __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 { instrumentationScopeId } from '../utils';
import { ViewRegistry } from '../view/ViewRegistry';
import { MeterSharedState } from './MeterSharedState';
/**
* An internal record for shared meter provider states.
*/
var MeterProviderSharedState = /** @class */ (function () {
function MeterProviderSharedState(resource) {
this.resource = resource;
this.viewRegistry = new ViewRegistry();
this.metricCollectors = [];
this.meterSharedStates = new Map();
}
MeterProviderSharedState.prototype.getMeterSharedState = function (instrumentationScope) {
var id = instrumentationScopeId(instrumentationScope);
var meterSharedState = this.meterSharedStates.get(id);
if (meterSharedState == null) {
meterSharedState = new MeterSharedState(this, instrumentationScope);
this.meterSharedStates.set(id, meterSharedState);
}
return meterSharedState;
};
MeterProviderSharedState.prototype.selectAggregations = function (instrumentType) {
var e_1, _a;
var result = [];
try {
for (var _b = __values(this.metricCollectors), _c = _b.next(); !_c.done; _c = _b.next()) {
var collector = _c.value;
result.push([collector, collector.selectAggregation(instrumentType)]);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
return result;
};
return MeterProviderSharedState;
}());
export { MeterProviderSharedState };
//# sourceMappingURL=MeterProviderSharedState.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"MeterProviderSharedState.js","sourceRoot":"","sources":["../../../src/state/MeterProviderSharedState.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;AAKH,OAAO,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAClD,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAGtD;;GAEG;AACH;IAOE,kCAAmB,QAAmB;QAAnB,aAAQ,GAAR,QAAQ,CAAW;QANtC,iBAAY,GAAG,IAAI,YAAY,EAAE,CAAC;QAElC,qBAAgB,GAAsB,EAAE,CAAC;QAEzC,sBAAiB,GAAkC,IAAI,GAAG,EAAE,CAAC;IAEpB,CAAC;IAE1C,sDAAmB,GAAnB,UAAoB,oBAA0C;QAC5D,IAAM,EAAE,GAAG,sBAAsB,CAAC,oBAAoB,CAAC,CAAC;QACxD,IAAI,gBAAgB,GAAG,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QACtD,IAAI,gBAAgB,IAAI,IAAI,EAAE;YAC5B,gBAAgB,GAAG,IAAI,gBAAgB,CAAC,IAAI,EAAE,oBAAoB,CAAC,CAAC;YACpE,IAAI,CAAC,iBAAiB,CAAC,GAAG,CAAC,EAAE,EAAE,gBAAgB,CAAC,CAAC;SAClD;QACD,OAAO,gBAAgB,CAAC;IAC1B,CAAC;IAED,qDAAkB,GAAlB,UAAmB,cAA8B;;QAC/C,IAAM,MAAM,GAA2C,EAAE,CAAC;;YAC1D,KAAwB,IAAA,KAAA,SAAA,IAAI,CAAC,gBAAgB,CAAA,gBAAA,4BAAE;gBAA1C,IAAM,SAAS,WAAA;gBAClB,MAAM,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,SAAS,CAAC,iBAAiB,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC;aACvE;;;;;;;;;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IACH,+BAAC;AAAD,CAAC,AA1BD,IA0BC","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 { InstrumentationScope } from '@opentelemetry/core';\nimport { IResource } from '@opentelemetry/resources';\nimport { Aggregation, InstrumentType } from '..';\nimport { instrumentationScopeId } from '../utils';\nimport { ViewRegistry } from '../view/ViewRegistry';\nimport { MeterSharedState } from './MeterSharedState';\nimport { MetricCollector, MetricCollectorHandle } from './MetricCollector';\n\n/**\n * An internal record for shared meter provider states.\n */\nexport class MeterProviderSharedState {\n viewRegistry = new ViewRegistry();\n\n metricCollectors: MetricCollector[] = [];\n\n meterSharedStates: Map<string, MeterSharedState> = new Map();\n\n constructor(public resource: IResource) {}\n\n getMeterSharedState(instrumentationScope: InstrumentationScope) {\n const id = instrumentationScopeId(instrumentationScope);\n let meterSharedState = this.meterSharedStates.get(id);\n if (meterSharedState == null) {\n meterSharedState = new MeterSharedState(this, instrumentationScope);\n this.meterSharedStates.set(id, meterSharedState);\n }\n return meterSharedState;\n }\n\n selectAggregations(instrumentType: InstrumentType) {\n const result: [MetricCollectorHandle, Aggregation][] = [];\n for (const collector of this.metricCollectors) {\n result.push([collector, collector.selectAggregation(instrumentType)]);\n }\n return result;\n }\n}\n"]}

View File

@@ -0,0 +1,42 @@
import { HrTime } from '@opentelemetry/api';
import { InstrumentationScope } from '@opentelemetry/core';
import { MetricCollectOptions } from '../export/MetricProducer';
import { ScopeMetrics } from '../export/MetricData';
import { InstrumentDescriptor } from '../InstrumentDescriptor';
import { Meter } from '../Meter';
import { Maybe } from '../utils';
import { AsyncMetricStorage } from './AsyncMetricStorage';
import { MeterProviderSharedState } from './MeterProviderSharedState';
import { MetricCollectorHandle } from './MetricCollector';
import { MetricStorageRegistry } from './MetricStorageRegistry';
import { MultiMetricStorage } from './MultiWritableMetricStorage';
import { ObservableRegistry } from './ObservableRegistry';
import { SyncMetricStorage } from './SyncMetricStorage';
import { Accumulation } from '../aggregator/types';
/**
* An internal record for shared meter provider states.
*/
export declare class MeterSharedState {
private _meterProviderSharedState;
private _instrumentationScope;
metricStorageRegistry: MetricStorageRegistry;
observableRegistry: ObservableRegistry;
meter: Meter;
constructor(_meterProviderSharedState: MeterProviderSharedState, _instrumentationScope: InstrumentationScope);
registerMetricStorage(descriptor: InstrumentDescriptor): MultiMetricStorage | SyncMetricStorage<Maybe<Accumulation>>;
registerAsyncMetricStorage(descriptor: InstrumentDescriptor): AsyncMetricStorage<Maybe<Accumulation>>[];
/**
* @param collector opaque handle of {@link MetricCollector} which initiated the collection.
* @param collectionTime the HrTime at which the collection was initiated.
* @param options options for collection.
* @returns the list of metric data collected.
*/
collect(collector: MetricCollectorHandle, collectionTime: HrTime, options?: MetricCollectOptions): Promise<ScopeMetricsResult | null>;
private _registerMetricStorage;
}
interface ScopeMetricsResult {
scopeMetrics?: ScopeMetrics;
errors: unknown[];
}
export {};
//# sourceMappingURL=MeterSharedState.d.ts.map

View File

@@ -0,0 +1,174 @@
/*
* 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 __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 { createInstrumentDescriptorWithView, } from '../InstrumentDescriptor';
import { Meter } from '../Meter';
import { isNotNullish } from '../utils';
import { AsyncMetricStorage } from './AsyncMetricStorage';
import { MetricStorageRegistry } from './MetricStorageRegistry';
import { MultiMetricStorage } from './MultiWritableMetricStorage';
import { ObservableRegistry } from './ObservableRegistry';
import { SyncMetricStorage } from './SyncMetricStorage';
import { AttributesProcessor } from '../view/AttributesProcessor';
/**
* An internal record for shared meter provider states.
*/
var MeterSharedState = /** @class */ (function () {
function MeterSharedState(_meterProviderSharedState, _instrumentationScope) {
this._meterProviderSharedState = _meterProviderSharedState;
this._instrumentationScope = _instrumentationScope;
this.metricStorageRegistry = new MetricStorageRegistry();
this.observableRegistry = new ObservableRegistry();
this.meter = new Meter(this);
}
MeterSharedState.prototype.registerMetricStorage = function (descriptor) {
var storages = this._registerMetricStorage(descriptor, SyncMetricStorage);
if (storages.length === 1) {
return storages[0];
}
return new MultiMetricStorage(storages);
};
MeterSharedState.prototype.registerAsyncMetricStorage = function (descriptor) {
var storages = this._registerMetricStorage(descriptor, AsyncMetricStorage);
return storages;
};
/**
* @param collector opaque handle of {@link MetricCollector} which initiated the collection.
* @param collectionTime the HrTime at which the collection was initiated.
* @param options options for collection.
* @returns the list of metric data collected.
*/
MeterSharedState.prototype.collect = function (collector, collectionTime, options) {
return __awaiter(this, void 0, void 0, function () {
var errors, storages, metricDataList;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.observableRegistry.observe(collectionTime, options === null || options === void 0 ? void 0 : options.timeoutMillis)];
case 1:
errors = _a.sent();
storages = this.metricStorageRegistry.getStorages(collector);
// prevent more allocations if there are no storages.
if (storages.length === 0) {
return [2 /*return*/, null];
}
metricDataList = storages
.map(function (metricStorage) {
return metricStorage.collect(collector, collectionTime);
})
.filter(isNotNullish);
// skip this scope if no data was collected (storage created, but no data observed)
if (metricDataList.length === 0) {
return [2 /*return*/, { errors: errors }];
}
return [2 /*return*/, {
scopeMetrics: {
scope: this._instrumentationScope,
metrics: metricDataList,
},
errors: errors,
}];
}
});
});
};
MeterSharedState.prototype._registerMetricStorage = function (descriptor, MetricStorageType) {
var _this = this;
var views = this._meterProviderSharedState.viewRegistry.findViews(descriptor, this._instrumentationScope);
var storages = views.map(function (view) {
var viewDescriptor = createInstrumentDescriptorWithView(view, descriptor);
var compatibleStorage = _this.metricStorageRegistry.findOrUpdateCompatibleStorage(viewDescriptor);
if (compatibleStorage != null) {
return compatibleStorage;
}
var aggregator = view.aggregation.createAggregator(viewDescriptor);
var viewStorage = new MetricStorageType(viewDescriptor, aggregator, view.attributesProcessor, _this._meterProviderSharedState.metricCollectors, view.aggregationCardinalityLimit);
_this.metricStorageRegistry.register(viewStorage);
return viewStorage;
});
// Fallback to the per-collector aggregations if no view is configured for the instrument.
if (storages.length === 0) {
var perCollectorAggregations = this._meterProviderSharedState.selectAggregations(descriptor.type);
var collectorStorages = perCollectorAggregations.map(function (_a) {
var _b = __read(_a, 2), collector = _b[0], aggregation = _b[1];
var compatibleStorage = _this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(collector, descriptor);
if (compatibleStorage != null) {
return compatibleStorage;
}
var aggregator = aggregation.createAggregator(descriptor);
var cardinalityLimit = collector.selectCardinalityLimit(descriptor.type);
var storage = new MetricStorageType(descriptor, aggregator, AttributesProcessor.Noop(), [collector], cardinalityLimit);
_this.metricStorageRegistry.registerForCollector(collector, storage);
return storage;
});
storages = storages.concat(collectorStorages);
}
return storages;
};
return MeterSharedState;
}());
export { MeterSharedState };
//# sourceMappingURL=MeterSharedState.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,42 @@
import { AggregationTemporalitySelector } from '../export/AggregationSelector';
import { CollectionResult } from '../export/MetricData';
import { MetricProducer, MetricCollectOptions } from '../export/MetricProducer';
import { MetricReader } from '../export/MetricReader';
import { InstrumentType } from '../InstrumentDescriptor';
import { ForceFlushOptions, ShutdownOptions } from '../types';
import { MeterProviderSharedState } from './MeterProviderSharedState';
/**
* An internal opaque interface that the MetricReader receives as
* MetricProducer. It acts as the storage key to the internal metric stream
* state for each MetricReader.
*/
export declare class MetricCollector implements MetricProducer {
private _sharedState;
private _metricReader;
constructor(_sharedState: MeterProviderSharedState, _metricReader: MetricReader);
collect(options?: MetricCollectOptions): Promise<CollectionResult>;
/**
* Delegates for MetricReader.forceFlush.
*/
forceFlush(options?: ForceFlushOptions): Promise<void>;
/**
* Delegates for MetricReader.shutdown.
*/
shutdown(options?: ShutdownOptions): Promise<void>;
selectAggregationTemporality(instrumentType: InstrumentType): import("..").AggregationTemporality;
selectAggregation(instrumentType: InstrumentType): import("..").Aggregation;
/**
* Select the cardinality limit for the given {@link InstrumentType} for this
* collector.
*/
selectCardinalityLimit(instrumentType: InstrumentType): number;
}
/**
* An internal interface for MetricCollector. Exposes the necessary
* information for metric collection.
*/
export interface MetricCollectorHandle {
selectAggregationTemporality: AggregationTemporalitySelector;
selectCardinalityLimit(instrumentType: InstrumentType): number;
}
//# sourceMappingURL=MetricCollector.d.ts.map

View File

@@ -0,0 +1,178 @@
/*
* 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 __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));
};
import { millisToHrTime } from '@opentelemetry/core';
/**
* An internal opaque interface that the MetricReader receives as
* MetricProducer. It acts as the storage key to the internal metric stream
* state for each MetricReader.
*/
var MetricCollector = /** @class */ (function () {
function MetricCollector(_sharedState, _metricReader) {
this._sharedState = _sharedState;
this._metricReader = _metricReader;
}
MetricCollector.prototype.collect = function (options) {
return __awaiter(this, void 0, void 0, function () {
var collectionTime, scopeMetrics, errors, meterCollectionPromises;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
collectionTime = millisToHrTime(Date.now());
scopeMetrics = [];
errors = [];
meterCollectionPromises = Array.from(this._sharedState.meterSharedStates.values()).map(function (meterSharedState) { return __awaiter(_this, void 0, void 0, function () {
var current;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, meterSharedState.collect(this, collectionTime, options)];
case 1:
current = _a.sent();
// only add scope metrics if available
if ((current === null || current === void 0 ? void 0 : current.scopeMetrics) != null) {
scopeMetrics.push(current.scopeMetrics);
}
// only add errors if available
if ((current === null || current === void 0 ? void 0 : current.errors) != null) {
errors.push.apply(errors, __spreadArray([], __read(current.errors), false));
}
return [2 /*return*/];
}
});
}); });
return [4 /*yield*/, Promise.all(meterCollectionPromises)];
case 1:
_a.sent();
return [2 /*return*/, {
resourceMetrics: {
resource: this._sharedState.resource,
scopeMetrics: scopeMetrics,
},
errors: errors,
}];
}
});
});
};
/**
* Delegates for MetricReader.forceFlush.
*/
MetricCollector.prototype.forceFlush = function (options) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this._metricReader.forceFlush(options)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
/**
* Delegates for MetricReader.shutdown.
*/
MetricCollector.prototype.shutdown = function (options) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this._metricReader.shutdown(options)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
MetricCollector.prototype.selectAggregationTemporality = function (instrumentType) {
return this._metricReader.selectAggregationTemporality(instrumentType);
};
MetricCollector.prototype.selectAggregation = function (instrumentType) {
return this._metricReader.selectAggregation(instrumentType);
};
/**
* Select the cardinality limit for the given {@link InstrumentType} for this
* collector.
*/
MetricCollector.prototype.selectCardinalityLimit = function (instrumentType) {
var _a, _b, _c;
return (_c = (_b = (_a = this._metricReader).selectCardinalityLimit) === null || _b === void 0 ? void 0 : _b.call(_a, instrumentType)) !== null && _c !== void 0 ? _c : 2000;
};
return MetricCollector;
}());
export { MetricCollector };
//# sourceMappingURL=MetricCollector.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,24 @@
import { HrTime } from '@opentelemetry/api';
import { MetricData } from '../export/MetricData';
import { Maybe } from '../utils';
import { MetricCollectorHandle } from './MetricCollector';
import { InstrumentDescriptor } from '../InstrumentDescriptor';
/**
* Internal interface.
*
* Represents a storage from which we can collect metrics.
*/
export declare abstract class MetricStorage {
protected _instrumentDescriptor: InstrumentDescriptor;
constructor(_instrumentDescriptor: InstrumentDescriptor);
/**
* Collects the metrics from this storage.
*
* Note: This is a stateful operation and may reset any interval-related
* state for the MetricCollector.
*/
abstract collect(collector: MetricCollectorHandle, collectionTime: HrTime): Maybe<MetricData>;
getInstrumentDescriptor(): Readonly<InstrumentDescriptor>;
updateDescription(description: string): void;
}
//# sourceMappingURL=MetricStorage.d.ts.map

View File

@@ -0,0 +1,40 @@
/*
* 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, } from '../InstrumentDescriptor';
/**
* Internal interface.
*
* Represents a storage from which we can collect metrics.
*/
var MetricStorage = /** @class */ (function () {
function MetricStorage(_instrumentDescriptor) {
this._instrumentDescriptor = _instrumentDescriptor;
}
MetricStorage.prototype.getInstrumentDescriptor = function () {
return this._instrumentDescriptor;
};
MetricStorage.prototype.updateDescription = function (description) {
this._instrumentDescriptor = createInstrumentDescriptor(this._instrumentDescriptor.name, this._instrumentDescriptor.type, {
description: description,
valueType: this._instrumentDescriptor.valueType,
unit: this._instrumentDescriptor.unit,
advice: this._instrumentDescriptor.advice,
});
};
return MetricStorage;
}());
export { MetricStorage };
//# sourceMappingURL=MetricStorage.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"MetricStorage.js","sourceRoot":"","sources":["../../../src/state/MetricStorage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAMH,OAAO,EACL,0BAA0B,GAE3B,MAAM,yBAAyB,CAAC;AAEjC;;;;GAIG;AACH;IACE,uBAAsB,qBAA2C;QAA3C,0BAAqB,GAArB,qBAAqB,CAAsB;IAAG,CAAC;IAarE,+CAAuB,GAAvB;QACE,OAAO,IAAI,CAAC,qBAAqB,CAAC;IACpC,CAAC;IAED,yCAAiB,GAAjB,UAAkB,WAAmB;QACnC,IAAI,CAAC,qBAAqB,GAAG,0BAA0B,CACrD,IAAI,CAAC,qBAAqB,CAAC,IAAI,EAC/B,IAAI,CAAC,qBAAqB,CAAC,IAAI,EAC/B;YACE,WAAW,EAAE,WAAW;YACxB,SAAS,EAAE,IAAI,CAAC,qBAAqB,CAAC,SAAS;YAC/C,IAAI,EAAE,IAAI,CAAC,qBAAqB,CAAC,IAAI;YACrC,MAAM,EAAE,IAAI,CAAC,qBAAqB,CAAC,MAAM;SAC1C,CACF,CAAC;IACJ,CAAC;IACH,oBAAC;AAAD,CAAC,AA9BD,IA8BC","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 { MetricData } from '../export/MetricData';\nimport { Maybe } from '../utils';\nimport { MetricCollectorHandle } from './MetricCollector';\nimport {\n createInstrumentDescriptor,\n InstrumentDescriptor,\n} from '../InstrumentDescriptor';\n\n/**\n * Internal interface.\n *\n * Represents a storage from which we can collect metrics.\n */\nexport abstract class MetricStorage {\n constructor(protected _instrumentDescriptor: InstrumentDescriptor) {}\n\n /**\n * Collects the metrics from this storage.\n *\n * Note: This is a stateful operation and may reset any interval-related\n * state for the MetricCollector.\n */\n abstract collect(\n collector: MetricCollectorHandle,\n collectionTime: HrTime\n ): Maybe<MetricData>;\n\n getInstrumentDescriptor(): Readonly<InstrumentDescriptor> {\n return this._instrumentDescriptor;\n }\n\n updateDescription(description: string): void {\n this._instrumentDescriptor = createInstrumentDescriptor(\n this._instrumentDescriptor.name,\n this._instrumentDescriptor.type,\n {\n description: description,\n valueType: this._instrumentDescriptor.valueType,\n unit: this._instrumentDescriptor.unit,\n advice: this._instrumentDescriptor.advice,\n }\n );\n }\n}\n"]}

View File

@@ -0,0 +1,19 @@
import { MetricStorage } from './MetricStorage';
import { InstrumentDescriptor } from '../InstrumentDescriptor';
import { MetricCollectorHandle } from './MetricCollector';
/**
* Internal class for storing {@link MetricStorage}
*/
export declare class MetricStorageRegistry {
private readonly _sharedRegistry;
private readonly _perCollectorRegistry;
static create(): MetricStorageRegistry;
getStorages(collector: MetricCollectorHandle): MetricStorage[];
register(storage: MetricStorage): void;
registerForCollector(collector: MetricCollectorHandle, storage: MetricStorage): void;
findOrUpdateCompatibleStorage<T extends MetricStorage>(expectedDescriptor: InstrumentDescriptor): T | null;
findOrUpdateCompatibleCollectorStorage<T extends MetricStorage>(collector: MetricCollectorHandle, expectedDescriptor: InstrumentDescriptor): T | null;
private _registerStorage;
private _findOrUpdateCompatibleStorage;
}
//# sourceMappingURL=MetricStorageRegistry.d.ts.map

View File

@@ -0,0 +1,155 @@
/*
* 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 __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 { isDescriptorCompatibleWith, } from '../InstrumentDescriptor';
import * as api from '@opentelemetry/api';
import { getConflictResolutionRecipe, getIncompatibilityDetails, } from '../view/RegistrationConflicts';
/**
* Internal class for storing {@link MetricStorage}
*/
var MetricStorageRegistry = /** @class */ (function () {
function MetricStorageRegistry() {
this._sharedRegistry = new Map();
this._perCollectorRegistry = new Map();
}
MetricStorageRegistry.create = function () {
return new MetricStorageRegistry();
};
MetricStorageRegistry.prototype.getStorages = function (collector) {
var e_1, _a, e_2, _b;
var storages = [];
try {
for (var _c = __values(this._sharedRegistry.values()), _d = _c.next(); !_d.done; _d = _c.next()) {
var metricStorages = _d.value;
storages = storages.concat(metricStorages);
}
}
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; }
}
var perCollectorStorages = this._perCollectorRegistry.get(collector);
if (perCollectorStorages != null) {
try {
for (var _e = __values(perCollectorStorages.values()), _f = _e.next(); !_f.done; _f = _e.next()) {
var metricStorages = _f.value;
storages = storages.concat(metricStorages);
}
}
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; }
}
}
return storages;
};
MetricStorageRegistry.prototype.register = function (storage) {
this._registerStorage(storage, this._sharedRegistry);
};
MetricStorageRegistry.prototype.registerForCollector = function (collector, storage) {
var storageMap = this._perCollectorRegistry.get(collector);
if (storageMap == null) {
storageMap = new Map();
this._perCollectorRegistry.set(collector, storageMap);
}
this._registerStorage(storage, storageMap);
};
MetricStorageRegistry.prototype.findOrUpdateCompatibleStorage = function (expectedDescriptor) {
var storages = this._sharedRegistry.get(expectedDescriptor.name);
if (storages === undefined) {
return null;
}
// If the descriptor is compatible, the type of their metric storage
// (either SyncMetricStorage or AsyncMetricStorage) must be compatible.
return this._findOrUpdateCompatibleStorage(expectedDescriptor, storages);
};
MetricStorageRegistry.prototype.findOrUpdateCompatibleCollectorStorage = function (collector, expectedDescriptor) {
var storageMap = this._perCollectorRegistry.get(collector);
if (storageMap === undefined) {
return null;
}
var storages = storageMap.get(expectedDescriptor.name);
if (storages === undefined) {
return null;
}
// If the descriptor is compatible, the type of their metric storage
// (either SyncMetricStorage or AsyncMetricStorage) must be compatible.
return this._findOrUpdateCompatibleStorage(expectedDescriptor, storages);
};
MetricStorageRegistry.prototype._registerStorage = function (storage, storageMap) {
var descriptor = storage.getInstrumentDescriptor();
var storages = storageMap.get(descriptor.name);
if (storages === undefined) {
storageMap.set(descriptor.name, [storage]);
return;
}
storages.push(storage);
};
MetricStorageRegistry.prototype._findOrUpdateCompatibleStorage = function (expectedDescriptor, existingStorages) {
var e_3, _a;
var compatibleStorage = null;
try {
for (var existingStorages_1 = __values(existingStorages), existingStorages_1_1 = existingStorages_1.next(); !existingStorages_1_1.done; existingStorages_1_1 = existingStorages_1.next()) {
var existingStorage = existingStorages_1_1.value;
var existingDescriptor = existingStorage.getInstrumentDescriptor();
if (isDescriptorCompatibleWith(existingDescriptor, expectedDescriptor)) {
// Use the longer description if it does not match.
if (existingDescriptor.description !== expectedDescriptor.description) {
if (expectedDescriptor.description.length >
existingDescriptor.description.length) {
existingStorage.updateDescription(expectedDescriptor.description);
}
api.diag.warn('A view or instrument with the name ', expectedDescriptor.name, ' has already been registered, but has a different description and is incompatible with another registered view.\n', 'Details:\n', getIncompatibilityDetails(existingDescriptor, expectedDescriptor), 'The longer description will be used.\nTo resolve the conflict:', getConflictResolutionRecipe(existingDescriptor, expectedDescriptor));
}
// Storage is fully compatible. There will never be more than one pre-existing fully compatible storage.
compatibleStorage = existingStorage;
}
else {
// The implementation SHOULD warn about duplicate instrument registration
// conflicts after applying View configuration.
api.diag.warn('A view or instrument with the name ', expectedDescriptor.name, ' has already been registered and is incompatible with another registered view.\n', 'Details:\n', getIncompatibilityDetails(existingDescriptor, expectedDescriptor), 'To resolve the conflict:\n', getConflictResolutionRecipe(existingDescriptor, expectedDescriptor));
}
}
}
catch (e_3_1) { e_3 = { error: e_3_1 }; }
finally {
try {
if (existingStorages_1_1 && !existingStorages_1_1.done && (_a = existingStorages_1.return)) _a.call(existingStorages_1);
}
finally { if (e_3) throw e_3.error; }
}
return compatibleStorage;
};
return MetricStorageRegistry;
}());
export { MetricStorageRegistry };
//# sourceMappingURL=MetricStorageRegistry.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,11 @@
import { Context, HrTime, Attributes } from '@opentelemetry/api';
import { WritableMetricStorage } from './WritableMetricStorage';
/**
* Internal interface.
*/
export declare class MultiMetricStorage implements WritableMetricStorage {
private readonly _backingStorages;
constructor(_backingStorages: WritableMetricStorage[]);
record(value: number, attributes: Attributes, context: Context, recordTime: HrTime): void;
}
//# sourceMappingURL=MultiWritableMetricStorage.d.ts.map

View File

@@ -0,0 +1,31 @@
/*
* 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.
*/
/**
* Internal interface.
*/
var MultiMetricStorage = /** @class */ (function () {
function MultiMetricStorage(_backingStorages) {
this._backingStorages = _backingStorages;
}
MultiMetricStorage.prototype.record = function (value, attributes, context, recordTime) {
this._backingStorages.forEach(function (it) {
it.record(value, attributes, context, recordTime);
});
};
return MultiMetricStorage;
}());
export { MultiMetricStorage };
//# sourceMappingURL=MultiWritableMetricStorage.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"MultiWritableMetricStorage.js","sourceRoot":"","sources":["../../../src/state/MultiWritableMetricStorage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAKH;;GAEG;AACH;IACE,4BAA6B,gBAAyC;QAAzC,qBAAgB,GAAhB,gBAAgB,CAAyB;IAAG,CAAC;IAE1E,mCAAM,GAAN,UACE,KAAa,EACb,UAAsB,EACtB,OAAgB,EAChB,UAAkB;QAElB,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,UAAA,EAAE;YAC9B,EAAE,CAAC,MAAM,CAAC,KAAK,EAAE,UAAU,EAAE,OAAO,EAAE,UAAU,CAAC,CAAC;QACpD,CAAC,CAAC,CAAC;IACL,CAAC;IACH,yBAAC;AAAD,CAAC,AAbD,IAaC","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 { WritableMetricStorage } from './WritableMetricStorage';\n\n/**\n * Internal interface.\n */\nexport class MultiMetricStorage implements WritableMetricStorage {\n constructor(private readonly _backingStorages: WritableMetricStorage[]) {}\n\n record(\n value: number,\n attributes: Attributes,\n context: Context,\n recordTime: HrTime\n ) {\n this._backingStorages.forEach(it => {\n it.record(value, attributes, context, recordTime);\n });\n }\n}\n"]}

View File

@@ -0,0 +1,25 @@
import { HrTime, BatchObservableCallback, Observable, ObservableCallback } from '@opentelemetry/api';
import { ObservableInstrument } from '../Instruments';
/**
* An internal interface for managing ObservableCallbacks.
*
* Every registered callback associated with a set of instruments are be evaluated
* exactly once during collection prior to reading data for that instrument.
*/
export declare class ObservableRegistry {
private _callbacks;
private _batchCallbacks;
addCallback(callback: ObservableCallback, instrument: ObservableInstrument): void;
removeCallback(callback: ObservableCallback, instrument: ObservableInstrument): void;
addBatchCallback(callback: BatchObservableCallback, instruments: Observable[]): void;
removeBatchCallback(callback: BatchObservableCallback, instruments: Observable[]): void;
/**
* @returns a promise of rejected reasons for invoking callbacks.
*/
observe(collectionTime: HrTime, timeoutMillis?: number): Promise<unknown[]>;
private _observeCallbacks;
private _observeBatchCallbacks;
private _findCallback;
private _findBatchCallback;
}
//# sourceMappingURL=ObservableRegistry.d.ts.map

View File

@@ -0,0 +1,222 @@
/*
* 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 __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));
};
import { diag, } from '@opentelemetry/api';
import { isObservableInstrument } from '../Instruments';
import { BatchObservableResultImpl, ObservableResultImpl, } from '../ObservableResult';
import { callWithTimeout, PromiseAllSettled, isPromiseAllSettledRejectionResult, setEquals, } from '../utils';
/**
* An internal interface for managing ObservableCallbacks.
*
* Every registered callback associated with a set of instruments are be evaluated
* exactly once during collection prior to reading data for that instrument.
*/
var ObservableRegistry = /** @class */ (function () {
function ObservableRegistry() {
this._callbacks = [];
this._batchCallbacks = [];
}
ObservableRegistry.prototype.addCallback = function (callback, instrument) {
var idx = this._findCallback(callback, instrument);
if (idx >= 0) {
return;
}
this._callbacks.push({ callback: callback, instrument: instrument });
};
ObservableRegistry.prototype.removeCallback = function (callback, instrument) {
var idx = this._findCallback(callback, instrument);
if (idx < 0) {
return;
}
this._callbacks.splice(idx, 1);
};
ObservableRegistry.prototype.addBatchCallback = function (callback, instruments) {
// Create a set of unique instruments.
var observableInstruments = new Set(instruments.filter(isObservableInstrument));
if (observableInstruments.size === 0) {
diag.error('BatchObservableCallback is not associated with valid instruments', instruments);
return;
}
var idx = this._findBatchCallback(callback, observableInstruments);
if (idx >= 0) {
return;
}
this._batchCallbacks.push({ callback: callback, instruments: observableInstruments });
};
ObservableRegistry.prototype.removeBatchCallback = function (callback, instruments) {
// Create a set of unique instruments.
var observableInstruments = new Set(instruments.filter(isObservableInstrument));
var idx = this._findBatchCallback(callback, observableInstruments);
if (idx < 0) {
return;
}
this._batchCallbacks.splice(idx, 1);
};
/**
* @returns a promise of rejected reasons for invoking callbacks.
*/
ObservableRegistry.prototype.observe = function (collectionTime, timeoutMillis) {
return __awaiter(this, void 0, void 0, function () {
var callbackFutures, batchCallbackFutures, results, rejections;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
callbackFutures = this._observeCallbacks(collectionTime, timeoutMillis);
batchCallbackFutures = this._observeBatchCallbacks(collectionTime, timeoutMillis);
return [4 /*yield*/, PromiseAllSettled(__spreadArray(__spreadArray([], __read(callbackFutures), false), __read(batchCallbackFutures), false))];
case 1:
results = _a.sent();
rejections = results
.filter(isPromiseAllSettledRejectionResult)
.map(function (it) { return it.reason; });
return [2 /*return*/, rejections];
}
});
});
};
ObservableRegistry.prototype._observeCallbacks = function (observationTime, timeoutMillis) {
var _this = this;
return this._callbacks.map(function (_a) {
var callback = _a.callback, instrument = _a.instrument;
return __awaiter(_this, void 0, void 0, function () {
var observableResult, callPromise;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
observableResult = new ObservableResultImpl(instrument._descriptor.name, instrument._descriptor.valueType);
callPromise = Promise.resolve(callback(observableResult));
if (timeoutMillis != null) {
callPromise = callWithTimeout(callPromise, timeoutMillis);
}
return [4 /*yield*/, callPromise];
case 1:
_b.sent();
instrument._metricStorages.forEach(function (metricStorage) {
metricStorage.record(observableResult._buffer, observationTime);
});
return [2 /*return*/];
}
});
});
});
};
ObservableRegistry.prototype._observeBatchCallbacks = function (observationTime, timeoutMillis) {
var _this = this;
return this._batchCallbacks.map(function (_a) {
var callback = _a.callback, instruments = _a.instruments;
return __awaiter(_this, void 0, void 0, function () {
var observableResult, callPromise;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
observableResult = new BatchObservableResultImpl();
callPromise = Promise.resolve(callback(observableResult));
if (timeoutMillis != null) {
callPromise = callWithTimeout(callPromise, timeoutMillis);
}
return [4 /*yield*/, callPromise];
case 1:
_b.sent();
instruments.forEach(function (instrument) {
var buffer = observableResult._buffer.get(instrument);
if (buffer == null) {
return;
}
instrument._metricStorages.forEach(function (metricStorage) {
metricStorage.record(buffer, observationTime);
});
});
return [2 /*return*/];
}
});
});
});
};
ObservableRegistry.prototype._findCallback = function (callback, instrument) {
return this._callbacks.findIndex(function (record) {
return record.callback === callback && record.instrument === instrument;
});
};
ObservableRegistry.prototype._findBatchCallback = function (callback, instruments) {
return this._batchCallbacks.findIndex(function (record) {
return (record.callback === callback &&
setEquals(record.instruments, instruments));
});
};
return ObservableRegistry;
}());
export { ObservableRegistry };
//# sourceMappingURL=ObservableRegistry.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,30 @@
import { Context, HrTime, Attributes } from '@opentelemetry/api';
import { WritableMetricStorage } from './WritableMetricStorage';
import { Accumulation, Aggregator } from '../aggregator/types';
import { InstrumentDescriptor } from '../InstrumentDescriptor';
import { AttributesProcessor } from '../view/AttributesProcessor';
import { MetricStorage } from './MetricStorage';
import { MetricData } from '../export/MetricData';
import { Maybe } from '../utils';
import { MetricCollectorHandle } from './MetricCollector';
/**
* Internal interface.
*
* Stores and aggregates {@link MetricData} for synchronous instruments.
*/
export declare class SyncMetricStorage<T extends Maybe<Accumulation>> extends MetricStorage implements WritableMetricStorage {
private _attributesProcessor;
private _aggregationCardinalityLimit?;
private _deltaMetricStorage;
private _temporalMetricStorage;
constructor(instrumentDescriptor: InstrumentDescriptor, aggregator: Aggregator<T>, _attributesProcessor: AttributesProcessor, collectorHandles: MetricCollectorHandle[], _aggregationCardinalityLimit?: number | undefined);
record(value: number, attributes: Attributes, context: Context, recordTime: HrTime): void;
/**
* Collects the metrics from this storage.
*
* Note: This is a stateful operation and may reset any interval-related
* state for the MetricCollector.
*/
collect(collector: MetricCollectorHandle, collectionTime: HrTime): Maybe<MetricData>;
}
//# sourceMappingURL=SyncMetricStorage.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 { MetricStorage } from './MetricStorage';
import { DeltaMetricProcessor } from './DeltaMetricProcessor';
import { TemporalMetricProcessor } from './TemporalMetricProcessor';
/**
* Internal interface.
*
* Stores and aggregates {@link MetricData} for synchronous instruments.
*/
var SyncMetricStorage = /** @class */ (function (_super) {
__extends(SyncMetricStorage, _super);
function SyncMetricStorage(instrumentDescriptor, aggregator, _attributesProcessor, collectorHandles, _aggregationCardinalityLimit) {
var _this = _super.call(this, instrumentDescriptor) || this;
_this._attributesProcessor = _attributesProcessor;
_this._aggregationCardinalityLimit = _aggregationCardinalityLimit;
_this._deltaMetricStorage = new DeltaMetricProcessor(aggregator, _this._aggregationCardinalityLimit);
_this._temporalMetricStorage = new TemporalMetricProcessor(aggregator, collectorHandles);
return _this;
}
SyncMetricStorage.prototype.record = function (value, attributes, context, recordTime) {
attributes = this._attributesProcessor.process(attributes, context);
this._deltaMetricStorage.record(value, attributes, context, recordTime);
};
/**
* Collects the metrics from this storage.
*
* Note: This is a stateful operation and may reset any interval-related
* state for the MetricCollector.
*/
SyncMetricStorage.prototype.collect = function (collector, collectionTime) {
var accumulations = this._deltaMetricStorage.collect();
return this._temporalMetricStorage.buildMetrics(collector, this._instrumentDescriptor, accumulations, collectionTime);
};
return SyncMetricStorage;
}(MetricStorage));
export { SyncMetricStorage };
//# sourceMappingURL=SyncMetricStorage.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"SyncMetricStorage.js","sourceRoot":"","sources":["../../../src/state/SyncMetricStorage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;AAOH,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAIpE;;;;GAIG;AACH;IACU,qCAAa;IAMrB,2BACE,oBAA0C,EAC1C,UAAyB,EACjB,oBAAyC,EACjD,gBAAyC,EACjC,4BAAqC;QAL/C,YAOE,kBAAM,oBAAoB,CAAC,SAS5B;QAbS,0BAAoB,GAApB,oBAAoB,CAAqB;QAEzC,kCAA4B,GAA5B,4BAA4B,CAAS;QAG7C,KAAI,CAAC,mBAAmB,GAAG,IAAI,oBAAoB,CACjD,UAAU,EACV,KAAI,CAAC,4BAA4B,CAClC,CAAC;QACF,KAAI,CAAC,sBAAsB,GAAG,IAAI,uBAAuB,CACvD,UAAU,EACV,gBAAgB,CACjB,CAAC;;IACJ,CAAC;IAED,kCAAM,GAAN,UACE,KAAa,EACb,UAAsB,EACtB,OAAgB,EAChB,UAAkB;QAElB,UAAU,GAAG,IAAI,CAAC,oBAAoB,CAAC,OAAO,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QACpE,IAAI,CAAC,mBAAmB,CAAC,MAAM,CAAC,KAAK,EAAE,UAAU,EAAE,OAAO,EAAE,UAAU,CAAC,CAAC;IAC1E,CAAC;IAED;;;;;OAKG;IACH,mCAAO,GAAP,UACE,SAAgC,EAChC,cAAsB;QAEtB,IAAM,aAAa,GAAG,IAAI,CAAC,mBAAmB,CAAC,OAAO,EAAE,CAAC;QAEzD,OAAO,IAAI,CAAC,sBAAsB,CAAC,YAAY,CAC7C,SAAS,EACT,IAAI,CAAC,qBAAqB,EAC1B,aAAa,EACb,cAAc,CACf,CAAC;IACJ,CAAC;IACH,wBAAC;AAAD,CAAC,AAtDD,CACU,aAAa,GAqDtB","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 { WritableMetricStorage } from './WritableMetricStorage';\nimport { Accumulation, Aggregator } from '../aggregator/types';\nimport { InstrumentDescriptor } from '../InstrumentDescriptor';\nimport { AttributesProcessor } from '../view/AttributesProcessor';\nimport { MetricStorage } from './MetricStorage';\nimport { MetricData } from '../export/MetricData';\nimport { DeltaMetricProcessor } from './DeltaMetricProcessor';\nimport { TemporalMetricProcessor } from './TemporalMetricProcessor';\nimport { Maybe } from '../utils';\nimport { MetricCollectorHandle } from './MetricCollector';\n\n/**\n * Internal interface.\n *\n * Stores and aggregates {@link MetricData} for synchronous instruments.\n */\nexport class SyncMetricStorage<T extends Maybe<Accumulation>>\n extends MetricStorage\n implements WritableMetricStorage\n{\n private _deltaMetricStorage: DeltaMetricProcessor<T>;\n private _temporalMetricStorage: TemporalMetricProcessor<T>;\n\n constructor(\n instrumentDescriptor: InstrumentDescriptor,\n aggregator: Aggregator<T>,\n private _attributesProcessor: AttributesProcessor,\n collectorHandles: MetricCollectorHandle[],\n private _aggregationCardinalityLimit?: number\n ) {\n super(instrumentDescriptor);\n this._deltaMetricStorage = new DeltaMetricProcessor(\n aggregator,\n this._aggregationCardinalityLimit\n );\n this._temporalMetricStorage = new TemporalMetricProcessor(\n aggregator,\n collectorHandles\n );\n }\n\n record(\n value: number,\n attributes: Attributes,\n context: Context,\n recordTime: HrTime\n ) {\n attributes = this._attributesProcessor.process(attributes, context);\n this._deltaMetricStorage.record(value, attributes, context, recordTime);\n }\n\n /**\n * Collects the metrics from this storage.\n *\n * Note: This is a stateful operation and may reset any interval-related\n * state for the MetricCollector.\n */\n collect(\n collector: MetricCollectorHandle,\n collectionTime: HrTime\n ): Maybe<MetricData> {\n const accumulations = this._deltaMetricStorage.collect();\n\n return this._temporalMetricStorage.buildMetrics(\n collector,\n this._instrumentDescriptor,\n accumulations,\n collectionTime\n );\n }\n}\n"]}

View File

@@ -0,0 +1,38 @@
import { HrTime } from '@opentelemetry/api';
import { Accumulation, Aggregator } from '../aggregator/types';
import { MetricData } from '../export/MetricData';
import { InstrumentDescriptor } from '../InstrumentDescriptor';
import { Maybe } from '../utils';
import { MetricCollectorHandle } from './MetricCollector';
import { AttributeHashMap } from './HashMap';
/**
* Internal interface.
*
* Provides unique reporting for each collector. Allows synchronous collection
* of metrics and reports given temporality values.
*/
export declare class TemporalMetricProcessor<T extends Maybe<Accumulation>> {
private _aggregator;
private _unreportedAccumulations;
private _reportHistory;
constructor(_aggregator: Aggregator<T>, collectorHandles: MetricCollectorHandle[]);
/**
* Builds the {@link MetricData} streams to report against a specific MetricCollector.
* @param collector The information of the MetricCollector.
* @param collectors The registered collectors.
* @param instrumentDescriptor The instrumentation descriptor that these metrics generated with.
* @param currentAccumulations The current accumulation of metric data from instruments.
* @param collectionTime The current collection timestamp.
* @returns The {@link MetricData} points or `null`.
*/
buildMetrics(collector: MetricCollectorHandle, instrumentDescriptor: InstrumentDescriptor, currentAccumulations: AttributeHashMap<T>, collectionTime: HrTime): Maybe<MetricData>;
private _stashAccumulations;
private _getMergedUnreportedAccumulations;
static merge<T extends Maybe<Accumulation>>(last: AttributeHashMap<T>, current: AttributeHashMap<T>, aggregator: Aggregator<T>): AttributeHashMap<T>;
/**
* Calibrate the reported metric streams' startTime to lastCollectionTime. Leaves
* the new stream to be the initial observation time unchanged.
*/
static calibrateStartTime<T extends Maybe<Accumulation>>(last: AttributeHashMap<T>, current: AttributeHashMap<T>, lastCollectionTime: HrTime): AttributeHashMap<T>;
}
//# sourceMappingURL=TemporalMetricProcessor.d.ts.map

View File

@@ -0,0 +1,214 @@
/*
* 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 __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.");
};
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 { AggregationTemporality } from '../export/AggregationTemporality';
import { AttributeHashMap } from './HashMap';
/**
* Internal interface.
*
* Provides unique reporting for each collector. Allows synchronous collection
* of metrics and reports given temporality values.
*/
var TemporalMetricProcessor = /** @class */ (function () {
function TemporalMetricProcessor(_aggregator, collectorHandles) {
var _this = this;
this._aggregator = _aggregator;
this._unreportedAccumulations = new Map();
this._reportHistory = new Map();
collectorHandles.forEach(function (handle) {
_this._unreportedAccumulations.set(handle, []);
});
}
/**
* Builds the {@link MetricData} streams to report against a specific MetricCollector.
* @param collector The information of the MetricCollector.
* @param collectors The registered collectors.
* @param instrumentDescriptor The instrumentation descriptor that these metrics generated with.
* @param currentAccumulations The current accumulation of metric data from instruments.
* @param collectionTime The current collection timestamp.
* @returns The {@link MetricData} points or `null`.
*/
TemporalMetricProcessor.prototype.buildMetrics = function (collector, instrumentDescriptor, currentAccumulations, collectionTime) {
this._stashAccumulations(currentAccumulations);
var unreportedAccumulations = this._getMergedUnreportedAccumulations(collector);
var result = unreportedAccumulations;
var aggregationTemporality;
// Check our last report time.
if (this._reportHistory.has(collector)) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
var last = this._reportHistory.get(collector);
var lastCollectionTime = last.collectionTime;
aggregationTemporality = last.aggregationTemporality;
// Use aggregation temporality + instrument to determine if we do a merge or a diff of
// previous. We have the following four scenarios:
// 1. Cumulative Aggregation (temporality) + Delta recording (sync instrument).
// Here we merge with our last record to get a cumulative aggregation.
// 2. Cumulative Aggregation + Cumulative recording (async instrument).
// Cumulative records are converted to delta recording with DeltaMetricProcessor.
// Here we merge with our last record to get a cumulative aggregation.
// 3. Delta Aggregation + Delta recording
// Calibrate the startTime of metric streams to be the reader's lastCollectionTime.
// 4. Delta Aggregation + Cumulative recording.
// Cumulative records are converted to delta recording with DeltaMetricProcessor.
// Calibrate the startTime of metric streams to be the reader's lastCollectionTime.
if (aggregationTemporality === AggregationTemporality.CUMULATIVE) {
// We need to make sure the current delta recording gets merged into the previous cumulative
// for the next cumulative recording.
result = TemporalMetricProcessor.merge(last.accumulations, unreportedAccumulations, this._aggregator);
}
else {
result = TemporalMetricProcessor.calibrateStartTime(last.accumulations, unreportedAccumulations, lastCollectionTime);
}
}
else {
// Call into user code to select aggregation temporality for the instrument.
aggregationTemporality = collector.selectAggregationTemporality(instrumentDescriptor.type);
}
// Update last reported (cumulative) accumulation.
this._reportHistory.set(collector, {
accumulations: result,
collectionTime: collectionTime,
aggregationTemporality: aggregationTemporality,
});
var accumulationRecords = AttributesMapToAccumulationRecords(result);
// do not convert to metric data if there is nothing to convert.
if (accumulationRecords.length === 0) {
return undefined;
}
return this._aggregator.toMetricData(instrumentDescriptor, aggregationTemporality, accumulationRecords,
/* endTime */ collectionTime);
};
TemporalMetricProcessor.prototype._stashAccumulations = function (currentAccumulation) {
var e_1, _a;
var registeredCollectors = this._unreportedAccumulations.keys();
try {
for (var registeredCollectors_1 = __values(registeredCollectors), registeredCollectors_1_1 = registeredCollectors_1.next(); !registeredCollectors_1_1.done; registeredCollectors_1_1 = registeredCollectors_1.next()) {
var collector = registeredCollectors_1_1.value;
var stash = this._unreportedAccumulations.get(collector);
if (stash === undefined) {
stash = [];
this._unreportedAccumulations.set(collector, stash);
}
stash.push(currentAccumulation);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (registeredCollectors_1_1 && !registeredCollectors_1_1.done && (_a = registeredCollectors_1.return)) _a.call(registeredCollectors_1);
}
finally { if (e_1) throw e_1.error; }
}
};
TemporalMetricProcessor.prototype._getMergedUnreportedAccumulations = function (collector) {
var e_2, _a;
var result = new AttributeHashMap();
var unreportedList = this._unreportedAccumulations.get(collector);
this._unreportedAccumulations.set(collector, []);
if (unreportedList === undefined) {
return result;
}
try {
for (var unreportedList_1 = __values(unreportedList), unreportedList_1_1 = unreportedList_1.next(); !unreportedList_1_1.done; unreportedList_1_1 = unreportedList_1.next()) {
var it_1 = unreportedList_1_1.value;
result = TemporalMetricProcessor.merge(result, it_1, this._aggregator);
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (unreportedList_1_1 && !unreportedList_1_1.done && (_a = unreportedList_1.return)) _a.call(unreportedList_1);
}
finally { if (e_2) throw e_2.error; }
}
return result;
};
TemporalMetricProcessor.merge = function (last, current, aggregator) {
var result = last;
var iterator = current.entries();
var next = iterator.next();
while (next.done !== true) {
var _a = __read(next.value, 3), key = _a[0], record = _a[1], hash = _a[2];
if (last.has(key, hash)) {
var lastAccumulation = last.get(key, hash);
// last.has() returned true, lastAccumulation is present.
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
var accumulation = aggregator.merge(lastAccumulation, record);
result.set(key, accumulation, hash);
}
else {
result.set(key, record, hash);
}
next = iterator.next();
}
return result;
};
/**
* Calibrate the reported metric streams' startTime to lastCollectionTime. Leaves
* the new stream to be the initial observation time unchanged.
*/
TemporalMetricProcessor.calibrateStartTime = function (last, current, lastCollectionTime) {
var e_3, _a;
try {
for (var _b = __values(last.keys()), _c = _b.next(); !_c.done; _c = _b.next()) {
var _d = __read(_c.value, 2), key = _d[0], hash = _d[1];
var currentAccumulation = current.get(key, hash);
currentAccumulation === null || currentAccumulation === void 0 ? void 0 : currentAccumulation.setStartTime(lastCollectionTime);
}
}
catch (e_3_1) { e_3 = { error: e_3_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_3) throw e_3.error; }
}
return current;
};
return TemporalMetricProcessor;
}());
export { TemporalMetricProcessor };
// TypeScript complains about converting 3 elements tuple to AccumulationRecord<T>.
function AttributesMapToAccumulationRecords(map) {
return Array.from(map.entries());
}
//# sourceMappingURL=TemporalMetricProcessor.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,23 @@
import { Context, HrTime, Attributes } from '@opentelemetry/api';
import { AttributeHashMap } from './HashMap';
/**
* Internal interface. Stores measurements and allows synchronous writes of
* measurements.
*
* An interface representing SyncMetricStorage with type parameters removed.
*/
export interface WritableMetricStorage {
/** Records a measurement. */
record(value: number, attributes: Attributes, context: Context, recordTime: HrTime): void;
}
/**
* Internal interface. Stores measurements and allows asynchronous writes of
* measurements.
*
* An interface representing AsyncMetricStorage with type parameters removed.
*/
export interface AsyncWritableMetricStorage {
/** Records a batch of measurements. */
record(measurements: AttributeHashMap<number>, observationTime: HrTime): void;
}
//# sourceMappingURL=WritableMetricStorage.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=WritableMetricStorage.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"WritableMetricStorage.js","sourceRoot":"","sources":["../../../src/state/WritableMetricStorage.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';\nimport { AttributeHashMap } from './HashMap';\n\n/**\n * Internal interface. Stores measurements and allows synchronous writes of\n * measurements.\n *\n * An interface representing SyncMetricStorage with type parameters removed.\n */\nexport interface WritableMetricStorage {\n /** Records a measurement. */\n record(\n value: number,\n attributes: Attributes,\n context: Context,\n recordTime: HrTime\n ): void;\n}\n\n/**\n * Internal interface. Stores measurements and allows asynchronous writes of\n * measurements.\n *\n * An interface representing AsyncMetricStorage with type parameters removed.\n */\nexport interface AsyncWritableMetricStorage {\n /** Records a batch of measurements. */\n record(measurements: AttributeHashMap<number>, observationTime: HrTime): void;\n}\n"]}