-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathREADME.Rmd
623 lines (543 loc) · 16.5 KB
/
README.Rmd
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
---
output:
md_document:
variant: gfm
---
```{r, echo=FALSE,strip.white=FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#",
fig.path = "README-"
)
set.seed(0)
#knitr::opts_knit$set(root.dir = 'inst/examples')
post <- function(URL, out, err) {
r <- httr::POST(URL)
cat("--- Request ---\n")
cat("curl -X POST \"", URL, "\"\n", sep="")
cat("--- Response ---\n")
cat(httr::content(r, "text", "application/json", "UTF-8"))
cat("\n--- STDOUT ---\n")
cat(readLines(out), sep="\n")
cat("--- STDERR ---\n")
cat(readLines(err), sep="\n")
invisible()
}
tmp <- tempdir()
```
# tryr: Client/Server Error Handling for HTTP APIs
> Differentiate client errors (4xx) from server errors (5xx) with a simple built-in logging mechanism for the Plumber and RestRserve HTTP API frameworks.
[![Build
status](https://github.com/analythium/tryr/actions/workflows/check.yml/badge.svg)](https://github.com/analythium/tryr/actions)
[![CRAN
version](http://www.r-pkg.org/badges/version/tryr)](https://CRAN.R-project.org/package=tryr)
[![CRAN RStudio mirror
downloads](http://cranlogs.r-pkg.org/badges/grand-total/tryr)](https://hub.analythium.io/tryr/)
```R
install.packages("tryr")
```
In client/server setups, the client might send user input that is incorrect. In such cases the front end application needs to know that the 4xx error status indicates that the message needs to be relayed to the user to correct the input.
As opposed to this, when the server fails due to unexpected reasons, the client only needs to know that an error with 5xx status happened. Logs are essential for backend developers to diagnose the problem.
## Problem statement
The Plumber R package implements a simple error catching hook that converts all responses that are an error condition to a status code 500 - Internal Server Error.
Let's see this for an example API:
```R
plumber::pr("inst/examples/plumber.R") |>
plumber::pr_set_debug(FALSE) |>
plumber::pr_run(port=8000)
```
### Default behavior
We use a handler calling the function `foo()`: note that the contents of the response also depend on the `pr_set_debug()` settings that depends on whether we use interactive or non-interactive session. This is now turned off so that we can see the 'production' behavior.
```R
foo <- function(x) {
x <- as.numeric(x)
if (x < 0)
stop("'x' is too low.")
"Success!"
}
#* @post /test
function(x) {
foo(x = x)
}
```
Here are the responses from this `/test` endpoint for various specification of the `x` parameter:
```{r, echo=FALSE}
out <- file.path(tmp, "out")
err <- file.path(tmp, "err")
rx <- callr::r_bg(function() {
plumber::pr("inst/examples/plumber.R") |>
plumber::pr_set_debug(FALSE) |>
plumber::pr_run(port=8000, quiet=TRUE)
},
stdout = out,
stderr = err
)
Sys.sleep(1)
URL <- "http://localhost:8000/test?x=0"
post(URL, out, err)
o <- rx$kill()
```
```{r, echo=FALSE}
out <- file.path(tmp, "out")
err <- file.path(tmp, "err")
rx <- callr::r_bg(function() {
plumber::pr("inst/examples/plumber.R") |>
plumber::pr_set_debug(FALSE) |>
plumber::pr_run(port=8000, quiet=TRUE)
},
stdout = out,
stderr = err
)
Sys.sleep(1)
URL <- "http://localhost:8000/test?x=-1"
post(URL, out, err)
o <- rx$kill()
```
```{r, echo=FALSE}
out <- file.path(tmp, "out")
err <- file.path(tmp, "err")
rx <- callr::r_bg(function() {
plumber::pr("inst/examples/plumber.R") |>
plumber::pr_set_debug(FALSE) |>
plumber::pr_run(port=8000, quiet=TRUE)
},
stdout = out,
stderr = err
)
Sys.sleep(1)
URL <- "http://localhost:8000/test?x=a"
post(URL, out, err)
o <- rx$kill()
```
```{r, echo=FALSE}
out <- file.path(tmp, "out")
err <- file.path(tmp, "err")
rx <- callr::r_bg(function() {
plumber::pr("inst/examples/plumber.R") |>
plumber::pr_set_debug(FALSE) |>
plumber::pr_run(port=8000, quiet=TRUE)
},
stdout = out,
stderr = err
)
Sys.sleep(1)
URL <- "http://localhost:8000/test?x="
post(URL, out, err)
o <- rx$kill()
```
As you can see, the response has a generic 500 HTTP status irrespective of nature of the error. On the back end, the error is printed to STDOUT, whereas a warning got printed to STDERR.
This default behavior is undesired for multiple reasons:
- We need to be able to differentiate 4xx and 5xx errors
- The detailed error message is helpful on the backend, but we should print it to STDERR instead of STDOUT
Warning: when `pr_set_debug(TRUE)` the error message itself is returned by the response, this might contain sensitive information that we should not leak to the client.
## Try/catch behavior
Alternatively, we can use some functions from tryr to handle these inconveniences:
```R
bar <- function(x) {
x <- suppressWarnings(as.numeric(x))
if (is.na(x))
tryr::http_error(400L, "Unexpected input.")
foo(x)
}
#* @post /try
function(req, res, x) {
tryr::http_try(req, res, {
if (missing(x))
stop("'x' is missing", call. = FALSE)
bar(x = x)
})
}
```
Here are the outputs from the `/try` endpoint for the same requests as before:
```{r echo=FALSE}
out <- file.path(tmp, "out")
err <- file.path(tmp, "err")
rx <- callr::r_bg(function() {
plumber::pr("inst/examples/plumber.R") |>
plumber::pr_set_debug(FALSE) |>
plumber::pr_run(port=8000, quiet=TRUE)
},
stdout = out,
stderr = err
)
Sys.sleep(1)
URL <- "http://localhost:8000/try?x=0"
post(URL, out, err)
o <- rx$kill()
```
```{r, echo=FALSE}
out <- file.path(tmp, "out")
err <- file.path(tmp, "err")
rx <- callr::r_bg(function() {
plumber::pr("inst/examples/plumber.R") |>
plumber::pr_set_debug(FALSE) |>
plumber::pr_run(port=8000, quiet=TRUE)
},
stdout = out,
stderr = err
)
Sys.sleep(1)
URL <- "http://localhost:8000/try?x=-1"
post(URL, out, err)
o <- rx$kill()
```
```{r, echo=FALSE}
out <- file.path(tmp, "out")
err <- file.path(tmp, "err")
rx <- callr::r_bg(function() {
plumber::pr("inst/examples/plumber.R") |>
plumber::pr_set_debug(FALSE) |>
plumber::pr_run(port=8000, quiet=TRUE)
},
stdout = out,
stderr = err
)
Sys.sleep(1)
URL <- "http://localhost:8000/try?x=a"
post(URL, out, err)
o <- rx$kill()
```
```{r, echo=FALSE}
out <- file.path(tmp, "out")
err <- file.path(tmp, "err")
rx <- callr::r_bg(function() {
plumber::pr("inst/examples/plumber.R") |>
plumber::pr_set_debug(FALSE) |>
plumber::pr_run(port=8000, quiet=TRUE)
},
stdout = out,
stderr = err
)
Sys.sleep(1)
URL <- "http://localhost:8000/try?x="
post(URL, out, err)
o <- rx$kill()
```
Now we can see that:
- Successful response (200) leaves a trace in STDOUT
- We can differentiate 4xx and 5xx errors
- When the error is 5xx, the error message is not included
- The detailed error message is printed to STDERR
So how did we do it? Here is what you get in tryr: we used `http_try()`. It is a wrapper that can handle _expected_ and _unexpected_ errors. Expected errors give the desired HTTP statuses using `http_error()`. Unexpected error are returned by `stop()` and we have very little control over those (i.e. these were written by someone else).
## Implementation
The logic inside `http_try()` is this:
_If we catch an error:_
* the error is a clear server error coming from `stop()`
- log it as an ERROR + print the error message to STDERR
- return a generic status 500 message
- set the status code of the response object to 500
* the error is a structured HTTP error coming from `http_error()`
- log it as an ERROR with the message from the condition attribute
- return the specific HTTP error code with the structured output
- set the status code of the response object
_If we don't catch an error:_
* the object is of class `http_success()` (this comes in handy for async jobs and redirects)
- log it as a SUCCESS with the message element
- return the specific HTTP status code with the structured output
- set the status code of the response object
* the object is NOT of class `http_success()`
- log it as a SUCCESS with a generic 200 message
- return the object as is (default status code 200 assumed)
Log messages are handled by the `msg` function. Here is how you can add a preroute hook: we add a logger to print incoming request info (HTTP method and route) to STDOUT. For the sake of better ingesting the logs we can set the logging type to JSON (or CSV) and the timestamp precision to 6 digits.
```R
Sys.setenv(
TRYR_LOG_FORMAT = "JSON",
TRYR_LOG_DIGITS = "6"
)
plumber::pr("inst/examples/plumber.R") |>
plumber::pr_set_debug(FALSE) |>
plumber::pr_hooks(
list(
preroute = function(data, req, res) {
tryr::msg(
title = paste(
method = req$REQUEST_METHOD,
path = req$PATH_INFO
),
level = "INFO"
)
}
)
) |>
plumber::pr_run(
port = 8000,
quiet = TRUE)
```
Output:
```{r echo=FALSE}
out <- file.path(tmp, "out")
err <- file.path(tmp, "err")
rx <- callr::r_bg(function() {
Sys.setenv(
TRYR_LOG_FORMAT = "JSON",
TRYR_LOG_DIGITS = "6"
)
plumber::pr("inst/examples/plumber.R") |>
plumber::pr_set_debug(FALSE) |>
plumber::pr_hooks(
list(
preroute = function(data, req, res) {
tryr::msg(
title = paste(
method = req$REQUEST_METHOD,
path = req$PATH_INFO
),
level = "INFO"
)
}
)
) |>
plumber::pr_run(
port = 8000,
quiet = TRUE)
},
stdout = out,
stderr = err
)
Sys.sleep(1)
URL <- "http://localhost:8000/try?x=0"
post(URL, out, err)
o <- rx$kill()
```
```{r echo=FALSE}
out <- file.path(tmp, "out")
err <- file.path(tmp, "err")
rx <- callr::r_bg(function() {
Sys.setenv(
TRYR_LOG_FORMAT = "JSON",
TRYR_LOG_DIGITS = "6"
)
plumber::pr("inst/examples/plumber.R") |>
plumber::pr_set_debug(FALSE) |>
plumber::pr_hooks(
list(
preroute = function(data, req, res) {
tryr::msg(
title = paste(
method = req$REQUEST_METHOD,
path = req$PATH_INFO
),
level = "INFO"
)
}
)
) |>
plumber::pr_run(
port = 8000,
quiet = TRUE)
},
stdout = out,
stderr = err
)
Sys.sleep(1)
URL <- "http://localhost:8000/try?x=-1"
post(URL, out, err)
o <- rx$kill()
```
```{r echo=FALSE}
out <- file.path(tmp, "out")
err <- file.path(tmp, "err")
rx <- callr::r_bg(function() {
Sys.setenv(
TRYR_LOG_FORMAT = "JSON",
TRYR_LOG_DIGITS = "6"
)
plumber::pr("inst/examples/plumber.R") |>
plumber::pr_set_debug(FALSE) |>
plumber::pr_hooks(
list(
preroute = function(data, req, res) {
tryr::msg(
title = paste(
method = req$REQUEST_METHOD,
path = req$PATH_INFO
),
level = "INFO"
)
}
)
) |>
plumber::pr_run(
port = 8000,
quiet = TRUE)
},
stdout = out,
stderr = err
)
Sys.sleep(1)
URL <- "http://localhost:8000/try?x=a"
post(URL, out, err)
o <- rx$kill()
```
```{r echo=FALSE}
out <- file.path(tmp, "out")
err <- file.path(tmp, "err")
rx <- callr::r_bg(function() {
Sys.setenv(
TRYR_LOG_FORMAT = "JSON",
TRYR_LOG_DIGITS = "6"
)
plumber::pr("inst/examples/plumber.R") |>
plumber::pr_set_debug(FALSE) |>
plumber::pr_hooks(
list(
preroute = function(data, req, res) {
tryr::msg(
title = paste(
method = req$REQUEST_METHOD,
path = req$PATH_INFO
),
level = "INFO"
)
}
)
) |>
plumber::pr_run(
port = 8000,
quiet = TRUE)
},
stdout = out,
stderr = err
)
Sys.sleep(1)
URL <- "http://localhost:8000/try?x="
post(URL, out, err)
o <- rx$kill()
```
Structured errors are handled by the `http_error()` function that uses default error messages as defined in the `http_status_codes` data frame.
The `http_success()` works similarly but it does not produce an error. It can also pass a `body` argument. This is useful if we need to return simple status messages when responding to webhooks during async execution.
The `http_response()` can be used for any of the status codes and is behind the `http_handler()` function that is useful to set default handlers for Plumber:
```{r eval=FALSE}
plumber::pr("inst/examples/plumber.R") |>
plumber::pr_set_debug(FALSE) |>
plumber::pr_set_404(
function(req, res) {
tryr::msg(
title = paste0(
"Status 404: ",
tryr::http_status_codes["404", "message"]),
level = "ERROR"
)
tryr::http_handler(req, res, 404L)
}
) |>
plumber::pr_set_error(
function(req, res, err) {
tryr::msg(
title = paste0(
"Status 500: ",
tryr::http_status_codes["500", "message"]),
message = err,
level = "ERROR"
)
tryr::http_handler(req, res, 500L)
}
) |>
plumber::pr_hooks(
list(
preroute = function(data, req, res) {
tryr::msg(
title = paste(
method = req$REQUEST_METHOD,
path = req$PATH_INFO
),
level = "INFO"
)
}
)
) |>
plumber::pr_run(
port = 8000,
quiet = TRUE)
```
## See the action
The `inst/examples` folder contains Shiny apps that you can edit and use to explore the differences between Plumber's default error handling (`/test` endpoint) and the tryr approach (`/tryr` endpoint). See the response, request, STDOUT and STDERR from the calls:
```{r eval=FALSE}
source("inst/examples/app.R")
```
![](https://raw.githubusercontent.com/analythium/tryr/main/tryr-01.png)
The second app is more general. You can edit the `plumber_fun` function definition and explore your own API's output printed to STDOUT and STDERR:
```{r eval=FALSE}
source("inst/examples/explore.R")
```
![](https://raw.githubusercontent.com/analythium/tryr/main/tryr-02.png)
## Supported API frameworks
- [plumber](https://www.rplumber.io/): the most popular API framework for R accounting for more than 95% of the total downloads.
- [RestRserve](https://restrserve.org/): the second most popular framework accounting for 2% of the total downloads. See the [`RestRserve.R`](inst/examples/RestRserve.R) example.
[Other frameworks](https://gist.github.com/psolymos/284b43b8dd0583b33ca7fc7dcf71082b) (fiery, beakr, ambiorix) are not supported -- using them will likely result in an error.
Let's see an example for RestRserve:
```{verbatim lang="R", file="inst/examples/RestRserve.R"}
```
```{r echo=FALSE}
out <- file.path(tmp, "out")
err <- file.path(tmp, "err")
rx <- callr::r_bg(function() {
source("inst/examples/RestRserve.R")
},
stdout = out,
stderr = err
)
Sys.sleep(1)
URL <- "http://localhost:8000/try?x=0"
post(URL, out, err)
o <- rx$kill()
```
```{r echo=FALSE}
out <- file.path(tmp, "out")
err <- file.path(tmp, "err")
rx <- callr::r_bg(function() {
source("inst/examples/RestRserve.R")
},
stdout = out,
stderr = err
)
Sys.sleep(1)
URL <- "http://localhost:8000/try?x=-1"
post(URL, out, err)
o <- rx$kill()
```
```{r echo=FALSE}
out <- file.path(tmp, "out")
err <- file.path(tmp, "err")
rx <- callr::r_bg(function() {
source("inst/examples/RestRserve.R")
},
stdout = out,
stderr = err
)
Sys.sleep(1)
URL <- "http://localhost:8000/try?x=a"
post(URL, out, err)
o <- rx$kill()
```
```{r echo=FALSE}
out <- file.path(tmp, "out")
err <- file.path(tmp, "err")
rx <- callr::r_bg(function() {
source("inst/examples/RestRserve.R")
},
stdout = out,
stderr = err
)
Sys.sleep(1)
URL <- "http://localhost:8000/try?x="
post(URL, out, err)
o <- rx$kill()
```
## What else is included
The functions use the `msg` function for logging. This function writes the log message to STDOUT or STDERR as a side effect. Instead of using `glue`, `sprintf`, or `paste`, you can use the `%+%` operator that is similar to addition in JavaScript:
```{r}
library(tryr)
n <- 5
"n = " %+% n
msg("Success", "We did it!")
msg("Success", "n = " %+% n %+% " is right", "SUCCESS")
msg("Error", "n = " %+% n %+% " is too high", "ERROR")
msg("Success", "We did it!", format = "JSON")
msg("Success", "n = " %+% n %+% " is right", "SUCCESS", digits = 0)
msg("Error", "n = " %+% n %+% " is too high", "ERROR", digits = 6)
```
You can't see the errors because those are written to STDERR.
## Other considerations
Similar ideas in the [tryCatchLog](https://CRAN.R-project.org/package=tryCatchLog) package for the general use case.
STDOUT is buffered, needs a flush. STDERR is unbuffered, more immediate ([_Do progress reports/logging information belong on stderr or stdout?_](https://unix.stackexchange.com/questions/331611/do-progress-reports-logging-information-belong-on-stderr-or-stdout))