Skip to content

Commit 611b2cd

Browse files
authored
Merge pull request #25 from openaustralia/download-sqlite-database
Add morph download for a scraper's sqlite database
2 parents ca6c5dc + 866adcf commit 611b2cd

7 files changed

Lines changed: 307 additions & 41 deletions

File tree

‎.rubocop_todo.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ Metrics/MethodLength:
3636
# Offense count: 1
3737
# Configuration parameters: CountComments, CountAsOne.
3838
Metrics/ModuleLength:
39-
Max: 124
39+
Max: 163
4040

4141
# Offense count: 1
4242
# Configuration parameters: ExpectMatchingDefinition, CheckDefinitionPathHierarchy, CheckDefinitionPathHierarchyRoots, Regex, IgnoreExecutableScripts, AllowedAcronyms.

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1919

2020
### Added
2121

22+
- `morph download` command that downloads a scraper's sqlite database from
23+
morph.io to `data.sqlite`, working out the scraper name from the git remote
24+
when it isn't given explicitly
2225
- SimpleCov coverage reporting and a much expanded test suite (CLI and HTTP behaviour
2326
tested with WebMock, no network access in tests)
2427

‎README.md‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,16 @@ you'd rather not wait for the upload, leave it out with
3535
The first time you run it, it will ask for your morph.io API key, which it
3636
saves in `~/.morph`.
3737

38+
To download the sqlite database of a scraper from morph.io to `data.sqlite`
39+
in your current directory
40+
41+
morph download
42+
43+
That works out which scraper you mean from the git remote of the current
44+
directory. You can also name the scraper explicitly
45+
46+
morph download openaustralia/example_scraper
47+
3848
For help
3949

4050
morph help
@@ -44,8 +54,6 @@ For help
4454
It uploads your code every time. So if it's big it might take a little while.
4555
Scrapers are not usually so I'm hoping this won't really be an issue.
4656

47-
It doesn't yet return you the resulting sqlite database.
48-
4957
## Development
5058

5159
After checking out the repo, run `bundle install` to install dependencies.

‎lib/morph-cli.rb‎

Lines changed: 55 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
require 'yaml'
33
require 'find'
44
require 'json'
5+
require 'open3'
56
require 'pathname'
67
require 'tempfile'
78
require 'fileutils'
@@ -21,25 +22,23 @@ def self.execute(directory, _development, env_config, skip_data: false)
2122
end
2223

2324
database_path = MorphCLI.database_path(directory)
24-
if skip_data
25-
all_paths.delete(database_path)
26-
database_path = nil
27-
end
25+
all_paths.delete(database_path)
26+
database_path = nil if skip_data
2827

29-
size = MorphCLI.get_dir_size(directory, all_paths)
28+
size = MorphCLI.get_dir_size(directory, all_paths + [database_path].compact)
3029
puts "Uploading #{size}#{" (including #{database_path})" if database_path}..."
3130

3231
file = MorphCLI.create_tar(directory, all_paths)
3332

34-
scraper_output = run(file, env_config)
33+
scraper_output = run(file, env_config, directory, database_path)
3534

3635
puts "Scraper didn't output anything, but it ran successfully." unless scraper_output
3736
end
3837

3938
# Uploads the code to the server, streams the run output to the local
4039
# stdout/stderr and returns whether the scraper itself wrote anything
4140
# to stdout or stderr
42-
def self.run(file, env_config)
41+
def self.run(file, env_config, directory, database_path)
4342
connection = Faraday.new(url: env_config[:base_url]) do |f|
4443
f.request :multipart
4544
f.response :raise_error
@@ -49,10 +48,18 @@ def self.run(file, env_config)
4948
buffer = +""
5049
scraper_output = false
5150
connection.post("/run") do |req|
52-
req.body = {
51+
body = {
5352
api_key: env_config[:api_key],
5453
code: Faraday::Multipart::FilePart.new(file, "application/gzip")
5554
}
55+
if database_path
56+
body[:database] = Faraday::Multipart::FilePart.new(
57+
File.join(directory, database_path),
58+
"application/octet-stream",
59+
database_path
60+
)
61+
end
62+
req.body = body
5663
# 10 minutes should be "enough for everyone", right?
5764
# Setting :timeout to nil in the config will disable the timeout
5865
# entirely. The Faraday default is 60 seconds.
@@ -72,6 +79,46 @@ def self.run(file, env_config)
7279
scraper_output
7380
end
7481

82+
def self.download(directory, env_config, scraper)
83+
connection = Faraday.new(url: env_config[:base_url]) do |f|
84+
f.response :raise_error
85+
f.adapter Faraday.default_adapter
86+
end
87+
88+
# Download to a tempfile in the same directory first so a failed download
89+
# doesn't clobber an existing database
90+
tempfile = Tempfile.new(["morph", ".sqlite"], directory)
91+
tempfile.binmode
92+
93+
begin
94+
connection.get("/#{scraper}/data.sqlite") do |req|
95+
req.params[:key] = env_config[:api_key]
96+
req.options.timeout = env_config.fetch(:timeout, 600)
97+
req.options.on_data = proc do |chunk, _overall_received_bytes, env|
98+
tempfile.write(chunk) if env.status == 200
99+
end
100+
end
101+
102+
tempfile.close
103+
File.rename(tempfile.path, File.join(directory, "data.sqlite"))
104+
ensure
105+
tempfile.close unless tempfile.closed?
106+
FileUtils.rm_f(tempfile.path)
107+
end
108+
109+
size = Filesize.from("#{File.size(File.join(directory, 'data.sqlite'))} B").pretty
110+
puts "Saved #{size} to data.sqlite"
111+
end
112+
113+
# The name of the scraper on morph (owner/name), worked out from the git
114+
# remote of the given directory. Returns nil if it can't be worked out.
115+
def self.scraper_name(directory)
116+
url, _stderr, status = Open3.capture3("git", "-C", directory, "config", "--get", "remote.origin.url")
117+
return nil unless status.success?
118+
119+
url.strip[%r{([^/:]+/[^/:]+?)(?:\.git)?\z}, 1]
120+
end
121+
75122
# Writes the line to the local stdout/stderr and returns the name of the
76123
# stream it came from
77124
def self.log(line)

‎lib/morph-cli/cli.rb‎

Lines changed: 56 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -18,33 +18,30 @@ def self.exit_on_failure?
1818
desc: "Don't upload the local data.sqlite database with the scraper"
1919

2020
def execute
21-
config = MorphCLI.load_config
22-
env_config = if options[:dev]
23-
config[:development]
24-
else
25-
config[:production]
26-
end
21+
env_config = load_env_config
2722

28-
config = ask_and_save_api_key(env_config, config) if env_config[:api_key].nil?
23+
with_working_api_key(env_config) do
24+
MorphCLI.execute(options[:directory], options[:dev], env_config, skip_data: options[:skip_data])
25+
end
26+
end
27+
28+
desc 'download [SCRAPER]', 'download the sqlite database of a scraper from morph'
29+
option :directory, default: Dir.getwd
30+
31+
def download(scraper = nil)
32+
env_config = load_env_config
33+
34+
scraper ||= MorphCLI.scraper_name(options[:directory])
35+
if scraper.nil?
36+
warn "Can't work out the scraper name from the git remote. Give it explicitly with: morph download OWNER/SCRAPER"
37+
exit(1)
38+
end
2939

30-
api_key_is_valid = false
31-
until api_key_is_valid
32-
begin
33-
MorphCLI.execute(options[:directory], options[:dev], env_config, skip_data: options[:skip_data])
34-
api_key_is_valid = true
35-
rescue Faraday::UnauthorizedError
36-
puts "Your key isn't working. Let's try again."
37-
config = ask_and_save_api_key(env_config, config)
38-
rescue Faraday::ConnectionFailed => e
39-
warn "Morph doesn't look to be running at #{env_config[:base_url]} (#{e})"
40-
exit(1)
41-
rescue Faraday::ServerError => e
42-
warn "Uh oh. Something has gone wrong on the Morph server at #{env_config[:base_url]} (#{e})"
43-
exit(1)
44-
rescue Faraday::Error => e
45-
warn "Request to #{env_config[:base_url]} failed (#{e})"
46-
exit(1)
47-
end
40+
with_working_api_key(env_config) do
41+
MorphCLI.download(options[:directory], env_config, scraper)
42+
rescue Faraday::ResourceNotFound
43+
warn "Can't find a database for #{scraper} on #{env_config[:base_url]}. Has the scraper run successfully?"
44+
exit(1)
4845
end
4946
end
5047

@@ -55,10 +52,41 @@ def version
5552
end
5653

5754
no_commands do
58-
def ask_and_save_api_key(env_config, config)
55+
def load_env_config
56+
@config = MorphCLI.load_config
57+
env_config = if options[:dev]
58+
@config[:development]
59+
else
60+
@config[:production]
61+
end
62+
63+
ask_and_save_api_key(env_config) if env_config[:api_key].nil?
64+
env_config
65+
end
66+
67+
# Runs the block, prompting for a new API key and retrying if the server
68+
# rejects the current one, and turning other request failures into
69+
# friendly errors
70+
def with_working_api_key(env_config)
71+
yield
72+
rescue Faraday::UnauthorizedError
73+
puts "Your key isn't working. Let's try again."
74+
ask_and_save_api_key(env_config)
75+
retry
76+
rescue Faraday::ConnectionFailed => e
77+
warn "Morph doesn't look to be running at #{env_config[:base_url]} (#{e})"
78+
exit(1)
79+
rescue Faraday::ServerError => e
80+
warn "Uh oh. Something has gone wrong on the Morph server at #{env_config[:base_url]} (#{e})"
81+
exit(1)
82+
rescue Faraday::Error => e
83+
warn "Request to #{env_config[:base_url]} failed (#{e})"
84+
exit(1)
85+
end
86+
87+
def ask_and_save_api_key(env_config)
5988
env_config[:api_key] = ask("What is your key? (Go to #{env_config[:base_url]}/settings)")
60-
MorphCLI.save_config(config)
61-
config
89+
MorphCLI.save_config(@config)
6290
end
6391
end
6492
end

‎spec/morph_cli/cli_spec.rb‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,4 +112,91 @@
112112
end.to output(%r{Request to https://morph\.io failed}).to_stderr
113113
end
114114
end
115+
116+
describe 'download' do
117+
let(:config) do
118+
{
119+
development: { base_url: 'http://127.0.0.1:3000', api_key: 'dev-key' },
120+
production: { base_url: 'https://morph.io', api_key: 'prod-key' }
121+
}
122+
end
123+
124+
before do
125+
allow(MorphCLI).to receive(:load_config).and_return(config)
126+
allow(MorphCLI).to receive(:save_config)
127+
end
128+
129+
it 'downloads the database of the given scraper with the production config' do
130+
allow(MorphCLI).to receive(:download)
131+
132+
described_class.start(['download', 'openaustralia/scraper', '--directory', '/somewhere'])
133+
134+
expect(MorphCLI).to have_received(:download)
135+
.with('/somewhere', config[:production], 'openaustralia/scraper')
136+
end
137+
138+
it 'works out the scraper name from the git remote when none is given' do
139+
allow(MorphCLI).to receive(:download)
140+
allow(MorphCLI).to receive(:scraper_name).with('/somewhere').and_return('openaustralia/scraper')
141+
142+
described_class.start(['download', '--directory', '/somewhere'])
143+
144+
expect(MorphCLI).to have_received(:download)
145+
.with('/somewhere', config[:production], 'openaustralia/scraper')
146+
end
147+
148+
it 'exits with an error when the scraper name cannot be worked out' do
149+
allow(MorphCLI).to receive(:scraper_name).and_return(nil)
150+
151+
expect do
152+
expect { described_class.start(['download']) }
153+
.to raise_error(SystemExit) { |e| expect(e.status).to eq(1) }
154+
end.to output(/Can't work out the scraper name/).to_stderr
155+
end
156+
157+
it 'uses the development config when --dev is given' do
158+
allow(MorphCLI).to receive(:download)
159+
160+
described_class.start(['download', 'openaustralia/scraper', '--dev'])
161+
162+
expect(MorphCLI).to have_received(:download)
163+
.with(anything, config[:development], 'openaustralia/scraper')
164+
end
165+
166+
it 'asks for a new API key and retries when the server rejects it' do
167+
attempts = 0
168+
allow(MorphCLI).to receive(:download) do
169+
attempts += 1
170+
raise Faraday::UnauthorizedError, '401' if attempts == 1
171+
end
172+
allow(Thor::LineEditor).to receive(:readline).and_return('fresh-key')
173+
174+
expect { described_class.start(['download', 'openaustralia/scraper']) }
175+
.to output(/Your key isn't working\. Let's try again\./).to_stdout
176+
177+
expect(attempts).to eq(2)
178+
expect(config[:production][:api_key]).to eq('fresh-key')
179+
expect(MorphCLI).to have_received(:save_config).with(config)
180+
end
181+
182+
it 'exits with an error when the scraper has no downloadable database' do
183+
allow(MorphCLI).to receive(:download)
184+
.and_raise(Faraday::ResourceNotFound, '404')
185+
186+
expect do
187+
expect { described_class.start(['download', 'openaustralia/scraper']) }
188+
.to raise_error(SystemExit) { |e| expect(e.status).to eq(1) }
189+
end.to output(%r{Can't find a database for openaustralia/scraper on https://morph\.io}).to_stderr
190+
end
191+
192+
it 'exits with an error when morph is not reachable' do
193+
allow(MorphCLI).to receive(:download)
194+
.and_raise(Faraday::ConnectionFailed, 'connection refused')
195+
196+
expect do
197+
expect { described_class.start(['download', 'openaustralia/scraper']) }
198+
.to raise_error(SystemExit) { |e| expect(e.status).to eq(1) }
199+
end.to output(%r{Morph doesn't look to be running at https://morph\.io}).to_stderr
200+
end
201+
end
115202
end

0 commit comments

Comments
 (0)