Skip to content

feat(serve): add REST API server command#232

Merged
fahimfaisaal merged 9 commits into
goptics:mainfrom
hfl0506:feat/add-serve-rest-api
Jul 19, 2026
Merged

feat(serve): add REST API server command#232
fahimfaisaal merged 9 commits into
goptics:mainfrom
hfl0506:feat/add-serve-rest-api

Conversation

@hfl0506

@hfl0506 hfl0506 commented Jul 17, 2026

Copy link
Copy Markdown
Collaborator

Related issues

Resolve #213

Changes

  • Added vizb serve with --host/--port defaults, limits, timeouts, listener
    errors, and bounded SIGINT/SIGTERM shutdown in cmd/serve.go.

  • Registered testable POST route composition for /, /merge, and /ui.

  • Added lifecycle/configuration/limit tests in cmd/serve_test.go.

  • Documented limits and lifecycle defaults in docs/src/content/docs/commands/

  • Included the local extract a server-safe Vizb core #212 server-safe core prerequisite commits.

Test Steps

go test ./...
task test:cli
task format:check:cli
go vet ./...

Summary by CodeRabbit

  • New Features

    • Added the vizb serve command for local HTTP conversion (/), merging (/merge), and HTML UI generation (/ui).
    • Added configurable server host/port, timeouts, and a 10 MiB request body limit with strict JSON validation.
    • Added standardized application/problem+json error responses and improved Accept negotiation behavior.
    • Enforced dataset settings so each chart type can appear at most once; added support for integer-typed CLI/chart flags.
  • Documentation

    • Updated serve and API docs with request limits, lifecycle/shutdown behavior, and refined error/status meanings.
  • Tests

    • Added comprehensive server and endpoint tests, plus OpenAPI contract and integer-flag validation tests.

@codecov-commenter

codecov-commenter commented Jul 17, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@hfl0506
hfl0506 force-pushed the feat/add-serve-rest-api branch from 98aadb8 to 2a4b1a8 Compare July 17, 2026 05:40
@hfl0506
hfl0506 marked this pull request as ready for review July 17, 2026 05:45
@hfl0506
hfl0506 requested a review from fahimfaisaal July 17, 2026 07:00
@hfl0506 hfl0506 added enhancement New feature or request cli Command line interface related tasks labels Jul 17, 2026
@hfl0506
hfl0506 force-pushed the feat/add-serve-rest-api branch from 2a4b1a8 to 145bbbe Compare July 18, 2026 02:39
@fahimfaisaal

fahimfaisaal commented Jul 18, 2026

Copy link
Copy Markdown
Member

Hi @hfl0506 we have conflicts here, Could you resolve it with the latest branch

@fahimfaisaal fahimfaisaal added this to the Release v0.16.0 milestone Jul 18, 2026
@hfl0506
hfl0506 force-pushed the feat/add-serve-rest-api branch from 145bbbe to a44e748 Compare July 18, 2026 16:00
@coderabbitai

coderabbitai Bot commented Jul 18, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@hfl0506, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 24 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9853219e-f13d-426f-9851-b4991d1e1c1d

📥 Commits

Reviewing files that changed from the base of the PR and between 6c89e78 and 11ef600.

📒 Files selected for processing (2)
  • cmd/serve_contract.go
  • cmd/serve_test.go
📝 Walkthrough

Walkthrough

Adds the vizb serve Cobra command with configurable HTTP hosting, strict request contracts, conversion/merge/UI endpoints, structured errors, graceful shutdown, API schema updates, integer chart flags, and comprehensive tests.

Changes

Serve REST API

Layer / File(s) Summary
Server lifecycle and routing
cmd/serve.go, cmd/serve_test.go, cmd/testing.go
Adds server configuration, route registration, request limits, timeouts, address validation, graceful shutdown, lifecycle error handling, and test-state resets.
Request contracts and validation
cmd/serve_contract.go, cmd/serve_test.go
Adds strict request and dataset decoding, conversion options, chart/statistics validation, structured validation errors, and UI option materialization.
REST handlers and responses
cmd/serve.go, cmd/serve_test.go
Adds conversion, merge, and UI handlers with content negotiation, JSON input handling, and application/problem+json responses.
OpenAPI contracts and documentation
api/openapi.yaml, api/openapi_test.go, api/README.md, docs/src/content/docs/commands/serve.mdx
Updates problem-response references, dataset chart-setting uniqueness, schema validation, operational documentation, and API status mappings.
Integer chart flag support
internal/flags/flag.go, cmd/cli/flagbag.go, shared/chart_spec.go, cmd/cli/flagbag_test.go, shared/chart_selection_test.go
Adds integer flag binding, access, validation, chart seeding, reset behavior, and tests.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant HTTPServer
  participant RESTHandler
  participant Core
  participant UIGenerator
  CLI->>HTTPServer: start serve command
  HTTPServer->>RESTHandler: receive POST request
  RESTHandler->>Core: convert or merge request data
  Core-->>RESTHandler: return datasets
  RESTHandler->>UIGenerator: generate HTML for UI output
  RESTHandler-->>HTTPServer: write JSON, HTML, or problem response
