Skip to content

Instantly share code, notes, and snippets.

@halcat0x15a
Last active August 29, 2015 13:58
Show Gist options
  • Save halcat0x15a/10066274 to your computer and use it in GitHub Desktop.
Save halcat0x15a/10066274 to your computer and use it in GitHub Desktop.

!SLIDE

Interruptible Program with Actor and Trampoline

@halcat0x15a

!SLIDE

デモ

会場の皆様には非公開のコードを交えて解説します

!SLIDE

プロセスの停止と再起動

スマートフォン,タブレットでサーバーに接続する

  • コマンド打つのが面倒
  • タスクマネージャを起動するのが面倒
  • マウスが暴れまわる(固有の問題)

!SLIDE

プロセス管理

  • 停止
  • 再起動
  • 設定の更新

Webからプログラムを操作する

!SLIDE

Libraries

  • Unfiltered
    • web toolkit
    • HTTPリクエストの処理に使う
    • プログラムに組み込み易い
  • Akka
    • actors and supervision
    • アクターを生成したりを殺したり
  • Scalaz
    • functional programming
    • Trampolineを使う
    • sequenceとか>>とか…

!SLIDE

Server

HTMLはXMLリテラルベタ書き

自分で使うツールなのでエラー処理とか適当

def intent = {
  case GET(Path("/")) =>
    Html(form())
  case POST(Path("/restart")) =>
    restart()
    Redirect("/")
  case POST(Path("/stop")) =>
    stop()
    Redirect("/")
  case POST(Path("/update")) & Params(params) =>
    update(params)
    Redirect("/")
}

!SLIDE

Interrupible

元のプログラムを割り込み可能な形に書き換えなければならない

def receive = {
  case "loop" =>
    f()
    self ! "loop"
  case "exit" =>
    System.exit(0)
}

全てをメッセージパッシングで書き換えるのは非現実的

!SLIDE

State Machine

プログラムをステートマシンに書き換えてアクターで駆動すれば良い

case class State[A](run: A => State[A])

def receive = {
  case state: State[_] => self ! state.run(input)
}

!SLIDE

Trampoline

元のプログラムはステートレスだったのでトランポリンで記述できる

標準のTailCallsだと再帰が書けないのでScalazを使う

モナドなので手続き的なコードの書き換えも簡単(要出典)

トランポリンの解説

!SLIDE

ActorDSL

アクターを再利用しないならActorDSLを使うと便利

import scalaz.Free
import akka.actor._, ActorDSL._

val system = ActorSystem("system")
 
actor(system, "process")(new Act {
  become {
    case tramp: Free.Trampoline[_] =>
      tramp.resume.fold(self ! _(), _ => ())
  }
})

!SLIDE

ActorSystem

動いてるアクターを参照したり殺したり

system.actorSelection("/user/process").resolveOne(timeout).onSuccess {
  case ref => system.stop(ref)
}

!SLIDE

まとめ

  • Akka便利
  • 2.11早く来てほしい
  • HTML手書きつらい

技術的におもしろいコードだけど公開できないのが残念

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment