Debian Codegraph @

R/context.R

raw
1 # nanonext - Contexts and RPC --------------------------------------------------
2
3 #' Open Context
4 #'
5 #' Open a new Context to be used with a Socket. The purpose of a Context is to
6 #' permit applications to share a single socket, with its underlying dialers and
7 #' listeners, while still benefiting from separate state tracking.
8 #'
9 #' Contexts allow the independent and concurrent use of stateful operations
10 #' using the same socket. For example, two different contexts created on a rep
11 #' socket can each receive requests, and send replies to them, without any
12 #' regard to or interference with each other.
13 #'
14 #' Only the following protocols support creation of contexts: req, rep, sub
15 #' (in a pub/sub pattern), surveyor, respondent.
16 #'
17 #' To send and receive over a context use [send()] and [recv()] or their async
18 #' counterparts [send_aio()] and [recv_aio()].
19 #'
20 #' For nano objects, use the `$context_open()` method, which will attach a new
21 #' context at `$context`. See [nano()].
22 #'
23 #' @param socket a Socket.
24 #'
25 #' @return A Context (object of class 'nanoContext' and 'nano').
26 #'
27 #' @seealso [request()] and [reply()] for use with contexts.
28 #' @examples
29 #' s <- socket("req", listen = "inproc://nanonext")
30 #' ctx <- context(s)
31 #' ctx
32 #' close(ctx)
33 #' close(s)
34 #'
35 #' n <- nano("req", listen = "inproc://nanonext")
36 #' n$context_open()
37 #' n$context
38 #' n$context_open()
39 #' n$context
40 #' n$context_close()
41 #' n$close()
42 #'
43 #' @export
44 #'
45 context <- function(socket) .Call(rnng_ctx_open, socket)
46
47 #' Technical Utility: Open Context
48 #'
49 #' Open a new Context to be used with a Socket. This function is a performance
50 #' variant of [context()], designed to wrap a socket in a function argument when
51 #' calling [request()] or [reply()].
52 #'
53 #' External pointers created by this function are unclassed, hence methods for
54 #' contexts such as [close()] will not work (use [reap()] instead). Otherwise
55 #' they function identically to a Context when passed to all messaging
56 #' functions.
57 #'
58 #' @param socket a Socket.
59 #'
60 #' @return An external pointer.
61 #'
62 #' @keywords internal
63 #' @export
64 #'
65 .context <- function(socket) .Call(rnng_ctx_create, socket)
66
67 #' @rdname close
68 #' @method close nanoContext
69 #' @export
70 #'
71 close.nanoContext <- function(con, ...) invisible(.Call(rnng_ctx_close, con))
72
73 #' Reply over Context (RPC Server for Req/Rep Protocol)
74 #'
75 #' Implements an executor/server for the rep node of the req/rep protocol.
76 #' Awaits data, applies an arbitrary specified function, and returns the result
77 #' to the caller/client.
78 #'
79 #' Receive will block while awaiting a message to arrive and is usually the
80 #' desired behaviour. Set a timeout to allow the function to return if no data
81 #' is forthcoming.
82 #'
83 #' In the event of an error in either processing the messages or in evaluation
84 #' of the function with respect to the data, a nul byte `00` (or serialized
85 #' nul byte) will be sent in reply to the client to signal an error. This is to
86 #' be distinguishable from a possible return value. [is_nul_byte()] can be used
87 #' to test for a nul byte.
88 #'
89 #' @param context a Context.
90 #' @param execute a function which takes the received (converted) data as its
91 #' first argument. Can be an anonymous function of the form
92 #' `function(x) do(x)`. Additional arguments can also be passed in through
93 #' `...`.
94 #' @param send_mode \[default 'serial'\] character value or integer equivalent -
95 #' either `"serial"` (1L) to send serialised R objects, or `"raw"` (2L) to
96 #' send atomic vectors of any type as a raw byte vector.
97 #' @param recv_mode \[default 'serial'\] character value or integer equivalent -
98 #' one of `"serial"` (1L), `"character"` (2L), `"complex"` (3L), `"double"`
99 #' (4L), `"integer"` (5L), `"logical"` (6L), `"numeric"` (7L), `"raw"` (8L),
100 #' or `"string"` (9L). The default `"serial"` means a serialised R object; for
101 #' the other modes, received bytes are converted into the respective mode.
102 #' `"string"` is a faster option for length one character vectors.
103 #' @param timeout \[default NULL\] integer value in milliseconds or NULL, which
104 #' applies a socket-specific default, usually the same as no timeout. Note
105 #' that this applies to receiving the request. The total elapsed time would
106 #' also include performing 'execute' on the received data. The timeout then
107 #' also applies to sending the result (in the event that the requestor has
108 #' become unavailable since sending the request).
109 #' @param ... additional arguments passed to the function specified by
110 #' 'execute'.
111 #'
112 #' @return Integer exit code (zero on success).
113 #'
114 #' @inheritSection send Send Modes
115 #'
116 #' @examples
117 #' req <- socket("req", listen = "inproc://req-example")
118 #' rep <- socket("rep", dial = "inproc://req-example")
119 #'
120 #' ctxq <- context(req)
121 #' ctxp <- context(rep)
122 #'
123 #' send(ctxq, 2022, block = 100)
124 #' reply(ctxp, execute = function(x) x + 1, send_mode = "raw", timeout = 100)
125 #' recv(ctxq, mode = "double", block = 100)
126 #'
127 #' send(ctxq, 100, mode = "raw", block = 100)
128 #' reply(ctxp, recv_mode = "double", execute = log, base = 10, timeout = 100)
129 #' recv(ctxq, block = 100)
130 #'
131 #' close(req)
132 #' close(rep)
133 #'
134 #' @export
135 #'
136 reply <- function(
137 context,
138 execute,
139 recv_mode = c("serial", "character", "complex", "double", "integer", "logical", "numeric", "raw", "string"),
140 send_mode = c("serial", "raw"),
141 timeout = NULL,
142 ...
143 ) {
144 block <- if (is.null(timeout)) TRUE else timeout
145 res <- recv(context, mode = recv_mode, block = block)
146 is_error_value(res) && return(res)
147 data <- .Call(rnng_eval_safe, as.call(list(execute, res, ...)))
148 send(context, data = data, mode = send_mode, block = block)
149 }
150
151 #' Request over Context (RPC Client for Req/Rep Protocol)
152 #'
153 #' Implements a caller/client for the req node of the req/rep protocol. Sends
154 #' data to the rep node (executor/server) and returns an Aio, which can be
155 #' called for the value when required.
156 #'
157 #' Sending the request and receiving the result are both performed async, hence
158 #' the function will return immediately with a 'recvAio' object. Access the
159 #' return value at `$data`.
160 #'
161 #' This is designed so that the process on the server can run concurrently
162 #' without blocking the client.
163 #'
164 #' Optionally use [call_aio()] on the 'recvAio' to call (and wait for) the
165 #' result.
166 #'
167 #' If an error occured in the server process, a nul byte `00` will be received.
168 #' This allows an error to be easily distinguished from a NULL return value.
169 #' [is_nul_byte()] can be used to test for a nul byte.
170 #'
171 #' It is recommended to use a new context for each request to ensure consistent
172 #' state tracking. The integer context ID is appended as the attribute `id` to
173 #' the returned 'recvAio'.
174 #'
175 #' @inheritParams reply
176 #' @inheritParams recv
177 #' @param data an object (if `send_mode = "raw"`, a vector).
178 #' @param timeout \[default NULL\] integer value in milliseconds or NULL, which
179 #' applies a socket-specific default, usually the same as no timeout.
180 #' @param cv (optional) a 'conditionVariable' to signal when the async receive
181 #' is complete, or NULL.
182 #' @param id NULL. For package internal use only.
183 #'
184 #' @return A 'recvAio' (object of class 'mirai' and 'recvAio') (invisibly).
185 #'
186 #' @inheritSection send Send Modes
187 #' @inheritSection recv_aio Signalling
188 #'
189 #' @examples
190 #' \dontrun{
191 #'
192 #' # works if req and rep are running in parallel in different processes
193 #'
194 #' req <- socket("req", listen = "tcp://127.0.0.1:6546")
195 #' rep <- socket("rep", dial = "tcp://127.0.0.1:6546")
196 #'
197 #' reply(.context(rep), execute = function(x) x + 1, timeout = 50)
198 #' aio <- request(.context(req), data = 2022)
199 #' aio$data
200 #'
201 #' close(req)
202 #' close(rep)
203 #'
204 #' # Signalling a condition variable
205 #'
206 #' req <- socket("req", listen = "tcp://127.0.0.1:6546")
207 #' ctxq <- context(req)
208 #' cv <- cv()
209 #' aio <- request(ctxq, data = 2022, cv = cv)
210 #' until(cv, 10L)
211 #' close(req)
212 #'
213 #' # The following should be run in another process
214 #' rep <- socket("rep", dial = "tcp://127.0.0.1:6546")
215 #' ctxp <- context(rep)
216 #' reply(ctxp, execute = function(x) x + 1)
217 #' close(rep)
218 #'
219 #' }
220 #'
221 #' @export
222 #'
223 request <- function(
224 context,
225 data,
226 send_mode = c("serial", "raw"),
227 recv_mode = c("serial", "character", "complex", "double", "integer", "logical", "numeric", "raw", "string"),
228 timeout = NULL,
229 cv = NULL,
230 id = NULL
231 )
232 data <- .Call(rnng_request, context, data, send_mode, recv_mode, timeout, cv, id, environment())