Showing posts with label scheme. Show all posts
Showing posts with label scheme. Show all posts

Friday, 22 May 2009

Serving Gambit Web Applications behind Apache

Now that writing web applications in Gambit Scheme is so easy using Black Hole, I thought I'd write an article on how to set everything up from scratch using Apache as a front end web server.



Using Apache as a front end web server isn't strictly necessary since the Black Hole web server fully supports HTTP and is capable of serving static as well as dynamic content but for robustness, SSL support and to offload the serving of static content it makes sense to place Gambit behind Apache.

Gambit uses lightweight internal threads which allows it to efficiently support thousands of concurrent requests but these run in a single OS thread. This means that if you are running on a multicore or multiprocessor system, you will need to run multiple Gambit processes and load balance between them in order to fully utilise the available CPU. The load balancer would need to be 'sticky' unless you are going to serialize continuations outside of Gambit.

Enter Black Hole
Black Hole is primarily a R5RS compatible module system for Gambit which allows you to easily import libraries into your code including macros which has previously been tricky on Gambit. Conversely you can also export your own code and create your own libraries to fully modularise your development. This is basic stuff but the lack of it has really stifled development on Gambit. For the web developer, the most interesting aspects are the bundled libraries for web serving, SXML and the 'Spork' continuations based web framework.

Getting Started
This guide is based very much on Per Eckerdal's Black Hole Tutorial guide but has been extended based on my own experiences using Black Hole.

Installing Black Hole
Assuming that you have Gambit installed, you need to download the latest Black Hole code from the git repository :-

git clone http://mwaza.dyndns.org/apps/files/modules.git

That will clone the current code repository to 'modules' directory in your working directory, you now need to copy or symlink this directory to the Gambit lib directory e.g. C:\Gambit-C\v4.4.3\lib\ on Windows to create ~~/lib/modules.

Although not strictly necessary, now would be a good time to build all the modules :-

cd \Gambit-C\v4.4.3\lib\modules
gsc build

Black Hole is now installed and ready to use, simply do a (load "~~/lib/modules/build") in Gambit to initialise. It is recommended that you use gsc rather than gsi because Black Hole uses compilation features that aren't available in gsi.


For convenience, you can create a wrapper command that loads Black Hole at startup, e.g. on Windows :-


bsc.cmd :


gsc -:dar- -e "(load \"~~/lib/modules/build\")" %1 -

Copy this to your Gambit bin directory then you can use 'bsc' in future instead of gsc or gsi.


Setting Up Apache
In this scenario we are using Apache to proxy the requests through to Gambit and to serve any static content, here's a sample Virtual Host setup from httpd.conf :

<VirtualHost *>
ServerName localhost
ProxyPass /spork http://localhost:8080
ProxyPassReverse /spork http://localhost:8080
DocumentRoot ${path}/www
</VirtualHost>


This configuration will forward any requests with a URI that starts with '/spork' to the Gambit server running on port 8080. Any other requests will be served from the 'www' directory under Apache.

Creating your Spork Application
So you are now ready to go, fire up Eclipse (with SchemeScript) or your alternative favorite development tool. Start your Gambit REPL window (with bsc or load the modules manually).

Enter this into REPL :-


(import (std spork/core))

(define c (spork-serve root: "/spork" ))

