clarify

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2023 License: Apache-2.0 Imports: 14 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.1, and include the following features, based on your integration access configuration:

Always possible:

  • Compose Clarify data frames using the data sub-package.
  • Write signal meta-data to Clarify with client.SaveSignals (scoped to the current integration). See examples/save_signals.
  • Write data frames to Clarify with client.Insert (scoped to the current integration). See examples/insert.

When access to the Admin namespace is granted in Clarify ` (scoped to entire organization):

  • Read signal meta-data to Clarify with client.Admin().SelectSignals. Allows side-loading related items. See examples/select_signals.
  • Publish signals as items directly with client.Admin().PublishSignals, or more conveniently via the automation package. See examples/publish_signals for the latter.

When access to the Clarify namespace is granted in Clarify (scoped to entire organization):

Setting up automation routines

By using our automation and automationcli packages, you can quickly define a tree-structure of Routines that can be recognized and run by path-name. See the automation_cli example, or fork our automation template repository to get started. This template let's you customize and build your own automation CLI and easily run it inside GitHub Actions; no external hosting environment is required (unless you want to).

Copyright 2022-2023 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 strError = "bad credentials"
	ErrBadResponse    strError = "bad response"
	ErrBadRequest     strError = "bad request"
)

Client errors.

Variables

This section is empty.

Functions

This section is empty.

Types

type AdminNamespace added in v0.3.0

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

func (AdminNamespace) PublishSignals added in v0.3.0

func (ns AdminNamespace) PublishSignals(integration string, itemsBySignal map[string]views.ItemSave) PublishSignalsRequest

PublishSignals returns a new request for publishing signals as items.

func (AdminNamespace) SelectSignals added in v0.3.0

func (ns AdminNamespace) SelectSignals(integration string, q fields.ResourceQuery) SelectSignalsRequest

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

Example
const integrationID = "c8ktonqsahsmemfs7lv0"

// In this example we use a mock client; real code should instead initialize
// client 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.Admin().SelectSignals(integrationID,
	fields.Query().Where(
		fields.CompareField("id", fields.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 ClarifyNamespace added in v0.3.0

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

func (ClarifyNamespace) DataFrame added in v0.3.0

DataFrame returns a new request from retrieving raw or aggregated data from Clarify. When a data query rollup is specified, data is aggregated using the default aggregation methods for each item is used. That is statistical aggregation values (count, min, max, sum, avg) for numeric items and a state histogram aggregation in seconds (duration spent in each state per bucket) for enum items.

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

// In this example we use a mock client; real code should instead initialize
// client 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.Clarify().DataFrame(
	fields.Query().Where(
		fields.CompareField("id", fields.In("c8keagasahsp3cpvma20")),
	).Limit(1),

	fields.Data().Where(
		fields.TimeRange(
			time.Date(2022, 1, 1, 0, 0, 0, 0, time.UTC),
			time.Date(2022, 1, 1, 4, 0, 0, 0, time.UTC),
		),
	).RollupDuration(time.Hour, time.Monday),
).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 (ClarifyNamespace) Evaluate added in v0.3.0

func (ns ClarifyNamespace) Evaluate(items []fields.ItemAggregation, calculations []fields.Calculation, data fields.DataQuery) EvaluateRequest

Evaluate returns a new request for retrieving aggregated data from Clarify and perform calculations.

func (ClarifyNamespace) SelectItems added in v0.3.0

SelectItems returns a request for querying items.

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) Admin added in v0.3.0

func (c Client) Admin() AdminNamespace

Admin return a handler for initializing methods that require access to the admin namespace.

Access to the admin namespace must be explicitly granted per integration in the Clarify admin panel. Do not grant excessive permissions.

func (Client) Clarify added in v0.3.0

func (c Client) Clarify() ClarifyNamespace

Clarify return a handler for initializing methods that require access to the clarify namespace.

Access to the clarify namespace must be explicitly granted per integration in the Clarify admin panel. Do not grant excessive permissions.

func (Client) Insert

func (c Client) Insert(data views.DataFrame) InsertRequest

Insert returns a new request for inserting data to clarify. When referencing input IDs that don't exist for the current integration, new signals are created automatically on demand.

c.Insert(data) is a short-hand for c.Integration().Insert(data).

func (Client) Integration added in v0.3.0

func (c Client) Integration() IntegrationNamespace

Integration return a handler for initializing methods that require access to the integration namespace.

All integrations got access to the integration namespace.

func (Client) SaveSignals

func (c Client) SaveSignals(inputs map[string]views.SignalSave) SaveSignalRequest

SaveSignals returns a new request for updating signal meta-data in Clarify. When referencing input IDs that don't exist for the current integration, new signals are created automatically on demand.

c.SaveSignals(inputs) si a short-hand for:

c.Integration().SaveSignals(inputs)

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 CredentialsFromString added in v0.3.1

func CredentialsFromString(s string) (*Credentials, error)

CredentialsFromString parse Clarify Credentials from the passed in JSON string, 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 DataFrameRequest

type DataFrameRequest = request.Relational[DataFrameResult]

type EvaluateRequest added in v0.3.0

type EvaluateRequest = request.Relational[EvaluateResult]

EvaluateRequest describe an initialized clarify.evaluate RPC request with access to a request handler.

type EvaluateResult added in v0.3.0

EvaluateResult describe the result format for a EvaluateRequest.

type HTTPError

type HTTPError = jsonrpc.HTTPError

type InsertRequest added in v0.3.0

type InsertRequest = request.Request[InsertResult]

type InsertResult

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

InsertResult holds the result of an Insert operation.

type IntegrationNamespace added in v0.3.0

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

func (IntegrationNamespace) Insert added in v0.3.0

Insert returns a new request for inserting data to clarify. When referencing input IDs that don't exist for the current integration, new signals are created automatically on demand.

func (IntegrationNamespace) SaveSignals added in v0.3.0

func (ns IntegrationNamespace) SaveSignals(inputs map[string]views.SignalSave) SaveSignalRequest

SaveSignals returns a new request for updating signal meta-data in Clarify. When referencing input IDs that don't exist for the current integration, new signals are created automatically on demand.

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 PublishSignalsRequest added in v0.3.0

type PublishSignalsRequest = request.Request[PublishSignalsResult]

PublishSignalsRequest describe an initialized admin.publishSignal RPC request with access to a request handler.

type PublishSignalsResult

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

PublishSignalsResult describe the result format for a PublishSignalsRequest.

type SaveSignalRequest added in v0.3.0

type SaveSignalRequest = request.Request[SaveSignalsResult]

SaveSignalRequest describe an initialized integration.saveSignals RPC request with access to a request handler.

type SaveSignalsResult

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

SaveSignalsResults describe the result format for a SaveSignalRequest.

type SelectItemsRequest added in v0.3.0

type SelectItemsRequest = request.Relational[SelectItemsResult]

SelectItemsRequest describe an initialized clarify.selectItems RPC request with access to a request handler.

type SelectItemsResult

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

SelectItemsResult describe the result format for a SelectItemsRequest.

type SelectSignalsRequest added in v0.3.0

type SelectSignalsRequest = request.Relational[SelectSignalsResult]

SelectSignalsRequest describe an initialized admin.selectSignals RPC request with access to a request handler.

type SelectSignalsResult

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

SelectSignalsResult describe the result format for a SelectSignalsRequest.

type ServerError

type ServerError = jsonrpc.ServerError

Directories

Path Synopsis
Package automation offers tools for building customized Clarify routines.
Package automation offers tools for building customized Clarify routines.
examples
Package fields define field types for defining JSON views and models.
Package fields define field types for defining JSON views and models.
internal
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