Something went wrong. Try again.
Correctness- and interoperability-oriented Tangled CLI
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283open Camlet_domain
let protocol_error ~code ~message = App_error.make ~category:Protocol ~code ~message
let valid_utf8 value = Uutf.String.fold_utf_8 (fun valid _ -> function `Uchar _ -> valid | `Malformed _ -> false) true value
let parse ~authority ~code body = try if valid_utf8 body then Ok (Yojson.Safe.from_string body) else raise (Yojson.Json_error "invalid UTF-8") with Yojson.Json_error _ -> Error (protocol_error ~code ~message:(authority ^ " returned malformed JSON"))
let object_fields ~authority ~code = function | `Assoc fields -> Ok fields | _ -> Error (protocol_error ~code ~message:(authority ^ " returned a JSON value of the wrong type"))
let occurrences name fields = List.filter_map (fun (key, value) -> if String.equal key name then Some value else None) fields
let required_field ~authority ~code name fields = match occurrences name fields with | [ value ] -> Ok value | [] -> Error (protocol_error ~code ~message:(authority ^ " response is missing required field " ^ name)) | _ -> Error (protocol_error ~code ~message: (authority ^ " response repeats trust-critical field " ^ name))
let optional_field ~authority ~code name fields = match occurrences name fields with | [ value ] -> Ok (Some value) | [] -> Ok None | _ -> Error (protocol_error ~code ~message: (authority ^ " response repeats trust-critical field " ^ name))
let wrong_string_type ~authority ~code name = Error (protocol_error ~code ~message:(authority ^ " response field " ^ name ^ " must be a string"))
let required_string ~authority ~code name fields = match required_field ~authority ~code name fields with | Error error -> Error error | Ok (`String value) -> Ok value | Ok _ -> wrong_string_type ~authority ~code name
let optional_string ~authority ~code name fields = match optional_field ~authority ~code name fields with | Error error -> Error error | Ok None -> Ok None | Ok (Some (`String value)) -> Ok (Some value) | Ok (Some _) -> wrong_string_type ~authority ~code name
let optional_or_null_string ~authority ~code name fields = match optional_field ~authority ~code name fields with | Error error -> Error error | Ok None | Ok (Some `Null) -> Ok None | Ok (Some (`String value)) -> Ok (Some value) | Ok (Some _) -> Error (protocol_error ~code ~message: (authority ^ " response field " ^ name ^ " must be a string or null"))