(add-spork c ("one")
`(html
(head
(title "Hello, world!"))
(body
"This is my first web application using Spork :)")))



And fire up your browser :-



OK it's not a spectacular example but you are setup now ready to do some more serious development effortlessly through REPL - just redefine the function and retest with no need for a restart.

Wednesday, 29 April 2009

Gambit MySQL client 0.2


After a few weeks wrestling with the MySQL protocol, I've finally managed to produce a reasonable attempt at a client for Gambit (and probably other Scheme's).

This is a pure Scheme implementation rather than using Gambit's C interface to glue the existing MySQL C API into Gambit. The reason for this is that Gambit's power, and in my view fantastic potential as a web platform, comes from it's lightweight threads which allows Gambit to process thousands of concurrent requests in a single OS thread. This is all acheived by an internal schedular, continuations and very careful use of non-blocking calls on all I/O functions. Using the C API effectively takes the OS thread out of Gambit and into the C code and therefore all of those lovely threads stop executing until your call is completed - seriously bad news for a web application.

This library is now around 80% complete and supports the following features :-
  • Multiple concurrent connections to MySQL,
  • Authentication using both the old and new authentication methods,
  • Switching Schema's,
  • Dynamic queries, updates, deletes etc.
  • Prepared statement creation,
  • Executing prepared statements (queries and updates) with bind variables for most datatypes,
  • Closing prepared statements,
  • Closing connections.
Additionally, I've also introduced a SQL Abstraction Layer. This is equivalent to JDBC in Java which defines a few generic SQL types and provides a common API across database vendors. The idea behind this is that if someone else provides another database client, they can use the same abstraction layer and then any programs can switch between databases without having to rewrite their code (hopefully).

There are a few limitations with the driver, i.e. features that aren't implemented yet :-
  • Not all datatypes are supported yet in prepared statements e.g. floats, doubles, sets, enums and one or two others. Some of these can easily be avoided e.g. by using DECIMAL instead of FLOAT or DOUBLE.
  • BLOB's and large character fields are not yet supported in either dynamic or prepared statements.
  • Large result sets requiring supplementary fetches aren't supported as I haven't implemented the additional fetch function.
Hopefully I'll add these things over the coming weeks and months. There are likely to be a few bugs in there, so if you find one or you are desperate for a feature that hasn't been implemented yet then please email me.

The library is in the Gambit Dumping Grounds. Here's an example of how you use it :-

(load "sql")
(load "mysql")

(with-connection (sql-connect "localhost" 3306 "test" "fred" "fred")

;;(mysql-execute "drop table test")
(mysql-execute "create table test (id integer PRIMARY KEY AUTO_INCREMENT, name varchar(50), inserted datetime, amount decimal(10,2) DEFAULT -4.5)")
(pp (sql-execute "select * from test"))


;; Prepared Statements
(let ((stmt1 (sql-prepare-statement "insert into test (name, amount, inserted) values (?, ?, sysdate())"))
(stmt2 (sql-prepare-statement "select id, name, amount, inserted from test where amount > ? order by id")))

(pp (sql-execute-prepared-statement stmt1 '("Fred" 10.5)))
(pp (sql-execute-prepared-statement stmt1 '("Joe" 5.5)))
(sql-close-statement stmt1)


(pp (sql-execute-prepared-statement stmt2 '(4.5)))
(sql-close-statement stmt2))

;; Close connection
(sql-close-connection)))

Result sets are returned as a list of lists i.e. a list of column values for each row in a list for the result set. The first row in the list is the column headings. For dynamic statements, the column data is always a string regardless of the SQL type because this is the way that MySQL sends it and I haven't implemented any type conversions yet. Prepared statements return binary types so I've mapped some of these e.g. strings and numbers into their respective Scheme types.

I would strongly recommend using prepared statements rather than dynamic statements for performance reasons and also for their natural resistance to SQL injection attacks in web applications.

Once the library is finished, I'll create a persistence layer that builds on top of the prepared statements to give a framework similar to ActiveRecord in Rails or Hibernate in Java.

Thursday, 11 December 2008

Functional Web Development with SISCWeb

Functional paradigms offer some innovative solutions to long standing Web development problems :-

1. Continuations fix the inversion of control problem caused by the stateless nature of HTTP. With continuations you can start a function and define some variables you can then 'call out' to the user i.e. send them a page. When the user responds, your function continues where it left off with all the variables still in scope. This means no need for hidden variables, sessions packed with transient data etc. Imagine now that your entire business process is now captured in one easy to read function, not spread over numerous java classes with varied XML structures.

2. Concurrency problems with poorly defined static variables leaking confidential data to the wrong customers are a thing of the past. Everything is passed on the stack as function arguments - there is no mutating state shared between requests. This also makes the application highly scaleable.

3. Security - the continuations approach means that the only way to link one page to another is via a continuation which is unique to each user. This means that data-driven attacks i.e. manipulating keys in forms to get access to data won't work - you can only access data within your continuation.

Try it with SISCWeb - a Scheme continuations based framework that runs on top of J2EE. This allows you to reuse all of your Java libraries and business components but benefit from a functional presentation layer. Also being Scheme based, it offers an embedded 'REPL' so you can build and change your application on the fly without restarting Tomcat or losing existing application state.

It's even better than Ruby on Rails but don't tell anyone - they'll all be using it.

Thursday, 6 November 2008

Luhn's algorithm in Scheme

I came across Luhn's algorithm yesterday whilst trying to resolve a work related issue and was surprised to find an implementation in Scheme for it on Andrew Dashin's blog.

Looking at Andrew's implementation, it struck me as being a not very scheme-like implementation because it used an iterator (do) and mutating variables (set!). This gave me an opportunity to test my new found Scheme skills :-

(define (luhn-check account-number)
(letrec (
(digit (lambda (str pos) (string->number (string (string-ref str pos)))))
(add-digits (lambda (str)
(+ (digit str 0) (if (> (string-length str) 1)(digit str 1) 0))
))
(luhn-pair (lambda (x)
(+ (digit account-number x)
(if (> x 0) (add-digits (number->string (* (digit account-number (- x 1)) 2))) 0)
(if (> x 1) (luhn-pair (- x 2)) 0))
)))
(luhn-pair (- (string-length account-number) 1))
)
)




It takes a string and returns a number which should be a multiple of 10 for a valid mod 10 check or a multiple of 11 for a valid mod 11 check.