File: background_task_coordinator.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (224 lines) | stat: -rw-r--r-- 8,389 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/notifications/scheduler/internal/background_task_coordinator.h"

#include <algorithm>
#include <optional>
#include <utility>

#include "base/command_line.h"
#include "base/memory/raw_ptr.h"
#include "base/time/clock.h"
#include "base/time/time.h"
#include "chrome/browser/notifications/scheduler/internal/impression_types.h"
#include "chrome/browser/notifications/scheduler/internal/notification_entry.h"
#include "chrome/browser/notifications/scheduler/internal/scheduler_config.h"
#include "chrome/browser/notifications/scheduler/internal/scheduler_utils.h"
#include "chrome/browser/notifications/scheduler/public/features.h"
#include "chrome/browser/notifications/scheduler/public/notification_background_task_scheduler.h"

namespace notifications {
namespace {

class BackgroundTaskCoordinatorHelper {
 public:
  BackgroundTaskCoordinatorHelper(
      NotificationBackgroundTaskScheduler* background_task,
      const SchedulerConfig* config,
      base::Clock* clock)
      : background_task_(background_task), config_(config), clock_(clock) {}
  BackgroundTaskCoordinatorHelper(const BackgroundTaskCoordinatorHelper&) =
      delete;
  BackgroundTaskCoordinatorHelper& operator=(
      const BackgroundTaskCoordinatorHelper&) = delete;
  ~BackgroundTaskCoordinatorHelper() = default;

  void ScheduleBackgroundTask(
      BackgroundTaskCoordinator::Notifications notifications,
      BackgroundTaskCoordinator::ClientStates client_states) {
    if (notifications.empty()) {
      background_task_->Cancel();
      return;
    }

    BackgroundTaskCoordinator::Notifications unthrottled_notifications;
    BackgroundTaskCoordinator::Notifications throttled_notifications;
    for (auto& pair : notifications) {
      for (const notifications::NotificationEntry* notification : pair.second) {
        auto type = pair.first;
        if (notification->schedule_params.priority ==
            ScheduleParams::Priority::kNoThrottle) {
          unthrottled_notifications[type].emplace_back(notification);
        } else {
          throttled_notifications[type].emplace_back(notification);
        }
      }
    }
    ProcessUnthrottledNotifications(std::move(unthrottled_notifications));
    ProcessThrottledNotifications(std::move(throttled_notifications),
                                  std::move(client_states));
    ScheduleBackgroundTaskInternal();
  }

 private:
  void ProcessUnthrottledNotifications(
      BackgroundTaskCoordinator::Notifications notifications) {
    for (const auto& pair : notifications) {
      for (const notifications::NotificationEntry* entry : pair.second) {
        DCHECK_EQ(entry->schedule_params.priority,
                  ScheduleParams::Priority::kNoThrottle);
        if (!entry->schedule_params.deliver_time_start.has_value()) {
          continue;
        }
        base::Time deliver_time_start =
            entry->schedule_params.deliver_time_start.value();
        MaybeUpdateBackgroundTaskTime(deliver_time_start);
      }
    }
  }

