SlideShare une entreprise Scribd logo
1  sur  20
Intro to OTP Behaviours
 Presenters: John Patton and Tristan Sloughter
What we’ll cover
• Build concepts over the course of the
  presentation to create a general server
  architecture

• Assumption: basic Erlang knowledge
• We’ll have time for Q&A at the end
What are we going to do?
• Look at high-level concepts used in making a
  simple chat server

• Start off using basic Erlang!!!
• Let’s understand the concepts first
• Build on top of concepts until we
  understand how a general server framework
  works under the hood
Simple Chat Server
What kind of things does a simple chat server need?
Simple Chat Server
What kind of things does a simple chat server need?
 •   Startup routine

 •   Server needs to be aware of the clients that are
     connected

 •   Clients need to register and unregister with the server

 •   The server needs to facilitate sending chat messages from
     one client to another

 •   Shutdown routine
What does our design look like?
                               start            stop

 register_client('john',Pid)                              register_client('tristan',Pid)
                                        Chat
         Chat                          Server                    Chat
         Client                                                  Client

send_message('tristan',Msg)                            send_message('john',Msg)

                               Client Lookup (dict)
                          Client = atom()   pid = pid()
                                'john'       <0.35.0>
                              'tristan'      <0.39.0>
Basic Design

 client defined elsewhere
 chat_server                                         chat_server
chat_server ! {register_client, Name, Pid}.

chat_server ! {send_message, To, Msg}.
                                                                  receive loop
chat_server ! {unregister_client, Name}.
                                                              {register_client,...}

...                                           loop            {unregister_client,...}
                                                              {send_message,...}
                                                              {stop,...}




                                                            loop()
Chat Server Receive loop
•   Our chat server’s loop function
    is spawned and registered
                                                  chat_server
•   The chat server loop function
    will maintain the dictionary of
    clients (client name -> pid)                               receive loop

                                                           {register_client,...}
                                           loop            {unregister_client,...}

•   Traditional tail recursion, will run                   {send_message,...}
                                                           {stop,...}

    until a stop message is received
                                                         loop()
•   Messages sent from a client are
    handled within the receive loop
Let’s organize startup                  start_link
  and initialization                                                spawn



•   Create an initialization function
    to handle registering self()
                                            init
                                        ‘chat_server’
•   Wrap the spawn inside a
    start_link function

•
                                                                 receive loop
    Instead of spawning loop, let’s                          {register_client,...}
    spawn the init function and call       loop              {unregister_client,...}
                                                             {send_message,...}
    loop                                                     {stop,...}



                                                    loop()
Where should we keep                start_link
 track of our clients?                                              spawn



•   Let’s make use of an internal
    state, a key-value dictionary
                                        init
                                    ‘chat_server’
•   Init will be responsible for      dict:new()
    creating the server’s State:
    {ClientName, ClientPID}                     State
                                                                 receive loop



•
                                                             {register_client,...}
    State will be passed into and      loop                  {unregister_client,...}
                                                             {send_message,...}
    maintained within the receive                            {stop,...}


    loop
                                               loop(State)
Let’s look back at
      where we started
 client defined elsewhere
 chat_server                                         chat_server
chat_server ! {register_client, Name, Pid}.

chat_server ! {send_message, To, Msg}.
                                                                  receive loop
chat_server ! {unregister_client, Name}.
                                                              {register_client,...}

...                                           loop            {unregister_client,...}
                                                              {send_message,...}
                                                              {stop,...}




                                                            loop()
Take a look at
        where we are.                             start_link
                                                                                  spawn
 client defined elsewhere
 chat_server
chat_server ! {register_client, Name, Pid}.

chat_server ! {send_message, To, Msg}.                init
                                                  ‘chat_server’
chat_server ! {unregister_client, Name}.      !     dict:new()

...                                                           State
                                                                               receive loop

                                                                           {register_client,...}

                                                     loop                  {unregister_client,...}
                                                                           {send_message,...}
                                                                           {stop,...}



                                                             loop(State)
Let’s make it easier for the
 client to bang messages
                                                          start_link
                                                                                  spawn

  •   “API” Functions in the
      chat_server module
      that a client can call                                 init
                                                          ‘chat_server’
                                   register_client          dict:new()
                                                                          State




  •
                                  unregister_client
      API functions facilitate                        !     loop
                                                                                        receive loop

                                                                                   {register_client,...}

      banging messages to the      send_message                                    {unregister_client,...}
                                                                                   {send_message,...}
                                                                                   {stop,...}


      server pid for the client         stop
                                                                    loop(State)




  •   Cleans up the code
Let’s make a handler for
    banged messages                                   start_link
                                                                              spawn

