File size: 9,469 Bytes
f1dd159
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
package batch

import (
	"context"
	"errors"
	"fmt"
	"math/rand/v2"
	"runtime/debug"
	"sync"
	"sync/atomic"
	"time"
)

// PanicError 表示任务发生 panic;堆栈只用于服务端诊断,不应直接返回给客户端。
type PanicError struct {
	Value any
	Stack []byte
}

func (e *PanicError) Error() string {
	return fmt.Sprintf("批量任务 panic: %v", e.Value)
}

// Pool 在多个批量操作之间共享并发容量,避免并发请求叠加突破上游保护阈值。
type Pool struct {
	mu      sync.Mutex
	limit   int
	slots   int
	changed chan struct{}
	parent  *Pool
	shared  LeaseLimiter
	key     string
	active  atomic.Int64
	queued  atomic.Int64
	peak    atomic.Int64
	jitter  atomic.Int64
}

type LeaseLimiter interface {
	Acquire(ctx context.Context, key string, limit int) (release func(), acquired bool, err error)
}

type PoolSnapshot struct {
	Limit  int
	Active int
	Queued int
	Peak   int
}

func NewPool(limit int) *Pool {
	if limit < 1 {
		limit = 1
	}
	return &Pool{limit: limit, changed: make(chan struct{})}
}

func NewSharedPool(limit int, limiter LeaseLimiter, key string) *Pool {
	pool := NewPool(limit)
	pool.shared = limiter
	pool.key = key
	return pool
}

// NewChildPool 创建分类并发池;任务先取得分类容量,再进入父级全局池。
func NewChildPool(limit int, parent *Pool) *Pool {
	pool := NewPool(limit)
	pool.parent = parent
	return pool
}

// NewSharedChildPool 创建同时受分类集群租约和父级总容量约束的并发池。
func NewSharedChildPool(limit int, limiter LeaseLimiter, key string, parent *Pool) *Pool {
	pool := NewSharedPool(limit, limiter, key)
	pool.parent = parent
	return pool
}

// UpdateLimit 热更新并发上限;降低上限不会中断正在执行的任务。
func (p *Pool) UpdateLimit(limit int) {
	if p == nil {
		return
	}
	if limit < 1 {
		limit = 1
	}
	p.mu.Lock()
	p.limit = limit
	p.signalLocked()
	p.mu.Unlock()
	p.peak.Store(p.active.Load())
}

// UpdateJitter 热更新任务进入并发池前的随机延迟上限;零表示关闭。
func (p *Pool) UpdateJitter(maximum time.Duration) {
	if p == nil {
		return
	}
	if maximum < 0 {
		maximum = 0
	}
	p.jitter.Store(int64(maximum))
}

// Do 等待共享执行容量并隔离任务 panic,调用方仍通过 context 控制排队和执行生命周期。
func (p *Pool) Do(ctx context.Context, work func(context.Context) error) (err error) {
	if p == nil {
		return invoke(ctx, work)
	}
	if err := ctx.Err(); err != nil {
		return err
	}
	if err := p.waitJitter(ctx); err != nil {
		return err
	}
	p.queued.Add(1)
	started := false
	defer func() {
		if !started {
			p.queued.Add(-1)
		}
	}()
	if err := p.acquireSlot(ctx); err != nil {
		return err
	}
	defer p.releaseSlot()
	var releaseShared func()
	if p.shared != nil {
		for {
			release, acquired, acquireErr := p.shared.Acquire(ctx, p.key, p.Limit())
			if acquireErr != nil {
				return acquireErr
			}
			if acquired {
				releaseShared = release
				break
			}
			timer := time.NewTimer(100 * time.Millisecond)
			select {
			case <-ctx.Done():
				timer.Stop()
				return ctx.Err()
			case <-timer.C:
			}
		}
	}
	defer func() {
		if releaseShared != nil {
			releaseShared()
		}
	}()
	run := func(workCtx context.Context) error {
		started = true
		p.queued.Add(-1)
		p.begin()
		defer p.end()
		return invoke(workCtx, work)
	}
	if p.parent != nil {
		return p.parent.Do(ctx, run)
	}
	return run(ctx)
}

func (p *Pool) waitJitter(ctx context.Context) error {
	maximum := p.jitter.Load()
	if maximum <= 0 || p.Limit() <= 1 {
		return nil
	}
	delay := time.Duration(rand.Int64N(maximum))
	if delay == 0 {
		return nil
	}
	timer := time.NewTimer(delay)
	defer timer.Stop()
	select {
	case <-ctx.Done():
		return ctx.Err()
	case <-timer.C:
		return nil
	}
}

func (p *Pool) acquireSlot(ctx context.Context) error {
	for {
		p.mu.Lock()
		if p.slots < p.limit {
			p.slots++
			p.mu.Unlock()
			return nil
		}
		changed := p.changed
		p.mu.Unlock()
		select {
		case <-ctx.Done():
			return ctx.Err()
		case <-changed:
		}
	}
}

func (p *Pool) releaseSlot() {
	p.mu.Lock()
	p.slots--
	p.signalLocked()
	p.mu.Unlock()
}

func (p *Pool) signalLocked() {
	close(p.changed)
	p.changed = make(chan struct{})
}

func (p *Pool) begin() {
	current := p.active.Add(1)
	for {
		peak := p.peak.Load()
		if current <= peak || p.peak.CompareAndSwap(peak, current) {
			break
		}
	}
}

func (p *Pool) end() {
	p.active.Add(-1)
}

// Limit 返回当前并发上限。
func (p *Pool) Limit() int {
	if p == nil {
		return 0
	}
	p.mu.Lock()
	defer p.mu.Unlock()
	return p.limit
}

func (p *Pool) Snapshot() PoolSnapshot {
	if p == nil {
		return PoolSnapshot{}
	}
	return PoolSnapshot{Limit: p.Limit(), Active: int(p.active.Load()), Queued: int(p.queued.Load()), Peak: int(p.peak.Load())}
}

// Do 隔离单个任务 panic,适用于长驻 Worker 和后台任务监督器。
func Do(ctx context.Context, work func(context.Context) error) error {
	return invoke(ctx, work)
}

type Options struct {
	Workers   int
	QueueSize int
	Pool      *Pool
}

type Result[T any] struct {
	Value     T
	Err       error
	Completed bool
}

type Summary struct {
	Total     int
	Submitted int
	Completed int
	Succeeded int
	Failed    int
	Panicked  int
	Canceled  bool
	Duration  time.Duration
}

type indexedItem[T any] struct {
	index int
	value T
}

// Map 以稳定输入顺序返回结果;单项失败和 panic 不会中断其他已提交任务。
func Map[T, R any](ctx context.Context, items []T, options Options, work func(context.Context, T) (R, error)) ([]Result[R], Summary, error) {
	return MapObserved(ctx, items, options, work, nil)
}

// MapObserved 在任务释放共享容量后通知结果观察者,适合连接下游有界流水线。
func MapObserved[T, R any](ctx context.Context, items []T, options Options, work func(context.Context, T) (R, error), observe func(index int, result Result[R])) ([]Result[R], Summary, error) {
	return mapObserved(ctx, items, options, work, observe, true)
}

// ForEachObserved 执行带观察者的批量任务,但不在内存中保留全部结果。
// 适用于单项结果已经流式发送给下游、最终只需要汇总信息的批量接口。
func ForEachObserved[T, R any](ctx context.Context, items []T, options Options, work func(context.Context, T) (R, error), observe func(index int, result Result[R])) (Summary, error) {
	_, summary, err := mapObserved(ctx, items, options, work, observe, false)
	return summary, err
}

func mapObserved[T, R any](ctx context.Context, items []T, options Options, work func(context.Context, T) (R, error), observe func(index int, result Result[R]), collectResults bool) ([]Result[R], Summary, error) {
	startedAt := time.Now()
	var results []Result[R]
	if collectResults {
		results = make([]Result[R], len(items))
	}
	summary := Summary{Total: len(items)}
	if len(items) == 0 {
		summary.Duration = time.Since(startedAt)
		return results, summary, nil
	}
	workers := options.Workers
	if workers < 1 {
		workers = 1
	}
	workers = min(workers, len(items))
	queueSize := options.QueueSize
	if queueSize < 1 {
		queueSize = workers * 2
	}
	queueSize = min(queueSize, len(items))
	jobs := make(chan indexedItem[T], queueSize)
	var completed atomic.Int64
	var succeeded atomic.Int64
	var failed atomic.Int64
	var panicked atomic.Int64
	var wait sync.WaitGroup
	wait.Add(workers)
	for range workers {
		go func() {
			defer wait.Done()
			for {
				select {
				case <-ctx.Done():
					return
				case job, ok := <-jobs:
					if !ok {
						return
					}
					var value R
					err := options.Pool.Do(ctx, func(workCtx context.Context) error {
						var workErr error
						value, workErr = work(workCtx, job.value)
						return workErr
					})
					execution := Result[R]{Value: value, Err: err, Completed: true}
					if observe != nil {
						observeErr := invoke(ctx, func(context.Context) error {
							observe(job.index, execution)
							return nil
						})
						if execution.Err == nil && observeErr != nil {
							execution.Err = observeErr
						}
					}
					if collectResults {
						results[job.index] = execution
					}
					completed.Add(1)
					if execution.Err == nil {
						succeeded.Add(1)
					} else {
						failed.Add(1)
						var panicErr *PanicError
						if errors.As(execution.Err, &panicErr) {
							panicked.Add(1)
						}
					}
				}
			}
		}()
	}

sendLoop:
	for index, item := range items {
		if ctx.Err() != nil {
			break
		}
		select {
		case jobs <- indexedItem[T]{index: index, value: item}:
			summary.Submitted++
		case <-ctx.Done():
			break sendLoop
		}
	}
	close(jobs)
	wait.Wait()
	summary.Completed = int(completed.Load())
	summary.Succeeded = int(succeeded.Load())
	summary.Failed = int(failed.Load())
	summary.Panicked = int(panicked.Load())
	summary.Canceled = ctx.Err() != nil
	summary.Duration = time.Since(startedAt)
	return results, summary, ctx.Err()
}

// Run 执行只关心成功或失败的批量任务。
func Run[T any](ctx context.Context, items []T, options Options, work func(context.Context, T) error) ([]Result[struct{}], Summary, error) {
	return Map(ctx, items, options, func(workCtx context.Context, item T) (struct{}, error) {
		return struct{}{}, work(workCtx, item)
	})
}

func invoke(ctx context.Context, work func(context.Context) error) (err error) {
	defer func() {
		if recovered := recover(); recovered != nil {
			err = &PanicError{Value: recovered, Stack: debug.Stack()}
		}
	}()
	return work(ctx)
}