# @douglance/stdb-backup

Filesystem-based backup and restore utilities for SpacetimeDB databases.

## Installation

```bash
npm install -g @douglance/stdb-backup
# or
bun install -g @douglance/stdb-backup
```

## Features

- **Database Address Support**: Use SpacetimeDB addresses (`c200...` hashes) directly!
- **Instant Snapshots**: Create compressed backups of SpacetimeDB databases
- **Fast Restoration**: Restore databases from snapshots in seconds
- **Safety Checks**: Warns if SpacetimeDB server is running during backup
- **Database Discovery**: Lists all databases with addresses and timestamps
- **CLI Tool**: Simple command-line interface
- **Automatic Resolution**: Accepts both addresses and replica IDs

## Quick Start

### List Databases

```typescript
import { FilesystemSnapshot } from '@douglance/stdb-backup';

const snapshot = new FilesystemSnapshot();
const databases = await snapshot.list();

for (const db of databases) {
  console.log(db.address);   // c200080000000008002600240ab586b24ba4d627...
  console.log(db.identity);  // 150000007
  console.log(db.name);      // game-name (if available)
}
```

### Create Snapshot

```typescript
// Use database address (recommended - matches what you use in code!)
await snapshot.create({
  databaseIdentity: 'c200080000000008002600240ab586b24ba4d62794e9724d065e68f854d76daf',
  output: './backups/my-game.tar.gz',
  compress: true,
});

// Or use replica ID
await snapshot.create({
  databaseIdentity: '150000007',
  output: './backups/my-game.tar.gz',
  compress: true,
});
```

### Restore Snapshot

```typescript
await snapshot.restore({
  input: './backups/my-game.tar.gz',
  databaseIdentity: '150000009', // Replica ID or address works
  force: true,
});
```

## CLI Usage

**Step 1: Find your database**
```bash
# List all local databases with addresses
stdb snapshot list
```

Output shows:
- Database addresses (the `c200...` hash you use in code)
- Replica IDs (numeric identifiers like `150000007`)
- Last modified time
- File paths

**Step 2: Create a snapshot**
```bash
# Use database address (recommended)
stdb snapshot save <address-or-id> -o <output-file>

# Examples:
stdb snapshot save c200080000000008002600240ab586b24ba4d627... -o ./backup.tar.gz
stdb snapshot save 150000007 -o ./backup.tar.gz
```

**Step 3: Restore from snapshot**
```bash
# Restore to any replica ID
stdb snapshot restore <snapshot-file> <address-or-id> --force
```

**Complete Example:**
```bash
# 1. See what databases you have (shows addresses!)
stdb snapshot list

# 2. Create backup using database address (c200...)
stdb snapshot save c200080000000008002600240ab586b24ba4d62794e9724d065e68f854d76daf -o ./backup.tar.gz

# 3. Or use the numeric replica ID
stdb snapshot save 150000007 -o ./backup.tar.gz

# 4. Restore to a different database
stdb snapshot restore ./backup.tar.gz 150000009 --force
```

**Using Database Addresses:**
- You can now use the SpacetimeDB address (the `c200...` hash you know from your code!)
- Run `stdb snapshot list` to see addresses for all local databases
- Both addresses and numeric replica IDs work interchangeably
- The tool automatically resolves addresses to replica IDs

## Safety

⚠️ **IMPORTANT**: For safe backups, stop SpacetimeDB before creating snapshots:

```bash
# Stop server
spacetime server stop

# Create snapshot
stdb snapshot save 150000007 -o ./backup.tar.gz

# Restart server
spacetime server start
```

## API Reference

### `FilesystemSnapshot`

#### `list(): Promise<DatabaseInfo[]>`

Lists all databases in the SpacetimeDB data directory.

Returns:
- `identity`: Replica ID (numeric identifier like `150000007`)
- `address`: Database address (`c200...` hash) - **use this to match your code!**
- `name`: Database name (if available from control database)
- `path`: Absolute path to database directory
- `modifiedAt`: Last modification timestamp
- `sizeBytes`: Size in bytes (currently 0 for performance)

#### `create(options): Promise<void>`

Creates a compressed snapshot of a database.

Options:
- `databaseIdentity`: Database address (`c200...`) **or** replica ID (`150000007`)
- `output`: Path to output file (.tar.gz)
- `compress`: Enable gzip compression (default: true)

#### `restore(options): Promise<void>`

Restores a database from a snapshot.

Options:
- `input`: Path to snapshot file
- `databaseIdentity`: Target database address or replica ID
- `force`: Overwrite existing database (default: false)

## Data Directory Structure

SpacetimeDB stores local databases at:
```
~/.local/share/spacetime/data/
├── control-db/
│   └── db                      ← Contains address mappings
├── replicas/
│   ├── 148000007/              ← Database directories (replica IDs)
│   ├── 150000001/
│   ├── 150000007/
│   └── ...
└── spacetime.pid
```

**How It Works:**
- Databases are stored in directories with numeric **replica IDs** (`148000007`, `150000001`, etc.)
- Each database has a unique **address** (`c200...` hash) stored in the control database
- This tool extracts addresses from the control database for easy identification
- You can use **either format** (address or replica ID) when creating/restoring snapshots
- Addresses match what you use in your SpacetimeDB client code!

## Examples

See `examples/` directory for complete working examples.

## Tested

✅ Successfully tested with 8 databases
✅ Database address extraction from control database verified
✅ Address-to-replica-ID resolution working
✅ Snapshot creation works (191 KB compressed from 5.04 MB database)
✅ Snapshot restoration verified
✅ Safety checks functional (detects running server)
✅ Both addresses and replica IDs work for all operations

## License

MIT
