feat: build wahrwelt A/D toolkit

This commit is contained in:
TakuyaYagam1 committed 2026-10-14 11:30:41 +03:00
1 parent 303438d206
commit 653924d8c6
564 files changed
+36310 -49998

No files matched your search

+37
View File
@@ -0,0 +1,37 @@
package pubsub
import "sync"
type PubSub[T any] struct {
subs map[string]*Subscription[T]
mu sync.RWMutex
}
func NewPubSub[T any]() *PubSub[T] {
return &PubSub[T]{
subs: make(map[string]*Subscription[T]),
}
}
func (ps *PubSub[T]) Publish(msg T) {
ps.mu.RLock()
defer ps.mu.RUnlock()
for _, sub := range ps.subs {
sub.Push(msg)
}
}
func (ps *PubSub[T]) Subscribe(onMsg MessageHandler[T]) *Subscription[T] {
ps.mu.Lock()
defer ps.mu.Unlock()
sub := NewSubscription(onMsg)
ps.subs[sub.GetID()] = sub
return sub
}
func (ps *PubSub[T]) Unsubscribe(sub *Subscription[T]) {
ps.mu.Lock()
defer ps.mu.Unlock()
delete(ps.subs, sub.GetID())
}
+262
View File
@@ -0,0 +1,262 @@
package pubsub
import (
"context"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/require"
"go.uber.org/goleak"
"github.com/c4t-but-s4d/neo/v2/pkg/neosync"
)
func TestMain(m *testing.M) {
goleak.VerifyTestMain(m)
}
func TestPubSub_single(t *testing.T) {
p := NewPubSub[string]()
wg := sync.WaitGroup{}
wg.Add(1)
sub := p.Subscribe(func(msg string) error {
require.Equal(t, "blah-blah", msg)
wg.Done()
return nil
})
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go sub.Run(ctx)
p.Publish("blah-blah")
wg.Wait()
}
func TestPubSub_nonBlockPublish(t *testing.T) {
p := NewPubSub[string]()
wg := sync.WaitGroup{}
wg.Add(11)
sub := p.Subscribe(func(msg string) error {
require.Equal(t, "pew-pew", msg)
wg.Done()
return nil
})
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go sub.Run(ctx)
done := make(chan struct{})
go func() {
for i := 0; i < 11; i++ {
p.Publish("pew-pew")
}
close(done)
}()
select {
case <-time.After(1 * time.Second):
t.Fatal("publish method must not be blocked")
case <-done:
}
wg.Wait()
}
func TestPubSub_multipleSubscribers(t *testing.T) {
p := NewPubSub[string]()
wgFirst := sync.WaitGroup{}
wgFirst.Add(1)
wgSecond := sync.WaitGroup{}
wgSecond.Add(1)
sub1 := p.Subscribe(func(msg string) error {
require.Equal(t, "blah", msg)
wgFirst.Done()
return nil
})
ctx1, cancel1 := context.WithCancel(context.Background())
defer cancel1()
go sub1.Run(ctx1)
sub2 := p.Subscribe(func(msg string) error {
require.Equal(t, "blah", msg)
wgSecond.Done()
return nil
})
ctx2, cancel2 := context.WithCancel(context.Background())
defer cancel2()
go sub2.Run(ctx2)
p.Publish("blah")
wgFirst.Wait()
wgSecond.Wait()
}
func TestPubSub_slowpoke(t *testing.T) {
p := NewPubSub[string]()
const samples = 100
wgSlow := sync.WaitGroup{}
wgSlow.Add(samples)
slowCtx, slowCancel := context.WithCancel(context.Background())
defer func() {
slowCancel()
wgSlow.Wait()
}()
slowSub := p.Subscribe(func(msg string) error {
defer wgSlow.Done()
select {
case <-slowCtx.Done():
return nil
default:
time.Sleep(1 * time.Second)
}
return nil
})
go slowSub.Run(slowCtx)
fastWg := sync.WaitGroup{}
fastWg.Add(samples)
fastSub := p.Subscribe(func(msg string) error {
require.Equal(t, "pew-pew", msg)
fastWg.Done()
return nil
})
fastCtx, cancel := context.WithCancel(context.Background())
defer cancel()
go fastSub.Run(fastCtx)
for i := 0; i < samples; i++ {
p.Publish("pew-pew")
}
select {
case <-time.After(1 * time.Second):
t.Fatal("publish blocks on slowpoke?")
case <-neosync.AwaitWG(&fastWg):
// ok
}
}
func TestPubSub_unsubscribe(t *testing.T) {
p := NewPubSub[string]()
sub1 := p.Subscribe(func(msg string) error {
t.Error("first subscriber must not be called")
return nil
})
ctx1, cancel1 := context.WithCancel(context.Background())
defer cancel1()
go sub1.Run(ctx1)
p.Unsubscribe(sub1)
wg := sync.WaitGroup{}
wg.Add(1)
sub2 := p.Subscribe(func(msg string) error {
require.Equal(t, "pew-pew", msg)
wg.Done()
return nil
})
ctx2, cancel2 := context.WithCancel(context.Background())
defer cancel2()
go sub2.Run(ctx2)
p.Publish("pew-pew")
wg.Wait()
}
func TestPubSub_sequencePublishers(t *testing.T) {
p := NewPubSub[string]()
wg := sync.WaitGroup{}
wg.Add(10)
sub := p.Subscribe(func(msg string) error {
require.Equal(t, "pew-pew", msg)
wg.Done()
return nil
})
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go sub.Run(ctx)
for i := 0; i < 10; i++ {
p.Publish("pew-pew")
}
wg.Wait()
}
func TestPubSub_concurrentPublishers(t *testing.T) {
p := NewPubSub[string]()
wg := sync.WaitGroup{}
wg.Add(10)
sub := p.Subscribe(func(msg string) error {
require.Equal(t, "pew-pew", msg)
wg.Done()
return nil
})
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go sub.Run(ctx)
for i := 0; i < 10; i++ {
go p.Publish("pew-pew")
}
wg.Wait()
}
func TestPubSub_msgOrder(t *testing.T) {
p := NewPubSub[uint64]()
wg := sync.WaitGroup{}
wg.Add(15)
c := uint64(0)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
sub := p.Subscribe(func(msg uint64) error {
expected := atomic.AddUint64(&c, 1)
require.Equal(t, expected, msg)
wg.Done()
return nil
})
go sub.Run(ctx)
for i := uint64(1); i < 11; i++ {
if i == 6 {
c := uint64(5)
sub := p.Subscribe(func(msg uint64) error {
expected := atomic.AddUint64(&c, 1)
require.Equal(t, expected, msg)
wg.Done()
return nil
})
go sub.Run(ctx)
}
p.Publish(i)
}
wg.Wait()
}
+73
View File
@@ -0,0 +1,73 @@
package pubsub
import (
"context"
"sync"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
)
type MessageHandler[T any] func(T) error
type Subscription[T any] struct {
id string
queue []T
mu sync.Mutex
notify chan struct{}
h MessageHandler[T]
}
func NewSubscription[T any](onMsg MessageHandler[T]) *Subscription[T] {
id := uuid.NewString()
return &Subscription[T]{
id: id,
queue: nil,
notify: make(chan struct{}, 1),
h: onMsg,
}
}
func (s *Subscription[T]) Run(ctx context.Context) {
for {
select {
case _, ok := <-s.notify:
if !ok {
return
}
for {
s.mu.Lock()
if len(s.queue) == 0 {
s.mu.Unlock()
break
}
cmd := s.queue[0]
s.queue = s.queue[1:]
s.mu.Unlock()
logrus.Debugf("Обработка сообщения типа %T в подписке %s", cmd, s.id)
if err := s.h(cmd); err != nil {
logrus.Errorf("Ошибка обработчика сообщения подписки: %v", err)
continue
}
}
case <-ctx.Done():
return
}
}
}
func (s *Subscription[T]) Push(msg T) {
s.mu.Lock()
s.queue = append(s.queue, msg)
s.mu.Unlock()
select {
case s.notify <- struct{}{}:
default:
}
}
func (s *Subscription[T]) GetID() string {
return s.id
}
@@ -0,0 +1,58 @@
package pubsub
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestNewSubscription(t *testing.T) {
sub := NewSubscription[int](nil)
newSub := NewSubscription[int](nil)
require.NotEqual(t, sub.GetID(), newSub.GetID(), "id is not random")
}
func Test_subscription_Push(t *testing.T) {
sub := &Subscription[string]{
id: "test",
queue: nil,
notify: make(chan struct{}),
h: nil,
}
sub.Push("test")
require.Equal(t, []string{"test"}, sub.queue)
}
func Test_subscription_Run(t *testing.T) {
var received string
signal := make(chan struct{})
handler := func(msg string) error {
received = msg
close(signal)
return nil
}
sub := &Subscription[string]{
id: "test",
queue: nil,
notify: make(chan struct{}, 1),
h: handler,
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go sub.Run(ctx)
const msg = "message"
sub.Push(msg)
select {
case <-signal:
break
case <-time.After(time.Millisecond * 100):
t.Errorf("Handler was not called in time")
}
require.Equal(t, msg, received)
}