torsh-package 0.2.0

Model packaging and distribution utilities for ToRSh
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
//! Resource handling for packages

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;

/// Type of resource in the package
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ResourceType {
    /// Model weights and state
    Model,
    /// Source code
    Source,
    /// Data files
    Data,
    /// Configuration files
    Config,
    /// Documentation
    Documentation,
    /// License files
    License,
    /// Binary assets
    Binary,
    /// Text assets
    Text,
    /// Metadata
    Metadata,
}

impl ResourceType {
    /// Get file extension for resource type
    pub fn extension(&self) -> &'static str {
        match self {
            ResourceType::Model => "model",
            ResourceType::Source => "rs",
            ResourceType::Data => "data",
            ResourceType::Config => "toml",
            ResourceType::Documentation => "md",
            ResourceType::License => "txt",
            ResourceType::Binary => "bin",
            ResourceType::Text => "txt",
            ResourceType::Metadata => "json",
        }
    }

    /// Get MIME type for resource
    pub fn mime_type(&self) -> &'static str {
        match self {
            ResourceType::Model => "application/octet-stream",
            ResourceType::Source => "text/x-rust",
            ResourceType::Data => "application/octet-stream",
            ResourceType::Config => "text/x-toml",
            ResourceType::Documentation => "text/markdown",
            ResourceType::License => "text/plain",
            ResourceType::Binary => "application/octet-stream",
            ResourceType::Text => "text/plain",
            ResourceType::Metadata => "application/json",
        }
    }

    /// Determine resource type from file extension
    pub fn from_extension(ext: &str) -> Self {
        match ext.to_lowercase().as_str() {
            "model" | "pth" | "pt" | "torsh" => ResourceType::Model,
            "rs" => ResourceType::Source,
            "json" => ResourceType::Metadata,
            "toml" | "yaml" | "yml" => ResourceType::Config,
            "md" | "rst" => ResourceType::Documentation,
            "txt" | "license" => ResourceType::License,
            "bin" | "dat" => ResourceType::Binary,
            _ => ResourceType::Data,
        }
    }

    /// Canonical, stable string tag for this resource type.
    ///
    /// Used by [`crate::exporter::PackageExporter`] to record a resource's
    /// exact type in its `.metadata` side-file (see
    /// [`RESOURCE_TYPE_METADATA_KEY`]), so [`crate::importer::PackageImporter`]
    /// can recover it authoritatively on import instead of re-deriving it
    /// from the archive path prefix or file extension — both of which are
    /// ambiguous (every type other than Model/Source/Data/Config/Documentation
    /// shares the same `resources/` archive prefix, and file extensions are
    /// not a 1:1 mapping back to a single [`ResourceType`]). See
    /// [`Self::from_tag`] for the inverse.
    pub fn as_tag(&self) -> &'static str {
        match self {
            ResourceType::Model => "model",
            ResourceType::Source => "source",
            ResourceType::Data => "data",
            ResourceType::Config => "config",
            ResourceType::Documentation => "documentation",
            ResourceType::License => "license",
            ResourceType::Binary => "binary",
            ResourceType::Text => "text",
            ResourceType::Metadata => "metadata",
        }
    }

    /// Parse a tag produced by [`Self::as_tag`].
    ///
    /// Returns `None` for an unrecognized tag (e.g. a package written by a
    /// version of this crate that used a different tag set), so callers can
    /// fall back to prefix/extension-based classification rather than
    /// failing the import outright.
    pub fn from_tag(tag: &str) -> Option<Self> {
        match tag {
            "model" => Some(ResourceType::Model),
            "source" => Some(ResourceType::Source),
            "data" => Some(ResourceType::Data),
            "config" => Some(ResourceType::Config),
            "documentation" => Some(ResourceType::Documentation),
            "license" => Some(ResourceType::License),
            "binary" => Some(ResourceType::Binary),
            "text" => Some(ResourceType::Text),
            "metadata" => Some(ResourceType::Metadata),
            _ => None,
        }
    }
}

