framework

package module
v0.3.68 Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2026 License: LGPL-2.1 Imports: 46 Imported by: 7

README

Golaxy Framework

English | 简体中文

Golaxy Framework is a Go service framework for real-time, distributed backends. It uses the EC (Entity-Component) system and Actor-style serialized execution model from Golaxy Core as its kernel, then adds application bootstrap, service and runtime assembly, distributed infrastructure, RPC, gateways, and a network protocol stack.

The project is designed for game servers, long-lived connection gateways, stateful business services, remote-control platforms, and other real-time systems that need entity-oriented state management and cross-node communication.

Contents

Positioning

Golaxy Framework is the server-side extension layer of the Golaxy ecosystem. It focuses on the following concerns:

  • Assemble, start, and stop multiple logical services and replicas in one process.
  • Isolate stateful workloads in runtimes, each of which serializes tasks and entity state on its owning goroutine.
  • Model composable, persistent, and globally addressable business objects with entities, components, and prototypes.
  • Integrate logging, configuration, messaging, discovery, distributed locks, distributed entities, and RPC behind consistent APIs.
  • Provide GAP and GTP protocols plus gateway features for service messaging and long-lived client connections.

This repository is a framework library; it does not bundle application services or infrastructure processes. The default assembly connects to NATS and ETCD. Golaxy Scaffold is the companion game-project scaffold and build-time toolset. Its primary capabilities are Protobuf code generation for Go/Godot and Excel-table schema, code, and data processing; it does not implement friend, mail, or other product services. See Golaxy Examples for end-to-end usage.

Business and tooling boundaries
Scope Typical responsibility Recommended integration
Long-lived connection core services Real-time player state, rooms, battles, and scenes Client RPC travels through GAP → GTP → Gate, then GAP over NATS to the target service.
Independent HTTP business services Common request/response features such as friends, mail, and operations administration Expose HTTP APIs; call internal RPC or the appropriate data service when real-time state is required.
Golaxy Scaffold Game-project layout and build tooling, not product-domain services Generate Go/Godot protocol code with the Protobuf toolchain, and use excelc to turn .xlsx into .proto, access code, and JSON/binary table data.

Key capabilities

  • Application and service orchestration: Cobra/Viper-based commands and configuration, multiple services and replicas, signal-driven graceful shutdown, and optional pprof.
  • Actor + EC execution model: serialized runtime state, composable entities and components, optional real-time frame loops, and automatic dependency injection.
  • Asynchronous coordination: runtime scheduling, lifecycle scopes, background goroutines, timers, distinct Future/Signal/Stream semantics, Future combinators, and Runtime continuations.
  • Distributed infrastructure: a NATS broker, ETCD service discovery, ETCD/Redis distributed mutexes, service-node registration, and distributed-entity lookup.
  • RPC: Service, Runtime, Entity, and Client targets with unicast, load balancing, broadcast, one-way calls, and future-based results.
  • Gateway and routing: TCP/WebSocket sessions, authentication, reconnection, clock synchronization, entity-to-session mappings, logical groups, and multicast.
  • Database integrations: GORM for MySQL, PostgreSQL, SQL Server, and SQLite, plus Redis and MongoDB add-ins and tag-based client injection.
  • Protocol stack: GAP for application messages and dynamic arguments; GTP for connection handshakes, ordering, heartbeats, compression, and optional encryption.

Architecture

flowchart TB
    subgraph Execution[Execution model]
        App[App<br/>configuration, commands, replicas] --> Service[Service<br/>concurrent service context]
        Service --> Runtime[Runtime<br/>actor goroutine]
        Runtime --> Entity[Entity]
        Entity --> Component[Component]
        Service -.-> ServiceAddins[service add-ins]
        Runtime -.-> RuntimeAddins[runtime add-ins]
    end

    subgraph ClientPath[Client long-connection RPC path]
        direction LR
        ClientRPC[Client / RPCli] <-->|RPC / Oneway RPC| ClientGAP[GAP<br/>Forward wrapping RPC]
        ClientGAP <-->|as GTP Payload| GTPLink[GTP<br/>TCP / WebSocket]
        GTPLink <--> GateNode[Gate<br/>session, authentication, reconnect]
        GateNode <-->|Payload| GateProcessor[Gate RPC Processor<br/>GAP codec and routing]
    end

    subgraph InternalPath[Service-to-service RPC path]
        direction LR
        ServiceCaller[Service / Runtime / Entity] <--> ServiceProcessor[Service RPC Processor]
    end

    GateProcessor <-->|GAP Forward| NatsBus[NATS Broker<br/>GAP messages only]
    ServiceProcessor <-->|GAP RPC Request / Reply / Oneway| NatsBus
    NatsBus <-->|GAP| TargetProcessor[Service / Forward RPC Processor]
    TargetProcessor -.->|dispatch to Service / Runtime / Entity| Service
    ServiceAddins <-->|registration, lookup, leases, locks| ETCD[ETCD]
RPC transport paths
Path Actual protocol path Description
Client → Service RPC → GAP MsgForward → GTP Payload → Gate → GAP MsgForward → NATS → ForwardProcessor A client sends RPC as well. Gate decodes GAP, resolves the service node from the Session/Entity mapping, and forwards the call.
Service → Service RPC → GAP MsgRPCRequest / MsgOnewayRPC → NATS → ServiceProcessor Internal service communication uses GAP over NATS directly and never enters GTP. RPC Reply returns over the same path.
Service → Client RPC → GAP MsgForward → NATS → Gate → GAP → GTP Payload → Client Gate resolves a Session from a client unicast address or logical group and sends it over the GTP connection. Client RPCli decodes GAP and invokes a local script.

For a client call, RPCli serializes MsgRPCRequest, MsgOnewayRPC, or MsgRPCReply into MsgForward.TransData. The outer MsgForward is GAP-encoded and sent as a GTP Payload. The Gate RPC Processor receives that Payload from the GTP session, decodes GAP, rebuilds the forwarding origin and destination, and passes it to dsvc for publication through NATS. Consequently, GTP ends at the client connection boundary; the service message bus uniformly carries GAP.

Core objects
Object Responsibility
App Registers service assemblers, loads configuration, starts the requested replicas, and waits for every service during shutdown.
IService Extends core/service.Context with service add-ins, configuration, logging, private memory, and Runtime/Entity builders.
IRuntime Extends core/runtime.Context with a task queue, entity manager, optional frame loop, and runtime add-ins.
Entity Prototype Declares an entity type, default scope, component set, and metadata in the service entity library.
Entity A stateful business object in a runtime. Global entities can be advertised automatically by the distributed-entity add-in.
Component A unit of behavior composed into an entity. ComponentBehavior exposes the owning Runtime, Service, logger, async helpers, and RPC helpers.
Add-in A replaceable Service or Runtime extension. Defaults are installed only when a capability with the same name is still absent.
Future / Signal / Stream Represent one-shot results, result-free completion, and continuous results; ContinueOn schedules a Future continuation onto the owning Runtime.
Execution and shutdown
  • Every service registered with SetAssembler starts with one replica by default. Override this with startup.services; IService.ReplicaNo() returns a zero-based replica number.
  • Each service replica runs in its own goroutine, and one service may own multiple runtimes.
  • Ordinary runtime tasks and entity state are serialized on the owning Runtime goroutine. Do not access runtime state from other goroutines unless an API explicitly documents concurrent safety.
  • App listens for SIGHUP, SIGINT, SIGTERM, and SIGQUIT. The first signal cancels the shared context, after which the application waits for all service replicas to terminate.

Actor + EC framework in depth

How Actor and EC work together

Golaxy combines two orthogonal models: Actor defines who owns mutable state and where code executes, while EC defines how business objects are decomposed, composed, and evolved.

Model Problem it solves Golaxy concepts
Actor Isolates mutable state and prevents conflicting writes through serialized message processing. Runtime, its task queue and owning goroutine, Futures, and continuations.
EC Gives identity to stateful objects and composes capabilities from replaceable components. Entity, Component, Prototype, lifecycle callbacks, and EntityTree.

The Actor boundary is the Runtime, not an individual Entity. A Runtime may manage one Entity or a group of entities that require strict execution ordering. EC here means Entity-Component; unlike a conventional data-oriented ECS, its primary programming model is not global System queries and batch processing. Behavior normally lives directly in Entity or Component lifecycle methods.

Runtime is the state and execution boundary

Every Runtime owns a task queue, entity manager, entity tree, and optional frame loop. Application code should treat the owning Runtime goroutine as the sole ordinary writer of its Entity and Component state:

sequenceDiagram
    participant Source as External goroutine / RPC / timer
    participant Queue as Runtime task queue
    participant RuntimeLoop as Runtime goroutine
    participant EC as Entity / Components
    Source->>Queue: Submit / Post / RPC dispatch
    Queue->>RuntimeLoop: Dequeue in order
    RuntimeLoop->>EC: Execute logic and mutate state
    EC-->>RuntimeLoop: async.Result
    RuntimeLoop-->>Source: Complete Future
    Source->>Queue: Re-enqueue ContinueOn continuation
    Note over Queue,RuntimeLoop: Update and LateUpdate are serialized in the same boundary
  • Ordinary tasks, entity lifecycle transitions, and frame callbacks never run concurrently inside one Runtime, so business state within that Runtime normally needs no locks.
  • An Entity does not automatically receive its own goroutine. Putting several entities in one Runtime makes them share one serialized execution domain.
  • Code outside the Runtime may directly use only explicitly concurrent-safe contexts or read-only surfaces. Schedule state reads and writes through Submit, Post, RPC, or another dispatch entry point.
  • Spawn is intended for blocking I/O and independent computation, but its function runs in a new goroutine and must not touch Runtime state directly. Use ContinueOn to schedule subsequent Future handling back onto the Runtime.
  • With the frame loop enabled, Update() and LateUpdate() share the execution boundary with ordinary tasks. A slow or blocking callback therefore delays both message handling and frame progress and should be moved off the Actor goroutine.
  • Framework-created runtimes use an unbounded task queue by default. This avoids immediate capacity failures for producers, but the application must control backlog through rate limits, timeouts, and metrics.

Service is the concurrent outer scope around runtimes. It holds service add-ins, entity/component prototype libraries, and the global entity index. Even after a cross-runtime or cross-node lookup resolves an entity, the call must still be dispatched to its owning Runtime instead of mutating it concurrently through a side channel.

Entity, Component, and Prototype
Concept Semantics
Entity A business object with an ID (generated when no persistence ID is supplied), scope, and metadata. It is also a component container and lifecycle root.
Component A unit of state or behavior attached to an Entity. Components can be added, enabled, and disabled dynamically; removable components can also be detached. Each has its own lifecycle.
Entity Prototype A reusable service-level construction definition for the Entity implementation, default scope, metadata, component options, and built-in component set.
Component Prototype A component construction definition registered by its full Go type name and available to prototype declarations and dependency injection.
EntityManager The Runtime-local entity collection responsible for entry, removal, and lifecycle progression.
EntityTree Parent-child relationships inside a Runtime, with attach, detach, move, and traversal operations. Changing a tree edge does not itself destroy an Entity.

