165
Institutionen för datavetenskap Department of Computer and Information Science Final thesis Representation of asynchronous communication protocols in Scala and Akka by Joakim Eriksson LIU-IDA/LITH-EX-A--13/038--SE 2013-06-28 Linköpings universitet SE-581 83 Linköping, Sweden Linköpings universitet 581 83 Linköping

liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

Institutionen för datavetenskapDepartment of Computer and Information Science

Final thesis

Representation of asynchronous communicationprotocols in Scala and Akka

by

Joakim Eriksson

LIU-IDA/LITH-EX-A--13/038--SE

2013-06-28

Linköpings universitetSE-581 83 Linköping, Sweden

Linköpings universitet581 83 Linköping

Page 2: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in
Page 3: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

Linköping University

Department of Computer and Information Science

Final Thesis

Representation of asynchronous

communication protocols in Scala and Akka

by

Joakim Eriksson

LIU-IDA/LITH-EX-A--13/038--SE

2013-06-28

Supervisors: Mattias Evensson (Xdin AB, Linköping)

Lena Buffoni (IDA, LiU)

Examiner: Kristian Sandahl (IDA, LiU)

Page 4: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in
Page 5: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

Abstract

This thesis work investigates how to represent protocols for asynchronouscommunication in the Scala programming language and the Akka actorframework, to be run on Java Virtual Machine (JVM). Further restrictionsfrom the problem domain - the coexistence of multiple protocol instancessharing the same Java thread - imply that neither an asynchronous call wait-ing for response nor anything else can block the underlying Java threads.

A common way to represent asynchronous communication protocols isto use state machines. This thesis seeks a way to shrink the size of andto reduce the complexity of the protocol implementations by representingsequences of asynchronous communication calls (i.e. sequences of sent andreceived messages) as a type of procedure. The idea is find a way to makethe procedures that contain asynchronous calls look like synchronous com-munication procedures by hiding the asynchronous details. In other words,the resulting procedure code should show what to do and not so much focuson how to overcome the impediment of the asynchronous calls.

With the help of an asynchronous communication protocol toy example,this report shows how such an protocol can be implemented with a combi-nation of a state machine and a procedure representation in Scala and Akka.The procedure representation hides away the asynchronous details by usingthe Scala capability to use CPS-transformed delimited continuations. Asa sub-problem, this thesis also shows how to safely schedule asynchronouscommunication timeouts with help of Scala and Akka within the restrictionsof the thesis problem domain.

Page 6: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

Acknowledgements

This thesis have been written with help from others. First, I want tothank my examiner Kristian Sandahl and institution supervisor Lena Buf-foni. Their experience, insight and feedback has had a great impact on thedirection of the work and the improvement of this report.

I want to thank my company supervisor Mattias Evensson, who has beena great source of information. He has had to put up with many difficultquestions from me.

My opponent Hampus Malmstrom did not have an easy task giving con-structive feedback on such a sizable report and narrow subject. I reallyappreciate the effort made.

Finally, a special thanks to my dear Linn who has spent a lot of timesupporting the work and motivating me. Without her this thesis would nothave been finished.

Vikingstad, June 2013

Joakim Eriksson

iv

Page 7: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

Contents

1 Thesis introduction 11.1 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11.2 Purpose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

1.2.1 A shift from state machine representation . . . . . . . 21.2.2 A representation suited for high concurrency . . . . . 2

1.3 Scope and limitations . . . . . . . . . . . . . . . . . . . . . . 31.4 Goals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.5 Methodology and thesis overview . . . . . . . . . . . . . . . . 31.6 Audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.7 Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.8 Typographical conventions . . . . . . . . . . . . . . . . . . . . 5

2 Technology introductions 72.1 Introduction to Scala . . . . . . . . . . . . . . . . . . . . . . . 7

2.1.1 Technical details of Scala . . . . . . . . . . . . . . . . 72.1.2 Comparison between Scala and Java . . . . . . . . . . 82.1.3 Reasons for the focus on Scala . . . . . . . . . . . . . 102.1.4 Scala literature . . . . . . . . . . . . . . . . . . . . . . 11

2.2 Introduction to Actors . . . . . . . . . . . . . . . . . . . . . . 122.2.1 The problem that actors solve . . . . . . . . . . . . . . 122.2.2 Using actors . . . . . . . . . . . . . . . . . . . . . . . . 132.2.3 The Scala actor library . . . . . . . . . . . . . . . . . 142.2.4 The Akka framework . . . . . . . . . . . . . . . . . . . 14

2.3 Introductions to state machines . . . . . . . . . . . . . . . . . 162.3.1 What are state machines used for? . . . . . . . . . . . 16

3 Investigation of current solution 183.1 Common traits of the protocols . . . . . . . . . . . . . . . . . 183.2 Graphic visualization of program logic as a state machine . . 193.3 Problems with the current solution . . . . . . . . . . . . . . . 193.4 Technical solutions of interest and limitations . . . . . . . . . 193.5 Focus on the developer . . . . . . . . . . . . . . . . . . . . . . 20

v

Page 8: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CONTENTS

4 Investigation of possible techniques 214.1 Generic SM implementations . . . . . . . . . . . . . . . . . . 21

4.1.1 Example state machine . . . . . . . . . . . . . . . . . 214.1.2 Nested match/case implementation . . . . . . . . . . . 234.1.3 Transition table . . . . . . . . . . . . . . . . . . . . . . 244.1.4 The state pattern . . . . . . . . . . . . . . . . . . . . . 254.1.5 The state machine compiler . . . . . . . . . . . . . . . 29

4.2 Akka specific SM implementations . . . . . . . . . . . . . . . 304.2.1 Actor methods become and unbecome . . . . . . . . . . 304.2.2 Akka FSM implementation . . . . . . . . . . . . . . . . 324.2.3 Composition of state machine and actor . . . . . . . . 33

4.3 Scala specific SM implementations . . . . . . . . . . . . . . . 344.3.1 Domain specific languages . . . . . . . . . . . . . . . . 344.3.2 Internal DSL . . . . . . . . . . . . . . . . . . . . . . . 354.3.3 External DSL . . . . . . . . . . . . . . . . . . . . . . . 38

4.4 How to delay, take time and schedule . . . . . . . . . . . . . . 404.4.1 Delay test bench evaluation . . . . . . . . . . . . . . . 404.4.2 Immediate response with no delay (ND) . . . . . . . . 414.4.3 Thread sleep (TS) . . . . . . . . . . . . . . . . . . . . 414.4.4 Java utility timer (GJT and LJT) . . . . . . . . . . . 424.4.5 Akka scheduler (AS) . . . . . . . . . . . . . . . . . . . 434.4.6 Akka FSM state timeout (FSMSTO) . . . . . . . . . . . 434.4.7 Akka FSM timers (FSMT) . . . . . . . . . . . . . . . . 444.4.8 Akka receive timeout (RTO) . . . . . . . . . . . . . . 454.4.9 Future with ask timeout (FTO) . . . . . . . . . . . . . 454.4.10 Future with Await.result (FAR) . . . . . . . . . . . . 464.4.11 Comparison . . . . . . . . . . . . . . . . . . . . . . . . 46

4.5 Asynchronous Procedures . . . . . . . . . . . . . . . . . . . . 504.5.1 Continuations . . . . . . . . . . . . . . . . . . . . . . . 514.5.2 Dataflow and Futures . . . . . . . . . . . . . . . . . . 544.5.3 Thunk procedure . . . . . . . . . . . . . . . . . . . . . 54

4.6 Investigation summary . . . . . . . . . . . . . . . . . . . . . . 60

5 Specification of toy example 625.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625.2 Relation to thesis context . . . . . . . . . . . . . . . . . . . . 635.3 NET states . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645.4 Interaction with UE NET . . . . . . . . . . . . . . . . . . . . 64

5.4.1 Interaction between APPL and NET . . . . . . . . . . 655.4.2 Interaction between RADIO and NET . . . . . . . . . 655.4.3 Interaction between UE and CORE side in NET layer. 67

5.5 Procedures in UE NET . . . . . . . . . . . . . . . . . . . . . 705.5.1 A procedure notation . . . . . . . . . . . . . . . . . . 705.5.2 Primitive procedures . . . . . . . . . . . . . . . . . . . 715.5.3 Composite procedures . . . . . . . . . . . . . . . . . . 72

vi

Page 9: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CONTENTS

5.6 A larger example . . . . . . . . . . . . . . . . . . . . . . . . . 73

6 Implementation of toy example 756.1 Technical choices for implementation . . . . . . . . . . . . . . 75

6.1.1 Mapping between specification and implementation . . 756.1.2 State machine . . . . . . . . . . . . . . . . . . . . . . . 766.1.3 Asynchronous Procedure . . . . . . . . . . . . . . . . . 766.1.4 Timeout . . . . . . . . . . . . . . . . . . . . . . . . . . 766.1.5 Test framework . . . . . . . . . . . . . . . . . . . . . . 766.1.6 Mock framework . . . . . . . . . . . . . . . . . . . . . 77

6.2 Implementation result . . . . . . . . . . . . . . . . . . . . . . 776.2.1 Code structure . . . . . . . . . . . . . . . . . . . . . . 776.2.2 Asynchronous procedure implementation . . . . . . . . 786.2.3 Toy example state machine part . . . . . . . . . . . . 796.2.4 Toy example asynchronous procedures part . . . . . . 796.2.5 Tests of toy example . . . . . . . . . . . . . . . . . . . 79

6.3 Evaluation of implementation . . . . . . . . . . . . . . . . . . 796.3.1 Technical details . . . . . . . . . . . . . . . . . . . . . 806.3.2 Implementation validity and applicability . . . . . . . 81

7 Discussion 837.1 Generalization and applicability . . . . . . . . . . . . . . . . . 83

7.1.1 The asynchronous procedure implementation . . . . . 837.1.2 Applicability on protocols similar to toy example . . . 847.1.3 Improved timeouts . . . . . . . . . . . . . . . . . . . . 84

7.2 Other solutions . . . . . . . . . . . . . . . . . . . . . . . . . . 857.2.1 Other implementation choices in Scala and Akka . . . 857.2.2 Java and Akka . . . . . . . . . . . . . . . . . . . . . . 867.2.3 Other JVM languages . . . . . . . . . . . . . . . . . . 86

7.3 Ideas for further investigation . . . . . . . . . . . . . . . . . . 867.3.1 Remove transitions states in state machine . . . . . . 867.3.2 Complete protocol as an asynchronous procedure . . . 877.3.3 Improve testing of asynchronous procedures . . . . . . 877.3.4 Remote actors for even greater numbers of simulated

entities . . . . . . . . . . . . . . . . . . . . . . . . . . 887.4 Thesis relevance and changing technologies . . . . . . . . . . 88

8 Conclusions 898.1 Representation of state machines . . . . . . . . . . . . . . . . 898.2 Asyncronous procedure . . . . . . . . . . . . . . . . . . . . . 89

8.2.1 AP usefulness . . . . . . . . . . . . . . . . . . . . . . . 898.2.2 AP performance . . . . . . . . . . . . . . . . . . . . . 90

8.3 Akka . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 908.4 Results from delay test bench . . . . . . . . . . . . . . . . . . 908.5 Conclusions from implementation evaluation . . . . . . . . . . 91

vii

Page 10: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CONTENTS

A Questions and answers in initial investigation 92A.1 Questions and answers in Swedish . . . . . . . . . . . . . . . 92

B Notes from implementation evaluation session 96B.1 The notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96

C Questions and answers for implementation evaluation 99C.1 Questions and answers in Swedish . . . . . . . . . . . . . . . 99

D Toy example implementation source code 101D.1 Asynchronous procedures . . . . . . . . . . . . . . . . . . . . 101D.2 Protocol definition . . . . . . . . . . . . . . . . . . . . . . . . 104

D.2.1 Source code folder protocol . . . . . . . . . . . . . . . 104D.2.2 Source code folder protocol/fsm . . . . . . . . . . . . 106D.2.3 Source code folder protocol/procedure . . . . . . . . . 109

D.3 Protocol tests . . . . . . . . . . . . . . . . . . . . . . . . . . . 119D.3.1 Test code folder protocol . . . . . . . . . . . . . . . . 119D.3.2 Test code folder protocol/fsm . . . . . . . . . . . . . . 120D.3.3 Test code folder protocol/procedure . . . . . . . . . . 126D.3.4 Test code folder protocol/procedure/mockable . . . . . 142

Index 146

Bibliography 147

viii

Page 11: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

List of Tables

4.1 Transition table for ballpoint pen state machine . . . . . . . . 224.2 Delay for actors using the techniques ND, GJT and AS . . . 484.3 Delay for actors using Java thread sleep (TS) . . . . . . . . . 484.4 Delay for actors using the techniques LJT and FAR . . . . . 494.5 Delay for quantity of 1 000 concurrent actors . . . . . . . . . 494.6 Delay for quantity of 20 000 concurrent actors . . . . . . . . . 494.7 SM representation technique summary . . . . . . . . . . . . . 604.8 Delay technique summary . . . . . . . . . . . . . . . . . . . . 614.9 AP representation technique summary . . . . . . . . . . . . . 61

ix

Page 12: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

List of Figures

4.1 State transition diagram for a ballpoint pen . . . . . . . . . . 224.2 The state pattern . . . . . . . . . . . . . . . . . . . . . . . . . 284.3 Class diagram for ballpoint pen SM as state pattern . . . . . 28

5.1 NET overview . . . . . . . . . . . . . . . . . . . . . . . . . . . 635.2 NAS overview . . . . . . . . . . . . . . . . . . . . . . . . . . . 635.3 Toy example state machine . . . . . . . . . . . . . . . . . . . 645.4 The powerOn interaction . . . . . . . . . . . . . . . . . . . . . 655.5 The powerOff interaction . . . . . . . . . . . . . . . . . . . . . 655.6 The is detached interaction . . . . . . . . . . . . . . . . . . . 655.7 The connect interaction . . . . . . . . . . . . . . . . . . . . . 665.8 The disconnect interaction . . . . . . . . . . . . . . . . . . . 665.9 The send interaction . . . . . . . . . . . . . . . . . . . . . . . 665.10 The receive interaction . . . . . . . . . . . . . . . . . . . . . 675.11 The forcedDetach interaction . . . . . . . . . . . . . . . . . . 675.12 The attach interaction . . . . . . . . . . . . . . . . . . . . . 685.13 The detach interaction . . . . . . . . . . . . . . . . . . . . . . 685.14 The authentication interaction . . . . . . . . . . . . . . . . . 695.15 Large message interaction example . . . . . . . . . . . . . . . 74

Page 13: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

List of code listings

1.1 A code listing sample . . . . . . . . . . . . . . . . . . . . . . . 62.1 A Java example program . . . . . . . . . . . . . . . . . . . . . 82.2 A long Scala example program . . . . . . . . . . . . . . . . . 92.3 A short Scala example program . . . . . . . . . . . . . . . . . 94.1 Classes common to all Ballpoint pen SM implementations . . 234.2 Ballpoint pen SM as nested match/case . . . . . . . . . . . . 244.3 Ballpoint pen SM as state-event tuple match/case . . . . . . 254.4 Ballpoint pen SM as transition table . . . . . . . . . . . . . . 264.5 Ballpoint pen SM as state design pattern . . . . . . . . . . . 274.6 Ballpoint pen SM in some definition format . . . . . . . . . . 294.7 Ballpoint pen SM as actor with become method. . . . . . . . . 314.8 Adapter between a ballpoint pen SM and an actor . . . . . . 314.9 Ballpoint pen SM as actor with FSM trait . . . . . . . . . . . . 334.10 Ballpoint pen SM as actor-SM composition . . . . . . . . . . 344.11 Internal DSL for SM example . . . . . . . . . . . . . . . . . . 364.12 Ballpoint pen SM with internal DSL . . . . . . . . . . . . . . 374.13 Pin code lock definitions . . . . . . . . . . . . . . . . . . . . . 374.14 Pin code lock SM with internal DSL . . . . . . . . . . . . . . 394.15 Delay test bench message token . . . . . . . . . . . . . . . . . 414.16 Delay test bench class AbstractDelayActor . . . . . . . . . . . 414.17 Delay test bench class AbstractAkkaFsmActor . . . . . . . . . . 424.18 Delay actor with no delay (ND) . . . . . . . . . . . . . . . . . 424.19 Delay actors using Thread.sleep . . . . . . . . . . . . . . . . . 434.20 Delay actors using java.util.Timer . . . . . . . . . . . . . . . 434.21 Delay actors using Akka scheduler . . . . . . . . . . . . . . . 444.22 Delay actors using Akka FMS state timeout . . . . . . . . . . . 444.23 Delay actors using Akka FSM timers . . . . . . . . . . . . . . . 444.24 Delay actors using Akka receive timeout . . . . . . . . . . . . 454.25 Delay actors using Future with ask timeout . . . . . . . . . . 464.26 Delay actors using Future with Await.result . . . . . . . . . 474.27 Delimited Continuation example . . . . . . . . . . . . . . . . 534.28 Simple AP example - thunk procedure implementation. . . . 554.29 Simple AP example - usage in test program. . . . . . . . . . . 564.30 Simple AP example - output from test program. . . . . . . . 56

xi

Page 14: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

4.31 Advanced AP example - thunk procedure implementation. . . 574.32 Advanced AP example - usage of AP in a test program. . . . 584.33 Advanced AP example - output from test program. . . . . . . 596.1 Toy example thunk definition . . . . . . . . . . . . . . . . . . 786.2 Toy example procedure runner definition . . . . . . . . . . . . 78D.1 Source file thunkprocedure/Procedure.scala . . . . . . . . . . 101D.2 Source file thunkprocedure/ThunkWrapper.scala . . . . . . . . 103D.3 Source file protocol/Message.scala . . . . . . . . . . . . . . . 104D.4 Source file protocol/Stratum.scala . . . . . . . . . . . . . . . 106D.5 Source file protocol/fsm/NetFsm.scala . . . . . . . . . . . . . 106D.6 Source file protocol/fsm/NetState.scala . . . . . . . . . . . . 107D.7 Source file protocol/fsm/Procedures.scala . . . . . . . . . . . 108D.8 Source file protocol/procedure/AuthProcedures.scala . . . . . 109D.9 Source file protocol/procedure/CoreProcedures.scala . . . . . 110D.10 Source file protocol/procedure/Environment.scala . . . . . . . 111D.11 Source file protocol/procedure/FsmProcedures.scala . . . . . 114D.12 Source file protocol/procedure/NondetReceiveSugar.scala . . 115D.13 Source file protocol/procedure/package.scala . . . . . . . . . 115D.14 Source file protocol/procedure/PrimitiveProcedures.scala . . 116D.15 Source file protocol/procedure/ThunkSugar.scala . . . . . . . 118D.16 Test source file protocol/CompleteSpecificationSuite.scala . 119D.17 Test source file protocol/fsm/FsmTestUtil.scala . . . . . . . . 120D.18 Test source file protocol/fsm/IntegrationTest.scala . . . . . 121D.19 Test source file protocol/fsm/NetFsmSpec.scala . . . . . . . . 124D.20 Test source file protocol/procedure/AuthProceduresSpec.scala 126D.21 Test source file protocol/procedure/CoreProceduresSpec.scala 129D.22 Test source file protocol/procedure/EnvironmentSpec.scala . 132D.23 Test source file protocol/procedure/Fixture.scala . . . . . . 136D.24 Test source file protocol/procedure/FsmProceduresSpec.scala 138D.25 Test source file protocol/procedure/PrimitiveProceduresSpec.scala139D.26 Test source file protocol/procedure/mockable/AuthMock.scala 142D.27 Test source file protocol/procedure/mockable/CoreMock.scala 142D.28 Test source file protocol/procedure/mockable/package.scala . 143D.29 Test source file protocol/procedure/mockable/PrimitiveMock.scala144

Page 15: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

Nomenclature

AP asynchronous procedure

AS Akka scheduler - a delay technique

CPS continuation passing style

DSL domain specific language

FAR future with Await.result - a delay technique

FSM finite state machine

FSMSTO Akka FSM state timeout - a delay technique

FSMT Akka FSM timers - a delay technique

FTO future using ask timeout - a delay technique

GJT global Java utility timer - a delay technique

JVM Java virtual machine

LJT local Java utility timer - a delay technique

ND no delay - a delay technique

RTO Akka receive timeout - a delay technique

RW real-world implementation techniques

SM state machine

TE toy example implementation techniques

TS thread sleep - a delay technique

xiii

Page 16: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in
Page 17: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

Chapter 1

Thesis introduction

This chapter starts with a background, definition of the thesis work andends with a small overview of this report.

1.1 Background

This thesis work is done at the Linkoping office of the consulting firm namedXdin. In Linkoping, Xdin has about 50 employees and works with embed-ded systems, test, quality assurance and system development among otherthings. This thesis work is related to Xdin’s operations in the developmentof test tools for mobile telecommunication systems.

Xdin develops performance test tools for network entities in these mobiletelecommunication systems. The performance test tools are programs runon a Java virtual machine (JVM) and simulate many simultaneous entities tobe connected to the device under test. These simulated connections are builtup via multiple protocol layer (a protocol stack), that must be implementedin the test tools.

A common practice when implementing communication protocols is torepresent the different protocols as state machines. What is currently doneat Xdin is to use a graphical tool to draw state machines as state tran-sition diagrams, in a plugin called UniMod1 in the Eclipse developmentenvironment (Eclipse IDE2). The graphical tool then generates Java codethat realizes the state machine that in its turn realizes a protocol.

The problem with the current solution at Xdin is that the state machinesare hard to overview and hard to maintain. There are too many states andtransitions in the state machines, for it to be easy to use even in the graphicaltool.

A distictive trait of these existing protocol state machines are that theyonly have a few long-term stable states. A simile would be the states on and

1UniMod homepage: http://unimod.sourceforge.net/ (accessed: 2013-05-27).2Eclipse IDE homepage: http://www.eclipse.org/ (accessed: 2013-05-27).

1

Page 18: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 1. THESIS INTRODUCTION

off. In addition to these stable states, there are large quantities of transitionstates that are there to bridge the stable states. The transition states oftenform sequences of multiple states, conducting asynchronous communicationwith other entities via messages sent back and forth between entities. Inaddition to this, there are also sequences of transition states to facilitate thecommunication error handling. All in all this ammounts to a lot of transitionstates in between the long-term stable states.

1.2 Purpose

The idea behind the thesis work is to look at other ways than the currentlyused state machines, to represent protocols in the protocol stack. In essence,the thesis show techniques that aims to simplify the development and main-tenance effort of the protocol implementations in the simulation test toolcontext.

1.2.1 A shift from state machine representation

As mentioned in the background, the protocol state machines have the for-mat of sequences of transition states between the few stable states. Thesecharacteristics have led to the idea to represent the protocols as a small statemachine in combination with a procedure representation. The procedurerepresentation replaces the current sequences of transition states betweenthe stable states.

The purpose of this thesis is to show that it is possible to in part breakaway from the current state machine representation in program code forasynchronous communication protocols, thereby reducing the intermediatetranslation to state machines from a protocol specification.

Further, the purpose of this thesis is to show that some asynchronousprotocol procedures can be represented directly as a function or a procedurein the selected host programming language. The asynchronous nature of theprotocol can be abstracted away, so the representation becomes compactand concise. In other words, the thesis aims to show how to reduce thetranslation effort between protocol specification and the representation inprogram code, compared to a exclusive use of state machines as protocolrepresentation.

1.2.2 A representation suited for high concurrency

As mentioned in the background, the protocol implementations are usedin a simulation context in a JVM environment. In the simulations, thenumber of simulated protocol instances far exceeds the number of possibleJVM threads. This means that an abstraction must be used to separate theprotocol instances (the concurrently executing entities) from the underlyingJVM threads. As an effect, many protocol instances will share the same

2

Page 19: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

1.3. SCOPE AND LIMITATIONS

JVM thread and this must be of consideration when representing a protocolin program code. Any operation in a protocol instance that blocks a JVMthread will also affect other protocol instances.

1.3 Scope and limitations

Some technology choices are made in order to limit the thesis scope. Sincethe use of the JVM is a must (a hard requirement), Scala is selected as theprogramming language to focus on. Scala can be run on the JVM and hassome features not available in Java. One such feature is called delimitedcontinuations and is in this thesis report shown to be useful in the thesiscontext.

This thesis focus on a specific Scala framework to facilitate the needfor high concurrency environment. This specific framework is Akka, and isnormally referred to as an actor framework.

The thesis does not so much focus the suitability of Scala and Akkain the application context and their suitability compared to other possibletechnology choices. The lion share of the focus in this report is on how tosolve the thesis goals given the technical capabilities in Scala and Akka.

1.4 Goals

The overall goal of the thesis work is to show whether it is possible andpractical to fulfill the thesis purpose with the use of Scala and Akka.

In detail, the first goal is to make an investigation of the technical capa-bilities in Scala and Akka, in relation to the thesis context.

The second goal is to make an implementation of a asynchronous proto-col using Scala and Akka. This implementation will practically show howan implementation can fulfill the intentions stated in the purpose section.The implementation is based on a toy example that in some sense is repre-sentative for the type of protocols dealt with at Xdin.

The third goal is to some extent evaluate the implementation and discussthe technology choices available. An assessment is made on the practical use-fulness and generalizability of the made implementation for other protocols,similar to the toy example protocol.

1.5 Methodology and thesis overview

The thesis work is divided into some sub parts. These are explained here togive an overview of the thesis work and report disposition:

1. An overview of some of the technologies used in this thesis is givenat first. The introduced technologies are the Scala programming lan-

3

Page 20: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 1. THESIS INTRODUCTION

guage, actor systems, the Akka actor framework and finally state ma-chines.

2. Investigation of the domain of the problem, to get a deeper under-standing of the current solution and to get a grip of what propertiesare sought after in a solution.

3. Investigation of the chosen technologies and common or possible solu-tions to technical challenges. An example of such a technical challengeto investigate is how state machines usually are represented and ifthere are some specific types of representations facilitated by Scala orAkka. Another technical challenge to investigate is how to representthe procedures for asynchronous communication.

4. Investigation and identification of possible problems and areas of in-terest, when making an implementation in Scala and Akka. One suchpossible problem is how to enable the asynchronous communicationtimeouts without blocking or creating numerous threads.

5. Definition of a toy example protocol. A key focus of the toy exampleis to let it contain properties common in real world examples.

6. Implementation of the toy example, with chosen solutions based onearlier investigations. The rationale for making a concrete implemen-tation is threefold. Firstly, it shows that it can be done. Secondly,a concrete implementation is a great communication tool and a goodbasis for conclusions. Thirdly, making a concrete implementation high-lights unforeseen problem areas and stress tests the technology choicesmade.

7. Evaluation of the implemented solution, to in some sense make anassessment of whether the thesis work has fulfilled the goals set up inthe thesis.

8. Discussion and conclusion based on the the investigations, implemen-tation and evaluations made in the thesis.

The three tasks initial problem domain investigation, definition of a toyexample and evaluation of solution (tasks 2, 5 and 7) are made with thehelp of the thesis supervisor at Xdin - Mattias Evensson. He is in thiscontext regarded as the domain expert, and are therefore used as a sourceof information for the initial investigation, the toy example specification andthe evaluation of the final toy example implementation.

1.6 Audience

The report aims to target an audience at approximately the same level asstudents at the near end of a computer science or computer engineering

4

Page 21: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

1.7. TERMINOLOGY

degree. The report makes some assumptions on areas that the reader isexpected to know.

The thesis focuses on specific problems, so the content might be mostrelevant to readers dealing with similar problems. To a wider audience,the thesis report gives discussions and concrete implementation examplesof Scala’s delimited continuations, some features in Akka and gives a fairlycomprehensive view of the alternative ways to implement state machines inScala.

The report does often present code listings in Scala, to illustrate a tech-nique or a problem solution, so at least a basic understanding of Scala willto a great extent help the reader.

1.7 Terminology

Two terms are extensively used in the report and need some explanation.

State Machine A state machine (SM) is normally regarded as more gen-eral compared to a finite state machine (FSM), because as a theoreticalconcept a state machine can have an infinite number of states.

In the communication protocol implementation context of this reportthe number of states in state machines is finite and therefore SM andFSM are used interchangeably. In this report, normally the termsstate machine or just SM are used and the term FSM is only usedfor entities named FSM such as the Akka trait akka.actor.FSM. Seesection 2.3 for a general introduction and section 4.1 some concreteusage examples.

Asynchronous procedure An asynchronous procedure (AP) is in this re-port used as a name for a type of program code representation for asyn-chronous communication. As described in the thesis purpose in 1.2.1,an AP is an asynchronous protocol procedure represented directly asa function or a procedure in the selected host programming languagewith the asynchronous details of protocol messaging abstracted away.This thesis shows a solution for this AP representation in the Scalaprogramming language.

This report do sometimes refer to AP to be synchronous looking andall that means is that the asynchonous details are abstracted away inthe protocol procedure implementation.

1.8 Typographical conventions

These typographical conventions will be used throughout the report:

• Larger code listings for Java and Scala code will look like the examplecode in listing 1.1. The numbers on the left of the listing indicates the

5

Page 22: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 1. THESIS INTRODUCTION

line numbers in original source code, and may therefore not alwaysbegin with the number 1 (one).

• Names that refer to code, such as names of objects, values or functionsare in a typewriter font.

• Names and things emphasized are italic, as long as they are not relatedto code.

• URLs are displayed as http://www.some.domain.

Code listing 1.1: A code listing sample

showspacesshowspacesshowspacesshowspaces showspaces1 val q = ”The answer to the u l t imate ques t i on o f l i f e i s ”showspacesshowspaces showspaces2 var a = 42showspacesshowspaces showspaces3 // comment: q i s of type String and a i s of type Intshowspacesshowspaces showspaces4 p r i n t l n ( q + a )showspacesshowspaces

6

Page 23: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

Chapter 2

Technology introductions

This chapter gives an overview and a short introduction to some of thetechnologies relevant to the thesis.

2.1 Introduction to Scala

“Scala is a big language, but you can use it effectively withoutknowing all of its details intimately.” - Horstman [6]

The fact that Scala is a big language is reflected in the thesis work.Scala solutions and examples presented in code listings are only exampleson how to solve things - there are most often also other ways to do it. In thissection only some features of Scala will be mentioned and the syntax willnot be explained. This report will focus on a few Scala features and theirapplication area in the thesis context. This section will only give an briefoverview and try to give some motivation to the Scala focus in this thesis.

2.1.1 Technical details of Scala

Scala unifies object oriented programming with functional programming.Scala is fully object oriented which means that everything is an object. Al-most everything in Scala is functional in the sense that it is an expression andreturns a value. Even control structures like if and for return a value andthe Java keyword void is replaced with the Scala class Unit. As mentionedby Kullberg [7], there is also a class named Option that replaces null andthereby considerably reduces the risk for generating NullPointerException.

Scala has advanced type inference, which means that types are figuredout by the Scala compiler, so there are in many cases no need to explicitlywrite out the type for values, variables, parameters and function. It mighthowever be a good idea to explicitly write out the type in certain places,just for clarity.

7

Page 24: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 2. TECHNOLOGY INTRODUCTIONS

Scala is extensible. Odersky et al. [9] states that a language cannotalways be perfect, but rather needs to be adaptable, and that Scala has thecapability to grow new control structures. An observation on this subject isthat from Scala version 2.8.0 onwards, the Scala compiler has a plugin thatenables a feature that is called delimited continuation in Scala.

Kullberg [7] mentions both that Scala is open source and not own by acompany. It is developed on a university and thereby paid for with taxes.

2.1.2 Comparison between Scala and Java

As explained in the background, Java is the language used in the currentsolution at Xdin. To give some perspective on the use of Scala in relation tothe current use of Java, a comparison is made between the two languages.Further, all Scala books in the bibliography have made some type of com-parison between Scala and Java and they have their obvious reasons.

According to Kullberg [7], Scala is closely integrated with Java and theScala performance is comparable with Java. Also, the Scala compiler com-piles Scala source code directly to JVM byte code1. For the JVM, there isno major difference between Scala and Java source code.

Code listings 2.1, 2.2 and 2.3 shows some differences between Java andScala. All three examples do the same thing - sorts a copy of the stringarray named data and print it out to standard out stream.

Code listing 2.1: A Java example program

showspacesshowspacesshowspacesshowspaces showspaces1 import java . u t i l . Arrays ;showspacesshowspaces showspaces2 import java . u t i l . Comparator ;showspacesshowspaces showspaces3

showspacesshowspaces showspaces4 import s t a t i c data . Data . data ;showspacesshowspaces showspaces5

showspacesshowspaces showspaces6 pub l i c f ina l class Java {showspacesshowspaces showspaces7 pub l i c s t a t i c void main ( S t r ing [ ] a rgs ) {showspacesshowspaces showspaces8

showspacesshowspaces showspaces9 St r ing [ ] dataByLength = data . c l one ( ) ;showspacesshowspaces showspaces10

showspacesshowspaces showspaces11 Arrays . s o r t ( dataByLength , new Comparator<Str ing >() {showspacesshowspaces showspaces12 @Overr ideshowspacesshowspaces showspaces13 pub l i c i n t compare ( S t r ing a , S t r ing b) {showspacesshowspaces showspaces14 return I n t e g e r . compare ( a . l ength ( ) , b . l ength ( ) ) ;showspacesshowspaces showspaces15 }showspacesshowspaces showspaces16 }) ;showspacesshowspaces showspaces17

showspacesshowspaces showspaces18 for ( S t r ing element : dataByLength )showspacesshowspaces showspaces19 System . out . p r i n t l n ( element ) ;showspacesshowspaces showspaces20 }showspacesshowspaces showspaces21 }showspacesshowspaces

1Scala code can also be compiled to the .NET platform according to the official Scalasite[1].

8

Page 25: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

2.1. INTRODUCTION TO SCALA

Code listing 2.2: A long Scala example program, made to resemble the cor-responding Java program in listing 2.1.

showspacesshowspacesshowspacesshowspaces showspaces1 import data . Data . datashowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 object Sca la1 {showspacesshowspaces showspaces4 def main ( args : Array [ S t r ing ] ) : Unit = {showspacesshowspaces showspaces5

showspacesshowspaces showspaces6 val dataByLength : Array [ S t r ing ] =showspacesshowspaces showspaces7 data . sortWith { ( a , b ) => a . l ength ( ) < b . l ength ( ) }showspacesshowspaces showspaces8

showspacesshowspaces showspaces9 for ( element <− dataByLength )showspacesshowspaces showspaces10 p r i n t l n ( element )showspacesshowspaces showspaces11 }showspacesshowspaces showspaces12 }showspacesshowspaces

Code listing 2.3: A short Scala example program, intentionally written to becompact.

showspacesshowspacesshowspacesshowspaces showspaces1 import data . Data . datashowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 object Sca la2 extends App {showspacesshowspaces showspaces4 data sortWith { . l ength < . l ength } f o r each p r i n t l nshowspacesshowspaces showspaces5 }showspacesshowspaces

Listing 2.1 shows an almost minimal2 Java program. The Scala code inlisting 2.2 is written to resemble the Java code in listing 2.1. The code inlisting 2.3 is intentionally written to be a small and compact Scala imple-mentation, that do the same thing as the Java code in listing 2.1.

After working with Scala under approximately half a year (the workwith this thesis), I have formed some opinions on the differences betweenScala and Java. I usually end up explaining to other people that Scala isas Java on steroids - You can access things in Java Runtime Environment(JRE) system library without restrictions, but you program with syntaxmuch more expressive and concise than ordinary Java syntax. On top ofthat, Scala has libraries that take full advantage of the extra functionalitythat Scala gives on top of Java.

Further, Scala’s functional programming and type inference are two fea-tures that are really handy when you have gotten used to them. Listing 2.3shows the strength of functional programming, when passing functions asarguments - it is done twice in the single line of code (line 4) in the Scala2

class body.

Less code Scala classes sometimes becomes so short it is hard to motivatewhy they should have a separate file. Besides, there is no need to haveseparate files for separate Scala classes as it is needed for Java classes. There

2disregarding white space characters, imports and variable names

9

Page 26: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 2. TECHNOLOGY INTRODUCTIONS

are several examples of that in code listings in this report. According toKullberg [7] Scala code size is approximately 25% - 50% of the correspondingJava code size.

Makes some design patterns moot Scala can to a large or at leastsome extent eliminate the need for some design patterns commonly used inJava:

• Visitor pattern is replaced with simple pattern matching.

• Decorator pattern can be replaced by the use of trait mixin.

• Strategy pattern and SAM3-interfaces intended for dependency injec-tion can to a large extent be replaced with, named or anonymous,functions as argument. In other words - they are replaced with func-tional programming. The Comparator in listing 2.1 compared to theanonymous comparison functions in listings 2.2 and 2.3 are excellentexamples.

Increases productivity Your mileage may vary depending on program-ming style and adoption rate, but I think Scala lets developers become moreproductive, compared to Java. If you consider the compact syntax and, letus call it, dynamically typed language feel this opinion is somewhat sup-ported by the comparison between seven different languages made by LutzPrechelt [11]. Worth noting is that Kullberg [7, p. 9] gives the productiv-ity increase together with a decreased risk taking, compared to traditionallanguages such as Java, as the very reason to learn and adopt Scala.

2.1.3 Reasons for the focus on Scala

Here follow some factors for the focus on Scala in the thesis:

• Scala runs on the the JVM.

• Scala has support for concurrency programming via a concept calledactors.

• Scala has support for a program construct called delimited continua-tions, via a technique called continuation passing style. This reportshows how the support for delimited continuations can be use as a toolto realize the concept of asynchronous procedure concept.

• Scala is statically typed. According to Odersky et al. [9] static typinggives some advantages over dynamic typing. Source code propertiedbecomes verifiable, safe refactoring of code can be made and the statictyping helps as documentation and communication in the source code.

3Single Abstract Method

10

Page 27: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

2.1. INTRODUCTION TO SCALA

• Scala is not Java. Java is a part of the current status quo. Currentsolutions used at Xdin are written in Java. Java does have supportfor actors via the Akka library but lacks the official support for con-tinuations, essential to achieve the goals of this thesis. See section 4.5- Asynchronous Procedures for more details.

However, it should be noted that there also exists some third partycontinuation solutions for Java. Searching for “Java continuation” onGoogle, a frequently mentioned solution is Apache Commons Javaflow4.

• Scala integrates seamlessly to Java. Scala is not a big step from Javaand this gives a shallow learning curve for Java developers who switchto Scala. Existing legacy code written in Java can be used with easein Scala.

• Specifying one single language limit the scope of the thesis.

2.1.4 Scala literature

This thesis makes heavy use of Scala, but further explanation of the Scalalanguage in general is out of scope for this thesis. There are many resourceson Internet on the Scala language.

The Scala language is currently under development and is subject tochange. From 2007 to 2013 there have been from one to five new releaseseach year5, but Scala resources in the bibliography list will probably give agood understanding of the Scala language:

• Programming Scala by Dean Wampler and Alex Payne [15]. Old edi-tion is accessible on Internet. Chapter on actors is not longer valid.Only covers the basics of the language.

• Programming in Scala by Martin Odersky, Lex Spoon and Bill Venners[9]. Old edition is accessible on Internet. This is a long and thoroughread. Chapter on actors is no longer valid.

• Scala for the Impatient by Cay S. Horstman [6]. Currently not freelyaccessible on Internet. This book not as long as some of the otherbooks (less than 400 pages), but does a great job covering advancedtopics such as delimited continuations and Scala’s built in parsingcapabilities. The downside is that it dives right in and skips muchof the basics in Scala. The chapter about actors is out of date forthe same reason as in the other books - since Scala version 2.10 theoriginal Scala actors are deprecated and Akka Actors has become apart of the distribution6.

4Javaflow - http://commons.apache.org/sandbox/commons-javaflow/index.html

(accessed 2013-03-27).5According to the distributions archive at the official Scala language site [1]6Scala version 2.10 was released 4 January 2013

11

Page 28: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 2. TECHNOLOGY INTRODUCTIONS

• Ett forsta steg i Scala by Olle Kullberg [7]. Swedish book. Currentlynot freely accessible on Internet. This book is a great introductionon the Scala language. The chapter on actors does cover Akka actorsand is therefore more up to date in that subject than the other books.However the Akka version used in the book is old and it might be agood idea to also look in the official Akka documentation [14] at thesame time as reading the book.

2.2 Introduction to Actors

“You can view the actor model as a special case of object-orientedprogramming where all communication between objects takes placevia message passing, and when an object’s internal state changesonly in response to messages.” - Haller and Sommers [5, ch. 2.2]

This section gives an introduction to actors in general and to the Akkaframework implementation of actors in specific.

As given by the Akka documentation [14], an actor model is a strategyfor implementing concurrent execution. A key concept of a actor model isto avoid shared mutable data (state) between concurrent executing entitiesin a program by not sharing any mutable data between the entities. Theseconcurrent executing entities are called actors.

The communication between actors is done via asynchronous messages.The messages are asynchronous in the sense “send and forget” - no directanswers are given when a message is sent. Each message received by anactor ends up in what can be called a mailbox. There are no guaranties onthe order of received messages, besides that consecutive messages sent fromone specific actor to another specific actor are received in the same orderthey are sent. There is no guarantee that a sent message is delivered. Thereis also no specific guarantee regarding the time to deliver a message to anactor, besides that the time to deliver is a finite duration.

An actor processes messages that are received in the mailbox, one mes-sage at a time. The fact that only one message is processed at a time ensuresthat there is no race condition between received messages in an actor. Mes-sages sent to an actor are stored in the mailbox until they are processed bythe actor.

2.2.1 The problem that actors solve

According to Haller et al. [5] the actor model can be seen as a high-levelconcurrency abstraction that shields the programmer from the intricaciesthat can easily lead to errors. Odersky et al. [9] states that actor styleprogramming lets you take advantage of multiple threads and processors ina computer system. They further state that the use of actors with mes-

12

Page 29: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

2.2. INTRODUCTION TO ACTORS

sage passing hide away the parts of multi-thread programming that are a“minefield of deadlocks and race conditions”.

No locks or monitors for shared-state synchronization

There is no need to synchronize the access to mutable data that is sharedbetween multiple threads, because with actors the data do not need to beaccessed directly. With actors, this can be solved by hiding the mutabledata within a specific actor. The data can then be read or written to viaimmutable messages sent to the actor safekeeping the data.

The synchronization of messages sent and received are hidden within theactor system and do not need to be dealt with by the developer using theactors. According to Kullberg [7] actors are easier to reason about thanusing the synchronization mechanisms in e.g. Java. Kullberg [7] also statesthat deadlocks in Java are especially tricky, because they are not relieveduntil the entire JVM is restarted.

Using actors does not eliminate deadlocks and race conditions but Oder-sky et at. [9] states that using actor style programming reduces the risksinvolved.

2.2.2 Using actors

Odersky et al. [9, ch. 30], Horstman [6, p. 301] and Kullberg [7, p. 58-60]state some different key points to think about when using actors. Some ofthese key points are mentioned in this section.

Actors should not block

Horstman [6] states that when an actor blocks, it does not process additionalmessages received in the mailbox and may well lead to deadlocks. Makingsynchronous calls between actors (asking a question and awaiting a reply)is one way to block an actor.

An investigation on different ways to trigger an delay in actors is con-ducted in section 4.4. The investigation among other things shows the per-formance impact when an actor actually blocks either the underlying threador the individual actor in the Akka actor framework.

Communicate with actors only via messages

Communication to an actor should be done via the actor message passingmechanism. Other means of communication may bypass the synchronizationmechanisms in the actor and undo the benefits of using actors.

In the Akka framework for instance, a great effort is put into anonymizingthe actor instances behind a indirect reference to the actor. The indirectaccess to actors in Akka can be broken out of, by gaining direct access tothe actor instance. This direct access does however undo features such as

13

Page 30: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 2. TECHNOLOGY INTRODUCTIONS

the actor life cycle management and the possibility to run the actor on aremote system, among other things.

Prefer immutable messages

Messages sent to an actor should be immutable. If the message is not im-mutable, the sender and the receiver can end up sharing access to a mutablemessage - i.e. a shared mutable state.

Make messages self-contained

Horstman [6] states that it is preferable to include contextual data in mes-sages - that an actor should be able to understand a message in isolation,without having to keep track of related messages.

As stated earlier, the order of receiving messages is not always guarantiedand keeping data from earlier messages also means greater complexity in thereceiving actor.

An actor is a single threaded safe haven

Actors put the focus on the communication between entities (threads oractors). By using a single entry point for the messages sent to an actor, allcode inside an actor can be regarded as single threaded. Ordinary threadsshould not be mixed with actors.

2.2.3 The Scala actor library

Before the Scala release version 2.10, there were two separate and well-known actor libraries for Scala. The Scala library was included in the Scalalanguage library while Akka was a completely separate entity. The Scalalanguage library has however initialized the migration to Akka actors inScala version 2.10, according to The Scala Actors Migration Guide7. TheScala actors will in the future be regarded as deprecated.

2.2.4 The Akka framework

Akka implements actors. Akka is a software framework that can be usedboth as a library and as a standalone program. It is designed for concur-rency, remoting and fault tolerance. Some key points from the official Akkadocumentation [14]:

• Akka has both a Scala API and a Java API, so the Akka frameworkis not limited to the use of the Scala programming language.

7http://docs.scala-lang.org/overviews/core/actors-migration-guide.html (ac-cessed 2013-03-20)

14

Page 31: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

2.2. INTRODUCTION TO ACTORS

• Akka actors can be seen as very lightweight event-driven processes(approximately 2.7 million actors per GB RAM).

• Actors can be run on remote systems and everything in Akka is de-signed to work in a distributed environment.

• Akka focuses on fault tolerance. Akka supports actor supervisor hi-erarchies, that can span over multiple JVMs to provide truly fault-tolerant systems. It can be used for writing highly fault-tolerant sys-tems that self-heal and never stop.

Akka has many configuration options and features. Some of those fea-tures are mentioned in this report. The FSM -functionality is addressed asa way to implement state machines in section 4.2.2. The Akka dataflow -functionality is mentioned as a possible way to realize asynchronous proce-dures in section 4.5. An Akka feature called test kit is used as an actor testtool in the implementation of a toy example shown in this report.

Akka performance and scalability

The Akka documentation [14] does claim that Akka actors can be seen asvery light-weight processes and this is also backed up by Horstman [6]. Hemakes a comparison between actor implementations with lightweight actorssuch as Akka and Scala actors, against Java threads. A computer thatsupports only a few thousand concurrent threads before the JVM runs outof memory, can support millions or even tens of millions of concurrent actors.

A practical evaluation between threads, thread based actors and eventbased actors in Scala is made by Haller and Odersky [4]. They note thatthe JVM has some deficiencies when it comes to concurrency, namely lowmaximum number of threads and high context-switch overhead. They doconclude that using event-based model for actors dramatically increases theefficiency and scalability compared both to thread based actors and imple-mentation made by using bare threads directly.

One thing to note here is that Akka makes use of an event-based modelfor its actors. The actors used in the comparison by Haller and Odersky, isthe basis for the Scala actor library - the library that as earlier mentionedis replaced by Akka.

The use of Akka in this thesis

This thesis builds on the precondition that Akka actors in highly scalableand enables the development of highly concurrent programs. The perfor-mance properties of Akka are assumed to be correct and are not investigatedfurther, besides referring to the statements made by others in this section(2.2.4).

The major focus point on Akka in this thesis is on how to use andincorporate Akka and if some or any of the features of Akka is relevant inthe thesis context.

15

Page 32: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 2. TECHNOLOGY INTRODUCTIONS

2.3 Introductions to state machines

As mentioned in Erlang/OTP design principles manual[2], many applica-tions can be modeled as FSMs. Protocol stacks are such an example.

If we define S as the current state of a system, E as a trigger event,A as an action to take and S′ as some next state, a state machine can bedescribed as a set of relations of the form:

S x E → A, S′

The meaning of this set of relations are that specific state event combi-nations (S x E) results in an action A and the system makes a transition tothe state S′. In other words - If we are in state S and the event E occurs, weshould perform the action A and S′ becomes the new state of the system.

There are more formal definitions of state machines, but such defini-tions are not needed in the context of this thesis. UML-notation is used tographically represent state machines in this thesis report, as in figure 4.1.

2.3.1 What are state machines used for?

“I use them in all levels of a system, from controlling the high-level GUI to the lowest-level communication protocols. They arealmost universally applicable.” - Robert C. Martin [8, p. 419]

As mentioned earlier, state machines can be used to implement protocolstacks. Another, frequently mentioned in literature, use of state machinesis in graphical user interfaces (GUI).

Inversion of control

A common denominator for these uses is the inversion of control (IOC).Both a state machine used in a communication protocol and a state machineused in a GUI are triggered by events produced by some other entity. Inshort - the control of the current state has been handed over to some otherexternal entity that triggers the events in the state machine - hence theinversion of control.

Haller et al.[4] states that most programming models support event-driven programming only through inversion of control and says the following:

“Virtually all approaches based on inversion of control sufferfrom the following two problems: First, the interactive logic of aprogram is fragmented across multiple event handlers (or classes,as in the state design pattern). Second, control flow amonghandlers is expressed implicitly through manipulation of sharedstate.”

16

Page 33: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

2.3. INTRODUCTIONS TO STATE MACHINES

One interpretation of what Haller et al. says is that because the separa-tion in time between triggered events in an event-based system, the controlflow needs to be divided up in separate pieces of code, where the separatepieces of code manipulates some shared state (control data).

As an extension of this - the use of state machines can be seen as anabstract concept to overcome the complexities in event-driven mechanismsand can also be seen as a development tool to specify program logic in anevent-driven system.

An example of IOC and shared state

One Java program related example is requiring a user to enter a value bytyping it the Java console / terminal and reading the value via System.in.Requiring a value via System.in is a blocking operation in Java, but thecontrol flow of the program can be written as one long sequential and syn-chronous piece of code.

An alternative and more event-driven way is to use multiple Java Swingbutton and register an action listener in each button. The program logicto be triggered when a button is pressed is hidden in the listener registeredin the button. The use of the buttons and the listeners are not blocking,but the control is handed over to the event mechanisms hidden within thebuttons.

In the System.in version of the problem, only one value can be entered inthe terminal if the program is written as such. In the Swing button version,multiple buttons can be pressed in sequence. One way to hinder the userfrom triggering multiple program control snippets is to use a state sharedby all button listeners. The shared state can then signal whether button isalready pressed or not.

17

Page 34: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

Chapter 3

Investigation of currentsolution

The investigation of the current solution is based on an interview with thethesis supervisor Mattias Evensson, who in this case is regarded as thedomain expert.

The purpose of the interview is to, at an early stage, establish a sharedview of the thesis problem and the objectives. The original questions andanswers of the interview can be seen in appendix A. This section presents asummary of the interview and the conclusions made based on the answersgiven.

3.1 Common traits of the protocols

A specific real world example of a protocol is given as a representative ex-ample. It is a protocol that is both hard to work with and do containsome properties that are representative for the type of protocols that theygenerally work with at Xdin:

• The protocols contain some few states that can be regarded as thestable states in the protocol. These states are the general modes ofoperation. In contrast to these stable states, there are states that areintermediate states in an ongoing transition procedure between thestable states. The intermediate transition states are in this reportcalled transition states.

• The protocols contain procedures of several states in sequence, usedas transition between the basic states.

• The protocols contain just three different events OK, TIMEOUT andFAIL.

18

Page 35: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

3.2. GRAPHIC VISUALIZATION OF PROGRAM LOGIC AS A STATEMACHINE

• The procedures to execute in transition between the basic states canin turn make use of sub procedures.

3.2 Graphic visualization of program logic asa state machine

The protocol specification documentation does contain graphical represen-tations of the protocols. There is no need for state machine visualization,especially if an implementation to a large extent resembles the specification.

The takeaway here is that it can be regarded as a good thing if theimplementation implemented does resemble the specification of the protocol.

3.3 Problems with the current solution

As mentioned earlier in the report, the current solution involves the task ofgraphically represent the protocol implementation as a state machine in adevelopment tool called UniMod. There might be some shortcomings relatedto the specific tool, but there is also an intrinsic problem with using statemachines, and thereby also representing them graphically.

The problem is that there is, what in the investigation is called, a stateexplosion in the transition procedures between the basic states. The reasonfor the state explosion is not explained further in the appended investigation,but some likely explanations are:

• Optional transition steps increasing the number of sub procedures.

• Error handling requiring tear down of partially applied transition pro-cedures, leading to a lot of states just to handle the error handling.

3.4 Technical solutions of interest and limita-tions

Some limitations (or requirements) on these protocol implementations comesfrom the context they are used in. The protocol implementations are used insimulation tools that simulate thousands of concurrent entities, all simulatedentities using some protocols.

This implies that performance and scalability are of great importance.Earlier experience shows that it is not possible to use one thread per en-tity1. The solution must run multiple simulated entities per JVM threadand thereby an entity cannot do anything that blocks the JVM tread (e.g.blocking asynchronous communication), because the blocking operation willaffect other entities using the same thread.

1The abbreviation UE (user equipment) is used in the investigation answers.

19

Page 36: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 3. INVESTIGATION OF CURRENT SOLUTION

There are some technical concepts that might lead to interesting solutionsto these problems:

• The Akka actor framework and possibly use of the Akka FSM func-tionality. As mentioned in the technical introduction on the Akkaframework in section 2.2.4, using Akka actors is assumed to solve theperformance and scalability problems for protocols implementationsin the simulation context.

• The use of continuations to enable the description of protocol proce-dures containing asynchronous calls as sequential procedures programcode. This is what in this thesis report is defined as asynchronousprocedure (AP).

3.5 Focus on the developer

By judging from the answers in the interview, the problem is not so muchthe functionality of the current representation, but the problem seems ratherto be that the current representation is hard to handle from a developerperspective. Some interpretations can be made from the information in theinvestigation.

One interpretation is that the development process is of importance whenworking with the protocol implementations. One example from the investi-gation answers is the need to be able to incrementally develop and improvethe protocol implementation. A more specific example is the emphasis oftesting in the development process and that the current type of represen-tation leads problems when testing the implementation. The investigationindicates that the current type of protocol representation makes unit testingunnecessary complicates and slow.

Another interpretation is that making procedures containing asynchronouscalls look like sequential procedures is thought to make the implementationof the protocol easier to handle. In other words - it is thought to be easierfor a developer to write and reason about an AP than breaking up a pro-cedure specification into multiple states in a state machine or some otherrepresentation using inversion of control.

20

Page 37: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

Chapter 4

Investigation of possibletechniques

This chapter focuses on the investigations needed to get a good foundationfor the other parts of the thesis work.

The investigations focuses on roughly three things - ways to representstate machines, how to use timers and schedulers in the performance tooldomain and how to actually represent asynchronous procedures.

The different ways to represent state machines are further divided up incommon ways, special Scala way and special Akka ways to represent statemachines.

4.1 Generic SM implementations

There are several common ways to represent state machines in programcode, i.e. implementations techniques. Four common types of implemen-tations techniques for state machines are listed in the book Agile SoftwareDevelopement by Robert Martin [8]. These are briefly explained in thesesections.

4.1.1 Example state machine

To help illustrate the different techniques a simple example is constructedand used in large parts of this chapter. The example is a state machinerepresenting a ballpoint pen. The ballpoint pen has a button to click, re-tracting or protracting the ballpoint tip, depending on the current state.With a ballpoint pen you can try to write things, but it will only disperseink in one of its two states. Table 4.1 shows the transition table for a ball-point pen state machine and figure 4.1 shows the state transition diagramfor the same.

21

Page 38: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 4. INVESTIGATION OF POSSIBLE TECHNIQUES

Table 4.1: Transition table for ballpoint pen state machine

State Event Next state Action

Protractedclick Retracted retractwrite Protracted disperse ink

Retractedclick Protracted protractwrite Retracted do nothing

RetractedRetracted ProtractedProtractedclick / protract

click / retract

write / do nothing write / disperse ink

Figure 4.1: State transition diagram for a ballpoint pen

Commonalities, interfaces and separation of concerns

The Scala code that is reused in all implementations for the different ball-point pen state machine representation examples can be seen in listing 4.1.The states in the State object and events in the Event object are the samein all types of state machine representations, besides in the state patternrepresentation. In the state pattern representation the state machine statesare represented by separate classes.

The abstract class BallpointPenController is used to completely sepa-rate the ballpoint pen state machine logic from the actions to make in eachtransition. The point here is that the state machine logic becomes com-pletely separated from the application area it is used in. As long as a statemachine has access to concrete instance of a BallpointPenController inter-face, the state machine does not need to know whether the actions just areprinted in a text file log or used to control a real pen.

The same idea works in the other direction for the usage of the abstractclass BallpointPen, which represents the interface to the Ballpoint pen statemachine. Here, the code that makes use of a state machine does not need tocare which type of representation the state machine uses, because all statemachines uses the same interface.

A bonus of separating the state machine logic from the application areait is used in, is that it makes the state machine logic easy to test becauseno application code need to be involved.

22

Page 39: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

4.1. GENERIC SM IMPLEMENTATIONS

Code listing 4.1: Enumerations and abstract classes common to all Ballpointpen state machine implementations.

showspacesshowspacesshowspacesshowspaces showspaces1 package commonshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 object State extends Enumeration {showspacesshowspaces showspaces4 val protracted , r e t r a c t e d = Valueshowspacesshowspaces showspaces5 }showspacesshowspaces showspaces6

showspacesshowspaces showspaces7 object Event extends Enumeration {showspacesshowspaces showspaces8 val c l i c k , wr i t e = Valueshowspacesshowspaces showspaces9 }showspacesshowspaces showspaces10

showspacesshowspaces showspaces11 abstract class Bal lpo in tPenCont ro l l e r {showspacesshowspaces showspaces12 def pro t r a c t ( ) : Unitshowspacesshowspaces showspaces13 def r e t r a c t ( ) : Unitshowspacesshowspaces showspaces14 def doNothing ( ) : Unitshowspacesshowspaces showspaces15 def d i s p e r s e I n k ( ) : Unitshowspacesshowspaces showspaces16 }showspacesshowspaces showspaces17

showspacesshowspaces showspaces18 abstract class Bal lpo intPen (showspacesshowspaces showspaces19 val ac t i on : Ba l lpo in tPenCont ro l l e r ) {showspacesshowspaces showspaces20

showspacesshowspaces showspaces21 def r ec i eveEvent ( event : Event . Value ) : Unitshowspacesshowspaces showspaces22 }showspacesshowspaces

4.1.2 Nested match/case implementation

This type of implementation is originally called a nested switch/case imple-mentation, but in the context of Scala nested match/case implementation isa more suitable name.

The idea behind the nested match/case implementation is that there aretwo levels of nested match/case blocks, one level for the current state andone level for the current event. Listing 4.2 shows what this can look like forthe ballpoint pen state machine implemented in Scala. In this code, eachsecond level case corresponds to a separate transition in the state transitiondiagram in figure 4.1.

The support for pattern matching in match/case expressions in Scalaenables a one-level match/case block for tuples of state and event. This canbe seen in listing 4.3.

Martin [8, p. 424] states that for simple state machines, the nestedmatch/case implementation is both elegant and efficient. Martin state how-ever, that for larger state machines the code devolves into page after pageof case statements, which can be very difficult and error-prone to maintain.

23

Page 40: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 4. INVESTIGATION OF POSSIBLE TECHNIQUES

Code listing 4.2: Ballpoint pen state machine as a nested match/case imple-mentation in Scala.

showspacesshowspacesshowspacesshowspaces showspaces1 package nestedmatchcaseshowspacesshowspaces showspaces2 import common .showspacesshowspaces showspaces3

showspacesshowspaces showspaces4 trait NestedMatchCasePen extends Bal lpo intPen {showspacesshowspaces showspaces5 var s t a t e = State . r e t r a c t e dshowspacesshowspaces showspaces6

showspacesshowspaces showspaces7 def r ec i eveEvent ( event : Event . Value ) {showspacesshowspaces showspaces8 s t a t e = s t a t e match {showspacesshowspaces showspaces9

showspacesshowspaces showspaces10 case State . r e t r a c t e d =>showspacesshowspaces showspaces11 event match {showspacesshowspaces showspaces12

showspacesshowspaces showspaces13 case Event . c l i c k =>showspacesshowspaces showspaces14 ac t i on . p ro t r a c t ( )showspacesshowspaces showspaces15 State . p ro t rac t edshowspacesshowspaces showspaces16

showspacesshowspaces showspaces17 case Event . wr i t e =>showspacesshowspaces showspaces18 ac t i on . doNothing ( )showspacesshowspaces showspaces19 s t a t e // no state changeshowspacesshowspaces showspaces20 }showspacesshowspaces showspaces21

showspacesshowspaces showspaces22 case State . p ro t rac t ed =>showspacesshowspaces showspaces23 event match {showspacesshowspaces showspaces24

showspacesshowspaces showspaces25 case Event . c l i c k =>showspacesshowspaces showspaces26 ac t i on . r e t r a c t ( )showspacesshowspaces showspaces27 State . r e t r a c t e dshowspacesshowspaces showspaces28

showspacesshowspaces showspaces29 case Event . wr i t e =>showspacesshowspaces showspaces30 ac t i on . d i s p e r s e I n k ( )showspacesshowspaces showspaces31 s t a t e // no state changeshowspacesshowspaces showspaces32 }showspacesshowspaces showspaces33 }showspacesshowspaces showspaces34 }showspacesshowspaces showspaces35 }showspacesshowspaces

4.1.3 Transition table

Listing 4.4 shows a transition table implementation for the ballpoint penstate machine in figure 4.1.

This implementation technique is based on a data table that describesthe transitions. This table is interpreted by an engine that handles theevents. The engine looks up the transition that matched the event, invokesthe appropriate action, and changes the state.

One advantages of the transition table technique is that it is easier tomaintain compared to the nested match/case implementation. Another ad-vantage is that, depending on the implementation, the table can be pro-

24

Page 41: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

4.1. GENERIC SM IMPLEMENTATIONS

Code listing 4.3: Ballpoint pen state machine, as a state and event tuplematch/case implementation in Scala.

showspacesshowspacesshowspacesshowspaces showspaces1 package tuplematchcaseshowspacesshowspaces showspaces2 import common .showspacesshowspaces showspaces3

showspacesshowspaces showspaces4 trait TupleMatchCasePen extends Bal lpo intPen {showspacesshowspaces showspaces5 var s t a t e = State . r e t r a c t e dshowspacesshowspaces showspaces6

showspacesshowspaces showspaces7 def r ec i eveEvent ( event : Event . Value ) {showspacesshowspaces showspaces8 import State . , Event .showspacesshowspaces showspaces9

showspacesshowspaces showspaces10 ( s ta te , event ) match {showspacesshowspaces showspaces11 case ( ‘ r e t rac t ed ‘ , ‘ c l i c k ‘ ) =>showspacesshowspaces showspaces12 ac t i on . r e t r a c t ( )showspacesshowspaces showspaces13 s t a t e = State . r e t r a c t e dshowspacesshowspaces showspaces14

showspacesshowspaces showspaces15 case ( ‘ protracted ‘ , ‘ c l i c k ‘ ) =>showspacesshowspaces showspaces16 ac t i on . p ro t r a c t ( )showspacesshowspaces showspaces17 s t a t e = State . p ro t rac t edshowspacesshowspaces showspaces18

showspacesshowspaces showspaces19 case ( ‘ r e t rac t ed ‘ , ) => ac t i on . doNothing ( )showspacesshowspaces showspaces20

showspacesshowspaces showspaces21 case => ac t i on . d i s p e r s e I n k ( )showspacesshowspaces showspaces22 }showspacesshowspaces showspaces23 }showspacesshowspaces showspaces24 }showspacesshowspaces

grammatically altered at runtime, allowing dynamic alteration of the logicof the state machine.

There can be speed costs associated with this approach. If the tablelookup time is not constant, it takes time to search through the transitiontable. According to Martin [8, p. 425] this time may become significant fora large state machine.

4.1.4 The state pattern

Martin [8, p. 426] states that the state pattern combines the efficiency of thenested match/case statement with the flexibility of interpreting a transitiontable. It is a object oriented design pattern, that uses a state-interface anddifferent concrete realizations to represent different states. Each realizationof the state interface can then implement their own behaviors for each event,resulting in different behaviors in different states.

Figure 4.2 illustrates the state pattern in its generic form. Listing 4.5and figure 4.3 shows how the state pattern can be implemented in Scala, forthe ballpoint pen state machine.

25

Page 42: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 4. INVESTIGATION OF POSSIBLE TECHNIQUES

Code listing 4.4: Ballpoint pen state machine as a transition table imple-mentation in Scala.

showspacesshowspacesshowspacesshowspaces showspaces1 // −−−− Code spec i f ic to the ballpoint pen state machine −−−−showspacesshowspaces showspaces2

showspacesshowspaces showspaces3 package t r a n s i t i o n t a b l eshowspacesshowspaces showspaces4 import common .showspacesshowspaces showspaces5

showspacesshowspaces showspaces6 trait Transit ionTablePen extends Bal lpo intPen {showspacesshowspaces showspaces7 import Event . , State . , a c t i on .showspacesshowspaces showspaces8

showspacesshowspaces showspaces9 def t r a n s i t i o n T a b l e = L i s t (showspacesshowspaces showspaces10 Trans i t i on ( protracted , c l i c k , r e t rac t ed , r e t r a c t ) ,showspacesshowspaces showspaces11 Trans i t i on ( r e t rac t ed , c l i c k , protracted , p ro t r a c t ) ,showspacesshowspaces showspaces12 Trans i t i on ( protracted , write , protracted , d i s p e r s e I n k ) ,showspacesshowspaces showspaces13 Trans i t i on ( r e t rac t ed , write , r e t rac t ed , doNothing ) )showspacesshowspaces showspaces14

showspacesshowspaces showspaces15 val eng ine = Trans i t ionEngine ( t r a n s i t i o n T a b l e )showspacesshowspaces showspaces16 var s t a t e = r e t r a c t e dshowspacesshowspaces showspaces17

showspacesshowspaces showspaces18 def r ec i eveEvent ( event : Event . Value ) {showspacesshowspaces showspaces19 s t a t e = engine . p roce s s ( s ta te , event )showspacesshowspaces showspaces20 }showspacesshowspaces showspaces21 }showspacesshowspaces showspaces22

showspacesshowspaces showspaces23 // −−−− Generic and reusable code for other state machines −−−−showspacesshowspaces showspaces24

showspacesshowspaces showspaces25 case class Trans i t i on [ S , E ] (showspacesshowspaces showspaces26 cu r r en tS ta t e : S , event : E,showspacesshowspaces showspaces27 nextState : S , a c t i on : ( ) => Unit )showspacesshowspaces showspaces28

showspacesshowspaces showspaces29 case class Trans i t ionEngine [ S , E ] (showspacesshowspaces showspaces30 t ab l e : L i s t [ Trans i t i on [ S , E ] ] ) {showspacesshowspaces showspaces31

showspacesshowspaces showspaces32 def proce s s ( s t a t e : S , event : E) : S = {showspacesshowspaces showspaces33 val t r an s i t i onOpt i on = ta b l e f i n dshowspacesshowspaces showspaces34 { t => t . event == event && t . cu r r en tS ta t e == s t a t e }showspacesshowspaces showspaces35

showspacesshowspaces showspaces36 t r an s i t i onOpt i on match {showspacesshowspaces showspaces37 case Some( t r a n s i t i o n ) =>showspacesshowspaces showspaces38 t r a n s i t i o n . a c t i on ( )showspacesshowspaces showspaces39 t r a n s i t i o n . nextStateshowspacesshowspaces showspaces40

showspacesshowspaces showspaces41 case None =>showspacesshowspaces showspaces42 throw new RuntimeException ( ” State−event combination ” +showspacesshowspaces showspaces43 ”%s−%s not found in ta b l e ! ” . format ( s ta te , event ) )showspacesshowspaces showspaces44 }showspacesshowspaces showspaces45 }showspacesshowspaces showspaces46 }showspacesshowspaces

Some words about design patterns

Gamma et al. [3, p. 2] addresses the state pattern and other patterns inparticular and design patterns in OOP in general. They describe design

26

Page 43: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

4.1. GENERIC SM IMPLEMENTATIONS

Code listing 4.5: Ballpoint pen state machine, as a state pattern implemen-tation in Scala.

showspacesshowspacesshowspacesshowspaces showspaces1 package s t a t e p a t t e r nshowspacesshowspaces showspaces2 import common .showspacesshowspaces showspaces3

showspacesshowspaces showspaces4 abstract class State {showspacesshowspaces showspaces5 def wr i t e ( ac t i on : Ba l lpo in tPenCont ro l l e r ) : Stateshowspacesshowspaces showspaces6 def c l i c k ( ac t i on : Ba l lpo in tPenCont ro l l e r ) : Stateshowspacesshowspaces showspaces7 }showspacesshowspaces showspaces8

showspacesshowspaces showspaces9 object RetractedState extends State {showspacesshowspaces showspaces10

showspacesshowspaces showspaces11 def c l i c k ( ac t i on : Ba l lpo in tPenCont ro l l e r ) = {showspacesshowspaces showspaces12 ac t i on . p ro t r a c t ( )showspacesshowspaces showspaces13 Prot rac tedStateshowspacesshowspaces showspaces14 }showspacesshowspaces showspaces15

showspacesshowspaces showspaces16 def wr i t e ( ac t i on : Ba l lpo in tPenCont ro l l e r ) = {showspacesshowspaces showspaces17 ac t i on . doNothing ( )showspacesshowspaces showspaces18 thisshowspacesshowspaces showspaces19 }showspacesshowspaces showspaces20 }showspacesshowspaces showspaces21

showspacesshowspaces showspaces22 object Prot rac tedState extends State {showspacesshowspaces showspaces23

showspacesshowspaces showspaces24 def c l i c k ( ac t i on : Ba l lpo in tPenCont ro l l e r ) = {showspacesshowspaces showspaces25 ac t i on . r e t r a c t ( )showspacesshowspaces showspaces26 RetractedStateshowspacesshowspaces showspaces27 }showspacesshowspaces showspaces28

showspacesshowspaces showspaces29 def wr i t e ( ac t i on : Ba l lpo in tPenCont ro l l e r ) = {showspacesshowspaces showspaces30 ac t i on . d i s p e r s e I n k ( )showspacesshowspaces showspaces31 thisshowspacesshowspaces showspaces32 }showspacesshowspaces showspaces33 }showspacesshowspaces showspaces34

showspacesshowspaces showspaces35 trait StatePatternPen extends Bal lpo intPen {showspacesshowspaces showspaces36 var s t a t e : State = RetractedStateshowspacesshowspaces showspaces37

showspacesshowspaces showspaces38 def r ec i eveEvent ( event : Event . Value ) =showspacesshowspaces showspaces39 s t a t e = event match {showspacesshowspaces showspaces40 case Event . c l i c k => s t a t e . c l i c k ( ac t i on )showspacesshowspaces showspaces41 case Event . wr i t e => s t a t e . wr i t e ( ac t i on )showspacesshowspaces showspaces42 }showspacesshowspaces showspaces43 }showspacesshowspaces

patterns as

“Each pattern describes a problem which occurs over and overagain in our environment, and then describes the core of thesolution to that problem, in such a way that you can use this

27

Page 44: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 4. INVESTIGATION OF POSSIBLE TECHNIQUES

state

<<interface>>State

handle()

Context

request()

S1

handle()

S2

handle()

Figure 4.2: The state pattern

state

action

<<interface>>State

write(BallpointPen)click(BallpointPen)

BallpointPen

write()click()

<<interface>>BallpointPenController

protract()retract()doNothing()disperseInk()

RetractedState

write(BallpointPen)click(BallpointPen)

ProtractedState

write(BallpointPen)click(BallpointPen)

Figure 4.3: Class diagram for the ballpoint pen state machine implementedas state pattern

solution a million times over, without ever doing it the sameway twice”

28

Page 45: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

4.1. GENERIC SM IMPLEMENTATIONS

Generally, a design pattern is a conceptual idea on how to organize somecode to solve a particular and reoccurring problem. In that sense, also nestedmatch/case and transition table can be regarded as design patterns.

4.1.5 The state machine compiler

Code listing 4.6: Ballpoint pen state machine in a made up example defini-tion format DSL used by some state machine compiler.

showspacesshowspacesshowspacesshowspaces showspaces1 context Bal lpo intPenshowspacesshowspaces showspaces2 c o n t r o l l e r Ba l lpo in tPenCont ro l l e rshowspacesshowspaces showspaces3 i n i t i a l S t a t e Retractedshowspacesshowspaces showspaces4

showspacesshowspaces showspaces5 s t a t e Retracted {showspacesshowspaces showspaces6 c l i c k Protracted p ro t r a c tshowspacesshowspaces showspaces7 wr i t e Retracted doNothingshowspacesshowspaces showspaces8 }showspacesshowspaces showspaces9

showspacesshowspaces showspaces10 s t a t e Protracted {showspacesshowspaces showspaces11 c l i c k Retracted r e t r a c tshowspacesshowspaces showspaces12 wr i t e Protracted d i s p e r s e I n kshowspacesshowspaces showspaces13 }showspacesshowspaces

Martin [8] mentions a fourth technique for implementing state machines.He calls this technique state machine compiler and it is in short a way togenerate program code for the state machine implementation from a defini-tion file, instead of writing the needed program code manually.

According to Martin [8, p. 431], the benefit of using state machinecompiler is that the logic of the state machine is strongly isolated fromthe implementation of the actions and the compact definition requires aminimum of coding. Martin also states that the cost is in the use of statemachine compiler, where you have to learn and use another developmenttool and a definition language.

In the example of the ballpoint state machine this could be realized by(1) defining the state machine in a definition file, (2) generate the Scalacode with the state machine compiler tool and as a last step (3) create aimplementation of the BallpointPenController interface in some class morebound to the application context.

Listing 4.6 is an example of how such a state machine definition can looklike for the ballpoint pen state machine. The output Scala code of such adefinition run through a state machine compiler can then look just as thestate pattern in listing 4.5 or any other of the techniques mentioned in thereport.

Using a state machine compiler can also incorporate other state machinerelated tools that are out of scope for an ordinary Scala development en-

29

Page 46: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 4. INVESTIGATION OF POSSIBLE TECHNIQUES

vironment or any other programming language development environment.Examples of such state machine related tools are validation of that the statemachine is minimal, that all states are reachable from all other states (i.e. noacyclic parts in the state machine) and other constraints that the developerwant to apply to the state machine.

4.2 Akka specific SM implementations

This section covers some different ways to combine actors and state ma-chines. The connection between actors and state machines might not beas obvious at first, but is as a matter of fact so closely connected that theAkka actor framework documentation mentions two different solutions tointegrate the two.

Section 4.2.1 shows one of the solutions mentioned in the Akka docu-mentation. It is to use two methods available in all Akka actors - become

and unbecome.Section 4.2.2 shows the other way mentioned in the Akka documentation.

The solution mentioned is to use the explicitly defined FSM trait as a mixinin the targeted actor.

A possible rationale for the emphasis on state machines in the Akkalibrary documentation can be that the asynchronous nature of actors andthe message passing between actors marries very well with the state machineconcept, as a tool for logic representation. The state machine enables theactor to change its behavior in the context of multiple messages. The statesmachine event and the actor message can to some extent be seen as the samething in two separate technology domains.

To get a complete image that covers all aspects of combining actors andstate machines, a third way is investigated. Section 4.2.3 is added to showhow to combine an actor with a completely separate state machine. Thisalso shows that the actor and state machine can be loosely coupled anddo not need to be tightly integrated with each other, in order to use statemachines in the actor domain.

4.2.1 Actor methods become and unbecome

Code listing 4.7 shows an example implementation where the ballpoint penstate machine is implemented as an actor using the become method in givenActorContext class.

Code listing 4.8 shows one way to adapt the state machine interface toa concrete actor implementation. In this case the class AkkaBecomePen, thatconcrete class that implements the BallpointPen state machine interface,acts as an adapter to the actor BecomeActor.

30

Page 47: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

4.2. AKKA SPECIFIC SM IMPLEMENTATIONS

Code listing 4.7: Ballpoint pen state machine, implemented as an actorchanging behavior with become method.

showspacesshowspacesshowspacesshowspaces showspaces1 package akkabecomeshowspacesshowspaces showspaces2 import common .showspacesshowspaces showspaces3 import akka . ac to r .showspacesshowspaces showspaces4

showspacesshowspaces showspaces5 /∗∗ Actor with the two behaviors protracted and retracted . ∗/showspacesshowspaces showspaces6 class BecomeActor ( ac t i on : Ba l lpo in tPenCont ro l l e r ) extends Actorshowspacesshowspaces showspaces{showspacesshowspaces showspaces7 import context .showspacesshowspaces showspaces8

showspacesshowspaces showspaces9 def prot rac t ed : Receive = {showspacesshowspaces showspaces10 case Event . c l i c k =>showspacesshowspaces showspaces11 ac t i on . r e t r a c t ( )showspacesshowspaces showspaces12 become ( r e t r a c t e d )showspacesshowspaces showspaces13

showspacesshowspaces showspaces14 case Event . wr i t e =>showspacesshowspaces showspaces15 ac t i on . d i s p e r s e I n k ( )showspacesshowspaces showspaces16 }showspacesshowspaces showspaces17

showspacesshowspaces showspaces18 def r e t r a c t e d : Receive = {showspacesshowspaces showspaces19 case Event . c l i c k =>showspacesshowspaces showspaces20 ac t i on . p ro t r a c t ( )showspacesshowspaces showspaces21 become ( pro t rac t ed )showspacesshowspaces showspaces22

showspacesshowspaces showspaces23 case Event . wr i t e =>showspacesshowspaces showspaces24 ac t i on . doNothing ( )showspacesshowspaces showspaces25 }showspacesshowspaces showspaces26

showspacesshowspaces showspaces27 def r e c e i v e = r e t r a c t e d // <−− i n i t i a l behaviorshowspacesshowspaces showspaces28 }showspacesshowspaces

Code listing 4.8: Adapter between a ballpoint pen state machine (instance ofclass BallpointPen) and the BecomeActor actor.

showspacesshowspacesshowspacesshowspaces showspaces30 /∗∗ Adapter between BallpointPen and the BecomeActor. ∗/showspacesshowspaces showspaces31 trait AkkaBecomePen extends Bal lpo intPen {showspacesshowspaces showspaces32

showspacesshowspaces showspaces33 val pen = {showspacesshowspaces showspaces34 val system = ActorSystem . c r e a t e ( )showspacesshowspaces showspaces35 val props = Props (new BecomeActor ( ac t i on ) )showspacesshowspaces showspaces36 system . actorOf ( props )showspacesshowspaces showspaces37 }showspacesshowspaces showspaces38

showspacesshowspaces showspaces39 def r ece iveEvent ( event : Event . Value ) = pen ! eventshowspacesshowspaces showspaces40 }showspacesshowspaces

31

Page 48: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 4. INVESTIGATION OF POSSIBLE TECHNIQUES

Stack multiple behaviors

Actor using the become functionality also has the functionality to stack multi-ple behaviors given by the become method and remove the topmost behaviorwith method unbecome.

In the example implementation in listing 4.7, this could be realized byreplacing become(retracted) at line 12 with unbecome and overriding thedefault argument to discard old behaviors1 in become(protracted) at line 21with the method call become(protracted,false).

A possible pitfall

A possible pitfall with overriding the default behavior to discard old behav-iors and instead combining the methods become with the method unbecome

is that the actor can store an excessive amount of behaviors and eventuallythe JVM gets into memory trouble.

A little test has been conducted to verify that this pitfall is real if notcareful to also remove stacked behaviors with the unbecome method. Anactor gets the behavior to send a message to itself. Each time the messageis received, the current behavior is stored on the behavior stack with a callto become and a new message is sent to itself. This creates a loop that forcesthe actor behavior stack to grow indefinitely.

The Scala program is executed on a computer with the OpenJDK 64-BitServer VM JVM, the Scala code runner version 2.9.2, Akka version 2.0.4and an option is given to the JVM that specifies that the maximum size ofthe memory allocation pool is 7000 MB.

After around 2.5 minutes and 120,000,000 calls to the become method,the computer starts to really walk on its knees. All approximately 7 gigabyteof memory given to the JVM is used up and further iterations are done ina much slower pace than it started with.

4.2.2 Akka FSM implementation

The functionality given by the Akka trait akka.actor.FSM is specifically cre-ated to facilitate state machines directly in actors. The code listing 4.9 givesan example how this could be done for the ballpoint pen state machine.

Compared to using the become/unbecome solution, the FMS trait alsohas some extra features available to ease the development of state machines,such as specifying state timeouts and to carry data between states. TheAkka documentation [14] describes all features in details.

When looking in the source code of file akka.actor.FSM.scala in the Akkalibrary version 2.0.4, I draw the conclusion that the FMS functionality isimplemented as an ordinary actor, but does not explicitly make use of thebecome/unbecome functionality. The FMS implementation keeps all partialfunctions added with the when-method in a map with the given state as a

1Given by the default boolean argument value true

32

Page 49: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

4.2. AKKA SPECIFIC SM IMPLEMENTATIONS

Code listing 4.9: Ballpoint pen state machine, implemented as an actorspecifically using the akka.actor.FSM trait as an actor mixin.

showspacesshowspacesshowspacesshowspaces showspaces1 package akkafsmshowspacesshowspaces showspaces2 import common .showspacesshowspaces showspaces3 import akka . ac to r .showspacesshowspaces showspaces4

showspacesshowspaces showspaces5 class FsmActor ( ac t i on : Ba l lpo in tPenCont ro l l e r )showspacesshowspaces showspaces6 extends Actor with FSM[ State . Value , Unit ] {showspacesshowspaces showspaces7 import common . State . , common . Event .showspacesshowspaces showspaces8 val noData = Unitshowspacesshowspaces showspaces9

showspacesshowspaces showspaces10 startWith ( r e t rac t ed , noData )showspacesshowspaces showspaces11

showspacesshowspaces showspaces12 when( pro t rac t ed ) {showspacesshowspaces showspaces13 case Event ( ‘ c l i c k ‘ , ) =>showspacesshowspaces showspaces14 ac t i on . r e t r a c t ( )showspacesshowspaces showspaces15 goto ( r e t r a c t e d )showspacesshowspaces showspaces16

showspacesshowspaces showspaces17 case Event ( ‘ write ‘ , ) =>showspacesshowspaces showspaces18 ac t i on . d i s p e r s e I n k ( )showspacesshowspaces showspaces19 s tayshowspacesshowspaces showspaces20 }showspacesshowspaces showspaces21

showspacesshowspaces showspaces22 when( r e t r a c t e d ) {showspacesshowspaces showspaces23 case Event ( ‘ c l i c k ‘ , ) =>showspacesshowspaces showspaces24 ac t i on . p ro t r a c t ( )showspacesshowspaces showspaces25 goto ( pro t rac t ed )showspacesshowspaces showspaces26

showspacesshowspaces showspaces27 case Event ( ‘ write ‘ , ) =>showspacesshowspaces showspaces28 ac t i on . doNothing ( )showspacesshowspaces showspaces29 s tayshowspacesshowspaces showspaces30 }showspacesshowspaces showspaces31 }showspacesshowspaces

map key, and is therefore not vulnerable to the same problem as become/un-become can be.

4.2.3 Composition of state machine and actor

This section does not show any Akka specific state machine functionality.It only shows that the composition of a state machine and an actor can bedone in a loosely coupled manner, where the actual SM implementation isinjected into the actor as a constructor argument. Listing 4.10 shows anexample on how this can be done.

This separation of actor and behavior logic can facilitate more special-ized or specific types of SM representations. The separation enables thebehavior logic representation to be more directed to the specific usage areathan generic Akka SM representations using become method or the FSM trait

33

Page 50: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 4. INVESTIGATION OF POSSIBLE TECHNIQUES

Code listing 4.10: Ballpoint pen state machine, implemented as an actorcomposed with an dependency injected state machine implementation.

showspacesshowspacesshowspacesshowspaces showspaces7 /∗∗ Actor , where state machine i s injected via constructor . ∗/showspacesshowspaces showspaces8 class ComposedActor ( fsm : Bal lpo intPen ) extends Actor {showspacesshowspaces showspaces9 def r e c e i v e = { case event : Value => fsm . rece iveEvent ( event ) }showspacesshowspaces showspaces10 }showspacesshowspaces

mentioned in sections 4.2.1 and 4.2.3.Examples of when separation can be convenient is when one of the generic

types of representations mentioned in section 4.1 is found to be easier to workwith, than the ones given by the Akka framework. Perhaps the separationof actor and state machine helps the developer in some way such as e.g.testing.

Examples of more specialized types of behavior logic are given in section4.3 - state machine implementations enabled by the Scala programminglanguage - and in section 4.5 - asynchronous procedures. These sectionsshow representations that can be more directed to the usage area of thebehavior logic.

4.3 Scala specific SM implementations

This section focuses on functionality in the Scala programming languagethat can be of an advantage when implementing state machines. As it turnsout, there are Scala features that can help when representing state machines,but the features are not restricted to only be used when implementing statemachines.

This section will mostly deal with the concept of domain specific lan-guages (DSL). This concept is not limited to Scala, but Scala happens tohave some capabilities that make two different kinds of DSL easy to use.

In the scope of this section, the focus is on how Scala features can helpthe implementation of state machines. This focus area serves as a goodexample on how to use domain specific languages. However, one thing tonote is that the Scala DSL features are general and can also help to leverageother parts of the protocol representations in this thesis.

4.3.1 Domain specific languages

In this context, a domain specific language is a programming language tai-lored to suite terms, expression and idioms of a specific domain or subject.

The book Programming Scala [15, ch. 11] states the following four ben-efits of using a well-designed DSL compared to using a plain programmingapproach without using a DSL:

34

Page 51: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

4.3. SCALA SPECIFIC SM IMPLEMENTATIONS

• Implementation detail encapsulation

• Developer effort efficiency

• Improved communication between stakeholders, such as developersand domain experts.

• Increasing implementation quality by reducing the need for extensivetranslation between feature requirements and implementation sourcecode.

Programming Scala [15, ch. 11] also mentions some drawbacks withDSLs. These drawbacks are mostly the difficulty to capture the details ofthe domain in the DSL and to cope with maintenance when the domainmodeled in the DSL changes.

4.3.2 Internal DSL

Scala enables something called internal DSLs via some features in the Scalalanguage. One interpretation of the prefix internal, is that Scala has featuresthat let the developer create structures (classes, methods, implicit conver-sions, operator overloading2 and more) that lets Scala code look like anotherlanguage. A good example of this is Baysick3, an internal DSL in Scala thatis made to look like the Basic programming language.

Ballpoint pen state machine as an internal DSL

As a context related example, an internal DSL created for the state machinedomain. All types of transitions can be seen in code listing 4.11. Theintention is that the DSL should look like text interpretations of hand drawntransitions. It is built up with, among other things a State class that hasfour operator-like methods that takes either a event or another state asargument. The methods are ---, -*-, -?-> and -?-/-. These methods, intheir turn, return some type with other operator-like methods. Using someimagination, the combination of these methods ends up looking like somekind of transition arrows between states.

Listing 4.12 uses the state machine DSL to implement a state machinefor the ballpoint pen example mentioned in section 4.1.

A more advanced example - PIN code lock

The ballpoint pen example is not a very large and advanced example. Ithas two states, two events and therefore a maximum of four state-eventcombinations.

2Scala does not actually have operator overloading, because operators are methods inScala.

3More information can be found at http://www.scala-lang.org/node/1403 and http:

//blog.fogus.me/2009/03/26/baysick-a-scala-dsl-implementing-basic/. Both sitesaccessed 2013-03-05.

35

Page 52: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 4. INVESTIGATION OF POSSIBLE TECHNIQUES

Code listing 4.11: An example of how an internal DSL for SMs can looklike.

showspacesshowspacesshowspacesshowspaces showspaces1 // Ordinary transition with action .showspacesshowspaces showspaces2 s t a t e −−− event −/− ac t i on −−> nextStateshowspacesshowspaces showspaces3

showspacesshowspaces showspaces4 // Ordinary transition without action .showspacesshowspaces showspaces5 s t a t e −−− event −−> nextStateshowspacesshowspaces showspaces6

showspacesshowspaces showspaces7 // Recursive transition with action .showspacesshowspaces showspaces8 s t a t e −∗− event −/− ac t i onshowspacesshowspaces showspaces9

showspacesshowspaces showspaces10 // Recursive transition without action .showspacesshowspaces showspaces11 s t a t e −∗− eventshowspacesshowspaces showspaces12

showspacesshowspaces showspaces13 // Default behaviour when the transitionshowspacesshowspaces showspaces14 // ( i . e . state−event combination) i s not defined .showspacesshowspaces showspaces15 s t a t e −?−> nextStateshowspacesshowspaces showspaces16

showspacesshowspaces showspaces17 // Default behaviour with a defined action .showspacesshowspaces showspaces18 s t a t e −?−/− ac t i on −−> nextStateshowspacesshowspaces

A more advanced example is a PIN code lock, with a ten digit numerickey pad and pin codes of length four. Another feature of the PIN code lockis that the user must use the code both when locking and unlocking thelock. The logic behind PIN code lock requires eight states and ten differentevents - one event for each digit pressed. This leads to a total of 80 differentstate-event combinations to take care of in an implementation.

Code listing 4.13 shows a definition of all events and actions for the PINcode lock. Code listing 4.14 shows the implementation of the state machine.

Here follow some indications of advantages to the developer, given bythis specific DSL and the implementation of the PIN code lock in listing4.14:

• Using some kind of object instance to uniquely identify different states,enables the states to be used as arguments to other Scala methods.As it is done here, the basic states locked and unlocked can easily besent as arguments to the correctPinCode method. This method helpsto build up a more advanced structure of intermediate states as a partof the transition between the basic states. In this specific example,eight states are created because the method correctPinCode is calledtwice.

This ability to programmatically structure the creation of a state ma-chine can be a big advantage in large state machines. As it is repre-sented in this DSL, the state instances in the resulting state machineare represented in a completely flat hierarchy, but the Scala code that

36

Page 53: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

4.3. SCALA SPECIFIC SM IMPLEMENTATIONS

Code listing 4.12: Ballpoint pen state machine implemented with an internaldomain specific language (DSL) for state machines.

showspacesshowspacesshowspacesshowspaces showspaces1 package i n t e r n a l d s lshowspacesshowspaces showspaces2 import common .showspacesshowspaces showspaces3

showspacesshowspaces showspaces4 trait Interna lDs lPen extends Bal lpo intPen {showspacesshowspaces showspaces5

showspacesshowspaces showspaces6 import ds l s ta temach ine .{ State => DslState }showspacesshowspaces showspaces7 import ds l s ta temach ine . StateMachineshowspacesshowspaces showspaces8 import common . Event .showspacesshowspaces showspaces9

showspacesshowspaces showspaces10 val fsm = {showspacesshowspaces showspaces11 def s t a t e = DslState [ Value ]showspacesshowspaces showspaces12 val r e t r a c t e d = s t a t e ( ” b a l l p o i n t pen i s r e t r a c t e d ” )showspacesshowspaces showspaces13 val prot rac t ed = s t a t e ( ” b a l l p o i n t pen i s p ro t rac t ed ” )showspacesshowspaces showspaces14

showspacesshowspaces showspaces15 r e t r a c t e d −−− c l i c k −/− ac t i on . p ro t r a c t −−> prot rac t edshowspacesshowspaces showspaces16 prot rac t ed −−− c l i c k −/− ac t i on . r e t r a c t −−> r e t r a c t e dshowspacesshowspaces showspaces17

showspacesshowspaces showspaces18 r e t r a c t e d −∗− wr i t e −/− ac t i on . doNothingshowspacesshowspaces showspaces19 prot rac t ed −∗− wr i t e −/− ac t i on . d i s p e r s e I n kshowspacesshowspaces showspaces20

showspacesshowspaces showspaces21 StateMachine ( r e t r a c t e d )showspacesshowspaces showspaces22 }showspacesshowspaces showspaces23

showspacesshowspaces showspaces24 def r ece iveEvent ( event : Value ) = fsm . t r i g g e r ( event )showspacesshowspaces showspaces25 }showspacesshowspaces

Code listing 4.13: Pin code lock events and actions definition.

showspacesshowspacesshowspacesshowspaces showspaces1

showspacesshowspaces showspaces2 object PinKeyEvent extends Enumeration {showspacesshowspaces showspaces3 val key0 , key1 , key2 , key3 , key4 , key5 , key6 , key7 , key8 , key9showspacesshowspaces showspaces= Valueshowspacesshowspaces showspaces4 }showspacesshowspaces showspaces5

showspacesshowspaces showspaces6 abstract class PinLockContro l l e r ( ) {showspacesshowspaces showspaces7 def l o ck ( )showspacesshowspaces showspaces8 def unlock ( )showspacesshowspaces showspaces9 }showspacesshowspaces

creates the state machine can be structured with the help of all codestructure and organization concepts built into the Scala language, suchas methods, objects and packages.

• Normally, as for the actor using the FSM trait in listing 4.9 amongothers, the state machine definitions tend to focus on the current state

37

Page 54: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 4. INVESTIGATION OF POSSIBLE TECHNIQUES

and group together all events that can happen in that state.

This state machine DSL can be regarded as centered on each individ-ual transition to make between states. The developer can still clusterall transitions from a specific state together, but it enables the de-veloper to also group the transitions in any way the developer findsadvantageous. Examples are the cluster of transitions on lines 40-43,47-48 and 51-54 in code listing 4.14. These transition clusters aregrouped together based on other premises than that they originatefrom a common source state.

• Another advantage is that the state machine representations using theexample DSL (i.e. listings 4.12 and 4.14) seem to be fairly compactcompared to some other types of state machine representations suchas using the state pattern or Akka FSM trait in listings 4.5 and 4.9respectively.

4.3.3 External DSL

An external domain specific language encapsulates the same concepts asusing an internal domain specific language. The purpose is to tailor somekind of representation to reflect the targeted domain.

The large differences between internal and external domain specific lan-guages are that an internal DSL in fact is Scala code that is made to lookand work in a certain way. On the other hand, an external DSL is not Scalacode at all, but instead an arbitrary language format that might be intendedto be parsed by some Scala program. One example of an external DSL is infact the made up state definition format in listing 4.6.

The Scala standard library provides some tools called parser combi-nators. The parser combinators are found in standard library packagescala.util.parsing.combinator. As the name indicates, these combinatorscan be combined to create a complete parser for some input format. Thecreated parser can for instance be designed to generate an abstract syntaxtree from a given source.

In the context of state machines, the external DSL tools given by Scalastandard library are in fact just a convenient way to realize a state machinecompiler, mentioned in section 4.1.5.

38

Page 55: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

4.3. SCALA SPECIFIC SM IMPLEMENTATIONS

Code listing 4.14: Pin code lock state machine implemented with an internaldomain specific language (DSL) for state machines.

showspacesshowspacesshowspacesshowspaces showspaces11 object PinLock {showspacesshowspaces showspaces12

showspacesshowspaces showspaces13 import PinKeyEvent .showspacesshowspaces showspaces14 import ds l s ta temach ine . StateMachineshowspacesshowspaces showspaces15 import ds l s ta temach ine . Stateshowspacesshowspaces showspaces16 type Action = ( ) => Unitshowspacesshowspaces showspaces17 type S = State [ PinKeyEvent . Value ]showspacesshowspaces showspaces18 type SM = StateMachine [ PinKeyEvent . Value ]showspacesshowspaces showspaces19

showspacesshowspaces showspaces20 def apply ( ac t i on : PinLockContro l l e r ) : SM = {showspacesshowspaces showspaces21

showspacesshowspaces showspaces22 // the basic statesshowspacesshowspaces showspaces23 val l ocked = new S( ” locked ” )showspacesshowspaces showspaces24 val unlocked = new S( ” unlocked ” )showspacesshowspaces showspaces25

showspacesshowspaces showspaces26 // transcend between basic states when pin code i s correctshowspacesshowspaces showspaces27 correctPinCode ( locked , unlocked , ac t i on . unlock )showspacesshowspaces showspaces28 correctPinCode ( unlocked , locked , ac t i on . l o ck )showspacesshowspaces showspaces29 StateMachine ( locked )showspacesshowspaces showspaces30 }showspacesshowspaces showspaces31

showspacesshowspaces showspaces32 def correctPinCode ( s t a r t : S , f i n i s h : S , a c t i on : Action ) = {showspacesshowspaces showspaces33

showspacesshowspaces showspaces34 // intermediate states between start and f inishshowspacesshowspaces showspaces35 val ok1 = new S( ”1 s t d i g i t c o r r e c t ” )showspacesshowspaces showspaces36 val ok2 = new S( ”2nd d i g i t c o r r e c t ” )showspacesshowspaces showspaces37 val ok3 = new S( ”3 rd d i g i t c o r r e c t ” )showspacesshowspaces showspaces38

showspacesshowspaces showspaces39 // the correct code i s 8879showspacesshowspaces showspaces40 s t a r t −−− key8 −−>showspacesshowspaces showspaces41 ok1 −−− key8 −−>showspacesshowspaces showspaces42 ok2 −−− key7 −−>showspacesshowspaces showspaces43 ok3 −−− key9 −/− ac t i on −−> f i n i s hshowspacesshowspaces showspaces44

showspacesshowspaces showspaces45 // i f key i s wrong at (current state ) but at theshowspacesshowspaces showspaces46 // same time the f i r s t digits ( s ) in the correct sequenceshowspacesshowspaces showspaces47 ok2 −−− key8 −−> ok2showspacesshowspaces showspaces48 ok3 −−− key8 −−> ok1showspacesshowspaces showspaces49

showspacesshowspaces showspaces50 // start over i f transition i s not expl ic i t ly definedshowspacesshowspaces showspaces51 s t a r t −?−> s t a r tshowspacesshowspaces showspaces52 ok1 −?−> s t a r tshowspacesshowspaces showspaces53 ok2 −?−> s t a r tshowspacesshowspaces showspaces54 ok3 −?−> s t a r tshowspacesshowspaces showspaces55 }showspacesshowspaces showspaces56 }showspacesshowspaces

39

Page 56: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 4. INVESTIGATION OF POSSIBLE TECHNIQUES

4.4 How to delay, take time and schedule

This section explores the different ways to delay, take time and scheduletasks in Scala and Akka and in this section, some concrete types of timekeeping are compared to each other.

In the scope of this thesis - implementation of asynchronous protocol -one potential usage area for this knowledge is to be able to trigger timeoutswhen there is no interaction between asynchronously communicating enti-ties. A use case is that a message response is expected to be received withina certain time limit and some fault handling should be done if the time limitis not kept.

One of the preconditions related to this thesis work is that there canexist more protocol instances than the number of threads that the JVM cansustain. This generates some criteria on the time keeping mechanisms used.The criteria for the time keeping mechanisms are that they cannot block aJava thread and they cannot spawn a new Java thread for each time task.

4.4.1 Delay test bench evaluation

A Scala-based test bench is constructed and used in order to be able tocompare the different ways to keep time. Some of the ways of keeping timeare features in the Akka library, and the complete test bench is thereforecentered on keeping time withing actors.

The conceptual idea of the test bench is that a dedicated test executionactor creates a number of delay actors. The delay actors will more or lessat the same time receive a message token that should be delayed a certainnumber of milliseconds and then resent back to the test execution actor. Alldelay actors implement one of the techniques under investigation.

The idea is to use so many actors at the same time in a test, that if thetested technique happens to block the running Java threads, it will affect theother delay actors running in the same threads. Thereby, tests conductedwith techniques that block Java threads will clearly stand out, because itwill result in some delay actors taking notably longer time than expected.

The token to pass around

Most part of the test bench Scala code is omitted in this thesis report.However, some parts are included to both show how the delay actors workand how the different techniques can be used.

The token to be passed from and to the delay actors can be seen in listing4.15. The token both contains the start time when the token is sent awayto the delay actor. The start time enables the execution actor to calculatethe actual delay of the token message, when token is received from delayactor. The delay duration value in the token tells the delay actor how longthe token should be delayed.

40

Page 57: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

4.4. HOW TO DELAY, TAKE TIME AND SCHEDULE

Code listing 4.15: Delay test bench message token

showspacesshowspacesshowspacesshowspaces showspaces1 sealed trait TestMessageshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 case class TestToken ( s t a r t : Long , de lay : Long )showspacesshowspaces showspaces4 extends TestMessageshowspacesshowspaces

Abstract delay actors

Some of the delay actors have much in common and does therefore extend acommon abstract delay actor just for convenience. The AbstractDelayActor

class in listing 4.16 is one of the abstract delay actors used in the tests. Itis a generic delay actor with a abstract delay method. The other abstractdelay actor is the class AbstractAkkaFsmActor in listing 4.17. It focuses onfeatures in the Akka FSM trait and is therefore more specialized.

Code listing 4.16: Delay test bench class AbstractDelayActor

showspacesshowspacesshowspacesshowspaces showspaces1 import akka . ac to r .showspacesshowspaces showspaces2

showspacesshowspaces showspaces3 abstract class AbstractDelayActor extends Actor {showspacesshowspaces showspaces4

showspacesshowspaces showspaces5 def delay (ms : Long ) ( delayedExpr : => Unit ) : Unitshowspacesshowspaces showspaces6

showspacesshowspaces showspaces7 def r e c e i v e = {showspacesshowspaces showspaces8 case token : TestToken =>showspacesshowspaces showspaces9 val replyToActor = sendershowspacesshowspaces showspaces10 delay ( token . de lay ) { replyToActor ! token }showspacesshowspaces showspaces11 }showspacesshowspaces showspaces12 }showspacesshowspaces

4.4.2 Immediate response with no delay (ND)

To be able to determine how much the test bench in itself affects the result,a delay actor that only makes an immediate response instead of doing anactual delay is included. It can be seen in code listing 4.18.

4.4.3 Thread sleep (TS)

To explicitly do a thread sleep is the obvious anti-solution to this problem.Listing 4.19 shows a usage example.

41

Page 58: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 4. INVESTIGATION OF POSSIBLE TECHNIQUES

Code listing 4.17: Delay test bench class AbstractAkkaFsmActor

showspacesshowspacesshowspacesshowspaces showspaces1 import s c a l a . concurrent . durat ion . DurationLongshowspacesshowspaces showspaces2 import s c a l a . concurrent . durat ion . F in i t eDurat ionshowspacesshowspaces showspaces3

showspacesshowspaces showspaces4 import akka . ac to r .showspacesshowspaces showspaces5

showspacesshowspaces showspaces6 abstract class AbstractAkkaFsmActorshowspacesshowspaces showspaces7 extends Actor with FSM[ Str ing , Option [ ( ) => Unit ] ] {showspacesshowspaces showspaces8

showspacesshowspaces showspaces9 val timeoutEvent : Anyshowspacesshowspaces showspaces10 def delay ( durat ion : F in i t eDurat ion ) ( s t a t e : State ) : Stateshowspacesshowspaces showspaces11

showspacesshowspaces showspaces12 when( ” i d l e ” ) {showspacesshowspaces showspaces13 case Event ( token : TestToken , None ) =>showspacesshowspaces showspaces14 val rep lyTarget = sendershowspacesshowspaces showspaces15 def delayedExpr ( ) = { rep lyTarget ! token }showspacesshowspaces showspaces16

showspacesshowspaces showspaces17 delay ( token . de lay m i l l i s e c o n d s ) {showspacesshowspaces showspaces18 goto ( ” act iveTimer ” ) us ing Some( delayedExpr )showspacesshowspaces showspaces19 }showspacesshowspaces showspaces20 }showspacesshowspaces showspaces21

showspacesshowspaces showspaces22 when( ” act iveTimer ” ) {showspacesshowspaces showspaces23 case Event ( ‘ timeoutEvent ‘ , Some( delayedExpr ) ) =>showspacesshowspaces showspaces24 delayedExpr ( ) // execute the expressionshowspacesshowspaces showspaces25 goto ( ” i d l e ” ) us ing Noneshowspacesshowspaces showspaces26 }showspacesshowspaces showspaces27

showspacesshowspaces showspaces28 startWith ( ” i d l e ” , None )showspacesshowspaces showspaces29 i n i t i a l i z eshowspacesshowspaces showspaces30 }showspacesshowspaces

Code listing 4.18: Delay actor with no delay (ND)

showspacesshowspacesshowspacesshowspaces showspaces1 f ina l class ImmediateResponseActor extends AbstractDelayActor {showspacesshowspaces showspaces2 // Ignore delay , just evaluate delayed expressionshowspacesshowspaces showspaces3 def delay (ms : Long ) ( delayedExpr : => Unit ) = delayedExprshowspacesshowspaces showspaces4 }showspacesshowspaces

4.4.4 Java utility timer (GJT and LJT)

There exists a Timer utility in the Java system library that can be used. Ac-cording to Java 6 documentation [10], there is a one-to-one relation betweentimer and Java threads. Therefore two different tests are conducted withclass java.util.Timer. One of the delay actors (GlobalJavaUtilTimerTaskActor)makes use of a single global timer instance. The other delay actor(LocalJavaUtilTimerTaskActor) creates a local timer instance for each cre-

42

Page 59: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

4.4. HOW TO DELAY, TAKE TIME AND SCHEDULE

Code listing 4.19: Delay actors using Thread.sleep

showspacesshowspacesshowspacesshowspaces showspaces1 f ina l class JavaThreadSleepActor extends AbstractDelayActor {showspacesshowspaces showspaces2 def delay (ms : Long ) ( delayedExpr : => Unit ) = {showspacesshowspaces showspaces3 Thread . s l e e p (ms)showspacesshowspaces showspaces4 delayedExprshowspacesshowspaces showspaces5 }showspacesshowspaces showspaces6 }showspacesshowspaces

ated actor. Both actors can be seen in listing 4.20.

Code listing 4.20: Delay actors using java.util.Timer

showspacesshowspacesshowspacesshowspaces showspaces1 import java . u t i l . TimerTaskshowspacesshowspaces showspaces2 import java . u t i l . Timershowspacesshowspaces showspaces3 import JavaUti lTimer .showspacesshowspaces showspaces4

showspacesshowspaces showspaces5 object JavaUti lTimer {showspacesshowspaces showspaces6 val t imer = new Timer ( )showspacesshowspaces showspaces7

showspacesshowspaces showspaces8 implicit def exprToTimerTask ( expr : => Unit ) =showspacesshowspaces showspaces9 new TimerTask ( ) { def run ( ) = expr }showspacesshowspaces showspaces10 }showspacesshowspaces showspaces11

showspacesshowspaces showspaces12 class GlobalJavaUtilTimerTaskActor extends AbstractDelayActor {showspacesshowspaces showspaces13 def delay (ms : Long ) ( delayedExpr : => Unit ) =showspacesshowspaces showspaces14 t imer . s chedu le ( delayedExpr , ms)showspacesshowspaces showspaces15 }showspacesshowspaces showspaces16

showspacesshowspaces showspaces17 class LocalJavaUti lTimerTaskActor extends AbstractDelayActor {showspacesshowspaces showspaces18 def delay (ms : Long ) ( delayedExpr : => Unit ) =showspacesshowspaces showspaces19 new Timer ( ) . s chedu le ( delayedExpr , ms)showspacesshowspaces showspaces20 }showspacesshowspaces

4.4.5 Akka scheduler (AS)

The Akka library has a scheduler that can be utilized. Listing 4.21 showshow this can be done in actor AkkaSchedulerActor.

4.4.6 Akka FSM state timeout (FSMSTO)

The Akka FSM trait has the ability to generate a message of type StateTimeout

when there is no message received within some time limit. How this can beused is shown in actor AkkaFsmStateTimeoutActor in listing 4.22.

43

Page 60: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 4. INVESTIGATION OF POSSIBLE TECHNIQUES

Code listing 4.21: Delay actors using Akka scheduler

showspacesshowspacesshowspacesshowspaces showspaces1 import s c a l a . concurrent . durat ion . DurationLongshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 f ina l class AkkaSchedulerActor extends AbstractDelayActor {showspacesshowspaces showspaces4 import context .showspacesshowspaces showspaces5

showspacesshowspaces showspaces6 def delay (ms : Long ) ( delayedExpr : => Unit ) =showspacesshowspaces showspaces7 context . system . s chedu l e r .showspacesshowspaces showspaces8 scheduleOnce (ms m i l l i s e c o n d s ) ( delayedExpr )showspacesshowspaces showspaces9 }showspacesshowspaces

Code listing 4.22: Delay actors using Akka FMS state timeout

showspacesshowspacesshowspacesshowspaces showspaces1 import s c a l a . concurrent . durat ion . F in i t eDurat ionshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 f ina l class AkkaFsmStateTimeoutActorshowspacesshowspaces showspaces4 extends AbstractAkkaFsmActor {showspacesshowspaces showspaces5

showspacesshowspaces showspaces6 val timeoutEvent = this . StateTimeoutshowspacesshowspaces showspaces7

showspacesshowspaces showspaces8 def delay ( durat ion : F in i t eDurat ion ) ( s t a t e : State ) =showspacesshowspaces showspaces9 s t a t e forMax ( durat ion )showspacesshowspaces showspaces10 }showspacesshowspaces

4.4.7 Akka FSM timers (FSMT)

Code listing 4.23: Delay actors using Akka FSM timers

showspacesshowspacesshowspacesshowspaces showspaces1 import s c a l a . concurrent . durat ion . F in i t eDurat ionshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 f ina l class AkkaFsmTimerActor extends AbstractAkkaFsmActor {showspacesshowspaces showspaces4

showspacesshowspaces showspaces5 val timeoutEvent = ”myTimeoutEvent”showspacesshowspaces showspaces6 val myTimer = ”myDelayTimer”showspacesshowspaces showspaces7 val noRepeat = fa l seshowspacesshowspaces showspaces8

showspacesshowspaces showspaces9 def delay ( durat ion : F in i t eDurat ion ) ( s t a t e : State ) : State = {showspacesshowspaces showspaces10 setTimer (myTimer , timeoutEvent , durat ion , noRepeat )showspacesshowspaces showspaces11 s t a t eshowspacesshowspaces showspaces12 }showspacesshowspaces showspaces13 }showspacesshowspaces

The Akka FSM trait has the ability to set multiple generic timers iden-

44

Page 61: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

4.4. HOW TO DELAY, TAKE TIME AND SCHEDULE

Code listing 4.24: Delay actors using Akka receive timeout

showspacesshowspacesshowspacesshowspaces showspaces1 import s c a l a . concurrent . durat ion . Durationshowspacesshowspaces showspaces2 import s c a l a . concurrent . durat ion . DurationLongshowspacesshowspaces showspaces3

showspacesshowspaces showspaces4 import akka . ac to r .showspacesshowspaces showspaces5

showspacesshowspaces showspaces6 class AkkaRecieveTimeoutActor extends Actor {showspacesshowspaces showspaces7 import context .showspacesshowspaces showspaces8

showspacesshowspaces showspaces9 def i d l e : Rece ive = {showspacesshowspaces showspaces10 case token : TestToken =>showspacesshowspaces showspaces11 setReceiveTimeout ( token . de lay m i l l i s e c o n d s )showspacesshowspaces showspaces12 become ( a c t i v e ( sender , token ) )showspacesshowspaces showspaces13 }showspacesshowspaces showspaces14

showspacesshowspaces showspaces15 def a c t i v e ( t a r g e t : ActorRef , token : TestToken ) : Receive = {showspacesshowspaces showspaces16 case ReceiveTimeout =>showspacesshowspaces showspaces17 t a r g e t ! tokenshowspacesshowspaces showspaces18 setReceiveTimeout ( Duration . Undefined ) // no more timeoutshowspacesshowspaces showspaces19 become ( i d l e )showspacesshowspaces showspaces20 }showspacesshowspaces showspaces21

showspacesshowspaces showspaces22 def r e c e i v e = i d l eshowspacesshowspaces showspaces23 }showspacesshowspaces

tified with string names. According to the Akka documentation [14], thesenamed timers complement state timeouts because they are not affected byintervening reception of other messages. Also, these timers can be canceledusing the method call cancelTimer(name) which is guaranteed to work im-mediately. How this can be used is shown in actor AkkaFsmTimerActor inlisting 4.23.

4.4.8 Akka receive timeout (RTO)

This generic feature of all Akka actors resembles the Akka FSM state timeout,to a large extends. Actor AkkaRecieveTimeoutActor in listing 4.24 shows howthis can be used.

4.4.9 Future with ask timeout (FTO)

Both Scala and Akka contain the concept of a Future. It can be regardedas a placeholder for a not yet given result - i.e. a placeholder for a futureresult.

The delay actor example in listing 4.25 may look a little bit convoluted,because the delay actor AkkaFutureTimeoutActor asks itself a question thatit do not answer. This should trigger a timeout exception that can be used

45

Page 62: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 4. INVESTIGATION OF POSSIBLE TECHNIQUES

Code listing 4.25: Delay actors using Future with ask timeout

showspacesshowspacesshowspacesshowspaces showspaces1 import s c a l a . concurrent . durat ion . DurationLongshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import akka . pattern . AskTimeoutExceptionshowspacesshowspaces showspaces4 import akka . pattern . askshowspacesshowspaces showspaces5 import akka . u t i l . Timeout . durationToTimeoutshowspacesshowspaces showspaces6

showspacesshowspaces showspaces7 class AkkaFutureTimeoutActor extends AbstractDelayActor {showspacesshowspaces showspaces8 import context .showspacesshowspaces showspaces9

showspacesshowspaces showspaces10 val t imeoutQuest ion = ” He l lo ?”showspacesshowspaces showspaces11 val doNothing = ( )showspacesshowspaces showspaces12

showspacesshowspaces showspaces13 override def r e c e i v e = super . r e c e i v e o rE l s e {showspacesshowspaces showspaces14 case t imeoutQuest ion => doNothingshowspacesshowspaces showspaces15 }showspacesshowspaces showspaces16

showspacesshowspaces showspaces17 def delay (ms : Long ) ( de layed : => Unit ) =showspacesshowspaces showspaces18 ask ( s e l f , t imeoutQuest ion ) (ms m i l l i s e c o n d s ) . onFa i lure {showspacesshowspaces showspaces19 case : AskTimeoutException => delayedshowspacesshowspaces showspaces20 }showspacesshowspaces showspaces21 }showspacesshowspaces

as a timer.

4.4.10 Future with Await.result (FAR)

An instance of a future is not in itself blocking Java threads, but waiting forthe result using Await.result is blocking according to the Akka documen-tation [14].

The actor in listing 4.26 should block the Java thread while waiting on aAskTimeoutException. This technique, explicitly waiting for a future result,is taken into account in this investigation just to ensure that it actually is abad technique.

4.4.11 Comparison

All different techniques are run in the delay test bench with an expecteddelay of 1 000 milliseconds (1 second). The tests are run on a desktopcomputer that at the time of writing (and test execution) can be regardedto have a reasonable performance.

Each test conducted makes use of a specific quantity of concurrentlyexecuted delay actors. All actors make use of the same delay technique.Each delay actor in a test gets a token message to delay. The actual delaysfor all message tokens are measured and collected. Both a mean delay value

46

Page 63: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

4.4. HOW TO DELAY, TAKE TIME AND SCHEDULE

Code listing 4.26: Delay actors using Future with Await.result

showspacesshowspacesshowspacesshowspaces showspaces1 import java . u t i l . concurrent . TimeoutExceptionshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import s c a l a . concurrent . Awaitshowspacesshowspaces showspaces4 import s c a l a . concurrent . durat ion . DurationLongshowspacesshowspaces showspaces5

showspacesshowspaces showspaces6 import akka . pattern . askshowspacesshowspaces showspaces7 import akka . u t i l . Timeout . durationToTimeoutshowspacesshowspaces showspaces8

showspacesshowspaces showspaces9 class AkkaFutureAwait extends AbstractDelayActor {showspacesshowspaces showspaces10 import context .showspacesshowspaces showspaces11

showspacesshowspaces showspaces12 val t imeoutQuest ion = ” He l lo ?”showspacesshowspaces showspaces13 val doNothing = ( )showspacesshowspaces showspaces14

showspacesshowspaces showspaces15 override def r e c e i v e = super . r e c e i v e o rE l s e {showspacesshowspaces showspaces16 case t imeoutQuest ion => doNothingshowspacesshowspaces showspaces17 }showspacesshowspaces showspaces18

showspacesshowspaces showspaces19 def delay (ms : Long ) ( de layed : => Unit ) = {showspacesshowspaces showspaces20 val f u tu r e = ask ( s e l f , t imeoutQuest ion ) (10 ∗ ms m i l l i s e c o n d sshowspacesshowspaces showspaces)showspacesshowspaces showspaces21 try {showspacesshowspaces showspaces22 Await . r e s u l t ( future , ms m i l l i s e c o n d s )showspacesshowspaces showspaces23 } catch {showspacesshowspaces showspaces24 case : TimeoutException => delayedshowspacesshowspaces showspaces25 }showspacesshowspaces showspaces26 }showspacesshowspaces showspaces27 }showspacesshowspaces

and a max delay value in milliseconds are calculated, based on all tokenmessage delays in a test. The mean value is rounded to whole milliseconds.

Table 4.2 shows three different delay techniques. The first technique(ND) shows the intrinsic delays in the delay test bench when used on thetest computer. The table shows that the test system in itself introducessignificant delays when using 10 000 and 20 000 concurrent delay actors. Forthis reason no test makes use of more than 20 000 actors.

The second technique in table 4.2 shows the delays when using a globalinstance of the java.util.Timer class (GJT). This technique shows the bestdelay performance of all techniques up to around 10 000 concurrent delayactors and then seems to fall behind when using 20 000 concurrent delayactors.

The second technique in table 4.2 shows the delays when using the Akkascheduler (AS). The delay values for the Akka scheduler are also represen-tative for some of the other techniques - Akka FSM timer (FSMT), AkkaFSM state timeout (FSMSTO), Akka receive timeout (RTO) and the use offuture timeout (FT).

47

Page 64: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 4. INVESTIGATION OF POSSIBLE TECHNIQUES

Table 4.2: Delay in milliseconds, for different quantities of concurrent delayactors using three different techniques - no delay (ND), global timer (GJT)and Akka scheduler (AS).

no delay (ND) global timer (GJT) Akka scheduler (AS)quantity mean max mean max mean max

100 0 0 1 001 1 001 1 101 1 101200 0 0 1 001 1 001 1 093 1 101500 10 10 1 001 1 001 1 079 1 101

1 000 16 20 1 003 1 011 1 070 1 1012 000 25 40 1 008 1 021 1 206 1 2925 000 67 112 1 033 1 074 1 066 1 160

10 000 198 382 1 097 1 274 1 121 1 30320 000 600 1 370 1 583 2 301 1 380 1 990

Table 4.3: Delay in milliseconds, for different quantities of concurrent delayactors using Java thread sleep (TS).

quantity mean max10 1 002 1 01120 1 401 2 00150 4 042 5 002

100 8 041 9 001200 16 041 17 001

As expected, the use of Thread.sleep generates delays that deviate con-siderably from the expected delay of 1 000 milliseconds. This can be seenin table 4.3. The actual resulting delays follow the number of delay actorsalmost linearly. The mean and max values follow each other quite closely,and this can be a sign of that the delay actors not only interfere with eachother, but also blocks the test execution actor thread, since the executionactor thread is one of the threads the Akka actor system uses for all actors.

The techniques using local instances of java.util.Thread (LJT) and theuse of Await.result (FAR) are both expected to perform badly in the testbench. They do not perform as badly as the use of Thread.sleep (TS), butdo still perform notably worse than most of the other techniques.

As seen in table 4.4, these two techniques seems to perform worse forthe quantity of 5 000 concurrent delay actors than for a quantity of 10 000concurrent delay actors. I find no apparent explanation for this behavior.This behavior is reproduced when the test bench is run multiple times - evenwhen the relative order between tests of different techniques is rearranged inthe test bench. However, one conclusion than can be made is that these twotechniques do worse than many of the other techniques for large quantitiesof concurrent delay actors.

As a comparison between different delay-techniques, table 4.5 and 4.6

48

Page 65: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

4.4. HOW TO DELAY, TAKE TIME AND SCHEDULE

Table 4.4: Delay in milliseconds, for different quantities of concurrent delayactors using two different techniques - local timer (LJT) and future await(FAR).

local timer (LJT) future await (FAR)quantity mean max mean max

1 000 1 029 1 061 1 041 1 1112 000 1 070 1 150 1 113 1 2855 000 7 073 7 966 132 051 132 920

10 000 1 317 1 644 2 376 4 42020 000 2 320 3 102 182 048 183 032

Table 4.5: Delay in milliseconds, for different techniques for the specificquantity of 1 000 concurrent delay actors.

delay technique mean maxno delay (ND) 16 20

global timer (GJT) 1 003 1 011local timer (LJT) 1 029 1 061

future await result (FAR) 1 041 1 111Akka scheduler (AS) 1 070 1 101

future timeout (FTO) 1 092 1 101Akka FSM timer (FSMT) 1 100 1 107

Akka FSM state timeout (FSMSTO) 1 101 1 101Akka recieve timeout (RTO) 1 200 1 202

Table 4.6: Delay in milliseconds, for different techniques for the specificquantity of 20 000 concurrent delay actors.

delay technique mean maxno delay (ND) 600 1370

Akka FSM timer (FSMT) 1 328 1 864Akka FSM state timeout (FSMSTO) 1 331 1 862

Akka scheduler (AS) 1 380 1 990Akka recieve timeout (RTO) 1 404 2 042

future timeout (FTO) 1 412 2 100global timer (GJT) 1 583 2 301

local timer (LJT) 2 320 3 102future await result (FAR) 182 048 183 032

49

Page 66: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 4. INVESTIGATION OF POSSIBLE TECHNIQUES

show compilations of all techniques for specific quantities of concurrent delayactors. Table 4.5 shows the comparison for 1 000 concurrent delay actors,while table 4.6 shows the comparison for 20 000 concurrent delay actors.The techniques are ordered by their mean delay. The use of Java threadsleep (TS) is not included in these tables.

Given the data collected in the test, it seems like there are several vi-able alternatives to choose from. It seems that the Akka related techniquesFSMT, FSMSTO, AS and RTO have more or less equal performance, butmay differ in suitable usage area. Using a global Java timer (GJT) seems tohave the best accuracy of all up to a specific limit of concurrent timer tasks.Techniques not to use are LJT, FAR and TS.

4.5 Asynchronous Procedures

As stated in the terminology definition for AP in section 1.7 the intendedmeaning and usage is to represent consecutive asynchronous calls to otherentities in some representation that in a way resembles synchronous com-munication by hiding the asynchronous implementation details.

Question 3 in the initial investigation interview (see appendix A) showshow such an AP could look like in pseudo code:

def myProcedure() {

try {

send(new SetupLowerLayerReq());

resp = receive();

if (resp.result == FAIL)

throw new FailureException();

send(new MessageReq);

resp = receive();

if (resp.result == FAIL)

throw new FailureException();

} catch (TimeoutException | FailureException) {

send(new TeardownLowerLayerReq());

resp = receive();

}

}

This procedure pseudo code makes use of the two functions send andreceive as functions to send and receive asynchronous messages withoutneeding to deal with the time delay between a call to send and the resultreturned from a call to receive. The intention of this pseudo code is alsothat it does not block the underlying Java thread while waiting to receivethe response message.

50

Page 67: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

4.5. ASYNCHRONOUS PROCEDURES

The hallmark of AP One thing can be identified in the pseudo code, inan effort to formalize what is sought after in an AP. The AP needs to haltthe execution when requiring a response by calling the receive function.

Expressed in more general terms, the sought functionality of an AP isthat the AP should halt the execution and in some way store the currentexecution state when some kind of input is required or expected. The ex-ecution of the AP should be continued when input is given at some laterpoint in time. The following pseudo code tries to visualize what is soughtafter:

def asynchronousProcedure() {

expression1

input

expression2

input

expression3

}

The pseudo code is synchronous looking, but the execution is halted intwo places, before expression2 and expression3, when input is expected.

Concrete technologies I have found two different candidate technolo-gies to use when implementing AP. One technology is an API in the Akkaframework that is called dataflow. The dataflow API, do in its turn make useof the Scala support for delimited continuations. The other technology forrealizing AP is to directly use the Scala support for delimited continuations,in a concept that in this thesis report will be called thunk procedure.

Realizing AP via thunk procedures require heavy use of the Scala supportfor delimited continuations. Therefore will section 4.5.1 give an introductionto continuations in Scala, while section 4.5.2 and 4.5.3 deals with dataflowand thunk procedures respectively.

The section about continuation is just a brief introduction to the de-limited continuations used in Scala, in the context of implementing AP. Irecommend the book Scala for the Impatient [6] for a pedagogical and thor-ough introduction on the subject of delimited continuations in Scala.

4.5.1 Continuations

“Continuations are a powerful construct that allows you to imple-ment control flow mechanisms other than the familiar branches,loops, function calls, and exceptions. For example, you can jumpback into a prior computation or reorder the execution of partsof a program. These capabilities can be mind-bending; they arenot intended for application programmers, but library implemen-tators can harness the power of continuations and make them

51

Page 68: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 4. INVESTIGATION OF POSSIBLE TECHNIQUES

available to library users in a transparent way.” - Horstman [6,p. 319]

Continuation can be regarded as a language construct that can capturethe runtime environment at a given point in execution to be continued atsome later point in execution or time. In other words, continuations givethe developer the ability to suspend and resume sequential code paths in acontrolled way, and conceptually this is specifically what is searched for inorder to realize AP.

In the case of Scala, a specific type of continuation is implemented,namely delimited continuations. As the name implies the delimited contin-uations are limited in range. In the Scala case, the delimited continuationis limited to the code block given to a function called reset.

Technical details of delimited continuations in Scala

The JVM does not have the ability to provide continuations. In the Scalacase, this is circumvented by making a code transformation of the delimitedcontinuation (everything inside the reset block) to something that is calledcontinuation passing style ( ), according to Horstman [6, p. 325, 332].

Ryan Stansifer [13, p. 257] describes CPS as each call to a functionimplicitly takes the remainder of the program as an argument. Stansifermeans that this enables the function to always to continue forward in itsexecution and never “return” to some previous state.

To be able to do the CPS transformation, the Scala compiler makes useof a compiler plugin that takes care of the code transformation. According tothe Scala documentation [1], using the compiler option -P:continuations:enable

enables this compiler plugin.As mentioned in the Scala introduction in section 2.1, Scala is a stat-

ically type language but the type inference saves much of the hassle withwriting out the types explicitly. However, types do some times need tobe written out explicitly anyway. To facilitate the CPS transformation ofthe delimited continuations in Scala, more type information must be giventhan just the direct parameter type or return type. Therefore do manytypes in a delimited continuation need to be annotated with annotationslike @cpsParam[B,C] or @cps[A], to specify all type information that theCPS transformation needs.

Delimited continuation examples in Scala

To in some way understand how the delimited continuations are used inthunk procedures in section 4.5.3, a small example on delimited continua-tions are given in listing 4.27.

The delimited continuations in Scala make use of two keywords (actuallyfunctions) - reset and shift. The code block given as argument to reset

is the outer bounds of the delimited continuation. shift is always used

52

Page 69: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

4.5. ASYNCHRONOUS PROCEDURES

Code listing 4.27: Delimited Continuation example

showspacesshowspacesshowspacesshowspaces showspaces1 import s c a l a . u t i l . c on t inua t i on s . r e s e tshowspacesshowspaces showspaces2 import s c a l a . u t i l . c on t inua t i on s . s h i f tshowspacesshowspaces showspaces3

showspacesshowspaces showspaces4 object Del imitedCont inuat ion extends App {showspacesshowspaces showspaces5

showspacesshowspaces showspaces6 val r e s u l t = r e s e t {showspacesshowspaces showspaces7 s h i f t { k : ( Int => Int ) =>showspacesshowspaces showspaces8 k ( k (3 ) )showspacesshowspaces showspaces9 } + 1showspacesshowspaces showspaces10 } ∗ 2showspacesshowspaces showspaces11

showspacesshowspaces showspaces12 pr in t ( r e s u l t ) // prints the number 10showspacesshowspaces showspaces13 }showspacesshowspaces

inside a reset block. The shift function takes a function that requires aspecific function as argument. In the example listing 4.27, shift is givenan anonymous function with parameter k: (Int => Int). The parameternamed k is in its turn a function from Int to Int.

A key thing to identify here is what the argument function named k

actually is. The function k is the rest of the code, from the end of the shift

block to the end of the reset block. In this example, k is a function thatcontains the expression on line 9, and could be defined as:

def k(i: Int) = i + 1

The resulting expression of the delimited continuation looks like the follow-ing expression:

val result = ((3 + 1) + 1) * 2

Performance of delimited continuations in Scala

Performance is of importance in the context of the thesis problem, withmany instances of code running concurrently in multiple threads. Usingdelimited continuations in Scala do not need to affect the performance ofScala code negatively.

Research done by Rompf et al. [12], shows that CPS-transformed de-limited continuations can be implemented on stock VMs in ways that arecompetitive in terms of performance. They conclude based on benchmarksthat the high-level approach of, what they call, selective code transforma-tion of delimited continuations to CPS “performs competitively” to ordinaryScala code without delimited continuations.

53

Page 70: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 4. INVESTIGATION OF POSSIBLE TECHNIQUES

4.5.2 Dataflow and Futures

The use of the dataflow API in the Akka framework seems as a viable so-lution when realizing AP. The Akka documentation [14] states that Akkaimplements Oz-style dataflow concurrency by using a special API for ScalaFutures that enables a complimentary way of writing synchronous-lookingcode that in reality is asynchronous. The dataflow API in Akka makes useof delimited continuations to be able to work.

Future is a trait representing a value that may not have been computedyet. A Promise is essentially the promise (or write-side) of a Future (read-side).

However, use of the dataflow API adds dependency to the Akka frame-work besides adding dependencies to the Scala continuation compiler plugin.Further, the close integration between dataflow and the use of the Future

and Promise will probably in most use cases add an extra level of complexityto the implementation of AP.

4.5.3 Thunk procedure

The principle behind the thunk procedure is that the execution of a proce-dure can be stored away as a value, to be continued at a later time. Thenot yet executed part of the procedure is in this case returned to the codethat called the procedure in the first place.

The returned value is in this report called thunk. The thunk is (or has- depending on implementation) a function that can be called at any latertime to continue the execution form the earlier halted procedure executionstate.

Consecutive calls to the AP via calls to the returned thunk may generatefurther thunks if the AP for some reason is halted further times.

A simple thunk procedure example

To show how thunk procedures can be implemented in Scala with the helpof delimited continuations, a little example is put together with code listings4.28, 4.29 and 4.30.

The concept of this example is to show how to implement AP requiringarbitrary number of inputs of type Int. The example is somewhat limited,because there is no (general) way to tell when the AP has reached its end.

Line 5 in listing 4.28 contains the recursive definition of the Thunk class.It contains a value named input and the value input is of type function withargument type Int and return type Thunk.

The class ProcedureRunner in listing 4.28 contains two methods - run andinput. These two methods are the locations where the use of the delimitedcontinuation blocks reset and shift are used. The run method is a wrapperfor reset. The method run is the method to call when executing an AP. The

54

Page 71: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

4.5. ASYNCHRONOUS PROCEDURES

Code listing 4.28: Simple AP example - thunk procedure implementation.

showspacesshowspacesshowspacesshowspaces showspaces1 import u t i l . c on t inua t i on s . r e s e tshowspacesshowspaces showspaces2 import u t i l . c on t inua t i on s . s h i f tshowspacesshowspaces showspaces3 import u t i l . c on t inua t i on s . cpsshowspacesshowspaces showspaces4

showspacesshowspaces showspaces5 case class Thunk( input : Int => Thunk)showspacesshowspaces showspaces6

showspacesshowspaces showspaces7 object ProcedureRunner {showspacesshowspaces showspaces8

showspacesshowspaces showspaces9 val i gnore Input : Thunk = Thunk { input =>showspacesshowspaces showspaces10 p r i n t l n ( ” ignored : ” + input )showspacesshowspaces showspaces11 i gnore Inputshowspacesshowspaces showspaces12 }showspacesshowspaces showspaces13

showspacesshowspaces showspaces14 def input = s h i f t { k : ( Int => Thunk) => Thunk( k ) }showspacesshowspaces showspaces15

showspacesshowspaces showspaces16 def run ( func : => Unit @cps [ Thunk ] ) = r e s e t {showspacesshowspaces showspaces17 funcshowspacesshowspaces showspaces18 i gnore Inputshowspacesshowspaces showspaces19 }showspacesshowspaces showspaces20 }showspacesshowspaces

last return value in the reset block is a value called ignoreInput, which is arecursive thunk handling any superfluous input.

The input method is a wrapper for shift and is called from within anAP when more input is required or expected.

Listing 4.29 shows a usage example of the AP implementation in listing4.28. Lines 26 to 31 shows the actual AP block. Input is requires on lines28-30. Input is given to the AP via the returned thunks on lines 35, 36 and39.

Listing 4.30 shows the generated output in a test run of this simpleexample.

One thing to note is that the thunks can be rerun multiple times. Asseen in the listing, input is given to thunkOne on both lines 35 and 39 inlisting 4.29.

Another thing to note is that the output “procedure start” and “proceduresecond line” is only displayed once, despite that the first thunk (thunkOne)is run twice. The reason for this is that the first thunk is generated andreturned from the input request made on line 28 in listing 4.29 and that theoutput text “procedure start” and “procedure second line” is printed onthe lines before the thunk is generated - i.e. the AP lines 26 and 27 is nota part of the first thunk returned.

Further, the input values 23, 29, 53 and 59 are ignored, because in bothcases the AP has finished before these inputs are given. Thereby are theseinputs taken care of by the ignoreInput thunk used on line 18 in listing 4.28.

55

Page 72: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 4. INVESTIGATION OF POSSIBLE TECHNIQUES

Code listing 4.29: Simple AP example - usage in test program.

showspacesshowspacesshowspacesshowspaces showspaces22 object ThunkProcedureSmallExample extends App {showspacesshowspaces showspaces23 import ProcedureRunner .showspacesshowspaces showspaces24

showspacesshowspaces showspaces25 val thunkOne : Thunk = run {showspacesshowspaces showspaces26 p r i n t l n ( ” procedure s t a r t ” )showspacesshowspaces showspaces27 p r i n t l n ( ” procedure second l i n e ” )showspacesshowspaces showspaces28 p r i n t l n ( ” value 1 : ” + input )showspacesshowspaces showspaces29 p r i n t l n ( ” value 2 : ” + input )showspacesshowspaces showspaces30 p r i n t l n ( ” value 3 : ” + input )showspacesshowspaces showspaces31 p r i n t l n ( ” procedure end” )showspacesshowspaces showspaces32 }showspacesshowspaces showspaces33

showspacesshowspaces showspaces34 p r i n t l n ( ”\nFeeding with some input ” )showspacesshowspaces showspaces35 val thunkTwo = thunkOne . input (13)showspacesshowspaces showspaces36 thunkTwo input 17 input 19 input 23 input 29showspacesshowspaces showspaces37

showspacesshowspaces showspaces38 p r i n t l n ( ”\nRestart procedure from f i r s t thunk” )showspacesshowspaces showspaces39 thunkOne input 41 input 43 input 47 input 53 input 59showspacesshowspaces showspaces40 }showspacesshowspaces

Code listing 4.30: Simple AP example - output from test program.

showspacesshowspacesshowspacesshowspaces showspaces1 procedure s t a r tshowspacesshowspaces showspaces2 procedure second l i n eshowspacesshowspaces showspaces3

showspacesshowspaces showspaces4 Feeding with some inputshowspacesshowspaces showspaces5 value 1 : 13showspacesshowspaces showspaces6 value 2 : 17showspacesshowspaces showspaces7 value 3 : 19showspacesshowspaces showspaces8 procedure endshowspacesshowspaces showspaces9 i gnored : 23showspacesshowspaces showspaces10 i gnored : 29showspacesshowspaces showspaces11

showspacesshowspaces showspaces12 Restart procedure from f i r s t thunkshowspacesshowspaces showspaces13 value 1 : 41showspacesshowspaces showspaces14 value 2 : 43showspacesshowspaces showspaces15 value 3 : 47showspacesshowspaces showspaces16 procedure endshowspacesshowspaces showspaces17 i gnored : 53showspacesshowspaces showspaces18 i gnored : 59showspacesshowspaces

A advanced thunk procedure example

To illustrate a solution of the shortcomings of the simple example, a moreadvanced example is shown here. This, more advanced example, have aremedy to two problems in the simple example. First, the advanced example

56

Page 73: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

4.5. ASYNCHRONOUS PROCEDURES

enables the possibility to be able to determine when the AP has reached itsend. Second feature of the more advance example is the possibility to returna final return value from the AP.

The example makes use of a procedure called isFirstFivePrimes thattests if the first five input values (integers) given are the first five primenumbers in ascending order (i.e. 2, 3, 5, 7 and 11). If the first numbersare the prime numbers, isFirstFivePrimes should return the Boolean valuetrue and in other cases it should return false.

Code listing 4.31: Advanced AP example - thunk procedure implementation.

showspacesshowspacesshowspacesshowspaces showspaces1 import s c a l a . u t i l . c on t inua t i on s . cpsshowspacesshowspaces showspaces2 import s c a l a . u t i l . c on t inua t i on s . r e s e tshowspacesshowspaces showspaces3 import s c a l a . u t i l . c on t inua t i on s . s h i f tshowspacesshowspaces showspaces4

showspacesshowspaces showspaces5 object ThunkProcedure {showspacesshowspaces showspaces6 def runProcedure ( proc : => Thunk @cps [ Thunk ] ) : Thunk =showspacesshowspaces showspaces7 r e s e t { proc }showspacesshowspaces showspaces8

showspacesshowspaces showspaces9 def input : Int @cps [ Thunk ] =showspacesshowspaces showspaces10 s h i f t { r e s t : ( Int => Thunk) => InputThunk ( r e s t ) }showspacesshowspaces showspaces11

showspacesshowspaces showspaces12 def terminate ( answer : Boolean ) : Nothing @cps [ Thunk ] =showspacesshowspaces showspaces13 s h i f t { r e s t : ( Nothing => Thunk) => AnswerThunk ( answer ) }showspacesshowspaces showspaces14 }showspacesshowspaces showspaces15

showspacesshowspaces showspaces16 sealed trait Thunk { def <<(input : Int ) : Thunk }showspacesshowspaces showspaces17

showspacesshowspaces showspaces18 case class InputThunk ( nextThunk : ( Int => Thunk) ) extends Thunk {showspacesshowspaces showspaces19 def <<(input : Int ) = {showspacesshowspaces showspaces20 p r i n t l n ( ” Input value ” + input + ” given . ” )showspacesshowspaces showspaces21 nextThunk ( input )showspacesshowspaces showspaces22 }showspacesshowspaces showspaces23 }showspacesshowspaces showspaces24

showspacesshowspaces showspaces25 case class AnswerThunk ( answer : Boolean ) extends Thunk {showspacesshowspaces showspaces26 def <<(input : Int ) = {showspacesshowspaces showspaces27 pr in t ( ” Ignore input value ” + input + ” . ” )showspacesshowspaces showspaces28 p r i n t l n ( ”Answer a l r eady given . ” )showspacesshowspaces showspaces29 thisshowspacesshowspaces showspaces30 }showspacesshowspaces showspaces31 }showspacesshowspaces

The code listings that belong to the advances example are listings 4.31(the thunk procedure implementation) and 4.32 (example AP applicationand execution of it). The output of the test program is shown in listing4.33.

Listing 4.31 show the central parts of thunk procedures. It contains theprocedure runner with methods to request input and to terminate an APwith a Boolean answer as the result of the procedure. It also contains the

57

Page 74: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 4. INVESTIGATION OF POSSIBLE TECHNIQUES

Code listing 4.32: Advanced AP example - usage of AP in a test program.

showspacesshowspacesshowspacesshowspaces showspaces33 object PrimeProcedure {showspacesshowspaces showspaces34 import ThunkProcedure .showspacesshowspaces showspaces35

showspacesshowspaces showspaces36 def a s s e r t I n p u t ( expected : Int ) : Unit @cps [ Thunk ] = {showspacesshowspaces showspaces37 p r i n t l n ( ” Expecting value ” + expected + ” . ” )showspacesshowspaces showspaces38 i f ( input != expected ) terminate ( fa l se )showspacesshowspaces showspaces39 }showspacesshowspaces showspaces40

showspacesshowspaces showspaces41 def i sF i r s t F i v e P r i m e s : Thunk = runProcedure {showspacesshowspaces showspaces42 a s s e r t I n p u t (2 )showspacesshowspaces showspaces43 a s s e r t I n p u t (3 )showspacesshowspaces showspaces44 a s s e r t I n p u t (5 )showspacesshowspaces showspaces45 a s s e r t I n p u t (7 )showspacesshowspaces showspaces46 a s s e r t I n p u t (11)showspacesshowspaces showspaces47

showspacesshowspaces showspaces48 p r i n t l n ( ” Procedure Success . ” )showspacesshowspaces showspaces49 terminate ( true )showspacesshowspaces showspaces50 }showspacesshowspaces showspaces51 }showspacesshowspaces showspaces52

showspacesshowspaces showspaces53 object P r i n t U t i l {showspacesshowspaces showspaces54 def printAnswer ( thunk : Thunk) = thunk match {showspacesshowspaces showspaces55 case AnswerThunk ( answer ) =>showspacesshowspaces showspaces56 p r i n t l n ( ”Answer i s ” + answer + ” . ” )showspacesshowspaces showspaces57 case InputThunk ( ) =>showspacesshowspaces showspaces58 p r i n t l n ( ”No answer g iven yet − to few inputs . ” )showspacesshowspaces showspaces59 }showspacesshowspaces showspaces60

showspacesshowspaces showspaces61 def p r i n t T e s t T i l e ( t i t l e : S t r ing ) =showspacesshowspaces showspaces62 p r i n t l n ( ”\n ## Test ” + t i t l e + ” ##” )showspacesshowspaces showspaces63 }showspacesshowspaces showspaces64

showspacesshowspaces showspaces65 object PrimeTest extends App {showspacesshowspaces showspaces66 import P r i n t U t i l .showspacesshowspaces showspaces67 import PrimeProcedure .showspacesshowspaces showspaces68

showspacesshowspaces showspaces69 val i s3rdTo5thPrimes : Thunk = i s F i r s tF i v eP r i me s << 2 << 3showspacesshowspaces showspaces70

showspacesshowspaces showspaces71 p r i n t T e s t T i l e ( ” 1 : F i r s t f i v e primes are c o r r e c t ” )showspacesshowspaces showspaces72 printAnswer ( is3rdTo5thPrimes << 5 << 7 << 11 << 98 << 99)showspacesshowspaces showspaces73

showspacesshowspaces showspaces74 p r i n t T e s t T i l e ( ” 2 : Miss ing f i f t h prime” )showspacesshowspaces showspaces75 printAnswer ( is3rdTo5thPrimes << 5 << 7)showspacesshowspaces showspaces76

showspacesshowspaces showspaces77 p r i n t T e s t T i l e ( ” 3 : Fourth prime i s wrong” )showspacesshowspaces showspaces78 printAnswer ( is3rdTo5thPrimes << 5 << 77 << 11)showspacesshowspaces showspaces79 }showspacesshowspaces

thunk definition. In this case a thunk can either be a request for more inputor it can be an answer (i.e. the final return value) from an AP. In either

58

Page 75: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

4.5. ASYNCHRONOUS PROCEDURES

Code listing 4.33: Advanced AP example - output from test program.

showspacesshowspacesshowspacesshowspaces showspaces1 Expecting value 2 .showspacesshowspaces showspaces2 Input value 2 g iven .showspacesshowspaces showspaces3 Expecting value 3 .showspacesshowspaces showspaces4 Input value 3 g iven .showspacesshowspaces showspaces5 Expecting value 5 .showspacesshowspaces showspaces6

showspacesshowspaces showspaces7 ## Test 1 : F i r s t f i v e primes are c o r r e c t ##showspacesshowspaces showspaces8 Input value 5 g iven .showspacesshowspaces showspaces9 Expecting value 7 .showspacesshowspaces showspaces10 Input value 7 g iven .showspacesshowspaces showspaces11 Expecting value 11 .showspacesshowspaces showspaces12 Input value 11 given .showspacesshowspaces showspaces13 Procedure Success .showspacesshowspaces showspaces14 Ignore input value 98 . Answer a l r eady given .showspacesshowspaces showspaces15 Ignore input value 99 . Answer a l r eady given .showspacesshowspaces showspaces16 Answer i s t rue .showspacesshowspaces showspaces17

showspacesshowspaces showspaces18 ## Test 2 : Miss ing f i f t h prime ##showspacesshowspaces showspaces19 Input value 5 g iven .showspacesshowspaces showspaces20 Expecting value 7 .showspacesshowspaces showspaces21 Input value 7 g iven .showspacesshowspaces showspaces22 Expecting value 11 .showspacesshowspaces showspaces23 No answer g iven yet − to few inputs .showspacesshowspaces showspaces24

showspacesshowspaces showspaces25 ## Test 3 : Fourth prime i s wrong ##showspacesshowspaces showspaces26 Input value 5 g iven .showspacesshowspaces showspaces27 Expecting value 7 .showspacesshowspaces showspaces28 Input value 77 given .showspacesshowspaces showspaces29 Ignore input value 11 . Answer a l r eady given .showspacesshowspaces showspaces30 Answer i s f a l s e .showspacesshowspaces

case - the thunk is generated from the procedure runner or returned as aresult from an earlier thunk requiring more input.

Both types of thunks implement a method <<, that consumes a input.This can be compared with the left shift operator for std::ostream in theC++ programming language. The InputThunk uses the given input value tocontinue the execution of the AP, while the AnswerThunk ignores the giveninput.

Listing 4.32 shows how an AP can look like an how to run it. Just asin the simple example, a key thing to identify here is that the execution ofisFirstFivePrimes is halted each time is reaches the call to method input.In the advanced example input is called at row 38 in listing 4.32. As seenat line 10 in listing 4.31, each time the method input is executed, the shift

block stores the rest of the isFirstFivePrimes procedure not yet executedin the variable called rest. The variable rest is a variable of type functiontaking an Int and returning a Thunk. The variable rest is then stored in anew InputThunk instance that is returned to the piece of code that initially

59

Page 76: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 4. INVESTIGATION OF POSSIBLE TECHNIQUES

executed the AP. The execution of isFirstFivePrimes is halted, because thevariable rest (of type function) is not at this stage called with an integer asargument.

At line 69 in listing 4.32, the two first thunk of the call to AP isFirstFivePrimes

is fed with input values 2 and 3. The third thunk is stored as valueis3rdTo5thPrimes. As seen in output in listing 4.33 at line 5, the is3rdTo5thPrimes

thunk is awaiting the input value 5 when starting the three different tests.

4.6 Investigation summary

This section contains some tables that tries to summarize the the technolo-gies investigated in this chapter.

Table 4.7 shows a summary of the SM representation techniques men-tioned. Table 4.8 shows a summary of the timeout techniques mentioned.The last table - table 4.9 shows a summary of the AP representation tech-niques mentioned in this chapter.

As the investigations show, there are multiple viable techniques to choosefrom when representing state machines and using delays in Scala.

Table 4.7: SM representation technique summary, where I/D means ‘imple-mentation dependent’.

SM repr. extra SM poentially Akka datatechnique tool tailored ineffi- integra- driven

required syntax cient ted logicNested match/caseTransition table I/D I/D yesState patternSM compiler yes yes I/D I/D I/DAkka become yes yesAkka FSM yes yes yesScala internal DSL yes I/D yes

60

Page 77: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

4.6. INVESTIGATION SUMMARY

Table 4.8: Delay technique summary.

Delay Acceptable Akkatechnique performance integratedAkka FSM timer (FSMT) yes yesAkka FSM state timeout (FSMSTO) yes yesAkka scheduler (AS) yes yesAkka recieve timeout (RTO) yes yesfuture timeout (FTO) yesglobal timer (GJT) yeslocal timer (LJT)future await result (FAR)Thread sleep (TS)

Table 4.9: AP representation technique summary.

AP repr. Based on Akkatechnique delimited integrated

continuationsThunk procedure yesAkka dataflow yes yes

61

Page 78: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

Chapter 5

Specification of toyexample

The purpose of this chapter is to define a protocol toy example specificationthat can act as a mannequin and guide for some of the implementationtechniques investigated in this thesis work.

Sections 5.1 and 5.2 give an overview of the toy example and explainsthe real world context of the toy example. The detailed specification of thetoy example is given in sections 5.3, 5.4 and 5.5.

5.1 Overview

This section gives an overview of the toy example protocol and the domainit operates in.

The toy example is defined as a protocol layer between two other pro-tocol layers. Figure 5.1 shows a schematic overview of the layers and theentities involved in the NET protocol layer. The toy example centers onthe user equipment (UE) side of the NET layer. A UE can for instancebe a mobile phone or any other communication device that uses the mobilecommunication network.

The protocol layer above is called APPL and can be thought of as theapplication layer. Just as an example, one application of the applicationlayer could be IP traffic.

The layer that the toy example focuses on is called NET and managesthe connection between UE and the communication network core, by com-munication to a network entity that in the toy example is called CORE.

The protocol layer below is called RADIO and is a protocol layer thatmanages the radio communication link between the UE and some radio basestation (RBS).

62

Page 79: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

5.2. RELATION TO THESIS CONTEXT

UE RBS CORE

APPL

|

NET NET

| |

RADIO ---- RADIO-S1AP ---- S1AP

Figure 5.1: NET overview, in context of different abstraction layers in thecommunication stack between entities.

5.2 Relation to thesis context

As mentioned in the answer to question 2 in the initial investigation (seeappendix A), there is a state machine for a protocol layer that is, as statedin the investigation, difficult to work with. That protocol is called NAS(Non Access Stratum), and is a specification given by the 3rd GenerationPartnership Project (3GPP) on a part of the LTE standard. LTE is abbre-viation for Long Term Evolution and is sometimes referred to as 4G (fourthgeneration) mobile communication standard.

The purpose of the toy example is to illustrate the specific features andidiosyncrasies of some of the real protocols that is the source for this thesiswork. The toy example is therefore loosely based on some parts of the NASspecification and the operating environment of NAS.

However, the toy example is a simplification inspired by the NAS spec-ification, but is not an actual real world example. This is why the contentof the toy example and the names used in the toy example is somewhatseparated from NAS or other real world examples.

UE ENB MME

APPL

|

NAS NAS

| |

RRC ----- RRC-S1AP ---- S1AP

Figure 5.2: NAS overview, in context of different abstraction layers in thecommunication stack between entities.

Figure 5.2 shows a schematic overview of the layers and the entitiesinvolved in the NAS protocol layer.

Compared to the toy example the RRC (Radio Resource Control) is

63

Page 80: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 5. SPECIFICATION OF TOY EXAMPLE

roughly the same as the RADIO layer and the NAS layer is roughly thesame as the NET layer. Also, ENB (Evolved NodeB) and MME (MobilityManagement Entity) is almost the same as the things called RBS and CORE.

The only names and abbreviations use in the rest of the toy exampledefinition belong to the toy example and are the layers APPL, NET andRADIO and the network entities UE and CORE.

5.3 NET states

IdleIdle AttachOngoingAttachOngoing

DetachOngoingDetachOngoing ConnectedConnected

POWER ON / powerOn

failure

success

forcedDetach

DETACH REQUEST /

POWER OFF / powerOff

success, failure

Figure 5.3: Toy example state machine

Figure 5.3 shows the states of the UE side of the NET layer. Idle

and Connected are the basic states while AttachOngoing and DetachOngoing

denotes the current transition between the basic states and can therefore beregarded as short term transition states.

5.4 Interaction with UE NET

This section tries to describe all interactions and expected messaging be-tween UE NET and related entities, with the help of sequence diagrams.Section 5.5 focuses on the internal structure, i.e. the behavior, of UE NET.

All interactions with the UE side NET layer are directly to the layersabove and below the net layer in the UE, i.e. the APPL and RADIO layersrespectively. Indirectly the UE side of the NET layer can communicate toCORE side of the NET layer, via messages to and from the RADIO layerwithin the UE. The radio layer delegates the messages further.

64

Page 81: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

5.4. INTERACTION WITH UE NET

5.4.1 Interaction between APPL and NET

The sequence diagrams in figures 5.4 to 5.6 describe the interactions betweenthe APPL layer and the NET layer.

POWER ON DONE

POWER ON FAIL

POWER ON

a:APPL n:NET

[failure]

alt

[success]

Figure 5.4: The powerOn interaction between application layer and NETwhen requesting to power on.

POWER OFF DONE

POWER OFF

a:APPL n:NET

Figure 5.5: The powerOff interaction between application layer and NETwhen requesting to power off.

IS DETACHED

a:APPL n:NET

Figure 5.6: The is detached interaction between application layer and NETwhen signaling that UE is detached from CORE.

5.4.2 Interaction between RADIO and NET

The sequence diagrams in figures 5.7 to 5.10 describe the interactions be-tween the RADIO layer and the NET layer.

65

Page 82: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 5. SPECIFICATION OF TOY EXAMPLE

CONNECT DONE

CONNECT FAIL

CONNECT

n:NET r:RADIO

[failure]

alt

[success]

Figure 5.7: The connect interaction between NET and RADIO when re-questing to create a RADIO layer connection.

DISCONNECT DONE

DISCONNECT

n:NET r:RADIO

Figure 5.8: The disconnect interaction between NET and RADIO whenrequesting to disconnect a RADIO layer connection.

SEND ACK

SEND FAIL

SEND(x)n:NET r:RADIO

[failure]

alt

[success]

Figure 5.9: The send interaction between UE NET and RADIO when UENET wants to send a payload x to CORE NET. If RADIO successfully sendsmessage further, the RADIO will respond with an acknowledgment to NET.

66

Page 83: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

5.4. INTERACTION WITH UE NET

RECEIVE(y)n:NET r:RADIO

Figure 5.10: The receive interaction between UE NET and RADIO whenCORE NET sends a payload y to UE NET.

5.4.3 Interaction between UE and CORE side in NETlayer.

The sequence diagrams in figures 5.11 to 5.14 describe the interactions be-tween the UE and CORE side in NET layer.

DETACH ACCEPT

DETACH REQUEST

u:UE NET m:CORE NET

Figure 5.11: The forcedDetach interaction between application layer, UENET and CORE NET when CORE NET forces a detach. The DETACHACCEPT response message is sent before disconnection.

67

Page 84: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 5. SPECIFICATION OF TOY EXAMPLE

authentication

ATTACH ACCEPT

ATTACH COMPLETE

ATTACH FAIL

ATTACH REQUEST

u:UE NET m:CORE NET

opt

[failure]

alt

[success]

Optional authenti-cation procedure.Optional authenti-cation procedure.

Figure 5.12: The attach interaction between UE NET and CORE NET whenUE tries to attach to CORE. The CORE NET might want to authenticatethe UE and therefore the authentication interaction might be applied afterthe initial attach request, depending on whether CORE NET responds withan attach accept or an authentication request.

DETACH COMPLETE

DETACH REQUEST

u:UE NET m:CORE NET

Figure 5.13: The detach interaction between UE NET and CORE NETwhen UE tries to detach from CORE

68

Page 85: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

5.4. INTERACTION WITH UE NET

AUTH RESPONSE

AUTH RESPONSE

AUTH REJECT

AUTH FAIL

AUTH REQUEST

u:UE NET m:CORE NET

[MME reject failure]

[UE reject failure]

alt

[success]

Figure 5.14: The authentication interaction between UE NET and CORENET when UE NET tries to authenticate it self towards CORE NET. De-pending on some variable the UE NET might not send an authenticationresponse to CORE NET, but instead send an authentication failure.

69

Page 86: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 5. SPECIFICATION OF TOY EXAMPLE

5.5 Procedures in UE NET

The purpose of the procedures in this section is to tie together the frag-mented sequence diagrams in section 5.4. The sequence diagrams in section5.4 needs to be put into a larger context that describes the complete behav-ior of UE NET. Figure 5.3 together with the procedures in this section doesjust that.

Some criteria put on the procedures:

• The procedures in this section directly correspond to the entities withthe same names in the interaction in the sequence diagrams and actionsin the state transition diagram 5.3.

• The action/interaction to make when a procedure returns a failure orsuccess is given by the corresponding interaction sequence diagram.For some procedures, interaction is expected to occur based on thereturn value, but for some it is not expected. This should be obviouswhen comparing sequence diagrams with procedures.

The difference comes from the fact that some methods are called assub-methods while other are called as topmost procedures in figure 5.3.This can be regarded as an artifact from the split in representationbetween a state transition diagram and a procedure representation.

• When a procedure fails, everything should revert to the previous state.However, this does not apply to the failure of detach or disconnectprocedures, that should end up in an idle (disconnected) state whenfailing.

5.5.1 A procedure notation

To be able to describe the procedures in the UE NET, a simple procedurenotation (a kind of pseudo language) is used. The point of this procedurenotation is to be abstract and minimalistic, so the intent of the procedurescan be described, but at the same time do not rely on any particular languagefeatures of Scala or any other programming language. This section focuseson defining the procedure notation. The actual representation in Scala isneither given nor of importance at this stage.

Conventions

Here follows some conventions for the procedure representation:

• A block of statements are denoted by being indented at the sameindentation level.

• S and F represents the success resp. failure of a procedure.

70

Page 87: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

5.5. PROCEDURES IN UE NET

• If a procedure calls a sub-procedure and the sub-procedure returns F,the calling procedure immediately also returns F (this can be comparedto exception in some languages).

• If no of the statements in a procedure returns F the procedure willreturn S. In other words, the return of S is implicit.

Keywords

Six procedure notation keywords are defined for the procedure notation:

if An if-statement. Gives the ability to execute conditional blocks of state-ments, given a boolean expression.

else The else part of an if-statement.

return Makes a procedure return a specific value.

whenfail Sets a statement (or blocks of statements) to execute if the currentprocedure fails from this point forward. Compared to Java or Scala,this can be regarded as a tear-down mechanism in the catch part of atry-catch block around something that might throw an exception.

nondet To simplify the abstract procedure notation, some parts are wrappedin a nondet block signaling that this block is non-deterministic and onlyexecuted if the first statement can be executed successfully.

If the first statement cannot be executed successfully, not even thefirst statement is executed. The nondet block is in this case regardedas an an success.

If the first statement in the nondet block is executed successfully, afailure in a subsequent statement in the nondet block is to be regardedas a failure for the entire nondet block. This is analogous to the con-vention that a failure of a statement in a procedure block at the sametime is regarded as a failure of the entire procedure.

5.5.2 Primitive procedures

These procedures are regarded as being primitive, and in some sense theirimplementation is not of importance, because they can be regarded as thebasic building blocks of procedures. In a more practical perspective, theycan be regarded as abstract functions or interface methods, where the im-plementation details are not of interest to the procedures that use them.

detachComplete Signal to the application layer that the UE is detached fromCORE.

connect Create a RADIO-layer connection.

71

Page 88: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 5. SPECIFICATION OF TOY EXAMPLE

disconnect Disconnect the currently existing RADIO-layer connection.

send Send a message to CORE NET over existing RADIO-layer connection.

receive Wait for a specific message from CORE NET over existing RADIO-layer connection. This procedure will fail if given timeout is exceeded.

5.5.3 Composite procedures

These composite procedures are built up of other statements given the prim-itive procedures, other composite procedures and the procedure notation.

powerOn When application layer wants to power on, this procedure makessure that the underlying RADIO- and NET-layers are properly set up.

connect

whenfail disconnect

attach

powerOff Tear-down of RADIO- and NET-layers when application layerwants to power of.

detach

disconnect

attach Attaches the UE NET to the CORE NET. The CORE NET mightalso request the UE to authenticate it self, as a part of the attachprocedure.

send(ATTACH_REQUEST)

nondet receive(ATTACH_FAIL, timeout)

return F

authentication

receive(ATTACH_ACCEPT,timeout)

send(ATTACH_COMPLETE)

detach Detached the UE NET from the CORE NET.

send(DETACH_REQUEST)

receive(DETACH_COMPLETE,timeout)

authentication This method also have access to a value shouldAuthenticate,that denotes whether the UE NET will try to authenticate it self to-wards the CORE NET or not.

72

Page 89: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

5.6. A LARGER EXAMPLE

nondet receive(AUTH_REQUEST,timeout)

if (shouldAuthenticate)

send(AUTH_RESPONSE)

nondet receive(AUTH_REJECT,timeout)

return F

else

send(AUTH_FAIL)

return F

forcedDetach

send(DETACH_ACCEPT)

disconnect

is_detached

5.6 A larger example

Figure 5.15 shows a large example to show that the specifications in sections5.3, 5.4 and 5.5 results in.

The sequence diagram shows the all interaction that might take placewhen the application layer wants to power on and all interactions are com-pleted successful. In the Idle protocol state, a POWER ON message is sentto the NET layer from the APPL layer. The NET layer makes all necessaryinteraction with the RADIO layer stated in the powerOn procedure beforereturning a POWER ON DONE message to the APPL layer and finallyending up in the Connected state.

73

Page 90: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 5. SPECIFICATION OF TOY EXAMPLE

CONNECT DONE

SEND(ATTACH REQUEST)

SEND ACK

RECEIVE(AUTH REQUEST)

SEND(AUTH RESPONSE)

SEND ACK

RECEIVE(ATTACH ACCEPT)

SEND(ATTACH COMPLETE)

SEND ACK

CONNECT

POWER ON DONE

POWER ON

a:APPL n:NET r:RADIO

Figure 5.15: Large message interaction example, with successful powerOn

procedure complete with all sub-procedures including authentication.

74

Page 91: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

Chapter 6

Implementation of toyexample

This chapter starts with an explanation of the design choices made in theimplementation. After that, some features of the implementation will behighlighted in the implementation presentation. The chapter ends with anevaluation of the implementation, based on code review with and questionsto the domain expert.

6.1 Technical choices for implementation

There are some choices to make in the implementation of the toy example.The technical investigations in chapter 4 give multiple option for both therepresentation of the protocol state machine and how to trigger protocoltimeouts. Only one way to implement AP is thoroughly investigated.

6.1.1 Mapping between specification and implementa-tion

To minimize the differences between the toy example specification and theimplementation, the implementation is divided up in the same way the spec-ification is in chapter 5.

The implementation is built up with a 4-state state machine using someprocedures in the transition between the states in the state machine. Thestate machine is based on figure 5.3 on page 64.

The toy example procedures specified in section 5.5 are implemented asAP with help of the thunk procedure solution illustrated in section 4.5.3 onpage 54.

75

Page 92: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 6. IMPLEMENTATION OF TOY EXAMPLE

6.1.2 State machine

The state machine implementation is realized with the help of the function-ality Akka FSM, shown in section 4.2.2 on page 32.

6.1.3 Asynchronous Procedure

As already mentioned, the thunk procedure solution using Scala’s capabilityto use delimited continuations is used when implementing the procedures inthe protocol specification as AP.

As given in the specification, the protocol procedures are specified toreturn a value denoting either success of failure of the procedure. In theimplementation, this is denoted with the Scala values true and false re-spectively.

The implementation of the AP functionality, using thunk procedures, isin a way completely independent to the implementation of the toy exampleprotocol. Therefore the implementation of the AP functionality is madeas a separate and generic implementation that that has no ties to the toyexample. This is reflected in the implementation code listings appendix inthis report, where the AP implementation in section D.1 is separated fromthe protocol definition and test code in sections D.2 and D.3.

The implementation of the toy example however, makes extensive use ofthe AP functionality.

6.1.4 Timeout

The protocol timeouts in the specification is realized with the use of FSM-STO (Akka FSM state timeout), explained in section 4.4.6 on page 43. Thissuits well with the use of Akka FSM in the state machine implementation.

An advantage with the use of FSMSTO is that there is no need to manu-ally cancel the timeout if a message is received within the timeout duration.

Another advantage with the use of FSMSTO is that the timeout is sig-naled to the FSM-using actor via a message named StateTimeout. This enablesthe ability to trigger the timeout explicitly by sending the StateTimeout mes-sage directly to the targeted actor. This comes in extra handy when doingtests on the FSM-actor state machine. The alternative would be that thetest code waits the entire timeout duration in order to trigger the timeout.The waiting alternative can make test suits with many or long timeouts runreally slow.

6.1.5 Test framework

A test framework is used in order to make unit tests for a individual compo-nent in the implementation. The unit tests helps to verify the functionalityof the individual components in the implementation.

76

Page 93: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

6.2. IMPLEMENTATION RESULT

In this implementation the test framework ScalaTest1 is used. ScalaTestis one of the two commonly referred test frameworks specifically written forScala and not just Java. The alternative test framework would in this casebe Specs2 2.

6.1.6 Mock framework

To be able to make unit tests for a individual component in the implemen-tation, the component needs to be isolated form the rest of the code, byusing mock objects or stub objects as replacements for the other parts ofthe implementation needed in the tested component.

Another advantage of the mock objects is that they usually can be in-strumented to verify that e.g. a method is called three times with specificarguments. This instrumentation is an test aid, handy when making e.g.unit test verifications of some component.

There exist a lot of mock frameworks that helps with the constructionof these mock objects. Most often, the differences between different mockframeworks comes down to personal preferences. For this implementation amock framework called Mockito3 is used.

6.2 Implementation result

The entire implementation is appended in appendix D starting on page 101.This section highlights some implementation details.

6.2.1 Code structure

As seen in appendix D, the implementation code is divided up into threemajor parts. These parts are:

• The generic AP implementation using the thunk procedure technique.It resides in appendix D.1.

• The code implementing the toy example specification. It resides inappendix D.2.

• The test code that tries to verify that the toy example implementationbehaves correctly. It resides in appendix D.3.

The code in the tree different parts is further divided up in Scala packagesbased on functionality. The Scala packages correspond to folders in the codelistings in the appendix.

1ScalaTest homepage: http://www.scalatest.org/ (accessed 2013-03-25).2Specs2 homepage: http://etorreborre.github.com/specs2/ (acessed 2013-03-25).3Mockito homepage: http://code.google.com/p/mockito/ (accessed 2013-03-25).

77

Page 94: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 6. IMPLEMENTATION OF TOY EXAMPLE

6.2.2 Asynchronous procedure implementation

Code listing 6.1: Toy example thunk definition in implementation filethunkprocedure/Procedure.scala.

showspacesshowspacesshowspacesshowspaces showspaces13 /∗∗ Recursive definition of continuation wrapper . ∗/showspacesshowspaces showspaces14 case class Input [ In , Out ] ( proceed : In => Thunk [ In , Out ] )showspacesshowspaces showspaces15

showspacesshowspaces showspaces16 /∗∗showspacesshowspaces showspaces17 ∗ A thunk i s either a procedure part waiting for input orshowspacesshowspaces showspaces18 ∗ a result value .showspacesshowspaces showspaces19 ∗/showspacesshowspaces showspaces20 type Thunk [ In , Out ] = Either [ Input [ In , Out ] , Out ]showspacesshowspaces

The entire AP functionality consists of one file for the basic functionalityand one extra file to enable some syntax sugar for thunks. The central partsare the thunk definition shown in listing 6.1. The thunk definition showsthat a thunk literally is either a request for input or a output result.

Code listing 6.2: Toy example procedure runner method definitions in im-plementation file thunkprocedure/Procedure.scala.

showspacesshowspacesshowspacesshowspaces showspaces41 type T = Thunk [ In , Out ]showspacesshowspaces showspaces42

showspacesshowspaces showspaces43 /∗∗showspacesshowspaces showspaces44 ∗ Require input . I . e . pause , return thunk and wait untilshowspacesshowspaces showspaces45 ∗ input i s given to thunk .showspacesshowspaces showspaces46 ∗/showspacesshowspaces showspaces47 def input : In @cps [T]showspacesshowspaces showspaces48

showspacesshowspaces showspaces49 /∗∗ Runs the procedure given as parameter . ∗/showspacesshowspaces showspaces50 def apply ( procedure : => Out @cps [T] ) : Tshowspacesshowspaces showspaces51

showspacesshowspaces showspaces52 /∗∗ Called when terminating a procedure from within .∗/showspacesshowspaces showspaces53 def terminate ( r e s u l t : Out) : Nothing @cps [T]showspacesshowspaces showspaces54

showspacesshowspaces showspaces55 /∗∗ Runs a sub−procedure from within another procedure . ∗/showspacesshowspaces showspaces56 def runSubProcedure ( procedure : => Out @cps [T] ) : Out @cps [T]showspacesshowspaces

The thunk procedure method definition shown in listing 6.2, where apply

is called when starting an AP and the three methods input, terminate andrunSubProcedure are all called from within a running AP. These are the onlymethods found to be needed when using AP to implement all features thetoy example protocol procedures.

78

Page 95: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

6.3. EVALUATION OF IMPLEMENTATION

6.2.3 Toy example state machine part

The toy example state machine part is located in the protocol.fsm package.The protocol state machine is located in class NetFsm in listing D.5.

6.2.4 Toy example asynchronous procedures part

The asynchronous procedures needed in the toy example are divided up inseveral Scala classes in an attempt to make them easier to test. The APimplementations are divided in a way where all sub-procedures used in aAP resides in another class.

This division in combination with mocking the behavior of sub-procedureclasses with the Mockito mock framework enables easy testing of all pro-cedures individually, without interference from sub-procedure implementa-tions.

6.2.5 Tests of toy example

The testing of the implementation focuses on two major types of testing. Thefirst type of testing is, as already mentioned, unit testing of each procedureclass individually. These test specifications reside in the protocol.procedure

package.The other type of testing is protocol message driven testing of the proto-

col state machine. These tests make use of the Akka TestKit testing utilityand these tests reside in the protocol.fsm package.

Mock framework deficiencies

In the development and testing of the protocol implementation, some testtool deficiencies where discovered. The Mockito mock framework is unableto handle the CPS type annotations used for the delimited continuations inScala. Delimited continuations are in this case used for the realization ofAP.

The code in the protocol.procedure.mockable package is specifically de-veloped to tackle the problem to mock methods with parameter type orreturn type with CPS type annotations.

6.3 Evaluation of implementation

The implementation shows that the protocol specification can be imple-mented with Akka FSM and AP realized with Scala’s delimited continuations.

Being the first implementation attempt of the toy example, the imple-mentation can be regarded as a first try or first implementation iteration.There is most often room for improvements in any implementation and thecurrent implementation can be seen as a base for further improvements. An

79

Page 96: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 6. IMPLEMENTATION OF TOY EXAMPLE

evaluation of the implementation helps to highlight problems and solutionsin the implementation.

The implementation evaluation in this section is heavily based on notesfrom a code review evaluation session and evaluation questions and answersin written correspondence. Both evaluations are directed to the thesis do-main expert. The data from these two evaluations are appended in appendixB and C.

6.3.1 Technical details

The code review in the evaluation session focuses on technical details inthe implementation. A summary of the notes from the evaluation session isgiven in this section.

Naming conventions

In the code review session, some of the comments involve the naming ofthings in the code. Some names in the implementation do not follow namingconventions or have the capability to mislead developer reading the code.This is obviously something that can be improved. The naming of things donot have so much to do with the technical aspects of the implementation,but can have an impact on how easy the code is to develop and maintain.Some mentioned naming problems:

• The use of the term cut (class under test) instead of e.g. fsm in sometests.

• The use of the prefix nondet in some places. It could be replaced withanother prefix like e.g. conditional or if.

Interface between SM and AP

There are some improvements to make in the interface boundary betweenthe two types of representation in the implementation - the state machineand asynchronous procedure representations. Two objections are:

• As seen in the adapter class protocol.fsm.Procedures, there are a littlebit to much logic in between the SM and AP parts of the implementa-tion. The logic works, but it might be regarded as good code hygieneto move the logic found on line 46 to 51 in listing D.7 to the classFsmProceduresImpl.

• The use of the thunk procedures realization of AP requires the statemachine in the class NetFsm in listing D.5 to use the method attachBehavior

already in the IDLE state. The same objection works for using detachBehavior

in the CONNECTED state.

80

Page 97: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

6.3. EVALUATION OF IMPLEMENTATION

The reason for this is an artifact from the fact that a thunk procedurecan immediately generate a thunk containing a final answer on theinitial call to the thunk procedure.

Testing

One opinion in the evaluation session is that some parts of the testing looksreally nice while other parts are hard to read. Generally, the code in the inte-gration tests in class protocol.fsm.IntegrationTest in listing D.18 looks nicewhile procedure test specifications such as class protocol.procedure.CoreProcedureSpecin listing D.21 are hard to read.

The difference between these two types of tests is the difference in ab-straction level of what they test. The integration tests execute tests onthe message level between different protocol layers, while the procedure testspecifications focus on the interaction between thunk procedures. Theremight be more message centric ways to test the asynchronous proceduresthat can improve readability of the procedure tests.

Parts of the implementation that stand out as good examples

One of the reasons for the implementation is to just show that an implemen-tation can be done and how it can be done. In addition to this some partsof the implementation are mentioned as good implementation examples inthe evaluation session:

• The state machine in the NetFsm class in listing D.5 is judged to becompact and easy understood.

• Another example being easy to read and understand is the integrationtests in the test specification class IntegrationTest in listing D.18.

• The use of the AP representation is a big step forward compared toboth the result from the UniMod tool and alternatively making use ofcallback methods in Java to accommodate asynchronous calls.4

6.3.2 Implementation validity and applicability

This section gives a summary of a set of questions and answers that to someextent examines the validity and applicability of a implementation similarto the concrete implementation of the toy example.

The questions used try to put an implementation similar to the toy ex-ample implementation in relation to the type of implementations used todayat the Xdin. Despite the concrete toy example implementation, the ques-tions are somewhat hypothetical in nature because it makes the comparison

4This comment is not based on the implementation evaluations in appendix B and C,but instead received 8 April 2013 from domain expert after a thesis report review.

81

Page 98: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 6. IMPLEMENTATION OF TOY EXAMPLE

between the representation techniques used in the single instance of toy ex-ample implementation and some distant real-world representation practicesused today at Xdin.

In the rest of this section, the techniques used in the toy example imple-mentation will be abbreviated TE and while the real-world techniques usedat Xdin involving Java and Unimod will be abbreviated RW .

Differences

The largest difference between TE and RW is that TE allows that non-blocking I/O can use a representation that looks like sequential blockingI/O in Java.

Gains

The possible gains with using TE is that the code and tests gets more easyto read and in the extension cheaper to maintain and to develop.

Problems

The largest obstacle with using TE is that the migration from RW mightneed considerable time. Also, it is not obvious how to in small steps partiallymigrate from RW to TE.

Missing aspects

The toy example specification is designed to cover most special cases exist-ing in RW implementations. There is a high probability that some specialcases are missed, but they might not show them self until a real world im-plementation of TE are tried.

Conclusions

The starting point for this thesis is the hypothesis that using the AP con-cept together with the alleged advantages of Scala over Java should give andevelopment edge over current RW techniques. The ability to realize AP inScala is something that speaks strongly for the use of TE.

However, without a closer and more extensive comparison between TEand RW, no definite conclusion can be made.

82

Page 99: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

Chapter 7

Discussion

This chapter discusses the results and findings in this thesis report and alsotries to mention some of the alternative solutions not used in the implemen-tation. Further, it mentions some of the things out of scope of the thesis,but might be interesting to look more into. Finally, the chapter tries tocapture some thoughts on the goals and methodology in the thesis.

7.1 Generalization and applicability

The implementation evaluation has not given any indications that the tech-niques used in the toy example implementation are not generalizable andapplicable to other similar protocol implementations.

The following sections make some more detailed elaborations on the gen-eralization and applicability on other protocols similar to the toy example.

7.1.1 The asynchronous procedure implementation

As mentioned earlier, the AP part of the toy example implementation residesin appendix D.1. This part of the toy example implementation can be seenas very generalized solution. Both the AP input type and output type aregeneric and therefore not tied to any particular usage area.

In general the AP implementation should be able to use in, if not inmost, but at least some places where inversion of control is needed, as theterm is described in section 2.3.1.

The changes proposed to deal with the missed timeout functionality insection 7.1.3 would make the AP implementation even more general. Thenthe AP can double as both a generator and a consumer of data via input1

thunks.

1In that case not only used for input

83

Page 100: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 7. DISCUSSION

7.1.2 Applicability on protocols similar to toy example

The principles and design choices used in the toy example protocol imple-mentation should be able to handle similar types of protocols.

Something to be aware of is that the procedures for the Net protocollayer is only specified to have two different return values - true and false,meaning success and failure. This can be a limiting factor that can createproblems for some types of protocol procedure representations.

The first thing to note is that the Net protocol layer procedures are anabstraction (specialization) on top of the generic AP implementation. Thesecond thing to note is that to simplify the implementation, multiple typesof failure are grouped into the Net procedure return value false. Thesetypes of failures are

• Received messages that is interpreted as failure messages.

• Timeouts for not received, but expected messages.

• Explicitly triggered failures in Net procedures.

If the two procedure return values - success and failure - do not suitea specific protocol representation, the principles and design choices used inthe toy example protocol implementation may not be directly applicable.

7.1.3 Improved timeouts

One thing that to some extent is overlooked and missed in the toy exampleis the usage and consequence of message timeouts. As it is now, the specifi-cation does not give an explicit and detailed specification on the usage andbehavior of timeouts when awaiting response (input) in a procedure. Thetoy example implementation do somewhat miss to deal with timeouts in ac-cordance to the bits of information given in the specification. As it is now,message timeouts are dealt with in the state machine and not delegated tothe asynchronous procedure thunks. This results in that the procedures losethe ability to make a proper error handling when a timeout occurs.

Pieces of the current implementation can be seen in listings 6.1 and 6.2on page 78 and the complete file can be seen in listing D.1 on page 101.

This does not invalidate the toy example implementation and the tech-niques used in it. The addition of proper handling of input timeouts in thethunk procedure implementation can be seen as an extension or generaliza-tion of the current implementation. A redefinition of a thunk input requestto enable passing a timeout duration argument, could then look like

case class Input[InArg, In, Out](

arg: InArg, proceed: In => Thunk[InArg, In, Out])

compared to the definition given in listing 6.1

case class Input[In, Out](proceed: In => Thunk[In, Out])

84

Page 101: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

7.2. OTHER SOLUTIONS

Put into the toy example context, the type argument InArg could bespecified to class scala.concurrent.duration.DurationLong or something likethat, while In would be bound to a concrete type that represents either avalid input argument or a timeout. A type that fit that interpretation couldbe the class Option[Message], instead as the currently used Message class.Obviously modifications also need to be made at other places too, to enableto handle timeouts in the toy example procedures.

7.2 Other solutions

This section tries to give some perspective on the toy example implementa-tion technique used and alternative techniques.

7.2.1 Other implementation choices in Scala and Akka

The investigations in chapter 4 shows that there are multiple techniquesthat can be used when implementing the toy example and similar proto-cols. Multiple state machine implementations and multiple ways to triggertimeouts are shown to be valid choices, depending on context.

The toy example implementation makes some specific choices for tech-niques to use, but other choices could be made instead. The specific tech-niques used only show one way to implement the toy example. The mainpurpose of the toy example is to demonstrate that an implementation ac-tually can be done in accordance to the thesis purpose and goals and howthat might look like.

This report avoids to make any general conclusion on which of the in-vestigated state machine implementation techniques that are most suitablewhen representing protocols similar to the toy example protocol, in Scalaand Akka.

Structures in perspective of multiple protocol layers

In the toy example implementation, the protocol state machine is tightlyconnected directly with an actor via the Akka FSM functionality. This canbe put in contrast to state machine representations not tied to an actor,such as using a transition table.

In a larger perspective, one could choose to group multiple protocol layerimplementations together inside a single actor. The advantage or disadvan-tage with using an actor per protocol layer versus using one actor per UE isneither investigated nor indicated to make a difference given the informationgathered in this thesis.

85

Page 102: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 7. DISCUSSION

7.2.2 Java and Akka

As earlier mentioned in the comparison between Scala and Java in section2.1.3 on page 10, Akka has support for direct use in Java. This enablesJava implementations to take advantage of at least the concurrency andscalability features of Akka. However, the referred section also mentions thatJava do not have native support for continuations, but it can be supportedin Java via third party byte code processing in Apache Commons javaflow.

Some of the other advantages of Scala over Java will however be lostsuch as generally more compact and productive syntax and specifically typeinference, pattern matching, functional programming and the reduced riskfor null pointer problems.

7.2.3 Other JVM languages

There exist a lot of languages for the JVM today. According to Kullberg [7],Scala where the only statically type JVM language besides Java up to year2010, when Groovy++ emerged. At the time of writing this report, a quicksearch for “statically typed JVM language” on Google results in languagessuch as Xtend, Yeti, Kotlin, Guso, Fantom, Ceylon and Talc. A Dr. Dobb’sarticle2 A Long Look at JVM Languages written by Eric Bruno, November2012, gives an introduction to some of them.

There are also some dynamically typed JVM languages such as Jython,Clojure and Rhino, but there are some drawbacks with using dynamicallytyped languages, as earlier mentioned in section 2.1.3. However, Kullberg [7]states that Clojure is a functional language suitable for parallel programing.

In perspective of these other languages, Scala is probably at least goodenough. Some of the reasons to use Scala in comparison with other JVMlanguages are delimited continuations, static typing with type inference,relative large adoption rate3, commercial support4, close integration withJava and performance comparable to Java.

7.3 Ideas for further investigation

Some questions and ideas have been raised during the investigation andimplementation parts of this thesis. Some of these ideas are possibly ofinterest for further investigation and are summarized here.

7.3.1 Remove transitions states in state machine

Is it possible and does it give any advantages to remove the explicit definitionof transition states in state machine part of the implementation?

2Article address is http://www.drdobbs.com/jvm/a-long-look-at-jvm-languages/

240007765 (accessed 2013-03-27).3Not compared to Java.4See Typesafe - http://typesafe.com/ (accessed 2013-03-27).

86

Page 103: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

7.3. IDEAS FOR FURTHER INVESTIGATION

One example is the toy example state machine implementation in classNetFsm, in listing D.5 on page 106. As it is right now in NetFsm, the transitionstates ATTACH and DETACH does not attribute much to the current state of theprotocol when the state machine is in transition in between the stable statesIDLE and CONNECTED. The behavior of the transition states ATTACH and DETACH

are almost equal to stable states IDLE and CONNECTED respectively. Further,in transition between IDLE and CONNECTED, the current state of the protocolare kept in the returned AP thunk passed around as optional data in thestate machine. There exists multiple ways to solve this.

One idea would to use the existing stable states or a single transitionstate for all transitions between stable states. The behavior to executewhen an AP has ended (i.e. returned a final value) can be sent as data ina tuple with the already sent AP thunk. In the toy example, this could berealized by letting NetFsm extend from

FSM[NetState, Option[(NetThunk, Behavior)]]

instead of as currently implemented, inherit from

FSM[NetState, Option[NetThunk]]

Another idea is that the removal of the transition states is somethingthat relates to the boundary between the SM and AP parts of the protocolrepresentation. If it turns out to be convenient to use the transition state,they could perhaps be implicitly defined by some type of SM-AP boundaryabstraction.

7.3.2 Complete protocol as an asynchronous procedure

Could the entire protocol be represented as an AP, instead of splitting therepresentation in a SM part and an AP part? This might have some devel-oper advantage, reducing the number techniques used when representing aprotocol and eliminating the border between SM and AP.

One technical detail relevant to this is how the CPS delimited continu-ations in Scala handles looping and/or tail recursion. Are there potentialproblems related to this?

7.3.3 Improve testing of asynchronous procedures

How can the testing of AP implementations be improved? In the toy ex-ample implementation evaluation in section 6.3, this stands out as an areawith room for improvement.

One problem is that the test specifications are hard to read. Should thetests be centered more around message passing instead of procedure calling?

Another problem is that the Mockito mock framework have problem withthe Scala type annotation related to the use of delimited continuations.Will the Scala type annotation problem be fixed in Mockito or are there

87

Page 104: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 7. DISCUSSION

other mock frameworks more suitable for the task? Can the test code beconstructed in another way that circumvents the problem in a better waythat it is implemented in the toy example?

7.3.4 Remote actors for even greater numbers of sim-ulated entities

The numbers of simulated entities is not something this thesis has put di-rect focus on. Not much information is given on the real world applicationcontext and the preconditions given in the initial investigation in section 3.

However, the use of the Akka framework gives great capabilities for bothconcurrency in a single JVM and distribution between multiple JVM onmultiple computer nodes in a network. Besides concurrently simulate manyUE in one JVM, this gives at least the possibility to also distribute thesimulated entities on multiple computers.

7.4 Thesis relevance and changing technolo-gies

This section tries to give some perspective on the relevance of the thesiswork.

Scala, Akka and other software are moving targets. During the thesiswork period, updates have been made many of the software tools used in thethesis. It seems that the development of Scala and the ecosystem aroundScala is quite active at the time of writing. Some of the software that havehad at least one new releases during the compilation of the thesis are Scala,Akka, ScalaTest and the Scala IDE plugin used in the Eclipse IDE.

New functionality is added and old functionality is removed in theseupdates. Some of the solutions found in this thesis might become obsoletein the future.

88

Page 105: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

Chapter 8

Conclusions

The conclusions in this chapter will focus three specific areas besides con-clusions related to the thesis goals.

As set out in the thesis goals, the thesis shows that it definitely is fea-sible to implement asynchronous protocols by using a state machine for afew stable states and using a procedure representation that hides away theasynchronous details of the protocol in between the stable states, withoutbeing blocking. In other words - Implementation of asynchronous protocolcan be done in Scala and Akka using a combination of SM and AP.

One way to implement this is shown with the help of an implementationbased on the toy example specification.

8.1 Representation of state machines

Multiple ways to represent state machines in Scala exists and have beenshown. Some generic ways of representing state machines are shown insection 4.1 and some Akka and Scala specific representations are shown insections 4.2 and 4.3.

8.2 Asyncronous procedure

This thesis shows that AP can be realized with use of Scala delimited con-tinuations.

8.2.1 AP usefulness

Based on the evaluation of the implementation, no definite claims can bemade on whether the AP representation is better and easier to work within the perspective of the developer. The opinion of the domain expert isalthough that this is so.

89

Page 106: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

CHAPTER 8. CONCLUSIONS

In some sense, the usefulness of the AP representation is relative. It canbe really handy in a new green field project, but can contain large investmentcosts for when transitioning from other technologies, as mentioned in theimplementation evaluation questions in appendix C.

The internal DSL section 4.3.2 and the syntax sugar class ThunkWrapper

in listing D.2 shows that there are features in Scala that help to shapethe syntax to suite the purpose. With the help of this flexibility in Scala,the use of AP can be tailored to suite different application areas and theconceptual models used by the developer. The attach methods on line 37-43 in listing D.9 shows how the basic AP implementation can be adaptedto something that looks very much similar to the actual attach methodspecification pseudo code in section 5.5.3.

8.2.2 AP performance

Based on the findings regarding the performance of the CPS-transformedScala code in section 4.5.1, no significant computational performance penaltyis added to using delimited continuations in Scala. Therefore, there shouldnot be any significant performance difference associated with the use of APin an protocol representation instead of using non-CPS-transformed codesuch as state machines or callback functions.

8.3 Akka

Based on claims made by others, Akka is clearly a much better alternativethan thread for enabling the capability to run many (thousands) of concur-rently asynchronous protocols with the purpose to simulate user equipment.

Further, based on the Akka capability to run on remote systems, it shouldbe able to simulate systems that are out of performance scope of a singleJVM computer node.

8.4 Results from delay test bench

Scheduling and delay techniques are of importance when dealing with asyn-chronous communication that need to contain mechanisms to trigger com-munication timeouts.

As seen in table 4.6 on page 49 there are four good ways to use scheduleror timeout delay, related to the Akka library. These are Akka FSM timer(FSMT), Akka FSM state timeout (FSMSTO), Akka scheduler (AS) and Akkareceive timeout (RTO).

Using a global Java timer (GJT) is the best choice when using a delaytechnique not related to Akka,

The types of delay technique to avoid are the use of a local Java timer(LJT), future await result (FAR) and thread sleep (TS). As shown in table

90

Page 107: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

8.5. CONCLUSIONS FROM IMPLEMENTATION EVALUATION

4.3, TS is the absolute worst technique to use.

8.5 Conclusions from implementation evalua-tion

The evaluation of the toy example implementation shows that there are someimplementation and testing details to improve to be easier to work with asa developer.

However, the implementation is a concrete implementation example thatdemonstrates the techniques searched for in this thesis. The implementationworks as a solid foundation for further advancements and other implemen-tations.

91

Page 108: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

Appendix A

Questions and answers ininitial investigation

This appendix contains some questions and answers to these questions. Thepurpose of the questions is to make an initial investigation of, and to getmore knowledge of the domain for the thesis work.

The questions are directed to people with domain knowledge, at the soft-ware consulting company (Xdin). In practice the thesis supervisor at thecompany (Mattias Evensson) is one of the few persons with good knowl-edge of the thesis context, and is therefore the single person answering thequestions.

Some questions did not get an answer and are therefore removed fromthe appendix. Because the questions are formulated with only superficialknowledge of the domain, it is probable that some of the questions withoutanswer were irrelevant or too hard to answer.

As seen in the questions and answers some information where alreadygiven at an earlier introduction to the thesis problem, but are implicitlyconfirmed by being included in the questions. Such information is the notionof the events OK, TIMEOUT and FAIL in these protocols.

Both the questions and answer are presented as is, in the original lan-guage (Swedish). Questions are in bold text with the original question num-bering.

A.1 Questions and answers in Swedish

Fraga 2

En del i att hitta en losning ar att veta vad losningen ska varaen losning till. Sen tidigare har jag information om att dessatillstandsmaskiner har vissa sardrag. De bestar av ett fa an-tal grundtillstand. Utover grundtillstanden, sa finns en mangd

92

Page 109: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

A.1. QUESTIONS AND ANSWERS IN SWEDISH

”overgangstillstand” for att overbrygga dessa grundtillstand. Mangaav overgangstillstanden hanterar asynkron kommunikation. Generelltsa kan ett asynkront anrop resultera i handelserna OK, TIMEOUToch FAIL. Finns det mera sardrag? Delar manga tillstand samma”event” eller samma ”action”? Finns det manga forgreningar,symmetrier eller langa procedurer av tillstand i tillstandsmaskinerna?

Den tillstandsmaskin vi har mest problem med ar NAS. NAS specengar att ladda ner fran: http://www.3gpp.org/ftp/Specs/archive/24_

series/24.301/24301-9a0.zip

Pa sidan 43 finns figur 5.1.3.2.2.7.1 som ar en grov skiss pa en tillstandsmaskinfor NAS. I figuren kan man se de fasta tillstanden EMM-DEREGISTERED ochEMM-REGISTERED samt procedurer for att ga mellan dem, ATTACH, SR (ServiceRequest), TAU (Tracking Area Update) och DETACH.

Sa dar har du huvudsardragen: nagra fa stabila tillstand och procedurermed asynkrona meddelanden for att ga mellan dem. Om man gar in pa merdetaljer sa finns det en del till sardrag:

• De stabila tillstanden kan delas in i undertillstand, se tex kapitel5.1.3.2.3 och 5.1.3.2.4.

• Procedurerna har en massa felfall som ska hanteras pa olika satt, setex 5.5.1.2.5 och 5.5.1.2.6 som beskriver felfall for attach.

• Under en procedur kan det startas subprocedurer, exempelvis sa kanen autentiseringsprocedur startas under attach, service request ochtracking area update.

Fraga 3

Finns det nagra typlosningar eller koncept som ar extra intres-santa att titta pa? (t.ex. tekniska mojligheter i Scala, mer allmannautvecklingskoncept, mentala tankeabstraktioner med mera)

Akka och continuations tror jag mycket pa. Min forhoppning ar att detgar att beskriva de fasta tillsanden plus eventuellt ett extra tillstand for varjeovergang/procedur med Akka’s FSM ramverk och att det med hjalp av texcontinuations gar att beskriva procedurerna sekventiellt, ex pa sekventiellprocedur i pseudokod:

def myProcedure() {

try {

send(new SetupLowerLayerReq());

resp = receive();

if (resp.result == FAIL)

throw new FailureException();

send(new MessageReq);

resp = receive();

if (resp.result == FAIL)

93

Page 110: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX A. QUESTIONS AND ANSWERS IN INITIALINVESTIGATION

throw new FailureException();

} catch (TimeoutException | FailureException) {

send(new TeardownLowerLayerReq());

resp = receive();

}

}

Fraga 5

Finns det nagra typer av tekniska begransningar att ta i beakt-ning? (t.ex. multi-/singeltradning, prestanda, kompatibilitet medmera)

Verktyget vi utvecklar simulerar 1000-tals UE:ar (mobiltelefoner). Saprestanda och skalbarhet ar viktigt. Erfarenheten vi har ar att det inte argorbart att anvanda en trad per UE, utan att ett antal UE:ar maste dela paen trad. Detta betyder att all kommunikation maste vara icke-blockerande.

Fraga 6

Finns det nagot behov av att grafiskt kunna visualisera tillstands-maskinerna? (t.ex. till dokumentation)

Det ar inte jatteviktigt. Som jag namnt ovan sa finns det figurer ispecarna, forhoppningen ar att implementationen ska bli sa lik/bra att detgar att anvanda de figurerna for visualisering.

Fraga 7

Om det finns problem med nuvarande (grafiska) losning, vad ardessa problem och ar dessa relaterade till specifikt program/verk-tyg eller till grafiska verktyg som generellt koncept?

Bade och, Unimod har en hel del tillkortakommanden som det antagli-gen finns andra verktyg som inte har. Tillstandsexplosionen som foljer avprocedurerna har jag dock svart att se att nagot grafiskt verktyg kan radabot pa. Darmed inte sagt att inte ett grafiskt verktyg skulle kunna fungerabra.

Fraga 8

Tidigare har det namnts att det bor vara latt att andra, lasa ochtesta tillstandsmaskinerna. Finns det aven andra saker som ar braatt fokusera pa?

Prestanda och skalbarhet ar viktigt, men jag tror inte att de ska varanagot storre problem. Tack vare att vi har sa manga UE:ar som ar oberoendeav varandra sa loser sig skalbarheten ratt latt, sa lange som losningen aricke-blockerande sa att flera UE:ar kan kora i samma trad.

94

Page 111: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

A.1. QUESTIONS AND ANSWERS IN SWEDISH

Fraga 9

Olika ord kan vara laddade med olika betydelse och de bety-delserna kan vara olika i olika sammanhang. Foljande tva fragorar stallda i kontext av att implementera tillstandsmaskiner i Scalapa Xdin.

Vad menas (enl. dig) med att kunna andra och lasa tillstands-maskinerna och har du nagra asikter om nar det ar latt?

Med lasa tillstandsmaskinerna menar jag att de ska vara latta att forstafor bade nya och gamla utvecklare.

Att implementera en hel standard ar ett jattejobb sa det kan vara lamligtatt borja med en delmangd och sedan succesivt utoka stodet, det ar en kallatill forandringar. En annan ar att standarden kontinuerligt utvecklas, sa attstodja en ny version medfor ocksa att forandringar behover goras. En tredjekalla till andringar ar rattning av fel.

Det jag menar med latt att andra ar alltsa att det ska vara latt att inforaden typen av forandringar. Hur man mater detta har jag inget svar pa.

Fraga 10

Vad menas (enl. dig) med att testa tillstandsmaskinerna och hardu nagra asikter om nar det ar latt eller hur det bor fungera?

Som jag ser det sa ar det sa finns det tva typer av tester som vi arintresserade av, scenariotester och unittester.

Scenariotesterna testar en viss sekvens av meddelanden/event tex en helattach-procedur foljd av en detach-procedur. Den typen av tester fungerarok i var nuvarande losning.

Unittester testar ett meddelande/event i ett tillstand. Den typen avtester fungerar inte bra i nuvarande losning. Det finns inget latt satt attsatta tillstandsmaskinen i ett visst tillstand, sa vi ar tvungna att ga igenomett helt scenario for att komma till ratt state. Detta gor testerna onodigtkomplicerade och langsamma.

95

Page 112: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

Appendix B

Notes fromimplementation evaluationsession

The following notes are from two evaluation sessions, done at 19 February2013, with the thesis supervisor at the company - Mattias Evensson. Thenotes are taken by me, thesis author, and thereby reflect my view of theevaluation session. The notes are retroactively cleaned up and contextualinformation is added, so the notes can be understood by other readers.The notes are originally written in Swedish but translated to English whencleaned up.

The evaluation sessions focus on the code in the toy example implementa-tion and source code details are discussed, so the following notes supposedlyhas the most value when compared to the actual implementation source codein appendix D.

B.1 The notes

The SM in class protocol.fsm.NetFSM

• The SM looks compact and nice. It is easy to understand.

• The states ATTACH and DETACH could possibly be renamed to ATTACH ONGOING

and DETACH ONGOING to emphasize the transitional nature of the states.

• It looks strange when using the attachBehavior method in the IDLE

state. Should just be something like goto(ATTACH) using procedures.powerOn().The same applies for detachBehavior in the CONNECTED state.

• A note about the partial function given to the function whenUnhandled

is that when an unexpected message is received, a log message is pro-

96

Page 113: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

B.1. THE NOTES

duced and the state machine makes a transition to the IDLE state.Normally the same is done in actual implementations, but with thedifference that the state machine stays in the same state (i.e. no tran-sition between states).

The interface between procedures and SM in class protocol.fsm.Procedures

• There is to much logic in the powerOn method. It would be better ifthe failure handling and the communication to the application layer isdelegated to the fsmProcedures instance used in Procedures.

The integration testing in class protocol.fsm.IntegrationTest

• It is not recommended to use Thread.sleep in test code.

• General impression of the integration tests is that they look really nice.It is obvious what the tests are doing and they are easy to read. Thisis how tests should look like. Even the error messages are good andeasy to understand.

Notes on procedure test specifications

• Generally the tests in the procedure specification test classes are hardto read. They are not as easy as the integration tests when it comesto how they are presented.

• In procedure specification test class protocol.procedure.CoreProcedureSpecit looks like there are a lot of repetitive code (code duplication) thatcan be improved.

Notes on code structure

• Some test specification uses the class protocol.fsm.FsmTestUtil.Fixtureas a test fixture. In these cases, it is not obvious that the second ar-gument in e.g. Fixture(idle,attach(input)) is the expected end state(in this case the attach state). In other words, it is not completelyclear that this actually is a verification of the end state.

• Sometimes it might not be completely clear what the difference be-tween the methods input and nondetInput in trait protocol.procedure.Environment,and in extension also the, in some procedures used, methods receiveExpectedand nondetReceive.

Notes on method and variable naming

• Many tests makes use of the name cut (class under test) and there areoften more suitable names as fsm.

97

Page 114: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX B. NOTES FROM IMPLEMENTATION EVALUATIONSESSION

• The related methods whenFail and recoverWith can be confusing. Ex-ample suggestions on alternative names are attempt and ifFail respec-tively.

• The prefix nondet in nondetInput and nondetReceive could be changedto another more descriptive prefix, like if or cond so e.g. nondetReceive

becomes ifReceive or condReceive.

98

Page 115: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

Appendix C

Questions and answers forimplementation evaluation

The purpose of the questions in this appendix is to, together with the eval-uation session notes in appendix B, make an evaluation of the resulting toyexample implementation.

Just as in the initial investigation in appendix A, the questions are an-swered by the thesis supervisor at the company (Mattias Evensson) andboth the questions and answer are presented as is, in the original language(Swedish). Questions are in bold text.

C.1 Questions and answers in Swedish

Fraga 1

Jag har forkortat “en Scala-implementation liknande exempelimple-mentationen” till S i alla fragor. Vad ar de storsta skillnadernamellan att anvanda S jamfort med Unimod eller andra Java-imple-mentationer?

Storsta skillnaden mot vad som ar mojligt att gora med Unimod ochJava-implementationer ar att procedurer med icke-blockerande I/O kan beskrivssekventiellt. Det ser i princip ut pa samma satt som nar man har blockerandeI/O i Java.

Om man i stallet jamfor med den implementation vi har, sa skulle jagsaga att storsta skillnaden ar uppdelningen i en FSM del plus ett antalprocedurer i stallet for allt i ett enda stort diagram. Fast det skulle ju hagatt att gora samma uppdelning med Unimod och andra Java-losningar.

Fraga 2

Vinster med att anvanda S?

99

Page 116: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX C. QUESTIONS AND ANSWERS FORIMPLEMENTATION EVALUATION

De vinster jag hoppas att S ska ge ar mer lattlast kod och mer lattlastatester. Med andra ord att det ska bli billigare att underhalla och vidareutvecklakoden.

Fraga 3 och 4

Problem med att anvanda S? Hur ar applicerbarheten for S i enverklig situation?

Det storsta problemet jag ser ar att portningen antagligen skulle ta rattlang tid och det ar inte uppenbart att det gar att gora den inkrementellt isma steg.

Fraga 5

Finns det nagra aspekter av ”verkliga implementationer” som intealls behandlas av S?

Nar jag specade upp vad din exempel implementation skulle innehalla saforsokte jag fa med alla de specialfall vi har i den “riktiga” implementatio-nen. Jag ar ratt saker pa att jag missat ett antal fall, men vilka det ar larman val fa se forst nar man forsoker sig pa att gora en skarp implementation.

100

Page 117: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

Appendix D

Toy exampleimplementation sourcecode

This appendix is divided up in three sections. Each section corresponds toa logical section in the toy example implementation code. The code in sec-tion D.1 shows the code that enables asynchronous procedures. The code insection D.2 shows the actual code that implements the toy example specifi-cation - in other words, the code that could be called the production code.The code in section D.3 shows the test code for the protocol implementa-tion, and is the code that asserts that the protocol implementation worksas expected.

D.1 Asynchronous procedures

This section shows the code that enables asynchronous procedures. Thiscode is very generic and is not tied to the toy example protocol in any way.The file Procedure.scala in listing D.1 contains all essential code while thefile ThunkWrapper.scala in listing D.2 contains helper code that makes theasynchronous procedure thunks easier to work with, via implicit conversionfrom the Procedure.Thunk type to the ThunkWrapper trait.

Code listing D.1: Source file thunkprocedure/Procedure.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package thunkprocedureshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import s c a l a . u t i l . c on t inua t i on s . r e s e tshowspacesshowspaces showspaces4 import s c a l a . u t i l . c on t inua t i on s . s h i f tshowspacesshowspaces showspaces5 import s c a l a . u t i l . c on t inua t i on s . cpsshowspacesshowspaces showspaces6

showspacesshowspaces showspaces7 /∗∗

101

Page 118: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX D. TOY EXAMPLE IMPLEMENTATION SOURCE CODE

showspacesshowspaces showspaces8 ∗ Helper object that makes using ProcedureRunner and Thunkshowspacesshowspaces showspaces9 ∗ easy .showspacesshowspaces showspaces10 ∗/showspacesshowspaces showspaces11 object Procedure {showspacesshowspaces showspaces12

showspacesshowspaces showspaces13 /∗∗ Recursive definition of continuation wrapper . ∗/showspacesshowspaces showspaces14 case class Input [ In , Out ] ( proceed : In => Thunk [ In , Out ] )showspacesshowspaces showspaces15

showspacesshowspaces showspaces16 /∗∗showspacesshowspaces showspaces17 ∗ A thunk i s either a procedure part waiting for input orshowspacesshowspaces showspaces18 ∗ a result value .showspacesshowspaces showspaces19 ∗/showspacesshowspaces showspaces20 type Thunk [ In , Out ] = Either [ Input [ In , Out ] , Out ]showspacesshowspaces showspaces21

showspacesshowspaces showspaces22 /∗∗showspacesshowspaces showspaces23 ∗ Wraps a thunk in a ThunkWrapper, to enable some syntaxshowspacesshowspaces showspaces24 ∗ sugar .showspacesshowspaces showspaces25 ∗/showspacesshowspaces showspaces26 implicit def wrapThunk [ In , Out ] (showspacesshowspaces showspaces27 t : Thunk [ In , Out ] ) : ThunkWrapper [ In , Out ] =showspacesshowspaces showspaces28 ThunkWrapper . wrapThunk( t )showspacesshowspaces showspaces29

showspacesshowspaces showspaces30 /∗∗ Quick way to create a procedure runner . ∗/showspacesshowspaces showspaces31 def createRunner [ In , Out ] : ProcedureRunner [ In , Out ] =showspacesshowspaces showspaces32 new RunnerImpl [ In , Out ] ( )showspacesshowspaces showspaces33 }showspacesshowspaces showspaces34

showspacesshowspaces showspaces35 /∗∗showspacesshowspaces showspaces36 ∗ Runs a code block and returns a Thunk whenshowspacesshowspaces showspaces37 ∗ input i s required or when code block returns .showspacesshowspaces showspaces38 ∗/showspacesshowspaces showspaces39 trait ProcedureRunner [ In , Out ] {showspacesshowspaces showspaces40 import Procedure . Thunkshowspacesshowspaces showspaces41 type T = Thunk [ In , Out ]showspacesshowspaces showspaces42

showspacesshowspaces showspaces43 /∗∗showspacesshowspaces showspaces44 ∗ Require input . I . e . pause , return thunk and wait untilshowspacesshowspaces showspaces45 ∗ input i s given to thunk .showspacesshowspaces showspaces46 ∗/showspacesshowspaces showspaces47 def input : In @cps [T]showspacesshowspaces showspaces48

showspacesshowspaces showspaces49 /∗∗ Runs the procedure given as parameter . ∗/showspacesshowspaces showspaces50 def apply ( procedure : => Out @cps [T] ) : Tshowspacesshowspaces showspaces51

showspacesshowspaces showspaces52 /∗∗ Called when terminating a procedure from within .∗/showspacesshowspaces showspaces53 def terminate ( r e s u l t : Out) : Nothing @cps [T]showspacesshowspaces showspaces54

showspacesshowspaces showspaces55 /∗∗ Runs a sub−procedure from within another procedure . ∗/showspacesshowspaces showspaces56 def runSubProcedure ( procedure : => Out @cps [T] ) : Out @cps [T]showspacesshowspaces showspaces57 }showspacesshowspaces showspaces58

showspacesshowspaces showspaces59 /∗∗ Implementation of ProcedureRunner . ∗/showspacesshowspaces showspaces60 private [ thunkprocedure ] class RunnerImpl [ In , Out ]showspacesshowspaces showspaces61 extends ProcedureRunner [ In , Out ] {showspacesshowspaces showspaces62

showspacesshowspaces showspaces63 import Procedure . Inputshowspacesshowspaces showspaces64

102

Page 119: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

D.1. ASYNCHRONOUS PROCEDURES

showspacesshowspaces showspaces65 def input = s h i f t { k : ( In => T) =>showspacesshowspaces showspaces66 Le f t ( Input [ In , Out ] ( k ) )showspacesshowspaces showspaces67 }showspacesshowspaces showspaces68

showspacesshowspaces showspaces69 def apply ( procedure : => Out @cps [T] ) =showspacesshowspaces showspaces70 r e s e t { Right ( procedure ) }showspacesshowspaces showspaces71

showspacesshowspaces showspaces72 def terminate ( r e s u l t : Out) =showspacesshowspaces showspaces73 s h i f t { k : ( Nothing => T) => Right ( r e s u l t ) }showspacesshowspaces showspaces74

showspacesshowspaces showspaces75 def runSubProcedure ( procedure : => Out @cps [T] ) = {showspacesshowspaces showspaces76

showspacesshowspaces showspaces77 def loop ( thunk : T) : Out @cps [T] =showspacesshowspaces showspaces78 i f ( thunk . hasResult ) thunk . f o r c e R e s u l tshowspacesshowspaces showspaces79 else loop ( thunk << input )showspacesshowspaces showspaces80

showspacesshowspaces showspaces81 loop ( apply { procedure })showspacesshowspaces showspaces82 }showspacesshowspaces showspaces83 }showspacesshowspaces

Code listing D.2: Source file thunkprocedure/ThunkWrapper.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package thunkprocedureshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import thunkprocedure . Procedure . Thunkshowspacesshowspaces showspaces4

showspacesshowspaces showspaces5 /∗∗ Enables some syntax sugar for thunks . ∗/showspacesshowspaces showspaces6 trait ThunkWrapper [ In , Out ] {showspacesshowspaces showspaces7 def i sWait ingForInput : Booleanshowspacesshowspaces showspaces8 def hasResult : Booleanshowspacesshowspaces showspaces9

showspacesshowspaces showspaces10 def f o r c e R e s u l t : Outshowspacesshowspaces showspaces11 def r e s u l t : Option [ Out ]showspacesshowspaces showspaces12 def thunk : Thunk [ In , Out ]showspacesshowspaces showspaces13

showspacesshowspaces showspaces14 /∗∗showspacesshowspaces showspaces15 ∗ Add input to thunk and return result from result−thunk .showspacesshowspaces showspaces16 ∗ To few input values wil l throw exception . Excessiveshowspacesshowspaces showspaces17 ∗ inputs wil l be ignored .showspacesshowspaces showspaces18 ∗/showspacesshowspaces showspaces19 def apply ( i n s : In ∗) : Outshowspacesshowspaces showspaces20

showspacesshowspaces showspaces21 /∗∗showspacesshowspaces showspaces22 ∗ Add input to thunk and return next thunk . Adding input toshowspacesshowspaces showspaces23 ∗ result−thunk wil l be ignored .showspacesshowspaces showspaces24 ∗/showspacesshowspaces showspaces25 def <<(in : In ) : Thunk [ In , Out ]showspacesshowspaces showspaces26

showspacesshowspaces showspaces27 }showspacesshowspaces showspaces28

showspacesshowspaces showspaces29 object ThunkWrapper {showspacesshowspaces showspaces30 implicit def wrapThunk [ In , Out ] (showspacesshowspaces showspaces31 t : Thunk [ In , Out ] ) : ThunkWrapper [ In , Out ] =showspacesshowspaces showspaces32 new ThunkWrapperImpl [ In , Out ] ( t )showspacesshowspaces showspaces33 }

103

Page 120: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX D. TOY EXAMPLE IMPLEMENTATION SOURCE CODE

showspacesshowspaces showspaces34

showspacesshowspaces showspaces35 case class ThunkWrapperImpl [ In , Out ] ( thunk : Thunk [ In , Out ] )showspacesshowspaces showspaces36 extends ThunkWrapper [ In , Out ] {showspacesshowspaces showspaces37 def i sWait ingForInput = thunk . i s L e f tshowspacesshowspaces showspaces38 def hasResult = thunk . i sR ightshowspacesshowspaces showspaces39 def f o r c e R e s u l t = thunk . r i g h t . getshowspacesshowspaces showspaces40

showspacesshowspaces showspaces41 f ina l def r e s u l t =showspacesshowspaces showspaces42 i f ( thunk . i sR ight ) Some( f o r c e R e s u l t )showspacesshowspaces showspaces43 else Noneshowspacesshowspaces showspaces44

showspacesshowspaces showspaces45 def <<(in : In ) =showspacesshowspaces showspaces46 i f ( thunk . i s L e f t ) thunk . l e f t . get . proceed ( in )showspacesshowspaces showspaces47 else thunkshowspacesshowspaces showspaces48

showspacesshowspaces showspaces49 def apply ( i n s : In ∗) =showspacesshowspaces showspaces50 i n s . f o l d L e f t ( thunk ) { << } f o r c e R e s u l tshowspacesshowspaces showspaces51 }showspacesshowspaces

D.2 Protocol definition

This section shows the actual code that implements the toy example defi-nition - in other words, the code that could be called the production code.The toy example protocol implementation consists of 13 source code files di-vided up in three Scala packages (i.e. three source tree folders), dependingon functionality.

Two files is used both the state machine part and the asynchronousprocedure part, and are therefore placed in the root folder protocol. Threefiles belong to the state machine part of the implementation and are placedin the folder protocol/fsm. Eight files belong to the asynchronous procedurepart of the implementation and are placed in the folder protocol/procedure.

D.2.1 Source code folder protocol

Code listing D.3: Source file protocol/Message.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co lshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 /∗∗showspacesshowspaces showspaces4 ∗ Messages between different protocol layers . Some messagesshowspacesshowspaces showspaces5 ∗ also have expl ic it unapply−methods to support patternshowspacesshowspaces showspaces6 ∗ matching .showspacesshowspaces showspaces7 ∗/showspacesshowspaces showspaces8 object Message {showspacesshowspaces showspaces9 val ATTACH ACCEPT = Attach ( Accept ( ) )showspacesshowspaces showspaces10 val ATTACH COMPLETE = Attach ( Complete ( ) )showspacesshowspaces showspaces11 val ATTACH REQUEST = Attach ( Request ( ) )showspacesshowspaces showspaces12 val ATTACH FAIL = Attach ( F a i l ( ) )showspacesshowspaces showspaces13 val AUTH FAIL = Authent icate ( Fa i l ( ) )

104

Page 121: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

D.2. PROTOCOL DEFINITION

showspacesshowspaces showspaces14 val AUTH RESPONSE = Authent icate ( Response ( ) )showspacesshowspaces showspaces15 val AUTH REJECT = Authent icate ( Reject ( ) )showspacesshowspaces showspaces16 val CONNECT = Connect ( Request ( ) )showspacesshowspaces showspaces17 val CONNECT DONE = Connect (Done ( ) )showspacesshowspaces showspaces18 val CONNECT FAIL = Connect ( Fa i l ( ) )showspacesshowspaces showspaces19 val DETACH ACCEPT = Detach ( Accept ( ) )showspacesshowspaces showspaces20 val DETACH COMPLETE = Detach ( Complete ( ) )showspacesshowspaces showspaces21 val DETACH REQUEST = Detach ( Request ( ) )showspacesshowspaces showspaces22 val DISCONNECT = Disconnect ( Request ( ) )showspacesshowspaces showspaces23 val DISCONNECT DONE = Disconnect (Done ( ) )showspacesshowspaces showspaces24 val POWER ON = PowerOn( Request ( ) )showspacesshowspaces showspaces25 val POWER ON DONE = PowerOn(Done ( ) )showspacesshowspaces showspaces26 val POWER ON FAIL = PowerOn( Fa i l ( ) )showspacesshowspaces showspaces27 val POWER OFF = PowerOff ( Request ( ) )showspacesshowspaces showspaces28 val POWER OFF DONE = PowerOff ( Request ( ) )showspacesshowspaces showspaces29 val SEND ACK = SendAck ( )showspacesshowspaces showspaces30 val SEND FAIL = SendFai l ( )showspacesshowspaces showspaces31

showspacesshowspaces showspaces32 val AUTH REQUEST = new {showspacesshowspaces showspaces33 def apply ( id : Int ) = Authent icate ( RequestWithId ( id ) )showspacesshowspaces showspaces34 def unapply (m: Message ) = m match {showspacesshowspaces showspaces35 case Authent icate ( RequestWithId ( id ) ) => Some( id )showspacesshowspaces showspaces36 case => Noneshowspacesshowspaces showspaces37 }showspacesshowspaces showspaces38 }showspacesshowspaces showspaces39

showspacesshowspaces showspaces40 val RECEIVE = new {showspacesshowspaces showspaces41 def apply ( payload : Message ) = Receive ( payload )showspacesshowspaces showspaces42 def unapply (m: Message ) = m match {showspacesshowspaces showspaces43 case Receive ( payload ) => Some( payload )showspacesshowspaces showspaces44 case => Noneshowspacesshowspaces showspaces45 }showspacesshowspaces showspaces46 }showspacesshowspaces showspaces47

showspacesshowspaces showspaces48 val SEND = new {showspacesshowspaces showspaces49 def apply ( payload : Message ) = Send ( payload )showspacesshowspaces showspaces50 def unapply (m: Message ) = m match {showspacesshowspaces showspaces51 case Send ( payload ) => Some( payload )showspacesshowspaces showspaces52 case => Noneshowspacesshowspaces showspaces53 }showspacesshowspaces showspaces54 }showspacesshowspaces showspaces55 }showspacesshowspaces showspaces56

showspacesshowspaces showspaces57 sealed trait Message {}showspacesshowspaces showspaces58

showspacesshowspaces showspaces59 case class Connect ( submessage : SubMessage ) extends Messageshowspacesshowspaces showspaces60 case class Disconnect ( submessage : SubMessage ) extends Messageshowspacesshowspaces showspaces61 case class Attach ( submessage : SubMessage ) extends Messageshowspacesshowspaces showspaces62 case class Authent icate ( submessage : SubMessage ) extends Messageshowspacesshowspaces showspaces63 case class Detach ( subMessage : SubMessage ) extends Messageshowspacesshowspaces showspaces64 case class PowerOn( submessage : SubMessage ) extends Messageshowspacesshowspaces showspaces65 case class PowerOff ( submessage : SubMessage ) extends Messageshowspacesshowspaces showspaces66 case class Receive ( payload : Message ) extends Messageshowspacesshowspaces showspaces67 case class Send ( payload : Message ) extends Messageshowspacesshowspaces showspaces68 case class SendAck ( ) extends Messageshowspacesshowspaces showspaces69 case class SendFai l ( ) extends Messageshowspacesshowspaces showspaces70

105

Page 122: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX D. TOY EXAMPLE IMPLEMENTATION SOURCE CODE

showspacesshowspaces showspaces71 sealed trait SubMessage {}showspacesshowspaces showspaces72

showspacesshowspaces showspaces73 case class Accept ( ) extends SubMessageshowspacesshowspaces showspaces74 case class Complete ( ) extends SubMessageshowspacesshowspaces showspaces75 case class Done ( ) extends SubMessageshowspacesshowspaces showspaces76 case class Fa i l ( ) extends SubMessageshowspacesshowspaces showspaces77 case class Reject ( ) extends SubMessageshowspacesshowspaces showspaces78 case class Response ( ) extends SubMessageshowspacesshowspaces showspaces79 case class Request ( ) extends SubMessageshowspacesshowspaces showspaces80 case class RequestWithId ( id : Int ) extends SubMessageshowspacesshowspaces

Code listing D.4: Source file protocol/Stratum.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co lshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 /∗∗ Interface used for other protocol layers . ∗/showspacesshowspaces showspaces4 trait Stratum {showspacesshowspaces showspaces5

showspacesshowspaces showspaces6 /∗∗ Sends a message to other protocol layer . ∗/showspacesshowspaces showspaces7 def output ( message : Message ) : Unitshowspacesshowspaces showspaces8

showspacesshowspaces showspaces9 }showspacesshowspaces

D.2.2 Source code folder protocol/fsm

Code listing D.5: Source file protocol/fsm/NetFsm.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co l . fsmshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import s c a l a . concurrent . durat ion . Durat ionIntshowspacesshowspaces showspaces4

showspacesshowspaces showspaces5 import NetState .ATTACHshowspacesshowspaces showspaces6 import NetState .CONNECTEDshowspacesshowspaces showspaces7 import NetState .DETACHshowspacesshowspaces showspaces8 import NetState . IDLEshowspacesshowspaces showspaces9 import akka . ac to r . Actorshowspacesshowspaces showspaces10 import akka . ac to r .FSMshowspacesshowspaces showspaces11 import pro to co l . Messageshowspacesshowspaces showspaces12 import pro to co l . Message .DETACH REQUESTshowspacesshowspaces showspaces13 import pro to co l . Message .POWER OFFshowspacesshowspaces showspaces14 import pro to co l . Message .POWER ONshowspacesshowspaces showspaces15 import pro to co l . procedure . NetThunkshowspacesshowspaces showspaces16 import pro to co l . procedure . ThunkSugar . ProcedureFa i lureshowspacesshowspaces showspaces17 import pro to co l . procedure . ThunkSugar . ProcedureInputshowspacesshowspaces showspaces18 import pro to co l . procedure . ThunkSugar . ProcedureSuccessshowspacesshowspaces showspaces19 import thunkprocedure . Procedure . wrapThunkshowspacesshowspaces showspaces20

showspacesshowspaces showspaces21 /∗∗showspacesshowspaces showspaces22 ∗ Implementation of the Net−layer FSM, as an actor and theshowspacesshowspaces showspaces23 ∗ FSM DSL.showspacesshowspaces showspaces24 ∗/

106

Page 123: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

D.2. PROTOCOL DEFINITION

showspacesshowspaces showspaces25 class NetFsm( procedures : Procedures ) extends Actorshowspacesshowspaces showspaces26 with FSM[ NetState , Option [ NetThunk ] ] {showspacesshowspaces showspaces27

showspacesshowspaces showspaces28 type Behavior = Part ia lFunct ion [ NetThunk , State ]showspacesshowspaces showspaces29 val t imeout = 1 secondshowspacesshowspaces showspaces30

showspacesshowspaces showspaces31 val attachBehavior : Behavior = {showspacesshowspaces showspaces32 case ProcedureInput ( thunk ) =>showspacesshowspaces showspaces33 goto (ATTACH) us ing Some( thunk ) forMax timeoutshowspacesshowspaces showspaces34 case ProcedureSuccess ( ) => goto (CONNECTED) us ing Noneshowspacesshowspaces showspaces35 case ProcedureFa i lure ( ) => goto (IDLE) us ing Noneshowspacesshowspaces showspaces36 }showspacesshowspaces showspaces37

showspacesshowspaces showspaces38 val detachBehavior : Behavior = {showspacesshowspaces showspaces39 case ProcedureInput ( thunk ) =>showspacesshowspaces showspaces40 goto (DETACH) us ing Some( thunk ) forMax timeoutshowspacesshowspaces showspaces41 case ProcedureSuccess ( ) => goto (IDLE) us ing Noneshowspacesshowspaces showspaces42 case ProcedureFa i lure ( ) => goto (IDLE) us ing Noneshowspacesshowspaces showspaces43 }showspacesshowspaces showspaces44

showspacesshowspaces showspaces45 startWith (IDLE , None )showspacesshowspaces showspaces46

showspacesshowspaces showspaces47 when(IDLE) {showspacesshowspaces showspaces48 case Event ( ‘POWER ON‘ , ) =>showspacesshowspaces showspaces49 attachBehavior ( procedures . powerOn ( ) )showspacesshowspaces showspaces50 case Event ( message , ) => goto (IDLE) us ing Noneshowspacesshowspaces showspaces51 }showspacesshowspaces showspaces52

showspacesshowspaces showspaces53 when(ATTACH) {showspacesshowspaces showspaces54 case Event (msg : Message , Some( thunk ) ) =>showspacesshowspaces showspaces55 attachBehavior ( thunk << msg)showspacesshowspaces showspaces56 }showspacesshowspaces showspaces57

showspacesshowspaces showspaces58 when(CONNECTED) {showspacesshowspaces showspaces59 case Event ( ‘POWER OFF‘ , ) =>showspacesshowspaces showspaces60 detachBehavior ( procedures . powerOff ( ) )showspacesshowspaces showspaces61 case Event ( ‘DETACH REQUEST‘ , ) =>showspacesshowspaces showspaces62 detachBehavior ( procedures . forcedDetach ( ) )showspacesshowspaces showspaces63 }showspacesshowspaces showspaces64

showspacesshowspaces showspaces65 when(DETACH) {showspacesshowspaces showspaces66 case Event (msg : Message , Some( thunk ) ) =>showspacesshowspaces showspaces67 detachBehavior ( thunk << msg)showspacesshowspaces showspaces68 }showspacesshowspaces showspaces69

showspacesshowspaces showspaces70 whenUnhandled {showspacesshowspaces showspaces71 case Event ( StateTimeout , ) => goto (IDLE) us ing Noneshowspacesshowspaces showspaces72 case Event ( message , ) =>showspacesshowspaces showspaces73 l og . warning ( ”Unhandled message {} in {}” ,showspacesshowspaces showspaces74 message , stateName )showspacesshowspaces showspaces75 goto (IDLE) us ing Noneshowspacesshowspaces showspaces76 }showspacesshowspaces showspaces77 }showspacesshowspaces

Code listing D.6: Source file protocol/fsm/NetState.scala

107

Page 124: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX D. TOY EXAMPLE IMPLEMENTATION SOURCE CODE

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co l . fsmshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 /∗∗ The state in the Net FSM. ∗/showspacesshowspaces showspaces4 object NetState {showspacesshowspaces showspaces5 val IDLE = I d l e ( )showspacesshowspaces showspaces6 val CONNECTED = Connected ( )showspacesshowspaces showspaces7 val ATTACH = Attach ( )showspacesshowspaces showspaces8 val DETACH = Detach ( )showspacesshowspaces showspaces9 }showspacesshowspaces showspaces10

showspacesshowspaces showspaces11 sealed trait NetStateshowspacesshowspaces showspaces12 case class I d l e ( ) extends NetStateshowspacesshowspaces showspaces13 case class Connected ( ) extends NetStateshowspacesshowspaces showspaces14 case class Attach ( ) extends NetStateshowspacesshowspaces showspaces15 case class Detach ( ) extends NetStateshowspacesshowspaces

Code listing D.7: Source file protocol/fsm/Procedures.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co l . fsmshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import pro to co l . Messageshowspacesshowspaces showspaces4 import pro to co l . Message .POWER OFF DONEshowspacesshowspaces showspaces5 import pro to co l . Message .POWER ON DONEshowspacesshowspaces showspaces6 import pro to co l . Message .POWER ON FAILshowspacesshowspaces showspaces7 import pro to co l . Stratumshowspacesshowspaces showspaces8 import pro to co l . procedure . AuthProceduresImplshowspacesshowspaces showspaces9 import pro to co l . procedure . CoreProceduresImplshowspacesshowspaces showspaces10 import pro to co l . procedure . EnvironmentImplshowspacesshowspaces showspaces11 import pro to co l . procedure . FsmProceduresImplshowspacesshowspaces showspaces12 import pro to co l . procedure . NetThunkshowspacesshowspaces showspaces13 import pro to co l . procedure . Pr imit iveProcedures Implshowspacesshowspaces showspaces14 import thunkprocedure . Procedure . createRunnershowspacesshowspaces showspaces15

showspacesshowspaces showspaces16 /∗∗showspacesshowspaces showspaces17 ∗ Procedures used by the Net FSM. It i s related toshowspacesshowspaces showspaces18 ∗ FsmProcedures , but does not contain any sign of CPS−showspacesshowspaces showspaces19 ∗ annotations and are therefore mockable in tests .showspacesshowspaces showspaces20 ∗showspacesshowspaces showspaces21 ∗ Also , in relation to FsmProcedures , Procedures are extendedshowspacesshowspaces showspaces22 ∗ to suite the context of the messages in the Net FSM thatshowspacesshowspaces showspaces23 ∗ triggers these procedures and sends back answers to theshowspacesshowspaces showspaces24 ∗ application layer .showspacesshowspaces showspaces25 ∗/showspacesshowspaces showspaces26 trait Procedures {showspacesshowspaces showspaces27 def powerOn ( ) : NetThunkshowspacesshowspaces showspaces28 def powerOff ( ) : NetThunkshowspacesshowspaces showspaces29 def forcedDetach ( ) : NetThunkshowspacesshowspaces showspaces30 }showspacesshowspaces showspaces31

showspacesshowspaces showspaces32 class ProceduresImpl ( rad io : Stratum , appl : Stratum )showspacesshowspaces showspaces33 extends Procedures {showspacesshowspaces showspaces34

showspacesshowspaces showspaces35 private val env =showspacesshowspaces showspaces36 new EnvironmentImpl ( createRunner [ Message , Boolean ] )

108

Page 125: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

D.2. PROTOCOL DEFINITION

showspacesshowspaces showspaces37

showspacesshowspaces showspaces38 private val fsmProcedures = {showspacesshowspaces showspaces39 val prim = new Primit iveProcedures Impl ( env , radio , appl )showspacesshowspaces showspaces40 val auth = new AuthProceduresImpl ( env , prim )showspacesshowspaces showspaces41 val core = new CoreProceduresImpl ( env , prim , auth )showspacesshowspaces showspaces42 new FsmProceduresImpl ( env , prim , core )showspacesshowspaces showspaces43 }showspacesshowspaces showspaces44

showspacesshowspaces showspaces45 def powerOn ( ) = env {showspacesshowspaces showspaces46 env . whenFail {showspacesshowspaces showspaces47 fsmProcedures . powerOn ( )showspacesshowspaces showspaces48 } recoverWith {showspacesshowspaces showspaces49 appl . output (POWER ON FAIL)showspacesshowspaces showspaces50 }showspacesshowspaces showspaces51 appl . output (POWER ON DONE)showspacesshowspaces showspaces52 }showspacesshowspaces showspaces53

showspacesshowspaces showspaces54 def powerOff ( ) = env {showspacesshowspaces showspaces55 fsmProcedures . powerOff ( )showspacesshowspaces showspaces56 appl . output (POWER OFF DONE)showspacesshowspaces showspaces57 }showspacesshowspaces showspaces58

showspacesshowspaces showspaces59 def forcedDetach ( ) = env ( fsmProcedures . forcedDetach ( ) )showspacesshowspaces showspaces60

showspacesshowspaces showspaces61 }showspacesshowspaces

D.2.3 Source code folder protocol/procedure

Code listing D.8: Source file protocol/procedure/AuthProcedures.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co l . procedureshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import s c a l a . u t i l . c on t inua t i on s . cpsshowspacesshowspaces showspaces4

showspacesshowspaces showspaces5 import pro to co l . Message .AUTH FAILshowspacesshowspaces showspaces6 import pro to co l . Message .AUTH REJECTshowspacesshowspaces showspaces7 import pro to co l . Message .AUTH REQUESTshowspacesshowspaces showspaces8 import pro to co l . Message .AUTH RESPONSEshowspacesshowspaces showspaces9 import pro to co l . Message .RECEIVEshowspacesshowspaces showspaces10

showspacesshowspaces showspaces11 trait AuthProcedures {showspacesshowspaces showspaces12

showspacesshowspaces showspaces13 /∗∗ Authenticates the UE i f authentication i s required . ∗/showspacesshowspaces showspaces14 def au then t i c a t i on ( ) : Unit @cps [ NetThunk ]showspacesshowspaces showspaces15 }showspacesshowspaces showspaces16

showspacesshowspaces showspaces17 /∗∗showspacesshowspaces showspaces18 ∗ Implementation where auth . request ID is regarded as validshowspacesshowspaces showspaces19 ∗ when i t i s even .showspacesshowspaces showspaces20 ∗/showspacesshowspaces showspaces21 class AuthProceduresImpl (showspacesshowspaces showspaces22 environment : Environment ,showspacesshowspaces showspaces23 pr imi t i veProcedure s : Pr imi t iveProcedures )

109

Page 126: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX D. TOY EXAMPLE IMPLEMENTATION SOURCE CODE

showspacesshowspaces showspaces24 extends AuthProcedures {showspacesshowspaces showspaces25

showspacesshowspaces showspaces26 import pr imi t i veProcedure s .showspacesshowspaces showspaces27 import environment .showspacesshowspaces showspaces28 def nondetReceive = NondetReceiveSugar ( environment )showspacesshowspaces showspaces29

showspacesshowspaces showspaces30 def au then t i c a t i on ( ) =showspacesshowspaces showspaces31 nondetReceive {showspacesshowspaces showspaces32 case AUTH REQUEST( id ) i f shouldAuthent icate ( id ) =>showspacesshowspaces showspaces33 send (AUTH RESPONSE)showspacesshowspaces showspaces34 nondetReceive { case AUTH REJECT => f a i l u r e ( ) }showspacesshowspaces showspaces35 case AUTH REQUEST( id ) i f ! shou ldAuthent icate ( id ) =>showspacesshowspaces showspaces36 send (AUTH FAIL)showspacesshowspaces showspaces37 f a i l u r e ( )showspacesshowspaces showspaces38 }showspacesshowspaces showspaces39

showspacesshowspaces showspaces40 private def shouldAuthent icate ( id : Int ) =showspacesshowspaces showspaces41 ( id % 2) == 0 // i s evenshowspacesshowspaces showspaces42

showspacesshowspaces showspaces43 }showspacesshowspaces

Code listing D.9: Source file protocol/procedure/CoreProcedures.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co l . procedureshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import s c a l a . u t i l . c on t inua t i on s . cpsshowspacesshowspaces showspaces4

showspacesshowspaces showspaces5 import pro to co l . Message .ATTACH ACCEPTshowspacesshowspaces showspaces6 import pro to co l . Message .ATTACH COMPLETEshowspacesshowspaces showspaces7 import pro to co l . Message .ATTACH FAILshowspacesshowspaces showspaces8 import pro to co l . Message .ATTACH REQUESTshowspacesshowspaces showspaces9 import pro to co l . Message .DETACH COMPLETEshowspacesshowspaces showspaces10 import pro to co l . Message .DETACH REQUESTshowspacesshowspaces showspaces11

showspacesshowspaces showspaces12 trait CoreProcedures {showspacesshowspaces showspaces13

showspacesshowspaces showspaces14 /∗∗showspacesshowspaces showspaces15 ∗ Attaches the UE to Net core , via messages to Radio layer .showspacesshowspaces showspaces16 ∗/showspacesshowspaces showspaces17 def attach ( ) : Unit @cps [ NetThunk ]showspacesshowspaces showspaces18

showspacesshowspaces showspaces19 /∗∗showspacesshowspaces showspaces20 ∗ Detaches the UE from the Net core , via messages to Radioshowspacesshowspaces showspaces21 ∗ layer .showspacesshowspaces showspaces22 ∗/showspacesshowspaces showspaces23 def detach ( ) : Unit @cps [ NetThunk ]showspacesshowspaces showspaces24 }showspacesshowspaces showspaces25

showspacesshowspaces showspaces26 class CoreProceduresImpl (showspacesshowspaces showspaces27 env : Environment ,showspacesshowspaces showspaces28 pr imi t i veProcedure s : Pr imit iveProcedures ,showspacesshowspaces showspaces29 authProcedures : AuthProcedures )showspacesshowspaces showspaces30 extends CoreProcedures {showspacesshowspaces showspaces31

showspacesshowspaces showspaces32 import pr imi t i veProcedure s .

110

Page 127: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

D.2. PROTOCOL DEFINITION

showspacesshowspaces showspaces33 import authProcedures .showspacesshowspaces showspaces34 import env .showspacesshowspaces showspaces35 def nondetReceive = NondetReceiveSugar ( env )showspacesshowspaces showspaces36

showspacesshowspaces showspaces37 def attach ( ) = {showspacesshowspaces showspaces38 send (ATTACH REQUEST)showspacesshowspaces showspaces39 nondetReceive { case ATTACH FAIL => f a i l u r e ( ) }showspacesshowspaces showspaces40 au then t i c a t i on ( )showspacesshowspaces showspaces41 rece iveExpected (ATTACH ACCEPT)showspacesshowspaces showspaces42 send (ATTACH COMPLETE)showspacesshowspaces showspaces43 }showspacesshowspaces showspaces44

showspacesshowspaces showspaces45 def detach ( ) = {showspacesshowspaces showspaces46 send (DETACH REQUEST)showspacesshowspaces showspaces47 rece iveExpected (DETACH COMPLETE)showspacesshowspaces showspaces48 }showspacesshowspaces showspaces49 }showspacesshowspaces

Code listing D.10: Source file protocol/procedure/Environment.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co l . procedureshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import u t i l . c on t inua t i on s . cpsshowspacesshowspaces showspaces4 import pro to co l . Messageshowspacesshowspaces showspaces5 import s c a l a . c o l l e c t i o n . mutable . Queueshowspacesshowspaces showspaces6

showspacesshowspaces showspaces7 /∗∗showspacesshowspaces showspaces8 ∗ An abstraction on top of bare thunk procedures , toshowspacesshowspaces showspaces9 ∗ f a c i l i t a te the functionality needed by the procedures .showspacesshowspaces showspaces10 ∗/showspacesshowspaces showspaces11 trait Environment {showspacesshowspaces showspaces12

showspacesshowspaces showspaces13 /∗∗ The underlying procedure runner . ∗/showspacesshowspaces showspaces14 protected def runner : NetProcedureRunnershowspacesshowspaces showspaces15

showspacesshowspaces showspaces16 /∗∗showspacesshowspaces showspaces17 ∗ Wait for any message given to this environment fromshowspacesshowspaces showspaces18 ∗ other layers .showspacesshowspaces showspaces19 ∗/showspacesshowspaces showspaces20 def input ( ) : Message @cps [ NetThunk ]showspacesshowspaces showspaces21

showspacesshowspaces showspaces22 /∗∗ Run a Net procedure . ∗/showspacesshowspaces showspaces23 def apply ( procedure : => Unit @cps [ NetThunk ] ) : NetThunkshowspacesshowspaces showspaces24

showspacesshowspaces showspaces25 /∗∗showspacesshowspaces showspaces26 ∗ This method takes a partial ly applicable procedure (P)showspacesshowspaces showspaces27 ∗ as parameter . P wil l be executed when ( i f ) the nextshowspacesshowspaces showspaces28 ∗ input matches the range of inputs that P i s defined for .showspacesshowspaces showspaces29 ∗showspacesshowspaces showspaces30 ∗ P is tested for applicabil ity for input when the nextshowspacesshowspaces showspaces31 ∗ ca l l to the receive method [1 ] i s made. I f P i sshowspacesshowspaces showspaces32 ∗ applicable for the input at next ca l l to the receiveshowspacesshowspaces showspaces33 ∗ method, P i s applied with the received input .showspacesshowspaces showspaces34 ∗showspacesshowspaces showspaces35 ∗ No matter whether P i s defined for the input or not

111

Page 128: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX D. TOY EXAMPLE IMPLEMENTATION SOURCE CODE

showspacesshowspaces showspaces36 ∗ ( i . e . in both cases ) , procedure P regarded as usedshowspacesshowspaces showspaces37 ∗ (consumed) and i s thrown away after input i s tested onshowspacesshowspaces showspaces38 ∗ i t .showspacesshowspaces showspaces39 ∗showspacesshowspaces showspaces40 ∗ I f the input message i s applicable on P, also theshowspacesshowspaces showspaces41 ∗ message wil l be consumed and another input message i sshowspacesshowspaces showspaces42 ∗ required for further processing of partial proceduresshowspacesshowspaces showspaces43 ∗ and the f ina l receive ca l l . Partial procedure wil l beshowspacesshowspaces showspaces44 ∗ matched in the order they are added via the nondetReceiveshowspacesshowspaces showspaces45 ∗ method.showspacesshowspaces showspaces46 ∗showspacesshowspaces showspaces47 ∗ All fa i lures ( terminations) triggered inside a partialshowspacesshowspaces showspaces48 ∗ procedure P wil l propagate .showspacesshowspaces showspaces49 ∗showspacesshowspaces showspaces50 ∗ [ 1 ] i . e . when a deterministic input i s expected .showspacesshowspaces showspaces51 ∗/showspacesshowspaces showspaces52 def nondetInput ( partProc : PartProc ) : Unitshowspacesshowspaces showspaces53

showspacesshowspaces showspaces54 /∗∗showspacesshowspaces showspaces55 ∗ Invokes a procedure fa i lure . It terminates the procedureshowspacesshowspaces showspaces56 ∗ execution and returns fa l se . This can be compared toshowspacesshowspaces showspaces57 ∗ throwing an exception and a catch block that returnsshowspacesshowspaces showspaces58 ∗ fa l se .showspacesshowspaces showspaces59 ∗/showspacesshowspaces showspaces60 def f a i l u r e ( ) : Nothing @cps [ NetThunk ]showspacesshowspaces showspaces61

showspacesshowspaces showspaces62 /∗∗showspacesshowspaces showspaces63 ∗ Enables to run sub procedures and handle fai lure , i . eshowspacesshowspaces showspaces64 ∗ when sub−procedure returns fa l se . Does not run sub−showspacesshowspaces showspaces65 ∗ procedure , only defines i t in a RecoverExecutor .showspacesshowspaces showspaces66 ∗/showspacesshowspaces showspaces67 def whenFail ( a : => Unit @cps [ NetThunk ] ) : RecoverExecutorshowspacesshowspaces showspaces68 }showspacesshowspaces showspaces69

showspacesshowspaces showspaces70 /∗∗ Implements basic features of environment . ∗/showspacesshowspaces showspaces71 trait EnvironmentBasics extends Environment {showspacesshowspaces showspaces72 def f a i l u r e ( ) = runner . terminate ( f a i l e d P r o c e d u r e )showspacesshowspaces showspaces73 def input ( ) = runner . inputshowspacesshowspaces showspaces74

showspacesshowspaces showspaces75 def apply ( procedure : => Unit @cps [ NetThunk ] ) = runner {showspacesshowspaces showspaces76 procedureshowspacesshowspaces showspaces77 s u c c e s s f u l P r oc e d u r eshowspacesshowspaces showspaces78 }showspacesshowspaces showspaces79 }showspacesshowspaces showspaces80

showspacesshowspaces showspaces81 /∗∗ Entity returned from whenFail−block . ∗/showspacesshowspaces showspaces82 trait RecoverExecutor {showspacesshowspaces showspaces83 /∗∗ Defines recover code and executes sub−procedure . ∗/showspacesshowspaces showspaces84 def recoverWith (showspacesshowspaces showspaces85 b : => Unit @cps [ NetThunk ] ) : Unit @cps [ NetThunk ]showspacesshowspaces showspaces86 }showspacesshowspaces showspaces87

showspacesshowspaces showspaces88 /∗∗showspacesshowspaces showspaces89 ∗ Handles fa i lure recovery . Implements the recovery of fa i ledshowspacesshowspaces showspaces90 ∗ sub−procedures , together with RecoverExecutor .showspacesshowspaces showspaces91 ∗/showspacesshowspaces showspaces92 trait Fai lRecover extends Environment {

112

Page 129: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

D.2. PROTOCOL DEFINITION

showspacesshowspaces showspaces93

showspacesshowspaces showspaces94 def whenFail ( a : => Unit @cps [ NetThunk ] ) =showspacesshowspaces showspaces95 new RecoverExecutorImpl ({ a } , runner )showspacesshowspaces showspaces96

showspacesshowspaces showspaces97 class RecoverExecutorImpl (showspacesshowspaces showspaces98 primaryProcedure : => Unit @cps [ NetThunk ] ,showspacesshowspaces showspaces99 runner : NetProcedureRunner )showspacesshowspaces showspaces100 extends RecoverExecutor {showspacesshowspaces showspaces101

showspacesshowspaces showspaces102 def recoverWith (showspacesshowspaces showspaces103 secondaryProcedure : => Unit @cps [ NetThunk ] ) : Unit @cps [showspacesshowspaces showspacesNetThunk ] = {showspacesshowspaces showspaces104

showspacesshowspaces showspaces105 val successWithPrimary =showspacesshowspaces showspaces106 runner . runSubProcedure {showspacesshowspaces showspaces107 primaryProcedureshowspacesshowspaces showspaces108 s u c c e s s f u l P r oc e d u r eshowspacesshowspaces showspaces109 }showspacesshowspaces showspaces110

showspacesshowspaces showspaces111 i f ( ! successWithPrimary ) {showspacesshowspaces showspaces112 secondaryProcedureshowspacesshowspaces showspaces113 f a i l u r eshowspacesshowspaces showspaces114 }showspacesshowspaces showspaces115 }showspacesshowspaces showspaces116 }showspacesshowspaces showspaces117 }showspacesshowspaces showspaces118

showspacesshowspaces showspaces119 /∗∗ Implements the nondeterministic receive functionality . ∗/showspacesshowspaces showspaces120 trait NondetInput extends Environment {showspacesshowspaces showspaces121 private val nondetQueue = Queue [ PartProc ] ( )showspacesshowspaces showspaces122

showspacesshowspaces showspaces123 private def f indInNondet (showspacesshowspaces showspaces124 message : Message ) : Message @cps [ NetThunk ] =showspacesshowspaces showspaces125

showspacesshowspaces showspaces126 i f ( nondetQueue . isEmpty ) messageshowspacesshowspaces showspaces127 else {showspacesshowspaces showspaces128 val pFunc = nondetQueue . dequeueshowspacesshowspaces showspaces129 val nextMessage =showspacesshowspaces showspaces130 i f ( pFunc . i sDef inedAt ( message ) ) {showspacesshowspaces showspaces131 pFunc . apply ( message )showspacesshowspaces showspaces132 runner . inputshowspacesshowspaces showspaces133 } else messageshowspacesshowspaces showspaces134

showspacesshowspaces showspaces135 f indInNondet ( nextMessage )showspacesshowspaces showspaces136 }showspacesshowspaces showspaces137

showspacesshowspaces showspaces138 abstract override def input ( ) = findInNondet ( super . input ( ) )showspacesshowspaces showspaces139

showspacesshowspaces showspaces140 def nondetInput ( partProc : PartProc ) : Unit = {showspacesshowspaces showspaces141 nondetQueue += partProcshowspacesshowspaces showspaces142 ( )showspacesshowspaces showspaces143 }showspacesshowspaces showspaces144

showspacesshowspaces showspaces145 }showspacesshowspaces showspaces146

showspacesshowspaces showspaces147 /∗∗showspacesshowspaces showspaces148 ∗ Contains a complete implementation for Environment , using

113

Page 130: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX D. TOY EXAMPLE IMPLEMENTATION SOURCE CODE

showspacesshowspaces showspaces149 ∗ multiple partial ly implemented traits .showspacesshowspaces showspaces150 ∗/showspacesshowspaces showspaces151 class EnvironmentImpl ( val runner : NetProcedureRunner )showspacesshowspaces showspaces152 extends Environmentshowspacesshowspaces showspaces153 with EnvironmentBasicsshowspacesshowspaces showspaces154 with Fai lRecovershowspacesshowspaces showspaces155 with NondetInput {}showspacesshowspaces

Code listing D.11: Source file protocol/procedure/FsmProcedures.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co l . procedureshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import s c a l a . u t i l . c on t inua t i on s . cpsshowspacesshowspaces showspaces4

showspacesshowspaces showspaces5 import pro to co l . Message .DETACH ACCEPTshowspacesshowspaces showspaces6

showspacesshowspaces showspaces7 trait FsmProcedures {showspacesshowspaces showspaces8

showspacesshowspaces showspaces9 /∗∗ Powers on everything from Net layer and down. ∗/showspacesshowspaces showspaces10 def powerOn ( ) : Unit @cps [ NetThunk ]showspacesshowspaces showspaces11

showspacesshowspaces showspaces12 /∗∗ Powers of f everything from Net layer and down. ∗/showspacesshowspaces showspaces13 def powerOff ( ) : Unit @cps [ NetThunk ]showspacesshowspaces showspaces14

showspacesshowspaces showspaces15 /∗∗ Powers of f after net core forced UE to detach . ∗/showspacesshowspaces showspaces16 def forcedDetach ( ) : Unit @cps [ NetThunk ]showspacesshowspaces showspaces17 }showspacesshowspaces showspaces18

showspacesshowspaces showspaces19 class FsmProceduresImpl (showspacesshowspaces showspaces20 env : Environment ,showspacesshowspaces showspaces21 p r i m i t i v e s : Pr imit iveProcedures ,showspacesshowspaces showspaces22 core : CoreProcedures )showspacesshowspaces showspaces23 extends FsmProcedures {showspacesshowspaces showspaces24

showspacesshowspaces showspaces25 import p r i m i t i v e s .showspacesshowspaces showspaces26 import core .showspacesshowspaces showspaces27 import env .showspacesshowspaces showspaces28

showspacesshowspaces showspaces29 def powerOn ( ) = {showspacesshowspaces showspaces30 connect ( )showspacesshowspaces showspaces31

showspacesshowspaces showspaces32 whenFail {showspacesshowspaces showspaces33 attach ( )showspacesshowspaces showspaces34 } recoverWith {showspacesshowspaces showspaces35 d i s connec t ( )showspacesshowspaces showspaces36 }showspacesshowspaces showspaces37 }showspacesshowspaces showspaces38

showspacesshowspaces showspaces39 def powerOff ( ) = {showspacesshowspaces showspaces40 detach ( )showspacesshowspaces showspaces41 d i s connec t ( )showspacesshowspaces showspaces42 }showspacesshowspaces showspaces43

showspacesshowspaces showspaces44 def forcedDetach ( ) = {showspacesshowspaces showspaces45 send (DETACH ACCEPT)

114

Page 131: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

D.2. PROTOCOL DEFINITION

showspacesshowspaces showspaces46 d i s connec t ( )showspacesshowspaces showspaces47 detachComplete ( )showspacesshowspaces showspaces48 }showspacesshowspaces showspaces49 }showspacesshowspaces

Code listing D.12: Source file protocol/procedure/NondetReceiveSugar.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co l . procedureshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import s c a l a . u t i l . c on t inua t i on s . cpsshowspacesshowspaces showspaces4

showspacesshowspaces showspaces5 import pro to co l . Messageshowspacesshowspaces showspaces6 import pro to co l . Message .RECEIVEshowspacesshowspaces showspaces7

showspacesshowspaces showspaces8 /∗∗showspacesshowspaces showspaces9 ∗ Wraps partial procedures so Environment . nondetInput worksshowspacesshowspaces showspaces10 ∗ on messages wrapped in RECEIVE message . This enablesshowspacesshowspaces showspaces11 ∗ procedures that are more l ike the declarative protocolshowspacesshowspaces showspaces12 ∗ definitions and do not need to have knowledge about theshowspacesshowspaces showspaces13 ∗ messages used in the RADIO−layer , i . e . the RECEIVE−message .showspacesshowspaces showspaces14 ∗/showspacesshowspaces showspaces15 object NondetReceiveSugar {showspacesshowspaces showspaces16

showspacesshowspaces showspaces17 def decorateWithRecieve ( innerProc : PartProc ) =showspacesshowspaces showspaces18 new PartProc {showspacesshowspaces showspaces19

showspacesshowspaces showspaces20 def apply (m: Message ) : Unit @cps [ NetThunk ] =showspacesshowspaces showspaces21 m match {showspacesshowspaces showspaces22 case RECEIVE( innerMessage ) =>showspacesshowspaces showspaces23 innerProc ( innerMessage )showspacesshowspaces showspaces24 }showspacesshowspaces showspaces25

showspacesshowspaces showspaces26 def i sDe f inedAt (m: Message ) =showspacesshowspaces showspaces27 m match {showspacesshowspaces showspaces28 case RECEIVE( innerMessage ) =>showspacesshowspaces showspaces29 innerProc . i sDef inedAt ( innerMessage )showspacesshowspaces showspaces30 case =>showspacesshowspaces showspaces31 fa l seshowspacesshowspaces showspaces32 }showspacesshowspaces showspaces33 }showspacesshowspaces showspaces34

showspacesshowspaces showspaces35 def apply ( env : Environment ) ( innerProc : PartProc ) : Unit =showspacesshowspaces showspaces36 env . nondetInput ( decorateWithRecieve ( innerProc ) )showspacesshowspaces showspaces37 }showspacesshowspaces

Code listing D.13: Source file protocol/procedure/package.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co lshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import thunkprocedure . Procedure . Thunkshowspacesshowspaces showspaces4 import thunkprocedure . ProcedureRunnershowspacesshowspaces showspaces5 import u t i l . c on t inua t i on s . cpsshowspacesshowspaces showspaces6

115

Page 132: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX D. TOY EXAMPLE IMPLEMENTATION SOURCE CODE

showspacesshowspaces showspaces7 /∗∗ Some procedure definitions . ∗/showspacesshowspaces showspaces8 package object procedure {showspacesshowspaces showspaces9

showspacesshowspaces showspaces10 /∗∗ A partial ly applicable Net procedure . ∗/showspacesshowspaces showspaces11 type PartProc = Part ia lFunct ion [ Message , Unit @cps [ NetThunk ] ]showspacesshowspaces showspaces12

showspacesshowspaces showspaces13 /∗∗showspacesshowspaces showspaces14 ∗ All procedures in the Net layer needs a runner of theseshowspacesshowspaces showspaces15 ∗ types .showspacesshowspaces showspaces16 ∗/showspacesshowspaces showspaces17 type NetProcedureRunner = ProcedureRunner [ Message , Boolean ]showspacesshowspaces showspaces18

showspacesshowspaces showspaces19 /∗∗showspacesshowspaces showspaces20 ∗ All procedures in the Net layer returns these types ofshowspacesshowspaces showspaces21 ∗ thunks .showspacesshowspaces showspaces22 ∗/showspacesshowspaces showspaces23 type NetThunk = Thunk [ Message , Boolean ]showspacesshowspaces showspaces24

showspacesshowspaces showspaces25 /∗∗ The value of a successful procedure .∗/showspacesshowspaces showspaces26 val s u c c e s s f u l P r o c e d u r e = trueshowspacesshowspaces showspaces27

showspacesshowspaces showspaces28 /∗∗ The value of a fa i led procedure .∗/showspacesshowspaces showspaces29 val f a i l e d P r o c e d u r e = fa l seshowspacesshowspaces showspaces30 }showspacesshowspaces

Code listing D.14: Source file protocol/procedure/PrimitiveProcedures.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co l . procedureshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import s c a l a . u t i l . c on t inua t i on s . cpsshowspacesshowspaces showspaces4

showspacesshowspaces showspaces5 import pro to co l . Messageshowspacesshowspaces showspaces6 import pro to co l . Message .CONNECTshowspacesshowspaces showspaces7 import pro to co l . Message .CONNECT DONEshowspacesshowspaces showspaces8 import pro to co l . Message .CONNECT FAILshowspacesshowspaces showspaces9 import pro to co l . Message .DETACH COMPLETEshowspacesshowspaces showspaces10 import pro to co l . Message .DISCONNECTshowspacesshowspaces showspaces11 import pro to co l . Message .DISCONNECT DONEshowspacesshowspaces showspaces12 import pro to co l . Message .RECEIVEshowspacesshowspaces showspaces13 import pro to co l . Message .SENDshowspacesshowspaces showspaces14 import pro to co l . Message .SEND ACKshowspacesshowspaces showspaces15 import pro to co l . Message . SEND FAILshowspacesshowspaces showspaces16 import pro to co l . Stratumshowspacesshowspaces showspaces17

showspacesshowspaces showspaces18 trait Pr imit iveProcedures {showspacesshowspaces showspaces19

showspacesshowspaces showspaces20 /∗∗ Creates radio layer connection . ∗/showspacesshowspaces showspaces21 def connect ( ) : Unit @cps [ NetThunk ]showspacesshowspaces showspaces22

showspacesshowspaces showspaces23 /∗∗ Disconnect the currently existing radio layer . ∗/showspacesshowspaces showspaces24 def d i s connec t ( ) : Unit @cps [ NetThunk ]showspacesshowspaces showspaces25

showspacesshowspaces showspaces26 /∗∗showspacesshowspaces showspaces27 ∗ Send a message net core over existing radio layershowspacesshowspaces showspaces28 ∗ connection .

116

Page 133: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

D.2. PROTOCOL DEFINITION

showspacesshowspaces showspaces29 ∗/showspacesshowspaces showspaces30 def send ( payload : Message ) : Unit @cps [ NetThunk ]showspacesshowspaces showspaces31

showspacesshowspaces showspaces32 /∗∗showspacesshowspaces showspaces33 ∗ Wait for a spec i f ic message from net core over existingshowspacesshowspaces showspaces34 ∗ radio layer connection .showspacesshowspaces showspaces35 ∗/showspacesshowspaces showspaces36 def rece iveExpected ( expected : Message ) : Unit @cps [ NetThunk ]showspacesshowspaces showspaces37

showspacesshowspaces showspaces38 /∗∗showspacesshowspaces showspaces39 ∗ Wait for a any message from net core over existing radioshowspacesshowspaces showspaces40 ∗ layer connection .showspacesshowspaces showspaces41 ∗/showspacesshowspaces showspaces42 def r e c e i v e ( ) : Message @cps [ NetThunk ]showspacesshowspaces showspaces43

showspacesshowspaces showspaces44 /∗∗showspacesshowspaces showspaces45 ∗ Signals to the application layer that UE is detachedshowspacesshowspaces showspaces46 ∗ from core .showspacesshowspaces showspaces47 ∗/showspacesshowspaces showspaces48 def detachComplete ( ) : Unit @cps [ NetThunk ]showspacesshowspaces showspaces49 }showspacesshowspaces showspaces50

showspacesshowspaces showspaces51 class Primit iveProcedures Impl (showspacesshowspaces showspaces52 env : Environment ,showspacesshowspaces showspaces53 rad io : Stratum ,showspacesshowspaces showspaces54 appl : Stratum ) extends Pr imit iveProcedures {showspacesshowspaces showspaces55

showspacesshowspaces showspaces56 import env .showspacesshowspaces showspaces57

showspacesshowspaces showspaces58 private def throwException (showspacesshowspaces showspaces59 ac tua l : Message ,showspacesshowspaces showspaces60 expected : S t r ing = ”” ) = {showspacesshowspaces showspaces61

showspacesshowspaces showspaces62 val messagePart =showspacesshowspaces showspaces63 i f ( expected == ”” ) ””showspacesshowspaces showspaces64 else ” when expect ing ” + expectedshowspacesshowspaces showspaces65 throw new Exception ( ” Received unexpected message ” +showspacesshowspaces showspaces66 messagePart )showspacesshowspaces showspaces67 }showspacesshowspaces showspaces68

showspacesshowspaces showspaces69 def connect ( ) = {showspacesshowspaces showspaces70 rad io . output (CONNECT)showspacesshowspaces showspaces71 input ( ) match {showspacesshowspaces showspaces72 case CONNECT DONE => ( )showspacesshowspaces showspaces73 case CONNECT FAIL => f a i l u r e ( )showspacesshowspaces showspaces74 case m => throwException (m,showspacesshowspaces showspaces75 ” connect con f i rmat ion (CONNECT DONE or CONNECT FAIL) ” )showspacesshowspaces showspaces76 }showspacesshowspaces showspaces77 }showspacesshowspaces showspaces78

showspacesshowspaces showspaces79 def d i s connec t ( ) = {showspacesshowspaces showspaces80 rad io . output (DISCONNECT)showspacesshowspaces showspaces81 input ( ) match {showspacesshowspaces showspaces82 case DISCONNECT DONE => ( )showspacesshowspaces showspaces83 case m => throwException (m, ”DISCONNECT DONE” )showspacesshowspaces showspaces84 }showspacesshowspaces showspaces85 }

117

Page 134: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX D. TOY EXAMPLE IMPLEMENTATION SOURCE CODE

showspacesshowspaces showspaces86

showspacesshowspaces showspaces87 def detachComplete ( ) = {showspacesshowspaces showspaces88 appl . output (DETACH COMPLETE)showspacesshowspaces showspaces89 }showspacesshowspaces showspaces90

showspacesshowspaces showspaces91 def send ( payload : Message ) = {showspacesshowspaces showspaces92 rad io . output (SEND( payload ) )showspacesshowspaces showspaces93 input ( ) match {showspacesshowspaces showspaces94 case SEND ACK => ( )showspacesshowspaces showspaces95 case SEND FAIL => f a i l u r e ( )showspacesshowspaces showspaces96 case m => throwException (m,showspacesshowspaces showspaces97 ” send con f i rmat ion (SEND ACK or SEND FAIL) ” )showspacesshowspaces showspaces98 }showspacesshowspaces showspaces99 }showspacesshowspaces showspaces100

showspacesshowspaces showspaces101 def rece iveExpected ( expected : Message ) = {showspacesshowspaces showspaces102 input ( ) match {showspacesshowspaces showspaces103 case RECEIVE( ‘ expected ‘ ) => ( )showspacesshowspaces showspaces104 case m => throwException (m, expected . t oS t r i ng )showspacesshowspaces showspaces105 }showspacesshowspaces showspaces106 }showspacesshowspaces showspaces107

showspacesshowspaces showspaces108 def r e c e i v e ( ) = {showspacesshowspaces showspaces109 input ( ) match {showspacesshowspaces showspaces110 case RECEIVE(m) => mshowspacesshowspaces showspaces111 case m => throwException (m)showspacesshowspaces showspaces112 }showspacesshowspaces showspaces113 }showspacesshowspaces showspaces114 }showspacesshowspaces

Code listing D.15: Source file protocol/procedure/ThunkSugar.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co l . procedureshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import pro to co l . Messageshowspacesshowspaces showspaces4 import thunkprocedure . Procedure . Inputshowspacesshowspaces showspaces5 import pro to co l . Messageshowspacesshowspaces showspaces6

showspacesshowspaces showspaces7 /∗∗showspacesshowspaces showspaces8 ∗ Syntax sugar that enables pattern matching of NetThunks.showspacesshowspaces showspaces9 ∗/showspacesshowspaces showspaces10 object ThunkSugar {showspacesshowspaces showspaces11

showspacesshowspaces showspaces12 object ProcedureSuccess {showspacesshowspaces showspaces13 def apply ( ) = Right ( true )showspacesshowspaces showspaces14 def unapply ( thunk : NetThunk ) =showspacesshowspaces showspaces15 i f ( thunk . hasResult ) {showspacesshowspaces showspaces16 val i s S u c c e s s f u l = thunk . f o r c e R e s u l tshowspacesshowspaces showspaces17 i f ( i s S u c c e s s f u l ) Some ( )showspacesshowspaces showspaces18 else Noneshowspacesshowspaces showspaces19 } else Noneshowspacesshowspaces showspaces20 }showspacesshowspaces showspaces21

showspacesshowspaces showspaces22 object ProcedureFa i lure {showspacesshowspaces showspaces23 def apply ( ) = Right ( fa l se )

118

Page 135: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

D.3. PROTOCOL TESTS

showspacesshowspaces showspaces24 def unapply ( thunk : NetThunk ) =showspacesshowspaces showspaces25 i f ( thunk . hasResult ) {showspacesshowspaces showspaces26 val i s S u c c e s s f u l = thunk . f o r c e R e s u l tshowspacesshowspaces showspaces27 i f ( ! i s S u c c e s s f u l ) Some ( )showspacesshowspaces showspaces28 else Noneshowspacesshowspaces showspaces29 } else Noneshowspacesshowspaces showspaces30 }showspacesshowspaces showspaces31

showspacesshowspaces showspaces32 object ProcedureInput {showspacesshowspaces showspaces33 def apply ( proceed : ( Message ) => NetThunk) =showspacesshowspaces showspaces34 Le f t ( Input ( proceed ) )showspacesshowspaces showspaces35

showspacesshowspaces showspaces36 def unapply ( thunk : NetThunk ) = thunk match {showspacesshowspaces showspaces37 case Le f t ( procedurePart ) => Some( thunk )showspacesshowspaces showspaces38 case => Noneshowspacesshowspaces showspaces39 }showspacesshowspaces showspaces40 }showspacesshowspaces showspaces41 }showspacesshowspaces

D.3 Protocol tests

Ths section shows the test code for the protocol implementation, and arethe code that asserts that the protocol implementation works as expected.

Many files in the test source code tree corresponds to files in the sourcecode tree. As an exampel, the test code file protocol/procedure/CoreProceduresSpec.scala

corresponds to the source code file protocol/procedure/CoreProcedures.scala.The test code folder protocol/procedure/mockable do not correspond to

a folder in the source code tree. It is instead a folder containing code thathelps the testing in the folder protocol/procedure by facilitating mockabletraits lacking references to any continuations.

D.3.1 Test code folder protocol

Code listing D.16: Test source file protocol/CompleteSpecificationSuite.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co lshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import org . s c a l a t e s t . Specsshowspacesshowspaces showspaces4

showspacesshowspaces showspaces5 import pro to co l . fsm . In t eg ra t i onTes tshowspacesshowspaces showspaces6 import pro to co l . fsm . NetFsmSpecshowspacesshowspaces showspaces7 import pro to co l . procedure . AuthPoceduresSpecshowspacesshowspaces showspaces8 import pro to co l . procedure . CoreProceduresSpecshowspacesshowspaces showspaces9 import pro to co l . procedure . EnvironmentSpecshowspacesshowspaces showspaces10 import pro to co l . procedure . FsmProceduresSpecshowspacesshowspaces showspaces11 import pro to co l . procedure . Pr imit iveProceduresSpecshowspacesshowspaces showspaces12

showspacesshowspaces showspaces13 /∗∗ Runs a l l Net layer tests ∗/showspacesshowspaces showspaces14 class Compl e t eSpec i f i c a t i onSu i t e extends Specs (showspacesshowspaces showspaces15 new AuthPoceduresSpec ( ) ,

119

Page 136: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX D. TOY EXAMPLE IMPLEMENTATION SOURCE CODE

showspacesshowspaces showspaces16 new CoreProceduresSpec ( ) ,showspacesshowspaces showspaces17 new EnvironmentSpec ( ) ,showspacesshowspaces showspaces18 new FsmProceduresSpec ( ) ,showspacesshowspaces showspaces19 new Primit iveProceduresSpec ( ) ,showspacesshowspaces showspaces20 new NetFsmSpec ( ) ,showspacesshowspaces showspaces21 new In t eg ra t i onTes t ( ) )showspacesshowspaces

D.3.2 Test code folder protocol/fsm

Code listing D.17: Test source file protocol/fsm/FsmTestUtil.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co l . fsmshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import org . s c a l a t e s t . BeforeAndAfterAl lshowspacesshowspaces showspaces4 import org . s c a l a t e s t . FlatSpecshowspacesshowspaces showspaces5 import org . s c a l a t e s t . mock . MockitoSugarshowspacesshowspaces showspaces6

showspacesshowspaces showspaces7 import NetState .ATTACHshowspacesshowspaces showspaces8 import NetState .CONNECTEDshowspacesshowspaces showspaces9 import NetState .DETACHshowspacesshowspaces showspaces10 import NetState . IDLEshowspacesshowspaces showspaces11 import akka . ac to r . ActorSystemshowspacesshowspaces showspaces12 import akka . t e s t k i t . TestFSMRefshowspacesshowspaces showspaces13 import akka . t e s t k i t . TestKitshowspacesshowspaces showspaces14 import pro to co l . Message .AUTH FAILshowspacesshowspaces showspaces15 import pro to co l . Message .RECEIVEshowspacesshowspaces showspaces16 import pro to co l . procedure . NetThunkshowspacesshowspaces showspaces17 import pro to co l . procedure . ThunkSugar . ProcedureFa i lureshowspacesshowspaces showspaces18 import pro to co l . procedure . ThunkSugar . ProcedureInputshowspacesshowspaces showspaces19 import pro to co l . procedure . ThunkSugar . ProcedureSuccessshowspacesshowspaces showspaces20

showspacesshowspaces showspaces21 /∗∗showspacesshowspaces showspaces22 ∗ Test ut i l i ty spec i f ic to the Net layer FSM domain,showspacesshowspaces showspaces23 ∗ extending the Akka test kit for actor testing .showspacesshowspaces showspaces24 ∗/showspacesshowspaces showspaces25 abstract class FsmTestUtilshowspacesshowspaces showspaces26 extends TestKit ( ActorSystem ( ”NetFsmSpec” ) )showspacesshowspaces showspaces27 with FlatSpec with MockitoSugar with BeforeAndAfterAl l {showspacesshowspaces showspaces28

showspacesshowspaces showspaces29 type FSMRef = TestFSMRef [ NetState , Option [ NetThunk ] , NetFsm ]showspacesshowspaces showspaces30 val arb i t raryMessage = RECEIVE(AUTH FAIL)showspacesshowspaces showspaces31

showspacesshowspaces showspaces32 /∗∗ Different kinds of thunks . ∗/showspacesshowspaces showspaces33 val input : NetThunk = ProcedureInput { messsage => input }showspacesshowspaces showspaces34 val f a i l u r e : NetThunk = ProcedureFa i lure ( )showspacesshowspaces showspaces35 val s u c c e s s : NetThunk = ProcedureSuccess ( )showspacesshowspaces showspaces36

showspacesshowspaces showspaces37 /∗∗ State−data pairs ∗/showspacesshowspaces showspaces38 type StateData = ( NetState , Option [ NetThunk ] )showspacesshowspaces showspaces39 val i d l e : StateData = (IDLE , None )showspacesshowspaces showspaces40 val connected : StateData = (CONNECTED, None )showspacesshowspaces showspaces41 def attach ( thunk : NetThunk ) : StateData =showspacesshowspaces showspaces42 (ATTACH, Some( thunk ) )

120

Page 137: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

D.3. PROTOCOL TESTS

showspacesshowspaces showspaces43 def detach ( thunk : NetThunk ) : StateData =showspacesshowspaces showspaces44 (DETACH, Some( thunk ) )showspacesshowspaces showspaces45

showspacesshowspaces showspaces46 /∗∗ Abstract methods . ∗/showspacesshowspaces showspaces47 def c reateProcedure s ( ) : Proceduresshowspacesshowspaces showspaces48 def v e r i f i c a t i o n A f t e r T e s t ( procedures : Procedures ) : Anyshowspacesshowspaces showspaces49

showspacesshowspaces showspaces50 class Fixture ( s t a r t S t a t e : StateData , endState : StateData ) {showspacesshowspaces showspaces51

showspacesshowspaces showspaces52 def t e s t ( testCode : (FSMRef , Procedures ) => Any) = {showspacesshowspaces showspaces53 val procedures = createProcedure s ( )showspacesshowspaces showspaces54 val c lassUnderTest : FSMRef =showspacesshowspaces showspaces55 TestFSMRef (new NetFsm( procedures ) )showspacesshowspaces showspaces56 c lassUnderTest . s e t S t a t e ( s t a r t S t a t e . 1 , s t a r t S t a t e . 2 )showspacesshowspaces showspaces57 testCode ( c lassUnderTest , procedures )showspacesshowspaces showspaces58 a s s e r t ( c lassUnderTest . stateName === endState . 1 )showspacesshowspaces showspaces59 a s s e r t ( c lassUnderTest . stateData . i sDe f i n ed ===showspacesshowspaces showspaces60 endState . 2 . i sDe f i n ed )showspacesshowspaces showspaces61 v e r i f i c a t i o n A f t e r T e s t ( procedures )showspacesshowspaces showspaces62 }showspacesshowspaces showspaces63 }showspacesshowspaces showspaces64

showspacesshowspaces showspaces65 override def a f t e r A l l { system . shutdown ( ) }showspacesshowspaces showspaces66 }showspacesshowspaces

Code listing D.18: Test source file protocol/fsm/IntegrationTest.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co l . fsmshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import NetState .ATTACHshowspacesshowspaces showspaces4 import NetState . IDLEshowspacesshowspaces showspaces5 import akka . ac to r . ac to rRe f2Sca lashowspacesshowspaces showspaces6 import akka . t e s t k i t . Imp l i c i tS ende rshowspacesshowspaces showspaces7 import pro to co l . Messageshowspacesshowspaces showspaces8 import pro to co l . Message .ATTACH ACCEPTshowspacesshowspaces showspaces9 import pro to co l . Message .ATTACH COMPLETEshowspacesshowspaces showspaces10 import pro to co l . Message .ATTACH REQUESTshowspacesshowspaces showspaces11 import pro to co l . Message .AUTH FAILshowspacesshowspaces showspaces12 import pro to co l . Message .AUTH REQUESTshowspacesshowspaces showspaces13 import pro to co l . Message .AUTH RESPONSEshowspacesshowspaces showspaces14 import pro to co l . Message .CONNECTshowspacesshowspaces showspaces15 import pro to co l . Message .CONNECT DONEshowspacesshowspaces showspaces16 import pro to co l . Message .DETACH ACCEPTshowspacesshowspaces showspaces17 import pro to co l . Message .DETACH COMPLETEshowspacesshowspaces showspaces18 import pro to co l . Message .DETACH REQUESTshowspacesshowspaces showspaces19 import pro to co l . Message .DISCONNECTshowspacesshowspaces showspaces20 import pro to co l . Message .DISCONNECT DONEshowspacesshowspaces showspaces21 import pro to co l . Message .POWER OFFshowspacesshowspaces showspaces22 import pro to co l . Message .POWER OFF DONEshowspacesshowspaces showspaces23 import pro to co l . Message .POWER ONshowspacesshowspaces showspaces24 import pro to co l . Message .POWER ON DONEshowspacesshowspaces showspaces25 import pro to co l . Message .POWER ON FAILshowspacesshowspaces showspaces26 import pro to co l . Message .RECEIVEshowspacesshowspaces showspaces27 import pro to co l . Message .SENDshowspacesshowspaces showspaces28 import pro to co l . Message .SEND ACK

121

Page 138: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX D. TOY EXAMPLE IMPLEMENTATION SOURCE CODE

showspacesshowspaces showspaces29 import pro to co l . Stratumshowspacesshowspaces showspaces30

showspacesshowspaces showspaces31 trait Dir e c t i onshowspacesshowspaces showspaces32 case class ToRadio (m: Message ) extends Dir e c t i onshowspacesshowspaces showspaces33 case class ToAppl (m: Message ) extends Dir e c t i onshowspacesshowspaces showspaces34

showspacesshowspaces showspaces35 /∗∗showspacesshowspaces showspaces36 ∗ Some larger integration tests using both the Net layershowspacesshowspaces showspaces37 ∗ FSM and Net layer procedures .showspacesshowspaces showspaces38 ∗/showspacesshowspaces showspaces39 class In t eg ra t i onTes t extends FsmTestUtilshowspacesshowspaces showspaces40 with Imp l i c i tSende r {showspacesshowspaces showspaces41 import Message .showspacesshowspaces showspaces42

showspacesshowspaces showspaces43 def c reateProcedure s ( ) = {showspacesshowspaces showspaces44 val rad io = new Stratum {showspacesshowspaces showspaces45 def output (m: Message ) = {showspacesshowspaces showspaces46 p r i n t l n ( ”#RADIO# ” + m)showspacesshowspaces showspaces47 t e s tActo r ! ToRadio (m)showspacesshowspaces showspaces48 }showspacesshowspaces showspaces49 }showspacesshowspaces showspaces50 val appl = new Stratum {showspacesshowspaces showspaces51 def output (m: Message ) = {showspacesshowspaces showspaces52 p r i n t l n ( ”#APPL# ” + m)showspacesshowspaces showspaces53 t e s tActo r ! ToAppl (m)showspacesshowspaces showspaces54 }showspacesshowspaces showspaces55 }showspacesshowspaces showspaces56 new ProceduresImpl ( radio , appl )showspacesshowspaces showspaces57 }showspacesshowspaces showspaces58

showspacesshowspaces showspaces59 def v e r i f i c a t i o n A f t e r T e s t ( procedures : Procedures ) = ( )showspacesshowspaces showspaces60 val v a l i d I d = 56 // even == valid authentication IDshowspacesshowspaces showspaces61 val i n v a l i d I d = 3 // odd == invalid authentication IDshowspacesshowspaces showspaces62

showspacesshowspaces showspaces63 ”IDLE −> POWER ON” should ”end up in CONNECTED, ” +showspacesshowspaces showspaces64 ”when s u c c e s s f u l ” inshowspacesshowspaces showspaces65 new Fixture ( i d l e , connected ) .showspacesshowspaces showspaces66 t e s t { ( cut , ) =>showspacesshowspaces showspaces67

showspacesshowspaces showspaces68 cut ! POWER ONshowspacesshowspaces showspaces69

showspacesshowspaces showspaces70 expectMsg ( ToRadio (CONNECT) )showspacesshowspaces showspaces71 cut ! CONNECT DONEshowspacesshowspaces showspaces72 expectMsg ( ToRadio (SEND(ATTACH REQUEST) ) )showspacesshowspaces showspaces73 cut ! SEND ACKshowspacesshowspaces showspaces74 cut ! RECEIVE(AUTH REQUEST( v a l i d I d ) )showspacesshowspaces showspaces75 expectMsg ( ToRadio (SEND(AUTH RESPONSE) ) )showspacesshowspaces showspaces76 cut ! SEND ACKshowspacesshowspaces showspaces77 cut ! RECEIVE(ATTACH ACCEPT)showspacesshowspaces showspaces78 expectMsg ( ToRadio (SEND(ATTACH COMPLETE) ) )showspacesshowspaces showspaces79 cut ! SEND ACKshowspacesshowspaces showspaces80

showspacesshowspaces showspaces81 expectMsg ( ToAppl (POWER ON DONE) )showspacesshowspaces showspaces82 }showspacesshowspaces showspaces83

showspacesshowspaces showspaces84 i t should ”end up in IDLE , ” +showspacesshowspaces showspaces85 ”when authen t i c a t i on ID i s i n v a l i d ” in

122

Page 139: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

D.3. PROTOCOL TESTS

showspacesshowspaces showspaces86 new Fixture ( i d l e , i d l e ) .showspacesshowspaces showspaces87 t e s t { ( cut , ) =>showspacesshowspaces showspaces88

showspacesshowspaces showspaces89 cut ! POWER ONshowspacesshowspaces showspaces90

showspacesshowspaces showspaces91 expectMsg ( ToRadio (CONNECT) )showspacesshowspaces showspaces92 cut ! CONNECT DONEshowspacesshowspaces showspaces93 expectMsg ( ToRadio (SEND(ATTACH REQUEST) ) )showspacesshowspaces showspaces94 cut ! SEND ACKshowspacesshowspaces showspaces95 cut ! RECEIVE(AUTH REQUEST( i n v a l i d I d ) )showspacesshowspaces showspaces96 expectMsg ( ToRadio (SEND(AUTH FAIL) ) )showspacesshowspaces showspaces97 cut ! SEND ACKshowspacesshowspaces showspaces98 expectMsg ( ToRadio (DISCONNECT) )showspacesshowspaces showspaces99 cut ! DISCONNECT DONEshowspacesshowspaces showspaces100

showspacesshowspaces showspaces101 expectMsg ( ToAppl (POWER ON FAIL) )showspacesshowspaces showspaces102 }showspacesshowspaces showspaces103

showspacesshowspaces showspaces104 i t should ”end up in IDLE , when timeout ” +showspacesshowspaces showspaces105 ”and then i gno r i ng messages that f o l l o w . ” inshowspacesshowspaces showspaces106 new Fixture ( i d l e , i d l e ) .showspacesshowspaces showspaces107 t e s t { ( cut , ) =>showspacesshowspaces showspaces108

showspacesshowspaces showspaces109 cut ! POWER ONshowspacesshowspaces showspaces110 expectMsg ( ToRadio (CONNECT) )showspacesshowspaces showspaces111 a s s e r t ( cut . stateName === ATTACH)showspacesshowspaces showspaces112

showspacesshowspaces showspaces113 // State timeout i s specif ied at 1 second .showspacesshowspaces showspaces114 Thread . s l e e p (1500)showspacesshowspaces showspaces115

showspacesshowspaces showspaces116 a s s e r t ( cut . stateName === IDLE)showspacesshowspaces showspaces117

showspacesshowspaces showspaces118 // should be ignored in IDLE, no exceptions thrownshowspacesshowspaces showspaces119 cut ! CONNECT DONEshowspacesshowspaces showspaces120 }showspacesshowspaces showspaces121

showspacesshowspaces showspaces122 ”CONNECTED −> POWER OFF” should ”end up in IDLE , ” +showspacesshowspaces showspaces123 ”when s u c c e s s f u l ” inshowspacesshowspaces showspaces124 new Fixture ( connected , i d l e ) .showspacesshowspaces showspaces125 t e s t { ( cut , ) =>showspacesshowspaces showspaces126

showspacesshowspaces showspaces127 cut ! POWER OFFshowspacesshowspaces showspaces128

showspacesshowspaces showspaces129 expectMsg ( ToRadio (SEND(DETACH REQUEST) ) )showspacesshowspaces showspaces130 cut ! SEND ACKshowspacesshowspaces showspaces131 cut ! RECEIVE(DETACH COMPLETE)showspacesshowspaces showspaces132 expectMsg ( ToRadio (DISCONNECT) )showspacesshowspaces showspaces133 cut ! DISCONNECT DONEshowspacesshowspaces showspaces134

showspacesshowspaces showspaces135 expectMsg ( ToAppl (POWER OFF DONE) )showspacesshowspaces showspaces136 }showspacesshowspaces showspaces137

showspacesshowspaces showspaces138 ”CONNECTED −> DETACH REQUEST” should ”end up in IDLE , ” +showspacesshowspaces showspaces139 ”when s u c c e s s f u l ” inshowspacesshowspaces showspaces140 new Fixture ( connected , i d l e ) .showspacesshowspaces showspaces141 t e s t { ( cut , ) =>showspacesshowspaces showspaces142

123

Page 140: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX D. TOY EXAMPLE IMPLEMENTATION SOURCE CODE

showspacesshowspaces showspaces143 cut ! DETACH REQUESTshowspacesshowspaces showspaces144

showspacesshowspaces showspaces145 expectMsg ( ToRadio (SEND(DETACH ACCEPT) ) )showspacesshowspaces showspaces146 cut ! SEND ACKshowspacesshowspaces showspaces147 expectMsg ( ToRadio (DISCONNECT) )showspacesshowspaces showspaces148 cut ! DISCONNECT DONEshowspacesshowspaces showspaces149

showspacesshowspaces showspaces150 expectMsg ( ToAppl (DETACH COMPLETE) )showspacesshowspaces showspaces151 }showspacesshowspaces showspaces152 }showspacesshowspaces

Code listing D.19: Test source file protocol/fsm/NetFsmSpec.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co l . fsmshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import org . mockito . Mockito . v e r i f yshowspacesshowspaces showspaces4 import org . mockito . Mockito . ve r i f yNoMore Inte rac t i onsshowspacesshowspaces showspaces5 import org . mockito . Mockito . whenshowspacesshowspaces showspaces6

showspacesshowspaces showspaces7 import pro to co l . Message .DETACH REQUESTshowspacesshowspaces showspaces8 import pro to co l . Message .POWER OFFshowspacesshowspaces showspaces9 import pro to co l . Message .POWER ONshowspacesshowspaces showspaces10

showspacesshowspaces showspaces11 /∗∗ Unit tests for the Net−layer FSM. ∗/showspacesshowspaces showspaces12 class NetFsmSpec extends FsmTestUtil {showspacesshowspaces showspaces13

showspacesshowspaces showspaces14 def c reateProcedure s ( ) = mock [ Procedures ]showspacesshowspaces showspaces15

showspacesshowspaces showspaces16 def v e r i f i c a t i o n A f t e r T e s t ( procedures : Procedures ) =showspacesshowspaces showspaces17 ver i f yNoMore Inte rac t i ons ( procedures )showspacesshowspaces showspaces18

showspacesshowspaces showspaces19 ”IDLE −> POWER ON” should ”end up in ATTACH ” +showspacesshowspaces showspaces20 ”when wai t ing f o r input ” inshowspacesshowspaces showspaces21 new Fixture ( i d l e , attach ( input ) ) .showspacesshowspaces showspaces22

showspacesshowspaces showspaces23 t e s t { ( cut , procedures ) =>showspacesshowspaces showspaces24 when( procedures . powerOn ( ) ) . thenReturn ( input )showspacesshowspaces showspaces25 cut ! POWER ONshowspacesshowspaces showspaces26 v e r i f y ( procedures ) . powerOn ( )showspacesshowspaces showspaces27 }showspacesshowspaces showspaces28

showspacesshowspaces showspaces29 i t should ”end up in IDLE when procedure f a i l s ” inshowspacesshowspaces showspaces30 new Fixture ( i d l e , i d l e ) .showspacesshowspaces showspaces31

showspacesshowspaces showspaces32 t e s t { ( cut , procedures ) =>showspacesshowspaces showspaces33 when( procedures . powerOn ( ) ) . thenReturn ( f a i l u r e )showspacesshowspaces showspaces34 cut ! POWER ONshowspacesshowspaces showspaces35 v e r i f y ( procedures ) . powerOn ( )showspacesshowspaces showspaces36 }showspacesshowspaces showspaces37

showspacesshowspaces showspaces38 i t should ”end up in CONNECTED when procedure succeeds ” inshowspacesshowspaces showspaces39 new Fixture ( i d l e , connected ) .showspacesshowspaces showspaces40

showspacesshowspaces showspaces41 t e s t { ( cut , procedures ) =>showspacesshowspaces showspaces42 when( procedures . powerOn ( ) ) . thenReturn ( s u c c e s s )

124

Page 141: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

D.3. PROTOCOL TESTS

showspacesshowspaces showspaces43 cut ! POWER ONshowspacesshowspaces showspaces44 v e r i f y ( procedures ) . powerOn ( )showspacesshowspaces showspaces45 }showspacesshowspaces showspaces46

showspacesshowspaces showspaces47 ”ATTACH” should ”end up in ATTACH ” +showspacesshowspaces showspaces48 ”when wai t ing f o r input ” inshowspacesshowspaces showspaces49 new Fixture ( attach ( input ) , attach ( input ) ) .showspacesshowspaces showspaces50 t e s t { ( cut , ) => cut ! arb i t raryMessage }showspacesshowspaces showspaces51

showspacesshowspaces showspaces52 i t should ”end up in IDLE when procedure f a i l s ” inshowspacesshowspaces showspaces53 new Fixture ( attach ( f a i l u r e ) , i d l e ) .showspacesshowspaces showspaces54 t e s t { ( cut , ) => cut ! arb i t raryMessage }showspacesshowspaces showspaces55

showspacesshowspaces showspaces56 i t should ”end up in CONNECTED when procedure succeeds ” inshowspacesshowspaces showspaces57 new Fixture ( attach ( s u c c e s s ) , connected ) .showspacesshowspaces showspaces58 t e s t { ( cut , ) => cut ! arb i t raryMessage }showspacesshowspaces showspaces59

showspacesshowspaces showspaces60 ”CONNECTED −> DETACH REQUEST” should ”end up in DETACH ” +showspacesshowspaces showspaces61 ”when wai t ing f o r input ” inshowspacesshowspaces showspaces62 new Fixture ( connected , detach ( input ) ) .showspacesshowspaces showspaces63

showspacesshowspaces showspaces64 t e s t { ( cut , procedures ) =>showspacesshowspaces showspaces65 when( procedures . forcedDetach ( ) ) . thenReturn ( input )showspacesshowspaces showspaces66 cut ! DETACH REQUESTshowspacesshowspaces showspaces67 v e r i f y ( procedures ) . forcedDetach ( )showspacesshowspaces showspaces68 }showspacesshowspaces showspaces69

showspacesshowspaces showspaces70 i t should ”end up in IDLE when procedure f a i l s ” inshowspacesshowspaces showspaces71 new Fixture ( connected , i d l e ) .showspacesshowspaces showspaces72

showspacesshowspaces showspaces73 t e s t { ( cut , procedures ) =>showspacesshowspaces showspaces74 when( procedures . forcedDetach ( ) ) . thenReturn ( f a i l u r e )showspacesshowspaces showspaces75 cut ! DETACH REQUESTshowspacesshowspaces showspaces76 v e r i f y ( procedures ) . forcedDetach ( )showspacesshowspaces showspaces77 }showspacesshowspaces showspaces78

showspacesshowspaces showspaces79 i t should ”end up in IDLE when procedure succeeds ” inshowspacesshowspaces showspaces80 new Fixture ( connected , i d l e ) .showspacesshowspaces showspaces81

showspacesshowspaces showspaces82 t e s t { ( cut , procedures ) =>showspacesshowspaces showspaces83 when( procedures . forcedDetach ( ) ) . thenReturn ( s u c c e s s )showspacesshowspaces showspaces84 cut ! DETACH REQUESTshowspacesshowspaces showspaces85

showspacesshowspaces showspaces86 v e r i f y ( procedures ) . forcedDetach ( )showspacesshowspaces showspaces87 }showspacesshowspaces showspaces88

showspacesshowspaces showspaces89 ”CONNECTED −> POWER OFF” should ”end up in DETACH ” +showspacesshowspaces showspaces90 ”when wai t ing f o r input ” inshowspacesshowspaces showspaces91 new Fixture ( connected , detach ( input ) ) .showspacesshowspaces showspaces92

showspacesshowspaces showspaces93 t e s t { ( cut , procedures ) =>showspacesshowspaces showspaces94 when( procedures . powerOff ( ) ) . thenReturn ( input )showspacesshowspaces showspaces95 cut ! POWER OFFshowspacesshowspaces showspaces96 v e r i f y ( procedures ) . powerOff ( )showspacesshowspaces showspaces97 }showspacesshowspaces showspaces98

showspacesshowspaces showspaces99 i t should ”end up in IDLE when procedure f a i l s ” in

125

Page 142: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX D. TOY EXAMPLE IMPLEMENTATION SOURCE CODE

showspacesshowspaces showspaces100 new Fixture ( connected , i d l e ) .showspacesshowspaces showspaces101

showspacesshowspaces showspaces102 t e s t { ( cut , procedures ) =>showspacesshowspaces showspaces103 when( procedures . powerOff ( ) ) . thenReturn ( f a i l u r e )showspacesshowspaces showspaces104 cut ! POWER OFFshowspacesshowspaces showspaces105 v e r i f y ( procedures ) . powerOff ( )showspacesshowspaces showspaces106 }showspacesshowspaces showspaces107

showspacesshowspaces showspaces108 i t should ”end up in IDLE when procedure succeeds ” inshowspacesshowspaces showspaces109 new Fixture ( connected , i d l e ) .showspacesshowspaces showspaces110

showspacesshowspaces showspaces111 t e s t { ( cut , procedures ) =>showspacesshowspaces showspaces112 when( procedures . powerOff ( ) ) . thenReturn ( s u c c e s s )showspacesshowspaces showspaces113 cut ! POWER OFFshowspacesshowspaces showspaces114 v e r i f y ( procedures ) . powerOff ( )showspacesshowspaces showspaces115 }showspacesshowspaces showspaces116

showspacesshowspaces showspaces117 ”DETACH” should ”end up in DETACH ” +showspacesshowspaces showspaces118 ”when wai t ing f o r input ” inshowspacesshowspaces showspaces119 new Fixture ( detach ( input ) , detach ( input ) ) .showspacesshowspaces showspaces120 t e s t { ( cut , ) => cut ! a rb i t raryMessage }showspacesshowspaces showspaces121

showspacesshowspaces showspaces122 i t should ”end up in IDLE when procedure f a i l s ” inshowspacesshowspaces showspaces123 new Fixture ( detach ( f a i l u r e ) , i d l e ) .showspacesshowspaces showspaces124 t e s t { ( cut , ) => cut ! a rb i t raryMessage }showspacesshowspaces showspaces125

showspacesshowspaces showspaces126 i t should ”end up in IDLE when procedure succeeds ” inshowspacesshowspaces showspaces127 new Fixture ( detach ( s u c c e s s ) , i d l e ) .showspacesshowspaces showspaces128 t e s t { ( cut , ) => cut ! a rb i t raryMessage }showspacesshowspaces showspaces129 }showspacesshowspaces

D.3.3 Test code folder protocol/procedure

Code listing D.20: Test source file protocol/procedure/AuthProceduresSpec.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co l . procedureshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import org . mockito . Mockito . v e r i f yshowspacesshowspaces showspaces4 import org . mockito . Mockito . ve r i f yNoMore Inte rac t i onsshowspacesshowspaces showspaces5 import org . mockito . Mockito . whenshowspacesshowspaces showspaces6 import org . s c a l a t e s t . FlatSpecshowspacesshowspaces showspaces7 import org . s c a l a t e s t . mock . MockitoSugarshowspacesshowspaces showspaces8

showspacesshowspaces showspaces9 import pro to co l . Messageshowspacesshowspaces showspaces10 import pro to co l . Message .ATTACH ACCEPTshowspacesshowspaces showspaces11 import pro to co l . Message .AUTH FAILshowspacesshowspaces showspaces12 import pro to co l . Message .AUTH REJECTshowspacesshowspaces showspaces13 import pro to co l . Message .AUTH REQUESTshowspacesshowspaces showspaces14 import pro to co l . Message .AUTH RESPONSEshowspacesshowspaces showspaces15 import pro to co l . Message .RECEIVEshowspacesshowspaces showspaces16 import pro to co l . procedure . mockable . PrimitiveMockshowspacesshowspaces showspaces17 import pro to co l . procedure . mockable . cont inueshowspacesshowspaces showspaces18 import pro to co l . procedure . mockable . terminate

126

Page 143: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

D.3. PROTOCOL TESTS

showspacesshowspaces showspaces19 import thunkprocedure . Procedure . wrapThunkshowspacesshowspaces showspaces20

showspacesshowspaces showspaces21 class AuthPoceduresSpec extends FlatSpec with MockitoSugar {showspacesshowspaces showspaces22 import Message .showspacesshowspaces showspaces23

showspacesshowspaces showspaces24 trait CUT extends Fixture {showspacesshowspaces showspaces25 val ( pr imi t iveProcedures , primitiveMock ) =showspacesshowspaces showspaces26 PrimitiveMock ( environment )showspacesshowspaces showspaces27

showspacesshowspaces showspaces28 val cut : AuthProcedures =showspacesshowspaces showspaces29 new AuthProceduresImpl ( environment , p r im i t iveProcedure s )showspacesshowspaces showspaces30

showspacesshowspaces showspaces31 val i n v a l i d I d = 1 // oddshowspacesshowspaces showspaces32 val v a l i d I d = 2 // evenshowspacesshowspaces showspaces33

showspacesshowspaces showspaces34 def tr iggerNondetWithExpectedAttachAcceptReceive ( ) =showspacesshowspaces showspaces35 a s s e r t ( environment . input === ATTACH ACCEPT)showspacesshowspaces showspaces36

showspacesshowspaces showspaces37 def tearDown = {showspacesshowspaces showspaces38 ver i f yNoMore Inte rac t i ons ( primitiveMock )showspacesshowspaces showspaces39 }showspacesshowspaces showspaces40 }showspacesshowspaces showspaces41

showspacesshowspaces showspaces42 ” Authent icat ion ” should ” succeed , ” +showspacesshowspaces showspaces43 ”when r e c e i v e d message i s not AUTH REQUEST. ” inshowspacesshowspaces showspaces44 new CUT with Success {showspacesshowspaces showspaces45

showspacesshowspaces showspaces46 def setup = {} // no setupshowspacesshowspaces showspaces47

showspacesshowspaces showspaces48 run {showspacesshowspaces showspaces49 cut . au then t i c a t i onshowspacesshowspaces showspaces50 tr iggerNondetWithExpectedAttachAcceptReceive ( )showspacesshowspaces showspaces51

showspacesshowspaces showspaces52 } w i t h I n t e r a c t i o n { t =>showspacesshowspaces showspaces53 t << Message .ATTACH ACCEPTshowspacesshowspaces showspaces54 }showspacesshowspaces showspaces55 }showspacesshowspaces showspaces56

showspacesshowspaces showspaces57 i t should ” succeed , ” +showspacesshowspaces showspaces58 ”when r e c e i v e d message i s AUTH REQUEST with v a l i d ID ” +showspacesshowspaces showspaces59 ”and send AUTH RESPONSE succeeds ” +showspacesshowspaces showspaces60 ”and no AUTH REJECT i s r e c e i v e d . ” inshowspacesshowspaces showspaces61 new CUT with Success {showspacesshowspaces showspaces62

showspacesshowspaces showspaces63 def setup =showspacesshowspaces showspaces64 cont inue (when( primitiveMock . send (AUTH RESPONSE) ) )showspacesshowspaces showspaces65

showspacesshowspaces showspaces66 run {showspacesshowspaces showspaces67 cut . au then t i c a t i on ( )showspacesshowspaces showspaces68 tr iggerNondetWithExpectedAttachAcceptReceive ( )showspacesshowspaces showspaces69

showspacesshowspaces showspaces70 } w i t h I n t e r a c t i o n { t1 =>showspacesshowspaces showspaces71

showspacesshowspaces showspaces72 val t2 = t1 << RECEIVE(AUTH REQUEST( v a l i d I d ) )showspacesshowspaces showspaces73 v e r i f y ( primitiveMock ) . send (AUTH RESPONSE)showspacesshowspaces showspaces74 a s s e r t ( t2 . i sWait ingForInput )showspacesshowspaces showspaces75 t2 << ATTACH ACCEPT

127

Page 144: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX D. TOY EXAMPLE IMPLEMENTATION SOURCE CODE

showspacesshowspaces showspaces76 }showspacesshowspaces showspaces77 }showspacesshowspaces showspaces78

showspacesshowspaces showspaces79 i t should ” f a i l , ” +showspacesshowspaces showspaces80 ”when r e c e i v e d message i s AUTH REQUEST with v a l i d ID ” +showspacesshowspaces showspaces81 ”and send AUTH RESPONSE succeeds ” +showspacesshowspaces showspaces82 ”and f i n a l l y an AUTH REJECT i s r e c e i v e d . ” inshowspacesshowspaces showspaces83 new CUT with Fa i l u r e {showspacesshowspaces showspaces84

showspacesshowspaces showspaces85 def setup =showspacesshowspaces showspaces86 cont inue (when( primitiveMock . send (AUTH RESPONSE) ) )showspacesshowspaces showspaces87

showspacesshowspaces showspaces88 run {showspacesshowspaces showspaces89 cut . au then t i c a t i onshowspacesshowspaces showspaces90 tr iggerNondetWithExpectedAttachAcceptReceive ( )showspacesshowspaces showspaces91

showspacesshowspaces showspaces92 } w i t h I n t e r a c t i o n { t1 =>showspacesshowspaces showspaces93 val t2 = t1 << RECEIVE(AUTH REQUEST( v a l i d I d ) )showspacesshowspaces showspaces94 v e r i f y ( primitiveMock ) . send (AUTH RESPONSE)showspacesshowspaces showspaces95 a s s e r t ( t2 . i sWait ingForInput )showspacesshowspaces showspaces96 t2 << RECEIVE(AUTH REJECT)showspacesshowspaces showspaces97 }showspacesshowspaces showspaces98 }showspacesshowspaces showspaces99

showspacesshowspaces showspaces100 i t should ” f a i l , ” +showspacesshowspaces showspaces101 ”when r e c e i v e d message i s AUTH REQUEST with v a l i d ID ” +showspacesshowspaces showspaces102 ”and send AUTH RESPONSE f a i l s . ” inshowspacesshowspaces showspaces103 new CUT with Fa i l u r e {showspacesshowspaces showspaces104

showspacesshowspaces showspaces105 def setup =showspacesshowspaces showspaces106 terminate (when( primitiveMock . send (AUTH RESPONSE) ) )showspacesshowspaces showspaces107

showspacesshowspaces showspaces108 run {showspacesshowspaces showspaces109 cut . au then t i c a t i onshowspacesshowspaces showspaces110 tr iggerNondetWithExpectedAttachAcceptReceive ( )showspacesshowspaces showspaces111

showspacesshowspaces showspaces112 } w i t h I n t e r a c t i o n { t1 =>showspacesshowspaces showspaces113 val t2 = t1 << RECEIVE(AUTH REQUEST( v a l i d I d ) )showspacesshowspaces showspaces114 v e r i f y ( primitiveMock ) . send (AUTH RESPONSE)showspacesshowspaces showspaces115 t2showspacesshowspaces showspaces116 }showspacesshowspaces showspaces117 }showspacesshowspaces showspaces118

showspacesshowspaces showspaces119 i t should ” f a i l , ” +showspacesshowspaces showspaces120 ”when r e c e i v e d message i s AUTH REQUEST with i n v a l i d ID ” +showspacesshowspaces showspaces121 ”and send AUTH FAIL succeeds . ” inshowspacesshowspaces showspaces122 new CUT with Fa i l u r e {showspacesshowspaces showspaces123

showspacesshowspaces showspaces124 def setup =showspacesshowspaces showspaces125 cont inue (when( primitiveMock . send (AUTH FAIL) ) )showspacesshowspaces showspaces126

showspacesshowspaces showspaces127 run {showspacesshowspaces showspaces128 cut . au then t i c a t i onshowspacesshowspaces showspaces129 tr iggerNondetWithExpectedAttachAcceptReceive ( )showspacesshowspaces showspaces130

showspacesshowspaces showspaces131 } w i t h I n t e r a c t i o n { t1 =>showspacesshowspaces showspaces132 val t2 = t1 << RECEIVE(AUTH REQUEST( i n v a l i d I d ) )

128

Page 145: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

D.3. PROTOCOL TESTS

showspacesshowspaces showspaces133 v e r i f y ( primitiveMock ) . send (AUTH FAIL)showspacesshowspaces showspaces134 t2showspacesshowspaces showspaces135 }showspacesshowspaces showspaces136 }showspacesshowspaces showspaces137

showspacesshowspaces showspaces138 i t should ” f a i l , ” +showspacesshowspaces showspaces139 ”when r e c e i v e d message i s AUTH REQUEST with i n v a l i d ID ” +showspacesshowspaces showspaces140 ”and send AUTH FAIL f a i l s . ” inshowspacesshowspaces showspaces141 new CUT with Fa i l u r e {showspacesshowspaces showspaces142

showspacesshowspaces showspaces143 def setup =showspacesshowspaces showspaces144 terminate (when( primitiveMock . send (AUTH FAIL) ) )showspacesshowspaces showspaces145

showspacesshowspaces showspaces146 run {showspacesshowspaces showspaces147 cut . au then t i c a t i onshowspacesshowspaces showspaces148 tr iggerNondetWithExpectedAttachAcceptReceive ( )showspacesshowspaces showspaces149

showspacesshowspaces showspaces150 } w i t h I n t e r a c t i o n { t1 =>showspacesshowspaces showspaces151 val t2 = t1 << RECEIVE(AUTH REQUEST( i n v a l i d I d ) )showspacesshowspaces showspaces152 v e r i f y ( primitiveMock ) . send (AUTH FAIL)showspacesshowspaces showspaces153 t2showspacesshowspaces showspaces154 }showspacesshowspaces showspaces155 }showspacesshowspaces showspaces156 }showspacesshowspaces

Code listing D.21: Test source file protocol/procedure/CoreProceduresSpec.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co l . procedureshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import org . mockito . Mockitoshowspacesshowspaces showspaces4 import org . mockito . Mockito . v e r i f yshowspacesshowspaces showspaces5 import org . mockito . Mockito . ve r i f yNoMore Inte rac t i onsshowspacesshowspaces showspaces6 import org . mockito . Mockito . whenshowspacesshowspaces showspaces7 import org . s c a l a t e s t . FlatSpecshowspacesshowspaces showspaces8 import org . s c a l a t e s t . mock . MockitoSugarshowspacesshowspaces showspaces9

showspacesshowspaces showspaces10 import pro to co l . Message .ATTACH ACCEPTshowspacesshowspaces showspaces11 import pro to co l . Message .ATTACH COMPLETEshowspacesshowspaces showspaces12 import pro to co l . Message .ATTACH REQUESTshowspacesshowspaces showspaces13 import pro to co l . Message .DETACH COMPLETEshowspacesshowspaces showspaces14 import pro to co l . Message .DETACH REQUESTshowspacesshowspaces showspaces15 import pro to co l . procedure . mockable . AuthMockshowspacesshowspaces showspaces16 import pro to co l . procedure . mockable . PrimitiveMockshowspacesshowspaces showspaces17 import pro to co l . procedure . mockable . cont inueshowspacesshowspaces showspaces18 import pro to co l . procedure . mockable . terminateshowspacesshowspaces showspaces19

showspacesshowspaces showspaces20 class CoreProceduresSpec extends FlatSpec with MockitoSugar {showspacesshowspaces showspaces21

showspacesshowspaces showspaces22 trait CUT extends Fixture {showspacesshowspaces showspaces23 val ( primProcedures , primMock ) = PrimitiveMock ( environment )showspacesshowspaces showspaces24 val ( authProcedures , authMock ) = AuthMock( environment )showspacesshowspaces showspaces25 val inOrder = Mockito . inOrder ( primMock , authMock ) ;showspacesshowspaces showspaces26

showspacesshowspaces showspaces27 val cut : CoreProcedures =showspacesshowspaces showspaces28 new CoreProceduresImpl ( environment ,

129

Page 146: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX D. TOY EXAMPLE IMPLEMENTATION SOURCE CODE

showspacesshowspaces showspaces29 primProcedures , authProcedures )showspacesshowspaces showspaces30

showspacesshowspaces showspaces31 def tearDown = {showspacesshowspaces showspaces32 ver i f yNoMore Inte rac t i ons ( primMock )showspacesshowspaces showspaces33 ver i f yNoMore Inte rac t i ons ( authMock )showspacesshowspaces showspaces34 }showspacesshowspaces showspaces35 }showspacesshowspaces showspaces36

showspacesshowspaces showspaces37 ”Attach” should ” succeed , ” +showspacesshowspaces showspaces38 ”when a l l subprocedures are s u c c e s s f u l . ” inshowspacesshowspaces showspaces39 new CUT with Success {showspacesshowspaces showspaces40

showspacesshowspaces showspaces41 def setup = {showspacesshowspaces showspaces42 cont inue (when( primMock . send (ATTACH REQUEST) ) )showspacesshowspaces showspaces43 cont inue (when( authMock . au then t i c a t i on ( ) ) )showspacesshowspaces showspaces44 cont inue (when( primMock . rece iveExpected (ATTACH ACCEPT) ) )showspacesshowspaces showspaces45 cont inue (when( primMock . send (ATTACH COMPLETE) ) )showspacesshowspaces showspaces46 }showspacesshowspaces showspaces47

showspacesshowspaces showspaces48 run { cut . attach } and {showspacesshowspaces showspaces49 inOrder . v e r i f y ( primMock ) . send (ATTACH REQUEST)showspacesshowspaces showspaces50 inOrder . v e r i f y ( authMock ) . au then t i c a t i on ( )showspacesshowspaces showspaces51 inOrder . v e r i f y ( primMock ) . r ece iveExpected (ATTACH ACCEPT)showspacesshowspaces showspaces52 inOrder . v e r i f y ( primMock ) . send (ATTACH COMPLETE)showspacesshowspaces showspaces53 }showspacesshowspaces showspaces54 }showspacesshowspaces showspaces55

showspacesshowspaces showspaces56 i t should ” f a i l , ” +showspacesshowspaces showspaces57 ”when send ATTACH COMPLETE f a i l s . ” inshowspacesshowspaces showspaces58 new CUT with Fa i l u r e {showspacesshowspaces showspaces59

showspacesshowspaces showspaces60 def setup = {showspacesshowspaces showspaces61 cont inue (when( primMock . send (ATTACH REQUEST) ) )showspacesshowspaces showspaces62 cont inue (when( authMock . au then t i c a t i on ( ) ) )showspacesshowspaces showspaces63 cont inue (when( primMock . rece iveExpected (ATTACH ACCEPT) ) )showspacesshowspaces showspaces64 terminate (when( primMock . send (ATTACH COMPLETE) ) )showspacesshowspaces showspaces65 }showspacesshowspaces showspaces66

showspacesshowspaces showspaces67 run { cut . attach } and {showspacesshowspaces showspaces68 inOrder . v e r i f y ( primMock ) . send (ATTACH REQUEST)showspacesshowspaces showspaces69 inOrder . v e r i f y ( authMock ) . au then t i c a t i on ( )showspacesshowspaces showspaces70 inOrder . v e r i f y ( primMock ) . r ece iveExpected (ATTACH ACCEPT)showspacesshowspaces showspaces71 inOrder . v e r i f y ( primMock ) . send (ATTACH COMPLETE)showspacesshowspaces showspaces72 }showspacesshowspaces showspaces73 }showspacesshowspaces showspaces74

showspacesshowspaces showspaces75 i t should ” f a i l , ” +showspacesshowspaces showspaces76 ”when i t r e c e i v e s ATTACH FAIL. ” inshowspacesshowspaces showspaces77 new CUT with Fa i l u r e {showspacesshowspaces showspaces78

showspacesshowspaces showspaces79 def setup = {showspacesshowspaces showspaces80 cont inue (when( primMock . send (ATTACH REQUEST) ) )showspacesshowspaces showspaces81 cont inue (when( authMock . au then t i c a t i on ( ) ) )showspacesshowspaces showspaces82 terminate (when( primMock . rece iveExpected (ATTACH ACCEPT) ) )showspacesshowspaces showspaces83 }showspacesshowspaces showspaces84

showspacesshowspaces showspaces85 run { cut . attach } and {

130

Page 147: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

D.3. PROTOCOL TESTS

showspacesshowspaces showspaces86 inOrder . v e r i f y ( primMock ) . send (ATTACH REQUEST)showspacesshowspaces showspaces87 inOrder . v e r i f y ( authMock ) . au then t i c a t i on ( )showspacesshowspaces showspaces88 inOrder . v e r i f y ( primMock ) . r ece iveExpected (ATTACH ACCEPT)showspacesshowspaces showspaces89 }showspacesshowspaces showspaces90 }showspacesshowspaces showspaces91

showspacesshowspaces showspaces92 i t should ” f a i l , ” +showspacesshowspaces showspaces93 ”when authen t i c a t i on f a i l s . ” inshowspacesshowspaces showspaces94 new CUT with Fa i l u r e {showspacesshowspaces showspaces95

showspacesshowspaces showspaces96 def setup = {showspacesshowspaces showspaces97 cont inue (when( primMock . send (ATTACH REQUEST) ) )showspacesshowspaces showspaces98 terminate (when( authMock . au then t i c a t i on ( ) ) )showspacesshowspaces showspaces99 }showspacesshowspaces showspaces100

showspacesshowspaces showspaces101 run { cut . attach } and {showspacesshowspaces showspaces102 inOrder . v e r i f y ( primMock ) . send (ATTACH REQUEST)showspacesshowspaces showspaces103 inOrder . v e r i f y ( authMock ) . au then t i c a t i on ( )showspacesshowspaces showspaces104 }showspacesshowspaces showspaces105 }showspacesshowspaces showspaces106

showspacesshowspaces showspaces107 i t should ” f a i l , ” +showspacesshowspaces showspaces108 ”when send ATTACH REQUEST f a i l s . ” inshowspacesshowspaces showspaces109 new CUT with Fa i l u r e {showspacesshowspaces showspaces110

showspacesshowspaces showspaces111 def setup =showspacesshowspaces showspaces112 terminate (when( primMock . send (ATTACH REQUEST) ) )showspacesshowspaces showspaces113

showspacesshowspaces showspaces114 run { cut . attach } andshowspacesshowspaces showspaces115 inOrder . v e r i f y ( primMock ) . send (ATTACH REQUEST)showspacesshowspaces showspaces116 }showspacesshowspaces showspaces117

showspacesshowspaces showspaces118 ”Detach” should ” succeed , ” +showspacesshowspaces showspaces119 ”when a l l subprocedures are s u c c e s s f u l . ” inshowspacesshowspaces showspaces120 new CUT with Success {showspacesshowspaces showspaces121

showspacesshowspaces showspaces122 def setup = {showspacesshowspaces showspaces123 cont inue (when( primMock . send (DETACH REQUEST) ) )showspacesshowspaces showspaces124 cont inue (when( primMock . rece iveExpected (DETACH COMPLETE) )showspacesshowspaces showspaces)showspacesshowspaces showspaces125 }showspacesshowspaces showspaces126

showspacesshowspaces showspaces127 run { cut . detach } and {showspacesshowspaces showspaces128 inOrder . v e r i f y ( primMock ) . send (DETACH REQUEST)showspacesshowspaces showspaces129 inOrder . v e r i f y ( primMock ) . r ece iveExpected (DETACH COMPLETEshowspacesshowspaces showspaces)showspacesshowspaces showspaces130 }showspacesshowspaces showspaces131 }showspacesshowspaces showspaces132

showspacesshowspaces showspaces133 i t should ” f a i l , ” +showspacesshowspaces showspaces134 ”when r e c e i v e DETACH COMPLETE f a i l s . ” inshowspacesshowspaces showspaces135 new CUT with Fa i l u r e {showspacesshowspaces showspaces136

showspacesshowspaces showspaces137 def setup = {showspacesshowspaces showspaces138 cont inue (when( primMock . send (DETACH REQUEST) ) )showspacesshowspaces showspaces139 terminate (when( primMock . rece iveExpected (DETACH COMPLETE)showspacesshowspaces showspaces) )

131

Page 148: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX D. TOY EXAMPLE IMPLEMENTATION SOURCE CODE

showspacesshowspaces showspaces140 }showspacesshowspaces showspaces141

showspacesshowspaces showspaces142 run { cut . detach } and {showspacesshowspaces showspaces143 inOrder . v e r i f y ( primMock ) . send (DETACH REQUEST)showspacesshowspaces showspaces144 inOrder . v e r i f y ( primMock ) . r ece iveExpected (DETACH COMPLETEshowspacesshowspaces showspaces)showspacesshowspaces showspaces145 }showspacesshowspaces showspaces146 }showspacesshowspaces showspaces147

showspacesshowspaces showspaces148 i t should ” f a i l , ” +showspacesshowspaces showspaces149 ”when send DETACH REQUEST. ” inshowspacesshowspaces showspaces150 new CUT with Fa i l u r e {showspacesshowspaces showspaces151

showspacesshowspaces showspaces152 def setup =showspacesshowspaces showspaces153 terminate (when( primMock . send (DETACH REQUEST) ) )showspacesshowspaces showspaces154

showspacesshowspaces showspaces155 run { cut . detach } andshowspacesshowspaces showspaces156 v e r i f y ( primMock ) . send (DETACH REQUEST)showspacesshowspaces showspaces157 }showspacesshowspaces showspaces158 }showspacesshowspaces

Code listing D.22: Test source file protocol/procedure/EnvironmentSpec.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co l . procedureshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import org . s c a l a t e s t . FlatSpecshowspacesshowspaces showspaces4 import thunkprocedure . Procedure .showspacesshowspaces showspaces5

showspacesshowspaces showspaces6 import pro to co l . Messageshowspacesshowspaces showspaces7 import pro to co l . Message .showspacesshowspaces showspaces8

showspacesshowspaces showspaces9 class EnvironmentSpec extends FlatSpec {showspacesshowspaces showspaces10

showspacesshowspaces showspaces11 trait EnvironmentFixture {showspacesshowspaces showspaces12 val runner = createRunner [ Message , Boolean ]showspacesshowspaces showspaces13 val env : Environment = new EnvironmentImpl ( runner )showspacesshowspaces showspaces14

showspacesshowspaces showspaces15 }showspacesshowspaces showspaces16

showspacesshowspaces showspaces17 trait NondetFixture extends EnvironmentFixture {showspacesshowspaces showspaces18 import env .showspacesshowspaces showspaces19

showspacesshowspaces showspaces20 var connectOneIsExec = fa l seshowspacesshowspaces showspaces21 var d i s connec t I sExec = fa l seshowspacesshowspaces showspaces22 var authFai l I sExec = fa l seshowspacesshowspaces showspaces23 var connectTwoIsExec = fa l seshowspacesshowspaces showspaces24

showspacesshowspaces showspaces25 def run ( ) : NetThunk = env {showspacesshowspaces showspaces26

showspacesshowspaces showspaces27 nondetInput {showspacesshowspaces showspaces28 case DISCONNECT => d i s connec t I sExec = trueshowspacesshowspaces showspaces29 case CONNECT => connectOneIsExec = trueshowspacesshowspaces showspaces30 }showspacesshowspaces showspaces31 nondetInput {showspacesshowspaces showspaces32 case AUTH FAIL => authFai l I sExec = true

132

Page 149: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

D.3. PROTOCOL TESTS

showspacesshowspaces showspaces33 }showspacesshowspaces showspaces34 nondetInput {showspacesshowspaces showspaces35 case CONNECT => connectTwoIsExec = trueshowspacesshowspaces showspaces36 }showspacesshowspaces showspaces37

showspacesshowspaces showspaces38 // Ordinary receive trigger messages to beshowspacesshowspaces showspaces39 // matched against application of nondetReceive .showspacesshowspaces showspaces40 a s s e r t ( input == SEND ACK)showspacesshowspaces showspaces41 }showspacesshowspaces showspaces42

showspacesshowspaces showspaces43 }showspacesshowspaces showspaces44

showspacesshowspaces showspaces45 def a s s e r t R e s u l t ( thunk : NetThunk , expectedVal : Boolean ) = {showspacesshowspaces showspaces46 a s s e r t ( thunk . hasResult )showspacesshowspaces showspaces47 a s s e r t ( thunk . f o r c e R e s u l t === expectedVal )showspacesshowspaces showspaces48 }showspacesshowspaces showspaces49

showspacesshowspaces showspaces50 ”Apply” should ” re turn thunk with true , ” +showspacesshowspaces showspaces51 ”when procedure i s completed ” inshowspacesshowspaces showspaces52 new EnvironmentFixture {showspacesshowspaces showspaces53

showspacesshowspaces showspaces54 val thunk = env ( )showspacesshowspaces showspaces55

showspacesshowspaces showspaces56 a s s e r t R e s u l t ( thunk , true )showspacesshowspaces showspaces57 }showspacesshowspaces showspaces58

showspacesshowspaces showspaces59 ” Fa i l u r e ” should ” re turn thunk with f a l s e ” inshowspacesshowspaces showspaces60 new EnvironmentFixture {showspacesshowspaces showspaces61

showspacesshowspaces showspaces62 val thunk = env { env . f a i l u r e ( ) }showspacesshowspaces showspaces63 a s s e r t R e s u l t ( thunk , fa l se )showspacesshowspaces showspaces64 }showspacesshowspaces showspaces65

showspacesshowspaces showspaces66 ” Receive ” should ” re turn thunk with input request , ” +showspacesshowspaces showspaces67 ”when procedure want to r e c e i v e input ” inshowspacesshowspaces showspaces68 new EnvironmentFixture {showspacesshowspaces showspaces69

showspacesshowspaces showspaces70 val thunk1 = env {showspacesshowspaces showspaces71 a s s e r t ( env . input === Message .DETACH COMPLETE)showspacesshowspaces showspaces72 a s s e r t ( env . input === Message .AUTH RESPONSE)showspacesshowspaces showspaces73 }showspacesshowspaces showspaces74

showspacesshowspaces showspaces75 a s s e r t ( thunk1 . i sWait ingForInput )showspacesshowspaces showspaces76 val thunk2 = thunk1 << Message .DETACH COMPLETEshowspacesshowspaces showspaces77

showspacesshowspaces showspaces78 a s s e r t ( thunk2 . i sWait ingForInput )showspacesshowspaces showspaces79 val thunk3 = thunk2 << Message .AUTH RESPONSEshowspacesshowspaces showspaces80

showspacesshowspaces showspaces81 a s s e r t R e s u l t ( thunk3 , true )showspacesshowspaces showspaces82 }showspacesshowspaces showspaces83

showspacesshowspaces showspaces84 ”WhenFail” should ”not r e cove r but cont inue ” +showspacesshowspaces showspaces85 ”when s u c c e s s f u l ” inshowspacesshowspaces showspaces86 new EnvironmentFixture {showspacesshowspaces showspaces87 import env .showspacesshowspaces showspaces88

showspacesshowspaces showspaces89 var cont inuesAfterWhenfa i lB lock = fa l se

133

Page 150: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX D. TOY EXAMPLE IMPLEMENTATION SOURCE CODE

showspacesshowspaces showspaces90

showspacesshowspaces showspaces91 val thunk = env {showspacesshowspaces showspaces92 whenFail {showspacesshowspaces showspaces93 // successful procedure that does nothingshowspacesshowspaces showspaces94 } recoverWith {showspacesshowspaces showspaces95 f a i l ( ”Recover block should not be executed . ” )showspacesshowspaces showspaces96 }showspacesshowspaces showspaces97 cont inuesAfterWhenfa i lB lock = trueshowspacesshowspaces showspaces98 }showspacesshowspaces showspaces99

showspacesshowspaces showspaces100 a s s e r t ( cont inuesAfterWhenfa i lB lock )showspacesshowspaces showspaces101 a s s e r t R e s u l t ( thunk , true )showspacesshowspaces showspaces102 }showspacesshowspaces showspaces103

showspacesshowspaces showspaces104 i t should ” r ecove r when f a i l u r e occurs ” +showspacesshowspaces showspaces105 ”and then terminate ” inshowspacesshowspaces showspaces106 new EnvironmentFixture {showspacesshowspaces showspaces107 import env .showspacesshowspaces showspaces108

showspacesshowspaces showspaces109 var recoverBlockIsExecuted = fa l seshowspacesshowspaces showspaces110

showspacesshowspaces showspaces111 val thunk = env {showspacesshowspaces showspaces112 whenFail {showspacesshowspaces showspaces113 env . f a i l u r e ( ) // trigger fa i lureshowspacesshowspaces showspaces114 } recoverWith {showspacesshowspaces showspaces115 recoverBlockIsExecuted = trueshowspacesshowspaces showspaces116 }showspacesshowspaces showspaces117 f a i l ( ” Procedure should terminate ” +showspacesshowspaces showspaces118 ” a f t e r r e cove r b lock . ” )showspacesshowspaces showspaces119 }showspacesshowspaces showspaces120

showspacesshowspaces showspaces121 a s s e r t ( recoverBlockIsExecuted )showspacesshowspaces showspaces122 a s s e r t R e s u l t ( thunk , fa l se )showspacesshowspaces showspaces123 }showspacesshowspaces showspaces124

showspacesshowspaces showspaces125 ” NondetReceive ” should ” not be executed ” +showspacesshowspaces showspaces126 ”when message do not match” inshowspacesshowspaces showspaces127 new NondetFixture {showspacesshowspaces showspaces128

showspacesshowspaces showspaces129 val thunk = run ( ) << SEND ACKshowspacesshowspaces showspaces130

showspacesshowspaces showspaces131 a s s e r t ( d i s connec t I sExec === fa l se )showspacesshowspaces showspaces132 a s s e r t ( connectOneIsExec === fa l se )showspacesshowspaces showspaces133 a s s e r t ( authFa i l I sExec === fa l se )showspacesshowspaces showspaces134 a s s e r t ( connectTwoIsExec === fa l se )showspacesshowspaces showspaces135 a s s e r t R e s u l t ( thunk , true )showspacesshowspaces showspaces136 }showspacesshowspaces showspaces137

showspacesshowspaces showspaces138 i t should ”overshadow l a t e r a p p l i c a t i o n s o f ” +showspacesshowspaces showspaces139 ” nondetReceive that a l s o match . ” inshowspacesshowspaces showspaces140 new NondetFixture {showspacesshowspaces showspaces141

showspacesshowspaces showspaces142 val thunk = run ( ) << CONNECT << SEND ACKshowspacesshowspaces showspaces143

showspacesshowspaces showspaces144 a s s e r t ( d i s connec t I sExec === fa l se )showspacesshowspaces showspaces145 a s s e r t ( connectOneIsExec )showspacesshowspaces showspaces146 a s s e r t ( authFa i l I sExec === fa l se )

134

Page 151: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

D.3. PROTOCOL TESTS

showspacesshowspaces showspaces147 a s s e r t ( connectTwoIsExec === fa l se )showspacesshowspaces showspaces148 a s s e r t R e s u l t ( thunk , true )showspacesshowspaces showspaces149 }showspacesshowspaces showspaces150

showspacesshowspaces showspaces151 i t should ” f o r g e t a p p l i c a t i o n s o f ” +showspacesshowspaces showspaces152 ” nondetReceive that has a l r eady matched . ” inshowspacesshowspaces showspaces153 new NondetFixture {showspacesshowspaces showspaces154

showspacesshowspaces showspaces155 val thunk = run ( ) << DISCONNECT << CONNECT << SEND ACKshowspacesshowspaces showspaces156

showspacesshowspaces showspaces157 a s s e r t ( d i s connec t I sExec )showspacesshowspaces showspaces158 a s s e r t ( connectOneIsExec === fa l se )showspacesshowspaces showspaces159 a s s e r t ( authFai l I sExec === fa l se )showspacesshowspaces showspaces160 a s s e r t ( connectTwoIsExec )showspacesshowspaces showspaces161 a s s e r t R e s u l t ( thunk , true )showspacesshowspaces showspaces162 }showspacesshowspaces showspaces163

showspacesshowspaces showspaces164 i t should ” f o r g e t e a r l i e r a p p l i c a t i o n s o f ” +showspacesshowspaces showspaces165 ” nondetReceive that might match at a l a t e r s tage . ” inshowspacesshowspaces showspaces166 new NondetFixture {showspacesshowspaces showspaces167

showspacesshowspaces showspaces168 val thunk = run ( ) << AUTH FAIL << CONNECT << SEND ACKshowspacesshowspaces showspaces169

showspacesshowspaces showspaces170 a s s e r t ( d i s connec t I sExec === fa l se )showspacesshowspaces showspaces171 a s s e r t ( connectOneIsExec === fa l se )showspacesshowspaces showspaces172 a s s e r t ( authFai l I sExec )showspacesshowspaces showspaces173 a s s e r t ( connectTwoIsExec )showspacesshowspaces showspaces174 a s s e r t R e s u l t ( thunk , true )showspacesshowspaces showspaces175 }showspacesshowspaces showspaces176

showspacesshowspaces showspaces177 i t should ”not f o r g e t other a p p l i c a t i o n s o f ” +showspacesshowspaces showspaces178 ” nondetReceive that a l s o match cur rent message , ” +showspacesshowspaces showspaces179 ”but are overshadowed at the moment . ” inshowspacesshowspaces showspaces180 new NondetFixture {showspacesshowspaces showspaces181

showspacesshowspaces showspaces182 val thunk1 = run ( ) << CONNECTshowspacesshowspaces showspaces183

showspacesshowspaces showspaces184 a s s e r t ( connectOneIsExec )showspacesshowspaces showspaces185 a s s e r t ( connectTwoIsExec === fa l se )showspacesshowspaces showspaces186 connectOneIsExec = fa l se // reset valueshowspacesshowspaces showspaces187

showspacesshowspaces showspaces188 val thunk2 = thunk1 << CONNECTshowspacesshowspaces showspaces189

showspacesshowspaces showspaces190 a s s e r t ( connectOneIsExec === fa l se )showspacesshowspaces showspaces191 a s s e r t ( connectTwoIsExec )showspacesshowspaces showspaces192 connectTwoIsExec = fa l se // reset valueshowspacesshowspaces showspaces193

showspacesshowspaces showspaces194 val thunk3 = thunk2 << SEND ACKshowspacesshowspaces showspaces195

showspacesshowspaces showspaces196 a s s e r t ( d i s connec t I sExec === fa l se )showspacesshowspaces showspaces197 a s s e r t ( connectOneIsExec === fa l se )showspacesshowspaces showspaces198 a s s e r t ( authFai l I sExec === fa l se )showspacesshowspaces showspaces199 a s s e r t ( connectTwoIsExec === fa l se )showspacesshowspaces showspaces200 a s s e r t R e s u l t ( thunk3 , true )showspacesshowspaces showspaces201 }showspacesshowspaces showspaces202

showspacesshowspaces showspaces203 i t should ”be complete ly f o r g o t t e n ” +

135

Page 152: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX D. TOY EXAMPLE IMPLEMENTATION SOURCE CODE

showspacesshowspaces showspaces204 ”when ord inary r e c e i v e are reached ” inshowspacesshowspaces showspaces205 new EnvironmentFixture {showspacesshowspaces showspaces206 import env .showspacesshowspaces showspaces207

showspacesshowspaces showspaces208 val thunk = env {showspacesshowspaces showspaces209 nondetInput {showspacesshowspaces showspaces210 case CONNECT => f a i l ( ”Should missmatch” )showspacesshowspaces showspaces211 }showspacesshowspaces showspaces212 a s s e r t ( input == SEND ACK)showspacesshowspaces showspaces213 a s s e r t ( input == CONNECT)showspacesshowspaces showspaces214

showspacesshowspaces showspaces215 } << SEND ACK << CONNECTshowspacesshowspaces showspaces216

showspacesshowspaces showspaces217 a s s e r t R e s u l t ( thunk , true )showspacesshowspaces showspaces218 }showspacesshowspaces showspaces219 }showspacesshowspaces

Code listing D.23: Test source file protocol/procedure/Fixture.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co l . procedureshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import s c a l a . u t i l . c on t inua t i on s . cpsshowspacesshowspaces showspaces4

showspacesshowspaces showspaces5 import org . s c a l a t e s t . FlatSpecshowspacesshowspaces showspaces6 import org . s c a l a t e s t . mock . MockitoSugar . mockshowspacesshowspaces showspaces7

showspacesshowspaces showspaces8 import pro to co l . Messageshowspacesshowspaces showspaces9 import thunkprocedure . Procedure . createRunnershowspacesshowspaces showspaces10 import thunkprocedure . Procedure . wrapThunkshowspacesshowspaces showspaces11

showspacesshowspaces showspaces12 /∗∗ Test fixture for procedure tests ∗/showspacesshowspaces showspaces13 trait Fixture extends FlatSpec {showspacesshowspaces showspaces14 val environment : Environment =showspacesshowspaces showspaces15 new EnvironmentImpl ( createRunner [ Message , Boolean ] )showspacesshowspaces showspaces16

showspacesshowspaces showspaces17 // abstractshowspacesshowspaces showspaces18 def expectedResu l t : Booleanshowspacesshowspaces showspaces19 def setup : Unitshowspacesshowspaces showspaces20 def tearDown : Unitshowspacesshowspaces showspaces21 def procedureWithValidationCode (showspacesshowspaces showspaces22 procedure : => Unit @cps [ NetThunk ] ) : Unit @cps [ NetThunk ] =showspacesshowspaces showspaces23 procedureshowspacesshowspaces showspaces24

showspacesshowspaces showspaces25 // concreteshowspacesshowspaces showspaces26 def thunkVal idat ions ( f inalThunk : NetThunk ) = {showspacesshowspaces showspaces27 a s s e r t ( f inalThunk . hasResult === true ,showspacesshowspaces showspaces28 ”Thunk should conta in r e s u l t a f t e r i n t e r a c t i o n s . ” )showspacesshowspaces showspaces29

showspacesshowspaces showspaces30 a s s e r t ( f inalThunk . f o r c e R e s u l t === expectedResult ,showspacesshowspaces showspaces31 ”The thunk r e s u l t i s expected to ” +showspacesshowspaces showspaces32 ”be ” + expectedResu l t + ” , but i s n ’ t . ” )showspacesshowspaces showspaces33 }showspacesshowspaces showspaces34

showspacesshowspaces showspaces35 def run ( procedure : => Unit @cps [ NetThunk ] ) = new {showspacesshowspaces showspaces36

136

Page 153: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

D.3. PROTOCOL TESTS

showspacesshowspaces showspaces37 def withNoInteract ion =showspacesshowspaces showspaces38 w i t h I n t e r a c t i o n { thunk => thunk }showspacesshowspaces showspaces39

showspacesshowspaces showspaces40 def and ( f : => Unit ) =showspacesshowspaces showspaces41 w i t h I n t e r a c t i o n { thunk => f ; thunk }showspacesshowspaces showspaces42

showspacesshowspaces showspaces43 def w i t h I n t e r a c t i o n (showspacesshowspaces showspaces44 i n t e r a c t i o n : ( NetThunk) => NetThunk) : Unit = {showspacesshowspaces showspaces45

showspacesshowspaces showspaces46 def runProcedure ( ) = environment {showspacesshowspaces showspaces47 procedureWithValidationCode { procedure }showspacesshowspaces showspaces48 }showspacesshowspaces showspaces49

showspacesshowspaces showspaces50 setupshowspacesshowspaces showspaces51 val i n i t i a lThunk = runProcedure ( )showspacesshowspaces showspaces52 val f inalThunk = i n t e r a c t i o n ( in i t i a lThunk )showspacesshowspaces showspaces53 tearDownshowspacesshowspaces showspaces54 thunkVal idat ions ( f inalThunk )showspacesshowspaces showspaces55 }showspacesshowspaces showspaces56 }showspacesshowspaces showspaces57 }showspacesshowspaces showspaces58

showspacesshowspaces showspaces59 /∗∗showspacesshowspaces showspaces60 ∗ Behavior implementation for some parts i f Fixture .showspacesshowspaces showspaces61 ∗ Ensures that the procedure f a i l s .showspacesshowspaces showspaces62 ∗/showspacesshowspaces showspaces63 trait Fa i l u r e extends Fixture {showspacesshowspaces showspaces64 def expectedResu l t = fa l seshowspacesshowspaces showspaces65

showspacesshowspaces showspaces66 override def procedureWithValidationCode (showspacesshowspaces showspaces67 procedure : => Unit @cps [ NetThunk ] ) = {showspacesshowspaces showspaces68

showspacesshowspaces showspaces69 procedureshowspacesshowspaces showspaces70 f a i l ( ” This l i n e should not be executed . ” )showspacesshowspaces showspaces71 }showspacesshowspaces showspaces72 }showspacesshowspaces showspaces73

showspacesshowspaces showspaces74 /∗∗showspacesshowspaces showspaces75 ∗ Behavior implementation for some parts i f Fixture .showspacesshowspaces showspaces76 ∗ Ensures that the procedure succeeds .showspacesshowspaces showspaces77 ∗/showspacesshowspaces showspaces78 trait Success extends Fixture {showspacesshowspaces showspaces79 def expectedResu l t = trueshowspacesshowspaces showspaces80

showspacesshowspaces showspaces81 var secondLineIsExecuted = fa l seshowspacesshowspaces showspaces82

showspacesshowspaces showspaces83 override def procedureWithValidationCode (showspacesshowspaces showspaces84 procedure : => Unit @cps [ NetThunk ] ) = {showspacesshowspaces showspaces85

showspacesshowspaces showspaces86 val r e s u l t = procedureshowspacesshowspaces showspaces87 secondLineIsExecuted = trueshowspacesshowspaces showspaces88 r e s u l tshowspacesshowspaces showspaces89 }showspacesshowspaces showspaces90

showspacesshowspaces showspaces91 abstract override def thunkVal idat ions ( f inalThunk : NetThunk ) =showspacesshowspaces showspaces{showspacesshowspaces showspaces92 a s s e r t ( secondLineIsExecuted ,

137

Page 154: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX D. TOY EXAMPLE IMPLEMENTATION SOURCE CODE

showspacesshowspaces showspaces93 ” Procedure should continue , not terminate ” )showspacesshowspaces showspaces94 super . thunkVal idat ions ( f inalThunk )showspacesshowspaces showspaces95 }showspacesshowspaces showspaces96 }showspacesshowspaces

Code listing D.24: Test source file protocol/procedure/FsmProceduresSpec.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co l . procedureshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import org . mockito . Mockitoshowspacesshowspaces showspaces4 import org . mockito . Mockito . v e r i f yshowspacesshowspaces showspaces5 import org . mockito . Mockito . ve r i f yNoMore Inte rac t i onsshowspacesshowspaces showspaces6 import org . mockito . Mockito . whenshowspacesshowspaces showspaces7 import org . s c a l a t e s t . FlatSpecshowspacesshowspaces showspaces8 import org . s c a l a t e s t . mock . MockitoSugarshowspacesshowspaces showspaces9

showspacesshowspaces showspaces10 import pro to co l . Message .DETACH ACCEPTshowspacesshowspaces showspaces11 import pro to co l . procedure . mockable . CoreMockshowspacesshowspaces showspaces12 import pro to co l . procedure . mockable . PrimitiveMockshowspacesshowspaces showspaces13 import pro to co l . procedure . mockable . cont inueshowspacesshowspaces showspaces14 import pro to co l . procedure . mockable . terminateshowspacesshowspaces showspaces15

showspacesshowspaces showspaces16 class FsmProceduresSpec extends FlatSpec with MockitoSugar {showspacesshowspaces showspaces17

showspacesshowspaces showspaces18 trait CUT extends Fixture {showspacesshowspaces showspaces19 val ( pr imi t iveProcedures , primitiveMock ) =showspacesshowspaces showspaces20 PrimitiveMock ( environment )showspacesshowspaces showspaces21

showspacesshowspaces showspaces22 val ( coreProcedures , coreMock ) = CoreMock ( environment )showspacesshowspaces showspaces23 val inOrder = Mockito . inOrder ( primitiveMock , coreMock ) ;showspacesshowspaces showspaces24

showspacesshowspaces showspaces25 val cut : FsmProcedures = new FsmProceduresImpl (showspacesshowspaces showspaces26 environment , pr imi t iveProcedures , coreProcedures )showspacesshowspaces showspaces27

showspacesshowspaces showspaces28 def tearDown = {showspacesshowspaces showspaces29 ver i f yNoMore Inte rac t i ons ( primitiveMock )showspacesshowspaces showspaces30 ver i f yNoMore Inte rac t i ons ( coreMock )showspacesshowspaces showspaces31 }showspacesshowspaces showspaces32 }showspacesshowspaces showspaces33

showspacesshowspaces showspaces34 ”PowerOn” should ” f a i l and disconnect , ” +showspacesshowspaces showspaces35 ”when attach f a i l s . ” inshowspacesshowspaces showspaces36 new CUT with Fa i l u r e {showspacesshowspaces showspaces37

showspacesshowspaces showspaces38 def setup =showspacesshowspaces showspaces39 terminate (when( coreMock . attach ( ) ) )showspacesshowspaces showspaces40

showspacesshowspaces showspaces41 run ( cut . powerOn) and {showspacesshowspaces showspaces42 inOrder . v e r i f y ( primitiveMock ) . connect ( )showspacesshowspaces showspaces43 inOrder . v e r i f y ( coreMock ) . attach ( )showspacesshowspaces showspaces44 inOrder . v e r i f y ( primitiveMock ) . d i s connec t ( )showspacesshowspaces showspaces45 }showspacesshowspaces showspaces46 }showspacesshowspaces showspaces47

showspacesshowspaces showspaces48 i t should ” succeed and not d i sconnect , ” +

138

Page 155: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

D.3. PROTOCOL TESTS

showspacesshowspaces showspaces49 ”when attach succeeds . ” inshowspacesshowspaces showspaces50 new CUT with Success {showspacesshowspaces showspaces51

showspacesshowspaces showspaces52 def setup =showspacesshowspaces showspaces53 cont inue (when( coreMock . attach ( ) ) )showspacesshowspaces showspaces54

showspacesshowspaces showspaces55 run ( cut . powerOn) and {showspacesshowspaces showspaces56 inOrder . v e r i f y ( primitiveMock ) . connect ( )showspacesshowspaces showspaces57 inOrder . v e r i f y ( coreMock ) . attach ( )showspacesshowspaces showspaces58 }showspacesshowspaces showspaces59 }showspacesshowspaces showspaces60

showspacesshowspaces showspaces61 ”PowerOff” should ” f a i l , ” +showspacesshowspaces showspaces62 ”when detach f a i l s . ” inshowspacesshowspaces showspaces63 new CUT with Fa i l u r e {showspacesshowspaces showspaces64

showspacesshowspaces showspaces65 def setup =showspacesshowspaces showspaces66 terminate (when( coreMock . detach ( ) ) )showspacesshowspaces showspaces67

showspacesshowspaces showspaces68 run ( cut . powerOff ) and {showspacesshowspaces showspaces69 v e r i f y ( coreMock ) . detach ( )showspacesshowspaces showspaces70 }showspacesshowspaces showspaces71 }showspacesshowspaces showspaces72

showspacesshowspaces showspaces73 i t should ” succeeed and disconnect , ” +showspacesshowspaces showspaces74 ”when detach succeeds . ” inshowspacesshowspaces showspaces75 new CUT with Success {showspacesshowspaces showspaces76

showspacesshowspaces showspaces77 def setup =showspacesshowspaces showspaces78 cont inue (when( coreMock . detach ( ) ) )showspacesshowspaces showspaces79

showspacesshowspaces showspaces80 run ( cut . powerOff ) and {showspacesshowspaces showspaces81 inOrder . v e r i f y ( coreMock ) . detach ( )showspacesshowspaces showspaces82 inOrder . v e r i f y ( primitiveMock ) . d i s connec t ( )showspacesshowspaces showspaces83 }showspacesshowspaces showspaces84 }showspacesshowspaces showspaces85

showspacesshowspaces showspaces86 ”ForcedDetach” shouldshowspacesshowspaces showspaces87 ” f i r s t send DETACH ACCEPT, ” +showspacesshowspaces showspaces88 ” then d i s connec t ” +showspacesshowspaces showspaces89 ”and then detachComplete . ” inshowspacesshowspaces showspaces90 new CUT with Success {showspacesshowspaces showspaces91 def setup = {} // no setupshowspacesshowspaces showspaces92

showspacesshowspaces showspaces93 run { cut . forcedDetach } and {showspacesshowspaces showspaces94 inOrder . v e r i f y ( primitiveMock ) . send (DETACH ACCEPT)showspacesshowspaces showspaces95 inOrder . v e r i f y ( primitiveMock ) . d i s connec t ( )showspacesshowspaces showspaces96 inOrder . v e r i f y ( primitiveMock ) . detachComplete ( )showspacesshowspaces showspaces97 }showspacesshowspaces showspaces98 }showspacesshowspaces showspaces99 }showspacesshowspaces

Code listing D.25: Test source file protocol/procedure/PrimitiveProceduresSpec.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co l . procedure

139

Page 156: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX D. TOY EXAMPLE IMPLEMENTATION SOURCE CODE

showspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import org . mockito . Mockito . v e r i f yshowspacesshowspaces showspaces4 import org . mockito . Mockito . ve r i f yNoMore Inte rac t i onsshowspacesshowspaces showspaces5 import org . s c a l a t e s t . FlatSpecshowspacesshowspaces showspaces6 import org . s c a l a t e s t . mock . MockitoSugarshowspacesshowspaces showspaces7

showspacesshowspaces showspaces8 import pro to co l . Message .AUTH FAILshowspacesshowspaces showspaces9 import pro to co l . Message .CONNECTshowspacesshowspaces showspaces10 import pro to co l . Message .CONNECT DONEshowspacesshowspaces showspaces11 import pro to co l . Message .CONNECT FAILshowspacesshowspaces showspaces12 import pro to co l . Message .DETACH COMPLETEshowspacesshowspaces showspaces13 import pro to co l . Message .DISCONNECTshowspacesshowspaces showspaces14 import pro to co l . Message .DISCONNECT DONEshowspacesshowspaces showspaces15 import pro to co l . Message .RECEIVEshowspacesshowspaces showspaces16 import pro to co l . Message .SENDshowspacesshowspaces showspaces17 import pro to co l . Message .SEND ACKshowspacesshowspaces showspaces18 import pro to co l . Message . SEND FAILshowspacesshowspaces showspaces19 import pro to co l . Stratumshowspacesshowspaces showspaces20 import thunkprocedure . Procedure . wrapThunkshowspacesshowspaces showspaces21

showspacesshowspaces showspaces22 class Primit iveProceduresSpec extends FlatSpecshowspacesshowspaces showspaces23 with MockitoSugar {showspacesshowspaces showspaces24

showspacesshowspaces showspaces25 trait CUT extends Fixture {showspacesshowspaces showspaces26 val rad io = mock [ Stratum ] ( ” rad io ” )showspacesshowspaces showspaces27 val appl = mock [ Stratum ] ( ” appl ” )showspacesshowspaces showspaces28 val cut : Pr imi t iveProcedures =showspacesshowspaces showspaces29 new Primit iveProcedures Impl ( environment , radio , appl )showspacesshowspaces showspaces30

showspacesshowspaces showspaces31 def setup = {} // no setupshowspacesshowspaces showspaces32

showspacesshowspaces showspaces33 def tearDown = {showspacesshowspaces showspaces34 ver i f yNoMore Inte rac t i ons ( rad io )showspacesshowspaces showspaces35 ver i f yNoMore Inte rac t i ons ( appl )showspacesshowspaces showspaces36 }showspacesshowspaces showspaces37 }showspacesshowspaces showspaces38

showspacesshowspaces showspaces39 ”Connect” should ” succeed a f t e r ” +showspacesshowspaces showspaces40 ” output CONNECT to rad io l a y e r ” +showspacesshowspaces showspaces41 ”when r e c e i v e s CONNECT DONE. ” inshowspacesshowspaces showspaces42 new CUT with Success {showspacesshowspaces showspaces43

showspacesshowspaces showspaces44 run {showspacesshowspaces showspaces45 cut . connect ( )showspacesshowspaces showspaces46

showspacesshowspaces showspaces47 } w i t h I n t e r a c t i o n { t =>showspacesshowspaces showspaces48 v e r i f y ( rad io ) . output (CONNECT)showspacesshowspaces showspaces49 t << CONNECT DONEshowspacesshowspaces showspaces50 }showspacesshowspaces showspaces51 }showspacesshowspaces showspaces52

showspacesshowspaces showspaces53 i t should ” f a i l a f t e r ” +showspacesshowspaces showspaces54 ” output CONNECT to rad io l a y e r ” +showspacesshowspaces showspaces55 ”when r e c e i v e s CONNECT FAIL. ” inshowspacesshowspaces showspaces56 new CUT with Fa i l u r e {showspacesshowspaces showspaces57

showspacesshowspaces showspaces58 run {

140

Page 157: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

D.3. PROTOCOL TESTS

showspacesshowspaces showspaces59 cut . connect ( )showspacesshowspaces showspaces60

showspacesshowspaces showspaces61 } w i t h I n t e r a c t i o n { t =>showspacesshowspaces showspaces62 v e r i f y ( rad io ) . output (CONNECT)showspacesshowspaces showspaces63 t << CONNECT FAILshowspacesshowspaces showspaces64 }showspacesshowspaces showspaces65 }showspacesshowspaces showspaces66

showspacesshowspaces showspaces67 ” Disconnect ” should ” succeed a f t e r ” +showspacesshowspaces showspaces68 ” output DISCONNECT to rad io l a y e r . ” inshowspacesshowspaces showspaces69 new CUT with Success {showspacesshowspaces showspaces70

showspacesshowspaces showspaces71 run ( cut . d i s connec t ) w i t h I n t e r a c t i o n { t =>showspacesshowspaces showspaces72 v e r i f y ( rad io ) . output (DISCONNECT)showspacesshowspaces showspaces73 a s s e r t ( t . i sWait ingForInput )showspacesshowspaces showspaces74 t << DISCONNECT DONEshowspacesshowspaces showspaces75 }showspacesshowspaces showspaces76 }showspacesshowspaces showspaces77

showspacesshowspaces showspaces78 ”DetachComplete” should ” succeed a f t e r ” +showspacesshowspaces showspaces79 ” output DETACH COMPLETE to appl l a y e r . ” inshowspacesshowspaces showspaces80 new CUT with Success {showspacesshowspaces showspaces81

showspacesshowspaces showspaces82 run ( cut . detachComplete ) andshowspacesshowspaces showspaces83 v e r i f y ( appl ) . output (DETACH COMPLETE)showspacesshowspaces showspaces84 }showspacesshowspaces showspaces85

showspacesshowspaces showspaces86 ”Send” should ” succeed a f t e r ” +showspacesshowspaces showspaces87 ” output SEND payload to rad io layer , ” +showspacesshowspaces showspaces88 ”when r e c e i v e s SEND ACK. ” inshowspacesshowspaces showspaces89 new CUT with Success {showspacesshowspaces showspaces90

showspacesshowspaces showspaces91 run {showspacesshowspaces showspaces92 cut . send (AUTH FAIL)showspacesshowspaces showspaces93

showspacesshowspaces showspaces94 } w i t h I n t e r a c t i o n { t =>showspacesshowspaces showspaces95 v e r i f y ( rad io ) . output (SEND(AUTH FAIL) )showspacesshowspaces showspaces96 t << SEND ACKshowspacesshowspaces showspaces97 }showspacesshowspaces showspaces98 }showspacesshowspaces showspaces99

showspacesshowspaces showspaces100 i t should ” f a i l a f t e r ” +showspacesshowspaces showspaces101 ” output SEND payload to rad io layer , ” +showspacesshowspaces showspaces102 ”when r e c e i v e s SEND FAIL . ” inshowspacesshowspaces showspaces103 new CUT with Fa i l u r e {showspacesshowspaces showspaces104

showspacesshowspaces showspaces105 run {showspacesshowspaces showspaces106 cut . send (AUTH FAIL)showspacesshowspaces showspaces107

showspacesshowspaces showspaces108 } w i t h I n t e r a c t i o n { t =>showspacesshowspaces showspaces109 v e r i f y ( rad io ) . output (SEND(AUTH FAIL) )showspacesshowspaces showspaces110 t << SEND FAILshowspacesshowspaces showspaces111 }showspacesshowspaces showspaces112 }showspacesshowspaces showspaces113

showspacesshowspaces showspaces114 ” ReceiveExpected ” should ” succeed , ” +showspacesshowspaces showspaces115 ”when input i s as expected . ” in

141

Page 158: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX D. TOY EXAMPLE IMPLEMENTATION SOURCE CODE

showspacesshowspaces showspaces116 new CUT with Success {showspacesshowspaces showspaces117 run {showspacesshowspaces showspaces118 cut . r ece iveExpected (DISCONNECT)showspacesshowspaces showspaces119

showspacesshowspaces showspaces120 } w i t h I n t e r a c t i o n { << RECEIVE(DISCONNECT) }showspacesshowspaces showspaces121 }showspacesshowspaces showspaces122

showspacesshowspaces showspaces123 ” Receive ” should ” re turn the content o f a ” +showspacesshowspaces showspaces124 ”RECEIVE−message . ” inshowspacesshowspaces showspaces125 new CUT with Success {showspacesshowspaces showspaces126 run {showspacesshowspaces showspaces127 a s s e r t ( cut . r e c e i v e ( ) === DISCONNECT)showspacesshowspaces showspaces128

showspacesshowspaces showspaces129 } w i t h I n t e r a c t i o n { << RECEIVE(DISCONNECT) }showspacesshowspaces showspaces130 }showspacesshowspaces showspaces131 }showspacesshowspaces

D.3.4 Test code folder protocol/procedure/mockable

Code listing D.26: Test source file protocol/procedure/mockable/AuthMock.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co l . procedure . mockableshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import org . s c a l a t e s t . mock . MockitoSugar . mockshowspacesshowspaces showspaces4 import pro to co l . procedure . CoreProceduresshowspacesshowspaces showspaces5 import pro to co l . procedure . Environmentshowspacesshowspaces showspaces6 import pro to co l . procedure . AuthProceduresshowspacesshowspaces showspaces7

showspacesshowspaces showspaces8 /∗∗ Mock trait that hides cps−annotations . ∗/showspacesshowspaces showspaces9 trait AuthMock {showspacesshowspaces showspaces10

showspacesshowspaces showspaces11 /∗∗ Determines whether this procedure should f a i l or not . ∗/showspacesshowspaces showspaces12 def au then t i c a t i on ( ) : Booleanshowspacesshowspaces showspaces13 }showspacesshowspaces showspaces14

showspacesshowspaces showspaces15 object AuthMock {showspacesshowspaces showspaces16 def apply ( env : Environment ) : ( AuthProcedures , AuthMock) = {showspacesshowspaces showspaces17

showspacesshowspaces showspaces18 def mf = mightFai l ( env )showspacesshowspaces showspaces19

showspacesshowspaces showspaces20 val am = mock [ AuthMock ]showspacesshowspaces showspaces21 val ap = new AuthProcedures {showspacesshowspaces showspaces22 def au then t i c a t i on ( ) = mf { am. au then t i c a t i on ( ) }showspacesshowspaces showspaces23 }showspacesshowspaces showspaces24

showspacesshowspaces showspaces25 ( ap , am)showspacesshowspaces showspaces26 }showspacesshowspaces showspaces27 }showspacesshowspaces

Code listing D.27: Test source file protocol/procedure/mockable/CoreMock.scala

showspacesshowspaces

142

Page 159: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

D.3. PROTOCOL TESTS

showspacesshowspaces showspaces1 package pro to co l . procedure . mockableshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import org . s c a l a t e s t . mock . MockitoSugar . mockshowspacesshowspaces showspaces4

showspacesshowspaces showspaces5 import pro to co l . procedure . CoreProceduresshowspacesshowspaces showspaces6 import pro to co l . procedure . Environmentshowspacesshowspaces showspaces7

showspacesshowspaces showspaces8 /∗∗ Mock trait that hides cps−annotations . ∗/showspacesshowspaces showspaces9 trait CoreMock {showspacesshowspaces showspaces10

showspacesshowspaces showspaces11 /∗∗ Determines whether this procedure should f a i l or not . ∗/showspacesshowspaces showspaces12 def attach ( ) : Booleanshowspacesshowspaces showspaces13

showspacesshowspaces showspaces14 /∗∗ Determines whether this procedure should f a i l or not . ∗/showspacesshowspaces showspaces15 def detach ( ) : Booleanshowspacesshowspaces showspaces16 }showspacesshowspaces showspaces17

showspacesshowspaces showspaces18 object CoreMock {showspacesshowspaces showspaces19 def apply (showspacesshowspaces showspaces20 environment : Environment ) : ( CoreProcedures , CoreMock ) = {showspacesshowspaces showspaces21

showspacesshowspaces showspaces22 def mf = mightFai l ( environment )showspacesshowspaces showspaces23

showspacesshowspaces showspaces24 val cm = mock [ CoreMock ]showspacesshowspaces showspaces25 val cp = new CoreProcedures {showspacesshowspaces showspaces26 def attach ( ) = mf { cm. attach ( ) }showspacesshowspaces showspaces27 def detach ( ) = mf { cm. detach ( ) }showspacesshowspaces showspaces28 }showspacesshowspaces showspaces29

showspacesshowspaces showspaces30 ( cp , cm)showspacesshowspaces showspaces31 }showspacesshowspaces showspaces32 }showspacesshowspaces

Code listing D.28: Test source file protocol/procedure/mockable/package.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co l . procedureshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import org . mockito . stubbing . OngoingStubbingshowspacesshowspaces showspaces4

showspacesshowspaces showspaces5 /∗∗ Mock object helpers ∗/showspacesshowspaces showspaces6 package object mockable {showspacesshowspaces showspaces7

showspacesshowspaces showspaces8 /∗∗showspacesshowspaces showspaces9 ∗ Triggers an procedure fa i lure (termination) i f givenshowspacesshowspaces showspaces10 ∗ argument function returns true .showspacesshowspaces showspaces11 ∗/showspacesshowspaces showspaces12 def mightFai l ( env : Environment ) ( doFai l : => Boolean ) =showspacesshowspaces showspaces13 i f ( doFai l ) env . f a i l u r e ( )showspacesshowspaces showspaces14

showspacesshowspaces showspaces15 /∗∗showspacesshowspaces showspaces16 ∗ Sugar . Procedure termination i s associated with mockshowspacesshowspaces showspaces17 ∗ methods returning true .showspacesshowspaces showspaces18 ∗/showspacesshowspaces showspaces19 def terminate ( stubbing : => OngoingStubbing [ Boolean ] ) : Unit =showspacesshowspaces showspaces20 stubbing . thenReturn ( true )

143

Page 160: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

APPENDIX D. TOY EXAMPLE IMPLEMENTATION SOURCE CODE

showspacesshowspaces showspaces21

showspacesshowspaces showspaces22 /∗∗showspacesshowspaces showspaces23 ∗ Sugar . Continues evaluation of procedure i s associatedshowspacesshowspaces showspaces24 ∗ with mock methods returning fa l se .showspacesshowspaces showspaces25 ∗/showspacesshowspaces showspaces26 def cont inue ( stubbing : => OngoingStubbing [ Boolean ] ) : Unit =showspacesshowspaces showspaces27 stubbing . thenReturn ( fa l se )showspacesshowspaces showspaces28

showspacesshowspaces showspaces29 }showspacesshowspaces

Code listing D.29: Test source file protocol/procedure/mockable/PrimitiveMock.scala

showspacesshowspacesshowspacesshowspaces showspaces1 package pro to co l . procedure . mockableshowspacesshowspaces showspaces2

showspacesshowspaces showspaces3 import pro to co l . Messageshowspacesshowspaces showspaces4 import pro to co l . procedure . Pr imi t iveProceduresshowspacesshowspaces showspaces5 import org . s c a l a t e s t . mock . MockitoSugar . mockshowspacesshowspaces showspaces6 import pro to co l . procedure . Environmentshowspacesshowspaces showspaces7

showspacesshowspaces showspaces8 /∗∗ Mock trait that hides CPS−annotations for some methods . ∗/showspacesshowspaces showspaces9 trait PrimitiveMock {showspacesshowspaces showspaces10

showspacesshowspaces showspaces11 /∗∗ Identical to method in PrimitiveProcedures . ∗/showspacesshowspaces showspaces12 def connect ( ) : Unitshowspacesshowspaces showspaces13

showspacesshowspaces showspaces14 /∗∗ Identical to method in PrimitiveProcedures . ∗/showspacesshowspaces showspaces15 def d i s connec t ( ) : Unitshowspacesshowspaces showspaces16

showspacesshowspaces showspaces17 /∗∗ Determines whether this procedure should f a i l or not . ∗/showspacesshowspaces showspaces18 def send ( payload : Message ) : Booleanshowspacesshowspaces showspaces19

showspacesshowspaces showspaces20 /∗∗ Determines whether this procedure should f a i l or not . ∗/showspacesshowspaces showspaces21 def rece iveExpected ( expected : Message ) : Booleanshowspacesshowspaces showspaces22

showspacesshowspaces showspaces23 /∗∗ Enables the poss ibi l i ty to mock the return message ∗/showspacesshowspaces showspaces24 def r e c e i v e ( ) : Messageshowspacesshowspaces showspaces25

showspacesshowspaces showspaces26 /∗∗ Identical to method in PrimitiveProcedures . ∗/showspacesshowspaces showspaces27 def detachComplete ( ) : Unitshowspacesshowspaces showspaces28 }showspacesshowspaces showspaces29

showspacesshowspaces showspaces30 object PrimitiveMock {showspacesshowspaces showspaces31

showspacesshowspaces showspaces32 def apply ( environment : Environment ) : ( Pr imit iveProcedures ,showspacesshowspaces showspacesPrimitiveMock ) = {showspacesshowspaces showspaces33

showspacesshowspaces showspaces34 def mf = mightFai l ( environment )showspacesshowspaces showspaces35

showspacesshowspaces showspaces36 val pm = mock [ PrimitiveMock ]showspacesshowspaces showspaces37 val pp = new Pr imit iveProcedures {showspacesshowspaces showspaces38 def connect ( ) = pm. connect ( )showspacesshowspaces showspaces39 def d i s connec t ( ) = pm. d i s connec t ( )showspacesshowspaces showspaces40 def detachComplete ( ) = pm. detachComplete ( )showspacesshowspaces showspaces41 def r e c e i v e ( ) = pm. r e c e i v e ( )showspacesshowspaces showspaces42

144

Page 161: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

D.3. PROTOCOL TESTS

showspacesshowspaces showspaces43 def send ( payload : Message ) =showspacesshowspaces showspaces44 mf { pm. send ( payload ) }showspacesshowspaces showspaces45 def rece iveExpected ( expected : Message ) =showspacesshowspaces showspaces46 mf { pm. rece iveExpected ( expected ) }showspacesshowspaces showspaces47 }showspacesshowspaces showspaces48

showspacesshowspaces showspaces49 (pp , pm)showspacesshowspaces showspaces50 }showspacesshowspaces showspaces51 }showspacesshowspaces

145

Page 162: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

Index

Akka FMS, 32AS, 43asynchronous procedure, 5Await.result, 46

become, 30

composition of SM and actor, 33continuation, 51continuation passing style, 52CPS, 52

dataflow, 51delimited continuations, 51design pattern, 26domain specific language, 34DSL, 34

Eclipse, 1

FAR, 46finite state machine, 5FSMSTO, 43FSMT, 44FTO, 45Future, 45

GJT, 42

internal DSL, 35

Java virtual machine, 1

LJT, 42

match/case implementation, 23

ND, 41

RTO, 45RW, 82

state machine, 5state machine compiler, 29state pattern, 25switch/case implementation, 23

TE, 82thread sleep, 41thunk procedure, 51toy example, 62transition table, 24TS, 41

unbecome, 30UniMod, 1

146

Page 163: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

Bibliography

[1] EPFL - Ecole Polytechnique Federale de Lausanne, Lausanne, Switzer-land. The official scala programming language site. http://www.

scala-lang.org. Accessed: 2012-10-29.

[2] Erlang/otp design principles user’s guide - finite state ma-chines. http://www.erlang.org/documentation/doc-5.9.3/doc/

design_principles/fsm.html#id68991. Accessed: 2013-02-22.

[3] E. Gamma, R. Helm, R. Johnson, and J. Vlissides. Design Patterns:Elements of Reusable Object-Oriented Software. Addison-Wesley, 1995.

[4] P. Haller and M. Odersky. Event-based programming withoutinversion of control. In Modular Programming Languages, Lec-ture Notes in Computer Science 4228, pages 4–22. Springer, 2006.Accessed: 2013-03-20 from http://infoscience.epfl.ch/record/

95710/files/jmlc06.pdf.

[5] P. Haller and F. Sommers. Actors in Scala. Artima, 2011.

[6] C. S. Horstman. Scala for the Impatient. PearsonEducation, Inc, 2012.

[7] O. Kullberg. Ett forsta steg i Scala. Studentlitteratur, 2011.

[8] R. C. Martin. Agile software developement: Principles, Patterns, andPractices. Pearson Education, 2003.

[9] M. Odersky, L. Spoon, and B. Venners. Programming in Scala, FirstEdition. Artima Inc, 2008. Accessed: 2012-11-16 from http://www.

artima.com/pins1ed.

[10] Oracle. Documentation for Java SE 6. http://http://docs.oracle.com/javase/6/docs/api/. Accessed: 2013-03-06.

[11] L. Prechelt. An empirical comparison of seven programming languages.Computer, 33(10):23–29, October 2000.

[12] T. Rompf, I. Maier, and M. Odersky. Implementing first-class polymor-phic delimited continuations by a type-directed selective cps-transform.

147

Page 164: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

BIBLIOGRAPHY

In ICFP ’09 Proceedings of the 14th ACM SIGPLAN internationalconference on Functional programming, pages 317–328. Associationfor Computing Machinery (AMC), 2009. Accessed: 2012-10-31 fromhttp://lampwww.epfl.ch/~rompf/continuations-icfp09.pdf.

[13] R. Stansifer. The Study of Programming Languages. Prentice-Hall,1995.

[14] Typesafe Inc. Documentation for stable version of Akka. http://akka.io/docs/stable/. Accessed: 2012-10-29.

[15] D. Wampler and A. Payne. Programming Scala. O’Reilly Media,2008. Accessed: 2012-11-16 from http://ofps.oreilly.com/titles/

9780596155957.

148

Page 165: liu.diva-portal.orgliu.diva-portal.org/smash/get/diva2:642459/FULLTEXT01.pdf · Abstract This thesis work investigates how to represent protocols for asynchronous communication in

På svenska

Detta dokument hålls tillgängligt på Internet – eller dess framtida ersättare –under en längre tid från publiceringsdatum under förutsättning att inga extra-ordinära omständigheter uppstår.

Tillgång till dokumentet innebär tillstånd för var och en att läsa, ladda ner,skriva ut enstaka kopior för enskilt bruk och att använda det oförändrat förickekommersiell forskning och för undervisning. Överföring av upphovsrättenvid en senare tidpunkt kan inte upphäva detta tillstånd. All annan användning avdokumentet kräver upphovsmannens medgivande. För att garantera äktheten,säkerheten och tillgängligheten finns det lösningar av teknisk och administrativart.

Upphovsmannens ideella rätt innefattar rätt att bli nämnd som upphovsman iden omfattning som god sed kräver vid användning av dokumentet på ovanbeskrivna sätt samt skydd mot att dokumentet ändras eller presenteras i sådanform eller i sådant sammanhang som är kränkande för upphovsmannens litteräraeller konstnärliga anseende eller egenart.

För ytterligare information om Linköping University Electronic Press seförlagets hemsida: http://www.ep.liu.se/

In English

The publishers will keep this document online on the Internet - or its possiblereplacement - for a considerable time from the date of publication barringexceptional circumstances.

The online availability of the document implies a permanent permission foranyone to read, to download, to print out single copies for your own use and touse it unchanged for any non-commercial research and educational purpose.Subsequent transfers of copyright cannot revoke this permission. All other usesof the document are conditional on the consent of the copyright owner. Thepublisher has taken technical and administrative measures to assure authenticity,security and accessibility.

According to intellectual property law the author has the right to bementioned when his/her work is accessed as described above and to be protectedagainst infringement.

For additional information about the Linköping University Electronic Pressand its procedures for publication and for assurance of document integrity,please refer to its WWW home page: http://www.ep.liu.se/

© Joakim Eriksson