Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package grpc

import (
"crypto/tls"
stderr "errors"
"math"
"os"
"strings"
Expand Down Expand Up @@ -80,7 +81,7 @@ func (c *Config) InitDefaults() error { //nolint:gocyclo,gocognit
}

if _, err := os.Stat(path); err != nil {
if os.IsNotExist(err) {
if stderr.Is(err, os.ErrNotExist) {
return errors.E(op, errors.Errorf("proto file '%s' does not exists", path))
}

Expand All @@ -92,15 +93,15 @@ func (c *Config) InitDefaults() error { //nolint:gocyclo,gocognit

if c.EnableTLS() {
if _, err := os.Stat(c.TLS.Key); err != nil {
if os.IsNotExist(err) {
if stderr.Is(err, os.ErrNotExist) {
return errors.E(op, errors.Errorf("key file '%s' does not exists", c.TLS.Key))
}

return errors.E(op, err)
}

if _, err := os.Stat(c.TLS.Cert); err != nil {
if os.IsNotExist(err) {
if stderr.Is(err, os.ErrNotExist) {
return errors.E(op, errors.Errorf("cert file '%s' does not exists", c.TLS.Cert))
}

Expand All @@ -110,7 +111,7 @@ func (c *Config) InitDefaults() error { //nolint:gocyclo,gocognit
// RootCA is optional, but if provided - check it
if c.TLS.RootCA != "" {
if _, err := os.Stat(c.TLS.RootCA); err != nil {
if os.IsNotExist(err) {
if stderr.Is(err, os.ErrNotExist) {
return errors.E(op, errors.Errorf("root ca path provided, but key file '%s' does not exists", c.TLS.RootCA))
Comment thread
rustatian marked this conversation as resolved.
Outdated
}
return errors.E(op, err)
Expand Down
12 changes: 10 additions & 2 deletions health_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,18 +42,26 @@ func NewHeathServer(p *Plugin, log *slog.Logger) *HealthCheckServer {
// Clients should keep in mind that the list of health services exposed by an
// application can change over the lifetime of the process.
func (h *HealthCheckServer) List(context.Context, *grpc_health_v1.HealthListRequest) (*grpc_health_v1.HealthListResponse, error) {
h.mu.Lock()
st := h.status
h.mu.Unlock()

return &grpc_health_v1.HealthListResponse{
Statuses: map[string]*grpc_health_v1.HealthCheckResponse{
"grpc": {
Status: h.status,
Status: st,
},
},
}, nil
}

func (h *HealthCheckServer) Check(_ context.Context, _ *grpc_health_v1.HealthCheckRequest) (*grpc_health_v1.HealthCheckResponse, error) {
h.mu.Lock()
st := h.status
h.mu.Unlock()

return &grpc_health_v1.HealthCheckResponse{
Status: h.status,
Status: st,
}, nil
}

Expand Down
20 changes: 8 additions & 12 deletions plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"sync"

"github.com/prometheus/client_golang/prometheus"
"github.com/roadrunner-server/pool/v2/pool/static_pool"
"github.com/roadrunner-server/tcplisten"
"go.opentelemetry.io/otel/propagation"

Expand Down Expand Up @@ -194,23 +193,20 @@ func (p *Plugin) Stop(ctx context.Context) error {
p.mu.Lock()
defer p.mu.Unlock()

p.healthServer.SetServingStatus(grpc_health_v1.HealthCheckResponse_NOT_SERVING)
if p.healthServer != nil {
p.healthServer.SetServingStatus(grpc_health_v1.HealthCheckResponse_NOT_SERVING)
}

if p.server != nil {
p.server.GracefulStop()
}

p.healthServer.Shutdown()
if p.healthServer != nil {
p.healthServer.Shutdown()
}

if p.gPool != nil {
switch pp := p.gPool.(type) {
case *static_pool.Pool:
if pp != nil {
pp.Destroy(ctx)
}
default:
// pool is nil, nothing to do
}
p.gPool.Destroy(ctx)
}

finCh <- struct{}{}
Expand Down Expand Up @@ -257,7 +253,7 @@ func (p *Plugin) Workers() []*process.State {
for i := range workers {
state, err := process.WorkerProcessState(workers[i])
if err != nil {
return nil
continue
}
ps = append(ps, state)
}
Expand Down
63 changes: 23 additions & 40 deletions protoc_plugins/protoc-gen-php-grpc/php/keywords.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,41 +23,34 @@
package php

import (
"bytes"
"strings"
"unicode"
)

// @see https://github.com/protocolbuffers/protobuf/blob/master/php/ext/google/protobuf/protobuf.c#L168
// immutable
var reservedKeywords = []string{ //nolint:gochecknoglobals
"abstract", "and", "array", "as", "break",
"callable", "case", "catch", "class", "clone",
"const", "continue", "declare", "default", "die",
"do", "echo", "else", "elseif", "empty",
"enddeclare", "endfor", "endforeach", "endif", "endswitch",
"endwhile", "eval", "exit", "extends", "final",
"for", "foreach", "function", "global", "goto",
"if", "implements", "include", "include_once", "instanceof",
"insteadof", "interface", "isset", "list", "namespace",
"new", "or", "print", "private", "protected",
"public", "require", "require_once", "return", "static",
"switch", "throw", "trait", "try", "unset",
"use", "var", "while", "xor", "int",
"float", "bool", "string", "true", "false",
"null", "void", "iterable",
var reservedKeywordsMap = map[string]struct{}{ //nolint:gochecknoglobals
"abstract": {}, "and": {}, "array": {}, "as": {}, "break": {},
"callable": {}, "case": {}, "catch": {}, "class": {}, "clone": {},
"const": {}, "continue": {}, "declare": {}, "default": {}, "die": {},
"do": {}, "echo": {}, "else": {}, "elseif": {}, "empty": {},
"enddeclare": {}, "endfor": {}, "endforeach": {}, "endif": {}, "endswitch": {},
"endwhile": {}, "eval": {}, "exit": {}, "extends": {}, "final": {},
"for": {}, "foreach": {}, "function": {}, "global": {}, "goto": {},
"if": {}, "implements": {}, "include": {}, "include_once": {}, "instanceof": {},
"insteadof": {}, "interface": {}, "isset": {}, "list": {}, "namespace": {},
"new": {}, "or": {}, "print": {}, "private": {}, "protected": {},
"public": {}, "require": {}, "require_once": {}, "return": {}, "static": {},
"switch": {}, "throw": {}, "trait": {}, "try": {}, "unset": {},
"use": {}, "var": {}, "while": {}, "xor": {}, "int": {},
"float": {}, "bool": {}, "string": {}, "true": {}, "false": {},
"null": {}, "void": {}, "iterable": {},
}

// Check if given name/keyword is reserved by php.
func isReserved(name string) bool {
name = strings.ToLower(name)
for _, k := range reservedKeywords {
if name == k {
return true
}
}

return false
_, ok := reservedKeywordsMap[strings.ToLower(name)]
return ok
}

// generate php namespace or path
Expand All @@ -66,7 +59,7 @@ func namespace(pkg *string, sep string) string {
return ""
}

result := bytes.NewBuffer(nil)
var result strings.Builder
for p := range strings.SplitSeq(*pkg, ".") {
result.WriteString(identifier(p, ""))
result.WriteString(sep)
Expand Down Expand Up @@ -103,14 +96,14 @@ func Camelize(word string) string {
}

func splitAtCaseChangeWithTitlecase(s string) []string {
words := make([]string, 0)
word := make([]rune, 0)
var words []string
var word []rune
for _, c := range s {
spacer := isSpacerChar(c)
if len(word) > 0 {
if unicode.IsUpper(c) || spacer {
words = append(words, string(word))
word = make([]rune, 0)
word = word[:0]
}
}
if !spacer {
Expand All @@ -126,15 +119,5 @@ func splitAtCaseChangeWithTitlecase(s string) []string {
}

func isSpacerChar(c rune) bool {
switch {
case c == rune("_"[0]):
return true
case c == rune(" "[0]):
return true
case c == rune(":"[0]):
return true
case c == rune("-"[0]):
return true
}
return false
return strings.ContainsRune("_ :-", c)
}
3 changes: 1 addition & 2 deletions protoc_plugins/protoc-gen-php-grpc/php/ns.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
package php

import (
"bytes"
"fmt"
"strings"

Expand Down Expand Up @@ -72,7 +71,7 @@ func (ns *ns) registerMessageNamespace(req *plugin.CodeGeneratorRequest, msg *st
chunks := strings.Split(*msg, ".")
pkg := strings.Join(chunks[:len(chunks)-1], ".")

result := bytes.NewBuffer(nil)
var result strings.Builder
for _, p := range chunks[:len(chunks)-1] {
result.WriteString(identifier(p, ""))
result.WriteString(`\`)
Expand Down
47 changes: 23 additions & 24 deletions protoc_plugins/protoc-gen-php-grpc/php/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,35 @@
package php

import (
"bytes"
"fmt"
"strings"
"sync"
"text/template"

desc "google.golang.org/protobuf/types/descriptorpb"
plugin "google.golang.org/protobuf/types/pluginpb"
)

var phpTemplate = sync.OnceValue(func() *template.Template { //nolint:gochecknoglobals
return template.Must(template.New("phpBody").Funcs(template.FuncMap{
"interface": func(name *string) string {
return identifier(*name, "interface")
},
"name": func(ns *ns, name *string) string {
return ns.resolve(name)
},
"strip_slashes": func(name string) string {
return strings.ReplaceAll(name, "\\\\", "\\")
},
"resolve_name_const": func(packagePath, serviceName *string) string {
if defaultOrVal(packagePath) == "" {
return defaultOrVal(serviceName)
}
return *packagePath + "." + defaultOrVal(serviceName)
},
}).Parse(phpBody))
})

const phpBody = `<?php
# Generated by the protocol buffer compiler (roadrunner-server/grpc). DO NOT EDIT!
# source: {{ .File.Name }}
Expand Down Expand Up @@ -72,8 +92,6 @@ func filename(file *desc.FileDescriptorProto, name *string) string {

// generate php file body
func body(req *plugin.CodeGeneratorRequest, file *desc.FileDescriptorProto, service *desc.ServiceDescriptorProto) string {
out := bytes.NewBuffer(nil)

data := struct {
Namespace *ns
File *desc.FileDescriptorProto
Expand All @@ -84,27 +102,8 @@ func body(req *plugin.CodeGeneratorRequest, file *desc.FileDescriptorProto, serv
Service: service,
}

tpl := template.Must(template.New("phpBody").Funcs(template.FuncMap{
"interface": func(name *string) string {
return identifier(*name, "interface")
},
"name": func(ns *ns, name *string) string {
return ns.resolve(name)
},
"strip_slashes": func(name string) string {
return strings.ReplaceAll(name, "\\\\", "\\")
},
"resolve_name_const": func(packagePath, serviceName *string) string {
if defaultOrVal(packagePath) == "" {
return defaultOrVal(serviceName)
}

return *packagePath + "." + defaultOrVal(serviceName)
},
}).Parse(phpBody))

err := tpl.Execute(out, data)
if err != nil {
var out strings.Builder
if err := phpTemplate().Execute(&out, data); err != nil {
panic(err)
}

Expand Down
16 changes: 5 additions & 11 deletions proxy/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
stderr "errors"
"fmt"
"log/slog"
"math"
"strconv"
"strings"
"sync"
Expand Down Expand Up @@ -335,8 +334,8 @@ func (p *Proxy) makePayload(ctx context.Context, method string, body *codec.RawM
}

func (p *Proxy) putPld(pld *payload.Payload) {
pld.Body = nil
pld.Context = nil
pld.Body = pld.Body[:0]
pld.Context = pld.Context[:0]
Comment thread
rustatian marked this conversation as resolved.
Outdated
p.pldPool.Put(pld)
}

Expand Down Expand Up @@ -368,21 +367,16 @@ func GetOriginalErr(err error) string {
func wrapError(err error) error {
// internal agreement
errMsg := GetOriginalErr(err)
if strings.Contains(errMsg, delimiter) {
chunks := strings.Split(errMsg, delimiter)
chunks := strings.Split(errMsg, delimiter)
if len(chunks) >= 2 {
code := codes.Internal

// protect the slice access
if len(chunks) < 2 {
return err
}

phpCode, errConv := strconv.ParseUint(chunks[0], 10, 32)
if errConv != nil {
return err
}

if phpCode > 0 && phpCode < math.MaxUint32 {
if phpCode > 0 {
code = codes.Code(phpCode)
}

Expand Down
6 changes: 3 additions & 3 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func (p *Plugin) createGRPCserver(interceptors map[string]api.Interceptor) (*grp
}

unaryInterceptors := []grpc.UnaryServerInterceptor{
grpc.UnaryServerInterceptor(p.interceptor),
p.interceptor,
}

// if we have interceptors in the config, we need to chain them with our interceptor, and add them to the server options
Expand All @@ -39,7 +39,7 @@ func (p *Plugin) createGRPCserver(interceptors map[string]api.Interceptor) (*grp
name := p.config.Interceptors[i]
if _, ok := interceptors[name]; !ok {
// we should raise an error here, since we may silently ignore let's say auth interceptor, which is critical for security
return nil, errors.E(op, errors.Str(fmt.Sprintf("interceptor %s is not registered", name)))
return nil, errors.E(op, errors.Errorf("interceptor %s is not registered", name))
}

unaryInterceptors = append(
Expand Down Expand Up @@ -176,7 +176,7 @@ func (p *Plugin) serverOptions() ([]grpc.ServerOption, error) {
grpc.KeepaliveParams(keepalive.ServerParameters{
MaxConnectionIdle: p.config.MaxConnectionIdle,
MaxConnectionAge: p.config.MaxConnectionAge,
MaxConnectionAgeGrace: p.config.MaxConnectionAge,
MaxConnectionAgeGrace: p.config.MaxConnectionAgeGrace,
Time: p.config.PingTime,
Timeout: p.config.Timeout,
}),
Expand Down
Loading