Merge branch 'dev' into 'main'
MSP-7042 Init service See merge request isp/isp-router-service!1
This commit is contained in:
commit
afeadb1d9a
25 files changed
+1664
-92
No files matched your search
@@ -0,0 +1,60 @@
|
||||
name: Create and publish a Docker image
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
IMAGE_NAME: ${{ github.repository }}
|
||||
APP_NAME: ${{ github.event.repository.name }}
|
||||
|
||||
jobs:
|
||||
build-and-push-image:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
attestations: write
|
||||
id-token: write
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
- name: Get version from tag
|
||||
id: version_reader
|
||||
run: |
|
||||
VERSION=${GITHUB_REF_NAME#v}
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
with:
|
||||
driver: docker-container
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Build and push Docker image
|
||||
id: push
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.version_reader.outputs.version }}
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
|
||||
labels: |
|
||||
org.opencontainers.image.title=${{ env.IMAGE_NAME }}
|
||||
org.opencontainers.image.version=${{ steps.version_reader.outputs.version }}
|
||||
build-args: |
|
||||
app_name=${{ env.APP_NAME }}
|
||||
version=${{ steps.version_reader.outputs.version }}
|
||||
- name: Generate artifact attestation
|
||||
uses: actions/attest-build-provenance@v2
|
||||
with:
|
||||
subject-name: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME}}
|
||||
subject-digest: ${{ steps.push.outputs.digest }}
|
||||
push-to-registry: true
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
# Created by .ignore support plugin (hsz.mobi)
|
||||
### JetBrains template
|
||||
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
|
||||
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
||||
|
||||
# User-specific stuff:
|
||||
/.idea/
|
||||
.idea/**/workspace.xml
|
||||
.idea/**/tasks.xml
|
||||
.idea/dictionaries
|
||||
*.iml
|
||||
routing_service
|
||||
routing-service
|
||||
|
||||
# Sensitive or high-churn files:
|
||||
.idea/**/dataSources/
|
||||
.idea/**/dataSources.ids
|
||||
.idea/**/dataSources.local.xml
|
||||
.idea/**/sqlDataSources.xml
|
||||
.idea/**/dynamic.xml
|
||||
.idea/**/uiDesigner.xml
|
||||
|
||||
# Gradle:
|
||||
.idea/**/gradle.xml
|
||||
.idea/**/libraries
|
||||
|
||||
# CMake
|
||||
cmake-build-debug/
|
||||
cmake-build-release/
|
||||
|
||||
# Mongo Explorer plugin:
|
||||
.idea/**/mongoSettings.xml
|
||||
|
||||
## File-based project format:
|
||||
*.iws
|
||||
|
||||
## Plugin-specific files:
|
||||
|
||||
# IntelliJ
|
||||
out/
|
||||
|
||||
# mpeltonen/sbt-idea plugin
|
||||
.idea_modules/
|
||||
|
||||
# JIRA plugin
|
||||
atlassian-ide-plugin.xml
|
||||
|
||||
# Cursive Clojure plugin
|
||||
.idea/replstate.xml
|
||||
|
||||
# Crashlytics plugin (for Android Studio and IntelliJ)
|
||||
com_crashlytics_export_strings.xml
|
||||
crashlytics.properties
|
||||
crashlytics-build.properties
|
||||
fabric.properties
|
||||
### Go template
|
||||
# Binaries for programs and plugins
|
||||
*.exe
|
||||
*.exe~
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
|
||||
# Test binary, build with `go test -c`
|
||||
*.test
|
||||
|
||||
# Output of the go coverage tool, specifically when used with LiteIDE
|
||||
*.out
|
||||
|
||||
/node_modules/
|
||||
/vendor/
|
||||
|
||||
conf/config_dev.yml
|
||||
@@ -0,0 +1,3 @@
|
||||
include:
|
||||
- project: '$CI_PROJECT_PATH'
|
||||
file: '/ci-isp-go-service.yml'
|
||||
@@ -0,0 +1,69 @@
|
||||
version: "2"
|
||||
run:
|
||||
allow-parallel-runners: true
|
||||
linters:
|
||||
default: all
|
||||
disable:
|
||||
- contextcheck # не имеет смысла
|
||||
- depguard # не всегда имеет смысл
|
||||
- dupword # не имеет смысла
|
||||
- exhaustruct # не имеет смысла
|
||||
- godot # не актуально для swagger
|
||||
- godox # не позволяет оставлять todo
|
||||
- musttag # у нас собственное правило: не используем теги, если работаем с пакетом isp-kit/json и с внутренними структурами(между нашими сервисами), при этом теги обязательный для всех внешних для нас структур
|
||||
- nlreturn # не всегда имеет смысл
|
||||
- nolintlint # Goland все равно форматирует с отступом
|
||||
- perfsprint # мнимая производительность в угоду читаемости
|
||||
- tagalign # не всегда имеет смысл
|
||||
- varnamelen # очень индивидуально (db)
|
||||
- wsl # расставление пробелов очень индивидуально
|
||||
- wsl_v5 # расставление пробелов очень индивидуально
|
||||
settings:
|
||||
cyclop:
|
||||
max-complexity: 15 # по умолчанию 10 мало
|
||||
funlen:
|
||||
lines: 80
|
||||
lll:
|
||||
line-length: 150
|
||||
revive:
|
||||
rules:
|
||||
- name: var-naming # отключаем Id -> ID
|
||||
disabled: true
|
||||
staticcheck:
|
||||
checks: # отключаем Id -> ID
|
||||
- -ST1000
|
||||
- -ST1016
|
||||
- -ST1020
|
||||
- -ST1021
|
||||
- -ST1022
|
||||
testifylint:
|
||||
disable:
|
||||
- compares
|
||||
- equal-values
|
||||
exclusions:
|
||||
generated: lax
|
||||
presets:
|
||||
- comments
|
||||
- common-false-positives
|
||||
- legacy
|
||||
- std-error-handling
|
||||
rules:
|
||||
- linters:
|
||||
- wrapcheck
|
||||
path: controller # достаточное кол-во контекста на уровне контроллеров
|
||||
- linters:
|
||||
- wrapcheck
|
||||
path: transaction # транзакции прозрачны
|
||||
paths:
|
||||
- third_party$
|
||||
- builtin$
|
||||
- examples$
|
||||
formatters:
|
||||
enable:
|
||||
- gofmt
|
||||
exclusions:
|
||||
generated: lax
|
||||
paths:
|
||||
- third_party$
|
||||
- builtin$
|
||||
- examples$
|
||||
@@ -0,0 +1,2 @@
|
||||
### v1.0.0
|
||||
* Инициализация сервиса
|
||||
@@ -1,93 +1,2 @@
|
||||
# isp-router-service
|
||||
|
||||
|
||||
|
||||
## Getting started
|
||||
|
||||
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
|
||||
|
||||
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
|
||||
|
||||
## Add your files
|
||||
|
||||
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
|
||||
- [ ] [Add files using the command line](https://docs.gitlab.com/topics/git/add_files/#add-files-to-a-git-repository) or push an existing Git repository with the following command:
|
||||
|
||||
```
|
||||
cd existing_repo
|
||||
git remote add origin https://gitlab.txix.ru/isp/isp-router-service.git
|
||||
git branch -M main
|
||||
git push -uf origin main
|
||||
```
|
||||
|
||||
## Integrate with your tools
|
||||
|
||||
- [ ] [Set up project integrations](https://gitlab.txix.ru/isp/isp-router-service/-/settings/integrations)
|
||||
|
||||
## Collaborate with your team
|
||||
|
||||
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
|
||||
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
|
||||
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
|
||||
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
|
||||
- [ ] [Set auto-merge](https://docs.gitlab.com/user/project/merge_requests/auto_merge/)
|
||||
|
||||
## Test and Deploy
|
||||
|
||||
Use the built-in continuous integration in GitLab.
|
||||
|
||||
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/)
|
||||
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
|
||||
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
|
||||
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
|
||||
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
|
||||
|
||||
***
|
||||
|
||||
# Editing this README
|
||||
|
||||
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
|
||||
|
||||
## Suggestions for a good README
|
||||
|
||||
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
|
||||
|
||||
## Name
|
||||
Choose a self-explaining name for your project.
|
||||
|
||||
## Description
|
||||
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
|
||||
|
||||
## Badges
|
||||
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
|
||||
|
||||
## Visuals
|
||||
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
|
||||
|
||||
## Installation
|
||||
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
|
||||
|
||||
## Usage
|
||||
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
|
||||
|
||||
## Support
|
||||
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
|
||||
|
||||
## Roadmap
|
||||
If you have ideas for releases in the future, it is a good idea to list them in the README.
|
||||
|
||||
## Contributing
|
||||
State if you are open to contributions and what your requirements are for accepting them.
|
||||
|
||||
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
|
||||
|
||||
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
|
||||
|
||||
## Authors and acknowledgment
|
||||
Show your appreciation to those who have contributed to the project.
|
||||
|
||||
## License
|
||||
For open source projects, say how it is licensed.
|
||||
|
||||
## Project status
|
||||
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
|
||||
[Wiki](/../wikis)
|
||||
@@ -0,0 +1,72 @@
|
||||
package assembly
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/txix-open/isp-kit/app"
|
||||
"github.com/txix-open/isp-kit/bootstrap"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/http"
|
||||
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
type Assembly struct {
|
||||
boot *bootstrap.Bootstrap
|
||||
server *http.Server
|
||||
proxyMap map[ProxyKey]Proxy
|
||||
logger *log.Adapter
|
||||
}
|
||||
|
||||
func New(boot *bootstrap.Bootstrap) *Assembly {
|
||||
return &Assembly{
|
||||
boot: boot,
|
||||
server: http.NewServer(boot.App.Logger()),
|
||||
proxyMap: make(map[ProxyKey]Proxy, 0),
|
||||
logger: boot.App.Logger(),
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Assembly) ReceiveRoutes(_ context.Context, routingCfg cluster.RoutingConfig) error {
|
||||
locator := NewLocator(a.logger)
|
||||
locatorCfg := locator.LocatorConfig(routingCfg, a.proxyMap)
|
||||
a.server.Upgrade(locatorCfg.Handler)
|
||||
|
||||
for key, oldProxy := range a.proxyMap {
|
||||
_, ok := locatorCfg.ProxyMap[key]
|
||||
if !ok {
|
||||
_ = oldProxy.Close()
|
||||
}
|
||||
}
|
||||
a.proxyMap = locatorCfg.ProxyMap
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *Assembly) Runners() []app.Runner {
|
||||
eventHandler := cluster.NewEventHandler().
|
||||
RoutesReceiver(a)
|
||||
return []app.Runner{
|
||||
app.RunnerFunc(func(ctx context.Context) error {
|
||||
return a.server.ListenAndServe(a.boot.BindingAddress)
|
||||
}),
|
||||
app.RunnerFunc(func(ctx context.Context) error {
|
||||
return a.boot.ClusterCli.Run(ctx, eventHandler)
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Assembly) Closers() []app.Closer {
|
||||
return []app.Closer{
|
||||
a.boot.ClusterCli,
|
||||
app.CloserFunc(func() error {
|
||||
return a.server.Shutdown(context.Background())
|
||||
}),
|
||||
app.CloserFunc(func() error {
|
||||
for _, proxy := range a.proxyMap {
|
||||
_ = proxy.Close()
|
||||
}
|
||||
return nil
|
||||
}),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package assembly
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"isp-router-service/domain"
|
||||
"isp-router-service/middleware"
|
||||
"isp-router-service/service/proxy"
|
||||
"net"
|
||||
"net/http"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
http2 "github.com/txix-open/isp-kit/http"
|
||||
"github.com/txix-open/isp-kit/http/endpoint"
|
||||
"github.com/txix-open/isp-kit/http/router"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
)
|
||||
|
||||
const (
|
||||
maxMessageSize = 64 * 1024 * 1024
|
||||
proxyTimeout = 5 * time.Second
|
||||
)
|
||||
|
||||
type Proxy interface {
|
||||
Handle(ctx *domain.RequestContext) error
|
||||
PrepareEndpoint(endpoint string, proxyApiPrefix bool) string
|
||||
Close() error
|
||||
}
|
||||
|
||||
type Locator struct {
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
func NewLocator(logger log.Logger) Locator {
|
||||
return Locator{
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
type LocatorConfig struct {
|
||||
ProxyMap map[ProxyKey]Proxy
|
||||
Handler http.Handler
|
||||
}
|
||||
|
||||
type ProxyKey struct {
|
||||
Transport string
|
||||
Addresses string
|
||||
}
|
||||
|
||||
func (l Locator) LocatorConfig(config cluster.RoutingConfig, oldProxyMap map[ProxyKey]Proxy) LocatorConfig {
|
||||
routes := l.getRoutes(config)
|
||||
|
||||
groupMap := make(map[string][]domain.RouteKey)
|
||||
for route, cfg := range routes {
|
||||
addresses := append([]string{}, cfg.Addresses...)
|
||||
sort.Strings(addresses) // чтобы ключ был одинаковым для одинакового множества
|
||||
groupKey := strings.Join(addresses, ",")
|
||||
groupMap[groupKey] = append(groupMap[groupKey], route)
|
||||
}
|
||||
|
||||
mux := router.New()
|
||||
mux.InternalRouter().NotFound = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, fmt.Sprintf("unknown endpoint '%s'", r.URL.Path), http.StatusNotImplemented)
|
||||
})
|
||||
|
||||
middlewares := []http2.Middleware{
|
||||
middleware.ErrorHandler(l.logger),
|
||||
endpoint.RequestId(),
|
||||
}
|
||||
|
||||
proxyMap := make(map[ProxyKey]Proxy, len(groupMap))
|
||||
for groupKey, routeKeys := range groupMap {
|
||||
addresses := strings.Split(groupKey, ",")
|
||||
// ОК, т.к. в getRoutes собираем только с endpoint'ами
|
||||
transport := routes[routeKeys[0]].Transport
|
||||
proxyKey := ProxyKey{
|
||||
Transport: transport,
|
||||
Addresses: groupKey,
|
||||
}
|
||||
|
||||
var err error
|
||||
proxy, ok := oldProxyMap[proxyKey]
|
||||
if !ok {
|
||||
proxy, err = buildProxy(proxyKey.Transport, addresses)
|
||||
if err != nil {
|
||||
l.logger.Error(context.Background(), err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
proxyMap[proxyKey] = proxy
|
||||
|
||||
for _, routeKey := range routeKeys {
|
||||
l.registerEndpoint(mux, routeKey, proxy, middlewares)
|
||||
}
|
||||
}
|
||||
|
||||
l.logger.Info(
|
||||
context.Background(),
|
||||
"change routing table",
|
||||
log.Int("totalBackends", len(proxyMap)),
|
||||
log.Int("totalEndpoints", len(routes)),
|
||||
)
|
||||
return LocatorConfig{
|
||||
ProxyMap: proxyMap,
|
||||
Handler: mux,
|
||||
}
|
||||
}
|
||||
|
||||
func (l Locator) getRoutes(config cluster.RoutingConfig) map[domain.RouteKey]*domain.RouteConfig {
|
||||
routes := make(map[domain.RouteKey]*domain.RouteConfig, len(config))
|
||||
|
||||
for _, decl := range config {
|
||||
if decl.Address.IP == "" ||
|
||||
decl.Address.Port == "" ||
|
||||
len(decl.Endpoints) == 0 ||
|
||||
decl.Transport == cluster.EmptyTransport {
|
||||
continue
|
||||
}
|
||||
|
||||
addr := net.JoinHostPort(decl.Address.IP, decl.Address.Port)
|
||||
|
||||
for _, ep := range decl.Endpoints {
|
||||
if !strings.HasPrefix(ep.Path, "/") {
|
||||
ep.Path = "/" + ep.Path
|
||||
}
|
||||
|
||||
transport := decl.Transport
|
||||
if decl.Transport == "" {
|
||||
transport = cluster.GrpcTransport
|
||||
}
|
||||
|
||||
withApiPrefix := strings.HasPrefix(ep.Path, domain.ApiPrefix)
|
||||
cleanPath := strings.TrimPrefix(ep.Path, domain.ApiPrefix)
|
||||
|
||||
method := ep.HttpMethod
|
||||
if transport == cluster.GrpcTransport &&
|
||||
method == "" {
|
||||
method = http.MethodPost
|
||||
}
|
||||
|
||||
key := domain.RouteKey{
|
||||
Method: method,
|
||||
CleanPath: cleanPath,
|
||||
WithApiPrefix: withApiPrefix,
|
||||
}
|
||||
|
||||
route, ok := routes[key]
|
||||
if !ok {
|
||||
route = &domain.RouteConfig{
|
||||
Transport: transport,
|
||||
}
|
||||
routes[key] = route
|
||||
}
|
||||
|
||||
if route.Transport != transport {
|
||||
l.logger.Error(
|
||||
context.Background(),
|
||||
"transport conflict for route",
|
||||
log.String("method", key.Method),
|
||||
log.String("path", key.CleanPath),
|
||||
log.String("transport1", route.Transport),
|
||||
log.String("transport2", transport),
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
route.Addresses = append(route.Addresses, addr)
|
||||
}
|
||||
}
|
||||
return routes
|
||||
}
|
||||
|
||||
func (l Locator) registerEndpoint(
|
||||
mux *router.Router,
|
||||
routeKey domain.RouteKey,
|
||||
proxy Proxy,
|
||||
middlewares []http2.Middleware,
|
||||
) {
|
||||
handler := middleware.Entrypoint(maxMessageSize, routeKey.WithApiPrefix, proxy, l.logger)
|
||||
for i := range slices.Backward(middlewares) {
|
||||
handler = middlewares[i](handler)
|
||||
}
|
||||
|
||||
paths := []string{
|
||||
domain.ApiPrefix + routeKey.CleanPath, // стандартный маршрут c /api
|
||||
}
|
||||
if !routeKey.WithApiPrefix {
|
||||
paths = append(paths, routeKey.CleanPath) // для межмодульного взаимодействия
|
||||
}
|
||||
|
||||
for _, path := range paths {
|
||||
func() {
|
||||
defer func() {
|
||||
_ = recover()
|
||||
}()
|
||||
|
||||
mux.Handler(routeKey.Method, path,
|
||||
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), proxyTimeout)
|
||||
defer cancel()
|
||||
|
||||
err := handler(ctx, w, r)
|
||||
if err != nil {
|
||||
l.logger.Error(ctx, err)
|
||||
}
|
||||
}),
|
||||
)
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
// nolint:ireturn
|
||||
func buildProxy(
|
||||
transport string,
|
||||
addresses []string,
|
||||
) (Proxy, error) {
|
||||
switch transport {
|
||||
case cluster.HttpTransport:
|
||||
return proxy.NewHttp(addresses), nil
|
||||
|
||||
case cluster.GrpcTransport:
|
||||
cli, err := client.New(addresses, client.WithDialOptions(
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(maxMessageSize)),
|
||||
grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(maxMessageSize)),
|
||||
))
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "init grpc client")
|
||||
}
|
||||
return proxy.NewGrpc(cli), nil
|
||||
default:
|
||||
return nil, errors.Errorf("unknown transport '%s'", transport)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
configServiceAddress:
|
||||
ip: 127.0.0.1
|
||||
port: 9001
|
||||
grpcOuterAddress:
|
||||
#ip: 127.0.0.1
|
||||
port: 9015
|
||||
grpcInnerAddress:
|
||||
ip: 0.0.0.0
|
||||
port: 9015
|
||||
moduleName: isp-router-service
|
||||
|
||||
logfile:
|
||||
path: /var/log/isp-router-service/runtime.log
|
||||
maxSizeMb: 512
|
||||
maxBackups: 4
|
||||
compress: true
|
||||
|
||||
infraServerPort: 9565
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package conf
|
||||
|
||||
type Remote struct {
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package domain
|
||||
|
||||
const (
|
||||
ApiPrefix = "/api"
|
||||
GrpcApiPrefix = "api/"
|
||||
)
|
||||
@@ -0,0 +1,41 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
)
|
||||
|
||||
type HttpError struct {
|
||||
statusCode int
|
||||
userMessage string
|
||||
details []any
|
||||
err error
|
||||
}
|
||||
|
||||
func NewHttpError(statusCode int, userMessage string, internalError error) *HttpError {
|
||||
return &HttpError{
|
||||
statusCode: statusCode,
|
||||
userMessage: userMessage,
|
||||
err: internalError,
|
||||
}
|
||||
}
|
||||
|
||||
func (e *HttpError) Error() string {
|
||||
return e.err.Error()
|
||||
}
|
||||
|
||||
func (e *HttpError) WriteError(w http.ResponseWriter) error {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(e.statusCode)
|
||||
data := map[string]any{
|
||||
"errorCode": http.StatusText(e.statusCode),
|
||||
"errorMessage": e.userMessage,
|
||||
"details": e.details,
|
||||
}
|
||||
return json.NewEncoder(w).Encode(data) // nolint:wrapcheck
|
||||
}
|
||||
|
||||
func (e *HttpError) WithDetails(details ...any) {
|
||||
e.details = details
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type RequestContext struct {
|
||||
request *http.Request
|
||||
responseWriter http.ResponseWriter
|
||||
|
||||
endpoint string
|
||||
|
||||
queryParams map[string]string
|
||||
}
|
||||
|
||||
func NewContext(request *http.Request, response http.ResponseWriter, endpoint string) *RequestContext {
|
||||
return &RequestContext{
|
||||
request: request,
|
||||
responseWriter: response,
|
||||
endpoint: endpoint,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *RequestContext) Request() *http.Request {
|
||||
return c.request
|
||||
}
|
||||
|
||||
func (c *RequestContext) ResponseWriter() http.ResponseWriter {
|
||||
return c.responseWriter
|
||||
}
|
||||
|
||||
func (c *RequestContext) SetResponseWriter(writer http.ResponseWriter) {
|
||||
c.responseWriter = writer
|
||||
}
|
||||
|
||||
func (c *RequestContext) Endpoint() string {
|
||||
return c.endpoint
|
||||
}
|
||||
|
||||
func (c *RequestContext) Context() context.Context {
|
||||
return c.request.Context()
|
||||
}
|
||||
|
||||
func (c *RequestContext) SetContext(ctx context.Context) {
|
||||
c.request = c.request.WithContext(ctx)
|
||||
}
|
||||
|
||||
func (c *RequestContext) Param(name string) string {
|
||||
value := c.request.Header.Get(name)
|
||||
if value != "" {
|
||||
return strings.TrimSpace(value)
|
||||
}
|
||||
|
||||
if c.queryParams == nil {
|
||||
query := c.request.URL.Query()
|
||||
c.queryParams = map[string]string{}
|
||||
for key, values := range query {
|
||||
if len(values) == 0 {
|
||||
continue
|
||||
}
|
||||
c.queryParams[strings.ToLower(key)] = values[0]
|
||||
}
|
||||
}
|
||||
value = c.queryParams[strings.ToLower(name)]
|
||||
|
||||
return strings.TrimSpace(value)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package domain
|
||||
|
||||
type RouteKey struct {
|
||||
Method string
|
||||
CleanPath string
|
||||
WithApiPrefix bool
|
||||
}
|
||||
|
||||
type RouteConfig struct {
|
||||
Transport string
|
||||
Addresses []string
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
module isp-router-service
|
||||
|
||||
go 1.25
|
||||
|
||||
require (
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/stretchr/testify v1.11.1
|
||||
github.com/txix-open/isp-kit v1.64.8
|
||||
google.golang.org/grpc v1.75.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bahlo/generic-list-go v0.2.0 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/buger/jsonparser v1.1.1 // indirect
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/coder/websocket v1.8.14 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.10 // indirect
|
||||
github.com/getsentry/sentry-go v0.35.2 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/julienschmidt/httprouter v1.3.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/mailru/easyjson v0.9.0 // indirect
|
||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/prometheus/client_golang v1.23.2 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
github.com/prometheus/common v0.66.1 // indirect
|
||||
github.com/prometheus/procfs v0.17.0 // indirect
|
||||
github.com/txix-open/bellows v1.2.0 // indirect
|
||||
github.com/txix-open/etp/v4 v4.0.1 // indirect
|
||||
github.com/txix-open/jsonschema v1.3.0 // indirect
|
||||
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb // indirect
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.0 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.63.0 // indirect
|
||||
go.opentelemetry.io/otel v1.38.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.38.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk v1.38.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.38.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.8.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap v1.27.0 // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.3 // indirect
|
||||
golang.org/x/crypto v0.45.0 // indirect
|
||||
golang.org/x/net v0.47.0 // indirect
|
||||
golang.org/x/sys v0.38.0 // indirect
|
||||
golang.org/x/text v0.31.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250908214217-97024824d090 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250908214217-97024824d090 // indirect
|
||||
google.golang.org/protobuf v1.36.9 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
@@ -0,0 +1,177 @@
|
||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so=
|
||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
|
||||
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
|
||||
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs=
|
||||
github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
|
||||
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
|
||||
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g=
|
||||
github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
|
||||
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||
github.com/gabriel-vasile/mimetype v1.4.10 h1:zyueNbySn/z8mJZHLt6IPw0KoZsiQNszIpU+bX4+ZK0=
|
||||
github.com/gabriel-vasile/mimetype v1.4.10/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||
github.com/getsentry/sentry-go v0.35.2 h1:jKuujpRwa8FFRYMIwwZpu83Xh0voll9bmvyc6310WBM=
|
||||
github.com/getsentry/sentry-go v0.35.2/go.mod h1:mdL49ixwT2yi57k5eh7mpnDyPybixPzlzEJFu0Z76QA=
|
||||
github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=
|
||||
github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
|
||||
github.com/go-faker/faker/v4 v4.6.1 h1:xUyVpAjEtB04l6XFY0V/29oR332rOSPWV4lU8RwDt4k=
|
||||
github.com/go-faker/faker/v4 v4.6.1/go.mod h1:arSdxNCSt7mOhdk8tEolvHeIJ7eX4OX80wXjKKvkKBY=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-resty/resty/v2 v2.16.5 h1:hBKqmWrr7uRc3euHVqmh1HTHcKn99Smr7o5spptdhTM=
|
||||
github.com/go-resty/resty/v2 v2.16.5/go.mod h1:hkJtXbA2iKHzJheXYvQ8snQES5ZLGKMwQ07xAwp/fiA=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 h1:8Tjv8EJ+pM1xP8mK6egEbD1OgnVTyacbefKhmbLhIhU=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2/go.mod h1:pkJQ2tZHJ0aFOVEEot6oZmaVEZcRme73eIFmhiVuRWs=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
|
||||
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
|
||||
github.com/klauspost/compress v1.18.1 h1:bcSGx7UbpBqMChDtsF28Lw6v/G94LPrrbMbdC3JH2co=
|
||||
github.com/klauspost/compress v1.18.1/go.mod h1:ZQFFVG+MdnR0P+l6wpXgIL4NTtwiKIdBnrBd8Nrxr+0=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/mailru/easyjson v0.9.0 h1:PrnmzHw7262yW8sTBwxi1PdJA3Iw/EKBa8psRf7d9a4=
|
||||
github.com/mailru/easyjson v0.9.0/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
|
||||
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
|
||||
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4=
|
||||
github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
|
||||
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
|
||||
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
|
||||
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
|
||||
github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs=
|
||||
github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA=
|
||||
github.com/prometheus/procfs v0.17.0 h1:FuLQ+05u4ZI+SS/w9+BWEM2TXiHKsUQ9TADiRH7DuK0=
|
||||
github.com/prometheus/procfs v0.17.0/go.mod h1:oPQLaDAMRbA+u8H5Pbfq+dl3VDAvHxMUOVhe0wYB2zw=
|
||||
github.com/rabbitmq/amqp091-go v1.10.0 h1:STpn5XsHlHGcecLmMFCtg7mqq0RnD+zFr4uzukfVhBw=
|
||||
github.com/rabbitmq/amqp091-go v1.10.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/txix-open/bellows v1.2.0 h1:CXv8nQaZtB/micraeRilYyj/gtfv+bqBgP5aPYQgjeY=
|
||||
github.com/txix-open/bellows v1.2.0/go.mod h1:qbKCy+RTgD30Qpw1fyb3y3jp5Y9mGhLLxgae1l0W92o=
|
||||
github.com/txix-open/etp/v4 v4.0.1 h1:5VSYgGsvnMz0tvUHsjVWFETI0qWBTCF1O3ARCHaCIgA=
|
||||
github.com/txix-open/etp/v4 v4.0.1/go.mod h1:FIu7TUDdwcgmtmF6tFTV1bGA2fRY/iVaPQdsGzvqYc8=
|
||||
github.com/txix-open/grmq v1.9.0 h1:ArDbJJcFX9zXKEcPf49rp9nYiRyGMJxGKJAxdbSsfaM=
|
||||
github.com/txix-open/grmq v1.9.0/go.mod h1:EyFOP17KrwEFOUjR+PH8iH3LCtiN9TSQ8t0ysyk62po=
|
||||
github.com/txix-open/isp-kit v1.64.8 h1:nck8Gw5a7Jh6AVLqR2FihurrP5bTfeLUrodYB4j4+p4=
|
||||
github.com/txix-open/isp-kit v1.64.8/go.mod h1:GvBsX5p2U3/ugK6PuWANYzSy/4YgawROm3eAKb35G6o=
|
||||
github.com/txix-open/jsonschema v1.3.0 h1:XGuOTg22G7PdqfKypjajM20/i5FyGfFYsJKmheebKi4=
|
||||
github.com/txix-open/jsonschema v1.3.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00=
|
||||
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb h1:UJgT4u/QMv5QHKOQeJ7igShHa36c2/vIRqJiRLdDlf0=
|
||||
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb/go.mod h1:0biAFE0bgbcKeBBAwgEDhbZz6uT1vuSETCrFQlv2RiA=
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc=
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw=
|
||||
go.opentelemetry.io/auto/sdk v1.2.0 h1:YpRtUFjvhSymycLS2T81lT6IGhcUP+LUPtv0iv1N8bM=
|
||||
go.opentelemetry.io/auto/sdk v1.2.0/go.mod h1:1deq2zL7rwjwC8mR7XgY2N+tlIl6pjmEUoLDENMEzwk=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.63.0 h1:2pn7OzMewmYRiNtv1doZnLo3gONcnMHlFnmOR8Vgt+8=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.63.0/go.mod h1:rjbQTDEPQymPE0YnRQp9/NuPwwtL0sesz/fnqRW/v84=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0 h1:RbKq8BG0FI8OiXhBfcRtqqHcZcka+gU3cskNuf05R18=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.63.0/go.mod h1:h06DGIukJOevXaj/xrNjhi/2098RZzcLTbc0jDAUbsg=
|
||||
go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8=
|
||||
go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0 h1:GqRJVj7UmLjCVyVJ3ZFLdPRmhDUp2zFmQe3RHIOsw24=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.38.0/go.mod h1:ri3aaHSmCTVYu2AWv44YMauwAQc0aqI9gHKIcSbI1pU=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0 h1:aTL7F04bJHUlztTsNGJ2l+6he8c+y/b//eR0jjjemT4=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.38.0/go.mod h1:kldtb7jDTeol0l3ewcmd8SDvx3EmIE7lyvqbasU3QC4=
|
||||
go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA=
|
||||
go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI=
|
||||
go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E=
|
||||
go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA=
|
||||
go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE=
|
||||
go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs=
|
||||
go.opentelemetry.io/proto/otlp v1.8.0 h1:fRAZQDcAFHySxpJ1TwlA1cJ4tvcrw7nXl9xWWC8N5CE=
|
||||
go.opentelemetry.io/proto/otlp v1.8.0/go.mod h1:tIeYOeNBU4cvmPqpaji1P+KbB4Oloai8wN4rWzRrFF0=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
|
||||
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||
go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
|
||||
go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=
|
||||
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
|
||||
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
|
||||
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
|
||||
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
|
||||
golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=
|
||||
golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
|
||||
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
|
||||
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
|
||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250908214217-97024824d090 h1:d8Nakh1G+ur7+P3GcMjpRDEkoLUcLW2iU92XVqR+XMQ=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20250908214217-97024824d090/go.mod h1:U8EXRNSd8sUYyDfs/It7KVWodQr+Hf9xtxyxWudSwEw=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250908214217-97024824d090 h1:/OQuEa4YWtDt7uQWHd3q3sUMb+QOLQUg1xa8CEsRv5w=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250908214217-97024824d090/go.mod h1:GmFNa4BdJZ2a8G+wCe9Bg3wwThLrJun751XstdJt5Og=
|
||||
google.golang.org/grpc v1.75.1 h1:/ODCNEuf9VghjgO3rqLcfg8fiOP0nSluljWFlDxELLI=
|
||||
google.golang.org/grpc v1.75.1/go.mod h1:JtPAzKiq4v1xcAB2hydNlWI2RnF85XXcV0mhKXr2ecQ=
|
||||
google.golang.org/protobuf v1.36.9 h1:w2gp2mA27hUeUzj9Ex9FBjsBm40zfaDtEWow293U7Iw=
|
||||
google.golang.org/protobuf v1.36.9/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,35 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"isp-router-service/assembly"
|
||||
"isp-router-service/conf"
|
||||
|
||||
"github.com/txix-open/isp-kit/bootstrap"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/shutdown"
|
||||
)
|
||||
|
||||
var (
|
||||
version = "1.0.0"
|
||||
)
|
||||
|
||||
func main() {
|
||||
boot := bootstrap.New(version, conf.Remote{}, nil, cluster.HttpTransport)
|
||||
app := boot.App
|
||||
logger := app.Logger()
|
||||
|
||||
assembly := assembly.New(boot)
|
||||
app.AddRunners(assembly.Runners()...)
|
||||
app.AddClosers(assembly.Closers()...)
|
||||
|
||||
shutdown.On(func() {
|
||||
logger.Info(app.Context(), "starting shutdown")
|
||||
app.Shutdown()
|
||||
logger.Info(app.Context(), "shutdown completed")
|
||||
})
|
||||
|
||||
err := app.Run()
|
||||
if err != nil {
|
||||
boot.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"isp-router-service/domain"
|
||||
"net/http"
|
||||
|
||||
http2 "github.com/txix-open/isp-kit/http"
|
||||
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
type Proxy interface {
|
||||
Handle(ctx *domain.RequestContext) error
|
||||
PrepareEndpoint(endpoint string, proxyApiPrefix bool) string
|
||||
}
|
||||
|
||||
func Entrypoint(
|
||||
maxMessageSize int64,
|
||||
proxyApiPrefix bool,
|
||||
proxy Proxy,
|
||||
logger log.Logger,
|
||||
) http2.HandlerFunc {
|
||||
return http2.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxMessageSize)
|
||||
|
||||
endpoint := proxy.PrepareEndpoint(r.URL.Path, proxyApiPrefix)
|
||||
reqCtx := domain.NewContext(r, w, endpoint)
|
||||
reqCtx.SetContext(ctx)
|
||||
|
||||
return proxy.Handle(reqCtx)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"isp-router-service/domain"
|
||||
|
||||
http2 "github.com/txix-open/isp-kit/http"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
type HttpError interface {
|
||||
WriteError(w http.ResponseWriter) error
|
||||
}
|
||||
|
||||
func ErrorHandler(logger log.Logger) http2.Middleware {
|
||||
return func(next http2.HandlerFunc) http2.HandlerFunc {
|
||||
return http2.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
|
||||
err := next(ctx, w, r)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
logger.Error(ctx, err)
|
||||
|
||||
httpErr, ok := err.(HttpError)
|
||||
if ok {
|
||||
return httpErr.WriteError(w)
|
||||
}
|
||||
|
||||
return domain.NewHttpError(http.StatusInternalServerError, "internal service error", err).
|
||||
WriteError(w)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
// nolint:wrapcheck
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"io"
|
||||
"isp-router-service/domain"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
"github.com/txix-open/isp-kit/requestid"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// nolint:gochecknoinits
|
||||
func init() {
|
||||
for httpCode, grpcCode := range codeMap {
|
||||
inverseCodeMap[grpcCode] = httpCode
|
||||
}
|
||||
}
|
||||
|
||||
// nolint:gochecknoglobals
|
||||
var (
|
||||
codeMap = map[int]codes.Code{
|
||||
http.StatusOK: codes.OK,
|
||||
http.StatusRequestTimeout: codes.Canceled,
|
||||
http.StatusBadRequest: codes.InvalidArgument,
|
||||
http.StatusGatewayTimeout: codes.DeadlineExceeded,
|
||||
http.StatusNotFound: codes.NotFound,
|
||||
http.StatusConflict: codes.AlreadyExists,
|
||||
http.StatusForbidden: codes.PermissionDenied,
|
||||
http.StatusUnauthorized: codes.Unauthenticated,
|
||||
http.StatusTooManyRequests: codes.ResourceExhausted,
|
||||
http.StatusPreconditionFailed: codes.FailedPrecondition,
|
||||
http.StatusNotImplemented: codes.Unimplemented,
|
||||
http.StatusInternalServerError: codes.Internal,
|
||||
http.StatusServiceUnavailable: codes.Unavailable,
|
||||
}
|
||||
inverseCodeMap = map[codes.Code]int{}
|
||||
)
|
||||
|
||||
type Grpc struct {
|
||||
cli *client.Client
|
||||
}
|
||||
|
||||
func NewGrpc(cli *client.Client) Grpc {
|
||||
return Grpc{
|
||||
cli: cli,
|
||||
}
|
||||
}
|
||||
|
||||
func (p Grpc) PrepareEndpoint(endpoint string, proxyApiPrefix bool) string {
|
||||
endpoint = strings.TrimPrefix(endpoint, "/")
|
||||
if proxyApiPrefix {
|
||||
return endpoint
|
||||
}
|
||||
|
||||
// api/endpoint -> endpoint
|
||||
return strings.TrimPrefix(endpoint, domain.GrpcApiPrefix)
|
||||
}
|
||||
|
||||
func (p Grpc) Handle(ctx *domain.RequestContext) error {
|
||||
body, err := io.ReadAll(ctx.Request().Body)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "grpc: read body")
|
||||
}
|
||||
|
||||
requestId := requestid.FromContext(ctx.Context())
|
||||
|
||||
md := httpHeadersToGrpcMetadata(ctx.Request().Header)
|
||||
md.Set(grpc.ProxyMethodNameHeader, ctx.Endpoint())
|
||||
|
||||
requestContext := metadata.NewOutgoingContext(ctx.Context(), md)
|
||||
|
||||
result, err := p.cli.BackendClient().Request(requestContext, &isp.Message{
|
||||
Body: &isp.Message_BytesBody{BytesBody: body},
|
||||
})
|
||||
if err != nil {
|
||||
return p.writeGrpcError(err, ctx.ResponseWriter(), ctx.Endpoint(), requestId)
|
||||
}
|
||||
|
||||
return p.writeResponse(http.StatusOK, result.GetBytesBody(), requestId, ctx.ResponseWriter())
|
||||
}
|
||||
|
||||
func (p Grpc) Close() error {
|
||||
return p.cli.Close()
|
||||
}
|
||||
|
||||
func (p Grpc) writeGrpcError(err error, w http.ResponseWriter, endpoint string, requestId string) error {
|
||||
status, ok := status.FromError(err)
|
||||
if !ok {
|
||||
return domain.NewHttpError(
|
||||
http.StatusServiceUnavailable,
|
||||
"upstream is not available",
|
||||
errors.WithMessage(err, "grpc proxy"),
|
||||
)
|
||||
}
|
||||
|
||||
statusCode := p.codeToHttpStatus(status.Code())
|
||||
for _, detail := range status.Details() {
|
||||
switch typeOfDetail := detail.(type) {
|
||||
case *isp.Message:
|
||||
switch {
|
||||
case typeOfDetail.GetBytesBody() != nil:
|
||||
return p.writeResponse(statusCode, typeOfDetail.GetBytesBody(), requestId, w)
|
||||
case typeOfDetail.GetListBody() != nil:
|
||||
return p.writeProto(statusCode, typeOfDetail.GetListBody(), requestId, w)
|
||||
case typeOfDetail.GetStructBody() != nil:
|
||||
return p.writeProto(statusCode, typeOfDetail.GetStructBody(), requestId, w)
|
||||
}
|
||||
default:
|
||||
return p.writeProto(statusCode, typeOfDetail, requestId, w)
|
||||
}
|
||||
}
|
||||
|
||||
return domain.NewHttpError(
|
||||
statusCode,
|
||||
status.Message(),
|
||||
errors.WithMessagef(err, "proxy '%s'", endpoint),
|
||||
)
|
||||
}
|
||||
|
||||
func (p Grpc) writeProto(statusCode int, proto any, requestId string, w http.ResponseWriter) error {
|
||||
data, err := json.Marshal(proto)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "marshal grpc details to json")
|
||||
}
|
||||
return p.writeResponse(statusCode, data, requestId, w)
|
||||
}
|
||||
|
||||
func (p Grpc) writeResponse(statusCode int, data []byte, requestId string, w http.ResponseWriter) error {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
if requestId != "" {
|
||||
w.Header().Set(requestid.Header, requestId)
|
||||
}
|
||||
w.WriteHeader(statusCode)
|
||||
_, err := w.Write(data)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "response write")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p Grpc) codeToHttpStatus(code codes.Code) int {
|
||||
s, ok := inverseCodeMap[code]
|
||||
if !ok {
|
||||
return http.StatusInternalServerError
|
||||
}
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
func httpHeadersToGrpcMetadata(h http.Header) metadata.MD {
|
||||
md := metadata.MD{}
|
||||
for header, values := range h {
|
||||
header = strings.ToLower(header)
|
||||
if strings.HasPrefix(header, "x-") {
|
||||
md.Set(header, values...)
|
||||
}
|
||||
}
|
||||
return md
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"isp-router-service/domain"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/lb"
|
||||
)
|
||||
|
||||
// nolint:gochecknoglobals,mnd
|
||||
var (
|
||||
httpTransport = &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: defaultTransportDialContext(&net.Dialer{
|
||||
Timeout: 3 * time.Second,
|
||||
KeepAlive: 90 * time.Second,
|
||||
}),
|
||||
ForceAttemptHTTP2: true,
|
||||
MaxIdleConns: 1024,
|
||||
MaxIdleConnsPerHost: 256,
|
||||
IdleConnTimeout: 60 * time.Second,
|
||||
TLSHandshakeTimeout: 5 * time.Second,
|
||||
ExpectContinueTimeout: 1 * time.Second,
|
||||
}
|
||||
)
|
||||
|
||||
type Http struct {
|
||||
hostManager *lb.RoundRobin
|
||||
proxies map[string]*httputil.ReverseProxy
|
||||
}
|
||||
|
||||
func NewHttp(addresses []string) Http {
|
||||
p := Http{
|
||||
hostManager: lb.NewRoundRobin(addresses),
|
||||
proxies: make(map[string]*httputil.ReverseProxy),
|
||||
}
|
||||
|
||||
for _, addr := range addresses {
|
||||
target, _ := url.Parse("http://" + addr)
|
||||
proxy := httputil.NewSingleHostReverseProxy(target)
|
||||
proxy.Transport = httpTransport
|
||||
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
|
||||
_ = domain.NewHttpError(
|
||||
http.StatusServiceUnavailable,
|
||||
"upstream is not available",
|
||||
errors.WithMessagef(err, "http proxy to %s", addr),
|
||||
).WriteError(w)
|
||||
}
|
||||
p.proxies[addr] = proxy
|
||||
}
|
||||
|
||||
return p
|
||||
}
|
||||
|
||||
func (p Http) PrepareEndpoint(endpoint string, proxyApiPrefix bool) string {
|
||||
if proxyApiPrefix {
|
||||
return endpoint
|
||||
}
|
||||
return strings.TrimPrefix(endpoint, domain.ApiPrefix)
|
||||
}
|
||||
|
||||
func (p Http) Handle(ctx *domain.RequestContext) error {
|
||||
host, err := p.hostManager.Next()
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "http: next host")
|
||||
}
|
||||
|
||||
proxy := p.proxies[host]
|
||||
|
||||
req := ctx.Request()
|
||||
req.URL.Scheme = "http"
|
||||
req.URL.Host = host
|
||||
req.Host = host
|
||||
req.URL.Path = ctx.Endpoint()
|
||||
|
||||
proxy.ServeHTTP(ctx.ResponseWriter(), req)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p Http) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func defaultTransportDialContext(dialer *net.Dialer) func(context.Context, string, string) (net.Conn, error) {
|
||||
return dialer.DialContext
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
// nolint:unparam,funlen
|
||||
package tests_test
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"isp-router-service/assembly"
|
||||
"isp-router-service/service/proxy"
|
||||
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
endpoint2 "github.com/txix-open/isp-kit/grpc/endpoint"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type AcceptanceTestSuite struct {
|
||||
suite.Suite
|
||||
|
||||
test *test.Test
|
||||
grpcMock *GrpcMockServer
|
||||
httpMocks []*httpt.MockServer
|
||||
proxyCli *httpcli.Client
|
||||
routing cluster.RoutingConfig
|
||||
}
|
||||
|
||||
func TestAcceptance(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, new(AcceptanceTestSuite))
|
||||
}
|
||||
|
||||
func (s *AcceptanceTestSuite) SetupSuite() {
|
||||
t, require := test.New(s.T())
|
||||
s.test = t
|
||||
|
||||
var grpcMockAddr string
|
||||
s.grpcMock, grpcMockAddr = newGrpcMockWithEndpoints(t, map[string]any{
|
||||
"grpc/alive_backend/endpoint": func() string { return "GRPC_OK" },
|
||||
"api/grpc/alive_backend/endpoint_v2": func() string { return "GRPC_API" },
|
||||
"grpc/alive_backend/endpoint_with_error": func() error {
|
||||
return status.Error(codes.FailedPrecondition, "test error")
|
||||
},
|
||||
})
|
||||
host, port, err := net.SplitHostPort(grpcMockAddr)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.routing = cluster.RoutingConfig{
|
||||
{
|
||||
ModuleName: "dead_backend",
|
||||
Version: "1.0.0",
|
||||
LibVersion: "1.0.0",
|
||||
Transport: "http",
|
||||
Endpoints: []cluster.EndpointDescriptor{
|
||||
{HttpMethod: http.MethodPost, Path: "dead_backend/endpoint"},
|
||||
},
|
||||
Address: cluster.AddressConfiguration{IP: "unknownhost", Port: "0"},
|
||||
},
|
||||
cluster.BackendDeclaration{
|
||||
ModuleName: "alive_backend",
|
||||
Version: "1.0.0",
|
||||
LibVersion: "1.0.0",
|
||||
Endpoints: []cluster.EndpointDescriptor{
|
||||
{Path: "grpc/alive_backend/endpoint"},
|
||||
{Path: "api/grpc/alive_backend/endpoint_v2"},
|
||||
{Path: "grpc/alive_backend/endpoint_with_error"},
|
||||
},
|
||||
Address: cluster.AddressConfiguration{
|
||||
IP: host,
|
||||
Port: port,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
s.httpMocks = []*httpt.MockServer{}
|
||||
handlers := map[string]any{
|
||||
"/alive_backend/endpoint": func() string {
|
||||
return "HTTP_OK"
|
||||
},
|
||||
"/api/alive_backend/endpoint_v2": func() string {
|
||||
return "HTTP_API"
|
||||
},
|
||||
"/alive_backend/endpoint_with_error": func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "test error", http.StatusPreconditionFailed)
|
||||
},
|
||||
}
|
||||
for range 2 {
|
||||
mock := httpt.NewMock(t)
|
||||
for path, h := range handlers {
|
||||
mock.Mock(http.MethodGet, path, h)
|
||||
mock.Mock(http.MethodPost, path, h)
|
||||
}
|
||||
s.httpMocks = append(s.httpMocks, mock)
|
||||
}
|
||||
|
||||
for _, mock := range s.httpMocks {
|
||||
hostPort := strings.TrimPrefix(mock.BaseURL(), "http://")
|
||||
h, p, err := net.SplitHostPort(hostPort)
|
||||
require.NoError(err)
|
||||
s.routing = append(s.routing, cluster.BackendDeclaration{
|
||||
ModuleName: "alive_backend",
|
||||
Version: "1.0.0",
|
||||
LibVersion: "1.0.0",
|
||||
Transport: "http",
|
||||
Endpoints: []cluster.EndpointDescriptor{
|
||||
{HttpMethod: http.MethodGet, Path: "alive_backend/endpoint"},
|
||||
{HttpMethod: http.MethodGet, Path: "/api/alive_backend/endpoint_v2"},
|
||||
{HttpMethod: http.MethodPost, Path: "alive_backend/endpoint_with_error"},
|
||||
},
|
||||
Address: cluster.AddressConfiguration{
|
||||
IP: h,
|
||||
Port: p,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
locator := assembly.NewLocator(s.test.Logger())
|
||||
|
||||
mock, mockCli := grpct.NewMock(s.test)
|
||||
mock.Mock("reuse_backend/endpoint", func() string { return "REUSE" })
|
||||
|
||||
reuseProxy := map[assembly.ProxyKey]assembly.Proxy{
|
||||
{Transport: "grpc", Addresses: "host:port"}: proxy.NewGrpc(mockCli),
|
||||
}
|
||||
|
||||
s.routing = append(s.routing,
|
||||
cluster.BackendDeclaration{
|
||||
ModuleName: "reuse_backend",
|
||||
Version: "1.0.0",
|
||||
LibVersion: "1.0.0",
|
||||
Endpoints: []cluster.EndpointDescriptor{
|
||||
{Path: "reuse_backend/endpoint"},
|
||||
},
|
||||
Address: cluster.AddressConfiguration{
|
||||
IP: "host",
|
||||
Port: "port",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
locatorCfg := locator.LocatorConfig(s.routing, reuseProxy)
|
||||
_, s.proxyCli = httpt.TestServer(t, locatorCfg.Handler)
|
||||
}
|
||||
|
||||
func (s *AcceptanceTestSuite) TestUnknownEndpoint() {
|
||||
s.assertStatus(http.MethodPost, "/api/unknown_endpoint", http.StatusNotImplemented)
|
||||
s.assertStatus(http.MethodPost, "/unknown_endpoint", http.StatusNotImplemented)
|
||||
}
|
||||
|
||||
func (s *AcceptanceTestSuite) TestDeadBackend() {
|
||||
s.assertStatus(http.MethodPost, "/api/dead_backend/endpoint", http.StatusServiceUnavailable)
|
||||
s.assertStatus(http.MethodPost, "/dead_backend/endpoint", http.StatusServiceUnavailable)
|
||||
}
|
||||
|
||||
func (s *AcceptanceTestSuite) TestGrpcReuseEndpoint() {
|
||||
s.assertJsonResponse(http.MethodPost, "api/reuse_backend/endpoint", "REUSE")
|
||||
s.assertJsonResponse(http.MethodPost, "reuse_backend/endpoint", "REUSE")
|
||||
}
|
||||
|
||||
func (s *AcceptanceTestSuite) TestGrpcAliveEndpoint() {
|
||||
s.assertJsonResponse(http.MethodPost, "api/grpc/alive_backend/endpoint", "GRPC_OK")
|
||||
s.assertJsonResponse(http.MethodPost, "grpc/alive_backend/endpoint", "GRPC_OK")
|
||||
}
|
||||
|
||||
func (s *AcceptanceTestSuite) TestGrpcAliveApiEndpoint() {
|
||||
s.assertJsonResponse(http.MethodPost, "api/grpc/alive_backend/endpoint_v2", "GRPC_API")
|
||||
}
|
||||
|
||||
func (s *AcceptanceTestSuite) TestGrpcEndpointWithError() {
|
||||
s.assertStatus(http.MethodPost, "api/grpc/alive_backend/endpoint_with_error", http.StatusPreconditionFailed)
|
||||
s.assertStatus(http.MethodPost, "grpc/alive_backend/endpoint_with_error", http.StatusPreconditionFailed)
|
||||
}
|
||||
|
||||
func (s *AcceptanceTestSuite) TestHttpAliveEndpoint() {
|
||||
s.assertJsonResponse(http.MethodGet, "/api/alive_backend/endpoint", "HTTP_OK")
|
||||
s.assertJsonResponse(http.MethodGet, "/alive_backend/endpoint", "HTTP_OK")
|
||||
}
|
||||
|
||||
func (s *AcceptanceTestSuite) TestHttpAliveApiEndpoint() {
|
||||
s.assertJsonResponse(http.MethodGet, "/api/alive_backend/endpoint_v2", "HTTP_API")
|
||||
}
|
||||
|
||||
func (s *AcceptanceTestSuite) TestHttpEndpointWithError() {
|
||||
s.assertStatus(http.MethodPost, "/api/alive_backend/endpoint_with_error", http.StatusPreconditionFailed)
|
||||
s.assertStatus(http.MethodPost, "/alive_backend/endpoint_with_error", http.StatusPreconditionFailed)
|
||||
}
|
||||
|
||||
func (s *AcceptanceTestSuite) assertStatus(method, path string, expected int) {
|
||||
reqBuilder := httpcli.NewRequestBuilder(method, path, s.proxyCli.GlobalRequestConfig(), s.proxyCli.Execute)
|
||||
resp, err := reqBuilder.Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
s.Require().Equal(expected, resp.StatusCode())
|
||||
resp.Close()
|
||||
}
|
||||
|
||||
func (s *AcceptanceTestSuite) assertJsonResponse(method, path string, expected any) {
|
||||
var resultRaw json.RawMessage
|
||||
|
||||
reqBuilder := httpcli.NewRequestBuilder(method, path, s.proxyCli.GlobalRequestConfig(), s.proxyCli.Execute)
|
||||
err := reqBuilder.StatusCodeToError().JsonResponseBody(&resultRaw).DoWithoutResponse(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
expectedRaw, err := json.Marshal(expected)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().JSONEq(string(expectedRaw), string(resultRaw))
|
||||
}
|
||||
|
||||
type GrpcMockServer struct {
|
||||
srv *grpc.Server
|
||||
logger log.Logger
|
||||
mockEndpoints map[string]any
|
||||
}
|
||||
|
||||
func newGrpcMockWithEndpoints(t *test.Test, endpoints map[string]any) (*GrpcMockServer, string) {
|
||||
srv, addr := grpcServer(t, grpc.NewMux())
|
||||
mock := &GrpcMockServer{
|
||||
srv: srv,
|
||||
logger: t.Logger(),
|
||||
mockEndpoints: make(map[string]any),
|
||||
}
|
||||
for ep, h := range endpoints {
|
||||
mock.Mock(ep, h)
|
||||
}
|
||||
return mock, addr
|
||||
}
|
||||
|
||||
func (m *GrpcMockServer) Mock(endpoint string, handler any) *GrpcMockServer {
|
||||
m.mockEndpoints[endpoint] = handler
|
||||
wrapper := endpoint2.DefaultWrapper(m.logger)
|
||||
muxer := grpc.NewMux()
|
||||
for e, h := range m.mockEndpoints {
|
||||
muxer.Handle(e, wrapper.Endpoint(h))
|
||||
}
|
||||
m.srv.Upgrade(muxer)
|
||||
return m
|
||||
}
|
||||
|
||||
func grpcServer(t *test.Test, service isp.BackendServiceServer) (*grpc.Server, string) {
|
||||
assert := t.Assert()
|
||||
|
||||
// nolint:noctx
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:")
|
||||
assert.NoError(err)
|
||||
srv := grpc.NewServer()
|
||||
assert.NoError(err)
|
||||
t.T().Cleanup(func() {
|
||||
srv.Shutdown()
|
||||
})
|
||||
srv.Upgrade(service)
|
||||
go func() {
|
||||
err := srv.Serve(listener)
|
||||
assert.NoError(err)
|
||||
}()
|
||||
return srv, listener.Addr().String()
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package tests_test
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"isp-router-service/assembly"
|
||||
"isp-router-service/service/proxy"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
)
|
||||
|
||||
func BenchmarkProxy_HTTP(b *testing.B) {
|
||||
test, _ := test.New(&testing.T{})
|
||||
require := require.New(b)
|
||||
|
||||
logger, err := log.New(log.WithDisableDefaultOutput())
|
||||
require.NoError(err)
|
||||
|
||||
mockServ := httpt.NewMock(test)
|
||||
mockServ.Wrapper.Middlewares = nil
|
||||
mockServ.Mock(http.MethodGet, "/alive_backend/endpoint", func() string { return "OK" })
|
||||
|
||||
hostPort := strings.TrimPrefix(mockServ.BaseURL(), "http://")
|
||||
h, p, err := net.SplitHostPort(hostPort)
|
||||
require.NoError(err)
|
||||
|
||||
routing := cluster.RoutingConfig{
|
||||
cluster.BackendDeclaration{
|
||||
ModuleName: "alive_backend",
|
||||
Version: "1.0.0",
|
||||
LibVersion: "1.0.0",
|
||||
Transport: "http",
|
||||
Endpoints: []cluster.EndpointDescriptor{
|
||||
{HttpMethod: http.MethodGet, Path: "alive_backend/endpoint"},
|
||||
},
|
||||
Address: cluster.AddressConfiguration{
|
||||
IP: h,
|
||||
Port: p,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
locator := assembly.NewLocator(logger)
|
||||
cfg := locator.LocatorConfig(routing, make(map[assembly.ProxyKey]assembly.Proxy))
|
||||
|
||||
_, proxyCli := httpt.TestServer(test, cfg.Handler)
|
||||
|
||||
b.ResetTimer()
|
||||
b.ReportAllocs()
|
||||
b.SetParallelism(32)
|
||||
b.RunParallel(func(p *testing.PB) {
|
||||
for p.Next() {
|
||||
_ = proxyCli.Get("/api/alive_backend/endpoint").
|
||||
DoWithoutResponse(b.Context())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func BenchmarkProxy_GRPC(b *testing.B) {
|
||||
test, _ := test.New(&testing.T{})
|
||||
require := require.New(b)
|
||||
|
||||
logger, err := log.New(log.WithDisableDefaultOutput())
|
||||
require.NoError(err)
|
||||
|
||||
routing := cluster.RoutingConfig{
|
||||
cluster.BackendDeclaration{
|
||||
ModuleName: "alive_backend",
|
||||
Version: "1.0.0",
|
||||
LibVersion: "1.0.0",
|
||||
Endpoints: []cluster.EndpointDescriptor{
|
||||
{Path: "alive_backend/endpoint"},
|
||||
},
|
||||
Address: cluster.AddressConfiguration{
|
||||
IP: "host",
|
||||
Port: "port",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
mock, mockCli := grpct.NewMock(test)
|
||||
mock.Mock("alive_backend/endpoint", func() string { return "OK" })
|
||||
|
||||
locator := assembly.NewLocator(logger)
|
||||
reuseProxy := map[assembly.ProxyKey]assembly.Proxy{
|
||||
{Transport: "grpc", Addresses: "host:port"}: proxy.NewGrpc(mockCli),
|
||||
}
|
||||
cfg := locator.LocatorConfig(routing, reuseProxy)
|
||||
|
||||
_, proxyCli := httpt.TestServer(test, cfg.Handler)
|
||||
|
||||
b.ResetTimer()
|
||||
b.ReportAllocs()
|
||||
b.SetParallelism(32)
|
||||
b.RunParallel(func(p *testing.PB) {
|
||||
for p.Next() {
|
||||
_ = proxyCli.Post("/api/alive_backend/endpoint").
|
||||
DoWithoutResponse(b.Context())
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user