recapi

package module
v0.1.16 Latest Latest
Warning

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

Go to latest
Published: Jan 1, 2026 License: MIT Imports: 25 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package recapi is the Go client for recapi, a recommendation API (https://recapi.io), for use on your servers. It keeps each user's history and sends it with every recommendation request, sends events in the background in batches with retries, and falls back to popular items when the API is slow or failing. Standard library only: it adds no dependency to your app.

Create one client per process, with a secret key that stays on your server:

client, err := recapi.New("rk_sec_…", "https://api.recapi.io", recapi.Options{})
if err != nil {
	log.Fatal(err)
}
defer client.Close() // sends the queued events

client.Track(ctx, recapi.Event{ItemID: "sku-42", Level: recapi.View, UserID: "cust-881"})
recs, err := client.Recommend(ctx, recapi.Request{UserID: "cust-881", Count: 4})

The guide is at https://recapi.io/docs, each error's cause and fix at https://recapi.io/docs/errors, and the usual problems at https://recapi.io/docs/troubleshooting.

Index

Constants

View Source
const (
	MaxEventsPerRequest = 1000
	MaxItemsPerRequest  = 1000
	MaxExclude          = 500
	DefaultCount        = 10
	MaxCount            = 100
	// A widget still empty after 1.5 s has lost the user: Recommend gives
	// up then and falls back, whatever the general timeout (which suits events).
	RecommendTimeout = 1500 * time.Millisecond
)

API limits.

View Source
const (
	View     = 3
	Cart     = 5
	Purchase = 10
	// Reject: never recommend the item to this user again until a positive
	// event on it.
	Reject = -10
)

The recommended level scale.

View Source
const (
	// RecentlyViewed is a home page's second row: the products the visitor
	// opened and has not bought, newest first, filled from the default list.
	RecentlyViewed = "recently_viewed"
	// BoughtTogether is a product page's second row: what shoppers carted or
	// bought with the product on screen.
	BoughtTogether = "bought_together"
)

The built-in placements, which serve their own list with nothing to set in the dashboard. Ask each beside the page's first row in one RecommendLists call, after it, so it never repeats that row.

View Source
const (
	HalfLifeSeconds = 604800
	TopK            = 50
	RecentSize      = 20
	RejectedSize    = 200
	MaxIDBytes      = 256
)

The history parameters of docs/history-spec.md.

View Source
const (

	// Retries is how many times a retryable failure is tried again.
	Retries = 3
)
View Source
const Version = "0.1.16"

Version is sent in the User-Agent.

Variables

View Source
var ErrInvalid = errors.New("recapi: invalid argument")

ErrInvalid wraps every refused argument (an id, a level).

View Source
var Levels = map[string]int{"view": View, "cart": Cart, "purchase": Purchase, "reject": Reject}

Levels names the recommended levels, for ParseLevel.

Functions

func IsID

func IsID(s string) bool

IsID reports whether the API accepts s as an id: 1-256 bytes of valid UTF-8 without control characters (unicode.IsControl, as the API checks).

func ParseLevel

func ParseLevel(name string) (int, error)

ParseLevel returns the level a name stands for: view, cart, purchase or reject.

Types

type CatalogItem

type CatalogItem struct {
	ItemID string   `json:"item_id"`
	Tags   []string `json:"tags,omitempty"`
	// Active nil is the API's default, true.
	Active      *bool     `json:"active,omitempty"`
	PublishedAt time.Time `json:"published_at,omitzero"`
	Boost       float64   `json:"boost,omitempty"`
	Title       string    `json:"title,omitempty"`
	// Metadata comes back with every recommendation of the item.
	Metadata map[string]any `json:"metadata,omitempty"`
}

CatalogItem is an item for UpsertItems (PUT /v1/items). Unset fields are not sent: with UpsertOptions.Merge they keep their stored values.

type Client

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

Client is a recapi client, safe for concurrent use; create one per process and Close it at exit, so the queued events are sent.

func New

func New(apiKey, baseURL string, opts Options) (*Client, error)

New returns a client. apiKey is a secret key (rk_sec_...): a server can then restore a user's history from recapi when the store lacks it. baseURL is your recapi API origin, e.g. https://api.example.com.

func (*Client) Close

func (c *Client) Close()

Close stops the sender and sends what is queued, one try per batch, so a deploy never waits on a recapi outage. Events tracked afterwards are sent at once, one try each.

func (*Client) DeleteUser

func (c *Client) DeleteUser(ctx context.Context, userID string) error

DeleteUser erases a user's events in recapi (GDPR) and their state in the store.

func (*Client) Flush

func (c *Client) Flush()

Flush sends every queued event now, with retries (the end of a job or a serverless handler). Failures are logged, and retryable batches stay queued.

func (*Client) Identify

func (c *Client) Identify(ctx context.Context, anonID, userID string) error

Identify is for a login: the visitor's history and shown items become the user's. They are merged into what the store has for userID (scores add up, as in the history spec), then the visitor's entry is deleted. Without it, a visitor's clicks stop counting once they log in.

func (*Client) Popular

func (c *Client) Popular(ctx context.Context, r PopularRequest) ([]Item, error)

Popular returns non-personalised popular items, for pages without a user (no retry). On a network error, timeout, 5xx, 429, 401 or 403 it logs the error and returns an empty list: hide the slot. Any other failure is returned as an *Error, as in Recommend.

func (*Client) Recommend

func (c *Client) Recommend(ctx context.Context, r Request) (*Recommendations, error)

Recommend returns personalised recommendations for a user (or a visitor's AnonID).

It sends the history from the store; without one, recapi uses its stored history for UserID and returns it for the store. A history the store started without it (a Track or Identify came first) gets recapi's fetched once, within the same deadline, and merged in. No retry, at most 1.5 s: on a network error, timeout, 5xx or 429 it returns popular items (Fallback, no id) and logs the error. If those fail too (recapi is down, or the plan's limit covers them), the list is empty: hide the slot. On a 401 or 403 (a revoked key, a suspended shop) it is empty at once, as popular would be refused too. A ContextItemID the API would refuse (a page often takes it from a visitor's URL) is never sent: the answer is the same popular list. Any other failure is returned as an *Error: a bad request or a reply that isn't the API's can't start on a live site without a deploy.

func (*Client) RecommendLists added in v0.1.9

func (c *Client) RecommendLists(ctx context.Context, r ListsRequest) ([]*Recommendations, error)

RecommendLists returns one list per entry of r.Lists, in order, from one call: a page's rows send the history once and are billed as one recommendation. A list holds none of the items of the lists before it unless r.AllowRepeats. It fails and falls back as Recommend does: each list then holds popular items (Fallback, no id), asked list by list, and once popular fails the lists after it are empty without asking.

func (*Client) Track

func (c *Client) Track(ctx context.Context, e Event) error

Track records an interaction: the user's history changes at once, the event is queued and sent in the background. It fails only on an invalid argument (ErrInvalid). An ItemID the API would refuse isn't one: a page often takes it from a visitor's URL, so the event is dropped and logged instead.

func (*Client) UpsertItems

func (c *Client) UpsertItems(ctx context.Context, items []CatalogItem, opts ...UpsertOptions) (int, error)

UpsertItems creates or replaces items (or merges them, with Merge), 1,000 per request, retried like events. It returns how many were stored. An invalid item doesn't keep the others out: once every request is sent, a *RejectedItemsError lists the refused ones.

type Error

type Error struct {
	Code    string
	Message string
	Status  int
	// RetryAfter is the Retry-After header, nil when absent or not seconds.
	RetryAfter *time.Duration
	// DocsURL is the errors page's section for Code, as the API sent it:
	// empty from an older server and on the library's own codes.
	DocsURL string
}

Error is a failed call. Status is 0 when no HTTP response was received.

Code is the API's error code (invalid_request, rate_limited, quota_exceeded...) or a client one: network, timeout, invalid_response, http_error.

func (*Error) Error

func (e *Error) Error() string

Error ends with DocsURL when there is one, so the line a log shows leads to the fix.

func (*Error) Outage

func (e *Error) Outage() bool

Outage reports whether recapi couldn't answer in time or failed on its side.

func (*Error) Retryable

func (e *Error) Retryable() bool

Retryable reports whether trying again later can succeed (quota_exceeded can't until it resets).

type Event

type Event struct {
	ItemID           string
	Level            int
	UserID           string
	AnonID           string
	RecommendationID string
	Value            *float64
	Currency         string
}

Event is one interaction. Level is an integer from -10 to 10 (View, Cart, Purchase, Reject). RecommendationID overrides the automatic attribution. Value is what was paid for a purchase's line (nil for none, 0 for a free line), Currency its ISO 4217 code; a Currency needs a Value.

type Item

type Item struct {
	ItemID string
	Score  float64
	// Slot is exploit, explore or backfill.
	Slot string
	// Metadata is the object stored with the item (metadata of PUT
	// /v1/items: name, picture, link, price...), nil when it has none.
	Metadata map[string]any
	// Why is a reason code to turn into a label for visitors: "for_you",
	// "similar", "next", "bought_together", "trending", "popular", "new",
	// "explore", "more" or "viewed_earlier", "" when the API sent none. New codes may be added:
	// show nothing for an unknown one.
	Why string
}

Item is one recommended or popular item.

type List added in v0.1.9

type List struct {
	Placement     string
	Count         int
	TagsAny       []string
	TagsAll       []string
	Exclude       []string
	ContextItemID string
	Discovery     *float64
}

List is one list of a RecommendLists call: a row of the page.

type ListsRequest added in v0.1.9

type ListsRequest struct {
	UserID string
	AnonID string
	Lists  []List
	// Exclude applies to every list, a List's own Exclude to it alone.
	Exclude []string
	// AllowRepeats lets an item appear on more than one list.
	AllowRepeats bool
}

ListsRequest asks several lists for one user (or visitor) in one call.

type MemoryStore

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

MemoryStore is an in-process Store keeping the most recently used users.

func NewMemoryStore

func NewMemoryStore(maxUsers int) *MemoryStore

NewMemoryStore returns a store keeping at most maxUsers users (10,000 when maxUsers < 1).

func (*MemoryStore) Delete

func (m *MemoryStore) Delete(_ context.Context, key string) error

func (*MemoryStore) Get

func (m *MemoryStore) Get(_ context.Context, key string) (string, error)

func (*MemoryStore) Set

func (m *MemoryStore) Set(_ context.Context, key, value string) error

type Options

type Options struct {
	// Store keeps per-user history and attribution state; default an
	// in-memory NewMemoryStore(10000). Pass a shared store (Redis...) when
	// several processes serve the same users.
	Store Store
	// Timeout per request, default 5 s (Recommend uses at most 1.5 s).
	Timeout time.Duration
	// FlushInterval between background event sends, default 2 s.
	FlushInterval time.Duration
	// MaxBatch is the events per request, at most (and by default, 0)
	// 1,000; a negative one is 1.
	MaxBatch int
	// Logger gets the failures the client handles itself; default slog.Default().
	Logger *slog.Logger
}

Options configures a Client; the zero value is the defaults.

type PopularRequest

type PopularRequest struct {
	Count   int
	TagsAny []string
	TagsAll []string
}

PopularRequest asks for popular items. Count 0 is DefaultCount.

type Recommendations

type Recommendations struct {
	RecommendationID string
	Fallback         bool
	Items            []Item
}

Recommendations is a recommendation list. Fallback lists are popular items with no id.

type RejectedItem added in v0.1.9

type RejectedItem struct {
	Index int
	Error string
}

RejectedItem is an item the API refused: Index is its position in the list given to UpsertItems.

type RejectedItemsError added in v0.1.9

type RejectedItemsError struct {
	Upserted int
	Rejected []RejectedItem
}

RejectedItemsError is UpsertItems' error when the API refused some items: the others were stored. errors.Is(err, ErrInvalid) is true.

func (*RejectedItemsError) Error added in v0.1.9

func (e *RejectedItemsError) Error() string

func (*RejectedItemsError) Unwrap added in v0.1.9

func (e *RejectedItemsError) Unwrap() error

type Request

type Request struct {
	UserID        string
	AnonID        string
	Count         int
	Placement     string
	TagsAny       []string
	TagsAll       []string
	Exclude       []string
	ContextItemID string
	// Discovery is the share of explore slots, nil for the tenant's setting.
	Discovery *float64
}

Request asks for recommendations for a user (or a visitor's AnonID). Count 0 is the API's default (10). A nil Exclude sends none.

type Store

type Store interface {
	Get(ctx context.Context, key string) (string, error)
	Set(ctx context.Context, key, value string) error
	Delete(ctx context.Context, key string) error
}

Store keeps per-user state: Redis, memcached, a database table... Values are strings; Get returns "" and no error for a missing key. Pass a shared store when several processes serve the same users.

type UpsertOptions added in v0.1.9

type UpsertOptions struct {
	// Merge changes only the fields each item sets and keeps the others'
	// stored values (PATCH semantics): a tags-only sync keeps the title and
	// metadata. Without it an item is replaced whole. A field left at its
	// zero value is not sent, so it can't clear a stored one: replace the
	// item for that.
	Merge bool
}

UpsertOptions changes how UpsertItems writes.

Source Files

  • client.go
  • history.go
  • store.go
  • transport.go

Jump to

Keyboard shortcuts

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