hamster-web 0.1.0.pre.2 → 0.1.0.pre.5
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 +42 -0
- data/README.md +576 -5
- data/lib/hamster/agent_guidance.rb +56 -0
- data/lib/hamster/application_graph.rb +336 -0
- data/lib/hamster/build/assets.rb +72 -0
- data/lib/hamster/build/callbacks.rb +124 -0
- data/lib/hamster/build/jobs.rb +78 -0
- data/lib/hamster/build/manifest.rb +31 -9
- data/lib/hamster/build/query_accessors.rb +18 -0
- data/lib/hamster/check.rb +122 -0
- data/lib/hamster/cli.rb +105 -12
- data/lib/hamster/data/persistence.rb +11 -6
- data/lib/hamster/data/read/nodes.rb +2 -0
- data/lib/hamster/data/read/schema.rb +28 -16
- data/lib/hamster/data/read/validator.rb +3 -0
- data/lib/hamster/data/record.rb +15 -1
- data/lib/hamster/data/table.rb +22 -3
- data/lib/hamster/database/database.rb +2 -25
- data/lib/hamster/database/migrator.rb +151 -0
- data/lib/hamster/database/pool.rb +7 -3
- data/lib/hamster/database/result.rb +3 -3
- data/lib/hamster/dev.rb +116 -0
- data/lib/hamster/endpoint_generator.rb +7 -0
- data/lib/hamster/form.rb +110 -0
- data/lib/hamster/generators/plan.rb +96 -0
- data/lib/hamster/generators/runner.rb +168 -0
- data/lib/hamster/jobs/adapters.rb +106 -0
- data/lib/hamster/jobs/postgres_queue.rb +146 -0
- data/lib/hamster/jobs/worker.rb +103 -0
- data/lib/hamster/jobs.rb +116 -0
- data/lib/hamster/migration.rb +36 -0
- data/lib/hamster/native_smoke.rb +53 -0
- data/lib/hamster/schema_validation.rb +4 -2
- data/lib/hamster/storage/disk.rb +89 -0
- data/lib/hamster/storage.rb +152 -0
- data/lib/hamster/test_database.rb +63 -0
- data/lib/hamster/test_runner.rb +29 -0
- data/lib/hamster/testing.rb +110 -0
- data/lib/hamster/web/action/base.rb +49 -4
- data/lib/hamster/web/application.rb +9 -0
- data/lib/hamster/web/assets.rb +28 -0
- data/lib/hamster/web/context.rb +122 -1
- data/lib/hamster/web/files.rb +118 -0
- data/lib/hamster/web/http.rb +4 -2
- data/lib/hamster/web/json.rb +39 -0
- data/lib/hamster/web/multipart.rb +138 -0
- data/lib/hamster/web/router.rb +13 -2
- data/lib/hamster/web/routing/base.rb +4 -2
- data/lib/hamster/web/turbo.rb +24 -0
- data/lib/hamster/web/version.rb +1 -1
- data/lib/hamster/web/view/form.rb +18 -1
- data/lib/hamster/web.rb +9 -0
- data/templates/app/.agents/skills/hamster-database/SKILL.md +29 -0
- data/templates/app/.agents/skills/hamster-endpoint/SKILL.md +27 -0
- data/templates/app/.dockerignore +19 -0
- data/templates/app/AGENTS.md +20 -7
- data/templates/app/Dockerfile +77 -0
- data/templates/app/Gemfile +5 -1
- data/templates/app/README.md +365 -2
- data/templates/app/app/application.rb +15 -0
- data/templates/app/app/assets/application.css +2 -0
- data/templates/app/app/assets/application.js +2 -0
- data/templates/app/app/assets/controllers/hello_controller.js +5 -0
- data/templates/app/app/assets/vendor/VERSIONS.md +12 -0
- data/templates/app/app/assets/vendor/stimulus.LICENSE.txt +9 -0
- data/templates/app/app/assets/vendor/stimulus.js +2563 -0
- data/templates/app/app/assets/vendor/turbo.LICENSE.txt +20 -0
- data/templates/app/app/assets/vendor/turbo.js +7178 -0
- data/templates/app/app/routes/mappings.rb +1 -0
- data/templates/app/app/routes/up/index/action.rb +14 -0
- data/templates/app/app/views/layouts/application.html.erb +2 -1
- data/templates/app/bin/hamster +8 -0
- data/templates/app/bin/server +13 -1
- data/templates/app/bin/worker +24 -0
- data/templates/app/config/application.rb +1 -1
- data/templates/app/config/deploy.worker.yml.example +32 -0
- data/templates/app/public/.keep +0 -0
- data/templates/app/test/home_test.rb +8 -0
- data/templates/app/test/native_http.rb +11 -0
- data/templates/app/test/native_server.rb +10 -0
- data/templates/app/test/test_helper.rb +8 -0
- metadata +58 -4
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
module Hamster
|
|
3
|
+
class Migration
|
|
4
|
+
attr_writer :connection
|
|
5
|
+
|
|
6
|
+
def execute(sql)
|
|
7
|
+
@connection.execute_script(sql)
|
|
8
|
+
end
|
|
9
|
+
|
|
10
|
+
def quote(name)
|
|
11
|
+
text = name.to_s
|
|
12
|
+
raise ArgumentError, "invalid identifier" if text.empty? || text.include?("\0")
|
|
13
|
+
'"' + text.gsub('"', '""') + '"'
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
def type_sql(type)
|
|
17
|
+
types = {integer: "INTEGER", bigint: "BIGINT", text: "TEXT", string: "VARCHAR(255)", boolean: "BOOLEAN", timestamp: "TIMESTAMP", decimal: "DECIMAL", binary: "BYTEA", date: "DATE", jsonb: "JSONB"}
|
|
18
|
+
types.fetch(type) { raise ArgumentError, "unsupported column type #{type.inspect}; use execute for custom SQL" }
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
def create_table(name, columns:)
|
|
22
|
+
definitions = columns.map { |column, type| "#{quote(column)} #{type_sql(type)}" }
|
|
23
|
+
raise ArgumentError, "columns required" if definitions.empty?
|
|
24
|
+
execute("CREATE TABLE #{quote(name)} (#{definitions.join(', ')})")
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
def drop_table(name); execute("DROP TABLE #{quote(name)}"); end
|
|
28
|
+
def add_column(table, column, type); execute("ALTER TABLE #{quote(table)} ADD COLUMN #{quote(column)} #{type_sql(type)}"); end
|
|
29
|
+
def remove_column(table, column); execute("ALTER TABLE #{quote(table)} DROP COLUMN #{quote(column)}"); end
|
|
30
|
+
def change_column(table, column, type); execute("ALTER TABLE #{quote(table)} ALTER COLUMN #{quote(column)} TYPE #{type_sql(type)}"); end
|
|
31
|
+
def add_index(table, columns, name:, unique: false)
|
|
32
|
+
execute("CREATE #{unique ? 'UNIQUE ' : ''}INDEX #{quote(name)} ON #{quote(table)} (#{Array(columns).map { |c| quote(c) }.join(', ')})")
|
|
33
|
+
end
|
|
34
|
+
def remove_index(name); execute("DROP INDEX #{quote(name)}"); end
|
|
35
|
+
end
|
|
36
|
+
end
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
require "tmpdir"
|
|
3
|
+
require "open3"
|
|
4
|
+
require "timeout"
|
|
5
|
+
require "net/http"
|
|
6
|
+
require "rbconfig"
|
|
7
|
+
|
|
8
|
+
module Hamster
|
|
9
|
+
module NativeSmoke
|
|
10
|
+
module_function
|
|
11
|
+
def run(root)
|
|
12
|
+
entry = File.join(root, "test/native_server.rb")
|
|
13
|
+
raise "Missing test/native_server.rb; add an explicit native test server" unless File.file?(entry)
|
|
14
|
+
spinner = Gem::Specification.find_by_name("spinel-spinner").full_gem_path
|
|
15
|
+
Dir.mktmpdir("hamster-native") do |temporary|
|
|
16
|
+
binary = File.join(temporary, "server")
|
|
17
|
+
flags = ["--require-gate", "-I", File.expand_path("..", __dir__), "-I", ENV.fetch("SPINNER_LIB", File.join(spinner, "lib")), "-I", root]
|
|
18
|
+
output, status = Open3.capture2e(ENV.fetch("SPINEL", "spinel"), entry, *flags, "-o", binary, chdir: root)
|
|
19
|
+
raise "Native compilation failed:\n#{output}" unless status.success?
|
|
20
|
+
log = File.join(temporary, "server.log")
|
|
21
|
+
pid = Process.spawn({"HOST" => "127.0.0.1", "PORT" => "0", "HAMSTER_ENV" => "test"}, binary, chdir: root, out: log, err: log)
|
|
22
|
+
begin
|
|
23
|
+
port = nil
|
|
24
|
+
Timeout.timeout(15) do
|
|
25
|
+
until port
|
|
26
|
+
contents = File.read(log)
|
|
27
|
+
port = contents[/SPINNER_READY \d+ (\d+)/, 1]&.to_i
|
|
28
|
+
raise "Native server exited:\n#{contents}" if Process.waitpid(pid, Process::WNOHANG)
|
|
29
|
+
sleep 0.05 unless port
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
response = Net::HTTP.start("127.0.0.1", port, nil, nil, nil, nil, open_timeout: 3, read_timeout: 3) { |http| http.get("/up") }
|
|
33
|
+
raise "Native /up returned #{response.code}" unless response.code == "200"
|
|
34
|
+
if File.file?(File.join(root, "test/native_http.rb"))
|
|
35
|
+
output, status = Open3.capture2e({"HAMSTER_TEST_URL" => "http://127.0.0.1:#{port}"}, RbConfig.ruby, "-I", File.expand_path("..", __dir__), "test/native_http.rb", chdir: root)
|
|
36
|
+
raise "Native HTTP assertions failed:\n#{output}" unless status.success?
|
|
37
|
+
end
|
|
38
|
+
ensure
|
|
39
|
+
begin
|
|
40
|
+
Process.kill("TERM", pid)
|
|
41
|
+
Timeout.timeout(12) { Process.waitpid(pid) }
|
|
42
|
+
rescue Errno::ESRCH, Errno::ECHILD
|
|
43
|
+
nil
|
|
44
|
+
rescue Timeout::Error
|
|
45
|
+
Process.kill("KILL", pid) rescue nil
|
|
46
|
+
Process.waitpid(pid) rescue nil
|
|
47
|
+
end
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
true
|
|
51
|
+
end
|
|
52
|
+
end
|
|
53
|
+
end
|
|
@@ -3,8 +3,10 @@ require_relative "data"
|
|
|
3
3
|
|
|
4
4
|
module Hamster
|
|
5
5
|
module SchemaValidation
|
|
6
|
-
def self.run(database, tables = Table.registry)
|
|
7
|
-
database.with_connection
|
|
6
|
+
def self.run(database, tables = Table.registry, detailed: false)
|
|
7
|
+
database.with_connection do |connection|
|
|
8
|
+
detailed ? Read::Schema.report(connection, tables) : Read::Schema.validate(connection, tables)
|
|
9
|
+
end
|
|
8
10
|
ensure
|
|
9
11
|
database.shutdown
|
|
10
12
|
end
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
require "digest"
|
|
3
|
+
require "securerandom"
|
|
4
|
+
module Hamster
|
|
5
|
+
module Storage
|
|
6
|
+
class Error < StandardError; end
|
|
7
|
+
class MissingBlob < Error; end
|
|
8
|
+
class IntegrityError < Error; end
|
|
9
|
+
class Unauthorized < Error; end
|
|
10
|
+
class InUse < Error; end
|
|
11
|
+
|
|
12
|
+
class Disk
|
|
13
|
+
def initialize(root)
|
|
14
|
+
@root = File.expand_path(root)
|
|
15
|
+
raise ArgumentError, "storage root cannot be a symlink" if File.symlink?(@root)
|
|
16
|
+
unless File.exist?(@root)
|
|
17
|
+
Dir.mkdir(@root, 0700)
|
|
18
|
+
# The pinned native Dir.mkdir binding ignores its optional mode.
|
|
19
|
+
File.chmod(0700, @root)
|
|
20
|
+
end
|
|
21
|
+
raise Error, "storage directory must be private (0700)" unless (File.stat(@root).mode & 0077) == 0
|
|
22
|
+
@canonical = File.realpath(@root)
|
|
23
|
+
@identity = File.stat(@root).ino
|
|
24
|
+
end
|
|
25
|
+
def path(key)
|
|
26
|
+
raise ArgumentError, "invalid blob key" unless key.is_a?(String) && key.match?(/\A[0-9a-f]{64}\z/)
|
|
27
|
+
raise Error, "storage root changed" if File.symlink?(@root) || File.realpath(@root) != @canonical || File.stat(@root).ino != @identity
|
|
28
|
+
File.join(@canonical, key)
|
|
29
|
+
end
|
|
30
|
+
def put(io, key:, max_bytes: 1048576)
|
|
31
|
+
target = path(key)
|
|
32
|
+
raise ArgumentError, "storage limit must be positive" unless max_bytes.is_a?(Integer) && max_bytes > 0
|
|
33
|
+
digest, size, created, complete = Digest::SHA256.new, 0, false, false
|
|
34
|
+
begin
|
|
35
|
+
File.open(target, File::WRONLY | File::CREAT | File::EXCL, 0600) do |file|
|
|
36
|
+
created = true
|
|
37
|
+
file.binmode
|
|
38
|
+
while (chunk = io.read(65536))
|
|
39
|
+
break if chunk.empty?
|
|
40
|
+
size += chunk.bytesize
|
|
41
|
+
raise Error, "blob exceeds storage limit" if size > max_bytes
|
|
42
|
+
digest.update(chunk)
|
|
43
|
+
file.write(chunk)
|
|
44
|
+
end
|
|
45
|
+
file.flush
|
|
46
|
+
file.fsync
|
|
47
|
+
end
|
|
48
|
+
complete = true
|
|
49
|
+
{"byte_size" => size, "checksum" => digest.hexdigest}
|
|
50
|
+
ensure
|
|
51
|
+
File.unlink(target) if created && !complete && File.exist?(target)
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
def open(key)
|
|
55
|
+
filename = path(key)
|
|
56
|
+
before = File.lstat(filename)
|
|
57
|
+
raise Error, "blob is not a regular file" unless before.file? && !before.symlink?
|
|
58
|
+
io = File.open(filename, "rb")
|
|
59
|
+
after = io.stat
|
|
60
|
+
unless after.file? && after.ino == before.ino && after.dev == before.dev
|
|
61
|
+
io.close
|
|
62
|
+
raise Error, "blob changed while opening"
|
|
63
|
+
end
|
|
64
|
+
io
|
|
65
|
+
rescue Errno::ENOENT
|
|
66
|
+
raise MissingBlob, "Blob file is missing"
|
|
67
|
+
end
|
|
68
|
+
def exists?(key)
|
|
69
|
+
filename = path(key)
|
|
70
|
+
File.file?(filename) && !File.symlink?(filename)
|
|
71
|
+
end
|
|
72
|
+
def delete(key)
|
|
73
|
+
filename = path(key)
|
|
74
|
+
raise Error, "refusing symlink blob" if File.symlink?(filename)
|
|
75
|
+
File.unlink(filename)
|
|
76
|
+
true
|
|
77
|
+
rescue Errno::ENOENT
|
|
78
|
+
false
|
|
79
|
+
end
|
|
80
|
+
def cleanup_temporary(older_than:)
|
|
81
|
+
Dir.glob(File.join(@canonical, ".pending-*")).count do |file|
|
|
82
|
+
next false if File.symlink?(file) || !File.file?(file) || File.mtime(file) >= older_than
|
|
83
|
+
File.unlink(file)
|
|
84
|
+
true
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
end
|
|
88
|
+
end
|
|
89
|
+
end
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
require_relative "storage/disk"
|
|
3
|
+
require_relative "data"
|
|
4
|
+
require_relative "web"
|
|
5
|
+
|
|
6
|
+
module Hamster
|
|
7
|
+
module Storage
|
|
8
|
+
class Attachments
|
|
9
|
+
def self.migration_sql
|
|
10
|
+
<<~SQL
|
|
11
|
+
CREATE TABLE hamster_blobs (
|
|
12
|
+
id TEXT PRIMARY KEY, storage_key TEXT NOT NULL UNIQUE, owner TEXT NOT NULL,
|
|
13
|
+
filename TEXT NOT NULL, content_type TEXT NOT NULL, byte_size BIGINT,
|
|
14
|
+
checksum TEXT, state TEXT NOT NULL CHECK (state IN ('pending','ready','deleting')),
|
|
15
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
16
|
+
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
|
17
|
+
);
|
|
18
|
+
CREATE TABLE hamster_attachments (
|
|
19
|
+
id TEXT PRIMARY KEY, blob_id TEXT NOT NULL REFERENCES hamster_blobs(id),
|
|
20
|
+
record_type TEXT NOT NULL, record_id TEXT NOT NULL, name TEXT NOT NULL,
|
|
21
|
+
owner TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
22
|
+
UNIQUE (blob_id, record_type, record_id, name)
|
|
23
|
+
);
|
|
24
|
+
CREATE INDEX hamster_attachments_blob ON hamster_attachments(blob_id);
|
|
25
|
+
CREATE INDEX hamster_blobs_cleanup ON hamster_blobs(state, updated_at);
|
|
26
|
+
SQL
|
|
27
|
+
end
|
|
28
|
+
def initialize(database:, adapter:)
|
|
29
|
+
@database, @adapter = database, adapter
|
|
30
|
+
end
|
|
31
|
+
def with_connection
|
|
32
|
+
@database.with_connection do |connection|
|
|
33
|
+
raise Error, "Storage operations require their own idle DB connection" unless connection.idle?
|
|
34
|
+
yield connection
|
|
35
|
+
end
|
|
36
|
+
end
|
|
37
|
+
def upload(io, filename:, owner:, content_type: "application/octet-stream", max_bytes: 1048576)
|
|
38
|
+
raise ArgumentError, "owner is required" if owner.to_s.empty?
|
|
39
|
+
display = filename.to_s.tr("\\", "/").split("/").last.to_s.gsub(/[\x00-\x1f\x7f]/, "")
|
|
40
|
+
raise ArgumentError, "filename must be valid UTF-8" unless display.valid_encoding?
|
|
41
|
+
display = "download.bin" if display.empty?
|
|
42
|
+
id, key = SecureRandom.hex(16), SecureRandom.hex(32)
|
|
43
|
+
with_connection do |connection|
|
|
44
|
+
connection.execute("INSERT INTO hamster_blobs(id,storage_key,owner,filename,content_type,state) VALUES($1,$2,$3,$4,$5,'pending')", [id, key, owner.to_s, display, content_type.to_s])
|
|
45
|
+
end
|
|
46
|
+
# Pending metadata commits before file creation. Failed writes or DB
|
|
47
|
+
# outages remain discoverable and recoverable by explicit cleanup.
|
|
48
|
+
metadata = @adapter.put(io, key: key, max_bytes: max_bytes)
|
|
49
|
+
with_connection do |connection|
|
|
50
|
+
connection.execute("UPDATE hamster_blobs SET byte_size=$1,checksum=$2,state='ready',updated_at=CURRENT_TIMESTAMP WHERE id=$3 AND state='pending'", [metadata.fetch("byte_size"), metadata.fetch("checksum"), id])
|
|
51
|
+
end
|
|
52
|
+
id
|
|
53
|
+
end
|
|
54
|
+
def authorize!(callback, metadata)
|
|
55
|
+
raise Unauthorized, "Attachment access denied" unless callback && callback.call(metadata.dup.freeze)
|
|
56
|
+
end
|
|
57
|
+
def attach(blob_id:, record_type:, record_id:, name:, owner:, authorize:)
|
|
58
|
+
with_connection do |connection|
|
|
59
|
+
connection.transaction do
|
|
60
|
+
blob = connection.execute("SELECT * FROM hamster_blobs WHERE id=$1 FOR UPDATE", [blob_id]).hashes.first
|
|
61
|
+
raise MissingBlob, "Blob is not ready" unless blob && blob["state"] == "ready"
|
|
62
|
+
raise Unauthorized, "Blob owner does not match" unless blob["owner"] == owner.to_s
|
|
63
|
+
metadata = blob.merge("record_type" => record_type.to_s, "record_id" => record_id.to_s, "name" => name.to_s)
|
|
64
|
+
authorize!(authorize, metadata)
|
|
65
|
+
row = connection.execute("INSERT INTO hamster_attachments(id,blob_id,record_type,record_id,name,owner) VALUES($1,$2,$3,$4,$5,$6) ON CONFLICT(blob_id,record_type,record_id,name) DO UPDATE SET name=EXCLUDED.name RETURNING id", [SecureRandom.hex(16), blob_id, record_type.to_s, record_id.to_s, name.to_s, owner.to_s]).hashes.first
|
|
66
|
+
row.fetch("id")
|
|
67
|
+
end
|
|
68
|
+
end
|
|
69
|
+
end
|
|
70
|
+
def metadata(id)
|
|
71
|
+
with_connection { |connection| connection.execute("SELECT * FROM hamster_blobs WHERE id=$1 AND state='ready'", [id]).hashes.first }
|
|
72
|
+
end
|
|
73
|
+
def open(id, authorize:)
|
|
74
|
+
blob = metadata(id)
|
|
75
|
+
raise MissingBlob, "Blob is not ready" unless blob
|
|
76
|
+
authorize!(authorize, blob)
|
|
77
|
+
io = @adapter.open(blob.fetch("storage_key"))
|
|
78
|
+
begin
|
|
79
|
+
digest, size = Digest::SHA256.new, 0
|
|
80
|
+
while (chunk = io.read(65536))
|
|
81
|
+
break if chunk.empty?
|
|
82
|
+
size += chunk.bytesize
|
|
83
|
+
digest.update(chunk)
|
|
84
|
+
end
|
|
85
|
+
unless size == blob.fetch("byte_size").to_i && digest.hexdigest == blob.fetch("checksum")
|
|
86
|
+
raise IntegrityError, "Blob checksum or size mismatch"
|
|
87
|
+
end
|
|
88
|
+
io.rewind
|
|
89
|
+
io
|
|
90
|
+
rescue Exception
|
|
91
|
+
io.close
|
|
92
|
+
raise
|
|
93
|
+
end
|
|
94
|
+
end
|
|
95
|
+
def download(id, authorize:)
|
|
96
|
+
blob = metadata(id)
|
|
97
|
+
raise MissingBlob, "Blob is not ready" unless blob
|
|
98
|
+
io = open(id, authorize: authorize)
|
|
99
|
+
begin
|
|
100
|
+
headers = Downloads.headers(blob.fetch("filename"), "application/octet-stream", "attachment")
|
|
101
|
+
[200, headers, FileBody.new(io)]
|
|
102
|
+
rescue Exception
|
|
103
|
+
io.close
|
|
104
|
+
raise
|
|
105
|
+
end
|
|
106
|
+
end
|
|
107
|
+
def detach(id, authorize:)
|
|
108
|
+
with_connection do |connection|
|
|
109
|
+
connection.transaction do
|
|
110
|
+
row = connection.execute("SELECT * FROM hamster_attachments WHERE id=$1 FOR UPDATE", [id]).hashes.first
|
|
111
|
+
next false unless row
|
|
112
|
+
authorize!(authorize, row)
|
|
113
|
+
connection.execute("DELETE FROM hamster_attachments WHERE id=$1", [id])
|
|
114
|
+
true
|
|
115
|
+
end
|
|
116
|
+
end
|
|
117
|
+
end
|
|
118
|
+
def delete(id, authorize:)
|
|
119
|
+
blob = with_connection do |connection|
|
|
120
|
+
connection.transaction do
|
|
121
|
+
row = connection.execute("SELECT * FROM hamster_blobs WHERE id=$1 FOR UPDATE", [id]).hashes.first
|
|
122
|
+
next nil unless row
|
|
123
|
+
authorize!(authorize, row)
|
|
124
|
+
references = connection.execute("SELECT id FROM hamster_attachments WHERE blob_id=$1 LIMIT 1", [id]).rows
|
|
125
|
+
raise InUse, "Blob still has attachment references" unless references.empty?
|
|
126
|
+
connection.execute("UPDATE hamster_blobs SET state='deleting',updated_at=CURRENT_TIMESTAMP WHERE id=$1", [id])
|
|
127
|
+
row
|
|
128
|
+
end
|
|
129
|
+
end
|
|
130
|
+
return false unless blob
|
|
131
|
+
@adapter.delete(blob.fetch("storage_key"))
|
|
132
|
+
with_connection { |connection| connection.execute("DELETE FROM hamster_blobs WHERE id=$1 AND state='deleting'", [id]) }
|
|
133
|
+
true
|
|
134
|
+
end
|
|
135
|
+
# Privileged maintenance; caller deliberately chooses a grace period.
|
|
136
|
+
def cleanup(older_than:, limit: 100)
|
|
137
|
+
raise ArgumentError, "cleanup limit must be positive" unless limit.is_a?(Integer) && limit > 0
|
|
138
|
+
candidates = with_connection do |connection|
|
|
139
|
+
connection.execute("SELECT b.id FROM hamster_blobs b WHERE b.updated_at < $1 AND NOT EXISTS (SELECT 1 FROM hamster_attachments a WHERE a.blob_id=b.id) ORDER BY b.updated_at,b.id LIMIT $2", [older_than, limit]).hashes
|
|
140
|
+
end
|
|
141
|
+
candidates.map do |row|
|
|
142
|
+
begin
|
|
143
|
+
delete(row.fetch("id"), authorize: ->(_metadata) { true })
|
|
144
|
+
{"id" => row["id"], "deleted" => true}
|
|
145
|
+
rescue InUse
|
|
146
|
+
{"id" => row["id"], "deleted" => false}
|
|
147
|
+
end
|
|
148
|
+
end
|
|
149
|
+
end
|
|
150
|
+
end
|
|
151
|
+
end
|
|
152
|
+
end
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
require "securerandom"
|
|
3
|
+
require_relative "data"
|
|
4
|
+
require_relative "database/migrator"
|
|
5
|
+
|
|
6
|
+
module Hamster
|
|
7
|
+
module Testing
|
|
8
|
+
# Own a fresh database for the duration of the block; never reuse a named DB.
|
|
9
|
+
module TestDatabase
|
|
10
|
+
module_function
|
|
11
|
+
def configuration(env)
|
|
12
|
+
raise ArgumentError, "Test databases require HAMSTER_ENV=test" unless env["HAMSTER_ENV"] == "test"
|
|
13
|
+
raise ArgumentError, "Use HAMSTER_TEST_DATABASE=1 to opt into disposable DB tests" unless env["HAMSTER_TEST_DATABASE"] == "1"
|
|
14
|
+
raise ArgumentError, "DATABASE_URL is not accepted for test databases" if env["DATABASE_URL"]
|
|
15
|
+
raise ArgumentError, "Use TEST_DATABASE_* settings, not DATABASE_NAME" if env["DATABASE_NAME"]
|
|
16
|
+
host = env.fetch("TEST_DATABASE_HOST", "127.0.0.1")
|
|
17
|
+
unless %w[127.0.0.1 localhost ::1].include?(host) || env["HAMSTER_TEST_ALLOW_REMOTE"] == "1"
|
|
18
|
+
raise ArgumentError, "Remote test hosts require HAMSTER_TEST_ALLOW_REMOTE=1"
|
|
19
|
+
end
|
|
20
|
+
values = {"DATABASE_USERNAME" => env.fetch("TEST_DATABASE_USERNAME"), "DATABASE_PASSWORD" => env.fetch("TEST_DATABASE_PASSWORD", ""),
|
|
21
|
+
"DATABASE_HOST" => host, "DATABASE_PORT" => env.fetch("TEST_DATABASE_PORT", "5432"),
|
|
22
|
+
"DATABASE_NAME" => "hamster_test_#{Process.pid}_#{SecureRandom.hex(8)}", "HAMSTER_ENV" => "test",
|
|
23
|
+
"DATABASE_ADMIN_NAME" => "postgres", "DATABASE_ADMIN_USERNAME" => env.fetch("TEST_DATABASE_ADMIN_USERNAME", env.fetch("TEST_DATABASE_USERNAME")),
|
|
24
|
+
"DATABASE_ADMIN_PASSWORD" => env.fetch("TEST_DATABASE_ADMIN_PASSWORD", env.fetch("TEST_DATABASE_PASSWORD", ""))}
|
|
25
|
+
Database::Configuration.from_env(values)
|
|
26
|
+
end
|
|
27
|
+
def rollback(database)
|
|
28
|
+
database.with_connection do |connection|
|
|
29
|
+
raise "Test transaction requires an idle connection" unless connection.idle?
|
|
30
|
+
connection.execute("BEGIN")
|
|
31
|
+
begin
|
|
32
|
+
yield connection
|
|
33
|
+
ensure
|
|
34
|
+
connection.execute("ROLLBACK") unless connection.idle?
|
|
35
|
+
end
|
|
36
|
+
end
|
|
37
|
+
end
|
|
38
|
+
def with_database(migrations_path:, env: ENV)
|
|
39
|
+
config = configuration(env)
|
|
40
|
+
# Load only after guardrails pass. Apps make the vendored pg driver available.
|
|
41
|
+
require_relative "database/postgres"
|
|
42
|
+
created = Database::Admin.create!(config)
|
|
43
|
+
raise "Refusing to reuse an existing test database" unless created
|
|
44
|
+
database = Database.new(config, migrations_path: migrations_path)
|
|
45
|
+
begin
|
|
46
|
+
database.migrate!
|
|
47
|
+
yield database
|
|
48
|
+
ensure
|
|
49
|
+
database.shutdown
|
|
50
|
+
admin = Database::Configuration.new(adapter: "postgres", host: config.host, port: config.port, database: "postgres",
|
|
51
|
+
username: config.admin_username, password: config.admin_password, pool_size: 1, checkout_timeout: 5)
|
|
52
|
+
connection = Database::Connection.new(Database::Postgres.connect(admin))
|
|
53
|
+
begin
|
|
54
|
+
raise "Unsafe test database name" unless config.database.match?(/\Ahamster_test_[0-9]+_[0-9a-f]{16}\z/)
|
|
55
|
+
connection.execute_script("DROP DATABASE \"#{config.database}\"")
|
|
56
|
+
ensure
|
|
57
|
+
connection.close
|
|
58
|
+
end
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
end
|
|
63
|
+
end
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
require "json"
|
|
3
|
+
require "open3"
|
|
4
|
+
require "rbconfig"
|
|
5
|
+
module Hamster
|
|
6
|
+
module TestRunner
|
|
7
|
+
module_function
|
|
8
|
+
def run(root, arguments)
|
|
9
|
+
args = arguments.dup
|
|
10
|
+
json = !!args.delete("--json")
|
|
11
|
+
raise ArgumentError, "Usage: test [test/path] [--json]" unless args.length <= 1 && args.none? { |arg| arg.start_with?("-") }
|
|
12
|
+
base = File.realpath(File.join(root, "test"))
|
|
13
|
+
target = args.empty? ? base : File.expand_path(args.first, root)
|
|
14
|
+
raise ArgumentError, "test path must be inside test/" unless File.realpath(target).start_with?(base + "/") || File.realpath(target) == base
|
|
15
|
+
files = File.directory?(target) ? Dir.glob(File.join(target, "**/*_test.rb")).sort : [target]
|
|
16
|
+
files.each do |path|
|
|
17
|
+
raise ArgumentError, "invalid test file" unless path.end_with?(".rb") && File.realpath(path).start_with?(base + "/")
|
|
18
|
+
end
|
|
19
|
+
raise ArgumentError, "No tests found" if files.empty?
|
|
20
|
+
output, status = Open3.capture2e({"HAMSTER_ENV" => "test"}, RbConfig.ruby, "-I", File.expand_path("..", __dir__), "-Itest", "-e", 'ARGV.each { |path| require File.expand_path(path) }', *files, chdir: root)
|
|
21
|
+
if json
|
|
22
|
+
puts JSON.generate({"format_version" => 1, "valid" => status.success?, "files" => files.map { |path| path.delete_prefix(root + "/") }, "exit_status" => status.exitstatus, "output" => output})
|
|
23
|
+
else
|
|
24
|
+
puts output
|
|
25
|
+
end
|
|
26
|
+
status.success? ? 0 : 1
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
end
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
# CRuby test tooling; never required by native application entrypoints.
|
|
3
|
+
require "minitest/autorun"
|
|
4
|
+
require "stringio"
|
|
5
|
+
require "uri"
|
|
6
|
+
require "json"
|
|
7
|
+
require "securerandom"
|
|
8
|
+
require_relative "web"
|
|
9
|
+
|
|
10
|
+
module Hamster
|
|
11
|
+
module Testing
|
|
12
|
+
class Response
|
|
13
|
+
attr_reader :status, :headers, :body
|
|
14
|
+
def initialize(status, headers, body)
|
|
15
|
+
@status, @headers, @body = status, headers, body
|
|
16
|
+
end
|
|
17
|
+
def json; JSON.parse(body); end
|
|
18
|
+
def content_type; headers.fetch("content-type", "").split(";", 2).first; end
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
class Client
|
|
22
|
+
UNSET = Object.new.freeze
|
|
23
|
+
def initialize(application)
|
|
24
|
+
@application = application
|
|
25
|
+
end
|
|
26
|
+
def request(method, path, headers: {}, form: nil, json: UNSET, body: nil)
|
|
27
|
+
raise ArgumentError, "choose one request body format" if [!form.nil?, json != UNSET, !body.nil?].count(true) > 1
|
|
28
|
+
uri = URI.parse(path)
|
|
29
|
+
raise ArgumentError, "request path must be absolute" unless uri.path.start_with?("/")
|
|
30
|
+
env = {"REQUEST_METHOD" => method.upcase, "PATH_INFO" => uri.path, "QUERY_STRING" => uri.query.to_s,
|
|
31
|
+
"HTTP_HOST" => uri.host || "localhost", "rack.url_scheme" => uri.scheme || "http"}
|
|
32
|
+
headers.each do |name, value|
|
|
33
|
+
key = name.to_s.upcase.tr("-", "_")
|
|
34
|
+
env[%w[CONTENT_TYPE CONTENT_LENGTH].include?(key) ? key : "HTTP_#{key}"] = value
|
|
35
|
+
end
|
|
36
|
+
if form
|
|
37
|
+
body = URI.encode_www_form(form)
|
|
38
|
+
env["CONTENT_TYPE"] ||= "application/x-www-form-urlencoded"
|
|
39
|
+
elsif json != UNSET
|
|
40
|
+
body = JSONValue.generate(json)
|
|
41
|
+
env["CONTENT_TYPE"] ||= "application/json"
|
|
42
|
+
end
|
|
43
|
+
body = body.to_s.b
|
|
44
|
+
input = StringIO.new(body)
|
|
45
|
+
env["CONTENT_LENGTH"] = body.bytesize.to_s
|
|
46
|
+
env["rack.input"] = input
|
|
47
|
+
response = nil
|
|
48
|
+
begin
|
|
49
|
+
response = @application.call(env)
|
|
50
|
+
bytes = +"".b
|
|
51
|
+
response[2].each { |chunk| bytes << chunk.b } unless method.upcase == "HEAD"
|
|
52
|
+
Response.new(response[0], response[1], bytes)
|
|
53
|
+
ensure
|
|
54
|
+
response[2].close if response && response[2].respond_to?(:close)
|
|
55
|
+
input.close
|
|
56
|
+
end
|
|
57
|
+
end
|
|
58
|
+
def get(path, **options); request("GET", path, **options); end
|
|
59
|
+
def post(path, **options); request("POST", path, **options); end
|
|
60
|
+
def patch(path, **options); request("PATCH", path, **options); end
|
|
61
|
+
def delete(path, **options); request("DELETE", path, **options); end
|
|
62
|
+
def head(path, **options); request("HEAD", path, **options); end
|
|
63
|
+
|
|
64
|
+
def multipart(path, fields: {}, files: {}, headers: {})
|
|
65
|
+
boundary = "hamster-test-#{SecureRandom.hex(12)}"
|
|
66
|
+
bytes = +"".b
|
|
67
|
+
fields.each do |name, values|
|
|
68
|
+
Array(values).each { |value| bytes << part(boundary, name, nil, nil, value.to_s) }
|
|
69
|
+
end
|
|
70
|
+
files.each do |name, values|
|
|
71
|
+
(values.is_a?(Array) ? values : [values]).each do |file|
|
|
72
|
+
data = file.fetch(:data)
|
|
73
|
+
data = data.read if data.respond_to?(:read)
|
|
74
|
+
bytes << part(boundary, name, file.fetch(:filename), file.fetch(:content_type, "application/octet-stream"), data)
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
bytes << "--#{boundary}--\r\n"
|
|
78
|
+
post(path, body: bytes, headers: headers.merge("Content-Type" => "multipart/form-data; boundary=#{boundary}"))
|
|
79
|
+
end
|
|
80
|
+
def part(boundary, name, filename, type, bytes)
|
|
81
|
+
[name, filename, type].compact.each do |value|
|
|
82
|
+
raise ArgumentError, "invalid multipart test metadata" if value.to_s.match?(/[\r\n"\\]/)
|
|
83
|
+
end
|
|
84
|
+
disposition = "form-data; name=\"#{name}\""
|
|
85
|
+
disposition += "; filename=\"#{filename}\"" if filename
|
|
86
|
+
"--#{boundary}\r\nContent-Disposition: #{disposition}\r\n#{type ? "Content-Type: #{type}\r\n" : ''}\r\n".b + bytes.b + "\r\n"
|
|
87
|
+
end
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
module Assertions
|
|
91
|
+
def assert_status(expected, response)
|
|
92
|
+
assert_equal Action::Base.status_code(expected), response.status
|
|
93
|
+
end
|
|
94
|
+
def assert_content_type(expected, response)
|
|
95
|
+
assert_equal expected, response.content_type
|
|
96
|
+
end
|
|
97
|
+
def assert_html(text, response)
|
|
98
|
+
assert_content_type "text/html", response
|
|
99
|
+
assert_includes response.body.force_encoding("UTF-8"), text
|
|
100
|
+
end
|
|
101
|
+
def assert_json(expected, response)
|
|
102
|
+
assert_content_type "application/json", response
|
|
103
|
+
assert_equal expected, response.json
|
|
104
|
+
end
|
|
105
|
+
end
|
|
106
|
+
class Test < Minitest::Test
|
|
107
|
+
include Assertions
|
|
108
|
+
end
|
|
109
|
+
end
|
|
110
|
+
end
|
|
@@ -2,8 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
module Hamster
|
|
4
4
|
module Action
|
|
5
|
+
module Callbacks
|
|
6
|
+
def before_action(name); end
|
|
7
|
+
def after_action(name); end
|
|
8
|
+
end
|
|
9
|
+
|
|
5
10
|
class Base
|
|
6
|
-
|
|
11
|
+
extend Callbacks
|
|
12
|
+
UNSET = :__hamster_unset_response__
|
|
13
|
+
STATUSES = {ok: 200, created: 201, no_content: 204, bad_request: 400, not_acceptable: 406, unsupported_media_type: 415, payload_too_large: 413, see_other: 303, unauthorized: 401, forbidden: 403,
|
|
7
14
|
not_found: 404, method_not_allowed: 405, unprocessable_entity: 422,
|
|
8
15
|
upgrade_required: 426, service_unavailable: 503}.freeze
|
|
9
16
|
attr_reader :context
|
|
@@ -17,14 +24,52 @@ module Hamster
|
|
|
17
24
|
@context = context
|
|
18
25
|
end
|
|
19
26
|
|
|
27
|
+
def self.before_action(name); end
|
|
28
|
+
def self.after_action(name); end
|
|
29
|
+
|
|
30
|
+
def dispatch
|
|
31
|
+
halted = run_before_actions
|
|
32
|
+
return halted unless halted.nil?
|
|
33
|
+
response = callback_response(call)
|
|
34
|
+
run_after_actions(response)
|
|
35
|
+
rescue StandardError
|
|
36
|
+
response[2].close if response && response[2].respond_to?(:close)
|
|
37
|
+
raise
|
|
38
|
+
end
|
|
39
|
+
|
|
20
40
|
private
|
|
21
41
|
|
|
22
|
-
def
|
|
42
|
+
def run_before_actions; nil; end
|
|
43
|
+
def run_after_actions(response); response; end
|
|
44
|
+
|
|
45
|
+
def callback_response(response)
|
|
46
|
+
unless response.is_a?(Array) && response.length == 3 && response[0].is_a?(Integer) && response[0] >= 100 && response[0] <= 599 && response[1].is_a?(Hash) && (response[2].respond_to?(:each) || response[0] == 101)
|
|
47
|
+
raise ArgumentError, "callback/action must return an HTTP response or nil (callbacks only)"
|
|
48
|
+
end
|
|
49
|
+
response
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def respond(view: nil, body: nil, json: UNSET, locals: {}, layout: "layouts/application",
|
|
23
53
|
status: :ok, type: :html, headers: {})
|
|
24
|
-
|
|
54
|
+
count = (view.nil? ? 0 : 1) + (body.nil? ? 0 : 1) + (json == UNSET ? 0 : 1)
|
|
55
|
+
raise ArgumentError, "respond requires exactly one of view:, body:, or json:" unless count == 1
|
|
56
|
+
unless json == UNSET
|
|
57
|
+
body = JSONValue.generate(json)
|
|
58
|
+
type = :json
|
|
59
|
+
end
|
|
25
60
|
raise ArgumentError, "respond locals: must be a Hash" unless locals.is_a?(Hash)
|
|
26
61
|
body = Hamster::View.render(view, locals, layout: layout) if view
|
|
27
|
-
Http.response(status, body, headers, type: type)
|
|
62
|
+
Http.response(status, body, context.response_headers(headers), type: type)
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
def send_file(path, root:, filename: nil, content_type: "application/octet-stream", disposition: "attachment")
|
|
66
|
+
Downloads.file(path, root: root, filename: filename, content_type: content_type, disposition: disposition)
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
def send_data(data, filename:, content_type: "application/octet-stream", disposition: "attachment")
|
|
70
|
+
headers = Downloads.headers(filename, content_type, disposition)
|
|
71
|
+
body = data.is_a?(String) ? [data.b] : FileBody.new(data)
|
|
72
|
+
[200, headers, body]
|
|
28
73
|
end
|
|
29
74
|
|
|
30
75
|
def redirect_to(path, cookie: nil)
|
|
@@ -3,20 +3,29 @@
|
|
|
3
3
|
module Hamster
|
|
4
4
|
class Application
|
|
5
5
|
attr_reader :database
|
|
6
|
+
attr_writer :upload_options
|
|
6
7
|
|
|
7
8
|
def initialize(routes:, database: nil)
|
|
8
9
|
@router = Router.new(routes)
|
|
9
10
|
@database = database
|
|
11
|
+
Jobs.database = database if database
|
|
12
|
+
@upload_options = {}
|
|
10
13
|
end
|
|
11
14
|
|
|
12
15
|
def call(env)
|
|
16
|
+
asset = Assets.response(env)
|
|
17
|
+
return asset if asset
|
|
18
|
+
env["hamster.upload_options"] = @upload_options
|
|
13
19
|
return @router.call(env) unless database
|
|
14
20
|
database.with_connection { |connection| @router.call(env, connection) }
|
|
21
|
+
rescue RequestBodyError => error
|
|
22
|
+
Http.response(error.status, error.message)
|
|
15
23
|
rescue StandardError
|
|
16
24
|
Http.response(500, "<!doctype html><title>Server error</title><h1>Server error</h1>")
|
|
17
25
|
end
|
|
18
26
|
|
|
19
27
|
def shutdown
|
|
28
|
+
Jobs.shutdown
|
|
20
29
|
database.shutdown if database
|
|
21
30
|
end
|
|
22
31
|
end
|