File: connections.R

package info (click to toggle)
r-cran-processx 3.8.6-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,068 kB
  • sloc: ansic: 6,485; sh: 13; makefile: 2
file content (607 lines) | stat: -rw-r--r-- 17,663 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607

#' Processx connections
#'
#' These functions are currently experimental and will change
#' in the future. Note that processx connections are  _not_
#' compatible with R's built-in connection system.
#'
#' `conn_create_fd()` creates a connection from a file descriptor.
#'
#' @param fd Integer scalar, a Unix file descriptor.
#' @param encoding Encoding of the readable connection when reading.
#' @param close Whether to close the OS file descriptor when closing
#'   the connection. Sometimes you want to leave it open, and use it again
#'   in a `conn_create_fd` call.
#' Encoding to re-encode `str` into when writing.
#'
#' @family processx connections
#' @rdname processx_connections
#' @export

conn_create_fd <- function(fd, encoding = "", close = TRUE) {
  assert_that(
    is_integerish_scalar(fd),
    is_string(encoding),
    is_flag(close))
  fd <- as.integer(fd)
  chain_call(c_processx_connection_create_fd, fd, encoding, close)
}

#' Processx FIFOs
#'
#' @description
#' `r lifecycle::badge("experimental")`
#'
#' Create a FIFO for inter-process communication
#' Note that these functions are currently experimental.
#'
#' @details
#' `conn_create_fifo()` creates a FIFO and connects to it.
#' On Unix this is a proper FIFO in the file system, in the R temporary
#' directory. On Windows it is a named pipe.
#'
#' Use [conn_file_name()] to query the name of the FIFO, and
#' `conn_connect_fifo()` to connect to the other end.
#'
#' # Notes
#'
#' ## In general Unix domain sockets work better than FIFOs, so we suggest
#' you use sockets if you can. See [conn_create_unix_socket()].
#'
#' ## Creating the read end of the FIFO
#'
#' This case is simpler. To wait for a writer to connect to the FIFO
#' you can use [poll()] as usual. Then use [conn_read_chars()] or
#' [conn_read_lines()] to read from the FIFO, as usual. Use
#' [conn_is_incomplete()] *after* a read to check if there is more data,
#' or the writer is done.
#'
#' ## Creating the write end of the FIFO
#'
#' This is somewhat trickier. Creating the (non-blocking) FIFO does not
#' block. However, there is no easy way to tell if a reader is connected
#' to the other end of the FIFO or not. On Unix you can start using
#' [conn_write()] to try to write to it, and this will succeed, until the
#' buffer gets full, even if there is no reader. (When the buffer is full
#' it will return the data that was not written, as usual.)
#'
#' On Windows, using [conn_write()] to write to a FIFO without a reader
#' fails with an error. This is not great, we are planning to improve it
#' later.
#'
#' Right now, one workaround for this behavior is for the reader to
#' connunicate to the writer process independenctly that it has connected
#' to the FIFO. (E.g. another FIFO in the opposite direction can do that.)
#'
#' @param filename File name of the FIFO. On Windows it the name of the
#' pipe within the `\\?\pipe\` namespace, either the full name, or the
#' part after that prefix. If `NULL`, then a random name
#' is used, on Unix in the R temporary directory: [base::tempdir()].
#' @param read If `TRUE` then connect to the read end of the FIFO.
#'   Exactly one of `read` and `write` must be set to `TRUE`.
#' @param write If `TRUE` then connect to the write end of the FIFO.
#'   Exactly one of `read` and `write` must be set to `TRUE`.
#' @param encoding Encoding to assume.
#' @param nonblocking Whether this should be a non-blocking FIFO.
#' Note that blocking FIFOs are not well tested and might not work well with
#' [poll()], especially on Windows. We might remove this option in the
#' future and make all FIFOs non-blocking.
#'
#' @seealso [processx internals](https://processx.r-lib.org/dev/articles/internals.html)
#'
#' @rdname processx_fifos
#' @export

conn_create_fifo <- function(filename = NULL, read = NULL, write = NULL,
                             encoding = "", nonblocking = TRUE) {
  if (is.null(read) && is.null(write)) { read <- TRUE; write <- FALSE }
  if (is.null(read)) read <- !write
  if (is.null(write)) write <- !read

  if (read && write) {
    throw(new_error("Bi-directional FIFOs are not supported currently"))
  }

  assert_that(
    is_string_or_null(filename),
    is_flag(read),
    is_flag(write),
    read || write,
    ! (read && write),
    is_string(encoding),
    is_flag(nonblocking)
  )

  filename <- make_pipe_file_name(filename)

  chain_call(
    c_processx_connection_create_fifo,
    read,
    write,
    filename,
    encoding,
    nonblocking
  )
}

