| 1 | // Copyright 2015 Matthew Holt and The Caddy Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package caddyevents |
| 16 | |
| 17 | import ( |
| 18 | "context" |
| 19 | "encoding/json" |
| 20 | "errors" |
| 21 | "fmt" |
| 22 | "strings" |
| 23 | |
| 24 | "go.uber.org/zap" |
| 25 | |
| 26 | "github.com/caddyserver/caddy/v2" |
| 27 | ) |
| 28 | |
| 29 | func init() { |
| 30 | caddy.RegisterModule(App{}) |
| 31 | } |
| 32 | |
| 33 | // App implements a global eventing system within Caddy. |
| 34 | // Modules can emit and subscribe to events, providing |
| 35 | // hooks into deep parts of the code base that aren't |
| 36 | // otherwise accessible. Events provide information about |
| 37 | // what and when things are happening, and this facility |
| 38 | // allows handlers to take action when events occur, |
| 39 | // add information to the event's metadata, and even |
| 40 | // control program flow in some cases. |
| 41 | // |
| 42 | // Events are propagated in a DOM-like fashion. An event |
| 43 | // emitted from module `a.b.c` (the "origin") will first |
| 44 | // invoke handlers listening to `a.b.c`, then `a.b`, |
| 45 | // then `a`, then those listening regardless of origin. |
| 46 | // If a handler returns the special error Aborted, then |
| 47 | // propagation immediately stops and the event is marked |
| 48 | // as aborted. Emitters may optionally choose to adjust |
| 49 | // program flow based on an abort. |
| 50 | // |
| 51 | // Modules can subscribe to events by origin and/or name. |
| 52 | // A handler is invoked only if it is subscribed to the |
| 53 | // event by name and origin. Subscriptions should be |
| 54 | // registered during the provisioning phase, before apps |
| 55 | // are started. |
| 56 | // |
| 57 | // Event handlers are fired synchronously as part of the |
| 58 | // regular flow of the program. This allows event handlers |
| 59 | // to control the flow of the program if the origin permits |
| 60 | // it and also allows handlers to convey new information |
| 61 | // back into the origin module before it continues. |
| 62 | // In essence, event handlers are similar to HTTP |
| 63 | // middleware handlers. |
| 64 | // |
| 65 | // Event bindings/subscribers are unordered; i.e. |
| 66 | // event handlers are invoked in an arbitrary order. |
| 67 | // Event handlers should not rely on the logic of other |
| 68 | // handlers to succeed. |
| 69 | // |
| 70 | // The entirety of this app module is EXPERIMENTAL and |
| 71 | // subject to change. Pay attention to release notes. |
| 72 | type App struct { |
| 73 | // Subscriptions bind handlers to one or more events |
| 74 | // either globally or scoped to specific modules or module |
| 75 | // namespaces. |
| 76 | Subscriptions []*Subscription `json:"subscriptions,omitempty"` |
| 77 | |
| 78 | // Map of event name to map of module ID/namespace to handlers |
| 79 | subscriptions map[string]map[caddy.ModuleID][]Handler |
| 80 | |
| 81 | logger *zap.Logger |
| 82 | started bool |
| 83 | } |
| 84 | |
| 85 | // Subscription represents binding of one or more handlers to |
| 86 | // one or more events. |
| 87 | type Subscription struct { |
| 88 | // The name(s) of the event(s) to bind to. Default: all events. |
| 89 | Events []string `json:"events,omitempty"` |
| 90 | |
| 91 | // The ID or namespace of the module(s) from which events |
| 92 | // originate to listen to for events. Default: all modules. |
| 93 | // |
| 94 | // Events propagate up, so events emitted by module "a.b.c" |
| 95 | // will also trigger the event for "a.b" and "a". Thus, to |
| 96 | // receive all events from "a.b.c" and "a.b.d", for example, |
| 97 | // one can subscribe to either "a.b" or all of "a" entirely. |
| 98 | Modules []caddy.ModuleID `json:"modules,omitempty"` |
| 99 | |
| 100 | // The event handler modules. These implement the actual |
| 101 | // behavior to invoke when an event occurs. At least one |
| 102 | // handler is required. |
| 103 | HandlersRaw []json.RawMessage `json:"handlers,omitempty" caddy:"namespace=events.handlers inline_key=handler"` |
| 104 | |
| 105 | // The decoded handlers; Go code that is subscribing to |
| 106 | // an event should set this field directly; HandlersRaw |
| 107 | // is meant for JSON configuration to fill out this field. |
| 108 | Handlers []Handler `json:"-"` |
| 109 | } |
| 110 | |
| 111 | // CaddyModule returns the Caddy module information. |
| 112 | func (App) CaddyModule() caddy.ModuleInfo { |
| 113 | return caddy.ModuleInfo{ |
| 114 | ID: "events", |
| 115 | New: func() caddy.Module { return new(App) }, |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | // Provision sets up the app. |
| 120 | func (app *App) Provision(ctx caddy.Context) error { |
| 121 | app.logger = ctx.Logger() |
| 122 | app.subscriptions = make(map[string]map[caddy.ModuleID][]Handler) |
| 123 | |
| 124 | for _, sub := range app.Subscriptions { |
| 125 | if sub.HandlersRaw == nil { |
| 126 | continue |
| 127 | } |
| 128 | handlersIface, err := ctx.LoadModule(sub, "HandlersRaw") |
| 129 | if err != nil { |
| 130 | return fmt.Errorf("loading event subscriber modules: %v", err) |
| 131 | } |
| 132 | for _, h := range handlersIface.([]any) { |
| 133 | sub.Handlers = append(sub.Handlers, h.(Handler)) |
| 134 | } |
| 135 | if len(sub.Handlers) == 0 { |
| 136 | // pointless to bind without any handlers |
| 137 | return fmt.Errorf("no handlers defined") |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | return nil |
| 142 | } |
| 143 | |
| 144 | // Start runs the app. |
| 145 | func (app *App) Start() error { |
| 146 | for _, sub := range app.Subscriptions { |
| 147 | if err := app.Subscribe(sub); err != nil { |
| 148 | return err |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | app.started = true |
| 153 | |
| 154 | return nil |
| 155 | } |
| 156 | |
| 157 | // Stop gracefully shuts down the app. |
| 158 | func (app *App) Stop() error { |
| 159 | return nil |
| 160 | } |
| 161 | |
| 162 | // Subscribe binds one or more event handlers to one or more events |
| 163 | // according to the subscription s. For now, subscriptions can only |
| 164 | // be created during the provision phase; new bindings cannot be |
| 165 | // created after the events app has started. |
| 166 | func (app *App) Subscribe(s *Subscription) error { |
| 167 | if app.started { |
| 168 | return fmt.Errorf("events already started; new subscriptions closed") |
| 169 | } |
| 170 | |
| 171 | // handle special case of catch-alls (omission of event name or module space implies all) |
| 172 | if len(s.Events) == 0 { |
| 173 | s.Events = []string{""} |
| 174 | } |
| 175 | if len(s.Modules) == 0 { |
| 176 | s.Modules = []caddy.ModuleID{""} |
| 177 | } |
| 178 | |
| 179 | for _, eventName := range s.Events { |
| 180 | if app.subscriptions[eventName] == nil { |
| 181 | app.subscriptions[eventName] = make(map[caddy.ModuleID][]Handler) |
| 182 | } |
| 183 | for _, originModule := range s.Modules { |
| 184 | app.subscriptions[eventName][originModule] = append(app.subscriptions[eventName][originModule], s.Handlers...) |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | return nil |
| 189 | } |
| 190 | |
| 191 | // On is syntactic sugar for Subscribe() that binds a single handler |
| 192 | // to a single event from any module. If the eventName is empty string, |
| 193 | // it counts for all events. |
| 194 | func (app *App) On(eventName string, handler Handler) error { |
| 195 | return app.Subscribe(&Subscription{ |
| 196 | Events: []string{eventName}, |
| 197 | Handlers: []Handler{handler}, |
| 198 | }) |
| 199 | } |
| 200 | |
| 201 | // Emit creates and dispatches an event named eventName to all relevant handlers with |
| 202 | // the metadata data. Events are emitted and propagated synchronously. The returned Event |
| 203 | // value will have any additional information from the invoked handlers. |
| 204 | // |
| 205 | // Note that the data map is not copied, for efficiency. After Emit() is called, the |
| 206 | // data passed in should not be changed in other goroutines. |
| 207 | func (app *App) Emit(ctx caddy.Context, eventName string, data map[string]any) caddy.Event { |
| 208 | logger := app.logger.With(zap.String("name", eventName)) |
| 209 | |
| 210 | e, err := caddy.NewEvent(ctx, eventName, data) |
| 211 | if err != nil { |
| 212 | logger.Error("failed to create event", zap.Error(err)) |
| 213 | } |
| 214 | |
| 215 | var originModule caddy.ModuleInfo |
| 216 | var originModuleID caddy.ModuleID |
| 217 | var originModuleName string |
| 218 | if origin := e.Origin(); origin != nil { |
| 219 | originModule = origin.CaddyModule() |
| 220 | originModuleID = originModule.ID |
| 221 | originModuleName = originModule.String() |
| 222 | } |
| 223 | |
| 224 | logger = logger.With( |
| 225 | zap.String("id", e.ID().String()), |
| 226 | zap.String("origin", originModuleName)) |
| 227 | |
| 228 | // add event info to replacer, make sure it's in the context |
| 229 | repl, ok := ctx.Context.Value(caddy.ReplacerCtxKey).(*caddy.Replacer) |
| 230 | if !ok { |
| 231 | repl = caddy.NewReplacer() |
| 232 | ctx.Context = context.WithValue(ctx.Context, caddy.ReplacerCtxKey, repl) |
| 233 | } |
| 234 | repl.Map(func(key string) (any, bool) { |
| 235 | switch key { |
| 236 | case "event": |
| 237 | return e, true |
| 238 | case "event.id": |
| 239 | return e.ID(), true |
| 240 | case "event.name": |
| 241 | return e.Name(), true |
| 242 | case "event.time": |
| 243 | return e.Timestamp(), true |
| 244 | case "event.time_unix": |
| 245 | return e.Timestamp().UnixMilli(), true |
| 246 | case "event.module": |
| 247 | return originModuleID, true |
| 248 | case "event.data": |
| 249 | return e.Data, true |
| 250 | } |
| 251 | |
| 252 | if after, ok0 := strings.CutPrefix(key, "event.data."); ok0 { |
| 253 | key = after |
| 254 | if val, ok := e.Data[key]; ok { |
| 255 | return val, true |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | return nil, false |
| 260 | }) |
| 261 | |
| 262 | logger = logger.WithLazy(zap.Any("data", e.Data)) |
| 263 | |
| 264 | logger.Debug("event") |
| 265 | |
| 266 | // invoke handlers bound to the event by name and also all events; this for loop |
| 267 | // iterates twice at most: once for the event name, once for "" (all events) |
| 268 | for { |
| 269 | moduleID := originModuleID |
| 270 | |
| 271 | // implement propagation up the module tree (i.e. start with "a.b.c" then "a.b" then "a" then "") |
| 272 | for { |
| 273 | if app.subscriptions[eventName] == nil { |
| 274 | break // shortcut if event not bound at all |
| 275 | } |
| 276 | |
| 277 | for _, handler := range app.subscriptions[eventName][moduleID] { |
| 278 | select { |
| 279 | case <-ctx.Done(): |
| 280 | logger.Error("context canceled; event handling stopped") |
| 281 | return e |
| 282 | default: |
| 283 | } |
| 284 | |
| 285 | // this log can be a useful sanity check to ensure your handlers are in fact being invoked |
| 286 | // (see https://github.com/mholt/caddy-events-exec/issues/6) |
| 287 | logger.Debug("invoking subscribed handler", |
| 288 | zap.String("subscribed_to", eventName), |
| 289 | zap.Any("handler", handler)) |
| 290 | |
| 291 | if err := handler.Handle(ctx, e); err != nil { |
| 292 | aborted := errors.Is(err, caddy.ErrEventAborted) |
| 293 | |
| 294 | logger.Error("handler error", |
| 295 | zap.Error(err), |
| 296 | zap.Bool("aborted", aborted)) |
| 297 | |
| 298 | if aborted { |
| 299 | e.Aborted = err |
| 300 | return e |
| 301 | } |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | if moduleID == "" { |
| 306 | break |
| 307 | } |
| 308 | lastDot := strings.LastIndex(string(moduleID), ".") |
| 309 | if lastDot < 0 { |
| 310 | moduleID = "" // include handlers bound to events regardless of module |
| 311 | } else { |
| 312 | moduleID = moduleID[:lastDot] |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | // include handlers listening to all events |
| 317 | if eventName == "" { |
| 318 | break |
| 319 | } |
| 320 | eventName = "" |
| 321 | } |
| 322 | |
| 323 | return e |
| 324 | } |
| 325 | |
| 326 | // Handler is a type that can handle events. |
| 327 | type Handler interface { |
| 328 | Handle(context.Context, caddy.Event) error |
| 329 | } |
| 330 | |
| 331 | // Interface guards |
| 332 | var ( |
| 333 | _ caddy.App = (*App)(nil) |
| 334 | _ caddy.Provisioner = (*App)(nil) |
| 335 | ) |