99 lines
2.5 KiB
Go
99 lines
2.5 KiB
Go
package plugin
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"sync"
|
|
"sync/atomic"
|
|
|
|
"github.com/Nwflower/reims-go/internal/downloader"
|
|
)
|
|
|
|
// downloaderProgressHub routes `host/downloader.progress` callbacks emitted by
|
|
// an L3 sidecar process back to the matching in-flight Download call.
|
|
type downloaderProgressHub struct {
|
|
mu sync.RWMutex
|
|
seq atomic.Uint64
|
|
cbs map[string]func(downloader.Progress)
|
|
}
|
|
|
|
func newDownloaderProgressHub() *downloaderProgressHub {
|
|
return &downloaderProgressHub{cbs: make(map[string]func(downloader.Progress))}
|
|
}
|
|
|
|
func (h *downloaderProgressHub) register(cb func(downloader.Progress)) (string, func()) {
|
|
id := fmt.Sprintf("dl-%d", h.seq.Add(1))
|
|
if cb != nil {
|
|
h.mu.Lock()
|
|
h.cbs[id] = cb
|
|
h.mu.Unlock()
|
|
}
|
|
return id, func() {
|
|
h.mu.Lock()
|
|
delete(h.cbs, id)
|
|
h.mu.Unlock()
|
|
}
|
|
}
|
|
|
|
func (h *downloaderProgressHub) handleRPC(_ context.Context, raw json.RawMessage) (any, error) {
|
|
var msg struct {
|
|
DownloadID string `json:"download_id"`
|
|
Done int64 `json:"done"`
|
|
Total int64 `json:"total"`
|
|
SpeedBPS float64 `json:"speed_bps"`
|
|
Connections int `json:"connections"`
|
|
Message string `json:"message"`
|
|
}
|
|
if err := json.Unmarshal(raw, &msg); err != nil {
|
|
return nil, err
|
|
}
|
|
h.mu.RLock()
|
|
cb := h.cbs[msg.DownloadID]
|
|
h.mu.RUnlock()
|
|
if cb != nil {
|
|
cb(downloader.Progress{
|
|
Done: msg.Done,
|
|
Total: msg.Total,
|
|
SpeedBPS: msg.SpeedBPS,
|
|
Connections: msg.Connections,
|
|
Message: msg.Message,
|
|
})
|
|
}
|
|
return map[string]any{"ok": true}, nil
|
|
}
|
|
|
|
type sidecarDownloader struct {
|
|
contrib DownloaderContribution
|
|
sup *SidecarSupervisor
|
|
hub *downloaderProgressHub
|
|
settingsFn func() map[string]any
|
|
}
|
|
|
|
func newSidecarDownloader(contrib DownloaderContribution, sup *SidecarSupervisor, hub *downloaderProgressHub, settingsFn func() map[string]any) downloader.Provider {
|
|
return &sidecarDownloader{contrib: contrib, sup: sup, hub: hub, settingsFn: settingsFn}
|
|
}
|
|
|
|
func (s *sidecarDownloader) ID() string {
|
|
return s.contrib.ID
|
|
}
|
|
|
|
func (s *sidecarDownloader) Download(ctx context.Context, req downloader.Request, onProgress func(downloader.Progress)) error {
|
|
dlID, unregister := s.hub.register(onProgress)
|
|
defer unregister()
|
|
|
|
var settings map[string]any
|
|
if s.settingsFn != nil {
|
|
settings = s.settingsFn()
|
|
}
|
|
var resp struct {
|
|
OK bool `json:"ok"`
|
|
}
|
|
return s.sup.Call(ctx, "downloader/download", map[string]any{
|
|
"downloader_id": s.contrib.ID,
|
|
"download_id": dlID,
|
|
"request": req,
|
|
"settings": settings,
|
|
}, &resp)
|
|
}
|