Implementing a Broken Link Checker in Guile
Background #
Some years ago we migrated our company website from WordPress to a static site using Hugo. As part of the build process we have a step to check for any broken links before the site is published; the script looks something like this:
# Start serving the site on localhost
hugo serve --buildDrafts --watch=false &
# Wait for the port to become reachable
while ! nc -z 127.0.0.1 1313; do sleep 1; done
# Run the broken link checker
blc -r http://127.0.0.1:1313/ \
--exclude linkedin.com \
--exclude twitter.com \
--exclude instagram.com
Imagine my surprise, then, when the Google search console was reporting that “New problems prevent indexing of your site” and that some of those problems were 404 errors for internal links. How had this got through the pipeline?
I checked the live site and confirmed the broken links, then re-ran the build
and checked that the link checker was running: it was, but it did not delve
deeply enough into the site to find the broken links, despite the -r option
making it recursive: it should be crawling everything on the site that’s
reachable from the home page.
The link checker in question, broken-link-checker, is implemented in NodeJS and unfortunately I don’t know Javascript well enough to start debugging. In any case, how hard can it be to implement a broken link checker?
The elements of a link checker #
To build a link checker, we need:
- a web client;
- an HTML parser;
- a tool to search for links in the parsed HTML;
- some way of keeping track of the work already done and the pages left to crawl.
In an effort to get to know Guile better I’ve started using it for ad hoc scripts that I might otherwise write in Python, and it turns out Guile has all the components we need to implement a link checker.
I was already familiar with Guile’s (web client)
module and Guile Library (a collection of
pure-scheme libraries for Guile) includes Neil Van Dyke’s permissive
(“pragmatic”) HTML parser,
(htmlprag).
This provides the html->sxml function to parse HTML text and return an
SXML expression. We can then use Guile’s
SXPath module
(a translation into scheme of the XML Path language, XPath) to extract links
from the SXML.
Finally, we can simply use a list as a queue of work to be done, and a hash table to keep track of pages we have already visited.
Down to business #
Our program starts by importing the modules we are going to need:
(use-modules
(ice-9 format)
(ice-9 match)
(web client)
(web response)
(web uri)
((web http) #:select (parse-header))
((htmlprag) #:select (html->sxml))
((sxml xpath) #:select (sxpath))
(srfi srfi-1)
(srfi srfi-9 gnu)
(srfi srfi-26)
(srfi srfi-37)
(srfi srfi-71))
Some of these are self-explanatory but if you’re not familiar with Scheme the SRFIs (Scheme Requests for Implementation) will need some explanation. These are extensions to the scheme language; sometimes they need to be installed as additional packages but the ones we use here are all part of Guile:
(srfi srfi-1)provides additional functions for working with lists.(srfi srfi-9)provides records (structs with named fields), and(srfi srfi-9 gnu)is an extension implementing theset-fieldfunction that we use below.(srfi srfi-26)implements thecutfunction for currying arguments.(srfi srfi-37)gives usargs-foldfor parsing command-line arguments.(srfi srfi-71)implements an extended version ofletthat handles multiple values.
Keeping track of state #
This program is intended to be run as a script, rather than a re-usable library, so we’ll keep things simple and store state in some global variables:
;; Queue of work to do, which is stored as pairs of (referrer . uri)
;; so we can report the referring page if `uri` is invalid
(define queue (list))
;; Hash of URLs already visited
(define seen (make-hash-table))
;; A count of invalid URLs we've seen.
(define error-count 0)
;; Whether or not we should act like a crawler and recurse into all
;; pages reachable from the start page. This will be set by a
;; command-line option.
(define recurse? #f)
;; A list of domains to exclude from checking (for example, sites
;; we know are valid but that return errors to crawlers). Populated
;; by command-line options.
(define excluded-domains (list))
;; Similar to excluded domains, but the entire URL must match, not
;; just the host part.
(define excluded-urls (list))
seen set as this could potentially grow quite large, but lists
will suffice for the exclusions which are coming from command-line options. (In
any case, we need to do a linear search of the excluded domains to test for a
matching suffix.)
Some handy functions #
We define some helper functions for managing the visited set and excluded URLs:
(define (seen? uri)
"Return #t if this URI has been visited, otherwise #f."
(hash-ref seen (uri->string uri) #f))
(define (set-seen! uri)
"Add the given URI to the visited set."
(hash-set! seen (uri->string uri) #t))
(define (exclude-domain! domain-name)
"Add a domain to the set of excluded domains."
(set! excluded-domains (lset-adjoin string=? excluded-domains domain-name)))
(define (exclude-url! url)
"Add a URL to the set of excluded URLs."
(set! excluded-urls (lset-adjoin string=? excluded-urls url)))
(define (excluded? uri)
"Check whether or not the URI is a memmber of the excluded URLs
or for an excluded domain."
(or (member (uri->string uri) excluded-urls string=?)
(any (cute string-suffix? <> (uri-host uri))
excluded-domains)))
…and some helpers for checking HTTP responses and comparing the host component of two URIs:
(define (html-content-type? res)
"Return #t if the response content type is HTML-like, otherwise #f."
(let ((ct (first (response-content-type res))))
(or (equal? ct 'text/html)
(equal? ct 'application/xhtml+xml)
(equal? ct 'application/xml))))
(define (ok-response? res)
"Return #t if the HTTP response code is 200 (OK), otherwise #f."
(= 200 (response-code res)))
(define (same-host? uri referrer)
"Return #t if URI has the same host name as REFERRER, otherwise #f."
(string=? (uri-host uri) (uri-host referrer)))
Extracting links from the HTML #
As described above, we parse the HTML body to get an SXML expression then use SXPath to extract the links. The SXPath expressions we’ll search for are:
(define link-paths (map sxpath
'((// a @ href)
(// img @ src)
(// link @ href)
(// video @ src)
(// video source @ src)
(// audio @ src)
(// audio source @ src))))
For simplicity, I haven’t included (// img @ srcset) in this list as the value
of that attribute would require further processing - a job for another day!
With this in hand, we can define a function that takes an HTML body as a string and returns
the links it finds as a list of strings:
(define (extract-links body)
"Extract links from an HTML document, discarding any tel: or mailto: links."
(let ((x (html->sxml body)))
(remove (lambda (s) (or (string-prefix? "tel:" s)
(string-prefix? "mailto:" s)))
(delete-duplicates
(map cadr
(concatenate
(map (lambda (f) (f x)) link-paths)))))))
Some of the links we get back will be complete links (that include the protocol,
host name, path, and optional query) but some will be relative links that could
be missing the host and port or have a relative path, so we need a function to
resolve these relative to their base-uri (the URL of the page they appear on):
(define (resolve-relative-uri base-uri s)
"If the string s is a relative URI, resolve it relative to base-uri."
(let ((uri (string->uri-reference s)))
(if (uri-scheme uri)
uri ; full URI, return as-is
(build-uri (uri-scheme base-uri)
#:userinfo (or (uri-userinfo uri)
(uri-userinfo base-uri))
#:host (or (uri-host uri)
(uri-host base-uri))
#:port (or (uri-port uri)
(uri-port base-uri))
#:path (cond
((string-prefix? "/" (uri-path uri))
(uri-path uri))
((string-suffix? "/" (uri-path base-uri))
(string-append (uri-path base-uri)
(uri-path uri)))
(else
(string-append (uri-path base-uri)
"/"
(uri-path uri))))
#:query (uri-query uri)))))
If a URI has a fragment (text after a trailing #) we strip it off as two URIs
that differ only in the fragment are actually for the same page.
(define (uri-without-fragment uri)
"If URI has a fragment, return a new URI without the fragment."
(if (uri-fragment uri)
(set-field uri (uri-fragment) #f)
uri))
Putting these pieces together, the code to fetch an HTML page, extract the links
from the body, and add the pair of (referrer . uri) to the work queue looks like:
(define (enqueue-links base-uri)
(unless (seen? base-uri)
(hash-set! seen (uri->string base-uri) #t)
(format #t "[INFO] enqueuing links for ~a~%" (uri->string base-uri))
(let ((res body (http-get base-uri)))
(if (ok-response? res)
(if (html-content-type? res)
(set! queue (append queue
(map (compose (cut cons base-uri <>)
uri-without-fragment
(cut resolve-relative-uri base-uri <>))
(extract-links body))))
(format #t "[ERROR] unexpected content type ~a for ~a~%"
(response-content-type res) (uri->string base-uri)))
(format #t "[ERROR] unexpected status code ~a for ~a~%"
(response-code res) (uri->string base-uri))))))
Validating links #
The main job of this script is to check that links appearing on our website are
valid. We do this by making an HTTP HEAD request for each URI and checking the
response status code. The same link might appear on more than one page of our
website so the queue of links to check is a list of pairs (referrer . uri)
where referrer is the page with the link and uri the target. We want to
report every page that contains a broken link, but there’s no need to check the
same target more than once, so we implement a memoized function for this:
(define http-head-memoized
(let ((memo (make-hash-table)))
(lambda (uri)
(let ((key (uri->string uri)))
(unless (hash-ref memo key #f)
(with-exception-handler
(lambda (e)
(hash-set! memo key e))
(lambda ()
(let ((res _ (http-head uri #:headers request-headers)))
(hash-set! memo key res)))
#:unwind? #t))
(hash-ref memo key)))))
We have to wrap the http-head call in an exception handler as certain errors
(such as host name not found) raise exceptions. In this case, we return the
exception object.
Some sites return spurious errors if they don’t recognize the user agent so we make the HEAD request with headers that look like a standard browser:
(define request-headers
(map (match-lambda ((k . v) (cons k (parse-header k v))))
'((accept . "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
(accept-encoding . "gzip, deflate, br, zstd")
(accept-language . "en-GB,en;q=0.5")
(user-agent . "Mozilla/5.0 (X11; Linux x86_64; rv:133.0) Gecko/20100101 Firefox/133.0"))))
parse-header function from (web http) to convert from a string to the
required format.
Managing the work queue #
The program will first call enqueue-links for the starting URLs requested on
the command-line, then the following function to work through the queue:
(define (process-queue)
(match queue
(()
(format #t "[INFO] processing complete, found ~a broken link~p~%" error-count error-count))
(((referrer . uri) rest ...)
(set! queue rest)
(if (excluded? uri)
(format #t "[INFO] skipping excluded URL ~a~%" (uri->string uri))
(let ((res (http-head-memoized uri)))
(cond
((exception? res)
(format #t "[ERROR] HEAD ~a referred to by ~a threw exception ~a~%"
(uri->string uri) (uri->string referrer) res)
(set! error-count (1+ error-count)))
((> (response-code res) 399)
(format #t "[ERROR] HEAD ~a referred to by ~a returned HTTP Status ~a~%"
(uri->string uri) (uri->string referrer) (response-code res))
(set! error-count (1+ error-count)))
((and recurse? (ok-response? res) (html-content-type? res) (same-host? uri referrer))
(enqueue-links uri)))))
(process-queue))))
This function is using the match function from (ice-9 match)
to destructure the queue. The first clause matches an empty queue (in which case
we print the number of broken links found and return), while the second clause
further destructures the first pair into referrer and target URI.
After destructuring, it pops the first element off of the queue then calls the memoized HEAD function to check the target URI and checks the response for exceptions or an HTTP response code indicating an error. In recursive mode, if the target URI is for an HTML page on the same site, it will call enqueue-links for that URI.
Finally the function calls itself: it will keep looping until the queue is empty.
Testing and debugging #
The program now has enough functionality to test it from the REPL. In a terminal
I ran hugo serve while in a REPL I loaded the script and ran:
(enqueue-links (string->uri "http://127.0.0.1:1313/"))
;; [INFO] enqueuing links for http://127.0.0.1:1313/
(process-queue)
;; [INFO] processing complete, found 0 broken links
It didn’t find the broken links! I added a debug line to http-head-memoized to see what was going on:
(define http-head-memoized
(let ((memo (make-hash-table)))
(lambda (uri)
(let ((key (uri->string uri)))
(pk 'http-head-memoized key)
(unless (hash-ref memo key #f)
(with-exception-handler
(lambda (e)
(hash-set! memo key e))
(lambda ()
(let ((res _ (http-head uri #:headers request-headers)))
(hash-set! memo key res)))
#:unwind? #t))
(hash-ref memo key)))))This was insightful: when I re-ran the test I could see two problems. Firstly,
some of the links generated by hugo were for http://127.0.0.1:1313/ and
matched the same-host? criteria as expected, but some were pointing at
http://localhost:1313/ which would resolve to the same address but fail the
simple string match I was using. The second issue was that our site authors had
sometimes hard-coded the live host name in links instead of using the hugo
short-code for the link.
In implementing this link checker I had uncovered the likely reason the NodeJS link checker had failed to find the broken links.
Now that I was in control of the code I could work around the problem. I added a list of host names to override in the scraped URLs and a function to apply these overrides to the crawled links:
(define host-overrides
'())
(define (add-host-override! host-name)
(set! host-overrides (lset-adjoin equal? host-overrides host-name)))
(define (override-host-port base-uri uri)
(if (member (uri-host uri) host-overrides)
(set-fields uri
((uri-scheme) (uri-scheme base-uri))
((uri-host) (uri-host base-uri))
((uri-port) (uri-port base-uri)))
uri))
This function was then composed with the other functions post-processing the crawled links:
(define (enqueue-links base-uri)
(unless (seen? base-uri)
(hash-set! seen (uri->string base-uri) #t)
(format #t "[INFO] enqueuing links for ~a~%" (uri->string base-uri))
(let ((res body (http-get base-uri)))
(if (ok-response? res)
(if (html-content-type? res)
(set! queue (append queue
(map (compose (cut cons base-uri <>)
(cut override-host-port base-uri <>)
uri-without-fragment
(cut resolve-relative-uri base-uri <>))
(extract-links body))))
(format #t "[ERROR] unexpected content type ~a for ~a~%" (response-content-type res) (uri->string base-uri)))
(format #t "[ERROR] unexpected status code ~a for ~a~%" (response-code res) (uri->string base-uri))))))Now at the REPL I reset the seen set, added the host overrides, and re-ran the link checker:
(set! seen (make-hash-table))
(add-host-override! "localhost")
(add-host-override! "metail.com")
(enqueue-links (string->uri "http://127.0.0.1:1313/"))
(process-queue)
Success! Now it did descend deeper into the site and find the broken links that Google was reporting.
Parsing command-line arguments #
To wrap this up and turn the program into a script we can add to our CI/CD pipeline I added some options processing and a shebang line:
#!/usr/bin/guile \
--no-auto-compile -e main -s
!#
This tells the operating system to invoke /usr/bin/guile to run the script; the -s option tells Guile to load the script as a Scheme file; and the -e main option tells Guile to invoke the
main function with the command-line arguments after reading the script. See Guile Scripting
for more information and examples.
For the options parsing, I decided to use the args-fold function from SRFI
37.
For each option, we define the single-character option, the long option name(s), whether it takes a required or optional argument, and a function to accumulate the result:
(define %options
(list
(option '(#\h "help") #f #f
(lambda args
(show-help)
(exit 0)))
(option '(#\X "exclude-domain") #t #f
(lambda (opt name val result)
(assoc-set! result 'exclude-domains
(cons val (assoc-ref result 'exclude-domains)))))
(option '(#\x "exclude-url") #t #f
(lambda (opt name val result)
(assoc-set! result 'exclude-urls
(cons val (assoc-ref result 'exclude-urls)))))
(option '(#\o "override-host") #t #f
(lambda (opt name val result)
(assoc-set! result 'host-overrides
(cons val (assoc-ref result 'host-overrides)))))
(option '(#\r "recurse") #f #f
(lambda (opt name val result)
(assoc-set! result 'recurse #t)))))
We accumulate the options in an association list:
(define %default-options
'((exclude-domains . ())
(exclude-urls . ())
(host-overrides . ())
(recurse . #f)
(urls . ())))
The first four keys correspond to the options above, while urls will come from the non-option arguments on the command-line, which are accumulated by the fourth argument to args-fold:
(define (parse-args args)
(args-fold args %options
(lambda (opt name arg result)
(format (current-error-port) "~A: unrecognized option~%" opt)
(exit 1))
(lambda (url result)
(assoc-set! result 'urls (cons url (assoc-ref result 'urls))))
%default-options))
Finally, we bring everything together with a main function:
(define (main args)
(let ((args (parse-args (cdr args))))
(set! recurse? (assoc-ref args 'recurse))
(for-each exclude-domain! (assoc-ref args 'exclude-domains))
(for-each exclude-url! (assoc-ref args 'exclude-urls))
(for-each add-host-override! (assoc-ref args 'host-overrides))
(for-each (compose enqueue-links string->uri) (assoc-ref args 'urls))
(process-queue)
(if (> error-count 0)
(exit 2)
(exit 0))))
Note: it might have been simpler (certainly less code) to have the options
processor call exclude-domain! etc. during options processing, but I thought
it was clearer to accumulate the options in a separate structure and have the
main function set the global variables.
Deployment #
In order to add this to our CI/CD pipeline I created a Docker container based on a HugoMods image, adding in the broken link checker script. This was not as straightforward as it might have been as the Guile Library package is not (at the time of writing) available in Alpine so had to be built from source. Here’s the Dockerfile for the image:
# syntax=docker/dockerfile:1
FROM hugomods/hugo:ci-0.141.0 AS build
RUN apk add --update --no-cache guile guile-dev libc-dev gcc make autoconf automake pkgconfig
ADD http://download.savannah.nongnu.org/releases/guile-lib/guile-lib-0.2.8.1.tar.gz .
RUN tar xf guile-lib-0.2.8.1.tar.gz \
&& cd ./guile-lib-0.2.8.1 \
&& ./configure --prefix /usr --with-guile-site \
&& make && make install
FROM hugomods/hugo:ci-0.141.0
COPY --from=build /usr/share/guile/site/ /usr/share/guile/site/
COPY --from=build /usr/lib/guile/3.0/site-ccache/ /usr/lib/guile/3.0/site-ccache/
RUN apk add --no-cache --update aws-cli curl guile guile-gnutls
COPY --chmod=0755 broken-link-checker.scm /usr/local/bin/blc
Using this image and the new script, the CI/CD job for our website build needs
just a small change to the blc arguments:
blc -r -o localhost -o metail.com \
-X linkedin.com -X twitter.com -X instagram.com \
http://127.0.0.1:1313/
You can download the complete script here: broken-link-checker.scm.
Addendum: handling srcset #
At the beginning of this article I said we would leave handling of ‘srcset` attributes until another day, but I don’t like to leave a job unfinished…
The scrset attribute allows web pages to offer a choice of images of different sizes to the user agent. It is a comma-separated list, with each element of the list being a space-separated URL and width or density specification. For example:
<source
id="el"
srcset="smile.png, smile-1.5x.png 1.5x, smile-2x.png 2x"
type="image/png" />
We start by implementing a function to parse these lists and return just the URLs:
(define (parse-srcset s)
"Parse out the list of URLs from an image srcset, discarding whitespace and the
width/density descriptor."
(map (compose first (cut string-split <> #\space))
(map string-trim-both (string-split s #\,))))
This splits the string on commas, strips leading and trailing white space from each value, then splits on spaces and returns the first element (the URL).
We add the srcset attributes to the list of SXPath expressions to search:
(define link-paths (map sxpath
'((// a @ href)
(// img @ src)
(// link @ href)
(// video @ src)
(// video source @ src)
(// audio @ src)
(// audio source @ src)
(// picture source @ srcset)
(// img @ srcset))))Finally, the extract-links function needed some refactoring to slot this in as the
result of the SXPath search could now be a single link or a list of links; I
thought the easiest way to deal with this was to use a nested fold. The outer
fold iterates over the SXPath expressions, returning a list of
(attr-name . link) for each matching element, and the inner fold iterates over
this list accumulating either the single link (with cons) or the list from
an expanded srcset (with append):
(define (extract-links body)
"Extract links from an HTML document, discarding any tel: or mailto: links."
(let ((x (html->sxml body)))
(remove (lambda (s) (or (string-prefix? "tel:" s) (string-prefix? "mailto:" s)))
(delete-duplicates
(fold (lambda (f accum)
(fold (lambda (x accum)
(match-let (((attr val) x))
(if (equal? attr 'srcset)
(append (parse-srcset val) accum)
(cons val accum))))
accum
(f x)))
'()
link-paths)))))