edgeway 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +18 -0
  3. data/README.md +43 -19
  4. data/js/cgi.js +11 -20
  5. data/js/cloudflare.js +25 -0
  6. data/js/jwt.js +1 -1
  7. data/js/runtime.js +6 -4
  8. data/lib/edgeway/cache/store.rb +2 -2
  9. data/lib/edgeway/cli/build/app_files.rb +22 -18
  10. data/lib/edgeway/cli/build/class_source.rb +21 -0
  11. data/lib/edgeway/cli/build/cloudflare_platform.rb +56 -0
  12. data/lib/edgeway/cli/build/dispatch_compiler.rb +71 -0
  13. data/lib/edgeway/cli/build/dispatch_probe.rb +52 -0
  14. data/lib/edgeway/cli/build/js_files.rb +12 -4
  15. data/lib/edgeway/cli/build/platform_config.rb +36 -0
  16. data/lib/edgeway/cli/build/view_compiler.rb +2 -11
  17. data/lib/edgeway/cli/build.rb +67 -28
  18. data/lib/edgeway/cli/cloudflare_test.rb +5 -2
  19. data/lib/edgeway/cli/generate.rb +11 -10
  20. data/lib/edgeway/cli/test.rb +11 -3
  21. data/lib/edgeway/cli/toolchain.rb +3 -3
  22. data/lib/edgeway/cli.rb +1 -1
  23. data/lib/edgeway/controller/base.rb +4 -2
  24. data/lib/edgeway/controller/{authentication.rb → bearer_token_authentication.rb} +4 -5
  25. data/lib/edgeway/controller/caching.rb +1 -2
  26. data/lib/edgeway/controller/dispatcher.rb +11 -21
  27. data/lib/edgeway/controller/rate_limiting.rb +1 -2
  28. data/lib/edgeway/errors.rb +1 -1
  29. data/lib/edgeway/generators/app/templates/README.md.tt +1 -1
  30. data/lib/edgeway/generators/app/templates/config/edgeway.yml +2 -0
  31. data/lib/edgeway/generators/app/templates/mise.toml.tt +1 -1
  32. data/lib/edgeway/http/form_body.rb +31 -0
  33. data/lib/edgeway/http/request.rb +3 -13
  34. data/lib/edgeway/model/attributes.rb +11 -6
  35. data/lib/edgeway/routing/mapper.rb +5 -5
  36. data/lib/edgeway/routing/route_set.rb +2 -2
  37. data/lib/edgeway/service/jwt.rb +30 -0
  38. data/lib/edgeway/version.rb +1 -1
  39. data/lib/edgeway.rb +2 -2
  40. metadata +11 -4
  41. data/lib/edgeway/service/cloudflare/jwt.rb +0 -32
@@ -9,17 +9,25 @@ module Edgeway
9
9
  module JsFiles
10
10
  TEST_ONLY = /-test(-[^\/]*)?\.js\z/
11
11
 
12
- def self.copy(destination, config_js, tests: false)
12
+ def self.copy(destination, config_js, paths)
13
13
  FileUtils.mkdir_p(destination)
14
- paths(tests).each { |file| FileUtils.cp(file, destination) }
14
+ paths.each { |file| FileUtils.cp(file, destination) }
15
15
  File.write(File.join(destination, "config.js"), config_js)
16
16
  end
17
17
 
18
- def self.paths(tests)
19
- files = Dir.glob(File.join(CLI.gem_dir, "js/*.js"))
18
+ # The files no platform claims, plus those prefixed by platform_name
19
+ # ("<name>.js", "<name>-*.js"); test-only files only when tests.
20
+ def self.paths(platform_name, tests, directory: File.join(CLI.gem_dir, "js"))
21
+ files = Dir.glob(File.join(directory, "*.js")).sort
22
+ files = files.select { |file| usable_on?(File.basename(file), platform_name) }
20
23
  tests ? files : files.grep_v(TEST_ONLY)
21
24
  end
22
25
 
