Help us shape the future of Go! Take the 2026 Go Developer Survey

datacap

package
v0.0.166 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

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

Client handles communication with the datacap sidecar service.

func NewClient

func NewClient(baseURL string, timeout time.Duration) *Client

NewClient creates a new datacap client. The baseURL can be overridden by the DATACAP_URL environment variable. Supports both HTTP and HTTPS. For HTTPS, uses system's trusted certificates by default.

func NewClientWithConfig

func NewClientWithConfig(config ClientConfig) *Client

NewClientWithConfig creates a new datacap client with advanced configuration.

func (*Client) GetDataCapStatus

func (c *Client) GetDataCapStatus(ctx context.Context, deviceID string) (*DataCapStatus, error)

func (*Client) ReportDataCapConsumption

func (c *Client) ReportDataCapConsumption(ctx context.Context, report *DataCapReport) (*DataCapStatus, error)

ReportDataCapConsumption sends data consumption report to the sidecar. Endpoint: POST /data-cap/ This tracks usage and returns updated cap status.

type ClientConfig

type ClientConfig struct {
	BaseURL            string
	Timeout            time.Duration
	InsecureSkipVerify bool
}

ClientConfig holds configuration for the datacap client.

type Conn

type Conn struct {
	net.Conn
	// contains filtered or unexported fields
}

Conn wraps a net.Conn and tracks data consumption for datacap reporting.

func NewConn

func NewConn(config ConnConfig) *Conn

NewConn creates a new datacap-tracked connection wrapper.

func (*Conn) Close

func (c *Conn) Close() error

Close stops reporting and closes the underlying connection.

func (*Conn) GetBytesConsumed

func (c *Conn) GetBytesConsumed() int64

GetBytesConsumed returns the total bytes consumed by this connection.

func (*Conn) GetStatus

func (c *Conn) GetStatus() (*DataCapStatus, error)

GetStatus queries the sidecar for current data cap status.

func (*Conn) Read

func (c *Conn) Read(b []byte) (n int, err error)

Read tracks bytes received and applies throttling if enabled.

func (*Conn) Upstream

func (c *Conn) Upstream() any

func (*Conn) Write

func (c *Conn) Write(b []byte) (n int, err error)

Write tracks bytes sent and applies throttling if enabled.

type ConnConfig

type ConnConfig struct {
	TrafficCategory string
	Conn            net.Conn
	Client          *Client
	Logger          log.ContextLogger
	ClientInfo      clientcontext.ClientInfo
	ReportInterval  time.Duration
	Throttler       *Throttler // Shared throttler from registry
}

ConnConfig holds configuration for creating a datacap-tracked connection.

type DataCapReport

type DataCapReport struct {
	DeviceID     string        `json:"deviceId"`
	CountryCode  string        `json:"countryCode"`
	Platform     string        `json:"platform"`
	BytesUsed    int64         `json:"bytesUsed"`
	TrafficUsage *TrafficUsage `json:"trafficUsage,omitempty"`
}

DataCapReport represents the request body for POST /data-cap/ endpoint.

type DataCapStatus

type DataCapStatus struct {
	Throttle   bool  `json:"throttle"`
	CapLimit   int64 `json:"capLimit"`
	ExpiryTime int64 `json:"expiryTime"`
}

DataCapStatus represents the response from the GET /data-cap/{deviceId} endpoint.

type DatacapTracker

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

func NewDatacapTracker

func NewDatacapTracker(options Options, logger log.ContextLogger) (*DatacapTracker, error)

func (*DatacapTracker) RoutedConnection

func (t *DatacapTracker) RoutedConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, matchedRule adapter.Rule, matchOutbound adapter.Outbound) net.Conn

func (*DatacapTracker) RoutedPacketConnection

func (t *DatacapTracker) RoutedPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext, matchedRule adapter.Rule, matchOutbound adapter.Outbound) N.PacketConn

type Options

type Options struct {
	TrafficCategories bool     `json:"traffic_categories,omitempty"`
	LanternHosts      []string `json:"lantern_hosts,omitempty"`
	ProbeHosts        []string `json:"probe_hosts,omitempty"`
	URL               string   `json:"url,omitempty"`
	ReportInterval    string   `json:"report_interval,omitempty"`
	HTTPTimeout       string   `json:"http_timeout,omitempty"`
}

type PacketConn

type PacketConn struct {
	N.PacketConn
	// contains filtered or unexported fields
}

PacketConn wraps a sing-box network.PacketConn and tracks data consumption for datacap reporting.

func NewPacketConn

func NewPacketConn(config PacketConnConfig) *PacketConn

NewPacketConn creates a new datacap-tracked packet connection wrapper.

func (*PacketConn) Close

func (c *PacketConn) Close() error

Close stops reporting and closes the underlying packet connection.

func (*PacketConn) GetBytesConsumed

func (c *PacketConn) GetBytesConsumed() int64

GetBytesConsumed returns the total bytes consumed by this packet connection.

func (*PacketConn) GetStatus

func (c *PacketConn) GetStatus() (*DataCapStatus, error)

