userup

package
v0.0.0-...-25d8182 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 29, 2024 License: MIT Imports: 11 Imported by: 0

README

go-client

The userup go client package provides a convenience wrapper for the GRPC interface. It supplies common functionality and a flexible query interface to ease integration of the userservice package into your application.

Installation

Import the package into your project:

import (
    userup "github.com/hillside-labs/userservice-go-sdk/go-client"
)

Usage

The userup package provides a UserService struct which can be used to interact with the userservice GRPC interface. Simply supply it with the address of the userservice GRPC server

client, err := userup.NewClient("localhost:9000")
defer client.Close()
Creating a User
user := &userup.User{
    Username: "jdoe2",
    Attributes: map[string]interface{}{
        "user_type": "admin",
        "email":     "jdoe@localhost.com",
        "ranking":   5,
    },
}

ctx := context.Background()
userRet, err := client.AddUser(ctx, user)
Retrieve a User
user, err = client.GetUser(ctx, userId)
Update a User
user, err := client.UpdateUser(ctx, user)

Any attributes or traits specified in the user struct will be added/updated during this operation.

Add an Attribute/Trait to a User

Attribute

err = client.AddAttribute(ctx, user.Id, "user_type", "admin")

Trait

err = client.AddTrait(ctx, user.Id, "selected_value", "gibson")
Log an Event
// Initialize the logger
logger := userup.NewLogger(userup.NewLoggerConfig("https://userup.io/sample-client", client))

...

logger.LogEvent(context.Background(), user.Id, "io.userup.user.created", "user", strconv.FormatUint(user.Id, 10), user)

Query Usage

The Query struct provides a flexible way to construct and execute queries in the userservice package. This is an experimental portion of the SDK and will likely change as it develops.

Creating a Query

To create a new query, you can simply initialize a Query struct:

query := userservice.NewQuery()
Filtering Users on username
query := userup.Query{
		Filter: map[string]userup.Condition{
			"username": "jdoe2",
		}
}
users, err := client.QueryUsers(ctx, &query)
Filtering with different operators

If no operator is specified, the default operator is $eq equality. Other supported operators are

  • $gt greater than
  • $gte greater than or equal to
  • $lt less than
  • $lte less than or equal to
  • $ne not equal
  • $regex regular expression
  • $in in
  • $nin not in
  • $like like
  • $ilike case insensitive like
query := userup.Query{
		Filter: map[string]userup.Condition{
			"id":  map[string]interface{}{"$gte": float64(70)},
		}
}
users, err := client.QueryUsers(ctx, &query)
Filtering users based on attributes value
query := userup.Query{
    Joins: []userup.Join{
        {
            Table: "attributes",
            On:    "users.id = attributes.user_id",
            Filter: map[string]userup.Condition{
                "attributes": {
                    "alias": "dumbledore",
                },
            },
        },
    },
}
users, err := client.QueryUsers(ctx, &query)
Filtering with an OR condition
query := userup.Query{
    Joins: []Join{
        {
            Table: "attributes",
            On:    "users.id = attributes.user_id",
            Filter: map[string]Condition{
                "attributes": {
                    "$or": []Condition{
                        {
                            "2fa": false,
                        },
                        {
                            "vip_level": float64(2),
                        },
                    },
                },
            },
        },
    },
}

Anonymous Sessions and Session Events

When a User is not known, Anonymous Sessions can be used to track activity and eventually resolve that activity back to a know/new User.

Add Session

In this example, we assume that an Anonymous ID has been created already. The data argument to the AddSession call is meant to be an example. There is no structure prescribed for this data. This example draws inspiration from the Segment Identify Call.


sessionData := map[string]interface{}{
  "channel": "browser",
  "context": {
    "ip": "8.8.8.8",
    "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36"
  },
  "attributes": {
    "vendor_url": "levis.com",
    "referrer_params": {
	  "utm_source": "promo_email",
	  "utm_medium": "email",
	  "utm_campaign": "feb24promo",
	  "utm_content": "greatjeans"
	}
  },
}

ctx := context.Background()
userup.AddSession(ctx, anonID, sessionData)
Session Events
// Initialize the logger
logger := userup.NewSessionLogger(userup.NewLoggerConfig("https://userup.io/sample-client", client))

...

logger.LogEvent(context.Background(), user.Id, "io.userup.user.created", "user", strconv.FormatUint(user.Id, 10), user)

Documentation

Overview

Package userup provides functionality for logging events in the user service.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewSessionID

func NewSessionID() string

NewSessionID creates a new random ID for a session ID.

func UserSearchToUserQuery

func UserSearchToUserQuery(usp *UserSearchParams) *userapi.UserQuery

Types

type Condition

type Condition map[string]interface{}

Condition represents a condition in a database query.

type Event

type Event struct {
	Timestamp       time.Time
	ID              string
	Source          string
	SpecVersion     string
	Type            string
	DataContentType string
	DataSchema      string
	Subject         string
	Data            interface{}
	UserID          UserID
	SessionKey      string
}

type EventLogger

type EventLogger struct {
	// contains filtered or unexported fields
}

EventLogger represents a logger for logging events in the user service.

func NewLogger

func NewLogger(config EventLoggerConfig) EventLogger

NewLogger creates a new EventLogger with the specified configuration. It returns the created EventLogger.

func (EventLogger) LogEvent

func (e EventLogger) LogEvent(ctx context.Context, event Event) (*Event, error)

LogEvent logs an event in the user service. It takes the user ID, data type, schema, subject, and data as input parameters. It returns the logged event and an error if any.

type EventLoggerConfig

type EventLoggerConfig struct {
	Source      string       // Source represents the source of the events.
	SpecVersion string       // SpecVersion represents the version of the event specification.
	UserService *UserService // UserService represents the user service client.
}

EventLoggerConfig represents the configuration for the EventLogger.

func NewLoggerConfig

func NewLoggerConfig(source string, userService *UserService) EventLoggerConfig

NewLoggerConfig creates a new EventLoggerConfig with the specified source and UserService. It returns the created EventLoggerConfig.

type Integration

type Integration struct {
	ID         int
	Name       string
	Schedule   string
	ExecPath   string
	ConfigPath string
	Enabled    bool
	Settings   map[string]interface{}
}

type IntegrationsService

type IntegrationsService struct {
	// contains filtered or unexported fields
}

func NewIntegrationsClient

func NewIntegrationsClient(uri string) (*IntegrationsService, error)

NewIntegrationsClient creates a new instance of the UserService Integrations client. It establishes a gRPC connection to the specified URI and returns the client. The URI should be in the format "host:port". If the connection cannot be established, an error is returned.

func (*IntegrationsService) AddIntegration

func (is *IntegrationsService) AddIntegration(ctx context.Context, integration *Integration) (*Integration, error)

AddIntegration adds a new integration to the user service.

func (*IntegrationsService) Close

func (is *IntegrationsService) Close()

func (*IntegrationsService) GetIntegration

func (is *IntegrationsService) GetIntegration(ctx context.Context, name string) (*Integration, error)

func (*IntegrationsService) GetJobHistory

func (is *IntegrationsService) GetJobHistory(ctx context.Context, integrationName string) ([]*Job, error)

func (*IntegrationsService) JobUpdate

func (is *IntegrationsService) JobUpdate(ctx context.Context, job *Job) error

func (*IntegrationsService) ListIntegrations

func (is *IntegrationsService) ListIntegrations(ctx context.Context) ([]*Integration, error)

func (*IntegrationsService) RemoveIntegration

func (is *IntegrationsService) RemoveIntegration(ctx context.Context, name string) error

func (*IntegrationsService) UpdateIntegration

func (is *IntegrationsService) UpdateIntegration(ctx context.Context, integration *Integration) (*Integration, error)

type Job

type Job struct {
	IntegrationName string
	Started         time.Time
	Ended           time.Time
	Status          userapi.JobStatus
	Error           string
	ID              int
}

type Join

type Join struct {
	Table  string               `json:"table"`            // The name of the table to join.
	On     string               `json:"on"`               // The join condition.
	Filter map[string]Condition `json:"filter,omitempty"` // Optional filter conditions for the join.
}

Join represents a join operation in a database query.

type LogicalOperator

type LogicalOperator string

LogicalOperator represents a logical operator used in query conditions.

type Order

type Order struct {
	Field     string `json:"field"`     // The field to order by.
	Direction string `json:"direction"` // The direction of the ordering ("ASC" or "DESC").
}

Order specifies the ordering of the query results.

type Query

type Query struct {
	Filter  map[string]Condition `json:"filter"`             // The filter conditions for the query.
	Select  []string             `json:"select,omitempty"`   // The fields to select in the query.
	OrderBy []Order              `json:"order_by,omitempty"` // The ordering of the query results.
	Limit   int                  `json:"limit,omitempty"`    // The maximum number of results to return.
	Offset  int                  `json:"offset,omitempty"`   // The offset of the query results.
	Joins   []Join               `json:"joins,omitempty"`    // The join operations in the query.
}

Query represents a database query.

type SessionEventQuery

type SessionEventQuery struct {
	UserID      UserID
	SessionKeys []string
	Begin       time.Time
	End         time.Time
	Limit       int32
	Offset      int32
	OrderBy     string
}

type SessionQuery

type SessionQuery struct {
	UserID  UserID
	Keys    []string
	Begin   time.Time
	End     time.Time
	Limit   int32
	Offset  int32
	OrderBy string
}

type User

type User struct {
	ID         UserID
	Username   string
	Attributes map[string]interface{}
	Traits     map[string]interface{}
}

func UserResponseToUser

func UserResponseToUser(userResp *userapi.UserResponse) *User

type UserID

type UserID struct {
	ID         uint64
	UUID       uuid.UUID
	ExternalID string
}

func ExtID

func ExtID(id string) UserID

func UID

func UID(id uint64) UserID

func UUID

func UUID(uuid uuid.UUID) UserID

type UserSearchParams

type UserSearchParams struct {
	ID               UserID
	Username         string
	AttributeFilters []*userapi.AttributeFilter
	TraitFilters     []*userapi.TraitFilter
}

