xref: /aosp_15_r20/external/perfetto/src/trace_processor/trace_reader_registry.h (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
1 /*
2  * Copyright (C) 2024 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 
17 #ifndef SRC_TRACE_PROCESSOR_TRACE_READER_REGISTRY_H_
18 #define SRC_TRACE_PROCESSOR_TRACE_READER_REGISTRY_H_
19 
20 #include <functional>
21 #include <memory>
22 
23 #include "perfetto/ext/base/flat_hash_map.h"
24 #include "perfetto/ext/base/status_or.h"
25 #include "src/trace_processor/util/trace_type.h"
26 
27 namespace perfetto {
28 namespace trace_processor {
29 
30 class ChunkedTraceReader;
31 class TraceProcessorContext;
32 
33 // Maps `TraceType` values to `ChunkedTraceReader` subclasses.
34 // This class is used to create `ChunkedTraceReader` instances for a given
35 // `TraceType`.
36 class TraceReaderRegistry {
37  public:
TraceReaderRegistry(TraceProcessorContext * context)38   explicit TraceReaderRegistry(TraceProcessorContext* context)
39       : context_(context) {}
40 
41   // Registers a mapping from `TraceType` value to `ChunkedTraceReader`
42   // subclass. Only one such mapping can be registered per `TraceType` value.
43   template <typename Reader>
RegisterTraceReader(TraceType trace_type)44   void RegisterTraceReader(TraceType trace_type) {
45     RegisterFactory(trace_type, [](TraceProcessorContext* ctxt) {
46       return std::make_unique<Reader>(ctxt);
47     });
48   }
49 
50   // Creates a new `ChunkedTraceReader` instance for the given `type`. Returns
51   // an error if no mapping has been previously registered.
52   base::StatusOr<std::unique_ptr<ChunkedTraceReader>> CreateTraceReader(
53       TraceType type);
54 
55  private:
56   using Factory = std::function<std::unique_ptr<ChunkedTraceReader>(
57       TraceProcessorContext*)>;
58   void RegisterFactory(TraceType trace_type, Factory factory);
59 
60   TraceProcessorContext* const context_;
61   base::FlatHashMap<TraceType,
62                     std::function<std::unique_ptr<ChunkedTraceReader>(
63                         TraceProcessorContext*)>>
64       factories_;
65 };
66 
67 }  // namespace trace_processor
68 }  // namespace perfetto
69 
70 #endif  // SRC_TRACE_PROCESSOR_TRACE_READER_REGISTRY_H_
71