Skip to content

Instantly share code, notes, and snippets.

@ostinelli
Last active December 17, 2021 12:12
Show Gist options
  • Save ostinelli/76a048a863e23c0a1232701802a52fad to your computer and use it in GitHub Desktop.
Save ostinelli/76a048a863e23c0a1232701802a52fad to your computer and use it in GitHub Desktop.
Dotted Version Vector Sets example on conflict detection
-module(dvvset_test).
-export([main/0]).
%% NOTE: we always generate a new client ID to enforce consistency.
main() ->
%% client 1 write
Dot0 = dvvset:update(dvvset:new("value-0"), generate_id()),
%% server
Dot0_Server = dvvset:sync([Dot0]),
1 = length(dvvset:values(Dot0_Server)),
%% => Dot0_Server saved on server
%% client 1 update
Context1 = dvvset:join(Dot0_Server),
Dot1 = dvvset:update(dvvset:new(Context1, "value-1"), Dot0_Server, generate_id()),
%% server
Dot1_Server = dvvset:sync([Dot0_Server, Dot1]),
1 = length(dvvset:values(Dot1_Server)),
%% => Dot1_Server saved on server
%% client 1b update
Context1b = dvvset:join(Dot0_Server),
Dot1b = dvvset:update(dvvset:new(Context1b, "value-1b"), Dot0_Server, generate_id()),
%% server CONFLICT!
Dot1b_Server = dvvset:sync([Dot1_Server, Dot1b]),
2 = length(dvvset:values(Dot1b_Server)),
%% => Dot1_Server KEPT on server
[Value] = dvvset:values(Dot1_Server),
Value.
generate_id() ->
binary:encode_hex(crypto:hash(sha256, erlang:term_to_binary({node(), erlang:system_time()}))).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment