function transformExponentialHistogramValue()

in packages/opentelemetry-cloud-monitoring-exporter/src/transform.ts [259:302]


function transformExponentialHistogramValue(
  value: ExponentialHistogram
): monitoring_v3.Schema$TypedValue {
  // Adapated from reference impl in Go which has more explanatory comments
  // https://github.com/GoogleCloudPlatform/opentelemetry-operations-go/blob/v1.8.0/exporter/collector/metrics.go#L582
  const underflow =
    value.zeroCount +
    value.negative.bucketCounts.reduce((prev, current) => prev + current, 0);
  const bucketCounts = [
    underflow,
    ...value.positive.bucketCounts,
    0, // overflow bucket is always empty
  ];

  let bucketOptions: monitoring_v3.Schema$BucketOptions;
  if (value.positive.bucketCounts.length === 0) {
    bucketOptions = {
      explicitBuckets: {bounds: []},
    };
  } else {
    const growthFactor = exp2(exp2(-value.scale));
    const scale = Math.pow(growthFactor, value.positive.offset);
    bucketOptions = {
      exponentialBuckets: {
        growthFactor,
        scale,
        numFiniteBuckets: bucketCounts.length - 2,
      },
    };
  }

  const mean =
    value.sum === undefined || value.count === 0 ? 0 : value.sum / value.count;

  return {
    distributionValue: {
      // sumOfSquaredDeviation param not aggregated
      count: value.count.toString(),
      mean,
      bucketOptions,
      bucketCounts: numbersToStrings(bucketCounts),
    },
  };
}