| 1 | // Package ctxext provides multiple useful context constructors. |
| 2 | package ctxext |
| 3 | |
| 4 | import ( |
| 5 | "time" |
| 6 | |
| 7 | context "golang.org/x/net/context" |
| 8 | ) |
| 9 | |
| 10 | // WithDeadlineFraction returns a Context with a fraction of the |
| 11 | // original context's timeout. This is useful in sequential pipelines |
| 12 | // of work, where one might try options and fall back to others |
| 13 | // depending on the time available, or failure to respond. For example: |
| 14 | // |
| 15 | // // getPicture returns a picture from our encrypted database |
| 16 | // // we have a pipeline of multiple steps. we need to: |
| 17 | // // - get the data from a database |
| 18 | // // - decrypt it |
| 19 | // // - apply many transforms |
| 20 | // // |
| 21 | // // we **know** that each step takes increasingly more time. |
| 22 | // // The transforms are much more expensive than decryption, and |
| 23 | // // decryption is more expensive than the database lookup. |
| 24 | // // If our database takes too long (i.e. >0.2 of available time), |
| 25 | // // there's no use in continuing. |
| 26 | // func getPicture(ctx context.Context, key string) ([]byte, error) { |
| 27 | // // fractional timeout contexts to the rescue! |
| 28 | // |
| 29 | // // try the database with 0.2 of remaining time. |
| 30 | // ctx1, _ := ctxext.WithDeadlineFraction(ctx, 0.2) |
| 31 | // val, err := db.Get(ctx1, key) |
| 32 | // if err != nil { |
| 33 | // return nil, err |
| 34 | // } |
| 35 | // |
| 36 | // // try decryption with 0.3 of remaining time. |
| 37 | // ctx2, _ := ctxext.WithDeadlineFraction(ctx, 0.3) |
| 38 | // if val, err = decryptor.Decrypt(ctx2, val); err != nil { |
| 39 | // return nil, err |
| 40 | // } |
| 41 | // |
| 42 | // // try transforms with all remaining time. hopefully it's enough! |
| 43 | // return transformer.Transform(ctx, val) |
| 44 | // } |
| 45 | // |
| 46 | // |
| 47 | func WithDeadlineFraction(ctx context.Context, fraction float64) ( |
| 48 | context.Context, context.CancelFunc) { |
| 49 | |
| 50 | d, found := ctx.Deadline() |
| 51 | if !found { // no deadline |
| 52 | return context.WithCancel(ctx) |
| 53 | } |
| 54 | |
| 55 | left := d.Sub(time.Now()) |
| 56 | if left < 0 { // already passed... |
| 57 | return context.WithCancel(ctx) |
| 58 | } |
| 59 | |
| 60 | left = time.Duration(float64(left) * fraction) |
| 61 | return context.WithTimeout(ctx, left) |
| 62 | } |