summaryrefslogtreecommitdiffstats
path: root/lib/cepis
diff options
context:
space:
mode:
authorMurilo Ijanc <[email protected]>2026-07-27 20:32:01 -0300
committerMurilo Ijanc <[email protected]>2026-07-27 20:32:01 -0300
commitb402de683eecef4c890081dd72edbcaf57f375e0 (patch)
tree13e184ad13b3cad394e5c84c25b48df3b2052781 /lib/cepis
parent36a0ddb01a4fcb8fb2fefd7c407ecca0e3e56e7c (diff)
downloadruby-84a6d224754979f76ce590e0175b9b939438a36f.tar.gz
Expose the band of a CEP that does not existHEADv0.2.0main
A CEP that fails a lookup is rarely a random number: it is someone who knows the city and guessed the digits, most often the -000 that 957 municipalities never received. The API now answers that 404 with an optional faixa naming the municipality those numbers belong to, so the caller can say "not found, but you seem to be looking at Areal/RJ" instead of just "not found". It stays an error. Faixa hangs off CEPNotFound and nothing about it promotes a nonexistent CEP into an address. Its cep_ini/cep_fim are the smallest and largest CEP that really exist there, not the published bounds — the DNE's own start for Areal is the CEP that just failed — and the band is sparse, which is what ceps is for; both facts are spelled out in the docs so nobody iterates the pair. Parsing is deliberately toothless: a missing, empty or malformed faixa, or a 404 body that is not JSON at all, all yield nil. Losing the consolation prize must never replace a clean not-found with a parse failure.
Diffstat (limited to 'lib/cepis')
-rw-r--r--lib/cepis/client.rb41
-rw-r--r--lib/cepis/errors.rb20
-rw-r--r--lib/cepis/models.rb85
-rw-r--r--lib/cepis/version.rb2
4 files changed, 144 insertions, 4 deletions
diff --git a/lib/cepis/client.rb b/lib/cepis/client.rb
index f451061..8480315 100644
--- a/lib/cepis/client.rb
+++ b/lib/cepis/client.rb
@@ -113,10 +113,15 @@ module Cepis
# message: the format already passed local validation, so the server knows
# something this client does not.
#
+ # A 404 may carry {CEPNotFound#faixa}: the municipality that owns the band
+ # of numbers the CEP fell into. It is still a 404 and still an exception —
+ # the context does not make a nonexistent CEP into an address. See {Faixa}.
+ #
# @param cep [String] masked or unmasked.
# @return [Address]
# @raise [InvalidCEP] the CEP is not 8 digits (no request is made).
- # @raise [CEPNotFound] well-formed, but not in the database.
+ # @raise [CEPNotFound] well-formed, but not in the database. Carries
+ # {CEPNotFound#faixa} when the API named a municipality for the band.
# @raise [RateLimited] 429 after every attempt.
# @raise [ServerError] 5xx after every attempt.
# @raise [NetworkError] the request never completed.
@@ -125,7 +130,7 @@ module Cepis
number = Cepis.normalize_cep(cep)
status, body = request("/#{number}")
- raise CEPNotFound, "CEP #{number} does not exist in the DNE database" if status == 404
+ raise not_found(number, body) if status == 404
raise InvalidCEP, error_message(body, "CEP #{number} rejected") if status == 400
Address.from_json(parse_json(body))
@@ -219,6 +224,38 @@ module Cepis
body.to_s.dup.force_encoding(Encoding::UTF_8).scrub
end
+ # The {CEPNotFound} for a 404, with the band read off the body when it is
+ # there.
+ #
+ # Every step of reading it is allowed to fail into `nil`: an absent
+ # `faixa` is the ordinary case (the API omits it, it never sends null),
+ # and a body that is not JSON at all is a proxy's doing, not the caller's.
+ # Neither may promote a definitive, well-understood not-found into an
+ # {InvalidResponse} — the reason the lookup failed would be replaced by
+ # the reason the consolation prize failed to parse.
+ def not_found(number, body)
+ faixa = begin
+ data = JSON.parse(decode(body))
+ data.is_a?(Hash) ? Faixa.from_json(data["faixa"]) : nil
+ rescue JSON::ParserError
+ nil
+ end
+
+ CEPNotFound.new(not_found_message(number, faixa), faixa: faixa)
+ end
+
+ # The message names the municipality when the API named one, because
+ # "does not exist" plus "the numbers around it are Areal/RJ" is what makes
+ # the log line diagnosable. The counts stay in the message too, so that
+ # nobody reads the two CEPs as the ends of a contiguous range.
+ def not_found_message(number, faixa)
+ base = "CEP #{number} does not exist in the DNE database"
+ return base if faixa.nil?
+
+ "#{base} (it falls in the band of #{faixa.localidade}/#{faixa.uf}, which has " \
+ "#{faixa.ceps} CEP(s) scattered between #{faixa.cep_ini} and #{faixa.cep_fim})"
+ end
+
def error_message(body, fallback)
data = JSON.parse(decode(body))
data.is_a?(Hash) && data["mensagem"] ? String(data["mensagem"]) : fallback
diff --git a/lib/cepis/errors.rb b/lib/cepis/errors.rb
index 7a15841..71b8a29 100644
--- a/lib/cepis/errors.rb
+++ b/lib/cepis/errors.rb
@@ -27,7 +27,25 @@ module Cepis
class InvalidCEP < Error; end
# The CEP is well-formed but does not exist in the DNE database.
- class CEPNotFound < Error; end
+ class CEPNotFound < Error
+ # The municipality that owns the band this CEP falls into, as a {Faixa},
+ # or `nil` when no municipality owns it — or when the API did not say.
+ #
+ # It is context for the failure, not a fallback address: the CEP asked for
+ # does not exist, and this only names the neighbourhood of numbers it
+ # would have belonged to. Useful because a CEP that fails is usually a
+ # guess by someone who knows the city, so the municipality is the one
+ # thing about it that tends to be right.
+ #
+ # Read {Faixa} before showing `cep_ini`/`cep_fim` to anyone: the band is
+ # sparse, and the pair is not a range of valid CEPs.
+ attr_reader :faixa
+
+ def initialize(message, faixa: nil)
+ super(message)
+ @faixa = faixa
+ end
+ end
# The request never completed: DNS, refused connection, timeout, TLS.
#
diff --git a/lib/cepis/models.rb b/lib/cepis/models.rb
index a0181ff..a80fe37 100644
--- a/lib/cepis/models.rb
+++ b/lib/cepis/models.rb
@@ -145,6 +145,91 @@ module Cepis
end
end
+ # The municipality that owns the band a **nonexistent** CEP falls into.
+ #
+ # It is context for an error, never an address: it arrives on the 404 of
+ # {Client#lookup}, hanging off {CEPNotFound#faixa}, and says "this CEP does
+ # not exist, but the numbers around it belong to Areal/RJ". The lookup still
+ # failed — nothing here turns it into a result.
+ #
+ # It is worth having because a CEP that fails is rarely a random number: it
+ # is usually someone who knows the city and guessed the digits. The classic
+ # guess is the `-000`, which 957 municipalities never received.
+ #
+ # **{#cep_ini} and {#cep_fim} are the smallest and the largest CEP that
+ # actually exist in the municipality, not the bounds the Correios publish.**
+ # The DNE's own start for Areal is `25845000` — exactly the CEP that just
+ # failed, which is why the published bounds would be useless here.
+ #
+ # **The band is sparse.** Areal's 118 CEPs are scattered across the ~4,900
+ # numbers between `25845001` and `25849899`. {#ceps} is there to say so. Do
+ # not present the pair as a range of valid CEPs, and do not iterate it: all
+ # but a fiftieth of it does not exist.
+ class Faixa
+ attr_reader :localidade, :uf, :estado, :regiao, :ibge, :cep_ini, :cep_fim, :ceps
+
+ def initialize(localidade:, uf:, estado:, regiao:, ibge:, cep_ini:, cep_fim:, ceps:)
+ @localidade = localidade
+ @uf = uf
+ @estado = estado
+ @regiao = regiao
+ @ibge = ibge
+ @cep_ini = cep_ini
+ @cep_fim = cep_fim
+ @ceps = ceps
+ freeze
+ end
+
+ # Build from the hash the API returned, or `nil` when the block is
+ # missing, empty or malformed.
+ #
+ # The API **omits** `faixa` — it never sends null — for a CEP falling in a
+ # band no municipality owns, so absence is the ordinary case and not an
+ # anomaly. Anything unreadable is treated as absence too: this is a bonus
+ # on top of a failure that has already happened, and it must never be the
+ # reason a clean not-found becomes something else.
+ def self.from_json(data)
+ return nil unless data.is_a?(Hash)
+
+ block = data.transform_keys(&:to_s)
+ localidade = String(block["localidade"] || "").strip
+ return nil if localidade.empty?
+
+ new(
+ localidade: localidade,
+ uf: String(block["uf"] || ""),
+ estado: String(block["estado"] || ""),
+ regiao: String(block["regiao"] || ""),
+ ibge: String(block["ibge"] || ""),
+ cep_ini: String(block["cep_ini"] || ""),
+ cep_fim: String(block["cep_fim"] || ""),
+ ceps: Integer(block["ceps"] || 0, exception: false) || 0
+ )
+ rescue TypeError, ArgumentError
+ nil
+ end
+
+ def to_h
+ {
+ localidade: @localidade, uf: @uf, estado: @estado, regiao: @regiao,
+ ibge: @ibge, cep_ini: @cep_ini, cep_fim: @cep_fim, ceps: @ceps
+ }
+ end
+
+ def ==(other)
+ other.is_a?(Faixa) && to_h == other.to_h
+ end
+ alias eql? ==
+
+ def hash
+ to_h.hash
+ end
+
+ def to_s
+ "#<Cepis::Faixa #{@localidade}/#{@uf} #{@cep_ini}-#{@cep_fim} #{@ceps} CEPs>"
+ end
+ end
+
# The response of `GET /health`.
#
# Good for two things: checking that the API answers, and knowing **which
diff --git a/lib/cepis/version.rb b/lib/cepis/version.rb
index cb88e06..ad38425 100644
--- a/lib/cepis/version.rb
+++ b/lib/cepis/version.rb
@@ -2,5 +2,5 @@
module Cepis
# Version of this library, as reported in the default `User-Agent`.
- VERSION = "0.1.0"
+ VERSION = "0.2.0"
end