wasma-client 1.3.0-beta-release

Windows Assignment System Monitoring Architecture - Cross-platform resource-aware window management
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
// WASMA - Configuration Parser
// Only reads and parses wasma.in.conf file

use serde::{Deserialize, Serialize};
use std::fs;
use std::net::IpAddr;
use std::path::Path;
use thiserror::Error;
use wbackend::ExecutionMode;

#[derive(Debug, Error)]
pub enum ParserError {
    #[error("Config file not found: {0}")]
    ConfigNotFound(String),
    #[error("Invalid configuration: {0}")]
    InvalidConfig(String),
    #[error("Parse error: {0}")]
    ParseError(String),
    #[error("IO error: {0}")]
    IoError(#[from] std::io::Error),
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum Protocol {
    Grpc,
    Http,
    Https,
    Tor,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProtocolConfig {
    pub protocol: Protocol,
    pub ip: IpAddr,
    pub port: u16,
    pub domain: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UriHandlingConfig {
    pub multi_instances: bool,
    pub singularity_instances: bool,
    pub protocols: Vec<ProtocolConfig>,
    pub window_app_spec: String,
    pub compilation_server: Option<CompilationServer>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompilationServer {
    pub uri: String,
    pub port: u16,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserConfig {
    pub user_withed: String,
    pub groups_withed: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceLimits {
    pub ip_scope: String,
    pub scope_level: u32,
    pub renderer: String,
    // ✅ WASMA-specific extended fields
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution_mode: Option<ExecutionMode>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_memory_mb: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_vram_mb: Option<u64>,
    #[serde(default)]
    pub cpu_cores: Vec<usize>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WasmaConfig {
    pub uri_handling: UriHandlingConfig,
    pub user_config: UserConfig,
    pub resource_limits: ResourceLimits,
}

/// Config Parser - Sadece dosya okuma ve parsing
pub struct ConfigParser {
    pub config_path: String,
}

impl ConfigParser {
    pub fn new(config_path: Option<String>) -> Self {
        let path = config_path.unwrap_or_else(|| "/etc/wasma/wasma.in.conf".to_string());
        Self { config_path: path }
    }

    /// Load config file
    pub fn load(&self) -> Result<WasmaConfig, ParserError> {
        if !Path::new(&self.config_path).exists() {
            return Err(ParserError::ConfigNotFound(self.config_path.clone()));
        }

        let content = fs::read_to_string(&self.config_path)?;
        self.parse(&content)
    }

    /// Parse config content
    pub fn parse(&self, content: &str) -> Result<WasmaConfig, ParserError> {
        let mut multi_instances = false;
        let mut singularity_instances = false;
        let mut protocols = Vec::new();
        let mut window_app_spec = String::new();
        let mut compilation_server = None;
        let mut user_withed = "sysuser".to_string();
        let mut groups_withed = Vec::new();
        let mut ip_scope = "ip_base10".to_string();
        let mut scope_level = 50;
        let mut renderer = "glx_renderer".to_string();

        // ✅ Extended fields
        let mut execution_mode = None;
        let mut max_memory_mb = None;
        let mut max_vram_mb = None;
        let mut cpu_cores = Vec::new();

        for line in content.lines() {
            let line = line.trim();

            if line.starts_with("*//") || line.starts_with("#") || line.is_empty() {
                continue;
            }

            if line.contains("multi_instances") {
                multi_instances = line.contains("true");
            }

            if line.contains("singularity_instances") {
                singularity_instances = line.contains("true");
            }

            if line.contains("protocol_def") {
                if let Some(proto_str) = self.extract_value(line) {
                    let parts: Vec<&str> = proto_str.split("://").collect();
                    if parts.len() == 2 {
                        let protocol = match parts[0] {
                            "tor" => Protocol::Tor,
                            "https" => Protocol::Https,
                            "http" => Protocol::Http,
                            "grpc" => Protocol::Grpc,
                            _ => Protocol::Http,
                        };

                        let addr_parts: Vec<&str> = parts[1].split(':').collect();
                        if addr_parts.len() == 2 {
                            let ip = addr_parts[0].parse().map_err(|e| {
                                ParserError::ParseError(format!("Invalid IP: {}", e))
                            })?;
                            let port = addr_parts[1].parse().map_err(|e| {
                                ParserError::ParseError(format!("Invalid port: {}", e))
                            })?;

                            protocols.push(ProtocolConfig {
                                protocol,
                                ip,
                                port,
                                domain: None,
                            });
                        }
                    }
                }
            }

            if line.contains("domain_def") {
                if let Some(d) = self.extract_value(line) {
                    if let Some(last_proto) = protocols.last_mut() {
                        last_proto.domain = Some(d.to_string());
                    }
                }
            }

            if line.contains("uri_handling_window_appspef") {
                if let Some(spec) = self.extract_value(line) {
                    window_app_spec = spec.to_string();
                }
            }

            if line.contains("uri_compilation_define") {
                if let Some(comp_uri) = self.extract_value(line) {
                    let parts: Vec<&str> = comp_uri.split("://").collect();
                    if parts.len() == 2 {
                        let addr_parts: Vec<&str> = parts[1].split(':').collect();
                        if addr_parts.len() == 2 {
                            compilation_server = Some(CompilationServer {
                                uri: addr_parts[0].to_string(),
                                port: addr_parts[1].parse().unwrap_or(90),
                            });
                        }
                    }
                }
            }

            if line.contains("user_withed") {
                if let Some(user) = self.extract_value_from_parens(line) {
                    user_withed = user.to_string();
                }
            }

            if line.contains("groups_ewithed") {
                if let Some(groups) = self.extract_value_from_parens(line) {
                    groups_withed = groups.split(',').map(|s| s.trim().to_string()).collect();
                }
            }

            if line.contains("in_limited_scope") {
                if let Some(scope) = line.split("in_limited_scope:").nth(1) {
                    ip_scope = scope
                        .split_whitespace()
                        .next()
                        .unwrap_or("ip_base10")
                        .to_string();
                }
            }

            if line.contains("in_scoped_bylevel") {
                if let Some(level) = line.split("in_scoped_bylevel:").nth(1) {
                    scope_level = level
                        .split_whitespace()
                        .next()
                        .and_then(|s| s.parse().ok())
                        .unwrap_or(50);
                }
            }

            if line.contains("in_request_withed") {
                if let Some(rend) = line.split("in_request_withed:").nth(1) {
                    renderer = rend
                        .split_whitespace()
                        .next()
                        .unwrap_or("glx_renderer")
                        .to_string();
                }
            }

            // ✅ Extended parsing
            if line.contains("execution_mode") {
                if let Some(mode_str) = self.extract_value(line) {
                    execution_mode = match mode_str.to_lowercase().as_str() {
                        "cpu" | "cpu_only" => Some(ExecutionMode::CpuOnly),
                        "gpu" | "gpu_only" => Some(ExecutionMode::GpuOnly),
                        "gpu_preferred" | "gpu_pref" => Some(ExecutionMode::GpuPreferred),
                        "hybrid" => Some(ExecutionMode::Hybrid),
                        _ => Some(ExecutionMode::GpuPreferred),
                    };
                }
            }

            if line.contains("max_memory_mb") {
                if let Some(mem_str) = self.extract_value(line) {
                    max_memory_mb = mem_str.parse().ok();
                }
            }

            if line.contains("max_vram_mb") {
                if let Some(vram_str) = self.extract_value(line) {
                    max_vram_mb = vram_str.parse().ok();
                }
            }

            if line.contains("cpu_cores") {
                if let Some(cores_str) = self.extract_value(line) {
                    cpu_cores = cores_str
                        .split(',')
                        .filter_map(|s| s.trim().parse().ok())
                        .collect();
                }
            }
        }

        Ok(WasmaConfig {
            uri_handling: UriHandlingConfig {
                multi_instances,
                singularity_instances,
                protocols,
                window_app_spec,
                compilation_server,
            },
            user_config: UserConfig {
                user_withed,
                groups_withed,
            },
            resource_limits: ResourceLimits {
                ip_scope,
                scope_level,
                renderer,
                execution_mode,
                max_memory_mb,
                max_vram_mb,
                cpu_cores,
            },
        })
    }

    /// Generate default config
    pub fn generate_default_config(&self) -> String {
        r#"uri_handling_op {
multi_instances = false;
singularity_instances = true;
protocol_def : http://127.0.0.1:8080
uri_handling_window_appspef : file://server_request/request.manifest
#*_END_BLOCK_DEFINE
uO:?? user_withed(*sysuser)
rg0:?? groups_ewithed(*groups_insys)
r0:?? in_limited_scope:ip_base10 in_scoped_bylevel:50 in_request_withed:glx_renderer
execution_mode : gpu_preferred
max_memory_mb : 512
max_vram_mb : 256
}"#
        .to_string()
    }

    /// Validation
    pub fn validate(&self, config: &WasmaConfig) -> Result<(), ParserError> {
        if config.uri_handling.multi_instances && config.uri_handling.singularity_instances {
            return Err(ParserError::InvalidConfig(
                "Cannot enable both multi_instances and singularity_instances".to_string(),
            ));
        }

        if config.uri_handling.singularity_instances && config.uri_handling.protocols.len() > 1 {
            return Err(ParserError::InvalidConfig(
                "Singularity mode only allows one protocol".to_string(),
            ));
        }

        if config.uri_handling.protocols.is_empty() {
            return Err(ParserError::InvalidConfig(
                "At least one protocol must be configured".to_string(),
            ));
        }

        for proto in &config.uri_handling.protocols {
            if proto.port == 0 {
                return Err(ParserError::InvalidConfig(format!(
                    "Port must be between 1-65535, got {}",
                    proto.port
                )));
            }
        }

        Ok(())
    }

    // Wrap with Some() from lines 341-345
    fn extract_value<'a>(&self, line: &'a str) -> Option<&'a str> {
        Some(line.split(':').nth(1)?.split("*//").next()?.trim())
    }

    // Wrap with Some() from lines 349-353
    fn extract_value_from_parens<'a>(&self, line: &'a str) -> Option<&'a str> {
        Some(
            line.split('(')
                .nth(1)?
                .split(')')
                .next()?
                .trim_start_matches('*'),
        )
    }
}
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parser_creation() {
        let parser = ConfigParser::new(None);
        assert_eq!(parser.config_path, "/etc/wasma/wasma.in.conf");
    }

    #[test]
    fn test_config_parsing() {
        let parser = ConfigParser::new(None);
        let config_content = parser.generate_default_config();
        let result = parser.parse(&config_content);

        assert!(result.is_ok());
        let config = result.unwrap();
        assert!(config.uri_handling.singularity_instances);
        assert!(!config.uri_handling.multi_instances);
        assert_eq!(config.uri_handling.protocols.len(), 1);
        assert_eq!(config.resource_limits.max_memory_mb, Some(512));
        assert_eq!(config.resource_limits.max_vram_mb, Some(256));
    }

    #[test]
    fn test_validation() {
        let parser = ConfigParser::new(None);
        let config_content = parser.generate_default_config();
        let config = parser.parse(&config_content).unwrap();

        assert!(parser.validate(&config).is_ok());
    }

    #[test]
    fn test_execution_mode_parsing() {
        let parser = ConfigParser::new(None);
        let config_content = "execution_mode : hybrid\n";
        let config = parser.parse(config_content).unwrap();

        assert_eq!(
            config.resource_limits.execution_mode,
            Some(ExecutionMode::Hybrid)
        );
    }
}