Skip to content

Latest commit

 

History

History
194 lines (165 loc) · 12.3 KB

HTTP_API.md

File metadata and controls

194 lines (165 loc) · 12.3 KB

Local calculator HTTP API

Local HTTP API

For exact linear/quadratic equations, use the separate stateless polynomial equation endpoint. Its three coefficient expressions do not read or change calculator sessions. The matrix endpoint provides separate exact matrix operations without reading calculator variables or sessions.

Evaluation accepts the shared calculator expression grammar, including exact fractions and automatic complex-domain promotion. Mathematical branches, singularities and precision belong to that reference and the BigComplex contract; this page defines HTTP transport and output. For example, sqrt(-1) returns exact i through the same endpoint as 2+2.

An optional final output option &form=cartesian|trig|exp follows precision, angle and notation, and precedes client/revision/action suffixes. Omission selects Cartesian. Example: POST /api/evaluate?precision=10&angle=rad&notation=auto&form=exp with body complex(-1;0) displays e^(i*(π)). Real values ignore the selected form. Polar angles are radians even when angle=deg applies to real function calls.

Session/cached complex responses provide copy as a lossless Cartesian constructor complex(re;im), or null when it cannot fit the input limit. This copy is independent of display rounding/form and is not a typed snapshot of approximation provenance. Stateless responses still provide display text; use typed session snapshots for authoritative components and their kind.

The browser guide describes layout, previews and error highlighting. HTTP column is a one-based Unicode character position; it identifies where evaluation detected an error. Resource/connection failures have no expression position.

numforge_web serves the calculator. Its evaluation endpoint is:

POST /api/evaluate?precision=10&angle=rad HTTP/1.1
Host: 127.0.0.1:8765
Content-Type: text/plain; charset=utf-8
Content-Length: 6

π / 2

A successful response is HTTP 200:

{"ok":true,"result":"1.5707963268"}

A short exact fraction can additionally return {"ok":true,"result":"1/3","approx":"0.3333333333"}. The approx field is only a display hint; result remains the exact value.

Invalid expressions, unsupported precision values, and arithmetic errors return HTTP 400. Calculator errors use this JSON shape:

{"ok":false,"error":"division by zero at column 3","status":"division by zero","column":3}

Content-Length is required for POST requests; omitting it returns HTTP 411. Browser requests that include Origin must come from this server's own http://127.0.0.1:8765 or http://localhost:8765 origin; other origins return HTTP 403. --origin https://host explicitly allows one additional origin for an HTTPS tunnel/reverse proxy; see hosting. Native clients may omit Origin. precision is optional: it accepts a non-negative whole number or full; if omitted, it defaults to 10. angle accepts rad or deg and defaults to rad; when supplied it follows precision in the query string. Optional notation=auto|plain|scientific|math|fraction follows angle and defaults to auto. A successful mathematical response adds "copy":"1.23E+45" (or "copy":null if the result cannot fit the parser's input range or size limit). Fraction results may add approx in any notation that displays the exact fraction; other responses retain the existing fields. Legacy clients may append &client=<32 lowercase hex digits>&revision=<N> after the normal options. N is a positive increasing integer up to 9007199254740991. These parameters opt into a bounded per-client cache; successful responses then also contain "cached":true or false. When a retained typed value is available, approximate is a boolean copied from its C numeric kind (decimal/complex-decimal versus exact rational). It describes calculation provenance, not display rounding or an error bound; it is omitted when the route has no retained typed value. Without them, the endpoint remains stateless and its response shape is unchanged. The browser generates a fresh random client ID for each page load, not a cookie or shared local-storage identity. The legacy cache holds at most 64 clients with one successful numeric value each; FIFO eviction frees the old value. Older or duplicate revisions may compute a response but cannot replace the stored value. Errors preserve the last successful value. This is not authentication or a public multiuser service.

The browser adds a final &action=start|preview|commit|delete-variable after client/revision. Browser previews wait for two seconds without input or settings changes; Enter or Calculate/Convert bypasses that wait and cancels the pending preview. This scheduling is client-side only: API requests are evaluated immediately. For example, start a page session with a POST to /api/evaluate?precision=10&angle=rad&client=<32 lowercase hex digits>&revision=1&action=start and an empty body. Start returns {"ok":true,"result":""} and is idempotent for an existing ID. Then send expressions with action preview or commit and increasing revisions. Start does not consume an evaluation revision.

delete-variable accepts a case-sensitive variable name as the plain-text body, reclaims its slot and preserves ans/history/RNG. It requires an existing session and a fresh revision; the same successful name/revision can be retried before another request. See Variables for deletion and UI semantics.

