1 /* 2 * Copyright (C) 2021 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 #pragma once 18 19 #include "LruSet.h" 20 #include "StringUtils.h" 21 #include "Wrap.h" 22 23 namespace android::mediametrics { 24 25 /* 26 * ValidateId is used to check whether the log session id is properly formed 27 * and has been registered (i.e. from the Java MediaMetricsManagerService). 28 * 29 * The default memory window to track registered ids is set to SINGLETON_LRU_SET_SIZE. 30 * 31 * This class is not thread-safe, but the singleton returned by get() uses LockWrap<> 32 * to ensure thread-safety. 33 */ 34 class ValidateId { 35 mediametrics::LruSet<std::string> mIdSet; 36 size_t mInvalidIds = 0; // count invalid ids encountered. 37 public: 38 /** Creates a ValidateId object with size memory window. */ ValidateId(size_t size)39 explicit ValidateId(size_t size) : mIdSet{size} {} 40 41 /** Returns a string dump of recent contents and stats. */ 42 std::string dump() const; 43 44 /** 45 * Registers the id string. 46 * 47 * If id string is malformed (not 16 Base64Url chars), it is ignored. 48 * Once registered, calling validateId() will return id (instead of the empty string). 49 * ValidateId may "forget" the id after not encountering it within the past N ids, 50 * where N is the size set in the constructor. 51 * 52 * param id string (from MediaMetricsManagerService). 53 */ 54 void registerId(const std::string& id); 55 56 /** 57 * Returns the empty string if id string is malformed (not 16 Base64Url chars) 58 * or if id string has not been seen (in the recent size ids); 59 * otherwise it returns the same id parameter. 60 * 61 * \param id string (to be sent to statsd). 62 */ 63 const std::string& validateId(const std::string& id); 64 65 /** Singleton set size */ 66 static inline constexpr size_t SINGLETON_LRU_SET_SIZE = 2000; 67 68 using LockedValidateId = mediametrics::LockWrap<ValidateId>; 69 /** 70 * Returns a singleton locked ValidateId object that is thread-safe using LockWrap<>. 71 * 72 * The Singleton ValidateId object is created with size LRU_SET_SIZE (during first call). 73 */ get()74 static inline LockedValidateId& get() { 75 static LockedValidateId privateSet{SINGLETON_LRU_SET_SIZE}; 76 return privateSet; 77 } 78 }; 79 80 } // namespace android::mediametrics 81