github.com/blend/go-sdk@v1.20220411.3/cron/event.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package cron 9 10 import ( 11 "context" 12 "fmt" 13 "io" 14 "time" 15 16 "github.com/blend/go-sdk/logger" 17 "github.com/blend/go-sdk/timeutil" 18 ) 19 20 // these are compile time assertions 21 var ( 22 _ logger.Event = (*Event)(nil) 23 _ logger.TextWritable = (*Event)(nil) 24 _ logger.JSONWritable = (*Event)(nil) 25 ) 26 27 // NewEventListener returns a new event listener. 28 func NewEventListener(listener func(context.Context, Event)) logger.Listener { 29 return func(ctx context.Context, e logger.Event) { 30 if typed, isTyped := e.(Event); isTyped { 31 listener(ctx, typed) 32 } 33 } 34 } 35 36 // NewEvent creates a new event with a given set of optional options. 37 func NewEvent(flag, jobName string, options ...EventOption) Event { 38 e := Event{ 39 Flag: flag, 40 JobName: jobName, 41 } 42 43 for _, option := range options { 44 option(&e) 45 } 46 return e 47 } 48 49 // EventOption is an option for an Event. 50 type EventOption func(*Event) 51 52 // OptEventJobInvocation sets a field. 53 func OptEventJobInvocation(jobInvocation string) EventOption { 54 return func(e *Event) { e.JobInvocation = jobInvocation } 55 } 56 57 // OptEventErr sets a field. 58 func OptEventErr(err error) EventOption { 59 return func(e *Event) { e.Err = err } 60 } 61 62 // OptEventElapsed sets a field. 63 func OptEventElapsed(elapsed time.Duration) EventOption { 64 return func(e *Event) { e.Elapsed = elapsed } 65 } 66 67 // Event is an event. 68 type Event struct { 69 Flag string 70 JobName string 71 JobInvocation string 72 Err error 73 Elapsed time.Duration 74 } 75 76 // GetFlag implements logger.Event. 77 func (e Event) GetFlag() string { return e.Flag } 78 79 // Complete returns if the event completed. 80 func (e Event) Complete() bool { 81 return e.Flag == FlagComplete 82 } 83 84 // WriteText implements logger.TextWritable. 85 func (e Event) WriteText(tf logger.TextFormatter, wr io.Writer) { 86 if e.Elapsed > 0 { 87 fmt.Fprint(wr, logger.Space) 88 fmt.Fprintf(wr, "(%v)", e.Elapsed) 89 } 90 } 91 92 // Decompose implements logger.JSONWritable. 93 func (e Event) Decompose() map[string]interface{} { 94 return map[string]interface{}{ 95 "jobName": e.JobName, 96 "err": e.Err, 97 "elapsed": timeutil.Milliseconds(e.Elapsed), 98 } 99 }