Debian Codegraph @

third_party/rust/glean/src/net/mod.rs

raw
1 // This Source Code Form is subject to the terms of the Mozilla Public
2 // License, v. 2.0. If a copy of the MPL was not distributed with this
3 // file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5 //! Handling the Glean upload logic.
6 //!
7 //! This doesn't perform the actual upload but rather handles
8 //! retries, upload limitations and error tracking.
9
10 use crossbeam_channel::{Receiver, Sender};
11 use std::sync::{atomic::Ordering, Arc, Mutex};
12 use std::thread::{self, JoinHandle};
13 use std::time::Duration;
14
15 use glean_core::upload::PingUploadTask;
16 pub use glean_core::upload::{PingRequest, UploadResult, UploadTaskAction};
17
18 pub use http_uploader::*;
19 use thread_state::{AtomicState, State};
20
21 mod http_uploader;
22
23 /// Everything you need to request a ping to be uploaded.
24 pub struct PingUploadRequest {
25 /// The URL the Glean SDK expects you to use to upload the ping.
26 pub url: String,
27 /// The body, already content-encoded, for upload.
28 pub body: Vec<u8>,
29 /// The HTTP headers, including any Content-Encoding.
30 pub headers: Vec<(String, String)>,
31 /// Whether the body has {client|ping}_info sections in it.
32 pub body_has_info_sections: bool,
33 /// The name (aka doctype) of the ping.
34 pub ping_name: String,
35 }
36
37 /// A PingUploadRequest requiring proof of uploader capability.
38 pub struct CapablePingUploadRequest {
39 request: PingUploadRequest,
40 capabilities: Vec<String>,
41 }
42
43 impl CapablePingUploadRequest {
44 /// If you are capable of satisfying this ping upload request's capabilities,
45 /// obtain the PingUploadRequest.
46 pub fn capable<F>(self, func: F) -> Option<PingUploadRequest>
47 where
48 F: FnOnce(Vec<String>) -> bool,
49 {
50 if func(self.capabilities) {
51 return Some(self.request);
52 }
53 None
54 }
55 }
56
57 /// A description of a component used to upload pings.
58 pub trait PingUploader: std::fmt::Debug + Send + Sync {
59 /// Uploads a ping to a server.
60 ///
61 /// # Arguments
62 ///
63 /// * `url` - the URL path to upload the data to.
64 /// * `body` - the serialized text data to send.
65 /// * `headers` - a vector of tuples containing the headers to send with
66 /// the request, i.e. (Name, Value).
67 fn upload(&self, upload_request: CapablePingUploadRequest) -> UploadResult;
68 }
69
70 /// The logic for uploading pings: this leaves the actual upload mechanism as
71 /// a detail of the user-provided object implementing [`PingUploader`].
72 #[derive(Debug)]
73 pub(crate) struct UploadManager {
74 inner: Arc<Inner>,
75 }
76
77 #[derive(Debug)]
78 struct Inner {
79 server_endpoint: String,
80 uploader: Box<dyn PingUploader + 'static>,
81 thread_running: AtomicState,
82 handle: Mutex<Option<JoinHandle<()>>>,
83 rx: Receiver<()>,
84 tx: Sender<()>,
85 }
86
87 impl UploadManager {
88 /// Create a new instance of the upload manager.
89 ///
90 /// # Arguments
91 ///
92 /// * `server_endpoint` - the server pings are sent to.
93 /// * `new_uploader` - the instance of the uploader used to send pings.
94 pub(crate) fn new(
95 server_endpoint: String,
96 new_uploader: Box<dyn PingUploader + 'static>,
97 ) -> Self {
98 let (tx, rx) = crossbeam_channel::bounded(1);
99 Self {
100 inner: Arc::new(Inner {
101 server_endpoint,
102 uploader: new_uploader,
103 thread_running: AtomicState::new(State::Stopped),
104 handle: Mutex::new(None),
105 rx,
106 tx,
107 }),
108 }
109 }
110
111 /// Signals Glean to upload pings at the next best opportunity.
112 pub(crate) fn trigger_upload(&self) {
113 // If no other upload proces is running, we're the one starting it.
114 // Need atomic compare/exchange to avoid any further races
115 // or we can end up with 2+ uploader threads.
116 if self
117 .inner
118 .thread_running
119 .compare_exchange(
120 State::Stopped,
121 State::Running,
122 Ordering::SeqCst,
123 Ordering::SeqCst,
124 )
125 .is_err()
126 {
127 return;
128 }
129
130 let inner = Arc::clone(&self.inner);
131
132 // Need to lock before we start so that noone thinks we're not running.
133 let mut handle = self.inner.handle.lock().unwrap();
134 let thread = thread::Builder::new()
135 .name("glean.upload".into())
136 .spawn(move || {
137 log::trace!("Started glean.upload thread");
138 loop {
139 let incoming_task = glean_core::glean_get_upload_task();
140
141 match incoming_task {
142 PingUploadTask::Upload { request } => {
143 log::trace!("Received upload task with request {:?}", request);
144 let doc_id = request.document_id.clone();
145 let upload_url = format!("{}{}", inner.server_endpoint, request.path);
146 let headers: Vec<(String, String)> =
147 request.headers.into_iter().collect();
148 let upload_request = PingUploadRequest {
149 url: upload_url,
150 body: request.body,
151 headers,
152 body_has_info_sections: request.body_has_info_sections,
153 ping_name: request.ping_name,
154 };
155 let upload_request = CapablePingUploadRequest {
156 request: upload_request,
157 capabilities: request.uploader_capabilities,
158 };
159 let result = inner.uploader.upload(upload_request);
160 // Process the upload response.
161 match glean_core::glean_process_ping_upload_response(doc_id, result) {
162 UploadTaskAction::Next => (),
163 UploadTaskAction::End => break,
164 }
165
166 let status = inner.thread_running.load(Ordering::SeqCst);
167 // asked to shut down. let's do it.
168 if status == State::ShuttingDown {
169 break;
170 }
171 }
172 PingUploadTask::Wait { time } => {
173 log::trace!("Instructed to wait for {:?}ms", time);
174 let _ = inner.rx.recv_timeout(Duration::from_millis(time));
175
176 let status = inner.thread_running.load(Ordering::SeqCst);
177 // asked to shut down. let's do it.
178 if status == State::ShuttingDown {
179 break;
180 }
181 }
182 PingUploadTask::Done { .. } => {
183 log::trace!("Received PingUploadTask::Done. Exiting.");
184 // Nothing to do here, break out of the loop.
185 break;
186 }
187 }
188 }
189
190 // Clear the running flag to signal that this thread is done,
191 // but only if there's no shutdown thread.
192 let _ = inner.thread_running.compare_exchange(
193 State::Running,
194 State::Stopped,
195 Ordering::SeqCst,
196 Ordering::SeqCst,
197 );
198 });
199
200 match thread {
201 Ok(thread) => *handle = Some(thread),
202 Err(err) => {
203 log::warn!("Failed to spawn Glean's uploader thread. This will be retried on next upload. Error: {err}");
204 // Swapping back the thread state. We're the ones setting it to `Running`, so
205 // should be able to set it back.
206 let state_change = self.inner.thread_running.compare_exchange(
207 State::Running,
208 State::Stopped,
209 Ordering::SeqCst,
210 Ordering::SeqCst,
211 );
212
213 if state_change.is_err() {
214 log::warn!("Failed to swap back thread state. Someone else jumped in and changed the state.");
215 }
216 }
217 };
218 }
219
220 pub(crate) fn shutdown(&self) {
221 // mark as shutting down.
222 self.inner
223 .thread_running
224 .store(State::ShuttingDown, Ordering::SeqCst);
225
226 // take the thread handle out.
227 let mut handle = self.inner.handle.lock().unwrap();
228 let thread = handle.take();
229
230 if let Some(thread) = thread {
231 // poke the thread in case it's in `Wait`.
232 let _ = self.inner.tx.send(());
233
234 thread
235 .join()
236 .expect("couldn't join on the uploader thread.");
237 }
238 }
239 }
240
241 mod thread_state {
242 use std::sync::atomic::{AtomicU8, Ordering};
243
244 #[derive(Debug, PartialEq)]
245 #[repr(u8)]
246 pub enum State {
247 Stopped = 0,
248 Running = 1,
249 ShuttingDown = 2,
250 }
251
252 #[derive(Debug)]
253 pub struct AtomicState(AtomicU8);
254
255 impl AtomicState {
256 const fn to_u8(val: State) -> u8 {
257 val as u8
258 }
259
260 fn from_u8(val: u8) -> State {
261 #![allow(non_upper_case_globals)]
262 const U8_Stopped: u8 = State::Stopped as u8;
263 const U8_Running: u8 = State::Running as u8;
264 const U8_ShuttingDown: u8 = State::ShuttingDown as u8;
265 match val {
266 U8_Stopped => State::Stopped,
267 U8_Running => State::Running,
268 U8_ShuttingDown => State::ShuttingDown,
269 _ => panic!("Invalid enum discriminant"),
270 }
271 }
272
273 pub const fn new(v: State) -> AtomicState {
274 AtomicState(AtomicU8::new(Self::to_u8(v)))
275 }
276
277 pub fn load(&self, order: Ordering) -> State {
278 Self::from_u8(self.0.load(order))
279 }
280
281 pub fn store(&self, val: State, order: Ordering) {
282 self.0.store(Self::to_u8(val), order)
283 }
284
285 pub fn compare_exchange(
286 &self,
287 current: State,
288 new: State,
289 success: Ordering,
290 failure: Ordering,
291 ) -> Result<State, State> {
292 self.0
293 .compare_exchange(Self::to_u8(current), Self::to_u8(new), success, failure)
294 .map(Self::from_u8)
295 .map_err(Self::from_u8)
296 }
297 }
298 }