service

package
v0.1.16 Latest Latest
Warning

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

Go to latest
Published: Feb 16, 2023 License: Apache-2.0 Imports: 11 Imported by: 1

README

mu/service

service is the core of the Mu framework.

service is based on the concept of hooks and workers. Hooks are functions that are invoked at various points in the service lifecycle. Workers are goroutines that are started and stopped as part of the service lifecycle.

service also contains core functionality that is useful for most services. This includes:

  • Logging - service provides a logger that is configured to output JSON formatted logs. The logger is instantiated as the first thing in the service lifecycle and is available to all hooks and workers.
  • Configuration - service makes configuration easy by providing a Config registry that is populated from environment variables. Configuration variables are strongly typed and validated at startup, so you can be sure that your service will fail fast if it is misconfigured.
  • Signal handing - service reacts appropriately to SIGINT and SIGTERM signals by shutting down gracefully.

Usage

To use service, you need to create a Service struct and register hooks and workers. You can then start the service by calling Main().

package main

import (
	ht "net/http"
	"os"

	"github.com/neuralnorthwest/mu/config"
	"github.com/neuralnorthwest/mu/http"
	"github.com/neuralnorthwest/mu/service"
	"github.com/neuralnorthwest/mu/worker"
)

// Demonstrates basic usage of the mu framework.
//
//  - Define BasicApp, which embeds an instance of service.Service
//  - Define newBasicApp, which initializes the application:
//    - Create a new service.Service
//    - Register the configuration setup hook `setupConfig`
//    - Register the worker setup hook `setupWorkers`
//    - Register the cleanup hook `cleanup`
//  - Define setupConfig, which sets up the configuration:
//    - Create a new string configuration variable `MESSAGE`
//  - Define setupWorkers, which sets up the application:
//    - Create a new HTTP server
//    - Register a handler for the `/hello` endpoint
//    - Add the HTTP server to the worker group
//  - Define cleanup, which cleans up the application:
//    - Nothing to do here
//  - Define main, which runs the application:
//    - Create a new basic application using newBasicApp
//    - Call Main on the application
//    - If an error occurs, print it to stderr and exit with a non-zero status

// BasicApp is a basic application.
type BasicApp struct {
	*service.Service
}

// NewBasicApp returns a new basic application.
func newBasicApp() (*BasicApp, error) {
	svc, err := service.New("basic")
	if err != nil {
		return nil, err
	}
	app := &BasicApp{
		Service: svc,
	}
	app.SetupConfig(app.setupConfig)
	app.SetupWorkers(app.setupWorkers)
	app.Cleanup(app.cleanup)
	return app, nil
}

// setupConfig sets up the configuration.
func (a *BasicApp) setupConfig(c config.Config) error {
	return c.NewString("MESSAGE", "Hello, World!", "The message to print.")
}

// setupWorkers sets up the application.
func (a *BasicApp) setupWorkers(workerGroup worker.Group) error {
	httpServer, err := http.NewServer()
	if err != nil {
		return err
	}
	httpServer.HandleFunc("/hello", func(w ht.ResponseWriter, r *ht.Request) {
		_, _ = w.Write([]byte(a.Config().String("MESSAGE")))
	})
	return workerGroup.Add("http_server", httpServer)
}

// cleanup cleans up the application.
func (a *BasicApp) cleanup() {
	a.Logger().Info("Cleaning up...")
}

func main() {
	app, err := newBasicApp()
	if err != nil {
		panic(err)
	}
	if err := app.Main(); err != nil {
		os.Exit(1)
	}
}

Documentation

Overview

Package service implements the Service type. This type is the core of the Mu framework.

Service is based on the concept of hooks and workers. Hooks are functions that are invoked at various points in the service lifecycle. Workers are goroutines that are started and stopped as part of the service lifecycle.

Service also contains some core functionality that is useful for most services. This includes logging, configuration, and signal handling.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CleanupFunc

type CleanupFunc func()

CleanupFunc is a function that cleans up a service.

type Hooks added in v0.1.5

type Hooks interface {
	PreRun(f PreRunFunc)
	SetupConfig(f SetupConfigFunc)
	SetupWorkers(f SetupWorkersFunc)
	SetupHTTP(f SetupHTTPFunc, opts ...http.ServerOption)
	// contains filtered or unexported methods
}

type Option

type Option func(*Service) error

Option is an option for a service.

func WithLogger

func WithLogger(newLogger func() (logging.Logger, error)) Option

WithLogger returns an option that sets the func used to create a new logger.

func WithMockMode

func WithMockMode() Option

WithMockMode returns an option that sets the mock mode of the service.

func WithVersion

func WithVersion(version string) Option

WithVersion returns an option that sets the version of the service.

type PreRunFunc added in v0.1.10

type PreRunFunc func() error

PreRunFunc is a function that runs before the workers are started.

type Service

type Service struct {

	// hooks are the hooks for the service.
	Hooks
	// contains filtered or unexported fields
}

Service represents a service.

func New

func New(name string, opts ...Option) (*Service, error)

New returns a new service.

func (*Service) Cancel

func (s *Service) Cancel()

Cancel cancels the context for the service.

func (*Service) Cleanup added in v0.1.14

func (s *Service) Cleanup(f CleanupFunc)

Cleanup registers a cleanup function that is invoked when the service is stopped. Multiple cleanup functions can be registered. Cleanups are invoked in the reverse order they are registered.

func (*Service) Config

func (s *Service) Config() config.Config

Config returns the config for the service.

func (*Service) Context

func (s *Service) Context() context.Context

Context returns the context for the service.

func (*Service) Logger

func (s *Service) Logger() logging.Logger

Logger returns the logger for the service.

func (*Service) Main

func (s *Service) Main() error

Main invokes the main cobra.Command for the service. If you need to customize the command, see MainCommand.

func (*Service) MainCommand

func (s *Service) MainCommand() *cobra.Command

MainCommand returns the main cobra.Command for the service. This allows you to customize the command (perhaps adding flags) before invoking it with Execute.

func (*Service) MockMode

func (s *Service) MockMode() bool

MockMode returns true if the service is in mock mode.

func (*Service) Name

func (s *Service) Name() string

Name returns the name of the service.

func (*Service) Run

func (s *Service) Run() (status error)

Run runs the service.

func (*Service) Version

func (s *Service) Version() string

Version returns the version of the service.

type SetupConfigFunc added in v0.1.11

type SetupConfigFunc func(c config.Config) error

SetupConfigFunc is a function that sets up a service configuration.

type SetupHTTPFunc added in v0.1.5

type SetupHTTPFunc func(server *http.Server) error

SetupHTTPFunc is a function that sets up a service HTTP server.

type SetupWorkersFunc added in v0.1.10

type SetupWorkersFunc func(workerGroup worker.Group) error

SetupWorkersFunc is a function that sets up workers for the service.

Jump to

Keyboard shortcuts

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