github.com/blend/go-sdk@v1.20220411.3/examples/db/statement-timeout/config.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package main
     9  
    10  import (
    11  	"log"
    12  	"strings"
    13  	"time"
    14  
    15  	"github.com/blend/go-sdk/env"
    16  	"github.com/blend/go-sdk/ex"
    17  )
    18  
    19  const (
    20  	envVarStatementTimeout = "DB_STATEMENT_TIMEOUT"
    21  )
    22  
    23  type config struct {
    24  	StatementTimeout time.Duration
    25  	PGSleep          time.Duration
    26  	ContextTimeout   time.Duration
    27  }
    28  
    29  func (c *config) SetEnvironment() error {
    30  	existing := env.Env().String(envVarStatementTimeout)
    31  	if existing != "" {
    32  		err := ex.New(
    33  			"Statement timeout will be set by the statement-timeout script",
    34  			ex.OptMessagef("Value set from the environment, %s=%q", envVarStatementTimeout, existing),
    35  		)
    36  		return err
    37  	}
    38  
    39  	env.Env().Set(envVarStatementTimeout, c.StatementTimeout.String())
    40  	return nil
    41  }
    42  
    43  func (c *config) Print() {
    44  	if c == nil {
    45  		return
    46  	}
    47  
    48  	log.Printf("Configured statement timeout: %s\n", c.StatementTimeout)
    49  	log.Printf("Configured pg_sleep:          %s\n", c.PGSleep)
    50  	log.Printf("Configured context timeout:   %s\n", c.ContextTimeout)
    51  }
    52  
    53  func getConfig() *config {
    54  	viaGoContext := env.Env().String("VIA_GO_CONTEXT")
    55  	if strings.EqualFold(viaGoContext, "true") {
    56  		return &config{
    57  			StatementTimeout: 10 * time.Second,
    58  			PGSleep:          200 * time.Millisecond,
    59  			ContextTimeout:   100 * time.Millisecond,
    60  		}
    61  	}
    62  
    63  	return &config{
    64  		StatementTimeout: 10 * time.Millisecond,
    65  		PGSleep:          200 * time.Millisecond,
    66  		ContextTimeout:   400 * time.Millisecond,
    67  	}
    68  }