newlisp-redis / redis.lsp

;; @module redis
;; @description newLISP bindings for the Redis database ( http://code.google.com/p/redis )
;; @version 0.1
;; @author Nikhil Marathe <nsm.nikhil@gmail.com> 2010
;; @link http://bitbucket.org/nikhilm/newlisp-redis http://bitbucket.org/nikhilm/newlisp-redis
;;
;; This module provides bindings to Redis. It communicates
;; with the Redis server and returns values in appropriate
;; lisp-y types.
;;
;; Commands are automatically generated, so the documentation
;; can be found in the Redis Command Reference.
;;
;; For a reference look at @link ../test-redis.lsp test-redis.lsp
;;
;; To view a list of commands do:
;; <pre> (println redis:inline-commands)</pre>
;; and so on for other types
;;
;; @example
;; (setf 'redis (redis:connect))
;; (redis:ping redis)
;; => "PONG"

(context 'redis)

(constant 'CRLF "\r\n")
(constant 'BUFSIZE 4096)

// transformed from redis-node-client + ping and quit
(constant 'inline-commands 
  '("auth" "bgsave" "dbsize" "decr" "decrby" "del"
    "exists" "expire" "flushall" "flushdb" "get" "incr" "incrby" "info"
    "keys" "lastsave" "lindex" "llen" "lpop" "lrange" "ltrim" "mget"
    "move" "ping" "quit" "randomkey" "rename" "renamenx" "rpop" "save" "scard" "sdiff"
    "sdiffstore" "select" "shutdown" "sinter" "sinterstore" "smembers"
    "spop" "srandmember" "sunion" "sunionstore" "ttl" "type"
    "zrange" "zrevrange" "zcard" "zrangebyscore"))

(constant 'bulk-commands
  '("getset" "lpush" "lrem" "lset" "rpush" "sadd"
    "set" "setnx" "sismember" "smove" "srem" "zadd"
    "zrem" "zscore" "rpoplpush"))

(define (make-inline-command command)
  (letex ((fname (sym command)) (cmd command))
    (define (fname r)
      (letn ( (args-as-strings (map (fn (x) (string x)) (args)))
              (command-string (join (cons (upper-case cmd) args-as-strings) " ")) )
          (postprocess cmd (:query r (append command-string redis:CRLF)))))))

(define (make-bulk-command command)
  (letex ((fname (sym command)) (cmd command))
    (define (fname r)
      (letn ((args-as-strings (map (fn (x) (string x)) (args)))
            (all-but-last (0 -1 args-as-strings))
            (last-arg (last args-as-strings))
            (len-last-arg (string (length last-arg)))
            (first-line (flat (list (upper-case cmd) all-but-last len-last-arg)))
            (command-string (join first-line " ")))
        (postprocess cmd (:query r (join (list command-string last-arg "") redis:CRLF)))))))

; any replies are always returned as strings
; certain commands might need to convert them
(define (postprocess cmd reply)
  (cond
    ((= cmd "keys") (parse reply " "))
    ((= cmd "info") (map (curry flipped-parse ":") (parse reply "\r\n")))
    ((= cmd "exists") (!= 0 reply))
    (true reply)))

(define (flipped-parse delim str)
  (parse str delim))

(context MAIN)

;; @syntax (redis [host] [port])
;; Creates a new connection to a Redis instance
;; @return a new connection object or nil on error
(define (redis:redis (host "localhost") (port 6379))
  (let (sock (net-connect host port))
    (if (nil? sock)
      nil
      (list redis sock ""))))

;; @syntax (:close redis)
;; Closes a redis connection, including the socket
(define (redis:close r)
  (:quit r)
  (net-close (r 1) true))

; Simply sends a string to the server
; And attempts to handle the reply
(define (redis:query r command-str)
  (net-send (r 1) (append command-str redis:CRLF))
  (redis:read r))

; Separated from :query, so that bulk reply
; handlers can call it multiple times in case
; one read isn't enough.
(define (redis:read r)
  (net-receive (r 1) buf redis:BUFSIZE)
  (write-buffer (r 2) buf)
  (:handle-reply r))

(define (redis:handle-reply r , reply)
  (while (> (length (r 2)) 0)
    (setf reply
        (case (first (r 2))
          ("+" (:handle-single-reply r))
          ("-" (:handle-error r))
          ("$" (:handle-bulk-reply r))
          ("*" (:handle-multi-bulk-reply r))
          (":" (:handle-integer-reply r))
          (true (:handle-unknown-reply r))))
    (setf (r 2) ((reply 1) (r 2)))
    (reply 0)))

(define (redis:handle-unknown-reply r)
  (throw-error "Unknown reply type " (first (r 2))))

(define (redis:handle-single-reply r)
  (letn ((trimm (chop (r 2) 2))
         (message (1 trimm)))
    (list message (length (r 2)))))

(define (redis:handle-bulk-reply r)
  (letn ( (indx (find redis:CRLF (r 2)))
          (reply-len (int (1 indx (r 2))))
          ; the below line means
          ; clip message from end of $<n>\r\n to howmuchever <n> is plus \r\n
          (message ((+ indx (length redis:CRLF)) (+ reply-len (length redis:CRLF)) (r 2))) )
    (case reply-len
      (-1 (list "" (+ (length "$-1") (length message) (length redis:CRLF)))) ; length of $-1 + remnant
      (true (begin
          (if (<= reply-len (- (length message) (length redis:CRLF))) ; if we don't need to read more
            (begin
              (let (read-len (+ indx
                                reply-len
                                (* 2 (length redis:CRLF)))) ; 2 times because \r\n on each line
                (list (0 (- 0 (length redis:CRLF)) message) read-len)))
            (redis:read r)))))))

(define (redis:handle-multi-bulk-reply r)
  (letn ( (crlf-index (find redis:CRLF (r 2)))
          (num (1 (- crlf-index 1) (r 2))) )
    (case (int num)
      (-1 (list '() (+ crlf-index (length redis:CRLF))))
      (nil (redis:read r))
      (true (begin
        (setf (r 2) ((+ crlf-index (length redis:CRLF)) (r 2)))
        (let ((byte-count (+ crlf-index (length redis:CRLF)))
              (results '()))
            (dotimes (x (int num))
              (let (result (redis:handle-bulk-reply r))
                (setf (r 2) ((result 1) (r 2)))
                (push (result 0) results -1)
                (inc byte-count (result 1))))
            (list results byte-count)))))))

(define (redis:handle-error r)
  (throw-error (1 (chop (r 2) 2))))

(define (redis:handle-integer-reply r)
  (let (num (int (1 (r 2)))) 
    (if (nil? num)
      (throw-error (append "Invalid integer reply:" (r 2)))
      (list (int num) (length (r 2))))))

(dolist (x redis:inline-commands)
  (redis:make-inline-command x))

(dolist (x redis:bulk-commands)
  (redis:make-bulk-command x))
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.