zeal-sdk 1.0.5

Rust SDK for Zeal Integration Protocol (ZIP)
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
# Zeal Rust SDK

High-performance Rust SDK for the Zeal Integration Protocol (ZIP), enabling efficient third-party workflow runtime integration with the Zeal workflow editor.

## Prerequisites

⚠️ **Important**: A running Zeal server instance is required for the SDK to function. The SDK communicates with the Zeal server via REST APIs and WebSocket connections.

### Starting the Zeal Server

```bash
# Clone the Zeal repository
git clone https://github.com/offbit-ai/zeal.git
cd zeal

# Install dependencies
npm install

# Start the development server
npm run dev
# Or use the start script
./start-dev.sh
```

The Zeal server will be available at `http://localhost:3000` by default.

For detailed setup instructions, deployment options, and configuration, please refer to the [Zeal repository](https://github.com/offbit-ai/zeal).

## Features

- **Zero-copy JSON parsing** with `serde_json` and `simd-json`
- **Async/await support** with `tokio` and `futures`
- **WebSocket real-time communication** with `tokio-tungstenite`
- **HTTP/2 client** with `reqwest` and connection pooling
- **Structured logging** with `tracing` and OpenTelemetry support
- **Memory-efficient streaming** for large payloads
- **Built-in retry logic** with exponential backoff
- **Compile-time safety** with strong typing and error handling
- **Observable streams** with `futures-util` and custom stream combinators
- **Thread-safe concurrent operations** with `Arc` and `Mutex`

## Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
zeal-sdk = "1.0.0"

# For async runtime
tokio = { version = "1.0", features = ["full"] }

# For observables/streams (optional)
futures = "0.3"
```

## Quick Start

```rust
use zeal_sdk::{ZealClient, ClientConfig, NodeTemplate};
use tokio;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize client
    let client = ZealClient::new(ClientConfig {
        base_url: "http://localhost:3000".to_string(),
        ..Default::default()
    })?;

    // Register node templates
    let templates = vec![
        NodeTemplate {
            id: "data-processor".to_string(),
            type_name: "processor".to_string(),
            title: "Data Processor".to_string(),
            category: "Processing".to_string(),
            description: "Processes data efficiently".to_string(),
            // ... other fields
        }
    ];

    client.templates().register(
        "my-runtime",
        templates,
        None
    ).await?;

    // Create webhook subscription
    let subscription = client.create_subscription(SubscriptionOptions {
        port: Some(3001),
        namespace: Some("my-runtime".to_string()),
        events: vec!["workflow.*".to_string(), "node.*".to_string()],
        ..Default::default()
    })?;

    // Handle events with callback
    subscription.on_event(|event| async move {
        println!("Received event: {} - {}", event.event_type, event.data);
    }).await;

    // Start receiving events
    subscription.start().await?;

    Ok(())
}
```

## Core APIs

### Templates API

Register and manage node templates:

```rust
use zeal_sdk::templates::*;

// Register templates
let result = client.templates().register(
    "my-integration",
    vec![template],
    Some("http://my-server.com/webhook".to_string())
).await?;

// List templates
let templates = client.templates().list("my-integration").await?;

// Get specific template
let template = client.templates().get("template-id").await?;
```

### Orchestrator API

Programmatically create and modify workflows:

```rust
use zeal_sdk::orchestrator::*;

// Create workflow
let workflow = client.orchestrator().create_workflow(CreateWorkflowRequest {
    name: "My Workflow".to_string(),
    description: Some("Created via Rust SDK".to_string()),
    metadata: None,
}).await?;

// Add node
let node = client.orchestrator().add_node(AddNodeRequest {
    workflow_id: workflow.workflow_id,
    template_id: "template-id".to_string(),
    position: Position { x: 100.0, y: 100.0 },
    property_values: Some(serde_json::json!({
        "param1": "value1"
    })),
}).await?;

// Connect nodes
client.orchestrator().connect_nodes(ConnectNodesRequest {
    workflow_id: workflow.workflow_id,
    source: NodePort {
        node_id: "node1".to_string(),
        port_id: "output".to_string(),
    },
    target: NodePort {
        node_id: "node2".to_string(),
        port_id: "input".to_string(),
    },
}).await?;
```

### Traces API

Submit execution trace data with high performance:

```rust
use zeal_sdk::traces::*;

// Create trace session
let session = client.traces().create_session(CreateTraceSessionRequest {
    workflow_id: "workflow-id".to_string(),
    execution_id: "exec-123".to_string(),
    metadata: Some(TraceMetadata {
        trigger: Some("manual".to_string()),
        environment: Some("production".to_string()),
        tags: vec!["batch-job".to_string()],
    }),
}).await?;

// Submit events (batched for efficiency)
let events = vec![
    TraceEvent {
        timestamp: chrono::Utc::now().timestamp_millis(),
        node_id: "node-id".to_string(),
        event_type: TraceEventType::Output,
        data: TraceData {
            size: 1024,
            data_type: "application/json".to_string(),
            preview: Some(serde_json::json!({"processed": 1000})),
            full_data: None,
        },
        duration: Some(std::time::Duration::from_millis(150)),
        ..Default::default()
    }
];

client.traces().submit_events(&session.session_id, events).await?;

// Complete session
client.traces().complete_session(
    &session.session_id,
    TraceStatus::Completed
).await?;
```

### Events API

Real-time bidirectional communication:

```rust
use zeal_sdk::events::*;
use futures_util::StreamExt;

// Connect to WebSocket
let mut event_stream = client.events().connect("workflow-id").await?;