winpipeprefix <- "\\\\?\\pipe\\"

make_pipe_file_name <- function(filename) {
  if (is_windows()) {
    filename <- filename %||% basename(tempfile())
    if (!starts_with(filename, winpipeprefix)) {
      filename <- paste0(winpipeprefix, filename)
    }
  } else {
    filename <- filename %||% tempfile()
  }
  filename
}

#' @details
#' `conn_connect_fifo()` connects to a FIFO created with
#' `conn_create_fifo()`, typically in another process. `filename` refers
#' to the name of the pipe on Windows.
#'
#' On Windows, `conn_connect_fifo()` may be successful even if the
#' FIFO does not exist, but then later `poll()` or read/write operations
#' will fail. We are planning on changing this behavior in the future,
#' to make `conn_connect_fifo()` fail immediately, like on Unix.
#'
#' @rdname processx_fifos
#' @export
#' @examples
#' # Example for a non-blocking FIFO
#'
#' # Need to open the reading end first, otherwise Unix fails
#' reader <- conn_create_fifo()
#'
#' # Always use poll() before you read, with a timeout if you like.
#' # If you read before the other end of the FIFO is connected, then
#' # the OS (or processx?) assumes that the FIFO is done, and you cannot
#' # read anything.
#' # Now poll() tells us that there is no data yet.
#' poll(list(reader), 0)
#'
#' writer <- conn_connect_fifo(conn_file_name(reader), write = TRUE)
#' conn_write(writer, "hello\nthere!\n")
#'
#' poll(list(reader), 1000)
#' conn_read_lines(reader, 1)
#' conn_read_chars(reader)
#'
#' conn_is_incomplete(reader)
#'
#' close(writer)
#' conn_read_chars(reader)
#' conn_is_incomplete(reader)
#'
#' close(reader)

conn_connect_fifo <- function(filename, read = NULL, write = NULL,
                              encoding = "", nonblocking = TRUE) {
  if (is.null(read) && is.null(write)) { read <- TRUE; write <- FALSE }
  if (is.null(read)) read <- !write
  if (is.null(write)) write <- !read

  if (read && write) {
    throw(new_error("Bi-directional FIFOs are not supported currently"))
  }

  assert_that(
    is_string(filename),
    is_flag(read),
    is_flag(write),
    read || write,
    ! (read && write),
    is_string(encoding),
    is_flag(nonblocking)
  )

  if (is_windows()) {
    if (!starts_with(filename, winpipeprefix)) {
      filename <- paste0(winpipeprefix, filename)
    }
  }

  chain_call(
    c_processx_connection_connect_fifo,
    filename,
    read,
    write,
    encoding,
    nonblocking
  )
}

#' @details
#' `conn_file_name()` returns the name of the file associated with the
#' connection. For connections that do not refer to a file in the file
#' system it returns `NA_character()`. Except for named pipes on Windows,
#' where it returns the full name of the pipe.
#'
#' @rdname processx_connections
#' @export

conn_file_name <- function(con) {
  assert_that(is_connection(con))

  chain_call(c_processx_connection_file_name, con)
}

#' @details
#' `conn_create_pipepair()` creates a pair of connected connections, the
#' first one is writeable, the second one is readable.
#'
#' @param nonblocking Whether the pipe should be non-blocking.
#' For `conn_create_pipepair()` it must be a logical vector of length two,
#' for both ends of the pipe.
#'
#' @rdname processx_connections
#' @export

conn_create_pipepair <- function(encoding = "",
                                 nonblocking = c(TRUE, FALSE)) {
  assert_that(
    is_string(encoding),
    is.logical(nonblocking), length(nonblocking) == 2,
    !any(is.na(nonblocking)))
  chain_call(c_processx_connection_create_pipepair, encoding, nonblocking)
}

#' @details
#' `conn_read_chars()` reads UTF-8 characters from the connections. If the
#' connection itself is not UTF-8 encoded, it re-encodes it.
#'
#' @param con Processx connection object.
#' @param n Number of characters or lines to read. -1 means all available
#' characters or lines.
#'
#' @rdname processx_connections
#' @export

conn_read_chars <- function(con, n = -1)
  UseMethod("conn_read_chars", con)

#' @rdname processx_connections
#' @export

conn_read_chars.processx_connection <- function(con, n = -1) {
  processx_conn_read_chars(con, n)
}

#' @rdname processx_connections
#' @export

