package autoprof

import (
	"context"
	"errors"
	"runtime"

	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/s3"

	"code.justin.tv/video/autoprof/profs3"
)

// Go creates a goroutine that periodically collects performance profiles
// and uploads the profiles to an S3 bucket.
//
// These profiles are helpful in debugging unexpected application
// behavior, especially in case of a production issue.
func Go(ctx context.Context, sess *session.Session, bucket string, onError func(err error) error) error {
	if bucket == "" {
		return errors.New("bucket not specified, will not collect profiles")
	}

	// Enables the mutex profile to collect contention events at 1/10 rate.
	runtime.SetMutexProfileFraction(10)

	// Enables the goroutine blocking profile to collect 1/10 goroutine blocking events.
	runtime.SetBlockProfileRate(10)

	c := &profs3.Collector{
		S3:       s3.New(sess),
		S3Bucket: bucket,
		OnError:  onError,
	}

	go func() {
		err := c.Run(ctx)
		if err != nil {
			_ = onError(err)
		}
	}()
	return nil
}
