Documentation
¶
Index ¶
- Constants
- Variables
- func RegionToEndpoint(s string) string
- func ToKeyID[T [16]byte | string | uint64 | uint32 | int64 | int32 | []byte](id T) string
- type AuthTokenProvider
- type CelExpressionFilter
- type Changed
- type Client
- type ContinueOptions
- type Deleted
- type GeneratedID
- type InternalClientOptions
- type Item
- type ItemTypeMapper
- type JSONItem
- type KeyCondition
- type KeyConditionOperator
- type ListOptions
- func (lo *ListOptions) Merge(other *ListOptions) *ListOptions
- func (lo ListOptions) WithCelExpressionFilter(itemType, expression string) ListOptions
- func (lo ListOptions) WithItemTypesToInclude(itemTypes ...string) ListOptions
- func (lo ListOptions) WithKeyGreaterThan(keyPath string) ListOptions
- func (lo ListOptions) WithKeyGreaterThanOrEqualTo(keyPath string) ListOptions
- func (lo ListOptions) WithKeyLessThan(keyPath string) ListOptions
- func (lo ListOptions) WithKeyLessThanOrEqualTo(keyPath string) ListOptions
- func (lo ListOptions) WithLimit(limit uint32) ListOptions
- func (lo ListOptions) WithSortDirection(direction SortDirection) ListOptions
- type ListResponse
- type ListToken
- type Options
- type OrganizationID
- type ProjectID
- type Reset
- type ScanOptions
- type SchemaID
- type SchemaVersionID
- type SortDirection
- type StoreID
- type SyncResponse
- type Transaction
- type TransactionHandler
- type TransactionResults
- type UnknownItemTypeError
- type UpdateOutsideOfWindow
- type UserID
- type WithPutOptions
Constants ¶
const ( RequestIDHeader = "X-Stately-Request-Id" NoAdminHeader = "X-Stately-NoAdmin" StoreIDHeader = "X-Stately-StoreId" )
Variables ¶
var AllCustomHeaders = []string{ RequestIDHeader, NoAdminHeader, StoreIDHeader, }
Functions ¶
func RegionToEndpoint ¶ added in v0.3.1
RegionToEndpoint converts a region to an endpoint.
Types ¶
type AuthTokenProvider ¶ added in v0.2.2
AuthTokenProvider is the functional interface which the client uses to authenticate outgoing requests. The client will be wired with a default implementation that is suitable for most use cases. This is a thread-safe interface. The `force` parameter causes current token to be invalidated and a new one to be synchronously fetched. This will block other incoming requests until the new token is fetched.
type CelExpressionFilter ¶ added in v0.40.0
type CelExpressionFilter struct {
// ItemType is the ItemType the filter applies to.
// Note: This filter has no effect on other ItemTypes that may be listed over; they
// will still be included in the results unless other filters are applied to them.
ItemType string
// Expression is the CEL expression to evaluate for the ItemType above.
// If the expression evaluates to true, the item is included in the results,
// otherwise it is excluded.
//
// In the context of the CEL expression, 'this' refers to the item being evaluated,
// and properties should be accessed by the names are as they appear in schema
// (this is also the json field name which can be found in the json tags of
// the generated schema) not in generated code name. For example, the following
// item type defined in schema:
//
// itemType("Person", {
// keyPath: "/Person-:id",
// fields: {
// id: { type: uuid, initialValue: "uuid" },
// full_name: { type: string },
// age: { type: int, required: false },
// email: { type: string, required: false },
// }
// })
//
// in generated code looks like:
//
// type Person struct {
// Id uuid.UUID `protobuf:"bytes,1" json:"id,omitempty"`
// FullName string `protobuf:"bytes,2" json:"full_name,omitempty"`
// Age int64 `protobuf:"zigzag64,3" json:"age,omitempty,string"`
// Email string `protobuf:"bytes,4" json:"email,omitempty"`
// }
//
// So, we could build a CEL expression like:
//
// this.full_name.contains('John') && this.age > 30 && !has(this.email)
//
// This will include all Person items where the full_name contains 'John'
// and the age is greater than 30, and the email field is absent.
// For more about CEL expressions, see the CEL documentation:
// https://github.com/google/cel-spec/blob/master/doc/langdef.md
Expression string
}
type Changed ¶ added in v0.2.2
type Changed struct {
Item Item
}
Changed is a SyncResponse that indicates that the item was changed.
func (*Changed) IsSyncResponse ¶ added in v0.2.2
func (r *Changed) IsSyncResponse()
IsSyncResponse is a marker method to indicate that a type is a SyncResponse.
type Client ¶ added in v0.2.2
type Client interface {
// WithAllowStale returns a new client with the given allowStale value set. By
// default clients do not allow stale reads, but this method can used to
// create a lightweight copy of the client where reads can show stale data.
WithAllowStale(allowStale bool) Client
// GetBatch retrieves multiple items by their full key paths. This will return
// any of the Items that exist. Use BeginList if you want to retrieve multiple
// items but don't already know the full key paths of the items you want to
// get. You can get items of different types in a single getBatch but you will
// need to use a type switch to determine what item type each item is.
//
// Example:
// items, err := client.GetBatch(ctx, "/movies-123", "/movies-456")
GetBatch(ctx context.Context, itemPaths ...string) ([]Item, error)
// Get retrieves one Item by its full key path, or nil if no item exists at
// that path.
//
// Example:
// item, err := client.Get(ctx, "/movies-123")
Get(ctx context.Context, itemPath string) (Item, error)
// PutBatch adds multiple Items to the Store, or replaces Items if they
// already exist at that path. Each item may optionally be wrapped in an
// WithPutOptions to specify additional per-item options. All puts in the
// request are applied atomically - there are no partial successes.
//
// This will fail if:
// - Any Item conflicts with an existing Item at the same path and its
// MustNotExist option is set, or the item's ID will be chosen with an
// `initialValue` and one of its other key paths conflicts with an existing
// item.
//
// Additional Notes: Example:
// items, err := client.PutBatch(ctx, item, item2)
// items, err := client.PutBatch(ctx, item, stately.WithPutOptions{Item: item2, MustNotExist:true})
PutBatch(ctx context.Context, items ...Item) ([]Item, error)
// Put adds one Item to the Store, or replaces the Item if it already exists
// at that path. The item may optionally be wrapped in an WithPutOptions
// to specify additional per-item options.
//
// This call will fail if:
// - The Item conflicts with an existing Item at the same path and the
// MustNotExist option is set, or the item's ID will be chosen with an
// `initialValue` and one of its other key paths conflicts with an existing
// item.
//
// Example:
// item, err := client.Put(ctx, item)
// item, err := client.Put(ctx, stately.WithPutOptions{Item: item, MustNotExist:true})
Put(ctx context.Context, item Item) (Item, error)
// Delete removes one or more items from the Store by their full key paths.
// Delete succeeds even if there isn't an item at that key path. Tombstones
// will be saved for deleted items for some time, so that SyncList can return
// information about deleted items. Deletes are always applied atomically; all
// will fail or all will succeed.
//
// Example:
// err := client.Delete(ctx, "/movies-123", "/movies-456")
Delete(ctx context.Context, itemPaths ...string) error
// BeginList retrieves Items that start with a specified keyPathPrefix from a
// single Group. Because it can only list items from a single Group, the key
// path prefix must at least start with a full Group Key (a single key segment
// with a namespace and an ID, e.g. `/user-1234`).
//
// BeginList will return an empty result set if there are no items matching
// that key prefix. This API returns a token that you can pass to ContinueList
// to expand the result set, or to SyncList to get updates within the result
// set.
//
// The options parameter is optional and can be used to limit the number of
// results in a page, change the sort order, etc. If you provide multiple
// options objects, the last one will take precedence.
//
// You can list items of different types in a single BeginList, and you can
// use a type switch to handle different item types.
//
// Example:
// iter, err := client.BeginList(ctx, "/movies-movieID", stately.ListOptions{Limit: 10})
// if err != nil { return err }
// for iter.Next() {
// item := iter.Value()
// // do something with item
// }
// token, err := iter.Token() // Save this for ContinueList/SyncList
BeginList(ctx context.Context, keyPath string, opts ...ListOptions) (ListResponse[Item], error)
// ContinueList takes the token from a BeginList call and returns the next
// "page" of results based on the original query parameters and pagination
// options. It doesn't have options because it is a continuation of a previous
// list operation. It will return a new token which can be used for another
// ContinueList call, and so on. The token is the same one used by SyncList -
// each time you call either ContinueList or SyncList, you should pass the
// latest version of the token, and then use the new token from the result in
// subsequent calls. You may interleave ContinueList and SyncList calls
// however you like, but it does not make sense to make both calls in
// parallel. Calls to ContinueList are tied to the authorization of the
// original BeginList call, so if the original BeginList call was allowed,
// ContinueList with its token should also be allowed.
//
// You can list items of different types in a single ContinueList, and you can
// use a type switch to handle different item types.
//
// Example:
// iter, err := client.ContinueList(ctx, token.Data)
// if err != nil { return err }
// for iter.Next() {
// item := iter.Value()
// // do something with item
// }
// token, err := iter.Token() // Save this for ContinueList/SyncList
ContinueList(ctx context.Context, token []byte) (ListResponse[Item], error)
// BeginScan retrieves all Items from the Store. This API returns a token that
// you can pass to ContinueScan to expand the result set. This can fail if the
// caller does not have permission to read Items.
//
// The options parameter is optional and can be used to limit the number of
// results in a page, return only items of a certain type, or implement
// parallel segmented scans. If you provide multiple options objects, the last
// one will take precedence.
//
// You can list items of different types in a single BeginScan, and you can
// use a type switch to handle different item types.
//
// WARNING: THIS API CAN BE EXPENSIVE FOR STORES WITH A LARGE NUMBER OF ITEMS.
//
// Example:
// iter, err := client.BeginScan(ctx, stately.ScanOptions{Limit: 10, ItemTypes: []string{"Movie"}})
// if err != nil { return err }
// for iter.Next() {
// item := iter.Value()
// // do something with item
// }
// token, err := iter.Token() // Save this for ContinueScan
BeginScan(ctx context.Context, opts ...ScanOptions) (ListResponse[Item], error)
// ContinueScan takes the token from a BeginScan call and returns the next
// "page" of results based on the original scan parameters and pagination
// options. It will return a new token which can be used for another
// ContinueScan call, and so on. Each time you call ContinueScan, you should
// pass the latest version of the token, and then use the new token from the
// result in subsequent calls. Calls to ContinueScan are tied to the
// authorization of the original BeginScan call, so if the original BeginScan
// call was allowed, ContinueScan with its token should also be allowed.
//
// You can list items of different types in a single ContinueScan, and you can
// use a type switch to handle different item types.
//
// WARNING: THIS API CAN BE EXPENSIVE FOR STORES WITH A LARGE NUMBER OF ITEMS.
//
// Example:
// iter, err := client.ContinueScan(ctx, token.Data)
// if err != nil { return err }
// for iter.Next() {
// item := iter.Value()
// // do something with item
// }
// token, err := iter.Token() // Save this for ContinueScan
ContinueScan(ctx context.Context, token []byte) (ListResponse[Item], error)
// NewTransaction allows you to issue reads and writes in any order, and all
// writes will either succeed or all will fail when the transaction finishes.
// You pass it a function with a single parameter, the transaction handler,
// which lets you perform operations within the transaction.
//
// Reads are guaranteed to reflect the state as of when the transaction
// started. A transaction may fail if another transaction commits before this
// one finishes - in that case, you should retry your transaction.
//
// If any error is returned from the handler function, the transaction is
// aborted and none of the changes made in it will be applied. If the handler
// returns without error, the transaction is automatically committed.
//
// If any of the operations in the handler function fails (e.g. a request is
// invalid) you may not find out until the *next* operation, or once the block
// finishes, due to some technicalities about how requests are handled.
//
// When the transaction is committed, the result property will contain the
// full version of any items that were put in the transaction, and the
// committed property will be True. If the transaction was aborted, the
// committed property will be False.
//
// Example:
// results, err := client.NewTransaction(ctx, func(txn stately.Transaction) error {
// item, err := txn.Get(ctx, "/movies-123")
// if err != nil { return err }
// item.Title = "New Title"
// _, err = txn.Put(ctx, item)
// return err
// })
// if err != nil { return err }
// for _, item := range results.PutResponse {
// // do something with the updated item
// }
NewTransaction(ctx context.Context, handler TransactionHandler) (*TransactionResults, error)
// SyncList returns all changes to Items within the result set of a previous
// List operation. For all Items within the result set that were modified, it
// returns the full Item at in its current state. If the result set has
// already been expanded to the end (in the direction of the original
// BeginList request), SyncList will return newly created Items as well. It
// also returns a list of Item key paths that were deleted since the last
// SyncList, which you should reconcile with your view of items returned from
// previous BeginList/ContinueList calls. Using this API, you can start with
// an initial set of items from beginList, and then stay up to date on any
// changes via repeated SyncList requests over time.
//
// The token is the same one used by ContinueList - each time you call either
// ContinueList or SyncList, you should pass the latest version of the token,
// and then use the new token from the result in subsequent calls. You may
// interleave ContinueList and SyncList calls however you like, but it does
// not make sense to make both calls in parallel. Calls to SyncList are tied
// to the authorization of the original BeginList call, so if the original
// beginList call was allowed, SyncList with its token should also be allowed.
//
// Each result will be one of the following types:
// - *stately.Changed: An item that was changed or added since the last
// SyncList call.
// - *stately.Deleted: The key path of an item that was deleted since
// the last SyncList call.
// - *stately.UpdateOutsideOfWindow: An item that was updated but
// is not within the current result set. You can treat this like
// stately.Deleted, but the item hasn't actually been deleted, it's
// just not part of your view of the list anymore.
// - *stately.Reset: A reset signal that indicates any previously cached
// view of the result set is no longer valid. You should throw away
// any locally cached data. This will always be followed by a series
// of *stately.Changed messages that make up a new view of the result set.
//
// Example:
//
// iter, err := client.SyncList(ctx, token.Data)
// for iter.Next() {
// switch v := iter.Value().(type) {
// case *stately.Changed:
// // do something with the changed item: v.Item
// case *stately.Deleted:
// // do something with removed key path: v.KeyPath
// case *stately.UpdateOutsideOfWindow:
// // do something with the out of window update: v.KeyPath
// case *stately.Reset:
// // reset the sync operation
// }
// }
// err, token := iter.Token() // Save this for ContinueList/SyncList
SyncList(ctx context.Context, token []byte) (ListResponse[SyncResponse], error)
}
Client is a stately client that interacts with the given store.
func InternalBindClientToTypes ¶ added in v0.36.0
func InternalBindClientToTypes( appCtx context.Context, storeID uint64, itemTypeMapper ItemTypeMapper, internalOptions InternalClientOptions, options ...*Options, ) Client
InternalBindClientToTypes should not be called directly by users - instead, you should use the NewClient function in your generated schema code, which passes the correct type information to this function.
func NewClient ¶ added in v0.2.2
func NewClient( appCtx context.Context, storeID uint64, schemaVersionID SchemaVersionID, schemaID uint64, itemTypeMapper ItemTypeMapper, options ...*Options, ) Client
NewClient creates a new client with the given store + schema version with options. Deprecated: This function is deprecated and will be removed in a future release.
type ContinueOptions ¶ added in v0.2.2
type ContinueOptions struct {
// SortDirection is the direction to sort by. Default is Ascending.
SortDirection SortDirection
}
ContinueOptions are optional parameters for Continue.
type Deleted ¶ added in v0.2.2
type Deleted struct {
KeyPath string
}
Deleted is a SyncResponse that indicates that the item was deleted.
func (*Deleted) IsSyncResponse ¶ added in v0.2.2
func (r *Deleted) IsSyncResponse()
IsSyncResponse is a marker method to indicate that a type is a SyncResponse.
type GeneratedID ¶ added in v0.2.2
GeneratedID represents a unique ID that was generated by the server for a new item. Right now we only ever generate uint or bytes values from our id generators (initialValue). If neither is set, this represents a put that didn't generate any ID (e.g. it was fully specified in the input).
type InternalClientOptions ¶ added in v0.36.0
type InternalClientOptions struct {
// SchemaID is the schema ID that this client was generated for. All its types
// are specific to a particular version of this schema.
SchemaID
// SchemaVersionID is the schema version that this client was generated for. All its types are specific to this version.
SchemaVersionID
}
InternalClientOptions are options that will be passed from generated code to the internal client constructor InternalBindClientToTypes. This is a struct to make it so new fields can be added later without breaking backwards compatibility every time, the way adding parameters to a function would.
type Item ¶
type Item interface {
// StatelyItemType can be used when switching or mapping item types to
// determine the type of the item. This is used by the SDK to determine the
// type of the item. You can also use this if you want to interact with
// the raw Stately APIs by providing this item type to the relevant Stately
// APIs
StatelyItemType() string
// UnmarshalStately unmarshals the wire format of your db.Item into your
// SDK generated Item. Invoking this method will overwrite the current
// state of the underlying Item with he contents of db.Item. If you're
// using the SDK, you shouldn't need to use this. If you wish to interact
// with the raw Stately APIs, you can use this method to unmarshal items
// like so:
//
// item := &myschema.MyItem{}
// dbItem, err := item.MarshalStately()
// // check for errors
// req := &db.PutRequest{
// Puts: []*db.PutItem{
// {
// Item: dbItem,
// },
// },
// }
// var client dbconnect.DatabaseServiceClient
// // init client
// resp, err := client.Put(ctx, connect.NewRequest[db.PutRequest](req))
// // check for errors
// for _, dbItem := range resp.Msg.Items {
// // handle response
// }
UnmarshalStately(item *db.Item) error
// MarshalStately marshals the contents of your generated SDK Item into our
// wire format. If you're using the SDK, you shouldn't need to use this. If
// you wish to interact with the raw Stately APIs, you can use this method
// to marshal items like so:
//
// req := &db.GetRequest{
// Gets: []*db.GetItem{
// {KeyPath: "/key-id/"},
// },
// }
// var client dbconnect.DatabaseServiceClient
// // init client
// resp, err := client.Get(ctx, connect.NewRequest[db.GetRequest](req))
// // check for errors
// for _, dbItem := range resp.Msg.Items {
// item := myschema.MyItem{}
// err = item.UnmarshalStately(dbItem)
// // check for errors + handle item
// }
MarshalStately() (*db.Item, error)
// KeyPath constructs and returns the primary (first defined) key path of
// the Item as defined by schema. This utility is provided as a convenience
// whenever a reference to the primary key path is required.
KeyPath() string
}
Item is the interface that all Stately items implement. We use this interface to distinguish between items that can be marshalled and unmarshalled to and from the Stately wire format. Item also exposes functionality for custom Marshalling and Unmarshalling of items.
func JSONItemMapper ¶ added in v0.2.2
JSONItemMapper should be used when you want to work with JSON data in your StatelyDB store. This is not a typical use case as you should use the item types generated by the Stately CLI code generator. See NewJSONClient for an example of how to use this.
type ItemTypeMapper ¶
ItemTypeMapper is a function that maps a db.Item to your SDK generated types. We will generate this type mapper when using Stately's code generation to handle the unmarshalling for you.
type JSONItem ¶ added in v0.2.2
type JSONItem struct {
// ItemType allows you + Stately to know "which" item in your schema you are working
// with. For example, if you have a schema with "User" and "Post", ItemType
// would be "User" or "Post".
//
// For Get/List operations, this field is set automatically.
// For Put operations, you must set this field specifically to the schema
// type you are working with.
ItemType string
// Data is the JSON data for the item.
// This data must conform to the item type in the schema of your StatelyDB
// store. If it doesn't you'll get an error when you try to Put the item.
Data *structpb.Struct
}
JSONItem allows for sending and receiving data as JSON in the StatelyDB. The JSON data must still conform to the backing schema of your specific StatelyDB store.
JSONItem is not a typical use case as you should use the item types generated by the Stately CLI code generator.
func (*JSONItem) KeyPath ¶ added in v0.2.2
KeyPath is part of the Stately Item interface; however it is not used for JSON items. This will return an empty string.
func (*JSONItem) MarshalStately ¶ added in v0.2.2
MarshalStately is internally used by the Stately SDK to handle data going over the wire.
func (*JSONItem) StatelyItemType ¶ added in v0.2.2
StatelyItemType is internally used by the Stately SDK to determine the type of the item.
type KeyCondition ¶ added in v0.39.0
type KeyCondition struct {
// KeyPath is a valid key prefix (or full key) used to filter or optimize the
// list operation based on the operator below.
//
// Note: When using KeyConditions and KeyPrefixes together, KeyCondition KeyPaths must
// share the same prefix. For example a KeyCondition:
//
// { Operator: GreaterThan KeyPath: "/group-MY_GROUP_ID/category-10/item-10" }
//
// Can be used with any of the key prefixes:
// - /group-MY_GROUP_ID
// - /group-MY_GROUP_ID/category
// - /group-MY_GROUP_ID/category-10
// - /group-MY_GROUP_ID/category-10/item
//
// But cannot be used with the key prefixes:
// - /group-MY_GROUP_ID/category-11
// - /group-MY_GROUP_ID/otherSubgroup
KeyPath string
// Operator specifies how to apply a KeyPath condition to the list operation.
// Valid operators are:
// - GreaterThan: Items returned must have a key greater than the key path above.
// - GreaterThanOrEqualTo: Items returned must have a key greater than or equal to the key path above.
// - LessThan: Items returned must have a key less than the key path above.
// - LessThanOrEqualTo: Items returned must have a key less than or equal to the key path above.
Operator KeyConditionOperator
}
A KeyCondition is an additional constraint to apply to a list operation to limit the scope of items to return. Stately applies these conditions at the DB layer to optimize the list operation latency and cost.
type KeyConditionOperator ¶ added in v0.39.0
type KeyConditionOperator int32
KeyConditionOperator defines the operator to use for key conditions.
const ( // GreaterThan specifies that a key must be greater than the specified value to be // included in the result set. // In ascending order, this can also be thought of as a "start" condition. // In descending order, this can be thought of as an "end" condition. GreaterThan KeyConditionOperator = iota + 1 // GreaterThanOrEqualTo specifies that a key must be greater than or equal to the // specified value to be included in the result set. // In ascending order, this can also be thought of as a "start" condition. // In descending order, this can be thought of as an "end" condition. GreaterThanOrEqualTo // LessThan specifies that a key must be less than the specified value to be // included in the result set. // In ascending order, this can also be thought of as an "end" condition. // In descending order, this can be thought of as a "start" condition. LessThan // LessThanOrEqualTo specifies that a key must be less than or equal to the // specified value to be included in the result set. // In ascending order, this can also be thought of as an "end" condition. // In descending order, this can be thought of as a "start" condition. LessThanOrEqualTo )
type ListOptions ¶ added in v0.2.2
type ListOptions struct {
// Limit is the maximum number of items to return. The default is unlimited -
// all items will be returned.
Limit uint32
// SortDirection is the direction to sort by. Default is Ascending.
SortDirection SortDirection
// ItemTypes are a list of item types to include in the result set.
// If not provided, all item types will be returned.
ItemTypes []string
// KeyConditions are additional constraints to apply to the list operation
// to limit the scope of items to return.
//
// At most two KeyConditions can be provided:
// - one GreaterThan (or GreaterThanOrEqualTo) condition
// - one LessThan (or LessThanOrEqualTo) condition
KeyConditions []KeyCondition
// CelExpressionFilters are CEL expression filters to apply to the result set.
// Each expression is evaluated on an item type basis, so you can have multiple
// expressions for different item types, and the existence of a filter for one
// item type does not mean that other item types are excluded from the result set.
// To ensure that ONLY specific item types are returned, use the ItemTypes field above.
CelExpressionFilters []CelExpressionFilter
}
ListOptions are optional parameters for List.
func (*ListOptions) Merge ¶ added in v0.2.2
func (lo *ListOptions) Merge(other *ListOptions) *ListOptions
Merge combines two ListOptions into one. "other" takes precedence over "this". Nils will overwrite non-nil values.
func (ListOptions) WithCelExpressionFilter ¶ added in v0.40.0
func (lo ListOptions) WithCelExpressionFilter(itemType, expression string) ListOptions
WithCelExpressionFilter adds a CEL expression filter to the ListOptions.
func (ListOptions) WithItemTypesToInclude ¶ added in v0.40.0
func (lo ListOptions) WithItemTypesToInclude(itemTypes ...string) ListOptions
WithItemTypesToInclude adds ItemType filters to the ListOptions.
func (ListOptions) WithKeyGreaterThan ¶ added in v0.39.0
func (lo ListOptions) WithKeyGreaterThan(keyPath string) ListOptions
WithKeyGreaterThan adds a KeyCondition to the ListOptions that restricts the result set to items with keys greater than the specified keyPath.
func (ListOptions) WithKeyGreaterThanOrEqualTo ¶ added in v0.39.0
func (lo ListOptions) WithKeyGreaterThanOrEqualTo(keyPath string) ListOptions
WithKeyGreaterThanOrEqualTo adds a KeyCondition to the ListOptions that restricts the result set to items with keys greater than or equal to the specified keyPath.
func (ListOptions) WithKeyLessThan ¶ added in v0.39.0
func (lo ListOptions) WithKeyLessThan(keyPath string) ListOptions
WithKeyLessThan adds a KeyCondition to the ListOptions that restricts the result set to items with keys less than the specified keyPath.
func (ListOptions) WithKeyLessThanOrEqualTo ¶ added in v0.39.0
func (lo ListOptions) WithKeyLessThanOrEqualTo(keyPath string) ListOptions
WithKeyLessThanOrEqualTo adds a KeyCondition to the ListOptions that restricts the result set to items with keys less than or equal to the specified keyPath.
func (ListOptions) WithLimit ¶ added in v0.39.0
func (lo ListOptions) WithLimit(limit uint32) ListOptions
WithLimit sets the maximum number of items to return in the ListOptions. Note: If no limit is set (or limit is zero) all items will be returned.
func (ListOptions) WithSortDirection ¶ added in v0.39.0
func (lo ListOptions) WithSortDirection(direction SortDirection) ListOptions
WithSortDirection sets the direction to sort by in the ListOptions.
type ListResponse ¶ added in v0.2.2
type ListResponse[T any] interface { // Next reads an item of the stream, and populates Value() with the current // item. It returns true if an item was read and is ready in Value(). Next() bool // Token will only return something when Next() == false, or in other // words, the iteration is done. Either a token or an error will be // returned. The resulting token can be used for subsequent list calls, or // for the sync api. Token() (*ListToken, error) // Value returns the current item in the iteration. Value() T }
ListResponse allows you to write idiomatic Go code to iterate over a list of value. For example, to iterate over a list of items:
for listResponse.Next() {
value := listResponse.Value()
// do something with item
}
token, err := listResponse.Token();
// handle error and token
type ListToken ¶ added in v0.2.2
type ListToken struct {
// Data will never be nil. This is the token data that you pass to
// ContinueList or SyncList.
Data []byte
// CanContinue indicates if there are more results to fetch using
// ContinueList.
CanContinue bool
// CanSync indicates that you could call SyncList with this token later to get
// updated items. This is determined by the type of store you're listing from.
CanSync bool
// SchemaVersionID is the schema version ID of the store that produced this token.
// When making ContinueList calls, ensure your client version uses tokens that
// match this field. Using tokens with different schema versions will result
// in a SchemaVersionMismatch error. For SyncList calls, you only need to
// ensure you handle Reset responses correctly.
SchemaVersionID SchemaVersionID
}
ListToken is a stateless token that saves your place in a result set, allowing you to fetch additional results with ContinueList, or get updated results with SyncList.
type Options ¶ added in v0.2.2
type Options struct {
// AccessKey is your Stately Access Key. If this is not set, it will be loaded
// from the STATELY_ACCESS_KEY environment variable.
AccessKey string
// NoAuth is a flag to indicate that the client should not attempt to get an
// auth token. This is used when talking to the Stately BYOC Data Plane on
// localhost.
NoAuth bool
// AuthTokenProvider handles fetching auth tokens for requests. It is
// defaulted to an appropriate implementation for most services.
AuthTokenProvider
// Either Region or Endpoint should be set, but not both. Doing so will
// result in an error. An empty Region and Endpoint will default to
// https://api.stately.cloud
//
// Region is the cloud region to use. This is used to determine
// the correct endpoint to use for SDK calls.
//
Region string
// Either Endpoint or Region should be set, but not both. Doing so will
// result in an error. An empty Region and Endpoint will default to
// https://api.stately.cloud
//
// Endpoint is the full URL to the Stately API endpoint to use.
Endpoint string
// JSONResponseFormat is a flag to indicate that the item in the response
// should be in JSON format. This can be used in conjunction with the
// JSONItemMapper to unmarshal the item to/from a JSON representation.
// This would be helpful if you are using the Stately client to send/receive
// items that only accept JSON. However, this is not a typical use case as
// you should use the item types generated by the Stately CLI code generator.
// Defaults to false.
JSONResponseFormat bool
// (internal) NoAdmin is an internal flag used by Stately employees.
// This flag has no effect for non-Stately Employees.
NoAdmin bool
// contains filtered or unexported fields
}
Options is a set of common options for a stately API client. You can either construct a single Options struct and pass it to the client, or you can use the ApplyDefaults method to fill in the defaults. See: NewClient and ApplyDefaults for more information.
func (*Options) ApplyDefaults ¶ added in v0.2.2
ApplyDefaults applies the default values (listed in Options) to the options. It will panic if provided with invalid options.
func (*Options) HTTPClient ¶ added in v0.2.2
HTTPClient builds an HTTP/2 client for the given options.
type OrganizationID ¶ added in v0.2.2
type OrganizationID uint64
OrganizationID is a globally-unique identifier for an organization.
type ProjectID ¶ added in v0.2.2
type ProjectID uint64
ProjectID is a globally-unique identifier for a project.
type Reset ¶ added in v0.2.2
type Reset struct{}
Reset is a SyncResponse that indicates that the sync operation should be reset.
func (*Reset) IsSyncResponse ¶ added in v0.2.2
func (r *Reset) IsSyncResponse()
IsSyncResponse is a marker method to indicate that a type is a SyncResponse.
type ScanOptions ¶ added in v0.29.0
type ScanOptions struct {
// Limit is the maximum number of items to return. If set to 0 then the first
// page of results will be returned which may empty because it does not
// contain items of your selected item types. Be sure to check
// token.canContinue to see if there are more results to fetch. The default 0.
Limit uint32
// ItemTypes are the item types to filter by. If not provided, all item
// types will be returned.
ItemTypes []string
// CelExpressionFilters are CEL expression filters to apply to the result set.
// Each expression is evaluated on an item type basis, so you can have multiple
// expressions for different item types, and the existence of a filter for one
// item type does not mean that other item types are excluded from the result set.
// To ensure that ONLY specific item types are returned, use the ItemTypes field above.
CelExpressionFilters []CelExpressionFilter
// TotalSegments is the total number of segments to divide the scan into.
// If this is provided, then segmentation will be enabled for the scan
// and this scan will only return items from the segment specified by
// SegmentIndex. If this is not provided, then segmentation will be
// disabled and SegmentIndex will be ignored.
TotalSegments uint32
// SegmentIndex is the index of the segment to scan. If TotalSegments is
// provided, SegmentIndex must also be provided and must be less than
// TotalSegments. If TotalSegments is not provided, SegmentIndex is ignored.
SegmentIndex uint32
}
ScanOptions are optional parameters for Scan.
func (*ScanOptions) Merge ¶ added in v0.29.0
func (lo *ScanOptions) Merge(other *ScanOptions) *ScanOptions
Merge combines two ScanOptions into one. "other" takes precedence over "this". Nils will overwrite non-nil values.
func (ScanOptions) WithCelExpressionFilter ¶ added in v0.43.0
func (lo ScanOptions) WithCelExpressionFilter(itemType, expression string) ScanOptions
WithCelExpressionFilter adds a CEL expression filter to the ScanOptions.
func (ScanOptions) WithItemTypesToInclude ¶ added in v0.43.0
func (lo ScanOptions) WithItemTypesToInclude(itemTypes ...string) ScanOptions
WithItemTypesToInclude adds ItemType filters to the ScanOptions.
type SchemaID ¶ added in v0.6.0
type SchemaID uint64
SchemaID is a globally-unique identifier for a schema.
type SchemaVersionID ¶ added in v0.6.0
type SchemaVersionID uint32
SchemaVersionID is a version of a specific SchemaID.
type SortDirection ¶ added in v0.2.2
type SortDirection int32
SortDirection is the direction to sort by.
const ( // Ascending is the default sort direction. Ascending SortDirection = iota // Descending is the reverse sort direction. Descending )
type StoreID ¶ added in v0.2.2
type StoreID uint64
StoreID is a globally-unique identifier for a store.
type SyncResponse ¶ added in v0.2.2
type SyncResponse interface {
// IsSyncResponse is a marker method to indicate that a type is a SyncResponse.
IsSyncResponse()
}
SyncResponse is a response from a sync operation.
type Transaction ¶ added in v0.2.2
type Transaction interface {
// Get retrieves one Item by its full key path, or nil if no item exists at
// that path. Use BeginList if you want to retrieve multiple items but don't
// already know the full key paths of the items you want to get. Use GetBatch
// if you want to retrieve multiple items by their full key paths.
//
// Example:
// item, err := txn.Get("/movies-123")
Get(item string) (Item, error)
// GetBatch retrieves multiple items by their full key paths. This will return
// any of the Items that exist. Use BeginList if you want to retrieve multiple
// items but don't already know the full key paths of the items you want to
// get. Use Get if you want to retrieve a single item. You can get items of
// different types in a single GetBatch - you will need to use a type switch
// to determine what item type each item is.
//
// Example:
// items, err := client.GetBatch("/movies-123", "/movies-456")
GetBatch(itemKeys ...string) ([]Item, error)
// The metadata (create time/version + modified time/version) for each put
// item is returned only at the end of the transaction. The returned
// GeneratedID represents the ID the item *will* have upon a successful
// commit. You can use this ID to build other Items in the same commit.
//
// This call will cause the transaction to fail if:
// - The Item conflicts with an existing Item at the same path and the
// MustNotExist option is set, or the item's ID will be chosen with an
// `initialValue` and one of its other key paths conflicts with an existing
// item.
//
// Example:
// genID, err := txn.Put(item)
// genID, err := txn.Put(stately.WithPutOptions{Item: item, MustNotExist:true})
Put(item Item) (GeneratedID, error)
// PutBatch adds multiple Items to the Store, or replaces the Items if they
// already exist at that path. Each item may optionally be wrapped in an
// WithPutOptions to specify additional per-item options.
//
// The metadata (create time/version + modified time/version) for each put
// item is returned only at the end of the transaction. The returned
// GeneratedID represents the ID the item *will* have upon a successful
// commit. You can use this ID to build other Items in the same commit.
//
// This will cause the transaction to fail if:
// - Any Item conflicts with an existing Item at the same path and its
// MustNotExist option is set, or the item's ID will be chosen with an
// `initialValue` and one of its other key paths conflicts with an existing
// item.
//
// Example:
// genIDs, err := txn.PutBatch(item, item2)
// genIDs, err := txn.PutBatch(item, stately.WithPutOptions{Item: item2, MustNotExist:true})
PutBatch(items ...Item) ([]GeneratedID, error)
// Delete removes multiple Items from the Store by their key paths. Delete
// succeeds even if there isn't an item at that key path.
//
// Example:
// err := txn.Delete("/movies-123", "/movies-456")
Delete(itemKeys ...string) error
// BeginList retrieves Items that start with a specified keyPathPrefix from a
// single Group. Because it can only list items from a single Group, the key
// path prefix must at least start with a full Group Key (a single key segment
// with a namespace and an ID, e.g. `/user-1234`).
//
// BeginList will return an empty result set if there are no items matching
// that key prefix. This API returns a token that you can pass to ContinueList
// to expand the result set.
//
// The options parameter is optional and can be used to limit the number of
// results in a page, change the sort order, etc. If you provide multiple
// options objects, the last one will take precedence.
//
// Example:
// iter, err := txn.BeginList("/movies", stately.ListOptions{Limit: 10})
// if err != nil { return err }
// for iter.Next() {
// item := iter.Value()
// // do something with item
// }
// token, err := iter.Token() // Save this for ContinueList/SyncList
BeginList(prefix string, options ...ListOptions) (ListResponse[Item], error)
// ContinueList takes the token from a BeginList call and returns the next
// "page" of results based on the original query parameters and pagination
// options. It will return a new token which can be used for another
// ContinueList call, and so on. The token is the same one used by SyncList -
// each time you call either ContinueList or SyncList, you should pass the
// latest version of the token, and then use the new token from the result in
// subsequent calls. You may interleave ContinueList and SyncList calls
// however you like, but it does not make sense to make both calls in
// parallel. Calls to ContinueList are tied to the authorization of the
// original BeginList call, so if the original BeginList call was allowed,
// ContinueList with its token should also be allowed.
//
// Example:
// iter, err := txn.ContinueList(token.Data)
// if err != nil { return err }
// for iter.Next() {
// item := iter.Value()
// // do something with item
// }
// token, err := iter.Token() // Save this for ContinueList/SyncList
ContinueList(token *ListToken) (ListResponse[Item], error)
}
Transaction represents a single transaction.
type TransactionHandler ¶ added in v0.2.2
type TransactionHandler func(Transaction) error
TransactionHandler operates on a single transaction.
The Transaction argument is passed to the handler function to allow the handler to interact with the transaction. This handler is not thread safe and should not be shared between goroutines. Additionally, do not share state outside the transaction handler. e.g. don't use a closure that captures variables from the outer scope.
If you wish to cancel/abort the transaction, simply return an error from the handler and we'll take care of cleaning up the transaction.
type TransactionResults ¶ added in v0.2.2
type TransactionResults struct {
// PutResponse contains the full result of each Put operation. This only
// comes back with the transaction is finished message because full
// metadata isn't available until then.
PutResponse []Item
// DeleteResponse contains the full result of each Delete operation. This
// only comes back with the TransactionFinished message because full
// metadata isn't available until then.
DeleteResponse []string
// Did the commit finish (the alternative is that it was aborted/rolled back)
Committed bool
}
TransactionResults holds all the results of a transaction after a commit.
type UnknownItemTypeError ¶
type UnknownItemTypeError struct {
ItemType string
}
UnknownItemTypeError is returned when we receive an item type in the wire format and don't have a corresponding SDK type to map to. This can happen if you're using an older version of the SDK that doesn't understand that type.
func (UnknownItemTypeError) Error ¶
func (e UnknownItemTypeError) Error() string
type UpdateOutsideOfWindow ¶ added in v0.2.2
type UpdateOutsideOfWindow struct {
KeyPath string
}
UpdateOutsideOfWindow is a SyncResponse containing items that were updated but Stately cannot tell if they were in the sync window. Treat these as deleted in most cases. For more information see: https://docs.stately.cloud/api/sync
func (*UpdateOutsideOfWindow) IsSyncResponse ¶ added in v0.2.2
func (r *UpdateOutsideOfWindow) IsSyncResponse()
IsSyncResponse is a marker method to indicate that a type is a SyncResponse.
type UserID ¶ added in v0.2.2
type UserID uint64
UserID is a globally-unique identifier for a Stately user.
type WithPutOptions ¶ added in v0.20.0
type WithPutOptions struct {
Item
// MustNotExist is a condition that indicates this item must not already exist
// at any of its key paths. If there is already an item at one of those paths,
// the Put operation will fail with a ConditionalCheckFailed error. Note that
// if the item has an `initialValue` field in its key, that initial value will
// automatically be chosen not to conflict with existing items, so this
// condition only applies to key paths that do not contain the `initialValue`
// field.
MustNotExist bool
// If set to true, the server will set the `createdAtTime` and/or
// `lastModifiedAtTime` fields based on the current values in this item
// (assuming you've mapped them to a field using `fromMetadata`). Without
// this, those fields are always ignored and the server sets them to the
// appropriate times. This option can be useful when migrating data from
// another system.
OverwriteMetadataTimestamps bool
}
WithPutOptions wraps an item and adds options for use when putting the item. This may be used in place of an Item in Put or PutBatch.