engine

package
v0.0.0-...-a2e4442 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 22, 2026 License: GPL-2.0 Imports: 55 Imported by: 0

Documentation

Index

Constants

View Source
const ShutdownDelay = 3 * time.Second

ShutdownDelay is the delay before shutdown actually executes, matching aria2's TimedHaltCommand 3-second delay to give clients time to receive the RPC response.

Variables

This section is empty.

Functions

This section is empty.

Types

type AddSpec

type AddSpec struct {
	URIs        []string
	Options     *config.Options
	Torrent     []byte
	Metalink    []byte
	MetadataURI string
	OutputName  string
	Position    int
	PositionSet bool
	BelongsTo   core.GID
}

AddSpec describes a download to be added to the engine.

type AuthConfig

type AuthConfig struct {
	// contains filtered or unexported fields
}

AuthConfig holds authentication credentials for a download request. Matches aria2's AuthConfig class.

func NewAuthConfig

func NewAuthConfig(user, password string) *AuthConfig

NewAuthConfig creates an AuthConfig. Returns nil if user is empty. Matches aria2's AuthConfig::create.

func (*AuthConfig) GetAuthText

func (a *AuthConfig) GetAuthText() string

GetAuthText returns "user:password" for HTTP Basic auth.

func (*AuthConfig) Password

func (a *AuthConfig) Password() string

Password returns the password.

func (*AuthConfig) User

func (a *AuthConfig) User() string

User returns the username.

type AuthConfigFactory

type AuthConfigFactory struct {
	// contains filtered or unexported fields
}

AuthConfigFactory creates AuthConfig objects from URIs and configuration. Matches aria2's AuthConfigFactory.

func NewAuthConfigFactory

func NewAuthConfigFactory() *AuthConfigFactory

NewAuthConfigFactory creates a new AuthConfigFactory.

func (*AuthConfigFactory) CreateAuthConfig

func (f *AuthConfigFactory) CreateAuthConfig(uri string, opts *config.Options) *AuthConfig

CreateAuthConfig creates an AuthConfig for the given URI using the provided options. Matches aria2's AuthConfigFactory::createAuthConfig.

func (*AuthConfigFactory) SetNetrc

func (f *AuthConfigFactory) SetNetrc(entries []netrc.Entry, def *netrc.DefaultEntry)

SetNetrc sets netrc entries and default for auth resolution.

type BtSession

type BtSession struct {
	// contains filtered or unexported fields
}

BtSession holds BitTorrent session-level state shared across downloads.

func NewBtSession

func NewBtSession(cfg *config.Options) *BtSession

func (*BtSession) Close

func (s *BtSession) Close() error

func (*BtSession) DHTPort

func (s *BtSession) DHTPort() int

func (*BtSession) Dial

func (s *BtSession) Dial(ctx context.Context, dialer *netx.Dialer, addr string, cfg btpeer.Config) (*btpeer.Conn, error)

func (*BtSession) EnsureListening

func (s *BtSession) EnsureListening(log *slog.Logger) error

func (*BtSession) PeerID

func (s *BtSession) PeerID() [20]byte

func (*BtSession) Port

func (s *BtSession) Port() int

func (*BtSession) Register

func (s *BtSession) Register(cfg btpeer.Config) (*btInboundRegistration, error)

type DownloadPlan

type DownloadPlan struct {
	// contains filtered or unexported fields
}

DownloadPlan holds the file layout, piece metadata, and base path for a download.

func NewDownloadPlan

func NewDownloadPlan(pieceLen int64, totalLen int64, basePath string) *DownloadPlan

NewDownloadPlan creates a DownloadPlan for a single-file download. The path is used as the default base path and as the first file entry.

func (*DownloadPlan) FileFilter

func (dc *DownloadPlan) FileFilter() []bool

FileFilter returns the file filter.

func (*DownloadPlan) Files

func (dc *DownloadPlan) Files() []disk.FileEntry

