serv

package module
v3.36.13 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: Apache-2.0 Imports: 40 Imported by: 0

README

Service

serv is the embeddable HTTP service built on top of the GraphJin core compiler.

Module path:

github.com/aegion-dynamic/graphjin-slim/serv/v3

The service package connects configuration, database adapters, caches, HTTP handlers, and the core.GraphJin runtime. It can be embedded in an existing Go HTTP application or used to run GraphJin's own server lifecycle.

Public Entry Points

The root serv package is the compatibility facade.

Important types and functions include:

serv.NewGraphJinService
serv.HttpService
serv.Config
serv.NewConfig
serv.ReadInConfig
serv.HandlerFunc

An embedded application normally creates a service and mounts its handlers:

service, err := serv.NewGraphJinService(conf)
if err != nil {
	return err
}
defer service.Close()

router.Handle("/graphql", service.GraphQL(authHandler))
router.Handle("/rest/", service.REST(nil))

The service owns database connections and cache resources created during construction. Call Close when the embedding application shuts down.

Responsibilities

Service owns:

  • Configuration loading and environment overrides
  • Postgres and SQLite connection setup
  • GraphQL and REST HTTP handlers
  • Health endpoint registration
  • Response-cache selection
  • Server startup and graceful shutdown
  • File and object-storage service integration
  • Service-level logging and telemetry setup

Core owns the compiler, schema model, query execution, and GraphJin runtime. The service should compose core; it should not duplicate compiler behavior.

Package Layout

serv/database

Database configuration and connection opening for Postgres and SQLite.

The package owns connection strings, pool configuration, Postgres TLS setup, database pinging, and retry behavior. The root service package keeps wrappers for compatibility with existing consumers.

serv/cache

Response-cache behavior and adapters.

cache.Config
cache.ResponseCache
cache.MemoryCache
cache.RedisCache

The package owns TTL policy, dependency invalidation, stale-while-revalidate, and cache metrics. The memory and Redis implementations share the same cache interface.

serv/http

Route registration and the minimal mux contract.

The root service package supplies GraphQL, REST, and Web UI handlers. The HTTP package owns route paths and registration, but does not import the service package or know how handlers are implemented.

Root serv package

The root package is the composition point. It currently contains the service state, configuration loader, handler implementation, startup lifecycle, and compatibility wrappers. These responsibilities are being extracted gradually; the root package remains the stable import path for users.

Request Flow

application router
    |
    v
serv/http route registration
    |
    v
serv GraphQL or REST handler
    |
    v
core.GraphJin
    |
    +--> database/sql connection
    +--> cache.Cache
    +--> core schema and compiler

Authentication is intentionally supplied by the embedding application through HandlerFunc. The service does not provide an application-specific identity provider.

Configuration

Configuration can be loaded from a file or constructed from a string:

conf, err := serv.ReadInConfig("./config.yml")
conf, err := serv.NewConfig(yamlText, "yaml")

The supported database types are:

database:
  type: postgres

or:

database:
  type: sqlite
  path: ./app.db

SQLite sources can be encrypted at rest by adding an encryption_key (SQLCipher is applied per connection; requires a SQLCipher-linked build — see serv/database/README.md):

database:
  type: sqlite
  path: ./app.db
  encryption_key: ${GJ_DB_KEY}   # supply via environment, not in the file

Environment overrides use the GJ_ prefix. Configuration names, defaults, and the generated config.schema.json are part of the service's compatibility surface.

Testing

Run the service suite from the workspace root:

go test ./serv/...
go vet ./serv/...

Cache tests live with the cache package. Database behavior should use SQLite or fake SQL drivers where possible. Service tests should test handler behavior through the public service interface rather than reaching into private service state.

Refactoring Rules

  • Keep serv/v3 stable for consumers.
  • Keep serv as the composition point, not a dumping ground for adapters.
  • Put backend-specific behavior in database, cache, or storage packages.
  • Keep transport registration independent from service state.
  • Do not make implementation packages import the root serv package.
  • Prefer one deep interface with multiple adapters over exposing backend details.

Documentation

Overview

Package serv provides an API to include and use the GraphJin service with your own code. For detailed documentation visit https://graphjin.com

Example usage:

package main

import (
	"database/sql"
	"fmt"
		"github.com/aegion-dynamic/graphjin-slim/core/v3"
	_ "github.com/jackc/pgx/v5/stdlib"
)

