Skip to main content

lingxia_provider/
lib.rs

1use std::future::Future;
2use std::pin::Pin;
3
4/// Boxed future type for dyn compatibility.
5pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
6
7/// Error type for provider operations.
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum ProviderErrorCode {
10    InvalidRequest,
11    NotFound,
12    Network,
13    Timeout,
14    Server,
15    PermissionDenied,
16    Internal,
17}
18
19impl ProviderErrorCode {
20    pub const fn biz_code(self) -> u32 {
21        match self {
22            Self::InvalidRequest => 1002,
23            Self::NotFound => 1003,
24            Self::Network => 5001,
25            Self::Timeout => 5002,
26            Self::Server => 5003,
27            Self::PermissionDenied => 3000,
28            Self::Internal => 1005,
29        }
30    }
31
32    pub const fn as_str(self) -> &'static str {
33        match self {
34            Self::InvalidRequest => "invalid_request",
35            Self::NotFound => "not_found",
36            Self::Network => "network",
37            Self::Timeout => "timeout",
38            Self::Server => "server",
39            Self::PermissionDenied => "permission_denied",
40            Self::Internal => "internal",
41        }
42    }
43}
44
45#[derive(Debug, Clone)]
46pub struct ProviderError {
47    code: ProviderErrorCode,
48    detail: String,
49}
50
51impl ProviderError {
52    pub fn new(code: ProviderErrorCode, detail: impl Into<String>) -> Self {
53        Self {
54            code,
55            detail: detail.into(),
56        }
57    }
58
59    pub fn invalid_request(detail: impl Into<String>) -> Self {
60        Self::new(ProviderErrorCode::InvalidRequest, detail)
61    }
62
63    pub fn not_found(detail: impl Into<String>) -> Self {
64        Self::new(ProviderErrorCode::NotFound, detail)
65    }
66
67    pub fn network(detail: impl Into<String>) -> Self {
68        Self::new(ProviderErrorCode::Network, detail)
69    }
70
71    pub fn timeout(detail: impl Into<String>) -> Self {
72        Self::new(ProviderErrorCode::Timeout, detail)
73    }
74
75    pub fn server(detail: impl Into<String>) -> Self {
76        Self::new(ProviderErrorCode::Server, detail)
77    }
78
79    pub fn permission_denied(detail: impl Into<String>) -> Self {
80        Self::new(ProviderErrorCode::PermissionDenied, detail)
81    }
82
83    pub fn internal(detail: impl Into<String>) -> Self {
84        Self::new(ProviderErrorCode::Internal, detail)
85    }
86
87    pub const fn code(&self) -> ProviderErrorCode {
88        self.code
89    }
90
91    pub const fn biz_code(&self) -> u32 {
92        self.code.biz_code()
93    }
94
95    pub fn detail(&self) -> &str {
96        &self.detail
97    }
98}
99
100impl std::fmt::Display for ProviderError {
101    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102        write!(f, "[{}] {}", self.code.as_str(), self.detail)
103    }
104}
105
106impl std::error::Error for ProviderError {}
107
108/// Error type for fingerprint operations.
109#[derive(Debug, Clone, Copy, PartialEq, Eq)]
110pub enum FingerprintError {
111    /// Device ID cannot be loaded/generated on current runtime.
112    DeviceIdUnavailable,
113}
114
115impl std::fmt::Display for FingerprintError {
116    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117        match self {
118            Self::DeviceIdUnavailable => write!(f, "device_id_unavailable"),
119        }
120    }
121}
122
123impl std::error::Error for FingerprintError {}
124
125/// Trait for device fingerprint.
126pub trait FingerprintProvider: Send + Sync + 'static {
127    /// Get the device fingerprint ID.
128    fn get_fingerprint(&self) -> Result<String, FingerprintError> {
129        Err(FingerprintError::DeviceIdUnavailable)
130    }
131}
132
133/// Trait for push token binding.
134pub trait PushNotificationProvider: Send + Sync + 'static {
135    /// Bind push token to cloud side.
136    fn bind_push_token<'a>(&'a self, _token: String) -> BoxFuture<'a, Result<(), ProviderError>> {
137        Box::pin(async { Ok(()) })
138    }
139}
140
141/// Server-owned lifecycle state of an lxapp.
142#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
143pub enum LxAppStatus {
144    /// The registry reported nothing for this app — an older server, an app it
145    /// does not know, or a check that never reached it.
146    #[default]
147    Unknown,
148    Published,
149    /// Temporarily unavailable while the operator works on it. Must not open,
150    /// but says something different to the user than `Suspended` does: one is
151    /// "come back later", the other is "this is not yours to open".
152    Maintain,
153    /// No longer offered. An already-installed copy keeps working.
154    Delisted,
155    /// Blocked by the operator. Must not open, installed or not.
156    Suspended,
157}
158
159impl LxAppStatus {
160    pub const fn as_str(self) -> &'static str {
161        match self {
162            Self::Unknown => "unknown",
163            Self::Published => "published",
164            Self::Maintain => "maintain",
165            Self::Delisted => "delisted",
166            Self::Suspended => "suspended",
167        }
168    }
169
170    /// Unrecognized values read as `Unknown` so a newer server cannot brick an
171    /// older client by inventing a state it never blocks on.
172    ///
173    /// Case- and whitespace-insensitive: `Unknown` does not block, so a server
174    /// sending `"Suspended"` against a case-sensitive match would degrade in
175    /// the unsafe direction on the one field that gates opening.
176    pub fn from_str_lossy(value: &str) -> Self {
177        match value.trim().to_ascii_lowercase().as_str() {
178            "published" => Self::Published,
179            "maintain" => Self::Maintain,
180            "delisted" => Self::Delisted,
181            "suspended" => Self::Suspended,
182            _ => Self::Unknown,
183        }
184    }
185
186    /// Whether opening must be refused.
187    ///
188    /// `Delisted` does not: it means the app is no longer offered, while an
189    /// installed copy keeps working. `Maintain` does, because the operator has
190    /// taken it down on purpose and a half-working app is worse than a clear
191    /// message.
192    pub const fn blocks_open(self) -> bool {
193        matches!(self, Self::Suspended | Self::Maintain)
194    }
195}
196
197impl std::fmt::Display for LxAppStatus {
198    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
199        f.write_str(self.as_str())
200    }
201}
202
203/// The registry's record for one lxapp: the facts the server owns.
204///
205/// Deliberately carries nothing about a *package* — version, url, checksum,
206/// `minRuntimeVersion` all belong to `UpdatePackageInfo` and travel the update
207/// path. Server-owned facts in, package facts out; the two must never become
208/// two answers to the same question.
209#[derive(Debug, Clone, Default)]
210pub struct LxAppRegistryInfo {
211    pub appid: String,
212    /// Display name as the backend defined it.
213    pub name: Option<String>,
214    pub description: Option<String>,
215    /// Where the icon lives. Also the cache key: the client re-fetches when
216    /// this changes and not otherwise, so a server that edits the artwork
217    /// behind a stable URL will never be picked up. Change the URL — a content
218    /// path, or a version query — when the image changes.
219    pub icon_url: Option<String>,
220    pub status: LxAppStatus,
221}
222
223/// Lookup of registry records, separate from `UpdateProvider` on purpose: an
224/// app's name, icon, and status change without any package changing, and the
225/// update path is gated (OTA-managed only, deduped, force-update aware) in ways
226/// that would silently strand them.
227pub trait LxAppRegistryProvider: Send + Sync + 'static {
228    /// Resolve one app's registry record.
229    ///
230    /// `name` and `description` are the strings the backend stored. The client
231    /// does not send a locale; localization, if any, is a server concern.
232    ///
233    /// `Ok(None)` means the registry does not know the app (HTTP 404). That is
234    /// a negative listing, not a transport failure.
235    fn fetch_registry_info<'a>(
236        &'a self,
237        _appid: &'a str,
238    ) -> BoxFuture<'a, Result<Option<LxAppRegistryInfo>, ProviderError>> {
239        Box::pin(async { Ok(None) })
240    }
241}
242
243#[cfg(test)]
244mod registry_tests {
245    use super::LxAppStatus;
246
247    #[test]
248    fn only_the_states_that_mean_do_not_open_block() {
249        // Two states block, and they say different things to a user: one is
250        // "come back later", the other is "this is not yours to open".
251        assert!(LxAppStatus::Suspended.blocks_open());
252        assert!(LxAppStatus::Maintain.blocks_open());
253        // Delisted is not offered any more, but an installed copy keeps working.
254        assert!(!LxAppStatus::Delisted.blocks_open());
255        assert!(!LxAppStatus::Published.blocks_open());
256        // An unrecognized state must never lock a user out.
257        assert!(!LxAppStatus::Unknown.blocks_open());
258        assert_eq!(
259            LxAppStatus::from_str_lossy("maintain"),
260            LxAppStatus::Maintain
261        );
262    }
263
264    #[test]
265    fn status_parsing_is_case_insensitive_because_unknown_never_blocks() {
266        assert_eq!(
267            LxAppStatus::from_str_lossy("suspended"),
268            LxAppStatus::Suspended
269        );
270        assert_eq!(
271            LxAppStatus::from_str_lossy("Suspended"),
272            LxAppStatus::Suspended
273        );
274        assert_eq!(
275            LxAppStatus::from_str_lossy(" SUSPENDED "),
276            LxAppStatus::Suspended
277        );
278        assert!(LxAppStatus::from_str_lossy("SUSPENDED").blocks_open());
279
280        assert_eq!(
281            LxAppStatus::from_str_lossy("Delisted"),
282            LxAppStatus::Delisted
283        );
284        assert_eq!(LxAppStatus::from_str_lossy(""), LxAppStatus::Unknown);
285        assert_eq!(LxAppStatus::from_str_lossy("retired"), LxAppStatus::Unknown);
286    }
287}