tauri-plugin-background-service 0.5.3

Background service lifecycle plugin for Tauri v2 — run long-lived tasks on Android, iOS, and desktop
Documentation
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! Setup validation for background service prerequisites.
//!
//! [`SetupValidator`] checks platform-specific prerequisites (permissions,
//! manifest entries, service manager availability) and returns a
//! [`SetupValidationReport`] with errors (blocking) and warnings (non-blocking).
//!
//! This module is available on all platforms. Platform-specific checks are
//! gated by `cfg` attributes so they only run on the target platform.

use crate::models::{Platform, SetupIssue, SetupValidationReport};

/// Validates background service setup prerequisites for the current platform.
///
/// Returns a [`SetupValidationReport`] containing errors (blocking issues that
/// prevent the service from working) and warnings (non-blocking issues that
/// may cause degraded behavior).
pub struct SetupValidator;

impl SetupValidator {
    /// Run all applicable checks for the current platform.
    ///
    /// The `platform` parameter is typically obtained from
    /// [`crate::capabilities::CapabilityProvider::detect_platform`].
    pub fn validate(platform: Platform) -> SetupValidationReport {
        match platform {
            Platform::Android => Self::android_checks(),
            Platform::Ios => Self::ios_checks(),
            Platform::Linux | Platform::Macos | Platform::Windows | Platform::Unknown => {
                Self::desktop_checks(platform)
            }
        }
    }

    fn android_checks() -> SetupValidationReport {
        let warnings = vec![
            SetupIssue {
                code: "android_fgs_type".into(),
                message: "Ensure the foreground service type is declared in AndroidManifest.xml \
                          with the matching permission"
                    .into(),
                platform: Platform::Android,
                fix: Some(
                    "Add <foregroundServiceType> to your <service> element and the \
                     corresponding <uses-permission> to the manifest"
                        .into(),
                ),
            },
            SetupIssue {
                code: "android_post_notifications".into(),
                message: "Android 13+ requires POST_NOTIFICATIONS runtime permission for \
                          foreground service notifications"
                    .into(),
                platform: Platform::Android,
                fix: Some(
                    "Request android.permission.POST_NOTIFICATIONS at runtime before \
                     starting the service on Android 13+"
                        .into(),
                ),
            },
            SetupIssue {
                code: "android_boot_receiver".into(),
                message: "Boot recovery requires a registered BroadcastReceiver for \
                          BOOT_COMPLETED"
                    .into(),
                platform: Platform::Android,
                fix: Some(
                    "Add RECEIVE_BOOT_COMPLETED permission and a <receiver> element for \
                     BOOT_COMPLETED in AndroidManifest.xml"
                        .into(),
                ),
            },
            SetupIssue {
                code: "android_special_use_subtype".into(),
                message: "When using specialUse FGS type, PROPERTY_SPECIAL_USE_FGS_SUBTYPE \
                          must be declared in the manifest"
                    .into(),
                platform: Platform::Android,
                fix: Some(
                    "Add <property android:name=\"android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE\" \
                     android:value=\"your_reason\" /> to the <service> element"
                        .into(),
                ),
            },
        ];

        SetupValidationReport {
            ok: true,
            errors: vec![],
            warnings,
        }
    }

    fn ios_checks() -> SetupValidationReport {
        let warnings = vec![
            SetupIssue {
                code: "ios_ui_background_modes".into(),
                message: "UIBackgroundModes must include 'background-fetch' and \
                          'background-processing' in Info.plist"
                    .into(),
                platform: Platform::Ios,
                fix: Some(
                    "Add UIBackgroundModes array with 'background-fetch' and \
                     'background-processing' to Info.plist"
                        .into(),
                ),
            },
            SetupIssue {
                code: "ios_bg_task_identifiers".into(),
                message: "BGTaskSchedulerPermittedIdentifiers must list your task \
                          identifiers in Info.plist"
                    .into(),
                platform: Platform::Ios,
                fix: Some(
                    "Add BGTaskSchedulerPermittedIdentifiers array with \
                     '$(BUNDLE_ID).bg-refresh' and '$(BUNDLE_ID).bg-processing' to Info.plist"
                        .into(),
                ),
            },
            SetupIssue {
                code: "ios_background_refresh".into(),
                message: "Background App Refresh must be enabled in iOS Settings for \
                          BGTaskScheduler to work"
                    .into(),
                platform: Platform::Ios,
                fix: Some(
                    "Instruct users to enable Background App Refresh in Settings > General > \
                     Background App Refresh"
                        .into(),
                ),
            },
        ];

        SetupValidationReport {
            ok: true,
            errors: vec![],
            warnings,
        }
    }

    #[allow(unused_mut)]
    fn desktop_checks(platform: Platform) -> SetupValidationReport {
        let mut errors: Vec<SetupIssue> = vec![];
        let mut warnings: Vec<SetupIssue> = vec![];

        #[cfg(feature = "desktop-service")]
        {
            if matches!(platform, Platform::Linux) {
                let systemctl = std::path::Path::new("/usr/bin/systemctl").exists()
                    || std::path::Path::new("/bin/systemctl").exists()
                    || which_exists("systemctl");

                if !systemctl {
                    errors.push(SetupIssue {
                        code: "desktop_systemd_missing".into(),
                        message: "systemctl not found — OS service mode requires systemd".into(),
                        platform: Platform::Linux,
                        fix: Some("Install systemd or use inProcess mode".into()),
                    });
                } else {
                    let uid = unsafe { libc::getuid() };
                    let linger_path = format!("/var/lib/systemd/linger/{uid}");
                    let linger_ok = std::path::Path::new(&linger_path).exists()
                        || std::env::var("USER")
                            .ok()
                            .map(|u| {
                                std::path::Path::new(&format!("/var/lib/systemd/linger/{u}"))
                                    .exists()
                            })
                            .unwrap_or(false);

                    if !linger_ok {
                        warnings.push(SetupIssue {
                            code: "desktop_systemd_no_linger".into(),
                            message: "systemd lingering is not enabled — user services \
                                      will stop when you log out"
                                .into(),
                            platform: Platform::Linux,
                            fix: Some(
                                "Run 'loginctl enable-linger' to keep user services alive \
                                 after logout"
                                    .into(),
                            ),
                        });
                    }
                }
            }

            if matches!(platform, Platform::Macos) {
                warnings.push(SetupIssue {
                    code: "desktop_macos_sandbox".into(),
                    message: "OS service mode is incompatible with macOS App Sandbox. \
                              Ensure your app is not sandboxed or use inProcess mode"
                        .into(),
                    platform: Platform::Macos,
                    fix: Some(
                        "Disable App Sandbox in your app's entitlements, or use \
                         desktopServiceMode: 'inProcess'"
                            .into(),
                    ),
                });
            }
        }

        #[cfg(not(feature = "desktop-service"))]
        {
            let _ = platform;
        }

        SetupValidationReport {
            ok: errors.is_empty(),
            errors,
            warnings,
        }
    }
}

