File Coverage

File:blib/lib/Database/BI/Model/Geocode.pm
Coverage:89.6%

linestmtbrancondsubtimecode
1package Database::BI::Model::Geocode;
2
3# Resolve a location column to coordinates, once per distinct value.
4#
5# A dataset with places but no coordinates offers
6# loc=<column>, and the distinct values of that column are looked up by a
7# Geo::Coder::List chain: Geo::Coder::Free's local data first, then
8# OpenStreetMap's Nominatim service (Geo::Coder::OSM) for the places the local
9# data does not know.  This module is that lookup, kept out of the controller so
10# that the interesting part - which values are worth asking about, which were
11# asked already, and what happens to the rest - is testable without an HTTP
12# request, a data file, or a geocoder on the machine.
13#
14# The rule it is built around is that a dirty column is normal rather than an
15# error.  A place column holds street names, blank cells, and the odd bare number
16# that a column-offset mistake put there.  Two things stop that from ending a
17# request:
18#
19#   1. Every distinct value is put to the geocoder's own valid_location() before
20#      anything is looked up.  A value it refuses is counted, reported, and
21#      dropped: it never reaches a backend, so it cannot croak, and it is not
22#      counted as a lookup.
23#   2. The batch is made with on_error => 'undef', so a value the geocoder
24#      refuses later is a miss rather than a death.  Nothing is wrapped in an
25#      eval: a backend exception still propagates, exactly as it does from
26#      geocode() itself.
27#
28# Skipping is remembered rather than repeated.  An attempted-and-unresolved value,
29# so the next request over the same column plots what resolved,
30# reports the rest, and asks the geocoder nothing at all.
31
32
26
26
26
70832
29
229
use strict;
33
26
26
26
29
20
581
use warnings;
34
35
26
26
26
34
21
525
use Carp                        qw(croak carp);
36
26
26
26
183
33
121
use Database::BI::I18N ();
37
26
26
26
30
17
358
use Readonly;
38
26
26
26
42
44
279
use Scalar::Util                qw(blessed);
39
26
26
26
58
21
89
use Time::HiRes                 ();
40
26
26
26
37
9180
136
use Params::Get                 ();
41
26
26
26
33
9639
12156
use Params::Validate::Strict    qw(validate_strict);
42
43our $VERSION = '0.025.0';
44
45# The version of Geo::Coder::Free this module asks for: 0.46 added valid_location()
46# and on_error => 'undef', 0.47 added geocode_many(), and 0.48 added the
47# per-lookup read counts the lookups figure below reports.  This module asks for
48# all three rather than reimplementing the rule, the batch loop or the count it
49# exists to use.  The messages that name the floor are given this number rather
50# than spelling it out, so there is one place to change; a caller that pins
51# min_geocoder_version for a test gets its own number quoted back, which is the
52# floor it asked for.  t/recommended-versions.t holds the constant and the
53# Makefile.PL recommends entry to each other.
54Readonly my $MIN_GEOCODER_VERSION => '0.48';
55
56# The chain the lookups go through, and the online geocoder at its end.
57# Geo::Coder::List 0.39 records every geocoder it asks in log(), which is how a
58# lookup that reached Nominatim is told from one the local data answered, and
59# how a Nominatim that did not answer is told from a place it does not know.
60# These are named FLOOR rather than MIN_*VERSION: t/recommended-versions.t
61# reads the file's one $MIN_*VERSION as Geo::Coder::Free's floor, and the
62# messages that name these modules spell their numbers out instead.
63Readonly my $LIST_FLOOR      => '0.39';
64Readonly my $OSM_FLOOR       => '0.03';
65Readonly my $THROTTLED_FLOOR => '0.14';
66
67# Nominatim's usage policy: at most one request a second, from a client that
68# names itself.  The gap is kept by LWP::UserAgent::Throttled, which waits
69# before a request rather than refusing it, and the user agent is shared by
70# every lookup in the process, so two map pages opened together still keep it.
71Readonly my $NOMINATIM_HOST => 'nominatim.openstreetmap.org';
72Readonly my $NOMINATIM_GAP  => 1;
73
74# Geo::Coder::OSM 0.03 asks http://nominatim..., which answers with a redirect
75# to https: two requests a lookup, the second held a second by the throttle, and
76# the place name sent once in clear.  Its documented %SOURCES hook names this
77# source instead, and it is asked for by name.
78Readonly my $NOMINATIM_SOURCE => 'database-bi-https';
79Readonly my $NOMINATIM_URL    => "https://$NOMINATIM_HOST";
80Readonly my $ONLINE_TIMEOUT => 10;   # seconds; a service that has stopped answering must not hold a page
81Readonly my $USER_AGENT     => "Database-BI/$VERSION (+https://metacpan.org/dist/Database-BI)";
82
83# Geo::Coder::List's own cache (its L2), used when the caller gives none: one
84# CHI Memory cache for the process, so the answers outlive the object, which the
85# map page makes afresh for every request.  A place Nominatim found is then not
86# asked again while the process lives, whichever request needs it.  The map page
87# and script/bi-geocode pass a CHI File cache under model_dir instead, which
88# also outlives the process and is shared by every hypnotoad worker.
89Readonly my $CACHE_NAMESPACE => __PACKAGE__;
90Readonly my $CACHE_MAX_SIZE  => 4 * 1024 * 1024;     # bytes, for the process-wide default
91Readonly my $CACHE_DIR       => 'geocode-cache';     # under model_dir, for file_cache()
92
93# The default for map_geocode_max (section 6.2): new lookups allowed in one
94# request.  A crafted URL must not be able to turn one request into unbounded CPU.
95Readonly my $DEFAULT_MAX => 500;
96
97# The most characters of text place_text() lets be added to each place (the
98# map page's loc_text=, bi-geocode's --text).
99Readonly our $PLACE_TEXT_MAX => 200;
100
101# The model store's shared place cache.  A place name means the same place
102# whichever file's column holds it, so one answer serves every dataset: the
103# second file that names Ramsgate plots it without asking the geocoder.  The
104# key cannot collide with a per-dataset entry, which always starts with a spec
105# scheme (path:, table:, url: or redis:).
106Readonly my $SHARED_CACHE_KEY => 'shared';
107
108# ---------------------------------------------------------------------------
109# I18N message dictionary.
110# Every user-visible string this module produces is keyed here.  The keys are
111# for the conditions it names - geocoder missing, the
112# location column not being in the view, skipped rows, the cap, and no openaddr
113# data - so the controller and this module describe the same conditions with the
114# same words; the rest are this module's own argument and interface errors, which
115# section 11 does not name because they are not states a page reaches.  Pass an
116# object that responds to maketext($key, @args) as the "i18n" constructor
117# argument to override them; it is called in preference to this table.
118# ---------------------------------------------------------------------------
119
120Readonly our %MESSAGES => (
121        'error_map_geocoder_missing'            => 'Geocoding a location column needs Geo::Coder::Free %s or later, and %s',
122        'error_map_geocoder_list_missing'       => 'Geocoding a location column needs Geo::Coder::List 0.39 or later, and %s',
123        'error_map_loc_column'                  => 'Column "%s" is not in this dataset, so there is nothing to geocode',
124        'error_geocoder_interface'              => 'Geocode: the geocoder must provide %s; Geo::Coder::Free %s or later does',
125        'error_max_invalid'                     => 'Geocode: option "max" must be a positive integer, not "%s"',
126        'error_online_max_invalid'              => 'Geocode: option "online_max" must be a positive integer, not "%s"',
127        'error_cache_dir'                       => 'Geocode: the geocode cache needs a directory that exists, not "%s"',
128        'error_cache_interface'                 => 'Geocode: option "cache" must be a hashref or an object with get() and set(), not a %s',
129        'error_values_arrayref'                 => 'Geocode: the values must be an arrayref, not "%s"',
130        'error_rows_arrayref'                   => 'Geocode: the rows must be an arrayref, not "%s"',
131        'error_column_required'                 => 'Geocode: the column name is required',
132        'warn_map_rows_skipped'                 => 'Plotted %d of %d rows; %d could not be plotted: %s',
133        # The reasons warn_map_rows_skipped gives, those that apply, joined with ', '.
134        'warn_map_rows_why_empty'               => '%d with no place in the row',
135        'warn_map_rows_why_refused'             => '%d whose place is a bare number, not a place name',
136        'warn_map_rows_why_not_found'           => '%d whose place was not found',
137        'warn_map_rows_why_later'               => '%d whose place has not been looked up yet',
138        'warn_map_geocode_capped'               => 'Geocoded %d of the %d places that had not been looked up before; the rest are untouched, so open the data source again or run the geocode warm script to finish them',
139        'warn_map_geocoder_unavailable_data'    => 'The geocoder has no OpenAddresses data configured (OPENADDR_HOME), so places resolve only as coarsely as the bundled MaxMind data allows',
140        'warn_map_geocoder_local_only'          => 'Places the local data does not know were not looked up online, which needs Geo::Coder::OSM 0.03 and LWP::UserAgent::Throttled 0.14 or later',
141        'warn_map_geocoder_online_failed'       => 'OpenStreetMap did not answer (%s), so %d places the local data does not know are left to try again later',
142);
143
144# _fmt($key [, @args]) -> $string
145#
146# Package-level i18n formatter, for the messages new() raises before the object
147# exists.  Instance methods use _msg() so a caller-supplied i18n object can
148# override the built-in strings.
149sub _fmt {
150
314
3429
        my ($key, @args) = @_;
151
152
314
409
        my $tmpl = Database::BI::I18N::text(__PACKAGE__, \%MESSAGES, $key)
153                 // "Internal error: unknown message key '" . ($key // 'undef') . "'";
154
155
314
1754
        return @args ? sprintf($tmpl, @args) : $tmpl;
156}
157
158# _msg($self, $key [, @args]) -> $string
159sub _msg {
160
228
189
        my ($self, $key, @args) = @_;
161
162
228
203
        if (my $i18n = $self->{'_i18n'}) {
163
4
5
                return $i18n->maketext($key, @args);
164        }
165
166
224
209
        return _fmt($key, @args);
167}
168
169# _message($self, $key [, @args]) -> { key => $key, text => $text }
170#
171# The form a message is reported in: the key lets a caller re-render it through
172# its own i18n, and the text is what to show when it does not.
173sub _message {
174
111
139
        my ($self, $key, @args) = @_;
175
176
111
134
        return { 'key' => $key, 'text' => $self->_msg($key, @args) };
177}
178
179=encoding utf8
180
181 - 600
=head1 NAME

Database::BI::Model::Geocode - Resolve a location column to coordinates, once per distinct value

=head1 VERSION

0.025.0

=head1 SYNOPSIS

B<Geocode a table's place column and build map markers:>

    use Database::BI::Model::Geocode;

    my $geocode = Database::BI::Model::Geocode->new();
    my $result  = $geocode->resolve_column($rows, 'city');

    for my $marker (@{ $result->{'markers'} }) {
        printf "  %s: lat=%.4f lon=%.4f (%d rows)\n",
            $marker->{'value'}, $marker->{'lat'}, $marker->{'lon'},
            $marker->{'rows'};
    }

    my $c = $result->{'counts'};
    printf "Plotted %d of %d rows (%d skipped, %d unresolved)\n",
        $c->{'plotted'}, $c->{'rows'}, $c->{'skipped'}, $c->{'unresolved'};

B<Re-use remembered answers so the next request costs nothing:>

    # Load what was stored from a previous run.
    my $spec   = 'table:sales';
    my $models = decode_json(Mojo::File->new('.bi/models.json')->slurp);
    my $cache  = Database::BI::Model::Geocode->cache_from_models($models, $spec);

    # Resolve; cached values are used without asking the geocoder.
    my $result = $geocode->resolve_column($rows, 'city', cache => $cache);

    # Save the updated cache back to the models file.
    my $updated = Database::BI::Model::Geocode->models_with_cache(
        $models, $spec, $result->{'cache'},
        backend => $result->{'backend'},
        built   => '2026-10-18T12:00:00',
    );
    Mojo::File->new('.bi/models.json')->spew(encode_json($updated));

B<Warm the cache for a whole column without needing rows:>

    # Extract unique city values from your own data.
    my @cities = do { my %s; grep { !$s{$_}++ } map { $_->{'city'} } @{ $rows } };

    my $result = $geocode->resolve_values(\@cities,
        cache  => $cache,
        region => 'GB',
        max    => 1000,
    );

    printf "Resolved %d / %d new places\n",
        $result->{'counts'}{'resolved'}, $result->{'counts'}{'attempted'};

B<Ask whether the geocoder is available before offering it in the UI:>

    my $geocode = Database::BI::Model::Geocode->new();
    my ($ok, $why) = $geocode->geocoder_available();

    unless ($ok) {
        carp "Map panel disabled: $why";
    }

