code.vegaprotocol.io/vega@v0.79.0/libs/job/runner.go (about)

     1  // Copyright (C) 2023 Gobalsky Labs Limited
     2  //
     3  // This program is free software: you can redistribute it and/or modify
     4  // it under the terms of the GNU Affero General Public License as
     5  // published by the Free Software Foundation, either version 3 of the
     6  // License, or (at your option) any later version.
     7  //
     8  // This program is distributed in the hope that it will be useful,
     9  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    10  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    11  // GNU Affero General Public License for more details.
    12  //
    13  // You should have received a copy of the GNU Affero General Public License
    14  // along with this program.  If not, see <http://www.gnu.org/licenses/>.
    15  
    16  package job
    17  
    18  import (
    19  	"context"
    20  	"sync"
    21  	"sync/atomic"
    22  )
    23  
    24  type Runner struct {
    25  	wg           sync.WaitGroup
    26  	jobsCtx      context.Context
    27  	jobsCancelFn context.CancelFunc
    28  
    29  	// blown tells if the runner has been used end-to-end (Go + StopAllJobs), or
    30  	// not. If blown, the runner can't be used anymore.
    31  	blown atomic.Bool
    32  }
    33  
    34  func (r *Runner) Ctx() context.Context {
    35  	return r.jobsCtx
    36  }
    37  
    38  func (r *Runner) Go(fn func(ctx context.Context)) {
    39  	if r.blown.Load() {
    40  		panic("the Runner cannot be recycled")
    41  	}
    42  
    43  	r.wg.Add(1)
    44  	go func() {
    45  		defer r.wg.Done()
    46  		fn(r.jobsCtx)
    47  	}()
    48  }
    49  
    50  func (r *Runner) StopAllJobs() {
    51  	r.blown.Store(true)
    52  	r.jobsCancelFn()
    53  	r.wg.Wait()
    54  }
    55  
    56  func NewRunner(ctx context.Context) *Runner {
    57  	jobsCtx, jobsCancelFn := context.WithCancel(ctx)
    58  	return &Runner{
    59  		blown:        atomic.Bool{},
    60  		jobsCtx:      jobsCtx,
    61  		jobsCancelFn: jobsCancelFn,
    62  		wg:           sync.WaitGroup{},
    63  	}
    64  }