Repository navigation
Expand file tree
/
Copy pathhooks.go
More file actions
418 lines (345 loc) · 10.8 KB
/
Copy pathhooks.go
File metadata and controls
418 lines (345 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
package ant
import (
"context"
"errors"
"fmt"
"maps"
"reflect"
"slices"
"sync"
"sync/atomic"
"unsafe"
"github.com/skudra-go/ant/internal/meta"
"github.com/skudra-go/ant/internal/track"
)
// A model implements these on its pointer type to run code around writes through
// Insert, Upsert, and SaveChanges. They run inside the write's transaction, so an
// error cancels the whole write. The ctx they get is bound to that transaction,
// as by InTx: what a hook runs with it, through any context on the same pool,
// such as a global root, runs there, sees the write, and rolls back with it.
// ant.InTx(ctx, db), with db in no transaction, unbinds it for a write that must
// stay. A write of one row with no After hook opens no transaction, so its
// Before hooks get the ctx as it came. Upsert runs the insert hooks whichever
// way the database goes. Bulk Update and Delete, InsertMany, UpdateMany, Merge,
// and Raw load no entities and do not run them.
type (
// Validator checks an entity before Insert, Upsert, or SaveChanges writes it.
Validator interface {
Validate(ctx context.Context) error
}
// BeforeInserter runs before an entity is inserted.
BeforeInserter interface {
BeforeInsert(ctx context.Context) error
}
// AfterInserter runs after an entity is inserted. Changes it makes to the
// entity are not written by that insert: a tracking context holds them as
// changes, which the next SaveChanges writes.
AfterInserter interface {
AfterInsert(ctx context.Context) error
}
// BeforeUpdater runs before a changed entity is updated. Changes it makes are
// saved too.
BeforeUpdater interface {
BeforeUpdate(ctx context.Context) error
}
// AfterUpdater runs after an entity is updated. Changes it makes to the
// entity are left for the next SaveChanges, as AfterInsert's are.
AfterUpdater interface {
AfterUpdate(ctx context.Context) error
}
// BeforeDeleter runs before an entity is deleted.
BeforeDeleter interface {
BeforeDelete(ctx context.Context) error
}
// AfterDeleter runs after an entity is deleted.
AfterDeleter interface {
AfterDelete(ctx context.Context) error
}
// AfterLoader runs on each entity a query returns, before Include.
AfterLoader interface {
AfterLoad(ctx context.Context) error
}
// AfterIncluder runs on each entity a query returns, after Include, so its
// relations are there.
AfterIncluder interface {
AfterInclude(ctx context.Context) error
}
)
// skipHooks is the context key of WithoutHooks.
type skipHooks struct{}
// WithoutHooks skips model hooks for writes made with ctx.
func WithoutHooks(ctx context.Context) context.Context {
return context.WithValue(ctx, skipHooks{}, true)
}
// hookKinds records which hooks a model has, so that models with none pay nothing.
type hookKinds struct {
validate, beforeInsert, afterInsert, beforeUpdate, afterUpdate, beforeDelete, afterDelete bool
}
// writes reports whether the model has a hook that runs around a write.
func (h hookKinds) writes() bool {
return h.validate || h.beforeInsert || h.afterInsert || h.beforeUpdate || h.afterUpdate ||
h.beforeDelete || h.afterDelete
}
var hookCache sync.Map // reflect.Type to hookKinds
func hooksOf(m *meta.Model) hookKinds {
if h, ok := hookCache.Load(m.Type); ok {
return h.(hookKinds)
}
p := reflect.PointerTo(m.Type)
is := func(t reflect.Type) bool { return p.Implements(t) }
h := hookKinds{
validate: is(reflect.TypeFor[Validator]()),
beforeInsert: is(reflect.TypeFor[BeforeInserter]()),
afterInsert: is(reflect.TypeFor[AfterInserter]()),
beforeUpdate: is(reflect.TypeFor[BeforeUpdater]()),
afterUpdate: is(reflect.TypeFor[AfterUpdater]()),
beforeDelete: is(reflect.TypeFor[BeforeDeleter]()),
afterDelete: is(reflect.TypeFor[AfterDeleter]()),
}
hookCache.Store(m.Type, h)
return h
}
func (n *node) hook(ctx context.Context, run func(any) error) error {
if ctx.Value(skipHooks{}) != nil {
return nil
}
if err := run(reflect.NewAt(n.model.Type, n.entity).Interface()); err != nil {
return fmt.Errorf("%s: %w", n.model.Type.Name(), err)
}
return nil
}
// checkRules runs the model's field rules. An insert leaves a zero default
// field to the database, so the value the database will store is not checked in Go.
//
// Every failing field is reported, joined, so a form gets all its errors at
// once. errors.As still reaches the first of them, as it did when the first
// was the only one.
func (n *node) checkRules(ctx context.Context) error {
if ctx.Value(skipHooks{}) != nil {
return nil
}
var failures []error
for _, rule := range n.model.Rules {
if n.insert && rule.Field.Default && rule.Field.Value(n.entity).IsZero() {
continue
}
if err := rule.Check(n.entity); err != nil {
failures = append(failures, &ValidationError{
Model: n.model.Type.Name(),
Field: rule.Field.Short,
Err: err,
})
}
}
return errors.Join(failures...)
}
func (n *node) beforeInsert(ctx context.Context) error {
if err := n.checkRules(ctx); err != nil {
return err
}
h := hooksOf(n.model)
if h.validate {
if err := n.hook(
ctx,
func(e any) error { return e.(Validator).Validate(ctx) },
); err != nil {
return err
}
}
if h.beforeInsert {
return n.hook(ctx, func(e any) error { return e.(BeforeInserter).BeforeInsert(ctx) })
}
return nil
}
func (n *node) afterInsert(ctx context.Context) error {
if hooksOf(n.model).afterInsert {
return n.after(ctx, func(e any) error { return e.(AfterInserter).AfterInsert(ctx) })
}
return nil
}
// after runs an After hook on a row just written. What was written is copied
// first, for the tracker to take as stored: a change the hook makes to its
// entity, such as a slug built from the new key, is one still to save, where
// taking the entity as stored after the hook lost it (#108).
func (n *node) after(ctx context.Context, run func(any) error) error {
if ctx.Value(skipHooks{}) != nil {
return nil
}
n.written = track.CopyOf(n.model, n.entity)
return n.hook(ctx, run)
}
func (n *node) beforeUpdate(ctx context.Context) error {
if err := n.checkRules(ctx); err != nil {
return err
}
h := hooksOf(n.model)
if h.validate {
if err := n.hook(
ctx,
func(e any) error { return e.(Validator).Validate(ctx) },
); err != nil {
return err
}
}
if h.beforeUpdate {
return n.hook(ctx, func(e any) error { return e.(BeforeUpdater).BeforeUpdate(ctx) })
}
return nil
}
func (n *node) afterUpdate(ctx context.Context) error {
if hooksOf(n.model).afterUpdate {
return n.after(ctx, func(e any) error { return e.(AfterUpdater).AfterUpdate(ctx) })
}
return nil
}
func (n *node) beforeDelete(ctx context.Context) error {
if hooksOf(n.model).beforeDelete {
return n.hook(ctx, func(e any) error { return e.(BeforeDeleter).BeforeDelete(ctx) })
}
return nil
}
func (n *node) afterDelete(ctx context.Context) error {
if hooksOf(n.model).afterDelete {
return n.hook(ctx, func(e any) error { return e.(AfterDeleter).AfterDelete(ctx) })
}
return nil
}
// Change describes one entity a SaveChanges is about to write.
type Change struct {
Model string
State State
Entity any // a pointer to the entity
Changed []string // field names, for an update
}
// SaveInterceptor is an Interceptor that also sees each SaveChanges before it
// writes, for auditing. An error cancels the save.
type SaveInterceptor interface {
SavingChanges(ctx context.Context, changes []Change) error
}
// saving reports the unit's changes to interceptors.
func (u *unit) saving(ctx context.Context) error {
var changes []Change
built := false
for _, in := range u.s.settings.interceptors {
saver, ok := in.(SaveInterceptor)
if !ok {
continue
}
if !built {
changes = u.changes()
built = true
}
if len(changes) == 0 {
continue
}
if err := saver.SavingChanges(ctx, changes); err != nil {
return err
}
}
return nil
}
func (u *unit) changes() []Change {
var out []Change
for _, n := range u.order {
change := Change{
Model: n.model.Type.Name(),
Entity: reflect.NewAt(n.model.Type, n.entity).Interface(),
}
switch {
case n.insert:
change.State = track.Added
case n.remove:
change.State = track.Deleted
default:
fields := n.pending(nil)
if len(fields) == 0 {
continue
}
change.State = track.Modified
for _, f := range fields {
change.Changed = append(change.Changed, f.Short)
}
}
out = append(out, change)
}
return out
}
// observers holds a context's Observe registrations. Every write reads them, from
// whichever goroutine made it, so a registration replaces the map rather than
// changing it, and readers take no lock. mu serializes registrations.
type observers struct {
mu sync.Mutex
byType atomic.Pointer[map[reflect.Type][]observer]
}
// load returns the current registrations. The map must not be written to.
func (o *observers) load() map[reflect.Type][]observer {
if m := o.byType.Load(); m != nil {
return *m
}
return nil
}
type observer struct {
inserted, updated, deleted func(context.Context, unsafe.Pointer)
}
// Observer receives entities after their change is committed, so it never sees a
// write that rolled back. It runs once per SaveChanges or Insert entity, after the
// outermost transaction ends, and cannot affect the write.
type Observer[T any] struct {
Inserted func(ctx context.Context, entity *T)
Updated func(ctx context.Context, entity *T)
Deleted func(ctx context.Context, entity *T)
}
// Observe registers an observer for model T, on this context and its sessions.
func Observe[T any](h Handle, o Observer[T]) error {
s, model, err := handleModel[T](h)
if err != nil {
return err
}
wrap := func(f func(context.Context, *T)) func(context.Context, unsafe.Pointer) {
if f == nil {
return nil
}
return func(ctx context.Context, p unsafe.Pointer) { f(ctx, (*T)(p)) }
}
s.observed.mu.Lock()
defer s.observed.mu.Unlock()
current := s.observed.load()
next := make(map[reflect.Type][]observer, len(current)+1)
maps.Copy(next, current)
// Clip makes append copy, so a write reading current never sees it change.
next[model.Type] = append(slices.Clip(current[model.Type]),
observer{wrap(o.Inserted), wrap(o.Updated), wrap(o.Deleted)})
s.observed.byType.Store(&next)
return nil
}
// notify tells observers what the unit wrote, now or at the transaction's commit.
func (u *unit) notify(ctx context.Context) {
// A snapshot, so an observer may itself call Observe.
observed := u.s.observed.load()
if len(observed) == 0 {
return
}
for _, n := range u.order {
for _, o := range observed[n.model.Type] {
var f func(context.Context, unsafe.Pointer)
switch {
case n.remove:
f = o.deleted
case n.insert:
f = o.inserted
case len(n.changed) > 0:
f = o.updated
}
if f == nil {
continue
}
entity := n.entity
switch t := u.s.tx; {
case t == nil:
f(ctx, entity)
case t.sees():
t.pending = append(t.pending, func(ctx context.Context) { f(ctx, entity) })
}
}
}
}