Exemple #1
0
// GetRepoEvents will upgrade the connection to a Websocket and will stream
// event updates to the browser.
func GetRepoEvents(c *gin.Context) {
	repo := session.Repo(c)
	c.Writer.Header().Set("Content-Type", "text/event-stream")

	eventc := make(chan *bus.Event, 1)
	bus.Subscribe(c, eventc)
	defer func() {
		bus.Unsubscribe(c, eventc)
		close(eventc)
		log.Infof("closed event stream")
	}()

	c.Stream(func(w io.Writer) bool {
		select {
		case event := <-eventc:
			if event == nil {
				log.Infof("nil event received")
				return false
			}

			// TODO(bradrydzewski) This is a super hacky workaround until we improve
			// the actual bus. Having a per-call database event is just plain stupid.
			if event.Repo.FullName == repo.FullName {

				var payload = struct {
					model.Build
					Jobs []*model.Job `json:"jobs"`
				}{}
				payload.Build = event.Build
				payload.Jobs, _ = store.GetJobList(c, &event.Build)
				data, _ := json.Marshal(&payload)

				sse.Encode(w, sse.Event{
					Event: "message",
					Data:  string(data),
				})
			}
		case <-c.Writer.CloseNotify():
			return false
		}
		return true
	})
}
Exemple #2
0
// Wait is a long request that polls and waits for cancelled build requests.
func Wait(c *gin.Context) {
	id, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.String(500, "Invalid input. %s", err)
		return
	}

	eventc := make(chan *bus.Event, 1)

	bus.Subscribe(c, eventc)
	defer bus.Unsubscribe(c, eventc)

	for {
		select {
		case event := <-eventc:
			if event.Job.ID == id && event.Type == bus.Cancelled {
				c.JSON(200, event.Job)
				return
			}
		case <-c.Writer.CloseNotify():
			return
		}
	}
}