SlideShare una empresa de Scribd logo
1 de 26
Descargar para leer sin conexión
Typed Channels
                              and
                           Macros
                           Dr. Roland Kuhn
                              @rolandkuhn




söndag 10 februari 13
The Problem



                  someActor ! CommandOne




söndag 10 februari 13
The Problem


                  trait Command
                  case class CommandOne(param: String) extends Command

                  someActor ! CommandOne




söndag 10 februari 13
The Vision


                           someActor <-!- CommandOne(”msg”)




                        because the other does not compile

söndag 10 februari 13
But How?


                        • ActorRef must know about message types
                          – Actor type must be parameterized
                        • Message type is verified against that




söndag 10 februari 13
And the replies?


                            val f: Future[Response] =

                        someActor <-?- CommandOne(”hello”)




                         because the compiler knows

söndag 10 februari 13
And How This?


                        • ActorRef must know reply types
                          – Actor must be parameterized with them
                        • Reply types are extracted at call site




söndag 10 februari 13
No Type Pollution

                        • Generic Filter/Transform Actors
                          – accept management commands
                          – pass on generic other type
                        • Using just one type is not enough!
                        • Need to use type unions and allow multiple
                          possible reply types for one input



söndag 10 februari 13
Actors Do Compose


                         msg -?-> firstActor -?-> secondActor -!-> client

                        msg -?-> someService -*-> (_ map httpOk) -!-> client




                                Process wiring from the outside

söndag 10 februari 13
The Result:




söndag 10 februari 13
Type-Safe Composability

                             of

                        Actor Systems


söndag 10 februari 13
Relation to π-calculus


                        • Actors are composite processes
                        • Actor types are structural, not nominal
                        • wiring A͡B can be done situationally


                            http://doc.akka.io/ see Typed Channels

söndag 10 februari 13
That was the
                            Eloi world
                        Now we’re going to visit the Morlocks




söndag 10 februari 13
The Implementation

                        • Tagged type union with
                          :+:[(In, Out), ChannelList] <: ChannelList

                        • Value class ChannelRef[…](val a: ActorRef)
                        • Actor mixin Channels[…]
                        • WrappedMessage[…, LUB](val m: LUB)
                        • ops desugar to tell/ask after type check


söndag 10 februari 13
How to Declare it?
                  class OpinionatedEcho extends Actor
                      with Channels[TNil, (String, String) :+: TNil] {

                        channel[String] { (str, sender) ⇒ sender <-!- str }
                        // or
                        channel[String] {
                          case (”hello”, sender) ⇒ sender <-!- ”world”
                          case (x, sender)       ⇒ sender <-!- s”dunno: $x”
                        }

                  }




                           “sender” will accept only String messages

söndag 10 februari 13
First Problem: Lambdas

                        • Type-checker transforms lambda before the
                          macro call
                          – pattern matches or PartialFunction literals
                            generate checks depending on static type info
                        • Behavior is not an argument to “channels”
                        • macro only emits object with right “apply”



söndag 10 februari 13
First Problem: Lambdas
                        private class Behaviorist[-R, Ch: ru.TypeTag](
                            wrapped: Boolean) extends (R ⇒ Unit) {
                          // ...
                            def apply(recv: R): Unit = {
                              val tt = ru.typeTag[Ch]
                                behavior ++= (
                                  for (t ← inputChannels(ru)(tt.tpe))
                                  yield
                                   tt.mirror.runtimeClass(t.widen) -> ff(recv))
                            }
                        }



                                calling channels[_] registers the behavior

söndag 10 februari 13
The Gory Details
                        def impl[LUB, ReplyChannels <: ChannelList,
                            MsgTChan <: ChannelList,
                            MsgT: c.WeakTypeTag,
                            MyCh <: ChannelList: c.WeakTypeTag,
                            ParentCh <: ChannelList: c.WeakTypeTag](
                              c: Context {
                                type PrefixType = Channels[ParentCh, MyCh]
                              }): c.Expr[(Nothing ⇒ Unit)] = {
                         // some type calculations happen here
                         val prepTree = reify(...)
                         reify {
                           prepTree.splice
                           c.prefix.splice.behaviorist[
                             (MsgT, ChannelRef[ReplyChannels]) ⇒ Unit, MsgT](
                               bool(c, false).splice)(universe.typeTag[MsgT])
                         }
                    }



