cruster-macros 0.0.5

Procedural macros for the cruster distributed entity framework
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
# Cruster

A Rust framework for building distributed, stateful entity systems with durable workflows.

> **Status:** Under active development. API may change. Feedback welcome.

## Features

- **Distributed Entities** - Stateful actors with automatic sharding, persistence, and lifecycle management
- **Durable Workflows** - Long-running operations that survive crashes with automatic replay
- **Activity Journaling** - State mutations with transactional guarantees and idempotency
- **Entity Traits** - Composable behaviors across multiple entity types
- **Singletons** - Cluster-wide unique instances with automatic failover
- **Timers & Scheduling** - Durable sleep and cron-based scheduling
- **gRPC Transport** - Inter-node communication with streaming support

## Installation

### Prerequisites

Protocol Buffers compiler is required:

```bash
# Debian/Ubuntu
sudo apt-get install protobuf-compiler

# macOS
brew install protobuf
```

### Cargo

```toml
[dependencies]
cruster = "0.0.2"
```

## Quick Start

### Defining an Entity

```rust
use cruster::prelude::*;
use serde::{Deserialize, Serialize};

// 1. Define persistent state
#[derive(Clone, Default, Serialize, Deserialize)]
struct CounterState {
    value: i64,
}

// 2. Define the entity
#[entity]
#[derive(Clone)]
struct Counter;

// 3. Implement handlers
#[entity_impl]
#[state(CounterState)]
impl Counter {
    // Required: initialize state for new entities
    fn init(&self, _ctx: &EntityContext) -> Result<CounterState, ClusterError> {
        Ok(CounterState::default())
    }

    // Activity: mutates state, journaled for replay safety
    #[activity]
    async fn do_increment(&mut self, amount: i64) -> Result<i64, ClusterError> {
        self.state.value += amount;
        Ok(self.state.value)
    }

    // Workflow: public entry point, orchestrates activities
    #[workflow]
    pub async fn increment(&self, amount: i64) -> Result<i64, ClusterError> {
        self.do_increment(amount).await
    }

    // RPC: read-only, no journaling
    #[rpc]
    pub async fn get(&self) -> Result<i64, ClusterError> {
        Ok(self.state.value)
    }
}
```

### Using the Entity

```rust
use cruster::testing::TestCluster;
use cruster::types::EntityId;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create test cluster
    let cluster = TestCluster::new().await;
    
    // Register entity and get typed client (CounterClient is generated by the macro)
    let counter = Counter.register(cluster.sharding().clone()).await?;
    
    // Call methods using the typed client - entity is created on first access
    let entity_id = EntityId::new("counter-1");
    let value = counter.increment(&entity_id, &5i64).await?;
    assert_eq!(value, 5);
    
    let value = counter.get(&entity_id).await?;
    assert_eq!(value, 5);
    
    Ok(())
}
```

## Core Concepts

### Method Types

| Attribute | Purpose | Self | Journaled | Default Visibility |
|-----------|---------|------|-----------|-------------------|
| `#[rpc]` | Read-only queries | `&self` | No | `#[public]` |
| `#[workflow]` | Durable operations | `&self` | Yes | `#[public]` |
| `#[activity]` | State mutations | `&mut self` | Yes | `#[private]` |

### The Workflow + Activity Pattern

**Best Practice:** Separate concerns between workflows (orchestration) and activities (mutation).

```rust
#[entity_impl]
#[state(OrderState)]
impl Order {
    // Activities: private, handle state mutations
    #[activity]
    async fn set_status(&mut self, status: OrderStatus) -> Result<(), ClusterError> {
        self.state.status = status;
        Ok(())
    }

    #[activity]
    async fn record_payment(&mut self, payment_id: String) -> Result<(), ClusterError> {
        self.state.payment_id = Some(payment_id);
        Ok(())
    }

    // Workflow: public, orchestrates activities
    #[workflow]
    pub async fn process_payment(&self, payment: PaymentRequest) -> Result<(), ClusterError> {
        // Validation (deterministic, no side effects)
        if payment.amount <= 0 {
            return Err(ClusterError::MalformedMessage {
                reason: "Invalid amount".into(),
                source: None,
            });
        }

        // Each activity is journaled - replays skip completed steps
        self.set_status(OrderStatus::Processing).await?;
        self.record_payment(payment.id).await?;
        self.set_status(OrderStatus::Paid).await?;
        
        Ok(())
    }
}
```

