Phase 6: Mini App

A Telegram Mini App served by the core under /app/, embedded in the binary.

- API under /app/api/ with initData validated (HMAC, age) on every call
- Pages: Home, Queue, Buy (target, product, invoice), History, Groups,
  group detail (Overview, Settings, Wallet, Usage) and Me
- Every action runs through the same service, billing and scheduler code
  as the chat, so limits, prices and admin checks are decided on the server
- Texts come from the catalog over the API; layout mirrors for RTL
- Front end in web/miniapp (Vite, React, TypeScript); the build is
  committed and guarded by a source hash test; the Docker image rebuilds it
- MINIAPP_ENABLED with an https PUBLIC_URL; entry points from /app, group
  settings and the over-limit offer
- Browser test (make miniapp-e2e) against a core in test mode
- Fix: each download attempt gets its own scratch directory, so a retry
  cannot lose its file to the cleanup of the failed attempt

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-18 10:27:20 +00:00
co-authored by Claude Fable 5.2
parent 51371da0e0
commit 4f11f939a0
55 changed files with 7069 additions and 6 deletions
+8 -1
View File
@@ -11,6 +11,7 @@ import (
"math"
"os"
"path/filepath"
"strconv"
"sync"
"sync/atomic"
"time"
@@ -71,6 +72,8 @@ type Worker struct {
trans ffmpeg.Transcoder
log *slog.Logger
active atomic.Int32
// runs numbers the jobs this process has started, for directory names.
runs atomic.Uint64
// lastOK is the unix time of the last call the core answered.
lastOK atomic.Int64
// authFailed is set when the core rejected the token.
@@ -277,7 +280,11 @@ func (w *Worker) slot(ctx context.Context) {
// process runs one job to completion and always reports an outcome.
func (w *Worker) process(ctx context.Context, job *workerproto.Job) {
log := w.log.With("job_id", job.ID, "attempt", job.Attempt)
dir := filepath.Join(w.cfg.TempDir, job.ID)
// Each run gets a directory of its own. A retry of the same job can
// start on another slot while this one is still reporting its
// failure; with a shared directory this slot's cleanup would delete
// the retry's file.
dir := filepath.Join(w.cfg.TempDir, job.ID+"."+strconv.FormatUint(w.runs.Add(1), 10))
defer func() {
if err := os.RemoveAll(dir); err != nil {
log.Warn("cannot remove temp dir", "err", err)
+77
View File
@@ -12,6 +12,7 @@ import (
"github.com/noderunners/dlbot/internal/sched"
"github.com/noderunners/dlbot/internal/storage"
"github.com/noderunners/dlbot/internal/worker"
"github.com/noderunners/dlbot/internal/workerproto"
"github.com/noderunners/dlbot/internal/ytdlp"
"github.com/noderunners/dlbot/internal/ytdlp/ytdlptest"
)
@@ -146,6 +147,82 @@ func TestWorkerRetriesOnceAfterRetryableFailure(t *testing.T) {
}
}
// slowFail is a coordinator whose Fail call returns late: the core has
// already put the job back in the queue, but the worker slot that reported
// the failure is still busy with the answer.
type slowFail struct {
*sched.Local
failed chan struct{} // closed when Fail may return
uploaded chan struct{}
}
func (c *slowFail) Fail(ctx context.Context, req workerproto.FailRequest) error {
err := c.Local.Fail(ctx, req)
<-c.failed
return err
}
func (c *slowFail) Upload(ctx context.Context, job *workerproto.Job, path string) error {
// The retry has its file. Now let the first attempt finish and clean
// up after itself, and only then upload.
close(c.failed)
time.Sleep(150 * time.Millisecond)
defer close(c.uploaded)
return c.Local.Upload(ctx, job, path)
}
// A retry can start on another slot of the same worker while the slot
// that failed is still wrapping up. The cleanup of the failed attempt must
// not remove the files of the retry.
func TestWorkerRetryDoesNotLoseItsFileToTheFailedAttempt(t *testing.T) {
url := "https://example.com/flaky"
fake := &ytdlptest.Fake{FileSize: 4096, DownloadErrs: map[string][]error{
url: {&ytdlp.Error{Code: ytdlp.CodeNetwork, Retryable: true, Raw: "connection reset"}},
}}
st, err := storage.NewLocal(filepath.Join(t.TempDir(), "files"))
if err != nil {
t.Fatal(err)
}
store := dbtest.Open(t).Store()
sc := sched.New(store, sched.Config{Lease: 5 * time.Second, MaxAttempts: 2}, nil)
coord := &slowFail{Local: &sched.Local{Sched: sc, Storage: st}, failed: make(chan struct{}), uploaded: make(chan struct{})}
w := worker.New(worker.Config{
ID: "w1", Concurrency: 2, TempDir: filepath.Join(t.TempDir(), "tmp"),
Heartbeat: 30 * time.Millisecond, ClaimWait: 100 * time.Millisecond,
}, coord, fake, nil)
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() { defer close(done); w.Run(ctx) }()
defer func() { cancel(); <-done }()
job, _, err := sc.Enqueue(ctx, sched.EnqueueParams{URL: url, Profile: "best", UserID: 1, ChatID: 1, MaxSize: 10 << 20})
if err != nil {
t.Fatal(err)
}
select {
case <-coord.uploaded:
case <-time.After(10 * time.Second):
t.Fatal("the retry never reached its upload")
}
deadline := time.Now().Add(5 * time.Second)
for {
got, err := store.GetJob(ctx, job.ID)
if err != nil {
t.Fatal(err)
}
if got.Status == db.JobDelivering {
if obj, err := st.Stat(ctx, got.StorageKey); err != nil || obj.Size != 4096 {
t.Fatalf("stored object = %+v, %v", obj, err)
}
return
}
if got.Status == db.JobFailed || time.Now().After(deadline) {
t.Fatalf("job is %s (%s): the retry lost its file to the cleanup of the first attempt", got.Status, got.ErrorCode)
}
time.Sleep(10 * time.Millisecond)
}
}
func TestWorkerGivesUpAfterSecondFailure(t *testing.T) {
url := "https://example.com/down"
netErr := &ytdlp.Error{Code: ytdlp.CodeNetwork, Retryable: true, Raw: "boom"}