Files
dobotai-platform/internal/channels/dingtalk/card_pump.go

98 lines
2.1 KiB
Go

package dingtalk
import (
"context"
"log"
"sync"
"time"
)
type cardPumpUpdate func(context.Context, string) error
type cardUpdatePump struct {
updates chan string
stop chan struct{}
done chan struct{}
once sync.Once
}
func newCardUpdatePump(ctx context.Context, interval time.Duration, update cardPumpUpdate) *cardUpdatePump {
if interval <= 0 {
interval = 500 * time.Millisecond
}
ticker := time.NewTicker(interval)
return newCardUpdatePumpWithTicks(ctx, ticker.C, ticker.Stop, update)
}
func newCardUpdatePumpWithTicks(ctx context.Context, ticks <-chan time.Time, stopTicks func(), update cardPumpUpdate) *cardUpdatePump {
p := &cardUpdatePump{
updates: make(chan string, 1),
stop: make(chan struct{}),
done: make(chan struct{}),
}
go p.run(ctx, ticks, stopTicks, update)
return p
}
func (p *cardUpdatePump) run(ctx context.Context, ticks <-chan time.Time, stopTicks func(), update cardPumpUpdate) {
defer close(p.done)
if stopTicks != nil {
defer stopTicks()
}
lastSuccessful := ""
for {
select {
case <-ctx.Done():
return
case <-p.stop:
return
case <-ticks:
var latest string
select {
case latest = <-p.updates:
default:
continue
}
if latest == lastSuccessful {
continue
}
if err := update(ctx, latest); err != nil {
log.Printf("DingTalk async card update failed, continuing")
continue
}
lastSuccessful = latest
}
}
}
// Offer replaces any pending content with the newest full card state. It never
// waits for DingTalk I/O, so the WeKnora SSE reader cannot be back-pressured by
// card delivery latency.
func (p *cardUpdatePump) Offer(content string) {
select {
case <-p.stop:
return
default:
}
select {
case p.updates <- content:
return
default:
}
select {
case <-p.updates:
default:
}
select {
case p.updates <- content:
case <-p.stop:
}
}
// Stop prevents stale non-final updates from racing with the synchronous final
// card update and waits for any in-flight DingTalk request to finish.
func (p *cardUpdatePump) Stop() {
p.once.Do(func() { close(p.stop) })
<-p.done
}