|
| 1 | +package messaging |
| 2 | + |
| 3 | +import ( |
| 4 | + crand "crypto/rand" |
| 5 | + "math/rand" |
| 6 | + "sort" |
| 7 | + "time" |
| 8 | + |
| 9 | + "ergo.services/ergo/act" |
| 10 | + "ergo.services/ergo/gen" |
| 11 | +) |
| 12 | + |
| 13 | +type bulkSender struct { |
| 14 | + act.Actor |
| 15 | + |
| 16 | + target int |
| 17 | +} |
| 18 | + |
| 19 | +func factoryBulkSender() gen.ProcessBehavior { |
| 20 | + return &bulkSender{} |
| 21 | +} |
| 22 | + |
| 23 | +func (s *bulkSender) Init(args ...any) error { |
| 24 | + s.Log().Info("bulk sender started on %s", s.Node().Name()) |
| 25 | + s.SetCompression(true) |
| 26 | + s.SendAfter(s.PID(), messageBulkBurst{}, startDelay+3*time.Second) |
| 27 | + return nil |
| 28 | +} |
| 29 | + |
| 30 | +func (s *bulkSender) HandleMessage(from gen.PID, message any) error { |
| 31 | + switch message.(type) { |
| 32 | + case messageBulkBurst: |
| 33 | + s.doBurst() |
| 34 | + wait := time.Duration(3+rand.Intn(15)) * time.Second |
| 35 | + s.SendAfter(s.PID(), messageBulkBurst{}, wait) |
| 36 | + } |
| 37 | + return nil |
| 38 | +} |
| 39 | + |
| 40 | +func (s *bulkSender) doBurst() { |
| 41 | + registrar, err := s.Node().Network().Registrar() |
| 42 | + if err != nil { |
| 43 | + return |
| 44 | + } |
| 45 | + |
| 46 | + routes, err := registrar.Resolver().ResolveApplication(appName) |
| 47 | + if err != nil { |
| 48 | + return |
| 49 | + } |
| 50 | + |
| 51 | + myName := s.Node().Name() |
| 52 | + remotes := make([]gen.Atom, 0, len(routes)) |
| 53 | + for _, route := range routes { |
| 54 | + if route.Node == myName { |
| 55 | + continue |
| 56 | + } |
| 57 | + remotes = append(remotes, route.Node) |
| 58 | + } |
| 59 | + |
| 60 | + if len(remotes) == 0 { |
| 61 | + return |
| 62 | + } |
| 63 | + |
| 64 | + sort.Slice(remotes, func(i, j int) bool { |
| 65 | + return string(remotes[i]) < string(remotes[j]) |
| 66 | + }) |
| 67 | + |
| 68 | + node := remotes[s.target%len(remotes)] |
| 69 | + s.target++ |
| 70 | + |
| 71 | + count := 5 + rand.Intn(20) // 5..24 large messages |
| 72 | + to := gen.ProcessID{Name: poolName, Node: node} |
| 73 | + for i := 0; i < count; i++ { |
| 74 | + // 100KB..300KB -- large enough to trigger both compression and fragmentation |
| 75 | + length := 100000 + rand.Intn(200001) |
| 76 | + data := make([]byte, length) |
| 77 | + crand.Read(data) |
| 78 | + msg := MessageBulkPayload{Data: data} |
| 79 | + if err := s.Send(to, msg); err != nil { |
| 80 | + s.Log().Warning("bulk sender: send error at %d: %s", i, err) |
| 81 | + return |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + s.Log().Debug("bulk sender: burst %d large messages -> %s", count, node) |
| 86 | +} |
| 87 | + |
| 88 | +func (s *bulkSender) Terminate(reason error) { |
| 89 | + s.Log().Info("bulk sender terminated: %s", reason) |
| 90 | +} |
0 commit comments