•   “Callback” functions in
    a module that will
    implement the                                        init
                                                      ‘chat_server’
                               register_client          dict:new()
    message functionality                                             State

                              unregister_client

•   Turns message loop         send_message
                                                  !     loop
                                                                                    receive loop

                                                                               {register_client,...}
                                                                               {unregister_client,...}

    into an interface                                                          {send_message,...}
                                                                               {stop,...}

                                    stop

•   Separates the                                               loop(State)


    implementation from
                               handle_receive
    the interface                                     {Message, State}

•
                                 terminate
    Callbacks update state
Why use OTP?
•   Large collection of libraries

•   Unified Application packaging and release structure

•   Standardized coding practices

•   Components: HTTP and FTP server, CORBA
    ORB, SNMP Agent, IDL, Error Handling

• Formalized design patterns into
    “behaviors”
What is an OTP
      behavior?                          OTP Behavior
                                      • gen_*:functionA/3
•   Simply: a formalization of a      • gen_*:functionB/2
    common pattern into two
    parts.                              ...

    •   Behavior Module that defines
        the pattern interface.
                                       Callback Module
    •   Callback Module that          • module:callbackA/2
        implements the pattern
        interface.                    • module:callbackB/3
                                        ...
Why use OTP for our server?
•   Much of the code needed to create the server in
    our example is already written in the OTP
    behavior: gen_server

•   Since the interface is only used to call a callback
    function, the callbacks can be in any module

•   The gen_server has a generic set of behavior
    functions available for use by ANY implementation
    (can use more than one callback implementation)
Behavior: gen_server
     chat server                  gen_server               !              callback
chat_server:start_link          gen_server:start_link            callback:init/1

chat_server:send_message        gen_server:call                  callback:handle_call/3
chat_server:register_client     gen_server:multi_call
chat_server:unregister_client

chat_server:stop                gen_server:cast                  callback:handle_cast/2
                                     sends stop message               returns: {stop, normal, State}
                                                                 callback:terminate/2



                                State is maintained here   State is passed in and returned back here
More Information
•   Client-server design principles:
    http://www.erlang.org/doc/design_principles/
    gen_server_concepts.html

•   gen_server “behaviour”:
    http://www.erlang.org/doc/man/gen_server.html

•   Chicago Erlang Users Group: start a discussion!

•   Me: John Patton <jpatton@gmail.com>
What happens if it
   crashes?

Contenu connexe

Dernier

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 

Dernier (20)

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 

En vedette

PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...DevGAMM Conference
 
Barbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationBarbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationErica Santiago
 

En vedette (20)

PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 
More than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike RoutesMore than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike Routes
 
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
Ride the Storm: Navigating Through Unstable Periods / Katerina Rudko (Belka G...
 
Barbie - Brand Strategy Presentation
Barbie - Brand Strategy PresentationBarbie - Brand Strategy Presentation
Barbie - Brand Strategy Presentation
 

CEUG: Introduction to OTP Behaviors, Part I - gen_server

  • 1. Intro to OTP Behaviours Presenters: John Patton and Tristan Sloughter
  • 2. What we’ll cover • Build concepts over the course of the presentation to create a general server architecture • Assumption: basic Erlang knowledge • We’ll have time for Q&A at the end
  • 3. What are we going to do? • Look at high-level concepts used in making a simple chat server • Start off using basic Erlang!!! • Let’s understand the concepts first • Build on top of concepts until we understand how a general server framework works under the hood
  • 4. Simple Chat Server What kind of things does a simple chat server need?
  • 5. Simple Chat Server What kind of things does a simple chat server need? • Startup routine • Server needs to be aware of the clients that are connected • Clients need to register and unregister with the server • The server needs to facilitate sending chat messages from one client to another • Shutdown routine
  • 6. What does our design look like? start stop register_client('john',Pid) register_client('tristan',Pid) Chat Chat Server Chat Client Client send_message('tristan',Msg) send_message('john',Msg) Client Lookup (dict) Client = atom() pid = pid() 'john' <0.35.0> 'tristan' <0.39.0>
  • 7. Basic Design client defined elsewhere chat_server chat_server chat_server ! {register_client, Name, Pid}. chat_server ! {send_message, To, Msg}. receive loop chat_server ! {unregister_client, Name}. {register_client,...} ... loop {unregister_client,...} {send_message,...} {stop,...} loop()
  • 8. Chat Server Receive loop • Our chat server’s loop function is spawned and registered chat_server • The chat server loop function will maintain the dictionary of clients (client name -> pid) receive loop {register_client,...} loop {unregister_client,...} • Traditional tail recursion, will run {send_message,...} {stop,...} until a stop message is received loop() • Messages sent from a client are handled within the receive loop
  • 9. Let’s organize startup start_link and initialization spawn • Create an initialization function to handle registering self() init ‘chat_server’ • Wrap the spawn inside a start_link function • receive loop Instead of spawning loop, let’s {register_client,...} spawn the init function and call loop {unregister_client,...} {send_message,...} loop {stop,...} loop()
  • 10. Where should we keep start_link track of our clients? spawn • Let’s make use of an internal state, a key-value dictionary init ‘chat_server’ • Init will be responsible for dict:new() creating the server’s State: {ClientName, ClientPID} State receive loop • {register_client,...} State will be passed into and loop {unregister_client,...} {send_message,...} maintained within the receive {stop,...} loop loop(State)
  • 11. Let’s look back at where we started client defined elsewhere chat_server chat_server chat_server ! {register_client, Name, Pid}. chat_server ! {send_message, To, Msg}. receive loop chat_server ! {unregister_client, Name}. {register_client,...} ... loop {unregister_client,...} {send_message,...} {stop,...} loop()
  • 12. Take a look at where we are. start_link spawn client defined elsewhere chat_server chat_server ! {register_client, Name, Pid}. chat_server ! {send_message, To, Msg}. init ‘chat_server’ chat_server ! {unregister_client, Name}. ! dict:new() ... State receive loop {register_client,...} loop {unregister_client,...} {send_message,...} {stop,...} loop(State)
  • 13. Let’s make it easier for the client to bang messages start_link spawn • “API” Functions in the chat_server module that a client can call init ‘chat_server’ register_client dict:new() State • unregister_client API functions facilitate ! loop receive loop {register_client,...} banging messages to the send_message {unregister_client,...} {send_message,...} {stop,...} server pid for the client stop loop(State) • Cleans up the code
  • 14. Let’s make a handler for banged messages start_link spawn • “Callback” functions in a module that will implement the init ‘chat_server’ register_client dict:new() message functionality State unregister_client • Turns message loop send_message ! loop receive loop {register_client,...} {unregister_client,...} into an interface {send_message,...} {stop,...} stop • Separates the loop(State) implementation from handle_receive the interface {Message, State} • terminate Callbacks update state
  • 15. Why use OTP? • Large collection of libraries • Unified Application packaging and release structure • Standardized coding practices • Components: HTTP and FTP server, CORBA ORB, SNMP Agent, IDL, Error Handling • Formalized design patterns into “behaviors”
  • 16. What is an OTP behavior? OTP Behavior • gen_*:functionA/3 • Simply: a formalization of a • gen_*:functionB/2 common pattern into two parts. ... • Behavior Module that defines the pattern interface. Callback Module • Callback Module that • module:callbackA/2 implements the pattern interface. • module:callbackB/3 ...
  • 17. Why use OTP for our server? • Much of the code needed to create the server in our example is already written in the OTP behavior: gen_server • Since the interface is only used to call a callback function, the callbacks can be in any module • The gen_server has a generic set of behavior functions available for use by ANY implementation (can use more than one callback implementation)
  • 18. Behavior: gen_server chat server gen_server ! callback chat_server:start_link gen_server:start_link callback:init/1 chat_server:send_message gen_server:call callback:handle_call/3 chat_server:register_client gen_server:multi_call chat_server:unregister_client chat_server:stop gen_server:cast callback:handle_cast/2 sends stop message returns: {stop, normal, State} callback:terminate/2 State is maintained here State is passed in and returned back here
  • 19. More Information • Client-server design principles: http://www.erlang.org/doc/design_principles/ gen_server_concepts.html • gen_server “behaviour”: http://www.erlang.org/doc/man/gen_server.html • Chicago Erlang Users Group: start a discussion! • Me: John Patton <jpatton@gmail.com>
  • 20. What happens if it crashes?

Notes de l'éditeur

  1. Remove &amp;#x201C;OTP&amp;#x201D;: just say youre developing a framework for a general server arch
  2. I&apos;d move the 3rd bullet to second bullet, reword it without a specific gen_server reference, say we will build these concepts into a general framework, something like that.. then the 3rd bullet can be we will show erlang&apos;s already existing framework, and why to use it instead
  3. move the spawn and registering bit to slide 9 just focus on the loop first
  4. if you are going to use &quot;behavior&quot;, stick with it, otherwise just use &quot;behavior&quot; everywhere and not make a reference to its english counterpart Revisit verb tense on all bullets Much More: * A major objective of the OTP is to provide a highly productive environment for designing applications.
  5. so 16 is really good, just when you talk, make sure to refer back to your initial guiding example you started with A Behaviour Module is a generic collection of functions provided by OTP. Callback Module is an implementation of a pre-defined set of functions expected by the behaviour.
  6. Lead into Tristan&amp;#x2019;s presentation