Debian Codegraph @

R/aio.R

raw
1 # nanonext - Core - Aio Functions ----------------------------------------------
2
3 # send_aio/recv_aio ------------------------------------------------------------
4
5 #' Send Async
6 #'
7 #' Send data asynchronously over a connection (Socket, Context, Stream or Pipe).
8 #'
9 #' Async send is always non-blocking and returns a 'sendAio' immediately.
10 #'
11 #' For a 'sendAio', the send result is available at `$result`. An 'unresolved'
12 #' logical NA is returned if the async operation is yet to complete. The
13 #' resolved value will be zero on success, or else an integer error code.
14 #'
15 #' To wait for and check the result of the send operation, use [call_aio()] on
16 #' the returned 'sendAio' object.
17 #'
18 #' Alternatively, to stop the async operation, use [stop_aio()].
19 #'
20 #' @inheritParams send
21 #' @param con a Socket, Context or Stream.
22 #' @param timeout \[default NULL\] integer value in milliseconds or NULL, which
23 #' applies a socket-specific default, usually the same as no timeout.
24 #'
25 #' @return A 'sendAio' (object of class 'sendAio') (invisibly).
26 #'
27 #' @inheritSection send Send Modes
28 #'
29 #' @seealso [send()] for synchronous send.
30 #'
31 #' @examples
32 #' pub <- socket("pub", dial = "inproc://nanonext")
33 #'
34 #' res <- send_aio(pub, data.frame(a = 1, b = 2), timeout = 100)
35 #' res
36 #' res$result
37 #'
38 #' res <- send_aio(pub, "example message", mode = "raw", timeout = 100)
39 #' call_aio(res)$result
40 #'
41 #' close(pub)
42 #'
43 #' @export
44 #'
45 send_aio <- function(con, data, mode = c("serial", "raw"), timeout = NULL, pipe = 0L)
46 data <- .Call(rnng_send_aio, con, data, mode, timeout, pipe, environment())
47
48 #' Receive Async
49 #'
50 #' Receive data asynchronously over a connection (Socket, Context or Stream).
51 #'
52 #' Async receive is always non-blocking and returns a 'recvAio' immediately.
53 #'
54 #' For a 'recvAio', the received message is available at `$data`. An
55 #' 'unresolved' logical NA is returned if the async operation is yet to
56 #' complete.
57 #'
58 #' To wait for the async operation to complete and retrieve the received
59 #' message, use [call_aio()] on the returned 'recvAio' object.
60 #'
61 #' Alternatively, to stop the async operation, use [stop_aio()].
62 #'
63 #' In case of an error, an integer 'errorValue' is returned (to be
64 #' distiguishable from an integer message value). This can be checked using
65 #' [is_error_value()].
66 #'
67 #' If an error occurred in unserialization or conversion of the message data to
68 #' the specified mode, a raw vector will be returned instead to allow recovery
69 #' (accompanied by a warning).
70 #'
71 #' @inheritParams recv
72 #' @inheritParams send_aio
73 #' @param cv (optional) a 'conditionVariable' to signal when the async receive
74 #' is complete.
75 #'
76 #' @return A 'recvAio' (object of class 'recvAio') (invisibly).
77 #'
78 #' @section Signalling:
79 #'
80 #' By supplying a 'conditionVariable', when the receive is complete, the
81 #' 'conditionVariable' is signalled by incrementing its value by 1. This
82 #' happens asynchronously and independently of the R execution thread.
83 #'
84 #' @seealso [recv()] for synchronous receive.
85 #'
86 #' @examples
87 #' s1 <- socket("pair", listen = "inproc://nanonext")
88 #' s2 <- socket("pair", dial = "inproc://nanonext")
89 #'
90 #' res <- send_aio(s1, data.frame(a = 1, b = 2), timeout = 100)
91 #' msg <- recv_aio(s2, timeout = 100)
92 #' msg
93 #' msg$data
94 #'
95 #' res <- send_aio(s1, c(1.1, 2.2, 3.3), mode = "raw", timeout = 100)
96 #' msg <- recv_aio(s2, mode = "double", timeout = 100)
97 #' msg
98 #' msg$data
99 #'
100 #' res <- send_aio(s1, "example message", mode = "raw", timeout = 100)
101 #' msg <- recv_aio(s2, mode = "character", timeout = 100)
102 #' call_aio(msg)
103 #' msg$data
104 #'
105 #' close(s1)
106 #' close(s2)
107 #'
108 #' # Signalling a condition variable
109 #'
110 #' s1 <- socket("pair", listen = "inproc://cv-example")
111 #' cv <- cv()
112 #' msg <- recv_aio(s1, timeout = 100, cv = cv)
113 #' until(cv, 10L)
114 #' msg$data
115 #' close(s1)
116 #'
117 #' # in another process in parallel
118 #' s2 <- socket("pair", dial = "inproc://cv-example")
119 #' res <- send_aio(s2, c(1.1, 2.2, 3.3), mode = "raw", timeout = 100)
120 #' close(s2)
121 #'
122 #' @export
123 #'
124 recv_aio <- function(
125 con,
126 mode = c("serial", "character", "complex", "double", "integer", "logical", "numeric", "raw", "string"),
127 timeout = NULL,
128 cv = NULL
129 )
130 data <- .Call(rnng_recv_aio, con, mode, timeout, cv, environment())
131
132 # Core aio functions -----------------------------------------------------------
133
134 #' Call the Value of an Asynchronous Aio Operation
135 #'
136 #' `call_aio` retrieves the value of an asynchronous Aio operation, waiting
137 #' for the operation to complete if still in progress. For a list of Aios, waits
138 #' for all asynchronous operations to complete before returning.
139 #'
140 #' For a 'recvAio', the received value may be retrieved at `$data`.
141 #'
142 #' For a 'sendAio', the send result may be retrieved at `$result`.
143 #' This will be zero on success, or else an integer error code.
144 #'
145 #' To access the values directly, use for example on a 'recvAio' `x`:
146 #' `call_aio(x)$data`.
147 #'
148 #' For a 'recvAio', if an error occurred in unserialization or conversion of the
149 #' message data to the specified mode, a raw vector will be returned instead to
150 #' allow recovery (accompanied by a warning).
151 #'
152 #' Note: this function operates silently and does not error even if `x` is not
153 #' an active Aio or list of Aios, always returning invisibly the passed object.
154 #'
155 #' @param x an Aio or list of Aios (objects of class 'sendAio', 'recvAio' or
156 #' 'ncurlAio').
157 #'
158 #' @return The passed object (invisibly).
159 #'
160 #' @section Alternatively:
161 #'
162 #' Aio values may be accessed directly at `$result` for a 'sendAio', and `$data`
163 #' for a 'recvAio'. If the Aio operation is yet to complete, an 'unresolved'
164 #' logical NA will be returned. Once complete, the resolved value will be
165 #' returned instead.
166 #'
167 #' [unresolved()] may also be used, which returns `TRUE` only if an Aio or Aio
168 #' value has yet to resolve and `FALSE` otherwise. This is suitable for use in
169 #' control flow statements such as `while` or `if`.
170 #'
171 #' @examples
172 #' s1 <- socket("pair", listen = "inproc://nanonext")
173 #' s2 <- socket("pair", dial = "inproc://nanonext")
174 #'
175 #' res <- send_aio(s1, data.frame(a = 1, b = 2), timeout = 100)
176 #' res
177 #' call_aio(res)
178 #' res$result
179 #'
180 #' msg <- recv_aio(s2, timeout = 100)
181 #' msg
182 #' call_aio_(msg)$data
183 #'
184 #' close(s1)
185 #' close(s2)
186 #'
187 #' @export
188 #'
189 call_aio <- function(x) invisible(.Call(rnng_aio_call, x))
190
191 #' Call the Value of an Asynchronous Aio Operation
192 #'
193 #' `call_aio_` is a variant that allows user interrupts, suitable for
194 #' interactive use.
195 #'
196 #' @rdname call_aio
197 #' @export
198 #'
199 call_aio_ <- function(x) invisible(.Call(rnng_wait_thread_create, x))
200
201 #' Collect Data of an Aio or List of Aios
202 #'
203 #' `collect_aio` collects the data of an Aio or list of Aios, waiting for
204 #' resolution if still in progress.
205 #'
206 #' This function will wait for the asynchronous operation(s) to complete if
207 #' still in progress (blocking).
208 #'
209 #' Using `x[]` on an Aio `x` is equivalent to the user-interruptible
210 #' `collect_aio_(x)`.
211 #'
212 #' @inheritParams call_aio
213 #'
214 #' @return Depending on the type of `x` supplied, an object or list of objects
215 #' (the same length as `x`, preserving names).
216 #'
217 #' @examples
218 #' s1 <- socket("pair", listen = "inproc://nanonext")
219 #' s2 <- socket("pair", dial = "inproc://nanonext")
220 #'
221 #' res <- send_aio(s1, data.frame(a = 1, b = 2), timeout = 100)
222 #' collect_aio(res)
223 #'
224 #' msg <- recv_aio(s2, timeout = 100)
225 #' collect_aio_(msg)
226 #'
227 #' msg[]
228 #'
229 #' close(s1)
230 #' close(s2)
231 #'
232 #' @export
233 #'
234 collect_aio <- function(x) .Call(rnng_aio_collect, x)
235
236 #' Collect Data of an Aio or List of Aios
237 #'
238 #' `collect_aio_` is a variant that allows user interrupts, suitable for
239 #' interactive use.
240 #'
241 #' @rdname collect_aio
242 #' @export
243 #'
244 collect_aio_ <- function(x) .Call(rnng_aio_collect_safe, x)
245
246 #' Race Aio
247 #'
248 #' Returns the index of the first resolved Aio in a list, waiting if necessary.
249 #'
250 #' @param x A list of Aio objects.
251 #' @param cv A condition variable. This must be the same cv supplied to
252 #' [recv_aio()] or [request()] when creating the Aio objects in `x`.
253 #'
254 #' @return Integer index of the first resolved Aio, or 0L if none are resolved,
255 #' the list is empty, or the cv was terminated.
256 #'
257 #' @export
258 #'
259 race_aio <- function(x, cv) .Call(rnng_race_aio, x, cv)
260
261 #' Stop Asynchronous Aio Operation
262 #'
263 #' Stop an asynchronous Aio operation, or a list of Aio operations.
264 #'
265 #' Stops the asynchronous I/O operation associated with Aio `x` by aborting, and
266 #' then waits for it to complete or to be completely aborted, and for the
267 #' callback associated with the Aio to have completed executing. If successful,
268 #' the Aio will resolve to an 'errorValue' 20 (Operation canceled).
269 #'
270 #' Note this function operates silently and does not error even if `x` is not an
271 #' active Aio, always returning invisible NULL.
272 #'
273 #' @inheritParams call_aio
274 #'
275 #' @return Invisible NULL.
276 #'
277 #' @export
278 #'
279 stop_aio <- function(x) invisible(.Call(rnng_aio_stop, x))
280
281 #' Stop Request Operation
282 #'
283 #' Stop an asynchronous Aio operation, or a list of Aio operations, created by
284 #' [request()]. This is an augmented version of [stop_aio()] that additionally
285 #' requests cancellation by sending an integer zero followed by the context ID
286 #' over the context, and waiting for the response.
287 #'
288 #' @param x an Aio or list of Aios (objects of class 'recvAio' returned by
289 #' [request()]).
290 #'
291 #' @return Invisibly, a logical vector.
292 #'
293 #' @keywords internal
294 #' @export
295 #'
296 stop_request <- function(x) invisible(.Call(rnng_request_stop, x))
297
298 #' Query if an Aio is Unresolved
299 #'
300 #' Query whether an Aio, Aio value or list of Aios remains unresolved. Unlike
301 #' [call_aio()], this function does not wait for completion.
302 #'
303 #' Suitable for use in control flow statements such as `while` or `if`.
304 #'
305 #' Note: querying resolution may cause a previously unresolved Aio to resolve.
306 #'
307 #' @param x an Aio or list of Aios (objects of class 'sendAio', 'recvAio' or
308 #' 'ncurlAio'), or Aio value stored at `$result` or `$data` etc.
309 #'
310 #' @return Logical `TRUE` if `x` is an unresolved Aio or Aio value or the list
311 #' of Aios contains at least one unresolved Aio, or `FALSE` otherwise.
312 #'
313 #' @examples
314 #' s1 <- socket("pair", listen = "inproc://nanonext")
315 #' aio <- send_aio(s1, "test", timeout = 100)
316 #'
317 #' while (unresolved(aio)) {
318 #' # do stuff before checking resolution again
319 #' cat("unresolved\n")
320 #' msleep(100)
321 #' }
322 #'
323 #' unresolved(aio)
324 #'
325 #' close(s1)
326 #'
327 #' @export
328 #'
329 unresolved <- function(x) .Call(rnng_unresolved, x)
330
331 #' Get the Pipe ID of a recvAio
332 #'
333 #' Caution: must only be used on an already-resolved 'recvAio'. This function
334 #' does not perform validation of these pre-conditions.
335 #'
336 #' @param x a resolved 'recvAio'.
337 #'
338 #' @return Integer pipe ID.
339 #'
340 #' @export
341 #'
342 pipe_id <- function(x) .subset2(x, "aio")
343
344 #' Technical Utility: Query if an Aio is Unresolved
345 #'
346 #' Query whether an Aio or list of Aios remains unresolved. This is an
347 #' experimental technical utility version of [unresolved()] not intended for
348 #' ordinary use. Provides a method of querying the busy status of an Aio without
349 #' altering its state in any way i.e. not attempting to retrieve the result or
350 #' message.
351 #'
352 #' `.unresolved()` is not intended to be used for 'recvAio' returned by a
353 #' signalling function, in which case [unresolved()] must be used in all cases.
354 #'
355 #' @inheritParams call_aio
356 #'
357 #' @return Logical `TRUE` if `x` is an unresolved Aio or else `FALSE`, or if `x`
358 #' is a list, the integer number of unresolved Aios in the list.
359 #'
360 #' @keywords internal
361 #' @export
362 #'
363 .unresolved <- function(x) .Call(rnng_unresolved2, x)
364
365 #' Make recvAio Promise
366 #'
367 #' Creates a 'promise' from an 'recvAio' object.
368 #'
369 #' This function is an S3 method for the generic `as.promise` for class
370 #' 'recvAio'.
371 #'
372 #' Requires the \pkg{promises} package.
373 #'
374 #' Allows a 'recvAio' to be used with the promise pipe `%...>%`, which schedules
375 #' a function to run upon resolution of the Aio.
376 #'
377 #' @param x an object of class 'recvAio'.
378 #'
379 #' @return A 'promise' object.
380 #'
381 #' @exportS3Method promises::as.promise
382 #'
383 as.promise.recvAio <- function(x) {
384 promise <- .subset2(x, "promise")
385
386 if (is.null(promise)) {
387 promise <- promises::promise(
388 function(resolve, reject) {
389 if (unresolved(x)) .keep(x, environment()) else resolve(.subset2(x, "value"))
390 }
391 )$then(
392 onFulfilled = handle_fulfilled
393 )
394 `[[<-`(x, "promise", promise)
395 }
396
397 promise
398 }
399
400 handle_fulfilled <- function(value, .visible) {
401 is_error_value(value) && stop(nng_error(value))
402 value
403 }
404
405 #' @exportS3Method promises::is.promising
406 #'
407 is.promising.recvAio <- function(x) TRUE
408
409 #' Keep Promise
410 #'
411 #' Internal package function.
412 #'
413 #' If successful, both `x` and `ctx` are preserved and accessible from the
414 #' promise callback.
415 #'
416 #' @param x a 'recvAio' or 'ncurlAio' object.
417 #' @param ctx the return value of `environment()`.
418 #'
419 #' @return NULL.
420 #'
421 #' @keywords internal
422 #' @export
423 #'
424 .keep <- function(x, ctx) .Call(rnng_set_promise_context, x, ctx)