1/*
2 * Copyright 2020, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17import viewerConfig
18  from '../../../../frameworks/base/data/etc/services.core.protolog.json';
19
20import {FormattedLogMessage, UnformattedLogMessage} from '@/traces/ProtoLog.ts';
21
22const PROTOLOG_VERSION = '1.0.0';
23
24class FormatStringMismatchError extends Error {
25  constructor(message) {
26    super(message);
27  }
28}
29
30function transformMessage(entry) {
31  const message = viewerConfig.messages[entry.messageHash];
32  if (message === undefined) {
33    return new FormattedLogMessage(entry);
34  } else {
35    try {
36      return new UnformattedLogMessage(entry, message);
37    } catch (err) {
38      if (err instanceof FormatStringMismatchError) {
39        return new FormattedLogMessage(entry);
40      }
41      throw err;
42    }
43  }
44}
45
46function transformProtolog(log) {
47  if (log.version !== PROTOLOG_VERSION) {
48    throw new Error('Unsupported log version');
49  }
50  if (viewerConfig.version !== PROTOLOG_VERSION) {
51    throw new Error('Unsupported viewer config version');
52  }
53
54  const data = log.log.map((entry) => (transformMessage(entry)));
55  data.sort(function(a, b) {
56    return a.timestamp - b.timestamp;
57  });
58  const transformed = {
59    children: data,
60  };
61  return transformed;
62}
63
64export {transformProtolog};
65