curtilage 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +75 -0
- data/README.md +76 -22
- data/SECURITY.md +18 -3
- data/docs/reference.md +221 -27
- data/docs/schema/site-v1.json +362 -0
- data/docs/security.md +69 -0
- data/exe/curtilage +375 -82
- data/lib/curtilage/audit.rb +5 -5
- data/lib/curtilage/auto_data.rb +61 -11
- data/lib/curtilage/batch.rb +116 -0
- data/lib/curtilage/build.rb +117 -63
- data/lib/curtilage/candidates.rb +67 -0
- data/lib/curtilage/catalogue.rb +44 -16
- data/lib/curtilage/confidence.rb +55 -0
- data/lib/curtilage/config.rb +24 -2
- data/lib/curtilage/corrections.rb +57 -0
- data/lib/curtilage/diff.rb +90 -0
- data/lib/curtilage/doctor.rb +92 -0
- data/lib/curtilage/download.rb +42 -16
- data/lib/curtilage/duckdb.rb +170 -6
- data/lib/curtilage/error.rb +3 -0
- data/lib/curtilage/features.rb +54 -5
- data/lib/curtilage/formats.rb +271 -36
- data/lib/curtilage/generator.rb +145 -166
- data/lib/curtilage/generator_details.rb +22 -14
- data/lib/curtilage/generator_lot.rb +56 -32
- data/lib/curtilage/generator_pin.rb +74 -0
- data/lib/curtilage/generator_roads.rb +109 -0
- data/lib/curtilage/generator_steps.rb +54 -0
- data/lib/curtilage/generator_store.rb +18 -4
- data/lib/curtilage/generator_zones.rb +93 -0
- data/lib/curtilage/geometry.rb +48 -52
- data/lib/curtilage/lookup.rb +41 -21
- data/lib/curtilage/overture.rb +137 -17
- data/lib/curtilage/preview.rb +55 -16
- data/lib/curtilage/profiles.rb +62 -0
- data/lib/curtilage/regions.rb +4 -8
- data/lib/curtilage/result.rb +72 -7
- data/lib/curtilage/validation.rb +73 -9
- data/lib/curtilage/version.rb +1 -1
- data/lib/curtilage/zip_range.rb +81 -16
- data/lib/curtilage.rb +155 -17
- data/sql/build_from_shapefiles.sql +1 -1
- metadata +15 -2
data/lib/curtilage/catalogue.rb
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require "digest"
|
|
3
4
|
require "json"
|
|
4
5
|
|
|
5
6
|
module Curtilage
|
|
@@ -14,12 +15,7 @@ module Curtilage
|
|
|
14
15
|
Geometry.box_points(pin, margin).any? { |point| holds?(point) }
|
|
15
16
|
end
|
|
16
17
|
|
|
17
|
-
def holds?(point)
|
|
18
|
-
lng, lat = point
|
|
19
|
-
return false unless lng.between?(bbox[0], bbox[2]) && lat.between?(bbox[1], bbox[3])
|
|
20
|
-
|
|
21
|
-
rings.nil? || rings.any? { |ring| Geometry.contains?(ring, point) }
|
|
22
|
-
end
|
|
18
|
+
def holds?(point) = Geometry.in_rings?(point, bbox, rings)
|
|
23
19
|
end
|
|
24
20
|
|
|
25
21
|
attr_reader :regions
|
|
@@ -28,16 +24,21 @@ module Curtilage
|
|
|
28
24
|
# where the Parquet files are served from instead (s3://bucket/path,
|
|
29
25
|
# https://...), when the metadata is local but the data isn't.
|
|
30
26
|
def self.from_dir(dir, base_url: nil)
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
27
|
+
new(Dir.glob(File.join(dir, "*.json")).filter_map { |file| region(file, dir, base_url) })
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
# A Region from one <region>.json, or nil if it isn't one. A file that
|
|
31
|
+
# claims to be one but can't be read is an error, not a silent gap.
|
|
32
|
+
def self.region(file, dir, base_url)
|
|
33
|
+
meta = JSON.parse(File.read(file, encoding: "utf-8"))
|
|
34
|
+
return nil unless meta.is_a?(Hash) && meta["format"] == 1 && meta["parquet"] && meta["bbox"]&.size == 4
|
|
35
|
+
|
|
36
|
+
parquet = base_url ? "#{base_url.chomp("/")}/#{meta["parquet"]}" : File.join(dir, meta["parquet"])
|
|
37
|
+
rings = meta["outline"]&.map { |ring| ring.map { |lng, lat| [Float(lng), Float(lat)] } }
|
|
38
|
+
Region.new(name: meta["region"], parquet: parquet, bbox: meta["bbox"].map { |v| Float(v) }, rings: rings,
|
|
39
|
+
metadata: meta)
|
|
40
|
+
rescue JSON::ParserError, ArgumentError, TypeError, NoMethodError => e
|
|
41
|
+
raise Error, "unreadable catalogue file #{file}: #{e.message[0, 200]}"
|
|
41
42
|
end
|
|
42
43
|
|
|
43
44
|
def initialize(regions)
|
|
@@ -61,6 +62,33 @@ module Curtilage
|
|
|
61
62
|
held == points.size ? :full : :partial
|
|
62
63
|
end
|
|
63
64
|
|
|
65
|
+
# Problems with the local Parquet files against what their metadata
|
|
66
|
+
# recorded (size and SHA256): missing, truncated or altered files.
|
|
67
|
+
def verify
|
|
68
|
+
@regions.filter_map do |r|
|
|
69
|
+
next if r.parquet.match?(Lookup::REMOTE) || !r.metadata["parquet_sha256"]
|
|
70
|
+
next "#{r.parquet}: missing" unless File.file?(r.parquet)
|
|
71
|
+
next "#{r.parquet}: #{File.size(r.parquet)} bytes, expected #{r.metadata["parquet_bytes"]}" \
|
|
72
|
+
if File.size(r.parquet) != r.metadata["parquet_bytes"]
|
|
73
|
+
|
|
74
|
+
next if Digest::SHA256.file(r.parquet).hexdigest == r.metadata["parquet_sha256"]
|
|
75
|
+
|
|
76
|
+
"#{r.parquet}: SHA256 differs from its metadata"
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
# Where the data for these files came from, for Result#provenance: each
|
|
81
|
+
# region's Geofabrik extract dates, and the ML footprints if the build
|
|
82
|
+
# added them (dated by the build, as their source publishes no dates).
|
|
83
|
+
def provenance(files)
|
|
84
|
+
regions = @regions.select { |r| files.include?(r.parquet) }.map do |r|
|
|
85
|
+
meta = r.metadata
|
|
86
|
+
ml = meta["ml_footprints"] && { source: meta["ml_footprints"], fetched: meta["built_at"].to_s[0, 10] }
|
|
87
|
+
{ region: meta["region"], extract_dates: meta["source_dates"], ml_footprints: ml }.compact
|
|
88
|
+
end
|
|
89
|
+
{ source: "geofabrik", regions: regions }
|
|
90
|
+
end
|
|
91
|
+
|
|
64
92
|
def attribution(files)
|
|
65
93
|
@regions.select { |r| files.include?(r.parquet) }.flat_map { |r| Array(r.metadata["attribution"]) }.uniq
|
|
66
94
|
end
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Curtilage
|
|
4
|
+
# How far to trust a result, 0 to 1, from what's known about how it was
|
|
5
|
+
# made: rule-based, no learning. Each factor that isn't met takes its
|
|
6
|
+
# weight off 1 (never below 0), so the score always comes with the reasons
|
|
7
|
+
# behind it. Flags say what to look at; confidence orders sites for review.
|
|
8
|
+
#
|
|
9
|
+
# The weights are judgement, set before measuring: to be calibrated on the
|
|
10
|
+
# public benchmark once its reference polygons exist. Data age isn't a
|
|
11
|
+
# factor, as it would make the same inputs score differently over time.
|
|
12
|
+
module Confidence
|
|
13
|
+
# name => [weight, what it means when met]
|
|
14
|
+
FACTORS = {
|
|
15
|
+
valid: [1.0, "The premises passed validation."],
|
|
16
|
+
main_method: [0.30, "Made by the main method (no fallback to the building rectangle)."],
|
|
17
|
+
building_under_pin: [0.20, "The pin was given on the building used (not near it, nor moved onto it)."],
|
|
18
|
+
full_data: [0.20, "Map data covers the whole area around the pin."],
|
|
19
|
+
osm_building: [0.10, "The building is from OpenStreetMap, not a machine-learned footprint."],
|
|
20
|
+
single_building_store: [0.10, "The building is small enough to be one store, not several tenants."],
|
|
21
|
+
plausible_building: [0.15, "The building is big enough to be a store, not a kiosk or canopy."],
|
|
22
|
+
mapped_parking: [0.15, "Mapped parking is inside the premises."],
|
|
23
|
+
road_frontage: [0.15, "At least one side of the premises runs along a public road."],
|
|
24
|
+
no_homes_next_door: [0.10, "No home borders the lot."],
|
|
25
|
+
no_warnings: [0.05, "Validation raised no warnings (size, shape and position look typical)."],
|
|
26
|
+
}.freeze
|
|
27
|
+
|
|
28
|
+
module_function
|
|
29
|
+
|
|
30
|
+
# [score, factors]: the score rounded to 2 places, and every factor as
|
|
31
|
+
# { name:, met:, weight: }.
|
|
32
|
+
def assess(result)
|
|
33
|
+
return [result.ok? ? 1.0 : 0.0, [{ name: :valid, met: result.ok?, weight: 1.0 }]] if result.method_name == :manual
|
|
34
|
+
|
|
35
|
+
factors = met(result).map { |name, ok| { name: name, met: ok, weight: FACTORS.fetch(name)[0] } }
|
|
36
|
+
lost = factors.reject { |f| f[:met] }.sum { |f| f[:weight] }
|
|
37
|
+
[[1.0 - lost, 0.0].max.round(2), factors]
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def met(result)
|
|
41
|
+
flags = result.flags
|
|
42
|
+
details = result.details || {}
|
|
43
|
+
{
|
|
44
|
+
valid: result.ok?, main_method: !flags.include?(:fallback),
|
|
45
|
+
building_under_pin: !flags.intersect?(%i[building_not_under_pin pin_moved]),
|
|
46
|
+
full_data: !flags.include?(:partial_data),
|
|
47
|
+
osm_building: !flags.include?(:ml_footprint),
|
|
48
|
+
single_building_store: !flags.intersect?(%i[large_building store_may_be_unit]),
|
|
49
|
+
plausible_building: !flags.include?(:small_building),
|
|
50
|
+
mapped_parking: details[:parking_area_m2].to_f.positive?, road_frontage: details[:frontage_m].to_f.positive?,
|
|
51
|
+
no_homes_next_door: !flags.include?(:near_houses), no_warnings: result.validation.warnings.empty?
|
|
52
|
+
}
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
end
|
data/lib/curtilage/config.rb
CHANGED
|
@@ -8,23 +8,45 @@
|
|
|
8
8
|
# CURTILAGE_CACHE_DIR where on-demand builds are kept (default: a
|
|
9
9
|
# temporary folder, deleted after each run)
|
|
10
10
|
# CURTILAGE_SOURCE auto (default), geofabrik or overture
|
|
11
|
+
# CURTILAGE_DUCKDB_TIMEOUT seconds a lookup or Overture query may take
|
|
12
|
+
# before DuckDB is stopped (default 600)
|
|
13
|
+
# CURTILAGE_OFFLINE 1: never touch the network (no downloads, no
|
|
14
|
+
# extension installs, no Overture or bucket reads)
|
|
11
15
|
#
|
|
12
16
|
# Curtilage.configure do |c|
|
|
13
17
|
# c.cache_dir = "/var/cache/curtilage"
|
|
14
18
|
# c.source = :overture
|
|
15
19
|
# end
|
|
16
20
|
module Curtilage
|
|
17
|
-
Config = Struct.new(:duckdb, :extension_directory, :cache_dir, :source,
|
|
21
|
+
Config = Struct.new(:duckdb, :extension_directory, :cache_dir, :source, :duckdb_timeout, :offline,
|
|
22
|
+
keyword_init: true)
|
|
18
23
|
|
|
19
24
|
def self.config
|
|
20
25
|
@config ||= Config.new(
|
|
21
26
|
duckdb: ENV.fetch("CURTILAGE_DUCKDB", "duckdb"),
|
|
22
27
|
extension_directory: ENV.fetch("CURTILAGE_EXTENSIONS", nil),
|
|
23
28
|
cache_dir: ENV.fetch("CURTILAGE_CACHE_DIR", nil),
|
|
24
|
-
source: ENV.fetch("CURTILAGE_SOURCE", "auto").to_sym
|
|
29
|
+
source: ENV.fetch("CURTILAGE_SOURCE", "auto").to_sym,
|
|
30
|
+
duckdb_timeout: seconds(ENV.fetch("CURTILAGE_DUCKDB_TIMEOUT", "600")),
|
|
31
|
+
offline: %w[1 true yes].include?(ENV.fetch("CURTILAGE_OFFLINE", "").downcase)
|
|
25
32
|
)
|
|
26
33
|
end
|
|
27
34
|
|
|
35
|
+
def self.offline? = config.offline == true
|
|
36
|
+
|
|
37
|
+
# Raises if offline mode forbids what's about to happen.
|
|
38
|
+
def self.online!(what)
|
|
39
|
+
raise Error, "offline mode (CURTILAGE_OFFLINE) forbids #{what}" if offline?
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def self.seconds(value)
|
|
43
|
+
number = Float(value, exception: false)
|
|
44
|
+
raise ArgumentError, "CURTILAGE_DUCKDB_TIMEOUT must be a number of seconds: #{value.inspect}" \
|
|
45
|
+
unless number&.positive? && number.finite?
|
|
46
|
+
|
|
47
|
+
number
|
|
48
|
+
end
|
|
49
|
+
|
|
28
50
|
def self.configure
|
|
29
51
|
yield config
|
|
30
52
|
config
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Curtilage
|
|
4
|
+
# Polygons a person drew or fixed, used instead of generating (generate's
|
|
5
|
+
# corrections:, the command line's --corrections): validated like any
|
|
6
|
+
# polygon and marked manual, so the few bad sites can be fixed once and
|
|
7
|
+
# the rest trusted.
|
|
8
|
+
module Corrections
|
|
9
|
+
module_function
|
|
10
|
+
|
|
11
|
+
# A Result for a corrected premises ring (and optionally a store ring)
|
|
12
|
+
# at pin: method :manual, provenance data source "manual". Not ok? if
|
|
13
|
+
# the ring fails validation; a store ring that isn't inside the
|
|
14
|
+
# premises is dropped, with a step saying so.
|
|
15
|
+
def result(pin, ring, store_ring: nil, validation: {})
|
|
16
|
+
pin = Validation.pin(pin)
|
|
17
|
+
log = Generator::Log.new([], [], nil, [])
|
|
18
|
+
log.note("manual: a corrected polygon, not generated", step: "manual")
|
|
19
|
+
checked = Validation.check(pin, ring, **validation)
|
|
20
|
+
Result.new(method_name: :manual, pin: pin, ring: (ring if checked.errors != ["missing"]),
|
|
21
|
+
store_ring: store(pin, ring, store_ring, checked, log), flags: log.flags,
|
|
22
|
+
explanation: log.notes, steps: log.steps, validation: checked, building: nil,
|
|
23
|
+
provenance: { gem_version: VERSION, data: { source: "manual" } })
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
def store(pin, ring, store_ring, checked, log)
|
|
27
|
+
return nil unless store_ring && checked.ok?
|
|
28
|
+
|
|
29
|
+
premises = Geometry.open_ring(Geometry.project(ring, pin))
|
|
30
|
+
inside = Validation.shape_errors(pin, store_ring).empty? &&
|
|
31
|
+
Geometry.open_ring(Geometry.project(store_ring, pin)).all? do |p|
|
|
32
|
+
Geometry.contains?(premises, p) || Geometry.distance_to_edges(premises, p) < 0.01
|
|
33
|
+
end
|
|
34
|
+
return store_ring if inside
|
|
35
|
+
|
|
36
|
+
log.note("dropped the corrected store zone: it isn't a valid ring inside the premises", step: "manual")
|
|
37
|
+
nil
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# corrections: { pin index => ring, or { ring:, store_ring: } }, checked
|
|
41
|
+
# against the number of pins.
|
|
42
|
+
def checked(corrections, size)
|
|
43
|
+
raise ArgumentError, "corrections must be a Hash of pin index => ring" unless corrections.is_a?(Hash)
|
|
44
|
+
|
|
45
|
+
corrections.to_h do |index, value|
|
|
46
|
+
unless index.is_a?(Integer) && index.between?(0, size - 1)
|
|
47
|
+
raise ArgumentError, "corrections: #{index.inspect} isn't a pin index (0 to #{size - 1})"
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
value = { ring: value } if value.is_a?(Array)
|
|
51
|
+
raise ArgumentError, "corrections: #{index}: a ring or { ring:, store_ring: }" unless value.is_a?(Hash)
|
|
52
|
+
|
|
53
|
+
[index, value.slice(:ring, :store_ring)]
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
end
|
|
57
|
+
end
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
|
|
5
|
+
module Curtilage
|
|
6
|
+
# Two runs compared site by site (curtilage diff OLD NEW), to refresh
|
|
7
|
+
# results as the map changes without reviewing everything again: only
|
|
8
|
+
# sites whose premises changed beyond a threshold need a look.
|
|
9
|
+
module Diff
|
|
10
|
+
# Below this IoU between old and new premises, a site needs review.
|
|
11
|
+
REVIEW_IOU = 0.9
|
|
12
|
+
COLUMNS = %w[id status review iou area_old_m2 area_new_m2 area_change_pct ok_old ok_new
|
|
13
|
+
flags_gained flags_lost confidence_old confidence_new].freeze
|
|
14
|
+
|
|
15
|
+
module_function
|
|
16
|
+
|
|
17
|
+
# Rows, by id, for results read with Formats.read_results. status:
|
|
18
|
+
# same, changed, added or removed. review: true when a site was added
|
|
19
|
+
# or removed, gained or lost premises, changed ok, gained a flag, or
|
|
20
|
+
# its premises overlap the old ones less than threshold (IoU).
|
|
21
|
+
def compare(old, new, threshold: REVIEW_IOU)
|
|
22
|
+
unless threshold.is_a?(Numeric) && threshold.between?(0, 1)
|
|
23
|
+
raise ArgumentError, "threshold is 0 to 1: #{threshold.inspect}"
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
(old.keys | new.keys).sort.map { |id| row(id, old[id], new[id], threshold) }
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
def row(id, before, after, threshold)
|
|
30
|
+
return { id: id, status: before ? "removed" : "added", review: true } unless before && after
|
|
31
|
+
|
|
32
|
+
a = props(before)
|
|
33
|
+
b = props(after)
|
|
34
|
+
iou, area_a, area_b = overlap(before[:ring], after[:ring])
|
|
35
|
+
same = before[:ring] == after[:ring] && a == b
|
|
36
|
+
{ id: id, status: same ? "same" : "changed", review: !same && review?(a, b, iou, threshold),
|
|
37
|
+
iou: iou&.round(3), area_old_m2: area_a, area_new_m2: area_b, area_change_pct: change(area_a, area_b),
|
|
38
|
+
ok_old: a[:ok], ok_new: b[:ok], flags_gained: b[:flags] - a[:flags], flags_lost: a[:flags] - b[:flags],
|
|
39
|
+
confidence_old: a[:confidence], confidence_new: b[:confidence] }
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def review?(before, after, iou, threshold)
|
|
43
|
+
(after[:flags] - before[:flags]).any? || before[:ok] != after[:ok] || iou.nil? || iou < threshold
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def change(before, after)
|
|
47
|
+
before&.positive? && after ? ((after - before) * 100.0 / before).round(1) : nil
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
def props(entry)
|
|
51
|
+
p = entry[:properties]
|
|
52
|
+
{ ok: p["ok"], flags: Array(p["flags"]).map(&:to_s), confidence: p["confidence"] }
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# [IoU, old area, new area] in square metres, or [nil, ...] when either
|
|
56
|
+
# ring is missing or not a usable shape. Premises are convex; a manual
|
|
57
|
+
# one that isn't is compared by its convex outline.
|
|
58
|
+
def overlap(ring_a, ring_b)
|
|
59
|
+
origin = (ring_a || ring_b)&.first
|
|
60
|
+
return [nil, nil, nil] unless origin.is_a?(Array) && Geometry.valid_coordinates?([origin])
|
|
61
|
+
|
|
62
|
+
a, b = [ring_a, ring_b].map { |r| usable_xy(r, origin) }
|
|
63
|
+
areas = [a, b].map { |xy| xy && Geometry.area(xy).round }
|
|
64
|
+
return [nil, *areas] unless a && b
|
|
65
|
+
|
|
66
|
+
inter = Geometry.clip_convex(a, Geometry.counter_clockwise(Geometry.convex_hull(b)))
|
|
67
|
+
shared = inter.size >= 3 ? Geometry.area(inter) : 0
|
|
68
|
+
[shared / (Geometry.area(a) + Geometry.area(b) - shared), *areas]
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
# The ring in metres around origin, or nil if it isn't a usable shape.
|
|
72
|
+
def usable_xy(ring, origin)
|
|
73
|
+
return nil unless ring && Validation.shape_errors(origin, ring).empty?
|
|
74
|
+
|
|
75
|
+
Geometry.counter_clockwise(Geometry.open_ring(Geometry.project(ring, origin)))
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# The rows as :csv (flags ;-separated) or :ndjson.
|
|
79
|
+
def write(rows, format)
|
|
80
|
+
case format.to_sym
|
|
81
|
+
when :csv
|
|
82
|
+
Formats.csv_text([COLUMNS] + rows.map { |r| COLUMNS.map { |c| cell(r[c.to_sym]) } })
|
|
83
|
+
when :ndjson then rows.map { |r| "#{JSON.generate(r)}\n" }.join
|
|
84
|
+
else raise ArgumentError, "unknown diff format #{format.inspect} (have: csv, ndjson)"
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
def cell(value) = value.is_a?(Array) ? value.join(";") : value
|
|
89
|
+
end
|
|
90
|
+
end
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Curtilage
|
|
4
|
+
# What `curtilage doctor` checks: everything the gem needs outside Ruby,
|
|
5
|
+
# each with a fix. Returns a report (a Hash) that the command prints as
|
|
6
|
+
# text or JSON.
|
|
7
|
+
module Doctor
|
|
8
|
+
# DuckDB versions the gem is tested with; others may work and get a warning.
|
|
9
|
+
TESTED = [/\Av?1\.4\./, /\Av?2\.0\./].freeze
|
|
10
|
+
INSTALL = {
|
|
11
|
+
"macOS" => "brew install duckdb",
|
|
12
|
+
"Linux" => "download the CLI from https://duckdb.org/docs/installation/ (most distributions don't package it) " \
|
|
13
|
+
"and set CURTILAGE_DUCKDB to its path",
|
|
14
|
+
}.freeze
|
|
15
|
+
|
|
16
|
+
module_function
|
|
17
|
+
|
|
18
|
+
# settings: duckdb:, extension_directory: (Curtilage.duckdb_options).
|
|
19
|
+
# verify: a catalogue or cache folder whose built files to check
|
|
20
|
+
# against their recorded SHA256s.
|
|
21
|
+
def report(settings, cache_dir: Curtilage.config.cache_dir, network: false, verify: nil)
|
|
22
|
+
checks = { "duckdb" => duckdb(settings) }
|
|
23
|
+
checks["extensions"] = extensions(settings) if checks["duckdb"]["ok"]
|
|
24
|
+
checks["cache"] = cache(cache_dir) if cache_dir
|
|
25
|
+
checks["built_files"] = built_files(verify) if verify
|
|
26
|
+
checks["network"] = reach if network
|
|
27
|
+
{ "ok" => checks.values.all? { |c| c["ok"] }, "offline" => Curtilage.offline?, "checks" => checks }
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
def duckdb(settings)
|
|
31
|
+
path = DuckDB.resolve(settings[:duckdb])
|
|
32
|
+
version = DuckDB.version(settings[:duckdb])
|
|
33
|
+
return { "ok" => false, "path" => path, "fix" => INSTALL } unless version
|
|
34
|
+
|
|
35
|
+
tested = TESTED.any? { |pattern| version.match?(pattern) }
|
|
36
|
+
{ "ok" => true, "path" => path, "version" => version, "tested" => tested,
|
|
37
|
+
"warning" => (tested ? nil : "untested DuckDB version (tested: 1.4 LTS and 2.0); it may still work") }.compact
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
def extensions(settings)
|
|
41
|
+
dir = settings[:extension_directory]
|
|
42
|
+
setup = [(DuckDB.extension_sql(dir, settings[:duckdb]) if dir), DuckDB.load_sql("spatial", "httpfs")].compact
|
|
43
|
+
versions = DuckDB.extension_versions(settings[:duckdb], setup.join("\n"), %w[spatial httpfs])
|
|
44
|
+
{ "ok" => versions.size == 2, "versions" => versions }
|
|
45
|
+
rescue Error => e
|
|
46
|
+
{ "ok" => false, "error" => e.message,
|
|
47
|
+
"fix" => Curtilage.offline? ? "run `curtilage doctor` once online to install them" : "check the network" }
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
def cache(dir)
|
|
51
|
+
return { "ok" => true, "path" => dir, "note" => "will be created (0700)" } unless File.exist?(dir)
|
|
52
|
+
|
|
53
|
+
problem = AutoData.cache_problem(File.stat(dir), dir)
|
|
54
|
+
problem ? { "ok" => false, "path" => dir, "error" => problem } : { "ok" => true, "path" => dir }
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
def built_files(dir)
|
|
58
|
+
catalogue = Catalogue.from_dir(dir)
|
|
59
|
+
problems = catalogue.verify
|
|
60
|
+
{ "ok" => problems.empty?, "path" => dir, "regions" => catalogue.regions.size, "problems" => problems,
|
|
61
|
+
"fix" => (problems.empty? ? nil : "rebuild the regions listed") }.compact
|
|
62
|
+
rescue Error => e
|
|
63
|
+
{ "ok" => false, "path" => dir, "error" => e.message }
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# Whether the hosts the gem downloads from answer (no locations are sent).
|
|
67
|
+
def reach
|
|
68
|
+
hosts = { Regions::HOST => Regions::INDEX, Overture::STAC_HOST => Overture::CATALOG }
|
|
69
|
+
results = hosts.to_h do |host, path|
|
|
70
|
+
[host, Download.exists?(host, path)]
|
|
71
|
+
rescue Curtilage::Error => e
|
|
72
|
+
[host, e.message]
|
|
73
|
+
end
|
|
74
|
+
{ "ok" => results.values.all?(true), "hosts" => results }
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
# The report as lines for a terminal.
|
|
78
|
+
def text(report)
|
|
79
|
+
report["checks"].flat_map { |name, check| lines(name, check) } +
|
|
80
|
+
[report["ok"] ? "Ready." : "Not ready: see the fixes above."]
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
def lines(name, check)
|
|
84
|
+
mark = check["ok"] ? "ok " : "!! "
|
|
85
|
+
detail = check.except("ok", "fix").map do |k, v|
|
|
86
|
+
"#{k}: #{v.is_a?(Hash) ? v.map { |a, b| "#{a} #{b}" }.join(", ") : v}"
|
|
87
|
+
end
|
|
88
|
+
fixes = Array(check["fix"].is_a?(Hash) ? check["fix"].map { |os, fix| "#{os}: #{fix}" } : check["fix"])
|
|
89
|
+
["#{mark}#{name}: #{detail.join("; ")}", *fixes.map { |f| " fix (#{f})" }]
|
|
90
|
+
end
|
|
91
|
+
end
|
|
92
|
+
end
|
data/lib/curtilage/download.rb
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require "fileutils"
|
|
3
4
|
require "net/http"
|
|
4
5
|
require "English"
|
|
5
6
|
require "openssl"
|
|
@@ -25,6 +26,10 @@ module Curtilage
|
|
|
25
26
|
Errno::ECONNABORTED, Errno::EPIPE, Errno::ETIMEDOUT, EOFError, OpenSSL::SSL::SSLError,
|
|
26
27
|
SocketError].freeze
|
|
27
28
|
ATTEMPTS = 3
|
|
29
|
+
# Every host the gem itself downloads from; anything else is refused.
|
|
30
|
+
# (DuckDB's own reads of Overture's storage, your bucket and its
|
|
31
|
+
# extension repository don't go through here.)
|
|
32
|
+
ALLOWED_HOSTS = %w[download.geofabrik.de stac.overturemaps.org minedbuildings.z5.web.core.windows.net].freeze
|
|
28
33
|
|
|
29
34
|
module_function
|
|
30
35
|
|
|
@@ -41,21 +46,25 @@ module Curtilage
|
|
|
41
46
|
|
|
42
47
|
# Writes to dest.part, then renames, so a dest file is always complete.
|
|
43
48
|
def fetch(host, path, dest, max_bytes:)
|
|
49
|
+
part = "#{dest}.part"
|
|
44
50
|
with_retries("downloading https://#{host}#{path}") do
|
|
45
|
-
curl ? curl_fetch(host, path,
|
|
51
|
+
curl ? curl_fetch(host, path, part, max_bytes) : http_fetch(host, path, part, max_bytes)
|
|
46
52
|
end
|
|
47
|
-
File.rename(
|
|
53
|
+
File.rename(part, dest)
|
|
48
54
|
dest
|
|
55
|
+
ensure
|
|
56
|
+
FileUtils.rm_f(part) if part && File.exist?(part) # failed or interrupted: no half file left behind
|
|
49
57
|
end
|
|
50
58
|
|
|
51
59
|
def read(host, path, max_bytes:)
|
|
52
60
|
with_retries("reading https://#{host}#{path}") do
|
|
53
61
|
start(host) do |http|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
62
|
+
body = nil
|
|
63
|
+
http.request_get(path) do |res|
|
|
64
|
+
check(res, host, path)
|
|
65
|
+
body = stream(res, String.new, max_bytes)
|
|
66
|
+
end
|
|
67
|
+
body
|
|
59
68
|
end
|
|
60
69
|
end
|
|
61
70
|
end
|
|
@@ -91,7 +100,7 @@ module Curtilage
|
|
|
91
100
|
check(res, host, path)
|
|
92
101
|
raise Error, "too large: https://#{host}#{path}" if res.content_length.to_i > max_bytes
|
|
93
102
|
|
|
94
|
-
stream(res,
|
|
103
|
+
File.open(dest, "wb") { |f| stream(res, f, max_bytes) }
|
|
95
104
|
end
|
|
96
105
|
end
|
|
97
106
|
end
|
|
@@ -119,6 +128,7 @@ module Curtilage
|
|
|
119
128
|
end
|
|
120
129
|
|
|
121
130
|
def curl_args(host, path)
|
|
131
|
+
allowed!(host)
|
|
122
132
|
[curl, "--silent", "--show-error", "--fail", "--proto", "=https", "--connect-timeout", "30",
|
|
123
133
|
"--speed-limit", "1000", "--speed-time", "60", "https://#{host}#{path}"]
|
|
124
134
|
end
|
|
@@ -137,20 +147,36 @@ module Curtilage
|
|
|
137
147
|
raise Transient, "curl failed for https://#{host}#{path}" unless $CHILD_STATUS.success?
|
|
138
148
|
end
|
|
139
149
|
|
|
140
|
-
|
|
150
|
+
# Appends the response body to out (a file or a binary string), stopping
|
|
151
|
+
# as soon as it passes max_bytes rather than after it has all arrived.
|
|
152
|
+
def stream(res, out, max_bytes)
|
|
141
153
|
bytes = 0
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
raise Error, "download over #{max_bytes} bytes" if bytes > max_bytes
|
|
154
|
+
res.read_body do |chunk|
|
|
155
|
+
bytes += chunk.bytesize
|
|
156
|
+
raise Error, "download over #{max_bytes} bytes" if bytes > max_bytes
|
|
146
157
|
|
|
147
|
-
|
|
148
|
-
end
|
|
158
|
+
out << chunk
|
|
149
159
|
end
|
|
160
|
+
out
|
|
150
161
|
end
|
|
151
162
|
|
|
152
163
|
def start(host, &)
|
|
153
|
-
|
|
164
|
+
allowed!(host)
|
|
165
|
+
proxy = proxy_for(host)
|
|
166
|
+
Net::HTTP.start(host, 443, proxy&.host, proxy&.port, proxy&.user, proxy&.password,
|
|
167
|
+
use_ssl: true, open_timeout: 30, read_timeout: 120, &)
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
# The proxy for an HTTPS download, as curl picks it: https_proxy (or
|
|
171
|
+
# HTTPS_PROXY) unless no_proxy covers the host. Net::HTTP on its own
|
|
172
|
+
# would read http_proxy instead.
|
|
173
|
+
def proxy_for(host)
|
|
174
|
+
URI("https://#{host}").find_proxy
|
|
175
|
+
end
|
|
176
|
+
|
|
177
|
+
def allowed!(host)
|
|
178
|
+
Curtilage.online!("downloading from #{host}")
|
|
179
|
+
raise Error, "not an allowed download host: #{host}" unless ALLOWED_HOSTS.include?(host)
|
|
154
180
|
end
|
|
155
181
|
|
|
156
182
|
# The path of an https URL on host, or nil for anything else.
|