processx_conn_read_chars <- function(con, n = -1) {
  assert_that(is_connection(con), is_integerish_scalar(n))
  chain_call(c_processx_connection_read_chars, con, n)
}

#' @details
#' `conn_read_lines()` reads lines from a connection.
#'
#' @rdname processx_connections
#' @export

conn_read_lines <- function(con, n = -1)
  UseMethod("conn_read_lines", con)

#' @rdname processx_connections
#' @export

conn_read_lines.processx_connection <- function(con, n = -1) {
  processx_conn_read_lines(con, n)
}

#' @rdname processx_connections
#' @export

processx_conn_read_lines <- function(con, n = -1) {
  assert_that(is_connection(con), is_integerish_scalar(n))
  chain_call(c_processx_connection_read_lines, con, n)
}

#' @details
#' `conn_is_incomplete()` returns `FALSE` if the connection surely has no
#' more data.
#'
#' @rdname processx_connections
#' @export

conn_is_incomplete <- function(con)
  UseMethod("conn_is_incomplete", con)

#' @rdname processx_connections
#' @export

conn_is_incomplete.processx_connection <- function(con) {
  processx_conn_is_incomplete(con)
}

#' @rdname processx_connections
#' @export

processx_conn_is_incomplete <- function(con) {
  assert_that(is_connection(con))
  ! chain_call(c_processx_connection_is_eof, con)
}

#' @details
#' `conn_write()` writes a character or raw vector to the connection.
#' It might not be able to write all bytes into the connection, in which
#' case it returns the leftover bytes in a raw vector. Call `conn_write()`
#' again with this raw vector.
#'
#' @param str Character or raw vector to write.
#' @param sep Separator to use if `str` is a character vector. Ignored if
#' `str` is a raw vector.
#'
#' @rdname processx_connections
#' @export

conn_write <- function(con, str, sep = "\n", encoding = "")
  UseMethod("conn_write", con)

#' @rdname processx_connections
#' @export

conn_write.processx_connection <- function(con, str, sep = "\n",
                                           encoding = "") {
  processx_conn_write(con, str, sep, encoding)
}

#' @rdname processx_connections
#' @export

processx_conn_write <- function(con, str, sep = "\n", encoding = "") {
  assert_that(
    is_connection(con),
    (is.character(str) && all(! is.na(str))) || is.raw(str),
    is_string(sep),
    is_string(encoding))

  if (is.character(str)) {
    pstr <- paste(str, collapse = sep)
    str <- iconv(pstr, "", encoding, toRaw = TRUE)[[1]]
  }
  invisible(chain_call(c_processx_connection_write_bytes, con, str))
}

#' @details
#' `conn_create_file()` creates a connection to a file.
#'
#' @param filename File name. For `conn_create_pipe()` on Windows, a
#' `\\?\pipe` prefix is added to this, if it does not have such a prefix.
#' For `conn_create_pipe()` it can also be `NULL`, in which case a random
#' file name is used via `tempfile()`.
#' @param read Whether the connection is readable.
#' @param write Whethe the connection is writeable.
#'
#' @rdname processx_connections
#' @export

conn_create_file <- function(filename, read = NULL, write = NULL) {
  if (is.null(read) && is.null(write)) { read <- TRUE; write <- FALSE }
  if (is.null(read)) read <- !write
  if (is.null(write)) write <- !read

  assert_that(
    is_string(filename),
    is_flag(read),
    is_flag(write),
    read || write)

  chain_call(c_processx_connection_create_file, filename, read, write)
}

#' @details
#' `conn_set_stdout()` set the standard output of the R process, to the
#' specified connection.
#'
#' @param drop Whether to close the original stdout/stderr, or keep it
#' open and return a connection to it.
#'
#' @rdname processx_connections
#' @export

conn_set_stdout <- function(con, drop = TRUE) {
  assert_that(
    is_connection(con),
    is_flag(drop))

  flush(stdout())
  invisible(chain_call(c_processx_connection_set_stdout, con, drop))
}

#' @details
#' `conn_set_stderr()` set the standard error of the R process, to the
#' specified connection.
#'
#' @rdname processx_connections
#' @export

conn_set_stderr <- function(con, drop = TRUE) {
  assert_that(
    is_connection(con),
    is_flag(drop))

  flush(stderr())
  invisible(chain_call(c_processx_connection_set_stderr, con, drop))
}

#' @details
#' `conn_get_fileno()` return the integer file desciptor that belongs to
#' the connection.
#'
#' @rdname processx_connections
#' @export

conn_get_fileno <- function(con) {
  chain_call(c_processx_connection_get_fileno, con)
}

