github.com/keybase/client/go@v0.0.0-20241007131713-f10651d043c8/kbfs/libkbfs/protected_context.go (about)

     1  // Copyright 2017 Keybase Inc. All rights reserved.
     2  // Use of this source code is governed by a BSD
     3  // license that can be found in the LICENSE file.
     4  
     5  package libkbfs
     6  
     7  import (
     8  	"sync"
     9  
    10  	"github.com/keybase/client/go/logger"
    11  	"golang.org/x/net/context"
    12  )
    13  
    14  type defaultContextReplacer struct{} // nolint
    15  
    16  func (defaultContextReplacer) maybeReplaceContext(context.Context) {}
    17  
    18  // protectedContext is a construct that helps avoid unwanted change of context
    19  // when the context needs to be stored.
    20  type protectedContext struct {
    21  	mu  sync.RWMutex
    22  	ctx context.Context
    23  	log logger.Logger
    24  
    25  	// defaultContextReplacer is embeded here as a helper that includes a no-op
    26  	// maybeReplaceContext, so that we can "override" the method in tests.
    27  	defaultContextReplacer // nolint
    28  }
    29  
    30  func newProtectedContext(
    31  	ctx context.Context, log logger.Logger) *protectedContext {
    32  	return &protectedContext{ctx: ctx, log: log}
    33  }
    34  
    35  func (c *protectedContext) setLogger(log logger.Logger) {
    36  	c.mu.Lock()
    37  	defer c.mu.Unlock()
    38  	c.log = log
    39  }
    40  
    41  // context returns the context stored in the protectedContext.
    42  func (c *protectedContext) context() context.Context {
    43  	c.mu.RLock()
    44  	defer c.mu.RUnlock()
    45  	return c.ctx
    46  }