<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>Thinking in Crowd / 鹄思乱想</title>
  <icon>https://www.gravatar.com/avatar/153cbdd8bc3e96a5208e80ecef4159a4</icon>
  <subtitle>Swan flying in the immense sky</subtitle>
  <link href="http://www.thinkingincrowd.me/atom.xml" rel="self"/>
  
  <link href="http://www.thinkingincrowd.me/"/>
  <updated>2022-09-11T02:22:20.619Z</updated>
  <id>http://www.thinkingincrowd.me/</id>
  
  <author>
    <name>鹄思乱想</name>
    <email>chengusky@gmail.com</email>
  </author>
  
  <generator uri="https://hexo.io/">Hexo</generator>
  
  <entry>
    <title>Elixir Module AST Inspect</title>
    <link href="http://www.thinkingincrowd.me/2022/09/04/Elixir-Module-AST-Inspect/"/>
    <id>http://www.thinkingincrowd.me/2022/09/04/Elixir-Module-AST-Inspect/</id>
    <published>2022-09-04T12:59:26.000Z</published>
    <updated>2022-09-11T02:22:20.619Z</updated>
    
    <content type="html"><![CDATA[<p>One day, I got a requirement of extracting the public function information from the Elixir Module.  I got no clue how to achieve it at the beginning but it turns out to be an interesting experience afterward.</p><h2 id="Through-Documentation"><a href="#Through-Documentation" class="headerlink" title="Through Documentation"></a>Through Documentation</h2><p>Anyone who learns Elixir should be familiar with Hex Docs.  Hence, my first reaction is to see how it works because there should be a way to extract the function signature and documentation.  I found out that I can use <code>Code.fetch_docs</code> as below:</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&#123;<span class="symbol">:docs_v1</span>, _, _, _, %&#123;<span class="string">&quot;en&quot;</span> =&gt; module_doc&#125;, _meta, doc_elements&#125; =</span><br><span class="line">  <span class="title class_">Code</span>.fetch_docs(module_or_path)</span><br></pre></td></tr></table></figure><p><em>Notes: If a module name is provided, it must be compiled from a file, not directly in Livebook because of <a href="https://elixirforum.com/t/what-is-the-module-name-compiled-in-livebook/49968/2?u=thinkingincrowd">this</a>.</em></p><p>The format of the <code>doc_elements</code> contains most of the information I need: the function signature and documentation.  However, as there are multiple implementations for one of the functions <code>get_best_block_height/2</code>, using <code>Code.fetch_docs</code> cannot deal with this scenario.  How to overcome it?</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">[</span><br><span class="line">  &#123;&#123;<span class="symbol">:function</span>, <span class="symbol">:get_best_block_height</span>, <span class="number">1</span>&#125;, <span class="number">35</span>, [<span class="string">&quot;get_best_block_height(endpoint)&quot;</span>],</span><br><span class="line">   %&#123;</span><br><span class="line">     <span class="string">&quot;en&quot;</span> =&gt; <span class="string">&quot;Get best **block height** of Ethereum-type network from given endpoint\n&quot;</span></span><br><span class="line">   &#125;, %&#123;&#125;&#125;,</span><br><span class="line">  &#123;&#123;<span class="symbol">:function</span>, <span class="symbol">:get_best_block_height</span>, <span class="number">2</span>&#125;, <span class="number">14</span>, [<span class="string">&quot;get_best_block_height(network, endpoint)&quot;</span>],</span><br><span class="line">   %&#123;</span><br><span class="line">     <span class="string">&quot;en&quot;</span> =&gt;</span><br><span class="line">       <span class="string">&quot;Get best **block height** from given endpoint of either:\n* Ethereum\n* Arweave\n\nNot implemented for BTC yet\n&quot;</span></span><br><span class="line">   &#125;, %&#123;&#125;&#125;,</span><br><span class="line">  &#123;&#123;<span class="symbol">:function</span>, <span class="symbol">:get_module_doc</span>, <span class="number">0</span>&#125;, <span class="number">9</span>, [<span class="string">&quot;get_module_doc()&quot;</span>], %&#123;<span class="string">&quot;en&quot;</span> =&gt; <span class="string">&quot;Get module doc\n&quot;</span>&#125;, %&#123;&#125;&#125;</span><br><span class="line">]</span><br></pre></td></tr></table></figure><h2 id="Through-AST"><a href="#Through-AST" class="headerlink" title="Through AST"></a>Through AST</h2><p>Anyone who has some years’ programming experience should know or hear about AST (Abstract Syntax Tree).  Abstract Syntax Trees are data structures widely used in compilers to represent the structure of program code.</p><p>Elixir has great Meta-programming capability and AST can do the job.  I did not come to AST in the first place due to the deep down scare in me facing this advanced &amp; complicated technique.</p><p>However, it’s actually not as complex as I thought, at least for achieving what I want to do.  According to Elixir’s <a href="https://hexdocs.pm/elixir/syntax-reference.html#the-elixir-ast">Documentation</a>:</p><blockquote><p>The building block of Elixir’s AST is a call, such as:</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sum(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>)</span><br></pre></td></tr></table></figure><p>which is represented as a tuple with three elements:</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;<span class="symbol">:sum</span>, meta, [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]&#125;</span><br></pre></td></tr></table></figure><p>the first element is an atom (or another tuple), the second element is a list of two-element tuples with metadata (such as line numbers) and the third is a list of arguments.</p><p>We can retrieve the AST for any Elixir expression by calling quote:</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">quote</span> <span class="keyword">do</span></span><br><span class="line">  sum()</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"><span class="comment">#=&gt; &#123;:sum, [], []&#125;</span></span><br></pre></td></tr></table></figure></blockquote><p>It is not difficult to understand the AST for a call statement and how to generate the AST.  How about the AST for a module?  Actually, using the <code>quote</code> approach cannot get a module’s AST.  We can load it from the source file using:</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">source_path |&gt; <span class="title class_">File</span>.read!() |&gt; <span class="title class_">Code</span>.string_to_quoted()</span><br></pre></td></tr></table></figure><h3 id="Module-AST-structure"><a href="#Module-AST-structure" class="headerlink" title="Module AST structure"></a>Module AST structure</h3><p><img src="https://github.com/kenspirit/blog-cdn-data/raw/master/elixir-module-ast-inspect.png" alt="Elixir Module AST structure"></p><p>By comparing the Elixir source code and generated AST structure, we can see that AST of the whole module fulfills the basic structure above.  The argument list is an alias and a do block:</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&#123;<span class="symbol">:defmodule</span>, [<span class="symbol">line:</span> <span class="number">1</span>],</span><br><span class="line"> [</span><br><span class="line">   &#123;<span class="symbol">:__aliases__</span>, [<span class="symbol">line:</span> <span class="number">1</span>], [<span class="symbol">:BestBlockHeightGetter</span>]&#125;,</span><br><span class="line">   [</span><br><span class="line">     <span class="symbol">do:</span> &#123;<span class="symbol">:__block__</span>, [], []&#125;</span><br><span class="line">   ]</span><br><span class="line"> ]&#125;</span><br></pre></td></tr></table></figure><h3 id="Module-Block-AST-structure"><a href="#Module-Block-AST-structure" class="headerlink" title="Module Block AST structure"></a>Module Block AST structure</h3><p>The block AST shows clearly that its argument list contains separate ASTs for every attribute (starting with <code>:@</code> atom) and function (starting with <code>:def</code> atom).</p><h3 id="Function-AST-structure"><a href="#Function-AST-structure" class="headerlink" title="Function AST structure"></a>Function AST structure</h3><p>As we can see, for simple functions without guard:</p><ul><li>If it has no parameters, the <code>get_module_doc</code> function (<code>[line: 12]</code>), its argument list in AST is nil.</li><li>If it has parameters, the <code>get_best_block_height</code> function (<code>[line: 26]</code>, <code>[line: 31]</code> and <code>[line: 39]</code>), the parameter is either a constant value or an AST.</li></ul><p>The function with guard is a bit more complex but you should still be able to recognize the components.</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># get_module_doc</span></span><br><span class="line">&#123;<span class="symbol">:def</span>, [<span class="symbol">line:</span> <span class="number">12</span>],</span><br><span class="line"> [</span><br><span class="line">   &#123;<span class="symbol">:get_module_doc</span>, [<span class="symbol">line:</span> <span class="number">12</span>], <span class="literal">nil</span>&#125;,</span><br><span class="line">   [<span class="symbol">do:</span> &#123;<span class="symbol">:</span>@, [<span class="symbol">line:</span> <span class="number">12</span>], [&#123;<span class="symbol">:moduledoc</span>, [<span class="symbol">line:</span> <span class="number">12</span>], <span class="literal">nil</span>&#125;]&#125;]</span><br><span class="line"> ]&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment"># get_best_block_height</span></span><br><span class="line">&#123;<span class="symbol">:def</span>, [<span class="symbol">line:</span> <span class="number">26</span>],</span><br><span class="line"> [</span><br><span class="line">   &#123;<span class="symbol">:get_best_block_height</span>, [<span class="symbol">line:</span> <span class="number">26</span>],</span><br><span class="line">    [<span class="string">&quot;ethereum&quot;</span>, &#123;<span class="symbol">:</span>\\, [<span class="symbol">line:</span> <span class="number">26</span>], [&#123;<span class="symbol">:endpoint</span>, [<span class="symbol">line:</span> <span class="number">26</span>], <span class="literal">nil</span>&#125;, <span class="string">&quot;eth&quot;</span>]&#125;]&#125;,</span><br><span class="line">   [</span><br><span class="line">     <span class="symbol">do:</span> &#123;<span class="symbol">:__block__</span>, [], []&#125;</span><br><span class="line">   ]</span><br><span class="line"> ]&#125;</span><br><span class="line"></span><br><span class="line">&#123;<span class="symbol">:def</span>, [<span class="symbol">line:</span> <span class="number">26</span>],</span><br><span class="line"> [</span><br><span class="line">   &#123;<span class="symbol">:get_best_block_height</span>, [<span class="symbol">line:</span> <span class="number">31</span>], [<span class="string">&quot;arweave&quot;</span>, &#123;<span class="symbol">:endpoint</span>, [<span class="symbol">line:</span> <span class="number">26</span>], <span class="literal">nil</span>&#125;]&#125;,</span><br><span class="line">   [</span><br><span class="line">     <span class="symbol">do:</span> &#123;<span class="symbol">:__block__</span>, [], []&#125;</span><br><span class="line">   ]</span><br><span class="line"> ]&#125;</span><br><span class="line"></span><br><span class="line">&#123;<span class="symbol">:def</span>, [<span class="symbol">line:</span> <span class="number">39</span>],</span><br><span class="line"> [</span><br><span class="line">   &#123;<span class="symbol">:get_best_block_height</span>, [<span class="symbol">line:</span> <span class="number">39</span>], [&#123;<span class="symbol">:endpoint</span>, [<span class="symbol">line:</span> <span class="number">39</span>], <span class="literal">nil</span>&#125;]&#125;,</span><br><span class="line">   [</span><br><span class="line">     <span class="symbol">do:</span> &#123;<span class="symbol">:__block__</span>, [], []&#125;</span><br><span class="line">   ]</span><br><span class="line"> ]&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment"># With Guards</span></span><br><span class="line">&#123;<span class="symbol">:def</span>, [<span class="symbol">line:</span> <span class="number">22</span>],</span><br><span class="line"> [</span><br><span class="line">   &#123;<span class="symbol">:when</span>, [<span class="symbol">line:</span> <span class="number">22</span>],</span><br><span class="line">    [</span><br><span class="line">      &#123;<span class="symbol">:get_best_block_height</span>, [<span class="symbol">line:</span> <span class="number">22</span>],</span><br><span class="line">       [&#123;<span class="symbol">:network</span>, [<span class="symbol">line:</span> <span class="number">22</span>], <span class="literal">nil</span>&#125;, &#123;<span class="symbol">:_endpoint</span>, [<span class="symbol">line:</span> <span class="number">22</span>], <span class="literal">nil</span>&#125;]&#125;,</span><br><span class="line">      &#123;<span class="symbol">:==</span>, [<span class="symbol">line:</span> <span class="number">22</span>], [&#123;<span class="symbol">:network</span>, [<span class="symbol">line:</span> <span class="number">22</span>], <span class="literal">nil</span>&#125;, <span class="string">&quot;btc&quot;</span>]&#125;</span><br><span class="line">    ]&#125;,</span><br><span class="line">   [<span class="symbol">do:</span> &#123;<span class="symbol">:-</span>, [<span class="symbol">line:</span> <span class="number">23</span>], [<span class="number">1</span>]&#125;]</span><br><span class="line"> ]&#125;</span><br></pre></td></tr></table></figure><p>Hence, based on this generated AST, I can get back the function signature using this code snippet (I know the part handling the <code>when</code> case is a bit ugly).</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line">&#123;<span class="symbol">:ok</span>, &#123;<span class="symbol">:defmodule</span>, _meta, [_, [<span class="symbol">do:</span> &#123;<span class="symbol">:__block__</span>, _, block_statements&#125;]]&#125;&#125; =</span><br><span class="line">  source_file_path |&gt; <span class="title class_">File</span>.read!() |&gt; <span class="title class_">Code</span>.string_to_quoted()</span><br><span class="line"></span><br><span class="line">quote_arg = <span class="keyword">fn</span> arg -&gt;</span><br><span class="line">  <span class="keyword">if</span> is_binary(arg), <span class="symbol">do:</span> <span class="string">&quot;\&quot;<span class="subst">#&#123;arg&#125;</span>\&quot;&quot;</span>, <span class="symbol">else:</span> arg</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">parse_arg = <span class="keyword">fn</span> arg -&gt;</span><br><span class="line">  <span class="keyword">case</span> arg <span class="keyword">do</span></span><br><span class="line">    &#123;<span class="symbol">:</span>\\, _, [&#123;arg_name, _, _&#125;, actual]&#125; -&gt;</span><br><span class="line">      <span class="string">&quot;<span class="subst">#&#123;arg_name&#125;</span> \\\\ <span class="subst">#&#123;quote_arg.(actual)&#125;</span>&quot;</span></span><br><span class="line"></span><br><span class="line">    &#123;arg_name, _, _&#125; -&gt;</span><br><span class="line">      arg_name</span><br><span class="line"></span><br><span class="line">    _ -&gt;</span><br><span class="line">      quote_arg.(arg)</span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">block_statements</span><br><span class="line">|&gt; <span class="title class_">Enum</span>.filter(<span class="keyword">fn</span> statement -&gt;</span><br><span class="line">  <span class="keyword">case</span> statement <span class="keyword">do</span></span><br><span class="line">    &#123;<span class="symbol">:def</span>, _meta, _args&#125; -&gt;</span><br><span class="line">      <span class="literal">true</span></span><br><span class="line"></span><br><span class="line">    _ -&gt;</span><br><span class="line">      <span class="literal">false</span></span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span>)</span><br><span class="line">|&gt; <span class="title class_">Enum</span>.map(<span class="keyword">fn</span> &#123;<span class="symbol">:def</span>, _meta, [signature, _block]&#125; -&gt;</span><br><span class="line">  signature</span><br><span class="line"><span class="keyword">end</span>)</span><br><span class="line">|&gt; <span class="title class_">Enum</span>.map(<span class="keyword">fn</span> fun_ast -&gt;</span><br><span class="line">  <span class="keyword">case</span> fun_ast <span class="keyword">do</span></span><br><span class="line">    &#123;<span class="symbol">:when</span>, _meta, [&#123;fun_name, _, args&#125;, &#123;operator, _, [arg1, arg2]&#125;]&#125; -&gt;</span><br><span class="line">      <span class="string">&quot;<span class="subst">#&#123;fun_name&#125;</span>(<span class="subst">#&#123;<span class="title class_">Enum</span>.map(args, &amp;parse_arg.(&amp;<span class="number">1</span>)) |&gt; <span class="title class_">Enum</span>.join(<span class="string">&quot;, &quot;</span>)&#125;</span>) when <span class="subst">#&#123;parse_arg.(arg1)&#125;</span> <span class="subst">#&#123;operator&#125;</span> <span class="subst">#&#123;parse_arg.(arg2)&#125;</span>&quot;</span></span><br><span class="line"></span><br><span class="line">    &#123;fun_name, _meta, <span class="literal">nil</span>&#125; -&gt;</span><br><span class="line">      <span class="string">&quot;<span class="subst">#&#123;fun_name&#125;</span>()&quot;</span></span><br><span class="line"></span><br><span class="line">    &#123;fun_name, _meta, args&#125; -&gt;</span><br><span class="line">      <span class="string">&quot;<span class="subst">#&#123;fun_name&#125;</span>(<span class="subst">#&#123;<span class="title class_">Enum</span>.map(args, &amp;parse_arg.(&amp;<span class="number">1</span>)) |&gt; <span class="title class_">Enum</span>.join(<span class="string">&quot;, &quot;</span>)&#125;</span>)&quot;</span></span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span>)</span><br><span class="line">|&gt; <span class="title class_">Enum</span>.each(&amp;<span class="title class_">IO</span>.puts/<span class="number">1</span>)</span><br></pre></td></tr></table></figure><p>The output would be:</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">get_module_doc()</span><br><span class="line">get_best_block_height(network, _endpoint) <span class="keyword">when</span> network == <span class="string">&quot;btc&quot;</span></span><br><span class="line">get_best_block_height(<span class="string">&quot;ethereum&quot;</span>, endpoint \\ <span class="string">&quot;eth&quot;</span>)</span><br><span class="line">get_best_block_height(<span class="string">&quot;arweave&quot;</span>, endpoint)</span><br><span class="line">get_best_block_height(endpoint)</span><br></pre></td></tr></table></figure>]]></content>
    
    
      
      
    <summary type="html">&lt;p&gt;One day, I got a requirement of extracting the public function information from the Elixir Module.  I got no clue how to achieve it at th</summary>
      
    
    
    
    <category term="Sword" scheme="http://www.thinkingincrowd.me/categories/Sword/"/>
    
    
    <category term="Elixir" scheme="http://www.thinkingincrowd.me/tags/Elixir/"/>
    
  </entry>
  
  <entry>
    <title>Broadway Source Reading (Part 5 - Subscription &amp; Concurrency)</title>
    <link href="http://www.thinkingincrowd.me/2021/10/04/broadway-source-reading-part-5-subscription-and-concurrency/"/>
    <id>http://www.thinkingincrowd.me/2021/10/04/broadway-source-reading-part-5-subscription-and-concurrency/</id>
    <published>2021-10-04T13:26:21.000Z</published>
    <updated>2022-09-04T13:03:03.491Z</updated>
    
    <content type="html"><![CDATA[<p>At the beginning of this interesting <a href="https://dockyard.com/blog/2021/06/24/tuning-broadway-rabbitmq-pipelines-for-latency?utm_medium=email&utm_source=elixir-radar">article</a> about Broadway’s concurrency, it said:</p><blockquote><p><strong>Every producer will try to satisfy the demand of every processor.</strong> If a processor asks for two messages and there are two producers, the processor may get four messages. Since it can only process them one at a time, the others will sit in its process mailbox until it’s ready for them.</p></blockquote><p>Where is the source code supporting this statement?</p><p>In my blog about <a href="https://www.thinkingincrowd.me/2021/06/19/broadway-source-reading-processor/">Processor</a>, there are several key points in the Startup Call Sequence Flow and the Pipeline Diagram:</p><ol><li>ProcessorStage <code>subscribe</code> to Producer during startup.  </li><li>ProcessorStage immediately <code>ask</code> events from Producer after subscription and <code>ask</code> recursively.  </li><li><code>DemandDispatcher</code> coordinates between the Producer and Processor.</li></ol><h2 id="How-the-subscription-is-done"><a href="#How-the-subscription-is-done" class="headerlink" title="How the subscription is done?"></a>How the subscription is done?</h2><p>In <code>Subscriber.init/1</code>, below statement tells us that <strong>every consumer process will subscribe to all producer processes randomly and ask for events</strong>.</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># We always subscribe in random order so the load is balanced across consumers.</span></span><br><span class="line">names |&gt; <span class="title class_">Enum</span>.shuffle() |&gt; <span class="title class_">Enum</span>.each(&amp;subscribe(&amp;<span class="number">1</span>, state))</span><br></pre></td></tr></table></figure><h2 id="Distribution-Logic-on-Biggest-Demand"><a href="#Distribution-Logic-on-Biggest-Demand" class="headerlink" title="Distribution Logic on Biggest Demand"></a>Distribution Logic on Biggest Demand</h2><p>Based on the documentation, the <code>DemandDispatcher</code> is:  </p><blockquote><ul><li><code>GenStage.DemandDispatcher</code> - dispatches the given batch of events to the consumer with the biggest demand in a FIFO ordering. This is the default dispatcher.</li></ul></blockquote><p>During startup, the initial <code>dispatcher_state</code> of the Dispatcher is set to <code>&#123;[], 0, nil&#125;</code>.  Once there is a processor subscribed to the producer, its state <code>&#123;0, pid, ref&#125;</code> is added to the last of the <code>demands</code> list.  </p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">init</span></span>(_opts) <span class="keyword">do</span></span><br><span class="line">  &#123;<span class="symbol">:ok</span>, &#123;[], <span class="number">0</span>, <span class="literal">nil</span>&#125;&#125;</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="variable">@doc</span> <span class="literal">false</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">subscribe</span></span>(_opts, &#123;pid, ref&#125;, &#123;demands, pending, max&#125;) <span class="keyword">do</span></span><br><span class="line">  &#123;<span class="symbol">:ok</span>, <span class="number">0</span>, &#123;demands ++ [&#123;<span class="number">0</span>, pid, ref&#125;], pending, max&#125;&#125;</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><p>When the Processor <code>ask</code> for events after subscription, the Dispatcher’s <code>ask/3</code> function is called:</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">ask</span></span>(counter, &#123;pid, ref&#125;, &#123;demands, pending, max&#125;) <span class="keyword">do</span></span><br><span class="line">  max = max || counter</span><br><span class="line"></span><br><span class="line">  <span class="comment"># Omitted demand checking for brevity</span></span><br><span class="line"></span><br><span class="line">  &#123;current, demands&#125; = pop_demand(ref, demands)</span><br><span class="line">  demands = add_demand(current + counter, pid, ref, demands)</span><br><span class="line"></span><br><span class="line">  already_sent = min(pending, counter)</span><br><span class="line">  &#123;<span class="symbol">:ok</span>, counter - already_sent, &#123;demands, pending - already_sent, max&#125;&#125;</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">defp</span> <span class="title">add_demand</span></span>(counter, pid, ref, [&#123;c, _, _&#125; | _] = demands) <span class="keyword">when</span> counter &gt; c <span class="keyword">do</span></span><br><span class="line">  [&#123;counter, pid, ref&#125; | demands]</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">defp</span> <span class="title">add_demand</span></span>(counter, pid, ref, [demand | demands]) <span class="keyword">do</span></span><br><span class="line">  [demand | add_demand(counter, pid, ref, demands)]</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">defp</span> <span class="title">add_demand</span></span>(counter, pid, ref, []) <span class="keyword">when</span> is_integer(counter) <span class="keyword">do</span></span><br><span class="line">  [&#123;counter, pid, ref&#125;]</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">defp</span> <span class="title">pop_demand</span></span>(ref, demands) <span class="keyword">do</span></span><br><span class="line">  &#123;&#123;current, _pid, ^ref&#125;, rest&#125; = <span class="title class_">List</span>.keytake(demands, ref, <span class="number">2</span>)</span><br><span class="line">  &#123;current, rest&#125;</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><p>Right after subscription, the <code>counter</code> passed in here is the <strong>max_demand</strong> of the Processor.  <code>pop_demand/2</code> finds out the current pending demand for this specific consumer, and then <code>add_demand/4</code>, assuming <code>demands</code> a sorted list of highest demand on the left, adds the current request count to its pending demand, loops through all other consumers and inserts it to the right position.  </p><h2 id="Unexpected-Subscription-and-Demand-Distribution"><a href="#Unexpected-Subscription-and-Demand-Distribution" class="headerlink" title="Unexpected Subscription and Demand Distribution"></a>Unexpected Subscription and Demand Distribution</h2><p>How many events does one Producer get?  How events are distributed across Processors?</p><p>RabbitMQ’s <a href="https://www.rabbitmq.com/consumer-prefetch.html">Consumer Prefetch</a> configuration sets the <code>global</code> flag to <code>false</code> as default value and that means the <code>:prefetch_count</code> option is applied to each Producer process (one RabbitMQ consumer) level.  That means when we set the Producer’s <code>:concurrency</code> to <code>10</code>, <code>:prefetch_count</code> to <code>1</code>, if the RabbitMQ has <code>10</code> messages, every Producer should have <code>1</code> message in theory.</p><p>According to my blog about <a href="http://www.thinkingincrowd.me/2021/05/07/broadway-source-reading-producer/">producer</a>, we know that RabbitMQ Producer does nothing on <code>handle_demand/2</code> and it returns an <code>[]</code>.  The events should be delivered in <code>handle_info/2</code> whenever the RabbitMQ pushes the message to the Producer.  That article’s tracking on <code>ask</code> function call actually does not reflect the event distribution reality because <code>ask</code> is called recursively.  They should happen to see so because they also added debug log in <code>handle_info/2</code>.  </p><p>According to the Call Sequence Flow and source code, GenStage’s <code>dispatch_events/3</code> and DemandDispatcher’s <code>dispatch/2</code> should be called.  The DemandDispatcher splits the events based on the count asked by the Processor, dispatches to the first Processor in <code>demands</code> list and rearranging the <code>demands</code> list afterwards.  </p><p>As the <code>handle_info/2</code> of Broadway RabbitMQ Producer passes one event to one Processor at a time, if every producer gets <code>1</code> message, and the random subscription makes the <code>demands</code> list random, the outcome should be several random Processors got <code>1</code> or <code>2</code> message.  </p><p>However, after I cloned the <a href="https://github.com/nathanl/broadway_rabbitmq_experiment">experiment project</a> from that article, added some debug messages into the dependency library <code>GenStage</code>, <code>Broadway</code>, some unexpected behavior occurs.</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Pipeline</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">start_link</span></span>(_opts) <span class="keyword">do</span></span><br><span class="line">  <span class="title class_">Broadway</span>.start_link(</span><br><span class="line">    __MODULE__,</span><br><span class="line">    <span class="symbol">name:</span> __MODULE__,</span><br><span class="line">    <span class="symbol">producer:</span> [</span><br><span class="line">      <span class="symbol">module:</span></span><br><span class="line">        &#123;<span class="title class_">BroadwayRabbitMQ</span>.<span class="title class_">Producer</span>,</span><br><span class="line">         <span class="symbol">queue:</span> <span class="title class_">Foo</span>.env!(<span class="symbol">:queue_name</span>),</span><br><span class="line">         <span class="symbol">connection:</span> <span class="title class_">Foo</span>.conn_options(),</span><br><span class="line">         <span class="symbol">qos:</span> [</span><br><span class="line">           <span class="comment"># this should never be less than @processor_concurrency</span></span><br><span class="line">           <span class="comment"># or else the processors won&#x27;t all get messages</span></span><br><span class="line">           <span class="symbol">prefetch_count:</span> <span class="number">1</span></span><br><span class="line">         ],</span><br><span class="line">         <span class="symbol">on_failure:</span> <span class="symbol">:reject</span>&#125;,</span><br><span class="line">      <span class="comment"># concurrency: 1, # correct behavior</span></span><br><span class="line">      <span class="symbol">concurrency:</span> <span class="number">10</span>, <span class="comment"># try this for poor performance</span></span><br><span class="line">    ],</span><br><span class="line">    <span class="symbol">processors:</span> [</span><br><span class="line">      <span class="symbol">default:</span> [</span><br><span class="line">        <span class="symbol">concurrency:</span> <span class="number">10</span>,</span><br><span class="line">        <span class="symbol">max_demand:</span> <span class="number">1</span></span><br><span class="line">      ]</span><br><span class="line">    ]</span><br><span class="line">  )</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># Broadway.Topology.Subscriber.init/1</span></span><br><span class="line"></span><br><span class="line">shuffled_names = names |&gt; <span class="title class_">Enum</span>.shuffle()</span><br><span class="line"><span class="title class_">IO</span>.inspect(<span class="string">&quot;Processor <span class="subst">#&#123;inspect(self())&#125;</span> subscribe to Producer <span class="subst">#&#123;inspect(<span class="title class_">Process</span>.whereis(<span class="title class_">Enum</span>.at(shuffled_names, <span class="number">0</span>)))&#125;</span> first&quot;</span>)</span><br><span class="line"><span class="title class_">Enum</span>.each(shuffled_names, &amp;subscribe(&amp;<span class="number">1</span>, state))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># GenStage.DemandDispatcher.subscribe/2</span></span><br><span class="line"></span><br><span class="line"><span class="title class_">IO</span>.inspect(<span class="string">&quot;Subscribed <span class="subst">#&#123;inspect(self())&#125;</span> from <span class="subst">#&#123;inspect(pid)&#125;</span>&quot;</span>)</span><br><span class="line">&#123;<span class="symbol">:ok</span>, <span class="number">0</span>, &#123;demands ++ [&#123;<span class="number">0</span>, pid, ref&#125;], pending, max&#125;&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># GenStage.DemandDispatcher.dispatch_demand/3</span></span><br><span class="line"></span><br><span class="line">pids = <span class="title class_">Enum</span>.map(demands, <span class="keyword">fn</span> &#123;_, other_pid, _&#125; -&gt;</span><br><span class="line">  other_pid</span><br><span class="line"><span class="keyword">end</span>)</span><br><span class="line"><span class="title class_">IO</span>.inspect(<span class="string">&quot;Producer <span class="subst">#&#123;inspect(self())&#125;</span> sends message to consumer <span class="subst">#&#123;inspect(pid)&#125;</span> out of <span class="subst">#&#123;inspect(pids)&#125;</span>&quot;</span>)</span><br></pre></td></tr></table></figure><p>When I started the application, the debug message shows that each Processor indeed try to subscribe to producer randomly.  However, if you examine the output below carefully, you can find that <strong>the actual moment of the subscription in GenStage process (debug logs like “Subscribed xxxx from yyyy”), which is also constructing the <code>demands</code> list, happens sequentially on each Producer and Processor</strong>.</p><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br></pre></td><td class="code"><pre><span class="line">&quot;Processor #PID&lt;0.344.0&gt; subscribe to Producer #PID&lt;0.341.0&gt; first&quot;</span><br><span class="line">&quot;Processor #PID&lt;0.345.0&gt; subscribe to Producer #PID&lt;0.333.0&gt; first&quot;</span><br><span class="line">&quot;Processor #PID&lt;0.346.0&gt; subscribe to Producer #PID&lt;0.336.0&gt; first&quot;</span><br><span class="line">&quot;Processor #PID&lt;0.347.0&gt; subscribe to Producer #PID&lt;0.340.0&gt; first&quot;</span><br><span class="line">&quot;Processor #PID&lt;0.348.0&gt; subscribe to Producer #PID&lt;0.341.0&gt; first&quot;</span><br><span class="line">&quot;Processor #PID&lt;0.349.0&gt; subscribe to Producer #PID&lt;0.337.0&gt; first&quot;</span><br><span class="line">&quot;Processor #PID&lt;0.350.0&gt; subscribe to Producer #PID&lt;0.339.0&gt; first&quot;</span><br><span class="line">&quot;Processor #PID&lt;0.351.0&gt; subscribe to Producer #PID&lt;0.339.0&gt; first&quot;</span><br><span class="line">&quot;Processor #PID&lt;0.352.0&gt; subscribe to Producer #PID&lt;0.334.0&gt; first&quot;</span><br><span class="line">&quot;Processor #PID&lt;0.353.0&gt; subscribe to Producer #PID&lt;0.341.0&gt; first&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.335.0&gt; from #PID&lt;0.344.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.339.0&gt; from #PID&lt;0.344.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.341.0&gt; from #PID&lt;0.344.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.335.0&gt; from #PID&lt;0.345.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.333.0&gt; from #PID&lt;0.344.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.335.0&gt; from #PID&lt;0.346.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.333.0&gt; from #PID&lt;0.345.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.339.0&gt; from #PID&lt;0.345.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.335.0&gt; from #PID&lt;0.347.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.341.0&gt; from #PID&lt;0.345.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.333.0&gt; from #PID&lt;0.346.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.342.0&gt; from #PID&lt;0.344.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.335.0&gt; from #PID&lt;0.348.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.339.0&gt; from #PID&lt;0.346.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.333.0&gt; from #PID&lt;0.347.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.341.0&gt; from #PID&lt;0.346.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.335.0&gt; from #PID&lt;0.349.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.333.0&gt; from #PID&lt;0.348.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.335.0&gt; from #PID&lt;0.350.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.342.0&gt; from #PID&lt;0.345.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.339.0&gt; from #PID&lt;0.347.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.333.0&gt; from #PID&lt;0.349.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.341.0&gt; from #PID&lt;0.347.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.338.0&gt; from #PID&lt;0.344.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.335.0&gt; from #PID&lt;0.351.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.337.0&gt; from #PID&lt;0.344.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.342.0&gt; from #PID&lt;0.346.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.336.0&gt; from #PID&lt;0.344.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.339.0&gt; from #PID&lt;0.348.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.333.0&gt; from #PID&lt;0.350.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.335.0&gt; from #PID&lt;0.352.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.340.0&gt; from #PID&lt;0.344.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.338.0&gt; from #PID&lt;0.345.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.341.0&gt; from #PID&lt;0.348.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.337.0&gt; from #PID&lt;0.345.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.342.0&gt; from #PID&lt;0.347.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.336.0&gt; from #PID&lt;0.345.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.339.0&gt; from #PID&lt;0.349.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.333.0&gt; from #PID&lt;0.351.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.341.0&gt; from #PID&lt;0.349.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.335.0&gt; from #PID&lt;0.353.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.342.0&gt; from #PID&lt;0.348.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.340.0&gt; from #PID&lt;0.345.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.338.0&gt; from #PID&lt;0.346.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.334.0&gt; from #PID&lt;0.344.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.337.0&gt; from #PID&lt;0.346.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.336.0&gt; from #PID&lt;0.346.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.333.0&gt; from #PID&lt;0.352.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.339.0&gt; from #PID&lt;0.350.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.338.0&gt; from #PID&lt;0.347.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.334.0&gt; from #PID&lt;0.345.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.340.0&gt; from #PID&lt;0.346.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.341.0&gt; from #PID&lt;0.350.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.337.0&gt; from #PID&lt;0.347.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.342.0&gt; from #PID&lt;0.349.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.333.0&gt; from #PID&lt;0.353.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.334.0&gt; from #PID&lt;0.346.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.338.0&gt; from #PID&lt;0.348.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.336.0&gt; from #PID&lt;0.347.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.341.0&gt; from #PID&lt;0.351.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.340.0&gt; from #PID&lt;0.347.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.342.0&gt; from #PID&lt;0.350.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.339.0&gt; from #PID&lt;0.351.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.337.0&gt; from #PID&lt;0.348.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.334.0&gt; from #PID&lt;0.347.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.336.0&gt; from #PID&lt;0.348.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.339.0&gt; from #PID&lt;0.352.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.341.0&gt; from #PID&lt;0.352.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.337.0&gt; from #PID&lt;0.349.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.342.0&gt; from #PID&lt;0.351.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.334.0&gt; from #PID&lt;0.348.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.338.0&gt; from #PID&lt;0.349.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.336.0&gt; from #PID&lt;0.349.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.341.0&gt; from #PID&lt;0.353.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.339.0&gt; from #PID&lt;0.353.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.342.0&gt; from #PID&lt;0.352.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.337.0&gt; from #PID&lt;0.350.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.340.0&gt; from #PID&lt;0.348.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.334.0&gt; from #PID&lt;0.349.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.338.0&gt; from #PID&lt;0.350.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.342.0&gt; from #PID&lt;0.353.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.336.0&gt; from #PID&lt;0.350.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.337.0&gt; from #PID&lt;0.351.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.334.0&gt; from #PID&lt;0.350.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.340.0&gt; from #PID&lt;0.349.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.338.0&gt; from #PID&lt;0.351.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.336.0&gt; from #PID&lt;0.351.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.340.0&gt; from #PID&lt;0.350.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.337.0&gt; from #PID&lt;0.352.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.334.0&gt; from #PID&lt;0.351.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.338.0&gt; from #PID&lt;0.352.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.336.0&gt; from #PID&lt;0.352.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.340.0&gt; from #PID&lt;0.351.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.337.0&gt; from #PID&lt;0.353.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.334.0&gt; from #PID&lt;0.352.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.336.0&gt; from #PID&lt;0.353.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.338.0&gt; from #PID&lt;0.353.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.340.0&gt; from #PID&lt;0.352.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.334.0&gt; from #PID&lt;0.353.0&gt;&quot;</span><br><span class="line">&quot;Subscribed #PID&lt;0.340.0&gt; from #PID&lt;0.353.0&gt;&quot;</span><br></pre></td></tr></table></figure><p>Once I send messages to RabbitMQ, we can see that every producer gets one message as expected.  But the <code>demands</code> list for every producer is the same, with the starting sequence of every consumer process.  Because the <code>demands</code> list across different Producer processes are the same at the beginning, the first batch of events are always distributed to the #1 Processor.  And this is also the observation documented in the experiment project Readme.</p><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">iex(dev@localhost)1&gt; Foo.send_messages(10)</span><br><span class="line">&quot;Producer #PID&lt;0.342.0&gt; got one message.&quot;</span><br><span class="line">&quot;Producer #PID&lt;0.340.0&gt; got one message.&quot;</span><br><span class="line">&quot;Producer #PID&lt;0.337.0&gt; got one message.&quot;</span><br><span class="line">&quot;Producer #PID&lt;0.333.0&gt; got one message.&quot;</span><br><span class="line">&quot;Producer #PID&lt;0.334.0&gt; got one message.&quot;</span><br><span class="line">&quot;Producer #PID&lt;0.335.0&gt; got one message.&quot;</span><br><span class="line">&quot;Producer #PID&lt;0.336.0&gt; got one message.&quot;</span><br><span class="line">&quot;Producer #PID&lt;0.338.0&gt; got one message.&quot;</span><br><span class="line">&quot;Producer #PID&lt;0.339.0&gt; got one message.&quot;</span><br><span class="line">&quot;Producer #PID&lt;0.341.0&gt; got one message.&quot;</span><br><span class="line">&quot;Producer #PID&lt;0.342.0&gt; sends message to consumer #PID&lt;0.344.0&gt; out of [#PID&lt;0.345.0&gt;, #PID&lt;0.346.0&gt;, #PID&lt;0.347.0&gt;, #PID&lt;0.348.0&gt;, #PID&lt;0.349.0&gt;, #PID&lt;0.350.0&gt;, #PID&lt;0.351.0&gt;, #PID&lt;0.352.0&gt;, #PID&lt;0.353.0&gt;]&quot;</span><br><span class="line">&quot;Producer #PID&lt;0.337.0&gt; sends message to consumer #PID&lt;0.344.0&gt; out of [#PID&lt;0.345.0&gt;, #PID&lt;0.346.0&gt;, #PID&lt;0.347.0&gt;, #PID&lt;0.348.0&gt;, #PID&lt;0.349.0&gt;, #PID&lt;0.350.0&gt;, #PID&lt;0.351.0&gt;, #PID&lt;0.352.0&gt;, #PID&lt;0.353.0&gt;]&quot;</span><br><span class="line">&quot;Producer #PID&lt;0.340.0&gt; sends message to consumer #PID&lt;0.344.0&gt; out of [#PID&lt;0.345.0&gt;, #PID&lt;0.346.0&gt;, #PID&lt;0.347.0&gt;, #PID&lt;0.348.0&gt;, #PID&lt;0.349.0&gt;, #PID&lt;0.350.0&gt;, #PID&lt;0.351.0&gt;, #PID&lt;0.352.0&gt;, #PID&lt;0.353.0&gt;]&quot;</span><br><span class="line">&quot;Producer #PID&lt;0.333.0&gt; sends message to consumer #PID&lt;0.344.0&gt; out of [#PID&lt;0.345.0&gt;, #PID&lt;0.346.0&gt;, #PID&lt;0.347.0&gt;, #PID&lt;0.348.0&gt;, #PID&lt;0.349.0&gt;, #PID&lt;0.350.0&gt;, #PID&lt;0.351.0&gt;, #PID&lt;0.352.0&gt;, #PID&lt;0.353.0&gt;]&quot;</span><br><span class="line">&quot;Producer #PID&lt;0.334.0&gt; sends message to consumer #PID&lt;0.344.0&gt; out of [#PID&lt;0.345.0&gt;, #PID&lt;0.346.0&gt;, #PID&lt;0.347.0&gt;, #PID&lt;0.348.0&gt;, #PID&lt;0.349.0&gt;, #PID&lt;0.350.0&gt;, #PID&lt;0.351.0&gt;, #PID&lt;0.352.0&gt;, #PID&lt;0.353.0&gt;]&quot;</span><br><span class="line">&quot;Producer #PID&lt;0.335.0&gt; sends message to consumer #PID&lt;0.344.0&gt; out of [#PID&lt;0.345.0&gt;, #PID&lt;0.346.0&gt;, #PID&lt;0.347.0&gt;, #PID&lt;0.348.0&gt;, #PID&lt;0.349.0&gt;, #PID&lt;0.350.0&gt;, #PID&lt;0.351.0&gt;, #PID&lt;0.352.0&gt;, #PID&lt;0.353.0&gt;]&quot;</span><br><span class="line">&quot;Producer #PID&lt;0.336.0&gt; sends message to consumer #PID&lt;0.344.0&gt; out of [#PID&lt;0.345.0&gt;, #PID&lt;0.346.0&gt;, #PID&lt;0.347.0&gt;, #PID&lt;0.348.0&gt;, #PID&lt;0.349.0&gt;, #PID&lt;0.350.0&gt;, #PID&lt;0.351.0&gt;, #PID&lt;0.352.0&gt;, #PID&lt;0.353.0&gt;]&quot;</span><br><span class="line">&quot;Producer #PID&lt;0.339.0&gt; sends message to consumer #PID&lt;0.344.0&gt; out of [#PID&lt;0.345.0&gt;, #PID&lt;0.346.0&gt;, #PID&lt;0.347.0&gt;, #PID&lt;0.348.0&gt;, #PID&lt;0.349.0&gt;, #PID&lt;0.350.0&gt;, #PID&lt;0.351.0&gt;, #PID&lt;0.352.0&gt;, #PID&lt;0.353.0&gt;]&quot;</span><br><span class="line">&quot;Producer #PID&lt;0.338.0&gt; sends message to consumer #PID&lt;0.344.0&gt; out of [#PID&lt;0.345.0&gt;, #PID&lt;0.346.0&gt;, #PID&lt;0.347.0&gt;, #PID&lt;0.348.0&gt;, #PID&lt;0.349.0&gt;, #PID&lt;0.350.0&gt;, #PID&lt;0.351.0&gt;, #PID&lt;0.352.0&gt;, #PID&lt;0.353.0&gt;]&quot;</span><br><span class="line">&quot;Producer #PID&lt;0.341.0&gt; sends message to consumer #PID&lt;0.344.0&gt; out of [#PID&lt;0.345.0&gt;, #PID&lt;0.346.0&gt;, #PID&lt;0.347.0&gt;, #PID&lt;0.348.0&gt;, #PID&lt;0.349.0&gt;, #PID&lt;0.350.0&gt;, #PID&lt;0.351.0&gt;, #PID&lt;0.352.0&gt;, #PID&lt;0.353.0&gt;]&quot;</span><br><span class="line">&quot;processor #PID&lt;0.344.0&gt; got &#x27;2&#x27;; has 3 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.344.0&gt; got &#x27;3&#x27;; has 8 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.344.0&gt; got &#x27;1&#x27;; has 7 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.344.0&gt; got &#x27;6&#x27;; has 6 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.344.0&gt; got &#x27;4&#x27;; has 5 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.344.0&gt; got &#x27;5&#x27;; has 4 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.344.0&gt; got &#x27;7&#x27;; has 3 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.344.0&gt; got &#x27;10&#x27;; has 2 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.344.0&gt; got &#x27;8&#x27;; has 1 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.344.0&gt; got &#x27;9&#x27;; has 0 message(s) in its mailbox&quot;</span><br></pre></td></tr></table></figure><p>How can this happen?  My suspicion is that the messages in the mailbox of each Producer process are filled by the sequence of Processors’ startup sequence.  That mean even though every Processor tries to subscribe to the Producer randomly by shuffling the producer names, but each Producer still receives the subscription signal from Processor #1 firstly, and then #2, and then #3, and finally the #10.  </p><p>This phenomenon happens obviously when the batch size of the messages is equal to or smaller than the processor count.  But even if the batch size is much larger, say 50, beside the first 10 will be sent to the #1 processor, others will be biased to the processors started earlier.  I think the load could only be balanced after the system running for a while.  Below is the output (sorted) of the first batch of <code>50</code> messages.</p><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line">&quot;processor #PID&lt;0.344.0&gt; got &#x27;1&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.344.0&gt; got &#x27;10&#x27;; has 3 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.344.0&gt; got &#x27;2&#x27;; has 7 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.344.0&gt; got &#x27;3&#x27;; has 8 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.344.0&gt; got &#x27;4&#x27;; has 6 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.344.0&gt; got &#x27;5&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.344.0&gt; got &#x27;6&#x27;; has 2 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.344.0&gt; got &#x27;7&#x27;; has 5 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.344.0&gt; got &#x27;8&#x27;; has 1 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.344.0&gt; got &#x27;9&#x27;; has 4 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.345.0&gt; got &#x27;11&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.345.0&gt; got &#x27;12&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.345.0&gt; got &#x27;14&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.345.0&gt; got &#x27;17&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.345.0&gt; got &#x27;21&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.345.0&gt; got &#x27;26&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.345.0&gt; got &#x27;32&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.345.0&gt; got &#x27;39&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.345.0&gt; got &#x27;47&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.346.0&gt; got &#x27;13&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.346.0&gt; got &#x27;16&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.346.0&gt; got &#x27;18&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.346.0&gt; got &#x27;22&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.346.0&gt; got &#x27;27&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.346.0&gt; got &#x27;33&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.346.0&gt; got &#x27;40&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.346.0&gt; got &#x27;48&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.347.0&gt; got &#x27;15&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.347.0&gt; got &#x27;20&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.347.0&gt; got &#x27;25&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.347.0&gt; got &#x27;28&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.347.0&gt; got &#x27;34&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.347.0&gt; got &#x27;41&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.347.0&gt; got &#x27;49&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.348.0&gt; got &#x27;19&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.348.0&gt; got &#x27;24&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.348.0&gt; got &#x27;31&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.348.0&gt; got &#x27;35&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.348.0&gt; got &#x27;42&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.348.0&gt; got &#x27;50&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.349.0&gt; got &#x27;23&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.349.0&gt; got &#x27;30&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.349.0&gt; got &#x27;38&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.349.0&gt; got &#x27;43&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.350.0&gt; got &#x27;29&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.350.0&gt; got &#x27;36&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.350.0&gt; got &#x27;46&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.351.0&gt; got &#x27;37&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.351.0&gt; got &#x27;44&#x27;; has 0 message(s) in its mailbox&quot;</span><br><span class="line">&quot;processor #PID&lt;0.352.0&gt; got &#x27;45&#x27;; has 0 message(s) in its mailbox&quot;</span><br></pre></td></tr></table></figure><p><em>Update:</em> As per the discussion in <a href="https://github.com/dashbitco/broadway/issues/269">issue raised in Broadway</a>, my suspicion is correct.  My PRs to GenStage and Broadway have fixed this issue.  :D</p>]]></content>
    
    
      
      
    <summary type="html">&lt;p&gt;At the beginning of this interesting &lt;a href=&quot;https://dockyard.com/blog/2021/06/24/tuning-broadway-rabbitmq-pipelines-for-latency?utm_med</summary>
      
    
    
    
    <category term="Sword" scheme="http://www.thinkingincrowd.me/categories/Sword/"/>
    
    
    <category term="Elixir" scheme="http://www.thinkingincrowd.me/tags/Elixir/"/>
    
    <category term="Source Reading" scheme="http://www.thinkingincrowd.me/tags/Source-Reading/"/>
    
  </entry>
  
  <entry>
    <title>Broadway Source Reading (Part 4 - Batching)</title>
    <link href="http://www.thinkingincrowd.me/2021/07/16/broadway-source-reading-batching/"/>
    <id>http://www.thinkingincrowd.me/2021/07/16/broadway-source-reading-batching/</id>
    <published>2021-07-16T14:50:00.000Z</published>
    <updated>2022-08-28T08:07:15.454Z</updated>
    
    <content type="html"><![CDATA[<h2 id="GenStage-pipelines"><a href="#GenStage-pipelines" class="headerlink" title="GenStage pipelines"></a>GenStage pipelines</h2><p>When options for batcher is configured, the processor becomes <code>:producer_consumer</code> type.  The GenStage pipeline becomes much more complex than the simple one shown in <a href="http://www.thinkingincrowd.me/2021/06/19/broadway-source-reading-processor/">the post about processor</a>.  </p><pre class="mermaid">graph TD  A(Producer) --> B(Processor_1)  A --> P(Processor_2)  B --> C(Batcher:S3)  B -.-> H(DemandDispatcher/PartitionDispatcher)  P -.-> H  P --> D(Batcher:SQS)  C --> F(BatchProcessor_S3_1)  C --> I(BatchProcessor_S3_2)  C -.-> H  D -.-> H  D --> G(BatchProcessor_SQS_1)  F -.-> K(Acknowledger)  I -.-> K  G -.-> K</pre><p><em>Notes: The communications between the stages are through process message passing, while other interactions between the <code>DemandDispatcher</code>, the <code>Acknowledger</code> and them are through direct method calls.  The Dispatcher and Acknowledger are not part of the GenStage pipelines and so here uses dotted line to indicate their interactions to have clearer separation.</em></p><p>In the scenario of multiple batchers, <code>PartitionDispatcher</code> is used instead of <code>DemandDispatcher</code> for the processors in <code>build_processors_specs/2</code> and the <code>:partitions</code> are set by the keys of the batchers’ config.  </p><p>The interactions with dispatcher is to register the processes of the <code>BatcherStage / BatchProcessorStage</code> into the <code>dispatcher_state</code> of the processes of <code>ProcessorStage / BatcherStage</code> respectively for event dispatching.  Related source code is the <code>handle_info/2</code> in the processes of <code>ProcessorStage</code> and <code>BatcherStage</code> matching the <code>&#123;:&quot;$gen_producer&quot;, &#123;consumer_pid, ref&#125; = from, &#123;:subscribe, cancel, opts&#125;&#125;</code> message.  It invokes the <code>producer_subscribe/3</code> function, subsequently invokes the function <code>subscribe(opts, from, dispatcher_state)</code> of the <code>DemandDispatcher / PartitionDispatcher</code>.  </p><h2 id="Message-Consuming-as-a-Producer-Consumer-w-Batcher"><a href="#Message-Consuming-as-a-Producer-Consumer-w-Batcher" class="headerlink" title="Message Consuming as a Producer Consumer (w Batcher)"></a>Message Consuming as a Producer Consumer (w Batcher)</h2><p>The sequence flow which starts with <code>ProducerStage</code> takes another path as the <code>ProcessorStage</code> is changed to be <code>:producer_consumer</code> with batchers.  And the <code>take_pc_events/3</code> function actually calls <code>consumer_dispatch/6</code> that we covered in <a href="http://www.thinkingincrowd.me/2021/06/19/broadway-source-reading-processor/">the post about processor</a>.  </p><pre class="mermaid">sequenceDiagram  participant P as ProducerStage  participant D as DemandDispatcher  participant PS as ProcessorStage  P->>P: take_from_buffer(counter, %{stage | dispatcher_state: dispatcher_state})  P->>P: noreply_callback(:handle_demand, [counter, state], stage)  P->>P: handle_demand/2  P->>P: handle_noreply_callback/2  P->>P: dispatch_events/3  P->>D: dispatch/3  alt as Producer      P--)PS: handle_info({:"$gen_consumer", {producer_pid, ref}, events}, %{type: :consumer} = stage)      PS->>PS: consumer_dispatch/6  else as ProducerConsumer      P--)PS: handle_info({:"$gen_consumer", {producer_pid, ref}, events}, %{type: :producer_consumer} = stage)      loop take_pc_events/3 until event in queue is empty        PS->>PS: send_pc_events/3        PS->>PS: consumer_dispatch/6      end  end</pre><p>Because the messages will be forwarded to the batchers without acknowledgement after processing.  As a result, the <code>successful_messages_to_ack</code> is <code>[]</code>, and the <code>successful_messages_to_forward</code> contain all messages to batchers.  Below is the sub-sequence flow of <code>dispatch_events/3</code>:  </p><pre class="mermaid">sequenceDiagram  participant PS as ProcessorStage  participant DD as DemandDispatcher  participant PD as PartitionDispatcher  participant BS as BatcherStage  alt w only one Batcher    PS->>DD: dispatch(successful_messages_to_forward)    loop dispatch_demand/3 until every batcher's demand is met      DD->>DD: split_events/3      PS->>BS: send(batcher_pid, {:"$gen_consumer", {self(), ref}, deliver_now}, [:noconnect])    end  else w multiple Batcher    PS->>PD: dispatch(successful_messages_to_forward)    loop until every partition is dispatched      PD->>PD: split_events/4      PD->>PD: dispatch_per_partition/1      PD->>PD: maybe_send/3      PS->>BS: send(batcher_pid, {:"$gen_consumer", {self(), ref}, :lists.reverse(events)}, [:noconnect])    end  end  PS--)BS: handle_info({:"$gen_consumer", {processor_pid, ref}, events}, %{type: :producer_consumer} = stage)  BS->>BS: take_pc_events/3</pre><p>Again, the <code>take_pc_events/3</code> function of the <code>BatcherStage</code> process is triggered.  As you can see, the GenStage pipelines work in such a way repeatedly on each stage.  Hence, we know that the Dispatcher will dispatch the events to <code>BatchProcessorStage</code>, and that process receiving the message will invoke <code>consumer_dispatch/6</code> and <code>handle_events/3</code>.  </p><p>Below is the sub-sequence flow of <code>handle_events/3</code> in <code>BatchProcessorStage</code>:  </p><pre class="mermaid">sequenceDiagram  participant BP as BatchProcessorStage  participant A as Acknowledger  participant B as MyBW  BP->>BP: handle_batch/4  BP->>B: handle_batch/4  BP->>A: maybe_handle_failed_messages/3  A->>B: handle_failed/2  BP->>A: ack_messages(successful_messages_to_ack, failed_messages)</pre><p>Now, we basically know how Broadway works with different pipeline options underneath.  However, it’s still far from really understanding it from bottom-up.  When I was working on this post, I came across one interesting <a href="https://dockyard.com/blog/2021/06/24/tuning-broadway-rabbitmq-pipelines-for-latency?utm_medium=email&utm_source=elixir-radar">article</a> about Broadway’s concurrency and how misconfiguration might have great impact on it.  The author did a lot of debugging to figure it out.  I will see if I can see it from the source code level with the observation from this article.  </p>]]></content>
    
    
      
      
    <summary type="html">&lt;h2 id=&quot;GenStage-pipelines&quot;&gt;&lt;a href=&quot;#GenStage-pipelines&quot; class=&quot;headerlink&quot; title=&quot;GenStage pipelines&quot;&gt;&lt;/a&gt;GenStage pipelines&lt;/h2&gt;&lt;p&gt;When o</summary>
      
    
    
    
    <category term="Sword" scheme="http://www.thinkingincrowd.me/categories/Sword/"/>
    
    
    <category term="Elixir" scheme="http://www.thinkingincrowd.me/tags/Elixir/"/>
    
    <category term="Source Reading" scheme="http://www.thinkingincrowd.me/tags/Source-Reading/"/>
    
  </entry>
  
  <entry>
    <title>Broadway Source Reading (Part 3 - Processor)</title>
    <link href="http://www.thinkingincrowd.me/2021/06/19/broadway-source-reading-processor/"/>
    <id>http://www.thinkingincrowd.me/2021/06/19/broadway-source-reading-processor/</id>
    <published>2021-06-19T06:26:44.000Z</published>
    <updated>2022-08-28T08:07:15.454Z</updated>
    
    <content type="html"><![CDATA[<p>Normally, we only need to define the pipeline options for the Producer of any Messaging Middleware, Processor, and implement the <code>handle_message/3</code> callback to use Broadway.  </p><p>The complexity of how the <code>handle_message/3</code> is called, how the messages got acknowledged and how the failed messages handled is all hidden behind.  But that is the part I would like to know by reading the source code.  As we have gone through <a href="http://www.thinkingincrowd.me/2021/05/07/broadway-source-reading-producer/">the Producer part</a>, I bet $10 dollars the questions above should be able to answer after reading the Processor part.  </p><h2 id="Startup-Call-Sequence"><a href="#Startup-Call-Sequence" class="headerlink" title="Startup Call Sequence"></a>Startup Call Sequence</h2><p>With the experience on the startup call sequence of Producer, we can find that the one for Processor is quite similar as below.  One thing to be noted is that, the <code>init</code> function in <code>Subscriber</code> make the consumers to subscribe to all upper stages randomly.</p><pre class="mermaid">sequenceDiagram  participant S as Supervisor  participant P as ProcessorStage  participant SB as Subscriber  participant G as GenStage  S->>P: start_link(args, stage_options)  P->>SB: start_link(ProcessorStage, ..., stage_opts)  SB->>G: start_link(Subscriber, {ProcessorStage, ...}, stage_opts)  G->>G: init({Subsriber, args})  G->>SB: init({ProcessorStage, ...})  SB->>P: init/1  alt w/o Batcher      P-->>SB: {:consumer, state, []}      SB-->>G: {:consumer, state, []}      G->>G: init_consumer(ProcessorStage, opts, state)  else w/ Batcher      P-->>SB: {:producer_consumer, state, dispatcher}      SB-->>G: {:producer_consumer, state, dispatcher}      G->>G: init_producer_consumer(ProcessorStage, opts, state)  end  G->>G: consumer_init_subscribe(subscribe_to, stage)  G->>G: consumer_subscribe/7  G->>G: ask/3</pre><h2 id="GenStage-pipelines"><a href="#GenStage-pipelines" class="headerlink" title="GenStage pipelines"></a>GenStage pipelines</h2><p>Using the simplest Broadway pipeline options without Batcher, the GenStage pipeline should be constructed with only two stages: Producer and Processors.  </p><pre class="mermaid">graph TD  A(Producer) --> B(Processor_1)  A -.-> D(DemandDispatcher)  A --> C(Processor_2)  B -.-> E(Acknowledger)  C -.-> E</pre><p><em>Notes: The communications between the stages are through process message passing, while other interactions between the <code>DemandDispatcher</code>, the <code>Acknowledger</code> and them are through direct method calls.  The Dispatcher and Acknowledger are not part of the GenStage pipelines and so here uses dotted line to indicate their interactions to have clearer separation.</em></p><h2 id="Message-Consuming-as-a-Consumer-w-x2F-o-Batcher"><a href="#Message-Consuming-as-a-Consumer-w-x2F-o-Batcher" class="headerlink" title="Message Consuming as a Consumer (w&#x2F;o Batcher)"></a>Message Consuming as a Consumer (w&#x2F;o Batcher)</h2><p>At the end of the startup call sequence, the processor <code>ask/3</code> for messages immediately after subscribing to the producers.  The process of ProcessorStage sends a <code>:&quot;$gen_producer&quot;</code> message to the producer process it subscribes to.  In the producer’s <code>handle_info/2</code>, it calls <code>dispatcher_callback/3</code> and redirect the call to dispatcher module’s <code>ask/3</code> method that passes the result to <code>handle_dispatcher_result/2</code>.</p><p>There are two branches in the <code>case</code> statement in <code>handle_dispatcher_result/2</code>.  As in this simplest GenStage pipeline, the process receivng the message is <code>:producer</code>, so the path for producer should be taken.  </p><pre class="mermaid">sequenceDiagram  participant P as ProducerStage  participant D as DemandDispatcher  participant PS as ProcessorStage  Note over P: when no events in buffer  P->>P: take_from_buffer(counter, %{stage | dispatcher_state: dispatcher_state})  P->>P: noreply_callback(:handle_demand, [counter, state], stage)  P->>P: handle_demand/2  P->>P: handle_noreply_callback/2  P->>P: dispatch_events/3  P->>D: dispatch/3  alt as Producer      P--)PS: handle_info({:"$gen_consumer", {producer_pid, ref}, events}, %{type: :consumer} = stage)      PS->>PS: consumer_dispatch/6  else as ProducerConsumer      P--)PS: handle_info({:"$gen_consumer", {producer_pid, ref}, events}, %{type: :producer_consumer} = stage)      P->>P: take_pc_events/3  end</pre><p>Below is the call sequence flow of <code>consumer_dispatch/6</code> after <code>:&quot;$gen_consumer&quot;</code> message received in the <code>ProcessorStage</code> as a consumer.  The events are acknowledged immediately because no batchers are specified in this simplest setup.  The <code>successful_messages_to_forward</code> is actually <code>[]</code> because no forwarding is required.  Finally, the consumer <code>ask</code> from the producer again for more events and this kind of asking&#x2F;pulling events happens <strong>recursively</strong> after subscription.</p><pre class="mermaid">sequenceDiagram  participant PS as ProcessorStage  participant A as Acknowledger  participant B as MyBW  loop consumer_dispatch/6 until event batches empty    PS->>PS: handle_events/3    PS->>PS: maybe_prepare_messages/2    PS->>B: prepare_messages/2    PS->>PS: handle_messages/4    PS->>B: handle_message/3    PS->>A: maybe_handle_failed_messages/3    A->>B: handle_failed/2    PS->>A: ack_messages(successful_messages_to_ack, failed_messages)    PS->>PS: dispatch_events(successful_messages_to_forward, _length, stage)    PS->>PS: ask/3  end</pre><h2 id="Failed-Messages-Handling-and-Acknowledging"><a href="#Failed-Messages-Handling-and-Acknowledging" class="headerlink" title="Failed Messages Handling and Acknowledging"></a>Failed Messages Handling and Acknowledging</h2><p>If we look into the <code>ProcessorStage.handle_events/3</code>, it’s clear that each message will be handled by our implemented callback <code>prepare_messages/2</code> and <code>handle_message/3</code> of our <code>MyBW</code> module.  Each message will be separated into the <code>successful_messages</code> and <code>failed_messages</code> categories.</p><p>The <code>failed_messages</code> will first be passed to <code>handle_failed/2</code> of our <code>MyBW</code> module so that we can do whatever necessary, such as saving them in DB or forwarding to another exception queue before the <code>Acknowledger</code> acknowledge them.</p><p>The messages are grouped by each message’s acknowledger to actually <code>ack</code> them.  The message acknowledger is set in the producer that fulfills the scenario mentioned in documentation:</p><blockquote><p>where messages are coming from different producers. Broadway will use this information to correctly identify the acknowledger and pass it among with the messages so you can properly communicate with the source of the data for acknowledgement.</p></blockquote><p>What I do not quite understand is that the messages are not passed through the Map (replacing the <code>true</code> value) but use the Process dict.  I checked the git history and found that it’s the <a href="https://github.com/dashbitco/broadway/pull/32/files">change</a> made by Jose from a branch named <strong>jv-speed-up-ack</strong>.  Is it faster?  Why?</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">defp</span> <span class="title">group_by_acknowledger</span></span>(ackers, messages, key) <span class="keyword">do</span></span><br><span class="line">  <span class="title class_">Enum</span>.reduce(messages, ackers, <span class="keyword">fn</span> %&#123;<span class="symbol">acknowledger:</span> &#123;acknowledger, ack_ref, _&#125;&#125; = msg, acc -&gt;</span><br><span class="line">    ack_info = &#123;acknowledger, ack_ref&#125;</span><br><span class="line">    pdict_key = &#123;ack_info, key&#125;</span><br><span class="line">    <span class="title class_">Process</span>.put(pdict_key, [msg | <span class="title class_">Process</span>.get(pdict_key, [])])</span><br><span class="line">    <span class="title class_">Map</span>.put(acc, ack_info, <span class="literal">true</span>)</span><br><span class="line">  <span class="keyword">end</span>)</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">defp</span> <span class="title">call_ack</span></span>(&#123;&#123;acknowledger, ack_ref&#125; = ack_info, <span class="literal">true</span>&#125;) <span class="keyword">do</span></span><br><span class="line">  successful = <span class="title class_">Process</span>.delete(&#123;ack_info, <span class="symbol">:successful</span>&#125;) || []</span><br><span class="line">  failed = <span class="title class_">Process</span>.delete(&#123;ack_info, <span class="symbol">:failed</span>&#125;) || []</span><br><span class="line">  acknowledger.ack(ack_ref, <span class="title class_">Enum</span>.reverse(successful), <span class="title class_">Enum</span>.reverse(failed))</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><p><em>Update:</em> I posted the <a href="https://elixirforum.com/t/may-anyone-help-to-explain-this-code-by-jose-in-broadway-to-me/40533/6">question</a> in ElixirForum and got Jose’s reply.  Take a look there.  :D</p>]]></content>
    
    
      
      
    <summary type="html">&lt;p&gt;Normally, we only need to define the pipeline options for the Producer of any Messaging Middleware, Processor, and implement the &lt;code&gt;ha</summary>
      
    
    
    
    <category term="Sword" scheme="http://www.thinkingincrowd.me/categories/Sword/"/>
    
    
    <category term="Elixir" scheme="http://www.thinkingincrowd.me/tags/Elixir/"/>
    
    <category term="Source Reading" scheme="http://www.thinkingincrowd.me/tags/Source-Reading/"/>
    
  </entry>
  
  <entry>
    <title>Broadway Source Reading (Part 2 - Producer)</title>
    <link href="http://www.thinkingincrowd.me/2021/05/07/broadway-source-reading-producer/"/>
    <id>http://www.thinkingincrowd.me/2021/05/07/broadway-source-reading-producer/</id>
    <published>2021-05-07T15:45:55.000Z</published>
    <updated>2022-08-28T08:07:15.454Z</updated>
    
    <content type="html"><![CDATA[<p>After having an overview on the <a href="http://www.thinkingincrowd.me/2021/03/30/broadway-source-reading-entry-and-architecture/">Broadway’s architecture</a>, I want to know how the basic Broadway pipeline works with only <code>Producer</code> and <code>Processor</code> options, such as this sample in the official Documentation:</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">defmodule</span> <span class="title">MyBroadway</span></span> <span class="keyword">do</span></span><br><span class="line">  <span class="keyword">use</span> <span class="title class_">Broadway</span></span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">start_link</span></span>(_opts) <span class="keyword">do</span></span><br><span class="line">    <span class="title class_">Broadway</span>.start_link(<span class="title class_">MyBroadway</span>,</span><br><span class="line">      <span class="symbol">name:</span> <span class="title class_">MyBroadwayExample</span>,</span><br><span class="line">      <span class="symbol">producer:</span> [</span><br><span class="line">        <span class="symbol">module:</span> &#123;<span class="title class_">Counter</span>, []&#125;,</span><br><span class="line">        <span class="symbol">concurrency:</span> <span class="number">1</span></span><br><span class="line">      ],</span><br><span class="line">      <span class="symbol">processors:</span> [</span><br><span class="line">        <span class="symbol">default:</span> [<span class="symbol">concurrency:</span> <span class="number">2</span>]</span><br><span class="line">      ]</span><br><span class="line">    )</span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">  ...callbacks...</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><h2 id="Producer"><a href="#Producer" class="headerlink" title="Producer"></a>Producer</h2><p>As the beginning of the Broadway pipeline, the <code>producer</code> module should either keep generating events&#x2F;messages as the data source, or forwarding the queue messages that your Messaging Middleware receives from other external systems to downstream consumers.  </p><p>Broadway has provided officially-supported producers for Messaging Middleware like Amazon SQS, Apache Kafka, Google Cloud Pub&#x2F;Sub and RabbitMQ.  How do these producers work with Broadway?  What I need to know if I want to implement one for other Messaging Middlewares?</p><h3 id="Initialization"><a href="#Initialization" class="headerlink" title="Initialization"></a>Initialization</h3><p>As shown in <a href="http://www.thinkingincrowd.me/2021/03/30/broadway-source-reading-entry-and-architecture/">Part 1 - Entry Point and Architecture</a>, <code>Topology.build_producers_specs/2</code> generates child specs of <code>ProducerStage</code> in the process supervision hierarchy.  The <code>ProducerStage</code> module which <code>use GenStage</code> acts as a wrapper of the producer module you specify in pipeline and delegates function calls to it, such as <code>handle_demand</code>, <code>handle_call</code>, <code>handle_cast</code>, <code>handle_info</code>, <code>prepare_for_draining</code> and <code>terminate</code>.  Its startup call sequence is:  </p><pre class="mermaid">sequenceDiagram  participant S as Supervisor  participant P as ProducerStage  participant G as GenStage  participant M as MyProducer  S->>P: start_link(args, index, opts)  P->>G: start_link(ProducerStage, {args, index}, opts)  G->>G: init({ProducerStage, {args, index}})  G-->>P: init({args, index})  P->>M: init(my_producer_args_in_pipeline)  M-->>G: {:producer, state, options}  G->>G: init_producer(ProducerStage, options, state)</pre><h2 id="Message-Consumption"><a href="#Message-Consumption" class="headerlink" title="Message Consumption"></a>Message Consumption</h2><p>There are two approaches to consume messages in the Messaging Middlewares:  <strong>Pull</strong> and <strong>Push</strong>.  <strong>Pull</strong> is like you ask for tasks from your boss instead of your boss <strong>Push</strong> them to you. (Although in real life, you might have the opposite experience unless your company is using <a href="http://www.thinkingincrowd.me/2015/05/20/Dive-into-Kanban-1-What-is-it/">Kanban</a>.  :D)</p><p>For above mentioned Messaging Middlewares:  </p><ul><li>RabbitMQ is pushed-based.  </li><li>Amazon SQS, and Apache Kafka are pull-based.  </li><li>Google Cloud Pub&#x2F;Sub and can do both.</li></ul><p>Because <code>GenStage</code>‘s philosophy is <strong>Pull</strong>, how do two different message consuming models work with Broadway?  Let’s use the source code of Amazon SQS and RabbitMQ’s Broadway Producer to illustrate below.  </p><h3 id="Pull-Proactive"><a href="#Pull-Proactive" class="headerlink" title="Pull (Proactive)"></a>Pull (Proactive)</h3><pre class="mermaid">graph BT  D(Amazon SQS Producer) -- pull --> C(Amazon SQS Queue)  E(Processors in Broadway) -- pull --> D</pre><p>In the source code of <a href="https://github.com/dashbitco/broadway_sqs/blob/78d32ba2d05ff6e9da3dc89948f91fd9d33299aa/lib/broadway_sqs/producer.ex#L214"><code>broadway_sqs/producer.ex</code></a>, the messages are to receive in the <code>handle_demand</code> callback because it’s the timing when consumers pulls for messages.  </p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable">@impl</span> <span class="literal">true</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">handle_demand</span></span>(incoming_demand, %&#123;<span class="symbol">demand:</span> demand&#125; = state) <span class="keyword">do</span></span><br><span class="line">  handle_receive_messages(%&#123;state | <span class="symbol">demand:</span> demand + incoming_demand&#125;)</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><p><code>handle_receive_messages</code> tries to get messages from SQS to meet the demand from consumers.  If the count of the messages is less than the demand, the producer schedules itself a signal to receive messages again until all demand is met.  </p><p>The messages received in scheduled task are handled in <code>handle_info</code> callback.</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable">@impl</span> <span class="literal">true</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">handle_info</span></span>(<span class="symbol">:receive_messages</span>, state) <span class="keyword">do</span></span><br><span class="line">  handle_receive_messages(%&#123;state | <span class="symbol">receive_timer:</span> <span class="literal">nil</span>&#125;)</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><p>Replying messages in <code>handle_demand</code> callback is not difficult to understand because that is where <code>GenStage</code> passes messages to consumers.  However, why <code>handle_info</code> can be used for the same purpose?  </p><p>In <code>GenStage</code>:</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">## Catch-all messages</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">handle_info</span></span>(msg, %&#123;<span class="symbol">state:</span> state&#125; = stage) <span class="keyword">do</span></span><br><span class="line">  noreply_callback(<span class="symbol">:handle_info</span>, [msg, state], stage)</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">## Shared helpers</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">defp</span> <span class="title">noreply_callback</span></span>(<span class="symbol">:handle_info</span>, [msg, state], %&#123;<span class="symbol">mod:</span> mod&#125; = stage) <span class="keyword">do</span></span><br><span class="line">  <span class="keyword">if</span> function_exported?(mod, <span class="symbol">:handle_info</span>, <span class="number">2</span>) <span class="keyword">do</span></span><br><span class="line">    handle_noreply_callback(mod.handle_info(msg, state), stage)</span><br><span class="line">  <span class="keyword">else</span></span><br><span class="line">    log = <span class="string">&#x27;** Undefined handle_info in ~tp~n** Unhandled message: ~tp~n&#x27;</span></span><br><span class="line">    <span class="symbol">:error_logger</span>.warning_msg(log, [mod, msg])</span><br><span class="line">    &#123;<span class="symbol">:noreply</span>, %&#123;stage | <span class="symbol">state:</span> state&#125;&#125;</span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">defp</span> <span class="title">handle_noreply_callback</span></span>(return, stage) <span class="keyword">do</span></span><br><span class="line">  <span class="keyword">case</span> return <span class="keyword">do</span></span><br><span class="line">    &#123;<span class="symbol">:noreply</span>, events, state&#125; <span class="keyword">when</span> is_list(events) -&gt;</span><br><span class="line">      stage = dispatch_events(events, length(events), %&#123;stage | <span class="symbol">state:</span> state&#125;)</span><br><span class="line">      &#123;<span class="symbol">:noreply</span>, stage&#125;</span><br><span class="line"></span><br><span class="line">    &#123;<span class="symbol">:noreply</span>, events, state, <span class="symbol">:hibernate</span>&#125; <span class="keyword">when</span> is_list(events) -&gt;</span><br><span class="line">      stage = dispatch_events(events, length(events), %&#123;stage | <span class="symbol">state:</span> state&#125;)</span><br><span class="line">      &#123;<span class="symbol">:noreply</span>, stage, <span class="symbol">:hibernate</span>&#125;</span><br><span class="line"></span><br><span class="line">    &#123;<span class="symbol">:stop</span>, reason, state&#125; -&gt;</span><br><span class="line">      &#123;<span class="symbol">:stop</span>, reason, %&#123;stage | <span class="symbol">state:</span> state&#125;&#125;</span><br><span class="line"></span><br><span class="line">    other -&gt;</span><br><span class="line">      &#123;<span class="symbol">:stop</span>, &#123;<span class="symbol">:bad_return_value</span>, other&#125;, stage&#125;</span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><p>And in <code>ProducerStage</code>:</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">handle_info</span></span>(message, state) <span class="keyword">do</span></span><br><span class="line">  %&#123;<span class="symbol">module:</span> module, <span class="symbol">module_state:</span> module_state&#125; = state</span><br><span class="line"></span><br><span class="line">  message</span><br><span class="line">  |&gt; module.handle_info(module_state)</span><br><span class="line">  |&gt; handle_no_reply(state)</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">defp</span> <span class="title">handle_no_reply</span></span>(reply, %&#123;<span class="symbol">transformer:</span> transformer&#125; = state) <span class="keyword">do</span></span><br><span class="line">  <span class="keyword">case</span> reply <span class="keyword">do</span></span><br><span class="line">    &#123;<span class="symbol">:noreply</span>, events, new_module_state&#125; <span class="keyword">when</span> is_list(events) -&gt;</span><br><span class="line">      messages = transform_events(events, transformer)</span><br><span class="line">      &#123;state, messages&#125; = maybe_rate_limit_and_buffer_messages(state, messages)</span><br><span class="line">      &#123;<span class="symbol">:noreply</span>, messages, %&#123;state | <span class="symbol">module_state:</span> new_module_state&#125;&#125;</span><br><span class="line"></span><br><span class="line">    &#123;<span class="symbol">:noreply</span>, events, new_module_state, <span class="symbol">:hibernate</span>&#125; -&gt;</span><br><span class="line">      messages = transform_events(events, transformer)</span><br><span class="line">      &#123;state, messages&#125; = maybe_rate_limit_and_buffer_messages(state, messages)</span><br><span class="line">      &#123;<span class="symbol">:noreply</span>, messages, %&#123;state | <span class="symbol">module_state:</span> new_module_state&#125;, <span class="symbol">:hibernate</span>&#125;</span><br><span class="line"></span><br><span class="line">    &#123;<span class="symbol">:stop</span>, reason, new_module_state&#125; -&gt;</span><br><span class="line">      &#123;<span class="symbol">:stop</span>, reason, %&#123;state | <span class="symbol">module_state:</span> new_module_state&#125;&#125;</span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><p>So the call sequence flow is:</p><pre class="mermaid">sequenceDiagram  participant P as ProducerStage  participant G as GenStage  participant M as MyProducer  G->>G: handle_info(msg, %{state: state} = stage)  G->>G: noreply_callback(:handle_info, [msg, state], stage)  G->>P: handle_info(message, %{module: module, module_state: module_state} = state)  P->>M: handle_info(message, module_state)  M-->>P: {:noreply, events, new_module_state}  P->>P: handle_no_reply(reply, state)  P-->>G: {:noreply, messages, %{state | module_state: new_module_state}}  G->>G: handle_noreply_callback(return, stage)  G->>G: dispatch_events(events, length(events), %{stage | state: state})</pre><p>As a result, the events returned from <code>handle_info</code> in our producer module will be dispatched to the consumers at the end.  </p><h3 id="Push-Passive"><a href="#Push-Passive" class="headerlink" title="Push (Passive)"></a>Push (Passive)</h3><pre class="mermaid">graph TD  A(RabbitMQ Queue) -- push --> B(RabbitMQ Producer)  C(Processors in Broadway) -- pull --> B</pre><p>According to this simple flow diagram, messages are pushed to the queue consumers if the queue has messages.  However, it’s possible that no broadway consumers ask for any message at that moment.  There are also times that the broadway consumers ask for messages but none have been pushed from queues.  How does the design fullfill these different scenarios?  </p><p>According to the source code of <a href="https://github.com/dashbitco/broadway_rabbitmq/blob/ddd58d468d8d47b0487aea6a0f170cd3f82f03b8/lib/broadway_rabbitmq/producer.ex#L466">RabbitMQ Broadway Producer</a>, <code>handle_demand</code> does nothing.  </p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable">@impl</span> <span class="literal">true</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">handle_demand</span></span>(_incoming_demand, state) <span class="keyword">do</span></span><br><span class="line">  &#123;<span class="symbol">:noreply</span>, [], state&#125;</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><p>As a result, demand request from consumers is ingored by the producer and the messages are always pushed from the producers.  In order to control Back-pressure for the consumers, option <code>:prefetch_count</code> is used in the producer to control the message volume.  The flow diagram should be this instead:  </p><pre class="mermaid">graph TD  A(RabbitMQ Queue) -- push --> B(RabbitMQ Producer)  B -- push --> C(Processors in Broadway)</pre><p>The underline logic is:  </p><ul><li><p>The Broadway RabbitMQ producer uses <code>:amqp</code> which uses <code>:amqp_client</code> to <a href="https://github.com/dashbitco/broadway_rabbitmq/blob/ddd58d468d8d47b0487aea6a0f170cd3f82f03b8/lib/broadway_rabbitmq/producer.ex#L663">connect</a> to RabbitMQ, it calls the client’s <a href="https://github.com/pma/amqp/blob/ddf3d1fae8a40a5e2edf4fa7afa3ef33eebe85f3/lib/amqp/basic.ex#L375">consume</a> method to register its process as a queue consumer.  </p></li><li><p>Every time a message is pushed from the queue, the producer’s process will receive message with structure <a href="https://github.com/pma/amqp/blob/ddf3d1fae8a40a5e2edf4fa7afa3ef33eebe85f3/lib/amqp/basic.ex#L331"><code>&#123;:basic_deliver, payload, meta&#125;</code></a>.  </p></li><li><p>In the same way we explored above, the <code>handle_info</code> method of RabbitMQ producer returns the message for <code>GenStage</code> to dispatch.</p></li></ul><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">handle_info</span></span>(&#123;<span class="symbol">:basic_deliver</span>, payload, meta&#125;, state) <span class="keyword">do</span></span><br><span class="line">  %&#123;<span class="symbol">channel:</span> channel, <span class="symbol">client:</span> client, <span class="symbol">config:</span> config&#125; = state</span><br><span class="line">  %&#123;<span class="symbol">delivery_tag:</span> tag, <span class="symbol">redelivered:</span> redelivered&#125; = meta</span><br><span class="line"></span><br><span class="line">  <span class="comment"># Omitted some code for acknowledger here.</span></span><br><span class="line"></span><br><span class="line">  metadata =</span><br><span class="line">    meta</span><br><span class="line">    |&gt; <span class="title class_">Map</span>.take(config[<span class="symbol">:metadata</span>])</span><br><span class="line">    |&gt; <span class="title class_">Map</span>.put(<span class="symbol">:amqp_channel</span>, channel)</span><br><span class="line"></span><br><span class="line">  message = %<span class="title class_">Message</span>&#123;</span><br><span class="line">    <span class="symbol">data:</span> payload,</span><br><span class="line">    <span class="symbol">metadata:</span> metadata,</span><br><span class="line">    <span class="symbol">acknowledger:</span> acknowledger</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  &#123;<span class="symbol">:noreply</span>, [message], state&#125;</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><p>Now we basically know how the producer receives and dispatches messages, we can move forward to the processors next.  </p>]]></content>
    
    
      
      
    <summary type="html">&lt;p&gt;After having an overview on the &lt;a href=&quot;http://www.thinkingincrowd.me/2021/03/30/broadway-source-reading-entry-and-architecture/&quot;&gt;Broadw</summary>
      
    
    
    
    <category term="Sword" scheme="http://www.thinkingincrowd.me/categories/Sword/"/>
    
    
    <category term="Elixir" scheme="http://www.thinkingincrowd.me/tags/Elixir/"/>
    
    <category term="Source Reading" scheme="http://www.thinkingincrowd.me/tags/Source-Reading/"/>
    
  </entry>
  
  <entry>
    <title>Broadway Source Reading (Part 1 - Entry Point and Architecture)</title>
    <link href="http://www.thinkingincrowd.me/2021/03/30/broadway-source-reading-entry-and-architecture/"/>
    <id>http://www.thinkingincrowd.me/2021/03/30/broadway-source-reading-entry-and-architecture/</id>
    <published>2021-03-30T13:26:58.000Z</published>
    <updated>2022-08-28T08:07:15.454Z</updated>
    
    <content type="html"><![CDATA[<p>I have learned Elixir for a while and always want to see if I can start reading any opensource project to learn from.  </p><p>Two reasons to pick <a href="https://hexdocs.pm/broadway/Broadway.html">Broadway</a> as a start:  </p><ul><li>Its code base is quite small and has 18 modules in total.  </li><li>The project in my company uses messaging components a lot.</li></ul><p>Hence, reading it has much benefit on how to design a message processing tool with well-reasoned architecture.  Maybe, after this, I can try writing the right producer for the messaging component we use and rewrite the project in Elixir as well. :D</p><h2 id="Entry-Point"><a href="#Entry-Point" class="headerlink" title="Entry Point"></a>Entry Point</h2><p>According to the Documentation:</p><blockquote><p>In order to use Broadway, you need to:</p><ol><li>Define your pipeline configuration</li><li>Define a module implementing the Broadway behaviour</li></ol></blockquote><p>Obviously, the first source file I checked out is <code>broadway.ex</code>.  It does not have much logic there except the necessary behaviors and functions to get&#x2F;update rate limiting.</p><p>The entry point is the <code>start_link</code> function which in turn calls <code>Topology.start_link(module, opts)</code> after option validation.</p><h2 id="Architecture-Diagram"><a href="#Architecture-Diagram" class="headerlink" title="Architecture Diagram"></a>Architecture Diagram</h2><p>In order to know a codebase well, I tend to learn its architecture before diving into detail.  </p><h3 id="Sequence-Diagram"><a href="#Sequence-Diagram" class="headerlink" title="Sequence Diagram"></a>Sequence Diagram</h3><p>Assuming our broadway module named <code>MyBW</code>:  </p><pre class="mermaid">sequenceDiagram  participant M as MyBW  participant B as Broadway  participant T as Topology  participant S as Supervisor  M->>B: start_link(MyBW, pipeline_opts)  B->>T: start_link(MyBW, pipeline_opts)  rect rgba(0, 0, 255, .1)  Note over T: init({MyBW, pipeline_opts})  T->>T: {child_specs, opts} = prepare_for_start(MyBW, pipeline_opts)  rect rgba(0, 0, 255, .2)  Note over T: start_supervisor(child_specs, %{module: MyBW} = config, pipeline_opts)  T->>T: {producers_names, producers_specs} = build_producers_specs(config, opts)  T->>T: {processors_names, processors_specs} = build_processors_specs(config, producers_names)  T->>T: build_rate_limiter_spec(config, producers_names)  T->>T: build_processor_supervisor_spec(config, processors_specs)  T->>T: build_batchers_supervisor_and_terminator_specs(config, producers_names, processors_names)  T->>S: start_link(all_child_specs)  end  S-->>B: %{supervisor_pid, terminator, name}  B-->>M:   end</pre><h3 id="Process-Supervision-Hierarchy"><a href="#Process-Supervision-Hierarchy" class="headerlink" title="Process Supervision Hierarchy"></a>Process Supervision Hierarchy</h3><pre class="mermaid">graph TD  A(Broadway.Topology) -.-> B(PrepareForProducer)  A ---> C(MyBW.Supervisor:rest_for_one)  C -.-> D(RateLimiter)  C --> E(MyBW.ProducerSupervisor:one_for_one) & F(MyBW.ProcessorSupervisor:one_for_all)  E -- ProducerStage --> G1(MyBW.Producer_1) & G2(MyBW.Producer_2)  F -- ProcessorStage --> H1(MyBW.Processor_key_1) & H2(MyBW.Processor_key_2)  C -. With Batcher .-> J(MyBW.BatchersSupervisor:one_for_one)  J --> K(MyBW.BatcherSupervisor_key1:rest_for_one) & P(Terminator)  K -- BatcherStage --> L(MyBW.Batcher_key1)  K --> M(MyBW.BatchProcessorSupervisor_key1:one_for_all)  M -- BatchProcessorStage --> M1(MyBW.BatchProcessor_key1_1) & M2(MyBW.BatchProcessor_key1_2)  C -. Without Batcher .-> P(Terminator)</pre><ul><li><p>The dashed line means that the component is optional.  </p></li><li><p>The text on the line mainly shows what module is started for the process, except the “With Batcher” and “Without Batcher”.  </p></li><li><p>The supervision strategy is next to the name of Supervisor.</p></li></ul><p>Most of the things make sense for me now but I still have one question:</p><p>Why <code>ProcessorSupervisor</code> and <code>BatchProcessorSupervisor</code> use <code>:one_for_all</code> instead of <code>:one_for_one</code>?  The Processors need to all live or crash?  I think I will get the answer after reading the processors part.</p>]]></content>
    
    
      
      
    <summary type="html">&lt;p&gt;I have learned Elixir for a while and always want to see if I can start reading any opensource project to learn from.  &lt;/p&gt;
&lt;p&gt;Two reason</summary>
      
    
    
    
    <category term="Sword" scheme="http://www.thinkingincrowd.me/categories/Sword/"/>
    
    
    <category term="Elixir" scheme="http://www.thinkingincrowd.me/tags/Elixir/"/>
    
    <category term="Source Reading" scheme="http://www.thinkingincrowd.me/tags/Source-Reading/"/>
    
  </entry>
  
  <entry>
    <title>你觉得自己是旁观者还是受害者？</title>
    <link href="http://www.thinkingincrowd.me/2020/11/15/are-you-a-bystander-or-victim/"/>
    <id>http://www.thinkingincrowd.me/2020/11/15/are-you-a-bystander-or-victim/</id>
    <published>2020-11-15T04:00:21.000Z</published>
    <updated>2022-08-28T08:07:15.454Z</updated>
    
    <content type="html"><![CDATA[<p>公司最近安排了一个关于敏捷领导力的培训。培训前，我对它其实没抱太高的期望。不是说我不喜欢这个话题，而是已经兴奋不起来。关于敏捷，以前我很热衷于看板理念的时候，可是能花好几千块钱，飞去北京，深圳上课的人。当年我还写了好几篇关于看板的文章，有兴趣的可以去看看：</p><ul><li><a href="http://www.thinkingincrowd.me/2015/05/20/Dive-into-Kanban-1-What-is-it/">Dive into Kanban (1) - What is it</a>  </li><li><a href="http://www.thinkingincrowd.me/2015/05/30/Dive-into-Kanban-2-Visualizing-Process/">Dive into Kanban (2) - Visualizing Process</a>  </li><li><a href="http://www.thinkingincrowd.me/2015/05/31/Dive-into-Kanban-3-How-Kanban-address-the-estimation-headache/">Dive into Kanban (3) - How Kanban address the estimation headache</a>  </li><li><a href="http://www.thinkingincrowd.me/2015/06/05/Dive-into-Kanban-4-Variability-and-Flow-Interruption/">Dive into Kanban (4) - Variability and Flow Interruption</a>  </li><li><a href="http://www.thinkingincrowd.me/2015/07/23/Dive-into-Kanban-5-Difficulty-and-Resisted-Opinions-on-Adoption/">Dive into Kanban (5) - Difficulty and Resisted Opinions on Adoption</a>  </li><li><a href="http://www.thinkingincrowd.me/2015/10/08/Dive-into-Kanban-6-Scrum-vs-Kanban/">Dive into Kanban (6) - Scrum vs Kanban</a></li></ul><p>培训过后，我却出乎意外的满意。不是因为增加了的那些关于敏捷的知识，而是老师的观念，让我看到了当初自己对敏捷的一些看法，也与我的内心产生共鸣。</p><p>培训前，老师让我们自己填了一份自测表单，同时让我们找 15 个同事朋友填他们对我们的评价。大家给我的评价大概是这样的：</p><ul><li>有亲和力，善于沟通，乐于听取意见。</li><li>踏实可靠，自律，有学习能力，且乐于分享</li><li>有时太过顺从或照顾他人，应该更强势或严厉，坚持立场</li></ul><p>从评价结果来看，自评和他评很接近。可以看出，我还是基本活出自己的本我（起码是善的那方面），表里基本一致。评测中很多人无脑给了 10 分，虽然让我知道那些曾经的战友，还是一如既往的好友。</p><p>在培训中，老师带我们玩了一个拍排球的游戏：整个团队，每个人拍球不超过 3 次，保证 200 次拍球不落地。在整个游戏当中，我经历以下几个阶段，可以说非常准确地把上述评价的点给体现了出来：</p><ul><li>一开始的时候，我没怎么参与，先观察着有没有人挺身而出。  </li><li>看了一段时间后，我发现大家拍球的效果不好，我觉得凭我的运动能力，和对游戏的观察，我应该出手。  </li><li>我参与了一段时间，提出一些应该如何调整的建议。  </li><li>团队中其他人并没采纳我的意见，我觉得他们的也未尝不可，然后就退居二线守护意外流出的球。</li></ul><p>你们觉得这是不是和评测结果挺匹配的？</p><p><strong>所谓领导力，其实就是让事情改变和发生的能力。</strong></p><p>每个人都有领导力，差别在于大小范围，产生影响的效果，和手段优劣而已。审视自己，在推进事情方面，有时候确实不够主动和强势。除了我的性格本来就不够强势外，另一个原因，则是和培训中老师分享的让我产生共鸣的观点有关：<strong>问题与我同在</strong>。</p><p>很多情况下，我们都在指出身边的人和事，存在什么问题，好像这些问题都是其他人导致的，与我无关。问题与我是分开的。</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">+-----+</span><br><span class="line">| 问题 |   我</span><br><span class="line">+-----+</span><br></pre></td></tr></table></figure><p>其实，真正的情况是我是问题的一部分：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">+-----------+</span><br><span class="line">| 问题    我 |</span><br><span class="line">+-----------+</span><br></pre></td></tr></table></figure><p>把自己和问题分开看待，要么成为<strong>旁观者</strong>，要么成为<strong>受害者</strong>。拥有这两种心态，都不利于问题的解决，都没法很好发挥自己的领导力，影响力。<strong>要改变自己能改变的事情</strong>。</p><p>拿公司推行敏捷来说，很多人抱怨公司或者团队的行为只是”声称敏捷“，我怎么样才能够让团队变成”真正的敏捷“？先放下”如何才是真正的敏捷“这个问题，然后问问自己：”我做了什么让这个团队更敏捷的事了吗？”</p><p>拿亲密关系的相处来说，很多人抱怨：“<strong>明明是 Ta 的错，为什么要我改？</strong>” 正如那个经典的笑话：老婆经常唠叨老公不待家里，而老公却说，我不想待家是因为老婆太唠叨。所以说，你做了什么改善这段关系的事情了吗？</p><p>虽然我没信上帝，但是这段话还是挺有哲理的：</p><p><strong>Serenity Prayer (宁静祷文)</strong></p><blockquote><p>God, grant me the serenity to accept the things I cannot change,<br>courage to change the things I can,<br>and wisdom to know the difference.</p></blockquote><blockquote><p>亲爱的上帝，请赐给我雅量从容的接受不可改变的事，<br>赐给我勇气去改变应该改变的事，<br>并赐给我智慧去分辨什么是可以改变的，什么是不可以改变的。</p></blockquote>]]></content>
    
    
      
      
    <summary type="html">&lt;p&gt;公司最近安排了一个关于敏捷领导力的培训。培训前，我对它其实没抱太高的期望。不是说我不喜欢这个话题，而是已经兴奋不起来。关于敏捷，以前我很热衷于看板理念的时候，可是能花好几千块钱，飞去北京，深圳上课的人。当年我还写了好几篇关于看板的文章，有兴趣的可以去看看：&lt;/p&gt;
&lt;ul&gt;</summary>
      
    
    
    
    <category term="Think" scheme="http://www.thinkingincrowd.me/categories/Think/"/>
    
    
    <category term="Change" scheme="http://www.thinkingincrowd.me/tags/Change/"/>
    
    <category term="Kanban" scheme="http://www.thinkingincrowd.me/tags/Kanban/"/>
    
    <category term="Leadership" scheme="http://www.thinkingincrowd.me/tags/Leadership/"/>
    
  </entry>
  
  <entry>
    <title>Message communication between supervisor and child processes in Elixir</title>
    <link href="http://www.thinkingincrowd.me/2020/10/27/message-communication-between-supervisor-and-child-processes-in-elixir/"/>
    <id>http://www.thinkingincrowd.me/2020/10/27/message-communication-between-supervisor-and-child-processes-in-elixir/</id>
    <published>2020-10-27T12:40:00.000Z</published>
    <updated>2022-08-28T08:07:15.453Z</updated>
    
    <content type="html"><![CDATA[<p>Process is one of the core concept in Elixir&#x2F;Erlang.  Sending &amp; receiving messages between them is crucial.  So how should the communication be done in the spider project I introduced in <a href="http://www.thinkingincrowd.me/2020/09/06/multi-level-supervision-in-elixir/">last blog</a>?</p><p>Let us take a look on different types of scenarios below.</p><h2 id="Messages-for-itself"><a href="#Messages-for-itself" class="headerlink" title="Messages for itself"></a>Messages for itself</h2><p>The <code>Spider.Fetcher</code> only has one job.  It asks one URL from <code>Spider.Manager</code>, crawls the page content and sends back the result.</p><p>This job should be invoked regularly based on a configured interval after initialization and crawling for one URL.  Hence, the <code>Spider.Fetcher</code> should send message to itself at this two points as you can see below.</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">init</span></span>(state = &#123;spider_config, index, manager_pid&#125;) <span class="keyword">do</span></span><br><span class="line">  next_move(spider_config)</span><br><span class="line"></span><br><span class="line">  &#123;<span class="symbol">:ok</span>, state&#125;</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">handle_info</span></span>(<span class="symbol">:crawl</span>, state = &#123;spider_config, _index, manager_pid&#125;) <span class="keyword">do</span></span><br><span class="line">  url = <span class="title class_">GenServer</span>.call(manager_pid, <span class="symbol">:next_url</span>)</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> url != <span class="literal">nil</span> <span class="keyword">do</span></span><br><span class="line">    result = crawl(spider_config, url)</span><br><span class="line">    <span class="title class_">GenServer</span>.cast(manager_pid, &#123;<span class="symbol">:result</span>, url, result&#125;)</span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">  next_move(spider_config)</span><br><span class="line"></span><br><span class="line">  &#123;<span class="symbol">:noreply</span>, state&#125;</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">defp</span> <span class="title">next_move</span></span>(spider_config) <span class="keyword">do</span></span><br><span class="line">  <span class="title class_">Process</span>.send_after(self(), <span class="symbol">:crawl</span>, spider_config.crawl_interval)</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><h2 id="Normal-Messages-between-Parent-and-Child"><a href="#Normal-Messages-between-Parent-and-Child" class="headerlink" title="Normal Messages between Parent and Child"></a>Normal Messages between Parent and Child</h2><p>As we can see in the code above, <code>Spider.Fetcher</code> sends two different types of message to its <code>Spider.Manager</code> process.  </p><ul><li><code>:next_url</code> for asking next url to crawl.  </li><li><code>:result</code> for sending back the crawled result.</li></ul><p>The <code>manager_pid</code> is captured in its state because leaking the process naming logic here and use Name Registration to look it up again are unnecessary.</p><p>For the same reason, the process ids of the child processes are captured during creation.  Messages can be sent through them if I need to collect child processes’ status or start&#x2F;stop them.</p><p>For example, in <code>SpiderEngine.Manager</code>, the <code>all_engines</code> is a map that uses spider name as key, spider process id as value.  </p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">handle_info</span></span>(<span class="symbol">:kickoff</span>, _) <span class="keyword">do</span></span><br><span class="line">  all_spiders = <span class="title class_">SpiderStorage</span>.get_all_spiders()</span><br><span class="line"></span><br><span class="line">  engines =</span><br><span class="line">    all_spiders</span><br><span class="line">    |&gt; <span class="title class_">Enum</span>.into(%&#123;&#125;, <span class="keyword">fn</span> spider_config -&gt;</span><br><span class="line">        start_spider(spider_config, %&#123;&#125;)</span><br><span class="line">      <span class="keyword">end</span>)</span><br><span class="line"></span><br><span class="line">  &#123;<span class="symbol">:noreply</span>, %&#123;<span class="symbol">all_engines:</span> engines&#125;&#125;</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><h2 id="Message-for-Parent-Supervisor-Termination"><a href="#Message-for-Parent-Supervisor-Termination" class="headerlink" title="Message for Parent Supervisor Termination"></a>Message for Parent Supervisor Termination</h2><h3 id="Why-the-case"><a href="#Why-the-case" class="headerlink" title="Why the case"></a>Why the case</h3><p>It might be counter-intuitive to ask the child process to terminate the whole supervisor, but it’s reasonable if you put it under a real scenario.</p><p>During spider initialization, if it encounters unrecoverable issues, say unreachable target website or receiving 401 status code because it’s blocked, you might prefer to take down the spider instead of keep trying.</p><h3 id="Which-direction"><a href="#Which-direction" class="headerlink" title="Which direction"></a>Which direction</h3><p>In my case, the <code>Spider.Manager.Facebook</code> makes the decision on bringing down the whole supervision tree below <code>Spider.Facebook</code>.  But how?  Should it directly sends signal to <code>Spider.Facebook</code> and ask it to exit?  Or go through the higher ladder by asking the <code>SpiderEngine.Manager</code> to terminate it?</p><p><strong>TLDR</strong>.  Never call <code>Process.exit</code> with parent process id in child process.  Use <code>Supervisor.stop/3</code> or <code>DynamicSupervisor.terminate_child/2</code> instead.</p><h3 id="Process-exit"><a href="#Process-exit" class="headerlink" title="Process.exit"></a>Process.exit</h3><p>I roughly remember there is one API called <code>Process.exit/2</code>, and so wrote some modules to test.</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">defmodule</span> <span class="title">Test.Root</span></span> <span class="keyword">do</span></span><br><span class="line">  <span class="keyword">use</span> <span class="title class_">Supervisor</span></span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">start_link</span></span>(_) <span class="keyword">do</span></span><br><span class="line">    <span class="title class_">Supervisor</span>.start_link(__MODULE__, <span class="symbol">:no_args</span>, <span class="symbol">name:</span> __MODULE__)</span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">init</span></span>(<span class="symbol">:no_args</span>) <span class="keyword">do</span></span><br><span class="line">    <span class="comment"># Code of Test.Manager is not attached.</span></span><br><span class="line">    <span class="comment"># Added it here just to ensure Test.Root has more than one child. </span></span><br><span class="line">    children = [</span><br><span class="line">      <span class="title class_">Test</span>.<span class="title class_">Manager</span>,</span><br><span class="line">      <span class="title class_">Test</span>.<span class="title class_">Supervisor</span></span><br><span class="line">    ]</span><br><span class="line"></span><br><span class="line">    <span class="comment"># So that when Test.Supervisor terminates, it does not affect Test.Root or others</span></span><br><span class="line">    opts = [<span class="symbol">strategy:</span> <span class="symbol">:one_for_one</span>]</span><br><span class="line">    <span class="title class_">Supervisor</span>.init(children, opts)</span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">defmodule</span> <span class="title">Test.Supervisor</span></span> <span class="keyword">do</span></span><br><span class="line">  <span class="comment"># When it&#x27;s terminated normally, it will not be restarted again</span></span><br><span class="line">  <span class="keyword">use</span> <span class="title class_">DynamicSupervisor</span>, <span class="symbol">restart:</span> <span class="symbol">:transient</span></span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">start_link</span></span>(_) <span class="keyword">do</span></span><br><span class="line">    <span class="title class_">DynamicSupervisor</span>.start_link(__MODULE__, <span class="symbol">:no_args</span>, <span class="symbol">name:</span> __MODULE__)</span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">init</span></span>(<span class="symbol">:no_args</span>) <span class="keyword">do</span></span><br><span class="line">    <span class="title class_">DynamicSupervisor</span>.init(<span class="symbol">strategy:</span> <span class="symbol">:one_for_one</span>)</span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">start_worker</span></span>(id) <span class="keyword">do</span></span><br><span class="line">    spec = %&#123;</span><br><span class="line">      <span class="symbol">id:</span> id,</span><br><span class="line">      <span class="symbol">start:</span> &#123;<span class="title class_">Test</span>.<span class="title class_">Worker</span>, <span class="symbol">:start_link</span>, [id]&#125;,</span><br><span class="line">      <span class="symbol">restart:</span> <span class="symbol">:transient</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title class_">DynamicSupervisor</span>.start_child(<span class="title class_">Test</span>.<span class="title class_">Supervisor</span>, spec)</span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">defmodule</span> <span class="title">Test.Worker</span></span> <span class="keyword">do</span></span><br><span class="line">  <span class="keyword">use</span> <span class="title class_">GenServer</span></span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">down</span></span>(self_pid, sup_pid) <span class="keyword">do</span></span><br><span class="line">    <span class="title class_">GenServer</span>.call(self_pid, &#123;<span class="symbol">:down</span>, sup_pid&#125;)</span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">start_link</span></span>(id) <span class="keyword">do</span></span><br><span class="line">    <span class="title class_">GenServer</span>.start_link(__MODULE__, <span class="symbol">:no_args</span>, <span class="symbol">name:</span> <span class="symbol">:<span class="string">&quot;<span class="subst">#&#123;__MODULE__&#125;</span>_<span class="subst">#&#123;id&#125;</span>&quot;</span></span>)</span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">init</span></span>(<span class="symbol">:no_args</span>) <span class="keyword">do</span></span><br><span class="line">    &#123;<span class="symbol">:ok</span>, %&#123; &#125;&#125;</span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">handle_call</span></span>(&#123;<span class="symbol">:down</span>, sup_pid&#125;, _from, state) <span class="keyword">do</span></span><br><span class="line">    &#123;<span class="symbol">:reply</span>, <span class="title class_">Process</span>.exit(sup_pid, <span class="symbol">:normal</span>), state&#125;</span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><p>Here is the testing code and result.</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">iex(<span class="number">1</span>)&gt; [root, mgr, sup] = [<span class="title class_">Test</span>.<span class="title class_">Root</span>, <span class="title class_">Test</span>.<span class="title class_">Manager</span>, <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>] |&gt; <span class="title class_">Enum</span>.map(&amp;<span class="title class_">Process</span>.whereis/<span class="number">1</span>)</span><br><span class="line">[<span class="comment">#PID&lt;0.394.0&gt;, #PID&lt;0.395.0&gt;, #PID&lt;0.396.0&gt;]</span></span><br><span class="line">iex(<span class="number">2</span>)&gt; &#123;<span class="symbol">:ok</span>, child_a&#125; = <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>.start_worker(<span class="string">&quot;A&quot;</span>)</span><br><span class="line">&#123;<span class="symbol">:ok</span>, <span class="comment">#PID&lt;0.407.0&gt;&#125;</span></span><br><span class="line">iex(<span class="number">3</span>)&gt; &#123;<span class="symbol">:ok</span>, child_b&#125; = <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>.start_worker(<span class="string">&quot;B&quot;</span>)</span><br><span class="line">&#123;<span class="symbol">:ok</span>, <span class="comment">#PID&lt;0.405.0&gt;&#125;</span></span><br><span class="line">iex(<span class="number">4</span>)&gt; <span class="title class_">Test</span>.<span class="title class_">Worker</span>.down(child_a, sup)</span><br><span class="line"><span class="literal">true</span></span><br><span class="line">iex(<span class="number">5</span>)&gt; [root, mgr, sup, child_a, child_b] |&gt; <span class="title class_">Enum</span>.map(&amp;<span class="title class_">Process</span>.alive?/<span class="number">1</span>)</span><br><span class="line">[<span class="literal">true</span>, <span class="literal">true</span>, <span class="literal">true</span>, <span class="literal">true</span>, <span class="literal">true</span>]</span><br><span class="line">iex(<span class="number">6</span>)&gt; <span class="title class_">Supervisor</span>.which_children(root)</span><br><span class="line">[</span><br><span class="line">  &#123;<span class="title class_">Test</span>.<span class="title class_">Supervisor</span>, <span class="comment">#PID&lt;0.396.0&gt;, :supervisor, [Test.Supervisor]&#125;,</span></span><br><span class="line">  &#123;<span class="title class_">Test</span>.<span class="title class_">Manager</span>, <span class="comment">#PID&lt;0.395.0&gt;, :worker, [Test.Manager]&#125;</span></span><br><span class="line">]</span><br><span class="line">iex(<span class="number">7</span>)&gt; <span class="title class_">Supervisor</span>.which_children(sup)</span><br><span class="line">[&#123;<span class="symbol">:undefined</span>, <span class="comment">#PID&lt;0.405.0&gt;, :worker, [Test.Worker]&#125;]</span></span><br></pre></td></tr></table></figure><p>In step 5, it shows that all the processes created are alived.  But shouldn’t the <code>Test.Supervisor</code> and two of its child processes be terminated?  When checking on the children of <code>root</code> and <code>sup</code> processes in step 6 &amp; 7:</p><ol><li>Process for <code>sup</code> and <code>child_a</code> are still alive.</li><li>Process <code>child_a</code> is not under supervision of <code>Test.Supervisor</code>.</li></ol><p>After going through the documentation for API <code>Process.exit/2</code> more carefully and learning what <strong>trapping exits</strong> means, I finally the reasons behind.</p><ol><li>Supervisor traps exits.  Exit signal is transformed to <code>&#123;:EXIT, from, :normal&#125;</code> message.</li><li><code>Process.exit(supp, :normal)</code> from <code>child_a</code> makes <code>Test.Supervisor</code> think that <code>child_a</code> is terminated.</li><li><code>Test.Supervisor</code> removes <code>child_a</code> from its supervision tree even though the <code>child_a</code> process is actually alive.</li></ol><p>According to the API doc, using <code>:kill</code> as exit reason can unconditionally kill the process.  Does it work in this case?</p><p>If I changed the handling for <code>:down</code> message in <code>Test.Worker</code> as below:</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">handle_call</span></span>(&#123;<span class="symbol">:down</span>, sup_pid&#125;, _from, state) <span class="keyword">do</span></span><br><span class="line">  &#123;<span class="symbol">:reply</span>, <span class="title class_">Process</span>.exit(sup_pid, <span class="symbol">:kill</span>), state&#125;</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><p>The test result will be:</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">iex(<span class="number">1</span>)&gt; [root, mgr, sup] = [<span class="title class_">Test</span>.<span class="title class_">Root</span>, <span class="title class_">Test</span>.<span class="title class_">Manager</span>, <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>] |&gt; <span class="title class_">Enum</span>.map(&amp;<span class="title class_">Process</span>.whereis/<span class="number">1</span>)</span><br><span class="line">[<span class="comment">#PID&lt;0.400.0&gt;, #PID&lt;0.401.0&gt;, #PID&lt;0.402.0&gt;]</span></span><br><span class="line">iex(<span class="number">2</span>)&gt; &#123;<span class="symbol">:ok</span>, child_a&#125; = <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>.start_worker(<span class="string">&quot;A&quot;</span>)</span><br><span class="line">&#123;<span class="symbol">:ok</span>, <span class="comment">#PID&lt;0.419.0&gt;&#125;</span></span><br><span class="line">iex(<span class="number">3</span>)&gt; &#123;<span class="symbol">:ok</span>, child_b&#125; = <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>.start_worker(<span class="string">&quot;B&quot;</span>)</span><br><span class="line">&#123;<span class="symbol">:ok</span>, <span class="comment">#PID&lt;0.421.0&gt;&#125;</span></span><br><span class="line">iex(<span class="number">4</span>)&gt; <span class="title class_">Test</span>.<span class="title class_">Worker</span>.down(child_a, sup)</span><br><span class="line"><span class="literal">true</span></span><br><span class="line">iex(<span class="number">5</span>)&gt; [root, mgr, sup, child_a, child_b] |&gt; <span class="title class_">Enum</span>.map(&amp;<span class="title class_">Process</span>.alive?/<span class="number">1</span>)</span><br><span class="line">[<span class="literal">true</span>, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">false</span>]</span><br><span class="line">iex(<span class="number">7</span>)&gt; <span class="title class_">Supervisor</span>.which_children(root)</span><br><span class="line">[</span><br><span class="line">  &#123;<span class="title class_">Test</span>.<span class="title class_">Supervisor</span>, <span class="comment">#PID&lt;0.423.0&gt;, :supervisor, [Test.Supervisor]&#125;,</span></span><br><span class="line">  &#123;<span class="title class_">Test</span>.<span class="title class_">Manager</span>, <span class="comment">#PID&lt;0.401.0&gt;, :worker, [Test.Manager]&#125;</span></span><br><span class="line">]</span><br></pre></td></tr></table></figure><p>In step 5, the supervision tree of <code>sup</code> is terminated.  However, when I checked the children of <code>root</code>, there is a new process created for <code>Test.Supervisor</code> because it is restarted as it does not exit normally.</p><h3 id="Impact-of-Restart-Strategy"><a href="#Impact-of-Restart-Strategy" class="headerlink" title="Impact of Restart Strategy"></a>Impact of Restart Strategy</h3><p>Worth noting that, if we keep using <code>Process.exit(sup_pid, :normal)</code> in <code>Test.Worker</code> but change the child spec of <code>Test.Worker</code> in <code>Test.Supervisor</code> by omitting the <code>restart</code> strategy which is <code>:permanent</code> by default, the test result might be misleading.</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">start_worker</span></span>(id) <span class="keyword">do</span></span><br><span class="line">  spec = %&#123;</span><br><span class="line">    <span class="symbol">id:</span> id,</span><br><span class="line">    <span class="comment"># restart: :transient, # Omitting this</span></span><br><span class="line">    <span class="symbol">start:</span> &#123;<span class="title class_">Test</span>.<span class="title class_">Worker</span>, <span class="symbol">:start_link</span>, [id]&#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="title class_">DynamicSupervisor</span>.start_child(<span class="title class_">Test</span>.<span class="title class_">Supervisor</span>, spec)</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><p>Test result:</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">iex(<span class="number">1</span>)&gt; [root, mgr, sup] = [<span class="title class_">Test</span>.<span class="title class_">Root</span>, <span class="title class_">Test</span>.<span class="title class_">Manager</span>, <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>] |&gt; <span class="title class_">Enum</span>.map(&amp;<span class="title class_">Process</span>.whereis/<span class="number">1</span>)</span><br><span class="line">[<span class="comment">#PID&lt;0.400.0&gt;, #PID&lt;0.401.0&gt;, #PID&lt;0.402.0&gt;]</span></span><br><span class="line">iex(<span class="number">2</span>)&gt; &#123;<span class="symbol">:ok</span>, child_a&#125; = <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>.start_worker(<span class="string">&quot;A&quot;</span>)</span><br><span class="line">&#123;<span class="symbol">:ok</span>, <span class="comment">#PID&lt;0.411.0&gt;&#125;</span></span><br><span class="line">iex(<span class="number">3</span>)&gt; &#123;<span class="symbol">:ok</span>, child_b&#125; = <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>.start_worker(<span class="string">&quot;B&quot;</span>)</span><br><span class="line">&#123;<span class="symbol">:ok</span>, <span class="comment">#PID&lt;0.413.0&gt;&#125;</span></span><br><span class="line">iex(<span class="number">4</span>)&gt; <span class="title class_">Test</span>.<span class="title class_">Worker</span>.down(child_a, sup)</span><br><span class="line"><span class="literal">true</span></span><br><span class="line">iex(<span class="number">5</span>)&gt;[root, mgr, sup, child_a, child_b] |&gt; <span class="title class_">Enum</span>.map(&amp;<span class="title class_">Process</span>.alive?/<span class="number">1</span>)</span><br><span class="line">[<span class="literal">true</span>, <span class="literal">true</span>, <span class="literal">false</span>, <span class="literal">false</span>, <span class="literal">false</span>]</span><br><span class="line">iex(<span class="number">6</span>)&gt; <span class="title class_">Supervisor</span>.which_children(root)</span><br><span class="line">[</span><br><span class="line">  &#123;<span class="title class_">Test</span>.<span class="title class_">Supervisor</span>, <span class="symbol">:undefined</span>, <span class="symbol">:supervisor</span>, [<span class="title class_">Test</span>.<span class="title class_">Supervisor</span>]&#125;,</span><br><span class="line">  &#123;<span class="title class_">Test</span>.<span class="title class_">Manager</span>, <span class="comment">#PID&lt;0.401.0&gt;, :worker, [Test.Manager]&#125;</span></span><br><span class="line">]</span><br></pre></td></tr></table></figure><p>It looks like the supervisor process <code>sup</code> is terminated correctly.  However, if you start up your application with <code>sasl</code> logging on: <code>iex --logger-sasl-reports true -S mix</code>, you can see similar information after step 4:</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">08</span><span class="symbol">:</span><span class="number">01</span><span class="symbol">:</span><span class="number">10.976</span> [error] <span class="title class_">Child</span> <span class="symbol">:undefined</span> of <span class="title class_">Supervisor</span> <span class="title class_">Test</span>.<span class="title class_">Supervisor</span> terminated</span><br><span class="line">** (exit) normal</span><br><span class="line"><span class="symbol">Pid:</span> <span class="comment">#PID&lt;0.411.0&gt;</span></span><br><span class="line"><span class="title class_">Start</span> <span class="symbol">Call:</span> <span class="title class_">Test</span>.<span class="title class_">Worker</span>.start_link(<span class="string">&quot;A&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="number">08</span><span class="symbol">:</span><span class="number">01</span><span class="symbol">:</span><span class="number">10.976</span> [error] <span class="title class_">Child</span> <span class="symbol">:undefined</span> of <span class="title class_">Supervisor</span> <span class="title class_">Test</span>.<span class="title class_">Supervisor</span> failed to start</span><br><span class="line">** (exit) already <span class="symbol">started:</span> <span class="comment">#PID&lt;0.411.0&gt;</span></span><br><span class="line"><span class="title class_">Start</span> <span class="symbol">Call:</span> <span class="title class_">Test</span>.<span class="title class_">Worker</span>.start_link(<span class="string">&quot;A&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="number">08</span><span class="symbol">:</span><span class="number">01</span><span class="symbol">:</span><span class="number">10.976</span> [error] <span class="title class_">Child</span> <span class="symbol">:undefined</span> of <span class="title class_">Supervisor</span> <span class="title class_">Test</span>.<span class="title class_">Supervisor</span> failed to start</span><br><span class="line">** (exit) already <span class="symbol">started:</span> <span class="comment">#PID&lt;0.411.0&gt;</span></span><br><span class="line"><span class="title class_">Start</span> <span class="symbol">Call:</span> <span class="title class_">Test</span>.<span class="title class_">Worker</span>.start_link(<span class="string">&quot;A&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="number">08</span><span class="symbol">:</span><span class="number">01</span><span class="symbol">:</span><span class="number">10.976</span> [error] <span class="title class_">Child</span> <span class="symbol">:undefined</span> of <span class="title class_">Supervisor</span> <span class="title class_">Test</span>.<span class="title class_">Supervisor</span> failed to start</span><br><span class="line">** (exit) already <span class="symbol">started:</span> <span class="comment">#PID&lt;0.411.0&gt;</span></span><br><span class="line"><span class="title class_">Start</span> <span class="symbol">Call:</span> <span class="title class_">Test</span>.<span class="title class_">Worker</span>.start_link(<span class="string">&quot;A&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="number">08</span><span class="symbol">:</span><span class="number">01</span><span class="symbol">:</span><span class="number">10.977</span> [error] <span class="title class_">Child</span> <span class="symbol">:undefined</span> of <span class="title class_">Supervisor</span> <span class="title class_">Test</span>.<span class="title class_">Supervisor</span> caused shutdown</span><br><span class="line">** (exit) <span class="symbol">:reached_max_restart_intensity</span></span><br><span class="line"><span class="title class_">Start</span> <span class="symbol">Call:</span> <span class="title class_">Test</span>.<span class="title class_">Worker</span>.start_link(<span class="string">&quot;A&quot;</span>)</span><br></pre></td></tr></table></figure><p>The <code>Test.Supervisor</code> actually tries to restart the <code>child_a</code> which indicates its termination by <code>Process.exit(sup_pid, :normal)</code>, but it keeps failing.  In the end, <code>Test.Supervisor</code> shutdown itself due to <code>:reached_max_restart_intensity</code>.  It seems the final outcome is what you need, but it is not working the same way as you thought.</p><p>By using <a href="https://github.com/redink/extrace">ExTrace</a> with below command before executing the testing code, it shows what really happens behind the scene.</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br></pre></td><td class="code"><pre><span class="line">iex(<span class="number">1</span>)&gt; <span class="title class_">Extrace</span>.calls([</span><br><span class="line">...(<span class="number">1</span>)&gt;   &#123;<span class="title class_">DynamicSupervisor</span>, <span class="symbol">:handle_info</span>, <span class="keyword">fn</span> _ -&gt; <span class="symbol">:return</span> <span class="keyword">end</span>&#125;,</span><br><span class="line">...(<span class="number">1</span>)&gt;   &#123;<span class="title class_">DynamicSupervisor</span>, <span class="symbol">:maybe_restart_child</span>, <span class="keyword">fn</span> _ -&gt; <span class="symbol">:return</span> <span class="keyword">end</span>&#125;,</span><br><span class="line">...(<span class="number">1</span>)&gt;   &#123;<span class="title class_">Test</span>.<span class="title class_">Worker</span>, <span class="symbol">:start_link</span>, <span class="keyword">fn</span> _ -&gt; <span class="symbol">:return</span> <span class="keyword">end</span>&#125;</span><br><span class="line">...(<span class="number">1</span>)&gt;   ], <span class="number">100</span>, <span class="symbol">scope:</span> <span class="symbol">:local</span>)</span><br><span class="line"><span class="number">3</span></span><br><span class="line">iex(<span class="number">2</span>)&gt; [root, mgr, sup] = [<span class="title class_">Test</span>.<span class="title class_">Root</span>, <span class="title class_">Test</span>.<span class="title class_">Manager</span>, <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>] |&gt; <span class="title class_">Enum</span>.map(&amp;<span class="title class_">Process</span>.whereis/<span class="number">1</span>)</span><br><span class="line">[<span class="comment">#PID&lt;0.382.0&gt;, #PID&lt;0.383.0&gt;, #PID&lt;0.384.0&gt;]</span></span><br><span class="line">iex(<span class="number">3</span>)&gt; &#123;<span class="symbol">:ok</span>, child_a&#125; = <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>.start_worker(<span class="string">&quot;A&quot;</span>)</span><br><span class="line">&#123;<span class="symbol">:ok</span>, <span class="comment">#PID&lt;0.400.0&gt;&#125;</span></span><br><span class="line">iex(<span class="number">4</span>)&gt; &#123;<span class="symbol">:ok</span>, child_b&#125; = <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>.start_worker(<span class="string">&quot;B&quot;</span>)</span><br><span class="line">&#123;<span class="symbol">:ok</span>, <span class="comment">#PID&lt;0.402.0&gt;&#125;</span></span><br><span class="line">iex(<span class="number">5</span>)&gt; <span class="title class_">Test</span>.<span class="title class_">Worker</span>.down(child_a, sup)</span><br><span class="line"><span class="literal">true</span></span><br><span class="line"></span><br><span class="line"><span class="number">08</span><span class="symbol">:</span><span class="number">14</span><span class="symbol">:</span><span class="number">42.840371</span> &lt;<span class="number">0.384</span>.<span class="number">0</span>&gt; <span class="title class_">DynamicSupervisor</span>.handle_info(&#123;<span class="symbol">:EXIT</span>, <span class="comment">#PID&lt;0.400.0&gt;, :normal&#125;, %DynamicSupervisor&#123;</span></span><br><span class="line">  <span class="symbol">args:</span> <span class="symbol">:no_args</span>,</span><br><span class="line">  <span class="symbol">children:</span> %&#123;</span><br><span class="line">    <span class="comment">#PID&lt;0.400.0&gt; =&gt; &#123;&#123;Test.Worker, :start_link, [&quot;A&quot;]&#125;, :permanent, 5000,</span></span><br><span class="line">     <span class="symbol">:worker</span>, [<span class="title class_">Test</span>.<span class="title class_">Worker</span>]&#125;,</span><br><span class="line">    <span class="comment">#PID&lt;0.402.0&gt; =&gt; &#123;&#123;Test.Worker, :start_link, [&quot;B&quot;]&#125;, :permanent, 5000,</span></span><br><span class="line">     <span class="symbol">:worker</span>, [<span class="title class_">Test</span>.<span class="title class_">Worker</span>]&#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="symbol">extra_arguments:</span> [],</span><br><span class="line">  <span class="symbol">max_children:</span> <span class="symbol">:infinity</span>,</span><br><span class="line">  <span class="symbol">max_restarts:</span> <span class="number">3</span>,</span><br><span class="line">  <span class="symbol">max_seconds:</span> <span class="number">5</span>,</span><br><span class="line">  <span class="symbol">mod:</span> <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>,</span><br><span class="line">  <span class="symbol">name:</span> &#123;<span class="symbol">:local</span>, <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>&#125;,</span><br><span class="line">  <span class="symbol">restarts:</span> [],</span><br><span class="line">  <span class="symbol">strategy:</span> <span class="symbol">:one_for_one</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="number">08</span><span class="symbol">:</span><span class="number">14</span><span class="symbol">:</span><span class="number">42.851545</span> &lt;<span class="number">0.384</span>.<span class="number">0</span>&gt; <span class="title class_">DynamicSupervisor</span>.maybe_restart_child(<span class="comment">#PID&lt;0.400.0&gt;, :normal, %DynamicSupervisor&#123;</span></span><br><span class="line">  <span class="symbol">args:</span> <span class="symbol">:no_args</span>,</span><br><span class="line">  <span class="symbol">children:</span> %&#123;</span><br><span class="line">    <span class="comment">#PID&lt;0.400.0&gt; =&gt; &#123;&#123;Test.Worker, :start_link, [&quot;A&quot;]&#125;, :permanent, 5000,</span></span><br><span class="line">     <span class="symbol">:worker</span>, [<span class="title class_">Test</span>.<span class="title class_">Worker</span>]&#125;,</span><br><span class="line">    <span class="comment">#PID&lt;0.402.0&gt; =&gt; &#123;&#123;Test.Worker, :start_link, [&quot;B&quot;]&#125;, :permanent, 5000,</span></span><br><span class="line">     <span class="symbol">:worker</span>, [<span class="title class_">Test</span>.<span class="title class_">Worker</span>]&#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="symbol">extra_arguments:</span> [],</span><br><span class="line">  <span class="symbol">max_children:</span> <span class="symbol">:infinity</span>,</span><br><span class="line">  <span class="symbol">max_restarts:</span> <span class="number">3</span>,</span><br><span class="line">  <span class="symbol">max_seconds:</span> <span class="number">5</span>,</span><br><span class="line">  <span class="symbol">mod:</span> <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>,</span><br><span class="line">  <span class="symbol">name:</span> &#123;<span class="symbol">:local</span>, <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>&#125;,</span><br><span class="line">  <span class="symbol">restarts:</span> [],</span><br><span class="line">  <span class="symbol">strategy:</span> <span class="symbol">:one_for_one</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="number">08</span><span class="symbol">:</span><span class="number">14</span><span class="symbol">:</span><span class="number">42.852137</span> &lt;<span class="number">0.384</span>.<span class="number">0</span>&gt; <span class="title class_">DynamicSupervisor</span>.maybe_restart_child(<span class="symbol">:permanent</span>, <span class="symbol">:normal</span>, <span class="comment">#PID&lt;0.400.0&gt;, &#123;&#123;Test.Worker, :start_link, [&quot;A&quot;]&#125;, :permanent, 5000, :worker, [Test.Worker]&#125;, %DynamicSupervisor&#123;</span></span><br><span class="line">  <span class="symbol">args:</span> <span class="symbol">:no_args</span>,</span><br><span class="line">  <span class="symbol">children:</span> %&#123;</span><br><span class="line">    <span class="comment">#PID&lt;0.400.0&gt; =&gt; &#123;&#123;Test.Worker, :start_link, [&quot;A&quot;]&#125;, :permanent, 5000,</span></span><br><span class="line">     <span class="symbol">:worker</span>, [<span class="title class_">Test</span>.<span class="title class_">Worker</span>]&#125;,</span><br><span class="line">    <span class="comment">#PID&lt;0.402.0&gt; =&gt; &#123;&#123;Test.Worker, :start_link, [&quot;B&quot;]&#125;, :permanent, 5000,</span></span><br><span class="line">     <span class="symbol">:worker</span>, [<span class="title class_">Test</span>.<span class="title class_">Worker</span>]&#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="symbol">extra_arguments:</span> [],</span><br><span class="line">  <span class="symbol">max_children:</span> <span class="symbol">:infinity</span>,</span><br><span class="line">  <span class="symbol">max_restarts:</span> <span class="number">3</span>,</span><br><span class="line">  <span class="symbol">max_seconds:</span> <span class="number">5</span>,</span><br><span class="line">  <span class="symbol">mod:</span> <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>,</span><br><span class="line">  <span class="symbol">name:</span> &#123;<span class="symbol">:local</span>, <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>&#125;,</span><br><span class="line">  <span class="symbol">restarts:</span> [],</span><br><span class="line">  <span class="symbol">strategy:</span> <span class="symbol">:one_for_one</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="number">08</span><span class="symbol">:</span><span class="number">14</span><span class="symbol">:</span><span class="number">42.853046</span> &lt;<span class="number">0.384</span>.<span class="number">0</span>&gt; <span class="title class_">DynamicSupervisor</span>.maybe_restart_child/<span class="number">5</span> --&gt; &#123;<span class="symbol">:ok</span>,</span><br><span class="line"> %<span class="title class_">DynamicSupervisor</span>&#123;</span><br><span class="line">   <span class="symbol">args:</span> <span class="symbol">:no_args</span>,</span><br><span class="line">   <span class="symbol">children:</span> %&#123;</span><br><span class="line">     <span class="comment">#PID&lt;0.400.0&gt; =&gt; &#123;:restarting,</span></span><br><span class="line">      &#123;&#123;<span class="title class_">Test</span>.<span class="title class_">Worker</span>, <span class="symbol">:start_link</span>, [<span class="string">&quot;A&quot;</span>]&#125;, <span class="symbol">:permanent</span>, <span class="number">5000</span>, <span class="symbol">:worker</span>,</span><br><span class="line">       [<span class="title class_">Test</span>.<span class="title class_">Worker</span>]&#125;&#125;,</span><br><span class="line">     <span class="comment">#PID&lt;0.402.0&gt; =&gt; &#123;&#123;Test.Worker, :start_link, [&quot;B&quot;]&#125;, :permanent, 5000,</span></span><br><span class="line">      <span class="symbol">:worker</span>, [<span class="title class_">Test</span>.<span class="title class_">Worker</span>]&#125;</span><br><span class="line">   &#125;,</span><br><span class="line">   <span class="symbol">extra_arguments:</span> [],</span><br><span class="line">   <span class="symbol">max_children:</span> <span class="symbol">:infinity</span>,</span><br><span class="line">   <span class="symbol">max_restarts:</span> <span class="number">3</span>,</span><br><span class="line">   <span class="symbol">max_seconds:</span> <span class="number">5</span>,</span><br><span class="line">   <span class="symbol">mod:</span> <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>,</span><br><span class="line">   <span class="symbol">name:</span> &#123;<span class="symbol">:local</span>, <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>&#125;,</span><br><span class="line">   <span class="symbol">restarts:</span> [<span class="number">-576460714</span>],</span><br><span class="line">   <span class="symbol">strategy:</span> <span class="symbol">:one_for_one</span></span><br><span class="line"> &#125;&#125;</span><br><span class="line"></span><br><span class="line"><span class="number">08</span><span class="symbol">:</span><span class="number">14</span><span class="symbol">:</span><span class="number">42.853617</span> &lt;<span class="number">0.384</span>.<span class="number">0</span>&gt; <span class="title class_">DynamicSupervisor</span>.maybe_restart_child/<span class="number">3</span> --&gt; &#123;<span class="symbol">:ok</span>,</span><br><span class="line"> %<span class="title class_">DynamicSupervisor</span>&#123;</span><br><span class="line">   <span class="symbol">args:</span> <span class="symbol">:no_args</span>,</span><br><span class="line">   <span class="symbol">children:</span> %&#123;</span><br><span class="line">     <span class="comment">#PID&lt;0.400.0&gt; =&gt; &#123;:restarting,</span></span><br><span class="line">      &#123;&#123;<span class="title class_">Test</span>.<span class="title class_">Worker</span>, <span class="symbol">:start_link</span>, [<span class="string">&quot;A&quot;</span>]&#125;, <span class="symbol">:permanent</span>, <span class="number">5000</span>, <span class="symbol">:worker</span>,</span><br><span class="line">       [<span class="title class_">Test</span>.<span class="title class_">Worker</span>]&#125;&#125;,</span><br><span class="line">     <span class="comment">#PID&lt;0.402.0&gt; =&gt; &#123;&#123;Test.Worker, :start_link, [&quot;B&quot;]&#125;, :permanent, 5000,</span></span><br><span class="line">      <span class="symbol">:worker</span>, [<span class="title class_">Test</span>.<span class="title class_">Worker</span>]&#125;</span><br><span class="line">   &#125;,</span><br><span class="line">   <span class="symbol">extra_arguments:</span> [],</span><br><span class="line">   <span class="symbol">max_children:</span> <span class="symbol">:infinity</span>,</span><br><span class="line">   <span class="symbol">max_restarts:</span> <span class="number">3</span>,</span><br><span class="line">   <span class="symbol">max_seconds:</span> <span class="number">5</span>,</span><br><span class="line">   <span class="symbol">mod:</span> <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>,</span><br><span class="line">   <span class="symbol">name:</span> &#123;<span class="symbol">:local</span>, <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>&#125;,</span><br><span class="line">   <span class="symbol">restarts:</span> [<span class="number">-576460714</span>],</span><br><span class="line">   <span class="symbol">strategy:</span> <span class="symbol">:one_for_one</span></span><br><span class="line"> &#125;&#125;</span><br><span class="line"></span><br><span class="line"><span class="number">08</span><span class="symbol">:</span><span class="number">14</span><span class="symbol">:</span><span class="number">42.854183</span> &lt;<span class="number">0.384</span>.<span class="number">0</span>&gt; <span class="title class_">DynamicSupervisor</span>.handle_info/<span class="number">2</span> --&gt; &#123;<span class="symbol">:noreply</span>,</span><br><span class="line"> %<span class="title class_">DynamicSupervisor</span>&#123;</span><br><span class="line">   <span class="symbol">args:</span> <span class="symbol">:no_args</span>,</span><br><span class="line">   <span class="symbol">children:</span> %&#123;</span><br><span class="line">     <span class="comment">#PID&lt;0.400.0&gt; =&gt; &#123;:restarting,</span></span><br><span class="line">      &#123;&#123;<span class="title class_">Test</span>.<span class="title class_">Worker</span>, <span class="symbol">:start_link</span>, [<span class="string">&quot;A&quot;</span>]&#125;, <span class="symbol">:permanent</span>, <span class="number">5000</span>, <span class="symbol">:worker</span>,</span><br><span class="line">       [<span class="title class_">Test</span>.<span class="title class_">Worker</span>]&#125;&#125;,</span><br><span class="line">     <span class="comment">#PID&lt;0.402.0&gt; =&gt; &#123;&#123;Test.Worker, :start_link, [&quot;B&quot;]&#125;, :permanent, 5000,</span></span><br><span class="line">      <span class="symbol">:worker</span>, [<span class="title class_">Test</span>.<span class="title class_">Worker</span>]&#125;</span><br><span class="line">   &#125;,</span><br><span class="line">   <span class="symbol">extra_arguments:</span> [],</span><br><span class="line">   <span class="symbol">max_children:</span> <span class="symbol">:infinity</span>,</span><br><span class="line">   <span class="symbol">max_restarts:</span> <span class="number">3</span>,</span><br><span class="line">   <span class="symbol">max_seconds:</span> <span class="number">5</span>,</span><br><span class="line">   <span class="symbol">mod:</span> <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>,</span><br><span class="line">   <span class="symbol">name:</span> &#123;<span class="symbol">:local</span>, <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>&#125;,</span><br><span class="line">   <span class="symbol">restarts:</span> [<span class="number">-576460714</span>],</span><br><span class="line">   <span class="symbol">strategy:</span> <span class="symbol">:one_for_one</span></span><br><span class="line"> &#125;&#125;</span><br><span class="line"></span><br><span class="line"><span class="number">08</span><span class="symbol">:</span><span class="number">14</span><span class="symbol">:</span><span class="number">42.854728</span> &lt;<span class="number">0.384</span>.<span class="number">0</span>&gt; <span class="title class_">DynamicSupervisor</span>.handle_info(&#123;<span class="symbol">:<span class="string">&quot;$gen_restart&quot;</span></span>, <span class="comment">#PID&lt;0.400.0&gt;&#125;, %DynamicSupervisor&#123;</span></span><br><span class="line">  <span class="symbol">args:</span> <span class="symbol">:no_args</span>,</span><br><span class="line">  <span class="symbol">children:</span> %&#123;</span><br><span class="line">    <span class="comment">#PID&lt;0.400.0&gt; =&gt; &#123;:restarting,</span></span><br><span class="line">     &#123;&#123;<span class="title class_">Test</span>.<span class="title class_">Worker</span>, <span class="symbol">:start_link</span>, [<span class="string">&quot;A&quot;</span>]&#125;, <span class="symbol">:permanent</span>, <span class="number">5000</span>, <span class="symbol">:worker</span>,</span><br><span class="line">      [<span class="title class_">Test</span>.<span class="title class_">Worker</span>]&#125;&#125;,</span><br><span class="line">    <span class="comment">#PID&lt;0.402.0&gt; =&gt; &#123;&#123;Test.Worker, :start_link, [&quot;B&quot;]&#125;, :permanent, 5000,</span></span><br><span class="line">     <span class="symbol">:worker</span>, [<span class="title class_">Test</span>.<span class="title class_">Worker</span>]&#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="symbol">extra_arguments:</span> [],</span><br><span class="line">  <span class="symbol">max_children:</span> <span class="symbol">:infinity</span>,</span><br><span class="line">  <span class="symbol">max_restarts:</span> <span class="number">3</span>,</span><br><span class="line">  <span class="symbol">max_seconds:</span> <span class="number">5</span>,</span><br><span class="line">  <span class="symbol">mod:</span> <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>,</span><br><span class="line">  <span class="symbol">name:</span> &#123;<span class="symbol">:local</span>, <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>&#125;,</span><br><span class="line">  <span class="symbol">restarts:</span> [<span class="number">-576460714</span>],</span><br><span class="line">  <span class="symbol">strategy:</span> <span class="symbol">:one_for_one</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="number">08</span><span class="symbol">:</span><span class="number">14</span><span class="symbol">:</span><span class="number">42.855276</span> &lt;<span class="number">0.384</span>.<span class="number">0</span>&gt; <span class="title class_">DynamicSupervisor</span>.handle_info/<span class="number">2</span> --&gt; &#123;<span class="symbol">:noreply</span>,</span><br><span class="line"> %<span class="title class_">DynamicSupervisor</span>&#123;</span><br><span class="line">   <span class="symbol">args:</span> <span class="symbol">:no_args</span>,</span><br><span class="line">   <span class="symbol">children:</span> %&#123;</span><br><span class="line">     <span class="comment">#PID&lt;0.400.0&gt; =&gt; &#123;:restarting,</span></span><br><span class="line">      &#123;&#123;<span class="title class_">Test</span>.<span class="title class_">Worker</span>, <span class="symbol">:start_link</span>, [<span class="string">&quot;A&quot;</span>]&#125;, <span class="symbol">:permanent</span>, <span class="number">5000</span>, <span class="symbol">:worker</span>,</span><br><span class="line">       [<span class="title class_">Test</span>.<span class="title class_">Worker</span>]&#125;&#125;,</span><br><span class="line">     <span class="comment">#PID&lt;0.402.0&gt; =&gt; &#123;&#123;Test.Worker, :start_link, [&quot;B&quot;]&#125;, :permanent, 5000,</span></span><br><span class="line">      <span class="symbol">:worker</span>, [<span class="title class_">Test</span>.<span class="title class_">Worker</span>]&#125;</span><br><span class="line">   &#125;,</span><br><span class="line">   <span class="symbol">extra_arguments:</span> [],</span><br><span class="line">   <span class="symbol">max_children:</span> <span class="symbol">:infinity</span>,</span><br><span class="line">   <span class="symbol">max_restarts:</span> <span class="number">3</span>,</span><br><span class="line">   <span class="symbol">max_seconds:</span> <span class="number">5</span>,</span><br><span class="line">   <span class="symbol">mod:</span> <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>,</span><br><span class="line">   <span class="symbol">name:</span> &#123;<span class="symbol">:local</span>, <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>&#125;,</span><br><span class="line">   <span class="symbol">restarts:</span> [<span class="number">-576460714</span>, <span class="number">-576460714</span>],</span><br><span class="line">   <span class="symbol">strategy:</span> <span class="symbol">:one_for_one</span></span><br><span class="line"> &#125;&#125;</span><br><span class="line"></span><br><span class="line"><span class="number">08</span><span class="symbol">:</span><span class="number">14</span><span class="symbol">:</span><span class="number">42.855847</span> &lt;<span class="number">0.384</span>.<span class="number">0</span>&gt; <span class="title class_">DynamicSupervisor</span>.handle_info(&#123;<span class="symbol">:<span class="string">&quot;$gen_restart&quot;</span></span>, <span class="comment">#PID&lt;0.400.0&gt;&#125;, %DynamicSupervisor&#123;</span></span><br><span class="line">  <span class="symbol">args:</span> <span class="symbol">:no_args</span>,</span><br><span class="line">  <span class="symbol">children:</span> %&#123;</span><br><span class="line">    <span class="comment">#PID&lt;0.400.0&gt; =&gt; &#123;:restarting,</span></span><br><span class="line">     &#123;&#123;<span class="title class_">Test</span>.<span class="title class_">Worker</span>, <span class="symbol">:start_link</span>, [<span class="string">&quot;A&quot;</span>]&#125;, <span class="symbol">:permanent</span>, <span class="number">5000</span>, <span class="symbol">:worker</span>,</span><br><span class="line">      [<span class="title class_">Test</span>.<span class="title class_">Worker</span>]&#125;&#125;,</span><br><span class="line">    <span class="comment">#PID&lt;0.402.0&gt; =&gt; &#123;&#123;Test.Worker, :start_link, [&quot;B&quot;]&#125;, :permanent, 5000,</span></span><br><span class="line">     <span class="symbol">:worker</span>, [<span class="title class_">Test</span>.<span class="title class_">Worker</span>]&#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="symbol">extra_arguments:</span> [],</span><br><span class="line">  <span class="symbol">max_children:</span> <span class="symbol">:infinity</span>,</span><br><span class="line">  <span class="symbol">max_restarts:</span> <span class="number">3</span>,</span><br><span class="line">  <span class="symbol">max_seconds:</span> <span class="number">5</span>,</span><br><span class="line">  <span class="symbol">mod:</span> <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>,</span><br><span class="line">  <span class="symbol">name:</span> &#123;<span class="symbol">:local</span>, <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>&#125;,</span><br><span class="line">  <span class="symbol">restarts:</span> [<span class="number">-576460714</span>, <span class="number">-576460714</span>],</span><br><span class="line">  <span class="symbol">strategy:</span> <span class="symbol">:one_for_one</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="number">08</span><span class="symbol">:</span><span class="number">14</span><span class="symbol">:</span><span class="number">42.856410</span> &lt;<span class="number">0.384</span>.<span class="number">0</span>&gt; <span class="title class_">DynamicSupervisor</span>.handle_info/<span class="number">2</span> --&gt; &#123;<span class="symbol">:noreply</span>,</span><br><span class="line"> %<span class="title class_">DynamicSupervisor</span>&#123;</span><br><span class="line">   <span class="symbol">args:</span> <span class="symbol">:no_args</span>,</span><br><span class="line">   <span class="symbol">children:</span> %&#123;</span><br><span class="line">     <span class="comment">#PID&lt;0.400.0&gt; =&gt; &#123;:restarting,</span></span><br><span class="line">      &#123;&#123;<span class="title class_">Test</span>.<span class="title class_">Worker</span>, <span class="symbol">:start_link</span>, [<span class="string">&quot;A&quot;</span>]&#125;, <span class="symbol">:permanent</span>, <span class="number">5000</span>, <span class="symbol">:worker</span>,</span><br><span class="line">       [<span class="title class_">Test</span>.<span class="title class_">Worker</span>]&#125;&#125;,</span><br><span class="line">     <span class="comment">#PID&lt;0.402.0&gt; =&gt; &#123;&#123;Test.Worker, :start_link, [&quot;B&quot;]&#125;, :permanent, 5000,</span></span><br><span class="line">      <span class="symbol">:worker</span>, [<span class="title class_">Test</span>.<span class="title class_">Worker</span>]&#125;</span><br><span class="line">   &#125;,</span><br><span class="line">   <span class="symbol">extra_arguments:</span> [],</span><br><span class="line">   <span class="symbol">max_children:</span> <span class="symbol">:infinity</span>,</span><br><span class="line">   <span class="symbol">max_restarts:</span> <span class="number">3</span>,</span><br><span class="line">   <span class="symbol">max_seconds:</span> <span class="number">5</span>,</span><br><span class="line">   <span class="symbol">mod:</span> <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>,</span><br><span class="line">   <span class="symbol">name:</span> &#123;<span class="symbol">:local</span>, <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>&#125;,</span><br><span class="line">   <span class="symbol">restarts:</span> [<span class="number">-576460714</span>, <span class="number">-576460714</span>, <span class="number">-576460714</span>],</span><br><span class="line">   <span class="symbol">strategy:</span> <span class="symbol">:one_for_one</span></span><br><span class="line"> &#125;&#125;</span><br><span class="line"></span><br><span class="line"><span class="number">08</span><span class="symbol">:</span><span class="number">14</span><span class="symbol">:</span><span class="number">42.857078</span> &lt;<span class="number">0.384</span>.<span class="number">0</span>&gt; <span class="title class_">DynamicSupervisor</span>.handle_info(&#123;<span class="symbol">:<span class="string">&quot;$gen_restart&quot;</span></span>, <span class="comment">#PID&lt;0.400.0&gt;&#125;, %DynamicSupervisor&#123;</span></span><br><span class="line">  <span class="symbol">args:</span> <span class="symbol">:no_args</span>,</span><br><span class="line">  <span class="symbol">children:</span> %&#123;</span><br><span class="line">    <span class="comment">#PID&lt;0.400.0&gt; =&gt; &#123;:restarting,</span></span><br><span class="line">     &#123;&#123;<span class="title class_">Test</span>.<span class="title class_">Worker</span>, <span class="symbol">:start_link</span>, [<span class="string">&quot;A&quot;</span>]&#125;, <span class="symbol">:permanent</span>, <span class="number">5000</span>, <span class="symbol">:worker</span>,</span><br><span class="line">      [<span class="title class_">Test</span>.<span class="title class_">Worker</span>]&#125;&#125;,</span><br><span class="line">    <span class="comment">#PID&lt;0.402.0&gt; =&gt; &#123;&#123;Test.Worker, :start_link, [&quot;B&quot;]&#125;, :permanent, 5000,</span></span><br><span class="line">     <span class="symbol">:worker</span>, [<span class="title class_">Test</span>.<span class="title class_">Worker</span>]&#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="symbol">extra_arguments:</span> [],</span><br><span class="line">  <span class="symbol">max_children:</span> <span class="symbol">:infinity</span>,</span><br><span class="line">  <span class="symbol">max_restarts:</span> <span class="number">3</span>,</span><br><span class="line">  <span class="symbol">max_seconds:</span> <span class="number">5</span>,</span><br><span class="line">  <span class="symbol">mod:</span> <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>,</span><br><span class="line">  <span class="symbol">name:</span> &#123;<span class="symbol">:local</span>, <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>&#125;,</span><br><span class="line">  <span class="symbol">restarts:</span> [<span class="number">-576460714</span>, <span class="number">-576460714</span>, <span class="number">-576460714</span>],</span><br><span class="line">  <span class="symbol">strategy:</span> <span class="symbol">:one_for_one</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="number">08</span><span class="symbol">:</span><span class="number">14</span><span class="symbol">:</span><span class="number">42.857723</span> &lt;<span class="number">0.384</span>.<span class="number">0</span>&gt; <span class="title class_">DynamicSupervisor</span>.handle_info/<span class="number">2</span> --&gt; &#123;<span class="symbol">:stop</span>, <span class="symbol">:shutdown</span>,</span><br><span class="line"> %<span class="title class_">DynamicSupervisor</span>&#123;</span><br><span class="line">   <span class="symbol">args:</span> <span class="symbol">:no_args</span>,</span><br><span class="line">   <span class="symbol">children:</span> %&#123;</span><br><span class="line">     <span class="comment">#PID&lt;0.402.0&gt; =&gt; &#123;&#123;Test.Worker, :start_link, [&quot;B&quot;]&#125;, :permanent, 5000,</span></span><br><span class="line">      <span class="symbol">:worker</span>, [<span class="title class_">Test</span>.<span class="title class_">Worker</span>]&#125;</span><br><span class="line">   &#125;,</span><br><span class="line">   <span class="symbol">extra_arguments:</span> [],</span><br><span class="line">   <span class="symbol">max_children:</span> <span class="symbol">:infinity</span>,</span><br><span class="line">   <span class="symbol">max_restarts:</span> <span class="number">3</span>,</span><br><span class="line">   <span class="symbol">max_seconds:</span> <span class="number">5</span>,</span><br><span class="line">   <span class="symbol">mod:</span> <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>,</span><br><span class="line">   <span class="symbol">name:</span> &#123;<span class="symbol">:local</span>, <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>&#125;,</span><br><span class="line">   <span class="symbol">restarts:</span> [<span class="number">-576460714</span>, <span class="number">-576460714</span>, <span class="number">-576460714</span>, <span class="number">-576460714</span>],</span><br><span class="line">   <span class="symbol">strategy:</span> <span class="symbol">:one_for_one</span></span><br><span class="line"> &#125;&#125;</span><br></pre></td></tr></table></figure>]]></content>
    
    
      
      
    <summary type="html">&lt;p&gt;Process is one of the core concept in Elixir&amp;#x2F;Erlang.  Sending &amp;amp; receiving messages between them is crucial.  So how should the c</summary>
      
    
    
    
    <category term="Sword" scheme="http://www.thinkingincrowd.me/categories/Sword/"/>
    
    
    <category term="Elixir" scheme="http://www.thinkingincrowd.me/tags/Elixir/"/>
    
    <category term="Supervisor" scheme="http://www.thinkingincrowd.me/tags/Supervisor/"/>
    
    <category term="OTP" scheme="http://www.thinkingincrowd.me/tags/OTP/"/>
    
  </entry>
  
  <entry>
    <title>Multi-level dynamic supervision in Elixir</title>
    <link href="http://www.thinkingincrowd.me/2020/09/06/multi-level-supervision-in-elixir/"/>
    <id>http://www.thinkingincrowd.me/2020/09/06/multi-level-supervision-in-elixir/</id>
    <published>2020-09-06T14:10:10.000Z</published>
    <updated>2022-08-28T08:07:15.453Z</updated>
    
    <content type="html"><![CDATA[<p>The most fantastic concepts in Erlang &amp; Elixir that fascinate me are:</p><ol><li>Everything can be a process.</li><li>Let it crash.</li></ol><blockquote><p>If you don’t need a process, then you don’t need a process. Use processes only to model runtime properties, such as mutable state, concurrency and failures, never for code organization.</p><p>quoted from <a href="https://hexdocs.pm/elixir/GenServer.html#module-when-not-to-use-a-genserver">GenServer, Elixir API Documentation</a></p></blockquote><p>In order to fully embrace these features in every programs I write, learning OTP, GenServer, Supervisor is a must.</p><p>But every senior developer knows something very well:  <strong>There is a large gap between knowing something in the book and using it</strong>.</p><p>When reading the「<a href="https://pragprog.com/book/elixir16/programming-elixir-1-6">Programming Elixir ≥ 1.6</a>」, everything makes sense to me on the chapters about OTP Servers and Supervisors.  But when I tried to implement my own version for a more sophisticated scenario, I realized how big that gap is for me.  </p><p>In this article, I would like to help you bridge the gap using my experience and the sophisticated enough scenario which seldom found in other tutorials.</p><h2 id="1-Level"><a href="#1-Level" class="headerlink" title="1-Level"></a>1-Level</h2><p>In many tutorials on <code>Supervisor</code>, they first tell us to create an application that has such capability by running command <code>mix new test --sup</code>.  The <code>application.ex</code> created in the project will be similar as below.  The application itself becomes a Supervisor that contains a defined set of children.  </p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">defmodule</span> <span class="title">Test.Application</span></span> <span class="keyword">do</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">use</span> <span class="title class_">Application</span></span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">start</span></span>(_type, _args) <span class="keyword">do</span></span><br><span class="line">    children = [</span><br><span class="line">      &#123;<span class="title class_">Test</span>.<span class="title class_">Service</span>, []&#125;</span><br><span class="line">    ]</span><br><span class="line"></span><br><span class="line">    opts = [<span class="symbol">strategy:</span> <span class="symbol">:one_for_one</span>, <span class="symbol">name:</span> <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>]</span><br><span class="line">    <span class="title class_">Supervisor</span>.start_link(children, opts)</span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><p>Later when the tutorial introduces the concept of <code>DynamicSupervisor</code>, it may define a module and modify the <code>application.ex</code> like this:</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">defmodule</span> <span class="title">Test.MyDynamicSupervisor</span></span> <span class="keyword">do</span></span><br><span class="line">  <span class="keyword">use</span> <span class="title class_">DynamicSupervisor</span></span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">start_link</span></span>(init_arg) <span class="keyword">do</span></span><br><span class="line">    <span class="title class_">DynamicSupervisor</span>.start_link(__MODULE__, init_arg, <span class="symbol">name:</span> __MODULE__)</span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">start_child</span></span>(foo, bar) <span class="keyword">do</span></span><br><span class="line">    spec = %&#123;<span class="symbol">id:</span> <span class="title class_">Test</span>.<span class="title class_">MyWorker</span>, <span class="symbol">start:</span> &#123;<span class="title class_">Test</span>.<span class="title class_">MyWorker</span>, <span class="symbol">:start_link</span>, [foo, bar]&#125;&#125;</span><br><span class="line">    <span class="title class_">DynamicSupervisor</span>.start_child(__MODULE__, spec)</span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">  <span class="variable">@impl</span> <span class="literal">true</span></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">init</span></span>(init_arg) <span class="keyword">do</span></span><br><span class="line">    <span class="title class_">DynamicSupervisor</span>.init(<span class="symbol">strategy:</span> <span class="symbol">:one_for_one</span>)</span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Modified in applicaiton.ex to include the Test.MyDynamicSupervisor</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">start</span></span>(_type, _args) <span class="keyword">do</span></span><br><span class="line">  children = [</span><br><span class="line">    &#123;<span class="title class_">Test</span>.<span class="title class_">Service</span>, []&#125;,</span><br><span class="line">    <span class="title class_">Test</span>.<span class="title class_">MyDynamicSupervisor</span></span><br><span class="line">  ]</span><br><span class="line"></span><br><span class="line">  opts = [<span class="symbol">strategy:</span> <span class="symbol">:one_for_one</span>, <span class="symbol">name:</span> <span class="title class_">Test</span>.<span class="title class_">Supervisor</span>]</span><br><span class="line">  <span class="title class_">Supervisor</span>.start_link(children, opts)</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><p>The process hierarchy for the above example is:</p><pre class="mermaid">graph TD  A(Application) --> B(Test.Service) & C(Test.MyDynamicSupervisor)  C(Test.MyDynamicSupervisor) --> D(Test.MyWorker) & E(Test.MyWorker)</pre><p>In a word, most of the tutorial about <code>Supervisor</code>, especially <code>DynamicSupervisor</code>, only has 1-level depth.</p><p>But the real world is much more than that.</p><h2 id="Multi-Level"><a href="#Multi-Level" class="headerlink" title="Multi-Level"></a>Multi-Level</h2><p>My application that involves multi-level supervision is a classic scenario for many personal or large corporate projects, Web Crawling.  This scenario is far more real and practical than most of the examples in the tutorials out there.  The process hierarchy of the application design is:</p><pre class="mermaid">graph TD  A(Spider Application) --> B(SpiderEngine)  B --> C(SpiderEngine.Manager) & D(SpiderEngine.Supervisor) & E(SpiderStorage)  D --> F(Spider.Facebook) & G(Spider.Instagram)  F --> H(Spider.Manager.Facebook) & I(Spider.Supervisor.Facebook)  G --> J(Spider.Manager.Instagram) & K(Spider.Supervisor.Instagram)  I --> L(Spider.Fetcher.Facebook.1) & M(Spider.Fetcher.Facebook.2)  K --> N(Spider.Fetcher.Instagram.1)</pre><p>You may have already known, most of the modules are normal <code>GenServer</code> except these:</p><ul><li><strong>Supervisor</strong>: <code>SpiderEngine</code>, <code>Spider.Instagram</code>, <code>Spider.Facebook</code></li><li><strong>DynamicSupervisor</strong>: <code>SpiderEngine.Supervisor</code>, <code>Spider.Supervisor.Instagram</code>, <code>Spider.Supervisor.Facebook</code></li></ul><h3 id="Why-the-design"><a href="#Why-the-design" class="headerlink" title="Why the design"></a>Why the design</h3><pre class="mermaid">sequenceDiagram  participant SpiderStorage  participant SpiderEngine.Manager  participant SpiderEngine.Supervisor  participant Spider  participant Spider.Manager  participant Spider.Supervisor  participant Spider.Fetcher  SpiderEngine.Manager->>SpiderStorage: What spiders to start?  SpiderEngine.Supervisor-->>Spider: Dynamically starts spider engine  Spider.Manager->>SpiderStorage: The base domain and urls to fetched?  Spider.Supervisor-->>Spider.Fetcher: Dynamically starts fetcher  Spider.Fetcher->>Spider.Manager: Asks for next url and/or sends back more urls  SpiderEngine.Manager->>Spider.Manager: Reset fecher count, speed, etc.</pre><ul><li><p><code>SpiderEngine</code> is the root of the whole web crawler.<br>  The reason of not using Application directly as root because the application might contain other components, such as Phoenix API and Web UI to help managing the crawler.</p><p>  The benefit of grouping all crawling behaviors under one particular module is the freedom to move them all at once easily if necessary.</p></li><li><p><code>SpiderEngine</code> must be able to supervise different types of crawlers depending on the nature of the websites or systems you want to crawl information from.</p></li><li><p>Types of the supported spiders should be configurable so that there must a <code>DynamicSupervisor</code> under <code>SpiderEngine</code>.</p></li><li><p>The reason of separating <code>xxx.Manager</code> from the <code>xxx.Supervisor</code> is that <code>Supervisor/DynamicSupervisor</code> is purely for process supervision.  There can be no other message passing between the <code>Supervisor/DynamicSupervisor</code> and children workers.  Hence, all children workers’ control logic have to be in the other module, <code>xxx.Manager</code>.  </p></li><li><p><code>Spider.Facebook</code>, <code>Spider.Instagram</code> and other possible crawlers for different websites, are supervisor of their own to manage their own crawling policy, frequency, fetcher count, etc.</p></li></ul><h3 id="Code"><a href="#Code" class="headerlink" title="Code"></a>Code</h3><p>I hope the process hierarchy and sequence diagram explain clearly enough.  Let’s move on to the real code.  Actually, there are only two things that you need to clearly understand in order to keep your thought straight on building the process hierarchy.</p><p><strong>start_link&#x2F;3</strong></p><p>The most important thing to be awared is the <code>name</code> option in <code>start_link/3</code>.  It’s for <strong>Name Registration</strong> which causes trouble if you do not pay attention to when constructing the multi-level supervision.</p><p>In my scenario, <code>SpiderStorage</code>, <code>SpiderEngine.Manager</code>, <code>SpiderEngine</code> and <code>SpiderEngine.Supervisor</code> only have one running process.  Hence, their calls to <code>start_link/3</code> can be simply:</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="title class_">GenServer</span>.start_link(__MODULE__, <span class="symbol">:no_args</span>, <span class="symbol">name:</span> __MODULE__)</span><br><span class="line"></span><br><span class="line"><span class="title class_">Supervisor</span>.start_link(__MODULE__, <span class="symbol">:no_args</span>, <span class="symbol">name:</span> __MODULE__)</span><br><span class="line"></span><br><span class="line"><span class="title class_">DynamicSupervisor</span>.start_link(__MODULE__, <span class="symbol">:no_args</span>, <span class="symbol">name:</span> __MODULE__)</span><br></pre></td></tr></table></figure><p>However, for the <code>Spider</code>, <code>Spider.Mananger</code>, <code>Spider.Supervisor</code>, they have multiple processes for different types of spiders.  Hence, their names should be differentiated.</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># for Spider</span></span><br><span class="line"><span class="title class_">Supervisor</span>.start_link(__MODULE__, spider_config, <span class="symbol">name:</span> <span class="symbol">:<span class="string">&quot;Spider.<span class="subst">#&#123;spider_config.name&#125;</span>&quot;</span></span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># for Spider.Manager</span></span><br><span class="line"><span class="title class_">GenServer</span>.start_link(__MODULE__, spider_config, <span class="symbol">name:</span> <span class="symbol">:<span class="string">&quot;Spider.Manager.<span class="subst">#&#123;spider_config.name&#125;</span>&quot;</span></span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># for Spider.Supervisor</span></span><br><span class="line"><span class="title class_">DynamicSupervisor</span>.start_link(__MODULE__, <span class="symbol">:no_args</span>, <span class="symbol">name:</span> <span class="symbol">:<span class="string">&quot;Spider.Supervisor.<span class="subst">#&#123;spider_config.name&#125;</span>&quot;</span></span>)</span><br></pre></td></tr></table></figure><p>How about <code>Spider.Fetcher</code>?  There are also multiple processes for it, but do we have to start them with different names?  </p><p>I think it’s a judgement call.  The communication between <code>Spider.Fetcher</code> and <code>Spider.Manager</code> are through PID.    Hence, if you have saved those children PID somewhere when <code>Spider.Manager</code> starts them, or the message is sent from <code>Spider.Fetcher</code> to <code>Spider.Manager</code>, it’s not quite necessary to name this type of children workers, especially when their amount is large.</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># for Fetcher, you can omit the name option or simply use a combined index as name</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">start_link</span></span>(state = &#123;spider_name, index, _manager_pid&#125;) <span class="keyword">do</span></span><br><span class="line">  <span class="title class_">GenServer</span>.start_link(__MODULE__, state, <span class="symbol">name:</span> <span class="symbol">:<span class="string">&quot;Spider.Fetcher.<span class="subst">#&#123;spider_name&#125;</span>.<span class="subst">#&#123;index&#125;</span>&quot;</span></span>)</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><p><strong>Child Spec</strong></p><p>There are different forms of child specification when we start them by Supervisor:</p><ul><li>A map</li><li>A tuple with a module as first element and the start argument as second</li><li>A module</li></ul><p>Below three samples are equal:</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># I just present three forms here.</span></span><br><span class="line"><span class="comment"># They cannot all exist in one children list for Supervisor.</span></span><br><span class="line"><span class="symbol">children:</span> [</span><br><span class="line">  %&#123;</span><br><span class="line">    <span class="symbol">id:</span> <span class="title class_">Child</span>,</span><br><span class="line">    <span class="symbol">start:</span> &#123;<span class="title class_">Child</span>, <span class="symbol">:start_link</span>, [[]]&#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  &#123;<span class="title class_">Child</span>, []&#125;,</span><br><span class="line">  <span class="title class_">Child</span></span><br><span class="line">]</span><br></pre></td></tr></table></figure><p>If you are using the map form, it’s important to know that, the <code>id</code> field is used by the supervisor internally to identify the child.  Hence, even in our scenario with multi-level supervision, we do not need to use spider name to differentiate it besides module name.</p><p><strong>start_child&#x2F;2</strong></p><p>This is where you should pay attention to.</p><p>The first argument of the supervisor’s reference.  It can be PID or other name forms used in <strong>Name Registration</strong>.  </p><p>So in this spider scenario, the only place need to take care is the <code>Spider.Supervisor</code> where it starts the <code>Spider.Fetcher</code>.  </p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># The spec can be any one of the three forms above.</span></span><br><span class="line"><span class="comment"># The important thing is that the supervisor name matches the one used in start_link/3</span></span><br><span class="line"><span class="title class_">DynamicSupervisor</span>.start_child(<span class="symbol">:<span class="string">&quot;Spider.Supervisor.<span class="subst">#&#123;spider_name&#125;</span>&quot;</span></span>, spec)</span><br></pre></td></tr></table></figure><h2 id="End"><a href="#End" class="headerlink" title="End"></a>End</h2><p>I hope this more sophisticated and real world example can help you understand the OTP Supervision more clearly.</p><p>Be used to model the system by process and modeling them correctly are just the first step on learning OTP.  Next, it would be the message passing between them for coordination.  I will share more when this web crawling project goes.</p><p>Please don’t hesitate to leave a comment if you have anything supplement or good advice.</p>]]></content>
    
    
      
      
    <summary type="html">&lt;p&gt;The most fantastic concepts in Erlang &amp;amp; Elixir that fascinate me are:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Everything can be a process.&lt;/li&gt;
&lt;li&gt;Let it crash</summary>
      
    
    
    
    <category term="Sword" scheme="http://www.thinkingincrowd.me/categories/Sword/"/>
    
    
    <category term="Elixir" scheme="http://www.thinkingincrowd.me/tags/Elixir/"/>
    
    <category term="Supervisor" scheme="http://www.thinkingincrowd.me/tags/Supervisor/"/>
    
    <category term="OTP" scheme="http://www.thinkingincrowd.me/tags/OTP/"/>
    
  </entry>
  
  <entry>
    <title>It&#39;s not that easy to configure mnesia dir as I thought</title>
    <link href="http://www.thinkingincrowd.me/2020/05/31/not-that-easy-to-configure-mnesia-dir-as-i-thought/"/>
    <id>http://www.thinkingincrowd.me/2020/05/31/not-that-easy-to-configure-mnesia-dir-as-i-thought/</id>
    <published>2020-05-31T15:05:16.000Z</published>
    <updated>2022-08-28T08:07:15.453Z</updated>
    
    <content type="html"><![CDATA[<h2 id="Why-Directory-is-Required"><a href="#Why-Directory-is-Required" class="headerlink" title="Why Directory is Required"></a>Why Directory is Required</h2><p>After using「<a href="http://www.thinkingincrowd.me/2020/04/16/One-Elixir-Code-for-Both-Mnesia-Master-Child/">One Elixir Code for Both Mnesia Master &amp; Child</a>」locally for basic testing, next step is to explore how to easily deploy to remote server.</p><p>Regarding the deployment, I am using Ansible + Mix Release, instead of Docker.  The main reason is to use native tools as much as possible within Elixir ecosystem as this is the main approach of learning one language.</p><p>Before using Mnesia, configuring one data directory for it is very important.</p><p>Theoretically, Mnesia creates one data directory, as format <code>NODE_NAME@HOST</code>, automatically in the same level of the program running directory even though you do not provide the parameter for it.  However, this is not one good approach.  Compared to the program or code directory, data directory should be permanent.  Because every time you deploy a new version of the code to the server, it should have a separate directory in order to keep track of the record or even for emergent fallback.  While data directory should be consistent on matter how many version of program code you deployed.</p><h2 id="The-Mix-Release-Way"><a href="#The-Mix-Release-Way" class="headerlink" title="The Mix Release Way"></a>The Mix Release Way</h2><p>When we use <code>mix release.init</code> to prepare files for release, one file named <code>vm.args.eex</code> will be generated.  This file contains the Erlang VM parameter we want to pass.  It will be renamed to <code>vm.args</code> during package generation.</p><p>But, if we set directory path in <code>vm.args.eex</code>, it becomes one compile-time configuration, instead of one run-time parameter.  How can one single release package run using different data directory?  And why would I want to do that?</p><h2 id="Multi-Site-High-Availability-amp-Blue-Green-Deployment"><a href="#Multi-Site-High-Availability-amp-Blue-Green-Deployment" class="headerlink" title="Multi-Site High Availability &amp; Blue Green Deployment"></a>Multi-Site High Availability &amp; Blue Green Deployment</h2><p>Through below steps, no matter using one or multiple machines:  </p><ol><li>Setup data directory A, point server A to it.  </li><li>Setup data directory B, point server B to it.  </li><li>Stop server A, deploy new version A+ and point to data directory A, restarts A+.  </li><li>Stop server B, deploy new version B+ and point to data directory B, restarts B+.</li></ol><p>we can have at least one running Mnesia and Elixir nodes any time achieving multi-site HA and blue green deployment without stopping the system.</p><p><em>Note: For a Mnesia cluster, we should not stop all nodes.  If they must be stopped for some reasons, the restart sequence should be the opposive of stopping sequence.  For example, if you stop the nodes in sequence of AB, then the starting sequence should be BA.</em></p><h2 id="Parameter-format-in-vm-args"><a href="#Parameter-format-in-vm-args" class="headerlink" title="Parameter format in vm.args"></a>Parameter format in vm.args</h2><p>According to the tips in <code>vm.args</code>, I checked <a href="http://erlang.org/doc/man/erl.html">http://erlang.org/doc/man/erl.html</a>, but still have no idea on how mensia directory should be set.  Based on the material I collected and testing done before, there are a couple of ways to set the dir parameter:  </p><ul><li>Through command line parameter: <code>iex --erl &#39;-mnesia dir &quot;path/to/db&quot;&#39; -S mix</code>  </li><li>Setup in Elixir <code>config.exs</code>: <code>config :mnesia, dir: &#39;path/to/db&#39;</code></li></ul><p>However, no matter I set <code>-mnesia dir &quot;path/to/db&quot;</code> or <code>-mnesia dir &#39;path/to/db&#39;</code> in <code>vm.args</code>, it always has below error while run <code>:mnesia.info</code> after server starts:  </p><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">** (exit) &#123;:aborted, &#123;:application_load_error, &#123;:bad_environment_value, &#x27;path/to/db&#x27;&#125;&#125;&#125;</span><br></pre></td></tr></table></figure><p>After some googling, I updated the setting based on one comment in <a href="https://stackoverflow.com/questions/23635474/how-to-specify-directory-for-mnesia-in-cowboy-application">Stackoverflow</a> and change it to <code>-mnesia &#123;dir,&#39;path/to/db&#39;&#125;</code>.  Although no more error, Mnesia was still not picking up the directory I provided.  </p><p>Come on, what should be the right format?  </p><h2 id="The-Right-Way-to-Debug"><a href="#The-Right-Way-to-Debug" class="headerlink" title="The Right Way to Debug"></a>The Right Way to Debug</h2><p>Why it does not work?  Incorrect parameter, or anything else?  </p><p>Debugging and finding the root cause is one fundamental and important skill as a developer.  Many inexperienced developer feels helpless once nothing can be found in Google or Stackoverflow.  </p><p>Actually, the real problem now is: I do not know whether the Erlang VM receives the parameter or not.  </p><p>Hence, the approach to dig out the cause should be:  </p><ol><li>Find out what the system state should be when it’s working properly.</li><li>Based on the normal system state as baseline, we can tell if the parameter is accepted or not.</li><li>If aligned, non-parameter setup issue; Else, it should be.</li></ol><p>With the help of Google, Erlang method <code>init.get_arguments</code> can be used to check all command line parameters and system flags.</p><p>Below is the output after configuring <code>-mnesia &#123;dir,&#39;path/to/db&#39;&#125;</code> in <code>vm.args</code>.  Judging from other parameters, such as <code>boot_var</code>, it should still be invalid parameter issue although it does not have any error during system startup.</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">iex(mgr<span class="variable">@127</span>.<span class="number">0.0</span>.<span class="number">1</span>)<span class="number">2</span>&gt; <span class="symbol">:init</span>.get_arguments</span><br><span class="line">[</span><br><span class="line">  <span class="symbol">root:</span> [<span class="string">&#x27;path/to/_build/prod/rel/mgr&#x27;</span>],</span><br><span class="line">  <span class="symbol">progname:</span> [<span class="string">&#x27;erl&#x27;</span>],</span><br><span class="line">  <span class="symbol">home:</span> [<span class="string">&#x27;/Users/kenchen&#x27;</span>],</span><br><span class="line">  <span class="symbol">kernel:</span> [<span class="string">&#x27;shell_history&#x27;</span>, <span class="string">&#x27;enabled&#x27;</span>],</span><br><span class="line">  <span class="symbol">elixir:</span> [<span class="string">&#x27;ansi_enabled&#x27;</span>, <span class="string">&#x27;true&#x27;</span>],</span><br><span class="line">  <span class="symbol">noshell:</span> [],</span><br><span class="line">  <span class="symbol">mode:</span> [<span class="string">&#x27;embedded&#x27;</span>],</span><br><span class="line">  <span class="symbol">setcookie:</span> [<span class="string">&#x27;spider&#x27;</span>],</span><br><span class="line">  <span class="symbol">name:</span> [<span class="string">&#x27;mgr@127.0.0.1&#x27;</span>],</span><br><span class="line">  <span class="symbol">config:</span> [<span class="string">&#x27;path/to/_build/prod/rel/mgr/tmp/mgr-0.0.1-20200531112256-c4fe.runtime&#x27;</span>],</span><br><span class="line">  <span class="symbol">boot:</span> [<span class="string">&#x27;path/to/_build/prod/rel/mgr/releases/0.0.1/start&#x27;</span>],</span><br><span class="line">  <span class="symbol">boot_var:</span> [<span class="string">&#x27;RELEASE_LIB&#x27;</span>,</span><br><span class="line">   <span class="string">&#x27;path/to/_build/prod/rel/mgr/lib&#x27;</span>],</span><br><span class="line">  <span class="symbol">mnesia:</span> [<span class="string">&#x27;&#123;dir,path/to/db&#125;&#x27;</span>]</span><br><span class="line">]</span><br></pre></td></tr></table></figure><p>Below is the ouput after starting system with command <code>iex --erl &#39;-mnesia dir &quot;path/to/db&quot;&#39; -S mix</code>.  </p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">iex(mgr<span class="variable">@127</span>.<span class="number">0.0</span>.<span class="number">1</span>)<span class="number">2</span>&gt; <span class="symbol">:init</span>.get_arguments</span><br><span class="line">[</span><br><span class="line">  <span class="symbol">root:</span> [<span class="string">&#x27;path/to/_build/prod/rel/mgr&#x27;</span>],</span><br><span class="line">  <span class="symbol">progname:</span> [<span class="string">&#x27;erl&#x27;</span>],</span><br><span class="line">  <span class="symbol">home:</span> [<span class="string">&#x27;/Users/kenchen&#x27;</span>],</span><br><span class="line">  <span class="symbol">kernel:</span> [<span class="string">&#x27;shell_history&#x27;</span>, <span class="string">&#x27;enabled&#x27;</span>],</span><br><span class="line">  <span class="symbol">elixir:</span> [<span class="string">&#x27;ansi_enabled&#x27;</span>, <span class="string">&#x27;true&#x27;</span>],</span><br><span class="line">  <span class="symbol">noshell:</span> [],</span><br><span class="line">  <span class="symbol">mode:</span> [<span class="string">&#x27;embedded&#x27;</span>],</span><br><span class="line">  <span class="symbol">setcookie:</span> [<span class="string">&#x27;spider&#x27;</span>],</span><br><span class="line">  <span class="symbol">name:</span> [<span class="string">&#x27;mgr@127.0.0.1&#x27;</span>],</span><br><span class="line">  <span class="symbol">config:</span> [<span class="string">&#x27;path/to/_build/prod/rel/mgr/tmp/mgr-0.0.1-20200531112256-c4fe.runtime&#x27;</span>],</span><br><span class="line">  <span class="symbol">boot:</span> [<span class="string">&#x27;path/to/_build/prod/rel/mgr/releases/0.0.1/start&#x27;</span>],</span><br><span class="line">  <span class="symbol">boot_var:</span> [<span class="string">&#x27;RELEASE_LIB&#x27;</span>,</span><br><span class="line">   <span class="string">&#x27;path/to/_build/prod/rel/mgr/lib&#x27;</span>],</span><br><span class="line">  <span class="symbol">mnesia:</span> [<span class="string">&#x27;dir&#x27;</span>, <span class="string">&#x27;&quot;path/to/db&quot;&#x27;</span>]</span><br><span class="line">]</span><br></pre></td></tr></table></figure><p>We can see that, <code>&#39;&quot;path/to/db&quot;&#39;</code> should be the correct format Erlang VM recognizes.  It has both double quote and single quote.  When I changed the parameter to be <code>-mnesia dir &#39;&quot;path/to/db&quot;&#39;</code> in file <code>vm.args</code>, problem solved.</p><p><em>Note: I found that the Mnesia official documentation has stated the command to start Mnesia and pass parameter: <code>erl -mnesia dir &#39;&quot;/tmp/funky&quot;&#39;</code>.  Although it is not exactly saying what to set in vm.args, it is still a good hint if I read this in advance.</em></p><h2 id="Ansible"><a href="#Ansible" class="headerlink" title="Ansible"></a>Ansible</h2><p>I only solves part of the puzzle after resovling previous issue.  How can I use Ansible to dynamically configure the parameter and add it to <code>vm.args</code>?</p><p>In the Ansible playbook, I define a task:  </p><figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="bullet">-</span> <span class="attr">name:</span> <span class="string">update</span> <span class="string">mnesia</span> <span class="string">path</span> <span class="string">in</span> <span class="string">vm.args</span></span><br><span class="line">  <span class="attr">shell:</span> <span class="string">&quot;echo -mnesia dir <span class="template-variable">&#123;&#123; data_root &#125;&#125;</span> &gt;&gt; <span class="template-variable">&#123;&#123; release_root &#125;&#125;</span>/vm.args&quot;</span></span><br><span class="line">  <span class="attr">args:</span></span><br><span class="line">    <span class="attr">executable:</span> <span class="string">/bin/bash</span></span><br></pre></td></tr></table></figure><p>Because the Mnesia dir parameter requires both double quote and single quote, I was beaten heavily on trying to escape them in late night.</p><p>But it does not take me a long time after clearing my mind by breaking down the issue.</p><ol><li>How to escape single or double quote in shell.  </li><li>How to escape single or double quote in Yaml.</li></ol><p>It’s not difficult to do that in shell：<code>echo -mnesia dir &quot;&#39;\&quot;/path/to/db\&quot;&#39;&quot; &gt;&gt; ~/test.txt</code>.</p><p>But it’s a little bit more complicated in Yaml, especially when you are using double quote scala.</p><ul><li>In double quote scala, it uses <code>\</code> to escape double quote, such as <code>&quot;here&#39;s to \&quot;quotes\&quot;&quot;</code>.</li></ul><p>And so the Ansible task should be:  </p><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">shell: &quot;echo -mnesia dir \&quot;&#x27;\\\&quot;&#123;&#123; data_root &#125;&#125;\\\&quot;&#x27;\&quot; &gt;&gt; &#123;&#123; release_root &#125;&#125;/vm.args&quot;</span><br></pre></td></tr></table></figure><ul><li>In single quote scala, it needs to duplicate single quote to escape, such as <code>&#39;here&#39;&#39;s to &quot;quotes&quot;&#39;</code>.</li></ul><p>And so the Ansible task should be:  </p><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">shell: &#x27;echo -mnesia dir &quot;&#x27;&#x27;\&quot;&#123;&#123; data_root &#125;&#125;\&quot;&#x27;&#x27;&quot; &gt;&gt; &#123;&#123; release_root &#125;&#125;/vm.args&#x27;</span><br></pre></td></tr></table></figure><p>I never thought so much trouble needs to go through in order to set the dir parameter right for Mnesia.  </p>]]></content>
    
    
      
      
    <summary type="html">&lt;h2 id=&quot;Why-Directory-is-Required&quot;&gt;&lt;a href=&quot;#Why-Directory-is-Required&quot; class=&quot;headerlink&quot; title=&quot;Why Directory is Required&quot;&gt;&lt;/a&gt;Why Directo</summary>
      
    
    
    
    <category term="Sword" scheme="http://www.thinkingincrowd.me/categories/Sword/"/>
    
    
    <category term="Elixir" scheme="http://www.thinkingincrowd.me/tags/Elixir/"/>
    
    <category term="Mnesia" scheme="http://www.thinkingincrowd.me/tags/Mnesia/"/>
    
  </entry>
  
  <entry>
    <title>Unsolved puzzle of mnesia behavior in mix test</title>
    <link href="http://www.thinkingincrowd.me/2020/04/28/Unsolved-puzzle-of-mnesia-behavior-in-mix-test/"/>
    <id>http://www.thinkingincrowd.me/2020/04/28/Unsolved-puzzle-of-mnesia-behavior-in-mix-test/</id>
    <published>2020-04-28T13:23:35.000Z</published>
    <updated>2022-08-28T08:07:15.452Z</updated>
    
    <content type="html"><![CDATA[<p>Recently, I am evaluating the usage of Mnesia in Elixir.</p><p>After figuring out how to use <a href="http://www.thinkingincrowd.me/2020/04/16/One-Elixir-Code-for-Both-Mnesia-Master-Child/">One Elixir Code for Both Mnesia Master &amp; Child</a>, I moved on to data CRUD operation.  </p><p>Before writing actual testing code, in order to make each test independent, I need to first complete the setup and teardown tasks between each test.</p><h2 id="Test-Callbacks"><a href="#Test-Callbacks" class="headerlink" title="Test Callbacks"></a>Test Callbacks</h2><p>In Elixir, these callbacks can be used:  </p><ul><li><code>setup_all</code>: Invoked once per module before any test is run.  </li><li><code>setup</code>: Invoked once before each test.  </li><li><code>on_exit</code>: Registered on demand during setup.</li></ul><p><em>Tips</em>: Multiple <code>setup</code> and <code>setup_all</code> are allowed.  They are invoked in sequence.  Failures in <code>setup_all</code> or <code>setup</code> will stop all remaining setup callbacks from executing while <code>on_exit</code> will always run.  </p><p>The test script looks like this:  </p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">defmodule</span> <span class="title">Sample.MnesiaTest</span></span> <span class="keyword">do</span></span><br><span class="line">  <span class="keyword">use</span> <span class="title class_">ExUnit</span>.<span class="title class_">Case</span></span><br><span class="line">  <span class="keyword">alias</span> <span class="symbol">:mnesia</span>, <span class="symbol">as:</span> <span class="title class_">Mnesia</span></span><br><span class="line"></span><br><span class="line">  <span class="title class_">ExUnit</span>.<span class="title class_">Case</span>.register_attribute(__MODULE__, <span class="symbol">:mnesia_table</span>, <span class="symbol">accumulate:</span> <span class="literal">true</span>)</span><br><span class="line"></span><br><span class="line">  <span class="variable">@node_list</span> [node()]</span><br><span class="line"></span><br><span class="line">  setup_all <span class="keyword">do</span></span><br><span class="line">    on_exit <span class="keyword">fn</span> -&gt;</span><br><span class="line">      <span class="title class_">Mnesia</span>.stop()</span><br><span class="line">      <span class="title class_">Mnesia</span>.delete_schema(<span class="variable">@node_list</span>)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">    <span class="title class_">Mnesia</span>.create_schema(<span class="variable">@node_list</span>)</span><br><span class="line">    <span class="title class_">Mnesia</span>.start()</span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">  setup context <span class="keyword">do</span></span><br><span class="line">    on_exit <span class="keyword">fn</span> -&gt;</span><br><span class="line">      <span class="title class_">Enum</span>.each(context.registered[<span class="symbol">:mnesia_table</span>], <span class="keyword">fn</span> table -&gt;</span><br><span class="line">        <span class="title class_">Mnesia</span>.delete_table(table)</span><br><span class="line">      <span class="keyword">end</span>)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">  <span class="variable">@mnesia_table</span> <span class="symbol">:test</span></span><br><span class="line">  test <span class="string">&quot;Create table&quot;</span>, _context <span class="keyword">do</span></span><br><span class="line">    // <span class="title class_">Dummy</span> test code</span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">  <span class="variable">@mnesia_table</span> <span class="symbol">:test</span></span><br><span class="line">  test <span class="string">&quot;Insert Data&quot;</span>, _context <span class="keyword">do</span></span><br><span class="line">    // <span class="title class_">Dummy</span> test code</span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><ul><li>Attribute <code>:mnesia_table</code> is registered and used on each test to annotate the table name within the following test.  </li><li>In <code>setup_all</code>, it performs steps to bring up the whole Mnesia and shutdown.  </li><li>In <code>setup</code>, it destroys the tables used in each test annotated by the <code>:mnesia_table</code> attribute.</li></ul><p>I set the <code>accumulate: true</code> so that we can specify multiple <code>@mnesia_table</code> attributes and so the value of <code>context.registered[:mnesia_table]</code> is a list.  </p><p><em>Tips</em>: Attribute, similar to tag, is cleared after each test.  The difference is that when a tag is given more than once, the last value wins.</p><h2 id="Puzzle"><a href="#Puzzle" class="headerlink" title="Puzzle"></a>Puzzle</h2><p>Everything sounds smooth but I noticed one thing after running <code>mix test</code>, the mnesia directory still has files inside.  Shouldn’t all files removed after calling <code>delete_schema</code>?  But the result of <code>delete_schema</code> returns <code>:ok</code> when I suspected its failure and printed it.  </p><p>Later, I realized that the mnesia directory contains the table name used in the application startup logic prepared last week.  It’s the table and schema created during the application startup when running <code>mix test</code>.  </p><img alt="Mnesia test in umbrella project" src="https://raw.githubusercontent.com/kenspirit/blog-cdn-data/master/mnesia_test_in_umbrella.png"/><p>Below is the observation of the puzzle:</p><ol><li>If <code>mix test</code> is run under umbrella root, the mnesia directory is generated under root and the files cannot be removed.  </li><li>However, if <code>mix test</code> is run under the folder of <code>app\mgr</code> where the mnesia startup and setup logic exists, the mnesia directory is generated there but the files can be removed.  </li><li>If I add <code>@moduletag :no_start</code> to the test module, add below code to the umbrella root <code>mix.exs</code>, and then run <code>mix ut</code>, the behavior just like running <code>mix test</code> in <code>app\mgr</code>.</li></ol><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">project</span></span> <span class="keyword">do</span></span><br><span class="line">  [</span><br><span class="line">    ...</span><br><span class="line">    <span class="symbol">aliases:</span> [<span class="symbol">ut:</span> <span class="string">&quot;test --no-start --only no_start&quot;</span>],</span><br><span class="line">    <span class="symbol">preferred_cli_env:</span> [<span class="symbol">ut:</span> <span class="symbol">:test</span>]</span><br><span class="line">  ]</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><p>Looks like there is something mysterious of the umbrella project causing the mnesia directory issue.  </p><p>It took me hours to try to figure out why but no luck.  </p><p>Before I got desperate and gave up, I found that the problem can be solved after I changed the <code>config.exs</code> following the suggestion in <a href="https://github.com/Nebo15/ecto_mnesia/issues/40">https://github.com/Nebo15/ecto_mnesia/issues/40</a>:  </p><p>from</p><p><code>config :mnesia, dir: &#39;mnesia.#&#123;Mix.env&#125;.#&#123;node()&#125;&#39;</code></p><p>to</p><p><code>config :mnesia, dir: to_charlist Path.join(File.cwd!, &#39;mnesia.#&#123;Mix.env&#125;.#&#123;node()&#125;&#39;)</code></p><p>Although the problem can be solved, the reason is still a puzzle remained.  Maybe it is the absolute and relative path handling issue of mnesia in umbrella project?  Your advice or explanation is greatly appreciated.  </p>]]></content>
    
    
      
      
    <summary type="html">&lt;p&gt;Recently, I am evaluating the usage of Mnesia in Elixir.&lt;/p&gt;
&lt;p&gt;After figuring out how to use &lt;a href=&quot;http://www.thinkingincrowd.me/2020</summary>
      
    
    
    
    <category term="Sword" scheme="http://www.thinkingincrowd.me/categories/Sword/"/>
    
    
    <category term="Elixir" scheme="http://www.thinkingincrowd.me/tags/Elixir/"/>
    
    <category term="Mnesia" scheme="http://www.thinkingincrowd.me/tags/Mnesia/"/>
    
  </entry>
  
  <entry>
    <title>One Elixir Code for Both Mnesia Master &amp; Child</title>
    <link href="http://www.thinkingincrowd.me/2020/04/16/One-Elixir-Code-for-Both-Mnesia-Master-Child/"/>
    <id>http://www.thinkingincrowd.me/2020/04/16/One-Elixir-Code-for-Both-Mnesia-Master-Child/</id>
    <published>2020-04-16T14:40:43.000Z</published>
    <updated>2022-08-28T08:07:15.452Z</updated>
    
    <content type="html"><![CDATA[<p>Mnesia is a native, persistent and distributed database in Erlang’s world.  If we want to use Erlang&#x2F;Elixir to build a fault-tolerance distributed application, Mnesia is quite attractive because it’s so closed to Erlang and has such great features:  </p><ul><li>Fast real-time key&#x2F;value lookup  </li><li>Complicated non-real-time queries mainly for operation and maintenance  </li><li>Distributed data because of distributed applications  </li><li>High fault tolerance  </li><li>Dynamic reconfiguration  </li><li>Complex objects</li></ul><p>To start using Mnesia, a couple of steps are required:  </p><ol><li>Specify a directory for data persistence</li><li>Create schema (Only for the first time usage)</li><li>Start Mnesia</li><li>Create tables when required</li></ol><p>It does not seems challenging at first glance.  However, it is if you think ahead on how it’s going to be used in dev, test and production environment with distributed nodes.  Let me elaborate why below.</p><h2 id="Specifying-Directory"><a href="#Specifying-Directory" class="headerlink" title="Specifying Directory"></a>Specifying Directory</h2><p>This sounds easy but devil lies in detail.  </p><h3 id="Use-Environment-Variable"><a href="#Use-Environment-Variable" class="headerlink" title="Use Environment Variable"></a>Use Environment Variable</h3><p>Below command can be used when starting up your elixir application and set the Mnesia directory with the environment variable.  </p><figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">iex --erl <span class="string">&#x27;-mnesia dir &quot;path/to/db&quot;&#x27;</span> -S mix</span><br></pre></td></tr></table></figure><p>However, it’s inconvenient as you have to constantly change the value for different environments, and nodes when testing distributed scenarios.</p><h3 id="Use-Mix-Config"><a href="#Use-Mix-Config" class="headerlink" title="Use Mix Config"></a>Use Mix Config</h3><p>The idea of using Mix Config may be your instant reaction after that.  We can setup in <code>config/config.exs</code> to fix above problems:  </p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">config <span class="symbol">:mnesia</span>, <span class="symbol">dir:</span> <span class="string">&#x27;mnesia.<span class="subst">#&#123;<span class="title class_">Mix</span>.env&#125;</span>.<span class="subst">#&#123;node()&#125;</span>&#x27;</span></span><br></pre></td></tr></table></figure><p><em>Notes:</em> <code>dir</code> path must use single quote.</p><p>The settings here can separate different environments for you easily.  However, as the Mix Config is compile-time setting, the <code>node()</code> might cause undesired effect because it’s the value <code>:nonode@nohost</code> evaluated in compile time.  That should not be the desired value you want to use in production environment.</p><h3 id="Use-Config-and-Release"><a href="#Use-Config-and-Release" class="headerlink" title="Use Config and Release"></a>Use Config and Release</h3><p>After Elixir 1.9, there is a new <code>Config</code> module as a replacement for <code>Mix.Config</code> and Mix Release is introduced.</p><p>We can setup a file named <code>releases.exs</code> in <code>config</code> folder along with <code>config.exs</code>:</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># In releases.exs file</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="title class_">Config</span></span><br><span class="line"></span><br><span class="line">config <span class="symbol">:mnesia</span>, <span class="symbol">dir:</span> <span class="title class_">System</span>.get_env(<span class="string">&quot;MNESIA_DIR&quot;</span>) || <span class="string">&#x27;mnesia_<span class="subst">#&#123;<span class="title class_">System</span>.get_env(<span class="string">&quot;RELEASE_NODE&quot;</span>)&#125;</span>&#x27;</span></span><br></pre></td></tr></table></figure><p>Then in <code>rel</code> folder created by <code>mix release.init</code>, we can update <code>env.sh.eex</code> or <code>env.bat.eex</code> to set above variables.  Normally, we just need to uncomment the last two lines in the file.  But I have two extra lines ahead to use the <code>HOST</code> and <code>NODE_NAME</code> variables so that I can easily change them for the node.</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#!/bin/sh</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># Sets and enables heart (recommended only in daemon mode)</span></span><br><span class="line"><span class="comment"># case $RELEASE_COMMAND in</span></span><br><span class="line"><span class="comment">#   daemon*)</span></span><br><span class="line"><span class="comment">#     HEART_COMMAND=&quot;$RELEASE_ROOT/bin/$RELEASE_NAME $RELEASE_COMMAND&quot;</span></span><br><span class="line"><span class="comment">#     export HEART_COMMAND</span></span><br><span class="line"><span class="comment">#     export ELIXIR_ERL_OPTIONS=&quot;-heart&quot;</span></span><br><span class="line"><span class="comment">#     ;;</span></span><br><span class="line"><span class="comment">#   *)</span></span><br><span class="line"><span class="comment">#     ;;</span></span><br><span class="line"><span class="comment"># esac</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># Set the release to work across nodes. If using the long name format like</span></span><br><span class="line"><span class="comment"># the one below (my_app@127.0.0.1), you need to also uncomment the</span></span><br><span class="line"><span class="comment"># RELEASE_DISTRIBUTION variable below.</span></span><br><span class="line"></span><br><span class="line"><span class="title class_">HOST</span>=<span class="variable">$&#123;</span><span class="symbol">HOST:</span><span class="number">-127.0</span>.<span class="number">0.1</span>&#125;</span><br><span class="line"><span class="title class_">NODE_NAME</span>=<span class="variable">$&#123;</span><span class="symbol">NODE_NAME:</span>-&lt;%= <span class="variable">@release</span>.name %&gt;&#125;</span><br><span class="line"></span><br><span class="line">export <span class="title class_">RELEASE_DISTRIBUTION</span>=name</span><br><span class="line">export <span class="title class_">RELEASE_NODE</span>=<span class="variable">$NODE_NAME</span>@<span class="variable">$HOST</span></span><br></pre></td></tr></table></figure><p>Once you have completed the setup above, you can update the <code>mix.exs</code> as below to build different releases and startup the apps with different node names as needed.</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">project</span></span> <span class="keyword">do</span></span><br><span class="line">  [</span><br><span class="line">    <span class="symbol">apps_path:</span> <span class="string">&quot;apps&quot;</span>,</span><br><span class="line">    <span class="symbol">version:</span> <span class="string">&quot;0.1.0&quot;</span>,</span><br><span class="line">    <span class="symbol">start_permanent:</span> <span class="title class_">Mix</span>.env() == <span class="symbol">:prod</span>,</span><br><span class="line">    <span class="symbol">deps:</span> deps(),</span><br><span class="line">    <span class="symbol">releases:</span> [</span><br><span class="line">      <span class="symbol">foo:</span> [</span><br><span class="line">        <span class="symbol">version:</span> <span class="string">&quot;0.0.1&quot;</span>,</span><br><span class="line">        <span class="symbol">applications:</span> [<span class="symbol">mgr:</span> <span class="symbol">:permanent</span>],</span><br><span class="line">        <span class="symbol">cookie:</span> <span class="string">&quot;thinkingincrowd&quot;</span></span><br><span class="line">      ],</span><br><span class="line">      <span class="symbol">bar:</span> [</span><br><span class="line">        <span class="symbol">version:</span> <span class="string">&quot;0.0.1&quot;</span>,</span><br><span class="line">        <span class="symbol">applications:</span> [<span class="symbol">worker:</span> <span class="symbol">:permanent</span>],</span><br><span class="line">        <span class="symbol">cookie:</span> <span class="string">&quot;thinkingincrowd&quot;</span></span><br><span class="line">      ]</span><br><span class="line">    ]</span><br><span class="line">  ]</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><h2 id="One-Elixir-Code"><a href="#One-Elixir-Code" class="headerlink" title="One Elixir Code"></a>One Elixir Code</h2><p>Now goes to the second step.</p><p>The API for Mnesia to create table schemas is:  </p><figure class="highlight erlang"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="title">create_schema</span><span class="params">(DiscNodes)</span> -&gt;</span> ok | &#123;error,Reason&#125;</span><br></pre></td></tr></table></figure><p>The <code>DiscNodes</code> parameters should include all <strong>alive</strong> Erlang nodes.  So people, at least me, may wonder how can I know all the node names ahead?  Isn’t a cluster supposed to be dynamic?</p><p>Why not do it in a more natural, lean and agile way instead?  We start only one node at the beginning and gradually add more nodes to form a cluster.  This approach is also applicable even if you know your nodes in advance.</p><h3 id="Mnesia-Startup-Customization"><a href="#Mnesia-Startup-Customization" class="headerlink" title="Mnesia Startup Customization"></a>Mnesia Startup Customization</h3><p>If we include the Mnesia into our Elixir application by putting it into <code>extra_applications</code> like <code>logger</code>, it will startup Mnesia automatically.  But this is not what we want if we have to do some customization and logic before that.</p><p>Instead, we should put it to the <code>included_applications</code> like this:</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">application</span></span> <span class="keyword">do</span></span><br><span class="line">  [</span><br><span class="line">    <span class="symbol">extra_applications:</span> [<span class="symbol">:logger</span>],</span><br><span class="line">    <span class="symbol">mod:</span> &#123;<span class="title class_">Sample</span>.<span class="title class_">Application</span>, []&#125;,</span><br><span class="line">    <span class="symbol">included_applications:</span> [<span class="symbol">:mnesia</span>]</span><br><span class="line">  ]</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><p>Then what should we do in the <code>start</code> function of <code>Sample.Application</code> before starting Mnesia up?</p><p>The difference between master node and later-joined child node is that the child knows which master node to refer to.  So, we can use an environment variable to distinguish the behavior during startup.  </p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">use</span> <span class="title class_">Application</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">start</span></span>(_type, _args) <span class="keyword">do</span></span><br><span class="line">  prepare_mnesia()</span><br><span class="line"></span><br><span class="line">  children = [</span><br><span class="line">    <span class="comment"># Starts a worker by calling: Sample.Worker.start_link(arg)</span></span><br><span class="line">    <span class="comment"># &#123;Sample.Worker, arg&#125;</span></span><br><span class="line">  ]</span><br><span class="line"></span><br><span class="line">  <span class="comment"># See https://hexdocs.pm/elixir/Supervisor.html</span></span><br><span class="line">  <span class="comment"># for other strategies and supported options</span></span><br><span class="line">  opts = [<span class="symbol">strategy:</span> <span class="symbol">:one_for_one</span>, <span class="symbol">name:</span> <span class="title class_">Sample</span>.<span class="title class_">Supervisor</span>]</span><br><span class="line">  <span class="title class_">Supervisor</span>.start_link(children, opts)</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">defp</span> <span class="title">prepare_mnesia</span></span> <span class="keyword">do</span></span><br><span class="line">  master_node = <span class="title class_">System</span>.get_env(<span class="string">&quot;MASTER_NODE&quot;</span>)</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> master_node == <span class="literal">nil</span> <span class="keyword">do</span></span><br><span class="line">    <span class="title class_">Sample</span>.<span class="title class_">Mnesia</span>.init_master()</span><br><span class="line">  <span class="keyword">else</span></span><br><span class="line">    <span class="title class_">String</span>.to_atom(master_node)</span><br><span class="line">    |&gt; <span class="title class_">Sample</span>.<span class="title class_">Mnesia</span>.add_self_to_cluster</span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><h3 id="Master-Node-Logic"><a href="#Master-Node-Logic" class="headerlink" title="Master Node Logic"></a>Master Node Logic</h3><p>In <code>Sample.Mnesia.init_master</code>, the operations should involve all the steps we listed at the very beginning.</p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">defmodule</span> <span class="title">Sample.Mnesia</span></span> <span class="keyword">do</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">alias</span> <span class="symbol">:mnesia</span>, <span class="symbol">as:</span> <span class="title class_">Mnesia</span></span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">def</span> <span class="title">init_master</span></span>() <span class="keyword">do</span></span><br><span class="line">    <span class="title class_">Mnesia</span>.stop()</span><br><span class="line"></span><br><span class="line">    node_list = [node()]</span><br><span class="line"></span><br><span class="line">    <span class="title class_">Mnesia</span>.create_schema(node_list)</span><br><span class="line"></span><br><span class="line">    <span class="title class_">Mnesia</span>.start()</span><br><span class="line"></span><br><span class="line">    <span class="title class_">Mnesia</span>.create_table(<span class="symbol">:sample</span>, [<span class="symbol">attributes:</span> [<span class="symbol">:id</span>, <span class="symbol">:title</span>, <span class="symbol">:content</span>, <span class="symbol">:tags</span>], <span class="symbol">index:</span> [<span class="symbol">:tags</span>], <span class="symbol">disc_copies:</span> node_list])</span><br><span class="line"></span><br><span class="line">    <span class="title class_">Mnesia</span>.wait_for_tables([<span class="symbol">:sample</span>], <span class="number">5_000</span>)</span><br><span class="line">  <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><p><em>Tips:</em> As <code>Mnesia.start()</code> is asynchronous, if we want do have operation on the tables, we should wait for them to be ready.  Function <code>wait_for_tables</code> is for such purpose.</p><h3 id="Client-Node-Logic"><a href="#Client-Node-Logic" class="headerlink" title="Client Node Logic"></a>Client Node Logic</h3><p>What need to be done if we try to add a new node into the cluster?  Let’s directly see the <code>add_self_to_cluster</code> function in <code>Sample.Mnesia</code>.  </p><figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add_self_to_cluster</span></span>(master_node) <span class="keyword">do</span></span><br><span class="line">  <span class="title class_">Node</span>.connect(master_node)</span><br><span class="line"></span><br><span class="line">  <span class="title class_">Mnesia</span>.start()</span><br><span class="line"></span><br><span class="line">  <span class="symbol">:rpc</span>.call(master_node, <span class="title class_">Sample</span>.<span class="title class_">Mnesia</span>, <span class="symbol">:add_child_to_cluster</span>, [node()])</span><br><span class="line"></span><br><span class="line">  <span class="title class_">Mnesia</span>.add_table_copy(<span class="symbol">:sample</span>, node(), <span class="symbol">:disc_copies</span>)</span><br><span class="line"></span><br><span class="line">  <span class="title class_">Mnesia</span>.wait_for_tables([<span class="symbol">:sample</span>], <span class="number">5_000</span>)</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add_child_to_cluster</span></span>(child_node) <span class="keyword">do</span></span><br><span class="line">  <span class="title class_">Mnesia</span>.change_config(<span class="symbol">:extra_db_nodes</span>, [child_node])</span><br><span class="line"></span><br><span class="line">  <span class="title class_">Mnesia</span>.change_table_copy_type(<span class="symbol">:schema</span>, child_node, <span class="symbol">:disc_copies</span>)</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure><ol><li>Connect the client Erlang node to master.  </li><li>Startup Mnesia locally.  </li><li>Remotely invoke master node’s <code>add_child_to_cluster</code> function:</li></ol><ul><li><code>change_config</code> adds the child node into the Mnesia nodes list.  Child node will has a copy of the schema at this point.  </li><li><code>change_table_copy_type</code> changes the schema table type in child node from <code>ram_copies</code> to <code>disc_copies</code>.</li></ul><ol start="4"><li>Function <code>add_table_copy</code> makes another copy of the desired table in child node to <code>disc_copies</code>.</li><li>Wait for the table to be ready.</li></ol><p><em>Tips:</em> If the <code>add_table_copy</code> is skipped, but you read the <code>:sample</code> table in child node, it actually goes to the master node to get the data.</p><h2 id="Wrap-Up"><a href="#Wrap-Up" class="headerlink" title="Wrap Up"></a>Wrap Up</h2><p>Above code is simple and some what naive, but it’s easy to have the basic understanding on what needs to be done.  </p><p>After the cluster is formed, when any of the node restarts, you do not need to provide the <code>MASTER_NODE</code> environment variable.  As the schemas and tables are created already, calling the function again will return <code>aborted</code> without harm.  </p><p>During the research, I have googled around and found some powerful library to help form the Elixr&#x2F;Mnesia clustering more intelligently.  You can take a look at them if you need more fancy features.  </p><p><a href="https://github.com/bitwalker/libcluster">https://github.com/bitwalker/libcluster</a></p><p><a href="https://github.com/beardedeagle/mnesiac">https://github.com/beardedeagle/mnesiac</a></p>]]></content>
    
    
      
      
    <summary type="html">&lt;p&gt;Mnesia is a native, persistent and distributed database in Erlang’s world.  If we want to use Erlang&amp;#x2F;Elixir to build a fault-toleran</summary>
      
    
    
    
    <category term="Sword" scheme="http://www.thinkingincrowd.me/categories/Sword/"/>
    
    
    <category term="Distributed" scheme="http://www.thinkingincrowd.me/tags/Distributed/"/>
    
    <category term="Elixir" scheme="http://www.thinkingincrowd.me/tags/Elixir/"/>
    
    <category term="Mnesia" scheme="http://www.thinkingincrowd.me/tags/Mnesia/"/>
    
  </entry>
  
  <entry>
    <title>一个疫情，让我更爱国</title>
    <link href="http://www.thinkingincrowd.me/2020/03/14/pandemic-makes-me-more-patriotic/"/>
    <id>http://www.thinkingincrowd.me/2020/03/14/pandemic-makes-me-more-patriotic/</id>
    <published>2020-03-14T09:53:36.000Z</published>
    <updated>2022-08-28T08:07:15.452Z</updated>
    
    <content type="html"><![CDATA[<p>2020，注定是世界再发生大变局的一年。</p><p>在这里，首先要感谢的是新浪微博，即便我也第一次享受到了禁言 30 天的待遇。但是，肺炎疑似事件和李文亮医生被训诫的消息，我最早就是从微博获取的。这也让我为家里准备到了 10 个基本的口罩。而且，微博上信息的快速流动，虽然传播了一些谣言，但我看到更多的是信息的透明传递，以便于监督，求助和援助。</p><p>从和老婆吵架，决定过年只待在珠海，到已经在家远程工作了好几周的今天，武汉湖北的疫情，全国各地的决策，慈善和援助的行动，国外的应对和民众行为，让我思考了很多。疫情应对真的是科学和人的结合。</p><h2 id="民族习惯"><a href="#民族习惯" class="headerlink" title="民族习惯"></a>民族习惯</h2><p>西方国家，推崇个人自由。不到非不得已，不可能实施封城这样的策略，也很难让民众接受。最开始意大利局部封城，都导致很多人不满，出来示威游行。</p><p>1918年导致全球 2000万人死亡的“西班牙流感”，欧洲强制要求民众带口罩，让大家认为带口罩是疫病的象征。美国当时还大肆反对。欧美的个人习惯是得病了才戴口罩。而我们的所谓保护自己，同时保护他人的想法，西方理解不了。</p><p>况且，国外还有反蒙面法，禁止公共场合遮盖脸部，仅仅露出眼睛。</p><p>而在亚洲，对戴口罩看的比较平常，甚至最近还是一种潮流，接受度比较高。</p><p>所以，结合民族习惯来看，需要肯定的是，在西方国家实施强制性戴口罩和隔离比较困难。</p><h2 id="理论和实践的差异"><a href="#理论和实践的差异" class="headerlink" title="理论和实践的差异"></a>理论和实践的差异</h2><p>顶级医学杂志《柳叶刀》说，没有证据表明，带口罩有助于防止被新冠病毒感染：</p><blockquote><p>there is no evidence that these masks prevent the acquisition of COVID-19, although they might slightly reduce the spread from an infected patient</p></blockquote><p>但是，我认为带口罩是有必要的:  </p><ol><li>不明确新冠是否会气溶胶传播。但当年的 SARS 似乎会。</li><li>不清楚新冠病人潜伏期多长。</li><li>目前病例说明病人在没任何外显征兆的情况下就具备传染性。</li><li>口鼻传播是肯定的。</li></ol><p>相信很多人都看过这个很搞笑又现实的视频。加州公共卫生官员 Sara Cody 刚在视频说完不要用手触摸脸部，然后就用舌头舔手指，翻阅笔记了。</p><p>我们是很习惯，且不经意地用手触碰头脸部的。<strong>知道怎么做，和是否能做到是两回事！</strong></p><p><strong>不能说理论上没法明确口罩不能防止感染，就否认它的积极性。“没有证据显示”这是一种误导。</strong></p><img alt="No Evidence is Misleading" src="https://raw.githubusercontent.com/kenspirit/blog-cdn-data/master/no-evidence-is-misleading.png"/><p>在那么多未知的情况下，口罩是一种阻碍，它减少了意外和不自觉。同时，口罩也是一种信号，可让我们意识到事情的严重性。对外，也减少病毒从患者留出，附着于公共区域。即便很大可能气溶胶传播不存在，那么，我们可以不用抢 N95，可以戴普通，可循环清洁的口罩，甚至一个口罩戴几天，只要小心保护，且不长时间在外。</p><p>所以，我认为现在国内情况稳定，就可以最大可能复工复产，但是依然坚持戴口罩。</p><h2 id="歧视和双标"><a href="#歧视和双标" class="headerlink" title="歧视和双标"></a>歧视和双标</h2><p>把疾病和人，和地区，和种族关联，很容易产生歧视。在国内，歧视外地，歧视湖北武汉，不让外地人进小区等行为都是可耻的。但国外也一样，带口罩的华人在欧洲，在美国被袭击，被刺。以前中国人在意大利被歧视，现在意大利的人逃出来，自己发现也被歧视了。<strong>要承认歧视的存在，并小心翼翼地确保自己不歧视，和保护自己</strong>。</p><p>面对未知、疾病、死亡，恐惧和躲避是人之常情。当时武汉封城前的人逃出来，很多人在骂。但是，想想如果那是你所在的地方，能逃肯定逃。只要逃出来时，注意保护身边的人，做好措施。有时候很难怪他们一开始撒谎，因为他们也知道歧视的存在。但是只要一逃出来马上去医院报道，隔离，我觉得这就尽责了。</p><p>民众歧视，官方则双标。纽约时报这次很好地说明了这一点。中国封城就“反人权”，意大利则“崇高”。</p><img alt="NT Double Standard" src="https://raw.githubusercontent.com/kenspirit/blog-cdn-data/master/nt-double-standard.jpg"/><h2 id="各政府的神操作"><a href="#各政府的神操作" class="headerlink" title="各政府的神操作"></a>各政府的神操作</h2><p>这次疫情中，各国政府对疫情的反应和表现可谓出乎很多人意料之外。</p><h3 id="中国"><a href="#中国" class="headerlink" title="中国"></a>中国</h3><p>国内，无论怎么说，一开始肯定是有地方瞒报的情况，不然不可能三次专家组派驻进场。对李文亮等医护人员警示的训诫和封锁，这两条板上钉钉的懒政和恶行，足以把当地官员翻个遍。还有，封城不果断，资源协调与调配工作的滞后，也可谓让人目瞪口呆。基本上都是慢半拍，甚至是反着来的。</p><p>幸亏中央及时出手，采取强硬措施，火速建方舱医院，调配全国的资源来援助，把猛烈的传染病迅速压制下来。这种执行力，和全国人民的配合措施，真的是放天下应该都不会再有另一个国家可以做到了。中国人民是真的伟大。</p><p>回过头来，很多人看到新加坡的“佛系”，沉稳，就说中国封城的措施太过了，没必要，导致很多中小企业活不下去等。这些人都是事后诸葛。</p><p>要知道，当时我们面临从未见过的病毒，不知道有多久的潜伏期，多大的传染性和致命性。而且，有迹象表明，传染性和致命性都比普通流感高很多，潜伏期又很长，也不明确传播方式。</p><p>在不知道传染的范围有多广，甚至在武汉和湖北可能已经传开了的情况，正值新春人口流动大潮，这个时候不采取强硬的措施是行不通的，因为你面临了太多的未知。如果不做这样的决定，可能后面全国各省，都会导致广泛传播，医疗资源匮乏，全国各省自救都无力了。危险初露，从重处理我觉得是理智的做法，这是为全国公共卫生安全的保障负责。</p><p>这么做了，即使后面发现病毒的传染或致命性不强，那仅牺牲一点经济，也可以很快恢复。可万一赌错了，严重到收拾不过来，对经济会有更大影响，恢复更难，接受更大的骂名。</p><p>当然，情况紧急，封城后对湖北省内资源的调配，市民的生活和医疗照顾，确实有很多地方做得还不到位。这些都是必须在执行强硬措施后不断跟上的。政府需要推出各方面措施，救援各大小企业，困难人士，比如免除一些税，五险一金等。因为这种强硬手段，没有大规模应对先例，而地方政府又不敢贸然做出决定，怕担责，措施就会滞后。向上级部门负责的方式，是值得反思和监督的。</p><p>总体来说，我觉得中央的决策是正确的。地方政府，我们看到有执行的好的地方，也有很多乱象，比如粗暴断路，抵制歧视外地人，暴力执法和禁言等，支持性措施也还不完善。</p><h3 id="新加坡"><a href="#新加坡" class="headerlink" title="新加坡"></a>新加坡</h3><p>新加坡其实并不“佛系”，它的沉稳，我觉得是建立在对病毒的清醒认识，以及严厉的监管措施之上的：</p><ol><li>最早对中国实施旅游禁令的国家之一</li><li>强制暂停大型集会，避免广泛的社区传播</li><li>指定 873 个感冒发热门诊</li><li>严格执行居家隔离，违者严刑峻法</li><li>政府信息公开，避免恐慌</li></ol><p>它的每一起病例，都非常细致地寻找关联和源头。通过严厉的措施，控制扩散，医疗资源也没有那么容易耗竭，最终治愈率也高。所以，它的上升速度慢。</p><p>但是，这也很可能难免有纰漏或意外的。那就是取决于病毒的潜伏性，传播率到底能有多长，多高。如果无症状的潜伏性太厉害，不小心扩散开，那就很麻烦。虽然是在赌，但是政府领导态度明确，重视。</p><p>我刚查了一下<a href="https://experience.arcgis.com/experience/7e30edc490a5441a874f9efe67bd8b89">新加坡最新情况</a>，在完全没有资源挤兑的情况下，截至三月十四号确诊 200，97 个出院，11 个危重。也就是说，5% 的重症率。但是，从三月六日到十三日，每天确诊人数比前段时间都高很多，每天都 10 个左右，而不是之前的三两个，感觉情况确诊数开始抬头，能不能继续佛系真的要斟酌。</p><h3 id="日本和韩国"><a href="#日本和韩国" class="headerlink" title="日本和韩国"></a>日本和韩国</h3><p>日本比较迷的操作就是让一整船人在上面自己隔离，措施又做得不好。如果可能，我觉得应该强制船上的成员下船，然后马上返回各自国籍所在。日本的国民，则返家或集中统一强制隔离。而不是让整船人在船上滞留，保护措施做得不好，还导致交叉传染。日本国内对新冠病毒的检测，条件要求严格，建议居家隔离，应该也是怕挤兑公共资源。日本感染和确诊数肯定是远远不止当前情况。但是日本目前重症数还没像武汉这样爆发，不知道是时间没到，还是日本人自我要求严格的作风使然。</p><p>韩国政府最迷的是那个新天地教会，故意到处去传染他人。当然，它的会长也被以杀人罪起诉。政府态度强硬，检测也非常迅猛到位，并且实施有监督的居家隔离，所以现在控制的还可以。</p><h3 id="西方"><a href="#西方" class="headerlink" title="西方"></a>西方</h3><p>西方这次疫情比较迷。最令人苦笑不得的操作，当然要数美国。</p><p>美国那边也是最开始对中国实施旅游禁令的国家，所以，让人感觉他们对这个病毒的态度应该是重视，并且觉得值得防范的。可是，特朗普对 COVID-19 却一直持续“流感化”叙述。什么大号流感啦，夏天来了很快就没啦，我们做得很好很全面，数字很快归零等。但是，不断的报道却让人们看到美国 CDC 和地方检测机构的怠慢，检测苛刻，还费用惊人。根据华大 UW 实验室三月十一日的检测，1300例，9%阳性。所以，美国其实感染人数肯定大大超越当前数字的。美国一开始责备中国隐瞒病情，然后严酷处理，侵犯人权，反应过度等。现在自己不也是隐瞒和怠慢？</p><p>欧洲那边呢，一开始也差不多这种策略。意大利有议员带口罩进入议会招群嘲。瑞士同样的场景，议员被逐出会议大厅。到现在，没办法了，则采取躺尸政策了。英国的防疫策略，是让慢慢地让每个人都得病，以获得群体免疫力，然后慢慢拖到夏天。瑞典也宣布“三不”，对疑似和轻症病人不测试、不追踪、不强制隔离，就是把新冠病毒当流感处理，因为国家没有那么多资源。</p><p>不知道那些之前喷武汉湖北官员让轻症者在家自我隔离的人，现在对于英国瑞士的策略是怎么看待这个问题。拖延政策，让疑似患者居家隔离，避免医疗资源挤兑，人群盲目聚集增加感染思路是对的。但是，这必须建立在检测快速完备，人群有清醒的防护意识，知道自己是不是确诊患者的基础上。必须像韩国那样。</p><p>但是，西方这些国家和人民的态度都比较散漫，和不在意。一开始还悠闲的参加集会，甚至不顾禁令坚持邮轮旅行。在患者没有病症就具备传染性的情况下，又没有快速检测和确诊信息，依靠个人自觉自我隔离，减少社交活动显然是不靠谱的。</p><p>当然最不靠谱就是 Trump 一开始各种吹牛B，传递信息错漏百出，初期不控制，慢慢事态严重才开始变强硬。Trump 刚表示自己接受了新冠检测，阴性。其实，刚开始写这篇文章的时候，我就想说：“希望他能感染一下，看看这个和大号流感的区别是什么。” 现在他已经确认没事，我才敢把这话放出来，不然好像太幸灾乐祸了。但是，最讨厌不尊重科学的人。</p><p>意大利就因为采取措施不及时，导致医疗挤兑，可能也因为老龄化，死亡率差不多去到 9%。我们的武汉和湖北的死亡率大概只是 4.5%。非湖北地区的死亡率大概是 0.9%。我对西方采取的软措施相当不乐观。</p><h2 id="国家之间的“友谊”"><a href="#国家之间的“友谊”" class="headerlink" title="国家之间的“友谊”"></a>国家之间的“友谊”</h2><p>国家之间的“友谊”啊，其实也在疫情很好地表现了一把。虽然说国家之间主要还是利益，但是还是看得出来，哪些相对没那么纯粹。</p><p>日本企业，民众自发捐赠口罩，防护服给中国，并留下一些相当美好的诗句：“山川异域，风月同天”，“岂曰无衣，与子同裳”。</p><p>伊朗，在本国资源和力量都不丰足的时候，第一批送达大量口罩，防护罩等援助。</p><p>美国的商务秘书长 Wilbur Ross 一月三十日在 Fox Business 上面说，<a href="https://www.foxbusiness.com/markets/coronavirus-jobs-north-america-wilbur-ross">新冠病毒可以帮助工作回流北美</a>。如果说以前灯塔国还有点原则，感觉现在就是赤裸裸的利益。</p><p>中国在疫情基本能控制之后，当然马上给予回报。安排专门的队伍，去支援伊拉克，意大利，伊朗。去意大利的队伍中，5位是四川专家，因为当初四川大地震的时候，意大利及时派驻14名专家，救助了 900 多人，还援助修建急救中心。</p><h2 id="唠叨"><a href="#唠叨" class="headerlink" title="唠叨"></a>唠叨</h2><p>说了这么多，只是希望大家看到更全面的一面。突发的传染病，对于任何国家来说，都是一大挑战。一国领导人，政府运作体系都很重要。民族的特点和参与也要充分考虑。</p><p>不要动不动就扯什么主义和政党，哪里都有做的好和不好的地方。双标不要太明显好不好？</p><p>自从上次 HK 事件以来，<a href="http://www.thinkingincrowd.me/2019/10/12/how-I-change-from-angry-youth-to-be-patriot/">灯塔国越来越让我失望</a>。中国也让我看到更多希望。希望这次的疫情，能让中国的民众及素质得到更大的提升，监督政府机构，团结发声。希望中国这篇土地上，勇敢的人越来越多，这才对得起李文亮。学习毛泽东的「论持久战」，坚定信念，对抗敌人。</p><blockquote><p>我认为中国最大的幸运，是生活在这片土地上的人民，总是被他们最勇敢的人保护得很好。<br> —  基辛格</p></blockquote>]]></content>
    
    
      
      
    <summary type="html">&lt;p&gt;2020，注定是世界再发生大变局的一年。&lt;/p&gt;
&lt;p&gt;在这里，首先要感谢的是新浪微博，即便我也第一次享受到了禁言 30 天的待遇。但是，肺炎疑似事件和李文亮医生被训诫的消息，我最早就是从微博获取的。这也让我为家里准备到了 10 个基本的口罩。而且，微博上信息的快速流动，虽</summary>
      
    
    
    
    <category term="Think" scheme="http://www.thinkingincrowd.me/categories/Think/"/>
    
    
    <category term="Politics" scheme="http://www.thinkingincrowd.me/tags/Politics/"/>
    
  </entry>
  
  <entry>
    <title>一文读懂 AWS S3</title>
    <link href="http://www.thinkingincrowd.me/2020/03/10/aws-s3/"/>
    <id>http://www.thinkingincrowd.me/2020/03/10/aws-s3/</id>
    <published>2020-03-10T02:16:06.000Z</published>
    <updated>2022-08-28T08:07:15.451Z</updated>
    
    <content type="html"><![CDATA[<p>AWS S3 全名是 Simple Storage Service，简便的存储服务。为什么这么起名啊？它：</p><ol><li>提供了统一的接口 REST&#x2F;SOAP 来统一访问任何数据</li><li>对 S3 来说，存在里面的数据就是对象名（键），和数据（值）</li><li>不限量，单个文件最高可达 5TB</li><li>高速。每个 bucket 下每秒可达 3500 PUT&#x2F;COPY&#x2F;POST&#x2F;DELETE 或 5500 GET&#x2F;HEAD 请求</li><li>具备版本，权限控制能力</li><li>具备数据生命周期管理能力</li></ol><p>作为一个对象存储服务，S3 功能真的很完备。如果不用搭梯子，访问快，我还真想过拿它来做自己的网盘。</p><h2 id="基本概念"><a href="#基本概念" class="headerlink" title="基本概念"></a>基本概念</h2><h3 id="Bucket"><a href="#Bucket" class="headerlink" title="Bucket"></a>Bucket</h3><p>要存储数据在 S3 里，首先我们要建立一个 Bucket。Bucket 默认是不公开的。</p><p>Bucket 有几个特点：  </p><ul><li>命名需全球唯一。每个帐号默认可建 100 个，可申请至最多 1000 个</li><li>创建者的拥有权不可转让，也不可以从一个 Region 转去别的 Region</li><li>没有对象存储数量限制</li></ul><p>Bucket 就像是电脑里面的某一个顶层分区。所有的对象都必须保存在某一个 bucket 下面。</p><h3 id="Object"><a href="#Object" class="headerlink" title="Object"></a>Object</h3><p>Bucket 里面每一个存储的数据就是对象，由对象名（键），和数据（值）组成。</p><p>对象的键（Key）可以很长，甚至按照一定前缀格式来指定，从而模拟文件夹的层级结构，比如 <code>Photo/Family/2020-01-25-new-year/altogether.jpg</code>。</p><p>每一个对象其实还包含一些元信息（Meta-data），包括系统指定的文件类型，创建时间，加密算法等，和用户上传时指定的元信息。元信息在对象创建后都无法更改。</p><p>我们也可以为对象指定最多 10个标签（Tag），标签的键和值的最大长度是 128 和 256 个字符。这个标签和元信息有什么不同呢？标签是可以修改和新增的。它最大的好处，是可以结合权限控制，生命周期管理，和数据分析等使用。</p><p>单个文件上传最大是 5GB。超过的话，需要使用 multipart upload API。最大支持 5TB。</p><h3 id="一致性特性"><a href="#一致性特性" class="headerlink" title="一致性特性"></a>一致性特性</h3><p>对程序员来说，这么一个类似数据库的东西，肯定需要关心它的读写特性和一致性模型。</p><ul><li><p>没有锁的功能。如果同时（几乎）发起两个更新对象的 PUT 请求，键相同，那么，以到达 S3 时间先后处理更新。</p></li><li><p>不同对象的更新，没法做到原子操作。</p></li><li><p>对全新的对象来说，它是 Read-after-Write Consistency 的。也就是写了之后马上读，肯定就是你刚才上传的数据。</p></li><li><p>如果你要更新数据，那就变成 Eventual Consistency 了。也就是说，更新后马上读，可能是旧的数据，也可能是新的。</p></li></ul><p>这里有一个比较坑的地方是，如果你先调用 GET 请求访问一个不存在的资源，S3 告诉你它不存在。然后你马上上传数据，再调用一个 GET，这时候是有可能拿不回来的。</p><h2 id="存储级别"><a href="#存储级别" class="headerlink" title="存储级别"></a>存储级别</h2><p>作为一个“云盘”，S3 的好处是可以把你存储的数据，按不同的存储级别来计费。这个存储级别是每个对象不同，上传时指定的。</p><p>我们看看不同的场景，应该选择哪种级别的存储：</p><ol><li>经常访问的数据对象</li></ol><ul><li>STANDARD - 这是最普通，最常用的类型</li><li>REDUCED_REDUNDANCY (RRS) - 不建议使用。仅为不重要，可再建数据设计，还有每年平均 0.01% 数据丢失的可能性。</li></ul><ol start="2"><li>按访问频率自动优化的数据</li></ol><ul><li>INTELLIGENT_TIERING - 可以智能地把不热门的数据自动转级别。但是，每个文件最低收费标准是 128KB，存 30天。</li></ul><ol start="3"><li>不经常访问的数据</li></ol><ul><li>STANDARD_IA</li><li>ONEZONE_IA</li></ul><p>  AWS 一个 Region，有两到三个 Zone。这两种级别的区别就是，One Zone 的数据就单点保存，丢了就丢了。</p><ol start="4"><li>归档的数据</li></ol><ul><li>S3 Glacier - 最低保存 90天。取出时间 1分钟至 12小时。</li><li>S3 Glacier Deep Archive - 最低保存 180天。默认 12小时内取出。</li></ul><p>S3 计费的大头主要是存储容量。但是，S3 还会按照数据获取的次数，和传输容量来计费。越不常访问的级别，虽然存储便宜，但是访问贵。INTELLIGENT_TIERING 还会收监测和管理费用。</p><h3 id="生命周期的管理"><a href="#生命周期的管理" class="headerlink" title="生命周期的管理"></a>生命周期的管理</h3><p>除了手动指定，或者使用 INTELLIGENT_TIERING 外，S3 其实还可以让我们在 bucket 上定义生命周期管理的策略（Policy），来自动转换对象的存储级别。</p><p>生命周期的管理可以做到：</p><ol><li>转换存储级别</li><li>过期删除</li></ol><h2 id="数据安全"><a href="#数据安全" class="headerlink" title="数据安全"></a>数据安全</h2><p>数据安全，是数据存储服务非常重要的一部分。S3 提供了很多方面的功能来保障这一点。</p><h3 id="多版本"><a href="#多版本" class="headerlink" title="多版本"></a>多版本</h3><p>不小心把数据删除了的痛，程序员应该都懂。但是，后悔药是没有的。所以，我们很多时候并不会做永久删除，而是实现软删除的功能。S3 就提供了多版本的功能。只要 bucket 打开了多版本的选项，每次对象的更新都会新加一个版本，而不是覆盖。删除对象，也只是新增一个删除标识。</p><p>当然，你要强行删除特定版本的数据也是可以的，它只是让这件事变得难一些而已。它甚至可以把 bucket 设置成只有通过 MFA 认证的请求才能实现永久删除。</p><p>要注意的是：</p><ol><li>打开版本控制的 bucket，是没法关闭的，顶多可以暂停。也就是说，暂停后的 bucket，新加对象的时候，版本 id 会设为 null。</li><li>无论打开，或者暂停版本控制，对 bucket 内已经存在的对象是没有影响的。</li></ol><h3 id="锁定"><a href="#锁定" class="headerlink" title="锁定"></a>锁定</h3><p>除了使用多版本控制让覆盖或者删除变得更难，S3 还可以锁定特定版本的对象。这种模型被称为 write-once-read-many (WORM)。</p><p>有两种锁定的方式：</p><ul><li>设定保留期限 - 在某固定期限内，对象 WORM。</li><li>法定留存 - 仅当这个留存标识被删除后，对象才能被覆盖或删除。</li></ul><p>一个特定版本的对象，可以同时设置这两种保护，或任意一种。</p><p>因为锁定是针对特定版本的对象，如果你的更改或删除操作请求只根据对象的键，那它还是允许你新增一个版本，或加上删除标识。只是这个锁定，还能防止对象因为生命周期的设置而被删除掉。</p><h3 id="服务端加密"><a href="#服务端加密" class="headerlink" title="服务端加密"></a>服务端加密</h3><p>数据传输过程（in-transit）中的保护，现在基本都由 SSL&#x2F;TLS 来实现的。AWS 也提供 VPN 或者网络直连服务。</p><p>S3 提供了服务端数据加密的功能，可实现数据的存储（at rest）方面的安全。不过它只支持对称加密，不支持非对称加密。虽然你可以本地把数据加密了再上传到 S3，但是，这需要自己保护好密钥，其实更不容易。</p><p>服务端加密开启后，bucket 内已经存在的对象不会被自动加密。而且，只有数据被加密，元信息（meta data），标签（Tag）不会被加密。</p><p>S3 的服务端加密有三种方式：  </p><ol><li>SSE-S3 - S3 自管理的密钥，使用 AES-256 加密算法。每个对象的密钥不同，并且它还被定期更换的主密钥同时加密。</li><li>SSE-KMS - 密钥存放在 KMS（软硬件结合的密钥管理系统）。</li><li>SSE-C - 在请求时自己提供密钥，S3 只管加解密逻辑和存储。S3 不保存密钥，只保存随机加盐的 HMAC 值来验证今后请求的合法性。</li></ol><p>这里主要说一下 S3 使用 SSE-KMS 特点：</p><ul><li>启用前，如果没有指定客户管理的 CMK（customer master key），S3 会自动创建一个由 AWS 管理的 CMK</li><li>加密数据的密钥，同时也被加密，并和数据保存在一起</li><li>有请求频率限制</li><li>只支持对称密钥</li><li>CMK 必须和 bucket 在同一个区（Region）</li></ul><h3 id="IAM-集成"><a href="#IAM-集成" class="headerlink" title="IAM 集成"></a>IAM 集成</h3><p><a href="http://www.thinkingincrowd.me/2020/02/16/aws-iam/">前一篇文章</a> 详细介绍了 AWS IAM 的功能，S3 当然能根据 IAM 的设置来控制权限。S3 的资源，除了 bucket 和 object 外，还包含了一些子资源。</p><p>Bucket 子资源:</p><ul><li>lifecycle</li><li>website</li><li>versioning</li><li>policy</li><li>cors</li><li>logging</li></ul><p>Object 子资源:</p><ul><li>acl</li><li>restore</li></ul><p>在了解 S3 如何控制权限以前，我们要理解资源的拥有者这个概念。在 S3 里面，资源是谁创建的，它所属的 AWS 帐号，就是这个资源的拥有者。有一种情况是，Bucket 是帐号 A 创建的。但是 A 允许 B 在里面创建对象 X。这个 X 的拥有者是 B 而不是 A。如果资源拥有者授权 A，A 可以把自己的权限委托给自己帐号内的其它人，但不可以再一次跨帐号授权。</p><h3 id="S3-如何验证请求"><a href="#S3-如何验证请求" class="headerlink" title="S3 如何验证请求"></a>S3 如何验证请求</h3><p>当 S3 收到请求时，会经过下面几个步骤验证请求：</p><ol><li>把所有相关的策略（user policy, bucket policy, ACL）集合起来。</li><li>根据下面 3 小步，拿出全集中的合适子集来分别验证：</li></ol><ul><li><p>用户范畴<br>如果请求发起者是 IAM User 或 Role，它所属的 aws 帐号就会先检查它是否有权限做这种类型的操作（user policy）。假如刚好要操作的资源（bucket 或 object）属于当前帐号，那么就同时检查相应的 bucket policy, bucket ACL 和 object ACL。</p><p>如果请求发起者不属于 IAM，则跳至下一步。</p></li><li><p>Bucket 范畴<br>S3 会检查拥有 bucket 的 aws 帐号的策略。</p><p>如果操作的是 bucket，那请求的用户需要有 bucket owner 赋予的权限。<br>如果操作的是对象，需要检查 bucket owner 是否有显式 deny 对象的设置。</p></li><li><p>Object 范畴<br>当请求是关于对象的时，最后检查对象 owner 的策略子集。</p></li></ul><p>天啊，这看上去好复杂。其实，<strong>和一个小孩想玩玩具一样</strong>：</p><p>首先，小孩必须获得父母的请求，可以玩玩具。然后，看这个玩具拥有者是谁，如果是自己父母，就看这个玩具是否能给孩子玩（比如可能年龄还不合适，超时等）。如果这个玩具是其它人的，那就要还获得其它人的允许。</p><h3 id="不同策略的场景"><a href="#不同策略的场景" class="headerlink" title="不同策略的场景"></a>不同策略的场景</h3><p>对于 S3 验证请求的时候，需要验证的那几种不同的策略，究竟各自的使用场景是什么呢？</p><ul><li><p>Object ACL</p><ul><li>唯一一种管理保存在他人 bucket 里的对象权限的方式</li><li>定义在单个对象级别</li><li>最多包含 100 个授权信息</li></ul></li><li><p>Bucket ACL</p><ul><li>唯一推荐使用的场景是为 S3 Log Delivery 赋予写访问日志的权限</li><li>虽然可以配置跨帐号权限，但仅仅支持有限的设置</li></ul></li><li><p>Bucket Policy</p><ul><li>能给自己帐号内的用户赋权</li><li>支持所有 S3 操作的跨帐号权限设置</li><li>Policy 自身大小不超过 20KB</li></ul></li><li><p>User Policy</p><ul><li>能给自己帐号内的用户赋权</li></ul></li></ul><h2 id="副本备份"><a href="#副本备份" class="headerlink" title="副本备份"></a>副本备份</h2><p>S3 不仅通过多点存储提高健壮性，还提供了自动的异步数据备份的功能。不仅支持同 Region，不同 bucket 的备份，还支持跨 Region，不同帐号的备份。要开启副本备份，首先必须在源和目标 bucket 同时打开多版本的设置。</p><h3 id="为什么要使用？"><a href="#为什么要使用？" class="headerlink" title="为什么要使用？"></a>为什么要使用？</h3><ul><li>备份同时保留元数据</li><li>备份至不同存储级别</li><li>更改备份数据的拥有权</li><li>15 分钟内自动备份</li></ul><h3 id="什么时候跨区备份（CRR）"><a href="#什么时候跨区备份（CRR）" class="headerlink" title="什么时候跨区备份（CRR）"></a>什么时候跨区备份（CRR）</h3><ul><li>满足监管需求</li><li>减少数据传输延时（地域原因）</li><li>提高数据操作的效率</li></ul><h3 id="什么时候同区备份（SRR）"><a href="#什么时候同区备份（SRR）" class="headerlink" title="什么时候同区备份（SRR）"></a>什么时候同区备份（SRR）</h3><ul><li>合并日志</li><li>生产和测试用户间数据同步</li><li>满足数据主权法规</li></ul><h3 id="什么会同步？"><a href="#什么会同步？" class="headerlink" title="什么会同步？"></a>什么会同步？</h3><ul><li>备份配置生效后新建的对象</li><li>没加密的对象</li><li>通过 SSE-S3 或者 SSE-KMS CMK（必须显式启用）加密的对象</li><li>对象元数据</li><li>bucket 拥有者有权读取的对象</li><li>对象 ACL 除非备份同属一个 aws 帐号</li><li>对象标签</li><li>对象的锁信息</li></ul><h3 id="什么不同步？"><a href="#什么不同步？" class="headerlink" title="什么不同步？"></a>什么不同步？</h3><ul><li>备份配置生效前新建的对象</li><li>使用 SSE-C 加密的对象</li><li>保存在 Glacier 或 Glacier Deep Archive 的对象</li><li>bucket 级别子资源的更新</li><li>由于生命周期配置导致的操作</li><li>源 bucket 中本来就是副本的对象</li><li>删除标识</li><li>源 bucket 中被删除的特定版本的对象</li></ul><h2 id="知识小点与周边"><a href="#知识小点与周边" class="headerlink" title="知识小点与周边"></a>知识小点与周边</h2><h3 id="路由请求"><a href="#路由请求" class="headerlink" title="路由请求"></a>路由请求</h3><ul><li>S3 使用的是 DNS 来接收转发请求。如果请求对象的 S3 地址不对，会返回一个临时的重定向。但是对那些 2019 年 3 月 20 日后启用的 Region，地址错误返回的则是 HTTP 400 状态。</li><li>S3 DNS 会按需更新 IP 地址。所以，对那些长期运行的客户端，可能需要采取特殊手段来更新 IP 信息。</li></ul><h3 id="静态资源网站"><a href="#静态资源网站" class="headerlink" title="静态资源网站"></a>静态资源网站</h3><p>S3 的 bucket 可以直接配置为静态资源网站。但是需要结合 CloudFront 才能支持 HTTPS 访问。<br>请求者付费的 bucket，不允许设置为静态网站。</p><p>CloudFront 数据的分发支持两种类型：</p><ul><li>Web Distribution</li><li>RTMP</li></ul><h3 id="Storage-Gateway"><a href="#Storage-Gateway" class="headerlink" title="Storage Gateway"></a>Storage Gateway</h3><p>当你本地服务器想要访问 AWS S3 的时候，除了 API，AWS 还提供了几种网关可供使用：</p><ul><li>File Gateway - 像访问文件或者共享文件那样访问 S3 资源</li><li>Volume Gateway - 通过 iSCSI 设备的方式连接。细分为两种：<ol><li>Stored Volumes - 所有数据都保存在本地，但是能异步备份到 S3</li><li>Cached Volumes - 所有的数据都保存到 S3，本地只存放经常访问的数据</li></ol></li><li>Tape Gateway - 模拟磁带访问的网关，数据异步备份到 S3 Glacier 或 Glacier Deep Archive</li></ul><h3 id="Athena-和-Macie"><a href="#Athena-和-Macie" class="headerlink" title="Athena 和 Macie"></a>Athena 和 Macie</h3><p>Athena 是交互式的查询服务，无须部署。可使用 SQL 来查询 S3 数据。支持的数据格式包括：CSV，JSON，Apache Parquet。</p><p>Macie 是一种可通过 NLP 和 ML 来协助你发现，分类和保护敏感数据的服务。它可以扫描 S3 中的数据，看是否包含 PII（Personally Identifiable Information）或者涉及版权的数据。</p>]]></content>
    
    
      
      
    <summary type="html">&lt;p&gt;AWS S3 全名是 Simple Storage Service，简便的存储服务。为什么这么起名啊？它：&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;提供了统一的接口 REST&amp;#x2F;SOAP 来统一访问任何数据&lt;/li&gt;
&lt;li&gt;对 S3 来说，存在里面的数据就是对象名（键），和数据</summary>
      
    
    
    
    <category term="Sword" scheme="http://www.thinkingincrowd.me/categories/Sword/"/>
    
    
    <category term="AWS" scheme="http://www.thinkingincrowd.me/tags/AWS/"/>
    
  </entry>
  
  <entry>
    <title>一文读懂 AWS IAM</title>
    <link href="http://www.thinkingincrowd.me/2020/02/16/aws-iam/"/>
    <id>http://www.thinkingincrowd.me/2020/02/16/aws-iam/</id>
    <published>2020-02-16T14:46:27.000Z</published>
    <updated>2022-08-28T08:07:15.451Z</updated>
    
    <content type="html"><![CDATA[<h2 id="Concept"><a href="#Concept" class="headerlink" title="Concept"></a>Concept</h2><p>IAM 是 AWS 云平台中负责身份认证，和权限控制的服务。AWS 云虽然分了很多个区（Region），但 IAM 是 Global，全局的。<br>所以，它的数据和配置的更改，也是 Eventually Consistent 的。</p><h2 id="Best-Practices"><a href="#Best-Practices" class="headerlink" title="Best Practices"></a>Best Practices</h2><p>在讲 IAM 的权限控制是怎么工作之前，先强调两个最重要的安全理念。</p><p><strong>Grant Least Privilege</strong></p><p>在 AWS 里面，每一个用户默认都是没有任何权限的。他甚至不能查看自己的密码或 access key，丢失了也只能重新生成。</p><p><strong>Lock Away Your AWS Account Root User</strong></p><p>AWS 账户开通的时候，你的登录邮箱和密码，就成为了这个账户下的超级管理员，它默认是什么都可以干的。<br>所以，和在 Linux 下不要滥用 root 一样，不要用这个超级帐号做日常操作，而是创建一个有 Full Administrator 权限的用户。</p><h2 id="How-It-Works"><a href="#How-It-Works" class="headerlink" title="How It Works?"></a>How It Works?</h2><p>权限控制有两个基本概念：</p><ol><li><strong>Authentication</strong> - 确认是否为有效用户，是否允许登录&#x2F;接入</li><li><strong>Authorization</strong> - 确认用户当前请求的操作（读写资源），是否合法</li></ol><p>所以，IAM 最重要就是管理 Identity，和控制 Resource 的操作。</p><h3 id="Identity-x2F-Principal"><a href="#Identity-x2F-Principal" class="headerlink" title="Identity&#x2F;Principal"></a>Identity&#x2F;Principal</h3><p>从资源访问的角度来看，使用 AWS 资源的其实不单单是具体的人，还可能是 Application。所以，AWS 里面的身份，分几种：</p><ul><li>User</li><li>Application</li><li>Federated User</li><li>Role</li></ul><p>能在 AWS IAM 控制台里创建的，只有 User 和 Role。而 User 在创建的时候，可以指定它的访问类型。是凭借用户名密码在 Console 登录，还是使用 Access Key ID 及 Secret 通过 API 来访问，还是两者皆可。</p><p>要特别注意的是，User 是直接操作 AWS 资源的用户，而不是你自己开发并部署在 AWS 的系统里面的用户。IAM 的 User 是有数量限制的，最多 5000 个。</p><p>如果你开发的系统需要操作 AWS 资源，比如说上传文件到 S3，那你需要用的是 Federated User。通过 OpenID Connect（如 Google&#x2F;Facebook）或者 SAML 2.0（如 Microsoft AD），你的系统用户可以在登录后换取代表某个 AWS Role 的临时 token 来访问 AWS 资源。</p><h3 id="Authentication"><a href="#Authentication" class="headerlink" title="Authentication"></a>Authentication</h3><p>访问和使用 AWS 资源有两种方式，一种是通过页面登录，也就是 Console。一种是通过 AWS API，也就是接口，包括 CLI, SDK 或 HTTPS 请求。</p><p>IAM User 在 Console 页面登录需要提供 AWS 帐号名，IAM User 名和密码。AWS 帐号名是 AWS 云服务开通时，系统生成的一串数字，或者是你赋予的别名。它其实就是一个多租户系统里面的租户帐号。<br> AWS 还会为每个帐号提供一个独特的登录链接，比如我的测试帐号： <a href="https://kcawsfree.signin.aws.amazon.com/console">https://kcawsfree.signin.aws.amazon.com/console</a> 。<code>kcawsfree</code> 就是我帐号的别名。</p><p>而如果是使用 API 访问 AWS，我们是需要用 IAM User 的 Access Key ID 及 Secret 来为这个 HTTP 请求生成签名的。为请求签名，是大多数的 API 集成的一种安全性考量。微信，支付宝等平台都这么做。为什么呢？  </p><ol><li>确认请求发起方是合法的，就是确保你就是你。</li><li>保护数据传输过程的安全，就是确保数据没被篡改。</li><li>防止重放攻击，就是确保一个请求不被多次使用，滥用或者冒用。</li></ol><p>签名需要根据什么信息生成呢？可以说是包含了请求唯一性的所有信息：  </p><p>请求的接口版本号<br>请求的操作是什么（Action）<br>请求的日期<br>所有请求的参数等</p><p>AWS 的请求样例：  </p><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">https://iam.amazonaws.com/?Action=AddUserToGroup</span><br><span class="line">&amp;GroupName=Managers</span><br><span class="line">&amp;UserName=Bob</span><br><span class="line">&amp;Version=2010-05-08</span><br><span class="line">&amp;AUTHPARAMS</span><br></pre></td></tr></table></figure><p>其实，如果你是使用 AWS SDK 或者 CLI，它会根据你配置的 Access Key 自动签名。只有当你自己发起一个 HTTP 请求的时候，才需要自己实现签名的逻辑。</p><h3 id="Authorization"><a href="#Authorization" class="headerlink" title="Authorization"></a>Authorization</h3><p>所谓是否有足够的权限，就是验证以下三者在一个请求的场景下，是否被允许：</p><ol><li>主体（Identity）</li><li>操作（Action）</li><li>资源（Resource）</li></ol><p>AWS 是通过策略（Policy）来定义权限（Permissions）的。最基本的策略有两大类。一种是 Identity-based policy，另一种是 Resource-based policy。前一种挂在 User&#x2F;Role&#x2F;Group 上面，用以定义这些被挂载的主体，能对什么资源进行怎样的操作。而后一种直接挂载在 AWS 资源上面，用以定义哪些主体可以对这个资源做什么样的操作。</p><p>AWS Policy 的 Permissions 定义，在内部是通过一个 JSON 格式来表示的。我们来看一个样例：</p><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"><span class="punctuation">&#123;</span></span><br><span class="line">  <span class="attr">&quot;Version&quot;</span><span class="punctuation">:</span> <span class="string">&quot;2012-10-17&quot;</span><span class="punctuation">,</span></span><br><span class="line">  <span class="attr">&quot;Statement&quot;</span><span class="punctuation">:</span> <span class="punctuation">[</span></span><br><span class="line">    <span class="punctuation">&#123;</span></span><br><span class="line">      <span class="attr">&quot;Sid&quot;</span><span class="punctuation">:</span> <span class="string">&quot;ListAndDescribe&quot;</span><span class="punctuation">,</span></span><br><span class="line">      <span class="attr">&quot;Effect&quot;</span><span class="punctuation">:</span> <span class="string">&quot;Allow&quot;</span><span class="punctuation">,</span></span><br><span class="line">      <span class="attr">&quot;Action&quot;</span><span class="punctuation">:</span> <span class="punctuation">[</span></span><br><span class="line">        <span class="string">&quot;dynamodb:List*&quot;</span><span class="punctuation">,</span></span><br><span class="line">        <span class="string">&quot;dynamodb:Describe*&quot;</span></span><br><span class="line">      <span class="punctuation">]</span><span class="punctuation">,</span></span><br><span class="line">      <span class="attr">&quot;Resource&quot;</span><span class="punctuation">:</span> <span class="string">&quot;*&quot;</span></span><br><span class="line">    <span class="punctuation">&#125;</span><span class="punctuation">,</span></span><br><span class="line">    <span class="punctuation">&#123;</span></span><br><span class="line">      <span class="attr">&quot;Sid&quot;</span><span class="punctuation">:</span> <span class="string">&quot;SpecificTable&quot;</span><span class="punctuation">,</span></span><br><span class="line">      <span class="attr">&quot;Effect&quot;</span><span class="punctuation">:</span> <span class="string">&quot;Allow&quot;</span><span class="punctuation">,</span></span><br><span class="line">      <span class="attr">&quot;Action&quot;</span><span class="punctuation">:</span> <span class="punctuation">[</span></span><br><span class="line">        <span class="string">&quot;dynamodb:BatchGet*&quot;</span><span class="punctuation">,</span></span><br><span class="line">        <span class="string">&quot;dynamodb:Get*&quot;</span><span class="punctuation">,</span></span><br><span class="line">        <span class="string">&quot;dynamodb:Query&quot;</span><span class="punctuation">,</span></span><br><span class="line">        <span class="string">&quot;dynamodb:Scan&quot;</span><span class="punctuation">,</span></span><br><span class="line">        <span class="string">&quot;dynamodb:BatchWrite*&quot;</span><span class="punctuation">,</span></span><br><span class="line">        <span class="string">&quot;dynamodb:Delete*&quot;</span><span class="punctuation">,</span></span><br><span class="line">        <span class="string">&quot;dynamodb:Update*&quot;</span><span class="punctuation">,</span></span><br><span class="line">        <span class="string">&quot;dynamodb:PutItem&quot;</span></span><br><span class="line">      <span class="punctuation">]</span><span class="punctuation">,</span></span><br><span class="line">      <span class="attr">&quot;Resource&quot;</span><span class="punctuation">:</span> <span class="string">&quot;arn:aws:dynamodb:*:*:table/MyTable&quot;</span></span><br><span class="line">    <span class="punctuation">&#125;</span><span class="punctuation">,</span></span><br><span class="line">    <span class="punctuation">&#123;</span></span><br><span class="line">      <span class="attr">&quot;Sid&quot;</span><span class="punctuation">:</span> <span class="string">&quot;AllowAllActionsForEC2&quot;</span><span class="punctuation">,</span></span><br><span class="line">      <span class="attr">&quot;Effect&quot;</span><span class="punctuation">:</span> <span class="string">&quot;Allow&quot;</span><span class="punctuation">,</span></span><br><span class="line">      <span class="attr">&quot;Action&quot;</span><span class="punctuation">:</span> <span class="string">&quot;ec2:*&quot;</span><span class="punctuation">,</span></span><br><span class="line">      <span class="attr">&quot;Resource&quot;</span><span class="punctuation">:</span> <span class="string">&quot;*&quot;</span></span><br><span class="line">    <span class="punctuation">&#125;</span><span class="punctuation">,</span></span><br><span class="line">    <span class="punctuation">&#123;</span></span><br><span class="line">      <span class="attr">&quot;Sid&quot;</span><span class="punctuation">:</span> <span class="string">&quot;DenyStopAndTerminateWhenMFAIsNotPresent&quot;</span><span class="punctuation">,</span></span><br><span class="line">      <span class="attr">&quot;Effect&quot;</span><span class="punctuation">:</span> <span class="string">&quot;Deny&quot;</span><span class="punctuation">,</span></span><br><span class="line">      <span class="attr">&quot;Action&quot;</span><span class="punctuation">:</span> <span class="punctuation">[</span></span><br><span class="line">        <span class="string">&quot;ec2:StopInstances&quot;</span><span class="punctuation">,</span></span><br><span class="line">        <span class="string">&quot;ec2:TerminateInstances&quot;</span></span><br><span class="line">      <span class="punctuation">]</span><span class="punctuation">,</span></span><br><span class="line">      <span class="attr">&quot;Resource&quot;</span><span class="punctuation">:</span> <span class="string">&quot;*&quot;</span><span class="punctuation">,</span></span><br><span class="line">      <span class="attr">&quot;Condition&quot;</span><span class="punctuation">:</span> <span class="punctuation">&#123;</span></span><br><span class="line">        <span class="attr">&quot;BoolIfExists&quot;</span><span class="punctuation">:</span> <span class="punctuation">&#123;</span></span><br><span class="line">          <span class="attr">&quot;aws:MultiFactorAuthPresent&quot;</span><span class="punctuation">:</span> <span class="literal"><span class="keyword">false</span></span></span><br><span class="line">        <span class="punctuation">&#125;</span></span><br><span class="line">      <span class="punctuation">&#125;</span></span><br><span class="line">    <span class="punctuation">&#125;</span></span><br><span class="line">  <span class="punctuation">]</span></span><br><span class="line"><span class="punctuation">&#125;</span></span><br></pre></td></tr></table></figure><p>这个策略控制了 DynamoDB 和 EC2 的访问权限。它看起来很复杂，但其实结构很清晰。这里面最主要的元素就是 <code>Effect</code>, <code>Action</code>, 和 <code>Resource</code>。它们确定了什么资源上的哪些操作，是被允许，还是禁止的。它们是 AND 的逻辑组合。</p><p>Statement 里前两个 Permission，允许用户获取 DynamoDB 里面的资源信息，但是只有 MyTable 这个表能做写操作。而后两部分允许用户对 EC2 做任何操作，但是停止和结束 Instance 则必须通过了 MFA 登录认证后才可以。</p><h3 id="Policy-Evaluation-Logic"><a href="#Policy-Evaluation-Logic" class="headerlink" title="Policy Evaluation Logic"></a>Policy Evaluation Logic</h3><p>一个用户或者角色主体上，可以拥有多个不同的 Policy。所以，Policy 的权限验证逻辑，可谓相当复杂。<br>在讲验证流程前，我再重复一次 AWS 权限的设计原则，这对流程的理解很重要。</p><ul><li>如果<strong>有显式的 Deny，就禁止</strong>。  </li><li><strong>Grant Least Privilege</strong> 原则。如果没有显式赋予权限，也就是没有任何 Policy 为请求的资源和操作定义了 <code>Allow</code> 权限，那这个主体就没有权限（Implicit Deny）。</li></ul><p>AWS 对收到的操作请求，会根据以下的流程来判断这个请求的主体是否有操作权限：</p><ol><li>Deny evaluation</li><li>AWS Organizations service control policies (SCP)</li><li>Resource-based policies</li><li>IAM permissions boundaries</li><li>Session policies</li><li>Identity-based policies</li></ol><p>第一步，首先把 2 至 6 里面的所有 policy 的显式 Deny 拿出来。如果当前的请求属于 Deny 的范围，直接禁止操作。这个就是第一个原则。</p><p>第二步到第六步，是具体的 policy。如果该主体有这个类型的 policy 存在，就按照第二个原则处理。如果没有，跳到下一个 policy 类别的检查。</p><p>那么多种的 Policy 类别，为什么是这个排列顺序呢？我是这么理解的：</p><ol><li>Organization SCP 作为组织级别策略，优先级最高。</li><li>Resource-based policy 可以跨帐号赋予权限，级别比后面的高一些。</li><li>Permission Boundary 的作用是提前为用户定义一个最大的权限范围，避免意外打开了权限的情况，所以比后面的级别要高。</li><li>Session policies 是会话级别，允许临时赋予权限，所以比 Identity-based policies 高。</li><li>Identity-based policies 是最稳定的，所以检查放在最后。</li></ol><p>不过，这里有一个特例，就是 Resource-based policy。如果它是 Implicit Deny 的情况，还是会继续后面的检查，不会阻止。<br>还有一个复杂的情况是关于 Session policy 的，这个就不在本文解释了，具体可看<a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session" title="Session Policy">文档</a>。</p><p>其实，即便逻辑复杂，判断是否有权限还是可以简单地总结为一句话：  </p><p><strong>只有具备显式的 Allow，并且没有显式的 Deny，才有权限。</strong></p><p>或者</p><p><strong>如果没有显式的 Allow，或者有显式的 Deny，就没有权限。</strong></p>]]></content>
    
    
      
      
    <summary type="html">&lt;h2 id=&quot;Concept&quot;&gt;&lt;a href=&quot;#Concept&quot; class=&quot;headerlink&quot; title=&quot;Concept&quot;&gt;&lt;/a&gt;Concept&lt;/h2&gt;&lt;p&gt;IAM 是 AWS 云平台中负责身份认证，和权限控制的服务。AWS 云虽然分了很多个区（Region</summary>
      
    
    
    
    <category term="Sword" scheme="http://www.thinkingincrowd.me/categories/Sword/"/>
    
    
    <category term="AWS" scheme="http://www.thinkingincrowd.me/tags/AWS/"/>
    
  </entry>
  
  <entry>
    <title>上了云，远程工作就没问题了吗？</title>
    <link href="http://www.thinkingincrowd.me/2020/02/09/Can-remote-working-be-smooth-after-moving-all-to-cloud/"/>
    <id>http://www.thinkingincrowd.me/2020/02/09/Can-remote-working-be-smooth-after-moving-all-to-cloud/</id>
    <published>2020-02-09T02:00:00.000Z</published>
    <updated>2022-08-28T08:07:15.450Z</updated>
    
    <content type="html"><![CDATA[<p>很久以前，我就期望能尝试下远程工作。一种崇尚已久的，更高效，更自由的方式。没想到，这个愿望，在 2020 年开初就因一个从没想到的悲剧而“实现”了。</p><p>这个全民悲剧就不多说了。能看懂 “<strong>能。明白</strong>” 这几个字的，就能体会我的心情。</p><p>最近很多技术公众号都发表了关于远程工作的文章，包含了工具的推荐，和要注意的事项，包括文档协作、视频会议、任务管理、工作协同等。</p><p>其实，我觉得现在欠缺的不是工具。不然，为什么网上还有不少人爆出公司执行远程工作同时，推出了一些幺蛾子政策：全程打开视频摄像头、10分钟内必须回复、每天发日报、估算效率等。</p><p>这些政策的出现，除了所谓的信任问题外，总的来说还是老板担心远程工作会影响效率。</p><p>效率的提高，需要从软硬两方面下手。</p><p>硬件方面，上了云，就减少了 VPN，Remote Desktop 的使用，降低网络卡壳的影响。公众号里介绍的协同工具，其实也算是在硬件方面提供助力为主。</p><p>但是，不是说上了云，什么都在线，效率就上来了。正如武林高手草木皆可为剑，摘叶即可伤人。<strong>工具虽然重要，但主要还是看怎么使用这些工具</strong>。</p><p>决定效率最关键的，还是软的方面，也就是沟通。</p><p>我说的沟通不是单纯地指用了什么通讯工具（邮件还是即时聊天），而是如何协作，如何使用那些协同工具。这些工具的目的就是提升沟通的效率。<strong>软件工程领域，沟通和协作是很多方面的。既有人和人的沟通，更多的是人和机器，系统的沟通</strong>。</p><p>如果有 Code Review，需要喊一嗓子，还是能自动发代码审查请求到模块负责人或者指定人员？</p><p>有多少比例的自动化测试，还是全人工测试？</p><p>通过看板来了解各方进度和项目障碍，还是靠写工作报告，发邮件？</p><p>持续集成环境是否会出问题？开发是否需要跨团队找人解决？</p><p>服务器和网络设置能像 AWS 的 CloudFormation 那样一键部署，还是需要人手几天的配置？</p><p>开发人员需要新服务器或数据库资源，网络接入，环境对接，需要层层审批获取权限，还是能自动化？即便同样使用的都是 AWS。如果使用传统的 RBAC，每为一个新资源赋权都要去改 Role。而使用 ABAC，则能更方便灵活地做权限管理。</p><p>工具用不好就算了。最可笑的是，可能云平台或工具本身已具备灵活的资源申请，权限控制和管理的能力，却被企业以安全的名义（Least Privilege 原则），实则不信任，强加上一些人手的，半自动化的审批流程，或者限制了一些功能。如果用的是被阉割的云平台，则让人啼笑皆非。</p><p>我认为，即便一家软件公司不是完全远程工作的模式，还需要面对面交流，也应该时不时尝试远程工作，来衡量组织内部的协作模式是否高效。</p><p><strong>远程工作应该是一个目标。它是衡量一家软件公司运作是否高效的一个指标</strong>。</p>]]></content>
    
    
      
      
    <summary type="html">&lt;p&gt;很久以前，我就期望能尝试下远程工作。一种崇尚已久的，更高效，更自由的方式。没想到，这个愿望，在 2020 年开初就因一个从没想到的悲剧而“实现”了。&lt;/p&gt;
&lt;p&gt;这个全民悲剧就不多说了。能看懂 “&lt;strong&gt;能。明白&lt;/strong&gt;” 这几个字的，就能体会我的心情。</summary>
      
    
    
    
    <category term="Think" scheme="http://www.thinkingincrowd.me/categories/Think/"/>
    
    
    <category term="Productivity" scheme="http://www.thinkingincrowd.me/tags/Productivity/"/>
    
  </entry>
  
  <entry>
    <title>没想到看书也需要勇气</title>
    <link href="http://www.thinkingincrowd.me/2019/11/30/never-thought-one-book-takes-courage-to-read/"/>
    <id>http://www.thinkingincrowd.me/2019/11/30/never-thought-one-book-takes-courage-to-read/</id>
    <published>2019-11-30T10:11:39.000Z</published>
    <updated>2022-08-28T08:07:15.450Z</updated>
    
    <content type="html"><![CDATA[<p>听到”勇气“这个词，你想到的是什么？</p><p>挺身而出的见义勇为者？不畏强权的斗士？还是奋不顾身的创业者？</p><p>你是否觉得勇气都需要在光辉的领域，在这些“大”事才能呈现？只有这样才足以被称为有勇气之人？</p><p>其实不是的。</p><p>对于严重抑郁症患者，能坚持活着，就需要很大的勇气；减肥人士，能毅然拒绝手边的零食炸鸡，也需要勇气。</p><p><strong>我们做的每一个选择，都取决于当时内在的勇气充足与否。</strong></p><p>我在国庆期间第一次读完《被讨厌的勇气》这本书时，忍不住在朋友圈感叹：</p><blockquote><p>被阿德勒种草。这是一本所有人都应该看的书，比任何道德教育更有价值的书。应该从初中起就被列为必读书籍。</p></blockquote><p>年少之时，我讨厌语文，基本没看过任何文学作品，即便是男生标配的武侠小说。除了学习教材或专业类书籍，我会拿来看的“书”，恐怕只剩下漫画了。看完《被讨厌的勇气后》，我忍不住感慨，如果以前能看到这本书，该多好。然而，这么一想，已经有违阿德勒的观点了。</p><p>虽然前面盛赞这本书，但我觉得并不是所有人都能马上接受阿德勒的观点。​你体会一下书中的这两个观点：</p><ol><li>心理创伤并不存在  </li><li><strong>你的不幸，皆是自己“选择”的</strong></li></ol><p>很残酷是不是？本来你看心理学书籍就是为了抚慰心灵，现在的你可能已经够伤心困惑的了，但是却还要被正面捅上一刀：“这是你自找的”。</p><p>最开始读这本书时，你可能会有种“没什么事情做不了，只是你自己没有勇气去做而已。”的近乎居高临下，站着说话不腰疼的感觉。书中那个和“禅师”辩论的“青年”，在最开始的辩论过程中，就被经常气得浑身发抖，但又哑口无言。能坚持把书看下来，真的需要点勇气。</p><p>即便我认为，心理创伤还是存在的，像经历残酷战役的军人，或者被暴力虐待过的人患上的 PTSD。而且，我们也不是说想变主动，变勤快，变温和，只要心想，马上就能改变的。但是，书中“禅师”和“青年”的对话，的确能为你提供新的思路和角度，有种豁然开朗的感觉。</p><p><strong>阿德勒心理学主张的是自我决定理论，目的论</strong>。他并不赞同精神分析学派的方式。因为关注过去，挖掘深层原因来解释事物很容易会陷入“决定论”的思维方式。最近流行的“原生家庭”说法，就是被很多人找来的当借口，把自己“无法改变”的责任，推给他人。</p><p>书中给我感触最大的两句话是：  </p><blockquote><p><strong>决定我们自身的不是过去的经历，而是我们自己赋予经历的意义。</strong></p><p><strong>重要的不是被给予了什么，而是如何去利用被给予的东西。</strong></p></blockquote><p>儿时课本中的张海迪，澳大利亚那位天生没有四肢的尼克·胡哲（Nick Vujicic），杭州保姆纵火案的“老婆孩子在天堂”，汶川地震的幸存者，他们经历了别人难以置信的缺失和悲痛，却还能为这些经历赋予了与众不同的意义，继续前行，甚至活出更精彩的人生。</p><p>老实说，换作是我遇到上述的困难，真的未必能克服。不过，只要知道自己还是能有掌控的能力，未来就不缺希望。看过这本书，能为自己充实点勇气，积蓄点动力，为生活带来一丝转变，其实已经值得。</p>]]></content>
    
    
      
      
    <summary type="html">&lt;p&gt;听到”勇气“这个词，你想到的是什么？&lt;/p&gt;
&lt;p&gt;挺身而出的见义勇为者？不畏强权的斗士？还是奋不顾身的创业者？&lt;/p&gt;
&lt;p&gt;你是否觉得勇气都需要在光辉的领域，在这些“大”事才能呈现？只有这样才足以被称为有勇气之人？&lt;/p&gt;
&lt;p&gt;其实不是的。&lt;/p&gt;
&lt;p&gt;对于严重抑郁</summary>
      
    
    
    
    <category term="Psychology" scheme="http://www.thinkingincrowd.me/categories/Psychology/"/>
    
    
    <category term="Courage" scheme="http://www.thinkingincrowd.me/tags/Courage/"/>
    
  </entry>
  
  <entry>
    <title>我是如何从一个“愤青”变成“亲中”的？</title>
    <link href="http://www.thinkingincrowd.me/2019/10/12/how-I-change-from-angry-youth-to-be-patriot/"/>
    <id>http://www.thinkingincrowd.me/2019/10/12/how-I-change-from-angry-youth-to-be-patriot/</id>
    <published>2019-10-12T00:47:43.000Z</published>
    <updated>2022-08-28T08:07:15.450Z</updated>
    
    <content type="html"><![CDATA[<p><img src="https://github.com/kenspirit/blog-cdn-data/blob/master/truth-over-fact.JPG?raw=true" alt="truth-over-fact">  </p><p>自从香港发生一些示威事件后，我的心情一直无法平复。作为一个会讲标准粤语的广东人，一个大半职业生涯在港资企业，在港工作过一年时间，一个有着好几个香港朋友的人来说，心情真的很不好受。</p><p>很早就想写些什么，但迟迟没有下笔。心情杂乱是一方面，主要原因则是目前这个乱局，谁是谁非，要抓住最开始那个源头，太难了。所以，无论我怎么写，写什么，可能都会招来持对立观点的人一顿攻击。以前流传的一句名言：<strong>“我不同意你的观点，但是我誓死捍卫你说话的权利”</strong>，现在还有多少人能做得到。</p><p>不过，不吐不快。即便可能因此损失一些朋友，但或许对你我也是好事。</p><h3 id="为什么我变了？"><a href="#为什么我变了？" class="headerlink" title="为什么我变了？"></a>为什么我变了？</h3><p>我以前也认为中国的自由民主是不足够的（即便现在还是不足够），特别是言论上，而且还有很多政府不作为行为。所以，我在大学时候，很倾向于出国，希望去到一个更自由的地方。国内有些什么贪腐案件，政府做的不好的地方，我会特别留意并把它拿来当支持自己观点的证据，证明我的想法是对的。</p><p>那为什么我现在变成“亲中”了呢？首先，“亲中”不代表我认为中国什么问题都没有。我依然看到政府还有做的不好的方面。“亲中”只是代表我认同自己是中国人，并且有义务使之变得更好，为了我的后代。</p><p>整个转变，主要是因为我看到了一个现实：“<strong>任何国家政权，都天然维护自己的国家利益，甚至不惜牺牲其它国家民族的利益。一个国家内的媒体机构，绝大多数都是为了国家政权而服务的。</strong>”</p><p>我已经不怎么相信以前崇拜的那些灯塔国，美国等西方国家，会真正为了理想的自由民主，为全世界人民谋福利。很多时候他们的政治宣言，行动等，都只是为了自己的政治生涯和国家利益而已。</p><p>连我一直笃信 “Don’t be evil” 的 Google，其实也会根据很多说不明的利益，更改搜索结果。这个 Motto 后来也被悄悄改成 “Do the right thing” 了。最近在 Facebook 有一个亚裔员工，帮跳楼的中国留学生公开发言，被开除了。</p><p>我不是说中国什么都好，只是不盲目相信国外只有美好。</p><p>帮我打破幻想的，主要是我越来越多地看到，一些西方媒体的报道是如何歪曲事实，来论述它们口中的真相。媒体的观点，取材，绝大多数都是以想让你看到什么，想让你有什么结论的前提来构建的。那是它们口中的真相，其实并不是事实。而所谓的“真相”，往往取决于人的角度和观点。</p><p>下面是一些例子：</p><p><a href="https://weibo.com/1401527553/I3PBNlNkn">扭曲原话</a><br><a href="https://weibo.com/1401527553/I1n3Of3IU">选择“真相”而不是“事实”</a><br><a href="https://weibo.com/1401527553/HETZoFBJs">故事的两面，只看你选择什么来报道</a><br><a href="https://weibo.com/1401527553/I98cf3ARZ">看似真话，实际误导</a>  </p><p>如果你认为我也是选择符合我观点的证据来服务我的观点，那就对了。我不否认这种可能性。只是，你是不是也想想，自己也是有可能倾向于相信你本来就认定的观点？</p><p>George Orwell 说过:  </p><blockquote><p>“The people will believe what the media tells them they believe”。</p></blockquote><p>人总是相信自己愿意相信的一些观点。所以，两大观点对立的媒体，很容易让你倾向于选择那些和你原来的观点一致的报道，而忽略了另一方即便是事实的报道。</p><h3 id="怎么办？"><a href="#怎么办？" class="headerlink" title="怎么办？"></a>怎么办？</h3><p>这种情况下，我们还能相信什么呢？这时候，我<strong>能坚守的，只能是自己认定的最基本的一些世界观和原则</strong>：</p><ol><li>我不同意你的观点，但是我捍卫你说话的权利。  </li><li>暴力，和伤害他人的正当权益是不可接受的，尤其是不能用一些“伟大”的理由或借口。</li></ol><p>所以，如果你要问我对这次香港示威的基本态度是什么？就是不认同所有的暴力行为。</p><p>即便你有很崇高的理由，也不能使用暴力和伤害他人的正当权益。值得别人尊重的，只有如他们这样：</p><p><a href="https://weibo.com/1401527553/Ia4dJg7xV">在弗格森枪击案引发的骚乱之后，奥巴马曾公开表示</a></p><p><a href="https://weibo.com/1750070171/IavWJ5x8m">被英国警方逮捕的极端环保者</a></p><h3 id="为什么示威发展成这样？"><a href="#为什么示威发展成这样？" class="headerlink" title="为什么示威发展成这样？"></a>为什么示威发展成这样？</h3><p>现在，示威的一方，认为是政府警察的错；政府认为是对方的错。现在双方就像争吵红了眼的夫妻双方，不断升级各自的手段，维持各自的情绪和态度，生怕一退缩下来，就输了。这种对称式的升级，只有当一方能突然退出这个循环，或者压倒性的暴力，才可能有打破的机会。但是，无论怎么样，我都不希望是大暴力收场，两败俱伤。</p><p>按示威者所言，他们也是不崇尚暴力，希望和平示威的。那为什么他们要蒙面？为什么他们不制止在游行中实施暴力，打杂破坏的人员？在一些视频里面，一些香港年轻人甚至说，他们使用暴力，进行经济和其它破坏，正是他们的目的。他们说就是要打倒了才能重建。</p><p>我觉得，现在的示威群体，已经专横和偏执化了。任何一点理性的反对意见，已经没法被听进去。</p><p>下面是在《乌合之众》这本出名的大众心理学书里面，关于群体方面的描述。所以，如果在示威群体中提出反驳意见，可能已经被排挤出去了。</p><blockquote><p>群体只知道简单而极端的感情；提供给他们的各种意见、想法和信念，他们或全盘接受，或者一概拒绝，将其视为绝对的真理或绝对谬误。<br>…<br>个人可以接受矛盾，进行讨论，群体是绝对不会这样做的。在公众集会上，演说者哪怕做出最轻微的反驳，立刻就会招来怒吼和粗野的叫骂。<br>…<br>专横和偏执是一切类型的群体的共性</p></blockquote><p>有不少示威人士都认定，那些暴力人士，是警察的奸细。可见，本来属于正义的警察，已经被认定为暴力和群众的对立面。在没有了信任的基础上，可以说你做什么都是错的。他们为什么不会认为，那些就像是港产片里面的卧底，目的只是为了抓获混入和平示威人士的暴力份子呢？只能说，他们已经完全不信任警察了。  </p><p>如果说那些带面罩的暴力人士是非和平示威人士，甚至是警察奸细，而你是和平示威人士。那与之区分的最好的途径，不是脱掉面具吗？甚至在政府颁布反蒙面法后，为什么还公然反抗法律？不蒙面，本来就是和平示威的要求，为什么他们反而不采纳？这也只能说明，他们已经完全不信任政府了。而且，蒙面本身，已经成为了示威这个群体的特征，质疑和反对这个特征，相当于质疑和反对示威的诉求，是不可接受的。</p><h3 id="怎么破？"><a href="#怎么破？" class="headerlink" title="怎么破？"></a>怎么破？</h3><p>最近在看的《Change: Principles of Problem Formulation and Problem Resolution》里面说到，<strong>一些看起来合理的处理问题的手段，其实只是起了短暂解决问题的作用，但是却反而长期维持了问题的存在</strong>。越是坚持采用相似的手段，问题就越难解决。</p><p>现在示威人士和政府双方，感觉都陷入了各自认为对的解决问题的方式上，却反而维持了问题，甚至在恶化。</p><p>在这种情况下，要产生真正的改变，企图追究最开始问题形成的原因来解决问题其实已经没有用了，而是需要观察现在用来解决问题的手段。要判断是否需要从另一个角度或维度上改变当前的手段。正如，如果你一开始失眠，可能只是因为恰巧睡前吃喝了什么，或者近期有什么突发事情。但是，如果你已经持续失眠了几个月，那可能就要观察你一直以来是如何尝试解决失眠的，用了什么方法。因为一开始失眠的原因，已经不再是导致现在持续失眠的原因了。而可能是现在尝试解决失眠的手段，反而维持了失眠的现象。</p><p>所以，如果从改变当前解决失眠的手段入手，比如停止所有尝试入睡的努力，平静的和自己说，既然睡不着了，那就干脆不睡了，做自己想做的事情吧。这样做，其实反而可能可以减轻了自己给自己带来的压力，让你忍不住就产生了睡意，然后睡着了。</p><p><strong>想解决一些顽固的问题，有时可能需要用一种看起来反直觉的，荒谬的手段来解决</strong>。</p><p>假如，政府突然宣布，鉴于大多数人都认同示威行为，并且他们都自认为是和平的示威人士，所以政府不会再派出任何警力去示威地点企图维持秩序，将交由他们自己组织管理。只要不带面罩，就是和平示威。如果真的还有暴力份子存在，请他们注意安全，和暴力份子保持距离。警察如果接到报警，才会出发处理。如果示威群众真的认为有能力阻止暴力的发生，才去制止他们，或者在远处拍照，录像再转交给警方。</p><p>这里创造的悖论就是说：既然你们原来不信任政府和警察，并认为政府干预了正常的示威，那政府就先承认大多数都是和平示威人士，让你们自己内部和少数的暴力份子疏远。把道德高点和责任还给示威人士，让他们自己考虑所有可能面对的情况，并判断什么应对手段是和自己的身份或观点违背的。</p><p>政府还可以让示威人士选出一两个代表，全球直播和政府对话。因为只有一两个人，就没有了群体的疯狂；而且通过全球直播，直接咨询示威代表如何解决那些暴力，侵犯他人权益的行为，解决冲突，把一部分外部矛盾转化为内部。</p><h3 id="未来会如何？"><a href="#未来会如何？" class="headerlink" title="未来会如何？"></a>未来会如何？</h3><p>我其实一直觉得，香港作为一个在中国内具备特殊地位，更多自由度的地区，它的一个伟大的使命是充分发挥它的影响力，软实力，慢慢辐射广东，华南，甚至全国，让中国变得更美好，民主和自由。但是，这次的示威，似乎起了反效果，感觉有点可惜。不知道经此一役，香港的未来会如何。毕竟，这次的蝴蝶效应，竟然是一个香港人在台湾杀了人，导致大陆看不到 NBA，炒鞋的凉了。</p><p>正如前面所说，我对外媒也是越来越鄙视，玩的双标也越来越多，越来越不靠谱（参见下面对“莫顿叉”这个解释）。最近国外那些环保人士示威，虽然没有暴力行为，但是也采用很多严重影响社会和他人利益的方式来表达。顿时感觉整个人类社会，辛苦建立的文明，怎么那么快，那么突然就堕落了。乌合之众啊，人类的理性实在是太脆弱了。</p><p><img src="https://github.com/kenspirit/blog-cdn-data/blob/master/Morton's%20fork.jpg?raw=true" alt="Morton&#39;s fork">  </p>]]></content>
    
    
      
      
    <summary type="html">&lt;p&gt;&lt;img src=&quot;https://github.com/kenspirit/blog-cdn-data/blob/master/truth-over-fact.JPG?raw=true&quot; alt=&quot;truth-over-fact&quot;&gt;  &lt;/p&gt;
&lt;p&gt;自从香港发生一些示威</summary>
      
    
    
    
    <category term="Think" scheme="http://www.thinkingincrowd.me/categories/Think/"/>
    
    
    <category term="Politics" scheme="http://www.thinkingincrowd.me/tags/Politics/"/>
    
  </entry>
  
  <entry>
    <title>有时候，你对下属，比对自己的孩子还要好</title>
    <link href="http://www.thinkingincrowd.me/2019/08/02/sometimes-you-treat-your-subordinates-better-than-your-child/"/>
    <id>http://www.thinkingincrowd.me/2019/08/02/sometimes-you-treat-your-subordinates-better-than-your-child/</id>
    <published>2019-08-02T13:32:41.000Z</published>
    <updated>2022-08-28T08:07:15.450Z</updated>
    
    <content type="html"><![CDATA[<p>刚刚上完了一个系统养育的线上课程，又紧接着参加了公司安排的一个两天的「优秀导师」培训。突然间发现，我们很多做家长的，对自己的下属，甚至比对自己的孩子或至亲还要好。</p><h3 id="你是-Boss-还是-Leader？"><a href="#你是-Boss-还是-Leader？" class="headerlink" title="你是 Boss 还是 Leader？"></a>你是 Boss 还是 Leader？</h3><p>大家可能看过类似的比较：  </p><p>Boss 使用权威；Leader 使用领导力。<br>Boss 制造畏惧；Leader 制造吸引力。<br>Boss 喜欢惩罚；Leader 喜欢指导。<br>Boss 绩效导向；Leader 发展导向。<br>Boss 喜欢控制和命令；Leader 喜欢引导和鼓励。  </p><p>很多人都会说：“我们更喜欢 Leader，而不是 Boss”。  </p><p>可是，我们在面对孩子的时候，是像 Boss 多一些，还是 Leader 多一些？</p><h3 id="你有用心去建立关系吗？"><a href="#你有用心去建立关系吗？" class="headerlink" title="你有用心去建立关系吗？"></a>你有用心去建立关系吗？</h3><p>一个成功的导师，带教新人的第一步是什么？建立关系和信任。</p><p>想想我们会为了和下属打好关系，帮助他们成长，我们做过什么？我们请 Ta 吃饭；花心思花时间来单独指导；当 Ta 遇到困难时，甚至还能共情地提问和引导，了解 Ta 真实的想法；我们察言观色，判断下属是否有抗拒心理，然后再想办法灵活应对。</p><p>可对着孩子，我们又做了多少？我们花过多少心思和孩子建立关系？还是我们默认拥有了父母的角色，就不需要用心去经营这段关系了？</p><h3 id="你违反了多少指导的原则？"><a href="#你违反了多少指导的原则？" class="headerlink" title="你违反了多少指导的原则？"></a>你违反了多少指导的原则？</h3><p><strong>表扬要公开，批评要私下</strong></p><p>  多少家长在饭桌上，在外人面前，在众目睽睽下批评自己的孩子。</p><p><strong>给出明确具体的指示</strong></p><p>  想像一下，老板对你说：”你写得这都是什么狗屎？重新写一遍！“ 你觉得这样的回应对你有帮助吗？但是，如果他说的是：”这里写的太笼统，你可以加一些具体的案例，数字，突出重点。“，你又有什么感觉？平时对待你的下属，指导你的孩子，你多数用的是哪种方式？  </p><p><strong>对事不对人</strong></p><p>  ”你怎么这么笨啊？“ ”你怎么一点上进心都没有？“ ”你看看某某做的比你好多少？“<br>  这些伤自尊的话，可能你对孩子说过不少吧？给 Ta 贴了多少标签？​可你对你的下属说过吗？为什么你会懂得给你下属面子？</p><h3 id="你是否期待-Ta-马上就变好？"><a href="#你是否期待-Ta-马上就变好？" class="headerlink" title="你是否期待 Ta 马上就变好？"></a>你是否期待 Ta 马上就变好？</h3><p>指导下属的时候，我们知道有时候难免要手把手教。还知道不可能一步到位，会帮他把目标进行分解，慢慢改进。我们还能认识到，不同的人有不同的特长，成长速度也不同，并针对他们的优缺点来安排任务。</p><p>可是对孩子呢？我们期望 Ta 一下子就能端端正正地坐上 45 分钟做作业不开小差。我们理所当然地认为孩子到了多少岁了，就应当具备了某种技能。还拿 Ta 和其他人比较，质问 Ta 为什么做不到。</p><p>在公司培训后回家的路上，我和另一位妈妈对养育问题都有了很大的感慨。之前还自认为自己做的应该可以了，在面对孩子的缺点和不足时，已经很耐心地去引导孩子，和给予意见。可现实却是大大地打脸。</p><p>她回想起自己教儿子练字时给予的那些回应，恰恰印证了培训老师教的方法。</p><p>她儿子的字写得很潦草，所以一直要求他练字。但是，她儿子一直非常抗拒。一开始她给的反馈就是：”你怎么写得这么乱？就不能整洁一些吗？“ 可是无论怎么说，都没有效果。后来，她给孩子的反馈变了：“你写的字，至少要在方块格子里面吧？我们的中文字是方块字，你写的这些有哪些可以算是方块的样子呢？” 这些改变了的反馈虽然可能还不算完美，但是，他儿子写的字竟然就慢慢变好了。更神奇的是，他儿子对练字的态度也都改变了，还会主动邀请她，看看自己的字写得怎么样。</p><p>其实，真的，<strong>”没有教不好的孩子，只有不会教的父母“</strong>。</p><p><strong>”养育孩子，其实养育的是自己“</strong></p>]]></content>
    
    
      
      
    <summary type="html">&lt;p&gt;刚刚上完了一个系统养育的线上课程，又紧接着参加了公司安排的一个两天的「优秀导师」培训。突然间发现，我们很多做家长的，对自己的下属，甚至比对自己的孩子或至亲还要好。&lt;/p&gt;
&lt;h3 id=&quot;你是-Boss-还是-Leader？&quot;&gt;&lt;a href=&quot;#你是-Boss-还是-Le</summary>
      
    
    
    
    <category term="Think" scheme="http://www.thinkingincrowd.me/categories/Think/"/>
    
    
    <category term="Education" scheme="http://www.thinkingincrowd.me/tags/Education/"/>
    
    <category term="Coach" scheme="http://www.thinkingincrowd.me/tags/Coach/"/>
    
  </entry>
  
  <entry>
    <title>福尔摩斯爸爸和华生妈妈</title>
    <link href="http://www.thinkingincrowd.me/2019/06/25/holmes-dad-and-watson-mom/"/>
    <id>http://www.thinkingincrowd.me/2019/06/25/holmes-dad-and-watson-mom/</id>
    <published>2019-06-25T14:55:06.000Z</published>
    <updated>2022-08-28T08:07:15.450Z</updated>
    
    <content type="html"><![CDATA[<p>在美剧 Elementary（福尔摩斯）第 5 季里面，Joan Watson 遇到了她当医生时救过的一位贩毒黑帮人员 Shinwell Johnson。Shinwell 在假释期间，表达了对生活的悲观情绪和想重新做人的意愿，Joan 也为他提供了很多帮助。可因为 Shinwell 一直不被社会接纳，Joan 提议跟她学做侦探。Shinwell 觉得自己并不合适，谢绝了她的提议。而 Sherlock Holmes 其实也同样觉得他没潜质。  </p><p>后来 Joan 知道他重新接触黑帮，找他沟通，反而被 Shinwell 怒斥，劝她别多管闲事，并让她从此远离自己。虽然 Joann 有点无奈，但她始终觉得 Shinwell 并没真正变坏。后来，他们发现 Shinwell 是在帮 FBI 在黑帮内做线人。可是这个 FBI 职员并没登记他为正式线人，而只是利用他的信息来抢劫黑帮，最后还嫁祸他杀人。幸亏 Holmes 最终揭露了对方的阴谋，并帮 Shinwell 擦去了凶器上的指纹，他才免去了牢狱之灾。  </p><p>Shinwell 想重新打入黑帮，帮警察做线人，是因为他在监狱内看到不断有他的后来者入狱，他想改变这一切。可是 Holmes 一直不赞成，也认为他没有足够的能力，还尝试说服警察那边不要接纳他，并派人跟踪他。不过，到了最后，Holmes 终于接受了他，并教他当线人的一些必要技能。</p><p>虽说这个剧情是成人之间的侦探类故事，可是却颇有父母和子女相处的影子。  </p><h3 id="给-Ta-我认为好的"><a href="#给-Ta-我认为好的" class="headerlink" title="给 Ta 我认为好的"></a>给 Ta 我认为好的</h3><p>Joan 一开始看到 Shinwell 需要帮助时，她尽自己最大的能力，并把自己认为是最好的东西（做侦探）教给他。我们当父母的，也习惯于把自己经历过的事情，对好坏优劣的判断，教给下一代。这种可能带着血一般痛苦教训的经验，大部分情况下是避免子女走弯路的好事。</p><p>但是，有时对方未必会这么认为，尤其在叛逆期的孩子，或者 Ta 认为你的指导某程度上是贬低 Ta 的时候。</p><p>Holmes 自认为（当然大多数情况确实是）他的智商和判断能力，是碾压很多普通人的，所以他经常非常直言并很没有礼貌地对他人做出指点。大多数的父母，当然也觉得自己的经验和智商都是碾压自己的子女，因为他们还是孩子嘛。所以，他们很常单方面根据自己的判断，决定某些事情是否适合于对方。</p><h3 id="好意被拒绝"><a href="#好意被拒绝" class="headerlink" title="好意被拒绝"></a>好意被拒绝</h3><p>而当你的好意或建议被拒绝，你关心的人看似朝你觉得错误的方向走时，你会怎么办？很多人可能说出类似的气话：  </p><p>“我真是懒得理你了！“<br>”所谓’不听老人言，吃亏在眼前‘，出事了不要来找我！“<br>“你怎么这么倔！”<br>“你不 xxx 就不要认我作老爸！”</p><p>Holmes 得知 Joan 协助 Shinwell 联系警察，登记做正式线人后，则单方面尝试阻碍事情的发生。这其实和有些父母很像。在孩子不认可自己的意见，坚持自己的做法时，有些父母会自作主张地帮对方决定，甚至寻找相关方加以阻挠。</p><p>如果父母靠的是强行灌输意志的方式，来给孩子传承经验和给予指导，很可能会遭遇反弹。并且，或许也会因此抹杀了 Ta 的体验感，破坏 Ta 对自我能力做判断，做决定，和承担相应后果的能力。再说，我们认为的好与坏，未必适用于孩子，未必适应未来社会。</p><p>那我们该怎么做呢？</p><h3 id="妥协后的全力支持"><a href="#妥协后的全力支持" class="headerlink" title="妥协后的全力支持"></a>妥协后的全力支持</h3><p>Shinwell 怒斥 Joan 离开时，Joan 并没有过多斥责，只是表达出我依然关心你，有什么事情随时来找我的态度。  </p><p>Holmes 最后做的，也是值得我们学习的：<strong>明知道对方的决定不是自己认同的方向，但还是尽量协助 Ta，提升 Ta 的能力以更适合向那个方向发展。</strong> 这才能算得上是全心全意的支持。</p><p>现在，很多父母都会说：“我对小孩子没什么要求，只要 Ta 能照顾好自己，找到自己的兴趣，以后想做什么就做什么。”</p><p>这种说辞看起来相当体谅自己的孩子，似乎背后充满了无限的支持。可是，真正落实到生活上，做的和说的就不太一样的：自作主张地报一堆学习班；或者常说 “你看 XXX 的语文&#x2F;数学&#x2F;英语&#x2F;科学&#x2F;政治为什么就那么高分，你怎么才 80 多？”。有多少父母可以接受得了孩子哪怕一点点偏科？他们既要孩子全面发展，又希望 Ta 能有某些特长。我们经常感叹别人家的孩子怎么从小在某些领域就那么厉害，可是自己又有多大的勇气和精力去支持自己的孩子做 Ta 喜欢的事情？  </p><p>“Ta 还小，还没成年，并不知道好和坏，也不知道现在应该做什么。” 这是无数家长的理由，同样也是在一些时候束缚着我的枷锁。在哪些方面可以尊重孩子的选择，哪些应该家长强制要求，我也把握的还不好。<strong>可要到孩子多少岁了，我们才会认为 Ta 可以自己做决定，尊重 Ta 的选择了呢？这个问题值得每位父母思考。</strong></p>]]></content>
    
    
      
      
    <summary type="html">&lt;p&gt;在美剧 Elementary（福尔摩斯）第 5 季里面，Joan Watson 遇到了她当医生时救过的一位贩毒黑帮人员 Shinwell Johnson。Shinwell 在假释期间，表达了对生活的悲观情绪和想重新做人的意愿，Joan 也为他提供了很多帮助。可因为 Shin</summary>
      
    
    
    
    <category term="Think" scheme="http://www.thinkingincrowd.me/categories/Think/"/>
    
    
    <category term="Support" scheme="http://www.thinkingincrowd.me/tags/Support/"/>
    
  </entry>
  
</feed>
