transcode

package
v4.2.8 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: AGPL-3.0 Imports: 19 Imported by: 0

Documentation

Overview

Package transcode chunk_manager.go:智能分段转码调度器

设计目标:

  1. 把视频按时间切成多个 chunk(默认每 60 秒一段),每个 chunk 独立用 ffmpeg 转码
  2. 用户拖动到任意位置时,按需启动对应 chunk 的 ffmpeg,不再线性等待
  3. 控制单 Job 最多并发 N 个 chunk ffmpeg,超出时 LRU 淘汰最久未访问的 chunk
  4. 当前 chunk 接近末尾时自动预启动下一个 chunk,保证顺序播放无缝衔接
  5. chunk 空闲超过阈值时 kill ffmpeg 释放 CPU,但保留已转出的切片文件

与 LocalRunner 的关系:

  • LocalRunner.runJob 不再直接启动一个完整的 ffmpeg,而是创建 ChunkSession 并阻塞等待
  • ChunkManager 是 ChunkSession 的"大脑",负责调度
  • TCSegment 收到切片请求时,调用 ChunkManager.EnsureChunkRunningForSeg(seq) 触发按需调度

Package transcode 实现 OpenList 的 FFmpeg 云端/本地转码功能。 设计目标:

  1. 总开关默认关,开启后按文件大小、源码率、源编码、文件后缀过滤决定是否转码。
  2. 协议自研,纯 HTTP/JSON,可挂接本地内置 Worker 或远程 Worker 节点池。
  3. 切片流式回吐,支持边转边播。

Index

Constants

View Source
const (
	// MaxPendingJobs 全局排队(未被 worker 领取)任务上限
	MaxPendingJobs = 200
	// MaxActiveJobsPerUser 单用户同时存在的未结束任务上限
	MaxActiveJobsPerUser = 3
)

提交配额。转码是 CPU/磁盘密集型操作,必须限制单用户并发与全局排队长度, 否则任何能访问播放接口的用户都能无限堆积任务(每个任务还会触发 30s 的 ffprobe)。

View Source
const (
	// MaxSegmentBytes 单个切片允许写入的最大字节数,防止 callback_token 持有者打满磁盘
	MaxSegmentBytes int64 = 32 << 20
)
View Source
const ProtocolVersion = "v1"

协议版本

Variables

View Source
var (

	// ErrInvalidProfile profile 名称不合法(可能是路径穿越尝试)
	ErrInvalidProfile = errors.New("invalid profile name")
	// ErrInvalidJobID job id 不合法
	ErrInvalidJobID = errors.New("invalid job id")
	// ErrInvalidSegment 切片序号越界
	ErrInvalidSegment = errors.New("invalid segment seq")
	// ErrSegmentTooLarge 切片超过大小上限
	ErrSegmentTooLarge = errors.New("segment too large")
)
View Source
var (
	// ErrQueueFull 全局队列已满
	ErrQueueFull = errors.New("transcode queue is full, try again later")
	// ErrUserQuota 单用户并发任务已达上限
	ErrUserQuota = errors.New("too many active transcode jobs for this user")
	// ErrJobNotFound 任务不存在或已被清理
	ErrJobNotFound = errors.New("transcode job not found")
)

Functions

func IsEnabled

func IsEnabled() bool

IsEnabled 总开关

func ProtocolWhitelistFor

func ProtocolWhitelistFor(source string) string

ProtocolWhitelistFor 根据输入地址返回应传给 ffmpeg/ffprobe 的 -protocol_whitelist 值。

func ValidProfileName

func ValidProfileName(profile string) bool

ValidProfileName 判断 profile 是否为安全的目录名(与 BuildProfile 产出的 source/1080p/720p 对齐)。

func ValidSourceInput

func ValidSourceInput(source string) bool

ValidSourceInput 判断输入是否可以安全交给 ffmpeg: 只接受绝对本地路径或 http(s) URL,拒绝 concat:/subfile:/data:/pipe: 等协议前缀, 也拒绝以 - 开头(会被当作 ffmpeg 选项)的值。

func VerifyWorkerSecret

func VerifyWorkerSecret(token string) bool

VerifyWorkerSecret 校验远程 worker 注册凭据

Types

type Cache

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

Cache 全局切片缓存

func NewCache

func NewCache(rootDir string, maxGB int64) *Cache

func (*Cache) BuildPlaylist