Files returns the file entries. Exported for tests.

func (*DownloadPlan) FindFileEntryByOffset

func (dc *DownloadPlan) FindFileEntryByOffset(offset int64) (int, error)

FindFileEntryByOffset finds the file entry containing the given absolute byte offset. Returns the index and nil error on success. Returns -1 and an error if files are empty or offset is past the total length.

func (*DownloadPlan) GetBasePath

func (dc *DownloadPlan) GetBasePath() string

GetBasePath returns the base path. If basePath is empty, it returns the first file entry's name.

func (*DownloadPlan) GetNumPieces

func (dc *DownloadPlan) GetNumPieces() int

GetNumPieces returns the number of pieces. Returns 0 if pieceLen is 0; otherwise it rounds the final file's end offset up to a full piece count.

func (*DownloadPlan) GetPieceHash

func (dc *DownloadPlan) GetPieceHash(idx int) ([]byte, bool)

GetPieceHash returns the piece hash at the given index. Returns nil, false if the index is out of range.

func (*DownloadPlan) KnowsTotalLength

func (dc *DownloadPlan) KnowsTotalLength() bool

KnowsTotalLength returns whether the total length is known.

func (*DownloadPlan) PieceLength

func (dc *DownloadPlan) PieceLength() int64

PieceLength returns the piece length.

func (*DownloadPlan) SetBasePath

func (dc *DownloadPlan) SetBasePath(path string)

SetBasePath sets the base path.

func (*DownloadPlan) SetFileFilter

func (dc *DownloadPlan) SetFileFilter(filter []bool)

SetFileFilter marks which files are requested based on the filter slice. If filter is empty or only one file, all files are requested. Otherwise, filter entries mark which files are requested.

func (*DownloadPlan) SetFiles

func (dc *DownloadPlan) SetFiles(files []disk.FileEntry)

SetFiles sets the file entries from a slice.

func (*DownloadPlan) SetKnowsTotalLength

func (dc *DownloadPlan) SetKnowsTotalLength(v bool)

SetKnowsTotalLength sets whether the total length is known.

func (*DownloadPlan) SetPieceHashes

func (dc *DownloadPlan) SetPieceHashes(hashes [][]byte)

SetPieceHashes sets the piece hash type and hashes.

func (*DownloadPlan) SetPieceLength

func (dc *DownloadPlan) SetPieceLength(l int64)

SetPieceLength sets the piece length.

func (*DownloadPlan) TotalLength

func (dc *DownloadPlan) TotalLength() int64

TotalLength returns the total download length. If no files are present it returns 0; otherwise it returns the final file's end offset.

type Engine

type Engine struct {
	RPCBackend RPCBackend
	// contains filtered or unexported fields
}

Engine is the central download orchestrator, matching aria2's DownloadEngine architecture. It manages the lifecycle of all downloads (RequestGroups), assigns GIDs via random generation (matching aria2's GroupId::create), and dispatches lifecycle events via a pub/sub event bus.

In aria2's C++ implementation the engine uses an event-poll + command pattern. In Go the same semantics are achieved with goroutines + context cancellation: each active download runs in a goroutine that watches its context for cancellation, and the engine's queue management goroutine moves downloads between waiting/active/stopped queues.

func New

func New(cfg *config.Options, log *slog.Logger) (*Engine, error)

New creates a new Engine with the given configuration and logger. The engine does not start any goroutines until Run is called.

func (*Engine) Add

func (e *Engine) Add(spec AddSpec) (core.GID, error)

Add creates a new download from the given specification and assigns either the supplied valid GID or a random GID (matching aria2's GroupId::create). The download is placed in the waiting queue. If there are available active slots (respecting max-concurrent-downloads), the queue manager will promote it to active.

Returns the assigned GID on success.

func (e *Engine) AddMetalink(data []byte, opts *config.Options, pos int, posSet bool) ([]core.GID, error)

func (*Engine) ChangeGlobalOption

func (e *Engine) ChangeGlobalOption(opts *config.Options) error

ChangeGlobalOption updates the global engine options. These apply to all new downloads created after the change.

func (*Engine) ChangeOption

func (e *Engine) ChangeOption(gid core.GID, opts *config.Options) error

ChangeOption applies per-download option changes. For active downloads, the options are stored as pending and take effect on restart (pause+resume), matching aria2's pendingOption_ pattern (RequestGroupMan.cc:440-443). For waiting downloads, the options are applied immediately since the download has not yet started.

func (*Engine) ChangePosition

func (e *Engine) ChangePosition(gid core.GID, pos int, how string) (int64, error)

ChangePosition moves a download within the waiting queue. how must be one of "POS_SET", "POS_CUR", or "POS_END". Returns the new absolute position (0-indexed) matching aria2's ChangePositionRpcMethod.

func (*Engine) ChangeURI

func (e *Engine) ChangeURI(gid core.GID, fileIndex int, delURIs, addURIs []string, pos int) (int64, int64, error)

ChangeURI mutates the URI list for a single-file download and returns the number of removed and added URIs.

func (*Engine) ChangeURIWithPosition

func (e *Engine) ChangeURIWithPosition(gid core.GID, fileIndex int, delURIs, addURIs []string, pos int, positionSet bool) (int64, int64, error)

ChangeURIWithPosition mutates the URI list for a single-file download. When positionSet is false, new URIs are appended; when true, pos is clamped to the current URI list length, matching aria2.changeUri's optional position.

func (*Engine) ClearGIDs

func (e *Engine) ClearGIDs()

ClearGIDs resets the used GID set. Only for testing.

func (*Engine) Created

func (e *Engine) Created() time.Time

Created returns the time the engine was created.

func (*Engine) ExitCode

func (e *Engine) ExitCode() core.ErrorCode

ExitCode returns the CLI session result code after Run has drained.

func (*Engine) GetDownloadStat

func (e *Engine) GetDownloadStat() (completed, errors, inProgress, waiting int)

GetDownloadStat returns aggregate statistics for completed/error/in-progress/waiting downloads, matching aria2's RequestGroupMan::getDownloadStat.

func (*Engine) GetGlobalOption

func (e *Engine) GetGlobalOption() *config.Options

GetGlobalOption returns a copy of the current global options.

func (*Engine) GetGlobalStat

func (e *Engine) GetGlobalStat() GlobalStat

GetGlobalStat returns aggregate statistics about the engine's current state, matching aria2's GetGlobalStatRpcMethod which calls RequestGroupMan::calculateStat plus getReservedGroups().size(), getDownloadResults().size(), and getNumStoppedTotal().

func (*Engine) GetOption

func (e *Engine) GetOption(gid core.GID) (*config.Options, error)

GetOption returns a copy of the current per-download options for gid.

func (*Engine) GetPeers

func (e *Engine) GetPeers(gid core.GID) ([]PeerStatus, error)

func (*Engine) LoadSession

func (e *Engine) LoadSession(path string) error

LoadSession restores downloads from an aria2 session file at the given path. Each entry in the session file is added to the engine as a waiting download. Entries with the pause flag set are added in paused state.

func (*Engine) NumStopped

func (e *Engine) NumStopped() int64

NumStopped returns the total number of downloads that have ever been stopped (mirrors aria2's RequestGroupMan::getNumStoppedTotal).

func (*Engine) Pause

func (e *Engine) Pause(gid core.GID, force bool) error

Pause pauses an active or waiting download. For an active download, this mirrors aria2's pauseRequestGroup(): it marks the group paused, requests the active worker to halt, and lets removeStoppedGroup finalize the transition to the waiting queue and fire pause hooks once the worker stops.

If force is true, the active worker is force-halted.

func (*Engine) PurgeDownloadResult

func (e *Engine) PurgeDownloadResult() int

PurgeDownloadResult clears the stopped/results queue and returns the number of entries purged. This matches aria2's purgeDownloadResult.

func (*Engine) Remove

func (e *Engine) Remove(gid core.GID, force bool) error

Remove removes a download. Active downloads are force-halted first. Waiting downloads are dropped from the reserved queue without producing a stopped result, matching aria2's removeReservedGroup path.

If force is true, the removal is immediate even if the download is mid-transfer.

func (*Engine) RemoveDownloadResult

func (e *Engine) RemoveDownloadResult(gid core.GID) error

RemoveDownloadResult removes a completed/error/removed result from the stopped-results queue.

func (*Engine) RemovedErrorResult

func (e *Engine) RemovedErrorResult() (count int, lastErr core.ErrorCode)

RemovedErrorResult returns the count and last error code of error results evicted from the stopped queue due to max-download-result limits.

func (*Engine) Resume

func (e *Engine) Resume(gid core.GID) error

Resume restarts a paused download after it has reached the waiting queue. The queue manager will promote it to active when a slot becomes available, matching aria2's unpause -> waiting -> active flow.

func (*Engine) Run

func (e *Engine) Run(ctx context.Context) error

Run starts the engine's main goroutines and blocks until the context is cancelled or all downloads complete. The engine exits cleanly when ctx is done; call Shutdown for graceful shutdown.

When keepRunning is true (set via PREF_ENABLE_RPC), the engine continues running even when there are no active downloads, matching aria2's keepRunning_ flag.

func (*Engine) SaveSession

func (e *Engine) SaveSession() error

SaveSession serializes the current engine state (all active and waiting downloads) to the save-session file path specified in configuration. The output is aria2-compatible session file format using the sessionfile package. If no save session path is configured, this is a no-op.

func (*Engine) SessionID

func (e *Engine) SessionID() string

SessionID returns the engine's session identifier, used by the RPC layer for session-scoped state.

func (*Engine) SetDispatcherFactory

func (e *Engine) SetDispatcherFactory(fn func(e *Engine, secret string) RPCBackend)

SetDispatcherFactory sets the factory function used to create an RPC dispatcher backend when EnableRPC is true. Must be called before Run(). The factory receives the engine and RPC secret, and returns an RPCBackend which bridges to the transport layer. This indirection avoids an import cycle between engine and rpc/dispatcher.

func (*Engine) Shutdown

func (e *Engine) Shutdown(force bool) error

Shutdown initiates an orderly shutdown. If force is true, the shutdown is immediate (matching aria2's requestForceHalt). Otherwise, active downloads are requested to halt gracefully (requestHalt).

func (*Engine) ShutdownDelayed

func (e *Engine) ShutdownDelayed(force bool)

ShutdownDelayed schedules a shutdown after ShutdownDelay, matching aria2's TimedHaltCommand pattern. This gives the RPC client time to receive the response before the server exits.

func (*Engine) Subscribe

func (e *Engine) Subscribe(ch chan core.Event) SubscribeResult

SubscribeChannel registers a channel to receive engine lifecycle events. Returns a result containing the read-only channel and an unsubscribe function.

Callers should use a buffered channel (e.g. make(chan core.Event, 64)) to avoid missing events during bursts. If the channel is full, events are dropped — matching aria2's Notifier behavior where missed events are not retried.

func (*Engine) SubscribeChannel

func (e *Engine) SubscribeChannel(ch chan core.Event) SubscribeResult

SubscribeChannel registers a channel to receive engine lifecycle events. Identical to Subscribe; provided for API compatibility with tests that prefer the explicit channel-oriented name.

func (*Engine) SubscribeLegacy

func (e *Engine) SubscribeLegacy(s Subscriber) (unsubscribe func())

SubscribeLegacy registers a Subscriber-compatible interface for engines that use the older synchronous pattern. Returns an unsubscribe function.

func (*Engine) TellActive

func (e *Engine) TellActive() []Status

TellActive returns status snapshots of all active downloads.

func (*Engine) TellActiveKeys

func (e *Engine) TellActiveKeys(keys []string) []map[string]any

TellActiveKeys returns status maps of all active downloads, filtered to the requested keys.

func (*Engine) TellStatus

func (e *Engine) TellStatus(gid core.GID) (*Status, error)

TellStatus returns the current status of a single download.

func (*Engine) TellStatusKeys

func (e *Engine) TellStatusKeys(gid core.GID, keys []string) (map[string]any, error)

TellStatusKeys returns the current status of a single download as an aria2 RPC-compatible map. If keys is non-empty, only the requested keys are included (matching aria2's tellStatus keys parameter behavior).

func (*Engine) TellStopped

func (e *Engine) TellStopped(offset, num int) []Status

TellStopped returns status snapshots of completed/error/removed downloads, starting at offset, up to num entries.

func (*Engine) TellStoppedKeys

func (e *Engine) TellStoppedKeys(offset, num int, keys []string) []map[string]any

TellStoppedKeys returns status maps of completed/error/removed downloads, starting at offset, up to num entries, filtered to the requested keys.

func (*Engine) TellWaiting

func (e *Engine) TellWaiting(offset, num int) []Status

TellWaiting returns status snapshots of waiting/paused downloads, starting at offset, up to num entries.

func (*Engine) TellWaitingKeys

func (e *Engine) TellWaitingKeys(offset, num int, keys []string) []map[string]any

TellWaitingKeys returns status maps of waiting/paused downloads, starting at offset, up to num entries, filtered to the requested keys.

type EventBus

type EventBus struct {
	// contains filtered or unexported fields
}

EventBus provides in-process pub/sub for download events. Subscribers receive events on channels, matching aria2's Notifier pattern (Notifier.h) where DownloadEventListener receives onEvent calls.

func NewEventBus

func NewEventBus() *EventBus

NewEventBus creates a new EventBus.

func (*EventBus) Emit

func (b *EventBus) Emit(ev core.Event)

Emit sends an event to all subscribers. If a subscriber's channel is full, the event is dropped for that subscriber (non-blocking). This matches aria2's Notifier::notifyDownloadEvent which calls each listener's onEvent synchronously — here we use channels for decoupling.

func (*EventBus) Len

func (b *EventBus) Len() int

Len returns the current number of subscribers.

func (*EventBus) Subscribe

func (b *EventBus) Subscribe(ch chan core.Event) (unsubscribe func())

Subscribe registers a channel to receive events. Returns a function that unsubscribes the channel. The channel is non-buffered; callers should use a buffered channel or a select-based drain to avoid blocking emits.

type FileStatus

type FileStatus struct {
	Index           int         `json:"index,string"`
	Path            string      `json:"path"`
	Length          int64       `json:"length,string"`
	CompletedLength int64       `json:"completedLength,string"`
	Selected        bool        `json:"selected,string"`
	URIs            []URIStatus `json:"uris"`
}

FileStatus describes a file within a multi-file download.

type GlobalStat

type GlobalStat struct {
	DownloadSpeed   int64
	UploadSpeed     int64
	NumActive       int
	NumWaiting      int
	NumStopped      int
	NumStoppedTotal int64
}

GlobalStat holds aggregate engine statistics matching aria2's getGlobalStat RPC response (downloadSpeed, uploadSpeed, numActive, numWaiting, numStopped, numStoppedTotal).

type PeerStatus

type PeerStatus struct {
	PeerID        string
	IP            string
	Port          string
	Bitfield      string
	AmChoking     bool
	PeerChoking   bool
	DownloadSpeed int64
	UploadSpeed   int64
	Seeder        bool
}

type RPCBackend

type RPCBackend interface {
	Call(ctx context.Context, token, method string, params []any) (any, error)
	SubscribeNotifications(sink func(name string, params map[string]any)) (cancel func())
}

RPCBackend is the interface the rpcAdapter bridges to the transport layer.

type Segment

type Segment struct {
	Index   int
	Start   int64
	End     int64
	Written int64
	Done    bool
	Claimed bool
}

Segment represents a byte range of a download. Start is inclusive, End is exclusive. When End is -1 the total size is unknown.

type SegmentMan

type SegmentMan struct {
	// contains filtered or unexported fields
}

SegmentMan manages a collection of segments for parallel download. Workers call Next to claim an undone segment and MarkDone when finished. Unclaim releases a claimed segment on transient error. Split subdivides the largest in-progress segment into two halves; the new half becomes available via Next.

func NewSegmentMan

func NewSegmentMan(totalSize int64, numSegments int) *SegmentMan

NewSegmentMan divides totalSize into numSegments equal-sized segments. When totalSize <= 0 the End of every segment is -1 (unknown size). When numSegments > totalSize each byte gets its own segment.

func NewSegmentManWithSplit

func NewSegmentManWithSplit(totalSize int64, numSegments int, minSplitSize int64) *SegmentMan

NewSegmentManWithSplit is like NewSegmentMan but also sets the minimum split size used by Split.

func (*SegmentMan) Done

func (sm *SegmentMan) Done() bool

Done reports whether every segment has been marked done.

func (*SegmentMan) MarkDone

func (sm *SegmentMan) MarkDone(idx int, written int64)

MarkDone marks a segment as complete and records the number of bytes written. Multiple calls update Written but do not undo the Done flag.

func (*SegmentMan) Next

func (sm *SegmentMan) Next() *Segment

Next returns an unclaimed, undone segment. It scans circularly from the last returned position. Returns nil when every segment is either claimed or done.

func (*SegmentMan) SegmentCount

func (sm *SegmentMan) SegmentCount() int

SegmentCount returns the current number of segments (including split segments).

func (*SegmentMan) Split

func (sm *SegmentMan) Split(minSplitSize int64) *Segment

Split subdivides the in-progress (claimed but not done) segment with the largest remaining bytes, provided it is at least 2*minSplitSize bytes long. The original segment is halved in place and a new segment covering the second half is appended. The original remains claimed; the new segment is unclaimed and available via Next.

Returns the new segment or nil when no segment qualifies.

func (*SegmentMan) Unclaim

func (sm *SegmentMan) Unclaim(idx int)

Unclaim releases a claimed but not done segment back to the pool, so another worker can pick it up (e.g. after a transient error). Does nothing if idx is out of range or the segment is already done.

func (*SegmentMan) Written

func (sm *SegmentMan) Written() int64

Written returns the total number of bytes recorded via MarkDone.

type ServerStat

type ServerStat struct {
	// contains filtered or unexported fields
}

ServerStat tracks per-server performance statistics. It matches aria2's ServerStat class.

func NewServerStat

func NewServerStat(hostname, protocol string) *ServerStat

NewServerStat creates a new ServerStat with the given hostname and protocol. Matches aria2's ServerStat(hostname, protocol) constructor: speeds=0, counter=0, status=OK.

func (*ServerStat) Counter

func (s *ServerStat) Counter() int32

Counter returns the use counter.

func (*ServerStat) DownloadSpeed

func (s *ServerStat) DownloadSpeed() int64

DownloadSpeed returns the current download speed.

func (*ServerStat) Equal

func (s *ServerStat) Equal(other *ServerStat) bool

Equal compares by hostname and protocol. Matches aria2's operator==.

func (*ServerStat) Hostname

func (s *ServerStat) Hostname() string

Hostname returns the server hostname.

func (*ServerStat) IncreaseCounter

func (s *ServerStat) IncreaseCounter()

IncreaseCounter increments the counter by 1. Matches aria2's increaseCounter.

func (*ServerStat) IsError

func (s *ServerStat) IsError() bool

IsError returns true if the status is ERROR.

func (*ServerStat) IsOK

func (s *ServerStat) IsOK() bool

IsOK returns true if the status is OK.

func (*ServerStat) LastUpdated

func (s *ServerStat) LastUpdated() time.Time

LastUpdated returns the last updated time.

func (*ServerStat) Less

func (s *ServerStat) Less(other *ServerStat) bool

Less compares by hostname then protocol. Matches aria2's operator<.

func (*ServerStat) MultiConnectionAvgSpeed

func (s *ServerStat) MultiConnectionAvgSpeed() int64

MultiConnectionAvgSpeed returns the multi-connection average speed.

func (*ServerStat) Protocol

func (s *ServerStat) Protocol() string

Protocol returns the server protocol.

func (*ServerStat) SetCounter

func (s *ServerStat) SetCounter(v int32)

SetCounter sets the counter.

func (*ServerStat) SetDownloadSpeed

func (s *ServerStat) SetDownloadSpeed(v int64)

SetDownloadSpeed sets the download speed without updating lastUpdated.

func (*ServerStat) SetError

func (s *ServerStat) SetError()

SetError sets status to ERROR and resets lastUpdated to now.

func (*ServerStat) SetLastUpdated

func (s *ServerStat) SetLastUpdated(t time.Time)

SetLastUpdated sets the last updated time without resetting.

func (*ServerStat) SetMultiConnectionAvgSpeed

func (s *ServerStat) SetMultiConnectionAvgSpeed(v int64)

SetMultiConnectionAvgSpeed sets the multi-connection average speed.

func (*ServerStat) SetOK

func (s *ServerStat) SetOK()

SetOK sets status to OK and resets lastUpdated to now.

func (*ServerStat) SetSingleConnectionAvgSpeed

func (s *ServerStat) SetSingleConnectionAvgSpeed(v int64)

SetSingleConnectionAvgSpeed sets the single-connection average speed.

func (*ServerStat) SetStatus

func (s *ServerStat) SetStatus(status string)

SetStatus sets the status from a string ("OK" or "ERROR") without updating lastUpdated. Matches aria2's setStatus(const string&).

func (*ServerStat) SingleConnectionAvgSpeed

func (s *ServerStat) SingleConnectionAvgSpeed() int64

SingleConnectionAvgSpeed returns the single-connection average speed.

func (*ServerStat) Status

func (s *ServerStat) Status() ServerStatStatus

Status returns the server status.

func (*ServerStat) UpdateDownloadSpeed

func (s *ServerStat) UpdateDownloadSpeed(v int64)

UpdateDownloadSpeed sets the download speed and resets lastUpdated to now. If speed > 0, status is set to OK. Matches aria2's updateDownloadSpeed.

type ServerStatMan

type ServerStatMan struct {
	// contains filtered or unexported fields
}

ServerStatMan manages a set of ServerStat entries, supporting load/save and stale removal. Matches aria2's ServerStatMan.

func NewServerStatMan

func NewServerStatMan() *ServerStatMan

NewServerStatMan creates a new ServerStatMan.

func (*ServerStatMan) Add

func (m *ServerStatMan) Add(stat *ServerStat)

Add inserts a ServerStat. If an entry with the same hostname and protocol already exists, false is returned. Matches aria2's add which uses lower_bound and checks for equality.

func (*ServerStatMan) Find

func (m *ServerStatMan) Find(hostname, protocol string) *ServerStat

Find looks up a ServerStat by hostname and protocol. Returns nil if not found. Matches aria2's find which creates a temp ServerStat for lookup.

func (*ServerStatMan) Len

func (m *ServerStatMan) Len() int

Len returns the number of stored server stats.

func (*ServerStatMan) Load

func (m *ServerStatMan) Load(r io.Reader) error

Load reads server stats from r in CSV format. Matches aria2's load which parses key=value pairs separated by commas, one entry per line.

func (*ServerStatMan) RemoveStale

func (m *ServerStatMan) RemoveStale(timeout time.Duration)

RemoveStale removes entries whose lastUpdated time is older than the given timeout duration. Matches aria2's removeStaleServerStat which compares Time::difference(now) >= timeout.

func (*ServerStatMan) Save

func (m *ServerStatMan) Save(w io.Writer) error

Save writes all server stats to w in CSV format, one line per entry. Matches aria2's save which writes toString() + "\n" for each entry.

func (*ServerStatMan) Stats

func (m *ServerStatMan) Stats() []*ServerStat

Stats returns a copy of all stored server stats.

type ServerStatStatus

type ServerStatStatus int32

ServerStatStatus represents the status of a server stat entry.

const (
	ServerStatOK    ServerStatStatus = 0
	ServerStatError ServerStatStatus = 1
)

func (ServerStatStatus) String

func (s ServerStatStatus) String() string

type Status

type Status struct {
	GID                    core.GID       `json:"gid"`
	Status                 core.Status    `json:"status"`
	TotalLength            int64          `json:"totalLength"`
	CompletedLength        int64          `json:"completedLength"`
	UploadLength           int64          `json:"uploadLength"`
	DownloadSpeed          int64          `json:"downloadSpeed"`
	UploadSpeed            int64          `json:"uploadSpeed"`
	InfoHash               string         `json:"infoHash,omitempty"`
	NumSeeders             int64          `json:"numSeeders,string"`
	Connections            int            `json:"connections"`
	ErrorCode              core.ErrorCode `json:"errorCode,string"`
	ErrorMessage           string         `json:"errorMessage,omitempty"`
	FollowedBy             []core.GID     `json:"followedBy,omitempty"`
	BelongsTo              core.GID       `json:"belongsTo,omitempty"`
	Following              core.GID       `json:"following,omitempty"`
	Dir                    string         `json:"dir"`
	Files                  []FileStatus   `json:"files"`
	Seeder                 bool           `json:"seeder,string"`
	Bittorrent             map[string]any `json:"bittorrent,omitempty"`
	VerifiedLength         int64          `json:"verifiedLength"`
	VerifyIntegrityPending bool           `json:"verifyIntegrityPending,string"`
	Bitfield               string         `json:"bitfield,omitempty"`
	PieceLength            int64          `json:"pieceLength"`
	NumPieces              int64          `json:"numPieces"`
}

Status is the public status snapshot of a single download, matching aria2's aria2.tellStatus RPC response shape.

type SubscribeResult

type SubscribeResult struct {
	C           <-chan core.Event
	Unsubscribe func()
}

SubscribeResult holds the result of subscribing to engine events.

type Subscriber

type Subscriber interface {
	OnEvent(ev core.Event)
}

Subscriber receives engine lifecycle events. Implementations must not block.

type Throttle

type Throttle struct {
	// contains filtered or unexported fields
}

Throttle implements a token bucket rate limiter with 100ms refill ticks. Zero rate means unlimited — Wait returns immediately.

func NewThrottle

func NewThrottle(bytesPerSec int64) *Throttle

NewThrottle creates a Throttle with the given bytes/sec rate. Pass 0 for unlimited.

func (*Throttle) SetRate

func (t *Throttle) SetRate(bytesPerSec int64)

SetRate changes the bytes/sec limit. Pass 0 for unlimited.

func (*Throttle) Stop

func (t *Throttle) Stop()

Stop shuts down the refill goroutine.

func (*Throttle) Wait

func (t *Throttle) Wait(ctx context.Context, n int) error

Wait blocks until n bytes of capacity are available or ctx is cancelled. If the rate is 0 (unlimited), Wait returns immediately.

type URIStatus

type URIStatus struct {
	URI    string `json:"uri"`
	Status string `json:"status"`
}

URIStatus describes the status of a single URI for a file.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL