{"modulePath":"github.com/cloudapp3/vmflow","version":"v0.4.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package engine\n\n## Constants\n\n```go\nconst (\n\t// DefaultUDPGlobalMaxSessions caps the total number of active UDP sessions\n\t// across all rules owned by one Manager. A zero ManagerOptions value uses\n\t// this limit rather than disabling the guard.\n\tDefaultUDPGlobalMaxSessions = 256\n\n\t// MaxUDPGlobalMaxSessions bounds configuration mistakes. A generic UDP\n\t// proxy consumes a socket and receive loop per active client address, so a\n\t// larger value is not a practical safe default for this implementation.\n\tMaxUDPGlobalMaxSessions = 4_096\n)\n```\n\n```go\nconst DefaultTCPIdleTimeout = 5 * time.Minute\n```\nDefaultTCPIdleTimeout bounds how long a TCP forwarding connection may stay idle (no data in either direction) before being reaped. It keeps Stop/reload from hanging on stuck or silent clients and caps per-connection resource hold time. Overridable per rule via idle\\_timeout (seconds); 0 means use this default.\n\n```go\nconst (\n\t// DefaultUDPRuleMaxSessions is the per-rule fallback when max_conn is zero.\n\t// Each UDP session owns a socket and receive goroutine, so zero cannot mean\n\t// unbounded without exposing the process to trivial resource exhaustion.\n\tDefaultUDPRuleMaxSessions = DefaultUDPGlobalMaxSessions\n)\n```\n\n## Variables\n\n```go\nvar (\n\tErrTrafficQuotaExceeded = errors.New(\"traffic quota exceeded\")\n\tErrQuotaStatePersist    = errors.New(\"persist traffic quota state\")\n)\n```\n\n## Functions\n\n```go\nfunc ParseSourceIPPrefix(value string) (netip.Prefix, error)\n```\nParseSourceIPPrefix parses one literal source IP or CIDR. Literal addresses are represented as /32 or /128 prefixes, and IPv4-mapped IPv6 values are normalized to IPv4 so socket-family representation cannot bypass a policy.\n\n## Types\n\n```go\ntype ApplyAction string\n```\n\n```go\nconst (\n\tApplyActionStarted   ApplyAction = \"started\"\n\tApplyActionRestarted ApplyAction = \"restarted\"\n\tApplyActionStopped   ApplyAction = \"stopped\"\n\tApplyActionRemoved   ApplyAction = \"removed\"\n\tApplyActionUnchanged ApplyAction = \"unchanged\"\n\tApplyActionFailed    ApplyAction = \"failed\"\n)\n```\n\n```go\ntype ApplyFailure struct {\n\tRuleID   string `json:\"rule_id,omitempty\"`\n\tRevision int64  `json:\"revision,omitempty\"`\n\tError    string `json:\"error\"`\n}\n```\nApplyFailure identifies the operation that prevented a transactional snapshot from being committed. Validation failures are also listed in Apply.Items; this field points at the first failure that stopped the batch.\n\n```go\ntype ApplyItemResult struct {\n\tRuleID   string      `json:\"rule_id\"`\n\tRevision int64       `json:\"revision,omitempty\"`\n\tAction   ApplyAction `json:\"action\"`\n\tStatus   string      `json:\"status\"`\n\tError    string      `json:\"error,omitempty\"`\n}\n```\n\n```go\ntype ApplyResult struct {\n\tAppliedRules int               `json:\"applied_rules\"`\n\tStoppedRules int               `json:\"stopped_rules\"`\n\tFailedRules  int               `json:\"failed_rules\"`\n\tTotalRules   int               `json:\"total_rules\"`\n\tItems        []ApplyItemResult `json:\"items\"`\n}\n```\n\n```go\ntype ApplySnapshotOptions struct {\n\tReplaceAll bool `json:\"replace_all\"`\n}\n```\n\n```go\ntype BandwidthLimit struct {\n\tRate     ByteRate `json:\"rate,omitempty\" yaml:\"rate,omitempty\"`\n\tUpload   ByteRate `json:\"upload,omitempty\" yaml:\"upload,omitempty\"`\n\tDownload ByteRate `json:\"download,omitempty\" yaml:\"download,omitempty\"`\n}\n```\nBandwidthLimit caps aggregate traffic for an entire rule. Rate applies the same full-duplex limit to upload and download; Upload and Download provide asymmetric limits and cannot be combined with Rate.\n\n```go\nfunc (limit BandwidthLimit) DownloadBytesPerSecond() int64\n```\n\n```go\nfunc (limit BandwidthLimit) UploadBytesPerSecond() int64\n```\n\n```go\ntype ByteRate int64\n```\nByteRate is a normalized byte-per-second value. Configuration accepts common network units such as \"100 Mbps\" and byte-rate units such as \"10 MiB/s\".\n\n```go\nfunc (value ByteRate) MarshalText() ([]byte, error)\n```\n\n```go\nfunc (value ByteRate) String() string\n```\n\n```go\nfunc (value *ByteRate) UnmarshalJSON(data []byte) error\n```\n\n```go\nfunc (value *ByteRate) UnmarshalText(text []byte) error\n```\n\n```go\ntype ByteSize int64\n```\nByteSize is a normalized byte count. Configuration accepts decimal provider units (GB/TB) and IEC units (GiB/TiB).\n\n```go\nfunc (value ByteSize) MarshalText() ([]byte, error)\n```\n\n```go\nfunc (value ByteSize) String() string\n```\n\n```go\nfunc (value *ByteSize) UnmarshalJSON(data []byte) error\n```\n\n```go\nfunc (value *ByteSize) UnmarshalText(text []byte) error\n```\n\n```go\ntype CertProvider interface {\n\tGetCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error)\n\tObtain(ctx context.Context, domains []string) error\n}\n```\n\n```go\ntype Collector struct {\n\t// contains filtered or unexported fields\n}\n```\n\n```go\nfunc NewCollector() *Collector\n```\n\n```go\nfunc (collector *Collector) AddDownload(ruleID string, n int64)\n```\n\n```go\nfunc (collector *Collector) AddQuotaRejectedBytes(ruleID string, n int64)\n```\n\n```go\nfunc (collector *Collector) AddUpload(ruleID string, n int64)\n```\n\n```go\nfunc (collector *Collector) BandwidthPolicies() map[string]BandwidthLimit\n```\nBandwidthPolicies returns isolated rule-level limits for metrics and other read-only observers. Map membership distinguishes an unlimited direction from a rule with no aggregate bandwidth policy.\n\n```go\nfunc (collector *Collector) DecConns(ruleID string)\n```\n\n```go\nfunc (collector *Collector) EnsureRule(ruleID string)\n```\n\n```go\nfunc (collector *Collector) EnsureRuleProtocol(ruleID string, protocol Protocol)\n```\n\n```go\nfunc (collector *Collector) IncConns(ruleID string)\n```\n\n```go\nfunc (collector *Collector) IncSourceIPDenied(ruleID string)\n```\n\n```go\nfunc (collector *Collector) IncUDPPacketsDropped(ruleID string)\n```\n\n```go\nfunc (collector *Collector) IncUDPSessionRejected(ruleID string)\n```\n\n```go\nfunc (collector *Collector) QuotaPolicy(ruleID string) *TrafficQuota\n```\n\n```go\nfunc (collector *Collector) RemoveRule(ruleID string)\n```\nRemoveRule discards a rule's counters and protocol metadata. Forwarding for the rule must be stopped first; Manager.RemoveRule enforces that ordering.\n\n```go\nfunc (collector *Collector) Restore(snapshots []TrafficSnapshot)\n```\nRestore seeds cumulative counters from persisted snapshots. Call before any forwarding starts. Conns (live connection count) is intentionally not restored: a freshly started daemon has zero connections, and restoring the old value would show a bogus active-connection count.\n\n```go\nfunc (collector *Collector) RuleProtocols() map[string]Protocol\n```\n\n```go\nfunc (collector *Collector) SetBandwidthPolicy(ruleID string, limit *BandwidthLimit)\n```\n\n```go\nfunc (collector *Collector) SetConns(ruleID string, value int64)\n```\n\n```go\nfunc (collector *Collector) SetQuotaPolicy(ruleID string, quota *TrafficQuota)\n```\n\n```go\nfunc (collector *Collector) Snapshot(ruleID string) TrafficSnapshot\n```\n\n```go\nfunc (collector *Collector) SnapshotAll() []TrafficSnapshot\n```\n\n```go\ntype Manager struct {\n\t// contains filtered or unexported fields\n}\n```\n\n```go\nfunc NewManager(collector *Collector) *Manager\n```\n\n```go\nfunc NewManagerWithCert(collector *Collector, certMgr CertProvider) *Manager\n```\n\n```go\nfunc NewManagerWithCertOptions(collector *Collector, certMgr CertProvider, opts ManagerOptions) *Manager\n```\nNewManagerWithCertOptions creates a manager with a certificate provider and explicit manager-wide resource limits.\n\n```go\nfunc NewManagerWithOptions(collector *Collector, opts ManagerOptions) *Manager\n```\nNewManagerWithOptions creates a manager with explicit manager-wide resource limits. Zero-valued limits use safe defaults.\n\n```go\nfunc (manager *Manager) ApplySnapshot(rules []Rule, opts ApplySnapshotOptions) ApplyResult\n```\n\n```go\nfunc (manager *Manager) ApplySnapshotTransactional(rules []Rule, opts ApplySnapshotOptions) TransactionalApplyResult\n```\nApplySnapshotTransactional applies a complete desired snapshot as one operation. Every rule is validated before runtime state changes. If a later operation fails, prior operations are undone in reverse order and collector state is restored to its pre-apply snapshot on a best-effort basis.\n\n```go\nfunc (manager *Manager) BandwidthPolicies() map[string]BandwidthLimit\n```\nBandwidthPolicies reports configured aggregate limits for retained rules.\n\n```go\nfunc (manager *Manager) BeginApplySnapshotTransactional(rules []Rule, opts ApplySnapshotOptions) (*SnapshotApplyTransaction, TransactionalApplyResult)\n```\nBeginApplySnapshotTransactional applies a desired snapshot while retaining an undo journal. A non-nil transaction means the apply succeeded and the caller must call Commit or Rollback. Failed applies are rolled back before this method returns and produce a nil transaction.\n\n```go\nfunc (manager *Manager) RemoveRule(ruleID string)\n```\n\n```go\nfunc (manager *Manager) RestartRule(rule Rule) error\n```\n\n```go\nfunc (manager *Manager) RuleProtocols() map[string]Protocol\n```\nRuleProtocols returns protocol metadata for running, stopped, and disabled rules whose counters are still retained by this manager.\n\n```go\nfunc (manager *Manager) RunningCount() int\n```\n\n```go\nfunc (manager *Manager) RunningRules() []Rule\n```\n\n```go\nfunc (manager *Manager) SaveQuotaStateExact() error\n```\nSaveQuotaStateExact persists actual quota usage after forwarding has stopped.\n\n```go\nfunc (manager *Manager) SetUDPMaxSessions(limit int)\n```\nSetUDPMaxSessions updates admission for future UDP sessions. Existing sessions are not terminated when the limit is lowered; new sessions remain blocked until usage falls below the new limit.\n\n```go\nfunc (manager *Manager) Snapshot(ruleID string) TrafficSnapshot\n```\n\n```go\nfunc (manager *Manager) SnapshotAll() []TrafficSnapshot\n```\n\n```go\nfunc (manager *Manager) StartRule(rule Rule) error\n```\n\n```go\nfunc (manager *Manager) StopAll()\n```\n\n```go\nfunc (manager *Manager) StopRule(ruleID string)\n```\n\n```go\nfunc (manager *Manager) UDPMaxSessions() (limit, active int)\n```\nUDPMaxSessions reports the configured global limit and current usage.\n\n```go\ntype ManagerOptions struct {\n\t// UDPMaxSessions uses DefaultUDPGlobalMaxSessions when non-positive and is\n\t// clamped to MaxUDPGlobalMaxSessions when larger than the supported bound.\n\tUDPMaxSessions int\n\n\t// QuotaLedger supplies calendar-period accounting and optional strict\n\t// persistence. Nil uses an in-memory ledger.\n\tQuotaLedger *QuotaLedger\n\n\t// Resolver controls outbound target name resolution. Nil uses vmflow's\n\t// automatic system-first failover policy.\n\tResolver *dnsresolver.Resolver\n}\n```\nManagerOptions controls manager-wide forwarding resource limits.\n\n```go\ntype Protocol string\n```\n\n```go\nconst (\n\tProtocolTCP    Protocol = \"tcp\"\n\tProtocolUDP    Protocol = \"udp\"\n\tProtocolTCPUDP Protocol = \"tcp+udp\"\n\tProtocolHTTP   Protocol = \"http\"\n\tProtocolHTTPS  Protocol = \"https\"\n)\n```\n\n```go\ntype QuotaLedger struct {\n\t// contains filtered or unexported fields\n}\n```\n\n```go\nfunc NewQuotaLedger(store QuotaStateStore) (*QuotaLedger, error)\n```\n\n```go\nfunc (ledger *QuotaLedger) SaveExact() error\n```\nSaveExact must be called only after all forwarding runners have stopped. It replaces conservative durable credits with actual successful byte counts.\n\n```go\ntype QuotaPeriodSnapshot struct {\n\tPeriod         string `json:\"period\"`\n\tUsedBytes      int64  `json:\"used_bytes\"`\n\tLimitBytes     int64  `json:\"limit_bytes\"`\n\tRemainingBytes int64  `json:\"remaining_bytes\"`\n\tResetTime      int64  `json:\"reset_time\"`\n\tExhausted      bool   `json:\"exhausted\"`\n}\n```\n\n```go\ntype QuotaPersistentState struct {\n\tRuleID  string           `json:\"rule_id\"`\n\tDaily   map[string]int64 `json:\"daily,omitempty\"`\n\tMonthly map[string]int64 `json:\"monthly,omitempty\"`\n}\n```\nQuotaPersistentState is the durable high-water mark for one rule. Period maps retain prior keys so a clock rollback cannot recreate an empty period.\n\n```go\ntype QuotaStateStore interface {\n\tLoadQuotaState() ([]QuotaPersistentState, error)\n\tSaveQuotaState([]QuotaPersistentState) error\n}\n```\nQuotaStateStore provides strict persistence for enforced traffic quotas.\n\nDurability contract with QuotaLedger's write-behind flush: a LoadQuotaState error stays fatal at startup, but a SaveQuotaState error does not roll back the traffic granted in that round. The failed save gates every further reserve (fail-closed going forward) until one succeeds, and a crash may under-count usage by up to one durable chunk per rule and period.\n\n```go\ntype RollbackItemResult struct {\n\tRuleID string      `json:\"rule_id\"`\n\tAction ApplyAction `json:\"action\"`\n\tStatus string      `json:\"status\"`\n\tError  string      `json:\"error,omitempty\"`\n}\n```\nRollbackItemResult reports the outcome of reverting one successfully applied rule operation. Action is the original operation being reverted.\n\n```go\ntype RollbackResult struct {\n\tAttempted bool                 `json:\"attempted\"`\n\tFailed    bool                 `json:\"failed\"`\n\tItems     []RollbackItemResult `json:\"items,omitempty\"`\n}\n```\n\n```go\ntype Rule struct {\n\tRuleID       string          `json:\"rule_id\" yaml:\"rule_id\"`\n\tName         string          `json:\"name\" yaml:\"name\"`\n\tProtocol     Protocol        `json:\"protocol\" yaml:\"protocol\"`\n\tListenAddr   string          `json:\"listen_addr\" yaml:\"listen_addr\"`\n\tListenPort   int             `json:\"listen_port\" yaml:\"listen_port\"`\n\tTargetAddr   string          `json:\"target_addr\" yaml:\"target_addr\"`\n\tTargetPort   int             `json:\"target_port\" yaml:\"target_port\"`\n\tEnabled      bool            `json:\"enabled\" yaml:\"enabled\"`\n\tSpeedLimit   int64           `json:\"speed_limit\" yaml:\"speed_limit\"`\n\tBandwidth    *BandwidthLimit `json:\"bandwidth_limit,omitempty\" yaml:\"bandwidth_limit,omitempty\"`\n\tTrafficQuota *TrafficQuota   `json:\"traffic_quota,omitempty\" yaml:\"traffic_quota,omitempty\"`\n\tMaxConn      int             `json:\"max_conn\" yaml:\"max_conn\"`\n\tIdleTimeout  int             `json:\"idle_timeout,omitempty\" yaml:\"idle_timeout,omitempty\"`\n\tSourceIPMode SourceIPMode    `json:\"source_ip_mode,omitempty\" yaml:\"source_ip_mode,omitempty\"`\n\tSourceIPs    []string        `json:\"source_ips,omitempty\" yaml:\"source_ips,omitempty\"`\n\tDomains      []string        `json:\"domains,omitempty\" yaml:\"domains,omitempty\"`\n\tRemark       string          `json:\"remark,omitempty\" yaml:\"remark,omitempty\"`\n\tRevision     int64           `json:\"revision,omitempty\" yaml:\"revision,omitempty\"`\n\tCreatedTime  int64           `json:\"created_time,omitempty\" yaml:\"created_time,omitempty\"`\n\tUpdatedTime  int64           `json:\"updated_time,omitempty\" yaml:\"updated_time,omitempty\"`\n}\n```\n\n```go\nfunc (rule Rule) RuntimeEqual(other Rule) bool\n```\n\n```go\nfunc (rule Rule) Standardize() Rule\n```\n\n```go\nfunc (rule Rule) Validate() error\n```\n\n```go\ntype Runner interface {\n\tStart() error\n\tStop()\n}\n```\n\n```go\ntype SnapshotApplyTransaction struct {\n\t// contains filtered or unexported fields\n}\n```\nSnapshotApplyTransaction keeps a successful runtime apply reversible until its caller commits the associated external state (for example a config file rename). It owns Manager.applyMu until Commit or Rollback is called.\n\n```go\nfunc (transaction *SnapshotApplyTransaction) Commit()\n```\nCommit makes the applied runtime snapshot final and releases the manager.\n\n```go\nfunc (transaction *SnapshotApplyTransaction) Rollback() RollbackResult\n```\nRollback restores the runtime state captured before BeginApplySnapshotTransactional. It is idempotent; calling it after Commit returns an unattempted result.\n\n```go\ntype SourceIPMode string\n```\nSourceIPMode controls how a rule interprets its SourceIPs entries.\n\n```go\nconst (\n\tSourceIPModeOff       SourceIPMode = \"off\"\n\tSourceIPModeAllowlist SourceIPMode = \"allowlist\"\n\tSourceIPModeDenylist  SourceIPMode = \"denylist\"\n\n\t// MaxSourceIPsPerRule bounds the work performed for every new connection or\n\t// UDP datagram. Exact addresses use a map; CIDR prefixes are scanned.\n\tMaxSourceIPsPerRule = 256\n)\n```\n\n```go\ntype TrafficQuota struct {\n\tDaily    ByteSize `json:\"daily,omitempty\" yaml:\"daily,omitempty\"`\n\tMonthly  ByteSize `json:\"monthly,omitempty\" yaml:\"monthly,omitempty\"`\n\tTimezone string   `json:\"timezone,omitempty\" yaml:\"timezone,omitempty\"`\n\tAction   string   `json:\"action,omitempty\" yaml:\"action,omitempty\"`\n}\n```\nTrafficQuota limits the combined successful upload and download payload for calendar-day and calendar-month periods in Timezone.\n\n```go\ntype TrafficQuotaSnapshot struct {\n\tDaily   *QuotaPeriodSnapshot `json:\"daily,omitempty\"`\n\tMonthly *QuotaPeriodSnapshot `json:\"monthly,omitempty\"`\n\tBlocked bool                 `json:\"blocked\"`\n}\n```\nTrafficQuotaSnapshot describes the active calendar-period budgets for a rule.\n\n```go\ntype TrafficSnapshot struct {\n\tRuleID             string                `json:\"rule_id\"`\n\tUploadBytes        int64                 `json:\"upload_bytes\"`\n\tDownloadBytes      int64                 `json:\"download_bytes\"`\n\tConns              int64                 `json:\"conns\"`\n\tSourceIPDenied     int64                 `json:\"source_ip_denied_total,omitempty\"`\n\tUDPSessionRejected int64                 `json:\"udp_session_rejected_total,omitempty\"`\n\tUDPPacketsDropped  int64                 `json:\"udp_packets_dropped_total,omitempty\"`\n\tQuotaRejectedBytes int64                 `json:\"quota_rejected_bytes_total,omitempty\"`\n\tQuota              *TrafficQuotaSnapshot `json:\"quota,omitempty\"`\n\tUpdatedTime        int64                 `json:\"updated_time\"`\n}\n```\n\n```go\ntype TransactionalApplyResult struct {\n\tApply        ApplyResult    `json:\"apply\"`\n\tApplyFailure *ApplyFailure  `json:\"apply_failure,omitempty\"`\n\tRollback     RollbackResult `json:\"rollback\"`\n}\n```\nTransactionalApplyResult separates the error that stopped the desired snapshot from any error encountered while restoring the previous snapshot.\n\n","path":"github.com/cloudapp3/vmflow/engine","name":"engine","synopsis":"","isRedistributable":true}
