scheduler

package
v1.0.0-rc.2 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ProbeModeAuto     = "auto"
	ProbeModeManual   = "manual"
	ProbeModeDisabled = "disabled"
)
View Source
const (
	PauseReasonPeerRatio = "做种竞争度过高"
)

Variables

View Source
var ErrAttendanceBusy = errors.New("站点正在探测或签到,请稍后再试")

ErrAttendanceBusy 表示该站正在被登录探测或另一次签到占用(共用单站单飞锁)。

Functions

func ComputeTier added in v0.35.0

func ComputeTier(state *models.SiteLoginState, effective, now time.Time) string

ComputeTier maps DaysRemaining into one of the predefined tier strings. The tier defines both the reminder urgency and whether quiet hours can be overridden (only banned-imminent overrides).

func DaysRemaining added in v0.35.0

func DaysRemaining(state *models.SiteLoginState, effective, now time.Time) int

DaysRemaining returns how many full days remain until the site's configured ban threshold elapses since the effective last-active time. Negative values mean the threshold has already been crossed.

func EffectiveActiveSource

func EffectiveActiveSource(state *models.SiteLoginState, effective time.Time) string

EffectiveActiveSource 返回判定活跃时间取自哪一列:last_access、api_last_login、 cookie_last_login、last_login、last_visit;没有依据时为 none。

func EffectiveLastActive added in v0.35.0

func EffectiveLastActive(state *models.SiteLoginState, _ time.Time) time.Time

EffectiveLastActive returns the most recent confirmed activity timestamp for a site.

Per research: site cleanup.php scripts predominantly check `last_access` (NexusPHP) / `last_action` (Unit3D) / `LastAccess` (Gazelle) / `lastModifiedDate` (mTorrent) — NOT `last_login`. So the probe-derived value prefers last_access-class timestamps and treats last_login-class timestamps (ApiLastLoginAt, CookieLastLoginAt) as supplementary signals, used only when last_access is missing:

  1. state.LastAccessAt
  2. max(state.ApiLastLoginAt, state.CookieLastLoginAt)
  3. state.LastLoginAt (legacy v1 field)

最近一次探测为 OK 时只用上面的结果(站点的数据就是事实,探测本身也刷新了它); 否则探测数据可能已过时,再与浏览器扩展上报的 LastVisitAt 取较新者, 避免探测坏掉后用户正常用浏览器访问,剩余天数却照样下降。

Types

type AttendanceMonitor

type AttendanceMonitor struct {
	Rand func(n int64) int64
	// contains filtered or unexported fields
}

AttendanceMonitor 每分钟检查一次开启了自动签到的站点:每站每天在时间窗内随机取一个时刻签到, 失败按 10、30 分钟退避重试最多 2 次,当天成功或已签后不再请求。结果写 SiteAttendanceLog, 当天所有站点都有结果后合成一条通知,经 MonitorNotifier 按通道静默时段投递。

func NewAttendanceMonitor

func NewAttendanceMonitor(cfg AttendanceMonitorConfig) *AttendanceMonitor

NewAttendanceMonitor 构造签到监控,不启动;调用 Start 开始调度。

func (*AttendanceMonitor) RunOnce

func (m *AttendanceMonitor) RunOnce(ctx context.Context)

RunOnce 处理一轮:为当天还没有记录的站点安排时刻,签到已到时刻的站点,并在都有结果后写当天的汇总通知。

func (*AttendanceMonitor) SignAll

SignAll 对所有开启了自动签到、当天还没有结果的站点立即签到一次,返回这些站点当天的记录。

func (*AttendanceMonitor) SignNow

func (m *AttendanceMonitor) SignNow(ctx context.Context, siteName string) (*models.SiteAttendanceLog, error)

SignNow 立即签到一次(手动或 ChatOps),不要求站点开启了自动签到。 成功、今日已签或不支持时写入当天的最终结果;失败只记下错误,不占用自动重试的次数。

func (*AttendanceMonitor) Start

func (m *AttendanceMonitor) Start()

