Skip to content

Conditional GETs #75

Open
Open

Description

@ElianHugh

It would be neat if plumber2 supported conditional GETs out of the box. I suspect I could use the tag creation functionality to do it myself, but it would be a nice to have for improving server-side rendered HTML applications.

Using an etag, plumber2 could automatic respond with a 304 Not Modified and short-circuit the response if the client's If-None-Match matches the server. This would speed up server responses and reduce repetitive computations. Perhaps the etag generation mechanism could be specified by a roxygen tag too.

Eg

#' @get /
#' @etag Sys.Date()
function() {
   my_html()
}

In this example, on a 200 OK, the server would return the normal response body as well as etag generated via Sys.Date(). Subsequent gets from the same client would return a 304 to the client if the client's etag date matches the server's (via string equality).

Scope: only applies to GET/HEAD routes, & no response body is sent

References

As an aside (and probably out of scope for this issue), being able to have a @cache tag to automatically cache responses would be nice. We can do this manually atm via eg memoise and client id, but it would make these patterns more discoverable and feel more "batteries included" particularly for SSR purposes

Activity

  1. ElianHugh commented on Jan 30, 2026

    @ElianHugh
    Author

    Would this be something that would belong in plumber2? I'm still learning the semantics of the API. This just implements weak etags, and I'm sure there's a more durable parsing method, but this seems to work for me.

    new_etag <- function(x) {
        stopifnot(length(x) == 1L, !is.null(x), !is.na(x))
        sprintf('W/"%s"', as.character(x))
    }
    
    strip_weak_prefix <- function(x) {
        reg <- regexec('^(?:W/)?(".*")$', x)
        res <- regmatches(x, reg)[[1]]
        if (length(res) == 0) return(NA_character_)
        res[[2]]
    }
    
    inm_match <- function(inm, etag) {
        inm <- trimws(inm %||% "")
    
        etag <- strip_weak_prefix(etag)
    
        if (is.na(etag)) return(FALSE)
        if (identical(inm, "")) return(FALSE)
        if (identical(inm, "*")) return(TRUE)
    
        candidates <- trimws(strsplit(inm, ",", fixed = TRUE)[[1L]])
        candidates <- candidates[nzchar(candidates)]
        candidates <- vapply(candidates, strip_weak_prefix, character(1L))
    
        any(!is.na(candidates) & candidates == etag)
    }
    
    api_cget <- function(api, path, etag_fn) {
        handler <- function(request, response) {
            inm <- request$get_header("If-None-Match")
    
            etag <- new_etag(etag_fn())
    
            response$set_header("ETag", etag)
    
            if (inm_match(inm, etag)) {
                response$status <- 304L
                plumber2::Break
            } else {
                plumber2::Next
            }
        }
    
        plumber2::api_get_header(api, path = path, handler = handler)
    
        api
    }
    
    plumber2::add_plumber2_tag("etag", function(block, call, tags, values, env) {
        class(block) <- c("etag", class(block))
        stopifnot("get" %in% tags)
    
        tag_idx <- which(tags == "etag")
        # tag function should be a function that is called without any arguments
        # and returns a single value that can be interpreted as a string
        tag_fn <- eval(parse(text=values[[tag_idx]] %||% ""), envir = env)
    
        stopifnot(is.function(tag_fn))
        block$etag_fn <- tag_fn
        block
    })
    
    #' @importFrom plumber2 apply_plumber2_block
    #' @export
    apply_plumber2_block.etag <- function(
        block,
        api,
        route_name,
        root,
        ...
    ) {
        NextMethod()
        for (i in seq_along(block$endpoints)) {
            for (path in block$endpoints[[i]]$path) {
                api <- api_cget(
                    api,
                    etag_fn = block$etag_fn,
                    path = paste0(root, path)
                )
            }
        }
        api
    }
    x <- 1L
    
    #' @get /
    #' @etag Sys.Date
    function(request, response) {
        print("got here")
        x <<- x + 1L
        x
    }
    curl -i -H 'If-None-Match: "a", W/"b", W/"2026-01-30"' http://localhost:9998/
    
    #> HTTP/1.1 304 Not Modified
    #> Date: Fri, 30 Jan 2026 00:50:32 GMT
    #> vary: Accept
    #> content-type: application/json
    #> etag: W/"2026-01-30"

    Edit:

    I have a more "useful" usecase example in my repo here: https://github.com/ElianHugh/freshwater/blob/7be81324ff4c66b7eaef491e5d54fe87fd2451ae/inst/examples/cache.R

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions