Help us shape the future of Go! Take the 2026 Go Developer Survey

plan

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: Apache-2.0 Imports: 4 Imported by: 0

README

Plan Component

Plan is a Go package that provides a flexible task orchestration system with shared state management and signal control capabilities.

Features

  • Task ordering and parallel execution
  • Shared state management between tasks
  • Task lifecycle control (pause/resume/stop)
  • Signal-based task communication
  • Configurable status check intervals
  • Thread-safe operations
  • Resource cleanup management

Installation

go get github.com/yaoapp/gou/plan

Quick Start

package main

import (
    "context"
    "time"
    "github.com/yaoapp/gou/plan"
)

func main() {
    // Create a shared space
    shared := plan.NewMemorySharedSpace()

    // Create a plan with custom status check interval
    p := plan.NewPlan(
        context.Background(),
        "example-plan",
        shared,
        plan.WithStatusCheckInterval(5*time.Millisecond),
    )

    // Add tasks
    p.AddTask("task1", 1, func(ctx context.Context, shared plan.SharedSpace, signals <-chan plan.Signal) error {
        // Task implementation
        return shared.Set("key1", "value1")
    })

    p.AddTask("task2", 2, func(ctx context.Context, shared plan.SharedSpace, signals <-chan plan.Signal) error {
        // Task implementation with signal handling
        select {
        case sig := <-signals:
            switch sig {
            case plan.SignalPause:
                // Handle pause
            case plan.SignalResume:
                // Handle resume
            case plan.SignalStop:
                return nil
            }
        case <-ctx.Done():
            return ctx.Err()
        }
        return nil
    })

    // Start the plan
    if err := p.Start(); err != nil {
        panic(err)
    }
}

Core Concepts

Plan

A Plan is a collection of tasks with a shared state space. It manages task execution order and lifecycle.

Task

A Task is a unit of work that can:

  • Access shared state
  • Respond to control signals
  • Execute in parallel with other tasks of the same order
  • Report its status and store task-specific data
Shared Space

SharedSpace provides a thread-safe storage mechanism for tasks to share data and communicate.

API Reference

Plan Creation
func NewPlan(ctx context.Context, id string, shared SharedSpace, opts ...Option) *Plan

Options:

  • WithStatusCheckInterval(duration): Set the interval for status checks
Task Management
func (p *Plan) AddTask(id string, order int, fn TaskFunc) error
func (p *Plan) RemoveTask(id string) error
Plan Control
func (p *Plan) Start() error
func (p *Plan) Pause() error
func (p *Plan) Resume() error
func (p *Plan) Stop() error
Status and Data
func (p *Plan) GetStatus() (Status, map[string]Status)
func (p *Plan) GetTaskData(taskID string) (interface{}, error)
Shared Space Operations
func (s SharedSpace) Set(key string, value interface{}) error
func (s SharedSpace) Get(key string) (interface{}, error)
func (s SharedSpace) Subscribe(key string, callback func(key string, value interface{})) error
func (s SharedSpace) Unsubscribe(key string) error

Task States

  • StatusCreated: Initial state
  • StatusRunning: Task is executing
  • StatusPaused: Task is temporarily halted
  • StatusCompleted: Task finished successfully
  • StatusFailed: Task encountered an error
  • StatusDestroyed: Task was terminated

Best Practices

  1. Error Handling: Always check for errors returned by plan operations.
  2. Signal Handling: Implement proper signal handling in long-running tasks.
  3. Resource Cleanup: Use Stop() to properly clean up resources.
  4. Context Usage: Respect context cancellation in task implementations.
  5. Shared State: Use shared space for task communication rather than external variables.

Thread Safety

The Plan component is designed to be thread-safe:

  • All plan operations are synchronized
  • Shared space operations are protected by mutexes
  • Signal channels are buffered to prevent blocking

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// StatusCheckInterval is the interval between status checks
	StatusCheckInterval time.Duration
}

Config represents plan configuration

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns the default configuration

type MemorySharedSpace

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

MemorySharedSpace implements SharedSpace interface using in-memory storage

func NewMemorySharedSpace

func NewMemorySharedSpace() *MemorySharedSpace

NewMemorySharedSpace creates a new MemorySharedSpace instance

func (*MemorySharedSpace) Clear

func (m *MemorySharedSpace) Clear() error

Clear removes all values from the shared space

func (*MemorySharedSpace) ClearNotify

func (m *MemorySharedSpace) ClearNotify() error

ClearNotify removes all values from the shared space and notifies subscribers

func (*MemorySharedSpace) Delete

func (m *MemorySharedSpace) Delete(key string) error

Delete removes a value from the shared space

func (*MemorySharedSpace) Get

func (m *MemorySharedSpace) Get(key string) (interface{}, error)

Get retrieves a value from the shared space

func (*MemorySharedSpace) Restore

func (m *MemorySharedSpace) Restore(data map[string]interface{}) error

Restore sets multiple key-value pairs from a snapshot Used for recovering space state after interruption

func (*MemorySharedSpace) Set

func (m *MemorySharedSpace) Set(key string, value interface{}) error

Set stores a value in the shared space

func (*MemorySharedSpace) Snapshot

func (m *MemorySharedSpace) Snapshot() map[string]interface{}

Snapshot returns a copy of all key-value pairs in the shared space Used for persisting space state for recovery purposes

func (*MemorySharedSpace) Subscribe

func (m *MemorySharedSpace) Subscribe(key string, callback func(key string, value interface{})) error

Subscribe subscribes to changes in the shared space

func (*MemorySharedSpace) Unsubscribe

func (m *MemorySharedSpace) Unsubscribe(key string) error

Unsubscribe removes a subscription

type Option

type Option func(*Config)

Option represents a function that modifies the plan configuration

func WithStatusCheckInterval

func WithStatusCheckInterval(d time.Duration) Option

WithStatusCheckInterval sets the status check interval

type Plan

type Plan struct {
	ID          string
	Tasks       map[string]*Task
	SharedSpace SharedSpace
	Status      Status
	Context     context.Context
	Cancel      context.CancelFunc
	Config      *Config
}

Plan represents a collection of tasks with shared space

func NewPlan

func NewPlan(ctx context.Context, id string, shared SharedSpace, opts ...Option) *Plan

NewPlan creates a new Plan instance

func (*Plan) AddTask

func (p *Plan) AddTask(id string, order int, fn TaskFunc) error

AddTask adds a new task to the plan

func (*Plan) GetStatus

func (p *Plan) GetStatus() (Status, map[string]Status)

GetStatus returns the current status of the plan and its tasks

func (*Plan) GetTaskData

func (p *Plan) GetTaskData(taskID string) (interface{}, error)

GetTaskData returns the data associated with a specific task

func (*Plan) GetTaskStatus

func (p *Plan) GetTaskStatus(taskID string) (Status, error)

GetTaskStatus returns the status of a specific task

func (*Plan) Pause

func (p *Plan) Pause() error

Pause temporarily halts execution of the plan

func (*Plan) Release

func (p *Plan) Release()

Release releases the plan

func (*Plan) RemoveTask

func (p *Plan) RemoveTask(id string) error

RemoveTask removes a task from the plan

func (*Plan) Resume

func (p *Plan) Resume() error

Resume continues execution of a paused plan

func (*Plan) Start

func (p *Plan) Start() error

Start begins execution of the plan

func (*Plan) Stop

func (p *Plan) Stop() error

Stop terminates execution of the plan

func (*Plan) Trigger

func (p *Plan) Trigger(event string, data interface{})

Trigger triggers an event on the plan

type SharedSpace

type SharedSpace interface {
	// Set stores a value in the shared space
	Set(key string, value interface{}) error

	// Get retrieves a value from the shared space
	Get(key string) (interface{}, error)

	// Delete removes a value from the shared space
	Delete(key string) error

	// Clear removes all values from the shared space
	Clear() error

	// ClearNotify removes all values from the shared space and notifies subscribers
	ClearNotify() error

	// Subscribe subscribes to changes in the shared space
	Subscribe(key string, callback func(key string, value interface{})) error

	// Unsubscribe removes a subscription
	Unsubscribe(key string) error
}

SharedSpace represents the interface for shared storage space

type Signal

type Signal int

Signal represents control signals for tasks

const (
	SignalPause Signal = iota
	SignalResume
	SignalStop
)

Signal constants for task control

type Space

type Space interface {
	Set(key string, value interface{}) error
	Get(key string) (interface{}, error)
	Delete(key string) error
	Clear() error
	ClearNotify() error
	Subscribe(key string, callback func(key string, value interface{})) error
	Unsubscribe(key string) error
	Snapshot() map[string]interface{}          // Returns a copy of all key-value pairs
	Restore(data map[string]interface{}) error // Restores multiple key-value pairs from a snapshot
}

Space interface

type Status

type Status int

Status represents the status of a plan or task

const (
	StatusCreated Status = iota
	StatusRunning
	StatusPaused
	StatusCompleted
	StatusFailed
	StatusDestroyed
	StatusUnknown
)

Status constants for tracking plan and task states

type Task

type Task struct {
	ID         string
	Order      int
	Fn         TaskFunc
	Status     Status
	Data       interface{}
	Context    context.Context
	Cancel     context.CancelFunc
	SignalChan chan Signal
}

Task represents a unit of work in a plan

type TaskFunc

type TaskFunc func(ctx context.Context, shared SharedSpace, signals <-chan Signal) error

TaskFunc is the function type that represents a task's execution unit

Jump to

Keyboard shortcuts

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