xref: /aosp_15_r20/external/cronet/components/metrics/debug/log_utils.ts (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1// Copyright 2022 The Chromium Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5import {assert} from 'chrome://resources/js/assert.js';
6
7import type {LogEvent} from './browser_proxy.js';
8
9/**
10 * Helper function to convert undefined UMA log types to "Unknown" string.
11 * @param type The UMA log's type (i.e., ongoing, independent, or stability).
12 * @returns The UMA log's type. "Unknown" if type is undefined.
13 */
14export function umaLogTypeToString(type: string|undefined) {
15  if (!type) {
16    return 'Unknown';
17  }
18  return type;
19}
20
21/**
22 * Converts a given Unix timestamp into a human-readable string.
23 * @param timestampSeconds The timestamp string (seconds since Epoch).
24 * @return A human-readable representation of the timestamp (e.g "01/01/1970,
25 *     12:00:00 AM").
26 */
27export function timestampToString(timestampSeconds: string) {
28  if (!timestampSeconds.length) {
29    // This case should not normally happen, but can happen when the table is
30    // empty (a dummy log |EMPTY_LOG| is added, which has an empty timestamp).
31    return 'N/A';
32  }
33
34  const timestampInt = parseInt(timestampSeconds);
35  assert(!isNaN(timestampInt));
36  // Multiply by 1000 since the constructor expects milliseconds, but the
37  // timestamps are in seconds.
38  return new Date(timestampInt * 1000).toLocaleString();
39}
40
41/**
42 * Converts the size of a log to a human-readable string.
43 * @param size The size of the log in bytes.
44 * @returns The size of the log in KiB as a string.
45 */
46export function sizeToString(size: number) {
47  if (size < 0) {
48    // This case should not normally happen, but can happen when the table is
49    // empty (a dummy log |EMPTY_LOG| is added, which has size -1).
50    return 'N/A';
51  }
52  return `${(size / 1024).toFixed(2)} KiB`;
53}
54
55/**
56 * Converts a log event to a human-readable string.
57 * @param event The log event.
58 * @returns A human-readable string of the log event.
59 */
60export function logEventToString(event: LogEvent) {
61  let result = `[${new Date(event.timestampMs).toISOString()}] ${event.event}`;
62  if (event.message) {
63    result += ` (${event.message})`;
64  }
65  return result;
66}
67
68/**
69 * Gets the string to display when the events div of a log are collapsed.
70 * @param events The list of events of the log.
71 * @returns A human-readable string of the last event that occurred.
72 */
73export function getEventsPeekString(events: LogEvent[]) {
74  if (!events.length) {
75    return 'N/A';
76  }
77  // Need to assert that last element exists, otherwise the call to
78  // logEventToString() fails to compile.
79  const lastEvent = events[events.length - 1];
80  assert(lastEvent);
81  return logEventToString(lastEvent);
82}
83