99 lines
2.3 KiB
Go
99 lines
2.3 KiB
Go
// Package influx_gateway_Lib provides an abstraction to the client influx.
|
|
package influx
|
|
|
|
import (
|
|
"context"
|
|
datapoint "gateway/point"
|
|
|
|
"github.com/InfluxCommunity/influxdb3-go/v2/influxdb3"
|
|
"github.com/InfluxCommunity/influxdb3-go/v2/influxdb3/batching"
|
|
)
|
|
|
|
const BatchSize = 50 // Number of points to batch before pushing to InfluxDB
|
|
const BatchCapacity = 50 // Capacity maximum of the buffer
|
|
|
|
// Gateway provides the abstraction of all gateways to send data points
|
|
type Gateway interface {
|
|
AddDatapoint(dp datapoint.DataPointInfo) error
|
|
Close() error
|
|
Flush() error
|
|
}
|
|
|
|
// An InfluxGateway is the abstracted influx gateway.
|
|
// It provides the influx parameters to initialize the connection
|
|
// and the batcher to batch the points before pushing to Influx.
|
|
type InfluxGateway struct {
|
|
client *influxdb3.Client
|
|
batcher *batching.Batcher
|
|
}
|
|
|
|
// NewInfluxGateway creates a new InfluxGateway with the given parameters.
|
|
func NewInfluxGateway(url string, token string, database string) (*InfluxGateway, error) {
|
|
|
|
client, err := influxdb3.New(influxdb3.ClientConfig{
|
|
Host: url,
|
|
Token: token,
|
|
Database: database,
|
|
})
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &InfluxGateway{
|
|
client: client,
|
|
batcher: batching.NewBatcher(
|
|
batching.WithSize(BatchSize),
|
|
batching.WithInitialCapacity(BatchCapacity),
|
|
),
|
|
}, nil
|
|
}
|
|
|
|
// AddDatapoint is used to add a datapoint in the batcher. It uses the
|
|
// DataPointInfo interface for abstracting the generic type of the DataPoint.
|
|
// It pushes the batch of point when the number of points >= batch size.
|
|
func (g *InfluxGateway) AddDatapoint(dp datapoint.DataPointInfo) error {
|
|
|
|
tagsList := map[string]string{}
|
|
for _, t := range dp.Tags() {
|
|
tagsList[t.Subject] = t.Content
|
|
}
|
|
g.batcher.Add(
|
|
influxdb3.NewPoint(
|
|
dp.MeasurementName(),
|
|
tagsList,
|
|
dp.PayloadAsAny(),
|
|
dp.Timestamp(),
|
|
),
|
|
)
|
|
|
|
// check if the number of point >= batchsize
|
|
if g.batcher.Ready() {
|
|
// Send batch to influx DB
|
|
err := g.Flush()
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Flush sends the current batch of points to InfluxDB.
|
|
func (g *InfluxGateway) Flush() error {
|
|
// Send batch to influx DB
|
|
err := g.client.WritePoints(context.Background(), g.batcher.Emit())
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// Close closes the InfluxGateway client.
|
|
func (g *InfluxGateway) Close() error {
|
|
return g.client.Close()
|
|
}
|