lib

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2015 License: MIT Imports: 19 Imported by: 0

README

package lib

The core internal functionality behind leaps. Various implementations of DocumentStore and TokenAuthenticator exist to offer different solutions for document access and user authentication.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GenerateStampedUUID added in v0.3.0

func GenerateStampedUUID() string

GenerateStampedUUID - Generates a UUID and prepends a timestamp to it.

func GenerateUUID added in v0.3.0

func GenerateUUID() string

GenerateUUID - Generates a UUID and returns it as a hex encoded string.

Types

type Anarchy

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

Anarchy - Most basic implementation of TokenAuthenticator, everyone has access to everything.

func (*Anarchy) AuthoriseCreate

func (a *Anarchy) AuthoriseCreate(_, _ string) bool

AuthoriseCreate - Always returns true, because anarchy.

func (*Anarchy) AuthoriseJoin

func (a *Anarchy) AuthoriseJoin(_, _ string) bool

AuthoriseJoin - Always returns true, because anarchy.

type Binder

type Binder struct {
	ID string
	// contains filtered or unexported fields
}

Binder - Contains a single document and acts as a broker between multiple readers, writers and the storage strategy.

func NewBinder added in v0.1.0

func NewBinder(
	id string,
	block DocumentStore,
	config BinderConfig,
	errorChan chan<- BinderError,
	log *log.Logger,
	stats *log.Stats,
) (*Binder, error)

NewBinder - Creates a binder targeting an existing document determined via an ID. Must provide a DocumentStore to acquire the document and apply future updates to.

func (*Binder) Close

func (b *Binder) Close()

Close - Close the binder, before closing the client channels the binder will flush changes and store the document.

func (*Binder) Subscribe

func (b *Binder) Subscribe(token string) BinderPortal

Subscribe - Returns a BinderPortal, which represents a contract between a client and the binder. If the subscription was unsuccessful the BinderPortal will contain an error.

type BinderClient

type BinderClient struct {
	Token         string
	TransformChan chan<- OTransform
	MessageChan   chan<- ClientMessage
}

BinderClient - A struct containing information about a connected client and channels used by the binder to push transforms and user updates out.

type BinderConfig

type BinderConfig struct {
	FlushPeriod           int64       `json:"flush_period_ms" yaml:"flush_period_ms"`
	RetentionPeriod       int64       `json:"retention_period_s" yaml:"retention_period_s"`
	ClientKickPeriod      int64       `json:"kick_period_ms" yaml:"kick_period_ms"`
	CloseInactivityPeriod int64       `json:"close_inactivity_period_s" yaml:"close_inactivity_period_s"`
	ModelConfig           ModelConfig `json:"transform_model" yaml:"transform_model"`
}

BinderConfig - Holds configuration options for a binder.

func DefaultBinderConfig

func DefaultBinderConfig() BinderConfig

DefaultBinderConfig - Returns a fully defined Binder configuration with the default values for each field.

type BinderError

type BinderError struct {
	ID  string
	Err error
}

BinderError - A binder has encountered a problem and needs to close. In order for this to happen it needs to inform its owner that it should be shut down. BinderError is a structure used to carry our error message and our ID over an error channel. A BinderError with the Err set to nil can be used as a graceful shutdown request.

type BinderPortal

type BinderPortal struct {
	Token            string
	Document         Document
	Version          int
	Error            error
	TransformRcvChan <-chan OTransform
	MessageRcvChan   <-chan ClientMessage
	TransformSndChan chan<- TransformSubmission
	MessageSndChan   chan<- MessageSubmission
	ExitChan         chan<- string
}

BinderPortal - A container that holds all data necessary to begin an open portal with the binder, allowing fresh transforms to be submitted and returned as they come. Also carries the token of the client.

func (*BinderPortal) Exit added in v0.1.0

func (p *BinderPortal) Exit(timeout time.Duration)

Exit - Inform the binder that this client is shutting down.

func (*BinderPortal) SendMessage added in v0.1.0

func (p *BinderPortal) SendMessage(message ClientMessage)

SendMessage - Sends a message to the binder, which is subsequently sent out to all other clients. This is safe to call from any goroutine.

func (*BinderPortal) SendTransform

func (p *BinderPortal) SendTransform(ot OTransform, timeout time.Duration) (int, error)

SendTransform - Submits a transform to the binder. The binder responds with either an error or a corrected version number for the transform. This is safe to call from any goroutine.

type BinderSubscribeBundle

type BinderSubscribeBundle struct {
	Token         string
	PortalRcvChan chan<- BinderPortal
}

BinderSubscribeBundle - A container that holds all data necessary to provide a binder that you wish to subscribe to. Contains a user token for identifying the client and a channel for receiving the resultant BinderPortal.

type ClientMessage added in v0.1.0

type ClientMessage struct {
	Message  string `json:"message,omitempty" yaml:"message,omitempty"`
	Position *int64 `json:"position,omitempty" yaml:"position,omitempty"`
	Active   bool   `json:"active" yaml:"active"`
	Token    string `json:"user_id" yaml:"user_id"`
}

ClientMessage - A struct containing various updates to a clients' state and an optional message to be distributed out to all other clients of a binder.

type Curator

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

Curator - A structure designed to keep track of a live collection of Binders. Assists prospective clients in locating their target Binders, and when necessary creates new Binders.

The curator is fully in control of the binders, and manages their life cycles internally.

func NewCurator added in v0.1.0

func NewCurator(
	config CuratorConfig,
	log *log.Logger,
	stats *log.Stats,
	auth TokenAuthenticator,
	store DocumentStore,
) (*Curator, error)

NewCurator - Creates and returns a fresh curator, and launches its internal loop.

func (*Curator) Close

func (c *Curator) Close()

Close - Shut the curator and all subsequent binders down. This call blocks until the shut down is finished, and you must ensure that this curator cannot be accessed after closing.

func (*Curator) CreateDocument added in v0.1.2

func (c *Curator) CreateDocument(token string, userID string, doc Document) (BinderPortal, error)

CreateDocument - Creates a fresh Binder for a new document, which is subsequently stored, returns an error if either the document ID is already currently in use, or if there is a problem storing the new document. May require authentication, if so a userID is supplied.

func (*Curator) FindDocument

func (c *Curator) FindDocument(token, id string) (BinderPortal, error)

FindDocument - Locates or creates a Binder for an existing document and returns that Binder for subscribing to. Returns an error if there was a problem locating the document.

type CuratorConfig

type CuratorConfig struct {
	BinderConfig BinderConfig `json:"binder" yaml:"binder"`
}

CuratorConfig - Holds configuration options for a curator.

func DefaultCuratorConfig

func DefaultCuratorConfig() CuratorConfig

DefaultCuratorConfig - Returns a fully defined curator configuration with the default values for each field.

type Document

type Document struct {
	ID      string `json:"id" yaml:"id"`
	Content string `json:"content" yaml:"content"`
}

Document - A representation of a leap document.

func NewDocument added in v0.1.0

func NewDocument(content string) (*Document, error)

NewDocument - Create a fresh leap document with a title, description, type and the initial content.

type DocumentStore

type DocumentStore interface {
	Create(string, Document) error
	Store(string, Document) error
	Fetch(string) (Document, error)
}

DocumentStore - Implemented by types able to acquire and store documents. This is abstracted in order to accommodate for multiple storage strategies. These methods should be asynchronous if possible.

func DocumentStoreFactory

func DocumentStoreFactory(config DocumentStoreConfig) (DocumentStore, error)

DocumentStoreFactory - Returns a document store object based on a configuration object.

func GetFileStore

func GetFileStore(config DocumentStoreConfig) (DocumentStore, error)

GetFileStore - Just a func that returns a FileStore

func GetMemoryStore

func GetMemoryStore(config DocumentStoreConfig) (DocumentStore, error)

GetMemoryStore - Just a func that returns a MemoryStore

func GetMockStore

func GetMockStore(config DocumentStoreConfig) (DocumentStore, error)

GetMockStore - returns a MemoryStore with a document already created for testing purposes. The document has the ID of the config value 'Name'.

func GetSQLStore

func GetSQLStore(config DocumentStoreConfig) (DocumentStore, error)

GetSQLStore - Just a func that returns an SQLStore

type DocumentStoreConfig

type DocumentStoreConfig struct {
	Type           string    `json:"type" yaml:"type"`
	Name           string    `json:"name" yaml:"name"`
	StoreDirectory string    `json:"store_directory" yaml:"store_directory"`
	SQLConfig      SQLConfig `json:"sql" yaml:"sql"`
}

DocumentStoreConfig - Holds generic configuration options for a document storage solution.

func DefaultDocumentStoreConfig

func DefaultDocumentStoreConfig() DocumentStoreConfig

DefaultDocumentStoreConfig - Returns a default generic configuration.

type FileAuthenticator added in v0.1.2

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

FileAuthenticator - A utility for using the filesystem as a way of validating that a document exists and is available to edit. This is intended to be used in tandem with the file based document store.

The FileAuthenticator takes a directory as a config option. When a client wishes to connect to a file the user token and document ID are given, where the document ID is the relative path to the target file.

The FileAuthenticator will then verify that this file exists within the configured directory. This is an attempt to isolate leaps, and avoid users connecting to paths such as ../../../etc/passwd.

func NewFileAuthenticator added in v0.1.2

func NewFileAuthenticator(config TokenAuthenticatorConfig, logger *log.Logger) *FileAuthenticator

NewFileAuthenticator - Creates an FileAuthenticator using the provided configuration.

func (*FileAuthenticator) AuthoriseCreate added in v0.1.2

func (f *FileAuthenticator) AuthoriseCreate(token, userID string) bool

AuthoriseCreate - Always returns false.

func (*FileAuthenticator) AuthoriseJoin added in v0.1.2

func (f *FileAuthenticator) AuthoriseJoin(token, documentID string) bool

AuthoriseJoin - Checks whether the documentID file exists, returns true if it does, otherwise false.

type FileAuthenticatorConfig added in v0.1.2

type FileAuthenticatorConfig struct {
	SharePath     string `json:"share_directory" yaml:"share_path"`
	Path          string `json:"path" yaml:"path"`
	ShowHidden    bool   `json:"show_hidden" yaml:"show_hidden"`
	RefreshPeriod int64  `json:"refresh_period_s" yaml:"refresh_period_s"`
}

FileAuthenticatorConfig - A config object for the file system authentication object.

func DefaultFileAuthenticatorConfig added in v0.1.2

func DefaultFileAuthenticatorConfig() FileAuthenticatorConfig

DefaultFileAuthenticatorConfig - Returns a default config object for a FileAuthenticator.

type FileStore

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

FileStore - Most basic persistent implementation of DocumentStore. Simply stores each document into a file within a configured directory. The ID represents the filepath relative to the configured directory.

For example, with StoreDirectory set to /var/www, a document can be given the ID css/main.css to create and edit the file /var/www/css/main.css

func (*FileStore) Create

func (s *FileStore) Create(id string, doc Document) error

Create - Store document in a file location

func (*FileStore) Fetch

func (s *FileStore) Fetch(id string) (Document, error)

Fetch - Fetch document from its file location.

func (*FileStore) Store

func (s *FileStore) Store(id string, doc Document) error

Store - Store document in its file location.

type MemoryStore

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

MemoryStore - Most basic implementation of DocumentStore, simply keeps the document in memory. Has zero persistence across sessions.

func (*MemoryStore) Create

func (s *MemoryStore) Create(id string, doc Document) error

Create - Store document in memory.

func (*MemoryStore) Fetch

func (s *MemoryStore) Fetch(id string) (Document, error)

Fetch - Fetch document from memory.

func (*MemoryStore) Store

func (s *MemoryStore) Store(id string, doc Document) error

Store - Store document in memory.

type MessageSubmission added in v0.1.0

type MessageSubmission struct {
	Token   string
	Message ClientMessage
}

MessageSubmission - A struct used to submit a message to a binder. The submission must contain the token of the client in order to avoid the message being sent back to the same client.

type Model

type Model interface {
	/* PushTransform - Push a single transform to our model, and if successful, return the updated
	 * transform along with the new version of the document.
	 */
	PushTransform(ot OTransform) (OTransform, int, error)

	/* FlushTransforms - apply all unapplied transforms to content, and delete old applied
	 * in accordance with our retention period. Returns a bool indicating whether any changes
	 * were applied, and an error in case a fatal problem was encountered.
	 */
	FlushTransforms(content *string, secondsRetention int64) (bool, error)

	/* GetVersion - returns the current version of the document.
	 */
	GetVersion() int
}

Model - an interface that represents an internal operation transform model of a particular type. Initially text is the only supported transform model, however, the plan will eventually be to have different models for various types of document that should all be supported by our binder.

func CreateTextModel

func CreateTextModel(config ModelConfig) Model

CreateTextModel - Returns a fresh transform model, with the version set to 1.

type ModelConfig

type ModelConfig struct {
	MaxDocumentSize    uint64 `json:"max_document_size" yaml:"max_document_size"`
	MaxTransformLength uint64 `json:"max_transform_length" yaml:"max_transform_length"`
}

ModelConfig - Holds configuration options for a transform model.

func DefaultModelConfig

func DefaultModelConfig() ModelConfig

DefaultModelConfig - Returns a default ModelConfig.

type OModel

type OModel struct {
	Version   int
	Applied   []OTransform
	Unapplied []OTransform
	// contains filtered or unexported fields
}

OModel - A representation of the transform model surrounding a document session. This keeps track of changes submitted and recently applied in order to distribute those changes to clients.

func (*OModel) FlushTransforms

func (m *OModel) FlushTransforms(content *string, secondsRetention int64) (bool, error)

FlushTransforms - apply all unapplied transforms and append them to the applied stack, then remove old entries from the applied stack. Accepts retention as an indicator for how many seconds applied transforms should be retained. Returns a bool indicating whether any changes were applied.

func (*OModel) GetVersion

func (m *OModel) GetVersion() int

GetVersion - returns the current version of the document.

func (*OModel) PushTransform

func (m *OModel) PushTransform(ot OTransform) (OTransform, int, error)

PushTransform - Inserts a transform onto the unapplied stack and increments the version number of the document. Whilst doing so it fixes the transform in relation to earlier transforms it was unaware of, this fixed version gets sent back for distributing across other clients.

type OTransform

type OTransform struct {
	Position  int    `json:"position" yaml:"position"`
	Delete    int    `json:"num_delete" yaml:"num_delete"`
	Insert    string `json:"insert" yaml:"insert"`
	Version   int    `json:"version" yaml:"version"`
	TReceived int64  `json:"received,omitempty" yaml:"received,omitempty"`
}

OTransform - A representation of a transformation relating to a leap document. This can either be a text addition, a text deletion, or both.

type RedisAuthenticator

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

RedisAuthenticator - A wrapper around the Redis client that acts as an authenticator.

func NewRedisAuthenticator added in v0.1.2

func NewRedisAuthenticator(config TokenAuthenticatorConfig, logger *log.Logger) *RedisAuthenticator

NewRedisAuthenticator - Creates a RedisAuthenticator using the provided configuration.

func (*RedisAuthenticator) AuthoriseCreate

func (s *RedisAuthenticator) AuthoriseCreate(token, userID string) bool

AuthoriseCreate - Checks whether a specific key exists in Redis and that the value matches our user ID.

func (*RedisAuthenticator) AuthoriseJoin

func (s *RedisAuthenticator) AuthoriseJoin(token, documentID string) bool

AuthoriseJoin - Checks whether a specific key exists in Redis and that the value matches a document ID.

func (*RedisAuthenticator) DeleteKey

func (s *RedisAuthenticator) DeleteKey(key string) error

DeleteKey - Deletes an existing key.

func (*RedisAuthenticator) ReadKey

func (s *RedisAuthenticator) ReadKey(key string) (string, error)

ReadKey - Simply return the value of a particular key, or an error.

type RedisAuthenticatorConfig

type RedisAuthenticatorConfig struct {
	URL          string `json:"url" yaml:"url"`
	Password     string `json:"password" yaml:"password"`
	PoolIdleTOut int64  `json:"pool_idle_s" yaml:"pool_idle_s"`
	PoolMaxIdle  int    `json:"pool_max_idle" yaml:"pool_max_idle"`
}

RedisAuthenticatorConfig - A config object for the redis authentication object.

func DefaultRedisAuthenticatorConfig

func DefaultRedisAuthenticatorConfig() RedisAuthenticatorConfig

DefaultRedisAuthenticatorConfig - Returns a default config object for a RedisAuthenticator.

type SQLConfig

type SQLConfig struct {
	DSN         string      `json:"dsn" yaml:"dsn"`
	TableConfig TableConfig `json:"db_table" yaml:"db_table"`
}

SQLConfig - The configuration fields for an SQL document store solution.

func DefaultSQLConfig

func DefaultSQLConfig() SQLConfig

DefaultSQLConfig - A default SQL configuration.

type SQLStore

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

SQLStore - A document store implementation for an SQL database.

func (*SQLStore) Create

func (m *SQLStore) Create(id string, doc Document) error

Create - Create a new document in a database table.

func (*SQLStore) Fetch

func (m *SQLStore) Fetch(id string) (Document, error)

Fetch - Fetch document from a database table.

func (*SQLStore) Store

func (m *SQLStore) Store(id string, doc Document) error

Store - Store document in a database table.

type TableConfig

type TableConfig struct {
	Name       string `json:"table" yaml:"table"`
	IDCol      string `json:"id_column" yaml:"id_column"`
	ContentCol string `json:"content_column" yaml:"content_column"`
}

TableConfig - The configuration fields for specifying the table labels of the SQL database target.

func DefaultTableConfig

func DefaultTableConfig() TableConfig

DefaultTableConfig - Default table configuration.

type TokenAuthenticator

type TokenAuthenticator interface {
	AuthoriseCreate(token, userID string) bool
	AuthoriseJoin(token, documentID string) bool
}

TokenAuthenticator - Implemented by types able to validate tokens for editing or creating documents. This is abstracted in order to accommodate for multiple authentication strategies.

func GetAnarchy

GetAnarchy - Get yourself a little taste of sweet, juicy anarchy.

func TokenAuthenticatorFactory

func TokenAuthenticatorFactory(config TokenAuthenticatorConfig, logger *log.Logger) (TokenAuthenticator, error)

TokenAuthenticatorFactory - Returns a document store object based on a configuration object.

type TokenAuthenticatorConfig

type TokenAuthenticatorConfig struct {
	Type        string                   `json:"type" yaml:"type"`
	AllowCreate bool                     `json:"allow_creation" yaml:"allow_creation"`
	RedisConfig RedisAuthenticatorConfig `json:"redis_config" yaml:"redis_config"`
	FileConfig  FileAuthenticatorConfig  `json:"file_config" yaml:"file_config"`
}

TokenAuthenticatorConfig - Holds generic configuration options for a token based authentication solution.

func DefaultTokenAuthenticatorConfig

func DefaultTokenAuthenticatorConfig() TokenAuthenticatorConfig

DefaultTokenAuthenticatorConfig - Returns a default generic configuration.

type TransformSubmission added in v0.1.0

type TransformSubmission struct {
	Token       string
	Transform   OTransform
	VersionChan chan<- int
	ErrorChan   chan<- error
}

TransformSubmission - A struct used to submit a transform to a binder. The submission must contain the token of the client, as well as two channels for returning either the corrected version of the transform if successful, or an error if the submit was unsuccessful.

Jump to

Keyboard shortcuts

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