# Index verify Source: https://v2.spacedrive.com/cli/index-verify # Index Integrity Verification Command ## Overview The `index verify` command performs a comprehensive integrity check of the Spacedrive index for any given path. It compares the actual filesystem state with what's stored in the database and reports any discrepancies. ## Usage ```bash theme={null} # Basic usage - verify a location sd-cli index verify /path/to/check # Verify with content hash checking (slower but more thorough) sd-cli index verify /path/to/check --verify-content # Verify without detailed output (just summary) sd-cli index verify /path/to/check --detailed=false # Future: Auto-fix issues (not yet implemented) sd-cli index verify /path/to/check --auto-fix ``` ## How It Works The command performs three main steps: ### 1. Ephemeral Indexing Runs a fresh, in-memory index scan of the filesystem path to capture the current state: * Discovers all files and directories * Extracts metadata (size, modified time, inode) * Optionally generates content hashes (with `--verify-content`) ### 2. Database Query Queries the Spacedrive database for all indexed entries under the given path: * Uses closure table for efficient descendant lookup * Resolves full paths for all entries * Extracts stored metadata ### 3. Comparison & Reporting Compares the two datasets and categorizes differences: | Issue Type | Description | | ---------------------- | ------------------------------------------------------ | | **Missing from Index** | Files exist on filesystem but not in database | | **Stale in Index** | Files exist in database but not on filesystem | | **Metadata Mismatch** | Files exist in both but with incorrect size/time/inode | | **Hierarchy Error** | Files have incorrect parent relationships | ## Output Format ``` ╔══════════════════════════════════════════════════════════════╗ ║ INDEX INTEGRITY VERIFICATION REPORT ║ ╠══════════════════════════════════════════════════════════════╣ ║ Path: /Users/jamie/Documents ║ ║ Duration: 2.34s ║ ╠══════════════════════════════════════════════════════════════╣ ║ Filesystem: 1247 files, 89 directories ║ ║ Database: 1245 files, 89 directories ║ ╠══════════════════════════════════════════════════════════════╣ ║ STATUS: DIVERGED - 4 issues found ║ ╠══════════════════════════════════════════════════════════════╣ ║ ️ Missing from index: 2 ║ ║ - /Users/jamie/Documents/new-file.txt ║ ║ - /Users/jamie/Documents/another-new.pdf ║ ║ ️ Stale in index: 2 ║ ║ - /Users/jamie/Documents/deleted-file.txt ║ ║ - /Users/jamie/Documents/old/removed.doc ║ ╠══════════════════════════════════════════════════════════════╣ ║ Index has diverged: 2 missing, 2 stale. Total: 4 ║ ╚══════════════════════════════════════════════════════════════╝ ``` ## When to Use ### Debugging Index Issues If you suspect the index is out of sync with the filesystem: ```bash theme={null} sd-cli index verify ~/Documents ``` ### After Manual File Operations If you've manually modified files outside Spacedrive: ```bash theme={null} # You edited files manually sd-cli index verify /path/that/changed ``` ### Performance Testing To verify the watcher is working correctly: ```bash theme={null} # Make changes, then verify touch /test/newfile.txt sleep 1 sd-cli index verify /test ``` ### Pre-Sync Validation Before syncing a library to ensure data integrity: ```bash theme={null} sd-cli index verify / # Verify entire library ``` ## Exit Codes | Code | Meaning | | ---- | ------------------------------------ | | 0 | Index is valid (no issues found) | | 1 | Index has diverged (issues found) | | 2 | Verification failed (error occurred) | ## Use in Scripts ```bash theme={null} #!/bin/bash # Automated integrity check if sd-cli index verify /data/important --detailed=false; then echo "Index is valid" else echo "Index has issues - running rescan" sd-cli location rescan fi ``` ## Performance Characteristics | Path Size | Typical Duration | Memory Usage | | ------------- | ---------------- | ------------ | | 100 files | \<1 second | \~10 MB | | 1,000 files | 1-3 seconds | \~50 MB | | 10,000 files | 10-30 seconds | \~200 MB | | 100,000 files | 1-5 minutes | \~1 GB | With `--verify-content`: * Add 50-200% time overhead (depends on file sizes) * Requires reading file contents for hashing ## Common Use Cases ### 1. Verify Location After Import ```bash theme={null} sd-cli location add ~/Photos --name "Photos" # Wait for indexing to complete sd-cli index verify ~/Photos ``` ### 2. Debug Watcher Issues ```bash theme={null} # Monitor filesystem watch -n 5 'sd-cli index verify /watched/path --detailed=false' ``` ### 3. Find Orphaned Entries ```bash theme={null} # Check for stale entries sd-cli index verify / | grep "Stale in index" ``` ### 4. Validate After Bulk Operations ```bash theme={null} # After moving many files mv ~/old-location/* ~/new-location/ sd-cli index verify ~/new-location ``` ## Troubleshooting ### "Path does not exist" * Ensure the path is correct and accessible * Check permissions ### "No entries found in database" * Path might not be part of a managed location * Run `sd-cli location list` to see indexed locations ### High number of "Missing from Index" * Location watcher might be disabled * Files were added manually without indexing * Run `sd-cli location rescan ` to fix ### High number of "Stale in Index" * Files were deleted manually * Database not updated * Consider running cleanup ## API Access The verification can also be triggered programmatically: ```rust theme={null} use sd_core::ops::indexing::verify::{IndexVerifyAction, IndexVerifyInput}; let input = IndexVerifyInput::new(PathBuf::from("/path/to/verify")); let result = IndexVerifyAction::from_input(input)? .execute(library, context) .await?; if !result.is_valid { println!("Found {} issues", result.report.total_issues()); } ``` ## Future Enhancements * `--auto-fix`: Automatically repair issues (add missing, remove stale) * `--watch`: Continuously verify and report drift * `--json`: Machine-readable output for automation * `--compare-with `: Compare current state with previous snapshot * `--export-snapshot`: Save current state for future comparison # Library sync setup Source: https://v2.spacedrive.com/cli/library-sync-setup # CLI: Library Sync Setup Commands ## Overview After pairing two devices, use these commands to set up library synchronization between them. ## Prerequisites 1. **Devices must be paired** - Use `sd network pair generate` and `sd network pair join` first 2. **At least one library exists** - Use `sd library list` to see available libraries 3. **Networking must be running** - Check with `sd network status` 4. **Know the device IDs** - Use `sd network devices` to list paired devices ## Commands ### 0. List Paired Devices (Get Device IDs) First, you need to know the device ID of the paired device. ```bash theme={null} sd network devices ``` **Options**: * `--connected` - Show only currently connected devices **Example**: ```bash theme={null} $ sd network devices Paired Devices (2 total, 1 connected): ───────────────────────────────────────────────────── Name: Bob's MacBook ID: 550e8400-e29b-41d4-a716-446655440000 Type: Desktop OS Version: 1.0 App Version: 2.0.0 Status: Connected Last Seen: 2025-10-05 03:30:00 Name: Alice's iPhone ID: e1054ba9-2e8b-4847-9644-a7fb764d4221 Type: Mobile OS Version: 1.0 App Version: 2.0.0 Status: Paired Last Seen: 2025-10-04 18:45:00 ``` **JSON Output**: ```bash theme={null} $ sd network devices --output json { "devices": [ { "id": "550e8400-e29b-41d4-a716-446655440000", "name": "Bob's MacBook", "device_type": "Desktop", "os_version": "1.0", "app_version": "2.0.0", "is_connected": true, "last_seen": "2025-10-05T03:30:00Z" } ], "total": 2, "connected": 1 } ``` **Filter Connected Only**: ```bash theme={null} $ sd network devices --connected Paired Devices (1 total, 1 connected): ───────────────────────────────────────────────────── Name: Bob's MacBook ID: 550e8400-e29b-41d4-a716-446655440000 Status: Connected ``` ### 1. Discover Remote Libraries Discover what libraries are available on a paired device. ```bash theme={null} sd library sync-setup discover ``` **Arguments**: * `` - UUID of the paired device **Example**: ```bash theme={null} $ sd library sync-setup discover 550e8400-e29b-41d4-a716-446655440000 Device: Bob's MacBook (550e8400-e29b-41d4-a716-446655440000) Online: true Remote Libraries (2): ───────────────────────────────────────── Name: My Library ID: 3f8cb26f-de79-4d87-88dd-01be5f024041 Created: 2025-01-01 10:30:00 Entries: 5000 Locations: 3 Devices: 1 Size: 10737418240 bytes Name: Work Documents ID: 7a9c2d1e-5f84-4b23-a567-1234567890ab Description: Work files and projects Created: 2025-01-15 14:20:00 Entries: 1200 Locations: 2 Devices: 1 Size: 2147483648 bytes ``` **JSON Output**: ```bash theme={null} $ sd library sync-setup discover --output json { "device_id": "550e8400-e29b-41d4-a716-446655440000", "device_name": "Bob's MacBook", "is_online": true, "libraries": [ { "id": "3f8cb26f-de79-4d87-88dd-01be5f024041", "name": "My Library", "description": null, "created_at": "2025-01-01T10:30:00Z", "statistics": { "total_entries": 5000, "total_locations": 3, "total_size_bytes": 10737418240, "device_count": 1 } } ] } ``` ### 2. Setup Library Sync Configure library sync between local and remote devices. ```bash theme={null} sd library sync-setup setup \ --local-library \ --remote-device \ [--remote-library ] \ [--action ] \ [--leader ] \ [--local-device ] ``` **Required Arguments**: * `--local-library` - UUID of your local library * `--remote-device` - UUID of the paired device **Optional Arguments**: * `--remote-library` - UUID of the remote library to sync with (optional for register-only) * `--action` - Sync action type (default: `register-only`) * `register-only` - Just register devices (Phase 1) * `merge-into-local` - Future (Phase 3) * `merge-into-remote` - Future (Phase 3) * `create-shared` - Future (Phase 3) * `--leader` - Which device is the sync leader (default: `local`) * `local` - This device is the leader * `remote` - Remote device is the leader * `--local-device` - Override auto-detected local device ID **Example**: ```bash theme={null} $ sd library sync-setup setup \ --local-library 3f8cb26f-de79-4d87-88dd-01be5f024041 \ --remote-device 550e8400-e29b-41d4-a716-446655440000 \ --remote-library 7a9c2d1e-5f84-4b23-a567-1234567890ab \ --action register-only \ --leader local ✓ Library sync setup successful Local library: 3f8cb26f-de79-4d87-88dd-01be5f024041 Remote library: 7a9c2d1e-5f84-4b23-a567-1234567890ab Devices successfully registered for library access ``` ## Complete Workflow Example Here's a complete workflow for pairing devices and setting up library sync: ### Device A (CLI Daemon) ```bash theme={null} # 1. Start the daemon $ sd start --foreground # 2. Generate a pairing code $ sd network pair generate Pairing code: word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12 Session: 2369763d-e205-a344-6341-dbfa2ec8a709 Expires at: 2025-10-05 03:28:44 # 3. Wait for Device B to join... # (Pairing completes) # 4. List paired devices (get device IDs) $ sd network devices Paired Devices (1 total, 1 connected): ───────────────────────────────────────────────────── Name: iOS Device ID: e1054ba9-2e8b-4847-9644-a7fb764d4221 Type: Mobile Status: Connected # 5. List local libraries $ sd library list - 3f8cb26f-de79-4d87-88dd-01be5f024041 /Users/alice/Library/Application Support/spacedrive/libraries/My Library.sdlibrary # 6. Discover libraries on Device B (iOS) $ sd library sync-setup discover e1054ba9-2e8b-4847-9644-a7fb764d4221 Device: iOS Device (e1054ba9-2e8b-4847-9644-a7fb764d4221) Online: true Remote Libraries (1): ───────────────────────────────────────── Name: My Library ID: d9828b35-6618-4d56-a37a-84ef03617d1e Entries: 0 Locations: 0 Devices: 1 # 7. Set up library sync $ sd library sync-setup setup \ --local-library 3f8cb26f-de79-4d87-88dd-01be5f024041 \ --remote-device e1054ba9-2e8b-4847-9644-a7fb764d4221 \ --remote-library d9828b35-6618-4d56-a37a-84ef03617d1e \ --leader local ✓ Library sync setup successful Local library: 3f8cb26f-de79-4d87-88dd-01be5f024041 Remote library: d9828b35-6618-4d56-a37a-84ef03617d1e Devices successfully registered for library access # 8. Verify devices are registered $ sd library info # You should see the remote device in the devices list ``` ### Device B (iOS) ```bash theme={null} # 1. Enter pairing code from Device A in the app # 2. After pairing completes, discover Device A's libraries # (Use iOS UI or similar CLI commands when running on device) # 3. Select libraries and set up sync # (Use iOS UI for library selection) ``` ## Output Formats All commands support `--output` flag: ```bash theme={null} # Human-readable (default) $ sd library sync-setup discover # JSON output $ sd library sync-setup discover --output json # YAML output $ sd library sync-setup discover --output yaml ``` ## Common Use Cases ### Scenario 1: Simple Two-Device Setup You have a desktop and a phone, both with "My Library" auto-created. ```bash theme={null} # On Desktop sd pair generate # Share code with phone # After phone joins: sd library sync-setup discover sd library sync-setup setup \ --local-library \ --remote-device \ --remote-library ``` ### Scenario 2: Multiple Libraries You want to choose which libraries to sync. ```bash theme={null} # Discover what libraries the remote device has sd library sync-setup discover # Set up sync for specific library pair sd library sync-setup setup \ --local-library \ --remote-device \ --remote-library # Optionally set up another pair sd library sync-setup setup \ --local-library \ --remote-device \ --remote-library ``` ### Scenario 3: One-Way Registration Register your device in their library without syncing data. ```bash theme={null} sd library sync-setup setup \ --local-library \ --remote-device \ --action register-only # No --remote-library specified ``` ## Troubleshooting ### "Device not paired" ```bash theme={null} Error: Device must be paired before setting up library sync Solution: 1. Check pairing status: sd pair status 2. Pair devices if needed: sd pair generate / sd pair join 3. Retry sync setup after pairing completes ``` ### "Device offline" ```bash theme={null} Device: Bob's MacBook (550e8400-e29b-41d4-a716-446655440000) Online: false No libraries found on remote device Solution: 1. Ensure remote device daemon is running 2. Check network connectivity 3. Verify devices can discover each other (mDNS) 4. Retry when device comes online ``` ### "Library not found" ```bash theme={null} Error: Library not found: Solution: 1. List local libraries: sd library list 2. Verify library ID is correct 3. Create library if needed: sd library create ``` ### "Context not available" ```bash theme={null} Error: Context not available for library operations Solution: 1. Restart the daemon: sd restart 2. Wait for initialization to complete 3. Check logs for networking initialization errors ``` ## Integration with Other Commands ### List Paired Devices ```bash theme={null} # See all paired devices with details $ sd network devices Paired Devices (2 total, 1 connected): Name: Bob's MacBook ID: 550e8400-e29b-41d4-a716-446655440000 Status: Connected # See only connected devices $ sd network devices --connected # Check network status summary $ sd network status Networking: running Paired: 2 | Connected: 1 ``` ### Verify Registration After setup, the remote device should appear in your library's device list: ```bash theme={null} # Get library info (when UI supports it) $ sd library info # Device list will include the remote device ``` ## Advanced Usage ### Custom Device ID If you need to override the auto-detected local device ID: ```bash theme={null} sd library sync-setup setup \ --local-library \ --remote-device \ --local-device \ --leader local ``` ### Specify Remote as Leader If the remote device should be the sync leader: ```bash theme={null} sd library sync-setup setup \ --local-library \ --remote-device \ --remote-library \ --leader remote ``` ## Future Commands (Phase 3) When full sync is implemented, additional actions will be available: ```bash theme={null} # Merge remote library into local sd library sync-setup setup \ --local-library \ --remote-device \ --remote-library \ --action merge-into-local \ --leader local # Merge local library into remote sd library sync-setup setup \ --local-library \ --remote-device \ --remote-library \ --action merge-into-remote \ --leader remote # Create new shared library sd library sync-setup setup \ --remote-device \ --action create-shared \ --leader local ``` ## See Also * **Pairing**: `sd network pair --help` * **Devices**: `sd network devices --help` * **Libraries**: `sd library --help` * **Networking**: `sd network --help` * **Design**: `docs/core/LIBRARY_SYNC_SETUP.md` ## Quick Command Reference ```bash theme={null} # Pairing sd network pair generate # Generate pairing code sd network pair join # Join with code sd network pair status # Show pairing sessions # Devices sd network devices # List all paired devices sd network devices --connected # List connected devices only # Library Sync Setup sd library sync-setup discover sd library sync-setup setup --local-library --remote-device [OPTIONS] # Libraries sd library list # List local libraries sd library info # Show library details ``` # Linux Deployment Source: https://v2.spacedrive.com/cli/linux-deployment Deploy Spacedrive CLI and daemon on Linux systems ## Overview The Spacedrive daemon and CLI can be deployed on Linux systems in several ways: * **Docker** - Recommended for easy deployment and isolation * **Native binaries** - Direct installation for TrueNAS, Raspberry Pi, and other Linux systems * **Systemd service** - Auto-start on boot with native binaries ## Docker Deployment ### Prerequisites * Docker 20.10+ or Docker Engine * Docker Compose (optional, but recommended) ### Quick Start with Docker Compose 1. **Create docker-compose.yml**: ```yaml theme={null} version: '3.8' services: spacedrive: image: spacedrive:latest container_name: spacedrive-daemon restart: unless-stopped volumes: - spacedrive-data:/data # Mount directories to index - /path/to/your/files:/mnt/files:ro environment: - SPACEDRIVE_DATA_DIR=/data volumes: spacedrive-data: ``` 2. **Build and start**: ```bash theme={null} # Build the image docker compose build # Start the daemon docker compose up -d # View logs docker compose logs -f ``` ### Docker CLI Commands ```bash theme={null} # Build image docker build -t spacedrive:latest . # Run daemon docker run -d \ --name spacedrive-daemon \ --restart unless-stopped \ -v spacedrive-data:/data \ -v /path/to/files:/mnt/files:ro \ spacedrive:latest # View status docker exec spacedrive-daemon sd-cli status # View logs docker logs -f spacedrive-daemon # Execute CLI commands docker exec spacedrive-daemon sd-cli library list ``` ### Multi-Architecture Support The Dockerfile supports both x86\_64 and ARM64: ```bash theme={null} # Build for ARM64 (Raspberry Pi) docker build --platform linux/arm64 -t spacedrive:arm64 . # Build for x86_64 (servers, TrueNAS) docker build --platform linux/amd64 -t spacedrive:amd64 . # Build multi-arch with buildx docker buildx build \ --platform linux/amd64,linux/arm64 \ -t spacedrive:latest \ --push . ``` ## Native Binary Deployment ### Installation 1. **Download binaries**: ```bash theme={null} # For x86_64 Linux curl -LO https://github.com/YOUR_ORG/releases/latest/download/sd-linux-x86_64 curl -LO https://github.com/YOUR_ORG/releases/latest/download/sd-daemon-linux-x86_64 # For ARM64 (Raspberry Pi) curl -LO https://github.com/YOUR_ORG/releases/latest/download/sd-linux-aarch64 curl -LO https://github.com/YOUR_ORG/releases/latest/download/sd-daemon-linux-aarch64 ``` 2. **Install binaries**: ```bash theme={null} # Move to PATH sudo mv sd-linux-* /usr/local/bin/sd-cli sudo mv sd-daemon-linux-* /usr/local/bin/sd-daemon # Set permissions sudo chmod +x /usr/local/bin/sd-cli /usr/local/bin/sd-daemon # Test installation sd-cli --version ``` ### Running the Daemon ```bash theme={null} # Start in foreground (for testing) sd-cli start --foreground # Start in background sd-cli start # Check status sd-cli status # Stop daemon sd-cli stop ``` ## Systemd Service (Auto-Start) ### Installation The CLI includes built-in systemd service management: ```bash theme={null} # Install and enable auto-start sd-cli daemon install # Check status sd-cli daemon status # Uninstall auto-start sd-cli daemon uninstall ``` This creates a systemd user service at: ``` ~/.config/systemd/user/spacedrive-daemon.service ``` ### Manual Systemd Setup If you prefer manual setup, create the service file: ```bash theme={null} mkdir -p ~/.config/systemd/user cat > ~/.config/systemd/user/spacedrive-daemon.service << 'EOF' [Unit] Description=Spacedrive Daemon After=network.target [Service] Type=simple ExecStart=/usr/local/bin/sd-daemon --data-dir %h/.local/share/spacedrive Restart=on-failure RestartSec=5s StandardOutput=journal StandardError=journal [Install] WantedBy=default.target EOF ``` Then enable and start: ```bash theme={null} # Reload systemd systemctl --user daemon-reload # Enable auto-start systemctl --user enable spacedrive-daemon # Start now systemctl --user start spacedrive-daemon # Check status systemctl --user status spacedrive-daemon # View logs journalctl --user -u spacedrive-daemon -f ``` ## TrueNAS Deployment ### TrueNAS SCALE (Debian-based) TrueNAS SCALE supports Docker, so you can use either method: #### Option 1: Docker (Recommended) 1. Enable Docker/Kubernetes in TrueNAS SCALE Apps 2. Deploy using the docker-compose.yml above 3. Mount your TrueNAS pools as volumes #### Option 2: Native Binary ```bash theme={null} # SSH into TrueNAS ssh admin@truenas # Download and install binaries curl -LO https://github.com/YOUR_ORG/releases/latest/download/sd-linux-x86_64 curl -LO https://github.com/YOUR_ORG/releases/latest/download/sd-daemon-linux-x86_64 sudo mv sd-linux-x86_64 /usr/local/bin/sd-cli sudo mv sd-daemon-linux-x86_64 /usr/local/bin/sd-daemon sudo chmod +x /usr/local/bin/sd-cli /usr/local/bin/sd-daemon # Set up systemd service sd-cli daemon install # Index your pools sd-cli location add /mnt/pool1 sd-cli location add /mnt/pool2 ``` ### TrueNAS CORE (FreeBSD) Currently unsupported. Use TrueNAS SCALE (recommended) or run in a Linux VM. ## Raspberry Pi Deployment ### Prerequisites * Raspberry Pi 3/4/5 or newer * Raspberry Pi OS (64-bit recommended) * At least 1GB free RAM ### Installation ```bash theme={null} # Update system sudo apt-get update && sudo apt-get upgrade -y # Download ARM64 binaries wget https://github.com/YOUR_ORG/releases/latest/download/sd-linux-aarch64 wget https://github.com/YOUR_ORG/releases/latest/download/sd-daemon-linux-aarch64 # Install sudo mv sd-linux-aarch64 /usr/local/bin/sd-cli sudo mv sd-daemon-linux-aarch64 /usr/local/bin/sd-daemon sudo chmod +x /usr/local/bin/sd-cli /usr/local/bin/sd-daemon # Install auto-start sd-cli daemon install # Start daemon sudo systemctl --user start spacedrive-daemon ``` ### Performance Tips * Use external SSD for better I/O performance * Limit concurrent indexing jobs: `sd-cli config set jobs.max_concurrent 2` * Disable thumbnail generation for large libraries to save RAM ## Configuration ### Data Directory By default, data is stored at: * Native: `~/.local/share/spacedrive` (Linux) * Docker: `/data` (mapped to volume) Override with `--data-dir` flag: ```bash theme={null} sd-cli --data-dir /mnt/external/spacedrive start ``` ### Auto-Update Configure update repository: ```bash theme={null} # Set your releases repo sd-cli config set update.repo "your-org/spacedrive-cli-releases" # Check for updates sd-cli update # Auto-update on schedule (cron) echo "0 2 * * * /usr/local/bin/sd-cli update --force" | crontab - ``` ### Multiple Instances Run multiple daemon instances: ```bash theme={null} # Instance for work files sd-cli --instance work --data-dir ~/spacedrive-work start # Instance for personal files sd-cli --instance personal --data-dir ~/spacedrive-personal start # Install both as services sd-cli --instance work daemon install sd-cli --instance personal daemon install ``` ## Monitoring ### Health Checks ```bash theme={null} # Check daemon status sd-cli status # Check systemd service systemctl --user status spacedrive-daemon # View recent logs journalctl --user -u spacedrive-daemon --since "1 hour ago" # Follow logs in real-time sd-cli logs follow ``` ### Resource Usage ```bash theme={null} # Check memory usage ps aux | grep sd-daemon # Check disk usage du -sh ~/.local/share/spacedrive # Monitor with htop htop -p $(pgrep sd-daemon) ``` ## Troubleshooting ### Daemon Won't Start ```bash theme={null} # Check logs journalctl --user -u spacedrive-daemon -n 50 # Or with CLI sd-cli logs follow # Reset data and restart sd-cli restart --reset ``` ### Permission Issues ```bash theme={null} # Fix binary permissions sudo chmod +x /usr/local/bin/sd-cli /usr/local/bin/sd-daemon # Fix data directory permissions chmod -R u+rw ~/.local/share/spacedrive ``` ### Port Conflicts If you see "address already in use": ```bash theme={null} # Check what's using the socket lsof ~/.local/share/spacedrive/daemon/daemon.sock # Kill old process pkill sd-daemon # Restart sd-cli start ``` ### Out of Memory (Raspberry Pi) ```bash theme={null} # Check available memory free -h # Reduce concurrent jobs sd-cli config set jobs.max_concurrent 1 # Restart daemon sd-cli restart ``` ## Security Considerations ### Running as Non-Root Always run as a regular user, never as root: ```bash theme={null} # DON'T do this sudo sd-cli start # ❌ # DO this instead sd-cli start # ✓ ``` ### Firewall Configuration If enabling API access (future): ```bash theme={null} # Allow specific port sudo ufw allow 8080/tcp # Or limit to local network sudo ufw allow from 192.168.1.0/24 to any port 8080 ``` ### File Permissions Ensure indexed directories are readable: ```bash theme={null} # Check permissions ls -la /path/to/index # Fix if needed chmod -R u+r /path/to/index ``` ## Uninstallation ### Remove Daemon ```bash theme={null} # Stop daemon sd-cli stop # Remove auto-start sd-cli daemon uninstall # Remove binaries sudo rm /usr/local/bin/sd-cli /usr/local/bin/sd-daemon # Remove data (optional) rm -rf ~/.local/share/spacedrive ``` ### Remove Docker ```bash theme={null} # Stop and remove container docker compose down # Remove volumes docker volume rm spacedrive-data # Remove image docker rmi spacedrive:latest ``` ## Advanced Configuration ### Custom Systemd Service Options Edit `~/.config/systemd/user/spacedrive-daemon.service`: ```ini theme={null} [Service] # Limit memory usage MemoryMax=1G # Set nice priority Nice=10 # Set I/O priority IOSchedulingClass=best-effort IOSchedulingPriority=5 # Environment variables Environment="RUST_LOG=info" ``` Then reload and restart: ```bash theme={null} systemctl --user daemon-reload systemctl --user restart spacedrive-daemon ``` ### Docker Resource Limits In docker-compose.yml: ```yaml theme={null} services: spacedrive: # ... other config ... deploy: resources: limits: cpus: '2.0' memory: 2G reservations: memory: 512M ``` ## Next Steps * [CLI Architecture](/core/cli) - Learn about the CLI architecture * [Library Sync Setup](/cli/library-sync-setup) - Set up multi-device sync * [Multi-Instance](/cli/multi-instance) - Run multiple daemon instances # Multi instance Source: https://v2.spacedrive.com/cli/multi-instance # Multi-Instance Daemon Support Spacedrive CLI now supports running multiple daemon instances simultaneously, enabling local testing of device pairing and other multi-device features. ## Overview Multiple daemon instances allow you to: * Test device pairing locally by running two instances * Simulate multi-device scenarios on a single machine * Isolate different development/testing environments * Run production and development daemons side-by-side ## Usage ### Starting Multiple Instances ```bash theme={null} # Start default instance spacedrive start # Start named instances spacedrive start --instance alice spacedrive start --instance bob # Start with networking enabled spacedrive start --instance alice spacedrive start --instance bob ``` ### Targeting Specific Instances Use the `--instance` flag to target commands to specific daemon instances: ```bash theme={null} # Default instance spacedrive library list # Named instances spacedrive --instance alice library list spacedrive --instance bob library create "Bob's Library" ``` ### Instance Management ```bash theme={null} # List all daemon instances spacedrive instance list # Stop specific instance spacedrive instance stop alice spacedrive --instance bob stop # Alternative syntax # Check status of specific instance spacedrive --instance alice daemon ``` ### Auto-Start Configuration On macOS, you can configure instances to start automatically on login: ```bash theme={null} # Install auto-start for default instance spacedrive daemon install # Install auto-start for named instance spacedrive --instance alice daemon install # Check auto-start status spacedrive --instance alice daemon status # Remove auto-start spacedrive --instance alice daemon uninstall ``` Each instance gets its own LaunchAgent plist file. The daemon starts with the correct `--data-dir` and `--instance` flags automatically. Logs write to `~/Library/Application Support/spacedrive/logs/daemon.out.log` and `daemon.err.log`. ### Device Pairing Example Test device pairing locally using two instances: ```bash theme={null} # Terminal 1: Start Alice's daemon spacedrive start --instance alice --foreground # Terminal 2: Start Bob's daemon spacedrive start --instance bob --foreground # Terminal 3: Alice generates pairing code spacedrive --instance alice network init --password "test123" spacedrive --instance alice network pair generate --auto-accept # Terminal 4: Bob joins using Alice's code spacedrive --instance bob network init --password "test123" spacedrive --instance bob network pair join "word1 word2 word3 ... word12" ``` ## Architecture ### Instance Isolation Each instance has completely isolated: * **Socket paths**: `spacedrive.sock`, `spacedrive-alice.sock`, `spacedrive-bob.sock` * **PID files**: `spacedrive.pid`, `spacedrive-alice.pid`, `spacedrive-bob.pid` * **Data directories**: `data/sd-cli-data/`, `data/sd-cli-data/instance-alice/` * **CLI state**: Separate `cli_state.json` per instance ### File Structure ``` $runtime_dir/ # /tmp or $XDG_RUNTIME_DIR ├── spacedrive.sock # Default instance socket ├── spacedrive.pid # Default instance PID ├── spacedrive-alice.sock # Alice instance socket ├── spacedrive-alice.pid # Alice instance PID ├── spacedrive-bob.sock # Bob instance socket └── spacedrive-bob.pid # Bob instance PID data/sd-cli-data/ # Default instance data ├── spacedrive.json ├── libraries/ └── cli_state.json data/sd-cli-data/instance-alice/ # Alice instance data ├── spacedrive.json ├── libraries/ └── cli_state.json data/sd-cli-data/instance-bob/ # Bob instance data ├── spacedrive.json ├── libraries/ └── cli_state.json ``` ## Development Workflow ### Testing Pairing Protocol ```bash theme={null} # Start two instances for pairing test spacedrive start --instance initiator --foreground & spacedrive start --instance joiner --foreground & # Initialize networking spacedrive --instance initiator network init --password "dev123" spacedrive --instance joiner network init --password "dev123" # Test pairing CODE=$(spacedrive --instance initiator network pair generate --auto-accept | grep "Pairing code:" | cut -d' ' -f3-) spacedrive --instance joiner network pair join "$CODE" # Verify connection spacedrive --instance initiator network devices spacedrive --instance joiner network devices ``` ### Instance Cleanup ```bash theme={null} # Stop all instances spacedrive instance list spacedrive instance stop alice spacedrive instance stop bob spacedrive stop # Default instance # Clean up sockets (if needed) rm /tmp/spacedrive*.sock /tmp/spacedrive*.pid ``` ## Backwards Compatibility The implementation maintains full backwards compatibility: * All existing commands work unchanged with the default instance * No breaking changes to CLI interface * Default instance behavior is identical to single-instance mode ## Implementation Notes * Instance names must be valid filenames (no special characters) * Socket discovery happens automatically via filesystem scanning * Daemon startup checks for instance conflicts * Each instance runs independently with separate process trees # Overview Source: https://v2.spacedrive.com/cli/overview # Spacedrive CLI A comprehensive command-line interface for managing Spacedrive Core with full daemon architecture, real-time monitoring, and cross-device file management. ## Features * **️ Daemon Architecture**: Background daemon with client-server communication * **Library Management**: Create, open, switch, and manage multiple libraries * **Location Management**: Add, remove, and monitor indexed locations with real-time watching * **️ Job Management**: View, monitor, and control background jobs with live progress * **Real-time Monitoring**: Beautiful TUI for monitoring job progress and system events * **Indexing Control**: Start indexing jobs with different modes (shallow/content/deep) * **Networking Support**: Device pairing, file sharing via Spacedrop * **Multiple Instances**: Run isolated daemon instances for different use cases * **Comprehensive Logging**: Built-in logging with file output for debugging * **️ Cross-platform**: Works on macOS, Linux, and Windows * **Rich UI**: Colored output, progress bars, and formatted tables ### New Modular Architecture Benefits The refactored daemon architecture provides: * **Maintainability**: Each domain (library, location, job, etc.) is isolated in its own handler module * **Extensibility**: New commands can be added by simply creating a new handler * **Type Safety**: All commands and responses are strongly typed * **Code Organization**: Clear separation between command handling, business logic, and transport * **Testability**: Individual handlers can be unit tested in isolation * **Performance**: Efficient command routing through handler registry ## Installation ```bash theme={null} # Build the CLI cargo build --release --package sd-cli --package sd-core # Or build just the CLI for development cd apps/cli && cargo build # Install globally (optional) cargo install --path apps/cli ``` Also you may create an alias to the cli as `sd` or `spacedrive`. Example for `sd`: ```bash theme={null} # For release build echo 'alias sd="/path/to/spacedrive/target/release/sd-cli"' >> ~/.zshrc # For debug build (faster compilation) echo 'alias sd="/path/to/spacedrive/target/debug/sd-cli"' >> ~/.zshrc # Reload your shell configuration source ~/.zshrc ``` ## Quick Start ```bash theme={null} # Start the Spacedrive daemon sd start # Create a library and add a location sd library create "Personal" sd location add ~/Desktop --name "Desktop" # Monitor indexing progress sd job monitor # Check system status sd status ``` **Note**: If you haven't set up the alias, use `./target/debug/sd-cli` or `./target/release/sd-cli` instead of `sd`. ## Usage ### Daemon Management ```bash theme={null} # Start daemon in background sd start # Start daemon with networking enabled sd start # Start daemon in foreground (for debugging) sd start --foreground # Stop the daemon sd stop # Check daemon status sd status ``` ### Daemon Auto-Start (macOS) Set up the daemon to start automatically on login: ```bash theme={null} # Install auto-start service sd daemon install # Check installation status sd daemon status # Remove auto-start service sd daemon uninstall ``` The install command creates a LaunchAgent that starts the daemon on login and restarts it if it crashes. Logs write to your data directory at `~/Library/Application Support/spacedrive/logs/`. This works with multiple instances by passing `--instance` before the daemon command. Auto-start is currently macOS-only. Linux systemd support is planned. ### Multiple Daemon Instances The CLI supports running multiple isolated daemon instances: ```bash theme={null} # Run a separate daemon instance sd --instance test start sd --instance test library create "Test Library" # Stop specific instance sd --instance test stop # Install auto-start for specific instance sd --instance test daemon install ``` ### Basic Commands ```bash theme={null} # Show help sd --help # Enable verbose logging sd -v # Use custom data directory sd --data-dir /path/to/data ``` ### Library Management ```bash theme={null} # Create a new library sd library create "My Library" sd library create "My Library" --path /custom/path # List all libraries sd library list # Open an existing library sd library open /path/to/library # Switch to a library by name or ID sd library switch "My Library" sd library switch 12345678-1234-1234-1234-123456789012 # Show current library sd library current # Close current library sd library close ``` ### Location Management ```bash theme={null} # Add a location to index (automatically starts watching) sd location add ~/Documents sd location add ~/Pictures --name "My Photos" --mode deep # List all locations with status sd location list # Remove a location (stops watching and indexing) sd location remove # Rescan a location (triggers re-indexing) sd location rescan sd location rescan --force # Full rescan, ignore change detection ``` **Note**: Location IDs are UUIDs displayed in the list command. All location operations work with the daemon automatically. ### Enhanced Indexing The new indexing system supports different scopes and persistence modes: ```bash theme={null} # Quick scan of current directory only (no subdirectories) sd index quick-scan /path/to/directory --scope current # Quick scan with ephemeral mode (no database writes) sd index quick-scan /path/to/directory --scope current --ephemeral # Browse external paths without adding to managed locations sd index browse /media/external-drive --scope current sd index browse /network/drive --scope recursive --content # Index managed locations with specific scope sd index location /managed/location --scope current --mode shallow sd index location --scope recursive --mode deep # Legacy full location indexing (backward compatibility) sd scan /path/to/directory --mode content --watch ``` **Index Scopes:** * `current`: Index only the specified directory (single level) * `recursive`: Index the directory and all subdirectories **Index Modes:** * `shallow`: Metadata only (fastest) * `content`: Metadata + content hashing (moderate) * `deep`: Full analysis including media metadata (slowest) **Use Cases:** * **UI Navigation**: `quick-scan --scope current` for instant directory viewing * **External Browsing**: `browse --ephemeral` for exploring non-managed paths * **Location Updates**: `location --scope current` to refresh specific directories ### Job Management ```bash theme={null} # List all jobs with colored status and progress sd job list sd job list --status running # Filter by status # Show detailed job information sd job info # Monitor jobs in real-time with live progress bars sd job monitor sd job monitor --job-id # Monitor specific job # Control jobs (planned features) sd job pause sd job resume sd job cancel ``` **Job Monitor Features:** * Live progress bars for running jobs * Color-coded status (running: yellow, completed: green, failed: red) * ️ Real-time updates every second * Automatic cleanup of completed jobs * ️ Ctrl+C to exit gracefully ### File Operations ```bash theme={null} # Copy files with progress tracking sd file copy ~/source.txt ~/destination.txt sd file copy ~/Photos/*.jpg ~/Backup/ --verify # Move files sd file move ~/Downloads/*.pdf ~/Documents/ --preserve-timestamps # Advanced copy options sd file copy ~/Project/ ~/Backup/Project/ \ --overwrite \ --verify \ --preserve-timestamps ``` ### System Commands ```bash theme={null} # Show system status sd status # Monitor all system activity (TUI) sd monitor # View daemon logs sd system logs sd system logs --tail 50 ``` ### Networking & Device Management ```bash theme={null} # Initialize networking (if daemon wasn't started with) sd network init # Start/stop networking sd network start sd network stop # List connected devices sd network devices # Device pairing sd network pair --initiate # Generate pairing code sd network pair --join # Join using code sd network pair --status # Check pairing status # Spacedrop (file sharing) sd network spacedrop /path/to/file --sender "Your Name" # Remove paired device sd network revoke ``` ## Real-time Job Monitor The job monitor provides live progress tracking with beautiful visual indicators: ```bash theme={null} sd job monitor ``` ### Monitor Features * **Multi-job tracking**: Monitor all running jobs simultaneously * **Progress bars**: Visual progress indicators with percentage * **Color coding**: Status-based colors (yellow=running, green=completed, red=failed) * **Real-time updates**: Updates every second with latest progress * **Smart cleanup**: Completed jobs automatically marked and removed * **Job filtering**: Option to monitor specific jobs ### Sample Output ``` Spacedrive Job Monitor - Press Ctrl+C to exit ═══════════════════════════════════════════ ⠚ Indexing Desktop [fdbe777d] [████████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░] 25% | Status: Running ⠂ Indexing Photos [a1b2c3d4] [██████████████████████████████████████████] 100% | Completed ⠈ Content Analysis [e5f6g7h8] [██████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░] 15% | Status: Running ``` ## Indexing Modes * **Shallow**: Fast metadata-only indexing (file names, sizes, dates) * **Content**: Standard indexing with content hashing for deduplication * **Deep**: Comprehensive analysis including media metadata extraction ## Examples ### Complete Workflow ```bash theme={null} # 1. Start the daemon sd start # 2. Create a library sd library create "Personal" # 3. Add locations with different index modes sd location add ~/Desktop --name "Desktop" --mode content sd location add ~/Documents --name "Documents" --mode content sd location add ~/Pictures --name "Photos" --mode deep # 4. Add cloud storage sd volume add-cloud "S3 Backup" --service s3 --bucket my-backup --region us-west-2 # 5. Monitor the indexing progress sd job monitor # 6. Copy files to cloud using unified URIs sd cp local://macbook/Desktop/important.pdf s3://my-backup/documents/ # 7. Check the results sd location list sd job list ``` ### Multiple Libraries ```bash theme={null} # Work with multiple libraries sd library create "Work" sd library create "Personal" sd library list sd library switch "Work" sd location add ~/Work/Projects ``` ### Batch Indexing ```bash theme={null} # Index multiple locations sd location add ~/Documents --name "Docs" sd location add ~/Pictures --name "Photos" --mode deep sd location add ~/Downloads --name "Downloads" --mode shallow sd job list --status running ``` ## Architecture The CLI follows a modular architecture with clear separation of concerns: * **Client**: Lightweight CLI that communicates with daemon * **Daemon**: Long-running background service managing Core * **Handlers**: Modular command processors for each domain * **Transport**: JSON-RPC communication over Unix socket * **Core**: Spacedrive Core library for all operations ### Benefits 1. **Performance**: Daemon keeps Core loaded in memory 2. **Persistence**: Operations continue after CLI exits 3. **Concurrency**: Multiple CLI clients can connect 4. **Monitoring**: Real-time tracking of background tasks 5. **Isolation**: Multiple instances for testing # Unified Addressing Source: https://v2.spacedrive.com/core/addressing Spacedrive uses a unified addressing scheme that works seamlessly across local devices, cloud storage, and content-addressed files. Every file has a single, intuitive URI that tells you exactly where it lives - whether it's on your laptop, in S3, or stored by content hash. **Local devices:** ``` local://jamies-macbook/Users/james/Documents/report.pdf ``` **Cloud storage:** ``` s3://my-bucket/photos/2024/vacation.jpg ``` **Content addressed:** ``` content://550e8400-e29b-41d4-a716-446655440000 ``` The same URI format works across all storage types, matching industry-standard cloud tools like AWS CLI and gsutil. Copy a path from Spacedrive and paste it directly into your terminal. ## URI Formats ### Cloud Storage - Service-Native URIs Cloud files use the same URI format as their native tools: ``` s3://my-bucket/photos/2024/vacation/IMG_0123.jpg gdrive://My Drive/Documents/Contract 2024.pdf onedrive://Documents/Budget Spreadsheet.xlsx dropbox://Apps/Spacedrive/backup-2024-10.zip azblob://container/data/export-2024.csv gcs://my-bucket/logs/application-2024-10-15.log ``` **Pattern**: `{service}://{identifier}/{path}` Where: * `{service}`: Cloud service type (s3, gdrive, onedrive, dropbox, azblob, gcs, b2, wasabi, spaces) * `{identifier}`: Service-specific root (bucket name, folder, container) * `{path}`: Path within the service These URIs match AWS CLI, gsutil, and other cloud tools exactly. Copy a path from Spacedrive and paste it into `aws s3 cp` without modification. ### Local Files - Device-Aware URIs Local files include the device name for multi-device clarity: ``` local://jamies-macbook/Users/james/Documents/report.pdf local://home-server/mnt/storage/media/movies/Inception.mkv local://work-desktop/C:/Projects/spacedrive/README.md ``` **Pattern**: `local://{device-slug}/{path}` Where: * `{device-slug}`: URL-safe device identifier (generated from device name) * `{path}`: Absolute path on that device Device slugs are generated automatically from your device name by converting to lowercase and replacing non-alphanumeric characters with hyphens. "Jamie's MacBook Pro" becomes `jamies-macbook-pro`. ### Content-Addressed Files Content URIs reference files by their content hash, independent of location: ``` content://550e8400-e29b-41d4-a716-446655440000 ``` **Pattern**: `content://{uuid}` This enables location-independent operations. The same photo stored on multiple devices and in cloud storage shares one content URI. Spacedrive resolves it to the most efficient available location. ## Device Slug System Spacedrive generates URL-safe slugs from device names to create stable, human-readable URIs. ### Slug Generation ```rust theme={null} // Convert device name to slug let name = "Jamie's MacBook Pro"; let slug = name.to_lowercase() .chars() .map(|c| if c.is_alphanumeric() { c } else { '-' }) .collect::() .trim_matches('-'); // Result: "jamies-macbook-pro" ``` Examples: * "Jamie's MacBook" → `jamies-macbook` * "Home Server 2024" → `home-server-2024` * "DESKTOP-ABC123" → `desktop-abc123` ### Slug Uniqueness Each device's slug must be unique within your Spacedrive network. The database enforces this with a unique constraint on the `slug` column. If you try to add a device with a duplicate name, you'll need to rename one device. If two devices have the same name (e.g., both "MacBook Pro"), you must give them distinct names before they can sync. Spacedrive will warn you during pairing. ### Resolution When parsing a `local://` URI, Spacedrive looks up the device by slug: ```rust theme={null} // Parse: local://jamies-macbook/Users/james/file.txt let device_id = device_manager.resolve_by_slug("jamies-macbook")?; let path = PathBuf::from("/Users/james/file.txt"); ``` Currently, slug resolution only works for the current device. Remote device paths use UUIDs internally but display with slugs for user-facing operations. ## How It Works Spacedrive maintains user-friendly URIs in the display layer while using efficient internal identifiers for operations. ### User-Facing Display ```rust theme={null} // Display path to user let display_uri = sd_path.display_with_context(&context).await; println!("{}", display_uri); // Output: "s3://media-bucket/videos/demo.mp4" ``` ### Internal Representation ```rust theme={null} pub enum SdPath { Physical { device_slug: String, // URL-safe device identifier path: PathBuf, }, Cloud { service: CloudServiceType, // Cloud service type (S3, GoogleDrive, etc.) identifier: String, // Service identifier (bucket, drive name, etc.) path: String, // Path within the service }, Content { content_id: Uuid, }, } ``` ### Resolution Flow ``` User Input: s3://my-bucket/file.jpg ↓ Parse Scheme: "s3" → CloudServiceType::S3 ↓ Parse Identity: identifier = "my-bucket" path = "file.jpg" ↓ Create SdPath: SdPath::Cloud { service: S3, identifier: "my-bucket", path: "file.jpg" } ↓ Find Volume: VolumeManager::find_cloud_volume(S3, "my-bucket") ↓ Mount Cache: "s3://my-bucket" → VolumeFingerprint (O(1) lookup) ↓ Operations: Use volume backend for I/O operations ``` The service and identifier are stored directly in the `SdPath`, making cloud paths self-contained. The VolumeManager maintains a mount point cache for fast volume lookups. ## Cloud Service Schemes Spacedrive supports these cloud URI schemes: | Service | Scheme | Example | | -------------------- | ------------- | -------------------------------------- | | Amazon S3 | `s3://` | `s3://my-bucket/path/file.jpg` | | Google Drive | `gdrive://` | `gdrive://My Drive/Documents/file.pdf` | | OneDrive | `onedrive://` | `onedrive://Documents/file.xlsx` | | Dropbox | `dropbox://` | `dropbox://Apps/Spacedrive/file.zip` | | Azure Blob | `azblob://` | `azblob://container/data/file.csv` | | Google Cloud Storage | `gcs://` | `gcs://bucket/logs/file.log` | | Backblaze B2 | `b2://` | `b2://bucket/backups/file.tar` | | Wasabi | `wasabi://` | `wasabi://bucket/archive/file.zip` | | DigitalOcean Spaces | `spaces://` | `spaces://space/assets/file.png` | S3-compatible services (MinIO, Cloudflare R2, Wasabi, etc.) use the `s3://` scheme with custom endpoints. ## Parsing URIs ### From User Input ```rust theme={null} use sd_core::domain::addressing::SdPath; // Parse cloud URI let path = SdPath::from_uri_with_context( "s3://my-bucket/photos/vacation.jpg", &context ).await?; // Parse local URI let path = SdPath::from_uri_with_context( "local://jamies-macbook/Users/james/file.txt", &context ).await?; // Parse content URI let path = SdPath::from_uri_with_context( "content://550e8400-e29b-41d4-a716-446655440000", &context ).await?; ``` ### Error Handling ```rust theme={null} match SdPath::from_uri_with_context(uri, &context).await { Ok(path) => { /* Use path */ } Err(SdPathParseError::UnknownScheme) => { // Invalid URI scheme } Err(SdPathParseError::VolumeNotFound) => { // Cloud volume doesn't exist or isn't added } Err(SdPathParseError::DeviceNotFound) => { // Device slug not found } Err(_) => { // Other parse errors } } ``` ## CLI Usage The unified addressing scheme makes CLI operations intuitive: ```bash theme={null} # Copy from Google Drive to S3 sd cp gdrive://Work/report.pdf s3://backup/documents/ # List files on remote device sd ls local://home-server/mnt/media/movies/ # Search across all storage sd search "*.mp4" # Results show unified URIs: # gdrive://Videos/vacation.mp4 # s3://media/clips/demo.mp4 # local://macbook/Users/james/Downloads/tutorial.mp4 # Sync local to cloud sd sync local://macbook/Photos/ s3://backup/photos/ ``` ## Code Examples ### File Operations ```rust theme={null} // Copy from cloud to local let src = SdPath::from_uri_with_context( "gdrive://Work/presentation.pptx", &context ).await?; let dst = SdPath::from_uri_with_context( "local://macbook/Desktop/", &context ).await?; copy_action.execute(src, dst).await?; ``` ### Display Paths ```rust theme={null} // Get user-friendly URI for display let uri = sd_path.display_with_context(&context).await; println!("File location: {}", uri); // Examples: // "s3://media-bucket/videos/demo.mp4" // "local://jamies-macbook/Users/james/file.txt" // "content://550e8400-e29b-41d4-a716-446655440000" ``` ### Building Paths ```rust theme={null} // Create cloud path let path = SdPath::Cloud { service: CloudServiceType::S3, identifier: "my-bucket".to_string(), path: "photos/vacation.jpg".to_string(), }; // Create local path let path = SdPath::Physical { device_slug: "jamies-macbook".to_string(), path: PathBuf::from("/Users/james/file.txt"), }; // Create content path let path = SdPath::Content { content_id: Uuid::new_v4(), }; ``` ## Industry Standard Alignment Spacedrive's addressing matches industry tools: **AWS CLI**: ```bash theme={null} aws s3 cp s3://bucket/file.jpg local-file.jpg sd cp s3://bucket/file.jpg local://macbook/Desktop/file.jpg ``` **gsutil**: ```bash theme={null} gsutil cp gs://bucket/file.jpg local-file.jpg sd cp gcs://bucket/file.jpg local://macbook/Desktop/file.jpg ``` **Azure CLI**: ```bash theme={null} az storage blob download --container container --name file.csv sd cp azblob://container/file.csv local://macbook/Desktop/file.csv ``` The alignment eliminates context switching between tools. URIs copy-paste directly between Spacedrive and native cloud tools. ## Benefits ### Self-Documenting URIs clearly show where files live: ``` s3://media-bucket/photos/vacation.jpg ↑ ↑ Service Bucket ``` No need to remember which cloud provider or check internal IDs. ### Cross-Storage Operations Operations work identically across storage types: ```rust theme={null} // Same API for all storage backends copy(src, dst).await?; // Works for any combination: // - local → local // - local → cloud // - cloud → cloud // - cloud → local ``` ### Location Independence Content URIs enable operations without knowing physical location: ```rust theme={null} // Reference by content, not location let file = SdPath::Content { content_id }; // Spacedrive finds the best location: // - Fastest device (SSD vs HDD) // - Lowest cost (local vs cloud egress) // - Highest availability ``` ## Limitations ### Device Slug Resolution Device slug resolution works for all devices in the library through an in-memory cache. When a library opens, all device slugs are loaded into the DeviceManager's cache, enabling instant O(1) resolution for any device whether online or offline. The cache updates automatically when: * A library is opened (loads all devices from database) * New devices pair and sync * The library closes (cache is cleared) This means `local://` URIs can reference any device in the library, not just the current device. ### Cloud Volume Lookup Cloud volumes use an O(1) mount point cache for fast lookups. The cache maps mount point strings (e.g., `"s3://my-bucket"`) to volume fingerprints. For volumes added before the cache was implemented, a linear scan serves as a fallback. ### Slug Collisions If two devices would generate the same slug, the second device must be renamed. There's no automatic disambiguation. ## Best Practices ### URI Display Use `display()` to convert SdPath to a user-facing URI string. The method generates the appropriate format automatically based on the path type. ### URI Parsing Use `from_uri()` when parsing user input. The method parses service-native URIs and validates the format. ### Device Naming Choose distinct device names to avoid slug collisions. Include location or purpose in names: * "jamies-macbook-home" * "jamies-macbook-work" * "home-server-basement" * "backup-nas-office" ### Cloud Mount Points Spacedrive ensures cloud mount points are unique by appending `-2`, `-3` if collisions occur: ``` s3://my-bucket ← First S3 volume with this bucket s3://my-bucket-2 ← Second volume (different credentials or endpoint) ``` This enables multiple configurations for the same cloud resource. ## Related Documentation * [Devices](/docs/core/devices) - Device management and pairing * [Volumes](/docs/core/volumes) - Volume system and cloud integration * [Cloud Integration](/docs/core/cloud-integration) - Cloud storage details * [Data Model](/docs/core/data-model) - SdPath internal representation # API Source: https://v2.spacedrive.com/core/api The API infrastructure is under active development. Some features described here are planned but not yet fully implemented. This document reflects both current implementation and planned architecture. The API infrastructure provides a secure, unified entry point for all Spacedrive operations. It handles authentication, authorization, session management, and request routing across CLI, Tauri desktop app, and native applications. ## Architecture Overview All API requests flow through a common pipeline: ``` Application → SessionContext → ApiDispatcher → PermissionLayer → Operation ``` This design enforces security policies consistently while providing rich context to operations. ## Session Management Sessions encapsulate all request context, replacing simple parameter passing with structured metadata: ```rust theme={null} // Create a device session (current implementation) let session = SessionContext::device_session(device_uuid, device_name) .with_library(library_uuid); // Session includes pre-configured permissions and metadata ``` Sessions include: **Authentication Info**: Device or user credentials and authorization level. **Library Context**: Currently selected library for scoped operations. **Permission Set**: Granular permissions for the session. **Request Metadata**: Tracking information for auditing and debugging. ## API Dispatcher The dispatcher provides a unified interface for all operations: ```rust theme={null} // Execute a library action let result = api.execute_library_action( CreateLocationAction { path: "/Users/data" }, session ).await?; // Execute a core query let libraries = api.execute_core_query( ListLibrariesQuery {}, session ).await?; ``` The dispatcher automatically: * Validates session permissions * Ensures library context for library operations * Tracks request metadata * Converts errors to API errors ## Permission System Permissions control access to specific operations: ```rust theme={null} #[derive(Debug, Clone)] pub struct PermissionSet { pub core: CorePermissions, pub library: LibraryPermissions, pub network: NetworkPermissions, pub jobs: JobPermissions, } ``` Each category has granular permissions: ```rust theme={null} pub struct LibraryPermissions { pub read_entries: bool, pub write_entries: bool, pub manage_locations: bool, pub manage_tags: bool, pub execute_jobs: bool, } ``` ### Permission Enforcement Configure enforcement behavior: ```rust theme={null} // Development: Permissive mode (allows all operations) let api = ApiDispatcher::permissive(core_context); // Production: Enforce permissions let api = ApiDispatcher::new(core_context); ``` ### Authorization Levels Four hierarchical levels provide increasing access: **None**: No authentication required (public operations only). **Device**: Authenticated device with basic permissions. **User**: Authenticated user with full library access. **Admin**: System administrator with all permissions. Higher levels inherit permissions from lower levels. ## Error Handling API errors provide structured information for clients: ```rust theme={null} pub enum ApiError { // Authentication/authorization failures Unauthorized { required_level: AuthLevel }, PermissionDenied { operation: String, permission: String }, // Validation errors ValidationError { field: String, message: String }, InvalidInput { details: String }, // Execution errors OperationFailed { operation: String, error: String }, ResourceNotFound { resource: String, id: String }, // System errors DatabaseError(String), InternalError(String), } ``` Errors automatically map to HTTP status codes for REST endpoints. ## Middleware Pipeline Middleware pipeline is partially implemented. The infrastructure exists but middleware chaining is not yet active. Cross-cutting concerns are handled through composable middleware: ```rust theme={null} let pipeline = MiddlewarePipeline::new() .with_logging() .with_metrics() .with_rate_limiting(); ``` ### Logging Middleware Tracks all requests with timing information: ``` [API] files.copy started (request_id: 7f3a2b1c) [API] files.copy completed in 145ms (request_id: 7f3a2b1c) ``` ### Metrics Middleware Records operation metrics for monitoring: * Request count by operation * Response times (p50, p90, p99) * Error rates by type * Active request count ## Request Sources Track where API calls originate: ```rust theme={null} pub enum RequestSource { Cli, // Command-line interface Swift, // iOS/macOS native application Internal, // Internal system calls Other(String), // Other sources (including Tauri desktop app) } ``` Tauri desktop app currently uses `Other("tauri")` or `Internal`. A dedicated `Tauri` variant is planned. This enables source-specific behavior like CLI-friendly error messages. ## API Discovery API discovery is a planned feature, not yet implemented. Applications will be able to query available operations: ```rust theme={null} // Planned feature let surface = api.describe_api(); for op in surface.operations { println!("{} - {}", op.name, op.description); println!(" Permissions: {:?}", op.required_permissions); println!(" Auth Level: {:?}", op.required_auth_level); } ``` This will power dynamic UI generation and permission checking. ## Integration Examples ### CLI Integration ```rust theme={null} // Create session from CLI context let session = api.create_base_session()? .with_library(current_library_id()); // Execute operation match api.execute_library_action(action, session).await { Ok(result) => println!("Success: {:?}", result), Err(ApiError::InsufficientPermissions { reason }) => { eprintln!("Permission denied: {}", reason); } Err(e) => eprintln!("Error: {}", e), } ``` ### Tauri Integration The Tauri desktop app integrates with the core through Rust FFI: ```rust theme={null} // Tauri command handlers call the API dispatcher #[tauri::command] async fn create_location( path: String, state: tauri::State<'_, AppState>, ) -> Result { let session = state.api.create_base_session() .map_err(|e| e.to_string())? .with_library(state.current_library_id); state.api.execute_library_action( CreateLocationAction { path }, session ).await.map_err(|e| e.to_string()) } ``` The Tauri app can run the daemon in two modes: * **In-Process**: Daemon runs within the Tauri app process * **Background Process**: Daemon runs as a separate system process (requires macOS entitlements) See [apps/tauri/DAEMON\_SETUP.md](../../apps/tauri/DAEMON_SETUP.md) for configuration details. ### Swift Integration ```swift theme={null} // Swift SDK uses generated types with session management let session = SessionContext( auth: deviceAuth, library: currentLibrary.id, source: .swift ) let location = try await api.libraries.createLocation( CreateLocationInput(path: "/Users/data"), session: session ) ``` ## Security Best Practices **Always use strict permissions in production**: Development warnings help identify missing permissions during development. **Validate library context**: Library operations must have `current_library_id` set in the session. **Track request metadata**: Use request IDs for debugging distributed operations. **Handle errors appropriately**: Convert internal errors to user-friendly messages at the boundary. ## Future Enhancements Planned improvements include: **User Authentication**: OAuth and session token support. **Rate Limiting**: Per-user and per-operation limits. **Request Caching**: Smart caching for read operations. **WebSocket Support**: Real-time operation subscriptions. The API infrastructure is designed to be transport-agnostic. While examples show Rust usage, the same patterns apply to REST endpoints and FFI boundaries. # Architecture Overview Source: https://v2.spacedrive.com/core/architecture Spacedrive operates as a distributed, local-first system. Your data stays on your devices. A Rust core manages everything through a Virtual Distributed File System (VDFS). No cloud servers control your files. ## System Design The architecture follows a client-server pattern on your own hardware. A daemon process runs the core engine. Clients connect to access functionality. Every device functions as an equal peer in the network. The daemon runs continuously in the background, indexing files and syncing data even when no UI is open. ## Core Components ### The Spacedrive Daemon The daemon is a headless process that runs the VDFS core. It manages the library database, executes background jobs, and exposes an RPC interface for clients. The daemon handles three primary responsibilities: 1. Core engine lifecycle management 2. Background task execution (indexing, sync, analysis) 3. Client communication through RPC ### Client Applications Clients provide the user interface without containing business logic. The desktop app, mobile app, and CLI all connect to the daemon to execute operations. This separation keeps interfaces lightweight and ensures consistent behavior across platforms. ### Communication Protocol Spacedrive implements Command Query Responsibility Segregation (CQRS) over RPC. Every operation falls into one of two categories: **Commands** change system state. They follow a three-phase lifecycle: ``` Preview → Commit → Verify ``` This ensures mutations are safe and auditable. Moving a file first previews the change, commits the operation, then verifies completion. **Queries** read data without side effects. Listing files or searching tags executes instantly without modifying state. The strict separation between commands and queries prevents accidental data modification during read operations. ## Code Organization ### Operations (`core/src/ops`) Operations implement the CQRS handlers. Each domain has its own module: * `ops/entry` - File and folder operations * `ops/tag` - Tag management * `ops/location` - Location indexing * `ops/collection` - Collection handling This modular structure keeps related functionality together while maintaining clear boundaries between domains. ### Services (`core/src/service`) Services orchestrate complex processes using lower-level operations: **NetworkService** manages peer-to-peer connections between devices. **SyncService** coordinates metadata synchronization across the network. **JobManager** executes durable background tasks like file analysis and thumbnail generation. Services run continuously, responding to events and coordinating between different parts of the system. ## Mobile Architecture iOS and Android apps embed the entire Rust core directly in the application binary. This embedded core enables mobile devices to function as complete Spacedrive nodes. Your phone can: * Index local photos and files * Manage its own SQLite database * Sync directly with other devices * Operate without a desktop connection The embedded core enables camera roll backup directly from your phone to any device on your network. ## System Lifecycle The typical execution flow follows these steps: ### Startup Sequence 1. **Daemon Launch**: The daemon starts when you launch the GUI app or run `sd start`. CLI users can optionally configure auto-start on login using `sd daemon install` on macOS. 2. **Library Load**: SQLite database opens and VDFS core initializes 3. **Service Activation**: Background services start and announce on the network 4. **Client Connection**: UI applications connect via RPC socket ### Runtime Operation During normal operation, clients send commands and queries to the daemon. The daemon processes requests, updates the database, and returns results. Background services continue indexing files and syncing with peers. ### Shutdown Process The daemon stops all services gracefully. Pending database transactions complete. Open connections close. The library saves its state for the next startup. ## Performance Characteristics The architecture optimizes for local-first operation: **Zero network latency** for local operations. File browsing and searching execute against the local database. **Parallel processing** across multiple CPU cores. The Rust core uses async/await for concurrent operations. **Minimal memory footprint** through lazy loading. Only active data loads into memory. **Background indexing** without blocking the UI. File analysis happens in separate worker threads. ## Security Model Every component enforces security at multiple levels: Database encryption protects data at rest. RPC authentication prevents unauthorized access. Peer verification ensures you only sync with trusted devices. The daemon's RPC interface binds to localhost only. Remote access requires explicit SSH tunneling or VPN configuration. ## Extension System Spacedrive provides a comprehensive SDK for building extensions that integrate seamlessly with core functionality. Extensions run in sandboxed WASM environments while maintaining full access to Spacedrive's capabilities. The SDK enables developers to: * Define custom data models that sync across devices * Build specialized interfaces for specific workflows * Create AI-powered agents for data analysis * Connect external services and platforms Extensions can share models and build on each other's data. A photo management extension can provide face data to a contacts extension. An email archive can feed into knowledge management tools. Learn more about building extensions in the [Spacedrive Developer SDK](/docs/extensions/introduction) documentation. ## Next Steps Understanding the architecture provides the foundation for working with Spacedrive. Explore these topics next: * [Libraries](/docs/core/libraries) - How Spacedrive organizes your data * [Networking](/docs/core/networking) - Peer-to-peer communication details * [Sync](/docs/core/sync) - Multi-device synchronization protocols # CLI Architecture Source: https://v2.spacedrive.com/core/cli Command-line interface for Spacedrive v2 ## Overview The Spacedrive CLI (`sd`) is a command-line interface for interacting with the Spacedrive daemon. It provides a comprehensive set of commands for managing libraries, files, devices, and daemon lifecycle. ## Architecture The CLI follows a client-daemon architecture: * **CLI Binary** (`sd-cli` / `sd`) - The client that sends commands * **Daemon Binary** (`sd-daemon`) - The background service that does the actual work * **Unix Socket** - Communication channel between CLI and daemon ``` ┌─────────┐ Unix Socket ┌──────────┐ │ sd │ ◄──────────────────► │ sd-daemon│ │ (client)│ │ (server) │ └─────────┘ └──────────┘ │ ▼ ┌──────────┐ │ Libraries│ └──────────┘ ``` ## Daemon Management ### Starting the Daemon ```bash theme={null} # Start in background sd start # Start in foreground (see logs) sd start --foreground ``` The daemon: * Runs as a background process * Listens on a Unix socket at `~/Library/Application Support/spacedrive/daemon/daemon.sock` * Manages all libraries and background tasks * Can run multiple instances with `--instance` flag ### Auto-Start on Login Install the daemon to start automatically on system boot: ```bash theme={null} # Install LaunchAgent (macOS) sd daemon install # Check status sd daemon status # Uninstall sd daemon uninstall ``` This creates a LaunchAgent at `~/Library/LaunchAgents/com.spacedrive.daemon.plist` that: * Starts daemon on user login * Restarts if it crashes * Logs to `~/Library/Application Support/spacedrive/logs/` ### Multi-Instance Support Run multiple daemon instances for different data directories: ```bash theme={null} # Start with custom instance name sd --instance work start sd --instance personal start # Each instance gets its own socket # daemon-work.sock # daemon-personal.sock ``` ## Configuration The CLI stores configuration in `~/Library/Application Support/spacedrive/cli.json`: ```json theme={null} { "current_library_id": "uuid-here", "update": { "repo": "spacedriveapp/spacedrive-cli-releases", "channel": "stable" } } ``` ### Config Commands ```bash theme={null} # View all configuration sd config show # Get specific value sd config get update.repo # Set value sd config set update.repo "your-org/releases-repo" ``` ## Auto-Update System The CLI includes a built-in update mechanism that fetches releases from a public GitHub repository. ### Update Architecture ``` ┌─────────┐ ┌────────────┐ │sd update│ ──── GitHub API ────────►│ Releases │ └─────────┘ │ Repository │ │ └────────────┘ │ Download binaries │ ▼ │ ┌─────────────────┐ │ │ sd-macos-arm64 │◄──────────────────────┘ │ sd-daemon-... │ └─────────────────┘ │ │ Atomic replacement ▼ ┌─────────────────┐ │ Installed bins │ └─────────────────┘ ``` ### Update Process 1. **Check for updates**: Queries GitHub API for latest release 2. **Download binaries**: Fetches platform-specific binaries 3. **Verify integrity**: Checks file sizes match expected values 4. **Atomic replacement**: Replaces binaries with rollback on failure 5. **Restart daemon**: If daemon was running, restarts it ```bash theme={null} # Check and install updates sd update # Force reinstall current version sd update --force ``` ### Release Repository Setup The update system uses a public GitHub repository containing only releases (no source code): 1. Create public repo: `your-org/spacedrive-cli-releases` 2. For each release: * Create empty commit: `git commit --allow-empty -m "Release v0.1.0"` * Tag it: `git tag v0.1.0` * Create GitHub release with binaries as assets 3. Configure CLI: `sd config set update.repo "your-org/spacedrive-cli-releases"` The CI workflow automatically builds binaries for: * macOS (arm64, x86\_64) * Linux (x86\_64) - coming soon * Windows (x86\_64) - coming soon ## Command Structure All CLI commands follow this pattern: ```bash theme={null} sd [--data-dir PATH] [--instance NAME] [--format FORMAT] [args] ``` ### Global Flags * `--data-dir` - Override default data directory * `--instance` - Connect to specific daemon instance * `--format` - Output format: `human` (default) or `json` ### Core Commands | Command | Description | | ------------ | --------------------- | | `sd start` | Start the daemon | | `sd stop` | Stop the daemon | | `sd restart` | Restart the daemon | | `sd status` | Show system status | | `sd update` | Update CLI and daemon | ### Domain Commands | Command | Description | | ------------- | ------------------------ | | `sd library` | Manage libraries | | `sd location` | Manage indexed locations | | `sd file` | File operations | | `sd index` | Indexing operations | | `sd search` | Search files | | `sd tag` | Tag management | | `sd volume` | Volume operations | | `sd device` | Device management | | `sd job` | Job control | | `sd network` | Networking and pairing | | `sd logs` | View daemon logs | | `sd config` | Configuration management | | `sd daemon` | Daemon lifecycle | ## Binary Distribution For development and testing, binaries can be distributed without building from source: 1. **Build release binaries**: ```bash theme={null} cargo build --release --bin sd-cli --bin sd-daemon ``` 2. **Copy both binaries** to target machine: * `sd-cli` → rename to `sd` * `sd-daemon` → keep as `sd-daemon` 3. **Place in PATH**: ```bash theme={null} mv sd ~/.local/bin/ mv sd-daemon ~/.local/bin/ chmod +x ~/.local/bin/sd ~/.local/bin/sd-daemon ``` 4. **Remove quarantine** (macOS): ```bash theme={null} xattr -d com.apple.quarantine ~/.local/bin/sd xattr -d com.apple.quarantine ~/.local/bin/sd-daemon ``` Both binaries must be in the same directory as the CLI expects to find the daemon binary in its parent directory. ## Development ### Building ```bash theme={null} # Build CLI only cargo build --package sd-cli # Build both CLI and daemon cargo build --bin sd-cli --bin sd-daemon # Release build cargo build --release --bin sd-cli --bin sd-daemon ``` ### Code Structure ``` apps/cli/ ├── src/ │ ├── main.rs # Entry point, daemon lifecycle │ ├── config.rs # CLI configuration │ ├── context.rs # Execution context │ ├── domains/ # Command domains │ │ ├── config/ # Config commands │ │ ├── daemon/ # Daemon management │ │ ├── update/ # Auto-update system │ │ ├── library/ # Library operations │ │ ├── location/ # Location operations │ │ └── ... │ └── util/ # Shared utilities └── Cargo.toml core/ └── src/ └── bin/ └── daemon.rs # Daemon binary ``` ### Adding New Commands 1. Create a new module in `domains/` 2. Define command enum with clap derives 3. Implement `run()` function 4. Register in `domains/mod.rs` and `main.rs` Example: ```rust theme={null} // domains/myfeature/mod.rs use anyhow::Result; use clap::Subcommand; #[derive(Subcommand, Debug)] pub enum MyFeatureCmd { /// Do something Action { arg: String }, } pub async fn run(ctx: &Context, cmd: MyFeatureCmd) -> Result<()> { match cmd { MyFeatureCmd::Action { arg } => { // Implementation } } Ok(()) } ``` ## Security Considerations ### Instance Name Validation Instance names are validated to prevent path traversal: * Only alphanumeric, dash, and underscore allowed * Max 64 characters * Cannot be empty ### Binary Verification The update system verifies downloaded binaries: * File size must match release asset size * Future: SHA256 checksum verification ### Daemon Socket Permissions The Unix socket is created with restrictive permissions (user-only access). ## Troubleshooting ### Daemon Won't Start ```bash theme={null} # Check if already running sd status # View logs sd logs follow # Reset data and restart sd restart --reset ``` ### Update Fails ```bash theme={null} # Check configuration sd config show # Verify repo is accessible curl https://api.github.com/repos/YOUR_ORG/YOUR_REPO/releases/latest # Force clean reinstall sd update --force ``` ### Socket Connection Errors The daemon socket is located at: ``` ~/Library/Application Support/spacedrive/daemon/daemon.sock ``` If connection fails: 1. Verify daemon is running: `ps aux | grep sd-daemon` 2. Check socket exists: `ls -la ` 3. Restart daemon: `sd restart` # Cloud Integration Source: https://v2.spacedrive.com/core/cloud-integration Spacedrive treats cloud storage as native volumes, enabling seamless file management across local and cloud storage. The system leverages OpenDAL to support over 40 cloud services while maintaining consistent performance and behavior. ## How Cloud Volumes Work Cloud volumes appear and function identically to local volumes in Spacedrive. When you connect a cloud service, it becomes a volume with the same capabilities as your local drives. Files are indexed, searchable, and manageable without downloading entire contents. The key innovation is content identification consistency. Whether a file lives on your SSD or in S3, Spacedrive generates the same content hash, enabling accurate deduplication and tracking across all storage locations. ### Connecting Cloud Storage Add cloud storage through the action system: ```rust theme={null} let input = VolumeAddCloudInput { service: CloudServiceType::S3, display_name: "My Bucket".to_string(), config: CloudStorageConfig::S3 { bucket: "my-bucket".to_string(), region: "us-west-2".to_string(), access_key_id: "...".to_string(), secret_access_key: "...".to_string(), endpoint: None, }, }; dispatcher.execute_library_action::(input, ctx).await?; ``` Once connected, the volume behaves like any other storage device. Browse directories, search files, and perform operations without thinking about the underlying storage type. Once indexed, you can search, browse thumbnails, and view metadata for cloud files even when offline. Only file content operations require an active internet connection. ### Path Representation Cloud paths use service-native URIs that match industry standards: ``` s3://my-bucket/photos/vacation.jpg gdrive://My Drive/Documents/contract.pdf onedrive://Documents/budget.xlsx dropbox://Apps/Spacedrive/backup.zip azblob://container/data/export.csv gcs://bucket/logs/app.log ``` These URIs match the format used by AWS CLI, gsutil, and other cloud tools. Copy a path from Spacedrive and paste it directly into cloud provider CLI commands. Internally, Spacedrive uses the `SdPath` enum with identity-based addressing: ```rust theme={null} pub enum SdPath { Physical { device_slug: String, // URL-safe device identifier path: PathBuf, }, Cloud { service: CloudServiceType, // S3, GoogleDrive, etc. identifier: String, // Bucket/drive/container name path: String, // Path within the service }, Content { content_id: Uuid, }, } ``` The service and identifier are stored directly in the path, enabling self-contained cloud addressing. The VolumeManager maintains an in-memory cache mapping mount points to volume fingerprints for O(1) lookups during volume resolution. See [Unified Addressing](/docs/core/addressing) for complete details on URI formats and resolution. ## Supported Services Spacedrive supports all major cloud providers through OpenDAL: **Object Storage**: S3, Azure Blob, Google Cloud Storage, MinIO, Backblaze B2, Cloudflare R2 **Consumer Cloud**: Google Drive, Dropbox, OneDrive, iCloud Drive, pCloud, MEGA **Enterprise Storage**: SharePoint, Box, Nextcloud, Seafile, WebDAV **Regional Services**: Alibaba Cloud OSS, Tencent COS, Huawei OBS, Baidu BOS Each service maintains its native features while presenting a unified interface through Spacedrive. ## Content Identification Spacedrive uses its sampling algorithm for all files, regardless of storage location. For files over 100KB, only 58KB of data transfers to generate the content hash: * 8KB header sample * 40KB from four evenly-spaced positions * 8KB footer sample This approach ensures identical files have matching identities whether stored locally or in the cloud. A photo on Google Drive and its copy on your laptop share the same content hash, enabling true cross-platform deduplication. ### Performance Impact | File Size | Data Transfer | Identification Time (100 Mbps) | | --------- | ------------- | ------------------------------ | | 10 MB | 10 MB | 0.8 seconds | | 100 MB | 58 KB | 0.005 seconds | | 1 GB | 58 KB | 0.005 seconds | | 10 GB | 58 KB | 0.005 seconds | The constant transfer size for large files makes cloud indexing predictable and fast. ## Credential Management Cloud credentials are encrypted with XChaCha20-Poly1305 using your library key. Credentials store in your OS keyring: Keychain on macOS, Credential Manager on Windows, Secret Service on Linux. Each library maintains separate credentials for isolation. ```rust theme={null} let credential_manager = CloudCredentialManager::new(library_key_manager); credential_manager .store_credential(library_id, &volume_fingerprint, &credential) .await?; ``` API keys and access credentials remain encrypted at rest. Removing a cloud volume purges its credentials from storage immediately. Spacedrive never stores credentials in plain text or transmits them outside the secure credential flow. ## Indexing Cloud Content The indexer handles cloud volumes intelligently: **Discovery Phase**: Lists directories using native cloud APIs for efficiency **Processing Phase**: Creates database entries identical to local files. Cloud entries are treated as new during initial indexing since metadata-based change detection is not yet implemented. **Content Phase**: Uses ranged reads to generate content hashes without full downloads **Aggregation Phase**: Calculates directory sizes and statistics The indexer protects the location root entry from deletion during change detection. This entry represents the mount point itself rather than a filesystem object, ensuring the location remains valid throughout indexing. Cloud indexing supports the same modes as local indexing: ```rust theme={null} // Quick scan for navigation let path = SdPath::from_uri_with_context( "s3://my-bucket/", &context ).await?; let config = IndexerJobConfig::ui_navigation(path, IndexMode::Shallow); // Deep scan with content identification let path = SdPath::from_uri_with_context( "s3://my-bucket/", &context ).await?; let config = IndexerJobConfig::new(path, IndexMode::Content); ``` ## File Operations Standard file operations work transparently across cloud volumes: ```rust theme={null} // Copy from cloud to local let src = SdPath::from_uri_with_context( "gdrive://Work/photos/vacation.jpg", &context ).await?; let dst = SdPath::from_uri_with_context( "local://macbook/backup/", &context ).await?; let input = FileCopyInput::new(vec![src], dst); let result = dispatcher.execute_library_action::( input, session_context ).await?; // Move between cloud services let src = SdPath::from_uri_with_context( "s3://archive/report.pdf", &context ).await?; let dst = SdPath::from_uri_with_context( "gdrive://Work/documents/", &context ).await?; let job = FileCopyJob::new( SdPathBatch::new(vec![src]), dst ).with_move(true); library.jobs().dispatch(job).await?; ``` Operations optimize based on source and destination capabilities. Same-cloud moves use native APIs when available. Cross-cloud transfers stream data efficiently without temporary files. Large file operations between cloud services depend on your internet bandwidth. Monitor transfer progress through the job system. ## Caching Strategy Cloud volumes implement intelligent caching: **Metadata Cache**: Directory listings and file information cache for 5 minutes **Content Cache**: Recently accessed file chunks remain in memory **Thumbnail Cache**: Generated thumbnails store locally like any other sidecar Cache invalidation happens automatically on file modifications. Manual refresh forces fresh metadata retrieval from cloud services. ## Best Practices ### Organization Structure cloud volumes based on access patterns: * Archive volumes for infrequent access * Working volumes for active projects * Backup volumes for redundancy ### Performance Optimize cloud operations: * Index during off-peak hours for large volumes * Enable shallow indexing for frequently changing directories * Use persistent indexing for stable archives ### Security Protect cloud data: * Enable two-factor authentication on cloud accounts * Rotate API keys periodically * Review cloud volume access in library settings ## Limitations Cloud volumes have some constraints: **Network Dependency**: Operations require internet connectivity **API Rate Limits**: Some services throttle requests during heavy usage **Cost Considerations**: Cloud providers may charge for API calls and bandwidth **Feature Parity**: Not all cloud services support all operations (some are read-only) ## Common Patterns ### Cloud Backup Set up automatic cloud backup: ```rust theme={null} // Add cloud volume as backup destination let backup_volume = volume_manager .add_cloud_volume(CloudServiceType::S3, backup_credentials) .await?; // Create backup job let src = SdPath::from_uri_with_context( "local://macbook/Users/james/Documents/important/", &context ).await?; let dst = SdPath::from_uri_with_context( "s3://backup-bucket/backups/", &context ).await?; let backup_job = FileCopyJob::new( SdPathBatch::new(vec![src]), dst ).with_options(CopyOptions { preserve_timestamps: true, verify_checksum: true, ..Default::default() }); library.jobs().dispatch(backup_job).await?; ``` ### Multi-Cloud Search Search across all storage locations: ```rust theme={null} // Search includes cloud volumes automatically let results = search_manager .search("vacation photos") .across_all_volumes() .await?; ``` ### Hybrid Workflows Combine local and cloud storage: ```rust theme={null} // Move old projects to cloud archive let src = SdPath::from_uri_with_context( "local://macbook/Users/james/projects/MyVideoProject", &context ).await?; let dst = SdPath::from_uri_with_context( "s3://archive/projects/archived/", &context ).await?; let move_job = FileCopyJob::new(src, dst).with_move(true); // Schedule regular archival scheduler.add_recurring_job(move_job, Schedule::Weekly); ``` ## Troubleshooting ### Authentication Issues If cloud authentication fails: 1. Verify credentials in cloud provider dashboard 2. Check for expired tokens (OAuth services) 3. Confirm API permissions include required scopes 4. Review firewall settings for cloud endpoints ### Slow Performance For sluggish cloud operations: 1. Check internet connection speed 2. Verify you're not hitting API rate limits 3. Enable metadata caching if disabled 4. Consider indexing during off-peak hours ### Sync Conflicts When files change outside Spacedrive: 1. Manually refresh the cloud volume 2. Re-index affected directories 3. Check cloud provider's version history 4. Resolve conflicts through the UI Enable cloud provider webhooks when available for real-time change notifications. ## Known Issues **Change Detection**: Cloud files are treated as new on each reindex. The system cannot yet detect modifications using cloud provider metadata. This means reindexing will recreate entries rather than updating them. **File Watcher**: Cloud volumes do not support real-time file monitoring. Changes made outside Spacedrive require manual refresh or reindexing to appear. **OAuth Tokens**: Token refresh is not yet implemented. You must re-authenticate manually when tokens expire. ## Related Documentation * [Volumes](/docs/core/volumes) - Volume system fundamentals * [Indexing](/docs/core/indexing) - How Spacedrive indexes files * [Jobs](/docs/core/jobs) - Monitor long-running operations * [Security](/docs/security) - Credential and encryption details # Data Model Source: https://v2.spacedrive.com/core/data-model Spacedrive's data model powers a Virtual Distributed File System (VDFS) that unifies files across all your devices. It enables instant organization, content deduplication, and powerful semantic search while maintaining performance at scale. ## Core Design The system separates concerns into distinct entities: * **SdPath** - Address any file; local, peer device, cloud, or by content ID * **Entry** - File and directory representation * **ContentIdentity** - Unique file content for deduplication * **UserMetadata** - Organization data (tags, notes, favorites) * **Location** - Monitored directories * **Device** - Individual machines in your network * **Volume** - Real storage volumes, local, external and cloud * **Sidecar** - Derivative and associated data ## Domain vs. Database Entity Models It is critical to understand the distinction between two data modeling layers in Spacedrive: * **Domain Models**: These are the rich objects used throughout the application's business logic. They contain computed fields and methods that provide a powerful, high-level interface to the underlying data. For example, the `domain::File` structure represents several database models such as `entities::entry`, `entities::content_identity`, and `entities::user_metadata`. * **Database Entity Models**: These are simpler structs that map directly to the database tables (e.g., `entities::entry`). They represent the raw, persisted state of the data and are optimized for storage and query performance. The code examples in this document generally refer to the database entity models to accurately represent what is stored on disk. The domain models provide a convenient abstraction over this raw data. ## SdPath The `SdPath` enum is the universal addressing system for files across all storage backends: ```rust theme={null} pub enum SdPath { /// A direct pointer to a file on a specific local device Physical { device_slug: String, // The device slug (e.g., "jamies-macbook") path: PathBuf, // The local filesystem path }, /// A cloud storage path within a cloud volume Cloud { service: CloudServiceType, // The cloud service type (S3, GoogleDrive, etc.) identifier: String, // The cloud identifier (bucket name, drive name, etc.) path: String, // The cloud-native path (e.g., "photos/vacation.jpg") }, /// An abstract, location-independent handle via content ID Content { content_id: Uuid, // The unique content identifier }, /// A derivative data file (thumbnail, OCR text, embedding, etc.) Sidecar { content_id: Uuid, // The content this sidecar is derived from kind: SidecarKind, // The type of sidecar (thumb, ocr, embeddings, etc.) variant: SidecarVariant, // The specific variant (e.g., "grid@2x", "1080p") format: SidecarFormat, // The storage format (webp, json, msgpack, etc.) }, } ``` This enum enables transparent operations across local filesystems, cloud storage, content-addressed files, and derivative data. The `Physical` variant handles traditional filesystem paths, `Cloud` manages cloud storage locations, `Content` enables deduplication-aware operations by referencing files by their content, and `Sidecar` addresses generated derivative data like thumbnails and embeddings. ### Unified Addressing Spacedrive displays paths using a unified addressing scheme that matches industry standards: ```rust theme={null} // Display user-friendly URIs let uri = sd_path.display_with_context(&context).await; // Examples: // Physical: "local://jamies-macbook/Users/james/Documents/report.pdf" // Cloud: "s3://my-bucket/photos/vacation.jpg" // Content: "content://550e8400-e29b-41d4-a716-446655440000" ``` The addressing system uses: * **Device slugs** for local paths (e.g., `local://jamies-macbook/path`) * **Service-native URIs** for cloud storage (e.g., `s3://`, `gdrive://`, `onedrive://`) * **Content UUIDs** for location-independent references See [Unified Addressing](/docs/core/addressing) for complete details on URI formats and resolution. ## Entry The `Entry` is the core entity representing a file or directory. The database entity (`entities::entry::Model`) stores the fundamental hierarchy and metadata. ```rust Expandable theme={null} theme={null} pub struct Entry { pub id: i32, // Database primary key pub uuid: Option, // Global identifier (assigned immediately during indexing) pub name: String, // File or directory name pub kind: i32, // 0=File, 1=Directory, 2=Symlink pub extension: Option, // File extension (without dot) // Relationships pub parent_id: Option, // Parent directory (self-referential) pub metadata_id: Option, // User metadata (when present) pub content_id: Option, // Content identity (for deduplication) pub volume_id: Option, // Volume this entry resides on (determines sync ownership) // Size and hierarchy pub size: i64, // File size in bytes pub aggregate_size: i64, // Total size including children pub child_count: i32, // Direct children count pub file_count: i32, // Total files in subtree // Filesystem metadata pub permissions: Option, // Unix-style permissions pub inode: Option, // Platform-specific identifier // Timestamps pub created_at: DateTime, pub modified_at: DateTime, pub accessed_at: Option>, pub indexed_at: Option>, // When this entry was indexed, used for sync } ``` ### Ownership via Volume Entries inherit sync ownership from their volume, not directly from a device. When you plug a portable drive into a different machine, updating the volume's device reference instantly transfers ownership of all entries on that volume. No bulk updates needed. This design enables portable storage to move seamlessly between devices while maintaining correct sync behavior. ### UUID Assignment All entries receive UUIDs immediately during indexing for UI caching compatibility. However, sync readiness is determined separately: * **Directories** - Sync ready immediately (no content to identify) * **Empty files** - Sync ready immediately (size = 0) * **Regular files** - Sync ready only after content identification (content\_id present) This ensures files sync only after proper content identification, while allowing the UI to cache and track all entries from the moment they're discovered. ### Hierarchical Queries A closure table enables efficient ancestor/descendant queries: ```rust theme={null} pub struct EntryClosure { pub ancestor_id: i32, pub descendant_id: i32, pub depth: i32, // 0=self, 1=child, 2=grandchild } ``` This structure allows instant queries like "find all files under this directory" without recursion. ## ContentIdentity ContentIdentity represents unique file content, enabling deduplication across your entire library: ```rust Expandable theme={null} theme={null} pub struct ContentIdentity { pub id: i32, pub uuid: Option, // Globally deterministic from content_hash only // Hashing pub content_hash: String, // Fast sampled hash (for deduplication) pub integrity_hash: Option, // Full hash (for validation) // Classification pub mime_type_id: Option, // FK to MimeType pub kind_id: i32, // FK to ContentKind (enum) // Content metadata pub text_content: Option, // Extracted text pub image_media_data_id: Option, // FK to image-specific metadata pub video_media_data_id: Option, // FK to video-specific metadata pub audio_media_data_id: Option, // FK to audio-specific metadata // Statistics pub total_size: i64, // Size of one instance pub entry_count: i32, // Entries sharing this content (in library) pub first_seen_at: DateTime, pub last_verified_at: DateTime, } ``` ### Two-Stage Hashing **Content Hash** - Fast sampling for deduplication **Integrity Hash** - Full file hash for verification ### Deduplication Multiple entries can point to the same ContentIdentity. When you have duplicate files, they all reference a single ContentIdentity record. ## UserMetadata UserMetadata stores how you organize your files: ```rust Expandable theme={null} theme={null} pub struct UserMetadata { pub id: i32, pub uuid: Uuid, // Scope - exactly one must be set pub entry_uuid: Option, // File-specific metadata pub content_identity_uuid: Option, // Content-universal metadata // Organization pub notes: Option, pub favorite: bool, pub hidden: bool, pub custom_data: Json, // Extensible JSON fields pub created_at: DateTime, pub updated_at: DateTime, } ``` ### Metadata Scoping UserMetadata can be scoped two ways: **Entry-Scoped** - Applies to a specific file instance **Content-Scoped** - Applies to all instances of the same content ## Semantic Tags Spacedrive uses a graph-based tagging system that understands context and relationships: ```rust Expandable theme={null} theme={null} pub struct Tag { pub id: i32, pub uuid: Uuid, // Core identity pub canonical_name: String, // Primary name pub display_name: Option, // Display variant // Semantic variants pub formal_name: Option, // Formal variant pub abbreviation: Option, // Short form pub aliases: Option, // Vec as JSON // Context pub namespace: Option, // Disambiguation namespace pub tag_type: String, // "standard" | "organizational" | "privacy" | "system" // Visual properties pub color: Option, // Hex color pub icon: Option, // Icon identifier pub description: Option, // Behavior pub is_organizational_anchor: bool, pub privacy_level: String, // "normal" | "archive" | "hidden" pub search_weight: i32, // Search ranking // Extensibility pub attributes: Option, // HashMap as JSON pub composition_rules: Option, // Vec as JSON pub created_at: DateTime, pub updated_at: DateTime, pub created_by_device: Option, } ``` ### Polymorphic Naming The same name can mean different things in different contexts: ```rust theme={null} // Different tags with same name Tag { canonical_name: "vacation", namespace: "travel", uuid: uuid_1 } Tag { canonical_name: "vacation", namespace: "work", uuid: uuid_2 } ``` ### Tag Relationships Tags form hierarchies and semantic networks: ```rust theme={null} pub struct TagRelationship { pub parent_tag_id: i32, pub child_tag_id: i32, pub relationship_type: String, // "parent_child" | "synonym" | "related" pub strength: f32, // 0.0-1.0 } ``` Examples: * Parent/Child: "Animals" → "Dogs" → "Puppies" * Synonyms: "Car" "Automobile" * Related: "Photography" "Camera" Tag hierarchies use closure tables for efficient ancestor/descendant queries, similar to entries. ## Location Locations are directories that Spacedrive monitors: ```rust Expandable theme={null} theme={null} pub struct Location { pub id: i32, pub uuid: Uuid, pub device_id: i32, // Device that owns this location pub entry_id: Option, // Root entry for this location (nullable during sync) pub name: Option, // User-friendly name // Indexing configuration pub index_mode: String, // "shallow" | "content" | "deep" pub scan_state: String, // "pending" | "scanning" | "completed" | "error" // Statistics pub last_scan_at: Option>, pub error_message: Option, pub total_file_count: i64, pub total_byte_size: i64, pub job_policies: Option, // JSON-serialized JobPolicies (local config) pub created_at: DateTime, pub updated_at: DateTime, } ``` ### Index Modes * **Shallow** - Metadata only (fast, no content hashing) * **Content** - Metadata + deduplication * **Deep** - Full analysis including media extraction ## Device Devices represent machines in your Spacedrive network: ```rust Expandable theme={null} theme={null} pub struct Device { pub id: i32, pub uuid: Uuid, pub name: String, pub slug: String, // URL-safe unique identifier // System information pub os: String, pub os_version: Option, pub hardware_model: Option, // Network pub network_addresses: Json, // Array of IP addresses pub is_online: bool, pub last_seen_at: DateTime, // Capabilities pub capabilities: Json, // Feature flags // Sync pub sync_enabled: bool, pub last_sync_at: Option>, pub created_at: DateTime, pub updated_at: DateTime, } ``` ## Volume Volumes track physical drives and partitions: ```rust Expandable theme={null} theme={null} pub struct Volume { pub id: i32, pub uuid: Uuid, pub device_id: Uuid, // FK to Device pub fingerprint: String, // Stable identifier across mounts pub display_name: Option, pub mount_point: Option, pub file_system: Option, // Capacity pub total_capacity: Option, pub available_capacity: Option, pub unique_bytes: Option, // Deduplicated storage usage // Performance pub read_speed_mbps: Option, pub write_speed_mbps: Option, pub last_speed_test_at: Option>, // Classification pub is_removable: Option, pub is_network_drive: Option, pub device_model: Option, pub volume_type: Option, pub is_user_visible: Option, // Visible in UI pub auto_track_eligible: Option, // Eligible for auto-tracking pub cloud_identifier: Option, // Cloud volume identifier // Tracking pub tracked_at: DateTime, pub last_seen_at: DateTime, pub is_online: bool, } ``` Volumes serve as the ownership anchor for entries. The `device_id` field determines which device owns all entries on this volume. When a portable drive moves between machines, updating this single field transfers ownership of the entire volume's contents. See [Library Sync](/docs/core/library-sync) for details on portable volume handling. ## Sidecar Sidecars store generated content like thumbnails: ```rust Expandable theme={null} theme={null} pub struct Sidecar { pub id: i32, pub uuid: Uuid, pub content_uuid: Uuid, // FK to ContentIdentity // Classification pub kind: String, // "thumbnail" | "preview" | "metadata" pub variant: String, // Size/quality variant pub format: String, // File format // Storage pub rel_path: String, // Relative path to sidecar pub source_entry_id: Option, // Reference to existing file // Metadata pub size: i64, pub checksum: Option, pub status: String, // "pending" | "processing" | "ready" | "error" pub source: Option, // Source of the sidecar pub version: i32, pub created_at: DateTime, pub updated_at: DateTime, } ``` Sidecars link to ContentIdentity, not Entry. This means one thumbnail serves all duplicate files. ## Extension Models Extensions create custom tables at runtime to store domain-specific data. These integrate seamlessly with core tagging and organization. The extension system is currently a work in progress. The API and implementation details described here are subject to change. ### Table Naming Extension tables use prefixed naming: ```sql theme={null} -- Photos extension creates: CREATE TABLE ext_photos_person ( id BLOB PRIMARY KEY, name TEXT NOT NULL, birth_date TEXT, metadata_id INTEGER NOT NULL, FOREIGN KEY (metadata_id) REFERENCES user_metadata(id) ); CREATE TABLE ext_photos_album ( id BLOB PRIMARY KEY, title TEXT NOT NULL, description TEXT, created_date TEXT, metadata_id INTEGER NOT NULL, FOREIGN KEY (metadata_id) REFERENCES user_metadata(id) ); ``` ### Model Definition Extensions define models using SDK macros: ```rust theme={null} #[model( table_name = "person", version = "1.0.0", scope = "content", sync_strategy = "shared" )] struct Person { #[primary_key] id: Uuid, name: String, birth_date: Option, #[metadata] metadata_id: i32, // Links to UserMetadata } ``` ### Integration Benefits 1. **SQL Queries** - Direct database queries with JOINs and indexes 2. **Foreign Keys** - Referential integrity enforced by database 3. **Unified Organization** - Extension data can be tagged and searched 4. **Type Safety** - Compile-time schema validation ## Sync Architecture ### Device-Owned Resources **Entities**: Device, Volume, Location, Entry Ownership flows through volumes. A device owns its volumes. Locations and entries reference a volume, inheriting ownership from the volume's device. This indirection enables portable storage: when a drive moves between machines, updating the volume's device reference transfers ownership of all associated entries instantly. Only the owning device can modify these resources. Last state wins. ### Shared Resources **Entities**: Tag, UserMetadata, TagRelationship, ContentIdentity Any device can modify shared resources. Changes are ordered using Hybrid Logical Clocks for consistency across devices. ### Foreign Key Mapping During sync, integer IDs map to UUIDs for wire format, then back to local IDs on receiving devices. ## Query Patterns Find files with a specific tag: ```rust theme={null} Entry::find() .inner_join(UserMetadata) .inner_join(UserMetadataTag) .inner_join(Tag) .filter(tag::Column::CanonicalName.eq("vacation")) .all(db).await? ``` Find duplicate files: ```rust theme={null} ContentIdentity::find() .find_with_related(Entry) .filter(content_identity::Column::EntryCount.gt(1)) .all(db).await? ``` ## Performance Optimizations 1. **Closure Tables** - O(1) hierarchical queries 2. **Directory Path Table** - The full path for every directory is stored in a dedicated `directory_paths` table. This is the source of truth for directory paths and avoids storing redundant path information on every file entry, making path-based updates significantly more efficient. 3. **Aggregate Columns** - Pre-computed size/count fields 4. **Deterministic UUIDs** - Consistent references across devices 5. **Integer PKs** - Fast local joins, UUIDs only for sync The data model provides a foundation for powerful file management that scales from single devices to complex multi-device networks. # Database Source: https://v2.spacedrive.com/core/database Spacedrive uses SQLite with SeaORM for database operations. The database is embedded within each library, providing fast local queries and simple backup strategies. ## Technology Stack We chose SQLite and SeaORM for specific technical reasons: **SQLite** provides embedded database functionality without external dependencies. It runs in-process with zero network overhead and supports advanced features like WAL mode for concurrent access. **SeaORM** offers type-safe database access in Rust. It generates compile-time checked queries, manages schema migrations automatically, and provides connection pooling out of the box. This combination replaced our previous prisma-client-rust dependency, which was abandoned upstream. ## Database Configuration Each library configures SQLite for optimal performance: ```rust theme={null} use sea_orm::{Database, ConnectOptions}; async fn create_connection(database_url: &str) -> Result { let mut opt = ConnectOptions::new(database_url.to_owned()); opt.max_connections(10) .min_connections(1) .connect_timeout(Duration::from_secs(10)) .idle_timeout(Duration::from_secs(300)) .sqlx_logging(false); // Disable in production let db = Database::connect(opt).await?; // Configure SQLite for performance db.execute_unprepared("PRAGMA journal_mode = WAL").await?; db.execute_unprepared("PRAGMA synchronous = NORMAL").await?; db.execute_unprepared("PRAGMA cache_size = 10000").await?; db.execute_unprepared("PRAGMA temp_store = MEMORY").await?; Ok(db) } ``` These pragmas enable: **WAL Mode**: Allows readers and writers to work concurrently. **Normal Synchronous**: Balances durability with performance. **Large Cache**: Keeps frequently accessed data in memory. **Memory Temp Store**: Uses RAM for temporary tables. ## Storage Efficiency Our schema design minimizes storage overhead through careful optimization. For a typical library with 100,000 files: | Component | Size | Notes | | ------------ | -------- | --------------------------------- | | **Database** | \~650 MB | Includes all metadata and indexes | | **Indexes** | \~150 MB | Optimized for common queries | | **WAL File** | `<32 MB` | Write-ahead log for durability | Compared to naive implementations, this represents a 70% reduction in storage requirements. ## Migration System SeaORM manages schema changes through versioned migrations. Each migration defines forward and rollback operations: ```rust theme={null} use sea_orm_migration::prelude::*; #[derive(DeriveMigrationName)] pub struct Migration; #[async_trait::async_trait] impl MigrationTrait for Migration { async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { // Apply schema changes manager.create_table(...).await } async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> { // Revert changes manager.drop_table(...).await } } ``` The migration system tracks applied migrations in a `seaql_migrations` table. This ensures each migration runs exactly once. Apply migrations during library initialization: ```rust theme={null} use sea_orm_migration::MigratorTrait; // Apply pending migrations Migrator::up(db, None).await?; // Check migration status let applied = Migrator::status(db).await?; ``` ## Performance Optimizations ### Index Strategy Indexes are critical for query performance. We maintain indexes for: **UUID Lookups**: Every table with a UUID has a unique index for O(1) lookups. **Foreign Keys**: All foreign key columns are indexed for fast joins. **Common Filters**: Frequently queried columns like `kind`, `size`, and `favorite` have dedicated indexes. **Composite Indexes**: Multi-column indexes optimize specific query patterns. Create partial indexes for better performance: ```sql theme={null} -- Index only file entries, not directories CREATE INDEX idx_file_sizes ON entries(size) WHERE kind = 0; -- Index only favorited items CREATE INDEX idx_favorites ON user_metadata(uuid) WHERE favorite = 1; ``` ### Query Performance SeaORM automatically uses prepared statements for repeated queries. This avoids SQL parsing overhead and enables query plan caching. For UI responsiveness, always paginate large result sets: ```rust theme={null} let page_size = 50; let entries = Entry::find() .order_by_asc(entry::Column::Name) .limit(page_size) .offset(page * page_size) .all(db) .await?; ``` Use `select_only()` to fetch only required columns: ```rust theme={null} let names = Entry::find() .select_only() .column(entry::Column::Name) .into_tuple::() .all(db) .await?; ``` ### Connection Pooling SeaORM manages a connection pool automatically. Configure pool settings based on your workload: ```rust theme={null} opt.max_connections(10) // Maximum concurrent connections .min_connections(1) // Minimum idle connections .connect_timeout(Duration::from_secs(10)) .idle_timeout(Duration::from_secs(300)); ``` These settings balance resource usage with responsiveness. Most operations complete within a single connection. ## Backup and Recovery Libraries support multiple backup strategies: ### File-Based Backup The simplest backup method copies the database file: ```rust theme={null} use std::fs; async fn backup_database(library_path: &Path) -> Result<(), std::io::Error> { let db_path = library_path.join("database.db"); let backup_dir = library_path.join("backups"); fs::create_dir_all(&backup_dir)?; let timestamp = chrono::Utc::now().format("%Y%m%d_%H%M%S"); let backup_path = backup_dir.join(format!("database_{}.db", timestamp)); fs::copy(&db_path, &backup_path)?; Ok(()) } ``` ### SQLite Backup API For live backups without stopping operations: ```rust theme={null} db.execute_unprepared( "VACUUM INTO '/path/to/backup.db'" ).await?; ``` This creates a compacted backup while the database remains accessible. ### Crash Recovery WAL mode provides automatic crash recovery. If Spacedrive crashes, SQLite automatically rolls back incomplete transactions on the next startup. The WAL file contains all pending writes. SQLite replays this journal to restore database consistency. Never delete the `-wal` or `-shm` files manually. SQLite uses these for recovery. ## Maintenance Operations ### Database Optimization Run optimization periodically to maintain performance: ```rust theme={null} async fn optimize_database(db: &DatabaseConnection) -> Result<(), DbErr> { // Update query planner statistics db.execute_unprepared("ANALYZE").await?; // Rebuild database file to reclaim space db.execute_unprepared("VACUUM").await?; // Optimize based on recent queries db.execute_unprepared("PRAGMA optimize").await?; Ok(()) } ``` **ANALYZE** updates table statistics for better query planning. **VACUUM** rebuilds the database file, removing deleted data and defragmenting tables. **PRAGMA optimize** analyzes recent query patterns to suggest new indexes. ### Integrity Checks Verify database integrity after crashes or disk errors: ```rust theme={null} let result = db.execute_unprepared("PRAGMA integrity_check").await?; ``` This performs extensive validation of database structures and returns any corruption found. ### Size Monitoring Track database growth over time: ```rust theme={null} let page_count: i64 = db.query_one( Statement::from_string( DbBackend::Sqlite, "PRAGMA page_count".to_string() ) ).await?; let page_size: i64 = db.query_one( Statement::from_string( DbBackend::Sqlite, "PRAGMA page_size".to_string() ) ).await?; let size_bytes = page_count * page_size; ``` ## Extension Support Spacedrive extensions can create custom tables at runtime. The database layer provides APIs for: **Table Creation**: Extensions define tables with proper namespacing. **Migration Tracking**: Each extension manages its own schema versions. **Foreign Keys**: Extensions can reference core tables safely. **Cleanup**: Tables are removed when extensions uninstall. See the Data Model documentation for details on extension table design. ## Future Enhancements Planned database improvements include: **Full-Text Search**: SQLite FTS5 for searching file content and metadata. **JSON Operations**: Native JSON functions for querying structured data. **R-Tree Indexes**: Spatial indexing for geographic data. **Encryption**: SQLCipher integration for at-rest encryption. These features will be added as libraries need them, maintaining backward compatibility. # Devices Source: https://v2.spacedrive.com/core/devices Devices are machines running Spacedrive. Each device has a unique identity, can pair with others, and participates in library synchronization. ## Architecture Devices operate across three layers: ### Identity Layer Manages device configuration and cryptographic keys. ```rust theme={null} // Device initialization let device_manager = DeviceManager::init()?; let device_id = device_manager.device_id()?; ``` **Storage locations**: * macOS: `~/Library/Application Support/com.spacedrive/device.json` * Linux: `~/.config/spacedrive/device.json` * Windows: `%APPDATA%/Spacedrive/device.json` ### Domain Layer Provides the rich device model used throughout the application. ```rust theme={null} pub struct Device { pub id: Uuid, pub name: String, pub slug: String, // URL-safe identifier for addressing pub os: OperatingSystem, pub hardware_model: Option, pub network_addresses: Vec, pub is_online: bool, pub last_seen_at: DateTime, } ``` Devices are stored per library, not globally. Each library database contains device records for all participating devices. The `devices` table is the **source of truth** for sync state within a library. It tracks which devices are online, when they were last seen, and their sync watermarks. ### Device Slugs for Unified Addressing Each device has a unique slug used in Spacedrive's unified addressing scheme. The slug is a URL-safe identifier generated from the device name: ```rust theme={null} // Slug generation let name = "Jamie's MacBook Pro"; let slug = name.to_lowercase() .chars() .map(|c| if c.is_alphanumeric() { c } else { '-' }) .collect::() .trim_matches('-'); // Result: "jamies-macbook-pro" ``` Slugs enable human-readable local file URIs: ``` local://jamies-macbook/Users/james/Documents/report.pdf local://home-server/mnt/storage/media/movies/Inception.mkv local://work-desktop/C:/Projects/spacedrive/README.md ``` The database enforces slug uniqueness with a UNIQUE constraint. If two devices would have the same slug (e.g., both named "MacBook Pro"), one must be renamed before they can sync. See [Unified Addressing](/docs/core/addressing) for complete details on URI formats and slug resolution. ### Network Layer Handles P2P connections and device pairing through Iroh. The network layer uses mDNS for local discovery and QUIC for encrypted communication. ## Device Pairing Pairing establishes trust between devices using a cryptographic handshake. ### Pairing Flow Device A generates a pairing code valid for 5 minutes. ```typescript theme={null} const pairing = await client.action("network.pair.generate", {}); console.log(`Pairing code: ${pairing.code}`); // "ABCD-1234-EFGH" ``` Device B joins using the pairing code. ```typescript theme={null} await client.action("network.pair.join", { code: "ABCD-1234-EFGH" }); ``` Devices exchange cryptographic signatures and derive session keys for future communication. ### Paired Device States * **Discovered**: Found via mDNS but not paired * **Pairing**: Authentication in progress * **Paired**: Trusted and persisted * **Connected**: Active P2P connection * **Disconnected**: Paired but offline ## Library Participation After pairing, devices must register with libraries to enable sync. ### Registration Process 1. Paired devices discover each other's libraries 2. User selects which libraries to join 3. Device records are created in each library's database 4. Sync begins automatically ### Device-Owned Data Ownership flows through volumes. Each device owns its volumes, and volumes own the locations and entries on them: * **Volumes**: Physical drives attached to the device * **Locations**: Filesystem paths on a volume * **Entries**: Files and folders within those locations This indirection enables portable storage: when an external drive moves between machines, updating the volume's device reference transfers ownership of all associated data instantly. See [Library Sync](/docs/core/library-sync) for details on the ownership chain and portable volume handling. ## Sync Participation Spacedrive uses a leaderless sync model. All devices are peers with no central authority. The `devices` table tracks device state within a library: * **Connection State**: `is_online`, `last_seen_at` track real-time availability * **Sync Enablement**: `sync_enabled` controls whether a device participates * **Last Sync**: `last_sync_at` records when the device last synced Watermarks for incremental sync are stored separately in sync.db on a per-resource basis. See [Library Sync](/docs/core/library-sync) for details. ### How Devices Participate in Sync Devices sync data using two protocols based on ownership: * **Device-owned data** (volumes, locations, entries): Owner broadcasts state, peers apply. Entries inherit ownership through their volume's device. Tracked via `last_state_watermark`. * **Shared resources** (tags, collections): Any device can modify. Changes ordered via HLC. Tracked via `last_shared_watermark`. For detailed protocol documentation, see [Library Sync](/docs/core/library-sync). ### Sync State Management Query sync-enabled devices in a library: ```rust theme={null} // Get all devices that can sync let sync_devices = entities::device::Entity::find() .filter(entities::device::Column::SyncEnabled.eq(true)) .all(db) .await?; // Get only online devices ready for immediate sync let online_devices = entities::device::Entity::find() .filter(entities::device::Column::SyncEnabled.eq(true)) .filter(entities::device::Column::IsOnline.eq(true)) .all(db) .await?; ``` ### Incremental Sync When devices reconnect after being offline, they use watermarks to determine what data needs synchronization, avoiding full re-sync. Watermarks are tracked per-resource in sync.db. See [Library Sync](/docs/core/library-sync) for implementation details. ## API Reference ### List Paired Devices ```typescript theme={null} const devices = await client.query("network.devices.list", { connectedOnly: false }); // Response { devices: [ { id: "device-uuid", name: "Jamie's MacBook", deviceType: "Laptop", isConnected: true, lastSeen: "2024-10-12T..." } ], total: 3, connected: 2 } ``` ### Device Events Devices emit events when their state changes: ```typescript theme={null} // Device comes online { kind: "ResourceChanged", resourceType: "device", resource: { id: "...", isOnline: true } } // Device goes offline { kind: "ResourceChanged", resourceType: "device", resource: { id: "...", isOnline: false } } ``` ## Platform Considerations ### Mobile Devices iOS and Android require special initialization: ```swift theme={null} // iOS: Pass UIDevice name to Rust let deviceName = UIDevice.current.name core.initializeDevice(withName: deviceName) ``` ### Device Types * **Desktop**: Windows, Linux desktops * **Laptop**: MacBooks, portable computers * **Mobile**: iOS, Android devices * **Server**: Headless installations ## Security Each device maintains: * **Ed25519 key pair**: Unique cryptographic identity * **Session keys**: Derived after pairing for encrypted communication * **Trust levels**: Verified (paired) or blocked Never share device keys or pairing codes over insecure channels. ## Troubleshooting ### Pairing Issues If devices won't pair: * Verify both devices are on the same network * Check firewall settings for mDNS (port 5353) * Ensure pairing code hasn't expired (5 minute timeout) * Restart the application on both devices ### Sync Not Working If changes aren't syncing between devices: * Confirm devices are paired (check paired device list) * Verify both devices have joined the library * Check `devices.is_online` status in the library database * Verify `devices.sync_enabled = 1` for both devices * Compare watermarks to check if sync is progressing * Check network connectivity between devices * Review sync status in the UI ### Debug Commands ```bash theme={null} # Check device registration and sync state in library sqlite3 ~/Spacedrive/Libraries/My\ Library.sdlibrary/database.db \ "SELECT uuid, name, is_online, sync_enabled, last_sync_at FROM devices;" # Check which devices are online and sync-enabled sqlite3 ~/Spacedrive/Libraries/My\ Library.sdlibrary/database.db \ "SELECT uuid, name, is_online, last_seen_at FROM devices WHERE sync_enabled = 1;" # View watermarks (stored in sync.db, not devices table) sqlite3 ~/Spacedrive/Libraries/My\ Library.sdlibrary/sync.db \ "SELECT * FROM device_resource_watermarks;" # Monitor sync activity RUST_LOG=sd_core::sync=debug,sd_core::service::sync=debug cargo run ``` ## Implementation Details ### Global Device ID Cache For performance, the current device ID is cached globally: ```rust theme={null} use sd_core::device::get_current_device_id; let device_id = get_current_device_id(); // Fast lookup ``` ### Device Registration Query ```sql theme={null} -- Each library database contains CREATE TABLE devices ( id INTEGER PRIMARY KEY, uuid TEXT UNIQUE NOT NULL, name TEXT NOT NULL, slug TEXT UNIQUE NOT NULL, os TEXT NOT NULL, os_version TEXT, hardware_model TEXT, -- Hardware specifications cpu_model TEXT, cpu_architecture TEXT, cpu_cores_physical INTEGER, cpu_cores_logical INTEGER, cpu_frequency_mhz INTEGER, memory_total_bytes INTEGER, form_factor TEXT, manufacturer TEXT, gpu_models TEXT, -- JSON array boot_disk_type TEXT, boot_disk_capacity_bytes INTEGER, swap_total_bytes INTEGER, -- Network and status network_addresses TEXT, -- JSON array is_online BOOLEAN DEFAULT 0, last_seen_at TEXT NOT NULL, capabilities TEXT, -- JSON object -- Sync coordination sync_enabled BOOLEAN DEFAULT 1, last_sync_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL ); ``` Watermarks for incremental sync are stored in sync.db, not the devices table. See [Library Sync](/docs/core/library-sync) for watermark tracking details. ### Connection State Management The sync system subscribes to network connection events and updates the `devices` table automatically: ```rust theme={null} // When a device connects (network event) entities::device::Entity::update_many() .col_expr(entities::device::Column::IsOnline, Expr::value(true)) .col_expr(entities::device::Column::LastSeenAt, Expr::value(Utc::now())) .filter(entities::device::Column::Uuid.eq(peer_id)) .exec(db) .await?; // When a device disconnects (network event) entities::device::Entity::update_many() .col_expr(entities::device::Column::IsOnline, Expr::value(false)) .col_expr(entities::device::Column::LastSeenAt, Expr::value(Utc::now())) .filter(entities::device::Column::Uuid.eq(peer_id)) .exec(db) .await?; ``` The `devices` table is the single source of truth - the network layer updates it, and the sync layer queries it to determine which peers to sync with. You can also check real-time connection status via the DeviceRegistry: ```rust theme={null} // Get current connection status (in-memory state) let networking = context.get_networking().await?; let registry = networking.device_registry(); let is_connected = registry.is_device_connected(device_id); ``` ## Related Documentation * [Sync System](/docs/core/sync) - How devices synchronize data * [Libraries](/docs/core/libraries) - Multi-device library management * [Networking](/docs/core/networking) - P2P connection details # Event System Source: https://v2.spacedrive.com/core/events Spacedrive's event system broadcasts real-time updates to all connected clients using a **unified resource event architecture** that eliminates per-resource event variants in favor of generic, horizontally-scalable events. ## Overview The event bus enables reactive UI updates by notifying clients when data changes. The system uses: * **Generic Resource Events**: A single event type (`ResourceChanged`) handles all database entities * **Path-Scoped Subscriptions**: Subscribe to events affecting specific directories or files * **Infrastructure Events**: Specialized events for jobs, sync, and system lifecycle * **Automatic Emission**: Events are emitted automatically by the TransactionManager - no manual calls needed ## Event Types ### Resource Events Generic events that work for ALL resources (files, tags, albums, locations, etc.): ```rust theme={null} Event::ResourceChanged { resource_type: String, // e.g., "file", "tag", "album", "location" resource: serde_json::Value, // Full resource data as JSON metadata: Option, // Cache hints and path scopes } Event::ResourceChangedBatch { resource_type: String, resources: serde_json::Value, // Array of resources metadata: Option, } Event::ResourceDeleted { resource_type: String, resource_id: Uuid, } ``` **Supported Resources**: * `file` - Files and directories (Entry entity) * `tag` - User tags * `collection` - File collections * `location` - Indexed locations * `device` - Devices in the network * `volume` - Storage volumes (replaces deprecated volume events) * `sidecar` - Generated thumbnails and metadata * `user_metadata` - User-added metadata (notes, favorites, etc.) * `content_identity` - Deduplicated content records Volume events (`VolumeAdded`, `VolumeUpdated`, etc.) and indexing events (`IndexingStarted`, `IndexingProgress`, etc.) are deprecated. Use `ResourceChanged` for volumes and job events for indexing progress. ### Infrastructure Events Specialized events for system operations: **Core Lifecycle**: * `CoreStarted`, `CoreShutdown` - Daemon lifecycle **Library Management**: * `LibraryCreated`, `LibraryOpened`, `LibraryClosed`, `LibraryDeleted` * `Refresh` - Invalidate all frontend caches **Jobs**: * `JobQueued`, `JobStarted`, `JobProgress`, `JobCompleted`, `JobFailed`, `JobCancelled` **Sync**: * `SyncStateChanged` - Sync state transitions * `SyncActivity` - Peer sync activity * `SyncConnectionChanged` - Peer connections * `SyncError` - Sync errors **Volumes** (deprecated - use `ResourceChanged` with `resource_type: "volume"`): * ~~`VolumeAdded`, `VolumeRemoved`, `VolumeUpdated`~~ * ~~`VolumeMountChanged`, `VolumeSpeedTested`~~ **Indexing** (deprecated - use job events): * ~~`IndexingStarted`, `IndexingProgress`, `IndexingCompleted`, `IndexingFailed`~~ **Filesystem**: * `FsRawChange` - Raw filesystem watcher events (before database resolution) ## Event Emission ### Automatic Emission (Recommended) Events are emitted automatically when using the TransactionManager: ```rust theme={null} // NO manual event emission needed! pub async fn create_collection( tm: &TransactionManager, library: Arc, name: String, ) -> Result { let model = collection::ActiveModel { id: NotSet, uuid: Set(Uuid::new_v4()), name: Set(name), // ... }; // TM handles: DB write + sync log + event emission let collection = tm.commit::(library, model).await?; Ok(collection) // ResourceChanged event already emitted! } ``` The TransactionManager emits `ResourceChanged` after successful commits, ensuring: * ✅ Events always match database state * ✅ No forgotten emissions * ✅ Automatic sync log integration ### Manual Emission (Infrastructure Only) Only use manual emission for infrastructure events: ```rust theme={null} // Jobs, sync, and system events event_bus.emit(Event::JobStarted { job_id: job.id.to_string(), job_type: "IndexLocation".to_string(), }); ``` ## Path-Scoped Subscriptions Subscribe to events affecting specific directories or files: ```rust theme={null} use sd_core::infra::event::SubscriptionFilter; // Subscribe to changes in a specific directory let filter = SubscriptionFilter::PathScoped { resource_type: "file".to_string(), path_scope: SdPath::physical(device_slug, "/Users/james/Photos"), }; let mut subscriber = event_bus.subscribe_filtered(vec![filter]); while let Ok(event) = subscriber.recv().await { // Only receives events affecting /Users/james/Photos println!("Event: {:?}", event); } ``` The `ResourceMetadata` field includes `affected_paths` that indicate which directories/files changed: ```rust theme={null} pub struct ResourceMetadata { pub no_merge_fields: Vec, // Fields to replace, not merge pub alternate_ids: Vec, // Alternate IDs for matching pub affected_paths: Vec, // Paths affected by this event } ``` Path matching supports: * **Physical paths**: Match by device slug + path prefix * **Content IDs**: Match by content identifier * **Cloud paths**: Match by service + bucket + path * **Sidecar paths**: Match by content ID ## Client Integration ### TypeScript (useNormalizedQuery) The `useNormalizedQuery` hook automatically subscribes to resource events and updates the cache: ```typescript theme={null} import { useNormalizedQuery } from '@sd/client'; // Automatically subscribes to ResourceChanged events for "tag" const tags = useNormalizedQuery({ resource_type: 'tag', query: api.tags.list(), }); // UI automatically updates when tags change! ``` The normalized cache: 1. Subscribes to `ResourceChanged` events matching the resource type 2. Deserializes the JSON resource using generated TypeScript types 3. Updates the local cache 4. Triggers React re-renders ### Swift ```swift theme={null} // Generic event handler works for ALL resources actor EventCacheUpdater { let cache: NormalizedCache func handleEvent(_ event: Event) async { switch event.kind { case .ResourceChanged(let resourceType, let resourceJSON): // Generic decode via type registry let resource = try ResourceTypeRegistry.decode( resourceType: resourceType, from: resourceJSON ) await cache.updateEntity(resource) case .ResourceDeleted(let resourceType, let resourceId): await cache.deleteEntity(resourceType: resourceType, id: resourceId) default: break } } } ``` ## CLI Event Monitoring Monitor events in real-time using the CLI: ```bash theme={null} # Monitor all events sd events monitor # Filter by event type sd events monitor --event-type JobProgress,JobCompleted # Filter by library sd events monitor --library-id # Filter by job sd events monitor --job-id # Show timestamps sd events monitor --timestamps # Verbose mode (full JSON) sd events monitor --verbose --pretty ``` **Available Filters**: * `-t, --event-type` - Comma-separated event types (e.g., `ResourceChanged,JobProgress`) * `-l, --library-id` - Filter by library UUID * `-j, --job-id` - Filter by job ID * `-d, --device-id` - Filter by device UUID * `--timestamps` - Show event timestamps * `-v, --verbose` - Show full event JSON * `-p, --pretty` - Pretty-print JSON output **Example Output**: ``` Monitoring events - Press Ctrl+C to exit ═══════════════════════════════════════════════════════ Connected to event stream JobStarted: Job started: IndexLocation (a1b2c3d4) JobProgress: Job progress: IndexLocation (a1b2c3d4) - 45.2% - Scanning directory ResourceChangedBatch: Resources changed: file (127 items) JobCompleted: Job completed: IndexLocation (a1b2c3d4) ``` ## Implementation Reference **Event enum**: `core/src/infra/event/mod.rs` ```rust theme={null} #[derive(Debug, Clone, Serialize, Deserialize, Type)] pub enum Event { // Core lifecycle CoreStarted, CoreShutdown, // Library events LibraryOpened { id: Uuid, name: String, path: PathBuf }, LibraryClosed { id: Uuid, name: String }, // Generic resource events ResourceChanged { resource_type: String, resource: serde_json::Value, metadata: Option, }, ResourceChangedBatch { resource_type: String, resources: serde_json::Value, metadata: Option, }, ResourceDeleted { resource_type: String, resource_id: Uuid, }, // Jobs, sync, volumes, indexing... // (See full enum in source) } ``` **Event bus**: `core/src/infra/event/mod.rs` ```rust theme={null} pub struct EventBus { sender: broadcast::Sender, subscribers: Arc>>, } impl EventBus { // Subscribe to all events pub fn subscribe(&self) -> EventSubscriber; // Subscribe with path/resource filters pub fn subscribe_filtered(&self, filters: Vec) -> EventSubscriber; // Emit an event pub fn emit(&self, event: Event); } ``` ## Benefits ### Backend * **Zero Manual Emission**: TransactionManager handles all resource events * **Type Safety**: Events always match actual resources * **Centralized**: Single point of emission prevents drift * **Scalable**: Adding new resources requires no event code ### Frontend * **Zero Boilerplate**: One event handler for all resource types * **Type Registry**: Automatic deserialization via generated types * **Path Scoping**: Subscribe only to relevant directory changes * **Cache Integration**: `useNormalizedQuery` handles subscriptions automatically ### Developer Experience * **No Event Variants**: \~40 variants eliminated → 3 generic events * **No Manual Calls**: Never call `event_bus.emit()` for resources * **No Client Changes**: Adding a 100th resource type = zero event handling updates * **CLI Debugging**: Monitor events in real-time with filtering ## Related Documentation * **Sync System**: See [sync.md](./sync.md) for event emission during sync * **Normalized Cache**: See [normalized\_cache.md](./normalized_cache.md) for client-side event handling * **TransactionManager**: See [transactions.md](./transactions.md) for automatic event emission # File Copy Operations Source: https://v2.spacedrive.com/core/file-copy-operations Spacedrive uses a strategy-based copy system that automatically selects the optimal method for moving or copying files. The system analyzes your hardware topology, filesystem capabilities, and operation context to choose between instant atomic operations, zero-copy techniques, streaming transfers, or encrypted network transfers. ## Strategy Selection When you copy or move files, Spacedrive evaluates the source and destination to pick the best approach. The router examines device IDs, volume relationships, and filesystem types to determine which strategy delivers the fastest, most reliable result. You can control strategy selection through three copy methods: **Auto** - Spacedrive analyzes your system and picks the optimal strategy. This is the default mode and works well for most operations. **Atomic** - Forces instant operations when possible. Moves use `fs::rename()` for metadata-only changes, while copies leverage Copy-on-Write features like APFS clones or Btrfs reflinks. **Streaming** - Ensures progress tracking and cancellation support by forcing chunked streaming copies, regardless of filesystem capabilities. ## Available Strategies ### LocalMoveStrategy Moves files on the same volume using atomic filesystem renames. The operation completes in microseconds by updating metadata pointers rather than copying data. Works for any file size since no data actually moves. ```rust theme={null} // Same-volume move: instant metadata update fs::rename(source_path, dest_path).await?; ``` This strategy only works when source and destination are on the same physical volume. Cross-volume moves automatically fall back to streaming copy with source deletion. ### FastCopyStrategy Copies files using `std::fs::copy()`, which automatically leverages filesystem optimizations. On APFS, this creates instant clones. On Btrfs and ZFS, it uses reflinks. On ReFS, it performs block clones. Other filesystems fall back to standard copying. ```rust theme={null} // Automatic CoW optimization based on filesystem std::fs::copy(&source_path, &dest_path) ``` The strategy skips progress callbacks since CoW operations complete near-instantly. Checksum verification runs after the copy if enabled. ### LocalStreamCopyStrategy Performs chunked streaming copies for cross-volume operations or when you need progress tracking. The strategy reads source files in volume-aware buffer sizes, writes to the destination, and reports progress every 50ms. The implementation supports: * Volume-aware buffer sizing (queries VolumeManager for optimal chunk size) * Blake3 checksum verification during transfer * Cancellation with automatic cleanup of partial files * Permission and timestamp preservation * Directory recursion with per-file progress Buffer sizes automatically adjust based on source and destination volumes. SSDs typically use larger buffers than HDDs, and the strategy picks the minimum of both volumes for cross-device transfers. ### RemoteTransferStrategy Handles file transfers between devices over the network. Files are encrypted using session keys, split into 64KB chunks, and streamed to the remote device through the networking service. The transfer protocol includes: * Per-chunk Blake3 checksums for integrity verification * XChaCha20-Poly1305 encryption with unique nonces * Transfer state tracking for fault tolerance * Final checksum verification after completion ```rust theme={null} // Transfer request structure FileTransferMessage::TransferRequest { transfer_id, file_metadata, transfer_mode: TransferMode::TrustedCopy, chunk_size, total_chunks, destination_path, } ``` Network transfers report progress through the same callback system as local copies, giving you consistent UI feedback across all operation types. ## Copy Method Selection The router uses this logic to pick strategies: **Cross-device operations** - Always use RemoteTransferStrategy, regardless of copy method setting. **Same-device with Atomic method** - Use LocalMoveStrategy for moves, FastCopyStrategy for copies. **Same-device with Streaming method** - Always use LocalStreamCopyStrategy. **Same-device with Auto method** - Analyze volume relationships: * Same storage + move → LocalMoveStrategy * Same storage + copy + CoW filesystem → FastCopyStrategy * Cross-storage → LocalStreamCopyStrategy ## Progress Tracking The job system uses a `ProgressAggregator` that tracks overall progress across multiple files. Strategies call a progress callback with current bytes copied and total file size. The aggregator accumulates this across files to compute job-level progress. When a file completes, strategies signal completion by passing `u64::MAX` as the signal value. The aggregator increments the completed file count and updates the bytes offset for the next file. The job reports progress through five phases: **Initializing** - Sets up internal state and validates paths. **DatabaseQuery** - Attempts to get instant size estimates from indexed file metadata. **Preparation** - Calculates actual total size by walking the filesystem. **Copying** - Executes the selected strategy for each source path. **Complete** - Reports final counts and returns the job output. ## Error Handling Copy operations collect errors in a `failed_copies` vector rather than stopping execution. This lets you see which files succeeded and which failed in a single job run. For move operations, if the copy succeeds but source deletion fails, the operation logs the error but doesn't mark the file as failed. The file exists at the destination, which is the primary goal of the operation. When using checksum verification, corrupted copies are automatically deleted to prevent partial or incorrect files from persisting. ## Job Resumption FileCopyJob tracks completed files in `completed_indices` and checkpoints every 20 files. If the job is interrupted, you can restart it and already-completed files will be skipped. The progress aggregator accounts for skipped files when calculating overall progress. This works for both single-file and directory operations. Each source path in the batch counts as one index, even if it contains hundreds of files. # File Sync Source: https://v2.spacedrive.com/core/file-sync This is provisional documentation describing the planned File Sync implementation. File Sync orchestrates content synchronization between locations by leveraging Spacedrive's Virtual Distributed File System (VDFS) index. Unlike traditional sync tools that scan filesystems, File Sync operates entirely through index queries. This makes sync state resolution a simple database operation and ensures perfect consistency with your indexing rules. ## Architecture File Sync builds on Spacedrive's core infrastructure. Each sync operation runs as a Job, providing state persistence and progress tracking. The system derives all sync decisions from the VDFS index, eliminating complex state management and ensuring files ignored during indexing remain excluded from sync. ### Index-Based Design The VDFS index serves as the single source of truth for File Sync. When you configure a sync relationship between two locations, the system: 1. Queries the index for entries at both locations 2. Calculates differences based on content hashes and timestamps 3. Dispatches existing file operations (copy, delete) to reconcile state 4. Updates sync history for conflict detection This approach transforms sync from a complex distributed systems problem into straightforward database queries. ### Core Principles **Index as Truth**\ If a file isn't indexed, it doesn't exist for sync purposes. This ensures consistency between what you see in Spacedrive and what gets synchronized. **Push-Based Transfer** The device that has files pushes them to devices that need them. This works naturally with iOS background processing and simplifies the protocol. **Library Sync First** File Sync requires a complete, up-to-date index via Library Sync before operating. This ensures all devices have the same view of what exists where. **Leverage Existing Jobs** File Sync orchestrates `FileCopyJob` and `DeleteJob` rather than implementing custom transfer logic. The existing job system already handles local vs remote routing, progress tracking, and error recovery. ## Sync Modes File Sync offers four distinct modes, each designed for specific workflows. Configure these per-location through the sync settings panel. ### Mirror Mode Creates an exact copy of your source at the destination. Changes flow one direction only. Perfect for backup scenarios where you want a read-only copy of important data. When you delete a file from the source, Mirror Mode removes it from the destination too. This keeps your backup lean and matches your working set exactly. ### Bidirectional Mode Keeps two locations identical across different devices. Changes made anywhere propagate everywhere. Ideal for working on the same projects from multiple computers. The system uses last-write-wins for conflicts. When the same file changes in multiple places, the most recent modification takes precedence. Previous versions remain in your Spacedrive history. ### Archive Mode Moves completed work to long-term storage. After verifying successful transfer, the source files are removed to free local space. The system performs cryptographic verification before any deletion. Use this mode when finishing projects. Your files move to cheaper storage while maintaining full Spacedrive search and preview capabilities. ### Selective Mode Intelligently manages limited local storage. Frequently accessed files stay local while older content moves to secondary storage. Files remain visible in Spacedrive and download on-demand when needed. The algorithm considers access patterns, available space, and manual pins. You control which files always stay local by pinning them in the Spacedrive interface. ## Implementation File Sync uses index queries to determine what needs synchronization. This eliminates filesystem scanning and complex state tracking. ### Prerequisites Before File Sync can operate, Library Sync must complete: ```rust theme={null} impl FileSyncJob { async fn can_start(&self) -> bool { // Ensure Library Sync is complete let library_sync_state = self.library.sync_state().await; library_sync_state.is_fully_synced() } } ``` This guarantees all devices share the same index view, preventing inconsistent sync decisions. ### Sync Resolution The sync resolver calculates operations by comparing index entries: ```rust theme={null} // Find files that need copying (exist in source but not target) let to_copy = source_entries .filter(|e| !target_entries.contains(e.path)) .collect(); // Find files that need deletion (exist in target but not source) let to_delete = target_entries .filter(|e| !source_entries.contains(e.path)) .collect(); ``` For bidirectional sync, the system uses timestamps to detect conflicts when both sides modified the same file. ### Index Consistency Files excluded from indexing (like `node_modules`) are automatically excluded from sync. This matches user expectations - if you told Spacedrive to ignore it, it won't sync either. For cases requiring full directory sync including normally-ignored files, sync conduits support an index mode override: ```rust theme={null} pub enum IndexingMode { Standard, // Use normal exclusion rules SyncComplete, // Index everything for this sync } ``` ### Network Protocol File transfers use Spacedrive's existing P2P infrastructure over QUIC. The protocol supports: * Resumable transfers for large files * Concurrent block transmission * Compression for slow links * Encryption for all data Each sync session negotiates capabilities. Modern devices use parallel transfers while older systems fall back to sequential mode. ### Transfer Coordination File Sync uses a push-based model where the device with files initiates transfers: ```rust theme={null} impl FileSyncJob { async fn execute(&self, ctx: &JobContext) -> Result<()> { let conduit = self.load_conduit().await?; match conduit.sync_mode { SyncMode::Mirror => { // Source pushes all changes to target if self.am_source(&conduit) { let ops = self.calculate_mirror_push().await?; self.push_changes(ops, conduit.target).await?; } } SyncMode::Bidirectional => { // Each device pushes its own changes let my_changes = self.calculate_my_changes().await?; if !my_changes.is_empty() { self.push_changes(my_changes, other_device).await?; } } } } } ``` ### Receiver Validation When receiving files, devices validate against their local index: ```rust theme={null} impl FileTransferProtocol { async fn handle_incoming_file(&self, metadata: FileMetadata) -> Result<()> { // Check if we already have this content let existing = self.db.content_identity() .find_by_hash(&metadata.content_hash) .await?; if existing.is_some() { return Ok(()); // Skip transfer, already have it } // Proceed with transfer self.receive_file(metadata).await } } ``` This prevents duplicate transfers and ensures consistency. ## Data Model File Sync introduces the `SyncConduit` entity to manage sync relationships between directories: ```rust theme={null} pub struct SyncConduit { pub id: i32, pub uuid: Uuid, // Sync endpoints - must be directories pub source_entry_id: i32, // FK to Entry pub target_entry_id: i32, // FK to Entry // Configuration pub sync_mode: SyncMode, pub enabled: bool, pub schedule: SyncSchedule, // Index integration pub use_index_rules: bool, // Default: true pub index_mode_override: Option, // Performance pub parallel_transfers: i32, pub bandwidth_limit_mbps: Option, // State tracking via index timestamps pub last_sync_completed_at: Option>, pub sync_generation: i64, // Increments each sync pub created_at: DateTime, pub updated_at: DateTime, } ``` ### Relationships SyncConduit creates a directed relationship between two Entry records. The source and target must be directories (kind=1). For bidirectional sync, the direction indicates the initial sync priority but changes flow both ways. ### Sync History Track sync operations for conflict detection and debugging: ```rust theme={null} pub struct SyncGeneration { pub id: i32, pub conduit_id: i32, pub generation: i64, pub started_at: DateTime, pub completed_at: Option>, // Operation summary pub files_copied: i32, pub files_deleted: i32, pub conflicts_resolved: i32, pub bytes_transferred: i64, } ``` Each sync creates a new generation record. For bidirectional sync, this history helps detect when the same file changed on both sides since the last sync. ## Configuration Create sync relationships through the Spacedrive interface by right-clicking any directory and selecting "Sync to...". The system creates a SyncConduit record linking your source and destination. ### Essential Settings **Sync Schedule**: Controls when File Sync runs. Instant mode monitors filesystem events for immediate sync. Periodic modes batch changes for efficiency. **Bandwidth Limits**: Prevents sync from saturating your connection. Applies per-conduit, so multiple syncs share available bandwidth intelligently. **Conflict Resolution**: Determines automatic resolution strategy. The system maintains conflict history for manual review regardless of settings. ## Monitoring The sync status panel shows all active sync relationships. Monitor transfer progress, view sync history, and troubleshoot issues from a unified interface. Key metrics displayed: * Current transfer speed and ETA * Queue depth and pending files * Recent conflicts and resolutions * Storage space on each device ## Limitations File Sync currently has these constraints: * Maximum file size: 1TB per file * Excluded files: System files, temporary files * Platform differences: Some attributes don't sync across OS types * Network requirements: Both devices must be online simultaneously Future updates will address these limitations based on user feedback and real-world usage patterns. ## Benefits of Index-Based Sync The index-driven architecture provides several advantages over traditional filesystem scanning approaches: **Performance**\ No directory traversal needed. Sync resolution becomes efficient database queries instead of recursive filesystem operations. **Consistency**\ Files ignored by indexing rules automatically stay out of sync. No divergence between what Spacedrive shows and what gets synchronized. **Simplicity**\ Push-based transfers eliminate complex negotiation protocols. The device with data initiates transfers, making the system predictable and debuggable. **Reliability**\ Library Sync ensures all devices share the same worldview before File Sync operates. Combined with receiver validation, this prevents inconsistent states. ## Future Enhancements ### Delta Transfers While the current system transfers whole files, future versions will add block-level delta transfers for large file modifications: ```rust theme={null} // Future: Only transfer changed blocks pub struct DeltaTransfer { pub file_id: i32, pub changed_blocks: Vec, pub block_size: u32, } ``` ### Remote Delete Support The current `DeleteJob` lacks cross-device support. Future updates will add remote deletion capability to complete the sync feature set. ### Conflict Resolution Advanced conflict handling will maintain version history and offer multiple resolution strategies beyond last-write-wins. ## Usage Scenarios File Sync excels at personal file management workflows: **Project Folders**: Keep active projects synchronized between laptop and desktop **Photo Libraries**: Mirror photos from phone to NAS for backup **Document Archive**: Move completed work to cloud storage automatically\ **Selective Cache**: Keep recent files local while older content lives in cloud The index-based design ensures these workflows remain fast and reliable while respecting your organization preferences. # Filesystems Source: https://v2.spacedrive.com/core/filesystems Spacedrive treats the native filesystem as the substrate for everything above it. Detection, capacity reporting, copy-on-write, visibility filtering, and same-storage checks all have filesystem-specific behavior because the abstractions leak: `df` lies about ZFS pool sizes, APFS volumes share containers, Btrfs subvolumes look independent but aren't, and Windows mount points rename themselves. This page documents what Spacedrive knows about each filesystem, how it detects them, and where the abstraction boundaries are. ## Support Matrix | Filesystem | Platform | CoW / Clones | Pool-aware | Visibility filter | Capacity correction | | ------------ | ---------- | --------------------------- | ---------------- | ------------------------ | ------------------- | | APFS | macOS, iOS | yes (clonefile) | yes (containers) | yes (system volumes) | no | | Btrfs | Linux | yes (reflink) | yes (subvolumes) | yes (via Linux rules) | no | | ZFS | Linux | yes (reflink on recent ZoL) | yes (pools) | yes (system pools, apps) | yes (pool root) | | ReFS | Windows | yes (block clone) | no | no | no | | NTFS | Windows | no | no | no | no | | ext2/3/4 | Linux | no | no | yes (via Linux rules) | no | | XFS | Linux | no | no | yes (via Linux rules) | no | | FAT32, exFAT | all | no | no | no | no | | HFS+ | macOS | no | no | yes (system volumes) | no | "CoW / Clones" means `std::fs::copy` and the `FastCopyStrategy` produce metadata-only copies when source and destination are on the same filesystem. Everything else falls back to `LocalStreamCopyStrategy` which streams bytes with progress reporting. ## Detection Volume detection runs at startup and on mount/unmount events. Each platform uses a different primary source: ### macOS (`core/src/volume/platform/macos.rs`) Primary: `diskutil apfs list` — gives APFS container topology, volume roles (`Data`, `System`, `VM`, `Preboot`, `Recovery`, `Update`), and mount points. Containers group volumes that share physical storage and space (`ApfsContainer`). Fallback: `df -h -T` for non-APFS volumes (HFS+, external FAT32, etc.). Classification: * `/`, `/System/Volumes/Data`, `/System/Volumes/Preboot` etc. are system roles — hidden from user-visible view but still fingerprinted. * `/Volumes/*` that aren't system roles are External. ### Linux (`core/src/volume/platform/linux.rs`) Primary: `df -h -T` — one line per mounted filesystem with device, type, size, available, mount point. Secondary: `/sys/block//queue/rotational` to distinguish SSD from HDD. `/proc/mounts` is also parseable via `parse_proc_mounts()` as an alternative source. ZFS datasets get a second pass via `zfs list -H -o name,mountpoint,used,available,type -t filesystem` to enrich each volume with dataset/pool information (see [Capacity Reporting](#capacity-reporting) below). ### Windows (`core/src/volume/platform/windows.rs`) Uses Win32 APIs via `windows-sys`: * `GetLogicalDrives` to enumerate drive letters. * `GetVolumeInformationW` for filesystem type and volume label. * `GetDiskFreeSpaceExW` for capacity. * `GetVolumeNameForVolumeMountPointW` for the stable `\\?\Volume{GUID}\` path — used as a hardware identifier that survives drive letter changes. ### iOS (`core/src/volume/platform/ios.rs`) Uses the macOS APFS code path but restricted to app-accessible volumes (sandboxed; detection is mostly informational). ## FilesystemHandler trait `core/src/volume/fs/mod.rs` defines a trait each filesystem implements: ```rust theme={null} #[async_trait] pub trait FilesystemHandler: Send + Sync { /// Add filesystem-specific fields to a Volume (dataset info, container, subvolume, etc.) async fn enhance_volume(&self, volume: &mut Volume) -> VolumeResult<()>; /// Can these two paths use fast same-storage operations (clone/reflink)? async fn same_physical_storage(&self, path1: &Path, path2: &Path) -> bool; /// Copy strategy to use for this filesystem fn get_copy_strategy(&self) -> Box; /// Filesystem-specific contains-path check (accounts for datasets/subvolumes/etc.) fn contains_path(&self, volume: &Volume, path: &Path) -> bool; } ``` `get_filesystem_handler(FileSystem)` returns the right implementation, falling back to `GenericFilesystemHandler` for anything unrecognized. ## Per-filesystem details ### APFS (`core/src/volume/fs/apfs.rs`) * **Containers**: APFS groups volumes into containers that share physical space. `ApfsContainer` is populated from `diskutil apfs list` and attached to each volume. `same_physical_storage` returns true when two paths are on volumes in the same container — that's when `clonefile(2)` produces instant clones. * **Firmlinks**: macOS silently maps paths like `/Users` onto `/System/Volumes/Data/Users`. `generate_macos_path_mappings()` materializes these mappings so `contains_path` resolves correctly. * **Role-based visibility**: volumes with roles `System`, `VM`, `Preboot`, `Recovery`, `Update` are marked `is_user_visible = false`. Only `Data` and unroled external volumes appear in the default UI. ### Btrfs (`core/src/volume/fs/btrfs.rs`) * **Subvolumes**: `btrfs subvolume show ` populates `SubvolumeInfo`. Subvolumes on the same Btrfs filesystem share storage. * **Reflinks**: `same_physical_storage` checks whether two paths share the top-level Btrfs filesystem via `btrfs filesystem show`. If yes, reflinks work between them. ### ZFS (`core/src/volume/fs/zfs.rs`) ZFS is the most-developed filesystem integration because TrueNAS Scale is a common Spacedrive server target. * **Datasets and pools**: `zfs list` output is parsed once per detection pass via `fetch_zfs_list_output()` (not per-volume — important for servers with many datasets). Each volume gets matched to its dataset via `find_dataset_for_path`, and the dataset's pool is extracted from the name (`pool/a/b` → pool `pool`). * **Pool root capacity correction**: see [Capacity Reporting](#capacity-reporting). * **System pool filter**: `is_system_zfs_pool` matches `boot-pool`, `rpool`, `zroot`. Datasets on these pools are marked `VolumeType::System`, `is_user_visible = false`, and never auto-tracked. * **App-managed dataset filter**: `is_app_managed_dataset` matches names containing `/ix-applications/`, `/.ix-apps/`, `/docker/`, or `/containerd/`. These are hidden from user view. TrueNAS Scale apps create dozens of nested datasets per app — without this filter the volume list becomes unusable. * **Clone support**: `supports_clones` returns true for any read-write dataset. ZoL 2.2+ supports reflinks; older versions fall back to streaming copy. ### ReFS (`core/src/volume/fs/refs.rs`) * **Block cloning**: checks for ReFS integrity stream support via `DeviceIoControl` / `FSCTL_DUPLICATE_EXTENTS_TO_FILE`. Sets `supports_block_cloning` on the volume. * **Version gating**: ReFS 3.x supports block cloning; 2.x doesn't. The handler feature-detects rather than version-checks. ### NTFS (`core/src/volume/fs/ntfs.rs`) No CoW primitive on NTFS, so `get_copy_strategy` returns `LocalStreamCopyStrategy`. The handler mainly exists to provide NTFS-aware `same_physical_storage` (compares Volume GUIDs, not drive letters). ### Generic (`core/src/volume/fs/generic.rs`) Fallback for ext2/3/4, XFS, FAT32, exFAT, HFS+, and anything unrecognized. `same_physical_storage` compares mount point roots. Copy strategy is always `LocalStreamCopyStrategy`. ## Visibility rules Spacedrive tracks far more volumes than it shows. Hidden volumes still get stable fingerprints so locations on them survive remounts, but they don't clutter the default UI and aren't eligible for auto-tracking. Two flags drive this: * `is_user_visible: bool` — shown in the default volume list. * `auto_track_eligible: bool` — picked up by `volumes.scan`. Always implies `is_user_visible`. ### Linux rules (`core/src/volume/utils.rs`) `is_virtual_filesystem(fs_type)` drops anything backed by kernel memory: `tmpfs`, `proc`, `sysfs`, `devtmpfs`, `cgroup`, `cgroup2`, `squashfs`, `efivarfs`, `overlay`, `fuse`, and \~20 more. These are hidden even before classification. `is_system_mount_point(path)` matches Linux OS paths: * Exact: `/`, `/usr`, `/var`, `/etc`, `/opt`, `/srv`, `/root`, `/boot`, `/home`, `/run`, `/dev`, `/proc`, `/sys`, `/tmp`, `/audit`, `/data`, `/conf`, `/mnt`, `/lost+found`. * Prefixes: `/boot/`, `/sys/`, `/proc/`, `/dev/`, `/run/`, `/var/log`, `/var/db/`, `/var/lib/systemd`, `/var/local/`, `/var/cache/`. The exact-match list includes TrueNAS Scale's split-root datasets (it mounts `/usr`, `/var`, `/etc` as separate ZFS datasets for atomic OS updates). `is_nested_app_mount(path)` matches container/app mounts: * Anything under `ix-applications/` or `.ix-apps/` (TrueNAS apps — one app creates dozens of datasets). * `docker/overlay2/`, `containerd/`, `kubelet/`, `snap/`. * `.snapshots/`, `.zfs/snapshot/` (ZFS snapshot browsing mounts). `should_hide_by_mount_path(path)` is the combined check. It's applied at: 1. **Detection** — so newly-discovered volumes get `is_user_visible = false` persistently. 2. **Volume list query** (`core/src/ops/volumes/list/query.rs`) — retroactively for tracked volumes whose DB rows predate these filters. 3. **Stats calculation** (`core/src/library/mod.rs`) — so `total_capacity` and `available_capacity` exclude hidden volumes even if the DB flag is stale. ### ZFS-specific rules Applied during ZFS enhancement after `should_hide_by_mount_path`: * Datasets on `is_system_zfs_pool` pools (boot-pool, rpool, zroot) → hidden + `VolumeType::System`. * Datasets matching `is_app_managed_dataset` → hidden. ### macOS rules APFS role-based: `System`, `VM`, `Preboot`, `Recovery`, `Update` roles are hidden. Also `/System/Volumes/*` except `/System/Volumes/Data` is hidden by path. ## Capacity reporting ### The df-for-ZFS problem `df -T` reports `Size = used + available` per mounted dataset. For a ZFS **leaf** dataset this is fine. For a ZFS **pool root** it's misleading: ``` $ df -T /mnt/pool Filesystem Type Size Used Available Mount pool zfs 15.0T 199M 14.9T /mnt/pool ``` The pool root's own `used` is tiny (199 MB) because all the real data lives in descendant datasets. `df` doesn't know that. On a 60 TB pool that's 75% full, `df` says the pool root is "15 TB" — essentially just the free space. ZFS's native `used` property on the pool root *does* include descendants: ``` $ zfs get used,available pool pool used 47.0T pool available 14.9T ``` 47 T + 14.9 T ≈ 62 T = the real pool capacity after raidz2 parity. ### Correction `enhance_volume_with_cached_output` in `zfs.rs` detects pool-root volumes (`dataset.name == dataset.pool_name`) and overwrites `total_capacity` with `used + available` from `zfs list`. Leaf datasets keep their df-derived values — they're accurate for single-dataset views. ### Library statistics `calculate_volume_capacity` (and `_static`) in `core/src/library/mod.rs` aggregates per-volume capacity with three passes: 1. Filter by `volume_type` (`Primary`, `UserData`, `External`, `Secondary`). 2. Filter by visibility (`is_user_visible = true` *and* `!should_hide_by_mount_path(mount)`). 3. Deduplicate by fingerprint. 4. Sort by mount-path length (shortest first). 5. For each volume: skip if it's a subpath of an already-counted volume on the same device; otherwise add its capacity to the running totals. Subpath dedup handles the common ZFS case: when `/mnt/pool` is tracked along with `/mnt/pool/footage` and `/mnt/pool/cctv`, only `/mnt/pool` gets counted (once). ### Pool-aware dedup limitation Subpath dedup breaks if the user tracks only leaf datasets without the pool root. Each leaf reports the full `available` as its own — summing them over-counts by the pool's free space per extra leaf. On TrueNAS this doesn't bite because `df` always detects the pool root. For other setups, proper fix requires either persisting `pool_name` on the volume record or a second dedup pass keyed on `(device_id, file_system=ZFS, available_capacity)`. Neither is implemented yet. ## Copy strategies `core/src/ops/files/copy/strategy.rs` defines three strategies: * **`LocalMoveStrategy`** — `fs::rename()` for same-volume moves. Metadata-only. * **`FastCopyStrategy`** — `std::fs::copy()` which invokes platform CoW primitives (`clonefile` on APFS, `ficlone`/`FICLONERANGE` on Btrfs/ZFS, block cloning on ReFS) when source and destination are on the same filesystem. Falls back to streaming if CoW fails. * **`LocalStreamCopyStrategy`** — chunked buffered copy with progress events. Used for cross-volume copies and for filesystems without CoW. `FilesystemHandler::get_copy_strategy` picks `FastCopyStrategy` for APFS, Btrfs, ZFS, ReFS. Everything else gets `LocalStreamCopyStrategy`. Note that `std::fs::copy` itself picks the right syscall — the `FastCopyStrategy`/`LocalStreamCopyStrategy` split is about *whether to try fast copy at all* and how to report progress, not about which syscall to call. See [File Copy Operations](/docs/core/file-copy-operations) for the higher-level copy/move API. ## Known limitations * **Leaf-only ZFS dataset tracking** — see [Pool-aware dedup limitation](#pool-aware-dedup-limitation). * **Windows detection is shallow** — we get capacity and FS type, but not the storage-pool topology that Storage Spaces / ReFS mirroring exposes. Same-pool detection across ReFS volumes isn't implemented. * **Btrfs subvolume visibility** — we detect subvolumes but don't hide nested subvolumes created by Docker or snapper. Equivalent to ZFS `is_app_managed_dataset` would need a similar name-based filter. * **Network filesystems (NFS, SMB)** — treated as `MountType::Network` but no protocol-aware capacity or CoW handling. `Available` comes from whatever the server reports via statvfs. * **Encrypted volumes (LUKS, FileVault, BitLocker)** — opaque to us once mounted; they appear as whatever filesystem is layered on top. # Indexing Source: https://v2.spacedrive.com/core/indexing Spacedrive's indexing system solves a specific challenge: How do you build a distributed database that feels as fast as a local file explorer? The answer is a **Hybrid Indexing Engine** that layers an ultra-fast, in-memory ephemeral index over a robust, SQLite-backed persistent index. These two systems operate in tandem, allowing Spacedrive to instantly browse unmanaged locations (like a file manager) while seamlessly upgrading those paths to managed libraries (like a DAM) without UI flicker or state loss. ## The Hybrid Philosophy Most file management software forces a choice: fast, dumb directory listing (Explorer/Finder) or slow, heavy database ingestion (Lightroom/Photos). Spacedrive does both simultaneously by decoupling **Discovery** from **Persistence**. ### The Ephemeral Layer ("File Manager" Mode) When you open a location that hasn't been added to your library—an external drive, network share, or local directory—Spacedrive runs only Phase 1 (Discovery) of the indexing pipeline: * **Memory-Resident**: The index lives entirely in RAM * **Highly Optimized**: Custom slab allocators (NodeArena) and string interning (NameCache) compress file entries down to \~50 bytes * **Massive Scale**: Can index millions of files into RAM for accelerated local search * **Zero Database I/O**: Bypasses SQLite entirely for maximum throughput ### The Persistent Layer ("Library" Mode) For files you want to track across devices, Spacedrive persists data to a synchronized SQLite database using the full multi-phase pipeline with deep content analysis, deduplication, and closure-table hierarchy management. ### Seamless State Promotion The critical innovation is how these two layers communicate. When you add a location to your library for a folder you're currently browsing ephemerally, the system performs an **Intelligent Promotion**: * **UUID Preservation**: The persistent indexer detects the existing ephemeral index and carries over UUIDs assigned during the browsing session into the database * **UI Consistency**: Because UUIDs remain stable, the UI doesn't flicker or reset. Selections, active tabs, and view states remain intact * **Phase Continuation**: The indexer essentially "resumes" from Phase 1, flushing discovered entries to SQLite and proceeding to Phase 2 (Processing) and Phase 3 (Content Analysis) This architecture allows Spacedrive to act as your daily driver file explorer. You get instant access to files immediately, with the option to progressively "deepen" the index for files that matter. ## Architecture Overview The indexing system consists of specialized components working together: **IndexerJob** orchestrates the entire indexing process as a resumable job. It maintains state across application restarts and provides detailed progress reporting. **IndexerState** preserves all necessary information to resume indexing from any interruption point. This includes the current phase, directories to process, accumulated statistics, and ephemeral UUID mappings for preserving user metadata across browsing-to-persistent transitions. **DatabaseStorage** provides the low-level database CRUD layer. All database operations (create, update, move, delete) flow through this module for consistency. **DatabaseAdapter** implements both `ChangeHandler` (for filesystem watcher events) and `IndexPersistence` (for indexer job batches). Both pipelines use the same code to write entries to the database via `DatabaseStorage`. **MemoryAdapter** implements both `ChangeHandler` (for filesystem watcher events) and `IndexPersistence` (for indexer job batches). Both pipelines use the same code to write entries to the in-memory `EphemeralIndex`. This dual-implementation architecture unifies watcher and job pipelines, eliminating code duplication between real-time filesystem monitoring and batch indexing operations. **FileTypeRegistry** identifies files through extensions, magic bytes, and content analysis. The system integrates deeply with Spacedrive's job infrastructure, which provides automatic state persistence through MessagePack serialization. When you pause an indexing operation, the entire job state is saved to a dedicated jobs database, allowing seamless resumption even after application restarts. Indexing jobs can run for hours on large directories. The resumable architecture ensures no work is lost if interrupted. ## Database Architecture The indexing system uses a closure table for hierarchy management instead of recursive queries: ### Closure Table Parent-child relationships are stored in the `entry_closure` table with precomputed ancestor-descendant pairs. This makes "find all descendants" queries O(1) regardless of nesting depth, at the cost of additional storage (worst-case N² for deeply nested trees). ```sql theme={null} CREATE TABLE entry_closure ( ancestor_id INTEGER, descendant_id INTEGER, depth INTEGER ); ``` The closure table stores all transitive relationships. For a file at `/home/user/docs/report.pdf`, entries exist for: * (home\_id, report\_id, depth=3) * (user\_id, report\_id, depth=2) * (docs\_id, report\_id, depth=1) * (report\_id, report\_id, depth=0) Move operations require rebuilding closures for the entire moved subtree, which can affect thousands of rows when moving large directories. ### Directory Paths Cache The `directory_paths` table provides O(1) absolute path lookups for directories: ```sql theme={null} CREATE TABLE directory_paths ( entry_id INTEGER PRIMARY KEY, path TEXT UNIQUE ); ``` This eliminates recursive parent traversal when building file paths. Each directory stores its complete absolute path, enabling instant resolution for child entries. ### Entries Table ```sql theme={null} CREATE TABLE entry ( id INTEGER PRIMARY KEY, uuid UUID UNIQUE, parent_id INTEGER, name TEXT, extension TEXT, kind INTEGER, size BIGINT, inode BIGINT, content_id INTEGER, aggregate_size BIGINT, child_count INTEGER, file_count INTEGER ); ``` ## Indexing Phases The pipeline is broken into atomic, resumable phases. The **Ephemeral engine** runs only Phase 1. The **Persistent engine** runs all five phases. ### Phase 1: Discovery **Used by: Ephemeral & Persistent** A parallel, asynchronous filesystem walk designed for raw speed: * **Parallelism**: Work-stealing architecture where workers consume directories and directly enqueue subdirectories. On systems with 8+ cores, multiple threads scan concurrently, communicating via channels to maximize disk throughput * **Rules Engine**: Filters system files (`.git`, `node_modules`) at the discovery edge through `IndexerRuler`, which applies toggleable system rules (`NO_HIDDEN`, `NO_DEV_DIRS`) and dynamically loaded `.gitignore` patterns when inside a Git repository * **Output**: A stream of lightweight `DirEntry` objects Progress is measured by directories discovered. Entries are collected into batches of 1,000 items before moving to processing. ### Phase 2: Processing **Used by: Persistent Only** Converts discovered entries into database records: * **Topology Sorting**: Entries are sorted by depth (parents before children) to maintain referential integrity during batch insertion * **Batching**: Writes occur in transactions of 1,000 items to minimize SQLite locking overhead **Change Detection** runs during this phase. The `ChangeDetector` loads existing database entries for the indexing path, then compares against filesystem state to identify: * **New**: Paths not in database * **Modified**: Size or mtime differs * **Moved**: Same inode at different path * **Deleted**: In database but missing from filesystem Changes are processed in batch transactions. Each batch inserts closure table rows, updates the directory paths cache, and syncs entries across devices. **Ephemeral UUID Preservation** happens here. When a browsed folder is promoted to a managed location, UUIDs assigned during ephemeral indexing are preserved (`state.ephemeral_uuids`). This prevents orphaning user metadata like tags and notes attached during browsing sessions. The processing phase validates that the indexing path stays within location boundaries, preventing catastrophic cross-location deletion if watcher routing bugs send events for the wrong path. ### Phase 3: Aggregation **Used by: Persistent Only** To allow sorting folders by "True Size" (the size of all children recursively), we aggregate statistics from the bottom up: * **Closure Table**: Uses the `entry_closure` table to perform O(1) descendant lookups * **Leaf-to-Root**: Calculates sizes for the deepest directories first, bubbling totals up to the root These aggregates are stored in the entry table: * `aggregate_size`: Total bytes including subdirectories * `child_count`: Direct children only * `file_count`: Recursive file count This enables instant directory size display without traversing descendants. ### Phase 4: Content Identification **Used by: Persistent Only** Enables Spacedrive's deduplication capabilities through Content Addressable Storage (CAS): * **BLAKE3 Hashing**: Generates content hashes for files, linking entries to `content_identity` records * **Globally Deterministic UUIDs**: Uses v5 UUIDs (namespace hash of `content_hash` only) so any device can independently identify identical files and arrive at the exact same Content UUID without communicating. This enables offline duplicate detection across all devices and libraries * **Sync Order**: Content identities must be synced before entries to avoid foreign key violations on receiving devices. The job system enforces this ordering * **File Type Identification**: Runs via `FileTypeRegistry` to populate `kind_id` and `mime_type_id` fields for new content ### Phase 5: Finalizing **Used by: Persistent Only** Finalizing handles post-processing tasks like directory aggregation updates and potential processor dispatch (thumbnail generation for Deep Mode). ## Change Detection System The indexing system includes both batch and real-time change detection: ### Batch Change Detection `ChangeDetector` compares database state against filesystem during indexer job scans: ```rust theme={null} let mut detector = ChangeDetector::new(); detector.load_existing_entries(ctx, location_id, indexing_path).await?; for entry in discovered_entries { if let Some(change) = detector.check_path(&path, &metadata, inode) { // Process New, Modified, or Moved change } } let deleted = detector.find_deleted(&seen_paths); ``` The detector tracks paths by inode to identify moves. On Unix systems, inodes provide stable file identity across renames. Windows falls back to path-only matching since file indices are unstable across reboots. ### Real-Time Change Detection Both `DatabaseAdapter` and `MemoryAdapter` implement the `ChangeHandler` trait, which defines the interface for responding to filesystem watcher events: ```rust theme={null} pub trait ChangeHandler { async fn find_by_path(&self, path: &Path) -> Result>; async fn create(&mut self, metadata: &DirEntry, parent_path: &Path) -> Result; async fn update(&mut self, entry: &EntryRef, metadata: &DirEntry) -> Result<()>; async fn move_entry(&mut self, entry: &EntryRef, old_path: &Path, new_path: &Path) -> Result<()>; async fn delete(&mut self, entry: &EntryRef) -> Result<()>; } ``` The watcher routes events to the appropriate handler based on whether the path belongs to a persistent location (`DatabaseAdapter` → database) or ephemeral session (`MemoryAdapter` → memory). ## Indexing Modes and Scopes The system provides flexible configuration through modes and scopes: ### Index Modes **Shallow Mode** extracts only filesystem metadata (name, size, dates). Completes in under 500ms for typical directories. **Content Mode** adds BLAKE3 hashing to identify files by content. Enables deduplication and content tracking. **Deep Mode** performs full analysis including file type identification and metadata extraction. Triggers thumbnail generation for images and videos. ### Index Scopes **Current Scope** indexes only immediate directory contents. Used for responsive UI navigation. **Recursive Scope** indexes the entire directory tree. Used for full location indexing. ## Persistence and Ephemeral Indexing Spacedrive supports both persistent and ephemeral indexing modes: ### Persistent Indexing Persistent indexing stores all data in the database permanently. This is the default for library locations: * Full change detection and history * Syncs across devices * Survives application restarts * Enables offline search ### Ephemeral Indexing Ephemeral indexing keeps data in memory only, perfect for browsing external drives without permanent storage. The system uses highly memory-optimized structures (detailed in the Data Structures section below): * **NodeArena**: Slab allocator for `FileNode` entries with 32-bit entry IDs instead of 64-bit pointers * **NameCache**: Global string interning pool where one copy of "index.js" serves thousands of node\_modules files * **NameRegistry**: BTreeMap for fast name-based lookups without full-text indexing overhead Memory usage is around 50 bytes per entry vs 200+ bytes with naive approaches—a 4-6x reduction that enables browsing hundreds of thousands of files without database overhead. The `EphemeralIndexCache` tracks which paths have been indexed, are currently being indexed, or are registered for filesystem watching. When a watched path receives filesystem events, the system updates the in-memory index in real-time through the unified `ChangeHandler` trait (shared with persistent storage). Ephemeral mode lets you explore USB drives or network shares without permanently adding them to your library. ## Data Structures & Optimizations Specific low-level optimizations make the hybrid architecture viable: ### NodeArena (Ephemeral) The ephemeral index doesn't use standard HashMaps. Instead, it uses a memory-mapped **NodeArena**—a contiguous slab of memory that stores file nodes using 32-bit integers as pointers rather than 64-bit pointers. This reduces memory overhead by 4-6x compared to naive `HashMap` implementations, enabling browsing of hundreds of thousands of files without database overhead. ### Name Pooling (Ephemeral) In typical filesystems, filenames like `index.js`, `.DS_Store`, or `conf.yaml` repeat thousands of times. The **NameCache** interns these strings, storing them once and referencing them by pointer. Multiple directory trees can coexist in the same `EphemeralIndex` (browsing both `/mnt/nas` and `/media/usb` simultaneously), sharing the string interning pool for maximum deduplication. **Future Roadmap**: We plan to port the Name Pooling strategy from the ephemeral engine to the SQLite database schema. This will significantly reduce the storage footprint of the persistent library by deduplicating filename strings at the database level. ### Directory Path Caching (Persistent) While the database uses an adjacency list (`parent_id`) for structure, recursive queries are slow. The `directory_paths` table caches the full absolute path of every directory, enabling O(1) path resolution for any file without recursive parent traversal. ## Indexer Rules The `IndexerRuler` applies filtering rules during discovery to skip unwanted files: **System Rules** are toggleable patterns like: * `NO_HIDDEN`: Skip dotfiles (`.git`, `.DS_Store`) * `NO_DEV_DIRS`: Skip `node_modules`, `target`, `dist` * `NO_SYSTEM`: Skip OS folders (`System32`, `Windows`) **Git Integration**: When indexing inside a Git repository, rules are dynamically loaded from `.gitignore` files. This automatically excludes build artifacts and local configuration. Rules return a `RulerDecision` (Accept/Reject) for each path during discovery, preventing unwanted entries from ever reaching the processing phase. ## Index Integrity Verification The `IndexVerifyAction` checks integrity by running a fresh ephemeral scan and comparing metadata against the existing persistent index: ```rust theme={null} let verify = IndexVerifyAction::from_input(IndexVerifyInput { path }).await?; let output = verify.execute(library, context).await?; // output.report contains: // - missing_from_index: Files on disk but not in database // - stale_in_index: Entries in database but missing from filesystem // - metadata_mismatches: Size, mtime, or inode differences ``` The verification system detects: * **MissingFromIndex**: Files created outside Spacedrive * **StaleInIndex**: Deleted files not yet purged from database * **SizeMismatch**: Files modified externally * **ModifiedTimeMismatch**: Timestamp drift (with 1-second tolerance) * **InodeMismatch**: File replacement or filesystem corruption Verification runs as a library action and returns a detailed `IntegrityReport` with per-file diagnostics. ## Job System Integration The indexing system leverages Spacedrive's job infrastructure for reliability and monitoring. ### State Persistence When interrupted, the entire job state is serialized: ```rust theme={null} #[derive(Serialize, Deserialize)] pub struct IndexerState { phase: Phase, dirs_to_walk: VecDeque, entry_batches: Vec>, entry_id_cache: HashMap, ephemeral_uuids: HashMap, stats: IndexerStats, } ``` This state is stored in the jobs database, separate from your library data. On resume, the job picks up exactly where it left off. ### Progress Tracking Real-time progress flows through multiple channels: ```rust theme={null} pub struct IndexerProgress { pub phase: IndexPhase, pub total_found: IndexerStats, pub processing_rate: f32, pub estimated_remaining: Option, } ``` Progress updates are sent to the UI via channels, persisted to the database, and available through job queries for time estimates. ### Error Handling **Non-critical errors** are accumulated but don't stop indexing: * Permission denied on individual files * Corrupted metadata * Unsupported file types **Critical errors** halt the job with state preserved: * Database connection lost * Filesystem unmounted * Out of disk space ## Performance Characteristics Indexing performance varies by mode and scope: | Configuration | Performance | Use Case | | ------------------- | --------------- | --------------- | | Current + Shallow | `<500ms` | UI navigation | | Recursive + Shallow | \~10K files/sec | Quick scan | | Recursive + Content | \~1K files/sec | Normal indexing | | Recursive + Deep | \~100 files/sec | Media libraries | ### Optimization Techniques **Batch Processing**: Groups operations into transactions of 1,000 items, reducing database overhead by 30x. **Parallel Discovery**: Work-stealing model with atomic counters for directory traversal, using half of available CPU cores by default. **Entry ID Cache**: Eliminates redundant parent lookups during hierarchy construction, critical for deep directory trees. **Checkpoint Strategy**: Checkpoints occur every 5,000 items or 30 seconds, balancing durability with performance. ## Usage Examples ### Quick UI Navigation For responsive directory browsing: ```rust theme={null} let config = IndexerJobConfig::ui_navigation(location_id, path); let handle = library.jobs().dispatch(IndexerJob::new(config)).await?; ``` ### External Drive Browsing Explore without permanent storage: ```rust theme={null} let config = IndexerJobConfig::ephemeral_browse( usb_path, IndexScope::Recursive ); let job = IndexerJob::new(config); ``` ### Full Library Location Full indexing with content identification: ```rust theme={null} let config = IndexerJobConfig::new( location_id, path, IndexMode::Deep ); ``` ## CLI Commands The indexer is fully accessible through the CLI: ```bash theme={null} # Quick current directory scan spacedrive index quick-scan ~/Documents # Browse external drive spacedrive index browse /media/usb --ephemeral # Full location with progress monitoring spacedrive index location ~/Pictures --mode deep spacedrive job monitor # Watch progress ``` ## Troubleshooting ### Common Issues **Slow Indexing**: Check for large `node_modules` or build directories. System rules automatically skip common patterns, or use `.gitignore` to exclude project-specific artifacts. **High Memory Usage**: Reduce batch size for directories over 1M files. Ephemeral mode uses around 50 bytes per entry, so 100K files requires roughly 5MB. **Resume Not Working**: Ensure the jobs database isn't corrupted. Check logs for serialization errors. ### Debug Tools Enable detailed logging: ```bash theme={null} RUST_LOG=sd_core::ops::indexing=debug spacedrive start ``` Inspect job state: ```bash theme={null} spacedrive job info --detailed ``` ## Platform Notes **Windows**: Uses file indices for change detection where available, falling back to path-only matching. Supports long paths transparently. Network drives may require polling. **macOS**: Leverages FSEvents and native inodes. Integrates with Time Machine exclusions. APFS provides efficient cloning. **Linux**: Full inode support with detailed permissions. Handles diverse filesystems from ext4 to ZFS. Symbolic links supported with cycle detection. ## Best Practices 1. **Start shallow** for new locations to verify configuration before deep scans 2. **Use Git repositories** to automatically inherit `.gitignore` exclusions 3. **Monitor progress** through the job system instead of polling the database 4. **Schedule deep scans** during low-usage periods for large photo/video libraries 5. **Enable checkpointing** for locations over 100K files to survive interruptions Always let indexing jobs complete or pause them properly. Force-killing can corrupt the job state and require reindexing from scratch. ## Related Documentation * [Jobs](/docs/core/jobs) - Job system architecture * [Locations](/docs/core/locations) - Directory management * [Search](/docs/core/search) - Querying indexed data * [Performance](/docs/core/performance) - Optimization guide # Job System Source: https://v2.spacedrive.com/core/jobs The job system powers long-running operations in Spacedrive. It provides automatic persistence, progress tracking, and graceful interruption handling for tasks like indexing, file processing, and sync operations. Jobs execute asynchronously with minimal boilerplate. They persist their state to survive crashes and resume where they left off. The system integrates with Spacedrive's task executor for efficient resource usage. ## Core Concepts A job represents a resumable unit of work. Jobs report progress, handle interruptions, and maintain state across executions. The system manages job lifecycles automatically. Jobs are library-scoped. Each library maintains its own job database and execution queue. ### Job Lifecycle Jobs transition through defined states during execution: Job created and waiting for execution. Initial state after dispatch. Job actively executing. Progress updates flow to subscribers. Job interrupted but resumable. State persisted to database. Job finished successfully. Moved to history table. Failed or cancelled jobs cannot resume. The system distinguishes between recoverable interruptions and permanent failures. ### Key Components The job system consists of several interconnected parts: **Job Manager** coordinates all job operations. It maintains the job database, tracks running jobs, and handles lifecycle transitions. Located at `core/src/infra/job/manager.rs`. **Job Registry** enables automatic job discovery. Jobs register themselves at compile time using the derive macro. The registry creates jobs dynamically from saved state. See `core/src/infra/job/registry.rs`. **Job Context** provides execution environment. Jobs access the database, report progress, and interact with services through context. Implementation in `core/src/infra/job/context.rs`. **Job Executor** bridges jobs with the task system. It manages interruption signals and checkpoint operations. Found at `core/src/infra/job/executor.rs`. ## Defining Jobs Jobs implement two traits: `Job` for metadata and `JobHandler` for execution logic. ```rust theme={null} use sd_task_system::TaskId; use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, Debug)] struct ProcessFilesJob { location_id: i32, files: Vec, processed: usize, } #[typetag::serde(name = "process_files")] impl Job for ProcessFilesJob { const NAME: &'static str = "process_files"; const VERSION: u32 = 1; const IS_RESUMABLE: bool = true; } #[async_trait::async_trait] impl JobHandler for ProcessFilesJob { async fn run(&mut self, ctx: &JobContext) -> Result, JobError> { // Skip already processed files when resuming let files_to_process = &self.files[self.processed..]; for (idx, file) in files_to_process.iter().enumerate() { // Check for interruption if ctx.check_interrupted().await? { return Err(JobError::Interrupted); } // Process file process_file(file, ctx).await?; // Update progress self.processed += 1; ctx.report_count_progress(self.processed, self.files.len()).await; // Save checkpoint periodically if idx % 100 == 0 { ctx.checkpoint().await?; } } Ok(vec![]) } } ``` The `#[typetag::serde]` attribute enables polymorphic serialization. Jobs must be serializable to support resumption. ### Progress Reporting Jobs communicate progress through the context. The system supports multiple progress types: ```rust theme={null} // Count-based progress ctx.report_count_progress(current, total).await; // Percentage progress ctx.report_percentage_progress(0.75).await; // Bytes processed ctx.report_bytes_progress(processed_bytes, total_bytes).await; // Custom structured data ctx.report_structured_progress("phase", json!({ "stage": "analyzing", "files_found": 1500 })).await; ``` Progress updates throttle automatically. The system batches updates to prevent database overhead. ### Error Handling Jobs distinguish between recoverable and permanent errors: ```rust theme={null} // Recoverable - job can resume if network_unavailable() { return Err(JobError::Interrupted); } // Permanent failure - job cannot resume if corrupt_data() { return Err(JobError::Critical( "Data corruption detected".into() )); } // Non-critical errors accumulate ctx.report_non_critical_error("Skipped locked file").await; ``` Always check `ctx.check_interrupted()` in loops. This enables graceful shutdown and pause operations. ## Dispatching Jobs The job manager provides typed and dynamic dispatch methods: ```rust theme={null} // Typed dispatch let handle = manager.dispatch(ProcessFilesJob { location_id: 1, files: vec![path1, path2], processed: 0, }).await?; // Dynamic dispatch by name let handle = manager.dispatch_by_name( "process_files", json!({ "location_id": 1, "files": ["path1", "path2"], "processed": 0 }) ).await?; // Wait for completion let result = handle.wait().await?; ``` Job handles provide status monitoring and progress streaming: ```rust theme={null} // Subscribe to status changes let mut status_rx = handle.status(); while let Ok(status) = status_rx.recv().await { match status { JobStatus::Running => println!("Job started"), JobStatus::Completed => break, _ => {} } } // Stream progress updates let mut progress_rx = handle.progress(); while let Ok(progress) = progress_rx.recv().await { if let Some(count) = progress.count { println!("Processed {}/{}", count.current, count.total); } } ``` ## Database Schema Jobs persist to a dedicated SQLite database (`jobs.db`) with three tables: Active job records containing: Unique job identifier Job type name for registry lookup Schema version for migrations Current job state MessagePack serialized job state Latest progress snapshot Performance statistics JSON Completed jobs moved here for audit trails Resumption checkpoints for long-running jobs ## Advanced Features ### Job Versioning Jobs specify versions for schema evolution: ```rust theme={null} impl Job for DataMigrationJob { const VERSION: u32 = 2; // Increment when schema changes } ``` The registry validates versions during resumption. Incompatible versions fail to load. ### Extension Jobs The system supports WASM-based extension jobs: ```rust theme={null} manager.dispatch_extension_job( extension_id, job_name, job_data ).await?; ``` Extensions run in isolated contexts with limited capabilities. ### Performance Considerations The job system optimizes for throughput and resumability: * Progress updates batch at 2-second intervals * Checkpoints save incrementally * Database operations use prepared statements * Channels use bounded capacity to prevent memory growth For high-frequency operations, batch work into larger chunks. This reduces checkpoint overhead and improves performance. ## Integration Points Jobs integrate with core Spacedrive systems: **Task System**: Jobs execute as tasks with configurable priority. The executor handles work distribution across threads. **Event System**: State changes emit events for UI updates. Subscribe to `JOB_MANAGER_EVENTS` for notifications. **Action System**: User actions spawn jobs with audit context. The system tracks who initiated operations. **Library System**: Each library maintains independent job state. Jobs cannot access cross-library data. ## Common Patterns ### Batch Processing Process items in chunks for efficiency: ```rust theme={null} const BATCH_SIZE: usize = 1000; for (batch_idx, chunk) in items.chunks(BATCH_SIZE).enumerate() { if ctx.check_interrupted().await? { self.batch_idx = batch_idx; return Err(JobError::Interrupted); } process_batch(chunk).await?; ctx.report_count_progress( batch_idx * BATCH_SIZE + chunk.len(), items.len() ).await; ctx.checkpoint().await?; } ``` ### Phased Execution Split complex jobs into phases: ```rust theme={null} match self.phase { Phase::Discovery => { let items = discover_items(ctx).await?; self.items = items; self.phase = Phase::Processing; ctx.checkpoint().await?; } Phase::Processing => { process_items(&mut self.items, ctx).await?; self.phase = Phase::Cleanup; ctx.checkpoint().await?; } Phase::Cleanup => { cleanup_resources(ctx).await?; } } ``` ### Child Jobs Spawn dependent jobs (feature in development): ```rust theme={null} let child_ids = ctx.spawn_children(vec![ AnalyzeFileJob { path: file1 }, AnalyzeFileJob { path: file2 }, ]).await?; ctx.wait_for_children(child_ids).await?; ``` ## Debugging Enable file-based logging for troubleshooting: ```rust theme={null} std::env::set_var("SD_JOBS_FILE_LOG", "1"); ``` Logs write to `.spacedrive/jobs/{job_id}.log` with detailed execution traces. Monitor job metrics through the context: ```rust theme={null} let metrics = ctx.get_metrics(); println!("Execution time: {}s", metrics.elapsed_seconds); println!("Memory used: {}MB", metrics.memory_mb); ``` Never block the job executor thread. Use `tokio::task::spawn_blocking` for CPU-intensive work. The job system provides the foundation for reliable background processing in Spacedrive. Its resumable design ensures operations complete despite interruptions, while the progress system keeps users informed of ongoing work. # Key Manager Source: https://v2.spacedrive.com/core/key-manager The KeyManager is Spacedrive's unified cryptographic secret storage system. It provides encrypted storage for all sensitive data including device keys, library encryption keys, paired device session keys, and cloud credentials. ## Architecture ### Storage Backend KeyManager uses **redb**, an embedded key-value database, for encrypted secret storage: * **Database**: `/secrets.redb` * **Encryption**: XChaCha20-Poly1305 AEAD cipher * **Root Key**: Device key stored in OS keychain (or plaintext file fallback for development and testing only) All secrets are encrypted at rest using the device key. The database provides ACID guarantees and transactional operations. ### Device Key Hierarchy ``` Device Key (256-bit, from OS keychain) │ ├─ Library Keys (per-library encryption) │ └─ Used by: Cloud credentials, library-specific secrets │ ├─ Paired Device Data (session keys, device info) │ └─ Used by: P2P networking, device pairing │ └─ Arbitrary Secrets (application-level secrets) └─ Used by: Extensions, custom storage needs ``` ### Key Storage Locations **Device Key**: 1. **Primary**: OS Keychain * macOS: Keychain Access (`Spacedrive` service) * Linux: Secret Service API (GNOME Keyring, KWallet) * Windows: Windows Credential Manager 2. **Fallback**: `/device_key` (development and testing only) **Encrypted Secrets**: * All platforms: `/secrets.redb` ## What's Stored ### 1. Library Encryption Keys Each library has a unique encryption key used for encrypting library-specific secrets: ```rust theme={null} // Automatically generated when first accessed let library_key = key_manager.get_library_key(library_id).await?; ``` **Key format**: `library_{uuid}` **Used for**: * Cloud credential encryption * Library-specific secret storage * Future: Library database encryption ### 2. Paired Device Data Device pairing information and session keys for P2P communication: ```rust theme={null} pub struct PersistedPairedDevice { device_info: DeviceInfo, session_keys: SessionKeys, paired_at: DateTime, last_connected_at: Option>, trust_level: TrustLevel, relay_url: Option, } ``` **Key format**: `paired_device_{uuid}` **Includes**: * Device identity (name, slug, type, OS) * Session keys for encrypted communication * Trust level (Trusted, Unreliable, Blocked) * Connection metadata ### 3. Cloud Credentials OAuth tokens and API keys for cloud storage integrations: ```rust theme={null} pub struct CloudCredential { volume_fingerprint: String, encrypted_credential: Vec, // Encrypted with library key service_type: String, // "google_drive", "dropbox", etc. } ``` **Note**: Cloud credentials are stored in the library database, but encrypted using library keys from KeyManager. ### 4. Arbitrary Secrets General-purpose encrypted storage for application or extension needs: ```rust theme={null} // Store any secret key_manager.set_secret("my_api_key", b"secret_value").await?; // Retrieve let secret = key_manager.get_secret("my_api_key").await?; // Delete key_manager.delete_secret("my_api_key").await?; ``` ## Security Model ### Encryption **Algorithm**: XChaCha20-Poly1305 * **Cipher**: XChaCha20 (extended-nonce ChaCha20) * **Authentication**: Poly1305 MAC * **Nonce**: 24 bytes (randomly generated per encryption) * **Key size**: 256 bits **Process**: 1. Generate random 24-byte nonce 2. Encrypt plaintext with device key and nonce 3. Compute authentication tag 4. Prepend nonce to ciphertext: `[nonce(24) | ciphertext | tag(16)]` ### Device Key Protection The device key never exists in plaintext on disk (except in development with file fallback): **Production**: ``` User's device └─ OS Keychain (hardware-backed on supported devices) └─ Device Key (256-bit) └─ Protected by OS authentication (biometrics, password) ``` **Development and Testing Only**: ``` /device_key (file fallback) └─ Plaintext 32-byte file └─ Protected only by OS file permissions └─ Not recommended for production ``` ### Key Rotation Device key rotation is not currently supported. Rotating the device key would require re-encrypting all secrets in the database. Library keys are automatically generated and do not require manual rotation. ## API Usage ### Initialization The KeyManager is initialized once at application startup and shared via `Arc`: ```rust theme={null} // In Core initialization let device_key_fallback = data_dir.join("device_key"); let key_manager = Arc::new(KeyManager::new_with_fallback( data_dir.clone(), Some(device_key_fallback), )?); ``` ### Basic Operations ```rust theme={null} // Get device key let device_key = key_manager.get_device_key().await?; // Get library key (auto-generates if not exists) let library_key = key_manager.get_library_key(library_id).await?; // Store a secret key_manager.set_secret("api_token", token_bytes).await?; // Retrieve a secret let token = key_manager.get_secret("api_token").await?; // Delete a secret key_manager.delete_secret("api_token").await?; // Close database (on shutdown) key_manager.close().await?; ``` ### Integration Examples **Device Manager** (network identity): ```rust theme={null} // DeviceManager uses KeyManager for device key let device = DeviceManager::init(&data_dir, key_manager.clone(), None)?; let device_key = device.master_key().await?; let identity = NetworkIdentity::from_device_key(&device_key).await?; ``` **Device Pairing** (session keys): ```rust theme={null} // Store paired device let persistence = DevicePersistence::new(key_manager.clone()); persistence.add_paired_device( device_id, device_info, session_keys, relay_url, ).await?; // Load paired devices let devices = persistence.load_paired_devices().await?; ``` **Cloud Credentials**: ```rust theme={null} // Encrypt and store cloud credential let cloud_manager = CloudCredentialManager::new(library_id, key_manager.clone()); cloud_manager.store_credential( volume_fingerprint, credential, service_type, ).await?; ``` ## Error Handling ```rust theme={null} use sd_core::crypto::key_manager::KeyManagerError; match key_manager.get_secret("my_key").await { Ok(secret) => println!("Secret: {:?}", secret), Err(KeyManagerError::KeyNotFound(key)) => { println!("Secret '{}' not found", key); } Err(KeyManagerError::EncryptionError(e)) => { eprintln!("Encryption failed: {}", e); } Err(e) => eprintln!("KeyManager error: {}", e), } ``` ## Performance Considerations ### Caching The device key is cached in memory after first retrieval to avoid repeated OS keychain access: ```rust theme={null} // First call: retrieves from keychain let key1 = key_manager.get_device_key().await?; // Subsequent calls: returns cached value (fast) let key2 = key_manager.get_device_key().await?; ``` ### Concurrent Access KeyManager uses async locking for safe concurrent access: ```rust theme={null} // Safe to call from multiple tasks let key_manager = Arc::new(KeyManager::new(data_dir)?); tokio::spawn({ let km = key_manager.clone(); async move { km.set_secret("key1", b"value").await } }); tokio::spawn({ let km = key_manager.clone(); async move { km.get_secret("key2").await } }); ``` ### Database Size The redb database grows with the number of secrets stored. Typical sizes: * **Fresh install**: \~4KB (empty database) * **With 10 paired devices**: \~20KB * **With 100 secrets**: \~50KB The database is compacted automatically by redb. ## Migration from Legacy Storage Prior to the unified KeyManager, Spacedrive stored secrets in multiple locations: * Device key: `/master_key` file * Paired devices: `/networking/paired_devices.json` (AES-256-GCM encrypted) * Cloud credentials: OS keychain (unreliable) These systems have been consolidated into KeyManager for better security and reliability. ## Troubleshooting ### "Failed to access keychain" Error If KeyManager can't access the OS keychain: 1. **macOS**: Grant Keychain Access permission in System Preferences 2. **Linux**: Install `gnome-keyring` or `kwallet` 3. **Fallback**: KeyManager will use file fallback at `/device_key` ### Corrupted Database If `secrets.redb` becomes corrupted: ```bash theme={null} # Backup first cp ~/.spacedrive/secrets.redb ~/.spacedrive/secrets.redb.backup # Remove corrupted database (will lose paired devices!) rm ~/.spacedrive/secrets.redb # Restart Spacedrive (new database will be created) ``` Deleting `secrets.redb` will unpair all devices and remove cloud credentials. You'll need to re-pair devices and re-authenticate cloud services. ### Inspecting Secrets (Development) ```rust theme={null} // List all paired device keys let db = key_manager.db.read().await; let read_txn = db.begin_read()?; let table = read_txn.open_table(SECRETS_TABLE)?; for item in table.iter()? { let (key, _value) = item?; if key.value().starts_with("paired_device_") { println!("Device key: {}", key.value()); } } ``` ## Security Best Practices * **Always use OS keychain** in production (never file fallback) * **Restrict file permissions** on `secrets.redb` (chmod 600) * **Enable disk encryption** (FileVault, LUKS, BitLocker) * **Backup device key** from keychain before system migration ### File Permissions Ensure strict permissions on sensitive files: ```bash theme={null} # Check permissions ls -la ~/.spacedrive/secrets.redb ls -la ~/.spacedrive/device_key # If using fallback # Fix if needed chmod 600 ~/.spacedrive/secrets.redb chmod 600 ~/.spacedrive/device_key ``` ### Backup Strategy The device key is critical for accessing all secrets: ```bash theme={null} # macOS: Export device key from Keychain security find-generic-password -s "Spacedrive" -a "device_key" -w # Linux: Backup entire secrets database cp ~/.spacedrive/secrets.redb ~/backup/ # Windows: Export from Credential Manager cmdkey /list | findstr Spacedrive ``` ## Related Documentation * [Devices](/docs/core/devices) - Device identity and pairing * [Networking](/docs/core/networking) - P2P communication using session keys * [Cloud Integration](/docs/core/cloud-integration) - Cloud credential storage * [Security](/docs/core/security) - Overall security architecture # Library Source: https://v2.spacedrive.com/core/library Libraries are self-contained directories that store all your data, metadata, and thumbnails in one place. Each library lives in a single folder with a `.sdlibrary` extension. You can move libraries between machines, back them up to external drives, or share them with others by copying the directory. When you open a library, Spacedrive loads its database and configuration into memory and locks it to prevent corruption from concurrent access. ## Structure Each library contains `library.json` for configuration and metadata, `database.db` for the SQLite database, and a `thumbnails/` directory with two-level sharding for performance. The thumbnails directory includes `metadata.json` for generation settings. A `.sdlibrary.lock` file appears when the library is open to prevent multiple processes from accessing it simultaneously. Future directories include `previews/` for full-size previews, `indexes/` for search indexes, and `exports/` for temporary exports. ## Core Components The **LibraryManager** creates, opens, and discovers libraries on your system. Each active **Library** instance holds a database connection and loaded configuration. The **LibraryConfig** stores settings like thumbnail quality and sync preferences in `library.json`. ## Working with Libraries Create a library with `create_library("My Photos", None)`. Omit the path to use your default libraries directory. Open an existing library with `open_library()` by providing its path. The manager checks for lock files and loads configuration before returning the instance. Scan your system for libraries with `scan_for_libraries()`. This searches common locations and returns metadata without opening each library. ## Thumbnail Management Libraries store thumbnails using content-addressed storage with two-level directory sharding. Save thumbnails with `save_thumbnail()`, check existence with `has_thumbnail()`, and retrieve them with `get_thumbnail()`. Thumbnails organize automatically into subdirectories based on their content hash. ## Configuration The `library.json` file stores all library settings: Schema version for compatibility Unique UUID for the library Display name of the library User-configurable options including thumbnail quality and sync preferences Cached counts and sizes for quick display ## Portability Self-contained libraries work immediately after copying to a new location with zero configuration. Copy the entire folder to create a complete backup. Store libraries on external drives, network shares, or cloud-synced folders for automatic backup. Future versions will add new directories for features like search indexes and version history without breaking existing libraries. # Library Sync Source: https://v2.spacedrive.com/core/library-sync Spacedrive synchronizes library metadata across all your devices using a leaderless peer-to-peer model. Every device is equal. No central server, no single point of failure. ## How Sync Works Sync uses two protocols based on data ownership: **Device-owned data** (locations, files): The owning device broadcasts changes in real-time and responds to pull requests for historical data. No conflicts possible since only the owner can modify. **Shared resources** (tags, collections): Any device can modify. Changes are ordered using Hybrid Logical Clocks (HLC) to ensure consistency across all devices. Library Sync handles metadata synchronization. For file content synchronization between storage locations, see [File Sync](/docs/core/file-sync). ## Quick Reference | Data Type | Ownership | Sync Method | Conflict Resolution | | -------------- | ------------ | --------------- | ------------------- | | Devices | Shared | HLC-ordered log | Last write wins | | Locations | Device-owned | State broadcast | None needed | | Files/Folders | Device-owned | State broadcast | None needed | | Volumes | Device-owned | State broadcast | None needed | | Tags | Shared | HLC-ordered log | Per-model strategy | | Collections | Shared | HLC-ordered log | Per-model strategy | | User Metadata | Shared | HLC-ordered log | Per-model strategy | | Spaces | Shared | HLC-ordered log | Per-model strategy | | Media Metadata | Shared | HLC-ordered log | Per-model strategy | | Content IDs | Shared | HLC-ordered log | Per-model strategy | ## Data Ownership Spacedrive recognizes that some data naturally belongs to specific devices. ### Device-Owned Data Only the device with physical access can modify: * **Locations**: Filesystem paths like `/Users/alice/Photos` * **Entries**: Files and folders within those locations * **Volumes**: Physical drives and mount points ### Shared Resources Any device can create or modify: * **Devices**: Library membership - all devices automatically discover each other * **Tags**: Labels applied to files, with hierarchy support * **Collections**: Groups of files * **User Metadata**: Notes, ratings, custom fields * **Content Identities**: Content-hash-based file identification * **Spaces**: User-defined workspace containers * **Media Metadata**: Video, audio, and image metadata * **Sidecars**: Generated files like thumbnails and previews * **Audit Logs**: Action history for compliance * **Extension Data**: Custom models from extensions This ownership model eliminates most conflicts and simplifies synchronization. ## Sync State Machine The sync service runs as a background process with well-defined state transitions. ### States | State | Description | | -------------------------------- | -------------------------------------------- | | `Uninitialized` | Device hasn't synced yet (no watermarks) | | `Backfilling { peer, progress }` | Receiving initial state from a peer (0-100%) | | `CatchingUp { buffered_count }` | Processing updates buffered during backfill | | `Ready` | Fully synced, applying real-time updates | | `Paused` | Sync disabled or device offline | ### Transitions | From | Trigger | To | | --------------- | ---------------------- | ------------------------------------------- | | `Uninitialized` | Peer becomes available | `Backfilling` | | `Uninitialized` | Already has data | `Ready` | | `Backfilling` | Transfer complete | `CatchingUp` | | `Backfilling` | Peer disconnected | Save checkpoint, select new peer | | `CatchingUp` | Buffer empty | `Ready` | | `CatchingUp` | 5 consecutive failures | `Uninitialized` (escalate to full backfill) | | `Ready` | Device goes offline | `Paused` | | `Ready` | Watermarks stale | `CatchingUp` | | `Paused` | Device comes online | `Ready` or `CatchingUp` | ### Buffer Queue During backfill, incoming real-time updates are buffered to prevent data loss: * **Max capacity**: 100,000 updates * **Ordering**: Priority queue sorted by timestamp/HLC * **Overflow handling**: Drops oldest updates to prevent OOM * **Processing**: Drained in order during CatchingUp phase ### Catch-Up Escalation If incremental catch-up fails repeatedly, the system uses exponential backoff before escalating to a full backfill. | Attempt | Delay | Action | | ------- | ------------- | ----------------------------------------------- | | 1 | 10s | Retry | | 2 | 20s | Retry | | 3 | 40s | Retry | | 4 | 80s | Retry | | 5 | 160s (capped) | Retry | | 6+ | - | Reset to `Uninitialized`, trigger full backfill | This prevents permanent sync failures from transient network issues. ## Sync Protocols ### State-Based Sync (Device-Owned) See `core/tests/sync_backfill_test.rs` and `core/tests/sync_realtime_test.rs` for sync protocol tests. State-based sync uses two mechanisms depending on the scenario: **Real-time broadcast**: When Device A creates or modifies a location, it sends a `StateChange` message via unidirectional stream to all connected peers. Peers apply the update immediately. **Pull-based backfill**: When Device B is new or reconnecting after being offline, it sends a `StateRequest` to Device A. Device A responds with a `StateResponse` containing records in configurable batches. This request/response pattern uses bidirectional streams. For large datasets, pagination automatically handles multiple batches using cursor-based checkpoints. The `StateRequest` includes both watermark and cursor: ```rust theme={null} StateRequest { model_types: ["location", "entry"], since: Some(last_state_watermark), // Only records newer than this checkpoint: Some("2025-10-21T19:10:00.456Z|uuid"), // Resume cursor batch_size: config.batching.backfill_batch_size, } ``` No version tracking needed. The owner's state is always authoritative. ### Log-Based Sync (Shared Resources) See `core/tests/sync_realtime_test.rs` for shared resource sync tests. Shared resources sync through an ordered log. When you create a tag, the device inserts it locally, generates an HLC timestamp, appends to the sync log, and broadcasts a `SharedChange` message. Receiving devices apply changes in HLC order, then acknowledge receipt. Once all peers acknowledge, the entry is pruned from the log. Batch operations work the same way but send a single `SharedChangeBatch` message containing multiple entries. This reduces network overhead during bulk imports while preserving HLC ordering for each individual record. For large datasets, the system uses HLC-based pagination. Each request includes the last seen HLC, and the peer responds with the next batch. This scales to millions of shared resources. ## Hybrid Logical Clocks HLC conflict resolution is covered in `core/tests/sync_realtime_test.rs`. HLCs provide global ordering without synchronized clocks: ```rust theme={null} pub struct HLC { /// Physical time component (milliseconds since Unix epoch) pub timestamp: u64, /// Logical counter for events within the same millisecond pub counter: u64, /// Device that generated this HLC (for deterministic ordering) pub device_id: Uuid, } ``` The HLC string format for storage and comparison is `{timestamp:016x}-{counter:016x}-{device_id}`, which is lexicographically sortable. Properties: * Events maintain causal ordering * Any two HLCs can be compared * No clock synchronization required ### HLC Update Algorithm When generating or receiving an HLC, the system maintains causality: ```rust theme={null} fn generate(last: Option, device_id: Uuid) -> HLC { let physical = now_millis(); let (timestamp, counter) = match last { Some(prev) if prev.timestamp >= physical => { // Clock hasn't advanced, increment counter (prev.timestamp, prev.counter + 1) } Some(prev) => { // Clock advanced, reset counter (physical, 0) } None => (physical, 0), }; HLC { timestamp, counter, device_id } } fn update(&mut self, received: HLC) { let physical = now_millis(); let max_ts = max(self.timestamp, max(received.timestamp, physical)); self.counter = if max_ts == self.timestamp && max_ts == received.timestamp { max(self.counter, received.counter) + 1 } else if max_ts == self.timestamp { self.counter + 1 } else if max_ts == received.timestamp { received.counter + 1 } else { 0 // Physical time advanced }; self.timestamp = max_ts; } ``` This ensures: * Local events always have increasing HLCs * Received events update local clock to maintain causality * Clock drift is bounded by the max of all observed timestamps ### Conflict Resolution Each shared model implements its own `apply_shared_change()` method, allowing per-model conflict resolution strategies. The `Syncable` trait provides this flexibility. **Default behavior (most models)**: Last Write Wins based on HLC ordering. When two devices concurrently modify the same record, the change with the higher HLC is applied: ``` Device A updates tag with HLC(timestamp_a, 0, device-a) Device B updates same tag with HLC(timestamp_b, 0, device-b) If timestamp_b > timestamp_a: Device B's version wins If timestamps equal: Higher device_id breaks the tie (deterministic) ``` **Creation conflicts**: When two devices create resources with the same logical identity (e.g., same tag name) but different UUIDs, both resources coexist. This is an implicit union merge - no data is lost. ``` Device A creates tag "Vacation" with UUID-A Device B creates tag "Vacation" with UUID-B After sync: Both tags exist (different UUIDs, same name) Tags can be disambiguated by namespace or merged by user ``` **Custom strategies**: Models can override `apply_shared_change()` to implement: * Field-level merging (merge specific fields from both versions) * CRDT-style merging (for sets, counters, etc.) * Domain-specific rules (e.g., always prefer longer descriptions) The sync system checks the peer log before applying changes to ensure only newer updates are applied. ## Database Architecture ### Main Database (database.db) Contains all library data from all devices: ```sql theme={null} -- Device-owned tables CREATE TABLE devices ( id INTEGER PRIMARY KEY, uuid TEXT UNIQUE, name TEXT, slug TEXT ); CREATE TABLE volumes ( id INTEGER PRIMARY KEY, uuid TEXT UNIQUE, device_id INTEGER, -- Owner device fingerprint TEXT, -- Stable cross-mount identifier FOREIGN KEY (device_id) REFERENCES devices(id) ); CREATE TABLE locations ( id INTEGER PRIMARY KEY, uuid TEXT UNIQUE, volume_id INTEGER, -- Ownership via volume entry_id INTEGER, -- Root entry name TEXT, FOREIGN KEY (volume_id) REFERENCES volumes(id) ); CREATE TABLE entries ( id INTEGER PRIMARY KEY, uuid TEXT UNIQUE, volume_id INTEGER, -- Ownership via volume parent_id INTEGER, name TEXT, kind INTEGER, size_bytes INTEGER, FOREIGN KEY (volume_id) REFERENCES volumes(id) ); -- Shared resource tables CREATE TABLE tags ( id INTEGER PRIMARY KEY, uuid TEXT UNIQUE, canonical_name TEXT ); ``` Ownership flows through volumes: Device → Volume → Location/Entry. This indirection enables portable storage to transfer between devices with a single volume update. ### Sync Database (sync.db) Contains pending changes for shared resources and sync coordination data: ```sql theme={null} -- Shared resource changes pending acknowledgment CREATE TABLE shared_changes ( hlc TEXT PRIMARY KEY, model_type TEXT NOT NULL, record_uuid TEXT NOT NULL, change_type TEXT NOT NULL, -- insert/update/delete data TEXT NOT NULL, -- JSON payload created_at TEXT NOT NULL -- When this change was logged ); -- Peer acknowledgment tracking (outgoing - for pruning our log) -- Tracks which of our changes each peer has acknowledged receiving CREATE TABLE peer_acks ( peer_device_id TEXT PRIMARY KEY, last_acked_hlc TEXT NOT NULL, acked_at TEXT NOT NULL ); -- Per-resource watermarks for device-owned incremental sync CREATE TABLE device_resource_watermarks ( device_uuid TEXT NOT NULL, peer_device_uuid TEXT NOT NULL, resource_type TEXT NOT NULL, -- "location", "entry", "volume", etc. last_watermark TEXT NOT NULL, -- RFC3339 timestamp updated_at TEXT NOT NULL, PRIMARY KEY (device_uuid, peer_device_uuid, resource_type) ); -- Per-peer watermarks for shared resource incremental sync (incoming) -- Tracks the maximum HLC we've received from each peer CREATE TABLE peer_received_watermarks ( device_uuid TEXT NOT NULL, peer_device_uuid TEXT NOT NULL, max_received_hlc TEXT NOT NULL, -- Maximum HLC received from this peer updated_at TEXT NOT NULL, PRIMARY KEY (device_uuid, peer_device_uuid) ); -- Resumable backfill checkpoints CREATE TABLE backfill_checkpoints ( id INTEGER PRIMARY KEY, peer_device_uuid TEXT NOT NULL, model_type TEXT NOT NULL, resume_token TEXT, -- timestamp|uuid cursor progress REAL, -- 0.0 to 1.0 completed_models TEXT, -- JSON array of completed model types created_at TEXT NOT NULL, updated_at TEXT NOT NULL ); ``` The sync database stays small (under 1MB) due to aggressive pruning after acknowledgments. ## Using the Sync API The sync API handles all complexity internally. Three methods cover all use cases: ```rust theme={null} // 1. Simple models without FK relationships (shared resources) // Use sync_model() - no DB connection needed let tag = tag::ActiveModel { ... }.insert(db).await?; library.sync_model(&tag, ChangeType::Insert).await?; // 2. Models with FK relationships (needs UUID lookup) // Use sync_model_with_db() - requires DB connection for FK conversion let location = location::ActiveModel { ... }.insert(db).await?; library.sync_model_with_db(&location, ChangeType::Insert, db.conn()).await?; // 3. Bulk operations (1000+ records) // Use sync_models_batch() - batches FK lookups and network broadcasts let entries: Vec = bulk_insert_entries(db).await?; library.sync_models_batch(&entries, ChangeType::Insert, db.conn()).await?; ``` The API automatically: * Detects ownership type (device-owned vs shared) * Manages HLC timestamps for shared resources * Converts between local IDs and UUIDs for foreign keys * Uses batch FK lookups to reduce queries * Batches network broadcasts (single message for many items) * Creates tombstones for deletions (device-owned models) * Manages the sync log and pruning ## Implementing Syncable Models To make a model syncable, implement the `Syncable` trait and register it with a macro: ```rust theme={null} impl Syncable for YourModel { /// Stable model identifier used in sync logs (must never change) const SYNC_MODEL: &'static str = "your_model"; /// Get the globally unique ID for this resource fn sync_id(&self) -> Uuid { self.uuid } /// Version number for optimistic concurrency control fn version(&self) -> i64 { self.version } /// Fields to exclude from sync (platform-specific data) fn exclude_fields() -> Option<&'static [&'static str]> { Some(&["id", "created_at", "updated_at"]) } /// Declare sync dependencies on other models fn sync_depends_on() -> &'static [&'static str] { &["parent_model"] // Models that must sync first } /// Declare foreign key mappings for automatic UUID conversion fn foreign_key_mappings() -> Vec { vec![ FKMapping::new("device_id", "devices"), FKMapping::new("parent_id", "your_models"), ] } } // Register with sync system - choose based on ownership model: // For shared resources (any device can modify): crate::register_syncable_shared!(Model, "your_model", "your_table"); // For shared resources with closure table rebuild after backfill: crate::register_syncable_shared!(Model, "tag_relationship", "tag_relationship", with_rebuild); // For device-owned data: crate::register_syncable_device_owned!(Model, "your_model", "your_table"); // With deletion support: crate::register_syncable_device_owned!(Model, "your_model", "your_table", with_deletion); // With deletion + post-backfill rebuild (for models with closure tables): crate::register_syncable_device_owned!(Model, "entry", "entries", with_deletion, with_rebuild); ``` The `with_rebuild` flag triggers `post_backfill_rebuild()` after backfill completes, which rebuilds derived tables like `entry_closure` or `tag_closure` from the synced base data. The registration macros use the `inventory` crate for automatic discovery at startup - no manual registry initialization needed. ### Custom Conflict Resolution Shared models can implement custom conflict resolution by overriding `apply_shared_change()`: ```rust theme={null} impl Syncable for YourModel { // ... other trait methods ... async fn apply_shared_change( entry: SharedChangeEntry, db: &DatabaseConnection, ) -> Result<(), sea_orm::DbErr> { match entry.change_type { ChangeType::Insert | ChangeType::Update => { // Option 1: Default LWW - just upsert let active = deserialize_to_active_model(&entry.data)?; Entity::insert(active) .on_conflict(/* upsert on uuid */) .exec(db).await?; // Option 2: Field-level merge if let Some(existing) = Entity::find_by_uuid(uuid).one(db).await? { let merged = merge_fields(existing, incoming, entry.hlc); merged.update(db).await?; } // Option 3: Domain-specific rules // e.g., keep longer description, union tags, etc. } ChangeType::Delete => { Entity::delete_by_uuid(uuid).exec(db).await?; } } Ok(()) } } ``` Currently, all models use the default LWW strategy. Custom strategies can be added per-model as needed without changes to the sync infrastructure. ### Dependency Resolution Algorithm To prevent foreign key violations, the sync system must process models in a specific order (e.g., `Device` records must exist before the `Location` records that depend on them). Spacedrive determines this order automatically at startup using a deterministic algorithm. The process works as follows: 1. **Dependency Declaration**: Each syncable model declares its parent models using the `sync_depends_on()` function. This creates a dependency graph where an edge from `Entry` to `Volume` means `Entry` depends on `Volume`. 2. **Topological Sort**: The `SyncRegistry` takes the full list of models and their dependencies and performs a **topological sort** using Kahn's algorithm. This algorithm produces a linear ordering of the models where every parent model comes before its children. It also detects circular dependencies (e.g., A depends on B, and B depends on A). 3. **Ordered Execution**: The `BackfillManager` receives this ordered list (e.g., `["device", "volume", "tag", "location", "entry"]`) and uses it to sync data in the correct sequence, guaranteeing that no foreign key violations can occur. ### Dependency Management The sync system respects model dependencies and enforces ordering: | Order | Models | Reason | | ----- | --------------------------------------------------------- | ---------------------------------------- | | 1 | Shared resources (tags, collections, content\_identities) | No dependencies, entries reference these | | 2 | Devices | Root of ownership chain | | 3 | Volumes | Needs devices | | 4 | Locations | Needs volumes | | 5 | Entries | Needs volumes and content\_identities | Shared resources sync first because entries reference content identities via foreign key. This prevents NULL foreign key references during backfill. ### Foreign Key Translation The sync system must ensure that relationships between models are preserved across devices. Since each device uses local, auto-incrementing integer IDs for performance, these IDs cannot be used for cross-device references. This is where foreign key translation comes in, a process orchestrated by the `foreign_key_mappings()` function on the `Syncable` trait. **The Process:** 1. **Outgoing**: When a record is being prepared for sync, the system uses the `foreign_key_mappings()` definition to find all integer foreign key fields (e.g., `parent_id: 42`). It looks up the corresponding UUID for each of these IDs in the local database and sends the UUIDs over the network (e.g., `parent_uuid: "abc-123..."`). 2. **Incoming**: When a device receives a record, it does the reverse. It uses `foreign_key_mappings()` to identify the incoming UUID foreign keys, looks up the corresponding local integer ID for each UUID, and replaces them before inserting the record into its own database (e.g., `parent_uuid: "abc-123..."` → `parent_id: 15`). This entire translation process is automatic and transparent. **Batch FK Optimization**: For bulk operations (backfill, batch sync), the system uses `batch_map_sync_json_to_local()` which reduces database queries from N×M (N records × M FKs) to just M (one query per FK type). For 1000 records with 3 FK fields each, this is a 365x reduction in queries. ```rust theme={null} // Before: 3000 queries for 1000 records with 3 FKs each // After: 3 queries total (one per FK type) let result = batch_map_sync_json_to_local(records, fk_mappings, db).await?; // Records with missing FK references are returned separately for retry for (record, fk_field, missing_uuid) in result.failed { // Buffer for retry when dependency arrives } ``` **Separation of Concerns:** `sync_depends_on()` determines the **order** of model synchronization at a high level. `foreign_key_mappings()` handles the **translation** of specific foreign key fields within a model during the actual data transfer. ### Dependency Tracking During backfill, records may arrive before their FK dependencies (e.g., an entry before its parent folder). The `DependencyTracker` handles this efficiently: ```rust theme={null} // Record fails FK resolution - parent doesn't exist yet let error = "Foreign key lookup failed: parent_uuid abc-123 not found"; let missing_uuid = extract_missing_dependency_uuid(&error); // Track the waiting record dependency_tracker.add_dependency(missing_uuid, buffered_update); // Later, when parent record arrives and is applied... let waiting = dependency_tracker.resolve(parent_uuid); for update in waiting { // Retry applying - FK should resolve now apply_update(update).await?; } ``` This provides **O(n) targeted retry** instead of O(n²) "retry entire buffer" approaches: | Approach | Records | FKs | Retries | Complexity | | ------------------- | ------- | --- | --------------- | ---------- | | Retry all | 10,000 | 3 | 10,000 × 10,000 | O(n²) | | Dependency tracking | 10,000 | 3 | \~100 targeted | O(n) | The tracker maintains a map of `missing_uuid → Vec`. When a record is successfully applied, its UUID is checked against the tracker to resolve any waiting dependents. ## Sync Flows See `core/tests/sync_backfill_test.rs` and `core/tests/sync_realtime_test.rs` for sync flow tests. ### Creating a Location Location and entry sync is tested in `test_initial_backfill_alice_indexes_first` in `core/tests/sync_backfill_test.rs`. User adds `/Users/alice/Documents`: * Insert into local database * Call `library.sync_model(&location)` * Send `StateChange` message to connected peers via unidirectional stream Receives `StateChange` message: - Map device UUID to local ID - Insert location (read-only view) - Update UI instantly No conflicts possible (ownership is exclusive) ### Creating a Tag User creates "Important" tag: * Insert into local database * Generate HLC timestamp * Append to sync log * Broadcast to peers Receives tag creation: - Update local HLC - Apply change in order - Send acknowledgment After all acknowledgments: * Remove from sync log * Log stays small ### New Device Joins New device sends `SharedChangeRequest`: * Peer responds with recent changes from sync log * If log was pruned, includes current state snapshot * For larger datasets, paginate using HLC cursors * Apply tags, collections, content identities in HLC order * Shared resources sync first to satisfy foreign key dependencies (entries reference content identities) New device sends `StateRequest` to each peer: - Request locations, entries, volumes owned by peer - Peer responds with `StateResponse` containing records in batches - For large datasets, automatically paginates using `timestamp|uuid` cursors - Apply in dependency order (devices, then locations, then entries) Process any changes that occurred during backfill from the buffer queue. Transition to Ready state. Begin receiving real-time broadcasts. ## Advanced Features ### Transitive Sync See `core/tests/sync_backfill_test.rs` for backfill scenarios. Spacedrive does not require a direct connection between all devices to keep them in sync. Changes can propagate transitively through intermediaries, ensuring the entire library eventually reaches a consistent state. This is made possible by two core architectural principles: 1. **Complete State Replication**: Every device maintains a full and independent copy of the entire library's shared state (like tags, collections, etc.). When Device A syncs a new tag to Device B, that tag becomes a permanent part of Device B's database, not just a temporary message. 2. **State-Based Backfill**: When a new or offline device (Device C) connects to any peer in the library (Device B), it initiates a backfill process. As part of this process, Device C requests the complete current state of all shared resources from Device B. **How it Works in Practice:** Device A creates a new tag. It connects to Device B and syncs the tag. The tag is now stored in the database on both A and B. Device A then goes offline. Device C comes online and connects only to Device B. It has never communicated with Device A. Device C requests the complete state of all shared resources from Device B. Since Device B has a full copy of the library state (including the tag from Device A), it sends that tag to Device C. Device C now has the tag created by Device A, even though they never connected directly. The change has propagated transitively. This architecture provides significant redundancy and resilience, as the library can stay in sync as long as there is any path of connectivity between peers. ### Peer Selection When starting a backfill, the system scores available peers to select the best source: ```rust theme={null} fn score(&self) -> i32 { let mut score = 0; // Prefer online peers if self.is_online { score += 100; } // Prefer peers with complete state if self.has_complete_state { score += 50; } // Prefer low latency (measured RTT) score -= (self.latency_ms / 10) as i32; // Prefer less busy peers score -= (self.active_syncs * 10) as i32; score } ``` Peers are sorted by score (highest first). The best peer is selected for backfill. If that peer disconnects, the checkpoint is saved and a new peer is selected. ### Deterministic UUIDs System-provided resources use deterministic UUIDs (v5 namespace hashing) so they're identical across all devices: ```rust theme={null} // System tags have consistent UUIDs everywhere let system_tag_uuid = deterministic_system_tag_uuid("system"); // Always: 550e8400-e29b-41d4-a716-446655440000 (example) // Library-scoped defaults let default_uuid = deterministic_library_default_uuid(library_id, "default_collection"); ``` **Use deterministic UUIDs for:** * System tags (system, screenshot, download, document, image, video, audio, hidden, archive, favorite) * Built-in collections * Library defaults **Use random UUIDs for:** * User-created tags (supports duplicate names in different contexts) * User-created collections * All user content This prevents creation conflicts for system resources while allowing polymorphic naming for user content. ### Delete Handling See `core/tests/sync_realtime_test.rs` for deletion sync tests. **Device-owned deletions** use tombstones that sync via `StateResponse`. When you delete a location or folder with thousands of files, only the root UUID is tombstoned. Receiving devices cascade the deletion through their local tree automatically. **Shared resource deletions** use HLC-ordered log entries with `ChangeType::Delete`. All devices process deletions in the same order for consistency. **Pruning:** Both deletion mechanisms use acknowledgment-based pruning. Tombstones and peer log entries are removed after all devices have synced past them. A 7-day safety limit prevents offline devices from blocking pruning indefinitely. The system tracks deletions in a `device_state_tombstones` table. Each tombstone contains just the root UUID of what was deleted. When syncing entries for a device, the `StateResponse` includes both updated records and a list of deleted UUIDs since your last sync. ```rust theme={null} StateResponse { records: [...], // New and updated entries deleted_uuids: [uuid1], // Root UUID only (cascade handles children) } ``` Receiving devices look up each deleted UUID and call the same deletion logic used locally. For entries, this triggers `delete_subtree()` which removes all descendants via the `entry_closure` table. A folder with thousands of files requires only one tombstone and one network message. **Race condition protection:** Models check tombstones before applying state changes during backfill. If a deletion arrives before the record itself, the system skips creating it. For entries, the system also checks if the parent is tombstoned to prevent orphaned children. ### Pre-Sync Data Pre-sync data backfill is tested in `core/tests/sync_backfill_test.rs`. Data created before enabling sync is included during backfill. When the peer log has been pruned or contains fewer items than expected, the response includes a current state snapshot: ```rust theme={null} SharedChangeResponse { entries: [...], // Recent changes from peer log current_state: { tags: [...], // Complete snapshot content_identities: [...], collections: [...], }, has_more: bool, // True if snapshot exceeds batch limit } ``` The receiving device applies both the incremental changes and the current state snapshot, ensuring all shared resources sync correctly even if created before sync was enabled. ### Watermark-Based Incremental Sync See `core/tests/sync_backfill_test.rs` for incremental sync tests. When devices reconnect after being offline, they use watermarks to avoid full re-sync. **Per-Resource Watermarks**: Each resource type (location, entry, volume) tracks its own timestamp watermark per peer device. This prevents watermark advancement in one resource from filtering out records in another resource with earlier timestamps. The `device_resource_watermarks` table in sync.db tracks: * Which peer device the watermark is for * Which resource type (model) the watermark covers * The last successfully synced timestamp This allows independent sync progress: if entries sync to timestamp T1 but locations only sync to T0, each resource type resumes from its own watermark rather than a global one. **Watermark Advancement**: Watermarks only advance when data is actually received. This invariant prevents a subtle data loss bug: if a catch-up request returns empty (peer has no new data), advancing the watermark anyway would permanently filter out any records that should have been returned. The system tracks the maximum timestamp from received records and uses that for the watermark update. **Shared Watermark**: HLC of the last shared resource change seen. Used for incremental sync of tags, collections, and other shared resources. **Stale Watermark Handling**: If a watermark is older than `force_full_sync_threshold_days` (default 25 days), the system forces a full sync instead of incremental catch-up. This ensures consistency when tombstones for deletions may have been pruned. During catch-up, the device sends a `StateRequest` with the `since` parameter set to its watermark. The peer responds with only records modified after that timestamp. This is a **pull request**, not a broadcast. Example flow when Device B reconnects: ``` 1. Device B checks entry watermark for Device A: 2025-10-20 14:30:00 2. Device B sends StateRequest(model_types: ["entry"], since: 2025-10-20 14:30:00) to Device A 3. Device A queries: SELECT * FROM entries WHERE updated_at >= '2025-10-20 14:30:00' 4. Device A responds with StateResponse containing 3 new entries 5. Device B applies changes and updates entry watermark for Device A ``` This syncs only changed records instead of re-syncing the entire dataset. ### Pagination for Large Datasets Pagination ensures backfill works reliably for libraries with millions of records. Both device-owned and shared resources use cursor-based pagination for large datasets. Batch size is configurable via `SyncConfig`. **Device-owned pagination** uses a `timestamp|uuid` cursor format: ``` checkpoint: "2025-10-21T19:10:00.456Z|abc-123-uuid" ``` Query logic handles identical timestamps from batch inserts: ```sql theme={null} WHERE (updated_at > cursor_timestamp) OR (updated_at = cursor_timestamp AND uuid > cursor_uuid) ORDER BY updated_at, uuid LIMIT {configured_batch_size} ``` **Shared resource pagination** uses HLC cursors: ```rust theme={null} SharedChangeRequest { since_hlc: Some(last_hlc), // Resume from this HLC limit: config.batching.backfill_batch_size, } ``` The peer log query returns the next batch starting after the provided HLC, maintaining total ordering. Both pagination strategies ensure all records are fetched exactly once, no records are skipped even with identical timestamps, and backfill is resumable from checkpoint if interrupted. ## Protocol Messages The sync protocol uses JSON-serialized messages over Iroh/QUIC streams: ### Message Types | Message | Direction | Purpose | | --------------------------- | --------- | ------------------------------------- | | `StateChange` | Broadcast | Single device-owned record update | | `StateBatch` | Broadcast | Batch of device-owned records | | `StateRequest` | Request | Pull device-owned data from peer | | `StateResponse` | Response | Device-owned data with tombstones | | `SharedChange` | Broadcast | Single shared resource update (HLC) | | `SharedChangeBatch` | Broadcast | Batch of shared resource updates | | `SharedChangeRequest` | Request | Pull shared changes since HLC | | `SharedChangeResponse` | Response | Shared changes + state snapshot | | `AckSharedChanges` | Broadcast | Acknowledge receipt (enables pruning) | | `Heartbeat` | Broadcast | Peer status with watermarks | | `WatermarkExchangeRequest` | Request | Request peer's sync progress | | `WatermarkExchangeResponse` | Response | Peer's watermarks for catch-up | | `Error` | Response | Error message | ### Message Structures ```rust theme={null} // Device-owned state change StateChange { library_id: Uuid, model_type: String, // "location", "entry", etc. record_uuid: Uuid, device_id: Uuid, // Owner device data: serde_json::Value, // Record as JSON timestamp: DateTime, } // Batch of device-owned changes StateBatch { library_id: Uuid, model_type: String, device_id: Uuid, records: Vec, // [{uuid, data, timestamp}, ...] } // Request device-owned state StateRequest { library_id: Uuid, model_types: Vec, device_id: Option, // Specific device or all since: Option, // Incremental sync checkpoint: Option, // Resume cursor batch_size: usize, } // Response with device-owned state StateResponse { library_id: Uuid, model_type: String, device_id: Uuid, records: Vec, deleted_uuids: Vec, // Tombstones checkpoint: Option, // Next page cursor has_more: bool, } // Shared resource change (HLC-ordered) SharedChange { library_id: Uuid, entry: SharedChangeEntry, } SharedChangeEntry { hlc: HLC, // Ordering key model_type: String, record_uuid: Uuid, change_type: ChangeType, // Insert, Update, Delete data: serde_json::Value, } // Heartbeat with sync progress Heartbeat { library_id: Uuid, device_id: Uuid, timestamp: DateTime, state_watermark: Option, // Last state sync shared_watermark: Option, // Last shared change } // Watermark exchange for reconnection WatermarkExchangeRequest { library_id: Uuid, device_id: Uuid, my_state_watermark: Option, my_shared_watermark: Option, } WatermarkExchangeResponse { library_id: Uuid, device_id: Uuid, state_watermark: Option, shared_watermark: Option, needs_state_catchup: bool, needs_shared_catchup: bool, } ``` ### Serialization * **Format**: JSON via serde * **Bidirectional streams**: 4-byte length prefix (big-endian) + JSON bytes * **Unidirectional streams**: Direct JSON bytes * **Timeout**: 30s for messages, 60s for backfill requests ### Connection State Tracking See `core/tests/sync_realtime_test.rs` for connection handling tests. The sync system uses the Iroh networking layer as the source of truth for device connectivity. When checking if a peer is online, the system queries Iroh's active connections directly rather than relying on cached state. A background monitor updates the devices table at configured intervals for UI purposes: ```sql theme={null} UPDATE devices SET is_online = true, last_seen_at = NOW() WHERE uuid = 'peer-device-id'; ``` All sync decisions use real-time Iroh connectivity checks, ensuring messages only send to reachable peers. ### Derived Tables Some data is computed locally and never syncs: * **directory\_paths**: A lookup table for the full paths of directories. * **entry\_closure**: Parent-child relationships * **tag\_closure**: Tag hierarchies These rebuild automatically from synced base data. ## Retry Queue Failed sync messages are automatically retried with exponential backoff: ### Retry Behavior | Attempt | Delay | Action | | ------- | ----- | --------------- | | 1 | 5s | First retry | | 2 | 10s | Second retry | | 3 | 20s | Third retry | | 4 | 40s | Fourth retry | | 5 | 80s | Final retry | | 6+ | - | Message dropped | ### How It Works ``` 1. Broadcast fails (peer unreachable, timeout, etc.) 2. Message queued with next_retry = now + 5s 3. Background task checks queue every sync_loop_interval 4. Ready messages retried in order 5. Success: remove from queue 6. Failure: re-queue with doubled delay 7. After 5 attempts: drop and log warning ``` ### Queue Management * **Atomic processing**: Messages removed before retry to prevent duplicates * **Ordered by next\_retry**: Earliest messages processed first * **No persistence**: Queue lost on restart (messages will re-sync via watermarks) * **Metrics**: `retry_queue_depth` tracks current queue size The retry queue handles transient network failures without blocking real-time sync. Permanent failures eventually resolve via watermark-based catch-up when the peer reconnects. ## Portable Volumes & Ownership Changes A key feature of Spacedrive is the ability to move external drives between devices without losing track of the data. This is handled through a special sync process that allows the "ownership" of a `Location` to change. ### Changing Device Ownership When you move a volume from one device to another, the `Location` associated with that volume must be assigned a new owner. This process is designed to be extremely efficient, avoiding the need for costly re-indexing or bulk data updates. It is handled using a **Hybrid Ownership Sync** model: When a device detects a known volume that it does not own, it broadcasts a special `RequestLocationOwnership` event. Unlike normal device-owned data, this event is sent to the HLC-ordered log, treating it like a shared resource update. Every device in the library processes this event in the same, deterministic order. Upon processing, each peer performs a single, atomic update on its local database: `UPDATE locations SET device_id = 'new_owner_id' WHERE uuid = 'location_uuid'` This single-row update is all that is required. Because an `Entry`'s ownership is inherited from its parent `Location` at runtime, this change instantly transfers ownership of millions of files. No bulk updates are needed on the `entries` or `directory_paths` tables. The new owner then takes over state-based sync for that `Location`. ### Handling Mount Point Changes A simpler scenario is when a volume's mount point changes on the same device (e.g., from `D:\` to `E:\` on Windows). 1. **Location Update**: The owning device updates the `path` field on its `Location` record. 2. **Path Table Migration**: This change requires a bulk update on the `directory_paths` table to replace the old path prefix with the new one (e.g., `REPLACE(path, 'D:\', 'E:\')`). 3. **No Entry Update**: Crucially, the main `entries` table, which is the largest, is completely untouched. This makes the operation much faster than a full re-index. ## Performance ### Sync Characteristics | Aspect | Device-Owned | Shared Resources | | --------- | -------------------- | ------------------ | | Storage | No log | Small peer log | | Conflicts | Impossible | HLC-resolved | | Offline | Queues state changes | Queues to peer log | ### Optimizations **Batching**: The sync system batches both device-owned and shared resource operations. Batch sizes are configurable via `SyncConfig`. Device-owned data syncs in batches during file indexing. One `StateBatch` message replaces many individual `StateChange` messages, providing significant performance improvement. Shared resources send batch messages instead of individual changes. For example, linking thousands of files to content identities during indexing sends a small number of network messages instead of one per file, providing substantial reduction in network traffic. Both batch types still write individual entries to the sync log for proper HLC ordering and conflict resolution. The optimization is purely in network broadcast efficiency. **Pruning**: The sync log automatically removes entries after all peers acknowledge receipt, keeping the sync database under 1MB. **Compression**: Network messages use compression to reduce bandwidth usage. **Caching**: Backfill responses cache for 15 minutes to improve performance when multiple devices join simultaneously. ## Troubleshooting ### Changes Not Syncing Check: 1. Devices are paired and online 2. Both devices joined the library 3. Network connectivity between devices 4. Sync service is running Debug commands: ```bash theme={null} # Check pending changes sqlite3 sync.db "SELECT COUNT(*) FROM shared_changes" # Verify peer connections sd sync status # Monitor sync activity RUST_LOG=sd_core::sync=debug cargo run ``` ### Common Issues **Large sync.db**: Peers not acknowledging. Check network connectivity. **Missing data**: Verify dependency order. Parents must sync before children. **Conflicts**: Check HLC implementation maintains ordering. ## Error Types The sync system defines specific error types for different failure modes: ### Infrastructure Errors ```rust theme={null} /// HLC parsing failures HLCError::ParseError(String) /// Peer log database errors PeerLogError { ConnectionError(String), // Can't open sync.db QueryError(String), // SQL query failed SerializationError(String), // JSON encode/decode failed ParseError(String), // Invalid data format } /// Watermark tracking errors WatermarkError { QueryError(String), ParseError(String), } /// Checkpoint persistence errors CheckpointError { QueryError(String), ParseError(String), } ``` ### Registry Errors ```rust theme={null} ApplyError { UnknownModel(String), // Model not registered MissingFkLookup(String), // FK mapper not configured WrongSyncType { model, expected, got }, // Device-owned vs shared mismatch MissingApplyFunction(String), // No apply handler MissingQueryFunction(String), // No query handler MissingDeletionHandler(String), // No deletion handler DatabaseError(String), // DB operation failed } ``` ### Dependency Errors ```rust theme={null} DependencyError { CircularDependency(String), // A → B → A detected UnknownDependency(String, String), // Depends on unregistered model NoModels, // Empty registry } ``` ### Transaction Errors ```rust theme={null} TxError { Database(DbErr), // SeaORM error SyncLog(String), // Peer log write failed Serialization(serde_json::Error), // JSON error InvalidModel(String), // Model validation failed } ``` All errors implement `std::error::Error` and include context for debugging. ## Metrics & Observability The sync system collects metrics for monitoring and debugging. ### Metric Categories **State Metrics**: * `current_state` - Current sync state (Uninitialized, Backfilling, etc.) * `state_entered_at` - When current state started * `state_history` - Recent state transitions (ring buffer) * `total_time_in_state` - Cumulative time per state * `transition_count` - Number of state transitions **Operation Metrics**: * `broadcasts_sent` - Total broadcast messages sent * `state_changes_broadcast` - Device-owned changes broadcast * `shared_changes_broadcast` - Shared resource changes broadcast * `changes_received` - Updates received from peers * `changes_applied` - Successfully applied updates * `changes_rejected` - Updates rejected (conflict, error) * `active_backfill_sessions` - Concurrent backfills in progress * `retry_queue_depth` - Messages waiting for retry **Data Volume Metrics**: * `entries_synced` - Records synced per model type * `entries_by_device` - Records synced per peer device * `bytes_sent` / `bytes_received` - Network bandwidth * `last_sync_per_peer` - Last sync timestamp per device * `last_sync_per_model` - Last sync timestamp per model **Performance Metrics**: * `broadcast_latency` - Time to broadcast to all peers (histogram) * `apply_latency` - Time to apply received changes (histogram) * `backfill_request_latency` - Backfill round-trip time (histogram) * `peer_rtt_ms` - Per-peer round-trip time * `watermark_lag_ms` - How far behind each peer is * `hlc_physical_drift_ms` - Clock drift detected via HLC * `hlc_counter_max` - Highest logical counter seen **Error Metrics**: * `total_errors` - Total error count * `network_errors` - Connection/timeout failures * `database_errors` - DB operation failures * `apply_errors` - Change application failures * `validation_errors` - Invalid data received * `recent_errors` - Last N errors with details * `conflicts_detected` - Concurrent modification conflicts * `conflicts_resolved_by_hlc` - Conflicts resolved via HLC ### Histogram Metrics Performance metrics use histograms with atomic min/max/avg tracking: ```rust theme={null} HistogramMetric { count: AtomicU64, // Number of samples sum: AtomicU64, // Sum for average min: AtomicU64, // Minimum value max: AtomicU64, // Maximum value } // Methods histogram.avg() // Average latency histogram.min() // Best case histogram.max() // Worst case histogram.count() // Sample count ``` ### Snapshots Metrics can be captured as point-in-time snapshots: ```rust theme={null} let snapshot = sync_service.metrics().snapshot().await; // Filter by time range let recent = snapshot.filter_since(one_hour_ago); // Filter by peer let alice_metrics = snapshot.filter_by_peer(alice_device_id); // Filter by model let entry_metrics = snapshot.filter_by_model("entry"); ``` ### History A ring buffer stores recent snapshots for time-series analysis: ```rust theme={null} MetricsHistory { capacity: 1000, // Max snapshots retained snapshots: VecDeque, } // Query methods history.get_snapshots_since(timestamp) history.get_snapshots_range(start, end) history.get_latest_snapshot() ``` ### Persistence Metrics are persisted to the database every 5 minutes (configurable via `metrics_log_interval_secs`). This enables post-mortem analysis of sync issues. ## Sync Event Bus The sync system uses a dedicated event bus separate from the general application event bus: ### Why Separate? The general `EventBus` handles high-volume events (filesystem changes, job progress, UI updates). During heavy indexing, thousands of events per second can queue up. The `SyncEventBus` is isolated to prevent sync events from being starved: * **Capacity**: 10,000 events (vs 1,000 for general bus) * **Priority**: Sync-critical events processed first * **Droppable**: Metrics events can be dropped under load ### Event Types ```rust theme={null} enum SyncEvent { // Device-owned state change ready to broadcast StateChange { library_id: Uuid, model_type: String, record_uuid: Uuid, device_id: Uuid, data: serde_json::Value, timestamp: DateTime, }, // Shared resource change ready to broadcast SharedChange { library_id: Uuid, entry: SharedChangeEntry, }, // Metrics snapshot available MetricsUpdated { library_id: Uuid, metrics: SyncMetricsSnapshot, }, } ``` ### Event Criticality | Event | Critical | Can Drop | | ---------------- | -------- | -------- | | `StateChange` | Yes | No | | `SharedChange` | Yes | No | | `MetricsUpdated` | No | Yes | Critical events trigger warnings if the bus lags. Non-critical events are silently dropped under load. ### Real-Time Batching The event listener batches events before broadcasting: ``` 1. Event arrives on SyncEventBus 2. Add to batch buffer 3. If buffer.len() >= 100 OR 50ms elapsed: 4. Flush batch as single network message 5. Reset buffer and timer ``` This reduces network overhead during rapid operations (e.g., bulk tagging). ## Implementation Status See `core/tests/sync_backfill_test.rs`, `core/tests/sync_realtime_test.rs`, and `core/tests/sync_metrics_test.rs` for the test suite. ### Production Ready * One-line sync API (`sync_model`, `sync_model_with_db`, `sync_models_batch`) * HLC implementation (thread-safe, lexicographically sortable) * Syncable trait infrastructure with `inventory`-based registration * Foreign key mapping with batch optimization (365x query reduction) * Dependency ordering via topological sort (Kahn's algorithm) * Network transport (Iroh/QUIC with bidirectional streams) * Backfill orchestration with resumable checkpoints * State snapshots for pre-sync data * HLC conflict resolution (last write wins) * Per-resource watermark tracking for incremental sync * Connection state tracking via Iroh * Transitive sync through intermediary devices * Cascading tombstones for device-owned deletions * Unified acknowledgment-based pruning * Post-backfill rebuild for closure tables * Metrics collection for observability ### Currently Syncing **Device-Owned Models (3):** | Model | Table | Dependencies | FK Mappings | Features | | -------- | ----------- | --------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | ----------------------------- | | Volume | `volumes` | `device` | `device_id → devices` | with\_deletion | | Location | `locations` | `volume` | `volume_id → volumes`, `entry_id → entries` | with\_deletion | | Entry | `entries` | `volume`, `content_identity`, `user_metadata` | `volume_id → volumes`, `parent_id → entries`, `metadata_id → user_metadata`, `content_id → content_identities` | with\_deletion, with\_rebuild | **Shared Models (16):** | Model | Table | Dependencies | FK Mappings | Features | | --------------- | -------------------- | ---------------------- | --------------------------------------------------------------------------- | ------------------ | | Device | `devices` | None | None | Library membership | | Tag | `tag` | None | None | - | | TagRelationship | `tag_relationship` | `tag` | `parent_tag_id → tag`, `child_tag_id → tag` | with\_rebuild | | Collection | `collection` | None | None | - | | CollectionEntry | `collection_entry` | `collection`, `entry` | `collection_id → collection`, `entry_id → entries` | - | | ContentIdentity | `content_identities` | None | None | Deterministic UUID | | UserMetadata | `user_metadata` | None | None | - | | UserMetadataTag | `user_metadata_tag` | `user_metadata`, `tag` | `user_metadata_id → user_metadata`, `tag_id → tag`, `device_uuid → devices` | - | | AuditLog | `audit_log` | None | None | - | | Sidecar | `sidecar` | `content_identity` | `content_uuid → content_identities` | - | | Space | `spaces` | None | None | - | | SpaceGroup | `space_groups` | `space` | `space_id → spaces` | - | | SpaceItem | `space_items` | `space`, `space_group` | `space_id → spaces`, `group_id → space_groups` | - | | VideoMediaData | `video_media_data` | None | None | - | | AudioMediaData | `audio_media_data` | None | None | - | | ImageMediaData | `image_media_data` | None | None | - | ### Excluded Fields Each model excludes certain fields from sync (local-only data): | Model | Excluded Fields | | --------------- | ------------------------------------------------------------------------------------------------------ | | Device | `id` | | Location | `id`, `scan_state`, `error_message`, `job_policies`, `created_at`, `updated_at` | | Entry | `id`, `indexed_at` | | Volume | `id`, `is_online`, `last_seen_at`, `last_speed_test_at`, `tracked_at` | | ContentIdentity | `id`, `mime_type_id`, `kind_id`, `entry_count`, `*_media_data_id`, `first_seen_at`, `last_verified_at` | | UserMetadata | `id`, `created_at`, `updated_at` | | AuditLog | `id`, `created_at`, `updated_at`, `job_id` | | Sidecar | `id`, `source_entry_id` | All models sync automatically during creation, updates, and deletions. File indexing uses batch sync for both device-owned entries (`StateBatch`) and shared content identities (`SharedChangeBatch`) to reduce network overhead. **Deletion sync:** Device-owned models (locations, entries, volumes) use cascading tombstones. The `device_state_tombstones` table tracks root UUIDs of deleted trees. Shared models use standard `ChangeType::Delete` in the peer log. Both mechanisms prune automatically once all devices have synced. ## Extension Sync Extension sync framework is ready. SDK integration pending. Extensions can define syncable models using the same infrastructure as core models. The registry pattern automatically handles new model types without code changes to the sync system. Extensions will declare models with sync metadata: ```rust theme={null} #[model( table_name = "album", sync_strategy = "shared" )] struct Album { #[primary_key] id: Uuid, title: String, #[metadata] metadata_id: i32, } ``` The sync system will detect and register extension models at runtime, applying the same HLC-based conflict resolution and dependency ordering used for core models. ## Configuration Sync behavior is controlled through a unified configuration system. All timing, batching, and retention parameters are configurable per library. ### Default Configuration The system uses sensible defaults tuned for typical usage across LAN and internet connections: ```rust theme={null} SyncConfig { batching: BatchingConfig { backfill_batch_size: 10_000, // Records per backfill request state_broadcast_batch_size: 1_000, // Device-owned records per broadcast shared_broadcast_batch_size: 100, // Shared records per broadcast max_snapshot_size: 100_000, // Max records in state snapshot realtime_batch_max_entries: 100, // Max entries before flush realtime_batch_flush_interval_ms: 50, // Auto-flush interval (ms) }, retention: RetentionConfig { strategy: AcknowledgmentBased, tombstone_max_retention_days: 7, // Hard limit for tombstone pruning peer_log_max_retention_days: 7, // Hard limit for peer log pruning force_full_sync_threshold_days: 25, // Force full sync if watermark older }, network: NetworkConfig { message_timeout_secs: 30, // Timeout for sync messages backfill_request_timeout_secs: 60, // Timeout for backfill requests sync_loop_interval_secs: 5, // Sync loop check interval connection_check_interval_secs: 10, // How often to check peer connectivity }, monitoring: MonitoringConfig { pruning_interval_secs: 3600, // How often to prune sync.db (1 hour) enable_metrics: true, // Enable sync metrics collection metrics_log_interval_secs: 300, // Persist metrics every 5 minutes }, } ``` **Batching** controls how many records are processed at once. Larger batches improve throughput but increase memory usage. Real-time batching collects changes for a short interval before flushing to reduce network overhead during rapid operations. **Retention** controls how long sync coordination data is kept. The acknowledgment-based strategy prunes tombstones and peer log entries as soon as all devices have synced past them. A 7-day safety limit prevents offline devices from blocking pruning indefinitely. **Network** controls timeouts and polling intervals. Shorter intervals provide faster sync but increase network traffic and CPU usage. **Monitoring** controls metrics collection and sync database maintenance. Metrics track operations, latency, and data volumes for debugging and observability. ### Presets **Aggressive** is optimized for fast local networks with always-online devices. Small batches and frequent pruning minimize storage and latency. **Conservative** handles unreliable networks and frequently offline devices. Large batches improve efficiency, and extended retention accommodates longer offline periods. **Mobile** optimizes for battery life and bandwidth. Less frequent sync checks and longer retention reduce power consumption. ### Configuring Sync ```bash theme={null} # Use a preset sd sync config set --preset aggressive # Customize individual settings sd sync config set --batch-size 5000 --retention-days 14 # Per-library configuration sd library "Photos" sync config set --preset mobile ``` Configuration can also be set via environment variables or a TOML file. The loading priority is: environment variables, config file, database, then defaults. ## Summary Library Sync is not traditional multi-leader replication. While multi-leader systems treat all nodes as equal for all data, Spacedrive recognizes a fundamental truth: `/Users/alice/Photos` can only be modified by Alice's laptop. This ownership model eliminates the entire class of filesystem conflicts that plague distributed systems. **Hybrid ownership** splits the problem in two. Device-owned data (files, folders, volumes) uses single-leader-per-resource semantics. No CRDTs, no version vectors, no conflict resolution needed. The owner's state is authoritative. Shared resources (tags, collections) use multi-leader semantics with HLC-based ordering. Only this small subset of data requires conflict resolution, and last-write-wins is sufficient. **State-based sync** handles device-owned data. Changes propagate via real-time broadcasts to connected peers. Historical data transfers via pull requests when devices join or reconnect. **Log-based sync** handles shared resources. Hybrid Logical Clocks maintain causal ordering without clock synchronization. All devices converge to the same state regardless of network topology. **Automatic recovery** handles offline periods through watermark-based incremental sync. Reconnecting devices receive only changes since their last sync, typically a small delta rather than the full dataset. The system is production-ready with all core models syncing automatically. Extensions can use the same infrastructure to sync custom models. ## Related Documentation * [Devices](/docs/core/devices) - Device pairing and management * [Networking](/docs/core/networking) - Network transport layer * [Libraries](/docs/core/libraries) - Library structure and management # Locations Source: https://v2.spacedrive.com/core/locations Locations are directories that Spacedrive tracks and monitors. When you add a location, Spacedrive indexes its contents and watches for changes in real-time. ## What is a Location? A location is any folder on your device that you want Spacedrive to index. Once added: * Files are indexed immediately * Changes are detected in real-time * Metadata syncs across your devices (if enabled) * Content gets unique identifiers for deduplication ## Location Architecture Locations have a sophisticated relationship with the file index: ### Root Entry When you add a location, Spacedrive creates a **root entry** in the entries table for the location directory itself. This root entry: * Has no parent (`parent_id = NULL`) * Gets a self-reference in the `entry_closure` table * Serves as the ancestor for all files/folders within the location * Is stored in the `directory_paths` table with its full filesystem path ```rust theme={null} // Location points to root entry Location { entry_id: Some(123), // References entries table // ... other fields } // Root entry for "/Users/alice/Documents" Entry { id: 123, name: "Documents", kind: Directory, parent_id: None, // Root has no parent // ... other fields } ``` ### Why Root Entries? This design enables **nested locations without duplicating the file tree**. If you have: 1. Location A: `/Users/alice/Documents` (entry\_id: 123) 2. Location B: `/Users/alice/Documents/Work` (entry\_id: 124) The entries table contains a single unified tree: ``` Entry(123): "Documents" parent_id: NULL ├─ Entry(124): "Work" parent_id: 123 ← Location B points here │ └─ Entry(125): "report.pdf" parent_id: 124 └─ Entry(126): "Photos" parent_id: 123 └─ Entry(127): "sunset.jpg" parent_id: 126 ``` **Benefits:** * **No duplication** - `Work/report.pdf` exists once in the database, accessible from both locations * **Consistent hierarchy** - Parent-child relationships are preserved regardless of location boundaries * **Efficient storage** - Adding nested locations doesn't create redundant entry records * **Flexible organization** - Users can create fine-grained locations within broader ones * **Different index modes** - Apply Deep indexing to `/Photos` but Shallow to `/Photos/RAW` without duplicating entries Without this design, overlapping locations would require duplicating all entries, leading to sync conflicts and wasted storage. ### Entry Hierarchy All files and folders within a location form a tree structure: ``` Location (entry_id: 123) └─ Entry(123): "Documents" parent_id: NULL ├─ Entry(124): "Work" parent_id: 123 │ └─ Entry(125): "report.pdf" parent_id: 124 └─ Entry(126): "Photos" parent_id: 123 └─ Entry(127): "sunset.jpg" parent_id: 126 ``` The `entry_closure` table enables efficient queries: * "Find all files in this location" → Query where `ancestor_id = 123` * "Get file path" → Walk up closure table following parent relationships * "Calculate total size" → Aggregate from all descendants ### Directory Paths Table Directory paths are stored separately for performance: ```sql theme={null} -- directory_paths table entry_id | path ---------|--------------------------- 123 | /Users/alice/Documents 124 | /Users/alice/Documents/Work 126 | /Users/alice/Documents/Photos ``` This avoids storing redundant path information on every file entry and makes path-based lookups significantly faster. Only directories are stored in this table, not individual files. ### Device Ownership & Sync Entries don't have a `device_id` field. Instead, **ownership is inherited from the location**: ```rust theme={null} // Location owns all its entries Location { device_id: 42, // Device that owns this location entry_id: 123, // Root of the entry tree } // Entries don't store device_id Entry { id: 124, parent_id: 123, // Part of location's tree // NO device_id field } ``` **Why this matters for sync:** 1. **Efficient ownership queries** - Find all entries owned by a device via `entry_closure`: ```sql theme={null} SELECT e.* FROM entries e INNER JOIN entry_closure ec ON e.id = ec.descendant_id WHERE ec.ancestor_id IN ( SELECT entry_id FROM locations WHERE device_id = ? ); ``` 2. **No redundant storage** - Avoids storing device\_id on millions of entry records 3. **Instant ownership transfer** - When you move an external drive between devices, just update the location's `device_id`. All millions of files instantly change ownership without touching the entries table. See [Library Sync - Portable Volumes](/docs/core/library-sync#portable-volumes--ownership-changes) for details. **Sync implications:** * Only the owning device can modify entries in a location * Other devices have read-only views of remote locations * Location ownership change is a single-row update (not a bulk migration) ### Core Properties ```rust theme={null} pub struct Location { pub id: i32, // Database primary key pub uuid: Uuid, // Unique identifier pub device_id: i32, // Device that owns this location pub entry_id: Option, // Root entry for this location's tree pub name: Option, // Display name pub index_mode: String, // "shallow" | "content" | "deep" pub scan_state: String, // "pending" | "scanning" | "completed" | "error" pub last_scan_at: Option>, pub error_message: Option, pub total_file_count: i64, pub total_byte_size: i64, pub job_policies: Option, // JSON-serialized policies pub created_at: DateTime, pub updated_at: DateTime, } ``` See [Data Model - Location](/docs/core/data-model#location) for the complete database schema. ### Index Modes Choose how deeply Spacedrive analyzes your files: * **Shallow**: Basic metadata only (name, size, dates) * **Content**: Includes content hashing for deduplication * **Deep**: Full media processing with thumbnails and metadata ### Scan States Locations track their scanning status: ```rust theme={null} pub enum ScanState { Idle, // Not scanning Scanning { progress: u8 }, // Currently scanning (0-100%) Completed, // Scan finished successfully Failed, // Scan encountered errors Paused, // Scan was paused } ``` ## Adding Locations ### Using the CLI ```bash theme={null} # Add a location spacedrive location add ~/Documents --name "Documents" # Add with deep indexing spacedrive location add ~/Photos --name "Photos" --mode deep # List all locations spacedrive location list ``` ### Using the API ```rust theme={null} let (location_id, job_id) = location_manager .add_location( library, PathBuf::from("/Users/alice/Desktop"), Some("Desktop".to_string()), device_id, IndexMode::Content, ) .await?; ``` ### What Happens When You Add a Location The location creation process is atomic (uses database transactions): 1. **Path validation** - Ensures the directory exists and is accessible 2. **Create root entry** - Creates an entry for the location directory * Assigns a UUID for sync compatibility * Sets `parent_id = NULL` (this is a root) * Sets `indexed_at` to enable sync emission 3. **Create closure record** - Adds self-reference to `entry_closure` table 4. **Create directory path** - Adds full path to `directory_paths` table 5. **Duplicate check** - Verifies no location already exists for this entry 6. **Create location record** - Stores location metadata * Links to root entry via `entry_id` * Sets initial `scan_state = "pending"` 7. **Commit transaction** - All or nothing (prevents partial state) 8. **Emit sync event** - Broadcasts root entry StateChange for sync 9. **Start indexing job** - Begins scanning child files/folders 10. **Watcher setup** - Begins monitoring changes 11. **Event broadcast** - Notifies other services If any step fails, the entire transaction rolls back. ## File System Watching The watcher service provides real-time monitoring across all platforms. ### Platform Support **macOS**: Uses FSEvents for efficient volume-level monitoring **Linux**: Uses inotify for precise file-level events **Windows**: Uses ReadDirectoryChangesW for real-time updates ### Event Types The watcher detects these file system changes: ```rust theme={null} pub enum WatcherEvent { Create, // New file or directory Modify, // Content or metadata changed Remove, // File or directory deleted Rename { // Move or rename operation from: PathBuf, to: PathBuf, }, } ``` ### Automatic Filtering The watcher respects the **indexer rules** configured for each location. These rules determine which files and directories are tracked: **Available Indexer Rules:** * `no_system_files` - Ignores `.DS_Store`, `Thumbs.db`, and other OS-generated files * `no_hidden` - Ignores hidden files (dotfiles) except important ones like `.gitignore` * `no_git` - Ignores `.git` directories * `gitignore` - Respects `.gitignore` patterns in the directory tree * `only_images` - Only processes image files * `no_dev_dirs` - Ignores `node_modules/`, `target/`, `.cache/`, and other build directories **Default Configuration:** ```rust theme={null} RuleToggles { no_system_files: true, // Skip OS junk no_hidden: false, // Include dotfiles no_git: true, // Skip .git gitignore: true, // Respect .gitignore only_images: false, // Index all file types no_dev_dirs: true, // Skip build artifacts } ``` Currently, the watcher uses hardcoded filtering instead of per-location indexer rules. Integration with the indexer rules engine is planned, which will allow each location to have custom filtering rules configured through the UI. When indexer rules integration is complete, the watcher will automatically filter events based on each location's configured rules, ensuring consistency between initial indexing and real-time change detection. ## Configuration ### Watcher Settings Configure the watcher for your needs: ```rust theme={null} LocationWatcherConfig { debounce_duration: Duration::from_millis(100), // Event consolidation event_buffer_size: 1000, // Queue size debug_mode: false, // Detailed logging } ``` ### Performance Tuning **For large directories** (>100k files): * Increase buffer size to prevent event loss * Use longer debounce periods * Consider excluding cache directories **For network drives**: * Enable polling fallback * Increase debounce duration * Monitor connection stability **For SSDs vs HDDs**: * SSDs: Shorter debounce, larger buffers * HDDs: Longer debounce for mechanical latency ## Watching Events Subscribe to location events in your code: ```rust theme={null} let mut events = event_bus.subscribe(); while let Ok(event) = events.recv().await { match event { Event::EntryCreated { path, .. } => { println!("New file: {}", path); } Event::EntryModified { path, .. } => { println!("File changed: {}", path); } _ => {} } } ``` ### Event Flow When a file changes: 1. Operating system detects change 2. Watcher receives raw event 3. Event is filtered and debounced 4. Structured event is created 5. Event bus broadcasts to subscribers 6. Services react (indexer, sync, UI) ## Managing Locations ### Pause Watching Temporarily stop monitoring without removing: ```bash theme={null} spacedrive location pause ``` ### Update Settings Change location configuration: ```bash theme={null} # Disable watching spacedrive location update --watch false # Change index mode spacedrive location update --mode shallow ``` ### Remove Location Stop tracking a directory: ```bash theme={null} spacedrive location remove ``` Removing a location doesn't delete files. It only stops Spacedrive from tracking them. ## Troubleshooting ### High CPU Usage If watching causes high CPU: 1. Check for directories with rapid changes 2. Increase debounce duration 3. Exclude problematic subdirectories 4. Temporarily disable watching ```bash theme={null} # Find active locations spacedrive location list --verbose # Disable problematic location spacedrive location update --watch false ``` ### Missing Changes If file changes aren't detected: 1. Verify location has watching enabled 2. Check file system permissions 3. Ensure platform limits aren't exceeded 4. Try restarting the watcher ### Duplicate Events If you see the same change multiple times: 1. Increase debounce duration 2. Check for symlink loops 3. Verify you're not watching overlapping paths ### Debug Mode Enable detailed logging: ```bash theme={null} # Set debug mode export SPACEDRIVE_WATCHER_DEBUG=1 # Run with verbose logging spacedrive --log-level debug ``` ## Platform Limits ### macOS * FSEvents may coalesce rapid changes * Volume-level monitoring affects all locations on a drive ### Linux * inotify has a watch descriptor limit (usually 8192) * Increase with: `echo 524288 | sudo tee /proc/sys/fs/inotify/max_user_watches` ### Windows * Long paths require special handling * Network drives may fall back to polling ## Best Practices ### Location Organization 1. **Nested locations are supported** - You can add both `/Documents` and `/Documents/Work` as separate locations * The file tree is shared, not duplicated * Each location provides a different "view" into the same hierarchy * Useful for applying different index modes or policies to subdirectories 2. **Group related content** - One location per project or media type 3. **Consider performance** - Separate frequently-changing directories ### Exclusion Patterns Create `.spacedriveignore` files to exclude: ``` # Build artifacts node_modules/ target/ dist/ # Cache directories .cache/ *.tmp # Large generated files *.log *.dump ``` ### Network Locations For network-attached storage: 1. Use Content index mode (avoid Deep) 2. Increase debounce to 500ms+ 3. Monitor connection stability 4. Consider scheduled indexing instead ## Integration ### Services Using Location Events * **Indexer**: Re-analyzes modified files * **Search**: Updates search index * **Sync**: Propagates changes to other devices * **Thumbnails**: Regenerates previews * **Frontend**: Updates UI in real-time ### Event Priority Critical events are processed first: 1. User-initiated changes 2. Create/delete operations 3. Modifications 4. Metadata updates ## Implementation Details ### Database Schema Locations utilize three main tables: **locations** - Location metadata ```sql theme={null} CREATE TABLE locations ( id INTEGER PRIMARY KEY, uuid BLOB NOT NULL UNIQUE, device_id INTEGER NOT NULL, entry_id INTEGER, -- References entries(id) name TEXT, index_mode TEXT NOT NULL, scan_state TEXT NOT NULL, -- ... other fields FOREIGN KEY (device_id) REFERENCES devices(id), FOREIGN KEY (entry_id) REFERENCES entries(id) ); ``` **entries** - All files and directories (see [Data Model](/docs/core/data-model#entry)) **entry\_closure** - Transitive closure table for hierarchy (see [Data Model](/docs/core/data-model#hierarchical-queries)) **directory\_paths** - Directory path cache ```sql theme={null} CREATE TABLE directory_paths ( entry_id INTEGER PRIMARY KEY, -- References entries(id) path TEXT NOT NULL, FOREIGN KEY (entry_id) REFERENCES entries(id) ); ``` ### Query Patterns **Find all entries in a location:** ```sql theme={null} SELECT e.* FROM entries e INNER JOIN entry_closure ec ON e.id = ec.descendant_id WHERE ec.ancestor_id = ( SELECT entry_id FROM locations WHERE uuid = ? ); ``` **Get full path for a directory:** ```sql theme={null} SELECT path FROM directory_paths WHERE entry_id = ?; ``` **Get full path for a file:** ```sql theme={null} -- Walk up parent chain and concatenate with directory path SELECT dp.path || '/' || e.name as full_path FROM entries e LEFT JOIN entries parent ON e.parent_id = parent.id LEFT JOIN directory_paths dp ON parent.id = dp.entry_id WHERE e.id = ?; ``` ## Related Documentation * [Data Model](/docs/core/data-model) - Complete database schema * [Indexing](/docs/core/indexing) - How files are analyzed * [Sync](/docs/core/sync) - Cross-device synchronization * [Events](/docs/core/events) - Event system architecture # Networking Source: https://v2.spacedrive.com/core/networking Spacedrive connects devices directly using Iroh, a peer-to-peer networking library built on QUIC. This enables secure communication between your devices without relying on cloud servers. ## Architecture The networking system manages all device-to-device communication through a single service that handles connections, protocols, and state management. ### Core Components **NetworkingService** coordinates all networking operations. It manages the Iroh endpoint, tracks device states, and routes messages to protocol handlers. ```rust theme={null} pub struct NetworkingService { endpoint: Endpoint, // Iroh's QUIC endpoint device_registry: DeviceRegistry, // Tracks all known devices protocol_registry: ProtocolRegistry, // Routes messages identity: NetworkIdentity, // Cryptographic identity } ``` **NetworkIdentity** manages your device's cryptographic identity using Ed25519 keys. This identity persists across sessions and proves your device's authenticity to others. ```rust theme={null} pub struct NetworkIdentity { node_id: NodeId, // Derived from public key signing_key: SigningKey, // Ed25519 private key verifying_key: VerifyingKey, // Ed25519 public key } ``` **DeviceRegistry** maintains the state of all discovered and paired devices. It provides a single source of truth for device relationships. ```rust theme={null} pub enum DeviceState { Discovered { node_addr: NodeAddr }, Pairing { session_id: Uuid }, Paired { session_keys: SessionKeys }, Connected { connection: Connection }, Disconnected { reason: DisconnectReason }, } ``` ### Network Transport Iroh provides the underlying transport using QUIC, which offers: * **Built-in encryption** using TLS 1.3 * **Multiplexed streams** over a single connection * **Reliable delivery** with automatic retransmission * **NAT traversal** with 90%+ success rate * **Relay fallback** when direct connections fail ### Protocol System The networking module uses ALPN (Application-Layer Protocol Negotiation) to route connections to specific protocol handlers. ```rust theme={null} // Protocol registration registry.register("pairing/1.0", PairingProtocol::new()); registry.register("sync/1.0", SyncProtocol::new()); registry.register("transfer/1.0", TransferProtocol::new()); // Connection routing based on ALPN match alpn { "pairing/1.0" => pairing_handler.handle(connection), "sync/1.0" => sync_handler.handle(connection), _ => Err(UnknownProtocol) } ``` ## Device Discovery Devices find each other through multiple mechanisms: ### Local Network Discovery Iroh automatically discovers devices on your local network using mDNS. When a device starts, it broadcasts its presence and listens for others. ```rust theme={null} // Automatic local discovery endpoint.discovery().add_discovery(Box::new( DnsDiscovery::builder().build() )); ``` ### Manual Connection You can connect to devices using their NodeAddr, which includes their NodeId and network addresses. ```rust theme={null} // Connect to a specific device let node_addr = NodeAddr { node_id: NodeId::from_str("...")?, relay_url: Some("https://relay.iroh.network"), direct_addresses: vec!["192.168.1.100:11204".parse()?], }; endpoint.connect(node_addr, "sync/1.0").await?; ``` Direct addresses work on local networks. The relay URL enables connections across the internet when direct connections fail. ## Device Pairing Pairing establishes trust between devices using cryptographic signatures and user-friendly codes. ### Pairing Flow The initiator generates a pairing code that the joiner enters to establish trust. The initiator creates a BIP39 mnemonic code: ```rust theme={null} // Initiator generates code let code = PairingCode::generate(); // "brave-lion-sunset" ``` Both devices exchange their information and public keys: ```rust theme={null} pub struct DeviceInfo { pub device_id: Uuid, pub device_name: String, pub device_type: DeviceType, pub public_key: VerifyingKey, } ``` The initiator challenges the joiner to prove they have the code: ```rust theme={null} // Initiator sends challenge let challenge = Challenge::random(); // Joiner signs challenge let signature = identity.sign(&challenge); // Initiator verifies signature identity.verify(&challenge, &signature)?; ``` Both devices derive session keys for future communication: ```rust theme={null} // Derive shared secret using ECDH let shared_secret = ecdh(my_private, their_public); // Derive session keys let keys = SessionKeys::from_shared_secret(shared_secret); ``` ### Pairing Security The pairing protocol prevents several attacks: * **Man-in-the-middle**: Public key exchange with out-of-band verification * **Replay attacks**: Fresh challenges for each pairing attempt * **Brute force**: Rate limiting on pairing attempts * **Eavesdropping**: All communication encrypted after initial handshake ## Message Protocol Paired devices communicate using an encrypted messaging protocol. ### Message Types ```rust theme={null} pub enum NetworkMessage { // Library discovery LibraryAnnounce { libraries: Vec }, LibraryRequest { library_id: Uuid }, // Sync coordination SyncRequest { library_id: Uuid, after: HLC }, SyncResponse { entries: Vec }, // File operations FileRequest { entry_id: Uuid }, FileResponse { chunks: Vec }, // Diagnostics Ping { timestamp: SystemTime }, Pong { timestamp: SystemTime }, } ``` ### Message Flow Messages are serialized as JSON and encrypted using session keys: ```rust theme={null} // Send a message async fn send_message( connection: &mut Connection, message: NetworkMessage, keys: &SessionKeys, ) -> Result<()> { // Serialize to JSON let json = serde_json::to_vec(&message)?; // Encrypt with session key let encrypted = keys.encrypt(&json)?; // Send over QUIC stream let mut stream = connection.open_uni().await?; stream.write_all(&encrypted).await?; stream.finish().await?; Ok(()) } ``` ### Reliability QUIC provides reliable delivery, but the application layer adds: * **Message acknowledgments** for critical operations * **Automatic retries** with exponential backoff * **Connection health monitoring** with periodic pings * **Graceful reconnection** after network changes ## File Transfer The file transfer protocol enables secure, resumable file sharing between devices. ### Transfer Process Device A requests a file by its entry ID: ```rust theme={null} let request = FileRequest { entry_id: Uuid::parse_str("...")?, resume_from: Some(1048576), // Resume from 1MB }; ``` Device B streams the file in encrypted chunks: ```rust theme={null} // 256KB chunks const CHUNK_SIZE: usize = 262144; while let Some(chunk) = file.read_chunk(CHUNK_SIZE).await? { let encrypted = session_keys.encrypt(&chunk)?; stream.write_all(&encrypted).await?; } ``` Both devices verify the transfer using checksums: ```rust theme={null} let checksum = blake3::hash(&file_data); if checksum != expected_checksum { return Err(TransferError::ChecksumMismatch); } ``` ### Transfer Features * **Resumable transfers**: Continue from where you left off * **Progress tracking**: Real-time updates on transfer status * **Bandwidth throttling**: Respect network limits * **Parallel transfers**: Multiple files simultaneously * **Compression**: Optional gzip compression for text files ## Connection Management The event loop handles all incoming connections and routes them appropriately. ### Event Loop ```rust theme={null} pub struct NetworkingEventLoop { endpoint: Endpoint, registry: ProtocolRegistry, commands: mpsc::Receiver, } impl NetworkingEventLoop { pub async fn run(mut self) -> Result<()> { loop { select! { // Handle incoming connections Some(connection) = self.endpoint.accept() => { let alpn = connection.alpn(); let handler = self.registry.get(alpn)?; tokio::spawn(handler.handle(connection)); } // Process commands Some(cmd) = self.commands.recv() => { self.handle_command(cmd).await?; } } } } } ``` ### Connection States Connections transition through several states: 1. **Connecting**: Initial QUIC handshake 2. **Connected**: Active connection, can send/receive 3. **Idle**: No recent activity, may be closed 4. **Closing**: Graceful shutdown in progress 5. **Closed**: Connection terminated ### Keep-Alive Connections are kept alive using periodic pings: ```rust theme={null} // Ping every 30 seconds of inactivity const KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(30); async fn keep_alive_loop(connection: Connection) { let mut interval = tokio::time::interval(KEEP_ALIVE_INTERVAL); loop { interval.tick().await; if let Err(_) = send_ping(&connection).await { // Connection lost break; } } } ``` ## NAT Traversal Iroh handles NAT traversal automatically using several techniques: ### Direct Connection First, Iroh attempts a direct connection using known addresses: ```rust theme={null} // Try direct addresses first for addr in &node_addr.direct_addresses { if let Ok(conn) = endpoint.connect_direct(addr).await { return Ok(conn); } } ``` ### STUN If direct connection fails, Iroh uses STUN to discover public addresses: ```rust theme={null} // STUN automatically handled by Iroh // Discovers public IP and port mapping let public_addr = endpoint.my_addr().await?; ``` ### Relay Fallback When both devices are behind symmetric NATs, Iroh falls back to relay servers: ```rust theme={null} // Relay connection automatic in Iroh // Uses relay_url from NodeAddr let conn = endpoint.connect(node_addr, alpn).await?; // This may be relayed if direct connection impossible ``` Relay servers don't decrypt your data. They only forward encrypted packets between devices. ## Security ### Encryption Layers The networking stack provides multiple encryption layers: 1. **Transport encryption**: QUIC's built-in TLS 1.3 2. **Application encryption**: Additional encryption using session keys 3. **File encryption**: Per-file encryption keys for transfers ### Key Management ```rust theme={null} pub struct KeyHierarchy { // Long-term identity device_key: SigningKey, // Per-pairing session keys session_keys: HashMap, // Per-transfer ephemeral keys transfer_keys: HashMap, } ``` ### Trust Model * **Device identity**: Ed25519 signatures prove device authenticity * **Pairing verification**: Out-of-band code exchange prevents MITM * **Forward secrecy**: New keys for each session and transfer * **No central authority**: Direct device-to-device trust ## API Usage ### Initialize Networking ```rust theme={null} // In Core initialization let networking = NetworkingService::new( data_dir.clone(), device_id, )?; // Start the event loop let event_loop = networking.spawn_event_loop(); tokio::spawn(event_loop.run()); ``` ### Pair Devices ```rust theme={null} // Generate pairing code (initiator) let code = core.networking() .start_pairing_as_initiator() .await?; println!("Share this code: {}", code); // Join pairing (joiner) core.networking() .join_pairing(&code) .await?; ``` ### Send Messages ```rust theme={null} // Get paired device let device = core.networking() .get_device(device_id)?; // Send sync request let message = NetworkMessage::SyncRequest { library_id, after: last_sync_hlc, }; device.send_message(message).await?; ``` ### Transfer Files ```rust theme={null} // Share a file let transfer = core.share_with_device( entry_id, device_id, TransferOptions { compress: true, encrypt: true, }, ).await?; // Monitor progress while let Some(progress) = transfer.progress().await { println!("Transfer: {}%", progress.percentage); } ``` ## Performance ### Benchmarks Typical performance on local network: * **Connection setup**: 10-50ms * **Message latency**: 1-5ms * **File transfer**: 100MB/s+ (gigabit network) * **Memory usage**: \~10MB per connection ### Optimization Strategies 1. **Connection pooling**: Reuse connections for multiple operations 2. **Stream multiplexing**: Multiple logical streams over one connection 3. **Adaptive chunking**: Adjust chunk size based on network conditions 4. **Compression**: Enable for text-heavy workloads ## Troubleshooting ### Connection Issues If devices can't connect: ```bash theme={null} # Check if port is open nc -zv 192.168.1.100 11204 # Monitor Iroh logs RUST_LOG=iroh=debug cargo run # Test connectivity iroh doctor connect ``` ### Common Problems **Problem**: "Connection refused" * Check firewall allows UDP port 11204 * Verify both devices are running * Ensure correct NodeId **Problem**: "Connection timeout" * Check network allows UDP traffic * Try relay connection instead of direct * Verify NAT type using STUN **Problem**: "Pairing failed" * Ensure pairing code is entered correctly * Check code hasn't expired (5 minute timeout) * Verify clocks are roughly synchronized ### Debug Commands ```rust theme={null} // Get connection info let info = endpoint.connection_info(node_id).await?; println!("RTT: {:?}", info.rtt); println!("Congestion: {:?}", info.congestion_window); // List connections for conn in endpoint.connections() { println!("Connected to: {}", conn.remote_node_id()); } // Force relay connection let mut node_addr = node_addr.clone(); node_addr.direct_addresses.clear(); // Force relay ``` ## Implementation Details ### Protocol Registration New protocols are registered during initialization: ```rust theme={null} impl Protocol for CustomProtocol { fn alpn(&self) -> &[u8] { b"custom/1.0" } async fn handle( &self, connection: Connection, ) -> Result<()> { // Handle incoming connection } } // Register during startup networking.register_protocol(Box::new(CustomProtocol::new())); ``` ### Error Handling The networking module uses a typed error system: ```rust theme={null} pub enum NetworkError { // Connection errors ConnectionFailed(node_id: NodeId), ConnectionTimeout(duration: Duration), // Protocol errors UnknownProtocol(alpn: String), ProtocolViolation(reason: String), // Security errors InvalidSignature, DecryptionFailed, // Device errors DeviceNotPaired(device_id: Uuid), DeviceOffline(device_id: Uuid), } ``` ### State Persistence Device relationships and session keys are encrypted and persisted via the KeyManager: ```rust theme={null} // Paired device data stored per-device in KeyManager pub struct PersistedPairedDevice { device_info: DeviceInfo, session_keys: SessionKeys, paired_at: DateTime, trust_level: TrustLevel, relay_url: Option, } // Storage: // - Device key: OS keychain or encrypted fallback file // - Paired devices: KeyManager's encrypted KV store (secrets.redb) // - Network identity: Derived from device key ``` ## Future Development ### Planned Features **Enhanced Discovery** * DHT-based global discovery * Bluetooth device discovery * QR code pairing **Advanced Protocols** * Video streaming protocol * Real-time collaboration * Distributed compute **Infrastructure** * Custom relay servers * Relay server selection * Bandwidth quotas **Performance** * Protocol buffer serialization * Native stream handling * Zero-copy transfers ### Extension Points The networking module is designed for extensibility: ```rust theme={null} // Custom protocol implementation pub trait NetworkProtocol: Send + Sync { fn alpn(&self) -> &[u8]; fn handle(&self, conn: Connection) -> BoxFuture>; } // Custom discovery mechanism pub trait Discovery: Send + Sync { fn discover(&self) -> BoxStream; } // Custom relay selection pub trait RelaySelector: Send + Sync { fn select(&self, relays: &[Url]) -> Url; } ``` ## Related Documentation * [Devices](/docs/core/devices) - Device identity and pairing * [Sync](/docs/core/sync) - Data synchronization over network * [Security](/docs/core/security) - Encryption and trust model # Operations Source: https://v2.spacedrive.com/core/ops The operations system automatically generates type-safe Swift and TypeScript clients from Rust API definitions. Define your API once in Rust and get native clients for iOS, web, and desktop without manual synchronization. ## How It Works The system uses compile-time type extraction to discover all operations and generate client code during the build process. This eliminates the traditional API boundary. ### Define Operations Operations are either Actions (write) or Queries (read): ```rust theme={null} #[derive(Debug, Clone, Serialize, Deserialize, Type)] pub struct CreateLibraryInput { pub name: String, pub description: Option, } pub struct CreateLibraryAction { input: CreateLibraryInput // action state can be held here } impl CoreAction for CreateLibraryAction { type Input = CreateLibraryInput; type Output = Library; async fn validate(&self, context: Arc) -> Result { // Check if the library already exists and return validation result Ok(ValidationResult::Success) } async fn execute(self, context: Arc) -> Result { // Create library and return it } fn action_kind(&self) -> &'static str { "libraries.create" } } ``` ### Register and Generate Register the operation with a single macro: ```rust theme={null} register_core_action!(CreateLibraryAction, "libraries.create"); ``` The build process automatically: 1. Extracts type information using Specta 2. Generates Swift and TypeScript type definitions 3. Creates native API methods for each client ### Use Generated Clients Swift: ```swift theme={null} let library = try await spacedrive.libraries.create( CreateLibraryInput(name: "My Library", description: nil) ) ``` TypeScript: ```typescript theme={null} const library = await spacedrive.libraries.create({ name: "My Library", }); ``` ## Operation Types ### Actions Actions modify state and typically return job receipts or updated entities: ```rust theme={null} pub trait LibraryAction { type Input: Send + Sync + 'static; type Output: Send + Sync + 'static; fn from_input(input: Self::Input) -> Result; async fn validate(&self, library: &Arc, context: Arc) -> Result; fn resolve_confirmation(&mut self, choice_index: usize) -> Result<(), ActionError>; async fn execute(self, library: Arc, context: Arc) -> impl Future>; fn action_kind(&self) -> &'static str; } ``` ### Validation and Confirmation Actions support a validation phase that can request user confirmation before execution. This enables safe, interactive operations with clear user feedback. #### ValidationResult The `validate()` method returns one of two results: ```rust theme={null} pub enum ValidationResult { /// Action is valid and can proceed Success, /// Action requires user confirmation RequiresConfirmation(ConfirmationRequest), } pub struct ConfirmationRequest { /// Message to display to the user pub message: String, /// List of choices for the user pub choices: Vec, } ``` #### Example: File Copy with Conflict Resolution ```rust theme={null} impl LibraryAction for FileCopyAction { type Input = FileCopyInput; type Output = JobReceipt; async fn validate(&self, library: &Arc, context: Arc) -> Result { // Check if destination file exists if !self.options.overwrite && self.destination_exists().await? { return Ok(ValidationResult::RequiresConfirmation(ConfirmationRequest { message: format!( "Destination file already exists: {}", self.destination.display() ), choices: vec![ "Overwrite the existing file".to_string(), "Rename the new file (e.g., file.txt -> file (1).txt)".to_string(), "Abort this copy operation".to_string(), ], })); } Ok(ValidationResult::Success) } fn resolve_confirmation(&mut self, choice_index: usize) -> Result<(), ActionError> { match choice_index { 0 => { self.on_conflict = Some(FileConflictResolution::Overwrite); Ok(()) } 1 => { self.on_conflict = Some(FileConflictResolution::AutoModifyName); Ok(()) } 2 => Err(ActionError::Cancelled), _ => Err(ActionError::Validation { field: "choice".to_string(), message: "Invalid choice selected".to_string(), }) } } async fn execute(mut self, library: Arc, context: Arc) -> Result { // Apply the conflict resolution strategy if set if let Some(resolution) = self.on_conflict { match resolution { FileConflictResolution::Overwrite => { self.options.overwrite = true; } FileConflictResolution::AutoModifyName => { self.destination = self.generate_unique_name().await?; } _ => {} } } // Execute the copy operation let job = FileCopyJob::new(self.sources, self.destination) .with_options(self.options); let receipt = library.jobs().dispatch(job).await?; Ok(receipt) } fn action_kind(&self) -> &'static str { "files.copy" } } ``` #### CLI Integration The CLI handles confirmations interactively: ```rust theme={null} // In CLI handler let mut action = FileCopyAction::from_input(input)?; // Validate the action let validation_result = action.validate(&library, context).await?; match validation_result { ValidationResult::Success => { // Proceed with execution let result = action.execute(library, context).await?; } ValidationResult::RequiresConfirmation(request) => { // Prompt user for choice let choice_index = prompt_for_choice(request)?; // Resolve the confirmation action.resolve_confirmation(choice_index)?; // Now execute with resolved choice let result = action.execute(library, context).await?; } } ``` The `validate()` method takes `&self` (a reference), while `execute()` takes `self` (consumes the action). This ensures validation doesn't modify state, while execution can take ownership to transform the action into its result. ### Queries Queries retrieve data without side effects: ```rust theme={null} pub trait LibraryQuery { type Input: Send + Sync + 'static; type Output: Send + Sync + 'static; fn from_input(input: Self::Input) -> QueryResult; fn execute(self, context: Arc, session: SessionContext) -> impl Future>; } ``` ## Type System All standard Rust types are supported through Specta: ```rust theme={null} #[derive(Debug, Clone, Serialize, Deserialize, Type)] pub struct FileOperationResult { pub succeeded: Vec, pub failed: HashMap, pub stats: OperationStats, } #[derive(Debug, Clone, Serialize, Deserialize, Type)] pub enum OperationError { NotFound(String), PermissionDenied, DiskFull { required: u64, available: u64 }, } ``` The `Type` derive is required for all types used in operations. This enables Specta to extract type information for client generation. ## Wire Protocol Operations use a consistent wire protocol: * Actions: `action:{category}.{operation}.input.v{version}` * Queries: `query:{scope}.{operation}.v{version}` Examples: * `action:files.copy.input` * `query:library.stats` ## Adding Operations ### 1. Create Input/Output Types ```rust theme={null} #[derive(Debug, Clone, Serialize, Deserialize, Type)] pub struct SearchInput { pub query: String, pub filters: SearchFilters, pub limit: u32, } #[derive(Debug, Clone, Serialize, Deserialize, Type)] pub struct SearchResult { pub items: Vec, pub total_count: u64, } ``` ### 2. Implement the Operation For a query: ```rust theme={null} pub struct SearchQuery { query: String, filters: SearchFilters, limit: u32, } impl LibraryQuery for SearchQuery { type Input = SearchInput; type Output = SearchResult; fn from_input(input: Self::Input) -> QueryResult { Ok(Self { query: input.query, filters: input.filters, limit: input.limit, }) } async fn execute(self, context: Arc, session: SessionContext) -> QueryResult { // Perform search and return results } } ``` ### 3. Register It ```rust theme={null} register_library_query!(SearchQuery, "search"); ``` ### 4. Build and Use After building, the operation is available in all clients automatically. ## iOS Integration The iOS app embeds the Rust core and communicates through FFI: ```rust theme={null} #[no_mangle] pub extern "C" fn handle_core_msg( query: *const c_char, callback: extern "C" fn(*mut c_void, *const c_char), callback_data: *mut c_void, ) { // Parse JSON-RPC request // Execute operation using same registry // Return JSON response } ``` Swift calls through the FFI boundary using the generated types. ## Code Generation Details ### Build Process The build script runs during `cargo build`: ```rust theme={null} // build.rs fn main() { generate_swift_api_code().expect("Failed to generate Swift code"); } ``` ### Type Extraction A binary extracts all registered operations: ```rust theme={null} // generate_swift_types binary fn main() { let (operations, queries, types) = generate_spacedrive_api(); // Generate Swift code let swift_types = specta_swift::Swift::new().export(&types)?; let api_methods = generate_api_methods(&operations, &queries); // Write to Swift package fs::write("SpacedriveTypes.swift", swift_types)?; fs::write("SpacedriveAPI.swift", api_methods)?; } ``` ### Registration Internals The registration macros use inventory for compile-time collection: ```rust theme={null} inventory::submit! { TypeExtractorEntry { extractor: SearchQuery::extract_types, identifier: "search", } } ``` ## Best Practices ### Operation Design Keep operations focused with clear inputs and outputs. Use appropriate scopes (Library vs Core) based on whether the operation needs library context. ### When to Use Validation Confirmations Use the confirmation pattern for operations that: 1. **Have Destructive Side Effects**: Deleting files, overwriting data, or making irreversible changes 2. **Encounter Conflicts**: File name collisions, duplicate entries, or conflicting states 3. **Need User Decisions**: Multiple valid approaches where user preference matters 4. **Risk Data Loss**: Operations that could result in unexpected data loss Examples of good confirmation use cases: * File copy/move when destination exists * Deleting non-empty directories * Overwriting modified files * Removing locations with indexed content * Irreversible format conversions Keep confirmations minimal - only ask when truly necessary. Don't confirm routine operations or when the intent is already clear from the input. ### Type Design Flatten structures when possible and use Rust enums for variants. Document fields as comments flow through to generated code. ### Error Handling Define specific error types for each operation: ```rust theme={null} #[derive(Debug, Serialize, Deserialize, Type)] pub enum SearchError { InvalidQuery(String), IndexNotReady, TooManyResults { max: u32, requested: u32 }, } ``` ### Performance For large result sets, consider pagination or streaming: ```rust theme={null} #[derive(Type)] pub struct PaginatedSearch { pub query: String, pub cursor: Option, pub limit: u32, } ``` ## Advanced Features ### Batch Operations ```rust theme={null} #[derive(Type)] pub struct BatchDeleteInput { pub items: Vec, pub skip_trash: bool, } ``` ### Operation Metadata Actions can define metadata for UI presentation: ```rust theme={null} impl ActionMetadata for DeleteAction { fn display_name() -> &'static str { "Delete Items" } fn description() -> &'static str { "Permanently delete selected items" } fn is_dangerous() -> bool { true } } ``` Confirmation is handled dynamically through the `validate()` method, not as static metadata. This allows context-aware confirmations based on the actual operation state. Run `cargo run --bin generate_swift_types` to debug type extraction issues. Check the generated files in `packages/swift/Sources/SpacedriveClient/Generated/`. The operations system eliminates manual API maintenance while providing type-safe, performant clients across all platforms. # Device Pairing Source: https://v2.spacedrive.com/core/pairing Device pairing establishes trust between Spacedrive instances using cryptographic signatures and user-friendly codes. Once paired, devices can communicate securely and share data directly. ## How Pairing Works Pairing uses a 12-word code to create a secure connection between two devices. The initiator generates the code, and the joiner enters it to establish trust. ### The Pairing Code Spacedrive uses BIP39 mnemonic codes for pairing, which come in two formats: #### Text Format (Local Network Only) A 12-word BIP39 mnemonic for manual entry: ``` brave lion sunset river eagle mountain forest ocean thunder crystal diamond phoenix ``` This format: * Works only on the same local network (mDNS discovery) * Easy to read and type * Contains 128 bits of entropy * Valid for 5 minutes * Never reused #### QR Code Format (Local + Internet) A JSON structure that enables both local and cross-network pairing: ```json theme={null} { "version": 2, "words": "brave lion sunset river eagle mountain forest ocean thunder crystal diamond phoenix", "node_id": "6jn4e7l3pzx2kqhv..." } ``` This format: * Works across different networks and the internet * Includes the initiator's node\_id for pkarr discovery * Enables automatic relay fallback * Same 5-minute expiration * Recommended for most use cases ### Security Model The pairing protocol provides multiple security guarantees: **Authentication**: Devices prove their identity using Ed25519 signatures **Confidentiality**: All communication encrypted with session keys **Integrity**: Challenge-response prevents tampering **Forward secrecy**: New keys for each session ## Choosing a Pairing Method ### When to Use Text Codes Text-based codes are best for: * Devices on the same local network (home, office) * Quick pairing without scanning QR codes * Situations where QR scanning is inconvenient **Limitations:** * Only works on the same subnet * Cannot traverse NATs or firewalls * Requires both devices to be on the same physical or virtual network ### When to Use QR Codes QR codes are recommended for: * Pairing across different networks * Remote device pairing over the internet * Maximum reliability (falls back to relay if needed) * Most production use cases **Benefits:** * Works anywhere with internet connectivity * Automatic relay fallback for NAT traversal * Faster on local networks (dual-path discovery) * More reliable overall ## Pairing Process ### For the Initiator Call the pairing API to generate a code: ```typescript theme={null} const result = await client.action("network.pair.generate", {}); // For local network pairing (manual entry) console.log(`Share this code: ${result.code}`); // For cross-network pairing (QR code) console.log(`QR code data: ${result.qr_json}`); // Contains: { version: 2, words: "...", node_id: "..." } ``` The device advertises via mDNS (local) and pkarr (internet) and waits for a joiner. The code expires after 5 minutes. **Advertisement includes:** * Session ID (via mDNS user\_data) * Node address published to dns.iroh.link (via pkarr) When a joiner connects, the initiator sends a cryptographic challenge to verify they have the correct code and own their device keys. After verification, both devices exchange session keys and save the pairing relationship. ### For the Joiner Enter the code from the initiator (text or QR): ```typescript theme={null} // Manual entry (local network only) await client.action("network.pair.join", { code: "brave lion sunset river eagle mountain forest ocean thunder crystal diamond phoenix" }); // QR code scan (local + internet) await client.action("network.pair.join", { code: '{"version":2,"words":"brave lion sunset...","node_id":"..."}' }); // Manual entry with node_id (enables internet pairing) await client.action("network.pair.join", { code: "brave lion sunset...", node_id: "6jn4e7l3pzx2kqhv..." }); ``` The system searches for the initiator using: * **Local network** (mDNS) - Scans for matching session\_id * **Internet** (pkarr/DNS) - Queries dns.iroh.link for node address (requires node\_id) * **Relay servers** - Automatic fallback if direct connection fails With QR codes, both paths run simultaneously and the first to succeed wins. Sign a challenge from the initiator to prove you have the code and own your device keys. Store the paired device information and session keys for future communication. ## Proxy pairing Proxy pairing lets a new device join a network after a single direct pairing. The device that completed the direct pairing can vouch for the new device to other trusted devices. Each receiving device can accept or reject the vouch. See [Proxy Pairing](/docs/core/proxy-pairing) for the full protocol, resource model, and flows. ## Technical Architecture ### Protocol Messages The pairing protocol uses four message types: ```rust theme={null} pub enum PairingMessage { // Joiner → Initiator: "I want to pair" PairingRequest { session_id: Uuid, device_info: DeviceInfo, public_key: Vec, }, // Initiator → Joiner: "Prove you have the code" Challenge { session_id: Uuid, challenge: Vec, // 32 random bytes device_info: DeviceInfo, }, // Joiner → Initiator: "Here's my signature" Response { session_id: Uuid, response: Vec, // 64-byte Ed25519 signature device_info: DeviceInfo, }, // Initiator → Joiner: "Pairing complete" Complete { session_id: Uuid, success: bool, reason: Option, }, } ``` ### State Machine The PairingProtocolHandler manages session state: ```rust theme={null} pub enum PairingState { // Initiator states WaitingForConnection, // Code generated, waiting ChallengeIssued, // Sent challenge to joiner // Joiner states Connecting, // Looking for initiator ChallengeReceived, // Got challenge, signing // Terminal states Completed, // Success! Failed(String), // Something went wrong } ``` ### Session Management Each pairing attempt creates a session: ```rust theme={null} pub struct PairingSession { session_id: Uuid, // Derived from code state: PairingState, // Current state remote_device: Option, created_at: SystemTime, expires_at: SystemTime, // 5 minutes later } ``` Sessions expire after 5 minutes. Users must complete pairing within this time window. ## Discovery Mechanisms Devices find each other through multiple methods, depending on the pairing code format: ### Local Network (mDNS) On the same network, devices discover each other instantly using multicast DNS: ```rust theme={null} // Initiator broadcasts session_id via user_data endpoint.set_user_data_for_discovery(Some(session_id)); // Joiner listens for matching session_id discovery_stream.filter(|item| { item.node_info().data.user_data() == session_id }); ``` **How it works:** * Initiator includes session\_id in mDNS broadcasts * Joiner scans local network for matching session\_id * Typically connects in 1-3 seconds * Only works on the same subnet ### Internet (Pkarr/DNS) For pairing across networks, Spacedrive uses pkarr to publish and resolve node addresses via DNS: ```rust theme={null} // Automatic pkarr publishing (done by Iroh) .add_discovery(PkarrPublisher::n0_dns()) // Publish to dns.iroh.link .add_discovery(DnsDiscovery::n0_dns()) // Resolve from dns.iroh.link // Joiner queries by node_id let node_addr = NodeAddr::new(node_id); // Pkarr resolves in background endpoint.connect(node_addr, PAIRING_ALPN).await?; ``` **How it works:** * Initiator automatically publishes its address to `dns.iroh.link` via pkarr * Record includes relay\_url and any direct addresses * Joiner queries `dns.iroh.link` with the node\_id from QR code * Pkarr returns all connection options (relay + direct) * Takes 5-15 seconds including DNS resolution Pkarr uses DNS-based discovery backed by the Mainline DHT. It's more reliable than traditional DHT for NAT traversal and works globally. ### Dual-Path Discovery When using QR codes (with node\_id), Spacedrive races both discovery methods: ```rust theme={null} tokio::select! { result = try_mdns_discovery(session_id) => { // Fast path: local network } result = try_relay_discovery(node_id) => { // Reliable path: internet via pkarr } } // First to succeed wins, other is canceled ``` This approach optimizes for speed on local networks while ensuring reliability across the internet. ### Relay Servers When direct connection fails, devices automatically connect through relay servers: ```rust theme={null} // Relay mode configured at startup .relay_mode(RelayMode::Default) // Uses n0's production relays // Automatic relay fallback during connection endpoint.connect(node_addr, PAIRING_ALPN).await?; // Tries direct, then relay ``` **Current Configuration:** * Uses n0's default relay servers (North America, Europe, Asia-Pacific) * Relay URLs discovered automatically via pkarr * Custom relay support coming soon (configurable per-node) Relay servers only forward encrypted QUIC traffic. They cannot decrypt your data or compromise security. ## Cryptographic Details ### Challenge-Response Authentication The challenge-response prevents replay attacks and verifies device identity: ```rust theme={null} // Initiator generates challenge let challenge = rand::thread_rng().gen::<[u8; 32]>(); // Joiner signs challenge let signature = signing_key.sign(&challenge); // Initiator verifies signature let valid = verifying_key.verify(&challenge, &signature).is_ok(); ``` ### Key Derivation Session keys are derived from the pairing code and device identities: ```rust theme={null} // Derive shared secret from pairing code let shared_secret = hkdf::extract( &pairing_code.secret, &[initiator_id, joiner_id].concat() ); // Generate session keys let (tx_key, rx_key) = hkdf::expand( &shared_secret, b"spacedrive-session-keys", 64 ); ``` ### Pkarr Implementation Spacedrive uses pkarr for decentralized node address resolution: ```rust theme={null} // Automatic publishing (initiator) let endpoint = Endpoint::builder() .add_discovery(PkarrPublisher::n0_dns()) // Publishes to dns.iroh.link .bind().await?; // Automatic resolution (joiner) let endpoint = Endpoint::builder() .add_discovery(DnsDiscovery::n0_dns()) // Resolves from dns.iroh.link .bind().await?; // Discovery happens automatically during connection endpoint.connect(NodeAddr::new(node_id), PAIRING_ALPN).await?; ``` **How Pkarr Works:** * Uses DNS TXT records backed by the Mainline DHT * Records include relay URL and direct addresses * Automatic publishing every time the node's address changes * TTL-based caching for performance * No manual DHT interaction required ### Transport Security All pairing communication uses encrypted channels: 1. **QUIC encryption**: TLS 1.3 at transport layer 2. **Application encryption**: Additional layer using session keys 3. **Perfect forward secrecy**: New keys each session ## Error Handling ### Common Errors ```rust theme={null} pub enum PairingError { // User errors InvalidCode, // Wrong or malformed code CodeExpired, // Took too long // Network errors DeviceNotFound, // Can't find initiator ConnectionFailed, // Network issues // Security errors InvalidSignature, // Challenge verification failed UntrustedDevice, // Device key mismatch // State errors SessionNotFound, // Unknown session ID InvalidState, // Wrong state transition } ``` ### Recovery Strategies **Invalid code**: Check spelling, ensure correct code **Connection failed**: Check network, firewall settings **Timeout**: Generate new code and try again **Signature failed**: Restart both applications ## Implementation Guide ### Starting Pairing (Initiator) ```rust theme={null} // High-level API pub async fn start_pairing_as_initiator( &self ) -> Result { // Generate secure code let code = PairingCode::generate(); let session_id = code.derive_session_id(); // Create session let session = PairingSession::new_initiator(session_id); self.sessions.insert(session_id, session); // Advertise on network self.advertise_pairing(session_id).await?; Ok(code) } ``` ### Joining Pairing (Joiner) ```rust theme={null} // High-level API pub async fn start_pairing_as_joiner( &self, code: &str ) -> Result<()> { // Parse and validate code let pairing_code = PairingCode::from_str(code)?; let session_id = pairing_code.derive_session_id(); // Create session let session = PairingSession::new_joiner(session_id); self.sessions.insert(session_id, session); // Find and connect to initiator let initiator = self.discover_initiator(session_id).await?; self.connect_and_pair(initiator, session_id).await?; Ok(()) } ``` ### Handling Protocol Messages ```rust theme={null} impl PairingProtocolHandler { async fn handle_message( &mut self, msg: PairingMessage, peer_id: PeerId, ) -> Result<()> { match msg { PairingMessage::PairingRequest { .. } => { self.handle_pairing_request(..); } PairingMessage::Challenge { .. } => { self.handle_challenge(..); } PairingMessage::Response { .. } => { self.handle_response(..); } PairingMessage::Complete { .. } => { self.handle_complete(..); } } } } ``` ## Testing Pairing ### Unit Tests ```rust theme={null} #[test] fn test_pairing_code_generation() { let code = PairingCode::generate(); assert_eq!(code.words.len(), 12); assert!(code.is_valid()); } #[test] fn test_challenge_response() { let (signing_key, verifying_key) = generate_keypair(); let challenge = generate_challenge(); let signature = signing_key.sign(&challenge); assert!(verifying_key.verify(&challenge, &signature).is_ok()); } ``` ### Integration Tests ```rust theme={null} #[tokio::test] async fn test_full_pairing_flow() { // Start initiator let code = initiator.start_pairing_as_initiator().await?; // Join with code joiner.start_pairing_as_joiner(&code.to_string()).await?; // Verify both paired assert!(initiator.is_paired_with(joiner.device_id())); assert!(joiner.is_paired_with(initiator.device_id())); } ``` ## Best Practices ### For Users 1. **Prefer QR codes**: Use QR codes for reliability across any network 2. **Share codes securely**: Use encrypted messaging or voice calls for text codes 3. **Complete quickly**: Codes expire in 5 minutes 4. **Verify device names**: Check the paired device is correct 5. **One code at a time**: Cancel old attempts before starting new ones 6. **Check network connectivity**: For cross-network pairing, ensure internet access ### For Developers 1. **Handle all states**: Account for every possible state transition 2. **Clean up sessions**: Remove expired sessions promptly 3. **Log failures**: Record why pairing failed for debugging 4. **Test edge cases**: Network failures, timeouts, wrong codes ## Troubleshooting ### Pairing Fails Immediately Check: * Both devices have network connectivity * Firewalls allow Spacedrive traffic * System time is roughly correct (within 5 minutes) ### Cannot Find Device **For text-based codes:** * Ensure both devices are on the same local network * Check that mDNS is not blocked by firewalls * Text codes only work locally - use QR codes for cross-network pairing **For QR codes:** * Ensure both devices have internet connectivity * Check that the node\_id is included in the QR code * Verify dns.iroh.link is accessible (not blocked by corporate firewalls) * Try generating a fresh code ### Code Invalid or Expired Solutions: * Double-check spelling of all 12 words * Ensure code was entered within 5 minutes * Generate new code if expired * Check for typos in word order ## Related Documentation * [Networking](/docs/core/networking) - Network transport details * [Devices](/docs/core/devices) - Device management system * [Proxy Pairing](/docs/core/proxy-pairing) - Vouching based pairing flow * [Security](/docs/core/security) - Cryptographic architecture # Proxy Pairing Source: https://v2.spacedrive.com/core/proxy-pairing Proxy pairing lets a new device join a network after a single direct pairing. The device that paired directly can vouch for the new device to other trusted devices. This reduces repeated pairing while keeping explicit user approval. ## Goals * Reduce the number of direct pairing sessions required to grow a network. * Keep the user confirmation flow for direct pairing. * Let receiving devices choose to accept or reject a vouch. * Record the trust chain for audit and review. * Support offline devices by queueing vouches. ## Non goals * Multi hop vouching. Only directly paired devices can vouch. * Shared group keys or a central authority. * Automatic trust propagation without user control. ## Trust model Direct pairings remain the base trust relationship. Proxy pairings are derived from a trusted voucher. ``` A <-> direct <-> B <-> direct <-> C | +-> proxied to C ``` Persisted paired devices record the pairing type and the voucher. ```rust theme={null} pub struct PersistedPairedDevice { pub device_info: DeviceInfo, pub session_keys: SessionKeys, pub paired_at: DateTime, pub last_connected_at: Option>, pub connection_attempts: u32, pub trust_level: TrustLevel, pub relay_url: Option, pub pairing_type: PairingType, pub vouched_by: Option, pub vouched_at: Option>, } pub enum PairingType { Direct, Proxied, } ``` ## Compatibility with direct confirmation Proxy pairing builds on the direct confirmation flow. The direct pairing must reach a confirmed state before any vouching starts. The voucher then offers to vouch the new device to other devices. Receiving devices can auto accept or ask for user confirmation. ## Protocol additions ```rust theme={null} pub enum PairingMessage { // Existing messages: // PairingRequest, Challenge, Response, Complete, Reject ProxyPairingRequest { session_id: Uuid, vouchee_device_info: DeviceInfo, vouchee_public_key: Vec, voucher_device_id: Uuid, voucher_signature: Vec, timestamp: DateTime, }, ProxyPairingResponse { session_id: Uuid, accepting_device_id: Uuid, accepted: bool, reason: Option, }, ProxyPairingComplete { session_id: Uuid, accepted_by: Vec, rejected_by: Vec, }, } pub struct AcceptedDevice { pub device_id: Uuid, pub device_name: String, pub node_id: Option, } pub struct RejectedDevice { pub device_id: Uuid, pub device_name: String, pub reason: String, } ``` ## Resource model for UI The vouching session is a resource that the UI can subscribe to with `ResourceChanged` events. ```rust theme={null} #[derive(Debug, Clone, Serialize, Deserialize)] pub struct VouchingSession { pub id: Uuid, pub vouchee_device_id: Uuid, pub vouchee_device_name: String, pub voucher_device_id: Uuid, pub created_at: DateTime, pub state: VouchingSessionState, pub vouches: HashMap, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum VouchingSessionState { Pending, InProgress, Completed, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct VouchState { pub device_id: Uuid, pub device_name: String, pub status: VouchStatus, pub updated_at: DateTime, pub reason: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] pub enum VouchStatus { Selected, Queued, Waiting, Accepted, Rejected, Unreachable, } impl Identifiable for VouchingSession { type Id = Uuid; fn id(&self) -> Self::Id { self.id } } crate::register_resource_type!(VouchingSession, "vouching_session"); ``` ## Events for confirmation prompts The vouching session is driven by resource updates. Events are only needed for confirmation prompts and UI entry points. ```rust theme={null} pub enum Event { ProxyPairingConfirmationRequired { session_id: Uuid, vouchee_device_name: String, vouchee_device_os: String, voucher_device_name: String, voucher_device_id: Uuid, expires_at: String, }, ProxyPairingVouchingReady { session_id: Uuid, vouchee_device_id: Uuid, }, } ``` ## Actions ```rust theme={null} pub struct PairVouchInput { pub session_id: Uuid, pub target_device_ids: Vec, } pub struct PairVouchOutput { pub success: bool, pub accepted_by: Vec, pub rejected_by: Vec, pub pending_count: u32, } pub struct PairConfirmProxyInput { pub session_id: Uuid, pub accepted: bool, } pub struct PairConfirmProxyOutput { pub success: bool, pub error: Option, } ``` ## Voucher flow 1. The new device sends `PairingRequest`. 2. The voucher enters the confirmation state and the user confirms. 3. Direct pairing completes and session keys are stored. 4. The voucher creates a `VouchingSession` resource in `Pending`. 5. The voucher emits `ProxyPairingVouchingReady` so the UI can open a modal. 6. The user selects target devices and triggers `network.pair.vouch`. 7. The background worker processes each target: * Online devices move to `Waiting` and receive `ProxyPairingRequest`. * Offline devices move to `Queued` and are stored in `vouching_queue`. 8. Responses update the vouch status to `Accepted` or `Rejected`. 9. When all vouches reach a terminal state, the session becomes `Completed`. 10. The voucher sends `ProxyPairingComplete` to the vouchee. ## Receiving device flow 1. Receive `ProxyPairingRequest`. 2. Verify the voucher is a trusted, directly paired device. 3. Verify the vouch signature and timestamp. 4. Check that the vouchee is not already paired. 5. If auto accept is enabled, accept and store the device. 6. If manual confirmation is required, emit `ProxyPairingConfirmationRequired`. 7. Send `ProxyPairingResponse` with accepted or rejected. 8. Store the vouchee as `pairing_type: Proxied` when accepted. ## Vouchee flow 1. Complete direct pairing with the voucher. 2. Receive `ProxyPairingComplete`. 3. Store accepted devices with `pairing_type: Proxied`. 4. Update the device registry and emit resource updates. ## Vouch payload signature ```rust theme={null} pub struct VouchPayload { pub vouchee_device_id: Uuid, pub vouchee_public_key: Vec, pub vouchee_device_info: DeviceInfo, pub timestamp: DateTime, pub session_id: Uuid, } impl VouchPayload { pub fn sign(&self, signing_key: &SigningKey) -> Vec { let serialized = bincode::serialize(self).unwrap(); signing_key.sign(&serialized).to_bytes().to_vec() } pub fn verify(&self, signature: &[u8], verifying_key: &VerifyingKey) -> bool { let serialized = bincode::serialize(self).unwrap(); let signature = Signature::from_bytes(signature.try_into().unwrap()); verifying_key.verify(&serialized, &signature).is_ok() } } ``` The receiver accepts vouches that are within the configured age window and that come from a trusted voucher. ## Session key derivation for proxied pairing The receiving device and the vouchee derive keys from the voucher and vouchee shared secret. ```rust theme={null} pub fn derive_proxied_session_keys( voucher_device_id: Uuid, vouchee_device_id: Uuid, vouchee_public_key: &[u8], voucher_vouchee_shared_secret: &[u8], ) -> SessionKeys { let context = format!( "spacedrive-proxy-pairing-{}:{}:{}", voucher_device_id, vouchee_device_id, hex::encode(vouchee_public_key) ); let hkdf = Hkdf::::new(None, voucher_vouchee_shared_secret); let mut send_key = [0u8; 32]; let mut receive_key = [0u8; 32]; hkdf.expand(format!("{}-send", context).as_bytes(), &mut send_key).unwrap(); hkdf.expand(format!("{}-recv", context).as_bytes(), &mut receive_key).unwrap(); SessionKeys { send_key: send_key.to_vec(), receive_key: receive_key.to_vec(), created_at: Utc::now(), expires_at: Some(Utc::now() + Duration::days(1)), } } ``` The voucher includes derived keys in the proxy request for the receiving device, encrypted with the existing shared secret. The voucher also includes keys in the completion message sent to the vouchee. ## Persistent queue for offline devices Queued vouches are stored in `sync.db` so the system can retry when a device comes online. ```sql theme={null} CREATE TABLE vouching_queue ( id INTEGER PRIMARY KEY, session_id TEXT NOT NULL, target_device_id TEXT NOT NULL, vouchee_device_id TEXT NOT NULL, vouchee_device_info TEXT NOT NULL, vouchee_public_key BLOB NOT NULL, vouch_signature BLOB NOT NULL, created_at TEXT NOT NULL, expires_at TEXT NOT NULL, retry_count INTEGER DEFAULT 0, last_attempt_at TEXT, UNIQUE(session_id, target_device_id) ); CREATE INDEX idx_vouching_queue_target ON vouching_queue(target_device_id); CREATE INDEX idx_vouching_queue_expires ON vouching_queue(expires_at); ``` Processing logic: 1. A worker polls the queue every 10 seconds. 2. If a target device is online, send `ProxyPairingRequest` and move the vouch to `Waiting`. 3. Remove entries after success or after the max retry count. 4. Delete entries after `expires_at`. ## Configuration ```rust theme={null} pub struct ProxyPairingConfig { pub auto_accept_vouched: bool, pub auto_vouch_to_all: bool, pub vouch_signature_max_age: u64, pub vouch_response_timeout: u64, } ``` Suggested defaults: * `auto_accept_vouched`: true * `auto_vouch_to_all`: false * `vouch_signature_max_age`: 300 * `vouch_response_timeout`: 30 ## Security checks * The voucher must be trusted and directly paired. * The vouch signature must match the voucher public key. * The vouch timestamp must be within the allowed window. * The vouchee must not already be paired. * Devices with unreliable or blocked trust levels reject proxy pairing. ## Backwards compatibility * Devices without proxy pairing ignore `ProxyPairingRequest`. * The voucher records the lack of response as a rejection. * Existing direct pairings remain unchanged. ## Cleanup and retention * Remove `VouchingSession` data one hour after completion. * Remove queued vouches after seven days. ## Testing * Unit tests for vouch signature verification and timestamp checks. * Integration tests for accept and reject flows. * Queue processing tests for offline devices. * Tests for trust level rules and auto accept settings. ## Open questions * Key rotation for proxied session keys. * Whether to allow multi hop vouching in a future version. * Vouch revocation when a voucher is unpaired. # Releases Source: https://v2.spacedrive.com/core/releases Spacedrive uses GitHub Actions workflows, git tags, and a custom xtask command to manage releases. This page covers the full release pipeline from version bump to published artifacts. ## Versioning Spacedrive follows semver with pre-release suffixes for alpha/beta releases. ``` 2.0.0-alpha.1 # Pre-release 2.0.0-beta.1 # Pre-release 2.0.0 # Stable release ``` The version string lives in 7 files across the repo: * `core/Cargo.toml` * `apps/server/Cargo.toml` * `apps/cli/Cargo.toml` * `apps/tauri/src-tauri/Cargo.toml` * `apps/tauri/sd-tauri-core/Cargo.toml` * `apps/tauri/src-tauri/tauri.conf.json` * `apps/tauri/package.json` These must stay in sync. The bump command handles this automatically. ## Bump Command `cargo xtask bump` updates all version files, commits the changes, and creates a git tag. ```bash theme={null} cargo xtask bump 2.0.0-alpha.2 ``` This does three things: 1. Updates the version string in all 7 files 2. Commits with message `v2.0.0-alpha.2` 3. Creates git tag `v2.0.0-alpha.2` It does not push. You push manually when ready: ```bash theme={null} git push --tags ``` Pushing the tag triggers the release workflows. ## Workflows Five GitHub Actions workflows handle CI and releases. ### CI (`ci.yml`) Runs on every pull request and push to `main`. Handles formatting checks, linting, and build verification. This is the standard PR gate. ### Core Tests (`core_tests.yml`) Runs `sd-core` integration tests on push to `main` across macOS, Linux, and Windows. Tests run on real hardware including self-hosted macOS ARM64 and Windows runners. ### Release (`release.yml`) Triggered by pushing a `v*` tag or manual dispatch. Builds all release artifacts and creates a draft GitHub release. **Server binary builds:** | Platform | Architecture | | -------- | ------------ | | Linux | x86\_64 | | Linux | aarch64 | Server binaries are compiled with `sd-core/heif`, `sd-core/ffmpeg`, and `sd-core/ai` features enabled. Each produces a tarball with the binary and a SHA256 checksum. **Desktop builds (Tauri):** | Platform | Architecture | Bundle | | -------- | ------------ | -------- | | macOS | aarch64 | DMG, App | | macOS | x86\_64 | DMG, App | | Windows | x86\_64 | NSIS | | Linux | x86\_64 | DEB | | Linux | aarch64 | DEB | Desktop builds go through `tauri-action` which handles code signing (macOS), Tauri signing keys (for the updater), and bundle creation. macOS builds run on self-hosted runners with Apple signing certificates. The final `release` job waits for all builds to complete, downloads all artifacts, and creates a draft release on GitHub. The release is always created as a draft so you can review before publishing. The release is created as a **draft**. You must manually publish it on GitHub after verifying the artifacts. ### Server Docker (`server.yml`) Triggered by the same `v*` tag or manual dispatch. Builds a multi-arch Docker image (amd64 + arm64) and pushes it to GitHub Container Registry at `ghcr.io/spacedriveapp/spacedrive/server`. The Docker build uses `buildah` with QEMU emulation for cross-platform images. The Dockerfile is at `apps/server/Dockerfile`. **Tagging behavior:** | Tag pushed | Docker tags applied | `latest` updated? | | ---------------- | ------------------------ | ----------------- | | `v2.0.0-alpha.1` | `v2.0.0-alpha.1` | No | | `v2.0.0-beta.1` | `v2.0.0-beta.1` | No | | `v2.0.0` | `v2.0.0`, `latest` | Yes | | Manual dispatch | `{short-sha}`, `staging` | No | The `latest` tag only moves for stable releases (tags matching `vX.Y.Z` with no suffix). Pre-release tags like `alpha` or `beta` are published under their specific version only. This protects users pulling `latest` from getting unstable builds. ### Mobile Release (`mobile.yml`) Manual dispatch only. Builds the React Native app for iOS and/or Android. A platform picker lets you build `ios`, `android`, or `all`. The mobile app bundles `sd-mobile-core`, a native Expo module that wraps the Spacedrive Rust core. This means mobile builds require the full Cargo workspace and Rust cross-compilation toolchain, not just JavaScript bundling. **iOS (TestFlight):** 1. Compiles `sd-mobile-core` for `aarch64-apple-ios` via `cargo xtask build-mobile` 2. Runs `expo prebuild` to generate the Xcode project 3. Archives with `xcodebuild` using manual code signing 4. Exports IPA with `app-store-connect` distribution method 5. Uploads directly to TestFlight via `xcrun altool` Runs on a self-hosted macOS ARM64 runner (same as desktop macOS builds). TestFlight handles distribution to testers automatically after upload. **Android (Play Store Internal):** 1. Compiles `sd-mobile-core` for `aarch64-linux-android` via `cargo xtask build-mobile` 2. Runs `expo prebuild` to generate the Android project 3. Builds a signed AAB with `./gradlew bundleRelease` 4. Uploads to Play Store internal testing track Runs on a Linux runner with Java 17 and the Android SDK/NDK. The mobile workflow is manual dispatch only. It is not triggered by tags. Run it from the Actions tab when you want to push a mobile build to testers. **Required secrets (in addition to existing Apple secrets):** | Secret | Purpose | | ----------------------------- | -------------------------------------------------------------------- | | `MOBILE_PROVISIONING_PROFILE` | iOS App Store distribution profile for `com.spacedrive.app` (base64) | | `ANDROID_KEYSTORE` | Android release keystore file (base64) | | `ANDROID_KEYSTORE_PASSWORD` | Keystore password | | `ANDROID_KEY_ALIAS` | Signing key alias | | `ANDROID_KEY_PASSWORD` | Signing key password | | `GOOGLE_PLAY_SERVICE_ACCOUNT` | Google Play API service account JSON (for automated upload) | ## Release Flow A full release looks like this: ```bash theme={null} # 1. Bump version, commit, and tag cargo xtask bump 2.0.0-alpha.2 # 2. Push the tag (triggers release + server docker workflows) git push --tags # 3. Wait for workflows to complete on GitHub Actions # 4. Review the draft release on GitHub, then publish ``` Both `release.yml` and `server.yml` trigger in parallel from the same tag push. The GitHub release is created as a draft. The Docker image is pushed to ghcr.io immediately. Mobile releases are decoupled from this flow. Trigger the mobile workflow manually from the Actions tab when you want to push a build to TestFlight or Play Store internal testing. ## Tauri Updater Desktop builds include `includeUpdaterJson: true` in the Tauri action config. This generates a JSON manifest that the Tauri updater checks against to notify users of new versions. The updater JSON files are included as release artifacts alongside the binaries. ## Secrets The release workflow depends on several repository secrets: | Secret | Purpose | | ---------------------------- | --------------------------------------- | | `APPLE_CERTIFICATE` | macOS code signing certificate (base64) | | `APPLE_CERTIFICATE_PASSWORD` | Certificate password | | `APPLE_SIGNING_IDENTITY` | Signing identity string | | `APPLE_API_KEY` | App Store Connect API key ID | | `APPLE_API_KEY_BASE64` | API key file (base64) | | `APPLE_API_ISSUER` | API key issuer ID | | `APPLE_PROVIDER_SHORT_NAME` | Team provider short name | | `TAURI_PRIVATE_KEY` | Tauri update signing key | | `TAURI_KEY_PASSWORD` | Tauri signing key password | | `SENTRY_AUTH_TOKEN` | Sentry error tracking | The Docker workflow uses only `GITHUB_TOKEN` which is provided automatically. # Spacedrive Semantic Tagging System Source: https://v2.spacedrive.com/core/tagging ## Overview The Spacedrive semantic tagging system is an advanced, graph-based tagging architecture that transforms traditional flat tagging into a sophisticated semantic fabric for content organization. Unlike simple label-based systems, semantic tags support polymorphic naming, context-aware disambiguation, hierarchical relationships, and intelligent conflict resolution during synchronization. This system implements the semantic tagging architecture described in the Spacedrive whitepaper, enabling enterprise-grade knowledge management capabilities while maintaining intuitive user experience. ## Core Architecture ### Design Principles 1. **Graph-Based DAG Structure** - Tags form a directed acyclic graph with closure table optimization 2. **Polymorphic Naming** - Multiple tags can share the same name in different contexts 3. **Semantic Variants** - Each tag supports formal names, abbreviations, and aliases 4. **Context Resolution** - Intelligent disambiguation based on existing tag relationships 5. **Union Merge Conflicts** - Sync conflicts resolved by combining tags (additive approach) 6. **AI-Native Integration** - Built-in confidence scoring and pattern recognition 7. **Privacy-Aware** - Tags support visibility controls and search filtering ### Core Components 1. **SemanticTag** - Enhanced tag entity with variants and relationships 2. **TagRelationship** - Typed relationships between tags (parent/child, synonym, related) 3. **TagClosure** - Closure table for efficient hierarchical queries 4. **TagApplication** - Context-aware association of tags with content 5. **TagUsagePattern** - Co-occurrence tracking for intelligent suggestions 6. **TagContextResolver** - Disambiguation engine for ambiguous tag names ## Data Models ### SemanticTag The core tag entity with advanced semantic capabilities: ```rust theme={null} pub struct SemanticTag { pub id: Uuid, // Core identity pub canonical_name: String, // Primary name (e.g., "JavaScript") pub display_name: Option, // Context-specific display // Semantic variants - multiple access points pub formal_name: Option, // "JavaScript Programming Language" pub abbreviation: Option, // "JS" pub aliases: Vec, // ["ECMAScript", "ES"] // Context and categorization pub namespace: Option, // "Technology", "Geography", etc. pub tag_type: TagType, // Standard, Organizational, Privacy, System // Visual and behavioral properties pub color: Option, // Hex color for UI pub icon: Option, // Icon identifier pub description: Option, // Human-readable description // Advanced capabilities pub is_organizational_anchor: bool, // Creates visual hierarchies in UI pub privacy_level: PrivacyLevel, // Normal, Archive, Hidden pub search_weight: i32, // Influence in search results // Compositional attributes pub attributes: HashMap, pub composition_rules: Vec, // Metadata pub created_at: DateTime, pub updated_at: DateTime, pub created_by_device: Uuid, } ``` ### TagType Enum ```rust theme={null} pub enum TagType { Standard, // Regular user-created tag Organizational,// Creates visual hierarchies in interface Privacy, // Controls visibility and search behavior System, // AI or system-generated tag } ``` ### PrivacyLevel Enum ```rust theme={null} pub enum PrivacyLevel { Normal, // Standard visibility in all contexts Archive, // Hidden from normal searches but accessible via direct query Hidden, // Completely hidden from standard UI } ``` ### TagRelationship Defines relationships between tags in the semantic graph: ```rust theme={null} pub struct TagRelationship { pub parent_tag_id: i32, pub child_tag_id: i32, pub relationship_type: RelationshipType, pub strength: f32, // 0.0-1.0 relationship strength pub created_at: DateTime, } pub enum RelationshipType { ParentChild, // Hierarchical relationship (Technology → Programming) Synonym, // Equivalent meaning (JavaScript ECMAScript) Related, // Semantic relatedness (React Frontend) } ``` ### TagApplication Context-aware association of tags with user metadata: ```rust theme={null} pub struct TagApplication { pub tag_id: Uuid, pub applied_context: Option, // "image_analysis", "user_input" pub applied_variant: Option, // Which name variant was used pub confidence: f32, // 0.0-1.0 confidence score pub source: TagSource, // User, AI, Import, Sync pub instance_attributes: HashMap, pub created_at: DateTime, pub device_uuid: Uuid, } pub enum TagSource { User, // Manually applied by user AI, // Applied by AI analysis with confidence scoring Import, // Imported from external source Sync, // Synchronized from another device } ``` ## Database Schema ### Tables Overview ```sql theme={null} -- Core semantic tags CREATE TABLE semantic_tags ( id INTEGER PRIMARY KEY, uuid BLOB UNIQUE NOT NULL, canonical_name TEXT NOT NULL, display_name TEXT, formal_name TEXT, abbreviation TEXT, aliases JSON, -- Array of alternative names namespace TEXT, -- Context grouping tag_type TEXT DEFAULT 'standard', color TEXT, icon TEXT, description TEXT, is_organizational_anchor BOOLEAN DEFAULT FALSE, privacy_level TEXT DEFAULT 'normal', search_weight INTEGER DEFAULT 100, attributes JSON, -- Key-value pairs for complex attributes composition_rules JSON, -- Rules for attribute composition created_at TIMESTAMP NOT NULL, updated_at TIMESTAMP NOT NULL, created_by_device UUID, UNIQUE(canonical_name, namespace) -- Allow same name in different contexts ); -- Hierarchical relationships CREATE TABLE tag_relationships ( id INTEGER PRIMARY KEY, parent_tag_id INTEGER NOT NULL, child_tag_id INTEGER NOT NULL, relationship_type TEXT DEFAULT 'parent_child', strength REAL DEFAULT 1.0, created_at TIMESTAMP NOT NULL, FOREIGN KEY (parent_tag_id) REFERENCES semantic_tags(id) ON DELETE CASCADE, FOREIGN KEY (child_tag_id) REFERENCES semantic_tags(id) ON DELETE CASCADE, UNIQUE(parent_tag_id, child_tag_id, relationship_type) ); -- Closure table for efficient hierarchy traversal CREATE TABLE tag_closure ( ancestor_id INTEGER NOT NULL, descendant_id INTEGER NOT NULL, depth INTEGER NOT NULL, path_strength REAL DEFAULT 1.0, PRIMARY KEY (ancestor_id, descendant_id), FOREIGN KEY (ancestor_id) REFERENCES semantic_tags(id) ON DELETE CASCADE, FOREIGN KEY (descendant_id) REFERENCES semantic_tags(id) ON DELETE CASCADE ); -- Enhanced tag applications CREATE TABLE user_metadata_semantic_tags ( id INTEGER PRIMARY KEY, user_metadata_id INTEGER NOT NULL, tag_id INTEGER NOT NULL, applied_context TEXT, applied_variant TEXT, confidence REAL DEFAULT 1.0, source TEXT DEFAULT 'user', instance_attributes JSON, created_at TIMESTAMP NOT NULL, updated_at TIMESTAMP NOT NULL, device_uuid UUID NOT NULL, FOREIGN KEY (user_metadata_id) REFERENCES user_metadata(id) ON DELETE CASCADE, FOREIGN KEY (tag_id) REFERENCES semantic_tags(id) ON DELETE CASCADE, UNIQUE(user_metadata_id, tag_id) ); -- Usage pattern tracking for intelligent suggestions CREATE TABLE tag_usage_patterns ( id INTEGER PRIMARY KEY, tag_id INTEGER NOT NULL, co_occurrence_tag_id INTEGER NOT NULL, occurrence_count INTEGER DEFAULT 1, last_used_together TIMESTAMP NOT NULL, FOREIGN KEY (tag_id) REFERENCES semantic_tags(id) ON DELETE CASCADE, FOREIGN KEY (co_occurrence_tag_id) REFERENCES semantic_tags(id) ON DELETE CASCADE, UNIQUE(tag_id, co_occurrence_tag_id) ); -- Full-text search support CREATE VIRTUAL TABLE tag_search_fts USING fts5( tag_id, canonical_name, display_name, formal_name, abbreviation, aliases, description, namespace, content='semantic_tags', content_rowid='id' ); ``` ### Closure Table Pattern The closure table enables O(1) hierarchical queries by pre-computing all ancestor-descendant relationships: ```sql theme={null} -- Example: Technology → Programming → Web Development → React -- Direct relationships: INSERT INTO tag_relationships VALUES (1, 2, 'parent_child', 1.0); -- Tech → Programming INSERT INTO tag_relationships VALUES (2, 3, 'parent_child', 1.0); -- Programming → Web Dev INSERT INTO tag_relationships VALUES (3, 4, 'parent_child', 1.0); -- Web Dev → React -- Closure table automatically maintains all paths: INSERT INTO tag_closure VALUES (1, 1, 0, 1.0); -- Tech → Tech (self) INSERT INTO tag_closure VALUES (1, 2, 1, 1.0); -- Tech → Programming INSERT INTO tag_closure VALUES (1, 3, 2, 1.0); -- Tech → Web Dev (via Programming) INSERT INTO tag_closure VALUES (1, 4, 3, 1.0); -- Tech → React (via Programming, Web Dev) -- ... and so on for all relationships ``` This enables efficient queries like "find all content tagged with any descendant of Technology": ```sql theme={null} SELECT DISTINCT e.* FROM entries e JOIN user_metadata_semantic_tags umst ON e.metadata_id = umst.user_metadata_id JOIN tag_closure tc ON umst.tag_id = tc.descendant_id WHERE tc.ancestor_id = (SELECT id FROM semantic_tags WHERE canonical_name = 'Technology'); ``` ## Key Features ### 1. Polymorphic Naming Multiple tags can share the same canonical name when differentiated by namespace: ```rust theme={null} // Same name, different contexts let phoenix_city = SemanticTag { canonical_name: "Phoenix".to_string(), namespace: Some("Geography".to_string()), description: Some("City in Arizona, USA".to_string()), // ... }; let phoenix_myth = SemanticTag { canonical_name: "Phoenix".to_string(), namespace: Some("Mythology".to_string()), description: Some("Mythical bird that rises from ashes".to_string()), // ... }; ``` This allows natural, human-friendly naming without forcing artificial uniqueness. ### 2. Semantic Variants Each tag supports multiple access points for flexible user interaction: ```rust theme={null} let js_tag = SemanticTag { canonical_name: "JavaScript".to_string(), formal_name: Some("JavaScript Programming Language".to_string()), abbreviation: Some("JS".to_string()), aliases: vec!["ECMAScript".to_string(), "ES".to_string()], namespace: Some("Technology".to_string()), // ... }; // All of these resolve to the same tag: assert!(js_tag.matches_name("JavaScript")); assert!(js_tag.matches_name("js")); // Case insensitive assert!(js_tag.matches_name("ECMAScript")); assert!(js_tag.matches_name("JavaScript Programming Language")); ``` ### 3. Context-Aware Resolution When users type ambiguous tag names, the system intelligently resolves them based on existing context: ```rust theme={null} // User is working with geographic data and types "Phoenix" let context_tags = vec![arizona_tag, usa_tag, city_tag]; let resolved = tag_resolver.resolve_ambiguous_tag("Phoenix", &context_tags).await?; // Returns "Geography::Phoenix" (city) rather than "Mythology::Phoenix" (bird) ``` The resolution considers: * **Namespace compatibility** with existing tags * **Usage patterns** from historical co-occurrence * **Hierarchical relationships** between tags ### 4. Hierarchical Organization Tags form a directed acyclic graph (DAG) structure supporting: ``` Technology ├── Programming │ ├── Web Development │ │ ├── Frontend │ │ │ ├── React │ │ │ └── Vue │ │ └── Backend │ │ ├── Node.js │ │ └── Python │ └── Mobile Development │ ├── iOS │ └── Android └── Design ├── UI/UX └── Graphic Design ``` Benefits of hierarchical organization: * **Implicit Classification**: Tagging with "React" automatically inherits "Frontend", "Web Development", etc. * **Semantic Discovery**: Searching "Technology" surfaces all descendant content * **Emergent Patterns**: System reveals organizational connections users didn't explicitly create ### 5. AI Integration The system supports AI-powered tagging with confidence scoring: ```rust theme={null} // AI analyzes image and applies tags let ai_application = TagApplication { tag_id: vacation_tag_id, applied_context: Some("image_analysis".to_string()), confidence: 0.92, source: TagSource::AI, instance_attributes: hashmap! { "detected_objects".to_string() => json!(["dog", "beach", "sunset"]), "model_version".to_string() => json!("v2.1") }, // ... }; ``` AI features: * **Confidence Scoring**: 0.0-1.0 confidence levels for AI suggestions * **User Review**: Low confidence tags require user approval * **Learning Loop**: User corrections improve future AI suggestions * **Privacy Options**: Local models (Ollama) or cloud APIs with user control ### 6. Union Merge Conflict Resolution During synchronization, tag conflicts are resolved using an additive approach: ```rust theme={null} // Device A: Photo tagged with "vacation" let local_apps = vec![TagApplication::user_applied(vacation_tag_id, device_a)]; // Device B: Same photo tagged with "family" let remote_apps = vec![TagApplication::user_applied(family_tag_id, device_b)]; // Union merge result: Photo tagged with BOTH "vacation" AND "family" let merged = resolver.merge_tag_applications(local_apps, remote_apps).await?; ``` This prevents data loss and preserves all user intent during synchronization. ## Manager Layer ### TagManager Core manager providing high-level tag operations. Located in `ops/tags/manager.rs`: ```rust theme={null} use crate::ops::tags::manager::TagManager; impl TagManager { // Create new semantic tag pub async fn create_tag( &self, canonical_name: String, namespace: Option, created_by_device: Uuid, ) -> Result; // Find tags by name (including variants) pub async fn find_tags_by_name(&self, name: &str) -> Result, TagError>; // Resolve ambiguous tag names using context pub async fn resolve_ambiguous_tag( &self, tag_name: &str, context_tags: &[SemanticTag], ) -> Result, TagError>; // Create hierarchical relationship pub async fn create_relationship( &self, parent_id: Uuid, child_id: Uuid, relationship_type: RelationshipType, strength: Option Result<(), TagError>; // Get all descendant tags pub async fn get_descendants(&self, tag_id: Uuid) -> Result, TagError>; // Discover organizational patterns pub async fn discover_organizational_patterns(&self) -> Result, TagError>; // Merge tag applications (for sync) pub async fn merge_tag_applications( &self, local: Vec, remote: Vec, ) -> Result; } ``` ### TagContextResolver Handles intelligent disambiguation of ambiguous tag names: ```rust theme={null} impl TagContextResolver { pub async fn resolve_ambiguous_tag( &self, tag_name: &str, context_tags: &[SemanticTag], ) -> Result, TagError> { let candidates = self.find_all_name_matches(tag_name).await?; if candidates.len() <= 1 { return Ok(candidates); } // Score candidates based on context compatibility let mut scored_candidates = Vec::new(); for candidate in candidates { let mut score = 0.0; // Namespace compatibility score += self.calculate_namespace_compatibility(&candidate, context_tags).await?; // Usage pattern compatibility score += self.calculate_usage_compatibility(&candidate, context_tags).await?; // Hierarchical relationship compatibility score += self.calculate_hierarchy_compatibility(&candidate, context_tags).await?; scored_candidates.push((candidate, score)); } // Return candidates sorted by relevance score scored_candidates.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap()); Ok(scored_candidates.into_iter().map(|(tag, _)| tag).collect()) } } ``` ### TagUsageAnalyzer Tracks usage patterns and discovers emergent organizational structures: ```rust theme={null} impl TagUsageAnalyzer { // Record when tags are used together pub async fn record_usage_patterns( &self, tag_applications: &[TagApplication], ) -> Result<(), TagError>; // Find frequently co-occurring tag pairs pub async fn get_frequent_co_occurrences( &self, min_count: i32, ) -> Result, TagError>; // Calculate how often a tag appears with context tags pub async fn calculate_co_occurrence_score( &self, candidate: &SemanticTag, context_tags: &[SemanticTag], ) -> Result; } ``` ### UserMetadataManager Manages user metadata including semantic tag applications. Located in `ops/metadata/manager.rs`: ```rust theme={null} use crate::ops::metadata::manager::UserMetadataManager; impl UserMetadataManager { // Apply semantic tags to user metadata pub async fn apply_semantic_tags( &self, entry_uuid: Uuid, tag_applications: Vec, device_id: Uuid, ) -> Result<(), TagError>; // Get all tags applied to an entry pub async fn get_applied_tags( &self, entry_uuid: Uuid, ) -> Result, TagError>; // Remove tags from an entry pub async fn remove_tags( &self, entry_uuid: Uuid, tag_ids: Vec, ) -> Result<(), TagError>; } ``` ## Usage Examples ### Basic Tag Creation ```rust theme={null} use crate::ops::tags::manager::TagManager; use std::sync::Arc; let manager = TagManager::new(Arc::new(db.conn().clone())); // Create a basic tag let project_tag = manager.create_tag( "Project".to_string(), None, device_id ).await?; // Create contextual tags let phoenix_city = manager.create_tag( "Phoenix".to_string(), Some("Geography".to_string()), device_id ).await?; let phoenix_myth = manager.create_tag( "Phoenix".to_string(), Some("Mythology".to_string()), device_id ).await?; ``` ### Building Hierarchies ```rust theme={null} // Create tag hierarchy: Technology → Programming → Web Development let tech_tag = manager.create_tag("Technology".to_string(), None, device_id).await?; let prog_tag = manager.create_tag("Programming".to_string(), None, device_id).await?; let web_tag = manager.create_tag("Web Development".to_string(), None, device_id).await?; // Create parent-child relationships manager.create_relationship( tech_tag.id, prog_tag.id, RelationshipType::ParentChild, None ).await?; manager.create_relationship( prog_tag.id, web_tag.id, RelationshipType::ParentChild, None ).await?; // Query descendants let all_tech_tags = manager.get_descendants(tech_tag.id).await?; // Returns: [Programming, Web Development, and any other descendant tags] ``` ### Applying Tags to Content ```rust theme={null} // User manually tags a file let user_app = TagApplication::user_applied(javascript_tag_id, device_id); // AI analyzes and suggests tags let ai_app = TagApplication::ai_applied(react_tag_id, 0.95, device_id); ai_app.applied_context = Some("code_analysis".to_string()); // Apply tags to user metadata let applications = vec![user_app, ai_app]; manager.record_tag_usage(&applications).await?; ``` ### Context Resolution ```rust theme={null} // User types "JS" while working with React files let context_tags = vec![react_tag, frontend_tag, web_dev_tag]; let resolved = manager.resolve_ambiguous_tag("JS", &context_tags).await?; // Returns JavaScript tag (in Technology namespace) as best match ``` ### Pattern Discovery ```rust theme={null} // Discover emergent organizational patterns let patterns = manager.discover_organizational_patterns().await?; for pattern in patterns { match pattern.pattern_type { PatternType::FrequentCoOccurrence => { println!("Tags often used together: suggest relationship"); } PatternType::HierarchicalRelationship => { println!("Suggest parent-child relationship"); } PatternType::ContextualGrouping => { println!("Suggest namespace grouping"); } } } ``` ## Integration with Core Systems ### Entry-Centric Metadata Every Entry has immediate metadata capability through the `metadata_id` field: ```rust theme={null} // Entry always links to UserMetadata pub struct Entry { pub metadata_id: i32, // Always present - immediate tagging! // ... other fields } // UserMetadata contains semantic tag applications pub struct UserMetadata { pub semantic_tags: Vec, // Enhanced tag applications // ... other metadata } ``` ### Action System Integration The semantic tagging system integrates with Spacedrive's Action System for validation, audit logging, and transactional operations: ```rust theme={null} // Tag creation through actions use crate::ops::tags::create::{CreateTagAction, CreateTagInput}; let action = CreateTagAction::new(CreateTagInput { canonical_name: "JavaScript".to_string(), namespace: Some("Technology".to_string()), // ... other fields }); let result = action.execute(library, context).await?; ``` ```rust theme={null} // Tag application through actions use crate::ops::tags::apply::{ApplyTagsAction, ApplyTagsInput}; let action = ApplyTagsAction::new(ApplyTagsInput { entry_ids: vec![entry_id], tag_applications: vec![tag_application], }); let result = action.execute(library, context).await?; ``` This enables: * **Instant Tagging**: Files can be tagged immediately upon discovery * **Rich Context**: Each tag application includes confidence, source, and attributes * **Sync Integration**: Tag applications sync with conflict resolution ### Indexing System Integration The indexing system can trigger automatic tagging during the Intelligence Queueing Phase: ```rust theme={null} // During indexing, queue AI analysis jobs if entry.kind == EntryKind::File { match entry.file_type { FileType::Image => { job_queue.push(ImageAnalysisJob::new(entry.id)).await?; } FileType::Code => { job_queue.push(CodeAnalysisJob::new(entry.id)).await?; } // ... other types } } ``` AI analysis jobs apply semantic tags with confidence scores. ### Search Integration The Temporal-Semantic Search system leverages semantic tags for enhanced discovery: ```sql theme={null} -- Semantic search using tag hierarchy SELECT DISTINCT e.* FROM entries e JOIN user_metadata_semantic_tags umst ON e.metadata_id = umst.user_metadata_id JOIN tag_closure tc ON umst.tag_id = tc.descendant_id JOIN semantic_tags st ON tc.ancestor_id = st.id WHERE st.canonical_name = 'Technology' AND umst.confidence > 0.8; ``` This enables queries like "find all Technology-related content" to surface files tagged with any descendant technology tags. ### Sync System Integration Semantic tags integrate with Library Sync using union merge resolution: ```rust theme={null} // Tags sync in the UserMetadata domain impl Syncable for UserMetadataSemanticTag { fn get_sync_domain(&self) -> SyncDomain { SyncDomain::UserMetadata // Union merge strategy } } // Conflict resolution preserves all tags let merged_tags = resolver.merge_tag_applications( local_applications, remote_applications ).await?; ``` ## Performance Considerations ### Closure Table Benefits The closure table pattern provides O(1) hierarchical queries: * **Ancestor Queries**: `SELECT * FROM tag_closure WHERE descendant_id = ?` * **Descendant Queries**: `SELECT * FROM tag_closure WHERE ancestor_id = ?` * **Path Queries**: `SELECT * FROM tag_closure WHERE ancestor_id = ? AND descendant_id = ?` * **Depth Queries**: `SELECT * FROM tag_closure WHERE depth = ?` ### Indexing Strategy Key database indexes for performance: ```sql theme={null} -- Tag lookup indexes CREATE INDEX idx_semantic_tags_canonical_name ON semantic_tags(canonical_name); CREATE INDEX idx_semantic_tags_namespace ON semantic_tags(namespace); CREATE INDEX idx_semantic_tags_type ON semantic_tags(tag_type); CREATE INDEX idx_semantic_tags_privacy ON semantic_tags(privacy_level); -- Closure table indexes CREATE INDEX idx_tag_closure_ancestor ON tag_closure(ancestor_id); CREATE INDEX idx_tag_closure_descendant ON tag_closure(descendant_id); CREATE INDEX idx_tag_closure_depth ON tag_closure(depth); -- Application indexes CREATE INDEX idx_user_metadata_semantic_tags_metadata ON user_metadata_semantic_tags(user_metadata_id); CREATE INDEX idx_user_metadata_semantic_tags_tag ON user_metadata_semantic_tags(tag_id); CREATE INDEX idx_user_metadata_semantic_tags_source ON user_metadata_semantic_tags(source); ``` ### Full-Text Search SQLite FTS5 provides efficient text search across all tag variants: ```sql theme={null} -- Search across all tag text fields SELECT tag_id, rank FROM tag_search_fts WHERE tag_search_fts MATCH 'javascript OR js OR ecmascript' ORDER BY rank; ``` ## File Organization The semantic tagging system is organized in the `ops/` directory following Spacedrive's architectural patterns: ``` core/src/ops/ ├── tags/ │ ├── manager.rs # Core tag management logic │ ├── facade.rs # High-level facade for UI/CLI │ ├── apply/ # Tag application actions │ │ └── action.rs │ ├── create/ # Tag creation actions │ │ └── action.rs │ └── search/ # Tag search actions │ └── action.rs └── metadata/ └── manager.rs # User metadata management ``` ## Migration Strategy Since this is a development codebase with no existing users, the semantic tagging system completely replaces the old simple tag system: 1. **Database Migration**: `m20250115_000001_semantic_tags.rs` creates all new tables 2. **Clean Implementation**: No data migration or backward compatibility needed 3. **Feature Complete**: All whitepaper features available from day one 4. **Performance Optimized**: Built with proper indexing and closure table 5. **Action Integration**: Full integration with Spacedrive's Action System ## Future Enhancements Planned advanced features building on this foundation: ### Enterprise RBAC Integration ```rust theme={null} // Role-based access control for tags pub struct TagPermission { pub role: UserRole, pub tag_namespace: Option, pub operations: Vec, // Create, Read, Update, Delete, Apply } ``` ### Advanced AI Features * **Semantic Similarity**: Vector embeddings for content-based tag suggestions * **Temporal Patterns**: Time-based usage analysis for lifecycle tagging * **Cross-Library Learning**: Federated learning across user libraries (privacy-preserving) ### Enhanced Sync Features * **Selective Sync**: Choose which tag namespaces to sync across devices * **Conflict Policies**: User-configurable resolution strategies * **Audit Trail**: Complete history of tag operations across all devices This semantic tagging architecture transforms Spacedrive from having simple labels to providing a sophisticated knowledge management foundation that scales from personal use to enterprise deployment. # Task Tracking Source: https://v2.spacedrive.com/core/task-tracking The `.tasks/` directory contains a structured task tracking system that manages the entire development lifecycle of Spacedrive. Tasks are defined as markdown files with YAML frontmatter and validated against a JSON schema. ## Overview Task tracking provides: * **Hierarchical organization** with epics and subtasks * **Status tracking** across the development lifecycle * **Metadata** like priority, assignee, and whitepaper references * **Validation** via a CLI tool to ensure consistency ### Directory Structure ``` .tasks/ ├── core/ # Backend/Rust tasks │ ├── CORE-000-vdfs-core.md │ ├── CORE-001-entry-centric-model.md │ ├── JOB-000-job-system.md │ ├── INDEX-*.md │ ├── LSYNC-*.md │ └── ... ├── interface/ # Frontend/React tasks │ ├── UI-000-interface-v2.md │ ├── EXPL-000-explorer-epic.md │ ├── SETS-000-settings-epic.md │ └── ... ├── mobile/ # Mobile-specific tasks │ └── (future tasks) ├── task.schema.json # JSON schema defining task structure └── Claude.md # Task tracking cheatsheet ``` Tasks follow the naming pattern: `{PREFIX}-{NUMBER}-{slug}.md` and are organized into subdirectories by domain (core, interface, mobile). ## Task Schema Every task file contains YAML frontmatter that must conform to the schema defined in `task.schema.json`. ### Required Fields ```yaml theme={null} --- id: CORE-001 title: Entry-Centric Data Model status: Done assignee: james priority: High --- ``` | Field | Type | Description | | ---------- | ------ | ---------------------------------------------------- | | `id` | string | Unique identifier matching pattern `^[A-Z]+-[0-9]+$` | | `title` | string | Human-readable title (min 5 characters) | | `status` | enum | One of: `To Do`, `In Progress`, `Done` | | `assignee` | string | Person responsible for the task | | `priority` | enum | One of: `High`, `Medium`, `Low` | ### Optional Fields ```yaml theme={null} --- parent: CORE-000 tags: [core, database, epic] whitepaper: Section 4.1 last_updated: 2025-12-02 --- ``` | Field | Type | Description | | -------------- | ------ | ------------------------------------ | | `parent` | string | Parent task ID for subtask hierarchy | | `tags` | array | Categorization tags | | `whitepaper` | string | Reference to design documentation | | `last_updated` | string | ISO date of last modification | ## Task Statuses The lifecycle of a task follows three states: ### To Do Task has not been started. No implementation exists. ### In Progress Task is actively being worked on. Criteria for this status: * Some code has been written * Feature is partially implemented * Still has rough edges or incomplete functionality ### Done Task is complete. All acceptance criteria must be met: * All listed acceptance criteria are implemented * Code is merged to main branch * Tests pass (if applicable) * Feature is production-ready Never mark a task as `Done` if implementation is partial, tests are failing, or the feature doesn't work as specified. ## Task Prefixes Tasks are organized by domain using prefixes. Tasks are further organized into subdirectories: ### Core Tasks (`.tasks/core/`) Backend and Rust-related tasks: | Prefix | Domain | | -------- | ------------------------------------- | | `CORE` | Core architecture and data model | | `JOB` | Job system and task execution | | `INDEX` | File indexing and location management | | `FSYNC` | File synchronization | | `LSYNC` | Library synchronization | | `NET` | Networking and P2P | | `SEARCH` | Search functionality | | `FILE` | File operations | | `LOC` | Location management | | `VOL` | Volume operations | | `SEC` | Security and privacy | | `CLI` | Command-line interface | | `CLOUD` | Cloud integration | | `AI` | AI and ML features | | `PLUG` | Plugin system | | `DEV` | Development tooling | ### Interface Tasks (`.tasks/interface/`) Frontend and React-related tasks: | Prefix | Domain | | ------- | ------------------------------- | | `UI` | UI primitives and design system | | `EXPL` | Explorer interface | | `SETS` | Settings pages | | `SRCH` | Search UI | | `TAG` | Tagging interface | | `MEDIA` | Media viewer | | `NAV` | Navigation and routing | | `PERF` | Performance optimizations | | `A11Y` | Accessibility | ### Mobile Tasks (`.tasks/mobile/`) Mobile-specific tasks (future): | Prefix | Domain | | ------- | --------------------- | | `IOS` | iOS native features | | `MACOS` | macOS native features | | `AND` | Android features | ## Task Validator CLI The `task-validator` binary provides utilities for managing and validating tasks. ### List Tasks View all tasks sorted by status: ```bash theme={null} cargo run --bin task-validator -- list --sort-by status ``` Output groups tasks by status (To Do, In Progress, Done): ``` === Done === CORE-000: Epic: VDFS Core Architecture CORE-001: Entry-Centric Data Model JOB-001: Job Manager for Task Scheduling === In Progress === CLOUD-003: Cloud Volume Support === To Do === AI-002: Create Fine-tuning Dataset ``` ### Filter Tasks Filter by specific criteria: ```bash theme={null} # By status cargo run --bin task-validator -- list --status "In Progress" # By priority cargo run --bin task-validator -- list --priority High # By assignee cargo run --bin task-validator -- list --assignee james ``` ### Validate Schema Ensure all task files conform to the schema: ```bash theme={null} cargo run --bin task-validator -- validate ``` This checks: * YAML frontmatter is valid * All required fields are present * Field values match allowed enums * ID pattern is correct * Parent references exist Validation runs in CI to prevent invalid tasks from being committed. ## Workflow ### Reviewing Task Status When code has been merged, tasks should be reviewed and updated: 1. **Check recent commits**: ```bash theme={null} git log --oneline -20 ``` 2. **List current task state**: ```bash theme={null} cargo run --bin task-validator -- list --sort-by status ``` 3. **For each potential completed feature**: * Read the task file to understand acceptance criteria * Read all implementation files mentioned in the task * Check `core/tests/` for integration tests * Verify each acceptance criterion is met in the code 4. **Update task status**: Edit the YAML frontmatter in the task file: ```yaml theme={null} --- status: Done # Changed from "In Progress" last_updated: 2025-12-02 # Update date --- ``` 5. **Validate changes**: ```bash theme={null} cargo run --bin task-validator -- validate ``` When unsure if a task is complete, leave it as `In Progress` rather than prematurely marking it `Done`. The tracker is only useful if it's accurate. ### Creating New Tasks 1. Choose appropriate subdirectory (`core/`, `interface/`, or `mobile/`) 2. Choose appropriate prefix based on domain 3. Find next available number (e.g., if `EXPL-002` exists, use `EXPL-003`) 4. Create file with pattern: `.tasks/{subdirectory}/{PREFIX}-{NUMBER}-{slug}.md` 5. Add YAML frontmatter with all required fields 6. Write task description and acceptance criteria 7. Validate: ```bash theme={null} cargo run --bin task-validator -- validate ``` Example core task file (`.tasks/core/LSYNC-017-realtime-sync.md`): ```markdown theme={null} --- id: LSYNC-017 title: Real-time Sync Protocol status: To Do assignee: james parent: LSYNC-000 priority: High tags: [core, sync, networking] whitepaper: Section 5.3 --- ## Description Implement a real-time synchronization protocol that pushes changes immediately rather than relying on polling intervals. ## Implementation Notes - Use WebSocket or similar bi-directional protocol - Integrate with existing sync service - Maintain backward compatibility with polling-based sync ## Acceptance Criteria - [ ] Changes propagate within 1 second between devices - [ ] Protocol handles network interruptions gracefully - [ ] Fallback to polling when real-time unavailable - [ ] Integration tests demonstrate cross-device sync ``` Example interface task file (`.tasks/interface/EXPL-004-breadcrumbs.md`): ```markdown theme={null} --- id: EXPL-004 title: Breadcrumb Navigation status: To Do assignee: james parent: EXPL-000 priority: Medium tags: [explorer, navigation, ui] --- ## Description Implement breadcrumb navigation in the Explorer top bar showing the current path with clickable segments. ## Implementation Notes - Display full path as clickable segments - Truncate middle segments if path is too long - Show dropdown menu for segments with many children - Keyboard navigation support ## Acceptance Criteria - [ ] Breadcrumbs show current location path - [ ] Click segment to navigate to that level - [ ] Path updates when navigating - [ ] Works with virtual locations and SD paths - [ ] Responsive truncation for long paths ``` ### Updating Task Status When updating tasks after completing work: **DO:** * Read implementation files thoroughly * Verify all acceptance criteria are met * Check for passing integration tests * Update `last_updated` field * Be rigorous about what "Done" means **DON'T:** * Mark tasks done based on assumptions * Skip reading the actual code * Ignore failing tests or partial implementations * Batch update tasks without verification ## Common Patterns ### Epic Tasks Epics are high-level tasks that have subtasks: ```yaml theme={null} --- id: CORE-000 title: "Epic: VDFS Core Architecture" status: Done assignee: james priority: High tags: [epic, core, vdfs] --- ``` Subtasks reference their epic via the `parent` field: ```yaml theme={null} --- id: CORE-001 title: Entry-Centric Data Model parent: CORE-000 status: Done --- ``` ### Task Dependencies While not enforced by schema, dependencies can be documented in task descriptions: ```markdown theme={null} ## Dependencies This task requires: - CORE-001 (Entry-Centric Model) - Done - INDEX-001 (Location Watcher) - In Progress ``` ### Whitepaper References Link tasks to design documentation: ```yaml theme={null} whitepaper: Section 4.1 ``` This helps trace implementation back to architectural decisions. ## Best Practices ### Task Granularity * **Epics**: High-level features spanning multiple subtasks * **Tasks**: Concrete features implementable in focused work * **Too granular**: Don't create tasks for every file or function ### Acceptance Criteria Write specific, testable criteria: **Good:** ```markdown theme={null} - [ ] User can add S3 bucket as a cloud volume - [ ] Cloud volumes appear in volume list - [ ] Files in cloud volume can be searched ``` **Bad:** ```markdown theme={null} - [ ] Implement cloud volume feature - [ ] Make it work properly ``` ### Status Accuracy The tracker is only valuable if it reflects reality: * Review and update tasks regularly * Don't mark tasks done to "clean up" the list * Keep `In Progress` honest about active work * Archive or remove truly obsolete tasks ### Git Integration While not automated, tasks can be referenced in commits: ```bash theme={null} git commit -m "feat: implement cloud volume indexing (CLOUD-003)" ``` This creates a searchable link between tasks and implementation: ```bash theme={null} git log --oneline --grep="CLOUD-003" ``` ## Troubleshooting ### Validation Errors **Invalid YAML**: ``` Error: Failed to parse YAML in CORE-001-entry-centric-model.md ``` Fix: Check YAML syntax, ensure frontmatter is enclosed in `---` **Missing Required Field**: ``` Error: Missing required field 'priority' in CORE-001 ``` Fix: Add the missing field to frontmatter **Invalid Status Value**: ``` Error: Invalid status 'Complete' in CORE-001. Must be one of: To Do, In Progress, Done ``` Fix: Use exact status values from schema (case-sensitive) ### Duplicate IDs Each task ID must be unique. If validation reports duplicates: ```bash theme={null} # Find all task IDs grep "^id:" .tasks/*.md | sort ``` Renumber conflicting tasks and update any parent references. ### Orphaned Tasks Tasks with `parent` fields referencing non-existent tasks: ```bash theme={null} cargo run --bin task-validator -- validate ``` Will report broken parent references. Either remove the parent field or create the missing epic. ## Examples ### Complete Epic with Subtasks ```markdown theme={null} # .tasks/SEARCH-000-semantic-search.md --- id: SEARCH-000 title: "Epic: Semantic Search System" status: In Progress assignee: james priority: High tags: [epic, search, ai] whitepaper: Section 6.2 --- ## Description Build a semantic search system using embeddings and vector similarity. ## Subtasks - SEARCH-001: Async search job infrastructure - SEARCH-002: Two-stage FTS + semantic reranking - SEARCH-003: Unified vector repositories ``` ```markdown theme={null} # .tasks/SEARCH-001-async-searchjob.md --- id: SEARCH-001 title: Async Search Job parent: SEARCH-000 status: Done assignee: james priority: High tags: [search, jobs] last_updated: 2025-11-15 --- ## Description Implement background search job that processes queries asynchronously. ## Acceptance Criteria - [x] SearchJob implements Job trait - [x] Queries execute in background thread pool - [x] Results stream back via events - [x] Integration test demonstrates full workflow ``` ## Integration with Development The task tracking system complements other development tools: * **Testing**: Acceptance criteria inform test cases * **CI/CD**: Schema validation runs in continuous integration * **Code Review**: Task IDs provide context in pull requests * **Documentation**: Tasks link to whitepaper design sections * **Planning**: Status overview shows project progress By maintaining accurate task status, the team has a real-time view of what's complete, what's in progress, and what's planned. # Testing Source: https://v2.spacedrive.com/core/testing Testing in Spacedrive Core ensures reliability across single-device operations and multi-device networking scenarios. This guide covers the available frameworks, patterns, and best practices. ## Testing Infrastructure Spacedrive Core provides two primary testing approaches: 1. **Standard Tests** - For unit and single-core integration testing 2. **Subprocess Framework** - For multi-device networking and distributed scenarios ### Test Organization Tests live in two locations: * `core/tests/` - Integration tests that verify complete workflows * `core/src/testing/` - Test framework utilities and helpers ## Standard Testing For single-device tests, use Tokio's async test framework: ```rust theme={null} #[tokio::test] async fn test_library_creation() { let setup = IntegrationTestSetup::new("library_test").await.unwrap(); let core = setup.create_core().await.unwrap(); let library = core.libraries .create_library("Test Library", None) .await .unwrap(); assert!(!library.id.is_empty()); } ``` ### Integration Test Setup The `IntegrationTestSetup` utility provides isolated test environments: ```rust theme={null} // Basic setup let setup = IntegrationTestSetup::new("test_name").await?; // Custom configuration let setup = IntegrationTestSetup::with_config("test_name", |builder| { builder .log_level("debug") .networking_enabled(true) .volume_monitoring_enabled(false) }).await?; ``` Key features: * Isolated temporary directories per test * Structured logging to `test_data/{test_name}/library/logs/` * Automatic cleanup on drop * Configurable app settings ## Multi-Device Testing Spacedrive provides two approaches for testing multi-device scenarios: ### When to Use Subprocess Framework **Use `CargoTestRunner` subprocess framework when:** * Testing **real networking** with actual network discovery, NAT traversal, and connections * Testing **device pairing** workflows that require independent network stacks * Scenarios need **true process isolation** (separate memory spaces, different ports) * You want to test network reconnection, timeout, and failure handling * Testing cross-platform network behavior **Examples:** Device pairing, network discovery, connection management ```rust theme={null} // Uses real networking, separate processes let mut runner = CargoTestRunner::new() .add_subprocess("alice", "alice_pairing_scenario") .add_subprocess("bob", "bob_pairing_scenario"); ``` ### When to Use Custom Transport/Harness **Use custom harness with mock transport when:** * Testing **sync logic** without network overhead * Fast iteration on **data synchronization** algorithms * Testing **deterministic scenarios** without network timing issues * Verifying **database state** and **conflict resolution** * Need precise control over sync event ordering **Examples:** Real-time sync, backfill, content identity linking, conflict resolution ```rust theme={null} // Uses mock transport, single process, fast and deterministic let harness = TwoDeviceHarnessBuilder::new("sync_test") .collect_events(true) .build() .await?; ``` ### Comparison | Aspect | Subprocess Framework | Custom Harness | | --------------- | --------------------------- | ----------------------- | | **Speed** | Slower (real networking) | Fast (in-memory) | | **Networking** | Real (discovery, NAT) | Mock transport | | **Isolation** | True process isolation | Shared process | | **Debugging** | Harder (multiple processes) | Easier (single process) | | **Determinism** | Network timing varies | Fully deterministic | | **Use Case** | Network features | Sync/data logic | ## Subprocess Testing Framework The subprocess framework spawns separate `cargo test` processes for each device role: ```rust theme={null} let mut runner = CargoTestRunner::new() .with_timeout(Duration::from_secs(90)) .add_subprocess("alice", "alice_scenario") .add_subprocess("bob", "bob_scenario"); runner.run_until_success(|outputs| { outputs.values().all(|output| output.contains("SUCCESS")) }).await?; ``` ### Writing Multi-Device Tests Create separate test functions for each device role: ```rust theme={null} #[tokio::test] async fn test_device_pairing() { let mut runner = CargoTestRunner::new() .add_subprocess("alice", "alice_pairing") .add_subprocess("bob", "bob_pairing"); runner.run_until_success(|outputs| { outputs.values().all(|o| o.contains("PAIRING_SUCCESS")) }).await.unwrap(); } #[tokio::test] #[ignore] async fn alice_pairing() { if env::var("TEST_ROLE").unwrap_or_default() != "alice" { return; } let data_dir = PathBuf::from(env::var("TEST_DATA_DIR").unwrap()); let core = create_test_core(data_dir).await.unwrap(); // Alice initiates pairing let (code, _) = core.start_pairing_as_initiator().await.unwrap(); fs::write("/tmp/pairing_code.txt", &code).unwrap(); // Wait for connection wait_for_connection(&core).await; println!("PAIRING_SUCCESS"); } ``` Device scenario functions must be marked with `#[ignore]` to prevent direct execution. They only run when called by the subprocess framework. ### Process Coordination Processes coordinate through: * **Environment variables**: `TEST_ROLE` and `TEST_DATA_DIR` * **Temporary files**: Share data like pairing codes * **Output patterns**: Success markers for the runner to detect ## Common Test Patterns ### Filesystem Watcher Testing When testing filesystem watcher functionality, several critical setup steps are required: #### Enable Watcher in Test Config The default `TestConfigBuilder` **disables the filesystem watcher** (for performance in sync tests). Tests that verify watcher events must explicitly enable it: ```rust theme={null} let mut config = TestConfigBuilder::new(test_root.clone()) .build()?; // CRITICAL: Enable watcher for change detection tests config.services.fs_watcher_enabled = true; config.save()?; let core = Core::new(config.data_dir.clone()).await?; ``` #### Use Home Directory Paths on macOS macOS temp directories (`/var/folders/...`) don't reliably deliver filesystem events. Use home directory paths instead: ```rust theme={null} // ❌ Don't use TempDir for watcher tests let temp_dir = TempDir::new()?; // ✅ Use home directory let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string()); let test_root = PathBuf::from(home).join(".spacedrive_test_my_test"); // Clean up before let _ = tokio::fs::remove_dir_all(&test_root).await; tokio::fs::create_dir_all(&test_root).await?; // ... run test ... // Clean up after tokio::fs::remove_dir_all(&test_root).await?; ``` #### Ephemeral Watching Requirements Ephemeral paths must be **indexed before watching**: ```rust theme={null} // 1. Index the directory (ephemeral mode) let config = IndexerJobConfig::ephemeral_browse( SdPath::local(dest_dir.clone()), IndexScope::Current ); let job = IndexerJob::new(config); library.jobs().dispatch(job).await?.wait().await?; // 2. Mark indexing complete (indexer job does this automatically) context.ephemeral_cache().mark_indexing_complete(&dest_dir); // 3. Register for watching (indexer job does this automatically) watcher.watch_ephemeral(dest_dir.clone()).await?; // Now filesystem events will be detected ``` The `IndexerJob` automatically calls `watch_ephemeral()` after successful indexing, so manual registration is only needed when bypassing the indexer. #### Persistent Location Watching For persistent locations, the watcher auto-loads locations at startup. New locations created during tests must be manually registered: ```rust theme={null} // After creating and indexing a location let location_meta = LocationMeta { id: location_uuid, library_id: library.id(), root_path: location_path.clone(), rule_toggles: RuleToggles::default(), }; watcher.watch_location(location_meta).await?; ``` The `IndexingHarness` handles this automatically. #### Event Collection Best Practices Start collecting events **after** initialization to avoid library statistics noise: ```rust theme={null} // Complete all setup first let harness = IndexingHarnessBuilder::new("test").build().await?; let location = harness.add_and_index_location(...).await?; // Wait for setup to settle tokio::time::sleep(Duration::from_millis(500)).await; // Start collecting BEFORE the operation you're testing let mut collector = EventCollector::new(&harness.core.events); let handle = tokio::spawn(async move { collector.collect_events(Duration::from_secs(5)).await; collector }); // Perform operation perform_copy_operation().await?; // Collect and verify let collector = handle.await.unwrap(); let stats = collector.analyze().await; assert!(stats.resource_changed.get("file").copied().unwrap_or(0) >= 2); ``` The `EventCollector` automatically filters out: * Library statistics updates (`LibraryStatisticsUpdated`) * Library resource events (non-file/entry events) #### Expected Event Types Different handlers emit different event types: * **Ephemeral handler**: Individual `ResourceChanged` events per file (CREATE + MODIFY) * **Persistent handler**: Batched `ResourceChangedBatch` events ```rust theme={null} // Ephemeral assertion let file_events = stats.resource_changed.get("file").copied().unwrap_or(0); assert!(file_events >= 2, "Expected file ResourceChanged events"); // Persistent assertion let batch_count = stats.resource_changed_batch.get("file").copied().unwrap_or(0); assert!(batch_count >= 2, "Expected file ResourceChangedBatch events"); ``` ### Event Monitoring #### Waiting for Specific Events Wait for specific Core events with timeouts: ```rust theme={null} let mut events = core.events.subscribe(); let event = wait_for_event( &mut events, |e| matches!(e, Event::JobCompleted { .. }), Duration::from_secs(30) ).await?; ``` #### Collecting All Events for Analysis For tests that need to verify event emission patterns (e.g., ResourceChanged events during operations), use the shared `EventCollector` helper: ```rust theme={null} use helpers::EventCollector; // Create collector with full event capture for debugging let mut collector = EventCollector::with_capture(&harness.core.events); // Spawn collection task let collection_handle = tokio::spawn(async move { collector.collect_events(Duration::from_secs(10)).await; collector }); // Perform operations that emit events perform_copy_operation().await?; location.reindex().await?; // Retrieve collector and analyze let collector = collection_handle.await.unwrap(); // Print statistics summary let stats = collector.analyze().await; stats.print(); // Print full event details for debugging (when using with_capture) collector.print_events().await; // Write events to JSON file for later inspection collector.write_to_file(&snapshot_dir.join("events.json")).await?; // Filter specific events let file_events = collector.get_resource_batch_events("file").await; let indexing_events = collector.get_events_by_type("IndexingCompleted").await; ``` The `EventCollector` tracks: * **ResourceChanged/ResourceChangedBatch** events by resource type * **Indexing** start/completion events * **Job** lifecycle events (started/completed) * **Entry** events (created/modified/deleted/moved) **Statistics Output:** ``` Event Statistics: ================== ResourceChangedBatch events: file → 45 resources Indexing events: Started: 1 Completed: 1 Entry events: Created: 3 Modified: 0 Job events: Started: indexer → 1 Completed: indexer → 1 ``` **Detailed Event Output (with `with_capture()`):** ``` === Collected Events (8) === [1] IndexingStarted Location: 550e8400-e29b-41d4-a716-446655440000 [2] JobStarted Job: indexer (job_123) [3] ResourceChangedBatch Type: file Resources: 45 items Paths: 1 affected [4] IndexingCompleted Location: 550e8400-e29b-41d4-a716-446655440000 Files: 42, Dirs: 3 [5] JobCompleted Job: indexer (job_123) Output: Success ``` **Use Cases:** * Verifying watcher events during file operations * Testing normalized cache updates * Debugging event emission patterns * Creating test fixtures with real event data * Inspecting actual resource payloads in events ### Database Verification Query the database directly to verify state: ```rust theme={null} use sd_core::entities; let entries = entities::entry::Entity::find() .filter(entities::entry::Column::Name.contains("test")) .all(db.conn()) .await?; assert_eq!(entries.len(), expected_count); ``` ### Job Testing Test job execution and resumption: ```rust theme={null} // Start a job let job_id = core.jobs.dispatch(IndexingJob::new(...)).await?; // Monitor progress wait_for_event(&mut events, |e| matches!( e, Event::JobProgress { id, .. } if *id == job_id ), timeout).await?; // Verify completion let job = core.jobs.get_job(job_id).await?; assert_eq!(job.status, JobStatus::Completed); ``` ### Mock Transport for Sync Testing Test synchronization without real networking: ```rust theme={null} let transport = Arc::new(Mutex::new(Vec::new())); let mut core_a = create_test_core().await?; let mut core_b = create_test_core().await?; // Connect cores with mock transport connect_with_mock_transport(&mut core_a, &mut core_b, transport).await?; // Verify sync perform_operation_on_a(&core_a).await?; wait_for_sync(&core_b).await?; ``` ## Test Data & Snapshot Conventions ### Data Directory Requirements All test data MUST be created in the system temp directory. Never persist data outside temp unless using the snapshot flag. **Naming convention**: `spacedrive-test-{test_name}` ```rust theme={null} // ✅ CORRECT: Platform-aware temp directory let test_data = TestDataDir::new("file_operations")?; // Creates: /tmp/spacedrive-test-file_operations/ (Unix) // or: %TEMP%\spacedrive-test-file_operations\ (Windows) // ❌ INCORRECT: Hardcoded paths outside temp let test_dir = PathBuf::from("~/Library/Application Support/spacedrive/tests"); let test_dir = PathBuf::from("core/data/test"); ``` **Standard structure**: ``` /tmp/spacedrive-test-{test_name}/ ├── core_data/ # Core database and state ├── locations/ # Test file locations └── logs/ # Test execution logs ``` **Cleanup**: Temp directories are automatically cleaned up after test completion using RAII pattern. ### Snapshot System Snapshots preserve test state for post-mortem debugging. They are optional and controlled by an environment variable. **Enable snapshots**: ```bash theme={null} # Single test SD_TEST_SNAPSHOTS=1 cargo test file_move_test --nocapture # Entire suite SD_TEST_SNAPSHOTS=1 cargo xtask test-core ``` **Snapshot location** (when enabled): ``` ~/Library/Application Support/spacedrive/test_snapshots/ (macOS) ~/.local/share/spacedrive/test_snapshots/ (Linux) %APPDATA%\spacedrive\test_snapshots\ (Windows) ``` **Structure**: ``` test_snapshots/ └── {test_name}/ └── {timestamp}/ ├── summary.md # Test metadata and statistics ├── core_data/ # Database copies │ ├── database.db │ └── sync.db ├── events.json # Event bus events (JSON lines) └── logs/ # Test execution logs ``` **When to use snapshots**: * Debugging sync tests (database state, event logs) * Complex indexing scenarios (closure table analysis) * Multi-phase operations (capture state at each phase) * Investigating flaky tests **Not needed for**: * Simple unit tests * Tests with assertion-only validation * Tests where console output is sufficient ### Fixture Generation Some tests generate fixtures used by other test suites (e.g., TypeScript tests consuming Rust-generated event data). These fixtures follow the same conventions as snapshots: always write to temp, only copy to source when explicitly requested. **Generate fixtures**: ```bash theme={null} # Single fixture test SD_REGENERATE_FIXTURES=1 cargo test normalized_cache_fixtures_test --nocapture ``` **Fixture location** (when enabled): ``` packages/ts-client/src/__fixtures/backend_events.json (TypeScript test fixtures) ``` **Default behavior**: * Fixtures written to temp directory * Test validates generation works * No modification of source tree **When `SD_REGENERATE_FIXTURES=1` is set**: * Fixtures generated in temp first (validation) * Copied to source tree for commit * Used by TypeScript tests **Example fixture test**: ```rust theme={null} #[tokio::test] async fn generate_typescript_fixtures() -> Result<()> { let temp_dir = TempDir::new()?; // Generate fixture data let fixture_data = generate_real_backend_events().await?; // Always write to temp let temp_fixture_path = temp_dir.path().join("backend_events.json"); std::fs::write(&temp_fixture_path, serde_json::to_string_pretty(&fixture_data)?)?; // Only copy to source if explicitly requested if std::env::var("SD_REGENERATE_FIXTURES").is_ok() { let source_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .parent().unwrap() .join("packages/ts-client/src/__fixtures__/backend_events.json"); std::fs::copy(&temp_fixture_path, &source_path)?; println!("Fixtures copied to source: {}", source_path.display()); } Ok(()) } ``` **When to regenerate fixtures**: * Backend event format changes * TypeScript types updated * New query responses added * Resource change events modified ### Helper Abstractions **TestDataDir** - Manages test data directories with automatic cleanup and snapshot support: ```rust theme={null} #[tokio::test] async fn test_file_operations() -> Result<()> { let test_data = TestDataDir::new("file_operations")?; let core = Core::new(test_data.core_data_path()).await?; // Perform test operations... // Optional: capture snapshot at specific point if let Some(manager) = test_data.snapshot_manager() { manager.capture("after_indexing").await?; } // Automatic cleanup and final snapshot (if enabled) on drop Ok(()) } ``` **SnapshotManager** - Captures test snapshots (accessed via `TestDataDir`): ```rust theme={null} // Multi-phase snapshot capture if let Some(manager) = test_data.snapshot_manager() { manager.capture("after_setup").await?; manager.capture("after_sync").await?; manager.capture("final_state").await?; } ``` **Integration with existing harnesses**: ```rust theme={null} // IndexingHarness uses TestDataDir internally let harness = IndexingHarnessBuilder::new("my_test").build().await?; // Access snapshot manager through harness if let Some(manager) = harness.snapshot_manager() { manager.capture("after_indexing").await?; } // TwoDeviceHarness has built-in snapshot method harness.capture_snapshot("after_sync").await?; ``` ## Test Helpers ### Common Utilities The framework provides comprehensive test helpers in `core/tests/helpers/`: **Event Collection:** * `EventCollector` - Collect and analyze all events from the event bus * `EventStats` - Statistics about collected events with formatted output **Indexing Tests:** * `IndexingHarnessBuilder` - Create isolated test environments with indexing support * `TestLocation` - Builder for test locations with files * `LocationHandle` - Handle to indexed locations with verification methods **Sync Tests:** * `TwoDeviceHarnessBuilder` - Pre-configured two-device sync test environments * `MockTransport` - Mock network transport for deterministic sync testing * `wait_for_sync()` - Sophisticated sync completion detection * `TestConfigBuilder` - Custom test configurations **Database & Jobs:** * `wait_for_event()` - Wait for specific events with timeout * `wait_for_indexing()` - Wait for indexing job completion * `register_device()` - Register a device in a library See `core/tests/helpers/README.md` for detailed documentation on all available helpers including usage examples and migration guides. ### Test Volumes For volume-related tests, use the test volume utilities: ```rust theme={null} use helpers::test_volumes; let volume = test_volumes::create_test_volume().await?; // Test volume operations test_volumes::cleanup_test_volume(volume).await?; ``` ## Core Integration Test Suite Spacedrive maintains a curated suite of core integration tests that run in CI and during local development. These tests are defined in a single source of truth using the `xtask` pattern. ### Running the Core Test Suite The `cargo xtask test-core` command runs all core integration tests with progress tracking: ```bash theme={null} # Run all core tests (minimal output) cargo xtask test-core # Run with full test output cargo xtask test-core --verbose ``` **Example output:** ``` ════════════════════════════════════════════════════════════════ Spacedrive Core Tests Runner Running 13 test suite(s) ════════════════════════════════════════════════════════════════ [1/13] Running: Library tests ──────────────────────────────────────────────────────────────── ✓ PASSED (2s) [2/13] Running: Indexing test ──────────────────────────────────────────────────────────────── ✓ PASSED (15s) ... ════════════════════════════════════════════════════════════════ Test Results Summary ════════════════════════════════════════════════════════════════ Total time: 7m 24s ✓ Passed (11/13): ✓ Library tests ✓ Indexing test ... ✗ Failed (2/13): ✗ Sync realtime test ✗ File sync test ``` ### Single Source of Truth All core integration tests are defined in `xtask/src/test_core.rs` in the `CORE_TESTS` constant: ```rust theme={null} pub const CORE_TESTS: &[TestSuite] = &[ TestSuite { name: "Library tests", args: &["test", "-p", "sd-core", "--lib", "--", "--test-threads=1"], }, TestSuite { name: "Indexing test", args: &["test", "-p", "sd-core", "--test", "indexing_test", "--", "--test-threads=1"], }, // ... more tests ]; ``` **Benefits:** * CI and local development use identical test definitions * Add or remove tests in one place * Automatic progress tracking and result summary * Continues running even if some tests fail ### CI Integration The GitHub Actions workflow runs the core test suite on all platforms: ```yaml theme={null} # .github/workflows/core_tests.yml - name: Run all tests run: cargo xtask test-core --verbose ``` Tests run in parallel on: * **macOS** (ARM64 self-hosted) * **Linux** (Ubuntu 22.04) * **Windows** (latest) With `fail-fast: false`, all platforms complete even if one fails. ### Deterministic Test Data Core integration tests use the Spacedrive source code itself as test data instead of user directories. This ensures: * **Consistent results** across all machines and CI * **No user data access** required * **Cross-platform compatibility** without setup * **Predictable file structure** for test assertions ```rust theme={null} // Tests index the Spacedrive project root let test_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) .parent() .unwrap() .to_path_buf(); let location = harness .add_and_index_location(test_path.to_str().unwrap(), "spacedrive") .await?; ``` Tests that need multiple locations use different subdirectories: ```rust theme={null} let project_root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) .parent() .unwrap() .to_path_buf(); let core_path = project_root.join("core"); let apps_path = project_root.join("apps"); ``` ### Adding Tests to the Suite To add a new test to the core suite: 1. Create your test in `core/tests/your_test.rs` 2. Add it to `CORE_TESTS` in `xtask/src/test_core.rs`: ```rust theme={null} pub const CORE_TESTS: &[TestSuite] = &[ // ... existing tests TestSuite { name: "Your new test", args: &[ "test", "-p", "sd-core", "--test", "your_test", "--", "--test-threads=1", "--nocapture", ], }, ]; ``` The test will automatically: * Run in CI on all platforms * Appear in `cargo xtask test-core` output * Show in progress tracking and summary Core integration tests use `--test-threads=1` to avoid conflicts when accessing the same locations or performing filesystem operations. ## Running Tests ### All Tests ```bash theme={null} cargo test --workspace ``` ### Core Integration Tests ```bash theme={null} # Run curated core test suite cargo xtask test-core # With full output cargo xtask test-core --verbose ``` ### Specific Test ```bash theme={null} cargo test test_device_pairing --nocapture ``` ### Debug Subprocess Tests ```bash theme={null} # Run individual scenario TEST_ROLE=alice TEST_DATA_DIR=/tmp/test cargo test alice_scenario -- --ignored --nocapture ``` ### With Logging ```bash theme={null} RUST_LOG=debug cargo test test_name --nocapture ``` ## Best Practices ### Test Structure 1. **Use descriptive names**: `test_cross_device_file_transfer` over `test_transfer` 2. **One concern per test**: Focus on a single feature or workflow 3. **Clean up resources**: Use RAII patterns or explicit cleanup 4. **Use deterministic test data**: Index Spacedrive source code instead of user directories ### Test Data 1. **All test data in temp directory**: Use `TestDataDir` or `TempDir` (see Test Data & Snapshot Conventions) 2. **Prefer project source code**: Use `env!("CARGO_MANIFEST_DIR")` to locate the Spacedrive repo for test indexing 3. **Avoid user directories**: Don't hardcode paths like `$HOME/Desktop` or `$HOME/Downloads` 4. **Use subdirectories for multiple locations**: `core/`, `apps/`, etc. when testing multi-location scenarios 5. **Cross-platform paths**: Ensure test paths work on Linux, macOS, and Windows ```rust theme={null} // ✅ Good: Platform-aware temp directory for test data let test_data = TestDataDir::new("my_test")?; // ✅ Good: Uses project source code for deterministic indexing let test_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) .parent() .unwrap() .to_path_buf(); // ❌ Bad: Data outside temp directory let test_dir = PathBuf::from("core/data/test"); // ❌ Bad: Uses user directory (non-deterministic) let desktop_path = std::env::var("HOME").unwrap() + "/Desktop"; ``` ### Subprocess Tests 1. **Always use `#[ignore]`** on scenario functions 2. **Check TEST\_ROLE early**: Return immediately if role doesn't match 3. **Use clear success patterns**: Print distinct markers for the runner 4. **Set appropriate timeouts**: Balance between test speed and reliability ### Debugging When tests fail, check the logs in `test_data/{test_name}/library/logs/` for detailed information about what went wrong. Common debugging approaches: * Run with `--nocapture` to see all output * Check job logs in `test_data/{test_name}/library/job_logs/` * Run scenarios individually with manual environment variables * Use `RUST_LOG=trace` for maximum verbosity ### Performance 1. **Run tests in parallel**: Use `cargo test` default parallelism 2. **Minimize sleeps**: Use event waiting instead of fixed delays 3. **Share setup code**: Extract common initialization into helpers ## Writing New Tests ### Single-Device Test Checklist * [ ] Create test with `#[tokio::test]` * [ ] Use `TestDataDir` or harness for test data (never hardcode paths outside temp) * [ ] Use deterministic test data for indexing (project source code, not user directories) * [ ] Wait for events instead of sleeping * [ ] Verify both positive and negative cases * [ ] Automatic cleanup via RAII pattern (no manual cleanup needed with helpers) ### Multi-Device Test Checklist * [ ] Create orchestrator function with `CargoTestRunner` * [ ] Create scenario functions with `#[ignore]` * [ ] Add TEST\_ROLE guards to scenarios * [ ] Define clear success patterns * [ ] Handle process coordination properly * [ ] Set reasonable timeouts * [ ] Use deterministic test data for cross-platform compatibility ### Core Integration Test Checklist When adding a test to the core suite (`cargo xtask test-core`): * [ ] Test uses deterministic data (Spacedrive source code) * [ ] Test runs reliably on Linux, macOS, and Windows * [ ] Test includes `--test-threads=1` if accessing shared resources * [ ] Add test definition to `xtask/src/test_core.rs` * [ ] Verify test runs successfully in CI workflow ## TypeScript Integration Testing Spacedrive provides a bridge infrastructure for running TypeScript tests against a real Rust daemon. This enables true end-to-end testing across the Rust backend and TypeScript frontend, verifying that cache updates, WebSocket events, and React hooks work correctly with real data. ### Architecture The TypeScript bridge test pattern works as follows: 1. **Rust test** creates a daemon with indexed locations using `IndexingHarnessBuilder` 2. **Connection info** (TCP socket address, library ID, paths) written to JSON config file 3. **Rust spawns** `bun test` with specific TypeScript test file 4. **TypeScript test** reads config, connects to daemon via `SpacedriveClient.fromTcpSocket()` 5. **TypeScript test** performs file operations and validates cache updates via React hooks 6. **Rust validates** test exit code and cleans up This pattern tests the entire stack: Rust daemon → RPC transport → TypeScript client → React hooks → cache updates. ### Writing Bridge Tests #### Rust Side Create a test in `core/tests/` that spawns the daemon and TypeScript test: ```rust theme={null} #[tokio::test] async fn test_typescript_cache_updates() -> anyhow::Result<()> { // Create daemon with RPC server enabled let harness = IndexingHarnessBuilder::new("typescript_bridge_test") .enable_daemon() // Start RPC server for TypeScript client .build() .await?; // Create test location with files let test_location = harness.create_test_location("test_files").await?; test_location.create_dir("folder_a").await?; test_location.write_file("folder_a/file1.txt", "Content").await?; // Index the location let location = test_location .index("Test Location", IndexMode::Shallow) .await?; // Get daemon socket address let socket_addr = harness .daemon_socket_addr() .expect("Daemon should be enabled") .to_string(); // Prepare bridge config for TypeScript let bridge_config = TestBridgeConfig { socket_addr, library_id: harness.library.id().to_string(), location_db_id: location.db_id, location_path: test_location.path().to_path_buf(), test_data_path: harness.temp_path().to_path_buf(), }; // Write config to temp file let config_path = harness.temp_path().join("bridge_config.json"); tokio::fs::write(&config_path, serde_json::to_string_pretty(&bridge_config)?).await?; // Spawn TypeScript test let ts_test_file = "packages/ts-client/tests/integration/mytest.test.ts"; let workspace_root = std::env::current_dir()?.parent().unwrap().to_path_buf(); let output = tokio::process::Command::new("bun") .arg("test") .arg(workspace_root.join(ts_test_file)) .env("BRIDGE_CONFIG_PATH", config_path.to_str().unwrap()) .current_dir(&workspace_root) .output() .await?; // Verify TypeScript test passed if !output.status.success() { anyhow::bail!("TypeScript test failed: {:?}", output.status.code()); } harness.shutdown().await?; Ok(()) } ``` Use `.enable_daemon()` on `IndexingHarnessBuilder` to start the RPC server. The daemon listens on a random TCP port returned by `.daemon_socket_addr()`. #### TypeScript Side Create a test in `packages/ts-client/tests/integration/`: ```typescript theme={null} import { describe, test, expect, beforeAll } from "bun:test"; import { readFile } from "fs/promises"; import { SpacedriveClient } from "../../src/client"; import { renderHook, waitFor } from "@testing-library/react"; import { SpacedriveProvider } from "../../src/hooks/useClient"; import { useNormalizedQuery } from "../../src/hooks/useNormalizedQuery"; interface BridgeConfig { socket_addr: string; library_id: string; location_db_id: number; location_path: string; test_data_path: string; } let bridgeConfig: BridgeConfig; let client: SpacedriveClient; beforeAll(async () => { // Read bridge config from Rust test const configPath = process.env.BRIDGE_CONFIG_PATH; const configJson = await readFile(configPath, "utf-8"); bridgeConfig = JSON.parse(configJson); // Connect to daemon via TCP socket client = SpacedriveClient.fromTcpSocket(bridgeConfig.socket_addr); client.setCurrentLibrary(bridgeConfig.library_id); }); describe("Cache Update Tests", () => { test("should update cache when files move", async () => { const wrapper = ({ children }) => React.createElement(SpacedriveProvider, { client }, children); // Query directory listing with useNormalizedQuery const { result } = renderHook( () => useNormalizedQuery({ query: "files.directory_listing", input: { path: { Physical: { path: folderPath } } }, resourceType: "file", pathScope: { Physical: { path: folderPath } }, debug: true, // Enable debug logging }), { wrapper }, ); // Wait for initial data await waitFor(() => { expect(result.current.data).toBeDefined(); }); // Perform file operation await rename(oldPath, newPath); // Wait for watcher to detect change (500ms buffer + processing) await new Promise((resolve) => setTimeout(resolve, 2000)); // Verify cache updated expect(result.current.data.files).toContainEqual( expect.objectContaining({ name: "newfile" }), ); }); }); ``` ### TCP Transport TypeScript tests connect to the daemon via TCP socket using `TcpSocketTransport`. This transport is designed for Bun/Node.js environments and enables testing outside the browser. ```typescript theme={null} // Automatic with factory method const client = SpacedriveClient.fromTcpSocket("127.0.0.1:6969"); // Manual construction import { TcpSocketTransport } from "@sd/ts-client/transports"; const transport = new TcpSocketTransport("127.0.0.1:6969"); const client = new SpacedriveClient(transport); ``` The TCP transport: * Uses JSON-RPC 2.0 over TCP * Supports WebSocket-style subscriptions for events * Automatically reconnects on connection loss * Works in both Bun and Node.js runtimes ### Testing Cache Updates The primary use case for bridge tests is verifying that `useNormalizedQuery` cache updates work correctly when the daemon emits `ResourceChanged` or `ResourceChangedBatch` events. **Key patterns:** 1. **Enable debug logging** with `debug: true` in `useNormalizedQuery` options 2. **Wait for watcher delays** (500ms buffer + processing time, typically 2-8 seconds) 3. **Collect events** by wrapping the subscription manager to log all received events 4. **Verify cache state** using React Testing Library's `waitFor` and assertions ```typescript theme={null} // Enable debug logging const { result } = renderHook( () => useNormalizedQuery({ query: "files.directory_listing", input: { /* ... */ }, resourceType: "file", pathScope: { /* ... */ }, debug: true, // Logs event processing }), { wrapper }, ); // Collect all events for debugging const allEvents: any[] = []; const originalCreateSubscription = (client as any).subscriptionManager .createSubscription; (client as any).subscriptionManager.createSubscription = function ( filter: any, callback: any, ) { const wrappedCallback = (event: any) => { allEvents.push({ timestamp: new Date().toISOString(), event }); console.log(`Event received:`, JSON.stringify(event, null, 2)); callback(event); }; return originalCreateSubscription.call(this, filter, wrappedCallback); }; ``` ### Running Bridge Tests ```bash theme={null} # Run all TypeScript bridge tests cargo test --package sd-core --test typescript_bridge_test -- --nocapture # Run specific bridge test cargo test test_typescript_use_normalized_query_with_file_moves -- --nocapture # Run only the TypeScript side (requires manual daemon setup) cd packages/ts-client BRIDGE_CONFIG_PATH=/path/to/config.json bun test tests/integration/mytest.test.ts ``` Use `--nocapture` to see TypeScript test output. The Rust test prints all stdout/stderr from the TypeScript test process. ### Common Scenarios **File moves between folders:** * Tests that files removed from one directory appear in another * Verifies UUID preservation (move detection vs delete+create) **Folder renames:** * Tests that nested files update their paths correctly * Verifies parent path updates propagate to descendants **Bulk operations:** * Tests 20+ file moves with mixed Physical/Content paths * Verifies cache updates don't miss files during batched events **Content-addressed files:** * Uses `IndexMode::Content` to enable content identification * Tests that files with `alternate_paths` update correctly * Verifies metadata-only updates don't add duplicate cache entries ### Debugging Bridge Tests **Check Rust logs:** ```bash theme={null} RUST_LOG=debug cargo test typescript_bridge -- --nocapture ``` **Check TypeScript output:** The Rust test prints all TypeScript stdout/stderr. Look for: * `[TS]` prefixed log messages * Event payloads with `🔔` emoji * Final event summary at test end **Verify daemon is running:** ```bash theme={null} # In Rust test output, look for: Socket address: 127.0.0.1:XXXXX Library ID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx ``` **Check bridge config:** ```bash theme={null} # The config file is written to test_data directory cat /tmp/test_data/typescript_bridge_test/bridge_config.json ``` **Common issues:** * **TypeScript test times out**: Increase watcher wait time (filesystem events can be slow) * **Cache not updating**: Enable `debug: true` to see if events are received * **Connection refused**: Verify daemon started with `.enable_daemon()` * **Wrong library**: Check that `client.setCurrentLibrary()` uses correct ID from config ## Examples For complete examples, refer to: **Core Test Infrastructure:** * `xtask/src/test_core.rs` - Single source of truth for all core integration tests * `.github/workflows/core_tests.yml` - CI workflow using xtask test runner **Single Device Tests:** * `tests/copy_action_test.rs` - Event collection during file operations (persistent + ephemeral) * `tests/job_resumption_integration_test.rs` - Job interruption handling **Subprocess Framework (Real Networking):** * `tests/device_pairing_test.rs` - Device pairing with real network discovery **Custom Harness (Mock Transport):** * `tests/sync_realtime_test.rs` - Real-time sync testing with deterministic transport using Spacedrive source code * `tests/sync_backfill_test.rs` - Backfill sync with deterministic test data * `tests/sync_backfill_race_test.rs` - Race condition testing with concurrent operations * `tests/file_transfer_test.rs` - Cross-device file operations **TypeScript Bridge Tests:** * `tests/typescript_bridge_test.rs` - Rust harness that spawns TypeScript tests * `packages/ts-client/tests/integration/useNormalizedQuery.test.ts` - File move cache updates * `packages/ts-client/tests/integration/useNormalizedQuery.folder-rename.test.ts` - Folder rename propagation * `packages/ts-client/tests/integration/useNormalizedQuery.bulk-moves.test.ts` - Bulk operations with content-addressed files # Virtual Sidecar System (VSS) Source: https://v2.spacedrive.com/core/virtual-sidecars The Virtual Sidecar System (VSS) manages derivative data associated with your files - thumbnails, OCR text, video transcripts, embeddings, and other metadata-rich artifacts. ## Key Principles **Content-Scoped**: Sidecars are linked to file content, not paths. Multiple copies of the same file share one set of sidecars. **Non-Destructive**: Spacedrive never modifies your original files during indexing. **Portable**: All managed sidecars live in `.sdlibrary/sidecars`, making your entire setup portable. ## Sidecar Types The VSS handles two types of sidecars: **Managed Sidecars** - Spacedrive-generated derivatives stored in `.sdlibrary/sidecars/`: * Thumbnails (`.webp`) * Video proxies (`.mp4`) * OCR text (`.json`) * Subtitles and lyrics (`.srt`) **Reference Sidecars** - Pre-existing files treated as sidecars: * Live Photo video components * RAW + JPEG pairs * Tracked by `source_entry_id` in database * Files stay in original location until user converts them to managed sidecars ### Filesystem Layout All sidecars are stored in a `sidecars` directory within the `.sdlibrary`. The path to a sidecar is deterministic and is derived from the content UUID of the file it is associated with, the kind of sidecar, and a variant. A typical path looks like this: ``` .sdlibrary/ sidecars/ content/ {h0}/{h1}/{content_uuid}/ thumbs/{variant}.webp proxies/{profile}.mp4 transcript/{variant}.srt ocr/default.json ``` * `{h0}/{h1}`: These are the first two byte-pairs of the content UUID, used for sharding the directory structure to ensure good filesystem performance at scale. * `{content_uuid}`: The unique identifier of the content the sidecar is associated with. * `thumbs/{variant}.webp`: An example of a thumbnail sidecar. ### Database Schema The VSS uses two tables in the Spacedrive database: * `sidecars`: This table tracks all the sidecars that have been generated or are pending generation. It stores information like the content UUID, kind, variant, format, path, size, and status. * `sidecar_availability`: This table tracks which devices in your library have a copy of a particular sidecar. This is used to avoid regenerating sidecars that already exist on another device. ### Sidecar Lifecycle **1. Identification** * **Managed**: Indexer queues generation job, creates "pending" record in `sidecars` table * **Reference**: Indexer creates `sidecar` record with `source_entry_id` pointing to original file **2. Generation** * **Managed**: Background job generates derivative, stores in deterministic path * **Reference**: No generation - already exists **3. Recording** * **Managed**: Job marks sidecar "ready", records size and metadata * **Reference**: Created as "ready" immediately * Both update `sidecar_availability` table for current device **4. Syncing** * Devices exchange availability information * Missing sidecars can be transferred from peers instead of regenerating ## Current Implementation Status The VSS is partially implemented. Here is a summary of the current status: * **Implemented:** * The core `SidecarManager` service. * Filesystem layout and path generation. * Database schema and queries for `sidecars` and `sidecar_availability`. * Enqueueing of sidecar generation jobs. * A `bootstrap_scan` function to synchronize the database with the filesystem. * Reference sidecars, which allow tracking files as sidecars without moving them. * **To-Do:** * **Job Dispatch and Execution:** The system for actually executing the generation jobs is not yet implemented. This is the most critical missing piece. * **Filesystem Watcher:** A watcher for the `sidecars` directory is needed for real-time updates. * **Checksumming:** Checksumming of sidecar files for integrity verification is not yet implemented. ## How to Use the VSS (API) The `SidecarManager` provides a set of APIs for interacting with the VSS. These are primarily for internal use by other Spacedrive services, but they can also be used for development and debugging. * `sidecars.presence(content_uuids, kind, variants)`: Checks for the presence of sidecars for a given set of content UUIDs. * `sidecars.path(content_uuid, kind, variant)`: Gets the local path to a sidecar, or enqueues it for generation if it doesn't exist. * `sidecars.reconcile()`: Triggers a bootstrap scan to reconcile the database with the filesystem. ## Benefits * **Non-Destructive**: Reference sidecars preserve original file locations * **Portable**: All managed sidecars in `.sdlibrary` can be moved/backed up as one unit * **Efficient**: One sidecar per content hash, shared across devices * **Extensible**: New sidecar kinds can be added without schema changes * **AI-Ready**: Provides structured data for semantic search and intelligent organization # Volumes Source: https://v2.spacedrive.com/core/volumes Spacedrive detects and tracks storage volumes across all platforms, including local drives and cloud storage. The volume system enables intelligent file operations by understanding where data lives and how to move it efficiently. ## How It Works The volume system operates in two modes: 1. **Runtime Detection** - Automatically discovers all mounted storage devices 2. **Volume Tracking** - Persists volumes you choose to track across sessions When you connect a drive or add cloud storage, Spacedrive detects it immediately. If you choose to track that volume, it remembers your preferences and recognizes it when reconnected. ## Storage Backends Spacedrive supports two types of storage backends: * **Local Filesystems** - Physical drives mounted on your system (APFS, NTFS, Ext4, etc.) * **Cloud Storage** - S3, Google Drive, Dropbox, OneDrive, and 40+ other services via OpenDAL ## Volume Identification Each volume gets a unique fingerprint based on hardware identifiers, capacity, and filesystem type: ```rust theme={null} let volume = volume_manager.volume_for_path(&path).await; println!("Volume: {} ({})", volume.name, volume.fingerprint); ``` This fingerprint remains stable even when mount points change. ### Sync Ownership Volumes serve as the ownership anchor for the sync system. Entries and locations reference a volume, inheriting ownership from the volume's device. This indirection enables portable storage: when you plug an external drive into a different machine, updating the volume's device reference transfers ownership of all associated files instantly. No bulk updates needed. See [Library Sync](/docs/core/library-sync) for details on how ownership flows through volumes and enables seamless device transfers. ### Unified Addressing Spacedrive uses service-native URIs for cloud volumes that match industry tools: ``` s3://my-bucket/photos/vacation.jpg ← Amazon S3 gdrive://My Drive/Documents/report.pdf ← Google Drive onedrive://Documents/budget.xlsx ← OneDrive azblob://container/data/export.csv ← Azure Blob gcs://bucket/logs/app.log ← Google Cloud Storage ``` These URIs work identically to local volume paths and enable seamless operations across all storage backends. See [Unified Addressing](/docs/core/addressing) for complete details. ## Volume Types ### Mount Types * **System** - Root filesystem and boot partitions * **External** - USB drives and removable storage * **Network** - NFS, SMB mounts * **Cloud** - Cloud storage services (S3, Google Drive, Dropbox, OneDrive, etc.) ### Disk Types * **SSD** - Solid state drives with fast random access * **HDD** - Traditional spinning disks * **Network** - Remote storage over network * **Virtual** - RAM disks and virtual filesystems ### Filesystems Spacedrive recognizes major filesystems including APFS, NTFS, Ext4, Btrfs, ZFS, FAT32, and ExFAT. ### Cloud Services Supports 40+ cloud services via OpenDAL: * **S3** - Amazon S3, Cloudflare R2, MinIO, Wasabi, Backblaze B2 * **Google Drive** - Consumer and Workspace accounts * **Dropbox** - Personal and Business * **OneDrive** - Personal and Business * **Google Cloud Storage** - GCS buckets * **Azure Blob Storage** - Azure containers ## Using Volumes ### Get Volume Information ```rust theme={null} // Find volume for a path let volume = volume_manager.volume_for_path("/Users/data").await; // List all volumes let volumes = volume_manager.get_all_volumes().await; // Check available space let available = volume.total_bytes_available; ``` ### Track Volumes Convert a runtime-detected volume into a tracked volume: ```rust theme={null} volume_manager.track_volume( &volume.fingerprint, &library_context, Some("My Backup Drive".to_string()) ).await?; ``` Tracked volumes persist across sessions and can have custom names, colors, and icons. ### Add Cloud Volumes Add cloud storage as a tracked volume: ```rust theme={null} use sd_core::ops::volumes::add_cloud::{CloudStorageConfig, VolumeAddCloudInput}; // Add S3 bucket via action let input = VolumeAddCloudInput { service: CloudServiceType::S3, display_name: "My S3 Bucket".to_string(), config: CloudStorageConfig::S3 { bucket: "my-bucket".to_string(), region: "us-west-2".to_string(), access_key_id: "AKIAXXXX".to_string(), secret_access_key: "secret".to_string(), endpoint: None, // Optional: for S3-compatible services }, }; let output = action_manager.execute(input, library, context).await?; ``` #### CLI Usage Add cloud volumes from the command line: ```bash theme={null} # Amazon S3 sd volume add-cloud "My S3 Bucket" \ --service s3 \ --bucket my-bucket \ --region us-west-2 \ --access-key-id AKIAXXXX \ --secret-access-key secret123 # Cloudflare R2 sd volume add-cloud "R2 Storage" \ --service s3 \ --bucket my-r2-bucket \ --region auto \ --access-key-id xxx \ --secret-access-key yyy \ --endpoint https://account.r2.cloudflarestorage.com # MinIO (self-hosted) sd volume add-cloud "MinIO Local" \ --service s3 \ --bucket test \ --region us-east-1 \ --access-key-id minioadmin \ --secret-access-key minioadmin \ --endpoint http://localhost:9000 # Remove cloud volume sd volume remove-cloud -y ``` Cloud volumes work identically to local volumes for indexing, searching, and file operations. ### Volume Events Monitor volume state changes: ```rust theme={null} let mut events = event_bus.subscribe(); while let Ok(event) = events.recv().await { match event { Event::VolumeAdded(volume) => { // New volume connected } Event::VolumeRemoved { fingerprint } => { // Volume disconnected } _ => {} } } ``` ## Copy-on-Write and Server-Side Operations Spacedrive uses optimal copy strategies based on the storage backend: ```rust theme={null} if volume.supports_cow() { // Use fast COW copy (APFS, Btrfs, ZFS, ReFS) perform_cow_copy(&src, &dst).await?; } else if volume.supports_server_side_copy() { // Cloud server-side copy (S3, GCS, Azure) perform_server_side_copy(&src, &dst).await?; } else { // Standard streaming copy perform_regular_copy(&src, &dst).await?; } ``` * COW copies on supported filesystems are nearly instant regardless of file size * Server-side cloud copies avoid downloading/uploading data through your machine * Cross-cloud operations automatically stream through local system ## Smart File Operations Volume awareness enables optimal file operations: ```rust theme={null} // Check if paths are on same volume let same_volume = volume_manager.same_volume(&src, &dst).await; if same_volume { // Fast move operation (local) or server-side rename (cloud) fs::rename(&src, &dst).await?; } else { // Cross-volume copy required copy_cross_volume(&src, &dst).await?; } ``` ### Cloud-Specific Optimizations Cloud volumes automatically use efficient operations: * **Ranged Reads** - Download only needed portions of files * **Content Hashing** - Sample-based hashing uses \~58KB for large files * **Parallel Operations** - Concurrent metadata and content fetches * **Metadata Caching** - Reduces redundant API calls ## Performance Monitoring Test volume read/write speeds: ```rust theme={null} let (read_mbps, write_mbps) = volume_manager .run_speed_test(&fingerprint).await?; ``` ## Platform Detection ### macOS Uses `diskutil` and `df` to detect APFS volumes and identify SSD/HDD types. ### Linux Parses `/sys/block/` and `df` output for filesystem and disk type information. ### Windows Uses PowerShell cmdlets for volume enumeration (implementation pending). ### Cloud Storage Uses OpenDAL for unified cloud service integration. Credentials are encrypted with library keys and stored securely in the OS keyring. #### Supported Cloud Services Fully integrated and tested: * **S3 and Compatible** - Amazon S3, Cloudflare R2, MinIO, Wasabi, Backblaze B2, DigitalOcean Spaces Implemented with OpenDAL backend: * Google Drive * Dropbox * OneDrive * Google Cloud Storage * Azure Blob Storage Note: OAuth flow for consumer cloud services (Google Drive, Dropbox, OneDrive) requires manual credential setup. Native OAuth integration coming soon. #### Credential Security Cloud credentials are: * Encrypted with library-specific keys using XChaCha20-Poly1305 * Stored in OS keyring (Keychain on macOS, Credential Manager on Windows, Secret Service on Linux) * Never written to disk in plaintext * Automatically deleted when volumes are removed ## Configuration ```rust theme={null} let config = VolumeDetectionConfig { include_system: false, // Skip system volumes include_virtual: false, // Skip virtual filesystems refresh_interval_secs: 30, // Monitor interval }; let volume_manager = VolumeManager::new(device_id, config, event_bus); ``` ### Cloud Volume Configuration Cloud volumes require service-specific configuration: ```rust theme={null} // S3-compatible services CloudStorageConfig::S3 { bucket: "bucket-name".to_string(), region: "us-west-2".to_string(), access_key_id: "key".to_string(), secret_access_key: "secret".to_string(), endpoint: Some("https://custom-endpoint.com".to_string()), // Optional } ``` The `endpoint` parameter enables use of S3-compatible services: * Cloudflare R2: `https://.r2.cloudflarestorage.com` * MinIO: `http://localhost:9000` or your server URL * Wasabi: `https://s3..wasabisys.com` * Backblaze B2: `https://s3..backblazeb2.com` * DigitalOcean Spaces: `https://.digitaloceanspaces.com` ## Error Handling ```rust theme={null} match volume_manager.track_volume(&library, &fingerprint, None).await { Ok(tracked) => { println!("Volume tracked: {}", tracked.display_name.unwrap_or_default()); } Err(VolumeError::NotFound(fp)) => { // Volume no longer available } Err(VolumeError::Platform(msg)) => { // Platform-specific error } Err(VolumeError::Database(msg)) => { // Database operation failed } } ``` ### Cloud-Specific Errors Cloud volumes may encounter additional error conditions: ```rust theme={null} use sd_core::crypto::cloud_credentials::CloudCredentialError; match credential_manager.get_credential(library_id, &fingerprint) { Ok(cred) => { /* Use credentials */ } Err(CloudCredentialError::NotFound(lib_id, fp)) => { // Credentials not found - volume may have been removed } Err(CloudCredentialError::Keyring(e)) => { // OS keyring access failed } Err(CloudCredentialError::Decryption(e)) => { // Credential decryption failed - may need re-authentication } } ``` ## Best Practices ### Performance * Cache volume lookups for hot paths * Use COW or server-side operations when available * Check space before large operations * For cloud: Use ranged reads for metadata extraction ### User Experience * Show tracking prompts for new external drives * Display volume capacity and network status in the UI * Allow custom naming and organization * Show cloud sync status and quota information ### Reliability * Handle disconnections gracefully (especially for cloud) * Validate fingerprints before operations * Monitor available space and network connectivity * Implement retry logic for transient cloud errors ### Security * Store cloud credentials encrypted in OS keyring using XChaCha20-Poly1305 * Use library-specific encryption keys for credential protection * Credentials are bound to both library ID and volume fingerprint * OAuth 2.0 with PKCE support planned for Google Drive, Dropbox, OneDrive * Never log credentials, tokens, or sensitive configuration * Automatic credential cleanup when volumes are removed ## Common Patterns ### Adding Locations When users add a location, suggest tracking its volume: ```rust theme={null} if let Some(volume) = volume_manager.volume_for_path(&location_path).await { if !volume_manager.is_volume_tracked(&volume.fingerprint).await? { // Prompt: "Track this volume for better performance?" } } ``` ### Space Checks Before large operations: ```rust theme={null} let required_bytes = calculate_operation_size(); let volumes = volume_manager.volumes_with_space(required_bytes).await; if volumes.is_empty() { return Err("Insufficient space on any volume"); } ``` ## Volume Statistics Tracked volumes maintain statistics: * Total files and directories * Read/write performance metrics (local) or API latency (cloud) * Last seen timestamp * Last sync timestamp (for cloud volumes) * User preferences (favorite, color, icon) These help users understand their storage usage and performance characteristics. ## Content Deduplication Across Storage Spacedrive uses consistent content hashing across all storage backends: ```rust theme={null} // Same file gets same content hash regardless of location let local_hash = hash_file("/local/photo.jpg").await?; let cloud_hash = hash_file("s3://bucket/photo.jpg").await?; assert_eq!(local_hash, cloud_hash); // Same content = same hash ``` This enables true cross-storage deduplication: * Identify duplicates between local drives and cloud storage * Skip uploading files that already exist in cloud * Find files across all storage locations using content hash Large files (>100KB) use sample-based hashing, transferring only \~58KB for content identification regardless of file size. This makes cloud indexing efficient even on slow connections. # Core Concepts Source: https://v2.spacedrive.com/extensions/core-concepts Extensions in Spacedrive are built with Rust macros that generate the integration code for you. Define your data models, jobs, and agents using attributes. The SDK handles sync, permissions, and sandboxing automatically. This page covers the five building blocks: extensions, models, jobs, agents, and actions. Each concept maps to a macro that generates the boilerplate. ### 1. Extension Definition (`#[extension]`) The `#[extension]` attribute is the entry point for your extension. It defines metadata, dependencies, and the permissions your extension requires. ```rust theme={null} #[extension( id = "com.spacedrive.photos", // Unique reverse-DNS ID name = "Photos Manager", version = "1.0.0", description = "Advanced photo organization with faces and places.", min_core_version = "2.0.0", // Minimum Spacedrive core version permissions = [ Permission::ReadEntries(glob = "**/*.{jpg,png,heic}"), Permission::WriteTags, ] )] struct Photos { config: PhotosConfig, // User-configurable settings } ``` * **Permissions**: Your extension requests permissions, and the user grants them, often scoped to specific parts of their library for privacy. * **Config**: You can define a configuration struct that allows users to customize your extension's behavior. ### 2. Models (`#[model]`) Models are the heart of your extension's data structure. The `#[model]` attribute allows you to define custom data models that are stored in **real database tables**, not as JSON blobs. This enables powerful querying, indexing, and relationships. ```rust theme={null} #[model( table_name = "person", version = "1.0.0", sync_strategy = "shared" )] #[index("email")] struct Person { #[primary_key] id: Uuid, name: String, #[indexed] email: Option, #[metadata] metadata_id: i32, // Enables tagging } ``` * **Real Tables**: Your models become actual SQL tables, prefixed with your extension's ID (e.g., `ext_photos_person`). * **Relationships**: You can define foreign key relationships to core Spacedrive objects or other models in your extension. * **Tagging**: By including a `#[metadata]` field, your models can be tagged and organized just like regular files. ### 3. Jobs and Tasks (`#[job]`, `#[task]`) Jobs and tasks are used to perform long-running or background operations, such as analyzing files or processing data. They are durable, resumable, and can be run in parallel. ```rust theme={null} #[task(retries = 3, timeout_ms = 30000)] async fn detect_faces(ctx: &TaskContext, entry: &Entry) -> TaskResult> { // ... face detection logic ... } #[job(parallelism = 4, trigger = "user_initiated")] async fn analyze_photos(ctx: &JobContext, location: SdPath) -> JobResult<()> { // ... logic to find photos and run detect_faces task ... } ``` * **Durability**: Jobs are persisted and can survive application restarts. * **Triggers**: Jobs can be initiated by users, events, or other system triggers. ### 4. AI Agents (`#[agent]`) Agents provide a way to create autonomous logic within your extension. They can observe events, reason about data, and act by dispatching jobs or modifying data. ```rust theme={null} #[agent] impl Photos { async fn on_new_photo(&self, ctx: &AgentContext, photo: Photo) -> AgentResult<()> { ctx.trace("New photo added - checking for faces"); // ... logic to analyze photo ... Ok(()) } } ``` * **Observe-Orient-Act**: Agents follow a classic AI loop to respond to changes in the system. * **Memory**: Agents can have their own memory to store knowledge and plans. ### 5. Actions (`#[action]`) Actions are user-invokable operations that can be previewed before execution. This ensures that users always know what changes an extension is about to make. ```rust theme={null} #[action] async fn organize_photos(ctx: &ActionContext, location: SdPath) -> ActionResult { // Works with any storage type match location { SdPath::Physical { .. } => organize_local_photos(ctx, location).await, SdPath::Cloud { .. } => organize_cloud_photos(ctx, location).await, SdPath::Content { .. } => { // Resolve content path to physical location first let resolved = location.resolve(ctx).await?; organize_photos(ctx, resolved).await } } } #[action_execute] async fn organize_photos_execute(ctx: &ActionContext, preview: ActionPreview) -> ActionResult<()> { // ... apply the changes ... } ``` * **Safety**: The preview-commit-verify flow ensures that all operations are safe and predictable. * **Universal**: Actions work seamlessly across local, cloud, and content-addressed files. # Data Storage Source: https://v2.spacedrive.com/extensions/data-storage Extensions get their own database tables and file storage locations. You define data models in Rust, and Spacedrive creates the tables automatically. You declare storage locations, and users choose where files go during installation. Extensions use three storage layers: database tables for domain models, files in user-controlled locations for original data, and sidecars for derivative intelligence. Spacedrive handles sync, indexing, and search automatically. #### Model Definition ```rust theme={null} #[model( table_name = "person", version = "1.0.0", sync_strategy = "shared" )] pub struct Person { #[primary_key] pub id: Uuid, pub name: String, #[indexed] pub email: Option, #[metadata] pub metadata_id: i32, } ``` #### Generated Schema This Rust struct will generate the following SQL table: ```sql theme={null} CREATE TABLE ext_photos_person ( id BLOB PRIMARY KEY, name TEXT NOT NULL, email TEXT, metadata_id INTEGER NOT NULL, FOREIGN KEY (metadata_id) REFERENCES user_metadata(id) ON DELETE CASCADE ); CREATE INDEX idx_ext_photos_person_email ON ext_photos_person(email); ``` ### Linking to Core Systems Extension models are not isolated silos. They are deeply integrated with Spacedrive's core systems. * **Tagging and Collections**: By adding the `#[metadata]` attribute to a field, your model is linked to the `user_metadata` table. This allows your custom data models to be tagged, added to collections, and searched just like any other file in Spacedrive. * **Core Entities**: You can define foreign key relationships to core Spacedrive tables like `entries` or `content_identities`. This allows you to, for example, create an `Album` model that has a many-to-many relationship with photos (entries). ### Migrations As you develop your extension, you will inevitably need to change your data models. The Spacedrive SDK includes a migration system to manage schema changes. * **Migration Files**: You can provide SQL migration files with your extension (e.g., `v1.1.0_add_birthdate.sql`). * **Automatic Execution**: When a user updates your extension, Spacedrive will automatically run the necessary migrations to bring their database schema up to date. ### Extension Locations Extensions that create files must declare their storage locations. Users choose where the data goes during installation. ```json theme={null} { "extension_id": "com.spacedrive.email", "locations": [ { "id": "email_archive", "name": "Email Archive", "purpose": "Store archived emails in .eml format", "suggested_path": "~/Spacedrive/Email Archive", "user_selects_path": true } ] } ``` When you write files to this location, Spacedrive indexes them automatically. Query via the core entries table, not a custom cache. ```rust theme={null} // Write file to extension's location let entry = ctx.write_file_to_location( "email_archive", "inbox/email.eml", email_data, ).await?; // Core creates Entry automatically // Query later via core VDFS let emails = ctx.query_entries() .in_location("email_archive") .with_extension("eml") .execute().await?; ``` ### What to Store Where **Database tables:** Domain models, configuration, relationships * EmailAccount, Transaction, Contact * NOT file metadata (use core entries table) **Files:** Original user data in standard formats * .eml files, receipt PDFs, research papers * User chooses where these go * Spacedrive indexes automatically **Sidecars:** Derivative analysis and intelligence * OCR text, embeddings, extracted metadata * Stored in library's sidecar directory * Portable with your library # Examples Source: https://v2.spacedrive.com/extensions/examples ## Example: A Simple CRM Extension To see how the core concepts of the Spacedrive SDK come together, let's look at an example of a simple CRM (Customer Relationship Management) extension. This extension will allow us to manage contacts, companies, and deals. ### 1. Model Definitions First, we define our data models using the `#[model]` attribute. ```rust theme={null} #[model(table_name = "contact")] #[index("email")] pub struct Contact { #[primary_key] pub id: Uuid, pub name: String, pub email: String, #[foreign_key(Company)] pub company_id: Option, #[metadata] pub metadata_id: i32, } #[model(table_name = "company")] pub struct Company { #[primary_key] pub id: Uuid, pub name: String, pub website: Option, #[metadata] pub metadata_id: i32, } #[model(table_name = "deal")] pub struct Deal { #[primary_key] pub id: Uuid, #[foreign_key(Contact)] pub contact_id: Uuid, pub title: String, pub amount: f64, pub stage: String, // e.g., "lead", "negotiation", "closed" #[metadata] pub metadata_id: i32, } ``` This will create three tables in the database: `ext_crm_contact`, `ext_crm_company`, and `ext_crm_deal`, with the appropriate columns, indexes, and foreign keys. ### 2. A Job to Create a Contact Next, we can create a job that adds a new contact to our CRM. ```rust theme={null} #[job] async fn create_contact(ctx: &JobContext, data: CreateContactInput) -> Result { let contact = Contact { id: Uuid::new_v4(), name: data.name, email: data.email, company_id: data.company_id, metadata_id: 0, // Will be auto-created by the core }; // Create the model in the database ctx.vdfs().create_model(contact).await?; // Tag the new contact ctx.vdfs().add_tag_to_model(contact.id, "#new-lead").await?; Ok(contact) } ``` ### 3. A Query to Find Contacts Finally, we can create a query to find contacts, potentially with joins to other tables. ```rust theme={null} #[query] async fn find_contacts( ctx: &JobContext, filters: ContactFilters ) -> Result> { let query = ctx.vdfs() .query_models::() .join::("company_id", "id") .select(&[ "Contact.*", "Company.name as company_name", ]); if let Some(tag) = filters.tag { query = query.with_tag(&tag); } query.collect().await } ``` This simple example demonstrates how you can use the Spacedrive SDK to quickly build powerful, data-driven applications as extensions. With real database tables, automatic sync, and integration with core features like tagging, the possibilities are nearly limitless. # Getting Started Source: https://v2.spacedrive.com/extensions/getting-started ## Setting Up Your Development Environment This guide will walk you through the process of setting up your development environment for building Spacedrive extensions. *This section is a placeholder and will be expanded with detailed instructions on setting up the toolchain, building the SDK, and running your first extension.* ### Prerequisites * Rust 1.81+ * Spacedrive CLI * WASM toolchain (`wasm-pack`) # Introduction to Extensions Source: https://v2.spacedrive.com/extensions/introduction Extensions turn Spacedrive into a platform. Build custom tools for any workflow using Rust, compile to WASM, and integrate seamlessly with Spacedrive's sync, search, and storage infrastructure. Extensions are not plugins that bolt onto the side. They're first-class applications built on Spacedrive's primitives. They get their own database tables, declare their own file storage locations, create AI agents with persistent memory, and appear indistinguishable from core features. The extension system runs in a secure WASM sandbox with fine-grained permissions. Extensions can read and write files, create custom data models, run background jobs, and propose actions—all while staying isolated and safe. ## What You Can Build Extensions can access Spacedrive's full capabilities. Define custom database tables that sync automatically. Create AI agents with unlimited memory. Run durable background jobs. Generate derivative sidecars. Propose file operations with user approval. **Photos Extension:** Face recognition, place identification, automatic albums. Adds "People" to the sidebar, creates face cluster models, generates embedding sidecars. **Email Archive:** IMAP sync to standard .eml files. The user picks where emails go. Spacedrive indexes them automatically. Extension queries via core search, enriches with analysis sidecars. **Ledger:** Receipt OCR, expense tracking, tax prep. Extension creates Transaction models in its database, stores receipt PDFs as files, extracts data to sidecars. The SDK handles sync, search, and indexing. You focus on your domain logic. ## Planned Extensions Spacedrive's WASM-based extension system enables both professional tools and data archival capabilities. Extensions can share models and build on each other's data. ### Professional Extensions Our lineup of industry extensions. | Extension | Purpose | Key Features | Status | | ------------- | ------------------------------- | --------------------------------------------------------------------------- | ----------- | | **Guardian** | Backup & redundancy monitoring | Content identity tracking, zero-redundancy alerts, smart backup suggestions | Planned | | **Photos** | AI-powered photo management | Face recognition, place identification, moments, scene classification | In Progress | | **Chronicle** | Research & knowledge management | Document analysis, knowledge graphs, AI summaries | In Progress | | **Ledger** | Financial intelligence | Receipt OCR, expense tracking, tax preparation | Planned | | **Atlas** | Dynamic CRM & team knowledge | Runtime schemas, contact tracking, deal pipelines | In Progress | | **Cipher** | Security & encryption | Password manager, file encryption, breach alerts | Planned | | **Studio** | Digital asset management | Scene detection, transcription, proxy generation | Planned | ### Open Source Archive Extensions | Extension | Purpose | Provides Data For | Status | | ------------------- | ----------------------- | ------------------------ | ------- | | **Email Archive** | Gmail/Outlook backup | Atlas, Ledger, Chronicle | Planned | | **Chrome History** | Browsing history backup | Chronicle | Planned | | **Spotify Archive** | Listening history | Analytics | Planned | | **GPS Tracker** | Location timeline | Photos, Analytics | Planned | | **Tweet Archive** | Twitter backup | Chronicle, Analytics | Planned | | **GitHub Tracker** | Repository tracking | Chronicle | Planned | # Security and Sync Source: https://v2.spacedrive.com/extensions/security-and-sync ## A Secure and Synchronized Ecosystem Spacedrive extensions are designed to be powerful, but also secure and well-behaved citizens of the user's digital ecosystem. This is achieved through a multi-layered security model and deep integration with Spacedrive's native sync capabilities. ### Migration Security When an extension needs to change its database schema, it does so through a migration system that is carefully controlled by the Spacedrive core. * **SQL Validation**: All migration SQL is parsed and validated before execution. An extension can only modify its own tables (i.e., those prefixed with `ext_{extension_id}_`). * **Restricted Operations**: Extensions are only allowed to perform a specific set of DDL operations (`CREATE TABLE`, `ALTER TABLE`, etc.). Any attempts to modify core tables or other extensions' tables are blocked. * **Sandboxed Execution**: Migrations are run in a restricted database connection that uses an authorizer to enforce these rules at a low level. ### Permission System Extensions must declare their required permissions in their manifest file. Users are prompted to grant these permissions upon installation and can scope them to specific locations in their library. ```json theme={null} { "id": "photos", "permissions": { "tables": { "own": ["ext_photos_*"] "read": ["entries", "content_identities"], "write": [] } } } ``` This ensures that users have full control over what data an extension can access. ### SQL Injection Prevention The SDK's query APIs use prepared statements to prevent SQL injection vulnerabilities. All user-provided input is treated as parameters, not as part of the SQL query itself. ## Extension Model Sync Extension models are first-class participants in Spacedrive's leaderless, hybrid sync system. This means that data created by an extension on one device will automatically sync to all other devices. ### Sync Strategies Spacedrive uses two primary sync strategies, and extensions can choose the appropriate one for each of their models: 1. **State-Based Sync (`device_owned`)**: Used for data that is owned by a single device. Only the owning device can modify the data, and other devices receive read-only copies. This is useful for device-specific state, like the progress of a local analysis job. 2. **Log-Based Sync (`shared`)**: Used for resources that can be modified by any device, such as tags, albums, or a `Person` model. This system uses Hybrid Logical Clocks (HLCs) to order events and resolve conflicts, ensuring eventual consistency across all peers. ### How It Works * **`Syncable` Trait**: The `#[model]` macro automatically implements the `Syncable` trait for your models, which integrates them into the sync system. * **Shared Infrastructure**: Extension models use the same sync infrastructure (database tables and network protocol) as core Spacedrive models. The `model_type` field in the sync log distinguishes between core models and extension models. * **Dependency Resolution**: The sync system can handle dependencies between models. For example, if a `FaceDetection` model depends on a `Person` model, the `Person` model will be synced first. * **Conflict Resolution**: For shared models, conflicts are automatically resolved using HLCs to determine which change came last. Last-write-wins is the default strategy. # UI Integration Source: https://v2.spacedrive.com/extensions/ui-integration ## Extending the Spacedrive Interface Extensions are not limited to background tasks and data processing; they can also add new elements to the Spacedrive user interface. This is done through a `ui_manifest.json` file that is packaged with your extension. This declarative approach allows extensions to add UI components without needing to write any frontend code. The Spacedrive application interprets this manifest and renders the appropriate UI elements. ### `ui_manifest.json` Here is an example of what a `ui_manifest.json` file might look like for a Photos extension: ```json theme={null} { "sidebar_sections": [ { "id": "people", "label": "People", "icon": "assets/people_icon.png", "query": "tags LIKE '#person:%'", "render_type": "list" } ], "views": [ { "id": "places_map", "label": "Places", "component": "map_view", "data_source": "query:exif_gps" } ] } ``` ### Sidebar Sections You can add new sections to the main sidebar in Spacedrive. Each section is defined by: * `id`: A unique identifier for the section. * `label`: The text that will be displayed in the sidebar. * `icon`: The path to an icon to be displayed next to the label. * `query`: A VDFS query that provides the data for this section. * `render_type`: The type of component to use for rendering the data (e.g., `list`, `grid`). ### Views Views are custom UI components that can be displayed in the main content area. They are defined by: * `id`: A unique identifier for the view. * `label`: The title of the view. * `component`: The name of a core-provided component to use for rendering (e.g., `map_view`). * `data_source`: The source of the data for the view, which can be a VDFS query or another data source. By using these declarative UI components, extensions can provide a rich user experience that is consistent with the rest of the Spacedrive application. # Add and Index Locations Source: https://v2.spacedrive.com/overview/add-index-locations Locations connect your existing folders to Spacedrive, making files searchable and organized without moving them. This guide covers adding locations, configuring indexing options, and optimizing performance for different use cases. You'll learn to index everything from small document folders to massive media libraries efficiently. ## Understand Locations A location represents a folder on your device that Spacedrive monitors. Key concepts: **Non-Destructive**: Spacedrive never moves or modifies your original files. It only reads and indexes. **Device-Specific**: Each location belongs to one device. Other devices see the files but can't access the physical path. **Real-Time Monitoring**: Spacedrive watches for changes and updates the index automatically. **Flexible Depth**: Control how deeply Spacedrive analyzes files, from basic names to full content extraction. Locations can be local folders, external drives, or network mounts. Spacedrive treats them equally once indexed. ## Add Your First Location Click the + button next to "Locations" in sidebar or navigate to Settings → Locations. Click "Add Location" and browse to the folder you want to index. Start with something manageable. Set initial options: * **Display Name**: Friendly name shown in sidebar * **Index Mode**: How deeply to analyze (see below) * **Hidden Files**: Include or exclude dot files Click "Add" to begin. Monitor progress in the job manager (bottom status bar). For testing, start with a folder containing \<1,000 files. This indexes quickly and helps you understand the process. ## Indexing Modes Explained Choose the right mode for your needs: ### Shallow Indexing Fastest option capturing basic metadata: * File names and extensions * Size and timestamps * Directory structure * Basic file type detection Use for: * Quick overviews * Temporary folders * Network drives * Initial exploration ### Deep Indexing (Recommended) Comprehensive analysis including: * Everything from shallow mode * Content-based hashing * Thumbnail generation * Media metadata (EXIF, duration) * Text extraction (coming soon) Use for: * Photo libraries * Document archives * Media collections * Permanent storage ### Content Indexing Full text and analysis (future release): * Everything from deep mode * OCR for images * Full text search * AI-powered tagging * Semantic relationships Indexing mode affects initial scan only. You can re-index with different settings later. ## Configure Location Settings Fine-tune each location after adding: Right-click location in sidebar and select "Settings" or click gear icon. Customize what gets indexed: * **File Extensions**: Include/exclude specific types * **Size Limits**: Skip files over certain size * **Path Patterns**: Ignore folders matching patterns * **Date Ranges**: Only index recent files Control real-time monitoring: * **Watch for Changes**: Enable filesystem monitoring * **Watch Frequency**: How often to check (default: instant) * **Process Immediately**: Index new files right away Performance and behavior: * **Priority**: Processing order vs other locations * **Parallelism**: Concurrent file processing * **Thumbnail Size**: Quality vs storage tradeoff ## Index Different Content Types ### Photo Libraries Optimize for image collections: ``` Settings for Photo Location: - Indexing: Deep - Thumbnails: High Quality - Include: *.jpg, *.raw, *.heic - Extract: EXIF metadata - Watch: Enabled ``` Enable "Generate Previews" for instant photo browsing without opening files. ### Document Archives Best practices for documents: ``` Settings for Documents: - Indexing: Deep - Include: *.pdf, *.docx, *.txt - OCR: Enabled (when available) - Versioning: Track changes ``` ### Media Collections Handle video and audio efficiently: ``` Settings for Media: - Indexing: Deep - Thumbnails: First frame - Extract: Duration, codec, resolution - Exclude: *.tmp, *.partial ``` ### Development Projects Index code intelligently: ``` Settings for Code: - Indexing: Shallow - Exclude: node_modules/, .git/, build/ - Include: Source files only - Watch: Enabled for hot reload ``` Avoid indexing package directories like `node_modules`. They contain thousands of files that change frequently. ## Add External Drives Index removable storage: Attach external drive and ensure it mounts properly. Select the drive root or specific folders. Name clearly like "Backup Drive - 4TB". In settings, enable "Offline Mode": * Preserves index when disconnected * Shows files as unavailable * Re-syncs on reconnection Optional: Configure system to auto-mount and index when connected. Spacedrive remembers external drives. Reconnecting automatically updates the index for changes made elsewhere. ## Add Network Locations Index NAS and network shares: Ensure share mounted at OS level: * macOS: Finder → Go → Connect to Server * Windows: Map network drive * Linux: Mount via fstab or GUI Browse to mounted path and add like any folder. Adjust settings for network performance: * Reduce parallelism * Enable caching * Increase timeouts * Shallow index initially Enable offline mode to prevent errors when network unavailable. ## Monitor Indexing Progress Track indexing status effectively: ### Job Manager Access via status bar or `⌘J` / `Ctrl+J`: * Current file being processed * Files completed vs total * Processing speed * Time remaining estimate * Pause/resume controls ### Location Statistics Right-click location → Statistics: ``` Files indexed: 45,234 Total size: 127 GB Last indexed: 2 mins ago Index health: 98% Thumbnails: 12,453 ``` ### System Resources Monitor impact during indexing: * CPU usage (adjustable) * Disk I/O * Memory consumption * Network bandwidth (for remote) Initial indexing runs at full speed. Subsequent updates throttle to avoid system impact. ## Optimize Performance ### Large Libraries (>100k files) Handle massive collections: Add subfolders separately rather than entire directory tree at once. Run initial index during off-hours: ```bash theme={null} sd location add /large/library --schedule "02:00" ``` Reduce concurrent processing for stability: Settings → Location → Advanced → Max Workers: 2 Generate thumbnails after initial index completes. ### Slow Storage Optimize for external/network drives: * Enable read caching * Increase batch sizes * Reduce random access * Use shallow indexing * Process sequentially ### System Impact Minimize resource usage: **CPU Management** * Set process priority to low * Limit worker threads * Enable thermal throttling **Disk I/O** * Reduce concurrent reads * Increase buffer sizes * Schedule during idle **Memory Usage** * Lower thumbnail cache * Reduce preview quality * Clear cache regularly ## Troubleshooting ### Indexing stuck or slow Common causes and solutions: **Corrupted Files** * Check logs for problem files * Exclude problematic paths * Run filesystem check **Permission Issues** * Verify read access * Run as appropriate user * Check security software **Resource Constraints** * Free up disk space * Close other applications * Increase system limits ### Files not appearing Verify files indexed correctly: 1. Check location statistics 2. Confirm indexing completed 3. Try manual rescan 4. Check exclusion rules 5. Verify file permissions ### Duplicates or missing files Fix index inconsistencies: Disable location watching temporarily. Right-click → Advanced → Clear Index (keeps settings). Start fresh index with same settings. Check file count matches filesystem. ## Advanced Location Management ### Location Templates Save configurations for reuse: ``` Photo Import Template: - Deep indexing - High quality thumbs - EXIF extraction - Auto-organization rules ``` Apply templates when adding similar locations. ### Conditional Indexing Index based on rules: ``` Only index if: - Free space > 10GB - System idle > 5 min - On AC power - Network connected ``` ### Location Hierarchies Organize nested locations: ``` Media Library/ ├── Photos/ (Deep index) ├── RAW Files/ (Shallow index) └── Exports/ (Watch only) ``` Each sublocation can have different settings. ### Cross-Device Locations Share location references: While files stay on original device, location metadata syncs so other devices know what exists where. ## Best Practices **Start Small**: Test with small folders before indexing everything. **Name Clearly**: Use descriptive names indicating content and device. **Regular Maintenance**: Re-scan locations monthly to catch any missed changes. **Exclude Wisely**: Prevent indexing temporary files, caches, and system folders. **Monitor Health**: Check location statistics regularly for issues. **Document Settings**: Note why specific settings chosen for future reference. Your locations now integrate seamlessly with Spacedrive, making all your files searchable and organized while preserving your existing structure. Add locations strategically and tune settings for optimal performance. # Back Up Photos from iPhone Source: https://v2.spacedrive.com/overview/backup-photos-ios Spacedrive provides automatic photo backup from your iPhone to any Mac, PC, or NAS you own. Your photos transfer directly between devices using encrypted peer-to-peer connections, keeping them private and under your control. This guide covers setting up photo backup, configuring automatic transfers, and managing your photo library across devices. ## Requirements Before starting, ensure you have: * iPhone running iOS 16 or later * Mac, Windows PC, or Linux machine as backup destination * Both devices on the same WiFi network (for initial setup) * Spacedrive installed on both devices * Sufficient storage space on destination device Photo backup works completely offline after initial pairing. No internet connection required for transfers. ## Install Spacedrive on iPhone Search for "Spacedrive" on the App Store or visit [spacedrive.com/ios](https://spacedrive.com/ios) for a direct link. Launch Spacedrive and grant necessary permissions: * **Photos access** to read your photo library * **Local network** to find and connect to your devices * **Notifications** for backup status updates (optional) Follow the setup wizard to create your library. Choose "Mobile Library" when prompted for library type. Without photo access permission, Spacedrive cannot back up your photos. iOS requires explicit permission for privacy protection. ## Set Up Your Backup Destination Configure the computer where photos will be stored: Launch Spacedrive on your Mac, Windows, or Linux machine. Ensure the daemon is running (check status bar). Navigate to Settings → Locations and add a folder for photo backups. Name it clearly like "iPhone Photos" or "Mobile Backup". In Settings → Network, ensure "Device Discovery" is enabled. This allows your iPhone to find this computer. Create a dedicated folder structure like `/Photos/iPhone/[Year]` for better organization. ## Pair Your Devices Connect your iPhone and computer for secure transfers: In Spacedrive iOS, tap the devices icon and select "Add Device". Your phone begins scanning for nearby Spacedrive instances. Choose your computer from the discovered devices list. If not visible, ensure both devices are on the same network. Confirm the 6-digit code matches on both devices. This ensures you're connecting to the right computer. Give this pairing a friendly name like "John's MacBook" for easy identification. Pairing uses end-to-end encryption. Even on the same network, your photos remain private during transfer. ## Configure Backup Settings Customize how and when photos back up: On iPhone, go to Settings → Photo Backup. Toggle "Enable Photo Backup" to on. Select your paired computer and choose the specific folder created earlier. Configure when backups occur: * **WiFi Only**: Prevents cellular data usage (recommended) * **While Charging**: Runs backups only when plugged in * **Background Backup**: Allows transfers when app is closed Choose what to back up: * Photos (HEIC/JPEG) * Videos * Live Photos * RAW files (if shooting ProRAW) ## Start Your First Backup Tap "Start Backup Now" for immediate transfer or wait for automatic backup based on your conditions. View real-time progress showing: * Photos queued * Transfer speed * Estimated time remaining * Individual file status For initial backup, keep Spacedrive open. Subsequent backups run in background. First backup may take hours depending on library size. A 10,000 photo library typically transfers in 2-4 hours on WiFi. ## Manage Ongoing Backups Spacedrive handles incremental backups intelligently: ### Automatic Detection The app identifies new photos since last backup. Only new items transfer, saving time and bandwidth. ### Duplicate Prevention Content-based deduplication ensures the same photo never backs up twice, even if edited or renamed. ### Conflict Resolution If you organize photos on computer, Spacedrive preserves both versions without overwriting. ### Storage Management Monitor backup status and storage usage: ``` Settings → Photo Backup → Storage Backed up: 15,234 photos Storage used: 45.2 GB Last backup: 2 hours ago Next backup: When charging ``` ## Advanced Configuration ### Multiple Backup Destinations Back up to multiple computers for redundancy: Repeat pairing process with other computers or NAS devices. In Photo Backup settings, enable multiple destinations and set priorities. Select between: * **Mirror**: Same photos on all destinations * **Distribute**: Split photos across devices * **Archive**: Move older photos to specific devices ### Network Optimization Improve transfer speeds: * **5GHz WiFi**: Use 5GHz networks when available for faster speeds * **Direct Connection**: Create device-to-device network for maximum speed * **Quality Settings**: Adjust compression for faster transfers (preserves originals) For fastest initial backup, connect devices to ethernet on same network switch. ### Backup Rules Create smart backup rules: ``` Only backup: - Photos from last 30 days - Favorites marked in Photos app - Photos with faces detected - Media larger than 1MB ``` ## Troubleshooting ### iPhone can't find computer * Verify both devices on same WiFi network * Disable VPNs temporarily * Check firewall allows Spacedrive * Restart both devices ### Backup seems stuck * Check available storage on destination * Verify WiFi connection stable * Force quit and reopen app * Check job manager for errors ### Photos missing after backup * Confirm backup completed (check status) * Verify correct destination folder * Check if filters excluded some photos * Look in Spacedrive's trash for accidents ### Battery draining quickly * Enable "While Charging Only" option * Reduce backup frequency * Lower transfer quality setting * Disable background backup ## Best Practices **Regular Backups**: Enable automatic daily backups while charging overnight. **Verify Backups**: Periodically check destination folder to confirm photos transferred correctly. **Organize Early**: Set up folder structure before accumulating thousands of photos. **Monitor Storage**: Keep 20% free space on destination for smooth operations. **Test Recovery**: Occasionally verify you can access backed-up photos from another device. Photo backup is not a sync service. Deleting photos from iPhone doesn't remove backups. Manage storage separately on each device. ## Next Steps With photo backup configured, explore these features: * **[Manage Your Libraries](/guides/manage-libraries)** - Organize across devices * **[Add and Index Locations](/guides/add-index-locations)** - Include existing photos * **[Search and Tag Photos](/guides/search-tag)** - Organize your collection Your photos now back up automatically and securely to devices you control. No subscriptions, no privacy concerns, just your memories safely preserved. # Get Started with Spacedrive Source: https://v2.spacedrive.com/overview/get-started Spacedrive unifies your files across all devices into one seamless experience. This guide walks you through initial setup and core concepts to get you organizing files in minutes. You'll install Spacedrive, create your first library, and understand how the distributed filesystem works. By the end, you'll have a foundation for managing files across all your devices. ## Install Spacedrive Spacedrive runs as a background service (daemon) with a separate user interface. This architecture enables features like offline sync and multi-device coordination. Visit [spacedrive.com/download](https://github.com/spacedriveapp/spacedrive/releases/tag/v2.0.0-alpha.1) and get the installer for your platform. Spacedrive (v2.0.0-alpha.1) supports macOS and Linux. Windows, iOS, and Android coming in v2.0.0-alpha.2. Follow your platform's standard installation process. On macOS, drag Spacedrive to Applications. On Windows, run the installer. Linux users can use AppImage or package managers. Open Spacedrive from your applications. The daemon starts automatically in the background. You'll see the setup wizard on first launch. The daemon runs separately from the UI. Closing the app window doesn't stop file syncing or background operations. CLI users can set up auto-start with `sd daemon install` on macOS. ## Create Your First Library Libraries organize your files and settings. Think of a library as a unified view of all your data across devices. Pick a descriptive name like "Personal" or "Work". You can create multiple libraries later for different purposes. Spacedrive stores library data in a local database. Choose the default location or pick a custom path with sufficient space. Click "Create Library" to initialize your database. Spacedrive creates the necessary structures for organizing your files. Your library starts empty. Next, you'll add locations to begin organizing files. ## Understand Key Concepts Spacedrive introduces concepts that differ from traditional file managers: ### Libraries A library is your personal database of file information. It stores: * File metadata and organization * Tags and custom attributes * Device relationships * Sync settings Libraries remain local to each device but can sync organizational data between devices you own. ### Locations Locations are folders on your device that Spacedrive monitors. Adding a location indexes its contents into your library without moving files. ### Virtual Filesystem (VDFS) Spacedrive creates a unified view of files across all devices. Files keep their physical location but appear in one searchable interface. ### SD Paths Universal file addresses that work across all storage types. Spacedrive uses three types of paths: * **Physical**: Traditional filesystem paths on local devices (`/Users/jane/Documents/report.pdf`) * **Cloud**: Cloud storage paths for services like S3, Google Drive, or Dropbox (`photos/vacation/beach.jpg`) * **Content**: Content-addressed paths that find files by their content, regardless of location This unified system means you can copy files between your laptop, external drive, and cloud storage using the same commands. ## Navigate the Interface The Spacedrive interface provides powerful tools for file management: **Sidebar** - Switch between libraries, access locations, and view system status. Collapsible for more workspace. **Explorer** - Browse files with list or grid views. Supports columns, sorting, and filtering like traditional file managers. **Inspector** - View and edit file metadata. Add tags, see technical details, and manage file relationships. **Search Bar** - Find files instantly across all indexed locations. Supports filters and advanced queries. **Job Manager** - Monitor background operations like indexing and sync. Access via the status indicator. Use keyboard shortcuts for efficiency. Press `⌘/` (Mac) or `Ctrl+/` (Windows/Linux) to see all available shortcuts. ## Add Your First Location Connect a folder to start organizing files: Click the + button next to "Locations" in the sidebar or go to Settings → Locations. Choose a folder to index. Start with something manageable like Documents or Pictures. Select indexing depth: * **Shallow**: File names and basic metadata only (fastest) * **Deep**: Full content analysis including thumbnails (recommended) Click "Add Location" to begin. Monitor progress in the job manager (status bar). Initial indexing time depends on folder size and depth selected. A folder with 10,000 files typically takes 2-5 minutes for deep indexing. ## Organize with Tags Tags provide flexible organization without moving files: Right-click any file and select "Add Tag" or use Settings → Tags to create tags first. Select multiple files and apply tags in bulk. Tags sync across devices. Click tags in the sidebar to filter your view instantly. Tags support colors and hierarchies for advanced organization. ## Search Across Everything Spacedrive's search works across all indexed locations simultaneously: ``` photo # Find all photos tag:vacation # Files tagged "vacation" size:>10MB # Large files modified:<7d # Changed in last week ``` Search runs locally for privacy. No file data leaves your devices. ## Connect Another Device Expand Spacedrive to multiple devices: Download and install Spacedrive on another computer or mobile device. Use the same account to link devices (coming soon) or set up peer-to-peer pairing. Choose which organizational data to sync. File content remains on original devices. Connected devices share tags, comments, and organization while keeping files in place. ## Next Steps You now have Spacedrive running with your first library and location. Explore these features: * **[Back Up Photos from iPhone](/guides/backup-photos-ios)** - Automatic photo backup * **[Manage Your Libraries](/guides/manage-libraries)** - Multiple library workflows * **[Add and Index Locations](/guides/add-index-locations)** - Advanced indexing options Join our [Discord community](https://discord.gg/spacedrive) for help, tips, and updates on new features. ## Troubleshooting ### Spacedrive won't start * Check if the daemon is running in your system processes * Restart your computer to clear any stuck processes * Reinstall if issues persist ### Indexing seems slow * Start with shallow indexing for large folders * Ensure your disk isn't full * Check job manager for detailed progress ### Can't see files * Verify the location was added successfully * Check if indexing completed in job manager * Ensure you're viewing the correct library Need more help? Visit our [troubleshooting guide](/troubleshooting) or ask in Discord. # Spacedrive - A Historical Chronicle Source: https://v2.spacedrive.com/overview/history ## Table of Contents 1. [Introduction](#introduction) 2. [Origins (2021-2022)](#origins-2021-2022) 3. [Open Source Launch (May 2022)](#open-source-launch-may-2022) 4. [Seed Funding (2022-2023)](#seed-funding-2022-2023) 5. [Technical Architecture V1](#technical-architecture-v1) 6. [Community Growth](#community-growth) 7. [Why V1 Failed](#why-v1-failed) 8. [V2 Rewrite (2025)](#v2-rewrite-2025) 9. [Development Approach](#development-approach) 10. [Lessons Learned](#lessons-learned) 11. [Future Direction](#future-direction) ## Introduction Spacedrive is a cross-platform file manager built to unify file access across devices and cloud services. This document tracks the project's evolution from initial development through its V1 challenges and V2 rewrite. ## Origins (2021-2022) Started in early 2021 as a personal project to solve file fragmentation across devices and cloud services. Core concept: a Virtual Distributed File System (VDFS) that would make device boundaries transparent. Initial goals: * Single interface for all storage locations * Content-addressable file identification * Cross-platform native apps * No vendor lock-in ## Open Source Launch (May 2022) Released on GitHub in May 2022. Reached #1 on GitHub Trending for 3 days, accumulated 10,000+ stars in the first week. The reception indicated the problem resonated with developers managing files across multiple devices and cloud services. ## Seed Funding (2022-2023) Raised \$2M seed round (June 2022) led by OSS Capital. Investors included Naval Ravikant, Guillermo Rauch, Tobias Lütke, Tom Preston-Werner, and others. Team grew to \~12 people working remotely. 100+ open source contributors participated. ## Technical Architecture V1 Built on what we called the "PRRTT stack": * **Prisma** for database ORM * **Rust** for core backend * **React** for UI * **TypeScript** for frontend * **Tauri** for native apps Key features shipped: * SQLite-backed file indexing * Cross-platform support (Windows, macOS, Linux) * Peer-to-peer networking foundation * Content-addressable storage By early 2025: 35,000 GitHub stars, 600,000+ installations. ## Community Growth * 35,000+ GitHub stars by 2025 * 1,100+ forks * 117+ contributors * Active Discord community * Translations in 11 languages ## Why V1 Failed By early 2025, V1 became unmaintainable. The decision to rewrite wasn't driven by perfectionism—the codebase had reached a state where shipping features or fixing bugs was no longer viable. ### Infrastructure Collapse **Prisma deprecation**: The Rust client engine was deprecated, leaving the project on an unmaintained fork with no migration path. Every database interaction depended on infrastructure we could no longer update or fix. **libp2p reliability**: P2P networking was fundamentally broken. File transfers would hang, connections would drop, and debugging was nearly impossible. The networking layer—core to the product vision—couldn't be trusted. **Dependency maintenance**: The team built `prisma-client-rust` and `rspc` out of necessity, then couldn't maintain them. These weren't side projects, they were critical infrastructure that became technical debt. ### Product Limitations **No SDK**: The community couldn't extend functionality. In a file manager where everyone has unique workflows, this was fatal. Users wanted custom integrations but had no way to build them. **No CLI**: Automated workflows and scripting were impossible. Power users—the core audience—couldn't integrate Spacedrive into their existing tooling. **Incomplete search**: Despite positioning as a search-focused tool, only basic SQL `LIKE` queries worked. No full-text indexing, no content search, no semantic search. The core value proposition was half-built. ### Development Velocity Collapse **No integration tests**: Rapid prototyping without full integration testing meant every release broke something. Manual testing couldn't scale, and regressions were constant. **Job system boilerplate**: Adding any file operation required 500-1000+ lines of boilerplate. Simple features took weeks to implement, making iteration impossible. **Poor modularity**: Refactors that developers knew were necessary couldn't be completed. The interconnected layers meant touching one thing broke three others. Technical debt compounded faster than it could be paid down. **Incomplete migrations**: The codebase had `old_*` files still in active use alongside new systems. Every migration stalled partway through, leaving the codebase in a perpetual transition state. ### Architecture Dead Ends **Dual file systems**: Two incompatible systems (indexed database files vs. ephemeral filesystem access) made basic operations like copying between locations impossible. Every file operation needed two implementations, and they'd drift out of sync. **Sync confusion**: Complex CRDTs built on top of Prisma with unclear boundaries between local and shared data. The team couldn't decide what should sync and what shouldn't, so the implementation was never finished. **Query invalidation**: Backend code contained hardcoded frontend cache keys (`invalidate_query!(library, "search.paths")`), creating tight coupling that made refactoring impossible. ### Business Model Misalignment **Cloud focus**: Development prioritized a cloud revenue model with high overhead, low margins, and questionable alignment with the core product. Resources went toward infrastructure that didn't serve users or validate product-market fit. (V2 pivots to premium extensions following the COSS model.) ### Process Breakdown **Slow release cycles**: Inefficient project management meant features took months to ship. Community momentum stalled. **Delayed refactors**: Developers knew what needed to be fixed, but priorities kept shifting. Technical debt accumulated while the team chased features. **No AI tooling**: The complexity required to work across the stack didn't have the AI assistance available today. What would now take hours took weeks. ### V1 as Necessary R\&D V1's apparent failure was actually essential research. The team pioneered a cross-platform file manager with P2P networking and content-addressable storage—problems with no existing solutions. Every architectural mistake taught us what not to do. Every incomplete migration revealed where boundaries should exist. Every performance bottleneck showed us where to optimize. Without V1, we'd have no idea how to build V2. The technical achievements—SQLite-backed indexing, cross-platform support, content-addressable storage—proved the core concepts worked. The failures showed us how to structure them properly. The rewrite wasn't a failure of the team. It was the natural outcome of exploring genuinely hard problems without a map. ## V2 Rewrite (2025) V2 has been rebuilt by the founder using AI-accelerated development, systematically addressing every failure from V1. Each architectural decision directly solves a specific problem that made V1 unmaintainable. ### Infrastructure: No More Deprecated Dependencies **Problem**: Prisma Rust deprecated, libp2p unreliable, custom infrastructure becoming debt. **Solution**: * Replaced Prisma with **SeaORM** - actively maintained ORM * Replaced libp2p with **Iroh** - purpose-built for reliable P2P with QUIC transport and NAT traversal that actually works * Moved away from custom infrastructure where possible ### Product: SDK, CLI, and Real Search **Problem**: No SDK meant community couldn't extend. No CLI meant no automation. Search was SQL `LIKE` queries. **Solution**: * **WASM Extension System** with complete Rust SDK - extensions are first-class, sandboxed, and can define their own data models * **Production CLI** (`sd-cli`) for library management, indexing, and automation * **FTS5 full-text search** with semantic re-ranking - sub-100ms queries on 1M+ files Launch extensions (Chronicle for research, Cipher for passwords, Atlas for CRM, Ledger for finances) prove the SDK works. ### Development Velocity: Eliminated Boilerplate **Problem**: 500-1000+ lines of boilerplate per file operation. No integration tests. Poor modularity made refactors impossible. **Solution**: * **Procedural macros** for job system - reduced to \~50 lines per job (95% reduction) * **Entry-centric model** - files and directories unified, eliminating dual implementations * **Integration test suite** - every major operation has tests that run against real SQLite * **Clear domain boundaries** - each module (location, library, volume, sync) is independent Development speed increased 10x. Adding new file operations went from weeks to hours. ### Architecture: Solved the Dual File System Problem **Problem**: Indexed files vs. ephemeral files created two incompatible worlds. Copying between them was impossible. **Solution**: **Universal `SdPath` addressing** ```rust theme={null} pub enum SdPath { Physical { device_id: Uuid, path: PathBuf }, Cloud { volume_id: Uuid, path: String }, Content { content_id: Uuid }, } ``` Every file in Spacedrive—indexed or not, local, cloud, or remote—has a single address. Operations work uniformly across all storage. Device and cloud boundaries disappeared. ### Sync: Domain Separation That Works **Problem**: Custom CRDT implementation never finished. Unclear boundaries between local and shared data. **Solution**: **Domain-separated sync with HLC timestamps** Instead of trying to sync everything, V2 defines clear boundaries: * **Shared**: Library metadata, tags, device list * **Local-only**: Volume mounts, locations, indexing state Leaderless P2P synchronization using Hybrid Logical Clocks. No coordination required, no consensus algorithms. It just works offline. ### Coupling: Event-Driven Architecture **Problem**: Backend code had hardcoded frontend cache keys (`invalidate_query!`). Tight coupling made changes impossible. **Solution**: **EventBus with domain events** Components publish events (`EntryCreated`, `LocationIndexed`, `SyncCompleted`). Subscribers react independently. Backend has zero knowledge of frontend caching. This eliminated cross-layer coupling entirely. ### Business Model: COSS Over Cloud **Problem**: Cloud revenue model with high overhead, low margins, misaligned with product. **Solution**: **Commercial Open Source Software (COSS) model** * Core file manager: free forever * Premium extensions (Photos, Chronicle, Guardian, Studio): paid * Self-hostable: no forced cloud dependency * Team/enterprise features: paid tiers Revenue aligns with value delivered. Resources go toward features users want, not cloud infrastructure. ### Actions: Preview Before Commit **Problem**: File operations were destructive and unpredictable. **Solution**: **Transactional action system** Every destructive operation follows preview-commit-verify flow: 1. Simulate the operation 2. Show user exact changes 3. Execute only on approval 4. Verify completion Conflicts are caught before execution. Users always know what will happen. ### Performance: Production-Ready Metrics V2 isn't just architecturally sound—it's fast: * **8,500 files/second** indexing (multi-phase resumable pipeline) * **\~55ms search** on 1M entries (FTS5 with semantic re-ranking) * **\~150MB memory** for 1M files (efficient SQLite schema) * **110 MB/s P2P transfers** (Iroh with QUIC transport) Enterprise capabilities running on consumer hardware. ## Development Approach Spacedrive’s rewrite from scratch, despite limited resources, was made feasible by advancements in AI-driven code generation for Rust in 2025. Tools like Claude 3.5 Opus, GPT-5, and Gemini’s expansive context window enabled translating detailed specifications into robust implementations across the entire codebase. The workflow centered on iteratively refining specs and test cases, ensuring implementations adhered to strict code style guidelines and passed all tests. This AI-accelerated, spec-first, test-driven approach enabled rapid development with a single-person team. **Why this worked:** The codebase prioritizes simplicity and structure over complexity. Domains—library, location, volume, sync, and networking are organized into isolated modules with well-defined boundaries. Documentation supports every layer, inline comments detail execution, and integration tests validate behavior. The original team established core concepts: file system abstractions, job system architecture, and sync protocol design. This rewrite leveraged these foundations but swapped much of the custom infrastructure for reliable, community-maintained tools. ## Lessons Learned 1. **User experience drives architecture** - Implementation details shouldn't leak into UX (dual file systems) 2. **Ship simple first** - Basic solutions are better than perfect ones that never ship 3. **Maintain what you create** - Don't create infrastructure you can't support long-term 4. **Reduce boilerplate** - Developer friction directly impacts iteration speed 5. **Deliver on core promises** - Search was a key value prop but remained weak 6. **One concept, one implementation** - Multiple representations of the same thing create confusion 7. **Complete migrations** - Don't start new ones until old systems are removed 8. **Loose coupling** - Event-driven beats direct dependencies 9. **Decide and move** - Imperfect decisions beat analysis paralysis 10. **Maintain momentum** - Regular releases keep community engaged ## Future Direction Near-term: * Production release of V2 * Mobile apps (iOS, Android) * Developer SDK * Extension ecosystem Long-term business model: * Free for individual use * Paid extensions * Team collaboration features * Enterprise security/compliance * Optional cloud services The core principle remains: files shouldn't be stuck in device ecosystems. Open source technology ensures users retain control over their data. *** *Development continues at [github.com/spacedriveapp/spacedrive](https://github.com/spacedriveapp/spacedrive)* # Welcome to Spacedrive Source: https://v2.spacedrive.com/overview/introduction Infrastructure for multi-device computing **v2.0.0-alpha.1 Released: December 26, 2025** The complete ground-up rewrite is here. This is an alpha release for testing and feedback. macOS and Linux are supported now. Windows support coming in alpha.2. Read the [full release notes](https://github.com/spacedriveapp/spacedrive/releases) for more details on the rewrite. ## What is Spacedrive? Spacedrive is a local-first file manager that unifies data across devices without centralized cloud services. Files stay where they are. Spacedrive creates a content-aware index that makes them searchable, syncable, and manageable from anywhere. Spacedrive column view file explorer ## Why Spacedrive Exists Computing was designed for single devices. File managers like Finder and Explorer assume your data lives on the computer in front of you. The shift to multi-device forced us into cloud ecosystems. Convenience required giving up data ownership. AI is accelerating this trend. Cloud services offer semantic search and intelligent analysis, but only if you upload your files to their infrastructure. Spacedrive is building the architecture for local AI on hardware you already own, on data that never leaves your control. This is infrastructure for the next era of computing. ## Current State ### What Works Now (v2.0.0-alpha.1) **Core Infrastructure** * Daemon-client architecture with persistent background operations * Tauri desktop app with working interface * CLI with full library, location, job, and network management * Resumable job system with checkpointing and progress tracking **Multi-Device Sync** * Peer-to-peer library sync via Iroh/QUIC with NAT traversal * Device pairing with BIP39 mnemonic codes * Local network discovery (mDNS) and relay fallback * Leaderless sync using Hybrid Logical Clocks (no central server) * Device-owned data (locations, files) and shared resources (tags, collections) * Incremental sync with watermarks for offline periods **File Management** * File indexing with shallow, content, and deep modes * Content identity and deduplication across devices * Unified addressing: `local://`, `s3://`, `content://` URIs * Copy/move operations with atomic and streaming strategies * Checksum verification and progress tracking **Cloud Storage** * Integration via OpenDAL (40+ services supported) * S3, Google Drive, OneDrive, Dropbox, Azure Blob, GCS * Cloud files indexed and searchable like local files * Cross-storage operations (local to cloud, cloud to cloud) **Media & Analysis** * Thumbnail generation * OCR text extraction * Speech transcription * Sampled content hashing (58KB identifies any file size) **Organization** * Semantic tagging with hierarchies and polymorphic naming * Spaces for custom workspace layouts * Collections for grouping files **Security** * Ed25519 device identity with session key derivation * XChaCha20-Poly1305 credential encryption * OS keyring integration (Keychain, Credential Manager, Secret Service) **Platform Support** * macOS: Fully supported * Linux: Fully supported * Windows: Coming in alpha.2 * iOS & Android: Coming soon ### Coming Soon * **alpha.2**: Windows support * **Future releases**: * iOS app * Android app * Server edition for headless deployments * Extension SDK (stable API) * AI integration with local models ### Prototypes (Not Public) Native Swift apps (iOS, macOS) and a GPUI media viewer exist as private prototypes. These demonstrate type-safe native integration and platform-specific optimizations. They may become production apps if performance demands it. ## How It Works Spacedrive treats files as first-class objects with content identity. A photo on your laptop and the same photo on your NAS are recognized as one piece of content. **Core capabilities:** * Search millions of files in under 100ms * Preview operations before execution (conflicts, space savings, outcomes) * Sync peer-to-peer without servers or consensus protocols * Track redundancy across devices * Full offline functionality Files stay in place. Spacedrive makes them universally addressable with rich metadata. ## Testing & Feedback This is an alpha release. We need community help validating: * macOS and Linux stability * v1 to v2 library migration * Multi-device sync scenarios * Performance at scale macOS and Linux users: Test indexing, multi-device sync, and cloud integration. Report bugs on GitHub or Discord. All feedback helps improve stability for the beta release. ## For Developers **Most architecture docs are in the Developer section.** The core technical documentation lives under [Architecture](/core/architecture), not in overview guides. Key technical docs: * [Architecture Overview](/core/architecture) - System design and principles * [Data Model](/core/data-model) - How data is structured * [Content Addressing](/core/addressing) - Content identity system * [Library Sync](/core/library-sync) - Multi-device synchronization * [Testing Guide](/core/testing) - Test framework and patterns ## Roadmap The `.tasks` folder in the repo tracks core development work. Check the [releases page](https://github.com/spacedriveapp/spacedrive/releases) for the public roadmap. These docs provide detailed technical reference. Some guides document planned features that aren't in alpha.1 yet. When features aren't ready, you'll see callouts indicating their status. ## Project Timeline Spacedrive v2 development began in June 2025. This is a ground-up rewrite addressing lessons from the v1 alpha. The architecture is designed for long-term sustainability, not quick feature delivery. v2.0.0-alpha.1 released December 26, 2025 after six months of development. This alpha provides the core infrastructure for multi-device file management. Additional platforms and features will roll out in subsequent releases. ## Screenshots
Column view - File explorer interface Video player Grid view - Browse files in a grid layout Media view - Gallery and media browsing Size view - Visualize storage usage 3D Gaussian Splat viewer
## Get Involved * **Test the code** - Build from source, report bugs, validate cross-platform * **Join Discord** - [discord.gg/gTaF2Z44f5](https://discord.gg/gTaF2Z44f5) * **Read the whitepaper** - [whitepaper/spacedrive.pdf](https://github.com/spacedriveapp/spacedrive/blob/main/whitepaper/spacedrive.pdf) (work in progress) * **Explore architecture docs** - Start with [core/architecture](/core/architecture) This is a living document. As development progresses through alpha and beta releases, this page will be updated to reflect current status. # Manage Your Libraries Source: https://v2.spacedrive.com/overview/manage-libraries Libraries in Spacedrive organize your digital life into separate, manageable collections. Create libraries for different purposes, sync settings between devices, and maintain clean separation between personal and work files. This guide explains library management from basic operations to advanced multi-library workflows. ## Understand Libraries A library is your personal file database containing: * Indexed file metadata and thumbnails * Tags, comments, and custom organization * Location mappings and folder relationships * Device pairings and sync settings * Job history and statistics Libraries exist independently. Files in one library remain completely separate from others, ensuring privacy and organization. ## Create Additional Libraries Beyond your first library, create specialized collections: Click the library name in the top bar or press `⌘L` (Mac) / `Ctrl+L` (Windows/Linux). Choose "Create New Library" from the dropdown menu. Name your library and optionally: * Set custom storage location * Choose encryption settings * Configure default indexing rules Click "Create" to build the database structure. Spacedrive switches to the new library automatically. Each library maintains its own database file. Default location: `~/Library/Application Support/spacedrive/libraries/` on macOS. ## Switch Between Libraries Navigate multiple libraries efficiently: ### Quick Switch Press `⌘L` / `Ctrl+L` to open the library switcher. Recent libraries appear at top. ### Keyboard Navigation Use number keys `1-9` to switch to libraries by position in the list. ### Set Default Library Right-click a library in the switcher and select "Set as Default". This library opens on app launch. Pin frequently used libraries to the top of the switcher for faster access. ## Library Settings Customize each library independently: Navigate to Settings → Library or press `⌘,` / `Ctrl+,` then select Library tab. Configure basic options: * **Name**: Update library display name * **Description**: Add notes about library purpose * **Storage Path**: View database location * **Statistics**: See total files, size, and devices Control library privacy: * **Encryption**: Enable database encryption * **Network Visibility**: Hide from network discovery * **Sync Permissions**: Limit which devices can sync Fine-tune behavior: * **Indexing Rules**: Default settings for new locations * **Thumbnail Quality**: Balance quality vs storage * **Job Concurrency**: Parallel processing limits ## Common Library Patterns ### Work/Personal Separation Create distinct libraries for different aspects of life: **Work Library** * Project files and documents * Client assets * Meeting recordings * Professional photos **Personal Library** * Family photos and videos * Personal documents * Entertainment media * Hobby projects Libraries cannot share files directly. Use separate locations if you need files accessible from multiple libraries. ### Project-Based Libraries Organize major projects independently: ``` Film Project Library ├── Raw Footage (Location) ├── Audio Files (Location) ├── Project Files (Location) └── Exports (Location) ``` Benefits: * Archive entire project when complete * Share library with collaborators * Prevent accidental cross-contamination ### Device-Specific Libraries Optimize for different device types: **Mobile Library** - Lightweight for phones/tablets * Photos and screenshots only * Minimal processing rules * Reduced thumbnail sizes **Desktop Library** - Full features for computers * All file types indexed * Maximum quality thumbnails * Advanced processing enabled ## Sync Libraries Between Devices Share organizational data across your devices: In Library Settings, toggle "Enable Sync" and note the Library ID displayed. On another device, choose "Join Existing Library" and enter the Library ID. Confirm device pairing using the security code shown on both screens. Choose what syncs: * **Metadata Only**: Tags, comments (default) * **Organization**: Folder structures * **Settings**: Library preferences * **Locations**: Folder mappings (advanced) Sync only shares organizational data. Actual files remain on their original devices unless explicitly transferred. ### Sync Behavior Understanding sync helps avoid confusion: **Immediate Sync** * Tags and labels * File relationships * Custom metadata **Device-Specific** * Location paths * Indexing progress * Local preferences **Never Synced** * Actual file contents * Temporary data * Job history ## Back Up Libraries Protect your organizational work: Find your library file: * macOS: `~/Library/Application Support/spacedrive/libraries/[id]/library.db` * Windows: `%APPDATA%\spacedrive\libraries\[id]\library.db` * Linux: `~/.config/spacedrive/libraries/[id]/library.db` Copy the entire library folder to backup location. Include all `.db` files and thumbnails directory. Set up automated backups using: * Time Machine (macOS) * File History (Windows) * rsync scripts (Linux) * Cloud backup services Name backup files with date stamps: `library-personal-2024-01-15.db` ## Restore Libraries Recover from backups when needed: Quit the app completely. Ensure daemon stops. Copy backup files to the library directory, overwriting existing files. Launch app. The restored library appears in the switcher. Check recent files and tags to confirm successful restore. ## Delete Libraries Remove unwanted libraries cleanly: Ensure you're not currently using the library to delete. Access via Settings → Libraries → Manage. Choose the library and click "Delete Library". Type the library name to confirm. This permanently removes: * Database files * Thumbnails * Organizational data * Sync relationships Library deletion cannot be undone. Back up important libraries before deleting. ## Troubleshooting ### Library won't open * Check disk space for database * Verify file permissions * Try recovery mode (hold Shift on launch) * Restore from backup if corrupted ### Sync not working * Confirm both devices online * Check Library IDs match * Verify network connectivity * Re-pair devices if needed ### Performance issues * Reduce thumbnail quality * Limit concurrent jobs * Archive old data * Split large libraries ### Missing locations * Locations are device-specific * Re-add locations after sync * Check paths still exist * Verify permissions ## Advanced Library Management ### Library Templates Create template libraries for repeated setups: ``` Photo Workshop Template ├── RAW Import (Location preset) ├── Working Files (Location preset) ├── Client Delivery (Location preset) └── Archive (Location preset) ``` Export and import library configurations without data. ### Multi-User Libraries Share libraries safely: **Read-Only Access** - Others can view but not modify **Contributor Access** - Add files and tags **Admin Access** - Full control including settings Multi-user features require Spacedrive Cloud (coming soon) or self-hosted server. ### Library Analytics Monitor library usage: * File type distribution * Growth over time * Most active locations * Tag usage patterns * Device contribution Access analytics in Settings → Library → Statistics. ## Best Practices **Name Clearly**: Use descriptive names indicating purpose or content type. **Regular Backups**: Automate weekly backups of important libraries. **Prune Regularly**: Remove unused locations and clean up old jobs. **Document Purpose**: Add descriptions explaining library organization. **Test Sync**: Verify sync works before relying on it. Your libraries now provide organized, separate spaces for different aspects of your digital life. Each library maintains its independence while enabling powerful organization features. # The Spacedrive Philosophy Source: https://v2.spacedrive.com/overview/philosophy Spacedrive is more than a file manager; it is a paradigm shift in how humans interact with their digital assets. It was born from the universal frustration of "data fragmentation hell"—a state where our digital lives are scattered across countless devices and incompatible cloud services. Our mission is to create a unified, content-aware ecosystem that gives users complete control over their data. The V2 architecture is the realization of this vision, built on a set of core principles that guide every design decision, line of code, and future feature. *** ## The Core Tenets ### 1. The User is Sovereign This is our most fundamental principle. In the Spacedrive ecosystem, you are in complete control. * **Local-First by Default**: Spacedrive is designed to work entirely offline. All indexing, analysis, and processing happen on your devices, ensuring your data and your privacy remain yours alone. * **You Own Your Data, Always**: We built Spacedrive as an intelligent layer that sits *on top* of your existing storage. Your files stay where they are, in their original locations, with zero vendor lock-in. Backing up your entire organizational system is as simple as copying a single directory. * **Human in the Loop**: The user is the final authority. AI agents and automation systems are designed to *propose* actions, which are then presented in a clear, previewable format for you to approve. You are always in command. ### 2. From Chaos to Cohesion We aim to solve the universal problem of file chaos by creating a single, unified view of your entire digital world. * **A Unified Virtual Layer**: The Virtual Distributed File System (VDFS) creates one interface to manage files across all devices and clouds. It makes scattered storage feel like a single, cohesive library. * **Content is King**: We move beyond rigid, location-based folder hierarchies to a content-aware model. Through Content-Addressed Storage (CAS), Spacedrive understands what a file *is*, not just where it is, enabling powerful features like global deduplication and data integrity verification. * **Location Transparency**: Our universal addressing system, `SdPath`, makes device boundaries disappear. A file on your offline laptop is as accessible as one on your local NAS, as the system can intelligently find and use any available copy. ### 3. Intelligence as Augmentation AI is not a bolted-on feature; it is a foundational, **but optional** element of the architecture, designed to enhance your capabilities without compromising your control. * **The AI Data Guardian**: With the official Guardian extension Spacedrive acts as a proactive protector of your data. By tracking file redundancy, it can identify irreplaceable memories that exist in only one location and suggest creating a backup before disaster strikes. * **Natural Language as a Command Line**: You can manage your files by simply stating your intent. The system translates commands like "find my design assets from last fall" into safe, verifiable, and previewable actions. * **Privacy-Preserving Intelligence**: We believe you shouldn't have to trade privacy for intelligence. Spacedrive is built to run powerful AI models locally on your hardware via tools like Ollama, ensuring your file contents are never sent to the cloud unless you explicitly choose to. ### 4. Pragmatism in Engineering The failure of Spacedrive V1 taught us a critical lesson: perfect is the enemy of good. The V2 architecture embodies a pragmatic approach focused on delivering value and reliability. * **Simplicity over Complexity**: We replace over-engineered solutions with simpler, more robust patterns. V2's domain-separated sync avoids the "analysis paralysis" of a custom CRDT implementation, allowing us to ship a reliable sync system. * **Developer Experience Matters**: We ruthlessly reduce boilerplate. The V2 job system, for example, cuts the code needed to add a new background operation by over 90%, enabling us to build and iterate faster. * **Power for Everyone**: We engineer enterprise-grade capabilities to run efficiently on consumer hardware. Sophisticated features like semantic search, cross-device deduplication, and transactional operations are made accessible to everyone, not just large organizations. ### 5. Open by Default Trust is earned through transparency. Our commitment to open source is a core part of our identity. * **Open Source for Control**: Spacedrive is open source to guarantee that you always retain absolute control over the software that manages your most important data. * **Community as a Partner**: The project's success is tied to our community. The V2 whitepaper and architecture are a definitive technical blueprint, inviting developers to review, contribute, and help build the future of file management with us. * **A Sustainable Vision**: We use a sustainable Open Core model. The core product is free for individuals, with paid features for teams and enterprises that ensure the project's long-term health and development. ### 6. A New Way to Build The story of V2's creation is a meta-philosophy in itself. It demonstrates a revolutionary new paradigm for software development. * **The AI-Augmented Team**: Spacedrive V2 was rebuilt from the ground up by a single developer orchestrating a suite of specialized AI assistants. This approach proved to be 100x faster and more effective than a traditional team. * **Radical Capital Efficiency**: This new development model changes the economics of building software. It allows capital to be invested in growth, security, and infrastructure instead of being consumed by large team salaries. * **Elite, Focused Teams**: Our hiring philosophy is to automate first and hire only the best humans for roles that require strategic impact. We believe small, focused, high-impact teams build better products. *** These principles are woven into every aspect of Spacedrive. They are the reason we believe we can solve the fundamental problems of data fragmentation, privacy, and intelligent management for the AI era. # Self-Hosting Spacedrive Source: https://v2.spacedrive.com/overview/self-hosting Deploy Spacedrive server for remote access and headless operation Self-hosting Spacedrive means running the server component on hardware you control. The server provides HTTP access to your libraries, enabling remote connections from desktop and mobile apps. Unlike the desktop app which requires a GUI, the server runs headless on Linux systems, NAS devices, or cloud instances. The server embeds the full Spacedrive daemon with media processing capabilities. It exposes RPC endpoints over HTTP with optional basic authentication. Your data stays on your infrastructure while remaining accessible from any device with network access. ## Installation Methods ### Static Binary Download the latest release binary for your platform. This method works on any Linux system and requires no container runtime. ```bash theme={null} # Download and extract wget https://github.com/spacedriveapp/spacedrive/releases/latest/download/sd-server-linux-x86_64.tar.gz tar -xzf sd-server-linux-x86_64.tar.gz # Verify checksum sha256sum -c sd-server-linux-x86_64.sha256 # Install to system sudo mv sd-server-linux-x86_64 /usr/local/bin/sd-server sudo chmod +x /usr/local/bin/sd-server ``` For ARM systems like Raspberry Pi, use `sd-server-linux-aarch64.tar.gz` instead. ### Docker Deployment Docker images are available for both x86\_64 and ARM64 architectures. The image includes all media processing dependencies and runs as a non-root user. ```bash theme={null} docker run -d \ --name spacedrive \ -p 8080:8080 \ -p 7373:7373 \ -v spacedrive-data:/data \ -e SD_AUTH=admin:your-secure-password \ ghcr.io/spacedriveapp/spacedrive/server:latest ``` The server listens on port 8080 for HTTP traffic and port 7373 for peer-to-peer connections. Mount additional volumes to index existing storage. ### Docker Compose For production deployments, use the provided compose file in the repository at `apps/server/docker-compose.yml`. This includes health checks and restart policies. ```yaml theme={null} version: '3.8' services: spacedrive: image: ghcr.io/spacedriveapp/spacedrive/server:latest ports: - "8080:8080" - "7373:7373" volumes: - spacedrive-data:/data - /mnt/media:/media:ro environment: SD_AUTH: "admin:your-password" TZ: "America/New_York" restart: unless-stopped volumes: spacedrive-data: ``` ## System Service Setup Running the server as a systemd service ensures it starts on boot and restarts on failure. Create a service file at `/etc/systemd/system/spacedrive.service`: ```ini theme={null} [Unit] Description=Spacedrive Server After=network.target [Service] Type=simple User=spacedrive Group=spacedrive Environment="DATA_DIR=/var/lib/spacedrive" Environment="SD_AUTH=admin:your-secure-password" ExecStart=/usr/local/bin/sd-server --data-dir /var/lib/spacedrive Restart=on-failure RestartSec=5s [Install] WantedBy=multi-user.target ``` Create the user and data directory, then enable the service: ```bash theme={null} sudo useradd -r -s /bin/false spacedrive sudo mkdir -p /var/lib/spacedrive sudo chown spacedrive:spacedrive /var/lib/spacedrive sudo systemctl enable --now spacedrive ``` Check status with `sudo systemctl status spacedrive`. ## Configuration The server accepts configuration via environment variables or command-line flags. **Authentication** is controlled by `SD_AUTH`. The format supports multiple users separated by commas: `user1:pass1,user2:pass2`. Set to `disabled` to disable authentication, though this is not recommended for network-accessible deployments. **Data directory** defaults to `/data` in Docker or a temporary directory in development. In production, always set `DATA_DIR` to a persistent location. The server creates library databases, thumbnails, and logs in this directory. **Port configuration** defaults to 8080. Change with `--port` flag or `PORT` environment variable. The P2P port (7373) is fixed and required for device sync. Production deployments must set `SD_AUTH`. The server refuses to start without authentication unless explicitly disabled. This prevents accidental exposure of your libraries. ## Network Access The server binds to all interfaces by default, making it accessible on your local network. For internet access, place it behind a reverse proxy with TLS termination. ### Nginx Example ```nginx theme={null} server { listen 443 ssl http2; server_name spacedrive.example.com; ssl_certificate /etc/letsencrypt/live/spacedrive.example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/spacedrive.example.com/privkey.pem; location / { proxy_pass http://localhost:8080; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } ``` ### Caddy Example Caddy handles TLS automatically with Let's Encrypt: ``` spacedrive.example.com { reverse_proxy localhost:8080 } ``` ## NAS Deployment Network-attached storage devices are ideal for Spacedrive server. The server indexes existing media while providing remote access. ### TrueNAS SCALE Install via the Apps interface using Docker. Map your pools as read-only volumes to prevent accidental modification during indexing. ```yaml theme={null} volumes: - /mnt/pool1/photos:/photos:ro - /mnt/pool1/videos:/videos:ro - /mnt/pool2/documents:/documents:ro ``` After deployment, create locations in Spacedrive pointing to these mount points. The server indexes files without moving them. ### Synology NAS Use Container Manager to deploy the Docker image. Configure port forwarding and volume mounts through the UI. Ensure the container has read access to your shared folders. ### Unraid Add a custom container template with the image `ghcr.io/spacedriveapp/spacedrive/server:latest`. Map your shares as additional paths in the container configuration. ## Storage Considerations The server creates three types of data in the data directory: **Libraries** contain SQLite databases with file indexes, tags, and metadata. Each library is a separate `.sdlibrary` directory. These are small, typically under 100MB even for millions of files. **Sidecars** include thumbnails, previews, and extracted text. Size depends on media processing settings. Budget 1-5% of your total media size for thumbnails. **Logs** rotate automatically but can grow large during initial indexing. The server keeps the last 10 log files, typically under 100MB total. Plan for library growth over time. A library indexing 1 million files uses approximately 500MB for the database and 10-50GB for sidecars, depending on media density. The server never modifies your original files. Indexing is read-only. File operations like copy and move require explicit user action through connected clients. ## Security Best Practices Self-hosted servers face different threats than desktop apps. Follow these guidelines for secure deployment. **Always use authentication** when the server is network-accessible. HTTP basic auth is sufficient for home networks but consider stronger methods for internet-facing deployments. **Enable TLS** for any internet access. Let's Encrypt provides free certificates through Caddy, Nginx, or Traefik. The server itself does not handle TLS, rely on reverse proxies. **Limit exposure** with firewall rules. Only open port 8080 to trusted networks or VPN connections. The P2P port (7373) requires UDP ingress for device sync but can be restricted to known peers. **Run as non-root** user. The Docker image and systemd example both use dedicated users with minimal permissions. Never run the server as root. **Regular backups** of the data directory protect against corruption. The SQLite databases can be backed up while running using the `.backup` command or by copying the entire data directory when the server is stopped. ## Connecting Clients Desktop and mobile apps can connect to self-hosted servers by configuring the server URL in settings. The URL format is `http://your-server:8080` or `https://spacedrive.example.com` if using a reverse proxy. Clients authenticate using credentials set in `SD_AUTH`. P2P sync works between the server and other devices without additional configuration. The server appears as a device in your library and participates in sync like any other device. ## Monitoring The server provides a health check endpoint at `/health` that returns HTTP 200 when operational. Use this for monitoring tools or container orchestration health probes. Logs are written to stdout and the data directory under `logs/`. Set `RUST_LOG` environment variable to `debug` for detailed output during troubleshooting. **Key metrics to monitor:** Disk usage in the data directory grows with library size. Alert when free space drops below 20% to prevent database corruption. Memory usage typically ranges from 100-500MB depending on active jobs. Spike during intensive operations like thumbnail generation. Network bandwidth peaks during initial sync with new devices. Ongoing sync uses minimal bandwidth after the first synchronization. ## Troubleshooting **Server won't start:** Check that the data directory exists and is writable by the server user. Verify no other process is using port 8080 with `lsof -i :8080`. Review logs for specific errors. **Authentication failures:** Ensure `SD_AUTH` format is correct. Test credentials with curl: `curl -u admin:password http://localhost:8080/health`. Browser authentication dialogs require exact username and password. **Clients can't connect:** Verify the server is accessible from the client network. Test with `curl http://server-ip:8080/health`. Check firewall rules on both server and client networks. Ensure reverse proxy configuration preserves authentication headers. **Media processing fails:** The server requires FFmpeg and libheif for video thumbnails and HEIF images. Docker images include these by default. Binary installations on minimal systems may need manual installation of these libraries. **Sync not working:** UDP port 7373 must be accessible for P2P connections. Check NAT and firewall rules. The server attempts hole-punching for NAT traversal but may fall back to relay servers if direct connection fails. ## Performance Tuning The server handles multiple concurrent operations through the job system. Performance depends on storage speed, available memory, and indexing load. **Indexing performance** is limited by storage I/O. SSDs provide 10-50x faster indexing than spinning disks. Network storage over gigabit ethernet typically indexes at 50-100MB/s for metadata reads. **Thumbnail generation** is CPU-bound. Disable thumbnail generation for video files if CPU usage is a concern. Image thumbnails are fast but video processing can use significant resources. **Database optimization** happens automatically through SQLite's auto-vacuum and WAL mode. Large libraries benefit from periodic `VACUUM` operations when the server is idle. **Memory allocation** can be limited using systemd or Docker resource constraints. The server operates efficiently with 512MB minimum, though 2GB provides better performance for large libraries. ## Backup Strategy Back up the data directory regularly to prevent data loss. The recommended approach depends on your infrastructure. **Systemd deployments** can use rsync or similar tools while the server is running. SQLite WAL mode ensures consistent reads during backup. **Docker deployments** should back up named volumes. Stop the container, copy the volume contents, then restart. Alternatively, use volume backup tools that handle running containers. **Cloud backups** of library databases are small enough for frequent uploads. Sidecar data can be regenerated from source files if needed, reducing backup size. Test restore procedures periodically. A backup is only useful if you can restore it successfully. ## Migration Moving an existing library to a new server requires copying the data directory and adjusting location paths. Copy the entire data directory to the new server. Start the server and verify the library loads. Update location paths if the mount points differ on the new system. File content identity ensures files are recognized even if paths change. The server re-indexes locations with new paths but preserves tags, collections, and metadata. ## Updates The server receives updates through new Docker image tags or binary releases. Always review release notes before updating to understand breaking changes. **Docker updates:** Pull the new image and recreate the container. Data persists in volumes across container replacements. ```bash theme={null} docker pull ghcr.io/spacedriveapp/spacedrive/server:latest docker stop spacedrive docker rm spacedrive # Run docker run command with new image ``` **Binary updates:** Download the new release, verify checksums, and replace the binary. Restart the systemd service. ```bash theme={null} sudo systemctl stop spacedrive sudo mv sd-server-new /usr/local/bin/sd-server sudo systemctl start spacedrive ``` Database migrations run automatically on first start after update. Check logs to confirm successful migration. ## Support Report issues on [GitHub](https://github.com/spacedriveapp/spacedrive/issues) with server logs and deployment details. Join [Discord](https://discord.gg/gTaF2Z44f5) for community support and deployment advice. # Spacedrive V2 Whitepaper Source: https://v2.spacedrive.com/overview/whitepaper This document explains the purpose of the Spacedrive V2 whitepaper, what it covers, and how our community can use it to understand, contribute to, and build upon the future of personal data management. ## [Read the paper →](https://github.com/spacedriveapp/spacedrive/blob/main/whitepaper/spacedrive.pdf) ## Why We Wrote This Whitepaper Spacedrive V2 represents a complete architectural reimagining of the project, designed to fulfill the original vision on a more robust and scalable foundation. After a period of reflection on the challenges faced by the first version, we recognized the need for a foundational rewrite to address critical issues like the "Dual File System Problem" and fragmented networking. This whitepaper was created to serve three primary purposes: 1. **To Provide a Definitive Technical Blueprint**: It is the single source of truth for the Spacedrive V2 architecture, detailing the core concepts, design decisions, and innovations that power the new system. 2. **To Re-engage Our Community**: We want to share our renewed vision and technical direction transparently, providing a clear path for developers, contributors, and users to rally behind. 3. **To Guide Future Development**: The document serves as a roadmap and a set of guiding principles, ensuring that all future contributions align with the core architectural tenets of performance, privacy, and user control. Ultimately, this paper is our commitment to building a paradigm shift in how humans interact with their digital assets in the AI era. *** ## What This Whitepaper Covers The whitepaper presents the complete architecture of Spacedrive V2, a local-first, AI-native Virtual Distributed File System (VDFS). It details the five foundational innovations that solve traditionally hard problems in distributed systems for a consumer-grade product. Key architectural pillars covered in detail include: * **A Virtual Distributed File System (VDFS)**: A unified, virtual layer that provides a single view of all your data across every device and cloud, while the files themselves stay in their original locations. This is made possible by a universal addressing system called **`SdPath`**. * **An AI-Native Architecture**: The system is designed from the ground up for intelligent management, enabling natural language commands ("find my tax documents from last year") and proactive assistance from a data guardian that respects user privacy. * **A Transactional Action System**: All file operations are treated as transactions that can be previewed before they are committed, preventing conflicts and guaranteeing completion even across offline devices. * **Domain-Separated Library Sync**: A novel synchronization method that maintains consistency across devices without the complexity of distributed consensus algorithms like CRDTs. * **The Content Identity System**: A content-addressable foundation that provides intelligent, cross-device deduplication while also powering a "Data Guardian" feature that monitors data redundancy to protect against loss. * **A Modern, Performant Implementation**: The entire core is implemented in **Rust** on a modern, asynchronous technology stack designed for enterprise-grade capabilities on consumer hardware. *** ## How to Use This Document This whitepaper is more than a technical document; it's an invitation to our community to help build the future of file management. #### **For Developers & Contributors:** * **Understand the Vision**: Before diving into the code, read the whitepaper to understand the "why" behind the architecture. It provides the context for our design choices and the problems we are solving. * **Guide Your Contributions**: Use this document alongside the **Roadmap** as a guide. The architecture detailed here is the blueprint for all new features. Whether you're fixing a bug or building a new operation, it should align with these core principles. * **Build with Confidence**: The paper explains the core abstractions like `SdPath`, the `ActionManager`, and the `JobManager`. Understanding these will help you build new features that integrate seamlessly and reliably with the rest of the system. #### **For System Architects & Designers:** * **Review and Feedback**: We welcome feedback on our architectural decisions. The whitepaper details our solutions to complex problems like synchronization and distributed file operations. If you have insights or see potential improvements, we encourage you to start a discussion. * **Propose Enhancements**: The document provides the context for proposing new, large-scale features or optimizations, such as the planned migration to a Closure Table for hierarchical queries. #### **For the Entire Community:** * **The Source of Truth**: When you have questions about how Spacedrive works under the hood, this document is the canonical source. It explains how we handle your data, ensure privacy, and deliver powerful features in a local-first environment. * **A Foundation for Discussion**: Use this paper as a common ground for discussions about Spacedrive's future. It ensures everyone is working from the same set of assumptions about the technology. We are incredibly excited about the foundation we've built with Spacedrive V2 and believe it positions us to solve the fundamental problems of data fragmentation and privacy for the modern era. We invite you to read, discuss, and build with us. # Colors Source: https://v2.spacedrive.com/react/ui/colors Spacedrive uses a semantic color system built on CSS variables and HSL values. The system provides context-aware colors that automatically support theming and opacity modifiers. ## Color Architecture Colors are defined as HSL triplets (hue, saturation, lightness) in CSS variables, then referenced via Tailwind's `alpha()` function for opacity support. ```css theme={null} /* Definition */ --color-accent: 208, 100%, 57%; /* Usage in Tailwind */ bg-accent /* hsla(var(--color-accent), 1) */ bg-accent/50 /* hsla(var(--color-accent), 0.5) */ ``` This approach enables: * Full opacity control (`/10`, `/20`, `/50`, etc.) * Runtime theme switching * Type-safe Tailwind classes ## Color Categories ### Accent Colors Primary brand colors for interactive elements. ```tsx theme={null}
Primary action button
Subtle accent background
``` **Variants:** * `accent` - Default accent (220, 90%, 56%) ### Text Colors (Ink) Hierarchical text colors for content. ```tsx theme={null}

Primary heading

Secondary text

Tertiary/disabled text ``` **Hierarchy:** * `ink` - Primary text (92% lightness) * `ink-dull` - Secondary text (70% lightness) * `ink-faint` - Tertiary text (55% lightness) ### App Colors Main application area colors for backgrounds, borders, and surfaces. ```tsx theme={null}
Card or panel
``` **Color Scale:** * `app` - Base background (235, 15%, 13%) * `app-box` - Card/panel background (235, 15%, 18%) * `app-overlay` - Overlay background (235, 15%, 16%) * `app-line` - Border color (235, 15%, 23%) * `app-frame` - Frame border (235, 15%, 25%) **Use Case Examples:** ```tsx theme={null} // Layered cards
Nested content
// Interactive elements // Form inputs ``` ### Sidebar Colors Sidebar-specific colors that can differ from main app area. ```tsx theme={null} ``` **Scale:** * `sidebar` - Base (235, 15%, 7%) * `sidebar-box` - Panels (235, 15%, 16%) * `sidebar-line` - Borders (235, 15%, 23%) * `sidebar-selected` - Selected state (235, 15%, 24%) * `sidebar-button` - Button background (235, 15%, 18%) * `sidebar-divider` - Dividers (235, 15%, 17%) * `sidebar-ink` / `sidebar-ink-dull` / `sidebar-ink-faint` - Text hierarchy ### Menu Colors Context menu and dropdown colors. ```tsx theme={null}
``` **Scale:** * `menu` - Base (235, 15%, 13%) * `menu-line` - Borders (235, 15%, 23%) * `menu-hover` - Hover state (235, 15%, 20%) * `menu-selected` - Selected state (235, 15%, 24%) * `menu-shade` - Shadow (235, 15%, 8%) * `menu-ink` - Primary text (235, 15%, 92%) * `menu-faint` - Secondary text (235, 10%, 55%) ## Theming ### Dark Theme (Default) Uses `--dark-hue: 235` with low lightness values. ### Light Theme Add `.vanilla-theme` class to root for light mode. Uses `--light-hue: 235` with high lightness values. ```tsx theme={null} {/* Entire app switches to light theme */} ``` The same color classes (`text-ink`, `bg-app-box`, etc.) automatically adapt to the theme. ### Custom Themes Create custom themes by defining a new class with color overrides: ```css theme={null} .custom-theme { --dark-hue: 280; /* Purple-tinted theme */ --color-accent: 280, 100%, 60%; /* Other color overrides */ } ``` ## Best Practices ### Use Semantic Names Don't use raw colors: ```tsx theme={null}
``` Use semantic colors: ```tsx theme={null}
``` ### Respect Context Don't mix contexts unnecessarily: ```tsx theme={null}

{/* Wrong context */}

``` Use matching context: ```tsx theme={null}

``` ### Use Opacity for Variations Don't hardcode alpha values: ```tsx theme={null}
``` Use Tailwind opacity: ```tsx theme={null}
``` ### Leverage Interaction States ```tsx theme={null} ``` ## Color Reference ### Complete Color List **Accent:** * `accent`, `accent-faint`, `accent-deep` **Text:** * `ink`, `ink-dull`, `ink-faint` **App:** * `app`, `app-box`, `app-dark-box`, `app-darker-box`, `app-light-box` * `app-input`, `app-focus`, `app-button` * `app-line`, `app-divider` * `app-hover`, `app-selected`, `app-active` * `app-overlay`, `app-shade`, `app-frame`, `app-slider` **Sidebar:** * `sidebar`, `sidebar-box`, `sidebar-line` * `sidebar-ink`, `sidebar-ink-dull`, `sidebar-ink-faint` * `sidebar-divider`, `sidebar-button`, `sidebar-selected`, `sidebar-shade` **Menu:** * `menu`, `menu-line`, `menu-hover`, `menu-selected` * `menu-ink`, `menu-faint`, `menu-shade` ## Migration from Generic Colors If you have code using generic Tailwind colors, migrate to semantic names: | Old | New | | ------------------- | -------------------- | | `text-white` | `text-ink` | | `text-gray-400` | `text-ink-dull` | | `text-gray-500` | `text-ink-faint` | | `bg-gray-800` | `bg-app-box` | | `bg-gray-900` | `bg-app` | | `border-gray-700` | `border-app-line` | | `hover:bg-gray-700` | `hover:bg-app-hover` | This ensures your UI automatically adapts to theme changes. # Explorer Architecture Source: https://v2.spacedrive.com/react/ui/explorer The Explorer is Spacedrive's primary file browsing interface. It displays files, locations, volumes, and devices using a unified system that treats all entities as navigable directories. The architecture centers on a single source of truth for navigation: URL query parameters. ## Navigation System The Explorer uses URL query parameters instead of route paths to manage navigation state. This design allows the sidebar, path bar, and Explorer view to stay synchronized without prop drilling or complex state management. ```typescript theme={null} // Path-based navigation /explorer?path={"Physical":{"device_slug":"home","path":"/Documents"}} // View-based navigation (virtual listings) /explorer?view=device&id=abc123 ``` When you navigate to a location from the sidebar, the URL updates with the new path. The Explorer reads this URL parameter and displays the corresponding directory. The sidebar highlights the active item by comparing its own path to the URL parameter. The URL is the single source of truth. All navigation actions update the URL first, then components react to URL changes. ### History Management Navigation history stores a union type that supports both real paths and virtual views: ```typescript theme={null} type NavigationEntry = | { type: "path"; path: SdPath } | { type: "view"; view: string; id?: string; params?: Record }; ``` The `ExplorerContext` maintains a history stack and current position. When you click back or forward, it restores the previous entry and updates the URL accordingly. This works seamlessly across both file system paths and virtual device listings. ## Virtual Listings Virtual listings display non-file entities (devices, locations, volumes) as if they were files in a directory. This allows the Explorer to reuse all existing view components (grid, list, column) without special cases. ### Mapping to Files The `virtualFiles.ts` module converts backend entities into `File` objects with a special `_virtual` metadata field: ```typescript theme={null} export function mapLocationToFile(location: Location, iconUrl?: string): File { return { id: `virtual:location:${location.id}`, kind: "Directory", name: location.name, sd_path: location.sd_path, // ... standard File fields _virtual: { type: "location", data: location, iconUrl, } }; } ``` The `_virtual` field marks this as a display-only entity. Virtual files cannot be copied, moved, or deleted. The `isVirtualFile()` helper checks for this field before allowing file operations. ### View Detection The `useVirtualListing` hook detects virtual view parameters in the URL and fetches the appropriate data: ```typescript theme={null} // Example: Device view if (view === "device" && id) { // Fetch locations and volumes for this device const locations = locationsData?.locations.filter( loc => loc.sd_path.Physical?.device_slug === device.slug ); const volumes = volumesData?.volumes.filter( vol => vol.device_id === id ); // Map to virtual files return locations.map(mapLocationToFile) .concat(volumes.map(mapVolumeToFile)); } ``` This returns an array of virtual files that the Explorer views consume like regular directory listings. ### Column View Integration Column view presents a unique challenge for virtual listings. When you select a virtual location, the next column should show that location's real contents. The system handles this by conditionally rendering columns: ```typescript theme={null} if (isVirtualView && virtualFiles) { const selectedDirectory = selectedFiles.length === 1 && selectedFiles[0].kind === "Directory" ? selectedFiles[0] : null; return (
{/* Virtual column */} {/* Real content column when directory selected */} {selectedDirectory && ( )}
); } ``` The first column displays virtual files. When you select one, the second column queries the backend for real directory contents using the virtual file's `sd_path`. Virtual files must never be passed to file operations like copy, move, or delete. Always check `isVirtualFile()` before backend mutations. ## Safety Guards The system includes multiple layers of protection against accidental operations on virtual files: **Context Menu**: Copy and delete menu items are hidden when virtual files are selected. The `getTargetFiles()` function filters out virtual files before operations. **Drag and Drop**: The `useDraggableFile` hook disables dragging for virtual files by setting `disabled: true` on the draggable configuration. **Type Checking**: Functions that access `_virtual` metadata use optional chaining to handle undefined files gracefully: ```typescript theme={null} const virtualMetadata = file?._virtual; const isVolume = virtualMetadata?.type === "volume"; ``` ## Path Bar Navigation The path bar displays breadcrumbs for the current path. For physical paths, the device icon is clickable and navigates to that device's virtual view: ```typescript theme={null} const handleDeviceClick = () => { if (device) { navigateToView("device", device.id); } }; ``` This creates a seamless transition from browsing a file system path to viewing all locations and volumes on that device. For virtual views, a separate `VirtualPathBar` component renders appropriate breadcrumbs like "Devices → My Device". ## Enum Handling The backend returns Rust enum variants that can be objects like `{ Other: "value" }`. These cannot be rendered directly in React. Always convert enums to strings before displaying: ```typescript theme={null} const volumeTypeStr = typeof volume.volume_type === "string" ? volume.volume_type : (volume.volume_type as any)?.Other || JSON.stringify(volume.volume_type); ``` This pattern extracts the `Other` variant value when present, falls back to JSON stringification, or uses the string directly if it's already a string. Apply this pattern consistently to `file_system`, `disk_type`, `volume_type`, `form_factor`, and any other backend enum fields. ## Component Communication The `ExplorerContext` provides methods for navigation that other components use: ```typescript theme={null} const { navigateToPath, navigateToView, goBack, goForward } = useExplorer(); // Navigate to a file system path navigateToPath({ Physical: { device_slug: "home", path: "/Documents" }}); // Navigate to a virtual view navigateToView("device", deviceId); ``` These methods update both the internal history stack and the URL. Components that render navigation UI (sidebar, path bar) use `useLocation()` to read the current URL and derive their active state. The sidebar calculates `isActive` by comparing its item's path or view parameters to the current URL parameters. This ensures the active state always matches what's visible in the Explorer. ## Inspector Integration The Inspector sidebar detects virtual files and renders appropriate content: ```typescript theme={null} if (isVirtualFile(file) && file._virtual?.type === "location") { const locationData = file._virtual.data; return ; } ``` This allows clicking a virtual location in the device view to show the `LocationInspector` rather than the generic `FileInspector`. ## View Modes All three view modes (grid, list, column) consume the same file array. When `useVirtualListing` returns virtual files, the views render them using the same components as real files. Icon overrides in `Thumb.tsx` check for `_virtual.iconUrl` and display custom icons for locations and volumes. The grid view conditionally renders a volume capacity bar when displaying virtual volumes: ```typescript theme={null} const isVolume = isVirtualFile(file) && file._virtual?.type === "volume"; if (isVolume) { return ; } ``` This adds visual information without requiring volume-specific components or branching logic in the core Explorer. # React Hooks Source: https://v2.spacedrive.com/react/ui/hooks Spacedrive provides type-safe React hooks for data fetching, mutations, and event subscriptions. All types are auto-generated from Rust definitions. ## Data Fetching Hooks ### useCoreQuery Type-safe hook for core-scoped queries (operations that don't require a library). ```tsx theme={null} import { useCoreQuery } from '@sd/interface'; function LibraryList() { const { data: libraries, isLoading, error } = useCoreQuery({ type: 'libraries.list', input: { include_stats: false }, }); if (isLoading) return ; if (error) return
Error: {error.message}
; return (
{libraries?.map(lib => (
{lib.name}
))}
); } ``` **Features:** * **Auto-generated types** - `type` and `input` are type-checked against Rust definitions * **TanStack Query** - Full TanStack Query API available * **Automatic caching** - Query results are cached by key * **Type inference** - `data` type is automatically inferred **Examples:** ```tsx theme={null} // Get node information const { data: nodeInfo } = useCoreQuery({ type: 'node.info', input: {}, }); // List all libraries with stats const { data: libraries } = useCoreQuery({ type: 'libraries.list', input: { include_stats: true }, }); // With TanStack Query options const { data: libraries } = useCoreQuery( { type: 'libraries.list', input: {}, }, { staleTime: 5 * 60 * 1000, // 5 minutes refetchOnWindowFocus: false, } ); ``` ### useLibraryQuery Type-safe hook for library-scoped queries (operations within a specific library). ```tsx theme={null} import { useLibraryQuery } from '@sd/interface'; function FileExplorer({ path }: { path: string }) { const { data, isLoading } = useLibraryQuery({ type: 'files.directory_listing', input: { path }, }); if (isLoading) return ; return (
{data?.entries.map(entry => (
{entry.name}
))}
); } ``` **Features:** * **Automatic library scoping** - Uses current library ID from client * **Library switching** - Automatically refetches when library changes * **Type safety** - Input/output types inferred from operation * **Disabled when no library** - Query is disabled if no library selected **Examples:** ```tsx theme={null} // Get directory listing const { data: files } = useLibraryQuery({ type: 'files.directory_listing', input: { path: '/photos' }, }); // List all locations const { data: locations } = useLibraryQuery({ type: 'locations.list', input: {}, }); // Get file metadata const { data: metadata } = useLibraryQuery({ type: 'files.get_metadata', input: { path: '/photos/IMG_1234.jpg' }, }); // Search files const { data: results } = useLibraryQuery({ type: 'files.search', input: { query: 'vacation', filters: [] }, }); ``` ### useNormalizedCache Event-driven cache updates for real-time sync across devices. See [Normalized Cache](/react/ui/normalized-cache) for full documentation. ```tsx theme={null} import { useNormalizedCache } from '@sd/interface'; function LocationsList() { const { data: locations } = useNormalizedCache({ query: 'locations.list', input: {}, resourceType: 'location', isGlobalList: true, }); return (
{locations?.map(location => (
{location.name}
))}
); } ``` **When to use:** * List queries that need instant updates across devices * File listings that change frequently * Real-time resource monitoring ## Mutation Hooks ### useCoreMutation Type-safe hook for core-scoped mutations (operations that don't require a library). ```tsx theme={null} import { useCoreMutation } from '@sd/interface'; function CreateLibraryButton() { const createLib = useCoreMutation('libraries.create'); const handleCreate = () => { createLib.mutate( { name: 'My Library', path: null }, { onSuccess: (library) => { console.log('Created:', library.name); }, onError: (error) => { console.error('Failed:', error.message); }, } ); }; return ( ); } ``` **Features:** * **Type-safe input** - Mutation input is type-checked * **Type-safe output** - Success callback receives typed result * **Loading states** - `isPending`, `isSuccess`, `isError` * **TanStack Query integration** - Full mutation API available **Examples:** ```tsx theme={null} // Create library const createLib = useCoreMutation('libraries.create'); createLib.mutate({ name: 'Photos', path: '/Users/me/Photos' }); // Delete library const deleteLib = useCoreMutation('libraries.delete'); deleteLib.mutate({ id: '123' }); // Update node config const updateConfig = useCoreMutation('node.update_config'); updateConfig.mutate({ theme: 'dark', port: 8080 }); ``` ### useLibraryMutation Type-safe hook for library-scoped mutations (operations within a specific library). ```tsx theme={null} import { useLibraryMutation } from '@sd/interface'; function ApplyTagsButton({ fileIds, tagIds }: { fileIds: number[], tagIds: string[] }) { const applyTags = useLibraryMutation('tags.apply'); return ( ); } ``` **Features:** * **Automatic library scoping** - Uses current library ID * **Type safety** - Input/output types inferred * **Error handling** - Throws if no library selected * **TanStack Query callbacks** - onSuccess, onError, onSettled **Examples:** ```tsx theme={null} // Create location const createLocation = useLibraryMutation('locations.create'); createLocation.mutate({ path: '/Users/me/Photos', index_mode: 'deep' }); // Delete files const deleteFiles = useLibraryMutation('files.delete'); deleteFiles.mutate({ paths: ['/photo1.jpg', '/photo2.jpg'] }); // Apply tags const applyTags = useLibraryMutation('tags.apply'); applyTags.mutate({ entry_ids: [1, 2, 3], tag_ids: ['tag-uuid'] }); // Move files const moveFiles = useLibraryMutation('files.move'); moveFiles.mutate({ source: '/old/path', destination: '/new/path' }); ``` ## Event Hooks ### useEvent Subscribe to specific Spacedrive events. ```tsx theme={null} import { useEvent } from '@sd/interface'; function JobProgress() { const [progress, setProgress] = useState(0); useEvent('JobProgress', (event) => { const jobProgress = event.JobProgress; setProgress(jobProgress.progress_percentage); }); return ; } ``` **Features:** * **Event filtering** - Only receives events of specified type * **Automatic cleanup** - Unsubscribes on unmount * **Type-safe** - Event type is checked at compile time **Examples:** ```tsx theme={null} // Listen for file creation useEvent('FileCreated', (event) => { console.log('New file:', event.FileCreated.path); }); // Listen for indexing progress useEvent('IndexingProgress', (event) => { const { location_id, progress } = event.IndexingProgress; updateProgress(location_id, progress); }); // Listen for library sync events useEvent('LibrarySynced', (event) => { console.log('Library synced:', event.LibrarySynced.library_id); }); // Listen for job completion useEvent('JobCompleted', (event) => { const job = event.JobCompleted; toast.success(`Job ${job.name} completed!`); }); ``` ### useAllEvents Subscribe to all Spacedrive events (useful for debugging). ```tsx theme={null} import { useAllEvents } from '@sd/interface'; function EventDebugger() { useAllEvents((event) => { console.log('Event:', event); }); return
Check console for events
; } ``` **Warning:** This can be noisy. Use `useEvent` for specific events in production. ## Custom Hooks ### useLibraries Convenience hook for fetching all libraries. ```tsx theme={null} import { useLibraries } from '@sd/interface'; function LibraryDropdown() { const { data: libraries, isLoading } = useLibraries(); if (isLoading) return ; return ( ); } ``` **With stats:** ```tsx theme={null} const { data: libraries } = useLibraries(true); libraries?.forEach(lib => { console.log(`${lib.name}: ${lib.statistics?.total_files} files`); }); ``` ## Client Hook ### useSpacedriveClient Access the Spacedrive client instance directly. ```tsx theme={null} import { useSpacedriveClient } from '@sd/interface'; function LibrarySwitcher() { const client = useSpacedriveClient(); const [currentLibraryId, setCurrentLibraryId] = useState(null); const switchLibrary = (id: string) => { client.setCurrentLibrary(id); setCurrentLibraryId(id); }; return (
); } ``` **Client methods:** * `client.setCurrentLibrary(id: string)` - Switch to a library * `client.getCurrentLibraryId()` - Get current library ID * `client.execute(method, input)` - Execute RPC method directly * `client.on(event, handler)` - Subscribe to events * `client.off(event, handler)` - Unsubscribe from events ## Hook Patterns ### Combining Queries ```tsx theme={null} function Dashboard() { const { data: libraries } = useLibraries(); const { data: nodeInfo } = useCoreQuery({ type: 'node.info', input: {}, }); const { data: jobs } = useLibraryQuery({ type: 'jobs.list', input: {}, }); return (

{nodeInfo?.name}

{libraries?.length} libraries

{jobs?.length} running jobs

); } ``` ### Dependent Queries ```tsx theme={null} function FileDetails({ path }: { path: string }) { // First get file info const { data: file } = useLibraryQuery({ type: 'files.get', input: { path }, }); // Then get metadata (only if file exists) const { data: metadata } = useLibraryQuery( { type: 'files.get_metadata', input: { file_id: file?.id }, }, { enabled: !!file, } ); return
{metadata?.size} bytes
; } ``` ### Mutations with Refetch ```tsx theme={null} function DeleteButton({ fileId }: { fileId: number }) { const queryClient = useQueryClient(); const deleteFile = useLibraryMutation('files.delete'); const handleDelete = () => { deleteFile.mutate( { file_ids: [fileId] }, { onSuccess: () => { // Refetch file list after deletion queryClient.invalidateQueries(['files.directory_listing']); }, } ); }; return ; } ``` ### Optimistic Updates ```tsx theme={null} function RenameButton({ fileId, currentName }: { fileId: number, currentName: string }) { const queryClient = useQueryClient(); const rename = useLibraryMutation('files.rename'); const handleRename = (newName: string) => { rename.mutate( { file_id: fileId, new_name: newName }, { // Optimistically update UI before server confirms onMutate: async (variables) => { // Cancel outgoing refetches await queryClient.cancelQueries(['files.get', fileId]); // Snapshot previous value const previous = queryClient.getQueryData(['files.get', fileId]); // Optimistically update queryClient.setQueryData(['files.get', fileId], (old: any) => ({ ...old, name: variables.new_name, })); return { previous }; }, // Rollback on error onError: (err, variables, context) => { queryClient.setQueryData(['files.get', fileId], context?.previous); }, // Refetch after success or error onSettled: () => { queryClient.invalidateQueries(['files.get', fileId]); }, } ); }; return ; } ``` ## Best Practices ### Use the Right Hook ```tsx theme={null} // Good - core query for libraries const { data: libraries } = useCoreQuery({ type: 'libraries.list', input: {}, }); // Bad - library query for core operation const { data: libraries } = useLibraryQuery({ type: 'libraries.list', // Type error! input: {}, }); // Good - library query for files const { data: files } = useLibraryQuery({ type: 'files.directory_listing', input: { path: '/' }, }); ``` ### Set Appropriate Stale Times ```tsx theme={null} // Static data - long stale time const { data: nodeInfo } = useCoreQuery( { type: 'node.info', input: {}, }, { staleTime: 5 * 60 * 1000, // 5 minutes } ); // Dynamic data - short stale time or use useNormalizedCache const { data: files } = useNormalizedCache({ query: 'files.directory_listing', input: { path }, resourceType: 'file', }); ``` ### Handle Loading and Error States ```tsx theme={null} // Good - handles all states function FileList() { const { data, isLoading, error } = useLibraryQuery({ type: 'files.directory_listing', input: { path: '/' }, }); if (isLoading) return ; if (error) return ; if (!data) return ; return
{data.entries.map(...)}
; } // Bad - assumes data exists function FileList() { const { data } = useLibraryQuery({ type: 'files.directory_listing', input: { path: '/' }, }); return
{data.entries.map(...)}
; // Can crash! } ``` ### Invalidate Related Queries ```tsx theme={null} const createLocation = useLibraryMutation('locations.create'); const handleCreate = () => { createLocation.mutate( { path: '/photos' }, { onSuccess: () => { // Invalidate related queries queryClient.invalidateQueries(['locations.list']); queryClient.invalidateQueries(['files.directory_listing']); }, } ); }; ``` ## Summary Spacedrive's React hooks provide: * **Type safety** - All operations are type-checked against Rust definitions * **Auto-generation** - Types are generated from Rust, never manually written * **TanStack Query** - Full TanStack Query API available * **Library scoping** - Automatic library ID management * **Event subscriptions** - Real-time updates via WebSocket * **Normalized cache** - Instant cross-device sync Use `useCoreQuery` and `useLibraryQuery` for data fetching, `useCoreMutation` and `useLibraryMutation` for mutations, and `useEvent` for event subscriptions. # Normalized Query Source: https://v2.spacedrive.com/react/ui/normalized-cache # Real-Time Normalized Cache with TanStack Query The `useNormalizedQuery` hook provides instant, event-driven cache updates with server-side filtering. Built with 2025 best practices including runtime validation (Valibot), type-safe merging (ts-deepmerge), and proper subscription cleanup. ## Overview `useNormalizedQuery` wraps TanStack Query to add real-time capabilities: * **Instant updates** across all devices via WebSocket events * **Server-side filtering** reduces network traffic by 90%+ * **Client-side safety** ensures correctness even with unrelated events * **Proper cleanup** prevents connection leaks * **Runtime validation** catches malformed events * **Type-safe merging** preserves data integrity ## Architecture ## Basic Usage ### Directory Listing ```tsx theme={null} import { useNormalizedQuery } from "@sd/ts-client"; function DirectoryView({ path }: { path: SdPath }) { const { data, isLoading } = useNormalizedQuery({ query: "files.directory_listing", input: { path }, resourceType: "file", pathScope: path, includeDescendants: false, // Only direct children }); if (isLoading) return ; return (
{data?.files?.map((file) => )}
); } ``` **What happens:** 1. Initial query fetches directory listing 2. Hook subscribes to file events for this path (exact mode) 3. When files are created/updated, events arrive instantly 4. Cache updates atomically 5. UI re-renders with new data ### Media View (Recursive) ```tsx theme={null} function MediaGallery({ path }: { path: SdPath }) { const { data } = useNormalizedQuery({ query: "files.media_listing", input: { path, include_descendants: true }, resourceType: "file", pathScope: path, includeDescendants: true, // All media in subtree }); return ( {data?.files?.map((file) => )} ); } ``` ### Global Resources ```tsx theme={null} function LocationsList() { const { data } = useNormalizedQuery({ query: "locations.list", input: null, resourceType: "location", // No pathScope - locations are global resources }); return (
    {data?.locations?.map((loc) =>
  • {loc.name}
  • )}
); } ``` ### Single Resource Queries ```tsx theme={null} function FileInspector({ fileId }: { fileId: string }) { const { data: file } = useNormalizedQuery({ query: "files.by_id", input: { file_id: fileId }, resourceType: "file", resourceId: fileId, // Only events for this file }); return (

{file?.name}

{/* Updates instantly when thumbnails generate */} {file?.sidecars?.map((sidecar) => ( ))}
); } ``` ## API Reference ### Options ```tsx theme={null} interface UseNormalizedQueryOptions { // Query method to call (e.g., "files.directory_listing") query: string; // Input for the query input: I; // Resource type for event filtering (e.g., "file", "location") resourceType: string; // Whether query is enabled (default: true) enabled?: boolean; // Optional path scope for server-side filtering pathScope?: SdPath; // Whether to include descendants (recursive) or only direct children (exact) // Default: false (exact matching) includeDescendants?: boolean; // Resource ID for single-resource queries resourceId?: string; } ``` ### Path Filtering Modes #### Exact Mode (Default) Only events for files **directly in** the specified directory: ```tsx theme={null} pathScope: { Physical: { device_slug: 'my-mac', path: '/Photos' } }, includeDescendants: false // or omit (default) ``` **Behavior:** * File in `/Photos/image.jpg` → ✓ Included * File in `/Photos/Vacation/beach.jpg` → ✗ Excluded * Directory `/Photos/Vacation` → ✗ Excluded #### Recursive Mode All events for files **anywhere under** the specified directory: ```tsx theme={null} pathScope: { Physical: { device_slug: 'my-mac', path: '/Photos' } }, includeDescendants: true ``` **Behavior:** * File in `/Photos/image.jpg` → ✓ Included * File in `/Photos/Vacation/beach.jpg` → ✓ Included * File in `/Photos/Vacation/Cruise/pic.jpg` → ✓ Included ## Server-Side Filtering ### How It Works Each hook creates a filtered subscription on the backend: ```tsx theme={null} client.subscribeFiltered({ resource_type: "file", // Only file events path_scope: "/Desktop", // Only this path include_descendants: false, // Exact mode library_id: "abc-123", // Current library }); ``` Backend applies filters **before** sending events: 1. ✓ `resource_type` matches? 2. ✓ `library_id` matches? 3. ✓ `path_scope` matches? (with `include_descendants` mode) 4. ✓ `resourceId` matches? (if specified) **Result:** Only matching events are transmitted over the network. ### Filter Logic **Exact Mode:** ``` Event has affected_paths: [ "/Desktop/file.txt", // File path "/Desktop" // Parent directory ] Subscription path_scope: "/Desktop" include_descendants: false Check: Does affected_paths contain "/Desktop" exactly? Result: YES → Forward event ``` **Recursive Mode:** ``` Event has affected_paths: [ "/Desktop/Subfolder/file.txt", "/Desktop/Subfolder" ] Subscription path_scope: "/Desktop" include_descendants: true Check: Does "/Desktop/Subfolder" start with "/Desktop"? Result: YES → Forward event ``` ## Client-Side Safety Filtering Even with server-side filtering, the client applies a safety filter to batch events: ```tsx theme={null} // Server forwards batch if ANY file matches // Client filters to ONLY files that match Batch has 100 files: - 10 in /Desktop/ (direct children) - 90 in /Desktop/Subfolder/ (subdirectories) Server: Has 1 direct child → forward entire batch Client: Filter batch → keep only 10 direct children Cache: Contains only 10 files ✓ ``` This ensures correctness even if server-side filtering has edge cases. ## Event Types ### ResourceChanged (Single) ```tsx theme={null} { ResourceChanged: { resource_type: "location", resource: { id: "uuid", name: "Photos", path: "/Users/me/Photos", // ... full resource data }, metadata: { no_merge_fields: ["sd_path"], affected_paths: [], alternate_ids: [] } } } ``` ### ResourceChangedBatch (Multiple) ```tsx theme={null} { ResourceChangedBatch: { resource_type: "file", resources: [ { id: "1", name: "photo1.jpg", ... }, { id: "2", name: "photo2.jpg", ... } ], metadata: { no_merge_fields: ["sd_path"], affected_paths: [ { Physical: { device_slug: "mac", path: "/Desktop/photo1.jpg" } }, { Physical: { device_slug: "mac", path: "/Desktop" } }, { Content: { content_id: "uuid" } } ], alternate_ids: [] } } } ``` ### ResourceDeleted ```tsx theme={null} { ResourceDeleted: { resource_type: "location", resource_id: "uuid" } } ``` ### Refresh (Invalidate All) ```tsx theme={null} "Refresh"; ``` Triggers `queryClient.invalidateQueries()` to refetch all data. ## Deep Merge Behavior Uses `ts-deepmerge` for type-safe, configurable merging: ```tsx theme={null} // Existing cache { id: "1", name: "Photos", metadata: { size: 1024, created_at: "2024-01-01" } } // Incoming event (partial update) { id: "1", name: "My Photos", metadata: { size: 2048 } } // Result after merge { id: "1", name: "My Photos", // Updated metadata: { size: 2048, // Updated created_at: "2024-01-01" // Preserved ✓ } } ``` ### No-Merge Fields Some fields should be replaced entirely, not merged: ```tsx theme={null} metadata: { no_merge_fields: ["sd_path"]; } // sd_path is replaced entirely, not deep merged // This prevents incorrect path combinations ``` ## Runtime Validation All events are validated with Valibot before processing: ```tsx theme={null} const ResourceChangedSchema = v.object({ ResourceChanged: v.object({ resource_type: v.string(), resource: v.any(), metadata: v.nullish(v.object({ ... })) }) }); // Invalid events are logged and ignored // Prevents crashes from malformed backend data ``` ## Subscription Multiplexing Multiple hooks with identical filters automatically share a single backend subscription: ```tsx theme={null} // Component A function LocationsList() { useNormalizedQuery({ query: 'locations.list', resourceType: 'location', }); } // Component B (mounted at same time) function LocationsDropdown() { useNormalizedQuery({ query: 'locations.list', resourceType: 'location', }); } // Result: Only 1 backend subscription created! // Both hooks receive events from the same connection. ``` **How it works:** 1. First hook creates subscription with filter `{resource_type: "location", library_id: "abc"}` 2. Subscription manager generates key from filter: `{"resource_type":"location","library_id":"abc"}` 3. Second hook with same filter reuses existing subscription 4. Events broadcast to all listeners 5. When both unmount, subscription cleaned up automatically **Benefits:** * Eliminates duplicate subscriptions during render cycles * Reduces backend load (fewer Unix socket connections) * Faster subscription setup (reuses existing connection) * Automatic reference counting prevents premature cleanup ## Subscription Cleanup Subscriptions are properly cleaned up when components unmount: ```tsx theme={null} useEffect(() => { let unsubscribe: (() => void) | undefined; client.subscribeFiltered(filter, handleEvent).then((unsub) => { unsubscribe = unsub; }); return () => { unsubscribe?.(); // Closes WebSocket subscription }; }, [dependencies]); ``` **Cleanup process:** 1. React calls cleanup function 2. Frontend stops listening to events 3. Tauri sends `Unsubscribe` request to daemon 4. Daemon closes subscription 5. Unix socket connection closed **Result:** No connection leaks, no memory leaks. ## Performance ### Event Reduction ``` Indexing 10,000 files: Without filtering: - Each hook receives: 10,000 events - Total transmitted: 50,000 events (5 hooks × 10,000) - Result: UI lag, slow With filtering: - Desktop hook: 100 events (1%) - Movies hook: 500 events (5%) - Inspector: 1-5 events (0.05%) - Total transmitted: ~600 events - Result: Zero lag ``` ### Connection Management * **Multiplexing:** Multiple hooks with identical filters share one backend subscription * **Reference counting:** Subscriptions cleaned up when last hook unmounts * **Deduplication:** Eliminates duplicate subscriptions during render cycles * **Monitoring:** Check `client.getSubscriptionStats()` for active subscriptions ## Testing ### Test Coverage **Rust (Backend):** * 9/9 event filtering tests passing * Validates exact vs recursive modes * Tests all path types (Physical, Content, Cloud, Sidecar) **TypeScript (Frontend):** * 5/5 integration tests passing * Uses real backend event fixtures * Validates filtering and cache updates * Proves correctness with actual production code ### Run Tests ```bash theme={null} # Rust tests cargo test --test event_filtering_test # TypeScript tests cd packages/ts-client && bun test # Generate new fixtures from backend cargo test --test normalized_cache_fixtures_test ``` ## Best Practices ### Always Scope File Queries ```tsx theme={null} // Good const { data } = useNormalizedQuery({ query: "files.directory_listing", input: { path }, resourceType: "file", pathScope: path, // Server filters efficiently }); // Bad - will skip subscription const { data } = useNormalizedQuery({ query: "files.directory_listing", input: { path }, resourceType: "file", // Missing pathScope! Subscription skipped to prevent overload }); ``` ### Use Correct Mode for View Type ```tsx theme={null} // Directory view - exact mode includeDescendants: false; // Only direct children // Media gallery - recursive mode includeDescendants: true; // All media in subtree // Search results - recursive mode includeDescendants: true; // All matching files ``` ### Combine with TanStack Query Options ```tsx theme={null} const { data } = useNormalizedQuery({ query: "files.directory_listing", input: { path }, resourceType: "file", pathScope: path, // TanStack Query options enabled: !!path, staleTime: 5 * 60 * 1000, refetchOnWindowFocus: true, }); ``` ## Advanced Usage ### Content-Addressed Files Files use Content-based `sd_path` but have Physical paths in `alternate_paths`: ```tsx theme={null} // File structure { sd_path: { Content: { content_id: "uuid" } }, alternate_paths: [ { Physical: { device_slug: "mac", path: "/Desktop/file.txt" } } ] } // Client-side filtering uses alternate_paths for path matching // This enables deduplication while maintaining path filtering ``` ### Multiple Instances Multiple files with same content have different IDs: ```tsx theme={null} // file1.txt (original) { id: "1", content_identity: { uuid: "abc" } } // file2.txt (duplicate) { id: "2", content_identity: { uuid: "abc" } } // Both update when content is processed ``` ## Debugging ### Enable Logging ```tsx theme={null} // Check console for: // "[useNormalizedQuery] Invalid event: ..." - Validation failures // "[TauriTransport] Unsubscribing: ..." - Cleanup events ``` ### Monitor Subscriptions ```bash theme={null} # Backend logs show subscription lifecycle RUST_LOG=sd_core::infra::daemon::rpc=debug cargo run -p spacedrive-tauri # Look for: # "New subscription created: ..." - Subscription started # "Subscription cancelled: ..." - Cleanup triggered # "Unsubscribe sent successfully" - Connection closed ``` **Frontend subscription stats:** ```tsx theme={null} import { useSpacedriveClient } from '@sd/ts-client'; function DebugPanel() { const client = useSpacedriveClient(); const stats = client.getSubscriptionStats(); console.log(`Active subscriptions: ${stats.activeSubscriptions}`); stats.subscriptions.forEach(sub => { console.log(` ${sub.key}: ${sub.refCount} hooks, ${sub.listenerCount} listeners`); }); } ``` ### Inspect Cache ```tsx theme={null} import { useQueryClient } from "@tanstack/react-query"; const queryClient = useQueryClient(); // View all cached queries console.log(queryClient.getQueryCache().getAll()); // View specific query const queryKey = ["query:files.directory_listing", libraryId, { path }]; console.log(queryClient.getQueryData(queryKey)); ``` ## Migration ### From useLibraryQuery ```tsx theme={null} // Before (no real-time updates) const { data } = useLibraryQuery({ type: "locations.list", input: {}, }); // After (instant updates) const { data } = useNormalizedQuery({ query: "locations.list", input: null, resourceType: "location", }); ``` ### Backward Compatibility The old `useNormalizedCache` name is aliased: ```tsx theme={null} // Both work identically import { useNormalizedQuery } from "@sd/ts-client"; import { useNormalizedCache } from "@sd/ts-client"; // Alias // Prefer useNormalizedQuery for new code ``` ## Technical Details ### Exported Functions Core logic is exported for testing: ```tsx theme={null} import { filterBatchResources, // Filter resources by pathScope updateBatchResources, // Update cache with batch updateSingleResource, // Update single resource deleteResource, // Remove from cache safeMerge, // Deep merge utility handleResourceEvent, // Event dispatcher } from "@sd/ts-client/hooks/useNormalizedQuery"; ``` ### Runtime Dependencies * **ts-deepmerge** - Type-safe deep merging * **valibot** - Runtime event validation * **tiny-invariant** - Assertion helpers * **type-fest** - TypeScript utilities * **@tanstack/react-query** - Core caching ### Subscription Lifecycle ``` 1. Component mounts ↓ 2. useNormalizedQuery creates subscription ↓ 3. Backend creates filtered event stream ↓ 4. Events flow: Backend → Tauri → Frontend → Hook → Cache ↓ 5. Component unmounts ↓ 6. Cleanup function called ↓ 7. Tauri cancels background task ↓ 8. Backend receives Unsubscribe ↓ 9. Unix socket closed ↓ 10. Connection freed ``` ## Common Patterns ### List with Real-Time Updates ```tsx theme={null} const { data: items } = useNormalizedQuery({ query: "items.list", input: filters, resourceType: "item", }); // Items list updates instantly when: // - New items created // - Existing items modified // - Items deleted ``` ### Directory with Instant File Appearance ```tsx theme={null} const { data: files } = useNormalizedQuery({ query: "files.directory_listing", input: { path }, resourceType: "file", pathScope: path, }); // New files appear instantly: // - Screenshot taken → appears immediately // - File copied → shows up without refresh // - File renamed → updates in real-time ``` ### Inspector with Sidecar Updates ```tsx theme={null} const { data: file } = useNormalizedQuery({ query: "files.by_id", input: { file_id }, resourceType: "file", resourceId: file_id, }); // Sidecars update as they're generated: // - Thumbnail generated → appears instantly // - Thumbstrip created → shows immediately // - OCR extracted → updates in real-time ``` ## Summary `useNormalizedQuery` provides production-grade real-time caching: * Server-side filtering (90%+ event reduction) * Client-side safety (validates and filters) * Proper cleanup (no connection leaks) * Runtime validation (catches bad events) * Type-safe merging (preserves data) * Comprehensive tests (9 Rust + 5 TypeScript) * TanStack Query compatible (all features work) * Cross-device sync (instant updates everywhere) Use it for any query where data can change and you want instant updates without manual refetching. # Platform Abstraction Source: https://v2.spacedrive.com/react/ui/platform The platform abstraction layer enables the Spacedrive interface to run on multiple platforms (Web, Tauri, React Native) while accessing platform-specific features. ## Problem Spacedrive runs on: * **Desktop** via Tauri (native file pickers, native dialogs) * **Web** via browser (limited native APIs) * **Mobile** via React Native (different native APIs) We need a single codebase that works everywhere without `if (isTauri)` checks scattered throughout. ## Solution The `Platform` type and `usePlatform()` hook provide a clean abstraction: ```tsx theme={null} // Component doesn't know or care which platform it's on function FilePicker() { const platform = usePlatform(); const handlePickFile = async () => { if (platform.openFilePickerDialog) { const path = await platform.openFilePickerDialog({ multiple: false }); console.log('Selected:', path); } else { // Fallback for platforms without native picker console.log('Use web file input instead'); } }; return ; } ``` ## Platform Type ```tsx theme={null} type Platform = { // Platform discriminator platform: "web" | "tauri"; // Open native directory picker dialog (Tauri only) openDirectoryPickerDialog?(opts?: { title?: string; multiple?: boolean; }): Promise; // Open native file picker dialog (Tauri only) openFilePickerDialog?(opts?: { title?: string; multiple?: boolean; }): Promise; // Save file picker dialog (Tauri only) saveFilePickerDialog?(opts?: { title?: string; defaultPath?: string; }): Promise; // Open a URL in the default browser openLink(url: string): void; // Show native confirmation dialog confirm(message: string, callback: (result: boolean) => void): void; }; ``` ## Usage ### Setup Wrap your app with `PlatformProvider`: ```tsx theme={null} import { PlatformProvider, Platform } from '@sd/interface'; // Tauri implementation const tauriPlatform: Platform = { platform: 'tauri', openDirectoryPickerDialog: async (opts) => { return await window.__TAURI__.dialog.open({ directory: true, title: opts?.title, multiple: opts?.multiple, }); }, openFilePickerDialog: async (opts) => { return await window.__TAURI__.dialog.open({ directory: false, title: opts?.title, multiple: opts?.multiple, }); }, saveFilePickerDialog: async (opts) => { return await window.__TAURI__.dialog.save({ title: opts?.title, defaultPath: opts?.defaultPath, }); }, openLink: (url) => { window.__TAURI__.shell.open(url); }, confirm: (message, callback) => { window.__TAURI__.dialog.confirm(message).then(callback); }, }; // Web implementation const webPlatform: Platform = { platform: 'web', // No native dialogs openLink: (url) => { window.open(url, '_blank'); }, confirm: (message, callback) => { callback(window.confirm(message)); }, }; function App() { const platform = window.__TAURI__ ? tauriPlatform : webPlatform; return ( ); } ``` ### Using in Components ```tsx theme={null} import { usePlatform } from '@sd/interface'; function AddLocationButton() { const platform = usePlatform(); const handleAddLocation = async () => { // Check if native picker is available if (platform.openDirectoryPickerDialog) { const path = await platform.openDirectoryPickerDialog({ title: 'Select folder to index', multiple: false, }); if (path && typeof path === 'string') { // Create location with selected path await createLocation({ path }); } } else { // Web fallback: show manual path input showManualPathDialog(); } }; return ( ); } ``` ### Opening External Links ```tsx theme={null} function HelpButton() { const platform = usePlatform(); return ( ); } ``` ### Confirmation Dialogs ```tsx theme={null} function DeleteButton({ itemName }: { itemName: string }) { const platform = usePlatform(); const handleDelete = () => { platform.confirm( `Are you sure you want to delete "${itemName}"?`, (confirmed) => { if (confirmed) { performDelete(); } } ); }; return ; } ``` ## Checking Platform Type ```tsx theme={null} function FeatureGate() { const platform = usePlatform(); if (platform.platform === 'web') { return
Web-specific UI
; } return
Desktop-specific UI
; } ``` ## Optional Methods Pattern All platform-specific methods are **optional** (marked with `?`). This enables: 1. **Graceful degradation** - Components can check availability and provide fallbacks 2. **Type safety** - TypeScript enforces checking before calling 3. **Platform flexibility** - New platforms can implement only what they support ```tsx theme={null} // Good - checks availability if (platform.openFilePickerDialog) { await platform.openFilePickerDialog(); } else { // Fallback for platforms without native picker } // Bad - will error at runtime on web await platform.openFilePickerDialog(); // Type error! ``` ## Adding New Platform Methods To add a new platform capability: 1. Update the `Platform` type in `platform.tsx` 2. Implement for each platform (Tauri, Web, React Native) 3. Use with optional chaining in components ```tsx theme={null} // 1. Add to Platform type type Platform = { // ... existing methods // New method showNotification?(opts: { title: string; body: string; }): void; }; // 2. Implement for Tauri const tauriPlatform: Platform = { // ... existing methods showNotification: (opts) => { window.__TAURI__.notification.sendNotification(opts); }, }; // 3. Implement for Web const webPlatform: Platform = { // ... existing methods showNotification: (opts) => { if ('Notification' in window && Notification.permission === 'granted') { new Notification(opts.title, { body: opts.body }); } }, }; // 4. Use in components function NotifyButton() { const platform = usePlatform(); const notify = () => { platform.showNotification?.({ title: 'Hello', body: 'World', }); }; return ; } ``` ## Best Practices ### Provide Fallbacks Always have a fallback for platforms without the feature: ```tsx theme={null} // Good const pickFile = async () => { if (platform.openFilePickerDialog) { return await platform.openFilePickerDialog(); } else { // Show web file input or manual path entry return await showWebFilePicker(); } }; // Bad - feature just doesn't work on some platforms const pickFile = async () => { return await platform.openFilePickerDialog?.(); // Returns undefined on web, no fallback! }; ``` ### Don't Check Platform String Avoid checking `platform.platform` directly. Check method availability instead: ```tsx theme={null} // Good - feature detection if (platform.openDirectoryPickerDialog) { // Use native picker } // Bad - platform detection if (platform.platform === 'tauri') { // Assumes Tauri = has picker (maybe not in future) } ``` ### Keep Platform Logic Minimal Platform-specific code should be minimal. Most logic should be platform-agnostic: ```tsx theme={null} // Good - only picker is platform-specific async function addLocation() { const path = await pickDirectory(); // Platform abstraction const location = createLocationFromPath(path); // Platform-agnostic await saveLocation(location); // Platform-agnostic showSuccessMessage(); // Platform-agnostic } // Bad - too much platform-specific code async function addLocationTauri() { // Entire flow is Tauri-specific, can't reuse } async function addLocationWeb() { // Duplicate logic for web } ``` ### Use Context, Not Props Use `usePlatform()` hook instead of prop drilling: ```tsx theme={null} // Good function DeepComponent() { const platform = usePlatform(); // Available anywhere } // Bad function Parent() { return ; } function Child({ platform }: { platform: Platform }) { return ; } ``` ## Platform Implementations ### Tauri ```tsx theme={null} const tauriPlatform: Platform = { platform: 'tauri', openDirectoryPickerDialog: async (opts) => { return await window.__TAURI__.dialog.open({ directory: true, title: opts?.title, multiple: opts?.multiple, }); }, openFilePickerDialog: async (opts) => { return await window.__TAURI__.dialog.open({ directory: false, title: opts?.title, multiple: opts?.multiple, }); }, saveFilePickerDialog: async (opts) => { return await window.__TAURI__.dialog.save({ title: opts?.title, defaultPath: opts?.defaultPath, }); }, openLink: (url) => { window.__TAURI__.shell.open(url); }, confirm: (message, callback) => { window.__TAURI__.dialog.confirm(message).then(callback); }, }; ``` ### Web ```tsx theme={null} const webPlatform: Platform = { platform: 'web', openLink: (url) => { window.open(url, '_blank'); }, confirm: (message, callback) => { callback(window.confirm(message)); }, // Native pickers not available }; ``` ### React Native (Future) ```tsx theme={null} const rnPlatform: Platform = { platform: 'mobile', openDirectoryPickerDialog: async (opts) => { // Use react-native-document-picker or similar return await DocumentPicker.pickDirectory(); }, openLink: (url) => { Linking.openURL(url); }, confirm: (message, callback) => { Alert.alert( 'Confirm', message, [ { text: 'Cancel', onPress: () => callback(false) }, { text: 'OK', onPress: () => callback(true) }, ] ); }, }; ``` ## Error Handling ```tsx theme={null} async function pickFile() { const platform = usePlatform(); if (!platform.openFilePickerDialog) { throw new Error('File picker not available on this platform'); } try { const path = await platform.openFilePickerDialog(); if (!path) { // User cancelled return null; } return path; } catch (error) { console.error('Failed to pick file:', error); return null; } } ``` ## Summary The platform abstraction layer: * **Single codebase** works on Web, Tauri, and React Native * **Clean API** via `usePlatform()` hook * **Type-safe** with optional methods * **Graceful degradation** with feature detection * **Minimal boilerplate** using React Context * **Easy to extend** with new platform methods Use it whenever you need platform-specific functionality like native dialogs, file pickers, or shell commands. # UI Primitives Source: https://v2.spacedrive.com/react/ui/primitives Spacedrive's UI is built on a set of reusable primitives from `@sd/ui`. These components provide consistent styling and behavior across the application. ## Design Principles ### Composition Over Configuration Primitives are simple, composable building blocks rather than complex configured components. ```tsx theme={null} // Complex configuration // Composable primitives
{data.map(item => ( ))}
Name
{item.name}
``` ### Semantic Color Usage All primitives use semantic color tokens, never raw Tailwind colors. ```tsx theme={null} // Raw colors
// Semantic colors
``` ### Consistent Patterns Common patterns are standardized across primitives: **Card Pattern:** ```tsx theme={null}
{/* Content */}
``` **List Item Pattern:** ```tsx theme={null}
{/* Content */}
``` **Table Pattern:** ```tsx theme={null}
Column
Data
``` ## Core Primitives ### Button Versatile button component with multiple variants and sizes. ```tsx theme={null} import { Button } from '@sd/ui'; ``` **Variants:** * `default` - Transparent with border, hover/active states * `gray` - App button background with hover/focus states * `accent` - Accent blue background with white text * `subtle` - Transparent border, subtle hover * `outline` - Sidebar line border style * `dotted` - Dashed border for add/create actions * `colored` - Custom colored backgrounds (pass bg color class) * `bare` - No styling whatsoever **Sizes:** * `xs` - Extra small (px-1.5 py-0.5, text-xs) * `sm` - Small (px-2 py-0.5, text-sm) - default * `md` - Medium (px-2.5 py-1.5, text-sm) * `lg` - Large (px-3 py-1.5, text-md) * `icon` - Square icon button (!p-1) **Best Practice:** Wrap icons and text in flex containers to prevent stacking: ```tsx theme={null} ``` ### Input Form input with semantic styling and size variants. ```tsx theme={null} import { Input, Label } from "@sd/ui";
; ``` **Variants:** * `default` - Standard input with border and background * `transparent` - Transparent background, no border on focus **Sizes:** * `xs` - 25px height * `sm` - 30px height (default) * `md` - 36px height * `lg` - 42px height * `xl` - 48px height **Props:** * `error` - Shows error state (red border/ring) * `icon` - Icon component or React node * `iconPosition` - `'left'` | `'right'` (default: `'left'`) * `right` - React node to display on the right side * `inputElementClassName` - Additional classes for the input element itself **Additional Components:** * `SearchInput` - Input with MagnifyingGlass icon pre-configured * `PasswordInput` - Input with eye icon toggle for show/hide password * `TextArea` - Multi-line text input with same styling system * `Label` - Semantic label component with slug prop for htmlFor ### Form Components React Hook Form integration with automatic validation display. ```tsx theme={null} import { Form, InputField, z } from "@sd/ui/src/forms"; import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; const schema = z.object({ username: z.string().min(3), email: z.string().email(), }); function MyForm() { const form = useForm({ resolver: zodResolver(schema), }); return (
); } ``` ### Switch Toggle switch for boolean settings. ```tsx theme={null} import { Switch } from "@sd/ui"; const [enabled, setEnabled] = useState(false);
Enable Feature
Description
; ``` ### ShinyToggle Animated toggle component for switching between multiple options with a smooth glowing indicator. ```tsx theme={null} import { ShinyToggle } from "@sd/ui"; const [view, setView] = useState<"grid" | "list">("grid"); ; ``` **Features:** * Smooth animated indicator using Framer Motion * Gradient background with glow effect * Optional count badges * Type-safe with generics * Fully accessible **Props:** * `value` - Current selected value (generic type T) * `onChange` - Callback when selection changes * `options` - Array of `{ value: T, label: ReactNode, count?: number }` * `className` - Additional classes for the container ### DropdownMenu Context menu and dropdown with Radix UI. ```tsx theme={null} import { DropdownMenu } from "@sd/ui"; Open Menu}> ; ``` ## Glassmorphism Effect Spacedrive's signature glassmorphism effect combines backdrop blur, transparency, and gradient borders. ```tsx theme={null}
{/* Top gradient border */}
{/* Bottom gradient border */}
{/* Content with noise texture */}
Content
``` **Noise Variants:** * `noise` - Base noise texture * `noise-faded` - Faded intensity * `noise-sm` - Small grain size ## Progress Bars Consistent progress bar pattern for resource usage. ```tsx theme={null}
Storage 45/100 GB
``` **Color by type:** * Storage: `bg-accent` (blue) * AI/Compute: `bg-purple-500` * Bandwidth: `bg-green-500` * Progress: `bg-accent` * Success: `bg-green-400` ## Status Badges Standard status badge pattern. ```tsx theme={null} const STATUS_CONFIG = { running: { color: "text-green-400", bg: "bg-green-500/20" }, stopped: { color: "text-gray-400", bg: "bg-gray-500/20" }, error: { color: "text-red-400", bg: "bg-red-500/20" }, };
Running
; ``` ## Empty States Pattern for when lists/grids are empty. ```tsx theme={null}

No items yet

Description of what would appear here

``` ## Gradients ### Background Gradients ```tsx theme={null}
Icon background
Gradient text
``` ### Border Gradients ```tsx theme={null}
``` ## Typography Scale Consistent text sizing across the app. ```tsx theme={null}

Page Title

Section Title

Description text

Helper text ``` **Scale:** * `text-xs` (12px) - Helper text, labels * `text-sm` (14px) - Body text, descriptions * `text-base` (16px) - Default body * `text-lg` (18px) - Subheadings * `text-xl` (20px) - Section titles * `text-2xl` (24px) - Card titles * `text-3xl` (30px) - Page titles ## Icons Use Phosphor Icons with consistent sizing and weights. ```tsx theme={null} import { Icon } from '@phosphor-icons/react'; // Buttons, small UI // Medium UI elements // Large icons // Headers // Empty states ``` **Weight Guidelines:** * `regular` - Default, inactive states * `fill` - Active states, buttons, emphasis * `bold` - Strong emphasis ## Spacing Scale Consistent spacing using Tailwind's scale. **Common patterns:** * Card padding: `p-6` * Button padding: `px-3 py-1.5` (md), `px-2.5 py-1.5` (sm) * Section spacing: `space-y-4` or `space-y-6` * Grid gaps: `gap-4` or `gap-6` * Icon-text gap: `gap-2` or `gap-3` ## Accessibility ### Color Contrast All semantic colors meet WCAG AA standards: * `text-ink` on `bg-app` - AAA * `text-ink-dull` on `bg-app-box` - AA * `text-ink-faint` on `bg-app-input` - AA (minimum) ### Focus States Interactive elements include focus rings: ```tsx theme={null}