Reference Manual | Prev: Chapter 8. Authentication | Next: Chapter 10. HTTP Client
CL-HTTP provides an in-memory data caching facility that stores
response bodies in dynamic memory for fast serving. The data cache
avoids repeated disk access for frequently requested static files by
maintaining their contents in RAM. The implementation is in
http:server;data-cache.lisp.
The data cache is organized around data universes — named collections of cached data. Each universe maintains a hash table of cached entries, tracks total cache size, and supports asynchronous revalidation of stale entries. The class hierarchy is:
basic-data-universe — Base class with cache table,
size limits, and access auditing.
file-data-universe — Adds background revalidation
via a dedicated process that periodically checks cached files for
modification.
The variable http:*standard-data-universe* holds the
current data universe object.
;; Intern a data universe, creating it if necessary
(http::intern-data-universe "My-Cache"
:if-does-not-exist :create
:class 'http::file-data-universe)
The generic function cache-data is the primary method
for caching data sources in a universe:
(cache-data universe data-source
&key revalidation-interval wired-p)
When data-source is a pathname, the system creates the
appropriate cache object — either a crlf-file-data-cache
for text files that need CRLF canonicalization, or a
binary-file-data-cache for binary files. The
:wired-p keyword prevents the cached data from being evicted
under memory pressure.
define-cached-data MacroThe define-cached-data macro provides a declarative
interface for specifying the initial data to cache in a universe:
(http::define-cached-data ("Standard-Pathname-Cache"
:audit-access-p t)
;; Wire frequently accessed files into the cache
("http:www;cl-http;cl-http.html" :wired-p t)
"http:www;cl-http;icons;power.gif")
:clear-data-universe-p (default t)
:audit-access-p
:data-universe-class (default 'file-data-universe)
The file-data-universe class supports asynchronous
revalidation. A background process periodically checks cached files
against disk, refreshing any whose modification dates have changed. The
revalidation interval is controlled per-universe and per-cache-entry.
Revalidation avoids serving stale content without incurring the cost of
checking disk on every request.
CL-HTTP supports HTTP expiration headers that control how downstream
caches (proxies and browsers) handle cached copies. Expiration is
configured per-URL via the :expiration keyword on
http:export-url.
The :expiration argument takes a list whose first element
specifies the type:
:no-expiration-header
Expires header is issued. Caching behavior is left
to the client's discretion.
:never
Expires header indicating one year from now,
effectively marking the resource as permanently cacheable.
:time universal-time
Expires header for the specified absolute
universal time.
:interval seconds
Expires header computed as the current time
plus the interval in seconds. This is the most common form.
:function function
Expires header, or
nil to suppress the header.
;; Content expires in one hour
(http:export-url #u"/reports/daily.html"
:computed
:response-function #'write-daily-report
:expiration '(:interval 3600))
;; Content expires at a specific time
(http:export-url #u"/events/schedule.html"
:html-file
:pathname "http:www;events;schedule.html"
:expiration '(:time 3980000000))
;; Content never expires (one year)
(http:export-url #u"/static/logo.gif"
:gif-image
:pathname "http:www;images;logo.gif"
:expiration '(:never))
HTTP/1.1 cache-control headers provide finer-grained control than
Expires. The :cache-control keyword on
http:with-successful-response and
http:with-conditional-get-response accepts a property list
of cache-control directives:
(http:with-successful-response (stream :html
:cache-control '(:public t :max-age 3600))
(html:with-html-document (:stream stream)
...))
Conditional GET allows a client to validate its cached copy of a
resource without transferring the full response body. CL-HTTP implements
this via the with-conditional-get-response macro.
with-conditional-get-response
(http:with-conditional-get-response
(stream content-type
&key bytes last-modification character-set
entity-tag expires location cache-control
content-location content-language
additional-headers additional-mime-headers
termination-line-p version)
body)
This macro checks whether the client has provided an
If-Modified-Since header. If the resource has not been
modified since that time, the server returns a 304 Not Modified
response with updated headers but no body. Otherwise, body is
executed and the full response is sent.
(defun write-data-page (url stream)
(let ((last-mod (get-data-modification-time)))
(http:with-conditional-get-response
(stream :html
:last-modification last-mod
:expires (+ (get-universal-time) 3600)
:cache-control '(:public t))
(html:with-html-document (:stream stream)
(html:with-document-preamble (:stream stream)
(html:declare-title "Data Report" :stream stream))
(html:with-document-body (:stream stream)
(write-report-body stream))))))
Entity tags (ETags) provide a more reliable validation mechanism than
modification dates, especially for content that may change within the
resolution of the file system clock. Supply the :entity-tag
keyword (or :version, which maps to entity-tag) to enable
ETag-based conditional responses.
The resource pooling facility (in http:mcl;server;resources.lisp)
provides object reuse to reduce garbage collection pressure. Rather than
allocating and discarding objects on every request, pooled objects are
returned to a free list and reused. CL-HTTP pools buffers, server objects,
process objects, and HTTP connections.
defresource(defresource name (parameters) :constructor constructor-function :initializer initializer-function :deinitializer deinitializer-function :initial-copies count :matcher predicate)
:constructor
:initializer
:deinitializer
:initial-copies
:matcher
;; Manual allocation and deallocation
(let ((buffer (allocate-resource 'http-buffer 8192)))
(unwind-protect
(process-with-buffer buffer)
(deallocate-resource 'http-buffer buffer)))
;; Automatic with using-resource
(using-resource (buffer http-buffer 8192)
(process-with-buffer buffer))
The using-resource macro is the preferred interface. It
allocates an object from the named resource, binds it to the variable,
executes the body, and deallocates the object on exit (including
non-local exits via unwind-protect).
CL-HTTP defines several standard resources:
(unsigned-byte 8)
arrays for bulk I/O, avoiding per-connection allocation of 8KB buffers.
CL-HTTP has been designed to run efficiently while preserving abstractions that enhance intelligibility and extensibility. The following guidelines help you write response functions and application code that runs fast without sacrificing the power of Common Lisp.
Come up with efficient algorithms (logarithmic or better) before
micro-optimizing. Start by developing good abstractions, then optimize
only the critical path. Meter your code using the Common Lisp
time function and profiling tools — this is the only
way to find out where time is actually spent.
Minimize unnecessary consing by using destructive operations
(nconc, nreverse, delete) and
copying data structures only when necessary. Use the
dynamic-extent declaration to stack-allocate temporary data
and closures:
;; Stack-allocate the closure for mapping
(flet ((process-header (name value)
(write-header-to-log name value log-stream)))
(declare (dynamic-extent #'process-header))
(map-headers #'process-header))
Prefer flet local functions over anonymous
lambda expressions — named local functions allow the
closure to be consed on the stack rather than the heap. When mapping
over sequences, either pass all arguments explicitly or use a named
flet with dynamic-extent declared.
format incurs overhead parsing the control string. In
inner loops and response-generation hot paths, use
write-string, write-char, and
princ directly:
;; Slow: FORMAT parses the control string each time (format stream "~A: ~A~%" name value) ;; Fast: direct output operations (write-string name stream) (write-string ": " stream) (princ value stream) (terpri stream)
Use declaim inline for small functions on the critical
path. This conserves abstraction while gaining efficiency. Beware of
over-inlining that bloats the instruction cache working set. Metering
determines when inlining is appropriate.
Keyword argument processing has runtime overhead. In frequently called
functions (but not macros or inline functions), prefer positional
arguments. Keep the number of arguments to inner-loop functions to four
or fewer for efficient register passing. Pass positional
:start and :end arguments to sequence
operations when available in the local context.
Use the loop iteration macro and especially the
iteration paths (collect, append,
nconc) because these expand into very efficient code.
Use defresource pooling (see Section 9.4)
to recycle data structures rather than consing new ones, unless the
allocation/deallocation overhead is more expensive than merely creating
new structures each time.
Do not serialize threads responding to requests because of a shared resource. Use fine-grained locking, lock-free patterns, or per-thread state to maintain concurrency. The data cache uses multiple-reader-single-writer locks to allow concurrent read access.
Use generic functions at points where method specialization enhances
abstraction, and otherwise use functions and fast slot accessors. In some
implementations, with-slots and slot-value are
faster than generic function accessors.
Declare all numeric operations to avoid bignum arithmetic:
(let ((count 0))
(declare (type fixnum count))
(loop for item in items
do (incf count))
count)
CL-HTTP provides a modular logging system based on CLOS mixin classes. Log objects are composed from mixins that provide different capabilities: file writing, counters, console notification, and dynamic per-URL tracking.
The standard log classes combine mixins for typical use cases:
http:common-file-log
http:extended-common-file-log
Referer and
User-Agent header fields. This is the default log class
(http:*log-access-log-class*). Conses slightly more than
common-file-log because it must copy two additional header values.
http:basic-common-file-log
http:http-log
The key mixin classes are:
http:basic-file-logging-mixin
http:log-counters-mixin
http:log-notification-mixin
http:compressed-file-logging-mixin
Set the default log class in your configuration file:
;; Use extended common log format (the default)
(setq http:*log-access-log-class* 'http:extended-common-file-log)
;; Install a log on a specific port
(http:intern-access-log "HTTP-8000-Log"
:port 8000
:class 'http:extended-common-file-log)
To define a custom log class, subclass the appropriate mixins and provide methods for:
http:log-entry-writer
http:write-access-log-entry
(defclass my-custom-log
(http:extended-common-file-format-mixin
http:access-log
http:basic-file-logging-mixin)
((log-file-name :initform "My-Log"
:allocation :class)))
(defmethod http:log-entry-writer
((log my-custom-log) (server http:server-logging-mixin))
;; Snapshot state and return a writer closure
(let ((host (http::host-log-name server))
(request (http:server-request server t)))
(flet ((write-entry (log-stream)
(format log-stream "~A ~A~%"
host request)))
#'write-entry)))
Log files are automatically rotated based on configuration. The method
http::switch-log-file handles rotation, and the
compressed-file-logging-mixin can automatically compress
old log files.