B<Inject a test double so geocoding works without a real geocoder:>

    package MyGeocoderStub;
    sub new            { bless {}, shift }
    sub valid_location { my ($self, $v) = @_; $v && $v !~ /\A\d+\z/ }
    sub geocode_many   {
        my ($self, $places, %opts) = @_;
        return { 'London' => { lat => 51.5, long => -0.12, database => 'stub' } };
    }

    my $geocode = Database::BI::Model::Geocode->new(geocoder => MyGeocoderStub->new);
    my $result  = $geocode->resolve_column($rows, 'city');

=head1 DESCRIPTION

The geocoder is a L<Geo::Coder::List> chain:

    Geo::Coder::List->new()
        ->push(Geo::Coder::Free->new())   # the local data
        ->push(Geo::Coder::OSM->new());   # OpenStreetMap's Nominatim

C<Geo::Coder::Free> answers from data on this machine.  A place it does not know
is asked of Nominatim, over the network, through an L<LWP::UserAgent::Throttled>
that keeps Nominatim's usage policy: one request a second, from a client that
names itself (C<Database-BI/I<version>>), with a ten-second time-out.  The user
agent is shared by every lookup in the process, so the gap holds across
requests.  Nominatim is told the place name and nothing else.

A table column holds something less tidy than a place name: values repeated
thousands of times, blank cells, numbers that drifted in from an adjacent
column.  This module does the three things the column then needs.

=over 4

=item B<Ask once per distinct value.>

The column is reduced to a set before any lookup happens.  A repeated city name
costs one lookup, so a 100,000-row file with a dozen cities costs twelve lookups,
not 100,000.

=item B<Refuse a value that is not a location before any backend sees it.>

C<< $geocoder->valid_location($value) >> is the gate the geocoder's own guard
applies before looking anything up.  This module asks the same question first, so
a pure-digit string (a row number that ended up in the wrong column), an empty
cell, or a Perl reference is counted and reported as skipped rather than sent to
a backend that would reject it anyway.

=item B<Look the rest up without letting one value end the batch.>

Each place goes down a C<Geo::Coder::List> on its own: the local data, then
Nominatim when it is in the chain.  With the local data alone the list holds
only C<Geo::Coder::Free>, which is given the C<region> hint (C<Geo::Coder::OSM>
would put it in the Nominatim query).  Either way the list's cache answers what
it has found before.  C<Geo::Coder::List> catches what a geocoder throws and
asks the next one, so a throw does not end the request; a place whose lookup
threw and found nothing is held (put in C<not_attempted>, not cached), because "not found" is
remembered for good and an error is not an answer.

An injected C<geocoder> is asked for one C<geocode_many()> batch instead,
requested with C<< on_error => 'undef' >>.  A value it refuses after the
pre-filter is a miss; a backend that throws is still a throw, because nothing
here wraps it in an C<eval>.

=item B<Tell a Nominatim that failed from a place it does not know.>

C<Geo::Coder::OSM> answers nothing in both cases.  The chain's log says whether
Nominatim was asked, and its last response says whether it answered.  A place
it failed on is held, not remembered as not found, and Nominatim is not asked
again in that request: the rest are asked of the local data alone, and the ones
it does not know are held too.  The page is told Nominatim's status line and how
many places wait, never which.

=back

The counts the module returns add up, always.

    skipped + cached + attempted + not_attempted  ==  distinct
    resolved + unresolved                         ==  cached + attempted

C<lookups> is the number of places that reached a geocoder rather than the
chain's own cache.  For an injected geocoder it is the number that geocoder
reports for the batch, which C<Geo::Coder::Free> 0.48 and later keeps lower than
C<attempted> when a value is answered from a warm process cache.  It never exceeds
C<attempted>.  C<online> is how many of them were asked of Nominatim.

=head2 The cache

A cache entry is a C<[lat, lon]> arrayref for a place that resolved, or the
scalar C<0> for a place that was looked up and not found.  That C<0> sentinel
prevents a column of unresolvable values from being retried on every page
request.

The cache is passed per call and returned per call.  The caller's hashref is
never modified: a request that dies part way through cannot leave a half-written
cache behind.  The controller is responsible for persisting the returned cache,
which keeps the C<model_dir>-inside-C<data_dir> guard in the one place that
already owns it.

A previously stored cache is used even when the geocoder is not available.
Places already resolved continue to be plotted; only new lookups are unavailable.

=head2 Without the geocoder

C<Geo::Coder::Free> and C<Geo::Coder::List> are recommended dependencies, not
required ones.  They are loaded the first time they are needed, not at compile
time.  C<Geo::Coder::OSM> and C<LWP::UserAgent::Throttled> are recommended too;
without them the chain is the local data alone, and a request with places it
did not know says so (C<warn_map_geocoder_local_only>).  When
C<Geo::Coder::Free> or C<Geo::Coder::List> is absent or older than its minimum
version:

=over 4

=item *

C<< $geocode->geocoder_available() >> returns C<(0, $reason)>.

=item *

C<resolve_column> and C<resolve_values> still return a complete result: all
values are placed in C<not_attempted>, cached answers are still plotted, and
the C<error_map_geocoder_missing> message explains the situation.

=item *

Nothing croaks.  The page renders with whatever the cache already holds.

=back

=head1 CONSTRUCTOR

=head2 new

    my $geocode = Database::BI::Model::Geocode->new(%options);
    my $geocode = Database::BI::Model::Geocode->new(\%options);  # hashref also accepted

Create a new resolver.  Accepts a flat key/value list or a hashref; both forms
are handled by C<Params::Get>.

=head3 API SPECIFICATION

=head4 INPUT

    geocoder             => object,   # optional; duck-typed: must provide valid_location() and geocode_many()
    openaddr             => string,   # optional; path to OpenAddresses data (default: $ENV{OPENADDR_HOME})
    min_geocoder_version => string,   # optional; minimum version to accept (default: '0.48')
    i18n                 => object,   # optional; must implement maketext($key, @args)
    online               => boolean,  # optional; ask Nominatim about places the local data does not know (default: 1)
    online_max           => positive integer, # optional; places asked of Nominatim per call (default: no limit)
    cache                => hashref|object, # optional; Geo::Coder::List's cache (a hashref, or an object with get() and set(), such as file_cache()); default: files under cache_dir (below)
    cache_dir            => string,   # optional; the directory for that cache, read through Object::Configure (below)
    model_dir            => string,   # optional; the default cache_dir is <model_dir>/geocode-cache
    config               => hashref,  # optional; the application's config, for its cache_dir (default: database_bi.conf is read)
    home                 => string,   # optional; the folder a relative cache_dir in config is under

Without C<cache>, the answers are kept as files (a L<CHI> C<File> cache, with
a copy in memory) in the first directory that is set of:

=over 4

=item 1. C<cache_dir> from L<Object::Configure>: its config files, then the
environment variable C<Database__BI__Model__Geocode__cache_dir>; the
C<cache_dir> argument is what those fall back on;

=item 2. C<$ENV{CACHEDIR}>;

=item 3. C<$ENV{CACHE_DIR}>;

=item 4. C<cache_dir> in F<database_bi.conf> (C<config>, or the file itself
when C<config> is not given);

=item 5. F<E<lt>model_dirE<gt>/geocode-cache>, when C<model_dir> is given.

=back

With none of them, the answers are kept in one CHI C<Memory> cache per process.
L<Database::BI::CacheDir> makes the choice; the directory chosen is
C<< $geocode->{cache_dir} >>.  Several caches may share a directory: each keeps
its own namespace in it.

C<geocoder> is the injection seam for tests.  An injected geocoder is used
exactly as given: it is not version-checked, so any object that responds to
C<valid_location()> and C<geocode_many()> works.  A geocoder that fails either
C<can()> check causes an immediate C<croak> (C<error_geocoder_interface>), not
a silent degradation.

C<openaddr> overrides C<$ENV{OPENADDR_HOME}>.  It is forwarded to
C<< Geo::Coder::Free->new(openaddr => ...) >>.  When it is absent and the
environment variable is not set, the geocoder uses its built-in MaxMind data
only, which resolves city and country names but not street addresses.
C<warn_map_geocoder_unavailable_data> is emitted in that case.

C<min_geocoder_version> lets the caller pin the floor, or a test simulate
a too-old installation on a machine that has the current version.

C<< online => 0 >> keeps every lookup on this machine: a place the local data
does not know is then not sent to OpenStreetMap.  C<online_max> caps how many
places one C<resolve_*()> call asks Nominatim about.  At one a second, it is
roughly how long the call can wait for Nominatim; the places past it go into
C<not_attempted> uncached, so the next call asks them.  An injected
C<geocoder> is used as it is, and these two do not apply to it.

C<i18n> is an optional object whose C<maketext($key, @args)> method is called
in place of the built-in C<%MESSAGES> table.  The key is one of the constants
defined in C<%MESSAGES>; the args are the same positional values C<sprintf>
would receive.

=head4 OUTPUT

Returns C<$self>.

Croaks with C<error_geocoder_interface> if the injected C<geocoder> does not
provide both C<valid_location()> and C<geocode_many()>, and with
C<error_online_max_invalid> if C<online_max> is not a positive integer.

Never croaks because the geocoder module is absent or too old: that is a
runtime condition reported by C<geocoder_available()>, not a constructor error.

=head1 SUBROUTINES/METHODS

=head2 resolve_column

    my $result = $geocode->resolve_column(\@rows, $column_name, %options);

Resolve one named column of a table.  C<\@rows> is an arrayref of hashrefs
(the records from the data pipeline), and C<$column_name> is the key to look
up in each row.

This is the main entry point for the map controller.  It runs the same
resolution as L</resolve_values>, then adds per-marker row counts and the
C<markers> list that a map rendering loop needs.

=head3 API SPECIFICATION

=head4 INPUT

    \@rows          => arrayref of hashrefs, required
    $column_name    => non-empty string, required
    cache    => hashref,            # optional; { value => [lat, lon] | 0 }
    region   => two-letter string,  # optional; country hint for the geocoder (e.g. 'GB')
    max      => positive integer,   # optional; max new lookups; default 500
    lookup   => 0 | 1,              # optional; 0 asks nothing and lists what it would ask; default 1

C<\@rows> is the full record set as returned by the pipeline.  Rows that are
not hashrefs produce an C<undef> cell, which is classified as skipped.

C<$column_name> must be a non-empty string.  It is used as a hash key; it is
not validated against a schema, so a column name with spaces or special
characters is accepted if the data uses one.

C<cache> holds the already-known answers for this column.  Entries are either
a C<[lat, lon]> arrayref (resolved) or C<0> (looked up and not found).  The
caller's hashref is never modified; the returned C<cache> key holds the
updated copy.

C<region> is passed straight through to the geocoder as a country hint.  It
is not derived from the Accept-Language header, because a language is not a
country.

C<max> is counted in new lookups, not rows.  A cached answer costs nothing
and does not count toward it.  Values held back by the cap go into
C<not_attempted> and are not stored in the cache, so the next request picks
them up.

C<lookup =E<gt> 0> plots from C<cache> alone and asks the geocoder nothing.
The places it would have asked (up to C<max>, in first-seen order) are returned
in C<pending>, and are counted in C<not_attempted> meanwhile.  A caller can then
look them up one at a time with L</resolve_values>, saving each answer as it
comes, which is how the map page shows its progress and can be cancelled.  The
geocoder is still loaded, because its rule decides which values are places.

=head4 OUTPUT

Returns a hashref:

    {
        available     => 1 | 0,
        points        => { $value => { lat => $n, lon => $n, rows => $n, first_row => $n, backend? => $s } },
        markers       => [ { value => $s, lat => $n, lon => $n, rows => $n, first_row => $n } ],
        counts        => {
            rows          => $n,   # total rows in \@rows
            plotted       => $n,   # rows whose value resolved to a point
            unusable      => $n,   # rows - plotted
            distinct      => $n,   # unique values seen
            skipped       => $n,   # refused before any lookup (empty, ref, digit-only)
            cached        => $n,   # found in the cache (resolved or not)
            attempted     => $n,   # sent to the geocoder this request
            lookups       => $n,   # lookups the geocoder reports (may be < attempted)
            online        => $n,   # of those, places asked of Nominatim
            resolved      => $n,   # total with a position (cache + new)
            unresolved    => $n,   # total without (cache + new)
            not_attempted => $n,   # held back by a cap, by a failed lookup, or because no geocoder
        },
        skipped       => [ $value, ... ],   # values refused before lookup
        unresolved    => [ $value, ... ],   # values tried (now or before) and not found
        not_attempted => [ $value, ... ],   # held back by the cap
        pending       => [ $value, ... ],   # with lookup => 0: what would have been asked; else empty
        messages      => [ { key => $k, text => $t }, ... ],
        cache         => { $value => [lat, lon] | 0 },   # updated copy; never the caller's hashref
        backends      => { $backend_name => $count },
        backend       => $backend_name | undef,          # undef when nothing resolved
        capped        => 0 | 1,
    }

