graphik

package
v1.4.1 Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2022 License: Apache-2.0 Imports: 20 Imported by: 1

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func LoadTransportCredentials added in v1.1.2

func LoadTransportCredentials(caCertificateFile string) (credentials.TransportCredentials, error)

LoadTransportCredentials loads the transport credentials from the given CA certificate

Types

type Client

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

func NewClient

func NewClient(ctx context.Context, target string, opts ...Opt) (*Client, error)
Example
ctx := context.Background()

// ensure graphik server is started with --auth.jwks=https://www.googleapis.com/oauth2/v3/certs
source, err := google.DefaultTokenSource(context.Background(), "https://www.googleapis.com/auth/devstorage.full_control")
if err != nil {
	fmt.Print(err)
	return
}
cli, err := graphik.NewClient(ctx, "localhost:7820", graphik.WithTokenSource(source))
if err != nil {
	fmt.Print(err)
	return
}
pong, err := cli.Ping(ctx, &empty.Empty{})
if err != nil {
	fmt.Println(err.Error())
	return
}
fmt.Println(pong.Message)
Output:

PONG

func (*Client) AggregateConnections

func (c *Client) AggregateConnections(ctx context.Context, in *apipb.AggFilter, opts ...grpc.CallOption) (*apipb.Number, error)

AggregateConnections executes an aggregation function against a set of connections

func (*Client) AggregateDocs

func (c *Client) AggregateDocs(ctx context.Context, in *apipb.AggFilter, opts ...grpc.CallOption) (*apipb.Number, error)

AggregateDocs executes an aggregation function against a set of documents

func (*Client) Broadcast

func (c *Client) Broadcast(ctx context.Context, in *apipb.OutboundMessage, opts ...grpc.CallOption) error

Broadcast broadcasts a message to a pubsub channel

Example
err := client.Broadcast(context.Background(), &apipb2.OutboundMessage{
	Channel: "testing",
	Data: apipb2.NewStruct(map[string]interface{}{
		"text": "hello world",
	}),
})
if err != nil {
	fmt.Print(err)
	return
}
fmt.Println("success!")
Output:

success!

func (*Client) ClusterState

func (c *Client) ClusterState(ctx context.Context, _ *empty.Empty, opts ...grpc.CallOption) error

ClusterState returns information about the raft cluster

func (*Client) ConnectionsFrom

func (c *Client) ConnectionsFrom(ctx context.Context, in *apipb.ConnectFilter, opts ...grpc.CallOption) (*apipb.Connections, error)

ConnectionsFrom returns connections from the given doc that pass the filter

func (*Client) ConnectionsTo

func (c *Client) ConnectionsTo(ctx context.Context, in *apipb.ConnectFilter, opts ...grpc.CallOption) (*apipb.Connections, error)

ConnectionsTo returns connections to the given doc that pass the filter

func (*Client) CreateConnection

func (c *Client) CreateConnection(ctx context.Context, in *apipb.ConnectionConstructor, opts ...grpc.CallOption) (*apipb.Connection, error)

CreateConnection creates a single connection in the graph

Example
dogs, err := client.SearchDocs(context.Background(), &apipb2.Filter{
	Gtype:      "dog",
	Expression: `this.attributes.name.contains("Charl")`,
	Limit:      1,
})
if err != nil {
	fmt.Print(err)
	return
}
charlie := dogs.GetDocs()[0]
coleman, err := client.CreateDoc(context.Background(), &apipb2.DocConstructor{
	Ref: &apipb2.RefConstructor{Gtype: "human"},
	Attributes: apipb2.NewStruct(map[string]interface{}{
		"name": "Coleman",
	}),
})
if err != nil {
	fmt.Print(err)
	return
}
ownerConnection, err := client.CreateConnection(context.Background(), &apipb2.ConnectionConstructor{
	Ref: &apipb2.RefConstructor{Gtype: "owner"},
	Attributes: apipb2.NewStruct(map[string]interface{}{
		"primary_owner": true,
	}),
	From: charlie.Ref,
	To:   coleman.Ref,
})
if err != nil {
	fmt.Print(err)
	return
}
has, err := client.HasConnection(context.Background(), ownerConnection.Ref)
if err != nil {
	fmt.Print(err)
	return
}
if !has.GetValue() {
	fmt.Print("failed to find owner connection: ", ownerConnection.Ref.String())
	return
}
exists, err := client.ExistsConnection(context.Background(), &apipb2.ExistsFilter{
	Gtype:      "owner",
	Expression: "this.attributes.primary_owner",
})
if err != nil {
	fmt.Print(err)
	return
}
if !exists.GetValue() {
	fmt.Print("failed to find owner connection: ", ownerConnection.Ref.String())
	return
}
primary := ownerConnection.Attributes.Fields["primary_owner"].GetBoolValue()
fmt.Println(primary)
Output:

true

func (*Client) CreateConnections

func (c *Client) CreateConnections(ctx context.Context, in *apipb.ConnectionConstructors, opts ...grpc.CallOption) (*apipb.Connections, error)

CreateConnections creates 1-many connections in the graph

func (*Client) CreateDoc

func (c *Client) CreateDoc(ctx context.Context, in *apipb.DocConstructor, opts ...grpc.CallOption) (*apipb.Doc, error)

CreateDoc creates a single doc in the graph

Example
ctx := context.Background()
charlie, err := client.CreateDoc(ctx, &apipb2.DocConstructor{
	Ref: &apipb2.RefConstructor{Gtype: "dog"},
	Attributes: apipb2.NewStruct(map[string]interface{}{
		"name":   "Charlie",
		"weight": 18,
	}),
})
if err != nil {
	fmt.Print("createDoc: ", err)
	return
}
has, err := client.HasDoc(ctx, charlie.GetRef())
if err != nil {
	fmt.Print("hasDoc: ", err)
	return
}
if !has.GetValue() {
	fmt.Print("failed to find charlie")
	return
}
exists, err := client.ExistsDoc(ctx, &apipb2.ExistsFilter{
	Gtype:      "dog",
	Expression: "this.attributes.name.contains('Charlie')",
})
if err != nil {
	fmt.Print("existsDoc: ", err)
	return
}
if !exists.GetValue() {
	fmt.Print("failed to find charlie")
	return
}
name := charlie.Attributes.Fields["name"].GetStringValue()
fmt.Println(name)
Output:

Charlie

func (*Client) CreateDocs

func (c *Client) CreateDocs(ctx context.Context, in *apipb.DocConstructors, opts ...grpc.CallOption) (*apipb.Docs, error)

CreateDocs creates 1-many documents in the graph

func (*Client) DelConnection

func (c *Client) DelConnection(ctx context.Context, in *apipb.Ref, opts ...grpc.CallOption) error

DelConnection deletes a single connection that pass a Filter

func (*Client) DelConnections

func (c *Client) DelConnections(ctx context.Context, in *apipb.Filter, opts ...grpc.CallOption) error

DelConnections deletes 0-many connections that pass a Filter

Example
ctx := context.Background()
err := client.DelConnections(ctx, &apipb2.Filter{
	Gtype:      "owner",
	Expression: "this.attributes.primary_owner",
	Limit:      10,
})
if err != nil {
	fmt.Print(err)
	return
}
fmt.Println("Success!")
Output:

Success!

func (*Client) DelDoc

func (c *Client) DelDoc(ctx context.Context, in *apipb.Ref, opts ...grpc.CallOption) error

DelDoc deletes a doc by reference

func (*Client) DelDocs

func (c *Client) DelDocs(ctx context.Context, in *apipb.Filter, opts ...grpc.CallOption) error

DelDocs deletes 0-many docs that pass a Filter

Example
ctx := context.Background()
err := client.DelDocs(ctx, &apipb2.Filter{
	Gtype:      "dog",
	Expression: "this.attributes.name == 'Charlie'",
	Limit:      10,
})
if err != nil {
	fmt.Print(err)
	return
}
fmt.Println("Success!")
Output:

Success!

func (*Client) EditConnection