  void ProcessThrottledNotifications(
      BackgroundTaskCoordinator::Notifications notifications,
      BackgroundTaskCoordinator::ClientStates client_states) {
    base::Time tomorrow;
    base::Time now = clock_->Now();
    bool success = ToLocalHour(0, now, 1 /*day_delta*/, &tomorrow);
    DCHECK(success);

    std::map<SchedulerClientType, int> shown_per_type;
    int shown_total = 0;
    SchedulerClientType last_shown_type = SchedulerClientType::kUnknown;
    NotificationsShownToday(client_states, &shown_per_type, &shown_total,
                            &last_shown_type, clock_);

    for (const auto& pair : notifications) {
      auto type = pair.first;
      auto it = client_states.find(type);
      if (pair.second.empty() || (it == client_states.end()))
        continue;

      const ClientState* client_state = it->second;
      bool reach_max_today =
          shown_per_type[type] >= client_state->current_max_daily_show ||
          shown_total >= config_->max_daily_shown_all_type;

      // Find the eariliest notification to launch the background task.
      for (const notifications::NotificationEntry* entry : pair.second) {
        DCHECK_NE(entry->schedule_params.priority,
                  ScheduleParams::Priority::kNoThrottle);
        // Currently only support deliver time window.
        if (!entry->schedule_params.deliver_time_start.has_value()) {
          continue;
        }

        base::Time deliver_time_start =
            entry->schedule_params.deliver_time_start.value();

        // Consider suppression time.
        if (client_state->suppression_info.has_value() &&
            deliver_time_start <
                client_state->suppression_info->ReleaseTime()) {
          deliver_time_start = client_state->suppression_info->ReleaseTime();
        }

        // Consider daily limit throttling.
        if (reach_max_today && deliver_time_start < tomorrow)
          deliver_time_start = tomorrow;

        // Deliver time window has passed.
        DCHECK(entry->schedule_params.deliver_time_end.has_value());
        if (!entry->schedule_params.deliver_time_end.has_value() ||
            deliver_time_start >
                entry->schedule_params.deliver_time_end.value()) {
          continue;
        }

        MaybeUpdateBackgroundTaskTime(deliver_time_start);
      }
    }
  }

  void MaybeUpdateBackgroundTaskTime(const base::Time& time) {
    if (!background_task_time_.has_value() ||
        time < background_task_time_.value())
      background_task_time_ = time;
  }

  void ScheduleBackgroundTaskInternal() {
    if (!background_task_time_.has_value())
      return;

    base::TimeDelta window_start_time =
        background_task_time_.value() - clock_->Now();
    window_start_time = std::clamp(window_start_time, base::TimeDelta(),
                                    base::TimeDelta::Max());

    // TODO(xingliu): Remove SchedulerTaskTime.
    if (base::CommandLine::ForCurrentProcess()->HasSwitch(
            switches::kNotificationSchedulerImmediateBackgroundTask)) {
      background_task_->Schedule(base::Seconds(30), base::Minutes(1));
      return;
    }

    background_task_->Schedule(
        window_start_time,
        window_start_time + config_->background_task_window_duration);
  }

  raw_ptr<NotificationBackgroundTaskScheduler> background_task_;
  raw_ptr<const SchedulerConfig> config_;
  raw_ptr<base::Clock> clock_;
  std::optional<base::Time> background_task_time_;
};

}  // namespace

class BackgroundTaskCoordinatorImpl : public BackgroundTaskCoordinator {
 public:
  BackgroundTaskCoordinatorImpl(
      std::unique_ptr<NotificationBackgroundTaskScheduler> background_task,
      const SchedulerConfig* config,
      base::Clock* clock)
      : background_task_(std::move(background_task)),
        config_(config),
        clock_(clock) {}

  BackgroundTaskCoordinatorImpl(const BackgroundTaskCoordinatorImpl&) = delete;
  BackgroundTaskCoordinatorImpl& operator=(
      const BackgroundTaskCoordinatorImpl&) = delete;
  ~BackgroundTaskCoordinatorImpl() override = default;

 private:
  // BackgroundTaskCoordinator implementation.
  void ScheduleBackgroundTask(Notifications notifications,
                              ClientStates client_states) override {
    auto helper = std::make_unique<BackgroundTaskCoordinatorHelper>(
        background_task_.get(), config_, clock_);
    helper->ScheduleBackgroundTask(std::move(notifications),
                                   std::move(client_states));
  }

  // The class that actually schedules platform background task.
  std::unique_ptr<NotificationBackgroundTaskScheduler> background_task_;

  // System configuration.
  raw_ptr<const SchedulerConfig> config_;

  // Clock to query the current timestamp.
  raw_ptr<base::Clock> clock_;
};

// static
std::unique_ptr<BackgroundTaskCoordinator> BackgroundTaskCoordinator::Create(
    std::unique_ptr<NotificationBackgroundTaskScheduler> background_task,
    const SchedulerConfig* config,
    base::Clock* clock) {
  return std::make_unique<BackgroundTaskCoordinatorImpl>(
      std::move(background_task), config, clock);
}

BackgroundTaskCoordinator::~BackgroundTaskCoordinator() = default;

}  // namespace notifications