| 1 |
--- a/exec.go 2026-07-10 01:31:35.188129862 +0200 |
| 2 |
+++ b/exec.go 2026-07-10 01:31:35.189129894 +0200 |
| 3 |
@@ -5,14 +5,17 @@ |
| 4 |
package gotext |
| 5 |
|
| 6 |
import ( |
| 7 |
+ "context" |
| 8 |
"errors" |
| 9 |
"fmt" |
| 10 |
- "heckel.io/ntfy/v2/template/gotext/fmtsort" |
| 11 |
"io" |
| 12 |
"reflect" |
| 13 |
"runtime" |
| 14 |
"strings" |
| 15 |
+ "sync/atomic" |
| 16 |
"text/template/parse" |
| 17 |
+ |
| 18 |
+ "heckel.io/ntfy/v2/template/gotext/fmtsort" |
| 19 |
) |
| 20 |
|
| 21 |
// maxExecDepth specifies the maximum stack depth of templates within |
| 22 |
@@ -32,11 +35,13 @@ |
| 23 |
// template so that multiple executions of the same template |
| 24 |
// can execute in parallel. |
| 25 |
type state struct { |
| 26 |
- tmpl *Template |
| 27 |
- wr io.Writer |
| 28 |
- node parse.Node // current node, for errors |
| 29 |
- vars []variable // push-down stack of variable values. |
| 30 |
- depth int // the height of the stack of executing templates. |
| 31 |
+ tmpl *Template |
| 32 |
+ ctx context.Context // ctx-ex: execution context; Execute uses context.Background. |
| 33 |
+ wr io.Writer |
| 34 |
+ node parse.Node // current node, for errors |
| 35 |
+ vars []variable // push-down stack of variable values. |
| 36 |
+ depth int // the height of the stack of executing templates. |
| 37 |
+ cancelled *atomic.Bool // ctx-ex: shared flag set by the context.AfterFunc watcher; nil if ctx cannot be canceled |
| 38 |
} |
| 39 |
|
| 40 |
// variable holds the dynamic value of a variable such as $, $x etc. |
| 41 |
@@ -160,6 +165,14 @@ |
| 42 |
}) |
| 43 |
} |
| 44 |
|
| 45 |
+// cancelError is the wrapper type used internally when execution is aborted |
| 46 |
+// because the context is done. Like writeError, it is stripped in errRecover |
| 47 |
+// so the caller receives the original ctx.Err(). It is not an implementation |
| 48 |
+// of error, so it cannot escape from the package as an error value. |
| 49 |
+type cancelError struct { |
| 50 |
+ Err error // Original context error. |
| 51 |
+} |
| 52 |
+ |
| 53 |
// errRecover is the handler that turns panics into returns from the top |
| 54 |
// level of Parse. |
| 55 |
func errRecover(errp *error) { |
| 56 |
@@ -170,6 +183,8 @@ |
| 57 |
panic(e) |
| 58 |
case writeError: |
| 59 |
*errp = err.Err // Strip the wrapper. |
| 60 |
+ case cancelError: |
| 61 |
+ *errp = err.Err // Strip the wrapper; return the context error. |
| 62 |
case ExecError: |
| 63 |
*errp = err // Keep the wrapper. |
| 64 |
default: |
| 65 |
@@ -186,11 +201,19 @@ |
| 66 |
// A template may be executed safely in parallel, although if parallel |
| 67 |
// executions share a Writer the output may be interleaved. |
| 68 |
func (t *Template) ExecuteTemplate(wr io.Writer, name string, data any) error { |
| 69 |
+ return t.ExecuteTemplateContext(context.Background(), wr, name, data) |
| 70 |
+} |
| 71 |
+ |
| 72 |
+// ExecuteTemplateContext is like [Template.ExecuteTemplate], but aborts and |
| 73 |
+// returns ctx.Err() if ctx is canceled or its deadline is exceeded before |
| 74 |
+// execution completes. See [Template.ExecuteContext] for the cancellation |
| 75 |
+// semantics. |
| 76 |
+func (t *Template) ExecuteTemplateContext(ctx context.Context, wr io.Writer, name string, data any) error { |
| 77 |
tmpl := t.Lookup(name) |
| 78 |
if tmpl == nil { |
| 79 |
return fmt.Errorf("template: no template %q associated with template %q", name, t.name) |
| 80 |
} |
| 81 |
- return tmpl.Execute(wr, data) |
| 82 |
+ return tmpl.ExecuteContext(ctx, wr, data) |
| 83 |
} |
| 84 |
|
| 85 |
// Execute applies a parsed template to the specified data object, |
| 86 |
@@ -204,10 +227,27 @@ |
| 87 |
// If data is a [reflect.Value], the template applies to the concrete |
| 88 |
// value that the reflect.Value holds, as in [fmt.Print]. |
| 89 |
func (t *Template) Execute(wr io.Writer, data any) error { |
| 90 |
- return t.execute(wr, data) |
| 91 |
+ return t.executeContext(context.Background(), wr, data) |
| 92 |
} |
| 93 |
|
| 94 |
-func (t *Template) execute(wr io.Writer, data any) (err error) { |
| 95 |
+// ExecuteContext is like [Template.Execute], but aborts and returns ctx.Err() |
| 96 |
+// (either [context.Canceled] or [context.DeadlineExceeded], retrievable with |
| 97 |
+// [errors.Is]) if ctx is canceled or its deadline is exceeded before execution |
| 98 |
+// completes. |
| 99 |
+// |
| 100 |
+// Cancellation is observed between node evaluations as the template is walked, |
| 101 |
+// so long-running renders -- including tight or nested {{range}} loops that |
| 102 |
+// write no output -- are aborted promptly. A template blocked inside a single |
| 103 |
+// function call is not interrupted until that call returns. Partial results may |
| 104 |
+// already have been written to wr. |
| 105 |
+func (t *Template) ExecuteContext(ctx context.Context, wr io.Writer, data any) error { |
| 106 |
+ if err := ctx.Err(); err != nil { |
| 107 |
+ return err |
| 108 |
+ } |
| 109 |
+ return t.executeContext(ctx, wr, data) |
| 110 |
+} |
| 111 |
+ |
| 112 |
+func (t *Template) executeContext(ctx context.Context, wr io.Writer, data any) (err error) { |
| 113 |
defer errRecover(&err) |
| 114 |
value, ok := data.(reflect.Value) |
| 115 |
if !ok { |
| 116 |
@@ -215,9 +255,20 @@ |
| 117 |
} |
| 118 |
state := &state{ |
| 119 |
tmpl: t, |
| 120 |
+ ctx: ctx, |
| 121 |
wr: wr, |
| 122 |
vars: []variable{{"$", value}}, |
| 123 |
} |
| 124 |
+ // If the context can be canceled, watch it with a single context.AfterFunc |
| 125 |
+ // callback that flips an atomic flag; walk polls that flag per node (a cheap |
| 126 |
+ // monomorphic atomic load) instead of calling ctx.Err() every node. |
| 127 |
+ // Contexts that can never be canceled (Background, TODO) have a nil Done |
| 128 |
+ // channel, so the default Execute path installs nothing and pays nothing. |
| 129 |
+ if ctx.Done() != nil { |
| 130 |
+ state.cancelled = new(atomic.Bool) |
| 131 |
+ stop := context.AfterFunc(ctx, func() { state.cancelled.Store(true) }) |
| 132 |
+ defer stop() |
| 133 |
+ } |
| 134 |
if t.Tree == nil || t.Root == nil { |
| 135 |
state.errorf("%q is an incomplete or empty template", t.Name()) |
| 136 |
} |
| 137 |
@@ -260,6 +311,12 @@ |
| 138 |
// generating output as they go. |
| 139 |
func (s *state) walk(dot reflect.Value, node parse.Node) { |
| 140 |
s.at(node) |
| 141 |
+ // Abort if the context has been canceled or its deadline has passed. The |
| 142 |
+ // flag is set by the watcher installed in executeContext; observing it here |
| 143 |
+ // interrupts any template shape, including loops that write no output. |
| 144 |
+ if s.cancelled != nil && s.cancelled.Load() { |
| 145 |
+ panic(cancelError{s.ctx.Err()}) |
| 146 |
+ } |
| 147 |
switch node := node.(type) { |
| 148 |
case *parse.ActionNode: |
| 149 |
// Do not pop variables so they persist until next end. |