func (c *Client) EditConnection(ctx context.Context, in *apipb.Edit, opts ...grpc.CallOption) (*apipb.Connection, error)

EditConnection edites a single connection in the graph

func (*Client) EditConnections

func (c *Client) EditConnections(ctx context.Context, in *apipb.EditFilter, opts ...grpc.CallOption) (*apipb.Connections, error)

EditConnections edites 0-many connections in the graph

func (*Client) EditDoc

func (c *Client) EditDoc(ctx context.Context, in *apipb.Edit, opts ...grpc.CallOption) (*apipb.Doc, error)

EditDoc edites a single doc in the graph

Example
dogs, err := client.SearchDocs(context.Background(), &apipb2.Filter{
	Gtype:      "dog",
	Expression: `this.attributes.name.contains("Charl")`,
	Limit:      1,
})
if err != nil {
	fmt.Print(err)
	return
}
charlie := dogs.GetDocs()[0]
charlie, err = client.EditDoc(context.Background(), &apipb2.Edit{
	Ref: charlie.Ref,
	Attributes: apipb2.NewStruct(map[string]interface{}{
		"weight": 25,
	}),
})
if err != nil {
	fmt.Print(err)
	return
}
fmt.Println(charlie.GetAttributes().GetFields()["weight"].GetNumberValue())
Output:

25

func (*Client) EditDocs

func (c *Client) EditDocs(ctx context.Context, in *apipb.EditFilter, opts ...grpc.CallOption) (*apipb.Docs, error)

EditDocs edites 0-many docs in the graph

func (*Client) ExistsConnection

func (c *Client) ExistsConnection(ctx context.Context, in *apipb.ExistsFilter, opts ...grpc.CallOption) (*apipb.Boolean, error)

ExistsConnection checks if a connection exists in the graph

func (*Client) ExistsDoc

func (c *Client) ExistsDoc(ctx context.Context, in *apipb.ExistsFilter, opts ...grpc.CallOption) (*apipb.Boolean, error)

ExistsDoc checks if a doc exists in the graph

func (*Client) GetConnection

func (c *Client) GetConnection(ctx context.Context, in *apipb.Ref, opts ...grpc.CallOption) (*apipb.Connection, error)

GetConnection gets a connection at the given ref

func (*Client) GetDoc

func (c *Client) GetDoc(ctx context.Context, in *apipb.Ref, opts ...grpc.CallOption) (*apipb.Doc, error)

GetDoc gets a doc at the given ref

func (*Client) GetSchema

func (c *Client) GetSchema(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*apipb.Schema, error)

GetSchema gets information about node/connection types, type-validators, indexes, and authorizers

Example
schema, err := client.GetSchema(context.Background(), &empty.Empty{})
if err != nil {
	fmt.Print(err)
	return
}
fmt.Printf("doc types: %s\n", strings.Join(schema.DocTypes, ","))
fmt.Printf("connection types: %s\n", strings.Join(schema.ConnectionTypes, ","))
var authorizers []string
for _, a := range schema.GetAuthorizers().GetAuthorizers() {
	authorizers = append(authorizers, a.Name)
}
fmt.Printf("authorizers: %s", strings.Join(authorizers, ","))
Output:

doc types: dog,human,note,user
connection types: created,created_by,edited,edited_by,owner
authorizers: testing-request

func (*Client) HasConnection

func (c *Client) HasConnection(ctx context.Context, in *apipb.Ref, opts ...grpc.CallOption) (*apipb.Boolean, error)

HasConnection checks if a connection exists in the graph by reference

func (*Client) HasDoc

func (c *Client) HasDoc(ctx context.Context, in *apipb.Ref, opts ...grpc.CallOption) (*apipb.Boolean, error)

HasDoc checks if a doc exists in the graph by reference

Example
ctx := context.Background()
me, err := client.Me(ctx, &empty.Empty{})
if err != nil {
	fmt.Print(err)
	return
}
has, err := client.HasDoc(ctx, me.GetRef())
if err != nil {
	fmt.Print(err)
	return
}
fmt.Println(has.GetValue())
Output:

true

func (*Client) JoinCluster

func (c *Client) JoinCluster(ctx context.Context, peer *apipb.Peer, opts ...grpc.CallOption) error

AddPeer adds a peer node to the raft cluster.

func (*Client) Me

func (c *Client) Me(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*apipb.Doc, error)

Me returns a Doc of the currently logged in user

Example
me, err := client.Me(context.Background(), &empty.Empty{})
if err != nil {
	fmt.Print(err)
	return
}
issuer := me.GetAttributes().GetFields()["sub"].GetStringValue() // token issuer
fmt.Println(issuer)
Output:

107146673535247272789

func (*Client) Ping

func (c *Client) Ping(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*apipb.Pong, error)

Ping checks if the server is healthy.

Example
ctx := context.Background()
msg, err := client.Ping(ctx, &empty.Empty{})
if err != nil {
	fmt.Println(err.Error())
	return
}
fmt.Println(msg.Message)
Output:

PONG

func (*Client) PushConnectionConstructors

func (c *Client) PushConnectionConstructors(ctx context.Context, ch <-chan *apipb.ConnectionConstructor, opts ...grpc.CallOption) error

PushConnectionConstructors streams connection constructors to & from the graph as they are created

func (*Client) PushDocConstructors

func (c *Client) PushDocConstructors(ctx context.Context, ch <-chan *apipb.DocConstructor, opts ...grpc.CallOption) error

PushDocConstructors streams doc constructors to & from the graph as they are created

func (*Client) PutConnection

func (c *Client) PutConnection(ctx context.Context, in *apipb.Connection, opts ...grpc.CallOption) (*apipb.Connection, error)

PutConnection create-or-replaces a Connection in the graph

func (*Client) PutConnections

func (c *Client) PutConnections(ctx context.Context, in *apipb.Connections, opts ...grpc.CallOption) (*apipb.Connections, error)

PutConnections puts a batch of connections in the graph

func (*Client) PutDoc

func (c *Client) PutDoc(ctx context.Context, in *apipb.Doc, opts ...grpc.CallOption) (*apipb.Doc, error)

PutDocs puts a batch of docs in the graph

Example
note33, err := client.PutDoc(context.Background(), &apipb2.Doc{
	Ref: &apipb2.Ref{
		Gtype: "note",
		Gid:   "note33",
	},
	Attributes: apipb2.NewStruct(map[string]interface{}{
		"title": "this is a note",
	}),
})
if err != nil {
	fmt.Print(err)
	return
}
has, err := client.HasDoc(context.Background(), note33.Ref)
if err != nil {
	fmt.Print(err)
	return
}
fmt.Println(has.Value)
Output:

true

func (*Client) PutDocs

func (c *Client) PutDocs(ctx context.Context, in *apipb.Docs, opts ...grpc.CallOption) (*apipb.Docs, error)

PutDoc creates a Doc if it doesnt exist already, otherwise it replaces it

func (*Client) SearchAndConnect

func (c *Client) SearchAndConnect(ctx context.Context, in *apipb.SearchConnectFilter, opts ...grpc.CallOption) (*apipb.Connections, error)

SearchAndConnect searches for documents and forms connections based on whether they pass a filter

func (*Client) SearchAndConnectMe

func (c *Client) SearchAndConnectMe(ctx context.Context, in *apipb.SearchConnectMeFilter, opts ...grpc.CallOption) (*apipb.Connections, error)

SearchAndConnectMe searches for documents and forms connections between the origin user & the document based on whether they pass a filter

func (*Client) SearchConnections

func (c *Client) SearchConnections(ctx context.Context, in *apipb.Filter, opts ...grpc.CallOption) (*apipb.Connections, error)

SearchConnections searches for 0-many connections

Example
owners, err := client.SearchConnections(context.Background(), &apipb2.Filter{
	Gtype:      "owner",
	Expression: `this.attributes.primary_owner == true`,
	Sort:       "ref.gtype",
	Limit:      1,
	Index:      "testing",
})
if err != nil {
	fmt.Print(err)
	return
}
coleman := owners.GetConnections()[0]
primary := coleman.Attributes.Fields["primary_owner"].GetBoolValue()
fmt.Println(primary)
Output:

true

func (*Client) SearchDocs

func (c *Client) SearchDocs(ctx context.Context, in *apipb.Filter, opts ...grpc.CallOption) (*apipb.Docs, error)

SearchDocs searches for 0-many docs

Example
dogs, err := client.SearchDocs(context.Background(), &apipb2.Filter{
	Gtype:      "dog",
	Expression: `this.attributes.name.contains("Charl")`,
	Limit:      1,
	Sort:       "ref.gid",
})
if err != nil {
	fmt.Print(err)
	return
}
dog := dogs.GetDocs()[0]
name := dog.Attributes.Fields["name"].GetStringValue()
fmt.Println(name)
Output:

Charlie

func (*Client) SeedConnections

func (c *Client) SeedConnections(ctx context.Context, connectionChan <-chan *apipb.Connection, opts ...grpc.CallOption) error

SeedConnections

func (*Client) SeedDocs

func (c *Client) SeedDocs(ctx context.Context, docChan <-chan *apipb.Doc, opts ...grpc.CallOption) error

SeedDocs

func (*Client) SetAuthorizers

func (c *Client) SetAuthorizers(ctx context.Context, in *apipb.Authorizers, opts ...grpc.CallOption) error

SetAuthorizers sets all of the authorizers in the graph

Example
err := client.SetAuthorizers(context.Background(), &apipb2.Authorizers{
	Authorizers: []*apipb2.Authorizer{
		{
			Name:            "testing-request",
			Method:          "/api.DatabaseService/GetSchema",
			Expression:      `this.user.attributes.email.contains("coleman")`,
			TargetRequests:  true,
			TargetResponses: false,
		},
	},
})
if err != nil {
	fmt.Print(err)
	return
}
schema, err := client.GetSchema(context.Background(), &empty.Empty{})
if err != nil {
	fmt.Print(err)
	return
}
var authorizers []string
for _, a := range schema.GetAuthorizers().GetAuthorizers() {
	authorizers = append(authorizers, a.Name)
}
fmt.Printf("%s", strings.Join(authorizers, ","))
Output:

testing-request

func (*Client) SetConstraints

func (c *Client) SetConstraints(ctx context.Context, in *apipb.Constraints, opts ...grpc.CallOption) error

SetConstraints sets all of the type validators in the graph

Example
err := client.SetConstraints(context.Background(), &apipb2.Constraints{
	Constraints: []*apipb2.Constraint{
		{
			Name:              "testing",
			Gtype:             "dog",
			Expression:        `int(this.attributes.weight) > 0`,
			TargetDocs:        true,
			TargetConnections: false,
		},
	},
})
if err != nil {
	fmt.Print(err)
	return
}
schema, err := client.GetSchema(context.Background(), &empty.Empty{})
if err != nil {
	fmt.Print(err)
	return
}
var validators []string
for _, a := range schema.GetConstraints().GetConstraints() {
	validators = append(validators, a.Name)
}
fmt.Printf("%s", strings.Join(validators, ","))
Output:

testing

func (*Client) SetIndexes

func (c *Client) SetIndexes(ctx context.Context, in *apipb.Indexes, opts ...grpc.CallOption) error

SetIndexes sets all of the indexes in the graph

Example
err := client.SetIndexes(context.Background(), &apipb2.Indexes{
	Indexes: []*apipb2.Index{
		{
			Name:              "testing",
			Gtype:             "owner",
			Expression:        `this.attributes.primary_owner`,
			TargetDocs:        false,
			TargetConnections: true,
		},
	},
})
if err != nil {
	fmt.Print(err)
	return
}
schema, err := client.GetSchema(context.Background(), &empty.Empty{})
if err != nil {
	fmt.Print(err)
	return
}
var indexes []string
for _, a := range schema.GetIndexes().GetIndexes() {
	indexes = append(indexes, a.Name)
}
fmt.Printf("%s", strings.Join(indexes, ","))
Output:

