motto 0.3.0

Compiler-as-a-Service: Turn Rust schema.rs into multi-platform SDK toolkits
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
# Motto: The Minimalist Bit-Level Toolchain

[![CI](https://github.com/bowber/motto/actions/workflows/ci.yml/badge.svg)](https://github.com/bowber/motto/actions/workflows/ci.yml)
[![Crates.io](https://img.shields.io/crates/v/motto.svg)](https://crates.io/crates/motto)
[![License](https://img.shields.io/crates/l/motto.svg)](LICENSE-MIT)

**Motto** turns your Rust structs into high-performance, bit-packed binary protocols with automated multi-platform SDK generation. Optimized for extreme efficiency on low-resource environments (e.g., 2GB RAM VPS).

## Why Motto?

**The Problem**: You're building a real-time multiplayer game or IoT system. You need:
- Consistent data types across server, web, mobile, and game clients
- Binary protocols that don't waste bandwidth
- Infrastructure that doesn't cost $500/month

**The Solution**: Define your types once in plain Rust. Motto generates everything else.

```rust
// src/schema.rs
// No serde, no manual routing, no boilerplate.

struct Player {
    id: u64,
    position: Position,
    health: u8,
}

struct Position {
    x: f32,
    y: f32,
}

struct ChatMessage {
    from: u64,
    content: String,
}

// Motto automatically aggregates these into a bit-optimized message router.
```

## Features

- **Zero Dependencies in Schema**: No `serde` derives required. Just plain Rust structs.
- **Implicit Message Router**: Individual structs are automatically aggregated into a single, bit-optimized router enum.
- **Bit-Level Packing**: Computes minimal bit-width for enum variants, skipping standard byte-alignment where possible.
- **A/B Deployment Ready**: 1-byte version header enables automatic traffic routing between protocol versions on your infrastructure.
- **Infrastructure Agnostic**: Works with WebTransport, WebSocket, NATS Core, or raw TCP. Bring your own transport.
- **Multi-Platform SDKs**: TypeScript/WASM, Swift, Kotlin, Unity/C#, and Rust — all from one schema.

## Installation

```bash
cargo install motto
```

Or build from source:

```bash
git clone https://github.com/bowber/motto
cd motto
cargo build --release
```

## Feature Flags

Motto uses Cargo feature flags to control which emitters are compiled:

| Feature | Default | Description |
|---------|---------|-------------|
| `all-emitters` | Yes | Enables all platform emitters |
| `emitter-typescript` | Yes (via `all-emitters`) | TypeScript/WASM SDK generation |
| `emitter-swift` | Yes (via `all-emitters`) | Swift SDK generation |
| `emitter-kotlin` | Yes (via `all-emitters`) | Kotlin SDK generation |
| `emitter-unity` | Yes (via `all-emitters`) | Unity/C# SDK generation |

The Rust emitter is always available (no feature flag required).

To install with only specific emitters:

```bash
# Only Rust + TypeScript
cargo install motto --no-default-features --features emitter-typescript

# Only Rust (smallest binary)
cargo install motto --no-default-features
```

## Quick Start

### 1. Initialize a project

```bash
motto init --path my-project
```

This creates:
- `src/schema.rs` - Your schema definitions
- `motto.lock` - Version tracking file
- `generated/` - Output directory

### 2. Define your schema

```rust
// src/schema.rs
// Clean, minimal, no ceremony.

struct Player {
    id: u64,
    position: Position,
    health: u8,
}

struct Position {
    x: f32,
    y: f32,
}

struct PlayerJoined {
    player: Player,
}

struct PlayerMoved {
    player_id: u64,
    position: Position,
}

struct PlayerLeft {
    player_id: u64,
}

// That's it. Motto handles the rest.
```

### 3. Generate SDKs

```bash
# Generate all platforms
motto generate

# Generate specific platforms
motto generate --targets typescript,swift,rust

# With WASM bindings
motto generate --wasm
```

### 4. Lock the schema version

```bash
motto lock --bump minor
```

## Architecture

Motto follows a three-phase compiler architecture:

### 1. Static Analysis Frontend
- Parses plain Rust structs (no macro annotations required)
- Computes schema fingerprint for change detection

### 2. Intermediate Representation (IR)
- **Implicit Routing**: Automatically aggregates individual structs into a single, bit-optimized router enum
- **Bit-Level Packing**: Computes minimal bit-width for enum variants and field offsets, skipping standard byte-alignment where possible
- Generates language-agnostic manifest with field offsets

### 3. Backend Emitters
- **TypeScript/WASM**: ESM-compliant TypeScript with conditional exports for WASM or Native Addon
- **Swift**: Native iOS/macOS SDK with Codable conformance
- **Kotlin**: Android/JVM SDK with kotlinx.serialization support
- **Unity/C#**: C# wrappers with unsafe pointers for memory-efficient DllImport
- **Rust**: Native Rust crate with zero-copy codec and Handler trait for routing

## Deployment Philosophy: Scale From Small to Large

Motto is designed to grow with you. The same protocol works whether you're:

- **Prototyping** on a single $5 VPS
- **Launching** with a small cluster
- **Scaling** to millions of concurrent users

The generated SDKs are infrastructure-agnostic — plug them into WebTransport, WebSocket, NATS, Kafka, or raw TCP. No code changes required as you scale.

### A/B Deployment with Version Routing

The 1-byte version header isn't just for "detecting" protocol changes — it enables **automatic traffic routing**:

```
┌─────────────┐     ┌──────────────────┐     ┌─────────────┐
│   Client    │────▶│  Gateway/Sidecar │────▶│  Server v2  │
│ (version 2) │     │   Routes by Ver  │     └─────────────┘
└─────────────┘     │                  │     ┌─────────────┐
                    │                  │────▶│  Server v1  │
┌─────────────┐     │                  │     │  (legacy)   │
│   Client    │────▶│                  │     └─────────────┘
│ (version 1) │     └──────────────────┘
└─────────────┘
```

Deploy new versions alongside old ones. Migrate clients gradually. Zero downtime.

## CLI Commands

| Command | Description |
|---------|-------------|
| `init` | Initialize a new motto project |
| `generate` | Generate SDK code from schema.rs |
| `check` | Check schema for breaking changes |
| `lock` | Update motto.lock with new schema fingerprint |
| `watch` | Watch for schema changes and regenerate |

## Generated Output Structure

```
generated/
├── typescript/
│   ├── package.json
│   └── src/
│       ├── types.ts      # Type definitions
│       ├── codec.ts      # Binary encoding/decoding
│       ├── runtime.ts    # State machine, transport
│       └── index.ts      # Exports
├── rust/
│   ├── Cargo.toml
│   └── src/
│       ├── lib.rs        # Types + Router enum + Handler trait
│       └── codec.rs      # Encode/Decode implementations
├── swift/
│   ├── Package.swift
│   └── Sources/MottoSDK/
│       ├── Types.swift
│       ├── Codec.swift
│       └── Runtime.swift
├── kotlin/
│   ├── build.gradle.kts
│   └── src/main/kotlin/io/motto/sdk/
│       ├── Types.kt
│       ├── Codec.kt
│       └── Runtime.kt
└── unity/MottoSDK/
    ├── Motto.SDK.asmdef
    └── Runtime/
        ├── Types.cs
        ├── Codec.cs
        ├── Runtime.cs
        └── NativeBridge.cs
```

## Using the Generated SDKs

The best practice is to **publish your generated SDK to a package registry** and import it like any other dependency. This keeps your application code clean and your protocol versioned.

### Rust (Server-side or Native Clients)

The Rust SDK is ideal for building game servers, native clients, or any Rust application that needs to communicate with other Motto-generated SDKs.

**1. Add as a dependency:**

```bash
cd generated/rust
cargo publish
# or for local development, add to your Cargo.toml:
# [dependencies]
# my_schema = { path = "../generated/rust" }
```

**2. Basic encode/decode:**

```rust
use my_schema::{Position, Player, PlayerStatus};
use my_schema::codec::{Encode, Decode};

// Create types
let position = Position { x: 100.5, y: 200.3 };
let player = Player {
    id: 12345,
    name: "Alice".to_string(),
    position: Position { x: 0.0, y: 0.0 },
    velocity: Velocity { dx: 0.0, dy: 0.0 },
    health: 100,
    score: 0,
    status: PlayerStatus::Online,
    avatar_url: None,
};

// Encode to binary (includes version byte header)
let encoded = position.to_bytes();
println!("Encoded {} bytes, version: 0x{:02X}", encoded.len(), encoded[0]);

// Decode back
let decoded = Position::from_bytes(&encoded)?;
println!("Position: ({}, {})", decoded.x, decoded.y);
```

**3. Message routing with match:**

The generated `SchemaRouter` enum wraps all non-generic message types for type-safe routing:

```rust
use my_schema::{ExampleSchemaRouter, Position, Player, GameState};
use my_schema::codec::Decode;

fn handle_message(bytes: &[u8]) -> Result<(), std::io::Error> {
    let message = ExampleSchemaRouter::from_bytes(bytes)?;
    
    match message {
        ExampleSchemaRouter::Position(pos) => {
            println!("Got position: ({}, {})", pos.x, pos.y);
        }
        ExampleSchemaRouter::Player(player) => {
            println!("Got player: {} (id={})", player.name, player.id);
        }
        ExampleSchemaRouter::GameState(state) => {
            println!("Got game state, tick={}", state.tick);
        }
        // ... handle other variants
        _ => {
            println!("Unknown message type, tag={}", message.tag());
        }
    }
    
    Ok(())
}
```

**4. Handler trait pattern:**

For more structured routing, implement the generated Handler trait:

```rust
use my_schema::{
    ExampleSchemaRouter, ExampleSchemaRouterHandler,
    Position, Velocity, Player, RoomConfig, GameState, PlayerUpdate,
};

struct MyHandler {
    player_count: usize,
}

impl ExampleSchemaRouterHandler for MyHandler {
    type Output = Result<(), String>;
    
    fn handle_position(&mut self, pos: Position) -> Self::Output {
        println!("Position update: ({}, {})", pos.x, pos.y);
        Ok(())
    }
    
    fn handle_player(&mut self, player: Player) -> Self::Output {
        self.player_count += 1;
        println!("Player joined: {} (total: {})", player.name, self.player_count);
        Ok(())
    }
    
    fn handle_game_state(&mut self, state: GameState) -> Self::Output {
        println!("State sync: {} players, tick {}", state.players.len(), state.tick);
        Ok(())
    }
    
    // ... implement other handlers
    fn handle_velocity(&mut self, _: Velocity) -> Self::Output { Ok(()) }
    fn handle_room_config(&mut self, _: RoomConfig) -> Self::Output { Ok(()) }
    fn handle_player_update(&mut self, _: PlayerUpdate) -> Self::Output { Ok(()) }
}

// Use it:
fn process_message(bytes: &[u8], handler: &mut MyHandler) -> Result<(), String> {
    let message = ExampleSchemaRouter::from_bytes(bytes)
        .map_err(|e| e.to_string())?;
    message.route(handler)
}
```

**5. Use with async runtime (tokio example):**

```rust
use tokio::net::TcpStream;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use my_schema::{Position, GameState};
use my_schema::codec::{Encode, Decode};

async fn game_client() -> std::io::Result<()> {
    let mut stream = TcpStream::connect("127.0.0.1:8080").await?;
    
    // Send position update
    let pos = Position { x: 100.0, y: 200.0 };
    let bytes = pos.to_bytes();
    stream.write_all(&(bytes.len() as u32).to_le_bytes()).await?;
    stream.write_all(&bytes).await?;
    
    // Read response
    let mut len_buf = [0u8; 4];
    stream.read_exact(&mut len_buf).await?;
    let len = u32::from_le_bytes(len_buf) as usize;
    
    let mut buf = vec![0u8; len];
    stream.read_exact(&mut buf).await?;
    
    let state = GameState::from_bytes(&buf)?;
    println!("Got state with {} players", state.players.len());
    
    Ok(())
}
```

### TypeScript / Node.js

**1. Publish to npm (or use a private registry):**

```bash
cd generated/typescript
npm run build
npm publish --access public
# or for private: npm publish --registry https://your-registry.com
```

**2. Install in your application:**

```bash
npm install @motto/schema
# or with your custom package name
```

**3. Use in your code:**

```typescript
import {
  // Types
  Player,
  Position,
  ClientMessage,
  ServerMessage,
  
  // Codec
  encodePosition,
  decodePosition,
  PacketBuilder,
  PacketView,
  PROTOCOL_VERSION_BYTE,
  
  // Runtime
  MottoTransport,
  ConnectionState,
} from '@motto/schema';

// Create a player position
const pos: Position = { x: 100.5, y: 200.3 };

// Encode to binary (includes version byte header)
const encoded = encodePosition(pos);
console.log(`Encoded ${encoded.byteLength} bytes, version: 0x${encoded[0].toString(16)}`);

// Decode back
const decoded = decodePosition(encoded);
console.log(`Position: (${decoded.x}, ${decoded.y})`);

// Build custom packets with PacketBuilder
const builder = new PacketBuilder();
builder.writeU64(BigInt(12345));  // player_id
builder.writeF32(pos.x);
builder.writeF32(pos.y);
const packet = builder.build();

// Connect via WebTransport
const transport = new MottoTransport('https://your-server.com/game');
await transport.connect();
await transport.sendDatagram(packet);
```

### Swift / iOS / macOS

**1. Add as a Swift Package dependency:**

```swift
// In your Package.swift or Xcode project
dependencies: [
    .package(url: "https://github.com/your-org/motto-schema-swift", from: "0.1.0"),
    // Or use a local path during development:
    // .package(path: "../generated/swift")
]
```

**2. Use in your code:**

```swift
import MottoSDK

// Types are ready to use
let position = Position(x: 100.5, y: 200.3)
let player = Player(
    id: 12345,
    name: "Alice",
    position: position,
    velocity: Velocity(dx: 0, dy: 0),
    health: 100,
    score: 0,
    status: .online,
    avatarUrl: nil
)

// Encode to binary
let encoded = Codec.encodePosition(position)
print("Encoded \(encoded.count) bytes")

// Decode back  
let decoded = Codec.decodePosition(encoded)
print("Position: (\(decoded.x), \(decoded.y))")

// Use the transport layer
let transport = MottoTransport(url: "https://your-server.com/game")
try await transport.connect()
try await transport.send(encoded)
```

### Kotlin / Android / JVM

**1. Publish to Maven (or use a local dependency):**

```bash
cd generated/kotlin
./gradlew publishToMavenLocal
# or publish to your Maven repository
```

**2. Add dependency in your app's `build.gradle.kts`:**

```kotlin
dependencies {
    implementation("io.motto:schema:0.1.0")
}
```

**3. Use in your code:**

```kotlin
import io.motto.sdk.*

// Create types
val position = Position(x = 100.5f, y = 200.3f)
val player = Player(
    id = 12345u,
    name = "Alice",
    position = position,
    velocity = Velocity(dx = 0f, dy = 0f),
    health = 100u,
    score = 0u,
    status = PlayerStatus.Online,
    avatarUrl = null
)

// Encode/decode
val encoded = Codec.encodePosition(position)
println("Encoded ${encoded.size} bytes")

val decoded = Codec.decodePosition(encoded)
println("Position: (${decoded.x}, ${decoded.y})")

// Use with coroutines
val transport = MottoTransport("https://your-server.com/game")
transport.connect()
transport.send(encoded)
```

### Unity / C#

**1. Copy the generated SDK to your Unity project:**

```bash
cp -r generated/unity/MottoSDK Assets/Plugins/
```

Or add as a Unity Package (add to `Packages/manifest.json`):

```json
{
  "dependencies": {
    "com.motto.sdk": "file:../../generated/unity/MottoSDK"
  }
}
```

**2. Use in your C# scripts:**

```csharp
using Motto.SDK;
using UnityEngine;

public class GameClient : MonoBehaviour
{
    private MottoTransport transport;

    async void Start()
    {
        // Create types
        var position = new Position { X = 100.5f, Y = 200.3f };
        var player = new Player
        {
            Id = 12345,
            Name = "Alice",
            Position = position,
            Health = 100,
            Score = 0,
            Status = PlayerStatus.Online
        };

        // Encode to binary
        byte[] encoded = Codec.EncodePosition(position);
        Debug.Log($"Encoded {encoded.Length} bytes, version: 0x{encoded[0]:X2}");

        // Decode back
        Position decoded = Codec.DecodePosition(encoded);
        Debug.Log($"Position: ({decoded.X}, {decoded.Y})");

        // Connect and send
        transport = new MottoTransport("wss://your-server.com/game");
        await transport.ConnectAsync();
        await transport.SendAsync(encoded);
    }

    void OnDestroy()
    {
        transport?.Dispose();
    }
}
```

## CI/CD Integration

Automate SDK generation and publishing in your pipeline:

```yaml
# .github/workflows/sdk.yml
name: Generate & Publish SDKs

on:
  push:
    paths: ['src/schema.rs']
    branches: [main]

jobs:
  generate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Install Motto CLI
        run: cargo install motto
      
      - name: Check for breaking changes
        run: motto check
      
      - name: Generate SDKs
        run: motto generate
      
      - name: Publish TypeScript SDK
        run: |
          cd generated/typescript
          npm run build
          npm publish
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
      
      - name: Publish Swift SDK
        run: |
          cd generated/swift
          git init && git add .
          git commit -m "SDK v$(cat ../../motto.lock | jq -r .version)"
          git push --force https://x:${{ secrets.GH_TOKEN }}@github.com/your-org/motto-schema-swift main
```

## Runtime Features

The generated SDKs include:

- **PacketBuilder/PacketView**: Zero-copy packet construction and parsing
- **State Machine**: Connection state management with retry logic
- **Compression**: Optional Zstd compression/decompression
- **Transport Abstraction**: Plug in WebTransport, WebSocket, NATS, or raw TCP

### Transport Status

The generated Rust SDK includes transport modules behind feature flags (`webtransport`, `websocket`):

| Transport | WASM | Native |
|-----------|------|--------|
| WebTransport | Implemented (via `web_sys`) | Stub (bring your own `wtransport` impl) |
| WebSocket | Implemented (via `web_sys`) | Stub (bring your own `tokio-tungstenite` impl) |

Native transport stubs return clear errors at runtime. To use native transports, add the appropriate crate (`wtransport` or `tokio-tungstenite`) to your generated SDK's `Cargo.toml` and implement the `do_connect`, `send_raw`, and `recv_raw` methods in the generated transport files.

## Supported Types

| Rust Type | TypeScript | Swift | Kotlin | C# | Rust SDK |
|-----------|------------|-------|--------|-----|----------|
| `u8`/`i8` | `number` | `UInt8`/`Int8` | `UByte`/`Byte` | `byte`/`sbyte` | `u8`/`i8` |
| `u16`/`i16` | `number` | `UInt16`/`Int16` | `UShort`/`Short` | `ushort`/`short` | `u16`/`i16` |
| `u32`/`i32` | `number` | `UInt32`/`Int32` | `UInt`/`Int` | `uint`/`int` | `u32`/`i32` |
| `u64`/`i64` | `bigint` | `UInt64`/`Int64` | `ULong`/`Long` | `ulong`/`long` | `u64`/`i64` |
| `f32`/`f64` | `number` | `Float`/`Double` | `Float`/`Double` | `float`/`double` | `f32`/`f64` |
| `bool` | `boolean` | `Bool` | `Boolean` | `bool` | `bool` |
| `String` | `string` | `String` | `String` | `string` | `String` |
| `Vec<T>` | `T[]` | `[T]` | `List<T>` | `T[]` | `Vec<T>` |
| `Option<T>` | `T \| undefined` | `T?` | `T?` | `T?` | `Option<T>` |
| `HashMap<K,V>` | `Map<K,V>` | `[K: V]` | `Map<K,V>` | `Dictionary<K,V>` | `HashMap<K,V>` |

## License

MIT OR Apache-2.0