src/gm.erl
author Simon MacMullen <simon@rabbitmq.com>
Thu Apr 24 13:23:27 2014 +0100 (79 minutes ago)
changeset 13370 a36911baa593
parent 13361 100ac26a17e0
permissions -rw-r--r--
stable to default
     1 %% The contents of this file are subject to the Mozilla Public License
     2 %% Version 1.1 (the "License"); you may not use this file except in
     3 %% compliance with the License. You may obtain a copy of the License at
     4 %% http://www.mozilla.org/MPL/
     5 %%
     6 %% Software distributed under the License is distributed on an "AS IS"
     7 %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
     8 %% License for the specific language governing rights and limitations
     9 %% under the License.
    10 %%
    11 %% The Original Code is RabbitMQ.
    12 %%
    13 %% The Initial Developer of the Original Code is GoPivotal, Inc.
    14 %% Copyright (c) 2007-2014 GoPivotal, Inc.  All rights reserved.
    15 %%
    16 
    17 -module(gm).
    18 
    19 %% Guaranteed Multicast
    20 %% ====================
    21 %%
    22 %% This module provides the ability to create named groups of
    23 %% processes to which members can be dynamically added and removed,
    24 %% and for messages to be broadcast within the group that are
    25 %% guaranteed to reach all members of the group during the lifetime of
    26 %% the message. The lifetime of a message is defined as being, at a
    27 %% minimum, the time from which the message is first sent to any
    28 %% member of the group, up until the time at which it is known by the
    29 %% member who published the message that the message has reached all
    30 %% group members.
    31 %%
    32 %% The guarantee given is that provided a message, once sent, makes it
    33 %% to members who do not all leave the group, the message will
    34 %% continue to propagate to all group members.
    35 %%
    36 %% Another way of stating the guarantee is that if member P publishes
    37 %% messages m and m', then for all members P', if P' is a member of
    38 %% the group prior to the publication of m, and P' receives m', then
    39 %% P' will receive m.
    40 %%
    41 %% Note that only local-ordering is enforced: i.e. if member P sends
    42 %% message m and then message m', then for-all members P', if P'
    43 %% receives m and m', then they will receive m' after m. Causality
    44 %% ordering is _not_ enforced. I.e. if member P receives message m
    45 %% and as a result publishes message m', there is no guarantee that
    46 %% other members P' will receive m before m'.
    47 %%
    48 %%
    49 %% API Use
    50 %% -------
    51 %%
    52 %% Mnesia must be started. Use the idempotent create_tables/0 function
    53 %% to create the tables required.
    54 %%
    55 %% start_link/3
    56 %% Provide the group name, the callback module name, and any arguments
    57 %% you wish to be passed into the callback module's functions. The
    58 %% joined/2 function will be called when we have joined the group,
    59 %% with the arguments passed to start_link and a list of the current
    60 %% members of the group. See the callbacks specs and the comments
    61 %% below for further details of the callback functions.
    62 %%
    63 %% leave/1
    64 %% Provide the Pid. Removes the Pid from the group. The callback
    65 %% terminate/2 function will be called.
    66 %%
    67 %% broadcast/2
    68 %% Provide the Pid and a Message. The message will be sent to all
    69 %% members of the group as per the guarantees given above. This is a
    70 %% cast and the function call will return immediately. There is no
    71 %% guarantee that the message will reach any member of the group.
    72 %%
    73 %% confirmed_broadcast/2
    74 %% Provide the Pid and a Message. As per broadcast/2 except that this
    75 %% is a call, not a cast, and only returns 'ok' once the Message has
    76 %% reached every member of the group. Do not call
    77 %% confirmed_broadcast/2 directly from the callback module otherwise
    78 %% you will deadlock the entire group.
    79 %%
    80 %% info/1
    81 %% Provide the Pid. Returns a proplist with various facts, including
    82 %% the group name and the current group members.
    83 %%
    84 %% validate_members/2
    85 %% Check whether a given member list agrees with the chosen member's
    86 %% view. Any differences will be communicated via the members_changed
    87 %% callback. If there are no differences then there will be no reply.
    88 %% Note that members will not necessarily share the same view.
    89 %%
    90 %% forget_group/1
    91 %% Provide the group name. Removes its mnesia record. Makes no attempt
    92 %% to ensure the group is empty.
    93 %%
    94 %% Implementation Overview
    95 %% -----------------------
    96 %%
    97 %% One possible means of implementation would be a fan-out from the
    98 %% sender to every member of the group. This would require that the
    99 %% group is fully connected, and, in the event that the original
   100 %% sender of the message disappears from the group before the message
   101 %% has made it to every member of the group, raises questions as to
   102 %% who is responsible for sending on the message to new group members.
   103 %% In particular, the issue is with [ Pid ! Msg || Pid <- Members ] -
   104 %% if the sender dies part way through, who is responsible for
   105 %% ensuring that the remaining Members receive the Msg? In the event
   106 %% that within the group, messages sent are broadcast from a subset of
   107 %% the members, the fan-out arrangement has the potential to
   108 %% substantially impact the CPU and network workload of such members,
   109 %% as such members would have to accommodate the cost of sending each
   110 %% message to every group member.
   111 %%
   112 %% Instead, if the members of the group are arranged in a chain, then
   113 %% it becomes easier to reason about who within the group has received
   114 %% each message and who has not. It eases issues of responsibility: in
   115 %% the event of a group member disappearing, the nearest upstream
   116 %% member of the chain is responsible for ensuring that messages
   117 %% continue to propagate down the chain. It also results in equal
   118 %% distribution of sending and receiving workload, even if all
   119 %% messages are being sent from just a single group member. This
   120 %% configuration has the further advantage that it is not necessary
   121 %% for every group member to know of every other group member, and
   122 %% even that a group member does not have to be accessible from all
   123 %% other group members.
   124 %%
   125 %% Performance is kept high by permitting pipelining and all
   126 %% communication between joined group members is asynchronous. In the
   127 %% chain A -> B -> C -> D, if A sends a message to the group, it will
   128 %% not directly contact C or D. However, it must know that D receives
   129 %% the message (in addition to B and C) before it can consider the
   130 %% message fully sent. A simplistic implementation would require that
   131 %% D replies to C, C replies to B and B then replies to A. This would
   132 %% result in a propagation delay of twice the length of the chain. It
   133 %% would also require, in the event of the failure of C, that D knows
   134 %% to directly contact B and issue the necessary replies. Instead, the
   135 %% chain forms a ring: D sends the message on to A: D does not
   136 %% distinguish A as the sender, merely as the next member (downstream)
   137 %% within the chain (which has now become a ring). When A receives
   138 %% from D messages that A sent, it knows that all members have
   139 %% received the message. However, the message is not dead yet: if C
   140 %% died as B was sending to C, then B would need to detect the death
   141 %% of C and forward the message on to D instead: thus every node has
   142 %% to remember every message published until it is told that it can
   143 %% forget about the message. This is essential not just for dealing
   144 %% with failure of members, but also for the addition of new members.
   145 %%
   146 %% Thus once A receives the message back again, it then sends to B an
   147 %% acknowledgement for the message, indicating that B can now forget
   148 %% about the message. B does so, and forwards the ack to C. C forgets
   149 %% the message, and forwards the ack to D, which forgets the message
   150 %% and finally forwards the ack back to A. At this point, A takes no
   151 %% further action: the message and its acknowledgement have made it to
   152 %% every member of the group. The message is now dead, and any new
   153 %% member joining the group at this point will not receive the
   154 %% message.
   155 %%
   156 %% We therefore have two roles:
   157 %%
   158 %% 1. The sender, who upon receiving their own messages back, must
   159 %% then send out acknowledgements, and upon receiving their own
   160 %% acknowledgements back perform no further action.
   161 %%
   162 %% 2. The other group members who upon receiving messages and
   163 %% acknowledgements must update their own internal state accordingly
   164 %% (the sending member must also do this in order to be able to
   165 %% accommodate failures), and forwards messages on to their downstream
   166 %% neighbours.
   167 %%
   168 %%
   169 %% Implementation: It gets trickier
   170 %% --------------------------------
   171 %%
   172 %% Chain A -> B -> C -> D
   173 %%
   174 %% A publishes a message which B receives. A now dies. B and D will
   175 %% detect the death of A, and will link up, thus the chain is now B ->
   176 %% C -> D. B forwards A's message on to C, who forwards it to D, who
   177 %% forwards it to B. Thus B is now responsible for A's messages - both
   178 %% publications and acknowledgements that were in flight at the point
   179 %% at which A died. Even worse is that this is transitive: after B
   180 %% forwards A's message to C, B dies as well. Now C is not only
   181 %% responsible for B's in-flight messages, but is also responsible for
   182 %% A's in-flight messages.
   183 %%
   184 %% Lemma 1: A member can only determine which dead members they have
   185 %% inherited responsibility for if there is a total ordering on the
   186 %% conflicting additions and subtractions of members from the group.
   187 %%
   188 %% Consider the simultaneous death of B and addition of B' that
   189 %% transitions a chain from A -> B -> C to A -> B' -> C. Either B' or
   190 %% C is responsible for in-flight messages from B. It is easy to
   191 %% ensure that at least one of them thinks they have inherited B, but
   192 %% if we do not ensure that exactly one of them inherits B, then we
   193 %% could have B' converting publishes to acks, which then will crash C
   194 %% as C does not believe it has issued acks for those messages.
   195 %%
   196 %% More complex scenarios are easy to concoct: A -> B -> C -> D -> E
   197 %% becoming A -> C' -> E. Who has inherited which of B, C and D?
   198 %%
   199 %% However, for non-conflicting membership changes, only a partial
   200 %% ordering is required. For example, A -> B -> C becoming A -> A' ->
   201 %% B. The addition of A', between A and B can have no conflicts with
   202 %% the death of C: it is clear that A has inherited C's messages.
   203 %%
   204 %% For ease of implementation, we adopt the simple solution, of
   205 %% imposing a total order on all membership changes.
   206 %%
   207 %% On the death of a member, it is ensured the dead member's
   208 %% neighbours become aware of the death, and the upstream neighbour
   209 %% now sends to its new downstream neighbour its state, including the
   210 %% messages pending acknowledgement. The downstream neighbour can then
   211 %% use this to calculate which publishes and acknowledgements it has
   212 %% missed out on, due to the death of its old upstream. Thus the
   213 %% downstream can catch up, and continues the propagation of messages
   214 %% through the group.
   215 %%
   216 %% Lemma 2: When a member is joining, it must synchronously
   217 %% communicate with its upstream member in order to receive its
   218 %% starting state atomically with its addition to the group.
   219 %%
   220 %% New members must start with the same state as their nearest
   221 %% upstream neighbour. This ensures that it is not surprised by
   222 %% acknowledgements they are sent, and that should their downstream
   223 %% neighbour die, they are able to send the correct state to their new
   224 %% downstream neighbour to ensure it can catch up. Thus in the
   225 %% transition A -> B -> C becomes A -> A' -> B -> C becomes A -> A' ->
   226 %% C, A' must start with the state of A, so that it can send C the
   227 %% correct state when B dies, allowing C to detect any missed
   228 %% messages.
   229 %%
   230 %% If A' starts by adding itself to the group membership, A could then
   231 %% die, without A' having received the necessary state from A. This
   232 %% would leave A' responsible for in-flight messages from A, but
   233 %% having the least knowledge of all, of those messages. Thus A' must
   234 %% start by synchronously calling A, which then immediately sends A'
   235 %% back its state. A then adds A' to the group. If A dies at this
   236 %% point then A' will be able to see this (as A' will fail to appear
   237 %% in the group membership), and thus A' will ignore the state it
   238 %% receives from A, and will simply repeat the process, trying to now
   239 %% join downstream from some other member. This ensures that should
   240 %% the upstream die as soon as the new member has been joined, the new
   241 %% member is guaranteed to receive the correct state, allowing it to
   242 %% correctly process messages inherited due to the death of its
   243 %% upstream neighbour.
   244 %%
   245 %% The canonical definition of the group membership is held by a
   246 %% distributed database. Whilst this allows the total ordering of
   247 %% changes to be achieved, it is nevertheless undesirable to have to
   248 %% query this database for the current view, upon receiving each
   249 %% message. Instead, we wish for members to be able to cache a view of
   250 %% the group membership, which then requires a cache invalidation
   251 %% mechanism. Each member maintains its own view of the group
   252 %% membership. Thus when the group's membership changes, members may
   253 %% need to become aware of such changes in order to be able to
   254 %% accurately process messages they receive. Because of the
   255 %% requirement of a total ordering of conflicting membership changes,
   256 %% it is not possible to use the guaranteed broadcast mechanism to
   257 %% communicate these changes: to achieve the necessary ordering, it
   258 %% would be necessary for such messages to be published by exactly one
   259 %% member, which can not be guaranteed given that such a member could
   260 %% die.
   261 %%
   262 %% The total ordering we enforce on membership changes gives rise to a
   263 %% view version number: every change to the membership creates a
   264 %% different view, and the total ordering permits a simple
   265 %% monotonically increasing view version number.
   266 %%
   267 %% Lemma 3: If a message is sent from a member that holds view version
   268 %% N, it can be correctly processed by any member receiving the
   269 %% message with a view version >= N.
   270 %%
   271 %% Initially, let us suppose that each view contains the ordering of
   272 %% every member that was ever part of the group. Dead members are
   273 %% marked as such. Thus we have a ring of members, some of which are
   274 %% dead, and are thus inherited by the nearest alive downstream
   275 %% member.
   276 %%
   277 %% In the chain A -> B -> C, all three members initially have view
   278 %% version 1, which reflects reality. B publishes a message, which is
   279 %% forward by C to A. B now dies, which A notices very quickly. Thus A
   280 %% updates the view, creating version 2. It now forwards B's
   281 %% publication, sending that message to its new downstream neighbour,
   282 %% C. This happens before C is aware of the death of B. C must become
   283 %% aware of the view change before it interprets the message its
   284 %% received, otherwise it will fail to learn of the death of B, and
   285 %% thus will not realise it has inherited B's messages (and will
   286 %% likely crash).
   287 %%
   288 %% Thus very simply, we have that each subsequent view contains more
   289 %% information than the preceding view.
   290 %%
   291 %% However, to avoid the views growing indefinitely, we need to be
   292 %% able to delete members which have died _and_ for which no messages
   293 %% are in-flight. This requires that upon inheriting a dead member, we
   294 %% know the last publication sent by the dead member (this is easy: we
   295 %% inherit a member because we are the nearest downstream member which
   296 %% implies that we know at least as much than everyone else about the
   297 %% publications of the dead member), and we know the earliest message
   298 %% for which the acknowledgement is still in flight.
   299 %%
   300 %% In the chain A -> B -> C, when B dies, A will send to C its state
   301 %% (as C is the new downstream from A), allowing C to calculate which
   302 %% messages it has missed out on (described above). At this point, C
   303 %% also inherits B's messages. If that state from A also includes the
   304 %% last message published by B for which an acknowledgement has been
   305 %% seen, then C knows exactly which further acknowledgements it must
   306 %% receive (also including issuing acknowledgements for publications
   307 %% still in-flight that it receives), after which it is known there
   308 %% are no more messages in flight for B, thus all evidence that B was
   309 %% ever part of the group can be safely removed from the canonical
   310 %% group membership.
   311 %%
   312 %% Thus, for every message that a member sends, it includes with that
   313 %% message its view version. When a member receives a message it will
   314 %% update its view from the canonical copy, should its view be older
   315 %% than the view version included in the message it has received.
   316 %%
   317 %% The state held by each member therefore includes the messages from
   318 %% each publisher pending acknowledgement, the last publication seen
   319 %% from that publisher, and the last acknowledgement from that
   320 %% publisher. In the case of the member's own publications or
   321 %% inherited members, this last acknowledgement seen state indicates
   322 %% the last acknowledgement retired, rather than sent.
   323 %%
   324 %%
   325 %% Proof sketch
   326 %% ------------
   327 %%
   328 %% We need to prove that with the provided operational semantics, we
   329 %% can never reach a state that is not well formed from a well-formed
   330 %% starting state.
   331 %%
   332 %% Operational semantics (small step): straight-forward message
   333 %% sending, process monitoring, state updates.
   334 %%
   335 %% Well formed state: dead members inherited by exactly one non-dead
   336 %% member; for every entry in anyone's pending-acks, either (the
   337 %% publication of the message is in-flight downstream from the member
   338 %% and upstream from the publisher) or (the acknowledgement of the
   339 %% message is in-flight downstream from the publisher and upstream
   340 %% from the member).
   341 %%
   342 %% Proof by induction on the applicable operational semantics.
   343 %%
   344 %%
   345 %% Related work
   346 %% ------------
   347 %%
   348 %% The ring configuration and double traversal of messages around the
   349 %% ring is similar (though developed independently) to the LCR
   350 %% protocol by [Levy 2008]. However, LCR differs in several
   351 %% ways. Firstly, by using vector clocks, it enforces a total order of
   352 %% message delivery, which is unnecessary for our purposes. More
   353 %% significantly, it is built on top of a "group communication system"
   354 %% which performs the group management functions, taking
   355 %% responsibility away from the protocol as to how to cope with safely
   356 %% adding and removing members. When membership changes do occur, the
   357 %% protocol stipulates that every member must perform communication
   358 %% with every other member of the group, to ensure all outstanding
   359 %% deliveries complete, before the entire group transitions to the new
   360 %% view. This, in total, requires two sets of all-to-all synchronous
   361 %% communications.
   362 %%
   363 %% This is not only rather inefficient, but also does not explain what
   364 %% happens upon the failure of a member during this process. It does
   365 %% though entirely avoid the need for inheritance of responsibility of
   366 %% dead members that our protocol incorporates.
   367 %%
   368 %% In [Marandi et al 2010], a Paxos-based protocol is described. This
   369 %% work explicitly focuses on the efficiency of communication. LCR
   370 %% (and our protocol too) are more efficient, but at the cost of
   371 %% higher latency. The Ring-Paxos protocol is itself built on top of
   372 %% IP-multicast, which rules it out for many applications where
   373 %% point-to-point communication is all that can be required. They also
   374 %% have an excellent related work section which I really ought to
   375 %% read...
   376 %%
   377 %%
   378 %% [Levy 2008] The Complexity of Reliable Distributed Storage, 2008.
   379 %% [Marandi et al 2010] Ring Paxos: A High-Throughput Atomic Broadcast
   380 %% Protocol
   381 
   382 
   383 -behaviour(gen_server2).
   384 
   385 -export([create_tables/0, start_link/4, leave/1, broadcast/2, broadcast/3,
   386          confirmed_broadcast/2, info/1, validate_members/2, forget_group/1]).
   387 
   388 -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2,
   389          code_change/3, prioritise_info/3]).
   390 
   391 -ifndef(use_specs).
   392 -export([behaviour_info/1]).
   393 -endif.
   394 
   395 -export([table_definitions/0]).
   396 
   397 -define(GROUP_TABLE, gm_group).
   398 -define(MAX_BUFFER_SIZE, 100000000). %% 100MB
   399 -define(HIBERNATE_AFTER_MIN, 1000).
   400 -define(DESIRED_HIBERNATE, 10000).
   401 -define(BROADCAST_TIMER, 25).
   402 -define(VERSION_START, 0).
   403 -define(SETS, ordsets).
   404 -define(DICT, orddict).
   405 
   406 -record(state,
   407         { self,
   408           left,
   409           right,
   410           group_name,
   411           module,
   412           view,
   413           pub_count,
   414           members_state,
   415           callback_args,
   416           confirms,
   417           broadcast_buffer,
   418           broadcast_buffer_sz,
   419           broadcast_timer,
   420           txn_executor
   421         }).
   422 
   423 -record(gm_group, { name, version, members }).
   424 
   425 -record(view_member, { id, aliases, left, right }).
   426 
   427 -record(member, { pending_ack, last_pub, last_ack }).
   428 
   429 -define(TABLE, {?GROUP_TABLE, [{record_name, gm_group},
   430                                {attributes, record_info(fields, gm_group)}]}).
   431 -define(TABLE_MATCH, {match, #gm_group { _ = '_' }}).
   432 
   433 -define(TAG, '$gm').
   434 
   435 -ifdef(use_specs).
   436 
   437 -export_type([group_name/0]).
   438 
   439 -type(group_name() :: any()).
   440 -type(txn_fun() :: fun((fun(() -> any())) -> any())).
   441 
   442 -spec(create_tables/0 :: () -> 'ok' | {'aborted', any()}).
   443 -spec(start_link/4 :: (group_name(), atom(), any(), txn_fun()) ->
   444                            rabbit_types:ok_pid_or_error()).
   445 -spec(leave/1 :: (pid()) -> 'ok').
   446 -spec(broadcast/2 :: (pid(), any()) -> 'ok').
   447 -spec(confirmed_broadcast/2 :: (pid(), any()) -> 'ok').
   448 -spec(info/1 :: (pid()) -> rabbit_types:infos()).
   449 -spec(validate_members/2 :: (pid(), [pid()]) -> 'ok').
   450 -spec(forget_group/1 :: (group_name()) -> 'ok').
   451 
   452 %% The joined, members_changed and handle_msg callbacks can all return
   453 %% any of the following terms:
   454 %%
   455 %% 'ok' - the callback function returns normally
   456 %%
   457 %% {'stop', Reason} - the callback indicates the member should stop
   458 %% with reason Reason and should leave the group.
   459 %%
   460 %% {'become', Module, Args} - the callback indicates that the callback
   461 %% module should be changed to Module and that the callback functions
   462 %% should now be passed the arguments Args. This allows the callback
   463 %% module to be dynamically changed.
   464 
   465 %% Called when we've successfully joined the group. Supplied with Args
   466 %% provided in start_link, plus current group members.
   467 -callback joined(Args :: term(), Members :: [pid()]) ->
   468     ok | {stop, Reason :: term()} | {become, Module :: atom(), Args :: any()}.
   469 
   470 %% Supplied with Args provided in start_link, the list of new members
   471 %% and the list of members previously known to us that have since
   472 %% died. Note that if a member joins and dies very quickly, it's
   473 %% possible that we will never see that member appear in either births
   474 %% or deaths. However we are guaranteed that (1) we will see a member
   475 %% joining either in the births here, or in the members passed to
   476 %% joined/2 before receiving any messages from it; and (2) we will not
   477 %% see members die that we have not seen born (or supplied in the
   478 %% members to joined/2).
   479 -callback members_changed(Args :: term(),
   480                           Births :: [pid()], Deaths :: [pid()]) ->
   481     ok | {stop, Reason :: term()} | {become, Module :: atom(), Args :: any()}.
   482 
   483 %% Supplied with Args provided in start_link, the sender, and the
   484 %% message. This does get called for messages injected by this member,
   485 %% however, in such cases, there is no special significance of this
   486 %% invocation: it does not indicate that the message has made it to
   487 %% any other members, let alone all other members.
   488 -callback handle_msg(Args :: term(), From :: pid(), Message :: term()) ->
   489     ok | {stop, Reason :: term()} | {become, Module :: atom(), Args :: any()}.
   490 
   491 %% Called on gm member termination as per rules in gen_server, with
   492 %% the Args provided in start_link plus the termination Reason.
   493 -callback terminate(Args :: term(), Reason :: term()) ->
   494     ok | term().
   495 
   496 -else.
   497 
   498 behaviour_info(callbacks) ->
   499     [{joined, 2}, {members_changed, 3}, {handle_msg, 3}, {terminate, 2}];
   500 behaviour_info(_Other) ->
   501     undefined.
   502 
   503 -endif.
   504 
   505 create_tables() ->
   506     create_tables([?TABLE]).
   507 
   508 create_tables([]) ->
   509     ok;
   510 create_tables([{Table, Attributes} | Tables]) ->
   511     case mnesia:create_table(Table, Attributes) of
   512         {atomic, ok}                       -> create_tables(Tables);
   513         {aborted, {already_exists, Table}} -> create_tables(Tables);
   514         Err                                -> Err
   515     end.
   516 
   517 table_definitions() ->
   518     {Name, Attributes} = ?TABLE,
   519     [{Name, [?TABLE_MATCH | Attributes]}].
   520 
   521 start_link(GroupName, Module, Args, TxnFun) ->
   522     gen_server2:start_link(?MODULE, [GroupName, Module, Args, TxnFun], []).
   523 
   524 leave(Server) ->
   525     gen_server2:cast(Server, leave).
   526 
   527 broadcast(Server, Msg) -> broadcast(Server, Msg, 0).
   528 
   529 broadcast(Server, Msg, SizeHint) ->
   530     gen_server2:cast(Server, {broadcast, Msg, SizeHint}).
   531 
   532 confirmed_broadcast(Server, Msg) ->
   533     gen_server2:call(Server, {confirmed_broadcast, Msg}, infinity).
   534 
   535 info(Server) ->
   536     gen_server2:call(Server, info, infinity).
   537 
   538 validate_members(Server, Members) ->
   539     gen_server2:cast(Server, {validate_members, Members}).
   540 
   541 forget_group(GroupName) ->
   542     {atomic, ok} = mnesia:sync_transaction(
   543                      fun () ->
   544                              mnesia:delete({?GROUP_TABLE, GroupName})
   545                      end),
   546     ok.
   547 
   548 init([GroupName, Module, Args, TxnFun]) ->
   549     put(process_name, {?MODULE, GroupName}),
   550     {MegaSecs, Secs, MicroSecs} = now(),
   551     random:seed(MegaSecs, Secs, MicroSecs),
   552     Self = make_member(GroupName),
   553     gen_server2:cast(self(), join),
   554     {ok, #state { self                = Self,
   555                   left                = {Self, undefined},
   556                   right               = {Self, undefined},
   557                   group_name          = GroupName,
   558                   module              = Module,
   559                   view                = undefined,
   560                   pub_count           = -1,
   561                   members_state       = undefined,
   562                   callback_args       = Args,
   563                   confirms            = queue:new(),
   564                   broadcast_buffer    = [],
   565                   broadcast_buffer_sz = 0,
   566                   broadcast_timer     = undefined,
   567                   txn_executor        = TxnFun }, hibernate,
   568      {backoff, ?HIBERNATE_AFTER_MIN, ?HIBERNATE_AFTER_MIN, ?DESIRED_HIBERNATE}}.
   569 
   570 
   571 handle_call({confirmed_broadcast, _Msg}, _From,
   572             State = #state { members_state = undefined }) ->
   573     reply(not_joined, State);
   574 
   575 handle_call({confirmed_broadcast, Msg}, _From,
   576             State = #state { self          = Self,
   577                              right         = {Self, undefined},
   578                              module        = Module,
   579                              callback_args = Args }) ->
   580     handle_callback_result({Module:handle_msg(Args, get_pid(Self), Msg),
   581                            ok, State});
   582 
   583 handle_call({confirmed_broadcast, Msg}, From, State) ->
   584     {Result, State1 = #state { pub_count = PubCount, confirms = Confirms }} =
   585         internal_broadcast(Msg, 0, State),
   586     Confirms1 = queue:in({PubCount, From}, Confirms),
   587     handle_callback_result({Result, flush_broadcast_buffer(
   588                                       State1 #state { confirms = Confirms1 })});
   589 
   590 handle_call(info, _From,
   591             State = #state { members_state = undefined }) ->
   592     reply(not_joined, State);
   593 
   594 handle_call(info, _From, State = #state { group_name = GroupName,
   595                                           module     = Module,
   596                                           view       = View }) ->
   597     reply([{group_name,    GroupName},
   598            {module,        Module},
   599            {group_members, get_pids(alive_view_members(View))}], State);
   600 
   601 handle_call({add_on_right, _NewMember}, _From,
   602             State = #state { members_state = undefined }) ->
   603     reply(not_ready, State);
   604 
   605 handle_call({add_on_right, NewMember}, _From,
   606             State = #state { self          = Self,
   607                              group_name    = GroupName,
   608                              members_state = MembersState,
   609                              txn_executor  = TxnFun }) ->
   610     Group = record_new_member_in_group(NewMember, Self, GroupName, TxnFun),
   611     View1 = group_to_view(Group),
   612     MembersState1 = remove_erased_members(MembersState, View1),
   613     ok = send_right(NewMember, View1,
   614                     {catchup, Self, prepare_members_state(MembersState1)}),
   615     {Result, State1} = change_view(View1, State #state {
   616                                             members_state = MembersState1 }),
   617     handle_callback_result({Result, {ok, Group}, State1}).
   618 
   619 handle_cast({?TAG, ReqVer, Msg},
   620             State = #state { view          = View,
   621                              members_state = MembersState,
   622                              group_name    = GroupName }) ->
   623     {Result, State1} =
   624         case needs_view_update(ReqVer, View) of
   625             true  -> View1 = group_to_view(dirty_read_group(GroupName)),
   626                      MemberState1 = remove_erased_members(MembersState, View1),
   627                      change_view(View1, State #state {
   628                                           members_state = MemberState1 });
   629             false -> {ok, State}
   630         end,
   631     handle_callback_result(
   632       if_callback_success(
   633         Result, fun handle_msg_true/3, fun handle_msg_false/3, Msg, State1));
   634 
   635 handle_cast({broadcast, _Msg, _SizeHint},
   636             State = #state { members_state = undefined }) ->
   637     noreply(State);
   638 
   639 handle_cast({broadcast, Msg, _SizeHint},
   640             State = #state { self          = Self,
   641                              right         = {Self, undefined},
   642                              module        = Module,
   643                              callback_args = Args }) ->
   644     handle_callback_result({Module:handle_msg(Args, get_pid(Self), Msg),
   645                             State});
   646 
   647 handle_cast({broadcast, Msg, SizeHint}, State) ->
   648     {Result, State1} = internal_broadcast(Msg, SizeHint, State),
   649     handle_callback_result({Result, maybe_flush_broadcast_buffer(State1)});
   650 
   651 handle_cast(join, State = #state { self          = Self,
   652                                    group_name    = GroupName,
   653                                    members_state = undefined,
   654                                    module        = Module,
   655                                    callback_args = Args,
   656                                    txn_executor  = TxnFun }) ->
   657     View = join_group(Self, GroupName, TxnFun),
   658     MembersState =
   659         case alive_view_members(View) of
   660             [Self] -> blank_member_state();
   661             _      -> undefined
   662         end,
   663     State1 = check_neighbours(State #state { view          = View,
   664                                              members_state = MembersState }),
   665     handle_callback_result(
   666       {Module:joined(Args, get_pids(all_known_members(View))), State1});
   667 
   668 handle_cast({validate_members, OldMembers},
   669             State = #state { view          = View,
   670                              module        = Module,
   671                              callback_args = Args }) ->
   672     NewMembers = get_pids(all_known_members(View)),
   673     Births = NewMembers -- OldMembers,
   674     Deaths = OldMembers -- NewMembers,
   675     case {Births, Deaths} of
   676         {[], []}  -> noreply(State);
   677         _         -> Result = Module:members_changed(Args, Births, Deaths),
   678                      handle_callback_result({Result, State})
   679     end;
   680 
   681 handle_cast(leave, State) ->
   682     {stop, normal, State}.
   683 
   684 
   685 handle_info(flush, State) ->
   686     noreply(
   687       flush_broadcast_buffer(State #state { broadcast_timer = undefined }));
   688 
   689 handle_info(timeout, State) ->
   690     noreply(flush_broadcast_buffer(State));
   691 
   692 handle_info({'DOWN', MRef, process, _Pid, Reason},
   693             State = #state { self          = Self,
   694                              left          = Left,
   695                              right         = Right,
   696                              group_name    = GroupName,
   697                              confirms      = Confirms,
   698                              txn_executor  = TxnFun }) ->
   699     Member = case {Left, Right} of
   700                  {{Member1, MRef}, _} -> Member1;
   701                  {_, {Member1, MRef}} -> Member1;
   702                  _                    -> undefined
   703              end,
   704     case {Member, Reason} of
   705         {undefined, _} ->
   706             noreply(State);
   707         {_, {shutdown, ring_shutdown}} ->
   708             noreply(State);
   709         _ ->
   710             View1 = group_to_view(record_dead_member_in_group(
   711                                     Member, GroupName, TxnFun)),
   712             handle_callback_result(
   713               case alive_view_members(View1) of
   714                   [Self] -> maybe_erase_aliases(
   715                               State #state {
   716                                 members_state = blank_member_state(),
   717                                 confirms      = purge_confirms(Confirms) },
   718                               View1);
   719                   _      -> change_view(View1, State)
   720               end)
   721     end.
   722 
   723 
   724 terminate(Reason, State = #state { module        = Module,
   725                                    callback_args = Args }) ->
   726     flush_broadcast_buffer(State),
   727     Module:terminate(Args, Reason).
   728 
   729 
   730 code_change(_OldVsn, State, _Extra) ->
   731     {ok, State}.
   732 
   733 prioritise_info(flush, _Len, _State) ->
   734     1;
   735 prioritise_info({'DOWN', _MRef, process, _Pid, _Reason}, _Len,
   736                 #state { members_state = MS }) when MS /= undefined ->
   737     1;
   738 prioritise_info(_, _Len, _State) ->
   739     0.
   740 
   741 
   742 handle_msg(check_neighbours, State) ->
   743     %% no-op - it's already been done by the calling handle_cast
   744     {ok, State};
   745 
   746 handle_msg({catchup, Left, MembersStateLeft},
   747            State = #state { self          = Self,
   748                             left          = {Left, _MRefL},
   749                             right         = {Right, _MRefR},
   750                             view          = View,
   751                             members_state = undefined }) ->
   752     ok = send_right(Right, View, {catchup, Self, MembersStateLeft}),
   753     MembersStateLeft1 = build_members_state(MembersStateLeft),
   754     {ok, State #state { members_state = MembersStateLeft1 }};
   755 
   756 handle_msg({catchup, Left, MembersStateLeft},
   757            State = #state { self = Self,
   758                             left = {Left, _MRefL},
   759                             view = View,
   760                             members_state = MembersState })
   761   when MembersState =/= undefined ->
   762     MembersStateLeft1 = build_members_state(MembersStateLeft),
   763     AllMembers = lists:usort(?DICT:fetch_keys(MembersState) ++
   764                                  ?DICT:fetch_keys(MembersStateLeft1)),
   765     {MembersState1, Activity} =
   766         lists:foldl(
   767           fun (Id, MembersStateActivity) ->
   768                   #member { pending_ack = PALeft, last_ack = LA } =
   769                       find_member_or_blank(Id, MembersStateLeft1),
   770                   with_member_acc(
   771                     fun (#member { pending_ack = PA } = Member, Activity1) ->
   772                             case is_member_alias(Id, Self, View) of
   773                                 true ->
   774                                     {_AcksInFlight, Pubs, _PA1} =
   775                                         find_prefix_common_suffix(PALeft, PA),
   776                                     {Member #member { last_ack = LA },
   777                                      activity_cons(Id, pubs_from_queue(Pubs),
   778                                                    [], Activity1)};
   779                                 false ->
   780                                     {Acks, _Common, Pubs} =
   781                                         find_prefix_common_suffix(PA, PALeft),
   782                                     {Member,
   783                                      activity_cons(Id, pubs_from_queue(Pubs),
   784                                                    acks_from_queue(Acks),
   785                                                    Activity1)}
   786                             end
   787                     end, Id, MembersStateActivity)
   788           end, {MembersState, activity_nil()}, AllMembers),
   789     handle_msg({activity, Left, activity_finalise(Activity)},
   790                State #state { members_state = MembersState1 });
   791 
   792 handle_msg({catchup, _NotLeft, _MembersState}, State) ->
   793     {ok, State};
   794 
   795 handle_msg({activity, Left, Activity},
   796            State = #state { self          = Self,
   797                             left          = {Left, _MRefL},
   798                             view          = View,
   799                             members_state = MembersState,
   800                             confirms      = Confirms })
   801   when MembersState =/= undefined ->
   802     {MembersState1, {Confirms1, Activity1}} =
   803         lists:foldl(
   804           fun ({Id, Pubs, Acks}, MembersStateConfirmsActivity) ->
   805                   with_member_acc(
   806                     fun (Member = #member { pending_ack = PA,
   807                                             last_pub    = LP,
   808                                             last_ack    = LA },
   809                          {Confirms2, Activity2}) ->
   810                             case is_member_alias(Id, Self, View) of
   811                                 true ->
   812                                     {ToAck, PA1} =
   813                                         find_common(queue_from_pubs(Pubs), PA,
   814                                                     queue:new()),
   815                                     LA1 = last_ack(Acks, LA),
   816                                     AckNums = acks_from_queue(ToAck),
   817                                     Confirms3 = maybe_confirm(
   818                                                   Self, Id, Confirms2, AckNums),
   819                                     {Member #member { pending_ack = PA1,
   820                                                       last_ack    = LA1 },
   821                                      {Confirms3,
   822                                       activity_cons(
   823                                         Id, [], AckNums, Activity2)}};
   824                                 false ->
   825                                     PA1 = apply_acks(Acks, join_pubs(PA, Pubs)),
   826                                     LA1 = last_ack(Acks, LA),
   827                                     LP1 = last_pub(Pubs, LP),
   828                                     {Member #member { pending_ack = PA1,
   829                                                       last_pub    = LP1,
   830                                                       last_ack    = LA1 },
   831                                      {Confirms2,
   832                                       activity_cons(Id, Pubs, Acks, Activity2)}}
   833                             end
   834                     end, Id, MembersStateConfirmsActivity)
   835           end, {MembersState, {Confirms, activity_nil()}}, Activity),
   836     State1 = State #state { members_state = MembersState1,
   837                             confirms      = Confirms1 },
   838     Activity3 = activity_finalise(Activity1),
   839     ok = maybe_send_activity(Activity3, State1),
   840     {Result, State2} = maybe_erase_aliases(State1, View),
   841     if_callback_success(
   842       Result, fun activity_true/3, fun activity_false/3, Activity3, State2);
   843 
   844 handle_msg({activity, _NotLeft, _Activity}, State) ->
   845     {ok, State}.
   846 
   847 
   848 noreply(State) ->
   849     {noreply, ensure_broadcast_timer(State), flush_timeout(State)}.
   850 
   851 reply(Reply, State) ->
   852     {reply, Reply, ensure_broadcast_timer(State), flush_timeout(State)}.
   853 
   854 flush_timeout(#state{broadcast_buffer = []}) -> hibernate;
   855 flush_timeout(_)                             -> 0.
   856 
   857 ensure_broadcast_timer(State = #state { broadcast_buffer = [],
   858                                         broadcast_timer  = undefined }) ->
   859     State;
   860 ensure_broadcast_timer(State = #state { broadcast_buffer = [],
   861                                         broadcast_timer  = TRef }) ->
   862     erlang:cancel_timer(TRef),
   863     State #state { broadcast_timer = undefined };
   864 ensure_broadcast_timer(State = #state { broadcast_timer = undefined }) ->
   865     TRef = erlang:send_after(?BROADCAST_TIMER, self(), flush),
   866     State #state { broadcast_timer = TRef };
   867 ensure_broadcast_timer(State) ->
   868     State.
   869 
   870 internal_broadcast(Msg, SizeHint,
   871                    State = #state { self                = Self,
   872                                     pub_count           = PubCount,
   873                                     module              = Module,
   874                                     callback_args       = Args,
   875                                     broadcast_buffer    = Buffer,
   876                                     broadcast_buffer_sz = BufferSize }) ->
   877     PubCount1 = PubCount + 1,
   878     {Module:handle_msg(Args, get_pid(Self), Msg),
   879      State #state { pub_count           = PubCount1,
   880                     broadcast_buffer    = [{PubCount1, Msg} | Buffer],
   881                     broadcast_buffer_sz = BufferSize + SizeHint}}.
   882 
   883 %% The Erlang distribution mechanism has an interesting quirk - it
   884 %% will kill the VM cold with "Absurdly large distribution output data
   885 %% buffer" if you attempt to send a message which serialises out to
   886 %% more than 2^31 bytes in size. It's therefore a very good idea to
   887 %% make sure that we don't exceed that size!
   888 %%
   889 %% Now, we could figure out the size of messages as they come in using
   890 %% size(term_to_binary(Msg)) or similar. The trouble is, that requires
   891 %% us to serialise the message only to throw the serialised form
   892 %% away. Hard to believe that's a sensible thing to do. So instead we
   893 %% accept a size hint from the application, via broadcast/3. This size
   894 %% hint can be the size of anything in the message which we expect
   895 %% could be large, and we just ignore the size of any small bits of
   896 %% the message term. Therefore MAX_BUFFER_SIZE is set somewhat
   897 %% conservatively at 100MB - but the buffer is only to allow us to
   898 %% buffer tiny messages anyway, so 100MB is plenty.
   899 
   900 maybe_flush_broadcast_buffer(State = #state{broadcast_buffer_sz = Size}) ->
   901     case Size > ?MAX_BUFFER_SIZE of
   902         true  -> flush_broadcast_buffer(State);
   903         false -> State
   904     end.
   905 
   906 flush_broadcast_buffer(State = #state { broadcast_buffer = [] }) ->
   907     State;
   908 flush_broadcast_buffer(State = #state { self             = Self,
   909                                         members_state    = MembersState,
   910                                         broadcast_buffer = Buffer,
   911                                         pub_count        = PubCount }) ->
   912     [{PubCount, _Msg}|_] = Buffer, %% ASSERTION match on PubCount
   913     Pubs = lists:reverse(Buffer),
   914     Activity = activity_cons(Self, Pubs, [], activity_nil()),
   915     ok = maybe_send_activity(activity_finalise(Activity), State),
   916     MembersState1 = with_member(
   917                       fun (Member = #member { pending_ack = PA }) ->
   918                               PA1 = queue:join(PA, queue:from_list(Pubs)),
   919                               Member #member { pending_ack = PA1,
   920                                                last_pub = PubCount }
   921                       end, Self, MembersState),
   922     State #state { members_state       = MembersState1,
   923                    broadcast_buffer    = [],
   924                    broadcast_buffer_sz = 0}.
   925 
   926 
   927 %% ---------------------------------------------------------------------------
   928 %% View construction and inspection
   929 %% ---------------------------------------------------------------------------
   930 
   931 needs_view_update(ReqVer, {Ver, _View}) -> Ver < ReqVer.
   932 
   933 view_version({Ver, _View}) -> Ver.
   934 
   935 is_member_alive({dead, _Member}) -> false;
   936 is_member_alive(_)               -> true.
   937 
   938 is_member_alias(Self, Self, _View) ->
   939     true;
   940 is_member_alias(Member, Self, View) ->
   941     ?SETS:is_element(Member,
   942                      ((fetch_view_member(Self, View)) #view_member.aliases)).
   943 
   944 dead_member_id({dead, Member}) -> Member.
   945 
   946 store_view_member(VMember = #view_member { id = Id }, {Ver, View}) ->
   947     {Ver, ?DICT:store(Id, VMember, View)}.
   948 
   949 with_view_member(Fun, View, Id) ->
   950     store_view_member(Fun(fetch_view_member(Id, View)), View).
   951 
   952 fetch_view_member(Id, {_Ver, View}) -> ?DICT:fetch(Id, View).
   953 
   954 find_view_member(Id, {_Ver, View}) -> ?DICT:find(Id, View).
   955 
   956 blank_view(Ver) -> {Ver, ?DICT:new()}.
   957 
   958 alive_view_members({_Ver, View}) -> ?DICT:fetch_keys(View).
   959 
   960 all_known_members({_Ver, View}) ->
   961     ?DICT:fold(
   962        fun (Member, #view_member { aliases = Aliases }, Acc) ->
   963                ?SETS:to_list(Aliases) ++ [Member | Acc]
   964        end, [], View).
   965 
   966 group_to_view(#gm_group { members = Members, version = Ver }) ->
   967     Alive = lists:filter(fun is_member_alive/1, Members),
   968     [_|_] = Alive, %% ASSERTION - can't have all dead members
   969     add_aliases(link_view(Alive ++ Alive ++ Alive, blank_view(Ver)), Members).
   970 
   971 link_view([Left, Middle, Right | Rest], View) ->
   972     case find_view_member(Middle, View) of
   973         error ->
   974             link_view(
   975               [Middle, Right | Rest],
   976               store_view_member(#view_member { id      = Middle,
   977                                                aliases = ?SETS:new(),
   978                                                left    = Left,
   979                                                right   = Right }, View));
   980         {ok, _} ->
   981             View
   982     end;
   983 link_view(_, View) ->
   984     View.
   985 
   986 add_aliases(View, Members) ->
   987     Members1 = ensure_alive_suffix(Members),
   988     {EmptyDeadSet, View1} =
   989         lists:foldl(
   990           fun (Member, {DeadAcc, ViewAcc}) ->
   991                   case is_member_alive(Member) of
   992                       true ->
   993                           {?SETS:new(),
   994                            with_view_member(
   995                              fun (VMember =
   996                                       #view_member { aliases = Aliases }) ->
   997                                      VMember #view_member {
   998                                        aliases = ?SETS:union(Aliases, DeadAcc) }
   999                              end, ViewAcc, Member)};
  1000                       false ->
  1001                           {?SETS:add_element(dead_member_id(Member), DeadAcc),
  1002                            ViewAcc}
  1003                   end
  1004           end, {?SETS:new(), View}, Members1),
  1005     0 = ?SETS:size(EmptyDeadSet), %% ASSERTION
  1006     View1.
  1007 
  1008 ensure_alive_suffix(Members) ->
  1009     queue:to_list(ensure_alive_suffix1(queue:from_list(Members))).
  1010 
  1011 ensure_alive_suffix1(MembersQ) ->
  1012     {{value, Member}, MembersQ1} = queue:out_r(MembersQ),
  1013     case is_member_alive(Member) of
  1014         true  -> MembersQ;
  1015         false -> ensure_alive_suffix1(queue:in_r(Member, MembersQ1))
  1016     end.
  1017 
  1018 
  1019 %% ---------------------------------------------------------------------------
  1020 %% View modification
  1021 %% ---------------------------------------------------------------------------
  1022 
  1023 join_group(Self, GroupName, TxnFun) ->
  1024     join_group(Self, GroupName, dirty_read_group(GroupName), TxnFun).
  1025 
  1026 join_group(Self, GroupName, {error, not_found}, TxnFun) ->
  1027     join_group(Self, GroupName,
  1028                prune_or_create_group(Self, GroupName, TxnFun), TxnFun);
  1029 join_group(Self, _GroupName, #gm_group { members = [Self] } = Group, _TxnFun) ->
  1030     group_to_view(Group);
  1031 join_group(Self, GroupName, #gm_group { members = Members } = Group, TxnFun) ->
  1032     case lists:member(Self, Members) of
  1033         true ->
  1034             group_to_view(Group);
  1035         false ->
  1036             case lists:filter(fun is_member_alive/1, Members) of
  1037                 [] ->
  1038                     join_group(Self, GroupName,
  1039                                prune_or_create_group(Self, GroupName, TxnFun));
  1040                 Alive ->
  1041                     Left = lists:nth(random:uniform(length(Alive)), Alive),
  1042                     Handler =
  1043                         fun () ->
  1044                                 join_group(
  1045                                   Self, GroupName,
  1046                                   record_dead_member_in_group(
  1047                                     Left, GroupName, TxnFun),
  1048                                   TxnFun)
  1049                         end,
  1050                     try
  1051                         case gen_server2:call(
  1052                                get_pid(Left), {add_on_right, Self}, infinity) of
  1053                             {ok, Group1} -> group_to_view(Group1);
  1054                             not_ready    -> join_group(Self, GroupName, TxnFun)
  1055                         end
  1056                     catch
  1057                         exit:{R, _}
  1058                           when R =:= noproc; R =:= normal; R =:= shutdown ->
  1059                             Handler();
  1060                         exit:{{R, _}, _}
  1061                           when R =:= nodedown; R =:= shutdown ->
  1062                             Handler()
  1063                     end
  1064             end
  1065     end.
  1066 
  1067 dirty_read_group(GroupName) ->
  1068     case mnesia:dirty_read(?GROUP_TABLE, GroupName) of
  1069         []      -> {error, not_found};
  1070         [Group] -> Group
  1071     end.
  1072 
  1073 read_group(GroupName) ->
  1074     case mnesia:read({?GROUP_TABLE, GroupName}) of
  1075         []      -> {error, not_found};
  1076         [Group] -> Group
  1077     end.
  1078 
  1079 write_group(Group) -> mnesia:write(?GROUP_TABLE, Group, write), Group.
  1080 
  1081 prune_or_create_group(Self, GroupName, TxnFun) ->
  1082     TxnFun(
  1083       fun () ->
  1084               GroupNew = #gm_group { name    = GroupName,
  1085                                      members = [Self],
  1086                                      version = get_version(Self) },
  1087               case read_group(GroupName) of
  1088                   {error, not_found} ->
  1089                       write_group(GroupNew);
  1090                   Group = #gm_group { members = Members } ->
  1091                       case lists:any(fun is_member_alive/1, Members) of
  1092                           true  -> Group;
  1093                           false -> write_group(GroupNew)
  1094                       end
  1095               end
  1096       end).
  1097 
  1098 record_dead_member_in_group(Member, GroupName, TxnFun) ->
  1099     TxnFun(
  1100       fun () ->
  1101               Group = #gm_group { members = Members, version = Ver } =
  1102                   read_group(GroupName),
  1103               case lists:splitwith(
  1104                      fun (Member1) -> Member1 =/= Member end, Members) of
  1105                   {_Members1, []} -> %% not found - already recorded dead
  1106                       Group;
  1107                   {Members1, [Member | Members2]} ->
  1108                       Members3 = Members1 ++ [{dead, Member} | Members2],
  1109                       write_group(Group #gm_group { members = Members3,
  1110                                                     version = Ver + 1 })
  1111               end
  1112       end).
  1113 
  1114 record_new_member_in_group(NewMember, Left, GroupName, TxnFun) ->
  1115     TxnFun(
  1116       fun () ->
  1117               Group = #gm_group { members = Members, version = Ver } =
  1118                   read_group(GroupName),
  1119               {Prefix, [Left | Suffix]} =
  1120                   lists:splitwith(fun (M) -> M =/= Left end, Members),
  1121               write_group(Group #gm_group {
  1122                             members = Prefix ++ [Left, NewMember | Suffix],
  1123                             version = Ver + 1 })
  1124       end).
  1125 
  1126 erase_members_in_group(Members, GroupName, TxnFun) ->
  1127     DeadMembers = [{dead, Id} || Id <- Members],
  1128     TxnFun(
  1129       fun () ->
  1130               Group = #gm_group { members = [_|_] = Members1, version = Ver } =
  1131                   read_group(GroupName),
  1132               case Members1 -- DeadMembers of
  1133                   Members1 -> Group;
  1134                   Members2 -> write_group(
  1135                                 Group #gm_group { members = Members2,
  1136                                                   version = Ver + 1 })
  1137               end
  1138       end).
  1139 
  1140 maybe_erase_aliases(State = #state { self          = Self,
  1141                                      group_name    = GroupName,
  1142                                      members_state = MembersState,
  1143                                      txn_executor  = TxnFun }, View) ->
  1144     #view_member { aliases = Aliases } = fetch_view_member(Self, View),
  1145     {Erasable, MembersState1}
  1146         = ?SETS:fold(
  1147              fun (Id, {ErasableAcc, MembersStateAcc} = Acc) ->
  1148                      #member { last_pub = LP, last_ack = LA } =
  1149                          find_member_or_blank(Id, MembersState),
  1150                      case can_erase_view_member(Self, Id, LA, LP) of
  1151                          true  -> {[Id | ErasableAcc],
  1152                                    erase_member(Id, MembersStateAcc)};
  1153                          false -> Acc
  1154                      end
  1155              end, {[], MembersState}, Aliases),
  1156     View1 = case Erasable of
  1157                 [] -> View;
  1158                 _  -> group_to_view(
  1159                         erase_members_in_group(Erasable, GroupName, TxnFun))
  1160             end,
  1161     change_view(View1, State #state { members_state = MembersState1 }).
  1162 
  1163 can_erase_view_member(Self, Self, _LA, _LP) -> false;
  1164 can_erase_view_member(_Self, _Id,   N,   N) -> true;
  1165 can_erase_view_member(_Self, _Id, _LA, _LP) -> false.
  1166 
  1167 
  1168 %% ---------------------------------------------------------------------------
  1169 %% View monitoring and maintanence
  1170 %% ---------------------------------------------------------------------------
  1171 
  1172 ensure_neighbour(_Ver, Self, {Self, undefined}, Self) ->
  1173     {Self, undefined};
  1174 ensure_neighbour(Ver, Self, {Self, undefined}, RealNeighbour) ->
  1175     ok = gen_server2:cast(get_pid(RealNeighbour),
  1176                           {?TAG, Ver, check_neighbours}),
  1177     {RealNeighbour, maybe_monitor(RealNeighbour, Self)};
  1178 ensure_neighbour(_Ver, _Self, {RealNeighbour, MRef}, RealNeighbour) ->
  1179     {RealNeighbour, MRef};
  1180 ensure_neighbour(Ver, Self, {RealNeighbour, MRef}, Neighbour) ->
  1181     true = erlang:demonitor(MRef),
  1182     Msg = {?TAG, Ver, check_neighbours},
  1183     ok = gen_server2:cast(get_pid(RealNeighbour), Msg),
  1184     ok = case Neighbour of
  1185              Self -> ok;
  1186              _    -> gen_server2:cast(get_pid(Neighbour), Msg)
  1187          end,
  1188     {Neighbour, maybe_monitor(Neighbour, Self)}.
  1189 
  1190 maybe_monitor( Self,  Self) -> undefined;
  1191 maybe_monitor(Other, _Self) -> erlang:monitor(process, get_pid(Other)).
  1192 
  1193 check_neighbours(State = #state { self             = Self,
  1194                                   left             = Left,
  1195                                   right            = Right,
  1196                                   view             = View,
  1197                                   broadcast_buffer = Buffer }) ->
  1198     #view_member { left = VLeft, right = VRight }
  1199         = fetch_view_member(Self, View),
  1200     Ver = view_version(View),
  1201     Left1 = ensure_neighbour(Ver, Self, Left, VLeft),
  1202     Right1 = ensure_neighbour(Ver, Self, Right, VRight),
  1203     Buffer1 = case Right1 of
  1204                   {Self, undefined} -> [];
  1205                   _                 -> Buffer
  1206               end,
  1207     State1 = State #state { left = Left1, right = Right1,
  1208                             broadcast_buffer = Buffer1 },
  1209     ok = maybe_send_catchup(Right, State1),
  1210     State1.
  1211 
  1212 maybe_send_catchup(Right, #state { right = Right }) ->
  1213     ok;
  1214 maybe_send_catchup(_Right, #state { self  = Self,
  1215                                     right = {Self, undefined} }) ->
  1216     ok;
  1217 maybe_send_catchup(_Right, #state { members_state = undefined }) ->
  1218     ok;
  1219 maybe_send_catchup(_Right, #state { self          = Self,
  1220                                     right         = {Right, _MRef},
  1221                                     view          = View,
  1222                                     members_state = MembersState }) ->
  1223     send_right(Right, View,
  1224                {catchup, Self, prepare_members_state(MembersState)}).
  1225 
  1226 
  1227 %% ---------------------------------------------------------------------------
  1228 %% Catch_up delta detection
  1229 %% ---------------------------------------------------------------------------
  1230 
  1231 find_prefix_common_suffix(A, B) ->
  1232     {Prefix, A1} = find_prefix(A, B, queue:new()),
  1233     {Common, Suffix} = find_common(A1, B, queue:new()),
  1234     {Prefix, Common, Suffix}.
  1235 
  1236 %% Returns the elements of A that occur before the first element of B,
  1237 %% plus the remainder of A.
  1238 find_prefix(A, B, Prefix) ->
  1239     case {queue:out(A), queue:out(B)} of
  1240         {{{value, Val}, _A1}, {{value, Val}, _B1}} ->
  1241             {Prefix, A};
  1242         {{empty, A1}, {{value, _A}, _B1}} ->
  1243             {Prefix, A1};
  1244         {{{value, {NumA, _MsgA} = Val}, A1},
  1245          {{value, {NumB, _MsgB}}, _B1}} when NumA < NumB ->
  1246             find_prefix(A1, B, queue:in(Val, Prefix));
  1247         {_, {empty, _B1}} ->
  1248             {A, Prefix} %% Prefix well be empty here
  1249     end.
  1250 
  1251 %% A should be a prefix of B. Returns the commonality plus the
  1252 %% remainder of B.
  1253 find_common(A, B, Common) ->
  1254     case {queue:out(A), queue:out(B)} of
  1255         {{{value, Val}, A1}, {{value, Val}, B1}} ->
  1256             find_common(A1, B1, queue:in(Val, Common));
  1257         {{empty, _A}, _} ->
  1258             {Common, B}
  1259     end.
  1260 
  1261 
  1262 %% ---------------------------------------------------------------------------
  1263 %% Members helpers
  1264 %% ---------------------------------------------------------------------------
  1265 
  1266 with_member(Fun, Id, MembersState) ->
  1267     store_member(
  1268       Id, Fun(find_member_or_blank(Id, MembersState)), MembersState).
  1269 
  1270 with_member_acc(Fun, Id, {MembersState, Acc}) ->
  1271     {MemberState, Acc1} = Fun(find_member_or_blank(Id, MembersState), Acc),
  1272     {store_member(Id, MemberState, MembersState), Acc1}.
  1273 
  1274 find_member_or_blank(Id, MembersState) ->
  1275     case ?DICT:find(Id, MembersState) of
  1276         {ok, Result} -> Result;
  1277         error        -> blank_member()
  1278     end.
  1279 
  1280 erase_member(Id, MembersState) -> ?DICT:erase(Id, MembersState).
  1281 
  1282 blank_member() ->
  1283     #member { pending_ack = queue:new(), last_pub = -1, last_ack = -1 }.
  1284 
  1285 blank_member_state() -> ?DICT:new().
  1286 
  1287 store_member(Id, MemberState, MembersState) ->
  1288     ?DICT:store(Id, MemberState, MembersState).
  1289 
  1290 prepare_members_state(MembersState) -> ?DICT:to_list(MembersState).
  1291 
  1292 build_members_state(MembersStateList) -> ?DICT:from_list(MembersStateList).
  1293 
  1294 make_member(GroupName) ->
  1295    {case dirty_read_group(GroupName) of
  1296         #gm_group { version = Version } -> Version;
  1297         {error, not_found}              -> ?VERSION_START
  1298     end, self()}.
  1299 
  1300 remove_erased_members(MembersState, View) ->
  1301     lists:foldl(fun (Id, MembersState1) ->
  1302                     store_member(Id, find_member_or_blank(Id, MembersState),
  1303                                  MembersState1)
  1304                 end, blank_member_state(), all_known_members(View)).
  1305 
  1306 get_version({Version, _Pid}) -> Version.
  1307 
  1308 get_pid({_Version, Pid}) -> Pid.
  1309 
  1310 get_pids(Ids) -> [Pid || {_Version, Pid} <- Ids].
  1311 
  1312 %% ---------------------------------------------------------------------------
  1313 %% Activity assembly
  1314 %% ---------------------------------------------------------------------------
  1315 
  1316 activity_nil() -> queue:new().
  1317 
  1318 activity_cons(   _Id,   [],   [], Tail) -> Tail;
  1319 activity_cons(Sender, Pubs, Acks, Tail) -> queue:in({Sender, Pubs, Acks}, Tail).
  1320 
  1321 activity_finalise(Activity) -> queue:to_list(Activity).
  1322 
  1323 maybe_send_activity([], _State) ->
  1324     ok;
  1325 maybe_send_activity(Activity, #state { self  = Self,
  1326                                        right = {Right, _MRefR},
  1327                                        view  = View }) ->
  1328     send_right(Right, View, {activity, Self, Activity}).
  1329 
  1330 send_right(Right, View, Msg) ->
  1331     ok = gen_server2:cast(get_pid(Right), {?TAG, view_version(View), Msg}).
  1332 
  1333 callback(Args, Module, Activity) ->
  1334     Result =
  1335       lists:foldl(
  1336         fun ({Id, Pubs, _Acks}, {Args1, Module1, ok}) ->
  1337                 lists:foldl(fun ({_PubNum, Pub}, Acc = {Args2, Module2, ok}) ->
  1338                                     case Module2:handle_msg(
  1339                                            Args2, get_pid(Id), Pub) of
  1340                                         ok ->
  1341                                             Acc;
  1342                                         {become, Module3, Args3} ->
  1343                                             {Args3, Module3, ok};
  1344                                         {stop, _Reason} = Error ->
  1345                                             Error
  1346                                     end;
  1347                                 (_, Error = {stop, _Reason}) ->
  1348                                     Error
  1349                             end, {Args1, Module1, ok}, Pubs);
  1350             (_, Error = {stop, _Reason}) ->
  1351                 Error
  1352         end, {Args, Module, ok}, Activity),
  1353     case Result of
  1354         {Args, Module, ok}      -> ok;
  1355         {Args1, Module1, ok}    -> {become, Module1, Args1};
  1356         {stop, _Reason} = Error -> Error
  1357     end.
  1358 
  1359 change_view(View, State = #state { view          = View0,
  1360                                    module        = Module,
  1361                                    callback_args = Args }) ->
  1362     OldMembers = all_known_members(View0),
  1363     NewMembers = all_known_members(View),
  1364     Births = NewMembers -- OldMembers,
  1365     Deaths = OldMembers -- NewMembers,
  1366     Result = case {Births, Deaths} of
  1367                  {[], []} -> ok;
  1368                  _        -> Module:members_changed(
  1369                                Args, get_pids(Births), get_pids(Deaths))
  1370              end,
  1371     {Result, check_neighbours(State #state { view = View })}.
  1372 
  1373 handle_callback_result({Result, State}) ->
  1374     if_callback_success(
  1375       Result, fun no_reply_true/3, fun no_reply_false/3, undefined, State);
  1376 handle_callback_result({Result, Reply, State}) ->
  1377     if_callback_success(
  1378       Result, fun reply_true/3, fun reply_false/3, Reply, State).
  1379 
  1380 no_reply_true (_Result,        _Undefined, State) -> noreply(State).
  1381 no_reply_false({stop, Reason}, _Undefined, State) -> {stop, Reason, State}.
  1382 
  1383 reply_true (_Result,        Reply, State) -> reply(Reply, State).
  1384 reply_false({stop, Reason}, Reply, State) -> {stop, Reason, Reply, State}.
  1385 
  1386 handle_msg_true (_Result, Msg, State) -> handle_msg(Msg, State).
  1387 handle_msg_false(Result, _Msg, State) -> {Result, State}.
  1388 
  1389 activity_true(_Result, Activity, State = #state { module        = Module,
  1390                                                   callback_args = Args }) ->
  1391     {callback(Args, Module, Activity), State}.
  1392 activity_false(Result, _Activity, State) ->
  1393     {Result, State}.
  1394 
  1395 if_callback_success(ok, True, _False, Arg, State) ->
  1396     True(ok, Arg, State);
  1397 if_callback_success(
  1398   {become, Module, Args} = Result, True, _False, Arg, State) ->
  1399     True(Result, Arg, State #state { module        = Module,
  1400                                      callback_args = Args });
  1401 if_callback_success({stop, _Reason} = Result, _True, False, Arg, State) ->
  1402     False(Result, Arg, State).
  1403 
  1404 maybe_confirm(_Self, _Id, Confirms, []) ->
  1405     Confirms;
  1406 maybe_confirm(Self, Self, Confirms, [PubNum | PubNums]) ->
  1407     case queue:out(Confirms) of
  1408         {empty, _Confirms} ->
  1409             Confirms;
  1410         {{value, {PubNum, From}}, Confirms1} ->
  1411             gen_server2:reply(From, ok),
  1412             maybe_confirm(Self, Self, Confirms1, PubNums);
  1413         {{value, {PubNum1, _From}}, _Confirms} when PubNum1 > PubNum ->
  1414             maybe_confirm(Self, Self, Confirms, PubNums)
  1415     end;
  1416 maybe_confirm(_Self, _Id, Confirms, _PubNums) ->
  1417     Confirms.
  1418 
  1419 purge_confirms(Confirms) ->
  1420     [gen_server2:reply(From, ok) || {_PubNum, From} <- queue:to_list(Confirms)],
  1421     queue:new().
  1422 
  1423 
  1424 %% ---------------------------------------------------------------------------
  1425 %% Msg transformation
  1426 %% ---------------------------------------------------------------------------
  1427 
  1428 acks_from_queue(Q) -> [PubNum || {PubNum, _Msg} <- queue:to_list(Q)].
  1429 
  1430 pubs_from_queue(Q) -> queue:to_list(Q).
  1431 
  1432 queue_from_pubs(Pubs) -> queue:from_list(Pubs).
  1433 
  1434 apply_acks(  [], Pubs) -> Pubs;
  1435 apply_acks(List, Pubs) -> {_, Pubs1} = queue:split(length(List), Pubs),
  1436                           Pubs1.
  1437 
  1438 join_pubs(Q, [])   -> Q;
  1439 join_pubs(Q, Pubs) -> queue:join(Q, queue_from_pubs(Pubs)).
  1440 
  1441 last_ack(  [], LA) -> LA;
  1442 last_ack(List, LA) -> LA1 = lists:last(List),
  1443                       true = LA1 > LA, %% ASSERTION
  1444                       LA1.
  1445 
  1446 last_pub(  [], LP) -> LP;
  1447 last_pub(List, LP) -> {PubNum, _Msg} = lists:last(List),
  1448                       true = PubNum > LP, %% ASSERTION
  1449                       PubNum.