<?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[Airframe - Medium]]></title>
        <description><![CDATA[Lightweight Building Blocks for Scala https://wvlet.org/airframe/ - Medium]]></description>
        <link>https://medium.com/airframe?source=rss----2320a6abf699---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Airframe - Medium</title>
            <link>https://medium.com/airframe?source=rss----2320a6abf699---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 18:27:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/airframe" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Scalaを少しだけ使いやすくするAirframe: Updates 2023]]></title>
            <link>https://medium.com/airframe/scala%E3%82%92%E5%B0%91%E3%81%97%E3%81%A0%E3%81%91%E4%BD%BF%E3%81%84%E3%82%84%E3%81%99%E3%81%8F%E3%81%99%E3%82%8Bairframe-updates-2023-8c8db21211f8?source=rss----2320a6abf699---4</link>
            <guid isPermaLink="false">https://medium.com/p/8c8db21211f8</guid>
            <category><![CDATA[airframe]]></category>
            <category><![CDATA[vitejs]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[rpc]]></category>
            <dc:creator><![CDATA[Taro L. Saito]]></dc:creator>
            <pubDate>Sun, 31 Dec 2023 07:19:46 GMT</pubDate>
            <atom:updated>2024-01-01T07:49:54.006Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UQnXgg9B2zD8GTNb" /></figure><p><a href="https://github.com/wvlet/airframe/">Airframe</a>はScalaでの開発を支援するOSSライブラリ集です。Scalaというプログラミング言語は、オブジェクト指向と関数型言語の良いところ取りをした言語で拡張性が優れているため、静的型付けを活かした高速化とコードの品質を同時に追い求められるような開発経験の深いエンジニアほどその恩恵にあずかりやすいのが特徴です。Scalaを使い始めて10年以上になっていますが、年々できることが増えていて手放せない言語になっています。</p><p>2023年には、Scala 3への完全対応、HTTP/RPCバックエンドのNettyへの切り替え、Futureに替えてRx (reactive)インターフェースでの非同期(async)処理の標準化、RxによるDOMレンダリング機能の強化（tap, onMountなど)、DuckDBサポート、JDK21、Node.js 20への対応、SQLコンパイラの機能・品質改善など、多くの更新がなされました。<a href="https://github.com/wvlet/airframe/releases">リリースノート</a>をPull Requestのタイトル、ラベルからGitHub Actionで自動生成するようにしたことでメンテナンスも楽になりました。</p><p>他にもscala-cliでもAirSpecなどが動くようになり、手軽に使い始められます。</p><h3>Taro L. Saito on Twitter: &quot;Writing tests with AirSpec is much easier now with scala-cli https://t.co/ZXyUCXMEP3 #Scala pic.twitter.com/3WAIto3LE2 / Twitter&quot;</h3><p>Writing tests with AirSpec is much easier now with scala-cli https://t.co/ZXyUCXMEP3 #Scala pic.twitter.com/3WAIto3LE2</p><p>AirframeのSQLコンパイラは、現在、<a href="https://github.com/xerial/dp-readings">差分プライバシー(Differential Privacy)</a>の技術を取り入れたクエリエンジンサービスのコアとして、プロダクションでも使われています。この内容は2023年12月の<a href="https://trino.io/blog/2023/12/18/trino-summit-recap.html">Trino Summit 2023</a>で紹介しました。</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fspeakerdeck.com%2Fplayer%2Fa88646b752db47adaaaf48e3024df9e1&amp;display_name=Speaker+Deck&amp;url=https%3A%2F%2Fspeakerdeck.com%2Fxerial%2Fsecure-exchange-sql-building-a-privacy-preserving-data-clean-room-over-trino-trino-summit-2023&amp;image=https%3A%2F%2Ffiles.speakerdeck.com%2Fpresentations%2Fa88646b752db47adaaaf48e3024df9e1%2Fslide_0.jpg%3F28187282&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=speakerdeck" width="710" height="399" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd561e20f4fb9019cf8a1c3699ddc0eb/href">https://medium.com/media/fd561e20f4fb9019cf8a1c3699ddc0eb/href</a></iframe><p>Scala.jsを活用したUI開発では、<a href="https://vitejs.dev/">Vite.js</a>と組み合わせることで、コードを変更するなりブラウザに反映されるというインタラクティブなUI開発体験が実現され快適になってきました。<a href="https://github.com/wvlet/airframe/edit/main/examples/rpc-examples/rpc-scalajs/ui/src/main/scala/example/ui/ExampleUI.scala">RPCと合わせると</a>、フロントエンド・バックエンドを同じScalaで統一できるため、学習曲線が低くなります。Scalaすら知らなかった同僚が、たった1日でRPCと通信するUIコードを書けるようになったり、社外でもAirframe RPCを試してくれる方が出てきたりもしました。</p><p><a href="https://blog.3qe.us/entry/2023/11/07/013338">ScalaのRPCライブラリAirframe RPCを使うとNext.js風に簡単にサーバ=クライアント通信できる - Lambdaカクテル</a></p><p>バックエンド、フロントエンドの双方を同時に作れるようになると、ちょっとしたデータからでもUIを作って情報を共有するなどが短期間で開発できるようになりました。以下はサービスの利用状況をAirframe RPCとRxで可視化した内部サービスのスクリーンショットです。今まで複雑な分析クエリを書ける一部の人でないと得られなかったデータを、社内の多くの人に手軽に届けられるようになりました。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*ysSelYFxy32NQnt0FCqgRA.png" /></figure><p>テストフレームワークである<a href="https://wvlet.org/airframe/docs/airspec">AirSpec</a>も、shouldContain, shouldMatchなど便利な構文が追加され、同僚のTakezoeさんがInteliJ用のプラグインも作成してくれました。VSCodeとMetalsの組み合わせではこのようなプラグインなしでもテスト実行ができます。</p><p><a href="https://takezoe.hatenablog.com/entry/2023/04/08/124618">AirSpecのテストケースをIntelliJ上で実行するプラグインを作った - たけぞう瀕死ブログ</a></p><p>Scala 3への対応も一通り終わりScalaの機能を拡張するライブラリとしての役割が落ち着いてきたので、2024年はAirframeとScala 3を最初から使ったアプリケーションの開発をいろいろ進めていこうと考えています。特にScala 2との互換性が必要ない新しいプロジェクトでは<a href="https://docs.scala-lang.org/scala3/reference/enums/enums.html">Enum</a>、<a href="https://docs.scala-lang.org/scala3/reference/other-new-features/indentation.html">Optional Braces</a>をはじめとするScala 3の簡潔なシンタックスを気兼ねなく使えるようになってきたので、また新たな楽しみとなっています。</p><h4>関連</h4><p><a href="https://medium.com/airframe/airframe-update-2022-85f7231280b8">Airframe Update 2022</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c8db21211f8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/airframe/scala%E3%82%92%E5%B0%91%E3%81%97%E3%81%A0%E3%81%91%E4%BD%BF%E3%81%84%E3%82%84%E3%81%99%E3%81%8F%E3%81%99%E3%82%8Bairframe-updates-2023-8c8db21211f8">Scalaを少しだけ使いやすくするAirframe: Updates 2023</a> was originally published in <a href="https://medium.com/airframe">Airframe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Airframe Update 2022]]></title>
            <link>https://medium.com/airframe/airframe-update-2022-85f7231280b8?source=rss----2320a6abf699---4</link>
            <guid isPermaLink="false">https://medium.com/p/85f7231280b8</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[airfrrame]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Taro L. Saito]]></dc:creator>
            <pubDate>Mon, 05 Dec 2022 22:52:43 GMT</pubDate>
            <atom:updated>2022-12-14T18:54:44.079Z</atom:updated>
            <content:encoded><![CDATA[<h3>Airframe Updates 2022</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nJbO3rrLkMnMn-rT" /><figcaption>Photo by <a href="https://unsplash.com/@billy_huy?utm_source=medium&amp;utm_medium=referral">Billy Huynh</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://github.com/wvlet/airframe/">Airframe</a>はScalaでの開発を支援するOSSライブラリ集です。カラフルなLogger、REST/RPCサーバー、HTTPクライアント、オブジェクトのSerialization、JSON処理、コマンドラインプログラムの作成などが一通り用意されており、Scalaでアプリケーションを作るまでの時間が短縮できます。</p><p><a href="https://wvlet.org/airframe/">Airframe · Essential Building Blocks For Scala</a></p><p>2021年11月に開催されたScala Con 2021では、Airframeを使うとScalaの知識のみでFrontend/Backendの開発ができることを紹介しました：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMliLBejnyy8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMliLBejnyy8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMliLBejnyy8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/14ba1de75579e38bb32012e1bad7384c/href">https://medium.com/media/14ba1de75579e38bb32012e1bad7384c/href</a></iframe><p>（本当は2020年に発表する予定でしたが、コロナの影響で2021年まで伸びてしまいました。無事開催できて良かったです）</p><h3>Scala 3 Support</h3><p>Scala 3への対応は<a href="https://github.com/wvlet/airframe/issues/1077">既に9割ほど完了しています</a>。<a href="https://blog.exoego.net/2022/12/scala-steward-2022.html">Scala Stewardのメンテナ</a>でもある<a href="https://github.com/exoego">Tatsuno (exoego)</a>さんがTreasure Dataに加入したタイミングで、Scala 3対応への様々なブロッカーを取り除いてくれました。そのおかげで多くのモジュールが既にScala 2.12/2.13/3 + Scala.jsのクロスビルドに対応しています。</p><p>最大の課題は、airframe-httpのバックエンドとして使っているFinagleのScala 3対応でしたが、開発元のTwitter社の大規模レイオフでFinagleのScala 3対応が絶望的になりました:</p><h3>Vladimir Kostюkov on Twitter: &quot;The entire finagle team resigned last week. There is zero people left at Twitter to actively maintain it. / Twitter&quot;</h3><p>The entire finagle team resigned last week. There is zero people left at Twitter to actively maintain it.</p><p>実際のところ、FinagleのScala 3対応には1年以上前から見切りをつけていて、Finagleの代替プロダクトを探していました。そこでFinagleやgRPCのバックエンドであるNettyを直接使って<a href="https://github.com/wvlet/airframe/tree/master/airframe-http-netty/src">airframe-http-netty</a>を実装できることがわかり、FinagleのScala 3対応を待たずにairfame-httpの移植が進みそうです。Netty版のAirframeは既にFinagle, gRPCと遜色ない性能でのRPC処理(40,000 RPC/sec. in M1 Macbook。最速のgRPC backendは50,000 RPC/sec.程度)が実現できています。</p><p>Scala 3への対応では、Scala 2と互換性のなくなった新しいマクロへの対応が課題でした。基本的には、マクロを使っているコードを親traitに押し込み、src/main/scala-2、src/main/scala-3とScala versionごとに違うソースフォルダに格納して、Scala 3への対応は無理をせず、ゆっくりと時間のあるときに進めていました。</p><p>以前、<a href="https://medium.com/@taroleo/3-tips-for-maintaining-your-scala-projects-e54a2feea9c4">Scalaプロジェクトをメンテする3つのコツ</a>、という記事で紹介したテクニックは、以下の通りです。</p><ul><li>Scalaのアップグレードを学習の機会としてとらえる</li><li>Mono repo（単一レポジトリ）にすることで管理・テストの手間を抑える</li><li>（細かいアップデートをしてくれる）Scala Ninjaを見つける</li></ul><p><a href="https://medium.com/@taroleo/3-tips-for-maintaining-your-scala-projects-e54a2feea9c4">3 Tips For Maintaining Your Scala Projects</a></p><p>今回、Scala 3のマクロやdottyコンパイラの中身にも触れる機会があり、新しいマクロ、inline機能の手軽さを学べました。また、Mono repoにしていたおかげでAirSpecがScala 3に対応しないと他のモジュールも対応できないなど依存関係が明確になり、Scala 3に向けて取捨選択すべき機能、互換性を壊すなどの判断も１つのレポジトリ内で行うことができました。最後のScala Ninjaに関しては、@exoegoさんと、彼が開発しているScala Stewardが強力でした。これまでに500以上のpull requestがmergeされています。おかげで常に最新版のライブラリ群に追従できているScala OSSになりました。最新リリースの情報が自動的にやってきて、さらに自分のプロダクトと合わせたテストまでしてくれます。情報の流れがこちら側に変わるので、毎日ニュースを読むような感覚でOSS界隈のアップデートについて知ることができるようになりました。</p><p>2年前ほどは、Scala 3に追従できずAirframeのコード資産を破棄しなくてはいけない可能性について怯えていましたが、もはやその心配はなくなっています。逆に、Sparkなど他の巨大プロジェクトがScala 3に追いつくのを楽しみに待てる状況です。</p><h3>Airframe HTTP</h3><p>HTTPクライアントのインターフェースを、より簡単に使えるように刷新しました。以下のように手軽に使い始めることができます。</p><pre>import wvlet.airframe.http.Http<br><br>val client = Http.newClient.newSyncClient(&quot;https://wvlet.org&quot;)<br>val req= client.request(Http.get(&quot;/&quot;))</pre><p>このHttpクライアントはairframe-json/codecによるserializationを内蔵していて、client.readAs[X](…) とすることで、JSONレスポンスをcase classなどのオブジェクト読み込むこともできます。</p><p>また、Httpクライアントのバックエンドに、Java11から正式に導入された<a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.net.http/java/net/http/HttpClient.html">Pure JavaのHttpクライアント</a>をデフォルトで使うようになりました。これで他のHTTPクライアントライブラリ（OkHttp, Jetty, Finagleなど）に依存せずにHTTPクライアントが使えます。Java8用にはURLConnnectionBackendが使えます。こちらは<a href="https://github.com/xerial/sbt-sonatype">sbt-sonatype</a>などまだJava8をサポートする必要があるプラグインで使われています。</p><p>airframe-httpのhttpクライアントには、HttpステータスコードやExceptionの種類に応じた<a href="https://github.com/wvlet/airframe/blob/master/airframe-http/src/main/scala/wvlet/airframe/http/HttpClientException.scala">複雑なリトライパターン</a>が実装されています。5xx status codeではリトライし、4xxではリトライしない（ただし、408 request timetout, 410 gone, 429 too many request, 499 client closedは例外）、SSL接続でのエラー時のリトライ処理が標準で実装されています。CircuitBreakerも導入されており、過剰なアクセスを抑えたり、Jitterを使ってリトライ間隔をバラつかせる対応もなされています。参考：<a href="https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/?nc1=h_ls">Timeouts, retries, and backoff with jitter </a>(AWS Builders’ Library):</p><p><a href="https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/?nc1=h_ls">Timeouts, retries and backoff with jitter</a></p><h3>Airframe RPCの標準化</h3><p><a href="https://github.com/wvlet/airframe/issues/2006">2022年の目標はAirframe RPCの規格の標準化</a>でした。エラー処理、RPCサーバー・クライアントのログ、バックエンドごとに別々だったRequest/Responseオブジェクトの共通化などです。</p><h4>Airframe RPCの仕組み</h4><p>Airframe RPCは、Scalaでメソッド定義を書くと、そのままScala/Scala.jsで使えるサーバー、クライアントのRPCインターフェースになるという、フレームワークです。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OYV6mb4_pSwK_gJOTz29Nw.png" /></figure><p>内部では、MessagePack（あるいはJSON)でデータを通信し、プログラマはローカルで関数呼びだしをしているのと同等の感覚で、リモートサーバーにあるコードを実行できます。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pEKNn6WR9JmfJh_3OEr-Ow.png" /></figure><h4>RPCStatus</h4><p>Airframe RPCを利用しやすくするため、まずRPCで使うエラーコードの標準化を進め、<a href="https://github.com/wvlet/airframe/blob/master/airframe-http/src/main/scala/wvlet/airframe/http/RPCStatus.scala">RPCStatus</a>を定義しました。HTTPのステータスコード(4xx, 5xx)やgRPCのステータスへの<a href="https://wvlet.org/airframe/docs/airframe-rpc#reporting-errors-with-rpcstatus">変換表も用意</a>しています。RPCStatusを起点としてエラーを報告することで、HTTPステータスコードの深い知識（例えばUnauthenticated errorは401 or 403? 僕は毎回Webで調べています）がなくても適切なHTTP/RPCステータスコードを返せるようになりました。基本的にはgRPCのエラーコードを元にしています。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*T0rZPOMsT15KwgTXr69vHg.png" /><figcaption>RPCで例外を投げる例</figcaption></figure><p>また、RPCStatusから作成されるRPCExceptionに対応するレスポンスにはエラーメッセージなどが自動的にJSON形式で含まれるようになっています。アプリケーション特有のエラーコード、メッセージ、スタックトレースなども標準化したフォーマットで入るので開発が非常に楽になります。<a href="https://wvlet.org/airframe/docs/airframe-rpc#sbt-airframe-plugin">sbt-airframe</a>で作成されたRPCクライアントを使うと、サーバーで発生したRPCExceptionを、クライアント側でRPCExceptionとしてそのまま受け取ることができます。例えば、try … catch { case e: RPCException =&gt; … } というコードで、サーバー・クライアント間でのエラーの受け渡しが確実に行えるようになりました。</p><p>まだいくつかScala 3への対応の課題が残っていますが、NettyバックエンドのHTTPサーバーができてきたことで、2023年にはScala 3に対応したHTTP/1, HTTP/2の双方に対応したRPCサービスが実現できそうです。</p><h3>Aiframe DI</h3><p>Airframe DIは、アプリケーションに必要な複雑な依存関係にあるクラスの構築を助けてくれるライブラリです。Scala 3の対応とともに、in-trait injectionを廃止し、constructor injectionのみをサポートするようにしました。</p><p><a href="https://wvlet.org/airframe/docs/airframe-di#constructor-injection">airframe-di: Dependency Injection · Airframe</a></p><p>In-trait injection (コード中にbind[X]と記述する）記法はコードにAirframe DIの依存関係が必要だったのですが、Treasure Data社内の利用例を調査しているうちにconstructor injectionのみでも問題ないことが見えてきました。またbind[X]記法をなくすことで、アプリケーションコードと、DIによるオブジェクト構築を完全に分離することができ、DIの使い方がよりシンプルになりました。</p><p>DIを使った開発中にエンジニアが考えることは、必要なサービスをコンストラクタの引数に型として並べるだけでよく、サービスの構築（オブジェクトの作成）はデザイン定義を見て、DIフレームワーク側が処理してくれます。</p><p>また、AutoCloseableのインターフェースを実装したクラスに関しては、DIのセッション終了後、自動的にclose()を呼ぶようになっています。DIでインジェクトされたクラスのリソースが自動的に解放されるので重宝しています。</p><p><a href="https://wvlet.org/airframe/docs/airspec#di-example">AirSpecテストフレームワークではAirframe DIがfirst-classでサポート</a>されており、テスト用に確保したリソースがテスト終了後に自動解放されます。before/after, setUp/tearDownなどを定義してリソース確保、解放のためのコードを書く手間がなくなっています：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*KowNVyDgG4zhAHLeCowCzg.png" /></figure><p>他に隠れた機能として、DIの<a href="https://wvlet.org/airframe/docs/airframe.html#tracing-di-with-google-chrome-browser">tracing機能</a>がサポートされています：</p><pre>val d = newDesign<br>  .withTracer(ChromeTracer.newTracer(&quot;target/trace.json&quot;))</pre><p>ここで出力されたJSONファイルをChromeに読ませるとDIの様子が可視化できます：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GVA2j5LlrrkaMUyD.png" /></figure><h3>Airframe Rx</h3><p>WebアプリケーションのUIを実装する際に、Reactive Streamの考え方が使えることはご存知でしょうか？</p><p><a href="https://www.reactive-streams.org/">Reactive Streams</a></p><p>Reactive Streamsのインターフェースは、Scala Collectionライブラリを日常的に使っている方には見慣れたもので、唯一の違いが、ユーザーのマウスクリックなどのイベントの受信を起点に、map, filterなどの一連のコレクション操作が実行される点です。サーバーからRPCのレスポンスを受け取ったタイミングで、任意のコードを実行して、DOMを書き換えることができるようになっています。</p><p><a href="https://wvlet.org/airframe/docs/airframe-rx">Airframe Rx</a>ではReactive Streamインターフェースを実装し、Scala.jsによるDOMレンダリングをサポートしています。以下にAirfram Rx, Scala.js, Airframe RPCで実装したアプリケーションの例を紹介します。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u3upY-uzckRBIHS1" /><figcaption>クエリの実行状況のモニタリングUI</figcaption></figure><p>VS Codeで使われているMonacoエディタを活用して、SQLエディタを作成：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tih0VcAdjLJ5u_Gv" /></figure><p>Airframe Rxの技術的な特徴は、Streamイベントの受信を適切にcancelできる点です。Webページではページの書き換えなどが頻繁に行われますが、ページが書き換えられたタイミングで、書き換え前のRxストリームのsubscriptionを自動的にキャンセルし、ブラウザのメモリを食い潰さないように管理できますし、安全です。また、イベントに応じて必要なDOM部分のみを書き換えるので、React.jsのような全DOMをメモリで構築してから差分を計算して描画するVirtual DOM方式よりも、高速化するのが簡単です。</p><p>Rxのインターフェースは、ウェブUIだけではなく、Streaming RPCの実装、HTTPクライアントのインターフェースとしても有用なことが見えてきました。2023年にはScalaのFuture（Execution Contextがアプリケーションロジックに紛れ込んで使い勝手が悪い）から脱却し、Rxベースのインターフェースを標準として採用していこうと考えています。</p><h3>Airframe SQL</h3><p>Airframeには実は、TPC-H/TPC-DSのSQLクエリを完全にparseできるSQL lexer/parser/analyzerが実装されています。このモジュールがどう使われるかは今後紹介する機会があると思われますが、1つの応用例として、カラムナのParquetファイルを手軽に読み書きするairframe-parquetモジュールで使われています。Parquetファイルに対して簡単なSQLを実行することもできます。</p><p><a href="https://wvlet.org/airframe/docs/airframe-parquet">airframe-parquet: Parquet Columnar File Reader and Writer · Airframe</a></p><h3>Airframe ULID</h3><p>ランダムなIDにタイムスタンプをつけることで時系列順にソートできるUUID v6などの話題が盛り上がっていますが、Airframe ULIDを使うと同等の機能が既に利用できます。詳細はこちらをどうぞ：</p><p><a href="https://medium.com/airframe/airframe-ulid-lexicographically-sortable-identifiers-for-scala-and-scala-js-c6530c10873e">Airframe ULID: Lexicographically Sortable Identifiers for Scala and Scala.js</a></p><h3>2023年に向けて</h3><p>2021- 2022年だけでもここでは紹介しきれないくらい多くの更新がなされています。詳細は<a href="https://wvlet.org/airframe/docs/release-notes">release note</a>にありますが、今後のアップデートはGitHubのリリースページで紹介していきます。</p><p><a href="https://github.com/wvlet/airframe/releases">Releases · wvlet/airframe</a></p><p>2023年には、</p><ul><li>Scala 3対応の完了</li><li>Airframeを使ったアプリケーション開発手法を通して学べるドキュメント</li></ul><p>を中心に開発を進めていく予定です。また、airframe-rxやairframe-sql周りから派生して面白いプロダクトもできるのではないかと思っています。</p><p>それではみなさま、良いお年を。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85f7231280b8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/airframe/airframe-update-2022-85f7231280b8">Airframe Update 2022</a> was originally published in <a href="https://medium.com/airframe">Airframe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Airframe ULID: Lexicographically Sortable Identifiers for Scala and Scala.js]]></title>
            <link>https://medium.com/airframe/airframe-ulid-lexicographically-sortable-identifiers-for-scala-and-scala-js-c6530c10873e?source=rss----2320a6abf699---4</link>
            <guid isPermaLink="false">https://medium.com/p/c6530c10873e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[uuid]]></category>
            <category><![CDATA[airframe]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Taro L. Saito]]></dc:creator>
            <pubDate>Mon, 19 Apr 2021 18:36:07 GMT</pubDate>
            <atom:updated>2021-04-20T16:18:49.921Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*_bKkrkyb4FRf1smL.png" /></figure><h3>What is ULID?</h3><p><a href="https://github.com/ulid/spec">ULID (Universally Unique Lexicographically Sortable Identifier)</a> is a case-insensitive 26-character string consisting of 48-bit timestamp (10 characters) and 80-bit randomness (16 characters):</p><pre> 01AN4Z07BY      79KA1307SR9X4MV3</pre><pre>|----------|    |----------------|<br> Timestamp          Randomness<br>   48bits             80bits</pre><p>We can use ULID as identifiers for labeling records while maintaining their time-series order with millisecond resolution. You can use ULID for providing chronologically sortable IDs in distributed systems. ULID doesn’t guarantee the ordering if ULIDs are generated within the same millisecond from multiple machines, but if you have a single coordinator, it’s possible to generate monotonically increasing ULIDs, which will be explained later.</p><p><a href="https://github.com/ulid/spec#universally-unique-lexicographically-sortable-identifier">ULID was born to overcome several shortcomings of UUID (v1-v4)</a>, whose string representation requires a bit long 32 characters for representing the same 128-bit values (e.g., 2a74dd3d-1abd-45a4-a147-a288a612fcd), and using UUID as identifiers just provides random distribution of records without any context like UNIX timestamp.</p><p>ULID provides both of the context (UNIX time) and randomness to IDs with URL-safe characters encoded with <a href="https://www.crockford.com/base32.html">Crockford’s Base32</a>, which excludes letters like I, L, O, and U to avoid confusion for human eyes. With ULIDs, you can perform time-range queries over records by using regular string range queries. And also, generating ULIDs can be faster than generating UUIDs and many <a href="https://github.com/ulid/spec#implementations-in-other-languages">implementations are already available for the most of the programming languages</a>.</p><p>So, why not using ULIDs?</p><h3>Airframe ULID: The Fastest ULID Generators for Scala</h3><p>We have released<a href="https://wvlet.org/airframe/docs/airframe-ulid"> Airframe ULID (airframe-ulid)</a> as a standalone library (i.e., no dependency other than Scala) for generating and parsing ULIDs. Airframe ULID is available since Airframe version 21.4.0:</p><p><a href="https://wvlet.org/airframe/docs/airframe-ulid">airframe-ulid: ULID Generator · Airframe</a></p><p>airframe-ulid can be used both for Scala and Scala.js. Scala.js support is useful when developing web applications. We often use ULIDs for assigning IDs to case class objects, e.g., case class Record(id: ULID, param:String, …), and pass these objects between server and clients (browser) with <a href="https://wvlet.org/airframe/docs/airframe-rpc">Airframe RPC</a>.</p><h3>Usage</h3><p><strong>build.sbt</strong></p><pre>libraryDependencies += &quot;org.wvlet.airframe&quot; %% &quot;airframe-ulid&quot; % &quot;21.4.0&quot;</pre><pre>// For Scala.js<br>libraryDependencies += &quot;org.wvlet.airframe&quot; %%% &quot;airframe-ulid&quot; % &quot;21.4.0&quot;</pre><p>(Note: check <a href="https://wvlet.org/airframe/docs/airframe-ulid">the latest version at the website</a>)</p><p>ULID can be generated with ULID.newULID method:</p><pre><strong>import</strong> wvlet.airframe.ulid.ULID</pre><pre>// Generate a new ULID<br><strong>val</strong> ulid: ULID = ULID.newULID</pre><pre>// ULID.toString produces the String representation of ULID<br>println(ulid)             // 01F3J0G1M4WQRBHGZ6HCF6JA0K<br>println(ulid.epochMillis) // 1618733434500</pre><pre>// Parse the string representation of ULIDs <br><strong>val</strong> ulid2 = ULID.fromString(&quot;01F3J0G1MD4QX7Z5QB148QNH4R&quot;)<br>ulid2.epochMillis // 1618733434509</pre><h4>Monotonically Increasing ULIDs</h4><p>ULID.newULID will produce <a href="https://github.com/ulid/spec#monotonicity">monotonically increasing ULIDs</a> in a thread-safe manner. If ULIDs are generated within the same millisecond, airframe-ulid will increment the random part of ULID by 1 to enforce the ordering:</p><pre>01F3HZ9V4BHVHJMMETE0MFBQKH<br>01F3HZ9V4BHVHJMMETE0MFBQKJ // &lt;- random part was incremented by 1<br>01F3HZ9V4BHVHJMMETE0MFBQKK // &lt;- random part was incremented by 1<br>01F3HZ9V4BHVHJMMETE0MFBQKM // &lt;- random part was incremented by 1<br>01F3HZ9V4BHVHJMMETE0MFBQKN // &lt;- random part was incremented by 1<br>01F3HZ9V4C8SWD21A4SCM4NMD8 // &lt;- millisecond is changed<br>...</pre><p>Empirically speaking, generating monotonically increasing ULIDs will reduce the probability of having ULID conflicts compared to using completely random ULIDs, according to <a href="https://medium.com/zendesk-engineering/how-probable-are-collisions-with-ulids-monotonic-option-d604d3ed2de">this report</a>. This report also showed that the chance of a ULID collision over the next 100 years is merely 0.000126%. So, in terms of risk management, we don’t need to worry too much about ULID conflicts.</p><p>If you use multiple machines, there is no guarantee that generated ULIDs will be monotonically increasing values. If you need a strict ordering, we recommend having a single coordinator to generate ULIDs. In airframe-ulid, if the 80-bit space for the randomness is exhausted (it’s quite rare!, though), it will add an artificial delay of 1 millisecond to use the next millisecond value of ULID.</p><h4>Serialization</h4><p>ULID can be serialized and deserialized with <a href="https://wvlet.org/airframe/docs/airframe-codec">airframe-codec</a>:</p><pre><strong>case</strong> <strong>class</strong> <strong>Transaction</strong>(id:ULID, status:String)</pre><pre><strong>val</strong> codec = MessageCodec.of[Transaction]</pre><pre><strong>val</strong> json = codec.toJson(Transaction(id = ULID.newULID, status = &quot;committed&quot;)) <br>// {&quot;id&quot;:&quot;01F3HZ9V454BC466FPDSBTZ64G&quot;, &quot;status&quot;:&quot;committed&quot;}</pre><pre><strong>val</strong> txx = codec.fromJson(json)<br>// Transaction(01F3HZ9V454BC466FPDSBTZ64G,committed) </pre><p><a href="https://wvlet.org/airframe/docs/airframe-rpc">Airframe RPC</a> internally uses this capability of airframe-codec to pass ULIDs data between servers and clients in JSON or MessagePack format.</p><h3>Performance</h3><p>airframe-ulid can produce 5 million ULIDs / sec. on my MacBook Pro (2018 model). As of April 2021, airframe-ulid is the fastest ULID generator in Scala:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*zV3oc2pJJ2m7RbwZ6W9UBQ.png" /></figure><p>Comparison targets:</p><ul><li><a href="https://github.com/chatwork/scala-ulid">scala-ulid (by Chatwork)</a>, which is faster than <a href="https://github.com/huxi/sulky">huxi/sulky-ulid</a></li><li>Java’s UUID.randomUUID()</li></ul><p>Here is the <a href="https://github.com/wvlet/airframe/blob/master/airframe-benchmark/src/main/scala/wvlet/airframe/benchmark/ulid/ULIDBenchmark.scala">benchmark code</a> using JMH.</p><p>If we use Apple Silicon (M1), the performance difference is much more impressive. Airframe ULID can produce 10 million ULIDs / sec., which is 3.4x faster than generating UUIDs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*NL8IT1z4b7R918dKiNsU5A.png" /></figure><p>Here are several keys we found for optimizing the performance of the ULID generator:</p><ul><li>Reducing the number of random value generation is the major performance factor. SecureRandom of Java is quite slow. For generating 80-bit random values, using SecureRandom.nextBytes(Array[Byte](10)) was found to be faster than calling SecureRandom.nextInt 3 times, which produces 32 x 3 = 96 bit values and wastes 16 bits. If we use the default non-secure Random (e.g., java.util.Random), however, there is no such performance difference between Random.nextBytes(Array[Byte]) or calling Random.nextInt 3 times.</li><li>Generating monotonically increasing ULIDs by remembering the previously generated ULID also worked well for reducing the random value generation. We just need to increment the randomness part of ULID by 1 within the same millisecond.</li><li>Using bit-shift operators as much as possible for encoding/decoding Crockford’s Base32 strings is important. It seems Apple Silicon’s cache, which is embedded in the same chip, has significant advantage for such operations. Both of airframe-ulid and Chartwork’s scala-ulid use the same SecureRandom algorithm, so the only difference should be Base32 encoding part. You can find such techniques in Hacker’s Delight:</li></ul><p><a href="https://www.amazon.com/Hackers-Delight-Henry-S-Warren-ebook-dp-B009GMUMTM/dp/B009GMUMTM/">Hacker&#39;s Delight</a></p><p>Based on these observations, in Airframe ULID, we decided to use SecureRandom.getInstanceStrong() as a random value generator by default, which often uses NativePRNGNonBlocking as a primary choice. We know it’s slow, but this slowness can be compensated by the fast increment operation.</p><p>ULID.nextULID of Airframe ULID will provide monotonically increasing ULIDs with the best available randomness characteristic in the current JVM. Users don’t need to care about such internals and the choice of random generators. The default behavior will provide the safest and fastest results.</p><p>Special thanks to <a href="https://medium.com/u/25b32cc5eaf4">Junichi Kato</a> for finding <a href="https://creators-note.chatwork.com/entry/2020/11/26/000100">the performance issue of an early version of airframe-ulid</a> (A blog post written in Japanese).</p><p>Link: GitHub <a href="https://github.com/wvlet/airframe/tree/master/airframe-ulid">source code of airframe-ulid</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6530c10873e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/airframe/airframe-ulid-lexicographically-sortable-identifiers-for-scala-and-scala-js-c6530c10873e">Airframe ULID: Lexicographically Sortable Identifiers for Scala and Scala.js</a> was originally published in <a href="https://medium.com/airframe">Airframe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[airframe-log for Scala 3 (Dotty)]]></title>
            <link>https://medium.com/airframe/airframe-log-for-scala-3-dotty-d5797b44a33?source=rss----2320a6abf699---4</link>
            <guid isPermaLink="false">https://medium.com/p/d5797b44a33</guid>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[airframe]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[dotty]]></category>
            <dc:creator><![CDATA[Taro L. Saito]]></dc:creator>
            <pubDate>Fri, 11 Dec 2020 00:28:51 GMT</pubDate>
            <atom:updated>2020-12-11T11:02:59.325Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oFwRWzS_NnM_UYFR" /><figcaption>Photo by <a href="https://unsplash.com/@aaronburden?utm_source=medium&amp;utm_medium=referral">Aaron Burden</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Airframe Log, a modern logging library for Scala, now supports Scala 3.0.0-M2 (Dotty) since version 20.12.1, released on December 2020.</p><p><a href="https://wvlet.org/airframe/docs/airframe-log">airframe-log: Application Logger · Airframe</a></p><p>The usage is quite simple: Add LogSupport trait to your class and use error/warn/info/debug/trace methods for showing logs of your applications:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97341d9ae5596a85c8bfa9980b8e2bcd/href">https://medium.com/media/97341d9ae5596a85c8bfa9980b8e2bcd/href</a></iframe><p>Now your application can show colorful logs, enriched with the source code location:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/0*dHa__u6j4p5ObSxy.png" /></figure><p>airframe-log uses Scala macros to reduce the overhead of generating log messages if the corresponding log level is not enabled. The biggest challenge in supporting Scala 3 was adopting the brand-new Scala Macro for Scala 3 while maintaining compatibilities with Scala 2.13 and Scala 2.12. To do so, we split the source code for Scala 2 and 3. The transition from Scala 2 to 3 may take several years until various libraries that are using Scala 2 macros or runtime-reflections will be fully migrated to Scala 3. Now, airframe-log has joined the list of libraries supporting Scala 3!</p><p><a href="https://scalacenter.github.io/scala-3-migration-guide/docs/macros/macro-libraries.html">Scala Macro Libraries · Scala 3 Migration guide</a></p><p>We still have many modules that need to be migrated to Scala 3, but now that tooling like sbt 1.4.x, vscode, and IntelliJ gradually have started supporting Scala 3 builds, it would be good timing to try and learn new exciting features of Scala 3!</p><p><a href="https://medium.com/airframe/airframe-log-a-modern-logging-library-for-scala-56fbc2f950bc">Airframe Log: A Modern Logging Library for Scala</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5797b44a33" width="1" height="1" alt=""><hr><p><a href="https://medium.com/airframe/airframe-log-for-scala-3-dotty-d5797b44a33">airframe-log for Scala 3 (Dotty)</a> was originally published in <a href="https://medium.com/airframe">Airframe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Airframe RPC: A Framework for Using Scala Both for Frontend and Backend Programming]]></title>
            <link>https://medium.com/airframe/airframe-rpc-a-framework-for-using-scala-both-for-frontend-and-backend-programming-79c4b4f38d04?source=rss----2320a6abf699---4</link>
            <guid isPermaLink="false">https://medium.com/p/79c4b4f38d04</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[web-framework]]></category>
            <dc:creator><![CDATA[Taro L. Saito]]></dc:creator>
            <pubDate>Thu, 02 Jul 2020 10:07:49 GMT</pubDate>
            <atom:updated>2020-07-02T17:03:13.105Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uZrHXWGNVAa4odpBX119jA.png" /></figure><p><a href="https://wvlet.org/airframe/docs/airframe-rpc">Airframe RPC</a> is an open-source framework for building RPC services, using Scala as a unified RPC interface between servers and clients.</p><h3>Why Airframe RPC?</h3><p>Airframe RPC enables calling Scala methods at remote servers. You don’t need to worry about how to encode your data into JSON, nor how to define HTTP REST endpoints. Airframe RPC abstracts away these details; the framework generates code for serializing your data objects into JSON or MessagePack and calls appropriate HTTP endpoints on your behalf.</p><p>While <a href="https://grpc.io/">gRPC</a> has been a popular approach for building RPC services, it’s built around <a href="https://developers.google.com/protocol-buffers/docs/overview">Protobuf</a> technology for defining data structures and RPC methods. This means, you and your collaborators need to use Protobuf ecosystem almost for everything to enjoy the benefits of gRPC. And also, gRPC heavily uses HTTP/2 features, some of them are not supported in web browsers, so if you need to write web applications using gRPC, an additional proxy like <a href="https://grpc.io/docs/languages/web/basics/">gRPC-Web</a> is required.</p><p>In 2020, <a href="https://www.scala-js.org/news/2020/02/25/announcing-scalajs-1.0.0/">Scala.js, which can compile Scala code into JavaScript, finally became 1.0.0 after 7 years of development</a>. This has paved a way for using Scala both for server (Scala JVM) and client (Scala.js) programming. We explored an approach for using Scala’s functional interfaces as RPC endpoint definitions, and successfully created Airframe RPC on top of <a href="https://wvlet.org/airframe/docs/">technology stack of 20+ Airframe modules</a>.</p><p><a href="https://github.com/wvlet/airframe">wvlet/airframe</a></p><p>Although Airframe RPC is a relatively new project started on January 2020 inside <a href="https://www.treasuredata.com/">Arm Treasure Data</a>, this project has proved various advantages. For example:</p><ul><li><strong>Free from REST</strong>. We can just use Scala’s functional interface for defining servers. <a href="https://cloud.google.com/apis/design">Google’s REST API Design Guide</a> has been useful resources for defining clear REST API endpoints, but we’ve found using programming language’s native interface is much easier.</li><li><strong>No more web-framework wars</strong>. In Scala, there are many web frameworks, such as <a href="https://github.com/twitter/finatra">Finatra</a>, <a href="https://github.com/finagle/finch">Finch</a>, <a href="https://doc.akka.io/docs/akka-http/current/index.html">Akka HTTP</a>, and our own <a href="https://wvlet.org/airframe/docs/airframe-http">airframe-http</a>, etc. Each of them has its own pros and cons, and choosing one of them has been a hard choice for us. Now, we can just start from Airframe RPC using plain Scala interfaces. If necessary, we can use airframe-http for adding custom HTTP endpoints.</li><li><strong>Seamless integration with Scala.js</strong>. Writing web browser applications in JavaScript that interact with servers is not easy. You may need to learn about existing frameworks like <a href="https://https//reactjs.org/">React.js</a>, <a href="https://vuejs.org/">Vue.js</a>, etc., and a lot of techniques for using them. By using Scala both for server and client code, an engineer just joined the company could write an RPC application using Scala and Scala.js in a few days.</li></ul><h3>Airframe RPC: Overview</h3><p>For using Airframe RPC, first, define your RPC service interface using regular Scala functions by adding @RPC annotation. All public methods in this class will be your RPC endpoints. For the method arguments and return types, you can use arbitrary types (See <a href="https://wvlet.org/airframe/docs/airframe-rpc#object-serialization">Object Serialization</a> for the list of available types). To pass complex messages, you can use case classes as well.</p><p>Here is an example RPC interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*yZtnKJsb0R1IZ85iUWCSbg.png" /></figure><p>Next, implement this service interface in Scala:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*ypb-e2KFRKiHhfx80iZ5Qg.png" /></figure><p>To start an RPC web server, Airframe RPC provides Finagle-based web server implementation. The following code starts an RPC web server at <a href="http://localhost:8080/">http://localhost:8080/</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*-W_bpfOiXeatSu72t2aIOA.png" /></figure><p>To access the RPC server, we need to generate an RPC client from the RPC interface definition. We can use an RPC client hello.api.v1.ServiceSyncClient generated by <a href="https://wvlet.org/airframe/docs/airframe-rpc#sbt-airframe-plugin">sbt-airframe</a>, which reads an RPC interface code and generates HTTP client code for calling RPC methods.</p><p>Now, you are ready to call remote Scala methods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*w6A87afw3peQC59owxoMRA.png" /></figure><p>That’s it! Now you can call remote Scala methods as if they were regular Scala functions. Airframe RPC also supports asynchronous clients using Future.</p><p>See also the <a href="https://wvlet.org/airframe/docs/airframe-rpc">documentation</a> for more details:</p><p><a href="https://wvlet.org/airframe/docs/airframe-rpc">Airframe RPC · Airframe</a></p><h3>What Makes Airframe RPC Unique?</h3><p>The primary goal of Airframe RPC is using plain Scala functions for RPC as much as possible. In the above examples, only @RPC annotation is the special syntax in Airframe RPC. Other than that, everything can be written in plain Scala without any weird syntax nor DSL. That means if you know how to write Scala, it will be straightforward to build RPC services with Airframe RPC.</p><p>There are existing RPC frameworks for Scala, such as <a href="https://github.com/cornerman/sloth">Sloth</a> (pure-Scala approach) or gRPC wrappers like <a href="https://higherkindness.io/mu-scala/">muScala</a>, <a href="https://scalapb.github.io/">ScalaPB</a>, etc., but none of them provides the same level of simplicity with Airframe RPC because they are trying to create DSLs over Scala’s type system or building bridges for gRPC.</p><p>To support natural RPC interface definitions, Airframe RPC uses various techniques behind the scene, notably, <a href="https://wvlet.org/airframe/docs/airframe-surface">runtime/compile-time object-shape inspection with airframe-surface</a>, <a href="https://wvlet.org/airframe/docs/airframe-codec">schema-on-read codec of airframe-codec</a> to support arbitrary data serialization, dynamic class loading in sbt-airframe plugins, etc. Providing a simple RPC interface for users actually needed significant amount of work. “Think Simple”, a slogan of Apple, doesn’t mean we can create a simple interface at ease.</p><p>Here, I’d like to thank my colleagues for helping Airframe RPC development. They used this RPC framework even before any documentation existed and helped me for fixing weird bugs and improving the usability until we became comfortable to use it in production.</p><h3>Future Work</h3><p>Here are a couple of items we are planning for Airframe RPC:</p><ul><li>Generating Open API specification from RPC interfaces. This will be useful for generating and implementing RPC clients for other than Scala.</li><li>Documentation of airframe-http-rx library. Along with Airframe RPC, we also have built a reactive DOM rendering library (<a href="https://github.com/wvlet/airframe/tree/master/airframe-http-rx">airframe-http-rx</a>) for Scala.js. This resolves several shortcomings of existing ScalaTags and monadic-html and interacts nicely with Airframe RPC servers.</li><li>Leveraging HTTP/2. The first milestone of Airframe RPC is completed as we can call remote Scala functions from Scala and Scala.js. We need to think about how to leverage HTTP/2’s advanced features for supporting bi-directional streaming like gRPC.</li></ul><h3>Related Article</h3><p>Airframe RPC is built on top of Airframe HTTP:</p><p><a href="https://medium.com/airframe/airframe-http-a-minimalist-approach-for-building-web-services-in-scala-743ba41af7f">Airframe HTTP: Building Low-Friction Web Services Over Finagle</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79c4b4f38d04" width="1" height="1" alt=""><hr><p><a href="https://medium.com/airframe/airframe-rpc-a-framework-for-using-scala-both-for-frontend-and-backend-programming-79c4b4f38d04">Airframe RPC: A Framework for Using Scala Both for Frontend and Backend Programming</a> was originally published in <a href="https://medium.com/airframe">Airframe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Airframe Meetup #3]]></title>
            <link>https://medium.com/airframe/airframe-meetup-3-1078a0a0c069?source=rss----2320a6abf699---4</link>
            <guid isPermaLink="false">https://medium.com/p/1078a0a0c069</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[airframe]]></category>
            <category><![CDATA[scalajs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Taro L. Saito]]></dc:creator>
            <pubDate>Mon, 02 Dec 2019 20:21:18 GMT</pubDate>
            <atom:updated>2019-12-03T00:56:10.982Z</atom:updated>
            <content:encoded><![CDATA[<p>2019年に追加されたAirframeの新機能とユースケースについて紹介</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dD0_Y3LmWzoT-kI1WrYOEw.png" /></figure><p>AirframeはScalaで高度なアプリケーションを手軽に作成するためのライブラリ集です。</p><p><a href="https://wvlet.org/airframe/">Airframe · Essential Building Blocks For Scala</a></p><p>AirframeユーザーのためのAirframe Meetup #3を2019年10月23日に東京で開催しました。当日は季節の変わり目ということもあり、風邪によるキャンセルが多かったのですが（お大事に）、今回は新しい試みとして、AirframeをSpark、Scala.jsなどと一緒に使っていただいている方々によるlightning talkを設けたことで、新しい発見も多く、実りのあるイベントになりました。</p><p><a href="https://airframe.connpass.com/event/148169/">Airframe Meetup #3 (2019/10/23 19:00〜)</a></p><p>嬉しいことに、参加してくれた方によるレポートもあります。</p><p><a href="https://blog.magnolia.tech/entry/2019/10/24/084445">Airframe Meetup #3へ参加しました - Magnolia Tech</a></p><p>まずは、2019年におけるAirframeのアップデートについて紹介です。Airframeプロジェクトの一環として作成されたScalaの新しいテストフレームワークであるAirSpec、今年リリースされたGitHub ActionsをどうAirframeのCI・リリースに使っているか、Scalaによるマイクロサービスを定義するのに便利なAirframe HTTPの新機能について紹介しました。</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.slideshare.net%2Fslideshow%2Fembed_code%2Fkey%2FzzH7awpYKPSLjx&amp;url=https%3A%2F%2Fwww.slideshare.net%2Ftaroleo%2Fairframe-meetup-3-2019-updates-airspec&amp;image=https%3A%2F%2Fcdn.slidesharecdn.com%2Fss_thumbnails%2F2019-10-23airframemeetup3-191202173724-thumbnail-4.jpg%3Fcb%3D1575308325&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=slideshare" width="600" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/f503404472d76a927202d1457aadac18/href">https://medium.com/media/f503404472d76a927202d1457aadac18/href</a></iframe><p>AirSpecは、シンプルさを追求したテストフレームワークで、以下のようにAirSpec traitを実装し、public methodをテストケースとして実行する、という２つのルールを覚えるだけで使い始められます。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*qJfyR15H23bZXYX1" /></figure><p><a href="https://wvlet.org/airframe/docs/airspec.html">Airframe: airspec</a></p><p>AirSpecは、AirframeのDIと組み合わせることでさらに高度なテストケースの記述ができるようになります。</p><p>まず、Airframe DIでは、Designの中にサービスの起動、終了処理が記述できるlifecycle designの機能が追加されました。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/0*fQ0r3mppAHbPMk_W" /></figure><p>これによりdesignでライフサイクル管理までを含めた再利用可能なコンポーネントを定義できるようになり、このようなdesignを組み合わせて、複雑なサービスを手軽に構築していけるようになっています。</p><p>この機能をAirSpecと組み合わせることで、テスト時に必要なサービスの初期化、終了処理を確実に行うことができるようなります。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*X4lzg36j-EGky_HSjfLOnw.png" /></figure><p>この機能追加により、Scalaにおけるプログラミング関心が、いかに再利用可能でテストしやすいdesignを定義するかに変わっていきました。lifecycle designを利用することで、サービス実装側のコードもbind[X]の構文だけを使ってモジュールをinjectしていく簡単なスタイルに統一できます。</p><p>AirframeやAirSpecのリリースはGitHub Actionsで自動化されています。GitHub Actionsは同時に実行できるタスク数が多いことが魅力で、workflow -&gt; job -&gt; stepの階層を把握し、他の人が書いたワークフローを再利用できるのが魅力です。これによりGitHubだけでCIが完結するようになりました。</p><p><a href="https://github.com/features/actions">GitHub Actions · CI/CD and automations · Agentic Workflows · Workflows</a></p><p>AirframeもTravis CIからGitHub Actionsに切り替えることで快適になりました。以下はAirframeでのworkflow定義例です:</p><p><a href="https://github.com/wvlet/airframe/tree/master/.github/workflows">wvlet/airframe</a></p><p>またsbt-sonatypeを更新し、数千以上のファイルでも1分以内でSonatypeにアップロード(bundle upload)できるようにしました。詳細は以下のブログで紹介しましたが、この変更により多くのScalaプロジェクトのリリースがこれで短時間で行えるようになっています。</p><p><a href="https://medium.com/@taroleo/sbt-sonatype-f02bdafd78f1">sbt-sonatype: Blazingly Fast Release to Sonatype</a></p><p>Airframeユーザーによるlightning talkもありました。</p><p>島田さんによる「Spark with Airframe」では、Airframeの各モジュールをSparkの運用で上手に活用する手法が紹介されました。</p><p>・時系列データの扱いを確実に行うために、airframe-metricsのTimeWindowを利用して区間指定のバグを減らす<br>・Sparkクラスタ間の通信のために、airframe-codecでオブジェクトをMessagePack形式にserializeし送受信する<br>・AWS FargateのAPIをSparkの複数ノードから利用してもFargate側がscale outをするまで待てるように、airframe-controlのRetryを利用</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fspeakerdeck.com%2Fplayer%2F5dc0fe4395014e70b8e49cc2a115053c&amp;url=https%3A%2F%2Fspeakerdeck.com%2Fsmdmts%2Fspark-with-airframe&amp;image=https%3A%2F%2Fspeakerd.s3.amazonaws.com%2Fpresentations%2F5dc0fe4395014e70b8e49cc2a115053c%2Fslide_0.jpg%3F566806&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=speakerdeck" width="710" height="532" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae8385430a2311bf56c2098edd4219c7/href">https://medium.com/media/ae8385430a2311bf56c2098edd4219c7/href</a></iframe><p>airframe-controlには、リトライの待ち時間をランダム化することで、分散ノードからあるサービスに対するリクエストのリトライ間隔が上手にばらつくというjitteringの機能があるのですが、Scala界隈でこの実装を探しても見つからなかったとのこと。exponential backoffでは複数ノードから同一サービスを使うとリトライ間隔に周期性ができてしまうので、exponential backoff + randomizationによるjitteringが有効です。</p><p><a href="https://wvlet.org/airframe/docs/airframe-control.html">Airframe: airframe-control</a></p><p>吉田さんは、GCPの<a href="https://github.com/GoogleCloudPlatform/functions-framework-nodejs">Functions Framework</a>とAirframeのScala.js対応モジュールを使ってサーバーサイドアプリケーションをサーバーレスで構築するためのデモをしてくれました。</p><p>・airframe-logでログメッセージを管理<br>・airframe-diでモジュールの管理（<a href="https://github.com/grimrose/cloud-build-slack-notifications/blob/master/functions/infrastructure/src/main/scala/ninja/grimrose/sandbox/infra/InfrastructureModule.scala">ソースコード</a>）。モジュール定義をまとめることで、アプリケーション側のコードがbind[X]を利用するだけ、と非常に簡潔になっています。<br>・AirSpecでScala.jsのテストコードを記述。Futureを返すasyncテストがフレームワーク側でサポートされるとさらに使いやすくなるとのこと。</p><p><a href="https://paper.dropbox.com/doc/2cFRwrXuX0HeK7sE5Kowy">Scala.js and Airframe on Functions Framework</a></p><p>AirframeはScala.jsでも利用できるモジュールが増えてきました。11月にairframe-codecもScala.js対応し、サーバーサイドアプリケーション(Scala + Airframe HTTP)と、クライアント（Scala.js)のオブジェクト通信がMessagePackを通して行えるようになり、gRPCに近いデータ通信の世界観がScalaのインターフェースで実現できるようになってきています。</p><p><a href="https://wvlet.org/airframe/docs/release-notes.html#19110">Airframe: Release Notes</a></p><p>最後に、竹添さんによるDependency Injectionの歴史、各フレームワークの利害得失のまとめです。Google Guice (JavaベースでScalaと親和性が悪い), implicit parameter、reader monad、MacWire (スコープに全部依存関係を含める必要があるが、コンパイラによるチェックが効く）、Cake Pattern (ボイラープレートが多い、NullPointerExceptionを防ぐのが難しいなどで最近は使われなくなってきたはず）、Airframe DI (コンパイル時チェックはないが、ライフサイクル管理ができて高機能）など、各々の特徴が上手に整理されています。</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.slideshare.net%2Fslideshow%2Fembed_code%2Fkey%2Fdouo1E4lRUkYHL&amp;url=https%3A%2F%2Fwww.slideshare.net%2Ftakezoe%2Frevisit-dependency-injection-in-scala&amp;image=https%3A%2F%2Fcdn.slidesharecdn.com%2Fss_thumbnails%2Frevisitdependencyinjectioninscala-191028011004-thumbnail-4.jpg%3Fcb%3D1572225146&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=slideshare" width="600" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/453a01de400d99a25fdd273bc9cc751d/href">https://medium.com/media/453a01de400d99a25fdd273bc9cc751d/href</a></iframe><p>Airframeは2019年度のロードマップを作成したことにより、目に見える形で順調に機能追加が進むようになりました。</p><p><a href="https://github.com/wvlet/airframe/issues/528">Milestone: Airframe 19 · Issue #528 · wvlet/airframe</a></p><p>今年の<a href="https://2019.scalamatsuri.org/">Scala Matsuri 2019</a>でもAirframeの開発について紹介したのですが、プロダクション開発の経験から共通部分として使えるコードを見出し、OSSとして抽出していく戦略をとっています。新しいScalaエンジニアがチームに戦力として加わったことで、社内のコードも、AirSpecによるテストケースや、Airframe HTTPを使ったマイクロサービスに置きかわるなど、リファクタリングがどんどん進んでいます。</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.slideshare.net%2Fslideshow%2Fembed_code%2Fkey%2Fic886MfbHpmGD7&amp;url=https%3A%2F%2Fwww.slideshare.net%2Ftaroleo%2Fhow-to-use-scala-at-work-airframe-in-action-at-arm-treasure-data&amp;image=https%3A%2F%2Fcdn.slidesharecdn.com%2Fss_thumbnails%2F2019-06-29-howtousescalaatwork-scalamatsuri2019-190629030452-thumbnail-4.jpg%3Fcb%3D1561777670&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=slideshare" width="600" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/1381ffdb1174de7cc14e3786780b271c/href">https://medium.com/media/1381ffdb1174de7cc14e3786780b271c/href</a></iframe><p>これからAirframe 20.x.x (2020年) のロードマップを作成する予定ですが、</p><p>・Airframe HTTPとScala.jsの融合 (Scala RPC)<br>・Scala.js 1.0.0対応と、UIライブラリ集 <a href="https://github.com/wvlet/airframe/issues/806">airframe-widget</a> <br>・CircuitBreaker, RateControlなどマイクロサービスAPIを安全に利用するために必要な機能強化<br>・SQLによるMessagePackデータ操作のサポート<br>・AirSpec: Async Testサポート</p><p>などが大きな目玉になる予定です。小さなモジュールの開発を積み重ねてAirframeリポジトリに集積していくことで、Webフレームワークなど大きめのライブラリ開発でも行いやすくなった利点を実感しています。OSSとして使い勝手の良いインターフェースを設計するのがAirframeの開発において一番難しい点ですが、今後も大きな成果のために、小さな投資を続けて行きたいと思います。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1078a0a0c069" width="1" height="1" alt=""><hr><p><a href="https://medium.com/airframe/airframe-meetup-3-1078a0a0c069">Airframe Meetup #3</a> was originally published in <a href="https://medium.com/airframe">Airframe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AirSpec: Writing Tests As Functions In Scala]]></title>
            <link>https://medium.com/airframe/airspec-bbc8d4369157?source=rss----2320a6abf699---4</link>
            <guid isPermaLink="false">https://medium.com/p/bbc8d4369157</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[airframe]]></category>
            <dc:creator><![CDATA[Taro L. Saito]]></dc:creator>
            <pubDate>Fri, 16 Aug 2019 19:50:55 GMT</pubDate>
            <atom:updated>2019-08-22T21:00:02.162Z</atom:updated>
            <content:encoded><![CDATA[<h3>AirSpec: Writing Tests As Plain Functions In Scala</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*uP6b7NZFSGBy4fCa.jpeg" /></figure><p><a href="https://github.com/wvlet/airframe/tree/master/airspec">AirSpec</a> is a new testing framework for Scala and Scala.js.</p><ul><li><a href="https://wvlet.org/airframe/docs/airspec.html">Airframe: airspec</a></li><li><a href="https://github.com/wvlet/airframe/tree/master/airspec">wvlet/airframe</a></li></ul><p>AirSpec uses <strong>plain Scala functions</strong> for writing test cases. This style requires no extra learning cost if you already know Scala. For advanced users, dependency injection to test cases and property-based testing are supported optionally.</p><p>AirSpec has nice properties for writing tests in Scala:</p><ul><li>Simple usage: import wvlet.airspec._, then extends AirSpec trait.</li><li>Using plain Scala classes and methods to define tests. Public methods in a class extending AirSpec trait will be your test cases.</li><li>No annotation (like ones in <a href="https://junit.org/junit5/docs/current/user-guide/">JUnit5</a>) aris necessary.</li><li>Testing with simple assertions: assert(cond) , x shouldBe y, etc. No need to learn complex DSLs.</li><li>Lifecycle management with <a href="https://wvlet.org/airframe/docs/airframe.html">Airframe DI</a>: The arguments of test methods can be used to inject necessary services for running your tests. And also the lifecycle (e.g., start and shutdown) of the injected services can be managed by Airframe DI.</li><li>Nesting and reusing test cases with context.run(spec)</li><li>Handy keyword search for <em>sbt</em>: &gt; testOnly -- (a pattern for class or method names)</li><li>Property-based testing integrated with <a href="https://www.scalacheck.org/">ScalaCheck</a></li><li>Scala 2.11, 2.12, 2.13, and Scala.js support</li></ul><p>We are now planning to add some missing features (e.g., better reporting, power assertions):</p><ul><li><a href="https://github.com/wvlet/airframe/issues/606">Milestone: AirSpec 19</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lC4r2Ox3ng46F5cIJM9qgw.png" /></figure><h3>Motivation</h3><p>In Scala, there are several rich testing frameworks like <a href="http://www.scalatest.org/">ScalaTests</a>, <a href="https://etorreborre.github.io/specs2/">Specs2</a>, <a href="https://github.com/lihaoyi/utest">uTest</a>, etc. We also have a simple testing framework like <a href="https://github.com/monix/minitest">minitest</a>. In 2019, Scala community has started an experiment to creating a nano-testing framework (<a href="https://github.com/scala/nanotest-strawman">nanotest-strawman</a>) based on minitest so that Scala users can have <a href="https://github.com/scala/scala-dev/issues/641">some standards for writing tests in Scala</a> without introducing third-party dependencies.</p><p>A problem here is, in order to write tests in Scala, we usually have only two choices: learning DSLs or being a minimalist.</p><p><strong>Complex DSLs</strong>:</p><ul><li>ScalaTests supports <a href="http://www.scalatest.org/user_guide/selecting_a_style">various writing styles of tests</a> and <a href="http://www.scalatest.org/user_guide/using_assertions">assertions</a>. We had no idea how to choose the best style for our team. To simplify this, uTest has picked only one of the styles from ScalaTests, but it’s still a new domain-specific language on top of Scala. Specs2 introduces its own testing syntax, and even <a href="https://etorreborre.github.io/specs2/">the very first example</a> can be cryptic for new people, resulting in high learning cost.</li><li>With these rich testing frameworks, using a consistent writing style is challenging as they have too much flexibility in writing test; Using rich assertion syntax like x should be (&gt;= 0), x.name must_== &quot;me&quot;, Array(1, 2, 3) ==&gt; Array(1, 2, 3)needs practices and education within team members. We can force team members so as not to use them, but having a consensus on what can be used or not usually takes time.</li></ul><p><strong>Too minimalistic framework:</strong></p><ul><li>On the other hand, a minimalist approach like minitest, which uses a limited set of syntax like asserts and test(&quot;....&quot;), is too restricted. For example, I believe assertion syntax like x shouldBe y is a good invention in ScalaTest to make clear the meaning of assertions to represent (value) shoudlBe (expected value). In minitest assert(x == y) has the same meaning, but the intention of test writers is not clear because we can write it in two ways: assert(value == expected) or assert(expected == value). Minitest also has no feature selecting test cases to run by specifying test names; It only supports specifying class names to run, which is just a basic functionality of <strong>sbt</strong>.</li><li>A minimalist approach forces us to be like a <a href="https://en.wikipedia.org/wiki/Zen">Zen</a> mode. We can extend minitest with rich assertions, but we need to figure out the right balance between a minimalist and developing a DSL for our own teams.</li></ul><h3>AirSpec: Writing Tests As Functions In Scala</h3><p>So where is a middle ground in-between these two extremes? We usually don’t want to learn too complex DSLs, and also we don’t want to be a minimalist, either.</p><p>Why can’t we <strong>use plain Scala functions to define tests</strong>? ScalaTest already has <a href="http://www.scalatest.org/user_guide/selecting_a_style">RefSpec</a> to write tests in Scala functions. Unfortunately, however, its support is limited only to Scala JVM as Scala.js does not support runtime reflections to list function names. Scala.js is powerful for developing web applications in Scala, so we don’t want to drop the support for it. Probably the lack of runtime reflection in Scala.js is a reason why existing testing frameworks needed to develop their own DSLs like test(....) { test body } .</p><p>Now listing functions in Scala.js is totally possible by using <a href="https://wvlet.org/airframe/docs/airframe-surface.html">airframe-surface</a>, which is a library to inspect parameters and methods in a class by using reflection (in Scala JVM) or Scala macros (in Scala.js). So it was good timing for us to develop a new testing framework, which has more Scala-friendly syntax.</p><p>If we can define tests by using functions, it becomes possible to <strong>pass test dependencies through function arguments</strong>. Using local variables in a test class has been the best practice of setting up testing environments (e.g., database, servers, etc.), but it is not always ideal as we need to properly initialize and clean-up these variables for each test method by using setUp/tearDown (or before/after) methods. If we can simply pass these service instances to function arguments using <a href="https://wvlet.org/airframe/docs/airframe.html">Airframe DI</a>, which has strong support of life-cycle management, we no longer need to write such setUp/tearDown steps for configuring testing environments. Once we define a production-quality service with proper lifecycle management hooks (using Airframe design and onStart/onShutdown hooks), we should be able to reuse this lifecycle management code even in test cases.</p><p>AirSpec was born with these ideas in mind by leveraging Airframe modules like Airframe Surface and DI. After implementing basic features of AirSpec, we’ve successfully <strong>migrated all of the test cases in 20+ Airframe modules into AirSpec</strong>, which were originally written in ScalaTest. Rewriting test cases was almost straightforward as AirSpec has handy shouldBe syntax and property testing support with ScalaCheck.</p><p>In the following sections, we will see how to use AirSpec to write tests in a Scala-friendly style.</p><h3>Quick Start</h3><p>To use AirSpec, add airspec to your test dependency and add wvlet.airspec.Framework as a TestFramework:</p><p><strong>build.sbt</strong></p><p>(Check the latest version on <a href="https://wvlet.org/airframe/docs/airspec.html">our web site</a>):</p><pre>libraryDependencies += &quot;org.wvlet.airframe&quot; %% &quot;airspec&quot; % &quot;(version)&quot; % &quot;test&quot;<br>testFrameworks += new TestFramework(&quot;wvlet.airspec.Framework&quot;)</pre><p>For Scala.js, use %%%:</p><pre>libraryDependencies += &quot;org.wvlet.airframe&quot; %%% &quot;airspec&quot; % &quot;(version)&quot; % &quot;test&quot;</pre><h3>Writing Unit Tests</h3><p>In AirSpec test cases are defined as functions in a class (or an object) extending AirSpec. All <strong>public methods</strong> in the class will be executed as test cases:</p><pre>import wvlet.airspec._</pre><pre>class MyTest extends AirSpec {<br>  // Basic assertion<br>  def emptySeqSizeShouldBe0: Unit = {<br>    assert(Seq.empty.size == 0)<br>  }</pre><pre>  // Catch an exception<br>  def emptySeqHeadShouldFail: Unit = {<br>    intercept[NoSuchElementException]{<br>      Seq.empty.head<br>    }<br>  }<br>}</pre><p>If you need to define utility methods in a class, use a private or protected scope.</p><p>AirSpec supports basic assertions like assert, fail, ignore, cancel, pending, skip, intercept[E], and shouldBe matchers, which is will be explained later.</p><p>Tests in AirSpec are just regular functions in Scala. AirSpec is designed to use pure Scala syntax as much as possible so as not to introduce any complex DSLs, which are usually hard to remember.</p><p>AirSpec also supports powerful object lifecycle management, integrated with <a href="https://wvlet.org/airframe/docs/airframe.html">Airframe DI</a>. The function arguments of test methods will be used for injecting objects that are necessary for running tests, and after finishing tests, these objects will be discarded properly.</p><h3>Running Tests in sbt</h3><p>AirSpec supports pattern matching for running only specific tests:</p><pre>$ sbt</pre><pre>&gt; test                                   # Run all tests<br>&gt; testOnly -- (pattern)                  # Run all test matching the pattern (class name or test name)<br>&gt; testOnly -- (class pattern)*(pattern)  # Search everything</pre><p>pattern is used for partial matching with test names. It also supports wildcard (*) and regular expressions. Basically, AirSpec will find matches from the list of all (test class full name):(test function name) strings. Cases of test names will be ignored in the search.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/0*sKR0JrCH_9D8sHSO.png" /></figure><h3>Writing Specs In Natural Languages</h3><p>If you prefer natural language descriptions for your test cases, use symbols for function names:</p><pre>import wvlet.airspec._</pre><pre>class SeqSpec extends AirSpec {<br>  def `the size of empty Seq should be 0`: Unit = {<br>    assert(Seq.empty.size == 0)<br>  }</pre><pre>  // Catch an exception<br>  def `throw NoSuchElementException when taking the head of an empty Set`(): Unit = {<br>    intercept[NoSuchElementException] {<br>      Seq.empty.head<br>    }<br>  }<br>}</pre><p>It is also possible to use symbols for test class names:</p><pre>import wvlet.airspec._</pre><pre>class `Seq[X] test spec` extends AirSpec {<br>  def `the size of empty Seq should be 0`: Unit = {<br>    assert(Seq.empty.size == 0)<br>  }<br>}</pre><h3>shouldBe matchers</h3><p>AirSpec supports handy assertions with shouldBe or shouldNotBe:</p><pre>import wvlet.airspec._</pre><pre>class MyTest extends AirSpec {<br>  def test: Unit = {<br>    // checking the value equality with shouldBe, shouldNotBe:<br>    1 shouldBe 1<br>    1 shouldNotBe 2<br>    List().isEmpty shouldBe true</pre><pre>    // For optional values, shouldBe defined (or empty) can be used:<br>    Option(&quot;hello&quot;) shouldBe defined<br>    Option(null) shouldBe empty<br>    None shouldNotBe defined</pre><pre>    // For Arrays, shouldBe checks the equality with deep equals<br>    Array(1, 2) shouldBe Array(1, 2)</pre><pre>    // Collection checker <br>    Seq(1) shouldBe defined<br>    Seq(1) shouldNotBe empty<br>    Seq(1, 2) shouldBe Seq(1, 2)<br>    (1, &#39;a&#39;) shouldBe (1, &#39;a&#39;)</pre><pre>    // Object equality checker<br>    val a = List(1, 2)<br>    val a1 = a<br>    val b = List(1, 2)<br>    a shouldBe a1<br>    a shouldBeTheSameInstanceAs a1<br>    a shouldBe b<br>    a shouldNotBeTheSameInstanceAs b<br>  }<br>}</pre><h3>Dependency Injection with Airframe DI</h3><p>AirSpec can pass shared objects to your test cases by using function arguments. This is useful for sharing objects initialized only once at the beginning with test cases.</p><h4>Global and Local Sessions</h4><p>AirSpec manages two types of sessions: <em>global</em> and <em>local</em>:</p><ul><li>For each AirSpec instance, a single global session will be created.</li><li>For each test method in the AirSpec instance, a local (child) session that inherits the global session will be created.</li></ul><p>To configure the design of objects that will be created in each session, override configure(Design) and configureLocal(Design)methods in AirSpec.</p><h4>Session LifeCycle</h4><p>AirSpec manages global/local sessions in this order:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*R1T08BoE1b_0eye9ALNKzg.png" /></figure><h4>DI Example</h4><p>This is an example to utilize a global session to share the same service instance between test methods:</p><pre>import wvlet.airspec._<br>import wvlet.airframe._</pre><pre>case class ServiceConfig(port:Int)</pre><pre>class Service(config:ServerConfig) extends LogSupport {<br>  @PostConstruct<br>  def start {<br>    info(s&quot;Starting a server at ${config.port}&quot;)<br>  }</pre><pre>  @PreDestroy<br>  def end {<br>    info(s&quot;Stopping the server at ${config.port}&quot;)<br>  }<br>}</pre><pre>class ServiceSpec extends AirSpec with LogSupport {<br>  override protected def configure(design:Design): Design = {<br>    design<br>      .bind[Service].toSingleton<br>      .bind[ServiceConfig].toInstance(ServiceConfig(port=8080))<br>  }</pre><pre>  def test1(service:Service): Unit = {<br>     info(s&quot;server id: ${service.hashCode}&quot;)<br>  }</pre><pre>  def test2(service:Service): Unit = {<br>     info(s&quot;server id: ${service.hashCode}&quot;)<br>  }<br>}</pre><p>This test shares the same Service instance between two test methods test1 and test2, and properly start and closes the service before and after running tests.</p><pre>&gt; testOnly -- ServiceSpec<br>2019-08-09 17:24:37.184-0700  info [Service] Starting a server at 8080  - (ServiceSpec.scala:25)<br>2019-08-09 17:24:37.188-0700  info [ServiceSpec] test1: server id: 588474577  - (ServiceSpec.scala:42)<br>2019-08-09 17:24:37.193-0700  info [ServiceSpec] test2: server id: 588474577  - (ServiceSpec.scala:46)<br>2019-08-09 17:24:37.194-0700  info [Service] Stopping the server at 8080  - (ServiceSpec.scala:30)<br>[info] ServiceSpec:<br>[info]  - test1 13.94ms<br>[info]  - test2 403.41us<br>[info] Passed: Total 2, Failed 0, Errors 0, Passed 2</pre><h3>Reusing Test Classes</h3><p>To reuse test cases, create a fixture, which is a class, object, or trait extending AirSpec. Then call AirSpecContext.run(AirSpec instance), which can be injected to test method arguments:</p><pre>import wvlet.airspec._</pre><pre>class MySpec extends AirSpec {<br>  // A template for reusable test cases<br>  class Fixture[A](data: Seq[A]) extends AirSpec {<br>    override protected def beforeAll: Unit = {<br>      info(s&quot;Run tests for ${data}&quot;)<br>    }<br>    def emptyTest: Unit = {<br>      data shouldNotBe empty<br>    }<br>    def sizeTest: Unit = {<br>      data.length shouldBe data.size<br>    }<br>  }</pre><pre>  // Inject AirSpecContext using DI<br>  def test(context: AirSpecContext): Unit = {<br>    context.run(new Fixture(Seq(1, 2)))<br>    context.run(new Fixture(Seq(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;)))<br>  }<br>}</pre><p>This code will run the same Fixture two times using different data sets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/0*cCQ_m6S7u7fzVTCl.png" /></figure><p>AirSpecContext also contains the name of test classes and method names, which would be useful to know which tests are currently running.</p><h3>Property-Based Testing with ScalaCheck</h3><p>Optionally AirSpec can integrate with <a href="https://github.com/typelevel/scalacheck/blob/master/doc/UserGuide.md">ScalaCheck</a>. Add wvlet.airspec.spi.PropertyCheck trait to your spec, and use forAll methods.</p><p><strong>build.sbt</strong></p><pre># Use %%% for Scala.js<br>libraryDependencies += &quot;org.scalacheck&quot; %% &quot;scalacheck&quot; % &quot;1.14.0&quot; % &quot;test&quot; <br></pre><pre>import wvlet.airspec._</pre><pre>class PropertyBasedTest extends AirSpec with PropertyCheck {<br>  def testAllInt: Unit = {<br>    forAll{ i:Int =&gt; i.isValidInt shouldBe true }<br>  }</pre><pre>  def testCommutativity: Unit = {<br>    forAll{ (x:Int, y:Int) =&gt; x+y == y+x }<br>  }</pre><pre>  // Using custom genrators of ScalaCheck<br>  def useGenerator: Unit = {<br>    import org.scalacheck.Gen<br>    forAll(Gen.posNum[Long]){ x: Long =&gt; x &gt; 0 shouldBe true }<br>  }<br>}</pre><h3>Scala.js</h3><p>To use AirSpec in Scala.js, scalaJsSupport must be called inside your spec classes:</p><pre>import wvlet.airspec._</pre><pre>class ScalaJSSpec extends AirSpec {<br>  // This is necessary to find test methods in Scala.js<br>  scalaJsSupport  </pre><pre>  def myTest: Unit = assert(1 == 1)<br>}</pre><p>This is because Scala.js has no runtime reflection to find methods in AirSpec classes, so we need to provide method data by calling scalaJsSupport. Internally this will generate MethodSurfaces (airframe-surface) at compile-time, so that AirSpec can find test methods at runtime. Calling scalaJsSupport has no effect in Scala JVM platform, so you can share the same test code with Scala and Scala.js.</p><h3>Conclusions</h3><p>AirSpec is a new testing framework based on Scala-friendly code syntax without introducing any complex DSLs, which usually require additional learning cost. With the integration with Airframe DI and ScalaCheck, it also works as a full-fledged testing framework for advanced users.</p><p>The design philosophy of AirSpec is as follows:</p><ul><li>Minimizing the learning cost by using plain Scala functions as test cases and a limited set of assertion syntax like assert(cond) and x shouldBe y.</li><li>Use function arguments to pass dependencies of your tests.</li><li>Help users to select test cases to run using a handy keyword search.</li></ul><p>The initial feature-complete version of AirSpec is 19.8.4. AirSpec is a part of 20+ Airframe modules and used for testing themselves. Currently, we have no intention to introduce furthermore assertion syntax to avoid becoming a complex framework. The next target is enhancing AirSpec to show more informative test results to users, like power assertions, test result differences, etc.</p><p>With AirSpec, you can now use plain Scala both for coding and writing tests. Let’s enjoy programming in Scala!</p><p><a href="https://github.com/wvlet/airframe/tree/master/airspec">wvlet/airframe</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbc8d4369157" width="1" height="1" alt=""><hr><p><a href="https://medium.com/airframe/airspec-bbc8d4369157">AirSpec: Writing Tests As Functions In Scala</a> was originally published in <a href="https://medium.com/airframe">Airframe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Airframe Meetup #1: Scala開発に役立つ5つのデザインパターンを紹介]]></title>
            <link>https://medium.com/airframe/airframe-meetup-72d6db13182e?source=rss----2320a6abf699---4</link>
            <guid isPermaLink="false">https://medium.com/p/72d6db13182e</guid>
            <category><![CDATA[airframe]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Taro L. Saito]]></dc:creator>
            <pubDate>Wed, 31 Oct 2018 17:26:45 GMT</pubDate>
            <atom:updated>2018-10-29T18:01:59.894Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JO771nBqs7oR5vNusHVKzQ.jpeg" /></figure><p>先日、初のAirframe Meetup #1を開催し、盛況のうちに終了しました。日本への帰国のタイミングに合わせて数週間前に企画したにも関わらず、コアなScalaエンジニアが多く集まる会になり、楽しい時間を過ごすことができました。企画、会場準備を快く手伝ってくれた<a href="https://twitter.com/takezoen">@takezoen</a>さんに感謝。</p><p><a href="https://airframe.connpass.com/event/104722/">Airframe Meetup #1 (2018/10/23 19:30〜)</a></p><p><a href="https://wvlet.org/airframe/">Airframe</a>は<a href="https://techplay.jp/event/694468">10月17日のTD Tech Talk</a>でも紹介しましたが、Scalaのための軽量ライブラリ集で、ここではScalaエンジニア以外の方にも楽しんでいただけるよう、Airframeの各種モジュールやコンセプトの紹介を中心に行いました。</p><p><a href="https://medium.com/@taroleo/airframe%E3%81%AB%E3%82%88%E3%82%8Bscala%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%9F%E3%83%B3%E3%82%B0-%E4%BD%95%E3%81%8C%E3%81%A7%E3%81%8D%E3%82%8B%E3%81%8B-%E3%81%8B%E3%82%89-%E4%BD%95%E3%82%92%E5%8A%B9%E6%9E%9C%E7%9A%84%E3%81%AB%E5%BF%98%E3%82%8C%E3%82%89%E3%82%8C%E3%82%8B%E3%81%8B-%E3%82%92%E8%80%83%E3%81%88%E3%82%8B-e9e0f7fc983a">AirframeによるScalaプログラミング：「何ができるか」から「何を効果的に忘れられるか」を考える</a></p><p>今回のAirframe Meetupでは、Scalaエンジニアにフォーカスすることで、コード例を多く交えながらAirframeのDependency Injection (DI)について、よりディープに解説していくことにしました。DIとは何かを理解するには<a href="https://medium.com/@taroleo/airframe%E3%81%AB%E3%82%88%E3%82%8Bscala%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%9F%E3%83%B3%E3%82%B0-%E4%BD%95%E3%81%8C%E3%81%A7%E3%81%8D%E3%82%8B%E3%81%8B-%E3%81%8B%E3%82%89-%E4%BD%95%E3%82%92%E5%8A%B9%E6%9E%9C%E7%9A%84%E3%81%AB%E5%BF%98%E3%82%8C%E3%82%89%E3%82%8C%E3%82%8B%E3%81%8B-%E3%82%92%E8%80%83%E3%81%88%E3%82%8B-e9e0f7fc983a">上記のブログ</a>を参考にしてください。</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.slideshare.net%2Fslideshow%2Fembed_code%2Fkey%2F2nLJ7Cb37cGsJE&amp;url=https%3A%2F%2Fwww.slideshare.net%2Ftaroleo%2Fairframe-meetup-1-20181023-arm-treasure-data-tokyo-office&amp;image=https%3A%2F%2Fcdn.slidesharecdn.com%2Fss_thumbnails%2F2018-10-23-airframe-meetup-181023102350-thumbnail-4.jpg%3Fcb%3D1540290342&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=slideshare" width="600" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/60c65733e52bf39aa96067b5f41e9882/href">https://medium.com/media/60c65733e52bf39aa96067b5f41e9882/href</a></iframe><p>Airframeでは「プログラマが考えるべきことを効率的に減らす」ためにライブラリをデザインしています。今回ははAirframeのデザインパターンとでも言うべき５つのパターン（+ Pattern 0 (基礎)）について紹介しました。</p><h3>Pattern 0: Auto Wiring</h3><p>AirframeのDIでは、constructor injectionか、in-trait injectionを使うことになります。コンストラクタの引数に必要モジュールを列挙するか、trait内にbind[X]構文を用いてモジュールを注入するかどうかの違いです。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T59bSp2c5U54Hcq_b-tDlw.png" /></figure><p>どちらの場合も、オブジェクトの設計(design)とオブジェクトの構築方法(build)のやり方は同じです。</p><p>ここで、以下のようなA, Bというサービスを作ることを考えます。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bdeg_sA0WaJPu-XgfXzBtA.png" /></figure><p>実際のコーディングの際には、direct dependency (直接の依存関係）にあるオブジェクト(ここではDBClient, FluentdLogger)だけを知っていればよいので、Airframeのin-trait injectionを使うと欲しい機能だけに注目してコーディングすることができます。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*3nvHGqspNAIeRtp-G5MjbQ.png" /></figure><p>しかし、実際には以下にあるように、DBClient, FluentdLoggerの裏側には以下に示すように詳細な実装が隠れています。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dTvuUGzwebb4nx-y" /></figure><p>AやBをテストしようとする際に、これらのモジュールの詳細を考えてオブジェクトを構築するのは非常に大変です。たとえば、手でオブジェクトを組み合わせて構築するコードを書くと以下のようになります：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nDE4ekUTAuDaUpE-k2Iy4g.png" /></figure><p>AirframeによるDIを使うと、オブジェクトの構築方法はフレームワーク側に任せることができるので、以下のような記述だけで済みます：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c-tXaBDRWcBZIJbCSmZiSg.png" /></figure><p>プロダクションのコードでは数十〜数百のモジュールを組み合わせてコーディングすることが普通なので、auto-wiringによるオブジェクト構築の支援はコードを簡潔にするために役立ちます。</p><h3>Pattern 1: Configuring Modules</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FhhoCZbelde8AHZe0vMVaA.png" /></figure><p>モジュールを作る過程で設定パラメータ（コンフィグ）を追加したくなるケースは多いでしょう。Airframeを使うと、モジュールに一番近い場所でコンフィグオブジェクトを定義することができ、モジュールの実装を最小化することができます。Airframeではデフォルトパラメータに基づいてオブジェクトを構築することもできるので、上の例ではConnectionPoolConfig(size=32)というデフォルトオブジェクトが自動的に生成されますし、後からdesignで上書きすることもできます。</p><p>モジュールを最小化するという当たり前のようなことが、実際のプログラミングでは非常に難しいものです。特にHand-wiringをしているとコンフィグオブジェクトを、クラスの深いネストをまたがって受け渡す必要があり、その手間を省くために、globalなコンフィグオブジェクトを作ってしまう例をよく見かけます。例えば、<a href="https://github.com/akka/akka/blob/ba996f8c5f7612cf19191936a25672916ccc909c/akka-actor/src/main/scala/akka/actor/ActorSystem.scala#L298-L383">Akkaにはglobalなコンフィグから、モジュール毎のコンフィグを読むコード</a>がありますが、このアプローチはAkkaくらい大規模なプロジェクトだから割りに合う実装の仕方ででしょう。</p><h3>Pattern 2: Switching Bindings for Tests</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYiP0qeNlB6lqDmDLevI7w.png" /></figure><p>Airframeでは、テスト用に一部の実装を切り替えるのも容易です。デザインの一部だけを上書きするだけで、テスト用のサービスを構築することができます。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/0*0FyDK5KhuwP6K_Qm" /></figure><h3>Pattern 3: Managing Lifecycle in FILO Order</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*fQqnZclFlwb-1xEWSUPGEQ.png" /></figure><p>データベースのコネクション、HTTPクライアントなど、起動、終了処理は通常FILO (First-In Last-Out)の順番で行うことになります。Airframeでは以下のようなライフサイクルフックを記述することでこの管理実現できます：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ggshjQ3vnmpf12xY9cL3tA.png" /></figure><p>オブジェクトの構築をAirframeのようなフレームワークに任せることの利点として、このようなFILOオーダーによるリソース管理もフレームワーク側で自動的に制御できるようになることが挙げられます。</p><h3>Pattern 4: Bundling Service Traits (Flower-bundle pattern)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uXXKzJ1T4FWXRnH6su_5MQ.png" /></figure><p>ScalaのTraitのmix-inは非常に強力で、trait = serviceと考え、DBClient、FluentdClientなどのサービスを定義していくと、traitのmix-inにより、好きなサービスを必要なだけ組み合わせて、より複雑なサービスを構築していくことができます。再利用可能なサービス(module)を構築していくことで、典型的なアプリケーションの開発が効率化されていくのが魅力です。</p><p>実装のパターンとしては、traitの中にサービスのAPIとなる変数１つだけを含む実装(flower)を各種用意し、それを束ねていく(bundle)様子に例えて、<strong>Flower-Bundle Pattern</strong>と呼んでいます。</p><p>基本的にコンストラクタでも同様の組み合わせは実現できますが、クラスが階層に挟まってしまいフラットにバンドルできないため、traitの方が無駄な階層ができずに綺麗に実装できます。</p><h3>Pattern 5: Binding Factory</h3><p>最近Airframeに追加したパターンですが、一部の設定だけを上書きし、その他のモジュールはdesignに指定されたものを使いたい場合に、bindFactoryが使えます。複数のDBへの接続を使い分けたいが、ConnectionPoolなどは再利用したいときなどに便利です。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ie5KHzAJW-eEMx2j4skPFQ.png" /></figure><h3>その他の話題</h3><p>さすが普段からScalaを書いている人たちの集まりで、さらにマニアックな話で盛り上がりました。</p><ul><li>Higher-kinded typeでもbindできるのはAirframeのみ。これは<a href="https://twitter.com/j5ik2o">かとじゅん</a>さんの要望で実現。</li></ul><p><a href="https://qiita.com/j5ik2o/items/fd5ae7c0bf78ae4dee21">高階型の型パラメータを持つDDDリポジトリをDIできるようにする - Qiita</a></p><ul><li>AirframeはJDK11まで対応している。JDK8からJDK9への移行が一番大変で、そこを乗り越えるとあとは楽。Scalaは2.12からJDK9以降に対応している。</li><li>Scala 2.13.0-M5と JDK11で、String.linesメソッド名の衝突のバグがあった。Scala 2.13.0-RC1では修正される。</li><li>Airframeは他のライブラリへの依存関係を極力減らしている。基本的には、Scalaのreflectライブラリのみに依存。</li><li>依存関係を減らすためだけに、JSONパーサー <a href="https://github.com/wvlet/airframe/tree/master/airframe-json">airframe-json</a>や、msgpackパーサー <a href="https://github.com/wvlet/airframe/tree/master/airframe-json">airframe-msgpack</a>まで自作</li><li>Jawn, circe JSON parserはなぜ速いか。table switch命令（コンパイル時にチェックされる）を使っているから。<a href="https://www.scala-lang.org/api/2.12.1/scala/annotation/switch.html">https://www.scala-lang.org/api/2.12.1/scala/annotation/switch.html</a> また、alphabet, numericのみの文字列用のfast pathがある。</li><li>したがって、日本語を多々含む文字列がある場合、json4s-jacksonの方が速いことがある。（巷のベンチマークを信用しすぎないのが吉）。<a href="http://www.lihaoyi.com/post/uJsonfastflexibleandintuitiveJSONforScala.html">速いと言われているuJson</a>がなぜかものすごく遅い。</li><li>無知による再発明(reinvention)は悪だが、十分承知した上で再実装するのは、知識の再現(reproduction)であって、学習のためには非常に有効。どんどん実践するべきだし、再発明より高速にできる。airframe-jsonも２日しか実装に使っていない。</li><li>AirframeはなぜMessagePackを使っているか。<a href="https://medium.com/@taroleo/airframe%E3%81%AB%E3%82%88%E3%82%8Bscala%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%9F%E3%83%B3%E3%82%B0-%E4%BD%95%E3%81%8C%E3%81%A7%E3%81%8D%E3%82%8B%E3%81%8B-%E3%81%8B%E3%82%89-%E4%BD%95%E3%82%92%E5%8A%B9%E6%9E%9C%E7%9A%84%E3%81%AB%E5%BF%98%E3%82%8C%E3%82%89%E3%82%8C%E3%82%8B%E3%81%8B-%E3%82%92%E8%80%83%E3%81%88%E3%82%8B-e9e0f7fc983a">object serializerの実装を簡単にできる</a>。MessagePack + SQLエンジンの実装も<a href="https://github.com/wvlet/airframe/tree/master/airframe-stream">こっそり</a>進めている。</li><li>基本的にREADME.mdを書いていないモジュールはAPIが安定していないので「まだ使わないで」という意図。</li><li>基本的に、bug fixなどを含めてrelease頻度が多いので（10分でScala 2.11, 2.12, 2.13, Scala.js x 18 modulesがリリースできるようになったため）、Airframeは常に最新版を使うのが吉。今年だけで30以上リリースしている。</li><li>SQLエンジンもScalaなら500行で書けるという<a href="https://www.cs.purdue.edu/homes/rompf/papers/rompf-icfp15.pdf">論文</a>の紹介。SQL -&gt; Scalaでパース -&gt; データベースクエリを実行するCやScalaコードを生成</li><li>Treasure DataのScalaエンジニアは最初は１人だったが、徐々に増えてきた。</li></ul><h3>開催後</h3><p>Airframe Meetupをきっかけに以下のようなDIライブラリの比較記事も書いていただきました。Airframeが「Guiceの正統的進化」というのは、開発者にとしてもそこを目指した経緯があり、しっくりくる表現です。</p><p><a href="https://qiita.com/bigwheel/items/86c15c9a205a81018612">Scala用DIライブラリ3種を雑に比較してみた(Guice, Airframe, MacWire) - Qiita</a></p><p>当日の様子は<a href="https://twitter.com/search?f=tweets&amp;vertical=default&amp;q=%23airframe&amp;l=ja&amp;src=typd">#airframeタグ</a>のツイートからも垣間見ることができます。</p><h3>Airframeの今後</h3><p>DIの機能としては、</p><ul><li>implicitパラメータを含むコンストラクタ class A(p1, p2, …)(implicit x1, x2, …) への対応 (<a href="https://github.com/wvlet/airframe/issues/281">#281</a>)</li><li>HTTP request handling時など、child sessionが使えると都合がよい (<a href="https://github.com/wvlet/airframe/issues/70">#70</a>)</li></ul><p>の２点が直近の課題。その他のモジュールもまだ増えていく予定です。</p><p>また日本に帰国する機会にAirframe Meetup #2が実現できれば良いかと思います。例えば、airframe-codec, msgpack周りや、Airframe DI + Finagleによるweb frameworkなど紹介できる事例がいくつかあります。</p><p><a href="https://medium.com/@taroleo/airframe-http-a-minimalist-approach-for-building-web-services-in-scala-743ba41af7f">Airframe HTTP: Building Low-Friction Web Services Over Finagle</a></p><p>Airframe Meetup #1に参加していただいた皆さま、どうもありがとうございました。会場の規模の都合で参加できなかった方にも（すぐに満席になってしまったため、告知もあまり積極的にできませんでした）この記事が参考になれば幸いです。</p><p><a href="https://github.com/wvlet/airframe">wvlet/airframe</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72d6db13182e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/airframe/airframe-meetup-72d6db13182e">Airframe Meetup #1: Scala開発に役立つ5つのデザインパターンを紹介</a> was originally published in <a href="https://medium.com/airframe">Airframe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AirframeによるScalaプログラミング：「何ができるか」から「何を効果的に忘れられるか」を考える]]></title>
            <link>https://medium.com/airframe/airframe%E3%81%AB%E3%82%88%E3%82%8Bscala%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%9F%E3%83%B3%E3%82%B0-%E4%BD%95%E3%81%8C%E3%81%A7%E3%81%8D%E3%82%8B%E3%81%8B-%E3%81%8B%E3%82%89-%E4%BD%95%E3%82%92%E5%8A%B9%E6%9E%9C%E7%9A%84%E3%81%AB%E5%BF%98%E3%82%8C%E3%82%89%E3%82%8C%E3%82%8B%E3%81%8B-%E3%82%92%E8%80%83%E3%81%88%E3%82%8B-e9e0f7fc983a?source=rss----2320a6abf699---4</link>
            <guid isPermaLink="false">https://medium.com/p/e9e0f7fc983a</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[messagepack]]></category>
            <category><![CDATA[airframe]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Taro L. Saito]]></dc:creator>
            <pubDate>Wed, 31 Oct 2018 17:26:35 GMT</pubDate>
            <atom:updated>2018-10-20T05:26:59.865Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dpW8TkGkcwNhQNJ7" /></figure><p><a href="https://techplay.jp/event/694468">TD Tech Talk (October 17, 2018)</a>で、Scala開発のための軽量ライブラリコレクションであるAirframe (<a href="https://wvlet.org/airframe">https://wvlet.org/airframe</a>) について紹介しました。</p><p><a href="https://wvlet.org/airframe">Airframe: Lightweight Building Blocks for Scala</a></p><p>当日の発表スライドはこちらから：</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.slideshare.net%2Fslideshow%2Fembed_code%2Fkey%2Fdnh6hi7aQheI1N&amp;url=https%3A%2F%2Fwww.slideshare.net%2Ftaroleo%2Fairframe-lightweight-building-blocks-for-scala-td-tech-talk-20181014&amp;image=https%3A%2F%2Fcdn.slidesharecdn.com%2Fss_thumbnails%2F2018-10-17-airframe-td-techtalk-181017115831-thumbnail-4.jpg%3Fcb%3D1539833550&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=slideshare" width="600" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/569cf1a73363511e27e780be84065102/href">https://medium.com/media/569cf1a73363511e27e780be84065102/href</a></iframe><p><strong>要点その１</strong>: <a href="https://msgpack.org/">MessagePack</a>を活用すると汎用的なデータ変換が実現でき、データフォーマットごとにオブジェクトマッパーを実装する手間が省けること。スライド中に紹介していますが、応用範囲はデータの変換、保存、転送だけでなくHTTPサーバーの実装と非常に広いです。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2VDGBfxcKq-V2VtuoBhEvQ.png" /><figcaption>、</figcaption></figure><p>MessagePackを使う利点は、以下の３つ：</p><ul><li>様々なデータフォーマットに対応できる</li><li>コンパクトなバイナリ表現</li><li>Self-describing format (データ自身が型を持っている）ため、種々のフォーマットからオブジェクトへのマッピングをschema-on-readのテクニックで実装できる</li></ul><p>また、オブジェクトデータをデータフォーマットを気にせずに手軽に保存できるというのは、計算の再利用、プログラムの再開などを可能にしてくれるので、複雑なデータ処理において強力な武器になります。</p><p><strong>要点その２</strong>: AirframeにはDependency Injection (DI)のためのライブラリがありますが、DIを理解するには、「何ができるか」ではなく、プログラミング中に「何を忘れることができるか」が大切です。</p><h3>Taro L. Saito on Twitter</h3><p>DIに関しては「何ができるか」ではなく「何を忘れることができるか」を見ると理解が深まる、という話をしました https://t.co/XD60A5JKs8 #Scala #airframe #tdtech</p><p>Dependency Injectionは「何ができるか」という観点で考えると非常に難しい概念です（<a href="https://wvlet.org/airframe/docs/comparison.html">DIライブラリの機能比較表</a>も用意しましたがこれだけでAirframeの便利さを実感するのは難しいでしょう ）。ここで発想を転換して「（プログラミング中に）何を効果的に忘れることができるか」を考えると、抑えておくべきポイントは以下に挙げる３つだけで済みます。</p><h4>１: オブジェクトの構築方法を忘れる</h4><p>まず、サービスを構築する際に複数のオブジェクト（モジュール）を組み合わせるのが通常のプログラミングですが、プロダクションとテスト時ではモジュールの構成が違うのが通常です。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vKW8PkLEOgy5mgyWafB13Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XUN7K17EDoBfB1Pb41saXQ.png" /></figure><p>上図のAやBを実装する際に、直接的な依存関係(direct dependency: DBClient, FluentdLogger)だけでなく、間接的な依存関係(indirect dependencies: ConnectionPool, HttpClient, DB, など）まで考慮すると、プログラミング中に大きなワーキングメモリーを必要とします。例えば、毎回手で依存関係を記述する(hand wiringと言います）と以下のようなコードを書く必要があります。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45f87b4ac8e3b303354d83cecc455499/href">https://medium.com/media/45f87b4ac8e3b303354d83cecc455499/href</a></iframe><p>一方、Airframeを利用すると、Aの構築方法(design)を分離し、フレームワーク側に自動的にwiringを任せることができます。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34057e7f063f63ed1a6fa3dbdc1f6311/href">https://medium.com/media/34057e7f063f63ed1a6fa3dbdc1f6311/href</a></iframe><p>一部のモジュールをテスト用に変更するのも簡単です：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/591617580790d7163cfdf9e1ce92670b/href">https://medium.com/media/591617580790d7163cfdf9e1ce92670b/href</a></iframe><p>こうすることで、プログラマはAやBの実装のみに集中することができます。これはインターフェースによる実装の分離という意味だけだと、プログラマにとって常識ではありますが、モジュールの種類やコンフィグオブジェクトの種類が数十〜百近くになると、次第にオブジェクトの受け渡しが面倒になり、インターフェースを最小に分離するのすら困難になる問題が起こります。（例えば、アプリケーションの全コンフィグを、AやBに渡さないとDBを設定できない、など。当然、通常のDBとテスト用のIn-Memory DBでは必要なコンフィグの種類も異なりますし、DBの設定そのものは、A, Bのロジックには関係ありません）</p><h4>2: リソースの管理順(FILO Order)を忘れる</h4><p>データベース、HttpClientなど、起動処理、終了処理が必要なモジュールのリソース管理は、意外と手間がかかります。特に、リソースが共有されている場合には、リソース間の依存関係はDAGの形状になり、正しい順番で管理をしないと、クローズしたリソースにアクセスすることになり、例外（NullPointerException, IllegalStateExceptionなど）が発生する原因になります。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4q9kzz-4gDg5x7w5xc5Hiw.png" /></figure><p>リソースの確保、解放は、FILO (First-In Last-Out)の順にすると安全です。上図の例のように、基本的には数字の順にobjectのリソースが割り当てられ、プログラムの終了時には逆順（8-&gt; 7-&gt; … -&gt; 2 -&gt; 1)で解放します。</p><p>オブジェクトの構築を手動で行う代わりに、フレームワークに任せることで、上図のようなDAGの形状をフレームワーク側が認識できるようになり、FILOオーダーでのリソース管理が自動的にできるようになります。</p><h4>3: DIの存在自体を忘れる</h4><p>Airframeは、フレームワークに依存した形でもコードをかけますが、<a href="https://wvlet.org/airframe/docs/index.html#constructor-injection">コンストラクタインジェクション</a>のみを使うことで、DI部分と実際のモジュールの実装を完全に分離することも可能です。</p><p>特に、Google Guice, ScaldiなどをScalaで利用して苦労していたエンジニアにはその効果が実感できるようです：</p><h3>かとじゅん on Twitter</h3><p>airframeは慣れるとDIコンテナ感がこんなになくて大丈夫か？ってなるんですよね。「Injectorが欲しい欲しい」とわがままを言っていた自分が懐かしいです。</p><h3>masa on Twitter</h3><p>Airframe、実装の実体からDIへの依存を切り離せるのが素晴らしいと思ってます。howとwhatの分離を完全に出来たと思いました。#tdtech</p><h4>まとめ</h4><p>Airframeでは、MessagePackを活用することにより各種データの操作を容易にしました。また、DIを通して、以下の３つに挙げるような、プログラマが実装時に考えるべきことを効率的に減らすことができます：</p><ul><li>オブジェクトの構築方法</li><li>リソースのFILOオーダーによる確保、解放管理</li><li>DIフレームワークそのものの存在</li></ul><p>Separation of concern(関心の分離）と言われることもありますが、具体例がないといまいち実感できない概念でもあるので、この記事では違った観点で紹介しました。</p><p>また、既に満席になってしまいましたが、2018年10月23日に、Airframeを使ったデザインパターンを紹介するためのAirframe Meetup #1を開催します：</p><p><a href="https://airframe.connpass.com/event/104722/">Airframe Meetup #1 (2018/10/23 19:30〜)</a></p><p>最後に、AirframeのリポジトリにGitHubスターをつけていただけると、開発者が喜びますので、どうぞよろしくお願いいたします。</p><p><a href="https://github.com/wvlet/airframe">wvlet/airframe</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9e0f7fc983a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/airframe/airframe%E3%81%AB%E3%82%88%E3%82%8Bscala%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%9F%E3%83%B3%E3%82%B0-%E4%BD%95%E3%81%8C%E3%81%A7%E3%81%8D%E3%82%8B%E3%81%8B-%E3%81%8B%E3%82%89-%E4%BD%95%E3%82%92%E5%8A%B9%E6%9E%9C%E7%9A%84%E3%81%AB%E5%BF%98%E3%82%8C%E3%82%89%E3%82%8C%E3%82%8B%E3%81%8B-%E3%82%92%E8%80%83%E3%81%88%E3%82%8B-e9e0f7fc983a">AirframeによるScalaプログラミング：「何ができるか」から「何を効果的に忘れられるか」を考える</a> was originally published in <a href="https://medium.com/airframe">Airframe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Airframe 0.37: Seamless Integration Between JSON and MessagePack]]></title>
            <link>https://medium.com/airframe/airframe-0-37-seamless-integration-between-json-and-messagepack-ee73b69dadab?source=rss----2320a6abf699---4</link>
            <guid isPermaLink="false">https://medium.com/p/ee73b69dadab</guid>
            <category><![CDATA[messagepack]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Taro L. Saito]]></dc:creator>
            <pubDate>Wed, 31 Oct 2018 17:26:19 GMT</pubDate>
            <atom:updated>2018-02-09T22:58:03.330Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*juFiUWNWWjvoIkmLSMElOQ.jpeg" /></figure><p>Airframe, lightweight building-blocks for Scala, now supports JSON to <a href="https://msgpack.org/">MessagePack</a> conversion in version 0.37:</p><p><a href="http://wvlet.org/airframe/">Airframe: Lightweight Building Blocks for Scala</a></p><p><a href="http://wvlet.org/airframe/docs/airframe-codec.html">airframe-codec</a> already provides mappings between Scala objects (e.g., case classes) and MessagePack, so we can now support conversions like JSON -&gt; MessagePack -&gt; Object -&gt; MessagePack -&gt; JSON. MessagePack works as a catalyst between data types.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee73b69dadab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/airframe/airframe-0-37-seamless-integration-between-json-and-messagepack-ee73b69dadab">Airframe 0.37: Seamless Integration Between JSON and MessagePack</a> was originally published in <a href="https://medium.com/airframe">Airframe</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>