123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491(*****************************************************************************)(* *)(* Open Source License *)(* Copyright (c) 2019 Nomadic Labs <contact@nomadic-labs.com> *)(* *)(* Permission is hereby granted, free of charge, to any person obtaining a *)(* copy of this software and associated documentation files (the "Software"),*)(* to deal in the Software without restriction, including without limitation *)(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)(* and/or sell copies of the Software, and to permit persons to whom the *)(* Software is furnished to do so, subject to the following conditions: *)(* *)(* The above copyright notice and this permission notice shall be included *)(* in all copies or substantial portions of the Software. *)(* *)(* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR*)(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)(* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *)(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)(* DEALINGS IN THE SOFTWARE. *)(* *)(*****************************************************************************)letjson_ppiddescriptionencodingppfdata=Format.pp_print_stringppf@@Data_encoding.Json.to_string@@letpp_encoding=Data_encoding.(obj3(req"id"string)(req"description"string)(req"data"encoding))inData_encoding.Json.constructpp_encoding(id,description,data)(* This is a global variable because it is shared amongst all the error monads (the
shell's and the protocols'). See below for use. *)letset_error_encoding_cache_dirty=ref(fun()->())moduleMake(Prefix:Sig.PREFIX):sigtypeerror=..includeSig.COREwithtypeerror:=errorincludeSig.EXTwithtypeerror:=errorincludeSig.WITH_WRAPPEDwithtypeerror:=errorend=structtypeerror=..leterror_encoding_name=ifPrefix.id=""then"error"elsePrefix.id^"error"moduletypeWrapped_error_monad=sigtypeunwrapped=..includeSig.COREwithtypeerror:=unwrappedincludeSig.EXTwithtypeerror:=unwrappedvalunwrap:error->unwrappedoptionvalwrap:unwrapped->errorendtypefull_error_category=|MainofSig.error_category|Wrappedof(moduleWrapped_error_monad)typeencoding_case=|Non_recursiveoferrorData_encoding.case|Recursiveof(errorData_encoding.t->errorData_encoding.case)(* the toplevel store for error kinds *)typeerror_kind=|Error_kind:{id:string;title:string;description:string;from_error:error->'erroption;category:full_error_category;encoding_case:encoding_case;pp:Format.formatter->'err->unit;}->error_kindtypeerror_info={category:Sig.error_category;id:string;title:string;description:string;schema:Data_encoding.json_schema;}leterror_kinds:error_kindlistref=ref[]lethas_recursive_error=reffalseletget_registered_errors():error_infolist=List.flatten(List.map(function|Error_kind{id="";_}->[]|Error_kind{id;title;description;category=Maincategory;encoding_case;_;}->(matchencoding_casewith|Non_recursiveencoding_case->[{id;title;description;category;schema=Data_encoding.Json.schema(Data_encoding.union[encoding_case]);};]|Recursivemake_encoding_case->[{id;title;description;category;schema=Data_encoding.Json.schema(Data_encoding.muerror_encoding_name@@funerror_encoding->Data_encoding.union[make_encoding_caseerror_encoding]);};])|Error_kind{category=Wrapped(moduleWEM);_}->List.map(fun{WEM.id;title;description;category;schema}->{id;title;description;category;schema})(WEM.get_registered_errors()))!error_kinds)leterror_encoding_cache=refNonelet()=letset_older_caches_dirty=!set_error_encoding_cache_dirtyinset_error_encoding_cache_dirty:=fun()->set_older_caches_dirty();error_encoding_cache:=Noneletstring_of_category=function|`Permanent->"permanent"|`Temporary->"temporary"|`Branch->"branch"letpp_infoppf{category;id;title;description;schema}=Format.fprintfppf"@[<v 2>category : %s\n\
id : %s\n\
title : %s\n\
description : %s\n\
schema : %a@]"(string_of_categorycategory)idtitledescription(Json_repr.pp(moduleJson_repr.Ezjsonm))(Json_schema.to_jsonschema)(* Catch all error when 'serializing' an error. *)typeerror+=Unclassifiedofstringlet()=letid=""inletcategory=Main`Temporaryinletto_errormsg=Unclassifiedmsginletfrom_error=function|Unclassifiedmsg->Somemsg|error->letmsg=Obj.Extension_constructor.(name@@of_valerror)inSome("Unclassified error: "^msg^". Was the error registered?")inlettitle="Generic error"inletdescription="An unclassified error"inletencoding_case=letopenData_encodingincaseJson_only~title:"Generic error"(def"generic_error"~title~description@@conv(funx->((),x))(fun((),x)->x)@@obj2(req"kind"(constant"generic"))(req"error"string))from_errorto_errorinletencoding_case=Non_recursiveencoding_caseinletppppfs=Format.fprintfppf"@[<h 0>%a@]"Format.pp_print_textsinerror_kinds:=Error_kind{id;title;description;from_error;category;encoding_case;pp}::!error_kinds(* Catch all error when 'deserializing' an error. *)typeerror+=Unregistered_errorofData_encoding.jsonlet()=letid=""inletcategory=Main`Temporaryinletto_errormsg=Unregistered_errormsginletfrom_error=function|Unregistered_errorjson->Somejson|_->Noneinletencoding_case=letopenData_encodingincaseJson_only~title:"Unregistered error"jsonfrom_errorto_errorinletencoding_case=Non_recursiveencoding_caseinletppppfjson=Format.fprintfppf"@[<v 2>Unregistered error:@ %a@]"Data_encoding.Json.ppjsoninerror_kinds:=Error_kind{id;title="";description="";from_error;category;encoding_case;pp;}::!error_kindsletprepare_registrationnew_id=!set_error_encoding_cache_dirty();letname=Prefix.id^new_idinifList.exists(fun(Error_kind{id;_})->name=id)!error_kindstheninvalid_arg(Printf.sprintf"register_error_kind: duplicate error name: %s"name);nameletregister_wrapped_error_kind(moduleWEM:Wrapped_error_monad)~id~title~description=letname=prepare_registrationidinletencoding_case=letunwraperr=matchWEM.unwraperrwith|Some(WEM.Unclassified_)->None|Some(WEM.Unregistered_error_)->None|res->resinletwraperr=matcherrwith|WEM.Unclassified_->failwith"ignore wrapped error when serializing"|WEM.Unregistered_error_->failwith"ignore wrapped error when deserializing"|res->WEM.wrapresinNon_recursive(caseJson_only~title:nameWEM.error_encodingunwrapwrap)inerror_kinds:=Error_kind{id=name;category=Wrapped(moduleWEM);title;description;from_error=WEM.unwrap;encoding_case;pp=WEM.pp;}::!error_kindsletadd_kind_and_id~category~name~title~descriptionencodingfrom_errorto_error=ifnot(Data_encoding.is_objencoding)theninvalid_arg(Printf.sprintf"Specified encoding for \"%s%s\" is not an object, but error \
encodings must be objects."Prefix.idname);letwith_id_and_kind_encoding=merge_objs(obj2(req"kind"(constant(string_of_categorycategory)))(req"id"(constantname)))encodingincaseJson_only~title~description(conv(funx->(((),()),x))(fun(((),()),x)->x)with_id_and_kind_encoding)from_errorto_errorletregister_error_kindcategory~id~title~description?ppencodingfrom_errorto_error=letname=prepare_registrationidinletencoding_case=Non_recursive(add_kind_and_id~category~name~title~descriptionencodingfrom_errorto_error)inerror_kinds:=Error_kind{id=name;category=Maincategory;title;description;from_error;encoding_case;pp=Option.value~default:(json_ppnamedescriptionencoding)pp;}::!error_kindsletregister_recursive_error_kindcategory~id~title~description~ppmake_encodingfrom_errorto_error=letname=prepare_registrationidinletencoding_case=Recursive(funerror_encoding->letencoding=make_encodingerror_encodinginadd_kind_and_id~category~name~title~descriptionencodingfrom_errorto_error)inhas_recursive_error:=true;error_kinds:=Error_kind{id=name;category=Maincategory;title;description;from_error;encoding_case;pp;}::!error_kindsleterror_encoding()=match!error_encoding_cachewith|None->letencoding=if!has_recursive_errorthenData_encoding.muerror_encoding_name@@funerror_encoding->letcases=List.map(fun(Error_kind{encoding_case;_})->matchencoding_casewith|Non_recursivecase->case|Recursivemake->makeerror_encoding)!error_kindsinletunion_encoding=Data_encoding.unioncasesinletopenData_encodingindynamic_size@@splitted~json:union_encoding~binary:(conv(Json.constructunion_encoding)(Json.destructunion_encoding)json)elseletcases=List.map(fun(Error_kind{encoding_case;_})->matchencoding_casewith|Non_recursivecase->case|Recursive_->assertfalse)!error_kindsinletunion_encoding=Data_encoding.unioncasesinletopenData_encodingindynamic_size@@splitted~json:union_encoding~binary:(conv(Json.constructunion_encoding)(Json.destructunion_encoding)json)inerror_encoding_cache:=Someencoding;encoding|Someencoding->encodingleterror_encoding=Data_encoding.delayederror_encodingletjson_of_errorerror=Data_encoding.Json.constructerror_encodingerrorleterror_of_jsonjson=Data_encoding.Json.destructerror_encodingjsonletfind_info_of_errorerror=List.find(fun(Error_kind{from_error;_})->Option.is_some(from_errorerror))!error_kinds|>function|Error_kind{id;title;description;category;encoding_case;_}->(matchcategorywith|Wrapped(moduleWEM)->(matchWEM.unwraperrorwith|None->failwith"incorrectly registered wrapped error"|Someerror->let{WEM.id;title;description;category;schema}=WEM.find_info_of_errorerrorin{id;title;description;category;schema})|Maincategory->(matchencoding_casewith|Non_recursiveencoding_case->{id;title;description;category;schema=Data_encoding.Json.schema(Data_encoding.union[encoding_case]);}|Recursivemake_encoding_case->{id;title;description;category;schema=Data_encoding.Json.schema(Data_encoding.muerror_encoding_name@@funerror_encoding->Data_encoding.union[make_encoding_caseerror_encoding]);}))letclassify_errorerror=letrecfinde=function|[]->`Temporary|Error_kind{from_error;category;_}::rest->(matchfrom_errorewith|Some_->(matchcategorywith|Mainerror_category->error_category|Wrapped(moduleWEM)->(matchWEM.unwrapewith|Somee->WEM.classify_errore|None->finderest))|None->finderest)infinderror!error_kindsletppppferror=letrecfind=function|[]->Format.fprintfppf"An unspecified error happened, the component that threw it did \
not provide a specific trace. This should be reported."|Error_kind{from_error;pp;_}::errors->(matchfrom_errorerrorwithNone->finderrors|Somex->ppppfx)infind!error_kindsend