handle etag header

This commit is contained in:
Swrup 2025-09-28 17:24:32 +02:00
parent b9dfee8d3a
commit bed6e3fec1
2 changed files with 77 additions and 56 deletions

View file

@ -46,24 +46,28 @@ module Etag : sig
module to parse < "*" / #entity-tag >,
used for If-Match and If-None-Match headers *)
type t
type header_value
val parse : string -> t
val parse : string -> (header_value, string) result
val of_crockford32 : string -> (t, string) result
val to_field_value : t -> string
val evaluate : t -> header_value -> bool
end = struct
type etag = { weak: bool; value: string }
type t = Any_etag | Etag_list of etag list
(* raw etag *)
type t = string
let pp_etag ppf { weak; value } =
(* type for the value of header field *)
type header_etag_item = { weak: bool; value: string }
type header_value = Any_etag | Etag_list of header_etag_item list
let pp_header_etag_item ppf { weak; value } =
if weak then Fmt.pf ppf {|W/"%s"|} value else Fmt.pf ppf {|"%s"|} value
let pp_etag_list = Fmt.list ~sep:(Fmt.any ", ") pp_etag
let to_field_value t =
(* always weak comparison for If-None-Match header *)
let v = { weak= true; value= t } in
Fmt.str "%a" pp_header_etag_item v
let pp ppf = function
| Any_etag -> Fmt.pf ppf "*"
| Etag_list etags -> Fmt.pf ppf "%a" pp_etag_list etags
let to_field_value t = Fmt.str "%a" pp t
let invalid_etag = Error "invalid etag field"
let has_valid_charset s =
@ -74,13 +78,7 @@ end = struct
String.for_all f s
let of_crockford32 s =
(* always weak comparison for If-None-Match header *)
let weak = true in
match has_valid_charset s with
| false -> invalid_etag
| true ->
let v = Etag_list [ { weak; value= s } ] in
Ok v
match has_valid_charset s with false -> invalid_etag | true -> Ok s
let trim_dquote s =
let len = String.length s in
@ -89,12 +87,12 @@ end = struct
else invalid_etag
let parse s =
if String.trim s = "*" then Any_etag
if String.trim s = "*" then Ok Any_etag
else
String.split_on_char ',' s
|> List.map String.trim
|> List.filter (( <> ) "")
|> List.map (fun s ->
|> Syntax.list_map (fun s ->
(* "W/" is the weak comparison indicator *)
let weak, s =
if String.starts_with ~prefix:"W/" s then
@ -104,6 +102,17 @@ end = struct
Result.bind (trim_dquote s) (fun s ->
if has_valid_charset s then Ok { weak; value= s }
else invalid_etag))
|> List.filter_map Result.to_option
|> fun l -> Etag_list l
|> Result.map (fun l -> Etag_list l)
(* To evaluate a received If-None-Match header field:
- If the field value is "*", the condition is false
if the origin server has a current representation for the target resource.
- If the field value is a list of entity tags, the condition is false
if one of the listed tags matches the entity tag of the selected representation.
- Otherwise, the condition is true. *)
let evaluate t header_value =
match header_value with
| Any_etag -> false
| Etag_list l ->
not @@ List.exists (fun { weak= _; value } -> String.equal t value) l
end