package agent /* Copyright 2025 Suyono Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import ( "context" "fmt" "google.golang.org/protobuf/types/known/emptypb" "net" pb "gitea.suyono.dev/suyono/go-agent/proto" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" ) type CacheConn struct { conn *grpc.ClientConn client pb.AgentClient } func NewCacheConn(socketPath string) (CacheConn, error) { var ( result CacheConn err error ) result.conn, err = grpc.NewClient( socketPath, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) { var d net.Dialer return d.DialContext(ctx, "unix", addr) }), ) if err != nil { return result, err } result.client = pb.NewAgentClient(result.conn) if _, err = result.client.Ping(context.Background(), new(emptypb.Empty)); err != nil { return result, err } return result, nil } func (c CacheConn) Get(ctx context.Context, key string) (string, error) { var ( rpcResult *pb.CacheValue err error ) if rpcResult, err = c.client.Get(ctx, &pb.CacheGetRequest{Key: key}); err != nil { return "", fmt.Errorf("get from cache: %w", err) } if rpcResult.Status != "OK" { return "", fmt.Errorf("get from cache: status %s with message %s", rpcResult.Status, rpcResult.Message) } return rpcResult.Value, nil } func (c CacheConn) Set(ctx context.Context, key string, value string) error { rpcStatus, err := c.client.Set(ctx, &pb.CacheSetRequest{Key: key, Value: value}) if err != nil { return fmt.Errorf("set to cache: %w", err) } if rpcStatus.Status != "OK" { return fmt.Errorf("set to cache: status %s with message %s", rpcStatus.Status, rpcStatus.Message) } return nil } func (c CacheConn) Shutdown(ctx context.Context) error { _, err := c.client.Shutdown(ctx, new(emptypb.Empty)) if err != nil { return fmt.Errorf("shutdown: %w", err) } return nil } func (c CacheConn) Close() error { return c.conn.Close() }