Multitier programming

Multitier programming is a programming paradigm for distributed software. In multitier programming, the functionalities that belong to multiple tiers (e.g., the client, the server and the database in a Web application) are part of the same compilation unit and are developed in the same programming language. In contrast, traditionally, tiers are developed using different languages, e.g., JavaScript for the Web client, PHP for the Web server and SQL for the database. The first multitier programming languages include Links. and Hop
As an example, we show an Echo client–server application: The client sends a message to the server and the server returns the same message to the client, where it is appended to a list of received messages. The application is simple and self-contained, and – despite all the limitations of short and synthetic examples – it gives us the chance to demonstrate different MT languages side by side. 
=== Example 1. Echo application in Hop.js. ===
service echo() {
 var input = <input type="text" /> 
 return <html>
 <body onload=~{
 var ws = new WebSocket("ws://localhost:" + ${hop.port} + "/hop/ws")
 ws.onmessage = function(event) { document.getElemenetById("list").appendChild(${event.data}) }
 }> 
 
 ${input}
 <button onclick=~{ ws.send(${input}.value) }>Echo!</button> 
 
 
 </body>
 </html> 
}
var wss = new WebSocketServer("ws") 
wss.onconnection = function(event){
 var ws = event.value
 ws.onmessage = function(event) { ws.send(event.value) } 
}
HTML can be embedded directly in Hop code. HTML generated on the server (Line 2–14) is passed to the client. HTML generated on the client can be added to the page using the standard DOM API (Line 6).
Hop supports bidirectional communication between a running server and a running client instance through its standard library. In the Echo application, the client connects to the WebSocket server through the standard HTML5 API (Line 5) and sends the current input value (Line 10). The server opens a WebSocket server (Line 17) that returns the value back to the client (Line 20).
The language allows the definition of services, which are executed on the server and produce a value that is returned to the client that invoked the service. For example, the echo service (Line 1) produces the HTML page served to the web client of the Echo application. Thus, the code in a service block is executed on the server.
Because of the ~{. . .} notation, the code for the onload (Line 4) and onclick (Line 10) handlers is not immediately executed but the server generates the code for later execution on the client. On the other hand, the ${. . .} notation escapes one level of program generation. The expressions hop.port (Line 5), event.data (Line 6) and input (Line 9 and 10) are evaluated by the outer server program and the values to which they evaluate are injected into the generated client program. Hop supports full stage programming, i.e., ~{. . .} expressions can be arbitrarily nested such that not only server-side programs can generate client-side programs but also client-side programs are able to generate other client-side programs.
=== Example 2. Echo application in Links. ===
fun echo(item) server { 
 item
}
fun main() server { 
 page
 <html> 
 <body>
 <form l:onsubmit="{appendChildren({stringToXml(echo(item))}, getNodeById("list"))}"> 
 <input l:name="item" />
 <button type="submit">Echo!</button>
 </form>
 
 </body>
 </html> 
}
main()
Links uses annotations on functions to specify whether they run on the client or on the server (Line 1 and 5). Upon request from the client, the server executes the main function (Line 18), which constructs the code that is sent to the client. Links allows embedding XML code (Line 7–15). XML attributes with the l: prefix are treated specially. The l:name attribute (Line 10) declares an identifier to which the value of the input field is bound. The identi�er can be used elsewhere (Line 9). The code to be executed for the l:onsubmit handler (Line 9) is not immediately executed but compiled to JavaScript for client-side execution. Curly braces indicate Links code embedded into XML. The l:onsubmit handler sends the current input value item to the server by calling echo. The item is returned by the server and appended to the list of received items using standard DOM APIs. The call to the server (Line 9) does not block the client. Instead, the continuation on the client is invoked when the result of the call is available. Client–server interaction is based on resumption passing style: Using continuation passing style transformation and defunctionalization, remote calls are implemented by passing the name of a function for the continuation and the data needed to continue the computation.
=== Example 3. Echo application in Ur/Web. ===
fun echo (item : string) = return item
fun main () =
 let fun mkhtml list =
 case list of
 [] => <xml/>
 | r :: list => <xml>{[r]}{mkhtml list}</xml> 
 in
 item <- source ""; 
 list <- source []; 
 return <xml><body>
 
 <ctextbox source={item} /> 
 <buttonvalue="Echo!"onclick={fn =>
 list' <- get list;
 item' <- get item;
 item' <- rpc (echo item'); 
 set list (item' :: list')
 }/> 
 
 
 <dyn signal={
 list' <- signal list;
 return (mkhtml list') 
 }/>
 
 </body></xml>
 end
Ur/Web allows embedding XML code using <xml>. . .</xml> (Line 6 and 7). The {. . .} notation embeds Ur/Web code into XML. {[. . .]} evaluates an expression and embeds its value as a literal. Ur/Web supports functional reactive programming for client-side user interfaces. The example defines an item source (Line 9), whose value is automatically updated to the value of the input field (Line 13) when it is changed through user input, i.e., it is reactive. The list source (Line 10) holds the list of received items from the echo server. Sources, time-changing input values, and signals, time-changing derived values, are Ur/Web’s reactive abstractions, i.e., signals recompute their values automatically when the signals or sources from which they are derived change their value, facilitating automatic change propagation. Upon clicking the button, the current value of list (Line 15) and item is accessed (Line 16), then a remote procedure call to the server’s echo function is invoked (Line 17) and list is updated with the item returned from the server (Line 18). To automatically reflect changes in the user interface, a signal is bound to the signal attribute of the HTML pseudo element <dyn> (Line 22). The signal uses the mkhtml function (Line 24, defined in Line 4), which creates HTML list elements. In addition to remote procedure calls – which initiate the communication from client to server – Ur/Web supports typed message-passing channels, which the server can use to push messages to the client.
=== Example 4. Echo application in Eliom. ===
module Echo app = Eliom registration.App (struct let application name = "echo" let global data path = None end)
let%server main_service = create ~path:(Path []) ~meth:(Get Eliom_parameter.unit) ()
let%server make input up =
 let inp = Html.D.Raw.input () in
 let btn = Html.D.button ~a:[Html.D.a_class] ["button"] [Html.D.pcdata "Echo!"] in
 ignore [%client
 (Lwt.async (fun () -> 
 Lwt js events.clicks (Html.To dom.of element ~%btn) (fun -> ___
 ~%up (Js.to string (Html.To dom.of input ~%inp)##.value);
 Lwt.return_unit)) : unit) ]; 
 Html.D.div [inp; btn]
let%server()=Echoapp.register _
 ~service:main service 
 (fun () () ->
 let item_up = Up.create (Eliom_parameter.ocaml "item" [%derive.json :string]) in
 let item down = Down.of react (Up.to react item up) in
 let list, handle = ReactiveData.RList.create [] in
 let list = ReactiveData.RList.map [%shared fun i -> Html.D.li [Html.D.pcdata i] ] list in 
 let input = make_input item_up in
 ignore [%client
 (Eliom_client.onload __
 (fun ->ignore(React.E.map(funi->ReactiveData.RList.consi~%handle)~%itemdown)):unit)]; 
 Lwt.return (Eliom_tools.D.html ~title:"echo" (Html.D.body [input; Html.R.ul list])))
Eliom extends let-bindings with section annota- tions %client, %server and %shared – the latter indicates code that runs on both the client and the server. The application starts with a call to Echo_app.register (Line 15). Eliom supports cross- tier reactive values: The application generates a server-side event (Line 18) and a corresponding client-side event (Line 19), which automatically propagates changes from the server to the client. A reactive list (Line 20) holds the items received from the server. Mapping the list produces a list of corresponding HTML elements (Line 21), which can directly be inserted into the generated HTML code (Line 26). Eliom supports a DSL for HTML, providing functions of the same name as the HTML element they generate. Server-side code can contain nested fragments to be run on the client ([%client . . .], Line 23) or to be run on both the client and the server ([%shared . . .], Line 21). Eliom uses injections (prefixed by ~%) to access values on the client side that were computed on the server. The client-side representation of the event item_down is injected into a client fragment to extend the reactive list with every item returned from the server (Line 25). The make_input function (Line 5) generates the main user interface, which processes the stream of button clicks (Line 10) and fires the up event for every item (Line 11). To �re the server-side up event from the client-side, we inject the event via ~%up into the client fragment.
=== Example 5. Echo application in GWT. ===
package echo.client; 
public interface EchoServiceextendsRemoteService{
 String echo(String item) throws IllegalArgumentException; }
 
package echo.client; 
public interface EchoServiceAsync {
 void echo(String item, AsyncCallback<String> callback) throws IllegalArgumentException; }
package echo.server; 
public class EchoServiceImpl extends RemoteServiceServlet implements EchoService {
 public String echo(String item) throws IllegalArgumentException { 
 return item; } }
 
package echo.client; 
public class Echo implements EntryPoint {
 private final EchoServiceAsync echoService = GWT.create(EchoService.class);
 
 public void onModuleLoad() {
 final TextBox itemField = new TextBox();
 final Button submitButton = new Button("Echo!");
 RootPanel.get("itemFieldContainer").add(itemField); 
 RootPanel.get("submitButtonContainer").add(submitButton);
 
 submitButton.addClickHandler(new ClickHandler { 
 public void onClick(ClickEvent event) {
 echoService.echo(itemField.getText(), new AsyncCallback<String>() { 
 public void onFailure(Throwable caught) { }
 public void onSuccess(String result) {
 RootPanel.get("itemContainer").add(new Label(result)); } }); } }); } }
For the sake of brevity, we leave out the external HTML file. The application adds an input field (Line 22) and a button (Line 23) to container elements defined in the HTML file and registers a handler for click events on the button (Line 25). When the button is clicked, the echo method of the echoService is invoked with the current item and a callback – to be executed when the remote call returns. When an item is returned by the remote call, it is added to the list of received items (Line 30). GWT requires developers to specify both the interface implemented by the service (Line 2) and the service interface for invoking methods remotely using a callback (Line 6). The implementation of the echo service (Line 10) simply returns the item sent from the client.
=== Example 6. Echo application in ScalaLoci. ===
@multitier object Application {
 @peer type Server <: { type Tie <: Single[Client] } 
 @peer type Client <: { type Tie <: Single[Server] }
 
 val message = on[Client] { Event[String]() } 
 val echoMessage = on[Server] { message.asLocal }
 def main() = on[Client] {
 val items = echoMessage.asLocal.list
 val list = Signal { ol(items() map { message => li(message) }) } 
 val inp = input.render
 dom.document.body = body(
 div( 
 inp,
 button(onclick := { () => message.fire(inp.value) })("Echo!")), 
 list.asFrag).render
 } 
}
The application first defines an input field (Line 11) using the ScalaTags library. The value of this field is used in the click event handler of a button (Line 15) to fire the message event with the current value of the input field. The value is then propagated to the server (Line 6) and back to the client (Line 9). On the client, the value of the event are accumulated using the list function and mapped to an HTML list (Line 10). This list is then used in the HTML (Line 16) to display the previous inputs.
* Links
* Hop/Hop.js
*Ur/Web
*Eliom/Ocsigen
*ScalaLoci
*StiP.js
*Scala Multi-Tier FRP
*OpaRajchenbach-Teller, D., & Sinot, Franois-R&#39;egis. (2010). Opa: Language support for a sane, safe and secure web. Proceedings of the OWASP AppSec Research, 2010(1).
*AmbientTalk/R
*ML5
*WebSharper
*Haste
*Fun
*Koka
*Multi-Tier Calculus
*Swift
*Volta
*GWT
*Meteor
*J-Orchestra
*Hiphop
*Distributed Orc
*Jif/split
*Fission
*SIF
*WebDSL
*Acute
*Mobl
*High-Level Abstractions for Web Programming
Category:Programming paradigms
Category:Distributed computing
Category:Application software
Category:Programming languages
Category:Web programming