GetStatus queries the sidecar for current data cap status.

func (*PacketConn) ReadPacket

func (c *PacketConn) ReadPacket(buffer *buf.Buffer) (destination M.Socksaddr, err error)

ReadPacket tracks bytes received from packet reading and applies throttling.

func (*PacketConn) Upstream

func (c *PacketConn) Upstream() any

func (*PacketConn) WritePacket

func (c *PacketConn) WritePacket(buffer *buf.Buffer, destination M.Socksaddr) error

WritePacket tracks bytes sent from packet writing and applies throttling.

type PacketConnConfig

type PacketConnConfig struct {
	TrafficCategories bool
	Conn              N.PacketConn
	Client            *Client
	Logger            log.ContextLogger
	ClientInfo        clientcontext.ClientInfo
	ReportInterval    time.Duration
	Throttler         *Throttler // Shared throttler from registry
}

PacketConnConfig holds configuration for creating a datacap-tracked packet connection.

type ThrottleRegistry

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

ThrottleRegistry manages shared throttlers per device. All connections from the same device share a single Throttler instance, ensuring the bandwidth limit is enforced across all parallel connections.

func NewThrottleRegistry

func NewThrottleRegistry() *ThrottleRegistry

NewThrottleRegistry creates a new registry.

func (*ThrottleRegistry) Count

func (r *ThrottleRegistry) Count() int

Count returns the number of devices with throttlers. Useful for testing and monitoring.

func (*ThrottleRegistry) GetOrCreate

func (r *ThrottleRegistry) GetOrCreate(deviceID string) *Throttler

GetOrCreate returns the throttler for the given device ID. If no throttler exists for the device, a new one is created with throttling disabled. Throttling is enabled later via UpdateRates when the datacap status indicates throttle=true.

type Throttler

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

Throttler implements bandwidth throttling using a token bucket algorithm. This matches the approach used in http-proxy-lantern for consistent behavior.

func NewThrottler

func NewThrottler(bytesPerSec int64) *Throttler

NewThrottler creates a new throttler with the specified bytes per second limit. Both read and write use the same rate initially.

func NewThrottlerWithRates

func NewThrottlerWithRates(readBytesPerSec, writeBytesPerSec int64) *Throttler

NewThrottlerWithRates creates a throttler with separate read and write rates. This allows asymmetric throttling (e.g., throttle downloads but not uploads).

func (*Throttler) Disable

func (t *Throttler) Disable()

Disable disables throttling.

func (*Throttler) Enable

func (t *Throttler) Enable(bytesPerSec int64)

Enable enables throttling with the specified rate for both read and write.

func (*Throttler) EnableWithRates

func (t *Throttler) EnableWithRates(readBytesPerSec, writeBytesPerSec int64)

EnableWithRates enables throttling with separate read and write rates.

func (*Throttler) GetBytesPerSecond

func (t *Throttler) GetBytesPerSecond() int64

GetBytesPerSecond returns the read throttle rate (for backward compatibility).

func (*Throttler) GetReadRate

func (t *Throttler) GetReadRate() int64

GetReadRate returns the current read throttle rate in bytes per second.

func (*Throttler) GetWriteRate

func (t *Throttler) GetWriteRate() int64

GetWriteRate returns the current write throttle rate in bytes per second.

func (*Throttler) IsEnabled

func (t *Throttler) IsEnabled() bool

IsEnabled returns whether throttling is enabled.

func (*Throttler) UpdateRates

func (t *Throttler) UpdateRates(readBytesPerSec, writeBytesPerSec int64)

UpdateRates updates throttle rates without resetting the token bucket. Use this when the throttle state is being refreshed (e.g., every report interval) to avoid giving users a burst of full-speed traffic.

func (*Throttler) WaitRead

func (t *Throttler) WaitRead(ctx context.Context, n int) error

WaitRead waits until n bytes can be read according to the rate limit. This uses the token bucket algorithm: tokens are added continuously at the configured rate, and operations consume tokens. If not enough tokens are available, the operation blocks until sufficient tokens accumulate.

func (*Throttler) WaitWrite

func (t *Throttler) WaitWrite(ctx context.Context, n int) error

WaitWrite waits until n bytes can be written according to the rate limit.

type TrafficUsage

type TrafficUsage struct {
	LanternBytes       int64 `json:"lanternBytes,omitempty"`
	ProbeBytes         int64 `json:"probeBytes,omitempty"`
	OtherBytes         int64 `json:"otherBytes,omitempty"`
	UnknownBytes       int64 `json:"unknownBytes,omitempty"`
	LanternConnections int64 `json:"lanternConnections,omitempty"`
	ProbeConnections   int64 `json:"probeConnections,omitempty"`
	OtherConnections   int64 `json:"otherConnections,omitempty"`
	UnknownConnections int64 `json:"unknownConnections,omitempty"`
}

TrafficUsage carries only coarse counters to the sidecar. A bidirectional connection is evidence of exchanged bytes, not application success or humanity.

Jump to

Keyboard shortcuts

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