gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/lifecycle/lifecycle.go (about)

     1  package lifecycle
     2  
     3  import (
     4  	"fmt"
     5  	"gitee.com/sy_183/go-common/errors"
     6  	"gitee.com/sy_183/go-common/lock"
     7  	"sync"
     8  	"sync/atomic"
     9  )
    10  
    11  type (
    12  	OnStartingFunc = func(Lifecycle)
    13  	OnStartedFunc  = func(Lifecycle, error)
    14  	OnCloseFunc    = func(Lifecycle, error)
    15  	OnClosedFunc   = func(Lifecycle, error)
    16  )
    17  
    18  type Lifecycle interface {
    19  	Run() error
    20  
    21  	Background() error
    22  
    23  	Start() error
    24  
    25  	StartedWaiter() <-chan error
    26  
    27  	Close(future Future[error]) error
    28  
    29  	ClosedWaiter() <-chan error
    30  
    31  	Shutdown() error
    32  
    33  	AddStartedFuture(future Future[error]) Future[error]
    34  
    35  	AddClosedFuture(future Future[error]) Future[error]
    36  
    37  	OnStarting(OnStartingFunc) Lifecycle
    38  
    39  	OnStarted(OnStartedFunc) Lifecycle
    40  
    41  	OnClose(OnCloseFunc) Lifecycle
    42  
    43  	OnClosed(OnClosedFunc) Lifecycle
    44  
    45  	SetOnStarting(OnStartingFunc) Lifecycle
    46  
    47  	SetOnStarted(OnStartedFunc) Lifecycle
    48  
    49  	SetOnClose(OnCloseFunc) Lifecycle
    50  
    51  	SetOnClosed(OnClosedFunc) Lifecycle
    52  
    53  	Field(name string) any
    54  
    55  	Fields() map[string]any
    56  
    57  	SetField(name string, value any) Lifecycle
    58  
    59  	SetDefaultField(name string, defaultValue any) (value any, exist bool)
    60  
    61  	DeleteField(name string) Lifecycle
    62  
    63  	RemoveField(name string) any
    64  
    65  	RangeField(f func(name string, value any) bool) Lifecycle
    66  
    67  	Error() error
    68  }
    69  
    70  func AddRunningFuture[FUTURE Future[error]](lifecycle Lifecycle, future FUTURE) FUTURE {
    71  	lifecycle.AddStartedFuture(future)
    72  	return future
    73  }
    74  
    75  func AddClosedFuture[FUTURE Future[error]](lifecycle Lifecycle, future FUTURE) FUTURE {
    76  	lifecycle.AddClosedFuture(future)
    77  	return future
    78  }
    79  
    80  func GetField[V any](l Lifecycle, name string) (v V) {
    81  	if value := l.Field(name); value != nil {
    82  		if r, is := value.(V); is {
    83  			v = r
    84  		}
    85  	}
    86  	return
    87  }
    88  
    89  func SetDefaultField[V any](l Lifecycle, name string, defaultValue V) (value V, exist bool) {
    90  	v, e := l.SetDefaultField(name, defaultValue)
    91  	if e {
    92  		if r, is := v.(V); is {
    93  			value = r
    94  			exist = true
    95  		}
    96  	}
    97  	return
    98  }
    99  
   100  func RemoveField[V any](l Lifecycle, name string) (v V) {
   101  	if value := l.RemoveField(name); value != nil {
   102  		if r, is := value.(V); is {
   103  			v = r
   104  		}
   105  	}
   106  	return
   107  }
   108  
   109  type defaultLifecycleClass interface {
   110  	// 在前台运行组件
   111  	doRun() error
   112  
   113  	// 在确定组件可以启动后,执行启动流程并在前台运行组件
   114  	run() error
   115  
   116  	// 检查组件是否可以启动,返回错误则不能启动
   117  	startCheck() error
   118  
   119  	// 检查组件是否已经启动,是否可以启动,如果返回的runnable为false,则不能启动,如果err
   120  	// 不为nil,则是检查组件是否可以启动返回的错误
   121  	preStart() (runnable bool, err error)
   122  
   123  	// 在确定组件可以启动后,执行启动流程,如果返回的runnable为false,则不能运行,如果err
   124  	// 不为nil,则是执行启动流程返回的错误
   125  	doStart() (runnable bool, err error)
   126  
   127  	// 检查组件是否可以启动并执行启动流程,如果返回的runnable为false,则不能运行,如果err
   128  	// 不为nil,则是检查组件是否可以启动返回的错误,或是执行启动流程返回的错误
   129  	start() (runnable bool, err error)
   130  
   131  	// 检查组件是否可以关闭,返回错误则不能关闭
   132  	closeCheck() error
   133  
   134  	// 检查组件是否可以关闭并执行关闭流程,返回错误则说明关闭失败,组件的状态未改变
   135  	doClose(future Future[error]) error
   136  
   137  	doOnStarting()
   138  
   139  	doOnStarted(err error)
   140  
   141  	doOnClose(err error)
   142  
   143  	doOnClosed(err error)
   144  
   145  	lock.RLocker
   146  
   147  	fmt.Stringer
   148  }
   149  
   150  type defaultLifecycle interface {
   151  	Lifecycle
   152  
   153  	defaultLifecycleClass
   154  }
   155  
   156  type DefaultLifecycle struct {
   157  	this   defaultLifecycle
   158  	runner Runner
   159  
   160  	runningFutures SyncFutures[error]
   161  	closedFutures  SyncFutures[error]
   162  
   163  	err atomic.Pointer[error]
   164  
   165  	onStarting     []OnStartingFunc
   166  	onStartingLock sync.Mutex
   167  
   168  	onStarted     []OnStartedFunc
   169  	onStartedLock sync.Mutex
   170  
   171  	onClose     []OnCloseFunc
   172  	onCloseLock sync.Mutex
   173  
   174  	onClosed     []OnClosedFunc
   175  	onClosedLock sync.Mutex
   176  
   177  	fields sync.Map
   178  
   179  	State
   180  	sync.RWMutex
   181  }
   182  
   183  func New(options ...Option) *DefaultLifecycle {
   184  	lifecycle := new(DefaultLifecycle)
   185  	lifecycle.init(lifecycle, options...)
   186  	return lifecycle
   187  }
   188  
   189  func NewWithRunner(runner Runner, options ...Option) *DefaultLifecycle {
   190  	return New(append(options, WithRunner(runner))...)
   191  }
   192  
   193  func NewWithRun(startFn StartFunc, runFn RunFunc, closeFn CloseFunc, options ...Option) *DefaultLifecycle {
   194  	return NewWithRunner(FuncRunner(startFn, runFn, closeFn), options...)
   195  }
   196  
   197  func NewWithInterruptedRunner(runner InterruptedRunner, options ...Option) *DefaultLifecycle {
   198  	return New(append(options, WithInterruptedRunner(runner))...)
   199  }
   200  
   201  func NewWithInterruptedRun(startFn InterruptedStartFunc, runFn InterruptedRunFunc, options ...Option) *DefaultLifecycle {
   202  	return NewWithInterruptedRunner(FuncInterruptedRunner(startFn, runFn), options...)
   203  }
   204  
   205  func NewWithStarter(starter Starter, options ...Option) *DefaultLifecycle {
   206  	return New(append(options, WithStarter(starter))...)
   207  }
   208  
   209  func NewWithStart(starterFn StarterFunc, options ...Option) *DefaultLifecycle {
   210  	return NewWithStarter(FuncStarter(starterFn), options...)
   211  }
   212  
   213  func NewWithInterruptedStarter(starter InterruptedStarter, options ...Option) *DefaultLifecycle {
   214  	return New(append(options, WithInterruptedStarter(starter))...)
   215  }
   216  
   217  func NewWithInterruptedStart(starterFn InterruptedStarterFunc, options ...Option) *DefaultLifecycle {
   218  	return NewWithInterruptedStarter(FuncInterruptedStarter(starterFn), options...)
   219  }
   220  
   221  func (l *DefaultLifecycle) init(self defaultLifecycle, options ...Option) {
   222  	l.this = self
   223  	for _, option := range options {
   224  		option.Apply(self)
   225  	}
   226  	if l.runner == nil {
   227  		l.runner = FuncRunner(nil, nil, nil)
   228  	}
   229  }
   230  
   231  func (l *DefaultLifecycle) self() defaultLifecycle {
   232  	return l.this
   233  }
   234  
   235  func (l *DefaultLifecycle) setSelf(self any) {
   236  	if this, is := self.(defaultLifecycle); is {
   237  		l.this = this
   238  	}
   239  }
   240  
   241  func (l *DefaultLifecycle) setRunner(runner Runner) {
   242  	l.runner = runner
   243  }
   244  
   245  func (l *DefaultLifecycle) doRun() error {
   246  	err := l.runner.DoRun(l.self())
   247  	l.err.Store(&err)
   248  	l.doOnClosed(err)
   249  	lock.LockGet[Futures[error]](l, func() Futures[error] {
   250  		l.ToClosed()
   251  		return l.closedFutures.LoadAndReset()
   252  	}).Complete(err)
   253  	return err
   254  }
   255  
   256  func (l *DefaultLifecycle) run() error {
   257  	if runnable, err := l.self().doStart(); !runnable {
   258  		return err
   259  	}
   260  	return l.self().doRun()
   261  }
   262  
   263  func (l *DefaultLifecycle) Run() error {
   264  	if runnable, err := l.self().start(); !runnable {
   265  		return err
   266  	}
   267  	return l.self().doRun()
   268  }
   269  
   270  func (l *DefaultLifecycle) Background() error {
   271  	if runnable, err := l.self().preStart(); !runnable {
   272  		return err
   273  	}
   274  	go l.self().run()
   275  	return nil
   276  }
   277  
   278  func (l *DefaultLifecycle) startCheck() error {
   279  	return nil
   280  }
   281  
   282  func (l *DefaultLifecycle) preStart() (runnable bool, err error) {
   283  	runnable, err = lock.LockGetDouble(l, func() (runnable bool, err error) {
   284  		if !l.Closed() {
   285  			return
   286  		}
   287  		err = l.self().startCheck()
   288  		l.err.Store(&err)
   289  		if err != nil {
   290  			return
   291  		}
   292  		runnable = true
   293  		l.ToStarting()
   294  		return
   295  	})
   296  	if runnable {
   297  		l.doOnStarting()
   298  	}
   299  	return
   300  }
   301  
   302  func (l *DefaultLifecycle) doStart() (runnable bool, err error) {
   303  	err = l.runner.DoStart(l.self())
   304  	if err != nil {
   305  		l.err.Store(&err)
   306  		l.doOnStarted(err)
   307  		runningFutures, closedFutures := lock.LockGetDouble(l, func() (Futures[error], Futures[error]) {
   308  			l.ToClosed()
   309  			return l.runningFutures.LoadAndReset(), l.closedFutures.LoadAndReset()
   310  		})
   311  		runningFutures.Complete(err)
   312  		closedFutures.Complete(err)
   313  		return
   314  	}
   315  	l.doOnStarted(nil)
   316  	lock.LockGet(l, func() Futures[error] {
   317  		if !l.Closing() {
   318  			l.ToRunning()
   319  		}
   320  		runnable = true
   321  		return l.runningFutures.LoadAndReset()
   322  	}).Complete(nil)
   323  	return
   324  }
   325  
   326  func (l *DefaultLifecycle) start() (runnable bool, err error) {
   327  	runnable, err = l.self().preStart()
   328  	if !runnable {
   329  		return
   330  	}
   331  	return l.self().doStart()
   332  }
   333  
   334  func (l *DefaultLifecycle) Start() error {
   335  	if runnable, err := l.self().start(); !runnable {
   336  		return err
   337  	}
   338  	go l.self().doRun()
   339  	return nil
   340  }
   341  
   342  func (l *DefaultLifecycle) StartedWaiter() <-chan error {
   343  	return AddRunningFuture(l.self(), make(ChanFuture[error], 1))
   344  }
   345  
   346  func (l *DefaultLifecycle) closeCheck() error {
   347  	return nil
   348  }
   349  
   350  func (l *DefaultLifecycle) doClose(future Future[error]) error {
   351  	if err := l.self().closeCheck(); err != nil {
   352  		return err
   353  	}
   354  	if err := l.runner.DoClose(l.self()); err != nil {
   355  		return err
   356  	}
   357  	l.ToClosing()
   358  	l.closedFutures.Append(future)
   359  	return nil
   360  }
   361  
   362  func (l *DefaultLifecycle) Close(future Future[error]) error {
   363  	var closed bool
   364  	var closing bool
   365  	if err := lock.LockGet[error](l, func() error {
   366  		if closed = l.Closed(); !closed {
   367  			if closing = l.Closing(); !closing {
   368  				return l.self().doClose(future)
   369  			}
   370  			l.closedFutures.Append(future)
   371  			return nil
   372  		}
   373  		return l.self().Error()
   374  	}); !closed {
   375  		if !closing {
   376  			l.doOnClose(err)
   377  		}
   378  		return err
   379  	} else {
   380  		if future != nil {
   381  			future.Complete(err)
   382  		}
   383  		return nil
   384  	}
   385  }
   386  
   387  func (l *DefaultLifecycle) ClosedWaiter() <-chan error {
   388  	return AddClosedFuture(l.self(), make(ChanFuture[error], 1))
   389  }
   390  
   391  func (l *DefaultLifecycle) Shutdown() error {
   392  	if err := l.self().Close(nil); err != nil {
   393  		return err
   394  	}
   395  	<-l.self().ClosedWaiter()
   396  	return nil
   397  }
   398  
   399  func (l *DefaultLifecycle) AddStartedFuture(future Future[error]) Future[error] {
   400  	if future == nil {
   401  		return nil
   402  	}
   403  	if lock.RLockGet(l, func() (completed bool) {
   404  		if completed = l.Running() || l.Closing(); !completed {
   405  			l.runningFutures.Append(future)
   406  		}
   407  		return
   408  	}) {
   409  		future.Complete(l.self().Error())
   410  	}
   411  	return future
   412  }
   413  
   414  func (l *DefaultLifecycle) AddClosedFuture(future Future[error]) Future[error] {
   415  	if future == nil {
   416  		return nil
   417  	}
   418  	if lock.RLockGet(l, func() (completed bool) {
   419  		if completed = l.Closed(); !completed {
   420  			l.closedFutures.Append(future)
   421  		}
   422  		return
   423  	}) {
   424  		future.Complete(l.self().Error())
   425  	}
   426  	return future
   427  }
   428  
   429  func (l *DefaultLifecycle) OnStarting(onStarting OnStartingFunc) Lifecycle {
   430  	if onStarting != nil {
   431  		lock.LockDo(&l.onStartingLock, func() { l.onStarting = append(l.onStarting, onStarting) })
   432  	}
   433  	return l.self()
   434  }
   435  
   436  func (l *DefaultLifecycle) OnStarted(onStarted OnStartedFunc) Lifecycle {
   437  	if onStarted != nil {
   438  		lock.LockDo(&l.onStartedLock, func() { l.onStarted = append(l.onStarted, onStarted) })
   439  	}
   440  	return l.self()
   441  }
   442  
   443  func (l *DefaultLifecycle) OnClose(onClose OnCloseFunc) Lifecycle {
   444  	if onClose != nil {
   445  		lock.LockDo(&l.onCloseLock, func() { l.onClose = append(l.onClose, onClose) })
   446  	}
   447  	return l.self()
   448  }
   449  
   450  func (l *DefaultLifecycle) OnClosed(onClosed OnClosedFunc) Lifecycle {
   451  	if onClosed != nil {
   452  		lock.LockDo(&l.onClosedLock, func() { l.onClosed = append(l.onClosed, onClosed) })
   453  	}
   454  	return l.self()
   455  }
   456  
   457  func (l *DefaultLifecycle) SetOnStarting(onStarting OnStartingFunc) Lifecycle {
   458  	lock.LockDo(&l.onStartingLock, func() {
   459  		if onStarting == nil {
   460  			l.onStarting = l.onStarting[:0]
   461  		} else {
   462  			l.onStarting = append(l.onStarting, onStarting)
   463  		}
   464  	})
   465  	return l.self()
   466  }
   467  
   468  func (l *DefaultLifecycle) SetOnStarted(onStarted OnStartedFunc) Lifecycle {
   469  	lock.LockDo(&l.onStartedLock, func() {
   470  		if onStarted == nil {
   471  			l.onStarted = l.onStarted[:0]
   472  		} else {
   473  			l.onStarted = append(l.onStarted, onStarted)
   474  		}
   475  	})
   476  	return l.self()
   477  }
   478  
   479  func (l *DefaultLifecycle) SetOnClose(onClose OnCloseFunc) Lifecycle {
   480  	lock.LockDo(&l.onCloseLock, func() {
   481  		if onClose == nil {
   482  			l.onClose = l.onClose[:0]
   483  		} else {
   484  			l.onClose = append(l.onClose, onClose)
   485  		}
   486  	})
   487  	return l.self()
   488  }
   489  
   490  func (l *DefaultLifecycle) SetOnClosed(onClosed OnClosedFunc) Lifecycle {
   491  	lock.LockDo(&l.onClosedLock, func() {
   492  		if onClosed == nil {
   493  			l.onClosed = l.onClosed[:0]
   494  		} else {
   495  			l.onClosed = append(l.onClosed, onClosed)
   496  		}
   497  	})
   498  	return l.self()
   499  }
   500  
   501  func (l *DefaultLifecycle) doOnStarting() {
   502  	lock.LockDo(&l.onStartingLock, func() {
   503  		for _, callback := range l.onStarting {
   504  			callback(l.self())
   505  		}
   506  	})
   507  }
   508  
   509  func (l *DefaultLifecycle) doOnStarted(err error) {
   510  	lock.LockDo(&l.onStartedLock, func() {
   511  		for _, callback := range l.onStarted {
   512  			callback(l.self(), err)
   513  		}
   514  	})
   515  }
   516  
   517  func (l *DefaultLifecycle) doOnClose(err error) {
   518  	lock.LockDo(&l.onCloseLock, func() {
   519  		for _, callback := range l.onClose {
   520  			callback(l.self(), err)
   521  		}
   522  	})
   523  }
   524  
   525  func (l *DefaultLifecycle) doOnClosed(err error) {
   526  	lock.LockDo(&l.onClosedLock, func() {
   527  		for _, callback := range l.onClosed {
   528  			callback(l.self(), err)
   529  		}
   530  	})
   531  }
   532  
   533  func (l *DefaultLifecycle) Field(name string) (value any) {
   534  	value, _ = l.fields.Load(name)
   535  	return
   536  }
   537  
   538  func (l *DefaultLifecycle) Fields() map[string]any {
   539  	fields := make(map[string]any)
   540  	l.self().RangeField(func(name string, value any) bool {
   541  		fields[name] = value
   542  		return true
   543  	})
   544  	return fields
   545  }
   546  
   547  func (l *DefaultLifecycle) SetField(name string, value any) Lifecycle {
   548  	if value == nil {
   549  		panic(errors.New("属性值不允许为空"))
   550  	}
   551  	l.fields.Store(name, value)
   552  	return l.self()
   553  }
   554  
   555  func (l *DefaultLifecycle) SetDefaultField(name string, defaultValue any) (value any, exist bool) {
   556  	return l.fields.LoadOrStore(name, defaultValue)
   557  }
   558  
   559  func (l *DefaultLifecycle) DeleteField(name string) Lifecycle {
   560  	l.fields.Delete(name)
   561  	return l.self()
   562  }
   563  
   564  func (l *DefaultLifecycle) RemoveField(name string) (value any) {
   565  	value, _ = l.fields.LoadAndDelete(name)
   566  	return
   567  }
   568  
   569  func (l *DefaultLifecycle) RangeField(f func(name string, value any) bool) Lifecycle {
   570  	l.fields.Range(func(key, value any) bool { return f(key.(string), value) })
   571  	return l.self()
   572  }
   573  
   574  func (l *DefaultLifecycle) Error() error {
   575  	if err := l.err.Load(); err != nil {
   576  		return *err
   577  	}
   578  	return nil
   579  }
   580  
   581  func (l *DefaultLifecycle) String() string {
   582  	return fmt.Sprintf("生命周期组件(%p)[%s]", l, lock.RLockGet(l, func() State { return l.State }))
   583  }