package xray

import "context"

// Capture traces an arbitrary synchronous code segment
func Capture(ctx context.Context, name string, fn func(context.Context) error) (err error) {
	ctx, seg := newSegment(ctx, name)
	defer func() { seg.close(err) }()

	defer func() {
		if p := recover(); p != nil {
			err = Panicf("%v", p)
			panic(p)
		}
	}()

	err = fn(ctx)
	return err
}

// CaptureAsync traces an arbitrary code segment within a goroutine.
// Use CaptureAsync instead of manually calling Capture within a goroutine
// to ensure the segment is flushed properly.
func CaptureAsync(ctx context.Context, name string, fn func(context.Context) error) {
	started := make(chan struct{})
	go Capture(ctx, name, func(ctx context.Context) error {
		close(started)
		return fn(ctx)
	})
	<-started
}
