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

View File

@@ -0,0 +1,20 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Aggregation } from '../view/Aggregation';
import { AggregationTemporality } from './AggregationTemporality';
export var DEFAULT_AGGREGATION_SELECTOR = function (_instrumentType) { return Aggregation.Default(); };
export var DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = function (_instrumentType) { return AggregationTemporality.CUMULATIVE; };
//# sourceMappingURL=AggregationSelector.js.map

View File

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

View File

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

View File

@@ -0,0 +1,24 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* AggregationTemporality indicates the way additive quantities are expressed.
*/
export var AggregationTemporality;
(function (AggregationTemporality) {
AggregationTemporality[AggregationTemporality["DELTA"] = 0] = "DELTA";
AggregationTemporality[AggregationTemporality["CUMULATIVE"] = 1] = "CUMULATIVE";
})(AggregationTemporality || (AggregationTemporality = {}));
//# sourceMappingURL=AggregationTemporality.js.map

View File

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

View File

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

View File

@@ -0,0 +1,17 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export {};
//# sourceMappingURL=CardinalitySelector.js.map

View File

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

View File

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

View File

@@ -0,0 +1,97 @@
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ExportResultCode } from '@opentelemetry/core';
import { DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR, } from './AggregationSelector';
/**
* This is an implementation of {@link PushMetricExporter} that prints metrics to the
* console. This class can be used for diagnostic purposes.
*
* NOTE: This {@link PushMetricExporter} is intended for diagnostics use only, output rendered to the console may change at any time.
*/
/* eslint-disable no-console */
var ConsoleMetricExporter = /** @class */ (function () {
function ConsoleMetricExporter(options) {
var _a;
this._shutdown = false;
this._temporalitySelector =
(_a = options === null || options === void 0 ? void 0 : options.temporalitySelector) !== null && _a !== void 0 ? _a : DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR;
}
ConsoleMetricExporter.prototype.export = function (metrics, resultCallback) {
if (this._shutdown) {
// If the exporter is shutting down, by spec, we need to return FAILED as export result
setImmediate(resultCallback, { code: ExportResultCode.FAILED });
return;
}
return ConsoleMetricExporter._sendMetrics(metrics, resultCallback);
};
ConsoleMetricExporter.prototype.forceFlush = function () {
return Promise.resolve();
};
ConsoleMetricExporter.prototype.selectAggregationTemporality = function (_instrumentType) {
return this._temporalitySelector(_instrumentType);
};
ConsoleMetricExporter.prototype.shutdown = function () {
this._shutdown = true;
return Promise.resolve();
};
ConsoleMetricExporter._sendMetrics = function (metrics, done) {
var e_1, _a, e_2, _b;
try {
for (var _c = __values(metrics.scopeMetrics), _d = _c.next(); !_d.done; _d = _c.next()) {
var scopeMetrics = _d.value;
try {
for (var _e = (e_2 = void 0, __values(scopeMetrics.metrics)), _f = _e.next(); !_f.done; _f = _e.next()) {
var metric = _f.value;
console.dir({
descriptor: metric.descriptor,
dataPointType: metric.dataPointType,
dataPoints: metric.dataPoints,
}, { depth: null });
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
}
finally { if (e_2) throw e_2.error; }
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
}
finally { if (e_1) throw e_1.error; }
}
done({ code: ExportResultCode.SUCCESS });
};
return ConsoleMetricExporter;
}());
export { ConsoleMetricExporter };
//# sourceMappingURL=ConsoleMetricExporter.js.map

View File

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

View File

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

View File

@@ -0,0 +1,63 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ExportResultCode } from '@opentelemetry/core';
/**
* In-memory Metrics Exporter is a Push Metric Exporter
* which accumulates metrics data in the local memory and
* allows to inspect it (useful for e.g. unit tests).
*/
var InMemoryMetricExporter = /** @class */ (function () {
function InMemoryMetricExporter(aggregationTemporality) {
this._shutdown = false;
this._metrics = [];
this._aggregationTemporality = aggregationTemporality;
}
/**
* @inheritedDoc
*/
InMemoryMetricExporter.prototype.export = function (metrics, resultCallback) {
// Avoid storing metrics when exporter is shutdown
if (this._shutdown) {
setTimeout(function () { return resultCallback({ code: ExportResultCode.FAILED }); }, 0);
return;
}
this._metrics.push(metrics);
setTimeout(function () { return resultCallback({ code: ExportResultCode.SUCCESS }); }, 0);
};
/**
* Returns all the collected resource metrics
* @returns ResourceMetrics[]
*/
InMemoryMetricExporter.prototype.getMetrics = function () {
return this._metrics;
};
InMemoryMetricExporter.prototype.forceFlush = function () {
return Promise.resolve();
};
InMemoryMetricExporter.prototype.reset = function () {
this._metrics = [];
};
InMemoryMetricExporter.prototype.selectAggregationTemporality = function (_instrumentType) {
return this._aggregationTemporality;
};
InMemoryMetricExporter.prototype.shutdown = function () {
this._shutdown = true;
return Promise.resolve();
};
return InMemoryMetricExporter;
}());
export { InMemoryMetricExporter };
//# sourceMappingURL=InMemoryMetricExporter.js.map

