123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422(*****************************************************************************)(* *)(* Open Source License *)(* Copyright (c) 2018 Dynamic Ledger Solutions, Inc. <contact@tezos.com> *)(* Copyright (c) 2020 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. *)(* *)(*****************************************************************************)moduletypeERROR_CATEGORY=sigtypetvaldefault_category:tvalstring_of_category:t->stringvalclassify:t->Error_classification.tendmoduletypePREFIX=sig(** The identifier for parts of the code that need their own error monad. It
is expected (but not enforced) that the identifier:
is printable and easy to read once printed, and
ends with a separator (typically a dot or a dash). *)valid:stringendmoduletypeCORE=sigtypeerror_categorytypeerror=..valstring_of_category:error_category->string(** The encoding for errors.
Note that this encoding has a few peculiarities, some of which may impact
your code. These peculiarities are due to the type [error] being an
extensible variant.
Because the [error] type is an extensible variant, you must register an
encoding for each error constructor you add to [error]. This is done via
{!register_error_kind}.
Because the [error] type is an extensible variant, with dynamically
registered errors (see peculiarity above), there are no tags
associated with each error. This does not affect the JSON encoding, but it
does impose restrictions on the binary encoding. The chosen workaround is
to encode errors as JSON and to encode the JSON to binary form. As a
result, errors can be somewhat large in binary: they include field names
and such.
Because the [error] type is an extensible variant, with dynamically
registered errors (see peculiarity above), the encoding must be recomputed
when a new error is registered. This is achieved by the means of a
{!Data_encoding.delayed} combinator: the encoding is recomputed on-demand.
There is a caching mechanism so that, in the case where no new errors have
been registered since the last use, the last result is used.
This last peculiarity imposes a limit on the use of [error_encoding]
itself. Specifically, it is invalid to use [error_encoding] inside the
[~json] argument of a {!Data_encoding.splitted}. This is because
[splitted] evaluates the [delayed] combinator once-and-for-all to produce
a json encoding. (Note that the following
data-encoding combinators use [splitted] internally:
{!Data_encoding.Compact.make}, {!Data_encoding.assoc}, and
{!Data_encoding.lazy_encoding}. As a result, it is invalid to use
[error_encoding] within the arguments of these combinators as well.) *)valerror_encoding:errorData_encoding.tvalpp:Format.formatter->error->unit(** The error data type is extensible. Each module can register specialized
error serializers
[id] unique name of this error. Ex.: overflow_time_counter
[title] more readable name. Ex.: Overflow of time counter
[description] human readable description. Ex.: The time counter overflowed while computing delta increase
[pp] formatter used to pretty print additional arguments. Ex.: The time counter overflowed while computing delta increase. Previous value %d. Delta: %d
[encoder] [decoder] data encoding for this error. If the error has no value, specify Data_encoding.empty
*)valregister_error_kind:error_category->id:string->title:string->description:string->?pp:(Format.formatter->'err->unit)->'errData_encoding.t->(error->'erroption)->('err->error)->unit(** Classify an error using the registered kinds *)valclassify_error:error->Error_classification.t(** Catch all error when 'serializing' an error. *)typeerror+=privateUnclassifiedofstring(**)(** Catch all error when 'deserializing' an error. *)typeerror+=privateUnregistered_errorofData_encoding.json(** An error serializer *)valjson_of_error:error->Data_encoding.jsonvalerror_of_json:Data_encoding.json->error(** {2 Error documentation} *)(** Error information *)typeerror_info={category:error_category;id:string;title:string;description:string;schema:Data_encoding.json_schema;}valpp_info:Format.formatter->error_info->unit(** [find_info_of_error e] retrieves the `error_info` associated with the
given error `e`.
@raise Invalid_argument if the error is a wrapped error from another monad
@raise Not_found if the error's constructor has not been registered
*)valfind_info_of_error:error->error_info(** Retrieves information of registered errors *)valget_registered_errors:unit->error_infolistendmoduletypeWITH_WRAPPED=sigtypeerrormoduletypeWrapped_error_monad=sig(** The purpose of this module is to wrap a specific error monad [E]
into a more general error monad [Eg].
The user implementing such an interface is responsible to
maintain the following assertions
- The [Eg] error is extended locally with a specific constructor [C]
- [unwrapped] is equal to the [error] type of [E]
- [wrap] builds an [Eg] [error] value from an [E] [error] value
- [unwrap] matches on [Eg] error cases and extracts [E]
error value from [C]
As a reference implementation,
see src/lib_protocol_environment/environment_V3.ml *)typeunwrapped=..includeCOREwithtypeerror:=unwrapped(** [unwrap e] returns [Some] when [e] matches variant constructor [C]
and [None] otherwise *)valunwrap:error->unwrappedoption(** [wrap e] returns a general [error] from a specific [unwrapped]
error [e] *)valwrap:unwrapped->errorend(** Same as [register_error_kind] but for a wrapped error monad.
The codec is defined in the module parameter. It makes the category
of the error [Wrapped] instead of [Main]. *)valregister_wrapped_error_kind:(moduleWrapped_error_monad)->id:string->title:string->description:string->unitendmoduletypeTRACE=sig(** The [trace] type (included as part of the
[Tezos_lwt_result_stdlib.Lwtreslib.TRACE] module is abstract in this
interface but it is made concrete in the instantiated error monad (see
[error_monad.mli]).
The idea of abstracting the trace is so that it can evolve more easily.
Eventually, we can make the trace abstract in the instantiated error
monad, we can have different notions of traces for the protocol and the
shell, etc. *)includeTezos_lwt_result_stdlib.Lwtreslib.TRACE(** [pp_print] pretty-prints a trace of errors *)valpp_print:(Format.formatter->'err->unit)->Format.formatter->'errtrace->unit(** [pp_print_top] pretty-prints the top errors of the trace *)valpp_print_top:(Format.formatter->'err->unit)->Format.formatter->'errtrace->unitvalencoding:'errorData_encoding.t->'errortraceData_encoding.t(** [fold f init trace] traverses the trace (in an unspecified manner) so that
[init] is folded over each of the error within [trace] by [f]. Typical use
is to find the worst error, to check for the presence of a given error,
etc. *)valfold:('a->'error->'a)->'a->'errortrace->'aend(** [MONAD_EXTENSION] is the Tezos-specific extension to the generic monad
provided by Lwtreslib. It sets some defaults (e.g., it defaults traced
failures), it brings some qualified identifiers into the main unqualified
part (e.g., [return_unit]), it provides some tracing helpers and some
in-monad assertion checks. *)moduletypeMONAD_EXTENSION=sig(** for substitution *)typeerror(** for substitution *)type'errortracetypetztrace=errortracetype'atzresult=('a,tztrace)resultvalclassify_trace:tztrace->Error_classification.tmoduleLegacy_monad_globals:sigvalreturn:'a->('a,'e)resultLwt.tvalreturn_unit:(unit,'e)resultLwt.tvalreturn_none:('aoption,'e)resultLwt.tvalreturn_some:'a->('aoption,'e)resultLwt.tvalreturn_nil:('alist,'e)resultLwt.tvalreturn_true:(bool,'e)resultLwt.tvalreturn_false:(bool,'e)resultLwt.tval(>>=):'aLwt.t->('a->'bLwt.t)->'bLwt.tval(>|=):'aLwt.t->('a->'b)->'bLwt.tvalok:'a->('a,'e)resultvalerror:'e->('a,'etrace)resultval(>>?):('a,'e)result->('a->('b,'e)result)->('b,'e)resultval(>|?):('a,'e)result->('a->'b)->('b,'e)resultvalfail:'e->('a,'etrace)resultLwt.tval(>>=?):('a,'e)resultLwt.t->('a->('b,'e)resultLwt.t)->('b,'e)resultLwt.tval(>|=?):('a,'e)resultLwt.t->('a->'b)->('b,'e)resultLwt.tval(>>?=):('a,'e)result->('a->('b,'e)resultLwt.t)->('b,'e)resultLwt.tval(>|?=):('a,'e)result->('a->'bLwt.t)->('b,'e)resultLwt.tend(* Pretty-prints an error trace. *)valpp_print_trace:Format.formatter->errortrace->unit(** Pretty-prints the top error of a trace *)valpp_print_top_error_of_trace:Format.formatter->errortrace->unitvaltrace_encoding:errortraceData_encoding.t(** A serializer for result of a given type *)valresult_encoding:'aData_encoding.t->'atzresultData_encoding.t(** [record_trace err res] is either [res] if [res] is [Ok _], or it is
[Error (Trace.cons err tr)] if [res] is [Error tr].
In other words, [record_trace err res] enriches the trace that is carried
by [res] (if it is carrying a trace) with the error [err]. It leaves [res]
untouched if [res] is not carrying a trace.
You can use this to add high-level information to potential low-level
errors. E.g.,
{[
record_trace
Failure_to_load_config
(load_data_from_file config_encoding config_file_name)
]}
Note that [record_trace] takes a {e fully evaluated} error [err] as
argument. It means that, whatever the value of the result [res], the error
[err] is evaluated. This is not an issue if the error is a simple
expression (a literal or a constructor with simple parameters). However,
for any expression that is more complex (e.g., one that calls a function)
you should prefer [record_trace_eval]. *)valrecord_trace:'err->('a,'errtrace)result->('a,'errtrace)result(** [trace] is identical to [record_trace] but applies to a promise. More
formally, [trace err p] is a promise that resolves to [Ok v] if [p]
resolves to [Ok v], or it resolves to [Error (Trace.cons err tr)] if
[res] resolves to [Error tr].
In other words, [trace err p] enriches the trace that [p] resolves to (if
it does resolve to a trace) with the error [err]. It leaves the value that
[p] resolves to untouched if it is not a trace.
You can use this to add high-level information to potential low-level
errors.
Note that, like {!record_trace}, [trace] takes a fully evaluated error as
argument. For a similar reason as explained there, you should only use
[trace] with simple expressions (literal or constructor with simple
parameters) and prefer [trace_eval] for any other expression (such as ones
that include functions calls). *)valtrace:'err->('b,'errtrace)resultLwt.t->('b,'errtrace)resultLwt.t(** [record_trace_eval] is identical to [record_trace] except that the error
that enriches the trace is wrapped in a function that is evaluated only if
it is needed. More formally [record_trace_eval mkerr res] is [res] if
[res] is [Ok _], or it is [Error (Trace.cons (mkerr ()) tr)] if [res] is
[Error tr].
You can achieve the same effect by hand with
{[
match res with
| Ok _ -> res
| Error tr -> Error (Trace.cons (mkerr ()) tr)
]}
Prefer [record_trace_eval] over [record_trace] when the enriching error is
expensive to compute or heavy to allocate. *)valrecord_trace_eval:(unit->'err)->('a,'errtrace)result->('a,'errtrace)result(** [trace_eval] is identical to [trace] except that the error that enriches
the trace is wrapped in a function that is evaluated only if {e and when}
it is needed. More formally [trace_eval mkerr p] is a promise that
resolves to [Ok v] if [p] resolves to [Ok v], or it resolves to
[Error (Trace.cons (mkerr ()) tr)] if [p] resolves to [Error tr].
You can achieve the same effect by hand with
{[
let* r = p in
match r with
| Ok _ -> p
| Error tr ->
Lwt.return (Error (Trace.cons (mkerr ()) tr))
]}
Note that the evaluation of the error can be arbitrarily delayed. Avoid
using references and other mutable values in the function [mkerr].
Prefer [trace_eval] over [trace] when the enriching error is expensive to
compute or heavy to allocate or when evaluating it requires the use of
Lwt. *)valtrace_eval:(unit->'err)->('b,'errtrace)resultLwt.t->('b,'errtrace)resultLwt.t(** [error_unless flag err] is [Ok ()] if [b] is [true], it is
[Error (Trace.make err)] otherwise. *)valerror_unless:bool->'err->(unit,'errtrace)result(** [error_when flag err] is [Error (Trace.make err)] if [b] is [true], it is
[Ok ()] otherwise. *)valerror_when:bool->'err->(unit,'errtrace)result(** [fail_unless flag err] is [Lwt.return @@ Ok ()] if [b] is [true], it is
[Lwt.return @@ Error (Trace.make err)] otherwise. *)valfail_unless:bool->'err->(unit,'errtrace)resultLwt.t(** [fail_when flag err] is [Lwt.return @@ Error (Trace.make err)] if [b] is
[true], it is [Lwt.return @@ Ok ()] otherwise. *)valfail_when:bool->'err->(unit,'errtrace)resultLwt.t(** [unless b f] is [f ()] if [b] is [false] and it is a promise already
resolved to [Ok ()] otherwise.
You can use [unless] to avoid having to write an [if] statement that you
then need to populate entirely to satisfy the type-checker. E.g, you can
write [unless b f] instead of [if not b then f () else return_unit]. *)valunless:bool->(unit->(unit,'trace)resultLwt.t)->(unit,'trace)resultLwt.t(** [when_ b f] is [f ()] if [b] is [true] and it is a promise already
resolved to [Ok ()] otherwise.
You can use [when_] to avoid having to write an [if] statement that you
then need to populate entirely to satisfy the type-checker. E.g, you can
write [when_ b f] instead of [if b then f () else return_unit]. *)valwhen_:bool->(unit->(unit,'trace)resultLwt.t)->(unit,'trace)resultLwt.t(** Wrapper around [Lwt_utils.dont_wait] *)valdont_wait:(unit->(unit,'trace)resultLwt.t)->('trace->unit)->(exn->unit)->unitend