repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/internal/global/handler.go
vendor/go.opentelemetry.io/otel/internal/global/handler.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package global // import "go.opentelemetry.io/otel/internal/global" import ( "log" "sync/atomic" ) // ErrorHandler handles irremediable events. type ErrorHandler interface { // Handle handles any error deemed irremediable by an OpenTelemetry // component. Handle(error) } type ErrDelegator struct { delegate atomic.Pointer[ErrorHandler] } // Compile-time check that delegator implements ErrorHandler. var _ ErrorHandler = (*ErrDelegator)(nil) func (d *ErrDelegator) Handle(err error) { if eh := d.delegate.Load(); eh != nil { (*eh).Handle(err) return } log.Print(err) } // setDelegate sets the ErrorHandler delegate. func (d *ErrDelegator) setDelegate(eh ErrorHandler) { d.delegate.Store(&eh) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/internal/global/meter.go
vendor/go.opentelemetry.io/otel/internal/global/meter.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package global // import "go.opentelemetry.io/otel/internal/global" import ( "container/list" "sync" "sync/atomic" "go.opentelemetry.io/otel/metric" "go.opentelemetry.io/otel/metric/embedded" ) // meterProvider is a placeholder for a configured SDK MeterProvider. // // All MeterProvider functionality is forwarded to a delegate once // configured. type meterProvider struct { embedded.MeterProvider mtx sync.Mutex meters map[il]*meter delegate metric.MeterProvider } // setDelegate configures p to delegate all MeterProvider functionality to // provider. // // All Meters provided prior to this function call are switched out to be // Meters provided by provider. All instruments and callbacks are recreated and // delegated. // // It is guaranteed by the caller that this happens only once. func (p *meterProvider) setDelegate(provider metric.MeterProvider) { p.mtx.Lock() defer p.mtx.Unlock() p.delegate = provider if len(p.meters) == 0 { return } for _, meter := range p.meters { meter.setDelegate(provider) } p.meters = nil } // Meter implements MeterProvider. func (p *meterProvider) Meter(name string, opts ...metric.MeterOption) metric.Meter { p.mtx.Lock() defer p.mtx.Unlock() if p.delegate != nil { return p.delegate.Meter(name, opts...) } // At this moment it is guaranteed that no sdk is installed, save the meter in the meters map. c := metric.NewMeterConfig(opts...) key := il{ name: name, version: c.InstrumentationVersion(), schema: c.SchemaURL(), } if p.meters == nil { p.meters = make(map[il]*meter) } if val, ok := p.meters[key]; ok { return val } t := &meter{name: name, opts: opts} p.meters[key] = t return t } // meter is a placeholder for a metric.Meter. // // All Meter functionality is forwarded to a delegate once configured. // Otherwise, all functionality is forwarded to a NoopMeter. type meter struct { embedded.Meter name string opts []metric.MeterOption mtx sync.Mutex instruments []delegatedInstrument registry list.List delegate atomic.Value // metric.Meter } type delegatedInstrument interface { setDelegate(metric.Meter) } // setDelegate configures m to delegate all Meter functionality to Meters // created by provider. // // All subsequent calls to the Meter methods will be passed to the delegate. // // It is guaranteed by the caller that this happens only once. func (m *meter) setDelegate(provider metric.MeterProvider) { meter := provider.Meter(m.name, m.opts...) m.delegate.Store(meter) m.mtx.Lock() defer m.mtx.Unlock() for _, inst := range m.instruments { inst.setDelegate(meter) } var n *list.Element for e := m.registry.Front(); e != nil; e = n { r := e.Value.(*registration) r.setDelegate(meter) n = e.Next() m.registry.Remove(e) } m.instruments = nil m.registry.Init() } func (m *meter) Int64Counter(name string, options ...metric.Int64CounterOption) (metric.Int64Counter, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Int64Counter(name, options...) } m.mtx.Lock() defer m.mtx.Unlock() i := &siCounter{name: name, opts: options} m.instruments = append(m.instruments, i) return i, nil } func (m *meter) Int64UpDownCounter(name string, options ...metric.Int64UpDownCounterOption) (metric.Int64UpDownCounter, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Int64UpDownCounter(name, options...) } m.mtx.Lock() defer m.mtx.Unlock() i := &siUpDownCounter{name: name, opts: options} m.instruments = append(m.instruments, i) return i, nil } func (m *meter) Int64Histogram(name string, options ...metric.Int64HistogramOption) (metric.Int64Histogram, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Int64Histogram(name, options...) } m.mtx.Lock() defer m.mtx.Unlock() i := &siHistogram{name: name, opts: options} m.instruments = append(m.instruments, i) return i, nil } func (m *meter) Int64Gauge(name string, options ...metric.Int64GaugeOption) (metric.Int64Gauge, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Int64Gauge(name, options...) } m.mtx.Lock() defer m.mtx.Unlock() i := &siGauge{name: name, opts: options} m.instruments = append(m.instruments, i) return i, nil } func (m *meter) Int64ObservableCounter(name string, options ...metric.Int64ObservableCounterOption) (metric.Int64ObservableCounter, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Int64ObservableCounter(name, options...) } m.mtx.Lock() defer m.mtx.Unlock() i := &aiCounter{name: name, opts: options} m.instruments = append(m.instruments, i) return i, nil } func (m *meter) Int64ObservableUpDownCounter(name string, options ...metric.Int64ObservableUpDownCounterOption) (metric.Int64ObservableUpDownCounter, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Int64ObservableUpDownCounter(name, options...) } m.mtx.Lock() defer m.mtx.Unlock() i := &aiUpDownCounter{name: name, opts: options} m.instruments = append(m.instruments, i) return i, nil } func (m *meter) Int64ObservableGauge(name string, options ...metric.Int64ObservableGaugeOption) (metric.Int64ObservableGauge, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Int64ObservableGauge(name, options...) } m.mtx.Lock() defer m.mtx.Unlock() i := &aiGauge{name: name, opts: options} m.instruments = append(m.instruments, i) return i, nil } func (m *meter) Float64Counter(name string, options ...metric.Float64CounterOption) (metric.Float64Counter, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Float64Counter(name, options...) } m.mtx.Lock() defer m.mtx.Unlock() i := &sfCounter{name: name, opts: options} m.instruments = append(m.instruments, i) return i, nil } func (m *meter) Float64UpDownCounter(name string, options ...metric.Float64UpDownCounterOption) (metric.Float64UpDownCounter, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Float64UpDownCounter(name, options...) } m.mtx.Lock() defer m.mtx.Unlock() i := &sfUpDownCounter{name: name, opts: options} m.instruments = append(m.instruments, i) return i, nil } func (m *meter) Float64Histogram(name string, options ...metric.Float64HistogramOption) (metric.Float64Histogram, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Float64Histogram(name, options...) } m.mtx.Lock() defer m.mtx.Unlock() i := &sfHistogram{name: name, opts: options} m.instruments = append(m.instruments, i) return i, nil } func (m *meter) Float64Gauge(name string, options ...metric.Float64GaugeOption) (metric.Float64Gauge, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Float64Gauge(name, options...) } m.mtx.Lock() defer m.mtx.Unlock() i := &sfGauge{name: name, opts: options} m.instruments = append(m.instruments, i) return i, nil } func (m *meter) Float64ObservableCounter(name string, options ...metric.Float64ObservableCounterOption) (metric.Float64ObservableCounter, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Float64ObservableCounter(name, options...) } m.mtx.Lock() defer m.mtx.Unlock() i := &afCounter{name: name, opts: options} m.instruments = append(m.instruments, i) return i, nil } func (m *meter) Float64ObservableUpDownCounter(name string, options ...metric.Float64ObservableUpDownCounterOption) (metric.Float64ObservableUpDownCounter, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Float64ObservableUpDownCounter(name, options...) } m.mtx.Lock() defer m.mtx.Unlock() i := &afUpDownCounter{name: name, opts: options} m.instruments = append(m.instruments, i) return i, nil } func (m *meter) Float64ObservableGauge(name string, options ...metric.Float64ObservableGaugeOption) (metric.Float64ObservableGauge, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { return del.Float64ObservableGauge(name, options...) } m.mtx.Lock() defer m.mtx.Unlock() i := &afGauge{name: name, opts: options} m.instruments = append(m.instruments, i) return i, nil } // RegisterCallback captures the function that will be called during Collect. func (m *meter) RegisterCallback(f metric.Callback, insts ...metric.Observable) (metric.Registration, error) { if del, ok := m.delegate.Load().(metric.Meter); ok { insts = unwrapInstruments(insts) return del.RegisterCallback(f, insts...) } m.mtx.Lock() defer m.mtx.Unlock() reg := &registration{instruments: insts, function: f} e := m.registry.PushBack(reg) reg.unreg = func() error { m.mtx.Lock() _ = m.registry.Remove(e) m.mtx.Unlock() return nil } return reg, nil } type wrapped interface { unwrap() metric.Observable } func unwrapInstruments(instruments []metric.Observable) []metric.Observable { out := make([]metric.Observable, 0, len(instruments)) for _, inst := range instruments { if in, ok := inst.(wrapped); ok { out = append(out, in.unwrap()) } else { out = append(out, inst) } } return out } type registration struct { embedded.Registration instruments []metric.Observable function metric.Callback unreg func() error unregMu sync.Mutex } func (c *registration) setDelegate(m metric.Meter) { insts := unwrapInstruments(c.instruments) c.unregMu.Lock() defer c.unregMu.Unlock() if c.unreg == nil { // Unregister already called. return } reg, err := m.RegisterCallback(c.function, insts...) if err != nil { GetErrorHandler().Handle(err) } c.unreg = reg.Unregister } func (c *registration) Unregister() error { c.unregMu.Lock() defer c.unregMu.Unlock() if c.unreg == nil { // Unregister already called. return nil } var err error err, c.unreg = c.unreg(), nil return err }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/internal/baggage/baggage.go
vendor/go.opentelemetry.io/otel/internal/baggage/baggage.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 /* Package baggage provides base types and functionality to store and retrieve baggage in Go context. This package exists because the OpenTracing bridge to OpenTelemetry needs to synchronize state whenever baggage for a context is modified and that context contains an OpenTracing span. If it were not for this need this package would not need to exist and the `go.opentelemetry.io/otel/baggage` package would be the singular place where W3C baggage is handled. */ package baggage // import "go.opentelemetry.io/otel/internal/baggage" // List is the collection of baggage members. The W3C allows for duplicates, // but OpenTelemetry does not, therefore, this is represented as a map. type List map[string]Item // Item is the value and metadata properties part of a list-member. type Item struct { Value string Properties []Property } // Property is a metadata entry for a list-member. type Property struct { Key, Value string // HasValue indicates if a zero-value value means the property does not // have a value or if it was the zero-value. HasValue bool }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/internal/baggage/context.go
vendor/go.opentelemetry.io/otel/internal/baggage/context.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package baggage // import "go.opentelemetry.io/otel/internal/baggage" import "context" type baggageContextKeyType int const baggageKey baggageContextKeyType = iota // SetHookFunc is a callback called when storing baggage in the context. type SetHookFunc func(context.Context, List) context.Context // GetHookFunc is a callback called when getting baggage from the context. type GetHookFunc func(context.Context, List) List type baggageState struct { list List setHook SetHookFunc getHook GetHookFunc } // ContextWithSetHook returns a copy of parent with hook configured to be // invoked every time ContextWithBaggage is called. // // Passing nil SetHookFunc creates a context with no set hook to call. func ContextWithSetHook(parent context.Context, hook SetHookFunc) context.Context { var s baggageState if v, ok := parent.Value(baggageKey).(baggageState); ok { s = v } s.setHook = hook return context.WithValue(parent, baggageKey, s) } // ContextWithGetHook returns a copy of parent with hook configured to be // invoked every time FromContext is called. // // Passing nil GetHookFunc creates a context with no get hook to call. func ContextWithGetHook(parent context.Context, hook GetHookFunc) context.Context { var s baggageState if v, ok := parent.Value(baggageKey).(baggageState); ok { s = v } s.getHook = hook return context.WithValue(parent, baggageKey, s) } // ContextWithList returns a copy of parent with baggage. Passing nil list // returns a context without any baggage. func ContextWithList(parent context.Context, list List) context.Context { var s baggageState if v, ok := parent.Value(baggageKey).(baggageState); ok { s = v } s.list = list ctx := context.WithValue(parent, baggageKey, s) if s.setHook != nil { ctx = s.setHook(ctx, list) } return ctx } // ListFromContext returns the baggage contained in ctx. func ListFromContext(ctx context.Context) List { switch v := ctx.Value(baggageKey).(type) { case baggageState: if v.getHook != nil { return v.getHook(ctx, v.list) } return v.list default: return nil } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/internal/attribute/attribute.go
vendor/go.opentelemetry.io/otel/internal/attribute/attribute.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 /* Package attribute provide several helper functions for some commonly used logic of processing attributes. */ package attribute // import "go.opentelemetry.io/otel/internal/attribute" import ( "reflect" ) // BoolSliceValue converts a bool slice into an array with same elements as slice. func BoolSliceValue(v []bool) interface{} { var zero bool cp := reflect.New(reflect.ArrayOf(len(v), reflect.TypeOf(zero))).Elem() reflect.Copy(cp, reflect.ValueOf(v)) return cp.Interface() } // Int64SliceValue converts an int64 slice into an array with same elements as slice. func Int64SliceValue(v []int64) interface{} { var zero int64 cp := reflect.New(reflect.ArrayOf(len(v), reflect.TypeOf(zero))).Elem() reflect.Copy(cp, reflect.ValueOf(v)) return cp.Interface() } // Float64SliceValue converts a float64 slice into an array with same elements as slice. func Float64SliceValue(v []float64) interface{} { var zero float64 cp := reflect.New(reflect.ArrayOf(len(v), reflect.TypeOf(zero))).Elem() reflect.Copy(cp, reflect.ValueOf(v)) return cp.Interface() } // StringSliceValue converts a string slice into an array with same elements as slice. func StringSliceValue(v []string) interface{} { var zero string cp := reflect.New(reflect.ArrayOf(len(v), reflect.TypeOf(zero))).Elem() reflect.Copy(cp, reflect.ValueOf(v)) return cp.Interface() } // AsBoolSlice converts a bool array into a slice into with same elements as array. func AsBoolSlice(v interface{}) []bool { rv := reflect.ValueOf(v) if rv.Type().Kind() != reflect.Array { return nil } var zero bool correctLen := rv.Len() correctType := reflect.ArrayOf(correctLen, reflect.TypeOf(zero)) cpy := reflect.New(correctType) _ = reflect.Copy(cpy.Elem(), rv) return cpy.Elem().Slice(0, correctLen).Interface().([]bool) } // AsInt64Slice converts an int64 array into a slice into with same elements as array. func AsInt64Slice(v interface{}) []int64 { rv := reflect.ValueOf(v) if rv.Type().Kind() != reflect.Array { return nil } var zero int64 correctLen := rv.Len() correctType := reflect.ArrayOf(correctLen, reflect.TypeOf(zero)) cpy := reflect.New(correctType) _ = reflect.Copy(cpy.Elem(), rv) return cpy.Elem().Slice(0, correctLen).Interface().([]int64) } // AsFloat64Slice converts a float64 array into a slice into with same elements as array. func AsFloat64Slice(v interface{}) []float64 { rv := reflect.ValueOf(v) if rv.Type().Kind() != reflect.Array { return nil } var zero float64 correctLen := rv.Len() correctType := reflect.ArrayOf(correctLen, reflect.TypeOf(zero)) cpy := reflect.New(correctType) _ = reflect.Copy(cpy.Elem(), rv) return cpy.Elem().Slice(0, correctLen).Interface().([]float64) } // AsStringSlice converts a string array into a slice into with same elements as array. func AsStringSlice(v interface{}) []string { rv := reflect.ValueOf(v) if rv.Type().Kind() != reflect.Array { return nil } var zero string correctLen := rv.Len() correctType := reflect.ArrayOf(correctLen, reflect.TypeOf(zero)) cpy := reflect.New(correctType) _ = reflect.Copy(cpy.Elem(), rv) return cpy.Elem().Slice(0, correctLen).Interface().([]string) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/propagation/baggage.go
vendor/go.opentelemetry.io/otel/propagation/baggage.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package propagation // import "go.opentelemetry.io/otel/propagation" import ( "context" "go.opentelemetry.io/otel/baggage" ) const baggageHeader = "baggage" // Baggage is a propagator that supports the W3C Baggage format. // // This propagates user-defined baggage associated with a trace. The complete // specification is defined at https://www.w3.org/TR/baggage/. type Baggage struct{} var _ TextMapPropagator = Baggage{} // Inject sets baggage key-values from ctx into the carrier. func (b Baggage) Inject(ctx context.Context, carrier TextMapCarrier) { bStr := baggage.FromContext(ctx).String() if bStr != "" { carrier.Set(baggageHeader, bStr) } } // Extract returns a copy of parent with the baggage from the carrier added. func (b Baggage) Extract(parent context.Context, carrier TextMapCarrier) context.Context { bStr := carrier.Get(baggageHeader) if bStr == "" { return parent } bag, err := baggage.Parse(bStr) if err != nil { return parent } return baggage.ContextWithBaggage(parent, bag) } // Fields returns the keys who's values are set with Inject. func (b Baggage) Fields() []string { return []string{baggageHeader} }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/propagation/doc.go
vendor/go.opentelemetry.io/otel/propagation/doc.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 /* Package propagation contains OpenTelemetry context propagators. OpenTelemetry propagators are used to extract and inject context data from and into messages exchanged by applications. The propagator supported by this package is the W3C Trace Context encoding (https://www.w3.org/TR/trace-context/), and W3C Baggage (https://www.w3.org/TR/baggage/). */ package propagation // import "go.opentelemetry.io/otel/propagation"
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/propagation/trace_context.go
vendor/go.opentelemetry.io/otel/propagation/trace_context.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package propagation // import "go.opentelemetry.io/otel/propagation" import ( "context" "encoding/hex" "fmt" "strings" "go.opentelemetry.io/otel/trace" ) const ( supportedVersion = 0 maxVersion = 254 traceparentHeader = "traceparent" tracestateHeader = "tracestate" delimiter = "-" ) // TraceContext is a propagator that supports the W3C Trace Context format // (https://www.w3.org/TR/trace-context/) // // This propagator will propagate the traceparent and tracestate headers to // guarantee traces are not broken. It is up to the users of this propagator // to choose if they want to participate in a trace by modifying the // traceparent header and relevant parts of the tracestate header containing // their proprietary information. type TraceContext struct{} var ( _ TextMapPropagator = TraceContext{} versionPart = fmt.Sprintf("%.2X", supportedVersion) ) // Inject injects the trace context from ctx into carrier. func (tc TraceContext) Inject(ctx context.Context, carrier TextMapCarrier) { sc := trace.SpanContextFromContext(ctx) if !sc.IsValid() { return } if ts := sc.TraceState().String(); ts != "" { carrier.Set(tracestateHeader, ts) } // Clear all flags other than the trace-context supported sampling bit. flags := sc.TraceFlags() & trace.FlagsSampled var sb strings.Builder sb.Grow(2 + 32 + 16 + 2 + 3) _, _ = sb.WriteString(versionPart) traceID := sc.TraceID() spanID := sc.SpanID() flagByte := [1]byte{byte(flags)} var buf [32]byte for _, src := range [][]byte{traceID[:], spanID[:], flagByte[:]} { _ = sb.WriteByte(delimiter[0]) n := hex.Encode(buf[:], src) _, _ = sb.Write(buf[:n]) } carrier.Set(traceparentHeader, sb.String()) } // Extract reads tracecontext from the carrier into a returned Context. // // The returned Context will be a copy of ctx and contain the extracted // tracecontext as the remote SpanContext. If the extracted tracecontext is // invalid, the passed ctx will be returned directly instead. func (tc TraceContext) Extract(ctx context.Context, carrier TextMapCarrier) context.Context { sc := tc.extract(carrier) if !sc.IsValid() { return ctx } return trace.ContextWithRemoteSpanContext(ctx, sc) } func (tc TraceContext) extract(carrier TextMapCarrier) trace.SpanContext { h := carrier.Get(traceparentHeader) if h == "" { return trace.SpanContext{} } var ver [1]byte if !extractPart(ver[:], &h, 2) { return trace.SpanContext{} } version := int(ver[0]) if version > maxVersion { return trace.SpanContext{} } var scc trace.SpanContextConfig if !extractPart(scc.TraceID[:], &h, 32) { return trace.SpanContext{} } if !extractPart(scc.SpanID[:], &h, 16) { return trace.SpanContext{} } var opts [1]byte if !extractPart(opts[:], &h, 2) { return trace.SpanContext{} } if version == 0 && (h != "" || opts[0] > 2) { // version 0 not allow extra // version 0 not allow other flag return trace.SpanContext{} } // Clear all flags other than the trace-context supported sampling bit. scc.TraceFlags = trace.TraceFlags(opts[0]) & trace.FlagsSampled // Ignore the error returned here. Failure to parse tracestate MUST NOT // affect the parsing of traceparent according to the W3C tracecontext // specification. scc.TraceState, _ = trace.ParseTraceState(carrier.Get(tracestateHeader)) scc.Remote = true sc := trace.NewSpanContext(scc) if !sc.IsValid() { return trace.SpanContext{} } return sc } // upperHex detect hex is upper case Unicode characters. func upperHex(v string) bool { for _, c := range v { if c >= 'A' && c <= 'F' { return true } } return false } func extractPart(dst []byte, h *string, n int) bool { part, left, _ := strings.Cut(*h, delimiter) *h = left // hex.Decode decodes unsupported upper-case characters, so exclude explicitly. if len(part) != n || upperHex(part) { return false } if p, err := hex.Decode(dst, []byte(part)); err != nil || p != n/2 { return false } return true } // Fields returns the keys who's values are set with Inject. func (tc TraceContext) Fields() []string { return []string{traceparentHeader, tracestateHeader} }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/propagation/propagation.go
vendor/go.opentelemetry.io/otel/propagation/propagation.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package propagation // import "go.opentelemetry.io/otel/propagation" import ( "context" "net/http" ) // TextMapCarrier is the storage medium used by a TextMapPropagator. type TextMapCarrier interface { // DO NOT CHANGE: any modification will not be backwards compatible and // must never be done outside of a new major release. // Get returns the value associated with the passed key. Get(key string) string // DO NOT CHANGE: any modification will not be backwards compatible and // must never be done outside of a new major release. // Set stores the key-value pair. Set(key string, value string) // DO NOT CHANGE: any modification will not be backwards compatible and // must never be done outside of a new major release. // Keys lists the keys stored in this carrier. Keys() []string // DO NOT CHANGE: any modification will not be backwards compatible and // must never be done outside of a new major release. } // MapCarrier is a TextMapCarrier that uses a map held in memory as a storage // medium for propagated key-value pairs. type MapCarrier map[string]string // Compile time check that MapCarrier implements the TextMapCarrier. var _ TextMapCarrier = MapCarrier{} // Get returns the value associated with the passed key. func (c MapCarrier) Get(key string) string { return c[key] } // Set stores the key-value pair. func (c MapCarrier) Set(key, value string) { c[key] = value } // Keys lists the keys stored in this carrier. func (c MapCarrier) Keys() []string { keys := make([]string, 0, len(c)) for k := range c { keys = append(keys, k) } return keys } // HeaderCarrier adapts http.Header to satisfy the TextMapCarrier interface. type HeaderCarrier http.Header // Get returns the value associated with the passed key. func (hc HeaderCarrier) Get(key string) string { return http.Header(hc).Get(key) } // Set stores the key-value pair. func (hc HeaderCarrier) Set(key string, value string) { http.Header(hc).Set(key, value) } // Keys lists the keys stored in this carrier. func (hc HeaderCarrier) Keys() []string { keys := make([]string, 0, len(hc)) for k := range hc { keys = append(keys, k) } return keys } // TextMapPropagator propagates cross-cutting concerns as key-value text // pairs within a carrier that travels in-band across process boundaries. type TextMapPropagator interface { // DO NOT CHANGE: any modification will not be backwards compatible and // must never be done outside of a new major release. // Inject set cross-cutting concerns from the Context into the carrier. Inject(ctx context.Context, carrier TextMapCarrier) // DO NOT CHANGE: any modification will not be backwards compatible and // must never be done outside of a new major release. // Extract reads cross-cutting concerns from the carrier into a Context. Extract(ctx context.Context, carrier TextMapCarrier) context.Context // DO NOT CHANGE: any modification will not be backwards compatible and // must never be done outside of a new major release. // Fields returns the keys whose values are set with Inject. Fields() []string // DO NOT CHANGE: any modification will not be backwards compatible and // must never be done outside of a new major release. } type compositeTextMapPropagator []TextMapPropagator func (p compositeTextMapPropagator) Inject(ctx context.Context, carrier TextMapCarrier) { for _, i := range p { i.Inject(ctx, carrier) } } func (p compositeTextMapPropagator) Extract(ctx context.Context, carrier TextMapCarrier) context.Context { for _, i := range p { ctx = i.Extract(ctx, carrier) } return ctx } func (p compositeTextMapPropagator) Fields() []string { unique := make(map[string]struct{}) for _, i := range p { for _, k := range i.Fields() { unique[k] = struct{}{} } } fields := make([]string, 0, len(unique)) for k := range unique { fields = append(fields, k) } return fields } // NewCompositeTextMapPropagator returns a unified TextMapPropagator from the // group of passed TextMapPropagator. This allows different cross-cutting // concerns to be propagates in a unified manner. // // The returned TextMapPropagator will inject and extract cross-cutting // concerns in the order the TextMapPropagators were provided. Additionally, // the Fields method will return a de-duplicated slice of the keys that are // set with the Inject method. func NewCompositeTextMapPropagator(p ...TextMapPropagator) TextMapPropagator { return compositeTextMapPropagator(p) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/attribute/kv.go
vendor/go.opentelemetry.io/otel/attribute/kv.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package attribute // import "go.opentelemetry.io/otel/attribute" import ( "fmt" ) // KeyValue holds a key and value pair. type KeyValue struct { Key Key Value Value } // Valid returns if kv is a valid OpenTelemetry attribute. func (kv KeyValue) Valid() bool { return kv.Key.Defined() && kv.Value.Type() != INVALID } // Bool creates a KeyValue with a BOOL Value type. func Bool(k string, v bool) KeyValue { return Key(k).Bool(v) } // BoolSlice creates a KeyValue with a BOOLSLICE Value type. func BoolSlice(k string, v []bool) KeyValue { return Key(k).BoolSlice(v) } // Int creates a KeyValue with an INT64 Value type. func Int(k string, v int) KeyValue { return Key(k).Int(v) } // IntSlice creates a KeyValue with an INT64SLICE Value type. func IntSlice(k string, v []int) KeyValue { return Key(k).IntSlice(v) } // Int64 creates a KeyValue with an INT64 Value type. func Int64(k string, v int64) KeyValue { return Key(k).Int64(v) } // Int64Slice creates a KeyValue with an INT64SLICE Value type. func Int64Slice(k string, v []int64) KeyValue { return Key(k).Int64Slice(v) } // Float64 creates a KeyValue with a FLOAT64 Value type. func Float64(k string, v float64) KeyValue { return Key(k).Float64(v) } // Float64Slice creates a KeyValue with a FLOAT64SLICE Value type. func Float64Slice(k string, v []float64) KeyValue { return Key(k).Float64Slice(v) } // String creates a KeyValue with a STRING Value type. func String(k, v string) KeyValue { return Key(k).String(v) } // StringSlice creates a KeyValue with a STRINGSLICE Value type. func StringSlice(k string, v []string) KeyValue { return Key(k).StringSlice(v) } // Stringer creates a new key-value pair with a passed name and a string // value generated by the passed Stringer interface. func Stringer(k string, v fmt.Stringer) KeyValue { return Key(k).String(v.String()) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/attribute/type_string.go
vendor/go.opentelemetry.io/otel/attribute/type_string.go
// Code generated by "stringer -type=Type"; DO NOT EDIT. package attribute import "strconv" func _() { // An "invalid array index" compiler error signifies that the constant values have changed. // Re-run the stringer command to generate them again. var x [1]struct{} _ = x[INVALID-0] _ = x[BOOL-1] _ = x[INT64-2] _ = x[FLOAT64-3] _ = x[STRING-4] _ = x[BOOLSLICE-5] _ = x[INT64SLICE-6] _ = x[FLOAT64SLICE-7] _ = x[STRINGSLICE-8] } const _Type_name = "INVALIDBOOLINT64FLOAT64STRINGBOOLSLICEINT64SLICEFLOAT64SLICESTRINGSLICE" var _Type_index = [...]uint8{0, 7, 11, 16, 23, 29, 38, 48, 60, 71} func (i Type) String() string { if i < 0 || i >= Type(len(_Type_index)-1) { return "Type(" + strconv.FormatInt(int64(i), 10) + ")" } return _Type_name[_Type_index[i]:_Type_index[i+1]] }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/attribute/filter.go
vendor/go.opentelemetry.io/otel/attribute/filter.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package attribute // import "go.opentelemetry.io/otel/attribute" // Filter supports removing certain attributes from attribute sets. When // the filter returns true, the attribute will be kept in the filtered // attribute set. When the filter returns false, the attribute is excluded // from the filtered attribute set, and the attribute instead appears in // the removed list of excluded attributes. type Filter func(KeyValue) bool // NewAllowKeysFilter returns a Filter that only allows attributes with one of // the provided keys. // // If keys is empty a deny-all filter is returned. func NewAllowKeysFilter(keys ...Key) Filter { if len(keys) <= 0 { return func(kv KeyValue) bool { return false } } allowed := make(map[Key]struct{}) for _, k := range keys { allowed[k] = struct{}{} } return func(kv KeyValue) bool { _, ok := allowed[kv.Key] return ok } } // NewDenyKeysFilter returns a Filter that only allows attributes // that do not have one of the provided keys. // // If keys is empty an allow-all filter is returned. func NewDenyKeysFilter(keys ...Key) Filter { if len(keys) <= 0 { return func(kv KeyValue) bool { return true } } forbid := make(map[Key]struct{}) for _, k := range keys { forbid[k] = struct{}{} } return func(kv KeyValue) bool { _, ok := forbid[kv.Key] return !ok } }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/attribute/iterator.go
vendor/go.opentelemetry.io/otel/attribute/iterator.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package attribute // import "go.opentelemetry.io/otel/attribute" // Iterator allows iterating over the set of attributes in order, sorted by // key. type Iterator struct { storage *Set idx int } // MergeIterator supports iterating over two sets of attributes while // eliminating duplicate values from the combined set. The first iterator // value takes precedence. type MergeIterator struct { one oneIterator two oneIterator current KeyValue } type oneIterator struct { iter Iterator done bool attr KeyValue } // Next moves the iterator to the next position. Returns false if there are no // more attributes. func (i *Iterator) Next() bool { i.idx++ return i.idx < i.Len() } // Label returns current KeyValue. Must be called only after Next returns // true. // // Deprecated: Use Attribute instead. func (i *Iterator) Label() KeyValue { return i.Attribute() } // Attribute returns the current KeyValue of the Iterator. It must be called // only after Next returns true. func (i *Iterator) Attribute() KeyValue { kv, _ := i.storage.Get(i.idx) return kv } // IndexedLabel returns current index and attribute. Must be called only // after Next returns true. // // Deprecated: Use IndexedAttribute instead. func (i *Iterator) IndexedLabel() (int, KeyValue) { return i.idx, i.Attribute() } // IndexedAttribute returns current index and attribute. Must be called only // after Next returns true. func (i *Iterator) IndexedAttribute() (int, KeyValue) { return i.idx, i.Attribute() } // Len returns a number of attributes in the iterated set. func (i *Iterator) Len() int { return i.storage.Len() } // ToSlice is a convenience function that creates a slice of attributes from // the passed iterator. The iterator is set up to start from the beginning // before creating the slice. func (i *Iterator) ToSlice() []KeyValue { l := i.Len() if l == 0 { return nil } i.idx = -1 slice := make([]KeyValue, 0, l) for i.Next() { slice = append(slice, i.Attribute()) } return slice } // NewMergeIterator returns a MergeIterator for merging two attribute sets. // Duplicates are resolved by taking the value from the first set. func NewMergeIterator(s1, s2 *Set) MergeIterator { mi := MergeIterator{ one: makeOne(s1.Iter()), two: makeOne(s2.Iter()), } return mi } func makeOne(iter Iterator) oneIterator { oi := oneIterator{ iter: iter, } oi.advance() return oi } func (oi *oneIterator) advance() { if oi.done = !oi.iter.Next(); !oi.done { oi.attr = oi.iter.Attribute() } } // Next returns true if there is another attribute available. func (m *MergeIterator) Next() bool { if m.one.done && m.two.done { return false } if m.one.done { m.current = m.two.attr m.two.advance() return true } if m.two.done { m.current = m.one.attr m.one.advance() return true } if m.one.attr.Key == m.two.attr.Key { m.current = m.one.attr // first iterator attribute value wins m.one.advance() m.two.advance() return true } if m.one.attr.Key < m.two.attr.Key { m.current = m.one.attr m.one.advance() return true } m.current = m.two.attr m.two.advance() return true } // Label returns the current value after Next() returns true. // // Deprecated: Use Attribute instead. func (m *MergeIterator) Label() KeyValue { return m.current } // Attribute returns the current value after Next() returns true. func (m *MergeIterator) Attribute() KeyValue { return m.current }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/attribute/set.go
vendor/go.opentelemetry.io/otel/attribute/set.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package attribute // import "go.opentelemetry.io/otel/attribute" import ( "cmp" "encoding/json" "reflect" "slices" "sort" ) type ( // Set is the representation for a distinct attribute set. It manages an // immutable set of attributes, with an internal cache for storing // attribute encodings. // // This type will remain comparable for backwards compatibility. The // equivalence of Sets across versions is not guaranteed to be stable. // Prior versions may find two Sets to be equal or not when compared // directly (i.e. ==), but subsequent versions may not. Users should use // the Equals method to ensure stable equivalence checking. // // Users should also use the Distinct returned from Equivalent as a map key // instead of a Set directly. In addition to that type providing guarantees // on stable equivalence, it may also provide performance improvements. Set struct { equivalent Distinct } // Distinct is a unique identifier of a Set. // // Distinct is designed to be ensures equivalence stability: comparisons // will return the save value across versions. For this reason, Distinct // should always be used as a map key instead of a Set. Distinct struct { iface interface{} } // Sortable implements sort.Interface, used for sorting KeyValue. // // Deprecated: This type is no longer used. It was added as a performance // optimization for Go < 1.21 that is no longer needed (Go < 1.21 is no // longer supported by the module). Sortable []KeyValue ) var ( // keyValueType is used in computeDistinctReflect. keyValueType = reflect.TypeOf(KeyValue{}) // emptySet is returned for empty attribute sets. emptySet = &Set{ equivalent: Distinct{ iface: [0]KeyValue{}, }, } ) // EmptySet returns a reference to a Set with no elements. // // This is a convenience provided for optimized calling utility. func EmptySet() *Set { return emptySet } // reflectValue abbreviates reflect.ValueOf(d). func (d Distinct) reflectValue() reflect.Value { return reflect.ValueOf(d.iface) } // Valid returns true if this value refers to a valid Set. func (d Distinct) Valid() bool { return d.iface != nil } // Len returns the number of attributes in this set. func (l *Set) Len() int { if l == nil || !l.equivalent.Valid() { return 0 } return l.equivalent.reflectValue().Len() } // Get returns the KeyValue at ordered position idx in this set. func (l *Set) Get(idx int) (KeyValue, bool) { if l == nil || !l.equivalent.Valid() { return KeyValue{}, false } value := l.equivalent.reflectValue() if idx >= 0 && idx < value.Len() { // Note: The Go compiler successfully avoids an allocation for // the interface{} conversion here: return value.Index(idx).Interface().(KeyValue), true } return KeyValue{}, false } // Value returns the value of a specified key in this set. func (l *Set) Value(k Key) (Value, bool) { if l == nil || !l.equivalent.Valid() { return Value{}, false } rValue := l.equivalent.reflectValue() vlen := rValue.Len() idx := sort.Search(vlen, func(idx int) bool { return rValue.Index(idx).Interface().(KeyValue).Key >= k }) if idx >= vlen { return Value{}, false } keyValue := rValue.Index(idx).Interface().(KeyValue) if k == keyValue.Key { return keyValue.Value, true } return Value{}, false } // HasValue tests whether a key is defined in this set. func (l *Set) HasValue(k Key) bool { if l == nil { return false } _, ok := l.Value(k) return ok } // Iter returns an iterator for visiting the attributes in this set. func (l *Set) Iter() Iterator { return Iterator{ storage: l, idx: -1, } } // ToSlice returns the set of attributes belonging to this set, sorted, where // keys appear no more than once. func (l *Set) ToSlice() []KeyValue { iter := l.Iter() return iter.ToSlice() } // Equivalent returns a value that may be used as a map key. The Distinct type // guarantees that the result will equal the equivalent. Distinct value of any // attribute set with the same elements as this, where sets are made unique by // choosing the last value in the input for any given key. func (l *Set) Equivalent() Distinct { if l == nil || !l.equivalent.Valid() { return emptySet.equivalent } return l.equivalent } // Equals returns true if the argument set is equivalent to this set. func (l *Set) Equals(o *Set) bool { return l.Equivalent() == o.Equivalent() } // Encoded returns the encoded form of this set, according to encoder. func (l *Set) Encoded(encoder Encoder) string { if l == nil || encoder == nil { return "" } return encoder.Encode(l.Iter()) } func empty() Set { return Set{ equivalent: emptySet.equivalent, } } // NewSet returns a new Set. See the documentation for // NewSetWithSortableFiltered for more details. // // Except for empty sets, this method adds an additional allocation compared // with calls that include a Sortable. func NewSet(kvs ...KeyValue) Set { s, _ := NewSetWithFiltered(kvs, nil) return s } // NewSetWithSortable returns a new Set. See the documentation for // NewSetWithSortableFiltered for more details. // // This call includes a Sortable option as a memory optimization. // // Deprecated: Use [NewSet] instead. func NewSetWithSortable(kvs []KeyValue, _ *Sortable) Set { s, _ := NewSetWithFiltered(kvs, nil) return s } // NewSetWithFiltered returns a new Set. See the documentation for // NewSetWithSortableFiltered for more details. // // This call includes a Filter to include/exclude attribute keys from the // return value. Excluded keys are returned as a slice of attribute values. func NewSetWithFiltered(kvs []KeyValue, filter Filter) (Set, []KeyValue) { // Check for empty set. if len(kvs) == 0 { return empty(), nil } // Stable sort so the following de-duplication can implement // last-value-wins semantics. slices.SortStableFunc(kvs, func(a, b KeyValue) int { return cmp.Compare(a.Key, b.Key) }) position := len(kvs) - 1 offset := position - 1 // The requirements stated above require that the stable // result be placed in the end of the input slice, while // overwritten values are swapped to the beginning. // // De-duplicate with last-value-wins semantics. Preserve // duplicate values at the beginning of the input slice. for ; offset >= 0; offset-- { if kvs[offset].Key == kvs[position].Key { continue } position-- kvs[offset], kvs[position] = kvs[position], kvs[offset] } kvs = kvs[position:] if filter != nil { if div := filteredToFront(kvs, filter); div != 0 { return Set{equivalent: computeDistinct(kvs[div:])}, kvs[:div] } } return Set{equivalent: computeDistinct(kvs)}, nil } // NewSetWithSortableFiltered returns a new Set. // // Duplicate keys are eliminated by taking the last value. This // re-orders the input slice so that unique last-values are contiguous // at the end of the slice. // // This ensures the following: // // - Last-value-wins semantics // - Caller sees the reordering, but doesn't lose values // - Repeated call preserve last-value wins. // // Note that methods are defined on Set, although this returns Set. Callers // can avoid memory allocations by: // // - allocating a Sortable for use as a temporary in this method // - allocating a Set for storing the return value of this constructor. // // The result maintains a cache of encoded attributes, by attribute.EncoderID. // This value should not be copied after its first use. // // The second []KeyValue return value is a list of attributes that were // excluded by the Filter (if non-nil). // // Deprecated: Use [NewSetWithFiltered] instead. func NewSetWithSortableFiltered(kvs []KeyValue, _ *Sortable, filter Filter) (Set, []KeyValue) { return NewSetWithFiltered(kvs, filter) } // filteredToFront filters slice in-place using keep function. All KeyValues that need to // be removed are moved to the front. All KeyValues that need to be kept are // moved (in-order) to the back. The index for the first KeyValue to be kept is // returned. func filteredToFront(slice []KeyValue, keep Filter) int { n := len(slice) j := n for i := n - 1; i >= 0; i-- { if keep(slice[i]) { j-- slice[i], slice[j] = slice[j], slice[i] } } return j } // Filter returns a filtered copy of this Set. See the documentation for // NewSetWithSortableFiltered for more details. func (l *Set) Filter(re Filter) (Set, []KeyValue) { if re == nil { return *l, nil } // Iterate in reverse to the first attribute that will be filtered out. n := l.Len() first := n - 1 for ; first >= 0; first-- { kv, _ := l.Get(first) if !re(kv) { break } } // No attributes will be dropped, return the immutable Set l and nil. if first < 0 { return *l, nil } // Copy now that we know we need to return a modified set. // // Do not do this in-place on the underlying storage of *Set l. Sets are // immutable and filtering should not change this. slice := l.ToSlice() // Don't re-iterate the slice if only slice[0] is filtered. if first == 0 { // It is safe to assume len(slice) >= 1 given we found at least one // attribute above that needs to be filtered out. return Set{equivalent: computeDistinct(slice[1:])}, slice[:1] } // Move the filtered slice[first] to the front (preserving order). kv := slice[first] copy(slice[1:first+1], slice[:first]) slice[0] = kv // Do not re-evaluate re(slice[first+1:]). div := filteredToFront(slice[1:first+1], re) + 1 return Set{equivalent: computeDistinct(slice[div:])}, slice[:div] } // computeDistinct returns a Distinct using either the fixed- or // reflect-oriented code path, depending on the size of the input. The input // slice is assumed to already be sorted and de-duplicated. func computeDistinct(kvs []KeyValue) Distinct { iface := computeDistinctFixed(kvs) if iface == nil { iface = computeDistinctReflect(kvs) } return Distinct{ iface: iface, } } // computeDistinctFixed computes a Distinct for small slices. It returns nil // if the input is too large for this code path. func computeDistinctFixed(kvs []KeyValue) interface{} { switch len(kvs) { case 1: ptr := new([1]KeyValue) copy((*ptr)[:], kvs) return *ptr case 2: ptr := new([2]KeyValue) copy((*ptr)[:], kvs) return *ptr case 3: ptr := new([3]KeyValue) copy((*ptr)[:], kvs) return *ptr case 4: ptr := new([4]KeyValue) copy((*ptr)[:], kvs) return *ptr case 5: ptr := new([5]KeyValue) copy((*ptr)[:], kvs) return *ptr case 6: ptr := new([6]KeyValue) copy((*ptr)[:], kvs) return *ptr case 7: ptr := new([7]KeyValue) copy((*ptr)[:], kvs) return *ptr case 8: ptr := new([8]KeyValue) copy((*ptr)[:], kvs) return *ptr case 9: ptr := new([9]KeyValue) copy((*ptr)[:], kvs) return *ptr case 10: ptr := new([10]KeyValue) copy((*ptr)[:], kvs) return *ptr default: return nil } } // computeDistinctReflect computes a Distinct using reflection, works for any // size input. func computeDistinctReflect(kvs []KeyValue) interface{} { at := reflect.New(reflect.ArrayOf(len(kvs), keyValueType)).Elem() for i, keyValue := range kvs { *(at.Index(i).Addr().Interface().(*KeyValue)) = keyValue } return at.Interface() } // MarshalJSON returns the JSON encoding of the Set. func (l *Set) MarshalJSON() ([]byte, error) { return json.Marshal(l.equivalent.iface) } // MarshalLog is the marshaling function used by the logging system to represent this Set. func (l Set) MarshalLog() interface{} { kvs := make(map[string]string) for _, kv := range l.ToSlice() { kvs[string(kv.Key)] = kv.Value.Emit() } return kvs } // Len implements sort.Interface. func (l *Sortable) Len() int { return len(*l) } // Swap implements sort.Interface. func (l *Sortable) Swap(i, j int) { (*l)[i], (*l)[j] = (*l)[j], (*l)[i] } // Less implements sort.Interface. func (l *Sortable) Less(i, j int) bool { return (*l)[i].Key < (*l)[j].Key }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/attribute/value.go
vendor/go.opentelemetry.io/otel/attribute/value.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package attribute // import "go.opentelemetry.io/otel/attribute" import ( "encoding/json" "fmt" "reflect" "strconv" "go.opentelemetry.io/otel/internal" "go.opentelemetry.io/otel/internal/attribute" ) //go:generate stringer -type=Type // Type describes the type of the data Value holds. type Type int // nolint: revive // redefines builtin Type. // Value represents the value part in key-value pairs. type Value struct { vtype Type numeric uint64 stringly string slice interface{} } const ( // INVALID is used for a Value with no value set. INVALID Type = iota // BOOL is a boolean Type Value. BOOL // INT64 is a 64-bit signed integral Type Value. INT64 // FLOAT64 is a 64-bit floating point Type Value. FLOAT64 // STRING is a string Type Value. STRING // BOOLSLICE is a slice of booleans Type Value. BOOLSLICE // INT64SLICE is a slice of 64-bit signed integral numbers Type Value. INT64SLICE // FLOAT64SLICE is a slice of 64-bit floating point numbers Type Value. FLOAT64SLICE // STRINGSLICE is a slice of strings Type Value. STRINGSLICE ) // BoolValue creates a BOOL Value. func BoolValue(v bool) Value { return Value{ vtype: BOOL, numeric: internal.BoolToRaw(v), } } // BoolSliceValue creates a BOOLSLICE Value. func BoolSliceValue(v []bool) Value { return Value{vtype: BOOLSLICE, slice: attribute.BoolSliceValue(v)} } // IntValue creates an INT64 Value. func IntValue(v int) Value { return Int64Value(int64(v)) } // IntSliceValue creates an INTSLICE Value. func IntSliceValue(v []int) Value { var int64Val int64 cp := reflect.New(reflect.ArrayOf(len(v), reflect.TypeOf(int64Val))) for i, val := range v { cp.Elem().Index(i).SetInt(int64(val)) } return Value{ vtype: INT64SLICE, slice: cp.Elem().Interface(), } } // Int64Value creates an INT64 Value. func Int64Value(v int64) Value { return Value{ vtype: INT64, numeric: internal.Int64ToRaw(v), } } // Int64SliceValue creates an INT64SLICE Value. func Int64SliceValue(v []int64) Value { return Value{vtype: INT64SLICE, slice: attribute.Int64SliceValue(v)} } // Float64Value creates a FLOAT64 Value. func Float64Value(v float64) Value { return Value{ vtype: FLOAT64, numeric: internal.Float64ToRaw(v), } } // Float64SliceValue creates a FLOAT64SLICE Value. func Float64SliceValue(v []float64) Value { return Value{vtype: FLOAT64SLICE, slice: attribute.Float64SliceValue(v)} } // StringValue creates a STRING Value. func StringValue(v string) Value { return Value{ vtype: STRING, stringly: v, } } // StringSliceValue creates a STRINGSLICE Value. func StringSliceValue(v []string) Value { return Value{vtype: STRINGSLICE, slice: attribute.StringSliceValue(v)} } // Type returns a type of the Value. func (v Value) Type() Type { return v.vtype } // AsBool returns the bool value. Make sure that the Value's type is // BOOL. func (v Value) AsBool() bool { return internal.RawToBool(v.numeric) } // AsBoolSlice returns the []bool value. Make sure that the Value's type is // BOOLSLICE. func (v Value) AsBoolSlice() []bool { if v.vtype != BOOLSLICE { return nil } return v.asBoolSlice() } func (v Value) asBoolSlice() []bool { return attribute.AsBoolSlice(v.slice) } // AsInt64 returns the int64 value. Make sure that the Value's type is // INT64. func (v Value) AsInt64() int64 { return internal.RawToInt64(v.numeric) } // AsInt64Slice returns the []int64 value. Make sure that the Value's type is // INT64SLICE. func (v Value) AsInt64Slice() []int64 { if v.vtype != INT64SLICE { return nil } return v.asInt64Slice() } func (v Value) asInt64Slice() []int64 { return attribute.AsInt64Slice(v.slice) } // AsFloat64 returns the float64 value. Make sure that the Value's // type is FLOAT64. func (v Value) AsFloat64() float64 { return internal.RawToFloat64(v.numeric) } // AsFloat64Slice returns the []float64 value. Make sure that the Value's type is // FLOAT64SLICE. func (v Value) AsFloat64Slice() []float64 { if v.vtype != FLOAT64SLICE { return nil } return v.asFloat64Slice() } func (v Value) asFloat64Slice() []float64 { return attribute.AsFloat64Slice(v.slice) } // AsString returns the string value. Make sure that the Value's type // is STRING. func (v Value) AsString() string { return v.stringly } // AsStringSlice returns the []string value. Make sure that the Value's type is // STRINGSLICE. func (v Value) AsStringSlice() []string { if v.vtype != STRINGSLICE { return nil } return v.asStringSlice() } func (v Value) asStringSlice() []string { return attribute.AsStringSlice(v.slice) } type unknownValueType struct{} // AsInterface returns Value's data as interface{}. func (v Value) AsInterface() interface{} { switch v.Type() { case BOOL: return v.AsBool() case BOOLSLICE: return v.asBoolSlice() case INT64: return v.AsInt64() case INT64SLICE: return v.asInt64Slice() case FLOAT64: return v.AsFloat64() case FLOAT64SLICE: return v.asFloat64Slice() case STRING: return v.stringly case STRINGSLICE: return v.asStringSlice() } return unknownValueType{} } // Emit returns a string representation of Value's data. func (v Value) Emit() string { switch v.Type() { case BOOLSLICE: return fmt.Sprint(v.asBoolSlice()) case BOOL: return strconv.FormatBool(v.AsBool()) case INT64SLICE: j, err := json.Marshal(v.asInt64Slice()) if err != nil { return fmt.Sprintf("invalid: %v", v.asInt64Slice()) } return string(j) case INT64: return strconv.FormatInt(v.AsInt64(), 10) case FLOAT64SLICE: j, err := json.Marshal(v.asFloat64Slice()) if err != nil { return fmt.Sprintf("invalid: %v", v.asFloat64Slice()) } return string(j) case FLOAT64: return fmt.Sprint(v.AsFloat64()) case STRINGSLICE: j, err := json.Marshal(v.asStringSlice()) if err != nil { return fmt.Sprintf("invalid: %v", v.asStringSlice()) } return string(j) case STRING: return v.stringly default: return "unknown" } } // MarshalJSON returns the JSON encoding of the Value. func (v Value) MarshalJSON() ([]byte, error) { var jsonVal struct { Type string Value interface{} } jsonVal.Type = v.Type().String() jsonVal.Value = v.AsInterface() return json.Marshal(jsonVal) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/attribute/doc.go
vendor/go.opentelemetry.io/otel/attribute/doc.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 // Package attribute provides key and value attributes. package attribute // import "go.opentelemetry.io/otel/attribute"
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/attribute/key.go
vendor/go.opentelemetry.io/otel/attribute/key.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package attribute // import "go.opentelemetry.io/otel/attribute" // Key represents the key part in key-value pairs. It's a string. The // allowed character set in the key depends on the use of the key. type Key string // Bool creates a KeyValue instance with a BOOL Value. // // If creating both a key and value at the same time, use the provided // convenience function instead -- Bool(name, value). func (k Key) Bool(v bool) KeyValue { return KeyValue{ Key: k, Value: BoolValue(v), } } // BoolSlice creates a KeyValue instance with a BOOLSLICE Value. // // If creating both a key and value at the same time, use the provided // convenience function instead -- BoolSlice(name, value). func (k Key) BoolSlice(v []bool) KeyValue { return KeyValue{ Key: k, Value: BoolSliceValue(v), } } // Int creates a KeyValue instance with an INT64 Value. // // If creating both a key and value at the same time, use the provided // convenience function instead -- Int(name, value). func (k Key) Int(v int) KeyValue { return KeyValue{ Key: k, Value: IntValue(v), } } // IntSlice creates a KeyValue instance with an INT64SLICE Value. // // If creating both a key and value at the same time, use the provided // convenience function instead -- IntSlice(name, value). func (k Key) IntSlice(v []int) KeyValue { return KeyValue{ Key: k, Value: IntSliceValue(v), } } // Int64 creates a KeyValue instance with an INT64 Value. // // If creating both a key and value at the same time, use the provided // convenience function instead -- Int64(name, value). func (k Key) Int64(v int64) KeyValue { return KeyValue{ Key: k, Value: Int64Value(v), } } // Int64Slice creates a KeyValue instance with an INT64SLICE Value. // // If creating both a key and value at the same time, use the provided // convenience function instead -- Int64Slice(name, value). func (k Key) Int64Slice(v []int64) KeyValue { return KeyValue{ Key: k, Value: Int64SliceValue(v), } } // Float64 creates a KeyValue instance with a FLOAT64 Value. // // If creating both a key and value at the same time, use the provided // convenience function instead -- Float64(name, value). func (k Key) Float64(v float64) KeyValue { return KeyValue{ Key: k, Value: Float64Value(v), } } // Float64Slice creates a KeyValue instance with a FLOAT64SLICE Value. // // If creating both a key and value at the same time, use the provided // convenience function instead -- Float64(name, value). func (k Key) Float64Slice(v []float64) KeyValue { return KeyValue{ Key: k, Value: Float64SliceValue(v), } } // String creates a KeyValue instance with a STRING Value. // // If creating both a key and value at the same time, use the provided // convenience function instead -- String(name, value). func (k Key) String(v string) KeyValue { return KeyValue{ Key: k, Value: StringValue(v), } } // StringSlice creates a KeyValue instance with a STRINGSLICE Value. // // If creating both a key and value at the same time, use the provided // convenience function instead -- StringSlice(name, value). func (k Key) StringSlice(v []string) KeyValue { return KeyValue{ Key: k, Value: StringSliceValue(v), } } // Defined returns true for non-empty keys. func (k Key) Defined() bool { return len(k) != 0 }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/attribute/encoder.go
vendor/go.opentelemetry.io/otel/attribute/encoder.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package attribute // import "go.opentelemetry.io/otel/attribute" import ( "bytes" "sync" "sync/atomic" ) type ( // Encoder is a mechanism for serializing an attribute set into a specific // string representation that supports caching, to avoid repeated // serialization. An example could be an exporter encoding the attribute // set into a wire representation. Encoder interface { // Encode returns the serialized encoding of the attribute set using // its Iterator. This result may be cached by a attribute.Set. Encode(iterator Iterator) string // ID returns a value that is unique for each class of attribute // encoder. Attribute encoders allocate these using `NewEncoderID`. ID() EncoderID } // EncoderID is used to identify distinct Encoder // implementations, for caching encoded results. EncoderID struct { value uint64 } // defaultAttrEncoder uses a sync.Pool of buffers to reduce the number of // allocations used in encoding attributes. This implementation encodes a // comma-separated list of key=value, with '/'-escaping of '=', ',', and // '\'. defaultAttrEncoder struct { // pool is a pool of attribute set builders. The buffers in this pool // grow to a size that most attribute encodings will not allocate new // memory. pool sync.Pool // *bytes.Buffer } ) // escapeChar is used to ensure uniqueness of the attribute encoding where // keys or values contain either '=' or ','. Since there is no parser needed // for this encoding and its only requirement is to be unique, this choice is // arbitrary. Users will see these in some exporters (e.g., stdout), so the // backslash ('\') is used as a conventional choice. const escapeChar = '\\' var ( _ Encoder = &defaultAttrEncoder{} // encoderIDCounter is for generating IDs for other attribute encoders. encoderIDCounter uint64 defaultEncoderOnce sync.Once defaultEncoderID = NewEncoderID() defaultEncoderInstance *defaultAttrEncoder ) // NewEncoderID returns a unique attribute encoder ID. It should be called // once per each type of attribute encoder. Preferably in init() or in var // definition. func NewEncoderID() EncoderID { return EncoderID{value: atomic.AddUint64(&encoderIDCounter, 1)} } // DefaultEncoder returns an attribute encoder that encodes attributes in such // a way that each escaped attribute's key is followed by an equal sign and // then by an escaped attribute's value. All key-value pairs are separated by // a comma. // // Escaping is done by prepending a backslash before either a backslash, equal // sign or a comma. func DefaultEncoder() Encoder { defaultEncoderOnce.Do(func() { defaultEncoderInstance = &defaultAttrEncoder{ pool: sync.Pool{ New: func() interface{} { return &bytes.Buffer{} }, }, } }) return defaultEncoderInstance } // Encode is a part of an implementation of the AttributeEncoder interface. func (d *defaultAttrEncoder) Encode(iter Iterator) string { buf := d.pool.Get().(*bytes.Buffer) defer d.pool.Put(buf) buf.Reset() for iter.Next() { i, keyValue := iter.IndexedAttribute() if i > 0 { _, _ = buf.WriteRune(',') } copyAndEscape(buf, string(keyValue.Key)) _, _ = buf.WriteRune('=') if keyValue.Value.Type() == STRING { copyAndEscape(buf, keyValue.Value.AsString()) } else { _, _ = buf.WriteString(keyValue.Value.Emit()) } } return buf.String() } // ID is a part of an implementation of the AttributeEncoder interface. func (*defaultAttrEncoder) ID() EncoderID { return defaultEncoderID } // copyAndEscape escapes `=`, `,` and its own escape character (`\`), // making the default encoding unique. func copyAndEscape(buf *bytes.Buffer, val string) { for _, ch := range val { switch ch { case '=', ',', escapeChar: _, _ = buf.WriteRune(escapeChar) } _, _ = buf.WriteRune(ch) } } // Valid returns true if this encoder ID was allocated by // `NewEncoderID`. Invalid encoder IDs will not be cached. func (id EncoderID) Valid() bool { return id.value != 0 }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/attribute_group.go
vendor/go.opentelemetry.io/otel/semconv/v1.20.0/attribute_group.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 // Code generated from semantic convention specification. DO NOT EDIT. package semconv // import "go.opentelemetry.io/otel/semconv/v1.20.0" import "go.opentelemetry.io/otel/attribute" // Describes HTTP attributes. const ( // HTTPMethodKey is the attribute Key conforming to the "http.method" // semantic conventions. It represents the hTTP request method. // // Type: string // RequirementLevel: Required // Stability: stable // Examples: 'GET', 'POST', 'HEAD' HTTPMethodKey = attribute.Key("http.method") // HTTPStatusCodeKey is the attribute Key conforming to the // "http.status_code" semantic conventions. It represents the [HTTP // response status code](https://tools.ietf.org/html/rfc7231#section-6). // // Type: int // RequirementLevel: ConditionallyRequired (If and only if one was // received/sent.) // Stability: stable // Examples: 200 HTTPStatusCodeKey = attribute.Key("http.status_code") ) // HTTPMethod returns an attribute KeyValue conforming to the "http.method" // semantic conventions. It represents the hTTP request method. func HTTPMethod(val string) attribute.KeyValue { return HTTPMethodKey.String(val) } // HTTPStatusCode returns an attribute KeyValue conforming to the // "http.status_code" semantic conventions. It represents the [HTTP response // status code](https://tools.ietf.org/html/rfc7231#section-6). func HTTPStatusCode(val int) attribute.KeyValue { return HTTPStatusCodeKey.Int(val) } // HTTP Server spans attributes const ( // HTTPSchemeKey is the attribute Key conforming to the "http.scheme" // semantic conventions. It represents the URI scheme identifying the used // protocol. // // Type: string // RequirementLevel: Required // Stability: stable // Examples: 'http', 'https' HTTPSchemeKey = attribute.Key("http.scheme") // HTTPRouteKey is the attribute Key conforming to the "http.route" // semantic conventions. It represents the matched route (path template in // the format used by the respective server framework). See note below // // Type: string // RequirementLevel: ConditionallyRequired (If and only if it's available) // Stability: stable // Examples: '/users/:userID?', '{controller}/{action}/{id?}' // Note: MUST NOT be populated when this is not supported by the HTTP // server framework as the route attribute should have low-cardinality and // the URI path can NOT substitute it. // SHOULD include the [application // root](/specification/trace/semantic_conventions/http.md#http-server-definitions) // if there is one. HTTPRouteKey = attribute.Key("http.route") ) // HTTPScheme returns an attribute KeyValue conforming to the "http.scheme" // semantic conventions. It represents the URI scheme identifying the used // protocol. func HTTPScheme(val string) attribute.KeyValue { return HTTPSchemeKey.String(val) } // HTTPRoute returns an attribute KeyValue conforming to the "http.route" // semantic conventions. It represents the matched route (path template in the // format used by the respective server framework). See note below func HTTPRoute(val string) attribute.KeyValue { return HTTPRouteKey.String(val) } // Attributes for Events represented using Log Records. const ( // EventNameKey is the attribute Key conforming to the "event.name" // semantic conventions. It represents the name identifies the event. // // Type: string // RequirementLevel: Required // Stability: stable // Examples: 'click', 'exception' EventNameKey = attribute.Key("event.name") // EventDomainKey is the attribute Key conforming to the "event.domain" // semantic conventions. It represents the domain identifies the business // context for the events. // // Type: Enum // RequirementLevel: Required // Stability: stable // Note: Events across different domains may have same `event.name`, yet be // unrelated events. EventDomainKey = attribute.Key("event.domain") ) var ( // Events from browser apps EventDomainBrowser = EventDomainKey.String("browser") // Events from mobile apps EventDomainDevice = EventDomainKey.String("device") // Events from Kubernetes EventDomainK8S = EventDomainKey.String("k8s") ) // EventName returns an attribute KeyValue conforming to the "event.name" // semantic conventions. It represents the name identifies the event. func EventName(val string) attribute.KeyValue { return EventNameKey.String(val) } // These attributes may be used for any network related operation. const ( // NetTransportKey is the attribute Key conforming to the "net.transport" // semantic conventions. It represents the transport protocol used. See // note below. // // Type: Enum // RequirementLevel: Optional // Stability: stable NetTransportKey = attribute.Key("net.transport") // NetProtocolNameKey is the attribute Key conforming to the // "net.protocol.name" semantic conventions. It represents the application // layer protocol used. The value SHOULD be normalized to lowercase. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'amqp', 'http', 'mqtt' NetProtocolNameKey = attribute.Key("net.protocol.name") // NetProtocolVersionKey is the attribute Key conforming to the // "net.protocol.version" semantic conventions. It represents the version // of the application layer protocol used. See note below. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: '3.1.1' // Note: `net.protocol.version` refers to the version of the protocol used // and might be different from the protocol client's version. If the HTTP // client used has a version of `0.27.2`, but sends HTTP version `1.1`, // this attribute should be set to `1.1`. NetProtocolVersionKey = attribute.Key("net.protocol.version") // NetSockPeerNameKey is the attribute Key conforming to the // "net.sock.peer.name" semantic conventions. It represents the remote // socket peer name. // // Type: string // RequirementLevel: Recommended (If available and different from // `net.peer.name` and if `net.sock.peer.addr` is set.) // Stability: stable // Examples: 'proxy.example.com' NetSockPeerNameKey = attribute.Key("net.sock.peer.name") // NetSockPeerAddrKey is the attribute Key conforming to the // "net.sock.peer.addr" semantic conventions. It represents the remote // socket peer address: IPv4 or IPv6 for internet protocols, path for local // communication, // [etc](https://man7.org/linux/man-pages/man7/address_families.7.html). // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: '127.0.0.1', '/tmp/mysql.sock' NetSockPeerAddrKey = attribute.Key("net.sock.peer.addr") // NetSockPeerPortKey is the attribute Key conforming to the // "net.sock.peer.port" semantic conventions. It represents the remote // socket peer port. // // Type: int // RequirementLevel: Recommended (If defined for the address family and if // different than `net.peer.port` and if `net.sock.peer.addr` is set.) // Stability: stable // Examples: 16456 NetSockPeerPortKey = attribute.Key("net.sock.peer.port") // NetSockFamilyKey is the attribute Key conforming to the // "net.sock.family" semantic conventions. It represents the protocol // [address // family](https://man7.org/linux/man-pages/man7/address_families.7.html) // which is used for communication. // // Type: Enum // RequirementLevel: ConditionallyRequired (If different than `inet` and if // any of `net.sock.peer.addr` or `net.sock.host.addr` are set. Consumers // of telemetry SHOULD accept both IPv4 and IPv6 formats for the address in // `net.sock.peer.addr` if `net.sock.family` is not set. This is to support // instrumentations that follow previous versions of this document.) // Stability: stable // Examples: 'inet6', 'bluetooth' NetSockFamilyKey = attribute.Key("net.sock.family") // NetPeerNameKey is the attribute Key conforming to the "net.peer.name" // semantic conventions. It represents the logical remote hostname, see // note below. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'example.com' // Note: `net.peer.name` SHOULD NOT be set if capturing it would require an // extra DNS lookup. NetPeerNameKey = attribute.Key("net.peer.name") // NetPeerPortKey is the attribute Key conforming to the "net.peer.port" // semantic conventions. It represents the logical remote port number // // Type: int // RequirementLevel: Optional // Stability: stable // Examples: 80, 8080, 443 NetPeerPortKey = attribute.Key("net.peer.port") // NetHostNameKey is the attribute Key conforming to the "net.host.name" // semantic conventions. It represents the logical local hostname or // similar, see note below. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'localhost' NetHostNameKey = attribute.Key("net.host.name") // NetHostPortKey is the attribute Key conforming to the "net.host.port" // semantic conventions. It represents the logical local port number, // preferably the one that the peer used to connect // // Type: int // RequirementLevel: Optional // Stability: stable // Examples: 8080 NetHostPortKey = attribute.Key("net.host.port") // NetSockHostAddrKey is the attribute Key conforming to the // "net.sock.host.addr" semantic conventions. It represents the local // socket address. Useful in case of a multi-IP host. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: '192.168.0.1' NetSockHostAddrKey = attribute.Key("net.sock.host.addr") // NetSockHostPortKey is the attribute Key conforming to the // "net.sock.host.port" semantic conventions. It represents the local // socket port number. // // Type: int // RequirementLevel: ConditionallyRequired (If defined for the address // family and if different than `net.host.port` and if `net.sock.host.addr` // is set. In other cases, it is still recommended to set this.) // Stability: stable // Examples: 35555 NetSockHostPortKey = attribute.Key("net.sock.host.port") ) var ( // ip_tcp NetTransportTCP = NetTransportKey.String("ip_tcp") // ip_udp NetTransportUDP = NetTransportKey.String("ip_udp") // Named or anonymous pipe. See note below NetTransportPipe = NetTransportKey.String("pipe") // In-process communication NetTransportInProc = NetTransportKey.String("inproc") // Something else (non IP-based) NetTransportOther = NetTransportKey.String("other") ) var ( // IPv4 address NetSockFamilyInet = NetSockFamilyKey.String("inet") // IPv6 address NetSockFamilyInet6 = NetSockFamilyKey.String("inet6") // Unix domain socket path NetSockFamilyUnix = NetSockFamilyKey.String("unix") ) // NetProtocolName returns an attribute KeyValue conforming to the // "net.protocol.name" semantic conventions. It represents the application // layer protocol used. The value SHOULD be normalized to lowercase. func NetProtocolName(val string) attribute.KeyValue { return NetProtocolNameKey.String(val) } // NetProtocolVersion returns an attribute KeyValue conforming to the // "net.protocol.version" semantic conventions. It represents the version of // the application layer protocol used. See note below. func NetProtocolVersion(val string) attribute.KeyValue { return NetProtocolVersionKey.String(val) } // NetSockPeerName returns an attribute KeyValue conforming to the // "net.sock.peer.name" semantic conventions. It represents the remote socket // peer name. func NetSockPeerName(val string) attribute.KeyValue { return NetSockPeerNameKey.String(val) } // NetSockPeerAddr returns an attribute KeyValue conforming to the // "net.sock.peer.addr" semantic conventions. It represents the remote socket // peer address: IPv4 or IPv6 for internet protocols, path for local // communication, // [etc](https://man7.org/linux/man-pages/man7/address_families.7.html). func NetSockPeerAddr(val string) attribute.KeyValue { return NetSockPeerAddrKey.String(val) } // NetSockPeerPort returns an attribute KeyValue conforming to the // "net.sock.peer.port" semantic conventions. It represents the remote socket // peer port. func NetSockPeerPort(val int) attribute.KeyValue { return NetSockPeerPortKey.Int(val) } // NetPeerName returns an attribute KeyValue conforming to the // "net.peer.name" semantic conventions. It represents the logical remote // hostname, see note below. func NetPeerName(val string) attribute.KeyValue { return NetPeerNameKey.String(val) } // NetPeerPort returns an attribute KeyValue conforming to the // "net.peer.port" semantic conventions. It represents the logical remote port // number func NetPeerPort(val int) attribute.KeyValue { return NetPeerPortKey.Int(val) } // NetHostName returns an attribute KeyValue conforming to the // "net.host.name" semantic conventions. It represents the logical local // hostname or similar, see note below. func NetHostName(val string) attribute.KeyValue { return NetHostNameKey.String(val) } // NetHostPort returns an attribute KeyValue conforming to the // "net.host.port" semantic conventions. It represents the logical local port // number, preferably the one that the peer used to connect func NetHostPort(val int) attribute.KeyValue { return NetHostPortKey.Int(val) } // NetSockHostAddr returns an attribute KeyValue conforming to the // "net.sock.host.addr" semantic conventions. It represents the local socket // address. Useful in case of a multi-IP host. func NetSockHostAddr(val string) attribute.KeyValue { return NetSockHostAddrKey.String(val) } // NetSockHostPort returns an attribute KeyValue conforming to the // "net.sock.host.port" semantic conventions. It represents the local socket // port number. func NetSockHostPort(val int) attribute.KeyValue { return NetSockHostPortKey.Int(val) } // These attributes may be used for any network related operation. const ( // NetHostConnectionTypeKey is the attribute Key conforming to the // "net.host.connection.type" semantic conventions. It represents the // internet connection type currently being used by the host. // // Type: Enum // RequirementLevel: Optional // Stability: stable // Examples: 'wifi' NetHostConnectionTypeKey = attribute.Key("net.host.connection.type") // NetHostConnectionSubtypeKey is the attribute Key conforming to the // "net.host.connection.subtype" semantic conventions. It represents the // this describes more details regarding the connection.type. It may be the // type of cell technology connection, but it could be used for describing // details about a wifi connection. // // Type: Enum // RequirementLevel: Optional // Stability: stable // Examples: 'LTE' NetHostConnectionSubtypeKey = attribute.Key("net.host.connection.subtype") // NetHostCarrierNameKey is the attribute Key conforming to the // "net.host.carrier.name" semantic conventions. It represents the name of // the mobile carrier. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'sprint' NetHostCarrierNameKey = attribute.Key("net.host.carrier.name") // NetHostCarrierMccKey is the attribute Key conforming to the // "net.host.carrier.mcc" semantic conventions. It represents the mobile // carrier country code. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: '310' NetHostCarrierMccKey = attribute.Key("net.host.carrier.mcc") // NetHostCarrierMncKey is the attribute Key conforming to the // "net.host.carrier.mnc" semantic conventions. It represents the mobile // carrier network code. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: '001' NetHostCarrierMncKey = attribute.Key("net.host.carrier.mnc") // NetHostCarrierIccKey is the attribute Key conforming to the // "net.host.carrier.icc" semantic conventions. It represents the ISO // 3166-1 alpha-2 2-character country code associated with the mobile // carrier network. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'DE' NetHostCarrierIccKey = attribute.Key("net.host.carrier.icc") ) var ( // wifi NetHostConnectionTypeWifi = NetHostConnectionTypeKey.String("wifi") // wired NetHostConnectionTypeWired = NetHostConnectionTypeKey.String("wired") // cell NetHostConnectionTypeCell = NetHostConnectionTypeKey.String("cell") // unavailable NetHostConnectionTypeUnavailable = NetHostConnectionTypeKey.String("unavailable") // unknown NetHostConnectionTypeUnknown = NetHostConnectionTypeKey.String("unknown") ) var ( // GPRS NetHostConnectionSubtypeGprs = NetHostConnectionSubtypeKey.String("gprs") // EDGE NetHostConnectionSubtypeEdge = NetHostConnectionSubtypeKey.String("edge") // UMTS NetHostConnectionSubtypeUmts = NetHostConnectionSubtypeKey.String("umts") // CDMA NetHostConnectionSubtypeCdma = NetHostConnectionSubtypeKey.String("cdma") // EVDO Rel. 0 NetHostConnectionSubtypeEvdo0 = NetHostConnectionSubtypeKey.String("evdo_0") // EVDO Rev. A NetHostConnectionSubtypeEvdoA = NetHostConnectionSubtypeKey.String("evdo_a") // CDMA2000 1XRTT NetHostConnectionSubtypeCdma20001xrtt = NetHostConnectionSubtypeKey.String("cdma2000_1xrtt") // HSDPA NetHostConnectionSubtypeHsdpa = NetHostConnectionSubtypeKey.String("hsdpa") // HSUPA NetHostConnectionSubtypeHsupa = NetHostConnectionSubtypeKey.String("hsupa") // HSPA NetHostConnectionSubtypeHspa = NetHostConnectionSubtypeKey.String("hspa") // IDEN NetHostConnectionSubtypeIden = NetHostConnectionSubtypeKey.String("iden") // EVDO Rev. B NetHostConnectionSubtypeEvdoB = NetHostConnectionSubtypeKey.String("evdo_b") // LTE NetHostConnectionSubtypeLte = NetHostConnectionSubtypeKey.String("lte") // EHRPD NetHostConnectionSubtypeEhrpd = NetHostConnectionSubtypeKey.String("ehrpd") // HSPAP NetHostConnectionSubtypeHspap = NetHostConnectionSubtypeKey.String("hspap") // GSM NetHostConnectionSubtypeGsm = NetHostConnectionSubtypeKey.String("gsm") // TD-SCDMA NetHostConnectionSubtypeTdScdma = NetHostConnectionSubtypeKey.String("td_scdma") // IWLAN NetHostConnectionSubtypeIwlan = NetHostConnectionSubtypeKey.String("iwlan") // 5G NR (New Radio) NetHostConnectionSubtypeNr = NetHostConnectionSubtypeKey.String("nr") // 5G NRNSA (New Radio Non-Standalone) NetHostConnectionSubtypeNrnsa = NetHostConnectionSubtypeKey.String("nrnsa") // LTE CA NetHostConnectionSubtypeLteCa = NetHostConnectionSubtypeKey.String("lte_ca") ) // NetHostCarrierName returns an attribute KeyValue conforming to the // "net.host.carrier.name" semantic conventions. It represents the name of the // mobile carrier. func NetHostCarrierName(val string) attribute.KeyValue { return NetHostCarrierNameKey.String(val) } // NetHostCarrierMcc returns an attribute KeyValue conforming to the // "net.host.carrier.mcc" semantic conventions. It represents the mobile // carrier country code. func NetHostCarrierMcc(val string) attribute.KeyValue { return NetHostCarrierMccKey.String(val) } // NetHostCarrierMnc returns an attribute KeyValue conforming to the // "net.host.carrier.mnc" semantic conventions. It represents the mobile // carrier network code. func NetHostCarrierMnc(val string) attribute.KeyValue { return NetHostCarrierMncKey.String(val) } // NetHostCarrierIcc returns an attribute KeyValue conforming to the // "net.host.carrier.icc" semantic conventions. It represents the ISO 3166-1 // alpha-2 2-character country code associated with the mobile carrier network. func NetHostCarrierIcc(val string) attribute.KeyValue { return NetHostCarrierIccKey.String(val) } // Semantic conventions for HTTP client and server Spans. const ( // HTTPRequestContentLengthKey is the attribute Key conforming to the // "http.request_content_length" semantic conventions. It represents the // size of the request payload body in bytes. This is the number of bytes // transferred excluding headers and is often, but not always, present as // the // [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) // header. For requests using transport encoding, this should be the // compressed size. // // Type: int // RequirementLevel: Optional // Stability: stable // Examples: 3495 HTTPRequestContentLengthKey = attribute.Key("http.request_content_length") // HTTPResponseContentLengthKey is the attribute Key conforming to the // "http.response_content_length" semantic conventions. It represents the // size of the response payload body in bytes. This is the number of bytes // transferred excluding headers and is often, but not always, present as // the // [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) // header. For requests using transport encoding, this should be the // compressed size. // // Type: int // RequirementLevel: Optional // Stability: stable // Examples: 3495 HTTPResponseContentLengthKey = attribute.Key("http.response_content_length") ) // HTTPRequestContentLength returns an attribute KeyValue conforming to the // "http.request_content_length" semantic conventions. It represents the size // of the request payload body in bytes. This is the number of bytes // transferred excluding headers and is often, but not always, present as the // [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) // header. For requests using transport encoding, this should be the compressed // size. func HTTPRequestContentLength(val int) attribute.KeyValue { return HTTPRequestContentLengthKey.Int(val) } // HTTPResponseContentLength returns an attribute KeyValue conforming to the // "http.response_content_length" semantic conventions. It represents the size // of the response payload body in bytes. This is the number of bytes // transferred excluding headers and is often, but not always, present as the // [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#field.content-length) // header. For requests using transport encoding, this should be the compressed // size. func HTTPResponseContentLength(val int) attribute.KeyValue { return HTTPResponseContentLengthKey.Int(val) } // Semantic convention describing per-message attributes populated on messaging // spans or links. const ( // MessagingMessageIDKey is the attribute Key conforming to the // "messaging.message.id" semantic conventions. It represents a value used // by the messaging system as an identifier for the message, represented as // a string. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: '452a7c7c7c7048c2f887f61572b18fc2' MessagingMessageIDKey = attribute.Key("messaging.message.id") // MessagingMessageConversationIDKey is the attribute Key conforming to the // "messaging.message.conversation_id" semantic conventions. It represents // the [conversation ID](#conversations) identifying the conversation to // which the message belongs, represented as a string. Sometimes called // "Correlation ID". // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'MyConversationID' MessagingMessageConversationIDKey = attribute.Key("messaging.message.conversation_id") // MessagingMessagePayloadSizeBytesKey is the attribute Key conforming to // the "messaging.message.payload_size_bytes" semantic conventions. It // represents the (uncompressed) size of the message payload in bytes. Also // use this attribute if it is unknown whether the compressed or // uncompressed payload size is reported. // // Type: int // RequirementLevel: Optional // Stability: stable // Examples: 2738 MessagingMessagePayloadSizeBytesKey = attribute.Key("messaging.message.payload_size_bytes") // MessagingMessagePayloadCompressedSizeBytesKey is the attribute Key // conforming to the "messaging.message.payload_compressed_size_bytes" // semantic conventions. It represents the compressed size of the message // payload in bytes. // // Type: int // RequirementLevel: Optional // Stability: stable // Examples: 2048 MessagingMessagePayloadCompressedSizeBytesKey = attribute.Key("messaging.message.payload_compressed_size_bytes") ) // MessagingMessageID returns an attribute KeyValue conforming to the // "messaging.message.id" semantic conventions. It represents a value used by // the messaging system as an identifier for the message, represented as a // string. func MessagingMessageID(val string) attribute.KeyValue { return MessagingMessageIDKey.String(val) } // MessagingMessageConversationID returns an attribute KeyValue conforming // to the "messaging.message.conversation_id" semantic conventions. It // represents the [conversation ID](#conversations) identifying the // conversation to which the message belongs, represented as a string. // Sometimes called "Correlation ID". func MessagingMessageConversationID(val string) attribute.KeyValue { return MessagingMessageConversationIDKey.String(val) } // MessagingMessagePayloadSizeBytes returns an attribute KeyValue conforming // to the "messaging.message.payload_size_bytes" semantic conventions. It // represents the (uncompressed) size of the message payload in bytes. Also use // this attribute if it is unknown whether the compressed or uncompressed // payload size is reported. func MessagingMessagePayloadSizeBytes(val int) attribute.KeyValue { return MessagingMessagePayloadSizeBytesKey.Int(val) } // MessagingMessagePayloadCompressedSizeBytes returns an attribute KeyValue // conforming to the "messaging.message.payload_compressed_size_bytes" semantic // conventions. It represents the compressed size of the message payload in // bytes. func MessagingMessagePayloadCompressedSizeBytes(val int) attribute.KeyValue { return MessagingMessagePayloadCompressedSizeBytesKey.Int(val) } // Semantic convention for attributes that describe messaging destination on // broker const ( // MessagingDestinationNameKey is the attribute Key conforming to the // "messaging.destination.name" semantic conventions. It represents the // message destination name // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'MyQueue', 'MyTopic' // Note: Destination name SHOULD uniquely identify a specific queue, topic // or other entity within the broker. If // the broker does not have such notion, the destination name SHOULD // uniquely identify the broker. MessagingDestinationNameKey = attribute.Key("messaging.destination.name") // MessagingDestinationTemplateKey is the attribute Key conforming to the // "messaging.destination.template" semantic conventions. It represents the // low cardinality representation of the messaging destination name // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: '/customers/{customerID}' // Note: Destination names could be constructed from templates. An example // would be a destination name involving a user name or product id. // Although the destination name in this case is of high cardinality, the // underlying template is of low cardinality and can be effectively used // for grouping and aggregation. MessagingDestinationTemplateKey = attribute.Key("messaging.destination.template") // MessagingDestinationTemporaryKey is the attribute Key conforming to the // "messaging.destination.temporary" semantic conventions. It represents a // boolean that is true if the message destination is temporary and might // not exist anymore after messages are processed. // // Type: boolean // RequirementLevel: Optional // Stability: stable MessagingDestinationTemporaryKey = attribute.Key("messaging.destination.temporary") // MessagingDestinationAnonymousKey is the attribute Key conforming to the // "messaging.destination.anonymous" semantic conventions. It represents a // boolean that is true if the message destination is anonymous (could be // unnamed or have auto-generated name). // // Type: boolean // RequirementLevel: Optional // Stability: stable MessagingDestinationAnonymousKey = attribute.Key("messaging.destination.anonymous") ) // MessagingDestinationName returns an attribute KeyValue conforming to the // "messaging.destination.name" semantic conventions. It represents the message // destination name func MessagingDestinationName(val string) attribute.KeyValue { return MessagingDestinationNameKey.String(val) } // MessagingDestinationTemplate returns an attribute KeyValue conforming to // the "messaging.destination.template" semantic conventions. It represents the // low cardinality representation of the messaging destination name func MessagingDestinationTemplate(val string) attribute.KeyValue { return MessagingDestinationTemplateKey.String(val) } // MessagingDestinationTemporary returns an attribute KeyValue conforming to // the "messaging.destination.temporary" semantic conventions. It represents a // boolean that is true if the message destination is temporary and might not // exist anymore after messages are processed. func MessagingDestinationTemporary(val bool) attribute.KeyValue { return MessagingDestinationTemporaryKey.Bool(val) } // MessagingDestinationAnonymous returns an attribute KeyValue conforming to // the "messaging.destination.anonymous" semantic conventions. It represents a // boolean that is true if the message destination is anonymous (could be // unnamed or have auto-generated name). func MessagingDestinationAnonymous(val bool) attribute.KeyValue { return MessagingDestinationAnonymousKey.Bool(val) } // Semantic convention for attributes that describe messaging source on broker const ( // MessagingSourceNameKey is the attribute Key conforming to the // "messaging.source.name" semantic conventions. It represents the message // source name // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'MyQueue', 'MyTopic' // Note: Source name SHOULD uniquely identify a specific queue, topic, or // other entity within the broker. If // the broker does not have such notion, the source name SHOULD uniquely // identify the broker. MessagingSourceNameKey = attribute.Key("messaging.source.name") // MessagingSourceTemplateKey is the attribute Key conforming to the // "messaging.source.template" semantic conventions. It represents the low // cardinality representation of the messaging source name // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: '/customers/{customerID}' // Note: Source names could be constructed from templates. An example would // be a source name involving a user name or product id. Although the // source name in this case is of high cardinality, the underlying template // is of low cardinality and can be effectively used for grouping and // aggregation. MessagingSourceTemplateKey = attribute.Key("messaging.source.template") // MessagingSourceTemporaryKey is the attribute Key conforming to the // "messaging.source.temporary" semantic conventions. It represents a // boolean that is true if the message source is temporary and might not // exist anymore after messages are processed. // // Type: boolean // RequirementLevel: Optional // Stability: stable MessagingSourceTemporaryKey = attribute.Key("messaging.source.temporary") // MessagingSourceAnonymousKey is the attribute Key conforming to the // "messaging.source.anonymous" semantic conventions. It represents a // boolean that is true if the message source is anonymous (could be // unnamed or have auto-generated name). // // Type: boolean // RequirementLevel: Optional // Stability: stable MessagingSourceAnonymousKey = attribute.Key("messaging.source.anonymous") ) // MessagingSourceName returns an attribute KeyValue conforming to the // "messaging.source.name" semantic conventions. It represents the message // source name func MessagingSourceName(val string) attribute.KeyValue { return MessagingSourceNameKey.String(val) } // MessagingSourceTemplate returns an attribute KeyValue conforming to the // "messaging.source.template" semantic conventions. It represents the low // cardinality representation of the messaging source name func MessagingSourceTemplate(val string) attribute.KeyValue { return MessagingSourceTemplateKey.String(val) } // MessagingSourceTemporary returns an attribute KeyValue conforming to the // "messaging.source.temporary" semantic conventions. It represents a boolean // that is true if the message source is temporary and might not exist anymore // after messages are processed. func MessagingSourceTemporary(val bool) attribute.KeyValue { return MessagingSourceTemporaryKey.Bool(val) } // MessagingSourceAnonymous returns an attribute KeyValue conforming to the // "messaging.source.anonymous" semantic conventions. It represents a boolean
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
true
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/trace.go
vendor/go.opentelemetry.io/otel/semconv/v1.20.0/trace.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 // Code generated from semantic convention specification. DO NOT EDIT. package semconv // import "go.opentelemetry.io/otel/semconv/v1.20.0" import "go.opentelemetry.io/otel/attribute" // The shared attributes used to report a single exception associated with a // span or log. const ( // ExceptionTypeKey is the attribute Key conforming to the "exception.type" // semantic conventions. It represents the type of the exception (its // fully-qualified class name, if applicable). The dynamic type of the // exception should be preferred over the static type in languages that // support it. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'java.net.ConnectException', 'OSError' ExceptionTypeKey = attribute.Key("exception.type") // ExceptionMessageKey is the attribute Key conforming to the // "exception.message" semantic conventions. It represents the exception // message. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'Division by zero', "Can't convert 'int' object to str // implicitly" ExceptionMessageKey = attribute.Key("exception.message") // ExceptionStacktraceKey is the attribute Key conforming to the // "exception.stacktrace" semantic conventions. It represents a stacktrace // as a string in the natural representation for the language runtime. The // representation is to be determined and documented by each language SIG. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'Exception in thread "main" java.lang.RuntimeException: Test // exception\\n at ' // 'com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\n at ' // 'com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\n at ' // 'com.example.GenerateTrace.main(GenerateTrace.java:5)' ExceptionStacktraceKey = attribute.Key("exception.stacktrace") ) // ExceptionType returns an attribute KeyValue conforming to the // "exception.type" semantic conventions. It represents the type of the // exception (its fully-qualified class name, if applicable). The dynamic type // of the exception should be preferred over the static type in languages that // support it. func ExceptionType(val string) attribute.KeyValue { return ExceptionTypeKey.String(val) } // ExceptionMessage returns an attribute KeyValue conforming to the // "exception.message" semantic conventions. It represents the exception // message. func ExceptionMessage(val string) attribute.KeyValue { return ExceptionMessageKey.String(val) } // ExceptionStacktrace returns an attribute KeyValue conforming to the // "exception.stacktrace" semantic conventions. It represents a stacktrace as a // string in the natural representation for the language runtime. The // representation is to be determined and documented by each language SIG. func ExceptionStacktrace(val string) attribute.KeyValue { return ExceptionStacktraceKey.String(val) } // The attributes described in this section are rather generic. They may be // used in any Log Record they apply to. const ( // LogRecordUIDKey is the attribute Key conforming to the "log.record.uid" // semantic conventions. It represents a unique identifier for the Log // Record. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: '01ARZ3NDEKTSV4RRFFQ69G5FAV' // Note: If an id is provided, other log records with the same id will be // considered duplicates and can be removed safely. This means, that two // distinguishable log records MUST have different values. // The id MAY be an [Universally Unique Lexicographically Sortable // Identifier (ULID)](https://github.com/ulid/spec), but other identifiers // (e.g. UUID) may be used as needed. LogRecordUIDKey = attribute.Key("log.record.uid") ) // LogRecordUID returns an attribute KeyValue conforming to the // "log.record.uid" semantic conventions. It represents a unique identifier for // the Log Record. func LogRecordUID(val string) attribute.KeyValue { return LogRecordUIDKey.String(val) } // Span attributes used by AWS Lambda (in addition to general `faas` // attributes). const ( // AWSLambdaInvokedARNKey is the attribute Key conforming to the // "aws.lambda.invoked_arn" semantic conventions. It represents the full // invoked ARN as provided on the `Context` passed to the function // (`Lambda-Runtime-Invoked-Function-ARN` header on the // `/runtime/invocation/next` applicable). // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'arn:aws:lambda:us-east-1:123456:function:myfunction:myalias' // Note: This may be different from `cloud.resource_id` if an alias is // involved. AWSLambdaInvokedARNKey = attribute.Key("aws.lambda.invoked_arn") ) // AWSLambdaInvokedARN returns an attribute KeyValue conforming to the // "aws.lambda.invoked_arn" semantic conventions. It represents the full // invoked ARN as provided on the `Context` passed to the function // (`Lambda-Runtime-Invoked-Function-ARN` header on the // `/runtime/invocation/next` applicable). func AWSLambdaInvokedARN(val string) attribute.KeyValue { return AWSLambdaInvokedARNKey.String(val) } // Attributes for CloudEvents. CloudEvents is a specification on how to define // event data in a standard way. These attributes can be attached to spans when // performing operations with CloudEvents, regardless of the protocol being // used. const ( // CloudeventsEventIDKey is the attribute Key conforming to the // "cloudevents.event_id" semantic conventions. It represents the // [event_id](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#id) // uniquely identifies the event. // // Type: string // RequirementLevel: Required // Stability: stable // Examples: '123e4567-e89b-12d3-a456-426614174000', '0001' CloudeventsEventIDKey = attribute.Key("cloudevents.event_id") // CloudeventsEventSourceKey is the attribute Key conforming to the // "cloudevents.event_source" semantic conventions. It represents the // [source](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#source-1) // identifies the context in which an event happened. // // Type: string // RequirementLevel: Required // Stability: stable // Examples: 'https://github.com/cloudevents', // '/cloudevents/spec/pull/123', 'my-service' CloudeventsEventSourceKey = attribute.Key("cloudevents.event_source") // CloudeventsEventSpecVersionKey is the attribute Key conforming to the // "cloudevents.event_spec_version" semantic conventions. It represents the // [version of the CloudEvents // specification](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#specversion) // which the event uses. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: '1.0' CloudeventsEventSpecVersionKey = attribute.Key("cloudevents.event_spec_version") // CloudeventsEventTypeKey is the attribute Key conforming to the // "cloudevents.event_type" semantic conventions. It represents the // [event_type](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#type) // contains a value describing the type of event related to the originating // occurrence. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'com.github.pull_request.opened', // 'com.example.object.deleted.v2' CloudeventsEventTypeKey = attribute.Key("cloudevents.event_type") // CloudeventsEventSubjectKey is the attribute Key conforming to the // "cloudevents.event_subject" semantic conventions. It represents the // [subject](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#subject) // of the event in the context of the event producer (identified by // source). // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'mynewfile.jpg' CloudeventsEventSubjectKey = attribute.Key("cloudevents.event_subject") ) // CloudeventsEventID returns an attribute KeyValue conforming to the // "cloudevents.event_id" semantic conventions. It represents the // [event_id](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#id) // uniquely identifies the event. func CloudeventsEventID(val string) attribute.KeyValue { return CloudeventsEventIDKey.String(val) } // CloudeventsEventSource returns an attribute KeyValue conforming to the // "cloudevents.event_source" semantic conventions. It represents the // [source](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#source-1) // identifies the context in which an event happened. func CloudeventsEventSource(val string) attribute.KeyValue { return CloudeventsEventSourceKey.String(val) } // CloudeventsEventSpecVersion returns an attribute KeyValue conforming to // the "cloudevents.event_spec_version" semantic conventions. It represents the // [version of the CloudEvents // specification](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#specversion) // which the event uses. func CloudeventsEventSpecVersion(val string) attribute.KeyValue { return CloudeventsEventSpecVersionKey.String(val) } // CloudeventsEventType returns an attribute KeyValue conforming to the // "cloudevents.event_type" semantic conventions. It represents the // [event_type](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#type) // contains a value describing the type of event related to the originating // occurrence. func CloudeventsEventType(val string) attribute.KeyValue { return CloudeventsEventTypeKey.String(val) } // CloudeventsEventSubject returns an attribute KeyValue conforming to the // "cloudevents.event_subject" semantic conventions. It represents the // [subject](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#subject) // of the event in the context of the event producer (identified by source). func CloudeventsEventSubject(val string) attribute.KeyValue { return CloudeventsEventSubjectKey.String(val) } // Semantic conventions for the OpenTracing Shim const ( // OpentracingRefTypeKey is the attribute Key conforming to the // "opentracing.ref_type" semantic conventions. It represents the // parent-child Reference type // // Type: Enum // RequirementLevel: Optional // Stability: stable // Note: The causal relationship between a child Span and a parent Span. OpentracingRefTypeKey = attribute.Key("opentracing.ref_type") ) var ( // The parent Span depends on the child Span in some capacity OpentracingRefTypeChildOf = OpentracingRefTypeKey.String("child_of") // The parent Span does not depend in any way on the result of the child Span OpentracingRefTypeFollowsFrom = OpentracingRefTypeKey.String("follows_from") ) // The attributes used to perform database client calls. const ( // DBSystemKey is the attribute Key conforming to the "db.system" semantic // conventions. It represents an identifier for the database management // system (DBMS) product being used. See below for a list of well-known // identifiers. // // Type: Enum // RequirementLevel: Required // Stability: stable DBSystemKey = attribute.Key("db.system") // DBConnectionStringKey is the attribute Key conforming to the // "db.connection_string" semantic conventions. It represents the // connection string used to connect to the database. It is recommended to // remove embedded credentials. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'Server=(localdb)\\v11.0;Integrated Security=true;' DBConnectionStringKey = attribute.Key("db.connection_string") // DBUserKey is the attribute Key conforming to the "db.user" semantic // conventions. It represents the username for accessing the database. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'readonly_user', 'reporting_user' DBUserKey = attribute.Key("db.user") // DBJDBCDriverClassnameKey is the attribute Key conforming to the // "db.jdbc.driver_classname" semantic conventions. It represents the // fully-qualified class name of the [Java Database Connectivity // (JDBC)](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) // driver used to connect. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'org.postgresql.Driver', // 'com.microsoft.sqlserver.jdbc.SQLServerDriver' DBJDBCDriverClassnameKey = attribute.Key("db.jdbc.driver_classname") // DBNameKey is the attribute Key conforming to the "db.name" semantic // conventions. It represents the this attribute is used to report the name // of the database being accessed. For commands that switch the database, // this should be set to the target database (even if the command fails). // // Type: string // RequirementLevel: ConditionallyRequired (If applicable.) // Stability: stable // Examples: 'customers', 'main' // Note: In some SQL databases, the database name to be used is called // "schema name". In case there are multiple layers that could be // considered for database name (e.g. Oracle instance name and schema // name), the database name to be used is the more specific layer (e.g. // Oracle schema name). DBNameKey = attribute.Key("db.name") // DBStatementKey is the attribute Key conforming to the "db.statement" // semantic conventions. It represents the database statement being // executed. // // Type: string // RequirementLevel: Recommended (Should be collected by default only if // there is sanitization that excludes sensitive information.) // Stability: stable // Examples: 'SELECT * FROM wuser_table', 'SET mykey "WuValue"' DBStatementKey = attribute.Key("db.statement") // DBOperationKey is the attribute Key conforming to the "db.operation" // semantic conventions. It represents the name of the operation being // executed, e.g. the [MongoDB command // name](https://docs.mongodb.com/manual/reference/command/#database-operations) // such as `findAndModify`, or the SQL keyword. // // Type: string // RequirementLevel: ConditionallyRequired (If `db.statement` is not // applicable.) // Stability: stable // Examples: 'findAndModify', 'HMSET', 'SELECT' // Note: When setting this to an SQL keyword, it is not recommended to // attempt any client-side parsing of `db.statement` just to get this // property, but it should be set if the operation name is provided by the // library being instrumented. If the SQL statement has an ambiguous // operation, or performs more than one operation, this value may be // omitted. DBOperationKey = attribute.Key("db.operation") ) var ( // Some other SQL database. Fallback only. See notes DBSystemOtherSQL = DBSystemKey.String("other_sql") // Microsoft SQL Server DBSystemMSSQL = DBSystemKey.String("mssql") // Microsoft SQL Server Compact DBSystemMssqlcompact = DBSystemKey.String("mssqlcompact") // MySQL DBSystemMySQL = DBSystemKey.String("mysql") // Oracle Database DBSystemOracle = DBSystemKey.String("oracle") // IBM DB2 DBSystemDB2 = DBSystemKey.String("db2") // PostgreSQL DBSystemPostgreSQL = DBSystemKey.String("postgresql") // Amazon Redshift DBSystemRedshift = DBSystemKey.String("redshift") // Apache Hive DBSystemHive = DBSystemKey.String("hive") // Cloudscape DBSystemCloudscape = DBSystemKey.String("cloudscape") // HyperSQL DataBase DBSystemHSQLDB = DBSystemKey.String("hsqldb") // Progress Database DBSystemProgress = DBSystemKey.String("progress") // SAP MaxDB DBSystemMaxDB = DBSystemKey.String("maxdb") // SAP HANA DBSystemHanaDB = DBSystemKey.String("hanadb") // Ingres DBSystemIngres = DBSystemKey.String("ingres") // FirstSQL DBSystemFirstSQL = DBSystemKey.String("firstsql") // EnterpriseDB DBSystemEDB = DBSystemKey.String("edb") // InterSystems Caché DBSystemCache = DBSystemKey.String("cache") // Adabas (Adaptable Database System) DBSystemAdabas = DBSystemKey.String("adabas") // Firebird DBSystemFirebird = DBSystemKey.String("firebird") // Apache Derby DBSystemDerby = DBSystemKey.String("derby") // FileMaker DBSystemFilemaker = DBSystemKey.String("filemaker") // Informix DBSystemInformix = DBSystemKey.String("informix") // InstantDB DBSystemInstantDB = DBSystemKey.String("instantdb") // InterBase DBSystemInterbase = DBSystemKey.String("interbase") // MariaDB DBSystemMariaDB = DBSystemKey.String("mariadb") // Netezza DBSystemNetezza = DBSystemKey.String("netezza") // Pervasive PSQL DBSystemPervasive = DBSystemKey.String("pervasive") // PointBase DBSystemPointbase = DBSystemKey.String("pointbase") // SQLite DBSystemSqlite = DBSystemKey.String("sqlite") // Sybase DBSystemSybase = DBSystemKey.String("sybase") // Teradata DBSystemTeradata = DBSystemKey.String("teradata") // Vertica DBSystemVertica = DBSystemKey.String("vertica") // H2 DBSystemH2 = DBSystemKey.String("h2") // ColdFusion IMQ DBSystemColdfusion = DBSystemKey.String("coldfusion") // Apache Cassandra DBSystemCassandra = DBSystemKey.String("cassandra") // Apache HBase DBSystemHBase = DBSystemKey.String("hbase") // MongoDB DBSystemMongoDB = DBSystemKey.String("mongodb") // Redis DBSystemRedis = DBSystemKey.String("redis") // Couchbase DBSystemCouchbase = DBSystemKey.String("couchbase") // CouchDB DBSystemCouchDB = DBSystemKey.String("couchdb") // Microsoft Azure Cosmos DB DBSystemCosmosDB = DBSystemKey.String("cosmosdb") // Amazon DynamoDB DBSystemDynamoDB = DBSystemKey.String("dynamodb") // Neo4j DBSystemNeo4j = DBSystemKey.String("neo4j") // Apache Geode DBSystemGeode = DBSystemKey.String("geode") // Elasticsearch DBSystemElasticsearch = DBSystemKey.String("elasticsearch") // Memcached DBSystemMemcached = DBSystemKey.String("memcached") // CockroachDB DBSystemCockroachdb = DBSystemKey.String("cockroachdb") // OpenSearch DBSystemOpensearch = DBSystemKey.String("opensearch") // ClickHouse DBSystemClickhouse = DBSystemKey.String("clickhouse") // Cloud Spanner DBSystemSpanner = DBSystemKey.String("spanner") // Trino DBSystemTrino = DBSystemKey.String("trino") ) // DBConnectionString returns an attribute KeyValue conforming to the // "db.connection_string" semantic conventions. It represents the connection // string used to connect to the database. It is recommended to remove embedded // credentials. func DBConnectionString(val string) attribute.KeyValue { return DBConnectionStringKey.String(val) } // DBUser returns an attribute KeyValue conforming to the "db.user" semantic // conventions. It represents the username for accessing the database. func DBUser(val string) attribute.KeyValue { return DBUserKey.String(val) } // DBJDBCDriverClassname returns an attribute KeyValue conforming to the // "db.jdbc.driver_classname" semantic conventions. It represents the // fully-qualified class name of the [Java Database Connectivity // (JDBC)](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) driver // used to connect. func DBJDBCDriverClassname(val string) attribute.KeyValue { return DBJDBCDriverClassnameKey.String(val) } // DBName returns an attribute KeyValue conforming to the "db.name" semantic // conventions. It represents the this attribute is used to report the name of // the database being accessed. For commands that switch the database, this // should be set to the target database (even if the command fails). func DBName(val string) attribute.KeyValue { return DBNameKey.String(val) } // DBStatement returns an attribute KeyValue conforming to the // "db.statement" semantic conventions. It represents the database statement // being executed. func DBStatement(val string) attribute.KeyValue { return DBStatementKey.String(val) } // DBOperation returns an attribute KeyValue conforming to the // "db.operation" semantic conventions. It represents the name of the operation // being executed, e.g. the [MongoDB command // name](https://docs.mongodb.com/manual/reference/command/#database-operations) // such as `findAndModify`, or the SQL keyword. func DBOperation(val string) attribute.KeyValue { return DBOperationKey.String(val) } // Connection-level attributes for Microsoft SQL Server const ( // DBMSSQLInstanceNameKey is the attribute Key conforming to the // "db.mssql.instance_name" semantic conventions. It represents the // Microsoft SQL Server [instance // name](https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15) // connecting to. This name is used to determine the port of a named // instance. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'MSSQLSERVER' // Note: If setting a `db.mssql.instance_name`, `net.peer.port` is no // longer required (but still recommended if non-standard). DBMSSQLInstanceNameKey = attribute.Key("db.mssql.instance_name") ) // DBMSSQLInstanceName returns an attribute KeyValue conforming to the // "db.mssql.instance_name" semantic conventions. It represents the Microsoft // SQL Server [instance // name](https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15) // connecting to. This name is used to determine the port of a named instance. func DBMSSQLInstanceName(val string) attribute.KeyValue { return DBMSSQLInstanceNameKey.String(val) } // Call-level attributes for Cassandra const ( // DBCassandraPageSizeKey is the attribute Key conforming to the // "db.cassandra.page_size" semantic conventions. It represents the fetch // size used for paging, i.e. how many rows will be returned at once. // // Type: int // RequirementLevel: Optional // Stability: stable // Examples: 5000 DBCassandraPageSizeKey = attribute.Key("db.cassandra.page_size") // DBCassandraConsistencyLevelKey is the attribute Key conforming to the // "db.cassandra.consistency_level" semantic conventions. It represents the // consistency level of the query. Based on consistency values from // [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). // // Type: Enum // RequirementLevel: Optional // Stability: stable DBCassandraConsistencyLevelKey = attribute.Key("db.cassandra.consistency_level") // DBCassandraTableKey is the attribute Key conforming to the // "db.cassandra.table" semantic conventions. It represents the name of the // primary table that the operation is acting upon, including the keyspace // name (if applicable). // // Type: string // RequirementLevel: Recommended // Stability: stable // Examples: 'mytable' // Note: This mirrors the db.sql.table attribute but references cassandra // rather than sql. It is not recommended to attempt any client-side // parsing of `db.statement` just to get this property, but it should be // set if it is provided by the library being instrumented. If the // operation is acting upon an anonymous table, or more than one table, // this value MUST NOT be set. DBCassandraTableKey = attribute.Key("db.cassandra.table") // DBCassandraIdempotenceKey is the attribute Key conforming to the // "db.cassandra.idempotence" semantic conventions. It represents the // whether or not the query is idempotent. // // Type: boolean // RequirementLevel: Optional // Stability: stable DBCassandraIdempotenceKey = attribute.Key("db.cassandra.idempotence") // DBCassandraSpeculativeExecutionCountKey is the attribute Key conforming // to the "db.cassandra.speculative_execution_count" semantic conventions. // It represents the number of times a query was speculatively executed. // Not set or `0` if the query was not executed speculatively. // // Type: int // RequirementLevel: Optional // Stability: stable // Examples: 0, 2 DBCassandraSpeculativeExecutionCountKey = attribute.Key("db.cassandra.speculative_execution_count") // DBCassandraCoordinatorIDKey is the attribute Key conforming to the // "db.cassandra.coordinator.id" semantic conventions. It represents the ID // of the coordinating node for a query. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'be13faa2-8574-4d71-926d-27f16cf8a7af' DBCassandraCoordinatorIDKey = attribute.Key("db.cassandra.coordinator.id") // DBCassandraCoordinatorDCKey is the attribute Key conforming to the // "db.cassandra.coordinator.dc" semantic conventions. It represents the // data center of the coordinating node for a query. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'us-west-2' DBCassandraCoordinatorDCKey = attribute.Key("db.cassandra.coordinator.dc") ) var ( // all DBCassandraConsistencyLevelAll = DBCassandraConsistencyLevelKey.String("all") // each_quorum DBCassandraConsistencyLevelEachQuorum = DBCassandraConsistencyLevelKey.String("each_quorum") // quorum DBCassandraConsistencyLevelQuorum = DBCassandraConsistencyLevelKey.String("quorum") // local_quorum DBCassandraConsistencyLevelLocalQuorum = DBCassandraConsistencyLevelKey.String("local_quorum") // one DBCassandraConsistencyLevelOne = DBCassandraConsistencyLevelKey.String("one") // two DBCassandraConsistencyLevelTwo = DBCassandraConsistencyLevelKey.String("two") // three DBCassandraConsistencyLevelThree = DBCassandraConsistencyLevelKey.String("three") // local_one DBCassandraConsistencyLevelLocalOne = DBCassandraConsistencyLevelKey.String("local_one") // any DBCassandraConsistencyLevelAny = DBCassandraConsistencyLevelKey.String("any") // serial DBCassandraConsistencyLevelSerial = DBCassandraConsistencyLevelKey.String("serial") // local_serial DBCassandraConsistencyLevelLocalSerial = DBCassandraConsistencyLevelKey.String("local_serial") ) // DBCassandraPageSize returns an attribute KeyValue conforming to the // "db.cassandra.page_size" semantic conventions. It represents the fetch size // used for paging, i.e. how many rows will be returned at once. func DBCassandraPageSize(val int) attribute.KeyValue { return DBCassandraPageSizeKey.Int(val) } // DBCassandraTable returns an attribute KeyValue conforming to the // "db.cassandra.table" semantic conventions. It represents the name of the // primary table that the operation is acting upon, including the keyspace name // (if applicable). func DBCassandraTable(val string) attribute.KeyValue { return DBCassandraTableKey.String(val) } // DBCassandraIdempotence returns an attribute KeyValue conforming to the // "db.cassandra.idempotence" semantic conventions. It represents the whether // or not the query is idempotent. func DBCassandraIdempotence(val bool) attribute.KeyValue { return DBCassandraIdempotenceKey.Bool(val) } // DBCassandraSpeculativeExecutionCount returns an attribute KeyValue // conforming to the "db.cassandra.speculative_execution_count" semantic // conventions. It represents the number of times a query was speculatively // executed. Not set or `0` if the query was not executed speculatively. func DBCassandraSpeculativeExecutionCount(val int) attribute.KeyValue { return DBCassandraSpeculativeExecutionCountKey.Int(val) } // DBCassandraCoordinatorID returns an attribute KeyValue conforming to the // "db.cassandra.coordinator.id" semantic conventions. It represents the ID of // the coordinating node for a query. func DBCassandraCoordinatorID(val string) attribute.KeyValue { return DBCassandraCoordinatorIDKey.String(val) } // DBCassandraCoordinatorDC returns an attribute KeyValue conforming to the // "db.cassandra.coordinator.dc" semantic conventions. It represents the data // center of the coordinating node for a query. func DBCassandraCoordinatorDC(val string) attribute.KeyValue { return DBCassandraCoordinatorDCKey.String(val) } // Call-level attributes for Redis const ( // DBRedisDBIndexKey is the attribute Key conforming to the // "db.redis.database_index" semantic conventions. It represents the index // of the database being accessed as used in the [`SELECT` // command](https://redis.io/commands/select), provided as an integer. To // be used instead of the generic `db.name` attribute. // // Type: int // RequirementLevel: ConditionallyRequired (If other than the default // database (`0`).) // Stability: stable // Examples: 0, 1, 15 DBRedisDBIndexKey = attribute.Key("db.redis.database_index") ) // DBRedisDBIndex returns an attribute KeyValue conforming to the // "db.redis.database_index" semantic conventions. It represents the index of // the database being accessed as used in the [`SELECT` // command](https://redis.io/commands/select), provided as an integer. To be // used instead of the generic `db.name` attribute. func DBRedisDBIndex(val int) attribute.KeyValue { return DBRedisDBIndexKey.Int(val) } // Call-level attributes for MongoDB const ( // DBMongoDBCollectionKey is the attribute Key conforming to the // "db.mongodb.collection" semantic conventions. It represents the // collection being accessed within the database stated in `db.name`. // // Type: string // RequirementLevel: Required // Stability: stable // Examples: 'customers', 'products' DBMongoDBCollectionKey = attribute.Key("db.mongodb.collection") ) // DBMongoDBCollection returns an attribute KeyValue conforming to the // "db.mongodb.collection" semantic conventions. It represents the collection // being accessed within the database stated in `db.name`. func DBMongoDBCollection(val string) attribute.KeyValue { return DBMongoDBCollectionKey.String(val) } // Call-level attributes for SQL databases const ( // DBSQLTableKey is the attribute Key conforming to the "db.sql.table" // semantic conventions. It represents the name of the primary table that // the operation is acting upon, including the database name (if // applicable). // // Type: string // RequirementLevel: Recommended // Stability: stable // Examples: 'public.users', 'customers' // Note: It is not recommended to attempt any client-side parsing of // `db.statement` just to get this property, but it should be set if it is // provided by the library being instrumented. If the operation is acting // upon an anonymous table, or more than one table, this value MUST NOT be // set. DBSQLTableKey = attribute.Key("db.sql.table") ) // DBSQLTable returns an attribute KeyValue conforming to the "db.sql.table" // semantic conventions. It represents the name of the primary table that the // operation is acting upon, including the database name (if applicable). func DBSQLTable(val string) attribute.KeyValue { return DBSQLTableKey.String(val) } // Call-level attributes for Cosmos DB. const ( // DBCosmosDBClientIDKey is the attribute Key conforming to the // "db.cosmosdb.client_id" semantic conventions. It represents the unique // Cosmos client instance id. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: '3ba4827d-4422-483f-b59f-85b74211c11d' DBCosmosDBClientIDKey = attribute.Key("db.cosmosdb.client_id") // DBCosmosDBOperationTypeKey is the attribute Key conforming to the // "db.cosmosdb.operation_type" semantic conventions. It represents the // cosmosDB Operation Type. // // Type: Enum // RequirementLevel: ConditionallyRequired (when performing one of the // operations in this list) // Stability: stable DBCosmosDBOperationTypeKey = attribute.Key("db.cosmosdb.operation_type") // DBCosmosDBConnectionModeKey is the attribute Key conforming to the // "db.cosmosdb.connection_mode" semantic conventions. It represents the // cosmos client connection mode. // // Type: Enum // RequirementLevel: ConditionallyRequired (if not `direct` (or pick gw as // default)) // Stability: stable DBCosmosDBConnectionModeKey = attribute.Key("db.cosmosdb.connection_mode") // DBCosmosDBContainerKey is the attribute Key conforming to the // "db.cosmosdb.container" semantic conventions. It represents the cosmos // DB container name. // // Type: string // RequirementLevel: ConditionallyRequired (if available) // Stability: stable // Examples: 'anystring' DBCosmosDBContainerKey = attribute.Key("db.cosmosdb.container") // DBCosmosDBRequestContentLengthKey is the attribute Key conforming to the // "db.cosmosdb.request_content_length" semantic conventions. It represents // the request payload size in bytes // // Type: int // RequirementLevel: Optional // Stability: stable DBCosmosDBRequestContentLengthKey = attribute.Key("db.cosmosdb.request_content_length") // DBCosmosDBStatusCodeKey is the attribute Key conforming to the // "db.cosmosdb.status_code" semantic conventions. It represents the cosmos // DB status code. // // Type: int // RequirementLevel: ConditionallyRequired (if response was received) // Stability: stable // Examples: 200, 201 DBCosmosDBStatusCodeKey = attribute.Key("db.cosmosdb.status_code")
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
true
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/http.go
vendor/go.opentelemetry.io/otel/semconv/v1.20.0/http.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package semconv // import "go.opentelemetry.io/otel/semconv/v1.20.0" // HTTP scheme attributes. var ( HTTPSchemeHTTP = HTTPSchemeKey.String("http") HTTPSchemeHTTPS = HTTPSchemeKey.String("https") )
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/resource.go
vendor/go.opentelemetry.io/otel/semconv/v1.20.0/resource.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 // Code generated from semantic convention specification. DO NOT EDIT. package semconv // import "go.opentelemetry.io/otel/semconv/v1.20.0" import "go.opentelemetry.io/otel/attribute" // The web browser in which the application represented by the resource is // running. The `browser.*` attributes MUST be used only for resources that // represent applications running in a web browser (regardless of whether // running on a mobile or desktop device). const ( // BrowserBrandsKey is the attribute Key conforming to the "browser.brands" // semantic conventions. It represents the array of brand name and version // separated by a space // // Type: string[] // RequirementLevel: Optional // Stability: stable // Examples: ' Not A;Brand 99', 'Chromium 99', 'Chrome 99' // Note: This value is intended to be taken from the [UA client hints // API](https://wicg.github.io/ua-client-hints/#interface) // (`navigator.userAgentData.brands`). BrowserBrandsKey = attribute.Key("browser.brands") // BrowserPlatformKey is the attribute Key conforming to the // "browser.platform" semantic conventions. It represents the platform on // which the browser is running // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'Windows', 'macOS', 'Android' // Note: This value is intended to be taken from the [UA client hints // API](https://wicg.github.io/ua-client-hints/#interface) // (`navigator.userAgentData.platform`). If unavailable, the legacy // `navigator.platform` API SHOULD NOT be used instead and this attribute // SHOULD be left unset in order for the values to be consistent. // The list of possible values is defined in the [W3C User-Agent Client // Hints // specification](https://wicg.github.io/ua-client-hints/#sec-ch-ua-platform). // Note that some (but not all) of these values can overlap with values in // the [`os.type` and `os.name` attributes](./os.md). However, for // consistency, the values in the `browser.platform` attribute should // capture the exact value that the user agent provides. BrowserPlatformKey = attribute.Key("browser.platform") // BrowserMobileKey is the attribute Key conforming to the "browser.mobile" // semantic conventions. It represents a boolean that is true if the // browser is running on a mobile device // // Type: boolean // RequirementLevel: Optional // Stability: stable // Note: This value is intended to be taken from the [UA client hints // API](https://wicg.github.io/ua-client-hints/#interface) // (`navigator.userAgentData.mobile`). If unavailable, this attribute // SHOULD be left unset. BrowserMobileKey = attribute.Key("browser.mobile") // BrowserLanguageKey is the attribute Key conforming to the // "browser.language" semantic conventions. It represents the preferred // language of the user using the browser // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'en', 'en-US', 'fr', 'fr-FR' // Note: This value is intended to be taken from the Navigator API // `navigator.language`. BrowserLanguageKey = attribute.Key("browser.language") ) // BrowserBrands returns an attribute KeyValue conforming to the // "browser.brands" semantic conventions. It represents the array of brand name // and version separated by a space func BrowserBrands(val ...string) attribute.KeyValue { return BrowserBrandsKey.StringSlice(val) } // BrowserPlatform returns an attribute KeyValue conforming to the // "browser.platform" semantic conventions. It represents the platform on which // the browser is running func BrowserPlatform(val string) attribute.KeyValue { return BrowserPlatformKey.String(val) } // BrowserMobile returns an attribute KeyValue conforming to the // "browser.mobile" semantic conventions. It represents a boolean that is true // if the browser is running on a mobile device func BrowserMobile(val bool) attribute.KeyValue { return BrowserMobileKey.Bool(val) } // BrowserLanguage returns an attribute KeyValue conforming to the // "browser.language" semantic conventions. It represents the preferred // language of the user using the browser func BrowserLanguage(val string) attribute.KeyValue { return BrowserLanguageKey.String(val) } // A cloud environment (e.g. GCP, Azure, AWS) const ( // CloudProviderKey is the attribute Key conforming to the "cloud.provider" // semantic conventions. It represents the name of the cloud provider. // // Type: Enum // RequirementLevel: Optional // Stability: stable CloudProviderKey = attribute.Key("cloud.provider") // CloudAccountIDKey is the attribute Key conforming to the // "cloud.account.id" semantic conventions. It represents the cloud account // ID the resource is assigned to. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: '111111111111', 'opentelemetry' CloudAccountIDKey = attribute.Key("cloud.account.id") // CloudRegionKey is the attribute Key conforming to the "cloud.region" // semantic conventions. It represents the geographical region the resource // is running. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'us-central1', 'us-east-1' // Note: Refer to your provider's docs to see the available regions, for // example [Alibaba Cloud // regions](https://www.alibabacloud.com/help/doc-detail/40654.htm), [AWS // regions](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/), // [Azure // regions](https://azure.microsoft.com/en-us/global-infrastructure/geographies/), // [Google Cloud regions](https://cloud.google.com/about/locations), or // [Tencent Cloud // regions](https://www.tencentcloud.com/document/product/213/6091). CloudRegionKey = attribute.Key("cloud.region") // CloudResourceIDKey is the attribute Key conforming to the // "cloud.resource_id" semantic conventions. It represents the cloud // provider-specific native identifier of the monitored cloud resource // (e.g. an // [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // on AWS, a [fully qualified resource // ID](https://learn.microsoft.com/en-us/rest/api/resources/resources/get-by-id) // on Azure, a [full resource // name](https://cloud.google.com/apis/design/resource_names#full_resource_name) // on GCP) // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'arn:aws:lambda:REGION:ACCOUNT_ID:function:my-function', // '//run.googleapis.com/projects/PROJECT_ID/locations/LOCATION_ID/services/SERVICE_ID', // '/subscriptions/<SUBSCIPTION_GUID>/resourceGroups/<RG>/providers/Microsoft.Web/sites/<FUNCAPP>/functions/<FUNC>' // Note: On some cloud providers, it may not be possible to determine the // full ID at startup, // so it may be necessary to set `cloud.resource_id` as a span attribute // instead. // // The exact value to use for `cloud.resource_id` depends on the cloud // provider. // The following well-known definitions MUST be used if you set this // attribute and they apply: // // * **AWS Lambda:** The function // [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html). // Take care not to use the "invoked ARN" directly but replace any // [alias // suffix](https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html) // with the resolved function version, as the same runtime instance may // be invokable with // multiple different aliases. // * **GCP:** The [URI of the // resource](https://cloud.google.com/iam/docs/full-resource-names) // * **Azure:** The [Fully Qualified Resource // ID](https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id) // of the invoked function, // *not* the function app, having the form // `/subscriptions/<SUBSCIPTION_GUID>/resourceGroups/<RG>/providers/Microsoft.Web/sites/<FUNCAPP>/functions/<FUNC>`. // This means that a span attribute MUST be used, as an Azure function // app can host multiple functions that would usually share // a TracerProvider. CloudResourceIDKey = attribute.Key("cloud.resource_id") // CloudAvailabilityZoneKey is the attribute Key conforming to the // "cloud.availability_zone" semantic conventions. It represents the cloud // regions often have multiple, isolated locations known as zones to // increase availability. Availability zone represents the zone where the // resource is running. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'us-east-1c' // Note: Availability zones are called "zones" on Alibaba Cloud and Google // Cloud. CloudAvailabilityZoneKey = attribute.Key("cloud.availability_zone") // CloudPlatformKey is the attribute Key conforming to the "cloud.platform" // semantic conventions. It represents the cloud platform in use. // // Type: Enum // RequirementLevel: Optional // Stability: stable // Note: The prefix of the service SHOULD match the one specified in // `cloud.provider`. CloudPlatformKey = attribute.Key("cloud.platform") ) var ( // Alibaba Cloud CloudProviderAlibabaCloud = CloudProviderKey.String("alibaba_cloud") // Amazon Web Services CloudProviderAWS = CloudProviderKey.String("aws") // Microsoft Azure CloudProviderAzure = CloudProviderKey.String("azure") // Google Cloud Platform CloudProviderGCP = CloudProviderKey.String("gcp") // Heroku Platform as a Service CloudProviderHeroku = CloudProviderKey.String("heroku") // IBM Cloud CloudProviderIbmCloud = CloudProviderKey.String("ibm_cloud") // Tencent Cloud CloudProviderTencentCloud = CloudProviderKey.String("tencent_cloud") ) var ( // Alibaba Cloud Elastic Compute Service CloudPlatformAlibabaCloudECS = CloudPlatformKey.String("alibaba_cloud_ecs") // Alibaba Cloud Function Compute CloudPlatformAlibabaCloudFc = CloudPlatformKey.String("alibaba_cloud_fc") // Red Hat OpenShift on Alibaba Cloud CloudPlatformAlibabaCloudOpenshift = CloudPlatformKey.String("alibaba_cloud_openshift") // AWS Elastic Compute Cloud CloudPlatformAWSEC2 = CloudPlatformKey.String("aws_ec2") // AWS Elastic Container Service CloudPlatformAWSECS = CloudPlatformKey.String("aws_ecs") // AWS Elastic Kubernetes Service CloudPlatformAWSEKS = CloudPlatformKey.String("aws_eks") // AWS Lambda CloudPlatformAWSLambda = CloudPlatformKey.String("aws_lambda") // AWS Elastic Beanstalk CloudPlatformAWSElasticBeanstalk = CloudPlatformKey.String("aws_elastic_beanstalk") // AWS App Runner CloudPlatformAWSAppRunner = CloudPlatformKey.String("aws_app_runner") // Red Hat OpenShift on AWS (ROSA) CloudPlatformAWSOpenshift = CloudPlatformKey.String("aws_openshift") // Azure Virtual Machines CloudPlatformAzureVM = CloudPlatformKey.String("azure_vm") // Azure Container Instances CloudPlatformAzureContainerInstances = CloudPlatformKey.String("azure_container_instances") // Azure Kubernetes Service CloudPlatformAzureAKS = CloudPlatformKey.String("azure_aks") // Azure Functions CloudPlatformAzureFunctions = CloudPlatformKey.String("azure_functions") // Azure App Service CloudPlatformAzureAppService = CloudPlatformKey.String("azure_app_service") // Azure Red Hat OpenShift CloudPlatformAzureOpenshift = CloudPlatformKey.String("azure_openshift") // Google Cloud Compute Engine (GCE) CloudPlatformGCPComputeEngine = CloudPlatformKey.String("gcp_compute_engine") // Google Cloud Run CloudPlatformGCPCloudRun = CloudPlatformKey.String("gcp_cloud_run") // Google Cloud Kubernetes Engine (GKE) CloudPlatformGCPKubernetesEngine = CloudPlatformKey.String("gcp_kubernetes_engine") // Google Cloud Functions (GCF) CloudPlatformGCPCloudFunctions = CloudPlatformKey.String("gcp_cloud_functions") // Google Cloud App Engine (GAE) CloudPlatformGCPAppEngine = CloudPlatformKey.String("gcp_app_engine") // Red Hat OpenShift on Google Cloud CloudPlatformGCPOpenshift = CloudPlatformKey.String("gcp_openshift") // Red Hat OpenShift on IBM Cloud CloudPlatformIbmCloudOpenshift = CloudPlatformKey.String("ibm_cloud_openshift") // Tencent Cloud Cloud Virtual Machine (CVM) CloudPlatformTencentCloudCvm = CloudPlatformKey.String("tencent_cloud_cvm") // Tencent Cloud Elastic Kubernetes Service (EKS) CloudPlatformTencentCloudEKS = CloudPlatformKey.String("tencent_cloud_eks") // Tencent Cloud Serverless Cloud Function (SCF) CloudPlatformTencentCloudScf = CloudPlatformKey.String("tencent_cloud_scf") ) // CloudAccountID returns an attribute KeyValue conforming to the // "cloud.account.id" semantic conventions. It represents the cloud account ID // the resource is assigned to. func CloudAccountID(val string) attribute.KeyValue { return CloudAccountIDKey.String(val) } // CloudRegion returns an attribute KeyValue conforming to the // "cloud.region" semantic conventions. It represents the geographical region // the resource is running. func CloudRegion(val string) attribute.KeyValue { return CloudRegionKey.String(val) } // CloudResourceID returns an attribute KeyValue conforming to the // "cloud.resource_id" semantic conventions. It represents the cloud // provider-specific native identifier of the monitored cloud resource (e.g. an // [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // on AWS, a [fully qualified resource // ID](https://learn.microsoft.com/en-us/rest/api/resources/resources/get-by-id) // on Azure, a [full resource // name](https://cloud.google.com/apis/design/resource_names#full_resource_name) // on GCP) func CloudResourceID(val string) attribute.KeyValue { return CloudResourceIDKey.String(val) } // CloudAvailabilityZone returns an attribute KeyValue conforming to the // "cloud.availability_zone" semantic conventions. It represents the cloud // regions often have multiple, isolated locations known as zones to increase // availability. Availability zone represents the zone where the resource is // running. func CloudAvailabilityZone(val string) attribute.KeyValue { return CloudAvailabilityZoneKey.String(val) } // Resources used by AWS Elastic Container Service (ECS). const ( // AWSECSContainerARNKey is the attribute Key conforming to the // "aws.ecs.container.arn" semantic conventions. It represents the Amazon // Resource Name (ARN) of an [ECS container // instance](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_instances.html). // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: // 'arn:aws:ecs:us-west-1:123456789123:container/32624152-9086-4f0e-acae-1a75b14fe4d9' AWSECSContainerARNKey = attribute.Key("aws.ecs.container.arn") // AWSECSClusterARNKey is the attribute Key conforming to the // "aws.ecs.cluster.arn" semantic conventions. It represents the ARN of an // [ECS // cluster](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/clusters.html). // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'arn:aws:ecs:us-west-2:123456789123:cluster/my-cluster' AWSECSClusterARNKey = attribute.Key("aws.ecs.cluster.arn") // AWSECSLaunchtypeKey is the attribute Key conforming to the // "aws.ecs.launchtype" semantic conventions. It represents the [launch // type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) // for an ECS task. // // Type: Enum // RequirementLevel: Optional // Stability: stable AWSECSLaunchtypeKey = attribute.Key("aws.ecs.launchtype") // AWSECSTaskARNKey is the attribute Key conforming to the // "aws.ecs.task.arn" semantic conventions. It represents the ARN of an // [ECS task // definition](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html). // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: // 'arn:aws:ecs:us-west-1:123456789123:task/10838bed-421f-43ef-870a-f43feacbbb5b' AWSECSTaskARNKey = attribute.Key("aws.ecs.task.arn") // AWSECSTaskFamilyKey is the attribute Key conforming to the // "aws.ecs.task.family" semantic conventions. It represents the task // definition family this task definition is a member of. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'opentelemetry-family' AWSECSTaskFamilyKey = attribute.Key("aws.ecs.task.family") // AWSECSTaskRevisionKey is the attribute Key conforming to the // "aws.ecs.task.revision" semantic conventions. It represents the revision // for this task definition. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: '8', '26' AWSECSTaskRevisionKey = attribute.Key("aws.ecs.task.revision") ) var ( // ec2 AWSECSLaunchtypeEC2 = AWSECSLaunchtypeKey.String("ec2") // fargate AWSECSLaunchtypeFargate = AWSECSLaunchtypeKey.String("fargate") ) // AWSECSContainerARN returns an attribute KeyValue conforming to the // "aws.ecs.container.arn" semantic conventions. It represents the Amazon // Resource Name (ARN) of an [ECS container // instance](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_instances.html). func AWSECSContainerARN(val string) attribute.KeyValue { return AWSECSContainerARNKey.String(val) } // AWSECSClusterARN returns an attribute KeyValue conforming to the // "aws.ecs.cluster.arn" semantic conventions. It represents the ARN of an [ECS // cluster](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/clusters.html). func AWSECSClusterARN(val string) attribute.KeyValue { return AWSECSClusterARNKey.String(val) } // AWSECSTaskARN returns an attribute KeyValue conforming to the // "aws.ecs.task.arn" semantic conventions. It represents the ARN of an [ECS // task // definition](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html). func AWSECSTaskARN(val string) attribute.KeyValue { return AWSECSTaskARNKey.String(val) } // AWSECSTaskFamily returns an attribute KeyValue conforming to the // "aws.ecs.task.family" semantic conventions. It represents the task // definition family this task definition is a member of. func AWSECSTaskFamily(val string) attribute.KeyValue { return AWSECSTaskFamilyKey.String(val) } // AWSECSTaskRevision returns an attribute KeyValue conforming to the // "aws.ecs.task.revision" semantic conventions. It represents the revision for // this task definition. func AWSECSTaskRevision(val string) attribute.KeyValue { return AWSECSTaskRevisionKey.String(val) } // Resources used by AWS Elastic Kubernetes Service (EKS). const ( // AWSEKSClusterARNKey is the attribute Key conforming to the // "aws.eks.cluster.arn" semantic conventions. It represents the ARN of an // EKS cluster. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'arn:aws:ecs:us-west-2:123456789123:cluster/my-cluster' AWSEKSClusterARNKey = attribute.Key("aws.eks.cluster.arn") ) // AWSEKSClusterARN returns an attribute KeyValue conforming to the // "aws.eks.cluster.arn" semantic conventions. It represents the ARN of an EKS // cluster. func AWSEKSClusterARN(val string) attribute.KeyValue { return AWSEKSClusterARNKey.String(val) } // Resources specific to Amazon Web Services. const ( // AWSLogGroupNamesKey is the attribute Key conforming to the // "aws.log.group.names" semantic conventions. It represents the name(s) of // the AWS log group(s) an application is writing to. // // Type: string[] // RequirementLevel: Optional // Stability: stable // Examples: '/aws/lambda/my-function', 'opentelemetry-service' // Note: Multiple log groups must be supported for cases like // multi-container applications, where a single application has sidecar // containers, and each write to their own log group. AWSLogGroupNamesKey = attribute.Key("aws.log.group.names") // AWSLogGroupARNsKey is the attribute Key conforming to the // "aws.log.group.arns" semantic conventions. It represents the Amazon // Resource Name(s) (ARN) of the AWS log group(s). // // Type: string[] // RequirementLevel: Optional // Stability: stable // Examples: // 'arn:aws:logs:us-west-1:123456789012:log-group:/aws/my/group:*' // Note: See the [log group ARN format // documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). AWSLogGroupARNsKey = attribute.Key("aws.log.group.arns") // AWSLogStreamNamesKey is the attribute Key conforming to the // "aws.log.stream.names" semantic conventions. It represents the name(s) // of the AWS log stream(s) an application is writing to. // // Type: string[] // RequirementLevel: Optional // Stability: stable // Examples: 'logs/main/10838bed-421f-43ef-870a-f43feacbbb5b' AWSLogStreamNamesKey = attribute.Key("aws.log.stream.names") // AWSLogStreamARNsKey is the attribute Key conforming to the // "aws.log.stream.arns" semantic conventions. It represents the ARN(s) of // the AWS log stream(s). // // Type: string[] // RequirementLevel: Optional // Stability: stable // Examples: // 'arn:aws:logs:us-west-1:123456789012:log-group:/aws/my/group:log-stream:logs/main/10838bed-421f-43ef-870a-f43feacbbb5b' // Note: See the [log stream ARN format // documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). // One log group can contain several log streams, so these ARNs necessarily // identify both a log group and a log stream. AWSLogStreamARNsKey = attribute.Key("aws.log.stream.arns") ) // AWSLogGroupNames returns an attribute KeyValue conforming to the // "aws.log.group.names" semantic conventions. It represents the name(s) of the // AWS log group(s) an application is writing to. func AWSLogGroupNames(val ...string) attribute.KeyValue { return AWSLogGroupNamesKey.StringSlice(val) } // AWSLogGroupARNs returns an attribute KeyValue conforming to the // "aws.log.group.arns" semantic conventions. It represents the Amazon Resource // Name(s) (ARN) of the AWS log group(s). func AWSLogGroupARNs(val ...string) attribute.KeyValue { return AWSLogGroupARNsKey.StringSlice(val) } // AWSLogStreamNames returns an attribute KeyValue conforming to the // "aws.log.stream.names" semantic conventions. It represents the name(s) of // the AWS log stream(s) an application is writing to. func AWSLogStreamNames(val ...string) attribute.KeyValue { return AWSLogStreamNamesKey.StringSlice(val) } // AWSLogStreamARNs returns an attribute KeyValue conforming to the // "aws.log.stream.arns" semantic conventions. It represents the ARN(s) of the // AWS log stream(s). func AWSLogStreamARNs(val ...string) attribute.KeyValue { return AWSLogStreamARNsKey.StringSlice(val) } // Heroku dyno metadata const ( // HerokuReleaseCreationTimestampKey is the attribute Key conforming to the // "heroku.release.creation_timestamp" semantic conventions. It represents // the time and date the release was created // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: '2022-10-23T18:00:42Z' HerokuReleaseCreationTimestampKey = attribute.Key("heroku.release.creation_timestamp") // HerokuReleaseCommitKey is the attribute Key conforming to the // "heroku.release.commit" semantic conventions. It represents the commit // hash for the current release // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'e6134959463efd8966b20e75b913cafe3f5ec' HerokuReleaseCommitKey = attribute.Key("heroku.release.commit") // HerokuAppIDKey is the attribute Key conforming to the "heroku.app.id" // semantic conventions. It represents the unique identifier for the // application // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: '2daa2797-e42b-4624-9322-ec3f968df4da' HerokuAppIDKey = attribute.Key("heroku.app.id") ) // HerokuReleaseCreationTimestamp returns an attribute KeyValue conforming // to the "heroku.release.creation_timestamp" semantic conventions. It // represents the time and date the release was created func HerokuReleaseCreationTimestamp(val string) attribute.KeyValue { return HerokuReleaseCreationTimestampKey.String(val) } // HerokuReleaseCommit returns an attribute KeyValue conforming to the // "heroku.release.commit" semantic conventions. It represents the commit hash // for the current release func HerokuReleaseCommit(val string) attribute.KeyValue { return HerokuReleaseCommitKey.String(val) } // HerokuAppID returns an attribute KeyValue conforming to the // "heroku.app.id" semantic conventions. It represents the unique identifier // for the application func HerokuAppID(val string) attribute.KeyValue { return HerokuAppIDKey.String(val) } // A container instance. const ( // ContainerNameKey is the attribute Key conforming to the "container.name" // semantic conventions. It represents the container name used by container // runtime. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'opentelemetry-autoconf' ContainerNameKey = attribute.Key("container.name") // ContainerIDKey is the attribute Key conforming to the "container.id" // semantic conventions. It represents the container ID. Usually a UUID, as // for example used to [identify Docker // containers](https://docs.docker.com/engine/reference/run/#container-identification). // The UUID might be abbreviated. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'a3bf90e006b2' ContainerIDKey = attribute.Key("container.id") // ContainerRuntimeKey is the attribute Key conforming to the // "container.runtime" semantic conventions. It represents the container // runtime managing this container. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'docker', 'containerd', 'rkt' ContainerRuntimeKey = attribute.Key("container.runtime") // ContainerImageNameKey is the attribute Key conforming to the // "container.image.name" semantic conventions. It represents the name of // the image the container was built on. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'gcr.io/opentelemetry/operator' ContainerImageNameKey = attribute.Key("container.image.name") // ContainerImageTagKey is the attribute Key conforming to the // "container.image.tag" semantic conventions. It represents the container // image tag. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: '0.1' ContainerImageTagKey = attribute.Key("container.image.tag") ) // ContainerName returns an attribute KeyValue conforming to the // "container.name" semantic conventions. It represents the container name used // by container runtime. func ContainerName(val string) attribute.KeyValue { return ContainerNameKey.String(val) } // ContainerID returns an attribute KeyValue conforming to the // "container.id" semantic conventions. It represents the container ID. Usually // a UUID, as for example used to [identify Docker // containers](https://docs.docker.com/engine/reference/run/#container-identification). // The UUID might be abbreviated. func ContainerID(val string) attribute.KeyValue { return ContainerIDKey.String(val) } // ContainerRuntime returns an attribute KeyValue conforming to the // "container.runtime" semantic conventions. It represents the container // runtime managing this container. func ContainerRuntime(val string) attribute.KeyValue { return ContainerRuntimeKey.String(val) } // ContainerImageName returns an attribute KeyValue conforming to the // "container.image.name" semantic conventions. It represents the name of the // image the container was built on. func ContainerImageName(val string) attribute.KeyValue { return ContainerImageNameKey.String(val) } // ContainerImageTag returns an attribute KeyValue conforming to the // "container.image.tag" semantic conventions. It represents the container // image tag. func ContainerImageTag(val string) attribute.KeyValue { return ContainerImageTagKey.String(val) } // The software deployment. const ( // DeploymentEnvironmentKey is the attribute Key conforming to the // "deployment.environment" semantic conventions. It represents the name of // the [deployment // environment](https://en.wikipedia.org/wiki/Deployment_environment) (aka // deployment tier). // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'staging', 'production' DeploymentEnvironmentKey = attribute.Key("deployment.environment") ) // DeploymentEnvironment returns an attribute KeyValue conforming to the // "deployment.environment" semantic conventions. It represents the name of the // [deployment // environment](https://en.wikipedia.org/wiki/Deployment_environment) (aka // deployment tier). func DeploymentEnvironment(val string) attribute.KeyValue { return DeploymentEnvironmentKey.String(val) } // The device on which the process represented by this resource is running. const ( // DeviceIDKey is the attribute Key conforming to the "device.id" semantic // conventions. It represents a unique identifier representing the device // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: '2ab2916d-a51f-4ac8-80ee-45ac31a28092' // Note: The device identifier MUST only be defined using the values // outlined below. This value is not an advertising identifier and MUST NOT // be used as such. On iOS (Swift or Objective-C), this value MUST be equal // to the [vendor // identifier](https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor). // On Android (Java or Kotlin), this value MUST be equal to the Firebase // Installation ID or a globally unique UUID which is persisted across // sessions in your application. More information can be found // [here](https://developer.android.com/training/articles/user-data-ids) on // best practices and exact implementation details. Caution should be taken // when storing personal data or anything which can identify a user. GDPR // and data protection laws may apply, ensure you do your own due // diligence. DeviceIDKey = attribute.Key("device.id") // DeviceModelIdentifierKey is the attribute Key conforming to the // "device.model.identifier" semantic conventions. It represents the model // identifier for the device // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'iPhone3,4', 'SM-G920F' // Note: It's recommended this value represents a machine readable version // of the model identifier rather than the market or consumer-friendly name // of the device. DeviceModelIdentifierKey = attribute.Key("device.model.identifier") // DeviceModelNameKey is the attribute Key conforming to the // "device.model.name" semantic conventions. It represents the marketing // name for the device model // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'iPhone 6s Plus', 'Samsung Galaxy S6' // Note: It's recommended this value represents a human readable version of // the device model rather than a machine readable alternative. DeviceModelNameKey = attribute.Key("device.model.name") // DeviceManufacturerKey is the attribute Key conforming to the // "device.manufacturer" semantic conventions. It represents the name of // the device manufacturer // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'Apple', 'Samsung' // Note: The Android OS provides this field via // [Build](https://developer.android.com/reference/android/os/Build#MANUFACTURER). // iOS apps SHOULD hardcode the value `Apple`. DeviceManufacturerKey = attribute.Key("device.manufacturer") ) // DeviceID returns an attribute KeyValue conforming to the "device.id" // semantic conventions. It represents a unique identifier representing the // device func DeviceID(val string) attribute.KeyValue { return DeviceIDKey.String(val) } // DeviceModelIdentifier returns an attribute KeyValue conforming to the // "device.model.identifier" semantic conventions. It represents the model // identifier for the device func DeviceModelIdentifier(val string) attribute.KeyValue { return DeviceModelIdentifierKey.String(val) } // DeviceModelName returns an attribute KeyValue conforming to the // "device.model.name" semantic conventions. It represents the marketing name // for the device model func DeviceModelName(val string) attribute.KeyValue { return DeviceModelNameKey.String(val) } // DeviceManufacturer returns an attribute KeyValue conforming to the // "device.manufacturer" semantic conventions. It represents the name of the // device manufacturer func DeviceManufacturer(val string) attribute.KeyValue { return DeviceManufacturerKey.String(val) } // A serverless instance. const (
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
true
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/event.go
vendor/go.opentelemetry.io/otel/semconv/v1.20.0/event.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 // Code generated from semantic convention specification. DO NOT EDIT. package semconv // import "go.opentelemetry.io/otel/semconv/v1.20.0" import "go.opentelemetry.io/otel/attribute" // This semantic convention defines the attributes used to represent a feature // flag evaluation as an event. const ( // FeatureFlagKeyKey is the attribute Key conforming to the // "feature_flag.key" semantic conventions. It represents the unique // identifier of the feature flag. // // Type: string // RequirementLevel: Required // Stability: stable // Examples: 'logo-color' FeatureFlagKeyKey = attribute.Key("feature_flag.key") // FeatureFlagProviderNameKey is the attribute Key conforming to the // "feature_flag.provider_name" semantic conventions. It represents the // name of the service provider that performs the flag evaluation. // // Type: string // RequirementLevel: Recommended // Stability: stable // Examples: 'Flag Manager' FeatureFlagProviderNameKey = attribute.Key("feature_flag.provider_name") // FeatureFlagVariantKey is the attribute Key conforming to the // "feature_flag.variant" semantic conventions. It represents the sHOULD be // a semantic identifier for a value. If one is unavailable, a stringified // version of the value can be used. // // Type: string // RequirementLevel: Recommended // Stability: stable // Examples: 'red', 'true', 'on' // Note: A semantic identifier, commonly referred to as a variant, provides // a means // for referring to a value without including the value itself. This can // provide additional context for understanding the meaning behind a value. // For example, the variant `red` maybe be used for the value `#c05543`. // // A stringified version of the value can be used in situations where a // semantic identifier is unavailable. String representation of the value // should be determined by the implementer. FeatureFlagVariantKey = attribute.Key("feature_flag.variant") ) // FeatureFlagKey returns an attribute KeyValue conforming to the // "feature_flag.key" semantic conventions. It represents the unique identifier // of the feature flag. func FeatureFlagKey(val string) attribute.KeyValue { return FeatureFlagKeyKey.String(val) } // FeatureFlagProviderName returns an attribute KeyValue conforming to the // "feature_flag.provider_name" semantic conventions. It represents the name of // the service provider that performs the flag evaluation. func FeatureFlagProviderName(val string) attribute.KeyValue { return FeatureFlagProviderNameKey.String(val) } // FeatureFlagVariant returns an attribute KeyValue conforming to the // "feature_flag.variant" semantic conventions. It represents the sHOULD be a // semantic identifier for a value. If one is unavailable, a stringified // version of the value can be used. func FeatureFlagVariant(val string) attribute.KeyValue { return FeatureFlagVariantKey.String(val) } // RPC received/sent message. const ( // MessageTypeKey is the attribute Key conforming to the "message.type" // semantic conventions. It represents the whether this is a received or // sent message. // // Type: Enum // RequirementLevel: Optional // Stability: stable MessageTypeKey = attribute.Key("message.type") // MessageIDKey is the attribute Key conforming to the "message.id" // semantic conventions. It represents the mUST be calculated as two // different counters starting from `1` one for sent messages and one for // received message. // // Type: int // RequirementLevel: Optional // Stability: stable // Note: This way we guarantee that the values will be consistent between // different implementations. MessageIDKey = attribute.Key("message.id") // MessageCompressedSizeKey is the attribute Key conforming to the // "message.compressed_size" semantic conventions. It represents the // compressed size of the message in bytes. // // Type: int // RequirementLevel: Optional // Stability: stable MessageCompressedSizeKey = attribute.Key("message.compressed_size") // MessageUncompressedSizeKey is the attribute Key conforming to the // "message.uncompressed_size" semantic conventions. It represents the // uncompressed size of the message in bytes. // // Type: int // RequirementLevel: Optional // Stability: stable MessageUncompressedSizeKey = attribute.Key("message.uncompressed_size") ) var ( // sent MessageTypeSent = MessageTypeKey.String("SENT") // received MessageTypeReceived = MessageTypeKey.String("RECEIVED") ) // MessageID returns an attribute KeyValue conforming to the "message.id" // semantic conventions. It represents the mUST be calculated as two different // counters starting from `1` one for sent messages and one for received // message. func MessageID(val int) attribute.KeyValue { return MessageIDKey.Int(val) } // MessageCompressedSize returns an attribute KeyValue conforming to the // "message.compressed_size" semantic conventions. It represents the compressed // size of the message in bytes. func MessageCompressedSize(val int) attribute.KeyValue { return MessageCompressedSizeKey.Int(val) } // MessageUncompressedSize returns an attribute KeyValue conforming to the // "message.uncompressed_size" semantic conventions. It represents the // uncompressed size of the message in bytes. func MessageUncompressedSize(val int) attribute.KeyValue { return MessageUncompressedSizeKey.Int(val) } // The attributes used to report a single exception associated with a span. const ( // ExceptionEscapedKey is the attribute Key conforming to the // "exception.escaped" semantic conventions. It represents the sHOULD be // set to true if the exception event is recorded at a point where it is // known that the exception is escaping the scope of the span. // // Type: boolean // RequirementLevel: Optional // Stability: stable // Note: An exception is considered to have escaped (or left) the scope of // a span, // if that span is ended while the exception is still logically "in // flight". // This may be actually "in flight" in some languages (e.g. if the // exception // is passed to a Context manager's `__exit__` method in Python) but will // usually be caught at the point of recording the exception in most // languages. // // It is usually not possible to determine at the point where an exception // is thrown // whether it will escape the scope of a span. // However, it is trivial to know that an exception // will escape, if one checks for an active exception just before ending // the span, // as done in the [example above](#recording-an-exception). // // It follows that an exception may still escape the scope of the span // even if the `exception.escaped` attribute was not set or set to false, // since the event might have been recorded at a time where it was not // clear whether the exception will escape. ExceptionEscapedKey = attribute.Key("exception.escaped") ) // ExceptionEscaped returns an attribute KeyValue conforming to the // "exception.escaped" semantic conventions. It represents the sHOULD be set to // true if the exception event is recorded at a point where it is known that // the exception is escaping the scope of the span. func ExceptionEscaped(val bool) attribute.KeyValue { return ExceptionEscapedKey.Bool(val) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/exception.go
vendor/go.opentelemetry.io/otel/semconv/v1.20.0/exception.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package semconv // import "go.opentelemetry.io/otel/semconv/v1.20.0" const ( // ExceptionEventName is the name of the Span event representing an exception. ExceptionEventName = "exception" )
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/doc.go
vendor/go.opentelemetry.io/otel/semconv/v1.20.0/doc.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 // Package semconv implements OpenTelemetry semantic conventions. // // OpenTelemetry semantic conventions are agreed standardized naming // patterns for OpenTelemetry things. This package represents the conventions // as of the v1.20.0 version of the OpenTelemetry specification. package semconv // import "go.opentelemetry.io/otel/semconv/v1.20.0"
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/semconv/v1.20.0/schema.go
vendor/go.opentelemetry.io/otel/semconv/v1.20.0/schema.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package semconv // import "go.opentelemetry.io/otel/semconv/v1.20.0" // SchemaURL is the schema URL that matches the version of the semantic conventions // that this package defines. Semconv packages starting from v1.4.0 must declare // non-empty schema URL in the form https://opentelemetry.io/schemas/<version> const SchemaURL = "https://opentelemetry.io/schemas/1.20.0"
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/metric.go
vendor/go.opentelemetry.io/otel/semconv/v1.24.0/metric.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 // Code generated from semantic convention specification. DO NOT EDIT. package semconv // import "go.opentelemetry.io/otel/semconv/v1.24.0" const ( // DBClientConnectionsUsage is the metric conforming to the // "db.client.connections.usage" semantic conventions. It represents the number // of connections that are currently in state described by the `state` // attribute. // Instrument: updowncounter // Unit: {connection} // Stability: Experimental DBClientConnectionsUsageName = "db.client.connections.usage" DBClientConnectionsUsageUnit = "{connection}" DBClientConnectionsUsageDescription = "The number of connections that are currently in state described by the `state` attribute" // DBClientConnectionsIdleMax is the metric conforming to the // "db.client.connections.idle.max" semantic conventions. It represents the // maximum number of idle open connections allowed. // Instrument: updowncounter // Unit: {connection} // Stability: Experimental DBClientConnectionsIdleMaxName = "db.client.connections.idle.max" DBClientConnectionsIdleMaxUnit = "{connection}" DBClientConnectionsIdleMaxDescription = "The maximum number of idle open connections allowed" // DBClientConnectionsIdleMin is the metric conforming to the // "db.client.connections.idle.min" semantic conventions. It represents the // minimum number of idle open connections allowed. // Instrument: updowncounter // Unit: {connection} // Stability: Experimental DBClientConnectionsIdleMinName = "db.client.connections.idle.min" DBClientConnectionsIdleMinUnit = "{connection}" DBClientConnectionsIdleMinDescription = "The minimum number of idle open connections allowed" // DBClientConnectionsMax is the metric conforming to the // "db.client.connections.max" semantic conventions. It represents the maximum // number of open connections allowed. // Instrument: updowncounter // Unit: {connection} // Stability: Experimental DBClientConnectionsMaxName = "db.client.connections.max" DBClientConnectionsMaxUnit = "{connection}" DBClientConnectionsMaxDescription = "The maximum number of open connections allowed" // DBClientConnectionsPendingRequests is the metric conforming to the // "db.client.connections.pending_requests" semantic conventions. It represents // the number of pending requests for an open connection, cumulative for the // entire pool. // Instrument: updowncounter // Unit: {request} // Stability: Experimental DBClientConnectionsPendingRequestsName = "db.client.connections.pending_requests" DBClientConnectionsPendingRequestsUnit = "{request}" DBClientConnectionsPendingRequestsDescription = "The number of pending requests for an open connection, cumulative for the entire pool" // DBClientConnectionsTimeouts is the metric conforming to the // "db.client.connections.timeouts" semantic conventions. It represents the // number of connection timeouts that have occurred trying to obtain a // connection from the pool. // Instrument: counter // Unit: {timeout} // Stability: Experimental DBClientConnectionsTimeoutsName = "db.client.connections.timeouts" DBClientConnectionsTimeoutsUnit = "{timeout}" DBClientConnectionsTimeoutsDescription = "The number of connection timeouts that have occurred trying to obtain a connection from the pool" // DBClientConnectionsCreateTime is the metric conforming to the // "db.client.connections.create_time" semantic conventions. It represents the // time it took to create a new connection. // Instrument: histogram // Unit: ms // Stability: Experimental DBClientConnectionsCreateTimeName = "db.client.connections.create_time" DBClientConnectionsCreateTimeUnit = "ms" DBClientConnectionsCreateTimeDescription = "The time it took to create a new connection" // DBClientConnectionsWaitTime is the metric conforming to the // "db.client.connections.wait_time" semantic conventions. It represents the // time it took to obtain an open connection from the pool. // Instrument: histogram // Unit: ms // Stability: Experimental DBClientConnectionsWaitTimeName = "db.client.connections.wait_time" DBClientConnectionsWaitTimeUnit = "ms" DBClientConnectionsWaitTimeDescription = "The time it took to obtain an open connection from the pool" // DBClientConnectionsUseTime is the metric conforming to the // "db.client.connections.use_time" semantic conventions. It represents the // time between borrowing a connection and returning it to the pool. // Instrument: histogram // Unit: ms // Stability: Experimental DBClientConnectionsUseTimeName = "db.client.connections.use_time" DBClientConnectionsUseTimeUnit = "ms" DBClientConnectionsUseTimeDescription = "The time between borrowing a connection and returning it to the pool" // AspnetcoreRoutingMatchAttempts is the metric conforming to the // "aspnetcore.routing.match_attempts" semantic conventions. It represents the // number of requests that were attempted to be matched to an endpoint. // Instrument: counter // Unit: {match_attempt} // Stability: Experimental AspnetcoreRoutingMatchAttemptsName = "aspnetcore.routing.match_attempts" AspnetcoreRoutingMatchAttemptsUnit = "{match_attempt}" AspnetcoreRoutingMatchAttemptsDescription = "Number of requests that were attempted to be matched to an endpoint." // AspnetcoreDiagnosticsExceptions is the metric conforming to the // "aspnetcore.diagnostics.exceptions" semantic conventions. It represents the // number of exceptions caught by exception handling middleware. // Instrument: counter // Unit: {exception} // Stability: Experimental AspnetcoreDiagnosticsExceptionsName = "aspnetcore.diagnostics.exceptions" AspnetcoreDiagnosticsExceptionsUnit = "{exception}" AspnetcoreDiagnosticsExceptionsDescription = "Number of exceptions caught by exception handling middleware." // AspnetcoreRateLimitingActiveRequestLeases is the metric conforming to the // "aspnetcore.rate_limiting.active_request_leases" semantic conventions. It // represents the number of requests that are currently active on the server // that hold a rate limiting lease. // Instrument: updowncounter // Unit: {request} // Stability: Experimental AspnetcoreRateLimitingActiveRequestLeasesName = "aspnetcore.rate_limiting.active_request_leases" AspnetcoreRateLimitingActiveRequestLeasesUnit = "{request}" AspnetcoreRateLimitingActiveRequestLeasesDescription = "Number of requests that are currently active on the server that hold a rate limiting lease." // AspnetcoreRateLimitingRequestLeaseDuration is the metric conforming to the // "aspnetcore.rate_limiting.request_lease.duration" semantic conventions. It // represents the duration of rate limiting lease held by requests on the // server. // Instrument: histogram // Unit: s // Stability: Experimental AspnetcoreRateLimitingRequestLeaseDurationName = "aspnetcore.rate_limiting.request_lease.duration" AspnetcoreRateLimitingRequestLeaseDurationUnit = "s" AspnetcoreRateLimitingRequestLeaseDurationDescription = "The duration of rate limiting lease held by requests on the server." // AspnetcoreRateLimitingRequestTimeInQueue is the metric conforming to the // "aspnetcore.rate_limiting.request.time_in_queue" semantic conventions. It // represents the time the request spent in a queue waiting to acquire a rate // limiting lease. // Instrument: histogram // Unit: s // Stability: Experimental AspnetcoreRateLimitingRequestTimeInQueueName = "aspnetcore.rate_limiting.request.time_in_queue" AspnetcoreRateLimitingRequestTimeInQueueUnit = "s" AspnetcoreRateLimitingRequestTimeInQueueDescription = "The time the request spent in a queue waiting to acquire a rate limiting lease." // AspnetcoreRateLimitingQueuedRequests is the metric conforming to the // "aspnetcore.rate_limiting.queued_requests" semantic conventions. It // represents the number of requests that are currently queued, waiting to // acquire a rate limiting lease. // Instrument: updowncounter // Unit: {request} // Stability: Experimental AspnetcoreRateLimitingQueuedRequestsName = "aspnetcore.rate_limiting.queued_requests" AspnetcoreRateLimitingQueuedRequestsUnit = "{request}" AspnetcoreRateLimitingQueuedRequestsDescription = "Number of requests that are currently queued, waiting to acquire a rate limiting lease." // AspnetcoreRateLimitingRequests is the metric conforming to the // "aspnetcore.rate_limiting.requests" semantic conventions. It represents the // number of requests that tried to acquire a rate limiting lease. // Instrument: counter // Unit: {request} // Stability: Experimental AspnetcoreRateLimitingRequestsName = "aspnetcore.rate_limiting.requests" AspnetcoreRateLimitingRequestsUnit = "{request}" AspnetcoreRateLimitingRequestsDescription = "Number of requests that tried to acquire a rate limiting lease." // DNSLookupDuration is the metric conforming to the "dns.lookup.duration" // semantic conventions. It represents the measures the time taken to perform a // DNS lookup. // Instrument: histogram // Unit: s // Stability: Experimental DNSLookupDurationName = "dns.lookup.duration" DNSLookupDurationUnit = "s" DNSLookupDurationDescription = "Measures the time taken to perform a DNS lookup." // HTTPClientOpenConnections is the metric conforming to the // "http.client.open_connections" semantic conventions. It represents the // number of outbound HTTP connections that are currently active or idle on the // client. // Instrument: updowncounter // Unit: {connection} // Stability: Experimental HTTPClientOpenConnectionsName = "http.client.open_connections" HTTPClientOpenConnectionsUnit = "{connection}" HTTPClientOpenConnectionsDescription = "Number of outbound HTTP connections that are currently active or idle on the client." // HTTPClientConnectionDuration is the metric conforming to the // "http.client.connection.duration" semantic conventions. It represents the // duration of the successfully established outbound HTTP connections. // Instrument: histogram // Unit: s // Stability: Experimental HTTPClientConnectionDurationName = "http.client.connection.duration" HTTPClientConnectionDurationUnit = "s" HTTPClientConnectionDurationDescription = "The duration of the successfully established outbound HTTP connections." // HTTPClientActiveRequests is the metric conforming to the // "http.client.active_requests" semantic conventions. It represents the number // of active HTTP requests. // Instrument: updowncounter // Unit: {request} // Stability: Experimental HTTPClientActiveRequestsName = "http.client.active_requests" HTTPClientActiveRequestsUnit = "{request}" HTTPClientActiveRequestsDescription = "Number of active HTTP requests." // HTTPClientRequestTimeInQueue is the metric conforming to the // "http.client.request.time_in_queue" semantic conventions. It represents the // amount of time requests spent on a queue waiting for an available // connection. // Instrument: histogram // Unit: s // Stability: Experimental HTTPClientRequestTimeInQueueName = "http.client.request.time_in_queue" HTTPClientRequestTimeInQueueUnit = "s" HTTPClientRequestTimeInQueueDescription = "The amount of time requests spent on a queue waiting for an available connection." // KestrelActiveConnections is the metric conforming to the // "kestrel.active_connections" semantic conventions. It represents the number // of connections that are currently active on the server. // Instrument: updowncounter // Unit: {connection} // Stability: Experimental KestrelActiveConnectionsName = "kestrel.active_connections" KestrelActiveConnectionsUnit = "{connection}" KestrelActiveConnectionsDescription = "Number of connections that are currently active on the server." // KestrelConnectionDuration is the metric conforming to the // "kestrel.connection.duration" semantic conventions. It represents the // duration of connections on the server. // Instrument: histogram // Unit: s // Stability: Experimental KestrelConnectionDurationName = "kestrel.connection.duration" KestrelConnectionDurationUnit = "s" KestrelConnectionDurationDescription = "The duration of connections on the server." // KestrelRejectedConnections is the metric conforming to the // "kestrel.rejected_connections" semantic conventions. It represents the // number of connections rejected by the server. // Instrument: counter // Unit: {connection} // Stability: Experimental KestrelRejectedConnectionsName = "kestrel.rejected_connections" KestrelRejectedConnectionsUnit = "{connection}" KestrelRejectedConnectionsDescription = "Number of connections rejected by the server." // KestrelQueuedConnections is the metric conforming to the // "kestrel.queued_connections" semantic conventions. It represents the number // of connections that are currently queued and are waiting to start. // Instrument: updowncounter // Unit: {connection} // Stability: Experimental KestrelQueuedConnectionsName = "kestrel.queued_connections" KestrelQueuedConnectionsUnit = "{connection}" KestrelQueuedConnectionsDescription = "Number of connections that are currently queued and are waiting to start." // KestrelQueuedRequests is the metric conforming to the // "kestrel.queued_requests" semantic conventions. It represents the number of // HTTP requests on multiplexed connections (HTTP/2 and HTTP/3) that are // currently queued and are waiting to start. // Instrument: updowncounter // Unit: {request} // Stability: Experimental KestrelQueuedRequestsName = "kestrel.queued_requests" KestrelQueuedRequestsUnit = "{request}" KestrelQueuedRequestsDescription = "Number of HTTP requests on multiplexed connections (HTTP/2 and HTTP/3) that are currently queued and are waiting to start." // KestrelUpgradedConnections is the metric conforming to the // "kestrel.upgraded_connections" semantic conventions. It represents the // number of connections that are currently upgraded (WebSockets). . // Instrument: updowncounter // Unit: {connection} // Stability: Experimental KestrelUpgradedConnectionsName = "kestrel.upgraded_connections" KestrelUpgradedConnectionsUnit = "{connection}" KestrelUpgradedConnectionsDescription = "Number of connections that are currently upgraded (WebSockets). ." // KestrelTLSHandshakeDuration is the metric conforming to the // "kestrel.tls_handshake.duration" semantic conventions. It represents the // duration of TLS handshakes on the server. // Instrument: histogram // Unit: s // Stability: Experimental KestrelTLSHandshakeDurationName = "kestrel.tls_handshake.duration" KestrelTLSHandshakeDurationUnit = "s" KestrelTLSHandshakeDurationDescription = "The duration of TLS handshakes on the server." // KestrelActiveTLSHandshakes is the metric conforming to the // "kestrel.active_tls_handshakes" semantic conventions. It represents the // number of TLS handshakes that are currently in progress on the server. // Instrument: updowncounter // Unit: {handshake} // Stability: Experimental KestrelActiveTLSHandshakesName = "kestrel.active_tls_handshakes" KestrelActiveTLSHandshakesUnit = "{handshake}" KestrelActiveTLSHandshakesDescription = "Number of TLS handshakes that are currently in progress on the server." // SignalrServerConnectionDuration is the metric conforming to the // "signalr.server.connection.duration" semantic conventions. It represents the // duration of connections on the server. // Instrument: histogram // Unit: s // Stability: Experimental SignalrServerConnectionDurationName = "signalr.server.connection.duration" SignalrServerConnectionDurationUnit = "s" SignalrServerConnectionDurationDescription = "The duration of connections on the server." // SignalrServerActiveConnections is the metric conforming to the // "signalr.server.active_connections" semantic conventions. It represents the // number of connections that are currently active on the server. // Instrument: updowncounter // Unit: {connection} // Stability: Experimental SignalrServerActiveConnectionsName = "signalr.server.active_connections" SignalrServerActiveConnectionsUnit = "{connection}" SignalrServerActiveConnectionsDescription = "Number of connections that are currently active on the server." // FaaSInvokeDuration is the metric conforming to the "faas.invoke_duration" // semantic conventions. It represents the measures the duration of the // function's logic execution. // Instrument: histogram // Unit: s // Stability: Experimental FaaSInvokeDurationName = "faas.invoke_duration" FaaSInvokeDurationUnit = "s" FaaSInvokeDurationDescription = "Measures the duration of the function's logic execution" // FaaSInitDuration is the metric conforming to the "faas.init_duration" // semantic conventions. It represents the measures the duration of the // function's initialization, such as a cold start. // Instrument: histogram // Unit: s // Stability: Experimental FaaSInitDurationName = "faas.init_duration" FaaSInitDurationUnit = "s" FaaSInitDurationDescription = "Measures the duration of the function's initialization, such as a cold start" // FaaSColdstarts is the metric conforming to the "faas.coldstarts" semantic // conventions. It represents the number of invocation cold starts. // Instrument: counter // Unit: {coldstart} // Stability: Experimental FaaSColdstartsName = "faas.coldstarts" FaaSColdstartsUnit = "{coldstart}" FaaSColdstartsDescription = "Number of invocation cold starts" // FaaSErrors is the metric conforming to the "faas.errors" semantic // conventions. It represents the number of invocation errors. // Instrument: counter // Unit: {error} // Stability: Experimental FaaSErrorsName = "faas.errors" FaaSErrorsUnit = "{error}" FaaSErrorsDescription = "Number of invocation errors" // FaaSInvocations is the metric conforming to the "faas.invocations" semantic // conventions. It represents the number of successful invocations. // Instrument: counter // Unit: {invocation} // Stability: Experimental FaaSInvocationsName = "faas.invocations" FaaSInvocationsUnit = "{invocation}" FaaSInvocationsDescription = "Number of successful invocations" // FaaSTimeouts is the metric conforming to the "faas.timeouts" semantic // conventions. It represents the number of invocation timeouts. // Instrument: counter // Unit: {timeout} // Stability: Experimental FaaSTimeoutsName = "faas.timeouts" FaaSTimeoutsUnit = "{timeout}" FaaSTimeoutsDescription = "Number of invocation timeouts" // FaaSMemUsage is the metric conforming to the "faas.mem_usage" semantic // conventions. It represents the distribution of max memory usage per // invocation. // Instrument: histogram // Unit: By // Stability: Experimental FaaSMemUsageName = "faas.mem_usage" FaaSMemUsageUnit = "By" FaaSMemUsageDescription = "Distribution of max memory usage per invocation" // FaaSCPUUsage is the metric conforming to the "faas.cpu_usage" semantic // conventions. It represents the distribution of CPU usage per invocation. // Instrument: histogram // Unit: s // Stability: Experimental FaaSCPUUsageName = "faas.cpu_usage" FaaSCPUUsageUnit = "s" FaaSCPUUsageDescription = "Distribution of CPU usage per invocation" // FaaSNetIo is the metric conforming to the "faas.net_io" semantic // conventions. It represents the distribution of net I/O usage per invocation. // Instrument: histogram // Unit: By // Stability: Experimental FaaSNetIoName = "faas.net_io" FaaSNetIoUnit = "By" FaaSNetIoDescription = "Distribution of net I/O usage per invocation" // HTTPServerRequestDuration is the metric conforming to the // "http.server.request.duration" semantic conventions. It represents the // duration of HTTP server requests. // Instrument: histogram // Unit: s // Stability: Stable HTTPServerRequestDurationName = "http.server.request.duration" HTTPServerRequestDurationUnit = "s" HTTPServerRequestDurationDescription = "Duration of HTTP server requests." // HTTPServerActiveRequests is the metric conforming to the // "http.server.active_requests" semantic conventions. It represents the number // of active HTTP server requests. // Instrument: updowncounter // Unit: {request} // Stability: Experimental HTTPServerActiveRequestsName = "http.server.active_requests" HTTPServerActiveRequestsUnit = "{request}" HTTPServerActiveRequestsDescription = "Number of active HTTP server requests." // HTTPServerRequestBodySize is the metric conforming to the // "http.server.request.body.size" semantic conventions. It represents the size // of HTTP server request bodies. // Instrument: histogram // Unit: By // Stability: Experimental HTTPServerRequestBodySizeName = "http.server.request.body.size" HTTPServerRequestBodySizeUnit = "By" HTTPServerRequestBodySizeDescription = "Size of HTTP server request bodies." // HTTPServerResponseBodySize is the metric conforming to the // "http.server.response.body.size" semantic conventions. It represents the // size of HTTP server response bodies. // Instrument: histogram // Unit: By // Stability: Experimental HTTPServerResponseBodySizeName = "http.server.response.body.size" HTTPServerResponseBodySizeUnit = "By" HTTPServerResponseBodySizeDescription = "Size of HTTP server response bodies." // HTTPClientRequestDuration is the metric conforming to the // "http.client.request.duration" semantic conventions. It represents the // duration of HTTP client requests. // Instrument: histogram // Unit: s // Stability: Stable HTTPClientRequestDurationName = "http.client.request.duration" HTTPClientRequestDurationUnit = "s" HTTPClientRequestDurationDescription = "Duration of HTTP client requests." // HTTPClientRequestBodySize is the metric conforming to the // "http.client.request.body.size" semantic conventions. It represents the size // of HTTP client request bodies. // Instrument: histogram // Unit: By // Stability: Experimental HTTPClientRequestBodySizeName = "http.client.request.body.size" HTTPClientRequestBodySizeUnit = "By" HTTPClientRequestBodySizeDescription = "Size of HTTP client request bodies." // HTTPClientResponseBodySize is the metric conforming to the // "http.client.response.body.size" semantic conventions. It represents the // size of HTTP client response bodies. // Instrument: histogram // Unit: By // Stability: Experimental HTTPClientResponseBodySizeName = "http.client.response.body.size" HTTPClientResponseBodySizeUnit = "By" HTTPClientResponseBodySizeDescription = "Size of HTTP client response bodies." // JvmMemoryInit is the metric conforming to the "jvm.memory.init" semantic // conventions. It represents the measure of initial memory requested. // Instrument: updowncounter // Unit: By // Stability: Experimental JvmMemoryInitName = "jvm.memory.init" JvmMemoryInitUnit = "By" JvmMemoryInitDescription = "Measure of initial memory requested." // JvmSystemCPUUtilization is the metric conforming to the // "jvm.system.cpu.utilization" semantic conventions. It represents the recent // CPU utilization for the whole system as reported by the JVM. // Instrument: gauge // Unit: 1 // Stability: Experimental JvmSystemCPUUtilizationName = "jvm.system.cpu.utilization" JvmSystemCPUUtilizationUnit = "1" JvmSystemCPUUtilizationDescription = "Recent CPU utilization for the whole system as reported by the JVM." // JvmSystemCPULoad1m is the metric conforming to the "jvm.system.cpu.load_1m" // semantic conventions. It represents the average CPU load of the whole system // for the last minute as reported by the JVM. // Instrument: gauge // Unit: {run_queue_item} // Stability: Experimental JvmSystemCPULoad1mName = "jvm.system.cpu.load_1m" JvmSystemCPULoad1mUnit = "{run_queue_item}" JvmSystemCPULoad1mDescription = "Average CPU load of the whole system for the last minute as reported by the JVM." // JvmBufferMemoryUsage is the metric conforming to the // "jvm.buffer.memory.usage" semantic conventions. It represents the measure of // memory used by buffers. // Instrument: updowncounter // Unit: By // Stability: Experimental JvmBufferMemoryUsageName = "jvm.buffer.memory.usage" JvmBufferMemoryUsageUnit = "By" JvmBufferMemoryUsageDescription = "Measure of memory used by buffers." // JvmBufferMemoryLimit is the metric conforming to the // "jvm.buffer.memory.limit" semantic conventions. It represents the measure of // total memory capacity of buffers. // Instrument: updowncounter // Unit: By // Stability: Experimental JvmBufferMemoryLimitName = "jvm.buffer.memory.limit" JvmBufferMemoryLimitUnit = "By" JvmBufferMemoryLimitDescription = "Measure of total memory capacity of buffers." // JvmBufferCount is the metric conforming to the "jvm.buffer.count" semantic // conventions. It represents the number of buffers in the pool. // Instrument: updowncounter // Unit: {buffer} // Stability: Experimental JvmBufferCountName = "jvm.buffer.count" JvmBufferCountUnit = "{buffer}" JvmBufferCountDescription = "Number of buffers in the pool." // JvmMemoryUsed is the metric conforming to the "jvm.memory.used" semantic // conventions. It represents the measure of memory used. // Instrument: updowncounter // Unit: By // Stability: Stable JvmMemoryUsedName = "jvm.memory.used" JvmMemoryUsedUnit = "By" JvmMemoryUsedDescription = "Measure of memory used." // JvmMemoryCommitted is the metric conforming to the "jvm.memory.committed" // semantic conventions. It represents the measure of memory committed. // Instrument: updowncounter // Unit: By // Stability: Stable JvmMemoryCommittedName = "jvm.memory.committed" JvmMemoryCommittedUnit = "By" JvmMemoryCommittedDescription = "Measure of memory committed." // JvmMemoryLimit is the metric conforming to the "jvm.memory.limit" semantic // conventions. It represents the measure of max obtainable memory. // Instrument: updowncounter // Unit: By // Stability: Stable JvmMemoryLimitName = "jvm.memory.limit" JvmMemoryLimitUnit = "By" JvmMemoryLimitDescription = "Measure of max obtainable memory." // JvmMemoryUsedAfterLastGc is the metric conforming to the // "jvm.memory.used_after_last_gc" semantic conventions. It represents the // measure of memory used, as measured after the most recent garbage collection // event on this pool. // Instrument: updowncounter // Unit: By // Stability: Stable JvmMemoryUsedAfterLastGcName = "jvm.memory.used_after_last_gc" JvmMemoryUsedAfterLastGcUnit = "By" JvmMemoryUsedAfterLastGcDescription = "Measure of memory used, as measured after the most recent garbage collection event on this pool." // JvmGcDuration is the metric conforming to the "jvm.gc.duration" semantic // conventions. It represents the duration of JVM garbage collection actions. // Instrument: histogram // Unit: s // Stability: Stable JvmGcDurationName = "jvm.gc.duration" JvmGcDurationUnit = "s" JvmGcDurationDescription = "Duration of JVM garbage collection actions." // JvmThreadCount is the metric conforming to the "jvm.thread.count" semantic // conventions. It represents the number of executing platform threads. // Instrument: updowncounter // Unit: {thread} // Stability: Stable JvmThreadCountName = "jvm.thread.count" JvmThreadCountUnit = "{thread}" JvmThreadCountDescription = "Number of executing platform threads." // JvmClassLoaded is the metric conforming to the "jvm.class.loaded" semantic // conventions. It represents the number of classes loaded since JVM start. // Instrument: counter // Unit: {class} // Stability: Stable JvmClassLoadedName = "jvm.class.loaded" JvmClassLoadedUnit = "{class}" JvmClassLoadedDescription = "Number of classes loaded since JVM start." // JvmClassUnloaded is the metric conforming to the "jvm.class.unloaded" // semantic conventions. It represents the number of classes unloaded since JVM // start. // Instrument: counter // Unit: {class} // Stability: Stable JvmClassUnloadedName = "jvm.class.unloaded" JvmClassUnloadedUnit = "{class}" JvmClassUnloadedDescription = "Number of classes unloaded since JVM start." // JvmClassCount is the metric conforming to the "jvm.class.count" semantic // conventions. It represents the number of classes currently loaded. // Instrument: updowncounter // Unit: {class} // Stability: Stable JvmClassCountName = "jvm.class.count" JvmClassCountUnit = "{class}" JvmClassCountDescription = "Number of classes currently loaded." // JvmCPUCount is the metric conforming to the "jvm.cpu.count" semantic // conventions. It represents the number of processors available to the Java // virtual machine. // Instrument: updowncounter // Unit: {cpu} // Stability: Stable JvmCPUCountName = "jvm.cpu.count" JvmCPUCountUnit = "{cpu}" JvmCPUCountDescription = "Number of processors available to the Java virtual machine." // JvmCPUTime is the metric conforming to the "jvm.cpu.time" semantic // conventions. It represents the cPU time used by the process as reported by // the JVM. // Instrument: counter // Unit: s // Stability: Stable JvmCPUTimeName = "jvm.cpu.time" JvmCPUTimeUnit = "s" JvmCPUTimeDescription = "CPU time used by the process as reported by the JVM." // JvmCPURecentUtilization is the metric conforming to the // "jvm.cpu.recent_utilization" semantic conventions. It represents the recent // CPU utilization for the process as reported by the JVM. // Instrument: gauge // Unit: 1 // Stability: Stable JvmCPURecentUtilizationName = "jvm.cpu.recent_utilization" JvmCPURecentUtilizationUnit = "1" JvmCPURecentUtilizationDescription = "Recent CPU utilization for the process as reported by the JVM." // MessagingPublishDuration is the metric conforming to the // "messaging.publish.duration" semantic conventions. It represents the // measures the duration of publish operation. // Instrument: histogram // Unit: s // Stability: Experimental MessagingPublishDurationName = "messaging.publish.duration" MessagingPublishDurationUnit = "s" MessagingPublishDurationDescription = "Measures the duration of publish operation." // MessagingReceiveDuration is the metric conforming to the // "messaging.receive.duration" semantic conventions. It represents the // measures the duration of receive operation. // Instrument: histogram // Unit: s // Stability: Experimental MessagingReceiveDurationName = "messaging.receive.duration" MessagingReceiveDurationUnit = "s" MessagingReceiveDurationDescription = "Measures the duration of receive operation." // MessagingDeliverDuration is the metric conforming to the // "messaging.deliver.duration" semantic conventions. It represents the // measures the duration of deliver operation. // Instrument: histogram // Unit: s // Stability: Experimental MessagingDeliverDurationName = "messaging.deliver.duration" MessagingDeliverDurationUnit = "s" MessagingDeliverDurationDescription = "Measures the duration of deliver operation." // MessagingPublishMessages is the metric conforming to the // "messaging.publish.messages" semantic conventions. It represents the // measures the number of published messages. // Instrument: counter // Unit: {message} // Stability: Experimental MessagingPublishMessagesName = "messaging.publish.messages" MessagingPublishMessagesUnit = "{message}" MessagingPublishMessagesDescription = "Measures the number of published messages." // MessagingReceiveMessages is the metric conforming to the // "messaging.receive.messages" semantic conventions. It represents the // measures the number of received messages. // Instrument: counter // Unit: {message} // Stability: Experimental MessagingReceiveMessagesName = "messaging.receive.messages"
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
true
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/attribute_group.go
vendor/go.opentelemetry.io/otel/semconv/v1.24.0/attribute_group.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 // Code generated from semantic convention specification. DO NOT EDIT. package semconv // import "go.opentelemetry.io/otel/semconv/v1.24.0" import "go.opentelemetry.io/otel/attribute" // Describes FaaS attributes. const ( // FaaSInvokedNameKey is the attribute Key conforming to the // "faas.invoked_name" semantic conventions. It represents the name of the // invoked function. // // Type: string // RequirementLevel: Required // Stability: experimental // Examples: 'my-function' // Note: SHOULD be equal to the `faas.name` resource attribute of the // invoked function. FaaSInvokedNameKey = attribute.Key("faas.invoked_name") // FaaSInvokedProviderKey is the attribute Key conforming to the // "faas.invoked_provider" semantic conventions. It represents the cloud // provider of the invoked function. // // Type: Enum // RequirementLevel: Required // Stability: experimental // Note: SHOULD be equal to the `cloud.provider` resource attribute of the // invoked function. FaaSInvokedProviderKey = attribute.Key("faas.invoked_provider") // FaaSInvokedRegionKey is the attribute Key conforming to the // "faas.invoked_region" semantic conventions. It represents the cloud // region of the invoked function. // // Type: string // RequirementLevel: ConditionallyRequired (For some cloud providers, like // AWS or GCP, the region in which a function is hosted is essential to // uniquely identify the function and also part of its endpoint. Since it's // part of the endpoint being called, the region is always known to // clients. In these cases, `faas.invoked_region` MUST be set accordingly. // If the region is unknown to the client or not required for identifying // the invoked function, setting `faas.invoked_region` is optional.) // Stability: experimental // Examples: 'eu-central-1' // Note: SHOULD be equal to the `cloud.region` resource attribute of the // invoked function. FaaSInvokedRegionKey = attribute.Key("faas.invoked_region") // FaaSTriggerKey is the attribute Key conforming to the "faas.trigger" // semantic conventions. It represents the type of the trigger which caused // this function invocation. // // Type: Enum // RequirementLevel: Optional // Stability: experimental FaaSTriggerKey = attribute.Key("faas.trigger") ) var ( // Alibaba Cloud FaaSInvokedProviderAlibabaCloud = FaaSInvokedProviderKey.String("alibaba_cloud") // Amazon Web Services FaaSInvokedProviderAWS = FaaSInvokedProviderKey.String("aws") // Microsoft Azure FaaSInvokedProviderAzure = FaaSInvokedProviderKey.String("azure") // Google Cloud Platform FaaSInvokedProviderGCP = FaaSInvokedProviderKey.String("gcp") // Tencent Cloud FaaSInvokedProviderTencentCloud = FaaSInvokedProviderKey.String("tencent_cloud") ) var ( // A response to some data source operation such as a database or filesystem read/write FaaSTriggerDatasource = FaaSTriggerKey.String("datasource") // To provide an answer to an inbound HTTP request FaaSTriggerHTTP = FaaSTriggerKey.String("http") // A function is set to be executed when messages are sent to a messaging system FaaSTriggerPubsub = FaaSTriggerKey.String("pubsub") // A function is scheduled to be executed regularly FaaSTriggerTimer = FaaSTriggerKey.String("timer") // If none of the others apply FaaSTriggerOther = FaaSTriggerKey.String("other") ) // FaaSInvokedName returns an attribute KeyValue conforming to the // "faas.invoked_name" semantic conventions. It represents the name of the // invoked function. func FaaSInvokedName(val string) attribute.KeyValue { return FaaSInvokedNameKey.String(val) } // FaaSInvokedRegion returns an attribute KeyValue conforming to the // "faas.invoked_region" semantic conventions. It represents the cloud region // of the invoked function. func FaaSInvokedRegion(val string) attribute.KeyValue { return FaaSInvokedRegionKey.String(val) } // Attributes for Events represented using Log Records. const ( // EventNameKey is the attribute Key conforming to the "event.name" // semantic conventions. It represents the identifies the class / type of // event. // // Type: string // RequirementLevel: Required // Stability: experimental // Examples: 'browser.mouse.click', 'device.app.lifecycle' // Note: Event names are subject to the same rules as [attribute // names](https://github.com/open-telemetry/opentelemetry-specification/tree/v1.26.0/specification/common/attribute-naming.md). // Notably, event names are namespaced to avoid collisions and provide a // clean separation of semantics for events in separate domains like // browser, mobile, and kubernetes. EventNameKey = attribute.Key("event.name") ) // EventName returns an attribute KeyValue conforming to the "event.name" // semantic conventions. It represents the identifies the class / type of // event. func EventName(val string) attribute.KeyValue { return EventNameKey.String(val) } // The attributes described in this section are rather generic. They may be // used in any Log Record they apply to. const ( // LogRecordUIDKey is the attribute Key conforming to the "log.record.uid" // semantic conventions. It represents a unique identifier for the Log // Record. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: '01ARZ3NDEKTSV4RRFFQ69G5FAV' // Note: If an id is provided, other log records with the same id will be // considered duplicates and can be removed safely. This means, that two // distinguishable log records MUST have different values. // The id MAY be an [Universally Unique Lexicographically Sortable // Identifier (ULID)](https://github.com/ulid/spec), but other identifiers // (e.g. UUID) may be used as needed. LogRecordUIDKey = attribute.Key("log.record.uid") ) // LogRecordUID returns an attribute KeyValue conforming to the // "log.record.uid" semantic conventions. It represents a unique identifier for // the Log Record. func LogRecordUID(val string) attribute.KeyValue { return LogRecordUIDKey.String(val) } // Describes Log attributes const ( // LogIostreamKey is the attribute Key conforming to the "log.iostream" // semantic conventions. It represents the stream associated with the log. // See below for a list of well-known values. // // Type: Enum // RequirementLevel: Optional // Stability: experimental LogIostreamKey = attribute.Key("log.iostream") ) var ( // Logs from stdout stream LogIostreamStdout = LogIostreamKey.String("stdout") // Events from stderr stream LogIostreamStderr = LogIostreamKey.String("stderr") ) // A file to which log was emitted. const ( // LogFileNameKey is the attribute Key conforming to the "log.file.name" // semantic conventions. It represents the basename of the file. // // Type: string // RequirementLevel: Recommended // Stability: experimental // Examples: 'audit.log' LogFileNameKey = attribute.Key("log.file.name") // LogFileNameResolvedKey is the attribute Key conforming to the // "log.file.name_resolved" semantic conventions. It represents the // basename of the file, with symlinks resolved. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'uuid.log' LogFileNameResolvedKey = attribute.Key("log.file.name_resolved") // LogFilePathKey is the attribute Key conforming to the "log.file.path" // semantic conventions. It represents the full path to the file. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: '/var/log/mysql/audit.log' LogFilePathKey = attribute.Key("log.file.path") // LogFilePathResolvedKey is the attribute Key conforming to the // "log.file.path_resolved" semantic conventions. It represents the full // path to the file, with symlinks resolved. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: '/var/lib/docker/uuid.log' LogFilePathResolvedKey = attribute.Key("log.file.path_resolved") ) // LogFileName returns an attribute KeyValue conforming to the // "log.file.name" semantic conventions. It represents the basename of the // file. func LogFileName(val string) attribute.KeyValue { return LogFileNameKey.String(val) } // LogFileNameResolved returns an attribute KeyValue conforming to the // "log.file.name_resolved" semantic conventions. It represents the basename of // the file, with symlinks resolved. func LogFileNameResolved(val string) attribute.KeyValue { return LogFileNameResolvedKey.String(val) } // LogFilePath returns an attribute KeyValue conforming to the // "log.file.path" semantic conventions. It represents the full path to the // file. func LogFilePath(val string) attribute.KeyValue { return LogFilePathKey.String(val) } // LogFilePathResolved returns an attribute KeyValue conforming to the // "log.file.path_resolved" semantic conventions. It represents the full path // to the file, with symlinks resolved. func LogFilePathResolved(val string) attribute.KeyValue { return LogFilePathResolvedKey.String(val) } // Describes Database attributes const ( // PoolNameKey is the attribute Key conforming to the "pool.name" semantic // conventions. It represents the name of the connection pool; unique // within the instrumented application. In case the connection pool // implementation doesn't provide a name, then the // [db.connection_string](/docs/database/database-spans.md#connection-level-attributes) // should be used // // Type: string // RequirementLevel: Required // Stability: experimental // Examples: 'myDataSource' PoolNameKey = attribute.Key("pool.name") // StateKey is the attribute Key conforming to the "state" semantic // conventions. It represents the state of a connection in the pool // // Type: Enum // RequirementLevel: Required // Stability: experimental // Examples: 'idle' StateKey = attribute.Key("state") ) var ( // idle StateIdle = StateKey.String("idle") // used StateUsed = StateKey.String("used") ) // PoolName returns an attribute KeyValue conforming to the "pool.name" // semantic conventions. It represents the name of the connection pool; unique // within the instrumented application. In case the connection pool // implementation doesn't provide a name, then the // [db.connection_string](/docs/database/database-spans.md#connection-level-attributes) // should be used func PoolName(val string) attribute.KeyValue { return PoolNameKey.String(val) } // ASP.NET Core attributes const ( // AspnetcoreDiagnosticsHandlerTypeKey is the attribute Key conforming to // the "aspnetcore.diagnostics.handler.type" semantic conventions. It // represents the full type name of the // [`IExceptionHandler`](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.diagnostics.iexceptionhandler) // implementation that handled the exception. // // Type: string // RequirementLevel: ConditionallyRequired (if and only if the exception // was handled by this handler.) // Stability: experimental // Examples: 'Contoso.MyHandler' AspnetcoreDiagnosticsHandlerTypeKey = attribute.Key("aspnetcore.diagnostics.handler.type") // AspnetcoreRateLimitingPolicyKey is the attribute Key conforming to the // "aspnetcore.rate_limiting.policy" semantic conventions. It represents // the rate limiting policy name. // // Type: string // RequirementLevel: ConditionallyRequired (if the matched endpoint for the // request had a rate-limiting policy.) // Stability: experimental // Examples: 'fixed', 'sliding', 'token' AspnetcoreRateLimitingPolicyKey = attribute.Key("aspnetcore.rate_limiting.policy") // AspnetcoreRateLimitingResultKey is the attribute Key conforming to the // "aspnetcore.rate_limiting.result" semantic conventions. It represents // the rate-limiting result, shows whether the lease was acquired or // contains a rejection reason // // Type: Enum // RequirementLevel: Required // Stability: experimental // Examples: 'acquired', 'request_canceled' AspnetcoreRateLimitingResultKey = attribute.Key("aspnetcore.rate_limiting.result") // AspnetcoreRequestIsUnhandledKey is the attribute Key conforming to the // "aspnetcore.request.is_unhandled" semantic conventions. It represents // the flag indicating if request was handled by the application pipeline. // // Type: boolean // RequirementLevel: ConditionallyRequired (if and only if the request was // not handled.) // Stability: experimental // Examples: True AspnetcoreRequestIsUnhandledKey = attribute.Key("aspnetcore.request.is_unhandled") // AspnetcoreRoutingIsFallbackKey is the attribute Key conforming to the // "aspnetcore.routing.is_fallback" semantic conventions. It represents a // value that indicates whether the matched route is a fallback route. // // Type: boolean // RequirementLevel: ConditionallyRequired (If and only if a route was // successfully matched.) // Stability: experimental // Examples: True AspnetcoreRoutingIsFallbackKey = attribute.Key("aspnetcore.routing.is_fallback") ) var ( // Lease was acquired AspnetcoreRateLimitingResultAcquired = AspnetcoreRateLimitingResultKey.String("acquired") // Lease request was rejected by the endpoint limiter AspnetcoreRateLimitingResultEndpointLimiter = AspnetcoreRateLimitingResultKey.String("endpoint_limiter") // Lease request was rejected by the global limiter AspnetcoreRateLimitingResultGlobalLimiter = AspnetcoreRateLimitingResultKey.String("global_limiter") // Lease request was canceled AspnetcoreRateLimitingResultRequestCanceled = AspnetcoreRateLimitingResultKey.String("request_canceled") ) // AspnetcoreDiagnosticsHandlerType returns an attribute KeyValue conforming // to the "aspnetcore.diagnostics.handler.type" semantic conventions. It // represents the full type name of the // [`IExceptionHandler`](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.diagnostics.iexceptionhandler) // implementation that handled the exception. func AspnetcoreDiagnosticsHandlerType(val string) attribute.KeyValue { return AspnetcoreDiagnosticsHandlerTypeKey.String(val) } // AspnetcoreRateLimitingPolicy returns an attribute KeyValue conforming to // the "aspnetcore.rate_limiting.policy" semantic conventions. It represents // the rate limiting policy name. func AspnetcoreRateLimitingPolicy(val string) attribute.KeyValue { return AspnetcoreRateLimitingPolicyKey.String(val) } // AspnetcoreRequestIsUnhandled returns an attribute KeyValue conforming to // the "aspnetcore.request.is_unhandled" semantic conventions. It represents // the flag indicating if request was handled by the application pipeline. func AspnetcoreRequestIsUnhandled(val bool) attribute.KeyValue { return AspnetcoreRequestIsUnhandledKey.Bool(val) } // AspnetcoreRoutingIsFallback returns an attribute KeyValue conforming to // the "aspnetcore.routing.is_fallback" semantic conventions. It represents a // value that indicates whether the matched route is a fallback route. func AspnetcoreRoutingIsFallback(val bool) attribute.KeyValue { return AspnetcoreRoutingIsFallbackKey.Bool(val) } // SignalR attributes const ( // SignalrConnectionStatusKey is the attribute Key conforming to the // "signalr.connection.status" semantic conventions. It represents the // signalR HTTP connection closure status. // // Type: Enum // RequirementLevel: Optional // Stability: experimental // Examples: 'app_shutdown', 'timeout' SignalrConnectionStatusKey = attribute.Key("signalr.connection.status") // SignalrTransportKey is the attribute Key conforming to the // "signalr.transport" semantic conventions. It represents the [SignalR // transport // type](https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/docs/specs/TransportProtocols.md) // // Type: Enum // RequirementLevel: Optional // Stability: experimental // Examples: 'web_sockets', 'long_polling' SignalrTransportKey = attribute.Key("signalr.transport") ) var ( // The connection was closed normally SignalrConnectionStatusNormalClosure = SignalrConnectionStatusKey.String("normal_closure") // The connection was closed due to a timeout SignalrConnectionStatusTimeout = SignalrConnectionStatusKey.String("timeout") // The connection was closed because the app is shutting down SignalrConnectionStatusAppShutdown = SignalrConnectionStatusKey.String("app_shutdown") ) var ( // ServerSentEvents protocol SignalrTransportServerSentEvents = SignalrTransportKey.String("server_sent_events") // LongPolling protocol SignalrTransportLongPolling = SignalrTransportKey.String("long_polling") // WebSockets protocol SignalrTransportWebSockets = SignalrTransportKey.String("web_sockets") ) // Describes JVM buffer metric attributes. const ( // JvmBufferPoolNameKey is the attribute Key conforming to the // "jvm.buffer.pool.name" semantic conventions. It represents the name of // the buffer pool. // // Type: string // RequirementLevel: Recommended // Stability: experimental // Examples: 'mapped', 'direct' // Note: Pool names are generally obtained via // [BufferPoolMXBean#getName()](https://docs.oracle.com/en/java/javase/11/docs/api/java.management/java/lang/management/BufferPoolMXBean.html#getName()). JvmBufferPoolNameKey = attribute.Key("jvm.buffer.pool.name") ) // JvmBufferPoolName returns an attribute KeyValue conforming to the // "jvm.buffer.pool.name" semantic conventions. It represents the name of the // buffer pool. func JvmBufferPoolName(val string) attribute.KeyValue { return JvmBufferPoolNameKey.String(val) } // Describes JVM memory metric attributes. const ( // JvmMemoryPoolNameKey is the attribute Key conforming to the // "jvm.memory.pool.name" semantic conventions. It represents the name of // the memory pool. // // Type: string // RequirementLevel: Recommended // Stability: stable // Examples: 'G1 Old Gen', 'G1 Eden space', 'G1 Survivor Space' // Note: Pool names are generally obtained via // [MemoryPoolMXBean#getName()](https://docs.oracle.com/en/java/javase/11/docs/api/java.management/java/lang/management/MemoryPoolMXBean.html#getName()). JvmMemoryPoolNameKey = attribute.Key("jvm.memory.pool.name") // JvmMemoryTypeKey is the attribute Key conforming to the // "jvm.memory.type" semantic conventions. It represents the type of // memory. // // Type: Enum // RequirementLevel: Recommended // Stability: stable // Examples: 'heap', 'non_heap' JvmMemoryTypeKey = attribute.Key("jvm.memory.type") ) var ( // Heap memory JvmMemoryTypeHeap = JvmMemoryTypeKey.String("heap") // Non-heap memory JvmMemoryTypeNonHeap = JvmMemoryTypeKey.String("non_heap") ) // JvmMemoryPoolName returns an attribute KeyValue conforming to the // "jvm.memory.pool.name" semantic conventions. It represents the name of the // memory pool. func JvmMemoryPoolName(val string) attribute.KeyValue { return JvmMemoryPoolNameKey.String(val) } // Describes System metric attributes const ( // SystemDeviceKey is the attribute Key conforming to the "system.device" // semantic conventions. It represents the device identifier // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: '(identifier)' SystemDeviceKey = attribute.Key("system.device") ) // SystemDevice returns an attribute KeyValue conforming to the // "system.device" semantic conventions. It represents the device identifier func SystemDevice(val string) attribute.KeyValue { return SystemDeviceKey.String(val) } // Describes System CPU metric attributes const ( // SystemCPULogicalNumberKey is the attribute Key conforming to the // "system.cpu.logical_number" semantic conventions. It represents the // logical CPU number [0..n-1] // // Type: int // RequirementLevel: Optional // Stability: experimental // Examples: 1 SystemCPULogicalNumberKey = attribute.Key("system.cpu.logical_number") // SystemCPUStateKey is the attribute Key conforming to the // "system.cpu.state" semantic conventions. It represents the state of the // CPU // // Type: Enum // RequirementLevel: Optional // Stability: experimental // Examples: 'idle', 'interrupt' SystemCPUStateKey = attribute.Key("system.cpu.state") ) var ( // user SystemCPUStateUser = SystemCPUStateKey.String("user") // system SystemCPUStateSystem = SystemCPUStateKey.String("system") // nice SystemCPUStateNice = SystemCPUStateKey.String("nice") // idle SystemCPUStateIdle = SystemCPUStateKey.String("idle") // iowait SystemCPUStateIowait = SystemCPUStateKey.String("iowait") // interrupt SystemCPUStateInterrupt = SystemCPUStateKey.String("interrupt") // steal SystemCPUStateSteal = SystemCPUStateKey.String("steal") ) // SystemCPULogicalNumber returns an attribute KeyValue conforming to the // "system.cpu.logical_number" semantic conventions. It represents the logical // CPU number [0..n-1] func SystemCPULogicalNumber(val int) attribute.KeyValue { return SystemCPULogicalNumberKey.Int(val) } // Describes System Memory metric attributes const ( // SystemMemoryStateKey is the attribute Key conforming to the // "system.memory.state" semantic conventions. It represents the memory // state // // Type: Enum // RequirementLevel: Optional // Stability: experimental // Examples: 'free', 'cached' SystemMemoryStateKey = attribute.Key("system.memory.state") ) var ( // used SystemMemoryStateUsed = SystemMemoryStateKey.String("used") // free SystemMemoryStateFree = SystemMemoryStateKey.String("free") // shared SystemMemoryStateShared = SystemMemoryStateKey.String("shared") // buffers SystemMemoryStateBuffers = SystemMemoryStateKey.String("buffers") // cached SystemMemoryStateCached = SystemMemoryStateKey.String("cached") ) // Describes System Memory Paging metric attributes const ( // SystemPagingDirectionKey is the attribute Key conforming to the // "system.paging.direction" semantic conventions. It represents the paging // access direction // // Type: Enum // RequirementLevel: Optional // Stability: experimental // Examples: 'in' SystemPagingDirectionKey = attribute.Key("system.paging.direction") // SystemPagingStateKey is the attribute Key conforming to the // "system.paging.state" semantic conventions. It represents the memory // paging state // // Type: Enum // RequirementLevel: Optional // Stability: experimental // Examples: 'free' SystemPagingStateKey = attribute.Key("system.paging.state") // SystemPagingTypeKey is the attribute Key conforming to the // "system.paging.type" semantic conventions. It represents the memory // paging type // // Type: Enum // RequirementLevel: Optional // Stability: experimental // Examples: 'minor' SystemPagingTypeKey = attribute.Key("system.paging.type") ) var ( // in SystemPagingDirectionIn = SystemPagingDirectionKey.String("in") // out SystemPagingDirectionOut = SystemPagingDirectionKey.String("out") ) var ( // used SystemPagingStateUsed = SystemPagingStateKey.String("used") // free SystemPagingStateFree = SystemPagingStateKey.String("free") ) var ( // major SystemPagingTypeMajor = SystemPagingTypeKey.String("major") // minor SystemPagingTypeMinor = SystemPagingTypeKey.String("minor") ) // Describes Filesystem metric attributes const ( // SystemFilesystemModeKey is the attribute Key conforming to the // "system.filesystem.mode" semantic conventions. It represents the // filesystem mode // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'rw, ro' SystemFilesystemModeKey = attribute.Key("system.filesystem.mode") // SystemFilesystemMountpointKey is the attribute Key conforming to the // "system.filesystem.mountpoint" semantic conventions. It represents the // filesystem mount path // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: '/mnt/data' SystemFilesystemMountpointKey = attribute.Key("system.filesystem.mountpoint") // SystemFilesystemStateKey is the attribute Key conforming to the // "system.filesystem.state" semantic conventions. It represents the // filesystem state // // Type: Enum // RequirementLevel: Optional // Stability: experimental // Examples: 'used' SystemFilesystemStateKey = attribute.Key("system.filesystem.state") // SystemFilesystemTypeKey is the attribute Key conforming to the // "system.filesystem.type" semantic conventions. It represents the // filesystem type // // Type: Enum // RequirementLevel: Optional // Stability: experimental // Examples: 'ext4' SystemFilesystemTypeKey = attribute.Key("system.filesystem.type") ) var ( // used SystemFilesystemStateUsed = SystemFilesystemStateKey.String("used") // free SystemFilesystemStateFree = SystemFilesystemStateKey.String("free") // reserved SystemFilesystemStateReserved = SystemFilesystemStateKey.String("reserved") ) var ( // fat32 SystemFilesystemTypeFat32 = SystemFilesystemTypeKey.String("fat32") // exfat SystemFilesystemTypeExfat = SystemFilesystemTypeKey.String("exfat") // ntfs SystemFilesystemTypeNtfs = SystemFilesystemTypeKey.String("ntfs") // refs SystemFilesystemTypeRefs = SystemFilesystemTypeKey.String("refs") // hfsplus SystemFilesystemTypeHfsplus = SystemFilesystemTypeKey.String("hfsplus") // ext4 SystemFilesystemTypeExt4 = SystemFilesystemTypeKey.String("ext4") ) // SystemFilesystemMode returns an attribute KeyValue conforming to the // "system.filesystem.mode" semantic conventions. It represents the filesystem // mode func SystemFilesystemMode(val string) attribute.KeyValue { return SystemFilesystemModeKey.String(val) } // SystemFilesystemMountpoint returns an attribute KeyValue conforming to // the "system.filesystem.mountpoint" semantic conventions. It represents the // filesystem mount path func SystemFilesystemMountpoint(val string) attribute.KeyValue { return SystemFilesystemMountpointKey.String(val) } // Describes Network metric attributes const ( // SystemNetworkStateKey is the attribute Key conforming to the // "system.network.state" semantic conventions. It represents a stateless // protocol MUST NOT set this attribute // // Type: Enum // RequirementLevel: Optional // Stability: experimental // Examples: 'close_wait' SystemNetworkStateKey = attribute.Key("system.network.state") ) var ( // close SystemNetworkStateClose = SystemNetworkStateKey.String("close") // close_wait SystemNetworkStateCloseWait = SystemNetworkStateKey.String("close_wait") // closing SystemNetworkStateClosing = SystemNetworkStateKey.String("closing") // delete SystemNetworkStateDelete = SystemNetworkStateKey.String("delete") // established SystemNetworkStateEstablished = SystemNetworkStateKey.String("established") // fin_wait_1 SystemNetworkStateFinWait1 = SystemNetworkStateKey.String("fin_wait_1") // fin_wait_2 SystemNetworkStateFinWait2 = SystemNetworkStateKey.String("fin_wait_2") // last_ack SystemNetworkStateLastAck = SystemNetworkStateKey.String("last_ack") // listen SystemNetworkStateListen = SystemNetworkStateKey.String("listen") // syn_recv SystemNetworkStateSynRecv = SystemNetworkStateKey.String("syn_recv") // syn_sent SystemNetworkStateSynSent = SystemNetworkStateKey.String("syn_sent") // time_wait SystemNetworkStateTimeWait = SystemNetworkStateKey.String("time_wait") ) // Describes System Process metric attributes const ( // SystemProcessesStatusKey is the attribute Key conforming to the // "system.processes.status" semantic conventions. It represents the // process state, e.g., [Linux Process State // Codes](https://man7.org/linux/man-pages/man1/ps.1.html#PROCESS_STATE_CODES) // // Type: Enum // RequirementLevel: Optional // Stability: experimental // Examples: 'running' SystemProcessesStatusKey = attribute.Key("system.processes.status") ) var ( // running SystemProcessesStatusRunning = SystemProcessesStatusKey.String("running") // sleeping SystemProcessesStatusSleeping = SystemProcessesStatusKey.String("sleeping") // stopped SystemProcessesStatusStopped = SystemProcessesStatusKey.String("stopped") // defunct SystemProcessesStatusDefunct = SystemProcessesStatusKey.String("defunct") ) // These attributes may be used to describe the client in a connection-based // network interaction where there is one side that initiates the connection // (the client is the side that initiates the connection). This covers all TCP // network interactions since TCP is connection-based and one side initiates // the connection (an exception is made for peer-to-peer communication over TCP // where the "user-facing" surface of the protocol / API doesn't expose a clear // notion of client and server). This also covers UDP network interactions // where one side initiates the interaction, e.g. QUIC (HTTP/3) and DNS. const ( // ClientAddressKey is the attribute Key conforming to the "client.address" // semantic conventions. It represents the client address - domain name if // available without reverse DNS lookup; otherwise, IP address or Unix // domain socket name. // // Type: string // RequirementLevel: Optional // Stability: stable // Examples: 'client.example.com', '10.1.2.80', '/tmp/my.sock' // Note: When observed from the server side, and when communicating through // an intermediary, `client.address` SHOULD represent the client address // behind any intermediaries, for example proxies, if it's available. ClientAddressKey = attribute.Key("client.address") // ClientPortKey is the attribute Key conforming to the "client.port" // semantic conventions. It represents the client port number. // // Type: int // RequirementLevel: Optional // Stability: stable // Examples: 65123 // Note: When observed from the server side, and when communicating through // an intermediary, `client.port` SHOULD represent the client port behind // any intermediaries, for example proxies, if it's available. ClientPortKey = attribute.Key("client.port") ) // ClientAddress returns an attribute KeyValue conforming to the // "client.address" semantic conventions. It represents the client address - // domain name if available without reverse DNS lookup; otherwise, IP address // or Unix domain socket name. func ClientAddress(val string) attribute.KeyValue { return ClientAddressKey.String(val) } // ClientPort returns an attribute KeyValue conforming to the "client.port" // semantic conventions. It represents the client port number. func ClientPort(val int) attribute.KeyValue { return ClientPortKey.Int(val) } // The attributes used to describe telemetry in the context of databases. const ( // DBCassandraConsistencyLevelKey is the attribute Key conforming to the // "db.cassandra.consistency_level" semantic conventions. It represents the // consistency level of the query. Based on consistency values from // [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). // // Type: Enum // RequirementLevel: Optional // Stability: experimental DBCassandraConsistencyLevelKey = attribute.Key("db.cassandra.consistency_level") // DBCassandraCoordinatorDCKey is the attribute Key conforming to the // "db.cassandra.coordinator.dc" semantic conventions. It represents the // data center of the coordinating node for a query. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'us-west-2' DBCassandraCoordinatorDCKey = attribute.Key("db.cassandra.coordinator.dc") // DBCassandraCoordinatorIDKey is the attribute Key conforming to the // "db.cassandra.coordinator.id" semantic conventions. It represents the ID // of the coordinating node for a query. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'be13faa2-8574-4d71-926d-27f16cf8a7af' DBCassandraCoordinatorIDKey = attribute.Key("db.cassandra.coordinator.id") // DBCassandraIdempotenceKey is the attribute Key conforming to the // "db.cassandra.idempotence" semantic conventions. It represents the // whether or not the query is idempotent. // // Type: boolean // RequirementLevel: Optional // Stability: experimental DBCassandraIdempotenceKey = attribute.Key("db.cassandra.idempotence") // DBCassandraPageSizeKey is the attribute Key conforming to the // "db.cassandra.page_size" semantic conventions. It represents the fetch // size used for paging, i.e. how many rows will be returned at once. // // Type: int // RequirementLevel: Optional // Stability: experimental // Examples: 5000 DBCassandraPageSizeKey = attribute.Key("db.cassandra.page_size") // DBCassandraSpeculativeExecutionCountKey is the attribute Key conforming // to the "db.cassandra.speculative_execution_count" semantic conventions. // It represents the number of times a query was speculatively executed.
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
true
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/trace.go
vendor/go.opentelemetry.io/otel/semconv/v1.24.0/trace.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 // Code generated from semantic convention specification. DO NOT EDIT. package semconv // import "go.opentelemetry.io/otel/semconv/v1.24.0" import "go.opentelemetry.io/otel/attribute" // Operations that access some remote service. const ( // PeerServiceKey is the attribute Key conforming to the "peer.service" // semantic conventions. It represents the // [`service.name`](/docs/resource/README.md#service) of the remote // service. SHOULD be equal to the actual `service.name` resource attribute // of the remote service if any. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'AuthTokenCache' PeerServiceKey = attribute.Key("peer.service") ) // PeerService returns an attribute KeyValue conforming to the // "peer.service" semantic conventions. It represents the // [`service.name`](/docs/resource/README.md#service) of the remote service. // SHOULD be equal to the actual `service.name` resource attribute of the // remote service if any. func PeerService(val string) attribute.KeyValue { return PeerServiceKey.String(val) } // These attributes may be used for any operation with an authenticated and/or // authorized enduser. const ( // EnduserIDKey is the attribute Key conforming to the "enduser.id" // semantic conventions. It represents the username or client_id extracted // from the access token or // [Authorization](https://tools.ietf.org/html/rfc7235#section-4.2) header // in the inbound request from outside the system. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'username' EnduserIDKey = attribute.Key("enduser.id") // EnduserRoleKey is the attribute Key conforming to the "enduser.role" // semantic conventions. It represents the actual/assumed role the client // is making the request under extracted from token or application security // context. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'admin' EnduserRoleKey = attribute.Key("enduser.role") // EnduserScopeKey is the attribute Key conforming to the "enduser.scope" // semantic conventions. It represents the scopes or granted authorities // the client currently possesses extracted from token or application // security context. The value would come from the scope associated with an // [OAuth 2.0 Access // Token](https://tools.ietf.org/html/rfc6749#section-3.3) or an attribute // value in a [SAML 2.0 // Assertion](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html). // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'read:message, write:files' EnduserScopeKey = attribute.Key("enduser.scope") ) // EnduserID returns an attribute KeyValue conforming to the "enduser.id" // semantic conventions. It represents the username or client_id extracted from // the access token or // [Authorization](https://tools.ietf.org/html/rfc7235#section-4.2) header in // the inbound request from outside the system. func EnduserID(val string) attribute.KeyValue { return EnduserIDKey.String(val) } // EnduserRole returns an attribute KeyValue conforming to the // "enduser.role" semantic conventions. It represents the actual/assumed role // the client is making the request under extracted from token or application // security context. func EnduserRole(val string) attribute.KeyValue { return EnduserRoleKey.String(val) } // EnduserScope returns an attribute KeyValue conforming to the // "enduser.scope" semantic conventions. It represents the scopes or granted // authorities the client currently possesses extracted from token or // application security context. The value would come from the scope associated // with an [OAuth 2.0 Access // Token](https://tools.ietf.org/html/rfc6749#section-3.3) or an attribute // value in a [SAML 2.0 // Assertion](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html). func EnduserScope(val string) attribute.KeyValue { return EnduserScopeKey.String(val) } // These attributes allow to report this unit of code and therefore to provide // more context about the span. const ( // CodeColumnKey is the attribute Key conforming to the "code.column" // semantic conventions. It represents the column number in `code.filepath` // best representing the operation. It SHOULD point within the code unit // named in `code.function`. // // Type: int // RequirementLevel: Optional // Stability: experimental // Examples: 16 CodeColumnKey = attribute.Key("code.column") // CodeFilepathKey is the attribute Key conforming to the "code.filepath" // semantic conventions. It represents the source code file name that // identifies the code unit as uniquely as possible (preferably an absolute // file path). // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: '/usr/local/MyApplication/content_root/app/index.php' CodeFilepathKey = attribute.Key("code.filepath") // CodeFunctionKey is the attribute Key conforming to the "code.function" // semantic conventions. It represents the method or function name, or // equivalent (usually rightmost part of the code unit's name). // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'serveRequest' CodeFunctionKey = attribute.Key("code.function") // CodeLineNumberKey is the attribute Key conforming to the "code.lineno" // semantic conventions. It represents the line number in `code.filepath` // best representing the operation. It SHOULD point within the code unit // named in `code.function`. // // Type: int // RequirementLevel: Optional // Stability: experimental // Examples: 42 CodeLineNumberKey = attribute.Key("code.lineno") // CodeNamespaceKey is the attribute Key conforming to the "code.namespace" // semantic conventions. It represents the "namespace" within which // `code.function` is defined. Usually the qualified class or module name, // such that `code.namespace` + some separator + `code.function` form a // unique identifier for the code unit. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'com.example.MyHTTPService' CodeNamespaceKey = attribute.Key("code.namespace") // CodeStacktraceKey is the attribute Key conforming to the // "code.stacktrace" semantic conventions. It represents a stacktrace as a // string in the natural representation for the language runtime. The // representation is to be determined and documented by each language SIG. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'at // com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\n at ' // 'com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\n at ' // 'com.example.GenerateTrace.main(GenerateTrace.java:5)' CodeStacktraceKey = attribute.Key("code.stacktrace") ) // CodeColumn returns an attribute KeyValue conforming to the "code.column" // semantic conventions. It represents the column number in `code.filepath` // best representing the operation. It SHOULD point within the code unit named // in `code.function`. func CodeColumn(val int) attribute.KeyValue { return CodeColumnKey.Int(val) } // CodeFilepath returns an attribute KeyValue conforming to the // "code.filepath" semantic conventions. It represents the source code file // name that identifies the code unit as uniquely as possible (preferably an // absolute file path). func CodeFilepath(val string) attribute.KeyValue { return CodeFilepathKey.String(val) } // CodeFunction returns an attribute KeyValue conforming to the // "code.function" semantic conventions. It represents the method or function // name, or equivalent (usually rightmost part of the code unit's name). func CodeFunction(val string) attribute.KeyValue { return CodeFunctionKey.String(val) } // CodeLineNumber returns an attribute KeyValue conforming to the "code.lineno" // semantic conventions. It represents the line number in `code.filepath` best // representing the operation. It SHOULD point within the code unit named in // `code.function`. func CodeLineNumber(val int) attribute.KeyValue { return CodeLineNumberKey.Int(val) } // CodeNamespace returns an attribute KeyValue conforming to the // "code.namespace" semantic conventions. It represents the "namespace" within // which `code.function` is defined. Usually the qualified class or module // name, such that `code.namespace` + some separator + `code.function` form a // unique identifier for the code unit. func CodeNamespace(val string) attribute.KeyValue { return CodeNamespaceKey.String(val) } // CodeStacktrace returns an attribute KeyValue conforming to the // "code.stacktrace" semantic conventions. It represents a stacktrace as a // string in the natural representation for the language runtime. The // representation is to be determined and documented by each language SIG. func CodeStacktrace(val string) attribute.KeyValue { return CodeStacktraceKey.String(val) } // These attributes may be used for any operation to store information about a // thread that started a span. const ( // ThreadIDKey is the attribute Key conforming to the "thread.id" semantic // conventions. It represents the current "managed" thread ID (as opposed // to OS thread ID). // // Type: int // RequirementLevel: Optional // Stability: experimental // Examples: 42 ThreadIDKey = attribute.Key("thread.id") // ThreadNameKey is the attribute Key conforming to the "thread.name" // semantic conventions. It represents the current thread name. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'main' ThreadNameKey = attribute.Key("thread.name") ) // ThreadID returns an attribute KeyValue conforming to the "thread.id" // semantic conventions. It represents the current "managed" thread ID (as // opposed to OS thread ID). func ThreadID(val int) attribute.KeyValue { return ThreadIDKey.Int(val) } // ThreadName returns an attribute KeyValue conforming to the "thread.name" // semantic conventions. It represents the current thread name. func ThreadName(val string) attribute.KeyValue { return ThreadNameKey.String(val) } // Span attributes used by AWS Lambda (in addition to general `faas` // attributes). const ( // AWSLambdaInvokedARNKey is the attribute Key conforming to the // "aws.lambda.invoked_arn" semantic conventions. It represents the full // invoked ARN as provided on the `Context` passed to the function // (`Lambda-Runtime-Invoked-Function-ARN` header on the // `/runtime/invocation/next` applicable). // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'arn:aws:lambda:us-east-1:123456:function:myfunction:myalias' // Note: This may be different from `cloud.resource_id` if an alias is // involved. AWSLambdaInvokedARNKey = attribute.Key("aws.lambda.invoked_arn") ) // AWSLambdaInvokedARN returns an attribute KeyValue conforming to the // "aws.lambda.invoked_arn" semantic conventions. It represents the full // invoked ARN as provided on the `Context` passed to the function // (`Lambda-Runtime-Invoked-Function-ARN` header on the // `/runtime/invocation/next` applicable). func AWSLambdaInvokedARN(val string) attribute.KeyValue { return AWSLambdaInvokedARNKey.String(val) } // Attributes for CloudEvents. CloudEvents is a specification on how to define // event data in a standard way. These attributes can be attached to spans when // performing operations with CloudEvents, regardless of the protocol being // used. const ( // CloudeventsEventIDKey is the attribute Key conforming to the // "cloudevents.event_id" semantic conventions. It represents the // [event_id](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#id) // uniquely identifies the event. // // Type: string // RequirementLevel: Required // Stability: experimental // Examples: '123e4567-e89b-12d3-a456-426614174000', '0001' CloudeventsEventIDKey = attribute.Key("cloudevents.event_id") // CloudeventsEventSourceKey is the attribute Key conforming to the // "cloudevents.event_source" semantic conventions. It represents the // [source](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#source-1) // identifies the context in which an event happened. // // Type: string // RequirementLevel: Required // Stability: experimental // Examples: 'https://github.com/cloudevents', // '/cloudevents/spec/pull/123', 'my-service' CloudeventsEventSourceKey = attribute.Key("cloudevents.event_source") // CloudeventsEventSpecVersionKey is the attribute Key conforming to the // "cloudevents.event_spec_version" semantic conventions. It represents the // [version of the CloudEvents // specification](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#specversion) // which the event uses. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: '1.0' CloudeventsEventSpecVersionKey = attribute.Key("cloudevents.event_spec_version") // CloudeventsEventSubjectKey is the attribute Key conforming to the // "cloudevents.event_subject" semantic conventions. It represents the // [subject](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#subject) // of the event in the context of the event producer (identified by // source). // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'mynewfile.jpg' CloudeventsEventSubjectKey = attribute.Key("cloudevents.event_subject") // CloudeventsEventTypeKey is the attribute Key conforming to the // "cloudevents.event_type" semantic conventions. It represents the // [event_type](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#type) // contains a value describing the type of event related to the originating // occurrence. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'com.github.pull_request.opened', // 'com.example.object.deleted.v2' CloudeventsEventTypeKey = attribute.Key("cloudevents.event_type") ) // CloudeventsEventID returns an attribute KeyValue conforming to the // "cloudevents.event_id" semantic conventions. It represents the // [event_id](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#id) // uniquely identifies the event. func CloudeventsEventID(val string) attribute.KeyValue { return CloudeventsEventIDKey.String(val) } // CloudeventsEventSource returns an attribute KeyValue conforming to the // "cloudevents.event_source" semantic conventions. It represents the // [source](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#source-1) // identifies the context in which an event happened. func CloudeventsEventSource(val string) attribute.KeyValue { return CloudeventsEventSourceKey.String(val) } // CloudeventsEventSpecVersion returns an attribute KeyValue conforming to // the "cloudevents.event_spec_version" semantic conventions. It represents the // [version of the CloudEvents // specification](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#specversion) // which the event uses. func CloudeventsEventSpecVersion(val string) attribute.KeyValue { return CloudeventsEventSpecVersionKey.String(val) } // CloudeventsEventSubject returns an attribute KeyValue conforming to the // "cloudevents.event_subject" semantic conventions. It represents the // [subject](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#subject) // of the event in the context of the event producer (identified by source). func CloudeventsEventSubject(val string) attribute.KeyValue { return CloudeventsEventSubjectKey.String(val) } // CloudeventsEventType returns an attribute KeyValue conforming to the // "cloudevents.event_type" semantic conventions. It represents the // [event_type](https://github.com/cloudevents/spec/blob/v1.0.2/cloudevents/spec.md#type) // contains a value describing the type of event related to the originating // occurrence. func CloudeventsEventType(val string) attribute.KeyValue { return CloudeventsEventTypeKey.String(val) } // Semantic conventions for the OpenTracing Shim const ( // OpentracingRefTypeKey is the attribute Key conforming to the // "opentracing.ref_type" semantic conventions. It represents the // parent-child Reference type // // Type: Enum // RequirementLevel: Optional // Stability: experimental // Note: The causal relationship between a child Span and a parent Span. OpentracingRefTypeKey = attribute.Key("opentracing.ref_type") ) var ( // The parent Span depends on the child Span in some capacity OpentracingRefTypeChildOf = OpentracingRefTypeKey.String("child_of") // The parent Span doesn't depend in any way on the result of the child Span OpentracingRefTypeFollowsFrom = OpentracingRefTypeKey.String("follows_from") ) // Span attributes used by non-OTLP exporters to represent OpenTelemetry Span's // concepts. const ( // OTelStatusCodeKey is the attribute Key conforming to the // "otel.status_code" semantic conventions. It represents the name of the // code, either "OK" or "ERROR". MUST NOT be set if the status code is // UNSET. // // Type: Enum // RequirementLevel: Optional // Stability: experimental OTelStatusCodeKey = attribute.Key("otel.status_code") // OTelStatusDescriptionKey is the attribute Key conforming to the // "otel.status_description" semantic conventions. It represents the // description of the Status if it has a value, otherwise not set. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'resource not found' OTelStatusDescriptionKey = attribute.Key("otel.status_description") ) var ( // The operation has been validated by an Application developer or Operator to have completed successfully OTelStatusCodeOk = OTelStatusCodeKey.String("OK") // The operation contains an error OTelStatusCodeError = OTelStatusCodeKey.String("ERROR") ) // OTelStatusDescription returns an attribute KeyValue conforming to the // "otel.status_description" semantic conventions. It represents the // description of the Status if it has a value, otherwise not set. func OTelStatusDescription(val string) attribute.KeyValue { return OTelStatusDescriptionKey.String(val) } // This semantic convention describes an instance of a function that runs // without provisioning or managing of servers (also known as serverless // functions or Function as a Service (FaaS)) with spans. const ( // FaaSInvocationIDKey is the attribute Key conforming to the // "faas.invocation_id" semantic conventions. It represents the invocation // ID of the current function invocation. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'af9d5aa4-a685-4c5f-a22b-444f80b3cc28' FaaSInvocationIDKey = attribute.Key("faas.invocation_id") ) // FaaSInvocationID returns an attribute KeyValue conforming to the // "faas.invocation_id" semantic conventions. It represents the invocation ID // of the current function invocation. func FaaSInvocationID(val string) attribute.KeyValue { return FaaSInvocationIDKey.String(val) } // Semantic Convention for FaaS triggered as a response to some data source // operation such as a database or filesystem read/write. const ( // FaaSDocumentCollectionKey is the attribute Key conforming to the // "faas.document.collection" semantic conventions. It represents the name // of the source on which the triggering operation was performed. For // example, in Cloud Storage or S3 corresponds to the bucket name, and in // Cosmos DB to the database name. // // Type: string // RequirementLevel: Required // Stability: experimental // Examples: 'myBucketName', 'myDBName' FaaSDocumentCollectionKey = attribute.Key("faas.document.collection") // FaaSDocumentNameKey is the attribute Key conforming to the // "faas.document.name" semantic conventions. It represents the document // name/table subjected to the operation. For example, in Cloud Storage or // S3 is the name of the file, and in Cosmos DB the table name. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'myFile.txt', 'myTableName' FaaSDocumentNameKey = attribute.Key("faas.document.name") // FaaSDocumentOperationKey is the attribute Key conforming to the // "faas.document.operation" semantic conventions. It represents the // describes the type of the operation that was performed on the data. // // Type: Enum // RequirementLevel: Required // Stability: experimental FaaSDocumentOperationKey = attribute.Key("faas.document.operation") // FaaSDocumentTimeKey is the attribute Key conforming to the // "faas.document.time" semantic conventions. It represents a string // containing the time when the data was accessed in the [ISO // 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format // expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: '2020-01-23T13:47:06Z' FaaSDocumentTimeKey = attribute.Key("faas.document.time") ) var ( // When a new object is created FaaSDocumentOperationInsert = FaaSDocumentOperationKey.String("insert") // When an object is modified FaaSDocumentOperationEdit = FaaSDocumentOperationKey.String("edit") // When an object is deleted FaaSDocumentOperationDelete = FaaSDocumentOperationKey.String("delete") ) // FaaSDocumentCollection returns an attribute KeyValue conforming to the // "faas.document.collection" semantic conventions. It represents the name of // the source on which the triggering operation was performed. For example, in // Cloud Storage or S3 corresponds to the bucket name, and in Cosmos DB to the // database name. func FaaSDocumentCollection(val string) attribute.KeyValue { return FaaSDocumentCollectionKey.String(val) } // FaaSDocumentName returns an attribute KeyValue conforming to the // "faas.document.name" semantic conventions. It represents the document // name/table subjected to the operation. For example, in Cloud Storage or S3 // is the name of the file, and in Cosmos DB the table name. func FaaSDocumentName(val string) attribute.KeyValue { return FaaSDocumentNameKey.String(val) } // FaaSDocumentTime returns an attribute KeyValue conforming to the // "faas.document.time" semantic conventions. It represents a string containing // the time when the data was accessed in the [ISO // 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format // expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). func FaaSDocumentTime(val string) attribute.KeyValue { return FaaSDocumentTimeKey.String(val) } // Semantic Convention for FaaS scheduled to be executed regularly. const ( // FaaSCronKey is the attribute Key conforming to the "faas.cron" semantic // conventions. It represents a string containing the schedule period as // [Cron // Expression](https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm). // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: '0/5 * * * ? *' FaaSCronKey = attribute.Key("faas.cron") // FaaSTimeKey is the attribute Key conforming to the "faas.time" semantic // conventions. It represents a string containing the function invocation // time in the [ISO // 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format // expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: '2020-01-23T13:47:06Z' FaaSTimeKey = attribute.Key("faas.time") ) // FaaSCron returns an attribute KeyValue conforming to the "faas.cron" // semantic conventions. It represents a string containing the schedule period // as [Cron // Expression](https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm). func FaaSCron(val string) attribute.KeyValue { return FaaSCronKey.String(val) } // FaaSTime returns an attribute KeyValue conforming to the "faas.time" // semantic conventions. It represents a string containing the function // invocation time in the [ISO // 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format // expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). func FaaSTime(val string) attribute.KeyValue { return FaaSTimeKey.String(val) } // Contains additional attributes for incoming FaaS spans. const ( // FaaSColdstartKey is the attribute Key conforming to the "faas.coldstart" // semantic conventions. It represents a boolean that is true if the // serverless function is executed for the first time (aka cold-start). // // Type: boolean // RequirementLevel: Optional // Stability: experimental FaaSColdstartKey = attribute.Key("faas.coldstart") ) // FaaSColdstart returns an attribute KeyValue conforming to the // "faas.coldstart" semantic conventions. It represents a boolean that is true // if the serverless function is executed for the first time (aka cold-start). func FaaSColdstart(val bool) attribute.KeyValue { return FaaSColdstartKey.Bool(val) } // The `aws` conventions apply to operations using the AWS SDK. They map // request or response parameters in AWS SDK API calls to attributes on a Span. // The conventions have been collected over time based on feedback from AWS // users of tracing and will continue to evolve as new interesting conventions // are found. // Some descriptions are also provided for populating general OpenTelemetry // semantic conventions based on these APIs. const ( // AWSRequestIDKey is the attribute Key conforming to the "aws.request_id" // semantic conventions. It represents the AWS request ID as returned in // the response headers `x-amz-request-id` or `x-amz-requestid`. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: '79b9da39-b7ae-508a-a6bc-864b2829c622', 'C9ER4AJX75574TDJ' AWSRequestIDKey = attribute.Key("aws.request_id") ) // AWSRequestID returns an attribute KeyValue conforming to the // "aws.request_id" semantic conventions. It represents the AWS request ID as // returned in the response headers `x-amz-request-id` or `x-amz-requestid`. func AWSRequestID(val string) attribute.KeyValue { return AWSRequestIDKey.String(val) } // Attributes that exist for multiple DynamoDB request types. const ( // AWSDynamoDBAttributesToGetKey is the attribute Key conforming to the // "aws.dynamodb.attributes_to_get" semantic conventions. It represents the // value of the `AttributesToGet` request parameter. // // Type: string[] // RequirementLevel: Optional // Stability: experimental // Examples: 'lives', 'id' AWSDynamoDBAttributesToGetKey = attribute.Key("aws.dynamodb.attributes_to_get") // AWSDynamoDBConsistentReadKey is the attribute Key conforming to the // "aws.dynamodb.consistent_read" semantic conventions. It represents the // value of the `ConsistentRead` request parameter. // // Type: boolean // RequirementLevel: Optional // Stability: experimental AWSDynamoDBConsistentReadKey = attribute.Key("aws.dynamodb.consistent_read") // AWSDynamoDBConsumedCapacityKey is the attribute Key conforming to the // "aws.dynamodb.consumed_capacity" semantic conventions. It represents the // JSON-serialized value of each item in the `ConsumedCapacity` response // field. // // Type: string[] // RequirementLevel: Optional // Stability: experimental // Examples: '{ "CapacityUnits": number, "GlobalSecondaryIndexes": { // "string" : { "CapacityUnits": number, "ReadCapacityUnits": number, // "WriteCapacityUnits": number } }, "LocalSecondaryIndexes": { "string" : // { "CapacityUnits": number, "ReadCapacityUnits": number, // "WriteCapacityUnits": number } }, "ReadCapacityUnits": number, "Table": // { "CapacityUnits": number, "ReadCapacityUnits": number, // "WriteCapacityUnits": number }, "TableName": "string", // "WriteCapacityUnits": number }' AWSDynamoDBConsumedCapacityKey = attribute.Key("aws.dynamodb.consumed_capacity") // AWSDynamoDBIndexNameKey is the attribute Key conforming to the // "aws.dynamodb.index_name" semantic conventions. It represents the value // of the `IndexName` request parameter. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'name_to_group' AWSDynamoDBIndexNameKey = attribute.Key("aws.dynamodb.index_name") // AWSDynamoDBItemCollectionMetricsKey is the attribute Key conforming to // the "aws.dynamodb.item_collection_metrics" semantic conventions. It // represents the JSON-serialized value of the `ItemCollectionMetrics` // response field. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: '{ "string" : [ { "ItemCollectionKey": { "string" : { "B": // blob, "BOOL": boolean, "BS": [ blob ], "L": [ "AttributeValue" ], "M": { // "string" : "AttributeValue" }, "N": "string", "NS": [ "string" ], // "NULL": boolean, "S": "string", "SS": [ "string" ] } }, // "SizeEstimateRangeGB": [ number ] } ] }' AWSDynamoDBItemCollectionMetricsKey = attribute.Key("aws.dynamodb.item_collection_metrics") // AWSDynamoDBLimitKey is the attribute Key conforming to the // "aws.dynamodb.limit" semantic conventions. It represents the value of // the `Limit` request parameter. // // Type: int // RequirementLevel: Optional // Stability: experimental // Examples: 10 AWSDynamoDBLimitKey = attribute.Key("aws.dynamodb.limit") // AWSDynamoDBProjectionKey is the attribute Key conforming to the // "aws.dynamodb.projection" semantic conventions. It represents the value // of the `ProjectionExpression` request parameter. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'Title', 'Title, Price, Color', 'Title, Description, // RelatedItems, ProductReviews' AWSDynamoDBProjectionKey = attribute.Key("aws.dynamodb.projection") // AWSDynamoDBProvisionedReadCapacityKey is the attribute Key conforming to // the "aws.dynamodb.provisioned_read_capacity" semantic conventions. It // represents the value of the `ProvisionedThroughput.ReadCapacityUnits` // request parameter. // // Type: double // RequirementLevel: Optional // Stability: experimental // Examples: 1.0, 2.0 AWSDynamoDBProvisionedReadCapacityKey = attribute.Key("aws.dynamodb.provisioned_read_capacity") // AWSDynamoDBProvisionedWriteCapacityKey is the attribute Key conforming // to the "aws.dynamodb.provisioned_write_capacity" semantic conventions. // It represents the value of the // `ProvisionedThroughput.WriteCapacityUnits` request parameter. // // Type: double // RequirementLevel: Optional // Stability: experimental // Examples: 1.0, 2.0 AWSDynamoDBProvisionedWriteCapacityKey = attribute.Key("aws.dynamodb.provisioned_write_capacity") // AWSDynamoDBSelectKey is the attribute Key conforming to the // "aws.dynamodb.select" semantic conventions. It represents the value of // the `Select` request parameter. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'ALL_ATTRIBUTES', 'COUNT' AWSDynamoDBSelectKey = attribute.Key("aws.dynamodb.select") // AWSDynamoDBTableNamesKey is the attribute Key conforming to the // "aws.dynamodb.table_names" semantic conventions. It represents the keys // in the `RequestItems` object field. // // Type: string[] // RequirementLevel: Optional // Stability: experimental // Examples: 'Users', 'Cats' AWSDynamoDBTableNamesKey = attribute.Key("aws.dynamodb.table_names") ) // AWSDynamoDBAttributesToGet returns an attribute KeyValue conforming to // the "aws.dynamodb.attributes_to_get" semantic conventions. It represents the // value of the `AttributesToGet` request parameter. func AWSDynamoDBAttributesToGet(val ...string) attribute.KeyValue { return AWSDynamoDBAttributesToGetKey.StringSlice(val) } // AWSDynamoDBConsistentRead returns an attribute KeyValue conforming to the // "aws.dynamodb.consistent_read" semantic conventions. It represents the value // of the `ConsistentRead` request parameter. func AWSDynamoDBConsistentRead(val bool) attribute.KeyValue { return AWSDynamoDBConsistentReadKey.Bool(val) } // AWSDynamoDBConsumedCapacity returns an attribute KeyValue conforming to // the "aws.dynamodb.consumed_capacity" semantic conventions. It represents the // JSON-serialized value of each item in the `ConsumedCapacity` response field. func AWSDynamoDBConsumedCapacity(val ...string) attribute.KeyValue { return AWSDynamoDBConsumedCapacityKey.StringSlice(val) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
true
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/resource.go
vendor/go.opentelemetry.io/otel/semconv/v1.24.0/resource.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 // Code generated from semantic convention specification. DO NOT EDIT. package semconv // import "go.opentelemetry.io/otel/semconv/v1.24.0" import "go.opentelemetry.io/otel/attribute" // A cloud environment (e.g. GCP, Azure, AWS). const ( // CloudAccountIDKey is the attribute Key conforming to the // "cloud.account.id" semantic conventions. It represents the cloud account // ID the resource is assigned to. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: '111111111111', 'opentelemetry' CloudAccountIDKey = attribute.Key("cloud.account.id") // CloudAvailabilityZoneKey is the attribute Key conforming to the // "cloud.availability_zone" semantic conventions. It represents the cloud // regions often have multiple, isolated locations known as zones to // increase availability. Availability zone represents the zone where the // resource is running. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'us-east-1c' // Note: Availability zones are called "zones" on Alibaba Cloud and Google // Cloud. CloudAvailabilityZoneKey = attribute.Key("cloud.availability_zone") // CloudPlatformKey is the attribute Key conforming to the "cloud.platform" // semantic conventions. It represents the cloud platform in use. // // Type: Enum // RequirementLevel: Optional // Stability: experimental // Note: The prefix of the service SHOULD match the one specified in // `cloud.provider`. CloudPlatformKey = attribute.Key("cloud.platform") // CloudProviderKey is the attribute Key conforming to the "cloud.provider" // semantic conventions. It represents the name of the cloud provider. // // Type: Enum // RequirementLevel: Optional // Stability: experimental CloudProviderKey = attribute.Key("cloud.provider") // CloudRegionKey is the attribute Key conforming to the "cloud.region" // semantic conventions. It represents the geographical region the resource // is running. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'us-central1', 'us-east-1' // Note: Refer to your provider's docs to see the available regions, for // example [Alibaba Cloud // regions](https://www.alibabacloud.com/help/doc-detail/40654.htm), [AWS // regions](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/), // [Azure // regions](https://azure.microsoft.com/global-infrastructure/geographies/), // [Google Cloud regions](https://cloud.google.com/about/locations), or // [Tencent Cloud // regions](https://www.tencentcloud.com/document/product/213/6091). CloudRegionKey = attribute.Key("cloud.region") // CloudResourceIDKey is the attribute Key conforming to the // "cloud.resource_id" semantic conventions. It represents the cloud // provider-specific native identifier of the monitored cloud resource // (e.g. an // [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // on AWS, a [fully qualified resource // ID](https://learn.microsoft.com/rest/api/resources/resources/get-by-id) // on Azure, a [full resource // name](https://cloud.google.com/apis/design/resource_names#full_resource_name) // on GCP) // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'arn:aws:lambda:REGION:ACCOUNT_ID:function:my-function', // '//run.googleapis.com/projects/PROJECT_ID/locations/LOCATION_ID/services/SERVICE_ID', // '/subscriptions/<SUBSCIPTION_GUID>/resourceGroups/<RG>/providers/Microsoft.Web/sites/<FUNCAPP>/functions/<FUNC>' // Note: On some cloud providers, it may not be possible to determine the // full ID at startup, // so it may be necessary to set `cloud.resource_id` as a span attribute // instead. // // The exact value to use for `cloud.resource_id` depends on the cloud // provider. // The following well-known definitions MUST be used if you set this // attribute and they apply: // // * **AWS Lambda:** The function // [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html). // Take care not to use the "invoked ARN" directly but replace any // [alias // suffix](https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html) // with the resolved function version, as the same runtime instance may // be invokable with // multiple different aliases. // * **GCP:** The [URI of the // resource](https://cloud.google.com/iam/docs/full-resource-names) // * **Azure:** The [Fully Qualified Resource // ID](https://docs.microsoft.com/rest/api/resources/resources/get-by-id) // of the invoked function, // *not* the function app, having the form // `/subscriptions/<SUBSCIPTION_GUID>/resourceGroups/<RG>/providers/Microsoft.Web/sites/<FUNCAPP>/functions/<FUNC>`. // This means that a span attribute MUST be used, as an Azure function // app can host multiple functions that would usually share // a TracerProvider. CloudResourceIDKey = attribute.Key("cloud.resource_id") ) var ( // Alibaba Cloud Elastic Compute Service CloudPlatformAlibabaCloudECS = CloudPlatformKey.String("alibaba_cloud_ecs") // Alibaba Cloud Function Compute CloudPlatformAlibabaCloudFc = CloudPlatformKey.String("alibaba_cloud_fc") // Red Hat OpenShift on Alibaba Cloud CloudPlatformAlibabaCloudOpenshift = CloudPlatformKey.String("alibaba_cloud_openshift") // AWS Elastic Compute Cloud CloudPlatformAWSEC2 = CloudPlatformKey.String("aws_ec2") // AWS Elastic Container Service CloudPlatformAWSECS = CloudPlatformKey.String("aws_ecs") // AWS Elastic Kubernetes Service CloudPlatformAWSEKS = CloudPlatformKey.String("aws_eks") // AWS Lambda CloudPlatformAWSLambda = CloudPlatformKey.String("aws_lambda") // AWS Elastic Beanstalk CloudPlatformAWSElasticBeanstalk = CloudPlatformKey.String("aws_elastic_beanstalk") // AWS App Runner CloudPlatformAWSAppRunner = CloudPlatformKey.String("aws_app_runner") // Red Hat OpenShift on AWS (ROSA) CloudPlatformAWSOpenshift = CloudPlatformKey.String("aws_openshift") // Azure Virtual Machines CloudPlatformAzureVM = CloudPlatformKey.String("azure_vm") // Azure Container Instances CloudPlatformAzureContainerInstances = CloudPlatformKey.String("azure_container_instances") // Azure Kubernetes Service CloudPlatformAzureAKS = CloudPlatformKey.String("azure_aks") // Azure Functions CloudPlatformAzureFunctions = CloudPlatformKey.String("azure_functions") // Azure App Service CloudPlatformAzureAppService = CloudPlatformKey.String("azure_app_service") // Azure Red Hat OpenShift CloudPlatformAzureOpenshift = CloudPlatformKey.String("azure_openshift") // Google Bare Metal Solution (BMS) CloudPlatformGCPBareMetalSolution = CloudPlatformKey.String("gcp_bare_metal_solution") // Google Cloud Compute Engine (GCE) CloudPlatformGCPComputeEngine = CloudPlatformKey.String("gcp_compute_engine") // Google Cloud Run CloudPlatformGCPCloudRun = CloudPlatformKey.String("gcp_cloud_run") // Google Cloud Kubernetes Engine (GKE) CloudPlatformGCPKubernetesEngine = CloudPlatformKey.String("gcp_kubernetes_engine") // Google Cloud Functions (GCF) CloudPlatformGCPCloudFunctions = CloudPlatformKey.String("gcp_cloud_functions") // Google Cloud App Engine (GAE) CloudPlatformGCPAppEngine = CloudPlatformKey.String("gcp_app_engine") // Red Hat OpenShift on Google Cloud CloudPlatformGCPOpenshift = CloudPlatformKey.String("gcp_openshift") // Red Hat OpenShift on IBM Cloud CloudPlatformIbmCloudOpenshift = CloudPlatformKey.String("ibm_cloud_openshift") // Tencent Cloud Cloud Virtual Machine (CVM) CloudPlatformTencentCloudCvm = CloudPlatformKey.String("tencent_cloud_cvm") // Tencent Cloud Elastic Kubernetes Service (EKS) CloudPlatformTencentCloudEKS = CloudPlatformKey.String("tencent_cloud_eks") // Tencent Cloud Serverless Cloud Function (SCF) CloudPlatformTencentCloudScf = CloudPlatformKey.String("tencent_cloud_scf") ) var ( // Alibaba Cloud CloudProviderAlibabaCloud = CloudProviderKey.String("alibaba_cloud") // Amazon Web Services CloudProviderAWS = CloudProviderKey.String("aws") // Microsoft Azure CloudProviderAzure = CloudProviderKey.String("azure") // Google Cloud Platform CloudProviderGCP = CloudProviderKey.String("gcp") // Heroku Platform as a Service CloudProviderHeroku = CloudProviderKey.String("heroku") // IBM Cloud CloudProviderIbmCloud = CloudProviderKey.String("ibm_cloud") // Tencent Cloud CloudProviderTencentCloud = CloudProviderKey.String("tencent_cloud") ) // CloudAccountID returns an attribute KeyValue conforming to the // "cloud.account.id" semantic conventions. It represents the cloud account ID // the resource is assigned to. func CloudAccountID(val string) attribute.KeyValue { return CloudAccountIDKey.String(val) } // CloudAvailabilityZone returns an attribute KeyValue conforming to the // "cloud.availability_zone" semantic conventions. It represents the cloud // regions often have multiple, isolated locations known as zones to increase // availability. Availability zone represents the zone where the resource is // running. func CloudAvailabilityZone(val string) attribute.KeyValue { return CloudAvailabilityZoneKey.String(val) } // CloudRegion returns an attribute KeyValue conforming to the // "cloud.region" semantic conventions. It represents the geographical region // the resource is running. func CloudRegion(val string) attribute.KeyValue { return CloudRegionKey.String(val) } // CloudResourceID returns an attribute KeyValue conforming to the // "cloud.resource_id" semantic conventions. It represents the cloud // provider-specific native identifier of the monitored cloud resource (e.g. an // [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html) // on AWS, a [fully qualified resource // ID](https://learn.microsoft.com/rest/api/resources/resources/get-by-id) on // Azure, a [full resource // name](https://cloud.google.com/apis/design/resource_names#full_resource_name) // on GCP) func CloudResourceID(val string) attribute.KeyValue { return CloudResourceIDKey.String(val) } // A container instance. const ( // ContainerCommandKey is the attribute Key conforming to the // "container.command" semantic conventions. It represents the command used // to run the container (i.e. the command name). // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'otelcontribcol' // Note: If using embedded credentials or sensitive data, it is recommended // to remove them to prevent potential leakage. ContainerCommandKey = attribute.Key("container.command") // ContainerCommandArgsKey is the attribute Key conforming to the // "container.command_args" semantic conventions. It represents the all the // command arguments (including the command/executable itself) run by the // container. [2] // // Type: string[] // RequirementLevel: Optional // Stability: experimental // Examples: 'otelcontribcol, --config, config.yaml' ContainerCommandArgsKey = attribute.Key("container.command_args") // ContainerCommandLineKey is the attribute Key conforming to the // "container.command_line" semantic conventions. It represents the full // command run by the container as a single string representing the full // command. [2] // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'otelcontribcol --config config.yaml' ContainerCommandLineKey = attribute.Key("container.command_line") // ContainerIDKey is the attribute Key conforming to the "container.id" // semantic conventions. It represents the container ID. Usually a UUID, as // for example used to [identify Docker // containers](https://docs.docker.com/engine/reference/run/#container-identification). // The UUID might be abbreviated. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'a3bf90e006b2' ContainerIDKey = attribute.Key("container.id") // ContainerImageIDKey is the attribute Key conforming to the // "container.image.id" semantic conventions. It represents the runtime // specific image identifier. Usually a hash algorithm followed by a UUID. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: // 'sha256:19c92d0a00d1b66d897bceaa7319bee0dd38a10a851c60bcec9474aa3f01e50f' // Note: Docker defines a sha256 of the image id; `container.image.id` // corresponds to the `Image` field from the Docker container inspect // [API](https://docs.docker.com/engine/api/v1.43/#tag/Container/operation/ContainerInspect) // endpoint. // K8S defines a link to the container registry repository with digest // `"imageID": "registry.azurecr.io // /namespace/service/dockerfile@sha256:bdeabd40c3a8a492eaf9e8e44d0ebbb84bac7ee25ac0cf8a7159d25f62555625"`. // The ID is assinged by the container runtime and can vary in different // environments. Consider using `oci.manifest.digest` if it is important to // identify the same image in different environments/runtimes. ContainerImageIDKey = attribute.Key("container.image.id") // ContainerImageNameKey is the attribute Key conforming to the // "container.image.name" semantic conventions. It represents the name of // the image the container was built on. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'gcr.io/opentelemetry/operator' ContainerImageNameKey = attribute.Key("container.image.name") // ContainerImageRepoDigestsKey is the attribute Key conforming to the // "container.image.repo_digests" semantic conventions. It represents the // repo digests of the container image as provided by the container // runtime. // // Type: string[] // RequirementLevel: Optional // Stability: experimental // Examples: // 'example@sha256:afcc7f1ac1b49db317a7196c902e61c6c3c4607d63599ee1a82d702d249a0ccb', // 'internal.registry.example.com:5000/example@sha256:b69959407d21e8a062e0416bf13405bb2b71ed7a84dde4158ebafacfa06f5578' // Note: // [Docker](https://docs.docker.com/engine/api/v1.43/#tag/Image/operation/ImageInspect) // and // [CRI](https://github.com/kubernetes/cri-api/blob/c75ef5b473bbe2d0a4fc92f82235efd665ea8e9f/pkg/apis/runtime/v1/api.proto#L1237-L1238) // report those under the `RepoDigests` field. ContainerImageRepoDigestsKey = attribute.Key("container.image.repo_digests") // ContainerImageTagsKey is the attribute Key conforming to the // "container.image.tags" semantic conventions. It represents the container // image tags. An example can be found in [Docker Image // Inspect](https://docs.docker.com/engine/api/v1.43/#tag/Image/operation/ImageInspect). // Should be only the `<tag>` section of the full name for example from // `registry.example.com/my-org/my-image:<tag>`. // // Type: string[] // RequirementLevel: Optional // Stability: experimental // Examples: 'v1.27.1', '3.5.7-0' ContainerImageTagsKey = attribute.Key("container.image.tags") // ContainerNameKey is the attribute Key conforming to the "container.name" // semantic conventions. It represents the container name used by container // runtime. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'opentelemetry-autoconf' ContainerNameKey = attribute.Key("container.name") // ContainerRuntimeKey is the attribute Key conforming to the // "container.runtime" semantic conventions. It represents the container // runtime managing this container. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'docker', 'containerd', 'rkt' ContainerRuntimeKey = attribute.Key("container.runtime") ) // ContainerCommand returns an attribute KeyValue conforming to the // "container.command" semantic conventions. It represents the command used to // run the container (i.e. the command name). func ContainerCommand(val string) attribute.KeyValue { return ContainerCommandKey.String(val) } // ContainerCommandArgs returns an attribute KeyValue conforming to the // "container.command_args" semantic conventions. It represents the all the // command arguments (including the command/executable itself) run by the // container. [2] func ContainerCommandArgs(val ...string) attribute.KeyValue { return ContainerCommandArgsKey.StringSlice(val) } // ContainerCommandLine returns an attribute KeyValue conforming to the // "container.command_line" semantic conventions. It represents the full // command run by the container as a single string representing the full // command. [2] func ContainerCommandLine(val string) attribute.KeyValue { return ContainerCommandLineKey.String(val) } // ContainerID returns an attribute KeyValue conforming to the // "container.id" semantic conventions. It represents the container ID. Usually // a UUID, as for example used to [identify Docker // containers](https://docs.docker.com/engine/reference/run/#container-identification). // The UUID might be abbreviated. func ContainerID(val string) attribute.KeyValue { return ContainerIDKey.String(val) } // ContainerImageID returns an attribute KeyValue conforming to the // "container.image.id" semantic conventions. It represents the runtime // specific image identifier. Usually a hash algorithm followed by a UUID. func ContainerImageID(val string) attribute.KeyValue { return ContainerImageIDKey.String(val) } // ContainerImageName returns an attribute KeyValue conforming to the // "container.image.name" semantic conventions. It represents the name of the // image the container was built on. func ContainerImageName(val string) attribute.KeyValue { return ContainerImageNameKey.String(val) } // ContainerImageRepoDigests returns an attribute KeyValue conforming to the // "container.image.repo_digests" semantic conventions. It represents the repo // digests of the container image as provided by the container runtime. func ContainerImageRepoDigests(val ...string) attribute.KeyValue { return ContainerImageRepoDigestsKey.StringSlice(val) } // ContainerImageTags returns an attribute KeyValue conforming to the // "container.image.tags" semantic conventions. It represents the container // image tags. An example can be found in [Docker Image // Inspect](https://docs.docker.com/engine/api/v1.43/#tag/Image/operation/ImageInspect). // Should be only the `<tag>` section of the full name for example from // `registry.example.com/my-org/my-image:<tag>`. func ContainerImageTags(val ...string) attribute.KeyValue { return ContainerImageTagsKey.StringSlice(val) } // ContainerName returns an attribute KeyValue conforming to the // "container.name" semantic conventions. It represents the container name used // by container runtime. func ContainerName(val string) attribute.KeyValue { return ContainerNameKey.String(val) } // ContainerRuntime returns an attribute KeyValue conforming to the // "container.runtime" semantic conventions. It represents the container // runtime managing this container. func ContainerRuntime(val string) attribute.KeyValue { return ContainerRuntimeKey.String(val) } // Describes device attributes. const ( // DeviceIDKey is the attribute Key conforming to the "device.id" semantic // conventions. It represents a unique identifier representing the device // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: '2ab2916d-a51f-4ac8-80ee-45ac31a28092' // Note: The device identifier MUST only be defined using the values // outlined below. This value is not an advertising identifier and MUST NOT // be used as such. On iOS (Swift or Objective-C), this value MUST be equal // to the [vendor // identifier](https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor). // On Android (Java or Kotlin), this value MUST be equal to the Firebase // Installation ID or a globally unique UUID which is persisted across // sessions in your application. More information can be found // [here](https://developer.android.com/training/articles/user-data-ids) on // best practices and exact implementation details. Caution should be taken // when storing personal data or anything which can identify a user. GDPR // and data protection laws may apply, ensure you do your own due // diligence. DeviceIDKey = attribute.Key("device.id") // DeviceManufacturerKey is the attribute Key conforming to the // "device.manufacturer" semantic conventions. It represents the name of // the device manufacturer // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'Apple', 'Samsung' // Note: The Android OS provides this field via // [Build](https://developer.android.com/reference/android/os/Build#MANUFACTURER). // iOS apps SHOULD hardcode the value `Apple`. DeviceManufacturerKey = attribute.Key("device.manufacturer") // DeviceModelIdentifierKey is the attribute Key conforming to the // "device.model.identifier" semantic conventions. It represents the model // identifier for the device // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'iPhone3,4', 'SM-G920F' // Note: It's recommended this value represents a machine-readable version // of the model identifier rather than the market or consumer-friendly name // of the device. DeviceModelIdentifierKey = attribute.Key("device.model.identifier") // DeviceModelNameKey is the attribute Key conforming to the // "device.model.name" semantic conventions. It represents the marketing // name for the device model // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'iPhone 6s Plus', 'Samsung Galaxy S6' // Note: It's recommended this value represents a human-readable version of // the device model rather than a machine-readable alternative. DeviceModelNameKey = attribute.Key("device.model.name") ) // DeviceID returns an attribute KeyValue conforming to the "device.id" // semantic conventions. It represents a unique identifier representing the // device func DeviceID(val string) attribute.KeyValue { return DeviceIDKey.String(val) } // DeviceManufacturer returns an attribute KeyValue conforming to the // "device.manufacturer" semantic conventions. It represents the name of the // device manufacturer func DeviceManufacturer(val string) attribute.KeyValue { return DeviceManufacturerKey.String(val) } // DeviceModelIdentifier returns an attribute KeyValue conforming to the // "device.model.identifier" semantic conventions. It represents the model // identifier for the device func DeviceModelIdentifier(val string) attribute.KeyValue { return DeviceModelIdentifierKey.String(val) } // DeviceModelName returns an attribute KeyValue conforming to the // "device.model.name" semantic conventions. It represents the marketing name // for the device model func DeviceModelName(val string) attribute.KeyValue { return DeviceModelNameKey.String(val) } // A host is defined as a computing instance. For example, physical servers, // virtual machines, switches or disk array. const ( // HostArchKey is the attribute Key conforming to the "host.arch" semantic // conventions. It represents the CPU architecture the host system is // running on. // // Type: Enum // RequirementLevel: Optional // Stability: experimental HostArchKey = attribute.Key("host.arch") // HostCPUCacheL2SizeKey is the attribute Key conforming to the // "host.cpu.cache.l2.size" semantic conventions. It represents the amount // of level 2 memory cache available to the processor (in Bytes). // // Type: int // RequirementLevel: Optional // Stability: experimental // Examples: 12288000 HostCPUCacheL2SizeKey = attribute.Key("host.cpu.cache.l2.size") // HostCPUFamilyKey is the attribute Key conforming to the // "host.cpu.family" semantic conventions. It represents the family or // generation of the CPU. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: '6', 'PA-RISC 1.1e' HostCPUFamilyKey = attribute.Key("host.cpu.family") // HostCPUModelIDKey is the attribute Key conforming to the // "host.cpu.model.id" semantic conventions. It represents the model // identifier. It provides more granular information about the CPU, // distinguishing it from other CPUs within the same family. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: '6', '9000/778/B180L' HostCPUModelIDKey = attribute.Key("host.cpu.model.id") // HostCPUModelNameKey is the attribute Key conforming to the // "host.cpu.model.name" semantic conventions. It represents the model // designation of the processor. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: '11th Gen Intel(R) Core(TM) i7-1185G7 @ 3.00GHz' HostCPUModelNameKey = attribute.Key("host.cpu.model.name") // HostCPUSteppingKey is the attribute Key conforming to the // "host.cpu.stepping" semantic conventions. It represents the stepping or // core revisions. // // Type: int // RequirementLevel: Optional // Stability: experimental // Examples: 1 HostCPUSteppingKey = attribute.Key("host.cpu.stepping") // HostCPUVendorIDKey is the attribute Key conforming to the // "host.cpu.vendor.id" semantic conventions. It represents the processor // manufacturer identifier. A maximum 12-character string. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'GenuineIntel' // Note: [CPUID](https://wiki.osdev.org/CPUID) command returns the vendor // ID string in EBX, EDX and ECX registers. Writing these to memory in this // order results in a 12-character string. HostCPUVendorIDKey = attribute.Key("host.cpu.vendor.id") // HostIDKey is the attribute Key conforming to the "host.id" semantic // conventions. It represents the unique host ID. For Cloud, this must be // the instance_id assigned by the cloud provider. For non-containerized // systems, this should be the `machine-id`. See the table below for the // sources to use to determine the `machine-id` based on operating system. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'fdbf79e8af94cb7f9e8df36789187052' HostIDKey = attribute.Key("host.id") // HostImageIDKey is the attribute Key conforming to the "host.image.id" // semantic conventions. It represents the vM image ID or host OS image ID. // For Cloud, this value is from the provider. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'ami-07b06b442921831e5' HostImageIDKey = attribute.Key("host.image.id") // HostImageNameKey is the attribute Key conforming to the // "host.image.name" semantic conventions. It represents the name of the VM // image or OS install the host was instantiated from. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'infra-ami-eks-worker-node-7d4ec78312', 'CentOS-8-x86_64-1905' HostImageNameKey = attribute.Key("host.image.name") // HostImageVersionKey is the attribute Key conforming to the // "host.image.version" semantic conventions. It represents the version // string of the VM image or host OS as defined in [Version // Attributes](/docs/resource/README.md#version-attributes). // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: '0.1' HostImageVersionKey = attribute.Key("host.image.version") // HostIPKey is the attribute Key conforming to the "host.ip" semantic // conventions. It represents the available IP addresses of the host, // excluding loopback interfaces. // // Type: string[] // RequirementLevel: Optional // Stability: experimental // Examples: '192.168.1.140', 'fe80::abc2:4a28:737a:609e' // Note: IPv4 Addresses MUST be specified in dotted-quad notation. IPv6 // addresses MUST be specified in the [RFC // 5952](https://www.rfc-editor.org/rfc/rfc5952.html) format. HostIPKey = attribute.Key("host.ip") // HostMacKey is the attribute Key conforming to the "host.mac" semantic // conventions. It represents the available MAC addresses of the host, // excluding loopback interfaces. // // Type: string[] // RequirementLevel: Optional // Stability: experimental // Examples: 'AC-DE-48-23-45-67', 'AC-DE-48-23-45-67-01-9F' // Note: MAC Addresses MUST be represented in [IEEE RA hexadecimal // form](https://standards.ieee.org/wp-content/uploads/import/documents/tutorials/eui.pdf): // as hyphen-separated octets in uppercase hexadecimal form from most to // least significant. HostMacKey = attribute.Key("host.mac") // HostNameKey is the attribute Key conforming to the "host.name" semantic // conventions. It represents the name of the host. On Unix systems, it may // contain what the hostname command returns, or the fully qualified // hostname, or another name specified by the user. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'opentelemetry-test' HostNameKey = attribute.Key("host.name") // HostTypeKey is the attribute Key conforming to the "host.type" semantic // conventions. It represents the type of host. For Cloud, this must be the // machine type. // // Type: string // RequirementLevel: Optional // Stability: experimental // Examples: 'n1-standard-1' HostTypeKey = attribute.Key("host.type") ) var ( // AMD64 HostArchAMD64 = HostArchKey.String("amd64") // ARM32 HostArchARM32 = HostArchKey.String("arm32") // ARM64 HostArchARM64 = HostArchKey.String("arm64") // Itanium HostArchIA64 = HostArchKey.String("ia64") // 32-bit PowerPC HostArchPPC32 = HostArchKey.String("ppc32") // 64-bit PowerPC HostArchPPC64 = HostArchKey.String("ppc64") // IBM z/Architecture HostArchS390x = HostArchKey.String("s390x") // 32-bit x86 HostArchX86 = HostArchKey.String("x86") ) // HostCPUCacheL2Size returns an attribute KeyValue conforming to the // "host.cpu.cache.l2.size" semantic conventions. It represents the amount of // level 2 memory cache available to the processor (in Bytes). func HostCPUCacheL2Size(val int) attribute.KeyValue { return HostCPUCacheL2SizeKey.Int(val) } // HostCPUFamily returns an attribute KeyValue conforming to the // "host.cpu.family" semantic conventions. It represents the family or // generation of the CPU. func HostCPUFamily(val string) attribute.KeyValue { return HostCPUFamilyKey.String(val) } // HostCPUModelID returns an attribute KeyValue conforming to the // "host.cpu.model.id" semantic conventions. It represents the model // identifier. It provides more granular information about the CPU, // distinguishing it from other CPUs within the same family. func HostCPUModelID(val string) attribute.KeyValue { return HostCPUModelIDKey.String(val) } // HostCPUModelName returns an attribute KeyValue conforming to the // "host.cpu.model.name" semantic conventions. It represents the model // designation of the processor. func HostCPUModelName(val string) attribute.KeyValue { return HostCPUModelNameKey.String(val) } // HostCPUStepping returns an attribute KeyValue conforming to the // "host.cpu.stepping" semantic conventions. It represents the stepping or core // revisions. func HostCPUStepping(val int) attribute.KeyValue { return HostCPUSteppingKey.Int(val) } // HostCPUVendorID returns an attribute KeyValue conforming to the // "host.cpu.vendor.id" semantic conventions. It represents the processor // manufacturer identifier. A maximum 12-character string. func HostCPUVendorID(val string) attribute.KeyValue { return HostCPUVendorIDKey.String(val) } // HostID returns an attribute KeyValue conforming to the "host.id" semantic // conventions. It represents the unique host ID. For Cloud, this must be the // instance_id assigned by the cloud provider. For non-containerized systems, // this should be the `machine-id`. See the table below for the sources to use // to determine the `machine-id` based on operating system. func HostID(val string) attribute.KeyValue { return HostIDKey.String(val) } // HostImageID returns an attribute KeyValue conforming to the // "host.image.id" semantic conventions. It represents the vM image ID or host // OS image ID. For Cloud, this value is from the provider. func HostImageID(val string) attribute.KeyValue { return HostImageIDKey.String(val) } // HostImageName returns an attribute KeyValue conforming to the // "host.image.name" semantic conventions. It represents the name of the VM // image or OS install the host was instantiated from. func HostImageName(val string) attribute.KeyValue { return HostImageNameKey.String(val) } // HostImageVersion returns an attribute KeyValue conforming to the
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
true
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/event.go
vendor/go.opentelemetry.io/otel/semconv/v1.24.0/event.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 // Code generated from semantic convention specification. DO NOT EDIT. package semconv // import "go.opentelemetry.io/otel/semconv/v1.24.0" import "go.opentelemetry.io/otel/attribute" // This event represents an occurrence of a lifecycle transition on the iOS // platform. const ( // IosStateKey is the attribute Key conforming to the "ios.state" semantic // conventions. It represents the this attribute represents the state the // application has transitioned into at the occurrence of the event. // // Type: Enum // RequirementLevel: Required // Stability: experimental // Note: The iOS lifecycle states are defined in the [UIApplicationDelegate // documentation](https://developer.apple.com/documentation/uikit/uiapplicationdelegate#1656902), // and from which the `OS terminology` column values are derived. IosStateKey = attribute.Key("ios.state") ) var ( // The app has become `active`. Associated with UIKit notification `applicationDidBecomeActive` IosStateActive = IosStateKey.String("active") // The app is now `inactive`. Associated with UIKit notification `applicationWillResignActive` IosStateInactive = IosStateKey.String("inactive") // The app is now in the background. This value is associated with UIKit notification `applicationDidEnterBackground` IosStateBackground = IosStateKey.String("background") // The app is now in the foreground. This value is associated with UIKit notification `applicationWillEnterForeground` IosStateForeground = IosStateKey.String("foreground") // The app is about to terminate. Associated with UIKit notification `applicationWillTerminate` IosStateTerminate = IosStateKey.String("terminate") ) // This event represents an occurrence of a lifecycle transition on the Android // platform. const ( // AndroidStateKey is the attribute Key conforming to the "android.state" // semantic conventions. It represents the this attribute represents the // state the application has transitioned into at the occurrence of the // event. // // Type: Enum // RequirementLevel: Required // Stability: experimental // Note: The Android lifecycle states are defined in [Activity lifecycle // callbacks](https://developer.android.com/guide/components/activities/activity-lifecycle#lc), // and from which the `OS identifiers` are derived. AndroidStateKey = attribute.Key("android.state") ) var ( // Any time before Activity.onResume() or, if the app has no Activity, Context.startService() has been called in the app for the first time AndroidStateCreated = AndroidStateKey.String("created") // Any time after Activity.onPause() or, if the app has no Activity, Context.stopService() has been called when the app was in the foreground state AndroidStateBackground = AndroidStateKey.String("background") // Any time after Activity.onResume() or, if the app has no Activity, Context.startService() has been called when the app was in either the created or background states AndroidStateForeground = AndroidStateKey.String("foreground") ) // This semantic convention defines the attributes used to represent a feature // flag evaluation as an event. const ( // FeatureFlagKeyKey is the attribute Key conforming to the // "feature_flag.key" semantic conventions. It represents the unique // identifier of the feature flag. // // Type: string // RequirementLevel: Required // Stability: experimental // Examples: 'logo-color' FeatureFlagKeyKey = attribute.Key("feature_flag.key") // FeatureFlagProviderNameKey is the attribute Key conforming to the // "feature_flag.provider_name" semantic conventions. It represents the // name of the service provider that performs the flag evaluation. // // Type: string // RequirementLevel: Recommended // Stability: experimental // Examples: 'Flag Manager' FeatureFlagProviderNameKey = attribute.Key("feature_flag.provider_name") // FeatureFlagVariantKey is the attribute Key conforming to the // "feature_flag.variant" semantic conventions. It represents the sHOULD be // a semantic identifier for a value. If one is unavailable, a stringified // version of the value can be used. // // Type: string // RequirementLevel: Recommended // Stability: experimental // Examples: 'red', 'true', 'on' // Note: A semantic identifier, commonly referred to as a variant, provides // a means // for referring to a value without including the value itself. This can // provide additional context for understanding the meaning behind a value. // For example, the variant `red` maybe be used for the value `#c05543`. // // A stringified version of the value can be used in situations where a // semantic identifier is unavailable. String representation of the value // should be determined by the implementer. FeatureFlagVariantKey = attribute.Key("feature_flag.variant") ) // FeatureFlagKey returns an attribute KeyValue conforming to the // "feature_flag.key" semantic conventions. It represents the unique identifier // of the feature flag. func FeatureFlagKey(val string) attribute.KeyValue { return FeatureFlagKeyKey.String(val) } // FeatureFlagProviderName returns an attribute KeyValue conforming to the // "feature_flag.provider_name" semantic conventions. It represents the name of // the service provider that performs the flag evaluation. func FeatureFlagProviderName(val string) attribute.KeyValue { return FeatureFlagProviderNameKey.String(val) } // FeatureFlagVariant returns an attribute KeyValue conforming to the // "feature_flag.variant" semantic conventions. It represents the sHOULD be a // semantic identifier for a value. If one is unavailable, a stringified // version of the value can be used. func FeatureFlagVariant(val string) attribute.KeyValue { return FeatureFlagVariantKey.String(val) } // RPC received/sent message. const ( // MessageCompressedSizeKey is the attribute Key conforming to the // "message.compressed_size" semantic conventions. It represents the // compressed size of the message in bytes. // // Type: int // RequirementLevel: Optional // Stability: experimental MessageCompressedSizeKey = attribute.Key("message.compressed_size") // MessageIDKey is the attribute Key conforming to the "message.id" // semantic conventions. It represents the mUST be calculated as two // different counters starting from `1` one for sent messages and one for // received message. // // Type: int // RequirementLevel: Optional // Stability: experimental // Note: This way we guarantee that the values will be consistent between // different implementations. MessageIDKey = attribute.Key("message.id") // MessageTypeKey is the attribute Key conforming to the "message.type" // semantic conventions. It represents the whether this is a received or // sent message. // // Type: Enum // RequirementLevel: Optional // Stability: experimental MessageTypeKey = attribute.Key("message.type") // MessageUncompressedSizeKey is the attribute Key conforming to the // "message.uncompressed_size" semantic conventions. It represents the // uncompressed size of the message in bytes. // // Type: int // RequirementLevel: Optional // Stability: experimental MessageUncompressedSizeKey = attribute.Key("message.uncompressed_size") ) var ( // sent MessageTypeSent = MessageTypeKey.String("SENT") // received MessageTypeReceived = MessageTypeKey.String("RECEIVED") ) // MessageCompressedSize returns an attribute KeyValue conforming to the // "message.compressed_size" semantic conventions. It represents the compressed // size of the message in bytes. func MessageCompressedSize(val int) attribute.KeyValue { return MessageCompressedSizeKey.Int(val) } // MessageID returns an attribute KeyValue conforming to the "message.id" // semantic conventions. It represents the mUST be calculated as two different // counters starting from `1` one for sent messages and one for received // message. func MessageID(val int) attribute.KeyValue { return MessageIDKey.Int(val) } // MessageUncompressedSize returns an attribute KeyValue conforming to the // "message.uncompressed_size" semantic conventions. It represents the // uncompressed size of the message in bytes. func MessageUncompressedSize(val int) attribute.KeyValue { return MessageUncompressedSizeKey.Int(val) }
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/exception.go
vendor/go.opentelemetry.io/otel/semconv/v1.24.0/exception.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package semconv // import "go.opentelemetry.io/otel/semconv/v1.24.0" const ( // ExceptionEventName is the name of the Span event representing an exception. ExceptionEventName = "exception" )
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/doc.go
vendor/go.opentelemetry.io/otel/semconv/v1.24.0/doc.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 // Package semconv implements OpenTelemetry semantic conventions. // // OpenTelemetry semantic conventions are agreed standardized naming // patterns for OpenTelemetry things. This package represents the v1.24.0 // version of the OpenTelemetry semantic conventions. package semconv // import "go.opentelemetry.io/otel/semconv/v1.24.0"
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
jesseduffield/lazydocker
https://github.com/jesseduffield/lazydocker/blob/f4fc3669ca8eb67aa350a76503397192bf26f057/vendor/go.opentelemetry.io/otel/semconv/v1.24.0/schema.go
vendor/go.opentelemetry.io/otel/semconv/v1.24.0/schema.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package semconv // import "go.opentelemetry.io/otel/semconv/v1.24.0" // SchemaURL is the schema URL that matches the version of the semantic conventions // that this package defines. Semconv packages starting from v1.4.0 must declare // non-empty schema URL in the form https://opentelemetry.io/schemas/<version> const SchemaURL = "https://opentelemetry.io/schemas/1.24.0"
go
MIT
f4fc3669ca8eb67aa350a76503397192bf26f057
2026-01-07T08:35:43.570558Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/cmd/memos/main.go
cmd/memos/main.go
package main import ( "context" "fmt" "log/slog" "net/http" "os" "os/signal" "syscall" "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/usememos/memos/internal/profile" "github.com/usememos/memos/internal/version" "github.com/usememos/memos/server" "github.com/usememos/memos/store" "github.com/usememos/memos/store/db" ) var ( rootCmd = &cobra.Command{ Use: "memos", Short: `An open source, lightweight note-taking service. Easily capture and share your great thoughts.`, Run: func(_ *cobra.Command, _ []string) { instanceProfile := &profile.Profile{ Mode: viper.GetString("mode"), Addr: viper.GetString("addr"), Port: viper.GetInt("port"), UNIXSock: viper.GetString("unix-sock"), Data: viper.GetString("data"), Driver: viper.GetString("driver"), DSN: viper.GetString("dsn"), InstanceURL: viper.GetString("instance-url"), Version: version.GetCurrentVersion(viper.GetString("mode")), } if err := instanceProfile.Validate(); err != nil { panic(err) } ctx, cancel := context.WithCancel(context.Background()) dbDriver, err := db.NewDBDriver(instanceProfile) if err != nil { cancel() slog.Error("failed to create db driver", "error", err) return } storeInstance := store.New(dbDriver, instanceProfile) if err := storeInstance.Migrate(ctx); err != nil { cancel() slog.Error("failed to migrate", "error", err) return } s, err := server.NewServer(ctx, instanceProfile, storeInstance) if err != nil { cancel() slog.Error("failed to create server", "error", err) return } c := make(chan os.Signal, 1) // Trigger graceful shutdown on SIGINT or SIGTERM. // The default signal sent by the `kill` command is SIGTERM, // which is taken as the graceful shutdown signal for many systems, eg., Kubernetes, Gunicorn. signal.Notify(c, os.Interrupt, syscall.SIGTERM) if err := s.Start(ctx); err != nil { if err != http.ErrServerClosed { slog.Error("failed to start server", "error", err) cancel() } } printGreetings(instanceProfile) go func() { <-c s.Shutdown(ctx) cancel() }() // Wait for CTRL-C. <-ctx.Done() }, } ) func init() { viper.SetDefault("mode", "dev") viper.SetDefault("driver", "sqlite") viper.SetDefault("port", 8081) rootCmd.PersistentFlags().String("mode", "dev", `mode of server, can be "prod" or "dev" or "demo"`) rootCmd.PersistentFlags().String("addr", "", "address of server") rootCmd.PersistentFlags().Int("port", 8081, "port of server") rootCmd.PersistentFlags().String("unix-sock", "", "path to the unix socket, overrides --addr and --port") rootCmd.PersistentFlags().String("data", "", "data directory") rootCmd.PersistentFlags().String("driver", "sqlite", "database driver") rootCmd.PersistentFlags().String("dsn", "", "database source name(aka. DSN)") rootCmd.PersistentFlags().String("instance-url", "", "the url of your memos instance") if err := viper.BindPFlag("mode", rootCmd.PersistentFlags().Lookup("mode")); err != nil { panic(err) } if err := viper.BindPFlag("addr", rootCmd.PersistentFlags().Lookup("addr")); err != nil { panic(err) } if err := viper.BindPFlag("port", rootCmd.PersistentFlags().Lookup("port")); err != nil { panic(err) } if err := viper.BindPFlag("unix-sock", rootCmd.PersistentFlags().Lookup("unix-sock")); err != nil { panic(err) } if err := viper.BindPFlag("data", rootCmd.PersistentFlags().Lookup("data")); err != nil { panic(err) } if err := viper.BindPFlag("driver", rootCmd.PersistentFlags().Lookup("driver")); err != nil { panic(err) } if err := viper.BindPFlag("dsn", rootCmd.PersistentFlags().Lookup("dsn")); err != nil { panic(err) } if err := viper.BindPFlag("instance-url", rootCmd.PersistentFlags().Lookup("instance-url")); err != nil { panic(err) } viper.SetEnvPrefix("memos") viper.AutomaticEnv() if err := viper.BindEnv("instance-url", "MEMOS_INSTANCE_URL"); err != nil { panic(err) } } func printGreetings(profile *profile.Profile) { fmt.Printf("Memos %s started successfully!\n", profile.Version) if profile.IsDev() { fmt.Fprint(os.Stderr, "Development mode is enabled\n") if profile.DSN != "" { fmt.Fprintf(os.Stderr, "Database: %s\n", profile.DSN) } } // Server information fmt.Printf("Data directory: %s\n", profile.Data) fmt.Printf("Database driver: %s\n", profile.Driver) fmt.Printf("Mode: %s\n", profile.Mode) // Connection information if len(profile.UNIXSock) == 0 { if len(profile.Addr) == 0 { fmt.Printf("Server running on port %d\n", profile.Port) fmt.Printf("Access your memos at: http://localhost:%d\n", profile.Port) } else { fmt.Printf("Server running on %s:%d\n", profile.Addr, profile.Port) fmt.Printf("Access your memos at: http://%s:%d\n", profile.Addr, profile.Port) } } else { fmt.Printf("Server running on unix socket: %s\n", profile.UNIXSock) } fmt.Println() fmt.Printf("Documentation: %s\n", "https://usememos.com") fmt.Printf("Source code: %s\n", "https://github.com/usememos/memos") fmt.Println("\nHappy note-taking!") } func main() { if err := rootCmd.Execute(); err != nil { panic(err) } }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/storage/s3/s3.go
plugin/storage/s3/s3.go
package s3 import ( "context" "io" "time" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/credentials" "github.com/aws/aws-sdk-go-v2/feature/s3/manager" "github.com/aws/aws-sdk-go-v2/service/s3" "github.com/pkg/errors" storepb "github.com/usememos/memos/proto/gen/store" ) type Client struct { Client *s3.Client Bucket *string } func NewClient(ctx context.Context, s3Config *storepb.StorageS3Config) (*Client, error) { cfg, err := config.LoadDefaultConfig(ctx, config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(s3Config.AccessKeyId, s3Config.AccessKeySecret, "")), config.WithRegion(s3Config.Region), ) if err != nil { return nil, errors.Wrap(err, "failed to load s3 config") } client := s3.NewFromConfig(cfg, func(o *s3.Options) { o.BaseEndpoint = aws.String(s3Config.Endpoint) o.UsePathStyle = s3Config.UsePathStyle o.RequestChecksumCalculation = aws.RequestChecksumCalculationWhenRequired o.ResponseChecksumValidation = aws.ResponseChecksumValidationWhenRequired }) return &Client{ Client: client, Bucket: aws.String(s3Config.Bucket), }, nil } // UploadObject uploads an object to S3. func (c *Client) UploadObject(ctx context.Context, key string, fileType string, content io.Reader) (string, error) { uploader := manager.NewUploader(c.Client) putInput := s3.PutObjectInput{ Bucket: c.Bucket, Key: aws.String(key), ContentType: aws.String(fileType), Body: content, } result, err := uploader.Upload(ctx, &putInput) if err != nil { return "", err } resultKey := result.Key if resultKey == nil || *resultKey == "" { return "", errors.New("failed to get file key") } return *resultKey, nil } // PresignGetObject presigns an object in S3. func (c *Client) PresignGetObject(ctx context.Context, key string) (string, error) { presignClient := s3.NewPresignClient(c.Client) presignResult, err := presignClient.PresignGetObject(ctx, &s3.GetObjectInput{ Bucket: aws.String(*c.Bucket), Key: aws.String(key), }, func(opts *s3.PresignOptions) { // Set the expiration time of the presigned URL to 5 days. // Reference: https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-query-string-auth.html opts.Expires = time.Duration(5 * 24 * time.Hour) }) if err != nil { return "", errors.Wrap(err, "failed to presign put object") } return presignResult.URL, nil } // GetObject retrieves an object from S3. func (c *Client) GetObject(ctx context.Context, key string) ([]byte, error) { downloader := manager.NewDownloader(c.Client) buffer := manager.NewWriteAtBuffer([]byte{}) _, err := downloader.Download(ctx, buffer, &s3.GetObjectInput{ Bucket: c.Bucket, Key: aws.String(key), }) if err != nil { return nil, errors.Wrap(err, "failed to download object") } return buffer.Bytes(), nil } // GetObjectStream retrieves an object from S3 as a stream. func (c *Client) GetObjectStream(ctx context.Context, key string) (io.ReadCloser, error) { output, err := c.Client.GetObject(ctx, &s3.GetObjectInput{ Bucket: c.Bucket, Key: aws.String(key), }) if err != nil { return nil, errors.Wrap(err, "failed to get object") } return output.Body, nil } // DeleteObject deletes an object in S3. func (c *Client) DeleteObject(ctx context.Context, key string) error { _, err := c.Client.DeleteObject(ctx, &s3.DeleteObjectInput{ Bucket: c.Bucket, Key: aws.String(key), }) if err != nil { return errors.Wrap(err, "failed to delete object") } return nil }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/httpgetter/html_meta_test.go
plugin/httpgetter/html_meta_test.go
package httpgetter import ( "errors" "testing" "github.com/stretchr/testify/require" ) func TestGetHTMLMeta(t *testing.T) { tests := []struct { urlStr string htmlMeta HTMLMeta }{} for _, test := range tests { metadata, err := GetHTMLMeta(test.urlStr) require.NoError(t, err) require.Equal(t, test.htmlMeta, *metadata) } } func TestGetHTMLMetaForInternal(t *testing.T) { // test for internal IP if _, err := GetHTMLMeta("http://192.168.0.1"); !errors.Is(err, ErrInternalIP) { t.Errorf("Expected error for internal IP, got %v", err) } // test for resolved internal IP if _, err := GetHTMLMeta("http://localhost"); !errors.Is(err, ErrInternalIP) { t.Errorf("Expected error for resolved internal IP, got %v", err) } }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/httpgetter/image.go
plugin/httpgetter/image.go
package httpgetter import ( "errors" "io" "net/http" "net/url" "strings" ) type Image struct { Blob []byte Mediatype string } func GetImage(urlStr string) (*Image, error) { if _, err := url.Parse(urlStr); err != nil { return nil, err } response, err := http.Get(urlStr) if err != nil { return nil, err } defer response.Body.Close() mediatype, err := getMediatype(response) if err != nil { return nil, err } if !strings.HasPrefix(mediatype, "image/") { return nil, errors.New("wrong image mediatype") } bodyBytes, err := io.ReadAll(response.Body) if err != nil { return nil, err } image := &Image{ Blob: bodyBytes, Mediatype: mediatype, } return image, nil }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/httpgetter/util.go
plugin/httpgetter/util.go
package httpgetter import ( "mime" "net/http" ) func getMediatype(response *http.Response) (string, error) { contentType := response.Header.Get("content-type") mediatype, _, err := mime.ParseMediaType(contentType) if err != nil { return "", err } return mediatype, nil }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/httpgetter/http_getter.go
plugin/httpgetter/http_getter.go
package httpgetter
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/httpgetter/html_meta.go
plugin/httpgetter/html_meta.go
package httpgetter import ( "fmt" "io" "net" "net/http" "net/url" "github.com/pkg/errors" "golang.org/x/net/html" "golang.org/x/net/html/atom" ) var ErrInternalIP = errors.New("internal IP addresses are not allowed") var httpClient = &http.Client{ CheckRedirect: func(req *http.Request, via []*http.Request) error { if err := validateURL(req.URL.String()); err != nil { return errors.Wrap(err, "redirect to internal IP") } if len(via) >= 10 { return errors.New("too many redirects") } return nil }, } type HTMLMeta struct { Title string `json:"title"` Description string `json:"description"` Image string `json:"image"` } func GetHTMLMeta(urlStr string) (*HTMLMeta, error) { if err := validateURL(urlStr); err != nil { return nil, err } response, err := httpClient.Get(urlStr) if err != nil { return nil, err } defer response.Body.Close() mediatype, err := getMediatype(response) if err != nil { return nil, err } if mediatype != "text/html" { return nil, errors.New("not a HTML page") } // TODO: limit the size of the response body htmlMeta := extractHTMLMeta(response.Body) enrichSiteMeta(response.Request.URL, htmlMeta) return htmlMeta, nil } func extractHTMLMeta(resp io.Reader) *HTMLMeta { tokenizer := html.NewTokenizer(resp) htmlMeta := new(HTMLMeta) for { tokenType := tokenizer.Next() if tokenType == html.ErrorToken { break } else if tokenType == html.StartTagToken || tokenType == html.SelfClosingTagToken { token := tokenizer.Token() if token.DataAtom == atom.Body { break } if token.DataAtom == atom.Title { tokenizer.Next() token := tokenizer.Token() htmlMeta.Title = token.Data } else if token.DataAtom == atom.Meta { description, ok := extractMetaProperty(token, "description") if ok { htmlMeta.Description = description } ogTitle, ok := extractMetaProperty(token, "og:title") if ok { htmlMeta.Title = ogTitle } ogDescription, ok := extractMetaProperty(token, "og:description") if ok { htmlMeta.Description = ogDescription } ogImage, ok := extractMetaProperty(token, "og:image") if ok { htmlMeta.Image = ogImage } } } } return htmlMeta } func extractMetaProperty(token html.Token, prop string) (content string, ok bool) { content, ok = "", false for _, attr := range token.Attr { if attr.Key == "property" && attr.Val == prop { ok = true } if attr.Key == "content" { content = attr.Val } } return content, ok } func validateURL(urlStr string) error { u, err := url.Parse(urlStr) if err != nil { return errors.New("invalid URL format") } if u.Scheme != "http" && u.Scheme != "https" { return errors.New("only http/https protocols are allowed") } host := u.Hostname() if host == "" { return errors.New("empty hostname") } // check if the hostname is an IP if ip := net.ParseIP(host); ip != nil { if ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() { return errors.Wrap(ErrInternalIP, ip.String()) } return nil } // check if it's a hostname, resolve it and check all returned IPs ips, err := net.LookupIP(host) if err != nil { return errors.Errorf("failed to resolve hostname: %v", err) } for _, ip := range ips { if ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() { return errors.Wrapf(ErrInternalIP, "host=%s, ip=%s", host, ip.String()) } } return nil } func enrichSiteMeta(url *url.URL, meta *HTMLMeta) { if url.Hostname() == "www.youtube.com" { if url.Path == "/watch" { vid := url.Query().Get("v") if vid != "" { meta.Image = fmt.Sprintf("https://img.youtube.com/vi/%s/mqdefault.jpg", vid) } } } }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/filter/parser.go
plugin/filter/parser.go
package filter import ( "time" "github.com/pkg/errors" exprv1 "google.golang.org/genproto/googleapis/api/expr/v1alpha1" ) func buildCondition(expr *exprv1.Expr, schema Schema) (Condition, error) { switch v := expr.ExprKind.(type) { case *exprv1.Expr_CallExpr: return buildCallCondition(v.CallExpr, schema) case *exprv1.Expr_ConstExpr: val, err := getConstValue(expr) if err != nil { return nil, err } switch v := val.(type) { case bool: return &ConstantCondition{Value: v}, nil case int64: return &ConstantCondition{Value: v != 0}, nil case float64: return &ConstantCondition{Value: v != 0}, nil default: return nil, errors.New("filter must evaluate to a boolean value") } case *exprv1.Expr_IdentExpr: name := v.IdentExpr.GetName() field, ok := schema.Field(name) if !ok { return nil, errors.Errorf("unknown identifier %q", name) } if field.Type != FieldTypeBool { return nil, errors.Errorf("identifier %q is not boolean", name) } return &FieldPredicateCondition{Field: name}, nil default: return nil, errors.New("unsupported top-level expression") } } func buildCallCondition(call *exprv1.Expr_Call, schema Schema) (Condition, error) { switch call.Function { case "_&&_": if len(call.Args) != 2 { return nil, errors.New("logical AND expects two arguments") } left, err := buildCondition(call.Args[0], schema) if err != nil { return nil, err } right, err := buildCondition(call.Args[1], schema) if err != nil { return nil, err } return &LogicalCondition{ Operator: LogicalAnd, Left: left, Right: right, }, nil case "_||_": if len(call.Args) != 2 { return nil, errors.New("logical OR expects two arguments") } left, err := buildCondition(call.Args[0], schema) if err != nil { return nil, err } right, err := buildCondition(call.Args[1], schema) if err != nil { return nil, err } return &LogicalCondition{ Operator: LogicalOr, Left: left, Right: right, }, nil case "!_": if len(call.Args) != 1 { return nil, errors.New("logical NOT expects one argument") } child, err := buildCondition(call.Args[0], schema) if err != nil { return nil, err } return &NotCondition{Expr: child}, nil case "_==_", "_!=_", "_<_", "_>_", "_<=_", "_>=_": return buildComparisonCondition(call, schema) case "@in": return buildInCondition(call, schema) case "contains": return buildContainsCondition(call, schema) default: val, ok, err := evaluateBool(call) if err != nil { return nil, err } if ok { return &ConstantCondition{Value: val}, nil } return nil, errors.Errorf("unsupported call expression %q", call.Function) } } func buildComparisonCondition(call *exprv1.Expr_Call, schema Schema) (Condition, error) { if len(call.Args) != 2 { return nil, errors.New("comparison expects two arguments") } op, err := toComparisonOperator(call.Function) if err != nil { return nil, err } left, err := buildValueExpr(call.Args[0], schema) if err != nil { return nil, err } right, err := buildValueExpr(call.Args[1], schema) if err != nil { return nil, err } // If the left side is a field, validate allowed operators. if field, ok := left.(*FieldRef); ok { def, exists := schema.Field(field.Name) if !exists { return nil, errors.Errorf("unknown identifier %q", field.Name) } if def.Kind == FieldKindVirtualAlias { def, exists = schema.ResolveAlias(field.Name) if !exists { return nil, errors.Errorf("invalid alias %q", field.Name) } } if def.AllowedComparisonOps != nil { if _, allowed := def.AllowedComparisonOps[op]; !allowed { return nil, errors.Errorf("operator %s not allowed for field %q", op, field.Name) } } } return &ComparisonCondition{ Left: left, Operator: op, Right: right, }, nil } func buildInCondition(call *exprv1.Expr_Call, schema Schema) (Condition, error) { if len(call.Args) != 2 { return nil, errors.New("in operator expects two arguments") } // Handle identifier in list syntax. if identName, err := getIdentName(call.Args[0]); err == nil { if field, ok := schema.Field(identName); ok && field.Kind == FieldKindVirtualAlias { if _, aliasOk := schema.ResolveAlias(identName); !aliasOk { return nil, errors.Errorf("invalid alias %q", identName) } } else if !ok { return nil, errors.Errorf("unknown identifier %q", identName) } if listExpr := call.Args[1].GetListExpr(); listExpr != nil { values := make([]ValueExpr, 0, len(listExpr.Elements)) for _, element := range listExpr.Elements { value, err := buildValueExpr(element, schema) if err != nil { return nil, err } values = append(values, value) } return &InCondition{ Left: &FieldRef{Name: identName}, Values: values, }, nil } } // Handle "value in identifier" syntax. if identName, err := getIdentName(call.Args[1]); err == nil { if _, ok := schema.Field(identName); !ok { return nil, errors.Errorf("unknown identifier %q", identName) } element, err := buildValueExpr(call.Args[0], schema) if err != nil { return nil, err } return &ElementInCondition{ Element: element, Field: identName, }, nil } return nil, errors.New("invalid use of in operator") } func buildContainsCondition(call *exprv1.Expr_Call, schema Schema) (Condition, error) { if call.Target == nil { return nil, errors.New("contains requires a target") } targetName, err := getIdentName(call.Target) if err != nil { return nil, err } field, ok := schema.Field(targetName) if !ok { return nil, errors.Errorf("unknown identifier %q", targetName) } if !field.SupportsContains { return nil, errors.Errorf("identifier %q does not support contains()", targetName) } if len(call.Args) != 1 { return nil, errors.New("contains expects exactly one argument") } value, err := getConstValue(call.Args[0]) if err != nil { return nil, errors.Wrap(err, "contains only supports literal arguments") } str, ok := value.(string) if !ok { return nil, errors.New("contains argument must be a string") } return &ContainsCondition{ Field: targetName, Value: str, }, nil } func buildValueExpr(expr *exprv1.Expr, schema Schema) (ValueExpr, error) { if identName, err := getIdentName(expr); err == nil { if _, ok := schema.Field(identName); !ok { return nil, errors.Errorf("unknown identifier %q", identName) } return &FieldRef{Name: identName}, nil } if literal, err := getConstValue(expr); err == nil { return &LiteralValue{Value: literal}, nil } if value, ok, err := evaluateNumeric(expr); err != nil { return nil, err } else if ok { return &LiteralValue{Value: value}, nil } if boolVal, ok, err := evaluateBoolExpr(expr); err != nil { return nil, err } else if ok { return &LiteralValue{Value: boolVal}, nil } if call := expr.GetCallExpr(); call != nil { switch call.Function { case "size": if len(call.Args) != 1 { return nil, errors.New("size() expects one argument") } arg, err := buildValueExpr(call.Args[0], schema) if err != nil { return nil, err } return &FunctionValue{ Name: "size", Args: []ValueExpr{arg}, }, nil case "now": return &LiteralValue{Value: timeNowUnix()}, nil case "_+_", "_-_", "_*_": value, ok, err := evaluateNumeric(expr) if err != nil { return nil, err } if ok { return &LiteralValue{Value: value}, nil } default: // Fall through to error return below } } return nil, errors.New("unsupported value expression") } func toComparisonOperator(fn string) (ComparisonOperator, error) { switch fn { case "_==_": return CompareEq, nil case "_!=_": return CompareNeq, nil case "_<_": return CompareLt, nil case "_>_": return CompareGt, nil case "_<=_": return CompareLte, nil case "_>=_": return CompareGte, nil default: return "", errors.Errorf("unsupported comparison operator %q", fn) } } func getIdentName(expr *exprv1.Expr) (string, error) { if ident := expr.GetIdentExpr(); ident != nil { return ident.GetName(), nil } return "", errors.New("expression is not an identifier") } func getConstValue(expr *exprv1.Expr) (interface{}, error) { v, ok := expr.ExprKind.(*exprv1.Expr_ConstExpr) if !ok { return nil, errors.New("expression is not a literal") } switch x := v.ConstExpr.ConstantKind.(type) { case *exprv1.Constant_StringValue: return v.ConstExpr.GetStringValue(), nil case *exprv1.Constant_Int64Value: return v.ConstExpr.GetInt64Value(), nil case *exprv1.Constant_Uint64Value: return int64(v.ConstExpr.GetUint64Value()), nil case *exprv1.Constant_DoubleValue: return v.ConstExpr.GetDoubleValue(), nil case *exprv1.Constant_BoolValue: return v.ConstExpr.GetBoolValue(), nil case *exprv1.Constant_NullValue: return nil, nil default: return nil, errors.Errorf("unsupported constant %T", x) } } func evaluateBool(call *exprv1.Expr_Call) (bool, bool, error) { val, ok, err := evaluateBoolExpr(&exprv1.Expr{ExprKind: &exprv1.Expr_CallExpr{CallExpr: call}}) return val, ok, err } func evaluateBoolExpr(expr *exprv1.Expr) (bool, bool, error) { if literal, err := getConstValue(expr); err == nil { if b, ok := literal.(bool); ok { return b, true, nil } return false, false, nil } if call := expr.GetCallExpr(); call != nil && call.Function == "!_" { if len(call.Args) != 1 { return false, false, errors.New("NOT expects exactly one argument") } val, ok, err := evaluateBoolExpr(call.Args[0]) if err != nil || !ok { return false, false, err } return !val, true, nil } return false, false, nil } func evaluateNumeric(expr *exprv1.Expr) (int64, bool, error) { if literal, err := getConstValue(expr); err == nil { switch v := literal.(type) { case int64: return v, true, nil case float64: return int64(v), true, nil } return 0, false, nil } call := expr.GetCallExpr() if call == nil { return 0, false, nil } switch call.Function { case "now": return timeNowUnix(), true, nil case "_+_", "_-_", "_*_": if len(call.Args) != 2 { return 0, false, errors.New("arithmetic requires two arguments") } left, ok, err := evaluateNumeric(call.Args[0]) if err != nil { return 0, false, err } if !ok { return 0, false, nil } right, ok, err := evaluateNumeric(call.Args[1]) if err != nil { return 0, false, err } if !ok { return 0, false, nil } switch call.Function { case "_+_": return left + right, true, nil case "_-_": return left - right, true, nil case "_*_": return left * right, true, nil default: return 0, false, errors.Errorf("unsupported arithmetic operator %q", call.Function) } default: return 0, false, nil } } func timeNowUnix() int64 { return time.Now().Unix() }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/filter/render.go
plugin/filter/render.go
package filter import ( "fmt" "strings" "github.com/pkg/errors" ) type renderer struct { schema Schema dialect DialectName placeholderOffset int placeholderCounter int args []any } type renderResult struct { sql string trivial bool unsatisfiable bool } func newRenderer(schema Schema, opts RenderOptions) *renderer { return &renderer{ schema: schema, dialect: opts.Dialect, placeholderOffset: opts.PlaceholderOffset, } } func (r *renderer) Render(cond Condition) (Statement, error) { result, err := r.renderCondition(cond) if err != nil { return Statement{}, err } args := r.args if args == nil { args = []any{} } switch { case result.unsatisfiable: return Statement{ SQL: "1 = 0", Args: args, }, nil case result.trivial: return Statement{ SQL: "", Args: args, }, nil default: return Statement{ SQL: result.sql, Args: args, }, nil } } func (r *renderer) renderCondition(cond Condition) (renderResult, error) { switch c := cond.(type) { case *LogicalCondition: return r.renderLogicalCondition(c) case *NotCondition: return r.renderNotCondition(c) case *FieldPredicateCondition: return r.renderFieldPredicate(c) case *ComparisonCondition: return r.renderComparison(c) case *InCondition: return r.renderInCondition(c) case *ElementInCondition: return r.renderElementInCondition(c) case *ContainsCondition: return r.renderContainsCondition(c) case *ConstantCondition: if c.Value { return renderResult{trivial: true}, nil } return renderResult{sql: "1 = 0", unsatisfiable: true}, nil default: return renderResult{}, errors.Errorf("unsupported condition type %T", c) } } func (r *renderer) renderLogicalCondition(cond *LogicalCondition) (renderResult, error) { left, err := r.renderCondition(cond.Left) if err != nil { return renderResult{}, err } right, err := r.renderCondition(cond.Right) if err != nil { return renderResult{}, err } switch cond.Operator { case LogicalAnd: return combineAnd(left, right), nil case LogicalOr: return combineOr(left, right), nil default: return renderResult{}, errors.Errorf("unsupported logical operator %s", cond.Operator) } } func (r *renderer) renderNotCondition(cond *NotCondition) (renderResult, error) { child, err := r.renderCondition(cond.Expr) if err != nil { return renderResult{}, err } if child.trivial { return renderResult{sql: "1 = 0", unsatisfiable: true}, nil } if child.unsatisfiable { return renderResult{trivial: true}, nil } return renderResult{ sql: fmt.Sprintf("NOT (%s)", child.sql), }, nil } func (r *renderer) renderFieldPredicate(cond *FieldPredicateCondition) (renderResult, error) { field, ok := r.schema.Field(cond.Field) if !ok { return renderResult{}, errors.Errorf("unknown field %q", cond.Field) } switch field.Kind { case FieldKindBoolColumn: column := qualifyColumn(r.dialect, field.Column) return renderResult{ sql: fmt.Sprintf("%s IS TRUE", column), }, nil case FieldKindJSONBool: sql, err := r.jsonBoolPredicate(field) if err != nil { return renderResult{}, err } return renderResult{sql: sql}, nil default: return renderResult{}, errors.Errorf("field %q cannot be used as a predicate", cond.Field) } } func (r *renderer) renderComparison(cond *ComparisonCondition) (renderResult, error) { switch left := cond.Left.(type) { case *FieldRef: field, ok := r.schema.Field(left.Name) if !ok { return renderResult{}, errors.Errorf("unknown field %q", left.Name) } switch field.Kind { case FieldKindBoolColumn: return r.renderBoolColumnComparison(field, cond.Operator, cond.Right) case FieldKindJSONBool: return r.renderJSONBoolComparison(field, cond.Operator, cond.Right) case FieldKindScalar: return r.renderScalarComparison(field, cond.Operator, cond.Right) default: return renderResult{}, errors.Errorf("field %q does not support comparison", field.Name) } case *FunctionValue: return r.renderFunctionComparison(left, cond.Operator, cond.Right) default: return renderResult{}, errors.New("comparison must start with a field reference or supported function") } } func (r *renderer) renderFunctionComparison(fn *FunctionValue, op ComparisonOperator, right ValueExpr) (renderResult, error) { if fn.Name != "size" { return renderResult{}, errors.Errorf("unsupported function %s in comparison", fn.Name) } if len(fn.Args) != 1 { return renderResult{}, errors.New("size() expects one argument") } fieldArg, ok := fn.Args[0].(*FieldRef) if !ok { return renderResult{}, errors.New("size() argument must be a field") } field, ok := r.schema.Field(fieldArg.Name) if !ok { return renderResult{}, errors.Errorf("unknown field %q", fieldArg.Name) } if field.Kind != FieldKindJSONList { return renderResult{}, errors.Errorf("size() only supports tag lists, got %q", field.Name) } value, err := expectNumericLiteral(right) if err != nil { return renderResult{}, err } expr := jsonArrayLengthExpr(r.dialect, field) placeholder := r.addArg(value) return renderResult{ sql: fmt.Sprintf("%s %s %s", expr, sqlOperator(op), placeholder), }, nil } func (r *renderer) renderScalarComparison(field Field, op ComparisonOperator, right ValueExpr) (renderResult, error) { lit, err := expectLiteral(right) if err != nil { return renderResult{}, err } columnExpr := field.columnExpr(r.dialect) if lit == nil { switch op { case CompareEq: return renderResult{sql: fmt.Sprintf("%s IS NULL", columnExpr)}, nil case CompareNeq: return renderResult{sql: fmt.Sprintf("%s IS NOT NULL", columnExpr)}, nil default: return renderResult{}, errors.Errorf("operator %s not supported for null comparison", op) } } placeholder := "" switch field.Type { case FieldTypeString: value, ok := lit.(string) if !ok { return renderResult{}, errors.Errorf("field %q expects string value", field.Name) } placeholder = r.addArg(value) case FieldTypeInt, FieldTypeTimestamp: num, err := toInt64(lit) if err != nil { return renderResult{}, errors.Wrapf(err, "field %q expects integer value", field.Name) } placeholder = r.addArg(num) default: return renderResult{}, errors.Errorf("unsupported data type %q for field %s", field.Type, field.Name) } return renderResult{ sql: fmt.Sprintf("%s %s %s", columnExpr, sqlOperator(op), placeholder), }, nil } func (r *renderer) renderBoolColumnComparison(field Field, op ComparisonOperator, right ValueExpr) (renderResult, error) { value, err := expectBool(right) if err != nil { return renderResult{}, err } placeholder := r.addBoolArg(value) column := qualifyColumn(r.dialect, field.Column) return renderResult{ sql: fmt.Sprintf("%s %s %s", column, sqlOperator(op), placeholder), }, nil } func (r *renderer) renderJSONBoolComparison(field Field, op ComparisonOperator, right ValueExpr) (renderResult, error) { value, err := expectBool(right) if err != nil { return renderResult{}, err } jsonExpr := jsonExtractExpr(r.dialect, field) switch r.dialect { case DialectSQLite: switch op { case CompareEq: if field.Name == "has_task_list" { target := "0" if value { target = "1" } return renderResult{sql: fmt.Sprintf("%s = %s", jsonExpr, target)}, nil } if value { return renderResult{sql: fmt.Sprintf("%s IS TRUE", jsonExpr)}, nil } return renderResult{sql: fmt.Sprintf("NOT(%s IS TRUE)", jsonExpr)}, nil case CompareNeq: if field.Name == "has_task_list" { target := "0" if value { target = "1" } return renderResult{sql: fmt.Sprintf("%s != %s", jsonExpr, target)}, nil } if value { return renderResult{sql: fmt.Sprintf("NOT(%s IS TRUE)", jsonExpr)}, nil } return renderResult{sql: fmt.Sprintf("%s IS TRUE", jsonExpr)}, nil default: return renderResult{}, errors.Errorf("operator %s not supported for boolean JSON field", op) } case DialectMySQL: boolStr := "false" if value { boolStr = "true" } return renderResult{ sql: fmt.Sprintf("%s %s CAST('%s' AS JSON)", jsonExpr, sqlOperator(op), boolStr), }, nil case DialectPostgres: placeholder := r.addArg(value) return renderResult{ sql: fmt.Sprintf("(%s)::boolean %s %s", jsonExpr, sqlOperator(op), placeholder), }, nil default: return renderResult{}, errors.Errorf("unsupported dialect %s", r.dialect) } } func (r *renderer) renderInCondition(cond *InCondition) (renderResult, error) { fieldRef, ok := cond.Left.(*FieldRef) if !ok { return renderResult{}, errors.New("IN operator requires a field on the left-hand side") } if fieldRef.Name == "tag" { return r.renderTagInList(cond.Values) } field, ok := r.schema.Field(fieldRef.Name) if !ok { return renderResult{}, errors.Errorf("unknown field %q", fieldRef.Name) } if field.Kind != FieldKindScalar { return renderResult{}, errors.Errorf("field %q does not support IN()", fieldRef.Name) } return r.renderScalarInCondition(field, cond.Values) } func (r *renderer) renderTagInList(values []ValueExpr) (renderResult, error) { field, ok := r.schema.ResolveAlias("tag") if !ok { return renderResult{}, errors.New("tag attribute is not configured") } conditions := make([]string, 0, len(values)) for _, v := range values { lit, err := expectLiteral(v) if err != nil { return renderResult{}, err } str, ok := lit.(string) if !ok { return renderResult{}, errors.New("tags must be compared with string literals") } switch r.dialect { case DialectSQLite: // Support hierarchical tags: match exact tag OR tags with this prefix (e.g., "book" matches "book" and "book/something") exactMatch := fmt.Sprintf("%s LIKE %s", jsonArrayExpr(r.dialect, field), r.addArg(fmt.Sprintf(`%%"%s"%%`, str))) prefixMatch := fmt.Sprintf("%s LIKE %s", jsonArrayExpr(r.dialect, field), r.addArg(fmt.Sprintf(`%%"%s/%%`, str))) expr := fmt.Sprintf("(%s OR %s)", exactMatch, prefixMatch) conditions = append(conditions, expr) case DialectMySQL: // Support hierarchical tags: match exact tag OR tags with this prefix exactMatch := fmt.Sprintf("JSON_CONTAINS(%s, %s)", jsonArrayExpr(r.dialect, field), r.addArg(fmt.Sprintf(`"%s"`, str))) prefixMatch := fmt.Sprintf("%s LIKE %s", jsonArrayExpr(r.dialect, field), r.addArg(fmt.Sprintf(`%%"%s/%%`, str))) expr := fmt.Sprintf("(%s OR %s)", exactMatch, prefixMatch) conditions = append(conditions, expr) case DialectPostgres: // Support hierarchical tags: match exact tag OR tags with this prefix exactMatch := fmt.Sprintf("%s @> jsonb_build_array(%s::json)", jsonArrayExpr(r.dialect, field), r.addArg(fmt.Sprintf(`"%s"`, str))) prefixMatch := fmt.Sprintf("(%s)::text LIKE %s", jsonArrayExpr(r.dialect, field), r.addArg(fmt.Sprintf(`%%"%s/%%`, str))) expr := fmt.Sprintf("(%s OR %s)", exactMatch, prefixMatch) conditions = append(conditions, expr) default: return renderResult{}, errors.Errorf("unsupported dialect %s", r.dialect) } } if len(conditions) == 1 { return renderResult{sql: conditions[0]}, nil } return renderResult{ sql: fmt.Sprintf("(%s)", strings.Join(conditions, " OR ")), }, nil } func (r *renderer) renderElementInCondition(cond *ElementInCondition) (renderResult, error) { field, ok := r.schema.Field(cond.Field) if !ok { return renderResult{}, errors.Errorf("unknown field %q", cond.Field) } if field.Kind != FieldKindJSONList { return renderResult{}, errors.Errorf("field %q is not a tag list", cond.Field) } lit, err := expectLiteral(cond.Element) if err != nil { return renderResult{}, err } str, ok := lit.(string) if !ok { return renderResult{}, errors.New("tags membership requires string literal") } switch r.dialect { case DialectSQLite: sql := fmt.Sprintf("%s LIKE %s", jsonArrayExpr(r.dialect, field), r.addArg(fmt.Sprintf(`%%"%s"%%`, str))) return renderResult{sql: sql}, nil case DialectMySQL: sql := fmt.Sprintf("JSON_CONTAINS(%s, %s)", jsonArrayExpr(r.dialect, field), r.addArg(fmt.Sprintf(`"%s"`, str))) return renderResult{sql: sql}, nil case DialectPostgres: sql := fmt.Sprintf("%s @> jsonb_build_array(%s::json)", jsonArrayExpr(r.dialect, field), r.addArg(fmt.Sprintf(`"%s"`, str))) return renderResult{sql: sql}, nil default: return renderResult{}, errors.Errorf("unsupported dialect %s", r.dialect) } } func (r *renderer) renderScalarInCondition(field Field, values []ValueExpr) (renderResult, error) { placeholders := make([]string, 0, len(values)) for _, v := range values { lit, err := expectLiteral(v) if err != nil { return renderResult{}, err } switch field.Type { case FieldTypeString: str, ok := lit.(string) if !ok { return renderResult{}, errors.Errorf("field %q expects string values", field.Name) } placeholders = append(placeholders, r.addArg(str)) case FieldTypeInt: num, err := toInt64(lit) if err != nil { return renderResult{}, err } placeholders = append(placeholders, r.addArg(num)) default: return renderResult{}, errors.Errorf("field %q does not support IN() comparisons", field.Name) } } column := field.columnExpr(r.dialect) return renderResult{ sql: fmt.Sprintf("%s IN (%s)", column, strings.Join(placeholders, ",")), }, nil } func (r *renderer) renderContainsCondition(cond *ContainsCondition) (renderResult, error) { field, ok := r.schema.Field(cond.Field) if !ok { return renderResult{}, errors.Errorf("unknown field %q", cond.Field) } column := field.columnExpr(r.dialect) arg := fmt.Sprintf("%%%s%%", cond.Value) switch r.dialect { case DialectPostgres: sql := fmt.Sprintf("%s ILIKE %s", column, r.addArg(arg)) return renderResult{sql: sql}, nil default: sql := fmt.Sprintf("%s LIKE %s", column, r.addArg(arg)) return renderResult{sql: sql}, nil } } func (r *renderer) jsonBoolPredicate(field Field) (string, error) { expr := jsonExtractExpr(r.dialect, field) switch r.dialect { case DialectSQLite: return fmt.Sprintf("%s IS TRUE", expr), nil case DialectMySQL: return fmt.Sprintf("%s = CAST('true' AS JSON)", expr), nil case DialectPostgres: return fmt.Sprintf("(%s)::boolean IS TRUE", expr), nil default: return "", errors.Errorf("unsupported dialect %s", r.dialect) } } func combineAnd(left, right renderResult) renderResult { if left.unsatisfiable || right.unsatisfiable { return renderResult{sql: "1 = 0", unsatisfiable: true} } if left.trivial { return right } if right.trivial { return left } return renderResult{ sql: fmt.Sprintf("(%s AND %s)", left.sql, right.sql), } } func combineOr(left, right renderResult) renderResult { if left.trivial || right.trivial { return renderResult{trivial: true} } if left.unsatisfiable { return right } if right.unsatisfiable { return left } return renderResult{ sql: fmt.Sprintf("(%s OR %s)", left.sql, right.sql), } } func (r *renderer) addArg(value any) string { r.placeholderCounter++ r.args = append(r.args, value) if r.dialect == DialectPostgres { return fmt.Sprintf("$%d", r.placeholderOffset+r.placeholderCounter) } return "?" } func (r *renderer) addBoolArg(value bool) string { var v any switch r.dialect { case DialectSQLite: if value { v = 1 } else { v = 0 } default: v = value } return r.addArg(v) } func expectLiteral(expr ValueExpr) (any, error) { lit, ok := expr.(*LiteralValue) if !ok { return nil, errors.New("expression must be a literal") } return lit.Value, nil } func expectBool(expr ValueExpr) (bool, error) { lit, err := expectLiteral(expr) if err != nil { return false, err } value, ok := lit.(bool) if !ok { return false, errors.New("boolean literal required") } return value, nil } func expectNumericLiteral(expr ValueExpr) (int64, error) { lit, err := expectLiteral(expr) if err != nil { return 0, err } return toInt64(lit) } func toInt64(value any) (int64, error) { switch v := value.(type) { case int: return int64(v), nil case int32: return int64(v), nil case int64: return v, nil case uint32: return int64(v), nil case uint64: return int64(v), nil case float32: return int64(v), nil case float64: return int64(v), nil default: return 0, errors.Errorf("cannot convert %T to int64", value) } } func sqlOperator(op ComparisonOperator) string { return string(op) } func qualifyColumn(d DialectName, col Column) string { switch d { case DialectPostgres: return fmt.Sprintf("%s.%s", col.Table, col.Name) default: return fmt.Sprintf("`%s`.`%s`", col.Table, col.Name) } } func jsonPath(field Field) string { return "$." + strings.Join(field.JSONPath, ".") } func jsonExtractExpr(d DialectName, field Field) string { column := qualifyColumn(d, field.Column) switch d { case DialectSQLite, DialectMySQL: return fmt.Sprintf("JSON_EXTRACT(%s, '%s')", column, jsonPath(field)) case DialectPostgres: return buildPostgresJSONAccessor(column, field.JSONPath, true) default: return "" } } func jsonArrayExpr(d DialectName, field Field) string { column := qualifyColumn(d, field.Column) switch d { case DialectSQLite, DialectMySQL: return fmt.Sprintf("JSON_EXTRACT(%s, '%s')", column, jsonPath(field)) case DialectPostgres: return buildPostgresJSONAccessor(column, field.JSONPath, false) default: return "" } } func jsonArrayLengthExpr(d DialectName, field Field) string { arrayExpr := jsonArrayExpr(d, field) switch d { case DialectSQLite: return fmt.Sprintf("JSON_ARRAY_LENGTH(COALESCE(%s, JSON_ARRAY()))", arrayExpr) case DialectMySQL: return fmt.Sprintf("JSON_LENGTH(COALESCE(%s, JSON_ARRAY()))", arrayExpr) case DialectPostgres: return fmt.Sprintf("jsonb_array_length(COALESCE(%s, '[]'::jsonb))", arrayExpr) default: return "" } } func buildPostgresJSONAccessor(base string, path []string, terminalText bool) string { expr := base for idx, part := range path { if idx == len(path)-1 && terminalText { expr = fmt.Sprintf("%s->>'%s'", expr, part) } else { expr = fmt.Sprintf("%s->'%s'", expr, part) } } return expr }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/filter/engine.go
plugin/filter/engine.go
package filter import ( "context" "fmt" "strings" "sync" "github.com/google/cel-go/cel" "github.com/pkg/errors" ) // Engine parses CEL filters into a dialect-agnostic condition tree. type Engine struct { schema Schema env *cel.Env } // NewEngine builds a new Engine for the provided schema. func NewEngine(schema Schema) (*Engine, error) { env, err := cel.NewEnv(schema.EnvOptions...) if err != nil { return nil, errors.Wrap(err, "failed to create CEL environment") } return &Engine{ schema: schema, env: env, }, nil } // Program stores a compiled filter condition. type Program struct { schema Schema condition Condition } // ConditionTree exposes the underlying condition tree. func (p *Program) ConditionTree() Condition { return p.condition } // Compile parses the filter string into an executable program. func (e *Engine) Compile(_ context.Context, filter string) (*Program, error) { if strings.TrimSpace(filter) == "" { return nil, errors.New("filter expression is empty") } filter = normalizeLegacyFilter(filter) ast, issues := e.env.Compile(filter) if issues != nil && issues.Err() != nil { return nil, errors.Wrap(issues.Err(), "failed to compile filter") } parsed, err := cel.AstToParsedExpr(ast) if err != nil { return nil, errors.Wrap(err, "failed to convert AST") } cond, err := buildCondition(parsed.GetExpr(), e.schema) if err != nil { return nil, err } return &Program{ schema: e.schema, condition: cond, }, nil } // CompileToStatement compiles and renders the filter in a single step. func (e *Engine) CompileToStatement(ctx context.Context, filter string, opts RenderOptions) (Statement, error) { program, err := e.Compile(ctx, filter) if err != nil { return Statement{}, err } return program.Render(opts) } // RenderOptions configure SQL rendering. type RenderOptions struct { Dialect DialectName PlaceholderOffset int DisableNullChecks bool } // Statement contains the rendered SQL fragment and its args. type Statement struct { SQL string Args []any } // Render converts the program into a dialect-specific SQL fragment. func (p *Program) Render(opts RenderOptions) (Statement, error) { renderer := newRenderer(p.schema, opts) return renderer.Render(p.condition) } var ( defaultOnce sync.Once defaultInst *Engine defaultErr error defaultAttachmentOnce sync.Once defaultAttachmentInst *Engine defaultAttachmentErr error ) // DefaultEngine returns the process-wide memo filter engine. func DefaultEngine() (*Engine, error) { defaultOnce.Do(func() { defaultInst, defaultErr = NewEngine(NewSchema()) }) return defaultInst, defaultErr } // DefaultAttachmentEngine returns the process-wide attachment filter engine. func DefaultAttachmentEngine() (*Engine, error) { defaultAttachmentOnce.Do(func() { defaultAttachmentInst, defaultAttachmentErr = NewEngine(NewAttachmentSchema()) }) return defaultAttachmentInst, defaultAttachmentErr } func normalizeLegacyFilter(expr string) string { expr = rewriteNumericLogicalOperand(expr, "&&") expr = rewriteNumericLogicalOperand(expr, "||") return expr } func rewriteNumericLogicalOperand(expr, op string) string { var builder strings.Builder n := len(expr) i := 0 var inQuote rune for i < n { ch := expr[i] if inQuote != 0 { builder.WriteByte(ch) if ch == '\\' && i+1 < n { builder.WriteByte(expr[i+1]) i += 2 continue } if ch == byte(inQuote) { inQuote = 0 } i++ continue } if ch == '\'' || ch == '"' { inQuote = rune(ch) builder.WriteByte(ch) i++ continue } if strings.HasPrefix(expr[i:], op) { builder.WriteString(op) i += len(op) // Preserve whitespace following the operator. wsStart := i for i < n && (expr[i] == ' ' || expr[i] == '\t') { i++ } builder.WriteString(expr[wsStart:i]) signStart := i if i < n && (expr[i] == '+' || expr[i] == '-') { i++ } for i < n && expr[i] >= '0' && expr[i] <= '9' { i++ } if i > signStart { numLiteral := expr[signStart:i] builder.WriteString(fmt.Sprintf("(%s != 0)", numLiteral)) } else { builder.WriteString(expr[signStart:i]) } continue } builder.WriteByte(ch) i++ } return builder.String() }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/filter/ir.go
plugin/filter/ir.go
package filter // Condition represents a boolean expression derived from the CEL filter. type Condition interface { isCondition() } // LogicalOperator enumerates the supported logical operators. type LogicalOperator string const ( LogicalAnd LogicalOperator = "AND" LogicalOr LogicalOperator = "OR" ) // LogicalCondition composes two conditions with a logical operator. type LogicalCondition struct { Operator LogicalOperator Left Condition Right Condition } func (*LogicalCondition) isCondition() {} // NotCondition negates a child condition. type NotCondition struct { Expr Condition } func (*NotCondition) isCondition() {} // FieldPredicateCondition asserts that a field evaluates to true. type FieldPredicateCondition struct { Field string } func (*FieldPredicateCondition) isCondition() {} // ComparisonOperator lists supported comparison operators. type ComparisonOperator string const ( CompareEq ComparisonOperator = "=" CompareNeq ComparisonOperator = "!=" CompareLt ComparisonOperator = "<" CompareLte ComparisonOperator = "<=" CompareGt ComparisonOperator = ">" CompareGte ComparisonOperator = ">=" ) // ComparisonCondition represents a binary comparison. type ComparisonCondition struct { Left ValueExpr Operator ComparisonOperator Right ValueExpr } func (*ComparisonCondition) isCondition() {} // InCondition represents an IN predicate with literal list values. type InCondition struct { Left ValueExpr Values []ValueExpr } func (*InCondition) isCondition() {} // ElementInCondition represents the CEL syntax `"value" in field`. type ElementInCondition struct { Element ValueExpr Field string } func (*ElementInCondition) isCondition() {} // ContainsCondition models the <field>.contains(<value>) call. type ContainsCondition struct { Field string Value string } func (*ContainsCondition) isCondition() {} // ConstantCondition captures a literal boolean outcome. type ConstantCondition struct { Value bool } func (*ConstantCondition) isCondition() {} // ValueExpr models arithmetic or scalar expressions whose result feeds a comparison. type ValueExpr interface { isValueExpr() } // FieldRef references a named schema field. type FieldRef struct { Name string } func (*FieldRef) isValueExpr() {} // LiteralValue holds a literal scalar. type LiteralValue struct { Value interface{} } func (*LiteralValue) isValueExpr() {} // FunctionValue captures simple function calls like size(tags). type FunctionValue struct { Name string Args []ValueExpr } func (*FunctionValue) isValueExpr() {}
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/filter/helpers.go
plugin/filter/helpers.go
package filter import ( "context" "fmt" ) // AppendConditions compiles the provided filters and appends the resulting SQL fragments and args. func AppendConditions(ctx context.Context, engine *Engine, filters []string, dialect DialectName, where *[]string, args *[]any) error { for _, filterStr := range filters { stmt, err := engine.CompileToStatement(ctx, filterStr, RenderOptions{ Dialect: dialect, PlaceholderOffset: len(*args), }) if err != nil { return err } if stmt.SQL == "" { continue } *where = append(*where, fmt.Sprintf("(%s)", stmt.SQL)) *args = append(*args, stmt.Args...) } return nil }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/filter/schema.go
plugin/filter/schema.go
package filter import ( "fmt" "time" "github.com/google/cel-go/cel" "github.com/google/cel-go/common/types" "github.com/google/cel-go/common/types/ref" ) // DialectName enumerates supported SQL dialects. type DialectName string const ( DialectSQLite DialectName = "sqlite" DialectMySQL DialectName = "mysql" DialectPostgres DialectName = "postgres" ) // FieldType represents the logical type of a field. type FieldType string const ( FieldTypeString FieldType = "string" FieldTypeInt FieldType = "int" FieldTypeBool FieldType = "bool" FieldTypeTimestamp FieldType = "timestamp" ) // FieldKind describes how a field is stored. type FieldKind string const ( FieldKindScalar FieldKind = "scalar" FieldKindBoolColumn FieldKind = "bool_column" FieldKindJSONBool FieldKind = "json_bool" FieldKindJSONList FieldKind = "json_list" FieldKindVirtualAlias FieldKind = "virtual_alias" ) // Column identifies the backing table column. type Column struct { Table string Name string } // Field captures the schema metadata for an exposed CEL identifier. type Field struct { Name string Kind FieldKind Type FieldType Column Column JSONPath []string AliasFor string SupportsContains bool Expressions map[DialectName]string AllowedComparisonOps map[ComparisonOperator]bool } // Schema collects CEL environment options and field metadata. type Schema struct { Name string Fields map[string]Field EnvOptions []cel.EnvOption } // Field returns the field metadata if present. func (s Schema) Field(name string) (Field, bool) { f, ok := s.Fields[name] return f, ok } // ResolveAlias resolves a virtual alias to its target field. func (s Schema) ResolveAlias(name string) (Field, bool) { field, ok := s.Fields[name] if !ok { return Field{}, false } if field.Kind == FieldKindVirtualAlias { target, ok := s.Fields[field.AliasFor] if !ok { return Field{}, false } return target, true } return field, true } var nowFunction = cel.Function("now", cel.Overload("now", []*cel.Type{}, cel.IntType, cel.FunctionBinding(func(_ ...ref.Val) ref.Val { return types.Int(time.Now().Unix()) }), ), ) // NewSchema constructs the memo filter schema and CEL environment. func NewSchema() Schema { fields := map[string]Field{ "content": { Name: "content", Kind: FieldKindScalar, Type: FieldTypeString, Column: Column{Table: "memo", Name: "content"}, SupportsContains: true, Expressions: map[DialectName]string{}, }, "creator_id": { Name: "creator_id", Kind: FieldKindScalar, Type: FieldTypeInt, Column: Column{Table: "memo", Name: "creator_id"}, Expressions: map[DialectName]string{}, AllowedComparisonOps: map[ComparisonOperator]bool{ CompareEq: true, CompareNeq: true, }, }, "created_ts": { Name: "created_ts", Kind: FieldKindScalar, Type: FieldTypeTimestamp, Column: Column{Table: "memo", Name: "created_ts"}, Expressions: map[DialectName]string{ // MySQL stores created_ts as TIMESTAMP, needs conversion to epoch DialectMySQL: "UNIX_TIMESTAMP(%s)", // PostgreSQL and SQLite store created_ts as BIGINT (epoch), no conversion needed DialectPostgres: "%s", DialectSQLite: "%s", }, }, "updated_ts": { Name: "updated_ts", Kind: FieldKindScalar, Type: FieldTypeTimestamp, Column: Column{Table: "memo", Name: "updated_ts"}, Expressions: map[DialectName]string{ // MySQL stores updated_ts as TIMESTAMP, needs conversion to epoch DialectMySQL: "UNIX_TIMESTAMP(%s)", // PostgreSQL and SQLite store updated_ts as BIGINT (epoch), no conversion needed DialectPostgres: "%s", DialectSQLite: "%s", }, }, "pinned": { Name: "pinned", Kind: FieldKindBoolColumn, Type: FieldTypeBool, Column: Column{Table: "memo", Name: "pinned"}, Expressions: map[DialectName]string{}, AllowedComparisonOps: map[ComparisonOperator]bool{ CompareEq: true, CompareNeq: true, }, }, "visibility": { Name: "visibility", Kind: FieldKindScalar, Type: FieldTypeString, Column: Column{Table: "memo", Name: "visibility"}, Expressions: map[DialectName]string{}, AllowedComparisonOps: map[ComparisonOperator]bool{ CompareEq: true, CompareNeq: true, }, }, "tags": { Name: "tags", Kind: FieldKindJSONList, Type: FieldTypeString, Column: Column{Table: "memo", Name: "payload"}, JSONPath: []string{"tags"}, }, "tag": { Name: "tag", Kind: FieldKindVirtualAlias, Type: FieldTypeString, AliasFor: "tags", }, "has_task_list": { Name: "has_task_list", Kind: FieldKindJSONBool, Type: FieldTypeBool, Column: Column{Table: "memo", Name: "payload"}, JSONPath: []string{"property", "hasTaskList"}, AllowedComparisonOps: map[ComparisonOperator]bool{ CompareEq: true, CompareNeq: true, }, }, "has_link": { Name: "has_link", Kind: FieldKindJSONBool, Type: FieldTypeBool, Column: Column{Table: "memo", Name: "payload"}, JSONPath: []string{"property", "hasLink"}, AllowedComparisonOps: map[ComparisonOperator]bool{ CompareEq: true, CompareNeq: true, }, }, "has_code": { Name: "has_code", Kind: FieldKindJSONBool, Type: FieldTypeBool, Column: Column{Table: "memo", Name: "payload"}, JSONPath: []string{"property", "hasCode"}, AllowedComparisonOps: map[ComparisonOperator]bool{ CompareEq: true, CompareNeq: true, }, }, "has_incomplete_tasks": { Name: "has_incomplete_tasks", Kind: FieldKindJSONBool, Type: FieldTypeBool, Column: Column{Table: "memo", Name: "payload"}, JSONPath: []string{"property", "hasIncompleteTasks"}, AllowedComparisonOps: map[ComparisonOperator]bool{ CompareEq: true, CompareNeq: true, }, }, } envOptions := []cel.EnvOption{ cel.Variable("content", cel.StringType), cel.Variable("creator_id", cel.IntType), cel.Variable("created_ts", cel.IntType), cel.Variable("updated_ts", cel.IntType), cel.Variable("pinned", cel.BoolType), cel.Variable("tag", cel.StringType), cel.Variable("tags", cel.ListType(cel.StringType)), cel.Variable("visibility", cel.StringType), cel.Variable("has_task_list", cel.BoolType), cel.Variable("has_link", cel.BoolType), cel.Variable("has_code", cel.BoolType), cel.Variable("has_incomplete_tasks", cel.BoolType), nowFunction, } return Schema{ Name: "memo", Fields: fields, EnvOptions: envOptions, } } // NewAttachmentSchema constructs the attachment filter schema and CEL environment. func NewAttachmentSchema() Schema { fields := map[string]Field{ "filename": { Name: "filename", Kind: FieldKindScalar, Type: FieldTypeString, Column: Column{Table: "attachment", Name: "filename"}, SupportsContains: true, Expressions: map[DialectName]string{}, }, "mime_type": { Name: "mime_type", Kind: FieldKindScalar, Type: FieldTypeString, Column: Column{Table: "attachment", Name: "type"}, Expressions: map[DialectName]string{}, }, "create_time": { Name: "create_time", Kind: FieldKindScalar, Type: FieldTypeTimestamp, Column: Column{Table: "attachment", Name: "created_ts"}, Expressions: map[DialectName]string{ // MySQL stores created_ts as TIMESTAMP, needs conversion to epoch DialectMySQL: "UNIX_TIMESTAMP(%s)", // PostgreSQL and SQLite store created_ts as BIGINT (epoch), no conversion needed DialectPostgres: "%s", DialectSQLite: "%s", }, }, "memo_id": { Name: "memo_id", Kind: FieldKindScalar, Type: FieldTypeInt, Column: Column{Table: "attachment", Name: "memo_id"}, Expressions: map[DialectName]string{}, AllowedComparisonOps: map[ComparisonOperator]bool{ CompareEq: true, CompareNeq: true, }, }, } envOptions := []cel.EnvOption{ cel.Variable("filename", cel.StringType), cel.Variable("mime_type", cel.StringType), cel.Variable("create_time", cel.IntType), cel.Variable("memo_id", cel.AnyType), nowFunction, } return Schema{ Name: "attachment", Fields: fields, EnvOptions: envOptions, } } // columnExpr returns the field expression for the given dialect, applying // any schema-specific overrides (e.g. UNIX timestamp conversions). func (f Field) columnExpr(d DialectName) string { base := qualifyColumn(d, f.Column) if expr, ok := f.Expressions[d]; ok && expr != "" { return fmt.Sprintf(expr, base) } return base }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/idp/idp.go
plugin/idp/idp.go
package idp type IdentityProviderUserInfo struct { Identifier string DisplayName string Email string AvatarURL string }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/idp/oauth2/oauth2.go
plugin/idp/oauth2/oauth2.go
// Package oauth2 is the plugin for OAuth2 Identity Provider. package oauth2 import ( "context" "encoding/json" "fmt" "io" "log/slog" "net/http" "github.com/pkg/errors" "golang.org/x/oauth2" "github.com/usememos/memos/plugin/idp" storepb "github.com/usememos/memos/proto/gen/store" ) // IdentityProvider represents an OAuth2 Identity Provider. type IdentityProvider struct { config *storepb.OAuth2Config } // NewIdentityProvider initializes a new OAuth2 Identity Provider with the given configuration. func NewIdentityProvider(config *storepb.OAuth2Config) (*IdentityProvider, error) { for v, field := range map[string]string{ config.ClientId: "clientId", config.ClientSecret: "clientSecret", config.TokenUrl: "tokenUrl", config.UserInfoUrl: "userInfoUrl", config.FieldMapping.Identifier: "fieldMapping.identifier", } { if v == "" { return nil, errors.Errorf(`the field "%s" is empty but required`, field) } } return &IdentityProvider{ config: config, }, nil } // ExchangeToken returns the exchanged OAuth2 token using the given authorization code. // If codeVerifier is provided, it will be used for PKCE (Proof Key for Code Exchange) validation. func (p *IdentityProvider) ExchangeToken(ctx context.Context, redirectURL, code, codeVerifier string) (string, error) { conf := &oauth2.Config{ ClientID: p.config.ClientId, ClientSecret: p.config.ClientSecret, RedirectURL: redirectURL, Scopes: p.config.Scopes, Endpoint: oauth2.Endpoint{ AuthURL: p.config.AuthUrl, TokenURL: p.config.TokenUrl, AuthStyle: oauth2.AuthStyleInParams, }, } // Prepare token exchange options opts := []oauth2.AuthCodeOption{} // Add PKCE code_verifier if provided if codeVerifier != "" { opts = append(opts, oauth2.SetAuthURLParam("code_verifier", codeVerifier)) } token, err := conf.Exchange(ctx, code, opts...) if err != nil { return "", errors.Wrap(err, "failed to exchange access token") } // Use the standard AccessToken field instead of Extra() // This is more reliable across different OAuth providers if token.AccessToken == "" { return "", errors.New("missing access token from authorization response") } return token.AccessToken, nil } // UserInfo returns the parsed user information using the given OAuth2 token. func (p *IdentityProvider) UserInfo(token string) (*idp.IdentityProviderUserInfo, error) { client := &http.Client{} req, err := http.NewRequest(http.MethodGet, p.config.UserInfoUrl, nil) if err != nil { return nil, errors.Wrap(err, "failed to new http request") } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) resp, err := client.Do(req) if err != nil { return nil, errors.Wrap(err, "failed to get user information") } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { return nil, errors.Wrap(err, "failed to read response body") } var claims map[string]any if err := json.Unmarshal(body, &claims); err != nil { return nil, errors.Wrap(err, "failed to unmarshal response body") } slog.Info("user info claims", "claims", claims) userInfo := &idp.IdentityProviderUserInfo{} if v, ok := claims[p.config.FieldMapping.Identifier].(string); ok { userInfo.Identifier = v } if userInfo.Identifier == "" { return nil, errors.Errorf("the field %q is not found in claims or has empty value", p.config.FieldMapping.Identifier) } // Best effort to map optional fields if p.config.FieldMapping.DisplayName != "" { if v, ok := claims[p.config.FieldMapping.DisplayName].(string); ok { userInfo.DisplayName = v } } if userInfo.DisplayName == "" { userInfo.DisplayName = userInfo.Identifier } if p.config.FieldMapping.Email != "" { if v, ok := claims[p.config.FieldMapping.Email].(string); ok { userInfo.Email = v } } if p.config.FieldMapping.AvatarUrl != "" { if v, ok := claims[p.config.FieldMapping.AvatarUrl].(string); ok { userInfo.AvatarURL = v } } slog.Info("user info", "userInfo", userInfo) return userInfo, nil }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/idp/oauth2/oauth2_test.go
plugin/idp/oauth2/oauth2_test.go
package oauth2 import ( "context" "encoding/json" "fmt" "io" "net/http" "net/http/httptest" "net/url" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/usememos/memos/plugin/idp" storepb "github.com/usememos/memos/proto/gen/store" ) func TestNewIdentityProvider(t *testing.T) { tests := []struct { name string config *storepb.OAuth2Config containsErr string }{ { name: "no tokenUrl", config: &storepb.OAuth2Config{ ClientId: "test-client-id", ClientSecret: "test-client-secret", AuthUrl: "", TokenUrl: "", UserInfoUrl: "https://example.com/api/user", FieldMapping: &storepb.FieldMapping{ Identifier: "login", }, }, containsErr: `the field "tokenUrl" is empty but required`, }, { name: "no userInfoUrl", config: &storepb.OAuth2Config{ ClientId: "test-client-id", ClientSecret: "test-client-secret", AuthUrl: "", TokenUrl: "https://example.com/token", UserInfoUrl: "", FieldMapping: &storepb.FieldMapping{ Identifier: "login", }, }, containsErr: `the field "userInfoUrl" is empty but required`, }, { name: "no field mapping identifier", config: &storepb.OAuth2Config{ ClientId: "test-client-id", ClientSecret: "test-client-secret", AuthUrl: "", TokenUrl: "https://example.com/token", UserInfoUrl: "https://example.com/api/user", FieldMapping: &storepb.FieldMapping{ Identifier: "", }, }, containsErr: `the field "fieldMapping.identifier" is empty but required`, }, } for _, test := range tests { t.Run(test.name, func(*testing.T) { _, err := NewIdentityProvider(test.config) assert.ErrorContains(t, err, test.containsErr) }) } } func newMockServer(t *testing.T, code, accessToken string, userinfo []byte) *httptest.Server { mux := http.NewServeMux() var rawIDToken string mux.HandleFunc("/oauth2/token", func(w http.ResponseWriter, r *http.Request) { require.Equal(t, http.MethodPost, r.Method) body, err := io.ReadAll(r.Body) require.NoError(t, err) vals, err := url.ParseQuery(string(body)) require.NoError(t, err) require.Equal(t, code, vals.Get("code")) require.Equal(t, "authorization_code", vals.Get("grant_type")) w.Header().Set("Content-Type", "application/json") err = json.NewEncoder(w).Encode(map[string]any{ "access_token": accessToken, "token_type": "Bearer", "expires_in": 3600, "id_token": rawIDToken, }) require.NoError(t, err) }) mux.HandleFunc("/oauth2/userinfo", func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "application/json") _, err := w.Write(userinfo) require.NoError(t, err) }) s := httptest.NewServer(mux) return s } func TestIdentityProvider(t *testing.T) { ctx := context.Background() const ( testClientID = "test-client-id" testCode = "test-code" testAccessToken = "test-access-token" testSubject = "123456789" testName = "John Doe" testEmail = "john.doe@example.com" ) userInfo, err := json.Marshal( map[string]any{ "sub": testSubject, "name": testName, "email": testEmail, }, ) require.NoError(t, err) s := newMockServer(t, testCode, testAccessToken, userInfo) oauth2, err := NewIdentityProvider( &storepb.OAuth2Config{ ClientId: testClientID, ClientSecret: "test-client-secret", TokenUrl: fmt.Sprintf("%s/oauth2/token", s.URL), UserInfoUrl: fmt.Sprintf("%s/oauth2/userinfo", s.URL), FieldMapping: &storepb.FieldMapping{ Identifier: "sub", DisplayName: "name", Email: "email", }, }, ) require.NoError(t, err) redirectURL := "https://example.com/oauth/callback" // Test without PKCE (backward compatibility) oauthToken, err := oauth2.ExchangeToken(ctx, redirectURL, testCode, "") require.NoError(t, err) require.Equal(t, testAccessToken, oauthToken) userInfoResult, err := oauth2.UserInfo(oauthToken) require.NoError(t, err) wantUserInfo := &idp.IdentityProviderUserInfo{ Identifier: testSubject, DisplayName: testName, Email: testEmail, } assert.Equal(t, wantUserInfo, userInfoResult) }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/cron/parser.go
plugin/cron/parser.go
package cron import ( "math" "strconv" "strings" "time" "github.com/pkg/errors" ) // Configuration options for creating a parser. Most options specify which // fields should be included, while others enable features. If a field is not // included the parser will assume a default value. These options do not change // the order fields are parse in. type ParseOption int const ( Second ParseOption = 1 << iota // Seconds field, default 0 SecondOptional // Optional seconds field, default 0 Minute // Minutes field, default 0 Hour // Hours field, default 0 Dom // Day of month field, default * Month // Month field, default * Dow // Day of week field, default * DowOptional // Optional day of week field, default * Descriptor // Allow descriptors such as @monthly, @weekly, etc. ) var places = []ParseOption{ Second, Minute, Hour, Dom, Month, Dow, } var defaults = []string{ "0", "0", "0", "*", "*", "*", } // A custom Parser that can be configured. type Parser struct { options ParseOption } // NewParser creates a Parser with custom options. // // It panics if more than one Optional is given, since it would be impossible to // correctly infer which optional is provided or missing in general. // // Examples // // // Standard parser without descriptors // specParser := NewParser(Minute | Hour | Dom | Month | Dow) // sched, err := specParser.Parse("0 0 15 */3 *") // // // Same as above, just excludes time fields // specParser := NewParser(Dom | Month | Dow) // sched, err := specParser.Parse("15 */3 *") // // // Same as above, just makes Dow optional // specParser := NewParser(Dom | Month | DowOptional) // sched, err := specParser.Parse("15 */3") func NewParser(options ParseOption) Parser { optionals := 0 if options&DowOptional > 0 { optionals++ } if options&SecondOptional > 0 { optionals++ } if optionals > 1 { panic("multiple optionals may not be configured") } return Parser{options} } // Parse returns a new crontab schedule representing the given spec. // It returns a descriptive error if the spec is not valid. // It accepts crontab specs and features configured by NewParser. func (p Parser) Parse(spec string) (Schedule, error) { if len(spec) == 0 { return nil, errors.New("empty spec string") } // Extract timezone if present var loc = time.Local if strings.HasPrefix(spec, "TZ=") || strings.HasPrefix(spec, "CRON_TZ=") { var err error i := strings.Index(spec, " ") eq := strings.Index(spec, "=") if loc, err = time.LoadLocation(spec[eq+1 : i]); err != nil { return nil, errors.Wrap(err, "provided bad location") } spec = strings.TrimSpace(spec[i:]) } // Handle named schedules (descriptors), if configured if strings.HasPrefix(spec, "@") { if p.options&Descriptor == 0 { return nil, errors.New("descriptors not enabled") } return parseDescriptor(spec, loc) } // Split on whitespace. fields := strings.Fields(spec) // Validate & fill in any omitted or optional fields var err error fields, err = normalizeFields(fields, p.options) if err != nil { return nil, err } field := func(field string, r bounds) uint64 { if err != nil { return 0 } var bits uint64 bits, err = getField(field, r) return bits } var ( second = field(fields[0], seconds) minute = field(fields[1], minutes) hour = field(fields[2], hours) dayofmonth = field(fields[3], dom) month = field(fields[4], months) dayofweek = field(fields[5], dow) ) if err != nil { return nil, err } return &SpecSchedule{ Second: second, Minute: minute, Hour: hour, Dom: dayofmonth, Month: month, Dow: dayofweek, Location: loc, }, nil } // normalizeFields takes a subset set of the time fields and returns the full set // with defaults (zeroes) populated for unset fields. // // As part of performing this function, it also validates that the provided // fields are compatible with the configured options. func normalizeFields(fields []string, options ParseOption) ([]string, error) { // Validate optionals & add their field to options optionals := 0 if options&SecondOptional > 0 { options |= Second optionals++ } if options&DowOptional > 0 { options |= Dow optionals++ } if optionals > 1 { return nil, errors.New("multiple optionals may not be configured") } // Figure out how many fields we need max := 0 for _, place := range places { if options&place > 0 { max++ } } min := max - optionals // Validate number of fields if count := len(fields); count < min || count > max { if min == max { return nil, errors.New("incorrect number of fields") } return nil, errors.New("incorrect number of fields, expected " + strconv.Itoa(min) + "-" + strconv.Itoa(max)) } // Populate the optional field if not provided if min < max && len(fields) == min { switch { case options&DowOptional > 0: fields = append(fields, defaults[5]) // TODO: improve access to default case options&SecondOptional > 0: fields = append([]string{defaults[0]}, fields...) default: return nil, errors.New("unexpected optional field") } } // Populate all fields not part of options with their defaults n := 0 expandedFields := make([]string, len(places)) copy(expandedFields, defaults) for i, place := range places { if options&place > 0 { expandedFields[i] = fields[n] n++ } } return expandedFields, nil } var standardParser = NewParser( Minute | Hour | Dom | Month | Dow | Descriptor, ) // ParseStandard returns a new crontab schedule representing the given // standardSpec (https://en.wikipedia.org/wiki/Cron). It requires 5 entries // representing: minute, hour, day of month, month and day of week, in that // order. It returns a descriptive error if the spec is not valid. // // It accepts // - Standard crontab specs, e.g. "* * * * ?" // - Descriptors, e.g. "@midnight", "@every 1h30m" func ParseStandard(standardSpec string) (Schedule, error) { return standardParser.Parse(standardSpec) } // getField returns an Int with the bits set representing all of the times that // the field represents or error parsing field value. A "field" is a comma-separated // list of "ranges". func getField(field string, r bounds) (uint64, error) { var bits uint64 ranges := strings.FieldsFunc(field, func(r rune) bool { return r == ',' }) for _, expr := range ranges { bit, err := getRange(expr, r) if err != nil { return bits, err } bits |= bit } return bits, nil } // getRange returns the bits indicated by the given expression: // // number | number "-" number [ "/" number ] // // or error parsing range. func getRange(expr string, r bounds) (uint64, error) { var ( start, end, step uint rangeAndStep = strings.Split(expr, "/") lowAndHigh = strings.Split(rangeAndStep[0], "-") singleDigit = len(lowAndHigh) == 1 err error ) var extra uint64 if lowAndHigh[0] == "*" || lowAndHigh[0] == "?" { start = r.min end = r.max extra = starBit } else { start, err = parseIntOrName(lowAndHigh[0], r.names) if err != nil { return 0, err } switch len(lowAndHigh) { case 1: end = start case 2: end, err = parseIntOrName(lowAndHigh[1], r.names) if err != nil { return 0, err } default: return 0, errors.New("too many hyphens: " + expr) } } switch len(rangeAndStep) { case 1: step = 1 case 2: step, err = mustParseInt(rangeAndStep[1]) if err != nil { return 0, err } // Special handling: "N/step" means "N-max/step". if singleDigit { end = r.max } if step > 1 { extra = 0 } default: return 0, errors.New("too many slashes: " + expr) } if start < r.min { return 0, errors.New("beginning of range below minimum: " + expr) } if end > r.max { return 0, errors.New("end of range above maximum: " + expr) } if start > end { return 0, errors.New("beginning of range after end: " + expr) } if step == 0 { return 0, errors.New("step cannot be zero: " + expr) } return getBits(start, end, step) | extra, nil } // parseIntOrName returns the (possibly-named) integer contained in expr. func parseIntOrName(expr string, names map[string]uint) (uint, error) { if names != nil { if namedInt, ok := names[strings.ToLower(expr)]; ok { return namedInt, nil } } return mustParseInt(expr) } // mustParseInt parses the given expression as an int or returns an error. func mustParseInt(expr string) (uint, error) { num, err := strconv.Atoi(expr) if err != nil { return 0, errors.Wrap(err, "failed to parse number") } if num < 0 { return 0, errors.New("number must be positive") } return uint(num), nil } // getBits sets all bits in the range [min, max], modulo the given step size. func getBits(min, max, step uint) uint64 { var bits uint64 // If step is 1, use shifts. if step == 1 { return ^(math.MaxUint64 << (max + 1)) & (math.MaxUint64 << min) } // Else, use a simple loop. for i := min; i <= max; i += step { bits |= 1 << i } return bits } // all returns all bits within the given bounds. func all(r bounds) uint64 { return getBits(r.min, r.max, 1) | starBit } // parseDescriptor returns a predefined schedule for the expression, or error if none matches. func parseDescriptor(descriptor string, loc *time.Location) (Schedule, error) { switch descriptor { case "@yearly", "@annually": return &SpecSchedule{ Second: 1 << seconds.min, Minute: 1 << minutes.min, Hour: 1 << hours.min, Dom: 1 << dom.min, Month: 1 << months.min, Dow: all(dow), Location: loc, }, nil case "@monthly": return &SpecSchedule{ Second: 1 << seconds.min, Minute: 1 << minutes.min, Hour: 1 << hours.min, Dom: 1 << dom.min, Month: all(months), Dow: all(dow), Location: loc, }, nil case "@weekly": return &SpecSchedule{ Second: 1 << seconds.min, Minute: 1 << minutes.min, Hour: 1 << hours.min, Dom: all(dom), Month: all(months), Dow: 1 << dow.min, Location: loc, }, nil case "@daily", "@midnight": return &SpecSchedule{ Second: 1 << seconds.min, Minute: 1 << minutes.min, Hour: 1 << hours.min, Dom: all(dom), Month: all(months), Dow: all(dow), Location: loc, }, nil case "@hourly": return &SpecSchedule{ Second: 1 << seconds.min, Minute: 1 << minutes.min, Hour: all(hours), Dom: all(dom), Month: all(months), Dow: all(dow), Location: loc, }, nil default: // Continue to check @every prefix below } const every = "@every " if strings.HasPrefix(descriptor, every) { duration, err := time.ParseDuration(descriptor[len(every):]) if err != nil { return nil, errors.Wrap(err, "failed to parse duration") } return Every(duration), nil } return nil, errors.New("unrecognized descriptor: " + descriptor) }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/cron/constantdelay.go
plugin/cron/constantdelay.go
package cron import "time" // ConstantDelaySchedule represents a simple recurring duty cycle, e.g. "Every 5 minutes". // It does not support jobs more frequent than once a second. type ConstantDelaySchedule struct { Delay time.Duration } // Every returns a crontab Schedule that activates once every duration. // Delays of less than a second are not supported (will round up to 1 second). // Any fields less than a Second are truncated. func Every(duration time.Duration) ConstantDelaySchedule { if duration < time.Second { duration = time.Second } return ConstantDelaySchedule{ Delay: duration - time.Duration(duration.Nanoseconds())%time.Second, } } // Next returns the next time this should be run. // This rounds so that the next activation time will be on the second. func (schedule ConstantDelaySchedule) Next(t time.Time) time.Time { return t.Add(schedule.Delay - time.Duration(t.Nanosecond())*time.Nanosecond) }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/cron/cron.go
plugin/cron/cron.go
package cron import ( "context" "sort" "sync" "time" ) // Cron keeps track of any number of entries, invoking the associated func as // specified by the schedule. It may be started, stopped, and the entries may // be inspected while running. type Cron struct { entries []*Entry chain Chain stop chan struct{} add chan *Entry remove chan EntryID snapshot chan chan []Entry running bool logger Logger runningMu sync.Mutex location *time.Location parser ScheduleParser nextID EntryID jobWaiter sync.WaitGroup } // ScheduleParser is an interface for schedule spec parsers that return a Schedule. type ScheduleParser interface { Parse(spec string) (Schedule, error) } // Job is an interface for submitted cron jobs. type Job interface { Run() } // Schedule describes a job's duty cycle. type Schedule interface { // Next returns the next activation time, later than the given time. // Next is invoked initially, and then each time the job is run. Next(time.Time) time.Time } // EntryID identifies an entry within a Cron instance. type EntryID int // Entry consists of a schedule and the func to execute on that schedule. type Entry struct { // ID is the cron-assigned ID of this entry, which may be used to look up a // snapshot or remove it. ID EntryID // Schedule on which this job should be run. Schedule Schedule // Next time the job will run, or the zero time if Cron has not been // started or this entry's schedule is unsatisfiable Next time.Time // Prev is the last time this job was run, or the zero time if never. Prev time.Time // WrappedJob is the thing to run when the Schedule is activated. WrappedJob Job // Job is the thing that was submitted to cron. // It is kept around so that user code that needs to get at the job later, // e.g. via Entries() can do so. Job Job } // Valid returns true if this is not the zero entry. func (e Entry) Valid() bool { return e.ID != 0 } // byTime is a wrapper for sorting the entry array by time // (with zero time at the end). type byTime []*Entry func (s byTime) Len() int { return len(s) } func (s byTime) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s byTime) Less(i, j int) bool { // Two zero times should return false. // Otherwise, zero is "greater" than any other time. // (To sort it at the end of the list.) if s[i].Next.IsZero() { return false } if s[j].Next.IsZero() { return true } return s[i].Next.Before(s[j].Next) } // New returns a new Cron job runner, modified by the given options. // // Available Settings // // Time Zone // Description: The time zone in which schedules are interpreted // Default: time.Local // // Parser // Description: Parser converts cron spec strings into cron.Schedules. // Default: Accepts this spec: https://en.wikipedia.org/wiki/Cron // // Chain // Description: Wrap submitted jobs to customize behavior. // Default: A chain that recovers panics and logs them to stderr. // // See "cron.With*" to modify the default behavior. func New(opts ...Option) *Cron { c := &Cron{ entries: nil, chain: NewChain(), add: make(chan *Entry), stop: make(chan struct{}), snapshot: make(chan chan []Entry), remove: make(chan EntryID), running: false, runningMu: sync.Mutex{}, logger: DefaultLogger, location: time.Local, parser: standardParser, } for _, opt := range opts { opt(c) } return c } // FuncJob is a wrapper that turns a func() into a cron.Job. type FuncJob func() func (f FuncJob) Run() { f() } // AddFunc adds a func to the Cron to be run on the given schedule. // The spec is parsed using the time zone of this Cron instance as the default. // An opaque ID is returned that can be used to later remove it. func (c *Cron) AddFunc(spec string, cmd func()) (EntryID, error) { return c.AddJob(spec, FuncJob(cmd)) } // AddJob adds a Job to the Cron to be run on the given schedule. // The spec is parsed using the time zone of this Cron instance as the default. // An opaque ID is returned that can be used to later remove it. func (c *Cron) AddJob(spec string, cmd Job) (EntryID, error) { schedule, err := c.parser.Parse(spec) if err != nil { return 0, err } return c.Schedule(schedule, cmd), nil } // Schedule adds a Job to the Cron to be run on the given schedule. // The job is wrapped with the configured Chain. func (c *Cron) Schedule(schedule Schedule, cmd Job) EntryID { c.runningMu.Lock() defer c.runningMu.Unlock() c.nextID++ entry := &Entry{ ID: c.nextID, Schedule: schedule, WrappedJob: c.chain.Then(cmd), Job: cmd, } if !c.running { c.entries = append(c.entries, entry) } else { c.add <- entry } return entry.ID } // Entries returns a snapshot of the cron entries. func (c *Cron) Entries() []Entry { c.runningMu.Lock() defer c.runningMu.Unlock() if c.running { replyChan := make(chan []Entry, 1) c.snapshot <- replyChan return <-replyChan } return c.entrySnapshot() } // Location gets the time zone location. func (c *Cron) Location() *time.Location { return c.location } // Entry returns a snapshot of the given entry, or nil if it couldn't be found. func (c *Cron) Entry(id EntryID) Entry { for _, entry := range c.Entries() { if id == entry.ID { return entry } } return Entry{} } // Remove an entry from being run in the future. func (c *Cron) Remove(id EntryID) { c.runningMu.Lock() defer c.runningMu.Unlock() if c.running { c.remove <- id } else { c.removeEntry(id) } } // Start the cron scheduler in its own goroutine, or no-op if already started. func (c *Cron) Start() { c.runningMu.Lock() defer c.runningMu.Unlock() if c.running { return } c.running = true go c.runScheduler() } // Run the cron scheduler, or no-op if already running. func (c *Cron) Run() { c.runningMu.Lock() if c.running { c.runningMu.Unlock() return } c.running = true c.runningMu.Unlock() c.runScheduler() } // runScheduler runs the scheduler.. this is private just due to the need to synchronize // access to the 'running' state variable. func (c *Cron) runScheduler() { c.logger.Info("start") // Figure out the next activation times for each entry. now := c.now() for _, entry := range c.entries { entry.Next = entry.Schedule.Next(now) c.logger.Info("schedule", "now", now, "entry", entry.ID, "next", entry.Next) } for { // Determine the next entry to run. sort.Sort(byTime(c.entries)) var timer *time.Timer if len(c.entries) == 0 || c.entries[0].Next.IsZero() { // If there are no entries yet, just sleep - it still handles new entries // and stop requests. timer = time.NewTimer(100000 * time.Hour) } else { timer = time.NewTimer(c.entries[0].Next.Sub(now)) } for { select { case now = <-timer.C: now = now.In(c.location) c.logger.Info("wake", "now", now) // Run every entry whose next time was less than now for _, e := range c.entries { if e.Next.After(now) || e.Next.IsZero() { break } c.startJob(e.WrappedJob) e.Prev = e.Next e.Next = e.Schedule.Next(now) c.logger.Info("run", "now", now, "entry", e.ID, "next", e.Next) } case newEntry := <-c.add: timer.Stop() now = c.now() newEntry.Next = newEntry.Schedule.Next(now) c.entries = append(c.entries, newEntry) c.logger.Info("added", "now", now, "entry", newEntry.ID, "next", newEntry.Next) case replyChan := <-c.snapshot: replyChan <- c.entrySnapshot() continue case <-c.stop: timer.Stop() c.logger.Info("stop") return case id := <-c.remove: timer.Stop() now = c.now() c.removeEntry(id) c.logger.Info("removed", "entry", id) } break } } } // startJob runs the given job in a new goroutine. func (c *Cron) startJob(j Job) { c.jobWaiter.Go(func() { j.Run() }) } // now returns current time in c location. func (c *Cron) now() time.Time { return time.Now().In(c.location) } // Stop stops the cron scheduler if it is running; otherwise it does nothing. // A context is returned so the caller can wait for running jobs to complete. func (c *Cron) Stop() context.Context { c.runningMu.Lock() defer c.runningMu.Unlock() if c.running { c.stop <- struct{}{} c.running = false } ctx, cancel := context.WithCancel(context.Background()) go func() { c.jobWaiter.Wait() cancel() }() return ctx } // entrySnapshot returns a copy of the current cron entry list. func (c *Cron) entrySnapshot() []Entry { var entries = make([]Entry, len(c.entries)) for i, e := range c.entries { entries[i] = *e } return entries } func (c *Cron) removeEntry(id EntryID) { var entries []*Entry for _, e := range c.entries { if e.ID != id { entries = append(entries, e) } } c.entries = entries }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/cron/option.go
plugin/cron/option.go
package cron import ( "time" ) // Option represents a modification to the default behavior of a Cron. type Option func(*Cron) // WithLocation overrides the timezone of the cron instance. func WithLocation(loc *time.Location) Option { return func(c *Cron) { c.location = loc } } // WithSeconds overrides the parser used for interpreting job schedules to // include a seconds field as the first one. func WithSeconds() Option { return WithParser(NewParser( Second | Minute | Hour | Dom | Month | Dow | Descriptor, )) } // WithParser overrides the parser used for interpreting job schedules. func WithParser(p ScheduleParser) Option { return func(c *Cron) { c.parser = p } } // WithChain specifies Job wrappers to apply to all jobs added to this cron. // Refer to the Chain* functions in this package for provided wrappers. func WithChain(wrappers ...JobWrapper) Option { return func(c *Cron) { c.chain = NewChain(wrappers...) } } // WithLogger uses the provided logger. func WithLogger(logger Logger) Option { return func(c *Cron) { c.logger = logger } }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/cron/spec.go
plugin/cron/spec.go
package cron import "time" // SpecSchedule specifies a duty cycle (to the second granularity), based on a // traditional crontab specification. It is computed initially and stored as bit sets. type SpecSchedule struct { Second, Minute, Hour, Dom, Month, Dow uint64 // Override location for this schedule. Location *time.Location } // bounds provides a range of acceptable values (plus a map of name to value). type bounds struct { min, max uint names map[string]uint } // The bounds for each field. var ( seconds = bounds{0, 59, nil} minutes = bounds{0, 59, nil} hours = bounds{0, 23, nil} dom = bounds{1, 31, nil} months = bounds{1, 12, map[string]uint{ "jan": 1, "feb": 2, "mar": 3, "apr": 4, "may": 5, "jun": 6, "jul": 7, "aug": 8, "sep": 9, "oct": 10, "nov": 11, "dec": 12, }} dow = bounds{0, 6, map[string]uint{ "sun": 0, "mon": 1, "tue": 2, "wed": 3, "thu": 4, "fri": 5, "sat": 6, }} ) const ( // Set the top bit if a star was included in the expression. starBit = 1 << 63 ) // Next returns the next time this schedule is activated, greater than the given // time. If no time can be found to satisfy the schedule, return the zero time. func (s *SpecSchedule) Next(t time.Time) time.Time { // General approach // // For Month, Day, Hour, Minute, Second: // Check if the time value matches. If yes, continue to the next field. // If the field doesn't match the schedule, then increment the field until it matches. // While incrementing the field, a wrap-around brings it back to the beginning // of the field list (since it is necessary to re-verify previous field // values) // Convert the given time into the schedule's timezone, if one is specified. // Save the original timezone so we can convert back after we find a time. // Note that schedules without a time zone specified (time.Local) are treated // as local to the time provided. origLocation := t.Location() loc := s.Location if loc == time.Local { loc = t.Location() } if s.Location != time.Local { t = t.In(s.Location) } // Start at the earliest possible time (the upcoming second). t = t.Add(1*time.Second - time.Duration(t.Nanosecond())*time.Nanosecond) // This flag indicates whether a field has been incremented. added := false // If no time is found within five years, return zero. yearLimit := t.Year() + 5 WRAP: if t.Year() > yearLimit { return time.Time{} } // Find the first applicable month. // If it's this month, then do nothing. for 1<<uint(t.Month())&s.Month == 0 { // If we have to add a month, reset the other parts to 0. if !added { added = true // Otherwise, set the date at the beginning (since the current time is irrelevant). t = time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, loc) } t = t.AddDate(0, 1, 0) // Wrapped around. if t.Month() == time.January { goto WRAP } } // Now get a day in that month. // // NOTE: This causes issues for daylight savings regimes where midnight does // not exist. For example: Sao Paulo has DST that transforms midnight on // 11/3 into 1am. Handle that by noticing when the Hour ends up != 0. for !dayMatches(s, t) { if !added { added = true t = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, loc) } t = t.AddDate(0, 0, 1) // Notice if the hour is no longer midnight due to DST. // Add an hour if it's 23, subtract an hour if it's 1. if t.Hour() != 0 { if t.Hour() > 12 { t = t.Add(time.Duration(24-t.Hour()) * time.Hour) } else { t = t.Add(time.Duration(-t.Hour()) * time.Hour) } } if t.Day() == 1 { goto WRAP } } for 1<<uint(t.Hour())&s.Hour == 0 { if !added { added = true t = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), 0, 0, 0, loc) } t = t.Add(1 * time.Hour) if t.Hour() == 0 { goto WRAP } } for 1<<uint(t.Minute())&s.Minute == 0 { if !added { added = true t = t.Truncate(time.Minute) } t = t.Add(1 * time.Minute) if t.Minute() == 0 { goto WRAP } } for 1<<uint(t.Second())&s.Second == 0 { if !added { added = true t = t.Truncate(time.Second) } t = t.Add(1 * time.Second) if t.Second() == 0 { goto WRAP } } return t.In(origLocation) } // dayMatches returns true if the schedule's day-of-week and day-of-month // restrictions are satisfied by the given time. func dayMatches(s *SpecSchedule, t time.Time) bool { var ( domMatch = 1<<uint(t.Day())&s.Dom > 0 dowMatch = 1<<uint(t.Weekday())&s.Dow > 0 ) if s.Dom&starBit > 0 || s.Dow&starBit > 0 { return domMatch && dowMatch } return domMatch || dowMatch }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/cron/chain_test.go
plugin/cron/chain_test.go
//nolint:all package cron import ( "io" "log" "reflect" "sync" "testing" "time" ) func appendingJob(slice *[]int, value int) Job { var m sync.Mutex return FuncJob(func() { m.Lock() *slice = append(*slice, value) m.Unlock() }) } func appendingWrapper(slice *[]int, value int) JobWrapper { return func(j Job) Job { return FuncJob(func() { appendingJob(slice, value).Run() j.Run() }) } } func TestChain(t *testing.T) { var nums []int var ( append1 = appendingWrapper(&nums, 1) append2 = appendingWrapper(&nums, 2) append3 = appendingWrapper(&nums, 3) append4 = appendingJob(&nums, 4) ) NewChain(append1, append2, append3).Then(append4).Run() if !reflect.DeepEqual(nums, []int{1, 2, 3, 4}) { t.Error("unexpected order of calls:", nums) } } func TestChainRecover(t *testing.T) { panickingJob := FuncJob(func() { panic("panickingJob panics") }) t.Run("panic exits job by default", func(*testing.T) { defer func() { if err := recover(); err == nil { t.Errorf("panic expected, but none received") } }() NewChain().Then(panickingJob). Run() }) t.Run("Recovering JobWrapper recovers", func(*testing.T) { NewChain(Recover(PrintfLogger(log.New(io.Discard, "", 0)))). Then(panickingJob). Run() }) t.Run("composed with the *IfStillRunning wrappers", func(*testing.T) { NewChain(Recover(PrintfLogger(log.New(io.Discard, "", 0)))). Then(panickingJob). Run() }) } type countJob struct { m sync.Mutex started int done int delay time.Duration } func (j *countJob) Run() { j.m.Lock() j.started++ j.m.Unlock() time.Sleep(j.delay) j.m.Lock() j.done++ j.m.Unlock() } func (j *countJob) Started() int { defer j.m.Unlock() j.m.Lock() return j.started } func (j *countJob) Done() int { defer j.m.Unlock() j.m.Lock() return j.done } func TestChainDelayIfStillRunning(t *testing.T) { t.Run("runs immediately", func(*testing.T) { var j countJob wrappedJob := NewChain(DelayIfStillRunning(DiscardLogger)).Then(&j) go wrappedJob.Run() time.Sleep(2 * time.Millisecond) // Give the job 2ms to complete. if c := j.Done(); c != 1 { t.Errorf("expected job run once, immediately, got %d", c) } }) t.Run("second run immediate if first done", func(*testing.T) { var j countJob wrappedJob := NewChain(DelayIfStillRunning(DiscardLogger)).Then(&j) go func() { go wrappedJob.Run() time.Sleep(time.Millisecond) go wrappedJob.Run() }() time.Sleep(3 * time.Millisecond) // Give both jobs 3ms to complete. if c := j.Done(); c != 2 { t.Errorf("expected job run twice, immediately, got %d", c) } }) t.Run("second run delayed if first not done", func(*testing.T) { var j countJob j.delay = 10 * time.Millisecond wrappedJob := NewChain(DelayIfStillRunning(DiscardLogger)).Then(&j) go func() { go wrappedJob.Run() time.Sleep(time.Millisecond) go wrappedJob.Run() }() // After 5ms, the first job is still in progress, and the second job was // run but should be waiting for it to finish. time.Sleep(5 * time.Millisecond) started, done := j.Started(), j.Done() if started != 1 || done != 0 { t.Error("expected first job started, but not finished, got", started, done) } // Verify that the second job completes. time.Sleep(25 * time.Millisecond) started, done = j.Started(), j.Done() if started != 2 || done != 2 { t.Error("expected both jobs done, got", started, done) } }) } func TestChainSkipIfStillRunning(t *testing.T) { t.Run("runs immediately", func(*testing.T) { var j countJob wrappedJob := NewChain(SkipIfStillRunning(DiscardLogger)).Then(&j) go wrappedJob.Run() time.Sleep(2 * time.Millisecond) // Give the job 2ms to complete. if c := j.Done(); c != 1 { t.Errorf("expected job run once, immediately, got %d", c) } }) t.Run("second run immediate if first done", func(*testing.T) { var j countJob wrappedJob := NewChain(SkipIfStillRunning(DiscardLogger)).Then(&j) go func() { go wrappedJob.Run() time.Sleep(time.Millisecond) go wrappedJob.Run() }() time.Sleep(3 * time.Millisecond) // Give both jobs 3ms to complete. if c := j.Done(); c != 2 { t.Errorf("expected job run twice, immediately, got %d", c) } }) t.Run("second run skipped if first not done", func(*testing.T) { var j countJob j.delay = 10 * time.Millisecond wrappedJob := NewChain(SkipIfStillRunning(DiscardLogger)).Then(&j) go func() { go wrappedJob.Run() time.Sleep(time.Millisecond) go wrappedJob.Run() }() // After 5ms, the first job is still in progress, and the second job was // already skipped. time.Sleep(5 * time.Millisecond) started, done := j.Started(), j.Done() if started != 1 || done != 0 { t.Error("expected first job started, but not finished, got", started, done) } // Verify that the first job completes and second does not run. time.Sleep(25 * time.Millisecond) started, done = j.Started(), j.Done() if started != 1 || done != 1 { t.Error("expected second job skipped, got", started, done) } }) t.Run("skip 10 jobs on rapid fire", func(*testing.T) { var j countJob j.delay = 10 * time.Millisecond wrappedJob := NewChain(SkipIfStillRunning(DiscardLogger)).Then(&j) for i := 0; i < 11; i++ { go wrappedJob.Run() } time.Sleep(200 * time.Millisecond) done := j.Done() if done != 1 { t.Error("expected 1 jobs executed, 10 jobs dropped, got", done) } }) t.Run("different jobs independent", func(*testing.T) { var j1, j2 countJob j1.delay = 10 * time.Millisecond j2.delay = 10 * time.Millisecond chain := NewChain(SkipIfStillRunning(DiscardLogger)) wrappedJob1 := chain.Then(&j1) wrappedJob2 := chain.Then(&j2) for i := 0; i < 11; i++ { go wrappedJob1.Run() go wrappedJob2.Run() } time.Sleep(100 * time.Millisecond) var ( done1 = j1.Done() done2 = j2.Done() ) if done1 != 1 || done2 != 1 { t.Error("expected both jobs executed once, got", done1, "and", done2) } }) }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/cron/option_test.go
plugin/cron/option_test.go
//nolint:all package cron import ( "log" "strings" "testing" "time" ) func TestWithLocation(t *testing.T) { c := New(WithLocation(time.UTC)) if c.location != time.UTC { t.Errorf("expected UTC, got %v", c.location) } } func TestWithParser(t *testing.T) { var parser = NewParser(Dow) c := New(WithParser(parser)) if c.parser != parser { t.Error("expected provided parser") } } func TestWithVerboseLogger(t *testing.T) { var buf syncWriter var logger = log.New(&buf, "", log.LstdFlags) c := New(WithLogger(VerbosePrintfLogger(logger))) if c.logger.(printfLogger).logger != logger { t.Error("expected provided logger") } c.AddFunc("@every 1s", func() {}) c.Start() time.Sleep(OneSecond) c.Stop() out := buf.String() if !strings.Contains(out, "schedule,") || !strings.Contains(out, "run,") { t.Error("expected to see some actions, got:", out) } }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/cron/parser_test.go
plugin/cron/parser_test.go
//nolint:all package cron import ( "reflect" "strings" "testing" "time" ) var secondParser = NewParser(Second | Minute | Hour | Dom | Month | DowOptional | Descriptor) func TestRange(t *testing.T) { zero := uint64(0) ranges := []struct { expr string min, max uint expected uint64 err string }{ {"5", 0, 7, 1 << 5, ""}, {"0", 0, 7, 1 << 0, ""}, {"7", 0, 7, 1 << 7, ""}, {"5-5", 0, 7, 1 << 5, ""}, {"5-6", 0, 7, 1<<5 | 1<<6, ""}, {"5-7", 0, 7, 1<<5 | 1<<6 | 1<<7, ""}, {"5-6/2", 0, 7, 1 << 5, ""}, {"5-7/2", 0, 7, 1<<5 | 1<<7, ""}, {"5-7/1", 0, 7, 1<<5 | 1<<6 | 1<<7, ""}, {"*", 1, 3, 1<<1 | 1<<2 | 1<<3 | starBit, ""}, {"*/2", 1, 3, 1<<1 | 1<<3, ""}, {"5--5", 0, 0, zero, "too many hyphens"}, {"jan-x", 0, 0, zero, `failed to parse number: strconv.Atoi: parsing "jan": invalid syntax`}, {"2-x", 1, 5, zero, `failed to parse number: strconv.Atoi: parsing "x": invalid syntax`}, {"*/-12", 0, 0, zero, "number must be positive"}, {"*//2", 0, 0, zero, "too many slashes"}, {"1", 3, 5, zero, "below minimum"}, {"6", 3, 5, zero, "above maximum"}, {"5-3", 3, 5, zero, "beginning of range after end: 5-3"}, {"*/0", 0, 0, zero, "step cannot be zero: */0"}, } for _, c := range ranges { actual, err := getRange(c.expr, bounds{c.min, c.max, nil}) if len(c.err) != 0 && (err == nil || !strings.Contains(err.Error(), c.err)) { t.Errorf("%s => expected %v, got %v", c.expr, c.err, err) } if len(c.err) == 0 && err != nil { t.Errorf("%s => unexpected error %v", c.expr, err) } if actual != c.expected { t.Errorf("%s => expected %d, got %d", c.expr, c.expected, actual) } } } func TestField(t *testing.T) { fields := []struct { expr string min, max uint expected uint64 }{ {"5", 1, 7, 1 << 5}, {"5,6", 1, 7, 1<<5 | 1<<6}, {"5,6,7", 1, 7, 1<<5 | 1<<6 | 1<<7}, {"1,5-7/2,3", 1, 7, 1<<1 | 1<<5 | 1<<7 | 1<<3}, } for _, c := range fields { actual, _ := getField(c.expr, bounds{c.min, c.max, nil}) if actual != c.expected { t.Errorf("%s => expected %d, got %d", c.expr, c.expected, actual) } } } func TestAll(t *testing.T) { allBits := []struct { r bounds expected uint64 }{ {minutes, 0xfffffffffffffff}, // 0-59: 60 ones {hours, 0xffffff}, // 0-23: 24 ones {dom, 0xfffffffe}, // 1-31: 31 ones, 1 zero {months, 0x1ffe}, // 1-12: 12 ones, 1 zero {dow, 0x7f}, // 0-6: 7 ones } for _, c := range allBits { actual := all(c.r) // all() adds the starBit, so compensate for that.. if c.expected|starBit != actual { t.Errorf("%d-%d/%d => expected %b, got %b", c.r.min, c.r.max, 1, c.expected|starBit, actual) } } } func TestBits(t *testing.T) { bits := []struct { min, max, step uint expected uint64 }{ {0, 0, 1, 0x1}, {1, 1, 1, 0x2}, {1, 5, 2, 0x2a}, // 101010 {1, 4, 2, 0xa}, // 1010 } for _, c := range bits { actual := getBits(c.min, c.max, c.step) if c.expected != actual { t.Errorf("%d-%d/%d => expected %b, got %b", c.min, c.max, c.step, c.expected, actual) } } } func TestParseScheduleErrors(t *testing.T) { var tests = []struct{ expr, err string }{ {"* 5 j * * *", `failed to parse number: strconv.Atoi: parsing "j": invalid syntax`}, {"@every Xm", "failed to parse duration"}, {"@unrecognized", "unrecognized descriptor"}, {"* * * *", "incorrect number of fields, expected 5-6"}, {"", "empty spec string"}, } for _, c := range tests { actual, err := secondParser.Parse(c.expr) if err == nil || !strings.Contains(err.Error(), c.err) { t.Errorf("%s => expected %v, got %v", c.expr, c.err, err) } if actual != nil { t.Errorf("expected nil schedule on error, got %v", actual) } } } func TestParseSchedule(t *testing.T) { tokyo, _ := time.LoadLocation("Asia/Tokyo") entries := []struct { parser Parser expr string expected Schedule }{ {secondParser, "0 5 * * * *", every5min(time.Local)}, {standardParser, "5 * * * *", every5min(time.Local)}, {secondParser, "CRON_TZ=UTC 0 5 * * * *", every5min(time.UTC)}, {standardParser, "CRON_TZ=UTC 5 * * * *", every5min(time.UTC)}, {secondParser, "CRON_TZ=Asia/Tokyo 0 5 * * * *", every5min(tokyo)}, {secondParser, "@every 5m", ConstantDelaySchedule{5 * time.Minute}}, {secondParser, "@midnight", midnight(time.Local)}, {secondParser, "TZ=UTC @midnight", midnight(time.UTC)}, {secondParser, "TZ=Asia/Tokyo @midnight", midnight(tokyo)}, {secondParser, "@yearly", annual(time.Local)}, {secondParser, "@annually", annual(time.Local)}, { parser: secondParser, expr: "* 5 * * * *", expected: &SpecSchedule{ Second: all(seconds), Minute: 1 << 5, Hour: all(hours), Dom: all(dom), Month: all(months), Dow: all(dow), Location: time.Local, }, }, } for _, c := range entries { actual, err := c.parser.Parse(c.expr) if err != nil { t.Errorf("%s => unexpected error %v", c.expr, err) } if !reflect.DeepEqual(actual, c.expected) { t.Errorf("%s => expected %b, got %b", c.expr, c.expected, actual) } } } func TestOptionalSecondSchedule(t *testing.T) { parser := NewParser(SecondOptional | Minute | Hour | Dom | Month | Dow | Descriptor) entries := []struct { expr string expected Schedule }{ {"0 5 * * * *", every5min(time.Local)}, {"5 5 * * * *", every5min5s(time.Local)}, {"5 * * * *", every5min(time.Local)}, } for _, c := range entries { actual, err := parser.Parse(c.expr) if err != nil { t.Errorf("%s => unexpected error %v", c.expr, err) } if !reflect.DeepEqual(actual, c.expected) { t.Errorf("%s => expected %b, got %b", c.expr, c.expected, actual) } } } func TestNormalizeFields(t *testing.T) { tests := []struct { name string input []string options ParseOption expected []string }{ { "AllFields_NoOptional", []string{"0", "5", "*", "*", "*", "*"}, Second | Minute | Hour | Dom | Month | Dow | Descriptor, []string{"0", "5", "*", "*", "*", "*"}, }, { "AllFields_SecondOptional_Provided", []string{"0", "5", "*", "*", "*", "*"}, SecondOptional | Minute | Hour | Dom | Month | Dow | Descriptor, []string{"0", "5", "*", "*", "*", "*"}, }, { "AllFields_SecondOptional_NotProvided", []string{"5", "*", "*", "*", "*"}, SecondOptional | Minute | Hour | Dom | Month | Dow | Descriptor, []string{"0", "5", "*", "*", "*", "*"}, }, { "SubsetFields_NoOptional", []string{"5", "15", "*"}, Hour | Dom | Month, []string{"0", "0", "5", "15", "*", "*"}, }, { "SubsetFields_DowOptional_Provided", []string{"5", "15", "*", "4"}, Hour | Dom | Month | DowOptional, []string{"0", "0", "5", "15", "*", "4"}, }, { "SubsetFields_DowOptional_NotProvided", []string{"5", "15", "*"}, Hour | Dom | Month | DowOptional, []string{"0", "0", "5", "15", "*", "*"}, }, { "SubsetFields_SecondOptional_NotProvided", []string{"5", "15", "*"}, SecondOptional | Hour | Dom | Month, []string{"0", "0", "5", "15", "*", "*"}, }, } for _, test := range tests { t.Run(test.name, func(*testing.T) { actual, err := normalizeFields(test.input, test.options) if err != nil { t.Errorf("unexpected error: %v", err) } if !reflect.DeepEqual(actual, test.expected) { t.Errorf("expected %v, got %v", test.expected, actual) } }) } } func TestNormalizeFields_Errors(t *testing.T) { tests := []struct { name string input []string options ParseOption err string }{ { "TwoOptionals", []string{"0", "5", "*", "*", "*", "*"}, SecondOptional | Minute | Hour | Dom | Month | DowOptional, "", }, { "TooManyFields", []string{"0", "5", "*", "*"}, SecondOptional | Minute | Hour, "", }, { "NoFields", []string{}, SecondOptional | Minute | Hour, "", }, { "TooFewFields", []string{"*"}, SecondOptional | Minute | Hour, "", }, } for _, test := range tests { t.Run(test.name, func(*testing.T) { actual, err := normalizeFields(test.input, test.options) if err == nil { t.Errorf("expected an error, got none. results: %v", actual) } if !strings.Contains(err.Error(), test.err) { t.Errorf("expected error %q, got %q", test.err, err.Error()) } }) } } func TestStandardSpecSchedule(t *testing.T) { entries := []struct { expr string expected Schedule err string }{ { expr: "5 * * * *", expected: &SpecSchedule{1 << seconds.min, 1 << 5, all(hours), all(dom), all(months), all(dow), time.Local}, }, { expr: "@every 5m", expected: ConstantDelaySchedule{time.Duration(5) * time.Minute}, }, { expr: "5 j * * *", err: `failed to parse number: strconv.Atoi: parsing "j": invalid syntax`, }, { expr: "* * * *", err: "incorrect number of fields", }, } for _, c := range entries { actual, err := ParseStandard(c.expr) if len(c.err) != 0 && (err == nil || !strings.Contains(err.Error(), c.err)) { t.Errorf("%s => expected %v, got %v", c.expr, c.err, err) } if len(c.err) == 0 && err != nil { t.Errorf("%s => unexpected error %v", c.expr, err) } if !reflect.DeepEqual(actual, c.expected) { t.Errorf("%s => expected %b, got %b", c.expr, c.expected, actual) } } } func TestNoDescriptorParser(t *testing.T) { parser := NewParser(Minute | Hour) _, err := parser.Parse("@every 1m") if err == nil { t.Error("expected an error, got none") } } func every5min(loc *time.Location) *SpecSchedule { return &SpecSchedule{1 << 0, 1 << 5, all(hours), all(dom), all(months), all(dow), loc} } func every5min5s(loc *time.Location) *SpecSchedule { return &SpecSchedule{1 << 5, 1 << 5, all(hours), all(dom), all(months), all(dow), loc} } func midnight(loc *time.Location) *SpecSchedule { return &SpecSchedule{1, 1, 1, all(dom), all(months), all(dow), loc} } func annual(loc *time.Location) *SpecSchedule { return &SpecSchedule{ Second: 1 << seconds.min, Minute: 1 << minutes.min, Hour: 1 << hours.min, Dom: 1 << dom.min, Month: 1 << months.min, Dow: all(dow), Location: loc, } }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/cron/chain.go
plugin/cron/chain.go
package cron import ( "errors" "fmt" "runtime" "sync" "time" ) // JobWrapper decorates the given Job with some behavior. type JobWrapper func(Job) Job // Chain is a sequence of JobWrappers that decorates submitted jobs with // cross-cutting behaviors like logging or synchronization. type Chain struct { wrappers []JobWrapper } // NewChain returns a Chain consisting of the given JobWrappers. func NewChain(c ...JobWrapper) Chain { return Chain{c} } // Then decorates the given job with all JobWrappers in the chain. // // This: // // NewChain(m1, m2, m3).Then(job) // // is equivalent to: // // m1(m2(m3(job))) func (c Chain) Then(j Job) Job { for i := range c.wrappers { j = c.wrappers[len(c.wrappers)-i-1](j) } return j } // Recover panics in wrapped jobs and log them with the provided logger. func Recover(logger Logger) JobWrapper { return func(j Job) Job { return FuncJob(func() { defer func() { if r := recover(); r != nil { const size = 64 << 10 buf := make([]byte, size) buf = buf[:runtime.Stack(buf, false)] err, ok := r.(error) if !ok { err = errors.New("panic: " + fmt.Sprint(r)) } logger.Error(err, "panic", "stack", "...\n"+string(buf)) } }() j.Run() }) } } // DelayIfStillRunning serializes jobs, delaying subsequent runs until the // previous one is complete. Jobs running after a delay of more than a minute // have the delay logged at Info. func DelayIfStillRunning(logger Logger) JobWrapper { return func(j Job) Job { var mu sync.Mutex return FuncJob(func() { start := time.Now() mu.Lock() defer mu.Unlock() if dur := time.Since(start); dur > time.Minute { logger.Info("delay", "duration", dur) } j.Run() }) } } // SkipIfStillRunning skips an invocation of the Job if a previous invocation is // still running. It logs skips to the given logger at Info level. func SkipIfStillRunning(logger Logger) JobWrapper { return func(j Job) Job { var ch = make(chan struct{}, 1) ch <- struct{}{} return FuncJob(func() { select { case v := <-ch: defer func() { ch <- v }() j.Run() default: logger.Info("skip") } }) } }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/cron/spec_test.go
plugin/cron/spec_test.go
//nolint:all package cron import ( "strings" "testing" "time" ) func TestActivation(t *testing.T) { tests := []struct { time, spec string expected bool }{ // Every fifteen minutes. {"Mon Jul 9 15:00 2012", "0/15 * * * *", true}, {"Mon Jul 9 15:45 2012", "0/15 * * * *", true}, {"Mon Jul 9 15:40 2012", "0/15 * * * *", false}, // Every fifteen minutes, starting at 5 minutes. {"Mon Jul 9 15:05 2012", "5/15 * * * *", true}, {"Mon Jul 9 15:20 2012", "5/15 * * * *", true}, {"Mon Jul 9 15:50 2012", "5/15 * * * *", true}, // Named months {"Sun Jul 15 15:00 2012", "0/15 * * Jul *", true}, {"Sun Jul 15 15:00 2012", "0/15 * * Jun *", false}, // Everything set. {"Sun Jul 15 08:30 2012", "30 08 ? Jul Sun", true}, {"Sun Jul 15 08:30 2012", "30 08 15 Jul ?", true}, {"Mon Jul 16 08:30 2012", "30 08 ? Jul Sun", false}, {"Mon Jul 16 08:30 2012", "30 08 15 Jul ?", false}, // Predefined schedules {"Mon Jul 9 15:00 2012", "@hourly", true}, {"Mon Jul 9 15:04 2012", "@hourly", false}, {"Mon Jul 9 15:00 2012", "@daily", false}, {"Mon Jul 9 00:00 2012", "@daily", true}, {"Mon Jul 9 00:00 2012", "@weekly", false}, {"Sun Jul 8 00:00 2012", "@weekly", true}, {"Sun Jul 8 01:00 2012", "@weekly", false}, {"Sun Jul 8 00:00 2012", "@monthly", false}, {"Sun Jul 1 00:00 2012", "@monthly", true}, // Test interaction of DOW and DOM. // If both are restricted, then only one needs to match. {"Sun Jul 15 00:00 2012", "* * 1,15 * Sun", true}, {"Fri Jun 15 00:00 2012", "* * 1,15 * Sun", true}, {"Wed Aug 1 00:00 2012", "* * 1,15 * Sun", true}, {"Sun Jul 15 00:00 2012", "* * */10 * Sun", true}, // verifies #70 // However, if one has a star, then both need to match. {"Sun Jul 15 00:00 2012", "* * * * Mon", false}, {"Mon Jul 9 00:00 2012", "* * 1,15 * *", false}, {"Sun Jul 15 00:00 2012", "* * 1,15 * *", true}, {"Sun Jul 15 00:00 2012", "* * */2 * Sun", true}, } for _, test := range tests { sched, err := ParseStandard(test.spec) if err != nil { t.Error(err) continue } actual := sched.Next(getTime(test.time).Add(-1 * time.Second)) expected := getTime(test.time) if test.expected && expected != actual || !test.expected && expected == actual { t.Errorf("Fail evaluating %s on %s: (expected) %s != %s (actual)", test.spec, test.time, expected, actual) } } } func TestNext(t *testing.T) { runs := []struct { time, spec string expected string }{ // Simple cases {"Mon Jul 9 14:45 2012", "0 0/15 * * * *", "Mon Jul 9 15:00 2012"}, {"Mon Jul 9 14:59 2012", "0 0/15 * * * *", "Mon Jul 9 15:00 2012"}, {"Mon Jul 9 14:59:59 2012", "0 0/15 * * * *", "Mon Jul 9 15:00 2012"}, // Wrap around hours {"Mon Jul 9 15:45 2012", "0 20-35/15 * * * *", "Mon Jul 9 16:20 2012"}, // Wrap around days {"Mon Jul 9 23:46 2012", "0 */15 * * * *", "Tue Jul 10 00:00 2012"}, {"Mon Jul 9 23:45 2012", "0 20-35/15 * * * *", "Tue Jul 10 00:20 2012"}, {"Mon Jul 9 23:35:51 2012", "15/35 20-35/15 * * * *", "Tue Jul 10 00:20:15 2012"}, {"Mon Jul 9 23:35:51 2012", "15/35 20-35/15 1/2 * * *", "Tue Jul 10 01:20:15 2012"}, {"Mon Jul 9 23:35:51 2012", "15/35 20-35/15 10-12 * * *", "Tue Jul 10 10:20:15 2012"}, {"Mon Jul 9 23:35:51 2012", "15/35 20-35/15 1/2 */2 * *", "Thu Jul 11 01:20:15 2012"}, {"Mon Jul 9 23:35:51 2012", "15/35 20-35/15 * 9-20 * *", "Wed Jul 10 00:20:15 2012"}, {"Mon Jul 9 23:35:51 2012", "15/35 20-35/15 * 9-20 Jul *", "Wed Jul 10 00:20:15 2012"}, // Wrap around months {"Mon Jul 9 23:35 2012", "0 0 0 9 Apr-Oct ?", "Thu Aug 9 00:00 2012"}, {"Mon Jul 9 23:35 2012", "0 0 0 */5 Apr,Aug,Oct Mon", "Tue Aug 1 00:00 2012"}, {"Mon Jul 9 23:35 2012", "0 0 0 */5 Oct Mon", "Mon Oct 1 00:00 2012"}, // Wrap around years {"Mon Jul 9 23:35 2012", "0 0 0 * Feb Mon", "Mon Feb 4 00:00 2013"}, {"Mon Jul 9 23:35 2012", "0 0 0 * Feb Mon/2", "Fri Feb 1 00:00 2013"}, // Wrap around minute, hour, day, month, and year {"Mon Dec 31 23:59:45 2012", "0 * * * * *", "Tue Jan 1 00:00:00 2013"}, // Leap year {"Mon Jul 9 23:35 2012", "0 0 0 29 Feb ?", "Mon Feb 29 00:00 2016"}, // Daylight savings time 2am EST (-5) -> 3am EDT (-4) {"2012-03-11T00:00:00-0500", "TZ=America/New_York 0 30 2 11 Mar ?", "2013-03-11T02:30:00-0400"}, // hourly job {"2012-03-11T00:00:00-0500", "TZ=America/New_York 0 0 * * * ?", "2012-03-11T01:00:00-0500"}, {"2012-03-11T01:00:00-0500", "TZ=America/New_York 0 0 * * * ?", "2012-03-11T03:00:00-0400"}, {"2012-03-11T03:00:00-0400", "TZ=America/New_York 0 0 * * * ?", "2012-03-11T04:00:00-0400"}, {"2012-03-11T04:00:00-0400", "TZ=America/New_York 0 0 * * * ?", "2012-03-11T05:00:00-0400"}, // hourly job using CRON_TZ {"2012-03-11T00:00:00-0500", "CRON_TZ=America/New_York 0 0 * * * ?", "2012-03-11T01:00:00-0500"}, {"2012-03-11T01:00:00-0500", "CRON_TZ=America/New_York 0 0 * * * ?", "2012-03-11T03:00:00-0400"}, {"2012-03-11T03:00:00-0400", "CRON_TZ=America/New_York 0 0 * * * ?", "2012-03-11T04:00:00-0400"}, {"2012-03-11T04:00:00-0400", "CRON_TZ=America/New_York 0 0 * * * ?", "2012-03-11T05:00:00-0400"}, // 1am nightly job {"2012-03-11T00:00:00-0500", "TZ=America/New_York 0 0 1 * * ?", "2012-03-11T01:00:00-0500"}, {"2012-03-11T01:00:00-0500", "TZ=America/New_York 0 0 1 * * ?", "2012-03-12T01:00:00-0400"}, // 2am nightly job (skipped) {"2012-03-11T00:00:00-0500", "TZ=America/New_York 0 0 2 * * ?", "2012-03-12T02:00:00-0400"}, // Daylight savings time 2am EDT (-4) => 1am EST (-5) {"2012-11-04T00:00:00-0400", "TZ=America/New_York 0 30 2 04 Nov ?", "2012-11-04T02:30:00-0500"}, {"2012-11-04T01:45:00-0400", "TZ=America/New_York 0 30 1 04 Nov ?", "2012-11-04T01:30:00-0500"}, // hourly job {"2012-11-04T00:00:00-0400", "TZ=America/New_York 0 0 * * * ?", "2012-11-04T01:00:00-0400"}, {"2012-11-04T01:00:00-0400", "TZ=America/New_York 0 0 * * * ?", "2012-11-04T01:00:00-0500"}, {"2012-11-04T01:00:00-0500", "TZ=America/New_York 0 0 * * * ?", "2012-11-04T02:00:00-0500"}, // 1am nightly job (runs twice) {"2012-11-04T00:00:00-0400", "TZ=America/New_York 0 0 1 * * ?", "2012-11-04T01:00:00-0400"}, {"2012-11-04T01:00:00-0400", "TZ=America/New_York 0 0 1 * * ?", "2012-11-04T01:00:00-0500"}, {"2012-11-04T01:00:00-0500", "TZ=America/New_York 0 0 1 * * ?", "2012-11-05T01:00:00-0500"}, // 2am nightly job {"2012-11-04T00:00:00-0400", "TZ=America/New_York 0 0 2 * * ?", "2012-11-04T02:00:00-0500"}, {"2012-11-04T02:00:00-0500", "TZ=America/New_York 0 0 2 * * ?", "2012-11-05T02:00:00-0500"}, // 3am nightly job {"2012-11-04T00:00:00-0400", "TZ=America/New_York 0 0 3 * * ?", "2012-11-04T03:00:00-0500"}, {"2012-11-04T03:00:00-0500", "TZ=America/New_York 0 0 3 * * ?", "2012-11-05T03:00:00-0500"}, // hourly job {"TZ=America/New_York 2012-11-04T00:00:00-0400", "0 0 * * * ?", "2012-11-04T01:00:00-0400"}, {"TZ=America/New_York 2012-11-04T01:00:00-0400", "0 0 * * * ?", "2012-11-04T01:00:00-0500"}, {"TZ=America/New_York 2012-11-04T01:00:00-0500", "0 0 * * * ?", "2012-11-04T02:00:00-0500"}, // 1am nightly job (runs twice) {"TZ=America/New_York 2012-11-04T00:00:00-0400", "0 0 1 * * ?", "2012-11-04T01:00:00-0400"}, {"TZ=America/New_York 2012-11-04T01:00:00-0400", "0 0 1 * * ?", "2012-11-04T01:00:00-0500"}, {"TZ=America/New_York 2012-11-04T01:00:00-0500", "0 0 1 * * ?", "2012-11-05T01:00:00-0500"}, // 2am nightly job {"TZ=America/New_York 2012-11-04T00:00:00-0400", "0 0 2 * * ?", "2012-11-04T02:00:00-0500"}, {"TZ=America/New_York 2012-11-04T02:00:00-0500", "0 0 2 * * ?", "2012-11-05T02:00:00-0500"}, // 3am nightly job {"TZ=America/New_York 2012-11-04T00:00:00-0400", "0 0 3 * * ?", "2012-11-04T03:00:00-0500"}, {"TZ=America/New_York 2012-11-04T03:00:00-0500", "0 0 3 * * ?", "2012-11-05T03:00:00-0500"}, // Unsatisfiable {"Mon Jul 9 23:35 2012", "0 0 0 30 Feb ?", ""}, {"Mon Jul 9 23:35 2012", "0 0 0 31 Apr ?", ""}, // Monthly job {"TZ=America/New_York 2012-11-04T00:00:00-0400", "0 0 3 3 * ?", "2012-12-03T03:00:00-0500"}, // Test the scenario of DST resulting in midnight not being a valid time. // https://github.com/robfig/cron/issues/157 {"2018-10-17T05:00:00-0400", "TZ=America/Sao_Paulo 0 0 9 10 * ?", "2018-11-10T06:00:00-0500"}, {"2018-02-14T05:00:00-0500", "TZ=America/Sao_Paulo 0 0 9 22 * ?", "2018-02-22T07:00:00-0500"}, } for _, c := range runs { sched, err := secondParser.Parse(c.spec) if err != nil { t.Error(err) continue } actual := sched.Next(getTime(c.time)) expected := getTime(c.expected) if !actual.Equal(expected) { t.Errorf("%s, \"%s\": (expected) %v != %v (actual)", c.time, c.spec, expected, actual) } } } func TestErrors(t *testing.T) { invalidSpecs := []string{ "xyz", "60 0 * * *", "0 60 * * *", "0 0 * * XYZ", } for _, spec := range invalidSpecs { _, err := ParseStandard(spec) if err == nil { t.Error("expected an error parsing: ", spec) } } } func getTime(value string) time.Time { if value == "" { return time.Time{} } var location = time.Local if strings.HasPrefix(value, "TZ=") { parts := strings.Fields(value) loc, err := time.LoadLocation(parts[0][len("TZ="):]) if err != nil { panic("could not parse location:" + err.Error()) } location = loc value = parts[1] } var layouts = []string{ "Mon Jan 2 15:04 2006", "Mon Jan 2 15:04:05 2006", } for _, layout := range layouts { if t, err := time.ParseInLocation(layout, value, location); err == nil { return t } } if t, err := time.ParseInLocation("2006-01-02T15:04:05-0700", value, location); err == nil { return t } panic("could not parse time value " + value) } func TestNextWithTz(t *testing.T) { runs := []struct { time, spec string expected string }{ // Failing tests {"2016-01-03T13:09:03+0530", "14 14 * * *", "2016-01-03T14:14:00+0530"}, {"2016-01-03T04:09:03+0530", "14 14 * * ?", "2016-01-03T14:14:00+0530"}, // Passing tests {"2016-01-03T14:09:03+0530", "14 14 * * *", "2016-01-03T14:14:00+0530"}, {"2016-01-03T14:00:00+0530", "14 14 * * ?", "2016-01-03T14:14:00+0530"}, } for _, c := range runs { sched, err := ParseStandard(c.spec) if err != nil { t.Error(err) continue } actual := sched.Next(getTimeTZ(c.time)) expected := getTimeTZ(c.expected) if !actual.Equal(expected) { t.Errorf("%s, \"%s\": (expected) %v != %v (actual)", c.time, c.spec, expected, actual) } } } func getTimeTZ(value string) time.Time { if value == "" { return time.Time{} } t, err := time.Parse("Mon Jan 2 15:04 2006", value) if err != nil { t, err = time.Parse("Mon Jan 2 15:04:05 2006", value) if err != nil { t, err = time.Parse("2006-01-02T15:04:05-0700", value) if err != nil { panic(err) } } } return t } // https://github.com/robfig/cron/issues/144 func TestSlash0NoHang(t *testing.T) { schedule := "TZ=America/New_York 15/0 * * * *" _, err := ParseStandard(schedule) if err == nil { t.Error("expected an error on 0 increment") } }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/cron/cron_test.go
plugin/cron/cron_test.go
//nolint:all package cron import ( "bytes" "fmt" "log" "strings" "sync" "sync/atomic" "testing" "time" ) // Many tests schedule a job for every second, and then wait at most a second // for it to run. This amount is just slightly larger than 1 second to // compensate for a few milliseconds of runtime. const OneSecond = 1*time.Second + 50*time.Millisecond type syncWriter struct { wr bytes.Buffer m sync.Mutex } func (sw *syncWriter) Write(data []byte) (n int, err error) { sw.m.Lock() n, err = sw.wr.Write(data) sw.m.Unlock() return } func (sw *syncWriter) String() string { sw.m.Lock() defer sw.m.Unlock() return sw.wr.String() } func newBufLogger(sw *syncWriter) Logger { return PrintfLogger(log.New(sw, "", log.LstdFlags)) } func TestFuncPanicRecovery(t *testing.T) { var buf syncWriter cron := New(WithParser(secondParser), WithChain(Recover(newBufLogger(&buf)))) cron.Start() defer cron.Stop() cron.AddFunc("* * * * * ?", func() { panic("YOLO") }) select { case <-time.After(OneSecond): if !strings.Contains(buf.String(), "YOLO") { t.Error("expected a panic to be logged, got none") } return } } type DummyJob struct{} func (DummyJob) Run() { panic("YOLO") } func TestJobPanicRecovery(t *testing.T) { var job DummyJob var buf syncWriter cron := New(WithParser(secondParser), WithChain(Recover(newBufLogger(&buf)))) cron.Start() defer cron.Stop() cron.AddJob("* * * * * ?", job) select { case <-time.After(OneSecond): if !strings.Contains(buf.String(), "YOLO") { t.Error("expected a panic to be logged, got none") } return } } // Start and stop cron with no entries. func TestNoEntries(t *testing.T) { cron := newWithSeconds() cron.Start() select { case <-time.After(OneSecond): t.Fatal("expected cron will be stopped immediately") case <-stop(cron): } } // Start, stop, then add an entry. Verify entry doesn't run. func TestStopCausesJobsToNotRun(t *testing.T) { wg := &sync.WaitGroup{} wg.Add(1) cron := newWithSeconds() cron.Start() cron.Stop() cron.AddFunc("* * * * * ?", func() { wg.Done() }) select { case <-time.After(OneSecond): // No job ran! case <-wait(wg): t.Fatal("expected stopped cron does not run any job") } } // Add a job, start cron, expect it runs. func TestAddBeforeRunning(t *testing.T) { wg := &sync.WaitGroup{} wg.Add(1) cron := newWithSeconds() cron.AddFunc("* * * * * ?", func() { wg.Done() }) cron.Start() defer cron.Stop() // Give cron 2 seconds to run our job (which is always activated). select { case <-time.After(OneSecond): t.Fatal("expected job runs") case <-wait(wg): } } // Start cron, add a job, expect it runs. func TestAddWhileRunning(t *testing.T) { wg := &sync.WaitGroup{} wg.Add(1) cron := newWithSeconds() cron.Start() defer cron.Stop() cron.AddFunc("* * * * * ?", func() { wg.Done() }) select { case <-time.After(OneSecond): t.Fatal("expected job runs") case <-wait(wg): } } // Test for #34. Adding a job after calling start results in multiple job invocations func TestAddWhileRunningWithDelay(t *testing.T) { cron := newWithSeconds() cron.Start() defer cron.Stop() time.Sleep(5 * time.Second) var calls int64 cron.AddFunc("* * * * * *", func() { atomic.AddInt64(&calls, 1) }) <-time.After(OneSecond) if atomic.LoadInt64(&calls) != 1 { t.Errorf("called %d times, expected 1\n", calls) } } // Add a job, remove a job, start cron, expect nothing runs. func TestRemoveBeforeRunning(t *testing.T) { wg := &sync.WaitGroup{} wg.Add(1) cron := newWithSeconds() id, _ := cron.AddFunc("* * * * * ?", func() { wg.Done() }) cron.Remove(id) cron.Start() defer cron.Stop() select { case <-time.After(OneSecond): // Success, shouldn't run case <-wait(wg): t.FailNow() } } // Start cron, add a job, remove it, expect it doesn't run. func TestRemoveWhileRunning(t *testing.T) { wg := &sync.WaitGroup{} wg.Add(1) cron := newWithSeconds() cron.Start() defer cron.Stop() id, _ := cron.AddFunc("* * * * * ?", func() { wg.Done() }) cron.Remove(id) select { case <-time.After(OneSecond): case <-wait(wg): t.FailNow() } } // Test timing with Entries. func TestSnapshotEntries(t *testing.T) { wg := &sync.WaitGroup{} wg.Add(1) cron := New() cron.AddFunc("@every 2s", func() { wg.Done() }) cron.Start() defer cron.Stop() // Cron should fire in 2 seconds. After 1 second, call Entries. select { case <-time.After(OneSecond): cron.Entries() } // Even though Entries was called, the cron should fire at the 2 second mark. select { case <-time.After(OneSecond): t.Error("expected job runs at 2 second mark") case <-wait(wg): } } // Test that the entries are correctly sorted. // Add a bunch of long-in-the-future entries, and an immediate entry, and ensure // that the immediate entry runs immediately. // Also: Test that multiple jobs run in the same instant. func TestMultipleEntries(t *testing.T) { wg := &sync.WaitGroup{} wg.Add(2) cron := newWithSeconds() cron.AddFunc("0 0 0 1 1 ?", func() {}) cron.AddFunc("* * * * * ?", func() { wg.Done() }) id1, _ := cron.AddFunc("* * * * * ?", func() { t.Fatal() }) id2, _ := cron.AddFunc("* * * * * ?", func() { t.Fatal() }) cron.AddFunc("0 0 0 31 12 ?", func() {}) cron.AddFunc("* * * * * ?", func() { wg.Done() }) cron.Remove(id1) cron.Start() cron.Remove(id2) defer cron.Stop() select { case <-time.After(OneSecond): t.Error("expected job run in proper order") case <-wait(wg): } } // Test running the same job twice. func TestRunningJobTwice(t *testing.T) { wg := &sync.WaitGroup{} wg.Add(2) cron := newWithSeconds() cron.AddFunc("0 0 0 1 1 ?", func() {}) cron.AddFunc("0 0 0 31 12 ?", func() {}) cron.AddFunc("* * * * * ?", func() { wg.Done() }) cron.Start() defer cron.Stop() select { case <-time.After(2 * OneSecond): t.Error("expected job fires 2 times") case <-wait(wg): } } func TestRunningMultipleSchedules(t *testing.T) { wg := &sync.WaitGroup{} wg.Add(2) cron := newWithSeconds() cron.AddFunc("0 0 0 1 1 ?", func() {}) cron.AddFunc("0 0 0 31 12 ?", func() {}) cron.AddFunc("* * * * * ?", func() { wg.Done() }) cron.Schedule(Every(time.Minute), FuncJob(func() {})) cron.Schedule(Every(time.Second), FuncJob(func() { wg.Done() })) cron.Schedule(Every(time.Hour), FuncJob(func() {})) cron.Start() defer cron.Stop() select { case <-time.After(2 * OneSecond): t.Error("expected job fires 2 times") case <-wait(wg): } } // Test that the cron is run in the local time zone (as opposed to UTC). func TestLocalTimezone(t *testing.T) { wg := &sync.WaitGroup{} wg.Add(2) now := time.Now() // FIX: Issue #205 // This calculation doesn't work in seconds 58 or 59. // Take the easy way out and sleep. if now.Second() >= 58 { time.Sleep(2 * time.Second) now = time.Now() } spec := fmt.Sprintf("%d,%d %d %d %d %d ?", now.Second()+1, now.Second()+2, now.Minute(), now.Hour(), now.Day(), now.Month()) cron := newWithSeconds() cron.AddFunc(spec, func() { wg.Done() }) cron.Start() defer cron.Stop() select { case <-time.After(OneSecond * 2): t.Error("expected job fires 2 times") case <-wait(wg): } } // Test that the cron is run in the given time zone (as opposed to local). func TestNonLocalTimezone(t *testing.T) { wg := &sync.WaitGroup{} wg.Add(2) loc, err := time.LoadLocation("Atlantic/Cape_Verde") if err != nil { fmt.Printf("Failed to load time zone Atlantic/Cape_Verde: %+v", err) t.Fail() } now := time.Now().In(loc) // FIX: Issue #205 // This calculation doesn't work in seconds 58 or 59. // Take the easy way out and sleep. if now.Second() >= 58 { time.Sleep(2 * time.Second) now = time.Now().In(loc) } spec := fmt.Sprintf("%d,%d %d %d %d %d ?", now.Second()+1, now.Second()+2, now.Minute(), now.Hour(), now.Day(), now.Month()) cron := New(WithLocation(loc), WithParser(secondParser)) cron.AddFunc(spec, func() { wg.Done() }) cron.Start() defer cron.Stop() select { case <-time.After(OneSecond * 2): t.Error("expected job fires 2 times") case <-wait(wg): } } // Test that calling stop before start silently returns without // blocking the stop channel. func TestStopWithoutStart(t *testing.T) { cron := New() cron.Stop() } type testJob struct { wg *sync.WaitGroup name string } func (t testJob) Run() { t.wg.Done() } // Test that adding an invalid job spec returns an error func TestInvalidJobSpec(t *testing.T) { cron := New() _, err := cron.AddJob("this will not parse", nil) if err == nil { t.Errorf("expected an error with invalid spec, got nil") } } // Test blocking run method behaves as Start() func TestBlockingRun(t *testing.T) { wg := &sync.WaitGroup{} wg.Add(1) cron := newWithSeconds() cron.AddFunc("* * * * * ?", func() { wg.Done() }) var unblockChan = make(chan struct{}) go func() { cron.Run() close(unblockChan) }() defer cron.Stop() select { case <-time.After(OneSecond): t.Error("expected job fires") case <-unblockChan: t.Error("expected that Run() blocks") case <-wait(wg): } } // Test that double-running is a no-op func TestStartNoop(t *testing.T) { var tickChan = make(chan struct{}, 2) cron := newWithSeconds() cron.AddFunc("* * * * * ?", func() { tickChan <- struct{}{} }) cron.Start() defer cron.Stop() // Wait for the first firing to ensure the runner is going <-tickChan cron.Start() <-tickChan // Fail if this job fires again in a short period, indicating a double-run select { case <-time.After(time.Millisecond): case <-tickChan: t.Error("expected job fires exactly twice") } } // Simple test using Runnables. func TestJob(t *testing.T) { wg := &sync.WaitGroup{} wg.Add(1) cron := newWithSeconds() cron.AddJob("0 0 0 30 Feb ?", testJob{wg, "job0"}) cron.AddJob("0 0 0 1 1 ?", testJob{wg, "job1"}) job2, _ := cron.AddJob("* * * * * ?", testJob{wg, "job2"}) cron.AddJob("1 0 0 1 1 ?", testJob{wg, "job3"}) cron.Schedule(Every(5*time.Second+5*time.Nanosecond), testJob{wg, "job4"}) job5 := cron.Schedule(Every(5*time.Minute), testJob{wg, "job5"}) // Test getting an Entry pre-Start. if actualName := cron.Entry(job2).Job.(testJob).name; actualName != "job2" { t.Error("wrong job retrieved:", actualName) } if actualName := cron.Entry(job5).Job.(testJob).name; actualName != "job5" { t.Error("wrong job retrieved:", actualName) } cron.Start() defer cron.Stop() select { case <-time.After(OneSecond): t.FailNow() case <-wait(wg): } // Ensure the entries are in the right order. expecteds := []string{"job2", "job4", "job5", "job1", "job3", "job0"} var actuals []string for _, entry := range cron.Entries() { actuals = append(actuals, entry.Job.(testJob).name) } for i, expected := range expecteds { if actuals[i] != expected { t.Fatalf("Jobs not in the right order. (expected) %s != %s (actual)", expecteds, actuals) } } // Test getting Entries. if actualName := cron.Entry(job2).Job.(testJob).name; actualName != "job2" { t.Error("wrong job retrieved:", actualName) } if actualName := cron.Entry(job5).Job.(testJob).name; actualName != "job5" { t.Error("wrong job retrieved:", actualName) } } // Issue #206 // Ensure that the next run of a job after removing an entry is accurate. func TestScheduleAfterRemoval(t *testing.T) { var wg1 sync.WaitGroup var wg2 sync.WaitGroup wg1.Add(1) wg2.Add(1) // The first time this job is run, set a timer and remove the other job // 750ms later. Correct behavior would be to still run the job again in // 250ms, but the bug would cause it to run instead 1s later. var calls int var mu sync.Mutex cron := newWithSeconds() hourJob := cron.Schedule(Every(time.Hour), FuncJob(func() {})) cron.Schedule(Every(time.Second), FuncJob(func() { mu.Lock() defer mu.Unlock() switch calls { case 0: wg1.Done() calls++ case 1: time.Sleep(750 * time.Millisecond) cron.Remove(hourJob) calls++ case 2: calls++ wg2.Done() case 3: panic("unexpected 3rd call") } })) cron.Start() defer cron.Stop() // the first run might be any length of time 0 - 1s, since the schedule // rounds to the second. wait for the first run to true up. wg1.Wait() select { case <-time.After(2 * OneSecond): t.Error("expected job fires 2 times") case <-wait(&wg2): } } type ZeroSchedule struct{} func (*ZeroSchedule) Next(time.Time) time.Time { return time.Time{} } // Tests that job without time does not run func TestJobWithZeroTimeDoesNotRun(t *testing.T) { cron := newWithSeconds() var calls int64 cron.AddFunc("* * * * * *", func() { atomic.AddInt64(&calls, 1) }) cron.Schedule(new(ZeroSchedule), FuncJob(func() { t.Error("expected zero task will not run") })) cron.Start() defer cron.Stop() <-time.After(OneSecond) if atomic.LoadInt64(&calls) != 1 { t.Errorf("called %d times, expected 1\n", calls) } } func TestStopAndWait(t *testing.T) { t.Run("nothing running, returns immediately", func(*testing.T) { cron := newWithSeconds() cron.Start() ctx := cron.Stop() select { case <-ctx.Done(): case <-time.After(time.Millisecond): t.Error("context was not done immediately") } }) t.Run("repeated calls to Stop", func(*testing.T) { cron := newWithSeconds() cron.Start() _ = cron.Stop() time.Sleep(time.Millisecond) ctx := cron.Stop() select { case <-ctx.Done(): case <-time.After(time.Millisecond): t.Error("context was not done immediately") } }) t.Run("a couple fast jobs added, still returns immediately", func(*testing.T) { cron := newWithSeconds() cron.AddFunc("* * * * * *", func() {}) cron.Start() cron.AddFunc("* * * * * *", func() {}) cron.AddFunc("* * * * * *", func() {}) cron.AddFunc("* * * * * *", func() {}) time.Sleep(time.Second) ctx := cron.Stop() select { case <-ctx.Done(): case <-time.After(time.Millisecond): t.Error("context was not done immediately") } }) t.Run("a couple fast jobs and a slow job added, waits for slow job", func(*testing.T) { cron := newWithSeconds() cron.AddFunc("* * * * * *", func() {}) cron.Start() cron.AddFunc("* * * * * *", func() { time.Sleep(2 * time.Second) }) cron.AddFunc("* * * * * *", func() {}) time.Sleep(time.Second) ctx := cron.Stop() // Verify that it is not done for at least 750ms select { case <-ctx.Done(): t.Error("context was done too quickly immediately") case <-time.After(750 * time.Millisecond): // expected, because the job sleeping for 1 second is still running } // Verify that it IS done in the next 500ms (giving 250ms buffer) select { case <-ctx.Done(): // expected case <-time.After(1500 * time.Millisecond): t.Error("context not done after job should have completed") } }) t.Run("repeated calls to stop, waiting for completion and after", func(*testing.T) { cron := newWithSeconds() cron.AddFunc("* * * * * *", func() {}) cron.AddFunc("* * * * * *", func() { time.Sleep(2 * time.Second) }) cron.Start() cron.AddFunc("* * * * * *", func() {}) time.Sleep(time.Second) ctx := cron.Stop() ctx2 := cron.Stop() // Verify that it is not done for at least 1500ms select { case <-ctx.Done(): t.Error("context was done too quickly immediately") case <-ctx2.Done(): t.Error("context2 was done too quickly immediately") case <-time.After(1500 * time.Millisecond): // expected, because the job sleeping for 2 seconds is still running } // Verify that it IS done in the next 1s (giving 500ms buffer) select { case <-ctx.Done(): // expected case <-time.After(time.Second): t.Error("context not done after job should have completed") } // Verify that ctx2 is also done. select { case <-ctx2.Done(): // expected case <-time.After(time.Millisecond): t.Error("context2 not done even though context1 is") } // Verify that a new context retrieved from stop is immediately done. ctx3 := cron.Stop() select { case <-ctx3.Done(): // expected case <-time.After(time.Millisecond): t.Error("context not done even when cron Stop is completed") } }) } func TestMultiThreadedStartAndStop(t *testing.T) { cron := New() go cron.Run() time.Sleep(2 * time.Millisecond) cron.Stop() } func wait(wg *sync.WaitGroup) chan bool { ch := make(chan bool) go func() { wg.Wait() ch <- true }() return ch } func stop(cron *Cron) chan bool { ch := make(chan bool) go func() { cron.Stop() ch <- true }() return ch } // newWithSeconds returns a Cron with the seconds field enabled. func newWithSeconds() *Cron { return New(WithParser(secondParser), WithChain()) }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/cron/logger.go
plugin/cron/logger.go
package cron import ( "io" "log" "os" "strings" "time" ) // DefaultLogger is used by Cron if none is specified. var DefaultLogger = PrintfLogger(log.New(os.Stdout, "cron: ", log.LstdFlags)) // DiscardLogger can be used by callers to discard all log messages. var DiscardLogger = PrintfLogger(log.New(io.Discard, "", 0)) // Logger is the interface used in this package for logging, so that any backend // can be plugged in. It is a subset of the github.com/go-logr/logr interface. type Logger interface { // Info logs routine messages about cron's operation. Info(msg string, keysAndValues ...interface{}) // Error logs an error condition. Error(err error, msg string, keysAndValues ...interface{}) } // PrintfLogger wraps a Printf-based logger (such as the standard library "log") // into an implementation of the Logger interface which logs errors only. func PrintfLogger(l interface{ Printf(string, ...interface{}) }) Logger { return printfLogger{l, false} } // VerbosePrintfLogger wraps a Printf-based logger (such as the standard library // "log") into an implementation of the Logger interface which logs everything. func VerbosePrintfLogger(l interface{ Printf(string, ...interface{}) }) Logger { return printfLogger{l, true} } type printfLogger struct { logger interface{ Printf(string, ...interface{}) } logInfo bool } func (pl printfLogger) Info(msg string, keysAndValues ...interface{}) { if pl.logInfo { keysAndValues = formatTimes(keysAndValues) pl.logger.Printf( formatString(len(keysAndValues)), append([]interface{}{msg}, keysAndValues...)...) } } func (pl printfLogger) Error(err error, msg string, keysAndValues ...interface{}) { keysAndValues = formatTimes(keysAndValues) pl.logger.Printf( formatString(len(keysAndValues)+2), append([]interface{}{msg, "error", err}, keysAndValues...)...) } // formatString returns a logfmt-like format string for the number of // key/values. func formatString(numKeysAndValues int) string { var sb strings.Builder sb.WriteString("%s") if numKeysAndValues > 0 { sb.WriteString(", ") } for i := 0; i < numKeysAndValues/2; i++ { if i > 0 { sb.WriteString(", ") } sb.WriteString("%v=%v") } return sb.String() } // formatTimes formats any time.Time values as RFC3339. func formatTimes(keysAndValues []interface{}) []interface{} { var formattedArgs []interface{} for _, arg := range keysAndValues { if t, ok := arg.(time.Time); ok { arg = t.Format(time.RFC3339) } formattedArgs = append(formattedArgs, arg) } return formattedArgs }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/cron/constantdelay_test.go
plugin/cron/constantdelay_test.go
//nolint:all package cron import ( "testing" "time" ) func TestConstantDelayNext(t *testing.T) { tests := []struct { time string delay time.Duration expected string }{ // Simple cases {"Mon Jul 9 14:45 2012", 15*time.Minute + 50*time.Nanosecond, "Mon Jul 9 15:00 2012"}, {"Mon Jul 9 14:59 2012", 15 * time.Minute, "Mon Jul 9 15:14 2012"}, {"Mon Jul 9 14:59:59 2012", 15 * time.Minute, "Mon Jul 9 15:14:59 2012"}, // Wrap around hours {"Mon Jul 9 15:45 2012", 35 * time.Minute, "Mon Jul 9 16:20 2012"}, // Wrap around days {"Mon Jul 9 23:46 2012", 14 * time.Minute, "Tue Jul 10 00:00 2012"}, {"Mon Jul 9 23:45 2012", 35 * time.Minute, "Tue Jul 10 00:20 2012"}, {"Mon Jul 9 23:35:51 2012", 44*time.Minute + 24*time.Second, "Tue Jul 10 00:20:15 2012"}, {"Mon Jul 9 23:35:51 2012", 25*time.Hour + 44*time.Minute + 24*time.Second, "Thu Jul 11 01:20:15 2012"}, // Wrap around months {"Mon Jul 9 23:35 2012", 91*24*time.Hour + 25*time.Minute, "Thu Oct 9 00:00 2012"}, // Wrap around minute, hour, day, month, and year {"Mon Dec 31 23:59:45 2012", 15 * time.Second, "Tue Jan 1 00:00:00 2013"}, // Round to nearest second on the delay {"Mon Jul 9 14:45 2012", 15*time.Minute + 50*time.Nanosecond, "Mon Jul 9 15:00 2012"}, // Round up to 1 second if the duration is less. {"Mon Jul 9 14:45:00 2012", 15 * time.Millisecond, "Mon Jul 9 14:45:01 2012"}, // Round to nearest second when calculating the next time. {"Mon Jul 9 14:45:00.005 2012", 15 * time.Minute, "Mon Jul 9 15:00 2012"}, // Round to nearest second for both. {"Mon Jul 9 14:45:00.005 2012", 15*time.Minute + 50*time.Nanosecond, "Mon Jul 9 15:00 2012"}, } for _, c := range tests { actual := Every(c.delay).Next(getTime(c.time)) expected := getTime(c.expected) if actual != expected { t.Errorf("%s, \"%s\": (expected) %v != %v (actual)", c.time, c.delay, expected, actual) } } }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/scheduler/parser.go
plugin/scheduler/parser.go
package scheduler import ( "strconv" "strings" "time" "github.com/pkg/errors" ) // Schedule represents a parsed cron expression. type Schedule struct { seconds fieldMatcher // 0-59 (optional, for 6-field format) minutes fieldMatcher // 0-59 hours fieldMatcher // 0-23 days fieldMatcher // 1-31 months fieldMatcher // 1-12 weekdays fieldMatcher // 0-7 (0 and 7 are Sunday) hasSecs bool } // fieldMatcher determines if a field value matches. type fieldMatcher interface { matches(value int) bool } // ParseCronExpression parses a cron expression and returns a Schedule. // Supports both 5-field (minute hour day month weekday) and 6-field (second minute hour day month weekday) formats. func ParseCronExpression(expr string) (*Schedule, error) { if expr == "" { return nil, errors.New("empty cron expression") } fields := strings.Fields(expr) if len(fields) != 5 && len(fields) != 6 { return nil, errors.Errorf("invalid cron expression: expected 5 or 6 fields, got %d", len(fields)) } s := &Schedule{ hasSecs: len(fields) == 6, } var err error offset := 0 // Parse seconds (if 6-field format) if s.hasSecs { s.seconds, err = parseField(fields[0], 0, 59) if err != nil { return nil, errors.Wrap(err, "invalid seconds field") } offset = 1 } else { s.seconds = &exactMatcher{value: 0} // Default to 0 seconds } // Parse minutes s.minutes, err = parseField(fields[offset], 0, 59) if err != nil { return nil, errors.Wrap(err, "invalid minutes field") } // Parse hours s.hours, err = parseField(fields[offset+1], 0, 23) if err != nil { return nil, errors.Wrap(err, "invalid hours field") } // Parse days s.days, err = parseField(fields[offset+2], 1, 31) if err != nil { return nil, errors.Wrap(err, "invalid days field") } // Parse months s.months, err = parseField(fields[offset+3], 1, 12) if err != nil { return nil, errors.Wrap(err, "invalid months field") } // Parse weekdays (0-7, where both 0 and 7 represent Sunday) s.weekdays, err = parseField(fields[offset+4], 0, 7) if err != nil { return nil, errors.Wrap(err, "invalid weekdays field") } return s, nil } // Next returns the next time the schedule should run after the given time. func (s *Schedule) Next(from time.Time) time.Time { // Start from the next second/minute if s.hasSecs { from = from.Add(1 * time.Second).Truncate(time.Second) } else { from = from.Add(1 * time.Minute).Truncate(time.Minute) } // Cap search at 4 years to prevent infinite loops maxTime := from.AddDate(4, 0, 0) for from.Before(maxTime) { if s.matches(from) { return from } // Advance to next potential match if s.hasSecs { from = from.Add(1 * time.Second) } else { from = from.Add(1 * time.Minute) } } // Should never reach here with valid cron expressions return time.Time{} } // matches checks if the given time matches the schedule. func (s *Schedule) matches(t time.Time) bool { return s.seconds.matches(t.Second()) && s.minutes.matches(t.Minute()) && s.hours.matches(t.Hour()) && s.months.matches(int(t.Month())) && (s.days.matches(t.Day()) || s.weekdays.matches(int(t.Weekday()))) } // parseField parses a single cron field (supports *, ranges, lists, steps). func parseField(field string, min, max int) (fieldMatcher, error) { // Wildcard if field == "*" { return &wildcardMatcher{}, nil } // Step values (*/N) if strings.HasPrefix(field, "*/") { step, err := strconv.Atoi(field[2:]) if err != nil || step < 1 || step > max { return nil, errors.Errorf("invalid step value: %s", field) } return &stepMatcher{step: step, min: min, max: max}, nil } // List (1,2,3) if strings.Contains(field, ",") { parts := strings.Split(field, ",") values := make([]int, 0, len(parts)) for _, p := range parts { val, err := strconv.Atoi(strings.TrimSpace(p)) if err != nil || val < min || val > max { return nil, errors.Errorf("invalid list value: %s", p) } values = append(values, val) } return &listMatcher{values: values}, nil } // Range (1-5) if strings.Contains(field, "-") { parts := strings.Split(field, "-") if len(parts) != 2 { return nil, errors.Errorf("invalid range: %s", field) } start, err1 := strconv.Atoi(strings.TrimSpace(parts[0])) end, err2 := strconv.Atoi(strings.TrimSpace(parts[1])) if err1 != nil || err2 != nil || start < min || end > max || start > end { return nil, errors.Errorf("invalid range: %s", field) } return &rangeMatcher{start: start, end: end}, nil } // Exact value val, err := strconv.Atoi(field) if err != nil || val < min || val > max { return nil, errors.Errorf("invalid value: %s (must be between %d and %d)", field, min, max) } return &exactMatcher{value: val}, nil } // wildcardMatcher matches any value. type wildcardMatcher struct{} func (*wildcardMatcher) matches(_ int) bool { return true } // exactMatcher matches a specific value. type exactMatcher struct { value int } func (m *exactMatcher) matches(value int) bool { return value == m.value } // rangeMatcher matches values in a range. type rangeMatcher struct { start, end int } func (m *rangeMatcher) matches(value int) bool { return value >= m.start && value <= m.end } // listMatcher matches any value in a list. type listMatcher struct { values []int } func (m *listMatcher) matches(value int) bool { for _, v := range m.values { if v == value { return true } } return false } // stepMatcher matches values at regular intervals. type stepMatcher struct { step, min, max int } func (m *stepMatcher) matches(value int) bool { if value < m.min || value > m.max { return false } return (value-m.min)%m.step == 0 }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/scheduler/job_test.go
plugin/scheduler/job_test.go
package scheduler import ( "context" "testing" ) func TestJobDefinition(t *testing.T) { callCount := 0 job := &Job{ Name: "test-job", Handler: func(_ context.Context) error { callCount++ return nil }, } if job.Name != "test-job" { t.Errorf("expected name 'test-job', got %s", job.Name) } // Test handler execution if err := job.Handler(context.Background()); err != nil { t.Fatalf("handler failed: %v", err) } if callCount != 1 { t.Errorf("expected handler to be called once, called %d times", callCount) } } func TestJobValidation(t *testing.T) { tests := []struct { name string job *Job wantErr bool }{ { name: "valid job", job: &Job{ Name: "valid", Schedule: "0 * * * *", Handler: func(_ context.Context) error { return nil }, }, wantErr: false, }, { name: "missing name", job: &Job{ Schedule: "0 * * * *", Handler: func(_ context.Context) error { return nil }, }, wantErr: true, }, { name: "missing schedule", job: &Job{ Name: "test", Handler: func(_ context.Context) error { return nil }, }, wantErr: true, }, { name: "invalid cron expression", job: &Job{ Name: "test", Schedule: "invalid cron", Handler: func(_ context.Context) error { return nil }, }, wantErr: true, }, { name: "missing handler", job: &Job{ Name: "test", Schedule: "0 * * * *", }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := tt.job.Validate() if (err != nil) != tt.wantErr { t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) } }) } }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/scheduler/middleware.go
plugin/scheduler/middleware.go
package scheduler import ( "context" "time" "github.com/pkg/errors" ) // Middleware wraps a JobHandler to add cross-cutting behavior. type Middleware func(JobHandler) JobHandler // Chain combines multiple middleware into a single middleware. // Middleware are applied in the order they're provided (left to right). func Chain(middlewares ...Middleware) Middleware { return func(handler JobHandler) JobHandler { // Apply middleware in reverse order so first middleware wraps outermost for i := len(middlewares) - 1; i >= 0; i-- { handler = middlewares[i](handler) } return handler } } // Recovery recovers from panics in job handlers and converts them to errors. func Recovery(onPanic func(jobName string, recovered interface{})) Middleware { return func(next JobHandler) JobHandler { return func(ctx context.Context) (err error) { defer func() { if r := recover(); r != nil { jobName := getJobName(ctx) if onPanic != nil { onPanic(jobName, r) } err = errors.Errorf("job %q panicked: %v", jobName, r) } }() return next(ctx) } } } // Logger is a minimal logging interface. type Logger interface { Info(msg string, args ...interface{}) Error(msg string, args ...interface{}) } // Logging adds execution logging to jobs. func Logging(logger Logger) Middleware { return func(next JobHandler) JobHandler { return func(ctx context.Context) error { jobName := getJobName(ctx) start := time.Now() logger.Info("Job started", "job", jobName) err := next(ctx) duration := time.Since(start) if err != nil { logger.Error("Job failed", "job", jobName, "duration", duration, "error", err) } else { logger.Info("Job completed", "job", jobName, "duration", duration) } return err } } } // Timeout wraps a job handler with a timeout. func Timeout(duration time.Duration) Middleware { return func(next JobHandler) JobHandler { return func(ctx context.Context) error { ctx, cancel := context.WithTimeout(ctx, duration) defer cancel() done := make(chan error, 1) go func() { done <- next(ctx) }() select { case err := <-done: return err case <-ctx.Done(): return errors.Errorf("job %q timed out after %v", getJobName(ctx), duration) } } } } // Context keys for job metadata. type contextKey int const ( jobNameKey contextKey = iota ) // withJobName adds the job name to the context. func withJobName(ctx context.Context, name string) context.Context { return context.WithValue(ctx, jobNameKey, name) } // getJobName retrieves the job name from the context. func getJobName(ctx context.Context) string { if name, ok := ctx.Value(jobNameKey).(string); ok { return name } return "unknown" } // GetJobName retrieves the job name from the context (public API). // Returns empty string if not found. // //nolint:revive // GetJobName is the public API, getJobName is internal func GetJobName(ctx context.Context) string { return getJobName(ctx) }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/scheduler/job.go
plugin/scheduler/job.go
package scheduler import ( "context" "github.com/pkg/errors" ) // JobHandler is the function signature for scheduled job handlers. // The context passed to the handler will be canceled if the scheduler is shutting down. type JobHandler func(ctx context.Context) error // Job represents a scheduled task. type Job struct { // Name is a unique identifier for this job (required). // Used for logging and metrics. Name string // Schedule is a cron expression defining when this job runs (required). // Supports standard 5-field format: "minute hour day month weekday" // Examples: "0 * * * *" (hourly), "0 0 * * *" (daily at midnight) Schedule string // Timezone for schedule evaluation (optional, defaults to UTC). // Use IANA timezone names: "America/New_York", "Europe/London", etc. Timezone string // Handler is the function to execute when the job triggers (required). Handler JobHandler // Description provides human-readable context about what this job does (optional). Description string // Tags allow categorizing jobs for filtering/monitoring (optional). Tags []string } // Validate checks if the job definition is valid. func (j *Job) Validate() error { if j.Name == "" { return errors.New("job name is required") } if j.Schedule == "" { return errors.New("job schedule is required") } // Validate cron expression using parser if _, err := ParseCronExpression(j.Schedule); err != nil { return errors.Wrap(err, "invalid cron expression") } if j.Handler == nil { return errors.New("job handler is required") } return nil }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/scheduler/middleware_test.go
plugin/scheduler/middleware_test.go
package scheduler import ( "context" "errors" "sync/atomic" "testing" ) func TestMiddlewareChaining(t *testing.T) { var order []string mw1 := func(next JobHandler) JobHandler { return func(ctx context.Context) error { order = append(order, "before-1") err := next(ctx) order = append(order, "after-1") return err } } mw2 := func(next JobHandler) JobHandler { return func(ctx context.Context) error { order = append(order, "before-2") err := next(ctx) order = append(order, "after-2") return err } } handler := func(_ context.Context) error { order = append(order, "handler") return nil } chain := Chain(mw1, mw2) wrapped := chain(handler) if err := wrapped(context.Background()); err != nil { t.Fatalf("wrapped handler failed: %v", err) } expected := []string{"before-1", "before-2", "handler", "after-2", "after-1"} if len(order) != len(expected) { t.Fatalf("expected %d calls, got %d", len(expected), len(order)) } for i, want := range expected { if order[i] != want { t.Errorf("order[%d] = %q, want %q", i, order[i], want) } } } func TestRecoveryMiddleware(t *testing.T) { var panicRecovered atomic.Bool onPanic := func(_ string, _ interface{}) { panicRecovered.Store(true) } handler := func(_ context.Context) error { panic("simulated panic") } recovery := Recovery(onPanic) wrapped := recovery(handler) // Should not panic, error should be returned err := wrapped(withJobName(context.Background(), "test-job")) if err == nil { t.Error("expected error from recovered panic") } if !panicRecovered.Load() { t.Error("panic handler was not called") } } func TestLoggingMiddleware(t *testing.T) { var loggedStart, loggedEnd atomic.Bool var loggedError atomic.Bool logger := &testLogger{ onInfo: func(msg string, _ ...interface{}) { if msg == "Job started" { loggedStart.Store(true) } else if msg == "Job completed" { loggedEnd.Store(true) } }, onError: func(msg string, _ ...interface{}) { if msg == "Job failed" { loggedError.Store(true) } }, } // Test successful execution handler := func(_ context.Context) error { return nil } logging := Logging(logger) wrapped := logging(handler) if err := wrapped(withJobName(context.Background(), "test-job")); err != nil { t.Fatalf("handler failed: %v", err) } if !loggedStart.Load() { t.Error("start was not logged") } if !loggedEnd.Load() { t.Error("end was not logged") } // Test error handling handlerErr := func(_ context.Context) error { return errors.New("job error") } wrappedErr := logging(handlerErr) _ = wrappedErr(withJobName(context.Background(), "test-job-error")) if !loggedError.Load() { t.Error("error was not logged") } } type testLogger struct { onInfo func(msg string, args ...interface{}) onError func(msg string, args ...interface{}) } func (l *testLogger) Info(msg string, args ...interface{}) { if l.onInfo != nil { l.onInfo(msg, args...) } } func (l *testLogger) Error(msg string, args ...interface{}) { if l.onError != nil { l.onError(msg, args...) } }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/scheduler/parser_test.go
plugin/scheduler/parser_test.go
package scheduler import ( "testing" "time" ) func TestParseCronExpression(t *testing.T) { tests := []struct { name string expr string wantErr bool }{ // Standard 5-field format {"every minute", "* * * * *", false}, {"hourly", "0 * * * *", false}, {"daily midnight", "0 0 * * *", false}, {"weekly sunday", "0 0 * * 0", false}, {"monthly", "0 0 1 * *", false}, {"specific time", "30 14 * * *", false}, // 2:30 PM daily {"range", "0 9-17 * * *", false}, // Every hour 9 AM - 5 PM {"step", "*/15 * * * *", false}, // Every 15 minutes {"list", "0 8,12,18 * * *", false}, // 8 AM, 12 PM, 6 PM // 6-field format with seconds {"with seconds", "0 * * * * *", false}, {"every 30 seconds", "*/30 * * * * *", false}, // Invalid expressions {"empty", "", true}, {"too few fields", "* * *", true}, {"too many fields", "* * * * * * *", true}, {"invalid minute", "60 * * * *", true}, {"invalid hour", "0 24 * * *", true}, {"invalid day", "0 0 32 * *", true}, {"invalid month", "0 0 1 13 *", true}, {"invalid weekday", "0 0 * * 8", true}, {"garbage", "not a cron expression", true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { schedule, err := ParseCronExpression(tt.expr) if (err != nil) != tt.wantErr { t.Errorf("ParseCronExpression(%q) error = %v, wantErr %v", tt.expr, err, tt.wantErr) return } if !tt.wantErr && schedule == nil { t.Errorf("ParseCronExpression(%q) returned nil schedule without error", tt.expr) } }) } } func TestScheduleNext(t *testing.T) { tests := []struct { name string expr string from time.Time expected time.Time }{ { name: "every minute from start of hour", expr: "* * * * *", from: time.Date(2025, 1, 1, 10, 0, 0, 0, time.UTC), expected: time.Date(2025, 1, 1, 10, 1, 0, 0, time.UTC), }, { name: "hourly at minute 30", expr: "30 * * * *", from: time.Date(2025, 1, 1, 10, 0, 0, 0, time.UTC), expected: time.Date(2025, 1, 1, 10, 30, 0, 0, time.UTC), }, { name: "hourly at minute 30 (already past)", expr: "30 * * * *", from: time.Date(2025, 1, 1, 10, 45, 0, 0, time.UTC), expected: time.Date(2025, 1, 1, 11, 30, 0, 0, time.UTC), }, { name: "daily at 2 AM", expr: "0 2 * * *", from: time.Date(2025, 1, 1, 10, 0, 0, 0, time.UTC), expected: time.Date(2025, 1, 2, 2, 0, 0, 0, time.UTC), }, { name: "every 15 minutes", expr: "*/15 * * * *", from: time.Date(2025, 1, 1, 10, 7, 0, 0, time.UTC), expected: time.Date(2025, 1, 1, 10, 15, 0, 0, time.UTC), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { schedule, err := ParseCronExpression(tt.expr) if err != nil { t.Fatalf("failed to parse expression: %v", err) } next := schedule.Next(tt.from) if !next.Equal(tt.expected) { t.Errorf("Next(%v) = %v, expected %v", tt.from, next, tt.expected) } }) } } func TestScheduleNextWithTimezone(t *testing.T) { nyc, _ := time.LoadLocation("America/New_York") // Schedule for 9 AM in New York schedule, err := ParseCronExpression("0 9 * * *") if err != nil { t.Fatalf("failed to parse expression: %v", err) } // Current time: 8 AM in New York from := time.Date(2025, 1, 1, 8, 0, 0, 0, nyc) next := schedule.Next(from) // Should be 9 AM same day in New York expected := time.Date(2025, 1, 1, 9, 0, 0, 0, nyc) if !next.Equal(expected) { t.Errorf("Next(%v) = %v, expected %v", from, next, expected) } }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/scheduler/scheduler_test.go
plugin/scheduler/scheduler_test.go
package scheduler import ( "context" "fmt" "strings" "sync" "sync/atomic" "testing" "time" ) func TestSchedulerCreation(t *testing.T) { s := New() if s == nil { t.Fatal("New() returned nil") } } func TestSchedulerWithTimezone(t *testing.T) { s := New(WithTimezone("America/New_York")) if s == nil { t.Fatal("New() with timezone returned nil") } } func TestJobRegistration(t *testing.T) { s := New() job := &Job{ Name: "test-registration", Schedule: "0 * * * *", Handler: func(_ context.Context) error { return nil }, } if err := s.Register(job); err != nil { t.Fatalf("failed to register valid job: %v", err) } // Registering duplicate name should fail if err := s.Register(job); err == nil { t.Error("expected error when registering duplicate job name") } } func TestSchedulerStartStop(t *testing.T) { s := New() var runCount atomic.Int32 job := &Job{ Name: "test-start-stop", Schedule: "* * * * * *", // Every second (6-field format) Handler: func(_ context.Context) error { runCount.Add(1) return nil }, } if err := s.Register(job); err != nil { t.Fatalf("failed to register job: %v", err) } // Start scheduler if err := s.Start(); err != nil { t.Fatalf("failed to start scheduler: %v", err) } // Let it run for 2.5 seconds time.Sleep(2500 * time.Millisecond) // Stop scheduler ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := s.Stop(ctx); err != nil { t.Fatalf("failed to stop scheduler: %v", err) } count := runCount.Load() // Should have run at least twice (at 0s and 1s, maybe 2s) if count < 2 { t.Errorf("expected job to run at least 2 times, ran %d times", count) } // Verify it stopped (count shouldn't increase) finalCount := count time.Sleep(1500 * time.Millisecond) if runCount.Load() != finalCount { t.Error("scheduler did not stop - job continued running") } } func TestSchedulerWithMiddleware(t *testing.T) { var executionLog []string var logMu sync.Mutex logger := &testLogger{ onInfo: func(msg string, _ ...interface{}) { logMu.Lock() executionLog = append(executionLog, fmt.Sprintf("INFO: %s", msg)) logMu.Unlock() }, onError: func(msg string, _ ...interface{}) { logMu.Lock() executionLog = append(executionLog, fmt.Sprintf("ERROR: %s", msg)) logMu.Unlock() }, } s := New(WithMiddleware( Recovery(func(jobName string, r interface{}) { logMu.Lock() executionLog = append(executionLog, fmt.Sprintf("PANIC: %s - %v", jobName, r)) logMu.Unlock() }), Logging(logger), )) job := &Job{ Name: "test-middleware", Schedule: "* * * * * *", // Every second Handler: func(_ context.Context) error { return nil }, } if err := s.Register(job); err != nil { t.Fatalf("failed to register job: %v", err) } if err := s.Start(); err != nil { t.Fatalf("failed to start: %v", err) } time.Sleep(1500 * time.Millisecond) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := s.Stop(ctx); err != nil { t.Fatalf("failed to stop: %v", err) } logMu.Lock() defer logMu.Unlock() // Should have at least one start and one completion log hasStart := false hasCompletion := false for _, log := range executionLog { if strings.Contains(log, "Job started") { hasStart = true } if strings.Contains(log, "Job completed") { hasCompletion = true } } if !hasStart { t.Error("expected job start log") } if !hasCompletion { t.Error("expected job completion log") } }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/scheduler/example_test.go
plugin/scheduler/example_test.go
package scheduler_test import ( "context" "fmt" "log/slog" "os" "time" "github.com/usememos/memos/plugin/scheduler" ) // Example demonstrates basic scheduler usage. func Example_basic() { s := scheduler.New() s.Register(&scheduler.Job{ Name: "hello", Schedule: "*/5 * * * *", // Every 5 minutes Description: "Say hello", Handler: func(_ context.Context) error { fmt.Println("Hello from scheduler!") return nil }, }) s.Start() defer s.Stop(context.Background()) // Scheduler runs in background time.Sleep(100 * time.Millisecond) } // Example demonstrates timezone-aware scheduling. func Example_timezone() { s := scheduler.New( scheduler.WithTimezone("America/New_York"), ) s.Register(&scheduler.Job{ Name: "daily-report", Schedule: "0 9 * * *", // 9 AM in New York Handler: func(_ context.Context) error { fmt.Println("Generating daily report...") return nil }, }) s.Start() defer s.Stop(context.Background()) } // Example demonstrates middleware usage. func Example_middleware() { logger := slog.New(slog.NewTextHandler(os.Stdout, nil)) s := scheduler.New( scheduler.WithMiddleware( scheduler.Recovery(func(jobName string, r interface{}) { logger.Error("Job panicked", "job", jobName, "panic", r) }), scheduler.Logging(&slogAdapter{logger}), scheduler.Timeout(5*time.Minute), ), ) s.Register(&scheduler.Job{ Name: "data-sync", Schedule: "0 */2 * * *", // Every 2 hours Handler: func(_ context.Context) error { // Your sync logic here return nil }, }) s.Start() defer s.Stop(context.Background()) } // slogAdapter adapts slog.Logger to scheduler.Logger interface. type slogAdapter struct { logger *slog.Logger } func (a *slogAdapter) Info(msg string, args ...interface{}) { a.logger.Info(msg, args...) } func (a *slogAdapter) Error(msg string, args ...interface{}) { a.logger.Error(msg, args...) } // Example demonstrates multiple jobs with different schedules. func Example_multipleJobs() { s := scheduler.New() // Cleanup old data every night at 2 AM s.Register(&scheduler.Job{ Name: "cleanup", Schedule: "0 2 * * *", Tags: []string{"maintenance"}, Handler: func(_ context.Context) error { fmt.Println("Cleaning up old data...") return nil }, }) // Health check every 5 minutes s.Register(&scheduler.Job{ Name: "health-check", Schedule: "*/5 * * * *", Tags: []string{"monitoring"}, Handler: func(_ context.Context) error { fmt.Println("Running health check...") return nil }, }) // Weekly backup on Sundays at 1 AM s.Register(&scheduler.Job{ Name: "weekly-backup", Schedule: "0 1 * * 0", Tags: []string{"backup"}, Handler: func(_ context.Context) error { fmt.Println("Creating weekly backup...") return nil }, }) s.Start() defer s.Stop(context.Background()) } // Example demonstrates graceful shutdown with timeout. func Example_gracefulShutdown() { s := scheduler.New() s.Register(&scheduler.Job{ Name: "long-running", Schedule: "* * * * *", Handler: func(ctx context.Context) error { select { case <-time.After(30 * time.Second): fmt.Println("Job completed") case <-ctx.Done(): fmt.Println("Job canceled, cleaning up...") return ctx.Err() } return nil }, }) s.Start() // Simulate shutdown signal time.Sleep(5 * time.Second) // Give jobs 10 seconds to finish shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := s.Stop(shutdownCtx); err != nil { fmt.Printf("Shutdown error: %v\n", err) } }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/scheduler/integration_test.go
plugin/scheduler/integration_test.go
package scheduler_test import ( "context" "errors" "fmt" "strings" "sync" "sync/atomic" "testing" "time" "github.com/usememos/memos/plugin/scheduler" ) // TestRealWorldScenario tests a realistic multi-job scenario. func TestRealWorldScenario(t *testing.T) { var ( quickJobCount atomic.Int32 hourlyJobCount atomic.Int32 logEntries []string logMu sync.Mutex ) logger := &testLogger{ onInfo: func(msg string, _ ...interface{}) { logMu.Lock() logEntries = append(logEntries, fmt.Sprintf("INFO: %s", msg)) logMu.Unlock() }, onError: func(msg string, _ ...interface{}) { logMu.Lock() logEntries = append(logEntries, fmt.Sprintf("ERROR: %s", msg)) logMu.Unlock() }, } s := scheduler.New( scheduler.WithTimezone("UTC"), scheduler.WithMiddleware( scheduler.Recovery(func(jobName string, r interface{}) { t.Logf("Job %s panicked: %v", jobName, r) }), scheduler.Logging(logger), scheduler.Timeout(5*time.Second), ), ) // Quick job (every second) s.Register(&scheduler.Job{ Name: "quick-check", Schedule: "* * * * * *", Handler: func(_ context.Context) error { quickJobCount.Add(1) time.Sleep(100 * time.Millisecond) return nil }, }) // Slower job (every 2 seconds) s.Register(&scheduler.Job{ Name: "slow-process", Schedule: "*/2 * * * * *", Handler: func(_ context.Context) error { hourlyJobCount.Add(1) time.Sleep(500 * time.Millisecond) return nil }, }) // Start scheduler if err := s.Start(); err != nil { t.Fatalf("failed to start scheduler: %v", err) } // Let it run for 5 seconds time.Sleep(5 * time.Second) // Graceful shutdown ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := s.Stop(ctx); err != nil { t.Fatalf("failed to stop scheduler: %v", err) } // Verify execution counts quick := quickJobCount.Load() slow := hourlyJobCount.Load() t.Logf("Quick job ran %d times", quick) t.Logf("Slow job ran %d times", slow) if quick < 4 { t.Errorf("expected quick job to run at least 4 times, ran %d", quick) } if slow < 2 { t.Errorf("expected slow job to run at least 2 times, ran %d", slow) } // Verify logging logMu.Lock() defer logMu.Unlock() hasStartLog := false hasCompleteLog := false for _, entry := range logEntries { if contains(entry, "Job started") { hasStartLog = true } if contains(entry, "Job completed") { hasCompleteLog = true } } if !hasStartLog { t.Error("expected job start logs") } if !hasCompleteLog { t.Error("expected job completion logs") } } // TestCancellationDuringExecution verifies jobs can be canceled mid-execution. func TestCancellationDuringExecution(t *testing.T) { var canceled atomic.Bool var started atomic.Bool s := scheduler.New() s.Register(&scheduler.Job{ Name: "long-job", Schedule: "* * * * * *", Handler: func(ctx context.Context) error { started.Store(true) // Simulate long-running work for i := 0; i < 100; i++ { select { case <-ctx.Done(): canceled.Store(true) return ctx.Err() case <-time.After(100 * time.Millisecond): // Keep working } } return nil }, }) if err := s.Start(); err != nil { t.Fatalf("failed to start: %v", err) } // Wait until job starts for i := 0; i < 30; i++ { if started.Load() { break } time.Sleep(100 * time.Millisecond) } if !started.Load() { t.Fatal("job did not start within timeout") } // Stop with reasonable timeout ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := s.Stop(ctx); err != nil { t.Logf("stop returned error (may be expected): %v", err) } if !canceled.Load() { t.Error("expected job to detect cancellation") } } // TestTimezoneHandling verifies timezone-aware scheduling. func TestTimezoneHandling(t *testing.T) { // Parse a schedule in a specific timezone schedule, err := scheduler.ParseCronExpression("0 9 * * *") // 9 AM if err != nil { t.Fatalf("failed to parse schedule: %v", err) } // Test in New York timezone nyc, err := time.LoadLocation("America/New_York") if err != nil { t.Fatalf("failed to load timezone: %v", err) } // Current time: 8:30 AM in New York now := time.Date(2025, 1, 15, 8, 30, 0, 0, nyc) // Next run should be 9:00 AM same day next := schedule.Next(now) expected := time.Date(2025, 1, 15, 9, 0, 0, 0, nyc) if !next.Equal(expected) { t.Errorf("next = %v, expected %v", next, expected) } // If it's already past 9 AM now = time.Date(2025, 1, 15, 9, 30, 0, 0, nyc) next = schedule.Next(now) expected = time.Date(2025, 1, 16, 9, 0, 0, 0, nyc) if !next.Equal(expected) { t.Errorf("next = %v, expected %v", next, expected) } } // TestErrorPropagation verifies error handling. func TestErrorPropagation(t *testing.T) { var errorLogged atomic.Bool logger := &testLogger{ onError: func(msg string, _ ...interface{}) { if msg == "Job failed" { errorLogged.Store(true) } }, } s := scheduler.New( scheduler.WithMiddleware( scheduler.Logging(logger), ), ) s.Register(&scheduler.Job{ Name: "failing-job", Schedule: "* * * * * *", Handler: func(_ context.Context) error { return errors.New("intentional error") }, }) if err := s.Start(); err != nil { t.Fatalf("failed to start: %v", err) } // Let it run once time.Sleep(1500 * time.Millisecond) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := s.Stop(ctx); err != nil { t.Fatalf("failed to stop: %v", err) } if !errorLogged.Load() { t.Error("expected error to be logged") } } // TestPanicRecovery verifies panic recovery middleware. func TestPanicRecovery(t *testing.T) { var panicRecovered atomic.Bool s := scheduler.New( scheduler.WithMiddleware( scheduler.Recovery(func(jobName string, r interface{}) { panicRecovered.Store(true) t.Logf("Recovered from panic in job %s: %v", jobName, r) }), ), ) s.Register(&scheduler.Job{ Name: "panicking-job", Schedule: "* * * * * *", Handler: func(_ context.Context) error { panic("intentional panic for testing") }, }) if err := s.Start(); err != nil { t.Fatalf("failed to start: %v", err) } // Let it run once time.Sleep(1500 * time.Millisecond) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := s.Stop(ctx); err != nil { t.Fatalf("failed to stop: %v", err) } if !panicRecovered.Load() { t.Error("expected panic to be recovered") } } // TestMultipleJobsWithDifferentSchedules verifies concurrent job execution. func TestMultipleJobsWithDifferentSchedules(t *testing.T) { var ( job1Count atomic.Int32 job2Count atomic.Int32 job3Count atomic.Int32 ) s := scheduler.New() // Job 1: Every second s.Register(&scheduler.Job{ Name: "job-1sec", Schedule: "* * * * * *", Handler: func(_ context.Context) error { job1Count.Add(1) return nil }, }) // Job 2: Every 2 seconds s.Register(&scheduler.Job{ Name: "job-2sec", Schedule: "*/2 * * * * *", Handler: func(_ context.Context) error { job2Count.Add(1) return nil }, }) // Job 3: Every 3 seconds s.Register(&scheduler.Job{ Name: "job-3sec", Schedule: "*/3 * * * * *", Handler: func(_ context.Context) error { job3Count.Add(1) return nil }, }) if err := s.Start(); err != nil { t.Fatalf("failed to start: %v", err) } // Let them run for 6 seconds time.Sleep(6 * time.Second) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := s.Stop(ctx); err != nil { t.Fatalf("failed to stop: %v", err) } // Verify counts (allowing for timing variance) c1 := job1Count.Load() c2 := job2Count.Load() c3 := job3Count.Load() t.Logf("Job 1 ran %d times, Job 2 ran %d times, Job 3 ran %d times", c1, c2, c3) if c1 < 5 { t.Errorf("expected job1 to run at least 5 times, ran %d", c1) } if c2 < 2 { t.Errorf("expected job2 to run at least 2 times, ran %d", c2) } if c3 < 1 { t.Errorf("expected job3 to run at least 1 time, ran %d", c3) } } // Helpers type testLogger struct { onInfo func(msg string, args ...interface{}) onError func(msg string, args ...interface{}) } func (l *testLogger) Info(msg string, args ...interface{}) { if l.onInfo != nil { l.onInfo(msg, args...) } } func (l *testLogger) Error(msg string, args ...interface{}) { if l.onError != nil { l.onError(msg, args...) } } func contains(s, substr string) bool { return strings.Contains(s, substr) }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/scheduler/scheduler.go
plugin/scheduler/scheduler.go
package scheduler import ( "context" "sync" "time" "github.com/pkg/errors" ) // Scheduler manages scheduled jobs. type Scheduler struct { jobs map[string]*registeredJob jobsMu sync.RWMutex timezone *time.Location middleware Middleware running bool runningMu sync.RWMutex stopCh chan struct{} wg sync.WaitGroup } // registeredJob wraps a Job with runtime state. type registeredJob struct { job *Job cancelFn context.CancelFunc } // Option configures a Scheduler. type Option func(*Scheduler) // WithTimezone sets the default timezone for all jobs. func WithTimezone(tz string) Option { return func(s *Scheduler) { loc, err := time.LoadLocation(tz) if err != nil { // Default to UTC on invalid timezone loc = time.UTC } s.timezone = loc } } // WithMiddleware sets middleware to wrap all job handlers. func WithMiddleware(mw ...Middleware) Option { return func(s *Scheduler) { if len(mw) > 0 { s.middleware = Chain(mw...) } } } // New creates a new Scheduler with optional configuration. func New(opts ...Option) *Scheduler { s := &Scheduler{ jobs: make(map[string]*registeredJob), timezone: time.UTC, stopCh: make(chan struct{}), } for _, opt := range opts { opt(s) } return s } // Register adds a job to the scheduler. // Jobs must be registered before calling Start(). func (s *Scheduler) Register(job *Job) error { if job == nil { return errors.New("job cannot be nil") } if err := job.Validate(); err != nil { return errors.Wrap(err, "invalid job") } s.jobsMu.Lock() defer s.jobsMu.Unlock() if _, exists := s.jobs[job.Name]; exists { return errors.Errorf("job with name %q already registered", job.Name) } s.jobs[job.Name] = &registeredJob{job: job} return nil } // Start begins executing scheduled jobs. func (s *Scheduler) Start() error { s.runningMu.Lock() defer s.runningMu.Unlock() if s.running { return errors.New("scheduler already running") } s.jobsMu.RLock() defer s.jobsMu.RUnlock() // Parse and schedule all jobs for _, rj := range s.jobs { schedule, err := ParseCronExpression(rj.job.Schedule) if err != nil { return errors.Wrapf(err, "failed to parse schedule for job %q", rj.job.Name) } ctx, cancel := context.WithCancel(context.Background()) rj.cancelFn = cancel s.wg.Add(1) go s.runJobWithSchedule(ctx, rj, schedule) } s.running = true return nil } // runJobWithSchedule executes a job according to its cron schedule. func (s *Scheduler) runJobWithSchedule(ctx context.Context, rj *registeredJob, schedule *Schedule) { defer s.wg.Done() // Apply middleware to handler handler := rj.job.Handler if s.middleware != nil { handler = s.middleware(handler) } for { // Calculate next run time now := time.Now() if rj.job.Timezone != "" { loc, err := time.LoadLocation(rj.job.Timezone) if err == nil { now = now.In(loc) } } else if s.timezone != nil { now = now.In(s.timezone) } next := schedule.Next(now) duration := time.Until(next) timer := time.NewTimer(duration) select { case <-timer.C: // Add job name to context and execute jobCtx := withJobName(ctx, rj.job.Name) if err := handler(jobCtx); err != nil { // Error already handled by middleware (if any) _ = err } case <-ctx.Done(): // Stop the timer to prevent it from firing. The timer will be garbage collected. timer.Stop() return case <-s.stopCh: // Stop the timer to prevent it from firing. The timer will be garbage collected. timer.Stop() return } } } // Stop gracefully shuts down the scheduler. // It waits for all running jobs to complete or until the context is canceled. func (s *Scheduler) Stop(ctx context.Context) error { s.runningMu.Lock() if !s.running { s.runningMu.Unlock() return errors.New("scheduler not running") } s.running = false s.runningMu.Unlock() // Cancel all job contexts s.jobsMu.RLock() for _, rj := range s.jobs { if rj.cancelFn != nil { rj.cancelFn() } } s.jobsMu.RUnlock() // Signal stop and wait for jobs to finish close(s.stopCh) done := make(chan struct{}) go func() { s.wg.Wait() close(done) }() select { case <-done: return nil case <-ctx.Done(): return ctx.Err() } }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/scheduler/doc.go
plugin/scheduler/doc.go
// Package scheduler provides a GitHub Actions-inspired cron job scheduler. // // Features: // - Standard cron expression syntax (5-field and 6-field formats) // - Timezone-aware scheduling // - Middleware pattern for cross-cutting concerns (logging, metrics, recovery) // - Graceful shutdown with context cancellation // - Zero external dependencies // // Basic usage: // // s := scheduler.New() // // s.Register(&scheduler.Job{ // Name: "daily-cleanup", // Schedule: "0 2 * * *", // 2 AM daily // Handler: func(ctx context.Context) error { // // Your cleanup logic here // return nil // }, // }) // // s.Start() // defer s.Stop(context.Background()) // // With middleware: // // s := scheduler.New( // scheduler.WithTimezone("America/New_York"), // scheduler.WithMiddleware( // scheduler.Recovery(), // scheduler.Logging(), // ), // ) package scheduler
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/webhook/webhook.go
plugin/webhook/webhook.go
package webhook import ( "bytes" "encoding/json" "io" "log/slog" "net/http" "time" "github.com/pkg/errors" v1pb "github.com/usememos/memos/proto/gen/api/v1" ) var ( // timeout is the timeout for webhook request. Default to 30 seconds. timeout = 30 * time.Second ) type WebhookRequestPayload struct { // The target URL for the webhook request. URL string `json:"url"` // The type of activity that triggered this webhook. ActivityType string `json:"activityType"` // The resource name of the creator. Format: users/{user} Creator string `json:"creator"` // The memo that triggered this webhook (if applicable). Memo *v1pb.Memo `json:"memo"` } // Post posts the message to webhook endpoint. func Post(requestPayload *WebhookRequestPayload) error { body, err := json.Marshal(requestPayload) if err != nil { return errors.Wrapf(err, "failed to marshal webhook request to %s", requestPayload.URL) } req, err := http.NewRequest("POST", requestPayload.URL, bytes.NewBuffer(body)) if err != nil { return errors.Wrapf(err, "failed to construct webhook request to %s", requestPayload.URL) } req.Header.Set("Content-Type", "application/json") client := &http.Client{ Timeout: timeout, } resp, err := client.Do(req) if err != nil { return errors.Wrapf(err, "failed to post webhook to %s", requestPayload.URL) } defer resp.Body.Close() b, err := io.ReadAll(resp.Body) if err != nil { return errors.Wrapf(err, "failed to read webhook response from %s", requestPayload.URL) } if resp.StatusCode < 200 || resp.StatusCode > 299 { return errors.Errorf("failed to post webhook %s, status code: %d, response body: %s", requestPayload.URL, resp.StatusCode, b) } response := &struct { Code int `json:"code"` Message string `json:"message"` }{} if err := json.Unmarshal(b, response); err != nil { return errors.Wrapf(err, "failed to unmarshal webhook response from %s", requestPayload.URL) } if response.Code != 0 { return errors.Errorf("receive error code sent by webhook server, code %d, msg: %s", response.Code, response.Message) } return nil } // PostAsync posts the message to webhook endpoint asynchronously. // It spawns a new goroutine to handle the request and does not wait for the response. func PostAsync(requestPayload *WebhookRequestPayload) { go func() { if err := Post(requestPayload); err != nil { // Since we're in a goroutine, we can only log the error slog.Warn("Failed to dispatch webhook asynchronously", slog.String("url", requestPayload.URL), slog.String("activityType", requestPayload.ActivityType), slog.Any("err", err)) } }() }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/webhook/webhook_test.go
plugin/webhook/webhook_test.go
package webhook
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/email/client.go
plugin/email/client.go
package email import ( "crypto/tls" "net/smtp" "github.com/pkg/errors" ) // Client represents an SMTP email client. type Client struct { config *Config } // NewClient creates a new email client with the given configuration. func NewClient(config *Config) *Client { return &Client{ config: config, } } // validateConfig validates the client configuration. func (c *Client) validateConfig() error { if c.config == nil { return errors.New("email configuration is required") } return c.config.Validate() } // createAuth creates an SMTP auth mechanism if credentials are provided. func (c *Client) createAuth() smtp.Auth { if c.config.SMTPUsername == "" && c.config.SMTPPassword == "" { return nil } return smtp.PlainAuth("", c.config.SMTPUsername, c.config.SMTPPassword, c.config.SMTPHost) } // createTLSConfig creates a TLS configuration for secure connections. func (c *Client) createTLSConfig() *tls.Config { return &tls.Config{ ServerName: c.config.SMTPHost, MinVersion: tls.VersionTLS12, } } // Send sends an email message via SMTP. func (c *Client) Send(message *Message) error { // Validate configuration if err := c.validateConfig(); err != nil { return errors.Wrap(err, "invalid email configuration") } // Validate message if message == nil { return errors.New("message is required") } if err := message.Validate(); err != nil { return errors.Wrap(err, "invalid email message") } // Format the message body := message.Format(c.config.FromEmail, c.config.FromName) // Get all recipients recipients := message.GetAllRecipients() // Create auth auth := c.createAuth() // Send based on encryption type if c.config.UseSSL { return c.sendWithSSL(auth, recipients, body) } return c.sendWithTLS(auth, recipients, body) } // sendWithTLS sends email using STARTTLS (port 587). func (c *Client) sendWithTLS(auth smtp.Auth, recipients []string, body string) error { serverAddr := c.config.GetServerAddress() if c.config.UseTLS { // Use STARTTLS return smtp.SendMail(serverAddr, auth, c.config.FromEmail, recipients, []byte(body)) } // Send without encryption (not recommended) return smtp.SendMail(serverAddr, auth, c.config.FromEmail, recipients, []byte(body)) } // sendWithSSL sends email using SSL/TLS (port 465). func (c *Client) sendWithSSL(auth smtp.Auth, recipients []string, body string) error { serverAddr := c.config.GetServerAddress() // Create TLS connection tlsConfig := c.createTLSConfig() conn, err := tls.Dial("tcp", serverAddr, tlsConfig) if err != nil { return errors.Wrapf(err, "failed to connect to SMTP server with SSL: %s", serverAddr) } defer conn.Close() // Create SMTP client client, err := smtp.NewClient(conn, c.config.SMTPHost) if err != nil { return errors.Wrap(err, "failed to create SMTP client") } defer client.Quit() // Authenticate if auth != nil { if err := client.Auth(auth); err != nil { return errors.Wrap(err, "SMTP authentication failed") } } // Set sender if err := client.Mail(c.config.FromEmail); err != nil { return errors.Wrap(err, "failed to set sender") } // Set recipients for _, recipient := range recipients { if err := client.Rcpt(recipient); err != nil { return errors.Wrapf(err, "failed to set recipient: %s", recipient) } } // Send message body writer, err := client.Data() if err != nil { return errors.Wrap(err, "failed to send DATA command") } if _, err := writer.Write([]byte(body)); err != nil { return errors.Wrap(err, "failed to write message body") } if err := writer.Close(); err != nil { return errors.Wrap(err, "failed to close message writer") } return nil }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/email/config.go
plugin/email/config.go
package email import ( "fmt" "github.com/pkg/errors" ) // Config represents the SMTP configuration for email sending. // These settings should be provided by the self-hosted instance administrator. type Config struct { // SMTPHost is the SMTP server hostname (e.g., "smtp.gmail.com") SMTPHost string // SMTPPort is the SMTP server port (common: 587 for TLS, 465 for SSL, 25 for unencrypted) SMTPPort int // SMTPUsername is the SMTP authentication username (usually the email address) SMTPUsername string // SMTPPassword is the SMTP authentication password or app-specific password SMTPPassword string // FromEmail is the email address that will appear in the "From" field FromEmail string // FromName is the display name that will appear in the "From" field FromName string // UseTLS enables STARTTLS encryption (recommended for port 587) UseTLS bool // UseSSL enables SSL/TLS encryption (for port 465) UseSSL bool } // Validate checks if the configuration is valid. func (c *Config) Validate() error { if c.SMTPHost == "" { return errors.New("SMTP host is required") } if c.SMTPPort <= 0 || c.SMTPPort > 65535 { return errors.New("SMTP port must be between 1 and 65535") } if c.FromEmail == "" { return errors.New("from email is required") } return nil } // GetServerAddress returns the SMTP server address in the format "host:port". func (c *Config) GetServerAddress() string { return fmt.Sprintf("%s:%d", c.SMTPHost, c.SMTPPort) }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/email/client_test.go
plugin/email/client_test.go
package email import ( "testing" "github.com/stretchr/testify/assert" ) func TestNewClient(t *testing.T) { config := &Config{ SMTPHost: "smtp.example.com", SMTPPort: 587, SMTPUsername: "user@example.com", SMTPPassword: "password", FromEmail: "noreply@example.com", FromName: "Test App", UseTLS: true, } client := NewClient(config) assert.NotNil(t, client) assert.Equal(t, config, client.config) } func TestClientValidateConfig(t *testing.T) { tests := []struct { name string config *Config wantErr bool }{ { name: "valid config", config: &Config{ SMTPHost: "smtp.example.com", SMTPPort: 587, FromEmail: "test@example.com", }, wantErr: false, }, { name: "nil config", config: nil, wantErr: true, }, { name: "invalid config", config: &Config{ SMTPHost: "", SMTPPort: 587, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { client := NewClient(tt.config) err := client.validateConfig() if tt.wantErr { assert.Error(t, err) } else { assert.NoError(t, err) } }) } } func TestClientSendValidation(t *testing.T) { config := &Config{ SMTPHost: "smtp.example.com", SMTPPort: 587, FromEmail: "test@example.com", } client := NewClient(config) tests := []struct { name string message *Message wantErr bool }{ { name: "valid message", message: &Message{ To: []string{"recipient@example.com"}, Subject: "Test", Body: "Test body", }, wantErr: false, // Will fail on actual send, but passes validation }, { name: "nil message", message: nil, wantErr: true, }, { name: "invalid message", message: &Message{ To: []string{}, Subject: "Test", Body: "Test", }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := client.Send(tt.message) // We expect validation errors for invalid messages // For valid messages, we'll get connection errors (which is expected in tests) if tt.wantErr { assert.Error(t, err) // Should fail validation before attempting connection assert.NotContains(t, err.Error(), "dial") } // Note: We don't assert NoError for valid messages because // we don't have a real SMTP server in tests }) } }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/email/email.go
plugin/email/email.go
package email import ( "log/slog" "github.com/pkg/errors" ) // Send sends an email synchronously. // Returns an error if the email fails to send. func Send(config *Config, message *Message) error { if config == nil { return errors.New("email configuration is required") } if message == nil { return errors.New("email message is required") } client := NewClient(config) return client.Send(message) } // SendAsync sends an email asynchronously. // It spawns a new goroutine to handle the sending and does not wait for the response. // Any errors are logged but not returned. func SendAsync(config *Config, message *Message) { go func() { if err := Send(config, message); err != nil { // Since we're in a goroutine, we can only log the error recipients := "" if message != nil && len(message.To) > 0 { recipients = message.To[0] if len(message.To) > 1 { recipients += " and others" } } slog.Warn("Failed to send email asynchronously", slog.String("recipients", recipients), slog.Any("error", err)) } }() }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/email/config_test.go
plugin/email/config_test.go
package email import ( "testing" "github.com/stretchr/testify/assert" ) func TestConfigValidation(t *testing.T) { tests := []struct { name string config *Config wantErr bool }{ { name: "valid config", config: &Config{ SMTPHost: "smtp.gmail.com", SMTPPort: 587, SMTPUsername: "user@example.com", SMTPPassword: "password", FromEmail: "noreply@example.com", FromName: "Memos", }, wantErr: false, }, { name: "missing host", config: &Config{ SMTPPort: 587, SMTPUsername: "user@example.com", SMTPPassword: "password", FromEmail: "noreply@example.com", }, wantErr: true, }, { name: "invalid port", config: &Config{ SMTPHost: "smtp.gmail.com", SMTPPort: 0, SMTPUsername: "user@example.com", SMTPPassword: "password", FromEmail: "noreply@example.com", }, wantErr: true, }, { name: "missing from email", config: &Config{ SMTPHost: "smtp.gmail.com", SMTPPort: 587, SMTPUsername: "user@example.com", SMTPPassword: "password", }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := tt.config.Validate() if tt.wantErr { assert.Error(t, err) } else { assert.NoError(t, err) } }) } } func TestConfigGetServerAddress(t *testing.T) { config := &Config{ SMTPHost: "smtp.gmail.com", SMTPPort: 587, } expected := "smtp.gmail.com:587" assert.Equal(t, expected, config.GetServerAddress()) }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/email/doc.go
plugin/email/doc.go
// Package email provides SMTP email sending functionality for self-hosted Memos instances. // // This package is designed for self-hosted environments where instance administrators // configure their own SMTP servers. It follows industry-standard patterns used by // platforms like GitHub, GitLab, and Discourse. // // # Configuration // // The package requires SMTP server configuration provided by the instance administrator: // // config := &email.Config{ // SMTPHost: "smtp.gmail.com", // SMTPPort: 587, // SMTPUsername: "your-email@gmail.com", // SMTPPassword: "your-app-password", // FromEmail: "noreply@yourdomain.com", // FromName: "Memos Notifications", // UseTLS: true, // } // // # Common SMTP Settings // // Gmail (requires App Password): // - Host: smtp.gmail.com // - Port: 587 (TLS) or 465 (SSL) // - Username: your-email@gmail.com // - UseTLS: true (for port 587) or UseSSL: true (for port 465) // // SendGrid: // - Host: smtp.sendgrid.net // - Port: 587 // - Username: apikey // - Password: your-sendgrid-api-key // - UseTLS: true // // AWS SES: // - Host: email-smtp.[region].amazonaws.com // - Port: 587 // - Username: your-smtp-username // - Password: your-smtp-password // - UseTLS: true // // Mailgun: // - Host: smtp.mailgun.org // - Port: 587 // - Username: your-mailgun-smtp-username // - Password: your-mailgun-smtp-password // - UseTLS: true // // # Sending Email // // Synchronous (waits for completion): // // message := &email.Message{ // To: []string{"user@example.com"}, // Subject: "Welcome to Memos", // Body: "Thank you for joining!", // IsHTML: false, // } // // err := email.Send(config, message) // if err != nil { // // Handle error // } // // Asynchronous (returns immediately): // // email.SendAsync(config, message) // // Errors are logged but not returned // // # HTML Email // // message := &email.Message{ // To: []string{"user@example.com"}, // Subject: "Welcome!", // Body: "<html><body><h1>Welcome to Memos!</h1></body></html>", // IsHTML: true, // } // // # Security Considerations // // - Always use TLS (port 587) or SSL (port 465) for production // - Store SMTP credentials securely (environment variables or secrets management) // - Use app-specific passwords for services like Gmail // - Validate and sanitize email content to prevent injection attacks // - Rate limit email sending to prevent abuse // // # Error Handling // // The package returns descriptive errors for common issues: // - Configuration validation errors (missing host, invalid port, etc.) // - Message validation errors (missing recipients, subject, or body) // - Connection errors (cannot reach SMTP server) // - Authentication errors (invalid credentials) // - SMTP protocol errors (recipient rejected, etc.) // // All errors are wrapped with context using github.com/pkg/errors for better debugging. package email
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/email/message.go
plugin/email/message.go
package email import ( "errors" "fmt" "strings" "time" ) // Message represents an email message to be sent. type Message struct { To []string // Required: recipient email addresses Cc []string // Optional: carbon copy recipients Bcc []string // Optional: blind carbon copy recipients Subject string // Required: email subject Body string // Required: email body content IsHTML bool // Whether the body is HTML (default: false for plain text) ReplyTo string // Optional: reply-to address } // Validate checks that the message has all required fields. func (m *Message) Validate() error { if len(m.To) == 0 { return errors.New("at least one recipient is required") } if m.Subject == "" { return errors.New("subject is required") } if m.Body == "" { return errors.New("body is required") } return nil } // Format creates an RFC 5322 formatted email message. func (m *Message) Format(fromEmail, fromName string) string { var sb strings.Builder // From header if fromName != "" { sb.WriteString(fmt.Sprintf("From: %s <%s>\r\n", fromName, fromEmail)) } else { sb.WriteString(fmt.Sprintf("From: %s\r\n", fromEmail)) } // To header sb.WriteString(fmt.Sprintf("To: %s\r\n", strings.Join(m.To, ", "))) // Cc header (optional) if len(m.Cc) > 0 { sb.WriteString(fmt.Sprintf("Cc: %s\r\n", strings.Join(m.Cc, ", "))) } // Reply-To header (optional) if m.ReplyTo != "" { sb.WriteString(fmt.Sprintf("Reply-To: %s\r\n", m.ReplyTo)) } // Subject header sb.WriteString(fmt.Sprintf("Subject: %s\r\n", m.Subject)) // Date header (RFC 5322 format) sb.WriteString(fmt.Sprintf("Date: %s\r\n", time.Now().Format(time.RFC1123Z))) // MIME headers sb.WriteString("MIME-Version: 1.0\r\n") // Content-Type header if m.IsHTML { sb.WriteString("Content-Type: text/html; charset=utf-8\r\n") } else { sb.WriteString("Content-Type: text/plain; charset=utf-8\r\n") } // Empty line separating headers from body sb.WriteString("\r\n") // Body sb.WriteString(m.Body) return sb.String() } // GetAllRecipients returns all recipients (To, Cc, Bcc) as a single slice. func (m *Message) GetAllRecipients() []string { var recipients []string recipients = append(recipients, m.To...) recipients = append(recipients, m.Cc...) recipients = append(recipients, m.Bcc...) return recipients }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/email/message_test.go
plugin/email/message_test.go
package email import ( "strings" "testing" ) func TestMessageValidation(t *testing.T) { tests := []struct { name string msg Message wantErr bool }{ { name: "valid message", msg: Message{ To: []string{"user@example.com"}, Subject: "Test Subject", Body: "Test Body", }, wantErr: false, }, { name: "no recipients", msg: Message{ To: []string{}, Subject: "Test Subject", Body: "Test Body", }, wantErr: true, }, { name: "no subject", msg: Message{ To: []string{"user@example.com"}, Subject: "", Body: "Test Body", }, wantErr: true, }, { name: "no body", msg: Message{ To: []string{"user@example.com"}, Subject: "Test Subject", Body: "", }, wantErr: true, }, { name: "multiple recipients", msg: Message{ To: []string{"user1@example.com", "user2@example.com"}, Cc: []string{"cc@example.com"}, Subject: "Test Subject", Body: "Test Body", }, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := tt.msg.Validate() if (err != nil) != tt.wantErr { t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) } }) } } func TestMessageFormatPlainText(t *testing.T) { msg := Message{ To: []string{"user@example.com"}, Subject: "Test Subject", Body: "Test Body", IsHTML: false, } formatted := msg.Format("sender@example.com", "Sender Name") // Check required headers if !strings.Contains(formatted, "From: Sender Name <sender@example.com>") { t.Error("Missing or incorrect From header") } if !strings.Contains(formatted, "To: user@example.com") { t.Error("Missing or incorrect To header") } if !strings.Contains(formatted, "Subject: Test Subject") { t.Error("Missing or incorrect Subject header") } if !strings.Contains(formatted, "Content-Type: text/plain; charset=utf-8") { t.Error("Missing or incorrect Content-Type header for plain text") } if !strings.Contains(formatted, "Test Body") { t.Error("Missing message body") } } func TestMessageFormatHTML(t *testing.T) { msg := Message{ To: []string{"user@example.com"}, Subject: "Test Subject", Body: "<html><body>Test Body</body></html>", IsHTML: true, } formatted := msg.Format("sender@example.com", "Sender Name") // Check HTML content-type if !strings.Contains(formatted, "Content-Type: text/html; charset=utf-8") { t.Error("Missing or incorrect Content-Type header for HTML") } if !strings.Contains(formatted, "<html><body>Test Body</body></html>") { t.Error("Missing HTML body") } } func TestMessageFormatMultipleRecipients(t *testing.T) { msg := Message{ To: []string{"user1@example.com", "user2@example.com"}, Cc: []string{"cc1@example.com", "cc2@example.com"}, Bcc: []string{"bcc@example.com"}, Subject: "Test Subject", Body: "Test Body", ReplyTo: "reply@example.com", } formatted := msg.Format("sender@example.com", "Sender Name") // Check To header formatting if !strings.Contains(formatted, "To: user1@example.com, user2@example.com") { t.Error("Missing or incorrect To header with multiple recipients") } // Check Cc header formatting if !strings.Contains(formatted, "Cc: cc1@example.com, cc2@example.com") { t.Error("Missing or incorrect Cc header") } // Bcc should NOT appear in the formatted message if strings.Contains(formatted, "Bcc:") { t.Error("Bcc header should not appear in formatted message") } // Check Reply-To header if !strings.Contains(formatted, "Reply-To: reply@example.com") { t.Error("Missing or incorrect Reply-To header") } } func TestGetAllRecipients(t *testing.T) { msg := Message{ To: []string{"user1@example.com", "user2@example.com"}, Cc: []string{"cc@example.com"}, Bcc: []string{"bcc@example.com"}, } recipients := msg.GetAllRecipients() // Should have all 4 recipients if len(recipients) != 4 { t.Errorf("GetAllRecipients() returned %d recipients, want 4", len(recipients)) } // Check all recipients are present expectedRecipients := map[string]bool{ "user1@example.com": true, "user2@example.com": true, "cc@example.com": true, "bcc@example.com": true, } for _, recipient := range recipients { if !expectedRecipients[recipient] { t.Errorf("Unexpected recipient: %s", recipient) } delete(expectedRecipients, recipient) } if len(expectedRecipients) > 0 { t.Error("Not all expected recipients were returned") } }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/email/email_test.go
plugin/email/email_test.go
package email import ( "testing" "time" "github.com/stretchr/testify/assert" "golang.org/x/sync/errgroup" ) func TestSend(t *testing.T) { config := &Config{ SMTPHost: "smtp.example.com", SMTPPort: 587, FromEmail: "test@example.com", } message := &Message{ To: []string{"recipient@example.com"}, Subject: "Test", Body: "Test body", } // This will fail to connect (no real server), but should validate inputs err := Send(config, message) // We expect an error because there's no real SMTP server // But it should be a connection error, not a validation error assert.Error(t, err) assert.Contains(t, err.Error(), "dial") } func TestSendValidation(t *testing.T) { tests := []struct { name string config *Config message *Message wantErr bool errMsg string }{ { name: "nil config", config: nil, message: &Message{To: []string{"test@example.com"}, Subject: "Test", Body: "Test"}, wantErr: true, errMsg: "configuration is required", }, { name: "nil message", config: &Config{SMTPHost: "smtp.example.com", SMTPPort: 587, FromEmail: "from@example.com"}, message: nil, wantErr: true, errMsg: "message is required", }, { name: "invalid config", config: &Config{ SMTPHost: "", SMTPPort: 587, }, message: &Message{To: []string{"test@example.com"}, Subject: "Test", Body: "Test"}, wantErr: true, errMsg: "invalid email configuration", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := Send(tt.config, tt.message) if tt.wantErr { assert.Error(t, err) assert.Contains(t, err.Error(), tt.errMsg) } }) } } func TestSendAsync(t *testing.T) { config := &Config{ SMTPHost: "smtp.example.com", SMTPPort: 587, FromEmail: "test@example.com", } message := &Message{ To: []string{"recipient@example.com"}, Subject: "Test Async", Body: "Test async body", } // SendAsync should not block start := time.Now() SendAsync(config, message) duration := time.Since(start) // Should return almost immediately (< 100ms) assert.Less(t, duration, 100*time.Millisecond) // Give goroutine time to start time.Sleep(50 * time.Millisecond) } func TestSendAsyncConcurrent(t *testing.T) { config := &Config{ SMTPHost: "smtp.example.com", SMTPPort: 587, FromEmail: "test@example.com", } g := errgroup.Group{} count := 5 for i := 0; i < count; i++ { g.Go(func() error { message := &Message{ To: []string{"recipient@example.com"}, Subject: "Concurrent Test", Body: "Test body", } SendAsync(config, message) return nil }) } if err := g.Wait(); err != nil { t.Fatalf("SendAsync calls failed: %v", err) } }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/markdown/markdown_test.go
plugin/markdown/markdown_test.go
package markdown import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestNewService(t *testing.T) { svc := NewService() assert.NotNil(t, svc) } func TestValidateContent(t *testing.T) { svc := NewService() tests := []struct { name string content string wantErr bool }{ { name: "valid markdown", content: "# Hello\n\nThis is **bold** text.", wantErr: false, }, { name: "empty content", content: "", wantErr: false, }, { name: "complex markdown", content: "# Title\n\n- List item 1\n- List item 2\n\n```go\ncode block\n```", wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := svc.ValidateContent([]byte(tt.content)) if tt.wantErr { assert.Error(t, err) } else { assert.NoError(t, err) } }) } } func TestGenerateSnippet(t *testing.T) { svc := NewService() tests := []struct { name string content string maxLength int expected string }{ { name: "simple text", content: "Hello world", maxLength: 100, expected: "Hello world", }, { name: "text with formatting", content: "This is **bold** and *italic* text.", maxLength: 100, expected: "This is bold and italic text.", }, { name: "truncate long text", content: "This is a very long piece of text that should be truncated at a word boundary.", maxLength: 30, expected: "This is a very long piece of ...", }, { name: "heading and paragraph", content: "# My Title\n\nThis is the first paragraph.", maxLength: 100, expected: "My Title This is the first paragraph.", }, { name: "code block removed", content: "Text before\n\n```go\ncode\n```\n\nText after", maxLength: 100, expected: "Text before Text after", }, { name: "list items", content: "- Item 1\n- Item 2\n- Item 3", maxLength: 100, expected: "Item 1 Item 2 Item 3", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { snippet, err := svc.GenerateSnippet([]byte(tt.content), tt.maxLength) require.NoError(t, err) assert.Equal(t, tt.expected, snippet) }) } } func TestExtractProperties(t *testing.T) { tests := []struct { name string content string hasLink bool hasCode bool hasTasks bool hasInc bool }{ { name: "plain text", content: "Just plain text", hasLink: false, hasCode: false, hasTasks: false, hasInc: false, }, { name: "with link", content: "Check out [this link](https://example.com)", hasLink: true, hasCode: false, hasTasks: false, hasInc: false, }, { name: "with inline code", content: "Use `console.log()` to debug", hasLink: false, hasCode: true, hasTasks: false, hasInc: false, }, { name: "with code block", content: "```go\nfunc main() {}\n```", hasLink: false, hasCode: true, hasTasks: false, hasInc: false, }, { name: "with completed task", content: "- [x] Completed task", hasLink: false, hasCode: false, hasTasks: true, hasInc: false, }, { name: "with incomplete task", content: "- [ ] Todo item", hasLink: false, hasCode: false, hasTasks: true, hasInc: true, }, { name: "mixed tasks", content: "- [x] Done\n- [ ] Not done", hasLink: false, hasCode: false, hasTasks: true, hasInc: true, }, { name: "everything", content: "# Title\n\n[Link](url)\n\n`code`\n\n- [ ] Task", hasLink: true, hasCode: true, hasTasks: true, hasInc: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { svc := NewService() props, err := svc.ExtractProperties([]byte(tt.content)) require.NoError(t, err) assert.Equal(t, tt.hasLink, props.HasLink, "HasLink") assert.Equal(t, tt.hasCode, props.HasCode, "HasCode") assert.Equal(t, tt.hasTasks, props.HasTaskList, "HasTaskList") assert.Equal(t, tt.hasInc, props.HasIncompleteTasks, "HasIncompleteTasks") }) } } func TestExtractTags(t *testing.T) { tests := []struct { name string content string withExt bool expected []string }{ { name: "no tags", content: "Just plain text", withExt: false, expected: []string{}, }, { name: "single tag", content: "Text with #tag", withExt: true, expected: []string{"tag"}, }, { name: "multiple tags", content: "Text with #tag1 and #tag2", withExt: true, expected: []string{"tag1", "tag2"}, }, { name: "duplicate tags", content: "#work is important. #Work #WORK", withExt: true, expected: []string{"work"}, // Deduplicated and lowercased }, { name: "tags with hyphens and underscores", content: "Tags: #work-notes #2024_plans", withExt: true, expected: []string{"work-notes", "2024_plans"}, }, { name: "tags at end of sentence", content: "This is important #urgent.", withExt: true, expected: []string{"urgent"}, }, { name: "headings not tags", content: "## Heading\n\n# Title\n\nText with #realtag", withExt: true, expected: []string{"realtag"}, }, { name: "numeric tag", content: "Issue #123", withExt: true, expected: []string{"123"}, }, { name: "tag in list", content: "- Item 1 #todo\n- Item 2 #done", withExt: true, expected: []string{"todo", "done"}, }, { name: "no extension enabled", content: "Text with #tag", withExt: false, expected: []string{}, }, { name: "Chinese tag", content: "Text with #测试", withExt: true, expected: []string{"测试"}, }, { name: "Chinese tag followed by punctuation", content: "Text #测试。 More text", withExt: true, expected: []string{"测试"}, }, { name: "mixed Chinese and ASCII tag", content: "#测试test123 content", withExt: true, expected: []string{"测试test123"}, }, { name: "Japanese tag", content: "#日本語 content", withExt: true, expected: []string{"日本語"}, }, { name: "Korean tag", content: "#한국어 content", withExt: true, expected: []string{"한국어"}, }, { name: "hierarchical tag with Chinese", content: "#work/测试/项目", withExt: true, expected: []string{"work/测试/项目"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { var svc Service if tt.withExt { svc = NewService(WithTagExtension()) } else { svc = NewService() } tags, err := svc.ExtractTags([]byte(tt.content)) require.NoError(t, err) assert.ElementsMatch(t, tt.expected, tags) }) } } func TestUniqueLowercase(t *testing.T) { tests := []struct { name string input []string expected []string }{ { name: "empty", input: []string{}, expected: []string{}, }, { name: "unique items", input: []string{"tag1", "tag2", "tag3"}, expected: []string{"tag1", "tag2", "tag3"}, }, { name: "duplicates", input: []string{"tag", "TAG", "Tag"}, expected: []string{"tag"}, }, { name: "mixed", input: []string{"Work", "work", "Important", "work"}, expected: []string{"work", "important"}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := uniqueLowercase(tt.input) assert.ElementsMatch(t, tt.expected, result) }) } } func TestTruncateAtWord(t *testing.T) { tests := []struct { name string input string maxLength int expected string }{ { name: "no truncation needed", input: "short", maxLength: 10, expected: "short", }, { name: "exact length", input: "exactly ten", maxLength: 11, expected: "exactly ten", }, { name: "truncate at word", input: "this is a long sentence", maxLength: 10, expected: "this is a ...", }, { name: "truncate very long word", input: "supercalifragilisticexpialidocious", maxLength: 10, expected: "supercalif ...", }, { name: "CJK characters without spaces", input: "这是一个很长的中文句子没有空格的情况下也要正确处理", maxLength: 15, expected: "这是一个很长的中文句子没有空格 ...", }, { name: "mixed CJK and Latin", input: "这是中文mixed with English文字", maxLength: 10, expected: "这是中文mixed ...", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := truncateAtWord(tt.input, tt.maxLength) assert.Equal(t, tt.expected, result) }) } } // Benchmark tests. func BenchmarkGenerateSnippet(b *testing.B) { svc := NewService() content := []byte(`# Large Document This is a large document with multiple paragraphs and formatting. ## Section 1 Here is some **bold** text and *italic* text with [links](https://example.com). - List item 1 - List item 2 - List item 3 ## Section 2 More content here with ` + "`inline code`" + ` and other elements. ` + "```go\nfunc example() {\n return true\n}\n```") b.ResetTimer() for i := 0; i < b.N; i++ { _, err := svc.GenerateSnippet(content, 200) if err != nil { b.Fatal(err) } } } func BenchmarkExtractProperties(b *testing.B) { svc := NewService() content := []byte("# Title\n\n[Link](url)\n\n`code`\n\n- [ ] Task\n- [x] Done") b.ResetTimer() for i := 0; i < b.N; i++ { _, err := svc.ExtractProperties(content) if err != nil { b.Fatal(err) } } }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/markdown/markdown.go
plugin/markdown/markdown.go
package markdown import ( "bytes" "strings" "github.com/yuin/goldmark" gast "github.com/yuin/goldmark/ast" "github.com/yuin/goldmark/extension" east "github.com/yuin/goldmark/extension/ast" "github.com/yuin/goldmark/parser" "github.com/yuin/goldmark/text" mast "github.com/usememos/memos/plugin/markdown/ast" "github.com/usememos/memos/plugin/markdown/extensions" "github.com/usememos/memos/plugin/markdown/renderer" storepb "github.com/usememos/memos/proto/gen/store" ) // ExtractedData contains all metadata extracted from markdown in a single pass. type ExtractedData struct { Tags []string Property *storepb.MemoPayload_Property } // Service handles markdown metadata extraction. // It uses goldmark to parse markdown and extract tags, properties, and snippets. // HTML rendering is primarily done on frontend using markdown-it, but backend provides // RenderHTML for RSS feeds and other server-side rendering needs. type Service interface { // ExtractAll extracts tags, properties, and references in a single parse (most efficient) ExtractAll(content []byte) (*ExtractedData, error) // ExtractTags returns all #tags found in content ExtractTags(content []byte) ([]string, error) // ExtractProperties computes boolean properties ExtractProperties(content []byte) (*storepb.MemoPayload_Property, error) // RenderMarkdown renders goldmark AST back to markdown text RenderMarkdown(content []byte) (string, error) // RenderHTML renders markdown content to HTML RenderHTML(content []byte) (string, error) // GenerateSnippet creates plain text summary GenerateSnippet(content []byte, maxLength int) (string, error) // ValidateContent checks for syntax errors ValidateContent(content []byte) error // RenameTag renames all occurrences of oldTag to newTag in content RenameTag(content []byte, oldTag, newTag string) (string, error) } // service implements the Service interface. type service struct { md goldmark.Markdown } // Option configures the markdown service. type Option func(*config) type config struct { enableTags bool } // WithTagExtension enables #tag parsing. func WithTagExtension() Option { return func(c *config) { c.enableTags = true } } // NewService creates a new markdown service with the given options. func NewService(opts ...Option) Service { cfg := &config{} for _, opt := range opts { opt(cfg) } exts := []goldmark.Extender{ extension.GFM, // GitHub Flavored Markdown (tables, strikethrough, task lists, autolinks) } // Add custom extensions based on config if cfg.enableTags { exts = append(exts, extensions.TagExtension) } md := goldmark.New( goldmark.WithExtensions(exts...), goldmark.WithParserOptions( parser.WithAutoHeadingID(), // Generate heading IDs ), ) return &service{ md: md, } } // parse is an internal helper to parse content into AST. func (s *service) parse(content []byte) (gast.Node, error) { reader := text.NewReader(content) doc := s.md.Parser().Parse(reader) return doc, nil } // ExtractTags returns all #tags found in content. func (s *service) ExtractTags(content []byte) ([]string, error) { root, err := s.parse(content) if err != nil { return nil, err } var tags []string // Walk the AST to find tag nodes err = gast.Walk(root, func(n gast.Node, entering bool) (gast.WalkStatus, error) { if !entering { return gast.WalkContinue, nil } // Check for custom TagNode if tagNode, ok := n.(*mast.TagNode); ok { tags = append(tags, string(tagNode.Tag)) } return gast.WalkContinue, nil }) if err != nil { return nil, err } // Deduplicate and normalize tags return uniqueLowercase(tags), nil } // ExtractProperties computes boolean properties about the content. func (s *service) ExtractProperties(content []byte) (*storepb.MemoPayload_Property, error) { root, err := s.parse(content) if err != nil { return nil, err } prop := &storepb.MemoPayload_Property{} err = gast.Walk(root, func(n gast.Node, entering bool) (gast.WalkStatus, error) { if !entering { return gast.WalkContinue, nil } switch n.Kind() { case gast.KindLink: prop.HasLink = true case gast.KindCodeBlock, gast.KindFencedCodeBlock, gast.KindCodeSpan: prop.HasCode = true case east.KindTaskCheckBox: prop.HasTaskList = true if checkBox, ok := n.(*east.TaskCheckBox); ok { if !checkBox.IsChecked { prop.HasIncompleteTasks = true } } default: // No special handling for other node types } return gast.WalkContinue, nil }) if err != nil { return nil, err } return prop, nil } // RenderMarkdown renders goldmark AST back to markdown text. func (s *service) RenderMarkdown(content []byte) (string, error) { root, err := s.parse(content) if err != nil { return "", err } mdRenderer := renderer.NewMarkdownRenderer() return mdRenderer.Render(root, content), nil } // RenderHTML renders markdown content to HTML using goldmark's built-in HTML renderer. func (s *service) RenderHTML(content []byte) (string, error) { var buf bytes.Buffer if err := s.md.Convert(content, &buf); err != nil { return "", err } return buf.String(), nil } // GenerateSnippet creates a plain text summary from markdown content. func (s *service) GenerateSnippet(content []byte, maxLength int) (string, error) { root, err := s.parse(content) if err != nil { return "", err } var buf strings.Builder var lastNodeWasBlock bool err = gast.Walk(root, func(n gast.Node, entering bool) (gast.WalkStatus, error) { if entering { // Skip code blocks and code spans entirely switch n.Kind() { case gast.KindCodeBlock, gast.KindFencedCodeBlock, gast.KindCodeSpan: return gast.WalkSkipChildren, nil default: // Continue walking for other node types } // Add space before block elements (except first) switch n.Kind() { case gast.KindParagraph, gast.KindHeading, gast.KindListItem: if buf.Len() > 0 && lastNodeWasBlock { buf.WriteByte(' ') } default: // No space needed for other node types } } if !entering { // Mark that we just exited a block element switch n.Kind() { case gast.KindParagraph, gast.KindHeading, gast.KindListItem: lastNodeWasBlock = true default: // Not a block element } return gast.WalkContinue, nil } lastNodeWasBlock = false // Only extract plain text nodes if textNode, ok := n.(*gast.Text); ok { segment := textNode.Segment buf.Write(segment.Value(content)) // Add space if this is a soft line break if textNode.SoftLineBreak() { buf.WriteByte(' ') } } // Stop walking if we've exceeded double the max length // (we'll truncate precisely later) if buf.Len() > maxLength*2 { return gast.WalkStop, nil } return gast.WalkContinue, nil }) if err != nil { return "", err } snippet := buf.String() // Truncate at word boundary if needed if len(snippet) > maxLength { snippet = truncateAtWord(snippet, maxLength) } return strings.TrimSpace(snippet), nil } // ValidateContent checks if the markdown content is valid. func (s *service) ValidateContent(content []byte) error { // Try to parse the content _, err := s.parse(content) return err } // ExtractAll extracts tags, properties, and references in a single parse for efficiency. func (s *service) ExtractAll(content []byte) (*ExtractedData, error) { root, err := s.parse(content) if err != nil { return nil, err } data := &ExtractedData{ Tags: []string{}, Property: &storepb.MemoPayload_Property{}, } // Single walk to collect all data err = gast.Walk(root, func(n gast.Node, entering bool) (gast.WalkStatus, error) { if !entering { return gast.WalkContinue, nil } // Extract tags if tagNode, ok := n.(*mast.TagNode); ok { data.Tags = append(data.Tags, string(tagNode.Tag)) } // Extract properties based on node kind switch n.Kind() { case gast.KindLink: data.Property.HasLink = true case gast.KindCodeBlock, gast.KindFencedCodeBlock, gast.KindCodeSpan: data.Property.HasCode = true case east.KindTaskCheckBox: data.Property.HasTaskList = true if checkBox, ok := n.(*east.TaskCheckBox); ok { if !checkBox.IsChecked { data.Property.HasIncompleteTasks = true } } default: // No special handling for other node types } return gast.WalkContinue, nil }) if err != nil { return nil, err } // Deduplicate and normalize tags data.Tags = uniqueLowercase(data.Tags) return data, nil } // RenameTag renames all occurrences of oldTag to newTag in content. func (s *service) RenameTag(content []byte, oldTag, newTag string) (string, error) { root, err := s.parse(content) if err != nil { return "", err } // Walk the AST to find and rename tag nodes err = gast.Walk(root, func(n gast.Node, entering bool) (gast.WalkStatus, error) { if !entering { return gast.WalkContinue, nil } // Check for custom TagNode and rename if it matches if tagNode, ok := n.(*mast.TagNode); ok { if string(tagNode.Tag) == oldTag { tagNode.Tag = []byte(newTag) } } return gast.WalkContinue, nil }) if err != nil { return "", err } // Render back to markdown using the already-parsed AST mdRenderer := renderer.NewMarkdownRenderer() return mdRenderer.Render(root, content), nil } // uniqueLowercase returns unique lowercase strings from input. func uniqueLowercase(strs []string) []string { seen := make(map[string]bool) var result []string for _, s := range strs { lower := strings.ToLower(s) if !seen[lower] { seen[lower] = true result = append(result, lower) } } return result } // truncateAtWord truncates a string at the last word boundary before maxLength. // maxLength is treated as a rune (character) count to properly handle UTF-8 multi-byte characters. func truncateAtWord(s string, maxLength int) string { // Convert to runes to properly handle multi-byte UTF-8 characters runes := []rune(s) if len(runes) <= maxLength { return s } // Truncate to max length (by character count, not byte count) truncated := string(runes[:maxLength]) // Find last space to avoid cutting in the middle of a word lastSpace := strings.LastIndexAny(truncated, " \t\n\r") if lastSpace > 0 { truncated = truncated[:lastSpace] } return truncated + " ..." }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/markdown/renderer/markdown_renderer.go
plugin/markdown/renderer/markdown_renderer.go
package renderer import ( "bytes" "fmt" "strings" gast "github.com/yuin/goldmark/ast" east "github.com/yuin/goldmark/extension/ast" mast "github.com/usememos/memos/plugin/markdown/ast" ) // MarkdownRenderer renders goldmark AST back to markdown text. type MarkdownRenderer struct { buf *bytes.Buffer } // NewMarkdownRenderer creates a new markdown renderer. func NewMarkdownRenderer() *MarkdownRenderer { return &MarkdownRenderer{ buf: &bytes.Buffer{}, } } // Render renders the AST node to markdown and returns the result. func (r *MarkdownRenderer) Render(node gast.Node, source []byte) string { r.buf.Reset() r.renderNode(node, source, 0) return r.buf.String() } // renderNode renders a single node and its children. func (r *MarkdownRenderer) renderNode(node gast.Node, source []byte, depth int) { switch n := node.(type) { case *gast.Document: r.renderChildren(n, source, depth) case *gast.Paragraph: r.renderChildren(n, source, depth) if node.NextSibling() != nil { r.buf.WriteString("\n\n") } case *gast.Text: // Text nodes store their content as segments in the source segment := n.Segment r.buf.Write(segment.Value(source)) if n.SoftLineBreak() { r.buf.WriteByte('\n') } else if n.HardLineBreak() { r.buf.WriteString(" \n") } case *gast.CodeSpan: r.buf.WriteByte('`') r.renderChildren(n, source, depth) r.buf.WriteByte('`') case *gast.Emphasis: symbol := "*" if n.Level == 2 { symbol = "**" } r.buf.WriteString(symbol) r.renderChildren(n, source, depth) r.buf.WriteString(symbol) case *gast.Link: r.buf.WriteString("[") r.renderChildren(n, source, depth) r.buf.WriteString("](") r.buf.Write(n.Destination) if len(n.Title) > 0 { r.buf.WriteString(` "`) r.buf.Write(n.Title) r.buf.WriteString(`"`) } r.buf.WriteString(")") case *gast.AutoLink: url := n.URL(source) if n.AutoLinkType == gast.AutoLinkEmail { r.buf.WriteString("<") r.buf.Write(url) r.buf.WriteString(">") } else { r.buf.Write(url) } case *gast.Image: r.buf.WriteString("![") r.renderChildren(n, source, depth) r.buf.WriteString("](") r.buf.Write(n.Destination) if len(n.Title) > 0 { r.buf.WriteString(` "`) r.buf.Write(n.Title) r.buf.WriteString(`"`) } r.buf.WriteString(")") case *gast.Heading: r.buf.WriteString(strings.Repeat("#", n.Level)) r.buf.WriteByte(' ') r.renderChildren(n, source, depth) if node.NextSibling() != nil { r.buf.WriteString("\n\n") } case *gast.CodeBlock, *gast.FencedCodeBlock: r.renderCodeBlock(n, source) case *gast.Blockquote: // Render each child line with "> " prefix r.renderBlockquote(n, source, depth) if node.NextSibling() != nil { r.buf.WriteString("\n\n") } case *gast.List: r.renderChildren(n, source, depth) if node.NextSibling() != nil { r.buf.WriteString("\n\n") } case *gast.ListItem: r.renderListItem(n, source, depth) case *gast.ThematicBreak: r.buf.WriteString("---") if node.NextSibling() != nil { r.buf.WriteString("\n\n") } case *east.Strikethrough: r.buf.WriteString("~~") r.renderChildren(n, source, depth) r.buf.WriteString("~~") case *east.TaskCheckBox: if n.IsChecked { r.buf.WriteString("[x] ") } else { r.buf.WriteString("[ ] ") } case *east.Table: r.renderTable(n, source) if node.NextSibling() != nil { r.buf.WriteString("\n\n") } // Custom Memos nodes case *mast.TagNode: r.buf.WriteByte('#') r.buf.Write(n.Tag) default: // For unknown nodes, try to render children r.renderChildren(n, source, depth) } } // renderChildren renders all children of a node. func (r *MarkdownRenderer) renderChildren(node gast.Node, source []byte, depth int) { child := node.FirstChild() for child != nil { r.renderNode(child, source, depth+1) child = child.NextSibling() } } // renderCodeBlock renders a code block. func (r *MarkdownRenderer) renderCodeBlock(node gast.Node, source []byte) { if fenced, ok := node.(*gast.FencedCodeBlock); ok { // Fenced code block with language r.buf.WriteString("```") if lang := fenced.Language(source); len(lang) > 0 { r.buf.Write(lang) } r.buf.WriteByte('\n') // Write all lines lines := fenced.Lines() for i := 0; i < lines.Len(); i++ { line := lines.At(i) r.buf.Write(line.Value(source)) } r.buf.WriteString("```") if node.NextSibling() != nil { r.buf.WriteString("\n\n") } } else if codeBlock, ok := node.(*gast.CodeBlock); ok { // Indented code block lines := codeBlock.Lines() for i := 0; i < lines.Len(); i++ { line := lines.At(i) r.buf.WriteString(" ") r.buf.Write(line.Value(source)) } if node.NextSibling() != nil { r.buf.WriteString("\n\n") } } } // renderBlockquote renders a blockquote with "> " prefix. func (r *MarkdownRenderer) renderBlockquote(node *gast.Blockquote, source []byte, depth int) { // Create a temporary buffer for the blockquote content tempBuf := &bytes.Buffer{} tempRenderer := &MarkdownRenderer{buf: tempBuf} tempRenderer.renderChildren(node, source, depth) // Add "> " prefix to each line content := tempBuf.String() lines := strings.Split(strings.TrimRight(content, "\n"), "\n") for i, line := range lines { r.buf.WriteString("> ") r.buf.WriteString(line) if i < len(lines)-1 { r.buf.WriteByte('\n') } } } // renderListItem renders a list item with proper indentation and markers. func (r *MarkdownRenderer) renderListItem(node *gast.ListItem, source []byte, depth int) { parent := node.Parent() list, ok := parent.(*gast.List) if !ok { r.renderChildren(node, source, depth) return } // Add indentation only for nested lists // Document=0, List=1, ListItem=2 (no indent), nested ListItem=3+ (indent) if depth > 2 { indent := strings.Repeat(" ", depth-2) r.buf.WriteString(indent) } // Add list marker if list.IsOrdered() { fmt.Fprintf(r.buf, "%d. ", list.Start) list.Start++ // Increment for next item } else { r.buf.WriteString("- ") } // Render content r.renderChildren(node, source, depth) // Add newline if there's a next sibling if node.NextSibling() != nil { r.buf.WriteByte('\n') } } // renderTable renders a table in markdown format. func (r *MarkdownRenderer) renderTable(table *east.Table, source []byte) { // This is a simplified table renderer // A full implementation would need to handle alignment, etc. r.renderChildren(table, source, 0) }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/markdown/renderer/markdown_renderer_test.go
plugin/markdown/renderer/markdown_renderer_test.go
package renderer import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/yuin/goldmark" "github.com/yuin/goldmark/extension" "github.com/yuin/goldmark/parser" "github.com/yuin/goldmark/text" "github.com/usememos/memos/plugin/markdown/extensions" ) func TestMarkdownRenderer(t *testing.T) { // Create goldmark instance with all extensions md := goldmark.New( goldmark.WithExtensions( extension.GFM, extensions.TagExtension, ), goldmark.WithParserOptions( parser.WithAutoHeadingID(), ), ) tests := []struct { name string input string expected string }{ { name: "simple text", input: "Hello world", expected: "Hello world", }, { name: "paragraph with newlines", input: "First paragraph\n\nSecond paragraph", expected: "First paragraph\n\nSecond paragraph", }, { name: "emphasis", input: "This is *italic* and **bold** text", expected: "This is *italic* and **bold** text", }, { name: "headings", input: "# Heading 1\n\n## Heading 2\n\n### Heading 3", expected: "# Heading 1\n\n## Heading 2\n\n### Heading 3", }, { name: "link", input: "Check [this link](https://example.com)", expected: "Check [this link](https://example.com)", }, { name: "image", input: "![alt text](image.png)", expected: "![alt text](image.png)", }, { name: "code inline", input: "This is `inline code` here", expected: "This is `inline code` here", }, { name: "code block fenced", input: "```go\nfunc main() {\n}\n```", expected: "```go\nfunc main() {\n}\n```", }, { name: "unordered list", input: "- Item 1\n- Item 2\n- Item 3", expected: "- Item 1\n- Item 2\n- Item 3", }, { name: "ordered list", input: "1. First\n2. Second\n3. Third", expected: "1. First\n2. Second\n3. Third", }, { name: "blockquote", input: "> This is a quote\n> Second line", expected: "> This is a quote\n> Second line", }, { name: "horizontal rule", input: "Text before\n\n---\n\nText after", expected: "Text before\n\n---\n\nText after", }, { name: "strikethrough", input: "This is ~~deleted~~ text", expected: "This is ~~deleted~~ text", }, { name: "task list", input: "- [x] Completed task\n- [ ] Incomplete task", expected: "- [x] Completed task\n- [ ] Incomplete task", }, { name: "tag", input: "This has #tag in it", expected: "This has #tag in it", }, { name: "multiple tags", input: "#work #important meeting notes", expected: "#work #important meeting notes", }, { name: "complex mixed content", input: "# Meeting Notes\n\n**Date**: 2024-01-01\n\n## Attendees\n- Alice\n- Bob\n\n## Discussion\n\nWe discussed #project status.\n\n```python\nprint('hello')\n```", expected: "# Meeting Notes\n\n**Date**: 2024-01-01\n\n## Attendees\n\n- Alice\n- Bob\n\n## Discussion\n\nWe discussed #project status.\n\n```python\nprint('hello')\n```", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Parse the input source := []byte(tt.input) reader := text.NewReader(source) doc := md.Parser().Parse(reader) require.NotNil(t, doc) // Render back to markdown renderer := NewMarkdownRenderer() result := renderer.Render(doc, source) // For debugging if result != tt.expected { t.Logf("Input: %q", tt.input) t.Logf("Expected: %q", tt.expected) t.Logf("Got: %q", result) } assert.Equal(t, tt.expected, result) }) } } func TestMarkdownRendererPreservesStructure(t *testing.T) { // Test that parsing and rendering preserves structure md := goldmark.New( goldmark.WithExtensions( extension.GFM, extensions.TagExtension, ), ) inputs := []string{ "# Title\n\nParagraph", "**Bold** and *italic*", "- List\n- Items", "#tag #another", "> Quote", } renderer := NewMarkdownRenderer() for _, input := range inputs { t.Run(input, func(t *testing.T) { source := []byte(input) reader := text.NewReader(source) doc := md.Parser().Parse(reader) result := renderer.Render(doc, source) // The result should be structurally similar // (may have minor formatting differences) assert.NotEmpty(t, result) }) } }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/markdown/extensions/tag.go
plugin/markdown/extensions/tag.go
package extensions import ( "github.com/yuin/goldmark" "github.com/yuin/goldmark/parser" "github.com/yuin/goldmark/util" mparser "github.com/usememos/memos/plugin/markdown/parser" ) type tagExtension struct{} // TagExtension is a goldmark extension for #tag syntax. var TagExtension = &tagExtension{} // Extend extends the goldmark parser with tag support. func (*tagExtension) Extend(m goldmark.Markdown) { m.Parser().AddOptions( parser.WithInlineParsers( // Priority 200 - run before standard link parser (500) util.Prioritized(mparser.NewTagParser(), 200), ), ) }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/markdown/ast/tag.go
plugin/markdown/ast/tag.go
package ast import ( gast "github.com/yuin/goldmark/ast" ) // TagNode represents a #tag in the markdown AST. type TagNode struct { gast.BaseInline // Tag name without the # prefix Tag []byte } // KindTag is the NodeKind for TagNode. var KindTag = gast.NewNodeKind("Tag") // Kind returns KindTag. func (*TagNode) Kind() gast.NodeKind { return KindTag } // Dump implements Node.Dump for debugging. func (n *TagNode) Dump(source []byte, level int) { gast.DumpHelper(n, source, level, map[string]string{ "Tag": string(n.Tag), }, nil) }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/markdown/parser/tag_test.go
plugin/markdown/parser/tag_test.go
package parser import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/yuin/goldmark/parser" "github.com/yuin/goldmark/text" mast "github.com/usememos/memos/plugin/markdown/ast" ) func TestTagParser(t *testing.T) { tests := []struct { name string input string expectedTag string shouldParse bool }{ { name: "basic tag", input: "#tag", expectedTag: "tag", shouldParse: true, }, { name: "tag with hyphen", input: "#work-notes", expectedTag: "work-notes", shouldParse: true, }, { name: "tag with underscore", input: "#2024_plans", expectedTag: "2024_plans", shouldParse: true, }, { name: "numeric tag", input: "#123", expectedTag: "123", shouldParse: true, }, { name: "tag followed by space", input: "#tag ", expectedTag: "tag", shouldParse: true, }, { name: "tag followed by punctuation", input: "#tag.", expectedTag: "tag", shouldParse: true, }, { name: "tag in sentence", input: "#important task", expectedTag: "important", shouldParse: true, }, { name: "heading (##)", input: "## Heading", expectedTag: "", shouldParse: false, }, { name: "space after hash", input: "# heading", expectedTag: "", shouldParse: false, }, { name: "lone hash", input: "#", expectedTag: "", shouldParse: false, }, { name: "hash with space", input: "# ", expectedTag: "", shouldParse: false, }, { name: "special characters", input: "#tag@special", expectedTag: "tag", shouldParse: true, }, { name: "mixed case", input: "#WorkNotes", expectedTag: "WorkNotes", shouldParse: true, }, { name: "hierarchical tag with slash", input: "#tag1/subtag", expectedTag: "tag1/subtag", shouldParse: true, }, { name: "hierarchical tag with multiple levels", input: "#tag1/subtag/subtag2", expectedTag: "tag1/subtag/subtag2", shouldParse: true, }, { name: "hierarchical tag followed by space", input: "#work/notes ", expectedTag: "work/notes", shouldParse: true, }, { name: "hierarchical tag followed by punctuation", input: "#project/2024.", expectedTag: "project/2024", shouldParse: true, }, { name: "hierarchical tag with numbers and dashes", input: "#work-log/2024/q1", expectedTag: "work-log/2024/q1", shouldParse: true, }, { name: "Chinese characters", input: "#测试", expectedTag: "测试", shouldParse: true, }, { name: "Chinese tag followed by space", input: "#测试 some text", expectedTag: "测试", shouldParse: true, }, { name: "Chinese tag followed by punctuation", input: "#测试。", expectedTag: "测试", shouldParse: true, }, { name: "mixed Chinese and ASCII", input: "#测试test123", expectedTag: "测试test123", shouldParse: true, }, { name: "Japanese characters", input: "#テスト", expectedTag: "テスト", shouldParse: true, }, { name: "Korean characters", input: "#테스트", expectedTag: "테스트", shouldParse: true, }, { name: "emoji", input: "#test🚀", expectedTag: "test🚀", shouldParse: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { p := NewTagParser() reader := text.NewReader([]byte(tt.input)) ctx := parser.NewContext() node := p.Parse(nil, reader, ctx) if tt.shouldParse { require.NotNil(t, node, "Expected tag to be parsed") require.IsType(t, &mast.TagNode{}, node) tagNode, ok := node.(*mast.TagNode) require.True(t, ok, "Expected node to be *mast.TagNode") assert.Equal(t, tt.expectedTag, string(tagNode.Tag)) } else { assert.Nil(t, node, "Expected tag NOT to be parsed") } }) } } func TestTagParser_Trigger(t *testing.T) { p := NewTagParser() triggers := p.Trigger() assert.Equal(t, []byte{'#'}, triggers) } func TestTagParser_MultipleTags(t *testing.T) { // Test that parser correctly handles multiple tags in sequence input := "#tag1 #tag2" p := NewTagParser() reader := text.NewReader([]byte(input)) ctx := parser.NewContext() // Parse first tag node1 := p.Parse(nil, reader, ctx) require.NotNil(t, node1) tagNode1, ok := node1.(*mast.TagNode) require.True(t, ok, "Expected node1 to be *mast.TagNode") assert.Equal(t, "tag1", string(tagNode1.Tag)) // Advance past the space reader.Advance(1) // Parse second tag node2 := p.Parse(nil, reader, ctx) require.NotNil(t, node2) tagNode2, ok := node2.(*mast.TagNode) require.True(t, ok, "Expected node2 to be *mast.TagNode") assert.Equal(t, "tag2", string(tagNode2.Tag)) } func TestTagNode_Kind(t *testing.T) { node := &mast.TagNode{ Tag: []byte("test"), } assert.Equal(t, mast.KindTag, node.Kind()) } func TestTagNode_Dump(t *testing.T) { node := &mast.TagNode{ Tag: []byte("test"), } // Should not panic assert.NotPanics(t, func() { node.Dump([]byte("#test"), 0) }) }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/plugin/markdown/parser/tag.go
plugin/markdown/parser/tag.go
package parser import ( "unicode" "unicode/utf8" gast "github.com/yuin/goldmark/ast" "github.com/yuin/goldmark/parser" "github.com/yuin/goldmark/text" mast "github.com/usememos/memos/plugin/markdown/ast" ) const ( // MaxTagLength defines the maximum number of runes allowed in a tag. MaxTagLength = 100 ) type tagParser struct{} // NewTagParser creates a new inline parser for #tag syntax. func NewTagParser() parser.InlineParser { return &tagParser{} } // Trigger returns the characters that trigger this parser. func (*tagParser) Trigger() []byte { return []byte{'#'} } // isValidTagRune checks if a Unicode rune is valid in a tag. // Uses Unicode categories for proper international character support. func isValidTagRune(r rune) bool { // Allow Unicode letters (any script: Latin, CJK, Arabic, Cyrillic, etc.) if unicode.IsLetter(r) { return true } // Allow Unicode digits if unicode.IsNumber(r) { return true } // Allow emoji and symbols (So category: Symbol, Other) // This includes emoji, which are essential for social media-style tagging if unicode.IsSymbol(r) { return true } // Allow specific ASCII symbols for tag structure // Underscore: word separation (snake_case) // Hyphen: word separation (kebab-case) // Forward slash: hierarchical tags (category/subcategory) if r == '_' || r == '-' || r == '/' { return true } return false } // Parse parses #tag syntax using Unicode-aware validation. // Tags support international characters and follow these rules: // - Must start with # followed by valid tag characters // - Valid characters: Unicode letters, Unicode digits, underscore (_), hyphen (-), forward slash (/) // - Maximum length: 100 runes (Unicode characters) // - Stops at: whitespace, punctuation, or other invalid characters func (*tagParser) Parse(_ gast.Node, block text.Reader, _ parser.Context) gast.Node { line, _ := block.PeekLine() // Must start with # if len(line) == 0 || line[0] != '#' { return nil } // Check if it's a heading (## or space after #) if len(line) > 1 { if line[1] == '#' { // It's a heading (##), not a tag return nil } if line[1] == ' ' { // Space after # - heading or just a hash return nil } } else { // Just a lone # return nil } // Parse tag using UTF-8 aware rune iteration tagStart := 1 pos := tagStart runeCount := 0 for pos < len(line) { r, size := utf8.DecodeRune(line[pos:]) // Stop at invalid UTF-8 if r == utf8.RuneError && size == 1 { break } // Validate character using Unicode categories if !isValidTagRune(r) { break } // Enforce max length (by rune count, not byte count) runeCount++ if runeCount > MaxTagLength { break } pos += size } // Must have at least one character after # if pos <= tagStart { return nil } // Extract tag (without #) tagName := line[tagStart:pos] // Make a copy of the tag name tagCopy := make([]byte, len(tagName)) copy(tagCopy, tagName) // Advance reader block.Advance(pos) // Create node node := &mast.TagNode{ Tag: tagCopy, } return node }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/proto/gen/store/memo.pb.go
proto/gen/store/memo.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.36.11 // protoc (unknown) // source: store/memo.proto package store import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type MemoPayload struct { state protoimpl.MessageState `protogen:"open.v1"` Property *MemoPayload_Property `protobuf:"bytes,1,opt,name=property,proto3" json:"property,omitempty"` Location *MemoPayload_Location `protobuf:"bytes,2,opt,name=location,proto3" json:"location,omitempty"` Tags []string `protobuf:"bytes,3,rep,name=tags,proto3" json:"tags,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *MemoPayload) Reset() { *x = MemoPayload{} mi := &file_store_memo_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *MemoPayload) String() string { return protoimpl.X.MessageStringOf(x) } func (*MemoPayload) ProtoMessage() {} func (x *MemoPayload) ProtoReflect() protoreflect.Message { mi := &file_store_memo_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use MemoPayload.ProtoReflect.Descriptor instead. func (*MemoPayload) Descriptor() ([]byte, []int) { return file_store_memo_proto_rawDescGZIP(), []int{0} } func (x *MemoPayload) GetProperty() *MemoPayload_Property { if x != nil { return x.Property } return nil } func (x *MemoPayload) GetLocation() *MemoPayload_Location { if x != nil { return x.Location } return nil } func (x *MemoPayload) GetTags() []string { if x != nil { return x.Tags } return nil } // The calculated properties from the memo content. type MemoPayload_Property struct { state protoimpl.MessageState `protogen:"open.v1"` HasLink bool `protobuf:"varint,1,opt,name=has_link,json=hasLink,proto3" json:"has_link,omitempty"` HasTaskList bool `protobuf:"varint,2,opt,name=has_task_list,json=hasTaskList,proto3" json:"has_task_list,omitempty"` HasCode bool `protobuf:"varint,3,opt,name=has_code,json=hasCode,proto3" json:"has_code,omitempty"` HasIncompleteTasks bool `protobuf:"varint,4,opt,name=has_incomplete_tasks,json=hasIncompleteTasks,proto3" json:"has_incomplete_tasks,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *MemoPayload_Property) Reset() { *x = MemoPayload_Property{} mi := &file_store_memo_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *MemoPayload_Property) String() string { return protoimpl.X.MessageStringOf(x) } func (*MemoPayload_Property) ProtoMessage() {} func (x *MemoPayload_Property) ProtoReflect() protoreflect.Message { mi := &file_store_memo_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use MemoPayload_Property.ProtoReflect.Descriptor instead. func (*MemoPayload_Property) Descriptor() ([]byte, []int) { return file_store_memo_proto_rawDescGZIP(), []int{0, 0} } func (x *MemoPayload_Property) GetHasLink() bool { if x != nil { return x.HasLink } return false } func (x *MemoPayload_Property) GetHasTaskList() bool { if x != nil { return x.HasTaskList } return false } func (x *MemoPayload_Property) GetHasCode() bool { if x != nil { return x.HasCode } return false } func (x *MemoPayload_Property) GetHasIncompleteTasks() bool { if x != nil { return x.HasIncompleteTasks } return false } type MemoPayload_Location struct { state protoimpl.MessageState `protogen:"open.v1"` Placeholder string `protobuf:"bytes,1,opt,name=placeholder,proto3" json:"placeholder,omitempty"` Latitude float64 `protobuf:"fixed64,2,opt,name=latitude,proto3" json:"latitude,omitempty"` Longitude float64 `protobuf:"fixed64,3,opt,name=longitude,proto3" json:"longitude,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *MemoPayload_Location) Reset() { *x = MemoPayload_Location{} mi := &file_store_memo_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *MemoPayload_Location) String() string { return protoimpl.X.MessageStringOf(x) } func (*MemoPayload_Location) ProtoMessage() {} func (x *MemoPayload_Location) ProtoReflect() protoreflect.Message { mi := &file_store_memo_proto_msgTypes[2] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use MemoPayload_Location.ProtoReflect.Descriptor instead. func (*MemoPayload_Location) Descriptor() ([]byte, []int) { return file_store_memo_proto_rawDescGZIP(), []int{0, 1} } func (x *MemoPayload_Location) GetPlaceholder() string { if x != nil { return x.Placeholder } return "" } func (x *MemoPayload_Location) GetLatitude() float64 { if x != nil { return x.Latitude } return 0 } func (x *MemoPayload_Location) GetLongitude() float64 { if x != nil { return x.Longitude } return 0 } var File_store_memo_proto protoreflect.FileDescriptor const file_store_memo_proto_rawDesc = "" + "\n" + "\x10store/memo.proto\x12\vmemos.store\"\xa0\x03\n" + "\vMemoPayload\x12=\n" + "\bproperty\x18\x01 \x01(\v2!.memos.store.MemoPayload.PropertyR\bproperty\x12=\n" + "\blocation\x18\x02 \x01(\v2!.memos.store.MemoPayload.LocationR\blocation\x12\x12\n" + "\x04tags\x18\x03 \x03(\tR\x04tags\x1a\x96\x01\n" + "\bProperty\x12\x19\n" + "\bhas_link\x18\x01 \x01(\bR\ahasLink\x12\"\n" + "\rhas_task_list\x18\x02 \x01(\bR\vhasTaskList\x12\x19\n" + "\bhas_code\x18\x03 \x01(\bR\ahasCode\x120\n" + "\x14has_incomplete_tasks\x18\x04 \x01(\bR\x12hasIncompleteTasks\x1af\n" + "\bLocation\x12 \n" + "\vplaceholder\x18\x01 \x01(\tR\vplaceholder\x12\x1a\n" + "\blatitude\x18\x02 \x01(\x01R\blatitude\x12\x1c\n" + "\tlongitude\x18\x03 \x01(\x01R\tlongitudeB\x94\x01\n" + "\x0fcom.memos.storeB\tMemoProtoP\x01Z)github.com/usememos/memos/proto/gen/store\xa2\x02\x03MSX\xaa\x02\vMemos.Store\xca\x02\vMemos\\Store\xe2\x02\x17Memos\\Store\\GPBMetadata\xea\x02\fMemos::Storeb\x06proto3" var ( file_store_memo_proto_rawDescOnce sync.Once file_store_memo_proto_rawDescData []byte ) func file_store_memo_proto_rawDescGZIP() []byte { file_store_memo_proto_rawDescOnce.Do(func() { file_store_memo_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_store_memo_proto_rawDesc), len(file_store_memo_proto_rawDesc))) }) return file_store_memo_proto_rawDescData } var file_store_memo_proto_msgTypes = make([]protoimpl.MessageInfo, 3) var file_store_memo_proto_goTypes = []any{ (*MemoPayload)(nil), // 0: memos.store.MemoPayload (*MemoPayload_Property)(nil), // 1: memos.store.MemoPayload.Property (*MemoPayload_Location)(nil), // 2: memos.store.MemoPayload.Location } var file_store_memo_proto_depIdxs = []int32{ 1, // 0: memos.store.MemoPayload.property:type_name -> memos.store.MemoPayload.Property 2, // 1: memos.store.MemoPayload.location:type_name -> memos.store.MemoPayload.Location 2, // [2:2] is the sub-list for method output_type 2, // [2:2] is the sub-list for method input_type 2, // [2:2] is the sub-list for extension type_name 2, // [2:2] is the sub-list for extension extendee 0, // [0:2] is the sub-list for field type_name } func init() { file_store_memo_proto_init() } func file_store_memo_proto_init() { if File_store_memo_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_store_memo_proto_rawDesc), len(file_store_memo_proto_rawDesc)), NumEnums: 0, NumMessages: 3, NumExtensions: 0, NumServices: 0, }, GoTypes: file_store_memo_proto_goTypes, DependencyIndexes: file_store_memo_proto_depIdxs, MessageInfos: file_store_memo_proto_msgTypes, }.Build() File_store_memo_proto = out.File file_store_memo_proto_goTypes = nil file_store_memo_proto_depIdxs = nil }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/proto/gen/store/attachment.pb.go
proto/gen/store/attachment.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.36.11 // protoc (unknown) // source: store/attachment.proto package store import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" timestamppb "google.golang.org/protobuf/types/known/timestamppb" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type AttachmentStorageType int32 const ( AttachmentStorageType_ATTACHMENT_STORAGE_TYPE_UNSPECIFIED AttachmentStorageType = 0 // Attachment is stored locally. AKA, local file system. AttachmentStorageType_LOCAL AttachmentStorageType = 1 // Attachment is stored in S3. AttachmentStorageType_S3 AttachmentStorageType = 2 // Attachment is stored in an external storage. The reference is a URL. AttachmentStorageType_EXTERNAL AttachmentStorageType = 3 ) // Enum value maps for AttachmentStorageType. var ( AttachmentStorageType_name = map[int32]string{ 0: "ATTACHMENT_STORAGE_TYPE_UNSPECIFIED", 1: "LOCAL", 2: "S3", 3: "EXTERNAL", } AttachmentStorageType_value = map[string]int32{ "ATTACHMENT_STORAGE_TYPE_UNSPECIFIED": 0, "LOCAL": 1, "S3": 2, "EXTERNAL": 3, } ) func (x AttachmentStorageType) Enum() *AttachmentStorageType { p := new(AttachmentStorageType) *p = x return p } func (x AttachmentStorageType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (AttachmentStorageType) Descriptor() protoreflect.EnumDescriptor { return file_store_attachment_proto_enumTypes[0].Descriptor() } func (AttachmentStorageType) Type() protoreflect.EnumType { return &file_store_attachment_proto_enumTypes[0] } func (x AttachmentStorageType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use AttachmentStorageType.Descriptor instead. func (AttachmentStorageType) EnumDescriptor() ([]byte, []int) { return file_store_attachment_proto_rawDescGZIP(), []int{0} } type AttachmentPayload struct { state protoimpl.MessageState `protogen:"open.v1"` // Types that are valid to be assigned to Payload: // // *AttachmentPayload_S3Object_ Payload isAttachmentPayload_Payload `protobuf_oneof:"payload"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *AttachmentPayload) Reset() { *x = AttachmentPayload{} mi := &file_store_attachment_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *AttachmentPayload) String() string { return protoimpl.X.MessageStringOf(x) } func (*AttachmentPayload) ProtoMessage() {} func (x *AttachmentPayload) ProtoReflect() protoreflect.Message { mi := &file_store_attachment_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AttachmentPayload.ProtoReflect.Descriptor instead. func (*AttachmentPayload) Descriptor() ([]byte, []int) { return file_store_attachment_proto_rawDescGZIP(), []int{0} } func (x *AttachmentPayload) GetPayload() isAttachmentPayload_Payload { if x != nil { return x.Payload } return nil } func (x *AttachmentPayload) GetS3Object() *AttachmentPayload_S3Object { if x != nil { if x, ok := x.Payload.(*AttachmentPayload_S3Object_); ok { return x.S3Object } } return nil } type isAttachmentPayload_Payload interface { isAttachmentPayload_Payload() } type AttachmentPayload_S3Object_ struct { S3Object *AttachmentPayload_S3Object `protobuf:"bytes,1,opt,name=s3_object,json=s3Object,proto3,oneof"` } func (*AttachmentPayload_S3Object_) isAttachmentPayload_Payload() {} type AttachmentPayload_S3Object struct { state protoimpl.MessageState `protogen:"open.v1"` S3Config *StorageS3Config `protobuf:"bytes,1,opt,name=s3_config,json=s3Config,proto3" json:"s3_config,omitempty"` // key is the S3 object key. Key string `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"` // last_presigned_time is the last time the object was presigned. // This is used to determine if the presigned URL is still valid. LastPresignedTime *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=last_presigned_time,json=lastPresignedTime,proto3" json:"last_presigned_time,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *AttachmentPayload_S3Object) Reset() { *x = AttachmentPayload_S3Object{} mi := &file_store_attachment_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *AttachmentPayload_S3Object) String() string { return protoimpl.X.MessageStringOf(x) } func (*AttachmentPayload_S3Object) ProtoMessage() {} func (x *AttachmentPayload_S3Object) ProtoReflect() protoreflect.Message { mi := &file_store_attachment_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use AttachmentPayload_S3Object.ProtoReflect.Descriptor instead. func (*AttachmentPayload_S3Object) Descriptor() ([]byte, []int) { return file_store_attachment_proto_rawDescGZIP(), []int{0, 0} } func (x *AttachmentPayload_S3Object) GetS3Config() *StorageS3Config { if x != nil { return x.S3Config } return nil } func (x *AttachmentPayload_S3Object) GetKey() string { if x != nil { return x.Key } return "" } func (x *AttachmentPayload_S3Object) GetLastPresignedTime() *timestamppb.Timestamp { if x != nil { return x.LastPresignedTime } return nil } var File_store_attachment_proto protoreflect.FileDescriptor const file_store_attachment_proto_rawDesc = "" + "\n" + "\x16store/attachment.proto\x12\vmemos.store\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1cstore/instance_setting.proto\"\x8c\x02\n" + "\x11AttachmentPayload\x12F\n" + "\ts3_object\x18\x01 \x01(\v2'.memos.store.AttachmentPayload.S3ObjectH\x00R\bs3Object\x1a\xa3\x01\n" + "\bS3Object\x129\n" + "\ts3_config\x18\x01 \x01(\v2\x1c.memos.store.StorageS3ConfigR\bs3Config\x12\x10\n" + "\x03key\x18\x02 \x01(\tR\x03key\x12J\n" + "\x13last_presigned_time\x18\x03 \x01(\v2\x1a.google.protobuf.TimestampR\x11lastPresignedTimeB\t\n" + "\apayload*a\n" + "\x15AttachmentStorageType\x12'\n" + "#ATTACHMENT_STORAGE_TYPE_UNSPECIFIED\x10\x00\x12\t\n" + "\x05LOCAL\x10\x01\x12\x06\n" + "\x02S3\x10\x02\x12\f\n" + "\bEXTERNAL\x10\x03B\x9a\x01\n" + "\x0fcom.memos.storeB\x0fAttachmentProtoP\x01Z)github.com/usememos/memos/proto/gen/store\xa2\x02\x03MSX\xaa\x02\vMemos.Store\xca\x02\vMemos\\Store\xe2\x02\x17Memos\\Store\\GPBMetadata\xea\x02\fMemos::Storeb\x06proto3" var ( file_store_attachment_proto_rawDescOnce sync.Once file_store_attachment_proto_rawDescData []byte ) func file_store_attachment_proto_rawDescGZIP() []byte { file_store_attachment_proto_rawDescOnce.Do(func() { file_store_attachment_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_store_attachment_proto_rawDesc), len(file_store_attachment_proto_rawDesc))) }) return file_store_attachment_proto_rawDescData } var file_store_attachment_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_store_attachment_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_store_attachment_proto_goTypes = []any{ (AttachmentStorageType)(0), // 0: memos.store.AttachmentStorageType (*AttachmentPayload)(nil), // 1: memos.store.AttachmentPayload (*AttachmentPayload_S3Object)(nil), // 2: memos.store.AttachmentPayload.S3Object (*StorageS3Config)(nil), // 3: memos.store.StorageS3Config (*timestamppb.Timestamp)(nil), // 4: google.protobuf.Timestamp } var file_store_attachment_proto_depIdxs = []int32{ 2, // 0: memos.store.AttachmentPayload.s3_object:type_name -> memos.store.AttachmentPayload.S3Object 3, // 1: memos.store.AttachmentPayload.S3Object.s3_config:type_name -> memos.store.StorageS3Config 4, // 2: memos.store.AttachmentPayload.S3Object.last_presigned_time:type_name -> google.protobuf.Timestamp 3, // [3:3] is the sub-list for method output_type 3, // [3:3] is the sub-list for method input_type 3, // [3:3] is the sub-list for extension type_name 3, // [3:3] is the sub-list for extension extendee 0, // [0:3] is the sub-list for field type_name } func init() { file_store_attachment_proto_init() } func file_store_attachment_proto_init() { if File_store_attachment_proto != nil { return } file_store_instance_setting_proto_init() file_store_attachment_proto_msgTypes[0].OneofWrappers = []any{ (*AttachmentPayload_S3Object_)(nil), } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_store_attachment_proto_rawDesc), len(file_store_attachment_proto_rawDesc)), NumEnums: 1, NumMessages: 2, NumExtensions: 0, NumServices: 0, }, GoTypes: file_store_attachment_proto_goTypes, DependencyIndexes: file_store_attachment_proto_depIdxs, EnumInfos: file_store_attachment_proto_enumTypes, MessageInfos: file_store_attachment_proto_msgTypes, }.Build() File_store_attachment_proto = out.File file_store_attachment_proto_goTypes = nil file_store_attachment_proto_depIdxs = nil }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/proto/gen/store/idp.pb.go
proto/gen/store/idp.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.36.11 // protoc (unknown) // source: store/idp.proto package store import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type IdentityProvider_Type int32 const ( IdentityProvider_TYPE_UNSPECIFIED IdentityProvider_Type = 0 IdentityProvider_OAUTH2 IdentityProvider_Type = 1 ) // Enum value maps for IdentityProvider_Type. var ( IdentityProvider_Type_name = map[int32]string{ 0: "TYPE_UNSPECIFIED", 1: "OAUTH2", } IdentityProvider_Type_value = map[string]int32{ "TYPE_UNSPECIFIED": 0, "OAUTH2": 1, } ) func (x IdentityProvider_Type) Enum() *IdentityProvider_Type { p := new(IdentityProvider_Type) *p = x return p } func (x IdentityProvider_Type) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (IdentityProvider_Type) Descriptor() protoreflect.EnumDescriptor { return file_store_idp_proto_enumTypes[0].Descriptor() } func (IdentityProvider_Type) Type() protoreflect.EnumType { return &file_store_idp_proto_enumTypes[0] } func (x IdentityProvider_Type) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use IdentityProvider_Type.Descriptor instead. func (IdentityProvider_Type) EnumDescriptor() ([]byte, []int) { return file_store_idp_proto_rawDescGZIP(), []int{0, 0} } type IdentityProvider struct { state protoimpl.MessageState `protogen:"open.v1"` Id int32 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` Type IdentityProvider_Type `protobuf:"varint,3,opt,name=type,proto3,enum=memos.store.IdentityProvider_Type" json:"type,omitempty"` IdentifierFilter string `protobuf:"bytes,4,opt,name=identifier_filter,json=identifierFilter,proto3" json:"identifier_filter,omitempty"` Config *IdentityProviderConfig `protobuf:"bytes,5,opt,name=config,proto3" json:"config,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *IdentityProvider) Reset() { *x = IdentityProvider{} mi := &file_store_idp_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *IdentityProvider) String() string { return protoimpl.X.MessageStringOf(x) } func (*IdentityProvider) ProtoMessage() {} func (x *IdentityProvider) ProtoReflect() protoreflect.Message { mi := &file_store_idp_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use IdentityProvider.ProtoReflect.Descriptor instead. func (*IdentityProvider) Descriptor() ([]byte, []int) { return file_store_idp_proto_rawDescGZIP(), []int{0} } func (x *IdentityProvider) GetId() int32 { if x != nil { return x.Id } return 0 } func (x *IdentityProvider) GetName() string { if x != nil { return x.Name } return "" } func (x *IdentityProvider) GetType() IdentityProvider_Type { if x != nil { return x.Type } return IdentityProvider_TYPE_UNSPECIFIED } func (x *IdentityProvider) GetIdentifierFilter() string { if x != nil { return x.IdentifierFilter } return "" } func (x *IdentityProvider) GetConfig() *IdentityProviderConfig { if x != nil { return x.Config } return nil } type IdentityProviderConfig struct { state protoimpl.MessageState `protogen:"open.v1"` // Types that are valid to be assigned to Config: // // *IdentityProviderConfig_Oauth2Config Config isIdentityProviderConfig_Config `protobuf_oneof:"config"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *IdentityProviderConfig) Reset() { *x = IdentityProviderConfig{} mi := &file_store_idp_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *IdentityProviderConfig) String() string { return protoimpl.X.MessageStringOf(x) } func (*IdentityProviderConfig) ProtoMessage() {} func (x *IdentityProviderConfig) ProtoReflect() protoreflect.Message { mi := &file_store_idp_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use IdentityProviderConfig.ProtoReflect.Descriptor instead. func (*IdentityProviderConfig) Descriptor() ([]byte, []int) { return file_store_idp_proto_rawDescGZIP(), []int{1} } func (x *IdentityProviderConfig) GetConfig() isIdentityProviderConfig_Config { if x != nil { return x.Config } return nil } func (x *IdentityProviderConfig) GetOauth2Config() *OAuth2Config { if x != nil { if x, ok := x.Config.(*IdentityProviderConfig_Oauth2Config); ok { return x.Oauth2Config } } return nil } type isIdentityProviderConfig_Config interface { isIdentityProviderConfig_Config() } type IdentityProviderConfig_Oauth2Config struct { Oauth2Config *OAuth2Config `protobuf:"bytes,1,opt,name=oauth2_config,json=oauth2Config,proto3,oneof"` } func (*IdentityProviderConfig_Oauth2Config) isIdentityProviderConfig_Config() {} type FieldMapping struct { state protoimpl.MessageState `protogen:"open.v1"` Identifier string `protobuf:"bytes,1,opt,name=identifier,proto3" json:"identifier,omitempty"` DisplayName string `protobuf:"bytes,2,opt,name=display_name,json=displayName,proto3" json:"display_name,omitempty"` Email string `protobuf:"bytes,3,opt,name=email,proto3" json:"email,omitempty"` AvatarUrl string `protobuf:"bytes,4,opt,name=avatar_url,json=avatarUrl,proto3" json:"avatar_url,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *FieldMapping) Reset() { *x = FieldMapping{} mi := &file_store_idp_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *FieldMapping) String() string { return protoimpl.X.MessageStringOf(x) } func (*FieldMapping) ProtoMessage() {} func (x *FieldMapping) ProtoReflect() protoreflect.Message { mi := &file_store_idp_proto_msgTypes[2] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use FieldMapping.ProtoReflect.Descriptor instead. func (*FieldMapping) Descriptor() ([]byte, []int) { return file_store_idp_proto_rawDescGZIP(), []int{2} } func (x *FieldMapping) GetIdentifier() string { if x != nil { return x.Identifier } return "" } func (x *FieldMapping) GetDisplayName() string { if x != nil { return x.DisplayName } return "" } func (x *FieldMapping) GetEmail() string { if x != nil { return x.Email } return "" } func (x *FieldMapping) GetAvatarUrl() string { if x != nil { return x.AvatarUrl } return "" } type OAuth2Config struct { state protoimpl.MessageState `protogen:"open.v1"` ClientId string `protobuf:"bytes,1,opt,name=client_id,json=clientId,proto3" json:"client_id,omitempty"` ClientSecret string `protobuf:"bytes,2,opt,name=client_secret,json=clientSecret,proto3" json:"client_secret,omitempty"` AuthUrl string `protobuf:"bytes,3,opt,name=auth_url,json=authUrl,proto3" json:"auth_url,omitempty"` TokenUrl string `protobuf:"bytes,4,opt,name=token_url,json=tokenUrl,proto3" json:"token_url,omitempty"` UserInfoUrl string `protobuf:"bytes,5,opt,name=user_info_url,json=userInfoUrl,proto3" json:"user_info_url,omitempty"` Scopes []string `protobuf:"bytes,6,rep,name=scopes,proto3" json:"scopes,omitempty"` FieldMapping *FieldMapping `protobuf:"bytes,7,opt,name=field_mapping,json=fieldMapping,proto3" json:"field_mapping,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *OAuth2Config) Reset() { *x = OAuth2Config{} mi := &file_store_idp_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *OAuth2Config) String() string { return protoimpl.X.MessageStringOf(x) } func (*OAuth2Config) ProtoMessage() {} func (x *OAuth2Config) ProtoReflect() protoreflect.Message { mi := &file_store_idp_proto_msgTypes[3] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use OAuth2Config.ProtoReflect.Descriptor instead. func (*OAuth2Config) Descriptor() ([]byte, []int) { return file_store_idp_proto_rawDescGZIP(), []int{3} } func (x *OAuth2Config) GetClientId() string { if x != nil { return x.ClientId } return "" } func (x *OAuth2Config) GetClientSecret() string { if x != nil { return x.ClientSecret } return "" } func (x *OAuth2Config) GetAuthUrl() string { if x != nil { return x.AuthUrl } return "" } func (x *OAuth2Config) GetTokenUrl() string { if x != nil { return x.TokenUrl } return "" } func (x *OAuth2Config) GetUserInfoUrl() string { if x != nil { return x.UserInfoUrl } return "" } func (x *OAuth2Config) GetScopes() []string { if x != nil { return x.Scopes } return nil } func (x *OAuth2Config) GetFieldMapping() *FieldMapping { if x != nil { return x.FieldMapping } return nil } var File_store_idp_proto protoreflect.FileDescriptor const file_store_idp_proto_rawDesc = "" + "\n" + "\x0fstore/idp.proto\x12\vmemos.store\"\x82\x02\n" + "\x10IdentityProvider\x12\x0e\n" + "\x02id\x18\x01 \x01(\x05R\x02id\x12\x12\n" + "\x04name\x18\x02 \x01(\tR\x04name\x126\n" + "\x04type\x18\x03 \x01(\x0e2\".memos.store.IdentityProvider.TypeR\x04type\x12+\n" + "\x11identifier_filter\x18\x04 \x01(\tR\x10identifierFilter\x12;\n" + "\x06config\x18\x05 \x01(\v2#.memos.store.IdentityProviderConfigR\x06config\"(\n" + "\x04Type\x12\x14\n" + "\x10TYPE_UNSPECIFIED\x10\x00\x12\n" + "\n" + "\x06OAUTH2\x10\x01\"d\n" + "\x16IdentityProviderConfig\x12@\n" + "\roauth2_config\x18\x01 \x01(\v2\x19.memos.store.OAuth2ConfigH\x00R\foauth2ConfigB\b\n" + "\x06config\"\x86\x01\n" + "\fFieldMapping\x12\x1e\n" + "\n" + "identifier\x18\x01 \x01(\tR\n" + "identifier\x12!\n" + "\fdisplay_name\x18\x02 \x01(\tR\vdisplayName\x12\x14\n" + "\x05email\x18\x03 \x01(\tR\x05email\x12\x1d\n" + "\n" + "avatar_url\x18\x04 \x01(\tR\tavatarUrl\"\x84\x02\n" + "\fOAuth2Config\x12\x1b\n" + "\tclient_id\x18\x01 \x01(\tR\bclientId\x12#\n" + "\rclient_secret\x18\x02 \x01(\tR\fclientSecret\x12\x19\n" + "\bauth_url\x18\x03 \x01(\tR\aauthUrl\x12\x1b\n" + "\ttoken_url\x18\x04 \x01(\tR\btokenUrl\x12\"\n" + "\ruser_info_url\x18\x05 \x01(\tR\vuserInfoUrl\x12\x16\n" + "\x06scopes\x18\x06 \x03(\tR\x06scopes\x12>\n" + "\rfield_mapping\x18\a \x01(\v2\x19.memos.store.FieldMappingR\ffieldMappingB\x93\x01\n" + "\x0fcom.memos.storeB\bIdpProtoP\x01Z)github.com/usememos/memos/proto/gen/store\xa2\x02\x03MSX\xaa\x02\vMemos.Store\xca\x02\vMemos\\Store\xe2\x02\x17Memos\\Store\\GPBMetadata\xea\x02\fMemos::Storeb\x06proto3" var ( file_store_idp_proto_rawDescOnce sync.Once file_store_idp_proto_rawDescData []byte ) func file_store_idp_proto_rawDescGZIP() []byte { file_store_idp_proto_rawDescOnce.Do(func() { file_store_idp_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_store_idp_proto_rawDesc), len(file_store_idp_proto_rawDesc))) }) return file_store_idp_proto_rawDescData } var file_store_idp_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_store_idp_proto_msgTypes = make([]protoimpl.MessageInfo, 4) var file_store_idp_proto_goTypes = []any{ (IdentityProvider_Type)(0), // 0: memos.store.IdentityProvider.Type (*IdentityProvider)(nil), // 1: memos.store.IdentityProvider (*IdentityProviderConfig)(nil), // 2: memos.store.IdentityProviderConfig (*FieldMapping)(nil), // 3: memos.store.FieldMapping (*OAuth2Config)(nil), // 4: memos.store.OAuth2Config } var file_store_idp_proto_depIdxs = []int32{ 0, // 0: memos.store.IdentityProvider.type:type_name -> memos.store.IdentityProvider.Type 2, // 1: memos.store.IdentityProvider.config:type_name -> memos.store.IdentityProviderConfig 4, // 2: memos.store.IdentityProviderConfig.oauth2_config:type_name -> memos.store.OAuth2Config 3, // 3: memos.store.OAuth2Config.field_mapping:type_name -> memos.store.FieldMapping 4, // [4:4] is the sub-list for method output_type 4, // [4:4] is the sub-list for method input_type 4, // [4:4] is the sub-list for extension type_name 4, // [4:4] is the sub-list for extension extendee 0, // [0:4] is the sub-list for field type_name } func init() { file_store_idp_proto_init() } func file_store_idp_proto_init() { if File_store_idp_proto != nil { return } file_store_idp_proto_msgTypes[1].OneofWrappers = []any{ (*IdentityProviderConfig_Oauth2Config)(nil), } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_store_idp_proto_rawDesc), len(file_store_idp_proto_rawDesc)), NumEnums: 1, NumMessages: 4, NumExtensions: 0, NumServices: 0, }, GoTypes: file_store_idp_proto_goTypes, DependencyIndexes: file_store_idp_proto_depIdxs, EnumInfos: file_store_idp_proto_enumTypes, MessageInfos: file_store_idp_proto_msgTypes, }.Build() File_store_idp_proto = out.File file_store_idp_proto_goTypes = nil file_store_idp_proto_depIdxs = nil }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/proto/gen/store/user_setting.pb.go
proto/gen/store/user_setting.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.36.11 // protoc (unknown) // source: store/user_setting.proto package store import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" timestamppb "google.golang.org/protobuf/types/known/timestamppb" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type UserSetting_Key int32 const ( UserSetting_KEY_UNSPECIFIED UserSetting_Key = 0 // General user settings. UserSetting_GENERAL UserSetting_Key = 1 // The shortcuts of the user. UserSetting_SHORTCUTS UserSetting_Key = 4 // The webhooks of the user. UserSetting_WEBHOOKS UserSetting_Key = 5 // Refresh tokens for the user. UserSetting_REFRESH_TOKENS UserSetting_Key = 6 // Personal access tokens for the user. UserSetting_PERSONAL_ACCESS_TOKENS UserSetting_Key = 7 ) // Enum value maps for UserSetting_Key. var ( UserSetting_Key_name = map[int32]string{ 0: "KEY_UNSPECIFIED", 1: "GENERAL", 4: "SHORTCUTS", 5: "WEBHOOKS", 6: "REFRESH_TOKENS", 7: "PERSONAL_ACCESS_TOKENS", } UserSetting_Key_value = map[string]int32{ "KEY_UNSPECIFIED": 0, "GENERAL": 1, "SHORTCUTS": 4, "WEBHOOKS": 5, "REFRESH_TOKENS": 6, "PERSONAL_ACCESS_TOKENS": 7, } ) func (x UserSetting_Key) Enum() *UserSetting_Key { p := new(UserSetting_Key) *p = x return p } func (x UserSetting_Key) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (UserSetting_Key) Descriptor() protoreflect.EnumDescriptor { return file_store_user_setting_proto_enumTypes[0].Descriptor() } func (UserSetting_Key) Type() protoreflect.EnumType { return &file_store_user_setting_proto_enumTypes[0] } func (x UserSetting_Key) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use UserSetting_Key.Descriptor instead. func (UserSetting_Key) EnumDescriptor() ([]byte, []int) { return file_store_user_setting_proto_rawDescGZIP(), []int{0, 0} } type UserSetting struct { state protoimpl.MessageState `protogen:"open.v1"` UserId int32 `protobuf:"varint,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"` Key UserSetting_Key `protobuf:"varint,2,opt,name=key,proto3,enum=memos.store.UserSetting_Key" json:"key,omitempty"` // Types that are valid to be assigned to Value: // // *UserSetting_General // *UserSetting_Shortcuts // *UserSetting_Webhooks // *UserSetting_RefreshTokens // *UserSetting_PersonalAccessTokens Value isUserSetting_Value `protobuf_oneof:"value"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *UserSetting) Reset() { *x = UserSetting{} mi := &file_store_user_setting_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *UserSetting) String() string { return protoimpl.X.MessageStringOf(x) } func (*UserSetting) ProtoMessage() {} func (x *UserSetting) ProtoReflect() protoreflect.Message { mi := &file_store_user_setting_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use UserSetting.ProtoReflect.Descriptor instead. func (*UserSetting) Descriptor() ([]byte, []int) { return file_store_user_setting_proto_rawDescGZIP(), []int{0} } func (x *UserSetting) GetUserId() int32 { if x != nil { return x.UserId } return 0 } func (x *UserSetting) GetKey() UserSetting_Key { if x != nil { return x.Key } return UserSetting_KEY_UNSPECIFIED } func (x *UserSetting) GetValue() isUserSetting_Value { if x != nil { return x.Value } return nil } func (x *UserSetting) GetGeneral() *GeneralUserSetting { if x != nil { if x, ok := x.Value.(*UserSetting_General); ok { return x.General } } return nil } func (x *UserSetting) GetShortcuts() *ShortcutsUserSetting { if x != nil { if x, ok := x.Value.(*UserSetting_Shortcuts); ok { return x.Shortcuts } } return nil } func (x *UserSetting) GetWebhooks() *WebhooksUserSetting { if x != nil { if x, ok := x.Value.(*UserSetting_Webhooks); ok { return x.Webhooks } } return nil } func (x *UserSetting) GetRefreshTokens() *RefreshTokensUserSetting { if x != nil { if x, ok := x.Value.(*UserSetting_RefreshTokens); ok { return x.RefreshTokens } } return nil } func (x *UserSetting) GetPersonalAccessTokens() *PersonalAccessTokensUserSetting { if x != nil { if x, ok := x.Value.(*UserSetting_PersonalAccessTokens); ok { return x.PersonalAccessTokens } } return nil } type isUserSetting_Value interface { isUserSetting_Value() } type UserSetting_General struct { General *GeneralUserSetting `protobuf:"bytes,3,opt,name=general,proto3,oneof"` } type UserSetting_Shortcuts struct { Shortcuts *ShortcutsUserSetting `protobuf:"bytes,6,opt,name=shortcuts,proto3,oneof"` } type UserSetting_Webhooks struct { Webhooks *WebhooksUserSetting `protobuf:"bytes,7,opt,name=webhooks,proto3,oneof"` } type UserSetting_RefreshTokens struct { RefreshTokens *RefreshTokensUserSetting `protobuf:"bytes,8,opt,name=refresh_tokens,json=refreshTokens,proto3,oneof"` } type UserSetting_PersonalAccessTokens struct { PersonalAccessTokens *PersonalAccessTokensUserSetting `protobuf:"bytes,9,opt,name=personal_access_tokens,json=personalAccessTokens,proto3,oneof"` } func (*UserSetting_General) isUserSetting_Value() {} func (*UserSetting_Shortcuts) isUserSetting_Value() {} func (*UserSetting_Webhooks) isUserSetting_Value() {} func (*UserSetting_RefreshTokens) isUserSetting_Value() {} func (*UserSetting_PersonalAccessTokens) isUserSetting_Value() {} type GeneralUserSetting struct { state protoimpl.MessageState `protogen:"open.v1"` // The user's locale. Locale string `protobuf:"bytes,1,opt,name=locale,proto3" json:"locale,omitempty"` // The user's memo visibility setting. MemoVisibility string `protobuf:"bytes,2,opt,name=memo_visibility,json=memoVisibility,proto3" json:"memo_visibility,omitempty"` // The user's theme preference. // This references a CSS file in the web/public/themes/ directory. Theme string `protobuf:"bytes,3,opt,name=theme,proto3" json:"theme,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GeneralUserSetting) Reset() { *x = GeneralUserSetting{} mi := &file_store_user_setting_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GeneralUserSetting) String() string { return protoimpl.X.MessageStringOf(x) } func (*GeneralUserSetting) ProtoMessage() {} func (x *GeneralUserSetting) ProtoReflect() protoreflect.Message { mi := &file_store_user_setting_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GeneralUserSetting.ProtoReflect.Descriptor instead. func (*GeneralUserSetting) Descriptor() ([]byte, []int) { return file_store_user_setting_proto_rawDescGZIP(), []int{1} } func (x *GeneralUserSetting) GetLocale() string { if x != nil { return x.Locale } return "" } func (x *GeneralUserSetting) GetMemoVisibility() string { if x != nil { return x.MemoVisibility } return "" } func (x *GeneralUserSetting) GetTheme() string { if x != nil { return x.Theme } return "" } type RefreshTokensUserSetting struct { state protoimpl.MessageState `protogen:"open.v1"` RefreshTokens []*RefreshTokensUserSetting_RefreshToken `protobuf:"bytes,1,rep,name=refresh_tokens,json=refreshTokens,proto3" json:"refresh_tokens,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *RefreshTokensUserSetting) Reset() { *x = RefreshTokensUserSetting{} mi := &file_store_user_setting_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *RefreshTokensUserSetting) String() string { return protoimpl.X.MessageStringOf(x) } func (*RefreshTokensUserSetting) ProtoMessage() {} func (x *RefreshTokensUserSetting) ProtoReflect() protoreflect.Message { mi := &file_store_user_setting_proto_msgTypes[2] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RefreshTokensUserSetting.ProtoReflect.Descriptor instead. func (*RefreshTokensUserSetting) Descriptor() ([]byte, []int) { return file_store_user_setting_proto_rawDescGZIP(), []int{2} } func (x *RefreshTokensUserSetting) GetRefreshTokens() []*RefreshTokensUserSetting_RefreshToken { if x != nil { return x.RefreshTokens } return nil } type PersonalAccessTokensUserSetting struct { state protoimpl.MessageState `protogen:"open.v1"` Tokens []*PersonalAccessTokensUserSetting_PersonalAccessToken `protobuf:"bytes,1,rep,name=tokens,proto3" json:"tokens,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *PersonalAccessTokensUserSetting) Reset() { *x = PersonalAccessTokensUserSetting{} mi := &file_store_user_setting_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *PersonalAccessTokensUserSetting) String() string { return protoimpl.X.MessageStringOf(x) } func (*PersonalAccessTokensUserSetting) ProtoMessage() {} func (x *PersonalAccessTokensUserSetting) ProtoReflect() protoreflect.Message { mi := &file_store_user_setting_proto_msgTypes[3] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PersonalAccessTokensUserSetting.ProtoReflect.Descriptor instead. func (*PersonalAccessTokensUserSetting) Descriptor() ([]byte, []int) { return file_store_user_setting_proto_rawDescGZIP(), []int{3} } func (x *PersonalAccessTokensUserSetting) GetTokens() []*PersonalAccessTokensUserSetting_PersonalAccessToken { if x != nil { return x.Tokens } return nil } type ShortcutsUserSetting struct { state protoimpl.MessageState `protogen:"open.v1"` Shortcuts []*ShortcutsUserSetting_Shortcut `protobuf:"bytes,1,rep,name=shortcuts,proto3" json:"shortcuts,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ShortcutsUserSetting) Reset() { *x = ShortcutsUserSetting{} mi := &file_store_user_setting_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *ShortcutsUserSetting) String() string { return protoimpl.X.MessageStringOf(x) } func (*ShortcutsUserSetting) ProtoMessage() {} func (x *ShortcutsUserSetting) ProtoReflect() protoreflect.Message { mi := &file_store_user_setting_proto_msgTypes[4] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ShortcutsUserSetting.ProtoReflect.Descriptor instead. func (*ShortcutsUserSetting) Descriptor() ([]byte, []int) { return file_store_user_setting_proto_rawDescGZIP(), []int{4} } func (x *ShortcutsUserSetting) GetShortcuts() []*ShortcutsUserSetting_Shortcut { if x != nil { return x.Shortcuts } return nil } type WebhooksUserSetting struct { state protoimpl.MessageState `protogen:"open.v1"` Webhooks []*WebhooksUserSetting_Webhook `protobuf:"bytes,1,rep,name=webhooks,proto3" json:"webhooks,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *WebhooksUserSetting) Reset() { *x = WebhooksUserSetting{} mi := &file_store_user_setting_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *WebhooksUserSetting) String() string { return protoimpl.X.MessageStringOf(x) } func (*WebhooksUserSetting) ProtoMessage() {} func (x *WebhooksUserSetting) ProtoReflect() protoreflect.Message { mi := &file_store_user_setting_proto_msgTypes[5] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use WebhooksUserSetting.ProtoReflect.Descriptor instead. func (*WebhooksUserSetting) Descriptor() ([]byte, []int) { return file_store_user_setting_proto_rawDescGZIP(), []int{5} } func (x *WebhooksUserSetting) GetWebhooks() []*WebhooksUserSetting_Webhook { if x != nil { return x.Webhooks } return nil } type RefreshTokensUserSetting_RefreshToken struct { state protoimpl.MessageState `protogen:"open.v1"` // Unique identifier (matches 'tid' claim in JWT) TokenId string `protobuf:"bytes,1,opt,name=token_id,json=tokenId,proto3" json:"token_id,omitempty"` // When the token expires ExpiresAt *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=expires_at,json=expiresAt,proto3" json:"expires_at,omitempty"` // When the token was created CreatedAt *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=created_at,json=createdAt,proto3" json:"created_at,omitempty"` // Client information for session management UI ClientInfo *RefreshTokensUserSetting_ClientInfo `protobuf:"bytes,4,opt,name=client_info,json=clientInfo,proto3" json:"client_info,omitempty"` // Optional description Description string `protobuf:"bytes,5,opt,name=description,proto3" json:"description,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *RefreshTokensUserSetting_RefreshToken) Reset() { *x = RefreshTokensUserSetting_RefreshToken{} mi := &file_store_user_setting_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *RefreshTokensUserSetting_RefreshToken) String() string { return protoimpl.X.MessageStringOf(x) } func (*RefreshTokensUserSetting_RefreshToken) ProtoMessage() {} func (x *RefreshTokensUserSetting_RefreshToken) ProtoReflect() protoreflect.Message { mi := &file_store_user_setting_proto_msgTypes[6] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RefreshTokensUserSetting_RefreshToken.ProtoReflect.Descriptor instead. func (*RefreshTokensUserSetting_RefreshToken) Descriptor() ([]byte, []int) { return file_store_user_setting_proto_rawDescGZIP(), []int{2, 0} } func (x *RefreshTokensUserSetting_RefreshToken) GetTokenId() string { if x != nil { return x.TokenId } return "" } func (x *RefreshTokensUserSetting_RefreshToken) GetExpiresAt() *timestamppb.Timestamp { if x != nil { return x.ExpiresAt } return nil } func (x *RefreshTokensUserSetting_RefreshToken) GetCreatedAt() *timestamppb.Timestamp { if x != nil { return x.CreatedAt } return nil } func (x *RefreshTokensUserSetting_RefreshToken) GetClientInfo() *RefreshTokensUserSetting_ClientInfo { if x != nil { return x.ClientInfo } return nil } func (x *RefreshTokensUserSetting_RefreshToken) GetDescription() string { if x != nil { return x.Description } return "" } type RefreshTokensUserSetting_ClientInfo struct { state protoimpl.MessageState `protogen:"open.v1"` // User agent string of the client. UserAgent string `protobuf:"bytes,1,opt,name=user_agent,json=userAgent,proto3" json:"user_agent,omitempty"` // IP address of the client. IpAddress string `protobuf:"bytes,2,opt,name=ip_address,json=ipAddress,proto3" json:"ip_address,omitempty"` // Optional. Device type (e.g., "mobile", "desktop", "tablet"). DeviceType string `protobuf:"bytes,3,opt,name=device_type,json=deviceType,proto3" json:"device_type,omitempty"` // Optional. Operating system (e.g., "iOS 17.0", "Windows 11"). Os string `protobuf:"bytes,4,opt,name=os,proto3" json:"os,omitempty"` // Optional. Browser name and version (e.g., "Chrome 119.0"). Browser string `protobuf:"bytes,5,opt,name=browser,proto3" json:"browser,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *RefreshTokensUserSetting_ClientInfo) Reset() { *x = RefreshTokensUserSetting_ClientInfo{} mi := &file_store_user_setting_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *RefreshTokensUserSetting_ClientInfo) String() string { return protoimpl.X.MessageStringOf(x) } func (*RefreshTokensUserSetting_ClientInfo) ProtoMessage() {} func (x *RefreshTokensUserSetting_ClientInfo) ProtoReflect() protoreflect.Message { mi := &file_store_user_setting_proto_msgTypes[7] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use RefreshTokensUserSetting_ClientInfo.ProtoReflect.Descriptor instead. func (*RefreshTokensUserSetting_ClientInfo) Descriptor() ([]byte, []int) { return file_store_user_setting_proto_rawDescGZIP(), []int{2, 1} } func (x *RefreshTokensUserSetting_ClientInfo) GetUserAgent() string { if x != nil { return x.UserAgent } return "" } func (x *RefreshTokensUserSetting_ClientInfo) GetIpAddress() string { if x != nil { return x.IpAddress } return "" } func (x *RefreshTokensUserSetting_ClientInfo) GetDeviceType() string { if x != nil { return x.DeviceType } return "" } func (x *RefreshTokensUserSetting_ClientInfo) GetOs() string { if x != nil { return x.Os } return "" } func (x *RefreshTokensUserSetting_ClientInfo) GetBrowser() string { if x != nil { return x.Browser } return "" } type PersonalAccessTokensUserSetting_PersonalAccessToken struct { state protoimpl.MessageState `protogen:"open.v1"` // Unique identifier for this token TokenId string `protobuf:"bytes,1,opt,name=token_id,json=tokenId,proto3" json:"token_id,omitempty"` // SHA-256 hash of the actual token TokenHash string `protobuf:"bytes,2,opt,name=token_hash,json=tokenHash,proto3" json:"token_hash,omitempty"` // User-provided description Description string `protobuf:"bytes,3,opt,name=description,proto3" json:"description,omitempty"` // When the token expires (null = never) ExpiresAt *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=expires_at,json=expiresAt,proto3" json:"expires_at,omitempty"` // When the token was created CreatedAt *timestamppb.Timestamp `protobuf:"bytes,5,opt,name=created_at,json=createdAt,proto3" json:"created_at,omitempty"` // When the token was last used LastUsedAt *timestamppb.Timestamp `protobuf:"bytes,6,opt,name=last_used_at,json=lastUsedAt,proto3" json:"last_used_at,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *PersonalAccessTokensUserSetting_PersonalAccessToken) Reset() { *x = PersonalAccessTokensUserSetting_PersonalAccessToken{} mi := &file_store_user_setting_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *PersonalAccessTokensUserSetting_PersonalAccessToken) String() string { return protoimpl.X.MessageStringOf(x) } func (*PersonalAccessTokensUserSetting_PersonalAccessToken) ProtoMessage() {} func (x *PersonalAccessTokensUserSetting_PersonalAccessToken) ProtoReflect() protoreflect.Message { mi := &file_store_user_setting_proto_msgTypes[8] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use PersonalAccessTokensUserSetting_PersonalAccessToken.ProtoReflect.Descriptor instead. func (*PersonalAccessTokensUserSetting_PersonalAccessToken) Descriptor() ([]byte, []int) { return file_store_user_setting_proto_rawDescGZIP(), []int{3, 0} } func (x *PersonalAccessTokensUserSetting_PersonalAccessToken) GetTokenId() string { if x != nil { return x.TokenId } return "" } func (x *PersonalAccessTokensUserSetting_PersonalAccessToken) GetTokenHash() string { if x != nil { return x.TokenHash } return "" } func (x *PersonalAccessTokensUserSetting_PersonalAccessToken) GetDescription() string { if x != nil { return x.Description } return "" } func (x *PersonalAccessTokensUserSetting_PersonalAccessToken) GetExpiresAt() *timestamppb.Timestamp { if x != nil { return x.ExpiresAt } return nil } func (x *PersonalAccessTokensUserSetting_PersonalAccessToken) GetCreatedAt() *timestamppb.Timestamp { if x != nil { return x.CreatedAt } return nil } func (x *PersonalAccessTokensUserSetting_PersonalAccessToken) GetLastUsedAt() *timestamppb.Timestamp { if x != nil { return x.LastUsedAt } return nil } type ShortcutsUserSetting_Shortcut struct { state protoimpl.MessageState `protogen:"open.v1"` Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` Title string `protobuf:"bytes,2,opt,name=title,proto3" json:"title,omitempty"` Filter string `protobuf:"bytes,3,opt,name=filter,proto3" json:"filter,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ShortcutsUserSetting_Shortcut) Reset() { *x = ShortcutsUserSetting_Shortcut{} mi := &file_store_user_setting_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *ShortcutsUserSetting_Shortcut) String() string { return protoimpl.X.MessageStringOf(x) } func (*ShortcutsUserSetting_Shortcut) ProtoMessage() {} func (x *ShortcutsUserSetting_Shortcut) ProtoReflect() protoreflect.Message { mi := &file_store_user_setting_proto_msgTypes[9] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ShortcutsUserSetting_Shortcut.ProtoReflect.Descriptor instead. func (*ShortcutsUserSetting_Shortcut) Descriptor() ([]byte, []int) { return file_store_user_setting_proto_rawDescGZIP(), []int{4, 0} } func (x *ShortcutsUserSetting_Shortcut) GetId() string { if x != nil { return x.Id } return "" } func (x *ShortcutsUserSetting_Shortcut) GetTitle() string { if x != nil { return x.Title } return "" } func (x *ShortcutsUserSetting_Shortcut) GetFilter() string { if x != nil { return x.Filter } return "" } type WebhooksUserSetting_Webhook struct { state protoimpl.MessageState `protogen:"open.v1"` // Unique identifier for the webhook Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` // Descriptive title for the webhook Title string `protobuf:"bytes,2,opt,name=title,proto3" json:"title,omitempty"` // The webhook URL endpoint Url string `protobuf:"bytes,3,opt,name=url,proto3" json:"url,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *WebhooksUserSetting_Webhook) Reset() { *x = WebhooksUserSetting_Webhook{} mi := &file_store_user_setting_proto_msgTypes[10] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *WebhooksUserSetting_Webhook) String() string { return protoimpl.X.MessageStringOf(x) } func (*WebhooksUserSetting_Webhook) ProtoMessage() {} func (x *WebhooksUserSetting_Webhook) ProtoReflect() protoreflect.Message { mi := &file_store_user_setting_proto_msgTypes[10] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use WebhooksUserSetting_Webhook.ProtoReflect.Descriptor instead. func (*WebhooksUserSetting_Webhook) Descriptor() ([]byte, []int) { return file_store_user_setting_proto_rawDescGZIP(), []int{5, 0} } func (x *WebhooksUserSetting_Webhook) GetId() string { if x != nil { return x.Id } return "" } func (x *WebhooksUserSetting_Webhook) GetTitle() string { if x != nil { return x.Title } return "" } func (x *WebhooksUserSetting_Webhook) GetUrl() string { if x != nil { return x.Url } return "" } var File_store_user_setting_proto protoreflect.FileDescriptor const file_store_user_setting_proto_rawDesc = "" + "\n" + "\x18store/user_setting.proto\x12\vmemos.store\x1a\x1fgoogle/protobuf/timestamp.proto\"\xcb\x04\n" + "\vUserSetting\x12\x17\n" + "\auser_id\x18\x01 \x01(\x05R\x06userId\x12.\n" + "\x03key\x18\x02 \x01(\x0e2\x1c.memos.store.UserSetting.KeyR\x03key\x12;\n" + "\ageneral\x18\x03 \x01(\v2\x1f.memos.store.GeneralUserSettingH\x00R\ageneral\x12A\n" + "\tshortcuts\x18\x06 \x01(\v2!.memos.store.ShortcutsUserSettingH\x00R\tshortcuts\x12>\n" + "\bwebhooks\x18\a \x01(\v2 .memos.store.WebhooksUserSettingH\x00R\bwebhooks\x12N\n" + "\x0erefresh_tokens\x18\b \x01(\v2%.memos.store.RefreshTokensUserSettingH\x00R\rrefreshTokens\x12d\n" + "\x16personal_access_tokens\x18\t \x01(\v2,.memos.store.PersonalAccessTokensUserSettingH\x00R\x14personalAccessTokens\"t\n" + "\x03Key\x12\x13\n" + "\x0fKEY_UNSPECIFIED\x10\x00\x12\v\n" + "\aGENERAL\x10\x01\x12\r\n" + "\tSHORTCUTS\x10\x04\x12\f\n" + "\bWEBHOOKS\x10\x05\x12\x12\n" + "\x0eREFRESH_TOKENS\x10\x06\x12\x1a\n" + "\x16PERSONAL_ACCESS_TOKENS\x10\aB\a\n" + "\x05value\"k\n" + "\x12GeneralUserSetting\x12\x16\n" + "\x06locale\x18\x01 \x01(\tR\x06locale\x12'\n" + "\x0fmemo_visibility\x18\x02 \x01(\tR\x0ememoVisibility\x12\x14\n" + "\x05theme\x18\x03 \x01(\tR\x05theme\"\xa4\x04\n" + "\x18RefreshTokensUserSetting\x12Y\n" + "\x0erefresh_tokens\x18\x01 \x03(\v22.memos.store.RefreshTokensUserSetting.RefreshTokenR\rrefreshTokens\x1a\x94\x02\n" + "\fRefreshToken\x12\x19\n" + "\btoken_id\x18\x01 \x01(\tR\atokenId\x129\n" + "\n" + "expires_at\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\texpiresAt\x129\n" + "\n" + "created_at\x18\x03 \x01(\v2\x1a.google.protobuf.TimestampR\tcreatedAt\x12Q\n" + "\vclient_info\x18\x04 \x01(\v20.memos.store.RefreshTokensUserSetting.ClientInfoR\n" + "clientInfo\x12 \n" + "\vdescription\x18\x05 \x01(\tR\vdescription\x1a\x95\x01\n" + "\n" + "ClientInfo\x12\x1d\n" + "\n" + "user_agent\x18\x01 \x01(\tR\tuserAgent\x12\x1d\n" + "\n" + "ip_address\x18\x02 \x01(\tR\tipAddress\x12\x1f\n" + "\vdevice_type\x18\x03 \x01(\tR\n" + "deviceType\x12\x0e\n" + "\x02os\x18\x04 \x01(\tR\x02os\x12\x18\n" + "\abrowser\x18\x05 \x01(\tR\abrowser\"\xa3\x03\n" + "\x1fPersonalAccessTokensUserSetting\x12X\n" + "\x06tokens\x18\x01 \x03(\v2@.memos.store.PersonalAccessTokensUserSetting.PersonalAccessTokenR\x06tokens\x1a\xa5\x02\n" + "\x13PersonalAccessToken\x12\x19\n" + "\btoken_id\x18\x01 \x01(\tR\atokenId\x12\x1d\n" + "\n" + "token_hash\x18\x02 \x01(\tR\ttokenHash\x12 \n" + "\vdescription\x18\x03 \x01(\tR\vdescription\x129\n" + "\n" + "expires_at\x18\x04 \x01(\v2\x1a.google.protobuf.TimestampR\texpiresAt\x129\n" + "\n" + "created_at\x18\x05 \x01(\v2\x1a.google.protobuf.TimestampR\tcreatedAt\x12<\n" + "\flast_used_at\x18\x06 \x01(\v2\x1a.google.protobuf.TimestampR\n" + "lastUsedAt\"\xaa\x01\n" + "\x14ShortcutsUserSetting\x12H\n" + "\tshortcuts\x18\x01 \x03(\v2*.memos.store.ShortcutsUserSetting.ShortcutR\tshortcuts\x1aH\n" + "\bShortcut\x12\x0e\n" + "\x02id\x18\x01 \x01(\tR\x02id\x12\x14\n" + "\x05title\x18\x02 \x01(\tR\x05title\x12\x16\n" + "\x06filter\x18\x03 \x01(\tR\x06filter\"\x9e\x01\n" + "\x13WebhooksUserSetting\x12D\n" + "\bwebhooks\x18\x01 \x03(\v2(.memos.store.WebhooksUserSetting.WebhookR\bwebhooks\x1aA\n" + "\aWebhook\x12\x0e\n" + "\x02id\x18\x01 \x01(\tR\x02id\x12\x14\n" + "\x05title\x18\x02 \x01(\tR\x05title\x12\x10\n" + "\x03url\x18\x03 \x01(\tR\x03urlB\x9b\x01\n" + "\x0fcom.memos.storeB\x10UserSettingProtoP\x01Z)github.com/usememos/memos/proto/gen/store\xa2\x02\x03MSX\xaa\x02\vMemos.Store\xca\x02\vMemos\\Store\xe2\x02\x17Memos\\Store\\GPBMetadata\xea\x02\fMemos::Storeb\x06proto3" var ( file_store_user_setting_proto_rawDescOnce sync.Once file_store_user_setting_proto_rawDescData []byte ) func file_store_user_setting_proto_rawDescGZIP() []byte { file_store_user_setting_proto_rawDescOnce.Do(func() { file_store_user_setting_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_store_user_setting_proto_rawDesc), len(file_store_user_setting_proto_rawDesc))) }) return file_store_user_setting_proto_rawDescData } var file_store_user_setting_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_store_user_setting_proto_msgTypes = make([]protoimpl.MessageInfo, 11) var file_store_user_setting_proto_goTypes = []any{ (UserSetting_Key)(0), // 0: memos.store.UserSetting.Key (*UserSetting)(nil), // 1: memos.store.UserSetting (*GeneralUserSetting)(nil), // 2: memos.store.GeneralUserSetting (*RefreshTokensUserSetting)(nil), // 3: memos.store.RefreshTokensUserSetting (*PersonalAccessTokensUserSetting)(nil), // 4: memos.store.PersonalAccessTokensUserSetting (*ShortcutsUserSetting)(nil), // 5: memos.store.ShortcutsUserSetting (*WebhooksUserSetting)(nil), // 6: memos.store.WebhooksUserSetting (*RefreshTokensUserSetting_RefreshToken)(nil), // 7: memos.store.RefreshTokensUserSetting.RefreshToken (*RefreshTokensUserSetting_ClientInfo)(nil), // 8: memos.store.RefreshTokensUserSetting.ClientInfo (*PersonalAccessTokensUserSetting_PersonalAccessToken)(nil), // 9: memos.store.PersonalAccessTokensUserSetting.PersonalAccessToken (*ShortcutsUserSetting_Shortcut)(nil), // 10: memos.store.ShortcutsUserSetting.Shortcut (*WebhooksUserSetting_Webhook)(nil), // 11: memos.store.WebhooksUserSetting.Webhook (*timestamppb.Timestamp)(nil), // 12: google.protobuf.Timestamp } var file_store_user_setting_proto_depIdxs = []int32{ 0, // 0: memos.store.UserSetting.key:type_name -> memos.store.UserSetting.Key 2, // 1: memos.store.UserSetting.general:type_name -> memos.store.GeneralUserSetting 5, // 2: memos.store.UserSetting.shortcuts:type_name -> memos.store.ShortcutsUserSetting 6, // 3: memos.store.UserSetting.webhooks:type_name -> memos.store.WebhooksUserSetting 3, // 4: memos.store.UserSetting.refresh_tokens:type_name -> memos.store.RefreshTokensUserSetting 4, // 5: memos.store.UserSetting.personal_access_tokens:type_name -> memos.store.PersonalAccessTokensUserSetting 7, // 6: memos.store.RefreshTokensUserSetting.refresh_tokens:type_name -> memos.store.RefreshTokensUserSetting.RefreshToken 9, // 7: memos.store.PersonalAccessTokensUserSetting.tokens:type_name -> memos.store.PersonalAccessTokensUserSetting.PersonalAccessToken 10, // 8: memos.store.ShortcutsUserSetting.shortcuts:type_name -> memos.store.ShortcutsUserSetting.Shortcut 11, // 9: memos.store.WebhooksUserSetting.webhooks:type_name -> memos.store.WebhooksUserSetting.Webhook 12, // 10: memos.store.RefreshTokensUserSetting.RefreshToken.expires_at:type_name -> google.protobuf.Timestamp 12, // 11: memos.store.RefreshTokensUserSetting.RefreshToken.created_at:type_name -> google.protobuf.Timestamp 8, // 12: memos.store.RefreshTokensUserSetting.RefreshToken.client_info:type_name -> memos.store.RefreshTokensUserSetting.ClientInfo 12, // 13: memos.store.PersonalAccessTokensUserSetting.PersonalAccessToken.expires_at:type_name -> google.protobuf.Timestamp 12, // 14: memos.store.PersonalAccessTokensUserSetting.PersonalAccessToken.created_at:type_name -> google.protobuf.Timestamp 12, // 15: memos.store.PersonalAccessTokensUserSetting.PersonalAccessToken.last_used_at:type_name -> google.protobuf.Timestamp 16, // [16:16] is the sub-list for method output_type 16, // [16:16] is the sub-list for method input_type 16, // [16:16] is the sub-list for extension type_name 16, // [16:16] is the sub-list for extension extendee 0, // [0:16] is the sub-list for field type_name } func init() { file_store_user_setting_proto_init() }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
true
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/proto/gen/store/activity.pb.go
proto/gen/store/activity.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.36.11 // protoc (unknown) // source: store/activity.proto package store import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type ActivityMemoCommentPayload struct { state protoimpl.MessageState `protogen:"open.v1"` MemoId int32 `protobuf:"varint,1,opt,name=memo_id,json=memoId,proto3" json:"memo_id,omitempty"` RelatedMemoId int32 `protobuf:"varint,2,opt,name=related_memo_id,json=relatedMemoId,proto3" json:"related_memo_id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ActivityMemoCommentPayload) Reset() { *x = ActivityMemoCommentPayload{} mi := &file_store_activity_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *ActivityMemoCommentPayload) String() string { return protoimpl.X.MessageStringOf(x) } func (*ActivityMemoCommentPayload) ProtoMessage() {} func (x *ActivityMemoCommentPayload) ProtoReflect() protoreflect.Message { mi := &file_store_activity_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ActivityMemoCommentPayload.ProtoReflect.Descriptor instead. func (*ActivityMemoCommentPayload) Descriptor() ([]byte, []int) { return file_store_activity_proto_rawDescGZIP(), []int{0} } func (x *ActivityMemoCommentPayload) GetMemoId() int32 { if x != nil { return x.MemoId } return 0 } func (x *ActivityMemoCommentPayload) GetRelatedMemoId() int32 { if x != nil { return x.RelatedMemoId } return 0 } type ActivityPayload struct { state protoimpl.MessageState `protogen:"open.v1"` MemoComment *ActivityMemoCommentPayload `protobuf:"bytes,1,opt,name=memo_comment,json=memoComment,proto3" json:"memo_comment,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ActivityPayload) Reset() { *x = ActivityPayload{} mi := &file_store_activity_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *ActivityPayload) String() string { return protoimpl.X.MessageStringOf(x) } func (*ActivityPayload) ProtoMessage() {} func (x *ActivityPayload) ProtoReflect() protoreflect.Message { mi := &file_store_activity_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use ActivityPayload.ProtoReflect.Descriptor instead. func (*ActivityPayload) Descriptor() ([]byte, []int) { return file_store_activity_proto_rawDescGZIP(), []int{1} } func (x *ActivityPayload) GetMemoComment() *ActivityMemoCommentPayload { if x != nil { return x.MemoComment } return nil } var File_store_activity_proto protoreflect.FileDescriptor const file_store_activity_proto_rawDesc = "" + "\n" + "\x14store/activity.proto\x12\vmemos.store\"]\n" + "\x1aActivityMemoCommentPayload\x12\x17\n" + "\amemo_id\x18\x01 \x01(\x05R\x06memoId\x12&\n" + "\x0frelated_memo_id\x18\x02 \x01(\x05R\rrelatedMemoId\"]\n" + "\x0fActivityPayload\x12J\n" + "\fmemo_comment\x18\x01 \x01(\v2'.memos.store.ActivityMemoCommentPayloadR\vmemoCommentB\x98\x01\n" + "\x0fcom.memos.storeB\rActivityProtoP\x01Z)github.com/usememos/memos/proto/gen/store\xa2\x02\x03MSX\xaa\x02\vMemos.Store\xca\x02\vMemos\\Store\xe2\x02\x17Memos\\Store\\GPBMetadata\xea\x02\fMemos::Storeb\x06proto3" var ( file_store_activity_proto_rawDescOnce sync.Once file_store_activity_proto_rawDescData []byte ) func file_store_activity_proto_rawDescGZIP() []byte { file_store_activity_proto_rawDescOnce.Do(func() { file_store_activity_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_store_activity_proto_rawDesc), len(file_store_activity_proto_rawDesc))) }) return file_store_activity_proto_rawDescData } var file_store_activity_proto_msgTypes = make([]protoimpl.MessageInfo, 2) var file_store_activity_proto_goTypes = []any{ (*ActivityMemoCommentPayload)(nil), // 0: memos.store.ActivityMemoCommentPayload (*ActivityPayload)(nil), // 1: memos.store.ActivityPayload } var file_store_activity_proto_depIdxs = []int32{ 0, // 0: memos.store.ActivityPayload.memo_comment:type_name -> memos.store.ActivityMemoCommentPayload 1, // [1:1] is the sub-list for method output_type 1, // [1:1] is the sub-list for method input_type 1, // [1:1] is the sub-list for extension type_name 1, // [1:1] is the sub-list for extension extendee 0, // [0:1] is the sub-list for field type_name } func init() { file_store_activity_proto_init() } func file_store_activity_proto_init() { if File_store_activity_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_store_activity_proto_rawDesc), len(file_store_activity_proto_rawDesc)), NumEnums: 0, NumMessages: 2, NumExtensions: 0, NumServices: 0, }, GoTypes: file_store_activity_proto_goTypes, DependencyIndexes: file_store_activity_proto_depIdxs, MessageInfos: file_store_activity_proto_msgTypes, }.Build() File_store_activity_proto = out.File file_store_activity_proto_goTypes = nil file_store_activity_proto_depIdxs = nil }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/proto/gen/store/instance_setting.pb.go
proto/gen/store/instance_setting.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.36.11 // protoc (unknown) // source: store/instance_setting.proto package store import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type InstanceSettingKey int32 const ( InstanceSettingKey_INSTANCE_SETTING_KEY_UNSPECIFIED InstanceSettingKey = 0 // BASIC is the key for basic settings. InstanceSettingKey_BASIC InstanceSettingKey = 1 // GENERAL is the key for general settings. InstanceSettingKey_GENERAL InstanceSettingKey = 2 // STORAGE is the key for storage settings. InstanceSettingKey_STORAGE InstanceSettingKey = 3 // MEMO_RELATED is the key for memo related settings. InstanceSettingKey_MEMO_RELATED InstanceSettingKey = 4 ) // Enum value maps for InstanceSettingKey. var ( InstanceSettingKey_name = map[int32]string{ 0: "INSTANCE_SETTING_KEY_UNSPECIFIED", 1: "BASIC", 2: "GENERAL", 3: "STORAGE", 4: "MEMO_RELATED", } InstanceSettingKey_value = map[string]int32{ "INSTANCE_SETTING_KEY_UNSPECIFIED": 0, "BASIC": 1, "GENERAL": 2, "STORAGE": 3, "MEMO_RELATED": 4, } ) func (x InstanceSettingKey) Enum() *InstanceSettingKey { p := new(InstanceSettingKey) *p = x return p } func (x InstanceSettingKey) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (InstanceSettingKey) Descriptor() protoreflect.EnumDescriptor { return file_store_instance_setting_proto_enumTypes[0].Descriptor() } func (InstanceSettingKey) Type() protoreflect.EnumType { return &file_store_instance_setting_proto_enumTypes[0] } func (x InstanceSettingKey) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use InstanceSettingKey.Descriptor instead. func (InstanceSettingKey) EnumDescriptor() ([]byte, []int) { return file_store_instance_setting_proto_rawDescGZIP(), []int{0} } type InstanceStorageSetting_StorageType int32 const ( InstanceStorageSetting_STORAGE_TYPE_UNSPECIFIED InstanceStorageSetting_StorageType = 0 // STORAGE_TYPE_DATABASE is the database storage type. InstanceStorageSetting_DATABASE InstanceStorageSetting_StorageType = 1 // STORAGE_TYPE_LOCAL is the local storage type. InstanceStorageSetting_LOCAL InstanceStorageSetting_StorageType = 2 // STORAGE_TYPE_S3 is the S3 storage type. InstanceStorageSetting_S3 InstanceStorageSetting_StorageType = 3 ) // Enum value maps for InstanceStorageSetting_StorageType. var ( InstanceStorageSetting_StorageType_name = map[int32]string{ 0: "STORAGE_TYPE_UNSPECIFIED", 1: "DATABASE", 2: "LOCAL", 3: "S3", } InstanceStorageSetting_StorageType_value = map[string]int32{ "STORAGE_TYPE_UNSPECIFIED": 0, "DATABASE": 1, "LOCAL": 2, "S3": 3, } ) func (x InstanceStorageSetting_StorageType) Enum() *InstanceStorageSetting_StorageType { p := new(InstanceStorageSetting_StorageType) *p = x return p } func (x InstanceStorageSetting_StorageType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (InstanceStorageSetting_StorageType) Descriptor() protoreflect.EnumDescriptor { return file_store_instance_setting_proto_enumTypes[1].Descriptor() } func (InstanceStorageSetting_StorageType) Type() protoreflect.EnumType { return &file_store_instance_setting_proto_enumTypes[1] } func (x InstanceStorageSetting_StorageType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use InstanceStorageSetting_StorageType.Descriptor instead. func (InstanceStorageSetting_StorageType) EnumDescriptor() ([]byte, []int) { return file_store_instance_setting_proto_rawDescGZIP(), []int{4, 0} } type InstanceSetting struct { state protoimpl.MessageState `protogen:"open.v1"` Key InstanceSettingKey `protobuf:"varint,1,opt,name=key,proto3,enum=memos.store.InstanceSettingKey" json:"key,omitempty"` // Types that are valid to be assigned to Value: // // *InstanceSetting_BasicSetting // *InstanceSetting_GeneralSetting // *InstanceSetting_StorageSetting // *InstanceSetting_MemoRelatedSetting Value isInstanceSetting_Value `protobuf_oneof:"value"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *InstanceSetting) Reset() { *x = InstanceSetting{} mi := &file_store_instance_setting_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *InstanceSetting) String() string { return protoimpl.X.MessageStringOf(x) } func (*InstanceSetting) ProtoMessage() {} func (x *InstanceSetting) ProtoReflect() protoreflect.Message { mi := &file_store_instance_setting_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use InstanceSetting.ProtoReflect.Descriptor instead. func (*InstanceSetting) Descriptor() ([]byte, []int) { return file_store_instance_setting_proto_rawDescGZIP(), []int{0} } func (x *InstanceSetting) GetKey() InstanceSettingKey { if x != nil { return x.Key } return InstanceSettingKey_INSTANCE_SETTING_KEY_UNSPECIFIED } func (x *InstanceSetting) GetValue() isInstanceSetting_Value { if x != nil { return x.Value } return nil } func (x *InstanceSetting) GetBasicSetting() *InstanceBasicSetting { if x != nil { if x, ok := x.Value.(*InstanceSetting_BasicSetting); ok { return x.BasicSetting } } return nil } func (x *InstanceSetting) GetGeneralSetting() *InstanceGeneralSetting { if x != nil { if x, ok := x.Value.(*InstanceSetting_GeneralSetting); ok { return x.GeneralSetting } } return nil } func (x *InstanceSetting) GetStorageSetting() *InstanceStorageSetting { if x != nil { if x, ok := x.Value.(*InstanceSetting_StorageSetting); ok { return x.StorageSetting } } return nil } func (x *InstanceSetting) GetMemoRelatedSetting() *InstanceMemoRelatedSetting { if x != nil { if x, ok := x.Value.(*InstanceSetting_MemoRelatedSetting); ok { return x.MemoRelatedSetting } } return nil } type isInstanceSetting_Value interface { isInstanceSetting_Value() } type InstanceSetting_BasicSetting struct { BasicSetting *InstanceBasicSetting `protobuf:"bytes,2,opt,name=basic_setting,json=basicSetting,proto3,oneof"` } type InstanceSetting_GeneralSetting struct { GeneralSetting *InstanceGeneralSetting `protobuf:"bytes,3,opt,name=general_setting,json=generalSetting,proto3,oneof"` } type InstanceSetting_StorageSetting struct { StorageSetting *InstanceStorageSetting `protobuf:"bytes,4,opt,name=storage_setting,json=storageSetting,proto3,oneof"` } type InstanceSetting_MemoRelatedSetting struct { MemoRelatedSetting *InstanceMemoRelatedSetting `protobuf:"bytes,5,opt,name=memo_related_setting,json=memoRelatedSetting,proto3,oneof"` } func (*InstanceSetting_BasicSetting) isInstanceSetting_Value() {} func (*InstanceSetting_GeneralSetting) isInstanceSetting_Value() {} func (*InstanceSetting_StorageSetting) isInstanceSetting_Value() {} func (*InstanceSetting_MemoRelatedSetting) isInstanceSetting_Value() {} type InstanceBasicSetting struct { state protoimpl.MessageState `protogen:"open.v1"` // The secret key for instance. Mainly used for session management. SecretKey string `protobuf:"bytes,1,opt,name=secret_key,json=secretKey,proto3" json:"secret_key,omitempty"` // The current schema version of database. SchemaVersion string `protobuf:"bytes,2,opt,name=schema_version,json=schemaVersion,proto3" json:"schema_version,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *InstanceBasicSetting) Reset() { *x = InstanceBasicSetting{} mi := &file_store_instance_setting_proto_msgTypes[1] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *InstanceBasicSetting) String() string { return protoimpl.X.MessageStringOf(x) } func (*InstanceBasicSetting) ProtoMessage() {} func (x *InstanceBasicSetting) ProtoReflect() protoreflect.Message { mi := &file_store_instance_setting_proto_msgTypes[1] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use InstanceBasicSetting.ProtoReflect.Descriptor instead. func (*InstanceBasicSetting) Descriptor() ([]byte, []int) { return file_store_instance_setting_proto_rawDescGZIP(), []int{1} } func (x *InstanceBasicSetting) GetSecretKey() string { if x != nil { return x.SecretKey } return "" } func (x *InstanceBasicSetting) GetSchemaVersion() string { if x != nil { return x.SchemaVersion } return "" } type InstanceGeneralSetting struct { state protoimpl.MessageState `protogen:"open.v1"` // disallow_user_registration disallows user registration. DisallowUserRegistration bool `protobuf:"varint,2,opt,name=disallow_user_registration,json=disallowUserRegistration,proto3" json:"disallow_user_registration,omitempty"` // disallow_password_auth disallows password authentication. DisallowPasswordAuth bool `protobuf:"varint,3,opt,name=disallow_password_auth,json=disallowPasswordAuth,proto3" json:"disallow_password_auth,omitempty"` // additional_script is the additional script. AdditionalScript string `protobuf:"bytes,4,opt,name=additional_script,json=additionalScript,proto3" json:"additional_script,omitempty"` // additional_style is the additional style. AdditionalStyle string `protobuf:"bytes,5,opt,name=additional_style,json=additionalStyle,proto3" json:"additional_style,omitempty"` // custom_profile is the custom profile. CustomProfile *InstanceCustomProfile `protobuf:"bytes,6,opt,name=custom_profile,json=customProfile,proto3" json:"custom_profile,omitempty"` // week_start_day_offset is the week start day offset from Sunday. // 0: Sunday, 1: Monday, 2: Tuesday, 3: Wednesday, 4: Thursday, 5: Friday, 6: Saturday // Default is Sunday. WeekStartDayOffset int32 `protobuf:"varint,7,opt,name=week_start_day_offset,json=weekStartDayOffset,proto3" json:"week_start_day_offset,omitempty"` // disallow_change_username disallows changing username. DisallowChangeUsername bool `protobuf:"varint,8,opt,name=disallow_change_username,json=disallowChangeUsername,proto3" json:"disallow_change_username,omitempty"` // disallow_change_nickname disallows changing nickname. DisallowChangeNickname bool `protobuf:"varint,9,opt,name=disallow_change_nickname,json=disallowChangeNickname,proto3" json:"disallow_change_nickname,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *InstanceGeneralSetting) Reset() { *x = InstanceGeneralSetting{} mi := &file_store_instance_setting_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *InstanceGeneralSetting) String() string { return protoimpl.X.MessageStringOf(x) } func (*InstanceGeneralSetting) ProtoMessage() {} func (x *InstanceGeneralSetting) ProtoReflect() protoreflect.Message { mi := &file_store_instance_setting_proto_msgTypes[2] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use InstanceGeneralSetting.ProtoReflect.Descriptor instead. func (*InstanceGeneralSetting) Descriptor() ([]byte, []int) { return file_store_instance_setting_proto_rawDescGZIP(), []int{2} } func (x *InstanceGeneralSetting) GetDisallowUserRegistration() bool { if x != nil { return x.DisallowUserRegistration } return false } func (x *InstanceGeneralSetting) GetDisallowPasswordAuth() bool { if x != nil { return x.DisallowPasswordAuth } return false } func (x *InstanceGeneralSetting) GetAdditionalScript() string { if x != nil { return x.AdditionalScript } return "" } func (x *InstanceGeneralSetting) GetAdditionalStyle() string { if x != nil { return x.AdditionalStyle } return "" } func (x *InstanceGeneralSetting) GetCustomProfile() *InstanceCustomProfile { if x != nil { return x.CustomProfile } return nil } func (x *InstanceGeneralSetting) GetWeekStartDayOffset() int32 { if x != nil { return x.WeekStartDayOffset } return 0 } func (x *InstanceGeneralSetting) GetDisallowChangeUsername() bool { if x != nil { return x.DisallowChangeUsername } return false } func (x *InstanceGeneralSetting) GetDisallowChangeNickname() bool { if x != nil { return x.DisallowChangeNickname } return false } type InstanceCustomProfile struct { state protoimpl.MessageState `protogen:"open.v1"` Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` LogoUrl string `protobuf:"bytes,3,opt,name=logo_url,json=logoUrl,proto3" json:"logo_url,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *InstanceCustomProfile) Reset() { *x = InstanceCustomProfile{} mi := &file_store_instance_setting_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *InstanceCustomProfile) String() string { return protoimpl.X.MessageStringOf(x) } func (*InstanceCustomProfile) ProtoMessage() {} func (x *InstanceCustomProfile) ProtoReflect() protoreflect.Message { mi := &file_store_instance_setting_proto_msgTypes[3] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use InstanceCustomProfile.ProtoReflect.Descriptor instead. func (*InstanceCustomProfile) Descriptor() ([]byte, []int) { return file_store_instance_setting_proto_rawDescGZIP(), []int{3} } func (x *InstanceCustomProfile) GetTitle() string { if x != nil { return x.Title } return "" } func (x *InstanceCustomProfile) GetDescription() string { if x != nil { return x.Description } return "" } func (x *InstanceCustomProfile) GetLogoUrl() string { if x != nil { return x.LogoUrl } return "" } type InstanceStorageSetting struct { state protoimpl.MessageState `protogen:"open.v1"` // storage_type is the storage type. StorageType InstanceStorageSetting_StorageType `protobuf:"varint,1,opt,name=storage_type,json=storageType,proto3,enum=memos.store.InstanceStorageSetting_StorageType" json:"storage_type,omitempty"` // The template of file path. // e.g. assets/{timestamp}_{filename} FilepathTemplate string `protobuf:"bytes,2,opt,name=filepath_template,json=filepathTemplate,proto3" json:"filepath_template,omitempty"` // The max upload size in megabytes. UploadSizeLimitMb int64 `protobuf:"varint,3,opt,name=upload_size_limit_mb,json=uploadSizeLimitMb,proto3" json:"upload_size_limit_mb,omitempty"` // The S3 config. S3Config *StorageS3Config `protobuf:"bytes,4,opt,name=s3_config,json=s3Config,proto3" json:"s3_config,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *InstanceStorageSetting) Reset() { *x = InstanceStorageSetting{} mi := &file_store_instance_setting_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *InstanceStorageSetting) String() string { return protoimpl.X.MessageStringOf(x) } func (*InstanceStorageSetting) ProtoMessage() {} func (x *InstanceStorageSetting) ProtoReflect() protoreflect.Message { mi := &file_store_instance_setting_proto_msgTypes[4] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use InstanceStorageSetting.ProtoReflect.Descriptor instead. func (*InstanceStorageSetting) Descriptor() ([]byte, []int) { return file_store_instance_setting_proto_rawDescGZIP(), []int{4} } func (x *InstanceStorageSetting) GetStorageType() InstanceStorageSetting_StorageType { if x != nil { return x.StorageType } return InstanceStorageSetting_STORAGE_TYPE_UNSPECIFIED } func (x *InstanceStorageSetting) GetFilepathTemplate() string { if x != nil { return x.FilepathTemplate } return "" } func (x *InstanceStorageSetting) GetUploadSizeLimitMb() int64 { if x != nil { return x.UploadSizeLimitMb } return 0 } func (x *InstanceStorageSetting) GetS3Config() *StorageS3Config { if x != nil { return x.S3Config } return nil } // Reference: https://developers.cloudflare.com/r2/examples/aws/aws-sdk-go/ type StorageS3Config struct { state protoimpl.MessageState `protogen:"open.v1"` AccessKeyId string `protobuf:"bytes,1,opt,name=access_key_id,json=accessKeyId,proto3" json:"access_key_id,omitempty"` AccessKeySecret string `protobuf:"bytes,2,opt,name=access_key_secret,json=accessKeySecret,proto3" json:"access_key_secret,omitempty"` Endpoint string `protobuf:"bytes,3,opt,name=endpoint,proto3" json:"endpoint,omitempty"` Region string `protobuf:"bytes,4,opt,name=region,proto3" json:"region,omitempty"` Bucket string `protobuf:"bytes,5,opt,name=bucket,proto3" json:"bucket,omitempty"` UsePathStyle bool `protobuf:"varint,6,opt,name=use_path_style,json=usePathStyle,proto3" json:"use_path_style,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *StorageS3Config) Reset() { *x = StorageS3Config{} mi := &file_store_instance_setting_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *StorageS3Config) String() string { return protoimpl.X.MessageStringOf(x) } func (*StorageS3Config) ProtoMessage() {} func (x *StorageS3Config) ProtoReflect() protoreflect.Message { mi := &file_store_instance_setting_proto_msgTypes[5] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use StorageS3Config.ProtoReflect.Descriptor instead. func (*StorageS3Config) Descriptor() ([]byte, []int) { return file_store_instance_setting_proto_rawDescGZIP(), []int{5} } func (x *StorageS3Config) GetAccessKeyId() string { if x != nil { return x.AccessKeyId } return "" } func (x *StorageS3Config) GetAccessKeySecret() string { if x != nil { return x.AccessKeySecret } return "" } func (x *StorageS3Config) GetEndpoint() string { if x != nil { return x.Endpoint } return "" } func (x *StorageS3Config) GetRegion() string { if x != nil { return x.Region } return "" } func (x *StorageS3Config) GetBucket() string { if x != nil { return x.Bucket } return "" } func (x *StorageS3Config) GetUsePathStyle() bool { if x != nil { return x.UsePathStyle } return false } type InstanceMemoRelatedSetting struct { state protoimpl.MessageState `protogen:"open.v1"` // disallow_public_visibility disallows set memo as public visibility. DisallowPublicVisibility bool `protobuf:"varint,1,opt,name=disallow_public_visibility,json=disallowPublicVisibility,proto3" json:"disallow_public_visibility,omitempty"` // display_with_update_time orders and displays memo with update time. DisplayWithUpdateTime bool `protobuf:"varint,2,opt,name=display_with_update_time,json=displayWithUpdateTime,proto3" json:"display_with_update_time,omitempty"` // content_length_limit is the limit of content length. Unit is byte. ContentLengthLimit int32 `protobuf:"varint,3,opt,name=content_length_limit,json=contentLengthLimit,proto3" json:"content_length_limit,omitempty"` // enable_double_click_edit enables editing on double click. EnableDoubleClickEdit bool `protobuf:"varint,4,opt,name=enable_double_click_edit,json=enableDoubleClickEdit,proto3" json:"enable_double_click_edit,omitempty"` // reactions is the list of reactions. Reactions []string `protobuf:"bytes,7,rep,name=reactions,proto3" json:"reactions,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *InstanceMemoRelatedSetting) Reset() { *x = InstanceMemoRelatedSetting{} mi := &file_store_instance_setting_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *InstanceMemoRelatedSetting) String() string { return protoimpl.X.MessageStringOf(x) } func (*InstanceMemoRelatedSetting) ProtoMessage() {} func (x *InstanceMemoRelatedSetting) ProtoReflect() protoreflect.Message { mi := &file_store_instance_setting_proto_msgTypes[6] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use InstanceMemoRelatedSetting.ProtoReflect.Descriptor instead. func (*InstanceMemoRelatedSetting) Descriptor() ([]byte, []int) { return file_store_instance_setting_proto_rawDescGZIP(), []int{6} } func (x *InstanceMemoRelatedSetting) GetDisallowPublicVisibility() bool { if x != nil { return x.DisallowPublicVisibility } return false } func (x *InstanceMemoRelatedSetting) GetDisplayWithUpdateTime() bool { if x != nil { return x.DisplayWithUpdateTime } return false } func (x *InstanceMemoRelatedSetting) GetContentLengthLimit() int32 { if x != nil { return x.ContentLengthLimit } return 0 } func (x *InstanceMemoRelatedSetting) GetEnableDoubleClickEdit() bool { if x != nil { return x.EnableDoubleClickEdit } return false } func (x *InstanceMemoRelatedSetting) GetReactions() []string { if x != nil { return x.Reactions } return nil } var File_store_instance_setting_proto protoreflect.FileDescriptor const file_store_instance_setting_proto_rawDesc = "" + "\n" + "\x1cstore/instance_setting.proto\x12\vmemos.store\"\x94\x03\n" + "\x0fInstanceSetting\x121\n" + "\x03key\x18\x01 \x01(\x0e2\x1f.memos.store.InstanceSettingKeyR\x03key\x12H\n" + "\rbasic_setting\x18\x02 \x01(\v2!.memos.store.InstanceBasicSettingH\x00R\fbasicSetting\x12N\n" + "\x0fgeneral_setting\x18\x03 \x01(\v2#.memos.store.InstanceGeneralSettingH\x00R\x0egeneralSetting\x12N\n" + "\x0fstorage_setting\x18\x04 \x01(\v2#.memos.store.InstanceStorageSettingH\x00R\x0estorageSetting\x12[\n" + "\x14memo_related_setting\x18\x05 \x01(\v2'.memos.store.InstanceMemoRelatedSettingH\x00R\x12memoRelatedSettingB\a\n" + "\x05value\"\\\n" + "\x14InstanceBasicSetting\x12\x1d\n" + "\n" + "secret_key\x18\x01 \x01(\tR\tsecretKey\x12%\n" + "\x0eschema_version\x18\x02 \x01(\tR\rschemaVersion\"\xd6\x03\n" + "\x16InstanceGeneralSetting\x12<\n" + "\x1adisallow_user_registration\x18\x02 \x01(\bR\x18disallowUserRegistration\x124\n" + "\x16disallow_password_auth\x18\x03 \x01(\bR\x14disallowPasswordAuth\x12+\n" + "\x11additional_script\x18\x04 \x01(\tR\x10additionalScript\x12)\n" + "\x10additional_style\x18\x05 \x01(\tR\x0fadditionalStyle\x12I\n" + "\x0ecustom_profile\x18\x06 \x01(\v2\".memos.store.InstanceCustomProfileR\rcustomProfile\x121\n" + "\x15week_start_day_offset\x18\a \x01(\x05R\x12weekStartDayOffset\x128\n" + "\x18disallow_change_username\x18\b \x01(\bR\x16disallowChangeUsername\x128\n" + "\x18disallow_change_nickname\x18\t \x01(\bR\x16disallowChangeNickname\"j\n" + "\x15InstanceCustomProfile\x12\x14\n" + "\x05title\x18\x01 \x01(\tR\x05title\x12 \n" + "\vdescription\x18\x02 \x01(\tR\vdescription\x12\x19\n" + "\blogo_url\x18\x03 \x01(\tR\alogoUrl\"\xd3\x02\n" + "\x16InstanceStorageSetting\x12R\n" + "\fstorage_type\x18\x01 \x01(\x0e2/.memos.store.InstanceStorageSetting.StorageTypeR\vstorageType\x12+\n" + "\x11filepath_template\x18\x02 \x01(\tR\x10filepathTemplate\x12/\n" + "\x14upload_size_limit_mb\x18\x03 \x01(\x03R\x11uploadSizeLimitMb\x129\n" + "\ts3_config\x18\x04 \x01(\v2\x1c.memos.store.StorageS3ConfigR\bs3Config\"L\n" + "\vStorageType\x12\x1c\n" + "\x18STORAGE_TYPE_UNSPECIFIED\x10\x00\x12\f\n" + "\bDATABASE\x10\x01\x12\t\n" + "\x05LOCAL\x10\x02\x12\x06\n" + "\x02S3\x10\x03\"\xd3\x01\n" + "\x0fStorageS3Config\x12\"\n" + "\raccess_key_id\x18\x01 \x01(\tR\vaccessKeyId\x12*\n" + "\x11access_key_secret\x18\x02 \x01(\tR\x0faccessKeySecret\x12\x1a\n" + "\bendpoint\x18\x03 \x01(\tR\bendpoint\x12\x16\n" + "\x06region\x18\x04 \x01(\tR\x06region\x12\x16\n" + "\x06bucket\x18\x05 \x01(\tR\x06bucket\x12$\n" + "\x0euse_path_style\x18\x06 \x01(\bR\fusePathStyle\"\x9c\x02\n" + "\x1aInstanceMemoRelatedSetting\x12<\n" + "\x1adisallow_public_visibility\x18\x01 \x01(\bR\x18disallowPublicVisibility\x127\n" + "\x18display_with_update_time\x18\x02 \x01(\bR\x15displayWithUpdateTime\x120\n" + "\x14content_length_limit\x18\x03 \x01(\x05R\x12contentLengthLimit\x127\n" + "\x18enable_double_click_edit\x18\x04 \x01(\bR\x15enableDoubleClickEdit\x12\x1c\n" + "\treactions\x18\a \x03(\tR\treactions*q\n" + "\x12InstanceSettingKey\x12$\n" + " INSTANCE_SETTING_KEY_UNSPECIFIED\x10\x00\x12\t\n" + "\x05BASIC\x10\x01\x12\v\n" + "\aGENERAL\x10\x02\x12\v\n" + "\aSTORAGE\x10\x03\x12\x10\n" + "\fMEMO_RELATED\x10\x04B\x9f\x01\n" + "\x0fcom.memos.storeB\x14InstanceSettingProtoP\x01Z)github.com/usememos/memos/proto/gen/store\xa2\x02\x03MSX\xaa\x02\vMemos.Store\xca\x02\vMemos\\Store\xe2\x02\x17Memos\\Store\\GPBMetadata\xea\x02\fMemos::Storeb\x06proto3" var ( file_store_instance_setting_proto_rawDescOnce sync.Once file_store_instance_setting_proto_rawDescData []byte ) func file_store_instance_setting_proto_rawDescGZIP() []byte { file_store_instance_setting_proto_rawDescOnce.Do(func() { file_store_instance_setting_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_store_instance_setting_proto_rawDesc), len(file_store_instance_setting_proto_rawDesc))) }) return file_store_instance_setting_proto_rawDescData } var file_store_instance_setting_proto_enumTypes = make([]protoimpl.EnumInfo, 2) var file_store_instance_setting_proto_msgTypes = make([]protoimpl.MessageInfo, 7) var file_store_instance_setting_proto_goTypes = []any{ (InstanceSettingKey)(0), // 0: memos.store.InstanceSettingKey (InstanceStorageSetting_StorageType)(0), // 1: memos.store.InstanceStorageSetting.StorageType (*InstanceSetting)(nil), // 2: memos.store.InstanceSetting (*InstanceBasicSetting)(nil), // 3: memos.store.InstanceBasicSetting (*InstanceGeneralSetting)(nil), // 4: memos.store.InstanceGeneralSetting (*InstanceCustomProfile)(nil), // 5: memos.store.InstanceCustomProfile (*InstanceStorageSetting)(nil), // 6: memos.store.InstanceStorageSetting (*StorageS3Config)(nil), // 7: memos.store.StorageS3Config (*InstanceMemoRelatedSetting)(nil), // 8: memos.store.InstanceMemoRelatedSetting } var file_store_instance_setting_proto_depIdxs = []int32{ 0, // 0: memos.store.InstanceSetting.key:type_name -> memos.store.InstanceSettingKey 3, // 1: memos.store.InstanceSetting.basic_setting:type_name -> memos.store.InstanceBasicSetting 4, // 2: memos.store.InstanceSetting.general_setting:type_name -> memos.store.InstanceGeneralSetting 6, // 3: memos.store.InstanceSetting.storage_setting:type_name -> memos.store.InstanceStorageSetting 8, // 4: memos.store.InstanceSetting.memo_related_setting:type_name -> memos.store.InstanceMemoRelatedSetting 5, // 5: memos.store.InstanceGeneralSetting.custom_profile:type_name -> memos.store.InstanceCustomProfile 1, // 6: memos.store.InstanceStorageSetting.storage_type:type_name -> memos.store.InstanceStorageSetting.StorageType 7, // 7: memos.store.InstanceStorageSetting.s3_config:type_name -> memos.store.StorageS3Config 8, // [8:8] is the sub-list for method output_type 8, // [8:8] is the sub-list for method input_type 8, // [8:8] is the sub-list for extension type_name 8, // [8:8] is the sub-list for extension extendee 0, // [0:8] is the sub-list for field type_name } func init() { file_store_instance_setting_proto_init() } func file_store_instance_setting_proto_init() { if File_store_instance_setting_proto != nil { return } file_store_instance_setting_proto_msgTypes[0].OneofWrappers = []any{ (*InstanceSetting_BasicSetting)(nil), (*InstanceSetting_GeneralSetting)(nil), (*InstanceSetting_StorageSetting)(nil), (*InstanceSetting_MemoRelatedSetting)(nil), } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_store_instance_setting_proto_rawDesc), len(file_store_instance_setting_proto_rawDesc)), NumEnums: 2, NumMessages: 7, NumExtensions: 0, NumServices: 0, }, GoTypes: file_store_instance_setting_proto_goTypes, DependencyIndexes: file_store_instance_setting_proto_depIdxs, EnumInfos: file_store_instance_setting_proto_enumTypes, MessageInfos: file_store_instance_setting_proto_msgTypes, }.Build() File_store_instance_setting_proto = out.File file_store_instance_setting_proto_goTypes = nil file_store_instance_setting_proto_depIdxs = nil }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false
usememos/memos
https://github.com/usememos/memos/blob/e75862de31b65f90007d771fd623e1d23261b2c6/proto/gen/store/inbox.pb.go
proto/gen/store/inbox.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.36.11 // protoc (unknown) // source: store/inbox.proto package store import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type InboxMessage_Type int32 const ( InboxMessage_TYPE_UNSPECIFIED InboxMessage_Type = 0 // Memo comment notification. InboxMessage_MEMO_COMMENT InboxMessage_Type = 1 ) // Enum value maps for InboxMessage_Type. var ( InboxMessage_Type_name = map[int32]string{ 0: "TYPE_UNSPECIFIED", 1: "MEMO_COMMENT", } InboxMessage_Type_value = map[string]int32{ "TYPE_UNSPECIFIED": 0, "MEMO_COMMENT": 1, } ) func (x InboxMessage_Type) Enum() *InboxMessage_Type { p := new(InboxMessage_Type) *p = x return p } func (x InboxMessage_Type) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (InboxMessage_Type) Descriptor() protoreflect.EnumDescriptor { return file_store_inbox_proto_enumTypes[0].Descriptor() } func (InboxMessage_Type) Type() protoreflect.EnumType { return &file_store_inbox_proto_enumTypes[0] } func (x InboxMessage_Type) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Use InboxMessage_Type.Descriptor instead. func (InboxMessage_Type) EnumDescriptor() ([]byte, []int) { return file_store_inbox_proto_rawDescGZIP(), []int{0, 0} } type InboxMessage struct { state protoimpl.MessageState `protogen:"open.v1"` // The type of the inbox message. Type InboxMessage_Type `protobuf:"varint,1,opt,name=type,proto3,enum=memos.store.InboxMessage_Type" json:"type,omitempty"` // The system-generated unique ID of related activity. ActivityId *int32 `protobuf:"varint,2,opt,name=activity_id,json=activityId,proto3,oneof" json:"activity_id,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *InboxMessage) Reset() { *x = InboxMessage{} mi := &file_store_inbox_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *InboxMessage) String() string { return protoimpl.X.MessageStringOf(x) } func (*InboxMessage) ProtoMessage() {} func (x *InboxMessage) ProtoReflect() protoreflect.Message { mi := &file_store_inbox_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use InboxMessage.ProtoReflect.Descriptor instead. func (*InboxMessage) Descriptor() ([]byte, []int) { return file_store_inbox_proto_rawDescGZIP(), []int{0} } func (x *InboxMessage) GetType() InboxMessage_Type { if x != nil { return x.Type } return InboxMessage_TYPE_UNSPECIFIED } func (x *InboxMessage) GetActivityId() int32 { if x != nil && x.ActivityId != nil { return *x.ActivityId } return 0 } var File_store_inbox_proto protoreflect.FileDescriptor const file_store_inbox_proto_rawDesc = "" + "\n" + "\x11store/inbox.proto\x12\vmemos.store\"\xa8\x01\n" + "\fInboxMessage\x122\n" + "\x04type\x18\x01 \x01(\x0e2\x1e.memos.store.InboxMessage.TypeR\x04type\x12$\n" + "\vactivity_id\x18\x02 \x01(\x05H\x00R\n" + "activityId\x88\x01\x01\".\n" + "\x04Type\x12\x14\n" + "\x10TYPE_UNSPECIFIED\x10\x00\x12\x10\n" + "\fMEMO_COMMENT\x10\x01B\x0e\n" + "\f_activity_idB\x95\x01\n" + "\x0fcom.memos.storeB\n" + "InboxProtoP\x01Z)github.com/usememos/memos/proto/gen/store\xa2\x02\x03MSX\xaa\x02\vMemos.Store\xca\x02\vMemos\\Store\xe2\x02\x17Memos\\Store\\GPBMetadata\xea\x02\fMemos::Storeb\x06proto3" var ( file_store_inbox_proto_rawDescOnce sync.Once file_store_inbox_proto_rawDescData []byte ) func file_store_inbox_proto_rawDescGZIP() []byte { file_store_inbox_proto_rawDescOnce.Do(func() { file_store_inbox_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_store_inbox_proto_rawDesc), len(file_store_inbox_proto_rawDesc))) }) return file_store_inbox_proto_rawDescData } var file_store_inbox_proto_enumTypes = make([]protoimpl.EnumInfo, 1) var file_store_inbox_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_store_inbox_proto_goTypes = []any{ (InboxMessage_Type)(0), // 0: memos.store.InboxMessage.Type (*InboxMessage)(nil), // 1: memos.store.InboxMessage } var file_store_inbox_proto_depIdxs = []int32{ 0, // 0: memos.store.InboxMessage.type:type_name -> memos.store.InboxMessage.Type 1, // [1:1] is the sub-list for method output_type 1, // [1:1] is the sub-list for method input_type 1, // [1:1] is the sub-list for extension type_name 1, // [1:1] is the sub-list for extension extendee 0, // [0:1] is the sub-list for field type_name } func init() { file_store_inbox_proto_init() } func file_store_inbox_proto_init() { if File_store_inbox_proto != nil { return } file_store_inbox_proto_msgTypes[0].OneofWrappers = []any{} type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_store_inbox_proto_rawDesc), len(file_store_inbox_proto_rawDesc)), NumEnums: 1, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_store_inbox_proto_goTypes, DependencyIndexes: file_store_inbox_proto_depIdxs, EnumInfos: file_store_inbox_proto_enumTypes, MessageInfos: file_store_inbox_proto_msgTypes, }.Build() File_store_inbox_proto = out.File file_store_inbox_proto_goTypes = nil file_store_inbox_proto_depIdxs = nil }
go
MIT
e75862de31b65f90007d771fd623e1d23261b2c6
2026-01-07T08:35:43.552360Z
false