View File

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

View File

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

View File

@@ -0,0 +1,44 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* The aggregated point data type.
*/
export var DataPointType;
(function (DataPointType) {
/**
* A histogram data point contains a histogram statistics of collected
* values with a list of explicit bucket boundaries and statistics such
* as min, max, count, and sum of all collected values.
*/
DataPointType[DataPointType["HISTOGRAM"] = 0] = "HISTOGRAM";
/**
* An exponential histogram data point contains a histogram statistics of
* collected values where bucket boundaries are automatically calculated
* using an exponential function, and statistics such as min, max, count,
* and sum of all collected values.
*/
DataPointType[DataPointType["EXPONENTIAL_HISTOGRAM"] = 1] = "EXPONENTIAL_HISTOGRAM";
/**
* A gauge metric data point has only a single numeric value.
*/
DataPointType[DataPointType["GAUGE"] = 2] = "GAUGE";
/**
* A sum metric data point has a single numeric value and a
* monotonicity-indicator.
*/
DataPointType[DataPointType["SUM"] = 3] = "SUM";
})(DataPointType || (DataPointType = {}));
//# sourceMappingURL=MetricData.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,41 @@
import { AggregationTemporality } from './AggregationTemporality';
import { ResourceMetrics } from './MetricData';
import { ExportResult } from '@opentelemetry/core';
import { InstrumentType } from '../InstrumentDescriptor';
import { Aggregation } from '../view/Aggregation';
/**
* An interface that allows different metric services to export recorded data
* in their own format.
*
* To export data this MUST be registered to the Metrics SDK with a MetricReader.
*/
export interface PushMetricExporter {
/**
* Called to export sampled {@link ResourceMetrics}.
* @param metrics the metric data to be exported.
* @param resultCallback callback for when the export has completed
*/
export(metrics: ResourceMetrics, resultCallback: (result: ExportResult) => void): void;
/**
* Ensure that the export of any metrics the exporter has received is
* completed before the returned promise is settled.
*/
forceFlush(): Promise<void>;
/**
* Select the {@link AggregationTemporality} for the given
* {@link InstrumentType} for this exporter.
*/
selectAggregationTemporality?(instrumentType: InstrumentType): AggregationTemporality;
/**
* Select the {@link Aggregation} for the given
* {@link InstrumentType} for this exporter.
*/
selectAggregation?(instrumentType: InstrumentType): Aggregation;
/**
* Returns a promise which resolves when the last exportation is completed.
* Further calls to {@link PushMetricExporter.export} may not export the
* data.
*/
shutdown(): Promise<void>;
}
//# sourceMappingURL=MetricExporter.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=MetricExporter.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"MetricExporter.js","sourceRoot":"","sources":["../../../src/export/MetricExporter.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 { AggregationTemporality } from './AggregationTemporality';\nimport { ResourceMetrics } from './MetricData';\nimport { ExportResult } from '@opentelemetry/core';\nimport { InstrumentType } from '../InstrumentDescriptor';\nimport { Aggregation } from '../view/Aggregation';\n\n/**\n * An interface that allows different metric services to export recorded data\n * in their own format.\n *\n * To export data this MUST be registered to the Metrics SDK with a MetricReader.\n */\nexport interface PushMetricExporter {\n /**\n * Called to export sampled {@link ResourceMetrics}.\n * @param metrics the metric data to be exported.\n * @param resultCallback callback for when the export has completed\n */\n export(\n metrics: ResourceMetrics,\n resultCallback: (result: ExportResult) => void\n ): void;\n\n /**\n * Ensure that the export of any metrics the exporter has received is\n * completed before the returned promise is settled.\n */\n forceFlush(): Promise<void>;\n\n /**\n * Select the {@link AggregationTemporality} for the given\n * {@link InstrumentType} for this exporter.\n */\n selectAggregationTemporality?(\n instrumentType: InstrumentType\n ): AggregationTemporality;\n\n /**\n * Select the {@link Aggregation} for the given\n * {@link InstrumentType} for this exporter.\n */\n selectAggregation?(instrumentType: InstrumentType): Aggregation;\n\n /**\n * Returns a promise which resolves when the last exportation is completed.\n * Further calls to {@link PushMetricExporter.export} may not export the\n * data.\n */\n shutdown(): Promise<void>;\n}\n"]}

