• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright (C) 2020 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15import {RecordConfig} from '../controller/record_config_types';
16
17export const BUCKET_NAME = 'perfetto-ui-data';
18import * as uuidv4 from 'uuid/v4';
19import {State} from './state';
20
21export async function saveTrace(trace: File|ArrayBuffer): Promise<string> {
22  // TODO(hjd): This should probably also be a hash but that requires
23  // trace processor support.
24  const name = uuidv4();
25  const url = 'https://www.googleapis.com/upload/storage/v1/b/' +
26      `${BUCKET_NAME}/o?uploadType=media` +
27      `&name=${name}&predefinedAcl=publicRead`;
28  const response = await fetch(url, {
29    method: 'post',
30    headers: {'Content-Type': 'application/octet-stream;'},
31    body: trace,
32  });
33  await response.json();
34  return `https://storage.googleapis.com/${BUCKET_NAME}/${name}`;
35}
36
37export async function saveState(stateOrConfig: State|
38                                RecordConfig): Promise<string> {
39  const text = JSON.stringify(stateOrConfig);
40  const hash = await toSha256(text);
41  const url = 'https://www.googleapis.com/upload/storage/v1/b/' +
42      `${BUCKET_NAME}/o?uploadType=media` +
43      `&name=${hash}&predefinedAcl=publicRead`;
44  const response = await fetch(url, {
45    method: 'post',
46    headers: {
47      'Content-Type': 'application/json; charset=utf-8',
48    },
49    body: text,
50  });
51  await response.json();
52  return hash;
53}
54
55export async function toSha256(str: string): Promise<string> {
56  // TODO(hjd): TypeScript bug with definition of TextEncoder.
57  // tslint:disable-next-line no-any
58  const buffer = new (TextEncoder as any)('utf-8').encode(str);
59  const digest = await crypto.subtle.digest('SHA-256', buffer);
60  return Array.from(new Uint8Array(digest)).map(x => x.toString(16)).join('');
61}