#' @details
#' `conn_disable_inheritance()` can be called to disable the inheritance
#' of all open handles. Call this function as soon as possible in a new
#' process to avoid inheriting the inherited handles even further.
#' The function is best effort to close the handles, it might still leave
#' some handles open. It should work for `stdin`, `stdout` and `stderr`,
#' at least.
#'
#' @rdname processx_connections
#' @export

conn_disable_inheritance <- function() {
  chain_call(c_processx_connection_disable_inheritance)
}

#' @rdname processx_connections
#' @export

close.processx_connection <- function(con, ...) {
  processx_conn_close(con, ...)
}

#' @param ... Extra arguments, for compatibility with the `close()`
#'    generic, currently ignored by processx.
#' @rdname processx_connections
#' @export

processx_conn_close <- function(con, ...) {
  chain_call(c_processx_connection_close, con)
}

#' @details
#' `is_valid_fd()` returns `TRUE` if `fd` is a valid open file
#' descriptor. You can use it to check if the R process has standard
#' input, output or error. E.g. R processes running in GUI (like RGui)
#' might not have any of the standard streams available.
#'
#' If a stream is redirected to the null device (e.g. in a callr
#' subprocess), that is is still a valid file descriptor.
#'
#' @rdname processx_connections
#' @export
#' @examples
#' is_valid_fd(0L)      # stdin
#' is_valid_fd(1L)      # stdout
#' is_valid_fd(2L)      # stderr

is_valid_fd <- function(fd) {
  assert_that(is_integerish_scalar(fd))
  fd <- as.integer(fd)
  chain_call(c_processx_is_valid_fd, fd)
}

#' Unix domain sockets
#'
#' @description
#' `r lifecycle::badge("experimental")`
#'
#' Cross platform point-to-point inter-process communication with
#' Unix=domain sockets, implemented via named pipes on Windows.
#' These connection are always bidirectional, i.e. you can read from them
#' and also write to them.
#'
#' @details
#' `conn_create_unix_socket()` creates a server socket. The new socket
#' is listening at `filename`. See `filename` above.
#'
#' `conn_connect_unix_socket()` creates a client socket and connects it to
#' a server socket.
#'
#' `conn_accept_unix_socket()` accepts a client connection at a server
#' socket.
#'
#' `conn_unix_socket_state()` returns the state of the socket. Currently it
#' can return: `"listening"`, `"connected_server"`, `"connected_client"`.
#' It is possible that other states (e.g. for a closed socket) will be added
#' in the future.
#'
#' ## Notes
#'
#' * [poll()] works on sockets, but only polls for data to read, and
#'   currently ignores the write-end of the socket.
#' * [poll()] also works for accepting client connections. It will return
#'   `"connect"`is a client connection is available for a server socket.
#'   After this you can call `conn_accept_unix_socket()` to accept the
#'   client connection.
#'
#' @param filename File name of the socket. On Windows it the name of the
#' pipe within the `\\?\pipe\` namespace, either the full name, or the
#' part after that prefix. If `NULL`, then a random name
#' is used, on Unix in the R temporary directory: [base::tempdir()].
#' @param encoding Encoding to assume when reading from the socket.
#' @param con Connection. An error is thrown if not a socket connection.
#' @return A new socket connection.
#'
#' @seealso [processx internals](https://processx.r-lib.org/dev/articles/internals.html)
#'
#' @rdname processx_sockets
#' @export

conn_create_unix_socket <- function(filename = NULL, encoding = "") {

  assert_that(
    is_string_or_null(filename),
    is_string(encoding)
  )

  filename <- make_pipe_file_name(filename)

  chain_call(
    c_processx_connection_create_socket,
    filename,
    encoding
  )
}

#' @rdname processx_sockets
#' @export

conn_connect_unix_socket <- function(filename, encoding = "") {

  assert_that(
    is_string_or_null(filename),
    is_string(encoding)
  )

  if (is_windows()) {
    if (!starts_with(filename, winpipeprefix)) {
      filename <- paste0(winpipeprefix, filename)
    }
  }

  chain_call(
    c_processx_connection_connect_socket,
    filename,
    encoding
  )
}

#' @rdname processx_sockets
#' @export

conn_accept_unix_socket <- function(con) {
  assert_that(is_connection(con))

  invisible(chain_call(
    c_processx_connection_accept_socket,
    con
  ))
}

#' @rdname processx_sockets
#' @export

conn_unix_socket_state <- function(con) {
  assert_that(is_connection(con))

  code <- chain_call(
    c_processx_connection_socket_state,
    con
  )

  c("listening", "listening", "connected_server", "connected_client")[code]
}