Start 启动调度循环;重复调用无效果。

func (*AttendanceMonitor) Stop

func (m *AttendanceMonitor) Stop()

Stop 停止调度循环并等它退出。

func (*AttendanceMonitor) Today

func (m *AttendanceMonitor) Today() string

Today 返回进程时区的当天日期(YYYY-MM-DD),签到记录按它分天。

type AttendanceMonitorConfig

type AttendanceMonitorConfig struct {
	DB     *gorm.DB
	Sites  AttendanceSites
	Window AttendanceWindowSource
	Locker ProbeLocker
	// Notifier 为空时不发当天的签到汇总。
	Notifier *MonitorNotifier
	Clock    sitelogin.Clock
	Logger   *zap.SugaredLogger
	Tick     time.Duration
	// Location 是计算日期与时间窗的时区,默认进程时区(time.Local)。
	Location *time.Location
	// Rand 返回 [0, n) 的随机数,用于在时间窗内取时刻;测试可以注入确定的值。
	Rand func(n int64) int64
}

AttendanceMonitorConfig 是 AttendanceMonitor 的依赖。

type AttendanceSites

type AttendanceSites interface {
	AttendanceSite(siteName string) (v2.AttendanceCapable, bool)
}

AttendanceSites 按站点名取能签到的站点实例;生产环境取 UserInfoService 里注册的共享实例,与搜索、探测共用限速器。

type AttendanceSitesFunc

type AttendanceSitesFunc func(siteName string) (v2.AttendanceCapable, bool)

AttendanceSitesFunc 把函数适配为 AttendanceSites。

func (AttendanceSitesFunc) AttendanceSite

func (f AttendanceSitesFunc) AttendanceSite(siteName string) (v2.AttendanceCapable, bool)

type AttendanceWindowSource

type AttendanceWindowSource interface {
	AttendanceWindow() (string, string, error)
}

AttendanceWindowSource 返回签到时间窗(HH:MM,进程时区),即 core.ConfigStore.AttendanceWindow。

type CleanupMonitor added in v0.14.0

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

func NewCleanupMonitor added in v0.14.0

func NewCleanupMonitor(db *gorm.DB, downloaderMgr *downloader.DownloaderManager) *CleanupMonitor

func (*CleanupMonitor) RunManual added in v0.14.0

func (c *CleanupMonitor) RunManual() (int, error)

func (*CleanupMonitor) Start added in v0.14.0

func (c *CleanupMonitor) Start() error

func (*CleanupMonitor) Stop added in v0.14.0

func (c *CleanupMonitor) Stop()

type CredentialDecryptor added in v0.35.0

type CredentialDecryptor interface {
	Decrypt(setting models.SiteSetting) (cookie string, err error)
}

CredentialDecryptor returns a usable cookie/api-key for a site. Real implementations decrypt SiteSetting.CookieEncrypted via core.ConfigStore; tests inject deterministic values.

type CronExpr added in v0.35.0

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

CronExpr is a tiny 5-field cron evaluator (minute hour dom month dow) covering the patterns used by LoginReminderMonitor:

  • Numeric value: "10", "22"
  • Comma list: "10,22"
  • Wildcard: "*"
  • Step: "*/5", "*/15"
  • Range: "1-5"

Day-of-week uses 0-6 with 0=Sunday (the standard cron convention). This is intentionally NOT a full cron implementation — it is purpose-built for reminder schedules and rejects unsupported syntax with a parse error so misconfigurations fail loud at config time, not silently at midnight.

func ParseCron added in v0.35.0

func ParseCron(spec string) (*CronExpr, error)

ParseCron parses a 5-field cron expression like "0 10,22 * * *".

func (*CronExpr) Match added in v0.35.0

func (c *CronExpr) Match(t time.Time) bool

Match reports whether the given time falls exactly on a cron tick (minute granularity). It does NOT consider seconds.

func (*CronExpr) WindowStart added in v0.35.0

func (c *CronExpr) WindowStart(t time.Time) time.Time

