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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
// 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 https://mozilla.org/MPL/2.0/.

use std::convert::TryFrom;
use std::ffi::CStr;
use std::os::raw::c_char;
use std::panic::UnwindSafe;

use ffi_support::{define_string_destructor, ConcurrentHandleMap, FfiStr, IntoFfi};

pub use glean_core::upload::ffi_upload_result::*;
use glean_core::Glean;

mod macros;

mod boolean;
mod counter;
mod custom_distribution;
mod datetime;
mod event;
mod ffi_string_ext;
mod from_raw;
mod handlemap_ext;
mod labeled;
mod memory_distribution;
pub mod ping_type;
mod quantity;
mod string;
mod string_list;
mod timespan;
mod timing_distribution;
pub mod upload;
mod uuid;

use ffi_string_ext::FallibleToString;
use from_raw::*;
use handlemap_ext::HandleMapExtension;
use ping_type::PING_TYPES;
use upload::FfiPingUploadTask;

/// Execute the callback with a reference to the Glean singleton, returning a `Result`.
///
/// The callback returns a `Result<T, E>` while:
///
/// - Catching panics, and logging them.
/// - Converting `T` to a C-compatible type using [`IntoFfi`].
/// - Logging `E` and returning a default value.
pub(crate) fn with_glean<R, F>(callback: F) -> R::Value
where
    F: UnwindSafe + FnOnce(&Glean) -> Result<R, glean_core::Error>,
    R: IntoFfi,
{
    let mut error = ffi_support::ExternError::success();
    let res =
        ffi_support::abort_on_panic::call_with_result(
            &mut error,
            || match glean_core::global_glean() {
                Some(glean) => {
                    let glean = glean.lock().unwrap();
                    callback(&glean)
                }
                None => Err(glean_core::Error::not_initialized()),
            },
        );
    handlemap_ext::log_if_error(error);
    res
}

/// Execute the callback with a mutable reference to the Glean singleton, returning a `Result`.
///
/// The callback returns a `Result<T, E>` while:
///
/// - Catching panics, and logging them.
/// - Converting `T` to a C-compatible type using [`IntoFfi`].
/// - Logging `E` and returning a default value.
pub(crate) fn with_glean_mut<R, F>(callback: F) -> R::Value
where
    F: UnwindSafe + FnOnce(&mut Glean) -> Result<R, glean_core::Error>,
    R: IntoFfi,
{
    let mut error = ffi_support::ExternError::success();
    let res =
        ffi_support::abort_on_panic::call_with_result(
            &mut error,
            || match glean_core::global_glean() {
                Some(glean) => {
                    let mut glean = glean.lock().unwrap();
                    callback(&mut glean)
                }
                None => Err(glean_core::Error::not_initialized()),
            },
        );
    handlemap_ext::log_if_error(error);
    res
}

/// Execute the callback with a reference to the Glean singleton, returning a value.
///
/// The callback returns a value while:
///
/// - Catching panics, and logging them.
/// - Converting the returned value to a C-compatible type using [`IntoFfi`].
pub(crate) fn with_glean_value<R, F>(callback: F) -> R::Value
where
    F: UnwindSafe + FnOnce(&Glean) -> R,
    R: IntoFfi,
{
    with_glean(|glean| Ok(callback(glean)))
}

/// Execute the callback with a mutable reference to the Glean singleton, returning a value.
///
/// The callback returns a value while:
///
/// - Catching panics, and logging them.
/// - Converting the returned value to a C-compatible type using [`IntoFfi`].
pub(crate) fn with_glean_value_mut<R, F>(callback: F) -> R::Value
where
    F: UnwindSafe + FnOnce(&mut Glean) -> R,
    R: IntoFfi,
{
    with_glean_mut(|glean| Ok(callback(glean)))
}

