Compare commits
340 Commits
submitter-
...
int
| Author | SHA1 | Date | |
|---|---|---|---|
|
49bee944d8
|
|||
|
f5d41ab672
|
|||
|
2578a74ddb
|
|||
| 45a58145ed | |||
|
a4cefd263d
|
|||
| 1b18649cb6 | |||
|
bdfd1a0b23
|
|||
|
859004f264
|
|||
|
89ef254b72
|
|||
|
36f9e2db5f
|
|||
|
ce4e37dc64
|
|||
|
f417111bcf
|
|||
|
1826a51ebd
|
|||
| 76903656c2 | |||
|
3e353b2ec6
|
|||
|
749ea7e57d
|
|||
|
03ec0b0183
|
|||
|
cc93776c25
|
|||
|
a8ad9f7de0
|
|||
|
d5d794703b
|
|||
|
70bbba6003
|
|||
|
39ba12edd9
|
|||
|
1cfdb3668a
|
|||
| 740e6368b1 | |||
|
746ac8e8a7
|
|||
|
bdfe16ed39
|
|||
|
3c21d8948a
|
|||
|
eaa8f704ea
|
|||
|
d50ae0e664
|
|||
|
f95d8b1665
|
|||
|
524c56b6b5
|
|||
|
e05f69ef7d
|
|||
|
a45fbb370c
|
|||
|
27a646c006
|
|||
|
dde6f3ebdb
|
|||
|
3d08b144b1
|
|||
|
63b701eb72
|
|||
| 07e08af5ed | |||
| 391a0fe6f9 | |||
| 0e06d00c21 | |||
|
cd0bfbaeb2
|
|||
|
70cb80ab9b
|
|||
|
6d0af22485
|
|||
|
c08fdddf36
|
|||
|
727b823fef
|
|||
| efefaa5e62 | |||
| c6ce9b8f82 | |||
| ca008f8fcf | |||
| e9affea859 | |||
| a31a92f131 | |||
|
a5187be8a6
|
|||
| 825b2aa91a | |||
| 6f9cd952d4 | |||
|
abb3cf3076
|
|||
|
40b0af0063
|
|||
| 976adf2b66 | |||
| 53cc4b9e9e | |||
|
51f62f039b
|
|||
|
42cc783887
|
|||
| ed7109270f | |||
| abd233ce65 | |||
| 215c39000b | |||
| c4d97b6537 | |||
| 0834400c05 | |||
| 463d14d2b5 | |||
| 6a52166901 | |||
| d7c2ad3dde | |||
| f54bf1dc34 | |||
| 644c04c133 | |||
| 8006e3efbc | |||
| b60d2b6186 | |||
| 8f2a0b53e4 | |||
| 70dd8502f4 | |||
| 5b977289e7 | |||
| 7b3af95f3d | |||
|
4d78a9b2c5
|
|||
|
ec59a83379
|
|||
| 54bf3f55a0 | |||
| 14f404ffe3 | |||
|
0e1d2fe50a
|
|||
|
ada8c322da
|
|||
|
84d2bfef20
|
|||
| 170e7c64b6 | |||
| b443866dd6 | |||
|
ebe37ad6a2
|
|||
|
131dad7ae0
|
|||
| 127402fa77 | |||
|
40f83a4e30
|
|||
|
b6d4ce4f80
|
|||
| 07391a84cb | |||
|
|
3f848a35c8 | ||
| e5e2387502 | |||
|
90d13d28ae
|
|||
| 513b9722b1 | |||
|
3da8e414e6
|
|||
|
2acc30e18c
|
|||
|
a990ed458c
|
|||
|
4055ef550e
|
|||
|
555844e6ee
|
|||
|
80f30d20fa
|
|||
|
489a8c9c10
|
|||
|
534598ba70
|
|||
|
fdc0240698
|
|||
|
b0829bc1fc
|
|||
|
845f8e69d9
|
|||
|
0d8937e896
|
|||
| 2927afd848 | |||
| 8f6c543f81 | |||
|
7c95f8ddd0
|
|||
|
24964407bd
|
|||
|
|
8d5bd9e523 | ||
|
|
e1fc637619 | ||
|
|
762ee874a0 | ||
| a1c84ff225 | |||
|
cea6242dd7
|
|||
| fefe116611 | |||
|
0ada77421f
|
|||
|
fa2d611534
|
|||
| 81539a606c | |||
| 32095296c2 | |||
|
8ea5ee2d41
|
|||
|
954dbaeac6
|
|||
| 5b7efa2426 | |||
|
|
740e3c8932 | ||
|
4f31f8c75a
|
|||
|
d39a8c0208
|
|||
|
636282b993
|
|||
|
e3667fec0c
|
|||
|
0dff464561
|
|||
|
e30fb5f916
|
|||
|
9dd7156f38
|
|||
|
fc9aae4235
|
|||
|
a11a0d2fd5
|
|||
|
9dad1a6b4d
|
|||
|
a95e6b7a9a
|
|||
|
|
4c1aef9113 | ||
|
|
c98d170423 | ||
|
6d14047f57
|
|||
|
41663624d3
|
|||
|
49b9b41085
|
|||
|
3614018794
|
|||
|
872b98aa74
|
|||
|
d5c8477869
|
|||
|
b600ca582b
|
|||
|
adbcbed9ac
|
|||
|
8f8d685f71
|
|||
|
a669de3c0b
|
|||
|
649b941d5f
|
|||
|
1b4456f30a
|
|||
|
d34a5c7091
|
|||
|
2f36877cb6
|
|||
|
3a124b8190
|
|||
|
6cc6da4879
|
|||
|
123b0c9a81
|
|||
|
54b0abbbf3
|
|||
|
1b0384da11
|
|||
|
e0cebfd80e
|
|||
|
5ba52ecb57
|
|||
|
9e42050a65
|
|||
|
c817bfc8c8
|
|||
|
8f97ca6690
|
|||
|
f220cb62bc
|
|||
|
f090fd7d68
|
|||
|
404e1281ff
|
|||
|
e4f710c83f
|
|||
|
a942c81ea8
|
|||
|
109b24061a
|
|||
|
ddef30984f
|
|||
|
9331f37d70
|
|||
|
c4f910c1f0
|
|||
|
343a4011dd
|
|||
|
c63997d161
|
|||
|
ea58fcedc9
|
|||
|
50e3fb283c
|
|||
|
aa513a7973
|
|||
|
eff9097456
|
|||
|
668c5fef51
|
|||
|
57db5f738e
|
|||
|
3789755a19
|
|||
|
ee6c37ab9d
|
|||
|
12bfbfb0a0
|
|||
|
c57a53692d
|
|||
|
ccf07c5931
|
|||
|
6efab4f411
|
|||
|
34d1db02a5
|
|||
|
d86ed0cdf5
|
|||
|
d19763349e
|
|||
|
5846e92924
|
|||
|
34b8d7475d
|
|||
|
a5daa2df4a
|
|||
|
1b73af9fe2
|
|||
|
8433030562
|
|||
|
8372665fd3
|
|||
|
d24b342738
|
|||
|
796f31aadf
|
|||
|
44f8736838
|
|||
|
b7e5d82c13
|
|||
|
169007f16e
|
|||
|
2519c9faa1
|
|||
|
1ff6bdbd4c
|
|||
|
d1ca9bdab9
|
|||
| c76ff3b687 | |||
| a42501d254 | |||
| f915c51ba4 | |||
| ff9da333eb | |||
| 1dabd216aa | |||
| cc7e890580 | |||
| 99d1b38535 | |||
| 12ca1b7dab | |||
|
fa1b44f172
|
|||
|
03519e9337
|
|||
|
60b6d30379
|
|||
|
19b8f7b7a2
|
|||
|
4f586c6176
|
|||
|
d1a70509b7
|
|||
|
95bfb87c6e
|
|||
|
de0cf37918
|
|||
|
f1fd826c62
|
|||
|
1380a00872
|
|||
|
174a210f81
|
|||
|
67a03f394f
|
|||
|
6eebe404d5
|
|||
|
1d409218a5
|
|||
|
e2c72c90c7
|
|||
|
7334e88b55
|
|||
|
b93c813dec
|
|||
|
926a90329b
|
|||
|
18abbd92ce
|
|||
|
c923a8a076
|
|||
|
d6da6f003e
|
|||
|
0dc7aec395
|
|||
|
c85cb63639
|
|||
|
6c865e8841
|
|||
|
99a082afb5
|
|||
|
434cd295f5
|
|||
|
bfc2a2cbca
|
|||
|
c24db2c3a0
|
|||
|
68f2311658
|
|||
|
163412a253
|
|||
|
044033cabf
|
|||
|
219a15f656
|
|||
|
383bc783a4
|
|||
|
24a5baae77
|
|||
|
4ba3b5cd01
|
|||
|
f610fc1c0f
|
|||
|
e67d679901
|
|||
|
3c3d09c4a7
|
|||
|
d02e3776f3
|
|||
|
77222c84db
|
|||
|
412f34817c
|
|||
|
cac288d73b
|
|||
|
29e414d6e7
|
|||
|
c9ba2e3e6e
|
|||
|
0666685a49
|
|||
|
ff9237e453
|
|||
|
9b5f7e0b0c
|
|||
|
e28c7e8149
|
|||
|
220ea84e22
|
|||
|
7648f407c5
|
|||
|
e0266c5d24
|
|||
|
9ab2e23fa9
|
|||
|
6b2f5e29e7
|
|||
|
d42e89fcb4
|
|||
|
7e881e6ac5
|
|||
|
2d57b945f2
|
|||
|
005e99424e
|
|||
|
a330b1c43b
|
|||
|
d2662eb833
|
|||
|
3ba599114d
|
|||
| d53f61fb5b | |||
|
5d259e20f2
|
|||
|
21b6903943
|
|||
|
14c7979310
|
|||
|
e376e02dc1
|
|||
|
4e7ee9dc5a
|
|||
|
ceaec14242
|
|||
|
9372caa157
|
|||
|
f73c274367
|
|||
|
c50a28443e
|
|||
|
c7150f1e23
|
|||
|
f16a817da2
|
|||
|
e858d252ab
|
|||
|
66e0d22ccd
|
|||
|
986ecfc7ad
|
|||
|
66890ccd44
|
|||
| ec15c1f2e5 | |||
|
8be9475ee5
|
|||
|
0cb2bec6e0
|
|||
| cf1906acaa | |||
|
7e93807298
|
|||
|
ee5b3331b4
|
|||
|
29c0acf3b2
|
|||
|
a844c4e90a
|
|||
|
5ed15a6847
|
|||
|
1ff1cae709
|
|||
|
|
c6ebe5a360 | ||
|
15dd6b4178
|
|||
|
ca1676db00
|
|||
|
56681f8862
|
|||
|
fe2c20bd72
|
|||
|
027a55661b
|
|||
|
a3d644f572
|
|||
|
d0634fc141
|
|||
| 719ef95b6d | |||
| c9041168e5 | |||
| 1e012af52e | |||
| 54b4cf2d13 | |||
|
|
91ac3a5e36 | ||
|
|
fc5519e744 | ||
| 170e194ac9 | |||
|
|
739c9354a6 | ||
| 73f559f049 | |||
|
|
3f377f4605 | ||
|
|
edc1ed5459 | ||
|
c9212a5ec8
|
|||
|
|
adaa088efe | ||
|
e85e3f130f
|
|||
| 0462788c53 | |||
| 2c31a9585b | |||
| 3699ce5cbb | |||
| 8776936e96 | |||
| e466af7d27 | |||
| abed5c6227 | |||
| a639b81988 | |||
| 5aa27c08a5 | |||
| 577ab5cdd0 | |||
| a72be13843 | |||
| d4e8edbb6e | |||
| 19c4e36990 | |||
| 56dec20189 | |||
| 34d37d8c1c | |||
| 508d41506a | |||
| 493c6d084a | |||
| 722ac5178f | |||
| df39101102 | |||
| e877ba4788 | |||
|
|
8a28d6cfcf | ||
|
e9f79241f1
|
|||
|
bfd287f3cc
|
|||
|
082c573ffb
|
68
.drone.yml
68
.drone.yml
@@ -25,6 +25,8 @@ steps:
|
||||
branch:
|
||||
- master
|
||||
- staging
|
||||
event:
|
||||
- push
|
||||
|
||||
- name: frontend
|
||||
image: plugins/docker
|
||||
@@ -44,6 +46,8 @@ steps:
|
||||
branch:
|
||||
- master
|
||||
- staging
|
||||
event:
|
||||
- push
|
||||
|
||||
- name: validator
|
||||
image: plugins/docker
|
||||
@@ -63,6 +67,8 @@ steps:
|
||||
branch:
|
||||
- master
|
||||
- staging
|
||||
event:
|
||||
- push
|
||||
|
||||
- name: deploy
|
||||
image: argoproj/argocd:latest
|
||||
@@ -84,8 +90,68 @@ steps:
|
||||
branch:
|
||||
- master
|
||||
- staging
|
||||
event:
|
||||
- push
|
||||
|
||||
# pr dry run
|
||||
- name: api-pr
|
||||
image: plugins/docker
|
||||
settings:
|
||||
registry: registry.itzana.me
|
||||
repo: registry.itzana.me/strafesnet/maptest-validator
|
||||
tags:
|
||||
- ${DRONE_BRANCH}-${DRONE_BUILD_NUMBER}
|
||||
- ${DRONE_BRANCH}
|
||||
dockerfile: Containerfile
|
||||
context: .
|
||||
dry_run: true
|
||||
when:
|
||||
event:
|
||||
- pull_request
|
||||
|
||||
- name: frontend-pr
|
||||
image: plugins/docker
|
||||
settings:
|
||||
registry: registry.itzana.me
|
||||
repo: registry.itzana.me/strafesnet/maptest-validator
|
||||
tags:
|
||||
- ${DRONE_BRANCH}-${DRONE_BUILD_NUMBER}
|
||||
- ${DRONE_BRANCH}
|
||||
dockerfile: web/Containerfile
|
||||
context: web
|
||||
dry_run: true
|
||||
when:
|
||||
event:
|
||||
- pull_request
|
||||
|
||||
- name: validator-pr
|
||||
image: plugins/docker
|
||||
settings:
|
||||
registry: registry.itzana.me
|
||||
repo: registry.itzana.me/strafesnet/maptest-validator
|
||||
tags:
|
||||
- ${DRONE_BRANCH}-${DRONE_BUILD_NUMBER}
|
||||
- ${DRONE_BRANCH}
|
||||
dockerfile: validation/Containerfile
|
||||
context: validation
|
||||
dry_run: true
|
||||
when:
|
||||
event:
|
||||
- pull_request
|
||||
|
||||
- name: build-pr
|
||||
image: alpine
|
||||
commands:
|
||||
- echo "Success!"
|
||||
depends_on:
|
||||
- api-pr
|
||||
- frontend-pr
|
||||
- validator-pr
|
||||
when:
|
||||
event:
|
||||
- pull_request
|
||||
---
|
||||
kind: signature
|
||||
hmac: 1162b329a9cad12b4c5db0ccf8b8998072b0de9279326f76a493fd0af6794095
|
||||
hmac: 11e6d7f1eb839d3798fdcb642ca5523c011bd14c1f3a0343a9c3106bab9ef142
|
||||
|
||||
...
|
||||
|
||||
923
Cargo.lock
generated
923
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,5 @@
|
||||
# Stage 1: Build
|
||||
FROM docker.io/golang:1.23 AS builder
|
||||
FROM registry.itzana.me/docker-proxy/golang:1.24 AS builder
|
||||
|
||||
# Set the working directory in the container
|
||||
WORKDIR /app
|
||||
@@ -14,7 +14,7 @@ COPY . .
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -o service ./cmd/maps-service/service.go
|
||||
|
||||
# Stage 2: Run
|
||||
FROM alpine
|
||||
FROM registry.itzana.me/docker-proxy/alpine:3.21
|
||||
|
||||
# Set up a non-root user for security
|
||||
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
|
||||
|
||||
@@ -26,10 +26,11 @@ Prerequisite: golang installed
|
||||
|
||||
Prerequisite: bun installed
|
||||
|
||||
The environment variable `API_HOST` will need to be set for the middleware.
|
||||
The environment variables `API_HOST` and `AUTH_HOST` will need to be set for the middleware.
|
||||
Example `.env` in web's root:
|
||||
```
|
||||
API_HOST="http://localhost:8082/v1/"
|
||||
API_HOST="http://localhost:8082/"
|
||||
AUTH_HOST="http://localhost:8083/"
|
||||
```
|
||||
|
||||
1. `cd web`
|
||||
|
||||
@@ -33,6 +33,8 @@ services:
|
||||
"--auth-rpc-host","authrpc:8081",
|
||||
"--data-rpc-host","dataservice:9000",
|
||||
]
|
||||
env_file:
|
||||
- ../auth-compose/strafesnet_staging.env
|
||||
depends_on:
|
||||
- authrpc
|
||||
- nats
|
||||
@@ -50,6 +52,7 @@ services:
|
||||
- "3000:3000"
|
||||
environment:
|
||||
- API_HOST=http://submissions:8082/v1
|
||||
- AUTH_HOST=http://localhost:8080/
|
||||
|
||||
validation:
|
||||
image:
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
package main
|
||||
|
||||
//go:generate go run github.com/ogen-go/ogen/cmd/ogen@latest --target pkg/api --clean openapi.yaml
|
||||
//go:generate go run github.com/ogen-go/ogen/cmd/ogen@latest --target pkg/internal --clean openapi-internal.yaml
|
||||
|
||||
4
go.mod
4
go.mod
@@ -5,7 +5,7 @@ go 1.22
|
||||
toolchain go1.23.3
|
||||
|
||||
require (
|
||||
git.itzana.me/strafesnet/go-grpc v0.0.0-20241129081229-9e166b3d11f7
|
||||
git.itzana.me/strafesnet/go-grpc v0.0.0-20250724030029-845bea991815
|
||||
git.itzana.me/strafesnet/utils v0.0.0-20220716194944-d8ca164052f9
|
||||
github.com/dchest/siphash v1.2.3
|
||||
github.com/go-faster/errors v0.7.1
|
||||
@@ -53,7 +53,7 @@ require (
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/segmentio/asm v1.2.0 // indirect
|
||||
go.uber.org/multierr v1.11.0
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap v1.27.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20240531132922-fd00a4e0eefc // indirect
|
||||
golang.org/x/net v0.25.0 // indirect
|
||||
|
||||
4
go.sum
4
go.sum
@@ -1,7 +1,7 @@
|
||||
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||
git.itzana.me/strafesnet/go-grpc v0.0.0-20241129081229-9e166b3d11f7 h1:5XzWd3ZZjSw1M60IfHuILty2vRPBYiqM0FZ+E7uHCi8=
|
||||
git.itzana.me/strafesnet/go-grpc v0.0.0-20241129081229-9e166b3d11f7/go.mod h1:X7XTRUScRkBWq8q8bplbeso105RPDlnY7J6Wy1IwBMs=
|
||||
git.itzana.me/strafesnet/go-grpc v0.0.0-20250724030029-845bea991815 h1:hkuOnehphRXUq/2z2UYgoqTq5MJj1GsWfshyc7bXda8=
|
||||
git.itzana.me/strafesnet/go-grpc v0.0.0-20250724030029-845bea991815/go.mod h1:X7XTRUScRkBWq8q8bplbeso105RPDlnY7J6Wy1IwBMs=
|
||||
git.itzana.me/strafesnet/utils v0.0.0-20220716194944-d8ca164052f9 h1:7lU6jyR7S7Rhh1dnUp7GyIRHUTBXZagw8F4n4hOyxLw=
|
||||
git.itzana.me/strafesnet/utils v0.0.0-20220716194944-d8ca164052f9/go.mod h1:uyYerSieEt4v0MJCdPLppG0LtJ4Yj035vuTetWGsxjY=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
|
||||
@@ -1,500 +0,0 @@
|
||||
openapi: 3.1.0
|
||||
info:
|
||||
title: StrafesNET Internal - OpenAPI 3.1
|
||||
description: Internal operations inaccessible from the public internet.
|
||||
version: 0.1.0
|
||||
tags:
|
||||
- name: Mapfixes
|
||||
description: Mapfix operations
|
||||
- name: Submissions
|
||||
description: Submission operations
|
||||
paths:
|
||||
/mapfixes/{MapfixID}/validated-model:
|
||||
post:
|
||||
summary: Update validated model
|
||||
operationId: updateMapfixValidatedModel
|
||||
tags:
|
||||
- Mapfixes
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/MapfixID'
|
||||
- name: ValidatedModelID
|
||||
in: query
|
||||
required: true
|
||||
schema:
|
||||
type: integer
|
||||
format: int64
|
||||
- name: ValidatedModelVersion
|
||||
in: query
|
||||
required: true
|
||||
schema:
|
||||
type: integer
|
||||
format: int64
|
||||
responses:
|
||||
"204":
|
||||
description: Successful response
|
||||
default:
|
||||
description: General Error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Error"
|
||||
/mapfixes/{MapfixID}/status/validator-validated:
|
||||
post:
|
||||
summary: (Internal endpoint) Role Validator changes status from Validating -> Validated
|
||||
operationId: actionMapfixValidated
|
||||
tags:
|
||||
- Mapfixes
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/MapfixID'
|
||||
responses:
|
||||
"204":
|
||||
description: Successful response
|
||||
default:
|
||||
description: General Error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Error"
|
||||
/mapfixes/{MapfixID}/status/validator-failed:
|
||||
post:
|
||||
summary: (Internal endpoint) Role Validator changes status from Validating -> Accepted
|
||||
operationId: actionMapfixAccepted
|
||||
tags:
|
||||
- Mapfixes
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/MapfixID'
|
||||
- name: StatusMessage
|
||||
in: query
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
minLength: 0
|
||||
maxLength: 4096
|
||||
responses:
|
||||
"204":
|
||||
description: Successful response
|
||||
default:
|
||||
description: General Error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Error"
|
||||
/mapfixes/{MapfixID}/status/validator-uploaded:
|
||||
post:
|
||||
summary: (Internal endpoint) Role Validator changes status from Uploading -> Uploaded
|
||||
operationId: actionMapfixUploaded
|
||||
tags:
|
||||
- Mapfixes
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/MapfixID'
|
||||
responses:
|
||||
"204":
|
||||
description: Successful response
|
||||
default:
|
||||
description: General Error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Error"
|
||||
/submissions/{SubmissionID}/validated-model:
|
||||
post:
|
||||
summary: Update validated model
|
||||
operationId: updateSubmissionValidatedModel
|
||||
tags:
|
||||
- Submissions
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/SubmissionID'
|
||||
- name: ValidatedModelID
|
||||
in: query
|
||||
required: true
|
||||
schema:
|
||||
type: integer
|
||||
format: int64
|
||||
- name: ValidatedModelVersion
|
||||
in: query
|
||||
required: true
|
||||
schema:
|
||||
type: integer
|
||||
format: int64
|
||||
responses:
|
||||
"204":
|
||||
description: Successful response
|
||||
default:
|
||||
description: General Error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Error"
|
||||
/submissions/{SubmissionID}/status/validator-validated:
|
||||
post:
|
||||
summary: (Internal endpoint) Role Validator changes status from Validating -> Validated
|
||||
operationId: actionSubmissionValidated
|
||||
tags:
|
||||
- Submissions
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/SubmissionID'
|
||||
responses:
|
||||
"204":
|
||||
description: Successful response
|
||||
default:
|
||||
description: General Error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Error"
|
||||
/submissions/{SubmissionID}/status/validator-failed:
|
||||
post:
|
||||
summary: (Internal endpoint) Role Validator changes status from Validating -> Accepted
|
||||
operationId: actionSubmissionAccepted
|
||||
tags:
|
||||
- Submissions
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/SubmissionID'
|
||||
- name: StatusMessage
|
||||
in: query
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
minLength: 0
|
||||
maxLength: 4096
|
||||
responses:
|
||||
"204":
|
||||
description: Successful response
|
||||
default:
|
||||
description: General Error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Error"
|
||||
/submissions/{SubmissionID}/status/validator-uploaded:
|
||||
post:
|
||||
summary: (Internal endpoint) Role Validator changes status from Uploading -> Uploaded
|
||||
operationId: actionSubmissionUploaded
|
||||
tags:
|
||||
- Submissions
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/SubmissionID'
|
||||
- name: UploadedAssetID
|
||||
in: query
|
||||
required: true
|
||||
schema:
|
||||
type: integer
|
||||
format: int64
|
||||
responses:
|
||||
"204":
|
||||
description: Successful response
|
||||
default:
|
||||
description: General Error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Error"
|
||||
/script-policy:
|
||||
get:
|
||||
summary: Get list of script policies
|
||||
operationId: listScriptPolicy
|
||||
tags:
|
||||
- ScriptPolicy
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/Page"
|
||||
- $ref: "#/components/parameters/Limit"
|
||||
- name: FromScriptHash
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
minLength: 16
|
||||
maxLength: 16
|
||||
- name: ToScriptID
|
||||
in: query
|
||||
schema:
|
||||
type: integer
|
||||
format: int64
|
||||
- name: Policy
|
||||
in: query
|
||||
schema:
|
||||
type: integer
|
||||
format: int32
|
||||
responses:
|
||||
"200":
|
||||
description: Successful response
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/components/schemas/ScriptPolicy"
|
||||
default:
|
||||
description: General Error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Error"
|
||||
post:
|
||||
summary: Create a new script policy
|
||||
operationId: createScriptPolicy
|
||||
tags:
|
||||
- ScriptPolicy
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ScriptPolicyCreate'
|
||||
responses:
|
||||
"201":
|
||||
description: Successful response
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Id"
|
||||
default:
|
||||
description: General Error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Error"
|
||||
/scripts:
|
||||
get:
|
||||
summary: Get list of scripts
|
||||
operationId: listScripts
|
||||
tags:
|
||||
- Script
|
||||
parameters:
|
||||
- $ref: "#/components/parameters/Page"
|
||||
- $ref: "#/components/parameters/Limit"
|
||||
- name: Hash
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
minLength: 16
|
||||
maxLength: 16
|
||||
- name: Name
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
maxLength: 128
|
||||
- name: Source
|
||||
in: query
|
||||
schema:
|
||||
type: string
|
||||
maxLength: 1048576
|
||||
- name: ResourceType
|
||||
in: query
|
||||
schema:
|
||||
type: integer
|
||||
format: int32
|
||||
- name: ResourceID
|
||||
in: query
|
||||
schema:
|
||||
type: integer
|
||||
format: int64
|
||||
responses:
|
||||
"200":
|
||||
description: Successful response
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: array
|
||||
items:
|
||||
$ref: "#/components/schemas/Script"
|
||||
default:
|
||||
description: General Error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Error"
|
||||
post:
|
||||
summary: Create a new script
|
||||
operationId: createScript
|
||||
tags:
|
||||
- Scripts
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ScriptCreate'
|
||||
responses:
|
||||
"201":
|
||||
description: Successful response
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Id"
|
||||
default:
|
||||
description: General Error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Error"
|
||||
/scripts/{ScriptID}:
|
||||
get:
|
||||
summary: Get the specified script by ID
|
||||
operationId: getScript
|
||||
tags:
|
||||
- Scripts
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/ScriptID'
|
||||
responses:
|
||||
"200":
|
||||
description: Successful response
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Script"
|
||||
default:
|
||||
description: General Error
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/Error"
|
||||
components:
|
||||
parameters:
|
||||
MapfixID:
|
||||
name: MapfixID
|
||||
in: path
|
||||
required: true
|
||||
description: The unique identifier for a submission.
|
||||
schema:
|
||||
type: integer
|
||||
format: int64
|
||||
SubmissionID:
|
||||
name: SubmissionID
|
||||
in: path
|
||||
required: true
|
||||
description: The unique identifier for a submission.
|
||||
schema:
|
||||
type: integer
|
||||
format: int64
|
||||
ScriptID:
|
||||
name: ScriptID
|
||||
in: path
|
||||
required: true
|
||||
description: The unique identifier for a script.
|
||||
schema:
|
||||
type: integer
|
||||
format: int64
|
||||
Page:
|
||||
name: Page
|
||||
in: query
|
||||
required: true
|
||||
schema:
|
||||
type: integer
|
||||
format: int32
|
||||
minimum: 1
|
||||
Limit:
|
||||
name: Limit
|
||||
in: query
|
||||
required: true
|
||||
schema:
|
||||
type: integer
|
||||
format: int32
|
||||
minimum: 1
|
||||
maximum: 100
|
||||
schemas:
|
||||
Id:
|
||||
required:
|
||||
- ID
|
||||
type: object
|
||||
properties:
|
||||
ID:
|
||||
type: integer
|
||||
format: int64
|
||||
Script:
|
||||
required:
|
||||
- ID
|
||||
- Name
|
||||
- Hash
|
||||
- Source
|
||||
- ResourceType
|
||||
- ResourceID
|
||||
type: object
|
||||
properties:
|
||||
ID:
|
||||
type: integer
|
||||
format: int64
|
||||
Name:
|
||||
type: string
|
||||
maxLength: 128
|
||||
Hash:
|
||||
type: string
|
||||
minLength: 16
|
||||
maxLength: 16
|
||||
Source:
|
||||
type: string
|
||||
maxLength: 1048576
|
||||
ResourceType:
|
||||
type: integer
|
||||
format: int32
|
||||
ResourceID:
|
||||
type: integer
|
||||
format: int64
|
||||
ScriptCreate:
|
||||
required:
|
||||
- Name
|
||||
- Source
|
||||
- ResourceType
|
||||
# - ResourceID
|
||||
type: object
|
||||
properties:
|
||||
Name:
|
||||
type: string
|
||||
maxLength: 128
|
||||
Source:
|
||||
type: string
|
||||
maxLength: 1048576
|
||||
ResourceType:
|
||||
type: integer
|
||||
format: int32
|
||||
ResourceID:
|
||||
type: integer
|
||||
format: int64
|
||||
ScriptPolicy:
|
||||
required:
|
||||
- ID
|
||||
- FromScriptHash
|
||||
- ToScriptID
|
||||
- Policy
|
||||
type: object
|
||||
properties:
|
||||
ID:
|
||||
type: integer
|
||||
format: int64
|
||||
FromScriptHash:
|
||||
type: string
|
||||
minLength: 16
|
||||
maxLength: 16
|
||||
ToScriptID:
|
||||
type: integer
|
||||
format: int64
|
||||
Policy:
|
||||
type: integer
|
||||
format: int32
|
||||
ScriptPolicyCreate:
|
||||
required:
|
||||
- FromScriptID
|
||||
- ToScriptID
|
||||
- Policy
|
||||
type: object
|
||||
properties:
|
||||
FromScriptID:
|
||||
type: integer
|
||||
format: int64
|
||||
ToScriptID:
|
||||
type: integer
|
||||
format: int64
|
||||
Policy:
|
||||
type: integer
|
||||
format: int32
|
||||
Error:
|
||||
description: Represents error object
|
||||
type: object
|
||||
properties:
|
||||
code:
|
||||
type: integer
|
||||
format: int64
|
||||
message:
|
||||
type: string
|
||||
required:
|
||||
- code
|
||||
- message
|
||||
884
openapi.yaml
884
openapi.yaml
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -6,46 +6,60 @@ package api
|
||||
type OperationName = string
|
||||
|
||||
const (
|
||||
ActionMapfixAcceptedOperation OperationName = "ActionMapfixAccepted"
|
||||
ActionMapfixRejectOperation OperationName = "ActionMapfixReject"
|
||||
ActionMapfixRequestChangesOperation OperationName = "ActionMapfixRequestChanges"
|
||||
ActionMapfixRetryValidateOperation OperationName = "ActionMapfixRetryValidate"
|
||||
ActionMapfixRevokeOperation OperationName = "ActionMapfixRevoke"
|
||||
ActionMapfixSubmitOperation OperationName = "ActionMapfixSubmit"
|
||||
ActionMapfixTriggerUploadOperation OperationName = "ActionMapfixTriggerUpload"
|
||||
ActionMapfixTriggerValidateOperation OperationName = "ActionMapfixTriggerValidate"
|
||||
ActionMapfixValidatedOperation OperationName = "ActionMapfixValidated"
|
||||
ActionSubmissionAcceptedOperation OperationName = "ActionSubmissionAccepted"
|
||||
ActionSubmissionRejectOperation OperationName = "ActionSubmissionReject"
|
||||
ActionSubmissionRequestChangesOperation OperationName = "ActionSubmissionRequestChanges"
|
||||
ActionSubmissionRetryValidateOperation OperationName = "ActionSubmissionRetryValidate"
|
||||
ActionSubmissionRevokeOperation OperationName = "ActionSubmissionRevoke"
|
||||
ActionSubmissionSubmitOperation OperationName = "ActionSubmissionSubmit"
|
||||
ActionSubmissionTriggerUploadOperation OperationName = "ActionSubmissionTriggerUpload"
|
||||
ActionSubmissionTriggerValidateOperation OperationName = "ActionSubmissionTriggerValidate"
|
||||
ActionSubmissionValidatedOperation OperationName = "ActionSubmissionValidated"
|
||||
CreateMapfixOperation OperationName = "CreateMapfix"
|
||||
CreateScriptOperation OperationName = "CreateScript"
|
||||
CreateScriptPolicyOperation OperationName = "CreateScriptPolicy"
|
||||
CreateSubmissionOperation OperationName = "CreateSubmission"
|
||||
DeleteScriptOperation OperationName = "DeleteScript"
|
||||
DeleteScriptPolicyOperation OperationName = "DeleteScriptPolicy"
|
||||
GetMapfixOperation OperationName = "GetMapfix"
|
||||
GetScriptOperation OperationName = "GetScript"
|
||||
GetScriptPolicyOperation OperationName = "GetScriptPolicy"
|
||||
GetSubmissionOperation OperationName = "GetSubmission"
|
||||
ListMapfixesOperation OperationName = "ListMapfixes"
|
||||
ListScriptPolicyOperation OperationName = "ListScriptPolicy"
|
||||
ListScriptsOperation OperationName = "ListScripts"
|
||||
ListSubmissionsOperation OperationName = "ListSubmissions"
|
||||
ReleaseSubmissionsOperation OperationName = "ReleaseSubmissions"
|
||||
SessionRolesOperation OperationName = "SessionRoles"
|
||||
SessionUserOperation OperationName = "SessionUser"
|
||||
SessionValidateOperation OperationName = "SessionValidate"
|
||||
SetMapfixCompletedOperation OperationName = "SetMapfixCompleted"
|
||||
SetSubmissionCompletedOperation OperationName = "SetSubmissionCompleted"
|
||||
UpdateMapfixModelOperation OperationName = "UpdateMapfixModel"
|
||||
UpdateScriptOperation OperationName = "UpdateScript"
|
||||
UpdateScriptPolicyOperation OperationName = "UpdateScriptPolicy"
|
||||
UpdateSubmissionModelOperation OperationName = "UpdateSubmissionModel"
|
||||
ActionMapfixAcceptedOperation OperationName = "ActionMapfixAccepted"
|
||||
ActionMapfixRejectOperation OperationName = "ActionMapfixReject"
|
||||
ActionMapfixRequestChangesOperation OperationName = "ActionMapfixRequestChanges"
|
||||
ActionMapfixResetSubmittingOperation OperationName = "ActionMapfixResetSubmitting"
|
||||
ActionMapfixRetryValidateOperation OperationName = "ActionMapfixRetryValidate"
|
||||
ActionMapfixRevokeOperation OperationName = "ActionMapfixRevoke"
|
||||
ActionMapfixTriggerSubmitOperation OperationName = "ActionMapfixTriggerSubmit"
|
||||
ActionMapfixTriggerSubmitUncheckedOperation OperationName = "ActionMapfixTriggerSubmitUnchecked"
|
||||
ActionMapfixTriggerUploadOperation OperationName = "ActionMapfixTriggerUpload"
|
||||
ActionMapfixTriggerValidateOperation OperationName = "ActionMapfixTriggerValidate"
|
||||
ActionMapfixValidatedOperation OperationName = "ActionMapfixValidated"
|
||||
ActionSubmissionAcceptedOperation OperationName = "ActionSubmissionAccepted"
|
||||
ActionSubmissionRejectOperation OperationName = "ActionSubmissionReject"
|
||||
ActionSubmissionRequestChangesOperation OperationName = "ActionSubmissionRequestChanges"
|
||||
ActionSubmissionResetSubmittingOperation OperationName = "ActionSubmissionResetSubmitting"
|
||||
ActionSubmissionRetryValidateOperation OperationName = "ActionSubmissionRetryValidate"
|
||||
ActionSubmissionRevokeOperation OperationName = "ActionSubmissionRevoke"
|
||||
ActionSubmissionTriggerSubmitOperation OperationName = "ActionSubmissionTriggerSubmit"
|
||||
ActionSubmissionTriggerSubmitUncheckedOperation OperationName = "ActionSubmissionTriggerSubmitUnchecked"
|
||||
ActionSubmissionTriggerUploadOperation OperationName = "ActionSubmissionTriggerUpload"
|
||||
ActionSubmissionTriggerValidateOperation OperationName = "ActionSubmissionTriggerValidate"
|
||||
ActionSubmissionValidatedOperation OperationName = "ActionSubmissionValidated"
|
||||
CreateMapfixOperation OperationName = "CreateMapfix"
|
||||
CreateMapfixAuditCommentOperation OperationName = "CreateMapfixAuditComment"
|
||||
CreateScriptOperation OperationName = "CreateScript"
|
||||
CreateScriptPolicyOperation OperationName = "CreateScriptPolicy"
|
||||
CreateSubmissionOperation OperationName = "CreateSubmission"
|
||||
CreateSubmissionAdminOperation OperationName = "CreateSubmissionAdmin"
|
||||
CreateSubmissionAuditCommentOperation OperationName = "CreateSubmissionAuditComment"
|
||||
DeleteScriptOperation OperationName = "DeleteScript"
|
||||
DeleteScriptPolicyOperation OperationName = "DeleteScriptPolicy"
|
||||
DownloadMapAssetOperation OperationName = "DownloadMapAsset"
|
||||
GetMapOperation OperationName = "GetMap"
|
||||
GetMapfixOperation OperationName = "GetMapfix"
|
||||
GetOperationOperation OperationName = "GetOperation"
|
||||
GetScriptOperation OperationName = "GetScript"
|
||||
GetScriptPolicyOperation OperationName = "GetScriptPolicy"
|
||||
GetSubmissionOperation OperationName = "GetSubmission"
|
||||
ListMapfixAuditEventsOperation OperationName = "ListMapfixAuditEvents"
|
||||
ListMapfixesOperation OperationName = "ListMapfixes"
|
||||
ListMapsOperation OperationName = "ListMaps"
|
||||
ListScriptPolicyOperation OperationName = "ListScriptPolicy"
|
||||
ListScriptsOperation OperationName = "ListScripts"
|
||||
ListSubmissionAuditEventsOperation OperationName = "ListSubmissionAuditEvents"
|
||||
ListSubmissionsOperation OperationName = "ListSubmissions"
|
||||
MigrateMapsOperation OperationName = "MigrateMaps"
|
||||
ReleaseSubmissionsOperation OperationName = "ReleaseSubmissions"
|
||||
SessionRolesOperation OperationName = "SessionRoles"
|
||||
SessionUserOperation OperationName = "SessionUser"
|
||||
SessionValidateOperation OperationName = "SessionValidate"
|
||||
SetMapfixCompletedOperation OperationName = "SetMapfixCompleted"
|
||||
SetSubmissionCompletedOperation OperationName = "SetSubmissionCompleted"
|
||||
UpdateMapfixModelOperation OperationName = "UpdateMapfixModel"
|
||||
UpdateScriptOperation OperationName = "UpdateScript"
|
||||
UpdateScriptPolicyOperation OperationName = "UpdateScriptPolicy"
|
||||
UpdateSubmissionModelOperation OperationName = "UpdateSubmissionModel"
|
||||
)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -3,20 +3,20 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"go.uber.org/multierr"
|
||||
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
)
|
||||
|
||||
func (s *Server) decodeCreateMapfixRequest(r *http.Request) (
|
||||
req *MapfixCreate,
|
||||
req *MapfixTriggerCreate,
|
||||
close func() error,
|
||||
rerr error,
|
||||
) {
|
||||
@@ -26,13 +26,13 @@ func (s *Server) decodeCreateMapfixRequest(r *http.Request) (
|
||||
// Close in reverse order, to match defer behavior.
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
c := closers[i]
|
||||
merr = multierr.Append(merr, c())
|
||||
merr = errors.Join(merr, c())
|
||||
}
|
||||
return merr
|
||||
}
|
||||
defer func() {
|
||||
if rerr != nil {
|
||||
rerr = multierr.Append(rerr, close())
|
||||
rerr = errors.Join(rerr, close())
|
||||
}
|
||||
}()
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
@@ -55,7 +55,7 @@ func (s *Server) decodeCreateMapfixRequest(r *http.Request) (
|
||||
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var request MapfixCreate
|
||||
var request MapfixTriggerCreate
|
||||
if err := func() error {
|
||||
if err := request.Decode(d); err != nil {
|
||||
return err
|
||||
@@ -86,6 +86,40 @@ func (s *Server) decodeCreateMapfixRequest(r *http.Request) (
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) decodeCreateMapfixAuditCommentRequest(r *http.Request) (
|
||||
req CreateMapfixAuditCommentReq,
|
||||
close func() error,
|
||||
rerr error,
|
||||
) {
|
||||
var closers []func() error
|
||||
close = func() error {
|
||||
var merr error
|
||||
// Close in reverse order, to match defer behavior.
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
c := closers[i]
|
||||
merr = errors.Join(merr, c())
|
||||
}
|
||||
return merr
|
||||
}
|
||||
defer func() {
|
||||
if rerr != nil {
|
||||
rerr = errors.Join(rerr, close())
|
||||
}
|
||||
}()
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return req, close, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "text/plain":
|
||||
reader := r.Body
|
||||
request := CreateMapfixAuditCommentReq{Data: reader}
|
||||
return request, close, nil
|
||||
default:
|
||||
return req, close, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) decodeCreateScriptRequest(r *http.Request) (
|
||||
req *ScriptCreate,
|
||||
close func() error,
|
||||
@@ -97,13 +131,13 @@ func (s *Server) decodeCreateScriptRequest(r *http.Request) (
|
||||
// Close in reverse order, to match defer behavior.
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
c := closers[i]
|
||||
merr = multierr.Append(merr, c())
|
||||
merr = errors.Join(merr, c())
|
||||
}
|
||||
return merr
|
||||
}
|
||||
defer func() {
|
||||
if rerr != nil {
|
||||
rerr = multierr.Append(rerr, close())
|
||||
rerr = errors.Join(rerr, close())
|
||||
}
|
||||
}()
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
@@ -168,13 +202,13 @@ func (s *Server) decodeCreateScriptPolicyRequest(r *http.Request) (
|
||||
// Close in reverse order, to match defer behavior.
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
c := closers[i]
|
||||
merr = multierr.Append(merr, c())
|
||||
merr = errors.Join(merr, c())
|
||||
}
|
||||
return merr
|
||||
}
|
||||
defer func() {
|
||||
if rerr != nil {
|
||||
rerr = multierr.Append(rerr, close())
|
||||
rerr = errors.Join(rerr, close())
|
||||
}
|
||||
}()
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
@@ -214,6 +248,14 @@ func (s *Server) decodeCreateScriptPolicyRequest(r *http.Request) (
|
||||
}
|
||||
return req, close, err
|
||||
}
|
||||
if err := func() error {
|
||||
if err := request.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return req, close, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &request, close, nil
|
||||
default:
|
||||
return req, close, validate.InvalidContentType(ct)
|
||||
@@ -221,7 +263,7 @@ func (s *Server) decodeCreateScriptPolicyRequest(r *http.Request) (
|
||||
}
|
||||
|
||||
func (s *Server) decodeCreateSubmissionRequest(r *http.Request) (
|
||||
req *SubmissionCreate,
|
||||
req *SubmissionTriggerCreate,
|
||||
close func() error,
|
||||
rerr error,
|
||||
) {
|
||||
@@ -231,13 +273,13 @@ func (s *Server) decodeCreateSubmissionRequest(r *http.Request) (
|
||||
// Close in reverse order, to match defer behavior.
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
c := closers[i]
|
||||
merr = multierr.Append(merr, c())
|
||||
merr = errors.Join(merr, c())
|
||||
}
|
||||
return merr
|
||||
}
|
||||
defer func() {
|
||||
if rerr != nil {
|
||||
rerr = multierr.Append(rerr, close())
|
||||
rerr = errors.Join(rerr, close())
|
||||
}
|
||||
}()
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
@@ -260,7 +302,7 @@ func (s *Server) decodeCreateSubmissionRequest(r *http.Request) (
|
||||
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var request SubmissionCreate
|
||||
var request SubmissionTriggerCreate
|
||||
if err := func() error {
|
||||
if err := request.Decode(d); err != nil {
|
||||
return err
|
||||
@@ -291,6 +333,111 @@ func (s *Server) decodeCreateSubmissionRequest(r *http.Request) (
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) decodeCreateSubmissionAdminRequest(r *http.Request) (
|
||||
req *SubmissionTriggerCreate,
|
||||
close func() error,
|
||||
rerr error,
|
||||
) {
|
||||
var closers []func() error
|
||||
close = func() error {
|
||||
var merr error
|
||||
// Close in reverse order, to match defer behavior.
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
c := closers[i]
|
||||
merr = errors.Join(merr, c())
|
||||
}
|
||||
return merr
|
||||
}
|
||||
defer func() {
|
||||
if rerr != nil {
|
||||
rerr = errors.Join(rerr, close())
|
||||
}
|
||||
}()
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return req, close, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
if r.ContentLength == 0 {
|
||||
return req, close, validate.ErrBodyRequired
|
||||
}
|
||||
buf, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return req, close, err
|
||||
}
|
||||
|
||||
if len(buf) == 0 {
|
||||
return req, close, validate.ErrBodyRequired
|
||||
}
|
||||
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var request SubmissionTriggerCreate
|
||||
if err := func() error {
|
||||
if err := request.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return req, close, err
|
||||
}
|
||||
if err := func() error {
|
||||
if err := request.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return req, close, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &request, close, nil
|
||||
default:
|
||||
return req, close, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) decodeCreateSubmissionAuditCommentRequest(r *http.Request) (
|
||||
req CreateSubmissionAuditCommentReq,
|
||||
close func() error,
|
||||
rerr error,
|
||||
) {
|
||||
var closers []func() error
|
||||
close = func() error {
|
||||
var merr error
|
||||
// Close in reverse order, to match defer behavior.
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
c := closers[i]
|
||||
merr = errors.Join(merr, c())
|
||||
}
|
||||
return merr
|
||||
}
|
||||
defer func() {
|
||||
if rerr != nil {
|
||||
rerr = errors.Join(rerr, close())
|
||||
}
|
||||
}()
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return req, close, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "text/plain":
|
||||
reader := r.Body
|
||||
request := CreateSubmissionAuditCommentReq{Data: reader}
|
||||
return request, close, nil
|
||||
default:
|
||||
return req, close, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) decodeReleaseSubmissionsRequest(r *http.Request) (
|
||||
req []ReleaseInfo,
|
||||
close func() error,
|
||||
@@ -302,13 +449,13 @@ func (s *Server) decodeReleaseSubmissionsRequest(r *http.Request) (
|
||||
// Close in reverse order, to match defer behavior.
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
c := closers[i]
|
||||
merr = multierr.Append(merr, c())
|
||||
merr = errors.Join(merr, c())
|
||||
}
|
||||
return merr
|
||||
}
|
||||
defer func() {
|
||||
if rerr != nil {
|
||||
rerr = multierr.Append(rerr, close())
|
||||
rerr = errors.Join(rerr, close())
|
||||
}
|
||||
}()
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
@@ -368,6 +515,23 @@ func (s *Server) decodeReleaseSubmissionsRequest(r *http.Request) (
|
||||
}).ValidateLength(len(request)); err != nil {
|
||||
return errors.Wrap(err, "array")
|
||||
}
|
||||
var failures []validate.FieldError
|
||||
for i, elem := range request {
|
||||
if err := func() error {
|
||||
if err := elem.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: fmt.Sprintf("[%d]", i),
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return req, close, errors.Wrap(err, "validate")
|
||||
@@ -389,13 +553,13 @@ func (s *Server) decodeUpdateScriptRequest(r *http.Request) (
|
||||
// Close in reverse order, to match defer behavior.
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
c := closers[i]
|
||||
merr = multierr.Append(merr, c())
|
||||
merr = errors.Join(merr, c())
|
||||
}
|
||||
return merr
|
||||
}
|
||||
defer func() {
|
||||
if rerr != nil {
|
||||
rerr = multierr.Append(rerr, close())
|
||||
rerr = errors.Join(rerr, close())
|
||||
}
|
||||
}()
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
@@ -460,13 +624,13 @@ func (s *Server) decodeUpdateScriptPolicyRequest(r *http.Request) (
|
||||
// Close in reverse order, to match defer behavior.
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
c := closers[i]
|
||||
merr = multierr.Append(merr, c())
|
||||
merr = errors.Join(merr, c())
|
||||
}
|
||||
return merr
|
||||
}
|
||||
defer func() {
|
||||
if rerr != nil {
|
||||
rerr = multierr.Append(rerr, close())
|
||||
rerr = errors.Join(rerr, close())
|
||||
}
|
||||
}()
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
@@ -506,6 +670,14 @@ func (s *Server) decodeUpdateScriptPolicyRequest(r *http.Request) (
|
||||
}
|
||||
return req, close, err
|
||||
}
|
||||
if err := func() error {
|
||||
if err := request.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return req, close, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &request, close, nil
|
||||
default:
|
||||
return req, close, validate.InvalidContentType(ct)
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
)
|
||||
|
||||
func encodeCreateMapfixRequest(
|
||||
req *MapfixCreate,
|
||||
req *MapfixTriggerCreate,
|
||||
r *http.Request,
|
||||
) error {
|
||||
const contentType = "application/json"
|
||||
@@ -25,6 +25,16 @@ func encodeCreateMapfixRequest(
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeCreateMapfixAuditCommentRequest(
|
||||
req CreateMapfixAuditCommentReq,
|
||||
r *http.Request,
|
||||
) error {
|
||||
const contentType = "text/plain"
|
||||
body := req
|
||||
ht.SetBody(r, body, contentType)
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeCreateScriptRequest(
|
||||
req *ScriptCreate,
|
||||
r *http.Request,
|
||||
@@ -54,7 +64,7 @@ func encodeCreateScriptPolicyRequest(
|
||||
}
|
||||
|
||||
func encodeCreateSubmissionRequest(
|
||||
req *SubmissionCreate,
|
||||
req *SubmissionTriggerCreate,
|
||||
r *http.Request,
|
||||
) error {
|
||||
const contentType = "application/json"
|
||||
@@ -67,6 +77,30 @@ func encodeCreateSubmissionRequest(
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeCreateSubmissionAdminRequest(
|
||||
req *SubmissionTriggerCreate,
|
||||
r *http.Request,
|
||||
) error {
|
||||
const contentType = "application/json"
|
||||
e := new(jx.Encoder)
|
||||
{
|
||||
req.Encode(e)
|
||||
}
|
||||
encoded := e.Bytes()
|
||||
ht.SetBody(r, bytes.NewReader(encoded), contentType)
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeCreateSubmissionAuditCommentRequest(
|
||||
req CreateSubmissionAuditCommentReq,
|
||||
r *http.Request,
|
||||
) error {
|
||||
const contentType = "text/plain"
|
||||
body := req
|
||||
ht.SetBody(r, body, contentType)
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeReleaseSubmissionsRequest(
|
||||
req []ReleaseInfo,
|
||||
r *http.Request,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -3,6 +3,7 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
@@ -34,6 +35,13 @@ func encodeActionMapfixRequestChangesResponse(response *ActionMapfixRequestChang
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeActionMapfixResetSubmittingResponse(response *ActionMapfixResetSubmittingNoContent, w http.ResponseWriter, span trace.Span) error {
|
||||
w.WriteHeader(204)
|
||||
span.SetStatus(codes.Ok, http.StatusText(204))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeActionMapfixRetryValidateResponse(response *ActionMapfixRetryValidateNoContent, w http.ResponseWriter, span trace.Span) error {
|
||||
w.WriteHeader(204)
|
||||
span.SetStatus(codes.Ok, http.StatusText(204))
|
||||
@@ -48,7 +56,14 @@ func encodeActionMapfixRevokeResponse(response *ActionMapfixRevokeNoContent, w h
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeActionMapfixSubmitResponse(response *ActionMapfixSubmitNoContent, w http.ResponseWriter, span trace.Span) error {
|
||||
func encodeActionMapfixTriggerSubmitResponse(response *ActionMapfixTriggerSubmitNoContent, w http.ResponseWriter, span trace.Span) error {
|
||||
w.WriteHeader(204)
|
||||
span.SetStatus(codes.Ok, http.StatusText(204))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeActionMapfixTriggerSubmitUncheckedResponse(response *ActionMapfixTriggerSubmitUncheckedNoContent, w http.ResponseWriter, span trace.Span) error {
|
||||
w.WriteHeader(204)
|
||||
span.SetStatus(codes.Ok, http.StatusText(204))
|
||||
|
||||
@@ -97,6 +112,13 @@ func encodeActionSubmissionRequestChangesResponse(response *ActionSubmissionRequ
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeActionSubmissionResetSubmittingResponse(response *ActionSubmissionResetSubmittingNoContent, w http.ResponseWriter, span trace.Span) error {
|
||||
w.WriteHeader(204)
|
||||
span.SetStatus(codes.Ok, http.StatusText(204))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeActionSubmissionRetryValidateResponse(response *ActionSubmissionRetryValidateNoContent, w http.ResponseWriter, span trace.Span) error {
|
||||
w.WriteHeader(204)
|
||||
span.SetStatus(codes.Ok, http.StatusText(204))
|
||||
@@ -111,7 +133,14 @@ func encodeActionSubmissionRevokeResponse(response *ActionSubmissionRevokeNoCont
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeActionSubmissionSubmitResponse(response *ActionSubmissionSubmitNoContent, w http.ResponseWriter, span trace.Span) error {
|
||||
func encodeActionSubmissionTriggerSubmitResponse(response *ActionSubmissionTriggerSubmitNoContent, w http.ResponseWriter, span trace.Span) error {
|
||||
w.WriteHeader(204)
|
||||
span.SetStatus(codes.Ok, http.StatusText(204))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeActionSubmissionTriggerSubmitUncheckedResponse(response *ActionSubmissionTriggerSubmitUncheckedNoContent, w http.ResponseWriter, span trace.Span) error {
|
||||
w.WriteHeader(204)
|
||||
span.SetStatus(codes.Ok, http.StatusText(204))
|
||||
|
||||
@@ -139,7 +168,7 @@ func encodeActionSubmissionValidatedResponse(response *ActionSubmissionValidated
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeCreateMapfixResponse(response *ID, w http.ResponseWriter, span trace.Span) error {
|
||||
func encodeCreateMapfixResponse(response *OperationID, w http.ResponseWriter, span trace.Span) error {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(201)
|
||||
span.SetStatus(codes.Ok, http.StatusText(201))
|
||||
@@ -153,7 +182,14 @@ func encodeCreateMapfixResponse(response *ID, w http.ResponseWriter, span trace.
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeCreateScriptResponse(response *ID, w http.ResponseWriter, span trace.Span) error {
|
||||
func encodeCreateMapfixAuditCommentResponse(response *CreateMapfixAuditCommentNoContent, w http.ResponseWriter, span trace.Span) error {
|
||||
w.WriteHeader(204)
|
||||
span.SetStatus(codes.Ok, http.StatusText(204))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeCreateScriptResponse(response *ScriptID, w http.ResponseWriter, span trace.Span) error {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(201)
|
||||
span.SetStatus(codes.Ok, http.StatusText(201))
|
||||
@@ -167,7 +203,7 @@ func encodeCreateScriptResponse(response *ID, w http.ResponseWriter, span trace.
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeCreateScriptPolicyResponse(response *ID, w http.ResponseWriter, span trace.Span) error {
|
||||
func encodeCreateScriptPolicyResponse(response *ScriptPolicyID, w http.ResponseWriter, span trace.Span) error {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(201)
|
||||
span.SetStatus(codes.Ok, http.StatusText(201))
|
||||
@@ -181,7 +217,7 @@ func encodeCreateScriptPolicyResponse(response *ID, w http.ResponseWriter, span
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeCreateSubmissionResponse(response *ID, w http.ResponseWriter, span trace.Span) error {
|
||||
func encodeCreateSubmissionResponse(response *OperationID, w http.ResponseWriter, span trace.Span) error {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(201)
|
||||
span.SetStatus(codes.Ok, http.StatusText(201))
|
||||
@@ -195,6 +231,27 @@ func encodeCreateSubmissionResponse(response *ID, w http.ResponseWriter, span tr
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeCreateSubmissionAdminResponse(response *OperationID, w http.ResponseWriter, span trace.Span) error {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(201)
|
||||
span.SetStatus(codes.Ok, http.StatusText(201))
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeCreateSubmissionAuditCommentResponse(response *CreateSubmissionAuditCommentNoContent, w http.ResponseWriter, span trace.Span) error {
|
||||
w.WriteHeader(204)
|
||||
span.SetStatus(codes.Ok, http.StatusText(204))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeDeleteScriptResponse(response *DeleteScriptNoContent, w http.ResponseWriter, span trace.Span) error {
|
||||
w.WriteHeader(204)
|
||||
span.SetStatus(codes.Ok, http.StatusText(204))
|
||||
@@ -209,6 +266,36 @@ func encodeDeleteScriptPolicyResponse(response *DeleteScriptPolicyNoContent, w h
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeDownloadMapAssetResponse(response DownloadMapAssetOK, w http.ResponseWriter, span trace.Span) error {
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
w.WriteHeader(200)
|
||||
span.SetStatus(codes.Ok, http.StatusText(200))
|
||||
|
||||
writer := w
|
||||
if closer, ok := response.Data.(io.Closer); ok {
|
||||
defer closer.Close()
|
||||
}
|
||||
if _, err := io.Copy(writer, response); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeGetMapResponse(response *Map, w http.ResponseWriter, span trace.Span) error {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(200)
|
||||
span.SetStatus(codes.Ok, http.StatusText(200))
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeGetMapfixResponse(response *Mapfix, w http.ResponseWriter, span trace.Span) error {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(200)
|
||||
@@ -223,6 +310,20 @@ func encodeGetMapfixResponse(response *Mapfix, w http.ResponseWriter, span trace
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeGetOperationResponse(response *Operation, w http.ResponseWriter, span trace.Span) error {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(200)
|
||||
span.SetStatus(codes.Ok, http.StatusText(200))
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeGetScriptResponse(response *Script, w http.ResponseWriter, span trace.Span) error {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(200)
|
||||
@@ -265,7 +366,39 @@ func encodeGetSubmissionResponse(response *Submission, w http.ResponseWriter, sp
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeListMapfixesResponse(response []Mapfix, w http.ResponseWriter, span trace.Span) error {
|
||||
func encodeListMapfixAuditEventsResponse(response []AuditEvent, w http.ResponseWriter, span trace.Span) error {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(200)
|
||||
span.SetStatus(codes.Ok, http.StatusText(200))
|
||||
|
||||
e := new(jx.Encoder)
|
||||
e.ArrStart()
|
||||
for _, elem := range response {
|
||||
elem.Encode(e)
|
||||
}
|
||||
e.ArrEnd()
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeListMapfixesResponse(response *Mapfixes, w http.ResponseWriter, span trace.Span) error {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(200)
|
||||
span.SetStatus(codes.Ok, http.StatusText(200))
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeListMapsResponse(response []Map, w http.ResponseWriter, span trace.Span) error {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(200)
|
||||
span.SetStatus(codes.Ok, http.StatusText(200))
|
||||
@@ -319,7 +452,7 @@ func encodeListScriptsResponse(response []Script, w http.ResponseWriter, span tr
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeListSubmissionsResponse(response []Submission, w http.ResponseWriter, span trace.Span) error {
|
||||
func encodeListSubmissionAuditEventsResponse(response []AuditEvent, w http.ResponseWriter, span trace.Span) error {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(200)
|
||||
span.SetStatus(codes.Ok, http.StatusText(200))
|
||||
@@ -337,6 +470,27 @@ func encodeListSubmissionsResponse(response []Submission, w http.ResponseWriter,
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeListSubmissionsResponse(response *Submissions, w http.ResponseWriter, span trace.Span) error {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(200)
|
||||
span.SetStatus(codes.Ok, http.StatusText(200))
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeMigrateMapsResponse(response *MigrateMapsOK, w http.ResponseWriter, span trace.Span) error {
|
||||
w.WriteHeader(200)
|
||||
span.SetStatus(codes.Ok, http.StatusText(200))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeReleaseSubmissionsResponse(response *ReleaseSubmissionsCreated, w http.ResponseWriter, span trace.Span) error {
|
||||
w.WriteHeader(201)
|
||||
span.SetStatus(codes.Ok, http.StatusText(201))
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -4,7 +4,10 @@ package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/go-faster/jx"
|
||||
)
|
||||
|
||||
func (s *ErrorStatusCode) Error() string {
|
||||
@@ -20,14 +23,20 @@ type ActionMapfixRejectNoContent struct{}
|
||||
// ActionMapfixRequestChangesNoContent is response for ActionMapfixRequestChanges operation.
|
||||
type ActionMapfixRequestChangesNoContent struct{}
|
||||
|
||||
// ActionMapfixResetSubmittingNoContent is response for ActionMapfixResetSubmitting operation.
|
||||
type ActionMapfixResetSubmittingNoContent struct{}
|
||||
|
||||
// ActionMapfixRetryValidateNoContent is response for ActionMapfixRetryValidate operation.
|
||||
type ActionMapfixRetryValidateNoContent struct{}
|
||||
|
||||
// ActionMapfixRevokeNoContent is response for ActionMapfixRevoke operation.
|
||||
type ActionMapfixRevokeNoContent struct{}
|
||||
|
||||
// ActionMapfixSubmitNoContent is response for ActionMapfixSubmit operation.
|
||||
type ActionMapfixSubmitNoContent struct{}
|
||||
// ActionMapfixTriggerSubmitNoContent is response for ActionMapfixTriggerSubmit operation.
|
||||
type ActionMapfixTriggerSubmitNoContent struct{}
|
||||
|
||||
// ActionMapfixTriggerSubmitUncheckedNoContent is response for ActionMapfixTriggerSubmitUnchecked operation.
|
||||
type ActionMapfixTriggerSubmitUncheckedNoContent struct{}
|
||||
|
||||
// ActionMapfixTriggerUploadNoContent is response for ActionMapfixTriggerUpload operation.
|
||||
type ActionMapfixTriggerUploadNoContent struct{}
|
||||
@@ -47,14 +56,20 @@ type ActionSubmissionRejectNoContent struct{}
|
||||
// ActionSubmissionRequestChangesNoContent is response for ActionSubmissionRequestChanges operation.
|
||||
type ActionSubmissionRequestChangesNoContent struct{}
|
||||
|
||||
// ActionSubmissionResetSubmittingNoContent is response for ActionSubmissionResetSubmitting operation.
|
||||
type ActionSubmissionResetSubmittingNoContent struct{}
|
||||
|
||||
// ActionSubmissionRetryValidateNoContent is response for ActionSubmissionRetryValidate operation.
|
||||
type ActionSubmissionRetryValidateNoContent struct{}
|
||||
|
||||
// ActionSubmissionRevokeNoContent is response for ActionSubmissionRevoke operation.
|
||||
type ActionSubmissionRevokeNoContent struct{}
|
||||
|
||||
// ActionSubmissionSubmitNoContent is response for ActionSubmissionSubmit operation.
|
||||
type ActionSubmissionSubmitNoContent struct{}
|
||||
// ActionSubmissionTriggerSubmitNoContent is response for ActionSubmissionTriggerSubmit operation.
|
||||
type ActionSubmissionTriggerSubmitNoContent struct{}
|
||||
|
||||
// ActionSubmissionTriggerSubmitUncheckedNoContent is response for ActionSubmissionTriggerSubmitUnchecked operation.
|
||||
type ActionSubmissionTriggerSubmitUncheckedNoContent struct{}
|
||||
|
||||
// ActionSubmissionTriggerUploadNoContent is response for ActionSubmissionTriggerUpload operation.
|
||||
type ActionSubmissionTriggerUploadNoContent struct{}
|
||||
@@ -65,8 +80,115 @@ type ActionSubmissionTriggerValidateNoContent struct{}
|
||||
// ActionSubmissionValidatedNoContent is response for ActionSubmissionValidated operation.
|
||||
type ActionSubmissionValidatedNoContent struct{}
|
||||
|
||||
// Ref: #/components/schemas/AuditEvent
|
||||
type AuditEvent struct {
|
||||
ID int64 `json:"ID"`
|
||||
Date int64 `json:"Date"`
|
||||
User int64 `json:"User"`
|
||||
Username string `json:"Username"`
|
||||
// Is this a submission or is it a mapfix.
|
||||
ResourceType int32 `json:"ResourceType"`
|
||||
ResourceID int64 `json:"ResourceID"`
|
||||
EventType int32 `json:"EventType"`
|
||||
// Arbitrary event data.
|
||||
EventData AuditEventEventData `json:"EventData"`
|
||||
}
|
||||
|
||||
// GetID returns the value of ID.
|
||||
func (s *AuditEvent) GetID() int64 {
|
||||
return s.ID
|
||||
}
|
||||
|
||||
// GetDate returns the value of Date.
|
||||
func (s *AuditEvent) GetDate() int64 {
|
||||
return s.Date
|
||||
}
|
||||
|
||||
// GetUser returns the value of User.
|
||||
func (s *AuditEvent) GetUser() int64 {
|
||||
return s.User
|
||||
}
|
||||
|
||||
// GetUsername returns the value of Username.
|
||||
func (s *AuditEvent) GetUsername() string {
|
||||
return s.Username
|
||||
}
|
||||
|
||||
// GetResourceType returns the value of ResourceType.
|
||||
func (s *AuditEvent) GetResourceType() int32 {
|
||||
return s.ResourceType
|
||||
}
|
||||
|
||||
// GetResourceID returns the value of ResourceID.
|
||||
func (s *AuditEvent) GetResourceID() int64 {
|
||||
return s.ResourceID
|
||||
}
|
||||
|
||||
// GetEventType returns the value of EventType.
|
||||
func (s *AuditEvent) GetEventType() int32 {
|
||||
return s.EventType
|
||||
}
|
||||
|
||||
// GetEventData returns the value of EventData.
|
||||
func (s *AuditEvent) GetEventData() AuditEventEventData {
|
||||
return s.EventData
|
||||
}
|
||||
|
||||
// SetID sets the value of ID.
|
||||
func (s *AuditEvent) SetID(val int64) {
|
||||
s.ID = val
|
||||
}
|
||||
|
||||
// SetDate sets the value of Date.
|
||||
func (s *AuditEvent) SetDate(val int64) {
|
||||
s.Date = val
|
||||
}
|
||||
|
||||
// SetUser sets the value of User.
|
||||
func (s *AuditEvent) SetUser(val int64) {
|
||||
s.User = val
|
||||
}
|
||||
|
||||
// SetUsername sets the value of Username.
|
||||
func (s *AuditEvent) SetUsername(val string) {
|
||||
s.Username = val
|
||||
}
|
||||
|
||||
// SetResourceType sets the value of ResourceType.
|
||||
func (s *AuditEvent) SetResourceType(val int32) {
|
||||
s.ResourceType = val
|
||||
}
|
||||
|
||||
// SetResourceID sets the value of ResourceID.
|
||||
func (s *AuditEvent) SetResourceID(val int64) {
|
||||
s.ResourceID = val
|
||||
}
|
||||
|
||||
// SetEventType sets the value of EventType.
|
||||
func (s *AuditEvent) SetEventType(val int32) {
|
||||
s.EventType = val
|
||||
}
|
||||
|
||||
// SetEventData sets the value of EventData.
|
||||
func (s *AuditEvent) SetEventData(val AuditEventEventData) {
|
||||
s.EventData = val
|
||||
}
|
||||
|
||||
// Arbitrary event data.
|
||||
type AuditEventEventData map[string]jx.Raw
|
||||
|
||||
func (s *AuditEventEventData) init() AuditEventEventData {
|
||||
m := *s
|
||||
if m == nil {
|
||||
m = map[string]jx.Raw{}
|
||||
*s = m
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
type CookieAuth struct {
|
||||
APIKey string
|
||||
Roles []string
|
||||
}
|
||||
|
||||
// GetAPIKey returns the value of APIKey.
|
||||
@@ -74,17 +196,75 @@ func (s *CookieAuth) GetAPIKey() string {
|
||||
return s.APIKey
|
||||
}
|
||||
|
||||
// GetRoles returns the value of Roles.
|
||||
func (s *CookieAuth) GetRoles() []string {
|
||||
return s.Roles
|
||||
}
|
||||
|
||||
// SetAPIKey sets the value of APIKey.
|
||||
func (s *CookieAuth) SetAPIKey(val string) {
|
||||
s.APIKey = val
|
||||
}
|
||||
|
||||
// SetRoles sets the value of Roles.
|
||||
func (s *CookieAuth) SetRoles(val []string) {
|
||||
s.Roles = val
|
||||
}
|
||||
|
||||
// CreateMapfixAuditCommentNoContent is response for CreateMapfixAuditComment operation.
|
||||
type CreateMapfixAuditCommentNoContent struct{}
|
||||
|
||||
type CreateMapfixAuditCommentReq struct {
|
||||
Data io.Reader
|
||||
}
|
||||
|
||||
// Read reads data from the Data reader.
|
||||
//
|
||||
// Kept to satisfy the io.Reader interface.
|
||||
func (s CreateMapfixAuditCommentReq) Read(p []byte) (n int, err error) {
|
||||
if s.Data == nil {
|
||||
return 0, io.EOF
|
||||
}
|
||||
return s.Data.Read(p)
|
||||
}
|
||||
|
||||
// CreateSubmissionAuditCommentNoContent is response for CreateSubmissionAuditComment operation.
|
||||
type CreateSubmissionAuditCommentNoContent struct{}
|
||||
|
||||
type CreateSubmissionAuditCommentReq struct {
|
||||
Data io.Reader
|
||||
}
|
||||
|
||||
// Read reads data from the Data reader.
|
||||
//
|
||||
// Kept to satisfy the io.Reader interface.
|
||||
func (s CreateSubmissionAuditCommentReq) Read(p []byte) (n int, err error) {
|
||||
if s.Data == nil {
|
||||
return 0, io.EOF
|
||||
}
|
||||
return s.Data.Read(p)
|
||||
}
|
||||
|
||||
// DeleteScriptNoContent is response for DeleteScript operation.
|
||||
type DeleteScriptNoContent struct{}
|
||||
|
||||
// DeleteScriptPolicyNoContent is response for DeleteScriptPolicy operation.
|
||||
type DeleteScriptPolicyNoContent struct{}
|
||||
|
||||
type DownloadMapAssetOK struct {
|
||||
Data io.Reader
|
||||
}
|
||||
|
||||
// Read reads data from the Data reader.
|
||||
//
|
||||
// Kept to satisfy the io.Reader interface.
|
||||
func (s DownloadMapAssetOK) Read(p []byte) (n int, err error) {
|
||||
if s.Data == nil {
|
||||
return 0, io.EOF
|
||||
}
|
||||
return s.Data.Read(p)
|
||||
}
|
||||
|
||||
// Represents error object.
|
||||
// Ref: #/components/schemas/Error
|
||||
type Error struct {
|
||||
@@ -138,21 +318,65 @@ func (s *ErrorStatusCode) SetResponse(val Error) {
|
||||
s.Response = val
|
||||
}
|
||||
|
||||
// Ref: #/components/schemas/Id
|
||||
type ID struct {
|
||||
ID int64 `json:"ID"`
|
||||
// Ref: #/components/schemas/Map
|
||||
type Map struct {
|
||||
ID int64 `json:"ID"`
|
||||
DisplayName string `json:"DisplayName"`
|
||||
Creator string `json:"Creator"`
|
||||
GameID int32 `json:"GameID"`
|
||||
Date int64 `json:"Date"`
|
||||
}
|
||||
|
||||
// GetID returns the value of ID.
|
||||
func (s *ID) GetID() int64 {
|
||||
func (s *Map) GetID() int64 {
|
||||
return s.ID
|
||||
}
|
||||
|
||||
// GetDisplayName returns the value of DisplayName.
|
||||
func (s *Map) GetDisplayName() string {
|
||||
return s.DisplayName
|
||||
}
|
||||
|
||||
// GetCreator returns the value of Creator.
|
||||
func (s *Map) GetCreator() string {
|
||||
return s.Creator
|
||||
}
|
||||
|
||||
// GetGameID returns the value of GameID.
|
||||
func (s *Map) GetGameID() int32 {
|
||||
return s.GameID
|
||||
}
|
||||
|
||||
// GetDate returns the value of Date.
|
||||
func (s *Map) GetDate() int64 {
|
||||
return s.Date
|
||||
}
|
||||
|
||||
// SetID sets the value of ID.
|
||||
func (s *ID) SetID(val int64) {
|
||||
func (s *Map) SetID(val int64) {
|
||||
s.ID = val
|
||||
}
|
||||
|
||||
// SetDisplayName sets the value of DisplayName.
|
||||
func (s *Map) SetDisplayName(val string) {
|
||||
s.DisplayName = val
|
||||
}
|
||||
|
||||
// SetCreator sets the value of Creator.
|
||||
func (s *Map) SetCreator(val string) {
|
||||
s.Creator = val
|
||||
}
|
||||
|
||||
// SetGameID sets the value of GameID.
|
||||
func (s *Map) SetGameID(val int32) {
|
||||
s.GameID = val
|
||||
}
|
||||
|
||||
// SetDate sets the value of Date.
|
||||
func (s *Map) SetDate(val int64) {
|
||||
s.Date = val
|
||||
}
|
||||
|
||||
// Ref: #/components/schemas/Mapfix
|
||||
type Mapfix struct {
|
||||
ID int64 `json:"ID"`
|
||||
@@ -167,7 +391,7 @@ type Mapfix struct {
|
||||
Completed bool `json:"Completed"`
|
||||
TargetAssetID int64 `json:"TargetAssetID"`
|
||||
StatusID int32 `json:"StatusID"`
|
||||
StatusMessage string `json:"StatusMessage"`
|
||||
Description string `json:"Description"`
|
||||
}
|
||||
|
||||
// GetID returns the value of ID.
|
||||
@@ -230,9 +454,9 @@ func (s *Mapfix) GetStatusID() int32 {
|
||||
return s.StatusID
|
||||
}
|
||||
|
||||
// GetStatusMessage returns the value of StatusMessage.
|
||||
func (s *Mapfix) GetStatusMessage() string {
|
||||
return s.StatusMessage
|
||||
// GetDescription returns the value of Description.
|
||||
func (s *Mapfix) GetDescription() string {
|
||||
return s.Description
|
||||
}
|
||||
|
||||
// SetID sets the value of ID.
|
||||
@@ -295,79 +519,160 @@ func (s *Mapfix) SetStatusID(val int32) {
|
||||
s.StatusID = val
|
||||
}
|
||||
|
||||
// SetStatusMessage sets the value of StatusMessage.
|
||||
func (s *Mapfix) SetStatusMessage(val string) {
|
||||
s.StatusMessage = val
|
||||
// SetDescription sets the value of Description.
|
||||
func (s *Mapfix) SetDescription(val string) {
|
||||
s.Description = val
|
||||
}
|
||||
|
||||
// Ref: #/components/schemas/MapfixCreate
|
||||
type MapfixCreate struct {
|
||||
DisplayName string `json:"DisplayName"`
|
||||
Creator string `json:"Creator"`
|
||||
GameID int32 `json:"GameID"`
|
||||
// Ref: #/components/schemas/MapfixTriggerCreate
|
||||
type MapfixTriggerCreate struct {
|
||||
AssetID int64 `json:"AssetID"`
|
||||
AssetVersion int64 `json:"AssetVersion"`
|
||||
TargetAssetID int64 `json:"TargetAssetID"`
|
||||
}
|
||||
|
||||
// GetDisplayName returns the value of DisplayName.
|
||||
func (s *MapfixCreate) GetDisplayName() string {
|
||||
return s.DisplayName
|
||||
}
|
||||
|
||||
// GetCreator returns the value of Creator.
|
||||
func (s *MapfixCreate) GetCreator() string {
|
||||
return s.Creator
|
||||
}
|
||||
|
||||
// GetGameID returns the value of GameID.
|
||||
func (s *MapfixCreate) GetGameID() int32 {
|
||||
return s.GameID
|
||||
Description string `json:"Description"`
|
||||
}
|
||||
|
||||
// GetAssetID returns the value of AssetID.
|
||||
func (s *MapfixCreate) GetAssetID() int64 {
|
||||
func (s *MapfixTriggerCreate) GetAssetID() int64 {
|
||||
return s.AssetID
|
||||
}
|
||||
|
||||
// GetAssetVersion returns the value of AssetVersion.
|
||||
func (s *MapfixCreate) GetAssetVersion() int64 {
|
||||
return s.AssetVersion
|
||||
}
|
||||
|
||||
// GetTargetAssetID returns the value of TargetAssetID.
|
||||
func (s *MapfixCreate) GetTargetAssetID() int64 {
|
||||
func (s *MapfixTriggerCreate) GetTargetAssetID() int64 {
|
||||
return s.TargetAssetID
|
||||
}
|
||||
|
||||
// SetDisplayName sets the value of DisplayName.
|
||||
func (s *MapfixCreate) SetDisplayName(val string) {
|
||||
s.DisplayName = val
|
||||
}
|
||||
|
||||
// SetCreator sets the value of Creator.
|
||||
func (s *MapfixCreate) SetCreator(val string) {
|
||||
s.Creator = val
|
||||
}
|
||||
|
||||
// SetGameID sets the value of GameID.
|
||||
func (s *MapfixCreate) SetGameID(val int32) {
|
||||
s.GameID = val
|
||||
// GetDescription returns the value of Description.
|
||||
func (s *MapfixTriggerCreate) GetDescription() string {
|
||||
return s.Description
|
||||
}
|
||||
|
||||
// SetAssetID sets the value of AssetID.
|
||||
func (s *MapfixCreate) SetAssetID(val int64) {
|
||||
func (s *MapfixTriggerCreate) SetAssetID(val int64) {
|
||||
s.AssetID = val
|
||||
}
|
||||
|
||||
// SetAssetVersion sets the value of AssetVersion.
|
||||
func (s *MapfixCreate) SetAssetVersion(val int64) {
|
||||
s.AssetVersion = val
|
||||
// SetTargetAssetID sets the value of TargetAssetID.
|
||||
func (s *MapfixTriggerCreate) SetTargetAssetID(val int64) {
|
||||
s.TargetAssetID = val
|
||||
}
|
||||
|
||||
// SetTargetAssetID sets the value of TargetAssetID.
|
||||
func (s *MapfixCreate) SetTargetAssetID(val int64) {
|
||||
s.TargetAssetID = val
|
||||
// SetDescription sets the value of Description.
|
||||
func (s *MapfixTriggerCreate) SetDescription(val string) {
|
||||
s.Description = val
|
||||
}
|
||||
|
||||
// Ref: #/components/schemas/Mapfixes
|
||||
type Mapfixes struct {
|
||||
Total int64 `json:"Total"`
|
||||
Mapfixes []Mapfix `json:"Mapfixes"`
|
||||
}
|
||||
|
||||
// GetTotal returns the value of Total.
|
||||
func (s *Mapfixes) GetTotal() int64 {
|
||||
return s.Total
|
||||
}
|
||||
|
||||
// GetMapfixes returns the value of Mapfixes.
|
||||
func (s *Mapfixes) GetMapfixes() []Mapfix {
|
||||
return s.Mapfixes
|
||||
}
|
||||
|
||||
// SetTotal sets the value of Total.
|
||||
func (s *Mapfixes) SetTotal(val int64) {
|
||||
s.Total = val
|
||||
}
|
||||
|
||||
// SetMapfixes sets the value of Mapfixes.
|
||||
func (s *Mapfixes) SetMapfixes(val []Mapfix) {
|
||||
s.Mapfixes = val
|
||||
}
|
||||
|
||||
// MigrateMapsOK is response for MigrateMaps operation.
|
||||
type MigrateMapsOK struct{}
|
||||
|
||||
// Ref: #/components/schemas/Operation
|
||||
type Operation struct {
|
||||
OperationID int32 `json:"OperationID"`
|
||||
Date int64 `json:"Date"`
|
||||
Owner int64 `json:"Owner"`
|
||||
Status int32 `json:"Status"`
|
||||
StatusMessage string `json:"StatusMessage"`
|
||||
Path string `json:"Path"`
|
||||
}
|
||||
|
||||
// GetOperationID returns the value of OperationID.
|
||||
func (s *Operation) GetOperationID() int32 {
|
||||
return s.OperationID
|
||||
}
|
||||
|
||||
// GetDate returns the value of Date.
|
||||
func (s *Operation) GetDate() int64 {
|
||||
return s.Date
|
||||
}
|
||||
|
||||
// GetOwner returns the value of Owner.
|
||||
func (s *Operation) GetOwner() int64 {
|
||||
return s.Owner
|
||||
}
|
||||
|
||||
// GetStatus returns the value of Status.
|
||||
func (s *Operation) GetStatus() int32 {
|
||||
return s.Status
|
||||
}
|
||||
|
||||
// GetStatusMessage returns the value of StatusMessage.
|
||||
func (s *Operation) GetStatusMessage() string {
|
||||
return s.StatusMessage
|
||||
}
|
||||
|
||||
// GetPath returns the value of Path.
|
||||
func (s *Operation) GetPath() string {
|
||||
return s.Path
|
||||
}
|
||||
|
||||
// SetOperationID sets the value of OperationID.
|
||||
func (s *Operation) SetOperationID(val int32) {
|
||||
s.OperationID = val
|
||||
}
|
||||
|
||||
// SetDate sets the value of Date.
|
||||
func (s *Operation) SetDate(val int64) {
|
||||
s.Date = val
|
||||
}
|
||||
|
||||
// SetOwner sets the value of Owner.
|
||||
func (s *Operation) SetOwner(val int64) {
|
||||
s.Owner = val
|
||||
}
|
||||
|
||||
// SetStatus sets the value of Status.
|
||||
func (s *Operation) SetStatus(val int32) {
|
||||
s.Status = val
|
||||
}
|
||||
|
||||
// SetStatusMessage sets the value of StatusMessage.
|
||||
func (s *Operation) SetStatusMessage(val string) {
|
||||
s.StatusMessage = val
|
||||
}
|
||||
|
||||
// SetPath sets the value of Path.
|
||||
func (s *Operation) SetPath(val string) {
|
||||
s.Path = val
|
||||
}
|
||||
|
||||
// Ref: #/components/schemas/OperationID
|
||||
type OperationID struct {
|
||||
OperationID int32 `json:"OperationID"`
|
||||
}
|
||||
|
||||
// GetOperationID returns the value of OperationID.
|
||||
func (s *OperationID) GetOperationID() int32 {
|
||||
return s.OperationID
|
||||
}
|
||||
|
||||
// SetOperationID sets the value of OperationID.
|
||||
func (s *OperationID) SetOperationID(val int32) {
|
||||
s.OperationID = val
|
||||
}
|
||||
|
||||
// NewOptInt32 returns new OptInt32 with value set to v.
|
||||
@@ -670,6 +975,21 @@ func (s *ScriptCreate) SetResourceID(val OptInt64) {
|
||||
s.ResourceID = val
|
||||
}
|
||||
|
||||
// Ref: #/components/schemas/ScriptID
|
||||
type ScriptID struct {
|
||||
ScriptID int64 `json:"ScriptID"`
|
||||
}
|
||||
|
||||
// GetScriptID returns the value of ScriptID.
|
||||
func (s *ScriptID) GetScriptID() int64 {
|
||||
return s.ScriptID
|
||||
}
|
||||
|
||||
// SetScriptID sets the value of ScriptID.
|
||||
func (s *ScriptID) SetScriptID(val int64) {
|
||||
s.ScriptID = val
|
||||
}
|
||||
|
||||
// Ref: #/components/schemas/ScriptPolicy
|
||||
type ScriptPolicy struct {
|
||||
ID int64 `json:"ID"`
|
||||
@@ -755,6 +1075,21 @@ func (s *ScriptPolicyCreate) SetPolicy(val int32) {
|
||||
s.Policy = val
|
||||
}
|
||||
|
||||
// Ref: #/components/schemas/ScriptPolicyID
|
||||
type ScriptPolicyID struct {
|
||||
ScriptPolicyID int64 `json:"ScriptPolicyID"`
|
||||
}
|
||||
|
||||
// GetScriptPolicyID returns the value of ScriptPolicyID.
|
||||
func (s *ScriptPolicyID) GetScriptPolicyID() int64 {
|
||||
return s.ScriptPolicyID
|
||||
}
|
||||
|
||||
// SetScriptPolicyID sets the value of ScriptPolicyID.
|
||||
func (s *ScriptPolicyID) SetScriptPolicyID(val int64) {
|
||||
s.ScriptPolicyID = val
|
||||
}
|
||||
|
||||
// Ref: #/components/schemas/ScriptPolicyUpdate
|
||||
type ScriptPolicyUpdate struct {
|
||||
ID int64 `json:"ID"`
|
||||
@@ -884,7 +1219,6 @@ type Submission struct {
|
||||
Completed bool `json:"Completed"`
|
||||
UploadedAssetID OptInt64 `json:"UploadedAssetID"`
|
||||
StatusID int32 `json:"StatusID"`
|
||||
StatusMessage string `json:"StatusMessage"`
|
||||
}
|
||||
|
||||
// GetID returns the value of ID.
|
||||
@@ -957,11 +1291,6 @@ func (s *Submission) GetStatusID() int32 {
|
||||
return s.StatusID
|
||||
}
|
||||
|
||||
// GetStatusMessage returns the value of StatusMessage.
|
||||
func (s *Submission) GetStatusMessage() string {
|
||||
return s.StatusMessage
|
||||
}
|
||||
|
||||
// SetID sets the value of ID.
|
||||
func (s *Submission) SetID(val int64) {
|
||||
s.ID = val
|
||||
@@ -1032,68 +1361,78 @@ func (s *Submission) SetStatusID(val int32) {
|
||||
s.StatusID = val
|
||||
}
|
||||
|
||||
// SetStatusMessage sets the value of StatusMessage.
|
||||
func (s *Submission) SetStatusMessage(val string) {
|
||||
s.StatusMessage = val
|
||||
// Ref: #/components/schemas/SubmissionTriggerCreate
|
||||
type SubmissionTriggerCreate struct {
|
||||
AssetID int64 `json:"AssetID"`
|
||||
DisplayName string `json:"DisplayName"`
|
||||
Creator string `json:"Creator"`
|
||||
GameID int32 `json:"GameID"`
|
||||
}
|
||||
|
||||
// Ref: #/components/schemas/SubmissionCreate
|
||||
type SubmissionCreate struct {
|
||||
DisplayName string `json:"DisplayName"`
|
||||
Creator string `json:"Creator"`
|
||||
GameID int32 `json:"GameID"`
|
||||
AssetID int64 `json:"AssetID"`
|
||||
AssetVersion int64 `json:"AssetVersion"`
|
||||
// GetAssetID returns the value of AssetID.
|
||||
func (s *SubmissionTriggerCreate) GetAssetID() int64 {
|
||||
return s.AssetID
|
||||
}
|
||||
|
||||
// GetDisplayName returns the value of DisplayName.
|
||||
func (s *SubmissionCreate) GetDisplayName() string {
|
||||
func (s *SubmissionTriggerCreate) GetDisplayName() string {
|
||||
return s.DisplayName
|
||||
}
|
||||
|
||||
// GetCreator returns the value of Creator.
|
||||
func (s *SubmissionCreate) GetCreator() string {
|
||||
func (s *SubmissionTriggerCreate) GetCreator() string {
|
||||
return s.Creator
|
||||
}
|
||||
|
||||
// GetGameID returns the value of GameID.
|
||||
func (s *SubmissionCreate) GetGameID() int32 {
|
||||
func (s *SubmissionTriggerCreate) GetGameID() int32 {
|
||||
return s.GameID
|
||||
}
|
||||
|
||||
// GetAssetID returns the value of AssetID.
|
||||
func (s *SubmissionCreate) GetAssetID() int64 {
|
||||
return s.AssetID
|
||||
}
|
||||
|
||||
// GetAssetVersion returns the value of AssetVersion.
|
||||
func (s *SubmissionCreate) GetAssetVersion() int64 {
|
||||
return s.AssetVersion
|
||||
// SetAssetID sets the value of AssetID.
|
||||
func (s *SubmissionTriggerCreate) SetAssetID(val int64) {
|
||||
s.AssetID = val
|
||||
}
|
||||
|
||||
// SetDisplayName sets the value of DisplayName.
|
||||
func (s *SubmissionCreate) SetDisplayName(val string) {
|
||||
func (s *SubmissionTriggerCreate) SetDisplayName(val string) {
|
||||
s.DisplayName = val
|
||||
}
|
||||
|
||||
// SetCreator sets the value of Creator.
|
||||
func (s *SubmissionCreate) SetCreator(val string) {
|
||||
func (s *SubmissionTriggerCreate) SetCreator(val string) {
|
||||
s.Creator = val
|
||||
}
|
||||
|
||||
// SetGameID sets the value of GameID.
|
||||
func (s *SubmissionCreate) SetGameID(val int32) {
|
||||
func (s *SubmissionTriggerCreate) SetGameID(val int32) {
|
||||
s.GameID = val
|
||||
}
|
||||
|
||||
// SetAssetID sets the value of AssetID.
|
||||
func (s *SubmissionCreate) SetAssetID(val int64) {
|
||||
s.AssetID = val
|
||||
// Ref: #/components/schemas/Submissions
|
||||
type Submissions struct {
|
||||
Total int64 `json:"Total"`
|
||||
Submissions []Submission `json:"Submissions"`
|
||||
}
|
||||
|
||||
// SetAssetVersion sets the value of AssetVersion.
|
||||
func (s *SubmissionCreate) SetAssetVersion(val int64) {
|
||||
s.AssetVersion = val
|
||||
// GetTotal returns the value of Total.
|
||||
func (s *Submissions) GetTotal() int64 {
|
||||
return s.Total
|
||||
}
|
||||
|
||||
// GetSubmissions returns the value of Submissions.
|
||||
func (s *Submissions) GetSubmissions() []Submission {
|
||||
return s.Submissions
|
||||
}
|
||||
|
||||
// SetTotal sets the value of Total.
|
||||
func (s *Submissions) SetTotal(val int64) {
|
||||
s.Total = val
|
||||
}
|
||||
|
||||
// SetSubmissions sets the value of Submissions.
|
||||
func (s *Submissions) SetSubmissions(val []Submission) {
|
||||
s.Submissions = val
|
||||
}
|
||||
|
||||
// UpdateMapfixModelNoContent is response for UpdateMapfixModel operation.
|
||||
|
||||
@@ -33,6 +33,53 @@ func findAuthorization(h http.Header, prefix string) (string, bool) {
|
||||
return "", false
|
||||
}
|
||||
|
||||
var operationRolesCookieAuth = map[string][]string{
|
||||
ActionMapfixAcceptedOperation: []string{},
|
||||
ActionMapfixRejectOperation: []string{},
|
||||
ActionMapfixRequestChangesOperation: []string{},
|
||||
ActionMapfixResetSubmittingOperation: []string{},
|
||||
ActionMapfixRetryValidateOperation: []string{},
|
||||
ActionMapfixRevokeOperation: []string{},
|
||||
ActionMapfixTriggerSubmitOperation: []string{},
|
||||
ActionMapfixTriggerSubmitUncheckedOperation: []string{},
|
||||
ActionMapfixTriggerUploadOperation: []string{},
|
||||
ActionMapfixTriggerValidateOperation: []string{},
|
||||
ActionMapfixValidatedOperation: []string{},
|
||||
ActionSubmissionAcceptedOperation: []string{},
|
||||
ActionSubmissionRejectOperation: []string{},
|
||||
ActionSubmissionRequestChangesOperation: []string{},
|
||||
ActionSubmissionResetSubmittingOperation: []string{},
|
||||
ActionSubmissionRetryValidateOperation: []string{},
|
||||
ActionSubmissionRevokeOperation: []string{},
|
||||
ActionSubmissionTriggerSubmitOperation: []string{},
|
||||
ActionSubmissionTriggerSubmitUncheckedOperation: []string{},
|
||||
ActionSubmissionTriggerUploadOperation: []string{},
|
||||
ActionSubmissionTriggerValidateOperation: []string{},
|
||||
ActionSubmissionValidatedOperation: []string{},
|
||||
CreateMapfixOperation: []string{},
|
||||
CreateMapfixAuditCommentOperation: []string{},
|
||||
CreateScriptOperation: []string{},
|
||||
CreateScriptPolicyOperation: []string{},
|
||||
CreateSubmissionOperation: []string{},
|
||||
CreateSubmissionAdminOperation: []string{},
|
||||
CreateSubmissionAuditCommentOperation: []string{},
|
||||
DeleteScriptOperation: []string{},
|
||||
DeleteScriptPolicyOperation: []string{},
|
||||
DownloadMapAssetOperation: []string{},
|
||||
GetOperationOperation: []string{},
|
||||
MigrateMapsOperation: []string{},
|
||||
ReleaseSubmissionsOperation: []string{},
|
||||
SessionRolesOperation: []string{},
|
||||
SessionUserOperation: []string{},
|
||||
SessionValidateOperation: []string{},
|
||||
SetMapfixCompletedOperation: []string{},
|
||||
SetSubmissionCompletedOperation: []string{},
|
||||
UpdateMapfixModelOperation: []string{},
|
||||
UpdateScriptOperation: []string{},
|
||||
UpdateScriptPolicyOperation: []string{},
|
||||
UpdateSubmissionModelOperation: []string{},
|
||||
}
|
||||
|
||||
func (s *Server) securityCookieAuth(ctx context.Context, operationName OperationName, req *http.Request) (context.Context, bool, error) {
|
||||
var t CookieAuth
|
||||
const parameterName = "session_id"
|
||||
@@ -46,6 +93,7 @@ func (s *Server) securityCookieAuth(ctx context.Context, operationName Operation
|
||||
return nil, false, errors.Wrap(err, "get cookie value")
|
||||
}
|
||||
t.APIKey = value
|
||||
t.Roles = operationRolesCookieAuth[operationName]
|
||||
rctx, err := s.sec.HandleCookieAuth(ctx, operationName, t)
|
||||
if errors.Is(err, ogenerrors.ErrSkipServerSecurity) {
|
||||
return nil, false, nil
|
||||
|
||||
@@ -26,6 +26,13 @@ type Handler interface {
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/request-changes
|
||||
ActionMapfixRequestChanges(ctx context.Context, params ActionMapfixRequestChangesParams) error
|
||||
// ActionMapfixResetSubmitting implements actionMapfixResetSubmitting operation.
|
||||
//
|
||||
// Role Submitter manually resets submitting softlock and changes status from Submitting ->
|
||||
// UnderConstruction.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/reset-submitting
|
||||
ActionMapfixResetSubmitting(ctx context.Context, params ActionMapfixResetSubmittingParams) error
|
||||
// ActionMapfixRetryValidate implements actionMapfixRetryValidate operation.
|
||||
//
|
||||
// Role Reviewer re-runs validation and changes status from Accepted -> Validating.
|
||||
@@ -38,12 +45,18 @@ type Handler interface {
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/revoke
|
||||
ActionMapfixRevoke(ctx context.Context, params ActionMapfixRevokeParams) error
|
||||
// ActionMapfixSubmit implements actionMapfixSubmit operation.
|
||||
// ActionMapfixTriggerSubmit implements actionMapfixTriggerSubmit operation.
|
||||
//
|
||||
// Role Submitter changes status from UnderConstruction|ChangesRequested -> Submitted.
|
||||
// Role Submitter changes status from UnderConstruction|ChangesRequested -> Submitting.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/submit
|
||||
ActionMapfixSubmit(ctx context.Context, params ActionMapfixSubmitParams) error
|
||||
// POST /mapfixes/{MapfixID}/status/trigger-submit
|
||||
ActionMapfixTriggerSubmit(ctx context.Context, params ActionMapfixTriggerSubmitParams) error
|
||||
// ActionMapfixTriggerSubmitUnchecked implements actionMapfixTriggerSubmitUnchecked operation.
|
||||
//
|
||||
// Role Reviewer changes status from ChangesRequested -> Submitting.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/trigger-submit-unchecked
|
||||
ActionMapfixTriggerSubmitUnchecked(ctx context.Context, params ActionMapfixTriggerSubmitUncheckedParams) error
|
||||
// ActionMapfixTriggerUpload implements actionMapfixTriggerUpload operation.
|
||||
//
|
||||
// Role Admin changes status from Validated -> Uploading.
|
||||
@@ -80,6 +93,13 @@ type Handler interface {
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/request-changes
|
||||
ActionSubmissionRequestChanges(ctx context.Context, params ActionSubmissionRequestChangesParams) error
|
||||
// ActionSubmissionResetSubmitting implements actionSubmissionResetSubmitting operation.
|
||||
//
|
||||
// Role Submitter manually resets submitting softlock and changes status from Submitting ->
|
||||
// UnderConstruction.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/reset-submitting
|
||||
ActionSubmissionResetSubmitting(ctx context.Context, params ActionSubmissionResetSubmittingParams) error
|
||||
// ActionSubmissionRetryValidate implements actionSubmissionRetryValidate operation.
|
||||
//
|
||||
// Role Reviewer re-runs validation and changes status from Accepted -> Validating.
|
||||
@@ -92,12 +112,18 @@ type Handler interface {
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/revoke
|
||||
ActionSubmissionRevoke(ctx context.Context, params ActionSubmissionRevokeParams) error
|
||||
// ActionSubmissionSubmit implements actionSubmissionSubmit operation.
|
||||
// ActionSubmissionTriggerSubmit implements actionSubmissionTriggerSubmit operation.
|
||||
//
|
||||
// Role Submitter changes status from UnderConstruction|ChangesRequested -> Submitted.
|
||||
// Role Submitter changes status from UnderConstruction|ChangesRequested -> Submitting.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/submit
|
||||
ActionSubmissionSubmit(ctx context.Context, params ActionSubmissionSubmitParams) error
|
||||
// POST /submissions/{SubmissionID}/status/trigger-submit
|
||||
ActionSubmissionTriggerSubmit(ctx context.Context, params ActionSubmissionTriggerSubmitParams) error
|
||||
// ActionSubmissionTriggerSubmitUnchecked implements actionSubmissionTriggerSubmitUnchecked operation.
|
||||
//
|
||||
// Role Reviewer changes status from ChangesRequested -> Submitting.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/trigger-submit-unchecked
|
||||
ActionSubmissionTriggerSubmitUnchecked(ctx context.Context, params ActionSubmissionTriggerSubmitUncheckedParams) error
|
||||
// ActionSubmissionTriggerUpload implements actionSubmissionTriggerUpload operation.
|
||||
//
|
||||
// Role Admin changes status from Validated -> Uploading.
|
||||
@@ -118,28 +144,46 @@ type Handler interface {
|
||||
ActionSubmissionValidated(ctx context.Context, params ActionSubmissionValidatedParams) error
|
||||
// CreateMapfix implements createMapfix operation.
|
||||
//
|
||||
// Create new mapfix.
|
||||
// Trigger the validator to create a mapfix.
|
||||
//
|
||||
// POST /mapfixes
|
||||
CreateMapfix(ctx context.Context, req *MapfixCreate) (*ID, error)
|
||||
CreateMapfix(ctx context.Context, req *MapfixTriggerCreate) (*OperationID, error)
|
||||
// CreateMapfixAuditComment implements createMapfixAuditComment operation.
|
||||
//
|
||||
// Post a comment to the audit log.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/comment
|
||||
CreateMapfixAuditComment(ctx context.Context, req CreateMapfixAuditCommentReq, params CreateMapfixAuditCommentParams) error
|
||||
// CreateScript implements createScript operation.
|
||||
//
|
||||
// Create a new script.
|
||||
//
|
||||
// POST /scripts
|
||||
CreateScript(ctx context.Context, req *ScriptCreate) (*ID, error)
|
||||
CreateScript(ctx context.Context, req *ScriptCreate) (*ScriptID, error)
|
||||
// CreateScriptPolicy implements createScriptPolicy operation.
|
||||
//
|
||||
// Create a new script policy.
|
||||
//
|
||||
// POST /script-policy
|
||||
CreateScriptPolicy(ctx context.Context, req *ScriptPolicyCreate) (*ID, error)
|
||||
CreateScriptPolicy(ctx context.Context, req *ScriptPolicyCreate) (*ScriptPolicyID, error)
|
||||
// CreateSubmission implements createSubmission operation.
|
||||
//
|
||||
// Create new submission.
|
||||
// Trigger the validator to create a new submission.
|
||||
//
|
||||
// POST /submissions
|
||||
CreateSubmission(ctx context.Context, req *SubmissionCreate) (*ID, error)
|
||||
CreateSubmission(ctx context.Context, req *SubmissionTriggerCreate) (*OperationID, error)
|
||||
// CreateSubmissionAdmin implements createSubmissionAdmin operation.
|
||||
//
|
||||
// Trigger the validator to create a new submission.
|
||||
//
|
||||
// POST /submissions-admin
|
||||
CreateSubmissionAdmin(ctx context.Context, req *SubmissionTriggerCreate) (*OperationID, error)
|
||||
// CreateSubmissionAuditComment implements createSubmissionAuditComment operation.
|
||||
//
|
||||
// Post a comment to the audit log.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/comment
|
||||
CreateSubmissionAuditComment(ctx context.Context, req CreateSubmissionAuditCommentReq, params CreateSubmissionAuditCommentParams) error
|
||||
// DeleteScript implements deleteScript operation.
|
||||
//
|
||||
// Delete the specified script by ID.
|
||||
@@ -152,12 +196,30 @@ type Handler interface {
|
||||
//
|
||||
// DELETE /script-policy/{ScriptPolicyID}
|
||||
DeleteScriptPolicy(ctx context.Context, params DeleteScriptPolicyParams) error
|
||||
// DownloadMapAsset implements downloadMapAsset operation.
|
||||
//
|
||||
// Download the map asset.
|
||||
//
|
||||
// GET /maps/{MapID}/download
|
||||
DownloadMapAsset(ctx context.Context, params DownloadMapAssetParams) (DownloadMapAssetOK, error)
|
||||
// GetMap implements getMap operation.
|
||||
//
|
||||
// Retrieve map with ID.
|
||||
//
|
||||
// GET /maps/{MapID}
|
||||
GetMap(ctx context.Context, params GetMapParams) (*Map, error)
|
||||
// GetMapfix implements getMapfix operation.
|
||||
//
|
||||
// Retrieve map with ID.
|
||||
//
|
||||
// GET /mapfixes/{MapfixID}
|
||||
GetMapfix(ctx context.Context, params GetMapfixParams) (*Mapfix, error)
|
||||
// GetOperation implements getOperation operation.
|
||||
//
|
||||
// Retrieve operation with ID.
|
||||
//
|
||||
// GET /operations/{OperationID}
|
||||
GetOperation(ctx context.Context, params GetOperationParams) (*Operation, error)
|
||||
// GetScript implements getScript operation.
|
||||
//
|
||||
// Get the specified script by ID.
|
||||
@@ -176,12 +238,24 @@ type Handler interface {
|
||||
//
|
||||
// GET /submissions/{SubmissionID}
|
||||
GetSubmission(ctx context.Context, params GetSubmissionParams) (*Submission, error)
|
||||
// ListMapfixAuditEvents implements listMapfixAuditEvents operation.
|
||||
//
|
||||
// Retrieve a list of audit events.
|
||||
//
|
||||
// GET /mapfixes/{MapfixID}/audit-events
|
||||
ListMapfixAuditEvents(ctx context.Context, params ListMapfixAuditEventsParams) ([]AuditEvent, error)
|
||||
// ListMapfixes implements listMapfixes operation.
|
||||
//
|
||||
// Get list of mapfixes.
|
||||
//
|
||||
// GET /mapfixes
|
||||
ListMapfixes(ctx context.Context, params ListMapfixesParams) ([]Mapfix, error)
|
||||
ListMapfixes(ctx context.Context, params ListMapfixesParams) (*Mapfixes, error)
|
||||
// ListMaps implements listMaps operation.
|
||||
//
|
||||
// Get list of maps.
|
||||
//
|
||||
// GET /maps
|
||||
ListMaps(ctx context.Context, params ListMapsParams) ([]Map, error)
|
||||
// ListScriptPolicy implements listScriptPolicy operation.
|
||||
//
|
||||
// Get list of script policies.
|
||||
@@ -194,12 +268,24 @@ type Handler interface {
|
||||
//
|
||||
// GET /scripts
|
||||
ListScripts(ctx context.Context, params ListScriptsParams) ([]Script, error)
|
||||
// ListSubmissionAuditEvents implements listSubmissionAuditEvents operation.
|
||||
//
|
||||
// Retrieve a list of audit events.
|
||||
//
|
||||
// GET /submissions/{SubmissionID}/audit-events
|
||||
ListSubmissionAuditEvents(ctx context.Context, params ListSubmissionAuditEventsParams) ([]AuditEvent, error)
|
||||
// ListSubmissions implements listSubmissions operation.
|
||||
//
|
||||
// Get list of submissions.
|
||||
//
|
||||
// GET /submissions
|
||||
ListSubmissions(ctx context.Context, params ListSubmissionsParams) ([]Submission, error)
|
||||
ListSubmissions(ctx context.Context, params ListSubmissionsParams) (*Submissions, error)
|
||||
// MigrateMaps implements migrateMaps operation.
|
||||
//
|
||||
// Perform maps migration.
|
||||
//
|
||||
// POST /migrate-maps
|
||||
MigrateMaps(ctx context.Context) error
|
||||
// ReleaseSubmissions implements releaseSubmissions operation.
|
||||
//
|
||||
// Release a set of uploaded maps.
|
||||
|
||||
@@ -40,6 +40,16 @@ func (UnimplementedHandler) ActionMapfixRequestChanges(ctx context.Context, para
|
||||
return ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ActionMapfixResetSubmitting implements actionMapfixResetSubmitting operation.
|
||||
//
|
||||
// Role Submitter manually resets submitting softlock and changes status from Submitting ->
|
||||
// UnderConstruction.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/reset-submitting
|
||||
func (UnimplementedHandler) ActionMapfixResetSubmitting(ctx context.Context, params ActionMapfixResetSubmittingParams) error {
|
||||
return ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ActionMapfixRetryValidate implements actionMapfixRetryValidate operation.
|
||||
//
|
||||
// Role Reviewer re-runs validation and changes status from Accepted -> Validating.
|
||||
@@ -58,12 +68,21 @@ func (UnimplementedHandler) ActionMapfixRevoke(ctx context.Context, params Actio
|
||||
return ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ActionMapfixSubmit implements actionMapfixSubmit operation.
|
||||
// ActionMapfixTriggerSubmit implements actionMapfixTriggerSubmit operation.
|
||||
//
|
||||
// Role Submitter changes status from UnderConstruction|ChangesRequested -> Submitted.
|
||||
// Role Submitter changes status from UnderConstruction|ChangesRequested -> Submitting.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/submit
|
||||
func (UnimplementedHandler) ActionMapfixSubmit(ctx context.Context, params ActionMapfixSubmitParams) error {
|
||||
// POST /mapfixes/{MapfixID}/status/trigger-submit
|
||||
func (UnimplementedHandler) ActionMapfixTriggerSubmit(ctx context.Context, params ActionMapfixTriggerSubmitParams) error {
|
||||
return ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ActionMapfixTriggerSubmitUnchecked implements actionMapfixTriggerSubmitUnchecked operation.
|
||||
//
|
||||
// Role Reviewer changes status from ChangesRequested -> Submitting.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/trigger-submit-unchecked
|
||||
func (UnimplementedHandler) ActionMapfixTriggerSubmitUnchecked(ctx context.Context, params ActionMapfixTriggerSubmitUncheckedParams) error {
|
||||
return ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
@@ -121,6 +140,16 @@ func (UnimplementedHandler) ActionSubmissionRequestChanges(ctx context.Context,
|
||||
return ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ActionSubmissionResetSubmitting implements actionSubmissionResetSubmitting operation.
|
||||
//
|
||||
// Role Submitter manually resets submitting softlock and changes status from Submitting ->
|
||||
// UnderConstruction.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/reset-submitting
|
||||
func (UnimplementedHandler) ActionSubmissionResetSubmitting(ctx context.Context, params ActionSubmissionResetSubmittingParams) error {
|
||||
return ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ActionSubmissionRetryValidate implements actionSubmissionRetryValidate operation.
|
||||
//
|
||||
// Role Reviewer re-runs validation and changes status from Accepted -> Validating.
|
||||
@@ -139,12 +168,21 @@ func (UnimplementedHandler) ActionSubmissionRevoke(ctx context.Context, params A
|
||||
return ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ActionSubmissionSubmit implements actionSubmissionSubmit operation.
|
||||
// ActionSubmissionTriggerSubmit implements actionSubmissionTriggerSubmit operation.
|
||||
//
|
||||
// Role Submitter changes status from UnderConstruction|ChangesRequested -> Submitted.
|
||||
// Role Submitter changes status from UnderConstruction|ChangesRequested -> Submitting.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/submit
|
||||
func (UnimplementedHandler) ActionSubmissionSubmit(ctx context.Context, params ActionSubmissionSubmitParams) error {
|
||||
// POST /submissions/{SubmissionID}/status/trigger-submit
|
||||
func (UnimplementedHandler) ActionSubmissionTriggerSubmit(ctx context.Context, params ActionSubmissionTriggerSubmitParams) error {
|
||||
return ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ActionSubmissionTriggerSubmitUnchecked implements actionSubmissionTriggerSubmitUnchecked operation.
|
||||
//
|
||||
// Role Reviewer changes status from ChangesRequested -> Submitting.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/trigger-submit-unchecked
|
||||
func (UnimplementedHandler) ActionSubmissionTriggerSubmitUnchecked(ctx context.Context, params ActionSubmissionTriggerSubmitUncheckedParams) error {
|
||||
return ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
@@ -177,19 +215,28 @@ func (UnimplementedHandler) ActionSubmissionValidated(ctx context.Context, param
|
||||
|
||||
// CreateMapfix implements createMapfix operation.
|
||||
//
|
||||
// Create new mapfix.
|
||||
// Trigger the validator to create a mapfix.
|
||||
//
|
||||
// POST /mapfixes
|
||||
func (UnimplementedHandler) CreateMapfix(ctx context.Context, req *MapfixCreate) (r *ID, _ error) {
|
||||
func (UnimplementedHandler) CreateMapfix(ctx context.Context, req *MapfixTriggerCreate) (r *OperationID, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// CreateMapfixAuditComment implements createMapfixAuditComment operation.
|
||||
//
|
||||
// Post a comment to the audit log.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/comment
|
||||
func (UnimplementedHandler) CreateMapfixAuditComment(ctx context.Context, req CreateMapfixAuditCommentReq, params CreateMapfixAuditCommentParams) error {
|
||||
return ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// CreateScript implements createScript operation.
|
||||
//
|
||||
// Create a new script.
|
||||
//
|
||||
// POST /scripts
|
||||
func (UnimplementedHandler) CreateScript(ctx context.Context, req *ScriptCreate) (r *ID, _ error) {
|
||||
func (UnimplementedHandler) CreateScript(ctx context.Context, req *ScriptCreate) (r *ScriptID, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
@@ -198,19 +245,37 @@ func (UnimplementedHandler) CreateScript(ctx context.Context, req *ScriptCreate)
|
||||
// Create a new script policy.
|
||||
//
|
||||
// POST /script-policy
|
||||
func (UnimplementedHandler) CreateScriptPolicy(ctx context.Context, req *ScriptPolicyCreate) (r *ID, _ error) {
|
||||
func (UnimplementedHandler) CreateScriptPolicy(ctx context.Context, req *ScriptPolicyCreate) (r *ScriptPolicyID, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// CreateSubmission implements createSubmission operation.
|
||||
//
|
||||
// Create new submission.
|
||||
// Trigger the validator to create a new submission.
|
||||
//
|
||||
// POST /submissions
|
||||
func (UnimplementedHandler) CreateSubmission(ctx context.Context, req *SubmissionCreate) (r *ID, _ error) {
|
||||
func (UnimplementedHandler) CreateSubmission(ctx context.Context, req *SubmissionTriggerCreate) (r *OperationID, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// CreateSubmissionAdmin implements createSubmissionAdmin operation.
|
||||
//
|
||||
// Trigger the validator to create a new submission.
|
||||
//
|
||||
// POST /submissions-admin
|
||||
func (UnimplementedHandler) CreateSubmissionAdmin(ctx context.Context, req *SubmissionTriggerCreate) (r *OperationID, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// CreateSubmissionAuditComment implements createSubmissionAuditComment operation.
|
||||
//
|
||||
// Post a comment to the audit log.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/comment
|
||||
func (UnimplementedHandler) CreateSubmissionAuditComment(ctx context.Context, req CreateSubmissionAuditCommentReq, params CreateSubmissionAuditCommentParams) error {
|
||||
return ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// DeleteScript implements deleteScript operation.
|
||||
//
|
||||
// Delete the specified script by ID.
|
||||
@@ -229,6 +294,24 @@ func (UnimplementedHandler) DeleteScriptPolicy(ctx context.Context, params Delet
|
||||
return ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// DownloadMapAsset implements downloadMapAsset operation.
|
||||
//
|
||||
// Download the map asset.
|
||||
//
|
||||
// GET /maps/{MapID}/download
|
||||
func (UnimplementedHandler) DownloadMapAsset(ctx context.Context, params DownloadMapAssetParams) (r DownloadMapAssetOK, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// GetMap implements getMap operation.
|
||||
//
|
||||
// Retrieve map with ID.
|
||||
//
|
||||
// GET /maps/{MapID}
|
||||
func (UnimplementedHandler) GetMap(ctx context.Context, params GetMapParams) (r *Map, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// GetMapfix implements getMapfix operation.
|
||||
//
|
||||
// Retrieve map with ID.
|
||||
@@ -238,6 +321,15 @@ func (UnimplementedHandler) GetMapfix(ctx context.Context, params GetMapfixParam
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// GetOperation implements getOperation operation.
|
||||
//
|
||||
// Retrieve operation with ID.
|
||||
//
|
||||
// GET /operations/{OperationID}
|
||||
func (UnimplementedHandler) GetOperation(ctx context.Context, params GetOperationParams) (r *Operation, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// GetScript implements getScript operation.
|
||||
//
|
||||
// Get the specified script by ID.
|
||||
@@ -265,12 +357,30 @@ func (UnimplementedHandler) GetSubmission(ctx context.Context, params GetSubmiss
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ListMapfixAuditEvents implements listMapfixAuditEvents operation.
|
||||
//
|
||||
// Retrieve a list of audit events.
|
||||
//
|
||||
// GET /mapfixes/{MapfixID}/audit-events
|
||||
func (UnimplementedHandler) ListMapfixAuditEvents(ctx context.Context, params ListMapfixAuditEventsParams) (r []AuditEvent, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ListMapfixes implements listMapfixes operation.
|
||||
//
|
||||
// Get list of mapfixes.
|
||||
//
|
||||
// GET /mapfixes
|
||||
func (UnimplementedHandler) ListMapfixes(ctx context.Context, params ListMapfixesParams) (r []Mapfix, _ error) {
|
||||
func (UnimplementedHandler) ListMapfixes(ctx context.Context, params ListMapfixesParams) (r *Mapfixes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ListMaps implements listMaps operation.
|
||||
//
|
||||
// Get list of maps.
|
||||
//
|
||||
// GET /maps
|
||||
func (UnimplementedHandler) ListMaps(ctx context.Context, params ListMapsParams) (r []Map, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
@@ -292,15 +402,33 @@ func (UnimplementedHandler) ListScripts(ctx context.Context, params ListScriptsP
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ListSubmissionAuditEvents implements listSubmissionAuditEvents operation.
|
||||
//
|
||||
// Retrieve a list of audit events.
|
||||
//
|
||||
// GET /submissions/{SubmissionID}/audit-events
|
||||
func (UnimplementedHandler) ListSubmissionAuditEvents(ctx context.Context, params ListSubmissionAuditEventsParams) (r []AuditEvent, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ListSubmissions implements listSubmissions operation.
|
||||
//
|
||||
// Get list of submissions.
|
||||
//
|
||||
// GET /submissions
|
||||
func (UnimplementedHandler) ListSubmissions(ctx context.Context, params ListSubmissionsParams) (r []Submission, _ error) {
|
||||
func (UnimplementedHandler) ListSubmissions(ctx context.Context, params ListSubmissionsParams) (r *Submissions, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// MigrateMaps implements migrateMaps operation.
|
||||
//
|
||||
// Perform maps migration.
|
||||
//
|
||||
// POST /migrate-maps
|
||||
func (UnimplementedHandler) MigrateMaps(ctx context.Context) error {
|
||||
return ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ReleaseSubmissions implements releaseSubmissions operation.
|
||||
//
|
||||
// Release a set of uploaded maps.
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -2,15 +2,21 @@ package cmds
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
|
||||
"git.itzana.me/strafesnet/go-grpc/auth"
|
||||
"git.itzana.me/strafesnet/go-grpc/maps"
|
||||
"git.itzana.me/strafesnet/go-grpc/maps_extended"
|
||||
"git.itzana.me/strafesnet/go-grpc/users"
|
||||
"git.itzana.me/strafesnet/go-grpc/validator"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/api"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/controller"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/datastore/gormstore"
|
||||
internal "git.itzana.me/strafesnet/maps-service/pkg/internal"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/roblox"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/service"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/service_internal"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/validator_controller"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/web_api"
|
||||
"github.com/nats-io/nats.go"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/urfave/cli/v2"
|
||||
@@ -90,6 +96,12 @@ func NewServeCommand() *cli.Command {
|
||||
EnvVars: []string{"NATS_HOST"},
|
||||
Value: "nats:4222",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "rbx-api-key",
|
||||
Usage: "API Key for downloading asset locations",
|
||||
EnvVars: []string{"RBX_API_KEY"},
|
||||
Required: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -122,45 +134,67 @@ func serve(ctx *cli.Context) error {
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
svc := &service.Service{
|
||||
DB: db,
|
||||
Nats: js,
|
||||
Client: maps.NewMapsServiceClient(conn),
|
||||
}
|
||||
svc_inner := service.NewService(
|
||||
db,
|
||||
js,
|
||||
maps.NewMapsServiceClient(conn),
|
||||
users.NewUsersServiceClient(conn),
|
||||
)
|
||||
|
||||
svc_external := web_api.NewService(
|
||||
&svc_inner,
|
||||
roblox.Client{
|
||||
HttpClient: http.DefaultClient,
|
||||
ApiKey: ctx.String("rbx-api-key"),
|
||||
},
|
||||
)
|
||||
|
||||
conn, err = grpc.Dial(ctx.String("auth-rpc-host"), grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
sec := service.SecurityHandler{
|
||||
sec := web_api.SecurityHandler{
|
||||
Client: auth.NewAuthServiceClient(conn),
|
||||
}
|
||||
|
||||
srv, err := api.NewServer(svc, sec, api.WithPathPrefix("/v1"))
|
||||
srv_external, err := api.NewServer(&svc_external, sec, api.WithPathPrefix("/v1"))
|
||||
if err != nil {
|
||||
log.WithError(err).Fatal("failed to initialize api server")
|
||||
}
|
||||
|
||||
svc2 := &service_internal.Service{
|
||||
DB: db,
|
||||
Nats: js,
|
||||
}
|
||||
grpcServer := grpc.NewServer()
|
||||
|
||||
srv2, err := internal.NewServer(svc2, internal.WithPathPrefix("/v1"))
|
||||
maps_controller := controller.NewMapsController(&svc_inner)
|
||||
maps_extended.RegisterMapsServiceServer(grpcServer,&maps_controller)
|
||||
|
||||
mapfix_controller := validator_controller.NewMapfixesController(&svc_inner)
|
||||
operation_controller := validator_controller.NewOperationsController(&svc_inner)
|
||||
script_controller := validator_controller.NewScriptsController(&svc_inner)
|
||||
script_policy_controller := validator_controller.NewScriptPolicyController(&svc_inner)
|
||||
submission_controller := validator_controller.NewSubmissionsController(&svc_inner)
|
||||
|
||||
validator.RegisterValidatorMapfixServiceServer(grpcServer,&mapfix_controller)
|
||||
validator.RegisterValidatorOperationServiceServer(grpcServer,&operation_controller)
|
||||
validator.RegisterValidatorScriptServiceServer(grpcServer,&script_controller)
|
||||
validator.RegisterValidatorScriptPolicyServiceServer(grpcServer,&script_policy_controller)
|
||||
validator.RegisterValidatorSubmissionServiceServer(grpcServer,&submission_controller)
|
||||
|
||||
port := ctx.Int("port-internal")
|
||||
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
|
||||
if err != nil {
|
||||
log.WithError(err).Fatal("failed to initialize api server")
|
||||
log.WithField("error", err).Fatalln("failed to net.Listen")
|
||||
}
|
||||
// Channel to collect errors
|
||||
errChan := make(chan error, 2)
|
||||
|
||||
// First server
|
||||
go func(errChan chan error) {
|
||||
errChan <- http.ListenAndServe(fmt.Sprintf(":%d", ctx.Int("port-internal")), srv2)
|
||||
errChan <- grpcServer.Serve(lis)
|
||||
}(errChan)
|
||||
|
||||
// Second server
|
||||
go func(errChan chan error) {
|
||||
errChan <- http.ListenAndServe(fmt.Sprintf(":%d", ctx.Int("port")), srv)
|
||||
errChan <- http.ListenAndServe(fmt.Sprintf(":%d", ctx.Int("port")), srv_external)
|
||||
}(errChan)
|
||||
|
||||
// Wait for the first error or completion of both tasks
|
||||
|
||||
197
pkg/controller/maps.go
Normal file
197
pkg/controller/maps.go
Normal file
@@ -0,0 +1,197 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"git.itzana.me/strafesnet/go-grpc/maps_extended"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/service"
|
||||
)
|
||||
|
||||
var (
|
||||
PageError = errors.New("Pagination required")
|
||||
)
|
||||
|
||||
type Maps struct {
|
||||
*maps_extended.UnimplementedMapsServiceServer
|
||||
inner *service.Service
|
||||
}
|
||||
|
||||
func NewMapsController(
|
||||
inner *service.Service,
|
||||
) Maps {
|
||||
return Maps{
|
||||
inner: inner,
|
||||
}
|
||||
}
|
||||
|
||||
func (svc *Maps) Create(ctx context.Context, request *maps_extended.MapCreate) (*maps_extended.MapId, error) {
|
||||
id, err := svc.inner.CreateMap(ctx, model.Map{
|
||||
ID: request.ID,
|
||||
DisplayName: request.DisplayName,
|
||||
Creator: request.Creator,
|
||||
GameID: request.GameID,
|
||||
Submitter: request.Submitter,
|
||||
Date: time.Unix(request.Date, 0),
|
||||
Thumbnail: request.Thumbnail,
|
||||
AssetVersion: request.AssetVersion,
|
||||
LoadCount: 0,
|
||||
Modes: request.Modes,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &maps_extended.MapId{
|
||||
ID: id,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (svc *Maps) Delete(ctx context.Context, request *maps_extended.MapId) (*maps_extended.NullResponse, error) {
|
||||
err := svc.inner.DeleteMap(ctx, request.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &maps_extended.NullResponse{}, nil
|
||||
}
|
||||
func (svc *Maps) Get(ctx context.Context, request *maps_extended.MapId) (*maps_extended.MapResponse, error) {
|
||||
item, err := svc.inner.GetMap(ctx, request.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &maps_extended.MapResponse{
|
||||
ID: item.ID,
|
||||
DisplayName: item.DisplayName,
|
||||
Creator: item.Creator,
|
||||
GameID: uint32(item.GameID),
|
||||
Date: item.Date.Unix(),
|
||||
CreatedAt: item.CreatedAt.Unix(),
|
||||
UpdatedAt: item.UpdatedAt.Unix(),
|
||||
Submitter: uint64(item.Submitter),
|
||||
Thumbnail: uint64(item.Thumbnail),
|
||||
AssetVersion: uint64(item.AssetVersion),
|
||||
LoadCount: item.LoadCount,
|
||||
Modes: item.Modes,
|
||||
}, nil
|
||||
}
|
||||
func (svc *Maps) GetList(ctx context.Context, request *maps_extended.MapIdList) (*maps_extended.MapList, error) {
|
||||
items, err := svc.inner.GetMapList(ctx, request.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp := maps_extended.MapList{}
|
||||
resp.Maps = make([]*maps_extended.MapResponse, len(items))
|
||||
for i, item := range items {
|
||||
resp.Maps[i] = &maps_extended.MapResponse{
|
||||
ID: item.ID,
|
||||
DisplayName: item.DisplayName,
|
||||
Creator: item.Creator,
|
||||
GameID: uint32(item.GameID),
|
||||
Date: item.Date.Unix(),
|
||||
CreatedAt: item.CreatedAt.Unix(),
|
||||
UpdatedAt: item.UpdatedAt.Unix(),
|
||||
Submitter: uint64(item.Submitter),
|
||||
Thumbnail: uint64(item.Thumbnail),
|
||||
AssetVersion: uint64(item.AssetVersion),
|
||||
LoadCount: item.LoadCount,
|
||||
Modes: item.Modes,
|
||||
}
|
||||
}
|
||||
|
||||
return &resp, nil
|
||||
}
|
||||
func (svc *Maps) List(ctx context.Context, request *maps_extended.ListRequest) (*maps_extended.MapList, error) {
|
||||
if request.Page == nil {
|
||||
return nil, PageError
|
||||
}
|
||||
|
||||
filter := service.NewMapFilter()
|
||||
if request.Filter != nil {
|
||||
if request.Filter.DisplayName != nil {
|
||||
filter.SetDisplayName(*request.Filter.DisplayName)
|
||||
}
|
||||
if request.Filter.Creator != nil {
|
||||
filter.SetCreator(*request.Filter.Creator)
|
||||
}
|
||||
if request.Filter.GameID != nil {
|
||||
filter.SetGameID(*request.Filter.GameID)
|
||||
}
|
||||
if request.Filter.Submitter != nil {
|
||||
filter.SetSubmitter(*request.Filter.Submitter)
|
||||
}
|
||||
}
|
||||
|
||||
items, err := svc.inner.ListMaps(ctx, filter, model.Page{
|
||||
Number: int32(request.Page.Number),
|
||||
Size: int32(request.Page.Size),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp := maps_extended.MapList{}
|
||||
resp.Maps = make([]*maps_extended.MapResponse, len(items))
|
||||
for i, item := range items {
|
||||
resp.Maps[i] = &maps_extended.MapResponse{
|
||||
ID: item.ID,
|
||||
DisplayName: item.DisplayName,
|
||||
Creator: item.Creator,
|
||||
GameID: uint32(item.GameID),
|
||||
Date: item.Date.Unix(),
|
||||
CreatedAt: item.CreatedAt.Unix(),
|
||||
UpdatedAt: item.UpdatedAt.Unix(),
|
||||
Submitter: uint64(item.Submitter),
|
||||
Thumbnail: uint64(item.Thumbnail),
|
||||
AssetVersion: uint64(item.AssetVersion),
|
||||
LoadCount: item.LoadCount,
|
||||
Modes: item.Modes,
|
||||
}
|
||||
}
|
||||
|
||||
return &resp, nil
|
||||
}
|
||||
func (svc *Maps) Update(ctx context.Context, request *maps_extended.MapUpdate) (*maps_extended.NullResponse, error) {
|
||||
update := service.NewMapUpdate()
|
||||
if request.DisplayName != nil {
|
||||
update.SetDisplayName(*request.DisplayName)
|
||||
}
|
||||
if request.Creator != nil {
|
||||
update.SetCreator(*request.Creator)
|
||||
}
|
||||
if request.GameID != nil {
|
||||
update.SetGameID(*request.GameID)
|
||||
}
|
||||
if request.Date != nil {
|
||||
update.SetDate(*request.Date)
|
||||
}
|
||||
if request.Submitter != nil {
|
||||
update.SetSubmitter(*request.Submitter)
|
||||
}
|
||||
if request.Thumbnail != nil {
|
||||
update.SetThumbnail(*request.Thumbnail)
|
||||
}
|
||||
if request.AssetVersion != nil {
|
||||
update.SetAssetVersion(*request.AssetVersion)
|
||||
}
|
||||
if request.Modes != nil {
|
||||
update.SetModes(*request.Modes)
|
||||
}
|
||||
|
||||
err := svc.inner.UpdateMap(ctx, request.ID, update)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &maps_extended.NullResponse{}, nil
|
||||
}
|
||||
|
||||
func (svc *Maps) IncrementLoadCount(ctx context.Context, request *maps_extended.MapId) (*maps_extended.NullResponse, error) {
|
||||
err := svc.inner.IncrementMapLoadCount(ctx, request.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &maps_extended.NullResponse{}, nil
|
||||
}
|
||||
@@ -3,6 +3,8 @@ package datastore
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
)
|
||||
|
||||
@@ -22,12 +24,33 @@ const (
|
||||
)
|
||||
|
||||
type Datastore interface {
|
||||
AuditEvents() AuditEvents
|
||||
Maps() Maps
|
||||
Mapfixes() Mapfixes
|
||||
Operations() Operations
|
||||
Submissions() Submissions
|
||||
Scripts() Scripts
|
||||
ScriptPolicy() ScriptPolicy
|
||||
}
|
||||
|
||||
type AuditEvents interface {
|
||||
Get(ctx context.Context, id int64) (model.AuditEvent, error)
|
||||
Create(ctx context.Context, smap model.AuditEvent) (model.AuditEvent, error)
|
||||
Update(ctx context.Context, id int64, values OptionalMap) error
|
||||
Delete(ctx context.Context, id int64) error
|
||||
List(ctx context.Context, filters OptionalMap, page model.Page) ([]model.AuditEvent, error)
|
||||
}
|
||||
|
||||
type Maps interface {
|
||||
Get(ctx context.Context, id int64) (model.Map, error)
|
||||
GetList(ctx context.Context, id []int64) ([]model.Map, error)
|
||||
Create(ctx context.Context, smap model.Map) (model.Map, error)
|
||||
Update(ctx context.Context, id int64, values OptionalMap) error
|
||||
Delete(ctx context.Context, id int64) error
|
||||
List(ctx context.Context, filters OptionalMap, page model.Page) ([]model.Map, error)
|
||||
IncrementLoadCount(ctx context.Context, id int64) error
|
||||
}
|
||||
|
||||
type Mapfixes interface {
|
||||
Get(ctx context.Context, id int64) (model.Mapfix, error)
|
||||
GetList(ctx context.Context, id []int64) ([]model.Mapfix, error)
|
||||
@@ -37,6 +60,15 @@ type Mapfixes interface {
|
||||
IfStatusThenUpdateAndGet(ctx context.Context, id int64, statuses []model.MapfixStatus, values OptionalMap) (model.Mapfix, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
List(ctx context.Context, filters OptionalMap, page model.Page, sort ListSort) ([]model.Mapfix, error)
|
||||
ListWithTotal(ctx context.Context, filters OptionalMap, page model.Page, sort ListSort) (int64, []model.Mapfix, error)
|
||||
}
|
||||
|
||||
type Operations interface {
|
||||
Get(ctx context.Context, id int32) (model.Operation, error)
|
||||
Create(ctx context.Context, smap model.Operation) (model.Operation, error)
|
||||
Update(ctx context.Context, id int32, values OptionalMap) error
|
||||
Delete(ctx context.Context, id int32) error
|
||||
CountSince(ctx context.Context, owner int64, since time.Time) (int64, error)
|
||||
}
|
||||
|
||||
type Submissions interface {
|
||||
@@ -48,6 +80,7 @@ type Submissions interface {
|
||||
IfStatusThenUpdateAndGet(ctx context.Context, id int64, statuses []model.SubmissionStatus, values OptionalMap) (model.Submission, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
List(ctx context.Context, filters OptionalMap, page model.Page, sort ListSort) ([]model.Submission, error)
|
||||
ListWithTotal(ctx context.Context, filters OptionalMap, page model.Page, sort ListSort) (int64, []model.Submission, error)
|
||||
}
|
||||
|
||||
type Scripts interface {
|
||||
|
||||
64
pkg/datastore/gormstore/audit_events.go
Normal file
64
pkg/datastore/gormstore/audit_events.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/datastore"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type AuditEvents struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func (env *AuditEvents) Get(ctx context.Context, id int64) (model.AuditEvent, error) {
|
||||
var mdl model.AuditEvent
|
||||
if err := env.db.First(&mdl, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return mdl, datastore.ErrNotExist
|
||||
}
|
||||
return mdl, err
|
||||
}
|
||||
return mdl, nil
|
||||
}
|
||||
|
||||
func (env *AuditEvents) Create(ctx context.Context, smap model.AuditEvent) (model.AuditEvent, error) {
|
||||
if err := env.db.Create(&smap).Error; err != nil {
|
||||
return smap, err
|
||||
}
|
||||
|
||||
return smap, nil
|
||||
}
|
||||
|
||||
func (env *AuditEvents) Update(ctx context.Context, id int64, values datastore.OptionalMap) error {
|
||||
if err := env.db.Model(&model.AuditEvent{}).Where("id = ?", id).Updates(values.Map()).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return datastore.ErrNotExist
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (env *AuditEvents) Delete(ctx context.Context, id int64) error {
|
||||
if err := env.db.Delete(&model.AuditEvent{}, id).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return datastore.ErrNotExist
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (env *AuditEvents) List(ctx context.Context, filters datastore.OptionalMap, page model.Page) ([]model.AuditEvent, error) {
|
||||
var events []model.AuditEvent
|
||||
if err := env.db.Where(filters.Map()).Order("id ASC").Offset(int((page.Number - 1) * page.Size)).Limit(int(page.Size)).Find(&events).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return events, nil
|
||||
}
|
||||
@@ -31,7 +31,10 @@ func New(ctx *cli.Context) (datastore.Datastore, error) {
|
||||
|
||||
if ctx.Bool("migrate") {
|
||||
if err := db.AutoMigrate(
|
||||
&model.AuditEvent{},
|
||||
&model.Map{},
|
||||
&model.Mapfix{},
|
||||
&model.Operation{},
|
||||
&model.Submission{},
|
||||
&model.Script{},
|
||||
&model.ScriptPolicy{},
|
||||
|
||||
@@ -9,10 +9,22 @@ type Gormstore struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func (g Gormstore) AuditEvents() datastore.AuditEvents {
|
||||
return &AuditEvents{db: g.db}
|
||||
}
|
||||
|
||||
func (g Gormstore) Maps() datastore.Maps {
|
||||
return &Maps{db: g.db}
|
||||
}
|
||||
|
||||
func (g Gormstore) Mapfixes() datastore.Mapfixes {
|
||||
return &Mapfixes{db: g.db}
|
||||
}
|
||||
|
||||
func (g Gormstore) Operations() datastore.Operations {
|
||||
return &Operations{db: g.db}
|
||||
}
|
||||
|
||||
func (g Gormstore) Submissions() datastore.Submissions {
|
||||
return &Submissions{db: g.db}
|
||||
}
|
||||
|
||||
@@ -55,11 +55,16 @@ func (env *Mapfixes) Update(ctx context.Context, id int64, values datastore.Opti
|
||||
|
||||
// the update can only occur if the status matches one of the provided values.
|
||||
func (env *Mapfixes) IfStatusThenUpdate(ctx context.Context, id int64, statuses []model.MapfixStatus, values datastore.OptionalMap) error {
|
||||
if err := env.db.Model(&model.Mapfix{}).Where("id = ?", id).Where("status_id IN ?", statuses).Updates(values.Map()).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
result := env.db.Model(&model.Mapfix{}).Where("id = ?", id).Where("status_id IN ?", statuses).Updates(values.Map())
|
||||
if result.Error != nil {
|
||||
if result.Error == gorm.ErrRecordNotFound {
|
||||
return datastore.ErrNotExist
|
||||
}
|
||||
return err
|
||||
return result.Error
|
||||
}
|
||||
|
||||
if result.RowsAffected == 0 {
|
||||
return datastore.ErroNoRowsAffected
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -130,3 +135,19 @@ func (env *Mapfixes) List(ctx context.Context, filters datastore.OptionalMap, pa
|
||||
|
||||
return maps, nil
|
||||
}
|
||||
|
||||
func (env *Mapfixes) ListWithTotal(ctx context.Context, filters datastore.OptionalMap, page model.Page, sort datastore.ListSort) (int64, []model.Mapfix, error) {
|
||||
// grab page items
|
||||
maps, err := env.List(ctx, filters, page, sort)
|
||||
if err != nil{
|
||||
return 0, nil, err
|
||||
}
|
||||
|
||||
// count total with filters
|
||||
var total int64
|
||||
if err := env.db.Model(&model.Mapfix{}).Where(filters.Map()).Count(&total).Error; err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
|
||||
return total, maps, nil
|
||||
}
|
||||
|
||||
84
pkg/datastore/gormstore/maps.go
Normal file
84
pkg/datastore/gormstore/maps.go
Normal file
@@ -0,0 +1,84 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/datastore"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Maps struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func (env *Maps) Get(ctx context.Context, id int64) (model.Map, error) {
|
||||
var mdl model.Map
|
||||
if err := env.db.First(&mdl, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return mdl, datastore.ErrNotExist
|
||||
}
|
||||
return mdl, err
|
||||
}
|
||||
return mdl, nil
|
||||
}
|
||||
|
||||
func (env *Maps) GetList(ctx context.Context, id []int64) ([]model.Map, error) {
|
||||
var mapList []model.Map
|
||||
if err := env.db.Find(&mapList, "id IN ?", id).Error; err != nil {
|
||||
return mapList, err
|
||||
}
|
||||
|
||||
return mapList, nil
|
||||
}
|
||||
|
||||
func (env *Maps) Create(ctx context.Context, smap model.Map) (model.Map, error) {
|
||||
if err := env.db.Create(&smap).Error; err != nil {
|
||||
return smap, err
|
||||
}
|
||||
|
||||
return smap, nil
|
||||
}
|
||||
|
||||
func (env *Maps) Update(ctx context.Context, id int64, values datastore.OptionalMap) error {
|
||||
if err := env.db.Model(&model.Map{}).Where("id = ?", id).Updates(values.Map()).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return datastore.ErrNotExist
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (env *Maps) IncrementLoadCount(ctx context.Context, id int64) error {
|
||||
if err := env.db.Model(&model.Map{}).Where("id = ?", id).UpdateColumn("load_count", gorm.Expr("load_count + ?", 1)).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return datastore.ErrNotExist
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (env *Maps) Delete(ctx context.Context, id int64) error {
|
||||
if err := env.db.Delete(&model.Map{}, id).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return datastore.ErrNotExist
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (env *Maps) List(ctx context.Context, filters datastore.OptionalMap, page model.Page) ([]model.Map, error) {
|
||||
var events []model.Map
|
||||
if err := env.db.Where(filters.Map()).Offset(int((page.Number - 1) * page.Size)).Limit(int(page.Size)).Find(&events).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return events, nil
|
||||
}
|
||||
65
pkg/datastore/gormstore/operations.go
Normal file
65
pkg/datastore/gormstore/operations.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package gormstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/datastore"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Operations struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func (env *Operations) Get(ctx context.Context, id int32) (model.Operation, error) {
|
||||
var operation model.Operation
|
||||
if err := env.db.First(&operation, id).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return operation, datastore.ErrNotExist
|
||||
}
|
||||
return operation, err
|
||||
}
|
||||
return operation, nil
|
||||
}
|
||||
|
||||
func (env *Operations) Create(ctx context.Context, smap model.Operation) (model.Operation, error) {
|
||||
if err := env.db.Create(&smap).Error; err != nil {
|
||||
return smap, err
|
||||
}
|
||||
|
||||
return smap, nil
|
||||
}
|
||||
|
||||
func (env *Operations) Update(ctx context.Context, id int32, values datastore.OptionalMap) error {
|
||||
if err := env.db.Model(&model.Operation{}).Where("id = ?", id).Updates(values.Map()).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return datastore.ErrNotExist
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (env *Operations) Delete(ctx context.Context, id int32) error {
|
||||
if err := env.db.Delete(&model.Operation{}, id).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return datastore.ErrNotExist
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (env *Operations) CountSince(ctx context.Context, owner int64, since time.Time) (int64, error) {
|
||||
var count int64
|
||||
if err := env.db.Model(&model.Operation{}).Where("owner = ? AND created_at > ?",owner,since).Count(&count).Error; err != nil {
|
||||
return count, err
|
||||
}
|
||||
|
||||
return count, nil
|
||||
}
|
||||
@@ -55,11 +55,16 @@ func (env *Submissions) Update(ctx context.Context, id int64, values datastore.O
|
||||
|
||||
// the update can only occur if the status matches one of the provided values.
|
||||
func (env *Submissions) IfStatusThenUpdate(ctx context.Context, id int64, statuses []model.SubmissionStatus, values datastore.OptionalMap) error {
|
||||
if err := env.db.Model(&model.Submission{}).Where("id = ?", id).Where("status_id IN ?", statuses).Updates(values.Map()).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
result := env.db.Model(&model.Submission{}).Where("id = ?", id).Where("status_id IN ?", statuses).Updates(values.Map())
|
||||
if result.Error != nil {
|
||||
if result.Error == gorm.ErrRecordNotFound {
|
||||
return datastore.ErrNotExist
|
||||
}
|
||||
return err
|
||||
return result.Error
|
||||
}
|
||||
|
||||
if result.RowsAffected == 0 {
|
||||
return datastore.ErroNoRowsAffected
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -130,3 +135,19 @@ func (env *Submissions) List(ctx context.Context, filters datastore.OptionalMap,
|
||||
|
||||
return maps, nil
|
||||
}
|
||||
|
||||
func (env *Submissions) ListWithTotal(ctx context.Context, filters datastore.OptionalMap, page model.Page, sort datastore.ListSort) (int64, []model.Submission, error) {
|
||||
// grab page items
|
||||
maps, err := env.List(ctx, filters, page, sort)
|
||||
if err != nil{
|
||||
return 0, nil, err
|
||||
}
|
||||
|
||||
// count total with filters
|
||||
var total int64
|
||||
if err := env.db.Model(&model.Submission{}).Where(filters.Map()).Count(&total).Error; err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
|
||||
return total, maps, nil
|
||||
}
|
||||
|
||||
@@ -1,283 +0,0 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
"github.com/ogen-go/ogen/middleware"
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
"github.com/ogen-go/ogen/otelogen"
|
||||
)
|
||||
|
||||
var (
|
||||
// Allocate option closure once.
|
||||
clientSpanKind = trace.WithSpanKind(trace.SpanKindClient)
|
||||
// Allocate option closure once.
|
||||
serverSpanKind = trace.WithSpanKind(trace.SpanKindServer)
|
||||
)
|
||||
|
||||
type (
|
||||
optionFunc[C any] func(*C)
|
||||
otelOptionFunc func(*otelConfig)
|
||||
)
|
||||
|
||||
type otelConfig struct {
|
||||
TracerProvider trace.TracerProvider
|
||||
Tracer trace.Tracer
|
||||
MeterProvider metric.MeterProvider
|
||||
Meter metric.Meter
|
||||
}
|
||||
|
||||
func (cfg *otelConfig) initOTEL() {
|
||||
if cfg.TracerProvider == nil {
|
||||
cfg.TracerProvider = otel.GetTracerProvider()
|
||||
}
|
||||
if cfg.MeterProvider == nil {
|
||||
cfg.MeterProvider = otel.GetMeterProvider()
|
||||
}
|
||||
cfg.Tracer = cfg.TracerProvider.Tracer(otelogen.Name,
|
||||
trace.WithInstrumentationVersion(otelogen.SemVersion()),
|
||||
)
|
||||
cfg.Meter = cfg.MeterProvider.Meter(otelogen.Name,
|
||||
metric.WithInstrumentationVersion(otelogen.SemVersion()),
|
||||
)
|
||||
}
|
||||
|
||||
// ErrorHandler is error handler.
|
||||
type ErrorHandler = ogenerrors.ErrorHandler
|
||||
|
||||
type serverConfig struct {
|
||||
otelConfig
|
||||
NotFound http.HandlerFunc
|
||||
MethodNotAllowed func(w http.ResponseWriter, r *http.Request, allowed string)
|
||||
ErrorHandler ErrorHandler
|
||||
Prefix string
|
||||
Middleware Middleware
|
||||
MaxMultipartMemory int64
|
||||
}
|
||||
|
||||
// ServerOption is server config option.
|
||||
type ServerOption interface {
|
||||
applyServer(*serverConfig)
|
||||
}
|
||||
|
||||
var _ ServerOption = (optionFunc[serverConfig])(nil)
|
||||
|
||||
func (o optionFunc[C]) applyServer(c *C) {
|
||||
o(c)
|
||||
}
|
||||
|
||||
var _ ServerOption = (otelOptionFunc)(nil)
|
||||
|
||||
func (o otelOptionFunc) applyServer(c *serverConfig) {
|
||||
o(&c.otelConfig)
|
||||
}
|
||||
|
||||
func newServerConfig(opts ...ServerOption) serverConfig {
|
||||
cfg := serverConfig{
|
||||
NotFound: http.NotFound,
|
||||
MethodNotAllowed: func(w http.ResponseWriter, r *http.Request, allowed string) {
|
||||
status := http.StatusMethodNotAllowed
|
||||
if r.Method == "OPTIONS" {
|
||||
w.Header().Set("Access-Control-Allow-Methods", allowed)
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
status = http.StatusNoContent
|
||||
} else {
|
||||
w.Header().Set("Allow", allowed)
|
||||
}
|
||||
w.WriteHeader(status)
|
||||
},
|
||||
ErrorHandler: ogenerrors.DefaultErrorHandler,
|
||||
Middleware: nil,
|
||||
MaxMultipartMemory: 32 << 20, // 32 MB
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt.applyServer(&cfg)
|
||||
}
|
||||
cfg.initOTEL()
|
||||
return cfg
|
||||
}
|
||||
|
||||
type baseServer struct {
|
||||
cfg serverConfig
|
||||
requests metric.Int64Counter
|
||||
errors metric.Int64Counter
|
||||
duration metric.Float64Histogram
|
||||
}
|
||||
|
||||
func (s baseServer) notFound(w http.ResponseWriter, r *http.Request) {
|
||||
s.cfg.NotFound(w, r)
|
||||
}
|
||||
|
||||
func (s baseServer) notAllowed(w http.ResponseWriter, r *http.Request, allowed string) {
|
||||
s.cfg.MethodNotAllowed(w, r, allowed)
|
||||
}
|
||||
|
||||
func (cfg serverConfig) baseServer() (s baseServer, err error) {
|
||||
s = baseServer{cfg: cfg}
|
||||
if s.requests, err = otelogen.ServerRequestCountCounter(s.cfg.Meter); err != nil {
|
||||
return s, err
|
||||
}
|
||||
if s.errors, err = otelogen.ServerErrorsCountCounter(s.cfg.Meter); err != nil {
|
||||
return s, err
|
||||
}
|
||||
if s.duration, err = otelogen.ServerDurationHistogram(s.cfg.Meter); err != nil {
|
||||
return s, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
type clientConfig struct {
|
||||
otelConfig
|
||||
Client ht.Client
|
||||
}
|
||||
|
||||
// ClientOption is client config option.
|
||||
type ClientOption interface {
|
||||
applyClient(*clientConfig)
|
||||
}
|
||||
|
||||
var _ ClientOption = (optionFunc[clientConfig])(nil)
|
||||
|
||||
func (o optionFunc[C]) applyClient(c *C) {
|
||||
o(c)
|
||||
}
|
||||
|
||||
var _ ClientOption = (otelOptionFunc)(nil)
|
||||
|
||||
func (o otelOptionFunc) applyClient(c *clientConfig) {
|
||||
o(&c.otelConfig)
|
||||
}
|
||||
|
||||
func newClientConfig(opts ...ClientOption) clientConfig {
|
||||
cfg := clientConfig{
|
||||
Client: http.DefaultClient,
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt.applyClient(&cfg)
|
||||
}
|
||||
cfg.initOTEL()
|
||||
return cfg
|
||||
}
|
||||
|
||||
type baseClient struct {
|
||||
cfg clientConfig
|
||||
requests metric.Int64Counter
|
||||
errors metric.Int64Counter
|
||||
duration metric.Float64Histogram
|
||||
}
|
||||
|
||||
func (cfg clientConfig) baseClient() (c baseClient, err error) {
|
||||
c = baseClient{cfg: cfg}
|
||||
if c.requests, err = otelogen.ClientRequestCountCounter(c.cfg.Meter); err != nil {
|
||||
return c, err
|
||||
}
|
||||
if c.errors, err = otelogen.ClientErrorsCountCounter(c.cfg.Meter); err != nil {
|
||||
return c, err
|
||||
}
|
||||
if c.duration, err = otelogen.ClientDurationHistogram(c.cfg.Meter); err != nil {
|
||||
return c, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Option is config option.
|
||||
type Option interface {
|
||||
ServerOption
|
||||
ClientOption
|
||||
}
|
||||
|
||||
// WithTracerProvider specifies a tracer provider to use for creating a tracer.
|
||||
//
|
||||
// If none is specified, the global provider is used.
|
||||
func WithTracerProvider(provider trace.TracerProvider) Option {
|
||||
return otelOptionFunc(func(cfg *otelConfig) {
|
||||
if provider != nil {
|
||||
cfg.TracerProvider = provider
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithMeterProvider specifies a meter provider to use for creating a meter.
|
||||
//
|
||||
// If none is specified, the otel.GetMeterProvider() is used.
|
||||
func WithMeterProvider(provider metric.MeterProvider) Option {
|
||||
return otelOptionFunc(func(cfg *otelConfig) {
|
||||
if provider != nil {
|
||||
cfg.MeterProvider = provider
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithClient specifies http client to use.
|
||||
func WithClient(client ht.Client) ClientOption {
|
||||
return optionFunc[clientConfig](func(cfg *clientConfig) {
|
||||
if client != nil {
|
||||
cfg.Client = client
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithNotFound specifies Not Found handler to use.
|
||||
func WithNotFound(notFound http.HandlerFunc) ServerOption {
|
||||
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||
if notFound != nil {
|
||||
cfg.NotFound = notFound
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithMethodNotAllowed specifies Method Not Allowed handler to use.
|
||||
func WithMethodNotAllowed(methodNotAllowed func(w http.ResponseWriter, r *http.Request, allowed string)) ServerOption {
|
||||
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||
if methodNotAllowed != nil {
|
||||
cfg.MethodNotAllowed = methodNotAllowed
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithErrorHandler specifies error handler to use.
|
||||
func WithErrorHandler(h ErrorHandler) ServerOption {
|
||||
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||
if h != nil {
|
||||
cfg.ErrorHandler = h
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithPathPrefix specifies server path prefix.
|
||||
func WithPathPrefix(prefix string) ServerOption {
|
||||
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||
cfg.Prefix = prefix
|
||||
})
|
||||
}
|
||||
|
||||
// WithMiddleware specifies middlewares to use.
|
||||
func WithMiddleware(m ...Middleware) ServerOption {
|
||||
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||
switch len(m) {
|
||||
case 0:
|
||||
cfg.Middleware = nil
|
||||
case 1:
|
||||
cfg.Middleware = m[0]
|
||||
default:
|
||||
cfg.Middleware = middleware.ChainMiddlewares(m...)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// WithMaxMultipartMemory specifies limit of memory for storing file parts.
|
||||
// File parts which can't be stored in memory will be stored on disk in temporary files.
|
||||
func WithMaxMultipartMemory(max int64) ServerOption {
|
||||
return optionFunc[serverConfig](func(cfg *serverConfig) {
|
||||
if max > 0 {
|
||||
cfg.MaxMultipartMemory = max
|
||||
}
|
||||
})
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,862 +0,0 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"math/bits"
|
||||
"strconv"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
)
|
||||
|
||||
// Encode implements json.Marshaler.
|
||||
func (s *Error) Encode(e *jx.Encoder) {
|
||||
e.ObjStart()
|
||||
s.encodeFields(e)
|
||||
e.ObjEnd()
|
||||
}
|
||||
|
||||
// encodeFields encodes fields.
|
||||
func (s *Error) encodeFields(e *jx.Encoder) {
|
||||
{
|
||||
e.FieldStart("code")
|
||||
e.Int64(s.Code)
|
||||
}
|
||||
{
|
||||
e.FieldStart("message")
|
||||
e.Str(s.Message)
|
||||
}
|
||||
}
|
||||
|
||||
var jsonFieldsNameOfError = [2]string{
|
||||
0: "code",
|
||||
1: "message",
|
||||
}
|
||||
|
||||
// Decode decodes Error from json.
|
||||
func (s *Error) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode Error to nil")
|
||||
}
|
||||
var requiredBitSet [1]uint8
|
||||
|
||||
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
|
||||
switch string(k) {
|
||||
case "code":
|
||||
requiredBitSet[0] |= 1 << 0
|
||||
if err := func() error {
|
||||
v, err := d.Int64()
|
||||
s.Code = int64(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"code\"")
|
||||
}
|
||||
case "message":
|
||||
requiredBitSet[0] |= 1 << 1
|
||||
if err := func() error {
|
||||
v, err := d.Str()
|
||||
s.Message = string(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"message\"")
|
||||
}
|
||||
default:
|
||||
return d.Skip()
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "decode Error")
|
||||
}
|
||||
// Validate required fields.
|
||||
var failures []validate.FieldError
|
||||
for i, mask := range [1]uint8{
|
||||
0b00000011,
|
||||
} {
|
||||
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
|
||||
// Mask only required fields and check equality to mask using XOR.
|
||||
//
|
||||
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
|
||||
// Bits of fields which would be set are actually bits of missed fields.
|
||||
missed := bits.OnesCount8(result)
|
||||
for bitN := 0; bitN < missed; bitN++ {
|
||||
bitIdx := bits.TrailingZeros8(result)
|
||||
fieldIdx := i*8 + bitIdx
|
||||
var name string
|
||||
if fieldIdx < len(jsonFieldsNameOfError) {
|
||||
name = jsonFieldsNameOfError[fieldIdx]
|
||||
} else {
|
||||
name = strconv.Itoa(fieldIdx)
|
||||
}
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: name,
|
||||
Error: validate.ErrFieldRequired,
|
||||
})
|
||||
// Reset bit.
|
||||
result &^= 1 << bitIdx
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s *Error) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *Error) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode implements json.Marshaler.
|
||||
func (s *ID) Encode(e *jx.Encoder) {
|
||||
e.ObjStart()
|
||||
s.encodeFields(e)
|
||||
e.ObjEnd()
|
||||
}
|
||||
|
||||
// encodeFields encodes fields.
|
||||
func (s *ID) encodeFields(e *jx.Encoder) {
|
||||
{
|
||||
e.FieldStart("ID")
|
||||
e.Int64(s.ID)
|
||||
}
|
||||
}
|
||||
|
||||
var jsonFieldsNameOfID = [1]string{
|
||||
0: "ID",
|
||||
}
|
||||
|
||||
// Decode decodes ID from json.
|
||||
func (s *ID) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode ID to nil")
|
||||
}
|
||||
var requiredBitSet [1]uint8
|
||||
|
||||
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
|
||||
switch string(k) {
|
||||
case "ID":
|
||||
requiredBitSet[0] |= 1 << 0
|
||||
if err := func() error {
|
||||
v, err := d.Int64()
|
||||
s.ID = int64(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"ID\"")
|
||||
}
|
||||
default:
|
||||
return d.Skip()
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "decode ID")
|
||||
}
|
||||
// Validate required fields.
|
||||
var failures []validate.FieldError
|
||||
for i, mask := range [1]uint8{
|
||||
0b00000001,
|
||||
} {
|
||||
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
|
||||
// Mask only required fields and check equality to mask using XOR.
|
||||
//
|
||||
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
|
||||
// Bits of fields which would be set are actually bits of missed fields.
|
||||
missed := bits.OnesCount8(result)
|
||||
for bitN := 0; bitN < missed; bitN++ {
|
||||
bitIdx := bits.TrailingZeros8(result)
|
||||
fieldIdx := i*8 + bitIdx
|
||||
var name string
|
||||
if fieldIdx < len(jsonFieldsNameOfID) {
|
||||
name = jsonFieldsNameOfID[fieldIdx]
|
||||
} else {
|
||||
name = strconv.Itoa(fieldIdx)
|
||||
}
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: name,
|
||||
Error: validate.ErrFieldRequired,
|
||||
})
|
||||
// Reset bit.
|
||||
result &^= 1 << bitIdx
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s *ID) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *ID) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode encodes int64 as json.
|
||||
func (o OptInt64) Encode(e *jx.Encoder) {
|
||||
if !o.Set {
|
||||
return
|
||||
}
|
||||
e.Int64(int64(o.Value))
|
||||
}
|
||||
|
||||
// Decode decodes int64 from json.
|
||||
func (o *OptInt64) Decode(d *jx.Decoder) error {
|
||||
if o == nil {
|
||||
return errors.New("invalid: unable to decode OptInt64 to nil")
|
||||
}
|
||||
o.Set = true
|
||||
v, err := d.Int64()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
o.Value = int64(v)
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s OptInt64) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *OptInt64) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode implements json.Marshaler.
|
||||
func (s *Script) Encode(e *jx.Encoder) {
|
||||
e.ObjStart()
|
||||
s.encodeFields(e)
|
||||
e.ObjEnd()
|
||||
}
|
||||
|
||||
// encodeFields encodes fields.
|
||||
func (s *Script) encodeFields(e *jx.Encoder) {
|
||||
{
|
||||
e.FieldStart("ID")
|
||||
e.Int64(s.ID)
|
||||
}
|
||||
{
|
||||
e.FieldStart("Name")
|
||||
e.Str(s.Name)
|
||||
}
|
||||
{
|
||||
e.FieldStart("Hash")
|
||||
e.Str(s.Hash)
|
||||
}
|
||||
{
|
||||
e.FieldStart("Source")
|
||||
e.Str(s.Source)
|
||||
}
|
||||
{
|
||||
e.FieldStart("ResourceType")
|
||||
e.Int32(s.ResourceType)
|
||||
}
|
||||
{
|
||||
e.FieldStart("ResourceID")
|
||||
e.Int64(s.ResourceID)
|
||||
}
|
||||
}
|
||||
|
||||
var jsonFieldsNameOfScript = [6]string{
|
||||
0: "ID",
|
||||
1: "Name",
|
||||
2: "Hash",
|
||||
3: "Source",
|
||||
4: "ResourceType",
|
||||
5: "ResourceID",
|
||||
}
|
||||
|
||||
// Decode decodes Script from json.
|
||||
func (s *Script) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode Script to nil")
|
||||
}
|
||||
var requiredBitSet [1]uint8
|
||||
|
||||
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
|
||||
switch string(k) {
|
||||
case "ID":
|
||||
requiredBitSet[0] |= 1 << 0
|
||||
if err := func() error {
|
||||
v, err := d.Int64()
|
||||
s.ID = int64(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"ID\"")
|
||||
}
|
||||
case "Name":
|
||||
requiredBitSet[0] |= 1 << 1
|
||||
if err := func() error {
|
||||
v, err := d.Str()
|
||||
s.Name = string(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"Name\"")
|
||||
}
|
||||
case "Hash":
|
||||
requiredBitSet[0] |= 1 << 2
|
||||
if err := func() error {
|
||||
v, err := d.Str()
|
||||
s.Hash = string(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"Hash\"")
|
||||
}
|
||||
case "Source":
|
||||
requiredBitSet[0] |= 1 << 3
|
||||
if err := func() error {
|
||||
v, err := d.Str()
|
||||
s.Source = string(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"Source\"")
|
||||
}
|
||||
case "ResourceType":
|
||||
requiredBitSet[0] |= 1 << 4
|
||||
if err := func() error {
|
||||
v, err := d.Int32()
|
||||
s.ResourceType = int32(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"ResourceType\"")
|
||||
}
|
||||
case "ResourceID":
|
||||
requiredBitSet[0] |= 1 << 5
|
||||
if err := func() error {
|
||||
v, err := d.Int64()
|
||||
s.ResourceID = int64(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"ResourceID\"")
|
||||
}
|
||||
default:
|
||||
return d.Skip()
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "decode Script")
|
||||
}
|
||||
// Validate required fields.
|
||||
var failures []validate.FieldError
|
||||
for i, mask := range [1]uint8{
|
||||
0b00111111,
|
||||
} {
|
||||
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
|
||||
// Mask only required fields and check equality to mask using XOR.
|
||||
//
|
||||
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
|
||||
// Bits of fields which would be set are actually bits of missed fields.
|
||||
missed := bits.OnesCount8(result)
|
||||
for bitN := 0; bitN < missed; bitN++ {
|
||||
bitIdx := bits.TrailingZeros8(result)
|
||||
fieldIdx := i*8 + bitIdx
|
||||
var name string
|
||||
if fieldIdx < len(jsonFieldsNameOfScript) {
|
||||
name = jsonFieldsNameOfScript[fieldIdx]
|
||||
} else {
|
||||
name = strconv.Itoa(fieldIdx)
|
||||
}
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: name,
|
||||
Error: validate.ErrFieldRequired,
|
||||
})
|
||||
// Reset bit.
|
||||
result &^= 1 << bitIdx
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s *Script) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *Script) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode implements json.Marshaler.
|
||||
func (s *ScriptCreate) Encode(e *jx.Encoder) {
|
||||
e.ObjStart()
|
||||
s.encodeFields(e)
|
||||
e.ObjEnd()
|
||||
}
|
||||
|
||||
// encodeFields encodes fields.
|
||||
func (s *ScriptCreate) encodeFields(e *jx.Encoder) {
|
||||
{
|
||||
e.FieldStart("Name")
|
||||
e.Str(s.Name)
|
||||
}
|
||||
{
|
||||
e.FieldStart("Source")
|
||||
e.Str(s.Source)
|
||||
}
|
||||
{
|
||||
e.FieldStart("ResourceType")
|
||||
e.Int32(s.ResourceType)
|
||||
}
|
||||
{
|
||||
if s.ResourceID.Set {
|
||||
e.FieldStart("ResourceID")
|
||||
s.ResourceID.Encode(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var jsonFieldsNameOfScriptCreate = [4]string{
|
||||
0: "Name",
|
||||
1: "Source",
|
||||
2: "ResourceType",
|
||||
3: "ResourceID",
|
||||
}
|
||||
|
||||
// Decode decodes ScriptCreate from json.
|
||||
func (s *ScriptCreate) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode ScriptCreate to nil")
|
||||
}
|
||||
var requiredBitSet [1]uint8
|
||||
|
||||
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
|
||||
switch string(k) {
|
||||
case "Name":
|
||||
requiredBitSet[0] |= 1 << 0
|
||||
if err := func() error {
|
||||
v, err := d.Str()
|
||||
s.Name = string(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"Name\"")
|
||||
}
|
||||
case "Source":
|
||||
requiredBitSet[0] |= 1 << 1
|
||||
if err := func() error {
|
||||
v, err := d.Str()
|
||||
s.Source = string(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"Source\"")
|
||||
}
|
||||
case "ResourceType":
|
||||
requiredBitSet[0] |= 1 << 2
|
||||
if err := func() error {
|
||||
v, err := d.Int32()
|
||||
s.ResourceType = int32(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"ResourceType\"")
|
||||
}
|
||||
case "ResourceID":
|
||||
if err := func() error {
|
||||
s.ResourceID.Reset()
|
||||
if err := s.ResourceID.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"ResourceID\"")
|
||||
}
|
||||
default:
|
||||
return d.Skip()
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "decode ScriptCreate")
|
||||
}
|
||||
// Validate required fields.
|
||||
var failures []validate.FieldError
|
||||
for i, mask := range [1]uint8{
|
||||
0b00000111,
|
||||
} {
|
||||
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
|
||||
// Mask only required fields and check equality to mask using XOR.
|
||||
//
|
||||
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
|
||||
// Bits of fields which would be set are actually bits of missed fields.
|
||||
missed := bits.OnesCount8(result)
|
||||
for bitN := 0; bitN < missed; bitN++ {
|
||||
bitIdx := bits.TrailingZeros8(result)
|
||||
fieldIdx := i*8 + bitIdx
|
||||
var name string
|
||||
if fieldIdx < len(jsonFieldsNameOfScriptCreate) {
|
||||
name = jsonFieldsNameOfScriptCreate[fieldIdx]
|
||||
} else {
|
||||
name = strconv.Itoa(fieldIdx)
|
||||
}
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: name,
|
||||
Error: validate.ErrFieldRequired,
|
||||
})
|
||||
// Reset bit.
|
||||
result &^= 1 << bitIdx
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s *ScriptCreate) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *ScriptCreate) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode implements json.Marshaler.
|
||||
func (s *ScriptPolicy) Encode(e *jx.Encoder) {
|
||||
e.ObjStart()
|
||||
s.encodeFields(e)
|
||||
e.ObjEnd()
|
||||
}
|
||||
|
||||
// encodeFields encodes fields.
|
||||
func (s *ScriptPolicy) encodeFields(e *jx.Encoder) {
|
||||
{
|
||||
e.FieldStart("ID")
|
||||
e.Int64(s.ID)
|
||||
}
|
||||
{
|
||||
e.FieldStart("FromScriptHash")
|
||||
e.Str(s.FromScriptHash)
|
||||
}
|
||||
{
|
||||
e.FieldStart("ToScriptID")
|
||||
e.Int64(s.ToScriptID)
|
||||
}
|
||||
{
|
||||
e.FieldStart("Policy")
|
||||
e.Int32(s.Policy)
|
||||
}
|
||||
}
|
||||
|
||||
var jsonFieldsNameOfScriptPolicy = [4]string{
|
||||
0: "ID",
|
||||
1: "FromScriptHash",
|
||||
2: "ToScriptID",
|
||||
3: "Policy",
|
||||
}
|
||||
|
||||
// Decode decodes ScriptPolicy from json.
|
||||
func (s *ScriptPolicy) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode ScriptPolicy to nil")
|
||||
}
|
||||
var requiredBitSet [1]uint8
|
||||
|
||||
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
|
||||
switch string(k) {
|
||||
case "ID":
|
||||
requiredBitSet[0] |= 1 << 0
|
||||
if err := func() error {
|
||||
v, err := d.Int64()
|
||||
s.ID = int64(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"ID\"")
|
||||
}
|
||||
case "FromScriptHash":
|
||||
requiredBitSet[0] |= 1 << 1
|
||||
if err := func() error {
|
||||
v, err := d.Str()
|
||||
s.FromScriptHash = string(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"FromScriptHash\"")
|
||||
}
|
||||
case "ToScriptID":
|
||||
requiredBitSet[0] |= 1 << 2
|
||||
if err := func() error {
|
||||
v, err := d.Int64()
|
||||
s.ToScriptID = int64(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"ToScriptID\"")
|
||||
}
|
||||
case "Policy":
|
||||
requiredBitSet[0] |= 1 << 3
|
||||
if err := func() error {
|
||||
v, err := d.Int32()
|
||||
s.Policy = int32(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"Policy\"")
|
||||
}
|
||||
default:
|
||||
return d.Skip()
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "decode ScriptPolicy")
|
||||
}
|
||||
// Validate required fields.
|
||||
var failures []validate.FieldError
|
||||
for i, mask := range [1]uint8{
|
||||
0b00001111,
|
||||
} {
|
||||
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
|
||||
// Mask only required fields and check equality to mask using XOR.
|
||||
//
|
||||
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
|
||||
// Bits of fields which would be set are actually bits of missed fields.
|
||||
missed := bits.OnesCount8(result)
|
||||
for bitN := 0; bitN < missed; bitN++ {
|
||||
bitIdx := bits.TrailingZeros8(result)
|
||||
fieldIdx := i*8 + bitIdx
|
||||
var name string
|
||||
if fieldIdx < len(jsonFieldsNameOfScriptPolicy) {
|
||||
name = jsonFieldsNameOfScriptPolicy[fieldIdx]
|
||||
} else {
|
||||
name = strconv.Itoa(fieldIdx)
|
||||
}
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: name,
|
||||
Error: validate.ErrFieldRequired,
|
||||
})
|
||||
// Reset bit.
|
||||
result &^= 1 << bitIdx
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s *ScriptPolicy) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *ScriptPolicy) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode implements json.Marshaler.
|
||||
func (s *ScriptPolicyCreate) Encode(e *jx.Encoder) {
|
||||
e.ObjStart()
|
||||
s.encodeFields(e)
|
||||
e.ObjEnd()
|
||||
}
|
||||
|
||||
// encodeFields encodes fields.
|
||||
func (s *ScriptPolicyCreate) encodeFields(e *jx.Encoder) {
|
||||
{
|
||||
e.FieldStart("FromScriptID")
|
||||
e.Int64(s.FromScriptID)
|
||||
}
|
||||
{
|
||||
e.FieldStart("ToScriptID")
|
||||
e.Int64(s.ToScriptID)
|
||||
}
|
||||
{
|
||||
e.FieldStart("Policy")
|
||||
e.Int32(s.Policy)
|
||||
}
|
||||
}
|
||||
|
||||
var jsonFieldsNameOfScriptPolicyCreate = [3]string{
|
||||
0: "FromScriptID",
|
||||
1: "ToScriptID",
|
||||
2: "Policy",
|
||||
}
|
||||
|
||||
// Decode decodes ScriptPolicyCreate from json.
|
||||
func (s *ScriptPolicyCreate) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode ScriptPolicyCreate to nil")
|
||||
}
|
||||
var requiredBitSet [1]uint8
|
||||
|
||||
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
|
||||
switch string(k) {
|
||||
case "FromScriptID":
|
||||
requiredBitSet[0] |= 1 << 0
|
||||
if err := func() error {
|
||||
v, err := d.Int64()
|
||||
s.FromScriptID = int64(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"FromScriptID\"")
|
||||
}
|
||||
case "ToScriptID":
|
||||
requiredBitSet[0] |= 1 << 1
|
||||
if err := func() error {
|
||||
v, err := d.Int64()
|
||||
s.ToScriptID = int64(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"ToScriptID\"")
|
||||
}
|
||||
case "Policy":
|
||||
requiredBitSet[0] |= 1 << 2
|
||||
if err := func() error {
|
||||
v, err := d.Int32()
|
||||
s.Policy = int32(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"Policy\"")
|
||||
}
|
||||
default:
|
||||
return d.Skip()
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "decode ScriptPolicyCreate")
|
||||
}
|
||||
// Validate required fields.
|
||||
var failures []validate.FieldError
|
||||
for i, mask := range [1]uint8{
|
||||
0b00000111,
|
||||
} {
|
||||
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
|
||||
// Mask only required fields and check equality to mask using XOR.
|
||||
//
|
||||
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
|
||||
// Bits of fields which would be set are actually bits of missed fields.
|
||||
missed := bits.OnesCount8(result)
|
||||
for bitN := 0; bitN < missed; bitN++ {
|
||||
bitIdx := bits.TrailingZeros8(result)
|
||||
fieldIdx := i*8 + bitIdx
|
||||
var name string
|
||||
if fieldIdx < len(jsonFieldsNameOfScriptPolicyCreate) {
|
||||
name = jsonFieldsNameOfScriptPolicyCreate[fieldIdx]
|
||||
} else {
|
||||
name = strconv.Itoa(fieldIdx)
|
||||
}
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: name,
|
||||
Error: validate.ErrFieldRequired,
|
||||
})
|
||||
// Reset bit.
|
||||
result &^= 1 << bitIdx
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s *ScriptPolicyCreate) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *ScriptPolicyCreate) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
)
|
||||
|
||||
// Labeler is used to allow adding custom attributes to the server request metrics.
|
||||
type Labeler struct {
|
||||
attrs []attribute.KeyValue
|
||||
}
|
||||
|
||||
// Add attributes to the Labeler.
|
||||
func (l *Labeler) Add(attrs ...attribute.KeyValue) {
|
||||
l.attrs = append(l.attrs, attrs...)
|
||||
}
|
||||
|
||||
// AttributeSet returns the attributes added to the Labeler as an attribute.Set.
|
||||
func (l *Labeler) AttributeSet() attribute.Set {
|
||||
return attribute.NewSet(l.attrs...)
|
||||
}
|
||||
|
||||
type labelerContextKey struct{}
|
||||
|
||||
// LabelerFromContext retrieves the Labeler from the provided context, if present.
|
||||
//
|
||||
// If no Labeler was found in the provided context a new, empty Labeler is returned and the second
|
||||
// return value is false. In this case it is safe to use the Labeler but any attributes added to
|
||||
// it will not be used.
|
||||
func LabelerFromContext(ctx context.Context) (*Labeler, bool) {
|
||||
if l, ok := ctx.Value(labelerContextKey{}).(*Labeler); ok {
|
||||
return l, true
|
||||
}
|
||||
return &Labeler{}, false
|
||||
}
|
||||
|
||||
func contextWithLabeler(ctx context.Context, l *Labeler) context.Context {
|
||||
return context.WithValue(ctx, labelerContextKey{}, l)
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"github.com/ogen-go/ogen/middleware"
|
||||
)
|
||||
|
||||
// Middleware is middleware type.
|
||||
type Middleware = middleware.Middleware
|
||||
@@ -1,22 +0,0 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
// OperationName is the ogen operation name
|
||||
type OperationName = string
|
||||
|
||||
const (
|
||||
ActionMapfixAcceptedOperation OperationName = "ActionMapfixAccepted"
|
||||
ActionMapfixUploadedOperation OperationName = "ActionMapfixUploaded"
|
||||
ActionMapfixValidatedOperation OperationName = "ActionMapfixValidated"
|
||||
ActionSubmissionAcceptedOperation OperationName = "ActionSubmissionAccepted"
|
||||
ActionSubmissionUploadedOperation OperationName = "ActionSubmissionUploaded"
|
||||
ActionSubmissionValidatedOperation OperationName = "ActionSubmissionValidated"
|
||||
CreateScriptOperation OperationName = "CreateScript"
|
||||
CreateScriptPolicyOperation OperationName = "CreateScriptPolicy"
|
||||
GetScriptOperation OperationName = "GetScript"
|
||||
ListScriptPolicyOperation OperationName = "ListScriptPolicy"
|
||||
ListScriptsOperation OperationName = "ListScripts"
|
||||
UpdateMapfixValidatedModelOperation OperationName = "UpdateMapfixValidatedModel"
|
||||
UpdateSubmissionValidatedModelOperation OperationName = "UpdateSubmissionValidatedModel"
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,150 +0,0 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"go.uber.org/multierr"
|
||||
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
)
|
||||
|
||||
func (s *Server) decodeCreateScriptRequest(r *http.Request) (
|
||||
req *ScriptCreate,
|
||||
close func() error,
|
||||
rerr error,
|
||||
) {
|
||||
var closers []func() error
|
||||
close = func() error {
|
||||
var merr error
|
||||
// Close in reverse order, to match defer behavior.
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
c := closers[i]
|
||||
merr = multierr.Append(merr, c())
|
||||
}
|
||||
return merr
|
||||
}
|
||||
defer func() {
|
||||
if rerr != nil {
|
||||
rerr = multierr.Append(rerr, close())
|
||||
}
|
||||
}()
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return req, close, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
if r.ContentLength == 0 {
|
||||
return req, close, validate.ErrBodyRequired
|
||||
}
|
||||
buf, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return req, close, err
|
||||
}
|
||||
|
||||
if len(buf) == 0 {
|
||||
return req, close, validate.ErrBodyRequired
|
||||
}
|
||||
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var request ScriptCreate
|
||||
if err := func() error {
|
||||
if err := request.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return req, close, err
|
||||
}
|
||||
if err := func() error {
|
||||
if err := request.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return req, close, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &request, close, nil
|
||||
default:
|
||||
return req, close, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) decodeCreateScriptPolicyRequest(r *http.Request) (
|
||||
req *ScriptPolicyCreate,
|
||||
close func() error,
|
||||
rerr error,
|
||||
) {
|
||||
var closers []func() error
|
||||
close = func() error {
|
||||
var merr error
|
||||
// Close in reverse order, to match defer behavior.
|
||||
for i := len(closers) - 1; i >= 0; i-- {
|
||||
c := closers[i]
|
||||
merr = multierr.Append(merr, c())
|
||||
}
|
||||
return merr
|
||||
}
|
||||
defer func() {
|
||||
if rerr != nil {
|
||||
rerr = multierr.Append(rerr, close())
|
||||
}
|
||||
}()
|
||||
ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return req, close, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
if r.ContentLength == 0 {
|
||||
return req, close, validate.ErrBodyRequired
|
||||
}
|
||||
buf, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return req, close, err
|
||||
}
|
||||
|
||||
if len(buf) == 0 {
|
||||
return req, close, validate.ErrBodyRequired
|
||||
}
|
||||
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var request ScriptPolicyCreate
|
||||
if err := func() error {
|
||||
if err := request.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return req, close, err
|
||||
}
|
||||
return &request, close, nil
|
||||
default:
|
||||
return req, close, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-faster/jx"
|
||||
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
)
|
||||
|
||||
func encodeCreateScriptRequest(
|
||||
req *ScriptCreate,
|
||||
r *http.Request,
|
||||
) error {
|
||||
const contentType = "application/json"
|
||||
e := new(jx.Encoder)
|
||||
{
|
||||
req.Encode(e)
|
||||
}
|
||||
encoded := e.Bytes()
|
||||
ht.SetBody(r, bytes.NewReader(encoded), contentType)
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeCreateScriptPolicyRequest(
|
||||
req *ScriptPolicyCreate,
|
||||
r *http.Request,
|
||||
) error {
|
||||
const contentType = "application/json"
|
||||
e := new(jx.Encoder)
|
||||
{
|
||||
req.Encode(e)
|
||||
}
|
||||
encoded := e.Bytes()
|
||||
ht.SetBody(r, bytes.NewReader(encoded), contentType)
|
||||
return nil
|
||||
}
|
||||
@@ -1,916 +0,0 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
)
|
||||
|
||||
func decodeActionMapfixAcceptedResponse(resp *http.Response) (res *ActionMapfixAcceptedNoContent, _ error) {
|
||||
switch resp.StatusCode {
|
||||
case 204:
|
||||
// Code 204.
|
||||
return &ActionMapfixAcceptedNoContent{}, nil
|
||||
}
|
||||
// Convenient error response.
|
||||
defRes, err := func() (res *ErrorStatusCode, err error) {
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response Error
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
return &ErrorStatusCode{
|
||||
StatusCode: resp.StatusCode,
|
||||
Response: response,
|
||||
}, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode)
|
||||
}
|
||||
return res, errors.Wrap(defRes, "error")
|
||||
}
|
||||
|
||||
func decodeActionMapfixUploadedResponse(resp *http.Response) (res *ActionMapfixUploadedNoContent, _ error) {
|
||||
switch resp.StatusCode {
|
||||
case 204:
|
||||
// Code 204.
|
||||
return &ActionMapfixUploadedNoContent{}, nil
|
||||
}
|
||||
// Convenient error response.
|
||||
defRes, err := func() (res *ErrorStatusCode, err error) {
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response Error
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
return &ErrorStatusCode{
|
||||
StatusCode: resp.StatusCode,
|
||||
Response: response,
|
||||
}, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode)
|
||||
}
|
||||
return res, errors.Wrap(defRes, "error")
|
||||
}
|
||||
|
||||
func decodeActionMapfixValidatedResponse(resp *http.Response) (res *ActionMapfixValidatedNoContent, _ error) {
|
||||
switch resp.StatusCode {
|
||||
case 204:
|
||||
// Code 204.
|
||||
return &ActionMapfixValidatedNoContent{}, nil
|
||||
}
|
||||
// Convenient error response.
|
||||
defRes, err := func() (res *ErrorStatusCode, err error) {
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response Error
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
return &ErrorStatusCode{
|
||||
StatusCode: resp.StatusCode,
|
||||
Response: response,
|
||||
}, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode)
|
||||
}
|
||||
return res, errors.Wrap(defRes, "error")
|
||||
}
|
||||
|
||||
func decodeActionSubmissionAcceptedResponse(resp *http.Response) (res *ActionSubmissionAcceptedNoContent, _ error) {
|
||||
switch resp.StatusCode {
|
||||
case 204:
|
||||
// Code 204.
|
||||
return &ActionSubmissionAcceptedNoContent{}, nil
|
||||
}
|
||||
// Convenient error response.
|
||||
defRes, err := func() (res *ErrorStatusCode, err error) {
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response Error
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
return &ErrorStatusCode{
|
||||
StatusCode: resp.StatusCode,
|
||||
Response: response,
|
||||
}, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode)
|
||||
}
|
||||
return res, errors.Wrap(defRes, "error")
|
||||
}
|
||||
|
||||
func decodeActionSubmissionUploadedResponse(resp *http.Response) (res *ActionSubmissionUploadedNoContent, _ error) {
|
||||
switch resp.StatusCode {
|
||||
case 204:
|
||||
// Code 204.
|
||||
return &ActionSubmissionUploadedNoContent{}, nil
|
||||
}
|
||||
// Convenient error response.
|
||||
defRes, err := func() (res *ErrorStatusCode, err error) {
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response Error
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
return &ErrorStatusCode{
|
||||
StatusCode: resp.StatusCode,
|
||||
Response: response,
|
||||
}, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode)
|
||||
}
|
||||
return res, errors.Wrap(defRes, "error")
|
||||
}
|
||||
|
||||
func decodeActionSubmissionValidatedResponse(resp *http.Response) (res *ActionSubmissionValidatedNoContent, _ error) {
|
||||
switch resp.StatusCode {
|
||||
case 204:
|
||||
// Code 204.
|
||||
return &ActionSubmissionValidatedNoContent{}, nil
|
||||
}
|
||||
// Convenient error response.
|
||||
defRes, err := func() (res *ErrorStatusCode, err error) {
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response Error
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
return &ErrorStatusCode{
|
||||
StatusCode: resp.StatusCode,
|
||||
Response: response,
|
||||
}, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode)
|
||||
}
|
||||
return res, errors.Wrap(defRes, "error")
|
||||
}
|
||||
|
||||
func decodeCreateScriptResponse(resp *http.Response) (res *ID, _ error) {
|
||||
switch resp.StatusCode {
|
||||
case 201:
|
||||
// Code 201.
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response ID
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
// Convenient error response.
|
||||
defRes, err := func() (res *ErrorStatusCode, err error) {
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response Error
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
return &ErrorStatusCode{
|
||||
StatusCode: resp.StatusCode,
|
||||
Response: response,
|
||||
}, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode)
|
||||
}
|
||||
return res, errors.Wrap(defRes, "error")
|
||||
}
|
||||
|
||||
func decodeCreateScriptPolicyResponse(resp *http.Response) (res *ID, _ error) {
|
||||
switch resp.StatusCode {
|
||||
case 201:
|
||||
// Code 201.
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response ID
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
// Convenient error response.
|
||||
defRes, err := func() (res *ErrorStatusCode, err error) {
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response Error
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
return &ErrorStatusCode{
|
||||
StatusCode: resp.StatusCode,
|
||||
Response: response,
|
||||
}, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode)
|
||||
}
|
||||
return res, errors.Wrap(defRes, "error")
|
||||
}
|
||||
|
||||
func decodeGetScriptResponse(resp *http.Response) (res *Script, _ error) {
|
||||
switch resp.StatusCode {
|
||||
case 200:
|
||||
// Code 200.
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response Script
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
// Validate response.
|
||||
if err := func() error {
|
||||
if err := response.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
// Convenient error response.
|
||||
defRes, err := func() (res *ErrorStatusCode, err error) {
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response Error
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
return &ErrorStatusCode{
|
||||
StatusCode: resp.StatusCode,
|
||||
Response: response,
|
||||
}, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode)
|
||||
}
|
||||
return res, errors.Wrap(defRes, "error")
|
||||
}
|
||||
|
||||
func decodeListScriptPolicyResponse(resp *http.Response) (res []ScriptPolicy, _ error) {
|
||||
switch resp.StatusCode {
|
||||
case 200:
|
||||
// Code 200.
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response []ScriptPolicy
|
||||
if err := func() error {
|
||||
response = make([]ScriptPolicy, 0)
|
||||
if err := d.Arr(func(d *jx.Decoder) error {
|
||||
var elem ScriptPolicy
|
||||
if err := elem.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
response = append(response, elem)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
// Validate response.
|
||||
if err := func() error {
|
||||
if response == nil {
|
||||
return errors.New("nil is invalid value")
|
||||
}
|
||||
var failures []validate.FieldError
|
||||
for i, elem := range response {
|
||||
if err := func() error {
|
||||
if err := elem.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: fmt.Sprintf("[%d]", i),
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "validate")
|
||||
}
|
||||
return response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
// Convenient error response.
|
||||
defRes, err := func() (res *ErrorStatusCode, err error) {
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response Error
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
return &ErrorStatusCode{
|
||||
StatusCode: resp.StatusCode,
|
||||
Response: response,
|
||||
}, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode)
|
||||
}
|
||||
return res, errors.Wrap(defRes, "error")
|
||||
}
|
||||
|
||||
func decodeListScriptsResponse(resp *http.Response) (res []Script, _ error) {
|
||||
switch resp.StatusCode {
|
||||
case 200:
|
||||
// Code 200.
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response []Script
|
||||
if err := func() error {
|
||||
response = make([]Script, 0)
|
||||
if err := d.Arr(func(d *jx.Decoder) error {
|
||||
var elem Script
|
||||
if err := elem.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
response = append(response, elem)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
// Validate response.
|
||||
if err := func() error {
|
||||
if response == nil {
|
||||
return errors.New("nil is invalid value")
|
||||
}
|
||||
var failures []validate.FieldError
|
||||
for i, elem := range response {
|
||||
if err := func() error {
|
||||
if err := elem.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: fmt.Sprintf("[%d]", i),
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "validate")
|
||||
}
|
||||
return response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
// Convenient error response.
|
||||
defRes, err := func() (res *ErrorStatusCode, err error) {
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response Error
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
return &ErrorStatusCode{
|
||||
StatusCode: resp.StatusCode,
|
||||
Response: response,
|
||||
}, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode)
|
||||
}
|
||||
return res, errors.Wrap(defRes, "error")
|
||||
}
|
||||
|
||||
func decodeUpdateMapfixValidatedModelResponse(resp *http.Response) (res *UpdateMapfixValidatedModelNoContent, _ error) {
|
||||
switch resp.StatusCode {
|
||||
case 204:
|
||||
// Code 204.
|
||||
return &UpdateMapfixValidatedModelNoContent{}, nil
|
||||
}
|
||||
// Convenient error response.
|
||||
defRes, err := func() (res *ErrorStatusCode, err error) {
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response Error
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
return &ErrorStatusCode{
|
||||
StatusCode: resp.StatusCode,
|
||||
Response: response,
|
||||
}, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode)
|
||||
}
|
||||
return res, errors.Wrap(defRes, "error")
|
||||
}
|
||||
|
||||
func decodeUpdateSubmissionValidatedModelResponse(resp *http.Response) (res *UpdateSubmissionValidatedModelNoContent, _ error) {
|
||||
switch resp.StatusCode {
|
||||
case 204:
|
||||
// Code 204.
|
||||
return &UpdateSubmissionValidatedModelNoContent{}, nil
|
||||
}
|
||||
// Convenient error response.
|
||||
defRes, err := func() (res *ErrorStatusCode, err error) {
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response Error
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
return &ErrorStatusCode{
|
||||
StatusCode: resp.StatusCode,
|
||||
Response: response,
|
||||
}, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode)
|
||||
}
|
||||
return res, errors.Wrap(defRes, "error")
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
"github.com/go-faster/jx"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
)
|
||||
|
||||
func encodeActionMapfixAcceptedResponse(response *ActionMapfixAcceptedNoContent, w http.ResponseWriter, span trace.Span) error {
|
||||
w.WriteHeader(204)
|
||||
span.SetStatus(codes.Ok, http.StatusText(204))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeActionMapfixUploadedResponse(response *ActionMapfixUploadedNoContent, w http.ResponseWriter, span trace.Span) error {
|
||||
w.WriteHeader(204)
|
||||
span.SetStatus(codes.Ok, http.StatusText(204))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeActionMapfixValidatedResponse(response *ActionMapfixValidatedNoContent, w http.ResponseWriter, span trace.Span) error {
|
||||
w.WriteHeader(204)
|
||||
span.SetStatus(codes.Ok, http.StatusText(204))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeActionSubmissionAcceptedResponse(response *ActionSubmissionAcceptedNoContent, w http.ResponseWriter, span trace.Span) error {
|
||||
w.WriteHeader(204)
|
||||
span.SetStatus(codes.Ok, http.StatusText(204))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeActionSubmissionUploadedResponse(response *ActionSubmissionUploadedNoContent, w http.ResponseWriter, span trace.Span) error {
|
||||
w.WriteHeader(204)
|
||||
span.SetStatus(codes.Ok, http.StatusText(204))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeActionSubmissionValidatedResponse(response *ActionSubmissionValidatedNoContent, w http.ResponseWriter, span trace.Span) error {
|
||||
w.WriteHeader(204)
|
||||
span.SetStatus(codes.Ok, http.StatusText(204))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeCreateScriptResponse(response *ID, w http.ResponseWriter, span trace.Span) error {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(201)
|
||||
span.SetStatus(codes.Ok, http.StatusText(201))
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeCreateScriptPolicyResponse(response *ID, w http.ResponseWriter, span trace.Span) error {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(201)
|
||||
span.SetStatus(codes.Ok, http.StatusText(201))
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeGetScriptResponse(response *Script, w http.ResponseWriter, span trace.Span) error {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(200)
|
||||
span.SetStatus(codes.Ok, http.StatusText(200))
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeListScriptPolicyResponse(response []ScriptPolicy, w http.ResponseWriter, span trace.Span) error {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(200)
|
||||
span.SetStatus(codes.Ok, http.StatusText(200))
|
||||
|
||||
e := new(jx.Encoder)
|
||||
e.ArrStart()
|
||||
for _, elem := range response {
|
||||
elem.Encode(e)
|
||||
}
|
||||
e.ArrEnd()
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeListScriptsResponse(response []Script, w http.ResponseWriter, span trace.Span) error {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(200)
|
||||
span.SetStatus(codes.Ok, http.StatusText(200))
|
||||
|
||||
e := new(jx.Encoder)
|
||||
e.ArrStart()
|
||||
for _, elem := range response {
|
||||
elem.Encode(e)
|
||||
}
|
||||
e.ArrEnd()
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeUpdateMapfixValidatedModelResponse(response *UpdateMapfixValidatedModelNoContent, w http.ResponseWriter, span trace.Span) error {
|
||||
w.WriteHeader(204)
|
||||
span.SetStatus(codes.Ok, http.StatusText(204))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeUpdateSubmissionValidatedModelResponse(response *UpdateSubmissionValidatedModelNoContent, w http.ResponseWriter, span trace.Span) error {
|
||||
w.WriteHeader(204)
|
||||
span.SetStatus(codes.Ok, http.StatusText(204))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeErrorResponse(response *ErrorStatusCode, w http.ResponseWriter, span trace.Span) error {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
code := response.StatusCode
|
||||
if code == 0 {
|
||||
// Set default status code.
|
||||
code = http.StatusOK
|
||||
}
|
||||
w.WriteHeader(code)
|
||||
if st := http.StatusText(code); code >= http.StatusBadRequest {
|
||||
span.SetStatus(codes.Error, st)
|
||||
} else {
|
||||
span.SetStatus(codes.Ok, st)
|
||||
}
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
if code >= http.StatusInternalServerError {
|
||||
return errors.Wrapf(ht.ErrInternalServerErrorResponse, "code: %d, message: %s", code, http.StatusText(code))
|
||||
}
|
||||
return nil
|
||||
|
||||
}
|
||||
@@ -1,965 +0,0 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
)
|
||||
|
||||
func (s *Server) cutPrefix(path string) (string, bool) {
|
||||
prefix := s.cfg.Prefix
|
||||
if prefix == "" {
|
||||
return path, true
|
||||
}
|
||||
if !strings.HasPrefix(path, prefix) {
|
||||
// Prefix doesn't match.
|
||||
return "", false
|
||||
}
|
||||
// Cut prefix from the path.
|
||||
return strings.TrimPrefix(path, prefix), true
|
||||
}
|
||||
|
||||
// ServeHTTP serves http request as defined by OpenAPI v3 specification,
|
||||
// calling handler that matches the path or returning not found error.
|
||||
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
elem := r.URL.Path
|
||||
elemIsEscaped := false
|
||||
if rawPath := r.URL.RawPath; rawPath != "" {
|
||||
if normalized, ok := uri.NormalizeEscapedPath(rawPath); ok {
|
||||
elem = normalized
|
||||
elemIsEscaped = strings.ContainsRune(elem, '%')
|
||||
}
|
||||
}
|
||||
|
||||
elem, ok := s.cutPrefix(elem)
|
||||
if !ok || len(elem) == 0 {
|
||||
s.notFound(w, r)
|
||||
return
|
||||
}
|
||||
args := [1]string{}
|
||||
|
||||
// Static code generated router with unwrapped path search.
|
||||
switch {
|
||||
default:
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/"
|
||||
|
||||
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'm': // Prefix: "mapfixes/"
|
||||
|
||||
if l := len("mapfixes/"); len(elem) >= l && elem[0:l] == "mapfixes/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "MapfixID"
|
||||
// Match until "/"
|
||||
idx := strings.IndexByte(elem, '/')
|
||||
if idx < 0 {
|
||||
idx = len(elem)
|
||||
}
|
||||
args[0] = elem[:idx]
|
||||
elem = elem[idx:]
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/"
|
||||
|
||||
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 's': // Prefix: "status/validator-"
|
||||
|
||||
if l := len("status/validator-"); len(elem) >= l && elem[0:l] == "status/validator-" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'f': // Prefix: "failed"
|
||||
|
||||
if l := len("failed"); len(elem) >= l && elem[0:l] == "failed" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
s.handleActionMapfixAcceptedRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, "POST")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
case 'u': // Prefix: "uploaded"
|
||||
|
||||
if l := len("uploaded"); len(elem) >= l && elem[0:l] == "uploaded" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
s.handleActionMapfixUploadedRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, "POST")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
case 'v': // Prefix: "validated"
|
||||
|
||||
if l := len("validated"); len(elem) >= l && elem[0:l] == "validated" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
s.handleActionMapfixValidatedRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, "POST")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 'v': // Prefix: "validated-model"
|
||||
|
||||
if l := len("validated-model"); len(elem) >= l && elem[0:l] == "validated-model" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
s.handleUpdateMapfixValidatedModelRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, "POST")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 's': // Prefix: "s"
|
||||
|
||||
if l := len("s"); len(elem) >= l && elem[0:l] == "s" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'c': // Prefix: "cript"
|
||||
|
||||
if l := len("cript"); len(elem) >= l && elem[0:l] == "cript" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '-': // Prefix: "-policy"
|
||||
|
||||
if l := len("-policy"); len(elem) >= l && elem[0:l] == "-policy" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleListScriptPolicyRequest([0]string{}, elemIsEscaped, w, r)
|
||||
case "POST":
|
||||
s.handleCreateScriptPolicyRequest([0]string{}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, "GET,POST")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
case 's': // Prefix: "s"
|
||||
|
||||
if l := len("s"); len(elem) >= l && elem[0:l] == "s" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleListScriptsRequest([0]string{}, elemIsEscaped, w, r)
|
||||
case "POST":
|
||||
s.handleCreateScriptRequest([0]string{}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, "GET,POST")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/"
|
||||
|
||||
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "ScriptID"
|
||||
// Leaf parameter, slashes are prohibited
|
||||
idx := strings.IndexByte(elem, '/')
|
||||
if idx >= 0 {
|
||||
break
|
||||
}
|
||||
args[0] = elem
|
||||
elem = ""
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleGetScriptRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, "GET")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 'u': // Prefix: "ubmissions/"
|
||||
|
||||
if l := len("ubmissions/"); len(elem) >= l && elem[0:l] == "ubmissions/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "SubmissionID"
|
||||
// Match until "/"
|
||||
idx := strings.IndexByte(elem, '/')
|
||||
if idx < 0 {
|
||||
idx = len(elem)
|
||||
}
|
||||
args[0] = elem[:idx]
|
||||
elem = elem[idx:]
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/"
|
||||
|
||||
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 's': // Prefix: "status/validator-"
|
||||
|
||||
if l := len("status/validator-"); len(elem) >= l && elem[0:l] == "status/validator-" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'f': // Prefix: "failed"
|
||||
|
||||
if l := len("failed"); len(elem) >= l && elem[0:l] == "failed" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
s.handleActionSubmissionAcceptedRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, "POST")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
case 'u': // Prefix: "uploaded"
|
||||
|
||||
if l := len("uploaded"); len(elem) >= l && elem[0:l] == "uploaded" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
s.handleActionSubmissionUploadedRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, "POST")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
case 'v': // Prefix: "validated"
|
||||
|
||||
if l := len("validated"); len(elem) >= l && elem[0:l] == "validated" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
s.handleActionSubmissionValidatedRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, "POST")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 'v': // Prefix: "validated-model"
|
||||
|
||||
if l := len("validated-model"); len(elem) >= l && elem[0:l] == "validated-model" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
s.handleUpdateSubmissionValidatedModelRequest([1]string{
|
||||
args[0],
|
||||
}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, "POST")
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
s.notFound(w, r)
|
||||
}
|
||||
|
||||
// Route is route object.
|
||||
type Route struct {
|
||||
name string
|
||||
summary string
|
||||
operationID string
|
||||
pathPattern string
|
||||
count int
|
||||
args [1]string
|
||||
}
|
||||
|
||||
// Name returns ogen operation name.
|
||||
//
|
||||
// It is guaranteed to be unique and not empty.
|
||||
func (r Route) Name() string {
|
||||
return r.name
|
||||
}
|
||||
|
||||
// Summary returns OpenAPI summary.
|
||||
func (r Route) Summary() string {
|
||||
return r.summary
|
||||
}
|
||||
|
||||
// OperationID returns OpenAPI operationId.
|
||||
func (r Route) OperationID() string {
|
||||
return r.operationID
|
||||
}
|
||||
|
||||
// PathPattern returns OpenAPI path.
|
||||
func (r Route) PathPattern() string {
|
||||
return r.pathPattern
|
||||
}
|
||||
|
||||
// Args returns parsed arguments.
|
||||
func (r Route) Args() []string {
|
||||
return r.args[:r.count]
|
||||
}
|
||||
|
||||
// FindRoute finds Route for given method and path.
|
||||
//
|
||||
// Note: this method does not unescape path or handle reserved characters in path properly. Use FindPath instead.
|
||||
func (s *Server) FindRoute(method, path string) (Route, bool) {
|
||||
return s.FindPath(method, &url.URL{Path: path})
|
||||
}
|
||||
|
||||
// FindPath finds Route for given method and URL.
|
||||
func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
|
||||
var (
|
||||
elem = u.Path
|
||||
args = r.args
|
||||
)
|
||||
if rawPath := u.RawPath; rawPath != "" {
|
||||
if normalized, ok := uri.NormalizeEscapedPath(rawPath); ok {
|
||||
elem = normalized
|
||||
}
|
||||
defer func() {
|
||||
for i, arg := range r.args[:r.count] {
|
||||
if unescaped, err := url.PathUnescape(arg); err == nil {
|
||||
r.args[i] = unescaped
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
elem, ok := s.cutPrefix(elem)
|
||||
if !ok {
|
||||
return r, false
|
||||
}
|
||||
|
||||
// Static code generated router with unwrapped path search.
|
||||
switch {
|
||||
default:
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/"
|
||||
|
||||
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'm': // Prefix: "mapfixes/"
|
||||
|
||||
if l := len("mapfixes/"); len(elem) >= l && elem[0:l] == "mapfixes/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "MapfixID"
|
||||
// Match until "/"
|
||||
idx := strings.IndexByte(elem, '/')
|
||||
if idx < 0 {
|
||||
idx = len(elem)
|
||||
}
|
||||
args[0] = elem[:idx]
|
||||
elem = elem[idx:]
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/"
|
||||
|
||||
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 's': // Prefix: "status/validator-"
|
||||
|
||||
if l := len("status/validator-"); len(elem) >= l && elem[0:l] == "status/validator-" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'f': // Prefix: "failed"
|
||||
|
||||
if l := len("failed"); len(elem) >= l && elem[0:l] == "failed" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "POST":
|
||||
r.name = ActionMapfixAcceptedOperation
|
||||
r.summary = "(Internal endpoint) Role Validator changes status from Validating -> Accepted"
|
||||
r.operationID = "actionMapfixAccepted"
|
||||
r.pathPattern = "/mapfixes/{MapfixID}/status/validator-failed"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
case 'u': // Prefix: "uploaded"
|
||||
|
||||
if l := len("uploaded"); len(elem) >= l && elem[0:l] == "uploaded" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "POST":
|
||||
r.name = ActionMapfixUploadedOperation
|
||||
r.summary = "(Internal endpoint) Role Validator changes status from Uploading -> Uploaded"
|
||||
r.operationID = "actionMapfixUploaded"
|
||||
r.pathPattern = "/mapfixes/{MapfixID}/status/validator-uploaded"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
case 'v': // Prefix: "validated"
|
||||
|
||||
if l := len("validated"); len(elem) >= l && elem[0:l] == "validated" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "POST":
|
||||
r.name = ActionMapfixValidatedOperation
|
||||
r.summary = "(Internal endpoint) Role Validator changes status from Validating -> Validated"
|
||||
r.operationID = "actionMapfixValidated"
|
||||
r.pathPattern = "/mapfixes/{MapfixID}/status/validator-validated"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 'v': // Prefix: "validated-model"
|
||||
|
||||
if l := len("validated-model"); len(elem) >= l && elem[0:l] == "validated-model" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "POST":
|
||||
r.name = UpdateMapfixValidatedModelOperation
|
||||
r.summary = "Update validated model"
|
||||
r.operationID = "updateMapfixValidatedModel"
|
||||
r.pathPattern = "/mapfixes/{MapfixID}/validated-model"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 's': // Prefix: "s"
|
||||
|
||||
if l := len("s"); len(elem) >= l && elem[0:l] == "s" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'c': // Prefix: "cript"
|
||||
|
||||
if l := len("cript"); len(elem) >= l && elem[0:l] == "cript" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '-': // Prefix: "-policy"
|
||||
|
||||
if l := len("-policy"); len(elem) >= l && elem[0:l] == "-policy" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = ListScriptPolicyOperation
|
||||
r.summary = "Get list of script policies"
|
||||
r.operationID = "listScriptPolicy"
|
||||
r.pathPattern = "/script-policy"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
case "POST":
|
||||
r.name = CreateScriptPolicyOperation
|
||||
r.summary = "Create a new script policy"
|
||||
r.operationID = "createScriptPolicy"
|
||||
r.pathPattern = "/script-policy"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
case 's': // Prefix: "s"
|
||||
|
||||
if l := len("s"); len(elem) >= l && elem[0:l] == "s" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = ListScriptsOperation
|
||||
r.summary = "Get list of scripts"
|
||||
r.operationID = "listScripts"
|
||||
r.pathPattern = "/scripts"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
case "POST":
|
||||
r.name = CreateScriptOperation
|
||||
r.summary = "Create a new script"
|
||||
r.operationID = "createScript"
|
||||
r.pathPattern = "/scripts"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/"
|
||||
|
||||
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "ScriptID"
|
||||
// Leaf parameter, slashes are prohibited
|
||||
idx := strings.IndexByte(elem, '/')
|
||||
if idx >= 0 {
|
||||
break
|
||||
}
|
||||
args[0] = elem
|
||||
elem = ""
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = GetScriptOperation
|
||||
r.summary = "Get the specified script by ID"
|
||||
r.operationID = "getScript"
|
||||
r.pathPattern = "/scripts/{ScriptID}"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 'u': // Prefix: "ubmissions/"
|
||||
|
||||
if l := len("ubmissions/"); len(elem) >= l && elem[0:l] == "ubmissions/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
// Param: "SubmissionID"
|
||||
// Match until "/"
|
||||
idx := strings.IndexByte(elem, '/')
|
||||
if idx < 0 {
|
||||
idx = len(elem)
|
||||
}
|
||||
args[0] = elem[:idx]
|
||||
elem = elem[idx:]
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/"
|
||||
|
||||
if l := len("/"); len(elem) >= l && elem[0:l] == "/" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 's': // Prefix: "status/validator-"
|
||||
|
||||
if l := len("status/validator-"); len(elem) >= l && elem[0:l] == "status/validator-" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
break
|
||||
}
|
||||
switch elem[0] {
|
||||
case 'f': // Prefix: "failed"
|
||||
|
||||
if l := len("failed"); len(elem) >= l && elem[0:l] == "failed" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "POST":
|
||||
r.name = ActionSubmissionAcceptedOperation
|
||||
r.summary = "(Internal endpoint) Role Validator changes status from Validating -> Accepted"
|
||||
r.operationID = "actionSubmissionAccepted"
|
||||
r.pathPattern = "/submissions/{SubmissionID}/status/validator-failed"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
case 'u': // Prefix: "uploaded"
|
||||
|
||||
if l := len("uploaded"); len(elem) >= l && elem[0:l] == "uploaded" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "POST":
|
||||
r.name = ActionSubmissionUploadedOperation
|
||||
r.summary = "(Internal endpoint) Role Validator changes status from Uploading -> Uploaded"
|
||||
r.operationID = "actionSubmissionUploaded"
|
||||
r.pathPattern = "/submissions/{SubmissionID}/status/validator-uploaded"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
case 'v': // Prefix: "validated"
|
||||
|
||||
if l := len("validated"); len(elem) >= l && elem[0:l] == "validated" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "POST":
|
||||
r.name = ActionSubmissionValidatedOperation
|
||||
r.summary = "(Internal endpoint) Role Validator changes status from Validating -> Validated"
|
||||
r.operationID = "actionSubmissionValidated"
|
||||
r.pathPattern = "/submissions/{SubmissionID}/status/validator-validated"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
case 'v': // Prefix: "validated-model"
|
||||
|
||||
if l := len("validated-model"); len(elem) >= l && elem[0:l] == "validated-model" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "POST":
|
||||
r.name = UpdateSubmissionValidatedModelOperation
|
||||
r.summary = "Update validated model"
|
||||
r.operationID = "updateSubmissionValidatedModel"
|
||||
r.pathPattern = "/submissions/{SubmissionID}/validated-model"
|
||||
r.args = args
|
||||
r.count = 1
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return r, false
|
||||
}
|
||||
@@ -1,444 +0,0 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func (s *ErrorStatusCode) Error() string {
|
||||
return fmt.Sprintf("code %d: %+v", s.StatusCode, s.Response)
|
||||
}
|
||||
|
||||
// ActionMapfixAcceptedNoContent is response for ActionMapfixAccepted operation.
|
||||
type ActionMapfixAcceptedNoContent struct{}
|
||||
|
||||
// ActionMapfixUploadedNoContent is response for ActionMapfixUploaded operation.
|
||||
type ActionMapfixUploadedNoContent struct{}
|
||||
|
||||
// ActionMapfixValidatedNoContent is response for ActionMapfixValidated operation.
|
||||
type ActionMapfixValidatedNoContent struct{}
|
||||
|
||||
// ActionSubmissionAcceptedNoContent is response for ActionSubmissionAccepted operation.
|
||||
type ActionSubmissionAcceptedNoContent struct{}
|
||||
|
||||
// ActionSubmissionUploadedNoContent is response for ActionSubmissionUploaded operation.
|
||||
type ActionSubmissionUploadedNoContent struct{}
|
||||
|
||||
// ActionSubmissionValidatedNoContent is response for ActionSubmissionValidated operation.
|
||||
type ActionSubmissionValidatedNoContent struct{}
|
||||
|
||||
// Represents error object.
|
||||
// Ref: #/components/schemas/Error
|
||||
type Error struct {
|
||||
Code int64 `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// GetCode returns the value of Code.
|
||||
func (s *Error) GetCode() int64 {
|
||||
return s.Code
|
||||
}
|
||||
|
||||
// GetMessage returns the value of Message.
|
||||
func (s *Error) GetMessage() string {
|
||||
return s.Message
|
||||
}
|
||||
|
||||
// SetCode sets the value of Code.
|
||||
func (s *Error) SetCode(val int64) {
|
||||
s.Code = val
|
||||
}
|
||||
|
||||
// SetMessage sets the value of Message.
|
||||
func (s *Error) SetMessage(val string) {
|
||||
s.Message = val
|
||||
}
|
||||
|
||||
// ErrorStatusCode wraps Error with StatusCode.
|
||||
type ErrorStatusCode struct {
|
||||
StatusCode int
|
||||
Response Error
|
||||
}
|
||||
|
||||
// GetStatusCode returns the value of StatusCode.
|
||||
func (s *ErrorStatusCode) GetStatusCode() int {
|
||||
return s.StatusCode
|
||||
}
|
||||
|
||||
// GetResponse returns the value of Response.
|
||||
func (s *ErrorStatusCode) GetResponse() Error {
|
||||
return s.Response
|
||||
}
|
||||
|
||||
// SetStatusCode sets the value of StatusCode.
|
||||
func (s *ErrorStatusCode) SetStatusCode(val int) {
|
||||
s.StatusCode = val
|
||||
}
|
||||
|
||||
// SetResponse sets the value of Response.
|
||||
func (s *ErrorStatusCode) SetResponse(val Error) {
|
||||
s.Response = val
|
||||
}
|
||||
|
||||
// Ref: #/components/schemas/Id
|
||||
type ID struct {
|
||||
ID int64 `json:"ID"`
|
||||
}
|
||||
|
||||
// GetID returns the value of ID.
|
||||
func (s *ID) GetID() int64 {
|
||||
return s.ID
|
||||
}
|
||||
|
||||
// SetID sets the value of ID.
|
||||
func (s *ID) SetID(val int64) {
|
||||
s.ID = val
|
||||
}
|
||||
|
||||
// NewOptInt32 returns new OptInt32 with value set to v.
|
||||
func NewOptInt32(v int32) OptInt32 {
|
||||
return OptInt32{
|
||||
Value: v,
|
||||
Set: true,
|
||||
}
|
||||
}
|
||||
|
||||
// OptInt32 is optional int32.
|
||||
type OptInt32 struct {
|
||||
Value int32
|
||||
Set bool
|
||||
}
|
||||
|
||||
// IsSet returns true if OptInt32 was set.
|
||||
func (o OptInt32) IsSet() bool { return o.Set }
|
||||
|
||||
// Reset unsets value.
|
||||
func (o *OptInt32) Reset() {
|
||||
var v int32
|
||||
o.Value = v
|
||||
o.Set = false
|
||||
}
|
||||
|
||||
// SetTo sets value to v.
|
||||
func (o *OptInt32) SetTo(v int32) {
|
||||
o.Set = true
|
||||
o.Value = v
|
||||
}
|
||||
|
||||
// Get returns value and boolean that denotes whether value was set.
|
||||
func (o OptInt32) Get() (v int32, ok bool) {
|
||||
if !o.Set {
|
||||
return v, false
|
||||
}
|
||||
return o.Value, true
|
||||
}
|
||||
|
||||
// Or returns value if set, or given parameter if does not.
|
||||
func (o OptInt32) Or(d int32) int32 {
|
||||
if v, ok := o.Get(); ok {
|
||||
return v
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// NewOptInt64 returns new OptInt64 with value set to v.
|
||||
func NewOptInt64(v int64) OptInt64 {
|
||||
return OptInt64{
|
||||
Value: v,
|
||||
Set: true,
|
||||
}
|
||||
}
|
||||
|
||||
// OptInt64 is optional int64.
|
||||
type OptInt64 struct {
|
||||
Value int64
|
||||
Set bool
|
||||
}
|
||||
|
||||
// IsSet returns true if OptInt64 was set.
|
||||
func (o OptInt64) IsSet() bool { return o.Set }
|
||||
|
||||
// Reset unsets value.
|
||||
func (o *OptInt64) Reset() {
|
||||
var v int64
|
||||
o.Value = v
|
||||
o.Set = false
|
||||
}
|
||||
|
||||
// SetTo sets value to v.
|
||||
func (o *OptInt64) SetTo(v int64) {
|
||||
o.Set = true
|
||||
o.Value = v
|
||||
}
|
||||
|
||||
// Get returns value and boolean that denotes whether value was set.
|
||||
func (o OptInt64) Get() (v int64, ok bool) {
|
||||
if !o.Set {
|
||||
return v, false
|
||||
}
|
||||
return o.Value, true
|
||||
}
|
||||
|
||||
// Or returns value if set, or given parameter if does not.
|
||||
func (o OptInt64) Or(d int64) int64 {
|
||||
if v, ok := o.Get(); ok {
|
||||
return v
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// NewOptString returns new OptString with value set to v.
|
||||
func NewOptString(v string) OptString {
|
||||
return OptString{
|
||||
Value: v,
|
||||
Set: true,
|
||||
}
|
||||
}
|
||||
|
||||
// OptString is optional string.
|
||||
type OptString struct {
|
||||
Value string
|
||||
Set bool
|
||||
}
|
||||
|
||||
// IsSet returns true if OptString was set.
|
||||
func (o OptString) IsSet() bool { return o.Set }
|
||||
|
||||
// Reset unsets value.
|
||||
func (o *OptString) Reset() {
|
||||
var v string
|
||||
o.Value = v
|
||||
o.Set = false
|
||||
}
|
||||
|
||||
// SetTo sets value to v.
|
||||
func (o *OptString) SetTo(v string) {
|
||||
o.Set = true
|
||||
o.Value = v
|
||||
}
|
||||
|
||||
// Get returns value and boolean that denotes whether value was set.
|
||||
func (o OptString) Get() (v string, ok bool) {
|
||||
if !o.Set {
|
||||
return v, false
|
||||
}
|
||||
return o.Value, true
|
||||
}
|
||||
|
||||
// Or returns value if set, or given parameter if does not.
|
||||
func (o OptString) Or(d string) string {
|
||||
if v, ok := o.Get(); ok {
|
||||
return v
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// Ref: #/components/schemas/Script
|
||||
type Script struct {
|
||||
ID int64 `json:"ID"`
|
||||
Name string `json:"Name"`
|
||||
Hash string `json:"Hash"`
|
||||
Source string `json:"Source"`
|
||||
ResourceType int32 `json:"ResourceType"`
|
||||
ResourceID int64 `json:"ResourceID"`
|
||||
}
|
||||
|
||||
// GetID returns the value of ID.
|
||||
func (s *Script) GetID() int64 {
|
||||
return s.ID
|
||||
}
|
||||
|
||||
// GetName returns the value of Name.
|
||||
func (s *Script) GetName() string {
|
||||
return s.Name
|
||||
}
|
||||
|
||||
// GetHash returns the value of Hash.
|
||||
func (s *Script) GetHash() string {
|
||||
return s.Hash
|
||||
}
|
||||
|
||||
// GetSource returns the value of Source.
|
||||
func (s *Script) GetSource() string {
|
||||
return s.Source
|
||||
}
|
||||
|
||||
// GetResourceType returns the value of ResourceType.
|
||||
func (s *Script) GetResourceType() int32 {
|
||||
return s.ResourceType
|
||||
}
|
||||
|
||||
// GetResourceID returns the value of ResourceID.
|
||||
func (s *Script) GetResourceID() int64 {
|
||||
return s.ResourceID
|
||||
}
|
||||
|
||||
// SetID sets the value of ID.
|
||||
func (s *Script) SetID(val int64) {
|
||||
s.ID = val
|
||||
}
|
||||
|
||||
// SetName sets the value of Name.
|
||||
func (s *Script) SetName(val string) {
|
||||
s.Name = val
|
||||
}
|
||||
|
||||
// SetHash sets the value of Hash.
|
||||
func (s *Script) SetHash(val string) {
|
||||
s.Hash = val
|
||||
}
|
||||
|
||||
// SetSource sets the value of Source.
|
||||
func (s *Script) SetSource(val string) {
|
||||
s.Source = val
|
||||
}
|
||||
|
||||
// SetResourceType sets the value of ResourceType.
|
||||
func (s *Script) SetResourceType(val int32) {
|
||||
s.ResourceType = val
|
||||
}
|
||||
|
||||
// SetResourceID sets the value of ResourceID.
|
||||
func (s *Script) SetResourceID(val int64) {
|
||||
s.ResourceID = val
|
||||
}
|
||||
|
||||
// Ref: #/components/schemas/ScriptCreate
|
||||
type ScriptCreate struct {
|
||||
Name string `json:"Name"`
|
||||
Source string `json:"Source"`
|
||||
ResourceType int32 `json:"ResourceType"`
|
||||
ResourceID OptInt64 `json:"ResourceID"`
|
||||
}
|
||||
|
||||
// GetName returns the value of Name.
|
||||
func (s *ScriptCreate) GetName() string {
|
||||
return s.Name
|
||||
}
|
||||
|
||||
// GetSource returns the value of Source.
|
||||
func (s *ScriptCreate) GetSource() string {
|
||||
return s.Source
|
||||
}
|
||||
|
||||
// GetResourceType returns the value of ResourceType.
|
||||
func (s *ScriptCreate) GetResourceType() int32 {
|
||||
return s.ResourceType
|
||||
}
|
||||
|
||||
// GetResourceID returns the value of ResourceID.
|
||||
func (s *ScriptCreate) GetResourceID() OptInt64 {
|
||||
return s.ResourceID
|
||||
}
|
||||
|
||||
// SetName sets the value of Name.
|
||||
func (s *ScriptCreate) SetName(val string) {
|
||||
s.Name = val
|
||||
}
|
||||
|
||||
// SetSource sets the value of Source.
|
||||
func (s *ScriptCreate) SetSource(val string) {
|
||||
s.Source = val
|
||||
}
|
||||
|
||||
// SetResourceType sets the value of ResourceType.
|
||||
func (s *ScriptCreate) SetResourceType(val int32) {
|
||||
s.ResourceType = val
|
||||
}
|
||||
|
||||
// SetResourceID sets the value of ResourceID.
|
||||
func (s *ScriptCreate) SetResourceID(val OptInt64) {
|
||||
s.ResourceID = val
|
||||
}
|
||||
|
||||
// Ref: #/components/schemas/ScriptPolicy
|
||||
type ScriptPolicy struct {
|
||||
ID int64 `json:"ID"`
|
||||
FromScriptHash string `json:"FromScriptHash"`
|
||||
ToScriptID int64 `json:"ToScriptID"`
|
||||
Policy int32 `json:"Policy"`
|
||||
}
|
||||
|
||||
// GetID returns the value of ID.
|
||||
func (s *ScriptPolicy) GetID() int64 {
|
||||
return s.ID
|
||||
}
|
||||
|
||||
// GetFromScriptHash returns the value of FromScriptHash.
|
||||
func (s *ScriptPolicy) GetFromScriptHash() string {
|
||||
return s.FromScriptHash
|
||||
}
|
||||
|
||||
// GetToScriptID returns the value of ToScriptID.
|
||||
func (s *ScriptPolicy) GetToScriptID() int64 {
|
||||
return s.ToScriptID
|
||||
}
|
||||
|
||||
// GetPolicy returns the value of Policy.
|
||||
func (s *ScriptPolicy) GetPolicy() int32 {
|
||||
return s.Policy
|
||||
}
|
||||
|
||||
// SetID sets the value of ID.
|
||||
func (s *ScriptPolicy) SetID(val int64) {
|
||||
s.ID = val
|
||||
}
|
||||
|
||||
// SetFromScriptHash sets the value of FromScriptHash.
|
||||
func (s *ScriptPolicy) SetFromScriptHash(val string) {
|
||||
s.FromScriptHash = val
|
||||
}
|
||||
|
||||
// SetToScriptID sets the value of ToScriptID.
|
||||
func (s *ScriptPolicy) SetToScriptID(val int64) {
|
||||
s.ToScriptID = val
|
||||
}
|
||||
|
||||
// SetPolicy sets the value of Policy.
|
||||
func (s *ScriptPolicy) SetPolicy(val int32) {
|
||||
s.Policy = val
|
||||
}
|
||||
|
||||
// Ref: #/components/schemas/ScriptPolicyCreate
|
||||
type ScriptPolicyCreate struct {
|
||||
FromScriptID int64 `json:"FromScriptID"`
|
||||
ToScriptID int64 `json:"ToScriptID"`
|
||||
Policy int32 `json:"Policy"`
|
||||
}
|
||||
|
||||
// GetFromScriptID returns the value of FromScriptID.
|
||||
func (s *ScriptPolicyCreate) GetFromScriptID() int64 {
|
||||
return s.FromScriptID
|
||||
}
|
||||
|
||||
// GetToScriptID returns the value of ToScriptID.
|
||||
func (s *ScriptPolicyCreate) GetToScriptID() int64 {
|
||||
return s.ToScriptID
|
||||
}
|
||||
|
||||
// GetPolicy returns the value of Policy.
|
||||
func (s *ScriptPolicyCreate) GetPolicy() int32 {
|
||||
return s.Policy
|
||||
}
|
||||
|
||||
// SetFromScriptID sets the value of FromScriptID.
|
||||
func (s *ScriptPolicyCreate) SetFromScriptID(val int64) {
|
||||
s.FromScriptID = val
|
||||
}
|
||||
|
||||
// SetToScriptID sets the value of ToScriptID.
|
||||
func (s *ScriptPolicyCreate) SetToScriptID(val int64) {
|
||||
s.ToScriptID = val
|
||||
}
|
||||
|
||||
// SetPolicy sets the value of Policy.
|
||||
func (s *ScriptPolicyCreate) SetPolicy(val int32) {
|
||||
s.Policy = val
|
||||
}
|
||||
|
||||
// UpdateMapfixValidatedModelNoContent is response for UpdateMapfixValidatedModel operation.
|
||||
type UpdateMapfixValidatedModelNoContent struct{}
|
||||
|
||||
// UpdateSubmissionValidatedModelNoContent is response for UpdateSubmissionValidatedModel operation.
|
||||
type UpdateSubmissionValidatedModelNoContent struct{}
|
||||
@@ -1,112 +0,0 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
// Handler handles operations described by OpenAPI v3 specification.
|
||||
type Handler interface {
|
||||
// ActionMapfixAccepted implements actionMapfixAccepted operation.
|
||||
//
|
||||
// (Internal endpoint) Role Validator changes status from Validating -> Accepted.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/validator-failed
|
||||
ActionMapfixAccepted(ctx context.Context, params ActionMapfixAcceptedParams) error
|
||||
// ActionMapfixUploaded implements actionMapfixUploaded operation.
|
||||
//
|
||||
// (Internal endpoint) Role Validator changes status from Uploading -> Uploaded.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/validator-uploaded
|
||||
ActionMapfixUploaded(ctx context.Context, params ActionMapfixUploadedParams) error
|
||||
// ActionMapfixValidated implements actionMapfixValidated operation.
|
||||
//
|
||||
// (Internal endpoint) Role Validator changes status from Validating -> Validated.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/validator-validated
|
||||
ActionMapfixValidated(ctx context.Context, params ActionMapfixValidatedParams) error
|
||||
// ActionSubmissionAccepted implements actionSubmissionAccepted operation.
|
||||
//
|
||||
// (Internal endpoint) Role Validator changes status from Validating -> Accepted.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/validator-failed
|
||||
ActionSubmissionAccepted(ctx context.Context, params ActionSubmissionAcceptedParams) error
|
||||
// ActionSubmissionUploaded implements actionSubmissionUploaded operation.
|
||||
//
|
||||
// (Internal endpoint) Role Validator changes status from Uploading -> Uploaded.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/validator-uploaded
|
||||
ActionSubmissionUploaded(ctx context.Context, params ActionSubmissionUploadedParams) error
|
||||
// ActionSubmissionValidated implements actionSubmissionValidated operation.
|
||||
//
|
||||
// (Internal endpoint) Role Validator changes status from Validating -> Validated.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/validator-validated
|
||||
ActionSubmissionValidated(ctx context.Context, params ActionSubmissionValidatedParams) error
|
||||
// CreateScript implements createScript operation.
|
||||
//
|
||||
// Create a new script.
|
||||
//
|
||||
// POST /scripts
|
||||
CreateScript(ctx context.Context, req *ScriptCreate) (*ID, error)
|
||||
// CreateScriptPolicy implements createScriptPolicy operation.
|
||||
//
|
||||
// Create a new script policy.
|
||||
//
|
||||
// POST /script-policy
|
||||
CreateScriptPolicy(ctx context.Context, req *ScriptPolicyCreate) (*ID, error)
|
||||
// GetScript implements getScript operation.
|
||||
//
|
||||
// Get the specified script by ID.
|
||||
//
|
||||
// GET /scripts/{ScriptID}
|
||||
GetScript(ctx context.Context, params GetScriptParams) (*Script, error)
|
||||
// ListScriptPolicy implements listScriptPolicy operation.
|
||||
//
|
||||
// Get list of script policies.
|
||||
//
|
||||
// GET /script-policy
|
||||
ListScriptPolicy(ctx context.Context, params ListScriptPolicyParams) ([]ScriptPolicy, error)
|
||||
// ListScripts implements listScripts operation.
|
||||
//
|
||||
// Get list of scripts.
|
||||
//
|
||||
// GET /scripts
|
||||
ListScripts(ctx context.Context, params ListScriptsParams) ([]Script, error)
|
||||
// UpdateMapfixValidatedModel implements updateMapfixValidatedModel operation.
|
||||
//
|
||||
// Update validated model.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/validated-model
|
||||
UpdateMapfixValidatedModel(ctx context.Context, params UpdateMapfixValidatedModelParams) error
|
||||
// UpdateSubmissionValidatedModel implements updateSubmissionValidatedModel operation.
|
||||
//
|
||||
// Update validated model.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/validated-model
|
||||
UpdateSubmissionValidatedModel(ctx context.Context, params UpdateSubmissionValidatedModelParams) error
|
||||
// NewError creates *ErrorStatusCode from error returned by handler.
|
||||
//
|
||||
// Used for common default response.
|
||||
NewError(ctx context.Context, err error) *ErrorStatusCode
|
||||
}
|
||||
|
||||
// Server implements http server based on OpenAPI v3 specification and
|
||||
// calls Handler to handle requests.
|
||||
type Server struct {
|
||||
h Handler
|
||||
baseServer
|
||||
}
|
||||
|
||||
// NewServer creates new Server.
|
||||
func NewServer(h Handler, opts ...ServerOption) (*Server, error) {
|
||||
s, err := newServerConfig(opts...).baseServer()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Server{
|
||||
h: h,
|
||||
baseServer: s,
|
||||
}, nil
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
)
|
||||
|
||||
// UnimplementedHandler is no-op Handler which returns http.ErrNotImplemented.
|
||||
type UnimplementedHandler struct{}
|
||||
|
||||
var _ Handler = UnimplementedHandler{}
|
||||
|
||||
// ActionMapfixAccepted implements actionMapfixAccepted operation.
|
||||
//
|
||||
// (Internal endpoint) Role Validator changes status from Validating -> Accepted.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/validator-failed
|
||||
func (UnimplementedHandler) ActionMapfixAccepted(ctx context.Context, params ActionMapfixAcceptedParams) error {
|
||||
return ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ActionMapfixUploaded implements actionMapfixUploaded operation.
|
||||
//
|
||||
// (Internal endpoint) Role Validator changes status from Uploading -> Uploaded.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/validator-uploaded
|
||||
func (UnimplementedHandler) ActionMapfixUploaded(ctx context.Context, params ActionMapfixUploadedParams) error {
|
||||
return ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ActionMapfixValidated implements actionMapfixValidated operation.
|
||||
//
|
||||
// (Internal endpoint) Role Validator changes status from Validating -> Validated.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/validator-validated
|
||||
func (UnimplementedHandler) ActionMapfixValidated(ctx context.Context, params ActionMapfixValidatedParams) error {
|
||||
return ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ActionSubmissionAccepted implements actionSubmissionAccepted operation.
|
||||
//
|
||||
// (Internal endpoint) Role Validator changes status from Validating -> Accepted.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/validator-failed
|
||||
func (UnimplementedHandler) ActionSubmissionAccepted(ctx context.Context, params ActionSubmissionAcceptedParams) error {
|
||||
return ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ActionSubmissionUploaded implements actionSubmissionUploaded operation.
|
||||
//
|
||||
// (Internal endpoint) Role Validator changes status from Uploading -> Uploaded.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/validator-uploaded
|
||||
func (UnimplementedHandler) ActionSubmissionUploaded(ctx context.Context, params ActionSubmissionUploadedParams) error {
|
||||
return ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ActionSubmissionValidated implements actionSubmissionValidated operation.
|
||||
//
|
||||
// (Internal endpoint) Role Validator changes status from Validating -> Validated.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/validator-validated
|
||||
func (UnimplementedHandler) ActionSubmissionValidated(ctx context.Context, params ActionSubmissionValidatedParams) error {
|
||||
return ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// CreateScript implements createScript operation.
|
||||
//
|
||||
// Create a new script.
|
||||
//
|
||||
// POST /scripts
|
||||
func (UnimplementedHandler) CreateScript(ctx context.Context, req *ScriptCreate) (r *ID, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// CreateScriptPolicy implements createScriptPolicy operation.
|
||||
//
|
||||
// Create a new script policy.
|
||||
//
|
||||
// POST /script-policy
|
||||
func (UnimplementedHandler) CreateScriptPolicy(ctx context.Context, req *ScriptPolicyCreate) (r *ID, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// GetScript implements getScript operation.
|
||||
//
|
||||
// Get the specified script by ID.
|
||||
//
|
||||
// GET /scripts/{ScriptID}
|
||||
func (UnimplementedHandler) GetScript(ctx context.Context, params GetScriptParams) (r *Script, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ListScriptPolicy implements listScriptPolicy operation.
|
||||
//
|
||||
// Get list of script policies.
|
||||
//
|
||||
// GET /script-policy
|
||||
func (UnimplementedHandler) ListScriptPolicy(ctx context.Context, params ListScriptPolicyParams) (r []ScriptPolicy, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ListScripts implements listScripts operation.
|
||||
//
|
||||
// Get list of scripts.
|
||||
//
|
||||
// GET /scripts
|
||||
func (UnimplementedHandler) ListScripts(ctx context.Context, params ListScriptsParams) (r []Script, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// UpdateMapfixValidatedModel implements updateMapfixValidatedModel operation.
|
||||
//
|
||||
// Update validated model.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/validated-model
|
||||
func (UnimplementedHandler) UpdateMapfixValidatedModel(ctx context.Context, params UpdateMapfixValidatedModelParams) error {
|
||||
return ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// UpdateSubmissionValidatedModel implements updateSubmissionValidatedModel operation.
|
||||
//
|
||||
// Update validated model.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/validated-model
|
||||
func (UnimplementedHandler) UpdateSubmissionValidatedModel(ctx context.Context, params UpdateSubmissionValidatedModelParams) error {
|
||||
return ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// NewError creates *ErrorStatusCode from error returned by handler.
|
||||
//
|
||||
// Used for common default response.
|
||||
func (UnimplementedHandler) NewError(ctx context.Context, err error) (r *ErrorStatusCode) {
|
||||
r = new(ErrorStatusCode)
|
||||
return r
|
||||
}
|
||||
@@ -1,159 +0,0 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"github.com/go-faster/errors"
|
||||
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
)
|
||||
|
||||
func (s *Script) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 0,
|
||||
MinLengthSet: false,
|
||||
MaxLength: 128,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: nil,
|
||||
}).Validate(string(s.Name)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "Name",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 16,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 16,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: nil,
|
||||
}).Validate(string(s.Hash)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "Hash",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 0,
|
||||
MinLengthSet: false,
|
||||
MaxLength: 1048576,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: nil,
|
||||
}).Validate(string(s.Source)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "Source",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ScriptCreate) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 0,
|
||||
MinLengthSet: false,
|
||||
MaxLength: 128,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: nil,
|
||||
}).Validate(string(s.Name)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "Name",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 0,
|
||||
MinLengthSet: false,
|
||||
MaxLength: 1048576,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: nil,
|
||||
}).Validate(string(s.Source)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "Source",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ScriptPolicy) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 16,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 16,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: nil,
|
||||
}).Validate(string(s.FromScriptHash)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "FromScriptHash",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
75
pkg/model/audit_event.go
Normal file
75
pkg/model/audit_event.go
Normal file
@@ -0,0 +1,75 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"math"
|
||||
"time"
|
||||
)
|
||||
|
||||
const ValidatorUserID uint64 = uint64(math.MaxInt64)
|
||||
|
||||
type AuditEventType int32
|
||||
|
||||
// User clicked "Submit", "Accept" etc
|
||||
const AuditEventTypeAction AuditEventType = 0
|
||||
type AuditEventDataAction struct {
|
||||
TargetStatus uint32 `json:"target_status"`
|
||||
}
|
||||
|
||||
// User wrote a comment
|
||||
const AuditEventTypeComment AuditEventType = 1
|
||||
type AuditEventDataComment struct {
|
||||
Comment string `json:"comment"`
|
||||
}
|
||||
|
||||
// User changed Model
|
||||
const AuditEventTypeChangeModel AuditEventType = 2
|
||||
type AuditEventDataChangeModel struct {
|
||||
OldModelID uint64 `json:"old_model_id"`
|
||||
OldModelVersion uint64 `json:"old_model_version"`
|
||||
NewModelID uint64 `json:"new_model_id"`
|
||||
NewModelVersion uint64 `json:"new_model_version"`
|
||||
}
|
||||
// Validator validates model
|
||||
const AuditEventTypeChangeValidatedModel AuditEventType = 3
|
||||
type AuditEventDataChangeValidatedModel struct {
|
||||
ValidatedModelID uint64 `json:"validated_model_id"`
|
||||
ValidatedModelVersion uint64 `json:"validated_model_version"`
|
||||
}
|
||||
|
||||
// User changed DisplayName / Creator
|
||||
const AuditEventTypeChangeDisplayName AuditEventType = 4
|
||||
const AuditEventTypeChangeCreator AuditEventType = 5
|
||||
type AuditEventDataChangeName struct {
|
||||
OldName string `json:"old_name"`
|
||||
NewName string `json:"new_name"`
|
||||
}
|
||||
|
||||
// Validator had an error
|
||||
const AuditEventTypeError AuditEventType = 6
|
||||
type AuditEventDataError struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
type Check struct {
|
||||
Name string `json:"name"`
|
||||
Summary string `json:"summary"`
|
||||
Passed bool `json:"passed"`
|
||||
}
|
||||
|
||||
// Validator map checks details
|
||||
const AuditEventTypeCheckList AuditEventType = 7
|
||||
|
||||
type AuditEventDataCheckList struct {
|
||||
CheckList []Check `json:"check_list"`
|
||||
}
|
||||
|
||||
type AuditEvent struct {
|
||||
ID int64 `gorm:"primaryKey"`
|
||||
CreatedAt time.Time
|
||||
User uint64
|
||||
ResourceType ResourceType // is this a submission or is it a mapfix
|
||||
ResourceID int64 // submission / mapfix / map ID
|
||||
EventType AuditEventType
|
||||
EventData json.RawMessage `gorm:"type:jsonb"`
|
||||
}
|
||||
18
pkg/model/map.go
Normal file
18
pkg/model/map.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type Map struct {
|
||||
ID int64
|
||||
DisplayName string
|
||||
Creator string
|
||||
GameID uint32
|
||||
Date time.Time // Release date
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
Submitter uint64 // UserID of submitter
|
||||
Thumbnail uint64 // AssetID of thumbnail
|
||||
AssetVersion uint64 // Version number for LoadAssetVersion
|
||||
LoadCount uint32 // How many times the map has been loaded
|
||||
Modes uint32 // Number of modes (always at least one)
|
||||
}
|
||||
@@ -5,36 +5,39 @@ import "time"
|
||||
type MapfixStatus int32
|
||||
|
||||
const (
|
||||
// Phase: Final MapfixStatus
|
||||
MapfixStatusRejected MapfixStatus = 8
|
||||
MapfixStatusUploaded MapfixStatus = 7 // uploaded to the group, final status for mapfixes
|
||||
// Phase: Creation
|
||||
MapfixStatusUnderConstruction MapfixStatus = 0
|
||||
MapfixStatusChangesRequested MapfixStatus = 1
|
||||
|
||||
// Phase: Review
|
||||
MapfixStatusSubmitting MapfixStatus = 2
|
||||
MapfixStatusSubmitted MapfixStatus = 3
|
||||
|
||||
// Phase: Testing
|
||||
MapfixStatusUploading MapfixStatus = 6
|
||||
MapfixStatusValidated MapfixStatus = 5
|
||||
MapfixStatusValidating MapfixStatus = 4
|
||||
MapfixStatusAccepted MapfixStatus = 3 // pending script review, can re-trigger validation
|
||||
MapfixStatusAcceptedUnvalidated MapfixStatus = 4 // pending script review, can re-trigger validation
|
||||
MapfixStatusValidating MapfixStatus = 5
|
||||
MapfixStatusValidated MapfixStatus = 6
|
||||
MapfixStatusUploading MapfixStatus = 7
|
||||
|
||||
// Phase: Creation
|
||||
MapfixStatusChangesRequested MapfixStatus = 2
|
||||
MapfixStatusSubmitted MapfixStatus = 1
|
||||
MapfixStatusUnderConstruction MapfixStatus = 0
|
||||
// Phase: Final MapfixStatus
|
||||
MapfixStatusUploaded MapfixStatus = 8 // uploaded to the group, but pending release
|
||||
MapfixStatusRejected MapfixStatus = 9
|
||||
)
|
||||
|
||||
type Mapfix struct {
|
||||
ID int64 `gorm:"primaryKey"`
|
||||
DisplayName string
|
||||
Creator string
|
||||
GameID int32
|
||||
GameID uint32
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
Submitter int64 // UserID
|
||||
AssetID int64
|
||||
AssetVersion int64
|
||||
ValidatedAssetID int64
|
||||
ValidatedAssetVersion int64
|
||||
Submitter uint64 // UserID
|
||||
AssetID uint64
|
||||
AssetVersion uint64
|
||||
ValidatedAssetID uint64
|
||||
ValidatedAssetVersion uint64
|
||||
Completed bool // Has this version of the map been completed at least once on maptest
|
||||
TargetAssetID int64 // where to upload map fix. if the TargetAssetID is 0, it's a new map.
|
||||
TargetAssetID uint64 // where to upload map fix. if the TargetAssetID is 0, it's a new map.
|
||||
StatusID MapfixStatus
|
||||
StatusMessage string
|
||||
Description string // mapfix description
|
||||
}
|
||||
|
||||
@@ -5,32 +5,63 @@ package model
|
||||
|
||||
// Requests are sent from maps-service to validator
|
||||
|
||||
type CreateSubmissionRequest struct {
|
||||
// operation_id is passed back in the response message
|
||||
OperationID int32
|
||||
ModelID uint64
|
||||
DisplayName string
|
||||
Creator string
|
||||
GameID uint32
|
||||
Status uint32
|
||||
Roles uint32
|
||||
}
|
||||
|
||||
type CreateMapfixRequest struct {
|
||||
OperationID int32
|
||||
ModelID uint64
|
||||
TargetAssetID uint64
|
||||
Description string
|
||||
}
|
||||
|
||||
|
||||
type CheckSubmissionRequest struct{
|
||||
SubmissionID int64
|
||||
ModelID uint64
|
||||
SkipChecks bool
|
||||
}
|
||||
|
||||
type CheckMapfixRequest struct{
|
||||
MapfixID int64
|
||||
ModelID uint64
|
||||
SkipChecks bool
|
||||
}
|
||||
|
||||
type ValidateSubmissionRequest struct {
|
||||
// submission_id is passed back in the response message
|
||||
SubmissionID int64
|
||||
ModelID int64
|
||||
ModelVersion int64
|
||||
ValidatedModelID *int64 // optional value
|
||||
SubmissionID int64
|
||||
ModelID uint64
|
||||
ModelVersion uint64
|
||||
ValidatedModelID *uint64 // optional value
|
||||
}
|
||||
|
||||
type ValidateMapfixRequest struct {
|
||||
MapfixID int64
|
||||
ModelID int64
|
||||
ModelVersion int64
|
||||
ValidatedModelID *int64 // optional value
|
||||
MapfixID int64
|
||||
ModelID uint64
|
||||
ModelVersion uint64
|
||||
ValidatedModelID *uint64 // optional value
|
||||
}
|
||||
|
||||
// Create a new map
|
||||
type UploadSubmissionRequest struct {
|
||||
SubmissionID int64
|
||||
ModelID int64
|
||||
ModelVersion int64
|
||||
SubmissionID int64
|
||||
ModelID uint64
|
||||
ModelVersion uint64
|
||||
ModelName string
|
||||
}
|
||||
|
||||
type UploadMapfixRequest struct {
|
||||
MapfixID int64
|
||||
ModelID int64
|
||||
ModelVersion int64
|
||||
TargetAssetID int64
|
||||
MapfixID int64
|
||||
ModelID uint64
|
||||
ModelVersion uint64
|
||||
TargetAssetID uint64
|
||||
}
|
||||
|
||||
19
pkg/model/operation.go
Normal file
19
pkg/model/operation.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type OperationStatus int32
|
||||
const (
|
||||
OperationStatusCreated OperationStatus = 0
|
||||
OperationStatusCompleted OperationStatus = 1
|
||||
OperationStatusFailed OperationStatus = 2
|
||||
)
|
||||
|
||||
type Operation struct {
|
||||
ID int32 `gorm:"primaryKey"`
|
||||
CreatedAt time.Time
|
||||
Owner uint64 // UserID
|
||||
StatusID OperationStatus
|
||||
StatusMessage string
|
||||
Path string // redirect to view completed operation e.g. "/mapfixes/4"
|
||||
}
|
||||
13
pkg/model/resource.go
Normal file
13
pkg/model/resource.go
Normal file
@@ -0,0 +1,13 @@
|
||||
package model
|
||||
|
||||
type ResourceType int32
|
||||
const (
|
||||
ResourceUnknown ResourceType = 0
|
||||
ResourceMapfix ResourceType = 1
|
||||
ResourceSubmission ResourceType = 2
|
||||
)
|
||||
|
||||
type Resource struct{
|
||||
ID int64
|
||||
Type ResourceType
|
||||
}
|
||||
33
pkg/model/roles.go
Normal file
33
pkg/model/roles.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package model
|
||||
|
||||
// Submissions roles bitflag
|
||||
type Roles int32
|
||||
var (
|
||||
RolesSubmissionUpload Roles = 1<<6
|
||||
RolesSubmissionReview Roles = 1<<5
|
||||
RolesSubmissionRelease Roles = 1<<4
|
||||
RolesScriptWrite Roles = 1<<3
|
||||
RolesMapfixUpload Roles = 1<<2
|
||||
RolesMapfixReview Roles = 1<<1
|
||||
RolesMapDownload Roles = 1<<0
|
||||
RolesEmpty Roles = 0
|
||||
)
|
||||
|
||||
// StrafesNET group roles
|
||||
type GroupRole int32
|
||||
var (
|
||||
// has ScriptWrite
|
||||
RoleQuat GroupRole = 255
|
||||
RoleItzaname GroupRole = 254
|
||||
RoleStagingDeveloper GroupRole = 240
|
||||
RolesAll Roles = ^RolesEmpty
|
||||
// has SubmissionUpload
|
||||
RoleMapAdmin GroupRole = 128
|
||||
RolesMapAdmin Roles = RolesSubmissionRelease|RolesSubmissionUpload|RolesSubmissionReview|RolesMapCouncil
|
||||
// has MapfixReview
|
||||
RoleMapCouncil GroupRole = 64
|
||||
RolesMapCouncil Roles = RolesMapfixReview|RolesMapfixUpload|RolesMapAccess
|
||||
// access to downloading maps
|
||||
RoleMapAccess GroupRole = 32
|
||||
RolesMapAccess Roles = RolesMapDownload
|
||||
)
|
||||
@@ -23,13 +23,6 @@ func HashParse(hash string) (uint64, error){
|
||||
return strconv.ParseUint(hash, 16, 64)
|
||||
}
|
||||
|
||||
type ResourceType int32
|
||||
const (
|
||||
ResourceUnknown ResourceType = 0
|
||||
ResourceMapfix ResourceType = 1
|
||||
ResourceSubmission ResourceType = 2
|
||||
)
|
||||
|
||||
type Script struct {
|
||||
ID int64 `gorm:"primaryKey"`
|
||||
Name string
|
||||
|
||||
@@ -5,37 +5,39 @@ import "time"
|
||||
type SubmissionStatus int32
|
||||
|
||||
const (
|
||||
// Phase: Final SubmissionStatus
|
||||
SubmissionStatusReleased SubmissionStatus = 9
|
||||
SubmissionStatusRejected SubmissionStatus = 8
|
||||
// Phase: Creation
|
||||
SubmissionStatusUnderConstruction SubmissionStatus = 0
|
||||
SubmissionStatusChangesRequested SubmissionStatus = 1
|
||||
|
||||
// Phase: Review
|
||||
SubmissionStatusSubmitting SubmissionStatus = 2
|
||||
SubmissionStatusSubmitted SubmissionStatus = 3
|
||||
|
||||
// Phase: Testing
|
||||
SubmissionStatusUploaded SubmissionStatus = 7 // uploaded to the group, but pending release
|
||||
SubmissionStatusUploading SubmissionStatus = 6
|
||||
SubmissionStatusValidated SubmissionStatus = 5
|
||||
SubmissionStatusValidating SubmissionStatus = 4
|
||||
SubmissionStatusAccepted SubmissionStatus = 3 // pending script review, can re-trigger validation
|
||||
SubmissionStatusAcceptedUnvalidated SubmissionStatus = 4 // pending script review, can re-trigger validation
|
||||
SubmissionStatusValidating SubmissionStatus = 5
|
||||
SubmissionStatusValidated SubmissionStatus = 6
|
||||
SubmissionStatusUploading SubmissionStatus = 7
|
||||
SubmissionStatusUploaded SubmissionStatus = 8 // uploaded to the group, but pending release
|
||||
|
||||
// Phase: Creation
|
||||
SubmissionStatusChangesRequested SubmissionStatus = 2
|
||||
SubmissionStatusSubmitted SubmissionStatus = 1
|
||||
SubmissionStatusUnderConstruction SubmissionStatus = 0
|
||||
// Phase: Final SubmissionStatus
|
||||
SubmissionStatusRejected SubmissionStatus = 9
|
||||
SubmissionStatusReleased SubmissionStatus = 10
|
||||
)
|
||||
|
||||
type Submission struct {
|
||||
ID int64 `gorm:"primaryKey"`
|
||||
DisplayName string
|
||||
Creator string
|
||||
GameID int32
|
||||
GameID uint32
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
Submitter int64 // UserID
|
||||
AssetID int64
|
||||
AssetVersion int64
|
||||
ValidatedAssetID int64
|
||||
ValidatedAssetVersion int64
|
||||
Submitter uint64 // UserID
|
||||
AssetID uint64
|
||||
AssetVersion uint64
|
||||
ValidatedAssetID uint64
|
||||
ValidatedAssetVersion uint64
|
||||
Completed bool // Has this version of the map been completed at least once on maptest
|
||||
UploadedAssetID int64 // where to upload map fix. if the TargetAssetID is 0, it's a new map.
|
||||
UploadedAssetID uint64 // where to upload map fix. if the TargetAssetID is 0, it's a new map.
|
||||
StatusID SubmissionStatus
|
||||
StatusMessage string
|
||||
}
|
||||
|
||||
95
pkg/roblox/asset_location.go
Normal file
95
pkg/roblox/asset_location.go
Normal file
@@ -0,0 +1,95 @@
|
||||
package roblox
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
type AssetMetadata struct {
|
||||
MetadataType uint32 `json:"metadataType"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
// Struct equivalent to Rust's AssetLocationInfo
|
||||
type AssetLocationInfo struct {
|
||||
Location string `json:"location"`
|
||||
RequestId string `json:"requestId"`
|
||||
IsArchived bool `json:"isArchived"`
|
||||
AssetTypeId uint32 `json:"assetTypeId"`
|
||||
AssetMetadatas []AssetMetadata `json:"assetMetadatas"`
|
||||
IsRecordable bool `json:"isRecordable"`
|
||||
}
|
||||
|
||||
// Input struct for getAssetLocation
|
||||
type GetAssetLatestRequest struct {
|
||||
AssetID uint64
|
||||
}
|
||||
|
||||
// Custom error type if needed
|
||||
type GetError string
|
||||
|
||||
func (e GetError) Error() string { return string(e) }
|
||||
|
||||
// Example client with a Get method
|
||||
type Client struct {
|
||||
HttpClient *http.Client
|
||||
ApiKey string
|
||||
}
|
||||
|
||||
func (c *Client) GetAssetLocation(config GetAssetLatestRequest) (*AssetLocationInfo, error) {
|
||||
rawURL := fmt.Sprintf("https://apis.roblox.com/asset-delivery-api/v1/assetId/%d", config.AssetID)
|
||||
parsedURL, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
return nil, GetError("ParseError: " + err.Error())
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("GET", parsedURL.String(), nil)
|
||||
if err != nil {
|
||||
return nil, GetError("RequestCreationError: " + err.Error())
|
||||
}
|
||||
|
||||
req.Header.Set("x-api-key", c.ApiKey)
|
||||
|
||||
resp, err := c.HttpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, GetError("RequestError: " + err.Error())
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, GetError(fmt.Sprintf("ResponseError: status code %d", resp.StatusCode))
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, GetError("ReadBodyError: " + err.Error())
|
||||
}
|
||||
|
||||
var info AssetLocationInfo
|
||||
if err := json.Unmarshal(body, &info); err != nil {
|
||||
return nil, GetError("JSONError: " + err.Error())
|
||||
}
|
||||
|
||||
return &info, nil
|
||||
}
|
||||
|
||||
func (c *Client) DownloadAsset(info *AssetLocationInfo) (io.Reader, error) {
|
||||
req, err := http.NewRequest("GET", info.Location, nil)
|
||||
if err != nil {
|
||||
return nil, GetError("RequestCreationError: " + err.Error())
|
||||
}
|
||||
|
||||
resp, err := c.HttpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, GetError("RequestError: " + err.Error())
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, GetError(fmt.Sprintf("ResponseError: status code %d", resp.StatusCode))
|
||||
}
|
||||
|
||||
return resp.Body, nil
|
||||
}
|
||||
238
pkg/service/audit_events.go
Normal file
238
pkg/service/audit_events.go
Normal file
@@ -0,0 +1,238 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"git.itzana.me/strafesnet/go-grpc/users"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/api"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/datastore"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
)
|
||||
|
||||
func (svc *Service) ListAuditEvents(ctx context.Context, resource model.Resource, page model.Page) ([]api.AuditEvent, error){
|
||||
filter := datastore.Optional()
|
||||
|
||||
filter.Add("resource_type", resource.Type)
|
||||
filter.Add("resource_id", resource.ID)
|
||||
|
||||
items, err := svc.db.AuditEvents().List(ctx, filter, page)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
idMap := make(map[int64]bool)
|
||||
for _, item := range items {
|
||||
idMap[int64(item.User)] = true
|
||||
}
|
||||
|
||||
var idList users.IdList
|
||||
idList.ID = make([]int64,len(idMap))
|
||||
for userId := range idMap {
|
||||
idList.ID = append(idList.ID, userId)
|
||||
}
|
||||
|
||||
userList, err := svc.users.GetList(ctx, &idList)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
userMap := make(map[int64]*users.UserResponse)
|
||||
for _,user := range userList.Users {
|
||||
userMap[user.ID] = user
|
||||
}
|
||||
|
||||
var resp []api.AuditEvent
|
||||
for _, item := range items {
|
||||
EventData := api.AuditEventEventData{}
|
||||
err = EventData.UnmarshalJSON(item.EventData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
username := ""
|
||||
if userMap[int64(item.User)] != nil {
|
||||
username = userMap[int64(item.User)].Username
|
||||
}
|
||||
resp = append(resp, api.AuditEvent{
|
||||
ID: item.ID,
|
||||
Date: item.CreatedAt.Unix(),
|
||||
User: int64(item.User),
|
||||
Username: username,
|
||||
ResourceType: int32(item.ResourceType),
|
||||
ResourceID: item.ResourceID,
|
||||
EventType: int32(item.EventType),
|
||||
EventData: EventData,
|
||||
})
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (svc *Service) CreateAuditEventAction(ctx context.Context, userId uint64, resource model.Resource, event_data model.AuditEventDataAction) error {
|
||||
EventData, err := json.Marshal(event_data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = svc.db.AuditEvents().Create(ctx, model.AuditEvent{
|
||||
ID: 0,
|
||||
User: userId,
|
||||
ResourceType: resource.Type,
|
||||
ResourceID: resource.ID,
|
||||
EventType: model.AuditEventTypeAction,
|
||||
EventData: EventData,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (svc *Service) CreateAuditEventComment(ctx context.Context, userId uint64, resource model.Resource, event_data model.AuditEventDataComment) error {
|
||||
EventData, err := json.Marshal(event_data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = svc.db.AuditEvents().Create(ctx, model.AuditEvent{
|
||||
ID: 0,
|
||||
User: userId,
|
||||
ResourceType: resource.Type,
|
||||
ResourceID: resource.ID,
|
||||
EventType: model.AuditEventTypeComment,
|
||||
EventData: EventData,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (svc *Service) CreateAuditEventChangeModel(ctx context.Context, userId uint64, resource model.Resource, event_data model.AuditEventDataChangeModel) error {
|
||||
EventData, err := json.Marshal(event_data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = svc.db.AuditEvents().Create(ctx, model.AuditEvent{
|
||||
ID: 0,
|
||||
User: userId,
|
||||
ResourceType: resource.Type,
|
||||
ResourceID: resource.ID,
|
||||
EventType: model.AuditEventTypeChangeModel,
|
||||
EventData: EventData,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
func (svc *Service) CreateAuditEventChangeValidatedModel(ctx context.Context, userId uint64, resource model.Resource, event_data model.AuditEventDataChangeValidatedModel) error {
|
||||
EventData, err := json.Marshal(event_data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = svc.db.AuditEvents().Create(ctx, model.AuditEvent{
|
||||
ID: 0,
|
||||
User: userId,
|
||||
ResourceType: resource.Type,
|
||||
ResourceID: resource.ID,
|
||||
EventType: model.AuditEventTypeChangeValidatedModel,
|
||||
EventData: EventData,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (svc *Service) CreateAuditEventError(ctx context.Context, userId uint64, resource model.Resource, event_data model.AuditEventDataError) error {
|
||||
EventData, err := json.Marshal(event_data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = svc.db.AuditEvents().Create(ctx, model.AuditEvent{
|
||||
ID: 0,
|
||||
User: userId,
|
||||
ResourceType: resource.Type,
|
||||
ResourceID: resource.ID,
|
||||
EventType: model.AuditEventTypeError,
|
||||
EventData: EventData,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (svc *Service) CreateAuditEventCheckList(ctx context.Context, userId uint64, resource model.Resource, event_data model.AuditEventDataCheckList) error {
|
||||
EventData, err := json.Marshal(event_data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = svc.db.AuditEvents().Create(ctx, model.AuditEvent{
|
||||
ID: 0,
|
||||
User: userId,
|
||||
ResourceType: resource.Type,
|
||||
ResourceID: resource.ID,
|
||||
EventType: model.AuditEventTypeCheckList,
|
||||
EventData: EventData,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (svc *Service) CreateAuditEventChangeDisplayName(ctx context.Context, userId uint64, resource model.Resource, event_data model.AuditEventDataChangeName) error {
|
||||
EventData, err := json.Marshal(event_data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = svc.db.AuditEvents().Create(ctx, model.AuditEvent{
|
||||
ID: 0,
|
||||
User: userId,
|
||||
ResourceType: resource.Type,
|
||||
ResourceID: resource.ID,
|
||||
EventType: model.AuditEventTypeChangeDisplayName,
|
||||
EventData: EventData,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (svc *Service) CreateAuditEventChangeCreator(ctx context.Context, userId uint64, resource model.Resource, event_data model.AuditEventDataChangeName) error {
|
||||
EventData, err := json.Marshal(event_data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = svc.db.AuditEvents().Create(ctx, model.AuditEvent{
|
||||
ID: 0,
|
||||
User: userId,
|
||||
ResourceType: resource.Type,
|
||||
ResourceID: resource.ID,
|
||||
EventType: model.AuditEventTypeChangeCreator,
|
||||
EventData: EventData,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -2,616 +2,115 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/api"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/datastore"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
)
|
||||
|
||||
var(
|
||||
CreationPhaseMapfixesLimit = 20
|
||||
CreationPhaseMapfixStatuses = []model.MapfixStatus{
|
||||
model.MapfixStatusChangesRequested,
|
||||
model.MapfixStatusSubmitted,
|
||||
model.MapfixStatusUnderConstruction,
|
||||
}
|
||||
// prevent two mapfixes with same asset id
|
||||
ActiveMapfixStatuses = []model.MapfixStatus{
|
||||
model.MapfixStatusUploading,
|
||||
model.MapfixStatusValidated,
|
||||
model.MapfixStatusValidating,
|
||||
model.MapfixStatusAccepted,
|
||||
model.MapfixStatusChangesRequested,
|
||||
model.MapfixStatusSubmitted,
|
||||
model.MapfixStatusUnderConstruction,
|
||||
}
|
||||
// limit mapfixes in the pipeline to one per target map
|
||||
ActiveAcceptedMapfixStatuses = []model.MapfixStatus{
|
||||
model.MapfixStatusUploading,
|
||||
model.MapfixStatusValidated,
|
||||
model.MapfixStatusValidating,
|
||||
model.MapfixStatusAccepted,
|
||||
}
|
||||
)
|
||||
type MapfixUpdate datastore.OptionalMap
|
||||
|
||||
var (
|
||||
ErrCreationPhaseMapfixesLimit = errors.New("Active mapfixes limited to 20")
|
||||
ErrActiveMapfixSameAssetID = errors.New("There is an active mapfix with the same AssetID")
|
||||
ErrActiveMapfixSameTargetAssetID = errors.New("There is an active mapfix with the same TargetAssetID")
|
||||
ErrAcceptOwnMapfix = fmt.Errorf("%w: You cannot accept your own mapfix as the submitter", ErrPermissionDenied)
|
||||
)
|
||||
|
||||
// POST /mapfixes
|
||||
func (svc *Service) CreateMapfix(ctx context.Context, request *api.MapfixCreate) (*api.ID, error) {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return nil, ErrUserInfo
|
||||
}
|
||||
|
||||
userId, err := userInfo.GetUserID()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Check if user's mapfixes in the creation phase exceeds the limit
|
||||
{
|
||||
filter := datastore.Optional()
|
||||
filter.Add("submitter", int64(userId))
|
||||
filter.Add("status_id", CreationPhaseMapfixStatuses)
|
||||
creation_mapfixes, err := svc.DB.Mapfixes().List(ctx, filter, model.Page{
|
||||
Number: 1,
|
||||
Size: int32(CreationPhaseMapfixesLimit),
|
||||
},datastore.ListSortDisabled)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if CreationPhaseMapfixesLimit <= len(creation_mapfixes) {
|
||||
return nil, ErrCreationPhaseMapfixesLimit
|
||||
}
|
||||
}
|
||||
|
||||
// Check if an active mapfix with the same asset id exists
|
||||
{
|
||||
filter := datastore.Optional()
|
||||
filter.Add("asset_id", request.AssetID)
|
||||
filter.Add("asset_version", request.AssetVersion)
|
||||
filter.Add("status_id", ActiveMapfixStatuses)
|
||||
active_mapfixes, err := svc.DB.Mapfixes().List(ctx, filter, model.Page{
|
||||
Number: 1,
|
||||
Size: 1,
|
||||
},datastore.ListSortDisabled)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(active_mapfixes) != 0{
|
||||
return nil, ErrActiveMapfixSameAssetID
|
||||
}
|
||||
}
|
||||
|
||||
mapfix, err := svc.DB.Mapfixes().Create(ctx, model.Mapfix{
|
||||
ID: 0,
|
||||
DisplayName: request.DisplayName,
|
||||
Creator: request.Creator,
|
||||
GameID: request.GameID,
|
||||
Submitter: int64(userId),
|
||||
AssetID: request.AssetID,
|
||||
AssetVersion: request.AssetVersion,
|
||||
Completed: false,
|
||||
TargetAssetID: request.TargetAssetID,
|
||||
StatusID: model.MapfixStatusUnderConstruction,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &api.ID{
|
||||
ID: mapfix.ID,
|
||||
}, nil
|
||||
func NewMapfixUpdate() MapfixUpdate {
|
||||
update := datastore.Optional()
|
||||
return MapfixUpdate(update)
|
||||
}
|
||||
|
||||
// GetMapfix implements getMapfix operation.
|
||||
//
|
||||
// Retrieve map with ID.
|
||||
//
|
||||
// GET /mapfixes/{MapfixID}
|
||||
func (svc *Service) GetMapfix(ctx context.Context, params api.GetMapfixParams) (*api.Mapfix, error) {
|
||||
mapfix, err := svc.DB.Mapfixes().Get(ctx, params.MapfixID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &api.Mapfix{
|
||||
ID: mapfix.ID,
|
||||
DisplayName: mapfix.DisplayName,
|
||||
Creator: mapfix.Creator,
|
||||
GameID: mapfix.GameID,
|
||||
CreatedAt: mapfix.CreatedAt.Unix(),
|
||||
UpdatedAt: mapfix.UpdatedAt.Unix(),
|
||||
Submitter: int64(mapfix.Submitter),
|
||||
AssetID: int64(mapfix.AssetID),
|
||||
AssetVersion: int64(mapfix.AssetVersion),
|
||||
Completed: mapfix.Completed,
|
||||
TargetAssetID: int64(mapfix.TargetAssetID),
|
||||
StatusID: int32(mapfix.StatusID),
|
||||
StatusMessage: mapfix.StatusMessage,
|
||||
}, nil
|
||||
func (update MapfixUpdate) SetDisplayName(display_name string) {
|
||||
datastore.OptionalMap(update).Add("display_name", display_name)
|
||||
}
|
||||
func (update MapfixUpdate) SetCreator(creator string) {
|
||||
datastore.OptionalMap(update).Add("creator", creator)
|
||||
}
|
||||
func (update MapfixUpdate) SetGameID(game_id uint32) {
|
||||
datastore.OptionalMap(update).Add("game_id", game_id)
|
||||
}
|
||||
func (update MapfixUpdate) SetSubmitter(submitter uint64) {
|
||||
datastore.OptionalMap(update).Add("submitter", submitter)
|
||||
}
|
||||
func (update MapfixUpdate) SetAssetID(asset_id uint64) {
|
||||
datastore.OptionalMap(update).Add("asset_id", asset_id)
|
||||
}
|
||||
func (update MapfixUpdate) SetAssetVersion(asset_version uint64) {
|
||||
datastore.OptionalMap(update).Add("asset_version", asset_version)
|
||||
}
|
||||
func (update MapfixUpdate) SetValidatedAssetID(validated_asset_id uint64) {
|
||||
datastore.OptionalMap(update).Add("validated_asset_id", validated_asset_id)
|
||||
}
|
||||
func (update MapfixUpdate) SetValidatedAssetVersion(validated_asset_version uint64) {
|
||||
datastore.OptionalMap(update).Add("validated_asset_version", validated_asset_version)
|
||||
}
|
||||
func (update MapfixUpdate) SetCompleted(completed bool) {
|
||||
datastore.OptionalMap(update).Add("completed", completed)
|
||||
}
|
||||
func (update MapfixUpdate) SetTargetAssetID(target_asset_id uint64) {
|
||||
datastore.OptionalMap(update).Add("target_asset_id", target_asset_id)
|
||||
}
|
||||
func (update MapfixUpdate) SetStatusID(status_id model.MapfixStatus) {
|
||||
datastore.OptionalMap(update).Add("status_id", status_id)
|
||||
}
|
||||
func (update MapfixUpdate) SetDescription(description string) {
|
||||
datastore.OptionalMap(update).Add("description", description)
|
||||
}
|
||||
|
||||
// ListMapfixes implements listMapfixes operation.
|
||||
//
|
||||
// Get list of mapfixes.
|
||||
//
|
||||
// GET /mapfixes
|
||||
func (svc *Service) ListMapfixes(ctx context.Context, params api.ListMapfixesParams) ([]api.Mapfix, error) {
|
||||
type MapfixFilter datastore.OptionalMap
|
||||
|
||||
func NewMapfixFilter(
|
||||
) MapfixFilter {
|
||||
filter := datastore.Optional()
|
||||
|
||||
if params.DisplayName.IsSet(){
|
||||
filter.Add("display_name", params.DisplayName.Value)
|
||||
}
|
||||
if params.Creator.IsSet(){
|
||||
filter.Add("creator", params.Creator.Value)
|
||||
}
|
||||
if params.GameID.IsSet(){
|
||||
filter.Add("game_id", params.GameID.Value)
|
||||
}
|
||||
|
||||
sort := datastore.ListSort(params.Sort.Or(int32(datastore.ListSortDisabled)))
|
||||
|
||||
items, err := svc.DB.Mapfixes().List(ctx, filter, model.Page{
|
||||
Number: params.Page,
|
||||
Size: params.Limit,
|
||||
},sort)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var resp []api.Mapfix
|
||||
for _, item := range items {
|
||||
resp = append(resp, api.Mapfix{
|
||||
ID: item.ID,
|
||||
DisplayName: item.DisplayName,
|
||||
Creator: item.Creator,
|
||||
GameID: item.GameID,
|
||||
CreatedAt: item.CreatedAt.Unix(),
|
||||
UpdatedAt: item.UpdatedAt.Unix(),
|
||||
Submitter: int64(item.Submitter),
|
||||
AssetID: int64(item.AssetID),
|
||||
AssetVersion: int64(item.AssetVersion),
|
||||
Completed: item.Completed,
|
||||
TargetAssetID: int64(item.TargetAssetID),
|
||||
StatusID: int32(item.StatusID),
|
||||
})
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
return MapfixFilter(filter)
|
||||
}
|
||||
func (update MapfixFilter) SetDisplayName(display_name string) {
|
||||
datastore.OptionalMap(update).Add("display_name", display_name)
|
||||
}
|
||||
func (update MapfixFilter) SetCreator(creator string) {
|
||||
datastore.OptionalMap(update).Add("creator", creator)
|
||||
}
|
||||
func (update MapfixFilter) SetGameID(game_id uint32) {
|
||||
datastore.OptionalMap(update).Add("game_id", game_id)
|
||||
}
|
||||
func (update MapfixFilter) SetSubmitter(submitter uint64) {
|
||||
datastore.OptionalMap(update).Add("submitter", submitter)
|
||||
}
|
||||
func (update MapfixFilter) SetAssetID(asset_id uint64) {
|
||||
datastore.OptionalMap(update).Add("asset_id", asset_id)
|
||||
}
|
||||
func (update MapfixFilter) SetAssetVersion(asset_version uint64) {
|
||||
datastore.OptionalMap(update).Add("asset_version", asset_version)
|
||||
}
|
||||
func (update MapfixFilter) SetTargetAssetID(target_asset_id uint64) {
|
||||
datastore.OptionalMap(update).Add("target_asset_id", target_asset_id)
|
||||
}
|
||||
func (update MapfixFilter) SetStatuses(statuses []model.MapfixStatus) {
|
||||
datastore.OptionalMap(update).Add("status_id", statuses)
|
||||
}
|
||||
|
||||
// PatchMapfixCompleted implements patchMapfixCompleted operation.
|
||||
//
|
||||
// Retrieve map with ID.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/completed
|
||||
func (svc *Service) SetMapfixCompleted(ctx context.Context, params api.SetMapfixCompletedParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
has_role, err := userInfo.HasRoleMaptest()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller has MaptestGame role (request must originate from a maptest roblox game)
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNeedRoleMaptest
|
||||
}
|
||||
|
||||
pmap := datastore.Optional()
|
||||
pmap.Add("completed", true)
|
||||
return svc.DB.Mapfixes().Update(ctx, params.MapfixID, pmap)
|
||||
func (svc *Service) CreateMapfix(ctx context.Context, script model.Mapfix) (model.Mapfix, error) {
|
||||
return svc.db.Mapfixes().Create(ctx, script)
|
||||
}
|
||||
|
||||
// UpdateMapfixModel implements patchMapfixModel operation.
|
||||
//
|
||||
// Update model following role restrictions.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/model
|
||||
func (svc *Service) UpdateMapfixModel(ctx context.Context, params api.UpdateMapfixModelParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
// read mapfix (this could be done with a transaction WHERE clause)
|
||||
mapfix, err := svc.DB.Mapfixes().Get(ctx, params.MapfixID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
has_role, err := userInfo.IsSubmitter(uint64(mapfix.Submitter))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller is the submitter
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNotSubmitter
|
||||
}
|
||||
|
||||
// check if Status is ChangesRequested|Submitted|UnderConstruction
|
||||
pmap := datastore.Optional()
|
||||
pmap.AddNotNil("asset_id", params.ModelID)
|
||||
pmap.AddNotNil("asset_version", params.VersionID)
|
||||
//always reset completed when model changes
|
||||
pmap.Add("completed", false)
|
||||
return svc.DB.Mapfixes().IfStatusThenUpdate(ctx, params.MapfixID, []model.MapfixStatus{model.MapfixStatusChangesRequested, model.MapfixStatusSubmitted, model.MapfixStatusUnderConstruction}, pmap)
|
||||
func (svc *Service) ListMapfixes(ctx context.Context, filter MapfixFilter, page model.Page, sort datastore.ListSort) ([]model.Mapfix, error) {
|
||||
return svc.db.Mapfixes().List(ctx, datastore.OptionalMap(filter), page, sort)
|
||||
}
|
||||
|
||||
// ActionMapfixReject invokes actionMapfixReject operation.
|
||||
//
|
||||
// Role Reviewer changes status from Submitted -> Rejected.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/reject
|
||||
func (svc *Service) ActionMapfixReject(ctx context.Context, params api.ActionMapfixRejectParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
has_role, err := userInfo.HasRoleMapfixReview()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller has required role
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNeedRoleMapReview
|
||||
}
|
||||
|
||||
// transaction
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.MapfixStatusRejected)
|
||||
return svc.DB.Mapfixes().IfStatusThenUpdate(ctx, params.MapfixID, []model.MapfixStatus{model.MapfixStatusSubmitted}, smap)
|
||||
func (svc *Service) ListMapfixesWithTotal(ctx context.Context, filter MapfixFilter, page model.Page, sort datastore.ListSort) (int64, []model.Mapfix, error) {
|
||||
return svc.db.Mapfixes().ListWithTotal(ctx, datastore.OptionalMap(filter), page, sort)
|
||||
}
|
||||
|
||||
// ActionMapfixRequestChanges invokes actionMapfixRequestChanges operation.
|
||||
//
|
||||
// Role Reviewer changes status from Validated|Accepted|Submitted -> ChangesRequested.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/request-changes
|
||||
func (svc *Service) ActionMapfixRequestChanges(ctx context.Context, params api.ActionMapfixRequestChangesParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
has_role, err := userInfo.HasRoleMapfixReview()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller has required role
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNeedRoleMapReview
|
||||
}
|
||||
|
||||
// transaction
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.MapfixStatusChangesRequested)
|
||||
return svc.DB.Mapfixes().IfStatusThenUpdate(ctx, params.MapfixID, []model.MapfixStatus{model.MapfixStatusValidated, model.MapfixStatusAccepted, model.MapfixStatusSubmitted}, smap)
|
||||
func (svc *Service) DeleteMapfix(ctx context.Context, id int64) error {
|
||||
return svc.db.Mapfixes().Delete(ctx, id)
|
||||
}
|
||||
|
||||
// ActionMapfixRevoke invokes actionMapfixRevoke operation.
|
||||
//
|
||||
// Role Submitter changes status from Submitted|ChangesRequested -> UnderConstruction.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/revoke
|
||||
func (svc *Service) ActionMapfixRevoke(ctx context.Context, params api.ActionMapfixRevokeParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
// read mapfix (this could be done with a transaction WHERE clause)
|
||||
mapfix, err := svc.DB.Mapfixes().Get(ctx, params.MapfixID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
has_role, err := userInfo.IsSubmitter(uint64(mapfix.Submitter))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller is the submitter
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNotSubmitter
|
||||
}
|
||||
|
||||
// transaction
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.MapfixStatusUnderConstruction)
|
||||
return svc.DB.Mapfixes().IfStatusThenUpdate(ctx, params.MapfixID, []model.MapfixStatus{model.MapfixStatusSubmitted, model.MapfixStatusChangesRequested}, smap)
|
||||
func (svc *Service) GetMapfix(ctx context.Context, id int64) (model.Mapfix, error) {
|
||||
return svc.db.Mapfixes().Get(ctx, id)
|
||||
}
|
||||
|
||||
// ActionMapfixSubmit invokes actionMapfixSubmit operation.
|
||||
//
|
||||
// Role Submitter changes status from UnderConstruction|ChangesRequested -> Submitted.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/submit
|
||||
func (svc *Service) ActionMapfixSubmit(ctx context.Context, params api.ActionMapfixSubmitParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
// read mapfix (this could be done with a transaction WHERE clause)
|
||||
mapfix, err := svc.DB.Mapfixes().Get(ctx, params.MapfixID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
has_role, err := userInfo.IsSubmitter(uint64(mapfix.Submitter))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller is the submitter
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNotSubmitter
|
||||
}
|
||||
|
||||
// transaction
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.MapfixStatusSubmitted)
|
||||
return svc.DB.Mapfixes().IfStatusThenUpdate(ctx, params.MapfixID, []model.MapfixStatus{model.MapfixStatusUnderConstruction, model.MapfixStatusChangesRequested}, smap)
|
||||
func (svc *Service) UpdateMapfix(ctx context.Context, id int64, pmap MapfixUpdate) error {
|
||||
return svc.db.Mapfixes().Update(ctx, id, datastore.OptionalMap(pmap))
|
||||
}
|
||||
|
||||
// ActionMapfixTriggerUpload invokes actionMapfixTriggerUpload operation.
|
||||
//
|
||||
// Role Admin changes status from Validated -> Uploading.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/trigger-upload
|
||||
func (svc *Service) ActionMapfixTriggerUpload(ctx context.Context, params api.ActionMapfixTriggerUploadParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
has_role, err := userInfo.HasRoleMapfixUpload()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller has required role
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNeedRoleMapUpload
|
||||
}
|
||||
|
||||
// transaction
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.MapfixStatusUploading)
|
||||
mapfix, err := svc.DB.Mapfixes().IfStatusThenUpdateAndGet(ctx, params.MapfixID, []model.MapfixStatus{model.MapfixStatusValidated}, smap)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// this is a map fix
|
||||
upload_fix_request := model.UploadMapfixRequest{
|
||||
MapfixID: mapfix.ID,
|
||||
ModelID: mapfix.ValidatedAssetID,
|
||||
ModelVersion: mapfix.ValidatedAssetVersion,
|
||||
TargetAssetID: mapfix.TargetAssetID,
|
||||
}
|
||||
|
||||
j, err := json.Marshal(upload_fix_request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
svc.Nats.Publish("maptest.mapfixes.uploadfix", []byte(j))
|
||||
|
||||
return nil
|
||||
func (svc *Service) UpdateMapfixIfStatus(ctx context.Context, id int64, statuses []model.MapfixStatus, pmap MapfixUpdate) error {
|
||||
return svc.db.Mapfixes().IfStatusThenUpdate(ctx, id, statuses, datastore.OptionalMap(pmap))
|
||||
}
|
||||
|
||||
// ActionMapfixValidate invokes actionMapfixValidate operation.
|
||||
//
|
||||
// Role MapfixRelease changes status from Uploading -> Validated.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/reset-uploading
|
||||
func (svc *Service) ActionMapfixValidated(ctx context.Context, params api.ActionMapfixValidatedParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
has_role, err := userInfo.HasRoleMapfixUpload()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller has required role
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNeedRoleMapUpload
|
||||
}
|
||||
|
||||
// check when mapfix was updated
|
||||
mapfix, err := svc.DB.Mapfixes().Get(ctx, params.MapfixID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if time.Now().Before(mapfix.UpdatedAt.Add(time.Second*10)) {
|
||||
// the last time the mapfix was updated must be longer than 10 seconds ago
|
||||
return ErrDelayReset
|
||||
}
|
||||
|
||||
// transaction
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.MapfixStatusValidated)
|
||||
return svc.DB.Mapfixes().IfStatusThenUpdate(ctx, params.MapfixID, []model.MapfixStatus{model.MapfixStatusUploading}, smap)
|
||||
}
|
||||
|
||||
// ActionMapfixTriggerValidate invokes actionMapfixTriggerValidate operation.
|
||||
//
|
||||
// Role Reviewer triggers validation and changes status from Submitted -> Validating.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/trigger-validate
|
||||
func (svc *Service) ActionMapfixTriggerValidate(ctx context.Context, params api.ActionMapfixTriggerValidateParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
has_role, err := userInfo.HasRoleMapfixReview()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller has required role
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNeedRoleMapReview
|
||||
}
|
||||
|
||||
// read mapfix (this could be done with a transaction WHERE clause)
|
||||
mapfix, err := svc.DB.Mapfixes().Get(ctx, params.MapfixID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
has_role, err = userInfo.IsSubmitter(uint64(mapfix.Submitter))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller is NOT the submitter
|
||||
if has_role {
|
||||
return ErrAcceptOwnMapfix
|
||||
}
|
||||
|
||||
// Check if an active mapfix with the same target asset id exists
|
||||
if mapfix.TargetAssetID != 0 {
|
||||
filter := datastore.Optional()
|
||||
filter.Add("target_asset_id", mapfix.TargetAssetID)
|
||||
filter.Add("status_id", ActiveAcceptedMapfixStatuses)
|
||||
active_mapfixes, err := svc.DB.Mapfixes().List(ctx, filter, model.Page{
|
||||
Number: 1,
|
||||
Size: 1,
|
||||
},datastore.ListSortDisabled)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(active_mapfixes) != 0{
|
||||
return ErrActiveMapfixSameTargetAssetID
|
||||
}
|
||||
}
|
||||
|
||||
// transaction
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.MapfixStatusValidating)
|
||||
mapfix, err = svc.DB.Mapfixes().IfStatusThenUpdateAndGet(ctx, params.MapfixID, []model.MapfixStatus{model.MapfixStatusSubmitted}, smap)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
validate_request := model.ValidateMapfixRequest{
|
||||
MapfixID: mapfix.ID,
|
||||
ModelID: mapfix.AssetID,
|
||||
ModelVersion: mapfix.AssetVersion,
|
||||
ValidatedModelID: nil,
|
||||
}
|
||||
|
||||
// sentinel values because we're not using rust
|
||||
if mapfix.ValidatedAssetID != 0 {
|
||||
validate_request.ValidatedModelID = &mapfix.ValidatedAssetID
|
||||
}
|
||||
|
||||
j, err := json.Marshal(validate_request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
svc.Nats.Publish("maptest.mapfixes.validate", []byte(j))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ActionMapfixRetryValidate invokes actionMapfixRetryValidate operation.
|
||||
//
|
||||
// Role Reviewer re-runs validation and changes status from Accepted -> Validating.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/retry-validate
|
||||
func (svc *Service) ActionMapfixRetryValidate(ctx context.Context, params api.ActionMapfixRetryValidateParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
has_role, err := userInfo.HasRoleMapfixReview()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller has required role
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNeedRoleMapReview
|
||||
}
|
||||
|
||||
// transaction
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.MapfixStatusValidating)
|
||||
mapfix, err := svc.DB.Mapfixes().IfStatusThenUpdateAndGet(ctx, params.MapfixID, []model.MapfixStatus{model.MapfixStatusAccepted}, smap)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
validate_request := model.ValidateMapfixRequest{
|
||||
MapfixID: mapfix.ID,
|
||||
ModelID: mapfix.AssetID,
|
||||
ModelVersion: mapfix.AssetVersion,
|
||||
ValidatedModelID: nil,
|
||||
}
|
||||
|
||||
// sentinel values because we're not using rust
|
||||
if mapfix.ValidatedAssetID != 0 {
|
||||
validate_request.ValidatedModelID = &mapfix.ValidatedAssetID
|
||||
}
|
||||
|
||||
j, err := json.Marshal(validate_request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
svc.Nats.Publish("maptest.mapfixes.validate", []byte(j))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ActionMapfixAccepted implements actionMapfixAccepted operation.
|
||||
//
|
||||
// Role MapfixReview changes status from Validating -> Accepted.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/reset-validating
|
||||
func (svc *Service) ActionMapfixAccepted(ctx context.Context, params api.ActionMapfixAcceptedParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
has_role, err := userInfo.HasRoleMapfixReview()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller has required role
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNeedRoleMapReview
|
||||
}
|
||||
|
||||
// check when mapfix was updated
|
||||
mapfix, err := svc.DB.Mapfixes().Get(ctx, params.MapfixID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if time.Now().Before(mapfix.UpdatedAt.Add(time.Second*10)) {
|
||||
// the last time the mapfix was updated must be longer than 10 seconds ago
|
||||
return ErrDelayReset
|
||||
}
|
||||
|
||||
// transaction
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.MapfixStatusAccepted)
|
||||
smap.Add("status_message", "Manually forced reset")
|
||||
return svc.DB.Mapfixes().IfStatusThenUpdate(ctx, params.MapfixID, []model.MapfixStatus{model.MapfixStatusValidating}, smap)
|
||||
func (svc *Service) UpdateAndGetMapfixIfStatus(ctx context.Context, id int64, statuses []model.MapfixStatus, pmap MapfixUpdate) (model.Mapfix, error) {
|
||||
return svc.db.Mapfixes().IfStatusThenUpdateAndGet(ctx, id, statuses, datastore.OptionalMap(pmap))
|
||||
}
|
||||
|
||||
188
pkg/service/maps.go
Normal file
188
pkg/service/maps.go
Normal file
@@ -0,0 +1,188 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"git.itzana.me/strafesnet/go-grpc/maps"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/datastore"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
)
|
||||
|
||||
// Optional map used to update an object
|
||||
type MapUpdate datastore.OptionalMap
|
||||
|
||||
func NewMapUpdate() MapUpdate {
|
||||
update := datastore.Optional()
|
||||
return MapUpdate(update)
|
||||
}
|
||||
|
||||
func (update MapUpdate) SetDisplayName(display_name string) {
|
||||
datastore.OptionalMap(update).Add("display_name", display_name)
|
||||
}
|
||||
func (update MapUpdate) SetCreator(creator string) {
|
||||
datastore.OptionalMap(update).Add("creator", creator)
|
||||
}
|
||||
func (update MapUpdate) SetGameID(game_id uint32) {
|
||||
datastore.OptionalMap(update).Add("game_id", game_id)
|
||||
}
|
||||
func (update MapUpdate) SetDate(date int64) {
|
||||
datastore.OptionalMap(update).Add("date", date)
|
||||
}
|
||||
func (update MapUpdate) SetSubmitter(submitter uint64) {
|
||||
datastore.OptionalMap(update).Add("submitter", submitter)
|
||||
}
|
||||
func (update MapUpdate) SetThumbnail(thumbnail uint64) {
|
||||
datastore.OptionalMap(update).Add("thumbnail", thumbnail)
|
||||
}
|
||||
func (update MapUpdate) SetAssetVersion(asset_version uint64) {
|
||||
datastore.OptionalMap(update).Add("asset_version", asset_version)
|
||||
}
|
||||
func (update MapUpdate) SetModes(modes uint32) {
|
||||
datastore.OptionalMap(update).Add("modes", modes)
|
||||
}
|
||||
|
||||
// getters
|
||||
func (update MapUpdate) GetDisplayName() (string, bool) {
|
||||
value, ok := datastore.OptionalMap(update).Map()["display_name"].(string)
|
||||
return value, ok
|
||||
}
|
||||
func (update MapUpdate) GetCreator() (string, bool) {
|
||||
value, ok := datastore.OptionalMap(update).Map()["creator"].(string)
|
||||
return value, ok
|
||||
}
|
||||
func (update MapUpdate) GetGameID() (uint32, bool) {
|
||||
value, ok := datastore.OptionalMap(update).Map()["game_id"].(uint32)
|
||||
return value, ok
|
||||
}
|
||||
func (update MapUpdate) GetDate() (int64, bool) {
|
||||
value, ok := datastore.OptionalMap(update).Map()["date"].(int64)
|
||||
return value, ok
|
||||
}
|
||||
|
||||
// Optional map used to find matching objects
|
||||
type MapFilter datastore.OptionalMap
|
||||
|
||||
func NewMapFilter(
|
||||
) MapFilter {
|
||||
filter := datastore.Optional()
|
||||
return MapFilter(filter)
|
||||
}
|
||||
func (update MapFilter) SetDisplayName(display_name string) {
|
||||
datastore.OptionalMap(update).Add("display_name", display_name)
|
||||
}
|
||||
func (update MapFilter) SetCreator(creator string) {
|
||||
datastore.OptionalMap(update).Add("creator", creator)
|
||||
}
|
||||
func (update MapFilter) SetGameID(game_id uint32) {
|
||||
datastore.OptionalMap(update).Add("game_id", game_id)
|
||||
}
|
||||
func (update MapFilter) SetSubmitter(submitter uint64) {
|
||||
datastore.OptionalMap(update).Add("submitter", submitter)
|
||||
}
|
||||
|
||||
func (svc *Service) TEMP_DoMapsMigration(ctx context.Context) (error) {
|
||||
// get all maps
|
||||
maps, err := svc.maps.List(ctx, &maps.ListRequest{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// create all maps
|
||||
for _, item := range maps.Maps {
|
||||
migrated := model.Map{
|
||||
ID: item.ID,
|
||||
DisplayName: item.DisplayName,
|
||||
Creator: item.Creator,
|
||||
GameID: uint32(item.GameID),
|
||||
Date: time.Unix(item.Date, 0),
|
||||
// CreatedAt: time.Time{},
|
||||
// UpdatedAt: time.Time{},
|
||||
// Submitter: 0,
|
||||
// Thumbnail: 0,
|
||||
// AssetVersion: 0,
|
||||
// LoadCount: 0,
|
||||
// Modes: 0,
|
||||
}
|
||||
_, err := svc.db.Maps().Create(ctx, migrated)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (svc *Service) CreateMap(ctx context.Context, item model.Map) (int64, error) {
|
||||
// 2 jobs:
|
||||
// create map on maps-service
|
||||
map_item, err := svc.db.Maps().Create(ctx, item)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
// create map on data-service
|
||||
date := item.Date.Unix()
|
||||
game_id := int32(item.GameID)
|
||||
_, err = svc.maps.Create(ctx, &maps.MapRequest{
|
||||
ID: item.ID,
|
||||
DisplayName: &item.DisplayName,
|
||||
Creator: &item.Creator,
|
||||
GameID: &game_id,
|
||||
Date: &date,
|
||||
})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return map_item.ID, nil
|
||||
}
|
||||
|
||||
func (svc *Service) ListMaps(ctx context.Context, filter MapFilter, page model.Page) ([]model.Map, error) {
|
||||
return svc.db.Maps().List(ctx, datastore.OptionalMap(filter), page)
|
||||
}
|
||||
|
||||
func (svc *Service) GetMapList(ctx context.Context, ids []int64) ([]model.Map, error) {
|
||||
return svc.db.Maps().GetList(ctx, ids)
|
||||
}
|
||||
|
||||
func (svc *Service) DeleteMap(ctx context.Context, id int64) error {
|
||||
// Do not delete the "embedded" map, since it deletes times.
|
||||
// _, err := svc.maps.Delete(ctx, &maps.IdMessage{ID: id})
|
||||
return svc.db.Maps().Delete(ctx, id)
|
||||
}
|
||||
|
||||
func (svc *Service) GetMap(ctx context.Context, id int64) (model.Map, error) {
|
||||
return svc.db.Maps().Get(ctx, id)
|
||||
}
|
||||
|
||||
func (svc *Service) UpdateMap(ctx context.Context, id int64, pmap MapUpdate) error {
|
||||
// 2 jobs:
|
||||
// update map on maps-service
|
||||
err := svc.db.Maps().Update(ctx, id, datastore.OptionalMap(pmap))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// update map on data-service
|
||||
update := maps.MapRequest{
|
||||
ID: id,
|
||||
}
|
||||
if display_name, ok := pmap.GetDisplayName(); ok {
|
||||
update.DisplayName = &display_name
|
||||
}
|
||||
if creator, ok := pmap.GetCreator(); ok {
|
||||
update.Creator = &creator
|
||||
}
|
||||
if game_id, ok := pmap.GetGameID(); ok {
|
||||
game_id_int32 := int32(game_id)
|
||||
update.GameID = &game_id_int32
|
||||
}
|
||||
if date, ok := pmap.GetDate(); ok {
|
||||
update.Date = &date
|
||||
}
|
||||
_, err = svc.maps.Update(ctx, &update)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (svc *Service) IncrementMapLoadCount(ctx context.Context, id int64) error {
|
||||
return svc.db.Maps().IncrementLoadCount(ctx, id)
|
||||
}
|
||||
114
pkg/service/nats_mapfix.go
Normal file
114
pkg/service/nats_mapfix.go
Normal file
@@ -0,0 +1,114 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
)
|
||||
|
||||
func (svc *Service) NatsCreateMapfix(
|
||||
OperationID int32,
|
||||
ModelID uint64,
|
||||
TargetAssetID uint64,
|
||||
Description string,
|
||||
) error {
|
||||
create_request := model.CreateMapfixRequest{
|
||||
OperationID: OperationID,
|
||||
ModelID: ModelID,
|
||||
TargetAssetID: TargetAssetID,
|
||||
Description: Description,
|
||||
}
|
||||
|
||||
j, err := json.Marshal(create_request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = svc.nats.Publish("maptest.mapfixes.create", []byte(j))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (svc *Service) NatsCheckMapfix(
|
||||
MapfixID int64,
|
||||
ModelID uint64,
|
||||
SkipChecks bool,
|
||||
) error {
|
||||
validate_request := model.CheckMapfixRequest{
|
||||
MapfixID: MapfixID,
|
||||
ModelID: ModelID,
|
||||
SkipChecks: SkipChecks,
|
||||
}
|
||||
|
||||
j, err := json.Marshal(validate_request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = svc.nats.Publish("maptest.mapfixes.check", []byte(j))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (svc *Service) NatsUploadMapfix(
|
||||
MapfixID int64,
|
||||
ModelID uint64,
|
||||
ModelVersion uint64,
|
||||
TargetAssetID uint64,
|
||||
) error {
|
||||
upload_fix_request := model.UploadMapfixRequest{
|
||||
MapfixID: MapfixID,
|
||||
ModelID: ModelID,
|
||||
ModelVersion: ModelVersion,
|
||||
TargetAssetID: TargetAssetID,
|
||||
}
|
||||
|
||||
j, err := json.Marshal(upload_fix_request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = svc.nats.Publish("maptest.mapfixes.upload", []byte(j))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (svc *Service) NatsValidateMapfix(
|
||||
MapfixID int64,
|
||||
ModelID uint64,
|
||||
ModelVersion uint64,
|
||||
ValidatedAssetID uint64,
|
||||
) error {
|
||||
validate_request := model.ValidateMapfixRequest{
|
||||
MapfixID: MapfixID,
|
||||
ModelID: ModelID,
|
||||
ModelVersion: ModelVersion,
|
||||
ValidatedModelID: nil,
|
||||
}
|
||||
|
||||
// sentinel values because we're not using rust
|
||||
if ValidatedAssetID != 0 {
|
||||
validate_request.ValidatedModelID = &ValidatedAssetID
|
||||
}
|
||||
|
||||
j, err := json.Marshal(validate_request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = svc.nats.Publish("maptest.mapfixes.validate", []byte(j))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
120
pkg/service/nats_submission.go
Normal file
120
pkg/service/nats_submission.go
Normal file
@@ -0,0 +1,120 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
)
|
||||
|
||||
func (svc *Service) NatsCreateSubmission(
|
||||
OperationID int32,
|
||||
ModelID uint64,
|
||||
DisplayName string,
|
||||
Creator string,
|
||||
GameID uint32,
|
||||
Status uint32,
|
||||
Roles uint32,
|
||||
) error {
|
||||
create_request := model.CreateSubmissionRequest{
|
||||
OperationID: OperationID,
|
||||
ModelID: ModelID,
|
||||
DisplayName: DisplayName,
|
||||
Creator: Creator,
|
||||
GameID: GameID,
|
||||
Status: Status,
|
||||
Roles: Roles,
|
||||
}
|
||||
|
||||
j, err := json.Marshal(create_request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = svc.nats.Publish("maptest.submissions.create", []byte(j))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (svc *Service) NatsCheckSubmission(
|
||||
SubmissionID int64,
|
||||
ModelID uint64,
|
||||
SkipChecks bool,
|
||||
) error {
|
||||
validate_request := model.CheckSubmissionRequest{
|
||||
SubmissionID: SubmissionID,
|
||||
ModelID: ModelID,
|
||||
SkipChecks: SkipChecks,
|
||||
}
|
||||
|
||||
j, err := json.Marshal(validate_request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = svc.nats.Publish("maptest.submissions.check", []byte(j))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (svc *Service) NatsUploadSubmission(
|
||||
SubmissionID int64,
|
||||
ModelID uint64,
|
||||
ModelVersion uint64,
|
||||
ModelName string,
|
||||
) error {
|
||||
upload_new_request := model.UploadSubmissionRequest{
|
||||
SubmissionID: SubmissionID,
|
||||
ModelID: ModelID,
|
||||
ModelVersion: ModelVersion,
|
||||
ModelName: ModelName,
|
||||
}
|
||||
|
||||
j, err := json.Marshal(upload_new_request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = svc.nats.Publish("maptest.submissions.upload", []byte(j))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (svc *Service) NatsValidateSubmission(
|
||||
SubmissionID int64,
|
||||
ModelID uint64,
|
||||
ModelVersion uint64,
|
||||
ValidatedModelID uint64,
|
||||
) error {
|
||||
validate_request := model.ValidateSubmissionRequest{
|
||||
SubmissionID: SubmissionID,
|
||||
ModelID: ModelID,
|
||||
ModelVersion: ModelVersion,
|
||||
ValidatedModelID: nil,
|
||||
}
|
||||
|
||||
// sentinel values because we're not using rust
|
||||
if ValidatedModelID != 0 {
|
||||
validate_request.ValidatedModelID = &ValidatedModelID
|
||||
}
|
||||
|
||||
j, err := json.Marshal(validate_request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = svc.nats.Publish("maptest.submissions.validate", []byte(j))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
55
pkg/service/operations.go
Normal file
55
pkg/service/operations.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/datastore"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
)
|
||||
|
||||
type OperationFailParams datastore.OptionalMap
|
||||
|
||||
func NewOperationFailParams(
|
||||
status_message string,
|
||||
) OperationFailParams {
|
||||
filter := datastore.Optional()
|
||||
filter.Add("status_id", model.OperationStatusFailed)
|
||||
filter.Add("status_message", status_message)
|
||||
return OperationFailParams(filter)
|
||||
}
|
||||
|
||||
type OperationCompleteParams datastore.OptionalMap
|
||||
|
||||
func NewOperationCompleteParams(
|
||||
path string,
|
||||
) OperationCompleteParams {
|
||||
filter := datastore.Optional()
|
||||
filter.Add("status_id", model.OperationStatusCompleted)
|
||||
filter.Add("path", path)
|
||||
return OperationCompleteParams(filter)
|
||||
}
|
||||
|
||||
func (svc *Service) CreateOperation(ctx context.Context, operation model.Operation) (model.Operation, error) {
|
||||
return svc.db.Operations().Create(ctx, operation)
|
||||
}
|
||||
|
||||
func (svc *Service) CountOperationsSince(ctx context.Context, owner int64, since time.Time) (int64, error) {
|
||||
return svc.db.Operations().CountSince(ctx, owner, since)
|
||||
}
|
||||
|
||||
func (svc *Service) DeleteOperation(ctx context.Context, id int32) error {
|
||||
return svc.db.Operations().Delete(ctx, id)
|
||||
}
|
||||
|
||||
func (svc *Service) GetOperation(ctx context.Context, id int32) (model.Operation, error) {
|
||||
return svc.db.Operations().Get(ctx, id)
|
||||
}
|
||||
|
||||
func (svc *Service) FailOperation(ctx context.Context, id int32, params OperationFailParams) error {
|
||||
return svc.db.Operations().Update(ctx, id, datastore.OptionalMap(params))
|
||||
}
|
||||
|
||||
func (svc *Service) CompleteOperation(ctx context.Context, id int32, params OperationCompleteParams) error {
|
||||
return svc.db.Operations().Update(ctx, id, datastore.OptionalMap(params))
|
||||
}
|
||||
@@ -3,176 +3,43 @@ package service
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/api"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/datastore"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
)
|
||||
|
||||
// CreateScriptPolicy implements createScriptPolicy operation.
|
||||
//
|
||||
// Create a new script policy.
|
||||
//
|
||||
// POST /script-policy
|
||||
func (svc *Service) CreateScriptPolicy(ctx context.Context, req *api.ScriptPolicyCreate) (*api.ID, error) {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return nil, ErrUserInfo
|
||||
}
|
||||
type ScriptPolicyFilter datastore.OptionalMap
|
||||
|
||||
has_role, err := userInfo.HasRoleScriptWrite()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !has_role {
|
||||
return nil, ErrPermissionDenied
|
||||
}
|
||||
|
||||
from_script, err := svc.DB.Scripts().Get(ctx, req.FromScriptID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// the existence of ToScriptID does not need to be validated because it's checked by a foreign key constraint.
|
||||
|
||||
script, err := svc.DB.ScriptPolicy().Create(ctx, model.ScriptPolicy{
|
||||
ID: 0,
|
||||
FromScriptHash: from_script.Hash,
|
||||
ToScriptID: req.ToScriptID,
|
||||
Policy: model.Policy(req.Policy),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &api.ID{
|
||||
ID: script.ID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
// ListScriptPolicy implements listScriptPolicy operation.
|
||||
//
|
||||
// Get list of script policies.
|
||||
//
|
||||
// GET /script-policy
|
||||
func (svc *Service) ListScriptPolicy(ctx context.Context, params api.ListScriptPolicyParams) ([]api.ScriptPolicy, error) {
|
||||
func NewScriptPolicyFilter() ScriptPolicyFilter {
|
||||
filter := datastore.Optional()
|
||||
|
||||
if params.FromScriptHash.IsSet(){
|
||||
hash, err := model.HashParse(params.FromScriptHash.Value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
filter.AddNotNil("from_script_hash", int64(hash)) // No type safety!
|
||||
}
|
||||
if params.ToScriptID.IsSet(){
|
||||
filter.AddNotNil("to_script_id", params.ToScriptID.Value)
|
||||
}
|
||||
if params.Policy.IsSet(){
|
||||
filter.AddNotNil("policy", params.Policy.Value)
|
||||
}
|
||||
|
||||
items, err := svc.DB.ScriptPolicy().List(ctx, filter, model.Page{
|
||||
Number: params.Page,
|
||||
Size: params.Limit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var resp []api.ScriptPolicy
|
||||
for _, item := range items {
|
||||
resp = append(resp, api.ScriptPolicy{
|
||||
ID: item.ID,
|
||||
FromScriptHash: model.HashFormat(uint64(item.FromScriptHash)),
|
||||
ToScriptID: item.ToScriptID,
|
||||
Policy: int32(item.Policy),
|
||||
})
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
return ScriptPolicyFilter(filter)
|
||||
}
|
||||
func (filter ScriptPolicyFilter) SetFromScriptHash(from_script_hash int64) {
|
||||
// Finally, type safety!
|
||||
datastore.OptionalMap(filter).Add("from_script_hash", from_script_hash)
|
||||
}
|
||||
func (filter ScriptPolicyFilter) SetToScriptID(to_script_id int64) {
|
||||
datastore.OptionalMap(filter).Add("to_script_id", to_script_id)
|
||||
}
|
||||
func (filter ScriptPolicyFilter) SetPolicy(policy int32) {
|
||||
datastore.OptionalMap(filter).Add("policy", policy)
|
||||
}
|
||||
|
||||
// DeleteScriptPolicy implements deleteScriptPolicy operation.
|
||||
//
|
||||
// Delete the specified script policy by ID.
|
||||
//
|
||||
// DELETE /script-policy/{ScriptPolicyID}
|
||||
func (svc *Service) DeleteScriptPolicy(ctx context.Context, params api.DeleteScriptPolicyParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
has_role, err := userInfo.HasRoleScriptWrite()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !has_role {
|
||||
return ErrPermissionDenied
|
||||
}
|
||||
|
||||
return svc.DB.ScriptPolicy().Delete(ctx, params.ScriptPolicyID)
|
||||
func (svc *Service) CreateScriptPolicy(ctx context.Context, script model.ScriptPolicy) (model.ScriptPolicy, error) {
|
||||
return svc.db.ScriptPolicy().Create(ctx, script)
|
||||
}
|
||||
|
||||
// GetScriptPolicy implements getScriptPolicy operation.
|
||||
//
|
||||
// Get the specified script policy by ID.
|
||||
//
|
||||
// GET /script-policy/{ScriptPolicyID}
|
||||
func (svc *Service) GetScriptPolicy(ctx context.Context, params api.GetScriptPolicyParams) (*api.ScriptPolicy, error) {
|
||||
_, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return nil, ErrUserInfo
|
||||
}
|
||||
|
||||
// Read permission for script policy only requires you to be logged in
|
||||
|
||||
policy, err := svc.DB.ScriptPolicy().Get(ctx, params.ScriptPolicyID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &api.ScriptPolicy{
|
||||
ID: policy.ID,
|
||||
FromScriptHash: model.HashFormat(uint64(policy.FromScriptHash)),
|
||||
ToScriptID: policy.ToScriptID,
|
||||
Policy: int32(policy.Policy),
|
||||
}, nil
|
||||
func (svc *Service) ListScriptPolicies(ctx context.Context, filter ScriptPolicyFilter, page model.Page) ([]model.ScriptPolicy, error) {
|
||||
return svc.db.ScriptPolicy().List(ctx, datastore.OptionalMap(filter), page)
|
||||
}
|
||||
|
||||
// UpdateScriptPolicy implements updateScriptPolicy operation.
|
||||
//
|
||||
// Update the specified script policy by ID.
|
||||
//
|
||||
// POST /script-policy/{ScriptPolicyID}
|
||||
func (svc *Service) UpdateScriptPolicy(ctx context.Context, req *api.ScriptPolicyUpdate, params api.UpdateScriptPolicyParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
has_role, err := userInfo.HasRoleScriptWrite()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !has_role {
|
||||
return ErrPermissionDenied
|
||||
}
|
||||
|
||||
pmap := datastore.Optional()
|
||||
if from_script_id, ok := req.FromScriptID.Get(); ok {
|
||||
from_script, err := svc.DB.Scripts().Get(ctx, from_script_id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pmap.Add("from_script_hash", from_script.Hash)
|
||||
}
|
||||
if to_script_id, ok := req.ToScriptID.Get(); ok {
|
||||
pmap.Add("to_script_id", to_script_id)
|
||||
}
|
||||
if policy, ok := req.Policy.Get(); ok {
|
||||
pmap.Add("policy", policy)
|
||||
}
|
||||
return svc.DB.ScriptPolicy().Update(ctx, req.ID, pmap)
|
||||
func (svc *Service) DeleteScriptPolicy(ctx context.Context, id int64) error {
|
||||
return svc.db.ScriptPolicy().Delete(ctx, id)
|
||||
}
|
||||
|
||||
func (svc *Service) GetScriptPolicy(ctx context.Context, id int64) (model.ScriptPolicy, error) {
|
||||
return svc.db.ScriptPolicy().Get(ctx, id)
|
||||
}
|
||||
|
||||
func (svc *Service) UpdateScriptPolicy(ctx context.Context, id int64, pmap ScriptPolicyFilter) error {
|
||||
return svc.db.ScriptPolicy().Update(ctx, id, datastore.OptionalMap(pmap))
|
||||
}
|
||||
|
||||
@@ -3,179 +3,48 @@ package service
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/api"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/datastore"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
)
|
||||
|
||||
// CreateScript implements createScript operation.
|
||||
//
|
||||
// Create a new script.
|
||||
//
|
||||
// POST /scripts
|
||||
func (svc *Service) CreateScript(ctx context.Context, req *api.ScriptCreate) (*api.ID, error) {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return nil, ErrUserInfo
|
||||
}
|
||||
type ScriptFilter datastore.OptionalMap
|
||||
|
||||
has_role, err := userInfo.HasRoleScriptWrite()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !has_role {
|
||||
return nil, ErrPermissionDenied
|
||||
}
|
||||
|
||||
script, err := svc.DB.Scripts().Create(ctx, model.Script{
|
||||
ID: 0,
|
||||
Name: req.Name,
|
||||
Hash: int64(model.HashSource(req.Source)),
|
||||
Source: req.Source,
|
||||
ResourceType: model.ResourceType(req.ResourceType),
|
||||
ResourceID: req.ResourceID.Or(0),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &api.ID{
|
||||
ID: script.ID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ListScripts implements listScripts operation.
|
||||
//
|
||||
// Get list of scripts.
|
||||
//
|
||||
// GET /scripts
|
||||
func (svc *Service) ListScripts(ctx context.Context, params api.ListScriptsParams) ([]api.Script, error) {
|
||||
func NewScriptFilter() ScriptFilter {
|
||||
filter := datastore.Optional()
|
||||
|
||||
if params.Hash.IsSet(){
|
||||
hash, err := model.HashParse(params.Hash.Value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
filter.AddNotNil("hash", int64(hash)) // No type safety!
|
||||
}
|
||||
if params.Name.IsSet(){
|
||||
filter.AddNotNil("name", params.Name.Value)
|
||||
}
|
||||
if params.Source.IsSet(){
|
||||
filter.AddNotNil("source", params.Source.Value)
|
||||
}
|
||||
if params.ResourceType.IsSet(){
|
||||
filter.AddNotNil("resource_type", params.ResourceType.Value)
|
||||
}
|
||||
if params.ResourceID.IsSet(){
|
||||
filter.AddNotNil("resource_id", params.ResourceID.Value)
|
||||
}
|
||||
|
||||
items, err := svc.DB.Scripts().List(ctx, filter, model.Page{
|
||||
Number: params.Page,
|
||||
Size: params.Limit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var resp []api.Script
|
||||
for _, item := range items {
|
||||
resp = append(resp, api.Script{
|
||||
ID: item.ID,
|
||||
Hash: model.HashFormat(uint64(item.Hash)),
|
||||
Source: item.Source,
|
||||
ResourceType: int32(item.ResourceType),
|
||||
ResourceID: item.ResourceID,
|
||||
})
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
return ScriptFilter(filter)
|
||||
}
|
||||
func (filter ScriptFilter) SetName(name string) {
|
||||
datastore.OptionalMap(filter).Add("name", name)
|
||||
}
|
||||
func (filter ScriptFilter) SetSource(source string) {
|
||||
datastore.OptionalMap(filter).Add("source", source)
|
||||
}
|
||||
func (filter ScriptFilter) SetHash(hash int64) {
|
||||
datastore.OptionalMap(filter).Add("hash", hash)
|
||||
}
|
||||
func (filter ScriptFilter) SetResourceType(resource_type int32) {
|
||||
datastore.OptionalMap(filter).Add("resource_type", resource_type)
|
||||
}
|
||||
func (filter ScriptFilter) SetResourceID(resource_id int64) {
|
||||
datastore.OptionalMap(filter).Add("resource_id", resource_id)
|
||||
}
|
||||
|
||||
// DeleteScript implements deleteScript operation.
|
||||
//
|
||||
// Delete the specified script by ID.
|
||||
//
|
||||
// DELETE /scripts/{ScriptID}
|
||||
func (svc *Service) DeleteScript(ctx context.Context, params api.DeleteScriptParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
has_role, err := userInfo.HasRoleScriptWrite()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !has_role {
|
||||
return ErrPermissionDenied
|
||||
}
|
||||
|
||||
return svc.DB.Scripts().Delete(ctx, params.ScriptID)
|
||||
func (svc *Service) CreateScript(ctx context.Context, script model.Script) (model.Script, error) {
|
||||
return svc.db.Scripts().Create(ctx, script)
|
||||
}
|
||||
|
||||
// GetScript implements getScript operation.
|
||||
//
|
||||
// Get the specified script by ID.
|
||||
//
|
||||
// GET /scripts/{ScriptID}
|
||||
func (svc *Service) GetScript(ctx context.Context, params api.GetScriptParams) (*api.Script, error) {
|
||||
_, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return nil, ErrUserInfo
|
||||
}
|
||||
|
||||
// Read permission for scripts only requires you to be logged in
|
||||
|
||||
script, err := svc.DB.Scripts().Get(ctx, params.ScriptID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &api.Script{
|
||||
ID: script.ID,
|
||||
Name: script.Name,
|
||||
Hash: model.HashFormat(uint64(script.Hash)),
|
||||
Source: script.Source,
|
||||
ResourceType: int32(script.ResourceType),
|
||||
ResourceID: script.ResourceID,
|
||||
}, nil
|
||||
func (svc *Service) ListScripts(ctx context.Context, filter ScriptFilter, page model.Page) ([]model.Script, error) {
|
||||
return svc.db.Scripts().List(ctx, datastore.OptionalMap(filter), page)
|
||||
}
|
||||
|
||||
// UpdateScript implements updateScript operation.
|
||||
//
|
||||
// Update the specified script by ID.
|
||||
//
|
||||
// PATCH /scripts/{ScriptID}
|
||||
func (svc *Service) UpdateScript(ctx context.Context, req *api.ScriptUpdate, params api.UpdateScriptParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
has_role, err := userInfo.HasRoleScriptWrite()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !has_role {
|
||||
return ErrPermissionDenied
|
||||
}
|
||||
|
||||
pmap := datastore.Optional()
|
||||
if Name, ok := req.Name.Get(); ok {
|
||||
pmap.Add("name", Name)
|
||||
}
|
||||
if source, ok := req.Source.Get(); ok {
|
||||
pmap.Add("source", source)
|
||||
pmap.Add("hash", int64(model.HashSource(source))) // No type safety!
|
||||
}
|
||||
if ResourceType, ok := req.ResourceType.Get(); ok {
|
||||
pmap.Add("resource_type", ResourceType)
|
||||
}
|
||||
if ResourceID, ok := req.ResourceID.Get(); ok {
|
||||
pmap.Add("resource_id", ResourceID)
|
||||
}
|
||||
return svc.DB.Scripts().Update(ctx, req.ID, pmap)
|
||||
func (svc *Service) DeleteScript(ctx context.Context, id int64) error {
|
||||
return svc.db.Scripts().Delete(ctx, id)
|
||||
}
|
||||
|
||||
func (svc *Service) GetScript(ctx context.Context, id int64) (model.Script, error) {
|
||||
return svc.db.Scripts().Get(ctx, id)
|
||||
}
|
||||
|
||||
func (svc *Service) UpdateScript(ctx context.Context, id int64, pmap ScriptFilter) error {
|
||||
return svc.db.Scripts().Update(ctx, id, datastore.OptionalMap(pmap))
|
||||
}
|
||||
|
||||
@@ -1,56 +1,29 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"git.itzana.me/strafesnet/go-grpc/maps"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/api"
|
||||
"git.itzana.me/strafesnet/go-grpc/users"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/datastore"
|
||||
"github.com/nats-io/nats.go"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrPermissionDenied caller does not have the required role
|
||||
ErrPermissionDenied = errors.New("Permission denied")
|
||||
// ErrUserInfo user info is missing for some reason
|
||||
ErrUserInfo = errors.New("Missing user info")
|
||||
ErrDelayReset = errors.New("Please give the validator at least 10 seconds to operate before attempting to reset the status")
|
||||
ErrPermissionDeniedNotSubmitter = fmt.Errorf("%w: You must be the submitter to perform this action", ErrPermissionDenied)
|
||||
ErrPermissionDeniedNeedRoleSubmissionRelease = fmt.Errorf("%w: Need Role SubmissionRelease", ErrPermissionDenied)
|
||||
ErrPermissionDeniedNeedRoleMapUpload = fmt.Errorf("%w: Need Role MapUpload", ErrPermissionDenied)
|
||||
ErrPermissionDeniedNeedRoleMapReview = fmt.Errorf("%w: Need Role MapReview", ErrPermissionDenied)
|
||||
ErrPermissionDeniedNeedRoleMapDownload = fmt.Errorf("%w: Need Role MapDownload", ErrPermissionDenied)
|
||||
ErrPermissionDeniedNeedRoleScriptWrite = fmt.Errorf("%w: Need Role ScriptWrite", ErrPermissionDenied)
|
||||
ErrPermissionDeniedNeedRoleMaptest = fmt.Errorf("%w: Need Role Maptest", ErrPermissionDenied)
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
DB datastore.Datastore
|
||||
Nats nats.JetStreamContext
|
||||
Client maps.MapsServiceClient
|
||||
db datastore.Datastore
|
||||
nats nats.JetStreamContext
|
||||
maps maps.MapsServiceClient
|
||||
users users.UsersServiceClient
|
||||
}
|
||||
|
||||
// NewError creates *ErrorStatusCode from error returned by handler.
|
||||
//
|
||||
// Used for common default response.
|
||||
func (svc *Service) NewError(ctx context.Context, err error) *api.ErrorStatusCode {
|
||||
status := 500
|
||||
if errors.Is(err, datastore.ErrNotExist) {
|
||||
status = 404
|
||||
}
|
||||
if errors.Is(err, ErrPermissionDenied) {
|
||||
status = 403
|
||||
}
|
||||
if errors.Is(err, ErrUserInfo) {
|
||||
status = 401
|
||||
}
|
||||
return &api.ErrorStatusCode{
|
||||
StatusCode: status,
|
||||
Response: api.Error{
|
||||
Code: int64(status),
|
||||
Message: err.Error(),
|
||||
},
|
||||
func NewService(
|
||||
db datastore.Datastore,
|
||||
nats nats.JetStreamContext,
|
||||
maps maps.MapsServiceClient,
|
||||
users users.UsersServiceClient,
|
||||
) Service {
|
||||
return Service{
|
||||
db: db,
|
||||
nats: nats,
|
||||
maps: maps,
|
||||
users: users,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,675 +2,119 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.itzana.me/strafesnet/go-grpc/maps"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/api"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/datastore"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
)
|
||||
|
||||
var(
|
||||
CreationPhaseSubmissionsLimit = 20
|
||||
CreationPhaseSubmissionStatuses = []model.SubmissionStatus{
|
||||
model.SubmissionStatusChangesRequested,
|
||||
model.SubmissionStatusSubmitted,
|
||||
model.SubmissionStatusUnderConstruction,
|
||||
}
|
||||
// prevent two mapfixes with same asset id
|
||||
ActiveSubmissionStatuses = []model.SubmissionStatus{
|
||||
model.SubmissionStatusUploading,
|
||||
model.SubmissionStatusValidated,
|
||||
model.SubmissionStatusValidating,
|
||||
model.SubmissionStatusAccepted,
|
||||
model.SubmissionStatusChangesRequested,
|
||||
model.SubmissionStatusSubmitted,
|
||||
model.SubmissionStatusUnderConstruction,
|
||||
}
|
||||
// limit mapfixes in the pipeline to one per target map
|
||||
ActiveAcceptedSubmissionStatuses = []model.SubmissionStatus{
|
||||
model.SubmissionStatusUploading,
|
||||
model.SubmissionStatusValidated,
|
||||
model.SubmissionStatusValidating,
|
||||
model.SubmissionStatusAccepted,
|
||||
}
|
||||
)
|
||||
type SubmissionUpdate datastore.OptionalMap
|
||||
|
||||
var (
|
||||
ErrCreationPhaseSubmissionsLimit = errors.New("Active submissions limited to 20")
|
||||
ErrActiveSubmissionSameAssetID = errors.New("There is an active submission with the same AssetID")
|
||||
ErrUploadedAssetIDAlreadyExists = errors.New("The submission UploadedAssetID is already set")
|
||||
ErrReleaseInvalidStatus = errors.New("Only submissions with Uploaded status can be released")
|
||||
ErrReleaseNoUploadedAssetID = errors.New("Only submissions with a UploadedAssetID can be released")
|
||||
ErrAcceptOwnSubmission = fmt.Errorf("%w: You cannot accept your own submission as the submitter", ErrPermissionDenied)
|
||||
)
|
||||
|
||||
// POST /submissions
|
||||
func (svc *Service) CreateSubmission(ctx context.Context, request *api.SubmissionCreate) (*api.ID, error) {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return nil, ErrUserInfo
|
||||
}
|
||||
|
||||
userId, err := userInfo.GetUserID()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Check if user's submissions in the creation phase exceeds the limit
|
||||
{
|
||||
filter := datastore.Optional()
|
||||
filter.Add("submitter", int64(userId))
|
||||
filter.Add("status_id", CreationPhaseSubmissionStatuses)
|
||||
creation_submissions, err := svc.DB.Submissions().List(ctx, filter, model.Page{
|
||||
Number: 1,
|
||||
Size: int32(CreationPhaseSubmissionsLimit),
|
||||
},datastore.ListSortDisabled)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if CreationPhaseSubmissionsLimit <= len(creation_submissions) {
|
||||
return nil, ErrCreationPhaseSubmissionsLimit
|
||||
}
|
||||
}
|
||||
|
||||
// Check if an active submission with the same asset id exists
|
||||
{
|
||||
filter := datastore.Optional()
|
||||
filter.Add("asset_id", request.AssetID)
|
||||
filter.Add("asset_version", request.AssetVersion)
|
||||
filter.Add("status_id", ActiveSubmissionStatuses)
|
||||
active_submissions, err := svc.DB.Submissions().List(ctx, filter, model.Page{
|
||||
Number: 1,
|
||||
Size: 1,
|
||||
},datastore.ListSortDisabled)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(active_submissions) != 0{
|
||||
return nil, ErrActiveSubmissionSameAssetID
|
||||
}
|
||||
}
|
||||
|
||||
submission, err := svc.DB.Submissions().Create(ctx, model.Submission{
|
||||
ID: 0,
|
||||
DisplayName: request.DisplayName,
|
||||
Creator: request.Creator,
|
||||
GameID: request.GameID,
|
||||
Submitter: int64(userId),
|
||||
AssetID: request.AssetID,
|
||||
AssetVersion: request.AssetVersion,
|
||||
Completed: false,
|
||||
StatusID: model.SubmissionStatusUnderConstruction,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &api.ID{
|
||||
ID: submission.ID,
|
||||
}, nil
|
||||
func NewSubmissionUpdate() SubmissionUpdate {
|
||||
update := datastore.Optional()
|
||||
return SubmissionUpdate(update)
|
||||
}
|
||||
|
||||
// GetSubmission implements getSubmission operation.
|
||||
//
|
||||
// Retrieve map with ID.
|
||||
//
|
||||
// GET /submissions/{SubmissionID}
|
||||
func (svc *Service) GetSubmission(ctx context.Context, params api.GetSubmissionParams) (*api.Submission, error) {
|
||||
submission, err := svc.DB.Submissions().Get(ctx, params.SubmissionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &api.Submission{
|
||||
ID: submission.ID,
|
||||
DisplayName: submission.DisplayName,
|
||||
Creator: submission.Creator,
|
||||
GameID: submission.GameID,
|
||||
CreatedAt: submission.CreatedAt.Unix(),
|
||||
UpdatedAt: submission.UpdatedAt.Unix(),
|
||||
Submitter: int64(submission.Submitter),
|
||||
AssetID: int64(submission.AssetID),
|
||||
AssetVersion: int64(submission.AssetVersion),
|
||||
Completed: submission.Completed,
|
||||
UploadedAssetID: api.NewOptInt64(int64(submission.UploadedAssetID)),
|
||||
StatusID: int32(submission.StatusID),
|
||||
StatusMessage: submission.StatusMessage,
|
||||
}, nil
|
||||
func (update SubmissionUpdate) SetDisplayName(display_name string) {
|
||||
datastore.OptionalMap(update).Add("display_name", display_name)
|
||||
}
|
||||
func (update SubmissionUpdate) SetCreator(creator string) {
|
||||
datastore.OptionalMap(update).Add("creator", creator)
|
||||
}
|
||||
func (update SubmissionUpdate) SetGameID(game_id uint32) {
|
||||
datastore.OptionalMap(update).Add("game_id", game_id)
|
||||
}
|
||||
func (update SubmissionUpdate) SetSubmitter(submitter uint64) {
|
||||
datastore.OptionalMap(update).Add("submitter", submitter)
|
||||
}
|
||||
func (update SubmissionUpdate) SetAssetID(asset_id uint64) {
|
||||
datastore.OptionalMap(update).Add("asset_id", asset_id)
|
||||
}
|
||||
func (update SubmissionUpdate) SetAssetVersion(asset_version uint64) {
|
||||
datastore.OptionalMap(update).Add("asset_version", asset_version)
|
||||
}
|
||||
func (update SubmissionUpdate) SetValidatedAssetID(validated_asset_id uint64) {
|
||||
datastore.OptionalMap(update).Add("validated_asset_id", validated_asset_id)
|
||||
}
|
||||
func (update SubmissionUpdate) SetValidatedAssetVersion(validated_asset_version uint64) {
|
||||
datastore.OptionalMap(update).Add("validated_asset_version", validated_asset_version)
|
||||
}
|
||||
func (update SubmissionUpdate) SetCompleted(completed bool) {
|
||||
datastore.OptionalMap(update).Add("completed", completed)
|
||||
}
|
||||
func (update SubmissionUpdate) SetUploadedAssetID(uploaded_asset_id uint64) {
|
||||
datastore.OptionalMap(update).Add("uploaded_asset_id", uploaded_asset_id)
|
||||
}
|
||||
func (update SubmissionUpdate) SetStatusID(status_id model.SubmissionStatus) {
|
||||
datastore.OptionalMap(update).Add("status_id", status_id)
|
||||
}
|
||||
func (update SubmissionUpdate) SetDescription(description string) {
|
||||
datastore.OptionalMap(update).Add("description", description)
|
||||
}
|
||||
|
||||
// ListSubmissions implements listSubmissions operation.
|
||||
//
|
||||
// Get list of submissions.
|
||||
//
|
||||
// GET /submissions
|
||||
func (svc *Service) ListSubmissions(ctx context.Context, params api.ListSubmissionsParams) ([]api.Submission, error) {
|
||||
type SubmissionFilter datastore.OptionalMap
|
||||
|
||||
func NewSubmissionFilter(
|
||||
) SubmissionFilter {
|
||||
filter := datastore.Optional()
|
||||
|
||||
if params.DisplayName.IsSet(){
|
||||
filter.Add("display_name", params.DisplayName.Value)
|
||||
}
|
||||
if params.Creator.IsSet(){
|
||||
filter.Add("creator", params.Creator.Value)
|
||||
}
|
||||
if params.GameID.IsSet(){
|
||||
filter.Add("game_id", params.GameID.Value)
|
||||
}
|
||||
|
||||
sort := datastore.ListSort(params.Sort.Or(int32(datastore.ListSortDisabled)))
|
||||
|
||||
items, err := svc.DB.Submissions().List(ctx, filter, model.Page{
|
||||
Number: params.Page,
|
||||
Size: params.Limit,
|
||||
},sort)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var resp []api.Submission
|
||||
for _, item := range items {
|
||||
resp = append(resp, api.Submission{
|
||||
ID: item.ID,
|
||||
DisplayName: item.DisplayName,
|
||||
Creator: item.Creator,
|
||||
GameID: item.GameID,
|
||||
CreatedAt: item.CreatedAt.Unix(),
|
||||
UpdatedAt: item.UpdatedAt.Unix(),
|
||||
Submitter: int64(item.Submitter),
|
||||
AssetID: int64(item.AssetID),
|
||||
AssetVersion: int64(item.AssetVersion),
|
||||
Completed: item.Completed,
|
||||
UploadedAssetID: api.NewOptInt64(int64(item.UploadedAssetID)),
|
||||
StatusID: int32(item.StatusID),
|
||||
})
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
return SubmissionFilter(filter)
|
||||
}
|
||||
func (update SubmissionFilter) SetDisplayName(display_name string) {
|
||||
datastore.OptionalMap(update).Add("display_name", display_name)
|
||||
}
|
||||
func (update SubmissionFilter) SetCreator(creator string) {
|
||||
datastore.OptionalMap(update).Add("creator", creator)
|
||||
}
|
||||
func (update SubmissionFilter) SetGameID(game_id uint32) {
|
||||
datastore.OptionalMap(update).Add("game_id", game_id)
|
||||
}
|
||||
func (update SubmissionFilter) SetSubmitter(submitter uint64) {
|
||||
datastore.OptionalMap(update).Add("submitter", submitter)
|
||||
}
|
||||
func (update SubmissionFilter) SetAssetID(asset_id uint64) {
|
||||
datastore.OptionalMap(update).Add("asset_id", asset_id)
|
||||
}
|
||||
func (update SubmissionFilter) SetAssetVersion(asset_version uint64) {
|
||||
datastore.OptionalMap(update).Add("asset_version", asset_version)
|
||||
}
|
||||
func (update SubmissionFilter) SetUploadedAssetID(uploaded_asset_id uint64) {
|
||||
datastore.OptionalMap(update).Add("uploaded_asset_id", uploaded_asset_id)
|
||||
}
|
||||
func (update SubmissionFilter) SetStatuses(statuses []model.SubmissionStatus) {
|
||||
datastore.OptionalMap(update).Add("status_id", statuses)
|
||||
}
|
||||
|
||||
// PatchSubmissionCompleted implements patchSubmissionCompleted operation.
|
||||
//
|
||||
// Retrieve map with ID.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/completed
|
||||
func (svc *Service) SetSubmissionCompleted(ctx context.Context, params api.SetSubmissionCompletedParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
has_role, err := userInfo.HasRoleMaptest()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller has MaptestGame role (request must originate from a maptest roblox game)
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNeedRoleMaptest
|
||||
}
|
||||
|
||||
pmap := datastore.Optional()
|
||||
pmap.Add("completed", true)
|
||||
return svc.DB.Submissions().Update(ctx, params.SubmissionID, pmap)
|
||||
func (svc *Service) CreateSubmission(ctx context.Context, script model.Submission) (model.Submission, error) {
|
||||
return svc.db.Submissions().Create(ctx, script)
|
||||
}
|
||||
|
||||
// UpdateSubmissionModel implements patchSubmissionModel operation.
|
||||
//
|
||||
// Update model following role restrictions.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/model
|
||||
func (svc *Service) UpdateSubmissionModel(ctx context.Context, params api.UpdateSubmissionModelParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
// read submission (this could be done with a transaction WHERE clause)
|
||||
submission, err := svc.DB.Submissions().Get(ctx, params.SubmissionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
has_role, err := userInfo.IsSubmitter(uint64(submission.Submitter))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller is the submitter
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNotSubmitter
|
||||
}
|
||||
|
||||
// check if Status is ChangesRequested|Submitted|UnderConstruction
|
||||
pmap := datastore.Optional()
|
||||
pmap.AddNotNil("asset_id", params.ModelID)
|
||||
pmap.AddNotNil("asset_version", params.VersionID)
|
||||
//always reset completed when model changes
|
||||
pmap.Add("completed", false)
|
||||
return svc.DB.Submissions().IfStatusThenUpdate(ctx, params.SubmissionID, []model.SubmissionStatus{model.SubmissionStatusChangesRequested, model.SubmissionStatusSubmitted, model.SubmissionStatusUnderConstruction}, pmap)
|
||||
func (svc *Service) ListSubmissions(ctx context.Context, filter SubmissionFilter, page model.Page, sort datastore.ListSort) ([]model.Submission, error) {
|
||||
return svc.db.Submissions().List(ctx, datastore.OptionalMap(filter), page, sort)
|
||||
}
|
||||
|
||||
// ActionSubmissionReject invokes actionSubmissionReject operation.
|
||||
//
|
||||
// Role Reviewer changes status from Submitted -> Rejected.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/reject
|
||||
func (svc *Service) ActionSubmissionReject(ctx context.Context, params api.ActionSubmissionRejectParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
has_role, err := userInfo.HasRoleSubmissionReview()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller has required role
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNeedRoleMapReview
|
||||
}
|
||||
|
||||
// transaction
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.SubmissionStatusRejected)
|
||||
return svc.DB.Submissions().IfStatusThenUpdate(ctx, params.SubmissionID, []model.SubmissionStatus{model.SubmissionStatusSubmitted}, smap)
|
||||
func (svc *Service) ListSubmissionsWithTotal(ctx context.Context, filter SubmissionFilter, page model.Page, sort datastore.ListSort) (int64, []model.Submission, error) {
|
||||
return svc.db.Submissions().ListWithTotal(ctx, datastore.OptionalMap(filter), page, sort)
|
||||
}
|
||||
|
||||
// ActionSubmissionRequestChanges invokes actionSubmissionRequestChanges operation.
|
||||
//
|
||||
// Role Reviewer changes status from Validated|Accepted|Submitted -> ChangesRequested.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/request-changes
|
||||
func (svc *Service) ActionSubmissionRequestChanges(ctx context.Context, params api.ActionSubmissionRequestChangesParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
has_role, err := userInfo.HasRoleSubmissionReview()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller has required role
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNeedRoleMapReview
|
||||
}
|
||||
|
||||
// transaction
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.SubmissionStatusChangesRequested)
|
||||
return svc.DB.Submissions().IfStatusThenUpdate(ctx, params.SubmissionID, []model.SubmissionStatus{model.SubmissionStatusValidated, model.SubmissionStatusAccepted, model.SubmissionStatusSubmitted}, smap)
|
||||
func (svc *Service) DeleteSubmission(ctx context.Context, id int64) error {
|
||||
return svc.db.Submissions().Delete(ctx, id)
|
||||
}
|
||||
|
||||
// ActionSubmissionRevoke invokes actionSubmissionRevoke operation.
|
||||
//
|
||||
// Role Submitter changes status from Submitted|ChangesRequested -> UnderConstruction.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/revoke
|
||||
func (svc *Service) ActionSubmissionRevoke(ctx context.Context, params api.ActionSubmissionRevokeParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
// read submission (this could be done with a transaction WHERE clause)
|
||||
submission, err := svc.DB.Submissions().Get(ctx, params.SubmissionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
has_role, err := userInfo.IsSubmitter(uint64(submission.Submitter))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller is the submitter
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNotSubmitter
|
||||
}
|
||||
|
||||
// transaction
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.SubmissionStatusUnderConstruction)
|
||||
return svc.DB.Submissions().IfStatusThenUpdate(ctx, params.SubmissionID, []model.SubmissionStatus{model.SubmissionStatusSubmitted, model.SubmissionStatusChangesRequested}, smap)
|
||||
func (svc *Service) GetSubmission(ctx context.Context, id int64) (model.Submission, error) {
|
||||
return svc.db.Submissions().Get(ctx, id)
|
||||
}
|
||||
|
||||
// ActionSubmissionSubmit invokes actionSubmissionSubmit operation.
|
||||
//
|
||||
// Role Submitter changes status from UnderConstruction|ChangesRequested -> Submitted.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/submit
|
||||
func (svc *Service) ActionSubmissionSubmit(ctx context.Context, params api.ActionSubmissionSubmitParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
// read submission (this could be done with a transaction WHERE clause)
|
||||
submission, err := svc.DB.Submissions().Get(ctx, params.SubmissionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
has_role, err := userInfo.IsSubmitter(uint64(submission.Submitter))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller is the submitter
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNotSubmitter
|
||||
}
|
||||
|
||||
// transaction
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.SubmissionStatusSubmitted)
|
||||
return svc.DB.Submissions().IfStatusThenUpdate(ctx, params.SubmissionID, []model.SubmissionStatus{model.SubmissionStatusUnderConstruction, model.SubmissionStatusChangesRequested}, smap)
|
||||
func (svc *Service) GetSubmissionList(ctx context.Context, ids []int64) ([]model.Submission, error) {
|
||||
return svc.db.Submissions().GetList(ctx, ids)
|
||||
}
|
||||
|
||||
// ActionSubmissionTriggerUpload invokes actionSubmissionTriggerUpload operation.
|
||||
//
|
||||
// Role Admin changes status from Validated -> Uploading.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/trigger-upload
|
||||
func (svc *Service) ActionSubmissionTriggerUpload(ctx context.Context, params api.ActionSubmissionTriggerUploadParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
has_role, err := userInfo.HasRoleSubmissionUpload()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller has required role
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNeedRoleMapUpload
|
||||
}
|
||||
|
||||
// transaction
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.SubmissionStatusUploading)
|
||||
submission, err := svc.DB.Submissions().IfStatusThenUpdateAndGet(ctx, params.SubmissionID, []model.SubmissionStatus{model.SubmissionStatusValidated}, smap)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// sentinel value because we are not using rust
|
||||
if submission.UploadedAssetID == 0 {
|
||||
// this is a new map
|
||||
upload_new_request := model.UploadSubmissionRequest{
|
||||
SubmissionID: submission.ID,
|
||||
ModelID: submission.ValidatedAssetID,
|
||||
ModelVersion: submission.ValidatedAssetVersion,
|
||||
// upload as displayname, whatever
|
||||
ModelName: submission.DisplayName,
|
||||
}
|
||||
|
||||
j, err := json.Marshal(upload_new_request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
svc.Nats.Publish("maptest.submissions.upload", []byte(j))
|
||||
} else {
|
||||
// refuse to operate
|
||||
return ErrUploadedAssetIDAlreadyExists
|
||||
}
|
||||
|
||||
return nil
|
||||
func (svc *Service) UpdateSubmission(ctx context.Context, id int64, pmap SubmissionUpdate) error {
|
||||
return svc.db.Submissions().Update(ctx, id, datastore.OptionalMap(pmap))
|
||||
}
|
||||
|
||||
// ActionSubmissionValidate invokes actionSubmissionValidate operation.
|
||||
//
|
||||
// Role SubmissionRelease changes status from Uploading -> Validated.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/reset-uploading
|
||||
func (svc *Service) ActionSubmissionValidated(ctx context.Context, params api.ActionSubmissionValidatedParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
has_role, err := userInfo.HasRoleSubmissionUpload()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller has required role
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNeedRoleMapUpload
|
||||
}
|
||||
|
||||
// check when submission was updated
|
||||
submission, err := svc.DB.Submissions().Get(ctx, params.SubmissionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if time.Now().Before(submission.UpdatedAt.Add(time.Second*10)) {
|
||||
// the last time the submission was updated must be longer than 10 seconds ago
|
||||
return ErrDelayReset
|
||||
}
|
||||
|
||||
// transaction
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.SubmissionStatusValidated)
|
||||
return svc.DB.Submissions().IfStatusThenUpdate(ctx, params.SubmissionID, []model.SubmissionStatus{model.SubmissionStatusUploading}, smap)
|
||||
func (svc *Service) UpdateSubmissionIfStatus(ctx context.Context, id int64, statuses []model.SubmissionStatus, pmap SubmissionUpdate) error {
|
||||
return svc.db.Submissions().IfStatusThenUpdate(ctx, id, statuses, datastore.OptionalMap(pmap))
|
||||
}
|
||||
|
||||
// ActionSubmissionTriggerValidate invokes actionSubmissionTriggerValidate operation.
|
||||
//
|
||||
// Role Reviewer triggers validation and changes status from Submitted -> Validating.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/trigger-validate
|
||||
func (svc *Service) ActionSubmissionTriggerValidate(ctx context.Context, params api.ActionSubmissionTriggerValidateParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
has_role, err := userInfo.HasRoleSubmissionReview()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller has required role
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNeedRoleMapReview
|
||||
}
|
||||
|
||||
// read submission (this could be done with a transaction WHERE clause)
|
||||
submission, err := svc.DB.Submissions().Get(ctx, params.SubmissionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
has_role, err = userInfo.IsSubmitter(uint64(submission.Submitter))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller is NOT the submitter
|
||||
if has_role {
|
||||
return ErrAcceptOwnSubmission
|
||||
}
|
||||
|
||||
// transaction
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.SubmissionStatusValidating)
|
||||
submission, err = svc.DB.Submissions().IfStatusThenUpdateAndGet(ctx, params.SubmissionID, []model.SubmissionStatus{model.SubmissionStatusSubmitted}, smap)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
validate_request := model.ValidateSubmissionRequest{
|
||||
SubmissionID: submission.ID,
|
||||
ModelID: submission.AssetID,
|
||||
ModelVersion: submission.AssetVersion,
|
||||
ValidatedModelID: nil,
|
||||
}
|
||||
|
||||
// sentinel values because we're not using rust
|
||||
if submission.ValidatedAssetID != 0 {
|
||||
validate_request.ValidatedModelID = &submission.ValidatedAssetID
|
||||
}
|
||||
|
||||
j, err := json.Marshal(validate_request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
svc.Nats.Publish("maptest.submissions.validate", []byte(j))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ActionSubmissionRetryValidate invokes actionSubmissionRetryValidate operation.
|
||||
//
|
||||
// Role Reviewer re-runs validation and changes status from Accepted -> Validating.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/retry-validate
|
||||
func (svc *Service) ActionSubmissionRetryValidate(ctx context.Context, params api.ActionSubmissionRetryValidateParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
has_role, err := userInfo.HasRoleSubmissionReview()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller has required role
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNeedRoleMapReview
|
||||
}
|
||||
|
||||
// transaction
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.SubmissionStatusValidating)
|
||||
submission, err := svc.DB.Submissions().IfStatusThenUpdateAndGet(ctx, params.SubmissionID, []model.SubmissionStatus{model.SubmissionStatusAccepted}, smap)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
validate_request := model.ValidateSubmissionRequest{
|
||||
SubmissionID: submission.ID,
|
||||
ModelID: submission.AssetID,
|
||||
ModelVersion: submission.AssetVersion,
|
||||
ValidatedModelID: nil,
|
||||
}
|
||||
|
||||
// sentinel values because we're not using rust
|
||||
if submission.ValidatedAssetID != 0 {
|
||||
validate_request.ValidatedModelID = &submission.ValidatedAssetID
|
||||
}
|
||||
|
||||
j, err := json.Marshal(validate_request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
svc.Nats.Publish("maptest.submissions.validate", []byte(j))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ActionSubmissionAccepted implements actionSubmissionAccepted operation.
|
||||
//
|
||||
// Role SubmissionReview changes status from Validating -> Accepted.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/reset-validating
|
||||
func (svc *Service) ActionSubmissionAccepted(ctx context.Context, params api.ActionSubmissionAcceptedParams) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
has_role, err := userInfo.HasRoleSubmissionReview()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller has required role
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNeedRoleMapReview
|
||||
}
|
||||
|
||||
// check when submission was updated
|
||||
submission, err := svc.DB.Submissions().Get(ctx, params.SubmissionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if time.Now().Before(submission.UpdatedAt.Add(time.Second*10)) {
|
||||
// the last time the submission was updated must be longer than 10 seconds ago
|
||||
return ErrDelayReset
|
||||
}
|
||||
|
||||
// transaction
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.SubmissionStatusAccepted)
|
||||
smap.Add("status_message", "Manually forced reset")
|
||||
return svc.DB.Submissions().IfStatusThenUpdate(ctx, params.SubmissionID, []model.SubmissionStatus{model.SubmissionStatusValidating}, smap)
|
||||
}
|
||||
|
||||
// ReleaseSubmissions invokes releaseSubmissions operation.
|
||||
//
|
||||
// Release a set of uploaded maps.
|
||||
//
|
||||
// POST /release-submissions
|
||||
func (svc *Service) ReleaseSubmissions(ctx context.Context, request []api.ReleaseInfo) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
has_role, err := userInfo.HasRoleSubmissionRelease()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// check if caller has required role
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNeedRoleSubmissionRelease
|
||||
}
|
||||
|
||||
idList := make([]int64, len(request))
|
||||
for i, releaseInfo := range request {
|
||||
idList[i] = releaseInfo.SubmissionID
|
||||
}
|
||||
|
||||
// fetch submissions
|
||||
submissions, err := svc.DB.Submissions().GetList(ctx, idList)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// check each submission to make sure it is ready to release
|
||||
for _,submission := range submissions{
|
||||
if submission.StatusID != model.SubmissionStatusUploaded{
|
||||
return ErrReleaseInvalidStatus
|
||||
}
|
||||
if submission.UploadedAssetID == 0{
|
||||
return ErrReleaseNoUploadedAssetID
|
||||
}
|
||||
}
|
||||
|
||||
for i,submission := range submissions{
|
||||
date := request[i].Date.Unix()
|
||||
// create each map with go-grpc
|
||||
_, err := svc.Client.Create(ctx, &maps.MapRequest{
|
||||
ID: submission.UploadedAssetID,
|
||||
DisplayName: &submission.DisplayName,
|
||||
Creator: &submission.Creator,
|
||||
GameID: &submission.GameID,
|
||||
Date: &date,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// update each status to Released
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.SubmissionStatusReleased)
|
||||
err = svc.DB.Submissions().IfStatusThenUpdate(ctx, submission.ID, []model.SubmissionStatus{model.SubmissionStatusUploaded}, smap)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
func (svc *Service) UpdateAndGetSubmissionIfStatus(ctx context.Context, id int64, statuses []model.SubmissionStatus, pmap SubmissionUpdate) (model.Submission, error) {
|
||||
return svc.db.Submissions().IfStatusThenUpdateAndGet(ctx, id, statuses, datastore.OptionalMap(pmap))
|
||||
}
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
package service_internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
internal "git.itzana.me/strafesnet/maps-service/pkg/internal"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/datastore"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
)
|
||||
|
||||
// UpdateMapfixValidatedModel implements patchMapfixModel operation.
|
||||
//
|
||||
// Update model following role restrictions.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/validated-model
|
||||
func (svc *Service) UpdateMapfixValidatedModel(ctx context.Context, params internal.UpdateMapfixValidatedModelParams) error {
|
||||
// check if Status is ChangesRequested|Submitted|UnderConstruction
|
||||
pmap := datastore.Optional()
|
||||
pmap.AddNotNil("validated_asset_id", params.ValidatedModelID)
|
||||
pmap.AddNotNil("validated_asset_version", params.ValidatedModelVersion)
|
||||
// DO NOT reset completed when validated model is updated
|
||||
// pmap.Add("completed", false)
|
||||
return svc.DB.Mapfixes().IfStatusThenUpdate(ctx, params.MapfixID, []model.MapfixStatus{model.MapfixStatusValidating}, pmap)
|
||||
}
|
||||
|
||||
// ActionMapfixValidate invokes actionMapfixValidate operation.
|
||||
//
|
||||
// Role Validator changes status from Validating -> Validated.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/validator-validated
|
||||
func (svc *Service) ActionMapfixValidated(ctx context.Context, params internal.ActionMapfixValidatedParams) error {
|
||||
// transaction
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.MapfixStatusValidated)
|
||||
return svc.DB.Mapfixes().IfStatusThenUpdate(ctx, params.MapfixID, []model.MapfixStatus{model.MapfixStatusValidating}, smap)
|
||||
}
|
||||
|
||||
// ActionMapfixAccepted implements actionMapfixAccepted operation.
|
||||
//
|
||||
// (Internal endpoint) Role Validator changes status from Validating -> Accepted.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/validator-failed
|
||||
func (svc *Service) ActionMapfixAccepted(ctx context.Context, params internal.ActionMapfixAcceptedParams) error {
|
||||
// transaction
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.MapfixStatusAccepted)
|
||||
smap.Add("status_message", params.StatusMessage)
|
||||
return svc.DB.Mapfixes().IfStatusThenUpdate(ctx, params.MapfixID, []model.MapfixStatus{model.MapfixStatusValidating}, smap)
|
||||
}
|
||||
|
||||
// ActionMapfixUploaded implements actionMapfixUploaded operation.
|
||||
//
|
||||
// (Internal endpoint) Role Validator changes status from Uploading -> Uploaded.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/validator-uploaded
|
||||
func (svc *Service) ActionMapfixUploaded(ctx context.Context, params internal.ActionMapfixUploadedParams) error {
|
||||
// transaction
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.MapfixStatusUploaded)
|
||||
return svc.DB.Mapfixes().IfStatusThenUpdate(ctx, params.MapfixID, []model.MapfixStatus{model.MapfixStatusUploading}, smap)
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
package service_internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/datastore"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/internal"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
)
|
||||
|
||||
// CreateScriptPolicy implements createScriptPolicy operation.
|
||||
//
|
||||
// Create a new script policy.
|
||||
//
|
||||
// POST /script-policy
|
||||
func (svc *Service) CreateScriptPolicy(ctx context.Context, req *api.ScriptPolicyCreate) (*api.ID, error) {
|
||||
from_script, err := svc.DB.Scripts().Get(ctx, req.FromScriptID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// the existence of ToScriptID does not need to be validated because it's checked by a foreign key constraint.
|
||||
|
||||
script, err := svc.DB.ScriptPolicy().Create(ctx, model.ScriptPolicy{
|
||||
ID: 0,
|
||||
FromScriptHash: from_script.Hash,
|
||||
ToScriptID: req.ToScriptID,
|
||||
Policy: model.Policy(req.Policy),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &api.ID{
|
||||
ID: script.ID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ListScriptPolicy implements listScriptPolicy operation.
|
||||
//
|
||||
// Get list of script policies.
|
||||
//
|
||||
// GET /script-policy
|
||||
func (svc *Service) ListScriptPolicy(ctx context.Context, params api.ListScriptPolicyParams) ([]api.ScriptPolicy, error) {
|
||||
filter := datastore.Optional()
|
||||
|
||||
if params.FromScriptHash.IsSet(){
|
||||
hash, err := model.HashParse(params.FromScriptHash.Value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
filter.AddNotNil("from_script_hash", int64(hash)) // No type safety!
|
||||
}
|
||||
if params.ToScriptID.IsSet(){
|
||||
filter.AddNotNil("to_script_id", params.ToScriptID.Value)
|
||||
}
|
||||
if params.Policy.IsSet(){
|
||||
filter.AddNotNil("policy", params.Policy.Value)
|
||||
}
|
||||
|
||||
items, err := svc.DB.ScriptPolicy().List(ctx, filter, model.Page{
|
||||
Number: params.Page,
|
||||
Size: params.Limit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var resp []api.ScriptPolicy
|
||||
for _, item := range items {
|
||||
resp = append(resp, api.ScriptPolicy{
|
||||
ID: item.ID,
|
||||
FromScriptHash: model.HashFormat(uint64(item.FromScriptHash)),
|
||||
ToScriptID: item.ToScriptID,
|
||||
Policy: int32(item.Policy),
|
||||
})
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
package service_internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/datastore"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/internal"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
)
|
||||
|
||||
// CreateScript implements createScript operation.
|
||||
//
|
||||
// Create a new script.
|
||||
//
|
||||
// POST /scripts
|
||||
func (svc *Service) CreateScript(ctx context.Context, req *api.ScriptCreate) (*api.ID, error) {
|
||||
script, err := svc.DB.Scripts().Create(ctx, model.Script{
|
||||
ID: 0,
|
||||
Name: req.Name,
|
||||
Hash: int64(model.HashSource(req.Source)),
|
||||
Source: req.Source,
|
||||
ResourceType: model.ResourceType(req.ResourceType),
|
||||
ResourceID: req.ResourceID.Or(0),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &api.ID{
|
||||
ID: script.ID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ListScripts implements listScripts operation.
|
||||
//
|
||||
// Get list of scripts.
|
||||
//
|
||||
// GET /scripts
|
||||
func (svc *Service) ListScripts(ctx context.Context, params api.ListScriptsParams) ([]api.Script, error) {
|
||||
filter := datastore.Optional()
|
||||
|
||||
if params.Hash.IsSet(){
|
||||
hash, err := model.HashParse(params.Hash.Value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
filter.AddNotNil("hash", int64(hash)) // No type safety!
|
||||
}
|
||||
if params.Name.IsSet(){
|
||||
filter.AddNotNil("name", params.Name.Value)
|
||||
}
|
||||
if params.Source.IsSet(){
|
||||
filter.AddNotNil("source", params.Source.Value)
|
||||
}
|
||||
if params.ResourceType.IsSet(){
|
||||
filter.AddNotNil("resource_type", params.ResourceType.Value)
|
||||
}
|
||||
if params.ResourceID.IsSet(){
|
||||
filter.AddNotNil("resource_id", params.ResourceID.Value)
|
||||
}
|
||||
|
||||
items, err := svc.DB.Scripts().List(ctx, filter, model.Page{
|
||||
Number: params.Page,
|
||||
Size: params.Limit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var resp []api.Script
|
||||
for _, item := range items {
|
||||
resp = append(resp, api.Script{
|
||||
ID: item.ID,
|
||||
Hash: model.HashFormat(uint64(item.Hash)),
|
||||
Source: item.Source,
|
||||
ResourceType: int32(item.ResourceType),
|
||||
ResourceID: item.ResourceID,
|
||||
})
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// GetScript implements getScript operation.
|
||||
//
|
||||
// Get the specified script by ID.
|
||||
//
|
||||
// GET /scripts/{ScriptID}
|
||||
func (svc *Service) GetScript(ctx context.Context, params api.GetScriptParams) (*api.Script, error) {
|
||||
script, err := svc.DB.Scripts().Get(ctx, params.ScriptID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &api.Script{
|
||||
ID: script.ID,
|
||||
Name: script.Name,
|
||||
Hash: model.HashFormat(uint64(script.Hash)),
|
||||
Source: script.Source,
|
||||
ResourceType: int32(script.ResourceType),
|
||||
ResourceID: script.ResourceID,
|
||||
}, nil
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package service_internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/datastore"
|
||||
internal "git.itzana.me/strafesnet/maps-service/pkg/internal"
|
||||
"github.com/nats-io/nats.go"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
DB datastore.Datastore
|
||||
Nats nats.JetStreamContext
|
||||
}
|
||||
|
||||
// yay duplicate code
|
||||
func (svc *Service) NewError(ctx context.Context, err error) *internal.ErrorStatusCode {
|
||||
status := 500
|
||||
if errors.Is(err, datastore.ErrNotExist) {
|
||||
status = 404
|
||||
}
|
||||
return &internal.ErrorStatusCode{
|
||||
StatusCode: status,
|
||||
Response: internal.Error{
|
||||
Code: int64(status),
|
||||
Message: err.Error(),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
package service_internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
internal "git.itzana.me/strafesnet/maps-service/pkg/internal"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/datastore"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
)
|
||||
|
||||
// UpdateSubmissionValidatedModel implements patchSubmissionModel operation.
|
||||
//
|
||||
// Update model following role restrictions.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/validated-model
|
||||
func (svc *Service) UpdateSubmissionValidatedModel(ctx context.Context, params internal.UpdateSubmissionValidatedModelParams) error {
|
||||
// check if Status is ChangesRequested|Submitted|UnderConstruction
|
||||
pmap := datastore.Optional()
|
||||
pmap.AddNotNil("validated_asset_id", params.ValidatedModelID)
|
||||
pmap.AddNotNil("validated_asset_version", params.ValidatedModelVersion)
|
||||
// DO NOT reset completed when validated model is updated
|
||||
// pmap.Add("completed", false)
|
||||
return svc.DB.Submissions().IfStatusThenUpdate(ctx, params.SubmissionID, []model.SubmissionStatus{model.SubmissionStatusValidating}, pmap)
|
||||
}
|
||||
|
||||
// ActionSubmissionValidate invokes actionSubmissionValidate operation.
|
||||
//
|
||||
// Role Validator changes status from Validating -> Validated.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/validator-validated
|
||||
func (svc *Service) ActionSubmissionValidated(ctx context.Context, params internal.ActionSubmissionValidatedParams) error {
|
||||
// transaction
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.SubmissionStatusValidated)
|
||||
return svc.DB.Submissions().IfStatusThenUpdate(ctx, params.SubmissionID, []model.SubmissionStatus{model.SubmissionStatusValidating}, smap)
|
||||
}
|
||||
|
||||
// ActionSubmissionAccepted implements actionSubmissionAccepted operation.
|
||||
//
|
||||
// (Internal endpoint) Role Validator changes status from Validating -> Accepted.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/validator-failed
|
||||
func (svc *Service) ActionSubmissionAccepted(ctx context.Context, params internal.ActionSubmissionAcceptedParams) error {
|
||||
// transaction
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.SubmissionStatusAccepted)
|
||||
smap.Add("status_message", params.StatusMessage)
|
||||
return svc.DB.Submissions().IfStatusThenUpdate(ctx, params.SubmissionID, []model.SubmissionStatus{model.SubmissionStatusValidating}, smap)
|
||||
}
|
||||
|
||||
// ActionSubmissionUploaded implements actionSubmissionUploaded operation.
|
||||
//
|
||||
// (Internal endpoint) Role Validator changes status from Uploading -> Uploaded.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/validator-uploaded
|
||||
func (svc *Service) ActionSubmissionUploaded(ctx context.Context, params internal.ActionSubmissionUploadedParams) error {
|
||||
// transaction
|
||||
smap := datastore.Optional()
|
||||
smap.Add("status_id", model.SubmissionStatusUploaded)
|
||||
smap.Add("uploaded_asset_id", params.UploadedAssetID)
|
||||
return svc.DB.Submissions().IfStatusThenUpdate(ctx, params.SubmissionID, []model.SubmissionStatus{model.SubmissionStatusUploading}, smap)
|
||||
}
|
||||
380
pkg/validator_controller/mapfixes.go
Normal file
380
pkg/validator_controller/mapfixes.go
Normal file
@@ -0,0 +1,380 @@
|
||||
package validator_controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"git.itzana.me/strafesnet/go-grpc/validator"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/datastore"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/service"
|
||||
)
|
||||
|
||||
type Mapfixes struct {
|
||||
*validator.UnimplementedValidatorMapfixServiceServer
|
||||
inner *service.Service
|
||||
}
|
||||
func NewMapfixesController(
|
||||
inner *service.Service,
|
||||
) Mapfixes {
|
||||
return Mapfixes{
|
||||
inner: inner,
|
||||
}
|
||||
}
|
||||
|
||||
var(
|
||||
// prevent two mapfixes with same asset id
|
||||
ActiveMapfixStatuses = []model.MapfixStatus{
|
||||
model.MapfixStatusUploading,
|
||||
model.MapfixStatusValidated,
|
||||
model.MapfixStatusValidating,
|
||||
model.MapfixStatusAcceptedUnvalidated,
|
||||
model.MapfixStatusChangesRequested,
|
||||
model.MapfixStatusSubmitted,
|
||||
model.MapfixStatusUnderConstruction,
|
||||
}
|
||||
)
|
||||
|
||||
var(
|
||||
ErrActiveMapfixSameAssetID = errors.New("There is an active mapfix with the same AssetID")
|
||||
ErrNotAssetOwner = errors.New("You can only submit an asset you own")
|
||||
)
|
||||
|
||||
// UpdateMapfixValidatedModel implements patchMapfixModel operation.
|
||||
//
|
||||
// Update model following role restrictions.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/validated-model
|
||||
func (svc *Mapfixes) SetValidatedModel(ctx context.Context, params *validator.ValidatedModelRequest) (*validator.NullResponse, error) {
|
||||
MapfixID := int64(params.ID)
|
||||
|
||||
// check if Status is ChangesRequested|Submitted|UnderConstruction
|
||||
update := service.NewMapfixUpdate()
|
||||
update.SetValidatedAssetID(params.ValidatedModelID)
|
||||
update.SetValidatedAssetVersion(params.ValidatedModelVersion)
|
||||
// DO NOT reset completed when validated model is updated
|
||||
// update.Add("completed", false)
|
||||
allow_statuses := []model.MapfixStatus{model.MapfixStatusValidating}
|
||||
err := svc.inner.UpdateMapfixIfStatus(ctx, MapfixID, allow_statuses, update)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
event_data := model.AuditEventDataChangeValidatedModel{
|
||||
ValidatedModelID: params.ValidatedModelID,
|
||||
ValidatedModelVersion: params.ValidatedModelVersion,
|
||||
}
|
||||
|
||||
err = svc.inner.CreateAuditEventChangeValidatedModel(
|
||||
ctx,
|
||||
model.ValidatorUserID,
|
||||
model.Resource{
|
||||
ID: MapfixID,
|
||||
Type: model.ResourceMapfix,
|
||||
},
|
||||
event_data,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &validator.NullResponse{}, nil
|
||||
}
|
||||
|
||||
// ActionMapfixSubmitted invokes actionMapfixSubmitted operation.
|
||||
//
|
||||
// Role Validator changes status from Submitting -> Submitted.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/validator-submitted
|
||||
func (svc *Mapfixes) SetStatusSubmitted(ctx context.Context, params *validator.SubmittedRequest) (*validator.NullResponse, error) {
|
||||
MapfixID := int64(params.ID)
|
||||
// transaction
|
||||
target_status := model.MapfixStatusSubmitted
|
||||
update := service.NewMapfixUpdate()
|
||||
update.SetStatusID(target_status)
|
||||
update.SetAssetVersion(uint64(params.ModelVersion))
|
||||
update.SetDisplayName(params.DisplayName)
|
||||
update.SetCreator(params.Creator)
|
||||
update.SetGameID(uint32(params.GameID))
|
||||
allow_statuses := []model.MapfixStatus{model.MapfixStatusSubmitting}
|
||||
err := svc.inner.UpdateMapfixIfStatus(ctx, MapfixID, allow_statuses, update)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
event_data := model.AuditEventDataAction{
|
||||
TargetStatus: uint32(target_status),
|
||||
}
|
||||
|
||||
err = svc.inner.CreateAuditEventAction(
|
||||
ctx,
|
||||
model.ValidatorUserID,
|
||||
model.Resource{
|
||||
ID: MapfixID,
|
||||
Type: model.ResourceMapfix,
|
||||
},
|
||||
event_data,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &validator.NullResponse{}, nil
|
||||
}
|
||||
|
||||
// ActionMapfixRequestChanges implements actionMapfixRequestChanges operation.
|
||||
//
|
||||
// (Internal endpoint) Role Validator changes status from Submitting -> RequestChanges.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/validator-request-changes
|
||||
func (svc *Mapfixes) SetStatusRequestChanges(ctx context.Context, params *validator.MapfixID) (*validator.NullResponse, error) {
|
||||
MapfixID := int64(params.ID)
|
||||
// transaction
|
||||
target_status := model.MapfixStatusChangesRequested
|
||||
update := service.NewMapfixUpdate()
|
||||
update.SetStatusID(target_status)
|
||||
allow_statuses := []model.MapfixStatus{model.MapfixStatusSubmitting}
|
||||
err := svc.inner.UpdateMapfixIfStatus(ctx, MapfixID, allow_statuses, update)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
event_data := model.AuditEventDataAction{
|
||||
TargetStatus: uint32(target_status),
|
||||
}
|
||||
|
||||
err = svc.inner.CreateAuditEventAction(
|
||||
ctx,
|
||||
model.ValidatorUserID,
|
||||
model.Resource{
|
||||
ID: MapfixID,
|
||||
Type: model.ResourceMapfix,
|
||||
},
|
||||
event_data,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &validator.NullResponse{}, nil
|
||||
}
|
||||
|
||||
// ActionMapfixValidate invokes actionMapfixValidate operation.
|
||||
//
|
||||
// Role Validator changes status from Validating -> Validated.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/validator-validated
|
||||
func (svc *Mapfixes) SetStatusValidated(ctx context.Context, params *validator.MapfixID) (*validator.NullResponse, error) {
|
||||
MapfixID := int64(params.ID)
|
||||
// transaction
|
||||
update := service.NewMapfixUpdate()
|
||||
update.SetStatusID(model.MapfixStatusValidated)
|
||||
allow_statuses := []model.MapfixStatus{model.MapfixStatusValidating}
|
||||
err := svc.inner.UpdateMapfixIfStatus(ctx, MapfixID, allow_statuses, update)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &validator.NullResponse{}, nil
|
||||
}
|
||||
|
||||
// ActionMapfixAccepted implements actionMapfixAccepted operation.
|
||||
//
|
||||
// (Internal endpoint) Role Validator changes status from Validating -> Accepted.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/validator-failed
|
||||
func (svc *Mapfixes) SetStatusFailed(ctx context.Context, params *validator.MapfixID) (*validator.NullResponse, error) {
|
||||
MapfixID := int64(params.ID)
|
||||
// transaction
|
||||
target_status := model.MapfixStatusAcceptedUnvalidated
|
||||
update := service.NewMapfixUpdate()
|
||||
update.SetStatusID(target_status)
|
||||
allow_statuses := []model.MapfixStatus{model.MapfixStatusValidating}
|
||||
err := svc.inner.UpdateMapfixIfStatus(ctx, MapfixID, allow_statuses, update)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// push an action audit event
|
||||
event_data := model.AuditEventDataAction{
|
||||
TargetStatus: uint32(target_status),
|
||||
}
|
||||
|
||||
err = svc.inner.CreateAuditEventAction(
|
||||
ctx,
|
||||
model.ValidatorUserID,
|
||||
model.Resource{
|
||||
ID: MapfixID,
|
||||
Type: model.ResourceMapfix,
|
||||
},
|
||||
event_data,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &validator.NullResponse{}, nil
|
||||
}
|
||||
|
||||
// ActionMapfixUploaded implements actionMapfixUploaded operation.
|
||||
//
|
||||
// (Internal endpoint) Role Validator changes status from Uploading -> Uploaded.
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/status/validator-uploaded
|
||||
func (svc *Mapfixes) SetStatusUploaded(ctx context.Context, params *validator.MapfixID) (*validator.NullResponse, error) {
|
||||
MapfixID := int64(params.ID)
|
||||
// transaction
|
||||
target_status := model.MapfixStatusUploaded
|
||||
update := service.NewMapfixUpdate()
|
||||
update.SetStatusID(target_status)
|
||||
allow_statuses := []model.MapfixStatus{model.MapfixStatusUploading}
|
||||
err := svc.inner.UpdateMapfixIfStatus(ctx, MapfixID, allow_statuses, update)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
event_data := model.AuditEventDataAction{
|
||||
TargetStatus: uint32(target_status),
|
||||
}
|
||||
|
||||
err = svc.inner.CreateAuditEventAction(
|
||||
ctx,
|
||||
model.ValidatorUserID,
|
||||
model.Resource{
|
||||
ID: MapfixID,
|
||||
Type: model.ResourceMapfix,
|
||||
},
|
||||
event_data,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &validator.NullResponse{}, nil
|
||||
}
|
||||
|
||||
// CreateMapfixAuditError implements createMapfixAuditError operation.
|
||||
//
|
||||
// Post an error to the audit log
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/error
|
||||
func (svc *Mapfixes) CreateAuditError(ctx context.Context, params *validator.AuditErrorRequest) (*validator.NullResponse, error) {
|
||||
MapfixID := int64(params.ID)
|
||||
event_data := model.AuditEventDataError{
|
||||
Error: params.ErrorMessage,
|
||||
}
|
||||
|
||||
err := svc.inner.CreateAuditEventError(
|
||||
ctx,
|
||||
model.ValidatorUserID,
|
||||
model.Resource{
|
||||
ID: MapfixID,
|
||||
Type: model.ResourceMapfix,
|
||||
},
|
||||
event_data,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &validator.NullResponse{}, nil
|
||||
}
|
||||
|
||||
// CreateMapfixAuditCheckList implements createMapfixAuditCheckList operation.
|
||||
//
|
||||
// Post a checklist to the audit log
|
||||
//
|
||||
// POST /mapfixes/{MapfixID}/checklist
|
||||
func (svc *Mapfixes) CreateAuditChecklist(ctx context.Context, params *validator.AuditChecklistRequest) (*validator.NullResponse, error) {
|
||||
MapfixID := int64(params.ID)
|
||||
check_list := make([]model.Check, len(params.CheckList))
|
||||
for i, check := range params.CheckList {
|
||||
check_list[i] = model.Check{
|
||||
Name: check.Name,
|
||||
Summary: check.Summary,
|
||||
Passed: check.Passed,
|
||||
}
|
||||
}
|
||||
|
||||
event_data := model.AuditEventDataCheckList{
|
||||
CheckList: check_list,
|
||||
}
|
||||
|
||||
err := svc.inner.CreateAuditEventCheckList(
|
||||
ctx,
|
||||
model.ValidatorUserID,
|
||||
model.Resource{
|
||||
ID: MapfixID,
|
||||
Type: model.ResourceMapfix,
|
||||
},
|
||||
event_data,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &validator.NullResponse{}, nil
|
||||
}
|
||||
|
||||
// POST /mapfixes
|
||||
func (svc *Mapfixes) Create(ctx context.Context, request *validator.MapfixCreate) (*validator.MapfixID, error) {
|
||||
var Submitter=request.AssetOwner;
|
||||
// Check if an active mapfix with the same asset id exists
|
||||
{
|
||||
filter := service.NewMapfixFilter()
|
||||
filter.SetAssetID(request.AssetID)
|
||||
filter.SetAssetVersion(request.AssetVersion)
|
||||
filter.SetStatuses(ActiveMapfixStatuses)
|
||||
active_mapfixes, err := svc.inner.ListMapfixes(ctx, filter, model.Page{
|
||||
Number: 1,
|
||||
Size: 1,
|
||||
},datastore.ListSortDisabled)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(active_mapfixes) != 0{
|
||||
return nil, ErrActiveMapfixSameAssetID
|
||||
}
|
||||
}
|
||||
|
||||
OperationID := int32(request.OperationID)
|
||||
operation, err := svc.inner.GetOperation(ctx, OperationID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// check if user owns asset
|
||||
// TODO: allow bypass by admin
|
||||
if operation.Owner != Submitter {
|
||||
return nil, ErrNotAssetOwner
|
||||
}
|
||||
|
||||
mapfix, err := svc.inner.CreateMapfix(ctx, model.Mapfix{
|
||||
ID: 0,
|
||||
DisplayName: request.DisplayName,
|
||||
Creator: request.Creator,
|
||||
GameID: request.GameID,
|
||||
Submitter: Submitter,
|
||||
AssetID: request.AssetID,
|
||||
AssetVersion: request.AssetVersion,
|
||||
Completed: false,
|
||||
TargetAssetID: request.TargetAssetID,
|
||||
StatusID: model.MapfixStatusUnderConstruction,
|
||||
Description: request.Description,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// mark the operation as completed and provide the path
|
||||
params := service.NewOperationCompleteParams(fmt.Sprintf("/mapfixes/%d", mapfix.ID))
|
||||
err = svc.inner.CompleteOperation(ctx, OperationID, params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &validator.MapfixID{
|
||||
ID: uint64(mapfix.ID),
|
||||
}, nil
|
||||
}
|
||||
37
pkg/validator_controller/operations.go
Normal file
37
pkg/validator_controller/operations.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package validator_controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.itzana.me/strafesnet/go-grpc/validator"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/service"
|
||||
)
|
||||
|
||||
type Operations struct {
|
||||
*validator.UnimplementedValidatorOperationServiceServer
|
||||
inner *service.Service
|
||||
}
|
||||
func NewOperationsController(
|
||||
inner *service.Service,
|
||||
) Operations {
|
||||
return Operations{
|
||||
inner: inner,
|
||||
}
|
||||
}
|
||||
|
||||
// ActionOperationFailed implements actionOperationFailed operation.
|
||||
//
|
||||
// Fail the specified OperationID with a StatusMessage.
|
||||
//
|
||||
// POST /operations/{OperationID}/status/operation-failed
|
||||
func (svc *Operations) Fail(ctx context.Context, params *validator.OperationFailRequest) (*validator.NullResponse, error) {
|
||||
fail_params := service.NewOperationFailParams(
|
||||
params.StatusMessage,
|
||||
)
|
||||
err := svc.inner.FailOperation(ctx, int32(params.OperationID), fail_params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &validator.NullResponse{}, nil
|
||||
}
|
||||
89
pkg/validator_controller/script_policy.go
Normal file
89
pkg/validator_controller/script_policy.go
Normal file
@@ -0,0 +1,89 @@
|
||||
package validator_controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.itzana.me/strafesnet/go-grpc/validator"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/service"
|
||||
)
|
||||
|
||||
type ScriptPolicy struct {
|
||||
*validator.UnimplementedValidatorScriptPolicyServiceServer
|
||||
inner *service.Service
|
||||
}
|
||||
func NewScriptPolicyController(
|
||||
inner *service.Service,
|
||||
) ScriptPolicy {
|
||||
return ScriptPolicy{
|
||||
inner: inner,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateScriptPolicy implements createScriptPolicy operation.
|
||||
//
|
||||
// Create a new script policy.
|
||||
//
|
||||
// POST /script-policy
|
||||
func (svc *ScriptPolicy) Create(ctx context.Context, req *validator.ScriptPolicyCreate) (*validator.ScriptPolicyID, error) {
|
||||
from_script, err := svc.inner.GetScript(ctx, int64(req.FromScriptID))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// the existence of ToScriptID does not need to be validated because it's checked by a foreign key constraint.
|
||||
|
||||
script, err := svc.inner.CreateScriptPolicy(ctx, model.ScriptPolicy{
|
||||
ID: 0,
|
||||
FromScriptHash: from_script.Hash,
|
||||
ToScriptID: int64(req.ToScriptID),
|
||||
Policy: model.Policy(req.Policy),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &validator.ScriptPolicyID{
|
||||
ID: uint64(script.ID),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ListScriptPolicy implements listScriptPolicy operation.
|
||||
//
|
||||
// Get list of script policies.
|
||||
//
|
||||
// GET /script-policy
|
||||
func (svc *ScriptPolicy) List(ctx context.Context, params *validator.ScriptPolicyListRequest) (*validator.ScriptPolicyListResponse, error) {
|
||||
filter := service.NewScriptPolicyFilter()
|
||||
|
||||
if params.Filter.FromScriptHash != nil {
|
||||
filter.SetFromScriptHash(int64(*params.Filter.FromScriptHash))
|
||||
}
|
||||
if params.Filter.ToScriptID != nil {
|
||||
filter.SetToScriptID(int64(*params.Filter.ToScriptID))
|
||||
}
|
||||
if params.Filter.Policy != nil {
|
||||
filter.SetPolicy(int32(*params.Filter.Policy))
|
||||
}
|
||||
|
||||
items, err := svc.inner.ListScriptPolicies(ctx, filter, model.Page{
|
||||
Number: int32(params.Page.Number),
|
||||
Size: int32(params.Page.Size),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp := validator.ScriptPolicyListResponse{}
|
||||
resp.ScriptPolicies = make([]*validator.ScriptPolicy, len(items))
|
||||
for i, item := range items {
|
||||
resp.ScriptPolicies[i] = &validator.ScriptPolicy{
|
||||
ID: uint64(item.ID),
|
||||
FromScriptHash: uint64(item.FromScriptHash),
|
||||
ToScriptID: uint64(item.ToScriptID),
|
||||
Policy: validator.Policy(int32(item.Policy)),
|
||||
}
|
||||
}
|
||||
|
||||
return &resp, nil
|
||||
}
|
||||
119
pkg/validator_controller/scripts.go
Normal file
119
pkg/validator_controller/scripts.go
Normal file
@@ -0,0 +1,119 @@
|
||||
package validator_controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.itzana.me/strafesnet/go-grpc/validator"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/service"
|
||||
)
|
||||
|
||||
type Scripts struct {
|
||||
*validator.UnimplementedValidatorScriptServiceServer
|
||||
inner *service.Service
|
||||
}
|
||||
func NewScriptsController(
|
||||
inner *service.Service,
|
||||
) Scripts {
|
||||
return Scripts{
|
||||
inner: inner,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateScript implements createScript operation.
|
||||
//
|
||||
// Create a new script.
|
||||
//
|
||||
// POST /scripts
|
||||
func (svc *Scripts) Create(ctx context.Context, req *validator.ScriptCreate) (*validator.ScriptID, error) {
|
||||
ResourceID := int64(0)
|
||||
if req.ResourceID != nil {
|
||||
ResourceID = int64(*req.ResourceID)
|
||||
}
|
||||
script, err := svc.inner.CreateScript(ctx, model.Script{
|
||||
ID: 0,
|
||||
Name: req.Name,
|
||||
Hash: int64(model.HashSource(req.Source)),
|
||||
Source: req.Source,
|
||||
ResourceType: model.ResourceType(req.ResourceType),
|
||||
ResourceID: ResourceID,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &validator.ScriptID{
|
||||
ID: uint64(script.ID),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ListScripts implements listScripts operation.
|
||||
//
|
||||
// Get list of scripts.
|
||||
//
|
||||
// GET /scripts
|
||||
func (svc *Scripts) List(ctx context.Context, params *validator.ScriptListRequest) (*validator.ScriptListResponse, error) {
|
||||
filter := service.NewScriptFilter()
|
||||
if params.Filter.Hash != nil {
|
||||
filter.SetHash(int64(*params.Filter.Hash))
|
||||
}
|
||||
if params.Filter.Name != nil {
|
||||
filter.SetName(*params.Filter.Name)
|
||||
}
|
||||
if params.Filter.Source != nil {
|
||||
filter.SetSource(*params.Filter.Source)
|
||||
}
|
||||
if params.Filter.ResourceType != nil {
|
||||
filter.SetResourceType(int32(*params.Filter.ResourceType))
|
||||
}
|
||||
if params.Filter.ResourceID != nil {
|
||||
filter.SetResourceID(int64(*params.Filter.ResourceID))
|
||||
}
|
||||
|
||||
items, err := svc.inner.ListScripts(ctx, filter, model.Page{
|
||||
Number: int32(params.Page.Number),
|
||||
Size: int32(params.Page.Size),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp := validator.ScriptListResponse{}
|
||||
resp.Scripts = make([]*validator.Script, len(items))
|
||||
for i, item := range items {
|
||||
resource_id := uint64(item.ResourceID)
|
||||
resp.Scripts[i] = &validator.Script{
|
||||
ID: uint64(item.ID),
|
||||
Name: item.Name,
|
||||
Hash: uint64(item.Hash),
|
||||
Source: item.Source,
|
||||
ResourceType: validator.ResourceType(item.ResourceType),
|
||||
ResourceID: &resource_id,
|
||||
}
|
||||
}
|
||||
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
// GetScript implements getScript operation.
|
||||
//
|
||||
// Get the specified script by ID.
|
||||
//
|
||||
// GET /scripts/{ScriptID}
|
||||
func (svc *Scripts) Get(ctx context.Context, params *validator.ScriptID) (*validator.Script, error) {
|
||||
ScriptID := int64(params.ID)
|
||||
script, err := svc.inner.GetScript(ctx, ScriptID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ResourceID := uint64(script.ResourceID)
|
||||
return &validator.Script{
|
||||
ID: uint64(script.ID),
|
||||
Name: script.Name,
|
||||
Hash: uint64(script.Hash),
|
||||
Source: script.Source,
|
||||
ResourceType: validator.ResourceType(script.ResourceType),
|
||||
ResourceID: &ResourceID,
|
||||
}, nil
|
||||
}
|
||||
403
pkg/validator_controller/submissions.go
Normal file
403
pkg/validator_controller/submissions.go
Normal file
@@ -0,0 +1,403 @@
|
||||
package validator_controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"git.itzana.me/strafesnet/go-grpc/validator"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/datastore"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/service"
|
||||
)
|
||||
|
||||
type Submissions struct {
|
||||
*validator.UnimplementedValidatorSubmissionServiceServer
|
||||
inner *service.Service
|
||||
}
|
||||
func NewSubmissionsController(
|
||||
inner *service.Service,
|
||||
) Submissions {
|
||||
return Submissions{
|
||||
inner: inner,
|
||||
}
|
||||
}
|
||||
|
||||
var(
|
||||
// prevent two mapfixes with same asset id
|
||||
ActiveSubmissionStatuses = []model.SubmissionStatus{
|
||||
model.SubmissionStatusUploading,
|
||||
model.SubmissionStatusValidated,
|
||||
model.SubmissionStatusValidating,
|
||||
model.SubmissionStatusAcceptedUnvalidated,
|
||||
model.SubmissionStatusChangesRequested,
|
||||
model.SubmissionStatusSubmitted,
|
||||
model.SubmissionStatusUnderConstruction,
|
||||
}
|
||||
)
|
||||
|
||||
var(
|
||||
ErrActiveSubmissionSameAssetID = errors.New("There is an active submission with the same AssetID")
|
||||
)
|
||||
|
||||
// UpdateSubmissionValidatedModel implements patchSubmissionModel operation.
|
||||
//
|
||||
// Update model following role restrictions.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/validated-model
|
||||
func (svc *Submissions) SetValidatedModel(ctx context.Context, params *validator.ValidatedModelRequest) (*validator.NullResponse, error) {
|
||||
SubmissionID := int64(params.ID)
|
||||
|
||||
// check if Status is ChangesRequested|Submitted|UnderConstruction
|
||||
update := service.NewSubmissionUpdate()
|
||||
update.SetValidatedAssetID(params.ValidatedModelID)
|
||||
update.SetValidatedAssetVersion(params.ValidatedModelVersion)
|
||||
// DO NOT reset completed when validated model is updated
|
||||
// update.Add("completed", false)
|
||||
allowed_statuses := []model.SubmissionStatus{model.SubmissionStatusValidating}
|
||||
err := svc.inner.UpdateSubmissionIfStatus(ctx, SubmissionID, allowed_statuses, update)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
event_data := model.AuditEventDataChangeValidatedModel{
|
||||
ValidatedModelID: params.ValidatedModelID,
|
||||
ValidatedModelVersion: params.ValidatedModelVersion,
|
||||
}
|
||||
|
||||
err = svc.inner.CreateAuditEventChangeValidatedModel(
|
||||
ctx,
|
||||
model.ValidatorUserID,
|
||||
model.Resource{
|
||||
ID: SubmissionID,
|
||||
Type: model.ResourceSubmission,
|
||||
},
|
||||
event_data,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &validator.NullResponse{}, nil
|
||||
}
|
||||
|
||||
// ActionSubmissionSubmitted invokes actionSubmissionSubmitted operation.
|
||||
//
|
||||
// Role Validator changes status from Submitting -> Submitted.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/validator-submitted
|
||||
func (svc *Submissions) SetStatusSubmitted(ctx context.Context, params *validator.SubmittedRequest) (*validator.NullResponse, error) {
|
||||
SubmissionID := int64(params.ID)
|
||||
// transaction
|
||||
target_status := model.SubmissionStatusSubmitted
|
||||
update := service.NewSubmissionUpdate()
|
||||
update.SetStatusID(target_status)
|
||||
update.SetAssetVersion(uint64(params.ModelVersion))
|
||||
update.SetDisplayName(params.DisplayName)
|
||||
update.SetCreator(params.Creator)
|
||||
update.SetGameID(uint32(params.GameID))
|
||||
allowed_statuses := []model.SubmissionStatus{model.SubmissionStatusSubmitting}
|
||||
err := svc.inner.UpdateSubmissionIfStatus(ctx, SubmissionID, allowed_statuses, update)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
event_data := model.AuditEventDataAction{
|
||||
TargetStatus: uint32(target_status),
|
||||
}
|
||||
|
||||
err = svc.inner.CreateAuditEventAction(
|
||||
ctx,
|
||||
model.ValidatorUserID,
|
||||
model.Resource{
|
||||
ID: SubmissionID,
|
||||
Type: model.ResourceSubmission,
|
||||
},
|
||||
event_data,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &validator.NullResponse{}, nil
|
||||
}
|
||||
|
||||
// ActionSubmissionRequestChanges implements actionSubmissionRequestChanges operation.
|
||||
//
|
||||
// (Internal endpoint) Role Validator changes status from Submitting -> RequestChanges.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/validator-request-changes
|
||||
func (svc *Submissions) SetStatusRequestChanges(ctx context.Context, params *validator.SubmissionID) (*validator.NullResponse, error) {
|
||||
SubmissionID := int64(params.ID)
|
||||
// transaction
|
||||
target_status := model.SubmissionStatusChangesRequested
|
||||
update := service.NewSubmissionUpdate()
|
||||
update.SetStatusID(target_status)
|
||||
allowed_statuses :=[]model.SubmissionStatus{model.SubmissionStatusSubmitting}
|
||||
err := svc.inner.UpdateSubmissionIfStatus(ctx, SubmissionID, allowed_statuses, update)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// push an action audit event
|
||||
event_data := model.AuditEventDataAction{
|
||||
TargetStatus: uint32(target_status),
|
||||
}
|
||||
|
||||
err = svc.inner.CreateAuditEventAction(
|
||||
ctx,
|
||||
model.ValidatorUserID,
|
||||
model.Resource{
|
||||
ID: SubmissionID,
|
||||
Type: model.ResourceSubmission,
|
||||
},
|
||||
event_data,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &validator.NullResponse{}, nil
|
||||
}
|
||||
|
||||
// ActionSubmissionValidate invokes actionSubmissionValidate operation.
|
||||
//
|
||||
// Role Validator changes status from Validating -> Validated.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/validator-validated
|
||||
func (svc *Submissions) SetStatusValidated(ctx context.Context, params *validator.SubmissionID) (*validator.NullResponse, error) {
|
||||
SubmissionID := int64(params.ID)
|
||||
// transaction
|
||||
target_status := model.SubmissionStatusValidated
|
||||
update := service.NewSubmissionUpdate()
|
||||
update.SetStatusID(target_status)
|
||||
allowed_statuses :=[]model.SubmissionStatus{model.SubmissionStatusValidating}
|
||||
err := svc.inner.UpdateSubmissionIfStatus(ctx, SubmissionID, allowed_statuses, update)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
event_data := model.AuditEventDataAction{
|
||||
TargetStatus: uint32(target_status),
|
||||
}
|
||||
|
||||
err = svc.inner.CreateAuditEventAction(
|
||||
ctx,
|
||||
model.ValidatorUserID,
|
||||
model.Resource{
|
||||
ID: SubmissionID,
|
||||
Type: model.ResourceSubmission,
|
||||
},
|
||||
event_data,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &validator.NullResponse{}, nil
|
||||
}
|
||||
|
||||
// ActionSubmissionAccepted implements actionSubmissionAccepted operation.
|
||||
//
|
||||
// (Internal endpoint) Role Validator changes status from Validating -> Accepted.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/validator-failed
|
||||
func (svc *Submissions) SetStatusFailed(ctx context.Context, params *validator.SubmissionID) (*validator.NullResponse, error) {
|
||||
SubmissionID := int64(params.ID)
|
||||
// transaction
|
||||
target_status := model.SubmissionStatusAcceptedUnvalidated
|
||||
update := service.NewSubmissionUpdate()
|
||||
update.SetStatusID(target_status)
|
||||
allowed_statuses :=[]model.SubmissionStatus{model.SubmissionStatusValidating}
|
||||
err := svc.inner.UpdateSubmissionIfStatus(ctx, SubmissionID, allowed_statuses, update)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// push an action audit event
|
||||
event_data := model.AuditEventDataAction{
|
||||
TargetStatus: uint32(target_status),
|
||||
}
|
||||
|
||||
err = svc.inner.CreateAuditEventAction(
|
||||
ctx,
|
||||
model.ValidatorUserID,
|
||||
model.Resource{
|
||||
ID: SubmissionID,
|
||||
Type: model.ResourceSubmission,
|
||||
},
|
||||
event_data,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &validator.NullResponse{}, nil
|
||||
}
|
||||
|
||||
// ActionSubmissionUploaded implements actionSubmissionUploaded operation.
|
||||
//
|
||||
// (Internal endpoint) Role Validator changes status from Uploading -> Uploaded.
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/status/validator-uploaded
|
||||
func (svc *Submissions) SetStatusUploaded(ctx context.Context, params *validator.StatusUploadedRequest) (*validator.NullResponse, error) {
|
||||
SubmissionID := int64(params.ID)
|
||||
// transaction
|
||||
target_status := model.SubmissionStatusUploaded
|
||||
update := service.NewSubmissionUpdate()
|
||||
update.SetStatusID(target_status)
|
||||
update.SetUploadedAssetID(params.UploadedAssetID)
|
||||
allowed_statuses :=[]model.SubmissionStatus{model.SubmissionStatusUploading}
|
||||
err := svc.inner.UpdateSubmissionIfStatus(ctx, SubmissionID, allowed_statuses, update)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
event_data := model.AuditEventDataAction{
|
||||
TargetStatus: uint32(target_status),
|
||||
}
|
||||
|
||||
err = svc.inner.CreateAuditEventAction(
|
||||
ctx,
|
||||
model.ValidatorUserID,
|
||||
model.Resource{
|
||||
ID: SubmissionID,
|
||||
Type: model.ResourceSubmission,
|
||||
},
|
||||
event_data,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &validator.NullResponse{}, nil
|
||||
}
|
||||
|
||||
// CreateSubmissionAuditError implements createSubmissionAuditError operation.
|
||||
//
|
||||
// Post an error to the audit log
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/error
|
||||
func (svc *Submissions) CreateAuditError(ctx context.Context, params *validator.AuditErrorRequest) (*validator.NullResponse, error) {
|
||||
SubmissionID := int64(params.ID)
|
||||
event_data := model.AuditEventDataError{
|
||||
Error: params.ErrorMessage,
|
||||
}
|
||||
|
||||
err := svc.inner.CreateAuditEventError(
|
||||
ctx,
|
||||
model.ValidatorUserID,
|
||||
model.Resource{
|
||||
ID: SubmissionID,
|
||||
Type: model.ResourceSubmission,
|
||||
},
|
||||
event_data,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &validator.NullResponse{}, nil
|
||||
}
|
||||
|
||||
// CreateSubmissionAuditCheckList implements createSubmissionAuditCheckList operation.
|
||||
//
|
||||
// Post a checklist to the audit log
|
||||
//
|
||||
// POST /submissions/{SubmissionID}/checklist
|
||||
func (svc *Submissions) CreateAuditChecklist(ctx context.Context, params *validator.AuditChecklistRequest) (*validator.NullResponse, error) {
|
||||
SubmissionID := int64(params.ID)
|
||||
check_list := make([]model.Check, len(params.CheckList))
|
||||
for i, check := range params.CheckList {
|
||||
check_list[i] = model.Check{
|
||||
Name: check.Name,
|
||||
Summary: check.Summary,
|
||||
Passed: check.Passed,
|
||||
}
|
||||
}
|
||||
|
||||
event_data := model.AuditEventDataCheckList{
|
||||
CheckList: check_list,
|
||||
}
|
||||
|
||||
err := svc.inner.CreateAuditEventCheckList(
|
||||
ctx,
|
||||
model.ValidatorUserID,
|
||||
model.Resource{
|
||||
ID: SubmissionID,
|
||||
Type: model.ResourceSubmission,
|
||||
},
|
||||
event_data,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &validator.NullResponse{}, nil
|
||||
}
|
||||
|
||||
// POST /submissions
|
||||
func (svc *Submissions) Create(ctx context.Context, request *validator.SubmissionCreate) (*validator.SubmissionID, error) {
|
||||
var Submitter=uint64(request.AssetOwner);
|
||||
var Status=model.SubmissionStatus(request.Status);
|
||||
var roles=model.Roles(request.Roles);
|
||||
|
||||
// Check if an active submission with the same asset id exists
|
||||
{
|
||||
filter := service.NewSubmissionFilter()
|
||||
filter.SetAssetID(request.AssetID)
|
||||
filter.SetAssetVersion(request.AssetVersion)
|
||||
filter.SetStatuses(ActiveSubmissionStatuses)
|
||||
active_submissions, err := svc.inner.ListSubmissions(ctx, filter, model.Page{
|
||||
Number: 1,
|
||||
Size: 1,
|
||||
},datastore.ListSortDisabled)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(active_submissions) != 0{
|
||||
return nil, ErrActiveSubmissionSameAssetID
|
||||
}
|
||||
}
|
||||
|
||||
operation_id := int32(request.OperationID)
|
||||
operation, err := svc.inner.GetOperation(ctx, operation_id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// check if user owns asset
|
||||
is_submitter := operation.Owner == Submitter
|
||||
// check if user is map admin
|
||||
has_submission_review := roles & model.RolesSubmissionReview == model.RolesSubmissionReview
|
||||
// if neither, u not allowed
|
||||
if !is_submitter && !has_submission_review {
|
||||
return nil, ErrNotAssetOwner
|
||||
}
|
||||
|
||||
submission, err := svc.inner.CreateSubmission(ctx, model.Submission{
|
||||
ID: 0,
|
||||
DisplayName: request.DisplayName,
|
||||
Creator: request.Creator,
|
||||
GameID: request.GameID,
|
||||
Submitter: Submitter,
|
||||
AssetID: request.AssetID,
|
||||
AssetVersion: request.AssetVersion,
|
||||
Completed: false,
|
||||
StatusID: Status,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// mark the operation as completed and provide the path
|
||||
params := service.NewOperationCompleteParams(fmt.Sprintf("/submissions/%d", submission.ID))
|
||||
err = svc.inner.CompleteOperation(ctx, operation_id, params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &validator.SubmissionID{
|
||||
ID: uint64(submission.ID),
|
||||
}, nil
|
||||
}
|
||||
1068
pkg/web_api/mapfixes.go
Normal file
1068
pkg/web_api/mapfixes.go
Normal file
File diff suppressed because it is too large
Load Diff
140
pkg/web_api/maps.go
Normal file
140
pkg/web_api/maps.go
Normal file
@@ -0,0 +1,140 @@
|
||||
package web_api
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/api"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/roblox"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/service"
|
||||
)
|
||||
|
||||
// MigrateMaps implements migrateMaps operation.
|
||||
//
|
||||
// Perform maps migration.
|
||||
//
|
||||
// POST /migrate
|
||||
func (svc *Service) MigrateMaps(ctx context.Context) (error) {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
has_role, err := userInfo.HasRoleSubmissionRelease()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNeedRoleSubmissionRelease
|
||||
}
|
||||
|
||||
return svc.inner.TEMP_DoMapsMigration(ctx)
|
||||
}
|
||||
|
||||
// ListMaps implements listMaps operation.
|
||||
//
|
||||
// Get list of maps.
|
||||
//
|
||||
// GET /maps
|
||||
func (svc *Service) ListMaps(ctx context.Context, params api.ListMapsParams) ([]api.Map, error) {
|
||||
filter := service.NewMapFilter()
|
||||
|
||||
if display_name, display_name_ok := params.DisplayName.Get(); display_name_ok{
|
||||
filter.SetDisplayName(display_name)
|
||||
}
|
||||
if creator, creator_ok := params.Creator.Get(); creator_ok{
|
||||
filter.SetCreator(creator)
|
||||
}
|
||||
if game_id, game_id_ok := params.GameID.Get(); game_id_ok{
|
||||
filter.SetGameID(uint32(game_id))
|
||||
}
|
||||
|
||||
items, err := svc.inner.ListMaps(ctx,
|
||||
filter,
|
||||
model.Page{
|
||||
Size: params.Limit,
|
||||
Number: params.Page,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var resp []api.Map
|
||||
for _, item := range items {
|
||||
resp = append(resp, api.Map{
|
||||
ID: item.ID,
|
||||
DisplayName: item.DisplayName,
|
||||
Creator: item.Creator,
|
||||
GameID: int32(item.GameID),
|
||||
Date: item.Date.Unix(),
|
||||
})
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// GetMap implements getScript operation.
|
||||
//
|
||||
// Get the specified script by ID.
|
||||
//
|
||||
// GET /maps/{MapID}
|
||||
func (svc *Service) GetMap(ctx context.Context, params api.GetMapParams) (*api.Map, error) {
|
||||
mapResponse, err := svc.inner.GetMap(ctx, params.MapID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &api.Map{
|
||||
ID: mapResponse.ID,
|
||||
DisplayName: mapResponse.DisplayName,
|
||||
Creator: mapResponse.Creator,
|
||||
GameID: int32(mapResponse.GameID),
|
||||
Date: mapResponse.Date.Unix(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// DownloadMapAsset invokes downloadMapAsset operation.
|
||||
//
|
||||
// Download the map asset.
|
||||
//
|
||||
// GET /maps/{MapID}/download
|
||||
func (svc *Service) DownloadMapAsset(ctx context.Context, params api.DownloadMapAssetParams) (ok api.DownloadMapAssetOK, err error) {
|
||||
userInfo, success := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !success {
|
||||
return ok, ErrUserInfo
|
||||
}
|
||||
|
||||
has_role, err := userInfo.HasRoleMapDownload()
|
||||
if err != nil {
|
||||
return ok, err
|
||||
}
|
||||
|
||||
if !has_role {
|
||||
return ok, ErrPermissionDeniedNeedRoleMapDownload
|
||||
}
|
||||
|
||||
// Ensure map exists in the db!
|
||||
// This could otherwise be used to access any asset
|
||||
_, err = svc.inner.GetMap(ctx, params.MapID)
|
||||
if err != nil {
|
||||
return ok, err
|
||||
}
|
||||
|
||||
info, err := svc.roblox.GetAssetLocation(roblox.GetAssetLatestRequest{
|
||||
AssetID: uint64(params.MapID),
|
||||
})
|
||||
if err != nil{
|
||||
return ok, err
|
||||
}
|
||||
|
||||
// download the complete file
|
||||
asset, err := svc.roblox.DownloadAsset(info)
|
||||
if err != nil{
|
||||
return ok, err
|
||||
}
|
||||
|
||||
ok.Data = asset
|
||||
return ok, nil
|
||||
}
|
||||
46
pkg/web_api/operations.go
Normal file
46
pkg/web_api/operations.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package web_api
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/api"
|
||||
)
|
||||
|
||||
// GetOperation implements getOperation operation.
|
||||
//
|
||||
// Get the specified operation by ID.
|
||||
//
|
||||
// GET /operations/{OperationID}
|
||||
func (svc *Service) GetOperation(ctx context.Context, params api.GetOperationParams) (*api.Operation, error) {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return nil, ErrUserInfo
|
||||
}
|
||||
|
||||
// You must be the operation owner to read it
|
||||
|
||||
operation, err := svc.inner.GetOperation(ctx, params.OperationID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
userId, err := userInfo.GetUserID()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// check if caller is the submitter
|
||||
has_role := userId == operation.Owner
|
||||
if !has_role {
|
||||
return nil, ErrPermissionDeniedNotSubmitter
|
||||
}
|
||||
|
||||
return &api.Operation{
|
||||
OperationID: operation.ID,
|
||||
Date: operation.CreatedAt.Unix(),
|
||||
Owner: int64(operation.Owner),
|
||||
Status: int32(operation.StatusID),
|
||||
StatusMessage: operation.StatusMessage,
|
||||
Path: operation.Path,
|
||||
}, nil
|
||||
}
|
||||
149
pkg/web_api/script_policy.go
Normal file
149
pkg/web_api/script_policy.go
Normal file
@@ -0,0 +1,149 @@
|
||||
package web_api
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/api"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/service"
|
||||
)
|
||||
|
||||
// CreateScriptPolicy implements createScriptPolicy operation.
|
||||
//
|
||||
// Create a new script policy.
|
||||
//
|
||||
// POST /script-policy
|
||||
func (svc *Service) CreateScriptPolicy(ctx context.Context, req *api.ScriptPolicyCreate) (*api.ScriptPolicyID, error) {
|
||||
err := CheckHasRoleScriptWrite(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
from_script, err := svc.inner.GetScript(ctx, req.FromScriptID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// the existence of ToScriptID does not need to be validated because it's checked by a foreign key constraint.
|
||||
|
||||
script, err := svc.inner.CreateScriptPolicy(ctx, model.ScriptPolicy{
|
||||
ID: 0,
|
||||
FromScriptHash: from_script.Hash,
|
||||
ToScriptID: req.ToScriptID,
|
||||
Policy: model.Policy(req.Policy),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &api.ScriptPolicyID{
|
||||
ScriptPolicyID: script.ID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
// ListScriptPolicy implements listScriptPolicy operation.
|
||||
//
|
||||
// Get list of script policies.
|
||||
//
|
||||
// GET /script-policy
|
||||
func (svc *Service) ListScriptPolicy(ctx context.Context, params api.ListScriptPolicyParams) ([]api.ScriptPolicy, error) {
|
||||
filter := service.NewScriptPolicyFilter()
|
||||
|
||||
if hash_hex, ok := params.FromScriptHash.Get(); ok{
|
||||
hash_parsed, err := model.HashParse(hash_hex)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
filter.SetFromScriptHash(int64(hash_parsed))
|
||||
}
|
||||
if to_script_id, to_script_id_ok := params.ToScriptID.Get(); to_script_id_ok{
|
||||
filter.SetToScriptID(to_script_id)
|
||||
}
|
||||
if policy, policy_ok := params.Policy.Get(); policy_ok{
|
||||
filter.SetPolicy(policy)
|
||||
}
|
||||
|
||||
|
||||
items, err := svc.inner.ListScriptPolicies(ctx, filter, model.Page{
|
||||
Number: params.Page,
|
||||
Size: params.Limit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var resp []api.ScriptPolicy
|
||||
for _, item := range items {
|
||||
resp = append(resp, api.ScriptPolicy{
|
||||
ID: item.ID,
|
||||
FromScriptHash: model.HashFormat(uint64(item.FromScriptHash)),
|
||||
ToScriptID: item.ToScriptID,
|
||||
Policy: int32(item.Policy),
|
||||
})
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// DeleteScriptPolicy implements deleteScriptPolicy operation.
|
||||
//
|
||||
// Delete the specified script policy by ID.
|
||||
//
|
||||
// DELETE /script-policy/{ScriptPolicyID}
|
||||
func (svc *Service) DeleteScriptPolicy(ctx context.Context, params api.DeleteScriptPolicyParams) error {
|
||||
err := CheckHasRoleScriptWrite(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return svc.inner.DeleteScriptPolicy(ctx, params.ScriptPolicyID)
|
||||
}
|
||||
|
||||
// GetScriptPolicy implements getScriptPolicy operation.
|
||||
//
|
||||
// Get the specified script policy by ID.
|
||||
//
|
||||
// GET /script-policy/{ScriptPolicyID}
|
||||
func (svc *Service) GetScriptPolicy(ctx context.Context, params api.GetScriptPolicyParams) (*api.ScriptPolicy, error) {
|
||||
policy, err := svc.inner.GetScriptPolicy(ctx, params.ScriptPolicyID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &api.ScriptPolicy{
|
||||
ID: policy.ID,
|
||||
FromScriptHash: model.HashFormat(uint64(policy.FromScriptHash)),
|
||||
ToScriptID: policy.ToScriptID,
|
||||
Policy: int32(policy.Policy),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// UpdateScriptPolicy implements updateScriptPolicy operation.
|
||||
//
|
||||
// Update the specified script policy by ID.
|
||||
//
|
||||
// POST /script-policy/{ScriptPolicyID}
|
||||
func (svc *Service) UpdateScriptPolicy(ctx context.Context, req *api.ScriptPolicyUpdate, params api.UpdateScriptPolicyParams) error {
|
||||
err := CheckHasRoleScriptWrite(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
filter := service.NewScriptPolicyFilter()
|
||||
if from_script_id, ok := req.FromScriptID.Get(); ok {
|
||||
from_script, err := svc.inner.GetScript(ctx, from_script_id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
filter.SetFromScriptHash(from_script.Hash)
|
||||
}
|
||||
if to_script_id, to_script_id_ok := req.ToScriptID.Get(); to_script_id_ok{
|
||||
filter.SetToScriptID(to_script_id)
|
||||
}
|
||||
if policy, policy_ok := req.Policy.Get(); policy_ok{
|
||||
filter.SetPolicy(policy)
|
||||
}
|
||||
|
||||
return svc.inner.UpdateScriptPolicy(ctx, req.ID, filter)
|
||||
}
|
||||
170
pkg/web_api/scripts.go
Normal file
170
pkg/web_api/scripts.go
Normal file
@@ -0,0 +1,170 @@
|
||||
package web_api
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/api"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/service"
|
||||
)
|
||||
|
||||
func CheckHasRoleScriptWrite(ctx context.Context) error {
|
||||
userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
|
||||
if !ok {
|
||||
return ErrUserInfo
|
||||
}
|
||||
|
||||
has_role, err := userInfo.HasRoleScriptWrite()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !has_role {
|
||||
return ErrPermissionDeniedNeedRoleScriptWrite
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateScript implements createScript operation.
|
||||
//
|
||||
// Create a new script.
|
||||
//
|
||||
// POST /scripts
|
||||
func (svc *Service) CreateScript(ctx context.Context, req *api.ScriptCreate) (*api.ScriptID, error) {
|
||||
err := CheckHasRoleScriptWrite(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
script, err := svc.inner.CreateScript(ctx, model.Script{
|
||||
ID: 0,
|
||||
Name: req.Name,
|
||||
Hash: int64(model.HashSource(req.Source)),
|
||||
Source: req.Source,
|
||||
ResourceType: model.ResourceType(req.ResourceType),
|
||||
ResourceID: req.ResourceID.Or(0),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &api.ScriptID{
|
||||
ScriptID: script.ID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ListScripts implements listScripts operation.
|
||||
//
|
||||
// Get list of scripts.
|
||||
//
|
||||
// GET /scripts
|
||||
func (svc *Service) ListScripts(ctx context.Context, params api.ListScriptsParams) ([]api.Script, error) {
|
||||
filter := service.NewScriptFilter()
|
||||
|
||||
if hash_hex, ok := params.Hash.Get(); ok{
|
||||
hash_parsed, err := model.HashParse(hash_hex)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
filter.SetHash(int64(hash_parsed))
|
||||
}
|
||||
if name, name_ok := params.Name.Get(); name_ok{
|
||||
filter.SetName(name)
|
||||
}
|
||||
if source, source_ok := params.Source.Get(); source_ok{
|
||||
filter.SetSource(source)
|
||||
}
|
||||
if resource_type, resource_type_ok := params.ResourceType.Get(); resource_type_ok{
|
||||
filter.SetResourceType(resource_type)
|
||||
}
|
||||
if resource_id, resource_id_ok := params.ResourceID.Get(); resource_id_ok{
|
||||
filter.SetResourceID(resource_id)
|
||||
}
|
||||
|
||||
|
||||
items, err := svc.inner.ListScripts(ctx, filter, model.Page{
|
||||
Number: params.Page,
|
||||
Size: params.Limit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var resp []api.Script
|
||||
for _, item := range items {
|
||||
resp = append(resp, api.Script{
|
||||
ID: item.ID,
|
||||
Name: item.Name,
|
||||
Hash: model.HashFormat(uint64(item.Hash)),
|
||||
Source: item.Source,
|
||||
ResourceType: int32(item.ResourceType),
|
||||
ResourceID: item.ResourceID,
|
||||
})
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// DeleteScript implements deleteScript operation.
|
||||
//
|
||||
// Delete the specified script by ID.
|
||||
//
|
||||
// DELETE /scripts/{ScriptID}
|
||||
func (svc *Service) DeleteScript(ctx context.Context, params api.DeleteScriptParams) error {
|
||||
err := CheckHasRoleScriptWrite(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return svc.inner.DeleteScript(ctx, params.ScriptID)
|
||||
}
|
||||
|
||||
// GetScript implements getScript operation.
|
||||
//
|
||||
// Get the specified script by ID.
|
||||
//
|
||||
// GET /scripts/{ScriptID}
|
||||
func (svc *Service) GetScript(ctx context.Context, params api.GetScriptParams) (*api.Script, error) {
|
||||
script, err := svc.inner.GetScript(ctx, params.ScriptID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &api.Script{
|
||||
ID: script.ID,
|
||||
Name: script.Name,
|
||||
Hash: model.HashFormat(uint64(script.Hash)),
|
||||
Source: script.Source,
|
||||
ResourceType: int32(script.ResourceType),
|
||||
ResourceID: script.ResourceID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// UpdateScript implements updateScript operation.
|
||||
//
|
||||
// Update the specified script by ID.
|
||||
//
|
||||
// PATCH /scripts/{ScriptID}
|
||||
func (svc *Service) UpdateScript(ctx context.Context, req *api.ScriptUpdate, params api.UpdateScriptParams) error {
|
||||
err := CheckHasRoleScriptWrite(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
filter := service.NewScriptFilter()
|
||||
if name, name_ok := req.Name.Get(); name_ok{
|
||||
filter.SetName(name)
|
||||
}
|
||||
if source, source_ok := req.Source.Get(); source_ok{
|
||||
filter.SetSource(source)
|
||||
filter.SetHash(int64(model.HashSource(source)))
|
||||
}
|
||||
if resource_type, resource_type_ok := req.ResourceType.Get(); resource_type_ok{
|
||||
filter.SetResourceType(resource_type)
|
||||
}
|
||||
if resource_id, resource_id_ok := req.ResourceID.Get(); resource_id_ok{
|
||||
filter.SetResourceID(resource_id)
|
||||
}
|
||||
|
||||
return svc.inner.UpdateScript(ctx, req.ID, filter)
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
package service
|
||||
package web_api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"git.itzana.me/strafesnet/go-grpc/auth"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/api"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/model"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -14,38 +16,6 @@ var (
|
||||
ErrInvalidSession = errors.New("Session invalid")
|
||||
)
|
||||
|
||||
// Submissions roles bitflag
|
||||
type Roles int32
|
||||
var (
|
||||
RolesSubmissionUpload Roles = 1<<6
|
||||
RolesSubmissionReview Roles = 1<<5
|
||||
RolesSubmissionRelease Roles = 1<<4
|
||||
RolesScriptWrite Roles = 1<<3
|
||||
RolesMapfixUpload Roles = 1<<2
|
||||
RolesMapfixReview Roles = 1<<1
|
||||
RolesMapDownload Roles = 1<<0
|
||||
RolesEmpty Roles = 0
|
||||
)
|
||||
|
||||
// StrafesNET group roles
|
||||
type GroupRole int32
|
||||
var (
|
||||
// has ScriptWrite
|
||||
RoleQuat GroupRole = 255
|
||||
RoleItzaname GroupRole = 254
|
||||
RoleStagingDeveloper GroupRole = 240
|
||||
RolesAll Roles = ^RolesEmpty
|
||||
// has SubmissionUpload
|
||||
RoleMapAdmin GroupRole = 128
|
||||
RolesMapAdmin Roles = RolesSubmissionRelease|RolesSubmissionUpload|RolesSubmissionReview|RolesMapCouncil
|
||||
// has MapfixReview
|
||||
RoleMapCouncil GroupRole = 64
|
||||
RolesMapCouncil Roles = RolesMapfixReview|RolesMapfixUpload|RolesMapAccess
|
||||
// access to downloading maps
|
||||
RoleMapAccess GroupRole = 32
|
||||
RolesMapAccess Roles = RolesMapDownload
|
||||
)
|
||||
|
||||
type UserInfoHandle struct {
|
||||
// Would love to know a better way to do this
|
||||
svc *SecurityHandler
|
||||
@@ -88,14 +58,7 @@ func (usr UserInfoHandle) Validate() (bool, error) {
|
||||
}
|
||||
return validate.Valid, nil
|
||||
}
|
||||
func (usr UserInfoHandle) IsSubmitter(submitter uint64) (bool, error) {
|
||||
userId, err := usr.GetUserID()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return userId == submitter, nil
|
||||
}
|
||||
func (usr UserInfoHandle) hasRoles(wantRoles Roles) (bool, error) {
|
||||
func (usr UserInfoHandle) hasRoles(wantRoles model.Roles) (bool, error) {
|
||||
haveroles, err := usr.GetRoles()
|
||||
if err != nil {
|
||||
return false, err
|
||||
@@ -103,27 +66,27 @@ func (usr UserInfoHandle) hasRoles(wantRoles Roles) (bool, error) {
|
||||
|
||||
return haveroles & wantRoles == wantRoles, nil
|
||||
}
|
||||
func (usr UserInfoHandle) GetRoles() (Roles, error) {
|
||||
func (usr UserInfoHandle) GetRoles() (model.Roles, error) {
|
||||
roles, err := usr.svc.Client.GetGroupRole(*usr.ctx, &auth.IdMessage{
|
||||
SessionID: usr.sessionId,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return RolesEmpty, err
|
||||
return model.RolesEmpty, err
|
||||
}
|
||||
|
||||
// map roles into bitflag
|
||||
rolesBitflag := RolesEmpty;
|
||||
rolesBitflag := model.RolesEmpty;
|
||||
for _, r := range roles.Roles {
|
||||
switch GroupRole(r.Rank){
|
||||
case RoleQuat, RoleItzaname, RoleStagingDeveloper:
|
||||
rolesBitflag|=RolesAll
|
||||
case RoleMapAdmin:
|
||||
rolesBitflag|=RolesMapAdmin
|
||||
case RoleMapCouncil:
|
||||
rolesBitflag|=RolesMapCouncil
|
||||
case RoleMapAccess:
|
||||
rolesBitflag|=RolesMapAccess
|
||||
switch model.GroupRole(r.Rank){
|
||||
case model.RoleQuat, model.RoleItzaname, model.RoleStagingDeveloper:
|
||||
rolesBitflag|=model.RolesAll
|
||||
case model.RoleMapAdmin:
|
||||
rolesBitflag|=model.RolesMapAdmin
|
||||
case model.RoleMapCouncil:
|
||||
rolesBitflag|=model.RolesMapCouncil
|
||||
case model.RoleMapAccess:
|
||||
rolesBitflag|=model.RolesMapAccess
|
||||
}
|
||||
}
|
||||
return rolesBitflag, nil
|
||||
@@ -131,25 +94,25 @@ func (usr UserInfoHandle) GetRoles() (Roles, error) {
|
||||
|
||||
// RoleThumbnail
|
||||
func (usr UserInfoHandle) HasRoleMapfixUpload() (bool, error) {
|
||||
return usr.hasRoles(RolesMapfixUpload)
|
||||
return usr.hasRoles(model.RolesMapfixUpload)
|
||||
}
|
||||
func (usr UserInfoHandle) HasRoleMapfixReview() (bool, error) {
|
||||
return usr.hasRoles(RolesMapfixReview)
|
||||
return usr.hasRoles(model.RolesMapfixReview)
|
||||
}
|
||||
func (usr UserInfoHandle) HasRoleMapDownload() (bool, error) {
|
||||
return usr.hasRoles(RolesMapDownload)
|
||||
return usr.hasRoles(model.RolesMapDownload)
|
||||
}
|
||||
func (usr UserInfoHandle) HasRoleSubmissionRelease() (bool, error) {
|
||||
return usr.hasRoles(RolesSubmissionRelease)
|
||||
return usr.hasRoles(model.RolesSubmissionRelease)
|
||||
}
|
||||
func (usr UserInfoHandle) HasRoleSubmissionUpload() (bool, error) {
|
||||
return usr.hasRoles(RolesSubmissionUpload)
|
||||
return usr.hasRoles(model.RolesSubmissionUpload)
|
||||
}
|
||||
func (usr UserInfoHandle) HasRoleSubmissionReview() (bool, error) {
|
||||
return usr.hasRoles(RolesSubmissionReview)
|
||||
return usr.hasRoles(model.RolesSubmissionReview)
|
||||
}
|
||||
func (usr UserInfoHandle) HasRoleScriptWrite() (bool, error) {
|
||||
return usr.hasRoles(RolesScriptWrite)
|
||||
return usr.hasRoles(model.RolesScriptWrite)
|
||||
}
|
||||
/// Not implemented
|
||||
func (usr UserInfoHandle) HasRoleMaptest() (bool, error) {
|
||||
68
pkg/web_api/service.go
Normal file
68
pkg/web_api/service.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package web_api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/api"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/datastore"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/roblox"
|
||||
"git.itzana.me/strafesnet/maps-service/pkg/service"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrPermissionDenied caller does not have the required role
|
||||
ErrPermissionDenied = errors.New("Permission denied")
|
||||
// ErrUserInfo user info is missing for some reason
|
||||
ErrUserInfo = errors.New("Missing user info")
|
||||
ErrDelayReset = errors.New("Please give the validator at least 10 seconds to operate before attempting to reset the status")
|
||||
ErrPermissionDeniedNotSubmitter = fmt.Errorf("%w: You must be the submitter to perform this action", ErrPermissionDenied)
|
||||
ErrPermissionDeniedNeedRoleSubmissionRelease = fmt.Errorf("%w: Need Role SubmissionRelease", ErrPermissionDenied)
|
||||
ErrPermissionDeniedNeedRoleMapfixUpload = fmt.Errorf("%w: Need Role MapfixUpload", ErrPermissionDenied)
|
||||
ErrPermissionDeniedNeedRoleMapfixReview = fmt.Errorf("%w: Need Role MapfixReview", ErrPermissionDenied)
|
||||
ErrPermissionDeniedNeedRoleSubmissionUpload = fmt.Errorf("%w: Need Role SubmissionUpload", ErrPermissionDenied)
|
||||
ErrPermissionDeniedNeedRoleSubmissionReview = fmt.Errorf("%w: Need Role SubmissionReview", ErrPermissionDenied)
|
||||
ErrPermissionDeniedNeedRoleMapDownload = fmt.Errorf("%w: Need Role MapDownload", ErrPermissionDenied)
|
||||
ErrPermissionDeniedNeedRoleScriptWrite = fmt.Errorf("%w: Need Role ScriptWrite", ErrPermissionDenied)
|
||||
ErrPermissionDeniedNeedRoleMaptest = fmt.Errorf("%w: Need Role Maptest", ErrPermissionDenied)
|
||||
ErrNegativeID = errors.New("A negative ID was provided")
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
inner *service.Service
|
||||
roblox roblox.Client
|
||||
}
|
||||
|
||||
func NewService(
|
||||
inner *service.Service,
|
||||
roblox roblox.Client,
|
||||
) Service {
|
||||
return Service{
|
||||
inner: inner,
|
||||
roblox: roblox,
|
||||
}
|
||||
}
|
||||
|
||||
// NewError creates *ErrorStatusCode from error returned by handler.
|
||||
//
|
||||
// Used for common default response.
|
||||
func (svc *Service) NewError(ctx context.Context, err error) *api.ErrorStatusCode {
|
||||
status := 500
|
||||
if errors.Is(err, datastore.ErrNotExist) {
|
||||
status = 404
|
||||
}
|
||||
if errors.Is(err, ErrPermissionDenied) {
|
||||
status = 403
|
||||
}
|
||||
if errors.Is(err, ErrUserInfo) {
|
||||
status = 401
|
||||
}
|
||||
return &api.ErrorStatusCode{
|
||||
StatusCode: status,
|
||||
Response: api.Error{
|
||||
Code: int64(status),
|
||||
Message: err.Error(),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package service
|
||||
package web_api
|
||||
|
||||
import (
|
||||
"context"
|
||||
1178
pkg/web_api/submissions.go
Normal file
1178
pkg/web_api/submissions.go
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,18 +1,21 @@
|
||||
[package]
|
||||
name = "maps-validation"
|
||||
version = "0.1.1"
|
||||
edition = "2021"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
submissions-api = { path = "api", features = ["internal"], default-features = false, registry = "strafesnet" }
|
||||
async-nats = "0.40.0"
|
||||
async-nats = "0.42.0"
|
||||
futures = "0.3.31"
|
||||
rbx_asset = { version = "0.2.5", registry = "strafesnet" }
|
||||
rbx_binary = { version = "0.7.4", registry = "strafesnet"}
|
||||
rbx_dom_weak = { version = "2.9.0", registry = "strafesnet"}
|
||||
rbx_reflection_database = { version = "0.2.12", registry = "strafesnet"}
|
||||
rbx_xml = { version = "0.13.3", registry = "strafesnet"}
|
||||
rbx_asset = { version = "0.4.7", registry = "strafesnet" }
|
||||
rbx_binary = "1.0.0"
|
||||
rbx_dom_weak = "3.0.0"
|
||||
rbx_reflection_database = "1.0.3"
|
||||
rbx_xml = "1.0.0"
|
||||
serde = { version = "1.0.215", features = ["derive"] }
|
||||
serde_json = "1.0.133"
|
||||
siphasher = "1.0.1"
|
||||
tokio = { version = "1.41.1", features = ["macros", "rt-multi-thread", "signal"] }
|
||||
heck = "0.5.0"
|
||||
lazy-regex = "3.4.1"
|
||||
rust-grpc = { version = "1.2.1", registry = "strafesnet" }
|
||||
tonic = "0.13.1"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Using the `rust-musl-builder` as base image, instead of
|
||||
# the official Rust toolchain
|
||||
FROM docker.io/clux/muslrust:stable AS chef
|
||||
FROM registry.itzana.me/docker-proxy/clux/muslrust:1.86.0-stable AS chef
|
||||
USER root
|
||||
RUN cargo install cargo-chef
|
||||
WORKDIR /app
|
||||
@@ -17,7 +17,7 @@ RUN cargo chef cook --release --target x86_64-unknown-linux-musl --recipe-path r
|
||||
COPY . .
|
||||
RUN cargo build --release --target x86_64-unknown-linux-musl --bin maps-validation
|
||||
|
||||
FROM docker.io/alpine:latest AS runtime
|
||||
FROM registry.itzana.me/docker-proxy/alpine:3.21 AS runtime
|
||||
RUN addgroup -S myuser && adduser -S myuser -G myuser
|
||||
COPY --from=builder /app/target/x86_64-unknown-linux-musl/release/maps-validation /usr/local/bin/
|
||||
USER myuser
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "submissions-api"
|
||||
version = "0.6.1"
|
||||
edition = "2021"
|
||||
version = "0.8.2"
|
||||
edition = "2024"
|
||||
publish = ["strafesnet"]
|
||||
repository = "https://git.itzana.me/StrafesNET/maps-service"
|
||||
license = "MIT OR Apache-2.0"
|
||||
@@ -11,13 +11,9 @@ authors = ["Rhys Lloyd <krakow20@gmail.com>"]
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
chrono = { version = "0.4.41", features = ["serde"] }
|
||||
reqwest = { version = "0", features = ["json"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
serde_repr = "0.1.19"
|
||||
url = "2"
|
||||
|
||||
[features]
|
||||
default = ["external"]
|
||||
internal = []
|
||||
external = []
|
||||
|
||||
@@ -33,15 +33,14 @@ impl Context{
|
||||
self.client.get(url)
|
||||
.send().await
|
||||
}
|
||||
#[cfg(feature="internal")]
|
||||
pub async fn post_empty_body(&self,url:impl reqwest::IntoUrl)->Result<reqwest::Response,reqwest::Error>{
|
||||
self.client.post(url)
|
||||
.send().await
|
||||
}
|
||||
pub async fn post(&self,url:impl reqwest::IntoUrl,body:impl Into<reqwest::Body>)->Result<reqwest::Response,reqwest::Error>{
|
||||
self.client.post(url)
|
||||
.header("Content-Type","application/json")
|
||||
.body(body)
|
||||
.send().await
|
||||
}
|
||||
pub async fn delete(&self,url:impl reqwest::IntoUrl)->Result<reqwest::Response,reqwest::Error>{
|
||||
self.client.delete(url)
|
||||
.send().await
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ impl Context{
|
||||
).await.map_err(Error::Response)?
|
||||
.json().await.map_err(Error::ReqwestJson)
|
||||
}
|
||||
pub async fn get_scripts<'a>(&self,config:GetScriptsRequest<'a>)->Result<Vec<ScriptResponse>,Error>{
|
||||
pub async fn get_scripts(&self,config:GetScriptsRequest<'_>)->Result<Vec<ScriptResponse>,Error>{
|
||||
let url_raw=format!("{}/scripts",self.0.base_url);
|
||||
let mut url=reqwest::Url::parse(url_raw.as_str()).map_err(Error::Parse)?;
|
||||
|
||||
@@ -36,7 +36,7 @@ impl Context{
|
||||
if let Some(resource_type)=config.ResourceType{
|
||||
query_pairs.append_pair("ResourceType",(resource_type as i32).to_string().as_str());
|
||||
}
|
||||
if let Some(resource_id)=config.ResourceID{
|
||||
if let Some(ResourceID(resource_id))=config.ResourceID{
|
||||
query_pairs.append_pair("ResourceID",resource_id.to_string().as_str());
|
||||
}
|
||||
}
|
||||
@@ -46,7 +46,7 @@ impl Context{
|
||||
).await.map_err(Error::Response)?
|
||||
.json().await.map_err(Error::ReqwestJson)
|
||||
}
|
||||
pub async fn get_script_from_hash<'a>(&self,config:HashRequest<'a>)->Result<Option<ScriptResponse>,SingleItemError>{
|
||||
pub async fn get_script_from_hash(&self,config:HashRequest<'_>)->Result<Option<ScriptResponse>,ScriptSingleItemError>{
|
||||
let scripts=self.get_scripts(GetScriptsRequest{
|
||||
Page:1,
|
||||
Limit:2,
|
||||
@@ -57,11 +57,11 @@ impl Context{
|
||||
ResourceID:None,
|
||||
}).await.map_err(SingleItemError::Other)?;
|
||||
if 1<scripts.len(){
|
||||
return Err(SingleItemError::DuplicateItems);
|
||||
return Err(SingleItemError::DuplicateItems(scripts.into_iter().map(|item|item.ID).collect()));
|
||||
}
|
||||
Ok(scripts.into_iter().next())
|
||||
}
|
||||
pub async fn create_script<'a>(&self,config:CreateScriptRequest<'a>)->Result<ScriptIDResponse,Error>{
|
||||
pub async fn create_script(&self,config:CreateScriptRequest<'_>)->Result<ScriptIDResponse,Error>{
|
||||
let url_raw=format!("{}/scripts",self.0.base_url);
|
||||
let url=reqwest::Url::parse(url_raw.as_str()).map_err(Error::Parse)?;
|
||||
|
||||
@@ -72,7 +72,17 @@ impl Context{
|
||||
).await.map_err(Error::Response)?
|
||||
.json().await.map_err(Error::ReqwestJson)
|
||||
}
|
||||
pub async fn get_script_policies<'a>(&self,config:GetScriptPoliciesRequest<'a>)->Result<Vec<ScriptPolicyResponse>,Error>{
|
||||
pub async fn delete_script(&self,config:GetScriptRequest)->Result<(),Error>{
|
||||
let url_raw=format!("{}/scripts/{}",self.0.base_url,config.ScriptID.0);
|
||||
let url=reqwest::Url::parse(url_raw.as_str()).map_err(Error::Parse)?;
|
||||
|
||||
response_ok(
|
||||
self.0.delete(url).await.map_err(Error::Reqwest)?
|
||||
).await.map_err(Error::Response)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
pub async fn get_script_policies(&self,config:GetScriptPoliciesRequest<'_>)->Result<Vec<ScriptPolicyResponse>,Error>{
|
||||
let url_raw=format!("{}/script-policy",self.0.base_url);
|
||||
let mut url=reqwest::Url::parse(url_raw.as_str()).map_err(Error::Parse)?;
|
||||
|
||||
@@ -96,7 +106,7 @@ impl Context{
|
||||
).await.map_err(Error::Response)?
|
||||
.json().await.map_err(Error::ReqwestJson)
|
||||
}
|
||||
pub async fn get_script_policy_from_hash<'a>(&self,config:HashRequest<'a>)->Result<Option<ScriptPolicyResponse>,SingleItemError>{
|
||||
pub async fn get_script_policy_from_hash(&self,config:HashRequest<'_>)->Result<Option<ScriptPolicyResponse>,ScriptPolicySingleItemError>{
|
||||
let policies=self.get_script_policies(GetScriptPoliciesRequest{
|
||||
Page:1,
|
||||
Limit:2,
|
||||
@@ -105,7 +115,7 @@ impl Context{
|
||||
Policy:None,
|
||||
}).await.map_err(SingleItemError::Other)?;
|
||||
if 1<policies.len(){
|
||||
return Err(SingleItemError::DuplicateItems);
|
||||
return Err(SingleItemError::DuplicateItems(policies.into_iter().map(|item|item.ID).collect()));
|
||||
}
|
||||
Ok(policies.into_iter().next())
|
||||
}
|
||||
@@ -130,6 +140,94 @@ impl Context{
|
||||
self.0.post(url,body).await.map_err(Error::Reqwest)?
|
||||
).await.map_err(Error::Response)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
pub async fn delete_script_policy(&self,config:GetScriptPolicyRequest)->Result<(),Error>{
|
||||
let url_raw=format!("{}/script-policy/{}",self.0.base_url,config.ScriptPolicyID.0);
|
||||
let url=reqwest::Url::parse(url_raw.as_str()).map_err(Error::Parse)?;
|
||||
|
||||
response_ok(
|
||||
self.0.delete(url).await.map_err(Error::Reqwest)?
|
||||
).await.map_err(Error::Response)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
pub async fn get_submissions(&self,config:GetSubmissionsRequest<'_>)->Result<SubmissionsResponse,Error>{
|
||||
let url_raw=format!("{}/submissions",self.0.base_url);
|
||||
let mut url=reqwest::Url::parse(url_raw.as_str()).map_err(Error::Parse)?;
|
||||
|
||||
{
|
||||
let mut query_pairs=url.query_pairs_mut();
|
||||
query_pairs.append_pair("Page",config.Page.to_string().as_str());
|
||||
query_pairs.append_pair("Limit",config.Limit.to_string().as_str());
|
||||
if let Some(sort)=config.Sort{
|
||||
query_pairs.append_pair("Sort",(sort as u8).to_string().as_str());
|
||||
}
|
||||
if let Some(display_name)=config.DisplayName{
|
||||
query_pairs.append_pair("DisplayName",display_name);
|
||||
}
|
||||
if let Some(creator)=config.Creator{
|
||||
query_pairs.append_pair("Creator",creator);
|
||||
}
|
||||
if let Some(game_id)=config.GameID{
|
||||
query_pairs.append_pair("GameID",(game_id as u8).to_string().as_str());
|
||||
}
|
||||
if let Some(submitter)=config.Submitter{
|
||||
query_pairs.append_pair("Submitter",submitter.to_string().as_str());
|
||||
}
|
||||
if let Some(asset_id)=config.AssetID{
|
||||
query_pairs.append_pair("AssetID",asset_id.to_string().as_str());
|
||||
}
|
||||
if let Some(uploaded_asset_id)=config.UploadedAssetID{
|
||||
query_pairs.append_pair("UploadedAssetID",uploaded_asset_id.to_string().as_str());
|
||||
}
|
||||
if let Some(status_id)=config.StatusID{
|
||||
query_pairs.append_pair("StatusID",(status_id as u8).to_string().as_str());
|
||||
}
|
||||
}
|
||||
|
||||
response_ok(
|
||||
self.0.get(url).await.map_err(Error::Reqwest)?
|
||||
).await.map_err(Error::Response)?
|
||||
.json().await.map_err(Error::ReqwestJson)
|
||||
}
|
||||
pub async fn get_maps(&self,config:GetMapsRequest<'_>)->Result<Vec<MapResponse>,Error>{
|
||||
let url_raw=format!("{}/maps",self.0.base_url);
|
||||
let mut url=reqwest::Url::parse(url_raw.as_str()).map_err(Error::Parse)?;
|
||||
|
||||
{
|
||||
let mut query_pairs=url.query_pairs_mut();
|
||||
query_pairs.append_pair("Page",config.Page.to_string().as_str());
|
||||
query_pairs.append_pair("Limit",config.Limit.to_string().as_str());
|
||||
if let Some(sort)=config.Sort{
|
||||
query_pairs.append_pair("Sort",(sort as u8).to_string().as_str());
|
||||
}
|
||||
if let Some(display_name)=config.DisplayName{
|
||||
query_pairs.append_pair("DisplayName",display_name);
|
||||
}
|
||||
if let Some(creator)=config.Creator{
|
||||
query_pairs.append_pair("Creator",creator);
|
||||
}
|
||||
if let Some(game_id)=config.GameID{
|
||||
query_pairs.append_pair("GameID",(game_id as u8).to_string().as_str());
|
||||
}
|
||||
}
|
||||
|
||||
response_ok(
|
||||
self.0.get(url).await.map_err(Error::Reqwest)?
|
||||
).await.map_err(Error::Response)?
|
||||
.json().await.map_err(Error::ReqwestJson)
|
||||
}
|
||||
pub async fn release_submissions(&self,config:ReleaseRequest<'_>)->Result<(),Error>{
|
||||
let url_raw=format!("{}/release-submissions",self.0.base_url);
|
||||
let url=reqwest::Url::parse(url_raw.as_str()).map_err(Error::Parse)?;
|
||||
|
||||
let body=serde_json::to_string(config.schedule).map_err(Error::JSON)?;
|
||||
|
||||
response_ok(
|
||||
self.0.post(url,body).await.map_err(Error::Reqwest)?
|
||||
).await.map_err(Error::Response)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,175 +0,0 @@
|
||||
use crate::types::*;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Context(crate::context::Context);
|
||||
|
||||
// conditionally include specified query pairs
|
||||
macro_rules! query_pairs{
|
||||
($url:expr,)=>{
|
||||
$url
|
||||
};
|
||||
($url:expr,$(($param:expr,$value:expr))+)=>{
|
||||
{
|
||||
let mut url=$url;
|
||||
url.query_pairs_mut()
|
||||
$(.append_pair($param,$value))*;
|
||||
url
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// there are lots of action endpoints and they all follow the same pattern
|
||||
macro_rules! action{
|
||||
($system:expr,$fname:ident,$config:ident,$config_type:ident,$action:expr,$config_submission_id:expr,$(($param:expr,$value:expr))*)=>{
|
||||
pub async fn $fname(&self,$config:$config_type)->Result<(),Error>{
|
||||
let url_raw=format!(concat!("{}/",$system,"/{}/status/",$action),self.0.base_url,$config_submission_id);
|
||||
let url=query_pairs!(reqwest::Url::parse(url_raw.as_str()).map_err(Error::Parse)?,$(($param,$value))*);
|
||||
|
||||
response_ok(
|
||||
self.0.post_empty_body(url).await.map_err(Error::Reqwest)?
|
||||
).await.map_err(Error::Response)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
}
|
||||
impl Context{
|
||||
pub fn new(base_url:String)->reqwest::Result<Self>{
|
||||
Ok(Self(crate::context::Context::new(base_url,None)?))
|
||||
}
|
||||
pub async fn get_script(&self,config:GetScriptRequest)->Result<ScriptResponse,Error>{
|
||||
let url_raw=format!("{}/scripts/{}",self.0.base_url,config.ScriptID.0);
|
||||
let url=reqwest::Url::parse(url_raw.as_str()).map_err(Error::Parse)?;
|
||||
|
||||
response_ok(
|
||||
self.0.get(url).await.map_err(Error::Reqwest)?
|
||||
).await.map_err(Error::Response)?
|
||||
.json().await.map_err(Error::ReqwestJson)
|
||||
}
|
||||
pub async fn get_scripts<'a>(&self,config:GetScriptsRequest<'a>)->Result<Vec<ScriptResponse>,Error>{
|
||||
let url_raw=format!("{}/scripts",self.0.base_url);
|
||||
let mut url=reqwest::Url::parse(url_raw.as_str()).map_err(Error::Parse)?;
|
||||
|
||||
{
|
||||
let mut query_pairs=url.query_pairs_mut();
|
||||
query_pairs.append_pair("Page",config.Page.to_string().as_str());
|
||||
query_pairs.append_pair("Limit",config.Limit.to_string().as_str());
|
||||
if let Some(name)=config.Name{
|
||||
query_pairs.append_pair("Name",name);
|
||||
}
|
||||
if let Some(hash)=config.Hash{
|
||||
query_pairs.append_pair("Hash",hash);
|
||||
}
|
||||
if let Some(source)=config.Source{
|
||||
query_pairs.append_pair("Source",source);
|
||||
}
|
||||
if let Some(resource_type)=config.ResourceType{
|
||||
query_pairs.append_pair("ResourceType",(resource_type as i32).to_string().as_str());
|
||||
}
|
||||
if let Some(resource_id)=config.ResourceID{
|
||||
query_pairs.append_pair("ResourceID",resource_id.to_string().as_str());
|
||||
}
|
||||
}
|
||||
|
||||
response_ok(
|
||||
self.0.get(url).await.map_err(Error::Reqwest)?
|
||||
).await.map_err(Error::Response)?
|
||||
.json().await.map_err(Error::ReqwestJson)
|
||||
}
|
||||
pub async fn get_script_from_hash<'a>(&self,config:HashRequest<'a>)->Result<Option<ScriptResponse>,SingleItemError>{
|
||||
let scripts=self.get_scripts(GetScriptsRequest{
|
||||
Page:1,
|
||||
Limit:2,
|
||||
Hash:Some(config.hash),
|
||||
Name:None,
|
||||
Source:None,
|
||||
ResourceType:None,
|
||||
ResourceID:None,
|
||||
}).await.map_err(SingleItemError::Other)?;
|
||||
if 1<scripts.len(){
|
||||
return Err(SingleItemError::DuplicateItems);
|
||||
}
|
||||
Ok(scripts.into_iter().next())
|
||||
}
|
||||
pub async fn create_script<'a>(&self,config:CreateScriptRequest<'a>)->Result<ScriptIDResponse,Error>{
|
||||
let url_raw=format!("{}/scripts",self.0.base_url);
|
||||
let url=reqwest::Url::parse(url_raw.as_str()).map_err(Error::Parse)?;
|
||||
|
||||
let body=serde_json::to_string(&config).map_err(Error::JSON)?;
|
||||
|
||||
response_ok(
|
||||
self.0.post(url,body).await.map_err(Error::Reqwest)?
|
||||
).await.map_err(Error::Response)?
|
||||
.json().await.map_err(Error::ReqwestJson)
|
||||
}
|
||||
pub async fn get_script_policies<'a>(&self,config:GetScriptPoliciesRequest<'a>)->Result<Vec<ScriptPolicyResponse>,Error>{
|
||||
let url_raw=format!("{}/script-policy",self.0.base_url);
|
||||
let mut url=reqwest::Url::parse(url_raw.as_str()).map_err(Error::Parse)?;
|
||||
|
||||
{
|
||||
let mut query_pairs=url.query_pairs_mut();
|
||||
query_pairs.append_pair("Page",config.Page.to_string().as_str());
|
||||
query_pairs.append_pair("Limit",config.Limit.to_string().as_str());
|
||||
if let Some(hash)=config.FromScriptHash{
|
||||
query_pairs.append_pair("FromScriptHash",hash);
|
||||
}
|
||||
if let Some(script_id)=config.ToScriptID{
|
||||
query_pairs.append_pair("ToScriptID",script_id.0.to_string().as_str());
|
||||
}
|
||||
if let Some(policy)=config.Policy{
|
||||
query_pairs.append_pair("Policy",(policy as i32).to_string().as_str());
|
||||
}
|
||||
}
|
||||
|
||||
response_ok(
|
||||
self.0.get(url).await.map_err(Error::Reqwest)?
|
||||
).await.map_err(Error::Response)?
|
||||
.json().await.map_err(Error::ReqwestJson)
|
||||
}
|
||||
pub async fn get_script_policy_from_hash<'a>(&self,config:HashRequest<'a>)->Result<Option<ScriptPolicyResponse>,SingleItemError>{
|
||||
let policies=self.get_script_policies(GetScriptPoliciesRequest{
|
||||
Page:1,
|
||||
Limit:2,
|
||||
FromScriptHash:Some(config.hash),
|
||||
ToScriptID:None,
|
||||
Policy:None,
|
||||
}).await.map_err(SingleItemError::Other)?;
|
||||
if 1<policies.len(){
|
||||
return Err(SingleItemError::DuplicateItems);
|
||||
}
|
||||
Ok(policies.into_iter().next())
|
||||
}
|
||||
pub async fn create_script_policy(&self,config:CreateScriptPolicyRequest)->Result<ScriptPolicyIDResponse,Error>{
|
||||
let url_raw=format!("{}/script-policy",self.0.base_url);
|
||||
let url=reqwest::Url::parse(url_raw.as_str()).map_err(Error::Parse)?;
|
||||
|
||||
let body=serde_json::to_string(&config).map_err(Error::JSON)?;
|
||||
|
||||
response_ok(
|
||||
self.0.post(url,body).await.map_err(Error::Reqwest)?
|
||||
).await.map_err(Error::Response)?
|
||||
.json().await.map_err(Error::ReqwestJson)
|
||||
}
|
||||
// simple submission endpoints
|
||||
action!("submissions",action_submission_validated,config,SubmissionID,"validator-validated",config.0,);
|
||||
action!("submissions",update_submission_validated_model,config,UpdateSubmissionModelRequest,"validated-model",config.SubmissionID,
|
||||
("ValidatedModelID",config.ModelID.to_string().as_str())
|
||||
("ValidatedModelVersion",config.ModelVersion.to_string().as_str())
|
||||
);
|
||||
action!("submissions",action_submission_uploaded,config,ActionSubmissionUploadedRequest,"validator-uploaded",config.SubmissionID,
|
||||
("UploadedAssetID",config.UploadedAssetID.to_string().as_str())
|
||||
);
|
||||
action!("submissions",action_submission_accepted,config,ActionSubmissionAcceptedRequest,"validator-failed",config.SubmissionID,
|
||||
("StatusMessage",config.StatusMessage.as_str())
|
||||
);
|
||||
// simple mapfixes endpoints
|
||||
action!("mapfixes",action_mapfix_validated,config,MapfixID,"validator-validated",config.0,);
|
||||
action!("mapfixes",update_mapfix_validated_model,config,UpdateMapfixModelRequest,"validated-model",config.MapfixID,
|
||||
("ValidatedModelID",config.ModelID.to_string().as_str())
|
||||
("ValidatedModelVersion",config.ModelVersion.to_string().as_str())
|
||||
);
|
||||
action!("mapfixes",action_mapfix_uploaded,config,ActionMapfixUploadedRequest,"validator-uploaded",config.MapfixID,);
|
||||
action!("mapfixes",action_mapfix_accepted,config,ActionMapfixAcceptedRequest,"validator-failed",config.MapfixID,
|
||||
("StatusMessage",config.StatusMessage.as_str())
|
||||
);
|
||||
}
|
||||
@@ -2,11 +2,6 @@ mod context;
|
||||
pub use context::Cookie;
|
||||
|
||||
pub mod types;
|
||||
|
||||
#[cfg(feature="internal")]
|
||||
pub mod internal;
|
||||
|
||||
#[cfg(feature="external")]
|
||||
pub mod external;
|
||||
|
||||
//lazy reexports
|
||||
|
||||
@@ -14,21 +14,25 @@ impl std::fmt::Display for Error{
|
||||
impl std::error::Error for Error{}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum SingleItemError{
|
||||
DuplicateItems,
|
||||
pub enum SingleItemError<Items>{
|
||||
DuplicateItems(Items),
|
||||
Other(Error),
|
||||
}
|
||||
impl std::fmt::Display for SingleItemError{
|
||||
impl<Items> std::fmt::Display for SingleItemError<Items>
|
||||
where
|
||||
Items:std::fmt::Debug
|
||||
{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
write!(f,"{self:?}")
|
||||
}
|
||||
}
|
||||
impl std::error::Error for SingleItemError{}
|
||||
impl<Items> std::error::Error for SingleItemError<Items> where Items:std::fmt::Debug{}
|
||||
pub type ScriptSingleItemError=SingleItemError<Vec<ScriptID>>;
|
||||
pub type ScriptPolicySingleItemError=SingleItemError<Vec<ScriptPolicyID>>;
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug)]
|
||||
pub struct StatusCodeWithUrlAndBody{
|
||||
pub status_code:reqwest::StatusCode,
|
||||
pub struct UrlAndBody{
|
||||
pub url:url::Url,
|
||||
pub body:String,
|
||||
}
|
||||
@@ -36,7 +40,10 @@ pub struct StatusCodeWithUrlAndBody{
|
||||
#[derive(Debug)]
|
||||
pub enum ResponseError{
|
||||
Reqwest(reqwest::Error),
|
||||
StatusCodeWithUrlAndBody(StatusCodeWithUrlAndBody),
|
||||
Details{
|
||||
status_code:reqwest::StatusCode,
|
||||
url_and_body:Box<UrlAndBody>,
|
||||
},
|
||||
}
|
||||
impl std::fmt::Display for ResponseError{
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
@@ -53,17 +60,63 @@ pub async fn response_ok(response:reqwest::Response)->Result<reqwest::Response,R
|
||||
let url=response.url().to_owned();
|
||||
let bytes=response.bytes().await.map_err(ResponseError::Reqwest)?;
|
||||
let body=String::from_utf8_lossy(&bytes).to_string();
|
||||
Err(ResponseError::StatusCodeWithUrlAndBody(StatusCodeWithUrlAndBody{
|
||||
Err(ResponseError::Details{
|
||||
status_code,
|
||||
url,
|
||||
body,
|
||||
}))
|
||||
url_and_body:Box::new(UrlAndBody{url,body})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone,Copy,Debug,PartialEq,Eq,serde::Serialize,serde::Deserialize)]
|
||||
#[derive(Clone,Copy,Debug,Hash,Eq,PartialEq,Ord,PartialOrd,serde_repr::Serialize_repr,serde_repr::Deserialize_repr)]
|
||||
#[repr(u8)]
|
||||
pub enum GameID{
|
||||
Bhop=1,
|
||||
Surf=2,
|
||||
KreedzClimb=3,
|
||||
FlyTrials=5,
|
||||
}
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug,serde::Serialize)]
|
||||
pub struct CreateMapfixRequest<'a>{
|
||||
pub OperationID:OperationID,
|
||||
pub AssetOwner:i64,
|
||||
pub DisplayName:&'a str,
|
||||
pub Creator:&'a str,
|
||||
pub GameID:GameID,
|
||||
pub AssetID:u64,
|
||||
pub AssetVersion:u64,
|
||||
pub TargetAssetID:u64,
|
||||
pub Description:&'a str,
|
||||
}
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug,serde::Deserialize)]
|
||||
pub struct MapfixIDResponse{
|
||||
pub MapfixID:MapfixID,
|
||||
}
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug,serde::Serialize)]
|
||||
pub struct CreateSubmissionRequest<'a>{
|
||||
pub OperationID:OperationID,
|
||||
pub AssetOwner:i64,
|
||||
pub DisplayName:&'a str,
|
||||
pub Creator:&'a str,
|
||||
pub GameID:GameID,
|
||||
pub AssetID:u64,
|
||||
pub AssetVersion:u64,
|
||||
pub Status:u32,
|
||||
pub Roles:u32,
|
||||
}
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug,serde::Deserialize)]
|
||||
pub struct SubmissionIDResponse{
|
||||
pub SubmissionID:SubmissionID,
|
||||
}
|
||||
|
||||
#[derive(Clone,Copy,Debug,Hash,Eq,PartialEq,serde::Serialize,serde::Deserialize)]
|
||||
pub struct ScriptID(pub(crate)i64);
|
||||
#[derive(Clone,Copy,Debug,serde::Serialize,serde::Deserialize)]
|
||||
#[derive(Clone,Copy,Debug,Hash,Eq,PartialEq,serde::Serialize,serde::Deserialize)]
|
||||
pub struct ScriptPolicyID(pub(crate)i64);
|
||||
|
||||
#[derive(Clone,Copy,Debug,PartialEq,Eq,serde_repr::Serialize_repr,serde_repr::Deserialize_repr)]
|
||||
@@ -92,7 +145,7 @@ pub struct GetScriptsRequest<'a>{
|
||||
#[serde(skip_serializing_if="Option::is_none")]
|
||||
pub ResourceType:Option<ResourceType>,
|
||||
#[serde(skip_serializing_if="Option::is_none")]
|
||||
pub ResourceID:Option<i64>,
|
||||
pub ResourceID:Option<ResourceID>,
|
||||
}
|
||||
#[derive(Clone,Copy,Debug)]
|
||||
pub struct HashRequest<'a>{
|
||||
@@ -106,7 +159,7 @@ pub struct ScriptResponse{
|
||||
pub Hash:String,
|
||||
pub Source:String,
|
||||
pub ResourceType:ResourceType,
|
||||
pub ResourceID:i64,
|
||||
pub ResourceID:ResourceID,
|
||||
}
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug,serde::Serialize)]
|
||||
@@ -115,12 +168,12 @@ pub struct CreateScriptRequest<'a>{
|
||||
pub Source:&'a str,
|
||||
pub ResourceType:ResourceType,
|
||||
#[serde(skip_serializing_if="Option::is_none")]
|
||||
pub ResourceID:Option<i64>,
|
||||
pub ResourceID:Option<ResourceID>,
|
||||
}
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug,serde::Deserialize)]
|
||||
pub struct ScriptIDResponse{
|
||||
pub ID:ScriptID,
|
||||
pub ScriptID:ScriptID,
|
||||
}
|
||||
|
||||
#[derive(Clone,Copy,Debug,PartialEq,Eq,serde_repr::Serialize_repr,serde_repr::Deserialize_repr)]
|
||||
@@ -133,6 +186,10 @@ pub enum Policy{
|
||||
Replace=4,
|
||||
}
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
pub struct GetScriptPolicyRequest{
|
||||
pub ScriptPolicyID:ScriptPolicyID,
|
||||
}
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug,serde::Serialize)]
|
||||
pub struct GetScriptPoliciesRequest<'a>{
|
||||
@@ -163,7 +220,7 @@ pub struct CreateScriptPolicyRequest{
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug,serde::Deserialize)]
|
||||
pub struct ScriptPolicyIDResponse{
|
||||
pub ID:ScriptPolicyID,
|
||||
pub ScriptPolicyID:ScriptPolicyID,
|
||||
}
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
@@ -181,48 +238,243 @@ pub struct UpdateScriptPolicyRequest{
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug)]
|
||||
pub struct UpdateSubmissionModelRequest{
|
||||
pub SubmissionID:i64,
|
||||
pub SubmissionID:SubmissionID,
|
||||
pub ModelID:u64,
|
||||
pub ModelVersion:u64,
|
||||
}
|
||||
|
||||
#[derive(Clone,Debug)]
|
||||
pub enum Sort{
|
||||
Disabled=0,
|
||||
DisplayNameAscending=1,
|
||||
DisplayNameDescending=2,
|
||||
DateAscending=3,
|
||||
DateDescending=4,
|
||||
}
|
||||
|
||||
#[derive(Clone,Debug,serde_repr::Deserialize_repr)]
|
||||
#[repr(u8)]
|
||||
pub enum SubmissionStatus{
|
||||
// Phase: Creation
|
||||
UnderConstruction=0,
|
||||
ChangesRequested=1,
|
||||
|
||||
// Phase: Review
|
||||
Submitting=2,
|
||||
Submitted=3,
|
||||
|
||||
// Phase: Testing
|
||||
AcceptedUnvalidated=4, // pending script review, can re-trigger validation
|
||||
Validating=5,
|
||||
Validated=6,
|
||||
Uploading=7,
|
||||
Uploaded=8, // uploaded to the group, but pending release
|
||||
|
||||
// Phase: Final SubmissionStatus
|
||||
Rejected=9,
|
||||
Released=10,
|
||||
}
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug)]
|
||||
pub struct GetSubmissionsRequest<'a>{
|
||||
pub Page:u32,
|
||||
pub Limit:u32,
|
||||
pub Sort:Option<Sort>,
|
||||
pub DisplayName:Option<&'a str>,
|
||||
pub Creator:Option<&'a str>,
|
||||
pub GameID:Option<GameID>,
|
||||
pub Submitter:Option<u64>,
|
||||
pub AssetID:Option<u64>,
|
||||
pub UploadedAssetID:Option<u64>,
|
||||
pub StatusID:Option<SubmissionStatus>,
|
||||
}
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug,serde::Deserialize)]
|
||||
pub struct SubmissionResponse{
|
||||
pub ID:SubmissionID,
|
||||
pub DisplayName:String,
|
||||
pub Creator:String,
|
||||
pub GameID:GameID,
|
||||
pub CreatedAt:i64,
|
||||
pub UpdatedAt:i64,
|
||||
pub Submitter:u64,
|
||||
pub AssetID:u64,
|
||||
pub AssetVersion:u64,
|
||||
pub UploadedAssetID:u64,
|
||||
pub StatusID:SubmissionStatus,
|
||||
}
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug,serde::Deserialize)]
|
||||
pub struct SubmissionsResponse{
|
||||
pub Total:u64,
|
||||
pub Submissions:Vec<SubmissionResponse>,
|
||||
}
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug)]
|
||||
pub struct GetMapsRequest<'a>{
|
||||
pub Page:u32,
|
||||
pub Limit:u32,
|
||||
pub Sort:Option<Sort>,
|
||||
pub DisplayName:Option<&'a str>,
|
||||
pub Creator:Option<&'a str>,
|
||||
pub GameID:Option<GameID>,
|
||||
}
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug,serde::Deserialize)]
|
||||
pub struct MapResponse{
|
||||
pub ID:i64,
|
||||
pub DisplayName:String,
|
||||
pub Creator:String,
|
||||
pub GameID:GameID,
|
||||
pub Date:i64,
|
||||
}
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug,serde::Serialize)]
|
||||
pub struct Check{
|
||||
pub Name:&'static str,
|
||||
pub Summary:String,
|
||||
pub Passed:bool,
|
||||
}
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug)]
|
||||
pub struct ActionSubmissionSubmittedRequest{
|
||||
pub SubmissionID:SubmissionID,
|
||||
pub ModelVersion:u64,
|
||||
pub DisplayName:String,
|
||||
pub Creator:String,
|
||||
pub GameID:GameID,
|
||||
}
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug)]
|
||||
pub struct ActionSubmissionRequestChangesRequest{
|
||||
pub SubmissionID:SubmissionID,
|
||||
}
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug)]
|
||||
pub struct ActionSubmissionUploadedRequest{
|
||||
pub SubmissionID:i64,
|
||||
pub SubmissionID:SubmissionID,
|
||||
pub UploadedAssetID:u64,
|
||||
}
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug)]
|
||||
pub struct ActionSubmissionAcceptedRequest{
|
||||
pub SubmissionID:i64,
|
||||
pub StatusMessage:String,
|
||||
pub SubmissionID:SubmissionID,
|
||||
}
|
||||
|
||||
#[derive(Clone,Copy,Debug)]
|
||||
pub struct SubmissionID(pub i64);
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug)]
|
||||
pub struct CreateSubmissionAuditErrorRequest{
|
||||
pub SubmissionID:SubmissionID,
|
||||
pub ErrorMessage:String,
|
||||
}
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug)]
|
||||
pub struct CreateSubmissionAuditCheckListRequest<'a>{
|
||||
pub SubmissionID:SubmissionID,
|
||||
pub CheckList:&'a [Check],
|
||||
}
|
||||
|
||||
#[derive(Clone,Copy,Debug,Hash,Eq,PartialEq,serde::Serialize,serde::Deserialize)]
|
||||
pub struct SubmissionID(pub(crate)i64);
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug)]
|
||||
pub struct UpdateMapfixModelRequest{
|
||||
pub MapfixID:i64,
|
||||
pub MapfixID:MapfixID,
|
||||
pub ModelID:u64,
|
||||
pub ModelVersion:u64,
|
||||
}
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug)]
|
||||
pub struct ActionMapfixSubmittedRequest{
|
||||
pub MapfixID:MapfixID,
|
||||
pub ModelVersion:u64,
|
||||
pub DisplayName:String,
|
||||
pub Creator:String,
|
||||
pub GameID:GameID,
|
||||
}
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug)]
|
||||
pub struct ActionMapfixRequestChangesRequest{
|
||||
pub MapfixID:MapfixID,
|
||||
}
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug)]
|
||||
pub struct ActionMapfixUploadedRequest{
|
||||
pub MapfixID:i64,
|
||||
pub MapfixID:MapfixID,
|
||||
}
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug)]
|
||||
pub struct ActionMapfixAcceptedRequest{
|
||||
pub MapfixID:i64,
|
||||
pub MapfixID:MapfixID,
|
||||
}
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug)]
|
||||
pub struct CreateMapfixAuditErrorRequest{
|
||||
pub MapfixID:MapfixID,
|
||||
pub ErrorMessage:String,
|
||||
}
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug)]
|
||||
pub struct CreateMapfixAuditCheckListRequest<'a>{
|
||||
pub MapfixID:MapfixID,
|
||||
pub CheckList:&'a [Check],
|
||||
}
|
||||
|
||||
#[derive(Clone,Copy,Debug,Hash,Eq,PartialEq,serde::Serialize,serde::Deserialize)]
|
||||
pub struct MapfixID(pub(crate)i64);
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug)]
|
||||
pub struct ActionOperationFailedRequest{
|
||||
pub OperationID:OperationID,
|
||||
pub StatusMessage:String,
|
||||
}
|
||||
|
||||
#[derive(Clone,Copy,Debug,Hash,Eq,PartialEq,serde::Serialize,serde::Deserialize)]
|
||||
pub struct OperationID(pub(crate)i64);
|
||||
|
||||
#[derive(Clone,Copy,Debug,Hash,Eq,PartialEq,serde::Serialize,serde::Deserialize)]
|
||||
pub struct ResourceID(pub(crate)i64);
|
||||
|
||||
#[derive(Clone,Copy,Debug)]
|
||||
pub struct MapfixID(pub i64);
|
||||
pub enum Resource{
|
||||
Submission(SubmissionID),
|
||||
Mapfix(MapfixID),
|
||||
}
|
||||
impl Resource{
|
||||
pub fn split(self)->(ResourceType,ResourceID){
|
||||
match self{
|
||||
Resource::Mapfix(MapfixID(mapfix_id))=>(ResourceType::Mapfix,ResourceID(mapfix_id)),
|
||||
Resource::Submission(SubmissionID(submission_id))=>(ResourceType::Submission,ResourceID(submission_id)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
#[derive(Clone,Debug,serde::Serialize)]
|
||||
pub struct ReleaseInfo{
|
||||
pub SubmissionID:SubmissionID,
|
||||
pub Date:chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
pub struct ReleaseRequest<'a>{
|
||||
pub schedule:&'a [ReleaseInfo],
|
||||
}
|
||||
|
||||
900
validation/src/check.rs
Normal file
900
validation/src/check.rs
Normal file
@@ -0,0 +1,900 @@
|
||||
use std::collections::{HashSet,HashMap};
|
||||
use crate::download::download_asset_version;
|
||||
use crate::rbx_util::{get_mapinfo,get_root_instance,read_dom,ReadDomError,GameID,ParseGameIDError,MapInfo,GetRootInstanceError,StringValueError};
|
||||
|
||||
use heck::{ToSnakeCase,ToTitleCase};
|
||||
use rbx_dom_weak::Instance;
|
||||
use rust_grpc::validator::Check;
|
||||
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug)]
|
||||
pub enum Error{
|
||||
ModelInfoDownload(rbx_asset::cloud::GetError),
|
||||
CreatorTypeMustBeUser,
|
||||
Download(crate::download::Error),
|
||||
ModelFileDecode(ReadDomError),
|
||||
GetRootInstance(GetRootInstanceError),
|
||||
IntoMapInfoOwned(IntoMapInfoOwnedError),
|
||||
ToJsonValue(serde_json::Error),
|
||||
}
|
||||
impl std::fmt::Display for Error{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
write!(f,"{self:?}")
|
||||
}
|
||||
}
|
||||
impl std::error::Error for Error{}
|
||||
|
||||
#[allow(nonstandard_style)]
|
||||
pub struct CheckRequest{
|
||||
ModelID:u64,
|
||||
SkipChecks:bool,
|
||||
}
|
||||
|
||||
impl From<crate::nats_types::CheckMapfixRequest> for CheckRequest{
|
||||
fn from(value:crate::nats_types::CheckMapfixRequest)->Self{
|
||||
Self{
|
||||
ModelID:value.ModelID,
|
||||
SkipChecks:value.SkipChecks,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl From<crate::nats_types::CheckSubmissionRequest> for CheckRequest{
|
||||
fn from(value:crate::nats_types::CheckSubmissionRequest)->Self{
|
||||
Self{
|
||||
ModelID:value.ModelID,
|
||||
SkipChecks:value.SkipChecks,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone,Copy,Debug,Hash,Eq,PartialEq)]
|
||||
struct ModeID(u64);
|
||||
impl ModeID{
|
||||
const MAIN:Self=Self(0);
|
||||
const BONUS:Self=Self(1);
|
||||
}
|
||||
enum Zone{
|
||||
Start,
|
||||
Finish,
|
||||
Anticheat,
|
||||
}
|
||||
struct ModeElement{
|
||||
zone:Zone,
|
||||
mode_id:ModeID,
|
||||
}
|
||||
#[allow(dead_code)]
|
||||
pub enum IDParseError{
|
||||
NoCaptures,
|
||||
ParseInt(core::num::ParseIntError),
|
||||
}
|
||||
// Parse a Zone from a part name
|
||||
impl std::str::FromStr for ModeElement{
|
||||
type Err=IDParseError;
|
||||
fn from_str(s:&str)->Result<Self,Self::Err>{
|
||||
match s{
|
||||
"MapStart"=>Ok(Self{zone:Zone::Start,mode_id:ModeID::MAIN}),
|
||||
"MapFinish"=>Ok(Self{zone:Zone::Finish,mode_id:ModeID::MAIN}),
|
||||
"MapAnticheat"=>Ok(Self{zone:Zone::Anticheat,mode_id:ModeID::MAIN}),
|
||||
"BonusStart"=>Ok(Self{zone:Zone::Start,mode_id:ModeID::BONUS}),
|
||||
"BonusFinish"=>Ok(Self{zone:Zone::Finish,mode_id:ModeID::BONUS}),
|
||||
"BonusAnticheat"=>Ok(Self{zone:Zone::Anticheat,mode_id:ModeID::BONUS}),
|
||||
other=>{
|
||||
let everything_pattern=lazy_regex::lazy_regex!(r"^Bonus(\d+)Start$|^BonusStart(\d+)$|^Bonus(\d+)Finish$|^BonusFinish(\d+)$|^Bonus(\d+)Anticheat$|^BonusAnticheat(\d+)$");
|
||||
if let Some(captures)=everything_pattern.captures(other){
|
||||
if let Some(mode_id)=captures.get(1).or(captures.get(2)){
|
||||
return Ok(Self{
|
||||
zone:Zone::Start,
|
||||
mode_id:ModeID(mode_id.as_str().parse().map_err(IDParseError::ParseInt)?),
|
||||
});
|
||||
}
|
||||
if let Some(mode_id)=captures.get(3).or(captures.get(4)){
|
||||
return Ok(Self{
|
||||
zone:Zone::Finish,
|
||||
mode_id:ModeID(mode_id.as_str().parse().map_err(IDParseError::ParseInt)?),
|
||||
});
|
||||
}
|
||||
if let Some(mode_id)=captures.get(5).or(captures.get(6)){
|
||||
return Ok(Self{
|
||||
zone:Zone::Anticheat,
|
||||
mode_id:ModeID(mode_id.as_str().parse().map_err(IDParseError::ParseInt)?),
|
||||
});
|
||||
}
|
||||
}
|
||||
Err(IDParseError::NoCaptures)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl std::fmt::Display for ModeElement{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
match self{
|
||||
ModeElement{zone:Zone::Start,mode_id:ModeID::MAIN}=>write!(f,"MapStart"),
|
||||
ModeElement{zone:Zone::Start,mode_id:ModeID::BONUS}=>write!(f,"BonusStart"),
|
||||
ModeElement{zone:Zone::Start,mode_id:ModeID(mode_id)}=>write!(f,"Bonus{mode_id}Start"),
|
||||
ModeElement{zone:Zone::Finish,mode_id:ModeID::MAIN}=>write!(f,"MapFinish"),
|
||||
ModeElement{zone:Zone::Finish,mode_id:ModeID::BONUS}=>write!(f,"BonusFinish"),
|
||||
ModeElement{zone:Zone::Finish,mode_id:ModeID(mode_id)}=>write!(f,"Bonus{mode_id}Finish"),
|
||||
ModeElement{zone:Zone::Anticheat,mode_id:ModeID::MAIN}=>write!(f,"MapAnticheat"),
|
||||
ModeElement{zone:Zone::Anticheat,mode_id:ModeID::BONUS}=>write!(f,"BonusAnticheat"),
|
||||
ModeElement{zone:Zone::Anticheat,mode_id:ModeID(mode_id)}=>write!(f,"Bonus{mode_id}Anticheat"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone,Copy,Debug,Hash,Eq,PartialEq)]
|
||||
struct StageID(u64);
|
||||
impl StageID{
|
||||
const FIRST:Self=Self(1);
|
||||
}
|
||||
enum StageElementBehaviour{
|
||||
Teleport,
|
||||
Spawn,
|
||||
}
|
||||
struct StageElement{
|
||||
stage_id:StageID,
|
||||
behaviour:StageElementBehaviour,
|
||||
}
|
||||
// Parse a SpawnTeleport from a part name
|
||||
impl std::str::FromStr for StageElement{
|
||||
type Err=IDParseError;
|
||||
fn from_str(s:&str)->Result<Self,Self::Err>{
|
||||
// Trigger ForceTrigger Teleport ForceTeleport SpawnAt ForceSpawnAt
|
||||
let bonus_start_pattern=lazy_regex::lazy_regex!(r"^(?:Force)?(Teleport|SpawnAt|Trigger)(\d+)$");
|
||||
if let Some(captures)=bonus_start_pattern.captures(s){
|
||||
return Ok(StageElement{
|
||||
behaviour:StageElementBehaviour::Teleport,
|
||||
stage_id:StageID(captures[1].parse().map_err(IDParseError::ParseInt)?),
|
||||
});
|
||||
}
|
||||
// Spawn
|
||||
let bonus_finish_pattern=lazy_regex::lazy_regex!(r"^Spawn(\d+)$");
|
||||
if let Some(captures)=bonus_finish_pattern.captures(s){
|
||||
return Ok(StageElement{
|
||||
behaviour:StageElementBehaviour::Spawn,
|
||||
stage_id:StageID(captures[1].parse().map_err(IDParseError::ParseInt)?),
|
||||
});
|
||||
}
|
||||
Err(IDParseError::NoCaptures)
|
||||
}
|
||||
}
|
||||
impl std::fmt::Display for StageElement{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
match self{
|
||||
StageElement{behaviour:StageElementBehaviour::Spawn,stage_id:StageID(stage_id)}=>write!(f,"Spawn{stage_id}"),
|
||||
StageElement{behaviour:StageElementBehaviour::Teleport,stage_id:StageID(stage_id)}=>write!(f,"Teleport{stage_id}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone,Copy,Debug,Hash,Eq,PartialEq)]
|
||||
struct WormholeID(u64);
|
||||
enum WormholeBehaviour{
|
||||
In,
|
||||
Out,
|
||||
}
|
||||
struct WormholeElement{
|
||||
behaviour:WormholeBehaviour,
|
||||
wormhole_id:WormholeID,
|
||||
}
|
||||
// Parse a Wormhole from a part name
|
||||
impl std::str::FromStr for WormholeElement{
|
||||
type Err=IDParseError;
|
||||
fn from_str(s:&str)->Result<Self,Self::Err>{
|
||||
let bonus_start_pattern=lazy_regex::lazy_regex!(r"^WormholeIn(\d+)$");
|
||||
if let Some(captures)=bonus_start_pattern.captures(s){
|
||||
return Ok(Self{
|
||||
behaviour:WormholeBehaviour::In,
|
||||
wormhole_id:WormholeID(captures[1].parse().map_err(IDParseError::ParseInt)?),
|
||||
});
|
||||
}
|
||||
let bonus_finish_pattern=lazy_regex::lazy_regex!(r"^WormholeOut(\d+)$");
|
||||
if let Some(captures)=bonus_finish_pattern.captures(s){
|
||||
return Ok(Self{
|
||||
behaviour:WormholeBehaviour::Out,
|
||||
wormhole_id:WormholeID(captures[1].parse().map_err(IDParseError::ParseInt)?),
|
||||
});
|
||||
}
|
||||
Err(IDParseError::NoCaptures)
|
||||
}
|
||||
}
|
||||
impl std::fmt::Display for WormholeElement{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
match self{
|
||||
WormholeElement{behaviour:WormholeBehaviour::In,wormhole_id:WormholeID(wormhole_id)}=>write!(f,"WormholeIn{wormhole_id}"),
|
||||
WormholeElement{behaviour:WormholeBehaviour::Out,wormhole_id:WormholeID(wormhole_id)}=>write!(f,"WormholeOut{wormhole_id}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Count various map elements
|
||||
#[derive(Default)]
|
||||
struct Counts<'a>{
|
||||
mode_start_counts:HashMap<ModeID,Vec<&'a Instance>>,
|
||||
mode_finish_counts:HashMap<ModeID,Vec<&'a Instance>>,
|
||||
mode_anticheat_counts:HashMap<ModeID,Vec<&'a Instance>>,
|
||||
teleport_counts:HashMap<StageID,Vec<&'a Instance>>,
|
||||
spawn_counts:HashMap<StageID,u64>,
|
||||
wormhole_in_counts:HashMap<WormholeID,u64>,
|
||||
wormhole_out_counts:HashMap<WormholeID,u64>,
|
||||
}
|
||||
|
||||
pub struct ModelInfo<'a>{
|
||||
model_class:&'a str,
|
||||
model_name:&'a str,
|
||||
map_info:MapInfo<'a>,
|
||||
counts:Counts<'a>,
|
||||
unanchored_parts:Vec<&'a Instance>,
|
||||
}
|
||||
|
||||
pub fn get_model_info<'a>(dom:&'a rbx_dom_weak::WeakDom,model_instance:&'a rbx_dom_weak::Instance)->ModelInfo<'a>{
|
||||
// extract model info
|
||||
let map_info=get_mapinfo(dom,model_instance);
|
||||
|
||||
// count objects (default count is 0)
|
||||
let mut counts=Counts::default();
|
||||
|
||||
// locate unanchored parts
|
||||
let mut unanchored_parts=Vec::new();
|
||||
let anchored_ustr=rbx_dom_weak::ustr("Anchored");
|
||||
|
||||
let db=rbx_reflection_database::get();
|
||||
let base_part=&db.classes["BasePart"];
|
||||
let base_parts=dom.descendants_of(model_instance.referent()).filter(|&instance|
|
||||
db.classes.get(instance.class.as_str()).is_some_and(|class|
|
||||
db.has_superclass(class,base_part)
|
||||
)
|
||||
);
|
||||
for instance in base_parts{
|
||||
// Zones
|
||||
match instance.name.parse(){
|
||||
Ok(ModeElement{zone:Zone::Start,mode_id})=>counts.mode_start_counts.entry(mode_id).or_default().push(instance),
|
||||
Ok(ModeElement{zone:Zone::Finish,mode_id})=>counts.mode_finish_counts.entry(mode_id).or_default().push(instance),
|
||||
Ok(ModeElement{zone:Zone::Anticheat,mode_id})=>counts.mode_anticheat_counts.entry(mode_id).or_default().push(instance),
|
||||
Err(_)=>(),
|
||||
}
|
||||
// Spawns & Teleports
|
||||
match instance.name.parse(){
|
||||
Ok(StageElement{behaviour:StageElementBehaviour::Teleport,stage_id})=>counts.teleport_counts.entry(stage_id).or_default().push(instance),
|
||||
Ok(StageElement{behaviour:StageElementBehaviour::Spawn,stage_id})=>*counts.spawn_counts.entry(stage_id).or_insert(0)+=1,
|
||||
Err(_)=>(),
|
||||
}
|
||||
// Wormholes
|
||||
match instance.name.parse(){
|
||||
Ok(WormholeElement{behaviour:WormholeBehaviour::In,wormhole_id})=>*counts.wormhole_in_counts.entry(wormhole_id).or_insert(0)+=1,
|
||||
Ok(WormholeElement{behaviour:WormholeBehaviour::Out,wormhole_id})=>*counts.wormhole_out_counts.entry(wormhole_id).or_insert(0)+=1,
|
||||
Err(_)=>(),
|
||||
}
|
||||
// Unanchored parts
|
||||
if let Some(rbx_dom_weak::types::Variant::Bool(false))=instance.properties.get(&anchored_ustr){
|
||||
unanchored_parts.push(instance);
|
||||
}
|
||||
}
|
||||
|
||||
ModelInfo{
|
||||
model_class:model_instance.class.as_str(),
|
||||
model_name:model_instance.name.as_str(),
|
||||
map_info,
|
||||
counts,
|
||||
unanchored_parts,
|
||||
}
|
||||
}
|
||||
|
||||
// check if an observed string matches an expected string
|
||||
pub struct StringCheck<'a,T,Str>(Result<T,StringCheckContext<'a,Str>>);
|
||||
pub struct StringCheckContext<'a,Str>{
|
||||
observed:&'a str,
|
||||
expected:Str,
|
||||
}
|
||||
impl<'a,Str> StringCheckContext<'a,Str>
|
||||
where
|
||||
&'a str:PartialEq<Str>,
|
||||
{
|
||||
/// Compute the StringCheck, passing through the provided value on success.
|
||||
fn check<T>(self,value:T)->StringCheck<'a,T,Str>{
|
||||
if self.observed==self.expected{
|
||||
StringCheck(Ok(value))
|
||||
}else{
|
||||
StringCheck(Err(self))
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<Str:std::fmt::Display> std::fmt::Display for StringCheckContext<'_,Str>{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
write!(f,"expected: {}, observed: {}",self.expected,self.observed)
|
||||
}
|
||||
}
|
||||
|
||||
// check if a string is empty
|
||||
pub struct StringEmpty;
|
||||
impl std::fmt::Display for StringEmpty{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
write!(f,"Empty string")
|
||||
}
|
||||
}
|
||||
fn check_empty(value:&str)->Result<&str,StringEmpty>{
|
||||
(!value.is_empty()).then_some(value).ok_or(StringEmpty)
|
||||
}
|
||||
|
||||
// check for duplicate objects
|
||||
pub struct DuplicateCheckContext<ID,T>(HashMap<ID,T>);
|
||||
pub struct DuplicateCheck<ID,T>(Result<(),DuplicateCheckContext<ID,T>>);
|
||||
impl<ID,T> DuplicateCheckContext<ID,T>{
|
||||
/// Compute the DuplicateCheck using the contents predicate.
|
||||
fn check(self,f:impl Fn(&T)->bool)->DuplicateCheck<ID,T>{
|
||||
let Self(mut set)=self;
|
||||
// remove correct entries
|
||||
set.retain(|_,c|f(c));
|
||||
// if any entries remain, they are incorrect
|
||||
if set.is_empty(){
|
||||
DuplicateCheck(Ok(()))
|
||||
}else{
|
||||
DuplicateCheck(Err(Self(set)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check that there are no items which do not have a matching item in a reference set
|
||||
pub struct SetDifferenceCheckContextAllowNone<ID,T>{
|
||||
extra:HashMap<ID,T>,
|
||||
}
|
||||
// Check that there is at least one matching item for each item in a reference set, and no extra items
|
||||
pub struct SetDifferenceCheckContextAtLeastOne<ID,T>{
|
||||
extra:HashMap<ID,T>,
|
||||
missing:HashSet<ID>,
|
||||
}
|
||||
pub struct SetDifferenceCheck<Context>(Result<(),Context>);
|
||||
impl<ID,T> SetDifferenceCheckContextAllowNone<ID,T>{
|
||||
fn new(initial_set:HashMap<ID,T>)->Self{
|
||||
Self{
|
||||
extra:initial_set,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<ID:Eq+std::hash::Hash,T> SetDifferenceCheckContextAllowNone<ID,T>{
|
||||
/// Compute the SetDifferenceCheck result for the specified reference set.
|
||||
fn check<U>(mut self,reference_set:&HashMap<ID,U>)->SetDifferenceCheck<Self>{
|
||||
// remove correct entries
|
||||
for id in reference_set.keys(){
|
||||
self.extra.remove(id);
|
||||
}
|
||||
// if any entries remain, they are incorrect
|
||||
if self.extra.is_empty(){
|
||||
SetDifferenceCheck(Ok(()))
|
||||
}else{
|
||||
SetDifferenceCheck(Err(self))
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<ID,T> SetDifferenceCheckContextAtLeastOne<ID,T>{
|
||||
fn new(initial_set:HashMap<ID,T>)->Self{
|
||||
Self{
|
||||
extra:initial_set,
|
||||
missing:HashSet::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<ID:Copy+Eq+std::hash::Hash,T> SetDifferenceCheckContextAtLeastOne<ID,T>{
|
||||
/// Compute the SetDifferenceCheck result for the specified reference set.
|
||||
fn check<U>(mut self,reference_set:&HashMap<ID,U>)->SetDifferenceCheck<Self>{
|
||||
// remove correct entries
|
||||
for id in reference_set.keys(){
|
||||
if self.extra.remove(id).is_none(){
|
||||
// the set did not contain a required item. This is a fail
|
||||
self.missing.insert(*id);
|
||||
}
|
||||
}
|
||||
// if any entries remain, they are incorrect
|
||||
if self.extra.is_empty()&&self.missing.is_empty(){
|
||||
SetDifferenceCheck(Ok(()))
|
||||
}else{
|
||||
SetDifferenceCheck(Err(self))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Info lifted out of a fully compliant map
|
||||
pub struct MapInfoOwned{
|
||||
pub display_name:String,
|
||||
pub creator:String,
|
||||
pub game_id:GameID,
|
||||
}
|
||||
#[allow(dead_code)]
|
||||
#[derive(Debug)]
|
||||
pub enum IntoMapInfoOwnedError{
|
||||
DisplayName(StringValueError),
|
||||
Creator(StringValueError),
|
||||
GameID(ParseGameIDError),
|
||||
}
|
||||
impl TryFrom<MapInfo<'_>> for MapInfoOwned{
|
||||
type Error=IntoMapInfoOwnedError;
|
||||
fn try_from(value:MapInfo<'_>)->Result<Self,Self::Error>{
|
||||
Ok(Self{
|
||||
display_name:value.display_name.map_err(IntoMapInfoOwnedError::DisplayName)?.to_owned(),
|
||||
creator:value.creator.map_err(IntoMapInfoOwnedError::Creator)?.to_owned(),
|
||||
game_id:value.game_id.map_err(IntoMapInfoOwnedError::GameID)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Named dummy types for readability
|
||||
struct Exists;
|
||||
struct Absent;
|
||||
|
||||
/// The result of every map check.
|
||||
struct MapCheck<'a>{
|
||||
// === METADATA CHECKS ===
|
||||
// The root must be of class Model
|
||||
model_class:StringCheck<'a,(),&'static str>,
|
||||
// Model's name must be in snake case
|
||||
model_name:StringCheck<'a,(),String>,
|
||||
// Map must have a StringValue named DisplayName.
|
||||
// Value must not be empty, must be in title case.
|
||||
display_name:Result<Result<StringCheck<'a,&'a str,String>,StringEmpty>,StringValueError>,
|
||||
// Map must have a StringValue named Creator.
|
||||
// Value must not be empty.
|
||||
creator:Result<Result<&'a str,StringEmpty>,StringValueError>,
|
||||
// The prefix of the model's name must match the game it was submitted for.
|
||||
// bhop_ for bhop, and surf_ for surf
|
||||
game_id:Result<GameID,ParseGameIDError>,
|
||||
|
||||
// === MODE CHECKS ===
|
||||
// MapStart must exist
|
||||
mapstart:Result<Exists,Absent>,
|
||||
// No duplicate map starts (including bonuses)
|
||||
mode_start_counts:DuplicateCheck<ModeID,Vec<&'a Instance>>,
|
||||
// At least one finish zone for each start zone, and no finishes with no start
|
||||
mode_finish_counts:SetDifferenceCheck<SetDifferenceCheckContextAtLeastOne<ModeID,Vec<&'a Instance>>>,
|
||||
// Check for dangling MapAnticheat zones (no associated MapStart)
|
||||
mode_anticheat_counts:SetDifferenceCheck<SetDifferenceCheckContextAllowNone<ModeID,Vec<&'a Instance>>>,
|
||||
// Spawn1 must exist
|
||||
spawn1:Result<Exists,Absent>,
|
||||
// Check for dangling Teleport# (no associated Spawn#)
|
||||
teleport_counts:SetDifferenceCheck<SetDifferenceCheckContextAllowNone<StageID,Vec<&'a Instance>>>,
|
||||
// No duplicate Spawn#
|
||||
spawn_counts:DuplicateCheck<StageID,u64>,
|
||||
// Check for dangling WormholeIn# (no associated WormholeOut#)
|
||||
wormhole_in_counts:SetDifferenceCheck<SetDifferenceCheckContextAtLeastOne<WormholeID,u64>>,
|
||||
// No duplicate WormholeOut# (duplicate WormholeIn# ok)
|
||||
// No dangling WormholeOut#
|
||||
wormhole_out_counts:DuplicateCheck<WormholeID,u64>,
|
||||
|
||||
// === GENERAL CHECKS ===
|
||||
unanchored_parts:Result<(),Vec<&'a Instance>>,
|
||||
}
|
||||
|
||||
impl<'a> ModelInfo<'a>{
|
||||
fn check(self)->MapCheck<'a>{
|
||||
// Check class is exactly "Model"
|
||||
let model_class=StringCheckContext{
|
||||
observed:self.model_class,
|
||||
expected:"Model",
|
||||
}.check(());
|
||||
|
||||
// Check model name is snake case
|
||||
let model_name=StringCheckContext{
|
||||
observed:self.model_name,
|
||||
expected:self.model_name.to_snake_case(),
|
||||
}.check(());
|
||||
|
||||
// Check display name is not empty and has title case
|
||||
let display_name=self.map_info.display_name.map(|display_name|{
|
||||
check_empty(display_name).map(|display_name|StringCheckContext{
|
||||
observed:display_name,
|
||||
expected:display_name.to_title_case(),
|
||||
}.check(display_name))
|
||||
});
|
||||
|
||||
// Check Creator is not empty
|
||||
let creator=self.map_info.creator.map(check_empty);
|
||||
|
||||
// Check GameID (model name was prefixed with bhop_ surf_ etc)
|
||||
let game_id=self.map_info.game_id;
|
||||
|
||||
// MapStart must exist
|
||||
let mapstart=if self.counts.mode_start_counts.contains_key(&ModeID::MAIN){
|
||||
Ok(Exists)
|
||||
}else{
|
||||
Err(Absent)
|
||||
};
|
||||
|
||||
// Spawn1 must exist
|
||||
let spawn1=if self.counts.spawn_counts.contains_key(&StageID::FIRST){
|
||||
Ok(Exists)
|
||||
}else{
|
||||
Err(Absent)
|
||||
};
|
||||
|
||||
// Check that at least one finish zone exists for each start zone.
|
||||
// This also checks that there are no finish zones without a corresponding start zone.
|
||||
let mode_finish_counts=SetDifferenceCheckContextAtLeastOne::new(self.counts.mode_finish_counts)
|
||||
.check(&self.counts.mode_start_counts);
|
||||
|
||||
// Check that there are no anticheat zones without a corresponding start zone.
|
||||
// Modes are allowed to have 0 anticheat zones.
|
||||
let mode_anticheat_counts=SetDifferenceCheckContextAllowNone::new(self.counts.mode_anticheat_counts)
|
||||
.check(&self.counts.mode_start_counts);
|
||||
|
||||
// There must be exactly one start zone for every mode in the map.
|
||||
let mode_start_counts=DuplicateCheckContext(self.counts.mode_start_counts).check(|c|1<c.len());
|
||||
|
||||
// Check that there are no Teleports without a corresponding Spawn.
|
||||
// Spawns are allowed to have 0 Teleports.
|
||||
let teleport_counts=SetDifferenceCheckContextAllowNone::new(self.counts.teleport_counts)
|
||||
.check(&self.counts.spawn_counts);
|
||||
|
||||
// There must be exactly one of any perticular spawn id in the map.
|
||||
let spawn_counts=DuplicateCheckContext(self.counts.spawn_counts).check(|&c|1<c);
|
||||
|
||||
// Check that at least one WormholeIn exists for each WormholeOut.
|
||||
// This also checks that there are no WormholeIn without a corresponding WormholeOut.
|
||||
let wormhole_in_counts=SetDifferenceCheckContextAtLeastOne::new(self.counts.wormhole_in_counts)
|
||||
.check(&self.counts.wormhole_out_counts);
|
||||
|
||||
// There must be exactly one of any perticular wormhole out id in the map.
|
||||
let wormhole_out_counts=DuplicateCheckContext(self.counts.wormhole_out_counts).check(|&c|1<c);
|
||||
|
||||
// There must not be any unanchored parts
|
||||
let unanchored_parts=if self.unanchored_parts.is_empty(){
|
||||
Ok(())
|
||||
}else{
|
||||
Err(self.unanchored_parts)
|
||||
};
|
||||
|
||||
MapCheck{
|
||||
model_class,
|
||||
model_name,
|
||||
display_name,
|
||||
creator,
|
||||
game_id,
|
||||
mapstart,
|
||||
mode_start_counts,
|
||||
mode_finish_counts,
|
||||
mode_anticheat_counts,
|
||||
spawn1,
|
||||
teleport_counts,
|
||||
spawn_counts,
|
||||
wormhole_in_counts,
|
||||
wormhole_out_counts,
|
||||
unanchored_parts,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MapCheck<'_>{
|
||||
fn result(self)->Result<MapInfoOwned,Result<MapCheckList,serde_json::Error>>{
|
||||
match self{
|
||||
MapCheck{
|
||||
model_class:StringCheck(Ok(())),
|
||||
model_name:StringCheck(Ok(())),
|
||||
display_name:Ok(Ok(StringCheck(Ok(display_name)))),
|
||||
creator:Ok(Ok(creator)),
|
||||
game_id:Ok(game_id),
|
||||
mapstart:Ok(Exists),
|
||||
mode_start_counts:DuplicateCheck(Ok(())),
|
||||
mode_finish_counts:SetDifferenceCheck(Ok(())),
|
||||
mode_anticheat_counts:SetDifferenceCheck(Ok(())),
|
||||
spawn1:Ok(Exists),
|
||||
teleport_counts:SetDifferenceCheck(Ok(())),
|
||||
spawn_counts:DuplicateCheck(Ok(())),
|
||||
wormhole_in_counts:SetDifferenceCheck(Ok(())),
|
||||
wormhole_out_counts:DuplicateCheck(Ok(())),
|
||||
unanchored_parts:Ok(()),
|
||||
}=>{
|
||||
Ok(MapInfoOwned{
|
||||
display_name:display_name.to_owned(),
|
||||
creator:creator.to_owned(),
|
||||
game_id,
|
||||
})
|
||||
},
|
||||
other=>Err(other.itemize()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Separated<F>{
|
||||
f:F,
|
||||
separator:&'static str,
|
||||
}
|
||||
impl<F> Separated<F>{
|
||||
fn new(separator:&'static str,f:F)->Self{
|
||||
Self{separator,f}
|
||||
}
|
||||
}
|
||||
impl<F,I,D> std::fmt::Display for Separated<F>
|
||||
where
|
||||
D:std::fmt::Display,
|
||||
I:IntoIterator<Item=D>,
|
||||
F:Fn()->I,
|
||||
{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
let mut it=(self.f)().into_iter();
|
||||
if let Some(first)=it.next(){
|
||||
write!(f,"{first}")?;
|
||||
for item in it{
|
||||
write!(f,"{}{item}",self.separator)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct Duplicates<D>{
|
||||
display:D,
|
||||
duplicates:usize,
|
||||
}
|
||||
impl<D> Duplicates<D>{
|
||||
fn new(display:D,duplicates:usize)->Self{
|
||||
Self{
|
||||
display,
|
||||
duplicates,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<D:std::fmt::Display> std::fmt::Display for Duplicates<D>{
|
||||
fn fmt(&self,f:&mut std::fmt::Formatter<'_>)->std::fmt::Result{
|
||||
write!(f,"{} ({} duplicates)",self.display,self.duplicates)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
macro_rules! passed{
|
||||
($name:literal)=>{
|
||||
Check{
|
||||
name:$name.to_owned(),
|
||||
summary:String::new(),
|
||||
passed:true,
|
||||
}
|
||||
}
|
||||
}
|
||||
macro_rules! summary{
|
||||
($name:literal,$summary:expr)=>{
|
||||
Check{
|
||||
name:$name.to_owned(),
|
||||
summary:$summary,
|
||||
passed:false,
|
||||
}
|
||||
};
|
||||
}
|
||||
macro_rules! summary_format{
|
||||
($name:literal,$fmt:literal)=>{
|
||||
Check{
|
||||
name:$name.to_owned(),
|
||||
summary:format!($fmt),
|
||||
passed:false,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Generate an error message for each observed issue separated by newlines.
|
||||
// This defines MapCheck.to_string() which is used in MapCheck.result()
|
||||
impl MapCheck<'_>{
|
||||
fn itemize(&self)->Result<MapCheckList,serde_json::Error>{
|
||||
let model_class=match &self.model_class{
|
||||
StringCheck(Ok(()))=>passed!("ModelClass"),
|
||||
StringCheck(Err(context))=>summary_format!("ModelClass","Invalid model class: {context}"),
|
||||
};
|
||||
let model_name=match &self.model_name{
|
||||
StringCheck(Ok(()))=>passed!("ModelName"),
|
||||
StringCheck(Err(context))=>summary_format!("ModelName","Model name must have snake_case: {context}"),
|
||||
};
|
||||
let display_name=match &self.display_name{
|
||||
Ok(Ok(StringCheck(Ok(_))))=>passed!("DisplayName"),
|
||||
Ok(Ok(StringCheck(Err(context))))=>summary_format!("DisplayName","DisplayName must have Title Case: {context}"),
|
||||
Ok(Err(context))=>summary_format!("DisplayName","Invalid DisplayName: {context}"),
|
||||
Err(StringValueError::ObjectNotFound)=>summary!("DisplayName","Missing DisplayName StringValue".to_owned()),
|
||||
Err(StringValueError::ValueNotSet)=>summary!("DisplayName","DisplayName Value not set".to_owned()),
|
||||
Err(StringValueError::NonStringValue)=>summary!("DisplayName","DisplayName Value is not a String".to_owned()),
|
||||
};
|
||||
let creator=match &self.creator{
|
||||
Ok(Ok(_))=>passed!("Creator"),
|
||||
Ok(Err(context))=>summary_format!("Creator","Invalid Creator: {context}"),
|
||||
Err(StringValueError::ObjectNotFound)=>summary!("Creator","Missing Creator StringValue".to_owned()),
|
||||
Err(StringValueError::ValueNotSet)=>summary!("Creator","Creator Value not set".to_owned()),
|
||||
Err(StringValueError::NonStringValue)=>summary!("Creator","Creator Value is not a String".to_owned()),
|
||||
};
|
||||
let game_id=match &self.game_id{
|
||||
Ok(_)=>passed!("GameID"),
|
||||
Err(ParseGameIDError)=>summary!("GameID","Model name must be prefixed with bhop_ surf_ or flytrials_".to_owned()),
|
||||
};
|
||||
let mapstart=match &self.mapstart{
|
||||
Ok(Exists)=>passed!("MapStart"),
|
||||
Err(Absent)=>summary_format!("MapStart","Model has no MapStart"),
|
||||
};
|
||||
let duplicate_start=match &self.mode_start_counts{
|
||||
DuplicateCheck(Ok(()))=>passed!("DuplicateStart"),
|
||||
DuplicateCheck(Err(DuplicateCheckContext(context)))=>{
|
||||
let context=Separated::new(", ",||context.iter().map(|(&mode_id,instances)|
|
||||
Duplicates::new(ModeElement{zone:Zone::Start,mode_id},instances.len())
|
||||
));
|
||||
summary_format!("DuplicateStart","Duplicate start zones: {context}")
|
||||
}
|
||||
};
|
||||
let (extra_finish,missing_finish)=match &self.mode_finish_counts{
|
||||
SetDifferenceCheck(Ok(()))=>(passed!("DanglingFinish"),passed!("MissingFinish")),
|
||||
SetDifferenceCheck(Err(context))=>(
|
||||
if context.extra.is_empty(){
|
||||
passed!("DanglingFinish")
|
||||
}else{
|
||||
let plural=if context.extra.len()==1{"zone"}else{"zones"};
|
||||
let context=Separated::new(", ",||context.extra.iter().map(|(&mode_id,_instances)|
|
||||
ModeElement{zone:Zone::Finish,mode_id}
|
||||
));
|
||||
summary_format!("DanglingFinish","No matching start zone for finish {plural}: {context}")
|
||||
},
|
||||
if context.missing.is_empty(){
|
||||
passed!("MissingFinish")
|
||||
}else{
|
||||
let plural=if context.missing.len()==1{"zone"}else{"zones"};
|
||||
let context=Separated::new(", ",||context.missing.iter().map(|&mode_id|
|
||||
ModeElement{zone:Zone::Finish,mode_id}
|
||||
));
|
||||
summary_format!("MissingFinish","Missing finish {plural}: {context}")
|
||||
}
|
||||
),
|
||||
};
|
||||
let dangling_anticheat=match &self.mode_anticheat_counts{
|
||||
SetDifferenceCheck(Ok(()))=>passed!("DanglingAnticheat"),
|
||||
SetDifferenceCheck(Err(context))=>{
|
||||
if context.extra.is_empty(){
|
||||
passed!("DanglingAnticheat")
|
||||
}else{
|
||||
let plural=if context.extra.len()==1{"zone"}else{"zones"};
|
||||
let context=Separated::new(", ",||context.extra.iter().map(|(&mode_id,_instances)|
|
||||
ModeElement{zone:Zone::Anticheat,mode_id}
|
||||
));
|
||||
summary_format!("DanglingAnticheat","No matching start zone for anticheat {plural}: {context}")
|
||||
}
|
||||
}
|
||||
};
|
||||
let spawn1=match &self.spawn1{
|
||||
Ok(Exists)=>passed!("Spawn1"),
|
||||
Err(Absent)=>summary_format!("Spawn1","Model has no Spawn1"),
|
||||
};
|
||||
let dangling_teleport=match &self.teleport_counts{
|
||||
SetDifferenceCheck(Ok(()))=>passed!("DanglingTeleport"),
|
||||
SetDifferenceCheck(Err(context))=>{
|
||||
let unique_names:HashSet<_>=context.extra.values().flat_map(|instances|
|
||||
instances.iter().map(|instance|instance.name.as_str())
|
||||
).collect();
|
||||
let plural=if unique_names.len()==1{"object"}else{"objects"};
|
||||
let context=Separated::new(", ",||&unique_names);
|
||||
summary_format!("DanglingTeleport","No matching Spawn for {plural}: {context}")
|
||||
}
|
||||
};
|
||||
let duplicate_spawns=match &self.spawn_counts{
|
||||
DuplicateCheck(Ok(()))=>passed!("DuplicateSpawn"),
|
||||
DuplicateCheck(Err(DuplicateCheckContext(context)))=>{
|
||||
let context=Separated::new(", ",||context.iter().map(|(&stage_id,&instances)|
|
||||
Duplicates::new(StageElement{behaviour:StageElementBehaviour::Spawn,stage_id},instances as usize)
|
||||
));
|
||||
summary_format!("DuplicateSpawn","Duplicate Spawn: {context}")
|
||||
}
|
||||
};
|
||||
let (extra_wormhole_in,missing_wormhole_in)=match &self.wormhole_in_counts{
|
||||
SetDifferenceCheck(Ok(()))=>(passed!("ExtraWormholeIn"),passed!("MissingWormholeIn")),
|
||||
SetDifferenceCheck(Err(context))=>(
|
||||
if context.extra.is_empty(){
|
||||
passed!("ExtraWormholeIn")
|
||||
}else{
|
||||
let context=Separated::new(", ",||context.extra.iter().map(|(&wormhole_id,_instances)|
|
||||
WormholeElement{behaviour:WormholeBehaviour::In,wormhole_id}
|
||||
));
|
||||
summary_format!("ExtraWormholeIn","WormholeIn with no matching WormholeOut: {context}")
|
||||
},
|
||||
if context.missing.is_empty(){
|
||||
passed!("MissingWormholeIn")
|
||||
}else{
|
||||
// This counts WormholeIn objects, but
|
||||
// flipped logic is easier to understand
|
||||
let context=Separated::new(", ",||context.missing.iter().map(|&wormhole_id|
|
||||
WormholeElement{behaviour:WormholeBehaviour::Out,wormhole_id}
|
||||
));
|
||||
summary_format!("MissingWormholeIn","WormholeOut with no matching WormholeIn: {context}")
|
||||
}
|
||||
)
|
||||
};
|
||||
let duplicate_wormhole_out=match &self.wormhole_out_counts{
|
||||
DuplicateCheck(Ok(()))=>passed!("DuplicateWormholeOut"),
|
||||
DuplicateCheck(Err(DuplicateCheckContext(context)))=>{
|
||||
let context=Separated::new(", ",||context.iter().map(|(&wormhole_id,&instances)|
|
||||
Duplicates::new(WormholeElement{behaviour:WormholeBehaviour::Out,wormhole_id},instances as usize)
|
||||
));
|
||||
summary_format!("DuplicateWormholeOut","Duplicate WormholeOut: {context}")
|
||||
}
|
||||
};
|
||||
let unanchored_parts=match &self.unanchored_parts{
|
||||
Ok(())=>passed!("UnanchoredParts"),
|
||||
Err(unanchored_parts)=>{
|
||||
let count=unanchored_parts.len();
|
||||
let plural=if count==1{"part"}else{"parts"};
|
||||
let context=Separated::new(", ",||unanchored_parts.iter().map(|&instance|
|
||||
instance.name.as_str()
|
||||
).take(20));
|
||||
summary_format!("UnanchoredParts","{count} unanchored {plural}: {context}")
|
||||
}
|
||||
};
|
||||
Ok(MapCheckList{checks:vec![
|
||||
model_class,
|
||||
model_name,
|
||||
display_name,
|
||||
creator,
|
||||
game_id,
|
||||
mapstart,
|
||||
duplicate_start,
|
||||
extra_finish,
|
||||
missing_finish,
|
||||
dangling_anticheat,
|
||||
spawn1,
|
||||
dangling_teleport,
|
||||
duplicate_spawns,
|
||||
extra_wormhole_in,
|
||||
missing_wormhole_in,
|
||||
duplicate_wormhole_out,
|
||||
unanchored_parts,
|
||||
]})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
pub struct MapCheckList{
|
||||
pub checks:Vec<Check>,
|
||||
}
|
||||
|
||||
pub struct CheckListAndVersion{
|
||||
pub status:Result<MapInfoOwned,MapCheckList>,
|
||||
pub version:u64,
|
||||
}
|
||||
|
||||
impl crate::message_handler::MessageHandler{
|
||||
pub async fn check_inner(&self,check_info:CheckRequest)->Result<CheckListAndVersion,Error>{
|
||||
// discover asset creator and latest version
|
||||
let info=self.cloud_context.get_asset_info(
|
||||
rbx_asset::cloud::GetAssetLatestRequest{asset_id:check_info.ModelID}
|
||||
).await.map_err(Error::ModelInfoDownload)?;
|
||||
|
||||
// reject models created by a group
|
||||
let rbx_asset::cloud::Creator::userId(_user_id)=info.creationContext.creator else{
|
||||
return Err(Error::CreatorTypeMustBeUser);
|
||||
};
|
||||
|
||||
// parse model version string
|
||||
let version=info.revisionId;
|
||||
|
||||
let maybe_gzip=download_asset_version(&self.cloud_context,rbx_asset::cloud::GetAssetVersionRequest{
|
||||
asset_id:check_info.ModelID,
|
||||
version,
|
||||
}).await.map_err(Error::Download)?;
|
||||
|
||||
// decode dom (slow!)
|
||||
let dom=maybe_gzip.read_with(read_dom,read_dom).map_err(Error::ModelFileDecode)?;
|
||||
|
||||
// extract the root instance
|
||||
let model_instance=get_root_instance(&dom).map_err(Error::GetRootInstance)?;
|
||||
|
||||
// skip checks
|
||||
if check_info.SkipChecks{
|
||||
// extract required fields
|
||||
let map_info=get_mapinfo(&dom,model_instance);
|
||||
let map_info_owned=map_info.try_into().map_err(Error::IntoMapInfoOwned)?;
|
||||
let status=Ok(map_info_owned);
|
||||
|
||||
// return early
|
||||
return Ok(CheckListAndVersion{status,version});
|
||||
}
|
||||
|
||||
// extract information from the model
|
||||
let model_info=get_model_info(&dom,model_instance);
|
||||
|
||||
// convert the model information into a structured report
|
||||
let map_check=model_info.check();
|
||||
|
||||
// check the report, generate an error message if it fails the check
|
||||
let status=match map_check.result(){
|
||||
Ok(map_info)=>Ok(map_info),
|
||||
Err(Ok(check_list))=>Err(check_list),
|
||||
Err(Err(e))=>return Err(Error::ToJsonValue(e)),
|
||||
};
|
||||
|
||||
Ok(CheckListAndVersion{status,version})
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user