View File

@@ -0,0 +1,23 @@
import { CollectionResult } from './MetricData';
export interface MetricCollectOptions {
/**
* Timeout for the SDK to perform the involved asynchronous callback
* functions.
*
* If the callback functions failed to finish the observation in time,
* their results are discarded and an error is appended in the
* {@link CollectionResult.errors}.
*/
timeoutMillis?: number;
}
/**
* This is a public interface that represent an export state of a MetricReader.
*/
export interface MetricProducer {
/**
* Collects the metrics from the SDK. If there are asynchronous Instruments
* involved, their callback functions will be triggered.
*/
collect(options?: MetricCollectOptions): Promise<CollectionResult>;
}
//# sourceMappingURL=MetricProducer.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=MetricProducer.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"MetricProducer.js","sourceRoot":"","sources":["../../../src/export/MetricProducer.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 { CollectionResult } from './MetricData';\n\nexport interface MetricCollectOptions {\n /**\n * Timeout for the SDK to perform the involved asynchronous callback\n * functions.\n *\n * If the callback functions failed to finish the observation in time,\n * their results are discarded and an error is appended in the\n * {@link CollectionResult.errors}.\n */\n timeoutMillis?: number;\n}\n\n/**\n * This is a public interface that represent an export state of a MetricReader.\n */\nexport interface MetricProducer {\n /**\n * Collects the metrics from the SDK. If there are asynchronous Instruments\n * involved, their callback functions will be triggered.\n */\n collect(options?: MetricCollectOptions): Promise<CollectionResult>;\n}\n"]}

View File

@@ -0,0 +1,111 @@
import { AggregationTemporality } from './AggregationTemporality';
import { MetricProducer } from './MetricProducer';
import { CollectionResult } from './MetricData';
import { InstrumentType } from '../InstrumentDescriptor';
import { CollectionOptions, ForceFlushOptions, ShutdownOptions } from '../types';
import { Aggregation } from '../view/Aggregation';
import { AggregationSelector, AggregationTemporalitySelector } from './AggregationSelector';
import { CardinalitySelector } from './CardinalitySelector';
export interface MetricReaderOptions {
/**
* Aggregation selector based on metric instrument types. If no views are
* configured for a metric instrument, a per-metric-reader aggregation is
* selected with this selector.
*/
aggregationSelector?: AggregationSelector;
/**
* Aggregation temporality selector based on metric instrument types. If
* not configured, cumulative is used for all instruments.
*/
aggregationTemporalitySelector?: AggregationTemporalitySelector;
/**
* Cardinality selector based on metric instrument types. If not configured,
* a default value is used.
*/
cardinalitySelector?: CardinalitySelector;
/**
* **Note, this option is experimental**. Additional MetricProducers to use as a source of
* aggregated metric data in addition to the SDK's metric data. The resource returned by
* these MetricProducers is ignored; the SDK's resource will be used instead.
* @experimental
*/
metricProducers?: MetricProducer[];
}
/**
* A registered reader of metrics that, when linked to a {@link MetricProducer}, offers global
* control over metrics.
*/
export declare abstract class MetricReader {
private _shutdown;
private _metricProducers;
private _sdkMetricProducer?;
private readonly _aggregationTemporalitySelector;
private readonly _aggregationSelector;
private readonly _cardinalitySelector?;
constructor(options?: MetricReaderOptions);
/**
* Set the {@link MetricProducer} used by this instance. **This should only be called by the
* SDK and should be considered internal.**
*
* To add additional {@link MetricProducer}s to a {@link MetricReader}, pass them to the
* constructor as {@link MetricReaderOptions.metricProducers}.
*
* @internal
* @param metricProducer
*/
setMetricProducer(metricProducer: MetricProducer): void;
/**
* Select the {@link Aggregation} for the given {@link InstrumentType} for this
* reader.
*/
selectAggregation(instrumentType: InstrumentType): Aggregation;
/**
* Select the {@link AggregationTemporality} for the given
* {@link InstrumentType} for this reader.
*/
selectAggregationTemporality(instrumentType: InstrumentType): AggregationTemporality;
/**
* Select the cardinality limit for the given {@link InstrumentType} for this
* reader.
*/
selectCardinalityLimit(instrumentType: InstrumentType): number;
/**
* Handle once the SDK has initialized this {@link MetricReader}
* Overriding this method is optional.
*/
protected onInitialized(): void;
/**
* Handle a shutdown signal by the SDK.
*
* <p> For push exporters, this should shut down any intervals and close any open connections.
* @protected
*/
protected abstract onShutdown(): Promise<void>;
/**
* Handle a force flush signal by the SDK.
*
* <p> In all scenarios metrics should be collected via {@link collect()}.
* <p> For push exporters, this should collect and report metrics.
* @protected
*/
protected abstract onForceFlush(): Promise<void>;
/**
* Collect all metrics from the associated {@link MetricProducer}
*/
collect(options?: CollectionOptions): Promise<CollectionResult>;
/**
* Shuts down the metric reader, the promise will reject after the optional timeout or resolve after completion.
*
* <p> NOTE: this operation will continue even after the promise rejects due to a timeout.
* @param options options with timeout.
*/
shutdown(options?: ShutdownOptions): Promise<void>;
/**
* Flushes metrics read by this reader, the promise will reject after the optional timeout or resolve after completion.
*
* <p> NOTE: this operation will continue even after the promise rejects due to a timeout.
* @param options options with timeout.
*/
forceFlush(options?: ForceFlushOptions): Promise<void>;
}
//# sourceMappingURL=MetricReader.d.ts.map

View File

