initial rewrite, use micro v4 and not cms-xxx stuff #4

Merged
vtolstov merged 24 commits from rewrite into master 2023-08-14 15:08:53 +03:00
20 changed files with 2691 additions and 2982 deletions
Showing only changes of commit 816b43dc37 - Show all commits

View File

@ -2,13 +2,26 @@ package main
import ( import (
"context" "context"
"os"
"os/signal"
"syscall"
"go.unistack.org/micro/v4/logger" "go.unistack.org/micro/v4/logger"
"go.unistack.org/unistack-org/pkgdash/service" "go.unistack.org/unistack-org/pkgdash/service"
) )
func main() { func main() {
ctx := context.Background() ctx, cancel := context.WithCancel(context.Background())
defer cancel()
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-ch
logger.Infof(ctx, "handle signal %v, exiting", sig)
cancel()
}()
svc, err := service.NewService(ctx) svc, err := service.NewService(ctx)
if err != nil { if err != nil {

View File

@ -15,7 +15,7 @@ import (
"github.com/go-git/go-git/v5/plumbing/filemode" "github.com/go-git/go-git/v5/plumbing/filemode"
"github.com/go-git/go-git/v5/plumbing/object" "github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/storage/memory" "github.com/go-git/go-git/v5/storage/memory"
flagconfig "go.unistack.org/micro-config-flag/v3" flagconfig "go.unistack.org/micro-config-flag/v4"
"go.unistack.org/micro/v4/config" "go.unistack.org/micro/v4/config"
"go.unistack.org/micro/v4/logger" "go.unistack.org/micro/v4/logger"
"golang.org/x/mod/modfile" "golang.org/x/mod/modfile"

View File

@ -1,22 +1,20 @@
package config package config
import service "go.unistack.org/cms-service"
type App struct { type App struct {
Address string `flag:"name=pkgdash.address,desc='listen address',default='127.0.0.1:8080'"` Name string
Version string
} }
type Config struct { type Config struct {
App *App App *App
Storage *service.ConfigStorage Address string `flag:"name=pkgdash.address,desc='listen address',default='127.0.0.1:8080'"`
Logger *service.ConfigLogger StorageDSN map[string]string `flag:"name=storage.dsn,desc='components storage dsn',default='all=sqlite+file:database.db'"`
Service *service.ConfigService LogLevel string `flag:"name=logger.level,desc='logging level',default='info'"`
Core *service.ConfigCore
} }
func NewConfig() *Config { func NewConfig() *Config {
return &Config{ return &Config{
Service: &service.ConfigService{ App: &App{
Name: ServiceName, Name: ServiceName,
Version: ServiceVersion, Version: ServiceVersion,
}, },

14
go.mod
View File

@ -12,9 +12,9 @@ require (
github.com/mattn/go-sqlite3 v1.14.16 github.com/mattn/go-sqlite3 v1.14.16
github.com/pkg/errors v0.9.1 github.com/pkg/errors v0.9.1
go.unistack.org/cms-service v0.0.1 go.unistack.org/cms-service v0.0.1
go.unistack.org/micro-client-http/v4 v4.0.2 go.unistack.org/micro-config-flag/v4 v4.0.2
go.unistack.org/micro-config-flag/v3 v3.8.9
go.unistack.org/micro-proto/v4 v4.0.1 go.unistack.org/micro-proto/v4 v4.0.1
go.unistack.org/micro-server-http/v3 v3.11.6
go.unistack.org/micro-server-http/v4 v4.0.9 go.unistack.org/micro-server-http/v4 v4.0.9
go.unistack.org/micro/v4 v4.0.6 go.unistack.org/micro/v4 v4.0.6
go.unistack.org/protoc-gen-go-micro/v4 v4.0.5 go.unistack.org/protoc-gen-go-micro/v4 v4.0.5
@ -23,6 +23,11 @@ require (
google.golang.org/protobuf v1.31.0 google.golang.org/protobuf v1.31.0
) )
require (
go.unistack.org/micro-client-http/v3 v3.9.3
go.unistack.org/micro/v3 v3.10.18
)
require ( require (
dario.cat/mergo v1.0.0 // indirect dario.cat/mergo v1.0.0 // indirect
github.com/Microsoft/go-winio v0.6.1 // indirect github.com/Microsoft/go-winio v0.6.1 // indirect
@ -40,7 +45,7 @@ require (
github.com/hashicorp/errwrap v1.0.0 // indirect github.com/hashicorp/errwrap v1.0.0 // indirect
github.com/hashicorp/go-multierror v1.1.0 // indirect github.com/hashicorp/go-multierror v1.1.0 // indirect
github.com/iancoleman/strcase v0.2.0 // indirect github.com/iancoleman/strcase v0.2.0 // indirect
github.com/imdario/mergo v0.3.15 // indirect github.com/imdario/mergo v0.3.16 // indirect
github.com/jackc/chunkreader/v2 v2.0.1 // indirect github.com/jackc/chunkreader/v2 v2.0.1 // indirect
github.com/jackc/pgconn v1.9.1-0.20210724152538-d89c8390a530 // indirect github.com/jackc/pgconn v1.9.1-0.20210724152538-d89c8390a530 // indirect
github.com/jackc/pgerrcode v0.0.0-20201024163028-a0d42d470451 // indirect github.com/jackc/pgerrcode v0.0.0-20201024163028-a0d42d470451 // indirect
@ -69,10 +74,9 @@ require (
go.unistack.org/micro-codec-yaml/v3 v3.10.0 // indirect go.unistack.org/micro-codec-yaml/v3 v3.10.0 // indirect
go.unistack.org/micro-config-env/v3 v3.8.5 // indirect go.unistack.org/micro-config-env/v3 v3.8.5 // indirect
go.unistack.org/micro-config-file/v3 v3.8.3 // indirect go.unistack.org/micro-config-file/v3 v3.8.3 // indirect
go.unistack.org/micro-config-flag/v3 v3.8.9 // indirect
go.unistack.org/micro-config-service/v3 v3.8.1 // indirect go.unistack.org/micro-config-service/v3 v3.8.1 // indirect
go.unistack.org/micro-proto/v3 v3.3.1 // indirect go.unistack.org/micro-proto/v3 v3.3.1 // indirect
go.unistack.org/micro-server-http/v3 v3.11.6 // indirect
go.unistack.org/micro/v3 v3.10.18 // indirect
golang.org/x/crypto v0.11.0 // indirect golang.org/x/crypto v0.11.0 // indirect
golang.org/x/lint v0.0.0-20210508222113-6edffad5e616 // indirect golang.org/x/lint v0.0.0-20210508222113-6edffad5e616 // indirect
golang.org/x/net v0.12.0 // indirect golang.org/x/net v0.12.0 // indirect

10
go.sum
View File

@ -579,8 +579,8 @@ github.com/imdario/mergo v0.3.10/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH
github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA=
github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA=
github.com/imdario/mergo v0.3.13/go.mod h1:4lJ1jqUDcsbIECGy0RUJAXNIhg+6ocWgb1ALK2O4oXg= github.com/imdario/mergo v0.3.13/go.mod h1:4lJ1jqUDcsbIECGy0RUJAXNIhg+6ocWgb1ALK2O4oXg=
github.com/imdario/mergo v0.3.15 h1:M8XP7IuFNsqUx6VPK2P9OSmsYsI/YFaGil0uD21V3dM= github.com/imdario/mergo v0.3.16 h1:wwQJbIsHYGMUyLSPrEq1CT16AhnhNJQ51+4fdHUnCl4=
github.com/imdario/mergo v0.3.15/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY= github.com/imdario/mergo v0.3.16/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/j-keck/arping v0.0.0-20160618110441-2cf9dc699c56/go.mod h1:ymszkNOg6tORTn+6F6j+Jc8TOr5osrynvN6ivFWZ2GA= github.com/j-keck/arping v0.0.0-20160618110441-2cf9dc699c56/go.mod h1:ymszkNOg6tORTn+6F6j+Jc8TOr5osrynvN6ivFWZ2GA=
github.com/jackc/chunkreader v1.0.0/go.mod h1:RT6O25fNZIuasFJRyZ4R/Y2BbhasbmZXF9QQ7T3kePo= github.com/jackc/chunkreader v1.0.0/go.mod h1:RT6O25fNZIuasFJRyZ4R/Y2BbhasbmZXF9QQ7T3kePo=
@ -1020,8 +1020,8 @@ go.unistack.org/cms-service v0.0.1 h1:XKKZqjQD3ViPGRzjadnVX94wQlKcWxompZac9YTeTj
go.unistack.org/cms-service v0.0.1/go.mod h1:3apbDEEgmoPfnPRpzgN40fCqbn/BdfXDk/Hvly8+bGk= go.unistack.org/cms-service v0.0.1/go.mod h1:3apbDEEgmoPfnPRpzgN40fCqbn/BdfXDk/Hvly8+bGk=
go.unistack.org/micro-broker-service/v3 v3.8.2 h1:K30wBLsoLO0WbD9rhPi8S8asU9pfes/M2X9tX9HLr24= go.unistack.org/micro-broker-service/v3 v3.8.2 h1:K30wBLsoLO0WbD9rhPi8S8asU9pfes/M2X9tX9HLr24=
go.unistack.org/micro-broker-service/v3 v3.8.2/go.mod h1:qTlBl4vdJSl66SFIjdjOWFWKO0BFQ2ImbwiPCti/H8M= go.unistack.org/micro-broker-service/v3 v3.8.2/go.mod h1:qTlBl4vdJSl66SFIjdjOWFWKO0BFQ2ImbwiPCti/H8M=
go.unistack.org/micro-client-http/v4 v4.0.2 h1:0xsm2RCRWMfb1moeXQQ220uz52XE0R/PZvM9was/4lM= go.unistack.org/micro-client-http/v3 v3.9.3 h1:5AicVsSwzAbIa1mpi99g5JhhDakUkgMV6e4F/Xyu3jI=
go.unistack.org/micro-client-http/v4 v4.0.2/go.mod h1:Z9QT/upeqrp/rXVkL0lk6AzrkTdes0W3QlFlZ+ytkqM= go.unistack.org/micro-client-http/v3 v3.9.3/go.mod h1:3zB0iVaYhG/xi0r/YvyTE422dOOOx1PAaiWlD2GSBlM=
go.unistack.org/micro-codec-yaml/v3 v3.10.0 h1:cnNiWQZ3F+jsCX9DhEHBdIw8CjBItxb+TrKGGdlQ8F8= go.unistack.org/micro-codec-yaml/v3 v3.10.0 h1:cnNiWQZ3F+jsCX9DhEHBdIw8CjBItxb+TrKGGdlQ8F8=
go.unistack.org/micro-codec-yaml/v3 v3.10.0/go.mod h1:UzwC3QZZ6+PgKSudlGZNLkugXzOFkp3sxhs/CctEwBY= go.unistack.org/micro-codec-yaml/v3 v3.10.0/go.mod h1:UzwC3QZZ6+PgKSudlGZNLkugXzOFkp3sxhs/CctEwBY=
go.unistack.org/micro-config-env/v3 v3.8.5 h1:k0BKpQflJ9mutzK//VcYw4XAKlKHTvg2GtkHTrEjbko= go.unistack.org/micro-config-env/v3 v3.8.5 h1:k0BKpQflJ9mutzK//VcYw4XAKlKHTvg2GtkHTrEjbko=
@ -1030,6 +1030,8 @@ go.unistack.org/micro-config-file/v3 v3.8.3 h1:yoAyDtmWutlUkVgFUtc7JhwCX7H/2Jz0n
go.unistack.org/micro-config-file/v3 v3.8.3/go.mod h1:dl+MQ27/P41+hINmSrZFltDSDYP1y2LItIDYb2jHFog= go.unistack.org/micro-config-file/v3 v3.8.3/go.mod h1:dl+MQ27/P41+hINmSrZFltDSDYP1y2LItIDYb2jHFog=
go.unistack.org/micro-config-flag/v3 v3.8.9 h1:I4eoJVV28CpxQvQ63TJ1fqK5JcV1gHmOZPveT2Vl5Iw= go.unistack.org/micro-config-flag/v3 v3.8.9 h1:I4eoJVV28CpxQvQ63TJ1fqK5JcV1gHmOZPveT2Vl5Iw=
go.unistack.org/micro-config-flag/v3 v3.8.9/go.mod h1:eWI90dcZh5AOhkd83fF0KY17ea/DZPebkJ8K61yky+8= go.unistack.org/micro-config-flag/v3 v3.8.9/go.mod h1:eWI90dcZh5AOhkd83fF0KY17ea/DZPebkJ8K61yky+8=
go.unistack.org/micro-config-flag/v4 v4.0.2 h1:qoDpT/H8a8TYZS9ucoNC0bLhNdp+UFlhnRWOuqIKAyo=
go.unistack.org/micro-config-flag/v4 v4.0.2/go.mod h1:s0AYvz8rRtMHG2tkXoSmF8xFuHG12x3v1NERdMHDdiQ=
go.unistack.org/micro-config-service/v3 v3.8.1 h1:Q+RPWCb88VGz5+EQUx45Xeysf+Mon9Q2IvqCF3e8LZM= go.unistack.org/micro-config-service/v3 v3.8.1 h1:Q+RPWCb88VGz5+EQUx45Xeysf+Mon9Q2IvqCF3e8LZM=
go.unistack.org/micro-config-service/v3 v3.8.1/go.mod h1:KdZJEuYwninyT04ysFkgEQa3OaMRa0kSQVPQHlumQoA= go.unistack.org/micro-config-service/v3 v3.8.1/go.mod h1:KdZJEuYwninyT04ysFkgEQa3OaMRa0kSQVPQHlumQoA=
go.unistack.org/micro-proto/v3 v3.3.1 h1:nQ0MtWvP2G3QrpOgawVOPhpZZYkq6umTGDqs8FxJYIo= go.unistack.org/micro-proto/v3 v3.3.1 h1:nQ0MtWvP2G3QrpOgawVOPhpZZYkq6umTGDqs8FxJYIo=

View File

@ -1,26 +0,0 @@
package encoders
import (
"encoding/json"
"net/http"
pb "go.unistack.org/unistack-org/pkgdash/proto"
"github.com/pkg/errors"
)
type JSON struct{}
func (*JSON) Success(rw http.ResponseWriter, response interface{}) error {
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
rw.WriteHeader(http.StatusOK)
return errors.WithStack(json.NewEncoder(rw).Encode(response))
}
func (*JSON) Error(rw http.ResponseWriter, err *pb.Error, status int) error {
rw.Header().Set("Content-Type", "application/problem+json; charset=utf-8")
rw.WriteHeader(status)
return errors.WithStack(json.NewEncoder(rw).Encode(&pb.ErrorRsp{Error: err}))
}

View File

@ -1,51 +0,0 @@
package encoders
import (
"github.com/pkg/errors"
pb "go.unistack.org/unistack-org/pkgdash/proto"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"io"
"net/http"
)
var ErrWrongResponseType = errors.New("JSONProto: wrong response message type")
type JSONProto struct {
m protojson.MarshalOptions
}
func NewJSONProto() *JSONProto {
return &JSONProto{m: protojson.MarshalOptions{
EmitUnpopulated: true,
UseProtoNames: false,
}}
}
func (e *JSONProto) Success(rw http.ResponseWriter, response interface{}) error {
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
rw.WriteHeader(http.StatusOK)
if v, ok := response.(proto.Message); ok {
return errors.WithStack(e.Fmarshal(rw, v))
}
return ErrWrongResponseType
}
func (e *JSONProto) Error(rw http.ResponseWriter, err *pb.Error, status int) error {
rw.Header().Set("Content-Type", "application/problem+json; charset=utf-8")
rw.WriteHeader(status)
return errors.WithStack(e.Fmarshal(rw, &pb.ErrorRsp{Error: err}))
}
func (e *JSONProto) Fmarshal(w io.Writer, m proto.Message) error {
b, err := e.m.Marshal(m)
if len(b) > 0 {
if _, err = w.Write(b); err != nil {
return err
}
}
return err
}

View File

@ -1,6 +1,16 @@
package handler package handler
import "github.com/pkg/errors" import (
"github.com/google/uuid"
"github.com/pkg/errors"
pb "go.unistack.org/unistack-org/pkgdash/proto"
)
const (
badRequest = `Bad Requet`
internalError = `Internal Error`
notFound = `Source Not Found`
)
type UnmarshalError struct { type UnmarshalError struct {
err error err error
@ -18,16 +28,15 @@ func NewUnmarshalError(err error) error {
return errors.WithStack(&UnmarshalError{err: err}) return errors.WithStack(&UnmarshalError{err: err})
} }
type InternalError struct { func NewInternalError(err error) *pb.ErrorRsp {
Err error return &pb.ErrorRsp{
} Error: &pb.Error{
Code: internalErrorCode,
func (e *InternalError) Error() string { Title: internalError,
return e.Err.Error() Uuid: uuid.New().String(),
} Details: err.Error(),
},
func NewInternalError(err error) error { }
return errors.WithStack(&InternalError{Err: err})
} }
type ParametersMissingError struct { type ParametersMissingError struct {
@ -42,26 +51,24 @@ func NewParametersMissingError(err error) error {
return errors.WithStack(&ParametersMissingError{Err: err}) return errors.WithStack(&ParametersMissingError{Err: err})
} }
type NotFoundError struct { func NewNotFoundError(err error) *pb.ErrorRsp {
Err error return &pb.ErrorRsp{
Error: &pb.Error{
Code: notFoundErrorCode,
Title: notFound,
Uuid: uuid.New().String(),
Details: err.Error(),
},
}
} }
func (e *NotFoundError) Error() string { func NewValidationError(err error) *pb.ErrorRsp {
return e.Err.Error() return &pb.ErrorRsp{
} Error: &pb.Error{
Code: badRequestCode,
func NewNotFoundError(err error) error { Title: badRequest,
return errors.WithStack(&NotFoundError{Err: err}) Uuid: uuid.New().String(),
} Details: err.Error(),
},
type ValidationError struct { }
Err error
}
func (e *ValidationError) Error() string {
return e.Err.Error()
}
func NewValidationError(err error) error {
return errors.WithStack(&ValidationError{Err: err})
} }

View File

@ -2,20 +2,18 @@ package handler
import ( import (
"context" "context"
"encoding/json" "database/sql"
"io" "errors"
"net/http"
"net/url"
cmsstorage "go.unistack.org/cms-service/storage" cmsstorage "go.unistack.org/cms-service/storage"
httpsrv "go.unistack.org/micro-server-http/v4"
"go.unistack.org/micro/v4" "go.unistack.org/micro/v4"
"go.unistack.org/micro/v4/errors"
"go.unistack.org/unistack-org/pkgdash/config" "go.unistack.org/unistack-org/pkgdash/config"
pb "go.unistack.org/unistack-org/pkgdash/proto" pb "go.unistack.org/unistack-org/pkgdash/proto"
cligit "go.unistack.org/unistack-org/pkgdash/service/client_git" cligit "go.unistack.org/unistack-org/pkgdash/service/client_git"
"go.unistack.org/unistack-org/pkgdash/storage" "go.unistack.org/unistack-org/pkgdash/storage"
"google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/emptypb"
"net/http"
) )
type Handler struct { type Handler struct {
@ -30,119 +28,80 @@ type Handler struct {
chanUrl chan *pb.AddPackageReq chanUrl chan *pb.AddPackageReq
} }
func (h *Handler) ListPackage(w http.ResponseWriter, r *http.Request) { func (h *Handler) ListPackage(ctx context.Context, _ *emptypb.Empty, rsp *pb.ListPackageRsp) error {
ctx := r.Context()
logger := h.svc.Logger() logger := h.svc.Logger()
logger.Debug(ctx, "Start getListPackage") logger.Debug(ctx, "Start getListPackage")
dbRsp, err := h.store.ListPackage(ctx) dbRsp, err := h.store.ListPackage(ctx)
if err != nil { if err != nil {
logger.Errorf(ctx, "error db response: %v", err) logger.Errorf(ctx, "error db response: %v", err)
h.writer.Response(ctx, w, err) httpsrv.SetRspCode(ctx, http.StatusInternalServerError)
return return httpsrv.SetError(NewInternalError(err))
} }
rsp := new(pb.ListPackageRsp) //rsp = new(pb.ListPackageRsp)
rsp.Packages = dbRsp.Decode() rsp.Packages = dbRsp.Decode()
logger.Debug(ctx, "Success finish getListPackage") logger.Debug(ctx, "Success finish getListPackage")
h.writer.Response(ctx, w, rsp) return nil
} }
func (h *Handler) UpdatePackage(w http.ResponseWriter, r *http.Request) { func (h *Handler) UpdatePackage(ctx context.Context, req *pb.UpdatePackageReq, rsp *pb.UpdatePackageRsp) error {
ctx := r.Context()
logger := h.svc.Logger() logger := h.svc.Logger()
logger.Debug(ctx, "Start UpdatePackage") logger.Debug(ctx, "Start UpdatePackage")
defer r.Body.Close() if err := req.Validate(); err != nil {
all, err := io.ReadAll(r.Body)
if err != nil {
logger.Error(ctx, err) logger.Error(ctx, err)
h.writer.Response(ctx, w, NewInternalError(err)) httpsrv.SetRspCode(ctx, http.StatusBadRequest)
return return httpsrv.SetError(NewValidationError(err))
} }
req := new(pb.UpdatePackageReq) if err := h.store.UpdatePackage(ctx, req); err != nil {
if err = h.Unmarshal(all, req); err != nil {
logger.Error(ctx, err) logger.Error(ctx, err)
h.writer.Response(ctx, w, NewUnmarshalError(err)) httpsrv.SetRspCode(ctx, http.StatusInternalServerError)
return return httpsrv.SetError(NewInternalError(err))
} }
if err = req.Validate(); err != nil { rsp.Id = req.Id
logger.Error(ctx, err)
h.writer.Response(ctx, w, NewValidationError(err))
return
}
if err = h.store.UpdatePackage(ctx, req); err != nil {
logger.Error(ctx, err)
h.writer.Response(ctx, w, NewInternalError(err))
return
}
logger.Debug(ctx, "Success finish UpdatePackage") logger.Debug(ctx, "Success finish UpdatePackage")
return nil
} }
func (h *Handler) AddComment(w http.ResponseWriter, r *http.Request) { func (h *Handler) AddComment(ctx context.Context, req *pb.AddCommentReq, rsp *pb.AddCommentRsp) error {
ctx := r.Context()
logger := h.svc.Logger() logger := h.svc.Logger()
logger.Debug(ctx, "Start AddComment") logger.Debug(ctx, "Start AddComment")
defer r.Body.Close() err := req.Validate()
all, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
logger.Error(ctx, err) logger.Error(ctx, err)
h.writer.Response(ctx, w, NewInternalError(err)) httpsrv.SetRspCode(ctx, http.StatusBadRequest)
return return httpsrv.SetError(NewValidationError(err))
} }
req := new(pb.AddCommentReq) if rsp.Id, err = h.store.AddComment(ctx, req); err != nil {
if err = h.Unmarshal(all, req); err != nil {
logger.Error(ctx, err) logger.Error(ctx, err)
h.writer.Response(ctx, w, NewUnmarshalError(err)) if errors.Is(err, sql.ErrNoRows) {
return httpsrv.SetRspCode(ctx, http.StatusNotFound)
} return httpsrv.SetError(NewNotFoundError(err))
}
if err = req.Validate(); err != nil { httpsrv.SetRspCode(ctx, http.StatusInternalServerError)
logger.Error(ctx, err) return httpsrv.SetError(NewInternalError(err))
h.writer.Response(ctx, w, NewValidationError(err))
return
}
if err = h.store.AddComment(ctx, req); err != nil {
logger.Error(ctx, err)
h.writer.Response(ctx, w, NewInternalError(err))
return
} }
logger.Debug(ctx, "Success finish addComment") logger.Debug(ctx, "Success finish addComment")
return nil
} }
func (h *Handler) AddPackage(w http.ResponseWriter, r *http.Request) { func (h *Handler) AddPackage(ctx context.Context, req *pb.AddPackageReq, rsp *pb.AddPackageRsp) error {
ctx := r.Context()
logger := h.svc.Logger() logger := h.svc.Logger()
logger.Debug(ctx, "Start AddPackage") logger.Debug(ctx, "Start AddPackage")
defer r.Body.Close() err := req.Validate()
all, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
logger.Error(ctx, err) logger.Error(ctx, err)
h.writer.Response(ctx, w, NewInternalError(err)) httpsrv.SetRspCode(ctx, http.StatusBadRequest)
return return httpsrv.SetError(NewValidationError(err))
}
req := new(pb.AddPackageReq)
if err = h.Unmarshal(all, req); err != nil {
logger.Error(ctx, err)
h.writer.Response(ctx, w, NewUnmarshalError(err))
return
}
if err = req.Validate(); err != nil {
logger.Error(ctx, err)
h.writer.Response(ctx, w, NewValidationError(err))
return
} }
if h.git.IsClose() { if h.git.IsClose() {
@ -151,69 +110,40 @@ func (h *Handler) AddPackage(w http.ResponseWriter, r *http.Request) {
h.chanUrl <- req h.chanUrl <- req
} }
rsp.Status = "Sent"
logger.Debug(ctx, "Success finish addPackage") logger.Debug(ctx, "Success finish addPackage")
return nil
} }
func (h *Handler) GetModule(w http.ResponseWriter, r *http.Request) { func (h *Handler) GetModule(ctx context.Context, req *pb.GetModuleReq, rsp *pb.GetModuleRsp) error {
ctx := r.Context()
logger := h.svc.Logger() logger := h.svc.Logger()
logger.Debug(ctx, "Start GetModule") logger.Debug(ctx, "Start GetModule")
req := new(pb.GetModuleReq)
if err := URLValuesToProto(r.URL.Query(), req); err != nil {
logger.Errorf(ctx, "Required parameter missing: %v", err)
h.writer.Response(ctx, w, err)
return
}
modules, err := h.store.GetModule(ctx, req) modules, err := h.store.GetModule(ctx, req)
if err != nil { if err != nil {
logger.Error(ctx, err) logger.Error(ctx, err)
h.writer.Response(ctx, w, NewInternalError(err)) httpsrv.SetRspCode(ctx, http.StatusInternalServerError)
return return httpsrv.SetError(NewInternalError(err))
} }
rsp := &pb.GetModuleRsp{Modules: modules.Decode()} rsp.Modules = modules.Decode()
h.writer.Response(ctx, w, rsp)
logger.Debug(ctx, "Success finish getModule") logger.Debug(ctx, "Success finish getModule")
}
func URLValuesToProto(vals url.Values, msg proto.Message) error {
params := make(map[string]interface{})
var err error
for k, v := range vals {
if len(v) == 0 {
continue
}
switch k {
case "id[]":
params[k] = v
default:
params[k] = v[0]
}
}
b, err := json.Marshal(params)
if err != nil {
return NewUnmarshalError(err)
}
if err = protojson.Unmarshal(b, msg); err != nil {
return NewUnmarshalError(err)
}
return nil return nil
} }
func NewHandler(svc micro.Service, w writer, client cligit.Client) *Handler { func NewHandler(svc micro.Service, client cligit.Client) *Handler {
h := &Handler{ h := &Handler{
svc: svc, svc: svc,
writer: w, git: client,
git: client,
} }
h.EmitUnpopulated = true h.EmitUnpopulated = true
h.UseProtoNames = false h.UseProtoNames = false
return h return h
} }
// TODO add conn db
func (h *Handler) Init(ctx context.Context) error { func (h *Handler) Init(ctx context.Context) error {
store := cmsstorage.InterfaceFromContext(h.svc.Options().Context) store := cmsstorage.InterfaceFromContext(h.svc.Options().Context)
if store == nil { if store == nil {

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -2,15 +2,15 @@ syntax = "proto3";
package pkgdash; package pkgdash;
import "api/annotations.proto";
import "google/protobuf/wrappers.proto";
import "openapiv3/annotations.proto";
import "validate/validate.proto";
option go_package = "go.unistack.org/unistack-org/pkgdash/proto;pkgdashpb"; option go_package = "go.unistack.org/unistack-org/pkgdash/proto;pkgdashpb";
import "api/annotations.proto";
import "openapiv3/annotations.proto";
import "validate/validate.proto";
import "google/protobuf/empty.proto";
service PkgdashService { service PkgdashService {
rpc ListPackage(ListPackageReq) returns (ListPackageRsp) { rpc ListPackage(google.protobuf.Empty) returns (ListPackageRsp) {
option (micro.openapiv3.openapiv3_operation) = { option (micro.openapiv3.openapiv3_operation) = {
operation_id: "ListPackage"; operation_id: "ListPackage";
responses: { responses: {
@ -19,8 +19,10 @@ service PkgdashService {
}; };
}; };
}; };
option (micro.api.http) = {get: "/v1/packages"}; option (micro.api.http) = {
} get: "/v1/packages";
};
};
rpc UpdatePackage(UpdatePackageReq) returns (UpdatePackageRsp) { rpc UpdatePackage(UpdatePackageReq) returns (UpdatePackageRsp) {
option (micro.openapiv3.openapiv3_operation) = { option (micro.openapiv3.openapiv3_operation) = {
operation_id: "UpdateInfo"; operation_id: "UpdateInfo";
@ -34,7 +36,7 @@ service PkgdashService {
post: "/v1/package/{id}"; post: "/v1/package/{id}";
body: "*"; body: "*";
}; };
} };
rpc AddComment(AddCommentReq) returns (AddCommentRsp) { rpc AddComment(AddCommentReq) returns (AddCommentRsp) {
option (micro.openapiv3.openapiv3_operation) = { option (micro.openapiv3.openapiv3_operation) = {
operation_id: "AddComment"; operation_id: "AddComment";
@ -48,7 +50,7 @@ service PkgdashService {
post: "/v1/package/{pkg}/comment"; post: "/v1/package/{pkg}/comment";
body: "*"; body: "*";
}; };
} };
rpc AddPackage(AddPackageReq) returns (AddPackageRsp) { rpc AddPackage(AddPackageReq) returns (AddPackageRsp) {
option (micro.openapiv3.openapiv3_operation) = { option (micro.openapiv3.openapiv3_operation) = {
operation_id: "AddPackage"; operation_id: "AddPackage";
@ -62,7 +64,7 @@ service PkgdashService {
post: "/v1/package"; post: "/v1/package";
body: "*"; body: "*";
}; };
} };
rpc GetModule(GetModuleReq) returns (GetModuleRsp) { rpc GetModule(GetModuleReq) returns (GetModuleRsp) {
option (micro.openapiv3.openapiv3_operation) = { option (micro.openapiv3.openapiv3_operation) = {
operation_id: "GetModule"; operation_id: "GetModule";
@ -72,65 +74,11 @@ service PkgdashService {
}; };
}; };
}; };
option (micro.api.http) = {get: "/v1/module"}; option (micro.api.http) = {
} get: "/v1/module";
} };
};
message ListPackageReq {} };
message ListPackageRsp {
repeated Package packages = 1;
}
message UpdatePackageReq {
google.protobuf.UInt64Value id = 1 [(validate.rules).message.required = true];
google.protobuf.StringValue name = 2 [(validate.rules).message.required = true];
google.protobuf.StringValue url = 3 [(validate.rules).message.required = true];
repeated uint64 modules = 4;
repeated uint64 issues = 5;
}
message UpdatePackageRsp {
uint64 id = 1 [(validate.rules).uint64.gt = 0];
}
message CommentReq {
uint64 pkg = 1 [(validate.rules).uint64.gt = 0];
string text = 2;
}
message AddCommentReq {
google.protobuf.UInt64Value idPackage = 1 [(validate.rules).message.required = true];
string text = 2;
}
message AddCommentRsp {
uint64 id = 1 [(validate.rules).uint64.gt = 0];
}
message AddPackageReq {
google.protobuf.StringValue name = 1 [(validate.rules).message.required = true];
google.protobuf.StringValue url = 2 [(validate.rules).message.required = true];
repeated uint64 modules = 3;
}
message AddPackageRsp {}
message GetModuleReq {
repeated uint64 id = 1;
}
message GetModuleRsp {
repeated Module modules = 1;
}
message Package {
uint64 id = 1 [(validate.rules).uint64.gt = 0];
string name = 2 [(validate.rules).string.min_len = 1];
string url = 3 [(validate.rules).string.min_len = 1];
repeated uint64 modules = 4;
repeated uint64 issues = 5;
repeated uint64 comments = 6;
}
message ErrorRsp { message ErrorRsp {
Error error = 1 [json_name = "error"]; Error error = 1 [json_name = "error"];
@ -143,6 +91,15 @@ message Error {
string details = 4 [json_name = "details"]; string details = 4 [json_name = "details"];
} }
message Package {
uint64 id = 1 [(validate.rules).uint64.gt = 0];
string name = 2 [(validate.rules).string.min_len = 1];
string url = 3 [(validate.rules).string.min_len = 1];
repeated uint64 modules = 4;
repeated uint64 issues = 5;
repeated uint64 comments = 6;
};
message Module { message Module {
uint64 id = 1 [(validate.rules).uint64.gt = 0]; uint64 id = 1 [(validate.rules).uint64.gt = 0];
string name = 2 [(validate.rules).string.min_len = 1]; string name = 2 [(validate.rules).string.min_len = 1];
@ -166,3 +123,50 @@ message Comment {
uint64 created = 4 [(validate.rules).uint64.gt = 0]; uint64 created = 4 [(validate.rules).uint64.gt = 0];
uint64 updated = 5 [(validate.rules).uint64.gt = 0]; uint64 updated = 5 [(validate.rules).uint64.gt = 0];
} }
message ListPackageReq {}
message ListPackageRsp{
repeated Package packages = 1;
}
message UpdatePackageReq {
uint64 id = 1 [(validate.rules).uint64.gt = 0];
string name = 2 [(validate.rules).string.min_len = 1];
string url = 3 [(validate.rules).string.min_len = 1];
repeated uint64 modules = 4 ;
repeated uint64 issues = 5 ;
}
message UpdatePackageRsp {
uint64 id = 1 [(validate.rules).uint64.gt = 0];
}
message CommentReq {
uint64 pkg = 1 [(validate.rules).uint64.gt = 0];
string text = 2;
}
message AddCommentReq {
uint64 idPackage = 1 [(validate.rules).uint64.gt = 0];
string text = 2;
}
message AddCommentRsp {
uint64 id = 1 [(validate.rules).uint64.gt = 0];
}
message AddPackageReq {
string name = 1 [(validate.rules).string.min_len = 1];
string url = 2 [(validate.rules).string.min_len = 1];
repeated uint64 modules = 3;
}
message AddPackageRsp{
string status = 1 [(validate.rules).string.min_len = 1];
}
message GetModuleReq {
repeated uint64 id = 1 ;
}
message GetModuleRsp {
repeated Module modules = 1 ;
}

View File

@ -1,6 +1,6 @@
// Code generated by protoc-gen-go-micro. DO NOT EDIT. // Code generated by protoc-gen-go-micro. DO NOT EDIT.
// versions: // versions:
// - protoc-gen-go-micro v4.0.2 // - protoc-gen-go-micro v3.10.3
// - protoc v4.23.4 // - protoc v4.23.4
// source: pkgdash.proto // source: pkgdash.proto
@ -8,24 +8,64 @@ package pkgdashpb
import ( import (
context "context" context "context"
_ "go.unistack.org/micro/v4/client" v3 "go.unistack.org/micro-server-http/v3"
options "go.unistack.org/micro/v4/options" client "go.unistack.org/micro/v3/client"
emptypb "google.golang.org/protobuf/types/known/emptypb"
) )
var ( var (
PkgdashServiceName = "PkgdashService" PkgdashServiceName = "PkgdashService"
) )
var (
PkgdashServiceServerEndpoints = []v3.EndpointMetadata{
{
Name: "PkgdashService.ListPackage",
Path: "/v1/packages",
Method: "GET",
Body: "",
Stream: false,
},
{
Name: "PkgdashService.UpdatePackage",
Path: "/v1/package/{id}",
Method: "POST",
Body: "*",
Stream: false,
},
{
Name: "PkgdashService.AddComment",
Path: "/v1/package/{pkg}/comment",
Method: "POST",
Body: "*",
Stream: false,
},
{
Name: "PkgdashService.AddPackage",
Path: "/v1/package",
Method: "POST",
Body: "*",
Stream: false,
},
{
Name: "PkgdashService.GetModule",
Path: "/v1/module",
Method: "GET",
Body: "",
Stream: false,
},
}
)
type PkgdashServiceClient interface { type PkgdashServiceClient interface {
ListPackage(ctx context.Context, req *ListPackageReq, opts ...options.Option) (*ListPackageRsp, error) ListPackage(ctx context.Context, req *emptypb.Empty, opts ...client.CallOption) (*ListPackageRsp, error)
UpdatePackage(ctx context.Context, req *UpdatePackageReq, opts ...options.Option) (*UpdatePackageRsp, error) UpdatePackage(ctx context.Context, req *UpdatePackageReq, opts ...client.CallOption) (*UpdatePackageRsp, error)
AddComment(ctx context.Context, req *AddCommentReq, opts ...options.Option) (*AddCommentRsp, error) AddComment(ctx context.Context, req *AddCommentReq, opts ...client.CallOption) (*AddCommentRsp, error)
AddPackage(ctx context.Context, req *AddPackageReq, opts ...options.Option) (*AddPackageRsp, error) AddPackage(ctx context.Context, req *AddPackageReq, opts ...client.CallOption) (*AddPackageRsp, error)
GetModule(ctx context.Context, req *GetModuleReq, opts ...options.Option) (*GetModuleRsp, error) GetModule(ctx context.Context, req *GetModuleReq, opts ...client.CallOption) (*GetModuleRsp, error)
} }
type PkgdashServiceServer interface { type PkgdashServiceServer interface {
ListPackage(ctx context.Context, req *ListPackageReq, rsp *ListPackageRsp) error ListPackage(ctx context.Context, req *emptypb.Empty, rsp *ListPackageRsp) error
UpdatePackage(ctx context.Context, req *UpdatePackageReq, rsp *UpdatePackageRsp) error UpdatePackage(ctx context.Context, req *UpdatePackageReq, rsp *UpdatePackageRsp) error
AddComment(ctx context.Context, req *AddCommentReq, rsp *AddCommentRsp) error AddComment(ctx context.Context, req *AddCommentReq, rsp *AddCommentRsp) error
AddPackage(ctx context.Context, req *AddPackageReq, rsp *AddPackageRsp) error AddPackage(ctx context.Context, req *AddPackageReq, rsp *AddPackageRsp) error

View File

@ -1,59 +1,19 @@
// Code generated by protoc-gen-go-micro. DO NOT EDIT. // Code generated by protoc-gen-go-micro. DO NOT EDIT.
// protoc-gen-go-micro version: v4.0.2 // protoc-gen-go-micro version: v3.10.3
// source: pkgdash.proto // source: pkgdash.proto
package pkgdashpb package pkgdashpb
import ( import (
context "context" context "context"
v41 "go.unistack.org/micro-client-http/v4" v3 "go.unistack.org/micro-client-http/v3"
v4 "go.unistack.org/micro-server-http/v4" v31 "go.unistack.org/micro-server-http/v3"
client "go.unistack.org/micro/v4/client" client "go.unistack.org/micro/v3/client"
options "go.unistack.org/micro/v4/options" server "go.unistack.org/micro/v3/server"
server "go.unistack.org/micro/v4/server" emptypb "google.golang.org/protobuf/types/known/emptypb"
http "net/http" http "net/http"
) )
var (
PkgdashServiceServerEndpoints = []v4.EndpointMetadata{
{
Name: "PkgdashService.ListPackage",
Path: "/v1/packages",
Method: "GET",
Body: "",
Stream: false,
},
{
Name: "PkgdashService.UpdatePackage",
Path: "/v1/package/{id}",
Method: "POST",
Body: "*",
Stream: false,
},
{
Name: "PkgdashService.AddComment",
Path: "/v1/package/{pkg}/comment",
Method: "POST",
Body: "*",
Stream: false,
},
{
Name: "PkgdashService.AddPackage",
Path: "/v1/package",
Method: "POST",
Body: "*",
Stream: false,
},
{
Name: "PkgdashService.GetModule",
Path: "/v1/module",
Method: "GET",
Body: "",
Stream: false,
},
}
)
type pkgdashServiceClient struct { type pkgdashServiceClient struct {
c client.Client c client.Client
name string name string
@ -63,15 +23,15 @@ func NewPkgdashServiceClient(name string, c client.Client) PkgdashServiceClient
return &pkgdashServiceClient{c: c, name: name} return &pkgdashServiceClient{c: c, name: name}
} }
func (c *pkgdashServiceClient) ListPackage(ctx context.Context, req *ListPackageReq, opts ...options.Option) (*ListPackageRsp, error) { func (c *pkgdashServiceClient) ListPackage(ctx context.Context, req *emptypb.Empty, opts ...client.CallOption) (*ListPackageRsp, error) {
errmap := make(map[string]interface{}, 1) errmap := make(map[string]interface{}, 1)
errmap["default"] = &ErrorRsp{} errmap["default"] = &ErrorRsp{}
opts = append(opts, opts = append(opts,
v41.ErrorMap(errmap), v3.ErrorMap(errmap),
) )
opts = append(opts, opts = append(opts,
v41.Method(http.MethodGet), v3.Method(http.MethodGet),
v41.Path("/v1/packages"), v3.Path("/v1/packages"),
) )
rsp := &ListPackageRsp{} rsp := &ListPackageRsp{}
err := c.c.Call(ctx, c.c.NewRequest(c.name, "PkgdashService.ListPackage", req), rsp, opts...) err := c.c.Call(ctx, c.c.NewRequest(c.name, "PkgdashService.ListPackage", req), rsp, opts...)
@ -81,16 +41,16 @@ func (c *pkgdashServiceClient) ListPackage(ctx context.Context, req *ListPackage
return rsp, nil return rsp, nil
} }
func (c *pkgdashServiceClient) UpdatePackage(ctx context.Context, req *UpdatePackageReq, opts ...options.Option) (*UpdatePackageRsp, error) { func (c *pkgdashServiceClient) UpdatePackage(ctx context.Context, req *UpdatePackageReq, opts ...client.CallOption) (*UpdatePackageRsp, error) {
errmap := make(map[string]interface{}, 1) errmap := make(map[string]interface{}, 1)
errmap["default"] = &ErrorRsp{} errmap["default"] = &ErrorRsp{}
opts = append(opts, opts = append(opts,
v41.ErrorMap(errmap), v3.ErrorMap(errmap),
) )
opts = append(opts, opts = append(opts,
v41.Method(http.MethodPost), v3.Method(http.MethodPost),
v41.Path("/v1/package/{id}"), v3.Path("/v1/package/{id}"),
v41.Body("*"), v3.Body("*"),
) )
rsp := &UpdatePackageRsp{} rsp := &UpdatePackageRsp{}
err := c.c.Call(ctx, c.c.NewRequest(c.name, "PkgdashService.UpdatePackage", req), rsp, opts...) err := c.c.Call(ctx, c.c.NewRequest(c.name, "PkgdashService.UpdatePackage", req), rsp, opts...)
@ -100,16 +60,16 @@ func (c *pkgdashServiceClient) UpdatePackage(ctx context.Context, req *UpdatePac
return rsp, nil return rsp, nil
} }
func (c *pkgdashServiceClient) AddComment(ctx context.Context, req *AddCommentReq, opts ...options.Option) (*AddCommentRsp, error) { func (c *pkgdashServiceClient) AddComment(ctx context.Context, req *AddCommentReq, opts ...client.CallOption) (*AddCommentRsp, error) {
errmap := make(map[string]interface{}, 1) errmap := make(map[string]interface{}, 1)
errmap["default"] = &ErrorRsp{} errmap["default"] = &ErrorRsp{}
opts = append(opts, opts = append(opts,
v41.ErrorMap(errmap), v3.ErrorMap(errmap),
) )
opts = append(opts, opts = append(opts,
v41.Method(http.MethodPost), v3.Method(http.MethodPost),
v41.Path("/v1/package/{pkg}/comment"), v3.Path("/v1/package/{pkg}/comment"),
v41.Body("*"), v3.Body("*"),
) )
rsp := &AddCommentRsp{} rsp := &AddCommentRsp{}
err := c.c.Call(ctx, c.c.NewRequest(c.name, "PkgdashService.AddComment", req), rsp, opts...) err := c.c.Call(ctx, c.c.NewRequest(c.name, "PkgdashService.AddComment", req), rsp, opts...)
@ -119,16 +79,16 @@ func (c *pkgdashServiceClient) AddComment(ctx context.Context, req *AddCommentRe
return rsp, nil return rsp, nil
} }
func (c *pkgdashServiceClient) AddPackage(ctx context.Context, req *AddPackageReq, opts ...options.Option) (*AddPackageRsp, error) { func (c *pkgdashServiceClient) AddPackage(ctx context.Context, req *AddPackageReq, opts ...client.CallOption) (*AddPackageRsp, error) {
errmap := make(map[string]interface{}, 1) errmap := make(map[string]interface{}, 1)
errmap["default"] = &ErrorRsp{} errmap["default"] = &ErrorRsp{}
opts = append(opts, opts = append(opts,
v41.ErrorMap(errmap), v3.ErrorMap(errmap),
) )
opts = append(opts, opts = append(opts,
v41.Method(http.MethodPost), v3.Method(http.MethodPost),
v41.Path("/v1/package"), v3.Path("/v1/package"),
v41.Body("*"), v3.Body("*"),
) )
rsp := &AddPackageRsp{} rsp := &AddPackageRsp{}
err := c.c.Call(ctx, c.c.NewRequest(c.name, "PkgdashService.AddPackage", req), rsp, opts...) err := c.c.Call(ctx, c.c.NewRequest(c.name, "PkgdashService.AddPackage", req), rsp, opts...)
@ -138,15 +98,15 @@ func (c *pkgdashServiceClient) AddPackage(ctx context.Context, req *AddPackageRe
return rsp, nil return rsp, nil
} }
func (c *pkgdashServiceClient) GetModule(ctx context.Context, req *GetModuleReq, opts ...options.Option) (*GetModuleRsp, error) { func (c *pkgdashServiceClient) GetModule(ctx context.Context, req *GetModuleReq, opts ...client.CallOption) (*GetModuleRsp, error) {
errmap := make(map[string]interface{}, 1) errmap := make(map[string]interface{}, 1)
errmap["default"] = &ErrorRsp{} errmap["default"] = &ErrorRsp{}
opts = append(opts, opts = append(opts,
v41.ErrorMap(errmap), v3.ErrorMap(errmap),
) )
opts = append(opts, opts = append(opts,
v41.Method(http.MethodGet), v3.Method(http.MethodGet),
v41.Path("/v1/module"), v3.Path("/v1/module"),
) )
rsp := &GetModuleRsp{} rsp := &GetModuleRsp{}
err := c.c.Call(ctx, c.c.NewRequest(c.name, "PkgdashService.GetModule", req), rsp, opts...) err := c.c.Call(ctx, c.c.NewRequest(c.name, "PkgdashService.GetModule", req), rsp, opts...)
@ -160,7 +120,7 @@ type pkgdashServiceServer struct {
PkgdashServiceServer PkgdashServiceServer
} }
func (h *pkgdashServiceServer) ListPackage(ctx context.Context, req *ListPackageReq, rsp *ListPackageRsp) error { func (h *pkgdashServiceServer) ListPackage(ctx context.Context, req *emptypb.Empty, rsp *ListPackageRsp) error {
return h.PkgdashServiceServer.ListPackage(ctx, req, rsp) return h.PkgdashServiceServer.ListPackage(ctx, req, rsp)
} }
@ -180,9 +140,9 @@ func (h *pkgdashServiceServer) GetModule(ctx context.Context, req *GetModuleReq,
return h.PkgdashServiceServer.GetModule(ctx, req, rsp) return h.PkgdashServiceServer.GetModule(ctx, req, rsp)
} }
func RegisterPkgdashServiceServer(s server.Server, sh PkgdashServiceServer, opts ...options.Option) error { func RegisterPkgdashServiceServer(s server.Server, sh PkgdashServiceServer, opts ...server.HandlerOption) error {
type pkgdashService interface { type pkgdashService interface {
ListPackage(ctx context.Context, req *ListPackageReq, rsp *ListPackageRsp) error ListPackage(ctx context.Context, req *emptypb.Empty, rsp *ListPackageRsp) error
UpdatePackage(ctx context.Context, req *UpdatePackageReq, rsp *UpdatePackageRsp) error UpdatePackage(ctx context.Context, req *UpdatePackageReq, rsp *UpdatePackageRsp) error
AddComment(ctx context.Context, req *AddCommentReq, rsp *AddCommentRsp) error AddComment(ctx context.Context, req *AddCommentReq, rsp *AddCommentRsp) error
AddPackage(ctx context.Context, req *AddPackageReq, rsp *AddPackageRsp) error AddPackage(ctx context.Context, req *AddPackageReq, rsp *AddPackageRsp) error
@ -192,7 +152,7 @@ func RegisterPkgdashServiceServer(s server.Server, sh PkgdashServiceServer, opts
pkgdashService pkgdashService
} }
h := &pkgdashServiceServer{sh} h := &pkgdashServiceServer{sh}
var nopts []options.Option var nopts []server.HandlerOption
nopts = append(nopts, v4.HandlerEndpoints(PkgdashServiceServerEndpoints)) nopts = append(nopts, v31.HandlerEndpoints(PkgdashServiceServerEndpoints))
return s.Handle(&PkgdashService{h}, append(nopts, opts...)...) return s.Handle(s.NewHandler(&PkgdashService{h}, append(nopts, opts...)...))
} }

View File

@ -2,20 +2,18 @@ package service
import ( import (
"context" "context"
"net/http" cmsstorage "go.unistack.org/cms-service/storage" // TODO
httpsrv "go.unistack.org/micro-server-http/v3"
cmsservice "go.unistack.org/cms-service"
cmsstorage "go.unistack.org/cms-service/storage"
httpsrv "go.unistack.org/micro-server-http/v4"
"go.unistack.org/micro/v4" "go.unistack.org/micro/v4"
"go.unistack.org/micro/v4/config" "go.unistack.org/micro/v4/config"
microcfg "go.unistack.org/micro/v4/config"
"go.unistack.org/micro/v4/logger" "go.unistack.org/micro/v4/logger"
"go.unistack.org/micro/v4/options" "go.unistack.org/micro/v4/options"
"go.unistack.org/micro/v4/register" "go.unistack.org/micro/v4/register"
"go.unistack.org/micro/v4/server" "go.unistack.org/micro/v4/server"
intcfg "go.unistack.org/unistack-org/pkgdash/config" intcfg "go.unistack.org/unistack-org/pkgdash/config"
"go.unistack.org/unistack-org/pkgdash/handler" "go.unistack.org/unistack-org/pkgdash/handler"
"go.unistack.org/unistack-org/pkgdash/handler/encoders" pb "go.unistack.org/unistack-org/pkgdash/proto"
"go.unistack.org/unistack-org/pkgdash/service/client_git" "go.unistack.org/unistack-org/pkgdash/service/client_git"
"go.unistack.org/unistack-org/pkgdash/storage" "go.unistack.org/unistack-org/pkgdash/storage"
) )
@ -23,51 +21,44 @@ import (
func NewService(ctx context.Context) (micro.Service, error) { func NewService(ctx context.Context) (micro.Service, error) {
var reg register.Register var reg register.Register
if ctx == nil {
ctx = context.Background()
}
cfg := intcfg.NewConfig() cfg := intcfg.NewConfig()
cs := cmsservice.NewConfigLocal(cfg)
cs := microcfg.NewConfig(config.Struct(cfg))
// TODO
mgsrv := httpsrv.NewServer( mgsrv := httpsrv.NewServer(
options.Register(reg), options.Register(reg),
) )
svc := micro.NewService( svc := micro.NewService(
micro.Config(cs...), micro.Config(cs),
) )
writer, err := handler.NewWriter(encoders.NewJSONProto()) h := handler.NewHandler(svc, client_git.NewClient(5))
if err != nil {
logger.Fatalf(ctx, "failed init writer: %v", err)
}
h := handler.NewHandler(svc, writer, client_git.NewClient(5)) if err := svc.Init(
if err = svc.Init(
micro.AfterStart(func(_ context.Context) error { micro.AfterStart(func(_ context.Context) error {
return h.Init(svc.Options().Context) return h.Init(svc.Options().Context)
}), }),
micro.BeforeStart(func(ctx context.Context) error { micro.BeforeStart(func(ctx context.Context) error {
if err = config.Load(ctx, cs, config.LoadOverride(true)); err != nil { if err := config.Load(ctx, []config.Config{cs}, config.LoadOverride(true)); err != nil {
return err return err
} }
if err = config.Validate(ctx, cfg); err != nil { if err := config.Validate(ctx, cfg); err != nil {
return err return err
} }
if err = svc.Init( if err := svc.Init(
micro.Name(cfg.Service.Name), micro.Name(intcfg.ServiceName),
micro.Version(cfg.Service.Version), micro.Version(intcfg.ServiceVersion),
); err != nil { ); err != nil {
return err return err
} }
if err := svc.Server("http").Init( if err := svc.Server("http").Init(
options.Address(cfg.App.Address), options.Address(cfg.Address),
options.Name(cfg.Service.Name), options.Name(cfg.App.Name),
server.Version(cfg.Service.Version), server.Version(cfg.App.Version),
); err != nil { ); err != nil {
return err return err
} }
@ -75,23 +66,17 @@ func NewService(ctx context.Context) (micro.Service, error) {
return nil return nil
}), }),
micro.BeforeStart(func(_ context.Context) error { micro.BeforeStart(func(_ context.Context) error {
level := logger.InfoLevel
if v, ok := cfg.Logger.Level[cfg.Service.Name]; ok {
level = logger.ParseLevel(v)
} else if v, ok = cfg.Logger.Level["all"]; ok {
level = logger.ParseLevel(v)
}
log := logger.NewLogger( log := logger.NewLogger(
logger.WithLevel(level), logger.WithLevel(logger.ParseLevel(cfg.LogLevel)),
logger.WithCallerSkipCount(3), logger.WithCallerSkipCount(3),
) )
return svc.Init(micro.Logger(log)) return svc.Init(micro.Logger(log))
}), }),
micro.BeforeStart(func(_ context.Context) error { micro.BeforeStart(func(_ context.Context) error { // TODO
var connstr string var connstr string
if v, ok := cfg.Storage.DSN[cfg.Service.Name]; ok { if v, ok := cfg.StorageDSN[cfg.App.Name]; ok {
connstr = v connstr = v
} else if v, ok = cfg.Storage.DSN["all"]; ok { } else if v, ok = cfg.StorageDSN["all"]; ok {
connstr = v connstr = v
} }
scheme, dsn, err := cmsstorage.StorageOptions(connstr) scheme, dsn, err := cmsstorage.StorageOptions(connstr)
@ -115,15 +100,15 @@ func NewService(ctx context.Context) (micro.Service, error) {
return nil, err return nil, err
} }
mux := http.NewServeMux() //mux := http.NewServeMux()
mux.HandleFunc("/listPackage", handler.Methods(http.MethodGet, h.ListPackage)) //mux.HandleFunc("/listPackage", handler.Methods(http.MethodGet, h.ListPackage))
mux.HandleFunc("/updatePackage", handler.Methods(http.MethodPost, h.UpdatePackage)) //mux.HandleFunc("/updatePackage", handler.Methods(http.MethodPost, h.UpdatePackage))
mux.HandleFunc("/addComment", handler.Methods(http.MethodPut, h.AddComment)) //mux.HandleFunc("/addComment", handler.Methods(http.MethodPut, h.AddComment))
mux.HandleFunc("/addPackage", handler.Methods(http.MethodPost, h.AddPackage)) //mux.HandleFunc("/addPackage", handler.Methods(http.MethodPost, h.AddPackage))
mux.HandleFunc("/getModule", handler.Methods(http.MethodGet, h.GetModule)) //mux.HandleFunc("/getModule", handler.Methods(http.MethodGet, h.GetModule))
if err = svc.Server().Handle(svc.Server().NewHandler(mux)); err != nil { if err := pb.RegisterPkgdashServiceServer(mgsrv, h); err != nil {
logger.Fatalf(ctx, "failed to register handler: %v", err) logger.Fatalf(ctx, "failed to register handler: %v", err)
} }

View File

@ -24,5 +24,9 @@ insert into package(name, url, modules) values ($1, $2, $3);
insert into module(name, version, last_version) values insert into module(name, version, last_version) values
%s %s
returning id; returning id;
`
queryGetModule = `
select id, name, version, last_version from module
where id in %s ;
` `
) )

View File

@ -6,7 +6,6 @@ import (
"embed" "embed"
"errors" "errors"
"fmt" "fmt"
pb "go.unistack.org/unistack-org/pkgdash/proto"
"strings" "strings"
"github.com/golang-migrate/migrate/v4" "github.com/golang-migrate/migrate/v4"
@ -16,6 +15,7 @@ import (
"go.unistack.org/micro/v4/logger" "go.unistack.org/micro/v4/logger"
"go.unistack.org/unistack-org/pkgdash/config" "go.unistack.org/unistack-org/pkgdash/config"
"go.unistack.org/unistack-org/pkgdash/models" "go.unistack.org/unistack-org/pkgdash/models"
pb "go.unistack.org/unistack-org/pkgdash/proto"
) )
const ( const (
@ -138,7 +138,7 @@ func (s *Postgres) AddComment(ctx context.Context, req *pb.AddCommentReq) error
} }
}() }()
res, err := tx.ExecContext(ctx, queryAddComment, req.Text, req.IdPackage.Value) res, err := tx.ExecContext(ctx, queryAddComment, req.Text, req.IdPackage)
if err != nil { if err != nil {
return err return err
} }
@ -168,7 +168,7 @@ func (s *Postgres) AddPackage(ctx context.Context, req *pb.AddPackageReq) error
} }
}() }()
res, err := tx.ExecContext(ctx, queryAddPackage, req.Name.Value, req.Url.Value, pq.Array(req.Modules)) res, err := tx.ExecContext(ctx, queryAddPackage, req.Name, req.Url, pq.Array(req.Modules))
if err != nil { if err != nil {
return err return err
} }

View File

@ -12,7 +12,7 @@ select
from package; from package;
` `
queryAddComment = ` queryAddComment = `
insert into comment(text) values ($1) ; insert into comment(text) values ($1) returning id;
update package update package
set comments = json_insert(comments, '$[#]', ( select last_insert_rowid() as id from comment )) set comments = json_insert(comments, '$[#]', ( select last_insert_rowid() as id from comment ))
where id = $2 ; where id = $2 ;

View File

@ -123,10 +123,10 @@ func (s *Sqlite) ListPackage(ctx context.Context) (models.ListPackage, error) {
return result, err return result, err
} }
func (s *Sqlite) AddComment(ctx context.Context, req *pb.AddCommentReq) error { func (s *Sqlite) AddComment(ctx context.Context, req *pb.AddCommentReq) (id uint64, err error) {
tx, err := s.db.BeginTx(ctx, nil) tx, err := s.db.BeginTx(ctx, nil)
if err != nil { if err != nil {
return err return 0, err
} }
defer func() { defer func() {
@ -139,18 +139,11 @@ func (s *Sqlite) AddComment(ctx context.Context, req *pb.AddCommentReq) error {
} }
}() }()
res, err := tx.ExecContext(ctx, queryAddComment, req.Text, req.IdPackage.Value) if err = tx.QueryRowContext(ctx, queryAddComment, req.Text, req.IdPackage).Scan(&id); err != nil {
if err != nil { return id, err
return err
} }
if aff, affErr := res.RowsAffected(); err != nil { return id, err
err = affErr
} else if aff == 0 {
err = errors.New("rows affected is 0")
}
return err
} }
func (s *Sqlite) AddPackage(ctx context.Context, req *pb.AddPackageReq) error { func (s *Sqlite) AddPackage(ctx context.Context, req *pb.AddPackageReq) error {
@ -169,7 +162,7 @@ func (s *Sqlite) AddPackage(ctx context.Context, req *pb.AddPackageReq) error {
} }
}() }()
res, err := tx.ExecContext(ctx, queryAddPackage, req.Name.Value, req.Url.Value, pq.Array(req.Modules)) res, err := tx.ExecContext(ctx, queryAddPackage, req.Name, req.Url, pq.Array(req.Modules))
if err != nil { if err != nil {
return err return err
} }

View File

@ -27,7 +27,7 @@ type Storage interface {
ListPackage(ctx context.Context) (models.ListPackage, error) ListPackage(ctx context.Context) (models.ListPackage, error)
UpdatePackage(ctx context.Context, req *pb.UpdatePackageReq) error UpdatePackage(ctx context.Context, req *pb.UpdatePackageReq) error
AddComment(ctx context.Context, req *pb.AddCommentReq) error AddComment(ctx context.Context, req *pb.AddCommentReq) (uint64, error)
AddPackage(ctx context.Context, req *pb.AddPackageReq) error AddPackage(ctx context.Context, req *pb.AddPackageReq) error
InsertButchModules(ctx context.Context, req []models.Module) ([]uint64, error) InsertButchModules(ctx context.Context, req []models.Module) ([]uint64, error)
GetModule(ctx context.Context, req *pb.GetModuleReq) (models.ListModule, error) GetModule(ctx context.Context, req *pb.GetModuleReq) (models.ListModule, error)