Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Overhaul the Khepri API again #145

Merged
merged 12 commits into from
Oct 5, 2022
Merged

Overhaul the Khepri API again #145

merged 12 commits into from
Oct 5, 2022

Conversation

dumbbell
Copy link
Member

@dumbbell dumbbell commented Oct 3, 2022

I was still not satisfied with the previous revisit in #79. I found the return values to be too complicated for the most common use cases.

The khepri and khepri_tx modules expose the same simple API:

  • khepri:get() returns {ok, Payload} directly. If the node has no payload, {ok, undefined} is returned. It's possible to use khepri:get_or() to get a default value instead of undefined.
  • khepri:get_many() and khepri:get_many_or() are introduced to get many nodes in a single call. The result is of the form {ok, #{Path => Payload}}.
  • Writes (khepri:put(), khepri:delete()...) always return ok in case of success.
  • There are also khepri:put_many() and khepri:delete_many() to provide the same distinctions as khepri:get() and khepri:get_many().

Example of the new simple API:

%% Store and get a value:
ok = khepri:put("/:stock/:wood/Oak", 120),
{ok, 120} = khepri:get("/:stock/:wood/Oak"),

%% Get the entire stock:
{ok, #{[stock, wood, <<"Oak">>] := 120,
       [stock, wood, <<"Maple">>] := 45}} = khepri:get_many("/:stock/:wood/*"),

%% Update the stock after a fire in the warehouse...
ok = khepri:put_many("/:stock/:wood/*", 0),

%% Or:
ok = khepri:delete("/:stock/:wood").

The detailed return values are still available from the khepri_adv and khepri_tx_adv modules. They expose the same functions as their simple API counterparts, but return complete values like before this commit. Also, the khepri*_adv:put()-related functions now return the properties of the tree node after the update, but the payload as it was before the update. This allows to know immediately the payload version of an updated tree node.

Example of the new advanced API:

%% Transactional update without using `khepri:transaction()':
{ok, #{data := Stock,
       payload_version := PayloadVersion}} = khepri_adv:get("/:stock/:wood/Oak"),

Path = [stock,
        wood,
        #if_all{conditions = [<<"Oak">>,
                              #if_payload_version{version = PayloadVersion}]}],
{ok, #{data := OldStock,
       payload_version := NewPayloadVersion}} = khepri_adv:put(Path, Stock + 30).

Erros have been sanitized a bit:

  • Errors (i.e. {error, ...} tuples) are returned for "normal" error conditions, like a missing tree node. The only exception to that where the error is thrown using erlang:throw/1 is when the function returns an arbitrary value (like with khepri:run_sproc()) and doesn't have room for Khepri-level errors.
  • Errors from Khepri always have the form {khepri, Name, Props} where Name is an atom qualifying the error and Props is a map to add more details to the error. That way, it's easier to understand where the error comes from when Khepri is used indirectly through a pile of other applications for instance.
  • Exceptions (using erlang:error/1) are thrown when there is a misuse of the library.
  • Exceptions from Khepri always have the form {khepri_ex, Name, Props}. Name and Props have the same meaning as for errors.

Example of an error:

{error,
 {khepri, node_not_found,
  #{node_name := non_existent,
    node_path := [non_existent],
    node_is_target := true}}} = khepri:get("/:non_existent").

Example of an exception:

try
    khepri:get("*")
catch
    error:{khepri_ex, possibly_matching_many_nodes_denied,
           #{path => [#if_name_matches{}]}} ->
        ...
end

The public header, include/khepri.hrl has been fixed to avoid namespace pollution and conflicts with other libraries by using the KHEPRI_ prefix in all exposed macros.

Some of the renamed macros:

true = ?IS_KHEPRI_NODE_ID(stock),

true = ?IS_KHEPRI_PATH([stock, wood, <<"Oak">>]),

%% Semantically the same:
Path = "../:orders/C451",
Path = [?PARENT_KHEPRI_NODE, orders, <<"C451">>].

This patch is nearly impossible to review, given the heavy code churn. I'm mostly looking for feedback on the public API, even if we discussed it several times internally.

@dumbbell dumbbell added the enhancement New feature or request label Oct 3, 2022
@dumbbell dumbbell self-assigned this Oct 3, 2022
@codecov
Copy link

codecov bot commented Oct 3, 2022

Codecov Report

Base: 91.55% // Head: 90.96% // Decreases project coverage by -0.58% ⚠️

Coverage data is based on head (220e3d1) compared to base (3cd6c8b).
Patch coverage: 86.89% of modified lines in pull request are covered.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #145      +/-   ##
==========================================
- Coverage   91.55%   90.96%   -0.59%     
==========================================
  Files          14       16       +2     
  Lines        2617     2868     +251     
==========================================
+ Hits         2396     2609     +213     
- Misses        221      259      +38     
Flag Coverage Δ
erlang-24 89.71% <86.49%> (-0.43%) ⬇️
erlang-25.0 89.50% <85.16%> (-0.45%) ⬇️
os-ubuntu-latest 90.89% <86.89%> (-0.51%) ⬇️
os-windows-latest 89.50% <85.16%> (-0.41%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Impacted Files Coverage Δ
src/khepri.erl 99.50% <ø> (+3.76%) ⬆️
src/khepri_condition.erl 90.35% <ø> (ø)
src/khepri_event_handler.erl 89.36% <ø> (-2.13%) ⬇️
src/khepri_evf.erl 100.00% <ø> (+9.09%) ⬆️
src/khepri_payload.erl 90.90% <ø> (ø)
src/khepri_sproc.erl 80.00% <0.00%> (ø)
src/khepri_utils.erl 98.96% <ø> (ø)
src/khepri_cluster.erl 80.19% <75.00%> (-0.14%) ⬇️
src/khepri_tx_adv.erl 80.19% <80.19%> (ø)
src/khepri_path.erl 96.99% <93.33%> (-0.16%) ⬇️
... and 9 more

Help us with your feedback. Take ten seconds to tell us how you rate us. Have a feature suggestion? Share it here.

☔ View full report at Codecov.
📢 Do you have feedback about the report comment? Let us know in this issue.

@dumbbell dumbbell marked this pull request as ready for review October 3, 2022 14:09
Copy link
Member

@the-mikedavis the-mikedavis left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly small typos/nits and a few questions.

I'm liking the new API 😀

The usage in cluster_SUITE seems really intuive to me.

src/khepri.erl Outdated Show resolved Hide resolved
src/khepri.erl Outdated Show resolved Hide resolved
src/khepri.erl Outdated Show resolved Hide resolved
src/khepri.erl Outdated Show resolved Hide resolved
src/khepri.erl Show resolved Hide resolved
src/khepri_machine.erl Outdated Show resolved Hide resolved
src/khepri_cluster.erl Show resolved Hide resolved
src/khepri_tx.erl Outdated Show resolved Hide resolved
src/khepri_tx.erl Outdated Show resolved Hide resolved
src/khepri_tx_adv.erl Outdated Show resolved Hide resolved
@dumbbell
Copy link
Member Author

dumbbell commented Oct 4, 2022

I see I forgot to update the khepri_cluster errors to use the same format as the rest of the library. Will do that today.

@dumbbell dumbbell force-pushed the api-overhaul branch 3 times, most recently from 4f3f182 to 09ed2db Compare October 5, 2022 09:56
src/khepri_tx.erl Outdated Show resolved Hide resolved
I was still not satisfied with the previous revisit in
commit 3fc0da9. I found the return
values to be too complicated for the most common use cases.

In this commit, the `khepri` and `khepri_tx` modules expose the same
simple API:

* `khepri:get()` returns `{ok, Payload}` directly. If the node has no
  payload, `{ok, undefined}` is returned. It's possible to use
  `khepri:get_or()` to get a default value instead of `undefined`.

* `khepri:get_many()` and `khepri:get_many_or()` are introduced to get
  many nodes in a single call. The result is of the form `{ok, #{Path =>
  Payload}}`.

* Writes (`khepri:put()`, `khepri:delete()`...) always return `ok` in
  case of success.

* There are also `khepri:put_many()` and `khepri:delete_many()` to
  provide the same distinctions as `khepri:get()` and
  `khepri:get_many()`.

The detailed return values are still available from the `khepri_adv` and
`khepri_tx_adv` modules. They expose the same functions as their simple
API counterparts, but return complete values like before this commit.

There are few small changes I want to make that will come in follow-up
commits.
Before this change, functions such as `khepri_adv:put()` would return
the properties and payload of a node as they were before the update.

With this patch, the payload is still the old one, however other
properties such as the payload version correspond to the node after the
update.

This allows to get the payload version of a freshly modified tree node
without having to query it.
This simplifies the API and the code. `keep_while` is extracted by
`khepri_machine` when needed, like it does for command and tree options.
With this commit, all errors and exceptions reported by Khepri should
all have the same form:

    {khepri | khepri_ex, Name, Props}

Errors are returned by the Khepri API to notify the failure of an
operation that is to be expected in a correct use of the library. Things
like a missing tree node or a non-matching path pattern. They are
expected to be handled by the caller. Here is an example of an error:

    {error, {khepri, node_not_found, #{...}}} = khepri:get(...)

Exceptions are raised by Khepri using `erlang:error()` to notify an
abnormal use of the library. Things like incorrect arguments or the
failure to prepare a transaction function. They are not expected to be
handled by the caller, they mostly target the developer. Here is an
example of an exception:

    try
        khepri:get([?STAR])
    catch
        error:{khepri_ex, possibly_matching_many_nodes_denied, #{...}} ->
            ...
    end

Some functions will return errors using `erlang:throw()` because their
return value doesn't leave room to return Khepri errors. This is the
case for instance with `khepri:run_sproc(...)` which returns directly
the value of the executed stored procedure otherwise.
Otherwise, they are a bit too generic and could cause conflicts with
other libraries out there.
This avoids namespace pollution. We export the type at the same time.
"Properties" is the name we use everywhere. Let's make that consistent
the record's field name consistent with the rest.
This breaks the clustering API, but anyway, the branch currently breaks
everything.
... instead of `lists:reverse/1` plus `++`. This should be slightly more
efficient.
The following bang functions were missing:
* `get_or!`
* `get_many!`
* `get_many_or!`
* `exists!`
* `has_data!`
* `is_sproc!`
* `count!`
* `put_many!`
* `delete_many!`
* `delete_payload!`
* `delete_many_payloads!`
`re_mp()` was clear what it was only for me apparently :) While renaming
the type to something more human-friendly nad making it more precise, I
discovered that the specs were buggy (because of the lack of precision
before).

In the end, instead of having a type for the compiled regex, the type
now represents the return value of `re:compile/1`.
@dumbbell dumbbell merged commit cab47f4 into main Oct 5, 2022
@dumbbell dumbbell deleted the api-overhaul branch October 5, 2022 14:46
dumbbell added a commit to rabbitmq/khepri-benchmark that referenced this pull request Oct 5, 2022
@dumbbell dumbbell added this to the v0.5.0 milestone Oct 6, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants