1/*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this 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 */
15
16#include "recovery_info_timer.h"
17#include "app_exit_reason_data_manager.h"
18
19namespace OHOS {
20namespace AAFwk {
21constexpr int32_t HOURS_TO_SECOND = 60 * 60;
22constexpr int32_t TIMEOUT_DELETE_TIME = 168;
23constexpr int32_t RESERVE_NUM = 5;
24
25RecoveryInfoTimer& RecoveryInfoTimer::GetInstance()
26{
27    static RecoveryInfoTimer instance;
28    return instance;
29}
30void RecoveryInfoTimer::SubmitSaveRecoveryInfo(RecoveryInfo recoveryInfo)
31{
32    std::lock_guard<std::mutex> lock(recoveryInfoQueueLock_);
33    auto findByInfo = [&recoveryInfo](RecoveryInfo& item) {
34        return item.abilityName == recoveryInfo.abilityName && item.bundleName == recoveryInfo.bundleName &&
35            item.moduleName == recoveryInfo.moduleName;
36    };
37    auto i = find_if(recoveryInfoQueue_.begin(), recoveryInfoQueue_.end(), findByInfo);
38    if (i != recoveryInfoQueue_.end()) {
39        recoveryInfoQueue_.erase(i);
40    }
41    recoveryInfoQueue_.push_back(recoveryInfo);
42
43    int64_t now = recoveryInfo.time;
44    auto timeoutDeleteTime = TIMEOUT_DELETE_TIME * HOURS_TO_SECOND;
45    auto reserveNumber = RESERVE_NUM;
46    int timeoutCount = 0;
47    for (auto p = recoveryInfoQueue_.begin(); p != recoveryInfoQueue_.end(); p++) {
48        if (now - p->time >= timeoutDeleteTime) {
49            timeoutCount++;
50        }
51    }
52
53    timeoutCount -= reserveNumber;
54    for (; timeoutCount > 0; timeoutCount--) {
55        auto recoveryInfo = recoveryInfoQueue_.begin();
56        TAG_LOGI(AAFwkTag::ABILITYMGR, "clearRecoveryInfo bundleName: %{public}s, abilityName: %{public}s",
57            recoveryInfo->bundleName.c_str(), recoveryInfo->abilityName.c_str());
58        (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
59            DeleteAbilityRecoverInfo(recoveryInfo->tokenId, recoveryInfo->moduleName, recoveryInfo->abilityName);
60        recoveryInfoQueue_.pop_front();
61    }
62}
63}
64}