diff options
| author | Murilo Ijanc <[email protected]> | 2026-07-26 12:42:28 -0300 |
|---|---|---|
| committer | Murilo Ijanc <[email protected]> | 2026-07-26 12:42:28 -0300 |
| commit | ae9ad8a4c61b793f6859c84dac80b1c1b04b7b68 (patch) | |
| tree | 62271e7672dfc58f59dda2ea4dc539c89a1ea5ca /src | |
| download | lisp-ae9ad8a4c61b793f6859c84dac80b1c1b04b7b68.tar.gz | |
Initial importv0.1.0
Diffstat (limited to 'src')
| -rw-r--r-- | src/client.lisp | 403 | ||||
| -rw-r--r-- | src/csv.lisp | 60 | ||||
| -rw-r--r-- | src/errors.lisp | 73 | ||||
| -rw-r--r-- | src/models.lisp | 147 | ||||
| -rw-r--r-- | src/package.lisp | 100 |
5 files changed, 783 insertions, 0 deletions
diff --git a/src/client.lisp b/src/client.lisp new file mode 100644 index 0000000..2965c86 --- /dev/null +++ b/src/client.lisp @@ -0,0 +1,403 @@ +(in-package #:cepis) + +(defparameter +version+ "0.1.0" + "Version of this library, as it appears in the default User-Agent.") + +(defparameter +default-url+ "https://cep.is" + "Where the API lives unless a client says otherwise.") + +(defconstant +max-batch+ 500 + "Most CEPs the API accepts in a single batch request.") + +(defparameter +retriable-status+ '(429 500 502 503 504) + "Statuses worth another attempt. 400 and 404 are deliberately absent: both +are definitive answers about the request, so retrying returns the same thing +more slowly while burning someone else's quota.") + +(defparameter +months+ + '("Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec") + "Month abbreviations of an HTTP date, in order.") + +(defun monotonic-now () + "Seconds from an arbitrary origin, for measuring elapsed time." + (/ (get-internal-real-time) (float internal-time-units-per-second 1.0d0))) + +(defun digits-only-p (string) + "True when STRING is made exclusively of ASCII digits." + (and (plusp (length string)) + (every (lambda (character) (char<= #\0 character #\9)) string))) + +(defun normalize-cep (value) + "Return the CEP's 8 digits, accepting the mask. + +\"01001-000\", \"01001000\" and \" 01001-000 \" all become \"01001000\". + +Signals `invalid-cep' unless exactly 8 digits remain. This runs before any +request: a 7-digit CEP is the caller's bug, and spending a round trip for the +server to say so wastes both sides' time." + (unless (stringp value) + (error 'invalid-cep + :message (format nil "CEP must be a string, got ~a" (type-of value)))) + (let ((cleaned (remove-if (lambda (character) + (member character '(#\- #\. #\Space #\Tab #\Newline #\Return))) + value))) + (unless (and (= (length cleaned) 8) (digits-only-p cleaned)) + (error 'invalid-cep + :message (format nil "CEP must be 8 digits, got ~s" value))) + cleaned)) + +(defun url-encode (value) + "Percent-encode VALUE for use inside a query string." + (with-output-to-string (out) + (loop for byte across (babel:string-to-octets (princ-to-string value) :encoding :utf-8) + for character = (code-char byte) + do (if (or (char<= #\a character #\z) + (char<= #\A character #\Z) + (char<= #\0 character #\9) + (find character "-._~")) + (write-char character out) + (format out "%~2,'0X" byte))))) + +(defun body-text (body) + "Decode a response body to a string, replacing anything that is not UTF-8." + (cond ((null body) "") + ((stringp body) body) + (t (babel:octets-to-string (coerce body '(vector (unsigned-byte 8))) + :encoding :utf-8 + :errorp nil)))) + +(defun parse-http-date (value) + "Parse an HTTP date such as \"Wed, 21 Oct 2026 07:28:00 GMT\" into a universal +time, or NIL when it does not look like one." + (let ((parts (remove "" (uiop:split-string value :separator " ,") :test #'string=))) + (when (>= (length parts) 5) + (destructuring-bind (weekday day month year clock &rest rest) parts + (declare (ignore weekday rest)) + (let ((month-index (position month +months+ :test #'string-equal)) + (clock-parts (uiop:split-string clock :separator ":"))) + (when (and month-index (= (length clock-parts) 3)) + (ignore-errors + (encode-universal-time (parse-integer (third clock-parts)) + (parse-integer (second clock-parts)) + (parse-integer (first clock-parts)) + (parse-integer day) + (1+ month-index) + (parse-integer year) + 0)))))))) + +(defun retry-after-seconds (value) + "Parse the Retry-After header in both RFC 9110 forms. + +It may arrive as a number of seconds (\"120\") or as an HTTP date (\"Wed, 21 +Oct 2026 07:28:00 GMT\"). Handling only the first is the common bug, and it +makes a client ignore exactly the wait request that matters most." + (when (and (stringp value) (plusp (length (string-trim " " value)))) + (let* ((trimmed (string-trim " " value)) + (seconds (ignore-errors (parse-integer trimmed)))) + (if seconds + (max 0 seconds) + (let ((date (parse-http-date trimmed))) + (when date + (max 0 (- date (get-universal-time))))))))) + +(defun header-value (headers name) + "The value of header NAME, which dexador gives us downcased in a hash table." + (when (hash-table-p headers) + (gethash name headers))) + +(defclass client () + ((base-url :initarg :base-url + :initform +default-url+ + :reader client-base-url + :documentation "Where the API lives. A trailing slash is stripped.") + (timeout :initarg :timeout + :initform 10.0 + :reader client-timeout + :documentation "Seconds allowed per socket operation.") + (max-attempts :initarg :max-attempts + :initform 3 + :reader client-max-attempts + :documentation "Attempts in total, counting the first.") + (backoff-base :initarg :backoff-base + :initform 0.5 + :reader client-backoff-base + :documentation "Base of the exponential wait, in seconds.") + (backoff-max :initarg :backoff-max + :initform 8.0 + :reader client-backoff-max + :documentation "Cap on each individual wait, in seconds.") + (total-timeout :initarg :total-timeout + :initform nil + :reader client-total-timeout + :documentation "Cap on the whole call, or NIL for no cap.") + (user-agent :initarg :user-agent + :initform nil + :reader client-user-agent + :documentation "What the client calls itself.")) + (:documentation + "Configuration for talking to the API. Build one with `make-client'. + +Reuse one instance: the configuration is not mutated and no function keeps +state between calls, so it is safe to share across threads.")) + +(defmethod initialize-instance :after ((client client) &key) + (with-slots (base-url timeout max-attempts user-agent) client + (unless (and (integerp max-attempts) (>= max-attempts 1)) + (error "max-attempts must be an integer >= 1, got ~s" max-attempts)) + (unless (and (realp timeout) (plusp timeout)) + (error "timeout must be > 0, got ~s" timeout)) + (setf base-url (string-right-trim "/" base-url)) + (unless user-agent + (setf user-agent (format nil "cepis-lisp/~a (+https://cep.is)" +version+))))) + +(defun make-client (&rest initargs + &key base-url timeout max-attempts backoff-base backoff-max + total-timeout user-agent) + "Build a `client'. + +BASE-URL is where the API lives, \"https://cep.is\" by default. Point it at a +local instance (the API repo brings one up on http://localhost:8080 with `just +up') or at a test server. It is the only parameter that usually changes +between environments. + +TIMEOUT is the seconds allowed per socket operation — connect, and each read. +It is not a cap on the whole call; that cap is TOTAL-TIMEOUT, which counts +attempts and waits alike and defaults to NIL, meaning MAX-ATTEMPTS is the only +bound. Set it in code serving a web request. + +MAX-ATTEMPTS is how many attempts in total, counting the first; 1 disables +retrying. The default of 3 covers the common case, one transient failure, +without turning a real outage into a long wait. + +BACKOFF-BASE is the base of the exponential wait, in seconds: the actual wait +is drawn from [0, base * 2^(n-1)], full jitter. The randomness is not +decoration — without it, N clients that fail together come back together and +reproduce the spike that took the service down. BACKOFF-MAX caps each +individual wait, a server-sent Retry-After included, so a misconfigured proxy +answering \"Retry-After: 3600\" cannot park the caller for an hour. + +USER-AGENT overrides the User-Agent header. The default identifies the library +and its version, which is what lets the server diagnose an old client +misbehaving." + (declare (ignorable base-url timeout max-attempts backoff-base backoff-max + total-timeout user-agent)) + (apply #'make-instance 'client initargs)) + +(defvar *client* (make-client) + "The client used when no :client argument is given. + +Built once, because a `client' keeps no state between calls and is thread +safe. Do not mutate it: it applies process-wide, including to third-party +libraries that also use this package. Anyone needing different settings should +build their own with `make-client'.") + +(defun backoff-delay (client attempt retry-after) + "How long to wait before the next attempt. + +The server's Retry-After wins over the local calculation when present: it +knows when it will be back, we are guessing. It still goes through the +`client-backoff-max' cap. Otherwise the wait is drawn from [0, ceiling] rather +than being the ceiling." + (if retry-after + (min retry-after (client-backoff-max client)) + (let ((ceiling (min (* (client-backoff-base client) (expt 2 (1- attempt))) + (client-backoff-max client)))) + (if (plusp ceiling) (random ceiling) 0)))) + +(defun perform-request (client url) + "One attempt at GET URL. + +Returns (values :response status body headers) for anything the server +answered, and (values :network condition) when the request never completed." + (handler-case + (multiple-value-bind (body status headers) + (dex:get url + :headers (list (cons "User-Agent" (client-user-agent client)) + (cons "Accept" "application/json, text/csv;q=0.9, */*;q=0.1") + (cons "Accept-Encoding" "identity")) + :force-binary t + :connect-timeout (client-timeout client) + :read-timeout (client-timeout client)) + (values :response status body headers)) + (dex:http-request-failed (condition) + (values :response + (dex:response-status condition) + (dex:response-body condition) + (dex:response-headers condition))) + (error (condition) + (values :network condition)))) + +(defun request (client path &key (accepted-status '(200))) + "Perform the GET, with retries. Returns (values status body headers). + +Definitive error statuses (400, 404) come back normally, for the caller to +turn into the right condition — only transient failures become conditions +here, and only once the attempts are exhausted." + (let* ((url (concatenate 'string (client-base-url client) path)) + (attempts (client-max-attempts client)) + (total-timeout (client-total-timeout client)) + (deadline (when total-timeout (+ (monotonic-now) total-timeout))) + (last-status nil) + (last-retry-after nil) + (last-condition nil)) + (loop for attempt from 1 to attempts + do (when (and deadline (>= (monotonic-now) deadline)) + (return)) + (multiple-value-bind (kind status body headers) (perform-request client url) + (if (eq kind :network) + (setf last-condition status + last-status nil + last-retry-after nil) + (progn + (when (or (member status accepted-status) + (not (member status +retriable-status+))) + (return-from request (values status body headers))) + (setf last-status status + last-retry-after (retry-after-seconds + (header-value headers "retry-after")) + last-condition nil)))) + (when (= attempt attempts) + (return)) + (let ((wait (backoff-delay client attempt last-retry-after))) + (when deadline + (let ((remaining (- deadline (monotonic-now)))) + (when (<= remaining 0) + (return)) + (setf wait (min wait remaining)))) + (sleep wait))) + (cond ((eql last-status 429) + (error 'rate-limited + :message (format nil "rate limit reached at ~a (after ~d attempt(s))" + url attempts) + :retry-after last-retry-after)) + (last-status + (error 'server-error + :message (format nil "the API answered ~d at ~a (after ~d attempt(s))" + last-status url attempts) + :status last-status)) + (t + (error 'network-error + :message (format nil "could not reach ~a (after ~d attempt(s)): ~a" + url attempts last-condition)))))) + +(defun parse-json-object (body) + "Decode a JSON object body, or signal `invalid-response'." + (let* ((text (body-text body)) + (data (handler-case (com.inuoe.jzon:parse text) + (error () + (error 'invalid-response + :message (format nil "response is not valid JSON — something ~ +between you and the API is answering instead of it: ~s" + (subseq text 0 (min 120 (length text))))))))) + (unless (hash-table-p data) + (error 'invalid-response + :message (format nil "expected a JSON object, got ~a" (type-of data)))) + data)) + +(defun api-message (body fallback) + "Pull \"mensagem\" out of an error body, falling back to FALLBACK." + (handler-case + (let ((data (com.inuoe.jzon:parse (body-text body)))) + (if (hash-table-p data) + (let ((message (gethash "mensagem" data))) + (if (and (stringp message) (plusp (length message))) + message + fallback)) + fallback)) + (error () fallback))) + +(defun lookup (cep &key (client *client*)) + "Look up a single CEP and return an `address'. + + (address-localidade (lookup \"01001-000\")) => \"São Paulo\" + +A 400 from the API is surfaced as `invalid-cep' carrying the API's own +message: the format already passed local validation, so the server knows +something this client does not. + +Signals `invalid-cep' when the CEP is not 8 digits, without making a request; +`cep-not-found' when it is well-formed but not in the database; `rate-limited' +on 429 and `server-error' on 5xx after every attempt; `network-error' when the +request never completed; `invalid-response' when the body cannot be read." + (let ((number (normalize-cep cep))) + (multiple-value-bind (status body) + (request client (concatenate 'string "/" number)) + (case status + (404 (error 'cep-not-found + :name number + :message (format nil "CEP ~a does not exist in the DNE database" + number))) + (400 (error 'invalid-cep + :message (api-message body (format nil "CEP ~a rejected" number)))) + (t (address-from-json (parse-json-object body))))))) + +(defun chunk-list (list size) + "Split LIST into consecutive lists of at most SIZE elements." + (let ((rest list) + (chunks '())) + (loop while rest + do (push (loop repeat size + while rest + collect (pop rest)) + chunks)) + (nreverse chunks))) + +(defun fit-length (list count) + "Pad LIST with NILs, or truncate it, so that it has exactly COUNT elements." + (let ((size (length list))) + (cond ((= size count) list) + ((> size count) (subseq list 0 count)) + (t (append list (make-list (- count size) :initial-element nil)))))) + +(defun lookup-chunk (client ceps) + "Resolve at most `+max-batch+' CEPs in a single request. + +A blank CSV row means \"not found\": the API fills only the cep column and +leaves the rest empty, precisely so it does not misalign whoever is consuming +the batch in a spreadsheet. + +The API guarantees one row per requested CEP. Should that ever fail to hold — +a proxy truncating, a cut response — the result is padded to the input length +rather than returned short, because a shifted list silently pairs the wrong +address with the wrong CEP." + (let ((path (format nil "/csv?ceps=~{~a~^%2C~}" (mapcar #'url-encode ceps)))) + (multiple-value-bind (status body) (request client path) + (declare (ignore status)) + (let* ((rows (parse-csv (body-text body))) + (header (first rows)) + (addresses (loop for row in (rest rows) + for table = (csv-row-table header row) + collect (when (plusp (length (string-trim " " + (json-string table "localidade")))) + (address-from-json table))))) + (fit-length addresses (length ceps)))))) + +(defun lookup-many (ceps &key (client *client*)) + "Look up many CEPs in one batch. + +Returns a list of the same length and in the same order as CEPS. A CEP that +does not exist becomes NIL at its position — it does not vanish from the list, +and it does not signal. That is the right difference from `lookup': in a batch +of a thousand, one bad CEP must not cost the other nine hundred and +ninety-nine. A malformed CEP becomes NIL for the same reason; validate with +`normalize-cep' first if you need to know which one it was. + +Input is chunked into blocks of 500, the API's limit, automatically. + +Beware: the batch carries no coordinate. The endpoint behind it is CSV, and +the CSV has no geo column. Every `address' returned here has `address-geo' of +NIL, including for CEPs that do have one. Need the coordinate? Use `lookup', +one at a time." + (loop for chunk in (chunk-list ceps +max-batch+) + append (lookup-chunk client chunk))) + +(defun health (&key (client *client*)) + "Query GET /health: does the API answer, and with which database. + +Does not signal for an API reporting itself degraded — that arrives in +`health-status', and checking health is exactly when you want the diagnosis +rather than a condition. Network failures still signal." + (multiple-value-bind (status body) + (request client "/health" :accepted-status '(200 503)) + (declare (ignore status)) + (health-from-json (parse-json-object body)))) diff --git a/src/csv.lisp b/src/csv.lisp new file mode 100644 index 0000000..4c6297b --- /dev/null +++ b/src/csv.lisp @@ -0,0 +1,60 @@ +(in-package #:cepis) + +(defun parse-csv (text) + "Parse TEXT as RFC 4180 CSV and return a list of rows, each a list of strings. + +Values may be double-quoted, in which case they may contain commas, newlines +and doubled quotes; that is why the batch endpoint cannot be read by splitting +on commas. A byte order mark and CRLF line endings are both tolerated." + (let ((rows '()) + (row '()) + (buffer (make-string-output-stream)) + (in-quotes nil) + (dirty nil) + (index 0) + (end (length text))) + (labels ((flush-field () + (push (get-output-stream-string buffer) row)) + (flush-row () + (flush-field) + (push (nreverse row) rows) + (setf row '() + dirty nil))) + (when (and (plusp end) (char= (char text 0) (code-char #xFEFF))) + (incf index)) + (loop while (< index end) + do (let ((character (char text index))) + (cond (in-quotes + (cond ((not (char= character #\")) + (write-char character buffer)) + ((and (< (1+ index) end) (char= (char text (1+ index)) #\")) + (write-char #\" buffer) + (incf index)) + (t (setf in-quotes nil)))) + ((char= character #\") + (setf in-quotes t + dirty t)) + ((char= character #\,) + (flush-field) + (setf dirty t)) + ((char= character #\Newline) + (flush-row)) + ((char= character #\Return)) + (t + (write-char character buffer) + (setf dirty t)))) + (incf index)) + (when (or dirty row) + (flush-row)) + (nreverse rows)))) + +(defun csv-row-table (header row) + "Zip HEADER and ROW into a hash table, so a CSV row reads like a JSON object. + +Columns the row does not reach are filled with the empty string, which is what +the API sends for a field it does not have." + (let ((table (make-hash-table :test #'equal))) + (loop for column in header + for rest = row then (cdr rest) + do (setf (gethash column table) (or (car rest) ""))) + table)) diff --git a/src/errors.lisp b/src/errors.lisp new file mode 100644 index 0000000..525ac67 --- /dev/null +++ b/src/errors.lisp @@ -0,0 +1,73 @@ +(in-package #:cepis) + +(define-condition cepis-error (error) + ((message :initarg :message + :initform "" + :reader error-message + :documentation "The human-readable description of the failure.")) + (:report (lambda (condition stream) + (write-string (error-message condition) stream))) + (:documentation + "Base of every error this library signals. Handle it to catch any failure. + +Below it the split is by the decision the caller has to make, not by the HTTP +status that caused it. `invalid-cep' and `cep-not-found' are problems with the +request: retrying is pointless, the same CEP will fail again. `network-error', +`server-error' and `rate-limited' are problems with transport: retrying may +help, and the client already retried on its own before signalling any of +them.")) + +(define-condition invalid-cep (cepis-error parse-error) + () + (:documentation + "The CEP is not 8 digits. + +Deliberately also a `parse-error': turning a string into a CEP is a parse, and +code that already handles `parse-error' while validating input keeps working +without knowing this library exists. + +Usually signalled without a request ever being made — the client checks the +format before going to the network.")) + +(define-condition cep-not-found (cepis-error cell-error) + () + (:documentation + "The CEP is well-formed but does not exist in the DNE database. + +Also a `cell-error', which is the closest thing the standard has to a failed +key lookup: `cell-error-name' returns the CEP that was not found.")) + +(define-condition network-error (cepis-error) + () + (:documentation + "The request never completed: DNS, refused connection, timeout, TLS. + +Signalled only after every configured attempt has failed.")) + +(define-condition server-error (cepis-error) + ((status :initarg :status + :initform 0 + :reader server-error-status + :documentation "The HTTP status seen on the last attempt.")) + (:documentation "The API answered 5xx on every attempt.")) + +(define-condition rate-limited (cepis-error) + ((retry-after :initarg :retry-after + :initform nil + :reader rate-limited-retry-after + :documentation + "What the server asked for, in seconds, or NIL if it did not say.")) + (:documentation + "The API (or the edge in front of it) answered 429. + +The client already honoured `rate-limited-retry-after' across the attempts it +made; it is exposed here for callers who want to reschedule the work.")) + +(define-condition invalid-response (cepis-error) + () + (:documentation + "A success status came back with a body that cannot be parsed. + +In practice this means something between you and the API is answering instead +of it — a captive Wi-Fi portal, a corporate proxy, an HTML error page. Useful +as a diagnosis: the problem is not in your code.")) diff --git a/src/models.lisp b/src/models.lisp new file mode 100644 index 0000000..8905ae1 --- /dev/null +++ b/src/models.lisp @@ -0,0 +1,147 @@ +(in-package #:cepis) + +(defstruct (geo (:copier nil)) + "The CEP's coordinate, when the database has one. + +The point is the median of the coordinates of that CEP's addresses, not the +mean: one badly geocoded address 40 km away shifts a mean and does not move a +median. + +Always check `geo-precisao' before using the point for distance: + +- \"logradouro\": the point is a stretch of street. `geo-raio-m' lands around + 100-150 m. Good for maps and for distance. +- \"localidade\": the CEP is the whole municipality (a city-wide general CEP), + and the point is its centroid. `geo-raio-m' runs from 7 km to 40 km. + Computing shipping from this is wrong by tens of kilometres. + +`geo-raio-m' is the radius containing 90% of that CEP's addresses. It exists +precisely so that error cannot pass unnoticed. The slot is the JSON's `raio_m' +with Lisp's hyphenation." + (lat 0.0d0 :type double-float :read-only t) + (lon 0.0d0 :type double-float :read-only t) + (raio-m 0 :type integer :read-only t) + (precisao "" :type string :read-only t)) + +(defun geo-precise-p (geo) + "True when the coordinate points at a street, not at a municipality. + +Shorthand for (string= (geo-precisao geo) \"logradouro\"), which is the check +to make before using the point to measure distance." + (string= (geo-precisao geo) "logradouro")) + +(defstruct (address (:copier nil)) + "A CEP and everything the database knows about it. + +Fields the database does not have for that CEP come back as empty strings, +never NIL — that is what the API returns, and changing it here would create a +difference between reading the JSON and reading this library. + +`address-geo' is the exception: it is NIL when there is no coordinate. There +the difference is real, because the API omits the whole field in that case +(about 43% of CEPs) rather than sending null. + +`address-raw' holds the response exactly as it arrived, as the hash table the +JSON parser produced, so a field the API grows before this library is updated +is not lost." + (cep "" :type string :read-only t) + (logradouro "" :type string :read-only t) + (complemento "" :type string :read-only t) + (unidade "" :type string :read-only t) + (bairro "" :type string :read-only t) + (localidade "" :type string :read-only t) + (uf "" :type string :read-only t) + (estado "" :type string :read-only t) + (regiao "" :type string :read-only t) + (ibge "" :type string :read-only t) + (gia "" :type string :read-only t) + (ddd "" :type string :read-only t) + (siafi "" :type string :read-only t) + (geo nil :type (or null geo) :read-only t) + (raw nil :type (or null hash-table) :read-only t)) + +(defun address-formatted-cep (address) + "The CEP with its mask: \"01001-000\". + +The native contract always returns it unmasked; formatting is presentation, +and it lives here so it does not become a repeated format string in every +project that uses this." + (let ((cep (address-cep address))) + (if (= (length cep) 8) + (format nil "~a-~a" (subseq cep 0 5) (subseq cep 5)) + cep))) + +(defstruct (health (:copier nil)) + "The response of GET /health. + +Good for two things: checking that the API answers, and knowing which version +of the database is live. The DNE database changes every two weeks; +`health-dne' identifies it." + (status "" :type string :read-only t) + (dne "" :type string :read-only t) + (ceps 0 :type integer :read-only t) + (geo 0 :type integer :read-only t) + (base-gerada-em "" :type string :read-only t)) + +(defun health-ok-p (health) + "True when the API reports itself healthy." + (string= (health-status health) "ok")) + +(defun json-string (table key) + "The value of KEY in TABLE as a string, or \"\" when it is absent or not a scalar." + (let ((value (gethash key table))) + (cond ((stringp value) value) + ((integerp value) (format nil "~d" value)) + ((realp value) (princ-to-string value)) + (t "")))) + +(defun json-integer (table key) + "The value of KEY in TABLE as an integer, or 0 when it is absent or not a number." + (let ((value (gethash key table))) + (if (realp value) (round value) 0))) + +(defun geo-from-json (value) + "Build a `geo' from the parsed \"geo\" block, or NIL when it is absent or malformed. + +A malformed block yields NIL rather than propagating the error: it is not +worth losing the whole address over, since the rest of the response is still +useful." + (when (hash-table-p value) + (let ((lat (gethash "lat" value)) + (lon (gethash "lon" value)) + (raio-m (gethash "raio_m" value)) + (precisao (gethash "precisao" value))) + (when (and (realp lat) (realp lon) (realp raio-m) (stringp precisao)) + (make-geo :lat (coerce lat 'double-float) + :lon (coerce lon 'double-float) + :raio-m (round raio-m) + :precisao precisao))))) + +(defun address-from-json (data) + "Build an `address' from the hash table the JSON parser produced. + +Unknown fields are ignored during construction but preserved in +`address-raw'. A new field in the API therefore cannot break this library." + (make-address :cep (json-string data "cep") + :logradouro (json-string data "logradouro") + :complemento (json-string data "complemento") + :unidade (json-string data "unidade") + :bairro (json-string data "bairro") + :localidade (json-string data "localidade") + :uf (json-string data "uf") + :estado (json-string data "estado") + :regiao (json-string data "regiao") + :ibge (json-string data "ibge") + :gia (json-string data "gia") + :ddd (json-string data "ddd") + :siafi (json-string data "siafi") + :geo (geo-from-json (gethash "geo" data)) + :raw data)) + +(defun health-from-json (data) + "Build a `health' from the hash table the JSON parser produced." + (make-health :status (json-string data "status") + :dne (json-string data "dne") + :ceps (json-integer data "ceps") + :geo (json-integer data "geo") + :base-gerada-em (json-string data "base_gerada_em"))) diff --git a/src/package.lisp b/src/package.lisp new file mode 100644 index 0000000..20d6f32 --- /dev/null +++ b/src/package.lisp @@ -0,0 +1,100 @@ +(defpackage #:cepis + (:use #:common-lisp) + (:documentation + "Common Lisp client for the public CEP API at https://cep.is. + +Quick use — the functions take the client as a keyword argument, defaulting +to the shared client in `*client*': + + (cepis:lookup \"01001-000\") + +In an application, build a client once and pass it explicitly: + + (defvar *cep* (cepis:make-client :timeout 5 :total-timeout 15)) + (cepis:lookup \"01001000\" :client *cep*) + +Pointing at a local instance (the API repo brings one up with `just up'): + + (cepis:make-client :base-url \"http://localhost:8080\") + +Errors are conditions split by the decision the caller has to make — whether +retrying helps or not. Everything derives from `cepis-error': + + (handler-case (cepis:lookup cep) + (cepis:cep-not-found () :ask-again) + (cepis:cepis-error () :retry-later)) + +Note on field names: the API surface is English, but the data fields keep the +API's own Portuguese names (`logradouro', `bairro', `localidade'). What you +read in the JSON is what you access on the object; the only adaptation is +Lisp's hyphenation, so the JSON `raio_m' is the slot `raio-m', read with +`geo-raio-m'.") + (:export + #:+default-url+ + #:+max-batch+ + #:+version+ + + #:cepis-error + #:invalid-cep + #:cep-not-found + #:network-error + #:server-error + #:rate-limited + #:invalid-response + #:error-message + #:server-error-status + #:rate-limited-retry-after + + #:geo + #:geo-p + #:make-geo + #:geo-lat + #:geo-lon + #:geo-raio-m + #:geo-precisao + #:geo-precise-p + + #:address + #:address-p + #:make-address + #:address-cep + #:address-logradouro + #:address-complemento + #:address-unidade + #:address-bairro + #:address-localidade + #:address-uf + #:address-estado + #:address-regiao + #:address-ibge + #:address-gia + #:address-ddd + #:address-siafi + #:address-geo + #:address-raw + #:address-formatted-cep + + #:health + #:health-p + #:make-health + #:health-status + #:health-dne + #:health-ceps + #:health-geo + #:health-base-gerada-em + #:health-ok-p + + #:client + #:make-client + #:client-base-url + #:client-timeout + #:client-max-attempts + #:client-backoff-base + #:client-backoff-max + #:client-total-timeout + #:client-user-agent + #:*client* + + #:normalize-cep + #:lookup + #:lookup-many)) |