github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/models/event.go (about)

     1  package models
     2  
     3  import (
     4  	"context"
     5  	"reflect"
     6  
     7  	"github.com/machinefi/w3bstream/pkg/depends/base/types"
     8  	"github.com/machinefi/w3bstream/pkg/depends/conf/logger"
     9  	"github.com/machinefi/w3bstream/pkg/depends/kit/sqlx"
    10  	"github.com/machinefi/w3bstream/pkg/depends/kit/sqlx/builder"
    11  	"github.com/machinefi/w3bstream/pkg/depends/kit/sqlx/datatypes"
    12  	"github.com/machinefi/w3bstream/pkg/enums"
    13  )
    14  
    15  // EventLog database model for event context
    16  // @def primary              ID
    17  // @def index I_event_id     EventID
    18  // @def index I_event_type   EventType
    19  // @def index I_project_id   ProjectID
    20  // @def index I_publisher_id PublisherID
    21  // @def index I_instance_id  InstanceID
    22  // @def index I_handler      Handler
    23  // @def index I_result_code  ResultCode
    24  // @def index I_published_at PublishedAt
    25  // @def index I_received_at  ReceivedAt
    26  // @def index I_handled_at   HandledAt
    27  // @def index I_completed_at CompletedAt
    28  // @def index I_stage        Stage
    29  //
    30  //go:generate toolkit gen model Event --database DB
    31  type Event struct {
    32  	datatypes.PrimaryID
    33  	EventContext
    34  }
    35  
    36  type EventContext struct {
    37  	// Stage event handle stage: RECEIVED, HANDLED and COMPLETED
    38  	Stage enums.EventStage `db:"f_stage" json:"stage"`
    39  	// From channel type: MQTT HTTP
    40  	From enums.EventSource `db:"f_from" json:"from"`
    41  	// AccountID account ID
    42  	AccountID types.SFID `db:"f_account_id" json:"accountID"`
    43  	// ProjectID project ID
    44  	ProjectID types.SFID `db:"f_project_id" json:"projectID"`
    45  	// ProjectName project name
    46  	ProjectName string `db:"f_project_name" json:"projectName"`
    47  	// PublisherID publisher ID
    48  	PublisherID types.SFID `db:"f_publisher_id" json:"publisherID"`
    49  	// PublisherKey publisher key
    50  	PublisherKey string `db:"f_publisher_key" json:"publisherKey"`
    51  	// EventID event ID
    52  	EventID string `db:"f_event_id" json:"eventID"`
    53  	// Index strategy index for different handler
    54  	Index int `db:"f_index,default='0'" json:"index"`
    55  	// Total strategy total
    56  	Total int `db:"f_total,default='1'" json:"total"`
    57  	// EventType event type
    58  	EventType string `db:"f_event_type" json:"eventType"`
    59  	// InstanceID instance ID
    60  	InstanceID types.SFID `db:"f_instance_id" json:"instanceID"`
    61  	// Handler wasm exported handling func
    62  	Handler string `db:"f_handler" json:"handler"`
    63  	// Input event payload
    64  	Input []byte `db:"f_input" json:"input"`
    65  	// ResultCode wasm handle result code
    66  	ResultCode int32 `db:"f_result_code,default='0'" json:"resultCode"`
    67  	// Error wasm handle error message
    68  	Error string `db:"f_error,default=''"   json:"error"`
    69  	// PublishedAt event published timestamp(epoch milliseconds) from request
    70  	PublishedAt int64 `db:"f_published_at" json:"publishedAt"`
    71  	// ReceivedAt event received timestamp(epoch milliseconds)
    72  	ReceivedAt int64 `db:"f_received_at"  json:"receivedAt"`
    73  	// HandledAt event handled timestamp(epoch milliseconds)
    74  	HandledAt int64 `db:"f_handled_at,default='0'"   json:"handledAt"`
    75  	// CompletedAt event completed timestamp(epoch milliseconds)
    76  	CompletedAt int64 `db:"f_completed_at,default='0'" json:"completedAt"`
    77  	// AutoCollect if do geo collection
    78  	AutoCollect datatypes.Bool `db:"f_auto_collection,default='2'" json:"autoCollection"`
    79  }
    80  
    81  func BatchFetchEvents(d sqlx.DBExecutor, adds ...builder.Addition) (results []*Event, err error) {
    82  	m := &Event{}
    83  	t := d.T(m)
    84  
    85  	err = d.QueryAndScan(builder.Select(nil).From(t, adds...), &results)
    86  	if err != nil {
    87  		return nil, err
    88  	}
    89  	return results, nil
    90  }
    91  
    92  func BatchFetchLastUnhandledEvents(ctx context.Context, d sqlx.DBExecutor, batch int64, prj types.SFID) ([]*Event, error) {
    93  	_, l := logger.NewSpanContext(ctx, "models.BatchFetchEvent")
    94  	defer l.End()
    95  
    96  	m := &Event{}
    97  	return BatchFetchEvents(
    98  		d,
    99  		builder.Where(
   100  			builder.And(
   101  				m.ColStage().Eq(enums.EVENT_STAGE__RECEIVED),
   102  				m.ColProjectID().Eq(prj),
   103  			),
   104  		),
   105  		builder.OrderBy(
   106  			builder.AscOrder(m.ColReceivedAt()),
   107  		),
   108  		builder.Limit(batch),
   109  		builder.Comment("BatchFetchLastUnhandledEvents"),
   110  	)
   111  }
   112  
   113  func BatchCreateEvents(d sqlx.DBExecutor, vs ...*Event) error {
   114  	m := &Event{}
   115  
   116  	cols := reflect.TypeOf(m).Elem().NumField()
   117  	args := make([]any, 0, len(vs)*cols)
   118  	for _, v := range vs {
   119  		args = append(args,
   120  			v.Stage,
   121  			v.From,
   122  			v.AccountID,
   123  			v.ProjectID,
   124  			v.ProjectName,
   125  			v.PublisherID,
   126  			v.PublisherKey,
   127  			v.EventID,
   128  			v.Index,
   129  			v.Total,
   130  			v.EventType,
   131  			v.InstanceID,
   132  			v.Handler,
   133  			v.Input,
   134  			v.ResultCode,
   135  			v.Error,
   136  			v.PublishedAt,
   137  			v.ReceivedAt,
   138  			v.HandledAt,
   139  			v.CompletedAt,
   140  			v.AutoCollect,
   141  		)
   142  	}
   143  	if len(args) == 0 {
   144  		return nil
   145  	}
   146  
   147  	t := d.T(m)
   148  	_, err := d.Exec(builder.Insert().Into(t).Values(
   149  		builder.Cols(
   150  			m.ColStage().Name,
   151  			m.ColFrom().Name,
   152  			m.ColAccountID().Name,
   153  			m.ColProjectID().Name,
   154  			m.ColProjectName().Name,
   155  			m.ColPublisherID().Name,
   156  			m.ColPublisherKey().Name,
   157  			m.ColEventID().Name,
   158  			m.ColIndex().Name,
   159  			m.ColTotal().Name,
   160  			m.ColEventType().Name,
   161  			m.ColInstanceID().Name,
   162  			m.ColHandler().Name,
   163  			m.ColInput().Name,
   164  			m.ColResultCode().Name,
   165  			m.ColError().Name,
   166  			m.ColPublishedAt().Name,
   167  			m.ColReceivedAt().Name,
   168  			m.ColHandledAt().Name,
   169  			m.ColCompletedAt().Name,
   170  			m.ColAutoCollect().Name,
   171  		),
   172  		args...,
   173  	))
   174  	return err
   175  }