Top Level Namespace
- Includes:
- SilenceReloadConstWarnings
Defined Under Namespace
Modules: Color, Fresco, Mime, Pg, SilenceReloadConstWarnings, Sock, Spinel, Sqlite Classes: Flash, Module, Params, Request, Response, Session
Constant Summary collapse
- ROOT =
Dir.pwd
- WATCH_GLOBS =
[ "config/routes.rb", "config/app.rb", "config/database.rb", "db/schema.rb", "app/action.rb", "app/actions/**/*.rb", "app/models/**/*.rb", "app/views/**/*.erb", ].freeze
- RELOAD_LOCK =
Mutex.new
- SESSION_COOKIE_NAME =
Name of the cookie carrying the signed session payload. Hardcoded rather than configurable — apps that need multiple session stores can reach for ‘res.set_cookie` directly with their own names.
"_session"- FLASH_KEY_PREFIX =
Key prefix marking flash entries inside the session payload. Apps never write this prefix directly; req.flash.set / req.flash.get do the bookkeeping.
"_flash."- REASON_PHRASES =
HTTP/1.1 reason phrases for the statuses M2-M3 actually emit. Spinel can’t take a Hash#[] of a missing key safely under polymorphism, so ‘reason_for` falls back to “OK” for anything we forgot.
{ 200 => "OK", 201 => "Created", 204 => "No Content", 301 => "Moved Permanently", 302 => "Found", 303 => "See Other", 304 => "Not Modified", 307 => "Temporary Redirect", 308 => "Permanent Redirect", 400 => "Bad Request", 401 => "Unauthorized", 403 => "Forbidden", 404 => "Not Found", 405 => "Method Not Allowed", 413 => "Payload Too Large", 500 => "Internal Server Error", 501 => "Not Implemented", 503 => "Service Unavailable", }.freeze
Constants included from SilenceReloadConstWarnings
SilenceReloadConstWarnings::IGNORE
Instance Method Summary collapse
-
#attach_session_cookie!(req, res) ⇒ Object
After the handler runs, if anything wrote to req.session, sign + encode the bag and attach a Set-Cookie line to the response.
-
#bad_request ⇒ Object
Parse an HTTP/1.x request out of the C-side request buffer.
- #build! ⇒ Object
- #build_headers(status, ctype, content_length, conn, set_cookies, location = "") ⇒ Object
-
#color_method(m = "") ⇒ Object
Per-method palette — green for safe reads, yellow for creates, blue for updates, red for destroys.
-
#color_sql(sql = "") ⇒ Object
SQL log colorization.
-
#color_status(status = 0) ⇒ Object
Status: 2xx green (success), 3xx cyan (redirect), 4xx yellow (client error — operator should glance), 5xx red (server error — operator must look).
-
#consume_flash_writes!(req) ⇒ Object
Before signing the outbound session cookie, copy req.flash.write_data into the session as ‘_flash.<key>` entries.
-
#error_response(status, default_body) ⇒ Object
Per-status error page lookup.
-
#file_response(rel_path = "", root = "") ⇒ Object
Build a sendfile-backed Response for a path-under-root.
-
#fmt_micros(us = 0) ⇒ Object
Format an integer micro-second count for the request / SQL log lines.
-
#format_hash(h) ⇒ Object
Format a Sym→Str hash for the request log.
-
#handle_connection(client) ⇒ Object
Serve one TCP connection.
- #handle_dev_connection(client) ⇒ Object
- #hex_char_upper(n = 0) ⇒ Object
-
#hex_nibble(c = "") ⇒ Object
Single hex nibble — explicit case keeps each branch monomorphic on String.
- #log_request_brief(method, path, status, micros) ⇒ Object
- #log_request_full(req, status, micros) ⇒ Object
-
#maybe_load_session!(req) ⇒ Object
If a signed session cookie is present and a secret is configured, verify + decode it into req.session.
-
#parse_cookie_header!(s = "", into = { "__t" => "" }) ⇒ Object
Parse a Cookie: header value (‘a=1; b=hello%20world; flag`) into the given Str->Str hash.
-
#parse_dev_request(sock) ⇒ Object
— Dev HTTP listener ——————————————.
-
#parse_form_body!(body, into) ⇒ Object
Form bodies share the ‘application/x-www-form-urlencoded` framing with query strings — same `k=v&k=v`, same percent/`+` decode.
- #parse_http_request(client) ⇒ Object
-
#parse_query_string!(s, into) ⇒ Object
Parse ‘k=v&k=v` into the supplied Params wrapper.
-
#promote_flash!(req) ⇒ Object
Move any ‘_flash.<key>` entries from the loaded session into req.flash.read_data, removing them from the session as we go.
- #reason_for(status) ⇒ Object
-
#reload! ⇒ Object
‘load` (vs require) re-evaluates on each call so reloads pick up edits.
-
#render_dev_error(err, req) ⇒ Object
Dev-only crash page.
- #run_server(port:, workers: 1) ⇒ Object
- #serve_dev(port) ⇒ Object
- #snapshot_mtimes ⇒ Object
-
#spawn_worker(port = 0, slot = 0) ⇒ Object
Prefork model.
- #start_watcher ⇒ Object
-
#str_idx(s = "", needle = "") ⇒ Object
Spinel #532: ‘String#index` / `#rindex` now return boxed poly (nil for not-found, boxed int when found) instead of `mrb_int` with a `-1` sentinel.
- #str_idx_from(s = "", needle = "", start = 0) ⇒ Object
- #str_ridx(s = "", needle = "") ⇒ Object
-
#url_decode(s = "") ⇒ Object
‘+` → space, then `%XX` → byte.
-
#url_encode(s = "") ⇒ Object
RFC 3986 percent-encode.
- #worker_loop(sfd) ⇒ Object
-
#write_dev_response(sock, res) ⇒ Object
Write an HTTP/1.1 response.
-
#write_response(client, res, keep_alive) ⇒ Object
Build a wire-format HTTP/1.1 response.
Methods included from SilenceReloadConstWarnings
Instance Method Details
#attach_session_cookie!(req, res) ⇒ Object
After the handler runs, if anything wrote to req.session, sign + encode the bag and attach a Set-Cookie line to the response. Path=/ so it covers the whole app; HttpOnly to keep it out of JS; SameSite=Lax as a sensible default (blocks CSRF on top-level cross-site POSTs without breaking link navigations).
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 |
# File 'lib/fresco/runtime/runtime.rb', line 1258 def (req, res) secret = Fresco.session_secret return if secret.length == 0 consume_flash_writes!(req) return unless req.session.dirty opts = { "__t" => "" } opts.delete("__t") opts["Path"] = "/" opts["HttpOnly"] = "" opts["SameSite"] = "Lax" res.(SESSION_COOKIE_NAME, req.session.(secret), opts) end |
#bad_request ⇒ Object
Parse an HTTP/1.x request out of the C-side request buffer. Reads the request line, headers (lowercased keys), strips any ‘?query` off the path, and pulls a `Content-Length`-bounded body. Returns a fully populated Request, or nil if the bytes don’t look like HTTP.
Body strategy: any bytes that arrived past the header terminator are already in the request buf (capped at 64 KiB). For bodies that span beyond that, sphttp_drain_body reads the rest into the body buf. Cap: 1 MiB (decision #5); larger requests get parse_status=413.
Always returns a Request — failures populate ‘parse_status` with the HTTP code the caller should respond with (400 / 413). The single-type return is load-bearing for Spinel: a Request|nil|:too_large union would widen the entire dispatch chain’s ‘req` parameter to sp_RbVal and break the polymorphic call from Fresco::Action#handle to each subclass’s #call.
1287 1288 1289 1290 1291 |
# File 'lib/fresco/runtime/runtime.rb', line 1287 def bad_request r = Request.new("", "", "") r.parse_status = 400 r end |
#build! ⇒ Object
68 69 70 71 72 73 74 75 76 77 78 |
# File 'lib/fresco/cli/dev_loop.rb', line 68 def build! # Subprocess (vs. in-process call) keeps Fresco's build-time DSL # accumulators (Fresco.models, Fresco.app.routes.entries, etc.) from # leaking across rebuilds. The cost is one fork + ruby startup per # reload, which is fine for development. unless system("bundle", "exec", "fresco", "build") warn "[dev] fresco build failed — keeping previous dispatcher" return false end true end |
#build_headers(status, ctype, content_length, conn, set_cookies, location = "") ⇒ Object
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 |
# File 'lib/fresco/runtime/runtime.rb', line 1426 def build_headers(status, ctype, content_length, conn, , location = "") out = "HTTP/1.1 " out += status.to_s out += " " out += reason_for(status) out += "\r\nContent-Type: " out += ctype out += "\r\nContent-Length: " out += content_length.to_s out += "\r\nConnection: " out += conn # `Location:` is emitted only for redirect responses (Response.redirect # populates @location). Empty string → no header, so non-redirect # responses stay byte-identical to before this slot existed. if location.length > 0 out += "\r\nLocation: " out += location end # One Set-Cookie line per array entry. Order matches push order. i = 0 while i < .length out += "\r\nSet-Cookie: " out += [i] i += 1 end out += "\r\n\r\n" out end |
#color_method(m = "") ⇒ Object
Per-method palette — green for safe reads, yellow for creates, blue for updates, red for destroys. Matches the convention most request inspectors (Postman, Insomnia, the Chrome devtools network panel) settled on, so it reads at a glance. Unknown methods route through Color.plain for the uniform-return-type discipline noted on Color.
‘s = m.to_s` is the type-pin: Spinel’s ‘.to_s` always lowers to `sp_poly_to_s` (declared `const char *`) regardless of m’s inferred type, so ‘s` is guaranteed String. Without this, m’s parameter type (which the analyzer pessimistically widens to RbVal here — the multiple ‘Color.*` call sites in this body form a circular unification with wrap’s ‘s`) would propagate into Color.green/red/ etc. and force every wrap-helper to take RbVal, which then breaks the `out = s` (String = RbVal) inside wrap.
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 |
# File 'lib/fresco/runtime/runtime.rb', line 1558 def color_method(m = "") s = m.to_s return Color.green(s) if s == "GET" return Color.green(s) if s == "HEAD" return Color.yellow(s) if s == "POST" return Color.blue(s) if s == "PATCH" return Color.blue(s) if s == "PUT" return Color.red(s) if s == "DELETE" return Color.cyan(s) if s == "OPTIONS" Color.plain(s) end |
#color_sql(sql = "") ⇒ Object
SQL log colorization. Verb-driven palette mirroring color_method —green for safe reads (SELECT), yellow for creates (INSERT), blue for updates (UPDATE), red for destroys (DELETE), magenta for transaction control and DDL (BEGIN/COMMIT/ROLLBACK/CREATE/ALTER/DROP). Unknown leads fall through to Color.plain.
Uniform-return-type discipline: every branch routes through a Color helper so the inferred return stays String. The same widening trap from color_method/color_status applies here — a bare ‘return sql` would fork the return into String|RbVal under Spinel’s analyzer.
Match is by leading-keyword on the raw SQL string. Generated model code always emits uppercase leads (see lib/templates/model.rb.erb); user-supplied ‘Fresco::Db.exec(…)` strings that lead with lowercase will fall through to Color.plain rather than mis-match, which is the right safety default.
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 |
# File 'lib/fresco/runtime/runtime.rb', line 1601 def color_sql(sql = "") return Color.green(sql) if sql.start_with?("SELECT") return Color.yellow(sql) if sql.start_with?("INSERT") return Color.blue(sql) if sql.start_with?("UPDATE") return Color.red(sql) if sql.start_with?("DELETE") return Color.magenta(sql) if sql.start_with?("BEGIN") return Color.magenta(sql) if sql.start_with?("COMMIT") return Color.magenta(sql) if sql.start_with?("ROLLBACK") return Color.magenta(sql) if sql.start_with?("CREATE") return Color.magenta(sql) if sql.start_with?("ALTER") return Color.magenta(sql) if sql.start_with?("DROP") Color.plain(sql) end |
#color_status(status = 0) ⇒ Object
Status: 2xx green (success), 3xx cyan (redirect), 4xx yellow (client error — operator should glance), 5xx red (server error —operator must look). 1xx falls through to Color.plain — same uniform-return-type discipline as color_method. ‘status.to_s` here is naturally String (Integer#to_s in Spinel is `sp_int_to_s` →`const char *`).
1576 1577 1578 1579 1580 1581 1582 1583 |
# File 'lib/fresco/runtime/runtime.rb', line 1576 def color_status(status = 0) s = status.to_s return Color.green(s) if status >= 200 && status < 300 return Color.cyan(s) if status >= 300 && status < 400 return Color.yellow(s) if status >= 400 && status < 500 return Color.red(s) if status >= 500 Color.plain(s) end |
#consume_flash_writes!(req) ⇒ Object
Before signing the outbound session cookie, copy req.flash.write_data into the session as ‘_flash.<key>` entries. Each set marks the session dirty, so the cookie will be emitted even if the handler didn’t touch req.session directly.
1246 1247 1248 1249 1250 1251 |
# File 'lib/fresco/runtime/runtime.rb', line 1246 def consume_flash_writes!(req) return if req.flash.write_data.length == 0 req.flash.write_data.each do |k, v| req.session.set(FLASH_KEY_PREFIX + k, v) end end |
#error_response(status, default_body) ⇒ Object
Per-status error page lookup. If ‘public/<status>.html` exists, serve it as the body (sendfile path); otherwise fall back to a plain-text body so 4xx/5xx still emit a sane response when the app hasn’t supplied a custom page. Used by the dispatcher 404, the static-file 404, the request-parse 400/413, and the action-raised 500 path. Keep this dead simple — no template rendering, no locals — so it stays callable when the rest of the app is broken.
1018 1019 1020 1021 1022 1023 1024 |
# File 'lib/fresco/runtime/runtime.rb', line 1018 def error_response(status, default_body) path = "public/" + status.to_s + ".html" if Sock.sphttp_file_size(path) >= 0 return Response.file(status, path, "text/html; charset=utf-8") end Response.text(status, default_body) end |
#file_response(rel_path = "", root = "") ⇒ Object
Build a sendfile-backed Response for a path-under-root. Rejects anything with ‘..` (traversal) or a leading `/` (absolute), then stats the file. Missing file → 404 (rendered via error_response, which picks up public/404.html if the app supplies one). Otherwise → Response.file with the right Content-Type for the extension.
Path-safety is intentionally simple: substring checks on the raw string. We don’t URL-decode (the parser leaves that alone for MVP), and we don’t follow symlinks back out of root. Good enough for an MVP serving from a known-safe public/ dir; tighten when needed.
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 |
# File 'lib/fresco/runtime/runtime.rb', line 999 def file_response(rel_path = "", root = "") if rel_path.include?("..") || rel_path.length == 0 || rel_path[0] == "/" return error_response(404, "Not Found") end abs = root + "/" + rel_path size = Sock.sphttp_file_size(abs) if size < 0 return error_response(404, "Not Found") end Response.file(200, abs, Mime.for_path(rel_path)) end |
#fmt_micros(us = 0) ⇒ Object
Format an integer micro-second count for the request / SQL log lines. Sub-millisecond values stay in micros (“742us”) so single- digit-millisecond values aren’t lost to rounding; >= 1ms switches to milliseconds with one decimal (“12.3ms”) because once you’re in the millis range nobody cares about the trailing micros.
Plain integer math — Spinel doesn’t lower Float arithmetic across the analyzer pass yet, and the rest of the timing code in this file is ‘int micros` throughout (sphttp_elapsed_micros returns `int`). The whole.to_s / tenth.to_s split keeps the result a narrow String.
1641 1642 1643 1644 1645 1646 |
# File 'lib/fresco/runtime/runtime.rb', line 1641 def fmt_micros(us = 0) return us.to_s + "us" if us < 1000 whole = us / 1000 tenth = (us % 1000) / 100 whole.to_s + "." + tenth.to_s + "ms" end |
#format_hash(h) ⇒ Object
Format a Sym→Str hash for the request log. Manual concat (vs Hash#inspect) keeps the each-block in the str-concat narrow path —Spinel infers the param as sym_str_hash from the k/v usage. See spinel test/hash_each_param_narrow.rb.
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 |
# File 'lib/fresco/runtime/runtime.rb', line 1619 def format_hash(h) out = "{" first = true h.each do |k, v| out += ", " unless first first = false out += k.to_s + "=" + v.to_s end out + "}" end |
#handle_connection(client) ⇒ Object
Serve one TCP connection. Loops until the client closes, a parse fails, or the response opts out of keep-alive. Each iteration reads a fresh request into the (reset) request buf; pipelining is out of scope — clients must wait for response N before sending request N+1.
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 |
# File 'lib/fresco/runtime/runtime.rb', line 1688 def handle_connection(client) keep_going = true while keep_going n = Sock.sphttp_read_request(client) break if n <= 0 # Parse-error logs still use the parse/write window below. Successful # requests reset the timer after parsing so dev and release report the # same app-handling window: dispatch + session-cookie attachment. Sock.sphttp_mark_now parsed = parse_http_request(client) if parsed.parse_status == 400 write_response(client, error_response(400, "Bad Request\n"), false) log_request_brief("?", "?", 400, Sock.sphttp_elapsed_micros) break end if parsed.parse_status == 413 write_response(client, error_response(413, "Payload Too Large\n"), false) log_request_brief("?", "?", 413, Sock.sphttp_elapsed_micros) break end keep_going = parsed.keep_alive? # Tell Fresco::Db to buffer SQL log lines during this request so # they flush as an indented block under the [request] line below # (instead of streaming above it in dispatch order). No-op when # FRESCO_LOG_SQL isn't set — the gate lives inside the db adapter. Fresco::Db.begin_request! begin Sock.sphttp_mark_now res = dispatch_request(parsed.verb, parsed.path, parsed) (parsed, res) micros = Sock.sphttp_elapsed_micros write_response(client, res, keep_going) log_request_full(parsed, res.status, micros) Fresco::Db.flush_log! rescue => e micros = Sock.sphttp_elapsed_micros # An action raised. Log a single line (so an operator can grep # for crashes) and serve a sanitised 500 — never the message, # since it could leak internals to clients. puts Color.red("[handler] ") + e.class + ": " + e. write_response(client, error_response(500, "Internal Server Error\n"), false) log_request_full(parsed, 500, micros) Fresco::Db.flush_log! keep_going = false end end Sock.sphttp_close(client) end |
#handle_dev_connection(client) ⇒ Object
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 |
# File 'lib/fresco/cli/dev_loop.rb', line 727 def handle_dev_connection(client) req = parse_dev_request(client) if req.nil? write_dev_response(client, error_response(400, "Bad Request\n")) puts "#{Color.dim('[request]')} ? ? #{color_status(400)}" return end # Mirror runtime.rb's request bracket so the SQL-log buffer flushes # under the [request] line. The Fresco::Db no-op stub is loaded even # when no adapter is configured, so this call is safe regardless. Fresco::Db.begin_request! t0 = Process.clock_gettime(Process::CLOCK_MONOTONIC) res = RELOAD_LOCK.synchronize { dispatch_request(req.verb, req.path, req) } (req, res) micros = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - t0) * 1_000_000).to_i write_dev_response(client, res) log_request_full(req, res.status, micros) Fresco::Db.flush_log! rescue => e puts "#{Color.red('[handler]')} #{e.class}: #{e.}" (e.backtrace || []).first(5).each { |b| puts Color.dim(" #{b}") } Fresco::Db.flush_log! begin write_dev_response(client, render_dev_error(e, req)) rescue StandardError # client already gone — nothing to do end ensure client.close rescue nil end |
#hex_char_upper(n = 0) ⇒ Object
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 |
# File 'lib/fresco/runtime/runtime.rb', line 1148 def hex_char_upper(n = 0) return "0" if n == 0 return "1" if n == 1 return "2" if n == 2 return "3" if n == 3 return "4" if n == 4 return "5" if n == 5 return "6" if n == 6 return "7" if n == 7 return "8" if n == 8 return "9" if n == 9 return "A" if n == 10 return "B" if n == 11 return "C" if n == 12 return "D" if n == 13 return "E" if n == 14 return "F" if n == 15 "0" end |
#hex_nibble(c = "") ⇒ Object
Single hex nibble — explicit case keeps each branch monomorphic on String. Returns -1 for a non-hex char so ‘url_decode` can fall back to literal ’%‘ rather than fabricating a byte. The `c = “”` default acts as a String type hint for Spinel: parameters without a default collapse to mrb_int when the analyzer can’t disambiguate (the same rule as ctor kwargs — see [[spinel_initialize_kwargs]]).
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 |
# File 'lib/fresco/runtime/runtime.rb', line 1032 def hex_nibble(c = "") return 0 if c == "0" return 1 if c == "1" return 2 if c == "2" return 3 if c == "3" return 4 if c == "4" return 5 if c == "5" return 6 if c == "6" return 7 if c == "7" return 8 if c == "8" return 9 if c == "9" return 10 if c == "a" || c == "A" return 11 if c == "b" || c == "B" return 12 if c == "c" || c == "C" return 13 if c == "d" || c == "D" return 14 if c == "e" || c == "E" return 15 if c == "f" || c == "F" -1 end |
#log_request_brief(method, path, status, micros) ⇒ Object
1648 1649 1650 1651 |
# File 'lib/fresco/runtime/runtime.rb', line 1648 def log_request_brief(method, path, status, micros) puts Color.dim("[request] ") + color_method(method) + " " + path + " " + color_status(status) + " " + Color.dim("(" + fmt_micros(micros) + ")") end |
#log_request_full(req, status, micros) ⇒ Object
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 |
# File 'lib/fresco/runtime/runtime.rb', line 1653 def log_request_full(req, status, micros) line = Color.dim("[request] ") + color_method(req.verb) + " " + req.path + " " + color_status(status) + " " + Color.dim("(" + fmt_micros(micros) + ")") # SQL roll-up. The db adapter funnels per-query micros into the # `Fresco`-module counters during the request (zeroed by # `Fresco::Db.begin_request!` → `Fresco.reset_db_sql_stats!`); # we read both back here so the operator sees the SQL share of # the request budget on the same line as the request total. # Read from `Fresco` (same file) rather than `Fresco::Db` (loaded # later) because cross-file value-returning module calls resolve # the receiver to `int` and emit 0 under Spinel — see the # comment on the counters' declaration above. `query_count == 0` # suppresses the segment entirely so request lines for handlers # that don't touch the DB stay short. The totals are maintained # even when FRESCO_LOG_SQL is off — per-query lines are gated, # the cheap roll-up isn't. sql_us = Fresco.db_sql_total_micros sql_n = Fresco.db_sql_query_count if sql_n > 0 line += " " + Color.dim("sql=" + fmt_micros(sql_us) + "/" + sql_n.to_s + "q") end # Query is now folded into params at parse time; logging only the # merged hash keeps the formatter monomorphic on Sym→Str (plan # decision #5). `req.params.raw` is the underlying Hash — handing # the Params wrapper to `format_hash` would force a second type. if req.params.length > 0 line += " " + Color.dim("params=" + format_hash(req.params.raw)) end puts line end |
#maybe_load_session!(req) ⇒ Object
If a signed session cookie is present and a secret is configured, verify + decode it into req.session. No-ops when either piece is missing — the bag stays empty and handlers writing to it just stage fresh state for the response cookie.
1203 1204 1205 1206 1207 1208 1209 1210 1211 |
# File 'lib/fresco/runtime/runtime.rb', line 1203 def maybe_load_session!(req) secret = Fresco.session_secret return if secret.length == 0 cv = req.[SESSION_COOKIE_NAME] return if cv.nil? return if cv.length == 0 req.session.load_from(cv, secret) promote_flash!(req) end |
#parse_cookie_header!(s = "", into = { "__t" => "" }) ⇒ Object
Parse a Cookie: header value (‘a=1; b=hello%20world; flag`) into the given Str->Str hash. Values are URL-decoded (clients may percent-encode arbitrary bytes; we always round-trip via `url_decode` on read). Bare tokens with no `=` are recorded as empty-value entries — rare but preserves “is this name present?” semantics.
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 |
# File 'lib/fresco/runtime/runtime.rb', line 1173 def (s = "", into = { "__t" => "" }) i = 0 n = s.length while i < n # Skip leading whitespace between pairs. while i < n && (s[i] == " " || s[i] == "\t") i += 1 end break if i >= n pair_end = str_idx_from(s, ";", i) pair_end = n if pair_end < 0 eq = str_idx_from(s, "=", i) if eq < 0 || eq >= pair_end into[s[i...pair_end]] = "" else name = s[i...eq] value = url_decode(s[(eq + 1)...pair_end]) into[name] = value end i = pair_end + 1 end end |
#parse_dev_request(sock) ⇒ Object
— Dev HTTP listener ——————————————
Single-threaded TCPServer accept loop. Each request: parse the request line + headers, read a Content-Length-bounded body, build a Request, dispatch under RELOAD_LOCK (so file-watcher reloads don’t race with in-flight requests), write the response. No keep-alive —every dev response carries ‘Connection: close`. Keep-alive lives in the prefork worker on the prod path.
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 |
# File 'lib/fresco/cli/dev_loop.rb', line 502 def parse_dev_request(sock) request_line = sock.gets("\r\n") return nil if request_line.nil? method, raw_path, _version = request_line.strip.split(" ", 3) return nil if method.nil? || raw_path.nil? qmark = raw_path.index("?") if qmark path = raw_path[0...qmark] qstr = raw_path[(qmark + 1)..] else path = raw_path qstr = "" end headers = {} while (line = sock.gets("\r\n")) line = line.chomp break if line.empty? colon = line.index(":") next unless colon name = line[0...colon].downcase value = line[(colon + 1)..].lstrip headers[name] = value end body = "" cl = headers["content-length"] if cl && cl.to_i > 0 body = sock.read(cl.to_i) || "" end req = Request.new(method, path, body) parse_query_string!(qstr, req.params) if qstr.length > 0 headers.each { |k, v| req.headers[k] = v } ctype = headers["content-type"] if ctype && ctype == "application/x-www-form-urlencoded" parse_form_body!(body, req.params) end # Mirror runtime's `_method` override (see runtime/runtime.rb). if req.verb == "POST" override = req.params.str(:_method) req.verb = override.upcase if override.length > 0 end # Parse Cookie header into req.cookies. We can't reuse runtime's # `parse_cookie_header!` because it relies on Spinel's # `String#index`-returns-`-1` semantics (CRuby returns nil). The # idiomatic split-and-loop below is equivalent. = headers["cookie"] if && !.empty? .split(";").each do |pair| pair = pair.strip next if pair.empty? eq = pair.index("=") if eq.nil? req.[pair] = "" else req.[pair[0...eq]] = url_decode(pair[(eq + 1)..]) end end end maybe_load_session!(req) req end |
#parse_form_body!(body, into) ⇒ Object
Form bodies share the ‘application/x-www-form-urlencoded` framing with query strings — same `k=v&k=v`, same percent/`+` decode. Kept as a separate function (vs aliasing) so the call-site reads “form body” rather than “abusing the query parser”. Takes the `Params` wrapper for the same reason as `parse_query_string!`.
1118 1119 1120 |
# File 'lib/fresco/runtime/runtime.rb', line 1118 def parse_form_body!(body, into) parse_query_string!(body, into) end |
#parse_http_request(client) ⇒ Object
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 |
# File 'lib/fresco/runtime/runtime.rb', line 1293 def parse_http_request(client) buf = Sock.sphttp_request_buf buf_len = Sock.sphttp_request_len hdr_end = Sock.sphttp_header_end return bad_request if hdr_end < 0 return bad_request if buf_len <= 0 rl_end = str_idx(buf, "\r\n") return bad_request if rl_end < 0 request_line = buf[0...rl_end] parts = request_line.split(" ") return bad_request if parts.length < 3 method = parts[0] raw_path = parts[1] version = parts[2] qmark = str_idx(raw_path, "?") if qmark >= 0 path = raw_path[0...qmark] qstr = raw_path[(qmark + 1)...raw_path.length] else path = raw_path qstr = "" end # Build the Request now so the parser can fill its headers/body # in place. Reassigning @headers risks Spinel's polymorphic-write # no-op trap (plan's Spinel quirks). req = Request.new(method, path, "") req.version = version hdrs = req.headers # Fold the query string directly into the params hash. The # dispatcher will write path captures into the same hash after this # parse returns, so path beats query without explicit precedence # logic — see plan decision #2. parse_query_string!(qstr, req.params) if qstr.length > 0 # cl + ctype captured during the header walk so the body-read step # below doesn't need a `hdrs[]` lookup. Reading through `hdrs[]` (a # Str→Str hash exposed via `attr_reader :headers`) returns sp_RbVal # under Spinel, and `cl_str.to_i` on a boxed value silently evaluates # to 0 — the body never gets drained and form-body params come back # empty. Capturing the values inline avoids the boxed read entirely. cl = 0 ctype = "" i = rl_end + 2 limit = hdr_end - 2 # one CRLF before the blank-line CRLF while i < limit line_end = str_idx_from(buf, "\r\n", i) break if line_end < 0 break if line_end == i colon = str_idx_from(buf, ":", i) if colon > i && colon < line_end name = buf[i...colon].downcase v = colon + 1 while v < line_end && buf[v] == " " v += 1 end val = buf[v...line_end] hdrs[name] = val cl = val.to_i if name == "content-length" ctype = val if name == "content-type" end i = line_end + 2 end = hdrs["cookie"] if && .length > 0 (, req.) end maybe_load_session!(req) # `cl` and `ctype` were captured during the header walk above — # see the comment there for why we don't read them back through # `hdrs[]` here. if cl > 0 if cl > 1048576 req.parse_status = 413 return req end body_in_buf = buf_len - hdr_end if body_in_buf < 0 body_in_buf = 0 end have = body_in_buf < cl ? body_in_buf : cl # Seed body buf with bytes that came in with the headers. Sock.sphttp_copy_body(hdr_end, 0, have) if have < cl Sock.sphttp_drain_body(client, have, cl - have) end # `+ ""` forces a Ruby-owned copy out of the C-owned body buf, # which will be overwritten on the next request. Stash in a local # so the form-body parser below gets a String-pinned value — # reading back through `req.body`'s attr_accessor widens the type # at the call site and the downstream `s.split("&")` lowers to a # silent no-op. body_str = Sock.sphttp_body_buf + "" req.body = body_str # Fold form bodies into the same params hash query went into. # Exact-match content-type filter (plan decision #6) — no # tolerance for `; charset=utf-8` suffixes in MVP. The dispatcher # writes path captures after parse_http_request returns, so the # final precedence is path > form > query. # # Calls parse_query_string! directly (not parse_form_body!): the # one-line indirection through parse_form_body! collapses param # types to mrb_int under Spinel and the parse silently no-ops. if ctype == "application/x-www-form-urlencoded" parse_query_string!(body_str, req.params) end end # Rails-style `_method` override: HTML forms can only emit GET/POST, # so a hidden `_method=patch|put|delete` lets a POST form route as # the verb the dispatcher expects. Only honored when the wire method # is POST — query-string overrides on GET would let a stray link # delete things. if req.verb == "POST" override = req.params.str(:_method) req.verb = override.upcase if override.length > 0 end req end |
#parse_query_string!(s, into) ⇒ Object
Parse ‘k=v&k=v` into the supplied Params wrapper. Mutates in place to dodge the polymorphic-write no-op (plan quirks). Both name and value run through `url_decode` so `?q=hello%20world` lands as `:q => “hello world”`.
Takes the ‘Params` object rather than the raw hash so writes lower through the monomorphic `Params#set_sym`. Spinel’s generic polymorphic ‘Hash#[]=` only emits array branches in the dispatch and silently no-ops on the hash case.
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 |
# File 'lib/fresco/runtime/runtime.rb', line 1094 def parse_query_string!(s, into) pairs = s.split("&") i = 0 while i < pairs.length pair = pairs[i] if pair.length > 0 eq = str_idx(pair, "=") if eq < 0 into.set_sym(url_decode(pair).to_sym, "") else name = url_decode(pair[0...eq]).to_sym value = url_decode(pair[(eq + 1)...pair.length]) into.set_sym(name, value) end end i += 1 end end |
#promote_flash!(req) ⇒ Object
Move any ‘_flash.<key>` entries from the loaded session into req.flash.read_data, removing them from the session as we go. The removal marks the session dirty so the cleared state ships back in the response cookie — that’s how flash earns its “one bounce only” guarantee. If no flash entries are present this is a no-op (session stays clean).
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 |
# File 'lib/fresco/runtime/runtime.rb', line 1219 def promote_flash!(req) data = req.session.data prefix_len = FLASH_KEY_PREFIX.length # Collect keys first; can't safely mutate a hash while iterating it. to_clear = [""] to_clear.delete_at(0) data.each do |k, v| if k.length > prefix_len && k[0, prefix_len] == FLASH_KEY_PREFIX short_key = k[prefix_len, k.length - prefix_len] req.flash.read_data[short_key] = v to_clear.push(k) end end i = 0 while i < to_clear.length data.delete(to_clear[i]) i += 1 end if to_clear.length > 0 req.session.mark_dirty end end |
#reason_for(status) ⇒ Object
770 771 772 773 774 |
# File 'lib/fresco/runtime/runtime.rb', line 770 def reason_for(status) r = REASON_PHRASES[status] return r if r "OK" end |
#reload! ⇒ Object
‘load` (vs require) re-evaluates on each call so reloads pick up edits. Paths are relative to ROOT (we chdir’d above).
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 |
# File 'lib/fresco/cli/dev_loop.rb', line 82 def reload! RELOAD_LOCK.synchronize do load "generated/runtime.rb" Dir.glob("generated/views/*.rb").sort.each { |f| load f } load "generated/layout_dispatch.rb" # db_adapter mirrors boot.rb's order: between layout_dispatch and # config/app so the FFI module + Fresco::Db::Active are defined # before user code can reference them. `fresco build` always emits # this file (an empty stub when no adapter is configured), so the # load never misses. load "generated/db_adapter.rb" # Migrations runner — defines Fresco::DbMigrations. Used by # `./app db:migrate` and `fresco dev db:migrate` alike, so it has # to be on the dev load path too. Boot.rb requires it between # db_adapter and config/app; we mirror that order here. load "generated/migrations.rb" load "config/app.rb" # config/database.rb populates Fresco.app.database_config from the # running process's environment (ENV.fetch lives inside the file). # `fresco build` also synthesises a placeholder when the user # didn't supply one, so the load is unconditional. load "config/database.rb" if File.exist?("config/database.rb") # Generated models load before user action.rb so action classes # can reference them. Models live under generated/models/ (one .rb # per declared model in app/models/) — same file location dev and # release use. Dir.glob("generated/models/*.rb").sort.each { |f| load f } load "app/action.rb" Dir.glob("app/actions/**/*.rb").sort.each { |f| load f } # Fresco-supplied default welcome action — only present when # config/routes.rb has no `root to:` and `fresco build` emitted # the fallback. Dispatch.rb references Fresco::Welcome, so load # it before the dispatcher. load "generated/welcome.rb" if File.exist?("generated/welcome.rb") load "generated/dispatch.rb" # The C shim isn't linked under CRuby — `ffi_func` was a no-op # above, so `Sock` exists but has no methods. Provide CRuby # stand-ins for the handful of Sock entries the runtime calls # from non-server code paths (i.e. inside actions like Files::Show). # The server-loop entries (sphttp_listen/accept/read/etc.) aren't # needed because serve_dev replaces that loop entirely. Sock.define_singleton_method(:sphttp_file_size) do |path| File.exist?(path) ? File.size(path) : -1 end # HMAC stand-ins. Under Spinel these are the public-domain # SHA-256/HMAC code in generated/runtime/http.c; under CRuby we # route through OpenSSL::HMAC so the Session class round-trips # identically. require "openssl" require "base64" Sock.define_singleton_method(:sphttp_hmac_sha256_hex) do |key, msg| OpenSSL::HMAC.hexdigest("SHA256", key, msg) end Sock.define_singleton_method(:sphttp_hmac_sha256_b64url) do |key, msg| Base64.urlsafe_encode64(OpenSSL::HMAC.digest("SHA256", key, msg), padding: false) end # Monotonic-clock stand-ins for the request-timing primitives the # production handle_connection uses. Actions can reach for these # (e.g. an around filter that times its work) and `fresco dev` # needs to honor the same API surface, even though serve_dev's own # loop doesn't rely on them. Sock.instance_variable_set(:@dev_mark, 0) Sock.define_singleton_method(:sphttp_mark_now) do Sock.instance_variable_set(:@dev_mark, Process.clock_gettime(Process::CLOCK_MONOTONIC, :microsecond)) 0 end Sock.define_singleton_method(:sphttp_elapsed_micros) do Process.clock_gettime(Process::CLOCK_MONOTONIC, :microsecond) - Sock.instance_variable_get(:@dev_mark) end # DB adapter stand-ins. config/database.rb (loaded above) sets # Fresco.app.database_config; we install the matching FFI stubs so # actions hitting Fresco::Db::Active work under CRuby. Production # routes through the linked C shim instead; the Ruby surface is # identical so dev and prod behave the same from action code. db_adapter = Fresco.database_adapter || :none if db_adapter == :sqlite require "sqlite3" Sock.instance_variable_set(:@dev_sqlite_handles, [nil] * 16) Sock.instance_variable_set(:@dev_sqlite_stmts, [nil] * 64) Sqlite.define_singleton_method(:fresco_sqlite_open) do |path| handles = Sock.instance_variable_get(:@dev_sqlite_handles) slot = handles.index(nil) return -1 if slot.nil? begin handles[slot] = ::SQLite3::Database.new(path) slot + 1 rescue ::SQLite3::Exception -1 end end Sqlite.define_singleton_method(:fresco_sqlite_close) do |h| handles = Sock.instance_variable_get(:@dev_sqlite_handles) stmts = Sock.instance_variable_get(:@dev_sqlite_stmts) return -1 if h < 1 || h > handles.length db = handles[h - 1] return -1 if db.nil? stmts.each_with_index do |s, i| next if s.nil? if s[0] == db s[1].close unless s[1].closed? stmts[i] = nil end end db.close handles[h - 1] = nil 0 end Sqlite.define_singleton_method(:fresco_sqlite_exec) do |h, sql| handles = Sock.instance_variable_get(:@dev_sqlite_handles) return -1 if h < 1 || h > handles.length db = handles[h - 1] return -1 if db.nil? begin db.execute_batch(sql) 0 rescue ::SQLite3::Exception -1 end end Sqlite.define_singleton_method(:fresco_sqlite_prepare) do |h, sql| handles = Sock.instance_variable_get(:@dev_sqlite_handles) stmts = Sock.instance_variable_get(:@dev_sqlite_stmts) return -1 if h < 1 || h > handles.length db = handles[h - 1] return -1 if db.nil? slot = stmts.index(nil) return -1 if slot.nil? begin stmt = db.prepare(sql) stmts[slot] = [db, stmt, nil] # [db, stmt, last_step_row_or_nil] slot + 1 rescue ::SQLite3::Exception -1 end end Sqlite.define_singleton_method(:fresco_sqlite_bind_str) do |cid, idx, value| stmts = Sock.instance_variable_get(:@dev_sqlite_stmts) return -1 if cid < 1 || cid > stmts.length entry = stmts[cid - 1] return -1 if entry.nil? begin entry[1].bind_param(idx, value) 0 rescue ::SQLite3::Exception -1 end end Sqlite.define_singleton_method(:fresco_sqlite_bind_int) do |cid, idx, value| stmts = Sock.instance_variable_get(:@dev_sqlite_stmts) return -1 if cid < 1 || cid > stmts.length entry = stmts[cid - 1] return -1 if entry.nil? begin entry[1].bind_param(idx, value) 0 rescue ::SQLite3::Exception -1 end end Sqlite.define_singleton_method(:fresco_sqlite_step) do |cid| stmts = Sock.instance_variable_get(:@dev_sqlite_stmts) return -1 if cid < 1 || cid > stmts.length entry = stmts[cid - 1] return -1 if entry.nil? # The gem's stmt acts as an iterator; capture the next row (or # nil at end-of-result) so col_* lookups read off the same row. entry[2] = entry[1].step return 0 if entry[2].nil? 1 end Sqlite.define_singleton_method(:fresco_sqlite_col_str) do |cid, idx| stmts = Sock.instance_variable_get(:@dev_sqlite_stmts) return "" if cid < 1 || cid > stmts.length entry = stmts[cid - 1] return "" if entry.nil? || entry[2].nil? v = entry[2][idx] v.nil? ? "" : v.to_s end Sqlite.define_singleton_method(:fresco_sqlite_col_int) do |cid, idx| stmts = Sock.instance_variable_get(:@dev_sqlite_stmts) return 0 if cid < 1 || cid > stmts.length entry = stmts[cid - 1] return 0 if entry.nil? || entry[2].nil? v = entry[2][idx] v.nil? ? 0 : v.to_i end Sqlite.define_singleton_method(:fresco_sqlite_col_count) do |cid| stmts = Sock.instance_variable_get(:@dev_sqlite_stmts) return 0 if cid < 1 || cid > stmts.length entry = stmts[cid - 1] return 0 if entry.nil? entry[1].columns.length end Sqlite.define_singleton_method(:fresco_sqlite_finalize) do |cid| stmts = Sock.instance_variable_get(:@dev_sqlite_stmts) return 0 if cid < 1 || cid > stmts.length entry = stmts[cid - 1] return 0 if entry.nil? entry[1].close unless entry[1].closed? stmts[cid - 1] = nil 0 end Sqlite.define_singleton_method(:fresco_sqlite_reset) do |cid| stmts = Sock.instance_variable_get(:@dev_sqlite_stmts) return -1 if cid < 1 || cid > stmts.length entry = stmts[cid - 1] return -1 if entry.nil? entry[1].reset! entry[2] = nil 0 end Sqlite.define_singleton_method(:fresco_sqlite_last_insert_rowid) do |h| handles = Sock.instance_variable_get(:@dev_sqlite_handles) return -1 if h < 1 || h > handles.length db = handles[h - 1] return -1 if db.nil? db.last_insert_row_id.to_i end end if db_adapter == :postgres # Postgres stand-ins. The `pg` gem is loaded lazily so apps on # the SQLite adapter (or with no DB) don't need it installed. # Mirrors the production generated/runtime/postgres.c shim: # per-cursor state holding {conn, sql, accumulated binds, # PGresult, row index}; bind_*/step lazy-execute via PQexecParams # on first step. begin require "pg" rescue LoadError abort "[dev] config/database.rb declares :postgres but the `pg` gem " \ "is not installed. Add `gem \"pg\"` to the :development group " \ "in your Gemfile and bundle." end Sock.instance_variable_set(:@dev_pg_handles, [nil] * 16) Sock.instance_variable_set(:@dev_pg_stmts, [nil] * 64) Pg.define_singleton_method(:fresco_pg_open) do |url| handles = Sock.instance_variable_get(:@dev_pg_handles) slot = handles.index(nil) return -1 if slot.nil? begin handles[slot] = ::PG.connect(url) slot + 1 rescue ::PG::Error -1 end end Pg.define_singleton_method(:fresco_pg_close) do |h| handles = Sock.instance_variable_get(:@dev_pg_handles) stmts = Sock.instance_variable_get(:@dev_pg_stmts) return -1 if h < 1 || h > handles.length conn = handles[h - 1] return -1 if conn.nil? stmts.each_with_index do |s, i| next if s.nil? if s[:conn] == conn stmts[i] = nil end end conn.close handles[h - 1] = nil 0 end Pg.define_singleton_method(:fresco_pg_exec) do |h, sql| handles = Sock.instance_variable_get(:@dev_pg_handles) return -1 if h < 1 || h > handles.length conn = handles[h - 1] return -1 if conn.nil? begin conn.exec(sql) 0 rescue ::PG::Error -1 end end Pg.define_singleton_method(:fresco_pg_prepare) do |h, sql| handles = Sock.instance_variable_get(:@dev_pg_handles) stmts = Sock.instance_variable_get(:@dev_pg_stmts) return -1 if h < 1 || h > handles.length conn = handles[h - 1] return -1 if conn.nil? slot = stmts.index(nil) return -1 if slot.nil? # Defer execution until the first step, like the C shim. Binds # accumulate into :params (1-indexed, sparse), then PQexecParams # equivalent fires on first step. stmts[slot] = { conn: conn, sql: sql, params: [], result: nil, row: -1, ntuples: 0 } slot + 1 end Pg.define_singleton_method(:fresco_pg_bind_str) do |cid, idx, value| stmts = Sock.instance_variable_get(:@dev_pg_stmts) return -1 if cid < 1 || cid > stmts.length entry = stmts[cid - 1] return -1 if entry.nil? entry[:params][idx - 1] = value.to_s 0 end Pg.define_singleton_method(:fresco_pg_bind_int) do |cid, idx, value| stmts = Sock.instance_variable_get(:@dev_pg_stmts) return -1 if cid < 1 || cid > stmts.length entry = stmts[cid - 1] return -1 if entry.nil? entry[:params][idx - 1] = value.to_s 0 end Pg.define_singleton_method(:fresco_pg_step) do |cid| stmts = Sock.instance_variable_get(:@dev_pg_stmts) return -1 if cid < 1 || cid > stmts.length entry = stmts[cid - 1] return -1 if entry.nil? if entry[:result].nil? # First step: fire query with accumulated binds. Replace nils # with empty strings so libpq's text coercion has something # to chew on. values = entry[:params].map { |v| v.nil? ? "" : v } begin entry[:result] = entry[:conn].exec_params(entry[:sql], values) entry[:ntuples] = entry[:result].ntuples entry[:row] = -1 rescue ::PG::Error entry[:result] = nil return -1 end end entry[:row] += 1 entry[:row] < entry[:ntuples] ? 1 : 0 end Pg.define_singleton_method(:fresco_pg_col_str) do |cid, idx| stmts = Sock.instance_variable_get(:@dev_pg_stmts) return "" if cid < 1 || cid > stmts.length entry = stmts[cid - 1] return "" if entry.nil? || entry[:result].nil? return "" if entry[:row] < 0 || entry[:row] >= entry[:ntuples] v = entry[:result].getvalue(entry[:row], idx) v.nil? ? "" : v.to_s end Pg.define_singleton_method(:fresco_pg_col_int) do |cid, idx| stmts = Sock.instance_variable_get(:@dev_pg_stmts) return 0 if cid < 1 || cid > stmts.length entry = stmts[cid - 1] return 0 if entry.nil? || entry[:result].nil? return 0 if entry[:row] < 0 || entry[:row] >= entry[:ntuples] v = entry[:result].getvalue(entry[:row], idx) v.nil? ? 0 : v.to_i end Pg.define_singleton_method(:fresco_pg_col_count) do |cid| stmts = Sock.instance_variable_get(:@dev_pg_stmts) return 0 if cid < 1 || cid > stmts.length entry = stmts[cid - 1] return 0 if entry.nil? || entry[:result].nil? entry[:result].nfields end Pg.define_singleton_method(:fresco_pg_finalize) do |cid| stmts = Sock.instance_variable_get(:@dev_pg_stmts) return 0 if cid < 1 || cid > stmts.length stmts[cid - 1] = nil 0 end Pg.define_singleton_method(:fresco_pg_reset) do |cid| stmts = Sock.instance_variable_get(:@dev_pg_stmts) return -1 if cid < 1 || cid > stmts.length entry = stmts[cid - 1] return -1 if entry.nil? entry[:result] = nil entry[:row] = -1 entry[:ntuples] = 0 0 end Pg.define_singleton_method(:fresco_pg_last_insert_rowid) do |h| handles = Sock.instance_variable_get(:@dev_pg_handles) return -1 if h < 1 || h > handles.length conn = handles[h - 1] return -1 if conn.nil? begin res = conn.exec("SELECT lastval()") res.ntuples > 0 ? res.getvalue(0, 0).to_i : -1 rescue ::PG::Error -1 end end end end end |
#render_dev_error(err, req) ⇒ Object
Dev-only crash page. Renders the exception class, message, and backtrace inline so /crash (and any other action raise) shows up in the browser instead of being a static “Internal Server Error” page. NEVER call this in production — leaks paths, gem versions, and whatever string the exception happened to carry.
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 |
# File 'lib/fresco/cli/dev_loop.rb', line 617 def render_dev_error(err, req) esc = ->(s) { Spinel::View.h(s.to_s) } bt = (err.backtrace || []).map { |line| "<li>#{esc.call(line)}</li>" }.join method = req ? req.verb : "?" path = req ? req.path : "?" params = req ? format_hash(req.params.raw) : "(unavailable)" query = req ? format_hash(req.query) : "(unavailable)" headers = req ? format_hash(req.headers) : "(unavailable)" body = <<~HTML <!doctype html> <html> <head> <meta charset="utf-8"> <title>500 — #{esc.call(err.class.name)}</title> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;700&display=swap" rel="stylesheet"> <script> (function () { var t = localStorage.getItem("theme"); if (!t) { t = (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) ? "dark" : "light"; localStorage.setItem("theme", t); } document.documentElement.setAttribute("data-theme", t); })(); </script> <style> :root { --bg: #fff; --fg: #222; --muted: #888; --border: #eee; --code-bg: #f7f7f7; --accent: #0066cc; --status: #b00020; } :root[data-theme="dark"] { --bg: #141414; --fg: #e8e8e8; --muted: #9a9a9a; --border: #2a2a2a; --code-bg: #1f1f1f; --accent: #6ab0ff; --status: #ff6680; } body { font-family: 'IBM Plex Mono', ui-monospace, monospace; max-width: 60rem; margin: 2rem auto; padding: 0 1.5rem; background: var(--bg); color: var(--fg); transition: background 0.15s, color 0.15s; } .status { color: var(--status); font-size: 0.8rem; letter-spacing: 0.05em; text-transform: uppercase; } h1 { font-size: 1.25rem; font-weight: 700; margin: 0.25rem 0 0; word-break: break-word; } .msg { color: var(--muted); margin: 0.5rem 0 1.5rem; white-space: pre-wrap; } h2 { font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted); margin-top: 2rem; } ol.bt { background: var(--code-bg); border: 1px solid var(--border); border-radius: 4px; padding: 1rem 1rem 1rem 3rem; font-size: 0.85rem; line-height: 1.5; color: var(--fg); } ol.bt li { word-break: break-all; } dl { display: grid; grid-template-columns: 6rem 1fr; gap: 0.4rem 1rem; font-size: 0.85rem; } dt { color: var(--muted); } dd { margin: 0; word-break: break-word; } footer { color: var(--muted); font-size: 0.8rem; margin-top: 2rem; border-top: 1px solid var(--border); padding-top: 1rem; } #theme-toggle { position: fixed; top: 1rem; right: 1rem; background: transparent; border: 1px solid var(--border); color: var(--fg); border-radius: 6px; padding: 0.4rem; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; } #theme-toggle:hover { background: var(--code-bg); } #theme-toggle svg { width: 18px; height: 18px; display: none; } :root[data-theme="light"] #theme-toggle .icon-moon { display: inline-block; } :root[data-theme="dark"] #theme-toggle .icon-sun { display: inline-block; } </style> </head> <body> <button id="theme-toggle" aria-label="Toggle color theme" title="Toggle color theme"> <svg class="icon-sun" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/></svg> <svg class="icon-moon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg> </button> <div class="status">500 · fresco dev exception</div> <h1>#{esc.call(err.class.name)}</h1> <p class="msg">#{esc.call(err.)}</p> <h2>Backtrace</h2> <ol class="bt">#{bt}</ol> <h2>Request</h2> <dl> <dt>Method</dt><dd>#{esc.call(method)}</dd> <dt>Path</dt><dd>#{esc.call(path)}</dd> <dt>Params</dt><dd>#{esc.call(params)}</dd> <dt>Query</dt><dd>#{esc.call(query)}</dd> <dt>Headers</dt><dd>#{esc.call(headers)}</dd> </dl> <footer>Rendered by `fresco dev`. Production serves public/500.html with no error details.</footer> <script> (function () { document.getElementById("theme-toggle").addEventListener("click", function () { var cur = document.documentElement.getAttribute("data-theme"); var nxt = cur === "dark" ? "light" : "dark"; document.documentElement.setAttribute("data-theme", nxt); localStorage.setItem("theme", nxt); }); })(); </script> </body> </html> HTML Response.html(500, body) end |
#run_server(port:, workers: 1) ⇒ Object
1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 |
# File 'lib/fresco/runtime/runtime.rb', line 1774 def run_server(port:, workers: 1) if workers <= 1 sfd = Sock.sphttp_listen(port, 0) if sfd < 0 puts Color.red("[server] ") + "sphttp_listen failed on port " + port.to_s return end puts Color.cyan("[server] ") + "listening on http://0.0.0.0:" + port.to_s + " (pid " + Sock.sphttp_getpid.to_s + ")" worker_loop(sfd) return end puts Color.cyan("[server] ") + "listening on http://0.0.0.0:" + port.to_s + " (parent pid " + Sock.sphttp_getpid.to_s + ", workers=" + workers.to_s + ")" workers.times do |i| spawn_worker(port, i) end # Reap-and-respawn: when a worker dies (crash or graceful exit), # the parent forks a fresh replacement so the served-process count # stays steady. General-purpose crash safety net — handlers that # raise are already caught inside handle_connection, but anything # that escapes (OS-level signal, FFI fault) drops the worker, and # without respawn the service degrades over time. # # `slot` is monotonically incremented so log lines remain unique # (a respawned worker reports `slot=42` etc., not slot 0 again), # making it easy to count restarts from logs. The initial spawn # uses 0..N-1, so respawn slots start at `workers` to avoid overlap. next_slot = workers loop do reaped = Sock.sphttp_wait_any break if reaped < 0 puts Color.dim("[server] reaped worker pid " + reaped.to_s + " — respawning as slot " + next_slot.to_s) spawn_worker(port, next_slot) next_slot += 1 end end |
#serve_dev(port) ⇒ Object
601 602 603 604 605 606 607 608 609 610 |
# File 'lib/fresco/cli/dev_loop.rb', line 601 def serve_dev(port) server = TCPServer.new("0.0.0.0", port) puts "#{Color.cyan('[dev]')} listening on http://0.0.0.0:#{port}" loop do client = server.accept handle_dev_connection(client) end rescue Interrupt puts "\n#{Color.cyan('[dev]')} stopping" end |
#snapshot_mtimes ⇒ Object
472 473 474 475 |
# File 'lib/fresco/cli/dev_loop.rb', line 472 def snapshot_mtimes files = WATCH_GLOBS.flat_map { |g| Dir.glob(g) }.sort files.each_with_object({}) { |f, h| h[f] = File.mtime(f).to_f } end |
#spawn_worker(port = 0, slot = 0) ⇒ Object
Prefork model. With workers == 1 we run the accept loop inline (no fork, easier to debug, same behavior as M4). With workers > 1 the parent forks N children — each opens its OWN SO_REUSEPORT listener on ‘port`, and the kernel load-balances incoming accepts across them. The parent never opens a listener; it just waits to reap children. Killing one worker (kill -9) leaves the others serving while the parent reaps the corpse. Fork one worker process and return the child’s pid in the parent. Child branch runs worker_loop until exit(0) / crash. Extracted so the initial spawn loop and the reap-loop respawn use one code path —important so the listener-setup details and the “ready” log line stay in lock-step between fresh-boot and post-crash respawn.
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 |
# File 'lib/fresco/runtime/runtime.rb', line 1759 def spawn_worker(port = 0, slot = 0) pid = Sock.sphttp_fork if pid == 0 sfd = Sock.sphttp_listen(port, 1) # SO_REUSEPORT — each worker binds independently if sfd < 0 puts Color.red("[worker " + Sock.sphttp_getpid.to_s + "] ") + "sphttp_listen failed" exit(1) end puts Color.cyan("[worker " + Sock.sphttp_getpid.to_s + "] ") + "ready (slot " + slot.to_s + ")" worker_loop(sfd) exit(0) end pid end |
#start_watcher ⇒ Object
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 |
# File 'lib/fresco/cli/dev_loop.rb', line 477 def start_watcher last = snapshot_mtimes Thread.new do Thread.current.abort_on_exception = false loop do sleep 0.2 cur = snapshot_mtimes next if cur == last changed = (cur.keys | last.keys).select { |k| cur[k] != last[k] } last = cur puts "#{Color.yellow('[reload]')} #{changed.join(', ')}" reload! if build! end end end |
#str_idx(s = "", needle = "") ⇒ Object
Spinel #532: ‘String#index` / `#rindex` now return boxed poly (nil for not-found, boxed int when found) instead of `mrb_int` with a `-1` sentinel. These wrappers restore the old contract so call sites can keep using `pos < 0` as the not-found test and pass `pos` to int-expecting slices (`s[pos, n]`, `s`) without each site having to unbox by hand. The `s = “”` / `needle = “”` / `start
0` defaults pin parameter types — required positional args with
no type signal collapse to ‘mrb_int` in Spinel’s analyzer.
169 170 171 172 |
# File 'lib/fresco/runtime/runtime.rb', line 169 def str_idx(s = "", needle = "") p = s.index(needle) p.nil? ? -1 : p.to_i end |
#str_idx_from(s = "", needle = "", start = 0) ⇒ Object
174 175 176 177 |
# File 'lib/fresco/runtime/runtime.rb', line 174 def str_idx_from(s = "", needle = "", start = 0) p = s.index(needle, start) p.nil? ? -1 : p.to_i end |
#str_ridx(s = "", needle = "") ⇒ Object
179 180 181 182 |
# File 'lib/fresco/runtime/runtime.rb', line 179 def str_ridx(s = "", needle = "") p = s.rindex(needle) p.nil? ? -1 : p.to_i end |
#url_decode(s = "") ⇒ Object
‘+` → space, then `%XX` → byte. Byte walk + char concat — no String#unpack or Regexp tricks (Spinel quirks). Malformed escapes (% at EOF, %ZZ) pass through literally rather than raising. `s = “”` default pins `s` to String — without it, Spinel’s analyzer can’t tell whether ‘s.length` / `s` mean String or bitfield-on-int and lowers s to `(s >> i) & 1` (genuinely surprising).
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 |
# File 'lib/fresco/runtime/runtime.rb', line 1058 def url_decode(s = "") out = "" i = 0 n = s.length while i < n c = s[i] if c == "+" out += " " i += 1 elsif c == "%" && i + 2 < n hi = hex_nibble(s[i + 1]) lo = hex_nibble(s[i + 2]) if hi >= 0 && lo >= 0 out += (hi * 16 + lo).chr i += 3 else out += c i += 1 end else out += c i += 1 end end out end |
#url_encode(s = "") ⇒ Object
RFC 3986 percent-encode. ALPHA / DIGIT / ‘-._~` pass through; every other byte becomes `%XX` (uppercase hex). Used by Response#set_cookie to make values safe for the Set-Cookie line and by Session to encode the signed payload. `s = “”` pins the String type for Spinel’s analyzer (same default-hint discipline as url_decode).
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 |
# File 'lib/fresco/runtime/runtime.rb', line 1127 def url_encode(s = "") out = "" i = 0 n = s.length while i < n c = s[i] if (c >= "a" && c <= "z") || (c >= "A" && c <= "Z") || (c >= "0" && c <= "9") || c == "-" || c == "." || c == "_" || c == "~" out += c else b = c.bytes[0] out += "%" out += hex_char_upper(b / 16) out += hex_char_upper(b % 16) end i += 1 end out end |
#worker_loop(sfd) ⇒ Object
1739 1740 1741 1742 1743 1744 1745 |
# File 'lib/fresco/runtime/runtime.rb', line 1739 def worker_loop(sfd) loop do cfd = Sock.sphttp_accept(sfd) next if cfd < 0 handle_connection(cfd) end end |
#write_dev_response(sock, res) ⇒ Object
Write an HTTP/1.1 response. Body responses go out as one write; file responses (file_path set on the Response) are loaded from disk and written inline — production uses sendfile(2), but dev is correctness-over-throughput.
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 |
# File 'lib/fresco/cli/dev_loop.rb', line 574 def write_dev_response(sock, res) if res.file_path.length > 0 if File.exist?(res.file_path) status = res.status ctype = res.content_type body = File.binread(res.file_path) else status = 404 ctype = "text/plain; charset=utf-8" body = "Not Found" end else status = res.status ctype = res.content_type body = res.body end reason = reason_for(status) sock.write("HTTP/1.1 #{status} #{reason}\r\n") sock.write("Content-Type: #{ctype}\r\n") sock.write("Content-Length: #{body.bytesize}\r\n") sock.write("Location: #{res.location}\r\n") if res.location.length > 0 res..each { |line| sock.write("Set-Cookie: #{line}\r\n") } sock.write("Connection: close\r\n\r\n") sock.write(body) end |
#write_response(client, res, keep_alive) ⇒ Object
Build a wire-format HTTP/1.1 response. For body responses the headers + body go out in one write. For file responses (file_path set on the Response) we stat the file for size, send the headers, then ‘sphttp_sendfile(2)` the bytes — skipping the copy through a Ruby string entirely.
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 |
# File 'lib/fresco/runtime/runtime.rb', line 1460 def write_response(client, res, keep_alive) if keep_alive conn = "keep-alive" else conn = "close" end if res.file_path.length > 0 size = Sock.sphttp_file_size(res.file_path) if size < 0 # File vanished between dispatch and write. Honor the contract # with a 404 rather than partial output. Force the socket shut. body = "Not Found" hdr = build_headers(404, "text/plain; charset=utf-8", body.length, "close", res., "") Sock.sphttp_write_str(client, hdr + body) return end Sock.sphttp_write_str(client, build_headers(res.status, res.content_type, size, conn, res., res.location)) Sock.sphttp_sendfile(client, res.file_path) return end body = res.body bytes = body.length Sock.sphttp_write_str(client, build_headers(res.status, res.content_type, bytes, conn, res., res.location) + body) end |