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 const DEFAULT_AGGREGATION_SELECTOR = _instrumentType => Aggregation.Default();
export const DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = _instrumentType => 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,MAAM,4BAA4B,GACvC,eAAe,CAAC,EAAE,CAAC,WAAW,CAAC,OAAO,EAAE,CAAC;AAC3C,MAAM,CAAC,MAAM,wCAAwC,GACnD,eAAe,CAAC,EAAE,CAAC,sBAAsB,CAAC,UAAU,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,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';
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 */
export class ConsoleMetricExporter {
constructor(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;
}
export(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);
}
forceFlush() {
return Promise.resolve();
}
selectAggregationTemporality(_instrumentType) {
return this._temporalitySelector(_instrumentType);
}
shutdown() {
this._shutdown = true;
return Promise.resolve();
}
static _sendMetrics(metrics, done) {
for (const scopeMetrics of metrics.scopeMetrics) {
for (const metric of scopeMetrics.metrics) {
console.dir({
descriptor: metric.descriptor,
dataPointType: metric.dataPointType,
dataPoints: metric.dataPoints,
}, { depth: null });
}
}
done({ code: ExportResultCode.SUCCESS });
}
}
//# 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,MAAM,OAAO,qBAAqB;IAIhC,YAAY,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,MAAM,CACJ,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,UAAU;QACR,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAED,4BAA4B,CAC1B,eAA+B;QAE/B,OAAO,IAAI,CAAC,oBAAoB,CAAC,eAAe,CAAC,CAAC;IACpD,CAAC;IAED,QAAQ;QACN,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAEO,MAAM,CAAC,YAAY,CACzB,OAAwB,EACxB,IAAoC;QAEpC,KAAK,MAAM,YAAY,IAAI,OAAO,CAAC,YAAY,EAAE;YAC/C,KAAK,MAAM,MAAM,IAAI,YAAY,CAAC,OAAO,EAAE;gBACzC,OAAO,CAAC,GAAG,CACT;oBACE,UAAU,EAAE,MAAM,CAAC,UAAU;oBAC7B,aAAa,EAAE,MAAM,CAAC,aAAa;oBACnC,UAAU,EAAE,MAAM,CAAC,UAAU;iBAC9B,EACD,EAAE,KAAK,EAAE,IAAI,EAAE,CAChB,CAAC;aACH;SACF;QAED,IAAI,CAAC,EAAE,IAAI,EAAE,gBAAgB,CAAC,OAAO,EAAE,CAAC,CAAC;IAC3C,CAAC;CACF","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,61 @@
/*
* 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).
*/
export class InMemoryMetricExporter {
constructor(aggregationTemporality) {
this._shutdown = false;
this._metrics = [];
this._aggregationTemporality = aggregationTemporality;
}
/**
* @inheritedDoc
*/
export(metrics, resultCallback) {
// Avoid storing metrics when exporter is shutdown
if (this._shutdown) {
setTimeout(() => resultCallback({ code: ExportResultCode.FAILED }), 0);
return;
}
this._metrics.push(metrics);
setTimeout(() => resultCallback({ code: ExportResultCode.SUCCESS }), 0);
}
/**
* Returns all the collected resource metrics
* @returns ResourceMetrics[]
*/
getMetrics() {
return this._metrics;
}
forceFlush() {
return Promise.resolve();
}
reset() {
this._metrics = [];
}
selectAggregationTemporality(_instrumentType) {
return this._aggregationTemporality;
}
shutdown() {
this._shutdown = true;
return Promise.resolve();
}
}
//# 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,MAAM,OAAO,sBAAsB;IAKjC,YAAY,sBAA8C;QAJhD,cAAS,GAAG,KAAK,CAAC;QAEpB,aAAQ,GAAsB,EAAE,CAAC;QAGvC,IAAI,CAAC,uBAAuB,GAAG,sBAAsB,CAAC;IACxD,CAAC;IAED;;OAEG;IACH,MAAM,CACJ,OAAwB,EACxB,cAA8C;QAE9C,kDAAkD;QAClD,IAAI,IAAI,CAAC,SAAS,EAAE;YAClB,UAAU,CAAC,GAAG,EAAE,CAAC,cAAc,CAAC,EAAE,IAAI,EAAE,gBAAgB,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;YACvE,OAAO;SACR;QAED,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAC5B,UAAU,CAAC,GAAG,EAAE,CAAC,cAAc,CAAC,EAAE,IAAI,EAAE,gBAAgB,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC1E,CAAC;IAED;;;OAGG;IACI,UAAU;QACf,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;IAED,UAAU;QACR,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAED,KAAK;QACH,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAC;IACrB,CAAC;IAED,4BAA4B,CAC1B,eAA+B;QAE/B,OAAO,IAAI,CAAC,uBAAuB,CAAC;IACtC,CAAC;IAED,QAAQ;QACN,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;CACF","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,154 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as 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.
*/
export class MetricReader {
constructor(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
*/
setMetricProducer(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.
*/
selectAggregation(instrumentType) {
return this._aggregationSelector(instrumentType);
}
/**
* Select the {@link AggregationTemporality} for the given
* {@link InstrumentType} for this reader.
*/
selectAggregationTemporality(instrumentType) {
return this._aggregationTemporalitySelector(instrumentType);
}
/**
* Select the cardinality limit for the given {@link InstrumentType} for this
* reader.
*/
selectCardinalityLimit(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.
*/
onInitialized() {
// Default implementation is empty.
}
/**
* Collect all metrics from the associated {@link MetricProducer}
*/
async collect(options) {
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');
}
const [sdkCollectionResults, ...additionalCollectionResults] = await Promise.all([
this._sdkMetricProducer.collect({
timeoutMillis: options === null || options === void 0 ? void 0 : options.timeoutMillis,
}),
...this._metricProducers.map(producer => producer.collect({
timeoutMillis: options === null || options === void 0 ? void 0 : options.timeoutMillis,
})),
]);
// Merge the results, keeping the SDK's Resource
const errors = sdkCollectionResults.errors.concat(FlatMap(additionalCollectionResults, result => result.errors));
const resource = sdkCollectionResults.resourceMetrics.resource;
const scopeMetrics = sdkCollectionResults.resourceMetrics.scopeMetrics.concat(FlatMap(additionalCollectionResults, result => result.resourceMetrics.scopeMetrics));
return {
resourceMetrics: {
resource,
scopeMetrics,
},
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.
*/
async shutdown(options) {
// Do not call shutdown again if it has already been called.
if (this._shutdown) {
api.diag.error('Cannot call shutdown twice.');
return;
}
// No timeout if timeoutMillis is undefined or null.
if ((options === null || options === void 0 ? void 0 : options.timeoutMillis) == null) {
await this.onShutdown();
}
else {
await callWithTimeout(this.onShutdown(), options.timeoutMillis);
}
this._shutdown = true;
}
/**
* 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.
*/
async forceFlush(options) {
if (this._shutdown) {
api.diag.warn('Cannot forceFlush on already shutdown MetricReader.');
return;
}
// No timeout if timeoutMillis is undefined or null.
if ((options === null || options === void 0 ? void 0 : options.timeoutMillis) == null) {
await this.onForceFlush();
return;
}
await callWithTimeout(this.onForceFlush(), options.timeoutMillis);
}
}
//# 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,106 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as 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}
*/
export class PeriodicExportingMetricReader extends MetricReader {
constructor(options) {
var _a, _b, _c, _d;
super({
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,
});
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;
}
async _runOnce() {
try {
await callWithTimeout(this._doRun(), this._exportTimeout);
}
catch (err) {
if (err instanceof TimeoutError) {
api.diag.error('Export took longer than %s milliseconds and timed out.', this._exportTimeout);
return;
}
globalErrorHandler(err);
}
}
async _doRun() {
var _a, _b;
const { resourceMetrics, errors } = await this.collect({
timeoutMillis: this._exportTimeout,
});
if (errors.length > 0) {
api.diag.error('PeriodicExportingMetricReader: metrics collection errors', ...errors);
}
if (resourceMetrics.resource.asyncAttributesPending) {
try {
await ((_b = (_a = resourceMetrics.resource).waitForAsyncAttributes) === null || _b === void 0 ? void 0 : _b.call(_a));
}
catch (e) {
api.diag.debug('Error while resolving async portion of resource: ', e);
globalErrorHandler(e);
}
}
if (resourceMetrics.scopeMetrics.length === 0) {
return;
}
const result = await internal._export(this._exporter, resourceMetrics);
if (result.code !== ExportResultCode.SUCCESS) {
throw new Error(`PeriodicExportingMetricReader: metrics export failed (error ${result.error})`);
}
}
onInitialized() {
// start running the interval as soon as this reader is initialized and keep handle for shutdown.
this._interval = setInterval(() => {
// this._runOnce never rejects. Using void operator to suppress @typescript-eslint/no-floating-promises.
void this._runOnce();
}, this._exportInterval);
unrefTimer(this._interval);
}
async onForceFlush() {
await this._runOnce();
await this._exporter.forceFlush();
}
async onShutdown() {
if (this._interval) {
clearInterval(this._interval);
}
await this.onForceFlush();
await this._exporter.shutdown();
}
}
//# sourceMappingURL=PeriodicExportingMetricReader.js.map