func (UserSearchParams) WithAttribute

func (usp UserSearchParams) WithAttribute(name string, value interface{}, operator ...userapi.Operator) UserSearchParams

func (UserSearchParams) WithTrait

func (usp UserSearchParams) WithTrait(name string, value interface{}, operator ...userapi.Operator) UserSearchParams

type UserService

type UserService struct {
	// contains filtered or unexported fields
}

func NewClient

func NewClient(uri string) (*UserService, error)

NewClient creates a new instance of the UserService client. It establishes a gRPC connection to the specified URI and returns the client. The URI should be in the format "host:port". If the connection cannot be established, an error is returned.

func (UserService) AddAttribute

func (us UserService) AddAttribute(ctx context.Context, id UserID, key string, value interface{}) error

AddAttribute adds an attribute to a user with the specified ID. It takes a context, user ID, attribute key, and attribute value as parameters. The attribute value can be of any type and will be converted to a structpb.Value. Returns an error if there was a problem adding the attribute.

func (UserService) AddSession

func (us UserService) AddSession(ctx context.Context, sessionKey string, sessionData map[string]interface{}) error

func (UserService) AddTrait

func (us UserService) AddTrait(ctx context.Context, id UserID, key string, value interface{}) error

AddTrait adds a trait to a user identified by their ID. It takes a context, user ID, trait key, and trait value as parameters. The trait value can be of any type and will be converted to a structpb.Value. Returns an error if there was a problem adding the trait.

func (UserService) AddUser

func (us UserService) AddUser(ctx context.Context, user *User) (*User, error)

AddUser adds a new user to the user service. It takes a context and a pointer to a User struct as input. It returns a pointer to the created User and an error, if any.

func (*UserService) Close

func (us *UserService) Close()

func (UserService) DeleteAttribute

func (us UserService) DeleteAttribute(ctx context.Context, userId UserID, key string) error

func (UserService) DeleteTrait

func (us UserService) DeleteTrait(ctx context.Context, userId UserID, key string) error

func (UserService) DeleteUser

func (us UserService) DeleteUser(ctx context.Context, id UserID) error

DeleteUser deletes a user by their ID.

func (UserService) FindUser

func (us UserService) FindUser(ctx context.Context, usp *UserSearchParams) ([]*User, error)

func (UserService) GetSessionEvents

func (us UserService) GetSessionEvents(ctx context.Context, query *SessionEventQuery) ([]*userapi.Event, error)

func (UserService) GetSessions

func (us UserService) GetSessions(ctx context.Context, query *SessionQuery) ([]*userapi.Session, error)

func (UserService) GetUser

func (us UserService) GetUser(ctx context.Context, id UserID) (*User, error)

GetUser retrieves a user by their ID. It makes a request to the user service API to fetch the user details. Returns the user object if found, otherwise returns an error.

func (UserService) GetUsersByEvents

func (us UserService) GetUsersByEvents(ctx context.Context, types []string, sources []string, schemas []string, begin time.Time, end time.Time) ([]*User, error)

func (UserService) GetUsersByTraits

func (us UserService) GetUsersByTraits(ctx context.Context, names []string, begin time.Time, end time.Time) ([]*User, error)

func (UserService) IdentifySession

func (us UserService) IdentifySession(ctx context.Context, sessionKey string, userID UserID) error

func (UserService) QueryAttributes

func (us UserService) QueryAttributes(ctx context.Context, query *Query) (map[string]interface{}, error)

QueryAttributes queries the attributes of a user based on the provided query. It takes a context.Context and a *Query as input parameters. It returns a map[string]interface{} containing the attributes of the user and an error if any.

func (UserService) QueryEvents

func (us UserService) QueryEvents(ctx context.Context, query *Query) ([]Event, error)

QueryEvents queries events based on the provided query parameters. It returns a slice of Event objects and an error if any.

func (UserService) QueryTraits

func (us UserService) QueryTraits(ctx context.Context, query *Query) (map[string]interface{}, error)

QueryTraits queries the traits of users based on the provided query. It takes a context.Context and a *Query as input parameters. It returns a map[string]interface{} containing the traits of the users and an error if any.

func (UserService) QueryUsers

func (us UserService) QueryUsers(ctx context.Context, query *Query) ([]*User, error)

QueryUsers queries the user service with the given query and returns a list of users and an error, if any. The query parameter specifies the criteria for filtering the users. The returned list of users contains the user ID, username, UUID, attributes, and traits.

func (UserService) SearchEvents

func (us UserService) SearchEvents(ctx context.Context, userId UserID, types []string, begin time.Time, end time.Time) ([]Event, error)

func (UserService) SearchUserTraits

func (us UserService) SearchUserTraits(ctx context.Context, userId UserID, names []string, begin time.Time, end time.Time) ([]interface{}, error)

func (UserService) UpdateUser

func (us UserService) UpdateUser(ctx context.Context, user *User) (*User, error)

UpdateUser updates a user with the provided user data. It takes a context.Context and a pointer to a User struct as input. It returns a pointer to the updated User struct and an error if any.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL