Files
Docwell/Server/internal/ai/media.go
T
tajniak81andClaude Opus 5.5 8c39b0aacb
CI / go (Media) (push) Successful in 11m59s
CI / go (Server) (push) Failing after 18m26s
CI / go (Web-App) (push) Canceled after 0s
CI / frontend (push) Failing after 8m35s
CI / desktop (ubuntu-latest) (push) Successful in 1h10m6s
CI / mobile (push) Failing after 3m43s
CI / docker (push) Successful in 1h2m44s
Docs / build (push) Successful in 11m58s
Docs / deploy (push) Skipped
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
Run ffmpeg in its own docwell-media service
ffmpeg parses untrusted uploads, so it moves out of the server image
into a container of its own (ADR-15):

- Media/: docwell-media, a small Go wrapper around ffmpeg.
  POST /v1/split takes a recording and returns the 16 kHz mono MP3
  pieces as multipart/mixed. ffmpeg may only open local files and
  common audio/video demuxers (no playlists); optional shared token,
  a job limit, a timeout and a 1 GB cap.
- Server: DOCWELL_MEDIA_URL and DOCWELL_MEDIA_TOKEN send recordings
  over 25 MB to the service. When it is blank or unreachable, the
  server uses a local ffmpeg if it has one, else cuts MP3 and WAV in
  Go. The server image no longer installs ffmpeg; the all-in-one
  image keeps it to stay one container.
- Compose: a media service in every stack, read-only, no
  capabilities, on an internal network only docwell-server joins.
- CI tests the new module and checks that only the server reaches
  media; the release workflow publishes docwell-media.
- Docs, ADR-15 and the .env examples.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 10:52:34 +01:00

127 lines
4.2 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package ai
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"mime"
"mime/multipart"
"net/http"
"net/url"
"strings"
"time"
"docwell/server/internal/apperr"
)
// ---- docwell-media ------------------------------------------------------------------
//
// docwell-media (Media/ in the repository) is ffmpeg behind a small HTTP API,
// in a container of its own. The server sends it a recording and gets back
// the MP3 pieces in order (multipart/mixed).
// mediaClient calls docwell-media; nil when DOCWELL_MEDIA_URL is not set.
type mediaClient struct {
url string // base URL, no trailing slash
token string
http *http.Client
}
func newMediaClient(base, token string) *mediaClient {
if base == "" {
return nil
}
// No response timeout: a long recording takes minutes to re-encode, and
// the request's context ends the call.
return &mediaClient{url: strings.TrimRight(base, "/"), token: token, http: &http.Client{
Transport: &http.Transport{TLSHandshakeTimeout: 15 * time.Second, IdleConnTimeout: 90 * time.Second},
}}
}
// errMediaUnavailable means docwell-media could not be used (not reachable,
// or failed); the server then cuts the recording itself where it can.
var errMediaUnavailable = errors.New("media service unavailable")
// split sends the recording to docwell-media and returns its MP3 pieces.
func (m *mediaClient) split(ctx context.Context, name string, data []byte) ([][]byte, error) {
q := url.Values{"name": {name}, "segment": {fmt.Sprint(segmentSeconds)}}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, m.url+"/v1/split?"+q.Encode(), bytes.NewReader(data))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/octet-stream")
if m.token != "" {
req.Header.Set("Authorization", "Bearer "+m.token)
}
res, err := m.http.Do(req)
if err != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
return nil, fmt.Errorf("%w: %w", errMediaUnavailable, err)
}
defer res.Body.Close()
switch res.StatusCode {
case http.StatusOK:
case http.StatusUnprocessableEntity: // ffmpeg could not read it
b, _ := io.ReadAll(io.LimitReader(res.Body, 1024))
return nil, apperr.Invalid(strings.TrimSpace(string(b)))
case http.StatusRequestEntityTooLarge:
return nil, apperr.Invalid("The recording is larger than the media service accepts.")
default:
b, _ := io.ReadAll(io.LimitReader(res.Body, 512))
return nil, fmt.Errorf("%w: %s %s", errMediaUnavailable, res.Status, strings.TrimSpace(string(b)))
}
mt, params, err := mime.ParseMediaType(res.Header.Get("Content-Type"))
if err != nil || mt != "multipart/mixed" || params["boundary"] == "" {
return nil, fmt.Errorf("%w: unexpected response %q", errMediaUnavailable, res.Header.Get("Content-Type"))
}
mr := multipart.NewReader(res.Body, params["boundary"])
var parts [][]byte
total := 0
for {
p, err := mr.NextPart()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return nil, fmt.Errorf("%w: %w", errMediaUnavailable, err)
}
// The pieces are smaller than the recording; a bigger answer is wrong.
b, err := io.ReadAll(io.LimitReader(p, int64(MaxRecordingBytes-total)+1))
if err != nil {
return nil, fmt.Errorf("%w: %w", errMediaUnavailable, err)
}
if total += len(b); total > MaxRecordingBytes {
return nil, fmt.Errorf("%w: response too large", errMediaUnavailable)
}
parts = append(parts, b)
}
return parts, nil
}
// splitRecording cuts a recording into pieces of at most max bytes: in
// docwell-media when it is set up, else on the server (splitAudio).
func (s *Service) splitRecording(ctx context.Context, name string, data []byte, max int) ([]audioPiece, error) {
if len(data) <= max || s.media == nil {
return splitAudio(ctx, name, data, max)
}
parts, err := s.media.split(ctx, name, data)
if err == nil {
return mp3Pieces(name, parts, max)
}
if !errors.Is(err, errMediaUnavailable) {
return nil, err
}
s.log.Warn("ai: media service failed, cutting the recording on the server", "err", err)
pieces, lerr := splitAudio(ctx, name, data, max)
if errors.Is(lerr, errNeedsFFmpeg) {
return nil, apperr.Invalid("The media service that cuts long recordings is not reachable. Try again later, or ask an administrator.")
}
return pieces, lerr
}