129 Commits
Author SHA1 Message Date
Demidyuk Oleg 48f0aaa40c MSP-3428 CRUD application_group, service -> application_group 2024-06-17 12:58:07 +03:00
Demidyuk Oleg 09ec0b3f88 MSP-3428 CRUD application_group, service -> application_group 2024-06-14 12:01:06 +03:00
Demidyuk Oleg bef400d0d9 MSP-3428 CRUD application_group, service -> application_group 2024-06-13 18:09:25 +03:00
Demidyuk Oleg 7108122102 MSP-3428 fix linter 2024-06-11 13:25:01 +03:00
Demidyuk Oleg 8b8bc04fbf MSP-3428 migrated to go 1.22 2024-06-11 12:56:14 +03:00
user 9de75322e5 MSP-3428 integration-system -> txix-open 2024-06-11 12:40:42 +03:00
Demidyuk Oleg 51dfcdb9ba MSP-3428 migrated to go 1.22 2024-06-11 12:40:10 +03:00
Кузьмин Игорь Александрович f062aada42 Update README.md 2024-03-26 11:25:59 +00:00
Кузьмин Игорь Александрович 81c5af7538 Add README.md 2024-03-26 09:18:49 +00:00
Кузьмин Игорь c0b47ef9c6 Upload New File 2023-05-10 08:47:42 +00:00
Кузьмин Игорь bbec75c8a1 Upload New File 2023-05-10 08:38:55 +00:00
komissarovyv 7ca053a733 Merge branch 'MSP-634' into 'master'
Resolve MSP-634

Closes MSP-634

See merge request integration-system/isp-system-service!8
2022-08-05 09:27:33 +00:00
DeniskaRediska 24b80af7da MSP-634 up version 2022-08-04 22:13:47 +03:00
d1slike 42a2ceb9c9 MSP-634 remove defaultExpireTime 2022-08-04 22:13:28 +03:00
d1slike 231792aefa MSP-634 replace jwt to simple crypto rand 2022-08-04 22:13:28 +03:00
d1slike 2ea518d902 MSP-634 allow for appId 1 login endpoint 2022-08-04 22:13:28 +03:00
d1slike 13e8ff0ed8 MSP-634 Actualize local config 2022-08-04 22:13:28 +03:00
DeniskaRediska 66d8645f4a MSP-634 add secure controller tests 2022-08-04 22:13:28 +03:00
DeniskaRediska 53cab90a5b MSP-634 add general insert db for tests 2022-08-04 22:13:28 +03:00
DeniskaRediska dd41024768 MSP-634 add secure endpoints to routes 2022-08-04 22:13:28 +03:00
DeniskaRediska fff9ddcbf8 MSP-634 implement secure service 2022-08-04 22:13:28 +03:00
DeniskaRediska f65dd9c2aa MSP-634 update swagger 2022-08-04 22:13:28 +03:00
DeniskaRediska 0d61264e73 MSP-634 implement secure controller 2022-08-04 22:13:28 +03:00
DeniskaRediska cbc9d0643a MSP-634 implement secure domain 2022-08-04 22:13:28 +03:00
DeniskaRediska e5d73d91de MSP-634 add func get_auth_data to token repository 2022-08-04 22:13:28 +03:00
DeniskaRediska bb0d2b460a MSP-634 add func get_access_list_by_app_id to access_list repository 2022-08-04 22:13:28 +03:00
DeniskaRediska ab89a27053 MSP-634 add new domain error 2022-08-04 22:13:28 +03:00
DeniskaRediska 132830bf6f MSP-634 update dependencies 2022-08-04 22:13:28 +03:00
DeniskaRediska c3e71c0c7e MSP-634 fix migration 2022-08-01 17:59:25 +03:00
DeniskaRediska b0d60603bb MSP-634 remove instanceUuid from local config 2022-08-01 14:07:31 +03:00
DeniskaRediska 894781c727 MSP-634 remove redis 2022-08-01 14:07:31 +03:00
Грязнов Денис Владимирович 82a2d8d98f Merge branch 'MSP-841' into 'master'
Resolve MSP-841

Closes MSP-841

See merge request integration-system/isp-system-service!7
2022-07-25 08:58:04 +00:00
DeniskaRediska ab07db354b MSP-841 up version 2022-07-22 14:22:03 +03:00
DeniskaRediska e1f081bf63 MSP-841 fix panic when update application 2022-07-22 14:21:46 +03:00
DeniskaRediska bcd4083dd9 MSP-841 update dependencies 2022-07-22 14:20:46 +03:00
Комиссаров Ян Вадимович 74aba7fcfe Update default_remote_config.json 2022-07-07 12:32:32 +00:00
Комиссаров Ян Вадимович 29348a3c39 Update config.yml 2022-07-07 12:26:02 +00:00
Комиссаров Ян Вадимович ea83597b19 Update default_remote_config.json 2022-07-07 12:20:27 +00:00
Комиссаров Ян Вадимович 4c88184112 Fix schema name 2022-07-07 12:17:27 +00:00
d1slike 8efe886a84 Mark InstanceUuid as required 2022-06-21 13:22:34 +03:00
Грязнов Денис Владимирович 636a901c66 Merge branch 'MSP-623' into 'master'
Resolve MSP-623

Closes MSP-623

See merge request integration-system/isp-system-service!6
2022-06-07 09:49:58 +00:00
DeniskaRediska b139590408 MSP-623 up version 2022-06-07 10:33:07 +03:00
DeniskaRediska ceeb2f03be MSP-623 update swagger 2022-06-07 10:33:07 +03:00
DeniskaRediska 1a90f50218 MSP-623 remove log code 2022-06-07 10:33:07 +03:00
DeniskaRediska ce75f8933c MSP-623 update main 2022-06-07 10:33:07 +03:00
DeniskaRediska f40b91a431 MSP-623 update linter 2022-06-07 10:33:07 +03:00
DeniskaRediska 9c1fc87430 MSP-623 update gitignore 2022-06-07 10:33:07 +03:00
DeniskaRediska 9b8432bb4c MSP-623 update go mod 2022-06-07 10:33:07 +03:00
DeniskaRediska 8deb2a2e38 MSP-623 add assembly 2022-06-06 15:44:28 +03:00
DeniskaRediska 2863f95a97 MSP-623 update config 2022-06-06 15:44:28 +03:00
DeniskaRediska a7feb4e234 MSP-623 refactoring initialize migration 2022-06-06 15:44:28 +03:00
DeniskaRediska 7b5ca9d12c MSP-623 reimplement routes 2022-06-06 15:44:28 +03:00
DeniskaRediska 9db858b0e2 MSP-623 reimplement domain controller 2022-06-06 15:44:28 +03:00
DeniskaRediska b429c0b6fc MSP-623 reimplement access_list controller 2022-06-06 15:44:28 +03:00
DeniskaRediska 82fd46b056 MSP-623 reimplement application controller 2022-06-06 15:44:28 +03:00
DeniskaRediska da4156afde MSP-623 reimplement service controller 2022-06-06 15:44:28 +03:00
DeniskaRediska ed5cb04ed3 MSP-623 reimplement token controller 2022-06-06 15:44:28 +03:00
DeniskaRediska e0fc90e4d4 MSP-623 remove system controller 2022-06-06 15:44:28 +03:00
DeniskaRediska 97fcc21fc6 MSP-623 reimplement redis cli 2022-06-06 15:44:28 +03:00
DeniskaRediska 3d9c516cfb MSP-623 implement transaction manager 2022-06-06 15:44:28 +03:00
DeniskaRediska 1ba15f4532 MSP-623 implement access_list service 2022-06-06 15:44:28 +03:00
DeniskaRediska 27d727823f MSP-623 implement application service 2022-06-06 15:44:28 +03:00
DeniskaRediska 6a120d6caa MSP-623 implement domain service 2022-06-06 15:44:28 +03:00
DeniskaRediska 0e22b988b2 MSP-623 implement token service 2022-06-06 15:44:28 +03:00
DeniskaRediska c0994fa5f1 MSP-623 implement service service 2022-06-06 15:44:28 +03:00
DeniskaRediska 1512fe33ce MSP-623 update jwt service 2022-06-06 15:44:27 +03:00
DeniskaRediska 0934f8136f MSP-623 split entity 2022-06-06 15:44:27 +03:00
DeniskaRediska 4b5412e21b MSP-623 add migration to set value access_list to not null 2022-06-06 15:44:27 +03:00
DeniskaRediska bb36c55746 MSP-623 remove global db client 2022-06-06 15:44:27 +03:00
DeniskaRediska 203c802071 MSP-623 reimplement domain repository 2022-06-06 15:44:27 +03:00
DeniskaRediska cc94ca71a4 MSP-623 reimplement access_list repository 2022-06-06 15:44:27 +03:00
DeniskaRediska a7c58f86ec MSP-623 reimplement application repository 2022-06-06 15:44:27 +03:00
DeniskaRediska 0f4c57cb67 MSP-623 reimplement token repository 2022-06-06 15:44:27 +03:00
DeniskaRediska bd7a06f8f0 MSP-623 reimplement service repository 2022-06-06 15:44:27 +03:00
DeniskaRediska 8c4393b861 MSP-623 remove system repository 2022-06-06 15:44:27 +03:00
DeniskaRediska 228b04e01d MSP-623 add domain structs 2022-06-06 15:44:27 +03:00
Мержанов Максим Владимирович bbfb435c46 Merge branch 'local_config_migrate' into 'master'
migrate local config to config.CommonLocalConfig, update dependencies

See merge request integration-system/isp-system-service!5
2021-08-09 13:43:20 +00:00
Maxim Merzhanov 379102a1ac migrate local config to config.CommonLocalConfig, update dependencies 2021-08-09 15:43:23 +03:00
Мержанов Максим Владимирович d9f8ae19f8 Merge branch 'fix_migrations' into 'master'
fix migrations

See merge request integration-system/isp-system-service!4
2021-05-18 14:18:35 +00:00
Maxim Merzhanov 2d9efe3454 fix migrations 2021-05-18 14:47:10 +03:00
Мержанов Максим Владимирович 220706c876 Merge branch '__deps' into 'master'
Update dependencies

See merge request integration-system/isp-system-service!3
2021-05-17 15:40:06 +00:00
Egor Kiryushchenko c88a15c392 Update dependencies 2021-05-17 16:12:00 +03:00
Мержанов Максим Владимирович 9f8efb6712 Merge branch '__deps' into 'master'
Update dependencies

See merge request integration-system/isp-system-service!2
2021-01-26 18:45:01 +03:00
Egor Kiryushchenko 3bd6fe820d Update dependencies 2021-01-26 14:05:10 +03:00
Мержанов Максим Владимирович 540e18743a Merge branch '__deps' into 'master'
Update dependencies

See merge request integration-system/isp-system-service!1
2021-01-25 14:22:38 +03:00
Egor Kiryushchenko 8440633967 Update dependencies 2021-01-25 12:28:34 +03:00
Максим Мержанов 9f4a0b5fe1 Merge branch '__deps' into 'master'
Update dependencies

See merge request integration-system/isp-system-service!10
2020-11-24 14:31:24 +03:00
Егор Кирющенко ffab32fcff Update dependencies 2020-11-24 14:31:24 +03:00
Максим Мержанов 23013ef033 Merge branch 'linter_swagger' into 'master'
add linter, update swagger doc

See merge request integration-system/isp-system-service!3
2020-09-22 16:47:24 +03:00
Дмитрий Гуляченков 091f3ed06e add linter, update swagger doc 2020-09-22 16:47:24 +03:00
yan komissarov c4a34c6cd2 Merge branch 'up_lib' into 'master'
up libs

See merge request integration-system/isp-system-service!2
2020-06-15 12:10:55 +03:00
DeniskaRediska e07527855f add restart event 2020-06-03 14:48:13 +03:00
DeniskaRediska 85012da9b0 up libs 2020-06-03 14:45:54 +03:00
DeniskaRediska f5139e46ed up libs 2020-06-03 14:44:16 +03:00
yan komissarov 9f69df64e6 Merge branch 'modules' into 'master'
migrate to go mod, up deps

See merge request integration-system/isp-system-service!1
2020-04-14 11:16:20 +03:00
Maxim Merzhanov 1c048520f8 migrate to go mod, up deps 2020-04-10 13:57:59 +03:00
Jenkins Automation Server e5bf25d2a4 Update dependencies 2020-01-09 19:17:49 +03:00
Yan 1f633a417d Merge pull request #5 from integration-system/dev
Update dependencies
2019-11-21 11:41:19 +03:00
ykomissarov d92df57ff7 update version 2019-11-20 10:52:03 +03:00
ykomissarov b3905d7ceb Merge remote-tracking branch 'origin/master' into dev
# Conflicts:
#	Gopkg.lock
2019-11-20 10:48:05 +03:00
ykomissarov 15c18b1452 fix go vet 2019-11-15 13:40:56 +03:00
Yan bf366f7824 Merge pull request #6 from integration-system/access-list
Add access list
2019-11-14 14:01:07 +03:00
DeniskaRediska 293a9def27 update(application method delete_applications) 2019-11-14 13:52:52 +03:00
DeniskaRediska c9334e651b update access_list method set_list 2019-11-13 18:56:26 +03:00
DeniskaRediska 05d645d5f4 rename configs element 2019-11-12 17:23:52 +03:00
DeniskaRediska 5a811a9203 fix handler error 2019-11-12 16:23:22 +03:00
DeniskaRediska 0aa1dc40fd fix(token revoke) 2019-11-12 16:17:37 +03:00
Maxim 9c13075f79 Update dependencies 2019-11-12 13:04:27 +03:00
DeniskaRediska 0aec014161 refactoring 2019-11-12 12:48:03 +03:00
DeniskaRediska f215008349 add access_list methods 2019-11-11 19:21:55 +03:00
Maxim Merzhanov 8a0ebe803a up 2019-11-01 15:08:37 +03:00
Maxim c1da3c89ad Update dependencies 2019-11-01 14:03:44 +03:00
Yan 9fb2e48c8c Merge pull request #4 from integration-system/new_log
update
2019-10-18 14:56:32 +03:00
DeniskaRediska 6b8f3c8b1d fix shutdown 2019-10-18 14:12:48 +03:00
DeniskaRediska d5289efddc update(new log, new db client) 2019-10-18 12:47:25 +03:00
Yan 25b61e7d1d Merge pull request #3 from integration-system/api-doc
add(document generation)
2019-09-09 13:36:32 +03:00
Yan 493f0f1190 Update main.go 2019-09-09 13:36:09 +03:00
DeniskaRediska 9f76e76e55 add(document generation) 2019-09-06 15:13:11 +03:00
DeniskaRediska ff84d68b72 update(lib) 2019-08-26 13:24:45 +03:00
DeniskaRediska 0885d3e331 update(config description) 2019-08-26 13:22:50 +03:00
DeniskaRediska a6e50b6096 change(schema_name) 2019-06-03 16:18:42 +03:00
DeniskaRediska fa4221d4a4 add(default remote config) 2019-06-03 16:04:59 +03:00
ykomissarov 555e253da1 package refactoring 2019-03-20 11:16:23 +03:00
ykomissarov 3b56724d8e package refactoring 2019-03-20 11:16:07 +03:00
ykomissarov 5af4c6a254 update libs 2019-03-18 14:01:52 +03:00
ykomissarov 12a2a86ac4 update libs 2019-03-18 11:26:30 +03:00
ykomissarov f4a7463eec fix nilled slices 2019-03-12 11:13:00 +03:00
Andrey Savchuk cfac1dd58e Merge branch 'master' of work.github.com:integration-system/isp-system-service 2019-01-29 16:42:57 +03:00
logicalslice c420a98f70 Initial commit 2019-01-29 16:30:17 +03:00
73 changed files with 2803 additions and 6030 deletions

No files matched your search

