Compare commits
No commits in common. "develop" and "main" have entirely different histories.
16
.app.config
16
.app.config
@ -1,16 +0,0 @@
|
||||
{
|
||||
"ID": "pricing",
|
||||
"Name": "pricing",
|
||||
"Address": "__IP__",
|
||||
"Tags": ["pricing-svc", "pricing", "https", "service"],
|
||||
"Port": 443,
|
||||
"Connect": {
|
||||
"Native": true
|
||||
},
|
||||
"Check": {
|
||||
"TCP": "__IP__:443",
|
||||
"Interval": "5s",
|
||||
"Timeout": "1s",
|
||||
"DeregisterCriticalServiceAfter": "10s"
|
||||
}
|
||||
}
|
13
.env.dist
13
.env.dist
@ -1,15 +1,4 @@
|
||||
SERVER_ADDR=:443
|
||||
|
||||
APP_NAME=pricing-svc
|
||||
APP_DOMAIN=pricing.service.ego.io
|
||||
REGISTRY_USE_DOMAIN_OVER_IP=false
|
||||
APP_PATH_PREFIX=/pricing
|
||||
APP_KV_NAMESPACE=dev.egommerce/service/pricing-svc
|
||||
|
||||
LOGGER_ADDR=api-logger:24224
|
||||
REGISTRY_ADDR=api-registry:8501
|
||||
SERVER_ADDR=:80
|
||||
DATABASE_URL=postgres://postgres:12345678@postgres-db:5432/egommerce
|
||||
CACHE_ADDR=api-cache:6379
|
||||
CACHE_PASSWORD=12345678
|
||||
MONGODB_URL=mongodb://mongodb:12345678@mongo-db:27017
|
||||
EVENTBUS_URL=amqp://guest:guest@api-eventbus:5672
|
6
.gitignore
vendored
6
.gitignore
vendored
@ -1,6 +0,0 @@
|
||||
.env
|
||||
.env.*
|
||||
!.env.dist
|
||||
|
||||
.vscode/
|
||||
__debug_bin
|
@ -5,7 +5,6 @@ ARG BIN_OUTPUT=/go/bin
|
||||
ARG GO_SERVER=cmd/server/main.go
|
||||
ARG GO_MIGRATE=cmd/migrate/main.go
|
||||
ARG GO_WORKER=cmd/worker/main.go
|
||||
ARG GO_HEALTH=cmd/health/main.go
|
||||
|
||||
WORKDIR /go/src/app
|
||||
COPY src ./
|
||||
@ -13,5 +12,4 @@ COPY src ./
|
||||
RUN export CGO_ENABLED=0 ; export GOOS=linux ; export GOARCH=amd64 && \
|
||||
go build -ldflags="-w -s" -o "$BIN_OUTPUT/server" $GO_SERVER && \
|
||||
go build -ldflags="-w -s" -o "$BIN_OUTPUT/migrate" $GO_MIGRATE && \
|
||||
go build -ldflags="-w -s" -o "$BIN_OUTPUT/worker" $GO_WORKER && \
|
||||
go build -ldflags="-w -s" -o "$BIN_OUTPUT/health" $GO_HEALTH
|
||||
go build -ldflags="-w -s" -o "$BIN_OUTPUT/worker" $GO_WORKER
|
||||
|
@ -19,18 +19,12 @@ LABEL dev.egommerce.image.build_time=${BUILD_TIME}
|
||||
|
||||
WORKDIR /
|
||||
COPY --from=builder $BIN_OUTPUT /app
|
||||
COPY --from=builder /go/bin/migrate /bin/migrate
|
||||
COPY --from=builder /go/bin/health /bin/health
|
||||
COPY .env.docker /.env
|
||||
COPY ./.app.config /
|
||||
COPY --from=builder /go/bin/migrate /bin/go_migrate
|
||||
COPY .env.dist /.env
|
||||
COPY ./bin /bin
|
||||
RUN chmod 755 /bin/entrypoint.sh /bin/migrate.sh
|
||||
|
||||
RUN apk add curl
|
||||
|
||||
EXPOSE 443
|
||||
EXPOSE 80
|
||||
|
||||
CMD ["/app"]
|
||||
ENTRYPOINT ["entrypoint.sh"]
|
||||
CMD ["sh", "-c", "/app"]
|
||||
|
||||
HEALTHCHECK --interval=5s --timeout=1s --retries=20 CMD health >/dev/null || exit 1
|
||||
|
173
LICENSE.md
173
LICENSE.md
@ -1,173 +0,0 @@
|
||||
# Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
|
||||
|
||||
Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
|
||||
|
||||
**Using Creative Commons Public Licenses**
|
||||
|
||||
Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
|
||||
|
||||
* __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors).
|
||||
|
||||
* __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees).
|
||||
|
||||
## Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License
|
||||
|
||||
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
|
||||
|
||||
### Section 1 – Definitions.
|
||||
|
||||
a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
|
||||
|
||||
b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
|
||||
|
||||
c. __BY-NC-SA Compatible License__ means a license listed at [creativecommons.org/compatiblelicenses](http://creativecommons.org/compatiblelicenses), approved by Creative Commons as essentially the equivalent of this Public License.
|
||||
|
||||
d. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
|
||||
|
||||
e. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
|
||||
|
||||
f. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
|
||||
|
||||
g. __License Elements__ means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike.
|
||||
|
||||
h. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
|
||||
|
||||
i. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
|
||||
|
||||
j. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
|
||||
|
||||
k. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
|
||||
|
||||
l. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
|
||||
|
||||
m. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
|
||||
|
||||
n. __You__ means the individual or entity exercising the Licensed Rights under this Public License. __Your__ has a corresponding meaning.
|
||||
|
||||
### Section 2 – Scope.
|
||||
|
||||
a. ___License grant.___
|
||||
|
||||
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
|
||||
|
||||
A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
|
||||
|
||||
B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
|
||||
|
||||
2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
|
||||
|
||||
3. __Term.__ The term of this Public License is specified in Section 6(a).
|
||||
|
||||
4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
|
||||
|
||||
5. __Downstream recipients.__
|
||||
|
||||
A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
|
||||
|
||||
B. __Additional offer from the Licensor – Adapted Material.__ Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply.
|
||||
|
||||
C. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
|
||||
|
||||
6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
|
||||
|
||||
b. ___Other rights.___
|
||||
|
||||
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
|
||||
|
||||
2. Patent and trademark rights are not licensed under this Public License.
|
||||
|
||||
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
|
||||
|
||||
### Section 3 – License Conditions.
|
||||
|
||||
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
|
||||
|
||||
a. ___Attribution.___
|
||||
|
||||
1. If You Share the Licensed Material (including in modified form), You must:
|
||||
|
||||
A. retain the following if it is supplied by the Licensor with the Licensed Material:
|
||||
|
||||
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
|
||||
|
||||
ii. a copyright notice;
|
||||
|
||||
iii. a notice that refers to this Public License;
|
||||
|
||||
iv. a notice that refers to the disclaimer of warranties;
|
||||
|
||||
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
|
||||
|
||||
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
|
||||
|
||||
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
|
||||
|
||||
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
|
||||
|
||||
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
|
||||
|
||||
b. ___ShareAlike.___
|
||||
|
||||
In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
|
||||
|
||||
1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License.
|
||||
|
||||
2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.
|
||||
|
||||
3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.
|
||||
|
||||
### Section 4 – Sui Generis Database Rights.
|
||||
|
||||
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
|
||||
|
||||
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;
|
||||
|
||||
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and
|
||||
|
||||
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
|
||||
|
||||
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
|
||||
|
||||
### Section 5 – Disclaimer of Warranties and Limitation of Liability.
|
||||
|
||||
a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__
|
||||
|
||||
b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__
|
||||
|
||||
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
|
||||
|
||||
### Section 6 – Term and Termination.
|
||||
|
||||
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
|
||||
|
||||
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
|
||||
|
||||
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
|
||||
|
||||
2. upon express reinstatement by the Licensor.
|
||||
|
||||
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
|
||||
|
||||
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
|
||||
|
||||
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
|
||||
|
||||
### Section 7 – Other Terms and Conditions.
|
||||
|
||||
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
|
||||
|
||||
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
|
||||
|
||||
### Section 8 – Interpretation.
|
||||
|
||||
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
|
||||
|
||||
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
|
||||
|
||||
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
|
||||
|
||||
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
|
||||
|
||||
> Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
|
||||
>
|
||||
> Creative Commons may be contacted at creativecommons.org
|
3
Makefile
3
Makefile
@ -8,9 +8,6 @@ build-image-dev:
|
||||
build-image-prod:
|
||||
- sh ${DEPLOY_DIR}/image-build.sh
|
||||
|
||||
push-image-dev:
|
||||
- sh ${DEPLOY_DIR}/image-push.sh dev
|
||||
|
||||
push-image-prod:
|
||||
- sh ${DEPLOY_DIR}/image-push.sh
|
||||
|
||||
|
@ -8,21 +8,16 @@ waitForService()
|
||||
while [ $status != 0 ]
|
||||
do
|
||||
echo "[x] wating for $1..."
|
||||
sleep 3
|
||||
sleep 1
|
||||
wait-for-it.sh $1 -t 2 1>/dev/null 2>&1
|
||||
status=$?
|
||||
done
|
||||
}
|
||||
|
||||
update-resolv # provided by stack - better approach - single copy
|
||||
update-ca-certificates
|
||||
|
||||
waitForService "postgres-db:5432"
|
||||
waitForService "api-eventbus:5672"
|
||||
waitForService "api-logger:24224"
|
||||
waitForService "api-registry:8501"
|
||||
waitForService "db-postgres:5432"
|
||||
|
||||
register-service
|
||||
waitForService "api-registry:8500"
|
||||
|
||||
# run migrations
|
||||
migrate.sh
|
||||
|
@ -1,17 +1,17 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
# ensure migrate env is initialized
|
||||
$(migrate version >/dev/null 2>&1)
|
||||
$(go_migrate version >/dev/null 2>&1)
|
||||
version=$?
|
||||
if [ $version != "0" ]
|
||||
then
|
||||
echo "Creating base table..."
|
||||
$(migrate init >/dev/null 2>&1)
|
||||
$(go_migrate init >/dev/null 2>&1)
|
||||
init=$?
|
||||
fi
|
||||
|
||||
# check again
|
||||
$(migrate version >/dev/null 2>&1)
|
||||
$(go_migrate version >/dev/null 2>&1)
|
||||
version=$?
|
||||
if [ $version != "0" ]
|
||||
then
|
||||
@ -20,6 +20,7 @@ then
|
||||
fi
|
||||
|
||||
# run migrations
|
||||
migrate up
|
||||
go_migrate up
|
||||
echo "Done."
|
||||
|
||||
exit $version
|
||||
|
@ -1,6 +1,4 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
# https://github.com/vishnubob/wait-for-it/blob/master/wait-for-it.sh
|
||||
# Use this script to test if a given TCP host/port are available
|
||||
|
||||
set -e
|
||||
|
@ -1,7 +1,7 @@
|
||||
#!/bin/sh
|
||||
# RUN IN REPO ROOT DIR !!
|
||||
|
||||
export IMAGE_PREFIX="git.pbiernat.io/egommerce/pricing"
|
||||
export IMAGE_PREFIX="git.pbiernat.dev/egommerce/pricing"
|
||||
export BUILDER_IMAGE="egommerce-builder:pricing"
|
||||
export BUILD_TIME=$(date +"%Y%m%d%H%M%S")
|
||||
export SERVER_IMAGE="$IMAGE_PREFIX-svc"
|
||||
|
@ -1,17 +1,13 @@
|
||||
#!/bin/sh
|
||||
# RUN IN REPO ROOT DIR !!
|
||||
|
||||
export IMAGE_BASE="git.pbiernat.io/egommerce/pricing"
|
||||
export IMAGE_BASE="git.pbiernat.dev/egommerce/pricing"
|
||||
export SERVER_IMAGE="$IMAGE_BASE-svc"
|
||||
export WORKER_IMAGE="$IMAGE_BASE-worker"
|
||||
|
||||
TARGET=${1:-latest}
|
||||
|
||||
echo $DOCKER_PASSWORD | docker login git.pbiernat.io -u $DOCKER_USERNAME --password-stdin
|
||||
echo $DOCKER_PASSWORD | docker login git.pbiernat.dev -u $DOCKER_USERNAME --password-stdin
|
||||
|
||||
docker push "$SERVER_IMAGE:$TARGET"
|
||||
docker push "$WORKER_IMAGE:$TARGET"
|
||||
|
||||
# Restart container
|
||||
curl -X POST http://127.0.0.1:9001/api/webhooks/1975af39-6f45-4da7-9fe0-f0783a6c42a8
|
||||
curl -X POST http://127.0.0.1:9001/api/webhooks/d473968f-e692-4ed7-b69b-008e35362007
|
||||
|
@ -1 +0,0 @@
|
||||
1750554
|
@ -1,39 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
const usageText = `This program runs healthcheck on the app.
|
||||
Usage:
|
||||
go run cmd/health/main.go
|
||||
`
|
||||
|
||||
func init() {
|
||||
flag.Usage = func() {
|
||||
fmt.Print(usageText)
|
||||
flag.PrintDefaults()
|
||||
os.Exit(2)
|
||||
}
|
||||
flag.Parse()
|
||||
}
|
||||
|
||||
func main() {
|
||||
var exitCode = 1
|
||||
if isOk := healthCheck(); isOk {
|
||||
exitCode = 0
|
||||
}
|
||||
os.Exit(exitCode)
|
||||
}
|
||||
|
||||
func healthCheck() bool {
|
||||
run, err := os.Open("./app.run")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer run.Close()
|
||||
|
||||
return true
|
||||
}
|
@ -6,20 +6,17 @@ import (
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"git.pbiernat.dev/egommerce/basket-service/internal/app/config"
|
||||
"git.pbiernat.dev/egommerce/go-api-pkg/fluentd"
|
||||
"github.com/go-pg/migrations/v8"
|
||||
"github.com/go-pg/pg/v10"
|
||||
|
||||
"git.pbiernat.io/egommerce/go-api-pkg/fluentd"
|
||||
|
||||
baseCnf "git.pbiernat.io/egommerce/go-api-pkg/config"
|
||||
cnf "git.pbiernat.io/egommerce/pricing-service/internal/server"
|
||||
)
|
||||
|
||||
const (
|
||||
defAppName = "pricing-svc-migrations"
|
||||
defMigrationsTableName = "pricing.migrations"
|
||||
defAppName = "basket-svc-migrations"
|
||||
defMigrationsTableName = "basket.migrations"
|
||||
defLoggerAddr = "api-logger:24224"
|
||||
// defKVNmspc = "dev.egommerce/service/pricing-migration"
|
||||
// defKVNmspc = "dev.egommerce/service/basket-migration"
|
||||
)
|
||||
|
||||
const usageText = `This program runs command on the db. Supported commands are:
|
||||
@ -35,44 +32,32 @@ Usage:
|
||||
`
|
||||
|
||||
func main() {
|
||||
flag.Usage = func() {
|
||||
fmt.Print(usageText)
|
||||
flag.PrintDefaults()
|
||||
os.Exit(2)
|
||||
}
|
||||
flag.Parse()
|
||||
|
||||
if baseCnf.ErrLoadingEnvs != nil {
|
||||
log.Panicln("Error loading .env file", baseCnf.ErrLoadingEnvs)
|
||||
if config.ErrLoadingEnvs != nil {
|
||||
log.Panicln("Error loading .env file", config.ErrLoadingEnvs)
|
||||
}
|
||||
|
||||
c := cnf.NewConfig("pricing-migrator")
|
||||
// dbURL := config.GetEnv("DATABASE_URL", defDbURL)
|
||||
loggerAddr := config.GetEnv("LOGGER_ADDR", defLoggerAddr)
|
||||
mTblName := config.GetEnv("MIGRATIONS_TABLE_NAME", defMigrationsTableName)
|
||||
|
||||
// dbURL := baseCnf.GetEnv("DATABASE_URL", defDbURL)
|
||||
|
||||
logHost, logPort, err := fluentd.ParseAddr(c.LoggerAddr)
|
||||
if err != nil {
|
||||
log.Fatalf("Error parsing logger addr: %s. Err: %v", c.LoggerAddr, err)
|
||||
}
|
||||
|
||||
logger, err := fluentd.NewLogger(c.GetAppFullName(), logHost, logPort) // @Refactor NewLogger return (logger, error)
|
||||
if err != nil {
|
||||
log.Fatalf("Error connecting to %s:%d. Err: %v", logHost, logPort, err)
|
||||
}
|
||||
logHost, logPort := fluentd.ParseAddr(loggerAddr)
|
||||
logger := fluentd.NewLogger(defAppName, logHost, logPort)
|
||||
defer logger.Close()
|
||||
|
||||
flag.Usage = usage
|
||||
flag.Parse()
|
||||
|
||||
db := pg.Connect(&pg.Options{ // FIXME
|
||||
Addr: "postgres-db:5432",
|
||||
User: "postgres",
|
||||
Password: "12345678",
|
||||
Database: "egommerce",
|
||||
})
|
||||
defer db.Close()
|
||||
|
||||
mTbl := baseCnf.GetEnv("MIGRATIONS_TABLE_NAME", defMigrationsTableName)
|
||||
mig := migrations.NewCollection()
|
||||
mig.SetTableName(mTbl)
|
||||
if err := mig.DiscoverSQLMigrations("./migrations"); err != nil {
|
||||
mig.SetTableName(mTblName)
|
||||
err := mig.DiscoverSQLMigrations("./migrations")
|
||||
if err != nil {
|
||||
logger.Log("migration dicovery error: %#v", err)
|
||||
}
|
||||
|
||||
@ -86,5 +71,10 @@ func main() {
|
||||
} else {
|
||||
logger.Log("version is %d\n", oldVersion)
|
||||
}
|
||||
// os.Exit(0)
|
||||
}
|
||||
|
||||
func usage() {
|
||||
fmt.Print(usageText)
|
||||
flag.PrintDefaults()
|
||||
os.Exit(2)
|
||||
}
|
||||
|
@ -1,41 +1,82 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
cnf "git.pbiernat.io/egommerce/go-api-pkg/config"
|
||||
"git.pbiernat.dev/egommerce/basket-service/internal/app/config"
|
||||
"git.pbiernat.dev/egommerce/basket-service/internal/app/database"
|
||||
"git.pbiernat.dev/egommerce/basket-service/internal/app/server"
|
||||
"git.pbiernat.dev/egommerce/go-api-pkg/fluentd"
|
||||
amqp "git.pbiernat.dev/egommerce/go-api-pkg/rabbitmq"
|
||||
)
|
||||
|
||||
"git.pbiernat.io/egommerce/pricing-service/internal/app"
|
||||
"git.pbiernat.io/egommerce/pricing-service/internal/server"
|
||||
const (
|
||||
defAppName = "basket-svc"
|
||||
defAppDomain = "basket-svc"
|
||||
defNetAddr = ":80"
|
||||
defLoggerAddr = "api-logger:24224"
|
||||
defRegistryAddr = "api-registry:8500"
|
||||
defDbURL = "postgres://postgres:12345678@postgres-db:5432/egommerce"
|
||||
defMongoDbURL = "mongodb://mongodb:12345678@mongo-db:27017"
|
||||
defEventBusURL = "amqp://guest:guest@api-eventbus:5672"
|
||||
ebEventsExchange = "api-events"
|
||||
ebEventsQueue = "basket-svc"
|
||||
defKVNmspc = "dev.egommerce/service/basket-svc"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if cnf.ErrLoadingEnvs != nil {
|
||||
log.Panicln("Error loading .env file", cnf.ErrLoadingEnvs)
|
||||
if config.ErrLoadingEnvs != nil {
|
||||
log.Panicln("Error loading .env file", config.ErrLoadingEnvs)
|
||||
}
|
||||
|
||||
c := server.NewConfig("pricing")
|
||||
cArr := c.GetArray()
|
||||
c := new(server.Config)
|
||||
c.AppID, _ = os.Hostname()
|
||||
c.AppName = config.GetEnv("APP_NAME", defAppName)
|
||||
c.AppDomain = config.GetEnv("APP_DOMAIN", defAppDomain)
|
||||
c.NetAddr = config.GetEnv("SERVER_ADDR", defNetAddr)
|
||||
c.Port, _ = strconv.Atoi(c.NetAddr[1:])
|
||||
c.LoggerAddr = config.GetEnv("LOGGER_ADDR", defLoggerAddr)
|
||||
c.RegistryAddr = config.GetEnv("REGISTRY_ADDR", defRegistryAddr)
|
||||
c.DbURL = config.GetEnv("DATABASE_URL", defDbURL)
|
||||
c.EventBusURL = config.GetEnv("EVENTBUS_URL", defEventBusURL)
|
||||
c.EventBusExchange = ebEventsExchange
|
||||
c.KVNamespace = config.GetEnv("APP_KV_NAMESPACE", defKVNmspc)
|
||||
|
||||
doer := server.New(c)
|
||||
a := app.NewApp(doer)
|
||||
a.RegisterPlugin(app.LoggerPlugin(cArr))
|
||||
a.RegisterPlugin(app.CachePlugin(cArr))
|
||||
a.RegisterPlugin(app.DatabasePlugin(cArr))
|
||||
a.RegisterPlugin(app.EventbusPlugin(cArr))
|
||||
// a.RegisterPlugin(app.RegistryPlugin(cArr))
|
||||
logHost, logPort := fluentd.ParseAddr(c.LoggerAddr)
|
||||
logger := fluentd.NewLogger(c.GetAppFullName(), logHost, logPort)
|
||||
defer logger.Close()
|
||||
|
||||
while := make(chan struct{})
|
||||
err := a.Start(while)
|
||||
<-while
|
||||
// db conn
|
||||
dbConn, err := database.Connect(c.DbURL)
|
||||
if err != nil { // fixme: add wait-for-db...
|
||||
logger.Log("Failed to connect to Database server: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer dbConn.Close()
|
||||
|
||||
// eventbus conn
|
||||
ebConn, ebCh, err := amqp.Open(c.EventBusURL)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to start server. Reason: %v\n", err)
|
||||
logger.Log("Failed to connect to EventBus server: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer ebCh.Close()
|
||||
defer amqp.Close(ebConn)
|
||||
|
||||
err = amqp.NewExchange(ebCh, c.EventBusExchange)
|
||||
if err != nil {
|
||||
logger.Log("Failed to declare EventBus exchange: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
fmt.Println("Gone")
|
||||
os.Exit(0)
|
||||
// start server
|
||||
srv := server.NewServer(c, logger, dbConn, ebCh)
|
||||
|
||||
forever := make(chan struct{})
|
||||
srv.StartWithGracefulShutdown(forever)
|
||||
<-forever
|
||||
|
||||
// os.Exit(1)
|
||||
}
|
||||
|
@ -1,40 +1,208 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
cnf "git.pbiernat.io/egommerce/go-api-pkg/config"
|
||||
"git.pbiernat.dev/egommerce/basket-service/internal/app/config"
|
||||
"git.pbiernat.dev/egommerce/basket-service/internal/app/database"
|
||||
def "git.pbiernat.dev/egommerce/basket-service/internal/app/definition"
|
||||
"git.pbiernat.dev/egommerce/basket-service/internal/app/event"
|
||||
"git.pbiernat.dev/egommerce/basket-service/internal/app/server"
|
||||
"git.pbiernat.dev/egommerce/basket-service/internal/app/service"
|
||||
discovery "git.pbiernat.dev/egommerce/go-api-pkg/consul"
|
||||
"git.pbiernat.dev/egommerce/go-api-pkg/fluentd"
|
||||
amqp "git.pbiernat.dev/egommerce/go-api-pkg/rabbitmq"
|
||||
)
|
||||
|
||||
"git.pbiernat.io/egommerce/pricing-service/internal/app"
|
||||
"git.pbiernat.io/egommerce/pricing-service/internal/worker"
|
||||
const (
|
||||
defAppName = "basket-worker"
|
||||
defLoggerAddr = "api-logger:24224"
|
||||
defRegistryAddr = "api-registry:8500"
|
||||
defDbURL = "postgres://postgres:12345678@postgres-db:5432/egommerce"
|
||||
defMongoDbURL = "mongodb://mongodb:12345678@mongo-db:27017"
|
||||
defEventBusURL = "amqp://guest:guest@api-eventbus:5672"
|
||||
ebEventsExchange = "api-events"
|
||||
ebEventsQueue = "basket-worker"
|
||||
defKVNmspc = "dev.egommerce/service/basket-worker"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if cnf.ErrLoadingEnvs != nil {
|
||||
log.Fatalln("Error loading .env file.")
|
||||
if config.ErrLoadingEnvs != nil {
|
||||
log.Panicln("Error loading .env file", config.ErrLoadingEnvs)
|
||||
}
|
||||
|
||||
c := worker.NewConfig("pricing-worker")
|
||||
cArr := c.GetArray()
|
||||
c := new(server.Config)
|
||||
c.AppID, _ = os.Hostname()
|
||||
c.AppName = config.GetEnv("APP_NAME", defAppName)
|
||||
c.LoggerAddr = config.GetEnv("LOGGER_ADDR", defLoggerAddr)
|
||||
c.RegistryAddr = config.GetEnv("REGISTRY_ADDR", defRegistryAddr)
|
||||
c.DbURL = config.GetEnv("DATABASE_URL", defDbURL)
|
||||
c.EventBusURL = config.GetEnv("EVENTBUS_URL", defEventBusURL)
|
||||
c.EventBusExchange = ebEventsExchange
|
||||
c.EventBusQueue = ebEventsQueue
|
||||
c.KVNamespace = config.GetEnv("APP_KV_NAMESPACE", defKVNmspc)
|
||||
|
||||
doer := worker.New(c)
|
||||
a := app.NewApp(doer)
|
||||
a.RegisterPlugin(app.LoggerPlugin(cArr))
|
||||
a.RegisterPlugin(app.CachePlugin(cArr))
|
||||
a.RegisterPlugin(app.DatabasePlugin(cArr))
|
||||
a.RegisterPlugin(app.EventbusPlugin(cArr))
|
||||
|
||||
while := make(chan struct{})
|
||||
err := a.Start(while)
|
||||
<-while
|
||||
logHost, logPort := fluentd.ParseAddr(c.LoggerAddr)
|
||||
logger := fluentd.NewLogger(c.GetAppFullName(), logHost, logPort)
|
||||
defer logger.Close()
|
||||
|
||||
consul, err := discovery.NewService(c.RegistryAddr, c.AppID, c.AppName, c.AppID, "", 0)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to start worker. Reason: %v\n", err)
|
||||
logger.Log("Error connecting to %s: %v", c.RegistryAddr, err)
|
||||
}
|
||||
|
||||
go func(consul *discovery.Service) {
|
||||
interval := time.Second * 3
|
||||
ticker := time.NewTicker(interval)
|
||||
for range ticker.C {
|
||||
updateKVConfig(consul, c) // FIXME: duplicated in internal/app/server/server.go
|
||||
}
|
||||
}(consul)
|
||||
|
||||
// db conn
|
||||
dbConn, err := database.Connect(c.DbURL)
|
||||
if err != nil { // fixme: add wait-for-db...
|
||||
logger.Log("Failed to connect to Database server: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer dbConn.Close()
|
||||
|
||||
// eventbus conn
|
||||
ebConn, ebCh, err := amqp.Open(c.EventBusURL)
|
||||
if err != nil {
|
||||
logger.Log("Failed to connect to EventBus server: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer ebCh.Close()
|
||||
defer amqp.Close(ebConn)
|
||||
|
||||
err = amqp.NewExchange(ebCh, c.EventBusExchange)
|
||||
if err != nil {
|
||||
logger.Log("Failed to declare EventBus exchange: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
fmt.Println("Gone")
|
||||
os.Exit(0)
|
||||
// create and bind queues
|
||||
_, err = ebCh.QueueDeclare(
|
||||
c.EventBusQueue, // name
|
||||
false, // durable
|
||||
false, // delete when unused
|
||||
false, // exclusive
|
||||
false, // no-wait
|
||||
nil, // arguments
|
||||
)
|
||||
if err != nil {
|
||||
logger.Log("Failed to declare EventBus queue: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
amqp.BindQueueToExchange(ebCh, c.EventBusQueue, c.EventBusExchange, "catalog.basket.productAddedToBasket")
|
||||
amqp.BindQueueToExchange(ebCh, c.EventBusQueue, c.EventBusExchange, "catalog.basket.productRemovedFromBasket")
|
||||
amqp.BindQueueToExchange(ebCh, c.EventBusQueue, c.EventBusExchange, "catalog.basket.updateQuantity")
|
||||
|
||||
// event consume
|
||||
msgs, err := ebCh.Consume(
|
||||
c.EventBusQueue, // queue
|
||||
"", // consumer
|
||||
false, // auto-ack
|
||||
false, // exclusive
|
||||
false, // no-local
|
||||
false, // no-wait
|
||||
nil, // args
|
||||
)
|
||||
if err != nil {
|
||||
logger.Log("Failed to register a consumer: %s", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
forever := make(chan struct{})
|
||||
go func() {
|
||||
sigint := make(chan os.Signal, 1)
|
||||
signal.Notify(sigint, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
|
||||
<-sigint
|
||||
|
||||
logger.Log("Worker %s stopped working...\n", c.GetAppFullName())
|
||||
|
||||
close(forever)
|
||||
}()
|
||||
|
||||
go func() {
|
||||
bSrvc := service.NewBasketService(dbConn, ebCh, logger)
|
||||
|
||||
for d := range msgs {
|
||||
msg, err := amqp.Deserialize(d.Body)
|
||||
if err != nil {
|
||||
logger.Log("json error: %v\n", err)
|
||||
d.Reject(false) // FIXME: how to handle erros in queue...????
|
||||
continue
|
||||
}
|
||||
|
||||
eName := fmt.Sprintf("%s", msg["event"])
|
||||
data := (msg["data"]).(map[string]interface{})
|
||||
logger.Log("Message<%s>: %s\n", eName, data)
|
||||
|
||||
basketID := data["basket_id"].(string) // FIXME Check input params!
|
||||
productID := data["product_id"].(string) // FIXME Check input params!
|
||||
|
||||
switch true {
|
||||
case strings.Contains(eName, event.EVENT_PRODUCT_ADDED_TO_BASKET):
|
||||
var basket *def.BasketModel
|
||||
basket, err := bSrvc.FetchFromDB(basketID)
|
||||
if err != nil {
|
||||
logger.Log("Basket#:%s not found. Creating...", basketID)
|
||||
basket, err = bSrvc.Create(basketID)
|
||||
if err != nil {
|
||||
logger.Log("Creating basket error: %v", err)
|
||||
d.Reject(false)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
err = bSrvc.AddProduct(productID, basketID, 1) // FIXME: change to Update quantity - which add or delete product to/from basket depends on new quantity
|
||||
if err != nil {
|
||||
logger.Log("Error adding product to basket: %v", err)
|
||||
d.Reject(false)
|
||||
}
|
||||
logger.Log("Fetched basket: %v", basket)
|
||||
|
||||
case strings.Contains(eName, event.EVENT_PRODUCT_REMOVED_FROM_BASKET):
|
||||
// remove product from basket
|
||||
logger.Log("Event: %s", event.EVENT_PRODUCT_REMOVED_FROM_BASKET)
|
||||
}
|
||||
|
||||
logger.Log("ACK: %s", eName)
|
||||
d.Ack(false)
|
||||
}
|
||||
}()
|
||||
|
||||
logger.Log("Waiting for messages...")
|
||||
<-forever
|
||||
}
|
||||
|
||||
func updateKVConfig(s *discovery.Service, oldCnf *server.Config) error { // FIXME: duplicated in internal/app/server/server.go
|
||||
data, _, err := s.KV().Get(oldCnf.KVNamespace, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if data == nil {
|
||||
return errors.New("empty KV config data")
|
||||
}
|
||||
|
||||
buf := bytes.NewBuffer(data.Value)
|
||||
decoder := json.NewDecoder(buf)
|
||||
if err := decoder.Decode(oldCnf); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
98
src/go.mod
98
src/go.mod
@ -1,116 +1,58 @@
|
||||
module git.pbiernat.io/egommerce/pricing-service
|
||||
module git.pbiernat.dev/egommerce/basket-service
|
||||
|
||||
go 1.18
|
||||
|
||||
require (
|
||||
git.pbiernat.io/egommerce/api-entities v0.2.3
|
||||
git.pbiernat.io/egommerce/go-api-pkg v0.3.24
|
||||
git.pbiernat.dev/egommerce/go-api-pkg v0.0.113
|
||||
github.com/georgysavva/scany/v2 v2.0.0
|
||||
github.com/go-pg/migrations/v8 v8.1.0
|
||||
github.com/go-pg/pg/v10 v10.10.7
|
||||
github.com/go-redis/redis/v8 v8.11.5
|
||||
github.com/gofiber/fiber/v2 v2.48.0
|
||||
github.com/gofiber/fiber/v2 v2.40.1
|
||||
github.com/jackc/pgtype v1.12.0
|
||||
github.com/jackc/pgx/v5 v5.1.1
|
||||
github.com/rabbitmq/amqp091-go v1.10.0
|
||||
github.com/joho/godotenv v1.4.0
|
||||
github.com/streadway/amqp v1.0.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/DataDog/datadog-go v3.2.0+incompatible // indirect
|
||||
github.com/andybalholm/brotli v1.0.5 // indirect
|
||||
github.com/andybalholm/brotli v1.0.4 // indirect
|
||||
github.com/armon/go-metrics v0.4.1 // indirect
|
||||
github.com/armon/go-radix v1.0.0 // indirect
|
||||
github.com/aws/aws-sdk-go v1.42.34 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/census-instrumentation/opencensus-proto v0.4.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||
github.com/circonus-labs/circonus-gometrics v2.3.1+incompatible // indirect
|
||||
github.com/circonus-labs/circonusllhist v0.1.3 // indirect
|
||||
github.com/cncf/xds/go v0.0.0-20230310173818-32f1caf87195 // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/envoyproxy/go-control-plane v0.11.0 // indirect
|
||||
github.com/envoyproxy/protoc-gen-validate v0.10.0 // indirect
|
||||
github.com/fatih/color v1.14.1 // indirect
|
||||
github.com/fatih/color v1.13.0 // indirect
|
||||
github.com/fluent/fluent-logger-golang v1.9.0 // indirect
|
||||
github.com/go-pg/zerochecker v0.2.0 // indirect
|
||||
github.com/golang/protobuf v1.5.3 // indirect
|
||||
github.com/google/btree v1.0.1 // indirect
|
||||
github.com/google/uuid v1.3.0 // indirect
|
||||
github.com/hashicorp/consul v1.16.0 // indirect
|
||||
github.com/hashicorp/consul-net-rpc v0.0.0-20221205195236-156cfab66a69 // indirect
|
||||
github.com/hashicorp/consul/api v1.22.0 // indirect
|
||||
github.com/hashicorp/consul/envoyextensions v0.3.0 // indirect
|
||||
github.com/hashicorp/consul/sdk v0.14.0 // indirect
|
||||
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||
github.com/hashicorp/go-bexpr v0.1.2 // indirect
|
||||
github.com/hashicorp/consul/api v1.18.0 // indirect
|
||||
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
|
||||
github.com/hashicorp/go-hclog v1.5.0 // indirect
|
||||
github.com/hashicorp/go-hclog v1.3.1 // indirect
|
||||
github.com/hashicorp/go-immutable-radix v1.3.1 // indirect
|
||||
github.com/hashicorp/go-msgpack v0.5.5 // indirect
|
||||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||
github.com/hashicorp/go-retryablehttp v0.6.7 // indirect
|
||||
github.com/hashicorp/go-rootcerts v1.0.2 // indirect
|
||||
github.com/hashicorp/go-sockaddr v1.0.2 // indirect
|
||||
github.com/hashicorp/go-syslog v1.0.0 // indirect
|
||||
github.com/hashicorp/go-uuid v1.0.3 // indirect
|
||||
github.com/hashicorp/go-version v1.2.1 // indirect
|
||||
github.com/hashicorp/golang-lru v0.5.4 // indirect
|
||||
github.com/hashicorp/hcl v1.0.0 // indirect
|
||||
github.com/hashicorp/memberlist v0.5.0 // indirect
|
||||
github.com/hashicorp/raft v1.5.0 // indirect
|
||||
github.com/hashicorp/raft-autopilot v0.1.6 // indirect
|
||||
github.com/hashicorp/serf v0.10.1 // indirect
|
||||
github.com/hashicorp/yamux v0.0.0-20211028200310-0bc27b27de87 // indirect
|
||||
github.com/jackc/pgio v1.0.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
||||
github.com/jackc/pgtype v1.14.3 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
|
||||
github.com/jackc/puddle/v2 v2.1.2 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/joho/godotenv v1.5.1 // indirect
|
||||
github.com/klauspost/compress v1.16.3 // indirect
|
||||
github.com/klauspost/compress v1.15.9 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.19 // indirect
|
||||
github.com/mattn/go-isatty v0.0.16 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.14 // indirect
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
|
||||
github.com/miekg/dns v1.1.41 // indirect
|
||||
github.com/mitchellh/copystructure v1.2.0 // indirect
|
||||
github.com/mitchellh/go-homedir v1.1.0 // indirect
|
||||
github.com/mitchellh/go-testing-interface v1.14.0 // indirect
|
||||
github.com/mitchellh/hashstructure v0.0.0-20170609045927-2bca23e0e452 // indirect
|
||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||
github.com/mitchellh/reflectwalk v1.0.2 // indirect
|
||||
github.com/philhofer/fwd v1.1.2 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||
github.com/prometheus/client_golang v1.14.0 // indirect
|
||||
github.com/prometheus/client_model v0.3.0 // indirect
|
||||
github.com/prometheus/common v0.37.0 // indirect
|
||||
github.com/prometheus/procfs v0.8.0 // indirect
|
||||
github.com/philhofer/fwd v1.1.1 // indirect
|
||||
github.com/rivo/uniseg v0.2.0 // indirect
|
||||
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 // indirect
|
||||
github.com/stretchr/objx v0.5.0 // indirect
|
||||
github.com/stretchr/testify v1.8.3 // indirect
|
||||
github.com/tinylib/msgp v1.1.8 // indirect
|
||||
github.com/tinylib/msgp v1.1.6 // indirect
|
||||
github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc // indirect
|
||||
github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasthttp v1.48.0 // indirect
|
||||
github.com/valyala/fasthttp v1.41.0 // indirect
|
||||
github.com/valyala/tcplisten v1.0.0 // indirect
|
||||
github.com/vmihailenco/bufpool v0.1.11 // indirect
|
||||
github.com/vmihailenco/msgpack/v5 v5.3.4 // indirect
|
||||
github.com/vmihailenco/tagparser v0.1.2 // indirect
|
||||
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
|
||||
go.uber.org/atomic v1.10.0 // indirect
|
||||
golang.org/x/crypto v0.20.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20230321023759-10a507213a29 // indirect
|
||||
golang.org/x/net v0.21.0 // indirect
|
||||
golang.org/x/sync v0.2.0 // indirect
|
||||
golang.org/x/sys v0.17.0 // indirect
|
||||
golang.org/x/text v0.14.0 // indirect
|
||||
golang.org/x/time v0.3.0 // indirect
|
||||
google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 // indirect
|
||||
google.golang.org/protobuf v1.30.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90 // indirect
|
||||
golang.org/x/sync v0.0.0-20220923202941-7f9b1623fab7 // indirect
|
||||
golang.org/x/sys v0.2.0 // indirect
|
||||
golang.org/x/text v0.3.8 // indirect
|
||||
mellium.im/sasl v0.2.1 // indirect
|
||||
)
|
||||
|
710
src/go.sum
710
src/go.sum
File diff suppressed because it is too large
Load Diff
@ -1,81 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
type (
|
||||
Doer interface {
|
||||
Start() error
|
||||
RegisterHandler(string, func() any)
|
||||
OnShutdown()
|
||||
}
|
||||
Application interface {
|
||||
Start(while chan struct{})
|
||||
RegisterPlugin(PluginFn) error
|
||||
Shutdown()
|
||||
}
|
||||
|
||||
App struct {
|
||||
doer Doer
|
||||
}
|
||||
)
|
||||
|
||||
func NewApp(d Doer) *App {
|
||||
return &App{
|
||||
doer: d,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) Start(while chan struct{}) error {
|
||||
go func() {
|
||||
sigint := make(chan os.Signal, 1)
|
||||
signal.Notify(sigint, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
|
||||
<-sigint
|
||||
|
||||
a.Shutdown()
|
||||
|
||||
close(while)
|
||||
}()
|
||||
|
||||
run := a.createRunFile("./app.run") // FIXME path...
|
||||
defer a.removeRunFile(run)
|
||||
|
||||
err := a.doer.Start()
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to start app. Reason: %v\n", err)
|
||||
close(while)
|
||||
}
|
||||
<-while
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (a *App) RegisterPlugin(p Plugin) error {
|
||||
a.doer.RegisterHandler(p.name, p.fn)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) Shutdown() {
|
||||
a.doer.OnShutdown()
|
||||
}
|
||||
|
||||
func (a *App) createRunFile(path string) *os.File {
|
||||
run, err := os.Create(path)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to create run file. Reason: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
run.WriteString(strconv.Itoa(os.Getpid()))
|
||||
|
||||
return run
|
||||
}
|
||||
|
||||
func (a *App) removeRunFile(f *os.File) error {
|
||||
return f.Close()
|
||||
}
|
22
src/internal/app/config/env.go
Normal file
22
src/internal/app/config/env.go
Normal file
@ -0,0 +1,22 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
)
|
||||
|
||||
var ErrLoadingEnvs error
|
||||
|
||||
func init() {
|
||||
ErrLoadingEnvs = godotenv.Load()
|
||||
}
|
||||
|
||||
func GetEnv(name string, defVal string) string { // FIXME defVal and return types
|
||||
env := os.Getenv(name)
|
||||
if env == "" {
|
||||
return defVal
|
||||
}
|
||||
|
||||
return env
|
||||
}
|
9
src/internal/app/definition/basket_http.go
Normal file
9
src/internal/app/definition/basket_http.go
Normal file
@ -0,0 +1,9 @@
|
||||
package definition
|
||||
|
||||
type BasketCheckoutRequest struct {
|
||||
BasketID string `json:"basket_id"`
|
||||
}
|
||||
|
||||
type BasketCheckoutResponse struct {
|
||||
ID string `json:"order_id"`
|
||||
}
|
11
src/internal/app/definition/basket_model.go
Normal file
11
src/internal/app/definition/basket_model.go
Normal file
@ -0,0 +1,11 @@
|
||||
package definition
|
||||
|
||||
import (
|
||||
"github.com/jackc/pgtype"
|
||||
)
|
||||
|
||||
type BasketModel struct {
|
||||
ID string `db:"id"`
|
||||
CreatedAt pgtype.Timestamp `db:"created_at"`
|
||||
UpdatedAt pgtype.Timestamp `db:"updated_at"`
|
||||
}
|
9
src/internal/app/definition/error.go
Normal file
9
src/internal/app/definition/error.go
Normal file
@ -0,0 +1,9 @@
|
||||
package definition
|
||||
|
||||
type ErrorResponse struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
func Error(err string) *ErrorResponse {
|
||||
return &ErrorResponse{err}
|
||||
}
|
5
src/internal/app/definition/health_http.go
Normal file
5
src/internal/app/definition/health_http.go
Normal file
@ -0,0 +1,5 @@
|
||||
package definition
|
||||
|
||||
type HealthResponse struct {
|
||||
Status string `json:"status,omitempty"`
|
||||
}
|
@ -1,13 +1,11 @@
|
||||
package event
|
||||
|
||||
type Event struct {
|
||||
Command string `json:"command"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
func NewEvent(command, reqID string) *Event {
|
||||
func NewEvent(reqID string) *Event {
|
||||
em := new(Event)
|
||||
em.Command = command
|
||||
em.RequestID = reqID
|
||||
|
||||
return em
|
@ -4,7 +4,7 @@ import (
|
||||
"log"
|
||||
)
|
||||
|
||||
const AppName = "pricing-svc"
|
||||
const AppName = "basket-svc"
|
||||
|
||||
func Panic(v ...any) {
|
||||
log.Panicln(AppName+":", v)
|
@ -1,139 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
|
||||
redis "github.com/go-redis/redis/v8"
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
|
||||
"git.pbiernat.io/egommerce/go-api-pkg/consul"
|
||||
"git.pbiernat.io/egommerce/go-api-pkg/fluentd"
|
||||
|
||||
db "git.pbiernat.io/egommerce/pricing-service/pkg/database"
|
||||
)
|
||||
|
||||
type (
|
||||
Plugin struct {
|
||||
name string
|
||||
fn PluginFn
|
||||
}
|
||||
PluginFn func() any
|
||||
)
|
||||
|
||||
func CachePlugin(cArr map[string]string) Plugin {
|
||||
return Plugin{
|
||||
name: "cache",
|
||||
fn: func() any {
|
||||
return redis.NewClient(&redis.Options{
|
||||
Addr: cArr["cacheAddr"],
|
||||
Password: cArr["cachePassword"],
|
||||
DB: 0,
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func DatabasePlugin(cArr map[string]string) Plugin {
|
||||
return Plugin{
|
||||
name: "database",
|
||||
fn: func() any {
|
||||
dbConn, err := db.Connect(cArr["dbURL"])
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to connect to the Database: %s. Err: %v\n", cArr["dbURL"], err)
|
||||
os.Exit(1) // TODO: retry in background...
|
||||
}
|
||||
|
||||
return dbConn
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func EventbusPlugin(cArr map[string]string) Plugin {
|
||||
return Plugin{
|
||||
name: "eventbus",
|
||||
fn: func() any {
|
||||
conn, err := amqp.Dial(cArr["eventBusURL"])
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to connect to the EventBus: %s. Err: %v\n", cArr["eventBusURL"], err)
|
||||
os.Exit(1) // TODO: retry in background...
|
||||
}
|
||||
|
||||
chn, err := conn.Channel()
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to open new EventBus channel. Err: %v\n", err)
|
||||
os.Exit(1) // TODO: retry in background...
|
||||
}
|
||||
|
||||
return chn
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func LoggerPlugin(cArr map[string]string) Plugin {
|
||||
return Plugin{
|
||||
name: "logger",
|
||||
fn: func() any {
|
||||
logHost, logPort, err := fluentd.ParseAddr(cArr["loggerAddr"])
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to parse FluentD address: %s. Err: %v", cArr["loggerAddr"], err)
|
||||
os.Exit(1) // TODO: retry in background...
|
||||
}
|
||||
|
||||
logger, err := fluentd.NewLogger(cArr["appFullname"], logHost, logPort)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to connect to the FluentD on %s:%d. Err: %v", logHost, logPort, err)
|
||||
os.Exit(1) // TODO: retry in background...
|
||||
}
|
||||
|
||||
return logger
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func RegistryPlugin(cArr map[string]string) Plugin {
|
||||
return Plugin{
|
||||
name: "registry",
|
||||
fn: func() any {
|
||||
port, _ := strconv.Atoi(cArr["netAddr"][1:]) // FIXME: can be IP:PORT or :PORT
|
||||
// log.Printf("Consul retrieved port: %v", port)
|
||||
registry, err := consul.NewService(cArr["registryAddr"], cArr["id"], cArr["name"], cArr["registryDomainOverIP"], cArr["ip"], cArr["domain"], cArr["pathPrefix"], port)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to connect to the Consul on: %s. Err: %v", cArr["registryAddr"], err)
|
||||
os.Exit(1) // TODO: retry in background...
|
||||
}
|
||||
|
||||
err = registry.Register()
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to register in the Consul service. Err: %v", err)
|
||||
os.Exit(1) // TODO: retry in background...
|
||||
}
|
||||
|
||||
registry.RegisterHealthChecks()
|
||||
// a.registerKVUpdater() // FIXME run as goroutine
|
||||
|
||||
return registry
|
||||
|
||||
// svc, _ := registry.Connect()
|
||||
// tlsCnf := svc.ServerTLSConfig()
|
||||
// s.Base.App.Server().TLSConfig = tlsCnf
|
||||
// fmt.Println("Podmiana configa TLS")
|
||||
// defer svc.Close()
|
||||
|
||||
// go func() { // Consul KV updater
|
||||
// ticker := time.NewTicker(time.Second * 15)
|
||||
// for range ticker.C {
|
||||
// fetchKVConfig(s) // FIXME: duplicated in worker
|
||||
// }
|
||||
// }()
|
||||
|
||||
// go func() { // Server metadata cache updater
|
||||
// ticker := time.NewTicker(time.Second * 5)
|
||||
// for range ticker.C {
|
||||
// s.cacheMetadata()
|
||||
// }
|
||||
// }()
|
||||
},
|
||||
}
|
||||
}
|
24
src/internal/app/server/basket_handler.go
Normal file
24
src/internal/app/server/basket_handler.go
Normal file
@ -0,0 +1,24 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
def "git.pbiernat.dev/egommerce/basket-service/internal/app/definition"
|
||||
"git.pbiernat.dev/egommerce/basket-service/internal/app/service"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func (s *Server) CheckoutHandler(c *fiber.Ctx) error {
|
||||
reqID, _ := s.GetRequestID(c)
|
||||
data := new(def.BasketCheckoutRequest)
|
||||
if err := c.BodyParser(data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
basketID := data.BasketID
|
||||
// vlaidate, pre check... etc
|
||||
basket := service.NewBasketService(s.db, s.ebCh, s.log)
|
||||
basket.Checkout(reqID, basketID)
|
||||
|
||||
return c.JSON(&def.BasketCheckoutResponse{
|
||||
ID: data.BasketID,
|
||||
})
|
||||
}
|
28
src/internal/app/server/config.go
Normal file
28
src/internal/app/server/config.go
Normal file
@ -0,0 +1,28 @@
|
||||
package server
|
||||
|
||||
import "fmt"
|
||||
|
||||
type Config struct {
|
||||
AppID string
|
||||
AppName string
|
||||
AppDomain string
|
||||
NetAddr string
|
||||
Port int
|
||||
RegistryAddr string
|
||||
KVNamespace string
|
||||
|
||||
LoggerAddr string `json:"logger_addr"`
|
||||
DbURL string `json:"db_url"`
|
||||
MongoDbUrl string `json:"mongodb_url"`
|
||||
EventBusURL string `json:"eventbus_url"`
|
||||
EventBusExchange string `json:"eventbus_exchange"`
|
||||
EventBusQueue string `json:"eventbus_queue"`
|
||||
HttpReadTimeout int `json:"http_read_timeout"`
|
||||
HttpWriteTimeout int `json:"http_write_timeout"`
|
||||
HttpIdleTimeout int `json:"http_idle_timeout"`
|
||||
// Fields with json mapping are available trough ConsulKV
|
||||
}
|
||||
|
||||
func (c *Config) GetAppFullName() string {
|
||||
return fmt.Sprintf("%s_%s", c.AppName, c.AppID)
|
||||
}
|
@ -1,9 +1,9 @@
|
||||
package server
|
||||
|
||||
// REFACTOR: UNIVERSAL SERVER CODE
|
||||
import (
|
||||
def "git.pbiernat.io/egommerce/api-entities/http"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
def "git.pbiernat.dev/egommerce/basket-service/internal/app/definition"
|
||||
)
|
||||
|
||||
func (s *Server) HealthHandler(c *fiber.Ctx) error {
|
||||
@ -11,3 +11,7 @@ func (s *Server) HealthHandler(c *fiber.Ctx) error {
|
||||
Status: "OK",
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) ConfigHandler(c *fiber.Ctx) error {
|
||||
return c.JSON(s.conf)
|
||||
}
|
38
src/internal/app/server/router.go
Normal file
38
src/internal/app/server/router.go
Normal file
@ -0,0 +1,38 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"git.pbiernat.dev/egommerce/go-api-pkg/fluentd"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func SetupRoutes(s *Server) {
|
||||
s.App.Get("/health", s.HealthHandler)
|
||||
s.App.Get("/config", s.ConfigHandler)
|
||||
|
||||
api := s.App.Group("/api")
|
||||
v1 := api.Group("/v1")
|
||||
v1.Post("/checkout", s.CheckoutHandler)
|
||||
}
|
||||
|
||||
func SetupMiddlewares(s *Server) {
|
||||
s.App.Use(LoggingMiddleware(s.log))
|
||||
}
|
||||
|
||||
// Middlewares
|
||||
func LoggingMiddleware(log *fluentd.Logger) func(c *fiber.Ctx) error {
|
||||
return func(c *fiber.Ctx) error {
|
||||
path := string(c.Request().URI().Path())
|
||||
if strings.Contains(path, "/health") {
|
||||
return c.Next()
|
||||
}
|
||||
|
||||
log.Log("Request: %s, remote: %s, via: %s",
|
||||
c.Request().URI().String(),
|
||||
c.Context().RemoteIP().String(),
|
||||
string(c.Context().UserAgent()))
|
||||
|
||||
return c.Next()
|
||||
}
|
||||
}
|
148
src/internal/app/server/server.go
Normal file
148
src/internal/app/server/server.go
Normal file
@ -0,0 +1,148 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/streadway/amqp"
|
||||
|
||||
discovery "git.pbiernat.dev/egommerce/go-api-pkg/consul"
|
||||
"git.pbiernat.dev/egommerce/go-api-pkg/fluentd"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
*fiber.App
|
||||
conf *Config
|
||||
log *fluentd.Logger
|
||||
db *pgxpool.Pool
|
||||
ebCh *amqp.Channel
|
||||
discovery *discovery.Service
|
||||
name string
|
||||
addr string
|
||||
kvNmspc string
|
||||
}
|
||||
|
||||
type Headers struct {
|
||||
RequestID string `reqHeader:"x-request-id"`
|
||||
}
|
||||
|
||||
func NewServer(conf *Config, logger *fluentd.Logger, db *pgxpool.Pool, ebCh *amqp.Channel) *Server {
|
||||
logger.Log("API_ID: %s", conf.AppID)
|
||||
consul, err := discovery.NewService(conf.RegistryAddr, conf.AppID, conf.AppName, conf.AppID, conf.AppDomain, conf.Port)
|
||||
if err != nil {
|
||||
logger.Log("Error connecting to %s: %v", conf.RegistryAddr, err)
|
||||
}
|
||||
|
||||
logger.Log("Registering service with name: %s, address: %s", consul.Name, consul.Address)
|
||||
err = consul.Register()
|
||||
if err != nil {
|
||||
logger.Log("register error: %v", err)
|
||||
}
|
||||
|
||||
cnf := fiber.Config{
|
||||
AppName: conf.AppName,
|
||||
ServerHeader: conf.AppName,
|
||||
ReadTimeout: time.Millisecond * 50,
|
||||
WriteTimeout: time.Millisecond * 50,
|
||||
IdleTimeout: time.Millisecond * 50,
|
||||
}
|
||||
s := &Server{
|
||||
fiber.New(cnf),
|
||||
conf,
|
||||
logger,
|
||||
db,
|
||||
ebCh,
|
||||
consul,
|
||||
conf.AppName,
|
||||
conf.NetAddr,
|
||||
conf.KVNamespace,
|
||||
}
|
||||
|
||||
go func(s *Server) { // Consul KV config updater
|
||||
interval := time.Second * 30
|
||||
ticker := time.NewTicker(interval)
|
||||
for range ticker.C {
|
||||
s.updateKVConfig()
|
||||
}
|
||||
}(s)
|
||||
|
||||
SetupMiddlewares(s)
|
||||
SetupRoutes(s)
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Server) Start() {
|
||||
err := s.Listen(s.addr)
|
||||
s.log.Log("Starting error: %v", err)
|
||||
}
|
||||
|
||||
func (s *Server) StartWithGracefulShutdown(forever chan struct{}) {
|
||||
go func() {
|
||||
sigint := make(chan os.Signal, 1)
|
||||
signal.Notify(sigint, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
|
||||
<-sigint
|
||||
|
||||
if err := s.gracefulShutdown(); err != nil {
|
||||
s.log.Log("Server is not shutting down! Reason: %v", err)
|
||||
}
|
||||
|
||||
close(forever)
|
||||
}()
|
||||
|
||||
if err := s.Listen(s.addr); err != nil {
|
||||
s.log.Log("Server is not running! Reason: %v", err)
|
||||
}
|
||||
|
||||
<-forever
|
||||
}
|
||||
|
||||
func (s *Server) GetRequestID(c *fiber.Ctx) (string, error) {
|
||||
var hdr = new(Headers)
|
||||
if err := c.ReqHeaderParser(hdr); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return hdr.RequestID, nil
|
||||
}
|
||||
|
||||
func (s *Server) updateKVConfig() error { // FIXME: duplicated in cmd/worker/main.go
|
||||
config, _, err := s.discovery.KV().Get(s.kvNmspc, nil)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
if config == nil {
|
||||
return errors.New("empty KV config data")
|
||||
}
|
||||
|
||||
kvCnf := bytes.NewBuffer(config.Value)
|
||||
decoder := json.NewDecoder(kvCnf)
|
||||
if err := decoder.Decode(&s.conf); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) gracefulShutdown() error {
|
||||
s.log.Log("Server is going down...")
|
||||
s.log.Log("Unregistering service: %s", s.discovery.GetID())
|
||||
s.discovery.Unregister()
|
||||
|
||||
s.ebCh.Close()
|
||||
s.db.Close()
|
||||
s.log.Close()
|
||||
|
||||
return s.Shutdown()
|
||||
}
|
70
src/internal/app/service/basket.go
Normal file
70
src/internal/app/service/basket.go
Normal file
@ -0,0 +1,70 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
def "git.pbiernat.dev/egommerce/basket-service/internal/app/definition"
|
||||
"git.pbiernat.dev/egommerce/basket-service/internal/app/event"
|
||||
"git.pbiernat.dev/egommerce/go-api-pkg/fluentd"
|
||||
amqp "git.pbiernat.dev/egommerce/go-api-pkg/rabbitmq"
|
||||
"github.com/georgysavva/scany/v2/pgxscan"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
base "github.com/streadway/amqp"
|
||||
)
|
||||
|
||||
type BasketService struct {
|
||||
dbConn *pgxpool.Pool
|
||||
ebCh *base.Channel
|
||||
log *fluentd.Logger
|
||||
}
|
||||
|
||||
func NewBasketService(dbConn *pgxpool.Pool, chn *base.Channel, log *fluentd.Logger) *BasketService {
|
||||
return &BasketService{dbConn, chn, log}
|
||||
}
|
||||
|
||||
func (s *BasketService) Create(basketID string) (*def.BasketModel, error) {
|
||||
ctx := context.Background()
|
||||
|
||||
sql := `INSERT INTO basket.basket(id) VALUES($1)`
|
||||
if _, err := s.dbConn.Exec(ctx, sql, basketID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &def.BasketModel{ID: basketID}, nil // FIXME
|
||||
}
|
||||
|
||||
func (s *BasketService) FetchFromDB(basketID string) (*def.BasketModel, error) {
|
||||
ctx := context.Background()
|
||||
|
||||
basket := new(def.BasketModel)
|
||||
err := pgxscan.Get(ctx, s.dbConn, basket, `SELECT id, created_at, updated_at FROM basket.basket WHERE id=$1`, basketID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return basket, nil
|
||||
}
|
||||
|
||||
func (s *BasketService) AddProduct(productId, basketID string, qty int) error {
|
||||
ctx := context.Background()
|
||||
s.log.Log("Adding product#:%s into Basket#:%s", productId, basketID)
|
||||
|
||||
sql := `INSERT INTO basket.basket_item(basket_id, product_id) VALUES($1,$2)`
|
||||
if _, err := s.dbConn.Exec(ctx, sql, basketID, productId); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// msg := &event.ProductAddedToBasketEvent{}
|
||||
// amqp.Publish(s.ebCh, "api-events", "basket.pricing.", msg)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *BasketService) Checkout(reqID, basketID string) (string, error) {
|
||||
s.log.Log("Creating initial order from basket#:%s", basketID)
|
||||
|
||||
msg := &event.BasketCheckoutEvent{Event: event.NewEvent(reqID), BasketID: basketID}
|
||||
amqp.Publish(s.ebCh, "api-events", "basket.order.basketCheckout", msg)
|
||||
|
||||
return basketID, nil
|
||||
}
|
@ -1,111 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
cnf "git.pbiernat.io/egommerce/go-api-pkg/config"
|
||||
)
|
||||
|
||||
const (
|
||||
defName = "pricing-svc"
|
||||
defDomain = "pricing-svc"
|
||||
defCacheAddr = "egommerce.local:6379"
|
||||
defCachePassword = "12345678"
|
||||
defDbURL = "postgres://postgres:12345678@db-postgres:5432/egommerce"
|
||||
defEventBusURL = "amqp://guest:guest@api-eventbus:5672"
|
||||
defKVNmspc = "dev.egommerce/service/pricing"
|
||||
defLoggerAddr = "api-logger:24224"
|
||||
defNetAddr = ":443"
|
||||
defMongoDbURL = "mongodb://mongodb:12345678@mongo-db:27017"
|
||||
defPathPrefix = "/pricing"
|
||||
defRegistryAddr = "api-registry:8501"
|
||||
defEbEventsExchange = "api-events"
|
||||
defEbEventsQueue = "pricing-svc"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
ID string
|
||||
Name string
|
||||
Domain string
|
||||
NetAddr string
|
||||
RegistryDomainOverIP string
|
||||
PathPrefix string
|
||||
|
||||
IdleTimeout time.Duration // miliseconds
|
||||
ReadTimeout time.Duration // miliseconds
|
||||
WriteTimeout time.Duration // miliseconds
|
||||
|
||||
LoggerAddr string `json:"logger_addr"`
|
||||
DbURL string `json:"db_url"`
|
||||
CacheAddr string `json:"cache_addr"`
|
||||
CachePassword string `json:"cache_password"`
|
||||
MongoDbUrl string `json:"mongodb_url"`
|
||||
EventBusURL string `json:"eventbus_url"`
|
||||
EventBusExchange string `json:"eventbus_exchange"`
|
||||
EventBusQueue string `json:"eventbus_queue"`
|
||||
KVNamespace string
|
||||
RegistryAddr string
|
||||
|
||||
// Fields with JSON mappings are available through Consul KV storage
|
||||
}
|
||||
|
||||
func NewConfig(name string) *Config {
|
||||
c := new(Config)
|
||||
|
||||
c.ID, _ = os.Hostname()
|
||||
c.Name = name
|
||||
c.Domain = cnf.GetEnv("APP_DOMAIN", defDomain)
|
||||
c.NetAddr = cnf.GetEnv("SERVER_ADDR", defNetAddr)
|
||||
c.RegistryDomainOverIP = cnf.GetEnv("REGISTRY_USE_DOMAIN_OVER_IP", "false")
|
||||
c.PathPrefix = cnf.GetEnv("APP_PATH_PREFIX", defPathPrefix)
|
||||
|
||||
c.CacheAddr = cnf.GetEnv("CACHE_ADDR", defCacheAddr)
|
||||
c.CachePassword = cnf.GetEnv("CACHE_PASSWORD", defCachePassword)
|
||||
c.DbURL = cnf.GetEnv("DATABASE_URL", defDbURL)
|
||||
c.EventBusExchange = defEbEventsExchange
|
||||
c.EventBusURL = cnf.GetEnv("EVENTBUS_URL", defEventBusURL)
|
||||
c.KVNamespace = cnf.GetEnv("APP_KV_NAMESPACE", defKVNmspc)
|
||||
c.LoggerAddr = cnf.GetEnv("LOGGER_ADDR", defLoggerAddr)
|
||||
c.RegistryAddr = cnf.GetEnv("REGISTRY_ADDR", defRegistryAddr)
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *Config) GetAppFullName() string {
|
||||
return fmt.Sprintf("%s_%s", c.Name, c.ID)
|
||||
}
|
||||
|
||||
func (c *Config) GetIP() string {
|
||||
host, _ := os.Hostname()
|
||||
ips, _ := net.LookupIP(host)
|
||||
// for _, ip := range ips {
|
||||
// return ip.String()
|
||||
// }
|
||||
|
||||
return ips[0].String()
|
||||
}
|
||||
|
||||
func (c *Config) GetArray() map[string]string { // FIXME fix types etc
|
||||
arr := make(map[string]string)
|
||||
arr["id"] = c.ID
|
||||
arr["name"] = c.Name
|
||||
arr["appFullname"] = c.GetAppFullName()
|
||||
arr["domain"] = c.Domain
|
||||
arr["ip"] = c.GetIP()
|
||||
arr["netAddr"] = c.NetAddr
|
||||
arr["registryDomainOverIP"] = c.RegistryDomainOverIP
|
||||
arr["pathPrefix"] = c.PathPrefix
|
||||
arr["cacheAddr"] = c.CacheAddr
|
||||
arr["cachePassword"] = c.CachePassword
|
||||
arr["dbURL"] = c.DbURL
|
||||
arr["eventBusExchange"] = c.EventBusExchange
|
||||
arr["eventBusURL"] = c.EventBusURL
|
||||
arr["kvNamespace"] = c.KVNamespace
|
||||
arr["loggerAddr"] = c.LoggerAddr
|
||||
arr["registryAddr"] = c.RegistryAddr
|
||||
|
||||
return arr
|
||||
}
|
@ -1,10 +0,0 @@
|
||||
package server
|
||||
|
||||
// REFACTOR: UNIVERSAL SERVER CODE
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func (s *Server) ConfigHandler(c *fiber.Ctx) error {
|
||||
return c.JSON(s.Config)
|
||||
}
|
@ -1,30 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"git.pbiernat.io/egommerce/go-api-pkg/fluentd"
|
||||
)
|
||||
|
||||
// "github.com/gofiber/fiber/v2"
|
||||
// "github.com/gofiber/fiber/v2/middleware/cors"
|
||||
|
||||
func SetupMiddleware(s *Server) {
|
||||
s.Use(LoggingMiddleware(s.GetLogger()))
|
||||
}
|
||||
|
||||
func LoggingMiddleware(log *fluentd.Logger) func(c *fiber.Ctx) error {
|
||||
return func(c *fiber.Ctx) error {
|
||||
// path := string(c.Request().URI().Path())
|
||||
// if strings.Contains(path, "/health") {
|
||||
// return c.Next()
|
||||
// }
|
||||
|
||||
log.Log("Request: %s, remote: %s, via: %s",
|
||||
c.Request().URI().String(),
|
||||
c.Context().RemoteIP().String(),
|
||||
string(c.Context().UserAgent()))
|
||||
|
||||
return c.Next()
|
||||
}
|
||||
}
|
@ -1,29 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
|
||||
"git.pbiernat.io/egommerce/pricing-service/internal/service"
|
||||
"git.pbiernat.io/egommerce/pricing-service/internal/ui"
|
||||
)
|
||||
|
||||
func (s *Server) GetProductPriceHandler(c *fiber.Ctx) error {
|
||||
prodID, err := strconv.Atoi(c.Params("id"))
|
||||
if err != nil {
|
||||
return s.Error(c, 404, err.Error())
|
||||
}
|
||||
|
||||
priceSrv := service.NewPriceService(s.GetDatabase(), s.GetCache(), s.GetEventBus(), s.GetLogger())
|
||||
res, err := ui.GetProductPrice(priceSrv, prodID)
|
||||
if err != nil {
|
||||
s.GetLogger().Log("GetProductPriceHandler error: %s", err)
|
||||
return s.Error(c, 404, "Product not found")
|
||||
}
|
||||
|
||||
s.GetLogger().Log("Price: %#v", res)
|
||||
// s.Logger.Log("GetProductPriceHandler res: %s", c.JSON(res))
|
||||
|
||||
return c.JSON(res)
|
||||
}
|
@ -1,29 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v2/middleware/cors"
|
||||
"github.com/gofiber/fiber/v2/middleware/recover"
|
||||
)
|
||||
|
||||
var (
|
||||
defaultCORS = cors.New(cors.Config{
|
||||
AllowOrigins: "*",
|
||||
// AllowCredentials: true,
|
||||
AllowMethods: "GET, POST, PATCH, PUT, DELETE, OPTIONS",
|
||||
AllowHeaders: "Accept, Authorization, Content-Type, Vary, X-Request-Id",
|
||||
})
|
||||
)
|
||||
|
||||
func SetupRouter(s *Server) {
|
||||
s.Options("*", defaultCORS)
|
||||
s.Use(defaultCORS)
|
||||
s.Use(recover.New())
|
||||
|
||||
s.Get("/health", s.HealthHandler)
|
||||
s.Get("/config", s.ConfigHandler)
|
||||
|
||||
api := s.Group("/api")
|
||||
v1 := api.Group("/v1")
|
||||
v1.Get("/product/:id<int>", s.GetProductPriceHandler)
|
||||
|
||||
}
|
@ -1,144 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"log"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/go-redis/redis/v8"
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
|
||||
"git.pbiernat.io/egommerce/api-entities/http"
|
||||
"git.pbiernat.io/egommerce/go-api-pkg/consul"
|
||||
"git.pbiernat.io/egommerce/go-api-pkg/fluentd"
|
||||
)
|
||||
|
||||
type (
|
||||
Server struct {
|
||||
*fiber.App
|
||||
|
||||
ID string
|
||||
addr string // e.g. "127.0.0.1:443"
|
||||
handlers map[string]any
|
||||
}
|
||||
HeaderRequestID struct {
|
||||
RequestID string `reqHeader:"x-request-id"`
|
||||
}
|
||||
)
|
||||
|
||||
func New(c *Config) *Server {
|
||||
return &Server{
|
||||
ID: c.ID,
|
||||
App: fiber.New(fiber.Config{
|
||||
AppName: c.ID,
|
||||
ServerHeader: c.Name + ":" + c.ID,
|
||||
ReadTimeout: c.ReadTimeout * time.Millisecond,
|
||||
WriteTimeout: c.WriteTimeout * time.Millisecond,
|
||||
IdleTimeout: c.IdleTimeout * time.Millisecond,
|
||||
}),
|
||||
addr: c.NetAddr,
|
||||
handlers: make(map[string]any),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) Start() error {
|
||||
SetupMiddleware(s)
|
||||
SetupRouter(s)
|
||||
|
||||
// fmt.Printf("Starting server at: %s...\n", s.addr)
|
||||
cer, err := tls.LoadX509KeyPair("certs/client.crt", "certs/client.key")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
tlsCnf := &tls.Config{Certificates: []tls.Certificate{cer}}
|
||||
|
||||
ln, _ := net.Listen("tcp", s.addr)
|
||||
ln = tls.NewListener(ln, tlsCnf)
|
||||
|
||||
return s.Listener(ln)
|
||||
}
|
||||
|
||||
func (s *Server) RegisterHandler(name string, fn func() any) {
|
||||
// fmt.Printf("Registering plugin( with handler): %s... OK\n", name)
|
||||
s.handlers[name] = fn()
|
||||
}
|
||||
|
||||
func (s *Server) OnShutdown() {
|
||||
// s.GetLogger().Log("Server %s is going down...", s.ID)
|
||||
|
||||
// s.GetRegistry().Unregister()
|
||||
// a.clearMetadataCache()
|
||||
s.GetEventBus().Close()
|
||||
s.GetDatabase().Close()
|
||||
s.GetLogger().Log("Gone.")
|
||||
s.GetLogger().Close()
|
||||
|
||||
s.Shutdown()
|
||||
}
|
||||
|
||||
func (s *Server) GetRequestID(c *fiber.Ctx) (string, error) {
|
||||
var hdr = new(HeaderRequestID)
|
||||
if err := c.ReqHeaderParser(hdr); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return hdr.RequestID, nil
|
||||
}
|
||||
|
||||
func (s *Server) Error(c *fiber.Ctx, code int, msg string) error {
|
||||
return c.Status(code).JSON(http.ErrorResponse{Error: msg})
|
||||
}
|
||||
|
||||
// Plugin helper funcitons
|
||||
func (s *Server) GetCache() *redis.Client {
|
||||
return (s.handlers["cache"]).(*redis.Client)
|
||||
}
|
||||
|
||||
func (s *Server) GetDatabase() *pgxpool.Pool { // FIXME hardcoded index issue
|
||||
return (s.handlers["database"]).(*pgxpool.Pool)
|
||||
}
|
||||
|
||||
func (s *Server) GetEventBus() *amqp.Channel {
|
||||
return (s.handlers["eventbus"]).(*amqp.Channel)
|
||||
}
|
||||
|
||||
func (s *Server) GetLogger() *fluentd.Logger {
|
||||
return (s.handlers["logger"]).(*fluentd.Logger)
|
||||
}
|
||||
|
||||
func (s *Server) GetRegistry() *consul.Service {
|
||||
return (s.handlers["registry"]).(*consul.Service)
|
||||
}
|
||||
|
||||
// @CHECK: merge s.Config and s.Base.Config to display all config as one array/map
|
||||
// func (s *Server) registerKVUpdater() { // @FIXME: merge duplication in server.go and worker.go
|
||||
// go func() {
|
||||
// ticker := time.NewTicker(time.Second * 10)
|
||||
// for range ticker.C {
|
||||
// config, _, err := s.Registry.KV().Get(s.Config.KVNamespace, nil)
|
||||
// if err != nil || config == nil {
|
||||
// return
|
||||
// }
|
||||
|
||||
// kvCnf := bytes.NewBuffer(config.Value)
|
||||
// decoder := json.NewDecoder(kvCnf)
|
||||
// if err := decoder.Decode(&s.Config); err != nil {
|
||||
// return
|
||||
// }
|
||||
// }
|
||||
// }()
|
||||
// }
|
||||
|
||||
// func (s *Server) clearMetadataCache() {
|
||||
// ctx := context.Background()
|
||||
// key, address := s.getMetadataIPsKey(), s.Config.Base.AppID
|
||||
|
||||
// s.Cache.LRem(ctx, key, 0, address)
|
||||
// }
|
||||
|
||||
// func (s *Server) getMetadataIPsKey() string {
|
||||
// return "internal__" + s.Base.Config.AppName + "__ips"
|
||||
// }
|
@ -1,71 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"git.pbiernat.io/egommerce/api-entities/model"
|
||||
|
||||
"git.pbiernat.io/egommerce/go-api-pkg/fluentd"
|
||||
|
||||
"github.com/georgysavva/scany/v2/pgxscan"
|
||||
"github.com/go-redis/redis/v8"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// REFACTOR -> to many things to do -> read(different sources) + save(redis-cache)
|
||||
type PriceService struct {
|
||||
dbConn *pgxpool.Pool
|
||||
redis *redis.Client
|
||||
ebCh *amqp.Channel
|
||||
log *fluentd.Logger
|
||||
}
|
||||
|
||||
func NewPriceService(dbConn *pgxpool.Pool, redis *redis.Client, chn *amqp.Channel, log *fluentd.Logger) *PriceService {
|
||||
return &PriceService{dbConn, redis, chn, log}
|
||||
}
|
||||
|
||||
func (s *PriceService) FetchFromDB(ctx context.Context, prodID int) (int, error) {
|
||||
product := new(model.ProductPriceModel)
|
||||
err := pgxscan.Get(ctx, s.dbConn, product, `SELECT id, pid, price FROM catalog.product WHERE id=$1`, prodID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return product.Price, nil // FIXME
|
||||
}
|
||||
|
||||
func (s *PriceService) FetchFromCache(ctx context.Context, key string, itemType string) (any, error) {
|
||||
if itemType == "" {
|
||||
itemType = "string"
|
||||
}
|
||||
|
||||
var (
|
||||
value any
|
||||
err error
|
||||
cmd = s.redis.Get(ctx, key)
|
||||
)
|
||||
switch itemType {
|
||||
case "string":
|
||||
value, err = cmd.Result()
|
||||
case "int":
|
||||
value, err = cmd.Int64()
|
||||
case "float":
|
||||
value, err = cmd.Float64()
|
||||
case "bool":
|
||||
value, err = cmd.Bool()
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (s *PriceService) SaveToCache(ctx context.Context, key string, value any, exp time.Duration) error {
|
||||
s.redis.Set(ctx, key, value, exp)
|
||||
|
||||
return nil
|
||||
}
|
@ -1,49 +0,0 @@
|
||||
package ui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
def "git.pbiernat.io/egommerce/api-entities/http"
|
||||
"git.pbiernat.io/egommerce/pricing-service/internal/service"
|
||||
)
|
||||
|
||||
func GetProductPrice(srv *service.PriceService, prodID int) (*def.ProductPriceResponse, error) {
|
||||
ctx := context.Background() // FIXME TODO
|
||||
key := "pricing__product_price__" + strconv.Itoa(prodID)
|
||||
res := &def.ProductPriceResponse{}
|
||||
|
||||
if price, _ := srv.FetchFromCache(ctx, key, "float"); price != 0 {
|
||||
res.Price = price.(int)
|
||||
} else {
|
||||
price, err := srv.FetchFromDB(ctx, prodID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
res.Price = price
|
||||
srv.SaveToCache(ctx, key, res.Price, 30*time.Second) // FIXME refactor as cache service sth
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// CalculateProductPrice mock
|
||||
func CalculateProductPrice(srv *service.PriceService, prodID int, price float64) (float64, error) {
|
||||
// customer := srv.GetCustomer(customerID)
|
||||
// customerPromo := srv.GetCustomerPromotions(customer)
|
||||
// customerDiscount := srv.GetCustomerDiscounts(customer)
|
||||
|
||||
// product := srv.GetProduct(prodID)
|
||||
// productPromo := srv.GetProductPromotions(product)
|
||||
// productDiscount := srv.GetProductDiscounts(product)
|
||||
|
||||
// srv.ApplyPromotions(product, customerPromo)
|
||||
// srv.ApplyPromotions(product, customerDiscount)
|
||||
// srv.ApplyPromotions(product, productPromo)
|
||||
// srv.ApplyPromotions(product, productDiscount)
|
||||
// finalPrice := product.GetPrice()
|
||||
|
||||
return price, nil
|
||||
}
|
@ -1,54 +0,0 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"git.pbiernat.io/egommerce/pricing-service/internal/service"
|
||||
)
|
||||
|
||||
var (
|
||||
StockUpdated = "event.WarehouseStockUpdatedEvent"
|
||||
)
|
||||
|
||||
type Command interface {
|
||||
run(CommandData) (bool, any)
|
||||
}
|
||||
|
||||
type CommandData map[string]interface{}
|
||||
|
||||
type CommandRunner struct {
|
||||
cmd Command
|
||||
}
|
||||
|
||||
func NewCommandRunner(data map[string]interface{}, srvc *service.PriceService) *CommandRunner {
|
||||
rnr := &CommandRunner{}
|
||||
rnr.cmd = getCommand((data["command"]).(string), srvc)
|
||||
|
||||
return rnr
|
||||
}
|
||||
|
||||
func getCommand(cmd string, srvc *service.PriceService) Command {
|
||||
// fmt.Printf("getCommand: %v\n", cmd)
|
||||
var c Command
|
||||
|
||||
switch cmd { // FIXME
|
||||
case "StockUpdated":
|
||||
c = &StockUpdatedCommand{srvc}
|
||||
}
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
func (r *CommandRunner) run(data CommandData) (bool, any) {
|
||||
return r.cmd.run(data)
|
||||
}
|
||||
|
||||
type StockUpdatedCommand struct {
|
||||
srvc *service.PriceService
|
||||
}
|
||||
|
||||
func (c *StockUpdatedCommand) run(data CommandData) (bool, any) {
|
||||
// reqID := data["request_id"].(string) // FIXME Check input params!
|
||||
// productID := int(data["product_id"].(float64)) // FIXME Check input params!
|
||||
|
||||
// stock, err := ui.StockUpdated(c.srvc, productID, reqID)
|
||||
return true, nil //err == nil, basket
|
||||
}
|
@ -1,85 +0,0 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
|
||||
cnf "git.pbiernat.io/egommerce/go-api-pkg/config"
|
||||
)
|
||||
|
||||
const (
|
||||
defName = "pricing-worker"
|
||||
defDomain = "pricing-worker"
|
||||
defCacheAddr = "egommerce.local:6379"
|
||||
defCachePassword = "12345678"
|
||||
defDbURL = "postgres://postgres:12345678@db-postgres:5432/egommerce"
|
||||
defEventBusURL = "amqp://guest:guest@api-eventbus:5672"
|
||||
defKVNmspc = "dev.egommerce/service/pricing-worker"
|
||||
defLoggerAddr = "api-logger:24224"
|
||||
defMongoDbURL = "mongodb://mongodb:12345678@mongo-db:27017"
|
||||
defEbEventsExchange = "api-events"
|
||||
defEbEventsQueue = "pricing-svc"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
ID string
|
||||
Name string
|
||||
|
||||
LoggerAddr string `json:"logger_addr"`
|
||||
DbURL string `json:"db_url"`
|
||||
CacheAddr string `json:"cache_addr"`
|
||||
CachePassword string `json:"cache_password"`
|
||||
MongoDbUrl string `json:"mongodb_url"`
|
||||
EventBusURL string `json:"eventbus_url"`
|
||||
EventBusExchange string `json:"eventbus_exchange"`
|
||||
EventBusQueue string `json:"eventbus_queue"`
|
||||
KVNamespace string
|
||||
}
|
||||
|
||||
func NewConfig(name string) *Config {
|
||||
c := new(Config)
|
||||
|
||||
c.ID, _ = os.Hostname()
|
||||
c.Name = name
|
||||
|
||||
c.CacheAddr = cnf.GetEnv("CACHE_ADDR", defCacheAddr)
|
||||
c.CachePassword = cnf.GetEnv("CACHE_PASSWORD", defCachePassword)
|
||||
c.DbURL = cnf.GetEnv("DATABASE_URL", defDbURL)
|
||||
c.EventBusExchange = defEbEventsExchange
|
||||
c.EventBusURL = cnf.GetEnv("EVENTBUS_URL", defEventBusURL)
|
||||
c.KVNamespace = cnf.GetEnv("APP_KV_NAMESPACE", defKVNmspc)
|
||||
c.LoggerAddr = cnf.GetEnv("LOGGER_ADDR", defLoggerAddr)
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *Config) GetAppFullName() string {
|
||||
return fmt.Sprintf("%s_%s", c.Name, c.ID)
|
||||
}
|
||||
|
||||
func (c *Config) GetIP() string {
|
||||
host, _ := os.Hostname()
|
||||
ips, _ := net.LookupIP(host)
|
||||
// for _, ip := range ips {
|
||||
// return ip.String()
|
||||
// }
|
||||
|
||||
return ips[0].String()
|
||||
}
|
||||
|
||||
func (c *Config) GetArray() map[string]string { // FIXME fix types etc
|
||||
arr := make(map[string]string)
|
||||
arr["id"] = c.ID
|
||||
arr["name"] = c.Name
|
||||
arr["appFullname"] = c.GetAppFullName()
|
||||
arr["cacheAddr"] = c.CacheAddr
|
||||
arr["cachePassword"] = c.CachePassword
|
||||
arr["dbURL"] = c.DbURL
|
||||
arr["eventBusExchange"] = c.EventBusExchange
|
||||
arr["eventBusURL"] = c.EventBusURL
|
||||
arr["kvNamespace"] = c.KVNamespace
|
||||
arr["loggerAddr"] = c.LoggerAddr
|
||||
|
||||
return arr
|
||||
}
|
@ -1,207 +0,0 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/go-redis/redis/v8"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
|
||||
"git.pbiernat.io/egommerce/go-api-pkg/fluentd"
|
||||
"git.pbiernat.io/egommerce/go-api-pkg/rabbitmq"
|
||||
|
||||
"git.pbiernat.io/egommerce/pricing-service/internal/event"
|
||||
"git.pbiernat.io/egommerce/pricing-service/internal/service"
|
||||
)
|
||||
|
||||
type (
|
||||
Worker struct {
|
||||
ID string
|
||||
cnf *Config
|
||||
handlers map[string]any
|
||||
services map[string]any
|
||||
doWrkUntil chan struct{}
|
||||
}
|
||||
)
|
||||
|
||||
func New(c *Config) *Worker {
|
||||
return &Worker{
|
||||
ID: c.ID,
|
||||
cnf: c,
|
||||
handlers: make(map[string]any),
|
||||
services: make(map[string]any),
|
||||
doWrkUntil: make(chan struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) Start() error {
|
||||
setupQueues(w)
|
||||
|
||||
err := w.doWork(w.doWrkUntil)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to start worker: %s. Reason: %v\n", w.ID, err)
|
||||
close(w.doWrkUntil)
|
||||
}
|
||||
<-w.doWrkUntil
|
||||
|
||||
return err
|
||||
|
||||
// go func() {
|
||||
// sigint := make(chan os.Signal, 1)
|
||||
// signal.Notify(sigint, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
|
||||
// <-sigint
|
||||
|
||||
// w.Shutdown()
|
||||
// close(while)
|
||||
// }()
|
||||
|
||||
// run := w.createRunFile("./app.run") // TODO move to common library (shared between server and worker)
|
||||
// defer w.removeRunFile(run)
|
||||
|
||||
// w.Logger.Log("Waiting for messages...")
|
||||
|
||||
// return nil
|
||||
}
|
||||
|
||||
func (w *Worker) RegisterHandler(name string, fn func() any) {
|
||||
// fmt.Printf("Registering plugin( with handler): %s... OK\n", name)
|
||||
w.handlers[name] = fn()
|
||||
}
|
||||
|
||||
func (w *Worker) OnShutdown() {
|
||||
w.GetLogger().Log("Worker %s is going down...", w.ID)
|
||||
// fmt.Printf("Worker %s is going down...\n", w.ID)
|
||||
|
||||
unbindQueues(w)
|
||||
w.GetEventBus().Close()
|
||||
w.GetDatabase().Close()
|
||||
w.GetLogger().Log("Gone.")
|
||||
w.GetLogger().Close()
|
||||
|
||||
close(w.doWrkUntil)
|
||||
}
|
||||
|
||||
// Plugin helper funcitons
|
||||
func (w *Worker) GetCache() *redis.Client {
|
||||
return (w.handlers["cache"]).(*redis.Client)
|
||||
}
|
||||
|
||||
func (w *Worker) GetDatabase() *pgxpool.Pool { // FIXME hardcoded index issue
|
||||
return (w.handlers["database"]).(*pgxpool.Pool)
|
||||
}
|
||||
|
||||
func (w *Worker) GetEventBus() *amqp.Channel {
|
||||
return (w.handlers["eventbus"]).(*amqp.Channel)
|
||||
}
|
||||
|
||||
func (w *Worker) GetLogger() *fluentd.Logger {
|
||||
return (w.handlers["logger"]).(*fluentd.Logger)
|
||||
}
|
||||
|
||||
func (w *Worker) doWork(while chan struct{}) error {
|
||||
w.services["price"] =
|
||||
service.NewPriceService(w.GetDatabase(), w.GetCache(), w.GetEventBus(), w.GetLogger())
|
||||
|
||||
pSrv := (w.services["price"]).(*service.PriceService)
|
||||
|
||||
msgs, err := w.GetEventBus().Consume(
|
||||
w.cnf.EventBusQueue, // queue
|
||||
"", // consumer
|
||||
false, // auto-ack
|
||||
false, // exclusive
|
||||
false, // no-local
|
||||
false, // no-wait
|
||||
nil, // args
|
||||
)
|
||||
if err != nil {
|
||||
w.GetLogger().Log("Failed to register a consumer: %s", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
go func() {
|
||||
for d := range msgs {
|
||||
// go func(d amqp.Delivery) {
|
||||
w.processMsg(pSrv, d)
|
||||
// }(d)
|
||||
}
|
||||
}()
|
||||
<-while
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *Worker) processMsg(srvc *service.PriceService, d amqp.Delivery) {
|
||||
msg, err := rabbitmq.Deserialize(d.Body)
|
||||
if err != nil {
|
||||
w.GetLogger().Log("Deserialization error: %v\n", err)
|
||||
fmt.Printf("Deserialization error: %v\n", err)
|
||||
d.Reject(false)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
name := fmt.Sprintf("%s", msg["event"])
|
||||
data := (msg["data"]).(map[string]interface{})
|
||||
// reqID := (data["request_id"]).(string) // FIXME Check input params!
|
||||
|
||||
w.GetLogger().Log("Processing message \"%s\" with data: %v\n", name, data)
|
||||
fmt.Printf("Processing message \"%s\" with data: %v\n", name, data)
|
||||
|
||||
var ok = false
|
||||
switch true { // Refactor -> use case for polymorphism
|
||||
case strings.Contains(name, event.EVENT_PRODUCT_ADDED_TO_BASKET):
|
||||
w.GetLogger().Log("Event: %s", event.EVENT_PRODUCT_ADDED_TO_BASKET)
|
||||
case strings.Contains(name, event.EVENT_PRODUCT_REMOVED_FROM_BASKET):
|
||||
w.GetLogger().Log("Event: %s", event.EVENT_PRODUCT_REMOVED_FROM_BASKET)
|
||||
}
|
||||
|
||||
rnr := NewCommandRunner(data, srvc)
|
||||
ok, _ = rnr.run(data)
|
||||
if ok {
|
||||
w.GetLogger().Log("Successful executed message \"%s\"\n", name)
|
||||
fmt.Printf("Successful executed message \"%s\"\n", name)
|
||||
d.Ack(false)
|
||||
return
|
||||
}
|
||||
|
||||
w.GetLogger().Log("Error processing \"%s\": %v", name, err)
|
||||
fmt.Printf("Error processing \"%s\": %v\n", name, err)
|
||||
d.Reject(false) // FIXME: or Nack(repeat until success - maybe message shout know...?
|
||||
}
|
||||
|
||||
func setupQueues(w *Worker) {
|
||||
err := rabbitmq.NewExchange(w.GetEventBus(), w.cnf.EventBusExchange)
|
||||
if err != nil {
|
||||
w.GetLogger().Log("Failed to declare EventBus exchange: %v\n", err)
|
||||
fmt.Printf("Failed to declare EventBus exchange: %v\n", err)
|
||||
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
args := amqp.Table{}
|
||||
args["x-message-ttl"] = 5
|
||||
_, err = w.GetEventBus().QueueDeclare(
|
||||
w.cnf.EventBusQueue, // name
|
||||
true, // durable
|
||||
false, // delete when unused
|
||||
false, // exclusive
|
||||
false, // no-wait
|
||||
args, // arguments
|
||||
)
|
||||
if err != nil {
|
||||
w.GetLogger().Log("Failed to declare EventBus queue: %v\n", err)
|
||||
fmt.Printf("Failed to declare EventBus queue: %v\n", err)
|
||||
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// w.bindQueues()
|
||||
rabbitmq.BindQueueToExchange(w.GetEventBus(), w.cnf.EventBusQueue, w.cnf.EventBusExchange, "basket.pricing.*")
|
||||
}
|
||||
|
||||
func unbindQueues(w *Worker) {
|
||||
w.GetEventBus().QueueUnbind(w.cnf.EventBusQueue, "basket.pricing.*", w.cnf.EventBusExchange, nil)
|
||||
}
|
Loading…
Reference in New Issue
Block a user