Preview does not change ans or history. Commit confirms a successful internal value and adds history atomically; failed calculations preserve both. ans is initially undefined and always refers to the stored value, not its display. Increasing precision does not recompute its original expression. An exact stored ans, such as 1/3, can be displayed at a higher precision; a previously approximated ans retains its original digits. Repeating the latest successful commit with the same revision, expression and settings returns the original result; conflicting or older revisions return stale session request. An unresolved confirmation must be retried with its original ID before sending another confirmation. A new intentional Enter/= uses a new revision.

For expressions containing rand, a preview keeps the same draws across automatic repeat requests and precision changes. A successful commit adopts those draws and advances the session generator once per occurrence. A new intentional commit makes fresh draws. Failed requests and replay of the same successful commit do not advance it. Each session has its own generator state; resetting starts a new sequence; reloading retains the session. One-shot and legacy HTTP requests draw afresh and do not cache random expressions.

The session pool is separate from the legacy cache: 64 sessions with 16 confirmed entries each. Retention policy bounds idle lifetime and the combined storage of values, variables, previews and histories. Each entry stores input, internal value, context and display. Evaluation of an unknown/evicted session returns session expired; reload the page and never starts another session implicitly. Reload, language and guide navigation reuse the tab ID and read its current revision from the server. New session explicitly resets existing state through the session API. Server restart loses all sessions. IDs are not authentication. History buttons restore only input, so expressions with ans use the current answer when evaluated again. CLI history lists its session entries; reset clears them and ans, retaining precision, angle and notation settings.

Output precision and notation are configurable in the UI; working precision remains automatic. Changing notation only reformats the retained numeric value. Matching input and working context allow reformatting without another evaluation. Exact typed integer and rational results, including divisions and proven roots, can also be reformatted when working precision changes. Approximate constants, irrational roots and transcendental calls require recalculation when working precision changes. Changing RAD/DEG also invalidates reuse. full keeps the existing 34-digit working policy, not infinite precision. More requested digits do not certify accuracy under cancellation; no rounded/inexact guarantee is inferred from the output.

Out-of-memory calculation failures return HTTP 500 with the same JSON fields. Malformed HTTP requests return JSON HTTP 400. Oversized bodies return JSON HTTP 413; a request that does not finish arriving within two seconds returns JSON HTTP 408. The receive deadline starts at acceptance, includes queue time and is not restarted by each byte. Responses also have a bounded send deadline. Connection overload uses best-effort HTTP 503 with code:server_busy, then closes; see worker/queue limits. Retained-memory rejection returns HTTP 400 with code:session_memory_limit and status:session memory limit exceeded; it preserves stored state and revisions. Unknown routes return plain-text HTTP 404; the UI tolerates non-JSON/network failures and ignores responses superseded by a new calculation or input edit. The UI distinguishes connection failures from unexpected server responses and offers retry with Enter. Calculation errors retain their status and source position, with argument rules for recognized function-domain/arity errors. These hints do not change the HTTP error schema or numerical API. Transfer-Encoding is unsupported and rejected; use Content-Length framing.

The local server accepts expressions up to 4096 bytes and listens only on loopback, using port 8765 by default. numforge_web --port N selects another port from 1 through 65535, and --no-browser suppresses automatic browser launching on Windows. The NUMFORGE_WEB_NO_BROWSER=1 environment setting also suppresses launching for headless runs. Browser origins must match the selected loopback port or the exact additional origin configured with --origin. Socket binding remains loopback-only. Forwarding headers do not grant origin access. Error columns are one-based Unicode character positions; the calculator internals retain zero-based UTF-8 byte offsets so source tokens remain lossless. The example body above is exactly six UTF-8 bytes and has no trailing newline.

See Web/API coverage for available calls and remaining gaps, and Unit HTTP API for catalogue and conversion routes. The session HTTP API adds read-only typed variables/history, explicit lifecycle actions, a function registry and confirmed conversion history. Its reads do not consume evaluation revisions or alter calculator previews.

The graph sampling HTTP API adds read-only POST /api/graph/sample with exact internal coordinates, bounded plotting projections and per-point classification. The complete request shares one budget.

Processing duration

Successful evaluation and conversion responses may include elapsed_ms for processing longer than 500 ms. This covers parsing, computation, number conversion and normalization, formatting, state operations and response preparation. Network transfer, the worker request queue, preview delay and browser rendering are excluded. Calculator session acquisition is included; unit conversion timing starts after session acquisition. Cached calculator results and stored history omit timing.

Optional timings_us contains exclusive monotonic phase durations in integer microseconds: parse, evaluate, convert, normalize, round, compose, format, serialize, other, and send (zero before transmission). Nested phases are subtracted from their parents; other includes unclassified state and adapter work. Totals can differ from elapsed_ms slightly because of clock resolution and sampling. Metadata assembly itself is excluded. Metadata is best effort and cannot fail a valid calculation.

The web labels this Processing time. Hover, focus or tap to inspect phases. Auto presents scalar E notation with superscripts and groups integer digits outside exponents; Scientific retains E notation. Copy preserves the original parser-compatible value. These display changes do not affect API result strings or calculation precision.