-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathserver.R
245 lines (214 loc) · 6.74 KB
/
server.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
#' Serve a local data directory for use with a browser
#'
#' This is a utility function that can be used to server
#' a local directory with data so that it can be used
#' in the genome browser.
#'
#' Note: This is intended for local development and use.
#' For a production deployment, refer to the vignette
#' on creating URLs for more robust options.
#'
#' @param path The path to the directory with data to serve
#' @param port The port to serve the directory on
#'
#' @return a list containing information about the newly
#' created HTTP server including the host, port, interval,
#' and URL. The list also contains the stop_server()
#' function which can be used to stop the server
#'
#' @export
#'
#' @examples
#' \dontrun{
#' server <- serve_data("~/path/to/my-data")
#' # use server$stop_server() to stop
#' }
serve_data <- function(path, port = 5000) {
path <- normalizePath(path, mustWork = TRUE)
if (path != ".") {
# clean up R directory after exit if not current directory
original_dir <- setwd(path)
on.exit(setwd(original_dir))
}
generate_cli_message(path, port)
server <- create_server(path, port)
app <- list(call = serve_directory(path))
server$start_server(app)
invisible(server)
}
create_server <- function(path, port) {
host <- "127.0.0.1"
server <- NULL
list(
host = host,
port = as.integer(port),
interval = 1,
url = sprintf("http://%s:%d", "127.0.0.1", as.integer(port)),
start_server = function(app) {
server_id <- httpuv::startServer(host, port, app)
server <<- server_id
invisible(server_id)
},
stop_server = function() {
if (is.null(server)) {
stop("The server has not been started.")
} else {
httpuv::stopServer(server)
}
}
)
}
serve_directory <- function(path) {
function(req) {
original_dir <- setwd(path)
on.exit(setwd(original_dir))
req_path <- resolve_req_path(req)
# response content
if (is.null(req$HTTP_RANGE)) {
status <- 200L
} else {
status <- 206L
range <- parse_range(req$HTTP_RANGE, req_path)
}
type <- guess_type(path)
body <- generate_body(req, req_path)
if (is.character(body) && length(body) > 1) {
body <- stringr::str_c(body, collapse = "")
}
headers <- c(
list(
"Access-Control-Allow-Origin" = "*",
"Access-Control-Allow-Headers" = "range, Origin, Content-Type",
"Access-Control-Expose-Headers" = "Content-Length,Content-Range",
"Content-Type" = type
), if (status == 206L) {
list(
"Content-Range" = paste0(
"bytes ",
range[2],
"-",
range[3],
"/",
file.info(req_path)[, "size"]
)
)
},
"Accept-Ranges" = "bytes"
)
list(
status = status,
body = body,
headers = headers
)
}
}
resolve_req_path <- function(req) {
req_path <- httpuv::decodeURIComponent(req$PATH_INFO)
Encoding(req_path) <- "UTF-8"
if (grepl("^/", req_path)) {
stringr::str_c(".", req_path)
} else if (req_path == "") {
"."
}
}
generate_body <- function(req, req_path) {
range <- req$HTTP_RANGE
if (is.null(range)) {
read_raw(req_path)
} else {
range <- parse_range(range, req_path)
byte2 <- as.numeric(range[2])
byte3 <- as.numeric(range[3])
if (length(range) < 3 || (range[1] != "bytes") || (byte2 >= byte3)) {
return(
list(
status = 416L, headers = list("Content-Type" = "text/plain"),
body = "Requested range not satisfiable\r\n"
)
)
}
connection <- file(req_path, open = "rb", raw = TRUE)
on.exit(close(connection))
seek(connection, where = byte2, origin = "start")
readBin(connection, "raw", byte3 - byte2 + 1)
}
}
read_raw <- function(req_path) {
readBin(
req_path,
"raw",
file.info(req_path)[, "size"]
)
}
guess_type <- function(path) {
mimetype <- function(...) {
system2("mimetype", c("-b", shQuote(path)), ...)
}
if (Sys.which("mimetype") == "" || mimetype(stdout = NULL) != 0) {
return(mime::guess_type(path))
}
mimetype(stdout = TRUE)
}
parse_range <- function(range, req_path) {
range <- strsplit(range, split = "(=|-)")[[1]]
if (length(range) == 2 && range[1] == "bytes") {
# open-end range request
range[3] <- file.info(req_path)[, "size"] - 1
}
range
}
generate_cli_message <- function(path, port) {
data_files <- dir(path)
cli::cli_par()
cli::cli_text("Serving data from: {path}")
cli::cli_end()
cli::cli_par()
cli::cli_text("Use the following URLs for your track data:")
cli::cli_end()
assembly <- c()
alignments <- c()
feature <- c()
variant <- c()
wiggle <- c()
for (i in seq_along(data_files)) {
stripped_gz <- strip_gz(data_files[i])
if (stringr::str_ends(stripped_gz, ".fa") || stringr::str_ends(stripped_gz, ".fasta")) {
assembly <- c(assembly, stringr::str_glue("http://127.0.0.1:{port}/{data_files[i]}"))
} else if (stringr::str_ends(stripped_gz, ".bam") || stringr::str_ends(stripped_gz, ".cram")) {
alignments <- c(alignments, stringr::str_glue("http://127.0.0.1:{port}/{data_files[i]}"))
} else if (stringr::str_ends(stripped_gz, ".gff") || stringr::str_ends(stripped_gz, ".gff3")) {
feature <- c(feature, stringr::str_glue("http://127.0.0.1:{port}/{data_files[i]}"))
} else if (stringr::str_ends(stripped_gz, ".vcf")) {
variant <- c(variant, stringr::str_glue("http://127.0.0.1:{port}/{data_files[i]}"))
} else if (stringr::str_ends(stripped_gz, ".bw") || stringr::str_ends(stripped_gz, ".bigWig")) {
wiggle <- c(wiggle, stringr::str_glue("http://127.0.0.1:{port}/{data_files[i]}"))
}
}
log_track_message("Assembly", assembly)
log_track_message("Alignments", alignments)
log_track_message("Feature", feature)
log_track_message("Variant", variant)
log_track_message("Wiggle", wiggle)
cli::cli_par()
cli::cli_alert_info("Note: this server is intended for local development and use.")
cli::cli_text(
"For a production deployment, refer to the vignette about creating URLs for a discussion of better options."
)
cli::cli_end()
cli::cli_text("To stop the server, use the $stop_server() function.")
}
log_track_message <- function(title, track_vector, port) {
if (length(track_vector) > 0) {
cli::cli_par()
cli::cli_h2(title)
cli::cli_ul(track_vector)
cli::cli_end()
}
}
# Notes: ------------------------------------------------------------------
# This is a small static HTTP server for local files
# It is heavily inspired by the static server in the {servr} package by
# Yihui Xie
# There are two crucial requirements for serving data to JBrowse 2:
# 1. CORS must be enabled. See headers for more info.
# 2. Must support range requests