summaryrefslogtreecommitdiffstats
path: root/toolkit/components/glean/xpcom/FOG.cpp
blob: 3673b23707d5d81887e2410defbb6ac414f67e0d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
/* -*- 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/FOG.h"

#include "mozilla/AppShutdown.h"
#include "mozilla/Atomics.h"
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/dom/Promise.h"
#include "mozilla/FOGIPC.h"
#include "mozilla/browser/NimbusFeatures.h"
#include "mozilla/glean/bindings/Common.h"
#include "mozilla/glean/bindings/jog/jog_ffi_generated.h"
#include "mozilla/glean/fog_ffi_generated.h"
#include "mozilla/glean/GleanMetrics.h"
#include "mozilla/Logging.h"
#include "mozilla/MozPromise.h"
#include "mozilla/ShutdownPhase.h"
#include "mozilla/Unused.h"
#include "nsContentUtils.h"
#include "nsIFOG.h"
#include "nsIUserIdleService.h"
#include "nsServiceManagerUtils.h"
#include "xpcpublic.h"

namespace mozilla {

using mozilla::LogLevel;
static mozilla::LazyLogModule sLog("fog");

using glean::LogToBrowserConsole;

#ifdef MOZ_GLEAN_ANDROID
// Defined by `glean-core`. We reexport it here for later use.
extern "C" NS_EXPORT void glean_enable_logging(void);

// Workaround to force a re-export of the `no_mangle` symbols from `glean-core`
//
// Due to how linking works and hides symbols the symbols from `glean-core`
// might not be re-exported and thus not usable. By forcing use of _at least
// one_ symbol in an exported function the functions will also be rexported.
//
// See also https://github.com/rust-lang/rust/issues/50007
extern "C" NS_EXPORT void _fog_force_reexport_donotcall(void) {
  glean_enable_logging();
}
#endif

static StaticRefPtr<FOG> gFOG;
static mozilla::Atomic<bool> gInitializeCalled(false);

// We wait for 5s of idle before dumping IPC and flushing ping data to disk.
// This number hasn't been tuned, so if you have a reason to change it,
// please by all means do.
const uint32_t kIdleSecs = 5;

// static
already_AddRefed<FOG> FOG::GetSingleton() {
  if (gFOG) {
    return do_AddRef(gFOG);
  }

  MOZ_LOG(sLog, LogLevel::Debug, ("FOG::GetSingleton()"));

  gFOG = new FOG();

  if (XRE_IsParentProcess()) {
    nsresult rv;
    nsCOMPtr<nsIUserIdleService> idleService =
        do_GetService("@mozilla.org/widget/useridleservice;1", &rv);
    NS_ENSURE_SUCCESS(rv, nullptr);
    MOZ_ASSERT(idleService);
    if (NS_WARN_IF(NS_FAILED(idleService->AddIdleObserver(gFOG, kIdleSecs)))) {
      glean::fog::failed_idle_registration.Set(true);
    }

    RunOnShutdown(
        [&] {
          nsresult rv;
          nsCOMPtr<nsIUserIdleService> idleService =
              do_GetService("@mozilla.org/widget/useridleservice;1", &rv);
          if (NS_SUCCEEDED(rv)) {
            MOZ_ASSERT(idleService);
            Unused << idleService->RemoveIdleObserver(gFOG, kIdleSecs);
          }
          if (!gInitializeCalled) {
            gInitializeCalled = true;
            // Assuming default data path and application id.
            // Consumers using non defaults _must_ initialize FOG explicitly.
            MOZ_LOG(sLog, LogLevel::Debug,
                    ("Init not called. Init-ing in shutdown"));
            glean::fog::inits_during_shutdown.Add(1);
            // It's enough to call init before shutting down.
            // We don't need to (and can't) wait for it to complete.
            glean::impl::fog_init(&VoidCString(), &VoidCString());
          }
          gFOG->Shutdown();
          gFOG = nullptr;
        },
        ShutdownPhase::XPCOMShutdown);
  }
  return do_AddRef(gFOG);
}

void FOG::Shutdown() {
  MOZ_ASSERT(XRE_IsParentProcess());
  glean::impl::fog_shutdown();
}

// This allows us to know it's too late to submit a ping in Rust.
extern "C" bool FOG_TooLateToSend(void) {
  MOZ_ASSERT(XRE_IsParentProcess());
  return AppShutdown::IsInOrBeyond(ShutdownPhase::AppShutdownNetTeardown);
}

// This allows us to pass the configurable maximum ping limit (in pings per
// minute) to Rust. Default value is 15.
extern "C" uint32_t FOG_MaxPingLimit(void) {
  return NimbusFeatures::GetInt("gleanInternalSdk"_ns,
                                "gleanMaxPingsPerMinute"_ns, 15);
}

// This allows us to pass whether to enable precise event timestamps to Rust.
// Default is false.
extern "C" bool FOG_EventTimestampsEnabled(void) {
  return NimbusFeatures::GetBool("gleanInternalSdk"_ns,
                                 "enableEventTimestamps"_ns, false);
}

// Called when knowing if we're in automation is necessary.
extern "C" bool FOG_IPCIsInAutomation(void) { return xpc::IsInAutomation(); }

NS_IMETHODIMP
FOG::InitializeFOG(const nsACString& aDataPathOverride,
                   const nsACString& aAppIdOverride) {
  MOZ_ASSERT(XRE_IsParentProcess());
  gInitializeCalled = true;
  RunOnShutdown(
      [&] {
        if (NimbusFeatures::GetBool("gleanInternalSdk"_ns, "finalInactive"_ns,
                                    false)) {
          glean::impl::fog_internal_glean_handle_client_inactive();
        }
      },
      ShutdownPhase::AppShutdownConfirmed);

  return glean::impl::fog_init(&aDataPathOverride, &aAppIdOverride);
}

NS_IMETHODIMP
FOG::RegisterCustomPings() {
  MOZ_ASSERT(XRE_IsParentProcess());
  glean::impl::fog_register_pings();
  return NS_OK;
}

NS_IMETHODIMP
FOG::SetLogPings(bool aEnableLogPings) {
#ifdef MOZ_GLEAN_ANDROID
  return NS_OK;
#else
  MOZ_ASSERT(XRE_IsParentProcess());
  return glean::impl::fog_set_log_pings(aEnableLogPings);
#endif
}

NS_IMETHODIMP
FOG::SetTagPings(const nsACString& aDebugTag) {
#ifdef MOZ_GLEAN_ANDROID
  return NS_OK;
#else
  MOZ_ASSERT(XRE_IsParentProcess());
  return glean::impl::fog_set_debug_view_tag(&aDebugTag);
#endif
}

NS_IMETHODIMP
FOG::SendPing(const nsACString& aPingName) {
#ifdef MOZ_GLEAN_ANDROID
  return NS_OK;
#else
  MOZ_ASSERT(XRE_IsParentProcess());
  return glean::impl::fog_submit_ping(&aPingName);
#endif
}

NS_IMETHODIMP
FOG::SetExperimentActive(const nsACString& aExperimentId,
                         const nsACString& aBranch, JS::HandleValue aExtra,
                         JSContext* aCx) {
#ifdef MOZ_GLEAN_ANDROID
  NS_WARNING("Don't set experiments from Gecko in Android. Ignoring.");
  return NS_OK;
#else
  MOZ_ASSERT(XRE_IsParentProcess());
  nsTArray<nsCString> extraKeys;
  nsTArray<nsCString> extraValues;
  if (!aExtra.isNullOrUndefined()) {
    JS::RootedObject obj(aCx, &aExtra.toObject());
    JS::Rooted<JS::IdVector> keys(aCx, JS::IdVector(aCx));
    if (!JS_Enumerate(aCx, obj, &keys)) {
      LogToBrowserConsole(nsIScriptError::warningFlag,
                          u"Failed to enumerate experiment extras object."_ns);
      return NS_OK;
    }

    for (size_t i = 0, n = keys.length(); i < n; i++) {
      nsAutoJSCString jsKey;
      if (!jsKey.init(aCx, keys[i])) {
        LogToBrowserConsole(
            nsIScriptError::warningFlag,
            u"Extra dictionary should only contain string keys."_ns);
        return NS_OK;
      }

      JS::Rooted<JS::Value> value(aCx);
      if (!JS_GetPropertyById(aCx, obj, keys[i], &value)) {
        LogToBrowserConsole(nsIScriptError::warningFlag,
                            u"Failed to get experiment extra property."_ns);
        return NS_OK;
      }

      nsAutoJSCString jsValue;
      if (!value.isString()) {
        LogToBrowserConsole(
            nsIScriptError::warningFlag,
            u"Experiment extra properties must have string values."_ns);
        return NS_OK;
      }

      if (!jsValue.init(aCx, value)) {
        LogToBrowserConsole(nsIScriptError::warningFlag,
                            u"Can't extract experiment extra property"_ns);
        return NS_OK;
      }

      extraKeys.AppendElement(jsKey);
      extraValues.AppendElement(jsValue);
    }
  }
  glean::impl::fog_set_experiment_active(&aExperimentId, &aBranch, &extraKeys,
                                         &extraValues);
  return NS_OK;
#endif
}

NS_IMETHODIMP
FOG::SetExperimentInactive(const nsACString& aExperimentId) {
#ifdef MOZ_GLEAN_ANDROID
  NS_WARNING("Don't unset experiments from Gecko in Android. Ignoring.");
  return NS_OK;
#else
  MOZ_ASSERT(XRE_IsParentProcess());
  glean::impl::fog_set_experiment_inactive(&aExperimentId);
  return NS_OK;
#endif
}

NS_IMETHODIMP
FOG::TestGetExperimentData(const nsACString& aExperimentId, JSContext* aCx,
                           JS::MutableHandleValue aResult) {
#ifdef MOZ_GLEAN_ANDROID
  NS_WARNING("Don't test experiments from Gecko in Android. Throwing.");
  aResult.set(JS::UndefinedValue());
  return NS_ERROR_FAILURE;
#else
  MOZ_ASSERT(XRE_IsParentProcess());
  if (!glean::impl::fog_test_is_experiment_active(&aExperimentId)) {
    aResult.set(JS::UndefinedValue());
    return NS_OK;
  }

  // We could struct-up the branch and extras and do what
  // EventMetric::TestGetValue does... but keeping allocation on this side feels
  // cleaner to me at the moment.
  nsCString branch;
  nsTArray<nsCString> extraKeys;
  nsTArray<nsCString> extraValues;

  glean::impl::fog_test_get_experiment_data(&aExperimentId, &branch, &extraKeys,
                                            &extraValues);
  MOZ_ASSERT(extraKeys.Length() == extraValues.Length());

  JS::RootedObject jsExperimentDataObj(aCx, JS_NewPlainObject(aCx));
  if (NS_WARN_IF(!jsExperimentDataObj)) {
    return NS_ERROR_FAILURE;
  }

  JS::RootedValue jsBranchStr(aCx);
  if (!dom::ToJSValue(aCx, branch, &jsBranchStr) ||
      !JS_DefineProperty(aCx, jsExperimentDataObj, "branch", jsBranchStr,
                         JSPROP_ENUMERATE)) {
    NS_WARNING("Failed to define branch for experiment data object.");
    return NS_ERROR_FAILURE;
  }

  JS::RootedObject jsExtraObj(aCx, JS_NewPlainObject(aCx));
  if (!JS_DefineProperty(aCx, jsExperimentDataObj, "extra", jsExtraObj,
                         JSPROP_ENUMERATE)) {
    NS_WARNING("Failed to define extra for experiment data object.");
    return NS_ERROR_FAILURE;
  }

  for (unsigned int i = 0; i < extraKeys.Length(); i++) {
    JS::RootedValue jsValueStr(aCx);
    if (!dom::ToJSValue(aCx, extraValues[i], &jsValueStr) ||
        !JS_DefineProperty(aCx, jsExtraObj, extraKeys[i].Data(), jsValueStr,
                           JSPROP_ENUMERATE)) {
      NS_WARNING("Failed to define extra property for experiment data object.");
      return NS_ERROR_FAILURE;
    }
  }
  aResult.setObject(*jsExperimentDataObj);
  return NS_OK;
#endif
}

NS_IMETHODIMP
FOG::SetMetricsFeatureConfig(const nsACString& aJsonConfig) {
#ifdef MOZ_GLEAN_ANDROID
  NS_WARNING(
      "Don't set metric feature configs from Gecko in Android. Ignoring.");
  return NS_OK;
#else
  MOZ_ASSERT(XRE_IsParentProcess());
  glean::impl::fog_set_metrics_feature_config(&aJsonConfig);
  return NS_OK;
#endif
}

NS_IMETHODIMP
FOG::TestFlushAllChildren(JSContext* aCx, mozilla::dom::Promise** aOutPromise) {
  MOZ_ASSERT(XRE_IsParentProcess());
  NS_ENSURE_ARG(aOutPromise);
  *aOutPromise = nullptr;
  nsIGlobalObject* global = xpc::CurrentNativeGlobal(aCx);
  if (NS_WARN_IF(!global)) {
    return NS_ERROR_FAILURE;
  }

  ErrorResult erv;
  RefPtr<dom::Promise> promise = dom::Promise::Create(global, erv);
  if (NS_WARN_IF(erv.Failed())) {
    return erv.StealNSResult();
  }

  glean::FlushAndUseFOGData()->Then(
      GetCurrentSerialEventTarget(), __func__,
      [promise]() { promise->MaybeResolveWithUndefined(); });

  promise.forget(aOutPromise);
  return NS_OK;
}

NS_IMETHODIMP
FOG::Observe(nsISupports* aSubject, const char* aTopic, const char16_t* aData) {
  MOZ_ASSERT(XRE_IsParentProcess());
  MOZ_ASSERT(NS_IsMainThread());

  // On idle, opportunistically flush child process data to the parent,
  // then persist ping-lifetime data to the db.
  if (!strcmp(aTopic, OBSERVER_TOPIC_IDLE)) {
    glean::FlushAndUseFOGData();
#ifndef MOZ_GLEAN_ANDROID
    Unused << glean::impl::fog_persist_ping_lifetime_data();
#endif
  }

  return NS_OK;
}

NS_IMETHODIMP
FOG::TestResetFOG(const nsACString& aDataPathOverride,
                  const nsACString& aAppIdOverride) {
  MOZ_ASSERT(XRE_IsParentProcess());
  return glean::impl::fog_test_reset(&aDataPathOverride, &aAppIdOverride);
}

NS_IMETHODIMP
FOG::TestTriggerMetrics(uint32_t aProcessType, JSContext* aCx,
                        mozilla::dom::Promise** aOutPromise) {
  MOZ_ASSERT(XRE_IsParentProcess());
  NS_ENSURE_ARG(aOutPromise);
  *aOutPromise = nullptr;
  nsIGlobalObject* global = xpc::CurrentNativeGlobal(aCx);
  if (NS_WARN_IF(!global)) {
    return NS_ERROR_FAILURE;
  }

  ErrorResult erv;
  RefPtr<dom::Promise> promise = dom::Promise::Create(global, erv);
  if (NS_WARN_IF(erv.Failed())) {
    return erv.StealNSResult();
  }

  glean::TestTriggerMetrics(aProcessType, promise);

  promise.forget(aOutPromise);
  return NS_OK;
}

NS_IMETHODIMP
FOG::TestRegisterRuntimeMetric(
    const nsACString& aType, const nsACString& aCategory,
    const nsACString& aName, const nsTArray<nsCString>& aPings,
    const nsACString& aLifetime, const bool aDisabled,
    const nsACString& aExtraArgs, uint32_t* aMetricIdOut) {
  *aMetricIdOut = 0;
  *aMetricIdOut = glean::jog::jog_test_register_metric(
      &aType, &aCategory, &aName, &aPings, &aLifetime, aDisabled, &aExtraArgs);
  return NS_OK;
}

NS_IMETHODIMP
FOG::TestRegisterRuntimePing(const nsACString& aName,
                             const bool aIncludeClientId,
                             const bool aSendIfEmpty,
                             const bool aPreciseTimestamps,
                             const nsTArray<nsCString>& aReasonCodes,
                             uint32_t* aPingIdOut) {
  *aPingIdOut = 0;
  *aPingIdOut =
      glean::jog::jog_test_register_ping(&aName, aIncludeClientId, aSendIfEmpty,
                                         aPreciseTimestamps, &aReasonCodes);
  return NS_OK;
}

NS_IMPL_ISUPPORTS(FOG, nsIFOG, nsIObserver)

}  //  namespace mozilla