Merken

Stuck in the Middle: Leverage the power of Rack Middleware

Zitierlink des Filmsegments
Embed Code

Automatisierte Medienanalyse

Beta
Erkannte Entitäten
Sprachtranskript
with the number of the the the the the path of each each of the morning everyone out they give a covering the start writing as a on the head I am here
to talk about I'm here to learn that my slide there becoming 17 but but also I'm here to talk about a part of the reals ecosystem that I ignored for quite some time and I came to regret that it's the the the new rails developer to ignore rack middleware I mean it's got words like rack and middleware and those neurons are scary especially when you're still getting to the point where you're comfortable with the concepts of models views and controllers and also became a more experienced developer I ran into gems that relied on middleware any no small piece of the middleware in the code of those working in and it's really easy to just pick out the parts of the middleware that seem relevant to the changes you need to make what the budget trying to track down the and so it's pretty easy to think that there's not much more Dirac middleware because to be honest there is that it's designed to be a simple but powerful interface but I never really took the time to understand what was going on so the beginning of my career wreck middlewares which seems so far too advanced for me and jump straight to begin to born into obvious non-military in on a secret I wrote some pretty bad middleware because of that probably the obvious conclusion but I I don't know and it wasn't thread-safe any push back would middleware that should never have been aware was written and I maintain some sprawling middleware that is pretty much unintelligible because it is so sprawling and then I didn't write middleware when I should have I didn't know that it was a tool that I can use so today I want to
address the things that I would have loved to know and some of the mistakes that I made so you don't have to make the person and I know what is another some examples about how you rebuild I think cover y you might want to use regular a tool and because none of the of my section headings this last 1 is called who has it who did this mistake who made this fact which
is I think it's when I stepped in 1 spot that it was a that by those who is talking about things that I used acceptors will try to find you try to get interrelation of them thought so with
white I mean into what rock in that middle where are look at how they fit into rails and then take a brief look at some familiar examples of rock middleware so it's this mapping so it's a little world where Bakhtin
exist errands you need a server for instance for this example use of a CGI server so your users going to make an HTTP request theater browser it's going to hit the CGI server 9 a CGI server is going to take that request and pass it into that different take parts of data that's going to shove onto the environment so it's that's about in 2030 environment variables
I families should be somewhat familiar uh popular HDP exactly 100 all this sort of stuff it's showing into the environment and then it will run your code
now your application code will then write to standard out which the CGI server will pick up on formally into needs to http response and send it back to the user now so with that means is
that your application needs to know that it's being run that suggested it needs to know that it can pull out those environment variables to figure out hey someone's asking for an index and HTML and that's a bit of a problem for many of us because we tend to develop with 1 server and then deployed production with another so using multiple servers in the course of a day and your application has to figure out what's running so move to a world with the rat so when we
shall rock in the middle of your server in your application the situation looks all that different the user makes an HTTP request your server here's Weber can be anything that's server knows that it's it should talk to wrap wrapped passes the information it gets from the server into a standard incoming requests that is the same for any different server and that means that no matter the server that's that is running your application your application can write the same logic and then coming back up the stock it's the same thing your application just returns the response interact compliant weight and rank figures of the details of how to them talk to the server
so what does Rock look like to your application to your application it looks like there's an incoming request with the environment hearts we then I see a
little more we can see that rat took inspiration from CGI because it essentially took those environment variables and wrap them in a harsh and call that the environment but it's no wonder setting those variables on the environment it's passing inter code the outgoing response bigger apples going return includes the status code header is In the content body it so sick of 0 look at the
simplest wrap path we can create that seem to follow 3 rules we need something we can call whether that's a class or an instance method for the proper we have here that the means to accept the environment so that the environments where you have that hash that includes pattern through headers all that information and needs to return an array with the following so here we can see this status which is 200 perhaps of headers you were just saying were returning HTML and every other kind of I so those are the 3 rules need to follow the
so what is rack middleware so we look
at this diagram and then and then zoom in on that the we can see
what we're going to look at the 3 parts of of working with rack now rock took their logo inspiration from a server rack but I mean I can use that to display the 3 different parts at so the 1st part is the handler for your server Web break mongrel C gentlemen etc. busy and therefore the next part is the after that to the bottom that will talk to your very much and so we have a pretty simple set up thing thing that has been at the is is going to flow through rat and get transformed for the server and then framework but what if we want to do things to that request before it hits the server coming back up as the response or hits your application coming in but women come so middlewares allow you to work with the request for the response before it exits either at the bottom of the stack for the top of the stack and this
session some of the power of the white rac middleware can give you some examples of middleware that rails provides you so 1st on rails uses middleware to serve up static files these is no to set up a longing for each request and then 1st of all of the end the request users middleware and set up a cookie for the past the you know flash messages and to pass out parameters so the brands that you use you in controllers that's done in the lower in addition to middleware in the rails codebase within these Ruby web app ecosystem there are other uh notable gems that use middleware as a strategy some them included these for throttling over uh security for pot and authentication of water so this is a quick
look at how we're going to build a middleware so 1st we're going to write a very
basic so that's going to be a pain set up we're just going to be able to ask application here you up and running the 1st will
print a file in the middleware thing will create a class called paying and to make sure that there won't be any means these classes I will throw that in a model so now we have this class middleware king we're going to write and initialize method now every piece of rat middleware needs to except when it's initialize it needs to accept the act then the act could be you work reals out but it can also be another piece of middleware you can imagine middleware as the set of Russian nesting dolls each 1 calls down to the smaller 1 until it hits your house so really what happening here is a middleware is going to be initialized with the next middleware down the stack if it's the very last middle and we call it will be initialized with our rails out so a middleware has to follow the same 3 rules as we need something response to call it must take the environment it it must return this status headers and content body so our common thing here is going to look very much like any the Rails app or anywhere complained I by except for the fact that it will lead to call them the set so let's write the simplest thing that is wrapped compliance so you can see our comet in here is accepting the and and it's returning a compliant response this is really cool this is going to work when we hit our have we will receive a response upon unfortunately is the that in every single case this will never call them the stack every with every request your app will respond with 200 of spelling not what we want to so that's fix that so 1st let's take a look at what that request we're going to take that and pass it out and something that's a little bit better to work with Net requests is going to
have some of these environment variables that but here we can see here that we can look to see whether to get a post we can see that happen and so with that information we're going to
be able to finish this method so in this 1st line we pass out the and into the request object we then check to see if the request pass is the rout that we want to match on if it's not were just and call them the set went into anything with is going to pass everything down they were going to immediately return what the year uh calls them stack what response but if the user can request that the now we're gonna return 200 calls right so let's look at the most basic middleware
request response I'm like then this is actually 1 of the most common middleware I've seen written for small pieces middleware it's amazing how often do you not have beautiful things like relic and instead here on a it solution we need to do a little bit of your own modern endowment so what we're going to do is worry tracking how much time it takes you have to complete a request to index on HTML to any else so also in the same pattern we suffer pain will
take a new file live middleware request money yeah will make a new class again namespace will create this method once again has a reference to the AP that it needs to call down the now we get to the mean of this middleware the company that's going to take the and as we know it needs still and it's going to call them the understand because we want this piece of middleware to always call them is that it's not intersecting and returning any requests and dropping any requests on the floor it's always going to call them we know we need to do this we know that we need to call them so let's get some timing in here what we can start with recording the start time of the call and then we compute the elapsed time now this is nice we're calling down that and we know how long it takes but problem we never actually returned a rocket flight response as you can see here referring just the number the elapsed time in seconds we probably actually literature or complaint response so the way we do that we want we know we want to return the status headers and response we know that will get that data from calling down the stack and so we just save that data or as we call them and we get that response coming back up the down into a middleware only return it so you have is working fine are users are hitting various uh endpoints in our and they're getting responses but we still haven't logged the elapsed time anywhere were computing in short but it's not being sent anyway so let's get working on that we're going to do that in another method I will call that 1 response time and the method will need to know how long it's taken to call them a stack and because it's important for us to know what the pathway is it's not really helpful for me to know that it took 54 seconds for this request a complete if I don't know what round the user was sitting also sending the request into writing the method we want to make sure that it's a private method there's really nothing middleware besides the initialize method and commented that needs to the public so it's a private method it takes elapsed time and the requests will set up a adjacent payload would that be data to be sent to our logging in because the most common set at the most common reason to do this is that you're using something like Splunk here is just an arbitrary implementation and sending it to Splunk with the instrumentation of request that response time and sending the payload and middleware is now complete this I wanna quickly
review a in the example of middleware in because it's after that you're going to the dividing something and it's good to just take a quick look at how you would deal with a larger codebase than something you might right quickly for your so the example here is the throttling Miller is a great option for throttling because it can drop requesting your on the floor or return them helpful in this case we're going to be returning with an off unauthorized response without actually putting any loan application or application never actually sees this are server doesn't have to be deal with the load of bringing that response only down the application we can return as soon as possible so retirado here
and get out 1 of the interesting things you'll see when trying to divide middleware genomes is that you need to find the the core middleware class the class that has been initialized method and the comment that and are always named differently for this 1 it's the women are class but once you find it you'll see that there is initialized method that does take after it also takes options which is an incredibly useful thing for allowing people to configure your code so if you are packaging of middleware as a dance but for the important thing is the and and then a call method is commented as we know takes the environment and on this 2nd line of the call method this some pretty short logic it asks is this request allowed if it is call them the stack and return the results and calling the if it's not all this method rate limit exceeded and presumably were going to return an unauthorized code uh response with some helpful message and I wanna show this to you because it shows how little rack middleware code you really need to right before you can really jump to writing code that is specific to your application to your to what you want to do so you really don't need understand too much of wreck middleware here to get going on with writing a traveller now all you have to know is how to throttle which is a totally different topic but 1 that would be very interesting but not stop so why would we
want to write pieces of rock middleware white is this tool best for middleware can simplify your application middleware is very good at dealing with requests the your applications University so a good example of this the is a situation or a job and
review where we use the support they website called out that for a good outcome this would be at a site where you can see all of our group you add on offerings essentially catalog of products now behind this application also with admin interface for managing as answer but the year promotion the product data the essentially the story has moved
to elements that were not for all now what this means is that we have a lot of people out there who
still want the adult stuttering dot com slash new Alex and data about the relative and those about training and some review . com but on somebody knock on currently has no idea where from the scene that is all it knows is an so our robot file and that France everything from ends up being hundreds of lines long because it needs to redirect users 2 on the marketing side even when as really should know anything about selling out of it just means you how to administer them so the solution here is to pull out some of those round form that root file move them into middleware so that when you in panels that review . com slash new relic you even need to hit the that review . com profile as a proper I can deal with a very simple rock found the learners get a response so far faster which says a redirect to this new site moving
on our middleware can protect your applications so continuing on the theme of healing request before they get to your application there are certain types of request you just don't want your application to deal with there's no point in you know that a particular request as much as there is no need for it here and you Milliken handle and along this line the throttling label that we saw if you're out should never received that request throughout the can stop it also similar is implementing honey honeypots no it's is both the request and response object so when request comes into your application becomes Idirans filing can you hear any number of controllers and often will take again through any 1 of those controllers the only singular piece of college and in fact singular method that you have easy access to you that sees boat that request object coming in and response coming back up is a piece of middleware and so this is how and so this is how we know we want to write that risk request response time in middleware because that is that 1 method you can be confident that it will see any request coming in as well as the response coming back up the no it can be a code sharing mechanisms so this cannot be so interesting to you if you writing middleware for your own personal maps but if you do have a piece of code that you want to share as a gender middleware be an important tool to sharing manner that code and allow users to easily just drop it in without needing to do much additional configuration it so now who has the things that will trigger your successors to get plain your code I 1st wanna talk
about water order interact middleware is important going back to the western this and all analogy it wouldn't make sense to try to fit the largest Russian nesting doll into the smallest 1 is not going to happen similarly we have the right middle
and there's a necessary order so where else provides a really nice rate counts to tell you which middleware are being configured to use to be used with your application right now and the order that they're in so if you 1 make middleware on any money wells that on any modern males and you'll
see this output and this is from top to bottom the order in which you're Braque middleware will run as the request is coming in and then as the response is coming back out reverses reverse order at the response comes up so let's look at some examples but how order can
be a difficult thing and cause funds for you so taking the example of sending return immediately for static file requests we can see at the top of the rate middleware command that rails is going to immediately respond with static files we can also see down below that real the setting the request and logging for the individual requests know what this means is that if you're looking in your login for all the requests for static files you're not necessarily going to see them In fact with this configuration is certainly won't so it was you have alternate monitoring are not going to know that you're being the dots by someone asking for you know a little bit about now if you wanted to to make sure that all of those static files do it a lot you can just more of it the order of how you move in your rack middleware so that you are logging those requests so another example configuration morning so we're really excited in this example it's they were really excited to at more we added right at the top were super excited and we can see lowered the bottom actually setting of that session now this is the problem if
we read the word and documentation because when is actually downstream it depends on having session variables that and so for warning we need to make
sure that when we 1st started using 1 against warning rock middleware it's and
solve in its used at the bottom of the stack next application logic so early I talked about how middleware can help you simplify application by pulling in relevant parts of the but this nothing in the early stopping you from obscuring your entire
applications in middleware this could be a entire at for an incredibly complicated application where everything is just in the middle now that's actually something that's kind of interesting to think about it if you wanted to compose your application of small services number also applications you probably actually want a full application that handles most of your business logic know what 1 place where people can work when they want to know about things you don't want to be dealing with rack middleware and dealing dealing with business logic in magna nowhere as well as in your application so surrender flags server maybe you
should consider moving this logic out of rock middleware into your application 1st off the they're modifying the request now there are plenty of things that are going to add to the requests many things are going to help set up your application to handle the request but if your it modifying or overriding things like whose data things like the request that you're probably on the wrong path next awareness and business logic it's hard to search for balance across multiple places so you probably want to keep your business logic in the place that people expect to it's also not use necessarily to test business logic in because you are mostly working with ITER unit test for that nowhere or in integration testing acceptance testing so you're probably going to end up with more about this if you split your business these but your business logic between your out and you are and you know when another thing that's very similar is if it has awareness of models that has awareness of the data structure you probably on the same path of something that's not going to be as maintainable but I don't know your app maybe you're doing these things and maybe they work for you so what are some mitigation strategies if you're going to be having an application logic to your middleware so the 1st suggestion I have its use at middlewares so if you are going to have that AppleTalk make it very explicit that that's what you're doing it makes it easier for someone who's coming in is dividing something just search for some key words out and find that it also makes it clear to a new developer coming on the yes and in the middle where there's something I need to learn them not extra libraries that I can reduce like cognitive load by learning later when I it's particularly hackish Use Act capsule impacts to add that extra red flag 0 hey now we know we're not super comfortable with this but it's still something that we want to and finally use the word comments make it easy for someone who is searching for this by 3 years after you've left to find the code by using during in comments some where you think there might be certain always return a response so be aware that you are in a stack of middleware and that you need to comply with the 3 rules follows wrapped middleware exceptions are not part of that if you're middleware is returning is during an exception that it never captures that's probably not a good thing what that's going to result in is the 500 error that's not really you're not going to get the rails In all sorry something's wrong and were on a page because you're really code has ever and Rock is going to try to do its best but it's going to be ugly so final thing thread safety that's they did not know where it is only important if you are setting instance variables now not usually implies a far more
complicated piece of middleware then why I've written for with you guys today so so will make
paying thread-safe even though it doesn't need to be thread-safe because we're not updating at least update AP on the fly no because we're not updating and we don't need to make this that say but as an example let's do it so you take that call method and all we have to do it is do the instance of middleware we then move on the logic that we put into the call method until another pride within the convention is underscore call and then when so we
review today what rock American aware our some of the reasons why you would want to use a piece of rock middleware in your application a little bit about how to make sure you're doing smart things with Bregman and generally I of this talk is made you FIL more excited about using that middleware sometime down the line thank you and
thank you was if the the net the web and if you you have 1
Sichtenkonzept
Punkt
Mathematisierung
Zahlenbereich
Code
Computeranimation
Rechenschieber
Middleware
Middleware
Informationsmodellierung
Reelle Zahl
Mereologie
Gamecontroller
Wort <Informatik>
Softwareentwickler
Schreib-Lese-Kopf
Schnittstelle
Adressraum
Garbentheorie
Computeranimation
Überlagerung <Mathematik>
Schreib-Lese-Kopf
Mapping <Computergraphik>
Middleware
Subtraktion
Variable
Spezialrechner
Browser
Mereologie
Server
Programmierumgebung
Computeranimation
Instantiierung
Server
Familie <Mathematik>
Kartesische Koordinaten
Programmierumgebung
Quick-Sort
Code
Computeranimation
Bit
Variable
Automatische Indexierung
Server
Kartesische Koordinaten
Biprodukt
Programmierumgebung
Computeranimation
Gewicht <Mathematik>
Hash-Algorithmus
Interaktives Fernsehen
Kartesische Koordinaten
Mathematische Logik
Computeranimation
Endogene Variable
Rangstatistik
Code
Endogene Variable
Server
Information
Figurierte Zahl
Programmierumgebung
Hacker
Hash-Algorithmus
Klasse <Mathematik>
Schlussregel
Code
Computeranimation
Endogene Variable
Arithmetisches Mittel
Variable
Code
Hash-Algorithmus
Endogene Variable
Mustersprache
Mixed Reality
Information
Programmierumgebung
E-Mail
Instantiierung
Middleware
Benutzerbeteiligung
Diagramm
Minimum
Mereologie
Endogene Variable
Server
Kontrollstruktur
Kartesische Koordinaten
Hacker
Framework <Informatik>
Computeranimation
Hydrostatik
Addition
Parametersystem
Wasserdampftafel
Computersicherheit
Web-Applikation
Elektronische Publikation
Computeranimation
Middleware
Flash-Speicher
Middleware
Flash-Speicher
Strategisches Spiel
Gamecontroller
Cookie <Internet>
Authentifikation
Message-Passing
Leistung <Physik>
App <Programm>
Bit
Hochdruck
Klasse <Mathematik>
Kartesische Koordinaten
Schlussregel
Elektronische Publikation
Computeranimation
Middleware
Middleware
Informationsmodellierung
Menge
Endogene Variable
Inhalt <Mathematik>
Programmierumgebung
E-Mail
Objekt <Kategorie>
Middleware
Variable
Menge
Systemaufruf
Routing
Information
Programmierumgebung
Message-Passing
Gerade
Computeranimation
Namensraum
Bit
Klasse <Mathematik>
Zwei
Wurm <Informatik>
Zahlenbereich
Systemaufruf
Implementierung
E-Mail
Elektronische Publikation
Systemaufruf
Computeranimation
Endogene Variable
Arithmetisches Mittel
Middleware
Menge
Automatische Indexierung
Mustersprache
Endogene Variable
Response-Zeit
E-Mail
Resultante
Konfiguration <Informatik>
Klasse <Mathematik>
Systemaufruf
Kartesische Koordinaten
Bitrate
Mathematische Logik
Systemaufruf
Code
Computeranimation
Konfiguration <Informatik>
Middleware
Last
Endogene Variable
Inverser Limes
Speicherabzug
Message-Passing
Gerade
Middleware
Softwareentwickler
Web Site
Gruppenkeim
Schreiben <Datenverarbeitung>
Online-Katalog
Kartesische Koordinaten
Biprodukt
Grundraum
Computeranimation
Schnittstelle
Softwareentwickler
Web Site
Wellenpaket
Profil <Aerodynamik>
Unrundheit
Element <Mathematik>
Elektronische Publikation
Computeranimation
Roboter
Demoszene <Programmierung>
Bildschirmmaske
Endogene Variable
COM
Gerade
Punkt
Wasserdampftafel
Zahlenbereich
Interaktives Fernsehen
Kartesische Koordinaten
Code
Computeranimation
Middleware
Code
Endogene Variable
Datentyp
Response-Zeit
Konfigurationsraum
Gerade
Analogieschluss
Kraftfahrzeugmechatroniker
Elektronische Publikation
Mechanismus-Design-Theorie
Endogene Variable
Objekt <Kategorie>
Singularität <Mathematik>
Middleware
Geschlecht <Mathematik>
Gamecontroller
Ordnung <Mathematik>
Middleware
Schreib-Lese-Kopf
Endogene Variable
Kartesische Koordinaten
Bitrate
Ordnung <Mathematik>
Computeranimation
Inverser Limes
Funktion <Mathematik>
Bit
Physikalischer Effekt
Default
Elektronische Publikation
Bitrate
Login
Computeranimation
Hydrostatik
Middleware
Middleware
Skalarprodukt
Variable
Wort <Informatik>
Ordnung <Mathematik>
Konfigurationsraum
Middleware
Mathematische Logik
Mereologie
Minimum
Keller <Informatik>
Kartesische Koordinaten
Mathematische Logik
Ganze Funktion
Computeranimation
Mathematische Logik
Komponententest
Zahlenbereich
Kartesische Koordinaten
Mathematische Logik
Code
Computeranimation
Multiplikation
Informationsmodellierung
Variable
Fahne <Mathematik>
Endogene Variable
Programmbibliothek
Thread
Softwareentwickler
Datenstruktur
Softwaretest
App <Programm>
Ausnahmebehandlung
Schlussregel
Instantiierung
Kontextbezogenes System
Variable
Endogene Variable
Integral
Teilmenge
Summengleichung
Middleware
Dienst <Informatik>
Thread
Last
Mereologie
Strategisches Spiel
Wort <Informatik>
Modelltheorie
Fehlermeldung
Instantiierung
Middleware
Systemaufruf
Mathematische Logik
Computeranimation
Instantiierung
Videokonferenz
Middleware
Bit
Gewicht <Mathematik>
Kartesische Koordinaten
Gerade
Computeranimation
Chipkarte

