Skip to main content

main.go

main.go - Overview

This file defines the ShardManager type, which is responsible for managing a collection of shards. It handles the lifecycle of the shards, including starting and stopping them, and provides methods for accessing shards based on keys. The ShardManager also listens for OS signals (SIGINT, SIGTERM) to trigger a graceful shutdown.

Detailed Documentation

ShardManager

type ShardManager struct {
shards []*shard.Shard
sigChan chan os.Signal
}
  • Purpose: Represents a manager responsible for handling multiple shards.
  • Fields:
    • shards: A slice of shard.Shard pointers, representing the managed shards.
    • sigChan: A channel to receive OS signals for shutdown.

NewShardManager

func NewShardManager(shardCount int, globalErrorChan chan error) *ShardManager
  • Purpose: Creates a new ShardManager instance. It initializes the shards based on the provided shardCount and sets up each shard with a ShardThread.
  • Parameters:
    • shardCount (int): The number of shards to create and manage.
    • globalErrorChan (chan error): A channel for reporting global errors.
  • Returns: A pointer to the newly created ShardManager.

Run

func (manager *ShardManager) Run(ctx context.Context)
  • Purpose: Starts the ShardManager, managing the shard lifecycle and listening for errors or OS signals to initiate shutdown.
  • Parameters:
    • ctx (context.Context): A context for managing the ShardManager's lifecycle.

start

func (manager *ShardManager) start(ctx context.Context, wg *sync.WaitGroup)
  • Purpose: Initializes and starts the shard threads.
  • Parameters:
    • ctx (context.Context): A context for managing the lifecycle of the shards.
    • wg (*sync.WaitGroup): A WaitGroup to synchronize the start and stop of shard goroutines.

GetShardForKey

func (manager *ShardManager) GetShardForKey(key string) *shard.Shard
  • Purpose: Returns the shard responsible for a given key. It uses xxhash to hash the key and then uses the modulo operator to determine the shard ID.
  • Parameters:
    • key (string): The key to find the shard for.
  • Returns: A pointer to the shard.Shard that is responsible for the given key.

ShardCount

func (manager *ShardManager) ShardCount() int8
  • Purpose: Returns the number of shards managed by the ShardManager.
  • Returns: The number of shards as an int8.

Shards

func (manager *ShardManager) Shards() []*shard.Shard
  • Purpose: Returns the slice of shards managed by the ShardManager.
  • Returns: A slice of shard.Shard pointers.

Getting Started Relevance