tguard

package module
v0.0.9 Latest Latest
Warning

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

Go to latest
Published: Jan 15, 2024 License: Apache-2.0 Imports: 4 Imported by: 0

README

tguard (time guard) Package

The tguard package is designed to manage data with specific timeouts. It offers functionalities to start, cancel, and manage data based on their time-to-live (TTL) settings.

Installation

go get github.com/9ssi7/tguard

Potential Use-Cases

Real-World Example: Ticketing System

The tguard package can be used in a ticketing system to manage reservations with a specific time limit. Here's a Mermaid diagram illustrating the flow:

graph TD
    A[Start] --> B[Request Ticket]
    B --> C[Add to tguard]
    C --> D[Process Payment]
    D --> E[Confirm Reservation]
    E --> F[End]
    C -->|Timeout| G[Cancel Reservation]
    G --> F

Documentation

Go Reference

Usage

Import the Package
import "github.com/9ssi7/tguard"
Define Your Data Structure

Define the structure of your data, which should include an identifier (Id) and any other relevant fields.

type TestData struct {
	Id   string `json:"id"`
	Name string `json:"name"`
}
Implement the Identity Checker

Implement an identity checker function to verify the data's identity.

identityChecker := func(id string, data TestData) bool {
	return id == data.Id
}
Create Configuration

Create a configuration for the tguard service, specifying the fallback function, identity checker, default TTL, and interval.

config := tguard.Config[TestData]{
	Fallback:        func(data TestData) {},
	IdentityChecker: identityChecker,
	DefaultTTL:      time.Minute * 5,
	Interval:        time.Second * 10,
}
Create and Start the Service

Create a new tguard service instance using the configuration and start the service.

g := tguard.New(config)
ctx := context.Background()
go g.Connect(ctx)
Manage Data

Use the Start method to add data and the Cancel method to remove data if needed.

data := TestData{
	Id:   "1",
	Name: "test",
}
_ = g.Start(ctx, data)

Full Example

Here's a complete example demonstrating how to use the tguard package:

// Import required packages
import (
	"context"
	"time"
	"github.com/9ssi7/tguard"
)

// Define the data structure
type TestData struct {
	Id   string `json:"id"`
	Name string `json:"name"`
}

func main() {
	// Implement the identity checker
	identityChecker := func(id string, data TestData) bool {
		return id == data.Id
	}

	// Create the configuration
	config := tguard.Config[TestData]{
		Fallback:        func(data TestData) {},
		IdentityChecker: identityChecker,
		DefaultTTL:      time.Minute * 5,
		Interval:        time.Second * 10,
	}

	// Create and start the service
	g := tguard.New(config)
	ctx := context.Background()
	go g.Connect(ctx)

	// Manage data
	data := TestData{
		Id:   "1",
		Name: "test",
	}
	_ = g.Start(ctx, data)
}

Without Standart TTL Example

By default, tguard uses the same ttl time for each data. For example, if you set the defaultTTL value to 7 minutes, whatever data comes in will expire 7 minutes after the data is saved.

However, with an update we made, we thought that each data could have its own TTL time. This is especially valuable for survey systems. One user may finish the survey after 5 minutes, another may finish it after 30 minutes.

That's exactly what we're doing in this example.

import (
	"context"
	"time"
	"github.com/9ssi7/tguard"
)

type PollData struct {
	Id   string `json:"id"`
	Name string `json:"name"`
	Options []string `json:"options"`
	EndTime time.Time `json:"end_time"`
}

func main() {
	identityChecker := func(id string, data TestData) bool {
		return id == data.Id
	}

	// Create the configuration
	config := tguard.Config[TestData]{
		Fallback:        func(data TestData) {},
		IdentityChecker: identityChecker,
		Interval:        time.Second * 1,
		WithStandardTTL: false,
		Now:		     time.Now, // you can change it for location time
	}

	// Create and start the service
	g := tguard.New(config)
	ctx := context.Background()
	go g.Connect(ctx)

	// Manage data
	data := PollData{
		Id:   "1",
		Name: "test",
		Options: []string{"a", "b", "c"},
		EndTime: time.Now().Add(time.Minute * 5),
	}
	_ = g.Start(ctx, data, data.EndTime.Sub(time.Now())) // ttl time is 5 minutes
	
	data2 := PollData{
		Id:   "2",
		Name: "test2",
		Options: []string{"a", "b", "c"},
		EndTime: time.Now().Add(time.Minute * 10),
	}
	_ = g.Start(ctx, data2, data2.EndTime.Sub(time.Now())) // ttl time is 10 minutes
}

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

License

This project is licensed under the Apache License. See LICENSE for more details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config[T interface{}] struct {
	Fallback        FallbackFunc[T]    // The fallback function for timed-out data.
	IdentityChecker IdentityChecker[T] // The function to check the identity of data.
	Now             NowFunc            // The function to get the current time. default: time.Now
	DefaultTTL      time.Duration      // The default time-to-live for data. default: 5 minutes. (time.Minute * 5)
	Interval        time.Duration      // The interval for checking timeouts. default: 1 minute. (time.Minute * 1)
	Storage         Storage            // The storage backend. default: memoryStorage
	StorageKey      string             // The key under which data will be stored. default: "tguard_default_key"
	WithStandardTTL bool               // Whether to use all data with the same expiration time. default: true
}

Config defines the configuration for the service.

type Data

type Data[T interface{}] struct {
	Original   T     `json:"original"`    // The original data.
	ExpireTime int64 `json:"expire_time"` // The expiration time for the data.
}

Data is the fundamental structure for managing data over time.

type FallbackFunc

type FallbackFunc[T interface{}] func(data T)

FallbackFunc defines the fallback mechanism for timed-out data.

type IdentityChecker

type IdentityChecker[T interface{}] func(id string, data T) bool

IdentityChecker is a function type used to authenticate data.

type NowFunc added in v0.0.9

type NowFunc func() time.Time

type Service

type Service[T interface{}] interface {
	Start(ctx context.Context, data T, ttl ...time.Duration) error
	Cancel(ctx context.Context, id string) error
	GetData(ctx context.Context) ([]Data[T], error)
	Connect(ctx context.Context)
}

Service is the interface that defines the core functionality.

func New

func New[T any](cnf Config[T]) Service[T]

New creates a new Service instance based on the given configuration.

type Storage

type Storage interface {
	Get(ctx context.Context, key string) (string, error)
	Set(ctx context.Context, key string, value interface{}) error
	Exist(ctx context.Context, key string) (bool, error)
}

Storage defines where the data will be stored.

func NewMemoryStorage

func NewMemoryStorage() Storage

NewMemoryStorage creates a new Storage instance for in-memory storage.

Jump to

Keyboard shortcuts

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