func main() {
	conf := serv.Config{ AppName: "Test App" }
	conf.DB.Host := "127.0.0.1"
	conf.DB.Port := 5432
	conf.DB.DBName := "test_db"
	conf.DB.User := "postgres"
	conf.DB.Password := "postgres"

	gjs, err := serv.NewGraphJinService(conf)
	if err != nil {
		log.Fatal(err)
	}

 	if err := gjs.Start(); err != nil {
		log.Fatal(err)
	}
}

Index

Constants

This section is empty.

Variables

View Source
var ErrGraphJinNotInitialized = errors.New("GraphJin not initialized - no database configured")

ErrGraphJinNotInitialized is returned when GraphJin core is not initialized

Functions

func GetConfigName

func GetConfigName() string

GetConfigName returns the config file name.

func NewDB

func NewDB(conf *Config, openDB bool, log *zap.SugaredLogger, fs core.FS) (*sql.DB, error)

Types

type CachingConfig

type CachingConfig struct{}

CachingConfig is a placeholder; response caching is not part of slim.

type Config

type Config struct {
	// Configuration for the GraphJin compiler core
	Core `mapstructure:",squash" jsonschema:"title=Compiler Configuration"`

	// Configuration for the GraphJin Service
	Serv `mapstructure:",squash" jsonschema:"title=Service Configuration"`

	// Name of another config file in the same directory to inherit and
	// override (one level only; the inherited file cannot itself inherit).
	Inherits string `mapstructure:"inherits" jsonschema:"title=Inherit From Config File"`
	// contains filtered or unexported fields
}

Configuration for the GraphJin service

func NewConfig

func NewConfig(config, format string) (*Config, error)

NewConfig creates a new GraphJin configuration from the provided config string.

func ReadInConfig

func ReadInConfig(configFile string) (*Config, error)

ReadInConfig reads the config file for the environment.

func ReadInConfigFS

func ReadInConfigFS(configFile string, fs afero.Fs) (*Config, error)

ReadInConfigFS is the same as ReadInConfig but with a filesystem argument.

func (*Config) AbsolutePath

func (c *Config) AbsolutePath(p string) string

AbsolutePath returns the absolute path of the file.

func (*Config) ShouldUseJSONLogs

func (c *Config) ShouldUseJSONLogs() bool

ShouldUseJSONLogs returns true if logs should be in JSON format.

type Core

type Core = core.Config

type Database

type Database = database.Config

type HandlerFunc

type HandlerFunc func(w http.ResponseWriter, r *http.Request) (context.Context, error)

HandlerFunc is the signature for auth handler functions that run before each request. In the slim build, auth is handled externally by the caller.

type HookFn

type HookFn func(*core.Result)

type HttpService

type HttpService struct {
	atomic.Value
	// contains filtered or unexported fields
}

func NewGraphJinService

func NewGraphJinService(conf *Config, options ...Option) (*HttpService, error)

NewGraphJinService a new service

func (*HttpService) Attach

func (s *HttpService) Attach(mux Mux) error

Attach route to the internal http service

func (*HttpService) AttachWithNS

func (s *HttpService) AttachWithNS(mux Mux, namespace string) error

AttachWithNS a namespaced route to the internal http service

func (*HttpService) Close

func (s *HttpService) Close() error

Close shuts down the in-process service resources owned by HttpService. It is useful for embedded use and tests that do not call Start().

func (*HttpService) Deploy

func (s *HttpService) Deploy(conf *Config, options ...Option) error

Deploy a new configuration

func (*HttpService) GetDB

func (s *HttpService) GetDB() *sql.DB

GetDB fetching internal db client (returns any connection from the pool)

func (*HttpService) GetGraphJin

func (s *HttpService) GetGraphJin() *core.GraphJin

GetGraphJin fetching internal GraphJin core

func (*HttpService) GraphQL

func (s *HttpService) GraphQL(ah HandlerFunc) http.Handler

GraphQLis the http handler the GraphQL endpoint

func (*HttpService) GraphQLWithNS

func (s *HttpService) GraphQLWithNS(ah HandlerFunc, ns string) http.Handler

GraphQLWithNS is the http handler the namespaced GraphQL endpoint

func (*HttpService) ModuleRoutes added in v3.35.0

func (s *HttpService) ModuleRoutes() []module.Route

ModuleRoutes returns the HTTP routes contributed by mounted modules. Applications attaching the service to their own mux can register these alongside the standard endpoints.

func (*HttpService) REST

