clarify

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2022 License: Apache-2.0 Imports: 15 Imported by: 3

README

Clarify Go SDK

GitHub Actions Go Reference Clarify Docs

This repository contains a Go(lang) SDK from Clarify. Clarify is a cloud service for active collaboration on time-series data. It includes a free plan to get started, a plan for small businesses as well as an Enterprise plan for our most demanding customers. If you are interested in SDKs for a different language, or perhaps a different way of integration altogether, please check our documentation.

Risk of breaking changes

This SDK is following Semantic Versioning. The SDK is currently in a v0 state, which means that we reserver the right to introduce breaking changes without increasing the MAJOR number.

Features

This SDK is currently written for Clarify API v1.1beta2, and include the following features:

  • Compose Clarify data frames using the data sub-package.
  • Write signal meta-data to Clarify with client.SaveSignals. See example.
  • Write data frames to Clarify with client.Insert. See example.

Copyright 2022 Searis AS

Licensed under the Apache License, Version 2.0 (the "License"); you may not use the content in this repo except in compliance with the License. You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Documentation

Overview

Package clarify allows interacting with https://api.clarify.io/v1/, and perform simple manipulations of Clarify data and meta-data.

Index

Examples

Constants

View Source
const (
	TypeBasicAuth         = "basic-auth"
	TypeClientCredentials = "client-credentials"
)

Supported credentials types.

View Source
const (
	// Standard JSON RPC error codes.
	CodeInvalidJSON    = -32700
	CodeInvalidRequest = -32600
	CodeMethodNotFound = -32601
	CodeInvalidParams  = -32602
	CodeInternal       = -32603

	// Clarify error codes.
	CodeServerError            = -32000
	CodeProduceInvalidResource = -32001
	CodeFoundInvalidResource   = -32002
	CodeForbidden              = -32003
	CodeConflict               = -32009
	CodeTryAgain               = -32015
	CodePartialFailure         = -32021
)
View Source
const (
	ErrBadCredentials strErr = "bad credentials"
	ErrBadResponse    strErr = "bad response"
	ErrBadRequest     strErr = "bad request"
)

Client errors.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

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

Client allows calling JSON RPC methods against Clarify.

func NewClient

func NewClient(integration string, h jsonrpc.Handler) *Client

NewClient can be used to initialize an integration client from a jsonrpc.Handler implementation.

func (*Client) DataFrame

func (c *Client) DataFrame() DataFrameRequest

DataFrame returns a new request from retrieving data from clarify. The request can be furthered modified by a chainable API before it's executed. By default, the data section is set to be included in the response.

Disclaimer: this method is based on a pre-release of the Clarify API, and might be unstable or stop working.

Example
const inputID = "temp"
const integrationID = "c8ktonqsahsmemfs7lv0"
const itemID = "c8l95d2sahsh22imiabg"

// In this example we use a mock client; real code should insted initialize
// using a clarify.Credentials instance.
h := mockRPCHandler{
	"clarify.dataframe": {
		err:       nil,
		rawResult: json.RawMessage(testdata.ResultDataFrameRollup),
	},
}
c := clarify.NewClient(integrationID, h)

ctx := context.Background()

res, err := c.DataFrame().
	Filter(
		query.Field("id", query.In("c8keagasahsp3cpvma20")),
	).
	Limit(1).
	TimeRange(
		time.Date(2022, 1, 1, 0, 0, 0, 0, time.UTC),
		time.Date(2022, 1, 1, 4, 0, 0, 0, time.UTC),
	).
	RollupBucket(time.Hour).
	Include("items").
	Do(ctx)

if err != nil {
	fmt.Println("error:", err)
	return
}
fmt.Println("meta.total:", res.Meta.Total)
fmt.Println("len(data):", len(res.Data))
if len(res.Data) > 0 {
	fmt.Println("data."+itemID+"_sum:", res.Data[itemID+"_sum"])
}
fmt.Println("len(included.items):", len(res.Included.Items))
if len(res.Included.Items) > 0 {
	fmt.Println("included.items.0.id:", res.Included.Items[0].ID)
	fmt.Println("included.items.0.meta.annotations:", res.Included.Items[0].Meta.Annotations)
}
Output:

meta.total: 2
len(data): 5
data.c8l95d2sahsh22imiabg_sum: map[1640995200000000:64 1640998800000000:32.1 1641002400000000:32.5]
len(included.items): 1
included.items.0.id: c8l95d2sahsh22imiabg
included.items.0.meta.annotations: map[clarify/clarify-go/from/signal/attributes-hash:220596a7b7b4ea2ac5abb6a13e6198f161443226 clarify/clarify-go/from/signal/id:c8keagasahsp3cpvma20]

func (*Client) Insert

Insert returns a new insert request that can be executed at will. Requires access to the integration namespace. Will insert the data to the integration set in c.

func (*Client) PublishSignals

func (c *Client) PublishSignals(integration string, itemsBySignal map[string]views.ItemSave) resource.SaveRequest[map[string]views.ItemSave, PublishSignalsResult]

PublishSignals returns a new request for publishing signals as Items. Requires access to the admin namespace.

Disclaimer: this method is based on a pre-release of the Clarify API, and might be unstable or stop working.

func (*Client) SaveSignals

SaveSignals returns a new save signals request that can be modified though a chainable API before it's executed. Keys in inputs are scoped to the current integration. Requires access to the integration namespace.

func (*Client) SelectItems

func (c *Client) SelectItems() resource.SelectRequest[SelectItemsResult]

SelectItems returns a new request for querying signals and related resources.

Disclaimer: this method is based on a pre-release of the Clarify API, and might be unstable or stop working.

func (*Client) SelectSignals

func (c *Client) SelectSignals(integration string) resource.SelectRequest[SelectSignalsResult]

SelectSignals returns a new request for querying signals and related resources.

Disclaimer: this method is based on a pre-release of the Clarify API, and might be unstable or stop working.

Example
const integrationID = "c8ktonqsahsmemfs7lv0"

// In this example we use a mock client; real code should insted initialize
// using a clarify.Credentials instance.
h := mockRPCHandler{
	"admin.selectsignals": {
		err:       nil,
		rawResult: json.RawMessage(testdata.ResultSelectSignals),
	},
}
c := clarify.NewClient(integrationID, h)

ctx := context.Background()

res, err := c.SelectSignals(integrationID).
	Filter(
		query.Field("id", query.In("c8keagasahsp3cpvma20", "c8l8bc2sahsgjg5cckcg")),
	).
	Limit(1).
	Include("items").
	Do(ctx)

if err != nil {
	fmt.Println("error:", err)
	return
}

fmt.Println("meta.total:", res.Meta.Total)
fmt.Println("len(data):", len(res.Data))
if len(res.Data) > 0 {
	fmt.Println("data.0.id:", res.Data[0].ID)
	fmt.Println("data.0.meta.attributesHash:", res.Data[0].Meta.AttributesHash)
}
fmt.Println("len(included.items):", len(res.Included.Items))
if len(res.Included.Items) > 0 {
	fmt.Println("included.items.0.id:", res.Included.Items[0].ID)
	fmt.Println("included.items.0.meta.annotations:", res.Included.Items[0].Meta.Annotations)
}
Output:

meta.total: 2
len(data): 1
data.0.id: c8keagasahsp3cpvma20
data.0.meta.attributesHash: 220596a7b7b4ea2ac5abb6a13e6198f161443226
len(included.items): 1
included.items.0.id: c8l95d2sahsh22imiabg
included.items.0.meta.annotations: map[clarify/clarify-go/from/signal/attributes-hash:220596a7b7b4ea2ac5abb6a13e6198f161443226 clarify/clarify-go/from/signal/id:c8keagasahsp3cpvma20]

type Credentials

type Credentials struct {
	Name      string    `json:"name"`
	CreatedAt time.Time `json:"createdAt"`

	APIURL      string          `json:"apiUrl"`
	Integration string          `json:"integration"`
	Credentials CredentialsAuth `json:"credentials"`
}

Credentials contain a data-structure with Clarify integration credentials.

func BasicAuthCredentials

func BasicAuthCredentials(integrationID, password string) *Credentials

BasicAuthCredentials returns basic auth credentials for use with Clarify.

func CredentialsFromFile

func CredentialsFromFile(name string) (creds *Credentials, err error)

CredentialsFromFile parse Clarify Credentials from the passed in filename, and return either valid credentials or an error.

func CredentialsFromReader

func CredentialsFromReader(r io.Reader) (*Credentials, error)

CredentialsFromReader parse Clarify Credentials from the passed in reader, and return either valid credentials or an error.

func (Credentials) Client

func (creds Credentials) Client(ctx context.Context) *Client

Client returns a new Clarify client for the current credentials, assuming the client credentials to be valid. If the credentials are invalid, this method will return a non-functional client where all requests result return the ErrBadCredentials error.

