• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright (C) 2024 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use size 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 {Engine} from '../trace_processor/engine';
16
17export class FlamegraphCache {
18  private cache: Map<string, string>;
19  private prefix: string;
20  private tableId: number;
21  private cacheSizeLimit: number;
22
23  constructor(prefix: string) {
24    this.cache = new Map<string, string>();
25    this.prefix = prefix;
26    this.tableId = 0;
27    this.cacheSizeLimit = 10;
28  }
29
30  async getTableName(engine: Engine, query: string): Promise<string> {
31    let tableName = this.cache.get(query);
32    if (tableName === undefined) {
33      // TODO(hjd): This should be LRU.
34      if (this.cache.size > this.cacheSizeLimit) {
35        for (const name of this.cache.values()) {
36          await engine.query(`drop table ${name}`);
37        }
38        this.cache.clear();
39      }
40      tableName = `${this.prefix}_${this.tableId++}`;
41      await engine.query(
42        `create temp table if not exists ${tableName} as ${query}`,
43      );
44      this.cache.set(query, tableName);
45    }
46    return tableName;
47  }
48
49  hasQuery(query: string): boolean {
50    return this.cache.get(query) !== undefined;
51  }
52}
53