diff --git a/action/protocol/rewarding/protocol.go b/action/protocol/rewarding/protocol.go index 15df94adc4..531b3abea1 100644 --- a/action/protocol/rewarding/protocol.go +++ b/action/protocol/rewarding/protocol.go @@ -28,8 +28,8 @@ import ( const ( // TODO: it works only for one instance per protocol definition now - _protocolID = "rewarding" - _v2Namespace = "Rewarding" + _protocolID = "rewarding" + _v2RewardingNamespace = "Rewarding" ) var ( @@ -332,7 +332,7 @@ func (p *Protocol) stateV1(sm protocol.StateReader, key []byte, value interface{ func (p *Protocol) stateV2(sm protocol.StateReader, key []byte, value interface{}) (uint64, error) { k := append(p.keyPrefix, key...) - return sm.State(value, protocol.KeyOption(k), protocol.NamespaceOption(_v2Namespace)) + return sm.State(value, protocol.KeyOption(k), protocol.NamespaceOption(_v2RewardingNamespace)) } func (p *Protocol) putState(ctx context.Context, sm protocol.StateManager, key []byte, value interface{}) error { @@ -350,7 +350,7 @@ func (p *Protocol) putStateV1(sm protocol.StateManager, key []byte, value interf func (p *Protocol) putStateV2(sm protocol.StateManager, key []byte, value interface{}) error { k := append(p.keyPrefix, key...) - _, err := sm.PutState(value, protocol.KeyOption(k), protocol.NamespaceOption(_v2Namespace)) + _, err := sm.PutState(value, protocol.KeyOption(k), protocol.NamespaceOption(_v2RewardingNamespace)) return err } @@ -373,7 +373,7 @@ func (p *Protocol) deleteStateV1(sm protocol.StateManager, key []byte) error { func (p *Protocol) deleteStateV2(sm protocol.StateManager, key []byte) error { k := append(p.keyPrefix, key...) - _, err := sm.DelState(protocol.KeyOption(k), protocol.NamespaceOption(_v2Namespace)) + _, err := sm.DelState(protocol.KeyOption(k), protocol.NamespaceOption(_v2RewardingNamespace)) if errors.Cause(err) == state.ErrStateNotExist { // don't care if not exist return nil diff --git a/action/protocol/staking/bucket_pool.go b/action/protocol/staking/bucket_pool.go index f62ec577ac..a7df9023fc 100644 --- a/action/protocol/staking/bucket_pool.go +++ b/action/protocol/staking/bucket_pool.go @@ -115,7 +115,7 @@ func (bp *BucketPool) Copy(enableSMStorage bool) *BucketPool { // Sync syncs the data from state manager func (bp *BucketPool) Sync(sm protocol.StateManager) error { if bp.enableSMStorage { - _, err := sm.State(bp.total, protocol.NamespaceOption(StakingNameSpace), protocol.KeyOption(_bucketPoolAddrKey)) + _, err := sm.State(bp.total, protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(_bucketPoolAddrKey)) return err } // get stashed total amount @@ -138,7 +138,7 @@ func (bp *BucketPool) CreditPool(sm protocol.StateManager, amount *big.Int) erro } if bp.enableSMStorage { - _, err := sm.PutState(bp.total, protocol.NamespaceOption(StakingNameSpace), protocol.KeyOption(_bucketPoolAddrKey)) + _, err := sm.PutState(bp.total, protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(_bucketPoolAddrKey)) return err } return sm.Load(_protocolID, _stakingBucketPool, bp.total) @@ -148,7 +148,7 @@ func (bp *BucketPool) CreditPool(sm protocol.StateManager, amount *big.Int) erro func (bp *BucketPool) DebitPool(sm protocol.StateManager, amount *big.Int, newBucket bool) error { bp.total.AddBalance(amount, newBucket) if bp.enableSMStorage { - _, err := sm.PutState(bp.total, protocol.NamespaceOption(StakingNameSpace), protocol.KeyOption(_bucketPoolAddrKey)) + _, err := sm.PutState(bp.total, protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(_bucketPoolAddrKey)) return err } return sm.Load(_protocolID, _stakingBucketPool, bp.total) diff --git a/action/protocol/staking/bucket_pool_test.go b/action/protocol/staking/bucket_pool_test.go index b24de208c7..fffc7cb7a7 100644 --- a/action/protocol/staking/bucket_pool_test.go +++ b/action/protocol/staking/bucket_pool_test.go @@ -157,7 +157,7 @@ func TestBucketPool(t *testing.T) { } if !testGreenland && v.postGreenland { - _, err = sm.PutState(c.BaseView().bucketPool.total, protocol.NamespaceOption(StakingNameSpace), protocol.KeyOption(_bucketPoolAddrKey)) + _, err = sm.PutState(c.BaseView().bucketPool.total, protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(_bucketPoolAddrKey)) r.NoError(err) testGreenland = true } @@ -165,7 +165,7 @@ func TestBucketPool(t *testing.T) { // verify state has been created successfully var b totalAmount - _, err = sm.State(&b, protocol.NamespaceOption(StakingNameSpace), protocol.KeyOption(_bucketPoolAddrKey)) + _, err = sm.State(&b, protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(_bucketPoolAddrKey)) r.NoError(err) r.Equal(total, b.amount) r.Equal(count, b.count) diff --git a/action/protocol/staking/candidate_statemanager.go b/action/protocol/staking/candidate_statemanager.go index a0ded16209..950e680a18 100644 --- a/action/protocol/staking/candidate_statemanager.go +++ b/action/protocol/staking/candidate_statemanager.go @@ -196,7 +196,7 @@ func (csm *candSM) updateBucket(index uint64, bucket *VoteBucket) error { _, err := csm.PutState( bucket, - protocol.NamespaceOption(StakingNameSpace), + protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(bucketKey(index))) return err } @@ -205,7 +205,7 @@ func (csm *candSM) putBucket(bucket *VoteBucket) (uint64, error) { var tc totalBucketCount if _, err := csm.State( &tc, - protocol.NamespaceOption(StakingNameSpace), + protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(TotalBucketKey)); err != nil && errors.Cause(err) != state.ErrStateNotExist { return 0, err } @@ -215,21 +215,21 @@ func (csm *candSM) putBucket(bucket *VoteBucket) (uint64, error) { bucket.Index = index if _, err := csm.PutState( bucket, - protocol.NamespaceOption(StakingNameSpace), + protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(bucketKey(index))); err != nil { return 0, err } tc.count++ _, err := csm.PutState( &tc, - protocol.NamespaceOption(StakingNameSpace), + protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(TotalBucketKey)) return index, err } func (csm *candSM) delBucket(index uint64) error { _, err := csm.DelState( - protocol.NamespaceOption(StakingNameSpace), + protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(bucketKey(index))) return err } @@ -272,14 +272,14 @@ func (csm *candSM) putBucketIndex(addr address.Address, prefix byte, index uint6 ) if _, err := csm.State( &bis, - protocol.NamespaceOption(StakingNameSpace), + protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(key)); err != nil && errors.Cause(err) != state.ErrStateNotExist { return err } bis.addBucketIndex(index) _, err := csm.PutState( &bis, - protocol.NamespaceOption(StakingNameSpace), + protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(key)) return err } @@ -295,7 +295,7 @@ func (csm *candSM) delBucketIndex(addr address.Address, prefix byte, index uint6 ) if _, err := csm.State( &bis, - protocol.NamespaceOption(StakingNameSpace), + protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(key)); err != nil { return err } @@ -304,12 +304,12 @@ func (csm *candSM) delBucketIndex(addr address.Address, prefix byte, index uint6 var err error if len(bis) == 0 { _, err = csm.DelState( - protocol.NamespaceOption(StakingNameSpace), + protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(key)) } else { _, err = csm.PutState( &bis, - protocol.NamespaceOption(StakingNameSpace), + protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(key)) } return err @@ -320,7 +320,7 @@ func (csm *candSM) delVoterBucketIndex(addr address.Address, index uint64) error } func (csm *candSM) putCandidate(d *Candidate) error { - _, err := csm.PutState(d, protocol.NamespaceOption(CandidateNameSpace), protocol.KeyOption(d.Owner.Bytes())) + _, err := csm.PutState(d, protocol.NamespaceOption(_candidateNameSpace), protocol.KeyOption(d.Owner.Bytes())) return err } @@ -329,7 +329,7 @@ func (csm *candSM) putCandBucketIndex(addr address.Address, index uint64) error } func (csm *candSM) delCandidate(name address.Address) error { - _, err := csm.DelState(protocol.NamespaceOption(CandidateNameSpace), protocol.KeyOption(name.Bytes())) + _, err := csm.DelState(protocol.NamespaceOption(_candidateNameSpace), protocol.KeyOption(name.Bytes())) return err } diff --git a/action/protocol/staking/candidate_statereader.go b/action/protocol/staking/candidate_statereader.go index dad079aab2..a5b7d4ba48 100644 --- a/action/protocol/staking/candidate_statereader.go +++ b/action/protocol/staking/candidate_statereader.go @@ -203,7 +203,7 @@ func (c *candSR) getTotalBucketCount() (uint64, error) { var tc totalBucketCount _, err := c.State( &tc, - protocol.NamespaceOption(StakingNameSpace), + protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(TotalBucketKey)) return tc.count, err } @@ -215,14 +215,14 @@ func (c *candSR) getBucket(index uint64) (*VoteBucket, error) { ) if _, err = c.State( &vb, - protocol.NamespaceOption(StakingNameSpace), + protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(bucketKey(index))); err != nil { return nil, err } var tc totalBucketCount if _, err := c.State( &tc, - protocol.NamespaceOption(StakingNameSpace), + protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(TotalBucketKey)); err != nil && errors.Cause(err) != state.ErrStateNotExist { return nil, err } @@ -234,7 +234,7 @@ func (c *candSR) getBucket(index uint64) (*VoteBucket, error) { func (c *candSR) getAllBuckets() ([]*VoteBucket, uint64, error) { height, iter, err := c.States( - protocol.NamespaceOption(StakingNameSpace), + protocol.NamespaceOption(_stakingNameSpace), protocol.KeysOption(func() ([][]byte, error) { // TODO (zhi): fix potential racing issue count, err := c.getTotalBucketCount() @@ -285,7 +285,7 @@ func (c *candSR) getBucketIndices(addr address.Address, prefix byte) (*BucketInd ) height, err := c.State( &bis, - protocol.NamespaceOption(StakingNameSpace), + protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(key)) if err != nil { return nil, height, err @@ -306,12 +306,12 @@ func (c *candSR) getCandidate(name address.Address) (*Candidate, uint64, error) return nil, 0, ErrNilParameters } var d Candidate - height, err := c.State(&d, protocol.NamespaceOption(CandidateNameSpace), protocol.KeyOption(name.Bytes())) + height, err := c.State(&d, protocol.NamespaceOption(_candidateNameSpace), protocol.KeyOption(name.Bytes())) return &d, height, err } func (c *candSR) getAllCandidates() (CandidateList, uint64, error) { - height, iter, err := c.States(protocol.NamespaceOption(CandidateNameSpace)) + height, iter, err := c.States(protocol.NamespaceOption(_candidateNameSpace)) if err != nil { return nil, height, err } @@ -336,7 +336,7 @@ func (c *candSR) NewBucketPool(enableSMStorage bool) (*BucketPool, error) { } if bp.enableSMStorage { - switch _, err := c.State(bp.total, protocol.NamespaceOption(StakingNameSpace), protocol.KeyOption(_bucketPoolAddrKey)); errors.Cause(err) { + switch _, err := c.State(bp.total, protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(_bucketPoolAddrKey)); errors.Cause(err) { case nil: return &bp, nil case state.ErrStateNotExist: diff --git a/action/protocol/staking/handlers_test.go b/action/protocol/staking/handlers_test.go index 1b9727afe5..51bb33dffa 100644 --- a/action/protocol/staking/handlers_test.go +++ b/action/protocol/staking/handlers_test.go @@ -65,7 +65,7 @@ func TestProtocol_HandleCreateStake(t *testing.T) { csr := newCandidateStateReader(sm) _, err := sm.PutState( &totalBucketCount{count: 0}, - protocol.NamespaceOption(StakingNameSpace), + protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(TotalBucketKey), ) require.NoError(err) @@ -2658,7 +2658,7 @@ func initAll(t *testing.T, ctrl *gomock.Controller) (protocol.StateManager, *Pro csm := newCandidateStateManager(sm) _, err := sm.PutState( &totalBucketCount{count: 0}, - protocol.NamespaceOption(StakingNameSpace), + protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(TotalBucketKey), ) require.NoError(err) diff --git a/action/protocol/staking/protocol.go b/action/protocol/staking/protocol.go index 69c10fa304..49ee758c1e 100644 --- a/action/protocol/staking/protocol.go +++ b/action/protocol/staking/protocol.go @@ -34,11 +34,11 @@ const ( // _protocolID is the protocol ID _protocolID = "staking" - // StakingNameSpace is the bucket name for staking state - StakingNameSpace = "Staking" + // _stakingNameSpace is the bucket name for staking state + _stakingNameSpace = "Staking" - // CandidateNameSpace is the bucket name for candidate state - CandidateNameSpace = "Candidate" + // _candidateNameSpace is the bucket name for candidate state + _candidateNameSpace = "Candidate" ) const ( @@ -239,7 +239,7 @@ func (p *Protocol) CreatePreStates(ctx context.Context, sm protocol.StateManager if err != nil { return err } - if _, err = sm.PutState(csr.BaseView().bucketPool.total, protocol.NamespaceOption(StakingNameSpace), protocol.KeyOption(_bucketPoolAddrKey)); err != nil { + if _, err = sm.PutState(csr.BaseView().bucketPool.total, protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(_bucketPoolAddrKey)); err != nil { return err } } diff --git a/action/protocol/staking/protocol_test.go b/action/protocol/staking/protocol_test.go index 7bb25c6951..365e6a9165 100644 --- a/action/protocol/staking/protocol_test.go +++ b/action/protocol/staking/protocol_test.go @@ -43,7 +43,7 @@ func TestProtocol(t *testing.T) { csmTemp := newCandidateStateManager(sm) _, err := sm.PutState( &totalBucketCount{count: 0}, - protocol.NamespaceOption(StakingNameSpace), + protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(TotalBucketKey), ) r.NoError(err) @@ -207,7 +207,7 @@ func TestCreatePreStates(t *testing.T) { _, err = NewCandidateStateManager(sm, true) require.Error(err) require.NoError(p.CreatePreStates(ctx, sm)) - _, err = sm.State(nil, protocol.NamespaceOption(StakingNameSpace), protocol.KeyOption(_bucketPoolAddrKey)) + _, err = sm.State(nil, protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(_bucketPoolAddrKey)) require.EqualError(errors.Cause(err), state.ErrStateNotExist.Error()) ctx = protocol.WithBlockCtx( ctx, @@ -216,7 +216,7 @@ func TestCreatePreStates(t *testing.T) { }, ) require.NoError(p.CreatePreStates(ctx, sm)) - _, err = sm.State(nil, protocol.NamespaceOption(StakingNameSpace), protocol.KeyOption(_bucketPoolAddrKey)) + _, err = sm.State(nil, protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(_bucketPoolAddrKey)) require.EqualError(errors.Cause(err), state.ErrStateNotExist.Error()) ctx = protocol.WithBlockCtx( ctx, @@ -226,7 +226,7 @@ func TestCreatePreStates(t *testing.T) { ) require.NoError(p.CreatePreStates(ctx, sm)) total := &totalAmount{} - _, err = sm.State(total, protocol.NamespaceOption(StakingNameSpace), protocol.KeyOption(_bucketPoolAddrKey)) + _, err = sm.State(total, protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(_bucketPoolAddrKey)) require.NoError(err) } diff --git a/action/protocol/staking/read_state.go b/action/protocol/staking/read_state.go index 49fe163aaf..0df2234849 100644 --- a/action/protocol/staking/read_state.go +++ b/action/protocol/staking/read_state.go @@ -76,7 +76,7 @@ func getTotalStakedAmount(ctx context.Context, csr CandidateStateReader) (*big.I if featureCtx.ReadStateFromDB(csr.Height()) { // after Greenland, read state from db var total totalAmount - h, err := csr.SR().State(&total, protocol.NamespaceOption(StakingNameSpace), protocol.KeyOption(_bucketPoolAddrKey)) + h, err := csr.SR().State(&total, protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(_bucketPoolAddrKey)) if err != nil { return nil, h, err } @@ -92,7 +92,7 @@ func getActiveBucketsCount(ctx context.Context, csr CandidateStateReader) (uint6 if featureCtx.ReadStateFromDB(csr.Height()) { // after Greenland, read state from db var total totalAmount - h, err := csr.SR().State(&total, protocol.NamespaceOption(StakingNameSpace), protocol.KeyOption(_bucketPoolAddrKey)) + h, err := csr.SR().State(&total, protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(_bucketPoolAddrKey)) if err != nil { return 0, h, err } diff --git a/action/protocol/staking/vote_bucket_test.go b/action/protocol/staking/vote_bucket_test.go index 3bd6f7cf9b..6cf6eaacf7 100644 --- a/action/protocol/staking/vote_bucket_test.go +++ b/action/protocol/staking/vote_bucket_test.go @@ -36,7 +36,7 @@ func TestGetPutStaking(t *testing.T) { csr := newCandidateStateReader(sm) sm.PutState( &totalBucketCount{count: 0}, - protocol.NamespaceOption(StakingNameSpace), + protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(TotalBucketKey), ) diff --git a/action/protocol/staking/vote_reviser_test.go b/action/protocol/staking/vote_reviser_test.go index eb54488bed..c7e2bf55e3 100644 --- a/action/protocol/staking/vote_reviser_test.go +++ b/action/protocol/staking/vote_reviser_test.go @@ -26,7 +26,7 @@ func TestVoteReviser(t *testing.T) { csr := newCandidateStateReader(sm) _, err := sm.PutState( &totalBucketCount{count: 0}, - protocol.NamespaceOption(StakingNameSpace), + protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(TotalBucketKey), ) r.NoError(err) diff --git a/api/http.go b/api/http.go index 66579ba1bd..f652fa336c 100644 --- a/api/http.go +++ b/api/http.go @@ -11,6 +11,7 @@ import ( apitypes "github.com/iotexproject/iotex-core/api/types" "github.com/iotexproject/iotex-core/pkg/log" + "github.com/iotexproject/iotex-core/pkg/util/httputil" ) type ( @@ -26,22 +27,17 @@ type ( ) // NewHTTPServer creates a new http server -// TODO: move timeout into config func NewHTTPServer(route string, port int, handler http.Handler) *HTTPServer { if port == 0 { return nil } - svr := &HTTPServer{ - svr: &http.Server{ - Addr: ":" + strconv.Itoa(port), - WriteTimeout: 30 * time.Second, - ReadHeaderTimeout: 10 * time.Second, - }, - } mux := http.NewServeMux() mux.Handle("/"+route, handler) - svr.svr.Handler = mux - return svr + + svr := httputil.NewServer(":"+strconv.Itoa(port), mux, httputil.ReadHeaderTimeout(10*time.Second)) + return &HTTPServer{ + svr: &svr, + } } // Start starts the http server diff --git a/e2etest/native_staking_test.go b/e2etest/native_staking_test.go index dd55f01f31..fd12745b9e 100644 --- a/e2etest/native_staking_test.go +++ b/e2etest/native_staking_test.go @@ -34,6 +34,8 @@ const ( _bucket _voterIndex _candIndex + _stakingNameSpace = "Staking" + _candidateNameSpace = "Candidate" candidate1Name = "candidate1" candidate2Name = "candidate2" @@ -226,12 +228,12 @@ func TestNativeStaking(t *testing.T) { // check buckets var bis staking.BucketIndices - _, err = sf.State(&bis, protocol.NamespaceOption(staking.StakingNameSpace), + _, err = sf.State(&bis, protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(staking.AddrKeyWithPrefix(voter1Addr, _voterIndex))) require.Error(err) require.Equal(state.ErrStateNotExist, errors.Cause(err)) - _, err = sf.State(&bis, protocol.NamespaceOption(staking.StakingNameSpace), + _, err = sf.State(&bis, protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(staking.AddrKeyWithPrefix(voter2Addr, _voterIndex))) require.NoError(err) require.Equal(2, len(bis)) @@ -378,12 +380,12 @@ func TestNativeStaking(t *testing.T) { require.Equal(hash.BytesToHash256(cand1Addr.Bytes()), logs[0].Topics[2]) // check buckets - _, err = sf.State(&bis, protocol.NamespaceOption(staking.StakingNameSpace), + _, err = sf.State(&bis, protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(staking.AddrKeyWithPrefix(cand1Addr, _voterIndex))) require.NoError(err) require.Equal(1, len(bis)) - _, err = sf.State(&bis, protocol.NamespaceOption(staking.StakingNameSpace), + _, err = sf.State(&bis, protocol.NamespaceOption(_stakingNameSpace), protocol.KeyOption(staking.AddrKeyWithPrefix(cand1Addr, _candIndex))) require.NoError(err) require.Equal(2, len(bis)) @@ -435,7 +437,7 @@ func checkCandidateState( candidateAddr address.Address, ) error { var cand staking.Candidate - if _, err := sr.State(&cand, protocol.NamespaceOption(staking.CandidateNameSpace), protocol.KeyOption(candidateAddr.Bytes())); err != nil { + if _, err := sr.State(&cand, protocol.NamespaceOption(_candidateNameSpace), protocol.KeyOption(candidateAddr.Bytes())); err != nil { return err } if expectedName != cand.Name { diff --git a/pkg/probe/probe.go b/pkg/probe/probe.go index d88f9a514a..6484e174af 100644 --- a/pkg/probe/probe.go +++ b/pkg/probe/probe.go @@ -55,7 +55,7 @@ func New(port int, opts ...Option) *Server { mux.HandleFunc("/health", readiness) mux.Handle("/metrics", promhttp.Handler()) - s.server = httputil.Server(fmt.Sprintf(":%d", port), mux) + s.server = httputil.NewServer(fmt.Sprintf(":%d", port), mux) return s } diff --git a/pkg/util/httputil/httputil.go b/pkg/util/httputil/httputil.go index d5dbea833b..5d3aa63194 100644 --- a/pkg/util/httputil/httputil.go +++ b/pkg/util/httputil/httputil.go @@ -10,19 +10,49 @@ import ( const ( _connectionCount = 400 - _readTimeout = 35 * time.Second - _writeTimeout = 35 * time.Second - _idleTimeout = 120 * time.Second ) -// Server creates a HTTP server with time out settings. -func Server(addr string, handler http.Handler) http.Server { +type ( + // ServerOption is a server option + ServerOption func(*serverConfig) + + serverConfig struct { + ReadHeaderTimeout time.Duration + ReadTimeout time.Duration + WriteTimeout time.Duration + IdleTimeout time.Duration + } +) + +// DefaultServerConfig is the default server config +var DefaultServerConfig = serverConfig{ + ReadHeaderTimeout: 5 * time.Second, + ReadTimeout: 30 * time.Second, + WriteTimeout: 30 * time.Second, + IdleTimeout: 120 * time.Second, +} + +// ReadHeaderTimeout sets header timeout +func ReadHeaderTimeout(h time.Duration) ServerOption { + return func(cfg *serverConfig) { + cfg.ReadHeaderTimeout = h + } +} + +// NewServer creates a HTTP server with time out settings. +func NewServer(addr string, handler http.Handler, opts ...ServerOption) http.Server { + cfg := DefaultServerConfig + for _, opt := range opts { + opt(&cfg) + } + return http.Server{ - ReadTimeout: _readTimeout, - WriteTimeout: _writeTimeout, - IdleTimeout: _idleTimeout, - Addr: addr, - Handler: handler, + ReadHeaderTimeout: cfg.ReadHeaderTimeout, + ReadTimeout: cfg.ReadTimeout, + WriteTimeout: cfg.WriteTimeout, + IdleTimeout: cfg.IdleTimeout, + Addr: addr, + Handler: handler, } } diff --git a/pkg/util/httputil/httputil_test.go b/pkg/util/httputil/httputil_test.go index 29189ed983..2c98dc9b78 100644 --- a/pkg/util/httputil/httputil_test.go +++ b/pkg/util/httputil/httputil_test.go @@ -15,13 +15,14 @@ func TestServer(t *testing.T) { addr := "myAddress" expectValue := http.Server{ - ReadTimeout: 35 * time.Second, - WriteTimeout: 35 * time.Second, - IdleTimeout: 120 * time.Second, - Addr: addr, - Handler: handler, + ReadHeaderTimeout: 2 * time.Second, + ReadTimeout: DefaultServerConfig.ReadTimeout, + WriteTimeout: DefaultServerConfig.WriteTimeout, + IdleTimeout: DefaultServerConfig.IdleTimeout, + Addr: addr, + Handler: handler, } - result := Server(addr, handler) + result := NewServer(addr, handler, ReadHeaderTimeout(2*time.Second)) require.Equal(t, expectValue, result) }) } diff --git a/server/itx/server.go b/server/itx/server.go index 1c550b6886..69633b6ad3 100644 --- a/server/itx/server.go +++ b/server/itx/server.go @@ -243,7 +243,7 @@ func StartServer(ctx context.Context, svr *Server, probeSvr *probe.Server, cfg c mux.Handle("/debug/pprof/trace", http.HandlerFunc(pprof.Trace)) port := fmt.Sprintf(":%d", cfg.System.HTTPAdminPort) - adminserv = httputil.Server(port, mux) + adminserv = httputil.NewServer(port, mux) defer func() { if err := adminserv.Shutdown(ctx); err != nil { log.L().Error("Error when serving metrics data.", zap.Error(err))