// Handle incoming events
tokio::spawn(async move {
    while let Some(event) = event_stream.next().await {
        match event {
            Ok(ZealEvent::NodeExecuting { node_id, .. }) => {
                println!("Node {} is executing", node_id);
            }
            Ok(ZealEvent::NodeCompleted { node_id, result, .. }) => {
                println!("Node {} completed: {:?}", node_id, result);
            }
            Err(e) => eprintln!("WebSocket error: {}", e),
        }
    }
});

// Send events
client.events().send_runtime_event(RuntimeEvent {
    event_type: RuntimeEventType::NodeExecutionStart,
    workflow_id: "workflow-id".to_string(),
    data: serde_json::json!({
        "nodeId": "node-123",
        "timestamp": chrono::Utc::now().timestamp_millis()
    }),
}).await?;
```

## Observable Streams

Process events with powerful stream combinators:

```rust
use zeal_sdk::observables::*;
use futures_util::{StreamExt, TryStreamExt};

// Create subscription and get observable stream
let subscription = client.create_subscription(SubscriptionOptions::default())?;
let stream = subscription.as_observable().await?;

// Filter and transform events
let error_stream = stream
    .filter_map(|event| async move {
        if event.event_type.contains("error") {
            Some(ErrorEvent {
                id: event.id,
                error: event.data.get("error").cloned()?,
                timestamp: event.timestamp,
            })
        } else {
            None
        }
    })
    .take(100) // Limit to first 100 errors
    .collect::<Vec<_>>()
    .await;

// Subscribe to specific event types
let node_events = stream
    .filter(|event| async move {
        matches!(event.event_type.as_str(), "node.executed" | "node.failed")
    })
    .for_each(|event| async {
        println!("Node event: {:#?}", event);
    })
    .await;

// Advanced stream processing
use futures_util::stream;

let processed_stream = stream
    .buffer_unordered(10) // Process up to 10 events concurrently
    .filter_map(|result| async move {
        match result {
            Ok(event) => Some(process_event(event).await),
            Err(e) => {
                eprintln!("Stream error: {}", e);
                None
            }
        }
    })
    .take_while(|processed| {
        let should_continue = processed.is_ok();
        async move { should_continue }
    });
```

## Advanced Features

### Connection Pooling and Performance

```rust
use zeal_sdk::{ClientConfig, PerformanceConfig};

let client = ZealClient::new(ClientConfig {
    base_url: "http://localhost:3000".to_string(),
    performance: PerformanceConfig {
        max_connections_per_host: 50,
        connection_timeout: std::time::Duration::from_secs(10),
        request_timeout: std::time::Duration::from_secs(30),
        tcp_keepalive: Some(std::time::Duration::from_secs(60)),
        http2_prior_knowledge: true,
        ..Default::default()
    },
    ..Default::default()
})?;
```

### Batch Operations

```rust
// Batch trace events for optimal performance
use zeal_sdk::traces::TraceBatch;

let mut batch = TraceBatch::new(1000); // 1000 events per batch

for i in 0..10000 {
    batch.add_event(TraceEvent {
        // ... event data
    })?;
    
    // Auto-submit when batch is full
    if let Some(events) = batch.try_flush() {
        client.traces().submit_events(&session_id, events).await?;
    }
}

// Submit remaining events
if let Some(events) = batch.flush() {
    client.traces().submit_events(&session_id, events).await?;
}
```

### Structured Logging and Observability

```rust
use tracing::{info, error, instrument};
use zeal_sdk::telemetry::ZealTelemetry;

// Initialize telemetry
ZealTelemetry::init()?;

#[instrument(skip(client))]
async fn process_workflow(
    client: &ZealClient,
    workflow_id: &str
) -> Result<(), Box<dyn std::error::Error>> {
    info!("Starting workflow processing: {}", workflow_id);
    
    let session = client.traces().create_session(CreateTraceSessionRequest {
        workflow_id: workflow_id.to_string(),
        execution_id: uuid::Uuid::new_v4().to_string(),
        metadata: None,
    }).await?;
    
    info!("Created trace session: {}", session.session_id);
    
    // Processing logic here...
    
    Ok(())
}
```

### Custom Error Types

```rust
use zeal_sdk::errors::*;

match client.templates().get("invalid-id").await {
    Ok(template) => println!("Template: {:#?}", template),
    Err(ZealError::NotFound { resource, id }) => {
        eprintln!("Template '{}' not found", id);
    }
    Err(ZealError::NetworkError { source, retryable }) => {
        eprintln!("Network error: {} (retryable: {})", source, retryable);
        if retryable {
            // Implement retry logic
        }
    }
    Err(ZealError::ValidationError { field, message }) => {
        eprintln!("Validation error in '{}': {}", field, message);
    }
    Err(e) => eprintln!("Other error: {}", e),
}
```

## Performance Benchmarks

The Rust SDK is designed for high-performance applications:

- **Memory usage**: ~2MB baseline, efficient streaming for large payloads
- **CPU efficiency**: Zero-copy JSON parsing, async I/O
- **Throughput**: 50,000+ events/second on modern hardware
- **Latency**: Sub-millisecond event processing overhead
- **Concurrent connections**: 1000+ WebSocket connections per instance

## Examples

See the [examples](examples/) directory for complete working examples:

- [Basic Integration]examples/basic-integration.rs
- [High-Performance Runtime]examples/performance-runtime.rs
- [Stream Processing]examples/stream-processing.rs
- [Batch Operations]examples/batch-operations.rs
- [Custom Error Handling]examples/error-handling.rs
- [Telemetry Integration]examples/telemetry.rs

## Platform Support

- Linux (x86_64, aarch64)
- macOS (x86_64, Apple Silicon)
- Windows (x86_64)

## License

Apache-2.0