-
Notifications
You must be signed in to change notification settings - Fork 31
/
BackendRserve.R
311 lines (298 loc) · 11.5 KB
/
BackendRserve.R
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
#' @title Creates Rserve backend for processing HTTP requests
#'
#' @description
#' Creates BackendRserve object which can start [Application] using Rserve backend.
#'
#' @references
# nolint start
#' [See http.c in Rserve](https://github.com/s-u/Rserve/blob/e6b2b6b10e92b6e201d34a05394b2186fda30696/src/http.c#L353-L372)
# nolint end
#' @export
#'
BackendRserve = R6::R6Class(
classname = "BackendRserve",
inherit = Backend,
public = list(
#' @description
#' Creates BackendRserve object.
#' @param ... Not used at the moment.
#' @param jit_level changes R's byte compiler level to this value before app
#' start.
#' @param precompile try to use R's byte compiler to pre-compile
initialize = function(..., jit_level = 0L, precompile = TRUE) {
private$jit_level = jit_level
private$precompile = precompile
invisible(self)
},
#' @description
#' Starts RestRserve application from current R session.
#' @param app [Application] object.
#' @param http_port HTTP port for application. Negative values (such as -1)
#' means not to expose plain http.
#' @param ... Key-value pairs of the Rserve configuration. If contains
#' `"http.port"` then `http_port` will be silently replaced with its value.
#' @param background Whether to try to launch in background process on UNIX.
#' @return [ApplicationProcess] object when `background = TRUE`.
start = function(app, http_port = 8080, ..., background = FALSE) { # nocov start
checkmate::assert_int(http_port)
ARGS = list(...)
if (http_port > 0L) {
if (is.null(ARGS[["http.port"]])) {
ARGS[["http.port"]] = http_port
}
}
if (is.null(ARGS[["port"]])) {
# find available port (if default (6311) is busy)
ARGS[["port"]] = RestRserve:::find_port()
}
if (RestRserve:::port_is_taken(ARGS[["port"]])) {
stop(sprintf("Port %s is already in use. ", ARGS[["port"]]),
"Please provide another 'port' argument value.", call. = FALSE)
}
keep_http_request = .GlobalEnv[[".http.request"]]
# restore global environment on exit
on.exit({.GlobalEnv[[".http.request"]] = keep_http_request}, add = TRUE)
# temporary modify global environment
.GlobalEnv[[".http.request"]] = function(url, parameters_query, body, headers) {
self$set_request(
app$.__enclos_env__$private$request,
path = url,
parameters_query = parameters_query,
headers = headers,
body = body
)
self$convert_response(app$process_request())
}
if (.Platform$OS.type != "windows" && background) {
run_mode = 'BACKGROUND'
} else {
run_mode = 'FOREGROUND'
}
# print endpoints summary
if (length(app$endpoints) == 0) {
app$logger$warn("", context = "'Application' doesn't have any endpoints")
}
app$logger$info("", context = list(http_port = http_port, endpoints = app$endpoints))
app$logger$debug("", context = sprintf("setting JIT level to %d", private$jit_level))
old_jit = compiler::enableJIT(private$jit_level)
on.exit(compiler::enableJIT(old_jit), add = TRUE)
# see https://github.com/rexyai/RestRserve/issues/149
if (isTRUE(private$precompile)) {
app$logger$debug("", context = "trying to byte compile .GlobalEnv recursively")
compile_all()
}
pid = Sys.getpid()
if (run_mode == 'BACKGROUND') {
pid = parallel::mcparallel(do.call(Rserve::run.Rserve, ARGS), detached = TRUE)[["pid"]]
return(ApplicationProcess$new(pid))
} else {
do.call(Rserve::run.Rserve, ARGS)
}
}, # nocov end
#' @description
#' Parse request and set to it fields.
#' @param request [Request] object.
#' @param path Character with requested path. Always starts with `/`.
#' @param parameters_query A named character vector with URL decoded query
#' parameters.
#' @param headers Request HTTP headers.
#' @param body Request body. Can be `NULL`, raw vector or named character
#' vector for the URL encoded form (like a `parameters_query` parameter).
#' @return `request` modified object.
set_request = function(request, path = "/", parameters_query = NULL, headers = NULL, body = NULL) {
# actually we can skip runtime check as inputs from Rserve are guaranteed
if (isTRUE(getOption('RestRserve.runtime.asserts', TRUE))) {
checkmate::assert_string(path)
checkmate::assert_character(parameters_query, null.ok = TRUE)
checkmate::assert(
checkmate::check_raw(headers, null.ok = TRUE),
checkmate::check_string(headers, null.ok = TRUE),
combine = "or"
)
checkmate::assert(
checkmate::check_raw(body, null.ok = TRUE),
checkmate::check_character(body, null.ok = TRUE),
combine = "or"
)
}
request$path = path
private$parse_headers(headers, request)
private$parse_query(parameters_query, request)
# Rserve adds "Request-Method: " key:
# https://github.com/s-u/Rserve/blob/05ff32d3c4512954a99162d392d0465d432d591e/src/http.c#L661
# according to the code above we assume that "request-method" is always exists
request$method = request$headers[["request-method"]]
# remove from headers as this was added by Rserve and wasn't present in original request
request$headers[["request-method"]] = NULL
private$parse_body_and_content_type(body, request)
private$parse_cookies(request)
invisible(request)
},
#' @description
#' Convert `self` object to Rserve compatible structure.
#' @param response [Response] object.
#' @return List with the following structure:
#' * `body`: can be a character vector of length one or a raw vector.
#' if the character vector is named "file" then the content of a file of
#' that name is the body.
#' If the character vector is named "tmpfile" then the content of a
#' temporary file of that name is the body.
#' * `content-type`: must be a character vector of length one or NULL
#' (if present, else default is `"text/plain"`).
#' * `headers`: must be a character vector - the elements will have CRLF
#' appended and neither `Content-type` nor `Content-length` may be used.
#' * `status-code`: must be an integer if present (default is 200).
convert_response = function(response) {
body = response$body
# prepare headers
if (length(response$headers) > 0L) {
headers = cpp_format_headers(as.list(response$headers))
if (length(response$cookies) > 0L) {
headers = paste(headers, cpp_format_cookies(as.list(response$cookies)), sep = "\r\n")
}
} else {
headers = character(0)
}
# prepare body
if (is_string(body)) {
body_name = names(body)
if (isTRUE(body_name %in% c("file", "tmpfile"))) {
# NOTE there is no call to response$encode() - we are serving files "as is"
return(c(as.list(body), list(response$content_type, headers, response$status_code)))
}
}
if (is.null(body)) {
body = raw()
}
if (isTRUE(is.raw(body) || is.character(body))) {
return(list(body, response$content_type, headers, response$status_code))
} else {
return(list("500 Internal Server Error (body is not character or raw)", "text/plain", headers, 500L))
}
}
),
private = list(
jit_level = NULL,
precompile = NULL,
request = NULL,
parse_form_urlencoded = function(body, request) {
if (length(body) > 0L) {
# Named character vector. Body parameters key-value pairs.
# Omit empty keys and empty values
body = body[nzchar(names(body)) & nzchar(body)]
request$parameters_body = as.list(body)
keys = names(body)
values = paste(cpp_url_encode(keys), cpp_url_encode(body), sep = "=", collapse = "&")
body = charToRaw(values)
} else {
body = raw()
}
request$body = body
return(request)
},
parse_form_multipart = function(body, request) {
# workaround for the issue #137
# content_type = attr(body, "content-type")
boundary = cpp_parse_multipart_boundary(request$content_type)
res = cpp_parse_multipart_body(body, boundary)
if (length(res$values) > 0L) {
values = unlist(res$values, use.names = TRUE)
values = values[nzchar(names(values)) & nzchar(values)]
keys = cpp_url_decode(names(values))
values = cpp_url_decode(values)
request$parameters_body[keys] = values
}
if (length(res$files) > 0L) {
request$files = res$files
keys = cpp_url_decode(names(res$files))
values = cpp_url_decode(vapply(res$files, "[[", character(1), "filename"))
request$parameters_body[keys] = values
}
request$body = body
return(request)
},
parse_query = function(parameters_query, request) {
res = structure(list(), names = character())
if (length(parameters_query) > 0L) {
# Named character vector. Query parameters key-value pairs.
res = as.list(parameters_query)
# Omit empty keys and empty values
res = res[nzchar(names(res)) & nzchar(parameters_query)]
}
request$parameters_query = res
return(request)
},
parse_headers = function(headers, request) {
if (is.raw(headers)) {
headers = rawToChar(headers)
}
if (is_string(headers)) {
headers = cpp_parse_headers(headers)
}
request$headers = headers
return(request)
},
parse_body_and_content_type = function(body, request) {
if (is.null(request$content_type)) {
request$content_type = request$headers[["content-type"]]
}
if (is.null(request$content_type)) {
body_type = attr(body, "content-type") # content-type from body attribute
# fill type from the body if empty
if (!is.null(body_type)) {
request$content_type = body_type
} else {
request$content_type = "text/plain"
}
}
if (is.null(body)) {
request$body = raw()
} else if (!is.raw(body)) {
# parse form
if (request$content_type == "application/x-www-form-urlencoded") {
return(private$parse_form_urlencoded(body, request))
}
} else {
if (startsWith(request$content_type, "multipart/form-data")) {
return(private$parse_form_multipart(body, request))
} else {
request$body = body
}
}
return(request)
},
parse_cookies = function(request) {
if (!is.null(request$headers[["cookie"]])) {
request$cookies = cpp_parse_cookies(request$headers[["cookie"]])
}
return(request)
}
),
)
#' @title Creates ApplicationProcess object
#'
#' @description
#' Creates ApplicationProcess to hold PID of the runnung applicaiton.
#'
ApplicationProcess = R6::R6Class(
classname = "ApplicationProcess",
public = list(
#' @field pid Process identificator.
pid = NULL,
#' @description
#' Creates ApplicationProcess object
#' @param pid Process identificator.
initialize = function(pid) {
self$pid = pid
},
#' @description
#' Send signal to process.
#' @param signal Singal code.
kill = function(signal = 15L) {
# kill service
tools::pskill(self$pid, signal)
# kill childs
system(sprintf("pkill -%s -P %s", signal, self$pid), wait = FALSE)
}
)
)