WindowStart returns the most recent cron tick at or before t. The boundary is used by reminder dedup: two events that map to the same WindowStart are considered the same window and at most one reminder fires per window.

type FallbackProvider

type FallbackProvider interface {
	FallbackFor(ctx context.Context, setting models.SiteSetting, def *v2.SiteDefinition) sitelogin.Transport
}

FallbackProvider 返回本次探测可用的后备通道(CloakBrowser)。每次探测前调用一次,实现方每次从库里读配置, 改配置不需要重启;配置不全、架构不支持、缺 Cookie 或缺身份信息时返回 nil,探测只用主通道。 只有主通道被拦截、网络错误或限流时才会真正用到它(见 sitelogin.ProbeWithFallback)。

type FreeEndMonitor added in v0.3.0

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

func NewFreeEndMonitor added in v0.3.0

func NewFreeEndMonitor(db *gorm.DB, downloaderMgr *downloader.DownloaderManager) *FreeEndMonitor

func (*FreeEndMonitor) CancelTorrent added in v0.3.0

func (m *FreeEndMonitor) CancelTorrent(torrentID uint)

func (*FreeEndMonitor) ScheduleTorrent added in v0.3.0

func (m *FreeEndMonitor) ScheduleTorrent(torrent models.TorrentInfo)

func (*FreeEndMonitor) Start added in v0.3.0

func (m *FreeEndMonitor) Start() error

func (*FreeEndMonitor) Stop added in v0.3.0

func (m *FreeEndMonitor) Stop()

func (*FreeEndMonitor) TestHandleFreeEndedTorrent added in v0.3.0

func (m *FreeEndMonitor) TestHandleFreeEndedTorrent(torrent models.TorrentInfo)

TestHandleFreeEndedTorrent 暴露给测试/调试命令使用

type JobStatus added in v0.31.0

type JobStatus struct {
	SiteName  string
	RSSName   string
	Running   bool
	StartedAt time.Time
}

type LoginReminderConfig added in v0.35.0

type LoginReminderConfig struct {
	DB *gorm.DB
	// Notifier 为空时只记录提醒决策,不投递(没有可用的通知服务)。
	Notifier *MonitorNotifier
	// UserInfo 非空时探测经 UserInfoService.FetchAndSave 进行:用与搜索共用的站点实例和限速器,
	// 成功时顺带刷新用户统计,也不再调用 Resolver。为空(仓库初始化失败)时退回 Resolver 新建实例。
	UserInfo sitelogin.UserInfoFetcher
	// Fallback 为空时不用后备通道。
	Fallback     FallbackProvider
	Resolver     SiteResolver
	Decryptor    CredentialDecryptor
	Clock        sitelogin.Clock
	Logger       *zap.SugaredLogger
	ProbeEvery   time.Duration
	ProbeTick    time.Duration
	ReminderTick time.Duration
	// DefinitionLookup 判断站点是否有内置定义,默认查 v2.GetDefinitionRegistry()。
	DefinitionLookup func(siteName string) (*v2.SiteDefinition, bool)
}

LoginReminderConfig holds the dependencies needed to construct a LoginReminderMonitor.

type LoginReminderMonitor added in v0.35.0

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

LoginReminderMonitor runs two cooperating loops:

  1. probe loop(每分钟检查一次):逐个探测到期的 auto 模式站点。到期条件是 NextProbeAt 已到,或 ProbeRequestedAt 晚于 LastProbeStartedAt。下一次探测 时间按结果退避(见 nextProbeDelay),首轮按每站固定抖动分散,重启不补探。

  2. reminder loop(每分钟):计算封号提醒等级,并判断探测失败与恢复提醒。 所有通知只写 MonitorNotificationLog,由 MonitorNotifier 按通道处理静默时段、 经 live 通道发送并重试;监控自己不创建通道实例。

SiteLoginState 的每一列只有一个写者,全部按列 Updates,不整行 Save:

探测(持有单站锁):last_probe_at、last_probe_started_at、last_probe_status、
  last_probe_error、consecutive_probe_failures、first_failure_at、last_success_at、
  next_probe_at、probe_jitter_seconds、last_access_at、last_login_at、
  api_last_login_at、cookie_last_login_at、last_consistency_check、access_stale_since
提醒循环:last_reminder_tier、last_reminder_sent_at、last_failure_notified_at
配置接口:ban_threshold_days、remind_before_days、reminder_cron、
  notification_channel_ids、probe_mode
访问上报:last_visit_at
探测请求(RequestProbe):probe_requested_at

The monitor never issues raw HTTP itself; all site I/O passes through the site/v2 driver layer (which inherits the project's circuit breaker and rate limiter).

func NewLoginReminderMonitor added in v0.35.0

func NewLoginReminderMonitor(cfg LoginReminderConfig) *LoginReminderMonitor

NewLoginReminderMonitor builds a LoginReminderMonitor. It does not start the loops; call Start to begin processing.

func (*LoginReminderMonitor) Notifier

func (m *LoginReminderMonitor) Notifier() *MonitorNotifier

Notifier 返回监控使用的通知投递器(可能为 nil)。

func (*LoginReminderMonitor) RequestProbe

func (m *LoginReminderMonitor) RequestProbe(siteName string) error

RequestProbe 记录一次探测请求:auto 模式下探测循环会在一分钟内探测该站,不在调用方的请求里同步探测。 用监控自己的时钟写 probe_requested_at,与 last_probe_started_at 可比。凭证与站点配置入口 按「写库 → 刷新站点注册 → RequestProbe」调用,所以请求早于某次探测开始时,那次探测一定读到新配置; 晚于开始时,该站在那次探测之后仍然到期。

func (*LoginReminderMonitor) RunDueProbes

func (m *LoginReminderMonitor) RunDueProbes(ctx context.Context)

RunDueProbes 逐个探测到期的 auto 模式站点。NextProbeAt 为空(升级后的老数据、新建的行) 时只安排首轮时间「当前时间 + 固定抖动」,不立即探测,除非有人请求过探测。

func (*LoginReminderMonitor) RunProbeOnce added in v0.35.0

func (m *LoginReminderMonitor) RunProbeOnce(ctx context.Context)

RunProbeOnce probes every enabled site whose mode allows cron probing, regardless of NextProbeAt. Exported so tests can drive the probe phase directly with a fake clock. Sites whose probe slot is held by another trigger source are skipped — R23 shared single-flight.

func (*LoginReminderMonitor) RunProbeOnceForSite added in v0.35.0

func (m *LoginReminderMonitor) RunProbeOnceForSite(ctx context.Context, siteName string) bool

RunProbeOnceForSite probes a single site by name. Used for manual endpoint triggering (manualTrigger=true), bypassing mode restrictions. Acquires the shared probe lock; returns false if another caller already holds it.

func (*LoginReminderMonitor) RunProbeOnceForSiteLocked added in v0.35.0

func (m *LoginReminderMonitor) RunProbeOnceForSiteLocked(ctx context.Context, siteName string)

RunProbeOnceForSiteLocked runs the probe assuming the caller already holds the per-site probe lock (via TryAcquireProbeLock). The web handler uses this split so the HTTP layer can shape its 409 response from TryAcquireProbeLock before dispatching the actual probe work.

func (*LoginReminderMonitor) RunReminderOnce added in v0.35.0

func (m *LoginReminderMonitor) RunReminderOnce(ctx context.Context)

RunReminderOnce iterates enabled sites, computes each site's tier, fires reminders that are due, and decides probe failure / recovery notices. Exported for testability.

func (*LoginReminderMonitor) SendTestReminder added in v0.35.0

func (m *LoginReminderMonitor) SendTestReminder(ctx context.Context, siteName string) error

SendTestReminder immediately sends a test login-reminder notification for one site.

func (*LoginReminderMonitor) Start added in v0.35.0

func (m *LoginReminderMonitor) Start()

Start launches the probe and reminder loops and the notification delivery loop. Calling Start twice is a no-op.

func (*LoginReminderMonitor) Stop added in v0.35.0

func (m *LoginReminderMonitor) Stop()

Stop signals the loops to exit and waits for them to drain.

func (*LoginReminderMonitor) TryAcquireProbeLock added in v0.35.0

func (m *LoginReminderMonitor) TryAcquireProbeLock(siteName string) (release func(), ok bool)

TryAcquireProbeLock attempts to acquire the per-site probe mutex without blocking. Returns (release, true) on success — caller MUST invoke release() in defer to free the slot. Returns (nil, false) if another caller (cron, REST, or extension) already holds the mutex; the caller should surface a 409-style "probe in progress" response. R23: this single map is the shared single-flight registry across all probe trigger sources.

type Manager

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

func NewManager

func NewManager() *Manager

func (*Manager) GetAttendanceMonitor

func (m *Manager) GetAttendanceMonitor() *AttendanceMonitor

GetAttendanceMonitor 返回每日签到监控,没有接线时为 nil。

func (*Manager) GetDownloaderManager added in v0.2.0

func (m *Manager) GetDownloaderManager() *downloader.DownloaderManager

GetDownloaderManager 获取下载器管理器

func (*Manager) GetFreeEndMonitor added in v0.3.0

func (m *Manager) GetFreeEndMonitor() *FreeEndMonitor

GetFreeEndMonitor 获取免费结束监控器

func (*Manager) GetLoginReminderMonitor added in v0.35.0

func (m *Manager) GetLoginReminderMonitor() *LoginReminderMonitor

GetLoginReminderMonitor returns the registered monitor, or nil if not yet wired. Used by web handlers that want to trigger ad-hoc probes.

func (*Manager) InitFreeEndMonitor added in v0.3.0

func (m *Manager) InitFreeEndMonitor()

func (*Manager) LastVersion

func (m *Manager) LastVersion() int64

func (*Manager) ListJobs added in v0.31.0

func (m *Manager) ListJobs() []JobStatus

func (*Manager) Reload

func (m *Manager) Reload(cfg *models.Config)

func (*Manager) SetAttendanceMonitor

func (m *Manager) SetAttendanceMonitor(mon *AttendanceMonitor)

SetAttendanceMonitor 登记每日签到监控;替换旧实例时先停掉旧的。

func (*Manager) SetLoginReminderMonitor added in v0.35.0

func (m *Manager) SetLoginReminderMonitor(mon *LoginReminderMonitor)

SetLoginReminderMonitor wires a fully-constructed LoginReminderMonitor into the manager. It is intended to be called by the web layer after the monitor has been built with a SiteResolver that knows how to produce v2.Site instances. Calling this twice replaces and stops the previous instance. Pass nil to detach without stopping.

func (*Manager) Start

func (m *Manager) Start(site models.SiteGroup, r models.RSSConfig, runner func(ctx context.Context))

func (*Manager) StartAll

func (m *Manager) StartAll(cfg *models.Config)

StartAll 按配置启动所有任务(不做停止),并记下用户要求运行任务。

func (*Manager) Stop

func (m *Manager) Stop(site models.SiteGroup, rssName string)

func (*Manager) StopAll

func (m *Manager) StopAll()

StopAll 是进程退出前的最终关闭:取消所有任务并等待结束,停掉全部监控器和配置事件订阅。 之后不能再用 StartAll 恢复;调度器里的「停止所有任务」用 StopJobs。

func (*Manager) StopJobs

func (m *Manager) StopJobs()

StopJobs 停止全部 RSS 任务(调度器里的「停止所有任务」)。免费到期、自动删种、竞争度、 登录提醒和签到监控继续运行,配置热重载也照常;之后的配置变更不会把任务重新拉起,直到 StartAll。

type MonitorNotifier

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

MonitorNotifier 负责后台监控通知的入队与投递,是这些通知唯一的重试者。

func NewMonitorNotifier

func NewMonitorNotifier(db *gorm.DB, sender MonitorSender, clock sitelogin.Clock, logger *zap.SugaredLogger) *MonitorNotifier

NewMonitorNotifier 构造投递器。sender 为 nil 时不写日志行(没有可用的通知服务)。

func (*MonitorNotifier) DeliverDue

func (n *MonitorNotifier) DeliverDue(ctx context.Context) int

DeliverDue 投递所有到期的 pending 行,返回成功发送的条数。

func (*MonitorNotifier) DeliverNow

func (n *MonitorNotifier) DeliverNow(ctx context.Context, e MonitorNotifyEntry) error

DeliverNow 立即投递某个决策的全部 pending 行(测试提醒用),返回首个失败的错误。

func (*MonitorNotifier) Enabled

func (n *MonitorNotifier) Enabled() bool

Enabled 报告投递器是否可用(有数据库也有发送方)。

func (*MonitorNotifier) Enqueue

Enqueue 按目标通道各写一行。通道此刻处于自己的静默时段时,该行顺延到静默结束。 返回新写入的行数;已存在的行(同一决策重做)不计入。

func (*MonitorNotifier) Start

func (n *MonitorNotifier) Start()

Start 启动每分钟一次的投递循环;重复调用无副作用。

func (*MonitorNotifier) Stop

func (n *MonitorNotifier) Stop()

Stop 停止投递循环并等待当前一轮结束。

type MonitorNotifyEntry

type MonitorNotifyEntry struct {
	Source   string
	Subject  string
	Kind     string
	EventKey string
	Title    string
	Text     string
	// ConfIDs 为空时发给决策当时所有启用的通道。
	ConfIDs []uint
	// BypassQuiet 为 true 时不受通道静默时段限制(封号前最后一天、测试提醒)。
	BypassQuiet bool
}

MonitorNotifyEntry 是一次「决定发送」。同一个 (Source, Subject, Kind, EventKey) 重复写入不会重复发送。

type MonitorSender

type MonitorSender interface {
	Send(ctx context.Context, confID uint, title, text string) error
}

MonitorSender 经 live 通道同步发送一条通知到指定通道,失败或超时直接返回错误,不写 outbox。

生产实现包装 app.NotificationService.PushSync(scheduler 不能依赖 internal/app,后者依赖 scheduler)。 不能换成 Push:Push 在 live 发送失败后转写 outbox 并返回 nil,而 outbox 用 registry.Make 新建通道实例, 发不了 QQ / Telegram 这类有状态通道,日志行也会被误记为已送达。

type MonitorSenderFunc

type MonitorSenderFunc func(ctx context.Context, confID uint, title, text string) error

MonitorSenderFunc 让普通函数实现 MonitorSender。

func (MonitorSenderFunc) Send

func (f MonitorSenderFunc) Send(ctx context.Context, confID uint, title, text string) error

type PeerRatioMonitor added in v0.23.0

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

func NewPeerRatioMonitor added in v0.23.0

func NewPeerRatioMonitor(db *gorm.DB, downloaderMgr *downloader.DownloaderManager) *PeerRatioMonitor

func (*PeerRatioMonitor) Start added in v0.23.0

func (p *PeerRatioMonitor) Start() error

func (*PeerRatioMonitor) Stop added in v0.23.0

func (p *PeerRatioMonitor) Stop()

type ProbeLocker

type ProbeLocker interface {
	TryAcquireProbeLock(siteName string) (release func(), ok bool)
}

ProbeLocker 是登录探测与签到共用的单站单飞锁,即 LoginReminderMonitor.TryAcquireProbeLock。

type SiteResolver added in v0.35.0

type SiteResolver interface {
	Resolve(setting models.SiteSetting) (*v2.SiteDefinition, v2.Site, error)
}

SiteResolver wires a SiteSetting row into a v2.Site instance plus its SiteDefinition. It is injected so that tests can substitute fake sites without touching the global site registry or HTTP layer.

Jump to

Keyboard shortcuts

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