github.com/projecteru2/core@v0.0.0-20240321043226-06bcc1c23f58/wal/event.go (about)

     1  package wal
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"path/filepath"
     7  	"strconv"
     8  	"strings"
     9  )
    10  
    11  // HydroEvent indicates a log event.
    12  type HydroEvent struct {
    13  	// A global unique identifier.
    14  	ID uint64 `json:"ID"`
    15  
    16  	// Registered event type name.
    17  	Type string `json:"type"`
    18  
    19  	// The encoded log item.
    20  	Item []byte `json:"item"`
    21  }
    22  
    23  // NewHydroEvent initializes a new HydroEvent instance.
    24  func NewHydroEvent(ID uint64, typ string, item []byte) *HydroEvent {
    25  	return &HydroEvent{ID: ID, Type: typ, Item: item}
    26  }
    27  
    28  // Encode this event
    29  func (e HydroEvent) Encode() ([]byte, error) {
    30  	return json.MarshalIndent(e, "", "\t")
    31  }
    32  
    33  // Key returns this event's key path.
    34  func (e HydroEvent) Key() []byte {
    35  	return []byte(filepath.Join(eventPrefix, fmt.Sprintf("%016x", e.ID)))
    36  }
    37  
    38  func parseHydroEventID(key []byte) (uint64, error) {
    39  	// Trims the EventPrefix, then trims the padding 0.
    40  	ID := strings.TrimLeft(strings.TrimPrefix(string(key), eventPrefix), "0")
    41  	return strconv.ParseUint(ID, 16, 64)
    42  }