2024-10-03 12:40:46 +05:30
|
|
|
package elasticstream
|
|
|
|
|
|
|
|
import (
|
2024-10-03 21:45:17 +05:30
|
|
|
"fmt"
|
|
|
|
|
2024-10-03 12:40:46 +05:30
|
|
|
"github.com/elastic/go-elasticsearch/v8"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Client struct {
|
|
|
|
es *elasticsearch.Client
|
|
|
|
config *Config
|
2024-10-03 14:04:17 +05:30
|
|
|
ch chan Data
|
2024-10-03 12:40:46 +05:30
|
|
|
}
|
|
|
|
|
2024-10-03 12:57:23 +05:30
|
|
|
func NewClient(config *Config) (*Client, error) {
|
|
|
|
client := &Client{
|
|
|
|
config: config,
|
|
|
|
}
|
2024-10-03 21:34:57 +05:30
|
|
|
return client, nil
|
|
|
|
}
|
2024-10-03 12:57:23 +05:30
|
|
|
|
2024-10-03 21:34:57 +05:30
|
|
|
func (c *Client) Open() error {
|
|
|
|
// Open a connection with ElasticSearch
|
2024-10-03 12:57:23 +05:30
|
|
|
cfg := elasticsearch.Config{
|
|
|
|
Addresses: []string{
|
2024-10-03 21:34:57 +05:30
|
|
|
c.config.Host,
|
2024-10-03 12:57:23 +05:30
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2024-10-03 21:34:57 +05:30
|
|
|
var err error
|
|
|
|
c.es, err = elasticsearch.NewClient(cfg)
|
2024-10-03 12:40:46 +05:30
|
|
|
if err != nil {
|
2024-10-03 21:34:57 +05:30
|
|
|
return err
|
2024-10-03 12:40:46 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
// create a buffer channel
|
2024-10-03 14:04:17 +05:30
|
|
|
c.ch = make(chan Data, 1)
|
2024-10-03 12:40:46 +05:30
|
|
|
|
2024-10-03 14:04:17 +05:30
|
|
|
for _, index := range c.config.Indexes {
|
|
|
|
NewWorker(c, index)
|
2024-10-03 12:40:46 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-10-03 21:45:17 +05:30
|
|
|
func (c *Client) Read() (*Data, error) {
|
|
|
|
|
|
|
|
data, ok := <-c.ch
|
|
|
|
if !ok {
|
|
|
|
return nil, fmt.Errorf("error reading data from channel")
|
|
|
|
}
|
|
|
|
return &data, nil
|
2024-10-03 12:40:46 +05:30
|
|
|
}
|
|
|
|
|
2024-10-03 21:34:57 +05:30
|
|
|
// func (c *Client) Ack(ctx context.Context, position int) error {
|
|
|
|
// return nil
|
|
|
|
// }
|
|
|
|
|
2024-10-03 12:40:46 +05:30
|
|
|
// close the client
|
|
|
|
func (c *Client) Teardown() error {
|
|
|
|
return nil
|
|
|
|
}
|