github.com/cockroachdb/cockroachdb-parser@v0.23.3-0.20240213214944-911057d40c9a/pkg/util/log/logpb/event.go (about)

     1  // Copyright 2022 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  package logpb
    12  
    13  import (
    14  	"reflect"
    15  	"strings"
    16  
    17  	"github.com/cockroachdb/redact"
    18  )
    19  
    20  // EventPayload is implemented by CommonEventDetails.
    21  type EventPayload interface {
    22  	// CommonDetails gives access to the common payload.
    23  	CommonDetails() *CommonEventDetails
    24  	// LoggingChannel indicates which logging channel to send this event to.
    25  	// This is defined by the event category, at the top of each .proto file.
    26  	LoggingChannel() Channel
    27  	// AppendJSONFields appends the JSON representation of the event's
    28  	// fields to the given redactable byte slice. Note that the
    29  	// representation is missing the outside '{' and '}'
    30  	// delimiters. This is intended so that the outside printer can
    31  	// decide how to embed the event in a larger payload.
    32  	//
    33  	// The printComma, if true, indicates whether to print a comma
    34  	// before the first field. The returned bool value indicates whether
    35  	// to print a comma when appending more fields afterwards.
    36  	AppendJSONFields(printComma bool, b redact.RedactableBytes) (bool, redact.RedactableBytes)
    37  }
    38  
    39  // CommonDetails implements the EventWithCommonPayload interface.
    40  func (m *CommonEventDetails) CommonDetails() *CommonEventDetails { return m }
    41  
    42  // GetEventTypeName retrieves the system.eventlog type name for the given payload.
    43  func GetEventTypeName(event EventPayload) string {
    44  	// This logic takes the type names and converts from CamelCase to snake_case.
    45  	typeName := reflect.TypeOf(event).Elem().Name()
    46  	var res strings.Builder
    47  	res.WriteByte(typeName[0] + 'a' - 'A')
    48  	for i := 1; i < len(typeName); i++ {
    49  		if typeName[i] >= 'A' && typeName[i] <= 'Z' {
    50  			res.WriteByte('_')
    51  			res.WriteByte(typeName[i] + 'a' - 'A')
    52  		} else {
    53  			res.WriteByte(typeName[i])
    54  		}
    55  	}
    56  	return res.String()
    57  }