An Entity may contain several Components with the same name. GetComponent returns the first match, while GetComponents returns all matches. Components reuse the Entity ID by default; enable SetComponentUniqueID(true) to assign independent IDs and make GetComponentById available.

Entity, Component, and Runtime also expose in-process signal/slot-style events. An event is emitted synchronously on the sender's current goroutine; it neither enters the Runtime task queue nor provides cross-process delivery. Code on an external goroutine must therefore enter the Runtime before emitting a business event. Subscription handles stored in the object's Managed() collection are unbound automatically when their owner is destroyed or terminated.

Scope determines where an Entity can be found, not where it executes:

Scope Lookup range Distributed behavior
ec.Scope_Local Only the owning Runtime's entity manager. It does not enter the Service global index and is not advertised by the default distributed-entity add-in.
ec.Scope_Global Both the Runtime-local index and the Service global entity index. The default distributed-entity registry publishes its location to ETCD for discovery by other nodes.

Scope_Global provides addressability; it does not make an Entity concurrency-safe. Remote calls and service-level lookups must ultimately re-enter the owning Runtime for execution.

Lifecycle and frame updates

The Runtime owns Entity and Component state transitions. Except for the Component enable/disable branch, lifecycles progress from construction toward destruction. Application code should never force a state transition itself:

Entity activation:    Born -> Entered -> Awakened -> Starting -> Alive
Entity deactivation:  Leaving -> Shutting -> Dead -> Destroyed

Component activation: Born -> Attached -> Awakened -> Enabling -> Starting -> Alive
Disable and re-enable: Enabling / Starting / Alive -> Idle; Idle -> Starting -> Alive
Component removal:    Detaching -> Shutting -> Disabling -> Dead -> Destroyed
Object Callback order and semantics
Entity Awake() at most once → Start() at most once → per-frame Update() / LateUpdate()Shut()Dispose(). Paired shutdown callbacks run only when the corresponding earlier phase completed.
Component Awake() at most once → OnEnable()Start() at most once → per-frame Update() / LateUpdate()Shut()OnDisable()Dispose(). OnEnable() / OnDisable() may repeat as enabled state changes.

Initial activation follows this concrete order:

  1. Framework resolves component dependencies when automatic injection is enabled;
  2. Entity Awake();
  3. each Component Awake();
  4. enabled Components OnEnable();
  5. enabled Components Start();
  6. Entity Start(), after which the Entity becomes Alive.

During Entity deactivation, Entity Shut() runs first, followed by Component Shut() in reverse order. Components then receive OnDisable() and Dispose() in reverse order, and Entity Dispose() runs last. Lifecycle interfaces are optional; objects without a particular callback still progress normally through their states.

When AddComponent is called on an active Entity, the Runtime advances the new component through Awake, OnEnable, and Start. Removal invokes the paired shutdown path. Components added directly at runtime are removable by default, while built-in components declared by an Entity Prototype are not; opt in with ComponentDescriptor.SetRemovable(true) when a built-in component must be detachable. Dynamic component changes, SetEnabled, Entity Destroy, and EntityTree mutations must all run inside the owning Runtime.

Prototype composition and component injection

Prototypes separate “what a business object contains” from instance creation. BuildEntityPT(name) declares a template in the Service EntityLib, and BuildEntity(name) constructs an instance from the current template. Redeclaring the same prototype name replaces the previous definition; it does not retroactively alter entities that already exist.

Automatic injection is enabled on runtimes by default. Before an Entity or a newly added component activates, Framework scans every Component on that Entity and injects matching sibling components into pointer or interface fields. Dependencies are therefore available from Component Awake() onward:

type Movement struct {
	framework.ComponentBehavior
	Position *Position `ec:"position"`
}

func (m *Movement) Awake() {
	if m.Position == nil {
		panic("movement requires position")
	}
}
  • The tag format is ec:"component name,full component prototype"; either part can be selected as needed. ec:"position" injects by component name.
  • An untagged pointer-to-struct field attempts to infer the component name and full prototype name from its type.
  • If the tag names a registered component prototype but no matching component is attached, injection may construct and add that component dynamically.
  • A missing match leaves the field unchanged, normally nil; validate required dependencies explicitly in Awake().
  • Adding a component to an active Entity rescans every Component, allowing existing components to receive the newly available dependency.

Automatic injection targets Component fields. An Entity should obtain its components through the component-manager API while inside the Runtime. Disable reflection-based injection with SetAutoInjection(false) when explicit wiring is preferred or the activation path is especially performance-sensitive.

Choosing Runtime granularity
Organization Good fit Main trade-off
One main Entity per Runtime Independent stateful objects such as players, devices, or order workflows. Calling IService.BuildEntity() directly uses this pattern by default. Strong isolation and parallelism, but more runtimes. The Runtime terminates automatically when its main Entity deactivates.
A group of entities in one Runtime A room, battle, scene, or another group that needs strictly ordered updates. Use SetRuntime(rt) to join an existing Runtime. Straightforward group consistency, but one slow task stalls the entire group.
An independent long-lived Runtime An in-service scheduler, matchmaker, or resident state machine. Create it first with BuildRuntime(), then add entities as needed. Its lifecycle is not coupled to one business Entity, so its termination condition must be managed explicitly.

As a rule, place state that must change in one serialized transaction in the same Runtime, and split state that needs true parallelism across runtimes. Treat cross-Runtime coordination as asynchronous message exchange; do not rely on shared mutable objects or implicit transactions spanning runtimes.

Requirements

Component Requirement Purpose
Go 1.25.0+ Matches the current go.mod.
NATS Required by default Default broker and service-to-service GAP/RPC transport. The default endpoint is localhost:4222.
ETCD Required by default Default discovery, distributed synchronization, and distributed-entity query/registration. The default endpoint is localhost:2379.
Redis Optional Redis-backed distributed synchronization and the Redis database add-in.
SQL database Optional MySQL, PostgreSQL, SQL Server, or SQLite through the GORM add-in.
MongoDB Optional MongoDB database add-in.

The default service assembly actively initializes the NATS and ETCD add-ins during startup, so these services must be reachable even for the minimal example. External dependencies may differ after replacing the defaults through installation hooks.

Quick start

1. Create a module and install the framework
mkdir golaxy-demo
cd golaxy-demo
go mod init example.com/golaxy-demo
go get git.golaxy.org/framework@latest
2. Prepare the default infrastructure

Start reachable NATS and ETCD instances listening at:

  • NATS: localhost:4222
  • ETCD: localhost:2379

You can select different endpoints with startup flags or a configuration file.

3. Create a minimal service
package main

import "git.golaxy.org/framework"

type LobbyService struct {
	framework.ServiceBehavior
}

func (*LobbyService) OnStarted(svc framework.IService) {
	rt, err := svc.BuildRuntime().
		SetName("main").
		SetEnableFrame(true).
		SetFPS(20).
		New()
	if err != nil {
		svc.S().Panicw("create runtime failed", "error", err)
	}

	svc.S().Infow("lobby service started", "runtime_id", rt.Id())
}

func main() {
	framework.NewApp().
		SetAssembler("lobby", &LobbyService{}).
		Run()
}
4. Run
go run .

Press Ctrl+C for graceful shutdown. The lobby name passed to SetAssembler is also:

  • the service key in startup.services;
  • the logical service name returned by IService.Name();
  • the configuration subtree returned by IService.ServiceConf();
  • the service name advertised by the distributed-service add-in.

When SetAssembler receives an instance or reflection type implementing IService, it creates a fresh instance of that concrete type for every replica; it does not reuse the supplied pointer.

Configuration

Sources and precedence

App binds Cobra flags to Viper. For the same key, values are resolved in this order:

  1. A value set through app.Conf().Set(...);
  2. An explicitly supplied command-line flag;
  3. An environment variable;
  4. A local configuration file;
  5. A remote configuration provider;
  6. The built-in flag default.

Set conf.local_path to load a local file; its format is inferred from the extension. Remote configuration is read once at startup through a Viper remote provider. The current dependency supports etcd, etcd3, consul, firestore, and nats; the framework does not automatically watch for subsequent changes.

Environment variables follow Viper's default mapping: keys are uppercased, but dots are retained. With the prefix GAME, for example, log.level maps to GAME_LOG.LEVEL. To use the more conventional GAME_LOG_LEVEL, configure an EnvKeyReplacer on app.Conf() before Run. Because conf.env_prefix is resolved before local and remote configuration are loaded, set it through a command-line flag or app.Conf().Set.

Built-in settings
Setting Default Description
log.level info debug, info, warn, error, dpanic, panic, or fatal.
log.encoder development Zap encoder: development or production.
log.format console Output format: console or json.
log.async true Enables the buffered log writer.
log.buffer_size 524288 Asynchronous log buffer size in bytes.
log.flush_interval 1s Asynchronous log flush interval.
conf.env_prefix empty Environment-variable prefix.
conf.local_path empty Local configuration file; no file is read when empty.
conf.remote_provider empty Viper remote provider; no remote configuration is read when empty.
conf.remote_endpoint empty Remote configuration endpoint.
conf.remote_path empty Remote configuration key or file path.
nats.address localhost:4222 Default NATS endpoint in host:port form.
nats.username empty NATS username.
nats.password empty NATS password.
etcd.address localhost:2379 Default ETCD endpoint in host:port form.
etcd.username empty ETCD username.
etcd.password empty ETCD password.
service.version v0.0.0 Node version advertised through discovery.
service.meta empty map Node metadata advertised through discovery.
service.ttl 10s Service registration lease; must be at least 3 seconds.
service.future_timeout 3s Default timeout for service interaction futures; must be at least 300 milliseconds.
service.dent_ttl 10s Distributed-entity registration lease; must be at least 3 seconds.
service.auto_recover false Recovers panics during Service/Runtime execution and reports them to the logger.
startup.services 1 for every registered service Map of service name to replica count. Invalid or non-positive counts disable that service.
pprof.enable false Enables the Go pprof HTTP server.
pprof.address 0.0.0.0:6060 pprof listen address.

The application-level nats.address and etcd.address settings are single-endpoint shortcuts. Use the corresponding add-in installation hook when you need multiple endpoints, TLS, or an existing client.

Configuration file example
log:
  level: info
  encoder: production
  format: json
  async: true

nats:
  address: localhost:4222

etcd:
  address: localhost:2379

service:
  version: v1.0.0
  meta:
    region: cn-east-1
    environment: production
  ttl: 10s
  future_timeout: 3s
  dent_ttl: 10s
  auto_recover: true

startup:
  services:
    lobby: "2"
    gate: "1"

pprof:
  enable: false
  address: 127.0.0.1:6060

lobby:
  tick_interval: 50ms
  matchmaking_region: cn-east-1

Inside the lobby service:

appConf := svc.AppConf()         // the full merged configuration
serviceConf := svc.ServiceConf() // the lobby subtree; it may be nil when absent

Command-line override example:

./your-app \
  --startup.services lobby=2,gate=1 \
  --nats.address localhost:4222 \
  --etcd.address localhost:2379 \
  --conf.local_path ./config.yaml

If a configuration file explicitly defines startup.services, include every service that should run. Registered services omitted from that map are treated as having zero replicas.

Programming model

App and service replicas
  • NewApp() creates an independent Cobra root command and Viper instance.
  • SetAssembler(name, assembler) can register multiple logical services; registering the same name replaces the previous assembler.
  • InitCB adds flags or Cobra subcommands; StartingCB runs after configuration and pprof initialization; TerminateCB runs after every service has stopped.
  • App.Cmd() and App.Conf() expose extension points before Run(). Configuration and assembly methods should be called from the same goroutine.
  • IService.Memory() is a replica-private concurrent key/value store, while ReplicaNo() returns the current replica number.
Service lifecycle
Phase Intended work
OnBirth The Service Context, configuration, and base logger exist. Install or replace service add-ins here.
Default assembly The framework fills in logging, configuration, broker, discovery, distributed sync, distributed service, entity query, and RPC.
OnBuilt Default add-ins are ready. This is the final application hook before the service add-in manager is frozen.
OnStarting Service add-ins are frozen and active; they can no longer be installed or removed.
OnStarted The distributed service has completed BringUp; subscriptions and node registration are ready for communication.
OnHeartbeat Called approximately once per second while the service is running.
OnTerminating Shutdown has started; notify application tasks to stop.
OnTerminated Wait groups and add-ins have stopped. The framework then flushes logging and closes shared resources.

Additional Service lifecycle interfaces cover entity prototypes, component prototypes, and global-entity registration and deregistration. See service_lifecycle.go for the complete contracts.

Runtime, Entity, and Component

This section covers the builder APIs; see Actor + EC framework in depth for execution boundaries, state machines, and composition rules.

BuildRuntime() starts from these defaults:

Option Default
Automatic start enabled
Task queue unbounded
Frame loop disabled
Target frame rate 30 (used only when the frame loop is enabled)
Automatic component dependency injection enabled
Panic recovery inherited from the Service
Continue after entity-activation panic disabled; the failed entity is removed

Customize these values with SetName, SetPersistId, SetMainEntity, SetEnableFrame, SetFPS, SetAutoInjection, and SetPanicHandling. A runtime terminates automatically after its main entity is deactivated.

The following example declares a global player prototype and creates an entity:

package main

import (
	"git.golaxy.org/core/ec"
	"git.golaxy.org/framework"
)

const playerPrototype = "player"

type GameService struct {
	framework.ServiceBehavior
}

type Player struct {
	framework.EntityBehavior
}

type Position struct {
	framework.ComponentBehavior
	X float64
	Y float64
}

type Movement struct {
	framework.ComponentBehavior
	Position  *Position `ec:"position"`
	VelocityX float64
	VelocityY float64
}

func (m *Movement) Awake() {
	if m.Position == nil {
		panic("movement requires position")
	}
	m.VelocityX = 0.25
}

func (m *Movement) Update() {
	m.Position.X += m.VelocityX
	m.Position.Y += m.VelocityY
}

func (*GameService) OnBuilt(svc framework.IService) {
	svc.BuildEntityPT(playerPrototype).
		SetInstance(&Player{}).
		SetScope(ec.Scope_Global).
		AddComponent(&Position{}, "position").
		AddComponent(&Movement{}, "movement").
		Declare()
}

func (*GameService) OnStarted(svc framework.IService) {
	_, err := svc.BuildEntity(playerPrototype).
		SetRuntimeCreator(
			svc.BuildRuntime().
				SetEnableFrame(true).
				SetFPS(20),
		).
		SetMeta(map[string]any{"region": "cn-east-1"}).
		New()
	if err != nil {
		svc.S().Panicw("create player failed", "error", err)
	}
}
  • BuildEntityPT(...).Declare() registers the prototype in the current Service's entity library.
  • When IService.BuildEntity() creates an entity without a selected Runtime, the framework creates a new Runtime and makes the entity its main entity.
  • Movement.Position is injected before Component Awake(). The frame loop targets 20 FPS and calls Update() serially with the Runtime's other tasks.
  • Use EntityCreator.SetRuntime(rt) to add an entity to an existing Runtime. Code already on the Runtime goroutine may also use IRuntime.BuildEntity().
  • Only ec.Scope_Global entities are advertised to ETCD by the default distributed-entity registry.
  • Custom entities and components embed EntityBehavior and ComponentBehavior respectively to gain direct access to the owning Runtime, Service, logger, async helpers, and RPC helpers.
Concurrency and async rules
API Execution location Guidance
Submit / SubmitVoid Owning Runtime goroutine Submit result-bearing work that reads or modifies Runtime, Entity, or Component state.
Post Owning Runtime goroutine Dispatch work whose result is not needed; no Future is allocated.
Spawn / SpawnVoid New goroutine managed by a Scope Use for blocking I/O or independent computation; do not access Runtime state directly.
After / At Async timer completing one Future Use for one-shot timers scoped to an Entity or Component lifetime.
Every / FromChan Produces a single-consumer Stream Use for periodic timers or channel bridging; ends when the Scope or source closes.
ContinueOn / ContinueOnVoid Reschedules a continuation onto the owning Runtime Continue accessing Runtime-local state after a Future completes.
async.Race / FirstSuccess / All / AllSettled Combines one-shot Futures Select the first completion or success, or collect all results.

A Future retains one replayable result, a Signal reports result-free lifecycle completion, and a Stream carries continuous results to one consumer. Entity and Component helpers bind work to their respective AsyncScope() values. When the owner dies, background tasks and streams receive cancellation, while work or continuations not yet executed stop or return ErrAsyncCallerNotAlive.

Add-in system

Default assembly
Scope Capability Default implementation Primary access point
Service Logging Zap logger svc.L() / svc.S()
Service Configuration Viper config add-in svc.AppConf() / svc.ServiceConf()
Service Broker NATS svc.Broker()
Service Discovery ETCD svc.Registry()
Service Distributed synchronization ETCD mutex svc.DistSync()
Service Distributed service GAP + Broker + Discovery + DSync svc.DistService()
Service Distributed-entity query ETCD + local Ristretto cache svc.DistEntityQuerier()
Service RPC Built-in RPC facade and processor chain svc.RPC()
Runtime Logging Reuses the Service logger rt.L() / rt.S()
Runtime RPC call stack Built-in rpcstack rt.RPCStack()
Runtime Distributed-entity registration ETCD lease rt.DistEntityRegistry()
Replacing defaults

There are two ways to replace a default:

  1. Install an add-in with the same name during OnBirth;
  2. Implement the corresponding InstallService... or InstallRuntime... interface.

For every capability, the framework checks “already installed → instance installation hook → assembler installation hook → default implementation” and requires the capability to exist afterward. This example replaces the default ETCD-backed distributed mutex with Redis:

import (
	"git.golaxy.org/framework"
	"git.golaxy.org/framework/addins"
)

func (*LobbyService) InstallDistSync(svc framework.IService) {
	addins.DsyncRedis.Install(svc,
		addins.DsyncRedisWith.RedisURL(
			svc.AppConf().GetString("redis.url"),
		),
	)
}

Service add-ins may be installed in OnBirth, an installation hook, or OnBuilt, and are frozen before the Starting callback. Because OnBuilt runs after default assembly, use it to append custom add-ins; replace a default in OnBirth or the corresponding installation hook. Runtime add-ins may be installed or removed while running, but those operations should execute on the owning Runtime goroutine.

Optional add-ins and tools
Package Capability
addins/gate TCP/WebSocket listeners, GTP handshakes, session authentication, reconnect migration, and data/event I/O.
addins/gate/cli Low-level Gate client with connect, reconnect, clock probing, and Future management.
addins/router Entity/Session mappings, ETCD-backed logical groups, unicast, and multicast.
addins/rpc/rpcpcsr Service, Gate, and Forward RPC processors and deliverers.
addins/rpc/rpcli Client RPC built on the Gate client and GAP.
addins/db/sqldb GORM connections for MySQL, PostgreSQL, SQL Server, and SQLite.
addins/db/redisdb Tagged Redis clients.
addins/db/mongodb Tagged MongoDB clients.
addins/db InjectDB injects clients by db struct tag; MigrateDB executes migration hooks in order.

The root addins package re-exports built-in add-in descriptors and their With option entry points for convenient use in assembly code.

Distributed communication and protocols

Service addressing and RPC

dsvc creates five broker address classes for every service node:

  • global broadcast;
  • global load balancing;
  • same-service broadcast;
  • same-service load balancing;
  • node unicast.

During bring-up, a node subscribes to its addresses before acquiring a distributed lock, checking for duplicates, and registering with discovery. This prevents an advertised node from losing messages before its subscriptions are ready. The current dsvc processing chain requires the broker to report AtMostOnce delivery semantics; a replacement broker must satisfy that constraint.

RPC builds on this addressing model and provides:

  • Service, Runtime, Entity, and Client targets;
  • named-service calls, random load balancing, and global load balancing;
  • same-service and global one-way broadcasts;
  • call-chain propagation and typed parse/assert helpers for up to 16 return values.
GAP and GTP
Layer Responsibility
GAP (Golaxy Application Protocol) Defines Forward, RPC Request/Reply, Oneway RPC, and other application messages. GAP can run over GTP or a Broker.
GAP Variant Represents Null, integers, floating-point numbers, booleans, bytes, strings, Array, Map, Error, CallChain, and custom values on the wire.
GTP (Golaxy Transfer Protocol) Runs over TCP/WebSocket and handles handshakes, authentication, message ordering, heartbeats, clock synchronization, reconnection, compression, and optional encryption.
GTP Codec / Transport Implements the wire codec and the connection I/O, retries, event delivery, and protocol state machine.

Protocol boundary: GTP is used only for the TCP/WebSocket connection between Client and Gate. Client RPC is a GAP message carried in a GTP Payload. After Gate enters the service domain, and for every service-to-service RPC, NATS transports GAP only; GTP is never nested into the NATS path.

Security note: GTP supports ECDHE, signing, and verification, but does not provide certificate validation itself. For high-security deployments, enable TLS below GTP on TCP/WebSocket and consider disabling GTP's built-in payload encryption; protocol signatures are not a replacement for a complete PKI trust chain. Do not expose pprof directly to untrusted networks either.

Project layout

Path Responsibility
./ App, Service, Runtime, Entity/Component behaviors, builders, lifecycles, and async helpers.
addins Aggregated exports for built-in add-in descriptors and option entry points.
addins/broker Broker abstraction, delivery semantics, and NATS implementation.
addins/conf Viper-backed application configuration and per-service subtrees.
addins/discovery Service registration, lookup, watch APIs, and ETCD implementation.
addins/dsync Distributed mutex abstraction with ETCD and Redis implementations.
addins/dsvc Service-node bring-up, address generation, GAP messaging, and Future control.
addins/dent Distributed-entity registration, query, events, and local caching.
addins/rpc RPC facade, proxies, call paths, processors, clients, and result parsing.
addins/rpcstack Runtime-scoped RPC call chain and variable stack.
addins/gate GTP gateway, listeners, handshakes, and session management.
addins/router Session routing, entity mappings, logical groups, and multicast.
addins/db SQL, Redis, and MongoDB add-ins plus injection and migration helpers.
net/gap GAP messages, serialization, codec, and dynamic Variant values.
net/gtp GTP messages, codec, cryptographic/compression methods, and transport.
net/netpath Logical network paths for service addresses, topics, and related names.
utils/binaryutil Byte streams, buffer pools, binary I/O, and bounded copying.
utils/concurrent FutureController, listener sets, and lightweight concurrency helpers.

