The Functional Web
Upcoming SlideShare
Loading in...5
×
 

The Functional Web

on

  • 1,391 views

The HTTP protocol adheres to the functional programming paradigm. This talk looks at HTTP on .NET and illustrates how F# allows for a more direct correlation to the patterns of composition inherent in ...

The HTTP protocol adheres to the functional programming paradigm. This talk looks at HTTP on .NET and illustrates how F# allows for a more direct correlation to the patterns of composition inherent in the design of HTTP.

Statistics

Views

Total Views
1,391
Views on SlideShare
1,310
Embed Views
81

Actions

Likes
0
Downloads
7
Comments
0

3 Embeds 81

http://speakerrate.com 78
https://www.linkedin.com 2
http://www.linkedin.com 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • HTTP defines several components that allow distributed, loosely-coupled agents to communicate. The first lines of requests and responses are standardized to ensure that loosely-coupled components can understand one another, yet they allow for extension either by standards bodies or for internal, proprietary use.
  • This may be new to some, but this resource is not the same as the collection of items at /items.
  • The aggregate of many resources is generally what we refer to as an HTTP, or Web, Application. A single resource is enough, as is a single method.
  • Resources may be directly returned in a response. In the beginning, when most HTTP applications served static files, this was common. However, Resources are not equivalent to the representation returned to the client, even if they appear identical. Unlike editing files locally, if you were to edit a file returned from an HTTP application, you would not be editing the original file. You would need to re-submit the file to the server, if allowed, and then the server would need to take the content you supplied and update the original Resource.It is thus reasonable to understand that a Resource can be represented in more than one way. A JSON representation is just as valid as XML, HTML, or even an image.Content negotiation, or “conneg,” is a cross-cutting concern that allows HTTP applications to select an appropriate representation to send in the response message. The actual execution of this selection could occur either at the top-level or at the lowest-level of a composed HTTP application.
  • It’s also important to note that the request and response headers are just NameValueCollections, so you don’t have easy, typed access to common header values. This isn’t critical for composition but odd for a statically-typed language platform.DEMO: In spite of its short-comings, you can still do some interesting things with HttpListener. Tomas Petricek created a really interesting project where he uses HttpListener as the base for a chat server.
  • It’s also important to note that the request and response headers are just NameValueCollections, so you don’t have easy, typed access to common header values. This isn’t critical for composition but odd for a statically-typed language platform.DEMO: In spite of its short-comings, you can still do some interesting things with HttpListener. Tomas Petricek created a really interesting project where he uses HttpListener as the base for a chat server.
  • It’s important to note here that these interfaces are exposed by IIS and can be used to modify that server directly, though they are also tied directly to that server. Mono offers additional options for hosting, but you should understand that you are generally tied to IIS.
  • It’s important to note here that these interfaces are exposed by IIS and can be used to modify that server directly, though they are also tied directly to that server. Mono offers additional options for hosting, but you should understand that you are generally tied to IIS.
  • ASP.NET Web Forms 4.0 provided a hook intoSystem.Web.Routing.Also of note:Web Forms has historically been demonized by it’s poor HTML output, requiring a element to scope control usage.Many server controls have weird behavior. Anchor tags, which generally perform GET requests instead POST back to server, even just to navigate to another page. Some of this is of course avoidable, but the designer-centric focus often leads to ill-advised HTTP use.FSharpCodeDomProvider has limitations.
  • Also difficult to use F# for View Models. You will have a difficult time using records and discriminated unions as types, and you’ll be forced into mutability.
  • Current frameworks typically choose to lean on one or the other of the above sets of options. However, there really should be no reason to require only one or the other. In fact, you should be free to define various boundaries where you might use a serializer approach over a subset of resources.
  • Routing is nothing more than filtering down a set of handlers to select the appropriate one and return a response.A Response is nothing more than a map function over a request, though it is true that some HTTP methods are destructive (e.g. POST).Pulling handlers into resources or applications is nothing more than a reduce function. Frank uses merge; WebSharper uses Sum.
  • For those with a stronger bent towards building web sites, Mauricio Scheffer’s Figment may be a closer match to your taste.
  • Compare the Frank application signature with the simplest app signature we used above. The only addition is that we are stating that an application is non-blocking. This is the same idea as is used in node.js. It’s also sort-of required since Frank sits on System.Net.Http via MessageHandlers. The signature for the MessageHandler.SendAsync is the same but for Task rather than Async. This signature extends all the way through all layers of composition.
  • A resource is the only current location that does not conform solely to the Frank application signature. A resource holds both a Uri Template (its name) as well as a HttpRequestMessage -> Async option. Why the option? The resource will respond with a 405 Method Not Allowed if it does not respond to the method thrown its way. Thus the option allows the programmer to define the methods for the resource without having to manually hook up the 405 response.
  • Similar to resource, merge is a function of HttpRequestMessage -> Async option. When a resource uri is not found, a 404 Not Found response is returned. The result, however, is a Frank application.
  • Frank currently uses Mauricio Scheffer’sFsConneg library, now in FSharpx.Http. System.Net.Http has a similar mechanism, but it’s currently still a little heavy as they work out the kinks in preparation for the RC. FsConneg provides a mechanism for submitting the Accept headers and a list of supported formats and returns the best match. negotiateMediaType wraps that with the selection of the appropriate formatter, of type System.Net.Http.Formatting.MediaTypeFormatter, and returns the formatted content.
  • Another option is Pit FW, which was featured on the Community for F# on 2/21/2012 (today). It also compiles F# to JavaScript. You can learn more at http://pitfw.org/.
  • Using F# for web projects isn’t just about code size. Yes, you’ll save some lines of code, but more importantly, you’ll work closer to the guts of HTTP. You can leverage the power of composition to build applications that will be more maintainable and much clearer to understand.

