github.com/braveheart12/just@v0.8.7/testutils/pulsarmodel/network.go (about)

     1  /*
     2   *    Copyright 2019 Insolar Technologies
     3   *
     4   *    Licensed under the Apache License, Version 2.0 (the "License");
     5   *    you may not use this file except in compliance with the License.
     6   *    You may obtain a copy of the License at
     7   *
     8   *        http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   *    Unless required by applicable law or agreed to in writing, software
    11   *    distributed under the License is distributed on an "AS IS" BASIS,
    12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   *    See the License for the specific language governing permissions and
    14   *    limitations under the License.
    15   */
    16  
    17  package main
    18  
    19  import (
    20  	"math/rand"
    21  	"time"
    22  )
    23  
    24  var network [10000]*NetworkNode
    25  var commonBus = make(chan *SignalStatistic, 10000000)
    26  
    27  type NetworkNode struct {
    28  	Neighbours      map[int]struct{}
    29  	Channel         chan *Signal
    30  	PreviousSignals map[int]struct{}
    31  }
    32  
    33  func (node *NetworkNode) Listen(current int) {
    34  	for signal := range node.Channel {
    35  		delay := time.Duration(rand.Intn(100)) * time.Millisecond
    36  		time.Sleep(delay)
    37  		commonBus <- &SignalStatistic{from: signal.from, to: current, id: signal.id, time: time.Now()}
    38  
    39  		if _, ok := node.PreviousSignals[signal.id]; !ok {
    40  			node.PreviousSignals[signal.id] = struct{}{}
    41  			for neighbour := range node.Neighbours {
    42  				if neighbour != signal.from {
    43  					network[neighbour].Channel <- &Signal{from: current, id: signal.id}
    44  
    45  				}
    46  			}
    47  		}
    48  	}
    49  }
    50  
    51  func pulse() {
    52  	id := 0
    53  	pulseFunc := func() {
    54  		id++
    55  		nextPulsar := rand.Intn(len(network))
    56  		network[nextPulsar].Channel <- &Signal{from: -1, id: id}
    57  	}
    58  	pulseFunc()
    59  
    60  	ticker := time.NewTicker(time.Second * 10)
    61  	go func() {
    62  		for range ticker.C {
    63  			pulseFunc()
    64  		}
    65  	}()
    66  }