DNF90 服务端与启动器完整源码(含 GM 工具功能增强)

服务端(Go):
- GM 塞背包/带属性装备发放:在线角色推送 op14 增量物品行,背包实时刷新,无需回角色选择界面
- GM 改金币/改等级:去掉在线拒绝,落库后推送 op14 钱包/op37 等级状态,在线实时刷新
- 等级端点统一切换到新版 GMSetCharacterLevel(自带在线刷新)
- 无限/锁死疲劳模式 + 燃烧疲劳:每房间消耗 2 点、打怪与通关经验双倍
- 燃烧疲劳开关时给所有在线角色推送系统提示(op12 mode 0)
- 深渊史诗掉率:GM 全局倍率 + 城镇增益药剂窗口倍率,真实接入掉落结算

启动器(Python/JS):
- 标题栏自绘、窗口 1204x717、禁止拖拽改大小、仅最小化/关闭
- GM 工具:疲劳与燃烧、深渊史诗掉率、拍卖行上架(单一定价对齐)
- 拍卖行上架前端对齐服务端单一价格语义,修复 400 报错
This commit is contained in:
hanfuit committed 2026-11-04 14:31:55 +08:00
commit 645b64fe21
4388 files changed
+1405457

No files matched your search

@@ -0,0 +1,323 @@
package admincmdqueue
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"longheng.io/server/internal/platform/admincmd"
"longheng.io/server/internal/platform/eventlog"
)
const DefaultApprovalStream = "admin.approval"
const (
ApprovalEventSubmitted = "submitted"
ApprovalEventApproved = "approved"
ApprovalEventRejected = "rejected"
ApprovalEventExecuted = "executed"
approvalEventDecided = "decided"
)
var ErrApprovalJournalRequired = errors.New("admin approval journal eventlog is required")
type ApprovalJournalOptions struct {
Log *eventlog.Log
Stream string
Policy admincmd.ApprovalPolicy
Now func() time.Time
}
type ApprovalJournal struct {
log *eventlog.Log
stream string
policy admincmd.ApprovalPolicy
now func() time.Time
}
type ApprovalEvent struct {
Request admincmd.ApprovalRequest `json:"request"`
}
type ApprovalResult struct {
Request admincmd.ApprovalRequest `json:"request"`
Event eventlog.Event `json:"event"`
Duplicate bool `json:"duplicate,omitempty"`
}
func NewApprovalJournal(options ApprovalJournalOptions) (*ApprovalJournal, error) {
if options.Log == nil {
return nil, ErrApprovalJournalRequired
}
stream := strings.TrimSpace(options.Stream)
if stream == "" {
stream = DefaultApprovalStream
}
policy := options.Policy
if policy.CommandPolicy == (admincmd.Policy{}) {
policy = admincmd.DangerousApprovalPolicy()
}
now := options.Now
if now == nil {
now = time.Now
}
return &ApprovalJournal{log: options.Log, stream: stream, policy: policy, now: now}, nil
}
func (j *ApprovalJournal) Submit(ctx context.Context, command admincmd.Command) (ApprovalResult, error) {
if err := ctxErr(ctx); err != nil {
return ApprovalResult{}, err
}
if j == nil || j.log == nil {
return ApprovalResult{}, ErrApprovalJournalRequired
}
command = admincmd.Normalize(command)
if err := admincmd.Validate(command, j.policy.CommandPolicy); err != nil {
return ApprovalResult{}, err
}
id, err := admincmd.ApprovalID(command)
if err != nil {
return ApprovalResult{}, err
}
request := admincmd.ApprovalRequest{
ID: id,
Command: command,
Status: admincmd.ApprovalPending,
RequestedAt: j.now().UTC(),
}
event, duplicate, err := j.append(ctx, request, ApprovalEventSubmitted, approvalIdemKey(command.IdempotencyKey, ApprovalEventSubmitted))
if err != nil {
return ApprovalResult{}, err
}
got, err := decodeApprovalEvent(event)
if err != nil {
return ApprovalResult{}, err
}
if got.ID != request.ID {
return ApprovalResult{}, fmt.Errorf("%w: approval=%s", ErrIdempotencyConflict, got.ID)
}
return ApprovalResult{Request: got, Event: event, Duplicate: duplicate}, nil
}
func (j *ApprovalJournal) Approve(ctx context.Context, id string, decision admincmd.ApprovalDecision) (ApprovalResult, error) {
return j.decide(ctx, id, decision, admincmd.ApprovalApproved, ApprovalEventApproved)
}
func (j *ApprovalJournal) Reject(ctx context.Context, id string, decision admincmd.ApprovalDecision) (ApprovalResult, error) {
return j.decide(ctx, id, decision, admincmd.ApprovalRejected, ApprovalEventRejected)
}
func (j *ApprovalJournal) ExecuteApproved(ctx context.Context, id string) (admincmd.Receipt, ApprovalResult, error) {
if err := ctxErr(ctx); err != nil {
return admincmd.Receipt{}, ApprovalResult{}, err
}
request, ok, err := j.Latest(ctx, id)
if err != nil || !ok {
if err != nil {
return admincmd.Receipt{}, ApprovalResult{}, err
}
return admincmd.Receipt{}, ApprovalResult{}, admincmd.ErrApprovalNotFound
}
if request.Status == admincmd.ApprovalExecuted && request.Receipt != nil {
return *request.Receipt, ApprovalResult{Request: request}, nil
}
if request.Status != admincmd.ApprovalApproved {
return admincmd.Receipt{}, ApprovalResult{}, admincmd.ErrApprovalNotApproved
}
if err := admincmd.Validate(request.Command, admincmd.DangerousPolicy()); err != nil {
return admincmd.Receipt{}, ApprovalResult{}, err
}
receipt, err := admincmd.NewReceipt(request.Command, admincmd.ApprovalExecuted, j.now().UTC())
if err != nil {
return admincmd.Receipt{}, ApprovalResult{}, err
}
request.Status = admincmd.ApprovalExecuted
request.ExecutedAt = receipt.CreatedAt
request.Receipt = &receipt
event, duplicate, err := j.append(ctx, request, ApprovalEventExecuted, approvalIdemKey(request.ID, ApprovalEventExecuted))
if err != nil {
return admincmd.Receipt{}, ApprovalResult{}, err
}
got, err := decodeApprovalEvent(event)
if err != nil {
return admincmd.Receipt{}, ApprovalResult{}, err
}
if got.Receipt != nil {
receipt = *got.Receipt
}
return receipt, ApprovalResult{Request: got, Event: event, Duplicate: duplicate}, nil
}
func (j *ApprovalJournal) Latest(ctx context.Context, id string) (admincmd.ApprovalRequest, bool, error) {
if err := ctxErr(ctx); err != nil {
return admincmd.ApprovalRequest{}, false, err
}
if j == nil || j.log == nil {
return admincmd.ApprovalRequest{}, false, ErrApprovalJournalRequired
}
id = strings.TrimSpace(id)
if id == "" {
return admincmd.ApprovalRequest{}, false, nil
}
events, err := j.log.ListByStreamAggregate(ctx, j.stream, id, 1)
if err != nil {
return admincmd.ApprovalRequest{}, false, err
}
if len(events) == 0 {
return admincmd.ApprovalRequest{}, false, nil
}
request, err := decodeApprovalEvent(events[0])
if err != nil {
return admincmd.ApprovalRequest{}, false, err
}
return request, true, nil
}
func (j *ApprovalJournal) decide(ctx context.Context, id string, decision admincmd.ApprovalDecision, status string, eventType string) (ApprovalResult, error) {
if err := ctxErr(ctx); err != nil {
return ApprovalResult{}, err
}
request, ok, err := j.Latest(ctx, id)
if err != nil || !ok {
if err != nil {
return ApprovalResult{}, err
}
return ApprovalResult{}, admincmd.ErrApprovalNotFound
}
if request.Status != admincmd.ApprovalPending {
return ApprovalResult{}, admincmd.ErrApprovalNotPending
}
decision.Approver = strings.TrimSpace(decision.Approver)
decision.Reason = strings.TrimSpace(decision.Reason)
decision.Confirmation = strings.TrimSpace(decision.Confirmation)
if decision.Approver == "" {
return ApprovalResult{}, admincmd.ErrMissingActor
}
if j.policy.RequireDifferentApprover && strings.EqualFold(decision.Approver, request.Command.Actor) {
return ApprovalResult{}, admincmd.ErrApprovalSelfApprove
}
if status == admincmd.ApprovalApproved && j.policy.RequireConfirmation && decision.Confirmation != request.Command.Operation {
return ApprovalResult{}, fmt.Errorf("%w: expected %s", admincmd.ErrApprovalConfirmation, request.Command.Operation)
}
request.Status = status
request.Approver = decision.Approver
request.DecisionReason = decision.Reason
request.DecidedAt = j.now().UTC()
if status == admincmd.ApprovalApproved {
request.Command.Confirmation = decision.Confirmation
}
event, duplicate, err := j.appendDecision(ctx, request, eventType)
if err != nil {
return ApprovalResult{}, err
}
got, err := decodeApprovalEvent(event)
if err != nil {
return ApprovalResult{}, err
}
if got.Status != status {
return ApprovalResult{Request: got, Event: event, Duplicate: duplicate}, admincmd.ErrApprovalNotPending
}
return ApprovalResult{Request: got, Event: event, Duplicate: duplicate}, nil
}
func (j *ApprovalJournal) append(ctx context.Context, request admincmd.ApprovalRequest, eventType string, idempotencyKey string) (eventlog.Event, bool, error) {
return j.appendWithEventID(ctx, request, eventType, idempotencyKey, approvalEventID(request.ID, eventType))
}
func (j *ApprovalJournal) appendDecision(ctx context.Context, request admincmd.ApprovalRequest, eventType string) (eventlog.Event, bool, error) {
id := approvalEventID(request.ID, approvalEventDecided)
event, duplicate, err := j.appendWithEventID(ctx, request, eventType, approvalIdemKey(request.ID, approvalEventDecided), id)
if errors.Is(err, eventlog.ErrEventExists) || errors.Is(err, eventlog.ErrIdempotencyConflict) {
existing, ok, getErr := j.log.Get(ctx, id)
if getErr != nil {
return eventlog.Event{}, false, getErr
}
if ok {
return existing, true, nil
}
}
return event, duplicate, err
}
func (j *ApprovalJournal) appendWithEventID(ctx context.Context, request admincmd.ApprovalRequest, eventType string, idempotencyKey string, eventID string) (eventlog.Event, bool, error) {
idempotencyKey = strings.TrimSpace(idempotencyKey)
if idempotencyKey != "" {
if existing, ok, err := j.log.GetByIdempotencyKey(ctx, idempotencyKey); err != nil {
return eventlog.Event{}, false, err
} else if ok {
return existing, true, nil
}
}
payload, err := json.Marshal(ApprovalEvent{Request: request})
if err != nil {
return eventlog.Event{}, false, err
}
eventID = strings.TrimSpace(eventID)
if eventID == "" {
eventID = approvalEventID(request.ID, eventType)
}
event, err := j.log.Append(ctx, eventlog.Event{
ID: eventID,
Stream: j.stream,
Type: eventType,
AggregateID: request.ID,
IdempotencyKey: idempotencyKey,
Payload: payload,
Status: eventlog.StatusPublished,
Headers: map[string]string{
"admin_operation": request.Command.Operation,
"admin_actor": request.Command.Actor,
"admin_approval": request.ID,
"approval_status": request.Status,
},
})
return event, false, err
}
func decodeApprovalEvent(event eventlog.Event) (admincmd.ApprovalRequest, error) {
var envelope ApprovalEvent
if len(event.Payload) == 0 {
return admincmd.ApprovalRequest{}, ErrInvalidCommandEvent
}
if err := json.Unmarshal(event.Payload, &envelope); err != nil {
return admincmd.ApprovalRequest{}, fmt.Errorf("%w: %w", ErrInvalidCommandEvent, err)
}
envelope.Request.Command = admincmd.Normalize(envelope.Request.Command)
if envelope.Request.ID == "" || envelope.Request.Command.Operation == "" || envelope.Request.Status == "" {
return admincmd.ApprovalRequest{}, ErrInvalidCommandEvent
}
return envelope.Request, nil
}
func approvalEventID(approvalID string, eventType string) string {
return strings.Join([]string{"adminapproval", "event", "v1", encodeApprovalPart(approvalID), encodeApprovalPart(eventType)}, ":")
}
func approvalIdemKey(key string, eventType string) string {
return strings.Join([]string{"adminapproval", "v1", encodeApprovalPart(key), encodeApprovalPart(eventType)}, ":")
}
func encodeApprovalPart(value string) string {
value = strings.TrimSpace(value)
if value == "" {
return "_"
}
return base64.RawURLEncoding.EncodeToString([]byte(value))
}
func ctxErr(ctx context.Context) error {
if ctx == nil {
return nil
}
select {
case <-ctx.Done():
return ctx.Err()
default:
return nil
}
}
@@ -0,0 +1,295 @@
package admincmdqueue
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"longheng.io/server/internal/platform/admincmd"
"longheng.io/server/internal/platform/eventlog"
)
var (
ErrEventLogRequired = errors.New("admin command eventlog is required")
ErrIdempotencyConflict = errors.New("admin command idempotency key conflicts with an existing command")
ErrInvalidCommandEvent = errors.New("admin command event payload is invalid")
ErrCommandHandlerNeeded = errors.New("admin command handler is required")
)
const (
DefaultStream = "admin.command"
ReceiptStatusAccepted = "accepted"
ReceiptStatusProcessing = "processing"
ReceiptStatusSucceeded = "succeeded"
ReceiptStatusFailed = "failed"
ReceiptStatusDeadLetter = "dead_letter"
)
type ExecutorOptions struct {
Log *eventlog.Log
Stream string
Now func() time.Time
}
type Executor struct {
log *eventlog.Log
stream string
now func() time.Time
}
type SubmitResult struct {
Receipt admincmd.Receipt `json:"receipt"`
Event eventlog.Event `json:"event"`
Duplicate bool `json:"duplicate"`
}
type CommandEnvelope struct {
Command admincmd.Command `json:"command"`
Receipt admincmd.Receipt `json:"receipt"`
CommandHash string `json:"command_hash"`
}
type Handler interface {
ExecuteAdminCommand(context.Context, admincmd.Command) error
}
type HandlerFunc func(context.Context, admincmd.Command) error
func (fn HandlerFunc) ExecuteAdminCommand(ctx context.Context, command admincmd.Command) error {
if fn == nil {
return ErrCommandHandlerNeeded
}
return fn(ctx, command)
}
func NewExecutor(options ExecutorOptions) (*Executor, error) {
if options.Log == nil {
return nil, ErrEventLogRequired
}
stream := strings.TrimSpace(options.Stream)
if stream == "" {
stream = DefaultStream
}
now := options.Now
if now == nil {
now = time.Now
}
return &Executor{log: options.Log, stream: stream, now: now}, nil
}
func (e *Executor) Submit(ctx context.Context, command admincmd.Command, policy admincmd.Policy) (SubmitResult, error) {
if e == nil || e.log == nil {
return SubmitResult{}, ErrEventLogRequired
}
command = admincmd.Normalize(command)
if err := admincmd.Validate(command, policy); err != nil {
return SubmitResult{}, err
}
receipt, err := admincmd.NewReceipt(command, ReceiptStatusAccepted, e.now())
if err != nil {
return SubmitResult{}, err
}
commandHash, err := CommandHash(command)
if err != nil {
return SubmitResult{}, err
}
envelope := CommandEnvelope{
Command: command,
Receipt: receipt,
CommandHash: commandHash,
}
payload, err := json.Marshal(envelope)
if err != nil {
return SubmitResult{}, err
}
idempotencyKey := EventIdempotencyKey(command)
if idempotencyKey != "" {
existing, ok, err := e.log.GetByIdempotencyKey(ctx, idempotencyKey)
if err != nil {
return SubmitResult{}, err
}
if ok {
if err := ensureSameCommand(existing, envelope); err != nil {
return SubmitResult{}, err
}
return SubmitResult{Receipt: receiptForEvent(existing), Event: existing, Duplicate: true}, nil
}
}
event, err := e.log.Append(ctx, eventlog.Event{
ID: receipt.ID,
Stream: e.stream,
Type: "accepted",
AggregateID: command.Target,
IdempotencyKey: idempotencyKey,
Payload: payload,
Headers: map[string]string{
"admin_operation": command.Operation,
"admin_scope": command.Scope,
"admin_actor": command.Actor,
"admin_target": command.Target,
"admin_receipt": receipt.ID,
},
})
if err != nil {
return SubmitResult{}, err
}
if err := ensureSameCommand(event, envelope); err != nil {
return SubmitResult{}, err
}
duplicate := event.ID != receipt.ID
receipt = receiptForEvent(event)
return SubmitResult{Receipt: receipt, Event: event, Duplicate: duplicate}, nil
}
func (e *Executor) Receipt(ctx context.Context, id string) (admincmd.Receipt, bool, error) {
if e == nil || e.log == nil {
return admincmd.Receipt{}, false, ErrEventLogRequired
}
event, ok, err := e.log.Get(ctx, id)
if err != nil || !ok {
return admincmd.Receipt{}, ok, err
}
return receiptForEvent(event), true, nil
}
func (e *Executor) ReceiptByIdempotencyKey(ctx context.Context, key string) (admincmd.Receipt, bool, error) {
if e == nil || e.log == nil {
return admincmd.Receipt{}, false, ErrEventLogRequired
}
key = strings.TrimSpace(key)
if key == "" {
return admincmd.Receipt{}, false, nil
}
event, ok, err := e.log.GetByIdempotencyKey(ctx, "admincmd:"+key)
if err != nil || !ok {
return admincmd.Receipt{}, ok, err
}
return receiptForEvent(event), true, nil
}
func (e *Executor) PublishPending(ctx context.Context, handler Handler, options eventlog.PublishOptions) (eventlog.PublishStats, error) {
if e == nil || e.log == nil {
return eventlog.PublishStats{}, ErrEventLogRequired
}
if handler == nil {
return eventlog.PublishStats{}, ErrCommandHandlerNeeded
}
return e.log.PublishPending(ctx, commandPublisher{handler: handler}, options)
}
func (e *Executor) MarkSucceeded(ctx context.Context, receiptID string) (admincmd.Receipt, error) {
if e == nil || e.log == nil {
return admincmd.Receipt{}, ErrEventLogRequired
}
event, err := e.log.MarkPublished(ctx, receiptID)
if err != nil {
return admincmd.Receipt{}, err
}
return receiptForEvent(event), nil
}
func (e *Executor) MarkFailed(ctx context.Context, receiptID string, message string, nextAttempt time.Time) (admincmd.Receipt, error) {
if e == nil || e.log == nil {
return admincmd.Receipt{}, ErrEventLogRequired
}
event, err := e.log.MarkFailed(ctx, receiptID, message, nextAttempt)
if err != nil {
return admincmd.Receipt{}, err
}
return receiptForEvent(event), nil
}
func EventIdempotencyKey(command admincmd.Command) string {
key := strings.TrimSpace(command.IdempotencyKey)
if key == "" {
return ""
}
return "admincmd:" + key
}
func CommandHash(command admincmd.Command) (string, error) {
command = admincmd.Normalize(command)
payload, err := json.Marshal(command)
if err != nil {
return "", err
}
sum := sha256.Sum256(payload)
return hex.EncodeToString(sum[:]), nil
}
type commandPublisher struct {
handler Handler
}
func (p commandPublisher) Publish(ctx context.Context, event eventlog.Event) error {
if p.handler == nil {
return ErrCommandHandlerNeeded
}
envelope, err := decodeEnvelope(event)
if err != nil {
return err
}
return p.handler.ExecuteAdminCommand(ctx, envelope.Command)
}
func ensureSameCommand(event eventlog.Event, want CommandEnvelope) error {
got, err := decodeEnvelope(event)
if err != nil {
return err
}
if got.CommandHash != "" && want.CommandHash != "" && got.CommandHash != want.CommandHash {
return fmt.Errorf("%w: receipt=%s", ErrIdempotencyConflict, got.Receipt.ID)
}
if got.Receipt.ID != "" && want.Receipt.ID != "" && got.Receipt.ID != want.Receipt.ID {
return fmt.Errorf("%w: receipt=%s", ErrIdempotencyConflict, got.Receipt.ID)
}
return nil
}
func decodeEnvelope(event eventlog.Event) (CommandEnvelope, error) {
var envelope CommandEnvelope
if len(event.Payload) == 0 {
return envelope, ErrInvalidCommandEvent
}
if err := json.Unmarshal(event.Payload, &envelope); err != nil {
return envelope, fmt.Errorf("%w: %w", ErrInvalidCommandEvent, err)
}
envelope.Command = admincmd.Normalize(envelope.Command)
if envelope.Receipt.ID == "" || envelope.Command.Operation == "" {
return envelope, ErrInvalidCommandEvent
}
return envelope, nil
}
func receiptForEvent(event eventlog.Event) admincmd.Receipt {
envelope, err := decodeEnvelope(event)
if err != nil {
return admincmd.Receipt{ID: event.ID, Status: ReceiptStatusFailed, CreatedAt: event.CreatedAt}
}
receipt := envelope.Receipt
receipt.Status = receiptStatusEvent(event.Status)
return receipt
}
func receiptStatusEvent(status string) string {
switch status {
case eventlog.StatusPending:
return ReceiptStatusAccepted
case eventlog.StatusProcessing:
return ReceiptStatusProcessing
case eventlog.StatusPublished:
return ReceiptStatusSucceeded
case eventlog.StatusFailed:
return ReceiptStatusFailed
case eventlog.StatusDeadLetter:
return ReceiptStatusDeadLetter
default:
return strings.TrimSpace(status)
}
}
@@ -0,0 +1,213 @@
package admincmdqueue
import (
"context"
"errors"
"fmt"
"log/slog"
"sync"
"time"
"longheng.io/server/internal/platform/eventlog"
)
var (
ErrWorkerConfig = errors.New("admin command worker config is invalid")
ErrWorkerStopping = errors.New("admin command worker is stopping")
)
type WorkerOptions struct {
Name string
Executor *Executor
Handler Handler
Interval time.Duration
Limit int
RetryDelay time.Duration
ClaimTimeout time.Duration
MaxAttempts int
Logger *slog.Logger
}
type Worker struct {
name string
executor *Executor
handler Handler
interval time.Duration
limit int
retryDelay time.Duration
claimTimeout time.Duration
maxAttempts int
logger *slog.Logger
mu sync.Mutex
running bool
stopping bool
cancel context.CancelFunc
done chan struct{}
stopped chan struct{}
}
func NewWorker(options WorkerOptions) (*Worker, error) {
name := options.Name
if name == "" {
name = "admin-command-worker"
}
if options.Executor == nil {
return nil, fmt.Errorf("%w: executor is required", ErrWorkerConfig)
}
if options.Handler == nil {
return nil, fmt.Errorf("%w: handler is required", ErrWorkerConfig)
}
interval := options.Interval
if interval <= 0 {
interval = time.Second
}
retryDelay := options.RetryDelay
if retryDelay <= 0 {
retryDelay = time.Second
}
return &Worker{
name: name,
executor: options.Executor,
handler: options.Handler,
interval: interval,
limit: options.Limit,
retryDelay: retryDelay,
claimTimeout: options.ClaimTimeout,
maxAttempts: options.MaxAttempts,
logger: options.Logger,
}, nil
}
func (w *Worker) Name() string {
if w == nil || w.name == "" {
return "admin-command-worker"
}
return w.name
}
func (w *Worker) Start(ctx context.Context) error {
if ctx != nil {
if err := ctx.Err(); err != nil {
return err
}
}
if w == nil || w.executor == nil || w.handler == nil {
return ErrWorkerConfig
}
w.mu.Lock()
if w.running {
w.mu.Unlock()
return nil
}
if w.stopping {
w.mu.Unlock()
return ErrWorkerStopping
}
runCtx, cancel := context.WithCancel(context.Background())
w.done = make(chan struct{})
w.stopped = make(chan struct{})
w.running = true
w.cancel = cancel
done := w.done
stopped := w.stopped
w.mu.Unlock()
go w.run(runCtx, done, stopped)
return nil
}
func (w *Worker) Stop(ctx context.Context) error {
if ctx == nil {
ctx = context.Background()
}
if w == nil {
return nil
}
w.mu.Lock()
if !w.running && !w.stopping {
w.mu.Unlock()
return nil
}
done := w.done
stopped := w.stopped
cancel := w.cancel
shouldSignal := w.running
if shouldSignal {
w.cancel = nil
w.running = false
w.stopping = true
}
w.mu.Unlock()
if shouldSignal && done != nil {
close(done)
}
if shouldSignal && cancel != nil {
cancel()
}
if stopped == nil {
return nil
}
select {
case <-stopped:
w.clearStopped(stopped)
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (w *Worker) RunOnce(ctx context.Context) (eventlog.PublishStats, error) {
if ctx == nil {
ctx = context.Background()
}
if w == nil || w.executor == nil || w.handler == nil {
return eventlog.PublishStats{}, ErrWorkerConfig
}
stats, err := w.executor.PublishPending(ctx, w.handler, eventlog.PublishOptions{
Limit: w.limit,
RetryDelay: w.retryDelay,
ClaimTimeout: w.claimTimeout,
MaxAttempts: w.maxAttempts,
})
if err != nil && w.logger != nil {
w.logger.Error("admin command publish failed", "worker", w.Name(), "fetched", stats.Fetched, "published", stats.Published, "failed", stats.Failed, "dead_lettered", stats.DeadLettered, "error", err)
return stats, err
}
if stats.Published > 0 && w.logger != nil {
w.logger.Info("admin command published", "worker", w.Name(), "published", stats.Published, "failed", stats.Failed, "dead_lettered", stats.DeadLettered)
}
return stats, err
}
func (w *Worker) run(ctx context.Context, done <-chan struct{}, stopped chan struct{}) {
defer func() {
w.clearStopped(stopped)
close(stopped)
}()
_, _ = w.RunOnce(ctx)
ticker := time.NewTicker(w.interval)
defer ticker.Stop()
for {
select {
case <-done:
return
case <-ticker.C:
_, _ = w.RunOnce(ctx)
}
}
}
func (w *Worker) clearStopped(stopped chan struct{}) {
w.mu.Lock()
defer w.mu.Unlock()
if w.stopped != stopped {
return
}
w.running = false
w.stopping = false
w.cancel = nil
w.done = nil
w.stopped = nil
}