summaryrefslogtreecommitdiffstats
path: root/toolkit/components/glean/bindings/private
diff options
context:
space:
mode:
Diffstat (limited to 'toolkit/components/glean/bindings/private')
-rw-r--r--toolkit/components/glean/bindings/private/Boolean.cpp71
-rw-r--r--toolkit/components/glean/bindings/private/Boolean.h80
-rw-r--r--toolkit/components/glean/bindings/private/Common.cpp33
-rw-r--r--toolkit/components/glean/bindings/private/Common.h24
-rw-r--r--toolkit/components/glean/bindings/private/Counter.cpp74
-rw-r--r--toolkit/components/glean/bindings/private/Counter.h77
-rw-r--r--toolkit/components/glean/bindings/private/CustomDistribution.cpp105
-rw-r--r--toolkit/components/glean/bindings/private/CustomDistribution.h95
-rw-r--r--toolkit/components/glean/bindings/private/Datetime.cpp121
-rw-r--r--toolkit/components/glean/bindings/private/Datetime.h79
-rw-r--r--toolkit/components/glean/bindings/private/Denominator.cpp64
-rw-r--r--toolkit/components/glean/bindings/private/Denominator.h77
-rw-r--r--toolkit/components/glean/bindings/private/DistributionData.h32
-rw-r--r--toolkit/components/glean/bindings/private/Event.cpp110
-rw-r--r--toolkit/components/glean/bindings/private/Event.h177
-rw-r--r--toolkit/components/glean/bindings/private/Labeled.cpp49
-rw-r--r--toolkit/components/glean/bindings/private/Labeled.h248
-rw-r--r--toolkit/components/glean/bindings/private/MemoryDistribution.cpp89
-rw-r--r--toolkit/components/glean/bindings/private/MemoryDistribution.h86
-rw-r--r--toolkit/components/glean/bindings/private/Numerator.cpp73
-rw-r--r--toolkit/components/glean/bindings/private/Numerator.h84
-rw-r--r--toolkit/components/glean/bindings/private/Ping.cpp85
-rw-r--r--toolkit/components/glean/bindings/private/Ping.h83
-rw-r--r--toolkit/components/glean/bindings/private/Quantity.cpp68
-rw-r--r--toolkit/components/glean/bindings/private/Quantity.h77
-rw-r--r--toolkit/components/glean/bindings/private/Rate.cpp86
-rw-r--r--toolkit/components/glean/bindings/private/Rate.h90
-rw-r--r--toolkit/components/glean/bindings/private/String.cpp75
-rw-r--r--toolkit/components/glean/bindings/private/String.h80
-rw-r--r--toolkit/components/glean/bindings/private/StringList.cpp80
-rw-r--r--toolkit/components/glean/bindings/private/StringList.h93
-rw-r--r--toolkit/components/glean/bindings/private/Text.cpp64
-rw-r--r--toolkit/components/glean/bindings/private/Text.h54
-rw-r--r--toolkit/components/glean/bindings/private/Timespan.cpp186
-rw-r--r--toolkit/components/glean/bindings/private/Timespan.h110
-rw-r--r--toolkit/components/glean/bindings/private/TimingDistribution.cpp242
-rw-r--r--toolkit/components/glean/bindings/private/TimingDistribution.h125
-rw-r--r--toolkit/components/glean/bindings/private/Url.cpp68
-rw-r--r--toolkit/components/glean/bindings/private/Url.h77
-rw-r--r--toolkit/components/glean/bindings/private/Uuid.cpp76
-rw-r--r--toolkit/components/glean/bindings/private/Uuid.h83
41 files changed, 3750 insertions, 0 deletions
diff --git a/toolkit/components/glean/bindings/private/Boolean.cpp b/toolkit/components/glean/bindings/private/Boolean.cpp
new file mode 100644
index 0000000000..8300990b49
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Boolean.cpp
@@ -0,0 +1,71 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/glean/bindings/Boolean.h"
+
+#include "nsString.h"
+#include "mozilla/ResultVariant.h"
+#include "mozilla/dom/GleanMetricsBinding.h"
+#include "mozilla/glean/bindings/ScalarGIFFTMap.h"
+#include "mozilla/glean/fog_ffi_generated.h"
+
+namespace mozilla::glean {
+
+namespace impl {
+
+void BooleanMetric::Set(bool aValue) const {
+ auto scalarId = ScalarIdForMetric(mId);
+ if (scalarId) {
+ Telemetry::ScalarSet(scalarId.extract(), aValue);
+ } else if (IsSubmetricId(mId)) {
+ GetLabeledMirrorLock().apply([&](auto& lock) {
+ auto tuple = lock.ref()->MaybeGet(mId);
+ if (tuple) {
+ Telemetry::ScalarSet(std::get<0>(tuple.ref()), std::get<1>(tuple.ref()),
+ aValue);
+ }
+ });
+ }
+ fog_boolean_set(mId, int(aValue));
+}
+
+Result<Maybe<bool>, nsCString> BooleanMetric::TestGetValue(
+ const nsACString& aPingName) const {
+ nsCString err;
+ if (fog_boolean_test_get_error(mId, &err)) {
+ return Err(err);
+ }
+ if (!fog_boolean_test_has_value(mId, &aPingName)) {
+ return Maybe<bool>();
+ }
+ return Some(fog_boolean_test_get_value(mId, &aPingName));
+}
+
+} // namespace impl
+
+JSObject* GleanBoolean::WrapObject(JSContext* aCx,
+ JS::Handle<JSObject*> aGivenProto) {
+ return dom::GleanBoolean_Binding::Wrap(aCx, this, aGivenProto);
+}
+
+void GleanBoolean::Set(bool aValue) { mBoolean.Set(aValue); }
+
+dom::Nullable<bool> GleanBoolean::TestGetValue(const nsACString& aPingName,
+ ErrorResult& aRv) {
+ dom::Nullable<bool> ret;
+ auto result = mBoolean.TestGetValue(aPingName);
+ if (result.isErr()) {
+ aRv.ThrowDataError(result.unwrapErr());
+ return ret;
+ }
+ auto optresult = result.unwrap();
+ if (!optresult.isNothing()) {
+ ret.SetValue(optresult.value());
+ }
+ return ret;
+}
+
+} // namespace mozilla::glean
diff --git a/toolkit/components/glean/bindings/private/Boolean.h b/toolkit/components/glean/bindings/private/Boolean.h
new file mode 100644
index 0000000000..6947e1b713
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Boolean.h
@@ -0,0 +1,80 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_glean_GleanBoolean_h
+#define mozilla_glean_GleanBoolean_h
+
+#include "mozilla/dom/BindingDeclarations.h"
+#include "mozilla/glean/bindings/GleanMetric.h"
+#include "mozilla/Result.h"
+#include "nsString.h"
+#include "nsWrapperCache.h"
+
+namespace mozilla {
+namespace glean {
+
+namespace impl {
+
+class BooleanMetric {
+ public:
+ constexpr explicit BooleanMetric(uint32_t id) : mId(id) {}
+
+ /**
+ * Set to the specified boolean value.
+ *
+ * @param aValue the value to set.
+ */
+ void Set(bool aValue) const;
+
+ /**
+ * **Test-only API**
+ *
+ * Gets the currently stored value as a boolean.
+ *
+ * This function will attempt to await the last parent-process task (if any)
+ * writing to the the metric's storage engine before returning a value.
+ * This function will not wait for data from child processes.
+ *
+ * This doesn't clear the stored value.
+ * Parent process only. Panics in child processes.
+ *
+ * @param aPingName The (optional) name of the ping to retrieve the metric
+ * for. Defaults to the first value in `send_in_pings`.
+ *
+ * @return value of the stored metric.
+ */
+ Result<Maybe<bool>, nsCString> TestGetValue(
+ const nsACString& aPingName = nsCString()) const;
+
+ private:
+ const uint32_t mId;
+};
+
+} // namespace impl
+
+class GleanBoolean final : public GleanMetric {
+ public:
+ explicit GleanBoolean(uint32_t id, nsISupports* aParent)
+ : GleanMetric(aParent), mBoolean(id) {}
+
+ virtual JSObject* WrapObject(
+ JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override final;
+
+ void Set(bool aValue);
+
+ dom::Nullable<bool> TestGetValue(const nsACString& aPingName,
+ ErrorResult& aRv);
+
+ private:
+ virtual ~GleanBoolean() = default;
+
+ const impl::BooleanMetric mBoolean;
+};
+
+} // namespace glean
+} // namespace mozilla
+
+#endif /* mozilla_glean_GleanBoolean.h */
diff --git a/toolkit/components/glean/bindings/private/Common.cpp b/toolkit/components/glean/bindings/private/Common.cpp
new file mode 100644
index 0000000000..f84c39c05d
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Common.cpp
@@ -0,0 +1,33 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "Common.h"
+#include "nsComponentManagerUtils.h"
+#include "nsIConsoleService.h"
+#include "nsIScriptError.h"
+#include "nsServiceManagerUtils.h"
+
+namespace mozilla::glean {
+
+// This is copied from TelemetryCommons.cpp (and modified because consoleservice
+// handles threading), but that one is not exported.
+// There's _at least_ a third instance of `LogToBrowserConsole`,
+// but that one is slightly different.
+void LogToBrowserConsole(uint32_t aLogLevel, const nsAString& aMsg) {
+ nsCOMPtr<nsIConsoleService> console(
+ do_GetService("@mozilla.org/consoleservice;1"));
+ if (!console) {
+ NS_WARNING("Failed to log message to console.");
+ return;
+ }
+
+ nsCOMPtr<nsIScriptError> error(do_CreateInstance(NS_SCRIPTERROR_CONTRACTID));
+ error->Init(aMsg, u""_ns, u""_ns, 0, 0, aLogLevel, "chrome javascript"_ns,
+ false /* from private window */, true /* from chrome context */);
+ console->LogMessage(error);
+}
+
+} // namespace mozilla::glean
diff --git a/toolkit/components/glean/bindings/private/Common.h b/toolkit/components/glean/bindings/private/Common.h
new file mode 100644
index 0000000000..e3dd7a0a47
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Common.h
@@ -0,0 +1,24 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2; -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_glean_Common_h
+#define mozilla_glean_Common_h
+
+#include "nsIScriptError.h"
+
+namespace mozilla::glean {
+
+/**
+ * Dumps a log message to the Browser Console using the provided level.
+ *
+ * @param aLogLevel The level to use when displaying the message in the browser
+ * console (e.g. nsIScriptError::warningFlag, ...).
+ * @param aMsg The text message to print to the console.
+ */
+void LogToBrowserConsole(uint32_t aLogLevel, const nsAString& aMsg);
+
+} // namespace mozilla::glean
+
+#endif /* mozilla_glean_Common_h */
diff --git a/toolkit/components/glean/bindings/private/Counter.cpp b/toolkit/components/glean/bindings/private/Counter.cpp
new file mode 100644
index 0000000000..f7f70f29eb
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Counter.cpp
@@ -0,0 +1,74 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/glean/bindings/Counter.h"
+
+#include "nsString.h"
+#include "mozilla/ResultVariant.h"
+#include "mozilla/dom/GleanMetricsBinding.h"
+#include "mozilla/glean/bindings/ScalarGIFFTMap.h"
+#include "mozilla/glean/fog_ffi_generated.h"
+
+namespace mozilla::glean {
+
+namespace impl {
+
+void CounterMetric::Add(int32_t aAmount) const {
+ auto scalarId = ScalarIdForMetric(mId);
+ if (aAmount >= 0) {
+ if (scalarId) {
+ Telemetry::ScalarAdd(scalarId.extract(), aAmount);
+ } else if (IsSubmetricId(mId)) {
+ GetLabeledMirrorLock().apply([&](auto& lock) {
+ auto tuple = lock.ref()->MaybeGet(mId);
+ if (tuple && aAmount > 0) {
+ Telemetry::ScalarAdd(std::get<0>(tuple.ref()),
+ std::get<1>(tuple.ref()), (uint32_t)aAmount);
+ }
+ });
+ }
+ }
+ fog_counter_add(mId, aAmount);
+}
+
+Result<Maybe<int32_t>, nsCString> CounterMetric::TestGetValue(
+ const nsACString& aPingName) const {
+ nsCString err;
+ if (fog_counter_test_get_error(mId, &err)) {
+ return Err(err);
+ }
+ if (!fog_counter_test_has_value(mId, &aPingName)) {
+ return Maybe<int32_t>(); // can't use Nothing() or templates will fail.
+ }
+ return Some(fog_counter_test_get_value(mId, &aPingName));
+}
+
+} // namespace impl
+
+/* virtual */
+JSObject* GleanCounter::WrapObject(JSContext* aCx,
+ JS::Handle<JSObject*> aGivenProto) {
+ return dom::GleanCounter_Binding::Wrap(aCx, this, aGivenProto);
+}
+
+void GleanCounter::Add(int32_t aAmount) { mCounter.Add(aAmount); }
+
+dom::Nullable<int32_t> GleanCounter::TestGetValue(const nsACString& aPingName,
+ ErrorResult& aRv) {
+ dom::Nullable<int32_t> ret;
+ auto result = mCounter.TestGetValue(aPingName);
+ if (result.isErr()) {
+ aRv.ThrowDataError(result.unwrapErr());
+ return ret;
+ }
+ auto optresult = result.unwrap();
+ if (!optresult.isNothing()) {
+ ret.SetValue(optresult.value());
+ }
+ return ret;
+}
+
+} // namespace mozilla::glean
diff --git a/toolkit/components/glean/bindings/private/Counter.h b/toolkit/components/glean/bindings/private/Counter.h
new file mode 100644
index 0000000000..c378df8e5d
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Counter.h
@@ -0,0 +1,77 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_glean_GleanCounter_h
+#define mozilla_glean_GleanCounter_h
+
+#include "mozilla/dom/BindingDeclarations.h"
+#include "mozilla/glean/bindings/GleanMetric.h"
+#include "mozilla/Maybe.h"
+#include "mozilla/Result.h"
+#include "nsString.h"
+
+namespace mozilla::glean {
+
+namespace impl {
+
+class CounterMetric {
+ public:
+ constexpr explicit CounterMetric(uint32_t aId) : mId(aId) {}
+
+ /*
+ * Increases the counter by `amount`.
+ *
+ * @param aAmount The amount to increase by. Should be positive.
+ */
+ void Add(int32_t aAmount = 1) const;
+
+ /**
+ * **Test-only API**
+ *
+ * Gets the currently stored value as an integer.
+ *
+ * This function will attempt to await the last parent-process task (if any)
+ * writing to the the metric's storage engine before returning a value.
+ * This function will not wait for data from child processes.
+ *
+ * This doesn't clear the stored value.
+ * Parent process only. Panics in child processes.
+ *
+ * @param aPingName The (optional) name of the ping to retrieve the metric
+ * for. Defaults to the first value in `send_in_pings`.
+ *
+ * @return value of the stored metric, or Nothing() if there is no value.
+ */
+ Result<Maybe<int32_t>, nsCString> TestGetValue(
+ const nsACString& aPingName = nsCString()) const;
+
+ private:
+ const uint32_t mId;
+};
+} // namespace impl
+
+class GleanCounter final : public GleanMetric {
+ public:
+ explicit GleanCounter(uint32_t id, nsISupports* aParent)
+ : GleanMetric(aParent), mCounter(id) {}
+
+ virtual JSObject* WrapObject(
+ JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override final;
+
+ void Add(int32_t aAmount);
+
+ dom::Nullable<int32_t> TestGetValue(const nsACString& aPingName,
+ ErrorResult& aRv);
+
+ private:
+ virtual ~GleanCounter() = default;
+
+ const impl::CounterMetric mCounter;
+};
+
+} // namespace mozilla::glean
+
+#endif /* mozilla_glean_GleanCounter_h */
diff --git a/toolkit/components/glean/bindings/private/CustomDistribution.cpp b/toolkit/components/glean/bindings/private/CustomDistribution.cpp
new file mode 100644
index 0000000000..2f0226cb58
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/CustomDistribution.cpp
@@ -0,0 +1,105 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/glean/bindings/CustomDistribution.h"
+
+#include "mozilla/ResultVariant.h"
+#include "mozilla/dom/GleanMetricsBinding.h"
+#include "mozilla/glean/bindings/HistogramGIFFTMap.h"
+#include "mozilla/glean/fog_ffi_generated.h"
+#include "nsJSUtils.h"
+#include "nsPrintfCString.h"
+#include "nsString.h"
+#include "js/PropertyAndElement.h" // JS_DefineProperty
+
+namespace mozilla::glean {
+
+namespace impl {
+
+void CustomDistributionMetric::AccumulateSamples(
+ const nsTArray<uint64_t>& aSamples) const {
+ auto hgramId = HistogramIdForMetric(mId);
+ if (hgramId) {
+ auto id = hgramId.extract();
+ // N.B.: There is an `Accumulate(nsTArray<T>)`, but `T` is `uint32_t` and
+ // we got `uint64_t`s here.
+ for (auto sample : aSamples) {
+ Telemetry::Accumulate(id, sample);
+ }
+ }
+ fog_custom_distribution_accumulate_samples(mId, &aSamples);
+}
+
+void CustomDistributionMetric::AccumulateSamplesSigned(
+ const nsTArray<int64_t>& aSamples) const {
+ auto hgramId = HistogramIdForMetric(mId);
+ if (hgramId) {
+ auto id = hgramId.extract();
+ // N.B.: There is an `Accumulate(nsTArray<T>)`, but `T` is `uint32_t` and
+ // we got `int64_t`s here.
+ for (auto sample : aSamples) {
+ Telemetry::Accumulate(id, sample);
+ }
+ }
+ fog_custom_distribution_accumulate_samples_signed(mId, &aSamples);
+}
+
+Result<Maybe<DistributionData>, nsCString>
+CustomDistributionMetric::TestGetValue(const nsACString& aPingName) const {
+ nsCString err;
+ if (fog_custom_distribution_test_get_error(mId, &err)) {
+ return Err(err);
+ }
+ if (!fog_custom_distribution_test_has_value(mId, &aPingName)) {
+ return Maybe<DistributionData>();
+ }
+ nsTArray<uint64_t> buckets;
+ nsTArray<uint64_t> counts;
+ uint64_t sum;
+ fog_custom_distribution_test_get_value(mId, &aPingName, &sum, &buckets,
+ &counts);
+ return Some(DistributionData(buckets, counts, sum));
+}
+
+} // namespace impl
+
+/* virtual */
+JSObject* GleanCustomDistribution::WrapObject(
+ JSContext* aCx, JS::Handle<JSObject*> aGivenProto) {
+ return dom::GleanCustomDistribution_Binding::Wrap(aCx, this, aGivenProto);
+}
+
+void GleanCustomDistribution::AccumulateSamples(
+ const dom::Sequence<int64_t>& aSamples) {
+ mCustomDist.AccumulateSamplesSigned(aSamples);
+}
+
+void GleanCustomDistribution::TestGetValue(
+ const nsACString& aPingName,
+ dom::Nullable<dom::GleanDistributionData>& aRetval, ErrorResult& aRv) {
+ auto result = mCustomDist.TestGetValue(aPingName);
+ if (result.isErr()) {
+ aRv.ThrowDataError(result.unwrapErr());
+ return;
+ }
+ auto optresult = result.unwrap();
+ if (optresult.isNothing()) {
+ return;
+ }
+
+ dom::GleanDistributionData ret;
+ ret.mSum = optresult.ref().sum;
+ auto& data = optresult.ref().values;
+ for (const auto& entry : data) {
+ dom::binding_detail::RecordEntry<nsCString, uint64_t> bucket;
+ bucket.mKey = nsPrintfCString("%" PRIu64, entry.GetKey());
+ bucket.mValue = entry.GetData();
+ ret.mValues.Entries().EmplaceBack(std::move(bucket));
+ }
+ aRetval.SetValue(std::move(ret));
+}
+
+} // namespace mozilla::glean
diff --git a/toolkit/components/glean/bindings/private/CustomDistribution.h b/toolkit/components/glean/bindings/private/CustomDistribution.h
new file mode 100644
index 0000000000..8227b024ad
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/CustomDistribution.h
@@ -0,0 +1,95 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_glean_GleanCustomDistribution_h
+#define mozilla_glean_GleanCustomDistribution_h
+
+#include "mozilla/dom/BindingDeclarations.h"
+#include "mozilla/glean/bindings/GleanMetric.h"
+#include "mozilla/glean/bindings/DistributionData.h"
+#include "mozilla/Maybe.h"
+#include "mozilla/Result.h"
+#include "nsTArray.h"
+
+namespace mozilla::dom {
+struct GleanDistributionData;
+} // namespace mozilla::dom
+
+namespace mozilla::glean {
+
+namespace impl {
+
+class CustomDistributionMetric {
+ public:
+ constexpr explicit CustomDistributionMetric(uint32_t aId) : mId(aId) {}
+
+ /**
+ * Accumulates the provided samples in the metric.
+ *
+ * @param aSamples The vector holding the samples to be recorded by the
+ * metric.
+ */
+ void AccumulateSamples(const nsTArray<uint64_t>& aSamples) const;
+
+ /**
+ * Accumulates the provided samples in the metric.
+ *
+ * @param aSamples The vector holding the samples to be recorded by the
+ * metric.
+ *
+ * Notes: Discards any negative value in `samples`
+ * and reports an `InvalidValue` error for each of them.
+ */
+ void AccumulateSamplesSigned(const nsTArray<int64_t>& aSamples) const;
+
+ /**
+ * **Test-only API**
+ *
+ * Gets the currently stored value as a DistributionData.
+ *
+ * This function will attempt to await the last parent-process task (if any)
+ * writing to the the metric's storage engine before returning a value.
+ * This function will not wait for data from child processes.
+ *
+ * This doesn't clear the stored value.
+ * Parent process only. Panics in child processes.
+ *
+ * @param aPingName The (optional) name of the ping to retrieve the metric
+ * for. Defaults to the first value in `send_in_pings`.
+ *
+ * @return value of the stored metric, or Nothing() if there is no value.
+ */
+ Result<Maybe<DistributionData>, nsCString> TestGetValue(
+ const nsACString& aPingName = nsCString()) const;
+
+ private:
+ const uint32_t mId;
+};
+} // namespace impl
+
+class GleanCustomDistribution final : public GleanMetric {
+ public:
+ explicit GleanCustomDistribution(uint64_t aId, nsISupports* aParent)
+ : GleanMetric(aParent), mCustomDist(aId) {}
+
+ virtual JSObject* WrapObject(
+ JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override final;
+
+ void AccumulateSamples(const dom::Sequence<int64_t>& aSamples);
+
+ void TestGetValue(const nsACString& aPingName,
+ dom::Nullable<dom::GleanDistributionData>& aRetval,
+ ErrorResult& aRv);
+
+ private:
+ virtual ~GleanCustomDistribution() = default;
+
+ const impl::CustomDistributionMetric mCustomDist;
+};
+
+} // namespace mozilla::glean
+
+#endif /* mozilla_glean_GleanCustomDistribution_h */
diff --git a/toolkit/components/glean/bindings/private/Datetime.cpp b/toolkit/components/glean/bindings/private/Datetime.cpp
new file mode 100644
index 0000000000..ac88c67426
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Datetime.cpp
@@ -0,0 +1,121 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/glean/bindings/Datetime.h"
+
+#include "jsapi.h"
+#include "js/Date.h"
+#include "nsString.h"
+#include "mozilla/ResultVariant.h"
+#include "mozilla/dom/GleanMetricsBinding.h"
+#include "mozilla/glean/bindings/ScalarGIFFTMap.h"
+#include "mozilla/glean/fog_ffi_generated.h"
+#include "prtime.h"
+
+namespace mozilla::glean {
+
+namespace impl {
+
+void DatetimeMetric::Set(const PRExplodedTime* aValue) const {
+ PRExplodedTime exploded;
+ if (!aValue) {
+ PR_ExplodeTime(PR_Now(), PR_LocalTimeParameters, &exploded);
+ } else {
+ exploded = *aValue;
+ }
+
+ auto id = ScalarIdForMetric(mId);
+ if (id) {
+ const uint32_t buflen = 64; // More than enough for now.
+ char buf[buflen];
+ uint32_t written = PR_FormatTime(buf, buflen, "%FT%T%z", &exploded);
+ if (written > 2 && written < 64) {
+ // Format's still not quite there. Gotta put a `:` between timezone
+ // hours and minutes
+ buf[written] = '\0';
+ buf[written - 1] = buf[written - 2];
+ buf[written - 2] = buf[written - 3];
+ buf[written - 3] = ':';
+ Telemetry::ScalarSet(id.extract(), NS_ConvertASCIItoUTF16(buf));
+ }
+ }
+
+ int32_t offset =
+ exploded.tm_params.tp_gmt_offset + exploded.tm_params.tp_dst_offset;
+ FogDatetime dt{exploded.tm_year,
+ static_cast<uint32_t>(exploded.tm_month + 1),
+ static_cast<uint32_t>(exploded.tm_mday),
+ static_cast<uint32_t>(exploded.tm_hour),
+ static_cast<uint32_t>(exploded.tm_min),
+ static_cast<uint32_t>(exploded.tm_sec),
+ static_cast<uint32_t>(exploded.tm_usec * 1000),
+ offset};
+ fog_datetime_set(mId, &dt);
+}
+
+Result<Maybe<PRExplodedTime>, nsCString> DatetimeMetric::TestGetValue(
+ const nsACString& aPingName) const {
+ nsCString err;
+ if (fog_datetime_test_get_error(mId, &err)) {
+ return Err(err);
+ }
+ if (!fog_datetime_test_has_value(mId, &aPingName)) {
+ return Maybe<PRExplodedTime>();
+ }
+ FogDatetime ret{0};
+ fog_datetime_test_get_value(mId, &aPingName, &ret);
+ PRExplodedTime pret{0};
+ pret.tm_year = static_cast<PRInt16>(ret.year);
+ pret.tm_month = static_cast<PRInt32>(ret.month - 1);
+ pret.tm_mday = static_cast<PRInt32>(ret.day);
+ pret.tm_hour = static_cast<PRInt32>(ret.hour);
+ pret.tm_min = static_cast<PRInt32>(ret.minute);
+ pret.tm_sec = static_cast<PRInt32>(ret.second);
+ pret.tm_usec = static_cast<PRInt32>(ret.nano / 1000); // truncated is fine
+ pret.tm_params.tp_gmt_offset = static_cast<PRInt32>(ret.offset_seconds);
+ return Some(std::move(pret));
+}
+
+} // namespace impl
+
+/* virtual */
+JSObject* GleanDatetime::WrapObject(JSContext* aCx,
+ JS::Handle<JSObject*> aGivenProto) {
+ return dom::GleanDatetime_Binding::Wrap(aCx, this, aGivenProto);
+}
+
+void GleanDatetime::Set(const dom::Optional<int64_t>& aValue) {
+ if (aValue.WasPassed()) {
+ PRExplodedTime exploded;
+ PR_ExplodeTime(aValue.Value(), PR_LocalTimeParameters, &exploded);
+ mDatetime.Set(&exploded);
+ } else {
+ mDatetime.Set();
+ }
+}
+
+void GleanDatetime::TestGetValue(JSContext* aCx, const nsACString& aPingName,
+ JS::MutableHandle<JS::Value> aResult,
+ ErrorResult& aRv) {
+ auto result = mDatetime.TestGetValue(aPingName);
+ if (result.isErr()) {
+ aResult.set(JS::UndefinedValue());
+ aRv.ThrowDataError(result.unwrapErr());
+ return;
+ }
+ auto optresult = result.unwrap();
+ if (optresult.isNothing()) {
+ aResult.set(JS::UndefinedValue());
+ } else {
+ double millis =
+ static_cast<double>(PR_ImplodeTime(optresult.ptr())) / PR_USEC_PER_MSEC;
+ JS::Rooted<JSObject*> root(aCx,
+ JS::NewDateObject(aCx, JS::TimeClip(millis)));
+ aResult.setObject(*root);
+ }
+}
+
+} // namespace mozilla::glean
diff --git a/toolkit/components/glean/bindings/private/Datetime.h b/toolkit/components/glean/bindings/private/Datetime.h
new file mode 100644
index 0000000000..1dc4dfbe70
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Datetime.h
@@ -0,0 +1,79 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_glean_GleanDatetime_h
+#define mozilla_glean_GleanDatetime_h
+
+#include "mozilla/dom/BindingDeclarations.h"
+#include "mozilla/glean/bindings/GleanMetric.h"
+#include "mozilla/Maybe.h"
+#include "mozilla/Result.h"
+#include "nsString.h"
+#include "nsWrapperCache.h"
+#include "prtime.h"
+
+namespace mozilla::glean {
+
+namespace impl {
+
+class DatetimeMetric {
+ public:
+ constexpr explicit DatetimeMetric(uint32_t aId) : mId(aId) {}
+
+ /*
+ * Set the datetime to the provided value, or the local now.
+ *
+ * @param amount The date value to set.
+ */
+ void Set(const PRExplodedTime* aValue = nullptr) const;
+
+ /**
+ * **Test-only API**
+ *
+ * Gets the currently stored value as a PRExplodedTime.
+ *
+ * This function will attempt to await the last parent-process task (if any)
+ * writing to the the metric's storage engine before returning a value.
+ * This function will not wait for data from child processes.
+ *
+ * This doesn't clear the stored value.
+ * Parent process only. Panics in child processes.
+ *
+ * @param aPingName The (optional) name of the ping to retrieve the metric
+ * for. Defaults to the first value in `send_in_pings`.
+ *
+ * @return value of the stored metric, or Nothing() if there is no value.
+ */
+ Result<Maybe<PRExplodedTime>, nsCString> TestGetValue(
+ const nsACString& aPingName = nsCString()) const;
+
+ private:
+ const uint32_t mId;
+};
+} // namespace impl
+
+class GleanDatetime final : public GleanMetric {
+ public:
+ explicit GleanDatetime(uint32_t aId, nsISupports* aParent)
+ : GleanMetric(aParent), mDatetime(aId) {}
+
+ virtual JSObject* WrapObject(
+ JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override final;
+
+ void Set(const dom::Optional<int64_t>& aValue);
+
+ void TestGetValue(JSContext* aCx, const nsACString& aPingName,
+ JS::MutableHandle<JS::Value> aResult, ErrorResult& aRv);
+
+ private:
+ virtual ~GleanDatetime() = default;
+
+ const impl::DatetimeMetric mDatetime;
+};
+
+} // namespace mozilla::glean
+
+#endif /* mozilla_glean_GleanDatetime_h */
diff --git a/toolkit/components/glean/bindings/private/Denominator.cpp b/toolkit/components/glean/bindings/private/Denominator.cpp
new file mode 100644
index 0000000000..459bb002a7
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Denominator.cpp
@@ -0,0 +1,64 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/glean/bindings/Denominator.h"
+
+#include "nsString.h"
+#include "mozilla/ResultVariant.h"
+#include "mozilla/dom/GleanMetricsBinding.h"
+#include "mozilla/glean/bindings/ScalarGIFFTMap.h"
+#include "mozilla/glean/fog_ffi_generated.h"
+
+namespace mozilla::glean {
+
+namespace impl {
+
+void DenominatorMetric::Add(int32_t aAmount) const {
+ auto scalarId = ScalarIdForMetric(mId);
+ if (scalarId && aAmount >= 0) {
+ Telemetry::ScalarAdd(scalarId.extract(), aAmount);
+ }
+ fog_denominator_add(mId, aAmount);
+}
+
+Result<Maybe<int32_t>, nsCString> DenominatorMetric::TestGetValue(
+ const nsACString& aPingName) const {
+ nsCString err;
+ if (fog_denominator_test_get_error(mId, &err)) {
+ return Err(err);
+ }
+ if (!fog_denominator_test_has_value(mId, &aPingName)) {
+ return Maybe<int32_t>();
+ }
+ return Some(fog_denominator_test_get_value(mId, &aPingName));
+}
+
+} // namespace impl
+
+/* virtual */
+JSObject* GleanDenominator::WrapObject(JSContext* aCx,
+ JS::Handle<JSObject*> aGivenProto) {
+ return dom::GleanDenominator_Binding::Wrap(aCx, this, aGivenProto);
+}
+
+void GleanDenominator::Add(int32_t aAmount) { mDenominator.Add(aAmount); }
+
+dom::Nullable<int32_t> GleanDenominator::TestGetValue(
+ const nsACString& aPingName, ErrorResult& aRv) {
+ dom::Nullable<int32_t> ret;
+ auto result = mDenominator.TestGetValue(aPingName);
+ if (result.isErr()) {
+ aRv.ThrowDataError(result.unwrapErr());
+ return ret;
+ }
+ auto optresult = result.unwrap();
+ if (!optresult.isNothing()) {
+ ret.SetValue(optresult.value());
+ }
+ return ret;
+}
+
+} // namespace mozilla::glean
diff --git a/toolkit/components/glean/bindings/private/Denominator.h b/toolkit/components/glean/bindings/private/Denominator.h
new file mode 100644
index 0000000000..c52b0cb7ad
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Denominator.h
@@ -0,0 +1,77 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_glean_GleanDenominator_h
+#define mozilla_glean_GleanDenominator_h
+
+#include "mozilla/dom/BindingDeclarations.h"
+#include "mozilla/glean/bindings/GleanMetric.h"
+#include "mozilla/Maybe.h"
+#include "mozilla/Result.h"
+#include "nsString.h"
+
+namespace mozilla::glean {
+
+namespace impl {
+
+class DenominatorMetric {
+ public:
+ constexpr explicit DenominatorMetric(uint32_t aId) : mId(aId) {}
+
+ /*
+ * Increases the counter by `amount`.
+ *
+ * @param aAmount The amount to increase by. Should be positive.
+ */
+ void Add(int32_t aAmount = 1) const;
+
+ /**
+ * **Test-only API**
+ *
+ * Gets the currently stored value as an integer.
+ *
+ * This function will attempt to await the last parent-process task (if any)
+ * writing to the the metric's storage engine before returning a value.
+ * This function will not wait for data from child processes.
+ *
+ * This doesn't clear the stored value.
+ * Parent process only. Panics in child processes.
+ *
+ * @param aPingName The (optional) name of the ping to retrieve the metric
+ * for. Defaults to the first value in `send_in_pings`.
+ *
+ * @return value of the stored metric, or Nothing() if there is no value.
+ */
+ Result<Maybe<int32_t>, nsCString> TestGetValue(
+ const nsACString& aPingName = nsCString()) const;
+
+ private:
+ const uint32_t mId;
+};
+} // namespace impl
+
+class GleanDenominator final : public GleanMetric {
+ public:
+ explicit GleanDenominator(uint32_t id, nsISupports* aParent)
+ : GleanMetric(aParent), mDenominator(id) {}
+
+ virtual JSObject* WrapObject(
+ JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override final;
+
+ void Add(int32_t aAmount);
+
+ dom::Nullable<int32_t> TestGetValue(const nsACString& aPingName,
+ ErrorResult& aRv);
+
+ private:
+ virtual ~GleanDenominator() = default;
+
+ const impl::DenominatorMetric mDenominator;
+};
+
+} // namespace mozilla::glean
+
+#endif /* mozilla_glean_GleanDenominator_h */
diff --git a/toolkit/components/glean/bindings/private/DistributionData.h b/toolkit/components/glean/bindings/private/DistributionData.h
new file mode 100644
index 0000000000..6ff995f222
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/DistributionData.h
@@ -0,0 +1,32 @@
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_glean_DistributionData_h
+#define mozilla_glean_DistributionData_h
+
+#include "nsTHashMap.h"
+
+namespace mozilla::glean {
+
+struct DistributionData final {
+ uint64_t sum;
+ nsTHashMap<nsUint64HashKey, uint64_t> values;
+
+ /**
+ * Create distribution data from the buckets, counts and sum,
+ * as returned by `fog_*_distribution_test_get_value`.
+ */
+ DistributionData(const nsTArray<uint64_t>& aBuckets,
+ const nsTArray<uint64_t>& aCounts, uint64_t aSum)
+ : sum(aSum) {
+ for (size_t i = 0; i < aBuckets.Length(); ++i) {
+ this->values.InsertOrUpdate(aBuckets[i], aCounts[i]);
+ }
+ }
+};
+
+} // namespace mozilla::glean
+
+#endif /* mozilla_glean_DistributionData_h */
diff --git a/toolkit/components/glean/bindings/private/Event.cpp b/toolkit/components/glean/bindings/private/Event.cpp
new file mode 100644
index 0000000000..6d4065947d
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Event.cpp
@@ -0,0 +1,110 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/glean/bindings/Event.h"
+
+#include "nsString.h"
+#include "mozilla/dom/GleanMetricsBinding.h"
+#include "mozilla/dom/ToJSValue.h"
+#include "mozilla/glean/bindings/Common.h"
+#include "jsapi.h"
+#include "js/PropertyAndElement.h" // JS_DefineElement, JS_DefineProperty, JS_Enumerate, JS_GetProperty, JS_GetPropertyById
+
+namespace mozilla::glean {
+
+/* virtual */
+JSObject* GleanEvent::WrapObject(JSContext* aCx,
+ JS::Handle<JSObject*> aGivenProto) {
+ return dom::GleanEvent_Binding::Wrap(aCx, this, aGivenProto);
+}
+
+// Convert all capital letters to "_x" where "x" is the corresponding lowercase.
+nsCString camelToSnake(const nsACString& aCamel) {
+ nsCString snake;
+ const auto* start = aCamel.BeginReading();
+ const auto* end = aCamel.EndReading();
+ for (; start != end; ++start) {
+ if ('A' <= *start && *start <= 'Z') {
+ snake.AppendLiteral("_");
+ snake.Append(static_cast<char>(std::tolower(*start)));
+ } else {
+ snake.Append(*start);
+ }
+ }
+ return snake;
+}
+
+void GleanEvent::Record(
+ const dom::Optional<dom::Record<nsCString, nsCString>>& aExtra) {
+ if (!aExtra.WasPassed()) {
+ mEvent.Record();
+ return;
+ }
+
+ nsTArray<nsCString> extraKeys;
+ nsTArray<nsCString> extraValues;
+ CopyableTArray<Telemetry::EventExtraEntry> telExtras;
+ for (const auto& entry : aExtra.Value().Entries()) {
+ if (entry.mValue.IsVoid()) {
+ // Someone passed undefined/null for this value.
+ // Pretend it wasn't here.
+ continue;
+ }
+ // We accept camelCase extra keys, but Glean requires snake_case.
+ auto snakeKey = camelToSnake(entry.mKey);
+
+ extraKeys.AppendElement(snakeKey);
+ extraValues.AppendElement(entry.mValue);
+ telExtras.EmplaceBack(Telemetry::EventExtraEntry{entry.mKey, entry.mValue});
+ }
+
+ // Since this calls the implementation directly, we need to implement GIFFT
+ // here as well as in EventMetric::Record.
+ auto id = EventIdForMetric(mEvent.mId);
+ if (id) {
+ Telemetry::RecordEvent(id.extract(), Nothing(),
+ telExtras.IsEmpty() ? Nothing() : Some(telExtras));
+ }
+
+ // Calling the implementation directly, because we have a `string->string`
+ // map, not a `T->string` map the C++ API expects.
+ impl::fog_event_record(mEvent.mId, &extraKeys, &extraValues);
+}
+
+void GleanEvent::TestGetValue(
+ const nsACString& aPingName,
+ dom::Nullable<nsTArray<dom::GleanEventRecord>>& aResult, ErrorResult& aRv) {
+ auto resEvents = mEvent.TestGetValue(aPingName);
+ if (resEvents.isErr()) {
+ aRv.ThrowDataError(resEvents.unwrapErr());
+ return;
+ }
+ auto optEvents = resEvents.unwrap();
+ if (optEvents.isNothing()) {
+ return;
+ }
+
+ nsTArray<dom::GleanEventRecord> ret;
+ for (auto& event : optEvents.extract()) {
+ dom::GleanEventRecord record;
+ if (!event.mExtra.IsEmpty()) {
+ record.mExtra.Construct();
+ for (auto& extraEntry : event.mExtra) {
+ dom::binding_detail::RecordEntry<nsCString, nsCString> extra;
+ extra.mKey = std::get<0>(extraEntry);
+ extra.mValue = std::get<1>(extraEntry);
+ record.mExtra.Value().Entries().EmplaceBack(std::move(extra));
+ }
+ }
+ record.mCategory = event.mCategory;
+ record.mName = event.mName;
+ record.mTimestamp = event.mTimestamp;
+ ret.EmplaceBack(std::move(record));
+ }
+ aResult.SetValue(std::move(ret));
+}
+
+} // namespace mozilla::glean
diff --git a/toolkit/components/glean/bindings/private/Event.h b/toolkit/components/glean/bindings/private/Event.h
new file mode 100644
index 0000000000..72fd70410c
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Event.h
@@ -0,0 +1,177 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_glean_GleanEvent_h
+#define mozilla_glean_GleanEvent_h
+
+#include "mozilla/dom/BindingDeclarations.h"
+#include "mozilla/dom/Record.h"
+#include "mozilla/glean/bindings/EventGIFFTMap.h"
+#include "mozilla/glean/bindings/GleanMetric.h"
+#include "mozilla/glean/fog_ffi_generated.h"
+#include "mozilla/ResultVariant.h"
+
+#include "nsString.h"
+#include "nsTArray.h"
+
+namespace mozilla::dom {
+// forward declaration
+struct GleanEventRecord;
+} // namespace mozilla::dom
+
+namespace mozilla::glean {
+
+// forward declaration
+class GleanEvent;
+
+namespace impl {
+
+/**
+ * Represents the recorded data for a single event
+ */
+struct RecordedEvent {
+ public:
+ uint64_t mTimestamp;
+ nsCString mCategory;
+ nsCString mName;
+
+ nsTArray<std::tuple<nsCString, nsCString>> mExtra;
+};
+
+template <class T>
+class EventMetric {
+ friend class mozilla::glean::GleanEvent;
+
+ public:
+ constexpr explicit EventMetric(uint32_t id) : mId(id) {}
+
+ /**
+ * Record an event.
+ *
+ * @param aExtras The list of (extra key, value) pairs. Allowed extra keys are
+ * defined in the metric definition.
+ * If the wrong keys are used or values are too large
+ * an error is report and no event is recorded.
+ */
+ void Record(const Maybe<T>& aExtras = Nothing()) const {
+ auto id = EventIdForMetric(mId);
+ if (id) {
+ // NB. In case `aExtras` is filled we call `ToFfiExtra`, causing
+ // twice the required allocation. We could be smarter and reuse the data.
+ // But this is GIFFT-only allocation, so wait to be told it's a problem.
+ Maybe<CopyableTArray<Telemetry::EventExtraEntry>> telExtras;
+ if (aExtras) {
+ CopyableTArray<Telemetry::EventExtraEntry> extras;
+ auto serializedExtras = aExtras->ToFfiExtra();
+ auto keys = std::move(std::get<0>(serializedExtras));
+ auto values = std::move(std::get<1>(serializedExtras));
+ for (size_t i = 0; i < keys.Length(); i++) {
+ extras.EmplaceBack(Telemetry::EventExtraEntry{keys[i], values[i]});
+ }
+ telExtras = Some(extras);
+ }
+ Telemetry::RecordEvent(id.extract(), Nothing(), telExtras);
+ }
+ if (aExtras) {
+ auto extra = aExtras->ToFfiExtra();
+ fog_event_record(mId, &std::get<0>(extra), &std::get<1>(extra));
+ } else {
+ nsTArray<nsCString> keys;
+ nsTArray<nsCString> vals;
+ fog_event_record(mId, &keys, &vals);
+ }
+ }
+
+ /**
+ * **Test-only API**
+ *
+ * Get a list of currently stored events for this event metric.
+ *
+ * This function will attempt to await the last parent-process task (if any)
+ * writing to the the metric's storage engine before returning a value.
+ * This function will not wait for data from child processes.
+ *
+ * This doesn't clear the stored value.
+ * Parent process only. Panics in child processes.
+ *
+ * @param aPingName The (optional) name of the ping to retrieve the metric
+ * for. Defaults to the first value in `send_in_pings`.
+ *
+ * @return value of the stored metric, or Nothing() if there is no value.
+ */
+ Result<Maybe<nsTArray<RecordedEvent>>, nsCString> TestGetValue(
+ const nsACString& aPingName = nsCString()) const {
+ nsCString err;
+ if (fog_event_test_get_error(mId, &err)) {
+ return Err(err);
+ }
+
+ if (!fog_event_test_has_value(mId, &aPingName)) {
+ return Maybe<nsTArray<RecordedEvent>>();
+ }
+
+ nsTArray<FfiRecordedEvent> events;
+ fog_event_test_get_value(mId, &aPingName, &events);
+
+ nsTArray<RecordedEvent> result;
+ for (const auto& event : events) {
+ auto ev = result.AppendElement();
+ ev->mTimestamp = event.timestamp;
+ ev->mCategory.Append(event.category);
+ ev->mName.Assign(event.name);
+
+ MOZ_ASSERT(event.extras.Length() % 2 == 0);
+ ev->mExtra.SetCapacity(event.extras.Length() / 2);
+ for (unsigned int i = 0; i < event.extras.Length(); i += 2) {
+ // keys & values are interleaved.
+ nsCString key = std::move(event.extras[i]);
+ nsCString value = std::move(event.extras[i + 1]);
+ ev->mExtra.AppendElement(
+ std::make_tuple(std::move(key), std::move(value)));
+ }
+ }
+ return Some(std::move(result));
+ }
+
+ private:
+ static const nsCString ExtraStringForKey(uint32_t aKey);
+
+ const uint32_t mId;
+};
+
+} // namespace impl
+
+struct NoExtraKeys {
+ std::tuple<nsTArray<nsCString>, nsTArray<nsCString>> ToFfiExtra() const {
+ nsTArray<nsCString> extraKeys;
+ nsTArray<nsCString> extraValues;
+ return std::make_tuple(std::move(extraKeys), std::move(extraValues));
+ }
+};
+
+class GleanEvent final : public GleanMetric {
+ public:
+ explicit GleanEvent(uint32_t id, nsISupports* aParent)
+ : GleanMetric(aParent), mEvent(id) {}
+
+ virtual JSObject* WrapObject(
+ JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override final;
+
+ void Record(const dom::Optional<dom::Record<nsCString, nsCString>>& aExtra);
+
+ void TestGetValue(const nsACString& aPingName,
+ dom::Nullable<nsTArray<dom::GleanEventRecord>>& aResult,
+ ErrorResult& aRv);
+
+ private:
+ virtual ~GleanEvent() = default;
+
+ const impl::EventMetric<NoExtraKeys> mEvent;
+};
+
+} // namespace mozilla::glean
+
+#endif /* mozilla_glean_GleanEvent.h */
diff --git a/toolkit/components/glean/bindings/private/Labeled.cpp b/toolkit/components/glean/bindings/private/Labeled.cpp
new file mode 100644
index 0000000000..23527708e0
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Labeled.cpp
@@ -0,0 +1,49 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/glean/bindings/Labeled.h"
+
+#include "mozilla/dom/GleanBinding.h"
+#include "mozilla/glean/fog_ffi_generated.h"
+#include "mozilla/glean/bindings/GleanJSMetricsLookup.h"
+#include "mozilla/glean/bindings/MetricTypes.h"
+#include "mozilla/glean/bindings/ScalarGIFFTMap.h"
+#include "nsString.h"
+
+namespace mozilla::glean {
+
+JSObject* GleanLabeled::WrapObject(JSContext* aCx,
+ JS::Handle<JSObject*> aGivenProto) {
+ return dom::GleanLabeled_Binding::Wrap(aCx, this, aGivenProto);
+}
+
+already_AddRefed<GleanMetric> GleanLabeled::NamedGetter(const nsAString& aName,
+ bool& aFound) {
+ auto label = NS_ConvertUTF16toUTF8(aName);
+ // All strings will map to a label. Either a valid one or `__other__`.
+ aFound = true;
+ uint32_t submetricId = 0;
+ already_AddRefed<GleanMetric> submetric =
+ NewSubMetricFromIds(mTypeId, mId, label, &submetricId, mParent);
+
+ auto mirrorId = ScalarIdForMetric(mId);
+ if (mirrorId) {
+ GetLabeledMirrorLock().apply([&](auto& lock) {
+ auto tuple = std::make_tuple<Telemetry::ScalarID, nsString>(
+ mirrorId.extract(), nsString(aName));
+ lock.ref()->InsertOrUpdate(submetricId, std::move(tuple));
+ });
+ }
+ return submetric;
+}
+
+bool GleanLabeled::NameIsEnumerable(const nsAString& aName) { return false; }
+
+void GleanLabeled::GetSupportedNames(nsTArray<nsString>& aNames) {
+ // We really don't know, so don't do anything.
+}
+
+} // namespace mozilla::glean
diff --git a/toolkit/components/glean/bindings/private/Labeled.h b/toolkit/components/glean/bindings/private/Labeled.h
new file mode 100644
index 0000000000..65e31bd2bd
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Labeled.h
@@ -0,0 +1,248 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_glean_Labeled_h
+#define mozilla_glean_Labeled_h
+
+#include "nsISupports.h"
+#include "nsWrapperCache.h"
+#include "mozilla/dom/BindingDeclarations.h"
+#include "mozilla/glean/bindings/Boolean.h"
+#include "mozilla/glean/bindings/Counter.h"
+#include "mozilla/glean/bindings/GleanMetric.h"
+#include "mozilla/glean/bindings/ScalarGIFFTMap.h"
+#include "mozilla/glean/bindings/String.h"
+#include "mozilla/glean/fog_ffi_generated.h"
+
+enum class DynamicLabel : uint16_t;
+
+namespace mozilla::glean {
+
+namespace impl {
+
+template <typename T, typename E>
+class Labeled {
+ public:
+ constexpr explicit Labeled<T, E>(uint32_t id) : mId(id) {}
+
+ /**
+ * Gets a specific metric for a given label.
+ *
+ * If a set of acceptable labels were specified in the `metrics.yaml` file,
+ * and the given label is not in the set, it will be recorded under the
+ * special `OTHER_LABEL` label.
+ *
+ * If a set of acceptable labels was not specified in the `metrics.yaml` file,
+ * only the first 16 unique labels will be used.
+ * After that, any additional labels will be recorded under the special
+ * `OTHER_LABEL` label.
+ *
+ * @param aLabel - a snake_case string under 30 characters in length,
+ * otherwise the metric will be recorded under the special
+ * `OTHER_LABEL` label and an error will be recorded.
+ */
+ T Get(const nsACString& aLabel) const;
+
+ /**
+ * Gets a specific metric for a given label, using the label's enum variant.
+ *
+ * @param aLabel - a variant of this label's label enum.
+ */
+ T EnumGet(E aLabel) const;
+
+ private:
+ const uint32_t mId;
+};
+
+static inline void UpdateLabeledMirror(Telemetry::ScalarID aMirrorId,
+ uint32_t aSubmetricId,
+ const nsACString& aLabel) {
+ GetLabeledMirrorLock().apply([&](auto& lock) {
+ auto tuple = std::make_tuple<Telemetry::ScalarID, nsString>(
+ std::move(aMirrorId), NS_ConvertUTF8toUTF16(aLabel));
+ lock.ref()->InsertOrUpdate(aSubmetricId, std::move(tuple));
+ });
+}
+
+template <typename E>
+class Labeled<BooleanMetric, E> {
+ public:
+ constexpr explicit Labeled(uint32_t id) : mId(id) {}
+
+ BooleanMetric Get(const nsACString& aLabel) const {
+ auto submetricId = fog_labeled_boolean_get(mId, &aLabel);
+ // If this labeled metric is mirrored, we need to map the submetric id back
+ // to the label string and mirrored scalar so we can mirror its operations.
+ auto mirrorId = ScalarIdForMetric(mId);
+ if (mirrorId) {
+ UpdateLabeledMirror(mirrorId.extract(), submetricId, aLabel);
+ }
+ return BooleanMetric(submetricId);
+ }
+
+ BooleanMetric EnumGet(E aLabel) const {
+ auto submetricId =
+ fog_labeled_boolean_enum_get(mId, static_cast<uint16_t>(aLabel));
+ auto mirrorId = ScalarIdForMetric(mId);
+ if (mirrorId) {
+ // Telemetry's keyed scalars operate on (16-bit) strings,
+ // so we're going to need the string for this enum.
+ nsCString label;
+ fog_labeled_enum_to_str(mId, static_cast<uint16_t>(aLabel), &label);
+ UpdateLabeledMirror(mirrorId.extract(), submetricId, label);
+ }
+ return BooleanMetric(submetricId);
+ }
+
+ private:
+ const uint32_t mId;
+};
+
+template <typename E>
+class Labeled<CounterMetric, E> {
+ public:
+ constexpr explicit Labeled(uint32_t id) : mId(id) {}
+
+ CounterMetric Get(const nsACString& aLabel) const {
+ auto submetricId = fog_labeled_counter_get(mId, &aLabel);
+ // If this labeled metric is mirrored, we need to map the submetric id back
+ // to the label string and mirrored scalar so we can mirror its operations.
+ auto mirrorId = ScalarIdForMetric(mId);
+ if (mirrorId) {
+ UpdateLabeledMirror(mirrorId.extract(), submetricId, aLabel);
+ }
+ return CounterMetric(submetricId);
+ }
+
+ CounterMetric EnumGet(E aLabel) const {
+ auto submetricId =
+ fog_labeled_counter_enum_get(mId, static_cast<uint16_t>(aLabel));
+ auto mirrorId = ScalarIdForMetric(mId);
+ if (mirrorId) {
+ // Telemetry's keyed scalars operate on (16-bit) strings,
+ // so we're going to need the string for this enum.
+ nsCString label;
+ fog_labeled_enum_to_str(mId, static_cast<uint16_t>(aLabel), &label);
+ UpdateLabeledMirror(mirrorId.extract(), submetricId, label);
+ }
+ return CounterMetric(submetricId);
+ }
+
+ private:
+ const uint32_t mId;
+};
+
+template <typename E>
+class Labeled<StringMetric, E> {
+ public:
+ constexpr explicit Labeled(uint32_t id) : mId(id) {}
+
+ StringMetric Get(const nsACString& aLabel) const {
+ auto submetricId = fog_labeled_string_get(mId, &aLabel);
+ // Why no GIFFT map here?
+ // Labeled Strings can't be mirrored. Telemetry has no compatible probe.
+ return StringMetric(submetricId);
+ }
+
+ StringMetric EnumGet(E aLabel) const {
+ auto submetricId =
+ fog_labeled_string_enum_get(mId, static_cast<uint16_t>(aLabel));
+ // Why no GIFFT map here?
+ // Labeled Strings can't be mirrored. Telemetry has no compatible probe.
+ return StringMetric(submetricId);
+ }
+
+ private:
+ const uint32_t mId;
+};
+
+template <>
+class Labeled<BooleanMetric, DynamicLabel> {
+ public:
+ constexpr explicit Labeled(uint32_t id) : mId(id) {}
+
+ BooleanMetric Get(const nsACString& aLabel) const {
+ auto submetricId = fog_labeled_boolean_get(mId, &aLabel);
+ // If this labeled metric is mirrored, we need to map the submetric id back
+ // to the label string and mirrored scalar so we can mirror its operations.
+ auto mirrorId = ScalarIdForMetric(mId);
+ if (mirrorId) {
+ UpdateLabeledMirror(mirrorId.extract(), submetricId, aLabel);
+ }
+ return BooleanMetric(submetricId);
+ }
+
+ BooleanMetric EnumGet(DynamicLabel aLabel) const = delete;
+
+ private:
+ const uint32_t mId;
+};
+
+template <>
+class Labeled<CounterMetric, DynamicLabel> {
+ public:
+ constexpr explicit Labeled(uint32_t id) : mId(id) {}
+
+ CounterMetric Get(const nsACString& aLabel) const {
+ auto submetricId = fog_labeled_counter_get(mId, &aLabel);
+ // If this labeled metric is mirrored, we need to map the submetric id back
+ // to the label string and mirrored scalar so we can mirror its operations.
+ auto mirrorId = ScalarIdForMetric(mId);
+ if (mirrorId) {
+ UpdateLabeledMirror(mirrorId.extract(), submetricId, aLabel);
+ }
+ return CounterMetric(submetricId);
+ }
+
+ CounterMetric EnumGet(DynamicLabel aLabel) const = delete;
+
+ private:
+ const uint32_t mId;
+};
+
+template <>
+class Labeled<StringMetric, DynamicLabel> {
+ public:
+ constexpr explicit Labeled(uint32_t id) : mId(id) {}
+
+ StringMetric Get(const nsACString& aLabel) const {
+ auto submetricId = fog_labeled_string_get(mId, &aLabel);
+ // Why no GIFFT map here?
+ // Labeled Strings can't be mirrored. Telemetry has no compatible probe.
+ return StringMetric(submetricId);
+ }
+
+ StringMetric EnumGet(DynamicLabel aLabel) const = delete;
+
+ private:
+ const uint32_t mId;
+};
+
+} // namespace impl
+
+class GleanLabeled final : public GleanMetric {
+ public:
+ explicit GleanLabeled(uint32_t aId, uint32_t aTypeId, nsISupports* aParent)
+ : GleanMetric(aParent), mId(aId), mTypeId(aTypeId) {}
+
+ JSObject* WrapObject(JSContext* aCx,
+ JS::Handle<JSObject*> aGivenProto) override final;
+
+ already_AddRefed<GleanMetric> NamedGetter(const nsAString& aName,
+ bool& aFound);
+ bool NameIsEnumerable(const nsAString& aName);
+ void GetSupportedNames(nsTArray<nsString>& aNames);
+
+ private:
+ virtual ~GleanLabeled() = default;
+
+ const uint32_t mId;
+ const uint32_t mTypeId;
+};
+
+} // namespace mozilla::glean
+
+#endif /* mozilla_glean_Labeled_h */
diff --git a/toolkit/components/glean/bindings/private/MemoryDistribution.cpp b/toolkit/components/glean/bindings/private/MemoryDistribution.cpp
new file mode 100644
index 0000000000..a580c5df3c
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/MemoryDistribution.cpp
@@ -0,0 +1,89 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/glean/bindings/MemoryDistribution.h"
+
+#include "mozilla/Components.h"
+#include "mozilla/Maybe.h"
+#include "mozilla/ResultVariant.h"
+#include "mozilla/dom/GleanMetricsBinding.h"
+#include "mozilla/glean/bindings/HistogramGIFFTMap.h"
+#include "mozilla/glean/fog_ffi_generated.h"
+#include "nsIClassInfoImpl.h"
+#include "nsJSUtils.h"
+#include "nsPrintfCString.h"
+#include "nsString.h"
+#include "js/PropertyAndElement.h" // JS_DefineProperty
+
+namespace mozilla::glean {
+
+namespace impl {
+
+void MemoryDistributionMetric::Accumulate(size_t aSample) const {
+ auto hgramId = HistogramIdForMetric(mId);
+ if (hgramId) {
+ Telemetry::Accumulate(hgramId.extract(), aSample);
+ }
+ static_assert(sizeof(size_t) <= sizeof(uint64_t),
+ "Memory distribution samples might overflow.");
+ fog_memory_distribution_accumulate(mId, aSample);
+}
+
+Result<Maybe<DistributionData>, nsCString>
+MemoryDistributionMetric::TestGetValue(const nsACString& aPingName) const {
+ nsCString err;
+ if (fog_memory_distribution_test_get_error(mId, &err)) {
+ return Err(err);
+ }
+ if (!fog_memory_distribution_test_has_value(mId, &aPingName)) {
+ return Maybe<DistributionData>();
+ }
+ nsTArray<uint64_t> buckets;
+ nsTArray<uint64_t> counts;
+ uint64_t sum;
+ fog_memory_distribution_test_get_value(mId, &aPingName, &sum, &buckets,
+ &counts);
+ return Some(DistributionData(buckets, counts, sum));
+}
+
+} // namespace impl
+
+/* virtual */
+JSObject* GleanMemoryDistribution::WrapObject(
+ JSContext* aCx, JS::Handle<JSObject*> aGivenProto) {
+ return dom::GleanMemoryDistribution_Binding::Wrap(aCx, this, aGivenProto);
+}
+
+void GleanMemoryDistribution::Accumulate(uint64_t aSample) {
+ mMemoryDist.Accumulate(aSample);
+}
+
+void GleanMemoryDistribution::TestGetValue(
+ const nsACString& aPingName,
+ dom::Nullable<dom::GleanDistributionData>& aRetval, ErrorResult& aRv) {
+ auto result = mMemoryDist.TestGetValue(aPingName);
+ if (result.isErr()) {
+ aRv.ThrowDataError(result.unwrapErr());
+ return;
+ }
+ auto optresult = result.unwrap();
+ if (optresult.isNothing()) {
+ return;
+ }
+
+ dom::GleanDistributionData ret;
+ ret.mSum = optresult.ref().sum;
+ auto& data = optresult.ref().values;
+ for (const auto& entry : data) {
+ dom::binding_detail::RecordEntry<nsCString, uint64_t> bucket;
+ bucket.mKey = nsPrintfCString("%" PRIu64, entry.GetKey());
+ bucket.mValue = entry.GetData();
+ ret.mValues.Entries().EmplaceBack(std::move(bucket));
+ }
+ aRetval.SetValue(std::move(ret));
+}
+
+} // namespace mozilla::glean
diff --git a/toolkit/components/glean/bindings/private/MemoryDistribution.h b/toolkit/components/glean/bindings/private/MemoryDistribution.h
new file mode 100644
index 0000000000..6b58fc7f75
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/MemoryDistribution.h
@@ -0,0 +1,86 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_glean_GleanMemoryDistribution_h
+#define mozilla_glean_GleanMemoryDistribution_h
+
+#include "mozilla/dom/BindingDeclarations.h"
+#include "mozilla/glean/bindings/DistributionData.h"
+#include "mozilla/glean/bindings/GleanMetric.h"
+#include "mozilla/Maybe.h"
+#include "nsTArray.h"
+
+namespace mozilla::dom {
+struct GleanDistributionData;
+} // namespace mozilla::dom
+
+namespace mozilla::glean {
+
+namespace impl {
+
+class MemoryDistributionMetric {
+ public:
+ constexpr explicit MemoryDistributionMetric(uint32_t aId) : mId(aId) {}
+
+ /*
+ * Accumulates the provided sample in the metric.
+ *
+ * @param aSample The sample to be recorded by the metric. The sample is
+ * assumed to be in the confgured memory unit of the metric.
+ *
+ * Notes: Values bigger than 1 Terabyte (2^40 bytes) are truncated and an
+ * InvalidValue error is recorded.
+ */
+ void Accumulate(size_t aSample) const;
+
+ /**
+ * **Test-only API**
+ *
+ * Gets the currently stored value as a DistributionData.
+ *
+ * This function will attempt to await the last parent-process task (if any)
+ * writing to the the metric's storage engine before returning a value.
+ * This function will not wait for data from child processes.
+ *
+ * This doesn't clear the stored value.
+ * Parent process only. Panics in child processes.
+ *
+ * @param aPingName The (optional) name of the ping to retrieve the metric
+ * for. Defaults to the first value in `send_in_pings`.
+ *
+ * @return value of the stored metric, or Nothing() if there is no value.
+ */
+ Result<Maybe<DistributionData>, nsCString> TestGetValue(
+ const nsACString& aPingName = nsCString()) const;
+
+ private:
+ const uint32_t mId;
+};
+} // namespace impl
+
+class GleanMemoryDistribution final : public GleanMetric {
+ public:
+ explicit GleanMemoryDistribution(uint64_t aId, nsISupports* aParent)
+ : GleanMetric(aParent), mMemoryDist(aId) {}
+
+ virtual JSObject* WrapObject(
+ JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override final;
+
+ void Accumulate(uint64_t aSample);
+
+ void TestGetValue(const nsACString& aPingName,
+ dom::Nullable<dom::GleanDistributionData>& aRetval,
+ ErrorResult& aRv);
+
+ private:
+ virtual ~GleanMemoryDistribution() = default;
+
+ const impl::MemoryDistributionMetric mMemoryDist;
+};
+
+} // namespace mozilla::glean
+
+#endif /* mozilla_glean_GleanMemoryDistribution_h */
diff --git a/toolkit/components/glean/bindings/private/Numerator.cpp b/toolkit/components/glean/bindings/private/Numerator.cpp
new file mode 100644
index 0000000000..87f931e53d
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Numerator.cpp
@@ -0,0 +1,73 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/glean/bindings/Numerator.h"
+
+#include "nsString.h"
+#include "mozilla/ResultVariant.h"
+#include "mozilla/dom/GleanMetricsBinding.h"
+#include "mozilla/glean/bindings/ScalarGIFFTMap.h"
+#include "mozilla/glean/fog_ffi_generated.h"
+#include "jsapi.h"
+
+namespace mozilla::glean {
+
+namespace impl {
+
+void NumeratorMetric::AddToNumerator(int32_t aAmount) const {
+ auto scalarId = ScalarIdForMetric(mId);
+ if (scalarId && aAmount >= 0) {
+ Telemetry::ScalarAdd(scalarId.extract(), u"numerator"_ns, aAmount);
+ }
+ fog_numerator_add_to_numerator(mId, aAmount);
+}
+
+Result<Maybe<std::pair<int32_t, int32_t>>, nsCString>
+NumeratorMetric::TestGetValue(const nsACString& aPingName) const {
+ nsCString err;
+ if (fog_numerator_test_get_error(mId, &err)) {
+ return Err(err);
+ }
+ if (!fog_numerator_test_has_value(mId, &aPingName)) {
+ return Maybe<std::pair<int32_t, int32_t>>();
+ }
+ int32_t num = 0;
+ int32_t den = 0;
+ fog_numerator_test_get_value(mId, &aPingName, &num, &den);
+ return Some(std::make_pair(num, den));
+}
+
+} // namespace impl
+
+/* virtual */
+JSObject* GleanNumerator::WrapObject(JSContext* aCx,
+ JS::Handle<JSObject*> aGivenProto) {
+ return dom::GleanNumerator_Binding::Wrap(aCx, this, aGivenProto);
+}
+
+void GleanNumerator::AddToNumerator(int32_t aAmount) {
+ mNumerator.AddToNumerator(aAmount);
+}
+
+void GleanNumerator::TestGetValue(const nsACString& aPingName,
+ dom::Nullable<dom::GleanRateData>& aResult,
+ ErrorResult& aRv) {
+ auto result = mNumerator.TestGetValue(aPingName);
+ if (result.isErr()) {
+ aRv.ThrowDataError(result.unwrapErr());
+ return;
+ }
+ auto optresult = result.unwrap();
+ if (!optresult.isNothing()) {
+ dom::GleanRateData ret;
+ auto pair = optresult.extract();
+ ret.mNumerator = pair.first;
+ ret.mDenominator = pair.second;
+ aResult.SetValue(std::move(ret));
+ }
+}
+
+} // namespace mozilla::glean
diff --git a/toolkit/components/glean/bindings/private/Numerator.h b/toolkit/components/glean/bindings/private/Numerator.h
new file mode 100644
index 0000000000..a2ea02936a
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Numerator.h
@@ -0,0 +1,84 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_glean_GleanNumerator_h
+#define mozilla_glean_GleanNumerator_h
+
+#include "mozilla/dom/BindingDeclarations.h"
+#include "mozilla/glean/bindings/GleanMetric.h"
+#include "mozilla/Maybe.h"
+#include "mozilla/Result.h"
+#include "nsString.h"
+
+namespace mozilla::dom {
+struct GleanRateData;
+} // namespace mozilla::dom
+
+namespace mozilla::glean {
+
+namespace impl {
+
+// Actually a RateMetric, but one whose denominator is a CounterMetric external
+// to the RateMetric.
+class NumeratorMetric {
+ public:
+ constexpr explicit NumeratorMetric(uint32_t aId) : mId(aId) {}
+
+ /*
+ * Increases the numerator by `amount`.
+ *
+ * @param aAmount The amount to increase by. Should be positive.
+ */
+ void AddToNumerator(int32_t aAmount = 1) const;
+
+ /**
+ * **Test-only API**
+ *
+ * Gets the currently stored value as a pair of integers.
+ *
+ * This function will attempt to await the last parent-process task (if any)
+ * writing to the the metric's storage engine before returning a value.
+ * This function will not wait for data from child processes.
+ *
+ * This doesn't clear the stored value.
+ * Parent process only. Panics in child processes.
+ *
+ * @param aPingName The (optional) name of the ping to retrieve the metric
+ * for. Defaults to the first value in `send_in_pings`.
+ *
+ * @return value of the stored metric, or Nothing() if there is no value.
+ */
+ Result<Maybe<std::pair<int32_t, int32_t>>, nsCString> TestGetValue(
+ const nsACString& aPingName = nsCString()) const;
+
+ private:
+ const uint32_t mId;
+};
+} // namespace impl
+
+class GleanNumerator final : public GleanMetric {
+ public:
+ explicit GleanNumerator(uint32_t id, nsISupports* aParent)
+ : GleanMetric(aParent), mNumerator(id) {}
+
+ virtual JSObject* WrapObject(
+ JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override final;
+
+ void AddToNumerator(int32_t aAmount);
+
+ void TestGetValue(const nsACString& aPingName,
+ dom::Nullable<dom::GleanRateData>& aResult,
+ ErrorResult& aRv);
+
+ private:
+ virtual ~GleanNumerator() = default;
+
+ const impl::NumeratorMetric mNumerator;
+};
+
+} // namespace mozilla::glean
+
+#endif /* mozilla_glean_GleanNumerator_h */
diff --git a/toolkit/components/glean/bindings/private/Ping.cpp b/toolkit/components/glean/bindings/private/Ping.cpp
new file mode 100644
index 0000000000..19f4fb5f77
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Ping.cpp
@@ -0,0 +1,85 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/glean/bindings/Ping.h"
+
+#include "mozilla/AppShutdown.h"
+#include "mozilla/ClearOnShutdown.h"
+#include "mozilla/Components.h"
+#include "nsIClassInfoImpl.h"
+#include "nsTHashMap.h"
+#include "nsString.h"
+
+namespace mozilla::glean {
+
+namespace impl {
+
+using CallbackMapType = nsTHashMap<uint32_t, PingTestCallback>;
+using MetricIdToCallbackMutex = StaticDataMutex<UniquePtr<CallbackMapType>>;
+static Maybe<MetricIdToCallbackMutex::AutoLock> GetCallbackMapLock() {
+ static MetricIdToCallbackMutex sCallbacks("sCallbacks");
+ auto lock = sCallbacks.Lock();
+ // Test callbacks will continue to work until the end of AppShutdownTelemetry
+ if (AppShutdown::IsInOrBeyond(ShutdownPhase::XPCOMWillShutdown)) {
+ return Nothing();
+ }
+ if (!*lock) {
+ *lock = MakeUnique<CallbackMapType>();
+ RunOnShutdown(
+ [&] {
+ auto lock = sCallbacks.Lock();
+ *lock = nullptr; // deletes, see UniquePtr.h
+ },
+ ShutdownPhase::XPCOMWillShutdown);
+ }
+ return Some(std::move(lock));
+}
+
+void Ping::Submit(const nsACString& aReason) const {
+ {
+ auto callback = Maybe<PingTestCallback>();
+ GetCallbackMapLock().apply(
+ [&](auto& lock) { callback = lock.ref()->Extract(mId); });
+ // Calling the callback outside of the lock allows it to register a new
+ // callback itself.
+ if (callback) {
+ callback.extract()(aReason);
+ }
+ }
+ fog_submit_ping_by_id(mId, &aReason);
+}
+
+void Ping::TestBeforeNextSubmit(PingTestCallback&& aCallback) const {
+ {
+ GetCallbackMapLock().apply(
+ [&](auto& lock) { lock.ref()->InsertOrUpdate(mId, aCallback); });
+ }
+}
+
+} // namespace impl
+
+NS_IMPL_CLASSINFO(GleanPing, nullptr, 0, {0})
+NS_IMPL_ISUPPORTS_CI(GleanPing, nsIGleanPing)
+
+NS_IMETHODIMP
+GleanPing::Submit(const nsACString& aReason) {
+ mPing.Submit(aReason);
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+GleanPing::TestBeforeNextSubmit(nsIGleanPingTestCallback* aCallback) {
+ if (NS_WARN_IF(!aCallback)) {
+ return NS_ERROR_INVALID_ARG;
+ }
+ // Throw the bare ptr into a COM ptr to keep it around in the lambda.
+ nsCOMPtr<nsIGleanPingTestCallback> callback = aCallback;
+ mPing.TestBeforeNextSubmit(
+ [callback](const nsACString& aReason) { callback->Call(aReason); });
+ return NS_OK;
+}
+
+} // namespace mozilla::glean
diff --git a/toolkit/components/glean/bindings/private/Ping.h b/toolkit/components/glean/bindings/private/Ping.h
new file mode 100644
index 0000000000..2a92d87995
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Ping.h
@@ -0,0 +1,83 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_glean_Ping_h
+#define mozilla_glean_Ping_h
+
+#include "mozilla/DataMutex.h"
+#include "mozilla/glean/fog_ffi_generated.h"
+#include "mozilla/Maybe.h"
+#include "nsIGleanPing.h"
+#include "nsString.h"
+
+namespace mozilla::glean {
+
+typedef std::function<void(const nsACString& aReason)> PingTestCallback;
+
+namespace impl {
+
+class Ping {
+ public:
+ constexpr explicit Ping(uint32_t aId) : mId(aId) {}
+
+ /**
+ * Collect and submit the ping for eventual upload.
+ *
+ * This will collect all stored data to be included in the ping.
+ * Data with lifetime `ping` will then be reset.
+ *
+ * If the ping is configured with `send_if_empty = false`
+ * and the ping currently contains no content,
+ * it will not be queued for upload.
+ * If the ping is configured with `send_if_empty = true`
+ * it will be queued for upload even if empty.
+ *
+ * Pings always contain the `ping_info` and `client_info` sections.
+ * See [ping
+ * sections](https://mozilla.github.io/glean/book/user/pings/index.html#ping-sections)
+ * for details.
+ *
+ * @param aReason - Optional. The reason the ping is being submitted.
+ * Must match one of the configured `reason_codes`.
+ */
+ void Submit(const nsACString& aReason = nsCString()) const;
+
+ /**
+ * **Test-only API**
+ *
+ * Register a callback to be called right before this ping is next submitted.
+ * The provided function is called exactly once before submitting.
+ *
+ * Note: The callback will be called on any call to submit.
+ * A ping may not be sent afterwards, e.g. if the ping is empty and
+ * `send_if_empty` is `false`
+ *
+ * @param aCallback - The callback to call on the next submit.
+ */
+ void TestBeforeNextSubmit(PingTestCallback&& aCallback) const;
+
+ private:
+ const uint32_t mId;
+};
+
+} // namespace impl
+
+class GleanPing final : public nsIGleanPing {
+ public:
+ NS_DECL_ISUPPORTS
+ NS_DECL_NSIGLEANPING
+
+ explicit GleanPing(uint32_t aId) : mPing(aId) {}
+
+ private:
+ virtual ~GleanPing() = default;
+
+ const impl::Ping mPing;
+};
+
+} // namespace mozilla::glean
+
+#endif /* mozilla_glean_Ping_h */
diff --git a/toolkit/components/glean/bindings/private/Quantity.cpp b/toolkit/components/glean/bindings/private/Quantity.cpp
new file mode 100644
index 0000000000..9b7034e013
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Quantity.cpp
@@ -0,0 +1,68 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/glean/bindings/Quantity.h"
+
+#include "mozilla/ResultVariant.h"
+#include "mozilla/dom/GleanMetricsBinding.h"
+#include "mozilla/glean/bindings/ScalarGIFFTMap.h"
+#include "mozilla/glean/fog_ffi_generated.h"
+#include "nsString.h"
+
+namespace mozilla::glean {
+
+namespace impl {
+
+void QuantityMetric::Set(int64_t aValue) const {
+ auto scalarId = ScalarIdForMetric(mId);
+ if (scalarId && aValue >= 0) {
+ uint32_t theValue = static_cast<uint32_t>(aValue);
+ if (aValue > std::numeric_limits<uint32_t>::max()) {
+ theValue = std::numeric_limits<uint32_t>::max();
+ }
+ Telemetry::ScalarSet(scalarId.extract(), theValue);
+ }
+ fog_quantity_set(mId, aValue);
+}
+
+Result<Maybe<int64_t>, nsCString> QuantityMetric::TestGetValue(
+ const nsACString& aPingName) const {
+ nsCString err;
+ if (fog_quantity_test_get_error(mId, &err)) {
+ return Err(err);
+ }
+ if (!fog_quantity_test_has_value(mId, &aPingName)) {
+ return Maybe<int64_t>();
+ }
+ return Some(fog_quantity_test_get_value(mId, &aPingName));
+}
+
+} // namespace impl
+
+/* virtual */
+JSObject* GleanQuantity::WrapObject(JSContext* aCx,
+ JS::Handle<JSObject*> aGivenProto) {
+ return dom::GleanQuantity_Binding::Wrap(aCx, this, aGivenProto);
+}
+
+void GleanQuantity::Set(int64_t aValue) { mQuantity.Set(aValue); }
+
+dom::Nullable<int64_t> GleanQuantity::TestGetValue(const nsACString& aPingName,
+ ErrorResult& aRv) {
+ dom::Nullable<int64_t> ret;
+ auto result = mQuantity.TestGetValue(aPingName);
+ if (result.isErr()) {
+ aRv.ThrowDataError(result.unwrapErr());
+ return ret;
+ }
+ auto optresult = result.unwrap();
+ if (!optresult.isNothing()) {
+ ret.SetValue(optresult.value());
+ }
+ return ret;
+}
+
+} // namespace mozilla::glean
diff --git a/toolkit/components/glean/bindings/private/Quantity.h b/toolkit/components/glean/bindings/private/Quantity.h
new file mode 100644
index 0000000000..bf7485a33c
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Quantity.h
@@ -0,0 +1,77 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_glean_GleanQuantity_h
+#define mozilla_glean_GleanQuantity_h
+
+#include "mozilla/dom/BindingDeclarations.h"
+#include "mozilla/glean/bindings/GleanMetric.h"
+#include "nsTString.h"
+#include "nsIScriptError.h"
+
+namespace mozilla::glean {
+
+namespace impl {
+
+class QuantityMetric {
+ public:
+ constexpr explicit QuantityMetric(uint32_t id) : mId(id) {}
+
+ /**
+ * Set to the specified value.
+ *
+ * @param aValue the value to set.
+ */
+ void Set(int64_t aValue) const;
+
+ /**
+ * **Test-only API**
+ *
+ * Gets the currently stored value.
+ *
+ * This function will attempt to await the last parent-process task (if any)
+ * writing to the the metric's storage engine before returning a value.
+ * This function will not wait for data from child processes.
+ *
+ * This doesn't clear the stored value.
+ * Parent process only. Panics in child processes.
+ *
+ * @param aPingName The (optional) name of the ping to retrieve the metric
+ * for. Defaults to the first value in `send_in_pings`.
+ *
+ * @return value of the stored metric.
+ */
+ Result<Maybe<int64_t>, nsCString> TestGetValue(
+ const nsACString& aPingName = nsCString()) const;
+
+ private:
+ const uint32_t mId;
+};
+
+} // namespace impl
+
+class GleanQuantity final : public GleanMetric {
+ public:
+ explicit GleanQuantity(uint32_t id, nsISupports* aParent)
+ : GleanMetric(aParent), mQuantity(id) {}
+
+ virtual JSObject* WrapObject(
+ JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override final;
+
+ void Set(int64_t aValue);
+
+ dom::Nullable<int64_t> TestGetValue(const nsACString& aPingName,
+ ErrorResult& aRv);
+
+ private:
+ virtual ~GleanQuantity() = default;
+
+ const impl::QuantityMetric mQuantity;
+};
+
+} // namespace mozilla::glean
+
+#endif /* mozilla_glean_GleanQuantity.h */
diff --git a/toolkit/components/glean/bindings/private/Rate.cpp b/toolkit/components/glean/bindings/private/Rate.cpp
new file mode 100644
index 0000000000..d317b5ad7d
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Rate.cpp
@@ -0,0 +1,86 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/glean/bindings/Rate.h"
+
+#include "jsapi.h"
+#include "nsString.h"
+#include "mozilla/ErrorResult.h"
+#include "mozilla/ResultVariant.h"
+#include "mozilla/dom/GleanMetricsBinding.h"
+#include "mozilla/glean/bindings/ScalarGIFFTMap.h"
+#include "mozilla/glean/fog_ffi_generated.h"
+
+namespace mozilla::glean {
+
+namespace impl {
+
+void RateMetric::AddToNumerator(int32_t aAmount) const {
+ auto scalarId = ScalarIdForMetric(mId);
+ if (scalarId && aAmount >= 0) {
+ Telemetry::ScalarAdd(scalarId.extract(), u"numerator"_ns, aAmount);
+ }
+ fog_rate_add_to_numerator(mId, aAmount);
+}
+
+void RateMetric::AddToDenominator(int32_t aAmount) const {
+ auto scalarId = ScalarIdForMetric(mId);
+ if (scalarId && aAmount >= 0) {
+ Telemetry::ScalarAdd(scalarId.extract(), u"denominator"_ns, aAmount);
+ }
+ fog_rate_add_to_denominator(mId, aAmount);
+}
+
+Result<Maybe<std::pair<int32_t, int32_t>>, nsCString> RateMetric::TestGetValue(
+ const nsACString& aPingName) const {
+ nsCString err;
+ if (fog_rate_test_get_error(mId, &err)) {
+ return Err(err);
+ }
+ if (!fog_rate_test_has_value(mId, &aPingName)) {
+ return Maybe<std::pair<int32_t, int32_t>>();
+ }
+ int32_t num = 0;
+ int32_t den = 0;
+ fog_rate_test_get_value(mId, &aPingName, &num, &den);
+ return Some(std::make_pair(num, den));
+}
+
+} // namespace impl
+
+/* virtual */
+JSObject* GleanRate::WrapObject(JSContext* aCx,
+ JS::Handle<JSObject*> aGivenProto) {
+ return dom::GleanRate_Binding::Wrap(aCx, this, aGivenProto);
+}
+
+void GleanRate::AddToNumerator(int32_t aAmount) {
+ mRate.AddToNumerator(aAmount);
+}
+
+void GleanRate::AddToDenominator(int32_t aAmount) {
+ mRate.AddToDenominator(aAmount);
+}
+
+void GleanRate::TestGetValue(const nsACString& aPingName,
+ dom::Nullable<dom::GleanRateData>& aResult,
+ ErrorResult& aRv) {
+ auto result = mRate.TestGetValue(aPingName);
+ if (result.isErr()) {
+ aRv.ThrowDataError(result.unwrapErr());
+ return;
+ }
+ auto optresult = result.unwrap();
+ if (!optresult.isNothing()) {
+ dom::GleanRateData ret;
+ auto pair = optresult.extract();
+ ret.mNumerator = pair.first;
+ ret.mDenominator = pair.second;
+ aResult.SetValue(std::move(ret));
+ }
+}
+
+} // namespace mozilla::glean
diff --git a/toolkit/components/glean/bindings/private/Rate.h b/toolkit/components/glean/bindings/private/Rate.h
new file mode 100644
index 0000000000..227372bdd2
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Rate.h
@@ -0,0 +1,90 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_glean_GleanRate_h
+#define mozilla_glean_GleanRate_h
+
+#include "mozilla/dom/BindingDeclarations.h"
+#include "mozilla/glean/bindings/GleanMetric.h"
+#include "mozilla/Maybe.h"
+#include "mozilla/Result.h"
+#include "nsString.h"
+
+namespace mozilla::dom {
+struct GleanRateData;
+} // namespace mozilla::dom
+
+namespace mozilla::glean {
+
+namespace impl {
+
+class RateMetric {
+ public:
+ constexpr explicit RateMetric(uint32_t aId) : mId(aId) {}
+
+ /*
+ * Increases the numerator by `amount`.
+ *
+ * @param aAmount The amount to increase by. Should be positive.
+ */
+ void AddToNumerator(int32_t aAmount = 1) const;
+
+ /*
+ * Increases the denominator by `amount`.
+ *
+ * @param aAmount The amount to increase by. Should be positive.
+ */
+ void AddToDenominator(int32_t aAmount = 1) const;
+
+ /**
+ * **Test-only API**
+ *
+ * Gets the currently stored value as a pair of integers.
+ *
+ * This function will attempt to await the last parent-process task (if any)
+ * writing to the the metric's storage engine before returning a value.
+ * This function will not wait for data from child processes.
+ *
+ * This doesn't clear the stored value.
+ * Parent process only. Panics in child processes.
+ *
+ * @param aPingName The (optional) name of the ping to retrieve the metric
+ * for. Defaults to the first value in `send_in_pings`.
+ *
+ * @return value of the stored metric, or Nothing() if there is no value.
+ */
+ Result<Maybe<std::pair<int32_t, int32_t>>, nsCString> TestGetValue(
+ const nsACString& aPingName = nsCString()) const;
+
+ private:
+ const uint32_t mId;
+};
+} // namespace impl
+
+class GleanRate final : public GleanMetric {
+ public:
+ explicit GleanRate(uint32_t id, nsISupports* aParent)
+ : GleanMetric(aParent), mRate(id) {}
+
+ virtual JSObject* WrapObject(
+ JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override final;
+
+ void AddToNumerator(int32_t aAmount);
+ void AddToDenominator(int32_t aAmount);
+
+ void TestGetValue(const nsACString& aPingName,
+ dom::Nullable<dom::GleanRateData>& aResult,
+ ErrorResult& aRv);
+
+ private:
+ virtual ~GleanRate() = default;
+
+ const impl::RateMetric mRate;
+};
+
+} // namespace mozilla::glean
+
+#endif /* mozilla_glean_GleanRate_h */
diff --git a/toolkit/components/glean/bindings/private/String.cpp b/toolkit/components/glean/bindings/private/String.cpp
new file mode 100644
index 0000000000..f012884c8c
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/String.cpp
@@ -0,0 +1,75 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/glean/bindings/String.h"
+
+#include "jsapi.h"
+#include "js/String.h"
+#include "nsString.h"
+#include "mozilla/ErrorResult.h"
+#include "mozilla/ResultVariant.h"
+#include "mozilla/dom/GleanMetricsBinding.h"
+#include "mozilla/glean/bindings/ScalarGIFFTMap.h"
+#include "mozilla/glean/fog_ffi_generated.h"
+
+namespace mozilla::glean {
+
+namespace impl {
+
+void StringMetric::Set(const nsACString& aValue) const {
+ auto scalarId = ScalarIdForMetric(mId);
+ if (scalarId) {
+ Telemetry::ScalarSet(scalarId.extract(), NS_ConvertUTF8toUTF16(aValue));
+ }
+ fog_string_set(mId, &aValue);
+}
+
+Result<Maybe<nsCString>, nsCString> StringMetric::TestGetValue(
+ const nsACString& aPingName) const {
+ nsCString err;
+ if (fog_string_test_get_error(mId, &err)) {
+ return Err(err);
+ }
+ if (!fog_string_test_has_value(mId, &aPingName)) {
+ return Maybe<nsCString>();
+ }
+ nsCString ret;
+ fog_string_test_get_value(mId, &aPingName, &ret);
+ return Some(ret);
+}
+
+} // namespace impl
+
+/* virtual */
+JSObject* GleanString::WrapObject(JSContext* aCx,
+ JS::Handle<JSObject*> aGivenProto) {
+ return dom::GleanString_Binding::Wrap(aCx, this, aGivenProto);
+}
+
+void GleanString::Set(const nsACString& aValue) {
+ if (aValue.IsVoid()) {
+ // TODO: Instrument this error (bug 1691073)
+ return;
+ }
+ mString.Set(aValue);
+}
+
+void GleanString::TestGetValue(const nsACString& aPingName, nsCString& aResult,
+ ErrorResult& aRv) {
+ auto result = mString.TestGetValue(aPingName);
+ if (result.isErr()) {
+ aRv.ThrowDataError(result.unwrapErr());
+ return;
+ }
+ auto optresult = result.unwrap();
+ if (!optresult.isNothing()) {
+ aResult.Assign(optresult.extract());
+ } else {
+ aResult.SetIsVoid(true);
+ }
+}
+
+} // namespace mozilla::glean
diff --git a/toolkit/components/glean/bindings/private/String.h b/toolkit/components/glean/bindings/private/String.h
new file mode 100644
index 0000000000..b4aadb63f9
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/String.h
@@ -0,0 +1,80 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_glean_GleanString_h
+#define mozilla_glean_GleanString_h
+
+#include "mozilla/dom/BindingDeclarations.h"
+#include "mozilla/glean/bindings/GleanMetric.h"
+#include "mozilla/Maybe.h"
+#include "mozilla/Result.h"
+#include "nsString.h"
+
+namespace mozilla::glean {
+
+namespace impl {
+
+class StringMetric {
+ public:
+ constexpr explicit StringMetric(uint32_t aId) : mId(aId) {}
+
+ /*
+ * Set to the specified value.
+ *
+ * Truncates the value if it is longer than 100 bytes and logs an error.
+ * See https://mozilla.github.io/glean/book/user/metrics/string.html#limits.
+ *
+ * @param aValue The string to set the metric to.
+ */
+ void Set(const nsACString& aValue) const;
+
+ /**
+ * **Test-only API**
+ *
+ * Gets the currently stored value as a string.
+ *
+ * This function will attempt to await the last parent-process task (if any)
+ * writing to the the metric's storage engine before returning a value.
+ * This function will not wait for data from child processes.
+ *
+ * This doesn't clear the stored value.
+ * Parent process only. Panics in child processes.
+ *
+ * @param aPingName The (optional) name of the ping to retrieve the metric
+ * for. Defaults to the first value in `send_in_pings`.
+ *
+ * @return value of the stored metric, or Nothing() if there is no value.
+ */
+ Result<Maybe<nsCString>, nsCString> TestGetValue(
+ const nsACString& aPingName = nsCString()) const;
+
+ private:
+ const uint32_t mId;
+};
+} // namespace impl
+
+class GleanString final : public GleanMetric {
+ public:
+ explicit GleanString(uint32_t aId, nsISupports* aParent)
+ : GleanMetric(aParent), mString(aId) {}
+
+ virtual JSObject* WrapObject(
+ JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override final;
+
+ void Set(const nsACString& aValue);
+
+ void TestGetValue(const nsACString& aPingName, nsCString& aResult,
+ ErrorResult& aRv);
+
+ virtual ~GleanString() = default;
+
+ private:
+ const impl::StringMetric mString;
+};
+
+} // namespace mozilla::glean
+
+#endif /* mozilla_glean_GleanString_h */
diff --git a/toolkit/components/glean/bindings/private/StringList.cpp b/toolkit/components/glean/bindings/private/StringList.cpp
new file mode 100644
index 0000000000..b2875807a1
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/StringList.cpp
@@ -0,0 +1,80 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/glean/bindings/StringList.h"
+
+#include "mozilla/ResultVariant.h"
+#include "mozilla/dom/ToJSValue.h"
+#include "mozilla/dom/GleanMetricsBinding.h"
+#include "mozilla/glean/bindings/ScalarGIFFTMap.h"
+#include "mozilla/glean/fog_ffi_generated.h"
+#include "nsString.h"
+#include "nsTArray.h"
+
+namespace mozilla::glean {
+
+namespace impl {
+
+void StringListMetric::Add(const nsACString& aValue) const {
+ auto scalarId = ScalarIdForMetric(mId);
+ if (scalarId) {
+ Telemetry::ScalarSet(scalarId.extract(), NS_ConvertUTF8toUTF16(aValue),
+ true);
+ }
+ fog_string_list_add(mId, &aValue);
+}
+
+void StringListMetric::Set(const nsTArray<nsCString>& aValue) const {
+ // Calling `Set` on a mirrored labeled_string is likely an error.
+ // We can't remove keys from the mirror scalar and handle this 'properly',
+ // so you shouldn't use this operation at all.
+ (void)NS_WARN_IF(ScalarIdForMetric(mId).isSome());
+ fog_string_list_set(mId, &aValue);
+}
+
+Result<Maybe<nsTArray<nsCString>>, nsCString> StringListMetric::TestGetValue(
+ const nsACString& aPingName) const {
+ nsCString err;
+ if (fog_string_list_test_get_error(mId, &err)) {
+ return Err(err);
+ }
+ if (!fog_string_list_test_has_value(mId, &aPingName)) {
+ return Maybe<nsTArray<nsCString>>();
+ }
+ nsTArray<nsCString> ret;
+ fog_string_list_test_get_value(mId, &aPingName, &ret);
+ return Some(std::move(ret));
+}
+
+} // namespace impl
+
+/* virtual */
+JSObject* GleanStringList::WrapObject(JSContext* aCx,
+ JS::Handle<JSObject*> aGivenProto) {
+ return dom::GleanStringList_Binding::Wrap(aCx, this, aGivenProto);
+}
+
+void GleanStringList::Add(const nsACString& aValue) { mStringList.Add(aValue); }
+
+void GleanStringList::Set(const dom::Sequence<nsCString>& aValue) {
+ mStringList.Set(aValue);
+}
+
+void GleanStringList::TestGetValue(const nsACString& aPingName,
+ dom::Nullable<nsTArray<nsCString>>& aResult,
+ ErrorResult& aRv) {
+ auto result = mStringList.TestGetValue(aPingName);
+ if (result.isErr()) {
+ aRv.ThrowDataError(result.unwrapErr());
+ return;
+ }
+ auto optresult = result.unwrap();
+ if (!optresult.isNothing()) {
+ aResult.SetValue(optresult.extract());
+ }
+}
+
+} // namespace mozilla::glean
diff --git a/toolkit/components/glean/bindings/private/StringList.h b/toolkit/components/glean/bindings/private/StringList.h
new file mode 100644
index 0000000000..94cb830cf6
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/StringList.h
@@ -0,0 +1,93 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_glean_GleanStringList_h
+#define mozilla_glean_GleanStringList_h
+
+#include "mozilla/Maybe.h"
+#include "mozilla/dom/BindingDeclarations.h"
+#include "mozilla/glean/bindings/GleanMetric.h"
+#include "nsString.h"
+#include "nsTArray.h"
+
+namespace mozilla::glean {
+
+namespace impl {
+
+class StringListMetric {
+ public:
+ constexpr explicit StringListMetric(uint32_t aId) : mId(aId) {}
+
+ /*
+ * Adds a new string to the list.
+ *
+ * Truncates the value if it is longer than 50 bytes and logs an error.
+ *
+ * @param aValue The string to add.
+ */
+ void Add(const nsACString& aValue) const;
+
+ /*
+ * Set to a specific list of strings.
+ *
+ * Truncates any values longer than 50 bytes and logs an error.
+ * Truncates the list if it is over 20 items long.
+ * See
+ * https://mozilla.github.io/glean/book/user/metrics/string_list.html#limits.
+ *
+ * @param aValue The list of strings to set the metric to.
+ */
+ void Set(const nsTArray<nsCString>& aValue) const;
+
+ /**
+ * **Test-only API**
+ *
+ * Gets the currently stored value.
+ *
+ * This function will attempt to await the last parent-process task (if any)
+ * writing to the the metric's storage engine before returning a value.
+ * This function will not wait for data from child processes.
+ *
+ * This doesn't clear the stored value.
+ * Parent process only. Panics in child processes.
+ *
+ * @param aPingName The (optional) name of the ping to retrieve the metric
+ * for. Defaults to the first value in `send_in_pings`.
+ *
+ * @return value of the stored metric, or Nothing() if there is no value.
+ */
+ Result<Maybe<nsTArray<nsCString>>, nsCString> TestGetValue(
+ const nsACString& aPingName = nsCString()) const;
+
+ private:
+ const uint32_t mId;
+};
+} // namespace impl
+
+class GleanStringList final : public GleanMetric {
+ public:
+ explicit GleanStringList(uint32_t aId, nsISupports* aParent)
+ : GleanMetric(aParent), mStringList(aId) {}
+
+ virtual JSObject* WrapObject(
+ JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override final;
+
+ void Add(const nsACString& aValue);
+ void Set(const dom::Sequence<nsCString>& aValue);
+
+ void TestGetValue(const nsACString& aPingName,
+ dom::Nullable<nsTArray<nsCString>>& aResult,
+ ErrorResult& aRv);
+
+ private:
+ virtual ~GleanStringList() = default;
+
+ const impl::StringListMetric mStringList;
+};
+
+} // namespace mozilla::glean
+
+#endif /* mozilla_glean_GleanStringList_h */
diff --git a/toolkit/components/glean/bindings/private/Text.cpp b/toolkit/components/glean/bindings/private/Text.cpp
new file mode 100644
index 0000000000..fd36f66136
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Text.cpp
@@ -0,0 +1,64 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/glean/bindings/Text.h"
+
+#include "jsapi.h"
+#include "js/String.h"
+#include "nsString.h"
+#include "mozilla/ResultVariant.h"
+#include "mozilla/dom/GleanMetricsBinding.h"
+#include "mozilla/glean/bindings/ScalarGIFFTMap.h"
+#include "mozilla/glean/fog_ffi_generated.h"
+
+namespace mozilla::glean {
+
+namespace impl {
+
+void TextMetric::Set(const nsACString& aValue) const {
+ fog_text_set(mId, &aValue);
+}
+
+Result<Maybe<nsCString>, nsCString> TextMetric::TestGetValue(
+ const nsACString& aPingName) const {
+ nsCString err;
+ if (fog_text_test_get_error(mId, &err)) {
+ return Err(err);
+ }
+ if (!fog_text_test_has_value(mId, &aPingName)) {
+ return Maybe<nsCString>();
+ }
+ nsCString ret;
+ fog_text_test_get_value(mId, &aPingName, &ret);
+ return Some(ret);
+}
+
+} // namespace impl
+
+/* virtual */
+JSObject* GleanText::WrapObject(JSContext* aCx,
+ JS::Handle<JSObject*> aGivenProto) {
+ return dom::GleanText_Binding::Wrap(aCx, this, aGivenProto);
+}
+
+void GleanText::Set(const nsACString& aValue) { mText.Set(aValue); }
+
+void GleanText::TestGetValue(const nsACString& aPingName, nsCString& aResult,
+ ErrorResult& aRv) {
+ auto result = mText.TestGetValue(aPingName);
+ if (result.isErr()) {
+ aRv.ThrowDataError(result.unwrapErr());
+ return;
+ }
+ auto optresult = result.unwrap();
+ if (!optresult.isNothing()) {
+ aResult.Assign(optresult.extract());
+ } else {
+ aResult.SetIsVoid(true);
+ }
+}
+
+} // namespace mozilla::glean
diff --git a/toolkit/components/glean/bindings/private/Text.h b/toolkit/components/glean/bindings/private/Text.h
new file mode 100644
index 0000000000..545b1e68a0
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Text.h
@@ -0,0 +1,54 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_glean_GleanText_h
+#define mozilla_glean_GleanText_h
+
+#include "mozilla/dom/BindingDeclarations.h"
+#include "mozilla/glean/bindings/GleanMetric.h"
+#include "mozilla/Maybe.h"
+#include "mozilla/Result.h"
+#include "nsString.h"
+
+namespace mozilla::glean {
+
+namespace impl {
+
+class TextMetric {
+ public:
+ constexpr explicit TextMetric(uint32_t aId) : mId(aId) {}
+
+ void Set(const nsACString& aValue) const;
+
+ Result<Maybe<nsCString>, nsCString> TestGetValue(
+ const nsACString& aPingName = nsCString()) const;
+
+ private:
+ const uint32_t mId;
+};
+
+} // namespace impl
+
+class GleanText final : public GleanMetric {
+ public:
+ explicit GleanText(uint32_t aId, nsISupports* aParent)
+ : GleanMetric(aParent), mText(aId) {}
+
+ virtual JSObject* WrapObject(
+ JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override final;
+
+ void Set(const nsACString& aValue);
+
+ void TestGetValue(const nsACString& aPingName, nsCString& aResult,
+ ErrorResult& aRv);
+
+ private:
+ virtual ~GleanText() = default;
+
+ const impl::TextMetric mText;
+};
+} // namespace mozilla::glean
+#endif
diff --git a/toolkit/components/glean/bindings/private/Timespan.cpp b/toolkit/components/glean/bindings/private/Timespan.cpp
new file mode 100644
index 0000000000..13e57317fa
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Timespan.cpp
@@ -0,0 +1,186 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/glean/bindings/Timespan.h"
+
+#include "nsString.h"
+#include "mozilla/Components.h"
+#include "mozilla/ResultVariant.h"
+#include "mozilla/dom/GleanMetricsBinding.h"
+#include "mozilla/glean/bindings/ScalarGIFFTMap.h"
+#include "mozilla/glean/fog_ffi_generated.h"
+
+namespace mozilla::glean {
+
+namespace impl {
+
+namespace {
+class ScalarIDHashKey : public PLDHashEntryHdr {
+ public:
+ using KeyType = const ScalarID&;
+ using KeyTypePointer = const ScalarID*;
+
+ explicit ScalarIDHashKey(KeyTypePointer aKey) : mValue(*aKey) {}
+ ScalarIDHashKey(ScalarIDHashKey&& aOther)
+ : PLDHashEntryHdr(std::move(aOther)), mValue(std::move(aOther.mValue)) {}
+ ~ScalarIDHashKey() = default;
+
+ KeyType GetKey() const { return mValue; }
+ bool KeyEquals(KeyTypePointer aKey) const { return *aKey == mValue; }
+
+ static KeyTypePointer KeyToPointer(KeyType aKey) { return &aKey; }
+ static PLDHashNumber HashKey(KeyTypePointer aKey) {
+ return static_cast<std::underlying_type<ScalarID>::type>(*aKey);
+ }
+ enum { ALLOW_MEMMOVE = true };
+
+ private:
+ const ScalarID mValue;
+};
+} // namespace
+
+using TimesToStartsMutex =
+ StaticDataMutex<UniquePtr<nsTHashMap<ScalarIDHashKey, TimeStamp>>>;
+static Maybe<TimesToStartsMutex::AutoLock> GetTimesToStartsLock() {
+ static TimesToStartsMutex sTimespanStarts("sTimespanStarts");
+ auto lock = sTimespanStarts.Lock();
+ // GIFFT will work up to the end of AppShutdownTelemetry.
+ if (AppShutdown::IsInOrBeyond(ShutdownPhase::XPCOMWillShutdown)) {
+ return Nothing();
+ }
+ if (!*lock) {
+ *lock = MakeUnique<nsTHashMap<ScalarIDHashKey, TimeStamp>>();
+ RefPtr<nsIRunnable> cleanupFn = NS_NewRunnableFunction(__func__, [&] {
+ if (AppShutdown::IsInOrBeyond(ShutdownPhase::XPCOMWillShutdown)) {
+ auto lock = sTimespanStarts.Lock();
+ *lock = nullptr; // deletes, see UniquePtr.h
+ return;
+ }
+ RunOnShutdown(
+ [&] {
+ auto lock = sTimespanStarts.Lock();
+ *lock = nullptr; // deletes, see UniquePtr.h
+ },
+ ShutdownPhase::XPCOMWillShutdown);
+ });
+ // Both getting the main thread and dispatching to it can fail.
+ // In that event we leak. Grab a pointer so we have something to NS_RELEASE
+ // in that case.
+ nsIRunnable* temp = cleanupFn.get();
+ nsCOMPtr<nsIThread> mainThread;
+ if (NS_FAILED(NS_GetMainThread(getter_AddRefs(mainThread))) ||
+ NS_FAILED(mainThread->Dispatch(cleanupFn.forget(),
+ nsIThread::DISPATCH_NORMAL))) {
+ // Failed to dispatch cleanup routine.
+ // First, un-leak the runnable (but only if we actually attempted
+ // dispatch)
+ if (!cleanupFn) {
+ NS_RELEASE(temp);
+ }
+ // Next, cleanup immediately, and allow metrics to try again later.
+ *lock = nullptr;
+ return Nothing();
+ }
+ }
+ return Some(std::move(lock));
+}
+
+void TimespanMetric::Start() const {
+ auto optScalarId = ScalarIdForMetric(mId);
+ if (optScalarId) {
+ auto scalarId = optScalarId.extract();
+ GetTimesToStartsLock().apply([&](auto& lock) {
+ (void)NS_WARN_IF(lock.ref()->Remove(scalarId));
+ lock.ref()->InsertOrUpdate(scalarId, TimeStamp::Now());
+ });
+ }
+ fog_timespan_start(mId);
+}
+
+void TimespanMetric::Stop() const {
+ auto optScalarId = ScalarIdForMetric(mId);
+ if (optScalarId) {
+ auto scalarId = optScalarId.extract();
+ GetTimesToStartsLock().apply([&](auto& lock) {
+ auto optStart = lock.ref()->Extract(scalarId);
+ if (!NS_WARN_IF(!optStart)) {
+ double delta = (TimeStamp::Now() - optStart.extract()).ToMilliseconds();
+ uint32_t theDelta = static_cast<uint32_t>(delta);
+ if (delta > std::numeric_limits<uint32_t>::max()) {
+ theDelta = std::numeric_limits<uint32_t>::max();
+ } else if (MOZ_UNLIKELY(delta < 0)) {
+ theDelta = 0;
+ }
+ Telemetry::ScalarSet(scalarId, theDelta);
+ }
+ });
+ }
+ fog_timespan_stop(mId);
+}
+
+void TimespanMetric::Cancel() const {
+ auto optScalarId = ScalarIdForMetric(mId);
+ if (optScalarId) {
+ auto scalarId = optScalarId.extract();
+ GetTimesToStartsLock().apply(
+ [&](auto& lock) { lock.ref()->Remove(scalarId); });
+ }
+ fog_timespan_cancel(mId);
+}
+
+void TimespanMetric::SetRaw(uint32_t aDuration) const {
+ auto optScalarId = ScalarIdForMetric(mId);
+ if (optScalarId) {
+ auto scalarId = optScalarId.extract();
+ Telemetry::ScalarSet(scalarId, aDuration);
+ }
+ fog_timespan_set_raw(mId, aDuration);
+}
+
+Result<Maybe<uint64_t>, nsCString> TimespanMetric::TestGetValue(
+ const nsACString& aPingName) const {
+ nsCString err;
+ if (fog_timespan_test_get_error(mId, &err)) {
+ return Err(err);
+ }
+ if (!fog_timespan_test_has_value(mId, &aPingName)) {
+ return Maybe<uint64_t>();
+ }
+ return Some(fog_timespan_test_get_value(mId, &aPingName));
+}
+
+} // namespace impl
+
+/* virtual */
+JSObject* GleanTimespan::WrapObject(JSContext* aCx,
+ JS::Handle<JSObject*> aGivenProto) {
+ return dom::GleanTimespan_Binding::Wrap(aCx, this, aGivenProto);
+}
+
+void GleanTimespan::Start() { mTimespan.Start(); }
+
+void GleanTimespan::Stop() { mTimespan.Stop(); }
+
+void GleanTimespan::Cancel() { mTimespan.Cancel(); }
+
+void GleanTimespan::SetRaw(uint32_t aDuration) { mTimespan.SetRaw(aDuration); }
+
+dom::Nullable<uint64_t> GleanTimespan::TestGetValue(const nsACString& aPingName,
+ ErrorResult& aRv) {
+ dom::Nullable<uint64_t> ret;
+ auto result = mTimespan.TestGetValue(aPingName);
+ if (result.isErr()) {
+ aRv.ThrowDataError(result.unwrapErr());
+ return ret;
+ }
+ auto optresult = result.unwrap();
+ if (!optresult.isNothing()) {
+ ret.SetValue(optresult.value());
+ }
+ return ret;
+}
+
+} // namespace mozilla::glean
diff --git a/toolkit/components/glean/bindings/private/Timespan.h b/toolkit/components/glean/bindings/private/Timespan.h
new file mode 100644
index 0000000000..296e1cb28f
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Timespan.h
@@ -0,0 +1,110 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_glean_GleanTimespan_h
+#define mozilla_glean_GleanTimespan_h
+
+#include "mozilla/Maybe.h"
+#include "mozilla/Result.h"
+#include "mozilla/dom/BindingDeclarations.h"
+#include "mozilla/glean/bindings/GleanMetric.h"
+#include "nsTString.h"
+
+namespace mozilla::glean {
+
+namespace impl {
+
+class TimespanMetric {
+ public:
+ constexpr explicit TimespanMetric(uint32_t aId) : mId(aId) {}
+
+ /**
+ * Start tracking time for the provided metric.
+ *
+ * This records an error if it’s already tracking time (i.e. start was already
+ * called with no corresponding [stop]): in that case the original
+ * start time will be preserved.
+ */
+ void Start() const;
+
+ /**
+ * Stop tracking time for the provided metric.
+ *
+ * Sets the metric to the elapsed time, but does not overwrite an already
+ * existing value.
+ * This will record an error if no [start] was called or there is an already
+ * existing value.
+ */
+ void Stop() const;
+
+ /**
+ * Abort a previous Start.
+ *
+ * No error will be recorded if no Start was called.
+ */
+ void Cancel() const;
+
+ /**
+ * Explicitly sets the timespan value
+ *
+ * This API should only be used if you cannot make use of
+ * `start`/`stop`/`cancel`.
+ *
+ * @param aDuration The duration of this timespan, in units matching the
+ * `time_unit` of this metric's definition.
+ */
+ void SetRaw(uint32_t aDuration) const;
+
+ /**
+ * **Test-only API**
+ *
+ * Gets the currently stored value as an integer.
+ *
+ * This function will attempt to await the last parent-process task (if any)
+ * writing to the the metric's storage engine before returning a value.
+ * This function will not wait for data from child processes.
+ *
+ * This doesn't clear the stored value.
+ * Parent process only. Panics in child processes.
+ *
+ * @param aPingName The (optional) name of the ping to retrieve the metric
+ * for. Defaults to the first value in `send_in_pings`.
+ *
+ * @return value of the stored metric, or Nothing() if there is no value.
+ */
+ Result<Maybe<uint64_t>, nsCString> TestGetValue(
+ const nsACString& aPingName = nsCString()) const;
+
+ private:
+ const uint32_t mId;
+};
+} // namespace impl
+
+class GleanTimespan final : public GleanMetric {
+ public:
+ explicit GleanTimespan(uint32_t aId, nsISupports* aParent)
+ : GleanMetric(aParent), mTimespan(aId) {}
+
+ virtual JSObject* WrapObject(
+ JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override final;
+
+ void Start();
+ void Stop();
+ void Cancel();
+ void SetRaw(uint32_t aDuration);
+
+ dom::Nullable<uint64_t> TestGetValue(const nsACString& aPingName,
+ ErrorResult& aRv);
+
+ private:
+ virtual ~GleanTimespan() = default;
+
+ const impl::TimespanMetric mTimespan;
+};
+
+} // namespace mozilla::glean
+
+#endif /* mozilla_glean_GleanTimespan_h */
diff --git a/toolkit/components/glean/bindings/private/TimingDistribution.cpp b/toolkit/components/glean/bindings/private/TimingDistribution.cpp
new file mode 100644
index 0000000000..f7a78165ae
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/TimingDistribution.cpp
@@ -0,0 +1,242 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/glean/bindings/TimingDistribution.h"
+
+#include "mozilla/AppShutdown.h"
+#include "mozilla/ClearOnShutdown.h"
+#include "mozilla/ResultVariant.h"
+#include "mozilla/dom/GleanMetricsBinding.h"
+#include "mozilla/dom/ToJSValue.h"
+#include "mozilla/glean/bindings/HistogramGIFFTMap.h"
+#include "mozilla/glean/fog_ffi_generated.h"
+#include "nsJSUtils.h"
+#include "nsPrintfCString.h"
+#include "nsString.h"
+#include "js/PropertyAndElement.h" // JS_DefineProperty
+
+namespace mozilla::glean {
+
+using MetricId = uint32_t; // Same type as in api/src/private/mod.rs
+using MetricTimerTuple = std::tuple<MetricId, TimerId>;
+class MetricTimerTupleHashKey : public PLDHashEntryHdr {
+ public:
+ using KeyType = const MetricTimerTuple&;
+ using KeyTypePointer = const MetricTimerTuple*;
+
+ explicit MetricTimerTupleHashKey(KeyTypePointer aKey) : mValue(*aKey) {}
+ MetricTimerTupleHashKey(MetricTimerTupleHashKey&& aOther)
+ : PLDHashEntryHdr(std::move(aOther)), mValue(aOther.mValue) {}
+ ~MetricTimerTupleHashKey() = default;
+
+ KeyType GetKey() const { return mValue; }
+ bool KeyEquals(KeyTypePointer aKey) const {
+ return std::get<0>(*aKey) == std::get<0>(mValue) &&
+ std::get<1>(*aKey) == std::get<1>(mValue);
+ }
+
+ static KeyTypePointer KeyToPointer(KeyType aKey) { return &aKey; }
+ static PLDHashNumber HashKey(KeyTypePointer aKey) {
+ // Chosen because this is how nsIntegralHashKey does it.
+ return HashGeneric(std::get<0>(*aKey), std::get<1>(*aKey));
+ }
+ enum { ALLOW_MEMMOVE = true };
+
+ private:
+ const MetricTimerTuple mValue;
+};
+
+using TimerToStampMutex =
+ StaticDataMutex<UniquePtr<nsTHashMap<MetricTimerTupleHashKey, TimeStamp>>>;
+static Maybe<TimerToStampMutex::AutoLock> GetTimerIdToStartsLock() {
+ static TimerToStampMutex sTimerIdToStarts("sTimerIdToStarts");
+ auto lock = sTimerIdToStarts.Lock();
+ // GIFFT will work up to the end of AppShutdownTelemetry.
+ if (AppShutdown::IsInOrBeyond(ShutdownPhase::XPCOMWillShutdown)) {
+ return Nothing();
+ }
+ if (!*lock) {
+ *lock = MakeUnique<nsTHashMap<MetricTimerTupleHashKey, TimeStamp>>();
+ RefPtr<nsIRunnable> cleanupFn = NS_NewRunnableFunction(__func__, [&] {
+ if (AppShutdown::IsInOrBeyond(ShutdownPhase::XPCOMWillShutdown)) {
+ auto lock = sTimerIdToStarts.Lock();
+ *lock = nullptr; // deletes, see UniquePtr.h
+ return;
+ }
+ RunOnShutdown(
+ [&] {
+ auto lock = sTimerIdToStarts.Lock();
+ *lock = nullptr; // deletes, see UniquePtr.h
+ },
+ ShutdownPhase::XPCOMWillShutdown);
+ });
+ // Both getting the main thread and dispatching to it can fail.
+ // In that event we leak. Grab a pointer so we have something to NS_RELEASE
+ // in that case.
+ nsIRunnable* temp = cleanupFn.get();
+ nsCOMPtr<nsIThread> mainThread;
+ if (NS_FAILED(NS_GetMainThread(getter_AddRefs(mainThread))) ||
+ NS_FAILED(mainThread->Dispatch(cleanupFn.forget(),
+ nsIThread::DISPATCH_NORMAL))) {
+ // Failed to dispatch cleanup routine.
+ // First, un-leak the runnable (but only if we actually attempted
+ // dispatch)
+ if (!cleanupFn) {
+ NS_RELEASE(temp);
+ }
+ // Next, cleanup immediately, and allow metrics to try again later.
+ *lock = nullptr;
+ return Nothing();
+ }
+ }
+ return Some(std::move(lock));
+}
+
+} // namespace mozilla::glean
+
+// Called from within FOG's Rust impl.
+extern "C" NS_EXPORT void GIFFT_TimingDistributionStart(
+ uint32_t aMetricId, mozilla::glean::TimerId aTimerId) {
+ auto mirrorId = mozilla::glean::HistogramIdForMetric(aMetricId);
+ if (mirrorId) {
+ mozilla::glean::GetTimerIdToStartsLock().apply([&](auto& lock) {
+ auto tuple = std::make_tuple(aMetricId, aTimerId);
+ // It should be all but impossible for anyone to have already inserted
+ // this timer for this metric given the monotonicity of timer ids.
+ (void)NS_WARN_IF(lock.ref()->Remove(tuple));
+ lock.ref()->InsertOrUpdate(tuple, mozilla::TimeStamp::Now());
+ });
+ }
+}
+
+// Called from within FOG's Rust impl.
+extern "C" NS_EXPORT void GIFFT_TimingDistributionStopAndAccumulate(
+ uint32_t aMetricId, mozilla::glean::TimerId aTimerId) {
+ auto mirrorId = mozilla::glean::HistogramIdForMetric(aMetricId);
+ if (mirrorId) {
+ mozilla::glean::GetTimerIdToStartsLock().apply([&](auto& lock) {
+ auto optStart = lock.ref()->Extract(std::make_tuple(aMetricId, aTimerId));
+ // The timer might not be in the map to be removed if it's already been
+ // cancelled or stop_and_accumulate'd.
+ if (!NS_WARN_IF(!optStart)) {
+ AccumulateTimeDelta(mirrorId.extract(), optStart.extract());
+ }
+ });
+ }
+}
+
+// Called from within FOG's Rust impl.
+extern "C" NS_EXPORT void GIFFT_TimingDistributionAccumulateRawMillis(
+ uint32_t aMetricId, uint32_t aMS) {
+ auto mirrorId = mozilla::glean::HistogramIdForMetric(aMetricId);
+ if (mirrorId) {
+ Accumulate(mirrorId.extract(), aMS);
+ }
+}
+
+// Called from within FOG's Rust impl.
+extern "C" NS_EXPORT void GIFFT_TimingDistributionCancel(
+ uint32_t aMetricId, mozilla::glean::TimerId aTimerId) {
+ auto mirrorId = mozilla::glean::HistogramIdForMetric(aMetricId);
+ if (mirrorId) {
+ mozilla::glean::GetTimerIdToStartsLock().apply([&](auto& lock) {
+ // The timer might not be in the map to be removed if it's already been
+ // cancelled or stop_and_accumulate'd.
+ (void)NS_WARN_IF(
+ !lock.ref()->Remove(std::make_tuple(aMetricId, aTimerId)));
+ });
+ }
+}
+
+namespace mozilla::glean {
+
+namespace impl {
+
+TimerId TimingDistributionMetric::Start() const {
+ return fog_timing_distribution_start(mId);
+}
+
+void TimingDistributionMetric::StopAndAccumulate(const TimerId&& aId) const {
+ fog_timing_distribution_stop_and_accumulate(mId, aId);
+}
+
+// Intentionally not exposed to JS for lack of use case and a time duration
+// type.
+void TimingDistributionMetric::AccumulateRawDuration(
+ const TimeDuration& aDuration) const {
+ fog_timing_distribution_accumulate_raw_nanos(
+ mId, uint64_t(aDuration.ToMicroseconds() * 1000.00));
+}
+
+void TimingDistributionMetric::Cancel(const TimerId&& aId) const {
+ fog_timing_distribution_cancel(mId, aId);
+}
+
+Result<Maybe<DistributionData>, nsCString>
+TimingDistributionMetric::TestGetValue(const nsACString& aPingName) const {
+ nsCString err;
+ if (fog_timing_distribution_test_get_error(mId, &err)) {
+ return Err(err);
+ }
+ if (!fog_timing_distribution_test_has_value(mId, &aPingName)) {
+ return Maybe<DistributionData>();
+ }
+ nsTArray<uint64_t> buckets;
+ nsTArray<uint64_t> counts;
+ uint64_t sum;
+ fog_timing_distribution_test_get_value(mId, &aPingName, &sum, &buckets,
+ &counts);
+ return Some(DistributionData(buckets, counts, sum));
+}
+
+} // namespace impl
+
+/* virtual */
+JSObject* GleanTimingDistribution::WrapObject(
+ JSContext* aCx, JS::Handle<JSObject*> aGivenProto) {
+ return dom::GleanTimingDistribution_Binding::Wrap(aCx, this, aGivenProto);
+}
+
+uint64_t GleanTimingDistribution::Start() { return mTimingDist.Start(); }
+
+void GleanTimingDistribution::StopAndAccumulate(uint64_t aId) {
+ mTimingDist.StopAndAccumulate(std::move(aId));
+}
+
+void GleanTimingDistribution::Cancel(uint64_t aId) {
+ mTimingDist.Cancel(std::move(aId));
+}
+
+void GleanTimingDistribution::TestGetValue(
+ const nsACString& aPingName,
+ dom::Nullable<dom::GleanDistributionData>& aRetval, ErrorResult& aRv) {
+ auto result = mTimingDist.TestGetValue(aPingName);
+ if (result.isErr()) {
+ aRv.ThrowDataError(result.unwrapErr());
+ return;
+ }
+ auto optresult = result.unwrap();
+ if (optresult.isNothing()) {
+ return;
+ }
+
+ dom::GleanDistributionData ret;
+ ret.mSum = optresult.ref().sum;
+ auto& data = optresult.ref().values;
+ for (const auto& entry : data) {
+ dom::binding_detail::RecordEntry<nsCString, uint64_t> bucket;
+ bucket.mKey = nsPrintfCString("%" PRIu64, entry.GetKey());
+ bucket.mValue = entry.GetData();
+ ret.mValues.Entries().EmplaceBack(std::move(bucket));
+ }
+ aRetval.SetValue(std::move(ret));
+}
+
+void GleanTimingDistribution::TestAccumulateRawMillis(uint64_t aSample) {
+ mTimingDist.AccumulateRawDuration(TimeDuration::FromMilliseconds(aSample));
+}
+
+} // namespace mozilla::glean
diff --git a/toolkit/components/glean/bindings/private/TimingDistribution.h b/toolkit/components/glean/bindings/private/TimingDistribution.h
new file mode 100644
index 0000000000..ae4a796279
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/TimingDistribution.h
@@ -0,0 +1,125 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_glean_GleanTimingDistribution_h
+#define mozilla_glean_GleanTimingDistribution_h
+
+#include "mozilla/dom/BindingDeclarations.h"
+#include "mozilla/glean/bindings/DistributionData.h"
+#include "mozilla/glean/bindings/GleanMetric.h"
+#include "mozilla/Maybe.h"
+#include "mozilla/Result.h"
+#include "mozilla/TimeStamp.h"
+#include "nsTArray.h"
+
+namespace mozilla::dom {
+struct GleanDistributionData;
+} // namespace mozilla::dom
+
+namespace mozilla::glean {
+
+typedef uint64_t TimerId;
+
+namespace impl {
+class TimingDistributionMetric {
+ public:
+ constexpr explicit TimingDistributionMetric(uint32_t aId) : mId(aId) {}
+
+ /*
+ * Starts tracking time for the provided metric.
+ *
+ * @returns A unique TimerId for the new timer
+ */
+ TimerId Start() const;
+
+ /*
+ * Stops tracking time for the provided metric and associated timer id.
+ *
+ * Adds a count to the corresponding bucket in the timing distribution.
+ * This will record an error if no `Start` was called on this TimerId or
+ * if this TimerId was used to call `Cancel`.
+ *
+ * @param aId The TimerId to associate with this timing. This allows for
+ * concurrent timing of events associated with different ids.
+ */
+ void StopAndAccumulate(const TimerId&& aId) const;
+
+ /*
+ * Adds a duration sample to a timing distribution metric.
+ *
+ * Adds a count to the corresponding bucket in the timing distribution.
+ * Prefer Start() and StopAndAccumulate() where possible.
+ * Users of this API are responsible for ensuring the timing source used
+ * to calculate the TimeDuration is monotonic and consistent accross
+ * platforms.
+ *
+ * NOTE: Negative durations are not handled and will saturate to INT64_MAX
+ * nanoseconds.
+ *
+ * @param aDuration The duration of the sample to add to the distribution.
+ */
+ void AccumulateRawDuration(const TimeDuration& aDuration) const;
+
+ /*
+ * Aborts a previous `Start` call. No error is recorded if no `Start` was
+ * called.
+ *
+ * @param aId The TimerId whose `Start` you wish to abort.
+ */
+ void Cancel(const TimerId&& aId) const;
+
+ /**
+ * **Test-only API**
+ *
+ * Gets the currently stored value as a DistributionData.
+ *
+ * This function will attempt to await the last parent-process task (if any)
+ * writing to the the metric's storage engine before returning a value.
+ * This function will not wait for data from child processes.
+ *
+ * This doesn't clear the stored value.
+ * Parent process only. Panics in child processes.
+ *
+ * @param aPingName The (optional) name of the ping to retrieve the metric
+ * for. Defaults to the first value in `send_in_pings`.
+ *
+ * @return value of the stored metric, or Nothing() if there is no value.
+ */
+ Result<Maybe<DistributionData>, nsCString> TestGetValue(
+ const nsACString& aPingName = nsCString()) const;
+
+ private:
+ const uint32_t mId;
+};
+} // namespace impl
+
+class GleanTimingDistribution final : public GleanMetric {
+ public:
+ explicit GleanTimingDistribution(uint64_t aId, nsISupports* aParent)
+ : GleanMetric(aParent), mTimingDist(aId) {}
+
+ virtual JSObject* WrapObject(
+ JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override final;
+
+ uint64_t Start();
+ void StopAndAccumulate(uint64_t aId);
+ void Cancel(uint64_t aId);
+
+ void TestGetValue(const nsACString& aPingName,
+ dom::Nullable<dom::GleanDistributionData>& aRetval,
+ ErrorResult& aRv);
+
+ void TestAccumulateRawMillis(uint64_t aSample);
+
+ private:
+ virtual ~GleanTimingDistribution() = default;
+
+ const impl::TimingDistributionMetric mTimingDist;
+};
+
+} // namespace mozilla::glean
+
+#endif /* mozilla_glean_GleanTimingDistribution_h */
diff --git a/toolkit/components/glean/bindings/private/Url.cpp b/toolkit/components/glean/bindings/private/Url.cpp
new file mode 100644
index 0000000000..060b27f125
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Url.cpp
@@ -0,0 +1,68 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/glean/bindings/Url.h"
+
+#include "jsapi.h"
+#include "js/String.h"
+#include "nsString.h"
+#include "mozilla/ResultVariant.h"
+#include "mozilla/dom/GleanMetricsBinding.h"
+#include "mozilla/glean/bindings/ScalarGIFFTMap.h"
+#include "mozilla/glean/fog_ffi_generated.h"
+
+namespace mozilla::glean {
+
+namespace impl {
+
+void UrlMetric::Set(const nsACString& aValue) const {
+ auto scalarId = ScalarIdForMetric(mId);
+ if (scalarId) {
+ Telemetry::ScalarSet(scalarId.extract(), NS_ConvertUTF8toUTF16(aValue));
+ }
+ fog_url_set(mId, &aValue);
+}
+
+Result<Maybe<nsCString>, nsCString> UrlMetric::TestGetValue(
+ const nsACString& aPingName) const {
+ nsCString err;
+ if (fog_url_test_get_error(mId, &err)) {
+ return Err(err);
+ }
+ if (!fog_url_test_has_value(mId, &aPingName)) {
+ return Maybe<nsCString>();
+ }
+ nsCString ret;
+ fog_url_test_get_value(mId, &aPingName, &ret);
+ return Some(ret);
+}
+
+} // namespace impl
+
+/* virtual */
+JSObject* GleanUrl::WrapObject(JSContext* aCx,
+ JS::Handle<JSObject*> aGivenProto) {
+ return dom::GleanUrl_Binding::Wrap(aCx, this, aGivenProto);
+}
+
+void GleanUrl::Set(const nsACString& aValue) { mUrl.Set(aValue); }
+
+void GleanUrl::TestGetValue(const nsACString& aPingName, nsCString& aResult,
+ ErrorResult& aRv) {
+ auto result = mUrl.TestGetValue(aPingName);
+ if (result.isErr()) {
+ aRv.ThrowDataError(result.unwrapErr());
+ return;
+ }
+ auto optresult = result.unwrap();
+ if (!optresult.isNothing()) {
+ aResult.Assign(optresult.extract());
+ } else {
+ aResult.SetIsVoid(true);
+ }
+}
+
+} // namespace mozilla::glean
diff --git a/toolkit/components/glean/bindings/private/Url.h b/toolkit/components/glean/bindings/private/Url.h
new file mode 100644
index 0000000000..26ebdafdd0
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Url.h
@@ -0,0 +1,77 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_glean_GleanUrl_h
+#define mozilla_glean_GleanUrl_h
+
+#include "mozilla/dom/BindingDeclarations.h"
+#include "mozilla/glean/bindings/GleanMetric.h"
+#include "mozilla/Maybe.h"
+#include "mozilla/Result.h"
+#include "nsString.h"
+
+namespace mozilla::glean {
+
+namespace impl {
+
+class UrlMetric {
+ public:
+ constexpr explicit UrlMetric(uint32_t aId) : mId(aId) {}
+
+ /*
+ * Set to the specified value.
+ *
+ * @param aValue The stringified Url to set the metric to.
+ */
+ void Set(const nsACString& aValue) const;
+
+ /**
+ * **Test-only API**
+ *
+ * Gets the currently stored value as a string.
+ *
+ * This function will attempt to await the last parent-process task (if any)
+ * writing to the the metric's storage engine before returning a value.
+ * This function will not wait for data from child processes.
+ *
+ * This doesn't clear the stored value.
+ * Parent process only. Panics in child processes.
+ *
+ * @param aPingName The (optional) name of the ping to retrieve the metric
+ * for. Defaults to the first value in `send_in_pings`.
+ *
+ * @return value of the stored metric, or Nothing() if there is no value.
+ */
+ Result<Maybe<nsCString>, nsCString> TestGetValue(
+ const nsACString& aPingName = nsCString()) const;
+
+ private:
+ const uint32_t mId;
+};
+} // namespace impl
+
+class GleanUrl final : public GleanMetric {
+ public:
+ explicit GleanUrl(uint32_t aId, nsISupports* aParent)
+ : GleanMetric(aParent), mUrl(aId) {}
+
+ virtual JSObject* WrapObject(
+ JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override final;
+
+ void Set(const nsACString& aValue);
+
+ void TestGetValue(const nsACString& aPingName, nsCString& aResult,
+ ErrorResult& aRv);
+
+ private:
+ virtual ~GleanUrl() = default;
+
+ const impl::UrlMetric mUrl;
+};
+
+} // namespace mozilla::glean
+
+#endif /* mozilla_glean_GleanUrl_h */
diff --git a/toolkit/components/glean/bindings/private/Uuid.cpp b/toolkit/components/glean/bindings/private/Uuid.cpp
new file mode 100644
index 0000000000..6503b5ffd8
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Uuid.cpp
@@ -0,0 +1,76 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/glean/bindings/Uuid.h"
+
+#include "jsapi.h"
+#include "mozilla/ResultVariant.h"
+#include "mozilla/dom/GleanMetricsBinding.h"
+#include "mozilla/glean/bindings/ScalarGIFFTMap.h"
+#include "mozilla/glean/fog_ffi_generated.h"
+#include "nsString.h"
+
+namespace mozilla::glean {
+
+namespace impl {
+
+void UuidMetric::Set(const nsACString& aValue) const {
+ auto scalarId = ScalarIdForMetric(mId);
+ if (scalarId) {
+ Telemetry::ScalarSet(scalarId.extract(), NS_ConvertUTF8toUTF16(aValue));
+ }
+ fog_uuid_set(mId, &aValue);
+}
+
+void UuidMetric::GenerateAndSet() const {
+ // We don't have the generated value to mirror to the scalar,
+ // so calling this function on a mirrored metric is likely an error.
+ (void)NS_WARN_IF(ScalarIdForMetric(mId).isSome());
+ fog_uuid_generate_and_set(mId);
+}
+
+Result<Maybe<nsCString>, nsCString> UuidMetric::TestGetValue(
+ const nsACString& aPingName) const {
+ nsCString err;
+ if (fog_uuid_test_get_error(mId, &err)) {
+ return Err(err);
+ }
+ if (!fog_uuid_test_has_value(mId, &aPingName)) {
+ return Maybe<nsCString>();
+ }
+ nsCString ret;
+ fog_uuid_test_get_value(mId, &aPingName, &ret);
+ return Some(ret);
+}
+
+} // namespace impl
+
+/* virtual */
+JSObject* GleanUuid::WrapObject(JSContext* aCx,
+ JS::Handle<JSObject*> aGivenProto) {
+ return dom::GleanUuid_Binding::Wrap(aCx, this, aGivenProto);
+}
+
+void GleanUuid::Set(const nsACString& aValue) { mUuid.Set(aValue); }
+
+void GleanUuid::GenerateAndSet() { mUuid.GenerateAndSet(); }
+
+void GleanUuid::TestGetValue(const nsACString& aPingName, nsCString& aResult,
+ ErrorResult& aRv) {
+ auto result = mUuid.TestGetValue(aPingName);
+ if (result.isErr()) {
+ aRv.ThrowDataError(result.unwrapErr());
+ return;
+ }
+ auto optresult = result.unwrap();
+ if (!optresult.isNothing()) {
+ aResult.Assign(optresult.extract());
+ } else {
+ aResult.SetIsVoid(true);
+ }
+}
+
+} // namespace mozilla::glean
diff --git a/toolkit/components/glean/bindings/private/Uuid.h b/toolkit/components/glean/bindings/private/Uuid.h
new file mode 100644
index 0000000000..b4c5e2bc32
--- /dev/null
+++ b/toolkit/components/glean/bindings/private/Uuid.h
@@ -0,0 +1,83 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_glean_GleanUuid_h
+#define mozilla_glean_GleanUuid_h
+
+#include "mozilla/Maybe.h"
+#include "mozilla/Result.h"
+#include "mozilla/dom/BindingDeclarations.h"
+#include "mozilla/glean/bindings/GleanMetric.h"
+#include "nsString.h"
+
+namespace mozilla::glean {
+
+namespace impl {
+
+class UuidMetric {
+ public:
+ constexpr explicit UuidMetric(uint32_t aId) : mId(aId) {}
+
+ /*
+ * Sets to the specified value.
+ *
+ * @param aValue The UUID to set the metric to.
+ */
+ void Set(const nsACString& aValue) const;
+
+ /*
+ * Generate a new random UUID and set the metric to it.
+ */
+ void GenerateAndSet() const;
+
+ /**
+ * **Test-only API**
+ *
+ * Gets the currently stored value as a hyphenated string.
+ *
+ * This function will attempt to await the last parent-process task (if any)
+ * writing to the the metric's storage engine before returning a value.
+ * This function will not wait for data from child processes.
+ *
+ * This doesn't clear the stored value.
+ * Parent process only. Panics in child processes.
+ *
+ * @param aPingName The (optional) name of the ping to retrieve the metric
+ * for. Defaults to the first value in `send_in_pings`.
+ *
+ * @return value of the stored metric, or Nothing() if there is no value.
+ */
+ Result<Maybe<nsCString>, nsCString> TestGetValue(
+ const nsACString& aPingName = nsCString()) const;
+
+ private:
+ const uint32_t mId;
+};
+} // namespace impl
+
+class GleanUuid final : public GleanMetric {
+ public:
+ explicit GleanUuid(uint32_t aId, nsISupports* aParent)
+ : GleanMetric(aParent), mUuid(aId) {}
+
+ virtual JSObject* WrapObject(
+ JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override final;
+
+ void Set(const nsACString& aValue);
+ void GenerateAndSet();
+
+ void TestGetValue(const nsACString& aPingName, nsCString& aResult,
+ ErrorResult& aRv);
+
+ private:
+ virtual ~GleanUuid() = default;
+
+ const impl::UuidMetric mUuid;
+};
+
+} // namespace mozilla::glean
+
+#endif /* mozilla_glean_GleanUuid_h */