Debian Codegraph @

vignettes/nanonext.Rmd

raw
1 ---
2 title: "nanonext - Quick Reference"
3 vignette: >
4 %\VignetteIndexEntry{nanonext - Quick Reference}
5 %\VignetteEngine{litedown::vignette}
6 %\VignetteEncoding{UTF-8}
7 ---
8
9 ## Core Concepts
10
11 **nanonext** provides bindings to NNG (Nanomsg Next Gen), a high-performance messaging library for building distributed systems.
12
13 This is a cheatsheet. Refer to the other vignettes for detailed introductions:
14
15 - [Messaging and Async I/O](v01-messaging.html) - cross-language exchange, async operations, synchronisation
16 - [Scalability Protocols](v02-protocols.html) - req/rep, pub/sub, surveyor/respondent
17 - [Configuration and Security](v03-configuration.html) - TLS, options, serialization, statistics
18 - [Web Toolkit](v04-web.html) - HTTP client/server, WebSocket, streaming
19
20 ## Key Takeaways
21
22 - **Sockets** connect via URLs using scalability protocols (req/rep, pub/sub, etc.)
23 - **Transports**: `inproc://` (in-process), `ipc://` (inter-process), `tcp://`, `ws://`, `wss://`, `tls+tcp://`
24 - **Async I/O**: `send_aio()` / `recv_aio()` return immediately; access results via `$data` or `$result`
25 - **Modes**: `"serial"` (R objects), `"raw"` (bytes), `"double"`, `"integer"`, `"character"`, etc.
26 - **Condition variables**: `cv()` for zero-latency event synchronisation
27
28 ## 1. Sockets and Connections
29
30 ### Create Sockets
31
32 ```r
33 library(nanonext)
34
35 # Functional interface
36 s <- socket("pair")
37 listen(s, "tcp://127.0.0.1:5555")
38 dial(s, "tcp://127.0.0.1:5555")
39
40 # Object-oriented interface
41 n <- nano("pair", listen = "tcp://127.0.0.1:5555")
42 n$dial("tcp://127.0.0.1:5556")
43
44 # Close when done
45 close(s)
46 n$close()
47 ```
48
49 ### Protocols
50
51 | Protocol | Description | Socket Types |
52 |----------|-------------|--------------|
53 | **Pair** | 1-to-1 bidirectional | `"pair"` |
54 | **Poly** | Polyamorous pair | `"poly"` |
55 | **Pipeline** | One-way data flow | `"push"`, `"pull"` |
56 | **Req/Rep** | RPC pattern | `"req"`, `"rep"` |
57 | **Pub/Sub** | Broadcast/subscribe | `"pub"`, `"sub"` |
58 | **Survey** | Query all peers | `"surveyor"`, `"respondent"` |
59 | **Bus** | Many-to-many mesh | `"bus"` |
60
61 ### Transports
62
63 | URL Scheme | Description |
64 |------------|-------------|
65 | `inproc://name` | In-process (fastest, same process) |
66 | `ipc:///path` | Inter-process (Unix socket / named pipe) |
67 | `tcp://host:port` | TCP/IP network |
68 | `ws://host:port/path` | WebSocket |
69 | `wss://host:port/path` | WebSocket over TLS |
70 | `tls+tcp://host:port` | TLS encrypted TCP |
71
72 ## 2. Send and Receive
73
74 ### Synchronous
75
76 ```r
77 # Send R object (serialized)
78 send(s, data.frame(a = 1, b = 2))
79
80 # Receive R object
81 recv(s)
82
83 # Send raw bytes (for cross-language exchange)
84 send(s, c(1.1, 2.2, 3.3), mode = "raw")
85
86 # Receive as specific type
87 recv(s, mode = "double")
88 recv(s, mode = "character")
89 recv(s, mode = "raw")
90 ```
91
92 ### Receive Modes
93
94 | Mode | Description |
95 |------|-------------|
96 | `"serial"` / `1` | R serialization (default) |
97 | `"character"` / `2` | Coerce to character |
98 | `"complex"` / `3` | Coerce to complex |
99 | `"double"` / `4` | Coerce to double |
100 | `"integer"` / `5` | Coerce to integer |
101 | `"logical"` / `6` | Coerce to logical |
102 | `"numeric"` / `7` | Coerce to numeric |
103 | `"raw"` / `8` | Raw bytes |
104 | `"string"` / `9` | Fast option for length-1 character |
105
106 ## 3. Async I/O
107
108 ### Basic Async
109
110 ```r
111 # Async send - returns immediately
112 res <- send_aio(s, data)
113 res$result # 0 = success, error code otherwise
114
115 # Async receive - returns immediately
116 msg <- recv_aio(s)
117 msg$data # Value when resolved, 'unresolved' NA otherwise
118
119 # Check if resolved
120 unresolved(msg) # TRUE while pending
121
122 # Wait for resolution
123 call_aio(msg) # Blocks, returns Aio object
124 collect_aio(msg) # Blocks, returns value directly
125 msg[] # Blocks (user-interruptible), returns value
126 ```
127
128 ### Non-blocking Patterns
129
130 ```r
131 # Poll while doing other work
132 while (unresolved(msg)) {
133 # do other tasks
134 }
135 result <- msg$data
136
137 # Multiple async operations
138 msg1 <- recv_aio(s1)
139 msg2 <- recv_aio(s2)
140 # Both run concurrently
141 ```
142
143 ## 4. Condition Variables
144
145 ### Basics
146
147 ```r
148 # Create condition variable
149 cv <- cv()
150
151 # Check/signal
152 cv_value(cv) # Get counter value
153 cv_signal(cv) # Increment counter
154 cv_reset(cv) # Reset to zero
155
156 # Wait (blocks until counter > 0, then decrements)
157 wait(cv)
158
159 # Wait with timeout (ms), returns FALSE on timeout
160 until(cv, 1000)
161 ```
162
163 ### Pipe Notifications
164
165 ```r
166 # Signal on connection/disconnection
167 pipe_notify(socket, cv = cv, add = TRUE, remove = TRUE)
168
169 # Distinguish message vs disconnect with flag
170 pipe_notify(socket, cv = cv, remove = TRUE, flag = TRUE)
171 r <- recv_aio(socket, cv = cv)
172 wait(cv) || stop("disconnected") # FALSE = pipe event
173 ```
174
175 ### Async with CV
176
177 ```r
178 cv <- cv()
179 msg <- recv_aio(s, cv = cv)
180 wait(cv) # Wake on receive completion
181 msg$data
182 ```
183
184 ## 5. Request/Reply (RPC)
185
186 ### Server
187
188 ```r
189 rep <- socket("rep", listen = "tcp://127.0.0.1:5555")
190 ctx <- context(rep)
191
192 # reply() blocks, waiting for request
193 reply(ctx, execute = my_function, send_mode = "raw")
194
195 close(rep)
196 ```
197
198 ### Client
199
200 ```r
201 req <- socket("req", dial = "tcp://127.0.0.1:5555")
202 ctx <- context(req)
203
204 # request() returns immediately
205 aio <- request(ctx, data = args, recv_mode = "double")
206
207 # Do other work while server processes...
208
209 # Get result when needed
210 result <- aio[]
211
212 close(req)
213 ```
214
215 ## 6. Pub/Sub
216
217 ```r
218 pub <- socket("pub", listen = "inproc://pubsub")
219 sub <- socket("sub", dial = "inproc://pubsub")
220
221 # Subscribe to topic (prefix matching)
222 subscribe(sub, topic = "news")
223 subscribe(sub, topic = NULL) # All topics
224
225 # Unsubscribe
226 unsubscribe(sub, topic = "news")
227
228 # Publish (topic is message prefix)
229 send(pub, c("news", "headline"), mode = "raw")
230
231 # Receive (includes topic)
232 recv(sub, mode = "character")
233
234 close(pub)
235 close(sub)
236 ```
237
238 ## 7. Surveyor/Respondent
239
240 ```r
241 sur <- socket("surveyor", listen = "inproc://survey")
242 res1 <- socket("respondent", dial = "inproc://survey")
243 res2 <- socket("respondent", dial = "inproc://survey")
244
245 # Set survey timeout (ms)
246 survey_time(sur, 500)
247
248 # Broadcast survey
249 send(sur, "ping")
250
251 # Collect responses (async)
252 aio1 <- recv_aio(sur)
253 aio2 <- recv_aio(sur)
254
255 # Respondents reply
256 recv(res1)
257 send(res1, "pong1")
258
259 # Late/missing responses timeout (errorValue 5)
260 msleep(500)
261 aio2$data # errorValue if no response
262
263 close(sur)
264 close(res1)
265 close(res2)
266 ```
267
268 ## 8. TLS Secure Connections
269
270 ### Self-signed Certificates
271
272 ```r
273 # Generate certificate (cn must match URL host exactly)
274 cert <- write_cert(cn = "127.0.0.1")
275
276 # Create TLS configs
277 server_tls <- tls_config(server = cert$server)
278 client_tls <- tls_config(client = cert$client)
279
280 # Use with tls+tcp:// or wss://
281 s1 <- socket(listen = "tls+tcp://127.0.0.1:5555", tls = server_tls)
282 s2 <- socket(dial = "tls+tcp://127.0.0.1:5555", tls = client_tls)
283 ```
284
285 ### CA Certificates
286
287 ```r
288 # Client with CA cert file
289 client_tls <- tls_config(client = "/path/to/ca-cert.pem")
290
291 # Server with cert + key
292 server_tls <- tls_config(server = c("/path/to/cert.pem", "/path/to/key.pem"))
293 ```
294
295 ## 9. Options and Statistics
296
297 ### Get/Set Options
298
299 ```r
300 # Delayed start for configuration
301 s <- socket(listen = "tcp://127.0.0.1:5555", autostart = FALSE)
302
303 # Get option
304 opt(s$listener[[1]], "recv-size-max")
305
306 # Set option
307 opt(s$listener[[1]], "recv-size-max") <- 8192L
308
309 # Start after configuration
310 start(s$listener[[1]])
311 ```
312
313 ### Common Options
314
315 | Option | Description |
316 |--------|-------------|
317 | `"recv-size-max"` | Max message size (0 = unlimited) |
318 | `"send-timeout"` | Send timeout (ms) |
319 | `"recv-timeout"` | Receive timeout (ms) |
320 | `"reconnect-time-min"` | Min reconnect interval (ms) |
321 | `"reconnect-time-max"` | Max reconnect interval (ms) |
322 | `"req:resend-time"` | Request retry interval |
323 | `"sub:prefnew"` | Prefer newer messages |
324
325 ### Custom Serialization
326
327 ```r
328 # Register custom serializer for a class
329 serial <- serial_config(
330 "class_name",
331 function(x) serialize(x, NULL), # serialize
332 unserialize # unserialize
333 )
334 opt(socket, "serial") <- serial
335 ```
336
337 ### Statistics
338
339 ```r
340 stat(socket, "pipes") # Active connections
341 stat(listener, "accept") # Connection attempts
342 stat(dialer, "reject") # Rejected connections
343 ```
344
345 ## 10. Contexts
346
347 Contexts enable concurrent operations on a single socket (for req/rep, surveyor/respondent).
348
349 ```r
350 s <- socket("req", dial = "tcp://127.0.0.1:5555")
351
352 # Create independent contexts
353 ctx1 <- context(s)
354 ctx2 <- context(s)
355
356 # Concurrent requests
357 aio1 <- request(ctx1, data1)
358 aio2 <- request(ctx2, data2)
359
360 # Close contexts (or they close with socket)
361 close(ctx1)
362 close(ctx2)
363 close(s)
364 ```
365
366 ## 11. Cross-language Exchange
367
368 ### R to Python (NumPy)
369
370 ```r
371 # R: send raw doubles
372 n <- nano("pair", dial = "ipc:///tmp/nanonext")
373 n$send(c(1.1, 2.2, 3.3), mode = "raw")
374 result <- n$recv(mode = "double")
375 ```
376
377 ```python
378 # Python: receive as NumPy array
379 import numpy as np
380 import pynng
381 socket = pynng.Pair0(listen="ipc:///tmp/nanonext")
382 array = np.frombuffer(socket.recv())
383 socket.send(array.tobytes())
384 ```
385
386 ## 12. Error Handling
387
388 ```r
389 # Errors return as 'errorValue' class
390 result <- recv(s, block = FALSE)
391
392 # Check for errors
393 is_error_value(result)
394
395 # Error codes
396 # 5 = Timed out
397 # 6 = Connection refused
398 # 8 = Try again (non-blocking, no message)
399
400 # Get error message
401 nng_error(5) # "Timed out"
402 ```
403
404 ## 13. Utilities
405
406 ```r
407 # Sleep (uninterruptible, ms)
408 msleep(100)
409
410 # Random bytes
411 random(8) # 8 random bytes as hex string
412 random(8, convert = FALSE) # As raw vector
413
414 # Parse URL
415 parse_url("tcp://127.0.0.1:5555")
416 ```