|
| 1 | +/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 | + * License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 | + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 | + |
| 5 | +import {DELETION_REQUEST_PING_NAME} from "../constants"; |
| 6 | +import Glean from "../glean"; |
| 7 | +import {generateUUIDv4} from "../utils"; |
| 8 | +import collectAndStorePing from "./maker"; |
| 9 | +import CommonPingData from "./index"; |
| 10 | + |
| 11 | +/** |
| 12 | + * Stores information about a ping. |
| 13 | + * |
| 14 | + * This is required so that given metric data queued on disk we can send |
| 15 | + * pings with the correct settings, e.g. whether it has a client_id. |
| 16 | + */ |
| 17 | +class PingType implements CommonPingData { |
| 18 | + readonly name: string; |
| 19 | + readonly includeClientId: boolean; |
| 20 | + readonly sendIfEmpty: boolean; |
| 21 | + readonly reasonCodes: string[]; |
| 22 | + |
| 23 | + constructor (meta: CommonPingData) { |
| 24 | + this.name = meta.name; |
| 25 | + this.includeClientId = meta.includeClientId; |
| 26 | + this.sendIfEmpty = meta.sendIfEmpty; |
| 27 | + this.reasonCodes = meta.reasonCodes ?? []; |
| 28 | + } |
| 29 | + |
| 30 | + private isDeletionRequest(): boolean { |
| 31 | + return this.name === DELETION_REQUEST_PING_NAME; |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * Collects and submits a ping for eventual uploading. |
| 36 | + * |
| 37 | + * The ping content is assembled as soon as possible, but upload is not |
| 38 | + * guaranteed to happen immediately, as that depends on the upload policies. |
| 39 | + * |
| 40 | + * If the ping currently contains no content, it will not be sent, |
| 41 | + * unless it is configured to be sent if empty. |
| 42 | + * |
| 43 | + * @param reason The reason the ping was triggered. Included in the |
| 44 | + * `ping_info.reason` part of the payload. |
| 45 | + */ |
| 46 | + submit(reason?: string): void { |
| 47 | + Glean.dispatcher.launch(async () => { |
| 48 | + if (!Glean.initialized) { |
| 49 | + console.info("Glean must be initialized before submitting pings."); |
| 50 | + return; |
| 51 | + } |
| 52 | + |
| 53 | + if (!Glean.isUploadEnabled() && !this.isDeletionRequest()) { |
| 54 | + console.info("Glean disabled: not submitting pings. Glean may still submit the deletion-request ping."); |
| 55 | + return; |
| 56 | + } |
| 57 | + |
| 58 | + let correctedReason = reason; |
| 59 | + if (reason && !this.reasonCodes.includes(reason)) { |
| 60 | + console.error(`Invalid reason code ${reason} from ${this.name}. Ignoring.`); |
| 61 | + correctedReason = undefined; |
| 62 | + } |
| 63 | + |
| 64 | + const identifier = generateUUIDv4(); |
| 65 | + await collectAndStorePing(identifier, this, correctedReason); |
| 66 | + return; |
| 67 | + }); |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +export default PingType; |
0 commit comments