// TriggerEventHandler perform search query and trigger EventHandler in context of each chat/user
760377
func (s *Service) TriggerEventHandler(queryChat bool, bsonQuery map[string]interface{}, data interface{}) error {

	if s.EventHandler == nil {
		return fmt.Errorf("EventHandler missed for %s service", s.Name)
	}

	if bsonQuery == nil {
		return nil
	}

	db := mongoSession.Clone().DB(mongo.Database)
	defer db.Session.Close()

	ctx := &Context{db: db, ServiceName: s.Name}
	atLeastOneWasHandled := false

	if queryChat {
		chats, err := ctx.FindChats(bsonQuery)

		if err != nil {
			s.Log().WithError(err).Error("FindChats error")
		}
		for _, chat := range chats {
			if chat.Deactivated || chat.BotWasKickedOrStopped() {
				continue
			}
			ctx.Chat = chat.Chat
			err := s.EventHandler(ctx, data)

			if err != nil {
				ctx.Log().WithError(err).Error("EventHandler returned error")
			} else {
				atLeastOneWasHandled = true
			}
		}
	} else {
		users, err := ctx.FindUsers(bsonQuery)

		if err != nil {
			s.Log().WithError(err).Error("findUsers error")
		}

		for _, user := range users {
			ctx.User = user.User
			ctx.User.ctx = ctx
			ctx.Chat = Chat{ID: user.ID, ctx: ctx}
			err := s.EventHandler(ctx, data)

			if err != nil {
				ctx.Log().WithError(err).Error("EventHandler returned error")
			} else {
				atLeastOneWasHandled = true
			}
		}
	}

	if !atLeastOneWasHandled {
		return errors.New("No single chat was handled")
	}
	return nil
}
767081
func (s *Server) EventsEnabled() bool {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.eventsEnabled()
}
658683
func (p *Parser) handleEvents(rawEvents <-chan []string, send chan<- event.Event, wg *sync.WaitGroup) {
	defer wg.Done()
	// TODO: spin up a group of goroutines to do this
	for rawEvent := range rawEvents {
		ev := p.handleEvent(rawEvent)
		if ev != nil {
			send <- *ev
		}
	}
}
869731
func (w *Webhook) UpdateEvent() error {
	data, err := jsoniter.Marshal(w.HookEvent)
	w.Events = string(data)
	return err
}
196136
func (hs Handlers) HandleEvent(ctx context.Context, e *executor.Event) (err error) {
	if h := hs[e.GetType()]; h != nil {
		return h.HandleEvent(ctx, e)
	}
	return nil
}
645372
func (h EventHandlerFunc) HandleEvent(ctx context.Context, e Event) error {
	return h(ctx, e)
}
842040
func eventHandler(w http.ResponseWriter, r *http.Request) {
	if r.Body != nil {
		defer r.Body.Close()
	}

	ctx := r.Context()

	switch r.Method {
	// Get all events
	case http.MethodGet:
		events, err := getEvents(Configuration.Service.ReadMaxLimit)
		if err != nil {
			LoggingClient.Error(err.Error())
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		encode(events, w)
		break
		// Post a new event
	case http.MethodPost:
		contentType := r.Header.Get(clients.ContentType)
		if contentType == clients.ContentTypeCBOR {
			errMsg := "CBOR payload is not yet supported"
			http.Error(w, errMsg, http.StatusNotImplemented)
			LoggingClient.Error(errMsg)

			return
		}

		var e models.Event
		dec := json.NewDecoder(r.Body)
		err := dec.Decode(&e)

		// Problem Decoding Event
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			LoggingClient.Error("Error decoding event: " + err.Error())
			return
		}

		LoggingClient.Info("Posting Event: " + e.String())

		newId, err := addNewEvent(e, ctx)
		if err != nil {
			switch t := err.(type) {
			case *errors.ErrValueDescriptorNotFound:
				http.Error(w, t.Error(), http.StatusBadRequest)
			case *errors.ErrValueDescriptorInvalid:
				http.Error(w, t.Error(), http.StatusBadRequest)
			default:
				http.Error(w, t.Error(), http.StatusInternalServerError)
			}
			LoggingClient.Error(err.Error())
			return
		}

		w.WriteHeader(http.StatusOK)
		w.Write([]byte(newId))

		break
		// Do not update the readings
	case http.MethodPut:
		contentType := r.Header.Get(clients.ContentType)
		if contentType == clients.ContentTypeCBOR {
			errMsg := "CBOR payload is not yet supported"
			http.Error(w, errMsg, http.StatusNotImplemented)
			LoggingClient.Error(errMsg)

			return
		}

		var from models.Event
		dec := json.NewDecoder(r.Body)
		err := dec.Decode(&from)

		// Problem decoding event
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			LoggingClient.Error("Error decoding the event: " + err.Error())
			return
		}

		LoggingClient.Info("Updating event: " + from.ID)
		err = updateEvent(from, ctx)
		if err != nil {
			switch t := err.(type) {
			case *errors.ErrEventNotFound:
				http.Error(w, t.Error(), http.StatusNotFound)
			default:
				http.Error(w, t.Error(), http.StatusInternalServerError)
			}
			LoggingClient.Error(err.Error())
			return
		}

		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("true"))
	}
}
121062
func (h *handler) HandleEvent(ctx context.Context, event eh.Event) error {
	select {
	case h.ch <- event:
	default:
		return fmt.Errorf("missed event: %s", event)
	}
	return nil
}
148072
func NewEventHandler(handlerType string) *EventHandler {
	return &EventHandler{
		Type:    handlerType,
		Events:  []eh.Event{},
		Context: context.Background(),
		Recv:    make(chan eh.Event, 10),
	}
}
947367
func (remote *RemoteDebugger) CallbackEvent(method string, cb EventCallback) {
	remote.Lock()
	remote.callbacks[method] = cb
	remote.Unlock()
}
849324
func (p *GuestListProjector) HandleEvent(ctx context.Context, event eh.Event) error {
	// NOTE: Temp fix because we need to count the guests atomically.
	p.repoMu.Lock()
	defer p.repoMu.Unlock()

	// Load or create the guest list.
	var g *GuestList
	m, err := p.repo.Find(ctx, p.eventID)
	if rrErr, ok := err.(eh.RepoError); ok && rrErr.Err == eh.ErrEntityNotFound {
		g = &GuestList{
			ID: p.eventID,
		}
	} else if err != nil {
		return err
	} else {
		var ok bool
		g, ok = m.(*GuestList)
		if !ok {
			return errors.New("projector: incorrect entity type")
		}
	}

	// Apply the count of the guests.
	switch event.EventType() {
	case InviteAcceptedEvent:
		g.NumAccepted++
		g.NumGuests++

	case InviteDeclinedEvent:
		g.NumDeclined++
		g.NumGuests++

	case InviteConfirmedEvent:
		g.NumConfirmed++

	case InviteDeniedEvent:
		g.NumDenied++

	default:
		return errors.New("could not handle event: " + event.String())
	}

	if err := p.repo.Save(ctx, g); err != nil {
		return errors.New("projector: could not save: " + err.Error())
	}

	return nil
}
384929
func (c *ServiceConfig) RegisterEventHandler(handler ServiceHandler) {
	c.eventHandlers = append(c.eventHandlers, handler)
}
435758
func (s *Serf) handleUserEvent(eventMsg *messageUserEvent) bool {
	// Witness a potentially newer time
	s.eventClock.Witness(eventMsg.LTime)

	s.eventLock.Lock()
	defer s.eventLock.Unlock()

	// Ignore if it is before our minimum event time
	if eventMsg.LTime < s.eventMinTime {
		return false
	}

	// Check if this message is too old
	curTime := s.eventClock.Time()
	if curTime > LamportTime(len(s.eventBuffer)) &&
		eventMsg.LTime < curTime-LamportTime(len(s.eventBuffer)) {
		s.logger.Printf(
			"[WARN] serf: received old event %s from time %d (current: %d)",
			eventMsg.Name,
			eventMsg.LTime,
			s.eventClock.Time())
		return false
	}

	// Check if we've already seen this
	idx := eventMsg.LTime % LamportTime(len(s.eventBuffer))
	seen := s.eventBuffer[idx]
	userEvent := userEvent{Name: eventMsg.Name, Payload: eventMsg.Payload}
	if seen != nil && seen.LTime == eventMsg.LTime {
		for _, previous := range seen.Events {
			if previous.Equals(&userEvent) {
				return false
			}
		}
	} else {
		seen = &userEvents{LTime: eventMsg.LTime}
		s.eventBuffer[idx] = seen
	}

	// Add to recent events
	seen.Events = append(seen.Events, userEvent)

	// Update some metrics
	metrics.IncrCounter([]string{"serf", "events"}, 1)
	metrics.IncrCounter([]string{"serf", "events", eventMsg.Name}, 1)

	if s.config.EventCh != nil {
		s.config.EventCh <- UserEvent{
			LTime:    eventMsg.LTime,
			Name:     eventMsg.Name,
			Payload:  eventMsg.Payload,
			Coalesce: eventMsg.CC,
		}
	}
	return true
}
671260
func (b *serverBuilder) GetEventHandler(event ServerBuildEvents) *ServerBuildEventHandler {
	if handler, ok := b.buildEventHandlers[event]; ok {
		return &handler
	}
	return nil
}
762190
func unexpectedEventHandler(ctx *VmContext, ev VmEvent, state string) {
	switch ev.Event() {
	case COMMAND_SHUTDOWN,
		COMMAND_RELEASE,
		COMMAND_PAUSEVM:
		ctx.reportUnexpectedRequest(ev, state)
	default:
		ctx.Log(WARNING, "got unexpected event during ", state)
	}
}
1064011
func (b *DiskBuilder) SetEventHandler(event DiskBuildEvents, handler DiskBuildEventHandler) {
	b.buildEventHandlers[event] = handler
}
984996
func trigger(phase string, stack []plugin.Plugin, ctx *c.Context) *c.Context {
	var wg sync.WaitGroup
	wg.Add(1)

	// Finisher function
	done := func(_ctx *c.Context) {
		ctx = _ctx
		wg.Done()
	}

	i := len(stack)
	if i == 0 {
		wg.Done()
		return ctx
	}

	next := done
	for i > 0 {
		i--
		next = nextHandler(phase, stack[i], next, done)
	}

	// Exposes current middleware phase via context
	ctx.Set("$phase", phase)

	// Triggers the middleware call chain
	next(ctx)

	wg.Wait()
	return ctx
}