func (c *Cache) BuildPlaylist(jobID, profile string, segDur int, completed bool, baseURL string, totalDuration float64) string

BuildPlaylist 生成 HLS playlist (m3u8) 【重要】当 totalDuration > 0 时,会根据总时长预先生成完整切片列表(VOD 模式), 即使切片还未生成,URL 也会出现在 playlist 中。HLS.js 请求未生成切片时 会阻塞等待(见 TCSegment 的 WaitForSegment)。这样可以让 HLS.js 知道 视频总时长,避免:

  1. 时长显示错误(只显示已转码部分)
  2. 拖动跳跃(playlist 增长导致切片序号重新对齐)

func (*Cache) Cleanup

func (c *Cache) Cleanup(jobID string)

Cleanup 删除某个 job 的所有切片,并关闭所有阻塞的 waiter goroutine

func (*Cache) EnforceLRU

func (c *Cache) EnforceLRU() error

EnforceLRU 简易 LRU 容量控制:超过 maxBytes 时按目录修改时间从早到晚删除

func (*Cache) GetSegment

func (c *Cache) GetSegment(jobID, profile string, seq int) (*SegmentInfo, error)

GetSegment 读取一个切片(不等待)

func (*Cache) Init

func (c *Cache) Init() error

Init 创建根目录

func (*Cache) MasterPlaylist

func (c *Cache) MasterPlaylist(profiles []Profile, baseURL string) string

MasterPlaylist 多档位主 m3u8

func (*Cache) PutSegment

func (c *Cache) PutSegment(jobID, profile string, seq int, duration float64, body io.Reader, isFinal bool) (*SegmentInfo, error)

PutSegment 写入一个切片,并通知所有等待者

func (*Cache) SegmentCount

func (c *Cache) SegmentCount(jobID, profile string) int

SegmentCount 返回 (jobID, profile) 当前已生成的切片数量。 用于 TCPlaylist 在首次返回前等待至少若干切片就绪,避免 playlist 中只有 seg-0 导致 HLS.js 反复请求填充缓冲。

func (*Cache) WaitForSegment

func (c *Cache) WaitForSegment(jobID, profile string, seq int, timeout time.Duration) (*SegmentInfo, error)

WaitForSegment 等待某个 seq 切片就绪,timeout 后返回 nil

type Chunk

type Chunk struct {
	Index      int     // chunk 序号(0 开始)
	StartTime  float64 // 起始秒
	Duration   float64 // 持续时长(最后一个 chunk 可能不足 chunkDur)
	StartSeq   int     // 起始切片序号(包含)
	EndSeq     int     // 结束切片序号(不包含)
	State      ChunkState
	StartedAt  time.Time
	LastAccess time.Time
	Error      string
	// contains filtered or unexported fields
}

Chunk 表示视频中的一个时间段,对应一段连续的切片序号

type ChunkManager

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

ChunkManager 全局 chunk 管理器(一个 Manager 一个)

func NewChunkManager

func NewChunkManager(mgr *Manager) *ChunkManager

NewChunkManager 创建实例

func (*ChunkManager) CancelAllForJob

func (cm *ChunkManager) CancelAllForJob(jobID string)

CancelAllForJob 取消该 job 下所有 profile 的 session(CancelJob 时调用)

func (*ChunkManager) CancelSession

func (cm *ChunkManager) CancelSession(jobID, profile string)

CancelSession 外部取消(job 被 cancel 或 idle 超时)

func (*ChunkManager) EnsureChunkRunningForSeg

func (cm *ChunkManager) EnsureChunkRunningForSeg(jobID, profile string, seq int) int

EnsureChunkRunningForSeg 确保覆盖 seq 的 chunk 正在转码(由 TCSegment 触发) 返回所属 chunk index;如果 seq 越界返回 -1

func (*ChunkManager) StartSession

func (cm *ChunkManager) StartSession(job *Job, profile Profile, outDir string) (*ChunkSession, error)

StartSession 创建并启动一个 chunk session(由 LocalRunner.runJob 调用) 返回的 ChunkSession.allDoneCh 在所有切片都转完时关闭

func (*ChunkManager) Stop

func (cm *ChunkManager) Stop()

Stop 停止 ChunkManager(Manager.Stop 调用)

type ChunkSession

