spatial_features 3.11.1 → 3.12.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 41ad7ed6a989f41b717e103a1f800a60c776ecdf772d3be54dd65128ac84882c
4
- data.tar.gz: 6b741f6c962678db2edf963fdd53a87756c657476159f882af36a0bbb1685798
3
+ metadata.gz: 992823b144d43f8a6c13f32ce0fbd71bb6bea5bafb1aadb7840767f18d2a8d9f
4
+ data.tar.gz: 45397ed799db69896d94a48e8c3958ab7026420587e9dd1a4755fe57a650132f
5
5
  SHA512:
6
- metadata.gz: da7049b48402b343a62045dd9910c334240ebfc9d02f0738c5896d3a0033330b4293badfa5e39b9837c34204d3fb221116a79810a812ffa41b3cbf05c0784367
7
- data.tar.gz: 5bf14c630adc5bf960a106e0d1ae17b4490770e62dadbcce24dfeaf0cc711ac0e77ef218266d764744a847e66e7bcd0a22cb81e153c7cf2cba1d176d2a3dc266
6
+ metadata.gz: 9a9c533b9af654d339344dee13b62f14becf6e2c20fdd57868bfe5c185a5bede4657d130a6c9049d0557b274c1ed2a4a7cd70a8b826c3548824ed4b7bf7df76c
7
+ data.tar.gz: 7a9d9ecdd4f65b01e2cc3c0558ca3699205ecf783617e2adcd4958ca2639dd8240a99b883f1567199ce34ca5a3aad4d5bee4804902c9dddc3cf7e38690015fa5
data/Rakefile CHANGED
@@ -16,3 +16,5 @@ RSpec::Core::RakeTask.new(:spec) do |task|
16
16
  end
17
17
 
18
18
  task :default => :spec
19
+
20
+ Dir['tasks/*.rake'].each { |f| load f }
@@ -1,42 +1,93 @@
1
+ require 'net/http'
1
2
  require 'open-uri'
3
+ require 'openssl'
2
4
 
3
5
  module SpatialFeatures
4
6
  module Download
