github.com/erda-project/erda-infra@v1.0.9/base/servicehub/event.go (about)

     1  // Copyright (c) 2021 Terminus, 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  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package servicehub
    16  
    17  // Events events about Hub
    18  type Events interface {
    19  	Initialized() <-chan error
    20  	Started() <-chan error
    21  	Exited() <-chan error
    22  }
    23  
    24  type events struct {
    25  	_initialized bool
    26  	_started     bool
    27  	initialized  chan error
    28  	started      chan error
    29  	exited       chan error
    30  }
    31  
    32  func newEvents() *events {
    33  	return &events{
    34  		initialized: make(chan error, 1),
    35  		started:     make(chan error, 1),
    36  		exited:      make(chan error, 1),
    37  	}
    38  }
    39  
    40  func (e *events) Initialized() <-chan error {
    41  	return e.initialized
    42  }
    43  
    44  func (e *events) Started() <-chan error {
    45  	return e.started
    46  }
    47  
    48  func (e *events) Exited() <-chan error {
    49  	return e.exited
    50  }
    51  
    52  // Events return Events
    53  func (h *Hub) Events() Events {
    54  	events := newEvents()
    55  	h.listeners = append(h.listeners, &DefaultListener{
    56  		AfterInitFunc: func(h *Hub) error {
    57  			events._initialized = true
    58  			close(events.initialized)
    59  			return nil
    60  		},
    61  		AfterStartFunc: func(h *Hub) error {
    62  			events._started = true
    63  			close(events.started)
    64  			return nil
    65  		},
    66  		BeforeExitFunc: func(h *Hub, err error) error {
    67  			if !events._initialized {
    68  				events.initialized <- err
    69  				close(events.initialized)
    70  			}
    71  			if !events._started {
    72  				events.started <- err
    73  				close(events.started)
    74  			}
    75  			events.exited <- err
    76  			close(events.exited)
    77  			return nil
    78  		},
    79  	})
    80  	return events
    81  }