söndag 10 februari 13
The Gory Details
                        trait Channels[P <: ChannelList, C <: ChannelList] {
                          this: Actor ⇒


                         def channel[T]: (Nothing ⇒ Unit) =
                           macro macros.Channel.impl[Any, ChannelList,
                             ChannelList, T, C, P]


                         def behaviorist[R, Ch: ru.TypeTag](wrapped: Boolean)
                           : (R ⇒ Unit) = new Behaviorist[R, Ch](wrapped)


                         // ...
                    }




söndag 10 februari 13
Sample Type Calculation
                    final def missingChannels(u: Universe)(
                        channels: u.Type, required: List[u.Type]): List[u.Type] = {
                        import u._
                        // making the top-level method recursive blows up the compiler
                        def rec(ch: Type, req: List[Type]): List[Type] = {
                            ch match {
                                case TypeRef(_, _, TypeRef(_, _, in :: _) :: tail :: Nil) ⇒
                                  rec(tail, req filterNot (_ <:< in))
                                case last ⇒ req filterNot (_ <:< last)
                            }
                        }
                        rec(channels, required)
                   }




söndag 10 februari 13
How to Return a Type
                        def impl[..., ReplyChannels <: ChannelList, ...]
                            (c: Context): c.Expr[(Nothing ⇒ Unit)] = {
                         // calculate “channels: u.Type” and then:
                         implicit val ttReplyChannels =
                           c.TypeTag[ReplyChannels](channels)


                         reify {
                             ...[(..., ...[ReplyChannels]) ⇒ ..., ...]...
                         }
                    }



                             “reify” picks up TypeTags and uses their .tpe

söndag 10 februari 13
Sharing Code with Runtime

                        final def x(u: Universe)(list: u.Type, msg: u.Type)
                            : List[u.Type] = {
                          val imp = u.mkImporter(ru)
                         val tpeReplyChannels =
                           imp.importType(ru.typeOf[ReplyChannels[_]])
                         val tpeTNil = imp.importType(ru.typeOf[TNil])
                         // ...
                    }




                            otherwise there will be weird exceptions

söndag 10 februari 13
How to test it?
                        def mkToolbox(compileOptions: String = "")
                          : ToolBox[_ <: scala.reflect.api.Universe] = {
                             val m = scala.reflect.runtime.currentMirror
                             m.mkToolBox(options = compileOptions)
                         }


                    def eval(code: String, compileOptions: String =
                             "-cp akka-actor/target/classes:akka-channels/target/classes")
                         : Any = {
                             val tb = mkToolbox(compileOptions)
                             tb.eval(tb.parse(code))
                         }




söndag 10 februari 13
How to test it?
                    intercept[ToolBoxError] {
                        eval("""
                             import akka.channels._
                             import ChannelSpec._
                             implicit val c = new ChannelRef[TNil](null)
                             new ChannelRef[(A, C) :+: TNil](null) <-!- B
                           """)
                    }.message must include(
                      "target ChannelRef does not support messages of " +
                        "types akka.channels.ChannelSpec.B.type")




söndag 10 februari 13
get it and learn more
                           http://akka.io
                        http://letitcrash.com
                        http://typesafe.com

söndag 10 februari 13
E0F
söndag 10 februari 13

Más contenido relacionado

Similar a Akka typed-channels

Unit Testing Presentation
Unit Testing PresentationUnit Testing Presentation
Unit Testing Presentationnicobn
 
Clojure 1.1 And Beyond
Clojure 1.1 And BeyondClojure 1.1 And Beyond
Clojure 1.1 And BeyondMike Fogus
 
From Java to Parellel Clojure - Clojure South 2019
From Java to Parellel Clojure - Clojure South 2019From Java to Parellel Clojure - Clojure South 2019
From Java to Parellel Clojure - Clojure South 2019Leonardo Borges
 
Testing for share
Testing for share Testing for share
Testing for share Rajeev Mehta
 
Property based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rulesProperty based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rulesDebasish Ghosh
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrencyAlex Navis
 
Asynchronous Orchestration DSL on squbs
Asynchronous Orchestration DSL on squbsAsynchronous Orchestration DSL on squbs
Asynchronous Orchestration DSL on squbsAnil Gursel
 