5
- # file can be a url, path, or file, any of which can return be a zipped archive
6
- def self.open(file)
7
- file = URI.open(file)
8
- file = normalize_file(file) if file.is_a?(StringIO)
9
- return file
10
- end
7
+ REMOTE_URL = %r{\Ahttps?://}i.freeze
8
+
9
+ # Seconds to wait for a remote source, applied both to establishing the connection and to
10
+ # each read. Without it a hung server holds an import worker open indefinitely.
11
+ mattr_accessor :timeout
12
+ self.timeout = 60
11
13
 
12
- # file can be a url, path, or file, any of which can return be a zipped archive
13
- def self.open_each(path_or_url, unzip: nil, **unzip_options)
14
- file = Download.open(path_or_url)
15
- files = if unzip && Unzip.is_zip?(file)
16
- find_in_zip(file, find: unzip, **unzip_options)
17
- else
18
- [file]
14
+ # Errors meaning a remote source could not be read at all, as opposed to being read and
15
+ # found unusable. `OpenURI::HTTPError` covers the 4xx and 5xx replies.
16
+ UNREACHABLE_ERRORS = [::OpenURI::HTTPError, ::SocketError, ::SystemCallError,
17
+ ::Net::OpenTimeout, ::Net::ReadTimeout, ::OpenSSL::SSL::SSLError].freeze
18
+
19
+ class << self
20
+ # Returns an open File for `file`, which may be a URL, a path, or a File. The content may
21
+ # be a zipped archive; `::open_each` unwraps one.
22
+ #
23
+ # @raise [SpatialFeatures::ImportError] when a remote source cannot be reached.
24
+ def open(file)
25
+ file = fetch(file)
26
+ file = normalize_file(file) if file.is_a?(StringIO)
27
+ return file
19
28
  end
20
29
 
21
- return files.map { |f| File.open(f) }
22
- end
30
+ # Returns the body of `path_or_url` as a String, without writing it to disk.
31
+ #
32
+ # @raise [SpatialFeatures::ImportError] when a remote source cannot be reached.
33
+ def read(path_or_url)
34
+ fetch(path_or_url).read
35
+ end
36
+
37
+ # Returns an open File for each source in `path_or_url`, unwrapping an archive when
38
+ # `unzip` is given a pattern its entries can match.
39
+ def open_each(path_or_url, unzip: nil, **unzip_options)
40
+ file = Download.open(path_or_url)
41
+ files = if unzip && Unzip.is_zip?(file)
42
+ find_in_zip(file, find: unzip, **unzip_options)
43
+ else
44
+ [file]
45
+ end
23
46
 
24
- def self.normalize_file(file)
25
- Tempfile.new.tap do |temp|
26
- temp.binmode
27
- temp.write(file.read)
28
- temp.rewind
47
+ return files.map { |f| File.open(f) }
29
48
  end
30
- end
31
49
 
32
- def self.entries(file)
33
- file = Kernel.open(file)
34
- file = normalize_file(file) if file.is_a?(StringIO)
35
- Unzip.entries(file)
36
- end
50
+ def normalize_file(file)
51
+ Tempfile.new.tap do |temp|
52
+ temp.binmode
53
+ temp.write(file.read)
54
+ temp.rewind
55
+ end
56
+ end
57
+
58
+ # Returns the entries of the archive at `file` without extracting them.
59
+ def entries(file)
60
+ file = fetch(file)
61
+ file = normalize_file(file) if file.is_a?(StringIO)
62
+ Unzip.entries(file)
63
+ end
64
+
65
+ def find_in_zip(file, find:, **unzip_options)
66
+ Unzip.paths(file, find: find, **unzip_options)
67
+ end
68
+
69
+ private
37
70
 
38
- def self.find_in_zip(file, find:, **unzip_options)
39
- Unzip.paths(file, find: find, **unzip_options)
71
+ # Returns an IO for `file`: fetched over the network when it is a remote URL, opened from
72
+ # disk when it is any other String, and left to open itself otherwise.
73
+ #
74
+ # @note A local path goes to `File.open`, never `URI.open`. `URI.open` hands anything
75
+ # that is not a URL to `Kernel#open`, which runs the name as a command when it begins
76
+ # with a pipe.
77
+ # @note Timeouts and the unreachable rescue apply only to a remote URL. `URI.open`
78
+ # rejects the timeouts when handed an already open file, and `Errno::ENOENT` for a
79
+ # local path is a `SystemCallError` that callers turn into a message for the person who
80
+ # uploaded the file, without naming the path the server looked in.
81
+ def fetch(file)
82
+ return URI.open(file) unless file.is_a?(String)
83
+ return File.open(file) unless file.match?(REMOTE_URL)
84
+
85
+ begin
86
+ URI.open(file, :open_timeout => timeout, :read_timeout => timeout)
87
+ rescue *UNREACHABLE_ERRORS => e
88
+ raise SpatialFeatures::ImportError, "This source could not be reached. #{e.message}"
89
+ end
90
+ end
40
91
  end
41
92
  end
42
93
  end
@@ -0,0 +1,42 @@
1
+ require 'open3'
2
+
3
+ module SpatialFeatures
4
+ # Runs the GDAL command line tools.
5
+ #
6
+ # Every argument reaches the tool as a single argv entry, so a path or a projection taken
7
+ # from an uploaded archive arrives as one string rather than as shell syntax.
8
+ module GDAL
9
+ class << self
10
+ # Returns what `tool` wrote to standard output.
11
+ #
12
+ # @param tool [String] the executable name, such as `ogr2ogr`.
13
+ # @param args [Array<String>] one argv entry each.
14
+ # @return [String] the output, empty when the tool wrote nothing.
15
+ # @raise [Errno::ENOENT] when the tool is not installed.
16
+ def capture(tool, *args)
17
+ Open3.capture2(*argv(tool, args)).first
18
+ end
19
+
20
+ # Runs `tool` for its exit status rather than its output.
21
+ #
22
+ # @param tool [String] the executable name, such as `ogr2ogr`.
23
+ # @param args [Array<String>] one argv entry each.
24
+ # @return [Boolean] true when the tool exited successfully.
25
+ # @raise [Errno::ENOENT] when the tool is not installed.
26
+ def run(tool, *args)
27
+ system(*argv(tool, args))
28
+ end
29
+
30
+ private
31
+
32
+ # Returns the argv to spawn `tool` with.
33
+ #
34
+ # @note The command is a two element array so that Ruby spawns the executable directly.
35
+ # Both `system` and `Open3` fall back to a shell when handed a lone string, which
36
+ # would put every argument here back in reach of shell parsing.
37
+ def argv(tool, args)
38
+ [[tool.to_s, tool.to_s], *args.map(&:to_s)]
39
+ end
40
+ end
41
+ end
42
+ end
@@ -1,9 +1,18 @@
1
1
  require 'digest/md5'
2
+ require 'json'
3
+ require 'tempfile'
2
4
  require 'spatial_features/importers/geo_json'
3
5
 
4
6
  module SpatialFeatures
5
7
  module Importers
6
8
  class ESRIGeoJSON < GeoJSON
9
+ # How many pages to walk before concluding the endpoint is ignoring `resultOffset` and
10
+ # serving the same features over and over. A service capped at the usual 1000 or 2000
11
+ # features per page would have to hold half a million features to reach this
12
+ # legitimately. Raise it for a layer that genuinely holds more.
13
+ class_attribute :max_pages
14
+ self.max_pages = 500
15
+
7
16
  def parsed_geojson
8
17
  @parsed_geojson ||= JSON.parse(geojson)
9
18
  end
@@ -14,12 +23,115 @@ module SpatialFeatures
14
23
 
15
24
  private
16
25
 
17
- def esri_json_to_geojson(url)
18
- if URI.parse(url).relative?
19
- `ogr2ogr -t_srs EPSG:4326 -f GeoJSON /dev/stdout "#{url}"` # It is a local file path
20
- else
21
- `ogr2ogr -t_srs EPSG:4326 -f GeoJSON /dev/stdout "#{url}" OGRGeoJSON`
26
+ # Returns the layer as GeoJSON. A relative path is read from disk; anything else is
27
+ # downloaded first, so OGR is always given a local file.
28
+ #
29
+ # @param path_or_url [String] a local file path, or the URL of an ArcGIS query endpoint.
30
+ # @return [String] a GeoJSON FeatureCollection in EPSG:4326.
31
+ # @note Downloading rather than passing the URL to OGR is what makes an endpoint offering
32
+ # only HTTPS 1.1 readable. GDAL's curl client gets an empty reply from those servers,
33
+ # which surfaces as `ERROR 1: Empty reply from server`.
34
+ def esri_json_to_geojson(path_or_url)
35
+ return ogr2ogr_to_geojson(path_or_url) if URI.parse(path_or_url).relative?
36
+
37
+ with_downloaded_file(path_or_url) do |path|
38
+ ogr2ogr_to_geojson(path)
39
+ end
40
+ end
41
+
42
+ # Returns the GeoJSON OGR reads out of the file at `path`, reprojected to EPSG:4326.
43
+ # OGR selects its driver by inspecting the content, so the file may hold either GeoJSON
44
+ # or ESRI JSON.
45
+ #
46
+ # @note No layer name is passed. OGR names a local file's layer after its basename, and
47
+ # naming a layer that does not exist fails the read.
48
+ def ogr2ogr_to_geojson(path)
49
+ GDAL.capture('ogr2ogr', '-t_srs', 'EPSG:4326', '-f', 'GeoJSON', '/dev/stdout', path)
50
+ end
51
+
52
+ # Downloads the query into a tempfile and yields its path, removing it afterwards.
53
+ def with_downloaded_file(url)
54
+ Tempfile.create(['esri_geojson', '.json']) do |tempfile|
55
+ tempfile.binmode
56
+ download_paginated(url, tempfile)
57
+ tempfile.close
58
+ return yield(tempfile.path)
59
+ end
60
+ end
61
+
62
+ # Walks the query's pages with `resultOffset` and writes them to `io` as one collection.
63
+ # ArcGIS endpoints cap each response at the service's `maxRecordCount`, commonly 1000 or
64
+ # 2000 features, and set `exceededTransferLimit` while more results are waiting.
65
+ #
66
+ # @note Raises `SpatialFeatures::ImportError` once `max_pages` requests have been made
67
+ # and the endpoint still reports more, since a server that ignores `resultOffset`
68
+ # otherwise repeats its first page until the process runs out of memory.
69
+ def download_paginated(url, io)
70
+ combined = nil
71
+ offset = 0
72
+ pages = 0
73
+
74
+ loop do
75
+ page = fetch_page(paginated_url(url, offset))
76
+ page_features = page['features'] || []
77
+
78
+ if combined.nil?
79
+ combined = page
80
+ else
81
+ combined['features'].concat(page_features)
82
+ end
83
+
84
+ break if page_features.empty? || !exceeded_transfer_limit?(page)
85
+
86
+ pages += 1
87
+ if pages >= max_pages
88
+ raise SpatialFeatures::ImportError,
89
+ "This layer was still reporting more features after #{max_pages} requests. " \
90
+ "The server may be ignoring the `resultOffset` parameter."
91
+ end
92
+
93
+ offset += page_features.length
22
94
  end
95
+
96
+ if combined
97
+ combined.delete('exceededTransferLimit')
98
+ combined['properties']&.delete('exceededTransferLimit')
99
+ io.write(JSON.dump(combined))
100
+ end
101
+ end
102
+
103
+ # Returns one page of the query.
104
+ #
105
+ # @return [Hash] the parsed response body.
106
+ # @raise [SpatialFeatures::ImportError] when the endpoint cannot be reached, or answers
107
+ # with a body that is not JSON. An endpoint that rejects a query replies with HTML or
108
+ # an error document, which the parse failure alone does not convey.
109
+ def fetch_page(url)
110
+ body = Download.read(url)
111
+ JSON.parse(body)
112
+ rescue JSON::ParserError
113
+ raise SpatialFeatures::ImportError,
114
+ "This layer did not return map data. The server replied with #{body.to_s[0, 100].inspect}."
115
+ end
116
+
117
+ # Returns true while the service reports that more features are waiting. Services set the
118
+ # flag at the top level or under `properties` depending on the response format.
119
+ def exceeded_transfer_limit?(page)
120
+ page['exceededTransferLimit'] || page.dig('properties', 'exceededTransferLimit')
121
+ end
122
+
123
+ # Returns `url` with `resultOffset` set to `offset`, replacing any the caller supplied.
124
+ # Returns it unchanged for the first page, so a service that does not paginate is asked
125
+ # exactly what the caller asked for.
126
+ def paginated_url(url, offset)
127
+ return url if offset.zero?
128
+
129
+ uri = URI.parse(url)
130
+ params = URI.decode_www_form(uri.query || '')
131
+ params.reject! { |key, _| key == 'resultOffset' }
132
+ params << ['resultOffset', offset.to_s]
133
+ uri.query = URI.encode_www_form(params)
134
+ uri.to_s
23
135
  end
24
136
  end
25
137
  end
@@ -55,8 +55,11 @@ module SpatialFeatures
55
55
  if proj4 == PROJ4_4326
56
56
  data[:geog] = wkt
57
57
  else
58
- data[:geog] = ActiveRecord::Base.connection.select_value <<-SQL
59
- SELECT ST_Transform(ST_GeomFromText('#{wkt}'), '#{proj4}', 4326) AS geog
58
+ # `proj4` is read out of the uploaded archive's .prj, so it is quoted before it
59
+ # reaches the statement.
60
+ conn = ActiveRecord::Base.connection
61
+ data[:geog] = conn.select_value <<-SQL
62
+ SELECT ST_Transform(ST_GeomFromText(#{conn.quote(wkt)}), #{conn.quote(proj4)}, 4326) AS geog
60
63
  SQL
61
64
  end
62
65
 
@@ -90,18 +93,27 @@ module SpatialFeatures
90
93
  end
91
94
 
92
95
  # Use OGR2OGR to reproject into EPSG:4326 so we can skip the reprojection step per-feature
96
+ #
97
+ # @note Both the projection and the path come from the uploaded archive, so they are
98
+ # passed as an argv list and no shell parses them. Assembling a command string here
99
+ # would let an uploader run commands of their choosing.
93
100
  def project_to_4326(file_path)
94
101
  output_path = Tempfile.create([::File.basename(file_path, '.shp') + '_epsg_4326_', '.shp']) { |file| file.path }
95
102
  return unless (proj4 = proj4_from_file(file_path))
96
- return unless system("ogr2ogr -s_srs '#{proj4}' -t_srs EPSG:4326 '#{output_path}' '#{file_path}'")
103
+ return unless GDAL.run('ogr2ogr', '-s_srs', proj4, '-t_srs', 'EPSG:4326', output_path, file_path)
97
104
  return ::File.open(output_path)
98
105
  end
99
106
 
107
+ # Returns the PROJ.4 projection string GDAL reads out of the file's .prj, or nil when
108
+ # it can't determine one. Returns nil when `gdalsrsinfo` is not installed, which
109
+ # `proj4_projection` reports.
100
110
  def proj4_from_file(file_path)
101
111
  # Sanitize: "'+proj=utm +zone=11 +datum=NAD83 +units=m +no_defs '\n" and lately
102
112
  # "+proj=utm +zone=11 +datum=NAD83 +units=m +no_defs \n" to
103
113
  # "+proj=utm +zone=11 +datum=NAD83 +units=m +no_defs"
104
- `gdalsrsinfo "#{file_path}" -o proj4`.strip.remove(/^'|'$/).presence
114
+ GDAL.capture('gdalsrsinfo', file_path, '-o', 'proj4').strip.remove(/^'|'$/).presence
115
+ rescue Errno::ENOENT
116
+ nil
105
117
  end
106
118
 
107
119
  # a zip archive may contain multiple SHP files
@@ -1,4 +1,5 @@
1
1
  require 'fileutils'
2
+ require 'pathname'
2
3
 
3
4
  module SpatialFeatures
4
5
  module Unzip
@@ -51,16 +52,26 @@ module SpatialFeatures
51
52
  end
52
53
  end
53
54
 
55
+ # Extracts the archive's entries and returns their paths, skipping entries that a name
56
+ # cannot place inside `tmpdir`.
57
+ #
58
+ # @param tmpdir [String] where to extract to. Must already exist, since the destination
59
+ # is resolved before anything is written. Defaults to a fresh temporary directory.
54
60
  def self.extract(file_path, tmpdir: nil, downcase: false)
55
61
  tmpdir ||= Dir.mktmpdir
62
+ root = Pathname.new(tmpdir).realpath
63
+
56
64
  [].tap do |paths|
57
65
  entries(file_path).each do |entry|
58
66
  next if entry.name =~ IGNORED_ENTRY_PATHS
67
+ next if entry.symlink?
59
68
 
60
69
  output_filename = entry.name
61
70
  output_filename = output_filename.downcase if downcase
62
71
 
63
- path = "#{tmpdir}/#{output_filename}"
72
+ path = contained_path(root, output_filename)
73
+ next unless path
74
+
64
75
  directory = File.dirname(path)
65
76
  basename = File.basename(path)
66
77
 
@@ -72,6 +83,24 @@ module SpatialFeatures
72
83
  end
73
84
  end
74
85
 
86
+ # Returns where an entry of this name lands under `root`, or nil when the name would place
87
+ # it outside. Entry names are stored in the archive verbatim, so they can carry `..`
88
+ # segments that climb out of the directory we extract into.
89
+ #
90
+ # @note `root` must already be a real path, and `::extract` skips symlink entries, so
91
+ # nothing beneath it is a symlink. `cleanpath` resolves `..` lexically, so a symlink
92
+ # under `root` would let an entry name walk back out of the directory unnoticed.
93
+ def self.contained_path(root, output_filename)
94
+ path = root.join(output_filename).cleanpath
95
+
96
+ return unless path.to_s.start_with?("#{root}#{File::SEPARATOR}")
97
+
98
+ # `cleanpath` drops the trailing separator that marks a directory entry, which
99
+ # `PathNotFound#extensions` reads to tell directories from the files it reports.
100
+ output_filename.end_with?(File::SEPARATOR) ? "#{path}#{File::SEPARATOR}" : path.to_s
101
+ end
102
+ private_class_method :contained_path
103
+
75
104
  def self.names(file_path)
76
105
  entries(file_path).collect(&:name)
77
106
  end
@@ -1,3 +1,3 @@
1
1
  module SpatialFeatures
2
- VERSION = "3.11.1"
2
+ VERSION = "3.12.0"
3
3
  end
@@ -10,6 +10,7 @@ require 'spatial_features/caching'
10
10
  require 'spatial_features/uncached_result'
11
11
  require 'spatial_features/venn_polygons'
12
12
  require 'spatial_features/controller_helpers/spatial_extensions'
13
+ require 'spatial_features/gdal'
13
14
  require 'spatial_features/download'
14
15
  require 'spatial_features/unzip'
15
16
  require 'spatial_features/utils'
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: spatial_features
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.11.1
4
+ version: 3.12.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Ryan Wallace
@@ -198,6 +198,7 @@ files:
198
198
  - lib/spatial_features/controller_helpers/spatial_extensions.rb
199
199
  - lib/spatial_features/download.rb
200
200
  - lib/spatial_features/engine.rb
201
+ - lib/spatial_features/gdal.rb
201
202
  - lib/spatial_features/has_spatial_features.rb
202
203
  - lib/spatial_features/has_spatial_features/feature_import.rb
203
204
  - lib/spatial_features/has_spatial_features/queued_spatial_processing.rb
@@ -236,7 +237,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
236
237
  - !ruby/object:Gem::Version
237
238
  version: '0'
238
239
  requirements: []
239
- rubygems_version: 4.0.5
240
+ rubygems_version: 3.7.2
240
241
  specification_version: 4
241
242
  summary: Adds spatial methods to a model.
242
243
  test_files: []