Loading

Possibly related issues

Possibly related PRs

  • goptics/vizb#239 — Modifies the same OpenAPI conversion contract, including dataset chart-setting uniqueness and problem-response references.
  • goptics/vizb#240 — Overlaps directly on the Dataset.settings contains/maxContains validation constraint.

Suggested labels: api

Suggested reviewers: fahimfaisaal

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely matches the main change: adding a serve REST API command.
Linked Issues check ✅ Passed The changes add the serve command, routes, limits, graceful shutdown, and tests required by #213.
Out of Scope Changes check ✅ Passed The additional OpenAPI, docs, and integer-flag support changes still align with the serve command and its request handling.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cmd/serve_contract.go`:
- Around line 570-577: Update the settings loop in the dataset validation flow
to track each decoded ChartType and reject duplicate types before applyUIOptions
can index them by type. Return a validation error identifying the duplicate
setting while preserving normal handling for unique settings. Add or update a
dataset-validation test covering two settings with the same type and asserting
rejection.
- Around line 461-476: Update the chart configuration construction around
targetTypes and the existing/overrides lookups so every explicitly selected
valid chart type produces a configuration even when the dataset has neither a
base setting nor an override; materialize that chart type’s defaults instead of
silently continuing. Preserve skipping unknown chart types, and add a test
covering a valid charts.types selection absent from the input dataset.

In `@cmd/serve.go`:
- Around line 218-222: Update the error handling in the generateUI path and the
corresponding alternate path in the serving handler to stop returning
err.Error() through writeAPIProblem. Log the underlying generation errors
server-side, then return a generic internal-server-error detail to clients while
preserving the existing HTTP status and response flow.
- Around line 105-106: Replace the direct Cobra bindings for Host and Port in
the serve command with bindings through cli.FlagBag, using the existing FlagBag
setup and lifecycle conventions. Preserve the current flag names, shorthand,
defaults, descriptions, and option targets while removing the direct StringVar
and IntVarP calls.
- Around line 231-258: Update handleMerge to negotiate the request’s Accept
header before writing the JSON response, returning HTTP 406 when
application/json is explicitly rejected while preserving the existing successful
JSON response otherwise. Add or update the merge endpoint test to send Accept:
text/html and assert a 406 response.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 10bd4102-35d1-4d7e-b167-8bb7819e71a6

📥 Commits

Reviewing files that changed from the base of the PR and between 914ada1 and a44e748.

📒 Files selected for processing (6)
  • api/openapi.yaml
  • cmd/serve.go
  • cmd/serve_contract.go
  • cmd/serve_test.go
  • cmd/testing.go
  • docs/src/content/docs/commands/serve.mdx

Comment thread cmd/serve_contract.go Outdated
Comment thread cmd/serve_contract.go
Comment thread cmd/serve.go Outdated
Comment thread cmd/serve.go
Comment thread cmd/serve.go
@hfl0506

hfl0506 commented Jul 18, 2026

Copy link
Copy Markdown
Collaborator Author

Hi @hfl0506 we have conflicts here, Could you resolve it with the latest branch

Hi @fahimfaisaal resolved and kindly take a look when you have a chance. Thanks

@fahimfaisaal fahimfaisaal left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oversized requests are currently handled as 400 Bad Request because *http.MaxBytesError flows into writeValidationProblem. Please detect this error and return a 413 Content Too Large Problem Details response. Update the limit test to assert the status, content type, response body, and that no application operation runs. Also add 413 to the OpenAPI responses and error documentation.

@fahimfaisaal fahimfaisaal left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unknown paths and wrong HTTP methods currently use http.ServeMux’s plain-text 404/405 responses. Please return application/problem+json for both cases, preserve Allow: POST on 405 responses, and update the routing tests to verify status, content type, Problem Details body, and the Allow header.

@fahimfaisaal fahimfaisaal left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Semantic validation errors currently always return 400 Bad Request, while the local REST specification requires 400 only for malformed JSON and 422 Unprocessable Content for valid JSON that violates schema or semantic constraints. Please separate these error paths and update the implementation, OpenAPI contract, documentation, and tests to use consistent statuses.

@fahimfaisaal fahimfaisaal left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When graceful shutdown reaches its deadline or fails, the server returns an error without force-closing active connections. Please call Server.Close() after Server.Shutdown() fails or times out, preserve the relevant shutdown/close error, and add a test with an active request proving connections are force-closed after the deadline.

@fahimfaisaal

Copy link
Copy Markdown
Member

and finally, can we improve the coverage a bit? @hfl0506

@hfl0506

hfl0506 commented Jul 19, 2026

Copy link
Copy Markdown
Collaborator Author

Hi @fahimfaisaal I updated from what you mention, kindly have a look when you have a moment. Thanks

@fahimfaisaal fahimfaisaal left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the changes. we can improve it more in the near future. for now it LGTM

@fahimfaisaal
fahimfaisaal merged commit 07d6aea into goptics:main Jul 19, 2026
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli Command line interface related tasks enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

add the vizb serve command

3 participants