github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/graceful/context.go (about)

     1  // Copyright 2023 The GitBundle Inc. All rights reserved.
     2  // Copyright 2017 The Gitea Authors. All rights reserved.
     3  // Use of this source code is governed by a MIT-style
     4  // license that can be found in the LICENSE file.
     5  
     6  package graceful
     7  
     8  import (
     9  	"context"
    10  	"time"
    11  )
    12  
    13  // ChannelContext is a context that wraps a channel and error as a context
    14  type ChannelContext struct {
    15  	done <-chan struct{}
    16  	err  error
    17  }
    18  
    19  // NewChannelContext creates a ChannelContext from a channel and error
    20  func NewChannelContext(done <-chan struct{}, err error) *ChannelContext {
    21  	return &ChannelContext{
    22  		done: done,
    23  		err:  err,
    24  	}
    25  }
    26  
    27  // Deadline returns the time when work done on behalf of this context
    28  // should be canceled. There is no Deadline for a ChannelContext
    29  func (ctx *ChannelContext) Deadline() (deadline time.Time, ok bool) {
    30  	return
    31  }
    32  
    33  // Done returns the channel provided at the creation of this context.
    34  // When closed, work done on behalf of this context should be canceled.
    35  func (ctx *ChannelContext) Done() <-chan struct{} {
    36  	return ctx.done
    37  }
    38  
    39  // Err returns nil, if Done is not closed. If Done is closed,
    40  // Err returns the error provided at the creation of this context
    41  func (ctx *ChannelContext) Err() error {
    42  	select {
    43  	case <-ctx.done:
    44  		return ctx.err
    45  	default:
    46  		return nil
    47  	}
    48  }
    49  
    50  // Value returns nil for all calls as no values are or can be associated with this context
    51  func (ctx *ChannelContext) Value(key interface{}) interface{} {
    52  	return nil
    53  }
    54  
    55  // ShutdownContext returns a context.Context that is Done at shutdown
    56  // Callers using this context should ensure that they are registered as a running server
    57  // in order that they are waited for.
    58  func (g *Manager) ShutdownContext() context.Context {
    59  	return g.shutdownCtx
    60  }
    61  
    62  // HammerContext returns a context.Context that is Done at hammer
    63  // Callers using this context should ensure that they are registered as a running server
    64  // in order that they are waited for.
    65  func (g *Manager) HammerContext() context.Context {
    66  	return g.hammerCtx
    67  }
    68  
    69  // TerminateContext returns a context.Context that is Done at terminate
    70  // Callers using this context should ensure that they are registered as a terminating server
    71  // in order that they are waited for.
    72  func (g *Manager) TerminateContext() context.Context {
    73  	return g.terminateCtx
    74  }