<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Aaron Kuo on Medium]]></title>
        <description><![CDATA[Stories by Aaron Kuo on Medium]]></description>
        <link>https://medium.com/@cloud1985xp?source=rss-f1b64e673d35------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*gAD_LmXjcx09vTcI.jpg</url>
            <title>Stories by Aaron Kuo on Medium</title>
            <link>https://medium.com/@cloud1985xp?source=rss-f1b64e673d35------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 12:12:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cloud1985xp/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Maintenance Mode of API Server]]></title>
            <link>https://medium.com/@cloud1985xp/maintenance-mode-of-api-server-92951fd85fa5?source=rss-f1b64e673d35------2</link>
            <guid isPermaLink="false">https://medium.com/p/92951fd85fa5</guid>
            <category><![CDATA[maintenance-management]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[alb]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[api-server]]></category>
            <dc:creator><![CDATA[Aaron Kuo]]></dc:creator>
            <pubDate>Fri, 09 Aug 2019 08:01:01 GMT</pubDate>
            <atom:updated>2019-08-09T08:01:01.301Z</atom:updated>
            <content:encoded><![CDATA[<p>在曉數碼 Server Application 主要的服務就是提供 API 服務給遊戲的 Client 端，而隨著營運與版本更新的安排，遊戲伺服器就會有所謂「進入維護模式」的情況。本文稍微介紹了各時期敝團隊在 Server Maintenance Mode 的幾種實作方法。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Ve_LId1YGNSrNT9ubCgAFw.png" /></figure><h3>Maintenance Switch at Application Layer</h3><p>做為 Server 端開發的工程師，可以很簡單地在 Controller 的 super class 加上一個 filter 來進行檢查 — 就如同檢驗每個 request 是否來自正確的 session 一樣。當 filter 判斷目前系統處於維護模式，即提前返還帶有維護資訊內容的 Response 給 Client 端。</p><p>Example in Rails:</p><pre>class ApiController &lt; ApplicationController<br>  before_action :check_maintenance</pre><pre>  def check_maintenance  <br>    render json: Maintenance.to_json if Maintenance.on?<br>  end<br>end</pre><p>再搭配建置後台，就可以讓營運人員可以開啟/關閉維護模式</p><p>然而這種方法下，每個 Request 仍然會對 Server 造成 overheads，在進入維護模式後其實仍然要維持服務，甚至還要有承受一定程度負載的能力</p><p>換言之，Application Service 其實還是在服務 Client，不論背後是要部署程式或改動資料庫等操作，都要顧及不能有 downtime 或炸掉 application 的事情發生 — 視 controller/filter 依賴什麼配置而定，更不用說要去變動 Infrastructure 之類的。（對，維護模式其實維護的不是伺服器)</p><h3>Maintenance at Web Server</h3><p>另一種常見方式是透過 web server (ex: Nginx) 設定規則來實現，常見的方式就是檢查某個代表維護模式的 flag (例如某個本地檔案是否存在)，成立的話就直接回應或導向正在維護的訊息給 client，這樣就完全不需要進到 application level，大大減少資源的浪費。</p><p>Example in Nginx:</p><pre>server {         <br>  listen      80;<br>  //....</pre><pre>  location / {<br>    if (-f $document_root/maintenance.json) {<br>      return 503;<br>    }<br>    ... # the rest of your config goes here<br>  }<br>  error_page 503 @maintenance;</pre><pre>  location @maintenance {<br>    rewrite ^(.*)$ /maintenance.json break;<br>  }<br>}</pre><p>這樣 Client Request 尚未進到 Application Layer 就被回應了， 不會受到 Application Service 的狀態影響。</p><p>但在 Large Scale 的架構下，會有多台的 Server 來處理 Client 的請求，如此就必須使每一台 Server 都讓規則成立，例如若是用本地檔案判斷，那就必須在每台 server 上都存在該檔案（或是讓各台 web server  共享 storage 取得維護標記與內容）</p><p>此做法讓 Application 被隔離且可以中斷服務，但此維護運作與原本運行的 Server 仍有依賴，至少跑在同機器上的 web server 不能掛掉。當需要變動底層 Infra. 時依然可能遇到麻煩。</p><h3>Maintenance with Load Balancer</h3><p>為了要讓伺服器真正進入可被維護的狀態，我們直接在 Load Balancer 進行操作。</p><p>在早期使用 AWS Classic Load Balancer 的時候，我們是直透過用替換 Load Balancer 中的 server，來實現隔離 Application Server 的維護模式</p><p>作法是另準備一台獨立的 server，上面跑的 http service 就僅單純地回覆代表維護資訊的 static content。在當開啟維護模式的時候，將該 Server Instance 加到 Load Balancer 中，然後將原本 Load Balancer 中的所有 Application Server 移出。</p><p>如此在維護期間，將由單純回覆維護訊息的 server 負責回應 client 的請求，主要的 Application 環境此時完全與外界分離，這時想怎麼操作它都可以了。</p><p>不過要將大量機器移出 Load Balancer 也是需要一點點時間的…</p><h3>Loader Balancer Listener Rule</h3><p>後來升級到 Application Load Balancer，有了 Listener &amp; Target Group 的機制，更可以直接控制 Listener Rule 來實現所需的維護模式</p><p>作法一：導向不同的 Target Group</p><p>與 Classic Load Balancer 作法類似，但讓 Application Server 與負責回應維護資訊的 Web Server 分處兩組不同的 Target Group。</p><p>在啟用維護模式時，直接把所有 Request 改成導向放置 static content 的 Web Server 所在的 Target Group 就行，如此一來，變更 Rule 所需的時間遠小於 ELB 替換 server 的法作，而且穩定許多。</p><p>作法二：使用 Rule Condition + Fixed Response Action</p><p>ALB 的 Listener Rule 可以直接設定成回應固定內容，搭配 Rule Condition，這樣連額外的 static server 都不用準備了。</p><p>例如只要設定 Request 條件為所有路徑 ( path=/*) 即回應帶有維護資訊的 json 內容即可以了</p><p>但在初期 ALB Listener Rule 支援的 Condition 類型太少了，因為我們 API 的設計必須依 Request Header 來判斷回應的 content 的語系（所以才先採用了方法一）。</p><p>而現在， ALB Listener 已經支援 Http Header Condition 了。</p><p><a href="https://docs.aws.amazon.com/en_us/elasticloadbalancing/latest/application/load-balancer-listeners.html#http-header-conditions">https://docs.aws.amazon.com/en_us/elasticloadbalancing/latest/application/load-balancer-listeners.html#http-header-conditions</a></p><p>直接呼叫 AWS CLI 就可以簡單完成了</p><p>e.g.:</p><pre>message=$(cat maintenance_message_zh.json)</pre><pre>aws elbv2 create-rule \<br>  --listener-arn $YOUR_LISTENER_ARN \ <br>  --conditions &#39;Field=path-pattern,Values=/*&#39; &#39;Field=http-header,HttpHeaderConfig={HttpHeaderName=X-Language,Values=&quot;zh&quot;}&#39; \<br>  --priority 99 \<br>  --actions &#39;Type=fixed-response,FixedResponseConfig={MessageBody=&quot;&#39;&quot;$message&quot;&#39;&quot;,StatusCode=503,ContentType=application/json}</pre><ul><li>Conditions: 針對 1. 所有路徑 2. Header 帶有 X-Language 值為 zh 的 Request</li><li>Actions: 回覆固定內容，並指定 Body (內容來自 .json 檔) + 503 Status+ ContentType 為 application/json</li><li>Priority: 99(蓋過原本正常的 Forwarding rule)</li></ul><p>要注意的是 AWS CLI 的版本需要更新 (我是升到 aws-cli/1.16.208) 才行，不然它會出現不支援 http-header 參數的錯誤</p><p><a href="https://forums.aws.amazon.com/thread.jspa?messageID=897663">https://forums.aws.amazon.com/thread.jspa?messageID=897663</a></p><p>而結束維護模式，只要把剛建立的 Rule (priority=99) 刪除即可</p><p>e.g.:</p><pre>rule_arn=$(aws elbv2 describe-rules --listener-arn &quot;$YOUR_LISTENER_ARN&quot; | jq -r &#39;.Rules | select(.Priority == &quot;99&quot;) | .RuleArn&#39;)<br>aws elbv2 delete-rule --rule-arn &quot;$rule_arn&quot;</pre><h3>結語</h3><p>這是為了把應用層環境與外部隔絕，讓工程師可以放心地對伺服器們做照顧。我們的維護模式的一路實作演進。</p><p>當然在不同的環境架構（例如用 API Gateway 的情況，或在 Kubernetes 用 Ingress？)、因應不同需求，相信都有不同的選擇與作法。</p><p>若有何任想法或問題，歡迎留言討論指教～</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92951fd85fa5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[在 Rails Application 使用 Http Authentication]]></title>
            <link>https://medium.com/@cloud1985xp/%E5%9C%A8-rails-application-%E4%BD%BF%E7%94%A8-http-authentication-fc6f5c4b097f?source=rss-f1b64e673d35------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc6f5c4b097f</guid>
            <category><![CDATA[http-authentication]]></category>
            <category><![CDATA[racks]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[Aaron Kuo]]></dc:creator>
            <pubDate>Fri, 29 Mar 2019 10:21:34 GMT</pubDate>
            <atom:updated>2019-03-29T10:36:50.872Z</atom:updated>
            <content:encoded><![CDATA[<p>by Aaron Kuo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*MMdvQ4UsDJe_SmS_2zZtcQ.png" /></figure><p>當你的 web application 是非公開的服務、必須保護不被陌生的使用者存取的時候，會需要建立某種身份驗証的機制 — 當然你可以選擇直接掛個 devise 或設計你的使用者管理系統 — 但若你的服務不是那麼龐大，或不想花太多額外的成本來處理身份驗証，那麼 HTTP level 的身份驗証或許就是一個簡單又快速的選擇。</p><h4>什麼是 HTTP Authentication</h4><p>HTTP Authentication 是 HTTP 定義的一種簡單的驗証機制；啟用 HTTP Authentication 的 uri 會在瀏覽器訪問該位置時，若 request 中未帶有經過驗証的憑証時，server 會回傳 401 status 並附帶一個 challenge-response 的資訊，</p><p>瀏覽器接收到這樣的 response 時，會直接跳出原生的對話視窗，要求輸入使用者名稱及密碼，在用戶輸入正確的身份識別後，http server 會產生一組 credentials 回傳給 browser，而 browser 會在而後發送的 requests 之中重複利用這組 credentials 來通過檢查</p><h4>常見的 HTTP Authentication Scheme</h4><p>而 HTTP Authentication Framework 中定義多種不同的 Scheme，它提供了不同的處理方式和驗証強度，有些 Scheme 則可能被不同的 client 或軟體所支援、用在不同的情境，例如數位簽章或 Oauth 驗証。而瀏覽器上最常見的 Scheme 即為 Basic 與 Digest Authentication</p><h4>Basic Authentication</h4><p>如名就是最基本的處理方式，browser 會將使用者輸入的用戶名稱和密碼用「:」拼接後以 base64 編碼，放在 Header 中送出，HTTP server 收到後再 decode 後進行檢驗。</p><p>因為是用 base64 編碼所以相當不安全，在 HTTP 明文傳送下，只要被欄截下來取得 header 資料，再以 base64 decode，就能清楚知道原文。它的目的充其量只是為了轉換字元而非安全；因此建議只在 https 下以及私有環境中使用。</p><h4>Digest Authentication</h4><p>相較 Basic 就安全許多，Digest Authentication 是利用MD5 雜湊演算進行非對稱加密， 傳輸過程中 Header 放的是加密後的值，基本上是較難以破解的。加上 Digest Authentication 驗証時引入了 nonce 值，來阻擋用戶端利用重放攻擊的方式去猜測密碼的情況</p><h4>如何啟用 HTTP Authentication</h4><p>既然是 HTTP Protocol 的協議，那最直接的方式就是從 HTTP Server 進行配置啦，以 nginx 為例，在它的網站上都有清楚的說明</p><ul><li><a href="https://www.nginx.com/resources/wiki/modules/auth_digest/">HTTP Digest Authentication | NGINX</a></li><li><a href="https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/">Restricting Access with HTTP Basic Authentication</a></li></ul><p>但如果你只是開發者，並不熟悉 Http Server 的管理或者是在無法更動 Http Server 配置的情況下，該怎麼辦呢？</p><p>如前所述，HTTP Authentication 的機制就是以 response 的 header 來運作，所以我們當然還是可以透過 Application 層來達成，更棒的是，ruby 的 Rack app 本身就已經有實作 Http Authentication 的 Middleware 供使用的</p><ul><li><a href="https://www.rubydoc.info/gems/rack/Rack/Auth/Basic">https://www.rubydoc.info/gems/rack/Rack/Auth/Basic</a></li><li><a href="https://www.rubydoc.info/gems/rack/Rack/Auth/Digest/MD5">https://www.rubydoc.info/gems/rack/Rack/Auth/Digest/MD5</a></li></ul><p>所以不管是 Rails 還是 Sinatra，想當然而我們可以簡單地將它加在 Middleware 中</p><p>以 Rails 為例，只要修改專案目錄中的 confige.ru:</p><pre>USERS = {<br>  &#39;username&#39; =&gt; &#39;password&#39;<br>}</pre><pre>use(DigestAuth, {<br>  realm: &#39;MyApp&#39;,<br>  opaque: &#39;secret&#39;<br>}) do |user|<br>  USERS[user]<br>end</pre><pre>run Rails.application</pre><p>（這裡僅以 Digest Auth 為例，Rack 同樣也提供有 Basic Auth，但它相對簡單又不安全，在這兒就不管它了）</p><ul><li>realm: 是讓用戶端視別現在與在登入的對象，同時也是加密原文的一部分。</li><li>opaque: 是伺服器定義好的固定字串，客戶端在回覆時必須以原值回返，用於識別正確來源的請求。</li><li>這裡的 USERS 常數中即定義好的用戶密碼對照，可自行選擇實作方式</li></ul><p>如此就能為你的網站加上 digest authentication 了</p><h4>加密</h4><p>當然你會發現這樣子對 config.ru 的修改，不就會把密碼 commit 進程式原始碼了嗎？解決辦法就是設置 passwords_hashed 這個參數，告知 DigestAuth 回傳值是已加密過的，這樣定義的密碼表就可以改成 MD5 加密過後的資料，例如：</p><pre>USERS = {<br>  &#39;username&#39; =&gt; &#39;42e47ee89fbd5a7fd1a1e0e36751da07&#39;<br>}</pre><pre>use(DigestAuth, {<br>  realm: &#39;MyApp&#39;,<br>  opaque: &#39;secret&#39;,<br>  passwords_hashed: true<br>}) do |user|<br>  USERS[user]<br>end</pre><p>根據 Digest Authentication 的驗証值是以 username:realm:password 組成<br>所以定義的加密值即需以此規則進行編碼，例如：</p><pre>Digest::MD5.hexdigest(&#39;username:MyApp:12345678&#39;)</pre><h4>HTTP Server or Rack Application?</h4><p>如果能在 HTTP Server 就進行配置，讓 Request 不用再進到 web application 層才做處理，當然會是比較高效的作法啦。</p><p>不過在 Application layer 來處理的話，則又多了一些 Programatic 的操作性，例如組織政策上除了要在安全機制加上 HTTP Authentication 外，可能還會希望它的密碼會是定期變換的，耶~這時我們就可以在實作上加入一些操作。</p><pre>USERS = {<br>  &#39;username&#39; =&gt; {<br>    Date.new(2019, 1, 1) =&gt; &#39;...&#39;,<br>    Date.new(2019, 2, 1) =&gt; &#39;...&#39;,<br>    Date.new(2019, 3, 1) =&gt; &#39;...&#39;,<br>    Date.new(2019, 4, 1) =&gt; &#39;...&#39;,<br>    Date.new(2019, 5, 1) =&gt; &#39;...&#39;,<br>}</pre><pre>use(DigestAuth, {<br>  realm: &#39;MyApp&#39;,<br>  opaque: &#39;secret&#39;,<br>  passwords_hashed: true<br>}) do |user|<br>  USERS[user][Time.zone.now.to_date.beginning_of_month]<br>end</pre><p>嘿，這樣每個月就會變成採用不同的密碼啦</p><p>不過 Nginx (or 其他 http server)我想應該也能有辦法實現啦，有待 nginx 能手釋疑；但能用 ruby 完成它，應該是簡便又更容易維護吧(笑)</p><h4>結語</h4><p>HTTP Authentication 當然不是絕對安全的，但至少是一種提高破解難度的手段；又或可以輕便地在私有環境內再加上一層保護機制，畢竟若只是要殺雞就別用牛刀啦。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc6f5c4b097f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS RDS First Touch Penalty]]></title>
            <link>https://medium.com/@cloud1985xp/aws-rds-first-touch-penalty-6eeefc9ef60c?source=rss-f1b64e673d35------2</link>
            <guid isPermaLink="false">https://medium.com/p/6eeefc9ef60c</guid>
            <category><![CDATA[rds]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Aaron Kuo]]></dc:creator>
            <pubDate>Mon, 03 Apr 2017 14:38:26 GMT</pubDate>
            <atom:updated>2017-04-03T14:38:57.626Z</atom:updated>
            <content:encoded><![CDATA[<p>最近工作上遇到了 first touch penalty 的問題</p><p>由於營運的需求，必須 scale out 原本的 user shards，作法是將原本的 shard db(RDS) 做 snapshot 後再 restore 成 double 數量的 instance。這時就產生 First touch penalty 的問題</p><h4>What is First Touch Penalty?</h4><p>RDS 從 snapshot restore instance 時，由於 EBS 新掛載的 disk area 尚未與 db system 完全連結，所以資料在初次被查尋時，RDS 需要額外花費更多的時間，就像是在對資料所在的區域進行「暖機」活動</p><p>這個問題對 全新建立的db/寫入 倒沒有明顯的影響，但若是從既有的 snapshot restore 時，當執行 select 資料時，RDS 就必須掃過初次啟用的 disk area，找到既存的資料內容。</p><h4>What’s the Affect?</h4><p>就當時實測原本300ms以內能完成的query，在遭受 first touch penalty 的狀況下竟花了超過 15sec 才完成。</p><p>據說日方那邊就因為這個問題一堆人進來 db 就慢成龜速，然後服務炸掉了。</p><h4>What’s the Solution?</h4><p>根據 aws 技術人員提供的解決方案，在 snapshot restore 之後，可先對整個db 下 dump 操作，讓 RDS 對每張 table 的每筆資料都 scan 一遍</p><p>mysqldump database &gt; /dev/null</p><p>除此之外，還需也對每張 table 做 analyze 指令，讓 index 資料也被跑過</p><p>mysql&gt; analyze table_name</p><h4>What we did</h4><p>當時我們預先測試 dump 一份剛 restore 完的 db，需要將近 10 小時才能完全處理完成；但這遠遠超過我們期望的維護時間</p><p>後來我們整理了各張 table 的重要順序，並寫 scripts 改對一張一張 table 單獨執行 dump，並將權重較低的放在後面處理。</p><p>dump 的時候還特別注意 bandwidth 的問題，因為同時有多個 shard db 都做 dump，其實 dump 的資料還是有傳回 client；為此我們還開了最大台的 ec2 來操作 （我們 engine 是用 mysql，若是 Postgresql 好像就另有指令 dump 在 server local 即可）；不然，多分散幾台 client 來做也是可以。</p><p>不過好險這些問題都是日方先踩過地雷給的經驗，我們才有時間預先規劃進一步的對策。</p><h4>參考資料</h4><ul><li><a href="http://ramblingsofraju.com/sql-server/aws-rds-first-touch-penalty/">http://ramblingsofraju.com/sql-server/aws-rds-first-touch-penalty/</a></li><li><a href="http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Storage.html">http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Storage.html</a></li><li><a href="https://digitalovercast.wordpress.com/2016/03/22/first-touch-penalty/">https://digitalovercast.wordpress.com/2016/03/22/first-touch-penalty/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6eeefc9ef60c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RSpec 入門一點補充]]></title>
            <link>https://medium.com/@cloud1985xp/rspec-%E5%85%A5%E9%96%80%E4%B8%80%E9%BB%9E%E8%A3%9C%E5%85%85-d045482f472a?source=rss-f1b64e673d35------2</link>
            <guid isPermaLink="false">https://medium.com/p/d045482f472a</guid>
            <category><![CDATA[rspec]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Aaron Kuo]]></dc:creator>
            <pubDate>Fri, 21 Oct 2016 03:29:01 GMT</pubDate>
            <atom:updated>2016-10-21T13:49:37.178Z</atom:updated>
            <content:encoded><![CDATA[<p>聽了某場分享 Rspec 入門後…私心覺得應該要被提及的幾個主題</p><p>沒提這些，別說是在分享 Rspec (狂) …</p><h4>一、物件導向的基礎：請區分公開和私有方法</h4><p>許多寫 rails 的朋友，尤其是接受「直接學 rails、不需要先學 ruby/oop 」學習路徑的開發者，若對物件導向的概念可能不是很清楚，容易忽略掉這點：在設計類別的方法時，至少做到區分 public 與 private/protected methods。換句話說，你的類別要清楚定義它所對外的介面是哪些。</p><p>因為一般來說，你只需要針對你的 public method 去寫 test。換言之，只要 public method 的測試覆蓋率足夠，private method 就應該也都被測試到（不然就是你的 class 設計有問題…）</p><p>所以養成區分 public/private method 的習慣，可以讓你有機會少寫一些單 元測試。（或著當別人來幫你補測試的時候可以少罵幾句）</p><h4>二、Testing 的概念</h4><p>講 rspec 怎麼能不先提 testing 的基本流程呢：每一個測試，可分為三個步驟 (AAA)</p><ol><li>初始化情境(Arrange)：先把測試的情境設定好</li><li>執行測試目標(Act)：執行你要測試的方法</li><li>驗証結果(Assertion)：驗証結果</li></ol><p>例如要測試「計算 BMI」的方法</p><ol><li>準備好要用來計算的資料/參數</li><li>執行計算的方法</li><li>驗証結果的數值</li></ol><p>寫成 Rspec 就像是</p><pre>it ‘return correct bmi value’ do<br>  student = Student.create(                   # Arrange<br>    name: &#39;Tom&#39;, height: 160, weight: 56<br>  )<br>  result = student.calculate_bmi              # Act<br>  expect(result).to eq(21.875)                # Assertion<br>end</pre><p>有了上述AAA的概念，才能引入 rspec 裡 before、let、subject、等 DSL 的使用，不然初學的聽眾可能會不知道你在幹什麼（如果過程又不詳加解釋的話…），搭配 AAA 的原則，比較能組織化的閱讀/撰寫你的測試</p><h4>三、Arrange</h4><p>測試的情境多了，在 Arrange 階段常有重複的程式碼，所以可以利用 before, let 以及 describe/context 巢狀的設計來讓程式碼更精簡與保持閱讀性</p><pre>describe &#39;#published&#39; do<br>  let(:article) { Article.create(title: &#39;foo&#39;, content: &#39;bar&#39;) }</pre><pre>  context &#39;an article published on past date&#39; do<br>    before do<br>      article.publish_on = Date.current.days_ago(3)<br>    end<br>    it &#39;should be published&#39; do<br>      expect(article.published?).to eq(true)<br>    end<br>  end</pre><pre>  context &#39;a article is publishing on future date&#39; do<br>    before do<br>      article.published_on = Date.current.days_since(3)<br>    end<br>    it &#39;should not be published&#39; do<br>      expect(article.published?).to eq(false)<br>    end<br>  end<br>end</pre><p>Arrange 階段常需要建立情境所需的資料，但資料內容往往重複性很高，因此又有 test fixture 的概念來維護測試資料的建立，但 rspec 我們又常用 factory girl 來取代 fixture，它提供更方便的 DSL 來組織你的假資料內容。</p><p>簡單說好處可以為建立的資料命名，透過這些命好名的 factory 來造出資料，factory 支援 lazy attribute、trait、nested 設計等特性，一來減少重複的程式碼、易於維護，二來有名稱用起來很方便（可以想像類似 scope 的好處）；命名是很重要的耶。</p><h4>四、Assertion/Matcher</h4><p>其中 Assertion 的部分常會有各種不同的驗証，rspec 在這方面更貼近自然語言地設計了許多幫助進行驗証的方法，叫做「matcher」，例如常見的：eq, respond_to, include, match_array, raise_error ….等</p><pre>expect(user.name).to eq &#39;James&#39;<br>expect(user).to respond_to(:admin?)<br>expect(user.courses).to include &#39;English&#39;<br>expect(user.courses).to match_array [&#39;History&#39;, &#39;English&#39;]<br>expect { user.save! }.to raise_error(SomeError)</pre><p>所以當你不確定要怎麼寫 assertion 時，可以 google `rspec matcher` 看看吧</p><p>另有一個常見但還算特別的用法：be_xxx，這是個動態 matcher，rspec 會對你要驗証的對象執行 xxx? 這個方法並檢驗回傳的 boolean 值</p><p>例如</p><pre>expect(article).to be_published</pre><p>即是驗証呼叫 article.published? 要回傳 true 的意思</p><p>因此若你要驗証的對象有 #xxx? 這個方法可呼叫，你都可以用 be_xxx 這個 matcher 來做 assertion。</p><p>不過 rspec 也有內建 be_truthy, 跟 be_falsey 就是了</p><pre>expect(article.published?).to be_truthy</pre><p>此外，你當然也可以自行擴充 rspec 的 matcher，google `rspec custom matcher`</p><h4>五、不是把重複的 code 搜尋取代就叫 shared example/refactoring …</h4><p>要 demo shared_example 時請講解一下它的內涵</p><p>每次展示完 share example，聽完還是霧煞煞</p><p>`然後咧？什麼時候要用它？`</p><p>使用 shared example 的時機，通常意味著這些物件們，但具有相同的 Act 並用共同的 Assertion 做驗証；「相同的 Act」 ，所以它叫某種 behavior，重點還是回歸到 OOP 的思維阿。</p><p>註：shared example 不僅限於單個 spec 檔裡的使用阿，通常它是被 shared 給多個不同 class 卻有相同行為而設計的測試</p><p>我的經驗是在於你能否抽象化的描述這些物件的某些共同行為，在思考抽像化描述的過程，其實就是在為這個 behavior 命名（搜尋取代誰不會，工程師最難的任務是命名阿）</p><pre># blog_spec.rb<br>describe Blog do<br>  it_behaves_like &#39;a publishable content&#39;<br>end</pre><pre># article_spec.rb<br>describe Article do<br>  it_behaves_like &#39;a publishable content&#39;<br>end</pre><p>當在為它命名的同時，才會去思考它背後代表含義，再來決定該不該設計 shared example 做測試</p><p>所以拜託，不要只是把重複的程式碼 find &amp; replace，然後表現得`很精美，用 shared example 就是潮`，這樣是有可能誤了台下的初學者</p><p>另一個相關的議題：寫 test 時要避免過度 DRY？</p><h4>六、Rspec 是個框架</h4><p>不要急著進 live demo，稍微介紹一下這個框架吧，目錄結構、設定檔、helper…，就算急著要火力展示 gem 多好用，有些也是需要去改設定檔的。</p><h4>七、其他</h4><p>Coverage: <a href="https://en.wikipedia.org/wiki/Code_coverage">https://en.wikipedia.org/wiki/Code_coverage</a></p><h4>結論</h4><p>其實只有一、二項比較重要，其他都是話唬爛的</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d045482f472a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When Pepper meets Watson 講座筆記]]></title>
            <link>https://medium.com/@cloud1985xp/when-pepper-meets-watson-%E8%AC%9B%E5%BA%A7%E7%AD%86%E8%A8%98-b00281f0d546?source=rss-f1b64e673d35------2</link>
            <guid isPermaLink="false">https://medium.com/p/b00281f0d546</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[pepper]]></category>
            <category><![CDATA[humix]]></category>
            <category><![CDATA[bluemix]]></category>
            <category><![CDATA[ibm-watson]]></category>
            <dc:creator><![CDATA[Aaron Kuo]]></dc:creator>
            <pubDate>Fri, 15 Jul 2016 18:07:35 GMT</pubDate>
            <atom:updated>2016-07-16T06:33:39.789Z</atom:updated>
            <content:encoded><![CDATA[<h3>Preperspective</h3><p>此次的講者是來自 IBM 的 Jeffery，為什麼我說是場很 IBM 的 talk</p><p>因為自學生時代，每當課堂上或 seminar 邀請了 IBM 的講者，內容總是滿滿的產品介紹<br>但也許是那時年輕，沒有清楚了解其問題背景與需求，所以總覺得很濃的商業味，感到只是一味照本宣科在推銷產品<br><br>現在似乎是稍微懂事了，比較能擺脫以前的刻板印象，還有從中學習些什麼</p><h3>Bluemix + Watson API</h3><p>整場 talk 有一半以上的時間在介紹 Bluemix &amp; Watson 吧<br>Bluemix 簡單說就是 IBM 推的 PaaS，而 Watson API 就是它與 Heroku 最大不同之處</p><p>使用 Bluemix 的 deployment 可以簡單快速地在上面設置各種 Watson API，而 Watson API 則提供了各種諸如人工智慧、機器學習、語音圖形辨識等功能的強大服務</p><p>講者有介紹了滿多支 API 的，之後應會釋出投影片可以再去詳閱，其中有幾個比較推薦&amp;我覺得滿有興趣的，像是</p><ul><li>Tradeoff Analytics</li><li>Visual recognition</li><li>Conversation</li></ul><h3>Humix</h3><p>介紹完 bluemix&amp;watson 後，才進入比較跟 pepper 有關的部分</p><p>雖然 Pepper 本身即為 embedded system 並有 SDK 可做開發<br>但相較於直接用 pepper 的 choreographe 開發所有想要的 pepper 功能，講者更傾向於「小腦 + 大腦」的設計<br><br>小腦即運行在 pepper 本身的 process<br>大腦則是架設在雲端的 server<br><br>這樣的架構下小腦基本上只負責輸入與輸出（語音/視覺辨識，肢體/情感表達），而主要行為決策（Process），其實是依賴雲端的大腦</p><p>主要原因：</p><ol><li>架構設計上更加彈性化</li><li>真正賦予機器人「學習」的能力</li><li>目前 pepper 本身的硬體即不適合做大量運算</li></ol><p>講者有稍微介紹到只在 pepper 本地端實作 conversation 的例子：<br><br>choreographe 本身有提供 framework 去實作它，但它就是去編寫一個 xml 檔來定義句詞；比較像 rule base，換句話說就是預先要把可能的對話定義出來<br><br>接著就是這次的主題 Humix framework 了<br><br>Humix 是 2014年 Hackthon Taiwan 時講者的團隊開發出的 framework，那時似乎是為 IoT 而設計的架構，主要分兩個部分 (<a href="https://github.com/project-humix/humix-ng">https://github.com/project-humix/humix-ng</a>)：</p><ul><li>humix-think (相當於 server side，即大腦）</li><li>humid-sense (相當於 client side，即小腦)</li></ul><p>humix-think 我想包含了是一個 socket server + web platform；<br>socket server 負責與 sense 溝通以及控制整個 bot 的 workflow<br>而實作的後台介面（好像叫 NodeRed）可以簡單的建立你的 bot flow 並且與 Watson API 串接<br><br>此外 humix-think 上還可以再接其他的 messaging channel，例如 Facebook Messenger 或 Slack，換句話說在 FB Messenger 丟個指令就可以去控制連線的機器(人) 啦</p><h4>舉例</h4><ol><li>先在 bluemix 上啟用 watson conversion 這項 api 服務</li><li>在 watson conversion 這邊設計好你的 intends dialoge （例如詢問天氣）</li><li>然後在 humix 上去拉出你要的 flow 接到 watson conversion</li></ol><p>所以當 humix-think 接收到來自 sense(pepper) 的訊息時，就依照 flow 被丟進 watson conversation，然後得到 conversation api 的回應後<br>humix-think 再把指令丟回給 client</p><h3>Humix on Pepper</h3><p>而在 pepper 這端，講者有大概解釋一下架構<br>加上我的理解（這邊我不確定怎麼實作的，是用 choregraphe 開發 還是直接登進 pepper terminal 做；或者兩者都有）：<br><br>它在 pepper 上建立一個 message queue（用的是 NATS http://www.nats.io/）</p><p>架構是採 message bus 來做 publish/subscribe，message bus 上主要有三個 module （1、2我有點不太確定，簡單來說 1+2 與 3 吧）</p><ol><li>pepper 內建的 tts/stt (Text to Speech/ Speech to Text)</li><li>pepper 的 QiMessage，好像是要操控它的 behavior (例如 做出動作、在顯示器上顯示圖像)</li><li>用 node 寫的 app （應該就是 humix-sense 啦）來 publish/subscribe NATS 上的 message ，並透過 websocket 與 humix-think 溝通</li></ol><p>簡單說 pepper 本地的小腦其實只負責 tts 與 stt 與 behavior (QiMessage)</p><p>將 stt 得到的 text 透過 message bus publish 到 humix-sense，再透過 web socket 送到 humix-think</p><p>當 humix-think 送來訊息後 humix-sense 再把它 publish 回去給 pepper 上的 module 看要做什麼（給 tts 說出來或用 QiMessage API 去做出預先設定好的動作 ex: 跳舞）</p><h4>沿續剛才的例子</h4><p>從上面的例子來說，當你對 pepper 說「明天會下雨嗎」</p><p>pepper 內建的 stt 模組接收到語音辨識為文字，然後 publish 到 NATS message bus 上，humix-sense receive 後把訊息送到 humix-think</p><p>humix-think 根據 flow 把訊息打進 watson conversion API</p><p>然後就根據你在 conversation API 上設計好的 dialogue 路徑去解析 intends （這邊 Watson API 是有透過 machine learning 的機制來辨識）<br><br>得到要回應的對話內容，再從 server 打回給 pepper 上的 humix-sense，經由 message bus 回到 tts/stt 模組上，於是 tts 就要 pepper 把回應的內容用語音傳達出來</p><p>簡言之， 就是設法把機器人要處理的問題 delegate 給 IBM Watson API 去處理啦（看要 NLP, Visual Recognition 還是 Machine Learning，任君挑選）</p><h3>Conclusion</h3><p>humix-think 才是大腦的核心，而且它整合了 IBM watson 的各種人工智慧相關 API，所以大家還是快去用 Bluemix 吧，結案～<br><br>哈 上面那段是我自己加的</p><p>其實講者有提到，也不能全依賴雲端大腦<br>兩者應要適當的並用，而且機器人難免會遇到無法連上網路的情況，<br>因此還是對網路環境不友善的情景做處理，才能達到人性化的體驗</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b00281f0d546" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>