/// Reserved [`Resource::metadata`] key used to persist a resource's exact
/// [`ResourceType`] in its `.metadata` archive side-file across an
/// export/import roundtrip (F240).
///
/// Chosen to be extremely unlikely to collide with a caller-supplied
/// metadata key. [`crate::importer::PackageImporter`] strips this key back
/// out of the metadata map it exposes on the imported [`Resource`], so it
/// never leaks into user-visible metadata.
pub(crate) const RESOURCE_TYPE_METADATA_KEY: &str = "__torsh_resource_type";

/// A resource in the package
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Resource {
    /// Resource name (unique identifier)
    pub name: String,

    /// Resource type
    pub resource_type: ResourceType,

    /// Resource data
    pub data: Vec<u8>,

    /// Additional metadata
    pub metadata: HashMap<String, String>,
}

impl Resource {
    /// Create a new resource
    pub fn new(name: String, resource_type: ResourceType, data: Vec<u8>) -> Self {
        Self {
            name,
            resource_type,
            data,
            metadata: HashMap::new(),
        }
    }

    /// Create resource from file
    pub fn from_file<P: AsRef<Path>>(
        path: P,
        resource_type: Option<ResourceType>,
    ) -> std::io::Result<Self> {
        let path = path.as_ref();
        let name = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("unnamed")
            .to_string();

        let resource_type = resource_type.unwrap_or_else(|| {
            path.extension()
                .and_then(|e| e.to_str())
                .map(ResourceType::from_extension)
                .unwrap_or(ResourceType::Data)
        });

        let data = std::fs::read(path)?;

        Ok(Self::new(name, resource_type, data))
    }

    /// Get resource size
    pub fn size(&self) -> usize {
        self.data.len()
    }

    /// Calculate SHA256 hash
    pub fn sha256(&self) -> String {
        use sha2::{Digest, Sha256};
        let mut hasher = Sha256::new();
        hasher.update(&self.data);
        hex::encode(hasher.finalize())
    }

    /// Add metadata
    pub fn add_metadata(&mut self, key: String, value: String) {
        self.metadata.insert(key, value);
    }

    /// Get metadata value
    pub fn get_metadata(&self, key: &str) -> Option<&str> {
        self.metadata.get(key).map(|s| s.as_str())
    }

    /// Check if resource is compressed
    pub fn is_compressed(&self) -> bool {
        self.metadata.contains_key("compression")
    }

    /// Get compression method
    pub fn compression_method(&self) -> Option<&str> {
        self.get_metadata("compression")
    }
}

/// Resource collection for managing multiple resources
pub struct ResourceCollection {
    resources: HashMap<String, Resource>,
}

impl ResourceCollection {
    /// Create a new resource collection
    pub fn new() -> Self {
        Self {
            resources: HashMap::new(),
        }
    }

    /// Add a resource
    pub fn add(&mut self, resource: Resource) -> Result<(), String> {
        if self.resources.contains_key(&resource.name) {
            return Err(format!("Resource '{}' already exists", resource.name));
        }

        self.resources.insert(resource.name.clone(), resource);
        Ok(())
    }

    /// Get a resource by name
    pub fn get(&self, name: &str) -> Option<&Resource> {
        self.resources.get(name)
    }

    /// Get mutable resource by name
    pub fn get_mut(&mut self, name: &str) -> Option<&mut Resource> {
        self.resources.get_mut(name)
    }

    /// Remove a resource
    pub fn remove(&mut self, name: &str) -> Option<Resource> {
        self.resources.remove(name)
    }

    /// List all resource names
    pub fn list(&self) -> Vec<&str> {
        self.resources.keys().map(|s| s.as_str()).collect()
    }

    /// Get resources by type
    pub fn by_type(&self, resource_type: ResourceType) -> Vec<&Resource> {
        self.resources
            .values()
            .filter(|r| r.resource_type == resource_type)
            .collect()
    }

    /// Get total size of all resources
    pub fn total_size(&self) -> usize {
        self.resources.values().map(|r| r.size()).sum()
    }

    /// Clear all resources
    pub fn clear(&mut self) {
        self.resources.clear();
    }

    /// Get number of resources
    pub fn len(&self) -> usize {
        self.resources.len()
    }

    /// Check if empty
    pub fn is_empty(&self) -> bool {
        self.resources.is_empty()
    }
}

impl Default for ResourceCollection {
    fn default() -> Self {
        Self::new()
    }
}

/// Resource filter for selective operations
pub struct ResourceFilter {
    types: Option<Vec<ResourceType>>,
    name_pattern: Option<String>,
    min_size: Option<usize>,
    max_size: Option<usize>,
}

impl ResourceFilter {
    /// Create a new filter
    pub fn new() -> Self {
        Self {
            types: None,
            name_pattern: None,
            min_size: None,
            max_size: None,
        }
    }

    /// Filter by resource types
    pub fn with_types(mut self, types: Vec<ResourceType>) -> Self {
        self.types = Some(types);
        self
    }

    /// Filter by name pattern
    pub fn with_name_pattern(mut self, pattern: String) -> Self {
        self.name_pattern = Some(pattern);
        self
    }

    /// Filter by size range
    pub fn with_size_range(mut self, min: Option<usize>, max: Option<usize>) -> Self {
        self.min_size = min;
        self.max_size = max;
        self
    }

    /// Check if resource matches filter
    pub fn matches(&self, resource: &Resource) -> bool {
        // Check type filter
        if let Some(types) = &self.types {
            if !types.contains(&resource.resource_type) {
                return false;
            }
        }

        // Check name pattern
        if let Some(pattern) = &self.name_pattern {
            if !resource.name.contains(pattern) {
                return false;
            }
        }

        // Check size range
        let size = resource.size();
        if let Some(min) = self.min_size {
            if size < min {
                return false;
            }
        }
        if let Some(max) = self.max_size {
            if size > max {
                return false;
            }
        }

        true
    }
}

impl Default for ResourceFilter {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_resource_type() {
        assert_eq!(ResourceType::from_extension("rs"), ResourceType::Source);
        assert_eq!(ResourceType::from_extension("model"), ResourceType::Model);
        assert_eq!(ResourceType::from_extension("json"), ResourceType::Metadata);
        assert_eq!(ResourceType::from_extension("unknown"), ResourceType::Data);
    }

    #[test]
    fn test_resource_creation() {
        let resource = Resource::new(
            "test.model".to_string(),
            ResourceType::Model,
            vec![1, 2, 3, 4],
        );

        assert_eq!(resource.name, "test.model");
        assert_eq!(resource.resource_type, ResourceType::Model);
        assert_eq!(resource.size(), 4);
    }

    #[test]
    fn test_resource_collection() {
        let mut collection = ResourceCollection::new();

        let resource1 = Resource::new("res1".to_string(), ResourceType::Model, vec![1, 2, 3]);
        let resource2 = Resource::new("res2".to_string(), ResourceType::Data, vec![4, 5, 6, 7]);

        collection.add(resource1).unwrap();
        collection.add(resource2).unwrap();

        assert_eq!(collection.len(), 2);
        assert_eq!(collection.total_size(), 7);

        let models = collection.by_type(ResourceType::Model);
        assert_eq!(models.len(), 1);
    }

    #[test]
    fn test_resource_filter() {
        let resource = Resource::new("test.model".to_string(), ResourceType::Model, vec![0; 100]);

        let filter = ResourceFilter::new()
            .with_types(vec![ResourceType::Model, ResourceType::Data])
            .with_size_range(Some(50), Some(200));

        assert!(filter.matches(&resource));

        let filter2 = ResourceFilter::new()
            .with_types(vec![ResourceType::Source])
            .with_size_range(Some(50), Some(200));

        assert!(!filter2.matches(&resource));
    }
}