Fun with errors? - Clojure Finland Meetup 26.3.2019 Tampere
Fun with errors? - Clojure Finland Meetup 26.3.2019 TampereFun with errors? - Clojure Finland Meetup 26.3.2019 Tampere
Fun with errors? - Clojure Finland Meetup 26.3.2019 TampereMetosin Oy
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Introthnetos
 
Functional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smartFunctional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smartChen Fisher
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
ClojureScript for the web
ClojureScript for the webClojureScript for the web
ClojureScript for the webMichiel Borkent
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojureAbbas Raza
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011tobiascrawley
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015Michiel Borkent
 

Similar a Akka typed-channels (20)

Lecture38
Lecture38Lecture38
Lecture38
 
Unit Testing Presentation
Unit Testing PresentationUnit Testing Presentation
Unit Testing Presentation
 
Clojure 1.1 And Beyond
Clojure 1.1 And BeyondClojure 1.1 And Beyond
Clojure 1.1 And Beyond
 
From Java to Parellel Clojure - Clojure South 2019
From Java to Parellel Clojure - Clojure South 2019From Java to Parellel Clojure - Clojure South 2019
From Java to Parellel Clojure - Clojure South 2019
 
C# programming
C# programming C# programming
C# programming
 
Testing for share
Testing for share Testing for share
Testing for share
 
Property based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rulesProperty based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rules
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
Clojure concurrency
Clojure concurrencyClojure concurrency
Clojure concurrency
 
Asynchronous Orchestration DSL on squbs
Asynchronous Orchestration DSL on squbsAsynchronous Orchestration DSL on squbs
Asynchronous Orchestration DSL on squbs
 
Fun with errors? - Clojure Finland Meetup 26.3.2019 Tampere
Fun with errors? - Clojure Finland Meetup 26.3.2019 TampereFun with errors? - Clojure Finland Meetup 26.3.2019 Tampere
Fun with errors? - Clojure Finland Meetup 26.3.2019 Tampere
 
StORM preview
StORM previewStORM preview
StORM preview
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Intro
 
Functional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smartFunctional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smart
 
Hidden Gems of Ruby 1.9
Hidden Gems of Ruby 1.9Hidden Gems of Ruby 1.9
Hidden Gems of Ruby 1.9
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
ClojureScript for the web
ClojureScript for the webClojureScript for the web
ClojureScript for the web
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
 

Más de Roland Kuhn

Taming Distribution: Formal Protocols for Akka Typed
Taming Distribution: Formal Protocols for Akka TypedTaming Distribution: Formal Protocols for Akka Typed
Taming Distribution: Formal Protocols for Akka TypedRoland Kuhn
 
Distributed systems vs compositionality
Distributed systems vs compositionalityDistributed systems vs compositionality
Distributed systems vs compositionalityRoland Kuhn
 
Reactive Design Patterns — J on the Beach
Reactive Design Patterns — J on the BeachReactive Design Patterns — J on the Beach
Reactive Design Patterns — J on the BeachRoland Kuhn
 
The Newest in Session Types
The Newest in Session TypesThe Newest in Session Types
The Newest in Session TypesRoland Kuhn
 
Akka Typed — between Session Types and the Actor Model
Akka Typed — between Session Types and the Actor ModelAkka Typed — between Session Types and the Actor Model
Akka Typed — between Session Types and the Actor ModelRoland Kuhn
 
Project Gålbma – Actors vs Types
Project Gålbma – Actors vs TypesProject Gålbma – Actors vs Types
Project Gålbma – Actors vs TypesRoland Kuhn
 
Akka Streams and HTTP
Akka Streams and HTTPAkka Streams and HTTP
Akka Streams and HTTPRoland Kuhn
 
Akka and AngularJS – Reactive Applications in Practice
Akka and AngularJS – Reactive Applications in PracticeAkka and AngularJS – Reactive Applications in Practice
Akka and AngularJS – Reactive Applications in PracticeRoland Kuhn
 
Go Reactive: Blueprint for Future Applications
Go Reactive: Blueprint for Future ApplicationsGo Reactive: Blueprint for Future Applications
Go Reactive: Blueprint for Future ApplicationsRoland Kuhn
 
Reactive Streams: Handling Data-Flow the Reactive Way
Reactive Streams: Handling Data-Flow the Reactive WayReactive Streams: Handling Data-Flow the Reactive Way
Reactive Streams: Handling Data-Flow the Reactive WayRoland Kuhn
 
Akka cluster overview at 010dev
Akka cluster overview at 010devAkka cluster overview at 010dev
Akka cluster overview at 010devRoland Kuhn
 

