github.com/blend/go-sdk@v1.20220411.3/cron/job_invocation.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 "time" 13 14 "github.com/blend/go-sdk/uuid" 15 ) 16 17 // NewJobInvocation returns a new job invocation. 18 func NewJobInvocation(jobName string) *JobInvocation { 19 return &JobInvocation{ 20 ID: NewJobInvocationID(), 21 Status: JobInvocationStatusIdle, 22 JobName: jobName, 23 } 24 } 25 26 type contextKeyJobInvocation struct{} 27 28 // WithJobInvocation adds job invocation to a context. 29 func WithJobInvocation(ctx context.Context, ji *JobInvocation) context.Context { 30 return context.WithValue(ctx, contextKeyJobInvocation{}, ji) 31 } 32 33 // GetJobInvocation gets the job invocation from a given context. 34 func GetJobInvocation(ctx context.Context) *JobInvocation { 35 if value := ctx.Value(contextKeyJobInvocation{}); value != nil { 36 if typed, ok := value.(*JobInvocation); ok { 37 return typed 38 } 39 } 40 return nil 41 } 42 43 // NewJobInvocationID returns a new pseudo-unique job invocation identifier. 44 func NewJobInvocationID() string { 45 return uuid.V4().String() 46 } 47 48 // JobInvocation is metadata for a job invocation (or instance of a job running). 49 type JobInvocation struct { 50 ID string `json:"id"` 51 JobName string `json:"jobName"` 52 53 Started time.Time `json:"started"` 54 Complete time.Time `json:"complete"` 55 Err error `json:"err"` 56 57 Parameters JobParameters `json:"parameters"` 58 Status JobInvocationStatus `json:"status"` 59 State interface{} `json:"-"` 60 61 Cancel context.CancelFunc `json:"-"` 62 } 63 64 // Elapsed returns the elapsed time for the invocation. 65 func (ji *JobInvocation) Elapsed() time.Duration { 66 if !ji.Complete.IsZero() { 67 return ji.Complete.Sub(ji.Started) 68 } 69 if !ji.Started.IsZero() { 70 return Now().Sub(ji.Started) 71 } 72 return 0 73 } 74 75 // Clone clones the job invocation. 76 func (ji *JobInvocation) Clone() *JobInvocation { 77 return &JobInvocation{ 78 ID: ji.ID, 79 JobName: ji.JobName, 80 81 Started: ji.Started, 82 Complete: ji.Complete, 83 Err: ji.Err, 84 85 Parameters: ji.Parameters, 86 Status: ji.Status, 87 State: ji.State, 88 89 Cancel: ji.Cancel, 90 } 91 }