Repository navigation
feat(server): let other programs send akou audio files and get transcripts back - #45
Conversation
…container's In a container Bun is pid 1 on every start, so a lock left on the volume by an unclean stop named a pid that looked alive, the app refused to start and exited 0, and the restart policy saw a clean exit. The lock now records the holder's pid and an id made once at process start, and the holder touches it every 10 s. - A lock with this process's pid and id is refused (a second acquire). - A live pid that is not this process is refused, as before. - In app mode a dead pid is taken at once, as before. - Otherwise (this pid with another id, or in server mode a pid this namespace cannot see) the lock is taken once its mtime is 30 s old, so a second container on the same volume stays out while the first runs. The call log writer follows the same rule. Refs akou-5an.60 (SI-4).
Server mode (`server.enabled`, or AKOU_SERVER=1) is the same /v1 with a door for programs on the network. This lays the base the job routes build on. - Bind: the app stays on 127.0.0.1. Server mode binds `api.bind`, 0.0.0.0 by default, and refuses to start (exit 78, naming both keys) on an address that is not loopback unless `server.behind_proxy` says a proxy terminates TLS. - Host: `server.public_host` when set, any host behind a proxy, or loopback. Browser headers are allowed there; the web UI's door is the admin login. - Keys: `akou keys create|list|revoke` edit keys.json (0600, the key's SHA-256 and the whsec_ secret) with no app running; the server reads the file again when it changes, so a revoked key gets 401 on its next request. - Scopes: every route declares `open`, `jobs` or `admin`, a route that says nothing is admin, and the guard checks the caller once before any handler. A jobs key gets 403 on PATCH /v1/config; the app token keeps admin. - Callback hosts: `requireCallbackAllowed` answers 422 callback_not_allowed for a host off the key's list; `*` allows any. - Uploads: a route added with `upload: true` takes multipart up to `server.max_upload_mb` (512 MiB); every other route keeps 64 KB of JSON. - `server.trusted_proxies`: only those peers' X-Forwarded-For names the source address; a refused key is logged under that source. - Open routes: GET /healthz (503 while models download), GET /v1/server (mode, presets, engines, capabilities that turn true with their routes), and GET /v1/keys/me for any key. Refs akou-5an.2, akou-5an.3, akou-5an.8, akou-5an.9, akou-5an.15, akou-5an.16, akou-5an.17, akou-5an.18, akou-5an.59.
A page reachable over the network needs a door, and the one-time code that opens it on loopback is minted by a CLI on the same machine. In server mode the API's own listener now serves the page behind the proxy, and the page opens a session with the admin password or an admin key pasted once. - `akou admin set-password` reads the password from stdin (never argv) and stores an argon2id hash as `server.admin_password_hash`; the login reads it from the file, so it works without a restart. - A wrong password or key gets 401 after 2 s; a jobs key cannot log in. - The session lives in the tab's sessionStorage, never a cookie, so it dies with the tab and there is no CSRF; a request from another Origin is refused. - A save over the API keeps the file's own keys as they are on disk, so a PATCH /v1/config no longer drops a hash written since the start. Refs akou-5an.47 (SV-U1).
…ddresses A key holding only '*' could point callbacks at 127.0.0.1, 10/8, link-local and akou's own API. The owner's rule is that '*' matches public hosts only; loopback, RFC 1918, shared, link-local and unique-local literals and localhost must be listed on the key by name.
Mounted on the API listener, the page inherited Bun's upload-sized body limit, so an anonymous POST /session could make akou hold up to 512 MiB. The page now refuses a declared body over 64 KB before reading it, and reads every body through the same capped reader as the API.
…ner comes back After a crash or OOM kill the restarted container is pid 1 again and the lock it left is under 30 s old. The entry point called that 'already running (pid 1)', naming itself, and exited 0, so Docker's on-failure policy left the service down. It now exits 75 (EX_TEMPFAIL) and says when the lock frees.
… models models_ready meant only that the files were on disk, so while the recognizer was still loading them, or after it failed to, /healthz said healthy and Compose's service_healthy released clients before any job could run.
…uessing The delay applied to each request on its own, so parallel guesses were not slowed at all, and each ran an argon2id check with no credentials needed. Logins now queue across the process, and a wrong one holds the queue for its delay: one guess per 2 s, one password check at a time.
nginx sends Host: $proxy_host by default, so akou saw its own loopback address while the browser sent Origin: https://akou.example, and every page POST, the login included, got 403 cross_site. An Origin naming server.public_host is now accepted too, and the SI-6 recipe says the proxy must pass the original Host or set the public host.
Run in a terminal, akou admin set-password waited silently for end of input and echoed the password as it was typed. It now says to pipe the password in from a file, and reads nothing.
…r keyless request key.refused wrote the first 7 characters of any bearer, so a client sending another service's secret left part of it in akou's log, and every request with no key wrote a warn line, so a scanner could grow the log without bound.
…age's dead TLS check The CLI always dials 127.0.0.1, so a server bound to ::1, 127.0.0.2 or one LAN address started fine and then could not be reached from its own box. Server mode now binds 127.0.0.1, 0.0.0.0 or :: and refuses anything else at start. With that rule in apiBind the page's own plain-HTTP refusal could never fire, so it is gone.
An unknown path was checked as an admin route, so a valid jobs key asking for GET /v1/jbos was told the route needs admin. It is now checked as needing any key: no key is still 401 before any 404, and a valid key gets the 404 or 405.
At a tenth of the timings the acceptance's 40 s is 4 s, the threshold plus one heartbeat; the test allowed 5 s.
Rule 2 says every request needs the token, GETs included, but /healthz and GET /v1/server answer with none in app mode too; the server-mode note listed only server-mode changes.
create and revoke each read keys.json, changed it and wrote it back with no lock, so a create running beside a revoke could write the revoked key back. Both now run under keys.json.lock and refuse while another edit holds it. revoke also matched by name, so a key named like another key's id took that key down with it; it matches the id only, as its usage says.
declare wrote 2 MiB of every large body. Past the drain cap the server closed on unread bytes, and past Bun's own limit Bun refused at the headers and closed at once, so the client's write hit EPIPE or ECONNRESET before the 413 arrived: 2 of 6 runs failed on the lane's first head. It now sends one byte past the drain cap, which the server reads whole, and nothing when the length is past Bun's limit. 12 of 12 runs pass.
…word changes A session opened with an admin key stayed valid after the key was revoked, and a new admin password left every session opened with the old one alive until a restart. Each admin session now carries a check of the credential that opened it, run on every use.
… says you A file job has one channel and no local speaker, so the finalize worker gains runJobPass and a long-lived JobWorker: the call pass's VAD cuts, whole-timeline rule and span halving over one channel, speaker labels only with diarize, and the audio before the first and after the last speech trimmed so an engine never decodes room noise on its own (SV-J7, SV-R5). Cancel terminates the Worker (SV-J6).
…ebhook outbox One SQLite file holds jobs, the per-key event feed and the webhook outbox, each state change one transaction (SV-J9). Deliveries follow Standard Webhooks: one id per event across retries, a timestamped HMAC over id, time and body, one v1 entry per secret (SV-E2), the result inline up to 256 KB (SV-E3), the design's retry schedule with jitter, 410 disabling the endpoint and no redirects (SV-E4), each try on disk before it is made (SV-E5). Callbacks go over http or https only; link-local and metadata addresses are refused at submit and after DNS at delivery, plain http reaches private addresses only, and the request dials the address that passed the check while https still verifies the host name (SV-E7). A key that reaches a host only through its * entry delivers to public addresses only (SV-K4). The test fixture is the Standard Webhooks reference verifier, MIT, with its hashing on node:crypto so the suite takes no dependency.
… and delete
POST /v1/jobs takes a multipart upload with a preset, language,
keywords, diarize, a callback URL and metadata echoed back (SV-J1).
An Idempotency-Key compares the key and the file's SHA-256 only: the
same file answers 200 with the existing job in any state, another file
422 idempotency_conflict (SV-J2). Jobs run one at a time through the
mono final pass; GET /v1/jobs/{id}?wait holds until the job ends and
GET /v1/jobs lists the key's own (SV-J3); the result has the one shape
of SV-J4. DELETE drops a queued job, terminates a running one's Worker
and removes a finished one's result, leaving the feed the id and final
state; server.retain_days does the same hourly (SV-J6). GET /v1/events
reads the key's outcomes after a cursor, long-polled or as SSE with
Last-Event-ID (SV-E1). A job the last process left running is queued
again at start, in its place (SV-J9).
The routes exist in server mode only. A callback URL goes through the
keys lane's allowlist (callback_not_allowed, the name Telegram-Archive
uses) and the address rules, and needs a key with a webhook secret.
Uploads that are 16 kHz PCM WAVs are read directly; anything else goes
through ffmpeg (decode.ts, identical to the server-image lane's).
…its pinned OpenAPI file POST /v1/audio/transcriptions is a synchronous door onto a file job, so Nextcloud, Home Assistant, whisper-subs and the openai libraries work with no code of their own (SV-C1). model names a preset or an engine and anything else is auto; prompt and keywords[] become hotwords; json, text, srt, vtt, verbose_json and diarized_json are answered, and stream=true sends transcript.text.delta or .segment events, then .done. The job is deleted once the answer is sent. The conformance test (SV-T3) reads the transcription operation from a pinned copy of openai/openai-openapi (MIT, commit 412c7b98), needs a sample for every request field it lists, and checks every answer against the operation's schemas with unknown properties refused, so renaming a field of akou's answer fails it. The schema check is a small test fixture, not a new dependency.
…erver runs Transcribing a file becomes a product feature (SV-D1): REQUIREMENTS F1.8 now reads carried, as a job, and open decision 2 is closed with a pointer to SERVER.md. akou transcribe FILE asks GET /v1/server whether the akou it reaches runs jobs, uploads the file to POST /v1/jobs, waits and prints the text; the desktop app exits 69 naming server.enabled. The CLI's client gains a multipart body for it. SERVER.md's Today column now says where each item of this lane stands, including what is still open: the multipart body is parsed in memory before it reaches disk, and words and confidences are empty until an engine gives them.
…write nothing once closed The outbox marked a delivery failed before its last try was made, so a reader saw failed while the receiver was still being asked, and a process killed during that try never made it. The last try is now pending with a resume point one timeout later, and failed only on its answer. A deliverer closed while a try is out no longer writes the answer into a store the next process owns, which the full suite showed as a closed-database error. The job and OpenAI suites run several real jobs per case, so they get a 30 s case timeout in place of the default 5 s.
… size A streaming writer (ffmpeg or sox to a pipe, arecord) cannot seek back to fill in the data chunk's size, so it leaves 0xFFFFFFFF or 0. The job then failed with an out-of-memory error, or came back done with empty text. The size is now capped at what the file holds, and 0 means read to the end.
…eviving a deleted job's delivery A try that outlasted the next delay left its row due while it was out, so the timer re-armed at zero until the try ended: a silent receiver meant about 25 s of SQLite polling on the API's thread. The timer now leaves in-flight deliveries out, and the next delay runs from the failed answer, as SV-E4 describes, not from the try's start. A job deleted during a try had its delivery marked failed, and the try's answer then wrote pending or delivered over it, so the receiver got the scrubbed event again. Every outcome write now lands only on a delivery still pending.
…hat keeps killing the server No length cap existed, and a decode held the audio three times: ffmpeg's chunks, a concatenated copy, and a float copy, then cloned it into the Worker. A 3 h file peaked near 2 GB, and a 512 MB upload of quiet Opus decodes to tens of GB. The process died, and the job left running was queued again at every start, so any jobs key could put the server in a restart loop. server.max_audio_minutes (default 240) kills ffmpeg once its output passes the limit and fails the job as too_long; a 16 kHz WAV is checked from its header. The chunks are copied once into the float buffer and the buffer is transferred to the Worker, not cloned. Each start of a job is counted: a job running at a second stop fails as interrupted instead of running a third time.
…nd write its shape down A completed event carries its result inline up to 256 KB, so one page at limit=1000 could build about 256 MB of JSON, and a client could not tell a full page from the end. A page now stops past 1 MiB of event data (always one event at least), reads only the rows that fit, and carries has_more. The SSE feed reads until a page is empty, since a page may end early by size. SV-E1 now names the body Telegram-Archive codes against.
After a delete or retention, a transcription.completed event read
{job_id, status: "done"} with no text and no marker, which a client
reconciling from the feed would store as an empty transcript. The
scrubbed data now carries deleted: true.
A crash mid-upload, or between a job's end and its file's delete, left the audio in jobs/audio with nothing to read or delete it, against SV-J6's promise that akou holds a copy only as long as it needs one.
…t the length cap The endpoint mapped every job error but decode_failed to 500, so a file over server.max_audio_minutes read as a server fault. The test runs the real app with a one-minute cap and a 61 s upload.
… placeholder for silence akou transcribe left its job on the server for retain_days after printing it, while the OpenAI endpoint deletes its own at once, and Ctrl-C left the job queued or running. An empty result printed "(no speech)" to stdout, which a pipe would save as the transcript. The job is now deleted after the transcript is out and on Ctrl-C (exit 130), and silence prints nothing on stdout with a note on stderr.
# Conflicts: # tests/api-helpers.ts
|
Warning Review limit reachedNext included review available in 35 minutes. View limit detailsLimit details: You’ve used the included review currently available. You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Review configuration: ⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (38)
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. Comment |
|
@coderabbitai review |
|
Put the keys lane's routes into the OpenAPI route table: GET /v1/server (open) and GET /v1/keys/me (jobs) carry RouteDocs and are in openapi.json; /healthz stays outside /v1 and the file. The guard's upload rule reads the route's multipart body spec instead of a second flag, an unknown path stays UNKNOWN_ROUTE (any key, so 401 before 404), ApiApp.mode is the method the OpenAPI route calls, the keys and admin commands carry the flag descriptions and examples the CLI registry requires, and stdin is read through the one readStdin.
…er-jobs Put the job, event and OpenAI routes into the OpenAPI route table: each carries a RouteDoc (server mode, any key; the OpenAI door is compat), reads its query through the declared specs, and is in openapi.json, so Executor's round trip runs against the real jobs routes. buildRouter(mode) registers them in server mode only, and with no mode for the file. akou transcribe carries the flag descriptions and examples the CLI registry requires.
Brings in the keys (#43) and jobs (#45) lanes this branch's CI needs: /healthz, api.bind and server.behind_proxy. Conflicts: decode.ts takes main's version (#45's superset with maxSamples and too_long); cli.ts keeps both serve and the server commands; args.ts keeps the secret-flag refusal beside main's described COMMON flags; ci.yml keeps the server job beside diarize and executor, all under ci-ok; floors add both sides' skips; the docs keep this branch's SV-P3, SV-T1 and SI-1 rows and main's SV-P4, SV-P5, SV-T2, SV-T3 and SI-2 to SI-4 rows. To pass main's CLI rules: flag descriptions and examples for jobs, serve and models pull, serve listed as local-only, and parity rows for jobs and serve.
… loads (#429) ## Problem The server died with `panic: NAPI FATAL ERROR: Error::Error napi_define_properties` right after a 280 s Parakeet load (#408). The cause is in Bun, not in sherpa-onnx or akou: on Bun 1.3.13 through 1.4.4, calling `Worker.terminate()` while the Worker is inside a native constructor aborts the whole process (oven-sh/bun#45252, fix still open in oven-sh/bun#45615). A model load sits in such a constructor for a second, or for minutes on a starved disk. akou terminates Workers in four places: a job cancelled or hung up on (`DELETE /v1/jobs/:id`, or the OpenAI, Bazarr or Wyoming caller going away), a job Worker that errors, a final pass that runs out of budget or is aborted, and the live Worker's close. Any of them during a load took the server or the app down. In #408 the most likely trigger is the proxy in front hanging up during the long load (openai.ts hangUp, then jobs.remove, then JobWorker.cancel). ## Fix - New `src/main/asr/native-guard.ts`. The host creates a shared `Int32Array` per Worker and sends it in the first message (`job`, `run`, `init`), not in `workerData`, which stays the string entry marker. - `sherpa.ts` runs every native load through `nativeLoad`: the `sherpa-onnx-node` require and the five constructors (OfflineRecognizer, Vad, SpeakerEmbeddingExtractor, OnlineRecognizer, OfflineSpeakerDiarization). It counts the load on the flag. - Every terminate site goes through `stopWorker`: `finalizeCall`'s finish, `JobWorker`'s onerror and cancel/close, and the live Worker's close. Outside a load it terminates at once, as before. Inside a load it only sets a stop bit. The Worker sees the bit as the load returns, posts `native.parked` and waits in JS, and the host terminates it on that message. There is no timer poll, so the terminate never lands in the decode that follows a load. A stop asked just before a load starts skips the load (the count and the stop bit are written and read in opposite order on each side, so one side always sees the other). - `JobWorker.cancel` still drops the Worker, kills its children and rejects the caller at once. Only the terminate waits. - A load that never returns now leaves a Worker thread behind instead of aborting the process. The guard can come out once the pinned Bun carries oven-sh/bun#45615. The TRAPS row says so. ## Evidence All on a Mac mini, Apple silicon, macOS 26, Bun 1.4.2, sherpa-onnx-node 1.13.8, Parakeet TDT 0.6b v3 fp32. - `tests/native-guard.test.ts`, with a fake Worker: - `[bun#45252] ... outside every load the Worker is terminated at once` - `[bun#45252] ... inside a load it is not terminated until it parks after the load, then once` - `[bun#45252] ... positive control: a bare terminate in its place is caught terminating inside the load` - `[bun#45252] ... a stop asked before a load starts skips the load and parks` - `[bun#45252] ... a load that throws while a stop waits still parks, and the count goes back to zero` - `[bun#45252] ... a Worker that errors while a stop waits is terminated` - `[bun#45252] ... without a flag (in-thread, tests) a load just runs` - Model-gated: `[bun#45252] a job cancelled inside Parakeet's load > 300 ms into the load, the job rejects at once and the process outlives the load`. It runs `tests/fixtures/cancel-during-load.ts` in a child process. CI's `server-macos` job, which pulls the fast models, now runs it and fails if it skips. The check jobs have no models and skip it, so `maxSkip` goes up by 1 in `tests/floors.json` for check (darwin, linux, win32) and clock-shift. - With the guard, the fixture cancelled at 100, 300 and 700 ms into the load: the job rejected with `cancelled` and the process stayed alive, exit 0 each time. - Mutation: with `stopWorker` reduced to a bare `w.terminate()`, the fixture exits 134 with `panic: NAPI FATAL ERROR: Error::Error napi_define_properties`. The gated test and 4 of the unit tests fail. - Standalone repro, terminate 300 ms into `new OfflineRecognizer(...)`: 1.3.12 survives; 1.3.13 exits 133 (`napi_create_object`); 1.4.2 exits 134 (`napi_define_properties`); 1.4.4 exits 134 (`A C++ exception occurred`). Posted on oven-sh/bun#45252. - `bunx [email protected] run check`: 3353 pass, 37 skip, 0 fail; floor check:darwin 37 skipped (at most 39). ## Not covered - A terminate during the native calls after a load (`decode`, `createStream`) is unchanged. One measured terminate during a 2.4 s decode did not crash, but that is one run. - The issue's other two asks need no change. Nothing creates the recognizer twice: loads are synchronous in one Worker, and `loadRecognizer` drops the old one first. Jobs left running are queued again at start since #45 (`jobs.ts`, `MAX_JOB_STARTS` = 2). The client's own connection still dies if the process dies, and no server change can save it. Fixes #408
Depends on #43 (server keys). This branch is stacked on
feat/server-keysand must merge after it. Until #43 lands, the diff below also shows its commits.Problem
Server mode could take keys and uploads, but there was nothing to send a file to. Another program (Telegram-Archive transcribing voice notes, a script with a folder of recordings) had no way to hand akou a file, learn when it was done, or get the text back, and an OpenAI client pointed at akou got nothing.
akou transcribedid not exist either, so a file on disk could only be transcribed by recording it.Fix
POST /v1/jobstakes a multipart file plus preset, language, metadata and an optional callback. AnIdempotency-Keymakes a retried submit return the first job.GET /v1/jobs/{id}?wait=60long-polls until done.GET /v1/jobs/{id}/resultreturns the transcript.DELETEdrops a queued job, stops a running one within two seconds, and removes its file.AKOU_HOMEwith exactly three tables:jobs,eventsandoutbox. A restarted server resumes queued jobs in order and loses no event. A job left running across two stops failsinterruptedinstead of crashing the server again. Uploads no job names are deleted at start.GET /v1/events?after=returns every outcome for the calling key since its cursor, paged by size (1 MiB) withhas_more, as JSON or Server-Sent Events withLast-Event-ID. A deleted job's events stay in the feed, markeddeleted: true.result_url. The refusal error iscallback_not_allowed.POST /v1/audio/transcriptionsanswersjson,verbose_json,textand streamed responses, checked against a pinned copy of OpenAI's OpenAPI transcription operation. Errors keep akou's single error shape.server.max_audio_minutes(default 240) fails a longer file withtoo_long(422 on the OpenAI route). ffmpeg is stopped as soon as its output passes the cap.akou transcribe <file>runs the same job through the local server, prints the transcript, and deletes the job afterwards. A silent file prints nothing and says so on stderr.Beads
akou transcribe sample.oggagainstakou serveon Linux prints a transcripttests/jobs.e2e.test.ts"SV-D1" (4 tests); REQUIREMENTS and PRINCIPLES updated. Missing: the Linux run needsakou serveand ffmpeg from the image lane{x: 1}comes back on the done job; nofilegets 422 in the PG-A7 shapetests/jobs.e2e.test.ts. Red with metadata forced to nullwait=60on a 5 s clip answersdonein one request;wait=1on a queued job answersqueuedafter a secondengine.modelsnames known model idsfastandautopass the schema;lite,best,fusionanswer 409preset_unavailablebecause those engines are not built.wordsis empty and confidences are null until an engine provides themcancelledwithin 2 s; retention does the sameyou; diarize labels two speakerstests/job-pass.test.ts"SV-J7" (7 tests). Red with the speaker label set toyoutests/webhooks.test.tsplus an end-to-end signed delivery. Red with the signature input changed (5 fail)result_urland no texttests/webhooks.test.ts, end-to-end inline deliverywebhook-id; 410 gets no sixth tryhttp://169.254.169.254/gets 422; a host resolving to 169.254.1.1 is loggedwebhook.refused; loopback delivered when the key names itopenaiPython client gets a transcripttests/openai.e2e.test.ts. The Python client 2.8.1 was run by hand (json, verbose_json, text, stream); CI does not run itfastandauto, including an engine that invents text on noise; the other presets are not builtduration, jsontext, the stream event typeFully done: akou-5an.21, .22, .23, .26, .27, .28, .30, .31, .32, .33, .34, .36, .37, .53, .54.
Partial: akou-5an.1, .24, .45 (they need the image lane's
serveand ffmpeg, or engines not built yet).For the owner to check
akou serve, thenakou transcribe sample.oggprints a transcript (SV-D1's last clause).openaiPython client at a server-mode akou withbase_urland ajobskey and transcribe a file.jobskey and watch a signed delivery arrive; verify it with the Standard Webhooks library of your choice.Known follow-ups
akou transcribehas no test.