Observability and operational guidance

  • Logging uses Zap. Production deployments will typically choose log.encoder=production and log.format=json; the framework flushes buffered logging during shutdown.
  • service.auto_recover=false is the default. When enabled, the Service and default Runtimes recover execution panics and report them through an error channel; the application must still decide whether continuing is safe for its consistency model.
  • pprof is disabled by default. When enabled, bind pprof.address to loopback or a management network and add access control at the network boundary.
  • Service and entity TTLs must be at least 3 seconds. Set production values according to ETCD latency, network jitter, and failure-detection goals rather than minimizing them blindly.
  • Gate listen addresses, TLS, maximum packet size, compression threshold, authenticator, I/O timeouts, and session inbox capacities are independently configurable through gate.With.
  • Replace the relevant default add-in when you need multiple NATS/ETCD endpoints, TLS, or custom client ownership. Clients supplied by the caller are not closed when an add-in shuts down.

Development and verification

# Format
go fmt ./...

# Run all tests
go test ./...

# Check for data races on supported platforms
go test -race ./...

# Static analysis
go vet ./...

Protocol and low-level utility tests are concentrated in net/gap/variant, net/gtp, net/gtp/codec, net/gtp/method, net/gtp/transport, utils/binaryutil, and utils/concurrent.

Ecosystem and license

  • Golaxy Core: EC system and Runtime/Service execution kernel.
  • Golaxy Scaffold: game-project scaffold centered on Protobuf generation and Excel-table processing.
  • Golaxy Examples: end-to-end service, gateway, and RPC examples.

This project is licensed under the GNU Lesser General Public License v2.1.

Documentation

Overview

Package framework 提供 Golaxy 分布式服务的应用启动、装配与业务开发入口。

它在 git.golaxy.org/core 之上补齐了服务端开发常用的组合能力,包括:

  • App 启动入口,以及基于 Cobra/Viper 的统一配置装载
  • Service 与 Runtime 的默认 add-in 装配
  • Service、Runtime、Entity、Component 之间的强类型桥接
  • 生命周期接口、异步调用辅助,以及实体原型/实体构建器

典型使用方式是先创建 App,注册一个或多个服务装配器,再在服务生命周期 回调中创建 runtime、声明实体原型并生成实体实例。

Index

Constants

This section is empty.

Variables

View Source
var BuildEntityPT = core.BuildEntityPT

BuildEntityPT 创建绑定服务上下文及 prototype 名称的实体原型构建器。

View Source
var (
	// ErrAsyncCallerNotAlive 表示异步结果返回时,发起续体的实体或组件已经失活。
	ErrAsyncCallerNotAlive = errors.New("async caller is not alive")
)
View Source
var (
	// ErrFramework 是 framework 包错误的根错误,可通过 errors.Is 判断错误类别。
	ErrFramework = errors.New("framework")
)

Functions

This section is empty.

Types

type App

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

App 负责装载应用配置、启动已注册的服务副本,并等待所有服务停止。 App 的配置和装配方法应在 Run 前由同一 goroutine 调用。

func NewApp

func NewApp() *App

NewApp 创建一个尚未运行的应用,并初始化命令行、配置及服务装配容器。

func (*App) Cmd added in v0.3.68

func (app *App) Cmd() *cobra.Command

Cmd 返回应用的根 Cobra 命令。 首次调用会注册内置参数并执行 InitCB;该初始化与 Run 共享一次性状态。

func (*App) Conf added in v0.3.68

func (app *App) Conf() *viper.Viper

Conf 返回应用持有的 Viper 配置实例。

func (*App) InitCB

func (app *App) InitCB(cb generic.Action1[*App]) *App

InitCB 设置命令初始化回调。 回调在内置参数注册后、首次执行命令前调用一次,可用于补充 Cobra 参数或子命令。

func (*App) Run

func (app *App) Run()

Run 初始化并执行应用命令,随后启动配置指定的服务副本。 Cobra 返回执行错误时 Run 会 panic;同一个 App 不应并发调用 Run。

func (*App) SetAssembler added in v0.3.68

func (app *App) SetAssembler(name string, assembler any) *App

SetAssembler 注册名为 name 的服务装配器。 assembler 可以是自定义装配器,也可以是实现 IService 的实例或 reflect.Type; 后两者会被转换为按需创建实例的默认装配器。同名注册会替换此前的装配器。

func (*App) StartingCB

func (app *App) StartingCB(cb generic.Action1[*App]) *App

StartingCB 设置应用启动回调。 回调在配置与可选 pprof 服务初始化完成后、启动服务副本前执行。

func (*App) TerminateCB added in v0.1.33

func (app *App) TerminateCB(cb generic.Action1[*App]) *App

TerminateCB 设置应用终止回调。 回调在全部服务副本停止后执行。

type ComponentBehavior added in v0.1.56

type ComponentBehavior struct {
	ec.ComponentBehavior
	// contains filtered or unexported fields
}

ComponentBehavior 扩展 core 组件行为,供自定义组件匿名嵌入。 日志器会按组件实例惰性创建,因此应在组件所属运行时 goroutine 中使用。

func (*ComponentBehavior) After added in v0.3.68

func (c *ComponentBehavior) After(dur time.Duration) async.Future

After 在组件生命周期内等待 dur 后以当前时间完成 Future。

func (*ComponentBehavior) At added in v0.3.68

At 在组件生命周期内等待到 at 后以当前时间完成 Future。

func (*ComponentBehavior) BalanceOnewayRPC added in v0.2.38

func (c *ComponentBehavior) BalanceOnewayRPC(service, comp, method string, args ...any) error

BalanceOnewayRPC 从承载当前实体且服务名匹配的节点中随机选择一个发起单向 RPC。

func (*ComponentBehavior) BalanceRPC added in v0.1.56

func (c *ComponentBehavior) BalanceRPC(service, comp, method string, args ...any) async.Future

BalanceRPC 从承载当前实体且服务名匹配的节点中随机选择一个发起 RPC。

func (*ComponentBehavior) BroadcastOnewayRPC added in v0.2.38

func (c *ComponentBehavior) BroadcastOnewayRPC(excludeSelf bool, service, comp, method string, args ...any) error

BroadcastOnewayRPC 向指定服务中承载当前实体的节点广播单向 RPC;excludeSelf 为 true 时排除源节点。

func (*ComponentBehavior) CliOnewayRPC added in v0.2.38

func (c *ComponentBehavior) CliOnewayRPC(proc, method string, args ...any) error

CliOnewayRPC 向当前实体 ID 对应的客户端单播地址发起单向 RPC。

func (*ComponentBehavior) CliRPC added in v0.1.56

func (c *ComponentBehavior) CliRPC(proc, method string, args ...any) async.Future

CliRPC 向当前实体 ID 对应的客户端单播地址发起 RPC。

func (*ComponentBehavior) ContinueOn added in v0.3.68

func (c *ComponentBehavior) ContinueOn(future async.Future, fun generic.FuncVar2[IRuntime, async.Result, any, async.Result], args ...any) async.Future

ContinueOn 在 future 完成后回到组件所属 Runtime 执行 fun。

func (*ComponentBehavior) ContinueOnVoid added in v0.3.68

func (c *ComponentBehavior) ContinueOnVoid(future async.Future, fun generic.ActionVar2[IRuntime, async.Result, any], args ...any) async.Future

ContinueOnVoid 在 future 完成后回到组件所属 Runtime 执行无业务返回值的 fun。

func (*ComponentBehavior) Every added in v0.3.68

func (c *ComponentBehavior) Every(dur time.Duration) async.Stream

Every 在组件生命周期内按 dur 周期产出当前时间。

func (*ComponentBehavior) FromChan added in v0.3.68

func (c *ComponentBehavior) FromChan(ch <-chan any) async.Stream

FromChan 将 ch 转换为绑定组件生命周期的 Stream。

func (*ComponentBehavior) GlobalBalanceOnewayRPC added in v0.2.38

func (c *ComponentBehavior) GlobalBalanceOnewayRPC(excludeSelf bool, comp, method string, args ...any) error

GlobalBalanceOnewayRPC 从承载当前实体的全部节点中随机选择一个发起单向 RPC;excludeSelf 为 true 时排除本节点。

func (*ComponentBehavior) GlobalBalanceRPC added in v0.1.56

func (c *ComponentBehavior) GlobalBalanceRPC(excludeSelf bool, comp, method string, args ...any) async.Future

GlobalBalanceRPC 从承载当前实体的全部节点中随机选择一个发起 RPC;excludeSelf 为 true 时排除本节点。

func (*ComponentBehavior) GlobalBroadcastOnewayRPC added in v0.2.38

func (c *ComponentBehavior) GlobalBroadcastOnewayRPC(excludeSelf bool, comp, method string, args ...any) error

GlobalBroadcastOnewayRPC 向所有服务中承载当前实体的节点广播单向 RPC;excludeSelf 为 true 时排除源节点。

func (*ComponentBehavior) L added in v0.3.68

func (c *ComponentBehavior) L() *zap.Logger

L 返回附带当前组件字段的结构化日志器。

func (*ComponentBehavior) OnewayRPC added in v0.2.38

func (c *ComponentBehavior) OnewayRPC(service, comp, method string, args ...any) error

OnewayRPC 向承载当前实体的首个指定服务节点发起单向 RPC。

func (*ComponentBehavior) Post added in v0.3.68

func (c *ComponentBehavior) Post(fun generic.ActionVar1[IRuntime, any], args ...any) error

Post 将 fun 投递到组件所属 Runtime,不创建 Future。 fun 执行前组件已经失活时会被忽略。

func (*ComponentBehavior) RPC added in v0.1.56

func (c *ComponentBehavior) RPC(service, comp, method string, args ...any) async.Future

RPC 向承载当前实体的首个指定服务节点发起 RPC。

func (*ComponentBehavior) Runtime added in v0.3.68

func (c *ComponentBehavior) Runtime() IRuntime

Runtime 返回组件所属的 framework 运行时。

func (*ComponentBehavior) S added in v0.3.68

S 返回附带当前组件字段的 SugaredLogger。

func (*ComponentBehavior) Service added in v0.3.68

func (c *ComponentBehavior) Service() IService

Service 返回承载组件所属运行时的服务。

func (*ComponentBehavior) Spawn added in v0.3.68

Spawn 在组件生命周期 Scope 中启动后台任务。 fun 不得直接并发访问 Runtime 局部状态。

func (*ComponentBehavior) SpawnVoid added in v0.3.68

func (c *ComponentBehavior) SpawnVoid(fun generic.ActionVar1[context.Context, any], args ...any) async.Future

SpawnVoid 在组件生命周期 Scope 中启动无业务返回值的后台任务。

func (*ComponentBehavior) Submit added in v0.3.68

Submit 将 fun 提交到组件所属 Runtime,并返回执行结果 Future。 执行时组件若已失活,Future 返回 ErrAsyncCallerNotAlive。

