In this short essay I’ll describe the “sentinel file” pattern, which I recently used when writing a command-line tool to use at
$WORK for interacting with our web API.
The essence of the sentinel file pattern is that you use a certain file’s last-modified time as a record against which you compare other time-based values.
It is useful in many contexts, such as software builds; in the context of web APIs, it can be used to track whether you will need to reauthenticate with the API before you fire off a bunch of API calls.
The recipe is essentially this:
- Update a sentinel file F‘s timestamp at time T.
- When you are about to take an action such as make an API call, see if the current time, T’, is greater than the timeout value of your web API, V, plus the sentinel file’s existing timestamp T.
We can translate this into Scheme as follows (this is scsh, to be exact), where:
;; F = sentinel-file ;; T = (file-last-mod sentinel-file) ;; T' = (time) ;; V = api-timeout-value (define (sentinel-expired? sentinel-file) (> (time) (+ (file-last-mod sentinel-file) api-timeout-value)))
FILE-LAST-MOD are part of the scsh POSIX API.
This pattern is much more efficient than storing some kind of “am I logged in?” value in a JSON/YAML/XML/s-expression config file that has to be read in and parsed on every invocation and written out from time to time.
I debated whether to write about this simple technique at all because it seems like an old trick that many people know. However, I’m going to assume that I am not unique, and that there are lots of people out there who could benefit from using this technique when the right situation arises.