C<points> holds one entry per value that produced a position, whether the
position came from the cache or from this request.  C<markers> is the same
data in first-seen row order, which reads better on a map than alphabetical
order.

C<backend> on a point entry is set only for values looked up in this request;
cached values do not carry one because the cache stores a position, not which
database gave it.  The top-level C<backend> is the name of the backend that
answered the most lookups this request.

The count invariant always holds:

    skipped + cached + attempted + not_attempted  ==  distinct

=head3 MESSAGES

    error_rows_arrayref                -- \@rows is not an arrayref
    error_column_required              -- $column_name is empty or undef
    error_map_loc_column               -- column not found in any row
    error_map_geocoder_missing         -- no geocoder, or version below the floor
    error_map_geocoder_list_missing    -- Geo::Coder::List absent or too old
    warn_map_rows_skipped              -- some rows could not be plotted, and why
    warn_map_rows_why_*                -- the reasons it names (not messages of their own)
    warn_map_geocode_capped            -- max or online_max held some values back
    warn_map_geocoder_unavailable_data -- local data only, and OPENADDR_HOME not set
    warn_map_geocoder_local_only       -- no Geo::Coder::OSM, and places were not found
    warn_map_geocoder_online_failed    -- Nominatim did not answer; places held

=head3 EXAMPLE

    my $cache   = Database::BI::Model::Geocode->cache_from_models($models, $spec);
    my $result  = $geocode->resolve_column($rows, 'city',
        cache  => $cache,
        region => 'GB',
        max    => 200,
    );

    if ($result->{'capped'}) {
        carp "Some cities were not looked up; load the page again to finish them.";
    }

    for my $m (@{ $result->{'markers'} }) {
        printf "[%.4f, %.4f]  %s (%d rows)\n",
            $m->{'lat'}, $m->{'lon'}, $m->{'value'}, $m->{'rows'};
    }