### Visibility Modifiers

```rust
#[entity_impl]
impl MyEntity {
    // Public: callable by external clients (default for #[rpc], #[workflow])
    #[rpc]
    #[public]
    pub async fn query(&self) -> Result<Data, ClusterError> { ... }

    // Protected: visible in the current trait and all entities that implement it
    #[activity]
    #[protected]
    pub async fn internal_update(&mut self, data: Data) -> Result<(), ClusterError> { ... }

    // Private: only callable within this entity (default for #[activity])
    #[activity]
    #[private]
    async fn do_mutation(&mut self) -> Result<(), ClusterError> { ... }
}
```

### Durable Workflows

Workflows survive crashes. On restart, the journal replays and completed activities return cached results:

```rust
#[workflow]
pub async fn checkout(&self, cart: Cart) -> Result<OrderId, ClusterError> {
    // If we crash after validate_inventory but before charge_payment,
    // on restart validate_inventory returns its cached result instantly
    self.validate_inventory(&cart).await?;
    
    let charge_id = self.charge_payment(&cart.total).await?;
    
    let order_id = self.create_order(&cart, &charge_id).await?;
    
    // Fire-and-forget notification (won't block workflow completion)
    self.send_confirmation_email(&order_id).await?;
    
    Ok(order_id)
}
```

### Durable Timers

```rust
use std::time::Duration;

#[workflow]
pub async fn delayed_reminder(&self, user_id: String) -> Result<(), ClusterError> {
    // Durable sleep - survives restarts, resumes where it left off
    self.sleep("reminder-delay", Duration::from_secs(3600)).await?;
    
    self.send_reminder(&user_id).await?;
    Ok(())
}
```

### Entity Traits (Composition)

Share behavior across entity types:

```rust
// Define a trait
#[entity_trait]
#[derive(Clone)]
pub struct Auditable;

#[entity_trait_impl]
#[state(AuditState)]
impl Auditable {
    fn init(&self) -> Result<AuditState, ClusterError> {
        Ok(AuditState::default())
    }

    // Use #[protected] so entities using this trait can call it
    #[activity]
    #[protected]
    pub async fn log_action(&mut self, action: String) -> Result<(), ClusterError> {
        self.state.log.push(AuditEntry {
            action,
            timestamp: Utc::now(),
        });
        Ok(())
    }

    #[rpc]
    pub async fn get_audit_log(&self) -> Result<Vec<AuditEntry>, ClusterError> {
        Ok(self.state.log.clone())
    }
}

// Use trait in entity
#[entity_impl(traits(Auditable))]
#[state(UserState)]
impl User {
    #[workflow]
    pub async fn update_email(&self, email: String) -> Result<(), ClusterError> {
        self.do_update_email(email.clone()).await?;
        
        // Call trait method
        self.log_action(format!("email_updated:{}", email)).await?;
        
        Ok(())
    }
    
    #[activity]
    async fn do_update_email(&mut self, email: String) -> Result<(), ClusterError> {
        self.state.email = email;
        Ok(())
    }
}
```

### Entity Configuration

```rust
#[entity(
    name = "user",                    // Custom entity type name
    shard_group = "premium",          // Shard group for isolation
    max_idle_time_secs = 300,         // Eviction timeout (default: 60)
    mailbox_capacity = 50,            // Message queue size (default: 100)
    concurrency = 4,                  // Parallel request handling (default: 1)
)]
#[derive(Clone)]
struct User;
```

### Self-Scheduling

Entities can schedule messages to themselves:

```rust
#[workflow]
pub async fn start_timeout(&self, timeout_secs: u64) -> Result<(), ClusterError> {
    if let Some(client) = self.self_client() {
        let deliver_at = Utc::now() + chrono::Duration::seconds(timeout_secs as i64);
        let entity_id = self.entity_id().clone();
        
        client.notify_at(&entity_id, "handle_timeout", &(), deliver_at).await?;
    }
    Ok(())
}

#[workflow]
pub async fn handle_timeout(&self) -> Result<(), ClusterError> {
    self.on_timeout().await
}
```