/// Check if a command exists in PATH.
#[cfg(feature = "desktop-service")]
fn which_exists(cmd: &str) -> bool {
    std::process::Command::new("which")
        .arg(cmd)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn android_returns_no_errors() {
        let report = SetupValidator::validate(Platform::Android);
        assert!(
            report.errors.is_empty(),
            "Android should have no hard errors (checks happen at build/Kotlin level)"
        );
        assert!(!report.warnings.is_empty(), "Android should have warnings");
        assert!(report.ok, "ok should be true when errors is empty");
    }

    #[test]
    fn android_has_fgs_type_warning() {
        let report = SetupValidator::validate(Platform::Android);
        let codes: Vec<&str> = report.warnings.iter().map(|w| w.code.as_str()).collect();
        assert!(
            codes.contains(&"android_fgs_type"),
            "Should warn about FGS type: {codes:?}"
        );
    }

    #[test]
    fn android_has_post_notifications_warning() {
        let report = SetupValidator::validate(Platform::Android);
        let codes: Vec<&str> = report.warnings.iter().map(|w| w.code.as_str()).collect();
        assert!(
            codes.contains(&"android_post_notifications"),
            "Should warn about POST_NOTIFICATIONS: {codes:?}"
        );
    }

    #[test]
    fn android_has_boot_receiver_warning() {
        let report = SetupValidator::validate(Platform::Android);
        let codes: Vec<&str> = report.warnings.iter().map(|w| w.code.as_str()).collect();
        assert!(
            codes.contains(&"android_boot_receiver"),
            "Should warn about boot receiver: {codes:?}"
        );
    }

    #[test]
    fn android_has_special_use_subtype_warning() {
        let report = SetupValidator::validate(Platform::Android);
        let codes: Vec<&str> = report.warnings.iter().map(|w| w.code.as_str()).collect();
        assert!(
            codes.contains(&"android_special_use_subtype"),
            "Should warn about specialUse subtype: {codes:?}"
        );
    }

    #[test]
    fn android_all_warnings_have_fix() {
        let report = SetupValidator::validate(Platform::Android);
        for w in &report.warnings {
            assert!(
                w.fix.is_some(),
                "Warning '{}' should have a fix suggestion",
                w.code
            );
        }
    }

    #[test]
    fn android_all_warnings_are_android_platform() {
        let report = SetupValidator::validate(Platform::Android);
        for w in &report.warnings {
            assert_eq!(
                w.platform,
                Platform::Android,
                "Warning '{}' should be Android platform",
                w.code
            );
        }
    }

    #[test]
    fn ios_returns_no_errors() {
        let report = SetupValidator::validate(Platform::Ios);
        assert!(
            report.errors.is_empty(),
            "iOS should have no hard errors (checks happen at build/Swift level)"
        );
        assert!(!report.warnings.is_empty(), "iOS should have warnings");
        assert!(report.ok, "ok should be true when errors is empty");
    }

    #[test]
    fn ios_has_background_modes_warning() {
        let report = SetupValidator::validate(Platform::Ios);
        let codes: Vec<&str> = report.warnings.iter().map(|w| w.code.as_str()).collect();
        assert!(
            codes.contains(&"ios_ui_background_modes"),
            "Should warn about UIBackgroundModes: {codes:?}"
        );
    }

    #[test]
    fn ios_has_task_identifiers_warning() {
        let report = SetupValidator::validate(Platform::Ios);
        let codes: Vec<&str> = report.warnings.iter().map(|w| w.code.as_str()).collect();
        assert!(
            codes.contains(&"ios_bg_task_identifiers"),
            "Should warn about BGTaskSchedulerPermittedIdentifiers: {codes:?}"
        );
    }

    #[test]
    fn ios_has_background_refresh_warning() {
        let report = SetupValidator::validate(Platform::Ios);
        let codes: Vec<&str> = report.warnings.iter().map(|w| w.code.as_str()).collect();
        assert!(
            codes.contains(&"ios_background_refresh"),
            "Should warn about background refresh: {codes:?}"
        );
    }

    #[test]
    fn ios_all_warnings_have_fix() {
        let report = SetupValidator::validate(Platform::Ios);
        for w in &report.warnings {
            assert!(
                w.fix.is_some(),
                "Warning '{}' should have a fix suggestion",
                w.code
            );
        }
    }

    #[test]
    fn ios_all_warnings_are_ios_platform() {
        let report = SetupValidator::validate(Platform::Ios);
        for w in &report.warnings {
            assert_eq!(
                w.platform,
                Platform::Ios,
                "Warning '{}' should be iOS platform",
                w.code
            );
        }
    }

    #[test]
    fn desktop_linux_no_errors_by_default() {
        let report = SetupValidator::validate(Platform::Linux);
        assert!(
            report.ok || !report.errors.is_empty(),
            "Report should be consistent: ok == errors.is_empty()"
        );
        assert_eq!(report.ok, report.errors.is_empty());
    }

    #[test]
    fn desktop_macos_no_errors_by_default() {
        let report = SetupValidator::validate(Platform::Macos);
        assert_eq!(report.ok, report.errors.is_empty());
    }

    #[test]
    fn desktop_windows_no_errors() {
        let report = SetupValidator::validate(Platform::Windows);
        assert!(
            report.errors.is_empty(),
            "Windows should have no desktop-service errors (not yet supported)"
        );
        assert!(report.ok);
    }

    #[test]
    fn desktop_unknown_no_errors() {
        let report = SetupValidator::validate(Platform::Unknown);
        assert!(report.errors.is_empty());
        assert!(report.ok);
    }

    #[test]
    fn all_issues_have_non_empty_message() {
        for platform in [
            Platform::Android,
            Platform::Ios,
            Platform::Linux,
            Platform::Macos,
            Platform::Windows,
        ] {
            let report = SetupValidator::validate(platform);
            for issue in report.errors.iter().chain(report.warnings.iter()) {
                assert!(
                    !issue.message.is_empty(),
                    "Issue '{}' on {:?} should have a non-empty message",
                    issue.code,
                    platform
                );
                assert!(
                    !issue.code.is_empty(),
                    "Found an issue with an empty code on {:?}",
                    platform
                );
            }
        }
    }

    #[test]
    fn setup_issue_serde_roundtrip() {
        let issue = SetupIssue {
            code: "test_code".into(),
            message: "Test message".into(),
            platform: Platform::Android,
            fix: Some("Do something".into()),
        };
        let json = serde_json::to_string(&issue).unwrap();
        let de: SetupIssue = serde_json::from_str(&json).unwrap();
        assert_eq!(de.code, "test_code");
        assert_eq!(de.message, "Test message");
        assert_eq!(de.platform, Platform::Android);
        assert_eq!(de.fix, Some("Do something".into()));
    }

    #[test]
    fn setup_issue_json_keys_camel_case() {
        let issue = SetupIssue {
            code: "c".into(),
            message: "m".into(),
            platform: Platform::Linux,
            fix: Some("f".into()),
        };
        let json = serde_json::to_string(&issue).unwrap();
        assert!(json.contains("\"code\":"), "{json}");
        assert!(json.contains("\"message\":"), "{json}");
        assert!(json.contains("\"platform\":"), "{json}");
        assert!(json.contains("\"fix\":"), "{json}");
    }

    #[test]
    fn setup_issue_fix_absent_when_none() {
        let issue = SetupIssue {
            code: "c".into(),
            message: "m".into(),
            platform: Platform::Linux,
            fix: None,
        };
        let json = serde_json::to_string(&issue).unwrap();
        assert!(
            !json.contains("\"fix\""),
            "fix should be absent when None: {json}"
        );
    }

    #[test]
    fn setup_validation_report_serde_roundtrip() {
        let report = SetupValidationReport {
            ok: true,
            errors: vec![],
            warnings: vec![SetupIssue {
                code: "w1".into(),
                message: "Warning 1".into(),
                platform: Platform::Android,
                fix: Some("Fix it".into()),
            }],
        };
        let json = serde_json::to_string(&report).unwrap();
        let de: SetupValidationReport = serde_json::from_str(&json).unwrap();
        assert!(de.ok);
        assert!(de.errors.is_empty());
        assert_eq!(de.warnings.len(), 1);
        assert_eq!(de.warnings[0].code, "w1");
    }

    #[test]
    fn setup_validation_report_json_keys_camel_case() {
        let report = SetupValidationReport {
            ok: false,
            errors: vec![SetupIssue {
                code: "e1".into(),
                message: "Error".into(),
                platform: Platform::Ios,
                fix: None,
            }],
            warnings: vec![],
        };
        let json = serde_json::to_string(&report).unwrap();
        assert!(json.contains("\"ok\":"), "{json}");
        assert!(json.contains("\"errors\":"), "{json}");
        assert!(json.contains("\"warnings\":"), "{json}");
    }

    #[test]
    fn setup_validation_report_ok_true_when_no_errors() {
        let report = SetupValidationReport {
            ok: true,
            errors: vec![],
            warnings: vec![SetupIssue {
                code: "w".into(),
                message: "warn".into(),
                platform: Platform::Linux,
                fix: None,
            }],
        };
        assert!(report.ok);
    }

    #[test]
    fn setup_validation_report_ok_false_with_errors() {
        let report = SetupValidationReport {
            ok: false,
            errors: vec![SetupIssue {
                code: "e".into(),
                message: "err".into(),
                platform: Platform::Linux,
                fix: None,
            }],
            warnings: vec![],
        };
        assert!(!report.ok);
    }

    #[cfg(feature = "desktop-service")]
    #[test]
    fn which_exists_true_for_ls() {
        assert!(which_exists("ls"), "ls should exist in PATH");
    }

    #[cfg(feature = "desktop-service")]
    #[test]
    fn which_exists_false_for_nonsense() {
        assert!(
            !which_exists("definitely_not_a_real_command_xyz_123"),
            "nonsense command should not exist"
        );
    }

    #[test]
    fn android_error_prevents_ok() {
        let report = SetupValidationReport {
            ok: false,
            errors: vec![SetupIssue {
                code: "test_error".into(),
                message: "test".into(),
                platform: Platform::Android,
                fix: None,
            }],
            warnings: vec![],
        };
        assert!(!report.ok);
        assert_eq!(report.errors.len(), 1);
    }

    #[test]
    fn warnings_do_not_affect_ok() {
        let report = SetupValidationReport {
            ok: true,
            errors: vec![],
            warnings: vec![SetupIssue {
                code: "w".into(),
                message: "just a warning".into(),
                platform: Platform::Linux,
                fix: None,
            }],
        };
        assert!(report.ok);
        assert!(!report.warnings.is_empty());
    }
}