1// Copyright (c) 2021 Huawei Device Co., Ltd.
2// Licensed under the Apache License, Version 2.0 (the "License");
3// you may not use this file except in compliance with the License.
4// You may obtain a copy of the License at
5//
6//     http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14import { CHART_OFFSET_LEFT, MAX_COUNT, QueryEnum, TraficEnum } from '../utils/QueryEnum';
15import { getThreadPool } from '../../SqlLite';
16import { TraceRow } from '../../../component/trace/base/TraceRow';
17import { ProcessStruct } from '../../ui-worker/ProcedureWorkerProcess';
18import { Utils } from '../../../component/trace/base/Utils';
19
20export function processDataSender(pid: number, row: TraceRow<ProcessStruct>, traceId?: string):
21  Promise<ProcessStruct[]> {
22  let trafic: number = TraficEnum.Memory;
23  let width = row.clientWidth - CHART_OFFSET_LEFT;
24  if (trafic === TraficEnum.SharedArrayBuffer && !row.sharedArrayBuffers) {
25    row.sharedArrayBuffers = {
26      cpu: new SharedArrayBuffer(Uint8Array.BYTES_PER_ELEMENT * MAX_COUNT),
27      value: new SharedArrayBuffer(Uint32Array.BYTES_PER_ELEMENT * MAX_COUNT),
28      dur: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT),
29      startTime: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT),
30    };
31  }
32  return new Promise((resolve): void => {
33    getThreadPool(traceId).submitProto(
34      QueryEnum.ProcessData,
35      {
36        pid: pid,
37        startNS: TraceRow.range?.startNS || 0,
38        endNS: TraceRow.range?.endNS || 0,
39        recordStartNS: Utils.getInstance().getRecordStartNS(traceId),
40        recordEndNS: Utils.getInstance().getRecordEndNS(traceId),
41        width: width,
42        t: new Date().getTime(),
43        trafic: trafic,
44        sharedArrayBuffers: row.sharedArrayBuffers,
45      },
46      (res: unknown, len: number, transfer: boolean): void => {
47        resolve(arrayBufferHandler(transfer ? res : row.sharedArrayBuffers, len));
48      }
49    );
50  });
51}
52
53function arrayBufferHandler(buffers: unknown, len: number): ProcessStruct[] {
54  let outArr: ProcessStruct[] = []; //@ts-ignore
55  let cpu = new Uint8Array(buffers.cpu); //@ts-ignore
56  let startTime = new Float64Array(buffers.startTime); //@ts-ignore
57  let dur = new Float64Array(buffers.dur);
58  for (let i = 0; i < len; i++) {
59    outArr.push({
60      cpu: cpu[i],
61      dur: dur[i],
62      startTime: startTime[i],
63    } as ProcessStruct);
64  }
65  return outArr;
66}
67