func (*ComponentBehavior) SubmitVoid added in v0.3.68

func (c *ComponentBehavior) SubmitVoid(fun generic.ActionVar1[IRuntime, any], args ...any) async.Future

SubmitVoid 将无业务返回值的 fun 提交到组件所属 Runtime。 执行时组件若已失活,Future 返回 ErrAsyncCallerNotAlive。

type EntityBehavior added in v0.1.76

type EntityBehavior struct {
	ec.EntityBehavior
	// contains filtered or unexported fields
}

EntityBehavior 扩展 core 实体行为,供自定义实体匿名嵌入。 日志器会按实体实例惰性创建,因此应在实体所属运行时 goroutine 中使用。

func (*EntityBehavior) After added in v0.3.68

func (e *EntityBehavior) After(dur time.Duration) async.Future

After 在实体生命周期内等待 dur 后以当前时间完成 Future。

func (*EntityBehavior) At added in v0.3.68

func (e *EntityBehavior) At(at time.Time) async.Future

At 在实体生命周期内等待到 at 后以当前时间完成 Future。

func (*EntityBehavior) BalanceOnewayRPC added in v0.2.38

func (e *EntityBehavior) BalanceOnewayRPC(service, comp, method string, args ...any) error

BalanceOnewayRPC 从承载当前实体且服务名匹配的节点中随机选择一个发起单向 RPC。

func (*EntityBehavior) BalanceRPC added in v0.1.76

func (e *EntityBehavior) BalanceRPC(service, comp, method string, args ...any) async.Future

BalanceRPC 从承载当前实体且服务名匹配的节点中随机选择一个发起 RPC。

func (*EntityBehavior) BroadcastOnewayRPC added in v0.2.38

func (e *EntityBehavior) BroadcastOnewayRPC(excludeSelf bool, service, comp, method string, args ...any) error

BroadcastOnewayRPC 向指定服务中承载当前实体的节点广播单向 RPC;excludeSelf 为 true 时排除源节点。

func (*EntityBehavior) CliOnewayRPC added in v0.2.38

func (e *EntityBehavior) CliOnewayRPC(proc, method string, args ...any) error

CliOnewayRPC 向当前实体 ID 对应的客户端单播地址发起单向 RPC。

func (*EntityBehavior) CliRPC added in v0.1.76

func (e *EntityBehavior) CliRPC(proc, method string, args ...any) async.Future

CliRPC 向当前实体 ID 对应的客户端单播地址发起 RPC。

func (*EntityBehavior) ContinueOn added in v0.3.68

func (e *EntityBehavior) ContinueOn(future async.Future, fun generic.FuncVar2[IRuntime, async.Result, any, async.Result], args ...any) async.Future

ContinueOn 在 future 完成后回到实体所属 Runtime 执行 fun。

func (*EntityBehavior) ContinueOnVoid added in v0.3.68

func (e *EntityBehavior) ContinueOnVoid(future async.Future, fun generic.ActionVar2[IRuntime, async.Result, any], args ...any) async.Future

ContinueOnVoid 在 future 完成后回到实体所属 Runtime 执行无业务返回值的 fun。

func (*EntityBehavior) Every added in v0.3.68

func (e *EntityBehavior) Every(dur time.Duration) async.Stream

Every 在实体生命周期内按 dur 周期产出当前时间。

func (*EntityBehavior) FromChan added in v0.3.68

func (e *EntityBehavior) FromChan(ch <-chan any) async.Stream

FromChan 将 ch 转换为绑定实体生命周期的 Stream。

func (*EntityBehavior) GlobalBalanceOnewayRPC added in v0.2.38

func (e *EntityBehavior) GlobalBalanceOnewayRPC(excludeSelf bool, comp, method string, args ...any) error

GlobalBalanceOnewayRPC 从承载当前实体的全部节点中随机选择一个发起单向 RPC;excludeSelf 为 true 时排除本节点。

func (*EntityBehavior) GlobalBalanceRPC added in v0.1.76

func (e *EntityBehavior) GlobalBalanceRPC(excludeSelf bool, comp, method string, args ...any) async.Future

GlobalBalanceRPC 从承载当前实体的全部节点中随机选择一个发起 RPC;excludeSelf 为 true 时排除本节点。

func (*EntityBehavior) GlobalBroadcastOnewayRPC added in v0.2.38

func (e *EntityBehavior) GlobalBroadcastOnewayRPC(excludeSelf bool, comp, method string, args ...any) error

GlobalBroadcastOnewayRPC 向所有服务中承载当前实体的节点广播单向 RPC;excludeSelf 为 true 时排除源节点。

func (*EntityBehavior) L added in v0.3.68

func (e *EntityBehavior) L() *zap.Logger

L 返回附带当前实体字段的结构化日志器。

func (*EntityBehavior) OnewayRPC added in v0.2.38

func (e *EntityBehavior) OnewayRPC(service, comp, method string, args ...any) error

OnewayRPC 向承载当前实体的首个指定服务节点发起单向 RPC。

func (*EntityBehavior) Post added in v0.3.68

func (e *EntityBehavior) Post(fun generic.ActionVar1[IRuntime, any], args ...any) error

Post 将 fun 投递到实体所属 Runtime,不创建 Future。 fun 执行前实体已经失活时会被忽略。

func (*EntityBehavior) RPC added in v0.1.76

func (e *EntityBehavior) RPC(service, comp, method string, args ...any) async.Future

RPC 向承载当前实体的首个指定服务节点发起 RPC。

func (*EntityBehavior) Runtime added in v0.3.68

func (e *EntityBehavior) Runtime() IRuntime

Runtime 返回实体所属的 framework 运行时。

func (*EntityBehavior) S added in v0.3.68

S 返回附带当前实体字段的 SugaredLogger。

func (*EntityBehavior) Service added in v0.3.68

func (e *EntityBehavior) Service() IService

Service 返回承载实体所属运行时的服务。

func (*EntityBehavior) Spawn added in v0.3.68

Spawn 在实体生命周期 Scope 中启动后台任务。 fun 不得直接并发访问 Runtime 局部状态。

func (*EntityBehavior) SpawnVoid added in v0.3.68

func (e *EntityBehavior) SpawnVoid(fun generic.ActionVar1[context.Context, any], args ...any) async.Future

SpawnVoid 在实体生命周期 Scope 中启动无业务返回值的后台任务。

func (*EntityBehavior) Submit added in v0.3.68

func (e *EntityBehavior) Submit(fun generic.FuncVar1[IRuntime, any, async.Result], args ...any) async.Future

Submit 将 fun 提交到实体所属 Runtime,并返回执行结果 Future。 执行时实体若已失活,Future 返回 ErrAsyncCallerNotAlive。

func (*EntityBehavior) SubmitVoid added in v0.3.68

func (e *EntityBehavior) SubmitVoid(fun generic.ActionVar1[IRuntime, any], args ...any) async.Future

SubmitVoid 将无业务返回值的 fun 提交到实体所属 Runtime。 执行时实体若已失活,Future 返回 ErrAsyncCallerNotAlive。

type EntityCreator added in v0.3.68

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

EntityCreator 保存一次实体构建所需的运行时目标、元数据与 core 实体选项。 构建器可按值复制,但不应由多个 goroutine 并发修改。

func BuildEntity added in v0.3.68

func BuildEntity(svcInst IService, prototype string) *EntityCreator

BuildEntity 创建绑定 svcInst 及 prototype 名称的实体构建器。

func (*EntityCreator) AssignMeta added in v0.3.68

func (c *EntityCreator) AssignMeta(m meta.Meta) *EntityCreator

AssignMeta 直接绑定实体元数据;m 不会在此时复制,nil 会替换为空 Meta。

func (*EntityCreator) MergeMeta added in v0.3.68

func (c *EntityCreator) MergeMeta(dict map[string]any) *EntityCreator

MergeMeta 合并实体元数据,同名键会被覆盖。

func (*EntityCreator) MergeMetaIfAbsent added in v0.3.68

func (c *EntityCreator) MergeMetaIfAbsent(dict map[string]any) *EntityCreator

MergeMetaIfAbsent 合并实体元数据,并保留已有的同名键。

func (*EntityCreator) New added in v0.3.68

func (c *EntityCreator) New() (ec.ConcurrentEntity, error)

New 构造实体并将其加入指定运行时。 未指定运行时时会创建自动运行的新运行时,并将实体设为其主实体。

func (*EntityCreator) NewAsync added in v0.3.68

func (c *EntityCreator) NewAsync() async.Future

NewAsync 构造实体并返回其加入运行时的 Future。 使用既有运行时时加入操作由该运行时调度;新建运行时时装配过程仍在调用方同步完成。

func (*EntityCreator) SetComponentAwakeOnFirstTouch added in v0.3.68

func (c *EntityCreator) SetComponentAwakeOnFirstTouch(b bool) *EntityCreator

SetComponentAwakeOnFirstTouch 设置是否在组件首次访问时检查并调用 Awake。

func (*EntityCreator) SetComponentUniqueID added in v0.3.68

func (c *EntityCreator) SetComponentUniqueID(b bool) *EntityCreator

SetComponentUniqueID 设置是否为组件分配唯一 ID。

func (*EntityCreator) SetInstance added in v0.3.68

func (c *EntityCreator) SetInstance(instance ec.Entity) *EntityCreator

SetInstance 设置自定义实体实例。

func (*EntityCreator) SetInstanceFace added in v0.3.68

func (c *EntityCreator) SetInstanceFace(face iface.Face[ec.Entity]) *EntityCreator

SetInstanceFace 设置实体实例面,用于提供自定义实体行为与反射信息。

func (*EntityCreator) SetMeta added in v0.3.68

func (c *EntityCreator) SetMeta(dict map[string]any) *EntityCreator

SetMeta 用 dict 替换实体元数据;dict 的内容会复制到新的 Meta 中。

func (*EntityCreator) SetPersistId added in v0.3.68

func (c *EntityCreator) SetPersistId(id uid.Id) *EntityCreator

SetPersistId 设置实体持久化 ID。

func (*EntityCreator) SetRuntime added in v0.3.68

func (c *EntityCreator) SetRuntime(rtInst IRuntime) *EntityCreator

SetRuntime 设置实体要加入的既有运行时。 rtInst 为 nil 时清除该设置;非 nil 运行时必须属于构建器绑定的服务。

func (*EntityCreator) SetRuntimeCreator added in v0.3.68

func (c *EntityCreator) SetRuntimeCreator(rtCreator *RuntimeCreator) *EntityCreator

SetRuntimeCreator 设置没有指定既有运行时时使用的运行时构建器。 nil 表示使用服务默认构建器;新实体会成为新运行时的主实体。

func (*EntityCreator) SetScope added in v0.3.68

func (c *EntityCreator) SetScope(scope ec.Scope) *EntityCreator

SetScope 设置实体的可访问作用域。

type EntityPTCreator added in v0.1.77

type EntityPTCreator = core.EntityPTCreator

EntityPTCreator 是 core 实体原型构建器的别名。

type IRuntime added in v0.3.24

type IRuntime interface {
	runtime.Context
	// DistEntityRegistry 返回分布式实体注册 add-in;未安装时会 panic。
	DistEntityRegistry() dent.IDistEntityRegistry
	// RPCStack 返回 RPC 调用栈 add-in;未安装时会 panic。
	RPCStack() rpcstack.IRPCStack
	// Service 返回承载当前运行时的服务实例。
	Service() IService
	// MainEntity 返回与运行时生命周期绑定的主实体;主实体停用后运行时会终止。
	MainEntity() ec.Entity
	// AutoInjection 报告实体或组件激活时是否自动注入组件依赖。
	AutoInjection() bool
	// BuildEntity 创建绑定当前运行时及 prototype 名称的 core 实体构建器。
	BuildEntity(prototype string) *core.EntityCreator
	// L 返回当前运行时的结构化日志器。
	L() *zap.Logger
	// S 返回当前运行时的 SugaredLogger。
	S() *zap.SugaredLogger
}

IRuntime 扩展 core runtime.Context,并聚合 framework 的运行时级 add-in 与构建入口。 除明确标注可并发的 API 外,应在所属运行时 goroutine 中访问运行时状态。

func GetRuntime added in v0.3.24

func GetRuntime(provider runtime.CurrentContextProvider) IRuntime

GetRuntime 返回 provider 所属的 framework 运行时实例。

type IRuntimeInstantiator added in v0.3.68

type IRuntimeInstantiator interface {
	Instantiate() IRuntime
}

IRuntimeInstantiator 为 RuntimeAssembler 提供自定义 IRuntime 实例。 每次构建运行时都会调用一次 Instantiate,且返回值必须是新的非 nil 实例。

type IService added in v0.3.24

type IService interface {
	service.Context
	// AppConf 返回合并后的应用配置。
	AppConf() *viper.Viper
	// ServiceConf 返回以服务名为键的配置子树;不存在时可能返回 nil。
	ServiceConf() *viper.Viper
	// Registry 返回服务发现 add-in;未安装时会 panic。
	Registry() discovery.IRegistry
	// Broker 返回消息代理 add-in;未安装时会 panic。
	Broker() broker.IBroker
	// DistSync 返回分布式同步 add-in;未安装时会 panic。
	DistSync() dsync.IDistSync
	// DistService 返回分布式服务 add-in;未安装时会 panic。
	DistService() dsvc.IDistService
	// DistEntityQuerier 返回分布式实体查询 add-in;未安装时会 panic。
	DistEntityQuerier() dent.IDistEntityQuerier
	// RPC 返回 RPC add-in;未安装时会 panic。
	RPC() rpc.IRPC
	// ReplicaNo 返回当前服务在本次应用启动中的副本序号,从 0 开始。
	ReplicaNo() int
	// Memory 返回服务私有的并发键值存储。
	Memory() *sync.Map
	// BuildRuntime 创建绑定当前服务的运行时构建器。
	BuildRuntime() *RuntimeCreator
	// BuildEntityPT 创建绑定当前服务及 prototype 名称的实体原型构建器。
	BuildEntityPT(prototype string) *EntityPTCreator
	// BuildEntity 创建绑定当前服务及 prototype 名称的实体构建器。
	BuildEntity(prototype string) *EntityCreator
	// L 返回当前服务的结构化日志器。
	L() *zap.Logger
	// S 返回当前服务的 SugaredLogger。
	S() *zap.SugaredLogger
}

IService 扩展 core service.Context,并聚合 framework 的服务级 add-in 与构建入口。 服务上下文可被多个 goroutine 访问;具体 add-in 的并发约束由各自接口说明。

func GetService added in v0.3.24

func GetService(provider runtime.ConcurrentContextProvider) IService

GetService 返回 provider 所属的 framework 服务实例。

type IServiceInstantiator added in v0.3.68

type IServiceInstantiator interface {
	Instantiate() IService
}

IServiceInstantiator 为 ServiceAssembler 提供自定义 IService 实例。 每个服务副本都会调用一次 Instantiate,且返回值必须是新的非 nil 实例。

type InstallRuntimeDistEntityRegistry added in v0.1.87

type InstallRuntimeDistEntityRegistry interface {
	InstallDistEntityRegistry(rt IRuntime)
}

InstallRuntimeDistEntityRegistry 为运行时提供自定义分布式实体注册 add-in 安装钩子。 仅当 Birth 阶段尚未安装同名 add-in 时调用;实现必须在返回前完成安装。

type InstallRuntimeLogger

type InstallRuntimeLogger interface {
	InstallLogger(rt IRuntime)
}

InstallRuntimeLogger 为运行时提供自定义日志 add-in 安装钩子。 仅当 Birth 阶段尚未安装同名 add-in 时调用;实现必须在返回前完成安装。

type InstallRuntimeRPCStack added in v0.1.69

type InstallRuntimeRPCStack interface {
	InstallRPCStack(rt IRuntime)
}

InstallRuntimeRPCStack 为运行时提供自定义 RPC 调用栈 add-in 安装钩子。 仅当 Birth 阶段尚未安装同名 add-in 时调用;实现必须在返回前完成安装。

type InstallServiceBroker

type InstallServiceBroker interface {
	InstallBroker(svc IService)
}

InstallServiceBroker 为服务提供自定义消息代理 add-in 安装钩子。 仅当 Birth 阶段尚未安装同名 add-in 时调用;实现必须在返回前完成安装。

type InstallServiceConfig

type InstallServiceConfig interface {
	InstallConfig(svc IService)
}

InstallServiceConfig 为服务提供自定义配置 add-in 安装钩子。 仅当 Birth 阶段尚未安装同名 add-in 时调用;实现必须在返回前完成安装。

type InstallServiceDistEntityQuerier

type InstallServiceDistEntityQuerier interface {
	InstallDistEntityQuerier(svc IService)
}

InstallServiceDistEntityQuerier 为服务提供自定义分布式实体查询 add-in 安装钩子。 仅当 Birth 阶段尚未安装同名 add-in 时调用;实现必须在返回前完成安装。

type InstallServiceDistService

type InstallServiceDistService interface {
	InstallDistService(svc IService)
}

InstallServiceDistService 为服务提供自定义分布式服务 add-in 安装钩子。 仅当 Birth 阶段尚未安装同名 add-in 时调用;实现必须在返回前完成安装。

type InstallServiceDistSync

type InstallServiceDistSync interface {
	InstallDistSync(svc IService)
}

InstallServiceDistSync 为服务提供自定义分布式同步 add-in 安装钩子。 仅当 Birth 阶段尚未安装同名 add-in 时调用;实现必须在返回前完成安装。

type InstallServiceLogger

type InstallServiceLogger interface {
	InstallLogger(svc IService)
}

InstallServiceLogger 为服务提供自定义日志 add-in 安装钩子。 仅当 Birth 阶段尚未安装同名 add-in 时调用;实现必须在返回前完成安装。

type InstallServiceRPC

type InstallServiceRPC interface {
	InstallRPC(svc IService)
}

InstallServiceRPC 为服务提供自定义 RPC add-in 安装钩子。 仅当 Birth 阶段尚未安装同名 add-in 时调用;实现必须在返回前完成安装。

type InstallServiceRegistry

type InstallServiceRegistry interface {
	InstallRegistry(svc IService)
}

InstallServiceRegistry 为服务提供自定义服务发现 add-in 安装钩子。 仅当 Birth 阶段尚未安装同名 add-in 时调用;实现必须在返回前完成安装。

type LifecycleRuntimeAddInActivated added in v0.2.85

type LifecycleRuntimeAddInActivated interface {
	OnAddInActivated(rt IRuntime, addIn extension.AddInStatus)
}

LifecycleRuntimeAddInActivated 在 add-in 完成 Init 并进入运行状态后接收回调。

type LifecycleRuntimeAddInActivating added in v0.2.85

type LifecycleRuntimeAddInActivating interface {
	OnAddInActivating(rt IRuntime, addIn extension.AddInStatus)
}

LifecycleRuntimeAddInActivating 在 add-in 调用 Init 前接收回调。 回调中卸载该 add-in 会中止激活流程。

type LifecycleRuntimeAddInActivationAborted added in v0.3.68

type LifecycleRuntimeAddInActivationAborted interface {
	OnAddInActivationAborted(rt IRuntime, addIn extension.AddInStatus)
}

LifecycleRuntimeAddInActivationAborted 在 add-in 激活流程被中止时接收回调。

type LifecycleRuntimeAddInDeactivated added in v0.2.85

type LifecycleRuntimeAddInDeactivated interface {
	OnAddInDeactivated(rt IRuntime, addIn extension.AddInStatus)
}

LifecycleRuntimeAddInDeactivated 在 add-in 完成 Shut 后接收回调。

type LifecycleRuntimeAddInDeactivating added in v0.2.85

type LifecycleRuntimeAddInDeactivating interface {
	OnAddInDeactivating(rt IRuntime, addIn extension.AddInStatus)
}

LifecycleRuntimeAddInDeactivating 在 add-in 调用 Shut 前接收回调。

type LifecycleRuntimeBirth

type LifecycleRuntimeBirth interface {
	OnBirth(rt IRuntime)
}

LifecycleRuntimeBirth 在运行时上下文创建后、framework add-in 装配前接收回调。

type LifecycleRuntimeBuilt added in v0.1.45

type LifecycleRuntimeBuilt interface {
	OnBuilt(rt IRuntime)
}

LifecycleRuntimeBuilt 在运行时完成 framework add-in 装配后接收回调。 此时运行时尚未进入 Starting,仍可补充初始状态。

type LifecycleRuntimeEntityActivated added in v0.3.68

type LifecycleRuntimeEntityActivated interface {
	OnEntityActivated(rt IRuntime, entity ec.Entity)
}

LifecycleRuntimeEntityActivated 在实体及其初始组件激活完成后接收回调。

type LifecycleRuntimeEntityActivating added in v0.3.68

type LifecycleRuntimeEntityActivating interface {
	OnEntityActivating(rt IRuntime, entity ec.Entity)
}

LifecycleRuntimeEntityActivating 在实体开始激活时接收回调。

type LifecycleRuntimeEntityActivationAborted added in v0.3.68

type LifecycleRuntimeEntityActivationAborted interface {
	OnEntityActivationAborted(rt IRuntime, entity ec.Entity)
}

LifecycleRuntimeEntityActivationAborted 在实体激活流程被中止时接收回调。

type LifecycleRuntimeEntityComponentDeactivated added in v0.3.68

type LifecycleRuntimeEntityComponentDeactivated interface {
	OnEntityComponentDeactivated(rt IRuntime, entity ec.Entity, component ec.Component)
}

LifecycleRuntimeEntityComponentDeactivated 在组件停用完成、即将从实体删除时接收回调。

type LifecycleRuntimeEntityComponentDeactivating added in v0.3.68

type LifecycleRuntimeEntityComponentDeactivating interface {
	OnEntityComponentDeactivating(rt IRuntime, entity ec.Entity, component ec.Component)
}

LifecycleRuntimeEntityComponentDeactivating 在即将删除的组件开始停用时接收回调。

type LifecycleRuntimeEntityComponentDeactivationAborted added in v0.3.68

type LifecycleRuntimeEntityComponentDeactivationAborted interface {
	OnEntityComponentDeactivationAborted(rt IRuntime, entity ec.Entity, component ec.Component)
}

LifecycleRuntimeEntityComponentDeactivationAborted 在组件停用回调流程被中止时接收回调。 该事件不会取消组件删除。

type LifecycleRuntimeEntityComponentsActivated added in v0.3.68

type LifecycleRuntimeEntityComponentsActivated interface {
	OnEntityComponentsActivated(rt IRuntime, entity ec.Entity, components []ec.Component)
}

LifecycleRuntimeEntityComponentsActivated 在一批新增组件激活完成后接收回调。

type LifecycleRuntimeEntityComponentsActivating added in v0.3.68

type LifecycleRuntimeEntityComponentsActivating interface {
	OnEntityComponentsActivating(rt IRuntime, entity ec.Entity, components []ec.Component)
}

LifecycleRuntimeEntityComponentsActivating 在一批新增组件开始激活时接收回调。

type LifecycleRuntimeEntityComponentsActivationAborted added in v0.3.68

type LifecycleRuntimeEntityComponentsActivationAborted interface {
	OnEntityComponentsActivationAborted(rt IRuntime, entity ec.Entity, components []ec.Component)
}

LifecycleRuntimeEntityComponentsActivationAborted 在新增组件的激活流程被中止时接收回调。

type LifecycleRuntimeEntityDeactivated added in v0.3.68

type LifecycleRuntimeEntityDeactivated interface {
	OnEntityDeactivated(rt IRuntime, entity ec.Entity)
}

LifecycleRuntimeEntityDeactivated 在实体停用完成时接收回调。

type LifecycleRuntimeEntityDeactivating added in v0.3.68

type LifecycleRuntimeEntityDeactivating interface {
	OnEntityDeactivating(rt IRuntime, entity ec.Entity)
}

LifecycleRuntimeEntityDeactivating 在实体开始停用时接收回调。

type LifecycleRuntimeFrameLoopBegin

type LifecycleRuntimeFrameLoopBegin interface {
	OnFrameLoopBegin(rt IRuntime)
}

LifecycleRuntimeFrameLoopBegin 在一次完整帧循环开始时接收回调。

type LifecycleRuntimeFrameLoopEnd

type LifecycleRuntimeFrameLoopEnd interface {
	OnFrameLoopEnd(rt IRuntime)
}

LifecycleRuntimeFrameLoopEnd 在一次完整帧循环结束时接收回调。

type LifecycleRuntimeFrameUpdateBegin

type LifecycleRuntimeFrameUpdateBegin interface {
	OnFrameUpdateBegin(rt IRuntime)
}

LifecycleRuntimeFrameUpdateBegin 在一次帧更新开始时接收回调。

type LifecycleRuntimeFrameUpdateEnd

type LifecycleRuntimeFrameUpdateEnd interface {
	OnFrameUpdateEnd(rt IRuntime)
}

LifecycleRuntimeFrameUpdateEnd 在一次帧更新结束时接收回调。

type LifecycleRuntimeRunCallBegin

type LifecycleRuntimeRunCallBegin interface {
	OnRunCallBegin(rt IRuntime)
}

LifecycleRuntimeRunCallBegin 在运行时开始执行一个普通异步调用任务时接收回调。

type LifecycleRuntimeRunCallEnd

type LifecycleRuntimeRunCallEnd interface {
	OnRunCallEnd(rt IRuntime)
}

LifecycleRuntimeRunCallEnd 在运行时执行完一个普通异步调用任务时接收回调。

type LifecycleRuntimeRunGCBegin

type LifecycleRuntimeRunGCBegin interface {
	OnRunGCBegin(rt IRuntime)
}

LifecycleRuntimeRunGCBegin 在运行时开始执行一次 GC 时接收回调。

type LifecycleRuntimeRunGCEnd

type LifecycleRuntimeRunGCEnd interface {
	OnRunGCEnd(rt IRuntime)
}

LifecycleRuntimeRunGCEnd 在运行时执行完一次 GC 时接收回调。

type LifecycleRuntimeStarted

type LifecycleRuntimeStarted interface {
	OnStarted(rt IRuntime)
}

LifecycleRuntimeStarted 在运行时工作循环及实体事件监听就绪后接收回调。

type LifecycleRuntimeStarting

type LifecycleRuntimeStarting interface {
	OnStarting(rt IRuntime)
}

LifecycleRuntimeStarting 在运行时工作循环启动时接收回调。 预装 add-in 已在回调前激活。

type LifecycleRuntimeTerminated

type LifecycleRuntimeTerminated interface {
	OnTerminated(rt IRuntime)
}

LifecycleRuntimeTerminated 在运行时等待组清空且 add-in 停用后接收回调。

type LifecycleRuntimeTerminating

type LifecycleRuntimeTerminating interface {
	OnTerminating(rt IRuntime)
}

LifecycleRuntimeTerminating 在运行时开始停止、等待子任务退出前接收回调。

type LifecycleServiceBirth

type LifecycleServiceBirth interface {
	OnBirth(svc IService)
}

LifecycleServiceBirth 在服务上下文及基础配置创建后、framework add-in 装配前接收回调。

type LifecycleServiceBuilt added in v0.1.45

type LifecycleServiceBuilt interface {
	OnBuilt(svc IService)
}

LifecycleServiceBuilt 在 framework add-in 装配完成后接收回调。 这是服务进入 Starting 并冻结 add-in 管理器前补充服务 add-in 的最后阶段。

type LifecycleServiceComponentPTDeclared added in v0.3.68

type LifecycleServiceComponentPTDeclared interface {
	OnComponentPTDeclared(svc IService, componentPT ec.ComponentPT)
}

LifecycleServiceComponentPTDeclared 在服务组件库声明组件原型后接收回调。

type LifecycleServiceEntityDeregistered added in v0.3.68

type LifecycleServiceEntityDeregistered interface {
	OnEntityDeregistered(svc IService, entity ec.ConcurrentEntity)
}

LifecycleServiceEntityDeregistered 在全局实体从服务实体库注销后接收回调。

type LifecycleServiceEntityPTDeclared added in v0.2.85

type LifecycleServiceEntityPTDeclared interface {
	OnEntityPTDeclared(svc IService, entityPT ec.EntityPT)
}

LifecycleServiceEntityPTDeclared 在服务实体库声明实体原型后接收回调。

type LifecycleServiceEntityRegistered added in v0.3.68

type LifecycleServiceEntityRegistered interface {
	OnEntityRegistered(svc IService, entity ec.ConcurrentEntity)
}

LifecycleServiceEntityRegistered 在全局实体注册到服务实体库后接收回调。

type LifecycleServiceHeartbeat added in v0.3.68

type LifecycleServiceHeartbeat interface {
	OnHeartbeat(svc IService)
}

LifecycleServiceHeartbeat 在服务运行期间接收每秒一次的心跳回调。

type LifecycleServiceStarted

type LifecycleServiceStarted interface {
	OnStarted(svc IService)
}

LifecycleServiceStarted 在服务完成启动并加入分布式网络后接收回调。

type LifecycleServiceStarting

type LifecycleServiceStarting interface {
	OnStarting(svc IService)
}

LifecycleServiceStarting 在服务开始运行时接收回调。 服务 add-in 已在回调前冻结并激活,之后不能再安装或卸载。

type LifecycleServiceTerminated

type LifecycleServiceTerminated interface {
	OnTerminated(svc IService)
}

LifecycleServiceTerminated 在服务等待组清空且 add-in 停用后接收回调。

type LifecycleServiceTerminating

type LifecycleServiceTerminating interface {
	OnTerminating(svc IService)
}

LifecycleServiceTerminating 在服务开始停止、等待子任务退出前接收回调。

type RuntimeAssembler added in v0.3.68

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

RuntimeAssembler 将 IRuntime 实例接入 framework 的 add-in、生命周期及实体事件。 自定义运行时装配类型通常匿名嵌入它并实现所需的生命周期或安装钩子接口。

type RuntimeBehavior

type RuntimeBehavior struct {
	runtime.ContextBehavior
	// contains filtered or unexported fields
}

RuntimeBehavior 提供 IRuntime 的默认实现,供自定义运行时匿名嵌入。

func (*RuntimeBehavior) AutoInjection added in v0.3.68

func (rt *RuntimeBehavior) AutoInjection() bool

AutoInjection 报告实体或组件激活时是否自动注入组件依赖。

func (*RuntimeBehavior) BuildEntity added in v0.3.53

func (rt *RuntimeBehavior) BuildEntity(prototype string) *core.EntityCreator

BuildEntity 创建绑定当前运行时及 prototype 名称的 core 实体构建器。

func (*RuntimeBehavior) DistEntityRegistry added in v0.3.68

func (rt *RuntimeBehavior) DistEntityRegistry() dent.IDistEntityRegistry

DistEntityRegistry 返回分布式实体注册 add-in;未安装时会 panic。

func (*RuntimeBehavior) L added in v0.3.68

func (rt *RuntimeBehavior) L() *zap.Logger

L 返回当前运行时的结构化日志器。

func (*RuntimeBehavior) MainEntity added in v0.3.68

func (rt *RuntimeBehavior) MainEntity() ec.Entity

MainEntity 返回与运行时生命周期绑定的主实体;主实体停用后运行时会终止。

func (*RuntimeBehavior) RPCStack added in v0.3.68

func (rt *RuntimeBehavior) RPCStack() rpcstack.IRPCStack

RPCStack 返回 RPC 调用栈 add-in;未安装时会 panic。

func (*RuntimeBehavior) S added in v0.3.68

S 返回当前运行时的 SugaredLogger。

func (*RuntimeBehavior) Service added in v0.3.68

func (rt *RuntimeBehavior) Service() IService

Service 返回承载当前运行时的服务实例。

type RuntimeCreator

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

RuntimeCreator 保存一次运行时构建所需的装配器与选项。 构建器可按值复制,但不应由多个 goroutine 并发修改。

func BuildRuntime added in v0.3.12

func BuildRuntime(svcInst IService) *RuntimeCreator

BuildRuntime 创建绑定 svcInst 的运行时构建器,并继承服务的 panic 处理配置。

func (*RuntimeCreator) New added in v0.3.12

func (c *RuntimeCreator) New() (IRuntime, error)

New 装配并自动启动运行时。 返回时运行时 goroutine 可能尚未完成 Starting;装配主实体失败时返回错误。

func (*RuntimeCreator) SetAssembler added in v0.3.68

func (c *RuntimeCreator) SetAssembler(assembler any) *RuntimeCreator

SetAssembler 设置运行时装配器。 assembler 可以是自定义装配器,也可以是实现 IRuntime 的实例或 reflect.Type; 后两者会被转换为按需创建实例的默认装配器。

func (*RuntimeCreator) SetAutoInjection added in v0.3.24

func (c *RuntimeCreator) SetAutoInjection(b bool) *RuntimeCreator

SetAutoInjection 设置实体或组件激活时是否自动注入组件依赖。

func (*RuntimeCreator) SetContinueOnActivatingEntityPanic added in v0.3.68

func (c *RuntimeCreator) SetContinueOnActivatingEntityPanic(b bool) *RuntimeCreator