@@ -0,0 +1,248 @@
/*
* 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 * as api from '@opentelemetry/api';
import { FlatMap, callWithTimeout } from '../utils';
import { DEFAULT_AGGREGATION_SELECTOR, DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR, } from './AggregationSelector';
/**
* A registered reader of metrics that, when linked to a {@link MetricProducer}, offers global
* control over metrics.
*/
var MetricReader = /** @class */ (function () {
function MetricReader(options) {
var _a, _b, _c;
// Tracks the shutdown state.
// TODO: use BindOncePromise here once a new version of @opentelemetry/core is available.
this._shutdown = false;
this._aggregationSelector =
(_a = options === null || options === void 0 ? void 0 : options.aggregationSelector) !== null && _a !== void 0 ? _a : DEFAULT_AGGREGATION_SELECTOR;
this._aggregationTemporalitySelector =
(_b = options === null || options === void 0 ? void 0 : options.aggregationTemporalitySelector) !== null && _b !== void 0 ? _b : DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR;
this._metricProducers = (_c = options === null || options === void 0 ? void 0 : options.metricProducers) !== null && _c !== void 0 ? _c : [];
this._cardinalitySelector = options === null || options === void 0 ? void 0 : options.cardinalitySelector;
}
/**
* Set the {@link MetricProducer} used by this instance. **This should only be called by the
* SDK and should be considered internal.**
*
* To add additional {@link MetricProducer}s to a {@link MetricReader}, pass them to the
* constructor as {@link MetricReaderOptions.metricProducers}.
*
* @internal
* @param metricProducer
*/
MetricReader.prototype.setMetricProducer = function (metricProducer) {
if (this._sdkMetricProducer) {
throw new Error('MetricReader can not be bound to a MeterProvider again.');
}
this._sdkMetricProducer = metricProducer;
this.onInitialized();
};
/**
* Select the {@link Aggregation} for the given {@link InstrumentType} for this
* reader.
*/
MetricReader.prototype.selectAggregation = function (instrumentType) {
return this._aggregationSelector(instrumentType);
};
/**
* Select the {@link AggregationTemporality} for the given
* {@link InstrumentType} for this reader.
*/
MetricReader.prototype.selectAggregationTemporality = function (instrumentType) {
return this._aggregationTemporalitySelector(instrumentType);
};
/**
* Select the cardinality limit for the given {@link InstrumentType} for this
* reader.
*/
MetricReader.prototype.selectCardinalityLimit = function (instrumentType) {
return this._cardinalitySelector
? this._cardinalitySelector(instrumentType)
: 2000; // default value if no selector is provided
};
/**
* Handle once the SDK has initialized this {@link MetricReader}
* Overriding this method is optional.
*/
MetricReader.prototype.onInitialized = function () {
// Default implementation is empty.
};
/**
* Collect all metrics from the associated {@link MetricProducer}
*/
MetricReader.prototype.collect = function (options) {
return __awaiter(this, void 0, void 0, function () {
var _a, sdkCollectionResults, additionalCollectionResults, errors, resource, scopeMetrics;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (this._sdkMetricProducer === undefined) {
throw new Error('MetricReader is not bound to a MetricProducer');
}
// Subsequent invocations to collect are not allowed. SDKs SHOULD return some failure for these calls.
if (this._shutdown) {
throw new Error('MetricReader is shutdown');
}
return [4 /*yield*/, Promise.all(__spreadArray([
this._sdkMetricProducer.collect({
timeoutMillis: options === null || options === void 0 ? void 0 : options.timeoutMillis,
})
], __read(this._metricProducers.map(function (producer) {
return producer.collect({
timeoutMillis: options === null || options === void 0 ? void 0 : options.timeoutMillis,
});
})), false))];
case 1:
_a = __read.apply(void 0, [_b.sent()]), sdkCollectionResults = _a[0], additionalCollectionResults = _a.slice(1);
errors = sdkCollectionResults.errors.concat(FlatMap(additionalCollectionResults, function (result) { return result.errors; }));
resource = sdkCollectionResults.resourceMetrics.resource;
scopeMetrics = sdkCollectionResults.resourceMetrics.scopeMetrics.concat(FlatMap(additionalCollectionResults, function (result) { return result.resourceMetrics.scopeMetrics; }));
return [2 /*return*/, {
resourceMetrics: {
resource: resource,
scopeMetrics: scopeMetrics,
},
errors: errors,
}];
}
});
});
};
/**
* Shuts down the metric reader, the promise will reject after the optional timeout or resolve after completion.
*
* <p> NOTE: this operation will continue even after the promise rejects due to a timeout.
* @param options options with timeout.
*/
MetricReader.prototype.shutdown = function (options) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// Do not call shutdown again if it has already been called.
if (this._shutdown) {
api.diag.error('Cannot call shutdown twice.');
return [2 /*return*/];
}
if (!((options === null || options === void 0 ? void 0 : options.timeoutMillis) == null)) return [3 /*break*/, 2];
return [4 /*yield*/, this.onShutdown()];
case 1:
_a.sent();
return [3 /*break*/, 4];
case 2: return [4 /*yield*/, callWithTimeout(this.onShutdown(), options.timeoutMillis)];
case 3:
_a.sent();
_a.label = 4;
case 4:
this._shutdown = true;
return [2 /*return*/];
}
});
});
};
/**
* Flushes metrics read by this reader, the promise will reject after the optional timeout or resolve after completion.
*
* <p> NOTE: this operation will continue even after the promise rejects due to a timeout.
* @param options options with timeout.
*/
MetricReader.prototype.forceFlush = function (options) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (this._shutdown) {
api.diag.warn('Cannot forceFlush on already shutdown MetricReader.');
return [2 /*return*/];
}
if (!((options === null || options === void 0 ? void 0 : options.timeoutMillis) == null)) return [3 /*break*/, 2];
return [4 /*yield*/, this.onForceFlush()];
case 1:
_a.sent();
return [2 /*return*/];
case 2: return [4 /*yield*/, callWithTimeout(this.onForceFlush(), options.timeoutMillis)];
case 3:
_a.sent();
return [2 /*return*/];
}
});
});
};
return MetricReader;
}());
export { MetricReader };
//# sourceMappingURL=MetricReader.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,42 @@
import { MetricReader } from './MetricReader';
import { PushMetricExporter } from './MetricExporter';
import { MetricProducer } from './MetricProducer';
export declare type PeriodicExportingMetricReaderOptions = {
/**
* The backing exporter for the metric reader.
*/
exporter: PushMetricExporter;
/**
* An internal milliseconds for the metric reader to initiate metric
* collection.
*/
exportIntervalMillis?: number;
/**
* Milliseconds for the async observable callback to timeout.
*/
exportTimeoutMillis?: number;
/**
* **Note, this option is experimental**. Additional MetricProducers to use as a source of
* aggregated metric data in addition to the SDK's metric data. The resource returned by
* these MetricProducers is ignored; the SDK's resource will be used instead.
* @experimental
*/
metricProducers?: MetricProducer[];
};
/**
* {@link MetricReader} which collects metrics based on a user-configurable time interval, and passes the metrics to
* the configured {@link PushMetricExporter}
*/
export declare class PeriodicExportingMetricReader extends MetricReader {
private _interval?;
private _exporter;
private readonly _exportInterval;
private readonly _exportTimeout;
constructor(options: PeriodicExportingMetricReaderOptions);
private _runOnce;
private _doRun;
protected onInitialized(): void;
protected onForceFlush(): Promise<void>;
protected onShutdown(): Promise<void>;
}
//# sourceMappingURL=PeriodicExportingMetricReader.d.ts.map

