Compare commits
9 Commits
adopt_ASG_
...
6da64092ca
| Author | SHA1 | Date | |
|---|---|---|---|
| 6da64092ca | |||
| 809aea454b | |||
| c5a70edd57 | |||
| b0acee053c | |||
| c25c6a8a43 | |||
| 34a6d19303 | |||
| 8ada1ca49c | |||
| 60ae464ea2 | |||
| c20a266e72 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,3 +1,4 @@
|
|||||||
node_modules/
|
node_modules/
|
||||||
package.json
|
package.json
|
||||||
package-lock.json
|
package-lock.json
|
||||||
|
target/
|
||||||
46
AI_prompt.md
46
AI_prompt.md
@@ -143,7 +143,7 @@ Since I develop src folder before I adopt SDD_FRAMEWORK.md approach, can you che
|
|||||||
|
|
||||||
# ---------------------------------------------- 100 --------------------------------------------- #
|
# ---------------------------------------------- 100 --------------------------------------------- #
|
||||||
|
|
||||||
Check NATSBridge/docs folder I want to update the content of the following files according to ASG_Framework/ASG_Framework.md:
|
I updated src/NATSBridge.jl. Check and NATSBridge/docs folder I want to update the content of the following files according to ASG_Framework/ASG_Framework.md:
|
||||||
- NATSBridge/docs/requirements.md
|
- NATSBridge/docs/requirements.md
|
||||||
- NATSBridge/docs/specification.md
|
- NATSBridge/docs/specification.md
|
||||||
- NATSBridge/docs/ui-specification.md (you'll need to create this one)
|
- NATSBridge/docs/ui-specification.md (you'll need to create this one)
|
||||||
@@ -153,20 +153,50 @@ I'll do the other docs not listed here later myself.
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
now help me update the following fileaccording to ASG_Framework/ASG_Framework.md:
|
now help me update the following file according to ASG_Framework/ASG_Framework.md:
|
||||||
- NATSBridge/docs/specification.md
|
- NATSBridge/docs/specification.md
|
||||||
|
|
||||||
|
|
||||||
<!-- ------------------------------------------- 100 ------------------------------------------- -->
|
<!-- ------------------------------------------- 100 ------------------------------------------- -->
|
||||||
|
|
||||||
|
|
||||||
Check NATSBridge/docs folder. I would like to expand this package to include Dart support.
|
Check ./docs folder. I would like to expand this package (NATSBRIDGE) to include Rust support.
|
||||||
Can you update the content of the following files according to ASG_Framework/ASG_Framework.md:
|
Can you update the content of the following files according to /home/ton/docker-apps/sommpanion/ASG_Framework/ASG_Framework.md:
|
||||||
- NATSBridge/docs/requirements.md
|
- ./docs/requirements.md
|
||||||
- NATSBridge/docs/specification.md
|
- ./docs/specification.md
|
||||||
- NATSBridge/docs/walkthrough.md
|
- ./docs/walkthrough.md
|
||||||
- NATSBridge/docs/architecture.md
|
- ./docs/architecture.md
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<!-- ------------------------------------------- 100 ------------------------------------------- -->
|
||||||
|
|
||||||
|
I updated ./src/NATSBridge.jl. Use it as groundtruth. Check ./docs folder I want to update the content of the following files according to /home/ton/docker-apps/sommpanion/ASG_Framework/ASG_Framework.md:
|
||||||
|
- ./docs/requirements.md
|
||||||
|
- ./docs/specification.md
|
||||||
|
- ./docs/walkthrough.md
|
||||||
|
- ./docs/architecture.md
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Check the following files:
|
||||||
|
- ./docs/requirements.md
|
||||||
|
- ./docs/specification.md
|
||||||
|
- ./docs/architecture.md
|
||||||
|
- ./docs/walkthrough.md
|
||||||
|
I would like to expand this package (NATSBRIDGE) to include Rust support.
|
||||||
|
Now help me update Rust implementation of this package at ./src/natsbridge.rs.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
I want to build a client-side-rendering Dioxus-based chat webapp.
|
||||||
|
Dioxus version 0.7+ should be great.
|
||||||
|
I already populate the current folder for the project.
|
||||||
|
my server REST API endpoint is sommpanion.yiem.cc/agent-fronent/api/v1/chat but I didn't run the server yet. A message format is JSON string.
|
||||||
|
I just placed my custom package for encode and decode message at ./src/natsbridge.rs. smartsend() is for encoding and smartreceive() is for decoding.
|
||||||
|
you may also check the file /home/ton/docker-apps/sommpanion/NATSBridge/docs/walkthrough.md for more info about my package.
|
||||||
|
You can test whether Dioxus webapp can be build using this command "dx bundle --web --release --debug-symbols=false"
|
||||||
|
|||||||
1915
Cargo.lock
generated
Normal file
1915
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
31
Cargo.toml
Normal file
31
Cargo.toml
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
[package]
|
||||||
|
name = "natsbridge"
|
||||||
|
version = "1.2.0"
|
||||||
|
edition = "2021"
|
||||||
|
description = "Cross-platform bi-directional data bridge for NATS communication"
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
name = "natsbridge"
|
||||||
|
path = "src/natsbridge.rs"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
serde_json = "1"
|
||||||
|
tokio = { version = "1", features = ["full"] }
|
||||||
|
reqwest = { version = "0.12", features = ["json", "stream", "multipart"] }
|
||||||
|
uuid = { version = "1", features = ["v4", "serde"] }
|
||||||
|
base64 = "0.22"
|
||||||
|
chrono = { version = "0.4", features = ["serde"] }
|
||||||
|
async-trait = "0.1"
|
||||||
|
futures = "0.3"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tempfile = "3"
|
||||||
|
|
||||||
|
[[example]]
|
||||||
|
name = "smartsend_example"
|
||||||
|
path = "examples/smartsend_example.rs"
|
||||||
|
|
||||||
|
[[example]]
|
||||||
|
name = "smartreceive_example"
|
||||||
|
path = "examples/smartreceive_example.rs"
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
# Architecture Documentation: NATSBridge
|
# Architecture Documentation: NATSBridge
|
||||||
|
|
||||||
**Version**: 1.1.0
|
**Version**: 1.2.0
|
||||||
**Date**: 2026-03-23
|
**Date**: 2026-05-13
|
||||||
**Status**: Active
|
**Status**: Active
|
||||||
**Ground Truth**: [`src/NATSBridge.jl`](../src/NATSBridge.jl)
|
**Ground Truth**: [`src/NATSBridge.jl`](../src/NATSBridge.jl)
|
||||||
**Architecture Level**: C4 Container Level
|
**Architecture Level**: C4 Container Level
|
||||||
@@ -10,7 +10,7 @@
|
|||||||
|
|
||||||
## 1. Executive Summary
|
## 1. Executive Summary
|
||||||
|
|
||||||
This document defines the **blueprint** for NATSBridge - the cross-platform bi-directional data bridge that enables seamless communication between **Julia**, **JavaScript**, **Python**, **Dart**, and **MicroPython** applications using NATS as the message bus.
|
This document defines the **blueprint** for NATSBridge - the cross-platform bi-directional data bridge that enables seamless communication between **Julia**, **JavaScript**, **Python**, **Dart**, **Rust**, and **MicroPython** applications using NATS as the message bus.
|
||||||
|
|
||||||
This architecture document serves as the single source of truth for:
|
This architecture document serves as the single source of truth for:
|
||||||
- **System Structure**: How components fit together and interact
|
- **System Structure**: How components fit together and interact
|
||||||
@@ -57,6 +57,7 @@ flowchart TD
|
|||||||
JS_App[JavaScript Application<br/>Node.js/Browser]
|
JS_App[JavaScript Application<br/>Node.js/Browser]
|
||||||
Python_App[Python Application<br/>Desktop]
|
Python_App[Python Application<br/>Desktop]
|
||||||
Dart_App[Dart Application<br/>Desktop/Flutter/Web]
|
Dart_App[Dart Application<br/>Desktop/Flutter/Web]
|
||||||
|
Rust_App[Rust Application<br/>Server/Desktop]
|
||||||
MicroPython_App[MicroPython Device]
|
MicroPython_App[MicroPython Device]
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -64,12 +65,14 @@ flowchart TD
|
|||||||
JS_App -->|NATS| NATS_Server
|
JS_App -->|NATS| NATS_Server
|
||||||
Python_App -->|NATS| NATS_Server
|
Python_App -->|NATS| NATS_Server
|
||||||
Dart_App -->|NATS| NATS_Server
|
Dart_App -->|NATS| NATS_Server
|
||||||
|
Rust_App -->|NATS| NATS_Server
|
||||||
MicroPython_App -->|NATS| NATS_Server
|
MicroPython_App -->|NATS| NATS_Server
|
||||||
|
|
||||||
Julia_App -->|HTTP| File_Server
|
Julia_App -->|HTTP| File_Server
|
||||||
JS_App -->|HTTP| File_Server
|
JS_App -->|HTTP| File_Server
|
||||||
Python_App -->|HTTP| File_Server
|
Python_App -->|HTTP| File_Server
|
||||||
Dart_App -->|HTTP| File_Server
|
Dart_App -->|HTTP| File_Server
|
||||||
|
Rust_App -->|HTTP| File_Server
|
||||||
MicroPython_App -->|HTTP| File_Server
|
MicroPython_App -->|HTTP| File_Server
|
||||||
|
|
||||||
style NATS_Server fill:#fff3e0,stroke:#f57c00
|
style NATS_Server fill:#fff3e0,stroke:#f57c00
|
||||||
@@ -78,6 +81,7 @@ flowchart TD
|
|||||||
style JS_App fill:#e3f2fd,stroke:#2196f3
|
style JS_App fill:#e3f2fd,stroke:#2196f3
|
||||||
style Python_App fill:#e3f2fd,stroke:#2196f3
|
style Python_App fill:#e3f2fd,stroke:#2196f3
|
||||||
style Dart_App fill:#fff0f6,stroke:#e91e63
|
style Dart_App fill:#fff0f6,stroke:#e91e63
|
||||||
|
style Rust_App fill:#dea584,stroke:#e65100
|
||||||
style MicroPython_App fill:#fce4ec,stroke:#e91e63
|
style MicroPython_App fill:#fce4ec,stroke:#e91e63
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -85,28 +89,20 @@ flowchart TD
|
|||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
flowchart TD
|
flowchart TD
|
||||||
subgraph "Client Container"
|
subgraph "Client Container"
|
||||||
Julia_Module[Julia NATSBridge Module]
|
Julia_Module[Julia NATSBridge Module]
|
||||||
JS_Module[JavaScript NATSBridge Module]
|
JS_Module[JavaScript NATSBridge Module]
|
||||||
Python_Module[Python NATSBridge Module]
|
Python_Module[Python NATSBridge Module]
|
||||||
Dart_Module[Dart NATSBridge Module]
|
Dart_Module[Dart NATSBridge Module]
|
||||||
|
Rust_Module[Rust NATSBridge Module]
|
||||||
MicroPython_Module[MicroPython NATSBridge Module]
|
MicroPython_Module[MicroPython NATSBridge Module]
|
||||||
end
|
end
|
||||||
|
|
||||||
subgraph "NATS Container"
|
|
||||||
NATS_Client[NATS Client]
|
|
||||||
NATS_Broker[NATS Broker]
|
|
||||||
end
|
|
||||||
|
|
||||||
subgraph "File Server Container"
|
|
||||||
File_Client[HTTP Client]
|
|
||||||
File_Server[File Server]
|
|
||||||
end
|
|
||||||
|
|
||||||
Julia_Module --> NATS_Client
|
Julia_Module --> NATS_Client
|
||||||
JS_Module --> NATS_Client
|
JS_Module --> NATS_Client
|
||||||
Python_Module --> NATS_Client
|
Python_Module --> NATS_Client
|
||||||
Dart_Module --> NATS_Client
|
Dart_Module --> NATS_Client
|
||||||
|
Rust_Module --> NATS_Client
|
||||||
MicroPython_Module --> NATS_Client
|
MicroPython_Module --> NATS_Client
|
||||||
|
|
||||||
NATS_Client --> NATS_Broker
|
NATS_Client --> NATS_Broker
|
||||||
@@ -115,6 +111,7 @@ flowchart TD
|
|||||||
JS_Module --> File_Client
|
JS_Module --> File_Client
|
||||||
Python_Module --> File_Client
|
Python_Module --> File_Client
|
||||||
Dart_Module --> File_Client
|
Dart_Module --> File_Client
|
||||||
|
Rust_Module --> File_Client
|
||||||
MicroPython_Module --> File_Client
|
MicroPython_Module --> File_Client
|
||||||
|
|
||||||
File_Client --> File_Server
|
File_Client --> File_Server
|
||||||
@@ -123,6 +120,7 @@ flowchart TD
|
|||||||
style JS_Module fill:#e3f2fd,stroke:#2196f3
|
style JS_Module fill:#e3f2fd,stroke:#2196f3
|
||||||
style Python_Module fill:#e3f2fd,stroke:#2196f3
|
style Python_Module fill:#e3f2fd,stroke:#2196f3
|
||||||
style Dart_Module fill:#fff0f6,stroke:#e91e63
|
style Dart_Module fill:#fff0f6,stroke:#e91e63
|
||||||
|
style Rust_Module fill:#dea584,stroke:#e65100
|
||||||
style MicroPython_Module fill:#fce4ec,stroke:#e91e63
|
style MicroPython_Module fill:#fce4ec,stroke:#e91e63
|
||||||
style NATS_Broker fill:#fff3e0,stroke:#f57c00
|
style NATS_Broker fill:#fff3e0,stroke:#f57c00
|
||||||
style File_Server fill:#f3e5f5,stroke:#9c27b4
|
style File_Server fill:#f3e5f5,stroke:#9c27b4
|
||||||
@@ -139,36 +137,31 @@ flowchart TD
|
|||||||
Serialize[_serialize_data]
|
Serialize[_serialize_data]
|
||||||
Deserialize[_deserialize_data]
|
Deserialize[_deserialize_data]
|
||||||
|
|
||||||
BuildEnvelope[build_envelope]
|
EnvelopeToJson[envelope_to_json]
|
||||||
BuildPayload[build_payload]
|
|
||||||
|
|
||||||
PublishMessage[publish_message]
|
|
||||||
|
|
||||||
FileServerUpload[fileserver_upload_handler]
|
FileServerUpload[fileserver_upload_handler]
|
||||||
FileServerDownload[fileserver_download_handler]
|
FileServerDownload[fileserver_download_handler]
|
||||||
|
|
||||||
|
LogTrace[log_trace]
|
||||||
end
|
end
|
||||||
|
|
||||||
subgraph "Data Models"
|
subgraph "Data Models"
|
||||||
Payload[MsgPayloadV1 Struct]
|
Payload[msg_payload_v1 Struct]
|
||||||
Envelope[MsgEnvelopeV1 Struct]
|
Envelope[msg_envelope_v1 Struct]
|
||||||
end
|
end
|
||||||
|
|
||||||
SmartSend --> Serialize
|
SmartSend --> Serialize
|
||||||
SmartSend --> BuildEnvelope
|
SmartSend --> EnvelopeToJson
|
||||||
SmartSend --> BuildPayload
|
|
||||||
SmartSend --> PublishMessage
|
|
||||||
SmartSend --> FileServerUpload
|
SmartSend --> FileServerUpload
|
||||||
|
|
||||||
SmartReceive --> Deserialize
|
SmartReceive --> Deserialize
|
||||||
SmartReceive --> FileServerDownload
|
SmartReceive --> FileServerDownload
|
||||||
|
|
||||||
|
EnvelopeToJson --> Envelope
|
||||||
Serialize --> Payload
|
Serialize --> Payload
|
||||||
BuildEnvelope --> Envelope
|
|
||||||
BuildPayload --> Payload
|
|
||||||
|
|
||||||
style SmartSend fill:#d1fae5,stroke:#10b981
|
style SmartSend fill:#d1fae5,stroke:#10b981
|
||||||
style SmartReceive fill:#d1fae5,stroke:#10b981
|
style SmartReceive fill:#d1fae5,stroke:#10b981
|
||||||
style PublishMessage fill:#fef3c7,stroke:#f59e0b
|
|
||||||
style FileServerUpload fill:#fef3c7,stroke:#f59e0b
|
style FileServerUpload fill:#fef3c7,stroke:#f59e0b
|
||||||
style FileServerDownload fill:#fef3c7,stroke:#f59e0b
|
style FileServerDownload fill:#fef3c7,stroke:#f59e0b
|
||||||
```
|
```
|
||||||
@@ -181,15 +174,14 @@ flowchart TD
|
|||||||
|
|
||||||
| Component | Purpose | Platform Support |
|
| Component | Purpose | Platform Support |
|
||||||
|-----------|---------|------------------|
|
|-----------|---------|------------------|
|
||||||
| **smartsend** | Send data via NATS with automatic transport selection | All |
|
| **smartsend** | Send data via NATS with automatic transport selection, returns (envelope, json_string) for caller to publish | All |
|
||||||
| **smartreceive** | Receive and process NATS messages | All |
|
| **smartreceive** | Receive and process NATS messages from JSON string | All |
|
||||||
| **_serialize_data** | Serialize data according to payload type | All |
|
| **_serialize_data** | Serialize data according to payload type | All |
|
||||||
| **_deserialize_data** | Deserialize bytes to native data types | All |
|
| **_deserialize_data** | Deserialize bytes to native data types | All |
|
||||||
| **_build_envelope** | Build message envelope from payloads | All |
|
| **envelope_to_json** | Convert msg_envelope_v1 struct to JSON string | All |
|
||||||
| **_build_payload** | Build payload object from serialized data | All |
|
| **log_trace** | Log trace messages with correlation ID | All |
|
||||||
| **publish_message** | Publish message to NATS subject | All |
|
| **fileserver_upload_handler** | Upload large payloads to HTTP server | Desktop (Julia/JS/Python/Dart/Rust) |
|
||||||
| **fileserver_upload_handler** | Upload large payloads to HTTP server | Desktop (Julia/JS/Python/Dart) |
|
| **fileserver_download_handler** | Download payloads from HTTP server with exponential backoff | Desktop (Julia/JS/Python/Dart/Rust) |
|
||||||
| **fileserver_download_handler** | Download payloads from HTTP server | Desktop (Julia/JS/Python/Dart) |
|
|
||||||
|
|
||||||
### Data Flow
|
### Data Flow
|
||||||
|
|
||||||
@@ -211,7 +203,7 @@ flowchart TD
|
|||||||
|
|
||||||
H --> L[Build envelope]
|
H --> L[Build envelope]
|
||||||
L --> M[Convert to JSON]
|
L --> M[Convert to JSON]
|
||||||
M --> N[Publish to NATS]
|
M --> N[Return envelope + JSON to caller]
|
||||||
|
|
||||||
style A fill:#f9f9f9,stroke:#333
|
style A fill:#f9f9f9,stroke:#333
|
||||||
style N fill:#e0e7ff,stroke:#3b82f6
|
style N fill:#e0e7ff,stroke:#3b82f6
|
||||||
@@ -304,7 +296,7 @@ end
|
|||||||
|------|-------------|---------------|----------|-----------|
|
|------|-------------|---------------|----------|-----------|
|
||||||
| `text` | Plain text string | UTF-8 bytes | Base64 | All |
|
| `text` | Plain text string | UTF-8 bytes | Base64 | All |
|
||||||
| `dictionary` | JSON object | JSON string | Base64/JSON | All |
|
| `dictionary` | JSON object | JSON string | Base64/JSON | All |
|
||||||
| `arrowtable` | Apache Arrow IPC | Arrow IPC stream | Base64/arrow-ipc | Desktop (Julia/Python/Node.js/Dart) |
|
| `arrowtable` | Apache Arrow IPC | Arrow IPC stream | Base64/arrow-ipc | Desktop (Julia/Python/Node.js/Dart/Rust) |
|
||||||
| `jsontable` | JSON array of objects | JSON string | Base64/json | All (including Browser/Dart Web) |
|
| `jsontable` | JSON array of objects | JSON string | Base64/json | All (including Browser/Dart Web) |
|
||||||
| `image` | Binary image data | Raw bytes | Base64 | All |
|
| `image` | Binary image data | Raw bytes | Base64 | All |
|
||||||
| `audio` | Binary audio data | Raw bytes | Base64 | All |
|
| `audio` | Binary audio data | Raw bytes | Base64 | All |
|
||||||
@@ -437,11 +429,9 @@ end
|
|||||||
|
|
||||||
JavaScript uses async/await for non-blocking I/O:
|
JavaScript uses async/await for non-blocking I/O:
|
||||||
|
|
||||||
- **Class-based NATS Client**: Connection management with `keepAlive` support
|
|
||||||
- **Module-level Utilities**: Serialization functions
|
- **Module-level Utilities**: Serialization functions
|
||||||
- **Native ArrayBuffer**: Binary data handling (Browser) / Buffer (Node.js)
|
- **Native ArrayBuffer**: Binary data handling (Browser) / Buffer (Node.js)
|
||||||
- **Fetch API**: HTTP file server communication
|
- **Fetch API**: HTTP file server communication
|
||||||
- **Connection Pooling**: `NATSConnectionPool` for high-throughput scenarios
|
|
||||||
|
|
||||||
#### Node.js Implementation (natsbridge_ssr.js)
|
#### Node.js Implementation (natsbridge_ssr.js)
|
||||||
|
|
||||||
@@ -449,36 +439,6 @@ JavaScript uses async/await for non-blocking I/O:
|
|||||||
- **Apache Arrow IPC**: Full support via `apache-arrow`
|
- **Apache Arrow IPC**: Full support via `apache-arrow`
|
||||||
- **Buffer for binary data**: Native Node.js Buffer handling
|
- **Buffer for binary data**: Native Node.js Buffer handling
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Class-based NATS client with keepAlive support
|
|
||||||
class NATSClient {
|
|
||||||
constructor(url, keepAlive = false) {
|
|
||||||
this.url = url;
|
|
||||||
this.connection = null;
|
|
||||||
this.keepAlive = keepAlive;
|
|
||||||
}
|
|
||||||
|
|
||||||
async connect() {
|
|
||||||
if (this.connection) return this.connection;
|
|
||||||
this.connection = await nats.connect({ servers: this.url });
|
|
||||||
return this.connection;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Connection pool for managing multiple connections
|
|
||||||
class NATSConnectionPool {
|
|
||||||
constructor(url, maxSize = 10) {
|
|
||||||
this.url = url;
|
|
||||||
this.maxSize = maxSize;
|
|
||||||
this.connections = new Map();
|
|
||||||
}
|
|
||||||
|
|
||||||
async acquire() { /* Get or create connection */ }
|
|
||||||
release(client) { /* Return to pool or close */ }
|
|
||||||
async closeAll() { /* Close all pool connections */ }
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Browser Implementation (natsbridge_csr.js)
|
#### Browser Implementation (natsbridge_csr.js)
|
||||||
|
|
||||||
- **WebSocket NATS connections**: Uses `ws://` or `wss://` URLs via `nats.ws`
|
- **WebSocket NATS connections**: Uses `ws://` or `wss://` URLs via `nats.ws`
|
||||||
@@ -486,23 +446,6 @@ class NATSConnectionPool {
|
|||||||
- **Uint8Array for binary data**: Browser-compatible binary handling
|
- **Uint8Array for binary data**: Browser-compatible binary handling
|
||||||
- **Web Crypto API**: UUID generation via `crypto.getRandomValues()`
|
- **Web Crypto API**: UUID generation via `crypto.getRandomValues()`
|
||||||
|
|
||||||
```javascript
|
|
||||||
// Class-based NATS client with keepAlive support
|
|
||||||
class NATSClient {
|
|
||||||
constructor(url, keepAlive = false) {
|
|
||||||
this.url = url; // ws:// or wss://
|
|
||||||
this.connection = null;
|
|
||||||
this.keepAlive = keepAlive;
|
|
||||||
}
|
|
||||||
|
|
||||||
async connect() {
|
|
||||||
if (this.connection) return this.connection;
|
|
||||||
this.connection = await nats.connect({ servers: this.url });
|
|
||||||
return this.connection;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Python Architecture
|
### Python Architecture
|
||||||
|
|
||||||
Python uses classes for stateful operations:
|
Python uses classes for stateful operations:
|
||||||
@@ -590,6 +533,62 @@ DEFAULT_SIZE_THRESHOLD = 100_000 # 100KB
|
|||||||
MAX_PAYLOAD_SIZE = 50_000 # 50KB hard limit
|
MAX_PAYLOAD_SIZE = 50_000 # 50KB hard limit
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Rust Architecture
|
||||||
|
|
||||||
|
Rust leverages compile-time type safety and async runtimes:
|
||||||
|
|
||||||
|
- **Type-safe payloads**: Rust enum discriminates between `Text`, `Dictionary`, `ArrowTable`, `Binary`, etc.
|
||||||
|
- **serde serialization**: Automatic JSON deserialization via `#[derive(Serialize, Deserialize)]`
|
||||||
|
- **tokio runtime**: Efficient async I/O for NATS connections and HTTP file server operations
|
||||||
|
- **arrow2 integration**: Native Arrow IPC deserialization without intermediate format conversion
|
||||||
|
- **reqwest**: High-performance HTTP client with built-in TLS and connection pooling
|
||||||
|
- **Zero-copy patterns**: `Vec<u8>` passed directly to avoid unnecessary memory copies
|
||||||
|
- **Result<T, E>**: Idiomatic error handling with typed error types
|
||||||
|
|
||||||
|
```rust
|
||||||
|
// Type-safe payload enum (compile-time discrimination)
|
||||||
|
#[derive(Serialize, Deserialize, Clone)]
|
||||||
|
pub enum Payload {
|
||||||
|
Text(String),
|
||||||
|
Dictionary(serde_json::Value),
|
||||||
|
ArrowTable(Vec<u8>),
|
||||||
|
JsonTable(serde_json::Value),
|
||||||
|
Image(Vec<u8>),
|
||||||
|
Audio(Vec<u8>),
|
||||||
|
Video(Vec<u8>),
|
||||||
|
Binary(Vec<u8>),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Configuration via builder pattern
|
||||||
|
pub struct SmartsendOptions {
|
||||||
|
pub broker_url: String,
|
||||||
|
pub fileserver_url: String,
|
||||||
|
pub fileserver_upload_handler: Option<UploadHandler>,
|
||||||
|
pub size_threshold: usize,
|
||||||
|
pub correlation_id: String,
|
||||||
|
pub msg_purpose: String,
|
||||||
|
pub sender_name: String,
|
||||||
|
// ... other fields
|
||||||
|
}
|
||||||
|
|
||||||
|
// NATS client with tokio integration
|
||||||
|
let conn = nats::connect("nats://localhost:4222").await?;
|
||||||
|
|
||||||
|
// Subscribe and process messages
|
||||||
|
let mut sub = conn.subscribe("/agent/wine/api/v1/analyze")?;
|
||||||
|
for msg in sub.messages() {
|
||||||
|
let envelope: MsgEnvelopeV1 = serde_json::from_slice(&msg.payload)?;
|
||||||
|
// Type-safe access to payloads
|
||||||
|
for payload in &envelope.payloads {
|
||||||
|
match &payload.data {
|
||||||
|
Payload::ArrowTable(bytes) => { /* process */ },
|
||||||
|
Payload::Text(text) => { /* process */ },
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Scaling Architecture
|
## Scaling Architecture
|
||||||
@@ -740,7 +739,7 @@ MAX_PAYLOAD_SIZE = 50_000 # 50KB hard limit
|
|||||||
|----------|---------|-------------|
|
|----------|---------|-------------|
|
||||||
| `NATS_URL` | `nats://localhost:4222` | NATS server URL |
|
| `NATS_URL` | `nats://localhost:4222` | NATS server URL |
|
||||||
| `FILESERVER_URL` | `http://localhost:8080` | HTTP file server URL |
|
| `FILESERVER_URL` | `http://localhost:8080` | HTTP file server URL |
|
||||||
| `SIZE_THRESHOLD` | `1000000` | Size threshold in bytes |
|
| `SIZE_THRESHOLD` | `500000` | Size threshold in bytes (0.5MB) |
|
||||||
|
|
||||||
### Container Deployment
|
### Container Deployment
|
||||||
|
|
||||||
@@ -826,7 +825,7 @@ flowchart TD
|
|||||||
|
|
||||||
| Version | Supported Platforms |
|
| Version | Supported Platforms |
|
||||||
|---------|---------------------|
|
|---------|---------------------|
|
||||||
| v1.0.x | Julia 1.7+, Node.js 16+, Python 3.8+, Dart 2.17+, MicroPython 1.19+ |
|
| v1.0.x | Julia 1.7+, Node.js 16+, Python 3.8+, Dart 2.17+, Rust 1.70+, MicroPython 1.19+ |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -834,6 +833,16 @@ flowchart TD
|
|||||||
|
|
||||||
| Date | Version | Changes |
|
| Date | Version | Changes |
|
||||||
|------|---------|---------|
|
|------|---------|---------|
|
||||||
|
| 2026-05-13 | 1.3.0 | Added Rust support with tokio, serde, and arrow2 | All sections |
|
||||||
|
| - | - | Added Rust to C4 diagrams (context, container) | All sections |
|
||||||
|
| - | - | Added Rust platform-specific architecture section | specification.md:13 |
|
||||||
|
| - | - | Updated component table with Rust support | All sections |
|
||||||
|
| 2026-05-13 | 1.2.0 | Aligned with ground truth implementation (src/NATSBridge.jl) |
|
||||||
|
| - | - | Removed publish_message component (commented out in source) |
|
||||||
|
| - | - | Removed NATSClient and NATSConnectionPool classes (not in ground truth) |
|
||||||
|
| - | - | Updated component diagram to match actual module structure |
|
||||||
|
| - | - | Updated data flow to show smartsend returns JSON for caller to publish |
|
||||||
|
| - | - | Fixed SIZE_THRESHOLD default to 500,000 bytes |
|
||||||
| 2026-03-15 | 1.1.0 | JavaScript connection management |
|
| 2026-03-15 | 1.1.0 | JavaScript connection management |
|
||||||
| - | - | Added NATSClient with keepAlive support |
|
| - | - | Added NATSClient with keepAlive support |
|
||||||
| - | - | Added NATSConnectionPool for connection reuse |
|
| - | - | Added NATSConnectionPool for connection reuse |
|
||||||
@@ -865,6 +874,7 @@ flowchart TD
|
|||||||
| [`src/natsbridge_csr.js`](../src/natsbridge_csr.js) | Browser | JSON table only, WebSocket NATS | specification.md:2-19 (all sections) | FR-001 through FR-014, NFR-101 through NFR-405 |
|
| [`src/natsbridge_csr.js`](../src/natsbridge_csr.js) | Browser | JSON table only, WebSocket NATS | specification.md:2-19 (all sections) | FR-001 through FR-014, NFR-101 through NFR-405 |
|
||||||
| [`src/natsbridge.py`](../src/natsbridge.py) | Python | Arrow IPC, async/await | specification.md:2-19 (all sections) | FR-001 through FR-014, NFR-101 through NFR-405 |
|
| [`src/natsbridge.py`](../src/natsbridge.py) | Python | Arrow IPC, async/await | specification.md:2-19 (all sections) | FR-001 through FR-014, NFR-101 through NFR-405 |
|
||||||
| [`src/natsbridge.dart`](../src/natsbridge.dart) | Dart | Full feature set, Arrow IPC, async/await | specification.md:2-19 (all sections) | FR-001 through FR-014, NFR-101 through NFR-405 |
|
| [`src/natsbridge.dart`](../src/natsbridge.dart) | Dart | Full feature set, Arrow IPC, async/await | specification.md:2-19 (all sections) | FR-001 through FR-014, NFR-101 through NFR-405 |
|
||||||
|
| [`src/natsbridge.rs`](../src/natsbridge.rs) | Rust | Full feature set, Arrow IPC, async/await, type-safe | specification.md:2-19 (all sections) | FR-001 through FR-014, NFR-101 through NFR-405 |
|
||||||
| [`src/natsbridge_mpy.py`](../src/natsbridge_mpy.py) | MicroPython | Limited to direct transport | specification.md:2-19 (all sections) | FR-005, FR-006, FR-012 |
|
| [`src/natsbridge_mpy.py`](../src/natsbridge_mpy.py) | MicroPython | Limited to direct transport | specification.md:2-19 (all sections) | FR-005, FR-006, FR-012 |
|
||||||
|
|
||||||
### 16.3 External Dependencies
|
### 16.3 External Dependencies
|
||||||
@@ -887,6 +897,13 @@ flowchart TD
|
|||||||
| Dart | http | Latest | HTTP file server | specification.md:11 | FR-008, FR-009 |
|
| Dart | http | Latest | HTTP file server | specification.md:11 | FR-008, FR-009 |
|
||||||
| Dart | uuid | Latest | UUID generation | specification.md:11 | FR-011, NFR-401 |
|
| Dart | uuid | Latest | UUID generation | specification.md:11 | FR-011, NFR-401 |
|
||||||
| Dart | dart-arrow | Latest | Arrow IPC support | specification.md:11 | FR-002, FR-012 |
|
| Dart | dart-arrow | Latest | Arrow IPC support | specification.md:11 | FR-002, FR-012 |
|
||||||
|
| Rust | nats | Latest | NATS client | specification.md:11 | FR-013, FR-014 |
|
||||||
|
| Rust | serde | Latest | JSON serialization | specification.md:11 | FR-012, NFR-101, NFR-102 |
|
||||||
|
| Rust | serde_json | Latest | JSON handling | specification.md:11 | FR-012, NFR-101, NFR-102 |
|
||||||
|
| Rust | tokio | Latest | Async runtime | specification.md:11 | FR-013, FR-014 |
|
||||||
|
| Rust | reqwest | Latest | HTTP file server | specification.md:11 | FR-008, FR-009 |
|
||||||
|
| Rust | uuid | Latest | UUID generation | specification.md:11 | FR-011, NFR-401 |
|
||||||
|
| Rust | arrow2 | Latest | Arrow IPC support | specification.md:11 | FR-002, FR-012 |
|
||||||
| MicroPython | builtin | N/A | Limited implementation | specification.md:11 | FR-005, FR-006, FR-012 |
|
| MicroPython | builtin | N/A | Limited implementation | specification.md:11 | FR-005, FR-006, FR-012 |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# Requirements Document: NATSBridge
|
# Requirements Document: NATSBridge
|
||||||
|
|
||||||
**Version**: 1.0.0
|
**Version**: 1.2.0
|
||||||
**Date**: 2026-03-23
|
**Date**: 2026-05-13
|
||||||
**Status**: Active
|
**Status**: Active
|
||||||
**Ground Truth**: [`src/NATSBridge.jl`](../src/NATSBridge.jl)
|
**Ground Truth**: [`src/NATSBridge.jl`](../src/NATSBridge.jl)
|
||||||
|
|
||||||
@@ -11,7 +11,7 @@
|
|||||||
|
|
||||||
### 1.1 Business Goal
|
### 1.1 Business Goal
|
||||||
|
|
||||||
NATSBridge is a cross-platform, bi-directional data bridge that enables seamless communication between **Julia**, **JavaScript**, **Python**, **Dart**, and **MicroPython** applications using NATS as the message bus. The system implements the **Claim-Check pattern** for efficient handling of large payloads (>0.5MB) by uploading them to an HTTP file server instead of sending raw binary data over NATS.
|
NATSBridge is a cross-platform, bi-directional data bridge that enables seamless communication between **Julia**, **JavaScript**, **Python**, **Dart**, **Rust**, and **MicroPython** applications using NATS as the message bus. The system implements the **Claim-Check pattern** for efficient handling of large payloads (>0.5MB) by uploading them to an HTTP file server instead of sending raw binary data over NATS.
|
||||||
|
|
||||||
### 1.2 User Stories (with acceptance criteria)
|
### 1.2 User Stories (with acceptance criteria)
|
||||||
|
|
||||||
@@ -25,6 +25,7 @@ NATSBridge is a cross-platform, bi-directional data bridge that enables seamless
|
|||||||
| **As a Dart developer**, I want to send tabular data (List<Map>) to other platforms | P1 | JSON table format exchange works with Arrow IPC on desktop |
|
| **As a Dart developer**, I want to send tabular data (List<Map>) to other platforms | P1 | JSON table format exchange works with Arrow IPC on desktop |
|
||||||
| **As a Dart developer**, I want to send large files (>0.5MB) | P1 | Large files are automatically uploaded to file server and URLs are sent via NATS |
|
| **As a Dart developer**, I want to send large files (>0.5MB) | P1 | Large files are automatically uploaded to file server and URLs are sent via NATS |
|
||||||
| **As a MicroPython developer**, I want to send sensor data with minimal memory usage | P1 | Direct transport works for payloads <100KB on memory-constrained devices |
|
| **As a MicroPython developer**, I want to send sensor data with minimal memory usage | P1 | Direct transport works for payloads <100KB on memory-constrained devices |
|
||||||
|
| **As a Rust developer**, I want to send and receive messages with type-safe APIs | P1 | Rust implementation uses serde for serialization, tokio for async, and nats-io for NATS connectivity |
|
||||||
| **As a developer**, I want to send mixed-content messages (text + image + file) | P1 | NATSBridge accepts list of (dataname, data, type) tuples and handles each payload appropriately |
|
| **As a developer**, I want to send mixed-content messages (text + image + file) | P1 | NATSBridge accepts list of (dataname, data, type) tuples and handles each payload appropriately |
|
||||||
| **As a developer**, I want to receive multi-payload messages | P1 | NATSBridge returns payloads as list of tuples with correct types preserved |
|
| **As a developer**, I want to receive multi-payload messages | P1 | NATSBridge returns payloads as list of tuples with correct types preserved |
|
||||||
| **As a developer**, I want to use Plik as the file server | P2 | Plik one-shot upload mode is supported with upload ID and token handling |
|
| **As a developer**, I want to use Plik as the file server | P2 | Plik one-shot upload mode is supported with upload ID and token handling |
|
||||||
@@ -51,7 +52,7 @@ NATSBridge is a cross-platform, bi-directional data bridge that enables seamless
|
|||||||
|
|
||||||
| Feature | Description |
|
| Feature | Description |
|
||||||
|---------|-------------|
|
|---------|-------------|
|
||||||
| Cross-platform interoperability | Seamless data exchange between Julia, JavaScript, Python, Dart, and MicroPython |
|
| Cross-platform interoperability | Seamless data exchange between Julia, JavaScript, Python, Dart, Rust, and MicroPython |
|
||||||
| Intelligent transport selection | Direct transport (<0.5MB) vs Link transport (≥0.5MB) based on payload size |
|
| Intelligent transport selection | Direct transport (<0.5MB) vs Link transport (≥0.5MB) based on payload size |
|
||||||
| Unified API | Consistent `smartsend()` and `smartreceive()` functions across all platforms |
|
| Unified API | Consistent `smartsend()` and `smartreceive()` functions across all platforms |
|
||||||
| Multi-payload support | List of (dataname, data, type) tuples with appropriate handling |
|
| Multi-payload support | List of (dataname, data, type) tuples with appropriate handling |
|
||||||
@@ -88,6 +89,11 @@ NATSBridge is a cross-platform, bi-directional data bridge that enables seamless
|
|||||||
| Dart | nats | Latest stable |
|
| Dart | nats | Latest stable |
|
||||||
| Dart | http | Latest stable |
|
| Dart | http | Latest stable |
|
||||||
| Dart | uuid | Latest stable |
|
| Dart | uuid | Latest stable |
|
||||||
|
| Rust | nats | Latest stable |
|
||||||
|
| Rust | serde | Latest stable |
|
||||||
|
| Rust | serde_json | Latest stable |
|
||||||
|
| Rust | tokio | Latest stable |
|
||||||
|
| Rust | uuid | Latest stable |
|
||||||
|
|
||||||
### 2.4 Platform Compatibility
|
### 2.4 Platform Compatibility
|
||||||
|
|
||||||
@@ -98,6 +104,7 @@ NATSBridge is a cross-platform, bi-directional data bridge that enables seamless
|
|||||||
| Python | 3.8+ | pyarrow required for arrowtable support |
|
| Python | 3.8+ | pyarrow required for arrowtable support |
|
||||||
| Browser | Latest | No Arrow IPC (uses jsontable only) |
|
| Browser | Latest | No Arrow IPC (uses jsontable only) |
|
||||||
| Dart | 2.17+ | Supports Desktop (Dart SDK), Flutter (Dart SDK), and Web (Dart SDK) |
|
| Dart | 2.17+ | Supports Desktop (Dart SDK), Flutter (Dart SDK), and Web (Dart SDK) |
|
||||||
|
| Rust | 1.70+ | Full support with async/await, Arrow IPC on desktop |
|
||||||
| MicroPython | 1.19+ | Limited to direct transport |
|
| MicroPython | 1.19+ | Limited to direct transport |
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -118,8 +125,8 @@ NATSBridge is a cross-platform, bi-directional data bridge that enables seamless
|
|||||||
| **FR-010** | Exponential backoff retry | System shall implement exponential backoff with configurable retries (default: 5, base_delay: 100ms, max_delay: 5000ms) for file server download failures |
|
| **FR-010** | Exponential backoff retry | System shall implement exponential backoff with configurable retries (default: 5, base_delay: 100ms, max_delay: 5000ms) for file server download failures |
|
||||||
| **FR-011** | Correlation ID propagation | System shall propagate correlation IDs through all message processing steps |
|
| **FR-011** | Correlation ID propagation | System shall propagate correlation IDs through all message processing steps |
|
||||||
| **FR-012** | Message serialization | System shall serialize data types using Base64, JSON, or Arrow IPC encoding |
|
| **FR-012** | Message serialization | System shall serialize data types using Base64, JSON, or Arrow IPC encoding |
|
||||||
| **FR-013** | NATS publishing | System shall publish messages to NATS subjects |
|
| **FR-013** | NATS publishing | System shall return JSON string representation for caller to publish to NATS subjects (caller is responsible for actual NATS publish) |
|
||||||
| **FR-014** | NATS subscription | System shall receive and process NATS messages |
|
| **FR-014** | NATS subscription | System shall receive and process NATS messages by accepting JSON string from NATS payload |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -189,14 +196,14 @@ NATSBridge is a cross-platform, bi-directional data bridge that enables seamless
|
|||||||
|
|
||||||
| Type | Julia | JavaScript | Python | Dart | MicroPython | Description |
|
| Type | Julia | JavaScript | Python | Dart | MicroPython | Description |
|
||||||
|------|-------|------------|--------|------|-------------|-------------|
|
|------|-------|------------|--------|------|-------------|-------------|
|
||||||
| `text` | `String` | `string` | `str` | `String` | `str` | Plain text strings |
|
| `text` | `String` | `string` | `str` | `String` | `String` | `str` | Plain text strings |
|
||||||
| `dictionary` | `Dict`, `NamedTuple` | `Object`, `Array` | `dict`, `list` | `Map` | `dict` | JSON-serializable data |
|
| `dictionary` | `Dict`, `NamedTuple` | `Object`, `Array` | `dict`, `list` | `Map`, `serde_json::Value` | `String` | `dict` | JSON-serializable data |
|
||||||
| `arrowtable` | `DataFrame`, `Arrow.Table` | ❌ (Browser), ✅ (Node.js) | `pandas.DataFrame` | `List<Map>` (Desktop), `List<dynamic>` (Flutter) | ❌ | Tabular data (Arrow IPC) |
|
| `arrowtable` | `DataFrame`, `Arrow.Table` | ❌ (Browser), ✅ (Node.js) | `pandas.DataFrame` | `List<Map>` (Desktop), `List<dynamic>` (Flutter) | `arrow2::Table` | ❌ | Tabular data (Arrow IPC) |
|
||||||
| `jsontable` | `Vector{NamedTuple}` | `Array<Object>` | `list[dict]` | `List<Map>` | ⚠️ | Tabular data (JSON) - **Only table type in Browser** |
|
| `jsontable` | `Vector{NamedTuple}` | `Array<Object>` | `list[dict]` | `Vec<Map>` | ⚠️ | Tabular data (JSON) - **Only table type in Browser** |
|
||||||
| `image` | `Vector{UInt8}` | `Uint8Array`, `Buffer` | `bytes` | `Uint8List` | `bytearray` | Image binary data |
|
| `image` | `Vector{UInt8}` | `Uint8Array`, `Buffer` | `bytes` | `Uint8List` | `Vec<u8>` | `bytearray` | Image binary data |
|
||||||
| `audio` | `Vector{UInt8}` | `Uint8Array`, `Buffer` | `bytes` | `Uint8List` | `bytearray` | Audio binary data |
|
| `audio` | `Vector{UInt8}` | `Uint8Array`, `Buffer` | `bytes` | `Uint8List` | `Vec<u8>` | `bytearray` | Audio binary data |
|
||||||
| `video` | `Vector{UInt8}` | `Uint8Array`, `Buffer` | `bytes` | `Uint8List` | `bytearray` | Video binary data |
|
| `video` | `Vector{UInt8}` | `Uint8Array`, `Buffer` | `bytes` | `Uint8List` | `Vec<u8>` | `bytearray` | Video binary data |
|
||||||
| `binary` | `Vector{UInt8}`, `IOBuffer` | `Uint8Array`, `Buffer` | `bytes`, `bytearray` | `Uint8List` | `bytearray` | Generic binary data |
|
| `binary` | `Vector{UInt8}`, `IOBuffer` | `Uint8Array`, `Buffer` | `bytes`, `bytearray` | `Uint8List` | `Vec<u8>` | `bytearray` | Generic binary data |
|
||||||
|
|
||||||
### 6.2 Encoding Requirements
|
### 6.2 Encoding Requirements
|
||||||
|
|
||||||
@@ -220,6 +227,7 @@ NATSBridge is a cross-platform, bi-directional data bridge that enables seamless
|
|||||||
| Dart Desktop | 0.5MB | Default size threshold |
|
| Dart Desktop | 0.5MB | Default size threshold |
|
||||||
| Dart Flutter | 0.5MB | Default size threshold |
|
| Dart Flutter | 0.5MB | Default size threshold |
|
||||||
| Dart Web | 0.5MB | Default size threshold |
|
| Dart Web | 0.5MB | Default size threshold |
|
||||||
|
| Rust | 0.5MB | Default size threshold |
|
||||||
| MicroPython | 100KB | Lower threshold for memory constraints |
|
| MicroPython | 100KB | Lower threshold for memory constraints |
|
||||||
|
|
||||||
### 7.2 Maximum Payload Size
|
### 7.2 Maximum Payload Size
|
||||||
@@ -230,6 +238,7 @@ NATSBridge is a cross-platform, bi-directional data bridge that enables seamless
|
|||||||
| Dart Desktop | Unlimited | Limited by NATS server configuration |
|
| Dart Desktop | Unlimited | Limited by NATS server configuration |
|
||||||
| Dart Flutter | Unlimited | Limited by NATS server configuration |
|
| Dart Flutter | Unlimited | Limited by NATS server configuration |
|
||||||
| Dart Web | Unlimited | Limited by NATS server configuration |
|
| Dart Web | Unlimited | Limited by NATS server configuration |
|
||||||
|
| Rust | Unlimited | Limited by NATS server configuration |
|
||||||
| MicroPython | 50KB | Hard limit due to 256KB-1MB memory |
|
| MicroPython | 50KB | Hard limit due to 256KB-1MB memory |
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -324,11 +333,11 @@ NATSBridge is a cross-platform, bi-directional data bridge that enables seamless
|
|||||||
```julia
|
```julia
|
||||||
function smartsend(
|
function smartsend(
|
||||||
subject::String,
|
subject::String,
|
||||||
data::AbstractArray{Tuple{String, Any, String}};
|
data::AbstractArray{Tuple{String, T1, String}, 1};
|
||||||
broker_url::String = "nats://localhost:4222",
|
broker_url::String = DEFAULT_BROKER_URL,
|
||||||
fileserver_url::String = "http://localhost:8080",
|
fileserver_url::String = DEFAULT_FILESERVER_URL,
|
||||||
fileserver_upload_handler::Function = plik_oneshot_upload,
|
fileserver_upload_handler::Function = plik_oneshot_upload,
|
||||||
size_threshold::Int = 1_000_000,
|
size_threshold::Int = DEFAULT_SIZE_THRESHOLD,
|
||||||
correlation_id::String = string(uuid4()),
|
correlation_id::String = string(uuid4()),
|
||||||
msg_purpose::String = "chat",
|
msg_purpose::String = "chat",
|
||||||
sender_name::String = "NATSBridge",
|
sender_name::String = "NATSBridge",
|
||||||
@@ -336,18 +345,18 @@ function smartsend(
|
|||||||
receiver_id::String = "",
|
receiver_id::String = "",
|
||||||
reply_to::String = "",
|
reply_to::String = "",
|
||||||
reply_to_msg_id::String = "",
|
reply_to_msg_id::String = "",
|
||||||
is_publish::Bool = true,
|
|
||||||
NATS_connection::Union{NATS.Connection, Nothing} = nothing,
|
|
||||||
msg_id::String = string(uuid4()),
|
msg_id::String = string(uuid4()),
|
||||||
sender_id::String = string(uuid4())
|
sender_id::String = string(uuid4())
|
||||||
)::Tuple{msg_envelope_v1, String}
|
)::Tuple{msg_envelope_v1, String} where {T1<:Any}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**Note**: NATS publishing is the caller's responsibility. `smartsend` returns `(env::msg_envelope_v1, env_json_str::String)`.
|
||||||
|
|
||||||
### 11.2 smartreceive Signature
|
### 11.2 smartreceive Signature
|
||||||
|
|
||||||
```julia
|
```julia
|
||||||
function smartreceive(
|
function smartreceive(
|
||||||
msg::NATS.Msg;
|
msg_json_str::String;
|
||||||
fileserver_download_handler::Function = _fetch_with_backoff,
|
fileserver_download_handler::Function = _fetch_with_backoff,
|
||||||
max_retries::Int = 5,
|
max_retries::Int = 5,
|
||||||
base_delay::Int = 100,
|
base_delay::Int = 100,
|
||||||
@@ -355,6 +364,8 @@ function smartreceive(
|
|||||||
)::JSON.Object{String, Any}
|
)::JSON.Object{String, Any}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**Note**: Pass `String(nats_msg.payload)` from NATS subscription to `smartreceive`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 12. Deployment Requirements
|
## 12. Deployment Requirements
|
||||||
@@ -374,7 +385,7 @@ function smartreceive(
|
|||||||
|----------|---------|-------------|
|
|----------|---------|-------------|
|
||||||
| `NATS_URL` | `nats://localhost:4222` | NATS server URL |
|
| `NATS_URL` | `nats://localhost:4222` | NATS server URL |
|
||||||
| `FILESERVER_URL` | `http://localhost:8080` | HTTP file server URL |
|
| `FILESERVER_URL` | `http://localhost:8080` | HTTP file server URL |
|
||||||
| `SIZE_THRESHOLD` | `1000000` | Size threshold in bytes |
|
| `SIZE_THRESHOLD` | `500000` | Size threshold in bytes (0.5MB) |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -390,7 +401,7 @@ function smartreceive(
|
|||||||
|
|
||||||
| Version | Supported Platforms |
|
| Version | Supported Platforms |
|
||||||
|---------|---------------------|
|
|---------|---------------------|
|
||||||
| v1.0.x | Julia 1.7+, Node.js 16+, Python 3.8+, Dart 2.17+, Browser (latest), MicroPython 1.19+ |
|
| v1.0.x | Julia 1.7+, Node.js 16+, Python 3.8+, Dart 2.17+, Rust 1.70+, Browser (latest), MicroPython 1.19+ |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -398,6 +409,13 @@ function smartreceive(
|
|||||||
|
|
||||||
| Date | Version | Changes |
|
| Date | Version | Changes |
|
||||||
|------|---------|---------|
|
|------|---------|---------|
|
||||||
|
| 2026-05-13 | 1.2.0 | Aligned with ground truth implementation (src/NATSBridge.jl) |
|
||||||
|
| - | - | Fixed smartsend signature: removed is_publish, NATS_connection; added sender_name |
|
||||||
|
| - | - | Fixed smartreceive signature: takes msg_json_str::String instead of msg::NATS.Msg |
|
||||||
|
| - | - | Fixed size_threshold default from 1,000,000 to 500,000 |
|
||||||
|
| - | - | Updated FR-013/FR-014 to reflect caller responsibility for NATS publishing |
|
||||||
|
| - | - | Updated FR-008/FR-009 to include file path upload overload |
|
||||||
|
| - | - | Updated SIZE_THRESHOLD env var default to 500000 |
|
||||||
| 2026-03-23 | 1.0.0 | Updated to ASG Framework requirements structure |
|
| 2026-03-23 | 1.0.0 | Updated to ASG Framework requirements structure |
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -410,6 +428,7 @@ function smartreceive(
|
|||||||
- [`src/natsbridge.py`](../src/natsbridge.py) - Python implementation
|
- [`src/natsbridge.py`](../src/natsbridge.py) - Python implementation
|
||||||
- [`src/natsbridge.dart`](../src/natsbridge.dart) - Dart implementation
|
- [`src/natsbridge.dart`](../src/natsbridge.dart) - Dart implementation
|
||||||
- [`src/natsbridge_mpy.py`](../src/natsbridge_mpy.py) - MicroPython implementation
|
- [`src/natsbridge_mpy.py`](../src/natsbridge_mpy.py) - MicroPython implementation
|
||||||
|
- [`src/natsbridge.rs`](../src/natsbridge.rs) - Rust implementation
|
||||||
- [`README.md`](../README.md) - Project overview
|
- [`README.md`](../README.md) - Project overview
|
||||||
- [`docs/specification.md`](./specification.md) - Technical specification
|
- [`docs/specification.md`](./specification.md) - Technical specification
|
||||||
- [`docs/ui-specification.md`](./ui-specification.md) - UI specification
|
- [`docs/ui-specification.md`](./ui-specification.md) - UI specification
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# Specification: NATSBridge
|
# Specification: NATSBridge
|
||||||
|
|
||||||
**Version**: 1.1.0
|
**Version**: 1.2.0
|
||||||
**Date**: 2026-03-23
|
**Date**: 2026-05-13
|
||||||
**Status**: Active
|
**Status**: Active
|
||||||
**Ground Truth**: [`src/NATSBridge.jl`](../src/NATSBridge.jl)
|
**Ground Truth**: [`src/NATSBridge.jl`](../src/NATSBridge.jl)
|
||||||
**Specification Format**: JSON Schema + AsyncAPI
|
**Specification Format**: JSON Schema + AsyncAPI
|
||||||
@@ -10,7 +10,7 @@
|
|||||||
|
|
||||||
## 1. Technical Contract Overview
|
## 1. Technical Contract Overview
|
||||||
|
|
||||||
This document defines the **technical contract** for NATSBridge - the cross-platform bi-directional data bridge that enables seamless communication between **Julia**, **JavaScript**, **Python**, **Dart**, and **MicroPython** applications using NATS as the message bus.
|
This document defines the **technical contract** for NATSBridge - the cross-platform bi-directional data bridge that enables seamless communication between **Julia**, **JavaScript**, **Python**, **Dart**, **Rust**, and **MicroPython** applications using NATS as the message bus.
|
||||||
|
|
||||||
This specification serves as the single source of truth for:
|
This specification serves as the single source of truth for:
|
||||||
- **Inputs**: What data structures are accepted by `smartsend()`
|
- **Inputs**: What data structures are accepted by `smartsend()`
|
||||||
@@ -418,11 +418,11 @@ When `transport = "link"`, the `data` field contains a URL pointing to the uploa
|
|||||||
```julia
|
```julia
|
||||||
function smartsend(
|
function smartsend(
|
||||||
subject::String,
|
subject::String,
|
||||||
data::AbstractArray{Tuple{String, Any, String}};
|
data::AbstractArray{Tuple{String, T1, String}, 1};
|
||||||
broker_url::String = "nats://localhost:4222",
|
broker_url::String = DEFAULT_BROKER_URL,
|
||||||
fileserver_url::String = "http://localhost:8080",
|
fileserver_url::String = DEFAULT_FILESERVER_URL,
|
||||||
fileserver_upload_handler::Function = plik_oneshot_upload,
|
fileserver_upload_handler::Function = plik_oneshot_upload,
|
||||||
size_threshold::Int = 500_000,
|
size_threshold::Int = DEFAULT_SIZE_THRESHOLD,
|
||||||
correlation_id::String = string(uuid4()),
|
correlation_id::String = string(uuid4()),
|
||||||
msg_purpose::String = "chat",
|
msg_purpose::String = "chat",
|
||||||
sender_name::String = "NATSBridge",
|
sender_name::String = "NATSBridge",
|
||||||
@@ -430,13 +430,13 @@ function smartsend(
|
|||||||
receiver_id::String = "",
|
receiver_id::String = "",
|
||||||
reply_to::String = "",
|
reply_to::String = "",
|
||||||
reply_to_msg_id::String = "",
|
reply_to_msg_id::String = "",
|
||||||
is_publish::Bool = true,
|
|
||||||
NATS_connection::Union{NATS.Connection, Nothing} = nothing,
|
|
||||||
msg_id::String = string(uuid4()),
|
msg_id::String = string(uuid4()),
|
||||||
sender_id::String = string(uuid4())
|
sender_id::String = string(uuid4())
|
||||||
)::Tuple{msg_envelope_v1, String}
|
)::Tuple{msg_envelope_v1, String} where {T1<:Any}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**Note**: NATS publishing is the caller's responsibility. Returns `(env::msg_envelope_v1, env_json_str::String)`.
|
||||||
|
|
||||||
#### Python
|
#### Python
|
||||||
|
|
||||||
```python
|
```python
|
||||||
@@ -454,13 +454,13 @@ async def smartsend(
|
|||||||
receiver_id: str = "",
|
receiver_id: str = "",
|
||||||
reply_to: str = "",
|
reply_to: str = "",
|
||||||
reply_to_msg_id: str = "",
|
reply_to_msg_id: str = "",
|
||||||
is_publish: bool = True,
|
|
||||||
nats_connection: Any = None,
|
|
||||||
msg_id: str = None,
|
msg_id: str = None,
|
||||||
sender_id: str = None
|
sender_id: str = None
|
||||||
) -> Tuple[Dict, str]:
|
) -> Tuple[Dict, str]:
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**Note**: NATS publishing is the caller's responsibility.
|
||||||
|
|
||||||
#### JavaScript (Node.js)
|
#### JavaScript (Node.js)
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
@@ -479,14 +479,14 @@ async function smartsend(
|
|||||||
receiver_id?: string;
|
receiver_id?: string;
|
||||||
reply_to?: string;
|
reply_to?: string;
|
||||||
reply_to_msg_id?: string;
|
reply_to_msg_id?: string;
|
||||||
is_publish?: boolean;
|
|
||||||
nats_connection?: NATS.Connection;
|
|
||||||
msg_id?: string;
|
msg_id?: string;
|
||||||
sender_id?: string;
|
sender_id?: string;
|
||||||
}
|
}
|
||||||
): Promise<[Object, string]>;
|
): Promise<[Object, string]>;
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**Note**: NATS publishing is the caller's responsibility.
|
||||||
|
|
||||||
#### JavaScript (Browser)
|
#### JavaScript (Browser)
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
@@ -505,51 +505,27 @@ async function smartsend(
|
|||||||
receiver_id?: string;
|
receiver_id?: string;
|
||||||
reply_to?: string;
|
reply_to?: string;
|
||||||
reply_to_msg_id?: string;
|
reply_to_msg_id?: string;
|
||||||
is_publish?: boolean;
|
|
||||||
nats_connection?: NATSClient | NATS.Connection;
|
|
||||||
msg_id?: string;
|
msg_id?: string;
|
||||||
sender_id?: string;
|
sender_id?: string;
|
||||||
}
|
}
|
||||||
): Promise<[Object, string]>;
|
): Promise<[Object, string]>;
|
||||||
|
|
||||||
// NATSClient class for connection management
|
|
||||||
class NATSClient {
|
|
||||||
constructor(url: string, keepAlive?: boolean);
|
|
||||||
connect(): Promise<NATS.Connection>;
|
|
||||||
publish(subject: string, message: string, correlationId: string): Promise<void>;
|
|
||||||
close(): Promise<void>;
|
|
||||||
getConnection(): NATS.Connection | null;
|
|
||||||
isConnected(): boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
// NATSConnectionPool for managing multiple connections
|
|
||||||
class NATSConnectionPool {
|
|
||||||
constructor(url: string, maxSize?: number);
|
|
||||||
acquire(): Promise<NATSClient>;
|
|
||||||
release(client: NATSClient): void;
|
|
||||||
closeAll(): Promise<void>;
|
|
||||||
}
|
|
||||||
|
|
||||||
// publishMessage function for manual publishing
|
|
||||||
async function publishMessage(
|
|
||||||
brokerUrlOrClient: string | NATSClient | NATS.Connection,
|
|
||||||
subject: string,
|
|
||||||
message: string,
|
|
||||||
correlationId: string,
|
|
||||||
closeConnection?: boolean
|
|
||||||
): Promise<void>;
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**Note**: NATS publishing is the caller's responsibility.
|
||||||
|
|
||||||
#### MicroPython
|
#### MicroPython
|
||||||
|
|
||||||
```python
|
```python
|
||||||
def smartsend(
|
def smartsend(
|
||||||
subject: str,
|
subject: str,
|
||||||
data: List[Tuple[str, Any, str]],
|
data: List[Tuple[str, Any, str]],
|
||||||
|
size_threshold: int = 100_000, # Lower threshold for memory constraints
|
||||||
**kwargs
|
**kwargs
|
||||||
) -> Tuple[Dict, str]:
|
) -> Tuple[Dict, str]:
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**Note**: NATS publishing is the caller's responsibility.
|
||||||
|
|
||||||
#### Dart (Desktop/Flutter)
|
#### Dart (Desktop/Flutter)
|
||||||
|
|
||||||
```dart
|
```dart
|
||||||
@@ -567,12 +543,11 @@ Future<[Map<String, dynamic>, String]> smartsend(
|
|||||||
String receiverId = '',
|
String receiverId = '',
|
||||||
String replyTo = '',
|
String replyTo = '',
|
||||||
String replyToMsgId = '',
|
String replyToMsgId = '',
|
||||||
bool isPublish = true,
|
|
||||||
dynamic natsConnection,
|
|
||||||
String? msgId,
|
String? msgId,
|
||||||
String? senderId,
|
String? senderId,
|
||||||
}) async {
|
}) async {
|
||||||
// Returns [envelope, jsonString]
|
// Returns [envelope, jsonString]
|
||||||
|
// NATS publishing is caller's responsibility
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -593,22 +568,82 @@ Future<[Map<String, dynamic>, String]> smartsend(
|
|||||||
String receiverId = '',
|
String receiverId = '',
|
||||||
String replyTo = '',
|
String replyTo = '',
|
||||||
String replyToMsgId = '',
|
String replyToMsgId = '',
|
||||||
bool isPublish = true,
|
|
||||||
dynamic natsConnection,
|
|
||||||
String? msgId,
|
String? msgId,
|
||||||
String? senderId,
|
String? senderId,
|
||||||
}) async {
|
}) async {
|
||||||
// Returns [envelope, jsonString]
|
// Returns [envelope, jsonString]
|
||||||
|
// NATS publishing is caller's responsibility
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
#### Rust
|
||||||
|
|
||||||
|
```rust
|
||||||
|
pub async fn smartsend(
|
||||||
|
subject: &str,
|
||||||
|
data: &[(String, Payload, String)],
|
||||||
|
options: &SmartsendOptions,
|
||||||
|
) -> Result<(MsgEnvelopeV1, String), NatSBridgeError>
|
||||||
|
|
||||||
|
// SmartsendOptions struct
|
||||||
|
pub struct SmartsendOptions {
|
||||||
|
pub broker_url: String,
|
||||||
|
pub fileserver_url: String,
|
||||||
|
pub fileserver_upload_handler: Option<UploadHandler>,
|
||||||
|
pub size_threshold: usize,
|
||||||
|
pub correlation_id: String,
|
||||||
|
pub msg_purpose: String,
|
||||||
|
pub sender_name: String,
|
||||||
|
pub receiver_name: String,
|
||||||
|
pub receiver_id: String,
|
||||||
|
pub reply_to: String,
|
||||||
|
pub reply_to_msg_id: String,
|
||||||
|
pub msg_id: String,
|
||||||
|
pub sender_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Payload enum for type-safe data handling
|
||||||
|
#[derive(Serialize, Deserialize, Clone)]
|
||||||
|
pub enum Payload {
|
||||||
|
Text(String),
|
||||||
|
Dictionary(serde_json::Value),
|
||||||
|
ArrowTable(Vec<u8>),
|
||||||
|
JsonTable(serde_json::Value),
|
||||||
|
Image(Vec<u8>),
|
||||||
|
Audio(Vec<u8>),
|
||||||
|
Video(Vec<u8>),
|
||||||
|
Binary(Vec<u8>),
|
||||||
|
}
|
||||||
|
|
||||||
|
// MsgEnvelopeV1 struct (serde-serializable)
|
||||||
|
#[derive(Serialize, Deserialize, Clone)]
|
||||||
|
pub struct MsgEnvelopeV1 {
|
||||||
|
pub correlation_id: String,
|
||||||
|
pub msg_id: String,
|
||||||
|
pub timestamp: String,
|
||||||
|
pub send_to: String,
|
||||||
|
pub msg_purpose: String,
|
||||||
|
pub sender_name: String,
|
||||||
|
pub sender_id: String,
|
||||||
|
pub receiver_name: String,
|
||||||
|
pub receiver_id: String,
|
||||||
|
pub reply_to: String,
|
||||||
|
pub reply_to_msg_id: String,
|
||||||
|
pub broker_url: String,
|
||||||
|
pub metadata: serde_json::Value,
|
||||||
|
pub payloads: Vec<MsgPayloadV1>,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Note**: NATS publishing is the caller's responsibility. Returns `Result<(MsgEnvelopeV1, String), NatSBridgeError>`. Uses `serde` for JSON serialization.
|
||||||
|
|
||||||
### `smartreceive` Function Signature
|
### `smartreceive` Function Signature
|
||||||
|
|
||||||
#### Julia
|
#### Julia
|
||||||
|
|
||||||
```julia
|
```julia
|
||||||
function smartreceive(
|
function smartreceive(
|
||||||
msg::NATS.Msg;
|
msg_json_str::String; # Pass String(nats_msg.payload) from NATS subscription
|
||||||
fileserver_download_handler::Function = _fetch_with_backoff,
|
fileserver_download_handler::Function = _fetch_with_backoff,
|
||||||
max_retries::Int = 5,
|
max_retries::Int = 5,
|
||||||
base_delay::Int = 100,
|
base_delay::Int = 100,
|
||||||
@@ -616,11 +651,13 @@ function smartreceive(
|
|||||||
)::JSON.Object{String, Any}
|
)::JSON.Object{String, Any}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**Note**: Input is JSON string from NATS message payload, not NATS.Msg directly.
|
||||||
|
|
||||||
#### Python
|
#### Python
|
||||||
|
|
||||||
```python
|
```python
|
||||||
async def smartreceive(
|
async def smartreceive(
|
||||||
msg: Any,
|
msg_json_str: str, # JSON string from NATS message payload
|
||||||
fileserver_download_handler: Callable = fetch_with_backoff,
|
fileserver_download_handler: Callable = fetch_with_backoff,
|
||||||
max_retries: int = 5,
|
max_retries: int = 5,
|
||||||
base_delay: int = 100,
|
base_delay: int = 100,
|
||||||
@@ -628,11 +665,13 @@ async def smartreceive(
|
|||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**Note**: Input is JSON string from NATS message payload.
|
||||||
|
|
||||||
#### JavaScript (Node.js)
|
#### JavaScript (Node.js)
|
||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
async function smartreceive(
|
async function smartreceive(
|
||||||
msg: Object,
|
msg_json_str: string, // JSON string from NATS message payload
|
||||||
options?: {
|
options?: {
|
||||||
fileserver_download_handler?: Function;
|
fileserver_download_handler?: Function;
|
||||||
max_retries?: number;
|
max_retries?: number;
|
||||||
@@ -646,7 +685,7 @@ async function smartreceive(
|
|||||||
|
|
||||||
```typescript
|
```typescript
|
||||||
async function smartreceive(
|
async function smartreceive(
|
||||||
msg: Object,
|
msg_json_str: string, // JSON string from NATS message payload
|
||||||
options?: {
|
options?: {
|
||||||
fileserver_download_handler?: Function;
|
fileserver_download_handler?: Function;
|
||||||
max_retries?: number;
|
max_retries?: number;
|
||||||
@@ -656,17 +695,22 @@ async function smartreceive(
|
|||||||
): Promise<Object>;
|
): Promise<Object>;
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**Note**: Input is JSON string from NATS message payload.
|
||||||
|
|
||||||
#### MicroPython
|
#### MicroPython
|
||||||
|
|
||||||
```python
|
```python
|
||||||
def smartreceive(msg: Any, **kwargs) -> Dict[str, Any]:
|
def smartreceive(msg_json_str: str, **kwargs) -> Dict[str, Any]:
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**Note**: Input is JSON string from NATS message payload.
|
||||||
|
|
||||||
#### Dart (Desktop/Flutter)
|
#### Dart (Desktop/Flutter)
|
||||||
|
|
||||||
```dart
|
```dart
|
||||||
Future<Map<String, dynamic>> smartreceive(
|
Future<Map<String, dynamic>> smartreceive(
|
||||||
Map<String, dynamic> msg, {
|
Map<String, dynamic> msg_json_str, // JSON object from NATS message payload
|
||||||
|
{
|
||||||
Function? fileserverDownloadHandler,
|
Function? fileserverDownloadHandler,
|
||||||
int maxRetries = 5,
|
int maxRetries = 5,
|
||||||
int baseDelay = 100,
|
int baseDelay = 100,
|
||||||
@@ -680,7 +724,8 @@ Future<Map<String, dynamic>> smartreceive(
|
|||||||
|
|
||||||
```dart
|
```dart
|
||||||
Future<Map<String, dynamic>> smartreceive(
|
Future<Map<String, dynamic>> smartreceive(
|
||||||
Map<String, dynamic> msg, {
|
Map<String, dynamic> msg_json_str, // JSON object from NATS message payload
|
||||||
|
{
|
||||||
Function? fileserverDownloadHandler,
|
Function? fileserverDownloadHandler,
|
||||||
int maxRetries = 5,
|
int maxRetries = 5,
|
||||||
int baseDelay = 100,
|
int baseDelay = 100,
|
||||||
@@ -690,6 +735,25 @@ Future<Map<String, dynamic>> smartreceive(
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
#### Rust
|
||||||
|
|
||||||
|
```rust
|
||||||
|
pub async fn smartreceive(
|
||||||
|
msg_json_str: &str, // JSON string from NATS message payload
|
||||||
|
options: &SmartreceiveOptions,
|
||||||
|
) -> Result<MsgEnvelopeV1, NatSBridgeError>
|
||||||
|
|
||||||
|
// SmartreceiveOptions struct
|
||||||
|
pub struct SmartreceiveOptions {
|
||||||
|
pub fileserver_download_handler: Option<DownloadHandler>,
|
||||||
|
pub max_retries: u32,
|
||||||
|
pub base_delay: u64,
|
||||||
|
pub max_delay: u64,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Note**: Input is JSON string from NATS message payload. Returns `Result<MsgEnvelopeV1, NatSBridgeError>`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## File Server Interface
|
## File Server Interface
|
||||||
@@ -703,6 +767,12 @@ function fileserver_upload_handler(
|
|||||||
dataname::String,
|
dataname::String,
|
||||||
data::Vector{UInt8}
|
data::Vector{UInt8}
|
||||||
)::Dict{String, Any}
|
)::Dict{String, Any}
|
||||||
|
|
||||||
|
# Overload: Upload file from disk
|
||||||
|
function fileserver_upload_handler(
|
||||||
|
file_server_url::String,
|
||||||
|
filepath::String
|
||||||
|
)::Dict{String, Any}
|
||||||
```
|
```
|
||||||
|
|
||||||
**Return Format**:
|
**Return Format**:
|
||||||
@@ -796,6 +866,18 @@ function fileserver_download_handler(
|
|||||||
| File server download | ✅ Supported | HTTP/HTTPS |
|
| File server download | ✅ Supported | HTTP/HTTPS |
|
||||||
| Size threshold | 500KB | Configurable |
|
| Size threshold | 500KB | Configurable |
|
||||||
|
|
||||||
|
### Rust
|
||||||
|
|
||||||
|
| Feature | Status | Notes |
|
||||||
|
|---------|--------|-------|
|
||||||
|
| Arrow IPC | ✅ Supported | Requires `arrow2` crate |
|
||||||
|
| JSON table | ✅ Supported | Uses `serde_json` |
|
||||||
|
| File server upload | ✅ Supported | HTTP/HTTPS via `reqwest` |
|
||||||
|
| File server download | ✅ Supported | HTTP/HTTPS via `reqwest` with retry |
|
||||||
|
| Size threshold | 500KB | Configurable |
|
||||||
|
| Async runtime | ✅ Supported | Uses `tokio` for async I/O |
|
||||||
|
| Type safety | ✅ Supported | Compile-time type checking via Rust enums |
|
||||||
|
|
||||||
### MicroPython
|
### MicroPython
|
||||||
|
|
||||||
| Feature | Status | Notes |
|
| Feature | Status | Notes |
|
||||||
@@ -818,6 +900,7 @@ function fileserver_download_handler(
|
|||||||
| [`src/natsbridge_csr.js`](../src/natsbridge_csr.js) | Browser | JSON table only, WebSocket NATS | Client-side rendering |
|
| [`src/natsbridge_csr.js`](../src/natsbridge_csr.js) | Browser | JSON table only, WebSocket NATS | Client-side rendering |
|
||||||
| [`src/natsbridge.py`](../src/natsbridge.py) | Python | Arrow IPC, async/await | Desktop Python |
|
| [`src/natsbridge.py`](../src/natsbridge.py) | Python | Arrow IPC, async/await | Desktop Python |
|
||||||
| [`src/natsbridge.dart`](../src/natsbridge.dart) | Dart | Full feature set, Arrow IPC, async/await | Desktop/Flutter/Web |
|
| [`src/natsbridge.dart`](../src/natsbridge.dart) | Dart | Full feature set, Arrow IPC, async/await | Desktop/Flutter/Web |
|
||||||
|
| [`src/natsbridge.rs`](../src/natsbridge.rs) | Rust | Full feature set, Arrow IPC, async/await, type-safe | Uses tokio + serde + arrow2 |
|
||||||
| [`src/natsbridge_mpy.py`](../src/natsbridge_mpy.py) | MicroPython | Limited to direct transport | Memory-constrained |
|
| [`src/natsbridge_mpy.py`](../src/natsbridge_mpy.py) | MicroPython | Limited to direct transport | Memory-constrained |
|
||||||
|
|
||||||
### Browser Implementation Notes
|
### Browser Implementation Notes
|
||||||
@@ -832,16 +915,16 @@ The browser implementation ([`src/natsbridge_csr.js`](../src/natsbridge_csr.js))
|
|||||||
|
|
||||||
### Payload Type Availability by Platform
|
### Payload Type Availability by Platform
|
||||||
|
|
||||||
| Payload Type | Julia | Node.js | Browser | Python | Dart | MicroPython |
|
| Payload Type | Julia | Node.js | Browser | Python | Dart | Rust | MicroPython |
|
||||||
|--------------|-------|---------|---------|--------|------|-------------|
|
|--------------|-------|---------|---------|--------|------|------|-------------|
|
||||||
| `text` | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
| `text` | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||||
| `dictionary` | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
| `dictionary` | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||||
| `arrowtable` | ✅ | ✅ | ❌ | ✅ | ✅ | ❌ |
|
| `arrowtable` | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ |
|
||||||
| `jsontable` | ✅ | ✅ | ✅ | ✅ | ✅ | ⚠️ |
|
| `jsontable` | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ⚠️ |
|
||||||
| `image` | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
| `image` | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||||
| `audio` | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
| `audio` | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||||
| `video` | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
| `video` | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||||
| `binary` | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
| `binary` | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -979,6 +1062,13 @@ flowchart TD
|
|||||||
| Dart | http | Latest | HTTP file server |
|
| Dart | http | Latest | HTTP file server |
|
||||||
| Dart | uuid | Latest | UUID generation |
|
| Dart | uuid | Latest | UUID generation |
|
||||||
| Dart | dart-arrow | Latest | Arrow IPC support (Desktop/Flutter) |
|
| Dart | dart-arrow | Latest | Arrow IPC support (Desktop/Flutter) |
|
||||||
|
| Rust | nats | Latest | NATS client |
|
||||||
|
| Rust | serde | Latest | JSON serialization |
|
||||||
|
| Rust | serde_json | Latest | JSON handling |
|
||||||
|
| Rust | tokio | Latest | Async runtime |
|
||||||
|
| Rust | reqwest | Latest | HTTP file server |
|
||||||
|
| Rust | uuid | Latest | UUID generation |
|
||||||
|
| Rust | arrow2 | Latest | Arrow IPC support |
|
||||||
| MicroPython | builtin | N/A | Limited implementation |
|
| MicroPython | builtin | N/A | Limited implementation |
|
||||||
|
|
||||||
### Optional Dependencies
|
### Optional Dependencies
|
||||||
@@ -1031,6 +1121,8 @@ flowchart TD
|
|||||||
| [`src/natsbridge_ssr.js`](../src/natsbridge_ssr.js) | Node.js | Arrow IPC, async/await | FR-001 through FR-014, NFR-101 through NFR-405 |
|
| [`src/natsbridge_ssr.js`](../src/natsbridge_ssr.js) | Node.js | Arrow IPC, async/await | FR-001 through FR-014, NFR-101 through NFR-405 |
|
||||||
| [`src/natsbridge_csr.js`](../src/natsbridge_csr.js) | Browser | JSON table only, WebSocket NATS | FR-001 through FR-014, NFR-101 through NFR-405 |
|
| [`src/natsbridge_csr.js`](../src/natsbridge_csr.js) | Browser | JSON table only, WebSocket NATS | FR-001 through FR-014, NFR-101 through NFR-405 |
|
||||||
| [`src/natsbridge.py`](../src/natsbridge.py) | Python | Arrow IPC, async/await | FR-001 through FR-014, NFR-101 through NFR-405 |
|
| [`src/natsbridge.py`](../src/natsbridge.py) | Python | Arrow IPC, async/await | FR-001 through FR-014, NFR-101 through NFR-405 |
|
||||||
|
| [`src/natsbridge.dart`](../src/natsbridge.dart) | Dart | Full feature set, Arrow IPC, async/await | FR-001 through FR-014, NFR-101 through NFR-405 |
|
||||||
|
| [`src/natsbridge.rs`](../src/natsbridge.rs) | Rust | Full feature set, Arrow IPC, async/await, type-safe | FR-001 through FR-014, NFR-101 through NFR-405 |
|
||||||
| [`src/natsbridge_mpy.py`](../src/natsbridge_mpy.py) | MicroPython | Limited to direct transport | FR-005, FR-006, FR-012 |
|
| [`src/natsbridge_mpy.py`](../src/natsbridge_mpy.py) | MicroPython | Limited to direct transport | FR-005, FR-006, FR-012 |
|
||||||
|
|
||||||
### 20.3 External Dependencies
|
### 20.3 External Dependencies
|
||||||
@@ -1049,6 +1141,17 @@ flowchart TD
|
|||||||
| Python | nats-py | Latest | NATS client | FR-013, FR-014 |
|
| Python | nats-py | Latest | NATS client | FR-013, FR-014 |
|
||||||
| Python | aiohttp | Latest | HTTP file server | FR-008, FR-009 |
|
| Python | aiohttp | Latest | HTTP file server | FR-008, FR-009 |
|
||||||
| Python | pyarrow | Latest | Arrow IPC support | FR-002, FR-012 |
|
| Python | pyarrow | Latest | Arrow IPC support | FR-002, FR-012 |
|
||||||
|
| Dart | nats | Latest | NATS client | FR-013, FR-014 |
|
||||||
|
| Dart | http | Latest | HTTP file server | FR-008, FR-009 |
|
||||||
|
| Dart | uuid | Latest | UUID generation | FR-011, NFR-401 |
|
||||||
|
| Dart | dart-arrow | Latest | Arrow IPC support | FR-002, FR-012 |
|
||||||
|
| Rust | nats | Latest | NATS client | FR-013, FR-014 |
|
||||||
|
| Rust | serde | Latest | JSON serialization | FR-012, NFR-101, NFR-102 |
|
||||||
|
| Rust | serde_json | Latest | JSON handling | FR-012, NFR-101, NFR-102 |
|
||||||
|
| Rust | tokio | Latest | Async runtime | FR-013, FR-014 |
|
||||||
|
| Rust | reqwest | Latest | HTTP file server | FR-008, FR-009 |
|
||||||
|
| Rust | uuid | Latest | UUID generation | FR-011, NFR-401 |
|
||||||
|
| Rust | arrow2 | Latest | Arrow IPC support | FR-002, FR-012 |
|
||||||
| MicroPython | builtin | N/A | Limited implementation | FR-005, FR-006 |
|
| MicroPython | builtin | N/A | Limited implementation | FR-005, FR-006 |
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -1057,6 +1160,12 @@ flowchart TD
|
|||||||
|
|
||||||
| Date | Version | Changes | Requirement ID(s) |
|
| Date | Version | Changes | Requirement ID(s) |
|
||||||
|------|---------|---------|-------------------|
|
|------|---------|---------|-------------------|
|
||||||
|
| 2026-05-13 | 1.2.0 | Aligned with ground truth implementation (src/NATSBridge.jl) | All |
|
||||||
|
| - | - | Updated smartsend signatures: removed is_publish, nats_connection; added sender_name | FR-001 through FR-014 |
|
||||||
|
| - | - | Updated smartreceive signatures: takes msg_json_str::String instead of msg | FR-001 through FR-014 |
|
||||||
|
| - | - | Removed publishMessage function and NATSClient/NATSConnectionPool classes from browser section | FR-013, FR-014 |
|
||||||
|
| - | - | Added plik_oneshot_upload(filepath) overload to file server interface | FR-008, FR-009 |
|
||||||
|
| - | - | Fixed SIZE_THRESHOLD default to 500,000 bytes | FR-003, FR-004 |
|
||||||
| 2026-03-23 | 1.1.0 | Updated to ASG Framework specification guidelines | All |
|
| 2026-03-23 | 1.1.0 | Updated to ASG Framework specification guidelines | All |
|
||||||
| 2026-03-15 | 1.1.0 | Browser connection management | FR-001 through FR-014 |
|
| 2026-03-15 | 1.1.0 | Browser connection management | FR-001 through FR-014 |
|
||||||
| 2026-03-13 | 1.0.0 | Initial specification | FR-001 through FR-014, NFR-101 through NFR-405 |
|
| 2026-03-13 | 1.0.0 | Initial specification | FR-001 through FR-014, NFR-101 through NFR-405 |
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# Walkthrough: NATSBridge
|
# Walkthrough: NATSBridge
|
||||||
|
|
||||||
**Version**: 1.0.0
|
**Version**: 1.2.0
|
||||||
**Date**: 2026-03-23
|
**Date**: 2026-05-13
|
||||||
**Status**: Active
|
**Status**: Active
|
||||||
**Ground Truth**: [`src/NATSBridge.jl`](../src/NATSBridge.jl)
|
**Ground Truth**: [`src/NATSBridge.jl`](../src/NATSBridge.jl)
|
||||||
|
|
||||||
@@ -9,7 +9,7 @@
|
|||||||
|
|
||||||
## 1. Executive Summary
|
## 1. Executive Summary
|
||||||
|
|
||||||
This document provides the **end-to-end trace** for NATSBridge - the cross-platform bi-directional data bridge that enables seamless communication between **Julia**, **JavaScript**, **Python**, **Dart**, and **MicroPython** applications using NATS as the message bus.
|
This document provides the **end-to-end trace** for NATSBridge - the cross-platform bi-directional data bridge that enables seamless communication between **Julia**, **JavaScript**, **Python**, **Dart**, **Rust**, and **MicroPython** applications using NATS as the message bus.
|
||||||
|
|
||||||
This walkthrough serves as the primary onboarding guide for new developers and explains:
|
This walkthrough serves as the primary onboarding guide for new developers and explains:
|
||||||
- **User scenarios** - Real-world use cases from developer perspective
|
- **User scenarios** - Real-world use cases from developer perspective
|
||||||
@@ -213,23 +213,25 @@ NATSBridge builds the message envelope:
|
|||||||
- **reply_to**: Tells backend where to send response
|
- **reply_to**: Tells backend where to send response
|
||||||
- **payloads array**: Contains all data with metadata for proper handling
|
- **payloads array**: Contains all data with metadata for proper handling
|
||||||
|
|
||||||
#### Step 5: Publish to NATS
|
#### Step 5: Publish to NATS (Caller's Responsibility)
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
await NATSBridge.NATSClient.connect("ws://localhost:4222");
|
// NATS publishing is the caller's responsibility
|
||||||
await NATSBridge.NATSClient.publish("/agent/wine/api/v1/prompt", msgJson);
|
const conn = await NATS.connect({ servers: "ws://localhost:4222" });
|
||||||
|
await conn.publish("/agent/wine/api/v1/prompt", msgJson);
|
||||||
```
|
```
|
||||||
|
|
||||||
**Rationale**:
|
**Rationale**:
|
||||||
- NATS provides low-latency message delivery
|
- NATS provides low-latency message delivery
|
||||||
- JSON format ensures cross-platform compatibility
|
- JSON format ensures cross-platform compatibility
|
||||||
|
- `smartsend()` returns `(env, msgJson)` - caller handles publishing
|
||||||
|
|
||||||
#### Step 6: Julia Backend Receives Message
|
#### Step 6: Julia Backend Receives Message
|
||||||
|
|
||||||
```julia
|
```julia
|
||||||
# Julia backend
|
# Julia backend
|
||||||
msg = NATS.subscription.next() # Get message from NATS
|
nats_msg = NATS.subscription.next() # Get message from NATS
|
||||||
env = smartreceive(msg)
|
env = smartreceive(String(nats_msg.payload))
|
||||||
|
|
||||||
# env["payloads"] is now:
|
# env["payloads"] is now:
|
||||||
# [
|
# [
|
||||||
@@ -355,8 +357,8 @@ const response = await plikOneshotUpload(
|
|||||||
|
|
||||||
```julia
|
```julia
|
||||||
# Julia backend
|
# Julia backend
|
||||||
msg = NATS.subscription.next()
|
nats_msg = NATS.subscription.next()
|
||||||
env = smartreceive(msg)
|
env = smartreceive(String(nats_msg.payload))
|
||||||
|
|
||||||
# NATSBridge automatically:
|
# NATSBridge automatically:
|
||||||
# 1. Extracts URL from payload
|
# 1. Extracts URL from payload
|
||||||
@@ -428,8 +430,8 @@ arrow_bytes = buf.getvalue()
|
|||||||
|
|
||||||
```julia
|
```julia
|
||||||
# Julia backend
|
# Julia backend
|
||||||
msg = NATS.subscription.next()
|
nats_msg = NATS.subscription.next()
|
||||||
env = smartreceive(msg)
|
env = smartreceive(String(nats_msg.payload))
|
||||||
|
|
||||||
# env["payloads"][1] is now:
|
# env["payloads"][1] is now:
|
||||||
# ("data", DataFrame with id, name, score columns, "arrowtable")
|
# ("data", DataFrame with id, name, score columns, "arrowtable")
|
||||||
@@ -461,7 +463,155 @@ env, msg_json = smartsend(
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## User Scenario 4: MicroPython Device
|
## User Scenario 4: Rust Service with Type-Safe API
|
||||||
|
|
||||||
|
### Scenario Description
|
||||||
|
|
||||||
|
A Rust service needs to process messages from a Julia analytics pipeline and send typed results back. The Rust implementation leverages compile-time type safety via Rust enums and serde for serialization.
|
||||||
|
|
||||||
|
### Step-by-Step Flow
|
||||||
|
|
||||||
|
#### Step 1: Rust Service Receives Message
|
||||||
|
|
||||||
|
```rust
|
||||||
|
// Rust service - using tokio async runtime
|
||||||
|
use natsbridge::{smartreceive, MsgEnvelopeV1};
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() {
|
||||||
|
let conn = nats::connect("nats://localhost:4222").unwrap();
|
||||||
|
|
||||||
|
// Subscribe and receive messages
|
||||||
|
let mut sub = conn.subscribe("/agent/wine/api/v1/analyze").unwrap();
|
||||||
|
|
||||||
|
for msg in sub.messages() {
|
||||||
|
let envelope: MsgEnvelopeV1 = smartreceive(
|
||||||
|
&String::from_utf8_lossy(&msg.payload),
|
||||||
|
&Default::default(),
|
||||||
|
).await.unwrap();
|
||||||
|
|
||||||
|
// Type-safe payload access
|
||||||
|
for payload in &envelope.payloads {
|
||||||
|
match &payload.data {
|
||||||
|
Payload::ArrowTable(arrow_bytes) => {
|
||||||
|
// Process Arrow IPC data using arrow2
|
||||||
|
let table = arrow2::io::ipc::read::Reader::new(
|
||||||
|
std::io::Cursor::new(arrow_bytes.clone()),
|
||||||
|
);
|
||||||
|
println!("Received {} rows", table.len());
|
||||||
|
},
|
||||||
|
Payload::Text(text) => {
|
||||||
|
println!("Message: {}", text);
|
||||||
|
},
|
||||||
|
_ => println!("Received {} bytes of {} data",
|
||||||
|
match &payload.data {
|
||||||
|
Payload::Binary(b) => b.len(),
|
||||||
|
_ => 0,
|
||||||
|
},
|
||||||
|
payload.payload_type),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Rationale**:
|
||||||
|
- **Type-safe payloads**: Rust enum discriminates between payload types at compile time
|
||||||
|
- **serde serialization**: Automatic JSON deserialization to `MsgEnvelopeV1`
|
||||||
|
- **tokio runtime**: Efficient async I/O for NATS and HTTP operations
|
||||||
|
- **arrow2 integration**: Direct Arrow IPC deserialization without intermediate format
|
||||||
|
|
||||||
|
#### Step 2: Rust Service Sends Processed Results
|
||||||
|
|
||||||
|
```rust
|
||||||
|
// Rust service sends results back with mixed payload types
|
||||||
|
use natsbridge::{smartsend, Payload, SmartsendOptions};
|
||||||
|
|
||||||
|
let results_df = /* processed Arrow table */;
|
||||||
|
let result_bytes = /* serialize to Arrow IPC */;
|
||||||
|
|
||||||
|
let (envelope, json_str) = smartsend(
|
||||||
|
"/agent/wine/api/v1/results",
|
||||||
|
&[
|
||||||
|
(
|
||||||
|
"results".to_string(),
|
||||||
|
Payload::ArrowTable(result_bytes),
|
||||||
|
"arrowtable".to_string(),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"summary".to_string(),
|
||||||
|
Payload::Text("Analysis complete: 1500 rows processed".to_string()),
|
||||||
|
"text".to_string(),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
&SmartsendOptions {
|
||||||
|
broker_url: "nats://localhost:4222".to_string(),
|
||||||
|
reply_to: "/python/worker/v1/results".to_string(),
|
||||||
|
msg_purpose: "chat".to_string(),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
).await?;
|
||||||
|
|
||||||
|
// Caller publishes to NATS
|
||||||
|
conn.publish("/agent/wine/api/v1/results", &json_str)?;
|
||||||
|
```
|
||||||
|
|
||||||
|
**Rationale**:
|
||||||
|
- **Builder pattern**: `SmartsendOptions` provides clean configuration
|
||||||
|
- **Enum-based payloads**: Type safety prevents sending incorrect data types
|
||||||
|
- **Default options**: sensible defaults reduce boilerplate
|
||||||
|
- **Result<T, E>**: idiomatic Rust error handling
|
||||||
|
|
||||||
|
#### Step 3: Python/Julia Receives Rust Response
|
||||||
|
|
||||||
|
```python
|
||||||
|
# Python backend receives Rust response
|
||||||
|
env = await smartreceive(str(nats_msg.payload))
|
||||||
|
|
||||||
|
# env["payloads"][0] is now:
|
||||||
|
# ("results", arrow_table_data, "arrowtable")
|
||||||
|
# env["payloads"][1] is now:
|
||||||
|
# ("summary", "Analysis complete: 1500 rows processed", "text")
|
||||||
|
```
|
||||||
|
|
||||||
|
**Rationale**:
|
||||||
|
- **Cross-platform parity**: Rust envelope matches other platform envelopes exactly
|
||||||
|
- **Same JSON wire format**: No protocol translation needed
|
||||||
|
- **Type preservation**: Arrow IPC and text types preserved across all platforms
|
||||||
|
|
||||||
|
#### Step 4: Large File Transfer from Rust
|
||||||
|
|
||||||
|
```rust
|
||||||
|
// Rust service sends large binary file via link transport
|
||||||
|
let large_file_data: Vec<u8> = std::fs::read("/data/large_dataset.parquet")?;
|
||||||
|
|
||||||
|
let (envelope, json_str) = smartsend(
|
||||||
|
"/agent/wine/api/v1/upload",
|
||||||
|
&[
|
||||||
|
(
|
||||||
|
"dataset".to_string(),
|
||||||
|
Payload::Binary(large_file_data),
|
||||||
|
"binary".to_string(),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
&SmartsendOptions {
|
||||||
|
broker_url: "nats://localhost:4222".to_string(),
|
||||||
|
fileserver_url: "http://localhost:8080".to_string(),
|
||||||
|
size_threshold: 500_000, // 0.5MB triggers link transport
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
).await?;
|
||||||
|
```
|
||||||
|
|
||||||
|
**Rationale**:
|
||||||
|
- **Automatic transport selection**: Same 0.5MB threshold as other desktop platforms
|
||||||
|
- **reqwest integration**: Efficient HTTP client for file server upload/download
|
||||||
|
- **Exponential backoff**: Built-in retry with configurable parameters
|
||||||
|
- **Zero-copy where possible**: `Vec<u8>` passed directly without intermediate copies
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## User Scenario 5: MicroPython Device
|
||||||
|
|
||||||
### Scenario Description
|
### Scenario Description
|
||||||
|
|
||||||
@@ -512,8 +662,8 @@ payload_b64 = base64.b64encode(json_bytes).decode('ascii')
|
|||||||
|
|
||||||
```python
|
```python
|
||||||
# Python backend
|
# Python backend
|
||||||
msg = await nats_consumer.next()
|
nats_msg = await nats_consumer.next()
|
||||||
env = await smartreceive(msg)
|
env = await smartreceive(str(nats_msg.payload))
|
||||||
|
|
||||||
# env["payloads"][0] is now:
|
# env["payloads"][0] is now:
|
||||||
# ("data", {"temperature": 25.5, "humidity": 60.0, ...}, "dictionary")
|
# ("data", {"temperature": 25.5, "humidity": 60.0, ...}, "dictionary")
|
||||||
@@ -526,7 +676,7 @@ env = await smartreceive(msg)
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## User Scenario 5: Cross-Platform Chat with Mixed Payloads
|
## User Scenario 6: Cross-Platform Chat with Mixed Payloads
|
||||||
|
|
||||||
### Scenario Description
|
### Scenario Description
|
||||||
|
|
||||||
@@ -561,8 +711,8 @@ const [env, msgJson] = await NATSBridge.smartsend(
|
|||||||
|
|
||||||
```python
|
```python
|
||||||
# Python (Backend)
|
# Python (Backend)
|
||||||
msg = await nats_consumer.next()
|
nats_msg = await nats_consumer.next()
|
||||||
env = await smartreceive(msg)
|
env = await smartreceive(str(nats_msg.payload))
|
||||||
|
|
||||||
# env["payloads"] is now:
|
# env["payloads"] is now:
|
||||||
# [
|
# [
|
||||||
@@ -580,8 +730,8 @@ env = await smartreceive(msg)
|
|||||||
|
|
||||||
```julia
|
```julia
|
||||||
# Julia (Backend)
|
# Julia (Backend)
|
||||||
msg = NATS.subscription.next()
|
nats_msg = NATS.subscription.next()
|
||||||
env = smartreceive(msg)
|
env = smartreceive(String(nats_msg.payload))
|
||||||
|
|
||||||
# env["payloads"] is now:
|
# env["payloads"] is now:
|
||||||
# [
|
# [
|
||||||
@@ -726,7 +876,7 @@ log_trace(correlation_id, "Published to NATS")
|
|||||||
|----------|---------|-------------|
|
|----------|---------|-------------|
|
||||||
| `NATS_URL` | `nats://localhost:4222` | NATS server URL |
|
| `NATS_URL` | `nats://localhost:4222` | NATS server URL |
|
||||||
| `FILESERVER_URL` | `http://localhost:8080` | HTTP file server URL |
|
| `FILESERVER_URL` | `http://localhost:8080` | HTTP file server URL |
|
||||||
| `SIZE_THRESHOLD` | `1000000` | Size threshold in bytes |
|
| `SIZE_THRESHOLD` | `500000` | Size threshold in bytes (0.5MB) |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -761,6 +911,7 @@ log_trace(correlation_id, "Published to NATS")
|
|||||||
| [`src/natsbridge_csr.js`](../src/natsbridge_csr.js) | Browser | JSON table only, WebSocket NATS | specification.md:2-19 (all sections) |
|
| [`src/natsbridge_csr.js`](../src/natsbridge_csr.js) | Browser | JSON table only, WebSocket NATS | specification.md:2-19 (all sections) |
|
||||||
| [`src/natsbridge.py`](../src/natsbridge.py) | Python | Arrow IPC, async/await | specification.md:2-19 (all sections) |
|
| [`src/natsbridge.py`](../src/natsbridge.py) | Python | Arrow IPC, async/await | specification.md:2-19 (all sections) |
|
||||||
| [`src/natsbridge.dart`](../src/natsbridge.dart) | Dart | Full feature set, Arrow IPC, async/await | specification.md:2-19 (all sections) |
|
| [`src/natsbridge.dart`](../src/natsbridge.dart) | Dart | Full feature set, Arrow IPC, async/await | specification.md:2-19 (all sections) |
|
||||||
|
| [`src/natsbridge.rs`](../src/natsbridge.rs) | Rust | Full feature set, Arrow IPC, async/await, type-safe | specification.md:2-19 (all sections) |
|
||||||
| [`src/natsbridge_mpy.py`](../src/natsbridge_mpy.py) | MicroPython | Limited to direct transport | specification.md:2-19 (all sections) |
|
| [`src/natsbridge_mpy.py`](../src/natsbridge_mpy.py) | MicroPython | Limited to direct transport | specification.md:2-19 (all sections) |
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -769,6 +920,13 @@ log_trace(correlation_id, "Published to NATS")
|
|||||||
|
|
||||||
| Date | Version | Changes | Specification Reference |
|
| Date | Version | Changes | Specification Reference |
|
||||||
|------|---------|---------|------------------------|
|
|------|---------|---------|------------------------|
|
||||||
|
| 2026-05-13 | 1.3.0 | Added Rust support with tokio, serde, and arrow2 | All sections |
|
||||||
|
| - | - | Added Rust user scenario (User Scenario 4) | specification.md:11 (Rust API) |
|
||||||
|
| - | - | Updated scenario numbering (MicroPython → Scenario 5, Cross-Platform → Scenario 6) | All sections |
|
||||||
|
| 2026-05-13 | 1.2.0 | Aligned with ground truth implementation (src/NATSBridge.jl) | All sections |
|
||||||
|
| - | - | Updated smartreceive calls to use String(nats_msg.payload) pattern | All sections |
|
||||||
|
| - | - | Removed NATSClient.publish() calls (caller responsible for NATS publishing) | All sections |
|
||||||
|
| - | - | Removed is_publish and nats_connection parameter references | All sections |
|
||||||
| 2026-03-23 | 1.0.0 | Updated to ASG Framework walkthrough guidelines | All sections |
|
| 2026-03-23 | 1.0.0 | Updated to ASG Framework walkthrough guidelines | All sections |
|
||||||
| 2026-03-13 | 1.0.0 | Initial walkthrough documentation | specification.md:2-19 (all sections) |
|
| 2026-03-13 | 1.0.0 | Initial walkthrough documentation | specification.md:2-19 (all sections) |
|
||||||
|
|
||||||
|
|||||||
96
examples/smartreceive_example.rs
Normal file
96
examples/smartreceive_example.rs
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
use natsbridge::{smartreceive, SmartreceiveOptions};
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() {
|
||||||
|
// Simulated NATS message JSON (received from NATS subscription)
|
||||||
|
let msg_json_str = r#"{
|
||||||
|
"correlation_id": "abc123-def456-ghi789",
|
||||||
|
"msg_id": "msg-uuid-001",
|
||||||
|
"timestamp": "2026-05-13T12:00:00.000Z",
|
||||||
|
"send_to": "/agent/wine/api/v1/prompt",
|
||||||
|
"msg_purpose": "chat",
|
||||||
|
"sender_name": "js-webapp",
|
||||||
|
"sender_id": "sender-uuid-001",
|
||||||
|
"receiver_name": "rust-backend",
|
||||||
|
"receiver_id": "",
|
||||||
|
"reply_to": "/agent/wine/api/v1/response",
|
||||||
|
"reply_to_msg_id": "",
|
||||||
|
"broker_url": "nats://localhost:4222",
|
||||||
|
"metadata": {},
|
||||||
|
"payloads": [
|
||||||
|
{
|
||||||
|
"id": "payload-uuid-001",
|
||||||
|
"dataname": "message",
|
||||||
|
"payload_type": "text",
|
||||||
|
"transport": "direct",
|
||||||
|
"encoding": "base64",
|
||||||
|
"size": 29,
|
||||||
|
"data": "SGVsbG8gZnJvbSBKYXZhU2NyaXB0ISE=",
|
||||||
|
"metadata": {"payload_bytes": 29}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "payload-uuid-002",
|
||||||
|
"dataname": "user_data",
|
||||||
|
"payload_type": "dictionary",
|
||||||
|
"transport": "direct",
|
||||||
|
"encoding": "json",
|
||||||
|
"size": 58,
|
||||||
|
"data": "eyJ0eXBlIjoiY2hhdCIsInNlbmRlciI6InNlcnZpY2VBIiwicmVjZWl2ZXIiOiJzZXJ2aWNlQiJ9",
|
||||||
|
"metadata": {"payload_bytes": 58}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}"#;
|
||||||
|
|
||||||
|
let options = SmartreceiveOptions::default();
|
||||||
|
|
||||||
|
match smartreceive(msg_json_str, &options).await {
|
||||||
|
Ok(envelope) => {
|
||||||
|
println!("=== Envelope Received ===");
|
||||||
|
println!("Correlation ID: {}", envelope.correlation_id);
|
||||||
|
println!("Message ID: {}", envelope.msg_id);
|
||||||
|
println!("Subject: {}", envelope.send_to);
|
||||||
|
println!("Purpose: {}", envelope.msg_purpose);
|
||||||
|
println!("Sender: {}", envelope.sender_name);
|
||||||
|
println!("Receiver: {}", envelope.receiver_name);
|
||||||
|
println!("Payloads: {}", envelope.payloads.len());
|
||||||
|
println!();
|
||||||
|
|
||||||
|
for payload in &envelope.payloads {
|
||||||
|
println!("--- Payload: {} ---", payload.dataname);
|
||||||
|
println!(" Type: {}", payload.payload_type);
|
||||||
|
println!(" Transport: {}", payload.transport);
|
||||||
|
println!(" Encoding: {}", payload.encoding);
|
||||||
|
println!(" Size: {} bytes", payload.size);
|
||||||
|
|
||||||
|
// In a real scenario, you would deserialize payload.data here
|
||||||
|
// based on payload_type to get the actual data
|
||||||
|
match payload.payload_type.as_str() {
|
||||||
|
"text" => {
|
||||||
|
// For demonstration, decode the base64
|
||||||
|
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
|
||||||
|
if payload.transport == "direct" {
|
||||||
|
let decoded = BASE64.decode(&payload.data).unwrap();
|
||||||
|
println!(" Data: {}", String::from_utf8_lossy(&decoded));
|
||||||
|
} else {
|
||||||
|
println!(" URL: {}", payload.data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"dictionary" => {
|
||||||
|
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
|
||||||
|
if payload.transport == "direct" {
|
||||||
|
let decoded = BASE64.decode(&payload.data).unwrap();
|
||||||
|
let json: serde_json::Value = serde_json::from_slice(&decoded).unwrap();
|
||||||
|
println!(" Data: {}", serde_json::to_string_pretty(&json).unwrap());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
other => {
|
||||||
|
println!(" Data type: {}", other);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("Error: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
70
examples/smartsend_example.rs
Normal file
70
examples/smartsend_example.rs
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
use natsbridge::{smartsend, Payload, SmartsendOptions};
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() {
|
||||||
|
// Create mixed payload data
|
||||||
|
let payloads = vec![
|
||||||
|
(
|
||||||
|
"message".to_string(),
|
||||||
|
Payload::Text("Hello from Rust!".to_string()),
|
||||||
|
"text".to_string(),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"user_data".to_string(),
|
||||||
|
Payload::Dictionary(serde_json::json!({
|
||||||
|
"name": "Alice",
|
||||||
|
"role": "admin",
|
||||||
|
"scores": [95, 88, 92]
|
||||||
|
})),
|
||||||
|
"dictionary".to_string(),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"avatar".to_string(),
|
||||||
|
Payload::Binary(vec![0x89, 0x50, 0x4E, 0x47]), // PNG header
|
||||||
|
"image".to_string(),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
|
let options = SmartsendOptions {
|
||||||
|
broker_url: "nats://localhost:4222".to_string(),
|
||||||
|
fileserver_url: "http://localhost:8080".to_string(),
|
||||||
|
msg_purpose: "chat".to_string(),
|
||||||
|
sender_name: "rust-example".to_string(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
match smartsend("/agent/wine/api/v1/prompt", &payloads, &options).await {
|
||||||
|
Ok((envelope, json_str)) => {
|
||||||
|
println!("=== Envelope Created ===");
|
||||||
|
println!("Correlation ID: {}", envelope.correlation_id);
|
||||||
|
println!("Message ID: {}", envelope.msg_id);
|
||||||
|
println!("Timestamp: {}", envelope.timestamp);
|
||||||
|
println!("Subject: {}", envelope.send_to);
|
||||||
|
println!("Purpose: {}", envelope.msg_purpose);
|
||||||
|
println!("Sender: {}", envelope.sender_name);
|
||||||
|
println!("Payloads: {}", envelope.payloads.len());
|
||||||
|
println!();
|
||||||
|
|
||||||
|
for payload in &envelope.payloads {
|
||||||
|
println!("Payload: {} (type: {}, transport: {}, encoding: {})",
|
||||||
|
payload.dataname,
|
||||||
|
payload.payload_type,
|
||||||
|
payload.transport,
|
||||||
|
payload.encoding);
|
||||||
|
println!(" Size: {} bytes", payload.size);
|
||||||
|
println!(" Data: {}", if payload.transport == "direct" {
|
||||||
|
&payload.data[..payload.data.len().min(40)]
|
||||||
|
} else {
|
||||||
|
&payload.data[..payload.data.len().min(60)]
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
println!();
|
||||||
|
println!("=== JSON String for NATS Publishing ===");
|
||||||
|
println!("{}", json_str);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("Error: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -43,7 +43,7 @@
|
|||||||
|
|
||||||
module NATSBridge
|
module NATSBridge
|
||||||
|
|
||||||
using NATS, JSON, Arrow, HTTP, UUIDs, Dates, Base64, PrettyPrinting, DataFrames
|
using JSON, Arrow, HTTP, UUIDs, Dates, Base64, PrettyPrinting, DataFrames
|
||||||
# ---------------------------------------------- 100 --------------------------------------------- #
|
# ---------------------------------------------- 100 --------------------------------------------- #
|
||||||
|
|
||||||
# Constants
|
# Constants
|
||||||
@@ -340,25 +340,29 @@ end
|
|||||||
""" smartsend - Send data either directly via NATS or via a fileserver URL, depending on payload size
|
""" smartsend - Send data either directly via NATS or via a fileserver URL, depending on payload size
|
||||||
|
|
||||||
This function intelligently routes data delivery based on payload size relative to a threshold.
|
This function intelligently routes data delivery based on payload size relative to a threshold.
|
||||||
If the serialized payload is smaller than `size_threshold`, it encodes the data as Base64 and publishes directly over NATS.
|
If the serialized payload is smaller than `size_threshold`, it encodes the data as Base64 and constructs a "direct" msg_payload_v1.
|
||||||
Otherwise, it uploads the data to a fileserver (by default using `plik_oneshot_upload`) and publishes only the download URL over NATS.
|
Otherwise, it uploads the data to a fileserver (by default using `plik_oneshot_upload`) and constructs a "link" msg_payload_v1 with the download URL.
|
||||||
|
|
||||||
The function accepts a list of (dataname, data, type) tuples as input and processes each payload individually.
|
The function accepts a list of (dataname, data, type) tuples as input and processes each payload individually.
|
||||||
Each payload can have a different type, enabling mixed-content messages (e.g., chat with text, images, audio).
|
Each payload can have a different type, enabling mixed-content messages (e.g., chat with text, images, audio).
|
||||||
|
|
||||||
|
This function creates and returns the msg_envelope_v1 and its JSON string representation only.
|
||||||
|
NATS publishing must be performed by the caller.
|
||||||
|
|
||||||
# Function Workflow:
|
# Function Workflow:
|
||||||
1. Iterates through the list of (dataname, data, type) tuples
|
1. Iterates through the list of (dataname, data, type) tuples
|
||||||
2. For each payload: extracts the type from the tuple and serializes accordingly
|
2. For each payload: extracts the type from the tuple and serializes accordingly
|
||||||
3. Compares the serialized size against `size_threshold`
|
3. Compares the serialized size against `size_threshold`
|
||||||
4. For small payloads: encodes as Base64, constructs a "direct" msg_payload_v1
|
4. For small payloads: encodes as Base64, constructs a "direct" msg_payload_v1
|
||||||
5. For large payloads: uploads to the fileserver, constructs a "link" msg_payload_v1 with the URL
|
5. For large payloads: uploads to the fileserver, constructs a "link" msg_payload_v1 with the URL
|
||||||
6. Converts envelope to JSON string and optionally publishes to NATS
|
6. Constructs msg_envelope_v1 with all payloads and metadata
|
||||||
|
7. Converts envelope to JSON string and returns (NATS publishing is handled by the caller)
|
||||||
|
|
||||||
# Arguments:
|
# Arguments:
|
||||||
- `subject::String` - NATS subject to publish the message to
|
- `subject::String` - NATS subject to publish the message to
|
||||||
- `data::AbstractArray{Tuple{String, Any, String}}` - List of (dataname, data, type) tuples to send
|
- `data::AbstractArray{Tuple{String, T1, String}, 1}` - List of (dataname, data, type) tuples to send
|
||||||
- `dataname::String` - Name of the payload
|
- `dataname::String` - Name of the payload
|
||||||
- `data::Any` - The actual data to send
|
- `data::T1` - The actual data to send (any type supported by `_serialize_data`)
|
||||||
- `payload_type::String` - Payload type: "text", "dictionary", "arrowtable", "jsontable", "image", "audio", "video", "binary"
|
- `payload_type::String` - Payload type: "text", "dictionary", "arrowtable", "jsontable", "image", "audio", "video", "binary"
|
||||||
- No standalone `type` parameter - type is specified per payload
|
- No standalone `type` parameter - type is specified per payload
|
||||||
|
|
||||||
@@ -367,17 +371,15 @@ Each payload can have a different type, enabling mixed-content messages (e.g., c
|
|||||||
- `fileserver_url = DEFAULT_FILESERVER_URL` - URL of the HTTP file server for large payloads
|
- `fileserver_url = DEFAULT_FILESERVER_URL` - URL of the HTTP file server for large payloads
|
||||||
- `fileserver_upload_handler::Function = plik_oneshot_upload` - Function to handle fileserver uploads (must return Dict with "status", "uploadid", "fileid", "url" keys)
|
- `fileserver_upload_handler::Function = plik_oneshot_upload` - Function to handle fileserver uploads (must return Dict with "status", "uploadid", "fileid", "url" keys)
|
||||||
- `size_threshold::Int = DEFAULT_SIZE_THRESHOLD` - Threshold in bytes separating direct vs link transport
|
- `size_threshold::Int = DEFAULT_SIZE_THRESHOLD` - Threshold in bytes separating direct vs link transport
|
||||||
- `correlation_id::String = string(uuid4())` - Correlation ID for tracing (auto-generated UUID)
|
- `correlation_id::String = string(uuid4())` - Correlation ID for tracing (auto-generated UUID)
|
||||||
- `msg_purpose::String = "chat"` - Purpose of the message: "ACK", "NACK", "updateStatus", "shutdown", "chat", etc.
|
- `msg_purpose::String = "chat"` - Purpose of the message: "ACK", "NACK", "updateStatus", "shutdown", "chat", etc.
|
||||||
- `sender_name::String = "NATSBridge"` - Name of the sender
|
- `sender_name::String = "NATSBridge"` - Name of the sender
|
||||||
- `receiver_name::String = ""` - Name of the receiver (empty string means broadcast)
|
- `receiver_name::String = ""` - Name of the receiver (empty string means broadcast)
|
||||||
- `receiver_id::String = ""` - UUID of the receiver (empty string means broadcast)
|
- `receiver_id::String = ""` - UUID of the receiver (empty string means broadcast)
|
||||||
- `reply_to::String = ""` - Topic to reply to (empty string if no reply expected)
|
- `reply_to::String = ""` - Topic to reply to (empty string if no reply expected)
|
||||||
- `reply_to_msg_id::String = ""` - Message ID this message is replying to
|
- `reply_to_msg_id::String = ""` - Message ID this message is replying to
|
||||||
- `is_publish::Bool = true` - Whether to automatically publish the message to NATS
|
- `msg_id::String = string(uuid4())` - Message ID (auto-generated UUID if not provided)
|
||||||
- `NATS_connection::Union{NATS.Connection, Nothing} = nothing` - Pre-existing NATS connection (if provided, uses this connection instead of creating a new one; saves connection establishment overhead)
|
- `sender_id::String = string(uuid4())` - Sender ID (auto-generated UUID if not provided)
|
||||||
- `msg_id::String = string(uuid4())` - Message ID (auto-generated UUID if not provided)
|
|
||||||
- `sender_id::String = string(uuid4())` - Sender ID (auto-generated UUID if not provided)
|
|
||||||
|
|
||||||
# Return:
|
# Return:
|
||||||
- `::Tuple{msg_envelope_v1, String}` - A tuple containing:
|
- `::Tuple{msg_envelope_v1, String}` - A tuple containing:
|
||||||
@@ -412,8 +414,9 @@ env, msg_json = smartsend("chat.subject", [
|
|||||||
("audio_clip", audio_data, "audio")
|
("audio_clip", audio_data, "audio")
|
||||||
])
|
])
|
||||||
|
|
||||||
# Publish the JSON string directly using NATS request-reply pattern
|
# Publish the JSON string directly using NATS (manual publish)
|
||||||
# reply = NATS.request(broker_url, subject, env_json_str; reply_to=reply_to_topic)
|
# conn = NATS.connect(broker_url)
|
||||||
|
# NATS.publish(conn, subject, env_json_str)
|
||||||
```
|
```
|
||||||
"""
|
"""
|
||||||
function smartsend(
|
function smartsend(
|
||||||
@@ -438,8 +441,6 @@ function smartsend(
|
|||||||
receiver_id::String = "",
|
receiver_id::String = "",
|
||||||
reply_to::String = "",
|
reply_to::String = "",
|
||||||
reply_to_msg_id::String = "",
|
reply_to_msg_id::String = "",
|
||||||
is_publish::Bool = true, # some time the user want to get env and env_json_str from this function without publishing the msg
|
|
||||||
NATS_connection::Union{NATS.Connection, Nothing} = nothing, # a provided connection saves establishing connection overhead.
|
|
||||||
msg_id::String = string(uuid4()), # Message ID
|
msg_id::String = string(uuid4()), # Message ID
|
||||||
sender_id::String = string(uuid4()) # Sender ID
|
sender_id::String = string(uuid4()) # Sender ID
|
||||||
)::Tuple{msg_envelope_v1, String} where {T1<:Any}
|
)::Tuple{msg_envelope_v1, String} where {T1<:Any}
|
||||||
@@ -539,13 +540,15 @@ function smartsend(
|
|||||||
)
|
)
|
||||||
|
|
||||||
env_json_str = envelope_to_json(env) # Convert envelope to JSON
|
env_json_str = envelope_to_json(env) # Convert envelope to JSON
|
||||||
if is_publish == false
|
# if is_publish == false
|
||||||
# skip publish a message
|
# # skip publish a message
|
||||||
elseif is_publish == true && NATS_connection === nothing
|
# elseif is_publish == true && NATS_connection === nothing
|
||||||
publish_message(broker_url, subject, env_json_str, correlation_id) # Publish message to NATS
|
# # Publish message to NATS using new connection
|
||||||
elseif is_publish == true && NATS_connection !== nothing
|
# publish_message(broker_url, subject, env_json_str, correlation_id)
|
||||||
publish_message(NATS_connection, subject, env_json_str, correlation_id) # Publish message to NATS
|
# elseif is_publish == true && NATS_connection !== nothing
|
||||||
end
|
# # Publish message to NATS using existing connection
|
||||||
|
# publish_message(NATS_connection, subject, env_json_str, correlation_id)
|
||||||
|
# end
|
||||||
|
|
||||||
return (env, env_json_str)
|
return (env, env_json_str)
|
||||||
end
|
end
|
||||||
@@ -700,73 +703,73 @@ function _serialize_data(data::Any, payload_type::String)
|
|||||||
end
|
end
|
||||||
|
|
||||||
|
|
||||||
""" publish_message - Publish message to NATS
|
# """ publish_message - Publish message to NATS
|
||||||
This function publishes a message to a NATS subject with proper
|
# This function publishes a message to a NATS subject with proper
|
||||||
connection management and logging.
|
# connection management and logging.
|
||||||
|
|
||||||
# Arguments:
|
# # Arguments:
|
||||||
- `broker_url::String` - NATS server URL (e.g., "nats://localhost:4222")
|
# - `broker_url::String` - NATS server URL (e.g., "nats://localhost:4222")
|
||||||
- `subject::String` - NATS subject to publish to (e.g., "/agent/wine/api/v1/prompt")
|
# - `subject::String` - NATS subject to publish to (e.g., "/agent/wine/api/v1/prompt")
|
||||||
- `message::String` - JSON message to publish
|
# - `message::String` - JSON message to publish
|
||||||
- `correlation_id::String` - Correlation ID for tracing and logging
|
# - `correlation_id::String` - Correlation ID for tracing and logging
|
||||||
|
|
||||||
# Return:
|
# # Return:
|
||||||
- `nothing` - This function performs publishing but returns nothing
|
# - `nothing` - This function performs publishing but returns nothing
|
||||||
|
|
||||||
# Example
|
# # Example
|
||||||
```jldoctest
|
# ```jldoctest
|
||||||
using NATS
|
# using NATS
|
||||||
|
|
||||||
# Prepare JSON message
|
# # Prepare JSON message
|
||||||
message = "{\"correlation_id\":\"abc123\",\"payload\":\"test\"}"
|
# message = "{\"correlation_id\":\"abc123\",\"payload\":\"test\"}"
|
||||||
|
|
||||||
# Publish to NATS
|
# # Publish to NATS
|
||||||
publish_message("nats://localhost:4222", "my.subject", message, "abc123")
|
# publish_message("nats://localhost:4222", "my.subject", message, "abc123")
|
||||||
```
|
# ```
|
||||||
"""
|
# """
|
||||||
function publish_message(broker_url::String, subject::String, message::String, correlation_id::String)
|
# function publish_message(broker_url::String, subject::String, message::String, correlation_id::String)
|
||||||
conn = NATS.connect(broker_url) # Create NATS connection
|
# conn = NATS.connect(broker_url) # Create NATS connection
|
||||||
publish_message(conn, subject, message, correlation_id)
|
# publish_message(conn, subject, message, correlation_id)
|
||||||
end
|
# end
|
||||||
|
|
||||||
""" publish_message - Publish message to NATS using pre-existing connection
|
# """ publish_message - Publish message to NATS using pre-existing connection
|
||||||
This function publishes a message to a NATS subject using a pre-existing NATS connection,
|
# This function publishes a message to a NATS subject using a pre-existing NATS connection,
|
||||||
avoiding the overhead of connection establishment.
|
# avoiding the overhead of connection establishment.
|
||||||
|
|
||||||
# Arguments:
|
# # Arguments:
|
||||||
- `conn::NATS.Connection` - Pre-existing NATS connection
|
# - `conn::NATS.Connection` - Pre-existing NATS connection
|
||||||
- `subject::String` - NATS subject to publish to (e.g., "/agent/wine/api/v1/prompt")
|
# - `subject::String` - NATS subject to publish to (e.g., "/agent/wine/api/v1/prompt")
|
||||||
- `message::String` - JSON message to publish
|
# - `message::String` - JSON message to publish
|
||||||
- `correlation_id::String` - Correlation ID for tracing and logging
|
# - `correlation_id::String` - Correlation ID for tracing and logging
|
||||||
|
|
||||||
# Return:
|
# # Return:
|
||||||
- `nothing` - This function performs publishing but returns nothing
|
# - `nothing` - This function performs publishing but returns nothing
|
||||||
|
|
||||||
# Example
|
# # Example
|
||||||
```jldoctest
|
# ```jldoctest
|
||||||
using NATS
|
# using NATS
|
||||||
|
|
||||||
# Prepare JSON message
|
# # Prepare JSON message
|
||||||
message = "{\"correlation_id\":\"abc123\",\"payload\":\"test\"}"
|
# message = "{\"correlation_id\":\"abc123\",\"payload\":\"test\"}"
|
||||||
|
|
||||||
# Create connection once and reuse for multiple publishes
|
# # Create connection once and reuse for multiple publishes
|
||||||
conn = NATS.connect("nats://localhost:4222")
|
# conn = NATS.connect("nats://localhost:4222")
|
||||||
publish_message(conn, "my.subject", message, "abc123")
|
# publish_message(conn, "my.subject", message, "abc123")
|
||||||
# Connection is automatically drained after publish
|
# # Connection is automatically drained after publish
|
||||||
```
|
# ```
|
||||||
|
|
||||||
# Use Case:
|
# # Use Case:
|
||||||
Use this version when you already have an established NATS connection and want to publish
|
# Use this version when you already have an established NATS connection and want to publish
|
||||||
multiple messages without the overhead of creating a new connection for each publish.
|
# multiple messages without the overhead of creating a new connection for each publish.
|
||||||
"""
|
# """
|
||||||
function publish_message(conn::NATS.Connection, subject::String, message::String, correlation_id::String)
|
# function publish_message(conn::NATS.Connection, subject::String, message::String, correlation_id::String)
|
||||||
try
|
# try
|
||||||
NATS.publish(conn, subject, message) # Publish message to NATS
|
# NATS.publish(conn, subject, message) # Publish message to NATS
|
||||||
log_trace(correlation_id, "Message published to $subject") # Log successful publish
|
# log_trace(correlation_id, "Message published to $subject") # Log successful publish
|
||||||
finally
|
# finally
|
||||||
NATS.drain(conn) # Ensure connection is closed properly
|
# NATS.drain(conn) # Ensure connection is closed properly
|
||||||
end
|
# end
|
||||||
end
|
# end
|
||||||
|
|
||||||
|
|
||||||
""" smartreceive - Receive and process messages from NATS
|
""" smartreceive - Receive and process messages from NATS
|
||||||
@@ -783,7 +786,7 @@ A HTTP file server is required along with its download function.
|
|||||||
5. For link transport: fetches data from URL with exponential backoff, then deserializes
|
5. For link transport: fetches data from URL with exponential backoff, then deserializes
|
||||||
|
|
||||||
# Arguments:
|
# Arguments:
|
||||||
- `msg::NATS.Msg` - NATS message to process
|
- `msg_json_str::String` - JSON string from NATS message payload (e.g., `String(nats_msg.payload)`)
|
||||||
|
|
||||||
# Keyword Arguments:
|
# Keyword Arguments:
|
||||||
- `fileserver_download_handler::Function = _fetch_with_backoff` - Function to handle downloading data from file server URLs
|
- `fileserver_download_handler::Function = _fetch_with_backoff` - Function to handle downloading data from file server URLs
|
||||||
@@ -798,19 +801,21 @@ A HTTP file server is required along with its download function.
|
|||||||
```jldoctest
|
```jldoctest
|
||||||
# Receive and process message
|
# Receive and process message
|
||||||
msg = nats_message # NATS message
|
msg = nats_message # NATS message
|
||||||
env = smartreceive(msg; fileserver_download_handler=_fetch_with_backoff, max_retries=5, base_delay=100, max_delay=5000)
|
msg_json_str = String(msg.payload)
|
||||||
|
env = smartreceive(msg_json_str; fileserver_download_handler=_fetch_with_backoff, max_retries=5, base_delay=100, max_delay=5000)
|
||||||
# env["payloads"] = [("dataname1", data1, "type1"), ("dataname2", data2, "type2"), ...]
|
# env["payloads"] = [("dataname1", data1, "type1"), ("dataname2", data2, "type2"), ...]
|
||||||
```
|
```
|
||||||
"""
|
"""
|
||||||
function smartreceive(
|
function smartreceive(
|
||||||
msg::NATS.Msg;
|
msg_json_str::String; # get it from String(nats_msg.payload)
|
||||||
fileserver_download_handler::Function = _fetch_with_backoff,
|
fileserver_download_handler::Function = _fetch_with_backoff,
|
||||||
max_retries::Int = 5,
|
max_retries::Int = 5,
|
||||||
base_delay::Int = 100,
|
base_delay::Int = 100,
|
||||||
max_delay::Int = 5000
|
max_delay::Int = 5000
|
||||||
)::JSON.Object{String, Any}
|
)::JSON.Object{String, Any}
|
||||||
|
|
||||||
# Parse the JSON envelope
|
# Parse the JSON envelope
|
||||||
env_json_obj = JSON.parse(String(msg.payload))
|
env_json_obj = JSON.parse(msg_json_str)
|
||||||
log_trace(env_json_obj["correlation_id"], "Processing received message") # Log message processing start
|
log_trace(env_json_obj["correlation_id"], "Processing received message") # Log message processing start
|
||||||
|
|
||||||
# Process all payloads in the envelope
|
# Process all payloads in the envelope
|
||||||
|
|||||||
1230
src/natsbridge.rs
Normal file
1230
src/natsbridge.rs
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user