WIP: initial commit

This commit is contained in:
Suyono 2025-06-23 09:48:01 +10:00
commit 949a75fb61
11 changed files with 936 additions and 0 deletions

73
LICENSE Normal file
View File

@ -0,0 +1,73 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
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.

72
agent/agent.go Normal file
View File

@ -0,0 +1,72 @@
package agent
/*
Copyright 2025 Suyono <suyono3484@gmail.com>
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"
"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)
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
}

12
go.mod Normal file
View File

@ -0,0 +1,12 @@
module gitea.suyono.dev/suyono/go-agent
go 1.24
require (
golang.org/x/net v0.41.0 // indirect
golang.org/x/sys v0.33.0 // indirect
golang.org/x/text v0.26.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822 // indirect
google.golang.org/grpc v1.73.0 // indirect
google.golang.org/protobuf v1.36.6 // indirect
)

12
go.sum Normal file
View File

@ -0,0 +1,12 @@
golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw=
golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA=
golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw=
golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M=
golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822 h1:fc6jSaCT0vBduLYZHYrBBNY4dsWuvgyff9noRNDdBeE=
google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A=
google.golang.org/grpc v1.73.0 h1:VIWSmpI2MegBtTuFt5/JWy2oXxtjJ/e89Z70ImfD2ok=
google.golang.org/grpc v1.73.0/go.mod h1:50sbHOUqWoCQGI8V2HQLJM0B+LMlIUjNSZmow7EVBQc=
google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=

312
proto/agent.pb.go Normal file
View File

@ -0,0 +1,312 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.6
// protoc v6.31.1
// source: gitea.suyono.dev/suyono/go-agent/proto/agent.proto
package proto
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
emptypb "google.golang.org/protobuf/types/known/emptypb"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type CacheGetRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *CacheGetRequest) Reset() {
*x = CacheGetRequest{}
mi := &file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *CacheGetRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*CacheGetRequest) ProtoMessage() {}
func (x *CacheGetRequest) ProtoReflect() protoreflect.Message {
mi := &file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use CacheGetRequest.ProtoReflect.Descriptor instead.
func (*CacheGetRequest) Descriptor() ([]byte, []int) {
return file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_rawDescGZIP(), []int{0}
}
func (x *CacheGetRequest) GetKey() string {
if x != nil {
return x.Key
}
return ""
}
type CacheValue struct {
state protoimpl.MessageState `protogen:"open.v1"`
Status string `protobuf:"bytes,1,opt,name=status,proto3" json:"status,omitempty"`
Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
Message string `protobuf:"bytes,3,opt,name=message,proto3" json:"message,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *CacheValue) Reset() {
*x = CacheValue{}
mi := &file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *CacheValue) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*CacheValue) ProtoMessage() {}
func (x *CacheValue) ProtoReflect() protoreflect.Message {
mi := &file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use CacheValue.ProtoReflect.Descriptor instead.
func (*CacheValue) Descriptor() ([]byte, []int) {
return file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_rawDescGZIP(), []int{1}
}
func (x *CacheValue) GetStatus() string {
if x != nil {
return x.Status
}
return ""
}
func (x *CacheValue) GetValue() string {
if x != nil {
return x.Value
}
return ""
}
func (x *CacheValue) GetMessage() string {
if x != nil {
return x.Message
}
return ""
}
type CacheSetRequest struct {
state protoimpl.MessageState `protogen:"open.v1"`
Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"`
Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *CacheSetRequest) Reset() {
*x = CacheSetRequest{}
mi := &file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *CacheSetRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*CacheSetRequest) ProtoMessage() {}
func (x *CacheSetRequest) ProtoReflect() protoreflect.Message {
mi := &file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use CacheSetRequest.ProtoReflect.Descriptor instead.
func (*CacheSetRequest) Descriptor() ([]byte, []int) {
return file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_rawDescGZIP(), []int{2}
}
func (x *CacheSetRequest) GetKey() string {
if x != nil {
return x.Key
}
return ""
}
func (x *CacheSetRequest) GetValue() string {
if x != nil {
return x.Value
}
return ""
}
type SetStatus struct {
state protoimpl.MessageState `protogen:"open.v1"`
Status string `protobuf:"bytes,1,opt,name=status,proto3" json:"status,omitempty"`
Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *SetStatus) Reset() {
*x = SetStatus{}
mi := &file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *SetStatus) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SetStatus) ProtoMessage() {}
func (x *SetStatus) ProtoReflect() protoreflect.Message {
mi := &file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_msgTypes[3]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SetStatus.ProtoReflect.Descriptor instead.
func (*SetStatus) Descriptor() ([]byte, []int) {
return file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_rawDescGZIP(), []int{3}
}
func (x *SetStatus) GetStatus() string {
if x != nil {
return x.Status
}
return ""
}
func (x *SetStatus) GetMessage() string {
if x != nil {
return x.Message
}
return ""
}
var File_gitea_suyono_dev_suyono_go_agent_proto_agent_proto protoreflect.FileDescriptor
const file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_rawDesc = "" +
"\n" +
"2gitea.suyono.dev/suyono/go-agent/proto/agent.proto\x12\x05proto\x1a\x1bgoogle/protobuf/empty.proto\"#\n" +
"\x0fCacheGetRequest\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\"T\n" +
"\n" +
"CacheValue\x12\x16\n" +
"\x06status\x18\x01 \x01(\tR\x06status\x12\x14\n" +
"\x05value\x18\x02 \x01(\tR\x05value\x12\x18\n" +
"\amessage\x18\x03 \x01(\tR\amessage\"9\n" +
"\x0fCacheSetRequest\x12\x10\n" +
"\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
"\x05value\x18\x02 \x01(\tR\x05value\"=\n" +
"\tSetStatus\x12\x16\n" +
"\x06status\x18\x01 \x01(\tR\x06status\x12\x18\n" +
"\amessage\x18\x02 \x01(\tR\amessage2\xa6\x01\n" +
"\x05Agent\x120\n" +
"\x03Get\x12\x16.proto.CacheGetRequest\x1a\x11.proto.CacheValue\x12/\n" +
"\x03Set\x12\x16.proto.CacheSetRequest\x1a\x10.proto.SetStatus\x12:\n" +
"\bShutdown\x12\x16.google.protobuf.Empty\x1a\x16.google.protobuf.EmptyB.Z,gitea.suyono.dev/suyono/go-agent/proto;protob\x06proto3"
var (
file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_rawDescOnce sync.Once
file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_rawDescData []byte
)
func file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_rawDescGZIP() []byte {
file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_rawDescOnce.Do(func() {
file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_rawDesc), len(file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_rawDesc)))
})
return file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_rawDescData
}
var file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
var file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_goTypes = []any{
(*CacheGetRequest)(nil), // 0: proto.CacheGetRequest
(*CacheValue)(nil), // 1: proto.CacheValue
(*CacheSetRequest)(nil), // 2: proto.CacheSetRequest
(*SetStatus)(nil), // 3: proto.SetStatus
(*emptypb.Empty)(nil), // 4: google.protobuf.Empty
}
var file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_depIdxs = []int32{
0, // 0: proto.Agent.Get:input_type -> proto.CacheGetRequest
2, // 1: proto.Agent.Set:input_type -> proto.CacheSetRequest
4, // 2: proto.Agent.Shutdown:input_type -> google.protobuf.Empty
1, // 3: proto.Agent.Get:output_type -> proto.CacheValue
3, // 4: proto.Agent.Set:output_type -> proto.SetStatus
4, // 5: proto.Agent.Shutdown:output_type -> google.protobuf.Empty
3, // [3:6] is the sub-list for method output_type
0, // [0:3] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_init() }
func file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_init() {
if File_gitea_suyono_dev_suyono_go_agent_proto_agent_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_rawDesc), len(file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_rawDesc)),
NumEnums: 0,
NumMessages: 4,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_goTypes,
DependencyIndexes: file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_depIdxs,
MessageInfos: file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_msgTypes,
}.Build()
File_gitea_suyono_dev_suyono_go_agent_proto_agent_proto = out.File
file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_goTypes = nil
file_gitea_suyono_dev_suyono_go_agent_proto_agent_proto_depIdxs = nil
}

34
proto/agent.proto Normal file
View File

@ -0,0 +1,34 @@
syntax = "proto3";
package proto;
option go_package="gitea.suyono.dev/suyono/go-agent/proto;proto";
import "google/protobuf/empty.proto";
message CacheGetRequest {
string key = 1;
}
message CacheValue {
string status = 1;
string value = 2;
string message = 3;
}
message CacheSetRequest {
string key = 1;
string value = 2;
}
message SetStatus{
string status = 1;
string message = 2;
}
service Agent {
rpc Get(CacheGetRequest) returns (CacheValue);
rpc Set(CacheSetRequest) returns (SetStatus);
rpc Shutdown(google.protobuf.Empty) returns (google.protobuf.Empty);
}

198
proto/agent_grpc.pb.go Normal file
View File

@ -0,0 +1,198 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.5.1
// - protoc v6.31.1
// source: gitea.suyono.dev/suyono/go-agent/proto/agent.proto
package proto
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
emptypb "google.golang.org/protobuf/types/known/emptypb"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.64.0 or later.
const _ = grpc.SupportPackageIsVersion9
const (
Agent_Get_FullMethodName = "/proto.Agent/Get"
Agent_Set_FullMethodName = "/proto.Agent/Set"
Agent_Shutdown_FullMethodName = "/proto.Agent/Shutdown"
)
// AgentClient is the client API for Agent service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type AgentClient interface {
Get(ctx context.Context, in *CacheGetRequest, opts ...grpc.CallOption) (*CacheValue, error)
Set(ctx context.Context, in *CacheSetRequest, opts ...grpc.CallOption) (*SetStatus, error)
Shutdown(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*emptypb.Empty, error)
}
type agentClient struct {
cc grpc.ClientConnInterface
}
func NewAgentClient(cc grpc.ClientConnInterface) AgentClient {
return &agentClient{cc}
}
func (c *agentClient) Get(ctx context.Context, in *CacheGetRequest, opts ...grpc.CallOption) (*CacheValue, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(CacheValue)
err := c.cc.Invoke(ctx, Agent_Get_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *agentClient) Set(ctx context.Context, in *CacheSetRequest, opts ...grpc.CallOption) (*SetStatus, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(SetStatus)
err := c.cc.Invoke(ctx, Agent_Set_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *agentClient) Shutdown(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*emptypb.Empty, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(emptypb.Empty)
err := c.cc.Invoke(ctx, Agent_Shutdown_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// AgentServer is the server API for Agent service.
// All implementations must embed UnimplementedAgentServer
// for forward compatibility.
type AgentServer interface {
Get(context.Context, *CacheGetRequest) (*CacheValue, error)
Set(context.Context, *CacheSetRequest) (*SetStatus, error)
Shutdown(context.Context, *emptypb.Empty) (*emptypb.Empty, error)
mustEmbedUnimplementedAgentServer()
}
// UnimplementedAgentServer must be embedded to have
// forward compatible implementations.
//
// NOTE: this should be embedded by value instead of pointer to avoid a nil
// pointer dereference when methods are called.
type UnimplementedAgentServer struct{}
func (UnimplementedAgentServer) Get(context.Context, *CacheGetRequest) (*CacheValue, error) {
return nil, status.Errorf(codes.Unimplemented, "method Get not implemented")
}
func (UnimplementedAgentServer) Set(context.Context, *CacheSetRequest) (*SetStatus, error) {
return nil, status.Errorf(codes.Unimplemented, "method Set not implemented")
}
func (UnimplementedAgentServer) Shutdown(context.Context, *emptypb.Empty) (*emptypb.Empty, error) {
return nil, status.Errorf(codes.Unimplemented, "method Shutdown not implemented")
}
func (UnimplementedAgentServer) mustEmbedUnimplementedAgentServer() {}
func (UnimplementedAgentServer) testEmbeddedByValue() {}
// UnsafeAgentServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to AgentServer will
// result in compilation errors.
type UnsafeAgentServer interface {
mustEmbedUnimplementedAgentServer()
}
func RegisterAgentServer(s grpc.ServiceRegistrar, srv AgentServer) {
// If the following call pancis, it indicates UnimplementedAgentServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
t.testEmbeddedByValue()
}
s.RegisterService(&Agent_ServiceDesc, srv)
}
func _Agent_Get_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CacheGetRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(AgentServer).Get(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Agent_Get_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(AgentServer).Get(ctx, req.(*CacheGetRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Agent_Set_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CacheSetRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(AgentServer).Set(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Agent_Set_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(AgentServer).Set(ctx, req.(*CacheSetRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Agent_Shutdown_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(emptypb.Empty)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(AgentServer).Shutdown(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Agent_Shutdown_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(AgentServer).Shutdown(ctx, req.(*emptypb.Empty))
}
return interceptor(ctx, in, info, handler)
}
// Agent_ServiceDesc is the grpc.ServiceDesc for Agent service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var Agent_ServiceDesc = grpc.ServiceDesc{
ServiceName: "proto.Agent",
HandlerType: (*AgentServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Get",
Handler: _Agent_Get_Handler,
},
{
MethodName: "Set",
Handler: _Agent_Set_Handler,
},
{
MethodName: "Shutdown",
Handler: _Agent_Shutdown_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "gitea.suyono.dev/suyono/go-agent/proto/agent.proto",
}

1
service/option.go Normal file
View File

@ -0,0 +1 @@
package service

139
service/serve.go Normal file
View File

@ -0,0 +1,139 @@
package service
/*
Copyright 2025 Suyono <suyono3484@gmail.com>
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"
"net"
"os"
"sync/atomic"
"time"
pb "gitea.suyono.dev/suyono/go-agent/proto"
"gitea.suyono.dev/suyono/go-agent/storage"
"google.golang.org/grpc"
"google.golang.org/protobuf/types/known/emptypb"
)
type Option interface {
SocketPath() string
Expiry() string
StopGraceTime() time.Duration
}
type Storage interface {
Get(string) (string, error)
Set(string, string) error
Shutdown() error
}
type server struct {
pb.UnimplementedAgentServer
stor Storage
}
func (s *server) Get(ctx context.Context, req *pb.CacheGetRequest) (*pb.CacheValue, error) {
val, err := s.stor.Get(req.GetKey())
if err != nil {
return nil, err
}
result := &pb.CacheValue{
Status: "OK",
Value: val,
}
return result, nil
}
func (s *server) Set(ctx context.Context, req *pb.CacheSetRequest) (*pb.SetStatus, error) {
err := s.stor.Set(req.GetKey(), req.GetValue())
if err != nil {
return nil, err
}
return &pb.SetStatus{
Status: "OK",
}, nil
}
func (s *server) Shutdown(context.Context, *emptypb.Empty) (*emptypb.Empty, error) {
if err := s.stor.Shutdown(); err != nil {
return nil, err
}
return &emptypb.Empty{}, nil
}
func Serve(ctx context.Context, opt Option) error {
var (
l net.Listener
err error
errC error
ok bool
sw *atomic.Bool
cancel context.CancelFunc
)
socketPath := opt.SocketPath()
os.Remove(socketPath)
if l, err = net.Listen("unix", socketPath); err != nil {
return fmt.Errorf("failed to listen on unix socket: %w", err)
}
grpcServer := grpc.NewServer()
pb.RegisterAgentServer(grpcServer, &server{stor: storage.NewInMap()})
errChan := make(chan error, 1)
ctx, cancel = context.WithCancel(ctx)
sw = new(atomic.Bool)
sw.Store(false)
go func() {
err := grpcServer.Serve(l)
sw.Swap(true)
if err != nil {
errChan <- err
}
close(errChan)
cancel()
}()
<-ctx.Done()
if !sw.Load() {
grpcServer.GracefulStop()
}
fst := time.NewTimer(opt.StopGraceTime())
err = nil
fsl:
for {
select {
case errC, ok = <-errChan:
if !ok {
break fsl
}
if errC != nil {
err = errC
}
case <-fst.C:
if !sw.Load() {
grpcServer.Stop()
}
break fsl
}
}
return err
}

23
storage/error.go Normal file
View File

@ -0,0 +1,23 @@
package storage
/*
Copyright 2025 Suyono <suyono3484@gmail.com>
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 "errors"
var (
ErrNotFound = errors.New("could not find key in the cache")
)

60
storage/inmap.go Normal file
View File

@ -0,0 +1,60 @@
package storage
/*
Copyright 2025 Suyono <suyono3484@gmail.com>
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 "sync"
type InMap struct {
mtx *sync.Mutex
stor map[string]string
}
func NewInMap() *InMap {
return &InMap{
mtx: new(sync.Mutex),
stor: make(map[string]string),
}
}
func (i *InMap) Set(key, value string) error {
i.mtx.Lock()
defer i.mtx.Unlock()
i.stor[key] = value
return nil
}
func (i *InMap) Get(key string) (string, error) {
var (
val string
ok bool
)
i.mtx.Lock()
defer i.mtx.Unlock()
if val, ok = i.stor[key]; !ok {
return "", ErrNotFound
}
return val, nil
}
func (i *InMap) Shutdown() error {
return nil
}