type ChunkSession struct {
	JobID   string
	Profile string
	Job     *Job
	ProfDef Profile

	// 静态参数
	TotalDuration float64 // 视频总时长
	SegDur        int     // 每片时长(秒)
	ChunkDur      int     // 每个 chunk 时长(秒)
	MaxConcurrent int     // 最大并发 chunk 数
	IdleSec       int     // chunk 空闲多久就 kill
	Prefetch      bool    // 是否启用预读

	// outDir / segPattern (供 ffmpeg 使用)
	OutDir string
	// contains filtered or unexported fields
}

ChunkSession 单个 (jobID, profile) 下的 chunk 调度上下文

func (*ChunkSession) WaitDone

func (s *ChunkSession) WaitDone() <-chan struct{}

WaitDone 阻塞等待所有 chunk 完成(LocalRunner.runJob 用)

type ChunkState

type ChunkState int

ChunkState chunk 当前状态

const (
	ChunkIdle    ChunkState = iota // 未启动
	ChunkRunning                   // ffmpeg 正在转码
	ChunkDone                      // ffmpeg 自然退出(chunk 内所有切片已转完)
	ChunkFailed                    // ffmpeg 异常失败
	ChunkKilled                    // 被 LRU 淘汰或空闲超时 kill
)

type ClaimRequest

type ClaimRequest struct {
	WorkerID string `json:"worker_id"`
	Slots    int    `json:"slots"`
	Wait     int    `json:"wait"` // 长轮询超时秒,0=不等
}

type ClaimResponse

type ClaimResponse struct {
	Jobs []*Job `json:"jobs"`
}

type DecideRequest

type DecideRequest struct {
	FileName string
	FileSize int64       // 字节
	Probe    SourceProbe // 可选;为空则只用大小+后缀判断
}

DecideRequest 决策器输入

type DecideResult

type DecideResult struct {
	NeedTranscode bool
	Reason        string
}

DecideResult 决策结果

func Decide

func Decide(r DecideRequest) DecideResult

Decide 根据全局设置判断是否需要走转码

type ErrorResponse

type ErrorResponse struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

type FinishRequest

type FinishRequest struct {
	JobID  string    `json:"job_id"`
	Status JobStatus `json:"status"`
	Error  string    `json:"error,omitempty"`
	Stats  JobStats  `json:"stats"`
}

type HWAccel

type HWAccel string

HWAccel 硬件加速类型

const (
	HWNone         HWAccel = "none"
	HWAuto         HWAccel = "auto"
	HWNVENC        HWAccel = "nvenc"        // NVIDIA
	HWQSV          HWAccel = "qsv"          // Intel QuickSync
	HWVAAPI        HWAccel = "vaapi"        // Linux VA-API
	HWAMF          HWAccel = "amf"          // AMD AMF
	HWVideoToolbox HWAccel = "videotoolbox" // macOS
)

type HeartbeatRequest

type HeartbeatRequest struct {
	WorkerID  string   `json:"worker_id"`
	Load      float64  `json:"load"`
	Running   []string `json:"running"`
	FreeSlots int      `json:"free_slots"`
}

type HeartbeatResponse

type HeartbeatResponse struct {
	OK     bool     `json:"ok"`
	Kick   bool     `json:"kick"`             // 服务端要求 worker 退出
	Cancel []string `json:"cancel,omitempty"` // 需要取消的 job ids
}

type Job

type Job struct {
	ID            string      `json:"id"`
	Path          string      `json:"path"`       // OpenList 文件路径
	SourceURL     string      `json:"source_url"` // 提供给 Worker 的签名 URL
	Probe         SourceProbe `json:"probe"`
	Profiles      []Profile   `json:"profiles"`
	Output        OutputSpec  `json:"output"`
	CallbackToken string      `json:"callback_token"` // Worker 回吐切片用(同时具备写权限,绝不外泄给播放端)
	// PlayToken 播放凭据:只用于 master/variant playlist 与切片下发,
	// 与 Worker 回写凭据(CallbackToken)分离,避免播放器拿到可写权限。
	// json:"-" 保证下发给 Worker 的任务描述里不会包含它。
	PlayToken string `json:"-"`
	Deadline  int64  `json:"deadline"` // unix 秒

	// OwnerID 发起转码者的配额键,仅服务端用于去重与配额,不下发给 Worker。
	// 用字符串而不是用户 ID:访客共用一个账号,需要按 "guest:<clientIP>" 拆分配额,
	// 否则单个匿名访客就能占满所有匿名转码配额。
	OwnerID string `json:"-"`

	// 运行时
	Status       JobStatus `json:"status"`
	WorkerID     string    `json:"worker_id"`
	CreatedAt    time.Time `json:"created_at"`
	StartedAt    time.Time `json:"started_at"`
	FinishedAt   time.Time `json:"finished_at"`
	LastAccessAt time.Time `json:"last_access_at"` // 播放端最后一次请求 segment/playlist 的时间
	Error        string    `json:"error,omitempty"`
	// contains filtered or unexported fields
}

Job 一次转码任务

func NewJob

func NewJob() *Job

NewJob 构造任务(自动初始化内部 channel)

func (*Job) GetLastAccess

func (j *Job) GetLastAccess() time.Time

GetLastAccess 获取最后访问时间(线程安全)

func (*Job) GetStatus

func (j *Job) GetStatus() JobStatus

GetStatus 获取当前状态(线程安全)

func (*Job) MarkReady

func (j *Job) MarkReady()

MarkReady 标记任务已可播放(首切片就绪)

func (*Job) Touch

func (j *Job) Touch()

Touch 更新最后访问时间(播放端每次请求 segment/playlist 时调用)

func (*Job) WaitReady

func (j *Job) WaitReady() <-chan struct{}

WaitReady 阻塞等待首切片就绪

type JobCache

type JobCache struct {
	JobID   string
	Profile string
	BaseDir string
	// contains filtered or unexported fields
}

JobCache 单个 Job 的切片缓存

type JobStats

type JobStats struct {
	Elapsed  float64 `json:"elapsed"`
	FPS      float64 `json:"fps"`
	Speed    float64 `json:"speed"`
	BytesOut int64   `json:"bytes_out"`
}

type JobStatus

type JobStatus string

JobStatus 转码任务状态

const (
	JobPending   JobStatus = "pending"  // 等待 Worker 领取
	JobRunning   JobStatus = "running"  // Worker 已领取并在转码
	JobReady     JobStatus = "ready"    // 至少首切片可用
	JobFinished  JobStatus = "finished" // 全部切片完成
	JobFailed    JobStatus = "failed"
	JobCancelled JobStatus = "cancelled"
)

type LocalRunner

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

LocalRunner 本地内置 worker,直接调用本机 ffmpeg

func NewLocalRunner

func NewLocalRunner(mgr *Manager) *LocalRunner

func (*LocalRunner) CancelJob

func (r *LocalRunner) CancelJob(jobID string) bool

CancelJob 外部取消指定 job 的 FFmpeg 进程(由 Scheduler.Cancel / 空闲超时调用)

func (*LocalRunner) RunningJobIDs

func (r *LocalRunner) RunningJobIDs() []string

RunningJobIDs 返回当前正在运行的所有 job ID 列表

func (*LocalRunner) Start

func (r *LocalRunner) Start() error

Start 注册本地 worker 并启动消费协程

func (*LocalRunner) Stop

func (r *LocalRunner) Stop()

type Manager

type Manager struct {
	Registry  *WorkerRegistry
	Scheduler *Scheduler
	Cache     *Cache
	Chunks    *ChunkManager // 智能 chunk 调度器(按需启动 ffmpeg,支持随机访问)
	// contains filtered or unexported fields
}

Manager 全局转码管理器单例

func Default

func Default() *Manager

Default 返回全局 Manager(懒加载)

func (*Manager) Start

func (m *Manager) Start()

Start 启动后台维护协程:心跳清理 + 缓存 LRU + 完成任务清理

func (*Manager) Stop

func (m *Manager) Stop()

Stop 停止 Manager

type OutputFormat

type OutputFormat string

OutputFormat 输出封装格式

const (
	FormatHLS  OutputFormat = "hls"
	FormatDASH OutputFormat = "dash"
	FormatMP4  OutputFormat = "mp4"
)

type OutputSpec

type OutputSpec struct {
	Format          OutputFormat `json:"format"`
	SegmentDuration int          `json:"segment_duration"` // 秒
}

OutputSpec 输出参数

func BuildOutputSpec

func BuildOutputSpec() OutputSpec

BuildOutputSpec 根据当前全局设置构建输出规格

type Profile