26
+ def self.usable_on?(basename, platform_name)
27
+ owner = PlatformConfig::PLATFORMS.keys.find { |name| basename.match?(/\A#{Regexp.escape(name)}(-|\.js\z)/) }
28
+ owner.nil? || owner == platform_name
29
+ end
30
+
23
31
  def self.config_js(values, command)
24
32
  "// Generated by `edgeway #{command}` from config/database.yml; do not edit.\n" \
25
33
  "export default #{JSON.generate(values)};\n"
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Edgeway
4
+ module CLI
5
+ class Build
6
+ class PlatformConfig
7
+ # name => the platform class; each platform file registers itself.
8
+ PLATFORMS = {}
9
+ DEFAULT = "cloudflare"
10
+ KEYS = %w[platform].freeze
11
+
12
+ def self.load(root)
13
+ path = File.join(root, "config", "edgeway.yml")
14
+ return platform_named(DEFAULT) unless File.exist?(path)
15
+
16
+ settings = YAML.safe_load_file(path) || {}
17
+ raise Error, "config/edgeway.yml must be a Hash" unless settings.is_a?(Hash)
18
+
19
+ unknown = settings.keys.map(&:to_s) - KEYS
20
+ raise Error, "config/edgeway.yml: unknown #{unknown.join(", ")} (one of #{KEYS.join(", ")})" unless unknown.empty?
21
+
22
+ platform_named(settings.fetch("platform", DEFAULT))
23
+ end
24
+
25
+ def self.platform_named(name)
26
+ platform = PLATFORMS[name]
27
+ raise Error, "config/edgeway.yml: platform must be one of #{PLATFORMS.keys.join(", ")} (got #{name.inspect})" unless platform
28
+
29
+ platform.new
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end
35
+
36
+ Dir[File.join(__dir__, "*_platform.rb")].sort.each { |file| require file }
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "../../inflector"
4
+ require_relative "class_source"
4
5
 
5
6
  module Edgeway
6
7
  module CLI
@@ -168,17 +169,7 @@ module Edgeway
168
169
  body.map { |l| " #{l}" } + [" out", "end"]
169
170
  end
170
171
 
171
- def wrap(klass, body)
172
- *modules, name = klass.split("::")
173
- depth = modules.size
174
- lines = [""]
175
- modules.each_with_index { |m, i| lines << "#{" " * i}module #{m}" }
176
- lines << "#{" " * depth}class #{name}"
177
- body.each { |l| lines << (l.empty? ? "" : "#{" " * (depth + 1)}#{l}") }
178
- lines << "#{" " * depth}end"
179
- modules.size.times { |i| lines << "#{" " * (modules.size - 1 - i)}end" }
180
- lines
181
- end
172
+ def wrap(klass, body) = ClassSource.wrap(klass, body)
182
173
 
183
174
  def controller_file!(dir, what)
184
175
  return if File.exist?(File.join(@root, "app/controllers/#{dir}_controller.rb"))
@@ -5,7 +5,9 @@ require "json"
5
5
  require_relative "build/app_config"
6
6
  require_relative "build/app_files"
7
7
  require_relative "build/cache_config"
8
+ require_relative "build/dispatch_compiler"
8
9
  require_relative "build/js_files"
10
+ require_relative "build/platform_config"
9
11
  require_relative "build/view_compiler"
10
12
 
11
13
  module Edgeway
@@ -13,19 +15,21 @@ module Edgeway
13
15
  # edgeway build: app/, config/ -> build/main.rb -> build/app.wasm, and the
14
16
  # gem's js/ -> build/edgeway/. Spinel compiles with --incremental (cached C
15
17
  # units, fast rebuilds, no inlining across units) unless --release, which
16
- # builds as one unit for deploying.
18
+ # builds as one unit for deploying and strips the DWARF debug info from
19
+ # build/app.wasm.
17
20
  #
18
21
  # Spinel resolves require at compile time and has no autoloading, so
19
22
  # build/main.rb requires every file, in an order where a class body finds
20
23
  # what it names (a superclass, an extended module):
21
- # 1. edgeway, the database adapter config/database.yml names, the JWT
22
- # verifier, the HTTP client, the rate limiter and the cache store
23
- # config/cache.yml names (when it needs a file)
24
+ # 1. edgeway, the database adapter config/database.yml names, the services
25
+ # of the platform config/edgeway.yml names (see PlatformConfig), and
26
+ # the cache store config/cache.yml names (when it needs a file)
24
27
  # 2. app/*/ other than models/ and controllers/ (services, ...)
25
28
  # 3. app/models/
26
29
  # 4. app/controllers/
27
30
  # 5. build/views.rb, the Ruby compiled from app/views (when there is one)
28
- # 6. config/routes.rb
31
+ # 6. build/dispatch.rb, the Ruby generated from the routes (see DispatchCompiler)
32
+ # 7. config/routes.rb
29
33
  # Within each, application_*.rb come first (the base classes), then the
30
34
  # rest by path (byte order).
31
35
  class Build
@@ -35,15 +39,16 @@ module Edgeway
35
39
  OptionParser.new do |o|
36
40
  o.banner = "Usage: edgeway build [--env ENV] [--release]"
37
41
  o.on("--env ENV", "environment (default: development)") { |v| env = v }
38
- o.on("--release", "build as one unit, without --incremental (for deploying)") { release = true }
42
+ o.on("--release", "build as one unit, without --incremental, and strip debug info (for deploying)") { release = true }
39
43
  end.parse!(args)
40
44
  new(Dir.pwd, env, release:).run
41
45
  end
42
46
 
43
- def initialize(root, env, release: false)
47
+ def initialize(root, env, release: false, platform: nil)
44
48
  @root = root
45
49
  @env = env
46
50
  @release = release
51
+ @platform = platform
47
52
  end
48
53
 
49
54
  def run
@@ -61,31 +66,48 @@ module Edgeway
61
66
 
62
67
  def write_main(config)
63
68
  cache = CacheConfig.load(@root, @env)
64
- lines = ["# Generated by `edgeway build` from app/ and config/; do not edit.", 'require "edgeway"']
65
- lines << "require #{config.adapter_file.dump}"
66
- # Always: js/cloudflare.js supplies the edgeway_jwt, edgeway_fetch and
67
- # edgeway_ratelimit imports to every app, and each is only called by an
68
- # app that authenticates, calls out or rate limits.
69
- lines << 'require "edgeway/service/cloudflare/jwt"'
70
- lines << 'require "edgeway/service/fetch"'
71
- lines << 'require "edgeway/service/cloudflare/rate_limit"'
72
- lines << "require #{cache.backend_file.dump}" if cache.backend_file
73
- lines << ""
69
+ check_platform_supports(config, cache)
70
+ library = library_lines(config, cache)
71
+ lines = ["# Generated by `edgeway build` from app/ and config/; do not edit.", *library, ""]
74
72
  lines << connection_line(config)
75
73
  config.databases.each { |name, binding_name| lines << connect_line(config, name, binding_name) }
76
- lines << "Edgeway::Auth.verifier = Edgeway::Cloudflare::JWTVerifier.new"
77
- lines << "Edgeway::HTTP.client = Edgeway::FetchTransport.new"
74
+ lines.concat(platform.setup_lines)
78
75
  lines << "Edgeway.cache = #{cache.store_expression}"
79
- lines << "Edgeway::Controller.rate_limiter = Edgeway::Cloudflare::RateLimiter.new(transport: Edgeway::Cloudflare::RateLimitImportTransport.new)"
76
+ lines.concat(platform.rate_limiter_lines)
80
77
  lines << ""
81
- views = ViewCompiler.new(@root).compile
82
- File.write(File.join(@root, "build/views.rb"), views) if views
83
- lines.concat(AppFiles.new(@root).require_lines(views: views && "views"))
78
+ lines.concat(app_lines(library))
84
79
  lines << ""
85
80
  lines << "Edgeway::Server.run"
86
81
  File.write(File.join(@root, "build/main.rb"), lines.join("\n") + "\n")
87
82
  end
88
83
 
84
+ def library_lines(config, cache)
85
+ lines = ['require "edgeway"', "require #{config.adapter_file.dump}", *platform.service_lines]
86
+ lines << "require #{cache.backend_file.dump}" if cache.backend_file
87
+ lines
88
+ end
89
+
90
+ def app_lines(library)
91
+ views = ViewCompiler.new(@root).compile
92
+ File.write(File.join(@root, "build/views.rb"), views) if views
93
+ dispatch = DispatchCompiler.new(@root, library).compile
94
+ File.write(File.join(@root, "build/dispatch.rb"), dispatch) if dispatch
95
+ AppFiles.new(@root).require_lines(views: views && "views", dispatch: dispatch && "dispatch")
96
+ end
97
+
98
+ def platform
99
+ @platform ||= PlatformConfig.load(@root)
100
+ end
101
+
102
+ def check_platform_supports(config, cache)
103
+ unsupported("database adapter", config.adapter) unless platform.adapters.include?(config.adapter)
104
+ unsupported("cache store", cache.store) unless platform.stores.include?(cache.store)
105
+ end
106
+
107
+ def unsupported(kind, value)
108
+ raise Error, "#{kind} #{value.inspect} is not supported on platform #{platform.name.inspect}"
109
+ end
110
+
89
111
  def connection_line(config)
90
112
  "Edgeway::Model.connection = #{adapter_expression(config, config.binding_name)}"
91
113
  end
@@ -95,14 +117,11 @@ module Edgeway
95
117
  end
96
118
 
97
119
  def adapter_expression(config, binding_name)
98
- case config.adapter
99
- when "d1" then "Edgeway::Cloudflare::D1Adapter.new(binding: #{binding_name.inspect})"
100
- else "Edgeway::DB::MemoryAdapter.new"
101
- end
120
+ platform.adapter_expression(config.adapter, binding_name)
102
121
  end
103
122
 
104
123
  def copy_js(config)
105
- JsFiles.copy(File.join(@root, "build/edgeway"), config_js(config))
124
+ JsFiles.copy(File.join(@root, "build/edgeway"), config_js(config), platform.js_paths)
106
125
  end
107
126
 
108
127
  def config_js(config)
@@ -116,6 +135,26 @@ module Edgeway
116
135
  cmd << "--incremental" unless @release
117
136
  puts cmd.join(" ")
118
137
  system(*cmd, chdir: @root) || raise(Error, "spinel failed")
138
+ strip_debug_info if @release
139
+ end
140
+
141
+ def strip_debug_info
142
+ strip = strip_tool
143
+ unless strip
144
+ warn("edgeway: warning: no llvm-strip in the WASI SDK; build/app.wasm keeps its debug info")
145
+ return
146
+ end
147
+
148
+ # --strip-debug and not --strip-all: the name section stays, so stack traces keep their function names.
149
+ command = [strip, "--strip-debug", "build/app.wasm"]
150
+ puts command.join(" ")
151
+ system(*command, chdir: @root) || raise(Error, "llvm-strip failed")
152
+ end
153
+
154
+ def strip_tool
155
+ sdk = Toolchain.wasi_sdk
156
+ tool = sdk && File.join(sdk, "bin/llvm-strip")
157
+ tool if tool && File.executable?(tool)
119
158
  end
120
159
  end
121
160
  end
@@ -17,6 +17,9 @@ module Edgeway
17
17
 
18
18
  def initialize(root)
19
19
  super
20
+ @platform = Build::PlatformConfig.load(root)
21
+ raise Error, "edgeway test needs platform: cloudflare in config/edgeway.yml (got #{@platform.name.inspect})" unless @platform.name == "cloudflare"
22
+
20
23
  @config = Build::AppConfig.load(root, "test")
21
24
  end
22
25
 
@@ -35,7 +38,7 @@ module Edgeway
35
38
  [
36
39
  'require "edgeway/db/memory"',
37
40
  'require "edgeway/service/cloudflare/test_databases"',
38
- 'require "edgeway/service/cloudflare/jwt"',
41
+ 'require "edgeway/service/jwt"',
39
42
  'require "edgeway/service/fetch"',
40
43
  "module Edgeway; TEST_DATABASES = #{@config.databases.keys.inspect}; end",
41
44
  "module Edgeway; TEST_BINDINGS = #{bindings.inspect}; end"
@@ -59,7 +62,7 @@ module Edgeway
59
62
  "appRoot" => @root, "databases" => databases
60
63
  }
61
64
  directory = File.join(@root, RUNTIME_DIR)
62
- Build::JsFiles.copy(directory, Build::JsFiles.config_js(values, "test"), tests: true)
65
+ Build::JsFiles.copy(directory, Build::JsFiles.config_js(values, "test"), @platform.js_paths(tests: true))
63
66
  File.write(File.join(directory, "package.json"), %({"type": "module"}\n))
64
67
  end
65
68
 
@@ -6,20 +6,12 @@ require_relative "package_manager"
6
6
  module Edgeway
7
7
  module CLI
8
8
  class Generate
9
- USAGE = <<~TEXT
10
- Usage: edgeway generate model NAME [field:type ...]
11
- edgeway generate controller NAME [action ...]
12
- edgeway generate scaffold NAME [field:type ...]
13
-
14
- Types: #{%w[string text integer float boolean datetime].join(", ")} (default string)
15
- TEXT
16
-
17
9
  # field type => its column's SQL type, its attribute type, and the values
18
10
  # (as Ruby source) the scaffold's test creates and updates with.
19
11
  # D1 is SQLite, which has no datetime/boolean type (only NULL, INTEGER,
20
12
  # REAL, TEXT and BLOB): a datetime is TEXT (ISO 8601, as Model.now
21
13
  # writes it) and a boolean is an INTEGER 0/1. It is SQLite's, not a
22
- # Cloudflare, limit.
14
+ # Cloudflare, limit. A binary's values are base64 in requests and JSON.
23
15
  Type = Struct.new(:sql, :attr, :created, :updated)
24
16
  TYPES = {
25
17
  "string" => Type.new("TEXT", ":string", '"MyString"', '"Updated"'),
@@ -27,9 +19,18 @@ module Edgeway
27
19
  "integer" => Type.new("INTEGER", ":integer", "1", "2"),
28
20
  "float" => Type.new("REAL", ":float", "1.5", "2.5"),
29
21
  "boolean" => Type.new("INTEGER NOT NULL DEFAULT 0", ":boolean", "true", "false"),
30
- "datetime" => Type.new("TEXT", ":datetime", '"2026-01-01T00:00:00Z"', '"2026-02-01T00:00:00Z"')
22
+ "datetime" => Type.new("TEXT", ":datetime", '"2026-01-01T00:00:00Z"', '"2026-02-01T00:00:00Z"'),
23
+ "binary" => Type.new("BLOB", ":binary", '"AQID"', '"BAUG"')
31
24
  }.freeze
32
25
 
26
+ USAGE = <<~TEXT
27
+ Usage: edgeway generate model NAME [field:type ...]
28
+ edgeway generate controller NAME [action ...]
29
+ edgeway generate scaffold NAME [field:type ...]
30
+
31
+ Types: #{TYPES.keys.join(", ")} (default string)
32
+ TEXT
33
+
33
34
  Field = Struct.new(:name, :sql, :attr, :created, :updated)
34
35
 
35
36
  RESOURCE_ACTIONS = %w[index show create update destroy].freeze
@@ -6,6 +6,8 @@ module Edgeway
6
6
  PLATFORMS = []
7
7
 
8
8
  def self.run(args)
9
+ raise Error, "edgeway test does not support --ruby (the tests always run as a Spinel build)" if args.include?("--ruby")
10
+
9
11
  root = Dir.pwd
10
12
  database = Build::DatabaseConfig.new(root)
11
13
  (PLATFORMS.find { |platform| platform.handles?(database) } || Test).new(root).run(args)
@@ -28,14 +30,20 @@ module Edgeway
28
30
  lines = ["# Generated by `edgeway test` from app/ and config/; do not edit.", 'require "edgeway"']
29
31
  lines.concat(database_lines)
30
32
  lines << ""
31
- views = Build::ViewCompiler.new(@root).compile
32
- File.write(File.join(@root, "tmp/views.rb"), views) if views
33
- lines.concat(Build::AppFiles.new(@root).require_lines(views: views && "views"))
33
+ lines.concat(app_lines(database_lines))
34
34
  File.write(File.join(@root, "tmp/test_app.rb"), lines.join("\n") + "\n")
35
35
  end
36
36
 
37
37
  private
38
38
 
39
+ def app_lines(library)
40
+ views = Build::ViewCompiler.new(@root).compile
41
+ File.write(File.join(@root, "tmp/views.rb"), views) if views
42
+ dispatch = Build::DispatchCompiler.new(@root, ['require "edgeway"', *library]).compile
43
+ File.write(File.join(@root, "tmp/dispatch.rb"), dispatch) if dispatch
44
+ Build::AppFiles.new(@root).require_lines(views: views && "views", dispatch: dispatch && "dispatch")
45
+ end
46
+
39
47
  def database_lines
40
48
  [
41
49
  'require "edgeway/db/memory"',
@@ -8,9 +8,9 @@ module Edgeway
8
8
  # 2. spinel on PATH (mise puts its spinel there when it is activated)
9
9
  # 3. `mise which spinel` (mise is installed but not activated)
10
10
  #
11
- # The WASI SDK that --target=wasm32-wasi needs is Spinel's to find: it
12
- # reads WASI_SDK (mise.toml sets it), then WASI_SDK_PATH, and defaults to
13
- # /opt/wasi-sdk.
11
+ # The WASI SDK that --target=wasm32-wasi needs is found the same way by
12
+ # Spinel and by Edgeway (for llvm-strip in a release build): WASI_SDK
13
+ # (mise.toml sets it), then WASI_SDK_PATH, and /opt/wasi-sdk by default.
14
14
  module Toolchain
15
15
  def self.spinel
16
16
  env = ENV["SPINEL"]
data/lib/edgeway/cli.rb CHANGED
@@ -23,7 +23,7 @@ module Edgeway
23
23
  new APP create a new app in APP/
24
24
  build [--env ENV] [--release]
25
25
  compile the app to build/app.wasm (ENV: development);
26
- --release builds for deploying (no --incremental)
26
+ --release builds for deploying (no --incremental, debug info stripped)
27
27
  test [ARGS] regenerate tmp/test_app.rb, run test/ with spinel_test-unit
28
28
  (natively, or as wasm on the platform's local database, by database.yml's test:)
29
29
  generate, g KIND NAME generate a model (NAME field:type ...), a controller (NAME action ...)
@@ -4,7 +4,7 @@ module Edgeway
4
4
  include Callbacks
5
5
  include Rescuable
6
6
  include Rendering
7
- include Authentication
7
+ include BearerTokenAuthentication
8
8
  include Caching
9
9
  include RateLimiting
10
10
 
@@ -85,7 +85,7 @@ module Edgeway
85
85
  def headers = @headers
86
86
 
87
87
  def action?(name)
88
- return false if name.start_with?("_view_") || name.start_with?("_render_")
88
+ return false if name.start_with?("_view_") || name.start_with?("_render_") || name.start_with?("_run_")
89
89
  respond_to?(name.to_sym) && !NON_ACTIONS.include?(name) && !self.class.non_action?(name)
90
90
  end
91
91
 
@@ -93,6 +93,8 @@ module Edgeway
93
93
 
94
94
  def _render_view(action) = nil
95
95
 
96
+ def _run_action(action) = nil
97
+
96
98
  def _render_layout(content) = content
97
99
 
98
100
  def params
@@ -1,16 +1,15 @@
1
1
  module Edgeway
2
2
  module Controller
3
- # Bearer-token authentication:
3
+ # Usage:
4
4
  #
5
5
  # class ApplicationController < Edgeway::Controller::Base
6
6
  # before_action :authenticate!
7
7
  # end
8
8
  # # or before_action :authenticate!, only: [:create]
9
9
  #
10
- # authenticate! answers 401 unless the request has an
11
- # "Authorization: Bearer <JWT>" whose token passes Edgeway::Auth; the
12
- # claims are then in current_claims.
13
- module Authentication
10
+ # The token is verified by Edgeway::Auth; its claims are then in
11
+ # current_claims.
12
+ module BearerTokenAuthentication
14
13
  # Raises Unauthorized (no token) or InvalidToken. Both are 401 with a
15
14
  # WWW-Authenticate header, unless the app rescue_froms them.
16
15
  def authenticate!
@@ -44,9 +44,8 @@ module Edgeway
44
44
  !fresh_when(etag: etag, last_modified: last_modified, public: public)
45
45
  end
46
46
 
47
- # Integer() gives Spinel a type for a parameter no call site types.
48
47
  def self.duration?(seconds)
49
- seconds.is_a?(Integer) && Integer(seconds) >= 0
48
+ seconds.is_a?(Integer) && seconds >= 0
50
49
  end
51
50
 
52
51
  # Weak, because a proxy may recompress the body and weaken a strong
@@ -1,32 +1,22 @@
1
1
  module Edgeway
2
2
  module Controller
3
3
  module Dispatcher
4
- def self.controller_class(route)
5
- klass = nil
6
- begin
7
- klass = Object.const_get(route.controller_class_name)
8
- rescue NameError
9
- return nil
10
- end
11
- klass.is_a?(Class) && klass < Base ? klass : nil
12
- end
4
+ def self.instantiate(name, request) = nil
13
5
 
14
6
  def self.dispatch(route, request)
15
- klass = controller_class(route)
16
- raise RoutingError, "no controller for #{route.controller_path}" if klass.nil?
17
- controller = klass.new(request)
7
+ controller = Dispatcher.instantiate(route.controller_class_name, request)
8
+ raise RoutingError, "no controller for #{route.controller_path}" if controller.nil?
18
9
  controller.action_name = route.action
19
- # A route whose action isn't defined (or is one of Base's own public
20
- # methods) is a 404, as in Rails.
10
+ # The build refuses a route to an action that isn't defined (or is one
11
+ # of Base's own public methods); this stays so that a private method
12
+ # or a Base method can't be reached whatever generated the dispatch.
21
13
  raise RoutingError, "no route for #{request.method} #{request.path}" unless controller.action?(route.action)
22
14
  begin
23
- # The action is called here, on an instance of a class found by
24
- # name, and not from a Base method: with a name taken as a method
25
- # argument Spinel's send looks among the literals of the program,
26
- # and misses a subclass's methods (matz/spinel#8592). public_send:
27
- # a route can't reach a private method.
28
- action = route.action.to_sym
29
- controller.public_send(action) if controller.run_before_actions(route.action)
15
+ # instantiate and _run_action are generated from the routes by
16
+ # `edgeway build` / `edgeway test`: a class found by name and a send
17
+ # with a computed name make Spinel emit a branch for every class and
18
+ # every method name of the program, and keep their code reachable.
19
+ controller._run_action(route.action) if controller.run_before_actions(route.action)
30
20
  implicit_render(controller, route) unless controller.performed?
31
21
  rescue => e
32
22
  raise e unless controller.rescue_with_handler(e)
@@ -116,9 +116,8 @@ module Edgeway
116
116
  group.to_i(16).to_s(16)
117
117
  end
118
118
 
119
- # Integer() gives Spinel a type for a parameter no call site types.
120
119
  def self.positive_integer?(value)
121
- value.is_a?(Integer) && Integer(value) > 0
120
+ value.is_a?(Integer) && value > 0
122
121
  end
123
122
 
124
123
  private
@@ -35,7 +35,7 @@ module Edgeway
35
35
 
36
36
  def initialize(message = "rate limit exceeded", retry_after = 0)
37
37
  super(message)
38
- @retry_after = retry_after.is_a?(Integer) && Integer(retry_after) > 0 ? retry_after : 0
38
+ @retry_after = retry_after.is_a?(Integer) && retry_after > 0 ? retry_after : 0
39
39
  end
40
40
  end
41
41
 
@@ -15,7 +15,7 @@ bundle exec edgeway build # build/app.wasm (or bin/build); -
15
15
  bundle exec edgeway routes
16
16
  ```
17
17
 
18
- `bin/deploy` builds with `--release`: one unit, without Spinel's `--incremental` (cached C units, no inlining across units), for deploying.
18
+ `bin/deploy` builds with `--release`: one unit, without Spinel's `--incremental` (cached C units, no inlining across units), for deploying. It also strips the debug info from `build/app.wasm` with the WASI SDK's `llvm-strip`; function names stay, so stack traces are readable.
19
19
 
20
20
  Files in `public/` are served by Cloudflare before the app, for every method on their path (see Edgeway's README, "Static assets").
21
21
 
@@ -0,0 +1,2 @@
1
+ # The platform this app is built for.
2
+ platform: cloudflare
@@ -14,7 +14,7 @@ spinel = "https://github.com/y-yagi/mise-spinel"
14
14
  # master, so an install (and CI's cache of it) is the Spinel that was tested.
15
15
  # depends: the wasi-sdk is installed first, so the build also makes Spinel's
16
16
  # wasm32-wasi runtime (mise-spinel does when WASI_SDK, set below, is there).
17
- spinel = { version = "ec0ad13e4", depends = ["github:WebAssembly/wasi-sdk"] }
17
+ spinel = { version = "1138767c4", depends = ["github:WebAssembly/wasi-sdk"] }
18
18
 
19
19
  # wrangler (package.json) runs on Node.js.
20
20
  node = "lts"
@@ -0,0 +1,31 @@
1
+ module Edgeway
2
+ module HTTP
3
+ class FormBody
4
+ attr_reader :pairs
5
+
6
+ def initialize(text)
7
+ @valid_utf8 = true
8
+ pieces = text.split("&", -1)
9
+ pieces.pop if !pieces.empty? && pieces.last.empty?
10
+ @pairs = pieces.map { |piece| decode_pair(piece) }
11
+ end
12
+
13
+ def valid_utf8?
14
+ @valid_utf8
15
+ end
16
+
17
+ private
18
+
19
+ def decode_pair(piece)
20
+ key, _, value = piece.partition("=")
21
+ [decode_component(key), decode_component(value)]
22
+ end
23
+
24
+ def decode_component(component)
25
+ decoded = component.b.tr("+", " ").gsub(/%([0-9A-Fa-f]{2})/) { $1.hex.chr }.force_encoding("UTF-8")
26
+ @valid_utf8 = false unless decoded.valid_encoding?
27
+ decoded.scrub
28
+ end
29
+ end
30
+ end
31
+ end
@@ -1,8 +1,6 @@
1
1
  module Edgeway
2
2
  module HTTP
3
3
  class Request
4
- REPLACEMENT = "\uFFFD"
5
-
6
4
  attr_reader :method, :path, :query_string, :content_type, :body, :params, :body_params
7
5
 
8
6
  def self.from_env
@@ -68,19 +66,11 @@ module Edgeway
68
66
  add_body_params(decode_pairs(@body, "form body"))
69
67
  end
70
68
 
71
- # URI.decode_www_form never raises on bad bytes: it turns those that aren't
72
- # UTF-8 (%ff) into U+FFFD. That is only right when the client sent a
73
- # U+FFFD itself, so otherwise one in the result is a BadRequest.
74
69
  def decode_pairs(text, what)
75
70
  raise BadRequest, "#{what} is not valid UTF-8" unless text.valid_encoding?
76
- pairs = URI.decode_www_form(text)
77
- sent = text.include?(REPLACEMENT) || text.downcase.include?("%ef%bf%bd")
78
- unless sent
79
- pairs.each do |k, v|
80
- raise BadRequest, "#{what} is not valid UTF-8" if k.include?(REPLACEMENT) || v.include?(REPLACEMENT)
81
- end
82
- end
83
- pairs
71
+ form = FormBody.new(text)
72
+ raise BadRequest, "#{what} is not valid UTF-8" unless form.valid_utf8?
73
+ form.pairs
84
74
  end
85
75
 
86
76
  def read_json
@@ -34,7 +34,8 @@ module Edgeway
34
34
 
35
35
  # Runs the block with writes queued instead of executed, then sends them
36
36
  # all as one atomic batch (one SQL transaction, all or none).
37
- # A batch belongs to the database of its first write.
37
+ # A batch belongs to the database of its first write. Leaving the block
38
+ # with break or return sends the writes like finishing it; a raise of any kind sends nothing.
38
39
  def self.batch
39
40
  if @batch_queue
40
41
  yield
@@ -43,15 +44,19 @@ module Edgeway
43
44
  queue = []
44
45
  @batch_queue = queue
45
46
  @batch_database = nil
47
+ results = []
48
+ failed = false
46
49
  begin
47
50
  yield
48
- rescue => e
51
+ rescue Exception
52
+ failed = true
53
+ raise
54
+ ensure
55
+ database = @batch_database
49
56
  @batch_queue = nil
50
- raise e
57
+ results = connection_for(database).batch(queue) unless failed || queue.empty?
51
58
  end
52
- database = @batch_database
53
- @batch_queue = nil
54
- queue.empty? ? [] : connection_for(database).batch(queue)
59
+ results
55
60
  end
56
61
 
57
62
  def self.batching? = !@batch_queue.nil?