### Singletons

Cluster-wide unique instances:

```rust
use cruster::singleton::register_singleton;

register_singleton(&*sharding, "leader-election", || async {
    loop {
        // This runs on exactly one node
        perform_leader_duties().await;
        tokio::time::sleep(Duration::from_secs(10)).await;
    }
}).await?;
```

## Testing

### TestCluster

```rust
use cruster::testing::TestCluster;
use cruster::types::EntityId;

#[tokio::test]
async fn test_counter_increment() {
    // Basic cluster (in-memory)
    let cluster = TestCluster::new().await;
    
    // Or with workflow support (durable context)
    let cluster = TestCluster::with_workflow_support().await;
    
    // Register entity and get typed client
    let counter = Counter.register(cluster.sharding().clone()).await.unwrap();
    
    let entity_id = EntityId::new("test-1");
    let result = counter.increment(&entity_id, &10i64).await.unwrap();
    assert_eq!(result, 10);
    
    let result = counter.get(&entity_id).await.unwrap();
    assert_eq!(result, 10);
}
```

### Client Methods

```rust
// Request-response
let result: Response = client.send(&entity_id, "method", &request).await?;

// Fire-and-forget
client.notify(&entity_id, "method", &request).await?;

// Persisted (at-least-once delivery)
let result: Response = client.send_persisted(&entity_id, "method", &request, Uninterruptible::Server).await?;

// Scheduled delivery
client.notify_at(&entity_id, "method", &request, deliver_at).await?;
```

## Production Deployment

### Multi-Node Cluster

```rust
use cruster::config::ShardingConfig;
use cruster::sharding_impl::ShardingImpl;

let config = ShardingConfig {
    runner_address: "10.0.0.1:9000".parse()?,
    shards_per_group: 2048,
    entity_max_idle_time: Duration::from_secs(300),
    ..Default::default()
};

let sharding = ShardingImpl::new(
    config,
    postgres_pool,
    etcd_runner_storage,
    grpc_runners,
).await?;

sharding.register_entity(Arc::new(MyEntity)).await?;
sharding.start().await?;
```

### Storage Requirements

**PostgreSQL** - State persistence, message storage, workflow journals

**etcd** - Runner discovery, shard locks, health monitoring

### Configuration Reference

| Option | Default | Description |
|--------|---------|-------------|
| `shards_per_group` | 2048 | Shards per shard group |
| `entity_max_idle_time` | 60s | Idle timeout before eviction |
| `entity_mailbox_capacity` | 100 | Per-entity message queue size |
| `storage_poll_interval` | 500ms | Message storage polling frequency |
| `storage_message_max_retries` | 10 | Max delivery attempts |

## Architecture

```
┌─────────────────────────────────────────────────────────┐
│                       Clients                            │
└─────────────────────────┬───────────────────────────────┘
┌─────────────────────────────────────────────────────────┐
│                   Sharding Layer                         │
│         Consistent hashing + request routing             │
└─────────────────────────┬───────────────────────────────┘
          ┌───────────────┼───────────────┐
          ▼               ▼               ▼
    ┌──────────┐    ┌──────────┐    ┌──────────┐
    │ Runner 1 │    │ Runner 2 │    │ Runner 3 │
    │ Shards   │    │ Shards   │    │ Shards   │
    │  0-682   │    │ 683-1365 │    │1366-2047 │
    └────┬─────┘    └────┬─────┘    └────┬─────┘
         │               │               │
         └───────────────┴───────────────┘
         ┌───────────────┴───────────────┐
         ▼                               ▼
   ┌───────────┐                   ┌───────────┐
   │ PostgreSQL│                   │   etcd    │
   │  - State  │                   │ - Runners │
   │  - Journals│                  │ - Locks   │
   │  - Messages│                  │ - Health  │
   └───────────┘                   └───────────┘
```

## Examples

See [`examples/`](examples/) for complete examples:

- **cluster-tests** - E2E test suite covering all features
- **chess-cluster** - Distributed chess server with matchmaking

## License

MIT