github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/core/discovery/worker.go (about)

     1  /*
     2   * Copyright (C) 2020 The "MysteriumNetwork/node" Authors.
     3   *
     4   * This program is free software: you can redistribute it and/or modify
     5   * it under the terms of the GNU General Public License as published by
     6   * the Free Software Foundation, either version 3 of the License, or
     7   * (at your option) any later version.
     8   *
     9   * This program is distributed in the hope that it will be useful,
    10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12   * GNU General Public License for more details.
    13   *
    14   * You should have received a copy of the GNU General Public License
    15   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    16   */
    17  
    18  package discovery
    19  
    20  import (
    21  	"fmt"
    22  )
    23  
    24  // Worker continuously runs discovery process in node's background.
    25  type Worker interface {
    26  	Start() error
    27  	Stop()
    28  }
    29  
    30  type workerComposite []Worker
    31  
    32  // NewWorker creates an instance of composite worker.
    33  func NewWorker(workers ...Worker) *workerComposite {
    34  	wc := workerComposite(workers)
    35  	return &wc
    36  }
    37  
    38  // AddWorker adds worker to set of workers.
    39  func (wc *workerComposite) AddWorker(worker Worker) {
    40  	*wc = append(*wc, worker)
    41  }
    42  
    43  // Start starts all workers.
    44  func (wc *workerComposite) Start() error {
    45  	for _, worker := range *wc {
    46  		if err := worker.Start(); err != nil {
    47  			return fmt.Errorf("failed to start worker: %w", err)
    48  		}
    49  	}
    50  
    51  	return nil
    52  }
    53  
    54  // Start starts all workers.
    55  func (wc *workerComposite) Stop() {
    56  	for _, worker := range *wc {
    57  		worker.Stop()
    58  	}
    59  }