ddp

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Sep 6, 2021 License: ISC Imports: 12 Imported by: 32

README

ddp

MeteorJS DDP library for Golang

Documentation

Overview

Package ddp implements the MeteorJS DDP protocol over websockets. Fallback to longpolling is NOT supported (and is not planned on ever being supported by this library). We will try to model the library after `net/http` - right now the library is barebones and doesn't provide the pluggability of http. However, that's the goal for the package eventually.

Index

Constants

View Source
const (
	DISCONNECTED = iota
	DIALING
	CONNECTING
	CONNECTED
)
View Source
const (
	DataByte = iota // data is raw []byte
	DataText        // data is string data
)

Logging data types

Variables

This section is empty.

Functions

This section is empty.

Types

type Call

type Call struct {
	ID            string      // The uuid for this method call
	ServiceMethod string      // The name of the service and method to call.
	Args          interface{} // The argument to the function (*struct).
	Reply         interface{} // The reply from the function (*struct).
	Error         error       // After completion, the error status.
	Done          chan *Call  // Strobes when call is complete.
	Owner         *Client     // Client that owns the method call
}

Call represents an active RPC call.

type Client

type Client struct {
	// HeartbeatInterval is the time between heartbeats to send
	HeartbeatInterval time.Duration
	// HeartbeatTimeout is the time for a heartbeat ping to timeout
	HeartbeatTimeout time.Duration
	// ReconnectInterval is the time between reconnections on bad connections
	ReconnectInterval time.Duration
	// contains filtered or unexported fields
}

Client represents a DDP client connection. The DDP client establish a DDP session and acts as a message pump for other tools.

func NewClient

func NewClient(url, origin string) *Client

NewClient creates a default client (using an internal websocket) to the provided URL using the origin for the connection. The client will automatically connect, upgrade to a websocket, and establish a DDP connection session before returning the client. The client will automatically and internally handle heartbeats and reconnects.

TBD create an option to use an external websocket (aka htt.Transport) TBD create an option to substitute heartbeat and reconnect behavior (aka http.Tranport) TBD create an option to hijack the connection (aka http.Hijacker) TBD create profiling features (aka net/http/pprof)

func (*Client) AddConnectionListener

func (c *Client) AddConnectionListener(listener ConnectionListener)

AddConnectionListener in order to receive connection updates.

func (*Client) AddStatusListener

func (c *Client) AddStatusListener(listener StatusListener)

AddStatusListener in order to receive status change updates.

func (*Client) Call

func (c *Client) Call(serviceMethod string, args ...interface{}) (interface{}, error)

Call invokes the named function, waits for it to complete, and returns its error status.

func (*Client) Close

func (c *Client) Close()

Close implements the io.Closer interface.

func (*Client) CollectionByName

func (c *Client) CollectionByName(name string) Collection

CollectionByName retrieves a collection by it's name.

func (*Client) CollectionStats

func (c *Client) CollectionStats() []CollectionStats

CollectionStats returns a snapshot of statistics for the currently known collections.

func (*Client) Connect

func (c *Client) Connect() error

Connect attempts to connect the client to the server.

func (*Client) Go

func (c *Client) Go(serviceMethod string, done chan *Call, args ...interface{}) *Call

Go invokes the function asynchronously. It returns the Call structure representing the invocation. The done channel will signal when the call is complete by returning the same Call object. If done is nil, Go will allocate a new channel. If non-nil, done must be buffered or Go will deliberately crash.

Go and Call are modeled after the standard `net/rpc` package versions.

func (*Client) Ping

func (c *Client) Ping()

Ping sends a heartbeat signal to the server. The Ping doesn't look for a response but may trigger the connection to reconnect if the ping timesout. This is primarily useful for reviving an unresponsive Client connection.

func (*Client) PingPong

func (c *Client) PingPong(id string, timeout time.Duration, handler func(error))

PingPong sends a heartbeat signal to the server and calls the provided function when a pong is received. An optional id can be sent to help track the responses - or an empty string can be used. It is the responsibility of the caller to respond to any errors that may occur.

func (*Client) Reconnect

func (c *Client) Reconnect()

Reconnect attempts to reconnect the client to the server on the existing DDP session.

TODO needs a reconnect backoff so we don't trash a down server TODO reconnect should not allow more reconnects while a reconnection is already in progress.

func (*Client) ResetStats

func (c *Client) ResetStats()

ResetStats resets the statistics for the client.

func (*Client) Send

func (c *Client) Send(msg interface{}) error

Send transmits messages to the server. The msg parameter must be json encoder compatible.

func (*Client) Session

