Debian Codegraph @

internal/event/core/export.go

raw symbols SCIP
1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package core
6
7 import (
8 "context"
9 "sync/atomic"
10 "time"
11
12 "golang.org/x/tools/internal/event/label"
13 )
14
15 // Exporter is a function that handles events.
16 // It may return a modified context and event.
17 type Exporter func(context.Context, Event, label.Map) context.Context
18
19 var exporter atomic.Pointer[Exporter]
20
21 // SetExporter sets the global exporter function that handles all events.
22 // The exporter is called synchronously from the event call site, so it should
23 // return quickly so as not to hold up user code.
24 func SetExporter(e Exporter) {
25 if e == nil {
26 // &e is always valid, and so p is always valid, but for the early abort
27 // of ProcessEvent to be efficient it needs to make the nil check on the
28 // pointer without having to dereference it, so we make the nil function
29 // also a nil pointer
30 exporter.Store(nil)
31 } else {
32 exporter.Store(&e)
33 }
34 }
35
36 // deliver is called to deliver an event to the supplied exporter.
37 // it will fill in the time.
38 func deliver(ctx context.Context, exporter Exporter, ev Event) context.Context {
39 // add the current time to the event
40 ev.at = time.Now()
41 // hand the event off to the current exporter
42 return exporter(ctx, ev, ev)
43 }
44
45 // Export is called to deliver an event to the global exporter if set.
46 func Export(ctx context.Context, ev Event) context.Context {
47 // get the global exporter and abort early if there is not one
48 exporterPtr := exporter.Load()
49 if exporterPtr == nil {
50 return ctx
51 }
52 return deliver(ctx, *exporterPtr, ev)
53 }
54
55 // ExportPair is called to deliver a start event to the supplied exporter.
56 // It also returns a function that will deliver the end event to the same
57 // exporter.
58 // It will fill in the time.
59 func ExportPair(ctx context.Context, begin, end Event) (context.Context, func()) {
60 // get the global exporter and abort early if there is not one
61 exporterPtr := exporter.Load()
62 if exporterPtr == nil {
63 return ctx, func() {}
64 }
65 ctx = deliver(ctx, *exporterPtr, begin)
66 return ctx, func() { deliver(ctx, *exporterPtr, end) }
67 }