type Profile struct {
	Name         string `json:"name"`          // 例如 1080p
	VideoCodec   string `json:"video_codec"`   // h264 / hevc / av1
	VideoBitrate string `json:"video_bitrate"` // 例如 4000k
	Scale        string `json:"scale"`         // 例如 1920:-2
	AudioCodec   string `json:"audio_codec"`   // aac / mp3 / opus / copy
	AudioBitrate string `json:"audio_bitrate"` // 例如 160k
	HWAccel      string `json:"hwaccel"`       // worker 端如何选择硬件加速
}

Profile 输出转码档位

func BuildProfile

func BuildProfile() Profile

BuildProfile 根据当前全局设置构建默认 Profile

type RegisterRequest

type RegisterRequest struct {
	Name          string   `json:"name"`
	Version       string   `json:"version"`
	Capacity      int      `json:"capacity"`
	HWAccel       []string `json:"hwaccel"`
	CodecsDecode  []string `json:"codecs_decode"`
	CodecsEncode  []string `json:"codecs_encode"`
	MaxResolution string   `json:"max_resolution"`
	Tags          []string `json:"tags"`
	Endpoint      string   `json:"endpoint,omitempty"`
}

type RegisterResponse

type RegisterResponse struct {
	WorkerID          string `json:"worker_id"`
	HeartbeatInterval int    `json:"heartbeat_interval"`
	ClaimStrategy     string `json:"claim_strategy"` // pull
	ProtocolVersion   string `json:"protocol_version"`
}

type Scheduler

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

Scheduler 任务调度器:维护 pending 队列并支持 worker pull 领取

func NewScheduler

func NewScheduler(reg *WorkerRegistry) *Scheduler

func (*Scheduler) Cancel

func (s *Scheduler) Cancel(jobID string)

Cancel 主动取消任务(同时通知对应 worker 并 kill 本地 FFmpeg 进程)

func (*Scheduler) Capacity

func (s *Scheduler) Capacity(ownerID string) error

Capacity 只读预检:在启动 ffprobe 这类昂贵操作之前先看配额是否已满。

真正的配额判定仍由 SubmitLimited 在同一把锁内完成;这里的目的有两个:

  1. 不让用户先等一次最长 30s 的 ffprobe 才收到 429;
  2. 把「并发请求同时通过配额判定」这个窗口内的探测数量压下来。

func (*Scheduler) Claim

func (s *Scheduler) Claim(workerID string, slots int, wait time.Duration) []*Job

Claim 由 worker 调用领取任务(最多 slots 个);如果没有任务则等待 wait 秒

func (*Scheduler) FindReusable

func (s *Scheduler) FindReusable(ownerID string, path string) (*Job, bool)

FindReusable 查找同一用户对同一路径、仍在进行中的任务,用于去重复用。

func (*Scheduler) Finish

func (s *Scheduler) Finish(req *FinishRequest) error

Finish 由 worker 调用,标记任务完成/失败

func (*Scheduler) Get

func (s *Scheduler) Get(id string) (*Job, bool)

Get 通过 id 获取任务

func (*Scheduler) ListActiveJobs

func (s *Scheduler) ListActiveJobs() []*Job

ListActiveJobs 列出所有活跃任务(pending/running/ready),用于空闲超时检测

func (*Scheduler) ListJobs

func (s *Scheduler) ListJobs() []*Job

ListJobs 列出全部任务(仅用于调试/管理)

func (*Scheduler) PopCancellations

func (s *Scheduler) PopCancellations(workerID string) []string

PopCancellations 取出某个 worker 待处理的取消列表(心跳响应中下发)

func (*Scheduler) PurgeBefore

func (s *Scheduler) PurgeBefore(t time.Time) []string

PurgeBefore 删除 finishedAt 早于某时刻的任务,避免 jobs map 无限增长 返回被清理的 job ID 列表,调用方需联动清理 Cache

func (*Scheduler) Reactivate

func (s *Scheduler) Reactivate(jobID string) (*Job, error)

Reactivate 把一个已 Cancelled / Failed / Finished 的 job 重新激活回 Pending 状态, 让 worker 能再次领取并跑转码。用于"播放端重新请求时按需重启转码"的场景。

设计点:

  1. 复用原 jobID 和两套 token(播放用 PlayToken / Worker 回写用 CallbackToken), 前端持有的 master.m3u8 中的 URL 不需要变更
  2. 重置 readyCh / Status / WorkerID 等运行时字段,但保留 Path / SourceURL / Profiles / Probe
  3. 重新加入 pending 队列并唤醒等待的 worker