func (c *Client) Session() string

Session returns the negotiated session token for the connection.

func (*Client) SetSocketLogActive

func (c *Client) SetSocketLogActive(active bool)

SetSocketLogActive to true to enable logging of raw socket data.

func (*Client) SocketLogActive

func (c *Client) SocketLogActive() bool

SocketLogActive returns the current logging status for the socket.

func (*Client) Stats

func (c *Client) Stats() *ClientStats

Stats returns the read and write statistics of the client.

func (*Client) Sub

func (c *Client) Sub(subName string, args ...interface{}) error

Sub sends a synchronous subscription request to the server.

func (*Client) Subscribe

func (c *Client) Subscribe(subName string, done chan *Call, args ...interface{}) *Call

Subscribe subscribes to data updates.

func (*Client) Version

func (c *Client) Version() string

Version returns the negotiated protocol version in use by the client.

type ClientStats

type ClientStats struct {
	// Reads provides statistics on the raw i/o network reads for the current connection.
	Reads *Stats
	// Reads provides statistics on the raw i/o network reads for the all client connections.
	TotalReads *Stats
	// Writes provides statistics on the raw i/o network writes for the current connection.
	Writes *Stats
	// Writes provides statistics on the raw i/o network writes for all the client connections.
	TotalWrites *Stats
	// Reconnects is the number of reconnections the client has made.
	Reconnects int64
	// PingsSent is the number of pings sent by the client
	PingsSent int64
	// PingsRecv is the number of pings received by the client
	PingsRecv int64
}

ClientStats displays combined statistics for the Client.

func (*ClientStats) String

func (stats *ClientStats) String() string

String produces a compact string representation of the client stats.

type Collection

type Collection interface {

	// FindOne queries objects and returns the first match.
	FindOne(id string) Update
	// FindAll returns a map of all items in the cache - this is a hack
	// until we have time to build out a real minimongo interface.
	FindAll() map[string]Update
	// AddUpdateListener adds a channel that receives update messages.
	AddUpdateListener(listener UpdateListener)
	// contains filtered or unexported methods
}

Collection managed cached collection data sent from the server in a livedata subscription.

It would be great to build an entire mongo compatible local store (minimongo)

func NewCollection

func NewCollection(name string) Collection

NewCollection creates a new collection - always KeyCache.

func NewMockCollection

func NewMockCollection() Collection

NewMockCollection creates an empty collection that does nothing.

type CollectionStats

type CollectionStats struct {
	Name  string // Name of the collection
	Count int    // Count is the total number of documents in the collection
}

CollectionStats combines statistics about a collection.

func (*CollectionStats) String

func (s *CollectionStats) String() string

String produces a compact string representation of the collection stat.

type Connect

type Connect struct {
	Message
	Version string   `json:"version"`
	Support []string `json:"support"`
	Session string   `json:"session,omitempty"`
}

Connect represents a DDP connect message.

func NewConnect

func NewConnect() *Connect

NewConnect creates a new connect message

func NewReconnect

func NewReconnect(session string) *Connect

NewReconnect creates a new connect message with a session ID to resume.

type ConnectionListener

type ConnectionListener interface {
	Connected()
}

type ConnectionNotifier

type ConnectionNotifier interface {
	AddConnectionListener(listener ConnectionListener)
}

type Doc

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

Doc provides hides the complexity of ejson documents.

func NewDoc

func NewDoc(in interface{}) *Doc

NewDoc creates a new document from a generic json parsed document.

func (*Doc) Array

func (d *Doc) Array(path string) []interface{}

Array locates an []interface{} - json array - at a path or returns nil if not found.

func (*Doc) Bool

func (d *Doc) Bool(path string) bool

Bool returns a boolean value located at the path or false if not found.

func (*Doc) Float

func (d *Doc) Float(path string) float64

Float returns a float64 value located at the path or zero if not found.

func (*Doc) Item

func (d *Doc) Item(path string) interface{}

Item locates a "raw" item at the provided path, returning the item found or nil if not found.

func (*Doc) Map

func (d *Doc) Map(path string) map[string]interface{}

Map locates a map[string]interface{} - json object - at a path or returns nil if not found.

func (*Doc) Set

func (d *Doc) Set(path string, value interface{})

Set a value for a path. Intermediate items are created as necessary.

func (*Doc) String

func (d *Doc) String(path string) string

String returns a string value located at the path or an empty string if not found.

func (*Doc) StringArray

func (d *Doc) StringArray(path string) []string

StringArray locates an []string - json array of strings - at a path or returns nil if not found. The string array will contain all string values in the array and skip any non-string entries.

func (*Doc) Time

func (d *Doc) Time(path string) time.Time

Time returns a time value located at the path or nil if not found.

type KeyCache

type KeyCache struct {
	// The name of the collection
	Name string
	// contains filtered or unexported fields
}

KeyCache caches items keyed on unique ID.

func (*KeyCache) AddUpdateListener

func (c *KeyCache) AddUpdateListener(listener UpdateListener)

AddUpdateListener adds a listener for changes on a collection.

func (*KeyCache) FindAll

func (c *KeyCache) FindAll() map[string]Update

FindAll returns a dump of all items in the collection

func (*KeyCache) FindOne

func (c *KeyCache) FindOne(id string) Update

FindOne returns the item with matching id.

type Logger

type Logger struct {
	// Active is true if the logger should be logging reads
	Active bool
	// Truncate is >0 to indicate the number of characters to truncate output
	Truncate int
	// contains filtered or unexported fields
}

Logger logs data from i/o sources.

func NewLogger

func NewLogger(logger *log.Logger, active bool, dataType int, truncate int) Logger

NewLogger creates a new i/o logger.

func (*Logger) Log

func (l *Logger) Log(p []byte, n int, err error) (int, error)

Log logs the current i/o operation and returns the read and error for easy call chaining.

type Login

type Login struct {
	User     *User     `json:"user"`
	Password *Password `json:"password"`
}

Accounts password login support

func NewEmailLogin

func NewEmailLogin(email, pass string) *Login

func NewUsernameLogin

func NewUsernameLogin(user, pass string) *Login

type LoginResume

type LoginResume struct {
	Token string `json:"resume"`
}

func NewLoginResume

func NewLoginResume(token string) *LoginResume

type Message

type Message struct {
	Type string `json:"msg"`
	ID   string `json:"id,omitempty"`
}

Message contains the common fields that all DDP messages use.

type Method

type Method struct {
	Message
	ServiceMethod string        `json:"method"`
	Args          []interface{} `json:"params"`
}

Method is used to send a remote procedure call to the server.

func NewMethod

func NewMethod(id, serviceMethod string, args []interface{}) *Method

NewMethod creates a new method invocation object.

type MockCache

type MockCache struct {
}

MockCache implements the Collection interface but does nothing with the data.

func (*MockCache) AddUpdateListener

func (c *MockCache) AddUpdateListener(ch UpdateListener)

AddUpdateListener does nothing.

func (*MockCache) FindAll

func (c *MockCache) FindAll() map[string]Update

FindAll returns a dump of all items in the collection

func (*MockCache) FindOne

func (c *MockCache) FindOne(id string) Update

FindOne returns the item with matching id.

type OrderedCache

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

OrderedCache caches items based on list order. This is a placeholder, currently not implemented as the Meteor server does not transmit ordered collections over DDP yet.

func (*OrderedCache) AddUpdateListener

func (c *OrderedCache) AddUpdateListener(ch UpdateListener)

AddUpdateListener does nothing.

func (*OrderedCache) FindAll

func (c *OrderedCache) FindAll() map[string]Update

FindAll returns a dump of all items in the collection

func (*OrderedCache) FindOne

func (c *OrderedCache) FindOne(id string) Update

FindOne returns the item with matching id.

type Password

type Password struct {
	Digest    string `json:"digest"`
	Algorithm string `json:"algorithm"`
}

func NewPassword

func NewPassword(pass string) *Password

type Ping

type Ping Message

Ping represents a DDP ping message.

func NewPing

func NewPing(id string) *Ping

NewPing creates a new ping message with optional ID.

type Pong

type Pong Message

Pong represents a DDP pong message.

func NewPong

func NewPong(id string) *Pong

NewPong creates a new pong message with optional ID.

type ReaderLogger

type ReaderLogger struct {
	Logger
	ReaderProxy
}

ReaderLogger logs data from any io.Reader. ReaderLogger wraps a Reader and passes data to the actual data consumer.

func NewReaderDataLogger

func NewReaderDataLogger(reader io.Reader) *ReaderLogger

NewReaderDataLogger creates an active binary data logger with a default log.Logger and a '->' prefix.

func NewReaderLogger

func NewReaderLogger(reader io.Reader, logger *log.Logger, active bool, dataType int, truncate int) *ReaderLogger

NewReaderLogger creates a Reader logger for the provided parameters.

func NewReaderTextLogger

func NewReaderTextLogger(reader io.Reader) *ReaderLogger

NewReaderTextLogger creates an active binary data logger with a default log.Logger and a '->' prefix.

func (*ReaderLogger) Read

func (r *ReaderLogger) Read(p []byte) (int, error)

Read logs the read bytes and passes them to the wrapped reader.

type ReaderProxy

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

ReaderProxy provides common tooling for structs that manage an io.Reader.

func NewReaderProxy

func NewReaderProxy(reader io.Reader) *ReaderProxy

NewReaderProxy creates a new proxy for the provided reader.

func (*ReaderProxy) SetReader

func (r *ReaderProxy) SetReader(reader io.Reader)

SetReader sets the reader on the proxy.

type ReaderStats

type ReaderStats struct {
	StatsTracker
	ReaderProxy
}

ReaderStats tracks statistics on any io.Reader. ReaderStats wraps a Reader and passes data to the actual data consumer.

func NewReaderStats

func NewReaderStats(reader io.Reader) *ReaderStats

NewReaderStats creates a ReaderStats object for the provided reader.

func (*ReaderStats) Read

func (r *ReaderStats) Read(p []byte) (int, error)

Read passes through a read collecting statistics and logging activity.

type Stats

type Stats struct {
	// Bytes is the total number of bytes transferred.
	Bytes int64
	// Ops is the total number of i/o operations performed.
	Ops int64
	// Errors is the total number of i/o errors encountered.
	Errors int64
	// Runtime is the duration that stats have been gathered.
	Runtime time.Duration
}

Stats tracks statistics for i/o operations. Stats are produced from a of a running stats agent.

type StatsTracker

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

StatsTracker provides the basic tooling for tracking i/o stats.

func NewStatsTracker

func NewStatsTracker() *StatsTracker

NewStatsTracker create a new stats tracker with start time set to now.

func (*StatsTracker) Op

func (t *StatsTracker) Op(n int, err error) (int, error)

Op records an i/o operation. The parameters are passed through to allow easy chaining.

func (*StatsTracker) Reset

func (t *StatsTracker) Reset() *Stats

Reset sets all of the stats to initial values.

func (*StatsTracker) Snapshot

func (t *StatsTracker) Snapshot() *Stats

Snapshot takes a snapshot of the current reader statistics.

type StatusListener

type StatusListener interface {
	Status(status int)
}

type StatusNotifier

type StatusNotifier interface {
	AddStatusListener(listener StatusListener)
}

type Sub

type Sub struct {
	Message
	SubName string        `json:"name"`
	Args    []interface{} `json:"params"`
}

Sub is used to send a subscription request to the server.

func NewSub

func NewSub(id, subName string, args []interface{}) *Sub

NewSub creates a new sub object.

type Update

type Update map[string]interface{}

type UpdateListener

type UpdateListener interface {
	CollectionUpdate(collection, operation, id string, doc Update)
}

type User

type User struct {
	Email    string `json:"email,omitempty"`
	Username string `json:"username,omitempty"`
}

type WriterLogger

type WriterLogger struct {
	Logger
	WriterProxy
}

WriterLogger logs data from any io.Writer. WriterLogger wraps a Writer and passes data to the actual data producer.

func NewWriterDataLogger

func NewWriterDataLogger(writer io.Writer) *WriterLogger

NewWriterDataLogger creates an active binary data logger with a default log.Logger and a '->' prefix.

func NewWriterLogger

func NewWriterLogger(writer io.Writer, logger *log.Logger, active bool, dataType int, truncate int) *WriterLogger

NewWriterLogger creates a Reader logger for the provided parameters.

func NewWriterTextLogger

func NewWriterTextLogger(writer io.Writer) *WriterLogger

NewWriterTextLogger creates an active binary data logger with a default log.Logger and a '->' prefix.

func (*WriterLogger) Write

func (w *WriterLogger) Write(p []byte) (int, error)

Write logs the written bytes and passes them to the wrapped writer.

type WriterProxy

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

WriterProxy provides common tooling for structs that manage an io.Writer.

func NewWriterProxy

func NewWriterProxy(writer io.Writer) *WriterProxy

NewWriterProxy creates a new proxy for the provided writer.

func (*WriterProxy) SetWriter

func (w *WriterProxy) SetWriter(writer io.Writer)

SetWriter sets the writer on the proxy.

type WriterStats

type WriterStats struct {
	StatsTracker
	WriterProxy
}

WriterStats tracks statistics on any io.Writer. WriterStats wraps a Writer and passes data to the actual data producer.

func NewWriterStats

func NewWriterStats(writer io.Writer) *WriterStats

NewWriterStats creates a WriterStats object for the provided writer.

func (*WriterStats) Write

func (w *WriterStats) Write(p []byte) (int, error)

Write passes through a write collecting statistics.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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