lingxia-app-context 0.8.0

Shared app/product context for LingXia crates
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
use semver::Version;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use thiserror::Error;

static APP_CONFIG: OnceLock<AppConfig> = OnceLock::new();
const APP_STATE_DIR: &str = "app_state";

#[derive(Debug, Error)]
pub enum AppContextError {
    #[error("invalid app.json: {0}")]
    InvalidJson(String),
    #[error("invalid app config: {0}")]
    InvalidConfig(String),
}

/// Build-time environment version baked into `app.json`.
///
/// Wire-compatible with `lingxia_update::ReleaseType` — both serialize as
/// lowercase `"developer" | "preview" | "release"`. Defined locally here
/// (rather than imported) to keep `lingxia-app-context` free of additional
/// crate dependencies; the JSON contract is what callers rely on.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum EnvVersion {
    #[default]
    Release,
    Preview,
    Developer,
}

impl EnvVersion {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Release => "release",
            Self::Preview => "preview",
            Self::Developer => "developer",
        }
    }
}

impl std::fmt::Display for EnvVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct AppConfig {
    #[serde(rename = "productName")]
    pub product_name: String,
    #[serde(rename = "productVersion")]
    pub product_version: String,

    #[serde(rename = "lingxiaId", default)]
    pub lingxia_id: Option<String>,

    #[serde(rename = "lingxiaServer", default)]
    pub lingxia_server: Option<String>,

    /// The environment this build was produced for. Defaults to [`EnvVersion::Release`]
    /// when missing, matching pre-envVersion app.json artifacts.
    #[serde(rename = "envVersion", default)]
    pub env_version: EnvVersion,

    #[serde(rename = "homeAppId")]
    pub home_app_id: String,

    #[serde(rename = "homeAppVersion")]
    pub home_app_version: String,

    #[serde(rename = "cacheMaxSizeMB", default = "default_cache_max_size_mb")]
    pub cache_max_size_mb: u64,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub storage: Option<StorageConfig>,

    #[serde(rename = "devWsUrl", default, skip_serializing_if = "Option::is_none")]
    pub dev_ws_url: Option<String>,

    #[serde(rename = "appLinks", default, skip_serializing_if = "Option::is_none")]
    pub app_links: Option<AppLinksConfig>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capabilities: Option<CapabilitiesConfig>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub panels: Option<PanelsConfig>,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct CapabilitiesConfig {
    #[serde(default)]
    pub notifications: bool,
    #[serde(default)]
    pub terminal: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct AppLinksConfig {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub hosts: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StorageConfig {
    #[serde(rename = "tempMaxSizeMB")]
    #[serde(default = "default_temp_max_size_mb")]
    pub temp_max_size_mb: u64,
    #[serde(rename = "cacheMaxSizeMB")]
    #[serde(default = "default_cache_max_size_mb")]
    pub cache_max_size_mb: u64,
    #[serde(rename = "dataMaxSizeMB")]
    #[serde(default = "default_data_max_size_mb")]
    pub data_max_size_mb: u64,
    #[serde(rename = "appStorageMaxSizeMB")]
    #[serde(default = "default_app_storage_max_size_mb")]
    pub app_storage_max_size_mb: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct PanelsConfig {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub items: Vec<PanelItem>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum PanelPosition {
    Left,
    Right,
    Bottom,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct PanelItem {
    pub id: String,
    pub label: String,
    pub icon: String,
    #[serde(default = "default_panel_position")]
    pub position: PanelPosition,
    pub content: PanelContent,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct PanelContent {
    #[serde(rename = "appId")]
    pub app_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
}

fn default_cache_max_size_mb() -> u64 {
    2048
}

fn default_temp_max_size_mb() -> u64 {
    1024
}

fn default_data_max_size_mb() -> u64 {
    4096
}

fn default_app_storage_max_size_mb() -> u64 {
    16384
}

fn default_panel_position() -> PanelPosition {
    PanelPosition::Right
}

impl AppConfig {
    pub fn parse_and_validate(content: &str) -> Result<Self, AppContextError> {
        let config: Self = serde_json::from_str(content).map_err(|e| {
            AppContextError::InvalidJson(format!("Failed to parse app.json: {}", e))
        })?;
        config.validate()?;
        Ok(config)
    }

    fn validate(&self) -> Result<(), AppContextError> {
        if self.product_name.is_empty() {
            return Err(AppContextError::InvalidConfig(
                "productName is mandatory and cannot be empty".to_string(),
            ));
        }
        if self.product_version.is_empty() {
            return Err(AppContextError::InvalidConfig(
                "productVersion is mandatory and cannot be empty".to_string(),
            ));
        }
        Version::parse(&self.product_version).map_err(|_| {
            AppContextError::InvalidConfig(
                "productVersion must be a semantic version (major.minor.patch)".to_string(),
            )
        })?;
        if self.home_app_id.is_empty() {
            return Err(AppContextError::InvalidConfig(
                "homeAppId is mandatory and cannot be empty".to_string(),
            ));
        }
        if self.home_app_version.is_empty() {
            return Err(AppContextError::InvalidConfig(
                "homeAppVersion is mandatory and cannot be empty".to_string(),
            ));
        }
        Version::parse(&self.home_app_version).map_err(|_| {
            AppContextError::InvalidConfig(
                "homeAppVersion must be a semantic version (major.minor.patch)".to_string(),
            )
        })?;
        validate_panels(self.panels.as_ref())
    }
}

pub fn set_app_config(config: AppConfig) -> Result<(), AppContextError> {
    if let Some(existing) = APP_CONFIG.get() {
        if existing == &config {
            return Ok(());
        }
        return Err(AppContextError::InvalidConfig(
            "app config is already initialized with different values".to_string(),
        ));
    }

    APP_CONFIG
        .set(config)
        .map_err(|_| {
            AppContextError::InvalidConfig(
                "app config was initialized concurrently with different values".to_string(),
            )
        })
        .map(|_| ())
}

pub fn app_config() -> Option<&'static AppConfig> {
    APP_CONFIG.get()
}

pub fn product_name() -> Option<&'static str> {
    APP_CONFIG.get().map(|c| c.product_name.as_str())
}

pub fn home_app_id() -> Option<&'static str> {
    APP_CONFIG.get().map(|c| c.home_app_id.as_str())
}

pub fn home_app_version() -> Option<&'static str> {
    APP_CONFIG.get().map(|c| c.home_app_version.as_str())
}

pub fn product_version() -> Option<&'static str> {
    APP_CONFIG.get().map(|c| c.product_version.as_str())
}

pub fn lingxia_id() -> Option<&'static str> {
    APP_CONFIG
        .get()
        .and_then(|c| c.lingxia_id.as_deref())
        .filter(|s| !s.is_empty())
}

/// Active environment version baked into the running build. Defaults to
/// [`EnvVersion::Release`] before [`set_app_config`] is called and for any
/// `app.json` produced before the envVersion field existed.
pub fn env_version() -> EnvVersion {
    APP_CONFIG.get().map(|c| c.env_version).unwrap_or_default()
}

pub fn notifications_enabled() -> bool {
    APP_CONFIG
        .get()
        .and_then(|c| c.capabilities.as_ref())
        .map(|capabilities| capabilities.notifications)
        .unwrap_or(false)
}

pub fn terminal_enabled() -> bool {
    APP_CONFIG
        .get()
        .and_then(|c| c.capabilities.as_ref())
        .map(|capabilities| capabilities.terminal)
        .unwrap_or(false)
}

pub fn temp_max_size_bytes() -> u64 {
    const MIB: u64 = 1024 * 1024;
    APP_CONFIG
        .get()
        .and_then(|c| c.storage.as_ref().map(|storage| storage.temp_max_size_mb))
        .unwrap_or_else(default_temp_max_size_mb)
        .saturating_mul(MIB)
}

pub fn cache_max_size_bytes() -> u64 {
    const MIB: u64 = 1024 * 1024;
    APP_CONFIG
        .get()
        .map(|c| {
            c.storage
                .as_ref()
                .map(|storage| storage.cache_max_size_mb)
                .unwrap_or(c.cache_max_size_mb)
        })
        .unwrap_or_else(default_cache_max_size_mb)
        .saturating_mul(MIB)
}

pub fn data_max_size_bytes() -> u64 {
    const MIB: u64 = 1024 * 1024;
    APP_CONFIG
        .get()
        .and_then(|c| c.storage.as_ref().map(|storage| storage.data_max_size_mb))
        .unwrap_or_else(default_data_max_size_mb)
        .saturating_mul(MIB)
}

pub fn app_storage_max_size_bytes() -> u64 {
    const MIB: u64 = 1024 * 1024;
    APP_CONFIG
        .get()
        .and_then(|c| {
            c.storage
                .as_ref()
                .map(|storage| storage.app_storage_max_size_mb)
        })
        .unwrap_or_else(default_app_storage_max_size_mb)
        .saturating_mul(MIB)
}

pub fn app_state_dir(app_data_dir: &Path) -> PathBuf {
    app_data_dir.join(APP_STATE_DIR)
}

pub fn app_state_file(app_data_dir: &Path, name: &str) -> PathBuf {
    app_state_dir(app_data_dir).join(name)
}

fn validate_panels(panels: Option<&PanelsConfig>) -> Result<(), AppContextError> {
    let Some(panels) = panels else {
        return Ok(());
    };

    let mut ids = HashSet::new();
    let mut positions = HashSet::new();
    let mut app_ids = HashSet::new();

    for item in &panels.items {
        if item.id.is_empty() {
            return Err(AppContextError::InvalidConfig(
                "panels.items[].id cannot be empty".to_string(),
            ));
        }
        if item.label.is_empty() {
            return Err(AppContextError::InvalidConfig(format!(
                "panel '{}' label cannot be empty",
                item.id
            )));
        }
        if item.content.app_id.is_empty() {
            return Err(AppContextError::InvalidConfig(format!(
                "panel '{}' content.appId cannot be empty",
                item.id
            )));
        }
        if !ids.insert(item.id.clone()) {
            return Err(AppContextError::InvalidConfig(format!(
                "duplicate panel id '{}'",
                item.id
            )));
        }
        if !positions.insert(item.position) {
            return Err(AppContextError::InvalidConfig(format!(
                "only one panel is supported at position '{}'",
                panel_position_name(item.position)
            )));
        }
        if !app_ids.insert(item.content.app_id.clone()) {
            return Err(AppContextError::InvalidConfig(format!(
                "panel appId '{}' must be unique",
                item.content.app_id
            )));
        }
    }

    Ok(())
}

fn panel_position_name(position: PanelPosition) -> &'static str {
    match position {
        PanelPosition::Left => "left",
        PanelPosition::Right => "right",
        PanelPosition::Bottom => "bottom",
    }
}

#[cfg(test)]
mod tests {
    use super::{AppConfig, AppContextError, set_app_config};

    fn test_config(product_name: &str) -> AppConfig {
        AppConfig {
            product_name: product_name.to_string(),
            product_version: "1.0.0".to_string(),
            lingxia_id: Some("lingxia".to_string()),
            lingxia_server: None,
            env_version: super::EnvVersion::Release,
            home_app_id: "home".to_string(),
            home_app_version: "1.0.0".to_string(),
            cache_max_size_mb: 1024,
            storage: None,
            dev_ws_url: None,
            app_links: None,
            capabilities: None,
            panels: None,
        }
    }

    #[test]
    fn set_app_config_rejects_mismatched_value_after_initialization() {
        let cfg = test_config("LingXia");
        assert!(set_app_config(cfg.clone()).is_ok());
        assert!(set_app_config(cfg).is_ok());
        let err = set_app_config(test_config("Other")).unwrap_err();
        assert!(matches!(err, AppContextError::InvalidConfig(_)));
    }
}