View File

@@ -0,0 +1,240 @@
/*
* 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 __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 * as api from '@opentelemetry/api';
import { internal, ExportResultCode, globalErrorHandler, unrefTimer, } from '@opentelemetry/core';
import { MetricReader } from './MetricReader';
import { callWithTimeout, TimeoutError } from '../utils';
/**
* {@link MetricReader} which collects metrics based on a user-configurable time interval, and passes the metrics to
* the configured {@link PushMetricExporter}
*/
var PeriodicExportingMetricReader = /** @class */ (function (_super) {
__extends(PeriodicExportingMetricReader, _super);
function PeriodicExportingMetricReader(options) {
var _a, _b, _c, _d;
var _this = _super.call(this, {
aggregationSelector: (_a = options.exporter.selectAggregation) === null || _a === void 0 ? void 0 : _a.bind(options.exporter),
aggregationTemporalitySelector: (_b = options.exporter.selectAggregationTemporality) === null || _b === void 0 ? void 0 : _b.bind(options.exporter),
metricProducers: options.metricProducers,
}) || this;
if (options.exportIntervalMillis !== undefined &&
options.exportIntervalMillis <= 0) {
throw Error('exportIntervalMillis must be greater than 0');
}
if (options.exportTimeoutMillis !== undefined &&
options.exportTimeoutMillis <= 0) {
throw Error('exportTimeoutMillis must be greater than 0');
}
if (options.exportTimeoutMillis !== undefined &&
options.exportIntervalMillis !== undefined &&
options.exportIntervalMillis < options.exportTimeoutMillis) {
throw Error('exportIntervalMillis must be greater than or equal to exportTimeoutMillis');
}
_this._exportInterval = (_c = options.exportIntervalMillis) !== null && _c !== void 0 ? _c : 60000;
_this._exportTimeout = (_d = options.exportTimeoutMillis) !== null && _d !== void 0 ? _d : 30000;
_this._exporter = options.exporter;
return _this;
}
PeriodicExportingMetricReader.prototype._runOnce = function () {
return __awaiter(this, void 0, void 0, function () {
var err_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, callWithTimeout(this._doRun(), this._exportTimeout)];
case 1:
_a.sent();
return [3 /*break*/, 3];
case 2:
err_1 = _a.sent();
if (err_1 instanceof TimeoutError) {
api.diag.error('Export took longer than %s milliseconds and timed out.', this._exportTimeout);
return [2 /*return*/];
}
globalErrorHandler(err_1);
return [3 /*break*/, 3];
case 3: return [2 /*return*/];
}
});
});
};
PeriodicExportingMetricReader.prototype._doRun = function () {
var _a, _b;
return __awaiter(this, void 0, void 0, function () {
var _c, resourceMetrics, errors, e_1, result;
var _d;
return __generator(this, function (_e) {
switch (_e.label) {
case 0: return [4 /*yield*/, this.collect({
timeoutMillis: this._exportTimeout,
})];
case 1:
_c = _e.sent(), resourceMetrics = _c.resourceMetrics, errors = _c.errors;
if (errors.length > 0) {
(_d = api.diag).error.apply(_d, __spreadArray(['PeriodicExportingMetricReader: metrics collection errors'], __read(errors), false));
}
if (!resourceMetrics.resource.asyncAttributesPending) return [3 /*break*/, 5];
_e.label = 2;
case 2:
_e.trys.push([2, 4, , 5]);
return [4 /*yield*/, ((_b = (_a = resourceMetrics.resource).waitForAsyncAttributes) === null || _b === void 0 ? void 0 : _b.call(_a))];
case 3:
_e.sent();
return [3 /*break*/, 5];
case 4:
e_1 = _e.sent();
api.diag.debug('Error while resolving async portion of resource: ', e_1);
globalErrorHandler(e_1);
return [3 /*break*/, 5];
case 5:
if (resourceMetrics.scopeMetrics.length === 0) {
return [2 /*return*/];
}
return [4 /*yield*/, internal._export(this._exporter, resourceMetrics)];
case 6:
result = _e.sent();
if (result.code !== ExportResultCode.SUCCESS) {
throw new Error("PeriodicExportingMetricReader: metrics export failed (error " + result.error + ")");
}
return [2 /*return*/];
}
});
});
};
PeriodicExportingMetricReader.prototype.onInitialized = function () {
var _this = this;
// start running the interval as soon as this reader is initialized and keep handle for shutdown.
this._interval = setInterval(function () {
// this._runOnce never rejects. Using void operator to suppress @typescript-eslint/no-floating-promises.
void _this._runOnce();
}, this._exportInterval);
unrefTimer(this._interval);
};
PeriodicExportingMetricReader.prototype.onForceFlush = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this._runOnce()];
case 1:
_a.sent();
return [4 /*yield*/, this._exporter.forceFlush()];
case 2:
_a.sent();
return [2 /*return*/];
}
});
});
};
PeriodicExportingMetricReader.prototype.onShutdown = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (this._interval) {
clearInterval(this._interval);
}
return [4 /*yield*/, this.onForceFlush()];
case 1:
_a.sent();
return [4 /*yield*/, this._exporter.shutdown()];
case 2:
_a.sent();
return [2 /*return*/];
}
});
});
};
return PeriodicExportingMetricReader;
}(MetricReader));
export { PeriodicExportingMetricReader };
//# sourceMappingURL=PeriodicExportingMetricReader.js.map

File diff suppressed because one or more lines are too long