Skip to content

Module API Reference

Алексей . edited this page Apr 12, 2026 · 5 revisions

Module API Reference

SFModuleAttribute

Source

[SFModule("id", "DisplayName",
    Category = "General",           // Grouping label
    Description = "",               // Shown in /sfs info
    DefaultEnabled = true,          // Auto-start when container runs
    ExecutionModel = ModuleExecutionModel.MainThread,
    RestartPolicy = ModuleRestartPolicy.Manual,
    Order = 0)]                     // Lower = starts first
Property Type Default Description
Id string required Unique identifier, used in /sfs commands
DisplayName string required Shown in dashboard UI
Category string "General" Grouping label
Description string "" Detailed description
DefaultEnabled bool true Start automatically on container run
ExecutionModel ModuleExecutionModel MainThread Thread model
RestartPolicy ModuleRestartPolicy Manual Auto-restart behavior
Order int 0 Sort order (ascending)

SFModuleBase

Source

Protected Properties

Property Type Description
Context ModuleContext Runtime context with telemetry and services
Log ILogger Module-scoped logger (Microsoft.Extensions.Logging)

Abstract Methods

Method Description
Task ExecuteAsync(CancellationToken) Main module logic. Runs until token is cancelled or an exception is thrown.

Virtual Lifecycle Hooks

Method When Called
Task OnStartingAsync() Before ExecuteAsync
Task OnCompletedAsync() After ExecuteAsync returns normally
Task OnFaultedAsync(Exception) After ExecuteAsync throws (before rethrowing)
Task OnStoppingAsync() Always, during teardown (in finally)
Task OnStoppedAsync() Always, after OnStoppingAsync (in finally)
ILogger CreateLogger(ModuleContext) Override to provide custom logger (Serilog, NLog, etc.)

ModuleContext

Source

Properties

Property Type Description
Descriptor ModuleDescriptor Immutable module metadata
CancellationToken CancellationToken Signals module shutdown

Telemetry Methods

Method Signature Description
Heartbeat void Heartbeat(string? activity = null) Record heartbeat, update last activity
ReportActivity void ReportActivity(string activity) Record activity without heartbeat
SetStatusText void SetStatusText(string? value) Set status shown in dashboard
IncrementCounter void IncrementCounter(string name, long delta = 1) Increment named counter
SetDetail void SetDetail(string key, string? value) Set/remove key-value detail
TrackLoop ModuleLoopScope TrackLoop(string? activity = null) Start loop timing scope
GetSnapshot ModuleRuntimeSnapshot GetSnapshot() Get full telemetry snapshot

Resource Management

Method Signature Description
RegisterDisposable IDisposable RegisterDisposable(IDisposable) Auto-dispose on module stop
RegisterChatCommand IDisposable RegisterChatCommand(string cmd, Action<string?> cb) Register chat command with telemetry

Threading

Method Signature Description
SwitchToMainThreadAsync Task SwitchToMainThreadAsync() Switch continuation to main thread
RunBackground Task RunBackground(Func<Task> work) Run async work on thread pool

ModuleLoopScope

Source

readonly struct implementing IDisposable. Records loop iteration duration on Dispose().

// Use as a using BLOCK (not declaration) with yield outside:
using (ModuleLoopScope _ = Context.TrackLoop("activity"))
{
    // measured work
}

await Task.Yield();  // outside scope

Tracks:

  • Iteration count
  • Average/max loop duration (milliseconds)
  • Duty cycle - ratio of sync work to iteration period

ModuleDescriptor

Source

Immutable record created from [SFModule] attribute via ModuleDescriptor.FromType(typeof(T)).

Property Type
Id string
DisplayName string
Category string
Description string
DefaultEnabled bool
ExecutionModel ModuleExecutionModel
RestartPolicy ModuleRestartPolicy
Order int
ModuleType Type

ModuleRuntimeSnapshot

Source

Sealed record with 25 fields capturing the full module state at a point in time.

Field Type Description
Descriptor ModuleDescriptor Module metadata
State ModuleLifecycleState Current state
LastStopReason ModuleStopReason Why module last stopped
AutoStartEnabled bool Auto-start flag
CreatedAt DateTimeOffset? First creation time
StartedAt DateTimeOffset? Last start time
StoppedAt DateTimeOffset? Last stop time
LastHeartbeatAt DateTimeOffset? Last heartbeat
LastActivityAt DateTimeOffset? Last activity
LastActivity string? Last activity description
StatusText string? Custom status text
StartThreadId int? Thread where module started
LastThreadId int? Last observed thread
StartCount long Total starts
RestartCount long Total restarts
FaultCount long Total faults
LoopCount long Total loop iterations
AverageLoopMilliseconds double Avg loop duration
MaxLoopMilliseconds double Max loop duration
EstimatedLoadPercent double Duty cycle 0-100%
LastMemoryBytes long Process memory (polled every 2s)
LastExceptionType string? Last exception type name
LastExceptionMessage string? Last exception message
Counters IReadOnlyDictionary<string, long> Custom counters
Details IReadOnlyDictionary<string, string> Custom details
OwnedDisposableCount int Registered disposables
Uptime TimeSpan? Computed from start/stop times

Enums

ModuleExecutionModel

MainThread | BackgroundWorker | Hybrid

ModuleRestartPolicy

Manual | OnFault

ModuleLifecycleState

Created | Starting | Running | Stopping | Stopped | Faulted

ModuleStopReason

None | Completed | UserRequested | RestartRequested | ContainerShutdown | Faulted

Clone this wiki locally