zrpc

package
v0.0.0-...-aa698f8 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2025 License: BSD-3-Clause Imports: 26 Imported by: 0

Documentation

Index

Constants

View Source
const PollRestartSecs = 10 // PollRestartSecs is how long to wait asking for a call, before doing a new poll.

Variables

View Source
var (
	MainResources     = new(Resources)
	MainResourceCalls = &ZRPCResourceCalls{Resources: MainResources}
)
View Source
var (
	NoCallForTokenErr       = errors.New("NoCallForTokenErr")
	EnableLogReverseClient  zlog.Enabler
	MainReverseClientsOwner *ReverseClientsOwner
)
View Source
var EnableLogExecute zlog.Enabler
View Source
var (
	EnableLogExecutor zlog.Enabler = false
)
View Source
var ExecuteTimedOutError = TransportError("Execution timed out")

Functions

func AddToTemporaryServe

func AddToTemporaryServe(data []byte) int64

AddToTemporaryServe adds some data to be served within a few seconds, returning a unique id. Client.RequestTemporaryServe requests it with that id.

func FuncForAll

func FuncForAll(r *ReverseClientsOwner, idWildcard, callID string, do func(receiverID string, rc *ReverseClient, i int))

FuncForAll iterates through all r.allReverseClients (which are typically open browsers sessions) If their id matches idWildcard, and there isn't already a call registered for callID, The do function is called with rc.ReverseClient, so the func can use the user's authentication token. It is used by CallAll() above to do a an rpc call to all.

func RegisterResources

func RegisterResources(resources ...string)

func RemoveReverseClient

func RemoveReverseClient(r *ReverseClientsOwner, receiverID string)

func ReverseCallAllSimple

func ReverseCallAllSimple(timeoutSecs float64, method, idWildcard string, args any) []error

func SetResourceUpdated

func SetResourceUpdated(resID, byClientID string)

SetResourceUpdatedmarks a given resource as changed. If a client id is given, that client is NOT informed the resource changed (presumably because it caused the change).

Types

type CallPayload

type CallPayload struct {
	ClientID string
	Method   string
	Args     interface{}
	Token    string `json:",omitempty"`
	Expires  time.Time
}

CallPayload is what a call is packaged into and serialized to json

type CallsBase

type CallsBase struct{} // CallsBase is just a dummy type one can derive from when defining a type to add methods to for registation. You don't need to use it.

type Client

type Client struct {
	AuthToken                        string  // AuthToken is the token sent with the rpc call to authenticate or identify (for reverse calls)
	HandleAuthenticationFailedFunc   func()  // HandleAuthenticationFailedFunc is called if authentication fails
	TimeoutSecs                      float64 // A new client with a different timeout can be created. This is total time of comminication to server, execution, and returning the result
	KeepTokenOnAuthenticationInvalid bool    // if KeepTokenOnAuthenticationInvalid is true, the auth token isn't cleared on failure to authenticate
	SkipVerifyCertificate            bool    // if true, no certificate checking is done for https calls
	PrefixURL                        string  // Stores PrefixURL, so easy to compare if it needs changing

	ID string
	// contains filtered or unexported fields
}

Client is a type used to perform rpc calls

var (
	MainClient *Client

	EnableLogClient zlog.Enabler
)

MainClient is the main, default client. Is set in zapp, and used in zusers.

func NewClient

func NewClient(prefixURL string, id string) *Client

NewClient creates a client with a url prefix, adding zrest.AppURLPrefix This is

func (*Client) Call

func (c *Client) Call(method string, input, result any) error

Call is used to execute a remote call. method is Type.MethodName input can be nil if not used, and result can be nil if not used/not in method.

func (*Client) CallGetForUpdatedResources

func (c *Client) CallGetForUpdatedResources(resIDs []string)

func (*Client) CallWithTimeout

func (c *Client) CallWithTimeout(timeoutSecs float64, method string, input, result any) error