The Functional Web The Functional Web Presentation Transcript

  • The Functional Web
  • Ryan RileyO Logos Bible SoftwareO Community for F#O F# MVPO OSS: FSharpx, Fracture, FrankO @panesofglass
  • OutlineO The State of HTTP on .NETO Composition Patterns in HTTPO Identifying ProblemsO Examining a Solution
  • The State of HTTP on .NET
  • Current OptionsO http.sys O HttpListener O IIS (IHttpModule & IHttpHandler) O Web Forms O MVC O WCF HTTP & Data Services
  • Future OptionsO System.Net.Http (BETA) O .NET 4.5 O Available on NuGetO ASP.NET Web API (BETA) O Builds on System.Net.Http O Integrated with MVC 4
  • OSS Options Frameworks ServersO FubuMVC O Firefly (OWIN)O MonoRail O Fracture (F#)O NancyFx O Kayak (OWIN)O OpenRasta O Manos de MonoO OWIN/GateO ServiceStack.NET O Mono XSPO WebSharperO … and many more!
  • Composition Patterns in HTTP
  • Component PartsO Request/Response Lines O Methods, URIs, Status CodesO Headers O General, Request, Response, ContentO ResourcesO RepresentationsO Hypermedia
  • Simplest HTTP Application HttpRequestMessage -> HttpResponseMessage
  • ResourcesGET /item/1+ POST /item/1+ PUT /item/1+ OPTIONS /item/1=Resource at / with GET, POST, PUT, &OPTIONS
  • HTTP Applications/+ /items+ /item/{itemId}+ /help=Typical HTTP “application”
  • Content NegotiationClient Accepts Server Supportsapplication/xml;q=0.9 application/jsonapplication/json;q=0.8 text/plaintext/plain;q=0.5 text/html application/json
  • Identifying Problems
  • HttpListenerO Low-levelO Defines the signature for a single application onlyO HttpListenerContext provides a singleton; no chance to intercept and chain behaviorO Routing requests requires custom handling; typically by using imperative if-then-elseO No means of chaining or composing multiple listeners
  • HttpListenerHttpListener.Start ("http://localhost:8082/", (fun (request, response) -> async { match request.Url.LocalPath with| "/post" ->// Send message to the chat room room.SendMessage(request.InputString) response.Reply("OK") | "/chat" -> // Get messages from the chat room (asynchronously!) let! text = room.AsyncGetContent() response.Reply(text) | s -> // Handle an ordinary file request let file = root + (if s = "/" then "chat.html" else s.ToLower()) if File.Exists(file) then let typ = contentTypes.[Path.GetExtension(file)] response.Reply(typ, File.ReadAllBytes(file)) else response.Reply(sprintf "File not found: %s" file) }),cts.Token)
  • IHttpModule & IHttpHandlerO Low-levelO HttpContext has the same problems as HttpListenerContextO IHttpHandler could represent a Resource, but method mapping is imperativeO IHttpModule provides a middleware layer for routing or hosting multiple IHttpHandlersO System.Web.Routing surfaces the routing component
  • IHttpModule & IHttpHandlerinterface IHttpModule{ void Dispose(); void Init(HttpApplication context);}interface IHttpHandler{ bool IsReusable { get; } void ProcessRequest(HttpContext context);}
  • ASP.NET Web FormsO HTML composition via MasterPages, Pages, and ControlsO Suffers many problems associated with IHttpModule and IHttpHandlerO Evented model allows for interceptionO No built-in support for other representationsO Pages loosely correlate to ResourcesO Application composition and routing by file path
  • ASP.NET MVCO Suffers many problems associated with IHttpModule and IHttpHandlerO Primarily HTML generation but allows for better HTTP controlO Built-in support for handling Ajax requestsO ActionFilters allow for behavior composition at different points: Authorize, ActionExecuting, ActionExecuted, Resul tExecuting, ResultExecuted
  • ASP.NET MVC, cont.O Content Negotiation is still very manualO ViewEngines and Serializers can be made to render various representationsO ViewEngines offer representation compositionO Controllers ~ Resources, but not quiteO Areas and Routing allow for Nested Resources, to a degree
  • Problem SummaryO Have: O Limited interception for cross-cutting concerns O Representation compositionO Do not have: O No easy resource composition O No built-in content negotiation
  • Composition for ConnegO Rendering O Imperative if-then-else O SerializersO Location O Within the specific method handler (common for imperative) O Top-level (common for serializers)O Why not both?
  • Nested ResourcesO Imperative if-then-elseO RoutingO MVC Areas offer another levelO What about more than one level? O Rails – problem with deep URIs O System.Web.Routing does everything at the top-level, so tracking deeper resource trees is difficult.
  • Examining a Solution
  • Function CompositionO Functional programming offers solutions to these problems O Filter O Map O Reduce
  • FrankO F# DSL using System.Net.HttpO Headers compositionO Follows the natural composition of HTTPO Frank Resources == HTTP ResourcesO Define your own conventions!
  • Simplest HTTP Frank Application HttpRequestMessage -> HttpResponseMessageHttpRequestMessage -> Async<HttpResponseMessage>
  • Define a Method Handler// handlerlet echo request = async { let! body = request.Content.AsyncReadAsString() return HttpResponseMessage.ReplyTo(request, body)}// method handlerget echo
  • Define a Resourcelet helloworld request = async { … }let echo request = async { … }let resource = route “/” (get helloworld <|> post echo)
  • Define an Applicationlet todoListResource = route “/” (get todoList <|> …)let todoItemResource = route “/item/{1}” (put …)let app = merge [ todoListResource; todoItemResource ]
  • Leverage Connegval negotiateMediaType = formatters -> HttpRequestMessage -> string -> Async<HttpResponseMessage>let echo = negotiateMediaType formatters <| fun request -> request.Content.AsyncReadAsString())
  • WebSharperO One language for both client and serverO Can leverage to cleanly separate partsO Use WebSharper to generate code-on- demand to send to the clientO Plays well with existing tools
  • Summary
  • ResourcesO ASP.NET Web Forms in F#O ASP.NET MVC in F#O Figment DSL for MVCO Frank DSL for Web APIO WebSharperO Pit FW
  • Thank you!O Please rate this talk: http://speakerrate.com/talks/9293-the- functional-web