github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/engine/pkg/clock/clock.go (about)

     1  // Copyright 2022 PingCAP, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package clock
    15  
    16  import (
    17  	"time"
    18  
    19  	bclock "github.com/benbjohnson/clock"
    20  	"github.com/gavv/monotime"
    21  )
    22  
    23  type (
    24  	// MonotonicTime alias to time.Duration
    25  	MonotonicTime time.Duration
    26  )
    27  
    28  var unixEpoch = time.Unix(0, 0)
    29  
    30  // Clock defines an interface that combines github.com/benbjohnson/clock.Clock
    31  // and a Mono methods that can return a monotonic time duration
    32  type Clock interface {
    33  	bclock.Clock
    34  	Mono() MonotonicTime
    35  }
    36  
    37  type withRealMono struct {
    38  	bclock.Clock
    39  }
    40  
    41  func (r withRealMono) Mono() MonotonicTime {
    42  	return MonotonicTime(monotime.Now())
    43  }
    44  
    45  // Mock is a mock struct that implements Clock interface
    46  type Mock struct {
    47  	*bclock.Mock
    48  }
    49  
    50  // Mono implements Clock.Mono
    51  func (r Mock) Mono() MonotonicTime {
    52  	return MonotonicTime(r.Now().Sub(unixEpoch))
    53  }
    54  
    55  // New creates a new withRealMono instance, which implements Clock interface
    56  func New() Clock {
    57  	return withRealMono{bclock.New()}
    58  }
    59  
    60  // NewMock creates a new Mock instance
    61  func NewMock() *Mock {
    62  	return &Mock{bclock.NewMock()}
    63  }
    64  
    65  // Sub returns time difference between two MonotonicTime
    66  func (m MonotonicTime) Sub(other MonotonicTime) time.Duration {
    67  	return time.Duration(m - other)
    68  }
    69  
    70  // MonoNow returns the MonotonicTime of current
    71  func MonoNow() MonotonicTime {
    72  	return MonotonicTime(monotime.Now())
    73  }
    74  
    75  // ToMono converts time.Time to MonotonicTime
    76  func ToMono(t time.Time) MonotonicTime {
    77  	return MonotonicTime(t.Sub(unixEpoch))
    78  }