/// Initialize the logging system based on the target platform. This ensures
/// that logging is shown when executing the Glean SDK unit tests.
#[no_mangle]
pub extern "C" fn glean_enable_logging() {
    #[cfg(target_os = "android")]
    {
        let _ = std::panic::catch_unwind(|| {
            android_logger::init_once(
                android_logger::Config::default()
                    .with_min_level(log::Level::Debug)
                    .with_tag("libglean_ffi"),
            );
            log::debug!("Android logging should be hooked up!")
        });
    }

    // On iOS enable logging with a level filter.
    #[cfg(target_os = "ios")]
    {
        // Debug logging in debug mode.
        // (Note: `debug_assertions` is the next best thing to determine if this is a debug build)
        #[cfg(debug_assertions)]
        let level = log::LevelFilter::Debug;
        #[cfg(not(debug_assertions))]
        let level = log::LevelFilter::Info;

        let mut builder = env_logger::Builder::new();
        builder.filter(None, level);
        match builder.try_init() {
            Ok(_) => log::debug!("stdout logging should be hooked up!"),
            // Please note that this is only expected to fail during unit tests,
            // where the logger might have already been initialized by a previous
            // test. So it's fine to print with the "logger".
            Err(_) => log::debug!("stdout was already initialized"),
        };
    }

    // Make sure logging does something on non Android platforms as well. Use
    // the RUST_LOG environment variable to set the desired log level, e.g.
    // setting RUST_LOG=debug sets the log level to debug.
    #[cfg(all(not(target_os = "android"), not(target_os = "ios")))]
    {
        match env_logger::try_init() {
            Ok(_) => log::debug!("stdout logging should be hooked up!"),
            // Please note that this is only expected to fail during unit tests,
            // where the logger might have already been initialized by a previous
            // test. So it's fine to print with the "logger".
            Err(_) => log::debug!("stdout was already initialized"),
        };
    }
}

/// Configuration over FFI.
///
/// **CAUTION**: This must match _exactly_ the definition on the Kotlin side.
/// If this side is changed, the Kotlin side need to be changed, too.
#[repr(C)]
pub struct FfiConfiguration<'a> {
    pub data_dir: FfiStr<'a>,
    pub package_name: FfiStr<'a>,
    pub upload_enabled: u8,
    pub max_events: Option<&'a i32>,
    pub delay_ping_lifetime_io: u8,
}

/// Convert the FFI-compatible configuration object into the proper Rust configuration object.
impl TryFrom<&FfiConfiguration<'_>> for glean_core::Configuration {
    type Error = glean_core::Error;

    fn try_from(cfg: &FfiConfiguration) -> Result<Self, Self::Error> {
        let data_path = cfg.data_dir.to_string_fallible()?;
        let application_id = cfg.package_name.to_string_fallible()?;
        let upload_enabled = cfg.upload_enabled != 0;
        let max_events = cfg.max_events.filter(|&&i| i >= 0).map(|m| *m as usize);
        let delay_ping_lifetime_io = cfg.delay_ping_lifetime_io != 0;

        Ok(Self {
            upload_enabled,
            data_path,
            application_id,
            max_events,
            delay_ping_lifetime_io,
        })
    }
}

/// # Safety
///
/// A valid and non-null configuration object is required for this function.
#[no_mangle]
pub unsafe extern "C" fn glean_initialize(cfg: *const FfiConfiguration) -> u8 {
    assert!(!cfg.is_null());

    handlemap_ext::handle_result(|| {
        // We can create a reference to the FfiConfiguration struct:
        // 1. We did a null check
        // 2. We're not holding on to it beyond this function
        //    and we copy out all data when needed.
        let glean_cfg = glean_core::Configuration::try_from(&*cfg)?;
        let glean = Glean::new(glean_cfg)?;
        glean_core::setup_glean(glean)?;
        log::info!("Glean initialized");
        Ok(true)
    })
}

#[no_mangle]
pub extern "C" fn glean_on_ready_to_submit_pings() -> u8 {
    with_glean_value(|glean| glean.on_ready_to_submit_pings())
}

#[no_mangle]
pub extern "C" fn glean_is_upload_enabled() -> u8 {
    with_glean_value(|glean| glean.is_upload_enabled())
}

#[no_mangle]
pub extern "C" fn glean_set_upload_enabled(flag: u8) {
    with_glean_value_mut(|glean| glean.set_upload_enabled(flag != 0));
    // The return value of set_upload_enabled is an implementation detail
    // that isn't exposed over FFI.
}