Metadaten

Formale Metadaten

Titel Stuck in the Middle: Leverage the power of Rack Middleware
Serientitel RailsConf 2016
Teil 17
Anzahl der Teile 89
Autor Unger, Amy
Lizenz CC-Namensnennung - Weitergabe unter gleichen Bedingungen 3.0 Unported:
Sie dürfen das Werk bzw. den Inhalt zu jedem legalen und nicht-kommerziellen Zweck nutzen, verändern und in unveränderter oder veränderter Form vervielfältigen, verbreiten und öffentlich zugänglich machen, sofern Sie den Namen des Autors/Rechteinhabers in der von ihm festgelegten Weise nennen und das Werk bzw. diesen Inhalt auch in veränderter Form nur unter den Bedingungen dieser Lizenz weitergeben.
DOI 10.5446/31563
Herausgeber Confreaks, LLC
Erscheinungsjahr 2016
Sprache Englisch

Inhaltliche Metadaten

Fachgebiet Informatik
Abstract Before a request ever hits your Rails application, it winds its way through a series of pieces of Rack middleware. Middleware sets session cookies, writes your logs, and enables the functionality in many gems such as Warden. With Rails or any Rack app, you can easily insert your own custom middleware, allowing you to log, track, redirect, and alter the incoming request before it hits your application. You will leave this talk confident in writing your own custom middleware, better able to troubleshoot gems that rely on middleware and with an understanding of how your Rails app functions.

Ähnliche Filme

Loading...