subscribe

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2019 License: MIT Imports: 8 Imported by: 0

README

go-subscribe

A (mostly generic) Subscription Library for Go.

This library allows you to subscribe things (like users) to events. The library holds subscribers in memory. It can be also be configured to persist subscriptions to disk. The subscription database should scale to thousands of subscriptions with hundreds of request per second. If you need more, this library may not work for you; I do not know.

Thread safe.

The following is a very simple example. This library provides many other methods not shown here to deal with event and notification rules, pause/un-pausing, etc.

package main

import (
	"fmt"
	"time"

	"golift.io/subscribe"
)

func main() {
	// Instantiate an in-memory database. Passing a file-path here loads
	// a DB from disk, or saves a new database to the file-path provided.
	db, _ := subscribe.GetDB("")
	// Create two new subscribers. Initial state has no subscriptions.
	newSub := db.CreateSub("you@email.com.tw", "smtp", false, false)
	newSub2 := db.CreateSub("+18089117234", "sms", false, false)
	// Subscribe the users to an event. Errors only if subscription already exists.
	_ = newSub.Subscribe("party invites")
	_ = newSub2.Subscribe("party invites")

	// Limit subscriber search to only email recipients. Initial state returns any API.
	db.EnableAPIs = []string{"smtp"}
	// Now that your party invites event has subscribers, you can find them when a party invite arrives.
	subs := db.GetSubscribers("party invites")
	fmt.Printf("Sending email to %d subscriber(s):\n", len(subs))
	for _, sub := range subs {
		fmt.Println(sub.Contact)
		// send email.
	}

	// Limit subscriber search to only sms.
	db.EnableAPIs[0] = "sms"
	// Now that your party invites event has subscribers, you can find them when a party invite arrives.
	subs = db.GetSubscribers("party invites")
	fmt.Printf("Sending Text Msg to %d subscriber(s):\n", len(subs))
	for _, sub := range subs {
		fmt.Println(sub.Contact)
		// send sms.
	}

	// if you want to save the DB:
	err := db.StateFileRelocate("/var/lib/somewhere/for/a/file.json")
	if err != nil {
		fmt.Println("Unable to relocate DB:", err)
		return
	}

	// save the DB once in a while, or after making changes.
	ticker := time.NewTicker(time.Minute)
	for range ticker.C {
		err = db.StateFileSave()
		// This always returns nil if state file path is empty: ""
		if err != nil {
			fmt.Println("Unable to save DB:", err)
		}
	}
}

Output:

Sending email to 1 subscriber(s):
you@email.com.tw
Sending Text Msg to 1 subscriber(s):
+18089117234
Unable to relocate DB: open /var/lib/somewhere/for/a/file.json: no such file or directory

Feedback, ideas and contributions welcomed!

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrorSubscriberNotFound is returned any time a requested subscriber does not exist.
	ErrorSubscriberNotFound = errors.New("subscriber not found")
	// ErrorEventNotFound is returned when a requested event has not been created.
	ErrorEventNotFound = errors.New("event not found")
	// ErrorEventExists is returned when a new event with an existing name is created.
	ErrorEventExists = errors.New("event already exists")
)

Functions

This section is empty.

Types

type Events added in v1.1.0

type Events struct {
	// Map is the events/rules map. Use the provided methods to interact with it.
	Map map[string]*Rules `json:"events_map"`
	// sync.RWMutex locks and unlocks the Events map
	sync.RWMutex
}

Events represents the map of tracked global Events. This is an arbitrary list that can be used to filter notifications in a consuming application.

func (*Events) Exists added in v1.1.0

func (e *Events) Exists(event string) bool

Exists returns true if an event exists.

func (*Events) IsPaused added in v1.1.0

func (e *Events) IsPaused(event string) bool

IsPaused returns true if the event's notifications are pasued. Returns true if the event subscription does not exist.

func (*Events) Len added in v1.1.0

func (e *Events) Len() int

Len returns the number of configured events.

func (*Events) Names added in v1.1.0

func (e *Events) Names() []string

Names returns all the configured event names.

func (*Events) New added in v1.1.0

func (e *Events) New(event string, rules *Rules) error

New adds an event.

func (*Events) Pause added in v1.1.0

func (e *Events) Pause(event string, duration time.Duration) error

Pause (or unpause with 0 duration) a subscriber's event subscription. Returns an error only if the event subscription is not found.

func (*Events) PauseTime added in v1.1.0

func (e *Events) PauseTime(event string) time.Time

PauseTime returns the pause time for an event.

func (*Events) Remove added in v1.1.0

func (e *Events) Remove(event string)

Remove deletes an event.

func (*Events) RuleDelAll added in v1.1.0

func (e *Events) RuleDelAll(event, rule string)

RuleDelAll deletes rules of any type with a specific name.

func (*Events) RuleDelD added in v1.1.0

func (e *Events) RuleDelD(event, rule string)

RuleDelD deletes a Duration rule.

func (*Events) RuleDelI added in v1.1.0

func (e *Events) RuleDelI(event, rule string)

RuleDelI deletes an integer rule.

func (*Events) RuleDelS added in v1.1.0

func (e *Events) RuleDelS(event, rule string)

RuleDelS deletes a string rule.

func (*Events) RuleDelT added in v1.1.0

func (e *Events) RuleDelT(event, rule string)

RuleDelT deletes a Time rule.

func (*Events) RuleGetD added in v1.1.0

func (e *Events) RuleGetD(event, rule string) (time.Duration, bool)

RuleGetD returns a Duration rule.

func (*Events) RuleGetI added in v1.1.0

func (e *Events) RuleGetI(event, rule string) (int, bool)

RuleGetI returns an integer rule.

func (*Events) RuleGetS added in v1.1.0

func (e *Events) RuleGetS(event, rule string) (string, bool)

RuleGetS returns a string rule.

func (*Events) RuleGetT added in v1.1.0

func (e *Events) RuleGetT(event, rule string) (time.Time, bool)

RuleGetT returns a Time rule.

func (*Events) RuleSetD added in v1.1.0

func (e *Events) RuleSetD(event, rule string, val time.Duration)

RuleSetD updates or sets a Duration rule.

func (*Events) RuleSetI added in v1.1.0

func (e *Events) RuleSetI(event, rule string, val int)

RuleSetI updates or sets an integer rule.

func (*Events) RuleSetS added in v1.1.0

func (e *Events) RuleSetS(event, rule string, val string)

RuleSetS updates or sets a string rule.

func (*Events) RuleSetT added in v1.1.0

func (e *Events) RuleSetT(event, rule string, val time.Time)

RuleSetT updates or sets a Time rule.

func (*Events) UnPause added in v1.1.0

func (e *Events) UnPause(event string) error

UnPause resumes a subscriber's event subscription. Returns an error only if the event subscription is not found.

type Rules

type Rules struct {
	Pause time.Time `json:"pause"`
	D     map[string]time.Duration
	I     map[string]int
	S     map[string]string
	T     map[string]time.Time
}

Rules contains the pause time and rules for a subscriber's event subscription. Rules are unused by the library and available for consumers.

type Subscribe

type Subscribe struct {
	// EnableAPIs sets the allowed APIs. Only subscriptions that have an API
	// with a prefix in this list will return from the GetSubscribers() method.
	EnableAPIs []string `json:"enabled_apis"` // imessage, skype, pushover, email, slack, growl, all, any

	// Events stores a list of arbitrary events. Use the included methods to interact with it.
	// This does not affect GetSubscribers(). Use the data here as a filter in your app.
	Events *Events `json:"events"`
	// Subscribers is a list of all Subscribers.
	Subscribers []*Subscriber `json:"subscribers"`
	// contains filtered or unexported fields
}

Subscribe is the data needed to initialize this module.

func GetDB

func GetDB(StateFile string) (*Subscribe, error)

GetDB returns an interface to manage events

func (*Subscribe) CreateSub

func (s *Subscribe) CreateSub(contact, api string, admin, ignore bool) *Subscriber

CreateSub creates or updates a subscriber.

func (*Subscribe) EventRemove

func (s *Subscribe) EventRemove(event string)

EventRemove obliterates an event and all subsciptions for it.

func (*Subscribe) GetAdmins

func (s *Subscribe) GetAdmins() (subs []*Subscriber)

GetAdmins returns a list of subscribed admins.

func (*Subscribe) GetIgnored

func (s *Subscribe) GetIgnored() (subs []*Subscriber)

GetIgnored returns a list of ignored subscribers.

func (*Subscribe) GetSubscriber

func (s *Subscribe) GetSubscriber(contact, api string) (*Subscriber, error)

GetSubscriber gets a subscriber based on their contact info.

func (*Subscribe) GetSubscribers

func (s *Subscribe) GetSubscribers(eventName string) (subscribers []*Subscriber)

GetSubscribers returns a list of valid event subscribers. This is the main method that should be triggered when an event occurs. Call this method when your event fires, collect the subscribers and send them notifications in your app. Subscribers can be people. Or functions.

func (*Subscribe) StateFileLoad

func (s *Subscribe) StateFileLoad() error

StateFileLoad data from a json file.

func (*Subscribe) StateFileRelocate

func (s *Subscribe) StateFileRelocate(newPath string) (err error)

StateFileRelocate writes the state file to a new location.

func (*Subscribe) StateFileSave

func (s *Subscribe) StateFileSave() error

StateFileSave writes out the state file.

func (*Subscribe) StateGetJSON

func (s *Subscribe) StateGetJSON() (string, error)

StateGetJSON returns the state data in json format.

type Subscriber

type Subscriber struct {
	// API is the type of API the subscriber is subscribed with. Used to filter results.
	API string `json:"api"`
	// Contact is the contact info used in the API to send the subscriber a notification.
	Contact string `json:"contact"`
	// Events is a list of events the subscriber is subscribed to, including a cooldown/pause time.
	Events *Events `json:"events"`
	// This is just extra data that can be used to make the user special.
	Admin bool `json:"is_admin"`
	// Ignored will exclude a user from GetSubscribers().
	Ignored bool `json:"ignored"`
}

Subscriber describes the contact info and subscriptions for a person.

func (*Subscriber) Subscribe

func (s *Subscriber) Subscribe(event string) error

Subscribe adds an event subscription to a subscriber. Returns an error only if the event subscription already exists.

Jump to

Keyboard shortcuts

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