<commit_before>package catalog

import (
	"bytes"
	"fmt"
	"net/http"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/relistan/go-director"
)

const (
	CLIENT_TIMEOUT = 3 * time.Second
	DEFAULT_RETRIES = 5
)

type UrlListener struct {
	Url          string
	Retries      int
	Client       *http.Client
	looper       director.Looper
	eventChannel chan ChangeEvent
}

func NewUrlListener(url string) *UrlListener {
	errorChan := make(chan error, 1)

	return &UrlListener{
		Url:          url,
		looper:       director.NewFreeLooper(director.FOREVER, errorChan),
		Client:       &http.Client{Timeout: CLIENT_TIMEOUT},
		eventChannel: make(chan ChangeEvent, 20),
		Retries:      DEFAULT_RETRIES,
	}
}

func withRetries(count int, fn func() error) error {
	var result error

	for i := -1; i < count; i++ {
		result = fn()
		if result == nil {
			return nil
		}
		time.Sleep(100*time.Duration(i)*time.Millisecond)
	}

	log.Warnf("Failed after %d retries", count)
	return result
}

func (u *UrlListener) Watch(state *ServicesState) {
	state.AddListener(u.eventChannel)

	go func() {
		// We don't care what the change was, we post them all, so
		// just listen for any event.
		u.looper.Loop(func() error {
			<-u.eventChannel
			data := state.Encode()

			// Check for some kind of junk JSON being generated by state.Encode()
			if len(data) < 10 {
				log.Warnf("Skipping post to '%s' because of bad state encoding!", u.Url)
				return nil
			}

			buf := bytes.NewBuffer(data)

			err := withRetries(u.Retries, func() error {
				resp, err := u.Client.Post(u.Url, "application/json", buf)

				if err != nil {
					return err
				}

				if resp.StatusCode > 299 || resp.StatusCode < 200 {
					return fmt.Errorf("Bad status code returned (%d)", resp.StatusCode)
				}

				return nil
			})

			if err != nil {
				log.Warnf("Failed posting state to '%s': %s", u.Url, err.Error())
			}

			return nil
		})
	}()
}<commit_msg>Pass full event + state over HTTP.<commit_after>package catalog

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/relistan/go-director"
)

const (
	CLIENT_TIMEOUT  = 3 * time.Second
	DEFAULT_RETRIES = 5
)

type UrlListener struct {
	Url          string
	Retries      int
	Client       *http.Client
	looper       director.Looper
	eventChannel chan ChangeEvent
}

type StateChangedEvent struct {
	State       ServicesState
	ChangeEvent ChangeEvent
}

func NewUrlListener(url string) *UrlListener {
	errorChan := make(chan error, 1)

	return &UrlListener{
		Url:          url,
		looper:       director.NewFreeLooper(director.FOREVER, errorChan),
		Client:       &http.Client{Timeout: CLIENT_TIMEOUT},
		eventChannel: make(chan ChangeEvent, 20),
		Retries:      DEFAULT_RETRIES,
	}
}

func withRetries(count int, fn func() error) error {
	var result error

	for i := -1; i < count; i++ {
		result = fn()
		if result == nil {
			return nil
		}
		time.Sleep(100 * time.Duration(i) * time.Millisecond)
	}

	log.Warnf("Failed after %d retries", count)
	return result
}

func (u *UrlListener) Watch(state *ServicesState) {
	state.AddListener(u.eventChannel)

	go func() {
		u.looper.Loop(func() error {
			changedServiceEvent := <-u.eventChannel

			state.Lock()
			event := StateChangedEvent{
				State:       *state,
				ChangeEvent: changedServiceEvent,
			}

			data, err := json.Marshal(event)
			state.Unlock()

			// Check for some kind of junk JSON being generated by state.Encode()
			if err != nil {
				log.Warnf("Skipping post to '%s' because of bad state encoding! (%s)", u.Url, err.Error())
				return nil
			}

			buf := bytes.NewBuffer(data)

			err = withRetries(u.Retries, func() error {
				resp, err := u.Client.Post(u.Url, "application/json", buf)

				if err != nil {
					return err
				}

				if resp.StatusCode > 299 || resp.StatusCode < 200 {
					return fmt.Errorf("Bad status code returned (%d)", resp.StatusCode)
				}

				return nil
			})

			if err != nil {
				log.Warnf("Failed posting state to '%s': %s", u.Url, err.Error())
			}

			return nil
		})
	}()
}
{'fraction_non_alphanumeric': 0.12586037364798427, 'fraction_numerical': 0.007866273352999017, 'mean_word_length': 2.96588693957115, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '735104', 'n_tokens_mistral': 1597, 'n_tokens_neox': 1384, 'n_words': 378}