CallWithTimeout is a convenience method that calls method with a different timeout

func (*Client) MakeCallURL

func (c *Client) MakeCallURL(name string) string

func (*Client) PollForUpdatedResources

func (c *Client) PollForUpdatedResources(got func(resID string))

func (*Client) RegisterPollGetter

func (c *Client) RegisterPollGetter(resID string, get func())

func (*Client) RequestTemporaryServe

func (c *Client) RequestTemporaryServe(id int64) (io.ReadCloser, error)

RequestTemporaryServe requests to get data bytes with id set up with AddToTemporaryServe() in executor.

type ClientInfo

type ClientInfo struct {
	Type      string // Type is zrpc or zrpc-rev for these calls. Might be something else if used elsewhere.
	ClientID  string // ClientID identifies the rpc client
	Token     string `json:",omitempty"` // Token can be any token, or a authentication token needed to allow the call
	UserID    int64  `json:",omitempty"` // UserID can be a userid gotten when authenticated
	Request   *http.Request
	UserAgent string    `json:",omitempty"`
	IPAddress string    `json:",omitempty"`
	SendDate  time.Time `json:",omitempty"`
	Context   context.Context
}

ClientInfo stores information about the client calling.

type Executor

type Executor struct {
	Authenticator TokenAuthenticator // used to authenticate a token in a RPC call

	IPAddressWhitelist map[string]bool // if non-empty, only ip-addresses in map are allowed to be called from
	ErrorHandler       func(err error) // calls this with errors that happen, for logging etc in system that uses zrpc
	// contains filtered or unexported fields
}

func NewExecutor

func NewExecutor() *Executor

func (*Executor) Error

func (e *Executor) Error(parts ...any) error

func (*Executor) Register

func (e *Executor) Register(callers ...interface{})

Register registers instances of types that have methods in them suitable for being an rpc call. func (t type) Method(<ci ClientInfo>, input, <*result>) error

type MultiCallResult

type MultiCallResult[R any] struct {
	Result     any
	ReceiverID string
	Error      error
}

func ReverseCallAll

func ReverseCallAll[R any](r *ReverseClientsOwner, timeoutSecs float64, method, idWildcard string, args any) []MultiCallResult[R]

type Resources

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

func (*Resources) ClearResourceID

func (r *Resources) ClearResourceID(resID string)

ClearResourceID clears changed status for a resource

func (*Resources) SetClientKnowsResourceUpdated

func (r *Resources) SetClientKnowsResourceUpdated(resID, clientID string)

SetClientKnowsResourceUpdated sets that a given client now knows resource updated

func (*Resources) SetResourceUpdated

func (r *Resources) SetResourceUpdated(resID, byClientID string)

type ReverseClient

type ReverseClient struct {
	ClientUserToken string
	TimeoutSecs     float64 // TimeoutSecs is time from a reverse call is initiated, until it times out if no result/error returned yet
	LastPolled      time.Time
	ErrorHandler    func(err error) // calls this with errors that happen, for logging etc in system that uses zrpc
	// contains filtered or unexported fields
}

It has a ReverseReceiverID, and is used to call to a specific (reverse) client.

func FindOrAddReverseClient

func FindOrAddReverseClient(r *ReverseClientsOwner, receiverID string, token string) *ReverseClient

func NewReverseClient

func NewReverseClient(r *ReverseClientsOwner, receiverID string, userAuthToken string, permanent bool) *ReverseClient

NewReverseClient adds a ReverseClient to allReverseClients. When overriding HandleNewReverseReceiverFunc, you probably call this anyway, but use the ReverseClient.

func (*ReverseClient) Call

func (rc *ReverseClient) Call(method string, args, resultPtr any) error

Call has the same syntax as a regular zrpc Call. See CallWithTimeout() below.

func (*ReverseClient) CallWithTimeout

func (rc *ReverseClient) CallWithTimeout(timeoutSecs float64, method string, args, resultPtr any) error

