Add server mode with live reload (rdoc --server)#1620
Conversation
|
🚀 Preview deployment available at: https://c473c39c.rdoc-6cd.pages.dev (commit: 9511fd0) |
5ab5492 to
a3bd278
Compare
| # server.mount '/rdoc', RDoc::RI::Servlet, '/rdoc' | ||
|
|
||
| class RDoc::Servlet < WEBrick::HTTPServlet::AbstractServlet | ||
| class RDoc::RI::Servlet < WEBrick::HTTPServlet::AbstractServlet |
There was a problem hiding this comment.
I don't have a strong opinion whether we re-implement our HTTP server or we use WEBrick but do we want to keep depending on WEBrick?
There was a problem hiding this comment.
I think we can let it go and potentially merge the server implementation between RDoc and RI. But it'll be outside of the scope of the PR.
lib/rdoc/code_object/class_module.rb
Outdated
| @name = name | ||
| @superclass = superclass | ||
| @comment_location = [] # Array of [comment, location] pairs | ||
| @comment_location = {} # Hash of { location => comment } |
There was a problem hiding this comment.
Same location comment will be removed with this change.
Example input:
# comment1
class A; end
# comment2
class A; endOutput:
<section class="description">
<p>comment1</p> <!-- this line disappears -->
<p>comment2</p>
</section>I don't think these kind of reopening with comment is normally used, but the original deduplicating logic is clearly only for C code.
if location.parser == RDoc::Parser::C
@comment_location.delete_if { |(_, l)| l == location }
endSince reopening class with a comment is both included in the document in some case(different file), I think it's natural to accept the same thing written in a single file too.
9fc00ce to
06dee4a
Compare
| # Clear or remove comment entries from this file | ||
| if cm.is_a?(RDoc::ClassModule) | ||
| if keep_position | ||
| cm.comment_location[top_level] = [] if cm.comment_location.key?(top_level) |
There was a problem hiding this comment.
A very edge case, comment_location[top_level] will be kept empty if reparsed file doesn't contain that ClassModule anymore, or a comment to the ClassModule is erased.
After this has happened, even every contribution files are removed, if cm.in_files.empty? won't be true.
I think one possible solution for this is:
def reparse_and_refresh(...)
unless removed_files.empty?
...
# Don't need to perform `@modules_hash.delete(cm.full_name)` logic
end
unless changed_files.empty?
...
end
if removed_files.any? || changed_files.any?
# Check all classes/modules for empty comment_location entries
# and perform `@modules_hash.delete(cm.full_name)` logic
end
...
endConvert `ClassModule#comment_location` from an Array of `[comment,
location]` pairs to a Hash of `{ location => [comments] }`.
## Motivation
When a class like `RDoc` is documented across multiple files
(`lib/rdoc.rb`, `lib/rdoc/rubygems_hook.rb`, etc.), each file
contributes a comment. With the old Array of `[comment, location]`
pairs, there was no efficient way to look up or replace comments by
file. This matters for server live-reload (#1620): when a user edits
`lib/rdoc.rb`, we need to clear that file's comment and re-parse — but
preserve comments from other files **in their original order**. The
Array structure made this fragile because removing and re-appending an
entry moved it to the end, changing the order comments appeared on the
rendered page.
The Hash structure solves this: `{ location => [comments] }` allows O(1)
lookup by file, and Ruby hashes preserve insertion order — replacing a
key's value keeps it in position.
A secondary benefit: a class reopened in the same file now preserves all
its comments:
```ruby
# comment1
class A; end
# comment2
class A; end
```
With the old Array, the C parser had a special-case `delete_if` to
deduplicate same-location entries, while Ruby parsers accumulated
duplicates inconsistently. With the new Hash, each location maps to an
array of comments — both comments are preserved and rendered, matching
the cross-file behavior.
## Changes
- `add_comment`: appends to array per location —
`(@comment_location[location] ||= []) << comment`
- `parse`: uses `flat_map` to flatten per-location comment arrays into
Document parts
- `marshal_load` / `merge`: use `group_by(&:file)` to reconstruct arrays
from Documents
- `documented?`, `search_snippet`, `from_module`: updated for new value
shape
- `i18n/text.rb`: handles Hash with array values
- C parser `delete_if` special case removed (hash key naturally
deduplicates by location)
Adds a built-in HTTP server for previewing documentation while editing source files. Parses all sources on startup, watches for file changes, re-parses only changed files, and auto-refreshes the browser. Server implementation (lib/rdoc/server.rb): - Uses Ruby's built-in TCPServer (no WEBrick or external dependencies) - Persistent Aliki generator instance rendering to strings - Thread-per-connection with Connection: close (no keep-alive) - Background watcher thread polls file mtimes every 1 second - Live reload via inline JS polling /__status endpoint - New --server[=PORT] option (default 4000) and rdoc:server Rake task - Moved RDoc::Servlet to RDoc::RI::Servlet (server mode uses new class) Security: - Binds to 127.0.0.1 only (localhost) - Path traversal protection in asset serving via expand_path containment - Proper HTTP error responses (400, 404, 405, 500) - 5-second read timeout on client sockets Concurrency: - Mutex protects all store mutations, generator refresh, and cache invalidation as a single atomic operation - Thread-safe last_change_time reads for the status endpoint Correctness: - Clears file contributions (methods, constants, comments, etc.) before re-parsing to prevent duplication, without removing shared namespaces - Individual parse_file errors caught so one failure doesn't block others - Store#remove_file recursively cleans nested classes/modules and C vars - Watcher thread uses @running flag with clean shutdown via join
Co-authored-by: Sutou Kouhei <kou@clear-code.com>
- Embed last_change_time into the live-reload script at render time so the browser's initial timestamp matches the page content. This fixes a race where a change between page generation and the first poll would be silently skipped. - Call clear_file_contributions for removed files (not just changed files) and remove classes/modules from the store when no files contribute to them anymore. This correctly handles reopened classes across multiple files and improves file deletion behavior.
Move `relative_path_for` from a private method on RDoc::Server to a public method on RDoc::RDoc, eliminating the duplication with the inline logic in `parse_file`. Move `clear_file_contributions` from RDoc::Server to RDoc::Store where it naturally belongs — it operates entirely on store internals (files_hash, classes_hash, modules_hash). Add tests for Store#clear_file_contributions covering single-file removal, multi-file preservation, per-file cleanup of methods/ constants/includes, and no-op for nonexistent files.
- Use exit instead of return in document method for consistency - Replace path.sub regex with delete_prefix in server.rb - Use to_json for safe JavaScript value embedding
Also update clear_file_contributions for the Hash-based comment_location: - Add keep_position: keyword for server re-parse (preserves key position) - Add rebuild_comment_from_location method - Server passes keep_position: true when re-parsing changed files
06dee4a to
9511fd0
Compare
A better attempt of #1151
Depends on: #1634
Implement
rdoc --server[=PORT]for previewing documentation with automatic browser refresh on source file changes. The server parses all sources on startup, serves pages from memory via the Aliki generator, and watches for file modifications, additions, and deletions — re-parsing only what changed.rdoc-server-demo.mp4
Changes
RDoc::Server(lib/rdoc/server.rb) — minimal HTTP server using Ruby's built-inTCPServer(no WEBrick or external dependencies)Connection: close/__statusendpoint every 1 second--server[=PORT]CLI option (default port 4000) andrdoc:serverRake taskRDoc::Store#remove_file— removes a file's entries from the store hashesRDoc::Store#clear_file_contributions— surgically removes a file's methods, constants, comments, includes, extends, and aliases from its classes/modules, preserving classes that span multiple files. Supportskeep_position:for server re-parse to preserve comment ordering.RDoc::RDoc#relative_path_for— extracted path normalization (againstoptions.rootandoptions.page_dir) shared byparse_fileand the serverDarkfish#refresh_store_data— extracted for reuse by the server after re-parsingRDoc::Servlet→RDoc::RI::Servlet— moved to clarify RI-specific usageSecurity & robustness
127.0.0.1only (localhost)File.expand_pathcontainment check)IO.selectread timeout on client socketsparse_fileerrors rescued so one failure doesn't block remaining files@runningflag with clean shutdown viaThread#joinKnown limitations