func (Credentials) HTTPHandler

func (creds Credentials) HTTPHandler(ctx context.Context) (*jsonrpc.HTTPHandler, error)

HTTPHandler returns a low-level RPC handler that communicates over HTTP using the credentials in creds.

func (*Credentials) Validate

func (creds *Credentials) Validate() error

Validate returns an error if the credentials are invalid.

type CredentialsAuth

type CredentialsAuth struct {
	Type         string `json:"type"`
	ClientID     string `json:"clientId"`
	ClientSecret string `json:"clientSecret"`
}

CredentialsAuth contains the information that is used to authenticate credentials against Clarify.

type DataFrameInclude

type DataFrameInclude struct {
	Items []views.Item `json:"items"`
}

DataFrameInclude describe the included properties for the dataFrame select view.

type DataFrameRequest

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

DataFrameRequest describes a data frame request.

func (DataFrameRequest) Do

Do performs the request against the server and returns the result.

func (DataFrameRequest) Filter

Filter returns a new request that includes Items matching the provided filter.

func (DataFrameRequest) FilterField deprecated

func (req DataFrameRequest) FilterField(path string, cmp query.Comparison) DataFrameRequest

FilterField returns a new request that includes Items matching the provided filter.

Deprecated: use Filter(query.Field(path, cmp)) instead.

func (DataFrameRequest) Include

func (req DataFrameRequest) Include(relationships ...string) DataFrameRequest

Include returns a new request set to include the specified relationships.

func (DataFrameRequest) Last

Last sets the query to only include the n last matching values per item.

func (DataFrameRequest) Limit

func (req DataFrameRequest) Limit(n int) DataFrameRequest

Limit returns a new request that limits the number of matches. Setting n < 0 will use the max limit.

func (DataFrameRequest) RollupBucket

func (req DataFrameRequest) RollupBucket(d time.Duration) DataFrameRequest

RollupBucket sets the query to rollup all data into fixed size bucket when d > 0. Otherwise, clear the rollup information from the query.

func (DataFrameRequest) RollupWindow

func (req DataFrameRequest) RollupWindow() DataFrameRequest

RollupWindow sets the query to rollup all data into a single timestamp.

func (DataFrameRequest) Skip

Skip returns a new request that skips the first n matches.

func (DataFrameRequest) TimeRange

func (req DataFrameRequest) TimeRange(gte, lt time.Time) DataFrameRequest

TimeRange returns a new request that include data for matching items in the specified time range. Note that including data will reduce the maximum number of items that can be returned by the response.

type DataFrameResult

type DataFrameResult = struct {
	Meta     resource.SelectionMeta `json:"meta"`
	Data     views.DataFrame        `json:"data"`
	Included DataFrameInclude       `json:"included"`
}

type HTTPError

type HTTPError = jsonrpc.HTTPError

type InsertResult

type InsertResult struct {
	SignalsByInput map[string]resource.CreateSummary `json:"signalsByInput"`
}

InsertResult holds the result of an Insert operation.

type PathErrors

type PathErrors map[string][]string

PathErrors describes issues for fields in a data-structure. Nested field errors are reported with as `<parentField>.<subField>`. Field names are camelCased to match the preferred case used for JSON encoding.

func (PathErrors) Error

func (err PathErrors) Error() string

type PublishSignalsResult

type PublishSignalsResult struct {
	ItemsBySignals map[string]resource.SaveSummary `json:"itemsBySignal"`
}

PublishSignalsResult holds the result of a PublishSignals operation.

type SaveSignalsResult

type SaveSignalsResult struct {
	SignalsByInput map[string]resource.SaveSummary `json:"signalsByInput"`
}

SaveSignalsResults holds the result of a SaveSignals operation.

type SelectItemsResult

type SelectItemsResult = resource.Selection[views.Item, views.ItemInclude]

SelectItemsResult holds the result of a SelectItems operation.

type SelectSignalsResult

type SelectSignalsResult = resource.Selection[views.Signal, views.SignalInclude]

SelectSignalsResult holds the result of a SelectSignals operation.

type ServerError

type ServerError = jsonrpc.ServerError

Directories

Path Synopsis
examples
Package fields define field types for defining JSON views and models.
Package fields define field types for defining JSON views and models.
Package jsonrpc provides a Clarify specific low-level RPC client.
Package jsonrpc provides a Clarify specific low-level RPC client.
Package views define views for Clarify resources.
Package views define views for Clarify resources.

Jump to

Keyboard shortcuts

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