-
Notifications
You must be signed in to change notification settings - Fork 54
/
service_task.rs
332 lines (307 loc) · 11 KB
/
service_task.rs
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use super::{
action::{
Action,
Action::{MonitorDownload, StartDownload},
ServiceAction,
},
client::{with_maybe_new_bits_client, ClientInitData},
dispatch_callback::{maybe_dispatch_request_via_callback, CallbackExpected},
error::{BitsTaskError, ErrorStage::CommandThread},
from_threadbound::{expect_from_threadbound_option, get_from_threadbound_option, DataType},
string::nsCString_to_OsString,
BitsRequest, BitsService,
};
use bits_client::{BitsClient, BitsMonitorClient, BitsProxyUsage, Guid};
use crossbeam_utils::atomic::AtomicCell;
use log::{info, warn};
use moz_task::Task;
use nserror::nsresult;
use nsstring::nsCString;
use xpcom::{
interfaces::{nsIBitsNewRequestCallback, nsIRequestObserver, nsISupports},
RefPtr, ThreadBoundRefPtr,
};
// D is the Data Type that the RunFn function needs to make S.
// S is the Success Type that the RunFn returns on success and that the
// DoneFn needs to make the BitsRequest.
type RunFn<D, S> = fn(&D, &mut BitsClient) -> Result<S, BitsTaskError>;
type DoneFn<D, S> = fn(
&D,
S,
&ClientInitData,
&BitsService,
&nsIRequestObserver,
Option<&nsISupports>,
) -> Result<RefPtr<BitsRequest>, BitsTaskError>;
pub struct ServiceTask<D, S> {
client_init_data: ClientInitData,
action: ServiceAction,
task_data: D,
run_fn: RunFn<D, S>,
done_fn: DoneFn<D, S>,
bits_service: AtomicCell<Option<ThreadBoundRefPtr<BitsService>>>,
observer: AtomicCell<Option<ThreadBoundRefPtr<nsIRequestObserver>>>,
context: AtomicCell<Option<ThreadBoundRefPtr<nsISupports>>>,
callback: AtomicCell<Option<ThreadBoundRefPtr<nsIBitsNewRequestCallback>>>,
result: AtomicCell<Option<Result<S, BitsTaskError>>>,
}
impl<D, S> ServiceTask<D, S>
where
D: Sync + Send,
S: Sync + Send,
{
pub fn new(
client_init_data: ClientInitData,
action: ServiceAction,
task_data: D,
run_fn: RunFn<D, S>,
done_fn: DoneFn<D, S>,
bits_service: RefPtr<BitsService>,
observer: RefPtr<nsIRequestObserver>,
context: Option<RefPtr<nsISupports>>,
callback: RefPtr<nsIBitsNewRequestCallback>,
) -> ServiceTask<D, S> {
ServiceTask {
client_init_data,
action,
task_data,
run_fn,
done_fn,
bits_service: AtomicCell::new(Some(ThreadBoundRefPtr::new(bits_service))),
observer: AtomicCell::new(Some(ThreadBoundRefPtr::new(observer))),
context: AtomicCell::new(context.map(ThreadBoundRefPtr::new)),
callback: AtomicCell::new(Some(ThreadBoundRefPtr::new(callback))),
result: AtomicCell::new(None),
}
}
}
impl<D, S> Task for ServiceTask<D, S> {
fn run(&self) {
let result =
with_maybe_new_bits_client(&self.client_init_data, self.action.into(), |client| {
(self.run_fn)(&self.task_data, client)
});
self.result.store(Some(result));
}
fn done(&self) -> Result<(), nsresult> {
// If TaskRunnable.run() calls Task.done() to return a result
// on the main thread before TaskRunnable.run() returns on the worker
// thread, then the Task will get dropped on the worker thread.
//
// But the callback is an nsXPCWrappedJS that isn't safe to release
// on the worker thread. So we move it out of the Task here to ensure
// it gets released on the main thread.
let maybe_tb_callback = self.callback.swap(None);
// It also isn't safe to drop the BitsService RefPtr off-thread,
// because BitsService refcounting is non-atomic
let maybe_tb_service = self.bits_service.swap(None);
// The observer and context are also an nsXPCWrappedJS that aren't safe
// to release on the worker thread.
let maybe_tb_observer = self.observer.swap(None);
let maybe_tb_context = self.context.swap(None);
let action: Action = self.action.into();
let maybe_callback =
expect_from_threadbound_option(&maybe_tb_callback, DataType::Callback, action);
// Immediately invoked function expression to allow for the ? operator
let result: Result<RefPtr<BitsRequest>, BitsTaskError> = (|| {
let bits_service =
expect_from_threadbound_option(&maybe_tb_service, DataType::BitsService, action)?;
let observer =
expect_from_threadbound_option(&maybe_tb_observer, DataType::Observer, action)?;
let maybe_context =
get_from_threadbound_option(&maybe_tb_context, DataType::Context, action);
let success = self
.result
.swap(None)
.ok_or_else(|| BitsTaskError::missing_result(action))??;
(self.done_fn)(
&self.task_data,
success,
&self.client_init_data,
bits_service,
observer,
maybe_context,
)
})();
info!("BITS Interface Task completed: {:?}", result);
// We incremented the request count when we dispatched an action to
// start the job. Now we will decrement since the action completed.
// See the declaration of InitBitsService::request_count for details.
let bits_service_result =
expect_from_threadbound_option(&maybe_tb_service, DataType::BitsService, action);
match bits_service_result {
Ok(bits_service) => {
bits_service.dec_request_count();
}
Err(error) => {
warn!(
concat!(
"Unable to decrement the request count when finishing ServiceTask. ",
"The command thread may not be shut down. Error: {:?}"
),
error
);
}
}
maybe_dispatch_request_via_callback(result, maybe_callback, CallbackExpected)
}
}
struct StartDownloadData {
download_url: nsCString,
save_rel_path: nsCString,
proxy: BitsProxyUsage,
no_progress_timeout_secs: u32,
update_interval_ms: u32,
}
struct StartDownloadSuccess {
guid: Guid,
monitor_client: BitsMonitorClient,
}
pub struct StartDownloadTask(ServiceTask<StartDownloadData, StartDownloadSuccess>);
impl Task for StartDownloadTask {
fn run(&self) {
self.0.run();
}
fn done(&self) -> Result<(), nsresult> {
self.0.done()
}
}
impl StartDownloadTask {
pub fn new(
client_init_data: ClientInitData,
download_url: nsCString,
save_rel_path: nsCString,
proxy: BitsProxyUsage,
no_progress_timeout_secs: u32,
update_interval_ms: u32,
bits_service: RefPtr<BitsService>,
observer: RefPtr<nsIRequestObserver>,
context: Option<RefPtr<nsISupports>>,
callback: RefPtr<nsIBitsNewRequestCallback>,
) -> StartDownloadTask {
StartDownloadTask(ServiceTask::new(
client_init_data,
ServiceAction::StartDownload,
StartDownloadData {
download_url,
save_rel_path,
proxy,
no_progress_timeout_secs,
update_interval_ms,
},
StartDownloadTask::run_fn,
StartDownloadTask::done_fn,
bits_service,
observer,
context,
callback,
))
}
fn run_fn(
data: &StartDownloadData,
client: &mut BitsClient,
) -> Result<StartDownloadSuccess, BitsTaskError> {
let url = nsCString_to_OsString(&data.download_url, StartDownload, CommandThread)?;
let path = nsCString_to_OsString(&data.save_rel_path, StartDownload, CommandThread)?;
let (success, monitor_client) = client
.start_job(
url,
path,
data.proxy,
data.no_progress_timeout_secs,
data.update_interval_ms,
)
.map_err(|pipe_error| BitsTaskError::from_pipe(StartDownload, pipe_error))??;
Ok(StartDownloadSuccess {
guid: success.guid,
monitor_client,
})
}
fn done_fn(
_data: &StartDownloadData,
success: StartDownloadSuccess,
client_init_data: &ClientInitData,
bits_service: &BitsService,
observer: &nsIRequestObserver,
maybe_context: Option<&nsISupports>,
) -> Result<RefPtr<BitsRequest>, BitsTaskError> {
BitsRequest::new(
success.guid.clone(),
RefPtr::new(bits_service),
client_init_data.monitor_timeout_ms,
RefPtr::new(&observer),
maybe_context.map(RefPtr::new),
success.monitor_client,
ServiceAction::StartDownload,
)
}
}
struct MonitorDownloadData {
guid: Guid,
update_interval_ms: u32,
}
pub struct MonitorDownloadTask(ServiceTask<MonitorDownloadData, BitsMonitorClient>);
impl Task for MonitorDownloadTask {
fn run(&self) {
self.0.run();
}
fn done(&self) -> Result<(), nsresult> {
self.0.done()
}
}
impl MonitorDownloadTask {
pub fn new(
client_init_data: ClientInitData,
guid: Guid,
update_interval_ms: u32,
bits_service: RefPtr<BitsService>,
observer: RefPtr<nsIRequestObserver>,
context: Option<RefPtr<nsISupports>>,
callback: RefPtr<nsIBitsNewRequestCallback>,
) -> MonitorDownloadTask {
MonitorDownloadTask(ServiceTask::new(
client_init_data,
ServiceAction::MonitorDownload,
MonitorDownloadData {
guid,
update_interval_ms,
},
MonitorDownloadTask::run_fn,
MonitorDownloadTask::done_fn,
bits_service,
observer,
context,
callback,
))
}
fn run_fn(
data: &MonitorDownloadData,
client: &mut BitsClient,
) -> Result<BitsMonitorClient, BitsTaskError> {
let result = client
.monitor_job(data.guid.clone(), data.update_interval_ms)
.map_err(|pipe_error| BitsTaskError::from_pipe(MonitorDownload, pipe_error));
Ok(result??)
}
fn done_fn(
data: &MonitorDownloadData,
monitor_client: BitsMonitorClient,
client_init_data: &ClientInitData,
bits_service: &BitsService,
observer: &nsIRequestObserver,
maybe_context: Option<&nsISupports>,
) -> Result<RefPtr<BitsRequest>, BitsTaskError> {
BitsRequest::new(
data.guid.clone(),
RefPtr::new(bits_service),
client_init_data.monitor_timeout_ms,
RefPtr::new(&observer),
maybe_context.map(RefPtr::new),
monitor_client,
ServiceAction::MonitorDownload,
)
}
}