#[no_mangle]
pub extern "C" fn glean_submit_ping_by_name(ping_name: FfiStr, reason: FfiStr) -> u8 {
    with_glean(|glean| {
        Ok(glean
            .submit_ping_by_name(&ping_name.to_string_fallible()?, reason.as_opt_str())
            .unwrap_or(false))
    })
}

#[no_mangle]
pub extern "C" fn glean_ping_collect(ping_type_handle: u64, reason: FfiStr) -> *mut c_char {
    with_glean_value(|glean| {
        PING_TYPES.call_infallible(ping_type_handle, |ping_type| {
            let ping_maker = glean_core::ping::PingMaker::new();
            let data = ping_maker
                .collect_string(glean, ping_type, reason.as_opt_str())
                .unwrap_or_else(|| String::from(""));
            log::info!("Ping({}): {}", ping_type.name.as_str(), data);
            data
        })
    })
}

#[no_mangle]
pub extern "C" fn glean_set_experiment_active(
    experiment_id: FfiStr,
    branch: FfiStr,
    extra_keys: RawStringArray,
    extra_values: RawStringArray,
    extra_len: i32,
) {
    with_glean(|glean| {
        let experiment_id = experiment_id.to_string_fallible()?;
        let branch = branch.to_string_fallible()?;
        let extra = from_raw_string_array_and_string_array(extra_keys, extra_values, extra_len)?;

        glean.set_experiment_active(experiment_id, branch, extra);
        Ok(())
    })
}

#[no_mangle]
pub extern "C" fn glean_set_experiment_inactive(experiment_id: FfiStr) {
    with_glean(|glean| {
        let experiment_id = experiment_id.to_string_fallible()?;
        glean.set_experiment_inactive(experiment_id);
        Ok(())
    })
}

#[no_mangle]
pub extern "C" fn glean_experiment_test_is_active(experiment_id: FfiStr) -> u8 {
    with_glean(|glean| {
        let experiment_id = experiment_id.to_string_fallible()?;
        Ok(glean.test_is_experiment_active(experiment_id))
    })
}

#[no_mangle]
pub extern "C" fn glean_experiment_test_get_data(experiment_id: FfiStr) -> *mut c_char {
    with_glean(|glean| {
        let experiment_id = experiment_id.to_string_fallible()?;
        Ok(glean.test_get_experiment_data_as_json(experiment_id))
    })
}

#[no_mangle]
pub extern "C" fn glean_clear_application_lifetime_metrics() {
    with_glean_value(|glean| glean.clear_application_lifetime_metrics());
}

#[no_mangle]
pub extern "C" fn glean_set_dirty_flag(flag: u8) {
    with_glean_value_mut(|glean| glean.set_dirty_flag(flag != 0));
}

#[no_mangle]
pub extern "C" fn glean_is_dirty_flag_set() -> u8 {
    with_glean_value(|glean| glean.is_dirty_flag_set())
}

#[no_mangle]
pub extern "C" fn glean_test_clear_all_stores() {
    with_glean_value(|glean| glean.test_clear_all_stores())
}

#[no_mangle]
pub extern "C" fn glean_destroy_glean() {
    with_glean_value_mut(|glean| glean.destroy_db())
}

#[no_mangle]
pub extern "C" fn glean_is_first_run() -> u8 {
    with_glean_value(|glean| glean.is_first_run())
}

#[no_mangle]
pub extern "C" fn glean_get_upload_task() -> FfiPingUploadTask {
    with_glean_value(|glean| FfiPingUploadTask::from(glean.get_upload_task()))
}

// We need to pass the whole task instead of only the document id,
// so that we can free the strings properly on Drop.
#[no_mangle]
pub extern "C" fn glean_process_ping_upload_response(task: FfiPingUploadTask, status: u32) {
    with_glean(|glean| {
        if let FfiPingUploadTask::Upload { document_id, .. } = task {
            assert!(!document_id.is_null());
            let document_id_str = unsafe {
                CStr::from_ptr(document_id)
                    .to_str()
                    .map_err(|_| glean_core::Error::utf8_error())
            }?;
            glean.process_ping_upload_response(document_id_str, status.into());
        };
        Ok(())
    });
}

define_string_destructor!(glean_str_free);