=cut
601
602sub new {
603        # Strategy: normalise the argument list with Params::Get so a caller may pass
604        # a hashref or a flat list interchangeably, then validate before using
605        # anything.  An injected geocoder is checked for the methods this module asks
606        # of one, rather than failing half way down a column.
607
246
873868
        my $class = shift;
608
246
507
        my $raw   = Params::Get::get_params(undef, \@_) // {};
609
610
246
3061
        my $args = validate_strict(
611                schema => {
612                        geocoder             => { type => 'object',  optional => 1, default => undef },
613                        openaddr             => { type => 'string',  optional => 1, default => undef },
614                        min_geocoder_version => { type => 'string',  optional => 1, default => $MIN_GEOCODER_VERSION },
615                        i18n                 => { type => 'object',  optional => 1, default => undef, can => 'maketext' },
616                        online               => { type => 'scalar',  optional => 1, default => 1 },
617                        online_max           => { type => 'scalar',  optional => 1, default => undef },
618                        cache                => { type => 'object|hashref', optional => 1, default => undef },
619                        cache_dir            => { type => 'string',  optional => 1, default => undef },
620                        model_dir            => { type => 'string',  optional => 1, default => undef },
621                        config               => { type => 'hashref', optional => 1, default => undef },
622                        home                 => { type => 'string',  optional => 1, default => undef },
623                },
624                input => $raw,
625        );
626
627        # Geo::Coder::List calls get() and set() on its cache inside an eval and
628        # carries on when they fail, so an object without them would cache nothing
629        # and say so only in a warning per place.  It is refused here instead.
630
239
49922
        my $cache = $args->{'cache'};
631
239
418
        croak(_fmt('error_cache_interface', ref($cache)))
632                if blessed($cache) && !($cache->can('get') && $cache->can('set'));
633
634        # Without a cache object, the answers are kept on disc in the directory
635        # Database::BI::CacheDir chooses (Object::Configure, CACHEDIR, CACHE_DIR,
636        # database_bi.conf, then <model_dir>/geocode-cache).  With none of those,
637        # they are kept in this process's memory, as before.
638
238
162
        my $cache_dir;
639
238
244
        unless (defined $cache) {
640
232
1471
                require Database::BI::CacheDir;
641                $cache_dir = Database::BI::CacheDir::resolve(
642                        class   => $class,
643                        params  => $args,
644                        (defined($args->{'config'}) ? (config => $args->{'config'}, home => $args->{'home'}) : ()),
645                        default => (defined($args->{'model_dir'}) && length($args->{'model_dir'})
646
232
706
                                ? _catdir($args->{'model_dir'}, $CACHE_DIR) : undef),
647                );
648
232
290
                $cache = _file_cache_at($cache_dir) if defined $cache_dir;
649        }
650
651        # A cap that is not a positive integer is refused, as max is in _options:
652        # defaulting it would quietly lift the limit a caller set to keep a page quick.
653
238
80421
        my $online_max = $args->{'online_max'};
654
238
422
        croak(_fmt('error_online_max_invalid', $online_max))
655                if defined($online_max) && !(($online_max =~ /\A\d+\z/) && ($online_max > 0));
656
657        my $self = bless {
658                '_i18n'       => $args->{'i18n'},
659                'openaddr'    => $args->{'openaddr'} // $ENV{'OPENADDR_HOME'},
660                'min_version' => $args->{'min_geocoder_version'},
661
237
970
                'online'      => $args->{'online'} ? 1 : 0,
662                'online_max'  => $online_max,
663                'cache'       => $cache,
664                'cache_dir'   => $cache_dir,
665        }, $class;
666
667
237
351
        if (my $geocoder = $args->{'geocoder'}) {
668
178
251
                $self->_check_interface($geocoder);
669
167
188
                $self->{'_geocoder'} = $geocoder;
670        }
671
672
226
543
        return $self;
673}
674
675# _check_interface($geocoder)
676#
677# A geocoder has to answer the two questions this module asks of one.  Checked
678# here rather than half way through a column.
679sub _check_interface {
680
183
218
        my ($self, $geocoder) = @_;
681
682
183
146
        for my $method (qw(valid_location geocode_many)) {
683
358
1266
                next if $geocoder->can($method);
684
14
217
                croak(_fmt('error_geocoder_interface', $method . '()', $MIN_GEOCODER_VERSION));
685        }
686
687
169
431
        return 1;
688}
689
690# _load_geocoder() -> geocoder object, or undef when there is not one to be had
691#
692# The real geocoder, loaded on demand so the application installs, starts and
693# tests without it: a Geo::Coder::List holding Geo::Coder::Free, and then
694# Geo::Coder::OSM when online lookups are wanted and it can be had.  Returns
695# nothing when Geo::Coder::Free or Geo::Coder::List is absent, older than its
696# floor, will not load, or builds nothing, and records which it was for the
697# message.  Geo::Coder::OSM is not needed: without it the chain is the local
698# data alone, and a page whose places it does not know says why.
699sub _load_geocoder {
700
28
28
        my $self = shift;
701
702
28
23
        my $ok = eval {
703
28
440
                require Geo::Coder::Free;
704
7
46
                Geo::Coder::Free->VERSION($self->{'min_version'});
705
6
7
                1;
706        };
707
708
28
542
        unless ($ok) {
709
22
22
                my $error = $@;
710
711
22
60
                $self->{'_unavailable'} =
712                        ($error =~ /Can't locate/)                  ? 'it is not installed'
713                        : (defined($Geo::Coder::Free::VERSION)          ? "$Geo::Coder::Free::VERSION is installed"
714                        : 'it could not be loaded');
715
716
22
52
                return;
717        }
718
719
6
5
        my $have_list = eval {
720
6
11
                require Geo::Coder::List;
721
5
17
                Geo::Coder::List->VERSION($LIST_FLOOR);
722
5
23
                1;
723        };
724
725
6
14
        unless ($have_list) {
726
1
1
                my $error = $@;
727
728
1
2
                $self->{'_unavailable_key'} = 'error_map_geocoder_list_missing';
729
1
4
                $self->{'_unavailable'} =
730                        ($error =~ /Can't locate/)                  ? 'it is not installed'
731                        : (defined($Geo::Coder::List::VERSION)          ? "$Geo::Coder::List::VERSION is installed"
732                        : 'it could not be loaded');
733
734
1
2
                return;
735        }
736
737        my $local = Geo::Coder::Free->new(
738
5
13
                $self->{'openaddr'} ? (openaddr => $self->{'openaddr'}) : ()
739        );
740
741
4
26
        unless ($local) {
742                # It is installed, so the message must not fall back on saying that it is not.
743
1
3
                $self->{'_unavailable'} = 'it could not be started';
744
1
3
                return;
745        }
746
747        # Two lists over one cache: the local data alone, which is asked with the
748        # region hint (Geo::Coder::OSM would put it in the Nominatim query), and the
749        # whole chain when Nominatim is wanted.  What either finds is in the cache
750        # for the other.
751
3
9
        my $cache = $self->{'cache'} // _default_cache();
752
3
7
        my $chain = Geo::Coder::List->new(cache => $cache)->push($local);
753
3
30
        $self->{'_local'}       = $local;
754
3
4
        $self->{'_local_chain'} = $chain;
755
756
3
5
        if ($self->{'online'}) {
757
3
7
                if (my $online = _online_geocoder()) {
758
0
0
                        $chain = Geo::Coder::List->new(cache => $cache)->push($local)->push($online);
759
0
0
                        $self->{'_online'} = $online;
760                } else {
761
3
7
                        $self->{'_online_missing'} = 1;
762                }
763        }
764
765
3
7
        return $chain;
766}
767
768# _default_cache() -> CHI cache
769#
770# The process-wide cache for Geo::Coder::List, made on first use.  CHI is a
771# prerequisite of the distribution, so this is not one more optional module.
772my $default_cache;
773
774sub _default_cache {
775
5
1252
        require CHI;
776
777
5
26
        $default_cache //= CHI->new(
778                driver    => 'Memory',
779                global    => 1,
780                namespace => $CACHE_NAMESPACE,
781                max_size  => $CACHE_MAX_SIZE,
782        );
783
784
5
10465
        return $default_cache;
785}
786
787# _online_geocoder() -> Geo::Coder::OSM object, or undef when it cannot be had
788#
789# Nominatim, behind a user agent that keeps its usage policy: one request a
790# second, a name that says who is asking, and a time-out so a service that has
791# stopped answering cannot hold a page.  The user agent is made once per
792# process, because the gap it keeps is measured from the last request it made:
793# one per object would let two pages opened together ask twice in a second.
794my $online_ua;
795
796sub _online_geocoder {
797
4
1054
        my $ok = eval {
798
4
128
                require Geo::Coder::OSM;
799
0
0
                Geo::Coder::OSM->VERSION($OSM_FLOOR);
800
0
0
                1;
801        };
802
4
11
        return unless $ok && nominatim_ua();
803
804        {
805
26
26
26
0
47
20
32593
0
                no warnings qw(once);   # the module's own variable, which only it reads
806
0
0
                $Geo::Coder::OSM::SOURCES{$NOMINATIM_SOURCE} = $NOMINATIM_URL;
807        }
808
809
0
0
        return Geo::Coder::OSM->new(ua => $online_ua, sources => $NOMINATIM_SOURCE);
810}
811
812 - 835
=head2 nominatim_ua

    my $ua = Database::BI::Model::Geocode::nominatim_ua()
        or return;    # LWP::UserAgent::Throttled is not installed

The user agent every request to Nominatim goes through, from the geocoder and
from L<Database::BI::Model::Boundary> alike: one per process, so the gap of a
second Nominatim's usage policy asks for holds across both, and across map
pages opened together.  It names this application, gives up after ten seconds,
and follows the environment's proxy settings.

=head3 API SPECIFICATION

=head4 INPUT

None.

=head4 OUTPUT

An L<LWP::UserAgent::Throttled> (an L<LWP::UserAgent>), the same object on
every call; or an empty list when LWP::UserAgent::Throttled 0.14 or later
cannot be loaded.

=cut
836
837sub nominatim_ua {
838
0
0
        return $online_ua if $online_ua;
839
840
0
0
        my $ok = eval {
841
0
0
                require LWP::UserAgent::Throttled;
842
0
0
                LWP::UserAgent::Throttled->VERSION($THROTTLED_FLOOR);
843
0
0
                1;
844        };
845
0
0
        return unless $ok;
846
847
0
0
        my $ua = LWP::UserAgent::Throttled->new(
848                agent      => $USER_AGENT,
849                timeout    => $ONLINE_TIMEOUT,
850                keep_alive => 1,
851        );
852
0
0
        $ua->env_proxy();
853
0
0
        $ua->throttle({ $NOMINATIM_HOST => $NOMINATIM_GAP });
854
0
0
        $online_ua = $ua;
855
856
0
0
        return $online_ua;
857}
858
859# _judge() -> the object whose valid_location() decides what is a place
860#
861# An injected geocoder answers for itself.  Geo::Coder::List has no rule of its
862# own, so the chain is judged by Geo::Coder::Free's, the module it asks first.
863sub _judge {
864
5243
3036
        my ($self, $geocoder) = @_;
865
866
5243
2548
        return $geocoder->can('valid_location') ? $geocoder : $self->{'_local'};
867}
868
869# _geocoder() -> geocoder object or undef
870#
871# Loaded once per object, so a missing module is not looked for on every value.
872sub _geocoder {
873
377
196
        my $self = shift;
874
875
377
331
        if (!exists $self->{'_geocoder'}) {
876
29
42
                $self->{'_geocoder'} = $self->_load_geocoder();
877        }
878
879
376
409
        return $self->{'_geocoder'};
880}
881
882# _coordinates($result) -> ($lat, $lon)
883#
884# The position out of a geocoder result, read through the accessors of a
885# Geo::Location::Point and the keys of a plain hashref from another geocoder.
886# 'lon' is only a third fallback, as in HTML::Genealogy::Map: it is not part of
887# the point interface, and only one of Geo::Coder::Free's MaxMind shortcuts ever
888# spells longitude that way.
889sub _coordinates {
890
685
6979
        my $point = shift;
891
892
685
541
        return unless ref($point) && (ref($point) ne 'ARRAY');
893
894
125
272
        if (blessed($point) && $point->can('latitude') && $point->can('longitude')) {
895
108
659
                return ($point->latitude(), $point->longitude());
896        }
897
898
17
16
        if (ref($point) eq 'HASH') {
899
17
40
                return ($point->{'lat'}, $point->{'long'} // $point->{'lng'} // $point->{'lon'});
900        }
901
902
0
0
        return;
903}
904
905# _backend_of($result) -> $name or undef
906#
907# Which database answered, as section 6.2 wants recorded and shown.  'database'
908# names the backend and 'geocoder' the distribution; a result carrying neither is
909# not guessed at.  Geo::Coder::List puts the geocoder object that answered in
910# 'geocoder', which is named by its class (Geo::Coder::OSM), and 'cache' when
911# its own cache did, which names nothing.
912sub _backend_of {
913
126
4862
        my $point = shift;
914
915
126
191
        return unless ref($point) && (ref($point) ne 'ARRAY');
916
917
123
77
        for my $key (qw(database geocoder)) {
918
131
210
                my $value = (blessed($point) && $point->can($key)) ? $point->$key() : $point->{$key};
919
131
422
                $value = ref($value) if blessed($value);
920
131
155
                next if defined($value) && $value eq 'cache';
921
131
269
                return $value if defined($value) && length($value) && !ref($value);
922        }
923
924
7
6
        return;
925}
926
927# _has_position($cache_entry)
928#
929# True for a remembered [lat, lon]; false for a remembered 0, which says "looked
930# up and not found" and is a different thing from "never looked up".
931sub _has_position {
932
63
7191
        my $entry = shift;
933
934
63
42
90
53
        return 0 unless (ref($entry) eq 'ARRAY') && (@{ $entry } >= 2);
935
936
39
103
        return (defined($entry->[0]) && defined($entry->[1])) ? 1 : 0;
937}
938
939# _resolve($values, \%opts) -> \%result
940#
941# The whole of section 6.2 in one pass: classify every distinct value, apply the
942# cap, make one batch, and count.  No rows and no row-level message.
943sub _resolve {
944
173
845
        my ($self, $values, $opts) = @_;
945
946
173
155
        my $max    = $opts->{'max'};
947
173
122
        my $region = $opts->{'region'};
948
949
173
222
        my ($available, $reason) = $self->geocoder_available();
950
173
148
        my $geocoder = $self->_geocoder();
951
952        # A working copy: a caller's cache is never modified, so a request that dies
953        # half way through cannot leave a half-written one behind.
954
173
173
98
270
        my %cache = %{ $opts->{'cache'} // {} };
955
956
173
135
        my %seen;
957
173
117
        my (@skipped, @unresolved, @not_attempted, @pending);
958
173
148
        my ($distinct, $cached_resolved, $cached_unresolved) = (0, 0, 0);
959
960        # The positions found, whether they were found now or in an earlier request.
961
173
109
        my %points;
962        my %backends;
963
964        # 1. Which values are worth asking about at all.
965
173
173
110
206
        for my $value (@{ $values // [] }) {
966
5815
3738
                my $key = (defined($value) && !ref($value)) ? $value : '';
967
5815
5548
                next if $seen{$key}++;
968
5347
1821
                $distinct++;
969
970                # A cell with nothing in it is not a location under any reading, so it is
971                # refused whether or not a geocoder is installed.
972
5347
4797
                if (!defined($value) || ref($value) || !length($key)) {
973
39
31
                        push @skipped, $value;
974
39
32
                        next;
975                }
976
977                # Remembered answers are used even when there is no geocoder: what has
978                # been resolved before is still plottable.
979
5308
2409
                if (exists $cache{$key}) {
980
46
69
                        if (_has_position($cache{$key})) {
981
28
16
                                $cached_resolved++;
982
983                                # A remembered place is a place to plot.  The point is built here
984                                # rather than only for the values looked up below, so that a
985                                # request which asks the geocoder nothing - because it has
986                                # nothing new to ask it - is not a request that plots nothing.
987                                # No backend is claimed for it: the cache remembers a position,
988                                # not which dataset gave it.
989                                $points{$key} = {
990                                        'lat' => $cache{$key}[0],
991
28
48
                                        'lon' => $cache{$key}[1],
992                                };
993                        } else {
994
18
14
                                $cached_unresolved++;
995
18
15
                                push @unresolved, $value;
996                        }
997
46
36
                        next;
998                }
999
1000
5262
2271
                unless ($geocoder) {
1001                        # No geocoder: the rule cannot be asked, so nothing is refused here
1002                        # and nothing is looked up either.
1003
21
19
                        push @not_attempted, $value;
1004
21
17
                        next;
1005                }
1006
1007                # The rule, asked of the module that would do the lookup.  A value it
1008                # refuses never reaches a backend, so it cannot croak there.
1009
5241
2303
                unless ($self->_judge($geocoder)->valid_location($key)) {
1010
29
131
                        push @skipped, $value;
1011
29
36
                        next;
1012                }
1013
1014
5211
15091
                push @pending, $value;
1015        }
1016
1017        # 2. The cap, counted in new lookups: map_geocode_max in section 6.2.  Values
1018        # held back are left out of the cache, so the next request picks them up.
1019
172
136
        my $wanted = scalar @pending;
1020
172
390
        my @attempt = @pending;
1021
172
111
        my $capped  = 0;
1022
1023
172
174
        if ($wanted > $max) {
1024
16
130
                @attempt = @pending[0 .. $max - 1];
1025
16
248
                push @not_attempted, @pending[$max .. $#pending];
1026
16
38
                $capped = 1;
1027        }
1028
1029        # With lookup => 0 nothing is asked: the places that would have been are
1030        # handed back as 'pending', for a caller that looks them up one at a time
1031        # (the map page's progress bar), and are not_attempted meanwhile.  The cap
1032        # still bounds the list; the rest are pending on the next request.
1033
172
103
        my @wait;
1034
1035
172
224
        unless ($opts->{'lookup'} // 1) {
1036
1
1
                @wait = @attempt;
1037
1
2
                unshift @not_attempted, @attempt;
1038
1
1
                @attempt = ();
1039
1
3
                $capped  = 0;
1040        }
1041
1042        # 3. The lookups, each place down a Geo::Coder::List on its own, so that its
1043        # cache answers what it has found before.  With an online geocoder a place
1044        # that reaches Nominatim is counted against online_max, and a Nominatim that
1045        # does not answer is not taken to mean the place does not exist.  Without
1046        # one the list holds the local data alone, asked with the region hint.  An
1047        # injected geocoder is asked for one batch, with the non-croaking mode.
1048
172
139
        my ($lookups, $resolved, $unresolved) = (0, 0, 0);
1049
172
238
        my $lookup = { 'answers' => {}, 'held' => [], 'online' => 0 };
1050
1051
172
186
        if (@attempt) {
1052                $lookup = $self->{'_online'}         ? $self->_lookup_online($geocoder, \@attempt, $region)
1053
110
251
                        : $self->{'_local_chain'}    ? $self->_lookup_local(\@attempt, $region)
1054                        :                                 _lookup_batch($geocoder, \@attempt, $region);
1055
1056
106
106
                $lookups = $lookup->{'lookups'};
1057
1058                # A place held back was not answered either way: it is left out of the
1059                # cache, like a place past the cap, so the next request asks again.
1060
106
0
106
75
0
122
                my %held = map { $_ => 1 } @{ $lookup->{'held'} };
1061
106
106
68
91
                push @not_attempted, @{ $lookup->{'held'} };
1062
106
675
95
356
                @attempt = grep { !$held{$_} } @attempt;
1063
106
0
156
0
                $capped = 1 if $lookup->{'spent'} && @{ $lookup->{'held'} };
1064
1065
106
83
                for my $value (@attempt) {
1066
675
305
                        my $point = $lookup->{'answers'}{$value};
1067
675
336
                        my ($lat, $lon) = _coordinates($point);
1068
1069
675
613
                        if (defined($lat) && defined($lon)) {
1070
119
102
                                my $backend = _backend_of($point);
1071
1072                                # Nominatim answers in strings ("51.33"), the local data in
1073                                # numbers; the cache and the map get numbers either way.
1074
119
119
                                ($lat, $lon) = ($lat + 0, $lon + 0);
1075
1076
119
116
                                $cache{$value} = [ $lat, $lon ];
1077
119
178
                                $points{$value} = {
1078                                        'lat' => $lat,
1079                                        'lon' => $lon,
1080                                        (defined($backend) ? ('backend' => $backend) : ()),
1081                                };
1082
119
117
                                $backends{$backend}++ if defined($backend);
1083
119
91
                                $resolved++;
1084
1085                        } else {
1086                                # Looked up and not found: recorded as tried, so the next request
1087                                # over this column does not ask again.
1088
556
295
                                $cache{$value} = 0;
1089
556
220
                                push @unresolved, $value;
1090
556
233
                                $unresolved++;
1091                        }
1092                }
1093        }
1094
1095        # 4. What to tell the user.  Counts and keys, never a location value: a place
1096        # column in a personal dataset is personal data (section 7).
1097
168
100
        my @messages;
1098
1099        # geocoder_available() already returns the finished sentence, so it is used as
1100        # the text; formatting it again repeated the whole message.
1101        push @messages, {
1102                'key'  => $self->{'_unavailable_key'} // 'error_map_geocoder_missing',
1103
168
196
                'text' => defined($reason) ? $reason : $self->_msg('error_map_geocoder_missing', $self->{'min_version'}, 'it is not installed'),
1104        } unless $available;
1105
1106
168
173
        push @messages, $self->_message('warn_map_geocode_capped', scalar @attempt, $wanted)
1107                if $capped;
1108
1109
0
0
        push @messages, $self->_message('warn_map_geocoder_online_failed', $lookup->{'failed'}, scalar @{ $lookup->{'held'} })
1110
168
0
217
0
                if defined($lookup->{'failed'}) && @{ $lookup->{'held'} };
1111
1112        # Coarse answers are what the local data gives on its own; once Nominatim is
1113        # asked about the places it does not know, the warning is no longer true.
1114        push @messages, $self->_message('warn_map_geocoder_unavailable_data')
1115
168
330
                if @attempt && !$self->{'openaddr'} && !$self->{'_online'};
1116
1117        push @messages, $self->_message('warn_map_geocoder_local_only')
1118
168
202
                if $unresolved && $self->{'_online_missing'};
1119
1120
168
197
        my @names = sort keys %backends;
1121
1122        return {
1123                'available'     => $available ? 1 : 0,
1124                'points'        => \%points,
1125                'counts'        => {
1126                        'distinct'      => $distinct,
1127                        'skipped'       => scalar @skipped,
1128                        'cached'        => $cached_resolved + $cached_unresolved,
1129                        'attempted'     => scalar @attempt,
1130                        'lookups'       => $lookups,
1131
168
1709
                        'online'        => $lookup->{'online'},
1132                        'resolved'      => $cached_resolved + $resolved,
1133                        'unresolved'    => $cached_unresolved + $unresolved,
1134                        'not_attempted' => scalar @not_attempted,
1135                },
1136                'skipped'       => \@skipped,
1137                'unresolved'    => \@unresolved,
1138                'not_attempted' => \@not_attempted,
1139                'pending'       => \@wait,
1140                'messages'      => \@messages,
1141                'cache'         => \%cache,
1142                'backends'      => \%backends,
1143                'backend'       => @names ? join(', ', @names) : undef,
1144                'capped'        => $capped,
1145        };
1146}
1147
1148# _lookup_batch($geocoder, \@values, $region) -> \%lookup
1149#
1150# One geocode_many() call, for a geocoder injected in place of the chain.
1151# The count the geocoder reports for the batch is the one a caller caps its
1152# work by; a geocoder that reports none leaves the number of values it was
1153# handed.
1154sub _lookup_batch {
1155
113
1854
        my ($geocoder, $values, $region) = @_;
1156
1157
113
177
        my $batch = $geocoder->geocode_many(
1158                $values,
1159                (defined($region) ? (region => $region) : ()),
1160                on_error => 'undef',
1161        );
1162
1163        return {
1164                'answers' => (ref($batch) eq 'HASH') ? $batch : {},
1165                'lookups' => ((ref($batch) eq 'HASH') && defined($batch->{'lookups'}))
1166                        ? $batch->{'lookups'}
1167
109
57
1054
103
                        : scalar @{ $values },
1168                'held'    => [],
1169                'online'  => 0,
1170        };
1171}
1172
1173# _lookup_local(\@values, $region) -> \%lookup
1174#
1175# Each place down the Geo::Coder::List that holds the local data alone, with
1176# the region hint.  Geo::Coder::Free's own geocode_many() asks geocode() once a
1177# place as well, so going one at a time costs nothing, and the list's cache
1178# answers what it has found before, here or online.  A lookup answered by that
1179# cache is not counted as one.  The list catches what the local geocoder throws
1180# and logs it; a place whose lookup threw and found nothing is held, not
1181# remembered as not found, as on the online path.
1182sub _lookup_local {
1183
4
1533
        my ($self, $values, $region) = @_;
1184
1185
4
3
        my $chain = $self->{'_local_chain'};
1186
4
2
        my (%answers, @held);
1187
4
4
        my $lookups = 0;
1188
1189
4
4
1
15
        for my $value (@{ $values }) {
1190
8
7
                $chain->flush();
1191
8
14
                my $point = $chain->geocode(location => $value, (defined($region) ? (region => $region) : ()));
1192
8
8
23
7
                my @log   = @{ $chain->log() // [] };
1193
1194
8
10
12
11
                $lookups++ unless grep { ($_->{'geocoder'} // '') eq 'cache' } @log;
1195
1196
8
7
8
6
                if (!$point && grep { defined $_->{'error'} } @log) {
1197
1
2
                        push @held, $value;
1198
1
1
                        next;
1199                }
1200
1201
7
7
                $answers{$value} = $point;
1202        }
1203
1204        return {
1205
4
6
                'answers' => \%answers,
1206                'lookups' => $lookups,
1207                'held'    => \@held,
1208                'online'  => 0,
1209        };
1210}
1211
1212# _lookup_online($chain, \@values, $region) -> \%lookup
1213#
1214# Each place down the Geo::Coder::List chain: the local data, then Nominatim.
1215# The chain's log says which geocoders a place reached, which is how the
1216# lookups that went online are counted, and how a Nominatim that did not answer
1217# is told apart from a place it does not know: Geo::Coder::OSM answers nothing
1218# in both cases, and only its last response says which.
1219#
1220# Once online_max places have gone online, or Nominatim has failed once, the
1221# rest are asked of the local data alone, through _lookup_local.  A place it
1222# does not know is then held rather than remembered as not found, because Nominatim
1223# was never asked.
1224#
1225# Geo::Coder::List catches whatever a geocoder in it throws, logs it and asks
1226# the next one, so on this path a local geocoder that throws does not end the
1227# request as it does on the batch path.  A place whose lookup threw somewhere
1228# and found nothing is held too: "not found" is remembered for good, and an
1229# error is not an answer.  Nothing here adds an eval of its own.
1230sub _lookup_online {
1231
4
2279
        my ($self, $chain, $values, $region) = @_;
1232
1233
4
4
        my $online = $self->{'_online'};
1234
4
4
        my $class  = ref($online);
1235
4
3
        my $budget = $self->{'online_max'};
1236
1237
4
3
        my (%answers, @held, @rest);
1238
4
4
        my ($lookups, $asked, $failed) = (0, 0, undef);
1239
1240
4
4
1
6
        for my $index (0 .. $#{ $values }) {
1241
7
11
                if (defined($failed) || (defined($budget) && ($asked >= $budget))) {
1242
2
2
2
2
2
3
                        @rest = @{ $values }[$index .. $#{ $values }];
1243
2
1
                        last;
1244                }
1245
1246
5
5
                my $value = $values->[$index];
1247
1248
5
5
                $chain->flush();
1249
5
6
                my $point = $chain->geocode(location => $value);
1250
5
5
15
5
                my @log   = @{ $chain->log() // [] };
1251
1252
5
9
7
22
                $lookups++ unless grep { ($_->{'geocoder'} // '') eq 'cache' } @log;
1253
1254
5
9
3
9
                my @went = grep { ($_->{'geocoder'} // '') eq $class } @log;
1255
5
3
                if (@went) {
1256
5
2
                        $asked++;
1257
1258
5
5
                        my $response = $online->response();
1259
5
5
5
8
5
2
                        my ($thrown) = grep { defined } map { $_->{'error'} } @went;
1260
1261
5
11
                        if (!$point && (defined($thrown) || !$response || !$response->is_success())) {
1262                                # What the page is told is the status line, never the error
1263                                # text: an exception may quote the request, and the request
1264                                # holds the place, which is the reader's data (section 7).
1265
3
8
                                $failed = defined($thrown)              ? 'an error in Geo::Coder::OSM'
1266                                        : $response                     ? $response->status_line()
1267                                        :                                 'no response';
1268
3
2
                                push @held, $value;
1269
3
3
                                next;
1270                        }
1271                }
1272
1273
2
2
5
3
                if (!$point && grep { defined $_->{'error'} && ($_->{'geocoder'} // '') ne $class } @log) {
1274
0
0
                        push @held, $value;
1275
0
0
                        next;
1276                }
1277
1278
2
2
                $answers{$value} = $point;
1279        }
1280
1281
4
6
        if (@rest) {
1282
2
3
                my $local = $self->_lookup_local(\@rest, $region);
1283
2
3
                $lookups += $local->{'lookups'};
1284
2
2
1
2
                push @held, @{ $local->{'held'} };
1285
1286
2
0
2
1
0
4
                my %thrown = map { $_ => 1 } @{ $local->{'held'} };
1287
2
3
2
2
                for my $value (grep { !$thrown{$_} } @rest) {
1288
3
5
                        my ($lat, $lon) = _coordinates($local->{'answers'}{$value});
1289
1290
3
6
                        if (defined($lat) && defined($lon)) {
1291
1
2
                                $answers{$value} = $local->{'answers'}{$value};
1292                        } else {
1293
2
4
                                push @held, $value;
1294                        }
1295                }
1296        }
1297
1298        return {
1299
4
14
                'answers' => \%answers,
1300                'lookups' => $lookups,
1301                'held'    => \@held,
1302                'online'  => $asked,
1303                'spent'   => (!defined($failed) && @rest) ? 1 : 0,
1304                'failed'  => $failed,
1305        };
1306}
1307
1308# The options resolve_values() and resolve_column() share, validated once.
1309sub _options {
1310
190
247
        my ($self, $opts) = @_;
1311
1312
190
665
        my $args = validate_strict(
1313                schema => {
1314                        cache  => { type => 'hashref', optional => 1, default => undef },
1315                        region => { type => 'string',  optional => 1, default => undef },
1316                        max    => { type => 'scalar',  optional => 1, default => undef },
1317                        lookup => { type => 'scalar',  optional => 1, default => 1 },
1318                },
1319                stack_trace => 1,
1320                input => $opts,
1321        );
1322
1323
189
16307
        my $max = $DEFAULT_MAX;
1324
1325
189
384
        if (defined($args->{'max'})) {
1326                # A cap that is not a positive integer is a caller bug, not a location
1327                # that could not be resolved: it is refused rather than defaulted,
1328                # because defaulting would silently cap a request the caller meant to
1329                # raise, or raise one they meant to cap.
1330                croak(_fmt('error_max_invalid', $args->{'max'}))
1331
74
251
                        unless ($args->{'max'} =~ /\A\d+\z/) && ($args->{'max'} > 0);
1332
1333
55
57
                $max = $args->{'max'};
1334        }
1335
1336        return {
1337                'cache'  => $args->{'cache'},
1338                'region' => $args->{'region'},
1339                'max'    => $max,
1340
170
498
                'lookup' => $args->{'lookup'} ? 1 : 0,
1341        };
1342}
1343
1344 - 1420
=head2 resolve_values

    my $result = $geocode->resolve_values(\@values, %options);
    my $result = $geocode->resolve_values(\@values, \%options);

Resolve a flat list of cell values, without the context of any row structure.
Use this when you want to warm the cache for a column's distinct values, or
when you have already extracted the values yourself and do not need per-marker
row counts.

The returned hashref is identical to L</resolve_column>'s, except that
C<counts.rows>, C<counts.plotted>, C<counts.unusable>, and C<markers> are
absent, and C<warn_map_rows_skipped> is never emitted.

=head3 API SPECIFICATION

=head4 INPUT

    \@values => arrayref, required;  elements may be any scalar or undef
    cache    => hashref,             # optional; { value => [lat, lon] | 0 }
    region   => string,              # optional; two-letter country hint
    max      => positive integer,    # optional; new lookups allowed; default 500
    lookup   => 0 | 1,               # optional; 0 asks nothing (see resolve_column); default 1

Duplicate values in C<\@values> cost one lookup each.  C<undef>, references,
empty strings, and pure-digit strings are refused before any lookup and counted
as C<skipped>.

=head4 OUTPUT

Returns a hashref (same shape as L</resolve_column> but without C<markers>,
C<counts.rows>, C<counts.plotted>, and C<counts.unusable>):

    {
        available     => 1 | 0,
        points        => { $value => { lat => $n, lon => $n, backend? => $s } },
        counts        => {
            distinct      => $n,
            skipped       => $n,
            cached        => $n,
            attempted     => $n,
            lookups       => $n,
            resolved      => $n,
            unresolved    => $n,
            not_attempted => $n,
        },
        skipped       => [ $value, ... ],
        unresolved    => [ $value, ... ],
        not_attempted => [ $value, ... ],
        pending       => [ $value, ... ],
        messages      => [ { key => $k, text => $t }, ... ],
        cache         => { $value => [lat, lon] | 0 },
        backends      => { $name => $count },
        backend       => $name | undef,
        capped        => 0 | 1,
    }

Croaks with C<error_values_arrayref> if C<\@values> is not an arrayref.

=head3 EXAMPLE

    # Build the distinct-value list yourself and warm the cache offline.
    my %seen;
    my @cities = grep { defined($_) && !$seen{$_}++ } map { $_->{'city'} } @{ $rows };

    my $result = $geocode->resolve_values(\@cities,
        cache  => $cache,
        region => 'GB',
        max    => 2000,
    );

    printf "New lookups: %d  Resolved: %d  Unresolved: %d\n",
        $result->{'counts'}{'attempted'},
        $result->{'counts'}{'resolved'},
        $result->{'counts'}{'unresolved'};

=cut
1421
1422sub resolve_values {
1423
111
7921
        my $self   = shift;
1424
111
83
        my $values = shift;
1425
1426
111
160
        croak(_fmt('error_values_arrayref', defined($values) ? ref($values) || $values : 'undef'))
1427                unless ref($values) eq 'ARRAY';
1428
1429
98
122
        my $raw = Params::Get::get_params(undef, \@_) // {};
1430
1431
98
865
        return $self->_resolve($values, $self->_options($raw));
1432}
1433
1434 - 1438
=head2 resolve_column

See full documentation above, in L</SUBROUTINES/METHODS>.

=cut
1439
1440sub resolve_column {
1441
110
13968
        my $self   = shift;
1442
110
97
        my $rows   = shift;
1443
110
76
        my $column = shift;
1444
1445
110
189
        croak(_fmt('error_rows_arrayref', defined($rows) ? ref($rows) || $rows : 'undef'))
1446                unless ref($rows) eq 'ARRAY';
1447
1448
102
224
        croak(_fmt('error_column_required')) unless defined($column) && length($column);
1449
1450
95
125
        my $raw = Params::Get::get_params(undef, \@_) // {};
1451
1452        # The cells in row order, and whether the column is there at all.  A row that
1453        # is not a hashref has no cell, which is one of the things that gets skipped
1454        # rather than a reason to stop.
1455
95
780
        my @cells;
1456
95
65
        my $found = 0;
1457
1458
95
95
61
92
        for my $row (@{ $rows }) {
1459
666
343
                if (ref($row) eq 'HASH') {
1460
659
369
                        $found = 1 if exists $row->{$column};
1461
659
322
                        push @cells, $row->{$column};
1462
659
290
                        next;
1463                }
1464
1465
7
7
                push @cells, undef;
1466        }
1467
1468
95
95
62
191
        croak(_fmt('error_map_loc_column', $column)) if @{ $rows } && !$found;
1469
1470
85
164
        my $result = $self->_resolve(\@cells, $self->_options($raw));
1471
1472        # How many rows hold each distinct value, and where the first of them is: what
1473        # an aggregated marker's popup and its draw order need.
1474
79
82
        my (%row_count, %first_row);
1475
1476
79
117
        for my $index (0 .. $#cells) {
1477
646
476
                my $key = (defined($cells[$index]) && !ref($cells[$index])) ? $cells[$index] : '';
1478
1479
646
262
                $row_count{$key}++;
1480
646
381
                $first_row{$key} = $index unless exists $first_row{$key};
1481        }
1482
1483
79
52
        my $plotted = 0;
1484
1485
79
79
52
92
        for my $key (keys %{ $result->{'points'} }) {
1486
84
92
                $result->{'points'}{$key}{'rows'}      = $row_count{$key};
1487
84
83
                $result->{'points'}{$key}{'first_row'} = $first_row{$key};
1488
1489
84
71
                $plotted += $row_count{$key};
1490        }
1491
1492        $result->{'markers'} = [
1493
84
84
47
193
                map { { 'value' => $_, %{ $result->{'points'}{$_} } } }
1494
79
29
79
70
34
99
                sort { $first_row{$a} <=> $first_row{$b} } keys %{ $result->{'points'} }
1495        ];
1496
1497
79
65
        my $rows_total = scalar @cells;
1498
1499
79
81
        $result->{'counts'}{'rows'}     = $rows_total;
1500
79
101
        $result->{'counts'}{'plotted'}  = $plotted;
1501
79
104
        $result->{'counts'}{'unusable'} = $rows_total - $plotted;
1502
1503
79
98
        if ($plotted < $rows_total) {
1504                # Why the rest were not plotted, counted in rows, naming only the reasons
1505                # that apply: a list of every possible reason sent a reader looking for
1506                # empty cells that were not there.
1507
58
42
                my %why;
1508
58
58
31
61
                for my $value (@{ $result->{'skipped'} }) {
1509
51
72
                        my $key = (defined($value) && !ref($value)) ? $value : '';
1510
51
53
                        $why{$key} = length($key) ? 'refused' : 'empty';
1511                }
1512
58
35
58
56
43
66
                $why{$_} = 'not_found' for grep { defined } @{ $result->{'unresolved'} };
1513
58
23
58
49
24
76
                $why{$_} = 'later'     for grep { defined } @{ $result->{'not_attempted'} };
1514
1515
58
63
                my %rows_by;
1516
58
109
64
148
                $rows_by{ $why{$_} } += $row_count{$_} for grep { exists $row_count{$_} } keys %why;
1517
1518
86
141
                my $reasons = join(', ', map { $self->_msg("warn_map_rows_why_$_", $rows_by{$_}) }
1519
58
232
101
145
                        grep { $rows_by{$_} } qw(empty refused not_found later));
1520
1521
58
58
49
130
                push @{ $result->{'messages'} }, $self->_message('warn_map_rows_skipped',
1522                        $plotted, $rows_total, $rows_total - $plotted, $reasons);
1523        }
1524
1525
79
187
        return $result;
1526}
1527
1528 - 1565
=head2 geocoder_available

    my ($is_available, $reason) = $geocode->geocoder_available();

Ask whether this object can make new geocoder lookups.  Returns a list of two
values: a boolean (C<1> or C<0>) and a human-readable reason string when the
answer is no.

Loads C<Geo::Coder::Free> lazily on the first call if it has not been loaded
yet.  Never croaks: a panel uses this to decide whether to show the location
option, so the answer must always be a string, not an exception.

=head3 API SPECIFICATION

=head4 INPUT

None.  (No arguments accepted.)

=head4 OUTPUT

    ($available, $reason)

    $available => 1      # geocoder is ready
    $available => 0      # geocoder is not available
    $reason    => undef  # when $available is 1
    $reason    => string # error_map_geocoder_missing text; when $available is 0

=head3 EXAMPLE

    my ($ok, $reason) = $geocode->geocoder_available();

    if (!$ok) {
        # Disable the "Map by location column" panel option.
        $stash->{'map_loc_disabled'} = 1;
        $stash->{'map_loc_disabled_reason'} = $reason;
    }

=cut
1566
1567sub geocoder_available {
1568
204
1858
        my $self = shift;
1569
1570
204
249
        return (1, undef) if $self->_geocoder();
1571
1572        return (0, $self->_msg('error_map_geocoder_list_missing', $self->{'_unavailable'}))
1573
29
106
                if ($self->{'_unavailable_key'} // '') eq 'error_map_geocoder_list_missing';
1574
1575        return (0, $self->_msg('error_map_geocoder_missing',
1576                $self->{'min_version'},
1577
28
83
                $self->{'_unavailable'} // 'it is not installed'));
1578}
1579
1580 - 1613
=head2 file_cache

    my $cache   = Database::BI::Model::Geocode->file_cache($model_dir);
    my $geocode = Database::BI::Model::Geocode->new(cache => $cache);

The cache Geo::Coder::List keeps its answers in, as files under
F<$model_dir/geocode-cache>: a place Nominatim found is not asked again for a
month (Geo::Coder::List's C<cache_hit_duration>), across requests, restarts and
every hypnotoad worker.  A copy of each answer is also kept in the process's
memory.  The directory is made when the first answer is stored.

This is a B<class method>.  The map page and C<script/bi-geocode> both call it
with the directory that holds F<models.json>, so they share one cache.  It holds
place names, as F<models.json> does, so it belongs in C<model_dir> and never in
C<data_dir>.

=head3 API SPECIFICATION

=head4 INPUT

    $model_dir => string, required; an existing directory

=head4 OUTPUT

A L<CHI> object (the C<File> driver), for the C<cache> option of C<new()>.
Croaks with C<error_cache_dir> when C<$model_dir> is not a directory.

=head3 EXAMPLE

    my $geocode = Database::BI::Model::Geocode->new(
        cache => Database::BI::Model::Geocode->file_cache('.bi'),
    );

=cut
1614
1615sub file_cache {
1616
7
19854
        my (undef, $dir) = @_;
1617
1618
7
52
        croak(_fmt('error_cache_dir', defined($dir) ? $dir : 'undef'))
1619                unless defined($dir) && !ref($dir) && -d $dir;
1620
1621
2
5
        return _file_cache_at(_catdir($dir, $CACHE_DIR));
1622}
1623
1624# _file_cache_at($root) -> CHI cache
1625#
1626# Geo::Coder::List's cache as files under $root, with a copy of each answer in
1627# this process's memory.  CHI makes $root when it first stores an answer.
1628sub _file_cache_at {
1629
40
51
        my $root = shift;
1630
1631
40
259
        require CHI;
1632
1633
40
19128
        return CHI->new(
1634                driver    => 'File',
1635                root_dir  => $root,
1636                namespace => $CACHE_NAMESPACE,
1637                l1_cache  => { driver => 'RawMemory', global => 1, max_size => $CACHE_MAX_SIZE },
1638        );
1639}
1640
1641sub _catdir {
1642
40
69
        require File::Spec;
1643
40
90
        return File::Spec->catdir(@_);
1644}
1645
1646 - 1695
=head2 place_rows

    my ($places, $name) = Database::BI::Model::Geocode->place_rows(\@rows, [ 'Address', 'Country' ]);
    my $result = $geocode->resolve_column($places, $name);

    # Places that need their state and country to be found
    my ($places, $name) = Database::BI::Model::Geocode->place_rows(\@rows, [ 'County' ], 'Virginia, USA');

A place written across several columns, such as an address and then its
country, as one column to geocode.  Each row's cells are trimmed and joined in
the order given, with C<", ">, leaving out the empty ones:
C<"Brezje 8, Cerknica"> and C<"Slovenia"> become
C<"Brezje 8, Cerknica, Slovenia">.  A row with every cell empty gives C<''>,
which C<resolve_column> counts as skipped.

Text given as the third argument is added to the end of each place, after
C<", ">, for places the cells do not name fully: C<"Accomack"> with
C<"Virginia, USA"> is looked up as C<"Accomack, Virginia, USA">.  A row with
no place stays C<''>, so it is not found at the place the text names.

The rows themselves are not changed (a SQL backend's are locked): the result is
a new row for each, in the same order, holding only the joined place, so a
marker's C<first_row> still indexes C<\@rows>.  With a single column and no
text the rows are returned as they are, under that column's name.

=head3 API SPECIFICATION

=head4 INPUT

    \@rows       arrayref of hashrefs        # required; a row that is not a hashref gives undef
    \@columns    arrayref of column names    # required; one or more, in order
    $text        string                      # optional; added to the end of each place

=head4 OUTPUT

    (\@places, $name)
        \@places   one hashref { $name => $place } per row, or \@rows itself for one
                   column and no text
        $name      the columns joined with ", " ("Address, Country")

Croaks with C<error_rows_arrayref> when C<\@rows> is not an arrayref, and with
C<error_column_required> when C<\@columns> names no column.

=head3 EXAMPLE

    # loc=Address&loc=Country on the map page
    my ($places, $name) = Database::BI::Model::Geocode->place_rows($records, [qw(Address Country)]);
    my $result = Database::BI::Model::Geocode->new->resolve_column($places, $name, cache => \%cache);

=cut
1696
1697sub place_rows {
1698
49
9183
        my ($class, $rows, $columns, $text) = @_;
1699
1700
49
87
        croak(_fmt('error_rows_arrayref', defined($rows) ? ref($rows) || $rows : 'undef'))
1701                unless ref($rows) eq 'ARRAY';
1702
1703
54
179
        my @columns = grep { defined($_) && !ref($_) && length($_) }
1704
46
45
73
48
                (ref($columns) eq 'ARRAY' ? @{$columns} : ());
1705
46
66
        croak(_fmt('error_column_required')) unless @columns;
1706
1707
42
44
        my $name = join(', ', @columns);
1708
42
118
        $text = (defined($text) && !ref($text)) ? ($text =~ s/\A\s+//r =~ s/\s+\z//r) : '';
1709
42
122
        return ($rows, $name) if @columns == 1 && !length($text);
1710
1711        my @places = map {
1712
29
20
                my $row = $_;
1713                my $place = (ref($row) eq 'HASH')
1714
41
28
                        ? join(', ', grep { length } map {
1715
29
41
21
25
                                my $cell = $row->{$_};
1716
41
61
                                (defined($cell) && !ref($cell)) ? ($cell =~ s/\A\s+//r =~ s/\s+\z//r) : '';
1717                        } @columns)
1718                        : undef;
1719
29
43
                $place .= ", $text" if defined($place) && length($place) && length($text);
1720
29
29
                defined($place) ? +{ $name => $place } : undef;
1721
9
9
9
8
        } @{$rows};
1722
1723
9
14
        return (\@places, $name);
1724}
1725
1726 - 1756
=head2 place_text

    my ($text) = Database::BI::Model::Geocode->place_text(' , Virginia,   USA ');   # 'Virginia, USA'

Tidies text to be added to the end of each place (the third argument of
C<place_rows>): spaces are trimmed and runs of them made one, and a leading
comma dropped, since the place and the text are joined with C<", ">.  The map
page's C<loc_text=> and bi-geocode's C<--text> both go through it, so a place
cached by one is found by the other.

=head3 API SPECIFICATION

=head4 INPUT

    $value    string    # optional; undef is no text

=head4 OUTPUT

    ($text)   the tidied text; '' for undef or blank
    ()        for a reference, a control character, or more than
              $PLACE_TEXT_MAX (200) characters once tidied

Never croaks.

=head3 EXAMPLE

    my ($text) = Database::BI::Model::Geocode->place_text($param)
        or die "Not one short line\n";
    my ($places, $name) = Database::BI::Model::Geocode->place_rows($rows, [ 'County' ], $text);

=cut
1757
1758sub place_text {
1759
309
11264
        my ($class, $value) = @_;
1760
309
438
        return ('') unless defined $value;
1761
220
482
        return if ref($value) || $value =~ /[\x00-\x1f\x7f]/;
1762
198
219
        (my $text = $value) =~ s/\s+/ /g;
1763
198
307
        $text =~ s/\A[\s,]+|\s+\z//g;
1764
198
380
        return if length($text) > $PLACE_TEXT_MAX;
1765
190
504
        return ($text);
1766}
1767
1768 - 1805
=head2 cache_from_models

    my $cache = Database::BI::Model::Geocode->cache_from_models(\%models, $spec_key);

Extract the geocode cache for one dataset spec from a model store.  Returns a
B<copy> of the stored places hashref so the caller cannot accidentally modify
the model store.

This is a B<class method>: call it on the package name, or on an instance if
you prefer; either way the invocant is ignored.

=head3 API SPECIFICATION

=head4 INPUT

    \%models  => hashref, required;  the structure returned by _read_models()
    $spec_key => string, required;   the dataset spec (e.g. 'table:sales')

=head4 OUTPUT

Returns a plain hashref:

    { $place_name => [lat, lon] | 0, ... }

Returns an empty hashref C<{}> for an unknown spec, a spec that has never
been geocoded, or a C<\%models> argument that is not a hashref.  Never
croaks.

=head3 EXAMPLE

    my $models = decode_json(Mojo::File->new($model_path)->slurp);
    my $cache  = Database::BI::Model::Geocode->cache_from_models(
        $models, 'table:sales'
    );

    # $cache is now { 'Ramsgate' => [51.336, 1.416], 'Paris' => 0, ... }

=cut
1806
1807sub cache_from_models {
1808
49
15336
        my ($class, $models, $spec_key) = @_;
1809
1810
49
121
        my $entry = (ref($models) eq 'HASH') ? $models->{'geo'}{$spec_key} : undef;
1811
1812
49
146
        return {} unless ref($entry) eq 'HASH' && (ref($entry->{'places'}) eq 'HASH');
1813
1814
10
10
10
16
        return { %{ $entry->{'places'} } };
1815}
1816
1817 - 1875
=head2 models_with_cache

    my $updated_models = Database::BI::Model::Geocode->models_with_cache(
        \%models, $spec_key, \%cache,
        backend => 'OpenAddresses',
        built   => '2026-10-18T12:00:00',
    );

Produce a new model store in which the geocode cache for C<$spec_key> is
replaced with C<\%cache>.  Every other key in the model store, and every
other spec's geocode data, is carried over unchanged.

This is a B<class method>; the invocant is ignored.

This module never writes the file.  The caller is responsible for passing
C<$updated_models> to C<_write_models()> or its equivalent, which is where
the writability and C<data_dir> guards live.  The separation keeps those
guards in the one place that already owns them

=head3 API SPECIFICATION

=head4 INPUT

    \%models  => hashref, required;  the existing model store (not modified)
    $spec_key => string, required;   the dataset spec to update
    \%cache   => hashref, required;  { place => [lat, lon] | 0 }
    backend   => string, optional;   name of the geocoder backend that resolved
    built     => string, optional;   ISO-8601 timestamp of when the cache was built

=head4 OUTPUT

Returns a new hashref.  The caller's C<\%models> is never modified.

    {
        ...all existing model keys...,
        geo => {
            ...all existing geo specs...,
            $spec_key => {
                places  => \%cache,
                backend => $backend,  # if supplied
                built   => $built,    # if supplied
            },
        },
    }

=head3 EXAMPLE

    my $updated = Database::BI::Model::Geocode->models_with_cache(
        $models,
        'path:/data/sales.csv',
        $result->{'cache'},
        backend => $result->{'backend'},
        built   => '2026-10-18T09:15:42',
    );

    # Now write the updated store to disk.
    Mojo::File->new($model_path)->spew(encode_json($updated));

=cut
1876
1877sub models_with_cache {
1878
16
16969
        my ($class, $models, $spec_key, $cache, %meta) = @_;
1879
1880
16
16
19
51
        my $spec = { %{ (ref($models) eq 'HASH') ? ($models->{'geo'}{$spec_key} // {}) : {} } };
1881
1882
16
16
18
287
        $spec->{'places'} = { %{ $cache // {} } };
1883
1884
16
24
        for my $key (qw(backend built)) {
1885
32
41
                $spec->{$key} = $meta{$key} if defined($meta{$key});
1886        }
1887
1888
16
16
10
24
        my %updated = %{ (ref($models) eq 'HASH') ? $models : {} };
1889
1890
16
16
13
28
        $updated{'geo'} = { %{ $updated{'geo'} // {} }, $spec_key => $spec };
1891
1892
16
23
        return \%updated;
1893}
1894
1895 - 1931
=head2 shared_cache_from_models

    my $cache = Database::BI::Model::Geocode->shared_cache_from_models(\%models);

Extract the place answers every dataset shares, as a B<copy> the caller may
modify.  This is the cache a map request should pass to C<resolve_column>:
a place geocoded for one file is then plotted for every other file that names
it, without a second lookup.

A model store written before the cache was shared has no shared entry; this
returns C<{}> and the per-dataset caches remain readable with
C<cache_from_models>.  A caller that reads both gets the old answers once and
writes them back to the shared entry (see C<models_with_shared_cache>).

This is a B<class method>; the invocant is ignored.

=head3 API SPECIFICATION

=head4 INPUT

    \%models  => hashref, required;  the structure returned by _read_models()

=head4 OUTPUT

    { $place_name => [lat, lon] | 0, ... }

Returns an empty hashref for a store with no shared cache, for a malformed
entry, or for a C<\%models> argument that is not a hashref.  Never croaks.

=head3 EXAMPLE

    my $models = decode_json(Mojo::File->new($model_path)->slurp);
    my $cache  = Database::BI::Model::Geocode->shared_cache_from_models($models);

    # $cache is now { 'Ramsgate' => [51.336, 1.416], 'Paris' => 0, ... }

=cut
1932
1933sub shared_cache_from_models {
1934
89
4740
        my ($class, $models) = @_;
1935
1936        # One level at a time: a nested read would add an empty 'geo' to the caller's
1937        # store, and the next write would save it.
1938
89
137
        my $geo   = (ref($models) eq 'HASH') ? $models->{'geo'} : undef;
1939
89
143
        my $entry = (ref($geo) eq 'HASH') ? $geo->{$SHARED_CACHE_KEY} : undef;
1940
1941
89
256
        return {} unless ref($entry) eq 'HASH' && (ref($entry->{'places'}) eq 'HASH');
1942
1943
14
14
11
33
        return { %{ $entry->{'places'} } };
1944}
1945
1946 - 2000
=head2 models_with_shared_cache

    my $updated_models = Database::BI::Model::Geocode->models_with_shared_cache(
        \%models, \%cache,
        backend => 'OpenAddresses',
        built   => '2026-10-18T12:00:00',
    );

Produce a new model store in which the shared place cache holds C<\%cache>.
The cache is B<merged>, not replaced: a request writes back every place it
saw, and another request may have answered a different place since this one
read the store.  Other model keys, and every per-dataset C<geo> entry, are
carried over unchanged.

This module never writes the file, and does not add a per-dataset entry.  The
caller passes the result to C<_write_models()> or its equivalent, where the
writability and C<data_dir> guards live.

=head3 API SPECIFICATION

=head4 INPUT

    \%models => hashref, required;  the existing model store (not modified)
    \%cache  => hashref, required;  { place => [lat, lon] | 0 }
    backend  => string, optional;   name of the geocoder backend that resolved
    built    => string, optional;   ISO-8601 timestamp of the cache update

=head4 OUTPUT

Returns a new hashref.  The caller's C<\%models> is never modified.

    {
        ...all existing model keys...,
        geo => {
            ...all existing per-dataset entries...,
            shared => {
                places  => \%merged_cache,
                backend => $backend,  # if supplied
                built   => $built,    # if supplied
            },
        },
    }

=head3 EXAMPLE

    my $updated = Database::BI::Model::Geocode->models_with_shared_cache(
        $models,
        $result->{'cache'},
        backend => $result->{'backend'},
        built   => '2026-10-18T09:15:42',
    );

    Mojo::File->new($model_path)->spew(encode_json($updated));

=cut
2001
2002sub models_with_shared_cache {
2003
34
5852
        my ($class, $models, $cache, %meta) = @_;
2004
2005        # Merge over what is already shared: the request may have read the store
2006        # before another one resolved a place, and replacing the entry would lose
2007        # that answer for every dataset rather than just this request.
2008        my %places = (
2009
34
31
                %{ $class->shared_cache_from_models($models) },
2010
34
34
37
71
                %{ (ref($cache) eq 'HASH') ? $cache : {} },
2011        );
2012
2013        # A section of the wrong shape (a hand-edited store) is rebuilt, not dereferenced.
2014
34
94
        my $geo   = (ref($models) eq 'HASH' && ref($models->{'geo'}) eq 'HASH') ? $models->{'geo'} : {};
2015
34
29
        my $entry = $geo->{$SHARED_CACHE_KEY};
2016
34
34
59
53
        my $spec  = { %{ (ref($entry) eq 'HASH') ? $entry : {} } };
2017
2018
34
41
        $spec->{'places'} = \%places;
2019
2020
34
35
        for my $key (qw(backend built)) {
2021
68
82
                $spec->{$key} = $meta{$key} if defined($meta{$key});
2022        }
2023
2024
34
34
34
81
        my %updated = %{ (ref($models) eq 'HASH') ? $models : {} };
2025
2026
34
44
        $updated{'geo'} = { %$geo, $SHARED_CACHE_KEY => $spec };
2027
2028
34
89
        return \%updated;
2029}
2030
20311;
2032
2033 - 2494
=head1 COMMON PITFALLS

=over 4

=item B<The cache sentinel 0 is not "false -- never looked up".>

A cache entry of C<0> means the place was looked up and not found.  An absent
key means it has never been attempted.  The module treats these two states
differently: a C<0> entry contributes to C<counts.unresolved> without
triggering a new lookup; an absent key enters the classification loop and may
reach the geocoder.

    # WRONG -- checking definedness misses the 0 sentinel.
    my $resolved = defined($cache{$place});

    # CORRECT -- use the internal _has_position logic.
    my $resolved = (ref($cache{$place}) eq 'ARRAY');

=item B<Pure-digit strings are skipped, not attempted.>

A value like C<'42'> fails C<valid_location()> and goes into C<@skipped>.  It
is never stored in the cache.  This is the correct behaviour for a row number
that ended up in the wrong column, but it surprises callers who expect every
non-empty value to be attempted.

=item B<The returned cache is a copy; the caller's hashref is never modified.>

Do not compare C<$cache_you_passed_in> with C<$result->{'cache'}> expecting
them to be the same reference.  The update is in C<$result->{'cache'}>.

=item B<resolve_column croaks when the column is absent; resolve_values does not.>

C<resolve_column> checks that the named column appears in at least one row.
If it does not, it croaks with C<error_map_loc_column>.  C<resolve_values>
does not do this check, because it receives values, not rows.

=item B<max counts new lookups, not rows or distinct values.>

A value already in C<cache> does not count toward C<max>, even if it was
looked up in a previous request.  A value skipped by C<valid_location()> does
not count either.

=item B<new() always succeeds; geocoder load failure is not a constructor error.>

You can always call C<new()> without checking whether C<Geo::Coder::Free> is
installed.  The load failure is deferred to the first call that needs the
geocoder, and is reported through C<geocoder_available()> and the
C<messages> array in the result, not through an exception.

=item B<cache_from_models and models_with_cache are class methods.>

You may call them on an instance for convenience, but the invocant is not used.
The pattern C<< Database::BI::Model::Geocode->cache_from_models(...) >> is
clearer.

=item B<An injected geocoder's batch receives on_error => 'undef'.>

A value an injected geocoder rejects after the C<valid_location()> pre-filter is
returned as C<undef> from the batch; it does not croak.  A backend that throws
an exception (a real database error, a network failure) still propagates
upward, because nothing here wraps the geocoder in an C<eval>.

=back

=head1 ENCODING

=over 4

=item B<Place names (values in the location column)>

Passed to the geocoder as byte strings.  UTF-8 place names such as
"Koeln" or "Beijing" are supported if the geocoder backend handles them.
The internal code does not re-encode or validate the bytes; it compares them
as opaque strings for deduplication and caching.

=item B<Column names>

Matched against row hash keys with a string equality test.  The column name
must be byte-for-byte identical to the key in the row hashrefs.  Column names
with non-ASCII bytes are accepted.

=item B<Spec keys (the $spec_key argument)>

Used as hash keys in the model store.  Any byte sequence is safe; UTF-8 spec
keys are stored and retrieved without modification.

=item B<Message strings>

The built-in C<%MESSAGES> table contains ASCII-only text.  If your application
needs non-ASCII messages (for example, a French translation), supply an C<i18n>
object to C<new()> whose C<maketext> method renders the key in the desired
locale.

=item B<Geocoder result strings (backend names)>

Stored and reported as returned by the geocoder.  The module does not impose
any encoding on them.

=back

=head1 DIAGNOSTICS

All user-visible messages are keyed in C<%Database::BI::Model::Geocode::MESSAGES>.

=over 4

=item C<error_map_geocoder_missing>

    Geocoding a location column needs Geo::Coder::Free %s or later, and %s

The geocoder module is not installed (the second C<%s> is "it is not
installed") or is too old (the second C<%s> is the installed version number).
The first C<%s> is the floor this module checks for - C<0.48> unless the caller
pinned C<min_geocoder_version>.  Install or upgrade C<Geo::Coder::Free>.

=item C<error_map_geocoder_list_missing>

    Geocoding a location column needs Geo::Coder::List 0.39 or later, and %s

C<Geo::Coder::Free> loaded but C<Geo::Coder::List>, which holds the chain, did
not: the C<%s> is "it is not installed" or the version that is.  Install or
upgrade C<Geo::Coder::List>.

=item C<error_cache_dir>

    Geocode: the geocode cache needs a directory that exists, not "%s"

C<file_cache()> was given a path that is not a directory.  Create it first.

=item C<error_cache_interface>

    Geocode: option "cache" must be a hashref or an object with get() and set(), not a %s

C<new()> was given a C<cache> object that Geo::Coder::List cannot use.

=item C<error_online_max_invalid>

    Geocode: option "online_max" must be a positive integer, not "%s"

C<new()> was given an C<online_max> that is not a positive integer.  Leave it
out for no limit, or pass C<< online => 0 >> to ask Nominatim nothing.

=item C<error_map_loc_column>

    Column "%s" is not in this dataset, so there is nothing to geocode

The C<$column_name> argument to C<resolve_column()> did not appear as a key in
any row.  Check the column name, including case and any spaces.

=item C<error_geocoder_interface>

    Geocode: the geocoder must provide %s; Geo::Coder::Free %s or later does

An injected C<geocoder> object does not respond to C<valid_location()> or
C<geocode_many()>.  Either use the real C<Geo::Coder::Free> or add the missing
method to your stub.

=item C<error_max_invalid>

    Geocode: option "max" must be a positive integer, not "%s"

The C<max> option was supplied but is not a positive integer string.  Passing
C<< max => 0 >> and C<< max => 'all' >> both trigger this error.

=item C<error_values_arrayref>

    Geocode: the values must be an arrayref, not "%s"

The first argument to C<resolve_values()> is not an arrayref.  Pass
C<\@values> (a reference), not C<@values> (a flat list).

=item C<error_rows_arrayref>

    Geocode: the rows must be an arrayref, not "%s"

The first argument to C<resolve_column()> is not an arrayref.

=item C<error_column_required>

    Geocode: the column name is required

The C<$column_name> argument to C<resolve_column()> is C<undef> or an empty
string.

=item C<warn_map_rows_skipped>

    Plotted %d of %d rows; %d could not be plotted: %s

Some rows could not be plotted.  The last argument says why, counted in rows,
naming only the reasons that apply, joined with C<, >; each is one of

    warn_map_rows_why_empty      %d with no place in the row
    warn_map_rows_why_refused    %d whose place is a bare number, not a place name
    warn_map_rows_why_not_found  %d whose place was not found
    warn_map_rows_why_later      %d whose place has not been looked up yet

in that order, rendered through the same C<i18n> object as the message.  Not an
error: the map renders with the rows that could be resolved.

=item C<warn_map_geocode_capped>

    Geocoded %d of the %d places that had not been looked up before; ...

The C<max> cap, or C<online_max>, prevented all pending values from being
looked up in this request.  The un-looked-up values are in C<not_attempted> and
are not stored in the cache, so the next request picks them up.

=item C<warn_map_geocoder_unavailable_data>

    The geocoder has no OpenAddresses data configured (OPENADDR_HOME), ...

The geocoder was loaded successfully but C<OPENADDR_HOME> is not set,
C<openaddr> was not passed to C<new()>, and Nominatim is not in the chain.
Resolution will succeed for broad place names (cities, countries) but will fail
for street-level addresses.  Set the environment variable or pass
C<< openaddr => $path >> to C<new()>.

=item C<warn_map_geocoder_local_only>

    Places the local data does not know were not looked up online, which needs Geo::Coder::OSM 0.03 and LWP::UserAgent::Throttled 0.14 or later

Online lookups were wanted, but one of the two modules is missing or too old,
and some places were not found.  Install them, or pass C<< online => 0 >> to
say the local data is all that is wanted.

=item C<warn_map_geocoder_online_failed>

    OpenStreetMap did not answer (%s), so %d places the local data does not know are left to try again later

Nominatim answered with an error (the C<%s> is its status line, such as
C<429 Too Many Requests>) or not at all.  The places are in C<not_attempted>,
uncached, and the next request asks again.

=back

=head1 FORMAL SPECIFICATION

The following sections use Z calculus notation to describe the exact state
transitions and invariants of each public operation.  Notation: ∈ (member of),
∉ (not member of), ⊆ (subset), ∪ (union), ∩ (intersection), ∧ (and), ∨ (or),
¬ (not), ∀ (for all), ∃ (there exists), → (maps to), ≤ (less than or equal),
≠ (not equal).

=head3 FORMAL SPECIFICATION

State transitions and invariants for each operation are described below.

=head2 _resolve -- value classification and batch geocoding

Let V be the multiset of input values.

Define the following disjoint sets that partition distinct(V):

    SKIPPED          = { v | v = undef, ref(v), or len(v) = 0,
                             or geocoder.valid_location(v) = false }
    CACHED_RESOLVED  = { v | v in dom(CACHE) and _has_position(CACHE(v)) }
    CACHED_UNRESOLVED = { v | v in dom(CACHE) and not _has_position(CACHE(v)) }
    NOT_ATTEMPTED    = { v | geocoder unavailable } (excludes SKIPPED and CACHED)
    PENDING          = distinct(V) \ (SKIPPED ∪ CACHED_RESOLVED ∪ CACHED_UNRESOLVED
                                      âˆª NOT_ATTEMPTED)

Partition invariant:

    |SKIPPED| + |CACHED_RESOLVED| + |CACHED_UNRESOLVED|
        + |NOT_ATTEMPTED| + |PENDING| = |distinct(V)|

Cap application (MAX = the max option, default 500):

    ATTEMPT        = PENDING[0 .. min(MAX, |PENDING|) - 1]
    CAPPED         = |PENDING| > MAX
    NOT_ATTEMPTED' = NOT_ATTEMPTED ∪ PENDING[MAX .. |PENDING| - 1]   (when CAPPED)

Deferral (lookup => 0):

    R.pending      = ATTEMPT
    NOT_ATTEMPTED' = NOT_ATTEMPTED' ∪ ATTEMPT
    ATTEMPT        = ∅                 (so CACHE' = CACHE, and nothing is asked)
    CAPPED         = false

Otherwise R.pending = ∅.

Geocoding step -- for each v in ATTEMPT:

    BATCH = { v => chain.geocode(v) | v in ATTEMPT }    (each through the list's
            cache; an injected geocoder: geocode_many(ATTEMPT, on_error => 'undef');
            a v whose lookup threw and found nothing moves to NOT_ATTEMPTED)

    for v in ATTEMPT:
        (lat, lon) = coordinates(BATCH(v))
        if defined(lat) and defined(lon):
            CACHE'(v)  = [lat, lon]
            POINTS'(v) = { lat, lon, backend? }
        else:
            CACHE'(v)  = 0
            UNRESOLVED_NEW += {v}

Count invariants (always hold):

    skipped + cached + attempted + not_attempted = distinct(V)
    resolved + unresolved = cached + attempted
    resolved  = |CACHED_RESOLVED| + |ATTEMPT ∩ POINTS'|
    unresolved = |CACHED_UNRESOLVED| + |ATTEMPT \ POINTS'|
    lookups   <= attempted

Cache monotonicity:

    dom(CACHE') ⊇ dom(CACHE)
    For all v in dom(CACHE): CACHE'(v) = CACHE(v)  (existing entries not modified)

=head2 resolve_column -- row augmentation

Given the output R of _resolve applied to the column's cell sequence CELLS:

    row_count  : Value -> N   where row_count(v) = |{ i | CELLS[i] = v }|
    first_row  : Value -> N   where first_row(v)  = min{ i | CELLS[i] = v }

    For each v in dom(R.points):
        R.points(v).rows      = row_count(v)
        R.points(v).first_row = first_row(v)

    R.markers = [ { value: v, ...R.points(v) }
                  | v <- sort_by(first_row, dom(R.points)) ]

    R.counts.rows     = |CELLS|
    R.counts.plotted  = sum{ row_count(v) | v in dom(R.points) }
    R.counts.unusable = R.counts.rows - R.counts.plotted

=head2 cache_from_models -- safe extraction

    cache_from_models(models, spec)
        = if ref(models) = HASH and ref(models.geo.spec) = HASH
                                and ref(models.geo.spec.places) = HASH
            then copy(models.geo.spec.places)
            else {}

The result is a shallow copy: the caller cannot modify the model store by
modifying the returned hashref, but values inside the cache (the [lat, lon]
arrayrefs) are shared references.

=head2 models_with_cache -- safe merge

    models_with_cache(models, spec, cache, backend?, built?)
        = { ...models,
            geo: { ...models.geo,
                   spec: { ...models.geo.spec,
                            places:  copy(cache),
                            backend: backend (if defined),
                            built:   built   (if defined) } } }

The caller's models hashref is never modified; a new top-level hashref is
returned.

=head1 STATE DIAGRAM

The object is in one of three states, according to whether it has a geocoder yet.
A geocoder given to C<new> is one straight away; otherwise one is looked for on
the first call that needs it.

    new()
      |
      +--[bad arguments, or a geocoder lacking
      |   valid_location or geocode_many]-----> croaks; no object
      |
      +--[geocoder => $g]---------------------> READY
      |
      v
  +-------------------+
  |    CONSTRUCTED    |  Geocoder not yet lazy-loaded.
  |  _geocoder not    |  resolve_*() and geocoder_available()
  |  yet called       |  may trigger a load on first call.
  +-------------------+
       |          |
  first call,     first call,
  module OK       module absent, too old or will not
       |          load, or its new() answers nothing
       v          v
  +---------+  +------------+
  |  READY  |  | UNAVAILABLE|
  |         |  |            |
  | Geocoder|  | No lookups |
  | loaded  |  | possible.  |
  | and     |  | Cache still|
  | working.|  | served.    |
  +---------+  +------------+
       |          |
  resolve_*()  resolve_*()
  geocodes +   cache only;
  cache        not_attempted
       |          |
       v          v
  +---------+  +------------+
  |  READY  |  | UNAVAILABLE|
  | (no     |  | (no        |
  | change) |  | change)    |
  +---------+  +------------+

Once the object is READY or UNAVAILABLE that does not change: neither a module
that appears nor one that goes away moves it, and the module is looked for once.

There are two ways for a call to croak and leave the state as it was.  Arguments a
resolve_*() call refuses are refused before any load is attempted.  A module that
loads and whose new() dies sends that exception to the caller and remembers
nothing, so the object stays CONSTRUCTED and the next call tries again.

Resolution itself is stateless: all state is in the result hashref and the cache
the caller manages.

    Valid state transitions summary:

    [START]          -> CONSTRUCTED      (new() with no geocoder)
    [START]          -> READY            (new() given a geocoder)
    [START]          -> ERROR            (new() refuses its arguments; croaks, no object)
    CONSTRUCTED      -> READY            (first call, module OK)
    CONSTRUCTED      -> UNAVAILABLE      (first call, no module that can be used)
    CONSTRUCTED      -> CONSTRUCTED      (arguments refused, or the module's new() dies; croaks)
    READY            -> READY            (resolve_*(), or arguments refused)
    UNAVAILABLE      -> UNAVAILABLE      (resolve_*(), or arguments refused)

Value-level state transitions within a single resolve_* call.  Each distinct value
takes the first of these that applies, from the top.  CACHE is the C<cache> in the
result, a copy: the cache the caller passed in is never modified.

    RECEIVED
       |
       +--[undef / ref / empty]-----------> SKIPPED
       |
       +--[in cache, has position]---------> CACHED_RESOLVED --> POINTS
       |
       +--[in cache, no position (= 0)]----> CACHED_UNRESOLVED --> UNRESOLVED
       |
       +--[geocoder unavailable]-----------> NOT_ATTEMPTED
       |
       +--[valid_location() throws]--------> EXCEPTION
       |
       +--[valid_location() = false]-------> SKIPPED
       |
       +--[within cap]--------------------> ATTEMPT
       |                                        |
       |                                        +--[geocoder returns position]--> RESOLVED_NEW --> POINTS, CACHE==[lat,lon]
       |                                        |
       |                                        +--[geocoder returns no position]--> UNRESOLVED_NEW, CACHE==0
       |                                        |
       |                                        +--[geocoder throws]--> EXCEPTION
       |
       +--[beyond cap]-------------------> NOT_ATTEMPTED

EXCEPTION is the whole request failing, on purpose: it goes to the caller, who has
no result and a cache exactly as it was, so nothing can be half-written.

=head1 AUTHOR

Nigel Horne C<< <njh@nigelhorne.com> >>

=head1 LICENCE AND COPYRIGHT

Copyright 2026 Nigel Horne.

Usage is subject to the GPL2 licence terms.
If you use it,
please let me know.

=cut