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 { threadPool } from '../../SqlLite';
16import { TraceRow } from '../../../component/trace/base/TraceRow';
17import { ProcessMemStruct } from '../../ui-worker/ProcedureWorkerMem';
18
19export function processMemDataSender(trackId: number, row: TraceRow<ProcessMemStruct>): Promise<ProcessMemStruct[]> {
20  let trafic: number = TraficEnum.ProtoBuffer;
21  let width = row.clientWidth - CHART_OFFSET_LEFT;
22  if (trafic === TraficEnum.SharedArrayBuffer && !row.sharedArrayBuffers) {
23    row.sharedArrayBuffers = {
24      track_id: new SharedArrayBuffer(Uint8Array.BYTES_PER_ELEMENT * MAX_COUNT),
25      value: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT),
26      startTime: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT),
27      ts: new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT * MAX_COUNT),
28    };
29  }
30  return new Promise((resolve): void => {
31    threadPool.submitProto(
32      QueryEnum.ProcessMemData,
33      {
34        startNS: TraceRow.range?.startNS || 0,
35        endNS: TraceRow.range?.endNS || 0,
36        recordStartNS: window.recordStartNS,
37        recordEndNS: window.recordEndNS,
38        width: width,
39        trafic: trafic,
40        sharedArrayBuffers: row.sharedArrayBuffers,
41        t: Date.now(),
42        trackId: trackId,
43      },
44      (res: unknown, len: number, transfer: boolean): void => {
45        resolve(arrayBufferHandler(transfer ? res : row.sharedArrayBuffers, len));
46      }
47    );
48  });
49}
50
51function arrayBufferHandler(buffers: unknown, len: number): ProcessMemStruct[] {
52  let outArr: ProcessMemStruct[] = [];
53  //@ts-ignore
54  let track_id = new Uint8Array(buffers.track_id);
55  //@ts-ignore
56  let value = new Float64Array(buffers.value);
57  //@ts-ignore
58  let startTime = new Float64Array(buffers.startTime);
59  //@ts-ignore
60  let ts = new Float64Array(buffers.ts);
61  for (let i = 0; i < len; i++) {
62    outArr.push({
63      track_id: track_id[i],
64      value: value[i],
65      startTime: startTime[i],
66      ts: ts[i],
67    } as unknown as ProcessMemStruct);
68  }
69  return outArr;
70}
71