SetContinueOnActivatingEntityPanic 设置实体激活发生 panic 后是否继续运行。 设置为 false 时,激活失败的实体会被移除。

func (*RuntimeCreator) SetEnableFrame added in v0.3.68

func (c *RuntimeCreator) SetEnableFrame(b bool) *RuntimeCreator

SetEnableFrame 设置是否启用实时帧循环。

func (*RuntimeCreator) SetFPS added in v0.3.12

func (c *RuntimeCreator) SetFPS(fps float64) *RuntimeCreator

SetFPS 设置启用帧循环时的目标帧率。

func (*RuntimeCreator) SetMainEntity added in v0.3.68

func (c *RuntimeCreator) SetMainEntity(entity ec.Entity) *RuntimeCreator

SetMainEntity 设置主实体;主实体停用后运行时会自动终止。

func (*RuntimeCreator) SetName added in v0.3.12

func (c *RuntimeCreator) SetName(name string) *RuntimeCreator

SetName 设置运行时名称。

func (*RuntimeCreator) SetPanicHandling added in v0.3.12

func (c *RuntimeCreator) SetPanicHandling(autoRecover bool, reportError chan error) *RuntimeCreator

SetPanicHandling 设置运行时是否自动恢复 panic 以及错误报告通道。 autoRecover 为 true 时,恢复出的错误会尝试写入 reportError。

func (*RuntimeCreator) SetPersistId added in v0.3.12

func (c *RuntimeCreator) SetPersistId(id uid.Id) *RuntimeCreator

SetPersistId 设置运行时持久化 ID。

type ServiceAssembler added in v0.3.68

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

ServiceAssembler 将 IService 实例接入应用配置、默认 add-in 及生命周期事件。 自定义服务装配类型通常匿名嵌入它并实现所需的生命周期或安装钩子接口。

type ServiceBehavior

type ServiceBehavior struct {
	service.ContextBehavior
	// contains filtered or unexported fields
}

ServiceBehavior 提供 IService 的默认实现,供自定义服务匿名嵌入。

func (*ServiceBehavior) AppConf added in v0.3.68

func (svc *ServiceBehavior) AppConf() *viper.Viper

AppConf 返回合并后的应用配置。 服务启动前直接读取装配配置,启动后通过 conf add-in 读取。

func (*ServiceBehavior) Broker added in v0.3.68

func (svc *ServiceBehavior) Broker() broker.IBroker

Broker 返回消息代理 add-in;未安装时会 panic。

func (*ServiceBehavior) BuildEntity added in v0.3.68

func (svc *ServiceBehavior) BuildEntity(prototype string) *EntityCreator

BuildEntity 创建绑定当前服务及 prototype 名称的实体构建器。

func (*ServiceBehavior) BuildEntityPT added in v0.3.53

func (svc *ServiceBehavior) BuildEntityPT(prototype string) *EntityPTCreator

BuildEntityPT 创建绑定当前服务及 prototype 名称的实体原型构建器。

func (*ServiceBehavior) BuildRuntime added in v0.3.53

func (svc *ServiceBehavior) BuildRuntime() *RuntimeCreator

BuildRuntime 创建绑定当前服务的运行时构建器。

func (*ServiceBehavior) DistEntityQuerier added in v0.3.68

func (svc *ServiceBehavior) DistEntityQuerier() dent.IDistEntityQuerier

DistEntityQuerier 返回分布式实体查询 add-in;未安装时会 panic。

func (*ServiceBehavior) DistService added in v0.3.68

func (svc *ServiceBehavior) DistService() dsvc.IDistService

DistService 返回分布式服务 add-in;未安装时会 panic。

func (*ServiceBehavior) DistSync added in v0.3.68

func (svc *ServiceBehavior) DistSync() dsync.IDistSync

DistSync 返回分布式同步 add-in;未安装时会 panic。

func (*ServiceBehavior) L added in v0.3.68

func (svc *ServiceBehavior) L() *zap.Logger

L 返回当前服务的结构化日志器。

func (*ServiceBehavior) Memory added in v0.3.68

func (svc *ServiceBehavior) Memory() *sync.Map

Memory 返回服务私有的并发键值存储。

func (*ServiceBehavior) RPC added in v0.3.68

func (svc *ServiceBehavior) RPC() rpc.IRPC

RPC 返回 RPC add-in;未安装时会 panic。

func (*ServiceBehavior) Registry added in v0.3.68

func (svc *ServiceBehavior) Registry() discovery.IRegistry

Registry 返回服务发现 add-in;未安装时会 panic。

func (*ServiceBehavior) ReplicaNo added in v0.3.68

func (svc *ServiceBehavior) ReplicaNo() int

ReplicaNo 返回当前服务在本次应用启动中的副本序号,从 0 开始。

func (*ServiceBehavior) S added in v0.3.68

func (svc *ServiceBehavior) S() *zap.SugaredLogger

S 返回当前服务的 SugaredLogger。

func (*ServiceBehavior) ServiceConf added in v0.3.68

func (svc *ServiceBehavior) ServiceConf() *viper.Viper

ServiceConf 返回以当前服务名为键的配置子树;不存在时可能返回 nil。

Directories

Path Synopsis
Package addins 在单一导入路径下重新导出框架内置 add-in 的描述符和 选项辅助入口。
Package addins 在单一导入路径下重新导出框架内置 add-in 的描述符和 选项辅助入口。
broker
Package broker 定义框架服务使用的发布订阅 broker 抽象。
Package broker 定义框架服务使用的发布订阅 broker 抽象。
broker/broker_nats
Package broker_nats 提供基于 NATS 的 broker add-in 实现。
Package broker_nats 提供基于 NATS 的 broker add-in 实现。
conf
Package conf 提供基于 Viper 的服务配置 add-in。
Package conf 提供基于 Viper 的服务配置 add-in。
db
Package db 为服务代码提供跨数据库的辅助能力。
Package db 为服务代码提供跨数据库的辅助能力。
db/dsn
Package dsn 定义数据库 add-in 共享的带标签连接描述和后端类型常量。
Package dsn 定义数据库 add-in 共享的带标签连接描述和后端类型常量。
db/mongodb
Package mongodb 提供服务侧的 MongoDB 客户端 add-in。
Package mongodb 提供服务侧的 MongoDB 客户端 add-in。
db/redisdb
Package redisdb 提供服务侧的 Redis 客户端 add-in。
Package redisdb 提供服务侧的 Redis 客户端 add-in。
db/sqldb
Package sqldb 提供基于 GORM 的 SQL 数据库 add-in。
Package sqldb 提供基于 GORM 的 SQL 数据库 add-in。
dent
Package dent 提供分布式实体查询与注册 add-in。
Package dent 提供分布式实体查询与注册 add-in。
discovery
Package discovery 定义分布式服务使用的服务发现抽象。
Package discovery 定义分布式服务使用的服务发现抽象。
discovery/discovery_etcd
Package discovery_etcd 提供基于 ETCD 的 discovery registry add-in 实现。
Package discovery_etcd 提供基于 ETCD 的 discovery registry add-in 实现。
dsvc
Package dsvc 提供分布式服务寻址和调用支撑能力。
Package dsvc 提供分布式服务寻址和调用支撑能力。
dsync
Package dsync 定义分布式同步能力的抽象层,供不同锁实现复用。
Package dsync 定义分布式同步能力的抽象层,供不同锁实现复用。
dsync/dsync_etcd
Package dsync_etcd 提供基于 ETCD 的 dsync add-in 实现。
Package dsync_etcd 提供基于 ETCD 的 dsync add-in 实现。
dsync/dsync_redis
Package dsync_redis 提供基于 Redis 的 dsync add-in 实现。
Package dsync_redis 提供基于 Redis 的 dsync add-in 实现。
gate
Package gate 提供构建在 GTP 传输栈之上的网关 add-in。
Package gate 提供构建在 GTP 传输栈之上的网关 add-in。
gate/cli
Package cli 提供面向 gate 服务端的客户端传输层。
Package cli 提供面向 gate 服务端的客户端传输层。
log
Package log 提供共享的基于 Zap 的日志 add-in。
Package log 提供共享的基于 Zap 的日志 add-in。
router
Package router 在 gate session 之上提供会话路由、实体映射和组播辅助。
Package router 在 gate session 之上提供会话路由、实体映射和组播辅助。
rpc
Package rpc 提供服务侧 RPC add-in,以及配套的代理与结果辅助能力。
Package rpc 提供服务侧 RPC add-in,以及配套的代理与结果辅助能力。
rpc/callpath
Package callpath 负责 RPC 目标路径的编码与解码。
Package callpath 负责 RPC 目标路径的编码与解码。
rpc/rpcli
Package rpcli 提供构建在 gate/cli 和 GAP 消息之上的客户端 RPC 辅助能力。
Package rpcli 提供构建在 gate/cli 和 GAP 消息之上的客户端 RPC 辅助能力。
rpc/rpcpcsr
Package rpcpcsr 提供 rpc add-in 使用的内置 RPC 处理器和投递器约定。
Package rpcpcsr 提供 rpc add-in 使用的内置 RPC 处理器和投递器约定。
rpcstack
Package rpcstack 提供 runtime 作用域的 RPC 调用链上下文。
Package rpcstack 提供 runtime 作用域的 RPC 调用链上下文。
net
Package net 汇总框架中的网络通信相关能力。
Package net 汇总框架中的网络通信相关能力。
gap
Package gap 定义 Golaxy 应用层协议(Golaxy Application Protocol)。
Package gap 定义 Golaxy 应用层协议(Golaxy Application Protocol)。
gap/codec
Package codec 提供 GAP 消息包的编解码能力。
Package codec 提供 GAP 消息包的编解码能力。
gap/variant
Package variant 提供 GAP 消息和 RPC 负载使用的动态值模型。
Package variant 提供 GAP 消息和 RPC 负载使用的动态值模型。
gtp
Package gtp 定义 Golaxy 传输协议(Golaxy Transfer Protocol)。
Package gtp 定义 Golaxy 传输协议(Golaxy Transfer Protocol)。
gtp/codec
Package codec 提供 GTP 消息包的编解码能力。
Package codec 提供 GTP 消息包的编解码能力。
gtp/method
Package method 提供 GTP 使用的密码学与压缩基础能力。
Package method 提供 GTP 使用的密码学与压缩基础能力。
gtp/sign command
Command sign 用于生成 GTP 签名和验签使用的 RSA 密钥文件。
Command sign 用于生成 GTP 签名和验签使用的 RSA 密钥文件。
gtp/transport
Package transport 提供 GTP 的连接层运行时能力。
Package transport 提供 GTP 的连接层运行时能力。
netpath
Package netpath 提供逻辑网络路径的基础处理函数。
Package netpath 提供逻辑网络路径的基础处理函数。
Package utils 汇总框架中的通用基础工具。
Package utils 汇总框架中的通用基础工具。
binaryutil
Package binaryutil 提供二进制读写和字节缓冲辅助工具。
Package binaryutil 提供二进制读写和字节缓冲辅助工具。
concurrent
Package concurrent 提供轻量级并发控制辅助组件。
Package concurrent 提供轻量级并发控制辅助组件。

Jump to

Keyboard shortcuts

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