-60
View File
@@ -1,60 +0,0 @@
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
+29 -3
View File
@@ -1,3 +1,29 @@
include:
- project: '$CI_PROJECT_PATH'
file: '/ci-isp-go-service.yml'
docker-build:
image: docker:latest
stage: build
services:
- docker:dind
before_script:
- docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
script:
- set
- docker build -f Dockerfile.dit --force-rm --pull -t "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA" .
- |
if [[ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]]; then
tag=""
echo "Running on default branch '$CI_DEFAULT_BRANCH': tag = ':latest'"
#docker pull "$CI_REGISTRY_IMAGE${tag}"
#docker tag "$CI_REGISTRY_IMAGE${tag}" "$CI_REGISTRY_IMAGE:pre"
#docker rmi "$CI_REGISTRY_IMAGE${tag}"
#docker push "$CI_REGISTRY_IMAGE:pre"
#docker rmi -f "$CI_REGISTRY_IMAGE:pre"
docker tag "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA" "$CI_REGISTRY_IMAGE${tag}"
docker rmi "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA"
docker push "$CI_REGISTRY_IMAGE${tag}"
docker rmi -f "$CI_REGISTRY_IMAGE${tag}"
else
tag=":$CI_COMMIT_BRANCH"
echo "Running on branch '$CI_COMMIT_BRANCH': tag = $tag"
fi
after_script:
- docker logout $CI_REGISTRY
+65 -65
View File
@@ -1,69 +1,69 @@
version: "2"
run:
allow-parallel-runners: true
timeout: 2m
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:
disable-all: true
enable:
- asciicheck
- bodyclose
- deadcode
- dogsled
- errcheck
- funlen
- goconst
- gocritic
- gocyclo
- gofmt
exclusions:
generated: lax
paths:
- third_party$
- builtin$
- examples$
- gomnd
- goprintffuncname
- gosimple
- govet
- nakedret
- nestif
- nolintlint
- prealloc
- rowserrcheck
- staticcheck
- structcheck
- typecheck
- unconvert
- unparam
- unused
- varcheck
- gosec
- misspell
- whitespace
- exhaustive #смотрит на соответствие между элементами enum и swich кейсами
- exportloopref #for _,p := []int{1, 2, 3} { s.Bar(&p) /* If s stores the pointer, it will be bug.*/ }
- sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed.
linters-settings:
funlen:
lines: 80
statements: 40
prealloc:
# Report preallocation suggestions only on simple loops that have no returns/breaks/continues/gotos in them.
# True by default.
simple: true
range-loops: true # Report preallocation suggestions on range loops, true by default
for-loops: true # Report preallocation suggestions on for loops, false by default
gocritic:
# Enable multiple checks by tags, run `GL_DEBUG=gocritic golangci-lint run` to see all tags and checks.
# Empty list by default. See https://github.com/go-critic/go-critic#usage -> section "Tags".
enabled-tags:
- diagnostic
- performance
disabled-checks:
- hugeParam
- rangeValCopy
- ifElseChain
exhaustive:
default-signifies-exhaustive: true
issues:
exclude-rules:
- path: _test\.go # to exclude all test files for linter errcheck
linters:
- errcheck
- linters:
- gosec
text: "G101:"
+1 -1
View File
@@ -1 +1 @@
5.7.0
4.0.0
-37
View File
@@ -1,40 +1,3 @@
### v5.7.0
* Обновлены зависимости
* Добавлено поле `http_method` в `access_list`
### v5.6.0
* Для endpoint'а `system/secure/authenticate` в ответ добавлено поле `appName` (название приложения)
* Обновлена версия `go` до `1.25`
* Обновлены зависимости
### v5.5.0
* Обновлены зависимости
### v5.4.0
* Добавлен новый endpoint: `/access_list/delete_list` для удаления методов из списка доступов у приложений
### v5.3.1
* добавлен `Dockerfile` и скрипт для сборки и публикации образа в `GitHub Contaier Registry`
* обновлены зависимости
### v5.3.0
* Добавлен новый endpoint: `/application/get_application_by_token`
### v5.2.1
* обновлены зависимости
### v5.2.0
* Обновлены зависимости
* Добавлены новые endpoint'ы: `/application/update_application`, `/application/create_application`, `/application_group/create`, `/application_group/update`, `/application_group/delete_list`, `/application_group/get_by_id_list`, `/application_group/get_all`
### v5.1.1
* обновлены зависимости
### v5.1.0
* все сервисы (группы приложений) перенесены в домен с id = 1
* при создании/изменении сервисов (групп приложений) будет использоваться только домен с id = 1
### v5.0.0
* изменен механизм инициализации токена панели администратора
* для механизма инициализации используется поле `baseline.initialAdminUiToken` в конфигурации
* если поле не заполнено, механизм не запускается
* иначе проверяется существование токена в базе, если токен уже создан, механизм не запускается
* иначе создаются все сущности и выпускается бессрочный токен, приложению выдается доступ к методу `admin/auth/login`
* механизм запускается при получении конфигурации
* при конкурентном запуске модуля, механизм запускается только на одном инстансе
* логи механизма маркируются полем "worker": "baseline"
* обновлена зависимости
### v4.0.0
* Удален `InstanceUuid`
* Удалена интеграция с Redis
+19
View File
@@ -0,0 +1,19 @@
FROM dockerhub.mos.ru/golang:1.19-alpine3.16 as builder
WORKDIR /build
ARG version
ENV version_env=$version
ARG app_name
ENV app_name_env=$app_name
COPY . .
ENV GOPROXY=https://repo-mirror.mos.ru/repository/go-public
RUN go build -ldflags="-X 'main.version=$version_env'" -o /main .
FROM dockerhub.mos.ru/alpine:3.16.0
WORKDIR /app
ARG app_name
ENV app_name_env=$app_name
COPY --from=builder main /app/$app_name_env
COPY /conf/config.yml /app/config.yml
COPY /conf/default_remote_config.json* /app/default_remote_config.json
COPY /migrations /app/migrations
ENTRYPOINT /app/$app_name_env
+16 -18
View File
@@ -3,10 +3,6 @@ package assembly
import (
"context"
"github.com/txix-open/isp-kit/rc"
"isp-system-service/conf"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/app"
"github.com/txix-open/isp-kit/bootstrap"
@@ -15,6 +11,8 @@ import (
"github.com/txix-open/isp-kit/dbx"
"github.com/txix-open/isp-kit/grpc"
"github.com/txix-open/isp-kit/log"
"isp-system-service/conf"
"isp-system-service/migrations"
)
type Assembly struct {
@@ -25,39 +23,39 @@ type Assembly struct {
}
func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
logger := boot.App.Logger()
dbCli := dbrx.New(logger, dbx.WithMigrationRunner(boot.MigrationsDir, logger))
dbCli := dbrx.New(dbx.WithMigrationRunner(boot.MigrationsDir, boot.App.Logger()))
server := grpc.NewServer()
return &Assembly{
boot: boot,
db: dbCli,
server: server,
logger: logger,
logger: boot.App.Logger(),
}, nil
}
func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error {
newCfg, _, err := rc.Upgrade[conf.Remote](a.boot.RemoteConfig, remoteConfig)
var (
newCfg conf.Remote
prevCfg conf.Remote
)
err := a.boot.RemoteConfig.Upgrade(remoteConfig, &newCfg, &prevCfg)
if err != nil {
a.boot.Fatal(errors.WithMessage(err, "upgrade remote config"))
a.logger.Fatal(ctx, errors.WithMessage(err, "upgrade remote config"))
}
migrations.Initialize.SetParams(a.boot.MigrationsDir, newCfg.Database.Schema)
a.logger.SetLevel(newCfg.LogLevel)
err = a.db.Upgrade(ctx, newCfg.Database)
if err != nil {
a.boot.Fatal(errors.WithMessage(err, "upgrade db client"))
a.logger.Fatal(ctx, errors.WithMessage(err, "upgrade db client"), log.Any("config", newCfg.Database))
}
locator := NewLocator(a.db, a.logger)
config := locator.Config(newCfg)
err = config.Baseline.Do(a.boot.App.Context())
if err != nil {
a.boot.Fatal(errors.WithMessage(err, "run baseline"))
}
a.server.Upgrade(config.Handler)
handler := locator.Handler(newCfg)
a.server.Upgrade(handler)
return nil
}
+22 -36
View File
@@ -1,20 +1,17 @@
package assembly
import (
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/grpc/endpoint"
"github.com/txix-open/isp-kit/grpc/isp"
"github.com/txix-open/isp-kit/log"
"isp-system-service/conf"
"isp-system-service/controller"
"isp-system-service/repository"
"isp-system-service/routes"
"isp-system-service/service"
"isp-system-service/service/baseline"
"isp-system-service/service/secure"
"isp-system-service/transaction"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/grpc"
"github.com/txix-open/isp-kit/grpc/endpoint"
"github.com/txix-open/isp-kit/grpc/endpoint/grpclog"
"github.com/txix-open/isp-kit/log"
)
type DB interface {
@@ -34,54 +31,43 @@ func NewLocator(db DB, logger log.Logger) Locator {
}
}
type Config struct {
Handler *grpc.Mux
Baseline baseline.Service
}
func (l Locator) Config(cfg conf.Remote) Config {
func (l Locator) Handler(cfg conf.Remote) isp.BackendServiceServer {
txManager := transaction.NewManager(l.db)
accessListRep := repository.NewAccessList(l.db)
applicationRep := repository.NewApplication(l.db)
domainRep := repository.NewDomain(l.db)
appGroupRep := repository.NewAppGroup(l.db)
groupRep := repository.NewApplicationGroup(l.db)
tokenRep := repository.NewToken(l.db)
secureService := secure.NewService(tokenRep, accessListRep)
secureApplicationGroup := secure.NewApplicationGroup(tokenRep, accessListRep)
accessListService := service.NewAccessList(txManager, accessListRep, applicationRep)
applicationService := service.NewApplication(txManager, applicationRep, domainRep, appGroupRep, tokenRep)
applicationService := service.NewApplication(txManager, applicationRep, domainRep, groupRep, tokenRep)
domainService := service.NewDomain(domainRep)
serviceService := service.NewService(domainRep, appGroupRep)
applicationGroupService := service.NewApplicationGroup(domainRep, groupRep)
jwtService := service.NewTokenSource()
tokenService := service.NewToken(jwtService, applicationService, txManager,
applicationRep, domainRep, appGroupRep, tokenRep,
applicationRep, domainRep, groupRep, tokenRep,
)
secureController := controller.NewSecure(secureService)
secureController := controller.NewSecure(secureApplicationGroup)
accessListController := controller.NewAccessList(accessListService)
applicationController := controller.NewApplication(applicationService)
domainController := controller.NewDomain(domainService)
serviceController := controller.NewService(serviceService)
serviceController := controller.NewService(applicationGroupService)
groupController := controller.NewApplicationGroup(applicationGroupService)
tokenController := controller.NewToken(tokenService)
appGroupService := service.NewAppGroup(appGroupRep)
appGroupController := controller.NewAppGroup(appGroupService)
c := routes.Controllers{
Secure: secureController,
AccessList: accessListController,
Domain: domainController,
Service: serviceController,
Application: applicationController,
Token: tokenController,
AppGroup: appGroupController,
Secure: secureController,
AccessList: accessListController,
Domain: domainController,
Service: serviceController,
ApplicationGroup: groupController,
Application: applicationController,
Token: tokenController,
}
mapper := endpoint.DefaultWrapper(l.logger, grpclog.Log(l.logger, true))
mapper := endpoint.DefaultWrapper(l.logger, endpoint.BodyLogger(l.logger))
server := routes.Handler(mapper, c)
baselineService := baseline.NewService(cfg.Baseline, txManager, l.logger)
return Config{
Handler: server,
Baseline: baselineService,
}
return server
}
-3
View File
@@ -7,8 +7,5 @@
"username": "{{ msp_pgsql_user }}",
"host": "{{ msp_pgsql_address }}",
"port": 5432
},
"baseline": {
"initialAdminUiToken": "{{ isp_service_admin_token }}"
}
}
+1 -7
View File
@@ -9,7 +9,6 @@ import (
"github.com/txix-open/jsonschema"
)
//nolint:gochecknoinits
func init() {
schema.CustomGenerators.Register("logLevel", func(field reflect.StructField, t *jsonschema.Schema) {
t.Type = "string"
@@ -19,10 +18,5 @@ func init() {
type Remote struct {
Database dbx.Config `schema:"Настройка базы данных"`
Baseline Baseline
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"`
}
type Baseline struct {
InitialAdminUiToken string
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"`
}
-13
View File
@@ -1,13 +0,0 @@
package conf_test
import (
"isp-system-service/conf"
"testing"
"github.com/txix-open/isp-kit/test/rct"
)
func TestDefaultRemoteConfig(t *testing.T) {
t.Parallel()
rct.Test(t, "default_remote_config.json", conf.Remote{})
}
+35 -111
View File
@@ -2,21 +2,17 @@ package controller
import (
"context"
"fmt"
"isp-system-service/domain"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/grpc/apierrors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-system-service/domain"
)
type AccessListService interface {
GetById(ctx context.Context, appId int) ([]domain.MethodInfo, error)
SetOne(ctx context.Context, request domain.AccessListSetOneRequest) (*domain.AccessListSetOneResponse, error)
SetList(ctx context.Context, req domain.AccessListSetListRequest) ([]domain.MethodInfo, error)
DeleteList(ctx context.Context, req domain.AccessListDeleteListRequest) error
DeleteListWithMethods(ctx context.Context, req domain.AccessListDeleteV2ListRequest) error
}
type AccessList struct {
@@ -30,27 +26,21 @@ func NewAccessList(service AccessListService) AccessList {
}
// GetById godoc
//
// @Tags accessList
// @Summary Получить список доступности методов для приложения
// @Description Возвращает список методов для приложения, для которых заданы настройки доступа
// @Accept json
// @Produce json
// @Param body body domain.Identity false "идентификатор приложения"
// @Success 200 {array} domain.MethodInfo "список доступности методов"
// @Failure 404 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /access_list/get_by_id [POST]
// @Tags accessList
// @Summary Получить список доступности методов для приложения
// @Description Возвращает список методов для приложения, для которых заданы настройки доступа
// @Accept json
// @Produce json
// @Param body body domain.Identity false "идентификатор приложения"
// @Success 200 {array} domain.MethodInfo "список доступности методов"
// @Failure 404 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /access_list/get_by_id [POST]
func (c AccessList) GetById(ctx context.Context, req domain.Identity) ([]domain.MethodInfo, error) {
result, err := c.service.GetById(ctx, req.Id)
switch {
case errors.Is(err, domain.ErrApplicationNotFound):
return nil, apierrors.New(
codes.NotFound,
domain.ErrCodeApplicationNotFound,
fmt.Sprintf("application with id %d not found", req.Id),
err,
)
return nil, status.Errorf(codes.NotFound, "application not found")
case err != nil:
return nil, err
default:
@@ -59,27 +49,21 @@ func (c AccessList) GetById(ctx context.Context, req domain.Identity) ([]domain.
}
// SetOne godoc
//
// @Tags accessList
// @Summary Настроить доступность метода для приложения
// @Description Возвращает количество измененных строк
// @Accept json
// @Produce json
// @Param body body domain.AccessListSetOneRequest false "объект для настройки доступа"
// @Success 200 {object} domain.AccessListSetOneResponse "количество измененных строк"
// @Failure 404 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /access_list/set_one [POST]
// @Tags accessList
// @Summary Настроить доступность метода для приложения
// @Description Возвращает количество измененных строк
// @Accept json
// @Produce json
// @Param body body domain.AccessListSetOneRequest false "объект для настройки доступа"
// @Success 200 {object} domain.AccessListSetOneResponse "количество измененных строк"
// @Failure 404 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /access_list/set_one [POST]
func (c AccessList) SetOne(ctx context.Context, req domain.AccessListSetOneRequest) (*domain.AccessListSetOneResponse, error) {
result, err := c.service.SetOne(ctx, req)
switch {
case errors.Is(err, domain.ErrApplicationNotFound):
return nil, apierrors.New(
codes.NotFound,
domain.ErrCodeApplicationNotFound,
fmt.Sprintf("application with id %d not found", req.AppId),
err,
)
return nil, status.Errorf(codes.NotFound, "application not found")
case err != nil:
return nil, err
default:
@@ -88,84 +72,24 @@ func (c AccessList) SetOne(ctx context.Context, req domain.AccessListSetOneReque
}
// SetList godoc
//
// @Tags accessList
// @Summary Настроить доступность списка методов для приложения
// @Description Возвращает список методов для приложения, для которых заданы настройки доступа
// @Accept json
// @Produce json
// @Param body body domain.AccessListSetListRequest false "объект настройки доступа"
// @Success 200 {array} domain.MethodInfo "список доступности методов"
// @Failure 404 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /access_list/set_list [POST]
// @Tags accessList
// @Summary Настроить доступность списка методов для приложения
// @Description Возвращает список методов для приложения, для которых заданы настройки доступа
// @Accept json
// @Produce json
// @Param body body domain.AccessListSetListRequest false "объект настройки доступа"
// @Success 200 {array} domain.MethodInfo "список доступности методов"
// @Failure 404 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /access_list/set_list [POST]
func (c AccessList) SetList(ctx context.Context, req domain.AccessListSetListRequest) ([]domain.MethodInfo, error) {
result, err := c.service.SetList(ctx, req)
switch {
case errors.Is(err, domain.ErrApplicationNotFound):
return nil, apierrors.New(
codes.NotFound,
domain.ErrCodeApplicationNotFound,
fmt.Sprintf("application with id %d not found", req.AppId),
err,
)
return nil, status.Errorf(codes.NotFound, "application not found")
case err != nil:
return nil, err
default:
return result, nil
}
}
// DeleteList godoc
//
// @Tags accessList
// @Summary Удалить список доступных методов для приложения
// @Description Удаляет заданный список методов для приложения
// @Accept json
// @Produce json
// @Param body body domain.AccessListDeleteListRequest false "тело запроса"
// @Success 200 {object} any
// @Failure 404 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /access_list/delete_list [POST]
func (c AccessList) DeleteList(ctx context.Context, req domain.AccessListDeleteListRequest) error {
err := c.service.DeleteList(ctx, req)
switch {
case errors.Is(err, domain.ErrApplicationNotFound):
return apierrors.New(
codes.NotFound,
domain.ErrCodeApplicationNotFound,
fmt.Sprintf("application with id %d not found", req.AppId),
err,
)
default:
return err
}
}
// DeleteListWithMethods godoc
//
// @Tags accessList
// @Summary Удалить список доступных методов для приложения
// @Description Удаляет заданный список методов для приложения
// @Accept json
// @Produce json
// @Param body body domain.AccessListDeleteV2ListRequest false "тело запроса"
// @Success 200 {object} any
// @Failure 404 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /access_list/delete_list_with_methods [POST]
func (c AccessList) DeleteListWithMethods(ctx context.Context, req domain.AccessListDeleteV2ListRequest) error {
err := c.service.DeleteListWithMethods(ctx, req)
switch {
case errors.Is(err, domain.ErrApplicationNotFound):
return apierrors.New(
codes.NotFound,
domain.ErrCodeApplicationNotFound,
fmt.Sprintf("application with id %d not found", req.AppId),
err,
)
default:
return err
}
}
-139
View File
@@ -1,139 +0,0 @@
package controller
import (
"context"
"fmt"
"isp-system-service/domain"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/grpc/apierrors"
"google.golang.org/grpc/codes"
)
type AppGroupService interface {
Create(ctx context.Context, req domain.CreateAppGroupRequest) (*domain.AppGroup, error)
Update(ctx context.Context, req domain.UpdateAppGroupRequest) (*domain.AppGroup, error)
DeleteList(ctx context.Context, req domain.IdListRequest) (*domain.DeleteResponse, error)
GetByIdList(ctx context.Context, idList []int) ([]domain.AppGroup, error)
GetAll(ctx context.Context) ([]domain.AppGroup, error)
}
type AppGroup struct {
service AppGroupService
}
func NewAppGroup(service AppGroupService) AppGroup {
return AppGroup{
service: service,
}
}
// Create godoc
//
// @Tags application_group
// @Summary Создать группу приложений
// @Description Если группа приложений таким именем существует, возвращает ошибку
// @Accept json
// @Produce json
// @Param body body domain.CreateAppGroupRequest true "Объект группы приложений"
// @Success 200 {object} domain.AppGroup
// @Failure 400 {object} apierrors.Error
// @Failure 409 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /application_group/create [POST]
func (c AppGroup) Create(ctx context.Context, req domain.CreateAppGroupRequest) (*domain.AppGroup, error) {
result, err := c.service.Create(ctx, req)
switch {
case errors.Is(err, domain.ErrAppGroupDuplicateName):
return nil, apierrors.New(
codes.AlreadyExists,
domain.ErrCodeAppGroupDuplicateName,
fmt.Sprintf("application group with name %s already exists", req.Name),
err,
)
default:
return result, err
}
}
// Update godoc
//
// @Tags application_group
// @Summary Обновить группу приложений
// @Description Если группа приложений таким именем существует или группы приложений с указанным id не существует, возвращает ошибку
// @Accept json
// @Produce json
// @Param body body domain.UpdateAppGroupRequest true "Объект группы приложений"
// @Success 200 {object} domain.AppGroup
// @Failure 400 {object} apierrors.Error
// @Failure 404 {object} apierrors.Error
// @Failure 409 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /application_group/update [POST]
func (c AppGroup) Update(ctx context.Context, req domain.UpdateAppGroupRequest) (*domain.AppGroup, error) {
result, err := c.service.Update(ctx, req)
switch {
case errors.Is(err, domain.ErrAppGroupDuplicateName):
return nil, apierrors.New(
codes.AlreadyExists,
domain.ErrCodeAppGroupDuplicateName,
fmt.Sprintf("application group with name %s already exists", req.Name),
err,
)
case errors.Is(err, domain.ErrAppGroupNotFound):
return nil, apierrors.New(
codes.NotFound,
domain.ErrCodeAppGroupNotFound,
fmt.Sprintf("application group with id %d not found", req.Id),
err,
)
default:
return result, err
}
}
// DeleteList godoc
//
// @Tags application_group
// @Summary Удалить группы приложений
// @Description Удаляет группы приложений по списку их идентификаторов, возвращает количество удаленных групп приложений
// @Accept json
// @Produce json
// @Param body body domain.IdListRequest true "список идентификаторов групп приложений"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /application_group/delete_list [POST]
func (c AppGroup) DeleteList(ctx context.Context, req domain.IdListRequest) (*domain.DeleteResponse, error) {
return c.service.DeleteList(ctx, req)
}
// GetByIdList godoc
//
// @Tags application_group
// @Summary Получить группы приложений по списку идентификаторов
// @Description Возвращает группы приложений с указанными идентификаторами
// @Accept json
// @Produce json
// @Param body body domain.IdListRequest true "список идентификаторов групп приложений"
// @Success 200 {array} domain.AppGroup
// @Failure 400 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /application_group/get_by_id_list [POST]
func (c AppGroup) GetByIdList(ctx context.Context, req domain.IdListRequest) ([]domain.AppGroup, error) {
return c.service.GetByIdList(ctx, req.IdList)
}
// GetAll godoc
//
// @Tags application_group
// @Summary Получить группы приложений
// @Description Возвращает все группы приложений
// @Accept json
// @Produce json
// @Success 200 {array} domain.AppGroup
// @Failure 500 {object} apierrors.Error
// @Router /application_group/get_all [POST]
func (c AppGroup) GetAll(ctx context.Context) ([]domain.AppGroup, error) {
return c.service.GetAll(ctx)
}
+73 -249
View File
@@ -2,28 +2,20 @@ package controller
import (
"context"
"fmt"
"isp-system-service/domain"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/grpc/apierrors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-system-service/domain"
)
// nolint:interfacebloat
type ApplicationService interface {
GetById(ctx context.Context, appId int) (*domain.ApplicationWithTokens, error)
GetByToken(ctx context.Context, token string) (*domain.GetApplicationByTokenResponse, error)
GetByIdList(ctx context.Context, idList []int) ([]*domain.ApplicationWithTokens, error)
GetByServiceId(ctx context.Context, id int) ([]*domain.ApplicationWithTokens, error)
SystemTree(ctx context.Context, systemId int) ([]*domain.DomainWithService, error)
GetByApplicationGroupId(ctx context.Context, id int) ([]*domain.ApplicationWithTokens, error)
SystemTree(ctx context.Context, systemId int) ([]*domain.DomainWithApplicationGroup, error)
CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error)
Delete(ctx context.Context, idList []int) (int, error)
NextId(ctx context.Context) (int, error)
GetAll(ctx context.Context) ([]domain.Application, error)
Create(ctx context.Context, req domain.CreateApplicationRequest) (*domain.ApplicationWithTokens, error)
Update(ctx context.Context, req domain.UpdateApplicationRequest) (*domain.ApplicationWithTokens, error)
}
type Application struct {
@@ -37,58 +29,22 @@ func NewApplication(service ApplicationService) Application {
}
// GetById godoc
//
// @Tags application
// @Summary Получить приложение по идентификатору
// @Description Возвращает описание приложения по его идентификатору
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор приложения"
// @Success 200 {object} domain.ApplicationWithTokens
// @Failure 400 {object} apierrors.Error
// @Failure 404 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /application/get_application_by_id [POST]
// @Tags application
// @Summary Получить приложение по идентификатору
// @Description Возвращает описание приложения по его идентификатору
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор приложения"
// @Success 200 {object} domain.ApplicationWithTokens
// @Failure 400 {object} domain.GrpcError
// @Failure 404 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /application/get_application_by_id [POST]
func (c Application) GetById(ctx context.Context, req domain.Identity) (*domain.ApplicationWithTokens, error) {
result, err := c.service.GetById(ctx, req.Id)
switch {
case errors.Is(err, domain.ErrApplicationNotFound):
return nil, apierrors.New(
codes.NotFound,
domain.ErrCodeApplicationNotFound,
fmt.Sprintf("application with id %d not found", req.Id),
err,
)
case err != nil:
return nil, err
default:
return result, nil
}
}
// GetByToken godoc
//
// @Tags application
// @Summary Получить идентификатор приложения и группы по токену
// @Description Возвращает идентификатор приложения и группы по токену
// @Accept json
// @Produce json
// @Param body body domain.GetApplicationByTokenRequest true "Тело запроса"
// @Success 200 {object} domain.GetApplicationByTokenResponse
// @Failure 400 {object} apierrors.Error
// @Failure 404 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /application/get_application_by_token [POST]
func (c Application) GetByToken(ctx context.Context, req domain.GetApplicationByTokenRequest) (*domain.GetApplicationByTokenResponse, error) {
result, err := c.service.GetByToken(ctx, req.Token)
switch {
case errors.Is(err, domain.ErrApplicationNotFound):
return nil, apierrors.New(
codes.NotFound,
domain.ErrCodeApplicationNotFound,
fmt.Sprintf("application with token '%s' not found", req.Token),
err,
)
return nil, status.Errorf(codes.NotFound, "application with id %d not found", req.Id)
case err != nil:
return nil, err
default:
@@ -97,86 +53,68 @@ func (c Application) GetByToken(ctx context.Context, req domain.GetApplicationBy
}
// GetByIdList godoc
//
// @Tags application
// @Summary Получить список приложений
// @Description Возвращает массив приложений с токенами по их идентификаторам
// @Accept json
// @Produce json
// @Param body body []integer false "Массив идентификаторов приложений"
// @Success 200 {array} domain.ApplicationWithTokens
// @Failure 500 {object} apierrors.Error
// @Router /application/get_applications [POST]
// @Tags application
// @Summary Получить список приложений
// @Description Возвращает массив приложений с токенами по их идентификаторам
// @Accept json
// @Produce json
// @Param body body []integer false "Массив идентификаторов приложений"
// @Success 200 {array} domain.ApplicationWithTokens
// @Failure 500 {object} domain.GrpcError
// @Router /application/get_applications [POST]
func (c Application) GetByIdList(ctx context.Context, req []int) ([]*domain.ApplicationWithTokens, error) {
return c.service.GetByIdList(ctx, req)
}
// GetByServiceId godoc
//
// @Tags application
// @Summary Получить список приложений по идентификатору сервиса
// @Description Возвращает список приложений по запрошенному идентификатору сервиса
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор сервиса"
// @Success 200 {array} domain.ApplicationWithTokens
// @Failure 500 {object} apierrors.Error
// @Router /application/get_applications_by_service_id [POST]
func (c Application) GetByServiceId(ctx context.Context, req domain.Identity) ([]*domain.ApplicationWithTokens, error) {
return c.service.GetByServiceId(ctx, req.Id)
// GetByApplicationGroupId godoc
// @Tags application
// @Summary Получить список приложений по идентификатору группы приложений
// @Description Возвращает список приложений по запрошенному идентификатору группы приложений
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор группы приложений"
// @Success 200 {array} domain.ApplicationWithTokens
// @Failure 500 {object} domain.GrpcError
// @Router /application/get_applications_by_service_id [POST]
func (c Application) GetByApplicationGroupId(ctx context.Context, req domain.Identity) ([]*domain.ApplicationWithTokens, error) {
return c.service.GetByApplicationGroupId(ctx, req.Id)
}
// GetSystemTree godoc
//
// @Tags application
// @Summary Метод получения системного дерева
// @Description Возвращает описание взаимосвязей сервисов и приложений
// @Accept json
// @Produce json
// @Success 200 {array} domain.DomainWithService
// @Failure 500 {object} apierrors.Error
// @Router /application/get_system_tree [POST]
func (c Application) GetSystemTree(ctx context.Context) ([]*domain.DomainWithService, error) {
// @Tags application
// @Summary Метод получения системного дерева
// @Description Возвращает описание взаимосвязей группы приложений и приложений
// @Accept json
// @Produce json
// @Success 200 {array} domain.DomainWithApplicationGroup
// @Failure 500 {object} domain.GrpcError
// @Router /application/get_system_tree [POST]
func (c Application) GetSystemTree(ctx context.Context) ([]*domain.DomainWithApplicationGroup, error) {
return c.service.SystemTree(ctx, domain.DefaultSystemId)
}
// CreateUpdate godoc
//
// @Tags application
// @Summary Создать/обновить приложение
// @Description Если приложение с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
// @Accept json
// @Produce json
// @Param body body domain.ApplicationCreateUpdateRequest true "Объект приложения"
// @Success 200 {object} domain.ApplicationWithTokens
// @Failure 400 {object} apierrors.Error
// @Failure 404 {object} apierrors.Error
// @Failure 409 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /application/create_update_application [POST]
// @Tags application
// @Summary Создать/обновить приложение
// @Description Если приложение с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
// @Accept json
// @Produce json
// @Param body body domain.ApplicationCreateUpdateRequest true "Объект приложения"
// @Success 200 {object} domain.ApplicationWithTokens
// @Failure 400 {object} domain.GrpcError
// @Failure 404 {object} domain.GrpcError
// @Failure 409 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /application/create_update_application [POST]
func (c Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error) {
result, err := c.service.CreateUpdate(ctx, req)
switch {
case errors.Is(err, domain.ErrAppGroupNotFound):
return nil, apierrors.NewBusinessError(
domain.ErrCodeAppGroupNotFound,
fmt.Sprintf("service with id %d not found", req.ServiceId),
err,
)
case errors.Is(err, domain.ErrApplicationGroupNotFound):
return nil, status.Errorf(codes.InvalidArgument, "application group with id %d not found", req.ApplicationGroupId)
case errors.Is(err, domain.ErrApplicationDuplicateName):
return nil, apierrors.New(
codes.AlreadyExists,
domain.ErrCodeApplicationDuplicateName,
fmt.Sprintf("application with name %s already exists", req.Name),
err,
)
return nil, status.Errorf(codes.AlreadyExists, "application with name %s already exists", req.Name)
case errors.Is(err, domain.ErrApplicationNotFound):
return nil, apierrors.New(
codes.NotFound,
domain.ErrCodeApplicationNotFound,
fmt.Sprintf("application with id %d not found", req.Id),
err,
)
return nil, status.Errorf(codes.NotFound, "application with id %d not found", req.Id)
case err != nil:
return nil, err
default:
@@ -185,21 +123,19 @@ func (c Application) CreateUpdate(ctx context.Context, req domain.ApplicationCre
}
// Delete godoc
//
// @Tags application
// @Summary Удалить приложения
// @Description Удаляет приложения по списку их идентификаторов, возвращает количество удаленных приложений
// @Accept json
// @Produce json
// @Param body body []integer false "Массив идентификаторов приложений"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /application/delete_applications [POST]
// @Tags application
// @Summary Удалить приложения
// @Description Удаляет приложения по списку их идентификаторов, возвращает количество удаленных приложений
// @Accept json
// @Produce json
// @Param body body []integer false "Массив идентификаторов приложений"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /application/delete_applications [POST]
func (c Application) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) {
if len(req) == 0 {
return nil, apierrors.NewBusinessError(domain.ErrCodeInvalidRequest,
"At least one id are required", errors.New("invalid id count"))
return nil, status.Errorf(codes.InvalidArgument, "At least one id are required")
}
result, err := c.service.Delete(ctx, req)
@@ -211,115 +147,3 @@ func (c Application) Delete(ctx context.Context, req []int) (*domain.DeleteRespo
Deleted: result,
}, nil
}
// NextId godoc
//
// @Tags application
// @Summary Получить следующий идентификатор приложения
// @Description Возвращает следующий идентификатор приложения
// @Accept json
// @Produce json
// @Success 200 {object} integer
// @Failure 500 {object} apierrors.Error
// @Router /application/next_id [POST]
func (c Application) NextId(ctx context.Context) (int, error) {
return c.service.NextId(ctx)
}
// GetAll godoc
//
// @Tags application
// @Summary Получить список приложений
// @Description Возвращает список приложений
// @Accept json
// @Produce json
// @Success 200 {array} domain.Application
// @Failure 500 {object} apierrors.Error
// @Router /application/get_all [POST]
func (c Application) GetAll(ctx context.Context) ([]domain.Application, error) {
return c.service.GetAll(ctx)
}
// Create godoc
//
// @Tags application
// @Summary Создать приложение
// @Description Если приложение с такими идентификатором или связкой `applicationGroupId`-`name` существует, то возвращает ошибку
// @Accept json
// @Produce json
// @Param body body domain.CreateApplicationRequest true "Объект приложения"
// @Success 200 {object} domain.ApplicationWithTokens
// @Failure 400 {object} apierrors.Error
// @Failure 409 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /application/create_application [POST]
func (c Application) Create(ctx context.Context, req domain.CreateApplicationRequest) (*domain.ApplicationWithTokens, error) {
result, err := c.service.Create(ctx, req)
switch {
case errors.Is(err, domain.ErrAppGroupNotFound):
return nil, apierrors.NewBusinessError(
domain.ErrCodeAppGroupNotFound,
fmt.Sprintf("application group with id %d not found", req.ApplicationGroupId),
err,
)
case errors.Is(err, domain.ErrApplicationDuplicateName):
return nil, apierrors.New(
codes.AlreadyExists,
domain.ErrCodeApplicationDuplicateName,
fmt.Sprintf("application with name %s already exists", req.Name),
err,
)
case errors.Is(err, domain.ErrApplicationDuplicateId):
return nil, apierrors.New(
codes.AlreadyExists,
domain.ErrCodeApplicationDuplicateId,
fmt.Sprintf("application with id %d already exists", req.Id),
err,
)
default:
return result, err
}
}
// Update godoc
//
// @Tags application
// @Summary Обновить приложение
// @Description Если приложение с связкой `applicationGroupId`-`name` существует или приложение не найдено, то возвращает ошибку
// @Accept json
// @Produce json
// @Param body body domain.UpdateApplicationRequest true "Объект приложения"
// @Success 200 {object} domain.ApplicationWithTokens
// @Failure 400 {object} apierrors.Error
// @Failure 404 {object} apierrors.Error
// @Failure 409 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /application/update_application [POST]
func (c Application) Update(ctx context.Context, req domain.UpdateApplicationRequest) (*domain.ApplicationWithTokens, error) {
result, err := c.service.Update(ctx, req)
switch {
case errors.Is(err, domain.ErrApplicationNotFound):
return nil, apierrors.New(
codes.NotFound,
domain.ErrCodeApplicationNotFound,
fmt.Sprintf("application with id %d not found", req.OldId),
err,
)
case errors.Is(err, domain.ErrApplicationDuplicateName):
return nil, apierrors.New(
codes.AlreadyExists,
domain.ErrCodeApplicationDuplicateName,
fmt.Sprintf("application with name %s already exists", req.Name),
err,
)
case errors.Is(err, domain.ErrApplicationDuplicateId):
return nil, apierrors.New(
codes.AlreadyExists,
domain.ErrCodeApplicationDuplicateId,
fmt.Sprintf("application with id %d already exists", req.NewId),
err,
)
default:
return result, err
}
}
+121
View File
@@ -0,0 +1,121 @@
package controller
import (
"context"
"github.com/pkg/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-system-service/domain"
)
type ApplicationGroupService interface {
GetById(ctx context.Context, id int) (*domain.ApplicationGroup, error)
GetByIdList(ctx context.Context, idList []int) ([]domain.ApplicationGroup, error)
CreateUpdate(ctx context.Context, req domain.ApplicationGroupCreateUpdateRequest) (*domain.ApplicationGroup, error)
Delete(ctx context.Context, idList []int) (int, error)
}
type ApplicationGroup struct {
service ApplicationGroupService
}
func NewApplicationGroup(service ApplicationGroupService) ApplicationGroup {
return ApplicationGroup{
service: service,
}
}
// GetById godoc
// @Tags application_group
// @Summary Получить группу приложений по идентификатору
// @Description Возвращает описание группы приложений по ее идентификатору
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор группы приложений"
// @Success 200 {object} domain.ApplicationGroup
// @Failure 404 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /application_group/get_group_by_id [POST]
func (c ApplicationGroup) GetById(ctx context.Context, req domain.Identity) (*domain.ApplicationGroup, error) {
result, err := c.service.GetById(ctx, req.Id)
switch {
case errors.Is(err, domain.ErrApplicationGroupNotFound):
return nil, status.Errorf(codes.NotFound, "application group with id %d not found", req.Id)
case err != nil:
return nil, err
default:
return result, nil
}
}
// Get godoc
// @Tags application_group
// @Summary Получить список группы приложений
// @Description Возвращает список групп приложений по их идентификаторам
// @Accept json
// @Produce json
// @Param body body []integer false "Массив идентификаторов групп приложений"
// @Success 200 {array} domain.ApplicationGroup
// @Failure 500 {object} domain.GrpcError
// @Router /application_group/get_group [POST]
func (c ApplicationGroup) Get(ctx context.Context, req []int) ([]domain.ApplicationGroup, error) {
return c.service.GetByIdList(ctx, req)
}
// CreateUpdate godoc
// @Tags application_group
// @Summary Создать/обновить группу приложений
// @Description Если группы приложений с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
// @Accept json
// @Produce json
// @Param body body domain.ApplicationGroupCreateUpdateRequest true "Объект группы приложений"
// @Success 200 {object} domain.ApplicationGroup
// @Failure 400 {object} domain.GrpcError
// @Failure 404 {object} domain.GrpcError
// @Failure 409 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /application_group/create_update_group [POST]
func (c ApplicationGroup) CreateUpdate(ctx context.Context, req domain.ApplicationGroupCreateUpdateRequest) (*domain.ApplicationGroup, error) {
req.DomainId = 1 // Хардкодом проставляем domainId = 1
result, err := c.service.CreateUpdate(ctx, req)
switch {
case errors.Is(err, domain.ErrDomainNotFound):
return nil, status.Errorf(codes.InvalidArgument, "domain with id %d not found", req.DomainId)
case errors.Is(err, domain.ErrApplicationGroupNotFound):
return nil, status.Errorf(codes.NotFound, "application group with id %d not found", req.Id)
case errors.Is(err, domain.ErrApplicationGroupDuplicateName):
return nil, status.Errorf(codes.AlreadyExists, "application group with name %s already exists", req.Name)
case err != nil:
return nil, err
default:
return result, nil
}
}
// Delete godoc
// @Tags application_group
// @Summary Удалить группы приложений
// @Description Удаляет группы приложений по списку их идентификаторов, возвращает количество удаленных групп
// @Accept json
// @Produce json
// @Param body body []integer true "Массив идентификаторов групп приложений"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /application_group/delete_group [POST]
func (c ApplicationGroup) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) {
if len(req) == 0 {
return nil, status.Error(codes.InvalidArgument, "at least one id are required")
}
result, err := c.service.Delete(ctx, req)
if err != nil {
return nil, err
}
return &domain.DeleteResponse{
Deleted: result,
}, nil
}
+45 -71
View File
@@ -2,13 +2,11 @@ package controller
import (
"context"
"fmt"
"isp-system-service/domain"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/grpc/apierrors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-system-service/domain"
)
type DomainService interface {
@@ -29,27 +27,21 @@ func NewDomain(service DomainService) Domain {
}
// GetById godoc
//
// @Tags domain
// @Summary Получить домен по идентификатору
// @Description Возвращает описание домена по его идентификатору
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор домена"
// @Success 200 {object} domain.Domain
// @Failure 404 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /domain/get_domain_by_id [POST]
// @Tags domain
// @Summary Получить домен по идентификатору
// @Description Возвращает описание домена по его идентификатору
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор домена"
// @Success 200 {object} domain.Domain
// @Failure 404 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /domain/get_domain_by_id [POST]
func (c Domain) GetById(ctx context.Context, req domain.Identity) (*domain.Domain, error) {
result, err := c.service.GetById(ctx, req.Id)
switch {
case errors.Is(err, domain.ErrDomainNotFound):
return nil, apierrors.New(
codes.NotFound,
domain.ErrCodeDomainNotFound,
fmt.Sprintf("domain with id %d not found", req.Id),
err,
)
return nil, status.Errorf(codes.NotFound, "domain with id %d not found", req.Id)
case err != nil:
return nil, err
default:
@@ -58,54 +50,38 @@ func (c Domain) GetById(ctx context.Context, req domain.Identity) (*domain.Domai
}
// GetBySystemId godoc
//
// @Tags domain
// @Summary Получить домены по идентификатору системы
// @Description Возвращает список доменов по системному идентификатору
// @Accept json
// @Produce json
// @Param body body integer false "Идентификатор системы"
// @Success 200 {array} domain.Domain
// @Failure 500 {object} apierrors.Error
// @Router /domain/get_domains_by_system_id [POST]
// @Tags domain
// @Summary Получить домены по идентификатору системы
// @Description Возвращает список доменов по системному идентификатору
// @Accept json
// @Produce json
// @Param body body integer false "Идентификатор системы"
// @Success 200 {array} domain.Domain
// @Failure 500 {object} domain.GrpcError
// @Router /domain/get_domains_by_system_id [POST]
func (c Domain) GetBySystemId(ctx context.Context) ([]domain.Domain, error) {
return c.service.GetBySystemId(ctx, domain.DefaultSystemId)
}
// CreateUpdate godoc
//
// @Tags domain
// @Summary Создать/обновить домен
// @Description Если домен с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
// @Accept json
// @Produce json
// @Param body body domain.DomainCreateUpdateRequest true "Объект домена"
// @Success 200 {object} domain.Domain
// @Failure 500 {object} apierrors.Error
// @Router /domain/create_update_domain [POST]
// @Tags domain
// @Summary Создать/обновить домен
// @Description Если домен с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
// @Accept json
// @Produce json
// @Param body body domain.DomainCreateUpdateRequest true "Объект домена"
// @Success 200 {object} domain.Domain
// @Failure 500 {object} domain.GrpcError
// @Router /domain/create_update_domain [POST]
func (c Domain) CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateRequest) (*domain.Domain, error) {
result, err := c.service.CreateUpdate(ctx, req, domain.DefaultSystemId)
switch {
case errors.Is(err, domain.ErrSystemNotFound):
return nil, apierrors.NewBusinessError(
domain.ErrCodeSystemNotFound,
fmt.Sprintf("system with id %d not found", domain.DefaultSystemId),
err,
)
return nil, status.Errorf(codes.InvalidArgument, "system with id %d not found", domain.DefaultSystemId)
case errors.Is(err, domain.ErrDomainNotFound):
return nil, apierrors.New(
codes.NotFound,
domain.ErrCodeDomainNotFound,
fmt.Sprintf("domain with id %d not found", req.Id),
err,
)
return nil, status.Errorf(codes.NotFound, "domain with id %d not found", req.Id)
case errors.Is(err, domain.ErrDomainDuplicateName):
return nil, apierrors.New(
codes.AlreadyExists,
domain.ErrCodeDomainDuplicateName,
fmt.Sprintf("domain with name %s already exists", req.Name),
err,
)
return nil, status.Errorf(codes.AlreadyExists, "domain with name %s already exists", req.Name)
case err != nil:
return nil, err
default:
@@ -114,21 +90,19 @@ func (c Domain) CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateR
}
// Delete godoc
//
// @Tags domain
// @Summary Удаление доменов
// @Description Удаляет домены по списку их идентификаторов, возвращает количество удаленных доменов
// @Accept json
// @Produce json
// @Param body body []integer false "Массив идентификаторов доменов"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /domain/delete_domains [POST]
// @Tags domain
// @Summary Удаление доменов
// @Description Удаляет домены по списку их идентификаторов, возвращает количество удаленных доменов
// @Accept json
// @Produce json
// @Param body body []integer false "Массив идентификаторов доменов"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /domain/delete_domains [POST]
func (c Domain) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) {
if len(req) == 0 {
return nil, apierrors.NewBusinessError(domain.ErrCodeInvalidRequest,
"At least one id are required", errors.New("invalid id count"))
return nil, status.Errorf(codes.InvalidArgument, "at least one id are required")
}
result, err := c.service.Delete(ctx, req)
+21 -24
View File
@@ -3,14 +3,13 @@ package controller
import (
"context"
"isp-system-service/domain"
"github.com/pkg/errors"
"isp-system-service/domain"
)
type SecureService interface {
Authenticate(ctx context.Context, token string) (*domain.AuthData, error)
Authorize(ctx context.Context, req domain.AuthorizeRequest) (bool, error)
Authorize(ctx context.Context, appId int, endpoint string) (bool, error)
}
type Secure struct {
@@ -24,16 +23,15 @@ func NewSecure(service SecureService) Secure {
}
// Authenticate godoc
//
// @Tags secure
// @Summary Метод аутентификации токена
// @Description Проверяет наличие токена в системе,
// @Accept json
// @Produce json
// @Param body body domain.AuthenticateRequest true "Тело запроса"
// @Success 200 {array} domain.AuthenticateResponse
// @Failure 500 {object} apierrors.Error
// @Router /secure/authenticate [POST]
// @Tags secure
// @Summary Метод аутентификации токена
// @Description Проверяет наличие токена в системе,
// @Accept json
// @Produce json
// @Param body body domain.AuthenticateRequest true "Тело запроса"
// @Success 200 {array} domain.AuthenticateResponse
// @Failure 500 {object} domain.GrpcError
// @Router /secure/authenticate [POST]
func (c Secure) Authenticate(ctx context.Context, req domain.AuthenticateRequest) (*domain.AuthenticateResponse, error) {
result, err := c.service.Authenticate(ctx, req.Token)
switch {
@@ -58,18 +56,17 @@ func (c Secure) Authenticate(ctx context.Context, req domain.AuthenticateRequest
}
// Authorize godoc
//
// @Tags secure
// @Summary Метод авторизации приложения
// @Description Проверяет доступ приложения к запрашиваемому ендпоинту
// @Accept json
// @Produce json
// @Param body body domain.AuthorizeRequest true "Тело запрос"
// @Success 200 {array} domain.AuthorizeResponse
// @Failure 500 {object} apierrors.Error
// @Router /secure/authorize [POST]
// @Tags secure
// @Summary Метод авторизации приложения
// @Description Проверяет доступ приложения к запрашиваемому ендпоинту
// @Accept json
// @Produce json
// @Param body body domain.AuthorizeRequest true "Тело запрос"
// @Success 200 {array} domain.AuthorizeResponse
// @Failure 500 {object} domain.GrpcError
// @Router /secure/authorize [POST]
func (c Secure) Authorize(ctx context.Context, req domain.AuthorizeRequest) (*domain.AuthorizeResponse, error) {
result, err := c.service.Authorize(ctx, req)
result, err := c.service.Authorize(ctx, req.ApplicationId, req.Endpoint)
switch {
case errors.Is(err, domain.ErrAccessListNotFound):
return &domain.AuthorizeResponse{
+68 -95
View File
@@ -2,20 +2,18 @@ package controller
import (
"context"
"fmt"
"isp-system-service/domain"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/grpc/apierrors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-system-service/domain"
)
type ServiceService interface {
GetById(ctx context.Context, id int) (*domain.Service, error)
GetByIdList(ctx context.Context, idList []int) ([]domain.Service, error)
GetByDomainId(ctx context.Context, domainId int) ([]domain.Service, error)
CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdateRequest) (*domain.Service, error)
GetById(ctx context.Context, id int) (*domain.ApplicationGroup, error)
GetByIdList(ctx context.Context, idList []int) ([]domain.ApplicationGroup, error)
GetByDomainId(ctx context.Context, domainId int) ([]domain.ApplicationGroup, error)
CreateUpdate(ctx context.Context, req domain.ApplicationGroupCreateUpdateRequest) (*domain.ApplicationGroup, error)
Delete(ctx context.Context, idList []int) (int, error)
}
@@ -30,27 +28,21 @@ func NewService(service ServiceService) Service {
}
// GetById godoc
//
// @Tags service
// @Summary Получить сервис по идентификатору
// @Description Возвращает описание сервиса по его идентификатору
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор сервиса"
// @Success 200 {object} domain.Service
// @Failure 404 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /service/get_service_by_id [POST]
func (c Service) GetById(ctx context.Context, req domain.Identity) (*domain.Service, error) {
// @Tags service
// @Summary Получить сервис по идентификатору
// @Description Возвращает описание сервиса по его идентификатору
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор сервиса"
// @Success 200 {object} domain.Service
// @Failure 404 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /service/get_service_by_id [POST]
func (c Service) GetById(ctx context.Context, req domain.Identity) (*domain.ApplicationGroup, error) {
result, err := c.service.GetById(ctx, req.Id)
switch {
case errors.Is(err, domain.ErrAppGroupNotFound):
return nil, apierrors.New(
codes.NotFound,
domain.ErrCodeAppGroupNotFound,
fmt.Sprintf("service with id %d not found", req.Id),
err,
)
case errors.Is(err, domain.ErrApplicationGroupNotFound):
return nil, status.Errorf(codes.NotFound, "service with id %d not found", req.Id)
case err != nil:
return nil, err
default:
@@ -59,72 +51,55 @@ func (c Service) GetById(ctx context.Context, req domain.Identity) (*domain.Serv
}
// Get godoc
//
// @Tags service
// @Summary Получить список сервисов
// @Description Возвращает список сервисов по их идентификаторам
// @Accept json
// @Produce json
// @Param body body []integer false "Массив идентификаторов сервисов"
// @Success 200 {array} domain.Service
// @Failure 500 {object} apierrors.Error
// @Router /service/get_service [POST]
func (c Service) Get(ctx context.Context, req []int) ([]domain.Service, error) {
// @Tags service
// @Summary Получить список сервисов
// @Description Возвращает список сервисов по их идентификаторам
// @Accept json
// @Produce json
// @Param body body []integer false "Массив идентификаторов сервисов"
// @Success 200 {array} domain.Service
// @Failure 500 {object} domain.GrpcError
// @Router /service/get_service [POST]
func (c Service) Get(ctx context.Context, req []int) ([]domain.ApplicationGroup, error) {
return c.service.GetByIdList(ctx, req)
}
// GetByDomainId godoc
//
// @Tags service
// @Summary Получить список сервисов по идентификатору домена
// @Description Возвращает список сервисов по идентификатору домена
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор домена"
// @Success 200 {array} domain.Service
// @Failure 500 {object} apierrors.Error
// @Router /service/get_services_by_domain_id [POST]
func (c Service) GetByDomainId(ctx context.Context, req domain.Identity) ([]domain.Service, error) {
// @Tags service
// @Summary Получить список сервисов по идентификатору домена
// @Description Возвращает список сервисов по идентификатору домена
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор домена"
// @Success 200 {array} domain.Service
// @Failure 500 {object} domain.GrpcError
// @Router /service/get_services_by_domain_id [POST]
func (c Service) GetByDomainId(ctx context.Context, req domain.Identity) ([]domain.ApplicationGroup, error) {
return c.service.GetByDomainId(ctx, req.Id)
}
// CreateUpdate godoc
//
// @Tags service
// @Summary Создать/обновить сервис
// @Description Если сервис с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
// @Accept json
// @Produce json
// @Param body body domain.ServiceCreateUpdateRequest true "Объект сервиса"
// @Success 200 {object} domain.Service
// @Failure 400 {object} apierrors.Error
// @Failure 404 {object} apierrors.Error
// @Failure 409 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /service/create_update_service [POST]
func (c Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdateRequest) (*domain.Service, error) {
// @Tags service
// @Summary Создать/обновить сервис
// @Description Если сервис с такими идентификатором существует, то обновляет данные, если нет, то добавляет данные в базу
// @Accept json
// @Produce json
// @Param body body domain.ServiceCreateUpdateRequest true "Объект сервиса"
// @Success 200 {object} domain.Service
// @Failure 400 {object} domain.GrpcError
// @Failure 404 {object} domain.GrpcError
// @Failure 409 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /service/create_update_service [POST]
func (c Service) CreateUpdate(ctx context.Context, req domain.ApplicationGroupCreateUpdateRequest) (*domain.ApplicationGroup, error) {
result, err := c.service.CreateUpdate(ctx, req)
switch {
case errors.Is(err, domain.ErrDomainNotFound):
return nil, apierrors.NewBusinessError(
domain.ErrCodeDomainNotFound,
fmt.Sprintf("domain with id %d not found", req.DomainId),
err,
)
case errors.Is(err, domain.ErrAppGroupNotFound):
return nil, apierrors.New(
codes.NotFound,
domain.ErrCodeAppGroupNotFound,
fmt.Sprintf("service with id %d not found", req.Id),
err,
)
case errors.Is(err, domain.ErrAppGroupDuplicateName):
return nil, apierrors.New(
codes.AlreadyExists,
domain.ErrCodeAppGroupNotFound,
fmt.Sprintf("service with name %s already exists", req.Name),
err,
)
return nil, status.Errorf(codes.InvalidArgument, "domain with id %d not found", req.DomainId)
case errors.Is(err, domain.ErrApplicationGroupNotFound):
return nil, status.Errorf(codes.NotFound, "service with id %d not found", req.Id)
case errors.Is(err, domain.ErrApplicationGroupDuplicateName):
return nil, status.Errorf(codes.AlreadyExists, "service with name %s already exists", req.Name)
case err != nil:
return nil, err
default:
@@ -133,21 +108,19 @@ func (c Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdat
}
// Delete godoc
//
// @Tags service
// @Summary Удалить сервисы
// @Description Удаляет сервисов по списку их идентификаторов, возвращает количество удаленных сервисов
// @Accept json
// @Produce json
// @Param body body []integer true "Массив идентификаторов сервисов"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} apierrors.Error
// @Failure 500 {object} apierrors.Error
// @Router /service/delete_service [POST]
// @Tags service
// @Summary Удалить сервисы
// @Description Удаляет сервисов по списку их идентификаторов, возвращает количество удаленных сервисов
// @Accept json
// @Produce json
// @Param body body []integer true "Массив идентификаторов сервисов"
// @Success 200 {object} domain.DeleteResponse
// @Failure 400 {object} domain.GrpcError
// @Failure 500 {object} domain.GrpcError
// @Router /service/delete_service [POST]
func (c Service) Delete(ctx context.Context, req []int) (*domain.DeleteResponse, error) {
if len(req) == 0 {
return nil, apierrors.NewBusinessError(domain.ErrCodeInvalidRequest,
"At least one id are required", errors.New("invalid id count"))
return nil, status.Error(codes.InvalidArgument, "at least one id are required")
}
result, err := c.service.Delete(ctx, req)
+45 -66
View File
@@ -2,16 +2,14 @@ package controller
import (
"context"
"fmt"
"isp-system-service/domain"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/grpc/apierrors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-system-service/domain"
)
type TokenService interface {
type ITokenService interface {
GetByAppId(ctx context.Context, appId int) ([]domain.Token, error)
Create(ctx context.Context, req domain.TokenCreateRequest) (*domain.ApplicationWithTokens, error)
Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*domain.ApplicationWithTokens, error)
@@ -19,65 +17,48 @@ type TokenService interface {
}
type Token struct {
service TokenService
service ITokenService
}
func NewToken(service TokenService) Token {
func NewToken(service ITokenService) Token {
return Token{
service: service,
}
}
// GetByAppId godoc
//
// @Tags token
// @Summary Получить токены по идентификатору приложения
// @Description Возвращает список токенов, привязанных к приложению
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор приложения"
// @Success 200 {array} entity.Token
// @Failure 500 {object} apierrors.Error
// @Router /token/get_tokens_by_app_id [POST]
// @Tags token
// @Summary Получить токены по идентификатору приложения
// @Description Возвращает список токенов, привязанных к приложению
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор приложения"
// @Success 200 {array} entity.Token
// @Failure 500 {object} domain.GrpcError
// @Router /token/get_tokens_by_app_id [POST]
func (c Token) GetByAppId(ctx context.Context, req domain.Identity) ([]domain.Token, error) {
return c.service.GetByAppId(ctx, req.Id)
}
// Create godoc
//
// @Tags token
// @Summary Создать токен
// @Description Создает токен и привязывает его к приложению
// @Accept json
// @Produce json
// @Param body body domain.TokenCreateRequest true "Объект создания токена"
// @Success 200 {object} domain.ApplicationWithTokens
// @Failure 500 {object} apierrors.Error
// @Router /token/create_token [POST]
// @Tags token
// @Summary Создать токен
// @Description Создает токен и привязывает его к приложению
// @Accept json
// @Produce json
// @Param body body domain.TokenCreateRequest true "Объект создания токена"
// @Success 200 {object} domain.ApplicationWithTokens
// @Failure 500 {object} domain.GrpcError
// @Router /token/create_token [POST]
func (c Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*domain.ApplicationWithTokens, error) {
result, err := c.service.Create(ctx, req)
switch {
case errors.Is(err, domain.ErrApplicationNotFound):
return nil, apierrors.New(
codes.NotFound,
domain.ErrCodeApplicationNotFound,
fmt.Sprintf("application with id %d not found", req.AppId),
err,
)
case errors.Is(err, domain.ErrAppGroupNotFound):
return nil, apierrors.New(
codes.NotFound,
domain.ErrCodeAppGroupNotFound,
fmt.Sprintf("service for app_id id %d not found", req.AppId),
err,
)
return nil, status.Errorf(codes.NotFound, "application with id %d not found", req.AppId)
case errors.Is(err, domain.ErrApplicationGroupNotFound):
return nil, status.Errorf(codes.NotFound, "application group for app_id id %d not found", req.AppId)
case errors.Is(err, domain.ErrDomainNotFound):
return nil, apierrors.New(
codes.NotFound,
domain.ErrCodeDomainNotFound,
fmt.Sprintf("domain for app_id id %d not found", req.AppId),
err,
)
return nil, status.Errorf(codes.NotFound, "domain for app_id %d not found", req.AppId)
case err != nil:
return nil, err
default:
@@ -86,31 +67,29 @@ func (c Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*doma
}
// Revoke godoc
//
// @Tags token
// @Summary Отозвать токены
// @Description Отвязывает токены от приложений и удаляет их
// @Accept json
// @Produce json
// @Param body body domain.TokenRevokeRequest true "Объект отзыва токенов"
// @Success 200 {object} domain.ApplicationWithTokens
// @Failure 500 {object} apierrors.Error
// @Router /token/revoke_tokens [POST]
// @Tags token
// @Summary Отозвать токены
// @Description Отвязывает токены от приложений и удаляет их
// @Accept json
// @Produce json
// @Param body body domain.TokenRevokeRequest true "Объект отзыва токенов"
// @Success 200 {object} domain.ApplicationWithTokens
// @Failure 500 {object} domain.GrpcError
// @Router /token/revoke_tokens [POST]
func (c Token) Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*domain.ApplicationWithTokens, error) {
return c.service.Revoke(ctx, req)
}
// RevokeForApp godoc
//
// @Tags token
// @Summary Отозвать токены для приложения
// @Description Отвязывает токены от приложений и удаляет их по идентификатору приложения
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор приложения"
// @Success 200 {object} domain.DeleteResponse
// @Failure 500 {object} apierrors.Error
// @Router /token/revoke_tokens_for_app [POST]
// @Tags token
// @Summary Отозвать токены для приложения
// @Description Отвязывает токены от приложений и удаляет их по идентификатору приложения
// @Accept json
// @Produce json
// @Param body body domain.Identity true "Идентификатор приложения"
// @Success 200 {object} domain.DeleteResponse
// @Failure 500 {object} domain.GrpcError
// @Router /token/revoke_tokens_for_app [POST]
func (c Token) RevokeForApp(ctx context.Context, req domain.Identity) (*domain.DeleteResponse, error) {
return c.service.RevokeByAppId(ctx, req.Id)
}
-9
View File
@@ -1,9 +0,0 @@
package docs
import _ "embed"
// Embedded swagger files.
var (
//go:embed swagger.json
SwaggerJson []byte
)
-2296
View File
File diff suppressed because it is too large. Load diff
+1012
View File
File diff suppressed because it is too large. Load diff
+6 -23
View File
@@ -1,10 +1,9 @@
package domain
type AccessListSetOneRequest struct {
AppId int `validate:"required"`
HttpMethod string
Method string `validate:"required"`
Value bool
AppId int `valid:"required~Required"`
Method string `valid:"required~Required"`
Value bool
}
type AccessListSetOneResponse struct {
@@ -12,28 +11,12 @@ type AccessListSetOneResponse struct {
}
type AccessListSetListRequest struct {
AppId int `validate:"required"`
AppId int `valid:"required~Required"`
RemoveOld bool
Methods []MethodInfo
}
type MethodInfo struct {
HttpMethod string
Method string
Value bool
}
type AccessListDeleteListRequest struct {
AppId int `validate:"required"`
Methods []string `validate:"required,min=1"`
}
type AccessListDeleteV2ListRequest struct {
AppId int `validate:"required"`
Methods []Method `validate:"required,min=1"`
}
type Method struct {
HttpMethod string
Method string `validate:"required"`
Method string
Value bool
}
-26
View File
@@ -1,26 +0,0 @@
package domain
import "time"
type AppGroup struct {
Id int
Name string
Description string
CreatedAt time.Time
UpdatedAt time.Time
}
type CreateAppGroupRequest struct {
Name string `validate:"required"`
Description string
}
type UpdateAppGroupRequest struct {
Id int `validate:"required"`
Name string `validate:"required"`
Description string
}
type IdListRequest struct {
IdList []int `validate:"required,min=1"`
}
+12 -41
View File
@@ -4,27 +4,22 @@ import (
"time"
)
const (
ApplicationSystemType = "SYSTEM"
ApplicationMobileType = "MOBILE"
)
type Application struct {
Id int
Name string
Description string
ServiceId int
Type string
CreatedAt time.Time
UpdatedAt time.Time
Id int
Name string
Description string
ApplicationGroupId int
Type string
CreatedAt time.Time
UpdatedAt time.Time
}
type ApplicationCreateUpdateRequest struct {
Id int
Name string `validate:"required"`
Description string
ServiceId int `validate:"required"`
Type string `validate:"required,oneof=SYSTEM MOBILE"`
Id int
Name string `valid:"required~Required"`
Description string
ApplicationGroupId int `valid:"required~Required"`
Type string `valid:"required~Required,in(SYSTEM|MOBILE)"`
}
type ApplicationWithTokens struct {
@@ -39,27 +34,3 @@ type ApplicationSimple struct {
Type string
Tokens []Token
}
type CreateApplicationRequest struct {
Id int `validate:"required"`
Name string `validate:"required"`
Description string
ApplicationGroupId int `validate:"required"`
Type string `validate:"required,oneof=SYSTEM MOBILE"`
}
type UpdateApplicationRequest struct {
OldId int `validate:"required"`
NewId int `validate:"required"`
Name string `validate:"required"`
Description string
}
type GetApplicationByTokenRequest struct {
Token string `validate:"required"`
}
type GetApplicationByTokenResponse struct {
ApplicationId int
ApplicationGroupId int
}
@@ -4,7 +4,7 @@ import (
"time"
)
type Service struct {
type ApplicationGroup struct {
Id int
Name string
Description string
@@ -13,14 +13,14 @@ type Service struct {
UpdatedAt time.Time
}
type ServiceCreateUpdateRequest struct {
type ApplicationGroupCreateUpdateRequest struct {
Id int
Name string `validate:"required"`
Name string `valid:"required~Required"`
Description string
DomainId int `validate:"required"`
DomainId int `valid:"required~Required"`
}
type ServiceWithApps struct {
type ApplicationGroupWithApps struct {
Id int
Name string
Description string
+1 -1
View File
@@ -2,7 +2,7 @@ package domain
type (
Identity struct {
Id int `validate:"required"`
Id int `valid:"required~Required"`
}
DeleteResponse struct {
+6 -6
View File
@@ -6,7 +6,7 @@ import (
type DomainCreateUpdateRequest struct {
Id int
Name string `validate:"required"`
Name string `valid:"required~Required"`
Description string
}
@@ -19,9 +19,9 @@ type Domain struct {
UpdatedAt time.Time
}
type DomainWithService struct {
Id int
Name string
Description string
Services []*ServiceWithApps
type DomainWithApplicationGroup struct {
Id int
Name string
Description string
ApplicationGroup []*ApplicationGroupWithApps
}
+2 -18
View File
@@ -4,33 +4,17 @@ import (
"github.com/pkg/errors"
)
const (
ErrCodeInvalidRequest = 600
ErrCodeApplicationNotFound = 602
ErrCodeApplicationDuplicateName = 603
ErrCodeApplicationDuplicateId = 604
ErrCodeAppGroupNotFound = 605
ErrCodeAppGroupDuplicateName = 606
ErrCodeSystemNotFound = 607
ErrCodeDomainNotFound = 608
ErrCodeDomainDuplicateName = 609
)
var (
ErrDomainNotFound = errors.New("domain not found")
ErrDomainDuplicateName = errors.New("domain name already exist")
ErrAppGroupNotFound = errors.New("application group not found")
ErrAppGroupDuplicateName = errors.New("application group name already exist")
ErrApplicationGroupNotFound = errors.New("application group not found")
ErrApplicationGroupDuplicateName = errors.New("application group name already exist")
ErrSystemNotFound = errors.New("system not found")
ErrApplicationNotFound = errors.New("application not found")
ErrApplicationDuplicateName = errors.New("application name already exist")
ErrApplicationDuplicateId = errors.New("application id already exist")
ErrTokenNotFound = errors.New("token not found")
ErrTokenExpired = errors.New("token is expired")
+7
View File
@@ -0,0 +1,7 @@
package domain
type GrpcError struct {
ErrorMessage string `json:"errorMessage"`
ErrorCode string `json:"errorCode"`
Details []interface{} `json:"details"`
}
+7 -9
View File
@@ -1,7 +1,7 @@
package domain
type AuthenticateRequest struct {
Token string `validate:"required"`
Token string `valid:"required~Required"`
}
type AuthenticateResponse struct {
@@ -11,17 +11,15 @@ type AuthenticateResponse struct {
}
type AuthData struct {
AppName string
SystemId int
DomainId int
ServiceId int
ApplicationId int
SystemId int
DomainId int
ApplicationGroupId int
ApplicationId int
}
type AuthorizeRequest struct {
ApplicationId int `validate:"required"`
HttpMethod string
Endpoint string `validate:"required"`
ApplicationId int `valid:"required~Required"`
Endpoint string `valid:"required~Required"`
}
type AuthorizeResponse struct {
+3 -3
View File
@@ -12,11 +12,11 @@ type Token struct {
}
type TokenRevokeRequest struct {
AppId int `validate:"required"`
AppId int `valid:"required~Required"`
Tokens []string
}
type TokenCreateRequest struct {
AppId int `validate:"required"`
ExpireTimeMs int `validate:"required"`
AppId int `valid:"required~Required"`
ExpireTimeMs int `valid:"required~Required"`
}
+3 -9
View File
@@ -1,13 +1,7 @@
package entity
type AccessList struct {
AppId int
HttpMethod string
Method string
Value bool
}
type Method struct {
HttpMethod string
Method string
AppId int
Method string
Value bool
}
+1 -2
View File
@@ -1,14 +1,13 @@
package entity
import (
"database/sql"
"time"
)
type Application struct {
Id int
Name string
Description sql.NullString
Description *string
ApplicationGroupId int
Type string
CreatedAt time.Time
@@ -1,14 +1,13 @@
package entity
import (
"database/sql"
"time"
)
type AppGroup struct {
type ApplicationGroup struct {
Id int
Name string
Description sql.NullString
Description *string
DomainId int
CreatedAt time.Time
UpdatedAt time.Time
+6 -7
View File
@@ -12,11 +12,10 @@ type Token struct {
}
type AuthData struct {
AppName string
SystemId int
DomainId int
ApplicationGroupId int
AppId int
ExpireTime int
CreatedAt time.Time
SystemId int
DomainId int
ApplicationGroupIdId int
AppId int
ExpireTime int
CreatedAt time.Time
}
+40 -47
View File
@@ -1,82 +1,75 @@
module isp-system-service
go 1.25
go 1.22
require (
github.com/Masterminds/squirrel v1.5.4
github.com/jackc/pgx/v5 v5.8.0
github.com/pkg/errors v0.9.1
github.com/stretchr/testify v1.11.1
github.com/txix-open/isp-kit v1.64.10
github.com/txix-open/jsonschema v1.3.0
google.golang.org/grpc v1.78.0
github.com/pressly/goose v2.7.0+incompatible
github.com/stretchr/testify v1.9.0
github.com/txix-open/isp-kit v1.31.4
github.com/txix-open/jsonschema v1.2.0
google.golang.org/grpc v1.64.0
)
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/cenkalti/backoff/v4 v4.3.0 // 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.13 // indirect
github.com/getsentry/sentry-go v0.42.0 // indirect
github.com/go-faker/faker/v4 v4.6.1 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/getsentry/sentry-go v0.27.0 // indirect
github.com/go-logr/logr v1.4.1 // 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.8 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.19.1 // indirect
github.com/iancoleman/strcase v0.3.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 // indirect
github.com/jackc/pgx/v5 v5.5.5 // indirect
github.com/jackc/puddle/v2 v2.2.1 // indirect
github.com/jmoiron/sqlx v1.4.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mailru/easyjson v0.9.1 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/mfridman/interpolate v0.0.2 // 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/pressly/goose/v3 v3.26.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.67.5 // indirect
github.com/prometheus/procfs v0.19.2 // indirect
github.com/sethvargo/go-retry v0.3.0 // indirect
github.com/pressly/goose/v3 v3.20.0 // indirect
github.com/prometheus/client_golang v1.19.0 // indirect
github.com/prometheus/client_model v0.6.1 // indirect
github.com/prometheus/common v0.53.0 // indirect
github.com/prometheus/procfs v0.14.0 // indirect
github.com/sethvargo/go-retry v0.2.4 // indirect
github.com/txix-open/bellows v1.2.0 // indirect
github.com/txix-open/etp/v4 v4.0.1 // indirect
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb // indirect
github.com/txix-open/etp/v3 v3.0.0 // indirect
github.com/txix-open/validator/v10 v10.0.0-20240401163703-e83541b40f99 // indirect
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/otel v1.40.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.40.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.40.0 // indirect
go.opentelemetry.io/otel/metric v1.40.0 // indirect
go.opentelemetry.io/otel/sdk v1.40.0 // indirect
go.opentelemetry.io/otel/trace v1.40.0 // indirect
go.opentelemetry.io/proto/otlp v1.9.0 // indirect
go.opentelemetry.io/otel v1.26.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.26.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.26.0 // indirect
go.opentelemetry.io/otel/metric v1.26.0 // indirect
go.opentelemetry.io/otel/sdk v1.26.0 // indirect
go.opentelemetry.io/otel/trace v1.26.0 // indirect
go.opentelemetry.io/proto/otlp v1.2.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.27.1 // indirect
go.yaml.in/yaml/v2 v2.4.3 // indirect
golang.org/x/crypto v0.48.0 // indirect
golang.org/x/net v0.50.0 // indirect
golang.org/x/sync v0.19.0 // indirect
golang.org/x/sys v0.41.0 // indirect
golang.org/x/text v0.34.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20260209200024-4cfbd4190f57 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260209200024-4cfbd4190f57 // indirect
google.golang.org/protobuf v1.36.11 // indirect
go.uber.org/zap v1.27.0 // indirect
golang.org/x/crypto v0.22.0 // indirect
golang.org/x/net v0.24.0 // indirect
golang.org/x/sync v0.7.0 // indirect
golang.org/x/sys v0.19.0 // indirect
golang.org/x/text v0.14.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20240415180920-8c6c420018be // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240415180920-8c6c420018be // indirect
google.golang.org/protobuf v1.33.0 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
nhooyr.io/websocket v1.8.11 // indirect
)
+103 -125
View File
@@ -10,28 +10,24 @@ 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/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
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/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/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM=
github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/getsentry/sentry-go v0.42.0 h1:eeFMACuZTbUQf90RE8dE4tXeSe4CZyfvR1MBL7RLEt8=
github.com/getsentry/sentry-go v0.42.0/go.mod h1:eRXCoh3uvmjQLY6qu63BjUZnaBu5L5WhMV1RwYO8W5s=
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
github.com/getsentry/sentry-go v0.27.0 h1:Pv98CIbtB3LkMWmXi4Joa5OOcwbmnX88sF5qbK3r3Ps=
github.com/getsentry/sentry-go v0.27.0/go.mod h1:lc76E2QywIyW8WuBnwl8Lc4bkmQH4+w1gwTf25trprY=
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/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ=
github.com/go-logr/logr v1.4.1/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=
@@ -40,42 +36,36 @@ github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/o
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-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo=
github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
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/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
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.8 h1:NpbJl/eVbvrGE0MJ6X16X9SAifesl6Fwxg/YmCvubRI=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.8/go.mod h1:mi7YA+gCzVem12exXy46ZespvGtX/lZmD/RLnQhVW7U=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.19.1 h1:/c3QmbOGMGTOumP2iT/rCwB7b0QDGLKzqOmktBjT+Is=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.19.1/go.mod h1:5SN9VR2LTsRFsrEC6FHgRbTWrTHu6tqPeKxEQv15giM=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.8.0 h1:TYPDoleBBme0xGSAX3/+NujXXtpZn9HBONkQC7IEZSo=
github.com/jackc/pgx/v5 v5.8.0/go.mod h1:QVeDInX2m9VyzvNeiCJVjCkNFqzsNb43204HshNSZKw=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 h1:L0QtFUgDarD7Fpv9jeVMgy/+Ec0mtnmYuImjTz6dtDA=
github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.5.5 h1:amBjrZVmksIdNjxGW/IiIMzxMKZFelXbUoPNb+8sjQw=
github.com/jackc/pgx/v5 v5.5.5/go.mod h1:ez9gk+OAat140fv9ErkZDYFWmXLfV+++K0uAOiwgm1A=
github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk=
github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
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/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq6+3iTQz8KNCLtVX6idSoTLdUw=
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o=
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk=
@@ -84,8 +74,8 @@ 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/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mailru/easyjson v0.9.1 h1:LbtsOm5WAswyWbvTEOqhypdPeZzHavpZx96/n553mR8=
github.com/mailru/easyjson v0.9.1/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
@@ -99,8 +89,6 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w
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/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4=
@@ -109,24 +97,26 @@ 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/pressly/goose/v3 v3.26.0 h1:KJakav68jdH0WDvoAcj8+n61WqOIaPGgH0bJWS6jpmM=
github.com/pressly/goose/v3 v3.26.0/go.mod h1:4hC1KrritdCxtuFsqgs1R4AU5bWtTAf+cnWvfhf2DNY=
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.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4=
github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw=
github.com/prometheus/procfs v0.19.2 h1:zUMhqEW66Ex7OXIiDkll3tl9a1ZdilUOd/F6ZXw4Vws=
github.com/prometheus/procfs v0.19.2/go.mod h1:M0aotyiemPhBCM0z5w87kL22CxfcH05ZpYlu+b4J7mw=
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/pressly/goose v2.7.0+incompatible h1:PWejVEv07LCerQEzMMeAtjuyCKbyprZ/LBa6K5P0OCQ=
github.com/pressly/goose v2.7.0+incompatible/go.mod h1:m+QHWCqxR3k8D9l7qfzuC/djtlfzxr34mozWDYEu1z8=
github.com/pressly/goose/v3 v3.20.0 h1:uPJdOxF/Ipj7ABVNOAMJXSxwFXZGwMGHNqjC8e61VA0=
github.com/pressly/goose/v3 v3.20.0/go.mod h1:BRfF2GcG4FTG12QfdBVy3q1yveaf4ckL9vWwEcIO3lA=
github.com/prometheus/client_golang v1.19.0 h1:ygXvpU1AoN1MhdzckN+PyD9QJOSD4x7kmXYlnfbA6JU=
github.com/prometheus/client_golang v1.19.0/go.mod h1:ZRM9uEAypZakd+q/x7+gmsvXdURP+DABIEIjnmDdp+k=
github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E=
github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY=
github.com/prometheus/common v0.53.0 h1:U2pL9w9nmJwJDa4qqLQ3ZaePJ6ZTwt7cMD3AG3+aLCE=
github.com/prometheus/common v0.53.0/go.mod h1:BrxBKv3FWBIGXw89Mg1AeBq7FSyRzXWI3l3e7W3RN5U=
github.com/prometheus/procfs v0.14.0 h1:Lw4VdGGoKEZilJsayHf0B+9YgLGREba2C6xr+Fdfq6s=
github.com/prometheus/procfs v0.14.0/go.mod h1:XL+Iwz8k8ZabyZfMFHPiilCniixqQarAy5Mu67pHlNQ=
github.com/rabbitmq/amqp091-go v1.9.0 h1:qrQtyzB4H8BQgEuJwhmVQqVHB9O4+MNDJCCAcpc3Aoo=
github.com/rabbitmq/amqp091-go v1.9.0/go.mod h1:+jPrT9iY2eLjRaMSRHUhc3z14E/l85kv/f+6luSD3pc=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
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/sethvargo/go-retry v0.3.0 h1:EEt31A35QhrcRZtrYFDTBg91cqZVnFL2navjDrah2SE=
github.com/sethvargo/go-retry v0.3.0/go.mod h1:mNX17F0C/HguQMyMyJxcnU471gOZGxCLyYaFyAZraas=
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
github.com/sethvargo/go-retry v0.2.4 h1:T+jHEQy/zKJf5s95UkguisicE0zuF9y7+/vgz08Ocec=
github.com/sethvargo/go-retry v0.2.4/go.mod h1:1afjQuvh7s4gflMObvjLPaWgluLLyhA1wmVZ6KLpICw=
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=
@@ -137,80 +127,60 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
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 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
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.10 h1:lAowLtShBbICZbOWQJ4ptr9LaKKRZ7CE5DBK+7LcLqM=
github.com/txix-open/isp-kit v1.64.10/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/txix-open/etp/v3 v3.0.0 h1:dzb28pB5b12r4wWjs1ap1fP10/Wmwngg3mv2V+tkWT4=
github.com/txix-open/etp/v3 v3.0.0/go.mod h1:DqYK1yIERoFsOWmlgYNrKfLU5u3dE4N64Tzpv7aYLLA=
github.com/txix-open/grmq v1.6.0 h1:V4QRb0sI2CMfdMaMsFGvGvUIDGad5vr3khNU7A3LlP8=
github.com/txix-open/grmq v1.6.0/go.mod h1:s+NNNv42+32yLpjvl2tpqtyBbMB9e7kKFee3lfa/dyo=
github.com/txix-open/isp-kit v1.31.4 h1:FiOOpsXBhP7B+YaviDXZjzHpAE/J++r9baEgW4Y2gAc=
github.com/txix-open/isp-kit v1.31.4/go.mod h1:t6/NHdK5JvpIiQU4+NUjky4jLbo7Bz/4hzpoBxZt64U=
github.com/txix-open/jsonschema v1.2.0 h1:B8TrdSsPhDvYv67oi/LVqf7/+PuqFlMsNwUzGeHfl1s=
github.com/txix-open/jsonschema v1.2.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00=
github.com/txix-open/validator/v10 v10.0.0-20240401163703-e83541b40f99 h1:Z0Sqf+U+Sc6hfIXtRCIZlbJprkCjwMFbS4ZbEPQ44To=
github.com/txix-open/validator/v10 v10.0.0-20240401163703-e83541b40f99/go.mod h1:pA0NYmhL0uEkkxj55S+S7MZU4e2QIt46x9XSrzrWc3c=
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=
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo=
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0=
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ=
github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74=
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
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/otel v1.40.0 h1:oA5YeOcpRTXq6NN7frwmwFR0Cn3RhTVZvXsP4duvCms=
go.opentelemetry.io/otel v1.40.0/go.mod h1:IMb+uXZUKkMXdPddhwAHm6UfOwJyh4ct1ybIlV14J0g=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.40.0 h1:QKdN8ly8zEMrByybbQgv8cWBcdAarwmIPZ6FThrWXJs=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.40.0/go.mod h1:bTdK1nhqF76qiPoCCdyFIV+N/sRHYXYCTQc+3VCi3MI=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.40.0 h1:wVZXIWjQSeSmMoxF74LzAnpVQOAFDo3pPji9Y4SOFKc=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.40.0/go.mod h1:khvBS2IggMFNwZK/6lEeHg/W57h/IX6J4URh57fuI40=
go.opentelemetry.io/otel/metric v1.40.0 h1:rcZe317KPftE2rstWIBitCdVp89A2HqjkxR3c11+p9g=
go.opentelemetry.io/otel/metric v1.40.0/go.mod h1:ib/crwQH7N3r5kfiBZQbwrTge743UDc7DTFVZrrXnqc=
go.opentelemetry.io/otel/sdk v1.40.0 h1:KHW/jUzgo6wsPh9At46+h4upjtccTmuZCFAc9OJ71f8=
go.opentelemetry.io/otel/sdk v1.40.0/go.mod h1:Ph7EFdYvxq72Y8Li9q8KebuYUr2KoeyHx0DRMKrYBUE=
go.opentelemetry.io/otel/sdk/metric v1.40.0 h1:mtmdVqgQkeRxHgRv4qhyJduP3fYJRMX4AtAlbuWdCYw=
go.opentelemetry.io/otel/sdk/metric v1.40.0/go.mod h1:4Z2bGMf0KSK3uRjlczMOeMhKU2rhUqdWNoKcYrtcBPg=
go.opentelemetry.io/otel/trace v1.40.0 h1:WA4etStDttCSYuhwvEa8OP8I5EWu24lkOzp+ZYblVjw=
go.opentelemetry.io/otel/trace v1.40.0/go.mod h1:zeAhriXecNGP/s2SEG3+Y8X9ujcJOTqQ5RgdEJcawiA=
go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A=
go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4=
go.opentelemetry.io/otel v1.26.0 h1:LQwgL5s/1W7YiiRwxf03QGnWLb2HW4pLiAhaA5cZXBs=
go.opentelemetry.io/otel v1.26.0/go.mod h1:UmLkJHUAidDval2EICqBMbnAd0/m2vmpf/dAM+fvFs4=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.26.0 h1:1u/AyyOqAWzy+SkPxDpahCNZParHV8Vid1RnI2clyDE=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.26.0/go.mod h1:z46paqbJ9l7c9fIPCXTqTGwhQZ5XoTIsfeFYWboizjs=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.26.0 h1:1wp/gyxsuYtuE/JFxsQRtcCDtMrO2qMvlfXALU5wkzI=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.26.0/go.mod h1:gbTHmghkGgqxMomVQQMur1Nba4M0MQ8AYThXDUjsJ38=
go.opentelemetry.io/otel/metric v1.26.0 h1:7S39CLuY5Jgg9CrnA9HHiEjGMF/X2VHvoXGgSllRz30=
go.opentelemetry.io/otel/metric v1.26.0/go.mod h1:SY+rHOI4cEawI9a7N1A4nIg/nTQXe1ccCNWYOJUrpX4=
go.opentelemetry.io/otel/sdk v1.26.0 h1:Y7bumHf5tAiDlRYFmGqetNcLaVUZmh4iYfmGxtmz7F8=
go.opentelemetry.io/otel/sdk v1.26.0/go.mod h1:0p8MXpqLeJ0pzcszQQN4F0S5FVjBLgypeGSngLsmirs=
go.opentelemetry.io/otel/trace v1.26.0 h1:1ieeAUb4y0TE26jUFrCIXKpTuVK7uJGN9/Z/2LP5sQA=
go.opentelemetry.io/otel/trace v1.26.0/go.mod h1:4iDxvGDQuUkHve82hJJ8UqrwswHYsZuWCBllGV2U2y0=
go.opentelemetry.io/proto/otlp v1.2.0 h1:pVeZGk7nXDC9O2hncA6nHldxEjm6LByfA2aN8IOkz94=
go.opentelemetry.io/proto/otlp v1.2.0/go.mod h1:gGpR8txAl5M03pDhMC79G6SdqNV26naRm/KDsgaHD8A=
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.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=
go.uber.org/zap v1.27.1/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.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b h1:M2rDM6z3Fhozi9O7NWsxAkg/yqS/lQJ6PmkyIV3YP+o=
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8=
golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60=
golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM=
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
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-20260209200024-4cfbd4190f57 h1:JLQynH/LBHfCTSbDWl+py8C+Rg/k1OVH3xfcaiANuF0=
google.golang.org/genproto/googleapis/api v0.0.0-20260209200024-4cfbd4190f57/go.mod h1:kSJwQxqmFXeo79zOmbrALdflXQeAYcUbgS7PbpMknCY=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260209200024-4cfbd4190f57 h1:mWPCjDEyshlQYzBpMNHaEof6UX1PmHcaUODUywQ0uac=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260209200024-4cfbd4190f57/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=
google.golang.org/grpc v1.78.0 h1:K1XZG/yGDJnzMdd/uZHAkVqJE+xIDOcmdSFZkBUicNc=
google.golang.org/grpc v1.78.0/go.mod h1:I47qjTo4OKbMkjA/aOOwxDIiPSBofUtQUI5EfpWvW7U=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30=
golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w=
golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8=
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
google.golang.org/genproto/googleapis/api v0.0.0-20240415180920-8c6c420018be h1:Zz7rLWqp0ApfsR/l7+zSHhY3PMiH2xqgxlfYfAfNpoU=
google.golang.org/genproto/googleapis/api v0.0.0-20240415180920-8c6c420018be/go.mod h1:dvdCTIoAGbkWbcIKBniID56/7XHTt6WfxXNMxuziJ+w=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240415180920-8c6c420018be h1:LG9vZxsWGOmUKieR8wPAUR3u3MpnYFQZROPIMaXh7/A=
google.golang.org/genproto/googleapis/rpc v0.0.0-20240415180920-8c6c420018be/go.mod h1:WtryC6hu0hhx87FDGxWCDptyssuo68sk10vYjF+T9fY=
google.golang.org/grpc v1.64.0 h1:KH3VH9y/MgNQg1dE7b3XfVK0GsPSIzJwdF617gUSbvY=
google.golang.org/grpc v1.64.0/go.mod h1:oxjF8E3FBnjp+/gVFYdWacaLDx9na1aqy9oovLpxQYg=
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
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=
@@ -219,11 +189,19 @@ gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYs
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=
modernc.org/libc v1.66.3 h1:cfCbjTUcdsKyyZZfEUKfoHcP3S0Wkvz3jgSzByEWVCQ=
modernc.org/libc v1.66.3/go.mod h1:XD9zO8kt59cANKvHPXpx7yS2ELPheAey0vjIuZOhOU8=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/sqlite v1.38.2 h1:Aclu7+tgjgcQVShZqim41Bbw9Cho0y/7WzYptXqkEek=
modernc.org/sqlite v1.38.2/go.mod h1:cPTJYSlgg3Sfg046yBShXENNtPrWrDX8bsbAQBzgQ5E=
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 h1:5D53IMaUuA5InSeMu9eJtlQXS2NxAhyWQvkKEgXZhHI=
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4=
modernc.org/libc v1.41.0 h1:g9YAc6BkKlgORsUWj+JwqoB1wU3o4DE3bM3yvA3k+Gk=
modernc.org/libc v1.41.0/go.mod h1:w0eszPsiXoOnoMJgrXjglgLuDy/bt5RR4y3QzUUeodY=
modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=
modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=
modernc.org/memory v1.7.2 h1:Klh90S215mmH8c9gO98QxQFsY+W451E8AnzjoE2ee1E=
modernc.org/memory v1.7.2/go.mod h1:NO4NVCQy0N7ln+T9ngWqOQfi7ley4vpwvARR+Hjw95E=
modernc.org/sqlite v1.29.6 h1:0lOXGrycJPptfHDuohfYgNqoe4hu+gYuN/pKgY5XjS4=
modernc.org/sqlite v1.29.6/go.mod h1:S02dvcmm7TnTRvGhv8IGYyLnIt7AS2KPaB1F/71p75U=
modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA=
modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0=
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
nhooyr.io/websocket v1.8.11 h1:f/qXNc2/3DpoSZkHt1DQu6rj4zGC8JmkkLkWss0MgN0=
nhooyr.io/websocket v1.8.11/go.mod h1:rN9OFWIUwuxg4fR5tELlYC04bXYowCP9GX47ivo2l+c=
+12 -13
View File
@@ -1,32 +1,30 @@
package main
import (
"github.com/txix-open/isp-kit/bootstrap"
"github.com/txix-open/isp-kit/shutdown"
"isp-system-service/assembly"
"isp-system-service/conf"
"isp-system-service/routes"
"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"
)
// @title isp-system-service
// @version 1.0.0
// @description Сервис управления реестром внешних приложений и токенами аутентификации
// @title isp-system-service
// @version 1.0.0
// @description Сервис управления реестром внешних приложений и токенами аутентификации
// @license.name GNU GPL v3.0
// @license.name GNU GPL v3.0
// @host localhost:9000
// @BasePath /api/system
// @host localhost:9000
// @BasePath /api/system
//go:generate swag init --parseDependency
//go:generate rm -f docs/swagger.yaml docs/docs.go
//go:generate rm -f docs/swagger.json
func main() {
boot := bootstrap.New(version, conf.Remote{}, routes.EndpointDescriptors(), cluster.GrpcTransport)
boot := bootstrap.New(version, conf.Remote{}, routes.EndpointDescriptors())
app := boot.App
logger := app.Logger()
@@ -45,6 +43,7 @@ func main() {
err = app.Run()
if err != nil {
boot.Fatal(err)
app.Shutdown()
logger.Fatal(app.Context(), err)
}
}
+160
View File
@@ -0,0 +1,160 @@
package migrations
import (
"database/sql"
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/pkg/errors"
"github.com/pressly/goose"
"isp-system-service/domain"
)
const (
insertDomain = "INSERT INTO %s.domain (id, name, description, system_id) VALUES (%d, '%s', '%s', %d) RETURNING id;"
insertApplicationGroup = "INSERT INTO %s.application_group (id, name, description, domain_id) VALUES (%d, '%s', '%s', %d) RETURNING id;"
insertApp = "INSERT INTO %s.application (id, name, description, application_group_id, type) VALUES (%d, '%s', '%s', %d, '%s') RETURNING id;"
insertToken = "INSERT INTO %s.token (token, app_id, expire_time) VALUES ('%s', %d, %d);"
setSeqQuery = "SELECT setval('%s.%s_id_seq' :: regclass, %d);"
initFile = "init.json"
)
func init() {
goose.AddMigration(Initialize.Up, Initialize.Down)
}
var Initialize = &initializeMigration{}
type initializeMigration struct {
migrationDir string
schema string
}
type identity struct {
domainId int
appId int
applicationGroupId int
}
func (i *initializeMigration) SetParams(migrationDir string, schema string) {
i.migrationDir = migrationDir
i.schema = schema
}
func (i *initializeMigration) Up(tx *sql.Tx) error {
path := filepath.Join(i.migrationDir, initFile)
bytes, err := os.ReadFile(path)
if err != nil {
return errors.WithMessage(err, "read file")
}
list := make([]domain.DomainWithApplicationGroup, 0)
err = json.Unmarshal(bytes, &list)
if err != nil {
return errors.WithMessage(err, "json unmarshal")
}
lastDomainId := 0
lastApplicationGroupId := 0
lastAppId := 0
for _, domainInfo := range list {
last, err := i.insert(tx, domainInfo)
if err != nil {
return errors.WithMessage(err, "")
}
if last.domainId > lastDomainId {
lastDomainId = last.domainId
}
if last.applicationGroupId > lastApplicationGroupId {
lastApplicationGroupId = last.applicationGroupId
}
if last.appId > lastAppId {
lastAppId = last.appId
}
}
err = i.setSeq(tx, "domain", lastDomainId)
if err != nil {
return errors.WithMessage(err, "set domain")
}
err = i.setSeq(tx, "application_group", lastApplicationGroupId)
if err != nil {
return errors.WithMessage(err, "set application group")
}
err = i.setSeq(tx, "application", lastAppId)
if err != nil {
return errors.WithMessage(err, "set application")
}
return nil
}
func (i *initializeMigration) Down(tx *sql.Tx) error {
return nil
}
func (i *initializeMigration) insert(tx *sql.Tx, domainInfo domain.DomainWithApplicationGroup) (*identity, error) {
domainId, err := i.insertNode(tx, insertDomain, true, i.schema, domainInfo.Id, domainInfo.Name, domainInfo.Description, 1)
if err != nil {
return nil, errors.WithMessage(err, "insert domain")
}
applicationGroupId := 0
appId := 0
for _, applicationGroup := range domainInfo.ApplicationGroup {
applicationGroupId, err = i.insertNode(tx, insertApplicationGroup, true, i.schema, applicationGroup.Id, applicationGroup.Name, applicationGroup.Description, domainId)
if err != nil {
return nil, errors.WithMessage(err, "insert application group")
}
for _, app := range applicationGroup.Apps {
appId, err = i.insertNode(tx, insertApp, true, i.schema, app.Id, app.Name, app.Description, applicationGroupId, app.Type)
if err != nil {
return nil, errors.WithMessage(err, "insert application")
}
for _, t := range app.Tokens {
_, err = i.insertNode(tx, insertToken, false, i.schema, t.Token, appId, t.ExpireTime)
if err != nil {
return nil, errors.WithMessage(err, "insert token")
}
}
}
}
return &identity{
domainId: domainId,
appId: appId,
applicationGroupId: applicationGroupId,
}, nil
}
func (i *initializeMigration) insertNode(tx *sql.Tx, query string, scan bool, args ...interface{}) (int, error) {
var id int
query = fmt.Sprintf(query, args...)
row := tx.QueryRow(query)
if scan {
err := row.Scan(&id)
if err != nil {
return 0, errors.WithMessage(err, "row scan")
}
}
return id, nil
}
func (i *initializeMigration) setSeq(tx *sql.Tx, table string, value int) error {
q := fmt.Sprintf(setSeqQuery, i.schema, table, value)
_, err := tx.Exec(q)
if err != nil {
return errors.WithMessage(err, "exec db")
}
return nil
}
@@ -0,0 +1,7 @@
-- +goose Up
insert into access_list (app_id, method, value)
values (1, 'admin/auth/login', true)
on conflict (app_id, method) do update set value = true;
-- +goose Down
@@ -0,0 +1,11 @@
-- +goose Up
ALTER TABLE service RENAME TO application_group;
ALTER TABLE application RENAME COLUMN service_id TO application_group_id;
ALTER TABLE application RENAME CONSTRAINT UQ_name_service_id TO UQ_name_application_group_id;
ALTER TABLE application RENAME CONSTRAINT FK_service_id__domain_id TO FK_application_group_id__domain_id;
ALTER TRIGGER modify_service ON application_group RENAME TO modify_application_group;
-- +goose Down
@@ -1,5 +0,0 @@
-- +goose Up
update service set domain_id = 1, updated_at = now();
-- +goose Down
@@ -1,42 +0,0 @@
-- +goose Up
ALTER TABLE application ALTER COLUMN id DROP DEFAULT;
DROP SEQUENCE application_id_seq;
ALTER TABLE service RENAME TO application_group;
ALTER TABLE application
RENAME COLUMN service_id TO application_group_id;
ALTER INDEX uq_name_service_id
RENAME TO uq_name_application_group_id;
ALTER TABLE application
RENAME CONSTRAINT "fk_service_id__domain_id" TO "fk_application_group_id";
-- +goose Down
ALTER TABLE application
RENAME CONSTRAINT "fk_application_group_id" TO "fk_service_id__domain_id";
ALTER INDEX uq_name_application_group_id
RENAME TO uq_name_service_id;
ALTER TABLE application
RENAME COLUMN application_group_id TO service_id;
ALTER TABLE application_group RENAME TO service;
CREATE SEQUENCE application_id_seq;
SELECT setval(
'application_id_seq', COALESCE(
(
SELECT MAX(id)
FROM isp_system_service.application
), 1
)
);
ALTER TABLE application
ALTER COLUMN id
SET DEFAULT nextval('application_id_seq');
@@ -1,36 +0,0 @@
-- +goose Up
CREATE TABLE access_list_new
(
app_id INT,
http_method VARCHAR(255) NOT NULL DEFAULT '',
method VARCHAR(255),
value BOOLEAN NOT NULL,
PRIMARY KEY (app_id, http_method, method),
CONSTRAINT FK_app_id__application_id FOREIGN KEY (app_id) REFERENCES application (id) ON DELETE CASCADE ON UPDATE CASCADE
);
INSERT INTO access_list_new (app_id, method, value)
SELECT app_id, method, value
FROM access_list
WHERE value = true;
DROP TABLE access_list;
ALTER TABLE access_list_new RENAME TO access_list;
-- +goose Down
CREATE TABLE access_list_old
(
app_id INT,
method VARCHAR(255),
value BOOLEAN NOT NULL,
PRIMARY KEY (app_id, method),
CONSTRAINT FK_app_id__application_id FOREIGN KEY (app_id) REFERENCES application (id) ON DELETE CASCADE ON UPDATE CASCADE
);
INSERT INTO access_list_old (app_id, method, value)
SELECT app_id, method, value
FROM access_list
WHERE value = true;
DROP TABLE access_list;
ALTER TABLE access_list_old RENAME TO access_list;
+28
View File
@@ -0,0 +1,28 @@
[
{
"id": 1,
"name": "rootDomain",
"description": "",
"services": [
{
"id": 1,
"name": "rootService",
"description": "",
"apps": [
{
"id": 1,
"name": "admin",
"description": "",
"type": "SYSTEM",
"tokens": [
{
"token": "{{ isp_service_admin_token }}",
"expireTime": -1
}
]
}
]
}
]
}
]
+36 -65
View File
@@ -4,14 +4,12 @@ import (
"context"
"database/sql"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/db/query"
"github.com/txix-open/isp-kit/metrics/sql_metrics"
"isp-system-service/domain"
"isp-system-service/entity"
)
type AccessList struct {
@@ -24,38 +22,30 @@ func NewAccessList(db db.DB) AccessList {
}
}
func (r AccessList) GetAccessListByAppIdAndMethod(ctx context.Context, appId int, httpMethod string, method string) (*entity.AccessList, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.GetAccessListByAppIdAndMethod")
func (r AccessList) GetAccessListByAppIdAndMethod(ctx context.Context, appId int, method string) (*entity.AccessList, error) {
q := `
SELECT app_id, http_method, method, value
FROM access_list
WHERE app_id = $1
AND method = $2
AND http_method IN ($3, '')
ORDER BY (http_method = $3) DESC
LIMIT 1;
`
SELECT app_id, method, value
FROM access_list
WHERE app_id = $1 AND method = $2
`
result := entity.AccessList{}
err := r.db.SelectRow(ctx, &result, q, appId, method, httpMethod)
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, domain.ErrAccessListNotFound
case err != nil:
return nil, errors.WithMessagef(err, "exec query %s", q)
default:
return &result, nil
err := r.db.SelectRow(ctx, &result, q, appId, method)
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrAccessListNotFound
}
return nil, errors.WithMessagef(err, "select db")
}
return &result, nil
}
func (r AccessList) GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.GetAccessListByAppId")
q := `
SELECT app_id, http_method, method, value
SELECT app_id, method, value
FROM access_list
WHERE app_id = $1
`
`
result := make([]entity.AccessList, 0)
err := r.db.Select(ctx, &result, q, appId)
if err != nil {
@@ -66,10 +56,8 @@ func (r AccessList) GetAccessListByAppId(ctx context.Context, appId int) ([]enti
}
func (r AccessList) GetAccessListByAppIdList(ctx context.Context, appIdList []int) ([]entity.AccessList, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.GetAccessListByAppIdList")
q, args, err := query.New().
Select("app_id", "http_method", "method", "value").
Select("app_id", "method", "value").
From("access_list").
Where(squirrel.Eq{"app_id": appIdList}).
ToSql()
@@ -80,20 +68,18 @@ func (r AccessList) GetAccessListByAppIdList(ctx context.Context, appIdList []in
result := make([]entity.AccessList, 0)
err = r.db.Select(ctx, &result, q, args...)
if err != nil {
return nil, errors.WithMessagef(err, "exec query %s", q)
return nil, errors.WithMessagef(err, "select db")
}
return result, nil
}
func (r AccessList) InsertArrayAccessList(ctx context.Context, entity []entity.AccessList) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.InsertArrayAccessList")
qBuilder := query.New().
Insert("access_list").
Columns("app_id", "http_method", "method", "value")
Columns("app_id", "method", "value")
for _, e := range entity {
qBuilder = qBuilder.Values(e.AppId, e.HttpMethod, e.Method, e.Value)
qBuilder = qBuilder.Values(e.AppId, e.Method, e.Value)
}
q, args, err := qBuilder.ToSql()
if err != nil {
@@ -102,26 +88,24 @@ func (r AccessList) InsertArrayAccessList(ctx context.Context, entity []entity.A
_, err = r.db.Exec(ctx, q, args...)
if err != nil {
return errors.WithMessagef(err, "exec query %s", q)
return errors.WithMessage(err, "exec db")
}
return nil
}
func (r AccessList) UpsertAccessList(ctx context.Context, e entity.AccessList) (int, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.UpsertAccessList")
q := `
INSERT INTO access_list
(app_id, http_method, method, value)
VALUES ($1, $2, $3, $4)
ON CONFLICT (app_id, http_method, method)
(app_id, method, value)
VALUES ($1, $2, $3)
ON CONFLICT (app_id, method)
DO UPDATE
SET (value) = (SELECT EXCLUDED.value)
`
result, err := r.db.Exec(ctx, q, e.AppId, e.HttpMethod, e.Method, e.Value)
`
result, err := r.db.Exec(ctx, q, e.AppId, e.Method, e.Value)
if err != nil {
return 0, errors.WithMessagef(err, "exec query %s", q)
return 0, errors.WithMessage(err, "exec db")
}
rowsAffected, err := result.RowsAffected()
@@ -132,25 +116,14 @@ func (r AccessList) UpsertAccessList(ctx context.Context, e entity.AccessList) (
return int(rowsAffected), nil
}
func (r AccessList) DeleteAccessList(ctx context.Context, appId int, methods []entity.Method) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.DeleteAccessList")
methodsClause := squirrel.Or{}
for _, method := range methods {
methodsClause = append(methodsClause, squirrel.And{
squirrel.Eq{"method": method.Method},
squirrel.Eq{"http_method": method.HttpMethod},
})
}
func (r AccessList) DeleteAccessList(ctx context.Context, appId int, methods []string) error {
q, args, err := query.New().
Delete("access_list").
Where(squirrel.And{
squirrel.Eq{
"app_id": appId,
},
methodsClause,
Where(squirrel.Eq{
"app_id": appId,
"method": methods,
}).
Suffix("RETURNING app_id, method, value").
ToSql()
if err != nil {
return errors.WithMessage(err, "build query")
@@ -165,17 +138,15 @@ func (r AccessList) DeleteAccessList(ctx context.Context, appId int, methods []e
}
func (r AccessList) DeleteAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AccessList.DeleteAccessListByAppId")
q := `
DELETE FROM access_list
WHERE app_id = $1
RETURNING app_id, http_method, method, value
`
RETURNING app_id, method, value
`
result := make([]entity.AccessList, 0)
err := r.db.Select(ctx, &result, q, appId)
if err != nil {
return nil, errors.WithMessagef(err, "exec query %s", q)
return nil, errors.WithMessagef(err, "select db")
}
return result, nil
-201
View File
@@ -1,201 +0,0 @@
package repository
import (
"context"
"database/sql"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/Masterminds/squirrel"
"github.com/jackc/pgx/v5/pgconn"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/db/query"
"github.com/txix-open/isp-kit/metrics/sql_metrics"
)
type AppGroup struct {
db db.DB
}
func NewAppGroup(db db.DB) AppGroup {
return AppGroup{
db: db,
}
}
func (r AppGroup) GetAppGroupById(ctx context.Context, id int) (*entity.AppGroup, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.GetAppGroupById")
q := `
SELECT id, name, description, domain_id, created_at, updated_at
FROM application_group
WHERE id = $1
`
result := entity.AppGroup{}
err := r.db.SelectRow(ctx, &result, q, id)
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, domain.ErrAppGroupNotFound
case err != nil:
return nil, errors.WithMessagef(err, "exec query %s", q)
default:
return &result, nil
}
}
func (r AppGroup) GetAppGroupByIdList(ctx context.Context, idList []int) ([]entity.AppGroup, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.GetAppGroupByIdList")
q, arg, err := query.New().
Select("id", "name", "description", "domain_id", "created_at", "updated_at").
From("application_group").
Where(squirrel.Eq{"id": idList}).
OrderBy("created_at DESC").
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.AppGroup, 0)
err = r.db.Select(ctx, &result, q, arg...)
if err != nil {
return nil, errors.WithMessagef(err, "exec query %s", q)
}
return result, nil
}
func (r AppGroup) GetAppGroupByDomainId(ctx context.Context, domainIdList []int) ([]entity.AppGroup, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.GetAppGroupByDomainId")
q, arg, err := query.New().
Select("id", "name", "description", "domain_id", "created_at", "updated_at").
From("application_group").
Where(squirrel.Eq{"domain_id": domainIdList}).
OrderBy("created_at DESC").
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.AppGroup, 0)
err = r.db.Select(ctx, &result, q, arg...)
if err != nil {
return nil, errors.WithMessagef(err, "exec query %s", q)
}
return result, nil
}
func (r AppGroup) GetAppGroupByNameAndDomainId(ctx context.Context, name string, domainId int) (*entity.AppGroup, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.GetAppGroupByNameAndDomainId")
q := `
SELECT id, name, description, domain_id, created_at, updated_at
FROM application_group
WHERE name = $1 AND domain_id = $2
`
result := entity.AppGroup{}
err := r.db.SelectRow(ctx, &result, q, name, domainId)
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, domain.ErrAppGroupNotFound
case err != nil:
return nil, errors.WithMessagef(err, "exec query %s", q)
default:
return &result, nil
}
}
func (r AppGroup) CreateAppGroup(ctx context.Context, name string, desc string, domainId int) (*entity.AppGroup, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.CreateAppGroup")
q := `
INSERT INTO application_group
(name, description, domain_id)
VALUES ($1, $2, $3)
ON CONFLICT (name, domain_id) DO NOTHING
RETURNING id, name, description, domain_id, created_at, updated_at
`
result := entity.AppGroup{}
err := r.db.SelectRow(ctx, &result, q, name, desc, domainId)
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, domain.ErrAppGroupDuplicateName
case err != nil:
return nil, errors.WithMessagef(err, "exec query %s", q)
default:
return &result, nil
}
}
func (r AppGroup) UpdateAppGroup(ctx context.Context, id int, name string, description string) (*entity.AppGroup, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.UpdateAppGroup")
q := `
UPDATE application_group
SET name = $1, description = $2
WHERE id = $3
RETURNING id, name, description, domain_id, created_at, updated_at
`
result := entity.AppGroup{}
err := r.db.SelectRow(ctx, &result, q, name, description, id)
var pgErr *pgconn.PgError
switch {
case errors.As(err, &pgErr) && pgErr.ConstraintName == applicationGroupUniqueNameConstraint:
return nil, domain.ErrAppGroupDuplicateName
case errors.Is(err, sql.ErrNoRows):
return nil, domain.ErrAppGroupNotFound
case err != nil:
return nil, errors.WithMessagef(err, "exec query %s", q)
default:
return &result, nil
}
}
func (r AppGroup) DeleteAppGroup(ctx context.Context, idList []int) (int, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.DeleteAppGroup")
q, args, err := query.New().
Delete("application_group").
Where(squirrel.Eq{"id": idList}).
ToSql()
if err != nil {
return 0, errors.WithMessagef(err, "build query")
}
result, err := r.db.Exec(ctx, q, args...)
if err != nil {
return 0, errors.WithMessagef(err, "exec query %s", q)
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return 0, errors.WithMessagef(err, "get rows affected")
}
return int(rowsAffected), nil
}
func (r AppGroup) GetAllAppGroups(ctx context.Context) ([]entity.AppGroup, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "AppGroup.GetAllAppGroups")
q, arg, err := query.New().
Select("id", "name", "description", "domain_id", "created_at", "updated_at").
From("application_group").
OrderBy("created_at DESC").
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.AppGroup, 0)
err = r.db.Select(ctx, &result, q, arg...)
if err != nil {
return nil, errors.WithMessagef(err, "exec query %s", q)
}
return result, nil
}
+42 -162
View File
@@ -4,15 +4,12 @@ import (
"context"
"database/sql"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/Masterminds/squirrel"
"github.com/jackc/pgx/v5/pgconn"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/db/query"
"github.com/txix-open/isp-kit/metrics/sql_metrics"
"isp-system-service/domain"
"isp-system-service/entity"
)
type Application struct {
@@ -26,28 +23,24 @@ func NewApplication(db db.DB) Application {
}
func (r Application) GetApplicationById(ctx context.Context, id int) (*entity.Application, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.GetApplicationById")
q := `
SELECT id, name, description, application_group_id, type, created_at, updated_at
FROM application
WHERE id = $1
`
`
result := entity.Application{}
err := r.db.SelectRow(ctx, &result, q, id)
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, domain.ErrApplicationNotFound
case err != nil:
return nil, errors.WithMessagef(err, "exec query %s", q)
default:
return &result, nil
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrApplicationNotFound
}
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Application) GetApplicationByIdList(ctx context.Context, idList []int) ([]entity.Application, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.GetApplicationByIdList")
q, args, err := query.New().
Select("id", "name", "description", "application_group_id", "type", "created_at", "updated_at").
From("application").
@@ -61,129 +54,85 @@ func (r Application) GetApplicationByIdList(ctx context.Context, idList []int) (
result := make([]entity.Application, 0)
err = r.db.Select(ctx, &result, q, args...)
if err != nil {
return nil, errors.WithMessagef(err, "exec query %s", q)
return nil, errors.WithMessagef(err, "select db")
}
return result, nil
}
func (r Application) GetApplicationByAppGroupIdList(ctx context.Context, appGroupIdList []int) ([]entity.Application, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.GetApplicationByAppGroupIdList")
func (r Application) GetApplicationByApplicationGroupIdList(ctx context.Context, applicationGroupIdList []int) ([]entity.Application, error) {
q, args, err := query.New().
Select("id", "name", "description", "application_group_id", "type", "created_at", "updated_at").
From("application").
Where(squirrel.Eq{"application_group_id": appGroupIdList}).
Where(squirrel.Eq{"application_group_id": applicationGroupIdList}).
OrderBy("created_at DESC").
ToSql()
if err != nil {
return nil, errors.WithMessagef(err, "exec query %s", q)
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.Application, 0)
err = r.db.Select(ctx, &result, q, args...)
if err != nil {
return nil, errors.WithMessagef(err, "exec query %s", q)
return nil, errors.WithMessagef(err, "select db")
}
return result, nil
}
func (r Application) GetApplicationByNameAndAppGroupId(ctx context.Context, name string, serviceId int) (*entity.Application, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.GetApplicationByNameAndAppGroupId")
func (r Application) GetApplicationByNameAndApplicationGroupId(ctx context.Context, name string, applicationGroupId int) (*entity.Application, error) {
q := `
SELECT id, name, description, application_group_id, type, created_at, updated_at
FROM application
WHERE name = $1 AND application_group_id = $2
`
`
result := entity.Application{}
err := r.db.SelectRow(ctx, &result, q, name, serviceId)
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, nil // nolint:nilnil
case err != nil:
return nil, errors.WithMessagef(err, "exec query %s", q)
default:
return &result, nil
}
}
func (r Application) CreateApplication(
ctx context.Context,
id int,
name string,
desc string,
appGroupId int,
appType string,
) (*entity.Application, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.CreateApplication")
q := `
INSERT INTO application
(id, name, description, application_group_id, type)
VALUES ($1, $2, $3, $4, $5)
RETURNING id, name, description, application_group_id, type, created_at, updated_at
`
result := entity.Application{}
err := r.db.SelectRow(ctx, &result, q, id, name, desc, appGroupId, appType)
err := r.db.SelectRow(ctx, &result, q, name, applicationGroupId)
if err != nil {
return nil, r.handleCreateError(err, q)
if err == sql.ErrNoRows {
return nil, nil
}
return nil, errors.WithMessagef(err, "select row db")
}
return &result, nil
}
func (r Application) UpdateApplication(
ctx context.Context,
id int,
name string,
description string,
) (*entity.Application, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.UpdateApplication")
func (r Application) CreateApplication(ctx context.Context, name string, desc string, applicationGroupId int, appType string) (
*entity.Application, error) {
q := `
INSERT INTO application
(name, description, application_group_id, type)
VALUES ($1, $2, $3, $4)
RETURNING id, name, description, application_group_id, type, created_at, updated_at
`
result := entity.Application{}
err := r.db.SelectRow(ctx, &result, q, name, desc, applicationGroupId, appType)
if err != nil {
return nil, errors.WithMessagef(err, "select row db")
}
return &result, nil
}
func (r Application) UpdateApplication(ctx context.Context, id int, name string, description string) (*entity.Application, error) {
q := `
UPDATE application
SET name = $2,
description = $3
WHERE id = $1
RETURNING id, name, description, application_group_id, type, created_at, updated_at
`
`
result := entity.Application{}
err := r.db.SelectRow(ctx, &result, q, id, name, description)
if err != nil {
return nil, r.handleUpdateError(err, q)
return nil, errors.WithMessagef(err, "select row db")
}
return &result, nil
}
func (r Application) UpdateApplicationWithNewId(
ctx context.Context,
oldId int,
newId int,
name string,
description string,
) (*entity.Application, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.UpdateApplicationWithNewId")
q := `
UPDATE application
SET id = $2,
name = $3,
description = $4
WHERE id = $1
RETURNING id, name, description, application_group_id, type, created_at, updated_at
`
result := entity.Application{}
err := r.db.SelectRow(ctx, &result, q, oldId, newId, name, description)
if err != nil {
return nil, r.handleUpdateError(err, q)
}
return &result, nil
}
func (r Application) DeleteApplicationByIdList(ctx context.Context, idList []int) (int, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.DeleteApplicationByIdList")
q, args, err := query.New().
Delete("application").
Where(squirrel.Eq{"id": idList}).
@@ -204,72 +153,3 @@ func (r Application) DeleteApplicationByIdList(ctx context.Context, idList []int
return int(rowsAffected), nil
}
func (r Application) NextApplicationId(ctx context.Context) (int, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.NextApplicationId")
q := `SELECT COALESCE(MAX(id)+1, 1) FROM application;`
nextAppId := 0
err := r.db.SelectRow(ctx, &nextAppId, q)
if err != nil {
return -1, errors.WithMessagef(err, "exec query %s", q)
}
return nextAppId, nil
}
func (r Application) GetAllApplications(ctx context.Context) ([]entity.Application, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Application.GetAllApplications")
q, args, err := query.New().
Select("id", "name", "description", "application_group_id", "type", "created_at", "updated_at").
From("application").
OrderBy("created_at DESC").
ToSql()
if err != nil {
return nil, errors.WithMessagef(err, "exec query %s", q)
}
result := make([]entity.Application, 0)
err = r.db.Select(ctx, &result, q, args...)
if err != nil {
return nil, errors.WithMessagef(err, "exec query %s", q)
}
return result, nil
}
func (r Application) handleCreateError(err error, q string) error {
var pgErr *pgconn.PgError
if !errors.As(err, &pgErr) {
return errors.WithMessagef(err, "exec query %s", q)
}
switch pgErr.ConstraintName {
case applicationPkConstraintName:
return domain.ErrApplicationDuplicateId
case applicationUniqueNameConstraintName:
return domain.ErrApplicationDuplicateName
case applicationFkAppGroupConstraintName:
return domain.ErrAppGroupNotFound
}
return errors.WithMessagef(err, "exec query %s", q)
}
func (r Application) handleUpdateError(err error, q string) error {
if errors.Is(err, sql.ErrNoRows) {
return domain.ErrApplicationNotFound
}
var pgErr *pgconn.PgError
if !errors.As(err, &pgErr) {
return errors.WithMessagef(err, "exec query %s", q)
}
switch pgErr.ConstraintName {
case applicationPkConstraintName:
return domain.ErrApplicationDuplicateId
case applicationUniqueNameConstraintName:
return domain.ErrApplicationDuplicateName
default:
return errors.WithMessagef(err, "exec query %s", q)
}
}
+156
View File
@@ -0,0 +1,156 @@
package repository
import (
"context"
"database/sql"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/db/query"
"isp-system-service/domain"
"isp-system-service/entity"
)
type ApplicationGroup struct {
db db.DB
}
func NewApplicationGroup(db db.DB) ApplicationGroup {
return ApplicationGroup{
db: db,
}
}
func (r ApplicationGroup) GetApplicationGroupById(ctx context.Context, id int) (*entity.ApplicationGroup, error) {
q := `
SELECT id, name, description, domain_id, created_at, updated_at
FROM application_group
WHERE id = $1
`
result := entity.ApplicationGroup{}
err := r.db.SelectRow(ctx, &result, q, id)
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrApplicationGroupNotFound
}
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r ApplicationGroup) GetApplicationGroupByIdList(ctx context.Context, idList []int) ([]entity.ApplicationGroup, error) {
q, arg, err := query.New().
Select("id", "name", "description", "domain_id", "created_at", "updated_at").
From("application_group").
Where(squirrel.Eq{"id": idList}).
OrderBy("created_at DESC").
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.ApplicationGroup, 0)
err = r.db.Select(ctx, &result, q, arg...)
if err != nil {
return nil, errors.WithMessagef(err, "select db")
}
return result, nil
}
func (r ApplicationGroup) GetApplicationGroupByDomainId(ctx context.Context, domainIdList []int) ([]entity.ApplicationGroup, error) {
q, arg, err := query.New().
Select("id", "name", "description", "domain_id", "created_at", "updated_at").
From("application_group").
Where(squirrel.Eq{"domain_id": domainIdList}).
OrderBy("created_at DESC").
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.ApplicationGroup, 0)
err = r.db.Select(ctx, &result, q, arg...)
if err != nil {
return nil, errors.WithMessagef(err, "select db")
}
return result, nil
}
func (r ApplicationGroup) GetSApplicationGroupByNameAndDomainId(ctx context.Context, name string, domainId int) (*entity.ApplicationGroup, error) {
q := `
SELECT id, name, description, domain_id, created_at, updated_at
FROM application_group
WHERE name = $1 AND domain_id = $2
`
result := entity.ApplicationGroup{}
err := r.db.SelectRow(ctx, &result, q, name, domainId)
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrApplicationGroupNotFound
}
return nil, errors.WithMessage(err, "select db")
}
return &result, nil
}
func (r ApplicationGroup) CreateApplicationGroup(ctx context.Context, name string, desc string, domainId int) (*entity.ApplicationGroup, error) {
q := `
INSERT INTO application_group
(name, description, domain_id)
VALUES ($1, $2, $3)
RETURNING id, name, description, domain_id, created_at, updated_at
`
result := entity.ApplicationGroup{}
err := r.db.SelectRow(ctx, &result, q, name, desc, domainId)
if err != nil {
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r ApplicationGroup) UpdateApplicationGroup(ctx context.Context, id int, name string, description string) (*entity.ApplicationGroup, error) {
q := `
UPDATE application_group
SET name = $1, description = $2
WHERE id = $3
RETURNING id, name, description, domain_id, created_at, updated_at
`
result := entity.ApplicationGroup{}
err := r.db.SelectRow(ctx, &result, q, name, description, id)
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrApplicationGroupNotFound
}
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r ApplicationGroup) DeleteApplicationGroup(ctx context.Context, idList []int) (int, error) {
q, args, err := query.New().
Delete("application_group").
Where(squirrel.Eq{"id": idList}).
ToSql()
if err != nil {
return 0, errors.WithMessagef(err, "build query")
}
result, err := r.db.Exec(ctx, q, args...)
if err != nil {
return 0, errors.WithMessagef(err, "exec db")
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return 0, errors.WithMessagef(err, "get rows affected")
}
return int(rowsAffected), nil
}
-9
View File
@@ -1,9 +0,0 @@
package repository
const (
applicationPkConstraintName = "application_pkey"
applicationUniqueNameConstraintName = "uq_name_application_group_id"
applicationFkAppGroupConstraintName = "fk_application_group_id"
applicationGroupUniqueNameConstraint = "uq_name_domain_name"
)
+33 -46
View File
@@ -4,14 +4,12 @@ import (
"context"
"database/sql"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/db/query"
"github.com/txix-open/isp-kit/metrics/sql_metrics"
"isp-system-service/domain"
"isp-system-service/entity"
)
type Domain struct {
@@ -25,28 +23,24 @@ func NewDomain(db db.DB) Domain {
}
func (r Domain) GetDomainById(ctx context.Context, id int) (*entity.Domain, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Domain.GetDomainById")
q := `
SELECT id, name, description, system_id, created_at, updated_at
FROM domain
WHERE id = $1
`
`
result := entity.Domain{}
err := r.db.SelectRow(ctx, &result, q, id)
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, domain.ErrDomainNotFound
case err != nil:
return nil, errors.WithMessagef(err, "exec query %s", q)
default:
return &result, nil
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrDomainNotFound
}
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Domain) GetDomainByIdList(ctx context.Context, idList []int) ([]entity.Domain, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Domain.GetDomainByIdList")
q, args, err := query.New().
Select("id", "name", "description", "system_id", "created_at", "updated_at").
From("domain").
@@ -66,63 +60,59 @@ func (r Domain) GetDomainByIdList(ctx context.Context, idList []int) ([]entity.D
}
func (r Domain) GetDomainBySystemId(ctx context.Context, systemId int) ([]entity.Domain, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Domain.GetDomainBySystemId")
q := `
SELECT id, name, description, system_id, created_at, updated_at
FROM domain
WHERE system_id = $1
ORDER BY created_at DESC
`
`
result := make([]entity.Domain, 0)
err := r.db.Select(ctx, &result, q, systemId)
if err != nil {
return nil, errors.WithMessagef(err, "exec query %s", q)
return nil, errors.WithMessage(err, "select db")
}
return result, nil
}
func (r Domain) GetDomainByNameAndSystemId(ctx context.Context, name string, systemId int) (*entity.Domain, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Domain.GetDomainByNameAndSystemId")
q := `
SELECT id, name, description, system_id, created_at, updated_at
FROM domain
WHERE name = $1 AND system_id = $2
`
`
result := entity.Domain{}
err := r.db.SelectRow(ctx, &result, q, name, systemId)
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, domain.ErrDomainNotFound
case err != nil:
return nil, errors.WithMessagef(err, "exec query %s", q)
default:
return &result, nil
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrDomainNotFound
}
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Domain) CreateDomain(ctx context.Context, name string, desc string, systemId int) (*entity.Domain, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Domain.CreateDomain")
q := `
INSERT INTO domain
(name, description, system_id)
VALUES ($1, $2, $3)
RETURNING id, name, description, system_id, created_at, updated_at
`
`
result := entity.Domain{}
err := r.db.SelectRow(ctx, &result, q, name, desc, systemId)
if err != nil {
return nil, errors.WithMessagef(err, "exec query %s", q)
if err == sql.ErrNoRows {
return nil, domain.ErrDomainNotFound
}
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Domain) UpdateDomain(ctx context.Context, id int, name string, description string) (*entity.Domain, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Domain.UpdateDomain")
q := `
UPDATE domain
SET name = $1, description = $2
@@ -131,19 +121,16 @@ func (r Domain) UpdateDomain(ctx context.Context, id int, name string, descripti
`
result := entity.Domain{}
err := r.db.SelectRow(ctx, &result, q, name, description, id)
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, domain.ErrDomainNotFound
case err != nil:
return nil, errors.WithMessagef(err, "exec query %s", q)
default:
return &result, nil
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrDomainNotFound
}
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Domain) DeleteDomain(ctx context.Context, idList []int) (int, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Domain.DeleteDomain")
q, args, err := query.New().
Delete("domain").
Where(squirrel.Eq{"id": idList}).
@@ -154,7 +141,7 @@ func (r Domain) DeleteDomain(ctx context.Context, idList []int) (int, error) {
result, err := r.db.Exec(ctx, q, args...)
if err != nil {
return 0, errors.WithMessagef(err, "exec query %s", q)
return 0, errors.WithMessagef(err, "exec db")
}
rowsAffected, err := result.RowsAffected()
-40
View File
@@ -1,40 +0,0 @@
package repository
import (
"context"
"hash/fnv"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/metrics/sql_metrics"
)
const (
prefix = "msp-service-template"
)
type Locker struct {
db db.DB
}
func NewLocker(db db.DB) Locker {
return Locker{db: db}
}
func (l Locker) TryLock(ctx context.Context, key string) (bool, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Locker.TryLock")
hash := fnv.New32a()
_, err := hash.Write([]byte(prefix + key))
if err != nil {
return false, errors.WithMessage(err, "generate hash")
}
sum := hash.Sum32()
acquired := false
err = l.db.SelectRow(ctx, &acquired, "SELECT pg_try_advisory_xact_lock($1)", sum)
if err != nil {
return false, errors.WithMessage(err, "pg try acquire advisory lock")
}
return acquired, nil
}
+20 -35
View File
@@ -4,14 +4,12 @@ import (
"context"
"database/sql"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/db/query"
"github.com/txix-open/isp-kit/metrics/sql_metrics"
"isp-system-service/domain"
"isp-system-service/entity"
)
type Token struct {
@@ -25,14 +23,12 @@ func NewToken(db db.DB) Token {
}
func (r Token) SaveToken(ctx context.Context, token string, appId int, expireTime int) (*entity.Token, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.SaveToken")
q := `
INSERT INTO token
(token, app_id, expire_time)
VALUES ($1, $2, $3)
RETURNING token, app_id, expire_time, created_at
`
`
result := entity.Token{}
err := r.db.SelectRow(ctx, &result, q, token, appId, expireTime)
if err != nil {
@@ -43,28 +39,21 @@ func (r Token) SaveToken(ctx context.Context, token string, appId int, expireTim
}
func (r Token) GetTokenById(ctx context.Context, token string) (*entity.Token, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.GetTokenById")
q := `
SELECT token, app_id, expire_time, created_at
FROM token
FROM system
WHERE token = $1
`
`
result := entity.Token{}
err := r.db.SelectRow(ctx, &result, q, token)
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, nil //nolint:nilnil
case err != nil:
return nil, errors.WithMessagef(err, "exec query %s", q)
default:
return &result, nil
if err != nil {
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
func (r Token) GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.GetTokenByAppIdList")
q, args, err := query.New().
Select("token", "app_id", "expire_time", "created_at").
From("token").
@@ -78,15 +67,13 @@ func (r Token) GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]enti
result := make([]entity.Token, 0)
err = r.db.Select(ctx, &result, q, args...)
if err != nil {
return nil, errors.WithMessagef(err, "exec query %s", q)
return nil, errors.WithMessagef(err, "select db")
}
return result, nil
}
func (r Token) DeleteToken(ctx context.Context, tokens []string) (int, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.DeleteToken")
q, args, err := query.New().
Delete("token").
Where(squirrel.Eq{"token": tokens}).
@@ -97,7 +84,7 @@ func (r Token) DeleteToken(ctx context.Context, tokens []string) (int, error) {
result, err := r.db.Exec(ctx, q, args...)
if err != nil {
return 0, errors.WithMessagef(err, "exec query %s", q)
return 0, errors.WithMessagef(err, "exec db")
}
rowsAffected, err := result.RowsAffected()
@@ -109,27 +96,25 @@ func (r Token) DeleteToken(ctx context.Context, tokens []string) (int, error) {
}
func (r Token) AuthDataByToken(ctx context.Context, token string) (*entity.AuthData, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.AuthDataByToken")
q := `
SELECT system_id, domain_id, application_group_id, app_id, application.name AS app_name , token.expire_time, token.created_at
SELECT system_id, domain_id, application_group_id, app_id, token.expire_time, token.created_at
FROM token
LEFT JOIN application
ON token.app_id = application.id
LEFT JOIN application_group
ON application.application_group_id = application_group.id
ON application.application_group_id = service.id
LEFT JOIN domain
ON application_group.domain_id = domain.id
WHERE token = $1
`
result := entity.AuthData{}
err := r.db.SelectRow(ctx, &result, q, token)
switch {
case errors.Is(err, sql.ErrNoRows):
return nil, domain.ErrTokenNotFound
case err != nil:
return nil, errors.WithMessagef(err, "exec query %s", q)
default:
return &result, nil
if err != nil {
if err == sql.ErrNoRows {
return nil, domain.ErrTokenNotFound
}
return nil, errors.WithMessage(err, "select row db")
}
return &result, nil
}
+40 -86
View File
@@ -1,30 +1,28 @@
package routes
import (
"isp-system-service/controller"
"isp-system-service/docs"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/common_endpoints"
"github.com/txix-open/isp-kit/grpc"
"github.com/txix-open/isp-kit/grpc/endpoint"
"github.com/txix-open/isp-kit/grpc/isp"
"isp-system-service/controller"
)
type Controllers struct {
AccessList controller.AccessList
Domain controller.Domain
Service controller.Service
Application controller.Application
AppGroup controller.AppGroup
Token controller.Token
Secure controller.Secure
AccessList controller.AccessList
Domain controller.Domain
Service controller.Service
ApplicationGroup controller.ApplicationGroup
Application controller.Application
Token controller.Token
Secure controller.Secure
}
func EndpointDescriptors() []cluster.EndpointDescriptor {
return endpointDescriptors(Controllers{})
}
func Handler(wrapper endpoint.Wrapper, c Controllers) *grpc.Mux {
func Handler(wrapper endpoint.Wrapper, c Controllers) isp.BackendServiceServer {
muxer := grpc.NewMux()
for _, descriptor := range endpointDescriptors(c) {
muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler))
@@ -33,16 +31,15 @@ func Handler(wrapper endpoint.Wrapper, c Controllers) *grpc.Mux {
}
func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
return concatCluster(
return concatCluster([][]cluster.EndpointDescriptor{
secureCluster(c),
accessListCluster(c),
domainCluster(c),
serviceCluster(c),
applicationGroupCluster(c),
applicationCluster(c),
tokenCluster(c),
applicationGroupCluster(c),
commonEndpoints(),
)
})
}
func secureCluster(c Controllers) []cluster.EndpointDescriptor {
@@ -77,16 +74,6 @@ func accessListCluster(c Controllers) []cluster.EndpointDescriptor {
Inner: true,
Handler: c.AccessList.SetList,
},
{
Path: "system/access_list/delete_list",
Inner: true,
Handler: c.AccessList.DeleteList,
},
{
Path: "system/access_list/delete_list_with_methods",
Inner: true,
Handler: c.AccessList.DeleteListWithMethods,
},
}
}
@@ -115,7 +102,6 @@ func domainCluster(c Controllers) []cluster.EndpointDescriptor {
}
}
// deprecated
func serviceCluster(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
@@ -146,6 +132,31 @@ func serviceCluster(c Controllers) []cluster.EndpointDescriptor {
}
}
func applicationGroupCluster(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "system/application_group/get_group",
Inner: true,
Handler: c.ApplicationGroup.Get,
},
{
Path: "system/application_group/create_update_group",
Inner: true,
Handler: c.ApplicationGroup.CreateUpdate,
},
{
Path: "system/application_group/get_group_by_id",
Inner: true,
Handler: c.ApplicationGroup.GetById,
},
{
Path: "system/application_group/delete_group",
Inner: true,
Handler: c.ApplicationGroup.Delete,
},
}
}
func applicationCluster(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
@@ -156,7 +167,7 @@ func applicationCluster(c Controllers) []cluster.EndpointDescriptor {
{
Path: "system/application/get_applications_by_service_id",
Inner: true,
Handler: c.Application.GetByServiceId,
Handler: c.Application.GetByApplicationGroupId,
},
{
Path: "system/application/create_update_application",
@@ -168,11 +179,6 @@ func applicationCluster(c Controllers) []cluster.EndpointDescriptor {
Inner: true,
Handler: c.Application.GetById,
},
{
Path: "system/application/get_application_by_token",
Inner: true,
Handler: c.Application.GetByToken,
},
{
Path: "system/application/delete_applications",
Inner: true,
@@ -183,25 +189,6 @@ func applicationCluster(c Controllers) []cluster.EndpointDescriptor {
Inner: true,
Handler: c.Application.GetSystemTree,
},
{
Path: "system/application/next_id",
Inner: true,
Handler: c.Application.NextId,
},
{
Path: "system/application/get_all",
Inner: true,
Handler: c.Application.GetAll,
},
{
Path: "system/application/create_application",
Inner: true,
Handler: c.Application.Create,
}, {
Path: "system/application/update_application",
Inner: true,
Handler: c.Application.Update,
},
}
}
@@ -230,40 +217,7 @@ func tokenCluster(c Controllers) []cluster.EndpointDescriptor {
}
}
func applicationGroupCluster(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "system/application_group/create",
Inner: true,
Handler: c.AppGroup.Create,
}, {
Path: "system/application_group/update",
Inner: true,
Handler: c.AppGroup.Update,
}, {
Path: "system/application_group/delete_list",
Inner: true,
Handler: c.AppGroup.DeleteList,
}, {
Path: "system/application_group/get_by_id_list",
Inner: true,
Handler: c.AppGroup.GetByIdList,
}, {
Path: "system/application_group/get_all",
Inner: true,
Handler: c.AppGroup.GetAll,
},
}
}
func commonEndpoints() []cluster.EndpointDescriptor {
return common_endpoints.CommonEndpoints(
"system",
common_endpoints.WithSwaggerEndpoint(docs.SwaggerJson),
)
}
func concatCluster(clusters ...[]cluster.EndpointDescriptor) []cluster.EndpointDescriptor {
func concatCluster(clusters [][]cluster.EndpointDescriptor) []cluster.EndpointDescriptor {
var result []cluster.EndpointDescriptor
for _, c := range clusters {
result = append(result, c...)
+38 -69
View File
@@ -3,60 +3,62 @@ package service
import (
"context"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/pkg/errors"
)
type AccessListRepo interface {
type IAccessListAccessListRep interface {
GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error)
DeleteAccessList(ctx context.Context, appId int, methods []entity.Method) error
}
type AccessListSetOneTx interface {
type IAccessListApplicationRep interface {
GetApplicationById(ctx context.Context, id int) (*entity.Application, error)
}
type IAccessListSetOneTx interface {
UpsertAccessList(ctx context.Context, e entity.AccessList) (int, error)
}
type AccessListSetListTx interface {
type IAccessListSetListTx interface {
GetAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error)
InsertArrayAccessList(ctx context.Context, entity []entity.AccessList) error
DeleteAccessList(ctx context.Context, appId int, methods []entity.Method) error
DeleteAccessList(ctx context.Context, appId int, methods []string) error
DeleteAccessListByAppId(ctx context.Context, appId int) ([]entity.AccessList, error)
}
type AccessListTxRunner interface {
AccessListSetOneTx(ctx context.Context, tx func(ctx context.Context, tx AccessListSetOneTx) error) error
AccessListSetListTx(ctx context.Context, tx func(ctx context.Context, tx AccessListSetListTx) error) error
type IAccessListTxRunner interface {
AccessListSetOneTx(ctx context.Context, tx func(ctx context.Context, tx IAccessListSetOneTx) error) error
AccessListSetListTx(ctx context.Context, tx func(ctx context.Context, tx IAccessListSetListTx) error) error
}
type AccessList struct {
tx AccessListTxRunner
accessListRepo AccessListRepo
appRepo ApplicationRepo
tx IAccessListTxRunner
accessListRep IAccessListAccessListRep
applicationRep IAccessListApplicationRep
}
func NewAccessList(
tx AccessListTxRunner,
accessListRepo AccessListRepo,
appRepo ApplicationRepo,
tx IAccessListTxRunner,
accessListRep IAccessListAccessListRep,
applicationRep IAccessListApplicationRep,
) AccessList {
return AccessList{
tx: tx,
accessListRepo: accessListRepo,
appRepo: appRepo,
accessListRep: accessListRep,
applicationRep: applicationRep,
}
}
func (s AccessList) GetById(ctx context.Context, appId int) ([]domain.MethodInfo, error) {
_, err := s.appRepo.GetApplicationById(ctx, appId)
_, err := s.applicationRep.GetApplicationById(ctx, appId)
if err != nil {
return nil, errors.WithMessage(err, "get application by id")
}
accessList, err := s.accessListRepo.GetAccessListByAppId(ctx, appId)
accessList, err := s.accessListRep.GetAccessListByAppId(ctx, appId)
if err != nil {
return nil, errors.WithMessage(err, "get access list by app_id")
return nil, errors.WithMessagef(err, "get access list by app_id")
}
methodInfos := make([]domain.MethodInfo, len(accessList))
@@ -71,21 +73,20 @@ func (s AccessList) GetById(ctx context.Context, appId int) ([]domain.MethodInfo
}
func (s AccessList) SetOne(ctx context.Context, request domain.AccessListSetOneRequest) (*domain.AccessListSetOneResponse, error) {
_, err := s.appRepo.GetApplicationById(ctx, request.AppId)
_, err := s.applicationRep.GetApplicationById(ctx, request.AppId)
if err != nil {
return nil, errors.WithMessage(err, "get application by id")
}
var resp int
err = s.tx.AccessListSetOneTx(ctx, func(ctx context.Context, tx AccessListSetOneTx) error {
err = s.tx.AccessListSetOneTx(ctx, func(ctx context.Context, tx IAccessListSetOneTx) error {
resp, err = tx.UpsertAccessList(ctx, entity.AccessList{
AppId: request.AppId,
HttpMethod: request.HttpMethod,
Method: request.Method,
Value: request.Value,
AppId: request.AppId,
Method: request.Method,
Value: request.Value,
})
if err != nil {
return errors.WithMessage(err, "upsert access list")
return errors.WithMessagef(err, "upsert access list")
}
return nil
@@ -100,12 +101,12 @@ func (s AccessList) SetOne(ctx context.Context, request domain.AccessListSetOneR
}
func (s AccessList) SetList(ctx context.Context, req domain.AccessListSetListRequest) ([]domain.MethodInfo, error) {
_, err := s.appRepo.GetApplicationById(ctx, req.AppId)
_, err := s.applicationRep.GetApplicationById(ctx, req.AppId)
if err != nil {
return nil, errors.WithMessage(err, "get application by id")
}
err = s.tx.AccessListSetListTx(ctx, func(ctx context.Context, tx AccessListSetListTx) error {
err = s.tx.AccessListSetListTx(ctx, func(ctx context.Context, tx IAccessListSetListTx) error {
if req.RemoveOld {
_, err = tx.DeleteAccessListByAppId(ctx, req.AppId)
if err != nil {
@@ -114,17 +115,13 @@ func (s AccessList) SetList(ctx context.Context, req domain.AccessListSetListReq
}
newAccessList := make([]entity.AccessList, len(req.Methods))
updateMethods := make([]entity.Method, len(req.Methods))
updateMethods := make([]string, len(req.Methods))
for i, m := range req.Methods {
updateMethods[i] = entity.Method{
HttpMethod: m.HttpMethod,
Method: m.Method,
}
updateMethods[i] = m.Method
newAccessList[i] = entity.AccessList{
AppId: req.AppId,
HttpMethod: m.HttpMethod,
Method: m.Method,
Value: m.Value,
AppId: req.AppId,
Method: m.Method,
Value: m.Value,
}
}
@@ -146,9 +143,9 @@ func (s AccessList) SetList(ctx context.Context, req domain.AccessListSetListReq
return nil, errors.WithMessage(err, "transaction access list set list")
}
accessList, err := s.accessListRepo.GetAccessListByAppId(ctx, req.AppId)
accessList, err := s.accessListRep.GetAccessListByAppId(ctx, req.AppId)
if err != nil {
return nil, errors.WithMessage(err, "get access list by app_id")
return nil, errors.WithMessagef(err, "get access list by app_id")
}
methodInfos := make([]domain.MethodInfo, len(accessList))
@@ -161,31 +158,3 @@ func (s AccessList) SetList(ctx context.Context, req domain.AccessListSetListReq
return methodInfos, nil
}
func (s AccessList) DeleteList(ctx context.Context, req domain.AccessListDeleteListRequest) error {
methods := make([]domain.Method, 0, len(req.Methods))
for _, method := range req.Methods {
methods = append(methods, domain.Method{Method: method})
}
return s.DeleteListWithMethods(ctx, domain.AccessListDeleteV2ListRequest{
AppId: req.AppId,
Methods: methods,
})
}
func (s AccessList) DeleteListWithMethods(ctx context.Context, req domain.AccessListDeleteV2ListRequest) error {
_, err := s.appRepo.GetApplicationById(ctx, req.AppId)
if err != nil {
return errors.WithMessage(err, "get application by id")
}
methods := make([]entity.Method, 0, len(req.Methods))
for _, method := range req.Methods {
methods = append(methods, entity.Method{Method: method.Method, HttpMethod: method.HttpMethod})
}
err = s.accessListRepo.DeleteAccessList(ctx, req.AppId, methods)
if err != nil {
return errors.WithMessage(err, "delete access_list")
}
return nil
}
-81
View File
@@ -1,81 +0,0 @@
package service
import (
"context"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/pkg/errors"
)
type AppGroup struct {
repo AppGroupRepo
}
func NewAppGroup(repo AppGroupRepo) AppGroup {
return AppGroup{
repo: repo,
}
}
func (s AppGroup) Create(ctx context.Context, req domain.CreateAppGroupRequest) (*domain.AppGroup, error) {
appGroup, err := s.repo.CreateAppGroup(ctx, req.Name, req.Description, 1)
if err != nil {
return nil, errors.WithMessage(err, "create appGroup")
}
converted := s.convertAppGroup(*appGroup)
return &converted, nil
}
func (s AppGroup) Update(ctx context.Context, req domain.UpdateAppGroupRequest) (*domain.AppGroup, error) {
appGroup, err := s.repo.UpdateAppGroup(ctx, req.Id, req.Name, req.Description)
if err != nil {
return nil, errors.WithMessage(err, "update appGroup")
}
converted := s.convertAppGroup(*appGroup)
return &converted, nil
}
func (s AppGroup) DeleteList(ctx context.Context, req domain.IdListRequest) (*domain.DeleteResponse, error) {
deleted, err := s.repo.DeleteAppGroup(ctx, req.IdList)
if err != nil {
return nil, errors.WithMessage(err, "delete appGroup")
}
return &domain.DeleteResponse{
Deleted: deleted,
}, nil
}
func (s AppGroup) GetByIdList(ctx context.Context, idList []int) ([]domain.AppGroup, error) {
appGroups, err := s.repo.GetAppGroupByIdList(ctx, idList)
if err != nil {
return nil, errors.WithMessage(err, "get appGroups by id list")
}
result := make([]domain.AppGroup, 0, len(appGroups))
for _, appGroup := range appGroups {
result = append(result, s.convertAppGroup(appGroup))
}
return result, nil
}
func (s AppGroup) GetAll(ctx context.Context) ([]domain.AppGroup, error) {
appGroups, err := s.repo.GetAllAppGroups(ctx)
if err != nil {
return nil, errors.WithMessage(err, "get all appGroups")
}
result := make([]domain.AppGroup, 0, len(appGroups))
for _, appGroup := range appGroups {
result = append(result, s.convertAppGroup(appGroup))
}
return result, nil
}
func (s AppGroup) convertAppGroup(appGroup entity.AppGroup) domain.AppGroup {
return domain.AppGroup{
Id: appGroup.Id,
Name: appGroup.Name,
Description: appGroup.Description.String,
CreatedAt: appGroup.CreatedAt,
UpdatedAt: appGroup.UpdatedAt,
}
}
+123 -135
View File
@@ -3,46 +3,67 @@ package service
import (
"context"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/pkg/errors"
)
type ApplicationDeleteTx interface {
type IApplicationApplicationRep interface {
GetApplicationById(ctx context.Context, id int) (*entity.Application, error)
GetApplicationByIdList(ctx context.Context, idList []int) ([]entity.Application, error)
GetApplicationByApplicationGroupIdList(ctx context.Context, serviceIdList []int) ([]entity.Application, error)
GetApplicationByNameAndApplicationGroupId(ctx context.Context, name string, serviceId int) (*entity.Application, error)
CreateApplication(ctx context.Context, name string, desc string, serviceId int, appType string) (*entity.Application, error)
UpdateApplication(ctx context.Context, id int, name string, description string) (*entity.Application, error)
}
type IApplicationTokenRep interface {
GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error)
}
type IApplicationServiceRep interface {
GetApplicationGroupById(ctx context.Context, id int) (*entity.ApplicationGroup, error)
GetApplicationGroupByDomainId(ctx context.Context, domainIdList []int) ([]entity.ApplicationGroup, error)
}
type IApplicationDomainRep interface {
GetDomainBySystemId(ctx context.Context, systemId int) ([]entity.Domain, error)
}
type IApplicationDeleteTx interface {
DeleteApplicationByIdList(ctx context.Context, idList []int) (int, error)
}
type ApplicationTxRunner interface {
ApplicationDeleteTx(ctx context.Context, tx func(ctx context.Context, tx ApplicationDeleteTx) error) error
type IApplicationTxRunner interface {
ApplicationDeleteTx(ctx context.Context, tx func(ctx context.Context, tx IApplicationDeleteTx) error) error
}
type Application struct {
txRunner ApplicationTxRunner
appRepo ApplicationRepo
domainRepo DomainRepo
serviceRepo AppGroupRepo
tokenRepo TokenRepo
tx IApplicationTxRunner
applicationRep IApplicationApplicationRep
domainRep IApplicationDomainRep
groupRep IApplicationServiceRep
tokenRep IApplicationTokenRep
}
func NewApplication(
txRunner ApplicationTxRunner,
applicationRepo ApplicationRepo,
domainRepo DomainRepo,
appGroupRepo AppGroupRepo,
tokenRepo TokenRepo,
tx IApplicationTxRunner,
applicationRep IApplicationApplicationRep,
domainRep IApplicationDomainRep,
groupRep IApplicationServiceRep,
tokenRep IApplicationTokenRep,
) Application {
return Application{
txRunner: txRunner,
appRepo: applicationRepo,
domainRepo: domainRepo,
serviceRepo: appGroupRepo,
tokenRepo: tokenRepo,
tx: tx,
applicationRep: applicationRep,
domainRep: domainRep,
groupRep: groupRep,
tokenRep: tokenRep,
}
}
func (s Application) GetById(ctx context.Context, appId int) (*domain.ApplicationWithTokens, error) {
application, err := s.appRepo.GetApplicationById(ctx, appId)
application, err := s.applicationRep.GetApplicationById(ctx, appId)
if err != nil {
return nil, errors.WithMessage(err, "get application by id")
}
@@ -55,27 +76,8 @@ func (s Application) GetById(ctx context.Context, appId int) (*domain.Applicatio
return arr[0], nil
}
func (s Application) GetByToken(ctx context.Context, tokenStr string) (*domain.GetApplicationByTokenResponse, error) {
token, err := s.tokenRepo.GetTokenById(ctx, tokenStr)
if err != nil {
return nil, errors.WithMessage(err, "get token by id")
}
if token == nil {
return nil, domain.ErrApplicationNotFound
}
app, err := s.appRepo.GetApplicationById(ctx, token.AppId)
if err != nil {
return nil, errors.WithMessage(err, "get app by id")
}
return &domain.GetApplicationByTokenResponse{
ApplicationId: app.Id,
ApplicationGroupId: app.ApplicationGroupId,
}, nil
}
func (s Application) GetByIdList(ctx context.Context, idList []int) ([]*domain.ApplicationWithTokens, error) {
res, err := s.appRepo.GetApplicationByIdList(ctx, idList)
res, err := s.applicationRep.GetApplicationByIdList(ctx, idList)
if err != nil {
return nil, errors.WithMessage(err, "get application by id list")
}
@@ -83,26 +85,26 @@ func (s Application) GetByIdList(ctx context.Context, idList []int) ([]*domain.A
return s.EnrichWithTokens(ctx, res)
}
func (s Application) GetByServiceId(ctx context.Context, id int) ([]*domain.ApplicationWithTokens, error) {
arr, err := s.appRepo.GetApplicationByAppGroupIdList(ctx, []int{id})
func (s Application) GetByApplicationGroupId(ctx context.Context, id int) ([]*domain.ApplicationWithTokens, error) {
arr, err := s.applicationRep.GetApplicationByApplicationGroupIdList(ctx, []int{id})
if err != nil {
return nil, errors.WithMessage(err, "get application by app_group_id")
return nil, errors.WithMessage(err, "get application by application_group_id")
}
return s.EnrichWithTokens(ctx, arr)
}
func (s Application) SystemTree(ctx context.Context, systemId int) ([]*domain.DomainWithService, error) {
domainEntityList, err := s.domainRepo.GetDomainBySystemId(ctx, systemId)
func (s Application) SystemTree(ctx context.Context, systemId int) ([]*domain.DomainWithApplicationGroup, error) {
domainEntityList, err := s.domainRep.GetDomainBySystemId(ctx, systemId)
if err != nil {
return nil, errors.WithMessage(err, "get domains by system_id")
}
if len(domainEntityList) == 0 {
return []*domain.DomainWithService{}, nil
return []*domain.DomainWithApplicationGroup{}, nil
}
result := make([]*domain.DomainWithService, len(domainEntityList))
resultByDomainId := make(map[int]*domain.DomainWithService, len(domainEntityList))
result := make([]*domain.DomainWithApplicationGroup, len(domainEntityList))
resultByDomainId := make(map[int]*domain.DomainWithApplicationGroup, len(domainEntityList))
domainIdList := make([]int, len(domainEntityList))
for i, domainEntity := range domainEntityList {
domainIdList[i] = domainEntity.Id
@@ -110,48 +112,56 @@ func (s Application) SystemTree(ctx context.Context, systemId int) ([]*domain.Do
if domainEntity.Description != nil {
description = *domainEntity.Description
}
r := &domain.DomainWithService{
Id: domainEntity.Id,
Name: domainEntity.Name,
Description: description,
Services: make([]*domain.ServiceWithApps, 0),
r := &domain.DomainWithApplicationGroup{
Id: domainEntity.Id,
Name: domainEntity.Name,
Description: description,
ApplicationGroup: make([]*domain.ApplicationGroupWithApps, 0),
}
resultByDomainId[domainEntity.Id] = r
result[i] = r
}
serviceEntityList, err := s.serviceRepo.GetAppGroupByDomainId(ctx, domainIdList)
applicationGroupEntityList, err := s.groupRep.GetApplicationGroupByDomainId(ctx, domainIdList)
if err != nil {
return nil, errors.WithMessage(err, "get service by domain_id")
return nil, errors.WithMessage(err, "get application group by domain_id")
}
serviceIdList := make([]int, len(serviceEntityList))
resultServiceByServiceId := make(map[int]*domain.ServiceWithApps, len(serviceEntityList))
for i, serviceEntity := range serviceEntityList {
serviceIdList[i] = serviceEntity.Id
resultService := &domain.ServiceWithApps{
Id: serviceEntity.Id,
Name: serviceEntity.Name,
Description: serviceEntity.Description.String,
applicationGroupIdList := make([]int, len(applicationGroupEntityList))
resultApplicationGroupById := make(map[int]*domain.ApplicationGroupWithApps, len(applicationGroupEntityList))
for i, applicationGroupEntity := range applicationGroupEntityList {
applicationGroupIdList[i] = applicationGroupEntity.Id
description := ""
if applicationGroupEntity.Description != nil {
description = *applicationGroupEntity.Description
}
resultApplicationGroup := &domain.ApplicationGroupWithApps{
Id: applicationGroupEntity.Id,
Name: applicationGroupEntity.Name,
Description: description,
Apps: make([]*domain.ApplicationSimple, 0),
}
r := resultByDomainId[serviceEntity.DomainId]
r.Services = append(r.Services, resultService)
resultServiceByServiceId[serviceEntity.Id] = resultService
r := resultByDomainId[applicationGroupEntity.DomainId]
r.ApplicationGroup = append(r.ApplicationGroup, resultApplicationGroup)
resultApplicationGroupById[applicationGroupEntity.Id] = resultApplicationGroup
}
applicationEntityList, err := s.appRepo.GetApplicationByAppGroupIdList(ctx, serviceIdList)
applicationEntityList, err := s.applicationRep.GetApplicationByApplicationGroupIdList(ctx, applicationGroupIdList)
if err != nil {
return nil, errors.WithMessage(err, "get application by service_id")
return nil, errors.WithMessagef(err, "get application by application_group_id")
}
for _, applicationEntity := range applicationEntityList {
resultService := resultServiceByServiceId[applicationEntity.ApplicationGroupId]
resultService.Apps = append(resultService.Apps, &domain.ApplicationSimple{
resultApplicationGroup := resultApplicationGroupById[applicationEntity.ApplicationGroupId]
description := ""
if applicationEntity.Description != nil {
description = *applicationEntity.Description
}
resultApplicationGroup.Apps = append(resultApplicationGroup.Apps, &domain.ApplicationSimple{
Id: applicationEntity.Id,
Name: applicationEntity.Name,
Type: applicationEntity.Type,
Description: applicationEntity.Description.String,
Description: description,
Tokens: make([]domain.Token, 0),
})
}
@@ -160,18 +170,29 @@ func (s Application) SystemTree(ctx context.Context, systemId int) ([]*domain.Do
}
func (s Application) CreateUpdate(ctx context.Context, req domain.ApplicationCreateUpdateRequest) (*domain.ApplicationWithTokens, error) {
existed, err := s.applicationRep.GetApplicationByNameAndApplicationGroupId(ctx, req.Name, req.ApplicationGroupId)
switch {
case errors.Is(err, domain.ErrApplicationNotFound):
case err != nil:
return nil, errors.WithMessage(err, "get application by name and application_group_id")
}
_, err = s.groupRep.GetApplicationGroupById(ctx, req.ApplicationGroupId)
if err != nil {
return nil, errors.WithMessage(err, "get application group by id")
}
if req.Id == 0 {
_, err := s.appRepo.GetApplicationByNameAndAppGroupId(ctx, req.Name, req.ServiceId)
if err != nil {
return nil, errors.WithMessage(err, "get application by name and service_id")
if existed != nil {
return nil, domain.ErrApplicationDuplicateName
}
appId, err := s.appRepo.NextApplicationId(ctx)
_, err = s.applicationRep.GetApplicationByNameAndApplicationGroupId(ctx, req.Name, req.ApplicationGroupId)
if err != nil {
return nil, errors.WithMessage(err, "next app id")
return nil, errors.WithMessage(err, "get application by name and application_group_id")
}
app, err := s.appRepo.CreateApplication(ctx, appId, req.Name, req.Description, req.ServiceId, req.Type)
app, err := s.applicationRep.CreateApplication(ctx, req.Name, req.Description, req.ApplicationGroupId, req.Type)
if err != nil {
return nil, errors.WithMessage(err, "create application")
}
@@ -184,7 +205,16 @@ func (s Application) CreateUpdate(ctx context.Context, req domain.ApplicationCre
return result[0], nil
}
app, err := s.appRepo.UpdateApplication(ctx, req.Id, req.Name, req.Description)
if existed != nil && existed.Id != req.Id {
return nil, domain.ErrApplicationDuplicateName
}
_, err = s.applicationRep.GetApplicationById(ctx, req.Id)
if err != nil {
return nil, errors.WithMessage(err, "get application by id")
}
app, err := s.applicationRep.UpdateApplication(ctx, req.Id, req.Name, req.Description)
if err != nil {
return nil, errors.WithMessage(err, "update application")
}
@@ -199,7 +229,7 @@ func (s Application) CreateUpdate(ctx context.Context, req domain.ApplicationCre
func (s Application) Delete(ctx context.Context, idList []int) (int, error) {
count := 0
err := s.txRunner.ApplicationDeleteTx(ctx, func(ctx context.Context, tx ApplicationDeleteTx) error {
err := s.tx.ApplicationDeleteTx(ctx, func(ctx context.Context, tx IApplicationDeleteTx) error {
deletedApp, err := tx.DeleteApplicationByIdList(ctx, idList)
if err != nil {
return errors.WithMessage(err, "delete application by id list")
@@ -233,7 +263,7 @@ func (s Application) EnrichWithTokens(ctx context.Context, apps []entity.Applica
result[i] = awt
}
tokens, err := s.tokenRepo.GetTokenByAppIdList(ctx, appIdList)
tokens, err := s.tokenRep.GetTokenByAppIdList(ctx, appIdList)
if err != nil {
return nil, errors.WithMessage(err, "get token by app_id list")
}
@@ -246,61 +276,19 @@ func (s Application) EnrichWithTokens(ctx context.Context, apps []entity.Applica
return result, nil
}
func (s Application) NextId(ctx context.Context) (int, error) {
nextId, err := s.appRepo.NextApplicationId(ctx)
if err != nil {
return 0, errors.WithMessage(err, "get next application id")
}
return nextId, nil
}
func (s Application) GetAll(ctx context.Context) ([]domain.Application, error) {
apps, err := s.appRepo.GetAllApplications(ctx)
if err != nil {
return nil, errors.WithMessage(err, "get applications list")
}
result := make([]domain.Application, 0, len(apps))
for _, app := range apps {
result = append(result, s.convertApplication(app))
}
return result, nil
}
func (s Application) Create(ctx context.Context, req domain.CreateApplicationRequest) (*domain.ApplicationWithTokens, error) {
app, err := s.appRepo.CreateApplication(ctx, req.Id, req.Name, req.Description, req.ApplicationGroupId, req.Type)
if err != nil {
return nil, errors.WithMessage(err, "create application")
}
return &domain.ApplicationWithTokens{
App: s.convertApplication(*app),
Tokens: make([]domain.Token, 0),
}, nil
}
func (s Application) Update(ctx context.Context, req domain.UpdateApplicationRequest) (*domain.ApplicationWithTokens, error) {
app, err := s.appRepo.UpdateApplicationWithNewId(ctx, req.OldId, req.NewId, req.Name, req.Description)
if err != nil {
return nil, errors.WithMessage(err, "update application")
}
result, err := s.EnrichWithTokens(ctx, []entity.Application{*app})
if err != nil {
return nil, errors.WithMessage(err, "enrich application with tokens")
}
return result[0], nil
}
func (s Application) convertApplication(req entity.Application) domain.Application {
desc := ""
if req.Description != nil {
desc = *req.Description
}
return domain.Application{
Id: req.Id,
Name: req.Name,
Description: req.Description.String,
ServiceId: req.ApplicationGroupId,
Type: req.Type,
CreatedAt: req.CreatedAt,
UpdatedAt: req.UpdatedAt,
Id: req.Id,
Name: req.Name,
Description: desc,
ApplicationGroupId: req.ApplicationGroupId,
Type: req.Type,
CreatedAt: req.CreatedAt,
UpdatedAt: req.UpdatedAt,
}
}
+147
View File
@@ -0,0 +1,147 @@
package service
import (
"context"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
)
type IApplicationGroupRep interface {
GetApplicationGroupById(ctx context.Context, id int) (*entity.ApplicationGroup, error)
GetApplicationGroupByIdList(ctx context.Context, idList []int) ([]entity.ApplicationGroup, error)
GetApplicationGroupByDomainId(ctx context.Context, domainIdList []int) ([]entity.ApplicationGroup, error)
GetSApplicationGroupByNameAndDomainId(ctx context.Context, name string, domainId int) (*entity.ApplicationGroup, error)
CreateApplicationGroup(ctx context.Context, name string, desc string, domainId int) (*entity.ApplicationGroup, error)
UpdateApplicationGroup(ctx context.Context, id int, name string, description string) (*entity.ApplicationGroup, error)
DeleteApplicationGroup(ctx context.Context, idList []int) (int, error)
}
type IApplicationGroupDomainRep interface {
GetDomainById(ctx context.Context, id int) (*entity.Domain, error)
}
type ApplicationGroup struct {
domainRep IApplicationGroupDomainRep
groupRep IApplicationGroupRep
}
func NewApplicationGroup(
domainRep IApplicationGroupDomainRep,
groupRep IApplicationGroupRep,
) ApplicationGroup {
return ApplicationGroup{
domainRep: domainRep,
groupRep: groupRep,
}
}
func (s ApplicationGroup) GetById(ctx context.Context, id int) (*domain.ApplicationGroup, error) {
applicationGroupEntity, err := s.groupRep.GetApplicationGroupById(ctx, id)
if err != nil {
return nil, errors.WithMessagef(err, "get application group by id")
}
result := s.convertApplicationGroup(*applicationGroupEntity)
return &result, nil
}
func (s ApplicationGroup) GetByIdList(ctx context.Context, idList []int) ([]domain.ApplicationGroup, error) {
applicationGroupEntity, err := s.groupRep.GetApplicationGroupByIdList(ctx, idList)
if err != nil {
return nil, errors.WithMessage(err, "get system by id list")
}
result := make([]domain.ApplicationGroup, len(applicationGroupEntity))
for i := range applicationGroupEntity {
result[i] = s.convertApplicationGroup(applicationGroupEntity[i])
}
return result, nil
}
func (s ApplicationGroup) GetByDomainId(ctx context.Context, domainId int) ([]domain.ApplicationGroup, error) {
applicationGroupEntity, err := s.groupRep.GetApplicationGroupByDomainId(ctx, []int{domainId})
if err != nil {
return nil, errors.WithMessage(err, "get system by id list")
}
result := make([]domain.ApplicationGroup, len(applicationGroupEntity))
for i := range applicationGroupEntity {
result[i] = s.convertApplicationGroup(applicationGroupEntity[i])
}
return result, nil
}
func (s ApplicationGroup) CreateUpdate(ctx context.Context, req domain.ApplicationGroupCreateUpdateRequest) (*domain.ApplicationGroup, error) {
req.DomainId = 1 // Хардкодом проставляем domainId = 1
existed, err := s.groupRep.GetSApplicationGroupByNameAndDomainId(ctx, req.Name, req.DomainId)
switch {
case errors.Is(err, domain.ErrApplicationGroupNotFound):
case err != nil:
return nil, errors.WithMessage(err, "get application group by name and domain_id")
}
_, err = s.domainRep.GetDomainById(ctx, req.DomainId)
if err != nil {
return nil, errors.WithMessage(err, "get domain by id")
}
if req.Id == 0 {
if existed != nil {
return nil, domain.ErrDomainDuplicateName
}
applicationGroupEntity, err := s.groupRep.CreateApplicationGroup(ctx, req.Name, req.Description, req.DomainId)
if err != nil {
return nil, errors.WithMessage(err, "create application group")
}
result := s.convertApplicationGroup(*applicationGroupEntity)
return &result, nil
}
if existed != nil && existed.Id != req.Id {
return nil, domain.ErrDomainDuplicateName
}
_, err = s.groupRep.GetApplicationGroupById(ctx, req.Id)
if err != nil {
return nil, errors.WithMessage(err, "get application group by id")
}
applicationGroupEntity, err := s.groupRep.UpdateApplicationGroup(ctx, req.Id, req.Name, req.Description)
if err != nil {
return nil, errors.WithMessage(err, "update application group")
}
result := s.convertApplicationGroup(*applicationGroupEntity)
return &result, nil
}
func (s ApplicationGroup) Delete(ctx context.Context, idList []int) (int, error) {
result, err := s.groupRep.DeleteApplicationGroup(ctx, idList)
if err != nil {
return 0, errors.WithMessage(err, "delete application group")
}
return result, nil
}
func (s ApplicationGroup) convertApplicationGroup(req entity.ApplicationGroup) domain.ApplicationGroup {
desc := ""
if req.Description != nil {
desc = *req.Description
}
result := domain.ApplicationGroup{
Id: req.Id,
Name: req.Name,
Description: desc,
DomainId: req.DomainId,
CreatedAt: req.CreatedAt,
UpdatedAt: req.UpdatedAt,
}
return result
}
-110
View File
@@ -1,110 +0,0 @@
package baseline
import (
"context"
"isp-system-service/conf"
"isp-system-service/entity"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/log"
)
const adminAppId = 1
type Transaction interface {
CreateDomain(ctx context.Context, name string, desc string, systemId int) (*entity.Domain, error)
CreateAppGroup(ctx context.Context, name string, desc string, domainId int) (*entity.AppGroup, error)
CreateApplication(ctx context.Context, id int, name string, desc string, appGroupId int, appType string) (*entity.Application, error)
UpsertAccessList(ctx context.Context, e entity.AccessList) (int, error)
SaveToken(ctx context.Context, token string, appId int, expireTime int) (*entity.Token, error)
GetTokenById(ctx context.Context, token string) (*entity.Token, error)
TryLock(ctx context.Context, key string) (bool, error)
}
type TxRunner interface {
BaselineTx(ctx context.Context, tx func(ctx context.Context, tx Transaction) error) error
}
type Service struct {
cfg conf.Baseline
txRunner TxRunner
logger log.Logger
}
func NewService(cfg conf.Baseline, txRunner TxRunner, logger log.Logger) Service {
return Service{
cfg: cfg,
txRunner: txRunner,
logger: logger,
}
}
func (s Service) Do(ctx context.Context) error {
ctx = log.ToContext(ctx, log.String("worker", "baseline"))
if s.cfg.InitialAdminUiToken == "" {
s.logger.Info(ctx, "initial admin ui token is empty, skip baseline")
return nil
}
err := s.txRunner.BaselineTx(ctx, s.transaction)
if err != nil {
return errors.WithMessage(err, "run baseline transaction")
}
return nil
}
func (s Service) transaction(ctx context.Context, tx Transaction) error {
locked, err := tx.TryLock(ctx, "isp-system-service.baseline")
if err != nil {
return errors.WithMessage(err, "try lock isp-system-service.baseline")
}
if !locked {
s.logger.Info(ctx, "baseline is locked, skip baseline")
return nil
}
token, err := tx.GetTokenById(ctx, s.cfg.InitialAdminUiToken)
if err != nil {
return errors.WithMessage(err, "get token by id")
}
if token != nil {
s.logger.Info(ctx, "initial admin ui token is exist, skip baseline")
return nil
}
s.logger.Info(ctx, "initial admin ui token is empty, run baseline")
domain, err := tx.CreateDomain(ctx, "root", "", 1)
if err != nil {
return errors.WithMessage(err, "create domain")
}
service, err := tx.CreateAppGroup(ctx, "rootService", "", domain.Id)
if err != nil {
return errors.WithMessage(err, "create service")
}
app, err := tx.CreateApplication(ctx, adminAppId, "admin", "", service.Id, "SYSTEM")
if err != nil {
return errors.WithMessage(err, "create application")
}
_, err = tx.SaveToken(ctx, s.cfg.InitialAdminUiToken, app.Id, -1)
if err != nil {
return errors.WithMessage(err, "save token")
}
_, err = tx.UpsertAccessList(ctx, entity.AccessList{
AppId: app.Id,
Method: "admin/auth/login",
Value: true,
})
if err != nil {
return errors.WithMessage(err, "upsert access list")
}
s.logger.Info(ctx, "baseline done")
return nil
}
+24 -14
View File
@@ -3,24 +3,34 @@ package service
import (
"context"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/pkg/errors"
)
type Domain struct {
repo DomainRepo
type IDomainDomainRep interface {
GetDomainById(ctx context.Context, id int) (*entity.Domain, error)
GetDomainBySystemId(ctx context.Context, systemId int) ([]entity.Domain, error)
GetDomainByNameAndSystemId(ctx context.Context, name string, systemId int) (*entity.Domain, error)
CreateDomain(ctx context.Context, name string, desc string, systemId int) (*entity.Domain, error)
UpdateDomain(ctx context.Context, id int, name string, description string) (*entity.Domain, error)
DeleteDomain(ctx context.Context, idList []int) (int, error)
}
func NewDomain(repo DomainRepo) Domain {
type Domain struct {
domainRep IDomainDomainRep
}
func NewDomain(
domainRep IDomainDomainRep,
) Domain {
return Domain{
repo: repo,
domainRep: domainRep,
}
}
func (s Domain) GetById(ctx context.Context, id int) (*domain.Domain, error) {
domainEntity, err := s.repo.GetDomainById(ctx, id)
domainEntity, err := s.domainRep.GetDomainById(ctx, id)
if err != nil {
return nil, errors.WithMessage(err, "get domain by id")
}
@@ -30,7 +40,7 @@ func (s Domain) GetById(ctx context.Context, id int) (*domain.Domain, error) {
}
func (s Domain) GetBySystemId(ctx context.Context, systemId int) ([]domain.Domain, error) {
domainEntity, err := s.repo.GetDomainBySystemId(ctx, systemId)
domainEntity, err := s.domainRep.GetDomainBySystemId(ctx, systemId)
if err != nil {
return nil, errors.WithMessage(err, "get domain by system_id")
}
@@ -43,7 +53,7 @@ func (s Domain) GetBySystemId(ctx context.Context, systemId int) ([]domain.Domai
}
func (s Domain) CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateRequest, systemId int) (*domain.Domain, error) {
existed, err := s.repo.GetDomainByNameAndSystemId(ctx, req.Name, systemId)
existed, err := s.domainRep.GetDomainByNameAndSystemId(ctx, req.Name, systemId)
switch {
case errors.Is(err, domain.ErrDomainNotFound):
case err != nil:
@@ -55,9 +65,9 @@ func (s Domain) CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateR
return nil, domain.ErrDomainDuplicateName
}
domainEntity, err := s.repo.CreateDomain(ctx, req.Name, req.Description, systemId)
domainEntity, err := s.domainRep.CreateDomain(ctx, req.Name, req.Description, systemId)
if err != nil {
return nil, errors.WithMessage(err, "create domain")
return nil, errors.WithMessagef(err, "create domain")
}
result := s.convertDomain(*domainEntity)
@@ -68,12 +78,12 @@ func (s Domain) CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateR
return nil, domain.ErrDomainDuplicateName
}
_, err = s.repo.GetDomainById(ctx, req.Id)
_, err = s.domainRep.GetDomainById(ctx, req.Id)
if err != nil {
return nil, errors.WithMessage(err, "get domain by id")
}
domainEntity, err := s.repo.UpdateDomain(ctx, req.Id, req.Name, req.Description)
domainEntity, err := s.domainRep.UpdateDomain(ctx, req.Id, req.Name, req.Description)
if err != nil {
return nil, errors.WithMessage(err, "update domain")
}
@@ -83,7 +93,7 @@ func (s Domain) CreateUpdate(ctx context.Context, req domain.DomainCreateUpdateR
}
func (s Domain) Delete(ctx context.Context, idList []int) (int, error) {
result, err := s.repo.DeleteDomain(ctx, idList)
result, err := s.domainRep.DeleteDomain(ctx, idList)
if err != nil {
return 0, errors.WithMessage(err, "delete domain")
}
-43
View File
@@ -1,43 +0,0 @@
package service
import (
"context"
"isp-system-service/entity"
)
type TokenRepo interface {
GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error)
GetTokenById(ctx context.Context, token string) (*entity.Token, error)
}
type DomainRepo interface {
GetDomainById(ctx context.Context, id int) (*entity.Domain, error)
GetDomainBySystemId(ctx context.Context, systemId int) ([]entity.Domain, error)
GetDomainByNameAndSystemId(ctx context.Context, name string, systemId int) (*entity.Domain, error)
CreateDomain(ctx context.Context, name string, desc string, systemId int) (*entity.Domain, error)
UpdateDomain(ctx context.Context, id int, name string, description string) (*entity.Domain, error)
DeleteDomain(ctx context.Context, idList []int) (int, error)
}
type ApplicationRepo interface {
GetApplicationById(ctx context.Context, id int) (*entity.Application, error)
GetApplicationByIdList(ctx context.Context, idList []int) ([]entity.Application, error)
GetApplicationByAppGroupIdList(ctx context.Context, appGroupIdList []int) ([]entity.Application, error)
GetApplicationByNameAndAppGroupId(ctx context.Context, name string, appGroupId int) (*entity.Application, error)
CreateApplication(ctx context.Context, id int, name string, desc string, appGroupId int, appType string) (*entity.Application, error)
UpdateApplication(ctx context.Context, id int, name string, description string) (*entity.Application, error)
UpdateApplicationWithNewId(ctx context.Context, oldId int, newId int, name string, description string) (*entity.Application, error)
NextApplicationId(ctx context.Context) (int, error)
GetAllApplications(ctx context.Context) ([]entity.Application, error)
}
type AppGroupRepo interface {
GetAppGroupById(ctx context.Context, id int) (*entity.AppGroup, error)
GetAppGroupByIdList(ctx context.Context, idList []int) ([]entity.AppGroup, error)
GetAppGroupByDomainId(ctx context.Context, domainIdList []int) ([]entity.AppGroup, error)
GetAllAppGroups(ctx context.Context) ([]entity.AppGroup, error)
GetAppGroupByNameAndDomainId(ctx context.Context, name string, domainId int) (*entity.AppGroup, error)
CreateAppGroup(ctx context.Context, name string, desc string, domainId int) (*entity.AppGroup, error)
UpdateAppGroup(ctx context.Context, id int, name string, description string) (*entity.AppGroup, error)
DeleteAppGroup(ctx context.Context, idList []int) (int, error)
}
@@ -4,10 +4,9 @@ import (
"context"
"time"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/pkg/errors"
)
type TokenRep interface {
@@ -15,25 +14,25 @@ type TokenRep interface {
}
type AccessListRep interface {
GetAccessListByAppIdAndMethod(ctx context.Context, appId int, httpMethod string, method string) (*entity.AccessList, error)
GetAccessListByAppIdAndMethod(ctx context.Context, appId int, method string) (*entity.AccessList, error)
}
type Service struct {
type ApplicationGroup struct {
tokenRep TokenRep
accessListRep AccessListRep
}
func NewService(
func NewApplicationGroup(
tokenRep TokenRep,
accessListRep AccessListRep,
) Service {
return Service{
) ApplicationGroup {
return ApplicationGroup{
tokenRep: tokenRep,
accessListRep: accessListRep,
}
}
func (s Service) Authenticate(ctx context.Context, token string) (*domain.AuthData, error) {
func (s ApplicationGroup) Authenticate(ctx context.Context, token string) (*domain.AuthData, error) {
authData, err := s.tokenRep.AuthDataByToken(ctx, token)
if err != nil {
return nil, errors.WithMessage(err, "get auth data by token")
@@ -45,21 +44,15 @@ func (s Service) Authenticate(ctx context.Context, token string) (*domain.AuthDa
}
return &domain.AuthData{
AppName: authData.AppName,
SystemId: authData.SystemId,
DomainId: authData.DomainId,
ServiceId: authData.ApplicationGroupId,
ApplicationId: authData.AppId,
SystemId: authData.SystemId,
DomainId: authData.DomainId,
ApplicationGroupId: authData.ApplicationGroupIdId,
ApplicationId: authData.AppId,
}, nil
}
func (s Service) Authorize(ctx context.Context, req domain.AuthorizeRequest) (bool, error) {
accessList, err := s.accessListRep.GetAccessListByAppIdAndMethod(
ctx,
req.ApplicationId,
req.HttpMethod,
req.Endpoint,
)
func (s ApplicationGroup) Authorize(ctx context.Context, appId int, endpoint string) (bool, error) {
accessList, err := s.accessListRep.GetAccessListByAppIdAndMethod(ctx, appId, endpoint)
if err != nil {
return false, errors.WithMessage(err, "get access list by app_id and method")
}
-115
View File
@@ -1,115 +0,0 @@
package service
import (
"context"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/pkg/errors"
)
type Service struct {
domainRepo DomainRepo
serviceRepo AppGroupRepo
}
func NewService(
domainRepo DomainRepo,
serviceRepo AppGroupRepo,
) Service {
return Service{
domainRepo: domainRepo,
serviceRepo: serviceRepo,
}
}
func (s Service) GetById(ctx context.Context, id int) (*domain.Service, error) {
serviceEntity, err := s.serviceRepo.GetAppGroupById(ctx, id)
if err != nil {
return nil, errors.WithMessage(err, "get service by id")
}
result := s.convertService(*serviceEntity)
return &result, nil
}
func (s Service) GetByIdList(ctx context.Context, idList []int) ([]domain.Service, error) {
serviceEntity, err := s.serviceRepo.GetAppGroupByIdList(ctx, idList)
if err != nil {
return nil, errors.WithMessage(err, "get system by id list")
}
result := make([]domain.Service, len(serviceEntity))
for i := range serviceEntity {
result[i] = s.convertService(serviceEntity[i])
}
return result, nil
}
func (s Service) GetByDomainId(ctx context.Context, domainId int) ([]domain.Service, error) {
serviceEntity, err := s.serviceRepo.GetAppGroupByDomainId(ctx, []int{domainId})
if err != nil {
return nil, errors.WithMessage(err, "get system by id list")
}
result := make([]domain.Service, len(serviceEntity))
for i := range serviceEntity {
result[i] = s.convertService(serviceEntity[i])
}
return result, nil
}
func (s Service) CreateUpdate(ctx context.Context, req domain.ServiceCreateUpdateRequest) (*domain.Service, error) {
req.DomainId = 1 // temporary use only 1 domain, soon domain entity will be removed
_, err := s.domainRepo.GetDomainById(ctx, req.DomainId)
if err != nil {
return nil, errors.WithMessage(err, "get domain by id")
}
if req.Id == 0 {
serviceEntity, err := s.serviceRepo.CreateAppGroup(ctx, req.Name, req.Description, req.DomainId)
if err != nil {
return nil, errors.WithMessage(err, "create service")
}
result := s.convertService(*serviceEntity)
return &result, nil
}
_, err = s.serviceRepo.GetAppGroupById(ctx, req.Id)
if err != nil {
return nil, errors.WithMessage(err, "get service by id")
}
serviceEntity, err := s.serviceRepo.UpdateAppGroup(ctx, req.Id, req.Name, req.Description)
if err != nil {
return nil, errors.WithMessage(err, "update service")
}
result := s.convertService(*serviceEntity)
return &result, nil
}
func (s Service) Delete(ctx context.Context, idList []int) (int, error) {
result, err := s.serviceRepo.DeleteAppGroup(ctx, idList)
if err != nil {
return 0, errors.WithMessage(err, "delete service")
}
return result, nil
}
func (s Service) convertService(req entity.AppGroup) domain.Service {
result := domain.Service{
Id: req.Id,
Name: req.Name,
Description: req.Description.String,
DomainId: req.DomainId,
CreatedAt: req.CreatedAt,
UpdatedAt: req.UpdatedAt,
}
return result
}
+65 -50
View File
@@ -3,65 +3,80 @@ package service
import (
"context"
"github.com/pkg/errors"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/pkg/errors"
)
type ApplicationTokenCreator interface {
type ITokenSource interface {
CreateApplicationToken() (string, error)
}
type AppEnricher interface {
type ITokenAppEnrich interface {
EnrichWithTokens(ctx context.Context, apps []entity.Application) ([]*domain.ApplicationWithTokens, error)
}
type TokenCreateTx interface {
type ITokenApplicationRep interface {
GetApplicationById(ctx context.Context, id int) (*entity.Application, error)
}
type ITokenServiceRep interface {
GetApplicationGroupById(ctx context.Context, id int) (*entity.ApplicationGroup, error)
}
type ITokenDomainRep interface {
GetDomainById(ctx context.Context, id int) (*entity.Domain, error)
}
type ITokenTokenRep interface {
GetTokenByAppIdList(ctx context.Context, appIdList []int) ([]entity.Token, error)
}
type ITokenCreateTx interface {
SaveToken(ctx context.Context, token string, appId int, expireTime int) (*entity.Token, error)
}
type TokenRevokeTx interface {
type ITokenRevokeTx interface {
DeleteToken(ctx context.Context, tokens []string) (int, error)
}
type TokenTxRunner interface {
TokenCreateTx(ctx context.Context, tx func(ctx context.Context, tx TokenCreateTx) error) error
TokenRevokeTx(ctx context.Context, tx func(ctx context.Context, tx TokenRevokeTx) error) error
type ITokenTxRunner interface {
TokenCreateTx(ctx context.Context, tx func(ctx context.Context, tx ITokenCreateTx) error) error
TokenRevokeTx(ctx context.Context, tx func(ctx context.Context, tx ITokenRevokeTx) error) error
}
type Token struct {
jwt ApplicationTokenCreator
appEnricher AppEnricher
tx TokenTxRunner
appRepo ApplicationRepo
domainRepo DomainRepo
serviceRepo AppGroupRepo
tokenRepo TokenRepo
jwt ITokenSource
appEnrich ITokenAppEnrich
tx ITokenTxRunner
appRep ITokenApplicationRep
domainRep ITokenDomainRep
groupRep ITokenServiceRep
tokenRep ITokenTokenRep
}
func NewToken(
jwtGenerate ApplicationTokenCreator,
appEnricher AppEnricher,
tx TokenTxRunner,
appRepo ApplicationRepo,
domainRepo DomainRepo,
appGroupRepo AppGroupRepo,
tokenRepo TokenRepo,
jwtGenerate ITokenSource,
appEnrich ITokenAppEnrich,
tx ITokenTxRunner,
appRep ITokenApplicationRep,
domainRep ITokenDomainRep,
groupRep ITokenServiceRep,
tokenRep ITokenTokenRep,
) Token {
return Token{
appEnricher: appEnricher,
jwt: jwtGenerate,
tx: tx,
appRepo: appRepo,
domainRepo: domainRepo,
serviceRepo: appGroupRepo,
tokenRepo: tokenRepo,
appEnrich: appEnrich,
jwt: jwtGenerate,
tx: tx,
appRep: appRep,
domainRep: domainRep,
groupRep: groupRep,
tokenRep: tokenRep,
}
}
func (s Token) GetByAppId(ctx context.Context, appId int) ([]domain.Token, error) {
tokenEntity, err := s.tokenRepo.GetTokenByAppIdList(ctx, []int{appId})
tokenEntity, err := s.tokenRep.GetTokenByAppIdList(ctx, []int{appId})
if err != nil {
return nil, errors.WithMessage(err, "get token by app_id list")
}
@@ -75,30 +90,30 @@ func (s Token) GetByAppId(ctx context.Context, appId int) ([]domain.Token, error
}
func (s Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*domain.ApplicationWithTokens, error) {
applicationEntity, err := s.appRepo.GetApplicationById(ctx, req.AppId)
applicationEntity, err := s.appRep.GetApplicationById(ctx, req.AppId)
if err != nil {
return nil, errors.WithMessage(err, "get application by id")
return nil, errors.WithMessagef(err, "get application by id")
}
serviceEntity, err := s.serviceRepo.GetAppGroupById(ctx, applicationEntity.ApplicationGroupId)
applicationGroupIdEntity, err := s.groupRep.GetApplicationGroupById(ctx, applicationEntity.ApplicationGroupId)
if err != nil {
return nil, errors.WithMessage(err, "get service by id")
return nil, errors.WithMessagef(err, "get application groupId by id")
}
_, err = s.domainRepo.GetDomainById(ctx, serviceEntity.DomainId)
_, err = s.domainRep.GetDomainById(ctx, applicationGroupIdEntity.DomainId)
if err != nil {
return nil, errors.WithMessage(err, "get domain by id")
return nil, errors.WithMessagef(err, "get domain by id")
}
token, err := s.jwt.CreateApplicationToken()
if err != nil {
return nil, errors.WithMessage(err, "create application token")
return nil, errors.WithMessagef(err, "create application token")
}
err = s.tx.TokenCreateTx(ctx, func(ctx context.Context, tx TokenCreateTx) error {
err = s.tx.TokenCreateTx(ctx, func(ctx context.Context, tx ITokenCreateTx) error {
_, err = tx.SaveToken(ctx, token, req.AppId, req.ExpireTimeMs)
if err != nil {
return errors.WithMessage(err, "tx save token")
return errors.WithMessagef(err, "tx save token")
}
return nil
@@ -107,35 +122,35 @@ func (s Token) Create(ctx context.Context, req domain.TokenCreateRequest) (*doma
return nil, errors.WithMessage(err, "token create transaction")
}
arr, err := s.appEnricher.EnrichWithTokens(ctx, []entity.Application{*applicationEntity})
arr, err := s.appEnrich.EnrichWithTokens(ctx, []entity.Application{*applicationEntity})
if err != nil {
return nil, errors.WithMessage(err, "application enrich with tokens")
return nil, errors.WithMessagef(err, "application enrich with tokens")
}
return arr[0], nil
}
func (s Token) Revoke(ctx context.Context, req domain.TokenRevokeRequest) (*domain.ApplicationWithTokens, error) {
app, err := s.appRepo.GetApplicationById(ctx, req.AppId)
app, err := s.appRep.GetApplicationById(ctx, req.AppId)
if err != nil {
return nil, errors.WithMessage(err, "get application by id")
return nil, errors.WithMessagef(err, "get application by id")
}
_, err = s.revokeTokens(ctx, req.Tokens)
if err != nil {
return nil, errors.WithMessage(err, "revoke tokens")
return nil, errors.WithMessagef(err, "reboke tokens")
}
res, err := s.appEnricher.EnrichWithTokens(ctx, []entity.Application{*app})
res, err := s.appEnrich.EnrichWithTokens(ctx, []entity.Application{*app})
if err != nil {
return nil, errors.WithMessage(err, "application enrich")
return nil, errors.WithMessagef(err, "application enrich")
}
return res[0], nil
}
func (s Token) RevokeByAppId(ctx context.Context, appId int) (*domain.DeleteResponse, error) {
tokens, err := s.tokenRepo.GetTokenByAppIdList(ctx, []int{appId})
tokens, err := s.tokenRep.GetTokenByAppIdList(ctx, []int{appId})
if err != nil {
return nil, errors.WithMessage(err, "get token by app_id list")
}
@@ -154,10 +169,10 @@ func (s Token) revokeTokens(ctx context.Context, tokens []string) (*domain.Delet
}
var count int
err := s.tx.TokenRevokeTx(ctx, func(ctx context.Context, tx TokenRevokeTx) error {
err := s.tx.TokenRevokeTx(ctx, func(ctx context.Context, tx ITokenRevokeTx) error {
deleted, err := tx.DeleteToken(ctx, tokens)
if err != nil {
return errors.WithMessage(err, "tx delete token")
return errors.WithMessagef(err, "tx delete token")
}
count = deleted
+3 -2
View File
@@ -7,14 +7,15 @@ import (
"github.com/pkg/errors"
)
type TokenSource struct{}
type TokenSource struct {
}
func NewTokenSource() TokenSource {
return TokenSource{}
}
func (s TokenSource) CreateApplicationToken() (string, error) {
cryptoRand := make([]byte, 128) //nolint:mnd
cryptoRand := make([]byte, 128) //nolint:gomnd
_, err := rand.Read(cryptoRand)
if err != nil {
return "", errors.WithMessage(err, "crypto/rand read")
-232
View File
@@ -1,232 +0,0 @@
package tests_test
import (
"testing"
"github.com/txix-open/isp-kit/dbx"
"isp-system-service/assembly"
"isp-system-service/conf"
"isp-system-service/domain"
"isp-system-service/entity"
"isp-system-service/repository"
"github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/fake"
"github.com/txix-open/isp-kit/test/grpct"
)
func TestAccessListSuite(t *testing.T) {
t.Parallel()
suite.Run(t, &AccessListSuite{})
}
type AccessListSuite struct {
suite.Suite
test *test.Test
testDb *dbt.TestDb
api *client.Client
accessListRepo repository.AccessList
appId int
}
func (s *AccessListSuite) SetupTest() {
s.test, _ = test.New(s.T())
s.testDb = dbt.New(s.test, dbx.WithMigrationRunner("../migrations", s.test.Logger()))
locator := assembly.NewLocator(s.testDb, s.test.Logger())
config := locator.Config(conf.Remote{})
_, s.api = grpct.TestServer(s.test, config.Handler)
s.accessListRepo = repository.NewAccessList(s.testDb)
createdDomain, err := repository.NewDomain(s.testDb).CreateDomain(
s.T().Context(),
fake.It[string](),
fake.It[string](),
1,
)
s.Require().NoError(err)
appGroup, err := repository.NewAppGroup(s.testDb).CreateAppGroup(
s.T().Context(),
fake.It[string](),
fake.It[string](),
createdDomain.Id,
)
s.Require().NoError(err)
s.appId = fake.It[int]()
_, err = repository.NewApplication(s.testDb).CreateApplication(
s.T().Context(),
s.appId,
fake.It[string](),
fake.It[string](),
appGroup.Id,
domain.ApplicationSystemType,
)
s.Require().NoError(err)
}
func (s *AccessListSuite) TestGetById_HappyPath() {
expectedAccessList := []entity.AccessList{
{
AppId: s.appId,
Method: fake.It[string](),
Value: false,
},
{
AppId: s.appId,
Method: fake.It[string](),
Value: true,
},
{
AppId: s.appId,
Method: fake.It[string](),
Value: true,
},
}
err := s.accessListRepo.InsertArrayAccessList(s.T().Context(), expectedAccessList)
s.Require().NoError(err)
req := domain.Identity{
Id: s.appId,
}
var accessList []domain.MethodInfo
err = s.api.Invoke("system/access_list/get_by_id").
JsonRequestBody(&req).
JsonResponseBody(&accessList).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().Len(accessList, len(expectedAccessList))
actualAccessList := s.convertAccessList(accessList)
s.Require().ElementsMatch(expectedAccessList, actualAccessList)
}
func (s *AccessListSuite) TestSetOne_HappyPath() {
expectedAccessList := []entity.AccessList{
{
AppId: s.appId,
Method: fake.It[string](),
Value: false,
},
{
AppId: s.appId,
Method: fake.It[string](),
Value: true,
},
{
AppId: s.appId,
Method: fake.It[string](),
Value: true,
},
}
err := s.accessListRepo.InsertArrayAccessList(s.T().Context(), expectedAccessList)
s.Require().NoError(err)
req := domain.AccessListSetOneRequest{
AppId: s.appId,
Method: expectedAccessList[0].Method,
Value: true,
}
err = s.api.Invoke("system/access_list/set_one").
JsonRequestBody(&req).
Do(s.T().Context())
s.Require().NoError(err)
actualAccessList, err := s.accessListRepo.GetAccessListByAppId(s.T().Context(), s.appId)
s.Require().NoError(err)
for i := range expectedAccessList {
expectedAccessList[i].Value = true
}
s.Require().ElementsMatch(expectedAccessList, actualAccessList)
}
func (s *AccessListSuite) TestSetList_HappyPath() {
req := domain.AccessListSetListRequest{
AppId: s.appId,
Methods: []domain.MethodInfo{
{
Method: fake.It[string](),
Value: true,
},
{
Method: fake.It[string](),
Value: true,
},
},
}
err := s.api.Invoke("system/access_list/set_list").
JsonRequestBody(&req).
Do(s.T().Context())
s.Require().NoError(err)
actualAccessList, err := s.accessListRepo.GetAccessListByAppId(s.T().Context(), s.appId)
s.Require().NoError(err)
s.Require().Len(actualAccessList, len(req.Methods))
expectedAccessList := s.convertAccessList(req.Methods)
s.Require().ElementsMatch(expectedAccessList, actualAccessList)
}
func (s *AccessListSuite) TestDeleteList_HappyPath() {
accessList := []entity.AccessList{
{
AppId: s.appId,
Method: fake.It[string](),
Value: false,
},
{
AppId: s.appId,
Method: fake.It[string](),
Value: true,
},
{
AppId: s.appId,
Method: fake.It[string](),
Value: true,
},
}
err := s.accessListRepo.InsertArrayAccessList(s.T().Context(), accessList)
s.Require().NoError(err)
req := domain.AccessListDeleteListRequest{
AppId: s.appId,
Methods: []string{
accessList[0].Method,
accessList[1].Method,
},
}
err = s.api.Invoke("system/access_list/delete_list").
JsonRequestBody(&req).
Do(s.T().Context())
s.Require().NoError(err)
actualAccessList, err := s.accessListRepo.GetAccessListByAppId(s.T().Context(), s.appId)
s.Require().NoError(err)
s.Require().Len(actualAccessList, 1)
s.Require().Equal(accessList[2], actualAccessList[0])
}
func (s *AccessListSuite) convertAccessList(methods []domain.MethodInfo) []entity.AccessList {
converted := make([]entity.AccessList, 0, len(methods))
for _, method := range methods {
converted = append(converted, entity.AccessList{
AppId: s.appId,
Method: method.Method,
Value: method.Value,
})
}
return converted
}
-288
View File
@@ -1,288 +0,0 @@
package tests_test
import (
"isp-system-service/assembly"
"isp-system-service/conf"
"isp-system-service/domain"
"isp-system-service/entity"
"isp-system-service/repository"
"testing"
"time"
"github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/dbx"
"github.com/txix-open/isp-kit/grpc/apierrors"
"github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/fake"
"github.com/txix-open/isp-kit/test/grpct"
)
func TestApplicationGroupSuite(t *testing.T) {
t.Parallel()
suite.Run(t, &AppGroupSuite{})
}
type AppGroupSuite struct {
suite.Suite
test *test.Test
testDb *dbt.TestDb
domainRepo repository.Domain
appGroupRepo repository.AppGroup
api *client.Client
}
func (s *AppGroupSuite) SetupTest() {
s.test, _ = test.New(s.T())
s.testDb = dbt.New(s.test, dbx.WithMigrationRunner("../migrations", s.test.Logger()))
locator := assembly.NewLocator(s.testDb, s.test.Logger())
config := locator.Config(conf.Remote{})
_, s.api = grpct.TestServer(s.test, config.Handler)
s.domainRepo = repository.NewDomain(s.testDb)
s.appGroupRepo = repository.NewAppGroup(s.testDb)
q := `
INSERT INTO domain
(id, name, description, system_id)
VALUES ($1, $2, $3, $4)
RETURNING id, name, description, system_id, created_at, updated_at
`
_, err := s.testDb.Exec(s.T().Context(), q, 1, fake.It[string](), fake.It[string](), 1)
s.Require().NoError(err)
}
func (s *AppGroupSuite) TestGetByIdList() {
toGenerate := 10
appGroups := make([]domain.AppGroup, 0, toGenerate)
ids := make([]int, 0, toGenerate)
for range 10 {
appGroup := s.createAppGroup()
appGroups = append(appGroups, domain.AppGroup{
Id: appGroup.Id,
Name: appGroup.Name,
Description: appGroup.Description.String,
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
})
ids = append(ids, appGroup.Id)
}
result := []domain.AppGroup{}
apiReq := domain.IdListRequest{IdList: ids}
err := s.api.Invoke("system/application_group/get_by_id_list").
JsonRequestBody(apiReq).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
for i := range result {
s.Require().NotEmpty(result[i].CreatedAt)
result[i].CreatedAt = time.Time{}
s.Require().NotEmpty(result[i].UpdatedAt)
result[i].UpdatedAt = time.Time{}
}
s.Require().ElementsMatch(appGroups, result)
}
func (s *AppGroupSuite) TestGetByIdList_EmptyDescription() {
toGenerate := 10
appGroups := make([]domain.AppGroup, 0, toGenerate)
ids := make([]int, 0, toGenerate)
for range 10 {
appGroup, err := s.appGroupRepo.CreateAppGroup(
s.T().Context(),
fake.It[string](),
"",
1,
)
s.Require().NoError(err)
appGroups = append(appGroups, domain.AppGroup{
Id: appGroup.Id,
Name: appGroup.Name,
Description: "",
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
})
ids = append(ids, appGroup.Id)
}
result := []domain.AppGroup{}
apiReq := domain.IdListRequest{IdList: ids}
err := s.api.Invoke("system/application_group/get_by_id_list").
JsonRequestBody(apiReq).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
for i := range result {
s.Require().NotEmpty(result[i].CreatedAt)
result[i].CreatedAt = time.Time{}
s.Require().NotEmpty(result[i].UpdatedAt)
result[i].UpdatedAt = time.Time{}
}
s.Require().ElementsMatch(appGroups, result)
}
func (s *AppGroupSuite) TestGetByIdList_NotFoundAppGroups() {
appGroup := s.createAppGroup()
result := []domain.AppGroup{}
apiReq := domain.IdListRequest{IdList: []int{appGroup.Id + 1}}
err := s.api.Invoke("system/application_group/get_by_id_list").
JsonRequestBody(apiReq).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().Empty(result)
}
func (s *AppGroupSuite) TestCreate_HappyPath() {
apiReq := domain.CreateAppGroupRequest{
Name: fake.It[string](),
Description: fake.It[string](),
}
var result domain.AppGroup
err := s.api.Invoke("system/application_group/create").
JsonRequestBody(apiReq).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().Equal(apiReq.Name, result.Name)
s.Require().Equal(apiReq.Description, result.Description)
appGroup, err := s.appGroupRepo.GetAppGroupById(s.T().Context(), result.Id)
s.Require().NoError(err)
s.Require().Equal(apiReq.Name, appGroup.Name)
s.Require().Equal(apiReq.Description, appGroup.Description.String)
}
func (s *AppGroupSuite) TestCreate_AppGroupNameNotUnique() {
appGroup := s.createAppGroup()
apiReq := domain.CreateAppGroupRequest{
Name: appGroup.Name,
Description: fake.It[string](),
}
var result domain.AppGroup
err := s.api.Invoke("system/application_group/create").
JsonRequestBody(apiReq).
JsonResponseBody(&result).
Do(s.T().Context())
apiError := apierrors.FromError(err)
s.Require().NotNil(apiError)
s.Require().Equal(domain.ErrCodeAppGroupDuplicateName, apiError.ErrorCode)
}
func (s *AppGroupSuite) TestUpdate_HappyPath() {
appGroupToUpdate := s.createAppGroup()
apiReq := domain.UpdateAppGroupRequest{
Id: appGroupToUpdate.Id,
Name: fake.It[string](),
Description: fake.It[string](),
}
var result domain.AppGroup
err := s.api.Invoke("system/application_group/update").
JsonRequestBody(apiReq).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().Equal(apiReq.Name, result.Name)
s.Require().Equal(apiReq.Description, result.Description)
appGroup, err := s.appGroupRepo.GetAppGroupById(s.T().Context(), apiReq.Id)
s.Require().NoError(err)
s.Require().Equal(apiReq.Name, appGroup.Name)
s.Require().Equal(apiReq.Description, appGroup.Description.String)
}
func (s *AppGroupSuite) TestUpdate_AppGroupNameNotUnique() {
appGroupToUpdate := s.createAppGroup()
appGroup := s.createAppGroup()
apiReq := domain.UpdateAppGroupRequest{
Id: appGroupToUpdate.Id,
Name: appGroup.Name,
Description: fake.It[string](),
}
err := s.api.Invoke("system/application_group/update").
JsonRequestBody(apiReq).
Do(s.T().Context())
apiError := apierrors.FromError(err)
s.Require().NotNil(apiError)
s.Require().Equal(domain.ErrCodeAppGroupDuplicateName, apiError.ErrorCode)
}
func (s *AppGroupSuite) TestUpdate_AppGroupNotFound() {
apiReq := domain.UpdateAppGroupRequest{
Id: fake.It[int](),
Name: fake.It[string](),
Description: fake.It[string](),
}
err := s.api.Invoke("system/application_group/update").
JsonRequestBody(apiReq).
Do(s.T().Context())
apiError := apierrors.FromError(err)
s.Require().NotNil(apiError)
s.Require().Equal(domain.ErrCodeAppGroupNotFound, apiError.ErrorCode)
}
func (s *AppGroupSuite) TestDeleteList() {
appGroupToDelete := s.createAppGroup()
appGroup := s.createAppGroup()
var result domain.DeleteResponse
apiReq := domain.IdListRequest{IdList: []int{appGroupToDelete.Id}}
err := s.api.Invoke("system/application_group/delete_list").
JsonRequestBody(apiReq).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().Equal(1, result.Deleted)
_, err = s.appGroupRepo.GetAppGroupById(s.T().Context(), appGroup.Id)
s.Require().NoError(err)
}
func (s *AppGroupSuite) TestGetAll() {
toGenerate := 10
appGroups := make([]domain.AppGroup, 0, toGenerate)
for range 10 {
appGroup := s.createAppGroup()
appGroups = append(appGroups, domain.AppGroup{
Id: appGroup.Id,
Name: appGroup.Name,
Description: appGroup.Description.String,
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
})
}
result := []domain.AppGroup{}
err := s.api.Invoke("system/application_group/get_all").
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
for i := range result {
s.Require().NotEmpty(result[i].CreatedAt)
result[i].CreatedAt = time.Time{}
s.Require().NotEmpty(result[i].UpdatedAt)
result[i].UpdatedAt = time.Time{}
}
s.Require().ElementsMatch(appGroups, result)
}
func (s *AppGroupSuite) createAppGroup() *entity.AppGroup {
appGroup, err := s.appGroupRepo.CreateAppGroup(
s.T().Context(),
fake.It[string](),
fake.It[string](),
1,
)
s.Require().NoError(err)
return appGroup
}
-342
View File
@@ -1,342 +0,0 @@
package tests_test
import (
"isp-system-service/assembly"
"isp-system-service/conf"
"isp-system-service/domain"
"isp-system-service/entity"
"isp-system-service/repository"
"testing"
"time"
"github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/dbx"
"github.com/txix-open/isp-kit/grpc/apierrors"
"github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/fake"
"github.com/txix-open/isp-kit/test/grpct"
)
func TestApplicationSuite(t *testing.T) {
t.Parallel()
suite.Run(t, &ApplicationSuite{})
}
type ApplicationSuite struct {
suite.Suite
test *test.Test
testDb *dbt.TestDb
domainRepo repository.Domain
appRepo repository.Application
appGroupRepo repository.AppGroup
tokenRepo repository.Token
api *client.Client
}
func (s *ApplicationSuite) SetupTest() {
s.test, _ = test.New(s.T())
s.testDb = dbt.New(s.test, dbx.WithMigrationRunner("../migrations", s.test.Logger()))
locator := assembly.NewLocator(s.testDb, s.test.Logger())
config := locator.Config(conf.Remote{})
_, s.api = grpct.TestServer(s.test, config.Handler)
s.domainRepo = repository.NewDomain(s.testDb)
s.appRepo = repository.NewApplication(s.testDb)
s.appGroupRepo = repository.NewAppGroup(s.testDb)
s.tokenRepo = repository.NewToken(s.testDb)
}
func (s *ApplicationSuite) TestGetAllApplications() {
expectedApps := s.insertApps(2)
result := []domain.Application{}
err := s.api.Invoke("system/application/get_all").
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
for i := range result {
s.Require().NotEmpty(result[i].CreatedAt)
result[i].CreatedAt = time.Time{}
s.Require().NotEmpty(result[i].UpdatedAt)
result[i].UpdatedAt = time.Time{}
}
s.Require().ElementsMatch(expectedApps, result)
}
func (s *ApplicationSuite) TestCreate_HappyPath() {
result := domain.ApplicationWithTokens{}
appGroup := s.createAppGroup()
apiReq := domain.CreateApplicationRequest{
Id: 1,
Name: fake.It[string](),
Type: domain.ApplicationSystemType,
ApplicationGroupId: appGroup.Id,
}
err := s.api.Invoke("system/application/create_application").
JsonRequestBody(apiReq).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().NotEmpty(result.App.CreatedAt)
result.App.CreatedAt = time.Time{}
s.Require().NotEmpty(result.App.UpdatedAt)
result.App.UpdatedAt = time.Time{}
expectedApp := domain.Application{
Id: apiReq.Id,
Name: apiReq.Name,
Description: apiReq.Description,
Type: apiReq.Type,
ServiceId: apiReq.ApplicationGroupId,
}
s.Require().Equal(expectedApp, result.App)
s.Require().Empty(result.Tokens)
}
func (s *ApplicationSuite) TestCreate_AppGroupNotFound() {
apiReq := domain.CreateApplicationRequest{
Id: 1,
Name: fake.It[string](),
Type: domain.ApplicationSystemType,
ApplicationGroupId: 1,
}
err := s.api.Invoke("system/application/create_application").
JsonRequestBody(apiReq).
Do(s.T().Context())
apiError := apierrors.FromError(err)
s.Require().NotNil(apiError)
s.Require().Equal(domain.ErrCodeAppGroupNotFound, apiError.ErrorCode)
}
func (s *ApplicationSuite) TestCreate_ApplicationNameNotUniqueInAppGroup() {
inserted := s.insertApps(1)
apiReq := domain.CreateApplicationRequest{
Id: inserted[0].Id + 1,
Name: inserted[0].Name,
Type: domain.ApplicationSystemType,
ApplicationGroupId: inserted[0].ServiceId,
}
err := s.api.Invoke("system/application/create_application").
JsonRequestBody(apiReq).
Do(s.T().Context())
apiError := apierrors.FromError(err)
s.Require().NotNil(apiError)
s.Require().Equal(domain.ErrCodeApplicationDuplicateName, apiError.ErrorCode)
}
func (s *ApplicationSuite) TestCreate_ApplicationIdNotUnique() {
inserted := s.insertApps(1)
apiReq := domain.CreateApplicationRequest{
Id: inserted[0].Id,
Name: inserted[0].Name,
Type: domain.ApplicationSystemType,
ApplicationGroupId: inserted[0].ServiceId,
}
err := s.api.Invoke("system/application/create_application").
JsonRequestBody(apiReq).
Do(s.T().Context())
apiError := apierrors.FromError(err)
s.Require().NotNil(apiError)
s.Require().Equal(domain.ErrCodeApplicationDuplicateId, apiError.ErrorCode)
}
func (s *ApplicationSuite) TestUpdate_HappyPath() {
inserted := s.insertApps(2)
apiReq := domain.UpdateApplicationRequest{
OldId: inserted[0].Id,
NewId: inserted[0].Id + inserted[1].Id,
Name: fake.It[string](),
Description: fake.It[string](),
}
var result domain.ApplicationWithTokens
err := s.api.Invoke("system/application/update_application").
JsonRequestBody(apiReq).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().NotEmpty(result.App.CreatedAt)
result.App.CreatedAt = time.Time{}
s.Require().NotEmpty(result.App.UpdatedAt)
result.App.UpdatedAt = time.Time{}
expectedApp := domain.Application{
Id: apiReq.NewId,
Name: apiReq.Name,
Description: apiReq.Description,
Type: inserted[0].Type,
ServiceId: inserted[0].ServiceId,
}
s.Require().Equal(expectedApp, result.App)
s.Require().Empty(result.Tokens)
app, err := s.appRepo.GetApplicationById(s.T().Context(), apiReq.NewId)
s.Require().NoError(err)
expectedDbApp := entity.Application{
Id: apiReq.NewId,
Name: apiReq.Name,
Description: app.Description,
Type: inserted[0].Type,
ApplicationGroupId: inserted[0].ServiceId,
}
s.Require().NotEmpty(app.CreatedAt)
app.CreatedAt = time.Time{}
s.Require().NotEmpty(app.UpdatedAt)
app.UpdatedAt = time.Time{}
s.Require().Equal(expectedDbApp, *app)
}
func (s *ApplicationSuite) TestUpdate_ApplicationNameNotUniqueInAppGroup() {
inserted := s.insertApps(2)
apiReq := domain.UpdateApplicationRequest{
NewId: inserted[0].Id,
OldId: inserted[0].Id,
Name: inserted[1].Name,
Description: fake.It[string](),
}
err := s.api.Invoke("system/application/update_application").
JsonRequestBody(apiReq).
Do(s.T().Context())
apiError := apierrors.FromError(err)
s.Require().NotNil(apiError)
s.Require().Equal(domain.ErrCodeApplicationDuplicateName, apiError.ErrorCode)
}
func (s *ApplicationSuite) TestUpdate_AppIdNotUnique() {
inserted := s.insertApps(2)
apiReq := domain.UpdateApplicationRequest{
OldId: inserted[0].Id,
NewId: inserted[1].Id,
Name: fake.It[string](),
Description: fake.It[string](),
}
err := s.api.Invoke("system/application/update_application").
JsonRequestBody(apiReq).
Do(s.T().Context())
apiError := apierrors.FromError(err)
s.Require().NotNil(apiError)
s.Require().Equal(domain.ErrCodeApplicationDuplicateId, apiError.ErrorCode)
}
func (s *ApplicationSuite) TestUpdate_AppNotFound() {
apiReq := domain.UpdateApplicationRequest{
OldId: fake.It[int](),
NewId: fake.It[int](),
Name: fake.It[string](),
Description: fake.It[string](),
}
err := s.api.Invoke("system/application/update_application").
JsonRequestBody(apiReq).
Do(s.T().Context())
apiError := apierrors.FromError(err)
s.Require().NotNil(apiError)
s.Require().Equal(domain.ErrCodeApplicationNotFound, apiError.ErrorCode)
}
func (s *ApplicationSuite) TestGetByToken() {
insertedApps := s.insertApps(2)
token := fake.It[string]()
expectedApp := domain.GetApplicationByTokenResponse{
ApplicationId: insertedApps[0].Id,
ApplicationGroupId: insertedApps[0].ServiceId,
}
_, err := s.tokenRepo.SaveToken(s.T().Context(), token, expectedApp.ApplicationId, fake.It[int]())
s.Require().NoError(err)
result := domain.GetApplicationByTokenResponse{}
err = s.api.Invoke("system/application/get_application_by_token").
JsonRequestBody(domain.GetApplicationByTokenRequest{Token: token}).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().Equal(expectedApp, result)
}
func (s *ApplicationSuite) TestGetByToken_NotFound() {
s.insertApps(2)
result := domain.GetApplicationByTokenResponse{}
err := s.api.Invoke("system/application/get_application_by_token").
JsonRequestBody(domain.GetApplicationByTokenRequest{Token: fake.It[string]()}).
JsonResponseBody(&result).
Do(s.T().Context())
apiError := apierrors.FromError(err)
s.Require().NotNil(apiError)
s.Require().Equal(domain.ErrCodeApplicationNotFound, apiError.ErrorCode)
}
func (s *ApplicationSuite) createAppGroup() *entity.AppGroup {
createdDomain, err := s.domainRepo.CreateDomain(
s.T().Context(),
fake.It[string](),
fake.It[string](),
1,
)
s.Require().NoError(err)
appGroup, err := s.appGroupRepo.CreateAppGroup(
s.T().Context(),
fake.It[string](),
fake.It[string](),
createdDomain.Id,
)
s.Require().NoError(err)
return appGroup
}
func (s *ApplicationSuite) insertApps(appsCount uint) []domain.Application {
toInsert := fake.It[[]domain.Application](fake.MinSliceSize(appsCount), fake.MaxSliceSize(appsCount))
appGroup := s.createAppGroup()
toExpect := make([]domain.Application, 0, len(toInsert))
for _, app := range toInsert {
appId, err := s.appRepo.NextApplicationId(s.T().Context())
s.Require().NoError(err)
createdApp, err := s.appRepo.CreateApplication(
s.T().Context(),
appId,
app.Name,
app.Description,
appGroup.Id,
app.Type,
)
s.Require().NoError(err)
s.Require().NotEmpty(createdApp.CreatedAt)
s.Require().NotEmpty(createdApp.UpdatedAt)
toExpect = append(toExpect, domain.Application{
Id: createdApp.Id,
Name: createdApp.Name,
Description: createdApp.Description.String,
ServiceId: createdApp.ApplicationGroupId,
Type: createdApp.Type,
CreatedAt: time.Time{},
UpdatedAt: time.Time{},
})
}
return toExpect
}
-52
View File
@@ -1,52 +0,0 @@
package tests_test
import (
"github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/dbx"
"github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/fake"
"github.com/txix-open/isp-kit/test/grpct"
"isp-system-service/assembly"
"isp-system-service/conf"
"isp-system-service/service/baseline"
"testing"
)
func TestBaselineSuite(t *testing.T) {
t.Parallel()
suite.Run(t, &BaselineSuite{})
}
type BaselineSuite struct {
suite.Suite
test *test.Test
testDb *dbt.TestDb
baseline baseline.Service
api *client.Client
}
func (s *BaselineSuite) SetupSuite() {
s.test, _ = test.New(s.T())
s.testDb = dbt.New(s.test, dbx.WithMigrationRunner("../migrations", s.test.Logger()))
locator := assembly.NewLocator(s.testDb, s.test.Logger())
config := locator.Config(conf.Remote{
Baseline: conf.Baseline{
InitialAdminUiToken: fake.It[string](),
},
})
s.baseline = config.Baseline
_, s.api = grpct.TestServer(s.test, config.Handler)
}
func (s *BaselineSuite) TestBaselineSuccess() {
err := s.baseline.Do(s.T().Context())
s.Require().NoError(err)
err = s.baseline.Do(s.T().Context())
s.Require().NoError(err)
}
@@ -1,9 +1,8 @@
package tests_test
package tests
import (
"isp-system-service/entity"
"github.com/txix-open/isp-kit/test/dbt"
"isp-system-service/entity"
)
func InsertDomain(db *dbt.TestDb, value entity.Domain) {
@@ -16,7 +15,7 @@ func InsertDomain(db *dbt.TestDb, value entity.Domain) {
db.Must().ExecNamed(q, value)
}
func InsertAppGroup(db *dbt.TestDb, value entity.AppGroup) {
func InsertApplicationGroup(db *dbt.TestDb, value entity.ApplicationGroup) {
q := `
INSERT INTO application_group
(id, name, description, domain_id, created_at, updated_at)
@@ -31,7 +30,7 @@ func InsertApplication(db *dbt.TestDb, value entity.Application) {
INSERT INTO application
(id, name, description, application_group_id, created_at, updated_at)
VALUES
(:id, :name, :description, :application_group_id, :created_at, :updated_at)
(:id, :name, :description, :service_id, :created_at, :updated_at)
`
db.Must().ExecNamed(q, value)
}
+57 -73
View File
@@ -1,51 +1,60 @@
package tests_test
package tests
import (
"net/http"
"context"
"github.com/txix-open/isp-kit/dbx/migration"
"testing"
"time"
"github.com/txix-open/isp-kit/dbx"
"isp-system-service/assembly"
"isp-system-service/conf"
"isp-system-service/domain"
"isp-system-service/entity"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/grpct"
"isp-system-service/assembly"
"isp-system-service/conf"
"isp-system-service/domain"
"isp-system-service/entity"
"isp-system-service/migrations"
)
func TestSecureSuite(t *testing.T) {
t.Parallel()
suite.Run(t, &SecureSuite{})
}
type SecureSuite struct {
suite.Suite
test *test.Test
testDb *dbt.TestDb
api *client.Client
test *test.Test
require *require.Assertions
testDb *dbt.TestDb
api *client.Client
}
func (s *SecureSuite) SetupSuite() {
s.test, _ = test.New(s.T())
s.test, s.require = test.New(s.T())
s.testDb = dbt.New(s.test, dbx.WithMigrationRunner("../migrations", s.test.Logger()))
s.testDb = dbt.New(s.test)
migrations.Initialize.SetParams("../migrations", s.testDb.Schema())
db, err := s.testDb.DB()
s.require.NoError(err)
logger := s.test.Logger()
err = migration.NewRunner(migration.DialectPostgreSQL, "../migrations", logger).Run(context.Background(), db.DB.DB)
s.require.NoError(err)
locator := assembly.NewLocator(s.testDb, s.test.Logger())
config := locator.Config(conf.Remote{})
_, s.api = grpct.TestServer(s.test, config.Handler)
handler := locator.Handler(conf.Remote{})
_, s.api = grpct.TestServer(s.test, handler)
createdTime := time.Now().UTC()
InsertDomain(s.testDb, entity.Domain{
Id: 3, Name: "test_domain", SystemId: 1, CreatedAt: createdTime, UpdatedAt: createdTime,
})
InsertAppGroup(s.testDb, entity.AppGroup{
InsertApplicationGroup(s.testDb, entity.ApplicationGroup{
Id: 5, Name: "test_application_group", DomainId: 3, CreatedAt: createdTime, UpdatedAt: createdTime,
})
InsertApplication(s.testDb, entity.Application{
@@ -64,17 +73,16 @@ func (s *SecureSuite) TestAuthenticate_Success() {
Token: "test_token_success",
}).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().Equal(domain.AuthenticateResponse{
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthenticateResponse{
Authenticated: true,
ErrorReason: "",
AuthData: &domain.AuthData{
AppName: "test_application",
SystemId: 1,
DomainId: 3,
ServiceId: 5,
ApplicationId: 7,
SystemId: 1,
DomainId: 3,
ApplicationGroupId: 5,
ApplicationId: 7,
},
}, result)
}
@@ -86,9 +94,9 @@ func (s *SecureSuite) TestAuthenticate_NotFound() {
Token: "test_token_not_found",
}).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().Equal(domain.AuthenticateResponse{
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthenticateResponse{
Authenticated: false,
ErrorReason: domain.ErrTokenNotFound.Error(),
AuthData: nil,
@@ -106,17 +114,16 @@ func (s *SecureSuite) TestAuthenticate_NotExpired() {
Token: "test_token_not_expired",
}).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().Equal(domain.AuthenticateResponse{
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthenticateResponse{
Authenticated: true,
ErrorReason: "",
AuthData: &domain.AuthData{
AppName: "test_application",
SystemId: 1,
DomainId: 3,
ServiceId: 5,
ApplicationId: 7,
SystemId: 1,
DomainId: 3,
ApplicationGroupId: 5,
ApplicationId: 7,
},
}, result)
}
@@ -132,9 +139,9 @@ func (s *SecureSuite) TestAuthenticate_Expired() {
Token: "test_token_expired",
}).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().Equal(domain.AuthenticateResponse{
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthenticateResponse{
Authenticated: false,
ErrorReason: domain.ErrTokenExpired.Error(),
AuthData: nil,
@@ -155,9 +162,9 @@ func (s *SecureSuite) TestAuthorize_Success_True() {
Endpoint: "endpoint/available",
}).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().Equal(domain.AuthorizeResponse{
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthorizeResponse{
Authorized: true,
}, result)
}
@@ -176,9 +183,9 @@ func (s *SecureSuite) TestAuthorize_Success_False() {
Endpoint: "endpoint/not_available",
}).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().Equal(domain.AuthorizeResponse{
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthorizeResponse{
Authorized: false,
}, result)
}
@@ -191,32 +198,9 @@ func (s *SecureSuite) TestAuthorize_NotFound() {
Endpoint: "endpoint/not_found",
}).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().Equal(domain.AuthorizeResponse{
Do(context.Background())
s.require.NoError(err)
s.require.Equal(domain.AuthorizeResponse{
Authorized: false,
}, result)
}
func (s *SecureSuite) TestAuthorize_WithHttpMethod_Success_True() {
InsertAccessList(s.testDb, entity.AccessList{
AppId: 7,
HttpMethod: http.MethodGet,
Method: "endpoint/available_http",
Value: true,
})
result := domain.AuthorizeResponse{}
err := s.api.Invoke("system/secure/authorize").
JsonRequestBody(domain.AuthorizeRequest{
ApplicationId: 7,
HttpMethod: http.MethodGet,
Endpoint: "endpoint/available_http",
}).
JsonResponseBody(&result).
Do(s.T().Context())
s.Require().NoError(err)
s.Require().Equal(domain.AuthorizeResponse{
Authorized: true,
}, result)
}
+7 -31
View File
@@ -2,12 +2,10 @@ package transaction
import (
"context"
"isp-system-service/service/baseline"
"isp-system-service/repository"
"isp-system-service/service"
"github.com/txix-open/isp-kit/db"
"isp-system-service/repository"
"isp-system-service/service"
)
type Manager struct {
@@ -24,7 +22,7 @@ type accessListSetOneTx struct {
repository.AccessList
}
func (m Manager) AccessListSetOneTx(ctx context.Context, msgTx func(ctx context.Context, tx service.AccessListSetOneTx) error) error {
func (m Manager) AccessListSetOneTx(ctx context.Context, msgTx func(ctx context.Context, tx service.IAccessListSetOneTx) error) error {
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
accessListRepository := repository.NewAccessList(tx)
return msgTx(ctx, accessListSetOneTx{
@@ -37,7 +35,7 @@ type accessListSetListTx struct {
repository.AccessList
}
func (m Manager) AccessListSetListTx(ctx context.Context, msgTx func(ctx context.Context, tx service.AccessListSetListTx) error) error {
func (m Manager) AccessListSetListTx(ctx context.Context, msgTx func(ctx context.Context, tx service.IAccessListSetListTx) error) error {
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
accessListRep := repository.NewAccessList(tx)
return msgTx(ctx, accessListSetListTx{
@@ -50,7 +48,7 @@ type applicationDeleteTx struct {
repository.Application
}
func (m Manager) ApplicationDeleteTx(ctx context.Context, msgTx func(ctx context.Context, tx service.ApplicationDeleteTx) error) error {
func (m Manager) ApplicationDeleteTx(ctx context.Context, msgTx func(ctx context.Context, tx service.IApplicationDeleteTx) error) error {
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
applicationRep := repository.NewApplication(tx)
return msgTx(ctx, applicationDeleteTx{
@@ -63,7 +61,7 @@ type tokenCreateTx struct {
repository.Token
}
func (m Manager) TokenCreateTx(ctx context.Context, msgTx func(ctx context.Context, tx service.TokenCreateTx) error) error {
func (m Manager) TokenCreateTx(ctx context.Context, msgTx func(ctx context.Context, tx service.ITokenCreateTx) error) error {
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
tokenRep := repository.NewToken(tx)
return msgTx(ctx, tokenCreateTx{
@@ -76,7 +74,7 @@ type tokenRevokeTx struct {
repository.Token
}
func (m Manager) TokenRevokeTx(ctx context.Context, msgTx func(ctx context.Context, tx service.TokenRevokeTx) error) error {
func (m Manager) TokenRevokeTx(ctx context.Context, msgTx func(ctx context.Context, tx service.ITokenRevokeTx) error) error {
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
tokenRep := repository.NewToken(tx)
return msgTx(ctx, tokenRevokeTx{
@@ -84,25 +82,3 @@ func (m Manager) TokenRevokeTx(ctx context.Context, msgTx func(ctx context.Conte
})
})
}
type baselineTx struct {
repository.Locker
repository.Domain
repository.AppGroup
repository.Application
repository.AccessList
repository.Token
}
func (m Manager) BaselineTx(ctx context.Context, txTx func(ctx context.Context, tx baseline.Transaction) error) error {
return m.db.RunInTransaction(ctx, func(ctx context.Context, tx *db.Tx) error {
return txTx(ctx, baselineTx{
Locker: repository.NewLocker(tx),
Domain: repository.NewDomain(tx),
AppGroup: repository.NewAppGroup(tx),
Application: repository.NewApplication(tx),
AccessList: repository.NewAccessList(tx),
Token: repository.NewToken(tx),
})
})
}