CallWithTimeout stores a call to be gotten from server, where it is executed, and waits for the server to push back the result: It creates a CallPayload, with a unique token, puts it on the pendingCallsToSend map. ReversePoll from ReverseExecutor will get th payload, execute it on the server, sending the result back with ReversePushResult and putting it on a channel. CallWithTimeout is waiting for a timeout or the result on the channel.

func (*ReverseClient) Error

func (rc *ReverseClient) Error(parts ...any) error

type ReverseClientsOwner

type ReverseClientsOwner struct {
	HandleNewReverseReceiverFunc func(id string, rc *ReverseClient)
	// contains filtered or unexported fields
}

func NewReverseClientsOwner

func NewReverseClientsOwner(executor *Executor) *ReverseClientsOwner

func (*ReverseClientsOwner) ReversePoll

func (r *ReverseClientsOwner) ReversePoll(ci *ClientInfo, receiverID string, cp *CallPayload) error

ReversePoll is called by clients, asking for calls. It first finds the correct ReverseClient using receiverID If the caller has an existing result (rp.Token set), the pendingCall is found in pendingCallsSent using rp.Token, and the call is finished by writing the result to the pendingCall's done channel. If there are calls waiting in pendingCallsToSend, *cp is set and the method returns. Otherwise it waits, intermittently sleeping for a short while, awaiting a call added. It returns without error if no calls waiting, cp.Method will be empty.

func (*ReverseClientsOwner) ReversePushResult

func (r *ReverseClientsOwner) ReversePushResult(rp ReverseResult) error

type ReverseExecutor

type ReverseExecutor struct {
	Executor *Executor
	// contains filtered or unexported fields
}

func NewReverseExecutor

func NewReverseExecutor(pollClient *Client, id string, executor *Executor) *ReverseExecutor

Starts the polling process in the background

func (*ReverseExecutor) Remove

func (r *ReverseExecutor) Remove()

func (*ReverseExecutor) SetOn

func (r *ReverseExecutor) SetOn(on bool)

type ReverseResult

type ReverseResult struct {
	ReverseReceiverID string
	Token             string
	// contains filtered or unexported fields
}

ReverseResult is always sent with a poll. It can contain an existing result (if Token set), or in any case a ReverseReceiverID to identify who is asking for calls.

type RowGetter

type RowGetter func(receiverID string, index int) any

type TokenAuthenticator

type TokenAuthenticator interface {
	IsTokenValid(token string, req *http.Request) (bool, int64)
}

type TransportError

type TransportError string

TransportError is a specific error type. Any problem with the actual transport of an zrpc call is returned as it, so we can check if it's an error returned from the call, or a problem calling.

func (TransportError) Error

func (t TransportError) Error() string

type Unused

type Unused struct{} // Any is used in function definition args/result when argument is not used

type RPCCalls CallsBase // RPCCalls is the type with zrpc's own build-in methods.

type ZRPCResourceCalls

type ZRPCResourceCalls struct {
	Resources *Resources
}

func (*ZRPCResourceCalls) GetURL

func (*ZRPCResourceCalls) GetURL(surl *string, reply *[]byte) error

GetURL is a convenience function to get the contents of a url via the server.

func (*ZRPCResourceCalls) GetUpdatedResourcesAndSetSent

func (rc *ZRPCResourceCalls) GetUpdatedResourcesAndSetSent(ci *ClientInfo, int Unused, reply *[]string) error

GetUpdatedResourcesAndSetSent is called from clients (often browsers) to ask for updated resource-ids The client id is stored as it having checked them out for that given update.

func (*ZRPCResourceCalls) SetResourceUpdatedFromClient

func (r *ZRPCResourceCalls) SetResourceUpdatedFromClient(ci *ClientInfo, resID string) error

SetResourceUpdatedFromClient is called from client to say it knows of update

Jump to

Keyboard shortcuts

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