Más de Roland Kuhn (11)

Taming Distribution: Formal Protocols for Akka Typed
Taming Distribution: Formal Protocols for Akka TypedTaming Distribution: Formal Protocols for Akka Typed
Taming Distribution: Formal Protocols for Akka Typed
 
Distributed systems vs compositionality
Distributed systems vs compositionalityDistributed systems vs compositionality
Distributed systems vs compositionality
 
Reactive Design Patterns — J on the Beach
Reactive Design Patterns — J on the BeachReactive Design Patterns — J on the Beach
Reactive Design Patterns — J on the Beach
 
The Newest in Session Types
The Newest in Session TypesThe Newest in Session Types
The Newest in Session Types
 
Akka Typed — between Session Types and the Actor Model
Akka Typed — between Session Types and the Actor ModelAkka Typed — between Session Types and the Actor Model
Akka Typed — between Session Types and the Actor Model
 
Project Gålbma – Actors vs Types
Project Gålbma – Actors vs TypesProject Gålbma – Actors vs Types
Project Gålbma – Actors vs Types
 
Akka Streams and HTTP
Akka Streams and HTTPAkka Streams and HTTP
Akka Streams and HTTP
 
Akka and AngularJS – Reactive Applications in Practice
Akka and AngularJS – Reactive Applications in PracticeAkka and AngularJS – Reactive Applications in Practice
Akka and AngularJS – Reactive Applications in Practice
 
Go Reactive: Blueprint for Future Applications
Go Reactive: Blueprint for Future ApplicationsGo Reactive: Blueprint for Future Applications
Go Reactive: Blueprint for Future Applications
 
Reactive Streams: Handling Data-Flow the Reactive Way
Reactive Streams: Handling Data-Flow the Reactive WayReactive Streams: Handling Data-Flow the Reactive Way
Reactive Streams: Handling Data-Flow the Reactive Way
 
Akka cluster overview at 010dev
Akka cluster overview at 010devAkka cluster overview at 010dev
Akka cluster overview at 010dev
 

Último

Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 

Último (20)

Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 