func (s *HttpService) REST(ah HandlerFunc) http.Handler

REST is the http handler the REST endpoint

func (*HttpService) RESTWithNS

func (s *HttpService) RESTWithNS(ah HandlerFunc, ns string) http.Handler

RESTWithNS is the http handler the namespaced REST endpoint

func (*HttpService) Reload

func (s *HttpService) Reload() error

Reload re-runs database discover and reinitializes service.

func (*HttpService) Shutdown

func (s *HttpService) Shutdown(ctx context.Context) error

Shutdown gracefully stops the running HTTP server so that a blocking Start returns. In-flight requests are drained until the context deadline, after which the server is force-closed. It is safe to call more than once and before Start (a no-op when the server was never started). Callers that embed the service and run their own signal handling use this to unblock Start; the service resources (databases, cache, etc.) are then released as Start returns, or explicitly via Close.

func (*HttpService) Start

func (s *HttpService) Start() error

Start the service listening on the configured port

type KeystoreConfig

type KeystoreConfig = configmodule.KeystoreConfig

type Mux

type Mux = httpapi.Mux

type Option

type Option func(*graphjinService) error

func OptionDisableQueryLearning

func OptionDisableQueryLearning() Option

OptionDisableQueryLearning suppresses dev-mode named-query and fragment auto-save for this embedded service instance. Existing saved queries remain discoverable and executable. This is intended for deterministic evaluation and other read-only harnesses whose catalog must not mutate while measured.

func OptionSetDB

func OptionSetDB(db *sql.DB) Option

OptionSetDB sets a new db client. The connection is stored under the DefaultDBName key in the dbs map for backward compatibility.

func OptionSetDatabases

func OptionSetDatabases(dbs map[string]*sql.DB) Option

OptionSetDatabases sets named database clients for multi-database embeddings.

func OptionSetFS

func OptionSetFS(fs core.FS) Option

OptionSetFS sets service filesystem

func OptionSetHookFunc

func OptionSetHookFunc(fn HookFn) Option

OptionSetHookFunc sets a function to be called on every request

func OptionSetLogOutput

func OptionSetLogOutput(output zapcore.WriteSyncer) Option

OptionSetLogOutput sets the log output writer (e.g., os.Stderr for MCP stdio mode)

func OptionSetModule added in v3.35.0

func OptionSetModule(mods ...module.Module) Option

OptionSetModule registers optional product-surface modules (embedded web console, OpenAPI export, ...). The application supplies them; the service knows only the module.Module interface. Modules read their own section under the top-level `modules:` config key; without a matching section a module stays inert.

func OptionSetMutationHook added in v3.36.11

func OptionSetMutationHook(h core.MutationHook) Option

OptionSetMutationHook installs a hook that receives the open mutation transaction and the row changes captured by the engine.

func OptionSetNamespace

func OptionSetNamespace(namespace string) Option

OptionSetNamespace sets service namespace

func OptionSetQueryPolicyHook added in v3.36.13

func OptionSetQueryPolicyHook(h core.QueryPolicyHook) Option

OptionSetQueryPolicyHook installs a request-scoped policy hook that can constrain compiled query IR before SQL generation.

func OptionSetRuntimeSchemaDDLDir

func OptionSetRuntimeSchemaDDLDir(dir string) Option

OptionSetRuntimeSchemaDDLDir sets where the core stores generated schema-DDL restart snapshots, relative to the service filesystem root.

func OptionSetZapLogger

func OptionSetZapLogger(zlog *zap.Logger) Option

OptionSetZapLogger sets service structured logger

type RateLimiter

type RateLimiter = configmodule.RateLimiter

type RedisConfig

type RedisConfig = configmodule.RedisConfig

type SecretsConfig

type SecretsConfig = configmodule.SecretsConfig

type Serv

type Serv = configmodule.Service

Directories

Path Synopsis
Package config contains service configuration mechanics.
Package config contains service configuration mechanics.
Package database contains service database configuration and adapters.
Package database contains service database configuration and adapters.
Package http contains the service HTTP routing contract.
Package http contains the service HTTP routing contract.
Package lifecycle owns service startup and shutdown mechanics.
Package lifecycle owns service startup and shutdown mechanics.
Package module is the seam between the service and optional product-surface modules (embedded web console, OpenAPI export, ...).
Package module is the seam between the service and optional product-surface modules (embedded web console, OpenAPI export, ...).

Jump to

Keyboard shortcuts

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