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
data/lib/hamster/data/record.rb
CHANGED
|
@@ -67,12 +67,26 @@ module Hamster
|
|
|
67
67
|
|
|
68
68
|
def [](name)
|
|
69
69
|
key = name.to_sym
|
|
70
|
+
assert_record_column_enabled!(key)
|
|
70
71
|
raise MissingAttributeError, "Unloaded attribute #{key}" if @partial && !@attributes.key?(key)
|
|
71
|
-
raise MissingAttributeError, "Undeclared attribute #{key}" unless self.class.columns.key?(key)
|
|
72
72
|
@attributes[key]
|
|
73
73
|
end
|
|
74
74
|
|
|
75
|
+
def assert_record_column_enabled!(name)
|
|
76
|
+
if RUBY_ENGINE == "ruby"
|
|
77
|
+
self.class.assert_column_enabled!(name)
|
|
78
|
+
raise MissingAttributeError, "Undeclared attribute #{name}" unless self.class.columns.key?(name.to_sym)
|
|
79
|
+
else
|
|
80
|
+
assert_compiled_record_column_enabled!(name)
|
|
81
|
+
end
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
def assert_compiled_record_column_enabled!(name)
|
|
85
|
+
raise MissingAttributeError, "Run hamster manifest to generate record schema guards"
|
|
86
|
+
end
|
|
87
|
+
|
|
75
88
|
def write_attribute(name, value)
|
|
89
|
+
assert_record_column_enabled!(name)
|
|
76
90
|
@attributes[name.to_sym] = value
|
|
77
91
|
end
|
|
78
92
|
end
|
data/lib/hamster/data/table.rb
CHANGED
|
@@ -9,25 +9,44 @@ module Hamster
|
|
|
9
9
|
REGISTRY = []
|
|
10
10
|
|
|
11
11
|
def self.inherited(child)
|
|
12
|
-
child.set_metadata(table_name, schema_name, columns) unless self == Table
|
|
12
|
+
child.set_metadata(table_name, schema_name, columns, enabled?) unless self == Table
|
|
13
13
|
REGISTRY << child
|
|
14
14
|
end
|
|
15
15
|
|
|
16
|
-
def self.set_metadata(name, schema, definitions)
|
|
16
|
+
def self.set_metadata(name, schema, definitions, enabled = true)
|
|
17
17
|
@table_name = name
|
|
18
18
|
@schema_name = schema
|
|
19
19
|
@columns = definitions.dup
|
|
20
|
+
@enabled = enabled
|
|
20
21
|
end
|
|
21
22
|
|
|
22
23
|
def self.registry
|
|
23
24
|
REGISTRY.dup.freeze
|
|
24
25
|
end
|
|
25
26
|
|
|
26
|
-
def self.table(name, schema: "public")
|
|
27
|
+
def self.table(name, schema: "public", enabled: true)
|
|
28
|
+
raise Read::ValidationError, "Table enabled must be boolean" unless [true, false].include?(enabled)
|
|
29
|
+
@enabled = enabled
|
|
27
30
|
@table_name = Read.identifier(name)
|
|
28
31
|
@schema_name = Read.identifier(schema)
|
|
29
32
|
end
|
|
30
33
|
|
|
34
|
+
def self.enabled?
|
|
35
|
+
@enabled != false
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def self.assert_enabled!
|
|
39
|
+
raise Read::DisabledTableError, "#{schema_name}.#{table_name}: table is disabled" unless enabled?
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def self.assert_column_enabled!(name)
|
|
43
|
+
assert_enabled!
|
|
44
|
+
definition = columns[name.to_sym]
|
|
45
|
+
if definition && !definition[:enabled]
|
|
46
|
+
raise Read::DisabledColumnError, "#{schema_name}.#{table_name}.#{name}: column is disabled"
|
|
47
|
+
end
|
|
48
|
+
end
|
|
49
|
+
|
|
31
50
|
def self.table_name
|
|
32
51
|
@table_name || name.split("::").last.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2').gsub(/([a-z0-9])([A-Z])/, '\1_\2').downcase + "s"
|
|
33
52
|
end
|
|
@@ -36,29 +36,6 @@ module Hamster
|
|
|
36
36
|
end
|
|
37
37
|
end
|
|
38
38
|
|
|
39
|
-
def migrate!
|
|
40
|
-
with_connection do |connection|
|
|
41
|
-
connection.transaction do
|
|
42
|
-
connection.execute(<<~SQL)
|
|
43
|
-
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
44
|
-
version TEXT PRIMARY KEY,
|
|
45
|
-
applied_at TIMESTAMPTZ NOT NULL
|
|
46
|
-
)
|
|
47
|
-
SQL
|
|
48
|
-
|
|
49
|
-
applied = rows(connection, "SELECT version FROM schema_migrations ORDER BY version")
|
|
50
|
-
migration_files.each do |version, path|
|
|
51
|
-
next if applied.any? { |row| row["version"] == version }
|
|
52
|
-
|
|
53
|
-
connection.execute_script(File.read(path))
|
|
54
|
-
connection.execute("INSERT INTO schema_migrations (version, applied_at) VALUES ($1, $2)",
|
|
55
|
-
[version, Time.now.utc.iso8601])
|
|
56
|
-
end
|
|
57
|
-
end
|
|
58
|
-
end
|
|
59
|
-
true
|
|
60
|
-
end
|
|
61
|
-
|
|
62
39
|
def verify!
|
|
63
40
|
with_connection do |connection|
|
|
64
41
|
present = rows(connection, "SELECT to_regclass('public.schema_migrations') AS name")
|
|
@@ -81,8 +58,8 @@ module Hamster
|
|
|
81
58
|
end
|
|
82
59
|
|
|
83
60
|
def migration_files
|
|
84
|
-
files = Dir[File.join(@migrations_path, "*.sql")].sort.map do |path|
|
|
85
|
-
[File.basename(path
|
|
61
|
+
files = Dir[File.join(@migrations_path, "*.{sql,rb}")].sort.map do |path|
|
|
62
|
+
[File.basename(path).sub(/\.(sql|rb)\z/, "").split("_", 2).first, path]
|
|
86
63
|
end
|
|
87
64
|
versions = files.map(&:first)
|
|
88
65
|
raise ConfigurationError, "duplicate migration versions" unless versions.uniq.length == versions.length
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
# Tooling only: never require this file from hamster/web or hamster/data.
|
|
3
|
+
require "digest"
|
|
4
|
+
require "json"
|
|
5
|
+
require_relative "../migration"
|
|
6
|
+
|
|
7
|
+
module Hamster
|
|
8
|
+
class Database
|
|
9
|
+
class Migrator
|
|
10
|
+
def initialize(database, path)
|
|
11
|
+
@database, @path = database, path
|
|
12
|
+
end
|
|
13
|
+
|
|
14
|
+
def files
|
|
15
|
+
entries = Dir[File.join(@path, "*.{rb,sql}")].sort.map do |path|
|
|
16
|
+
name = File.basename(path)
|
|
17
|
+
version = name.split("_", 2).first.sub(/\.(rb|sql)\z/, "")
|
|
18
|
+
raise ConfigurationError, "invalid migration version #{name}" unless version.match?(/\A[0-9]+\z/)
|
|
19
|
+
{"version" => version, "file" => name, "checksum" => Digest::SHA256.file(path).hexdigest}
|
|
20
|
+
end
|
|
21
|
+
raise ConfigurationError, "duplicate migration versions" unless entries.map { |f| f["version"] }.uniq.size == entries.size
|
|
22
|
+
entries.sort_by { |f| f["version"] }
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def tracking(c)
|
|
26
|
+
c.execute("CREATE TABLE IF NOT EXISTS schema_migrations (version TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL)")
|
|
27
|
+
c.execute("ALTER TABLE schema_migrations ADD COLUMN IF NOT EXISTS file TEXT, ADD COLUMN IF NOT EXISTS checksum TEXT")
|
|
28
|
+
c.execute("CREATE TABLE IF NOT EXISTS hamster_migration_events (id BIGSERIAL PRIMARY KEY, version TEXT NOT NULL, direction TEXT NOT NULL, file TEXT NOT NULL, checksum TEXT NOT NULL, occurred_at TIMESTAMPTZ NOT NULL)")
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def locked
|
|
32
|
+
@database.with_connection do |c|
|
|
33
|
+
c.execute("SELECT pg_advisory_lock(726144807)")
|
|
34
|
+
begin
|
|
35
|
+
c.transaction { tracking(c) }
|
|
36
|
+
yield c
|
|
37
|
+
ensure
|
|
38
|
+
c.execute("SELECT pg_advisory_unlock(726144807)")
|
|
39
|
+
end
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
def report(c)
|
|
44
|
+
applied = c.execute("SELECT version, file, checksum, applied_at FROM schema_migrations ORDER BY version").hashes
|
|
45
|
+
disk = files
|
|
46
|
+
versions = (disk + applied).map { |f| f["version"] }.uniq.sort
|
|
47
|
+
versions.map do |v|
|
|
48
|
+
f = disk.find { |e| e["version"] == v }
|
|
49
|
+
row = applied.find { |e| e["version"] == v }
|
|
50
|
+
state = if row.nil? then "pending"
|
|
51
|
+
elsif f.nil? then "missing"
|
|
52
|
+
elsif row["checksum"].nil? then "legacy_unknown"
|
|
53
|
+
elsif row["checksum"] != f["checksum"] || row["file"] != f["file"] then "modified"
|
|
54
|
+
else "applied" end
|
|
55
|
+
{"version" => v, "file" => f ? f["file"] : row["file"], "status" => state,
|
|
56
|
+
"checksum" => row ? row["checksum"] : f["checksum"], "applied_at" => row && row["applied_at"]}
|
|
57
|
+
end
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def status
|
|
61
|
+
locked { |c| report(c) }
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def history
|
|
65
|
+
locked do |c|
|
|
66
|
+
{"format_version" => 1, "migrations" => report(c),
|
|
67
|
+
"events" => c.execute("SELECT version, direction, file, checksum, occurred_at FROM hamster_migration_events ORDER BY id").hashes}
|
|
68
|
+
end
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
def preflight(c)
|
|
72
|
+
rows = report(c)
|
|
73
|
+
bad = rows.select { |r| %w[missing modified].include?(r["status"]) }
|
|
74
|
+
raise ConfigurationError, "migration integrity failure: #{bad.map { |r| r['version'] + ':' + r['status'] }.join(', ')}" unless bad.empty?
|
|
75
|
+
rows
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
def migrate!
|
|
79
|
+
locked do |c|
|
|
80
|
+
pending = preflight(c).select { |r| r["status"] == "pending" }
|
|
81
|
+
pending.each { |f| apply(c, f, "up") }
|
|
82
|
+
end
|
|
83
|
+
true
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
def rollback!(steps)
|
|
87
|
+
raise ArgumentError, "STEP must be positive" unless steps.is_a?(Integer) && steps > 0
|
|
88
|
+
locked do |c|
|
|
89
|
+
preflight(c)
|
|
90
|
+
selected = c.execute("SELECT version, file, checksum FROM schema_migrations ORDER BY applied_at DESC, version DESC").hashes.take(steps)
|
|
91
|
+
operations = selected.map do |f|
|
|
92
|
+
raise ConfigurationError, "irreversible migration #{f['version']}" unless f["file"]&.end_with?(".rb")
|
|
93
|
+
migration = load_migration(f)
|
|
94
|
+
raise ConfigurationError, "missing down for #{f['version']}" unless migration.respond_to?(:down)
|
|
95
|
+
[f, migration]
|
|
96
|
+
end
|
|
97
|
+
operations.each { |f, m| apply(c, f, "down", m) }
|
|
98
|
+
end
|
|
99
|
+
true
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
def load_migration(f)
|
|
103
|
+
scope = Module.new
|
|
104
|
+
Kernel.load(File.join(@path, f.fetch("file")), scope)
|
|
105
|
+
classes = scope.constants(false).map { |name| scope.const_get(name) }.select { |k| k.is_a?(Class) && k < Hamster::Migration }
|
|
106
|
+
raise ConfigurationError, "expected one Hamster::Migration in #{f['file']}" unless classes.size == 1
|
|
107
|
+
classes.first.new
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
def apply(c, f, direction, migration = nil)
|
|
111
|
+
c.transaction do
|
|
112
|
+
if f.fetch("file").end_with?(".sql")
|
|
113
|
+
c.execute_script(File.read(File.join(@path, f["file"])))
|
|
114
|
+
else
|
|
115
|
+
migration ||= load_migration(f)
|
|
116
|
+
migration.connection = c
|
|
117
|
+
direction == "up" ? migration.up : migration.down
|
|
118
|
+
end
|
|
119
|
+
now = Time.now.utc.iso8601(6)
|
|
120
|
+
if direction == "up"
|
|
121
|
+
c.execute("INSERT INTO schema_migrations (version, file, checksum, applied_at) VALUES ($1,$2,$3,$4)", [f["version"], f["file"], f["checksum"], now])
|
|
122
|
+
else
|
|
123
|
+
c.execute("DELETE FROM schema_migrations WHERE version = $1", [f["version"]])
|
|
124
|
+
end
|
|
125
|
+
c.execute("INSERT INTO hamster_migration_events (version,direction,file,checksum,occurred_at) VALUES ($1,$2,$3,$4,$5)", [f["version"], direction, f["file"], f["checksum"], now])
|
|
126
|
+
end
|
|
127
|
+
end
|
|
128
|
+
end
|
|
129
|
+
end
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
module Hamster
|
|
133
|
+
class Database
|
|
134
|
+
def migrate!
|
|
135
|
+
Migrator.new(self, @migrations_path).migrate!
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
def rollback!(steps = 1)
|
|
139
|
+
Migrator.new(self, @migrations_path).rollback!(steps)
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
def migration_status
|
|
143
|
+
Migrator.new(self, @migrations_path).status
|
|
144
|
+
end
|
|
145
|
+
|
|
146
|
+
def migration_history
|
|
147
|
+
Migrator.new(self, @migrations_path).history
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
end
|
|
151
|
+
end
|
|
@@ -35,16 +35,19 @@ module Hamster
|
|
|
35
35
|
end
|
|
36
36
|
end
|
|
37
37
|
|
|
38
|
-
|
|
39
|
-
@lock.synchronize do
|
|
38
|
+
retain = @lock.synchronize do
|
|
40
39
|
@borrowed -= 1
|
|
41
40
|
if reusable && !@closed
|
|
42
41
|
@available << connection
|
|
42
|
+
@ready.broadcast
|
|
43
|
+
true
|
|
43
44
|
else
|
|
44
45
|
@total -= 1
|
|
46
|
+
@ready.broadcast
|
|
47
|
+
false
|
|
45
48
|
end
|
|
46
|
-
@ready.broadcast
|
|
47
49
|
end
|
|
50
|
+
connection.close unless retain
|
|
48
51
|
end
|
|
49
52
|
|
|
50
53
|
def shutdown
|
|
@@ -52,6 +55,7 @@ module Hamster
|
|
|
52
55
|
@closed = true
|
|
53
56
|
connections = @available
|
|
54
57
|
@available = []
|
|
58
|
+
@total -= connections.length
|
|
55
59
|
@ready.broadcast
|
|
56
60
|
connections
|
|
57
61
|
end
|
|
@@ -20,9 +20,9 @@ module Hamster
|
|
|
20
20
|
|
|
21
21
|
def hashes
|
|
22
22
|
rows.map do |row|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
23
|
+
result = {}
|
|
24
|
+
columns.each_with_index { |column, index| result[column] = row[index] }
|
|
25
|
+
result
|
|
26
26
|
end
|
|
27
27
|
end
|
|
28
28
|
end
|
data/lib/hamster/dev.rb
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
require "digest"
|
|
3
|
+
require "json"
|
|
4
|
+
require "timeout"
|
|
5
|
+
require_relative "check"
|
|
6
|
+
|
|
7
|
+
module Hamster
|
|
8
|
+
module Dev
|
|
9
|
+
class Runner
|
|
10
|
+
attr_reader :root, :state, :pid
|
|
11
|
+
def initialize(root, build: nil, output: $stdout, debounce: 0.2, interval: 0.1, drain_timeout: 12)
|
|
12
|
+
@root, @output = File.realpath(root), output
|
|
13
|
+
@build = build || -> { CLI.dispatch("build") }
|
|
14
|
+
@debounce, @interval, @drain_timeout = debounce, interval, drain_timeout
|
|
15
|
+
raise ArgumentError, "watch intervals must be positive" unless [debounce, interval, drain_timeout].all? { |v| v.is_a?(Numeric) && v.finite? && v > 0 }
|
|
16
|
+
name = JSON.parse(File.read(File.join(root, "config/hamster.json"))).fetch("name")
|
|
17
|
+
@binary = ENV.fetch("HAMSTER_SERVER_BINARY", File.join(root, "bin/#{name}-server"))
|
|
18
|
+
@state = :stopped
|
|
19
|
+
end
|
|
20
|
+
def now; Process.clock_gettime(Process::CLOCK_MONOTONIC); end
|
|
21
|
+
def say(message)
|
|
22
|
+
@output.puts("hamster dev: #{message}")
|
|
23
|
+
@output.flush
|
|
24
|
+
end
|
|
25
|
+
def snapshot
|
|
26
|
+
paths = Dir.glob("{app,db,config,lib,public,assets,test}/**/*", base: root).select { |p| File.file?(File.join(root, p)) }
|
|
27
|
+
paths += %w[Gemfile Gemfile.lock spin.toml spin.lock].select { |p| File.file?(File.join(root, p)) }
|
|
28
|
+
paths.reject! { |path| path.start_with?("public/assets/") }
|
|
29
|
+
paths -= %w[config/manifest.rb config/view_registry.rb config/callback_registry.rb config/asset_registry.rb config/job_registry.rb]
|
|
30
|
+
paths.sort.to_h { |path| [path, Digest::SHA256.file(File.join(root, path)).hexdigest] }
|
|
31
|
+
rescue Errno::ENOENT
|
|
32
|
+
retry
|
|
33
|
+
end
|
|
34
|
+
def stop!
|
|
35
|
+
@stopping = true
|
|
36
|
+
end
|
|
37
|
+
def stop_server
|
|
38
|
+
return unless @pid
|
|
39
|
+
begin
|
|
40
|
+
Process.kill("TERM", -@pid)
|
|
41
|
+
Timeout.timeout(@drain_timeout) { 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
|
+
ensure
|
|
48
|
+
@pid = nil
|
|
49
|
+
@state = :stopped
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
def rebuild(expected)
|
|
53
|
+
@state = :building
|
|
54
|
+
started = now
|
|
55
|
+
say("running CRuby source checks, then native Spinel build")
|
|
56
|
+
paths = Dir.glob("{app,db,config}/**/*.rb", base: root)
|
|
57
|
+
invalid = paths.find { |path| !Ripper.sexp(File.read(File.join(root, path))) }
|
|
58
|
+
raise "#{invalid}: invalid Ruby syntax" if invalid
|
|
59
|
+
@build.call
|
|
60
|
+
report = Check.run(root)
|
|
61
|
+
raise report["diagnostics"].map { |d| "#{d['path']}:#{d['line']}: #{d['message']}" }.join("\n") unless report["valid"]
|
|
62
|
+
return false if @stopping || snapshot != expected
|
|
63
|
+
raise "Native executable missing after build: #{@binary}" unless File.executable?(@binary)
|
|
64
|
+
@pid = Process.spawn(@binary, chdir: root, pgroup: true)
|
|
65
|
+
@state = :running
|
|
66
|
+
say("native server started pid=#{@pid}; rebuild #{format('%.3f', now - started)}s (request tests were not run)")
|
|
67
|
+
true
|
|
68
|
+
rescue StandardError => error
|
|
69
|
+
@state = :failed
|
|
70
|
+
say("build failed; server stopped\n#{error.message}")
|
|
71
|
+
false
|
|
72
|
+
end
|
|
73
|
+
def run
|
|
74
|
+
previous = {}
|
|
75
|
+
%w[INT TERM].each { |signal| previous[signal] = Signal.trap(signal) { stop! } }
|
|
76
|
+
observed = snapshot
|
|
77
|
+
dirty_at = now - @debounce
|
|
78
|
+
say("watching app/views/routes/config; Ctrl-C stops server and watcher")
|
|
79
|
+
until @stopping
|
|
80
|
+
current = snapshot
|
|
81
|
+
if current != observed
|
|
82
|
+
stop_server
|
|
83
|
+
observed = current
|
|
84
|
+
dirty_at = now
|
|
85
|
+
say("source changed; server stopped until a successful build")
|
|
86
|
+
end
|
|
87
|
+
if dirty_at && now - dirty_at >= @debounce
|
|
88
|
+
expected = observed
|
|
89
|
+
rebuild(expected)
|
|
90
|
+
after = snapshot
|
|
91
|
+
if after != expected
|
|
92
|
+
observed = after
|
|
93
|
+
dirty_at = now
|
|
94
|
+
else
|
|
95
|
+
dirty_at = nil
|
|
96
|
+
end
|
|
97
|
+
end
|
|
98
|
+
if @pid && Process.waitpid(@pid, Process::WNOHANG)
|
|
99
|
+
@pid = nil
|
|
100
|
+
@state = :failed
|
|
101
|
+
say("native server exited; waiting for source changes")
|
|
102
|
+
end
|
|
103
|
+
sleep @interval
|
|
104
|
+
end
|
|
105
|
+
ensure
|
|
106
|
+
stop_server
|
|
107
|
+
previous&.each { |signal, handler| Signal.trap(signal, handler) }
|
|
108
|
+
end
|
|
109
|
+
end
|
|
110
|
+
def self.run(root, args)
|
|
111
|
+
raise ArgumentError, "Usage: dev" unless args.empty?
|
|
112
|
+
Runner.new(root).run
|
|
113
|
+
0
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
end
|
data/lib/hamster/form.rb
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
module Hamster
|
|
3
|
+
class Form
|
|
4
|
+
CONTROL_FIELDS = %w[csrf_token _method].freeze
|
|
5
|
+
TYPES = [:string, :integer, :boolean].freeze
|
|
6
|
+
MESSAGES = {"missing" => "is required", "blank" => "must not be blank", "malformed" => "has an invalid format",
|
|
7
|
+
"too_short" => "is too short", "too_long" => "is too long", "unauthorized" => "is not permitted",
|
|
8
|
+
"unknown_fields" => "contains undeclared fields"}.freeze
|
|
9
|
+
attr_reader :errors, :error_codes
|
|
10
|
+
def self.inherited(child)
|
|
11
|
+
child.set_definition(fields, @model, @operation)
|
|
12
|
+
end
|
|
13
|
+
def self.set_definition(fields, model, operation)
|
|
14
|
+
@fields, @model, @operation = fields.dup, model, operation
|
|
15
|
+
end
|
|
16
|
+
def self.fields; (@fields || {}).dup; end
|
|
17
|
+
def self.model(table, operation: :create)
|
|
18
|
+
raise ArgumentError, "form operation must be create or update" unless [:create, :update].include?(operation)
|
|
19
|
+
@model, @operation = table, operation
|
|
20
|
+
end
|
|
21
|
+
def self.model_class; @model; end
|
|
22
|
+
def self.operation; @operation || :create; end
|
|
23
|
+
def self.field(name, type: :string, required: false, min_length: nil, max_length: nil, sensitive: false)
|
|
24
|
+
key = name.to_s
|
|
25
|
+
raise ArgumentError, "reserved form control field" if CONTROL_FIELDS.include?(key)
|
|
26
|
+
raise ArgumentError, "invalid form field" unless key.match?(/\A[a-z][a-z0-9_]*\z/)
|
|
27
|
+
raise ArgumentError, "field shadows form method" if Form.method_defined?(key) || Form.private_method_defined?(key)
|
|
28
|
+
raise ArgumentError, "unsupported input type" unless TYPES.include?(type)
|
|
29
|
+
raise ArgumentError, "form flags must be boolean" unless [true, false].include?(required) && [true, false].include?(sensitive)
|
|
30
|
+
[min_length, max_length].compact.each { |v| raise ArgumentError, "length must be nonnegative" unless v.is_a?(Integer) && v >= 0 }
|
|
31
|
+
raise ArgumentError, "inverted length bounds" if min_length && max_length && min_length > max_length
|
|
32
|
+
@fields = fields.merge(key => {type: type, required: required, min_length: min_length, max_length: max_length, sensitive: sensitive}.freeze)
|
|
33
|
+
define_method(key) { self[key] } if RUBY_ENGINE == "ruby"
|
|
34
|
+
end
|
|
35
|
+
def initialize(input = {})
|
|
36
|
+
raise ArgumentError, "form input must be a Hash" unless input.is_a?(Hash)
|
|
37
|
+
@errors, @error_codes, @values, @attributes = {}, {}, {}, {}
|
|
38
|
+
supplied = {}
|
|
39
|
+
input.each { |key, value| supplied[key.to_s] = value unless CONTROL_FIELDS.include?(key.to_s) }
|
|
40
|
+
definitions = self.class.fields
|
|
41
|
+
reject("_base", "unknown_fields") unless (supplied.keys - definitions.keys).empty?
|
|
42
|
+
model = self.class.model_class
|
|
43
|
+
model.assert_enabled! if model
|
|
44
|
+
definitions.each do |name, spec|
|
|
45
|
+
if model
|
|
46
|
+
model.assert_column_enabled!(name)
|
|
47
|
+
allowed = self.class.operation == :create ? model.create_fields : model.update_fields
|
|
48
|
+
unless allowed.include?(name)
|
|
49
|
+
reject(name, "unauthorized") if supplied.key?(name)
|
|
50
|
+
next
|
|
51
|
+
end
|
|
52
|
+
end
|
|
53
|
+
unless supplied.key?(name)
|
|
54
|
+
reject(name, "missing") if spec[:required]
|
|
55
|
+
next
|
|
56
|
+
end
|
|
57
|
+
raw = supplied[name]
|
|
58
|
+
@values[name] = raw if !spec[:sensitive] && (raw.nil? || raw.is_a?(String) || raw.is_a?(Integer) || raw == true || raw == false)
|
|
59
|
+
if raw.nil? || (raw.is_a?(String) && raw.strip.empty?)
|
|
60
|
+
reject(name, "blank") if spec[:required]
|
|
61
|
+
@attributes[name] = spec[:type] == :string ? raw : nil
|
|
62
|
+
next
|
|
63
|
+
end
|
|
64
|
+
value = coerce(raw, spec[:type])
|
|
65
|
+
if value == :__hamster_invalid_input__
|
|
66
|
+
reject(name, "malformed")
|
|
67
|
+
next
|
|
68
|
+
end
|
|
69
|
+
if value.is_a?(String)
|
|
70
|
+
reject(name, "too_short") if spec[:min_length] && value.length < spec[:min_length]
|
|
71
|
+
reject(name, "too_long") if spec[:max_length] && value.length > spec[:max_length]
|
|
72
|
+
end
|
|
73
|
+
@attributes[name] = value
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
def coerce(value, type)
|
|
77
|
+
case type
|
|
78
|
+
when :string
|
|
79
|
+
return value if value.is_a?(String) && value.valid_encoding?
|
|
80
|
+
when :integer
|
|
81
|
+
return value if value.is_a?(Integer)
|
|
82
|
+
if value.is_a?(String) && value.match?(/\A-?[0-9]+\z/)
|
|
83
|
+
number = value.to_i
|
|
84
|
+
return number if number >= -9223372036854775808 && number <= 9223372036854775807
|
|
85
|
+
end
|
|
86
|
+
when :boolean
|
|
87
|
+
return true if value == true || value == "1" || value == "true"
|
|
88
|
+
return false if value == false || value == "0" || value == "false"
|
|
89
|
+
end
|
|
90
|
+
:__hamster_invalid_input__
|
|
91
|
+
end
|
|
92
|
+
def reject(name, code = "unauthorized")
|
|
93
|
+
raise ArgumentError, "unknown form error code" unless MESSAGES.key?(code)
|
|
94
|
+
key = name.to_s
|
|
95
|
+
@errors[key] ||= []
|
|
96
|
+
@error_codes[key] ||= []
|
|
97
|
+
@errors[key] << MESSAGES[code].dup unless @errors[key].include?(MESSAGES[code])
|
|
98
|
+
@error_codes[key] << code unless @error_codes[key].include?(code)
|
|
99
|
+
@attributes.delete(key)
|
|
100
|
+
self
|
|
101
|
+
end
|
|
102
|
+
def valid?; errors.empty?; end
|
|
103
|
+
def [](name); @attributes[name.to_s]; end
|
|
104
|
+
def attributes
|
|
105
|
+
raise ArgumentError, "cannot persist invalid form" unless valid?
|
|
106
|
+
@attributes.to_h { |name, value| [name.to_sym, value] }
|
|
107
|
+
end
|
|
108
|
+
def values; @values.dup; end
|
|
109
|
+
end
|
|
110
|
+
end
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
require "tmpdir"
|
|
3
|
+
require "fileutils"
|
|
4
|
+
require_relative "../build/manifest"
|
|
5
|
+
|
|
6
|
+
module Hamster
|
|
7
|
+
module Generators
|
|
8
|
+
# Validate the complete proposal in isolation; never execute application code.
|
|
9
|
+
class Plan
|
|
10
|
+
attr_reader :root, :files
|
|
11
|
+
def initialize(root)
|
|
12
|
+
@root = File.realpath(root)
|
|
13
|
+
@files = {}
|
|
14
|
+
@expected = {}
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def safe!(path)
|
|
18
|
+
raise ArgumentError, "invalid generator path: #{path}" if path.start_with?("/") || path.split("/").include?("..")
|
|
19
|
+
cursor = root
|
|
20
|
+
path.split("/").each do |part|
|
|
21
|
+
cursor = File.join(cursor, part)
|
|
22
|
+
raise ArgumentError, "symlink generator path: #{path}" if File.symlink?(cursor)
|
|
23
|
+
end
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
def add(path, content, replace: false)
|
|
27
|
+
safe!(path)
|
|
28
|
+
raise ArgumentError, "generator file exists: #{path}" if !replace && (files.key?(path) || File.exist?(File.join(root, path)))
|
|
29
|
+
@expected[path] = File.file?(File.join(root, path)) ? File.binread(File.join(root, path)) : nil unless @expected.key?(path)
|
|
30
|
+
files[path] = content.b
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
def validate!
|
|
34
|
+
%w[app db config test public].each do |folder|
|
|
35
|
+
Dir.glob("#{folder}/**/*", File::FNM_DOTMATCH, base: root).each { |path| safe!(path) }
|
|
36
|
+
safe!(folder)
|
|
37
|
+
end
|
|
38
|
+
Dir.mktmpdir("hamster-generate") do |staging|
|
|
39
|
+
%w[app db config test public].each do |folder|
|
|
40
|
+
origin = File.join(root, folder)
|
|
41
|
+
FileUtils.cp_r(origin, staging) if File.directory?(origin)
|
|
42
|
+
end
|
|
43
|
+
files.each do |path, content|
|
|
44
|
+
target = File.join(staging, path)
|
|
45
|
+
FileUtils.mkdir_p(File.dirname(target))
|
|
46
|
+
File.write(target, content)
|
|
47
|
+
end
|
|
48
|
+
Dir.glob("{app,db,config}/**/*.rb", base: staging).each do |path|
|
|
49
|
+
raise ArgumentError, "invalid Ruby: #{path}" unless Ripper.sexp(File.read(File.join(staging, path)))
|
|
50
|
+
end
|
|
51
|
+
expected = Build::Manifest.outputs(staging)
|
|
52
|
+
expected.each do |path, content|
|
|
53
|
+
target = File.join(staging, path)
|
|
54
|
+
FileUtils.mkdir_p(File.dirname(target))
|
|
55
|
+
File.binwrite(target, content)
|
|
56
|
+
end
|
|
57
|
+
issues = Build::Manifest.check(staging, expected: expected)
|
|
58
|
+
raise ArgumentError, issues.join("\n") unless issues.empty?
|
|
59
|
+
expected.each { |path, content| add(path, content, replace: true) }
|
|
60
|
+
end
|
|
61
|
+
files.delete_if { |path, content| File.file?(File.join(root, path)) && File.binread(File.join(root, path)) == content }
|
|
62
|
+
self
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
def apply!
|
|
66
|
+
originals, created_directories = {}, []
|
|
67
|
+
files.each_key do |path|
|
|
68
|
+
safe!(path)
|
|
69
|
+
target = File.join(root, path)
|
|
70
|
+
originals[path] = File.file?(target) ? File.binread(target) : nil
|
|
71
|
+
raise ArgumentError, "File changed during generation: #{path}" unless originals[path] == @expected[path]
|
|
72
|
+
end
|
|
73
|
+
begin
|
|
74
|
+
files.each do |path, content|
|
|
75
|
+
target = File.join(root, path)
|
|
76
|
+
parent = File.dirname(target)
|
|
77
|
+
missing = []
|
|
78
|
+
until File.directory?(parent)
|
|
79
|
+
missing << parent
|
|
80
|
+
parent = File.dirname(parent)
|
|
81
|
+
end
|
|
82
|
+
missing.reverse_each { |directory| Dir.mkdir(directory); created_directories << directory }
|
|
83
|
+
File.binwrite(target, content)
|
|
84
|
+
end
|
|
85
|
+
rescue Exception
|
|
86
|
+
originals.each do |path, content|
|
|
87
|
+
target = File.join(root, path)
|
|
88
|
+
content.nil? ? (File.unlink(target) if File.file?(target)) : File.binwrite(target, content)
|
|
89
|
+
end
|
|
90
|
+
created_directories.reverse_each { |directory| Dir.rmdir(directory) if Dir.empty?(directory) }
|
|
91
|
+
raise
|
|
92
|
+
end
|
|
93
|
+
end
|
|
94
|
+
end
|
|
95
|
+
end
|
|
96
|
+
end
|