Akka typed-channels

  • 1. Typed Channels and Macros Dr. Roland Kuhn @rolandkuhn söndag 10 februari 13
  • 2. The Problem someActor ! CommandOne söndag 10 februari 13
  • 3. The Problem trait Command case class CommandOne(param: String) extends Command someActor ! CommandOne söndag 10 februari 13
  • 4. The Vision someActor <-!- CommandOne(”msg”) because the other does not compile söndag 10 februari 13
  • 5. But How? • ActorRef must know about message types – Actor type must be parameterized • Message type is verified against that söndag 10 februari 13
  • 6. And the replies? val f: Future[Response] = someActor <-?- CommandOne(”hello”) because the compiler knows söndag 10 februari 13
  • 7. And How This? • ActorRef must know reply types – Actor must be parameterized with them • Reply types are extracted at call site söndag 10 februari 13
  • 8. No Type Pollution • Generic Filter/Transform Actors – accept management commands – pass on generic other type • Using just one type is not enough! • Need to use type unions and allow multiple possible reply types for one input söndag 10 februari 13
  • 9. Actors Do Compose msg -?-> firstActor -?-> secondActor -!-> client msg -?-> someService -*-> (_ map httpOk) -!-> client Process wiring from the outside söndag 10 februari 13
  • 10. The Result: söndag 10 februari 13
  • 11. Type-Safe Composability of Actor Systems söndag 10 februari 13
  • 12. Relation to π-calculus • Actors are composite processes • Actor types are structural, not nominal • wiring A͡B can be done situationally http://doc.akka.io/ see Typed Channels söndag 10 februari 13
  • 13. That was the Eloi world Now we’re going to visit the Morlocks söndag 10 februari 13
  • 14. The Implementation • Tagged type union with :+:[(In, Out), ChannelList] <: ChannelList • Value class ChannelRef[…](val a: ActorRef) • Actor mixin Channels[…] • WrappedMessage[…, LUB](val m: LUB) • ops desugar to tell/ask after type check söndag 10 februari 13
  • 15. How to Declare it? class OpinionatedEcho extends Actor with Channels[TNil, (String, String) :+: TNil] { channel[String] { (str, sender) ⇒ sender <-!- str } // or channel[String] { case (”hello”, sender) ⇒ sender <-!- ”world” case (x, sender) ⇒ sender <-!- s”dunno: $x” } } “sender” will accept only String messages söndag 10 februari 13
  • 16. First Problem: Lambdas • Type-checker transforms lambda before the macro call – pattern matches or PartialFunction literals generate checks depending on static type info • Behavior is not an argument to “channels” • macro only emits object with right “apply” söndag 10 februari 13
  • 17. First Problem: Lambdas private class Behaviorist[-R, Ch: ru.TypeTag]( wrapped: Boolean) extends (R ⇒ Unit) { // ... def apply(recv: R): Unit = { val tt = ru.typeTag[Ch] behavior ++= ( for (t ← inputChannels(ru)(tt.tpe)) yield tt.mirror.runtimeClass(t.widen) -> ff(recv)) } } calling channels[_] registers the behavior söndag 10 februari 13
  • 18. The Gory Details def impl[LUB, ReplyChannels <: ChannelList, MsgTChan <: ChannelList, MsgT: c.WeakTypeTag, MyCh <: ChannelList: c.WeakTypeTag, ParentCh <: ChannelList: c.WeakTypeTag]( c: Context { type PrefixType = Channels[ParentCh, MyCh] }): c.Expr[(Nothing ⇒ Unit)] = { // some type calculations happen here val prepTree = reify(...) reify { prepTree.splice c.prefix.splice.behaviorist[ (MsgT, ChannelRef[ReplyChannels]) ⇒ Unit, MsgT]( bool(c, false).splice)(universe.typeTag[MsgT]) } } söndag 10 februari 13
  • 19. The Gory Details trait Channels[P <: ChannelList, C <: ChannelList] { this: Actor ⇒ def channel[T]: (Nothing ⇒ Unit) = macro macros.Channel.impl[Any, ChannelList, ChannelList, T, C, P] def behaviorist[R, Ch: ru.TypeTag](wrapped: Boolean) : (R ⇒ Unit) = new Behaviorist[R, Ch](wrapped) // ... } söndag 10 februari 13
  • 20. Sample Type Calculation final def missingChannels(u: Universe)( channels: u.Type, required: List[u.Type]): List[u.Type] = { import u._ // making the top-level method recursive blows up the compiler def rec(ch: Type, req: List[Type]): List[Type] = { ch match { case TypeRef(_, _, TypeRef(_, _, in :: _) :: tail :: Nil) ⇒ rec(tail, req filterNot (_ <:< in)) case last ⇒ req filterNot (_ <:< last) } } rec(channels, required) } söndag 10 februari 13
  • 21. How to Return a Type def impl[..., ReplyChannels <: ChannelList, ...] (c: Context): c.Expr[(Nothing ⇒ Unit)] = { // calculate “channels: u.Type” and then: implicit val ttReplyChannels = c.TypeTag[ReplyChannels](channels) reify { ...[(..., ...[ReplyChannels]) ⇒ ..., ...]... } } “reify” picks up TypeTags and uses their .tpe söndag 10 februari 13
  • 22. Sharing Code with Runtime final def x(u: Universe)(list: u.Type, msg: u.Type) : List[u.Type] = { val imp = u.mkImporter(ru) val tpeReplyChannels = imp.importType(ru.typeOf[ReplyChannels[_]]) val tpeTNil = imp.importType(ru.typeOf[TNil]) // ... } otherwise there will be weird exceptions söndag 10 februari 13
  • 23. How to test it? def mkToolbox(compileOptions: String = "") : ToolBox[_ <: scala.reflect.api.Universe] = { val m = scala.reflect.runtime.currentMirror m.mkToolBox(options = compileOptions) } def eval(code: String, compileOptions: String = "-cp akka-actor/target/classes:akka-channels/target/classes") : Any = { val tb = mkToolbox(compileOptions) tb.eval(tb.parse(code)) } söndag 10 februari 13
  • 24. How to test it? intercept[ToolBoxError] { eval(""" import akka.channels._ import ChannelSpec._ implicit val c = new ChannelRef[TNil](null) new ChannelRef[(A, C) :+: TNil](null) <-!- B """) }.message must include( "target ChannelRef does not support messages of " + "types akka.channels.ChannelSpec.B.type") söndag 10 februari 13
  • 25. get it and learn more http://akka.io http://letitcrash.com http://typesafe.com söndag 10 februari 13