summaryrefslogtreecommitdiffstats
path: root/toolkit/components/telemetry/pings/EventPing.sys.mjs
blob: 36e8489e37cc96a03b8cd3f2e6aeef0c0ec5a299 (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
/* 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/. */

/*
 * This module sends Telemetry Events periodically:
 * https://firefox-source-docs.mozilla.org/toolkit/components/telemetry/telemetry/data/event-ping.html
 */

import { TelemetryUtils } from "resource://gre/modules/TelemetryUtils.sys.mjs";

import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";

const lazy = {};

ChromeUtils.defineESModuleGetters(lazy, {
  Log: "resource://gre/modules/Log.sys.mjs",
  TelemetryController: "resource://gre/modules/TelemetryController.sys.mjs",
  TelemetrySession: "resource://gre/modules/TelemetrySession.sys.mjs",
  clearTimeout: "resource://gre/modules/Timer.sys.mjs",
  setTimeout: "resource://gre/modules/Timer.sys.mjs",
});

const Utils = TelemetryUtils;

const MS_IN_A_MINUTE = 60 * 1000;

const DEFAULT_EVENT_LIMIT = 1000;
const DEFAULT_MIN_FREQUENCY_MS = 60 * MS_IN_A_MINUTE;
const DEFAULT_MAX_FREQUENCY_MS = 10 * MS_IN_A_MINUTE;

const LOGGER_NAME = "Toolkit.Telemetry";
const LOGGER_PREFIX = "TelemetryEventPing::";

const EVENT_LIMIT_REACHED_TOPIC = "event-telemetry-storage-limit-reached";

export var Policy = {
  setTimeout: (callback, delayMs) => lazy.setTimeout(callback, delayMs),
  clearTimeout: id => lazy.clearTimeout(id),
  sendPing: (type, payload, options) =>
    lazy.TelemetryController.submitExternalPing(type, payload, options),
};

export var TelemetryEventPing = {
  Reason: Object.freeze({
    PERIODIC: "periodic", // Sent the ping containing events from the past periodic interval (default one hour).
    MAX: "max", // Sent the ping containing the maximum number (default 1000) of event records, earlier than the periodic interval.
    SHUTDOWN: "shutdown", // Recorded data was sent on shutdown.
  }),

  EVENT_PING_TYPE: "event",

  _logger: null,

  _testing: false,

  // So that if we quickly reach the max limit we can immediately send.
  _lastSendTime: -DEFAULT_MIN_FREQUENCY_MS,

  _processStartTimestamp: 0,

  get dataset() {
    return Services.telemetry.canRecordPrereleaseData
      ? Ci.nsITelemetry.DATASET_PRERELEASE_CHANNELS
      : Ci.nsITelemetry.DATASET_ALL_CHANNELS;
  },

  startup() {
    this._log.trace("Starting up.");

    // Calculate process creation once.
    this._processStartTimestamp =
      Math.round(
        (Date.now() - TelemetryUtils.monotonicNow()) / MS_IN_A_MINUTE
      ) * MS_IN_A_MINUTE;

    Services.obs.addObserver(this, EVENT_LIMIT_REACHED_TOPIC);

    XPCOMUtils.defineLazyPreferenceGetter(
      this,
      "maxFrequency",
      Utils.Preferences.EventPingMaximumFrequency,
      DEFAULT_MAX_FREQUENCY_MS
    );
    XPCOMUtils.defineLazyPreferenceGetter(
      this,
      "minFrequency",
      Utils.Preferences.EventPingMinimumFrequency,
      DEFAULT_MIN_FREQUENCY_MS
    );

    this._startTimer();
  },

  shutdown() {
    this._log.trace("Shutting down.");
    // removeObserver may throw, which could interrupt shutdown.
    try {
      Services.obs.removeObserver(this, EVENT_LIMIT_REACHED_TOPIC);
    } catch (ex) {}

    this._submitPing(this.Reason.SHUTDOWN, true /* discardLeftovers */);
    this._clearTimer();
  },

  observe(aSubject, aTopic, aData) {
    switch (aTopic) {
      case EVENT_LIMIT_REACHED_TOPIC:
        this._log.trace("event limit reached");
        let now = Utils.monotonicNow();
        if (now - this._lastSendTime < this.maxFrequency) {
          this._log.trace("can't submit ping immediately as it's too soon");
          this._startTimer(
            this.maxFrequency - this._lastSendTime,
            this.Reason.MAX,
            true /* discardLeftovers*/
          );
        } else {
          this._log.trace("submitting ping immediately");
          this._submitPing(this.Reason.MAX);
        }
        break;
    }
  },

  _startTimer(
    delay = this.minFrequency,
    reason = this.Reason.PERIODIC,
    discardLeftovers = false
  ) {
    this._clearTimer();
    this._timeoutId = Policy.setTimeout(
      () => TelemetryEventPing._submitPing(reason, discardLeftovers),
      delay
    );
  },

  _clearTimer() {
    if (this._timeoutId) {
      Policy.clearTimeout(this._timeoutId);
      this._timeoutId = null;
    }
  },

  /**
   * Submits an "event" ping and restarts the timer for the next interval.
   *
   * @param {String} reason The reason we're sending the ping. One of TelemetryEventPing.Reason.
   * @param {bool} discardLeftovers Whether to discard event records left over from a previous ping.
   */
  _submitPing(reason, discardLeftovers = false) {
    this._log.trace("_submitPing");

    if (reason !== this.Reason.SHUTDOWN) {
      this._startTimer();
    }

    let snapshot = Services.telemetry.snapshotEvents(
      this.dataset,
      true /* clear */,
      DEFAULT_EVENT_LIMIT
    );

    if (!this._testing) {
      for (let process of Object.keys(snapshot)) {
        snapshot[process] = snapshot[process].filter(
          ([, category]) => !category.startsWith("telemetry.test")
        );
      }
    }

    let eventCount = Object.values(snapshot).reduce(
      (acc, val) => acc + val.length,
      0
    );
    if (eventCount === 0) {
      // Don't send a ping if we haven't any events.
      this._log.trace("not sending event ping due to lack of events");
      return;
    }

    // The reason doesn't matter as it will just be echo'd back.
    let sessionMeta = lazy.TelemetrySession.getMetadata(reason);

    let payload = {
      reason,
      processStartTimestamp: this._processStartTimestamp,
      sessionId: sessionMeta.sessionId,
      subsessionId: sessionMeta.subsessionId,
      lostEventsCount: 0,
      events: snapshot,
    };

    if (discardLeftovers) {
      // Any leftovers must be discarded, the count submitted in the ping.
      // This can happen on shutdown or if our max was reached before faster
      // than our maxFrequency.
      let leftovers = Services.telemetry.snapshotEvents(
        this.dataset,
        true /* clear */
      );
      let leftoverCount = Object.values(leftovers).reduce(
        (acc, val) => acc + val.length,
        0
      );
      payload.lostEventsCount = leftoverCount;
    }

    const options = {
      addClientId: true,
      addEnvironment: true,
      usePingSender: reason == this.Reason.SHUTDOWN,
    };

    this._lastSendTime = Utils.monotonicNow();
    Services.telemetry
      .getHistogramById("TELEMETRY_EVENT_PING_SENT")
      .add(reason);
    Policy.sendPing(this.EVENT_PING_TYPE, payload, options);
  },

  /**
   * Test-only, restore to initial state.
   */
  testReset() {
    this._lastSendTime = -DEFAULT_MIN_FREQUENCY_MS;
    this._clearTimer();
    this._testing = true;
  },

  get _log() {
    if (!this._logger) {
      this._logger = lazy.Log.repository.getLoggerWithMessagePrefix(
        LOGGER_NAME,
        LOGGER_PREFIX + "::"
      );
    }

    return this._logger;
  },
};