返回被激活的 Job;job 不存在返回 ErrJobNotFound,单用户配额不足返回 ErrUserQuota, 全局排队已满返回 ErrQueueFull。

func (*Scheduler) SetOnCancel

func (s *Scheduler) SetOnCancel(fn func(jobID string))

SetOnCancel 注入取消回调(由 Manager 在启动本地 worker 后调用)

func (*Scheduler) Submit

func (s *Scheduler) Submit(j *Job) *Job

Submit 提交一个任务并返回(带 ID + token)。不做配额限制,仅供内部流程(如重新激活)使用。

func (*Scheduler) SubmitLimited

func (s *Scheduler) SubmitLimited(j *Job) (*Job, bool, error)

SubmitLimited 带去重与配额的提交:

  1. 同一用户对同一路径已有进行中的任务时直接复用,不重复入队;
  2. 全局排队过长或用户任务过多时拒绝。

返回 (job, reused, err)。

type SegmentInfo

type SegmentInfo struct {
	Seq      int     `json:"seq"`
	Duration float64 `json:"duration"`
	Size     int64   `json:"size"`
	Path     string  `json:"-"` // 本地实际文件路径
}

SegmentInfo 单个切片元数据

type SourceProbe

type SourceProbe struct {
	Duration     float64 `json:"duration"`      // 秒
	Size         int64   `json:"size"`          // 字节
	VideoCodec   string  `json:"video_codec"`   // h264 / hevc / av1 / vp9 ...
	VideoBitrate int64   `json:"video_bitrate"` // bps
	Width        int     `json:"width"`
	Height       int     `json:"height"`
	AudioCodec   string  `json:"audio_codec"`
	AudioBitrate int64   `json:"audio_bitrate"`
}

SourceProbe 源文件探测信息(由 ffprobe 得出)

func ProbeSource

func ProbeSource(url string) (SourceProbe, error)

ProbeSource 调用 ffprobe 探测源文件

type Worker

type Worker struct {
	ID            string   `json:"id"`
	Name          string   `json:"name"`
	Version       string   `json:"version"`
	Capacity      int      `json:"capacity"`       // 最大并发任务数
	HWAccel       []string `json:"hwaccel"`        // 支持的硬件加速
	CodecsDecode  []string `json:"codecs_decode"`  // 可解码
	CodecsEncode  []string `json:"codecs_encode"`  // 可编码
	MaxResolution string   `json:"max_resolution"` // 最大分辨率
	Tags          []string `json:"tags"`
	Endpoint      string   `json:"endpoint,omitempty"` // 反向连接地址(可选)

	// 运行时
	Load         float64   `json:"load"`    // 0~1
	Running      []string  `json:"running"` // 当前 job_ids
	FreeSlots    int       `json:"free_slots"`
	LastSeen     time.Time `json:"last_seen"`
	RegisteredAt time.Time `json:"registered_at"`
	Local        bool      `json:"local"` // 是否本地内置 Worker
}

Worker 节点信息

type WorkerRegistry

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

WorkerRegistry 维护当前在线的 Worker 池

func NewWorkerRegistry

func NewWorkerRegistry() *WorkerRegistry

func (*WorkerRegistry) Get

func (r *WorkerRegistry) Get(id string) (*Worker, bool)

Get 获取 worker

func (*WorkerRegistry) HasAvailable

func (r *WorkerRegistry) HasAvailable() bool

HasAvailable 是否存在有空闲槽位的 worker

func (*WorkerRegistry) Heartbeat

func (r *WorkerRegistry) Heartbeat(req *HeartbeatRequest) (*Worker, bool)

Heartbeat 更新 worker 心跳信息,未注册返回 false

func (*WorkerRegistry) List

func (r *WorkerRegistry) List() []*Worker

List 列出所有 worker(拷贝)

func (*WorkerRegistry) Register

func (r *WorkerRegistry) Register(req *RegisterRequest, local bool) *Worker

Register 注册一个新的 worker,返回分配的 ID

func (*WorkerRegistry) Sweep

func (r *WorkerRegistry) Sweep() []string

Sweep 清理超时未心跳的 worker;返回被移除的 worker_id 列表

func (*WorkerRegistry) Unregister

func (r *WorkerRegistry) Unregister(id string)

Unregister 主动移除 worker

Jump to

Keyboard shortcuts

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