testing

func (*Client) SetTriggers

func (c *Client) SetTriggers(ctx context.Context, in *apipb.Triggers, opts ...grpc.CallOption) error

SetTriggers sets all of the triggers in the graph

func (*Client) Stream

func (c *Client) Stream(ctx context.Context, in *apipb.StreamFilter, handler func(msg *apipb.Message) bool, opts ...grpc.CallOption) error

Stream opens a stream of messages that pass a filter on a pubsub channel

Example
m := machine.New(context.Background())
m.Go(func(routine machine.Routine) {
	err := client.Stream(context.Background(), &apipb2.StreamFilter{
		Channel: "testing",
		// subscribe from 5 minutes in the past(optional)
		Min: timestamppb.New(time.Now().Truncate(5 * time.Minute)),
		// subscribe until 5 minutes into the future(optional)
		Max: timestamppb.New(time.Now().Add(5 * time.Minute)),
		//Expression: `this.data.text.contains("hello")`,
	}, func(msg *apipb2.Message) bool {
		if msg.Data.GetFields()["text"] != nil && msg.Data.GetFields()["text"].GetStringValue() == "hello world" {
			fmt.Println(msg.Data.GetFields()["text"].GetStringValue())
			return false
		}
		return true
	})
	if err != nil {
		fmt.Print("failed to subscribe: ", err.Error())
		return
	}
})
time.Sleep(1 * time.Second)
err := client.Broadcast(context.Background(), &apipb2.OutboundMessage{
	Channel: "testing",
	Data: apipb2.NewStruct(map[string]interface{}{
		"text": "hello world",
	}),
})
if err != nil {
	fmt.Print(err)
	return
}
m.Wait()
Output:

hello world

func (*Client) Traverse

func (c *Client) Traverse(ctx context.Context, in *apipb.TraverseFilter, opts ...grpc.CallOption) (*apipb.Traversals, error)

Traverse searches for 0-many docs using a graph traversal algorithm

Example
me, err := client.Me(context.Background(), &empty.Empty{})
if err != nil {
	fmt.Print(err)
	return
}
ctx := context.Background()
bfsTraversals, err := client.Traverse(ctx, &apipb2.TraverseFilter{
	Root:                 me.GetRef(),
	DocExpression:        "this.attributes.name == 'Charlie'",
	ConnectionExpression: "",
	Limit:                1,
	Sort:                 "",
	Reverse:              false,
	Algorithm:            apipb2.Algorithm_BFS,
	MaxDepth:             1,
	MaxHops:              50,
})
if err != nil {
	fmt.Print(err)
	return
}
fmt.Println(len(bfsTraversals.GetTraversals()))
dfsTraversals, err := client.Traverse(ctx, &apipb2.TraverseFilter{
	Root:                 me.GetRef(),
	DocExpression:        "",
	ConnectionExpression: "",
	Limit:                3,
	Sort:                 "",
	Reverse:              false,
	Algorithm:            apipb2.Algorithm_DFS,
	MaxDepth:             1,
	MaxHops:              50,
})
if err != nil {
	fmt.Print(err)
	return
}
fmt.Println(len(dfsTraversals.GetTraversals()))
Output:

1
3

func (*Client) TraverseMe

func (c *Client) TraverseMe(ctx context.Context, in *apipb.TraverseMeFilter, opts ...grpc.CallOption) (*apipb.Traversals, error)

TraverseMe executes a graph traversal searching for docs related to the currently logged in user

type Opt

type Opt func(o *Options)

func WithLogging

func WithLogging(logging, logPayload bool) Opt

func WithMetrics

func WithMetrics(metrics bool) Opt

func WithRaftSecret

func WithRaftSecret(raftSecret string) Opt

func WithRetry

func WithRetry(retry uint) Opt

func WithTokenSource

func WithTokenSource(tokenSource oauth2.TokenSource) Opt

func WithTransportCreds added in v1.1.2

func WithTransportCreds(creds credentials.TransportCredentials) Opt

type Options

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

Jump to

Keyboard shortcuts

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