diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..a757b69 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,48 @@ +name: CI + +on: + push: + branches: + - 'main' + pull_request: + branches: + - 'main' + - 'feature/**' + +jobs: + + ci: + name: Run CI + runs-on: ubuntu-latest + strategy: + matrix: + go-version: [ '1.20' ] + steps: + + - name: Checkout + uses: actions/checkout@v3 + + - name: Set up Go + uses: actions/setup-go@v3 + with: + go-version: ${{ matrix.go-version }} + + - name: Determine Go cache paths + id: golang-path + run: | + echo "build=$(go env GOCACHE)" >>"$GITHUB_OUTPUT" + echo "module=$(go env GOMODCACHE)" >>"$GITHUB_OUTPUT" + shell: bash + + - name: Setup Go cache + uses: actions/cache@v3 + with: + path: | + ${{ steps.golang-path.outputs.build }} + ${{ steps.golang-path.outputs.module }} + key: ${{ runner.os }}-golang-${{ hashFiles('**/go.sum', 'Makefile') }} + restore-keys: | + ${{ runner.os }}-golang- + + - name: Run tests + run: make ci diff --git a/.github/workflows/publish-docker-image.yml b/.github/workflows/publish-docker-image.yml new file mode 100644 index 0000000..3b21ae4 --- /dev/null +++ b/.github/workflows/publish-docker-image.yml @@ -0,0 +1,45 @@ +name: Publish Docker image + +on: + push: + branches: ['main'] + +env: + REGISTRY: ghcr.io + IMAGE_NAME: ${{ github.repository }} + +jobs: + push_to_registry: + name: Push Docker image to ghcr registry + runs-on: ubuntu-latest + permissions: + packages: write + contents: read + + steps: + - name: Check out the repo + uses: actions/checkout@v3 + + - name: Log in to the Github Container registry + uses: docker/login-action@v2 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract metadata (tags, labels) for Docker + id: meta + uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7 + with: + images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} + tags: | + type=ref,event=branch,suffix=_{{sha}} + type=raw,value=latest,enable={{is_default_branch}} + + - name: Build and push Docker images + uses: docker/build-push-action@v4 + with: + context: . + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} diff --git a/.github/workflows/publish-stable-docker-image.yml b/.github/workflows/publish-stable-docker-image.yml new file mode 100644 index 0000000..906400c --- /dev/null +++ b/.github/workflows/publish-stable-docker-image.yml @@ -0,0 +1,45 @@ +name: Publish Stable Docker image with tag + +on: + push: + tags: + - 2**-**-** + +env: + REGISTRY: ghcr.io + IMAGE_NAME: ${{ github.repository }} + +jobs: + push_to_registries: + name: Push Docker image to ghcr registry + runs-on: ubuntu-latest + permissions: + packages: write + contents: read + steps: + - name: Check out the repo + uses: actions/checkout@v3 + + - name: Log in to the Github Container registry + uses: docker/login-action@v2 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract metadata (tags, labels) for Docker + id: meta + uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7 + with: + images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} + tags: | + type=ref,event=tag + type=raw,event=tag,value=stable + + - name: Build and push Docker images + uses: docker/build-push-action@v4 + with: + context: . + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..80fa825 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +.idea/ +.env +.envrc +# don't commit APNS certs +*.p12 +# don't commit firestore certs (which usually follow this pattern) +nos-notification-service-*.json +database.sqlite +database.sqlite-journal +run.sh diff --git a/.golangci.yaml b/.golangci.yaml new file mode 100644 index 0000000..7d14cb6 --- /dev/null +++ b/.golangci.yaml @@ -0,0 +1,3 @@ +run: + build-tags: + - wireinject \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..3ca4509 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,14 @@ +FROM golang:1.20-alpine AS build + +WORKDIR /usr/src/app +COPY . . +# get ssl certs to copy into scratch image, as it won't have them by default. +RUN apk update && apk add --no-cache git ca-certificates && update-ca-certificates +RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -v -o /usr/local/bin/event-service ./cmd/event-service + + +FROM scratch as app +WORKDIR / +COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ +COPY --from=build /usr/local/bin/event-service /event-service +CMD ["/event-service"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a612ad9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..5ac013d --- /dev/null +++ b/Makefile @@ -0,0 +1,32 @@ +.PHONY: ci +ci: tools test lint generate fmt tidy check_repository_unchanged + +.PHONY: check_repository_unchanged +check_repository_unchanged: + _tools/check_repository_unchanged.sh + +.PHONY: generate +generate: + go generate ./... + +.PHONY: fmt +fmt: + gosimports -l -w ./ + +.PHONY: test +test: + go test -race ./... + +.PHONY: tidy +tidy: + go mod tidy + +.PHONY: lint +lint: + go vet ./... + golangci-lint run ./... + +.PHONY: tools +tools: + go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.51.1 + go install github.com/rinchsan/gosimports/cmd/gosimports@v0.3.5 # https://github.com/golang/go/issues/20818 diff --git a/README.md b/README.md new file mode 100644 index 0000000..ac0961e --- /dev/null +++ b/README.md @@ -0,0 +1,134 @@ +# Nos Event Service + +## Building and running + +Build the program like so: + + $ go build -o event-service ./cmd/event-service + $ ./event-service + +The program takes no arguments. There is a Dockerfile available. + +## Configuration + +Configuration is performed using environment variables. This is also the case +for the Dockerfile. + +### `EVENTS_LISTEN_ADDRESS` + +Listen address for the main webserver in the format accepted by the Go standard +library. The metrics are exposed under path `/metrics`. + +Optional, defaults to `:8008` if empty. + +### `EVENTS_ENVIRONMENT` + +Execution environment. Setting environment to `DEVELOPMENT`: +- replaces a Twitter API adapter with a fake adapter + - it doesn't actually post to Twitter + - it returns hardcoded fake Twitter account details (due to weird rate-limiting errors) + +Optional, can be set to `PRODUCTION` or `DEVELOPMENT`. Defaults to `PRODUCTION`. + +### `EVENTS_LOG_LEVEL` + +Log level. + +Optional, can be set to `TRACE`, `DEBUG`, `ERROR` or `DISABLED`. Defaults to +`DEBUG`. + +### `EVENTS_DATABASE_PATH` + +Full path to the database file. + +Required, e.g. `/some/directory/database.sqlite`. + +## Metrics + +See configuration for the address of our metrics endpoint. Many out-of-the-box +Go-related metrics are available. We also have custom metrics: + +- `application_handler_calls_total` +- `application_handler_calls_duration` + +See `service/adapters/prometheus`. + +## Contributing + +### Go version + +The project usually uses the latest Go version as declared by the `go.mod` file. +You may not be able to build it using older compilers. + +### How to do local development + +Run the following command changing appropriate environment variables: + +``` +EVENTS_DATABASE_PATH=/path/to/database.sqlite \ +EVENTS_ENVIRONMENT=DEVELOPMENT \ +go run ./cmd/event-service +``` + +### Updating frontend files + +Frontend is written in Vue and located in `./frontend`. Precompiled files are +supposed to be commited as they are embedded in executable files. + +In order to update the embedded compiled frontend files run the following +command: + + $ make frontend + +### Makefile + +We recommend reading the `Makefile` to discover some targets which you can +execute. It can be used as a shortcut to run various useful commands. + +You may have to run the following command to install a linter and a code +formatter before executing certain targets: + + $ make tools + +If you want to check if the pipeline will pass for your commit it should be +enough to run the following command: + + $ make ci + +It is also useful to often run just the tests during development: + + $ make test + +Easily format your code with the following command: + + $ make fmt + +### Writing code + +Resources which are in my opinion informative and good to read: + +- [Effective Go][effective-go] +- [Go Code Review Comments][code-review-comments] +- [Uber Go Style Guide][uber-style-guide] + +#### Naming tests + +When naming tests which tests a specific behaviour it is recommended to follow a +pattern `TestNameOfType_ExpectedBehaviour`. Example: +`TestRelayDownloader_EventsDownloadedFromRelaysArePublishedUsingPublisher` +. + +#### Panicking constructors + +Some constructors are prefixed with the word `Must`. Those constructors panic +and should always be accompanied by a normal constructor which isn't prefixed +with the `Must` and returns an error. The panicking constructors should only be +used in the following cases: +- when writing tests +- when a static value has to be created e.g. `MustNewHops(1)` and this branch of + logic in the code is covered by tests + +[effective-go]: http://golang.org/doc/effective_go.html +[code-review-comments]: https://github.com/golang/go/wiki/CodeReviewComments +[uber-style-guide]: https://github.com/uber-go/guide/blob/master/style.md + diff --git a/_tools/check_repository_unchanged.sh b/_tools/check_repository_unchanged.sh new file mode 100755 index 0000000..cfeedc9 --- /dev/null +++ b/_tools/check_repository_unchanged.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +if [ -n "$(git status --porcelain 2>&1)" ]; then + echo "Detected changes in the repository!"; + git --no-pager diff; + exit 1; +else + echo "No changes detected in the repository."; +fi \ No newline at end of file diff --git a/cmd/event-service/di/inject_adapters.go b/cmd/event-service/di/inject_adapters.go new file mode 100644 index 0000000..e2c3898 --- /dev/null +++ b/cmd/event-service/di/inject_adapters.go @@ -0,0 +1,85 @@ +package di + +import ( + "database/sql" + + "github.com/boreq/errors" + "github.com/google/wire" + "github.com/planetary-social/nos-event-service/internal/logging" + "github.com/planetary-social/nos-event-service/service/adapters/prometheus" + "github.com/planetary-social/nos-event-service/service/adapters/sqlite" + "github.com/planetary-social/nos-event-service/service/app" + "github.com/planetary-social/nos-event-service/service/config" + "github.com/planetary-social/nos-event-service/service/domain/relays" +) + +var sqliteAdaptersSet = wire.NewSet( + newSqliteDB, + + sqlite.NewTransactionProvider, + wire.Bind(new(app.TransactionProvider), new(*sqlite.TransactionProvider)), + + newAdaptersFactoryFn, + + wire.Struct(new(buildTransactionSqliteAdaptersDependencies), "*"), +) + +var sqliteTestAdaptersSet = wire.NewSet( + newSqliteDB, + + sqlite.NewTestTransactionProvider, + + newTestAdaptersFactoryFn, + + wire.Struct(new(buildTransactionSqliteAdaptersDependencies), "*"), +) + +var sqliteTxAdaptersSet = wire.NewSet( + sqlite.NewEventRepository, + wire.Bind(new(app.EventRepository), new(*sqlite.EventRepository)), +) + +var adaptersSet = wire.NewSet( + prometheus.NewPrometheus, + wire.Bind(new(app.Metrics), new(*prometheus.Prometheus)), + wire.Bind(new(relays.Metrics), new(*prometheus.Prometheus)), + + //adapters.NewIDGenerator, + //wire.Bind(new(app.SessionIDGenerator), new(*adapters.IDGenerator)), + //wire.Bind(new(app.AccountIDGenerator), new(*adapters.IDGenerator)), + // + //adapters.NewRelaySource, + //adapters.NewPurplePages, + //wire.Bind(new(app.RelaySource), new(*adapters.RelaySource)), + // + //adapters.NewRelayEventDownloader, + //wire.Bind(new(app.RelayEventDownloader), new(*adapters.RelayEventDownloader)), + // + //adapters.NewTwitterAccountDetailsCache, + //wire.Bind(new(app.TwitterAccountDetailsCache), new(*adapters.TwitterAccountDetailsCache)), +) + +func newAdaptersFactoryFn(deps buildTransactionSqliteAdaptersDependencies) sqlite.AdaptersFactoryFn { + return func(db *sql.DB, tx *sql.Tx) (app.Adapters, error) { + return buildTransactionSqliteAdapters(db, tx, deps) + } +} + +func newTestAdaptersFactoryFn(deps buildTransactionSqliteAdaptersDependencies) sqlite.TestAdaptersFactoryFn { + return func(db *sql.DB, tx *sql.Tx) (sqlite.TestAdapters, error) { + return buildTestTransactionSqliteAdapters(db, tx, deps) + } +} + +func newSqliteDB(conf config.Config, logger logging.Logger) (*sql.DB, func(), error) { + v, err := sqlite.Open(conf) + if err != nil { + return nil, nil, errors.Wrap(err, "error opening sqlite") + } + + return v, func() { + if err := v.Close(); err != nil { + logger.Error().WithError(err).Message("error closing sqlite") + } + }, nil +} diff --git a/cmd/event-service/di/inject_application.go b/cmd/event-service/di/inject_application.go new file mode 100644 index 0000000..db30dcc --- /dev/null +++ b/cmd/event-service/di/inject_application.go @@ -0,0 +1,18 @@ +package di + +import ( + "github.com/google/wire" + "github.com/planetary-social/nos-event-service/service/app" + "github.com/planetary-social/nos-event-service/service/ports/memorypubsub" + "github.com/planetary-social/nos-event-service/service/ports/sqlitepubsub" +) + +var applicationSet = wire.NewSet( + wire.Struct(new(app.Application), "*"), + + app.NewSaveReceivedEventHandler, + wire.Bind(new(memorypubsub.SaveReceivedEventHandler), new(*app.SaveReceivedEventHandler)), + + app.NewProcessSavedEventHandler, + wire.Bind(new(sqlitepubsub.ProcessSavedEventHandler), new(*app.ProcessSavedEventHandler)), +) diff --git a/cmd/event-service/di/inject_logging.go b/cmd/event-service/di/inject_logging.go new file mode 100644 index 0000000..b2b5d24 --- /dev/null +++ b/cmd/event-service/di/inject_logging.go @@ -0,0 +1,37 @@ +package di + +import ( + "github.com/ThreeDotsLabs/watermill" + "github.com/boreq/errors" + "github.com/google/wire" + "github.com/planetary-social/nos-event-service/internal/logging" + "github.com/planetary-social/nos-event-service/service/config" + "github.com/sirupsen/logrus" +) + +var loggingSet = wire.NewSet( + newLogger, + + logging.NewWatermillAdapter, + wire.Bind(new(watermill.LoggerAdapter), new(*logging.WatermillAdapter)), +) + +func newLogger(conf config.Config) (logging.Logger, error) { + if conf.LogLevel() == logging.LevelDisabled { + return logging.NewDevNullLogger(), nil + } + + v := logrus.New() + switch conf.LogLevel() { + case logging.LevelTrace: + v.SetLevel(logrus.TraceLevel) + case logging.LevelDebug: + v.SetLevel(logrus.DebugLevel) + case logging.LevelError: + v.SetLevel(logrus.ErrorLevel) + default: + return nil, errors.New("unsupported log level") + } + + return logging.NewSystemLogger(logging.NewLogrusLoggingSystem(v), "root"), nil +} diff --git a/cmd/event-service/di/inject_migrations.go b/cmd/event-service/di/inject_migrations.go new file mode 100644 index 0000000..6b65a35 --- /dev/null +++ b/cmd/event-service/di/inject_migrations.go @@ -0,0 +1,20 @@ +package di + +import ( + "github.com/google/wire" + "github.com/planetary-social/nos-event-service/migrations" + "github.com/planetary-social/nos-event-service/service/adapters" + "github.com/planetary-social/nos-event-service/service/adapters/sqlite" +) + +var migrationsAdaptersSet = wire.NewSet( + sqlite.NewMigrations, + sqlite.NewMigrationFns, + migrations.NewRunner, + + sqlite.NewMigrationsStorage, + wire.Bind(new(migrations.Storage), new(*sqlite.MigrationsStorage)), + + adapters.NewLoggingMigrationsProgressCallback, + wire.Bind(new(migrations.ProgressCallback), new(*adapters.LoggingMigrationsProgressCallback)), +) diff --git a/cmd/event-service/di/inject_ports.go b/cmd/event-service/di/inject_ports.go new file mode 100644 index 0000000..81d18e1 --- /dev/null +++ b/cmd/event-service/di/inject_ports.go @@ -0,0 +1,13 @@ +package di + +import ( + "github.com/google/wire" + "github.com/planetary-social/nos-event-service/service/ports/http" + "github.com/planetary-social/nos-event-service/service/ports/memorypubsub" +) + +var portsSet = wire.NewSet( + http.NewServer, + + memorypubsub.NewReceivedEventSubscriber, +) diff --git a/cmd/event-service/di/inject_pubsub.go b/cmd/event-service/di/inject_pubsub.go new file mode 100644 index 0000000..de94879 --- /dev/null +++ b/cmd/event-service/di/inject_pubsub.go @@ -0,0 +1,28 @@ +package di + +import ( + "github.com/google/wire" + "github.com/planetary-social/nos-event-service/service/adapters/memorypubsub" + "github.com/planetary-social/nos-event-service/service/adapters/sqlite" + "github.com/planetary-social/nos-event-service/service/app" + "github.com/planetary-social/nos-event-service/service/ports/sqlitepubsub" +) + +var memoryPubsubSet = wire.NewSet( + memorypubsub.NewReceivedEventPubSub, + wire.Bind(new(app.ReceivedEventPublisher), new(*memorypubsub.ReceivedEventPubSub)), + wire.Bind(new(app.ReceivedEventSubscriber), new(*memorypubsub.ReceivedEventPubSub)), +) + +var sqlitePubsubSet = wire.NewSet( + sqlitepubsub.NewEventSavedEventSubscriber, + sqlite.NewPubSub, + + sqlite.NewSubscriber, + //wire.Bind(new(app.Subscriber), new(*sqlite.Subscriber)), +) + +var sqliteTxPubsubSet = wire.NewSet( + sqlite.NewPublisher, + wire.Bind(new(app.Publisher), new(*sqlite.Publisher)), +) diff --git a/cmd/event-service/di/service.go b/cmd/event-service/di/service.go new file mode 100644 index 0000000..3de72f9 --- /dev/null +++ b/cmd/event-service/di/service.go @@ -0,0 +1,90 @@ +package di + +import ( + "context" + + "github.com/boreq/errors" + "github.com/hashicorp/go-multierror" + "github.com/planetary-social/nos-event-service/migrations" + "github.com/planetary-social/nos-event-service/service/app" + "github.com/planetary-social/nos-event-service/service/ports/http" + "github.com/planetary-social/nos-event-service/service/ports/memorypubsub" + "github.com/planetary-social/nos-event-service/service/ports/sqlitepubsub" +) + +type Service struct { + app app.Application + server http.Server + downloader *app.Downloader + receivedEventSubscriber *memorypubsub.ReceivedEventSubscriber + eventSavedEventSubscriber *sqlitepubsub.EventSavedEventSubscriber + migrationsRunner *migrations.Runner + migrations migrations.Migrations + migrationsProgressCallback migrations.ProgressCallback +} + +func NewService( + app app.Application, + server http.Server, + downloader *app.Downloader, + receivedEventSubscriber *memorypubsub.ReceivedEventSubscriber, + eventSavedEventSubscriber *sqlitepubsub.EventSavedEventSubscriber, + migrationsRunner *migrations.Runner, + migrations migrations.Migrations, + migrationsProgressCallback migrations.ProgressCallback, +) Service { + return Service{ + app: app, + server: server, + downloader: downloader, + receivedEventSubscriber: receivedEventSubscriber, + eventSavedEventSubscriber: eventSavedEventSubscriber, + migrationsRunner: migrationsRunner, + migrations: migrations, + migrationsProgressCallback: migrationsProgressCallback, + } +} + +func (s Service) App() app.Application { + return s.app +} + +func (s Service) ExecuteMigrations(ctx context.Context) error { + return s.migrationsRunner.Run(ctx, s.migrations, s.migrationsProgressCallback) +} + +func (s Service) Run(ctx context.Context) error { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + + errCh := make(chan error) + runners := 0 + + runners++ + go func() { + errCh <- errors.Wrap(s.server.ListenAndServe(ctx), "server error") + }() + + runners++ + go func() { + errCh <- errors.Wrap(s.downloader.Run(ctx), "downloader error") + }() + + runners++ + go func() { + errCh <- errors.Wrap(s.receivedEventSubscriber.Run(ctx), "received event subscriber error") + }() + + runners++ + go func() { + errCh <- errors.Wrap(s.eventSavedEventSubscriber.Run(ctx), "event saved subscriber error") + }() + + var err error + for i := 0; i < runners; i++ { + err = multierror.Append(err, errors.Wrap(<-errCh, "error returned by runner")) + cancel() + } + + return err +} diff --git a/cmd/event-service/di/wire.go b/cmd/event-service/di/wire.go new file mode 100644 index 0000000..cdf04b5 --- /dev/null +++ b/cmd/event-service/di/wire.go @@ -0,0 +1,108 @@ +//go:build wireinject +// +build wireinject + +package di + +import ( + "context" + "database/sql" + "testing" + + "github.com/google/wire" + "github.com/planetary-social/nos-event-service/internal/fixtures" + "github.com/planetary-social/nos-event-service/internal/logging" + "github.com/planetary-social/nos-event-service/service/adapters/sqlite" + "github.com/planetary-social/nos-event-service/service/app" + "github.com/planetary-social/nos-event-service/service/config" + "github.com/planetary-social/nos-event-service/service/domain" + "github.com/planetary-social/nos-event-service/service/domain/relays" +) + +func BuildService(context.Context, config.Config) (Service, func(), error) { + wire.Build( + NewService, + + portsSet, + applicationSet, + sqliteAdaptersSet, + downloaderSet, + memoryPubsubSet, + sqlitePubsubSet, + loggingSet, + adaptersSet, + migrationsAdaptersSet, + domainSet, + ) + return Service{}, nil, nil +} + +func BuildTestAdapters(context.Context, testing.TB) (sqlite.TestedItems, func(), error) { + wire.Build( + wire.Struct(new(sqlite.TestedItems), "*"), + + sqliteTestAdaptersSet, + sqlitePubsubSet, + loggingSet, + newTestAdaptersConfig, + migrationsAdaptersSet, + ) + return sqlite.TestedItems{}, nil, nil +} + +func newTestAdaptersConfig(tb testing.TB) (config.Config, error) { + return config.NewConfig( + fixtures.SomeString(), + config.EnvironmentDevelopment, + logging.LevelDebug, + false, + fixtures.SomeString(), + nil, + fixtures.SomeFile(tb), + ) +} + +type buildTransactionSqliteAdaptersDependencies struct { + Logger logging.Logger +} + +func buildTransactionSqliteAdapters(*sql.DB, *sql.Tx, buildTransactionSqliteAdaptersDependencies) (app.Adapters, error) { + wire.Build( + wire.Struct(new(app.Adapters), "*"), + wire.FieldsOf(new(buildTransactionSqliteAdaptersDependencies), "Logger"), + + sqliteTxAdaptersSet, + sqliteTxPubsubSet, + sqlitePubsubSet, + ) + return app.Adapters{}, nil +} + +func buildTestTransactionSqliteAdapters(*sql.DB, *sql.Tx, buildTransactionSqliteAdaptersDependencies) (sqlite.TestAdapters, error) { + wire.Build( + wire.Struct(new(sqlite.TestAdapters), "*"), + wire.FieldsOf(new(buildTransactionSqliteAdaptersDependencies), "Logger"), + + sqliteTxAdaptersSet, + sqliteTxPubsubSet, + sqlitePubsubSet, + ) + return sqlite.TestAdapters{}, nil +} + +var downloaderSet = wire.NewSet( + app.NewDownloader, + + relays.NewBootstrapRelaySource, + wire.Bind(new(app.BootstrapRelaySource), new(*relays.BootstrapRelaySource)), + + app.NewMockRelaySource, + wire.Bind(new(app.RelaySource), new(*app.MockRelaySource)), + + relays.NewRelayConnections, + wire.Bind(new(app.RelayConnections), new(*relays.RelayConnections)), +) + +var domainSet = wire.NewSet( + domain.NewRelaysExtractor, + wire.Bind(new(app.RelaysExtractor), new(*domain.RelaysExtractor)), +) diff --git a/cmd/event-service/di/wire_gen.go b/cmd/event-service/di/wire_gen.go new file mode 100644 index 0000000..41bdc5a --- /dev/null +++ b/cmd/event-service/di/wire_gen.go @@ -0,0 +1,177 @@ +// Code generated by Wire. DO NOT EDIT. + +//go:generate go run github.com/google/wire/cmd/wire +//go:build !wireinject +// +build !wireinject + +package di + +import ( + "context" + "database/sql" + "testing" + + "github.com/google/wire" + "github.com/planetary-social/nos-event-service/internal/fixtures" + "github.com/planetary-social/nos-event-service/internal/logging" + "github.com/planetary-social/nos-event-service/migrations" + "github.com/planetary-social/nos-event-service/service/adapters" + "github.com/planetary-social/nos-event-service/service/adapters/memorypubsub" + "github.com/planetary-social/nos-event-service/service/adapters/prometheus" + "github.com/planetary-social/nos-event-service/service/adapters/sqlite" + "github.com/planetary-social/nos-event-service/service/app" + "github.com/planetary-social/nos-event-service/service/config" + "github.com/planetary-social/nos-event-service/service/domain" + "github.com/planetary-social/nos-event-service/service/domain/relays" + "github.com/planetary-social/nos-event-service/service/ports/http" + memorypubsub2 "github.com/planetary-social/nos-event-service/service/ports/memorypubsub" + "github.com/planetary-social/nos-event-service/service/ports/sqlitepubsub" +) + +// Injectors from wire.go: + +func BuildService(contextContext context.Context, configConfig config.Config) (Service, func(), error) { + logger, err := newLogger(configConfig) + if err != nil { + return Service{}, nil, err + } + db, cleanup, err := newSqliteDB(configConfig, logger) + if err != nil { + return Service{}, nil, err + } + diBuildTransactionSqliteAdaptersDependencies := buildTransactionSqliteAdaptersDependencies{ + Logger: logger, + } + genericAdaptersFactoryFn := newAdaptersFactoryFn(diBuildTransactionSqliteAdaptersDependencies) + genericTransactionProvider := sqlite.NewTransactionProvider(db, genericAdaptersFactoryFn) + prometheusPrometheus, err := prometheus.NewPrometheus(logger) + if err != nil { + cleanup() + return Service{}, nil, err + } + saveReceivedEventHandler := app.NewSaveReceivedEventHandler(genericTransactionProvider, logger, prometheusPrometheus) + relaysExtractor := domain.NewRelaysExtractor(logger) + processSavedEventHandler := app.NewProcessSavedEventHandler(genericTransactionProvider, relaysExtractor, logger, prometheusPrometheus) + application := app.Application{ + SaveReceivedEvent: saveReceivedEventHandler, + ProcessSavedEvent: processSavedEventHandler, + } + server := http.NewServer(configConfig, logger, application, prometheusPrometheus) + bootstrapRelaySource := relays.NewBootstrapRelaySource() + mockRelaySource := app.NewMockRelaySource() + relayConnections := relays.NewRelayConnections(contextContext, logger, prometheusPrometheus) + receivedEventPubSub := memorypubsub.NewReceivedEventPubSub() + downloader := app.NewDownloader(bootstrapRelaySource, mockRelaySource, relayConnections, receivedEventPubSub, logger) + receivedEventSubscriber := memorypubsub2.NewReceivedEventSubscriber(receivedEventPubSub, saveReceivedEventHandler, logger) + pubSub := sqlite.NewPubSub(db, logger) + subscriber := sqlite.NewSubscriber(pubSub, db) + eventSavedEventSubscriber := sqlitepubsub.NewEventSavedEventSubscriber(processSavedEventHandler, subscriber, logger, prometheusPrometheus) + migrationsStorage, err := sqlite.NewMigrationsStorage(db) + if err != nil { + cleanup() + return Service{}, nil, err + } + runner := migrations.NewRunner(migrationsStorage, logger) + migrationFns := sqlite.NewMigrationFns(db, pubSub) + migrationsMigrations, err := sqlite.NewMigrations(migrationFns) + if err != nil { + cleanup() + return Service{}, nil, err + } + loggingMigrationsProgressCallback := adapters.NewLoggingMigrationsProgressCallback(logger) + service := NewService(application, server, downloader, receivedEventSubscriber, eventSavedEventSubscriber, runner, migrationsMigrations, loggingMigrationsProgressCallback) + return service, func() { + cleanup() + }, nil +} + +func BuildTestAdapters(contextContext context.Context, tb testing.TB) (sqlite.TestedItems, func(), error) { + configConfig, err := newTestAdaptersConfig(tb) + if err != nil { + return sqlite.TestedItems{}, nil, err + } + logger, err := newLogger(configConfig) + if err != nil { + return sqlite.TestedItems{}, nil, err + } + db, cleanup, err := newSqliteDB(configConfig, logger) + if err != nil { + return sqlite.TestedItems{}, nil, err + } + diBuildTransactionSqliteAdaptersDependencies := buildTransactionSqliteAdaptersDependencies{ + Logger: logger, + } + genericAdaptersFactoryFn := newTestAdaptersFactoryFn(diBuildTransactionSqliteAdaptersDependencies) + genericTransactionProvider := sqlite.NewTestTransactionProvider(db, genericAdaptersFactoryFn) + pubSub := sqlite.NewPubSub(db, logger) + subscriber := sqlite.NewSubscriber(pubSub, db) + migrationsStorage, err := sqlite.NewMigrationsStorage(db) + if err != nil { + cleanup() + return sqlite.TestedItems{}, nil, err + } + runner := migrations.NewRunner(migrationsStorage, logger) + migrationFns := sqlite.NewMigrationFns(db, pubSub) + migrationsMigrations, err := sqlite.NewMigrations(migrationFns) + if err != nil { + cleanup() + return sqlite.TestedItems{}, nil, err + } + loggingMigrationsProgressCallback := adapters.NewLoggingMigrationsProgressCallback(logger) + testedItems := sqlite.TestedItems{ + TransactionProvider: genericTransactionProvider, + Subscriber: subscriber, + MigrationsStorage: migrationsStorage, + PubSub: pubSub, + MigrationsRunner: runner, + Migrations: migrationsMigrations, + MigrationsProgressCallback: loggingMigrationsProgressCallback, + } + return testedItems, func() { + cleanup() + }, nil +} + +func buildTransactionSqliteAdapters(db *sql.DB, tx *sql.Tx, diBuildTransactionSqliteAdaptersDependencies buildTransactionSqliteAdaptersDependencies) (app.Adapters, error) { + eventRepository, err := sqlite.NewEventRepository(tx) + if err != nil { + return app.Adapters{}, err + } + logger := diBuildTransactionSqliteAdaptersDependencies.Logger + pubSub := sqlite.NewPubSub(db, logger) + publisher := sqlite.NewPublisher(pubSub, tx) + appAdapters := app.Adapters{ + Events: eventRepository, + Publisher: publisher, + } + return appAdapters, nil +} + +func buildTestTransactionSqliteAdapters(db *sql.DB, tx *sql.Tx, diBuildTransactionSqliteAdaptersDependencies buildTransactionSqliteAdaptersDependencies) (sqlite.TestAdapters, error) { + eventRepository, err := sqlite.NewEventRepository(tx) + if err != nil { + return sqlite.TestAdapters{}, err + } + logger := diBuildTransactionSqliteAdaptersDependencies.Logger + pubSub := sqlite.NewPubSub(db, logger) + publisher := sqlite.NewPublisher(pubSub, tx) + testAdapters := sqlite.TestAdapters{ + EventRepository: eventRepository, + Publisher: publisher, + } + return testAdapters, nil +} + +// wire.go: + +func newTestAdaptersConfig(tb testing.TB) (config.Config, error) { + return config.NewConfig(fixtures.SomeString(), config.EnvironmentDevelopment, logging.LevelDebug, false, fixtures.SomeString(), nil, fixtures.SomeFile(tb)) +} + +type buildTransactionSqliteAdaptersDependencies struct { + Logger logging.Logger +} + +var downloaderSet = wire.NewSet(app.NewDownloader, relays.NewBootstrapRelaySource, wire.Bind(new(app.BootstrapRelaySource), new(*relays.BootstrapRelaySource)), app.NewMockRelaySource, wire.Bind(new(app.RelaySource), new(*app.MockRelaySource)), relays.NewRelayConnections, wire.Bind(new(app.RelayConnections), new(*relays.RelayConnections))) + +var domainSet = wire.NewSet(domain.NewRelaysExtractor, wire.Bind(new(app.RelaysExtractor), new(*domain.RelaysExtractor))) diff --git a/cmd/event-service/main.go b/cmd/event-service/main.go new file mode 100644 index 0000000..2e69eb8 --- /dev/null +++ b/cmd/event-service/main.go @@ -0,0 +1,39 @@ +package main + +import ( + "context" + "fmt" + "os" + + "github.com/boreq/errors" + "github.com/planetary-social/nos-event-service/cmd/event-service/di" + configadapters "github.com/planetary-social/nos-event-service/service/adapters/config" +) + +func main() { + if err := run(); err != nil { + fmt.Printf("error: %s\n", err) + os.Exit(1) + } +} + +func run() error { + ctx := context.Background() + + conf, err := configadapters.NewEnvironmentConfigLoader().Load() + if err != nil { + return errors.Wrap(err, "error creating a config") + } + + service, cleanup, err := di.BuildService(ctx, conf) + if err != nil { + return errors.Wrap(err, "error building a service") + } + defer cleanup() + + if err := service.ExecuteMigrations(ctx); err != nil { + return errors.Wrap(err, "error executing migrations") + } + + return service.Run(ctx) +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..0ea940c --- /dev/null +++ b/go.mod @@ -0,0 +1,83 @@ +module github.com/planetary-social/nos-event-service + +go 1.21 + +require ( + github.com/ThreeDotsLabs/watermill v1.3.1 + github.com/ThreeDotsLabs/watermill-googlecloud v1.0.13 + github.com/boreq/errors v0.1.0 + github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 + github.com/google/wire v0.5.0 + github.com/gorilla/websocket v1.5.0 + github.com/hashicorp/go-multierror v1.1.1 + github.com/mattn/go-sqlite3 v1.14.18 + github.com/nbd-wtf/go-nostr v0.18.10 + github.com/oklog/ulid/v2 v2.1.0 + github.com/prometheus/client_golang v1.16.0 + github.com/rs/zerolog v1.29.1 + github.com/sirupsen/logrus v1.9.3 + github.com/stretchr/testify v1.8.4 + google.golang.org/api v0.123.0 +) + +require ( + cloud.google.com/go v0.110.2 // indirect + cloud.google.com/go/compute v1.19.0 // indirect + cloud.google.com/go/compute/metadata v0.2.3 // indirect + cloud.google.com/go/iam v0.13.0 // indirect + cloud.google.com/go/longrunning v0.4.2 // indirect + cloud.google.com/go/pubsub v1.30.0 // indirect + github.com/beorn7/perks v1.0.1 // indirect + github.com/btcsuite/btcd/btcec/v2 v2.2.0 // indirect + github.com/btcsuite/btcd/btcutil v1.1.3 // indirect + github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1 // indirect + github.com/cenkalti/backoff/v3 v3.2.2 // indirect + github.com/cespare/xxhash/v2 v2.2.0 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/decred/dcrd/crypto/blake256 v1.0.0 // indirect + github.com/gobwas/httphead v0.1.0 // indirect + github.com/gobwas/pool v0.2.1 // indirect + github.com/gobwas/ws v1.2.0 // indirect + github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect + github.com/golang/protobuf v1.5.3 // indirect + github.com/google/go-cmp v0.5.9 // indirect + github.com/google/s2a-go v0.1.3 // indirect + github.com/google/subcommands v1.0.1 // indirect + github.com/google/uuid v1.3.0 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.2.3 // indirect + github.com/googleapis/gax-go/v2 v2.8.0 // indirect + github.com/hashicorp/errwrap v1.1.0 // indirect + github.com/josharian/intern v1.0.0 // indirect + github.com/kr/text v0.2.0 // indirect + github.com/lithammer/shortuuid/v3 v3.0.7 // indirect + github.com/mailru/easyjson v0.7.7 // indirect + github.com/mattn/go-colorable v0.1.12 // indirect + github.com/mattn/go-isatty v0.0.14 // indirect + github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect + github.com/oklog/ulid v1.3.1 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/prometheus/client_model v0.3.0 // indirect + github.com/prometheus/common v0.42.0 // indirect + github.com/prometheus/procfs v0.10.1 // indirect + github.com/puzpuzpuz/xsync v1.5.2 // indirect + github.com/rogpeppe/go-internal v1.9.0 // indirect + github.com/tidwall/gjson v1.14.4 // indirect + github.com/tidwall/match v1.1.1 // indirect + github.com/tidwall/pretty v1.2.0 // indirect + go.opencensus.io v0.24.0 // indirect + golang.org/x/crypto v0.7.0 // indirect + golang.org/x/exp v0.0.0-20221106115401-f9659909a136 // indirect + golang.org/x/mod v0.8.0 // indirect + golang.org/x/net v0.10.0 // indirect + golang.org/x/oauth2 v0.8.0 // indirect + golang.org/x/sync v0.2.0 // indirect + golang.org/x/sys v0.8.0 // indirect + golang.org/x/text v0.9.0 // indirect + golang.org/x/tools v0.6.0 // indirect + google.golang.org/appengine v1.6.7 // indirect + google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 // indirect + google.golang.org/grpc v1.55.0 // indirect + google.golang.org/protobuf v1.30.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..e373163 --- /dev/null +++ b/go.sum @@ -0,0 +1,365 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.110.2 h1:sdFPBr6xG9/wkBbfhmUz/JmZC7X6LavQgcrVINrKiVA= +cloud.google.com/go v0.110.2/go.mod h1:k04UEeEtb6ZBRTv3dZz4CeJC3jKGxyhl0sAiVVquxiw= +cloud.google.com/go/compute v1.19.0 h1:+9zda3WGgW1ZSTlVppLCYFIr48Pa35q1uG2N1itbCEQ= +cloud.google.com/go/compute v1.19.0/go.mod h1:rikpw2y+UMidAe9tISo04EHNOIf42RLYF/q8Bs93scU= +cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY= +cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA= +cloud.google.com/go/iam v0.13.0 h1:+CmB+K0J/33d0zSQ9SlFWUeCCEn5XJA0ZMZ3pHE9u8k= +cloud.google.com/go/iam v0.13.0/go.mod h1:ljOg+rcNfzZ5d6f1nAUJ8ZIxOaZUVoS14bKCtaLZ/D0= +cloud.google.com/go/kms v1.10.1 h1:7hm1bRqGCA1GBRQUrp831TwJ9TWhP+tvLuP497CQS2g= +cloud.google.com/go/longrunning v0.4.2 h1:WDKiiNXFTaQ6qz/G8FCOkuY9kJmOJGY67wPUC1M2RbE= +cloud.google.com/go/longrunning v0.4.2/go.mod h1:OHrnaYyLUV6oqwh0xiS7e5sLQhP1m0QU9R+WhGDMgIQ= +cloud.google.com/go/pubsub v1.30.0 h1:vCge8m7aUKBJYOgrZp7EsNDf6QMd2CAlXZqWTn3yq6s= +cloud.google.com/go/pubsub v1.30.0/go.mod h1:qWi1OPS0B+b5L+Sg6Gmc9zD1Y+HaM0MdUr7LsupY1P4= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/ThreeDotsLabs/watermill v1.3.1 h1:Fm+K9soLPEO/N2U90OkdwoyrIm4X8YsCDPxmuyniOR8= +github.com/ThreeDotsLabs/watermill v1.3.1/go.mod h1:zn/7F0TGOr1K/RX7bFbVxii6p1abOMLllAMpVpKinQg= +github.com/ThreeDotsLabs/watermill-googlecloud v1.0.13 h1:MueV70SYuc9lt0XeJaVlR4Y1MzlMcZsZa/pOqsMx09I= +github.com/ThreeDotsLabs/watermill-googlecloud v1.0.13/go.mod h1:HfJGTfrFonSoztBGy4RGFlRXy6I8Fa0op50Yno6buJI= +github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII= +github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/boreq/errors v0.1.0 h1:aJIXv9JnyR5KtxFpQ8/AiblH3nfYmr1e1yoTze/5A1k= +github.com/boreq/errors v0.1.0/go.mod h1:B3dsXzhYvfgUXp7ViU/moPYM4PojgQ9MiQ21uvY6qqQ= +github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ= +github.com/btcsuite/btcd v0.22.0-beta.0.20220111032746-97732e52810c/go.mod h1:tjmYdS6MLJ5/s0Fj4DbLgSbDHbEqLJrtnHecBFkdz5M= +github.com/btcsuite/btcd v0.23.0/go.mod h1:0QJIIN1wwIXF/3G/m87gIwGniDMDQqjVn4SZgnFpsYY= +github.com/btcsuite/btcd/btcec/v2 v2.1.0/go.mod h1:2VzYrv4Gm4apmbVVsSq5bqf1Ec8v56E48Vt0Y/umPgA= +github.com/btcsuite/btcd/btcec/v2 v2.1.3/go.mod h1:ctjw4H1kknNJmRN4iP1R7bTQ+v3GJkZBd6mui8ZsAZE= +github.com/btcsuite/btcd/btcec/v2 v2.2.0 h1:fzn1qaOt32TuLjFlkzYSsBC35Q3KUjT1SwPxiMSCF5k= +github.com/btcsuite/btcd/btcec/v2 v2.2.0/go.mod h1:U7MHm051Al6XmscBQ0BoNydpOTsFAn707034b5nY8zU= +github.com/btcsuite/btcd/btcutil v1.0.0/go.mod h1:Uoxwv0pqYWhD//tfTiipkxNfdhG9UrLwaeswfjfdF0A= +github.com/btcsuite/btcd/btcutil v1.1.0/go.mod h1:5OapHB7A2hBBWLm48mmw4MOHNJCcUBTwmWH/0Jn8VHE= +github.com/btcsuite/btcd/btcutil v1.1.3 h1:xfbtw8lwpp0G6NwSHb+UE67ryTFHJAiNuipusjXSohQ= +github.com/btcsuite/btcd/btcutil v1.1.3/go.mod h1:UR7dsSJzJUfMmFiiLlIrMq1lS9jh9EdCV7FStZSnpi0= +github.com/btcsuite/btcd/chaincfg/chainhash v1.0.0/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc= +github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1 h1:q0rUy8C/TYNBQS1+CGKw68tLOFYSNEs0TFnxxnS9+4U= +github.com/btcsuite/btcd/chaincfg/chainhash v1.0.1/go.mod h1:7SFka0XMvUgj3hfZtydOrQY2mwhPclbT2snogU7SQQc= +github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA= +github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg= +github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg= +github.com/btcsuite/goleveldb v0.0.0-20160330041536-7834afc9e8cd/go.mod h1:F+uVaaLLH7j4eDXPRvw78tMflu7Ie2bzYOH4Y8rRKBY= +github.com/btcsuite/goleveldb v1.0.0/go.mod h1:QiK9vBlgftBg6rWQIj6wFzbPfRjiykIEhBH4obrXJ/I= +github.com/btcsuite/snappy-go v0.0.0-20151229074030-0bdef8d06723/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc= +github.com/btcsuite/snappy-go v1.0.0/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc= +github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY= +github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs= +github.com/cenkalti/backoff/v3 v3.2.2 h1:cfUAAO3yvKMYKPrvhDuHSwQnhZNk/RMHKdZqKTxfm6M= +github.com/cenkalti/backoff/v3 v3.2.2/go.mod h1:cIeZDE3IrqwwJl6VUwCN6trj1oXrTS4rc0ij+ULvLYs= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= +github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= +github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0= +github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 h1:YLtO71vCjJRCBcrPMtQ9nqBsqpA1m5sE92cU+pd5Mcc= +github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeCxkaw7y45JueMRL4DIyJDKs= +github.com/decred/dcrd/lru v1.0.0/go.mod h1:mxKOwFd7lFjN2GZYsiz/ecgqR6kkYAl+0pz0tEMk218= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU= +github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM= +github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og= +github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= +github.com/gobwas/ws v1.2.0 h1:u0p9s3xLYpZCA1z5JgCkMeB34CKCMMQbM+G8Ii7YD0I= +github.com/gobwas/ws v1.2.0/go.mod h1:hRKAFb8wOxFROYNsT1bqfWnhX+b5MFeJM9r2ZSwg/KY= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= +github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg= +github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= +github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/s2a-go v0.1.3 h1:FAgZmpLl/SXurPEZyCMPBIiiYeTbqfjlbdnCNTAkbGE= +github.com/google/s2a-go v0.1.3/go.mod h1:Ej+mSEMGRnqRzjc7VtF+jdBwYG5fuJfiZ8ELkjEwM0A= +github.com/google/subcommands v1.0.1 h1:/eqq+otEXm5vhfBrbREPCSVQbvofip6kIz+mX5TUH7k= +github.com/google/subcommands v1.0.1/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk= +github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/wire v0.5.0 h1:I7ELFeVBr3yfPIcc8+MWvrjk+3VjbcSzoXm3JVa+jD8= +github.com/google/wire v0.5.0/go.mod h1:ngWDr9Qvq3yZA10YrxfyGELY/AFWGVpy9c1LTRi1EoU= +github.com/googleapis/enterprise-certificate-proxy v0.2.3 h1:yk9/cqRKtT9wXZSsRH9aurXEpJX+U6FLtpYTdC3R06k= +github.com/googleapis/enterprise-certificate-proxy v0.2.3/go.mod h1:AwSRAtLfXpU5Nm3pW+v7rGDHp09LsPtGY9MduiEsR9k= +github.com/googleapis/gax-go/v2 v2.8.0 h1:UBtEZqx1bjXtOQ5BVTkuYghXrr3N4V123VKJK67vJZc= +github.com/googleapis/gax-go/v2 v2.8.0/go.mod h1:4orTrqY6hXxxaUL4LHIPl6lGo8vAE38/qKbhSAKP6QI= +github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= +github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= +github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= +github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= +github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= +github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= +github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= +github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ= +github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/lithammer/shortuuid/v3 v3.0.7 h1:trX0KTHy4Pbwo/6ia8fscyHoGA+mf1jWbPJVuvyJQQ8= +github.com/lithammer/shortuuid/v3 v3.0.7/go.mod h1:vMk8ke37EmiewwolSO1NLW8vP4ZaKlRuDIi8tWWmAts= +github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= +github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40= +github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= +github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y= +github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= +github.com/mattn/go-sqlite3 v1.14.18 h1:JL0eqdCOq6DJVNPSvArO/bIV9/P7fbGrV00LZHc+5aI= +github.com/mattn/go-sqlite3 v1.14.18/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg= +github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo= +github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4= +github.com/nbd-wtf/go-nostr v0.18.10 h1:9kD9U1QkAvqW4CH4CdKagY2wwyZoH80tO/voMZiSisg= +github.com/nbd-wtf/go-nostr v0.18.10/go.mod h1:F9y6+M8askJCjilLgMC3rD0moA6UtG1MCnyClNYXeys= +github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= +github.com/oklog/ulid v1.3.1 h1:EGfNDEx6MqHz8B3uNV6QAib1UR2Lm97sHi3ocA6ESJ4= +github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= +github.com/oklog/ulid/v2 v2.1.0 h1:+9lhoxAP56we25tyYETBBY1YLA2SaoLvUFgrP2miPJU= +github.com/oklog/ulid/v2 v2.1.0/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= +github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= +github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= +github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v1.16.0 h1:yk/hx9hDbrGHovbci4BY+pRMfSuuat626eFsHb7tmT8= +github.com/prometheus/client_golang v1.16.0/go.mod h1:Zsulrv/L9oM40tJ7T815tM89lFEugiJ9HzIqaAx4LKc= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.3.0 h1:UBgGFHqYdG/TPFD1B1ogZywDqEkwp3fBMvqdiQ7Xew4= +github.com/prometheus/client_model v0.3.0/go.mod h1:LDGWKZIo7rky3hgvBe+caln+Dr3dPggB5dvjtD7w9+w= +github.com/prometheus/common v0.42.0 h1:EKsfXEYo4JpWMHH5cg+KOUWeuJSov1Id8zGR8eeI1YM= +github.com/prometheus/common v0.42.0/go.mod h1:xBwqVerjNdUDjgODMpudtOMwlOwf2SaTr1yjz4b7Zbc= +github.com/prometheus/procfs v0.10.1 h1:kYK1Va/YMlutzCGazswoHKo//tZVlFpKYh+PymziUAg= +github.com/prometheus/procfs v0.10.1/go.mod h1:nwNm2aOCAYw8uTR/9bWRREkZFxAUcWzPHWJq+XBB/FM= +github.com/puzpuzpuz/xsync v1.5.2 h1:yRAP4wqSOZG+/4pxJ08fPTwrfL0IzE/LKQ/cw509qGY= +github.com/puzpuzpuz/xsync v1.5.2/go.mod h1:K98BYhX3k1dQ2M63t1YNVDanbwUPmBCAhNmVrrxfiGg= +github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= +github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= +github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= +github.com/rs/zerolog v1.29.1 h1:cO+d60CHkknCbvzEWxP0S9K6KqyTjrCNUy1LdQLCGPc= +github.com/rs/zerolog v1.29.1/go.mod h1:Le6ESbR7hc+DP6Lt1THiV8CQSdkkNrd3R0XbEgp3ZBU= +github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= +github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7/go.mod h1:q4W45IWZaF22tdD+VEXcAWRA037jwmWEB5VWYORlTpc= +github.com/tidwall/gjson v1.14.4 h1:uo0p8EbA09J7RQaflQ1aBRffTR7xedD2bcIVSYxLnkM= +github.com/tidwall/gjson v1.14.4/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= +github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= +github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs= +github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= +go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= +go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= +golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20220314234659-1baeb1ce4c0b/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.7.0 h1:AvwMYaRytfdeVt3u6mLaxYtErKYjxA2OXjJ1HHq6t3A= +golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20221106115401-f9659909a136 h1:Fq7F/w7MAa1KJ5bt2aJ62ihqp9HDcRuyILskkpIAurw= +golang.org/x/exp v0.0.0-20221106115401-f9659909a136/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0 h1:LUYupSeNrTNCGzR/hVBk2NHZO4hXcVaW1k4Qx7rjPx8= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200813134508-3edf25e44fcc/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.8.0 h1:6dkIjl3j3LtZ/O3sTgZTMsLKSftL/B8Zgq4huOIIUu8= +golang.org/x/oauth2 v0.8.0/go.mod h1:yr7u4HXZRm1R1kBWqr/xKNqewf0plRYoB7sla+BCIXE= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.2.0 h1:PUR+T4wwASmuSTYdKjYHI5TD22Wy5ogLU5qZCOLxBrI= +golang.org/x/sync v0.2.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200814200057-3d37ad5750ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= +golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190422233926-fe54fb35175b/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.6.0 h1:BOw41kyTf3PuCW1pVQf8+Cyg8pMlkYB1oo9iJ6D/lKM= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/api v0.123.0 h1:yHVU//vA+qkOhm4reEC9LtzHVUCN/IqqNRl1iQ9xE20= +google.golang.org/api v0.123.0/go.mod h1:gcitW0lvnyWjSp9nKxAbdHKIZ6vF4aajGueeslZOyms= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= +google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 h1:KpwkzHKEF7B9Zxg18WzOa7djJ+Ha5DzthMyZYQfEn2A= +google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= +google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= +google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.45.0/go.mod h1:lN7owxKUQEqMfSyQikvvk5tf/6zMPsrK+ONuO11+0rQ= +google.golang.org/grpc v1.55.0 h1:3Oj82/tFSCeUrRTg/5E/7d/W5A1tj6Ky1ABAuZuv5ag= +google.golang.org/grpc v1.55.0/go.mod h1:iYEXKGkEBhg1PjZQvoYEVPTDkHo1/bjTnfwTeGONTY8= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng= +google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/internal/fixtures/fixtures.go b/internal/fixtures/fixtures.go new file mode 100644 index 0000000..129072b --- /dev/null +++ b/internal/fixtures/fixtures.go @@ -0,0 +1,165 @@ +package fixtures + +import ( + "context" + cryptorand "crypto/rand" + "encoding/hex" + "fmt" + "math/rand" + "os" + "testing" + + "github.com/nbd-wtf/go-nostr" + "github.com/planetary-social/nos-event-service/internal" + "github.com/planetary-social/nos-event-service/internal/logging" + "github.com/planetary-social/nos-event-service/service/domain" +) + +func somePrivateKeyHex() string { + return nostr.GeneratePrivateKey() +} + +func SomeKeyPair() (publicKey domain.PublicKey, secretKeyHex string) { + hex := somePrivateKeyHex() + + p, err := nostr.GetPublicKey(hex) + if err != nil { + panic(err) + } + v, err := domain.NewPublicKeyFromHex(p) + if err != nil { + panic(err) + } + return v, hex +} + +func SomeRelayAddress() domain.RelayAddress { + protocol := internal.RandomElement([]string{"ws", "wss"}) + address := fmt.Sprintf("%s://%s", protocol, SomeString()) + + v, err := domain.NewRelayAddress(address) + if err != nil { + panic(err) + } + return v +} + +func SomeString() string { + return randSeq(10) +} + +func SomeHexBytesOfLen(l int) string { + b := make([]byte, l) + n, err := cryptorand.Read(b) + if n != len(b) { + panic("short read") + } + if err != nil { + panic(err) + } + return hex.EncodeToString(b) +} + +func SomeError() error { + return fmt.Errorf("some error: %d", rand.Int()) +} + +func SomeEvent() domain.Event { + libevent := nostr.Event{ + Kind: internal.RandomElement([]domain.EventKind{domain.EventKindContacts, domain.EventKindNote, domain.EventKindMetadata}).Int(), + Tags: []nostr.Tag{ + {SomeString(), SomeString()}, + }, + Content: SomeString(), + } + + _, sk := SomeKeyPair() + err := libevent.Sign(sk) + if err != nil { + panic(err) + } + + event, err := domain.NewEvent(libevent) + if err != nil { + panic(err) + } + + return event +} + +func Event(kind domain.EventKind, tags []domain.EventTag, content string) domain.Event { + libevent := nostr.Event{ + Kind: kind.Int(), + Content: content, + } + + for _, tag := range tags { + libevent.Tags = append(libevent.Tags, nostr.Tag{tag.Name().String(), tag.FirstValue()}) + } + + _, sk := SomeKeyPair() + err := libevent.Sign(sk) + if err != nil { + panic(err) + } + + event, err := domain.NewEvent(libevent) + if err != nil { + panic(err) + } + + return event +} + +func SomeFile(t testing.TB) string { + file, err := os.CreateTemp("", "nos-events-test") + if err != nil { + t.Fatal(err) + } + + cleanup := func() { + err := os.Remove(file.Name()) + if err != nil { + t.Fatal(err) + } + } + t.Cleanup(cleanup) + + return file.Name() +} + +func SomeEventID() domain.EventId { + return domain.MustNewEventId(SomeHexBytesOfLen(32)) +} + +func TestContext(t testing.TB) context.Context { + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + return ctx +} + +func TestLogger(t testing.TB) logging.Logger { + return logging.NewSystemLogger(logging.NewTestingLoggingSystem(t), "test") +} + +func SomeBytesOfLen(l int) []byte { + b := make([]byte, l) + n, err := cryptorand.Read(b) + if n != len(b) { + panic("short read") + } + if err != nil { + panic(err) + } + return b +} + +var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") + +func randSeq(n int) string { + b := make([]rune, n) + for i := range b { + b[i] = letters[rand.Intn(len(letters))] + } + return string(b) +} diff --git a/internal/logging/log.go b/internal/logging/log.go new file mode 100644 index 0000000..d164189 --- /dev/null +++ b/internal/logging/log.go @@ -0,0 +1,192 @@ +package logging + +const ( + loggerFieldName = "name" + loggerFieldError = "error" +) + +type Level int + +const ( + LevelTrace Level = iota + LevelDebug + LevelError + LevelDisabled +) + +type Logger interface { + New(name string) Logger + WithError(err error) Logger + WithField(key string, v any) Logger + + Error() Entry + Debug() Entry + Trace() Entry +} + +type Entry interface { + WithError(err error) Entry + WithField(key string, v any) Entry + Message(msg string) +} + +type LoggingSystem interface { + EnabledLevel() Level + Error() LoggingSystemEntry + Debug() LoggingSystemEntry + Trace() LoggingSystemEntry +} + +type LoggingSystemEntry interface { + WithField(key string, v any) LoggingSystemEntry + Message(msg string) +} + +type SystemLogger struct { + fields map[string]any + logger LoggingSystem +} + +func NewSystemLogger(logger LoggingSystem, name string) Logger { + if logger.EnabledLevel() >= LevelDisabled { + return NewDevNullLogger() + } + return newSystemLogger(logger, map[string]any{loggerFieldName: name}) +} + +func newSystemLogger(logger LoggingSystem, fields map[string]any) SystemLogger { + newLogger := SystemLogger{ + fields: make(map[string]any), + + logger: logger, + } + + for k, v := range fields { + newLogger.fields[k] = v + } + + return newLogger +} + +func (l SystemLogger) Error() Entry { + if l.logger.EnabledLevel() > LevelError { + return newDevNullLoggerEntry() + } + return l.withFields(newEntry(l.logger.Error())) +} + +func (l SystemLogger) Debug() Entry { + if l.logger.EnabledLevel() > LevelDebug { + return newDevNullLoggerEntry() + } + return l.withFields(newEntry(l.logger.Debug())) +} + +func (l SystemLogger) Trace() Entry { + if l.logger.EnabledLevel() > LevelTrace { + return newDevNullLoggerEntry() + } + return l.withFields(newEntry(l.logger.Trace())) +} + +func (l SystemLogger) New(name string) Logger { + newLogger := newSystemLogger(l.logger, l.fields) + v, okExists := l.fields[loggerFieldName] + if okExists { + if stringV, okType := v.(string); okType { + newLogger.fields[loggerFieldName] = stringV + "." + name + return newLogger + } + return newLogger + } + newLogger.fields[loggerFieldName] = name + return newLogger +} + +func (l SystemLogger) WithError(err error) Logger { + newLogger := newSystemLogger(l.logger, l.fields) + newLogger.fields[loggerFieldError] = err + return newLogger +} + +func (l SystemLogger) WithField(key string, v any) Logger { + newLogger := newSystemLogger(l.logger, l.fields) + newLogger.fields[key] = v + return newLogger +} + +func (l SystemLogger) withFields(entry Entry) Entry { + for k, v := range l.fields { + entry = entry.WithField(k, v) + } + return entry +} + +type entry struct { + loggingSystemEntry LoggingSystemEntry +} + +func newEntry(loggingSystemEntry LoggingSystemEntry) entry { + return entry{loggingSystemEntry: loggingSystemEntry} +} + +func (e entry) WithError(err error) Entry { + return newEntry(e.loggingSystemEntry.WithField(loggerFieldError, err)) +} + +func (e entry) WithField(key string, v any) Entry { + return newEntry(e.loggingSystemEntry.WithField(key, v)) +} + +func (e entry) Message(msg string) { + e.loggingSystemEntry.Message(msg) +} + +type DevNullLogger struct { +} + +func NewDevNullLogger() DevNullLogger { + return DevNullLogger{} +} + +func (d DevNullLogger) New(name string) Logger { + return d +} + +func (d DevNullLogger) WithError(err error) Logger { + return d +} + +func (d DevNullLogger) WithField(key string, v any) Logger { + return d +} + +func (d DevNullLogger) Error() Entry { + return newDevNullLoggerEntry() +} + +func (d DevNullLogger) Debug() Entry { + return newDevNullLoggerEntry() +} + +func (d DevNullLogger) Trace() Entry { + return newDevNullLoggerEntry() +} + +type devNullLoggerEntry struct { +} + +func newDevNullLoggerEntry() devNullLoggerEntry { + return devNullLoggerEntry{} +} + +func (d devNullLoggerEntry) WithError(err error) Entry { + return d +} + +func (d devNullLoggerEntry) WithField(key string, v any) Entry { + return d +} + +func (d devNullLoggerEntry) Message(msg string) { +} diff --git a/internal/logging/log_test.go b/internal/logging/log_test.go new file mode 100644 index 0000000..9c3a16a --- /dev/null +++ b/internal/logging/log_test.go @@ -0,0 +1,72 @@ +package logging_test + +import ( + "io" + "testing" + + "github.com/planetary-social/nos-event-service/internal/logging" + "github.com/rs/zerolog" + "github.com/sirupsen/logrus" +) + +func BenchmarkContextLogger(b *testing.B) { + benchCases := []struct { + Name string + GetLoggingSystem func(tb testing.TB) logging.LoggingSystem + }{ + { + Name: "dev_null", + GetLoggingSystem: func(tb testing.TB) logging.LoggingSystem { + return logging.NewDevNullLoggingSystem() + }, + }, + { + Name: "logrus", + GetLoggingSystem: func(tb testing.TB) logging.LoggingSystem { + logrusLogger := logrus.New() + logrusLogger.SetLevel(logrus.TraceLevel) + logrusLogger.SetOutput(io.Discard) + return logging.NewLogrusLoggingSystem(logrusLogger) + }, + }, + { + Name: "logrus_disabled", + GetLoggingSystem: func(tb testing.TB) logging.LoggingSystem { + logrusLogger := logrus.New() + logrusLogger.SetLevel(logrus.ErrorLevel) + logrusLogger.SetOutput(io.Discard) + return logging.NewLogrusLoggingSystem(logrusLogger) + }, + }, + { + Name: "zerolog", + GetLoggingSystem: func(tb testing.TB) logging.LoggingSystem { + zerologLogger := zerolog.New(io.Discard).Level(zerolog.TraceLevel) + return logging.NewZerologLoggingSystem(zerologLogger) + }, + }, + { + Name: "zerolog_disabled", + GetLoggingSystem: func(tb testing.TB) logging.LoggingSystem { + zerologLogger := zerolog.New(io.Discard).Level(zerolog.Disabled) + return logging.NewZerologLoggingSystem(zerologLogger) + }, + }, + } + + for _, benchCase := range benchCases { + b.Run(benchCase.Name, func(b *testing.B) { + logger := logging.NewSystemLogger(benchCase.GetLoggingSystem(b), "bench") + + b.ReportAllocs() + + for i := 0; i < b.N; i++ { + logger.Trace(). + WithField("field1", 123). + WithField("field2", "somestring"). + WithField("field3", struct{ string }{"object"}). + Message("some message") + } + }) + } +} diff --git a/internal/logging/system_dev_null.go b/internal/logging/system_dev_null.go new file mode 100644 index 0000000..d386cf6 --- /dev/null +++ b/internal/logging/system_dev_null.go @@ -0,0 +1,38 @@ +package logging + +type DevNullLoggingSystem struct { +} + +func NewDevNullLoggingSystem() DevNullLoggingSystem { + return DevNullLoggingSystem{} +} + +func (d DevNullLoggingSystem) EnabledLevel() Level { + return LevelDisabled +} + +func (d DevNullLoggingSystem) Error() LoggingSystemEntry { + return newDevNullEntry() +} + +func (d DevNullLoggingSystem) Debug() LoggingSystemEntry { + return newDevNullEntry() +} + +func (d DevNullLoggingSystem) Trace() LoggingSystemEntry { + return newDevNullEntry() +} + +type devNullEntry struct { +} + +func newDevNullEntry() devNullEntry { + return devNullEntry{} +} + +func (d devNullEntry) WithField(string, any) LoggingSystemEntry { + return d +} + +func (d devNullEntry) Message(string) { +} diff --git a/internal/logging/system_logrus.go b/internal/logging/system_logrus.go new file mode 100644 index 0000000..a689bfc --- /dev/null +++ b/internal/logging/system_logrus.go @@ -0,0 +1,83 @@ +package logging + +import ( + "github.com/sirupsen/logrus" +) + +type LogrusLoggingSystem struct { + logger *logrus.Logger +} + +func NewLogrusLoggingSystem(logger *logrus.Logger) LogrusLoggingSystem { + return LogrusLoggingSystem{ + logger: logger, + } +} + +func (t LogrusLoggingSystem) EnabledLevel() Level { + switch t.logger.GetLevel() { + case logrus.TraceLevel: + return LevelTrace + case logrus.DebugLevel: + return LevelDebug + default: + return LevelError + } +} + +func (l LogrusLoggingSystem) Error() LoggingSystemEntry { + return newLogrusEntry(l.logger, logrusLogError) +} + +func (l LogrusLoggingSystem) Debug() LoggingSystemEntry { + return newLogrusEntry(l.logger, logrusLogDebug) +} + +func (l LogrusLoggingSystem) Trace() LoggingSystemEntry { + return newLogrusEntry(l.logger, logrusLogTrace) +} + +type logrusEntry struct { + logger logrus.Ext1FieldLogger + fields map[string]any + logFn logrusLogFn +} + +func newLogrusEntry(logger logrus.Ext1FieldLogger, logFn logrusLogFn) *logrusEntry { + return &logrusEntry{ + logger: logger, + fields: make(map[string]any), + logFn: logFn, + } +} + +func (l logrusEntry) WithField(key string, v any) LoggingSystemEntry { + entry := newLogrusEntry(l.logger, l.logFn) + for k, v := range l.fields { + entry.fields[k] = v + } + entry.fields[key] = v + return entry +} + +func (l logrusEntry) Message(msg string) { + logger := l.logger + for k, v := range l.fields { + logger = logger.WithField(k, v) + } + l.logFn(logger, msg) +} + +type logrusLogFn func(logrus.Ext1FieldLogger, string) + +func logrusLogError(logger logrus.Ext1FieldLogger, s string) { + logger.Error(s) +} + +func logrusLogDebug(logger logrus.Ext1FieldLogger, s string) { + logger.Debug(s) +} + +func logrusLogTrace(logger logrus.Ext1FieldLogger, s string) { + logger.Trace(s) +} diff --git a/internal/logging/system_testing.go b/internal/logging/system_testing.go new file mode 100644 index 0000000..76d523a --- /dev/null +++ b/internal/logging/system_testing.go @@ -0,0 +1,51 @@ +package logging + +import ( + "fmt" + "testing" +) + +type TestingLoggingSystem struct { + tb testing.TB +} + +func NewTestingLoggingSystem(tb testing.TB) *TestingLoggingSystem { + return &TestingLoggingSystem{tb: tb} +} + +func (t TestingLoggingSystem) EnabledLevel() Level { + return LevelTrace +} + +func (t TestingLoggingSystem) Error() LoggingSystemEntry { + return newTestingEntry(t.tb.Log) +} + +func (t TestingLoggingSystem) Debug() LoggingSystemEntry { + return newTestingEntry(t.tb.Log) +} + +func (t TestingLoggingSystem) Trace() LoggingSystemEntry { + return newTestingEntry(t.tb.Log) +} + +type testingEntry struct { + log func(args ...any) +} + +func newTestingEntry(log func(args ...any)) *testingEntry { + return &testingEntry{log: log} +} + +func (t testingEntry) WithField(key string, v any) LoggingSystemEntry { + prev := t.log + return newTestingEntry(func(args ...any) { + tmp := []any{fmt.Sprintf("%s=%s", key, v)} + tmp = append(tmp, args...) + prev(tmp) + }) +} + +func (t testingEntry) Message(msg string) { + t.log(msg) +} diff --git a/internal/logging/system_zerolog.go b/internal/logging/system_zerolog.go new file mode 100644 index 0000000..80a5abe --- /dev/null +++ b/internal/logging/system_zerolog.go @@ -0,0 +1,57 @@ +package logging + +import ( + "github.com/rs/zerolog" +) + +type ZerologLoggingSystem struct { + logger zerolog.Logger +} + +func NewZerologLoggingSystem(logger zerolog.Logger) ZerologLoggingSystem { + logger.GetLevel() + return ZerologLoggingSystem{ + logger: logger, + } +} + +func (t ZerologLoggingSystem) EnabledLevel() Level { + switch t.logger.GetLevel() { + case zerolog.TraceLevel: + return LevelTrace + case zerolog.DebugLevel: + return LevelDebug + case zerolog.Disabled: + return LevelDisabled + default: + return LevelError + } +} + +func (l ZerologLoggingSystem) Error() LoggingSystemEntry { + return newZerologEntry(l.logger.Error()) +} + +func (l ZerologLoggingSystem) Debug() LoggingSystemEntry { + return newZerologEntry(l.logger.Error()) +} + +func (l ZerologLoggingSystem) Trace() LoggingSystemEntry { + return newZerologEntry(l.logger.Error()) +} + +type zerologEntry struct { + event *zerolog.Event +} + +func newZerologEntry(event *zerolog.Event) *zerologEntry { + return &zerologEntry{event: event} +} + +func (z zerologEntry) WithField(key string, v any) LoggingSystemEntry { + return newZerologEntry(z.event.Interface(key, v)) +} + +func (z zerologEntry) Message(msg string) { + z.event.Msg(msg) +} diff --git a/internal/logging/watermill.go b/internal/logging/watermill.go new file mode 100644 index 0000000..e2bea67 --- /dev/null +++ b/internal/logging/watermill.go @@ -0,0 +1,45 @@ +package logging + +import "github.com/ThreeDotsLabs/watermill" + +type WatermillAdapter struct { + logger Logger +} + +func NewWatermillAdapter(logger Logger) *WatermillAdapter { + return &WatermillAdapter{logger: logger} +} + +func (a WatermillAdapter) Error(msg string, err error, fields watermill.LogFields) { + a.withFields(a.logger.Error(), fields).WithError(err).Message(msg) +} + +func (a WatermillAdapter) Info(msg string, fields watermill.LogFields) { + a.withFields(a.logger.Debug(), fields).Message(msg) +} + +func (a WatermillAdapter) Debug(msg string, fields watermill.LogFields) { + a.withFields(a.logger.Debug(), fields).Message(msg) +} + +func (a WatermillAdapter) Trace(msg string, fields watermill.LogFields) { + a.withFields(a.logger.Trace(), fields).Message(msg) +} + +func (a WatermillAdapter) With(fields watermill.LogFields) watermill.LoggerAdapter { + return NewWatermillAdapter(a.loggerWithFields(a.logger, fields)) +} + +func (a WatermillAdapter) withFields(e Entry, fields watermill.LogFields) Entry { + for name, value := range fields { + e = e.WithField(name, value) + } + return e +} + +func (a WatermillAdapter) loggerWithFields(e Logger, fields watermill.LogFields) Logger { + for name, value := range fields { + e = e.WithField(name, value) + } + return e +} diff --git a/internal/pointer.go b/internal/pointer.go new file mode 100644 index 0000000..9901124 --- /dev/null +++ b/internal/pointer.go @@ -0,0 +1,5 @@ +package internal + +func Pointer[T any](v T) *T { + return &v +} diff --git a/internal/set.go b/internal/set.go new file mode 100644 index 0000000..cb70fd7 --- /dev/null +++ b/internal/set.go @@ -0,0 +1,54 @@ +package internal + +type Set[T comparable] struct { + values map[T]struct{} +} + +func NewEmptySet[T comparable]() *Set[T] { + return &Set[T]{ + values: make(map[T]struct{}), + } +} + +func NewSet[T comparable](values []T) *Set[T] { + v := NewEmptySet[T]() + for _, value := range values { + v.Put(value) + } + return v +} + +func (s *Set[T]) Contains(v T) bool { + _, ok := s.values[v] + return ok +} + +func (s *Set[T]) Put(v T) { + s.values[v] = struct{}{} +} + +func (s *Set[T]) PutMany(vs []T) { + for _, v := range vs { + s.Put(v) + } +} + +func (s *Set[T]) Clear() { + s.values = make(map[T]struct{}) +} + +func (s *Set[T]) Delete(v T) { + delete(s.values, v) +} + +func (s *Set[T]) List() []T { + var result []T + for v := range s.values { + result = append(result, v) + } + return result +} + +func (s *Set[T]) Len() int { + return len(s.values) +} diff --git a/internal/set_test.go b/internal/set_test.go new file mode 100644 index 0000000..1024829 --- /dev/null +++ b/internal/set_test.go @@ -0,0 +1,49 @@ +package internal + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestSet(t *testing.T) { + s := NewEmptySet[int]() + + require.False(t, s.Contains(0)) + require.Equal(t, 0, s.Len()) + require.Len(t, s.List(), 0) + + s.Put(0) + + require.True(t, s.Contains(0)) + require.Equal(t, 1, s.Len()) + require.Equal(t, []int{0}, s.List()) +} + +func TestSet_Delete(t *testing.T) { + s := NewEmptySet[int]() + + require.False(t, s.Contains(0)) + + s.Put(0) + + require.True(t, s.Contains(0)) + + s.Delete(0) + + require.False(t, s.Contains(0)) +} + +func TestSet_Clear(t *testing.T) { + s := NewEmptySet[int]() + + require.False(t, s.Contains(0)) + + s.Put(0) + + require.True(t, s.Contains(0)) + + s.Clear() + + require.False(t, s.Contains(0)) +} diff --git a/internal/slice.go b/internal/slice.go new file mode 100644 index 0000000..447464f --- /dev/null +++ b/internal/slice.go @@ -0,0 +1,13 @@ +package internal + +import "math/rand" + +func CopySlice[T any](slice []T) []T { + result := make([]T, len(slice)) + copy(result, slice) + return result +} + +func RandomElement[T any](slice []T) T { + return slice[rand.Intn(len(slice))] +} diff --git a/migrations/migrations.go b/migrations/migrations.go new file mode 100644 index 0000000..6b77640 --- /dev/null +++ b/migrations/migrations.go @@ -0,0 +1,239 @@ +package migrations + +import ( + "context" + "encoding/json" + "fmt" + + "github.com/boreq/errors" + "github.com/hashicorp/go-multierror" + "github.com/planetary-social/nos-event-service/internal" + "github.com/planetary-social/nos-event-service/internal/logging" +) + +type State map[string]string + +type SaveStateFunc func(state State) error + +// MigrationFunc is executed with the previously saved state. If the migration +// func is executed for the first time then the saved state will be an empty +// map. State is saved by calling the provided function. If a migration function +// returns an error it will be executed again. If a function doesn't return an +// error it should not be executed again. +type MigrationFunc func(ctx context.Context, state State, saveStateFunc SaveStateFunc) error + +type ProgressCallback interface { + // OnRunning is only called when a migration is actually being executed. + OnRunning(migrationIndex int, migrationsCount int) + + // OnError is called when the migration process for one of the migrations + // fails with an error. + OnError(migrationIndex int, migrationsCount int, err error) + + // OnDone is always called once all migrations were successfully executed + // even if no migrations were run. + OnDone(migrationsCount int) +} + +type Migration struct { + name string + fn MigrationFunc +} + +func NewMigration(name string, fn MigrationFunc) (Migration, error) { + if name == "" { + return Migration{}, errors.New("name is an empty string") + } + if fn == nil { + return Migration{}, errors.New("function is nil") + } + return Migration{name: name, fn: fn}, nil +} + +func MustNewMigration(name string, fn MigrationFunc) Migration { + v, err := NewMigration(name, fn) + if err != nil { + panic(err) + } + return v +} + +func (m Migration) Name() string { + return m.name +} + +func (m Migration) Fn() MigrationFunc { + return m.fn +} + +func (m Migration) IsZero() bool { + return m.fn == nil +} + +type Migrations struct { + migrations []Migration +} + +func NewMigrations(migrations []Migration) (Migrations, error) { + names := internal.NewEmptySet[string]() + for _, migration := range migrations { + if migration.IsZero() { + return Migrations{}, errors.New("zero value of migration") + } + + if names.Contains(migration.Name()) { + return Migrations{}, fmt.Errorf("duplicate name '%s'", migration.Name()) + } + names.Put(migration.Name()) + } + + return Migrations{migrations: migrations}, nil +} + +func MustNewMigrations(migrations []Migration) Migrations { + v, err := NewMigrations(migrations) + if err != nil { + panic(err) + } + return v +} + +func (m Migrations) List() []Migration { + return m.migrations +} + +func (m Migrations) Count() int { + return len(m.migrations) +} + +type Status struct { + s string +} + +var ( + StatusFailed = Status{"failed"} + StatusFinished = Status{"finished"} +) + +var ( + ErrStateNotFound = errors.New("state not found") + ErrStatusNotFound = errors.New("status not found") +) + +type Storage interface { + // LoadState returns ErrStateNotFound if state has not been saved yet. + LoadState(name string) (State, error) + SaveState(name string, state State) error + + // LoadStatus returns ErrStatusNotFound if status has not been saved yet. + LoadStatus(name string) (Status, error) + SaveStatus(name string, status Status) error +} + +type Runner struct { + storage Storage + logger logging.Logger +} + +func NewRunner(storage Storage, logger logging.Logger) *Runner { + return &Runner{storage: storage, logger: logger.New("migrations_runner")} +} + +func (r Runner) Run(ctx context.Context, migrations Migrations, callback ProgressCallback) error { + for i, migration := range migrations.List() { + onRunning := func() { + callback.OnRunning(i, migrations.Count()) + } + + if err := r.runMigration(ctx, migration, onRunning); err != nil { + err = errors.Wrapf(err, "error running migration '%s'", migration.Name()) + callback.OnError(i, migrations.Count(), err) + return err + } + } + + callback.OnDone(migrations.Count()) + + return nil +} + +func (r Runner) runMigration(ctx context.Context, migration Migration, onRunning func()) error { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + + logger := r.logger.WithField("migration_name", migration.Name()) + + logger.Trace().Message("considering migration") + + shouldRun, err := r.shouldRun(migration) + if err != nil { + return errors.Wrap(err, "error checking if migration should be run") + } + + if !shouldRun { + logger.Debug().Message("not running this migration") + return nil + } + + onRunning() + + state, err := r.loadState(migration) + if err != nil { + return errors.Wrap(err, "error loading state") + } + + humanReadableState, err := json.Marshal(state) + if err != nil { + return errors.Wrap(err, "state json marshal error") + } + + logger.Debug().WithField("state", string(humanReadableState)).Message("executing migration") + + saveStateFunc := func(state State) error { + return r.storage.SaveState(migration.Name(), state) + } + + migrationErr := migration.Fn()(ctx, state, saveStateFunc) + saveStateErr := r.storage.SaveStatus(migration.Name(), r.statusFromError(migrationErr)) + + var resultErr error + + if migrationErr != nil { + resultErr = multierror.Append(resultErr, errors.Wrap(migrationErr, "migration function returned an error")) + } + + if saveStateErr != nil { + resultErr = multierror.Append(resultErr, errors.Wrap(saveStateErr, "error saving state")) + } + + return resultErr +} + +func (r Runner) shouldRun(migration Migration) (bool, error) { + status, err := r.storage.LoadStatus(migration.Name()) + if err != nil { + if errors.Is(err, ErrStatusNotFound) { + return true, nil + } + return false, errors.Wrap(err, "error loading status") + } + return status != StatusFinished, nil +} + +func (r Runner) loadState(migration Migration) (State, error) { + state, err := r.storage.LoadState(migration.Name()) + if err != nil { + if errors.Is(err, ErrStateNotFound) { + return make(State), nil + } + return nil, errors.Wrap(err, "error loading state") + } + return state, nil +} + +func (r Runner) statusFromError(err error) Status { + if err == nil { + return StatusFinished + } + return StatusFailed +} diff --git a/migrations/migrations_test.go b/migrations/migrations_test.go new file mode 100644 index 0000000..eb234c2 --- /dev/null +++ b/migrations/migrations_test.go @@ -0,0 +1,736 @@ +package migrations_test + +import ( + "context" + "fmt" + "testing" + + "github.com/planetary-social/nos-event-service/internal" + "github.com/planetary-social/nos-event-service/internal/fixtures" + "github.com/planetary-social/nos-event-service/internal/logging" + "github.com/planetary-social/nos-event-service/migrations" + "github.com/stretchr/testify/require" +) + +func TestRunner_MigrationsCanBeEmpty(t *testing.T) { + r := newTestRunner(t) + + ctx := + fixtures.TestContext(t) + m := migrations.MustNewMigrations(nil) + callback := newProgressCallbackMock() + + err := r.Runner.Run(ctx, m, callback) + require.NoError(t, err) + + require.Empty(t, r.Storage.saveStateCalls) + require.Empty(t, r.Storage.saveStatusCalls) + require.Empty(t, r.Storage.loadStateCalls) + require.Empty(t, r.Storage.loadStatusCalls) +} + +func TestRunner_MigrationIsExecutedWithEmptyInitializedStateIfNoStateIsSaved(t *testing.T) { + r := newTestRunner(t) + + name := fixtures.SomeString() + + var passedState *migrations.State + + ctx := fixtures.TestContext(t) + m := migrations.MustNewMigrations([]migrations.Migration{ + migrations.MustNewMigration( + name, + func(ctx context.Context, state migrations.State, saveStateFunc migrations.SaveStateFunc) error { + passedState = &state + return nil + }, + ), + }) + callback := newProgressCallbackMock() + + err := r.Runner.Run(ctx, m, callback) + require.NoError(t, err) + + require.Equal(t, + []loadStateCall{ + { + name: name, + }, + }, + r.Storage.loadStateCalls, + ) + require.EqualValues(t, internal.Pointer(make(migrations.State)), passedState) +} + +func TestRunner_MigrationIsExecutedWithSavedStateIfStateWasSaved(t *testing.T) { + r := newTestRunner(t) + + name := fixtures.SomeString() + + var passedState *migrations.State + + ctx := fixtures.TestContext(t) + m := migrations.MustNewMigrations([]migrations.Migration{ + migrations.MustNewMigration( + name, + func(ctx context.Context, state migrations.State, saveStateFunc migrations.SaveStateFunc) error { + passedState = &state + return nil + }, + ), + }) + + someState := migrations.State{ + fixtures.SomeString(): fixtures.SomeString(), + } + + r.Storage.MockState(name, someState) + callback := newProgressCallbackMock() + + err := r.Runner.Run(ctx, m, callback) + require.NoError(t, err) + + require.Equal(t, + []loadStateCall{ + { + name: name, + }, + }, + r.Storage.loadStateCalls, + ) + require.EqualValues(t, internal.Pointer(someState), passedState) +} + +func TestRunner_MigrationIsExecutedIfNoStatusIsSaved(t *testing.T) { + r := newTestRunner(t) + + name := fixtures.SomeString() + + ctx := fixtures.TestContext(t) + m := migrations.MustNewMigrations([]migrations.Migration{ + migrations.MustNewMigration( + name, + func(ctx context.Context, state migrations.State, saveStateFunc migrations.SaveStateFunc) error { + return nil + }, + ), + }) + callback := newProgressCallbackMock() + + err := r.Runner.Run(ctx, m, callback) + require.NoError(t, err) + + require.Equal(t, + []loadStateCall{ + { + name: name, + }, + }, + r.Storage.loadStateCalls, + ) + require.Equal(t, + []loadStatusCall{ + { + name: name, + }, + }, + r.Storage.loadStatusCalls, + ) +} + +func TestRunner_StatusIsSavedBasedOnReturnedErrors(t *testing.T) { + testCases := []struct { + Name string + ReturnedError error + ExpectedStatus migrations.Status + }{ + { + Name: "no_error", + ReturnedError: nil, + ExpectedStatus: migrations.StatusFinished, + }, + { + Name: "error", + ReturnedError: fixtures.SomeError(), + ExpectedStatus: migrations.StatusFailed, + }, + } + + for _, testCase := range testCases { + r := newTestRunner(t) + name := fixtures.SomeString() + + ctx := fixtures.TestContext(t) + m := migrations.MustNewMigrations([]migrations.Migration{ + migrations.MustNewMigration( + name, + func(ctx context.Context, state migrations.State, saveStateFunc migrations.SaveStateFunc) error { + return testCase.ReturnedError + }, + ), + }) + callback := newProgressCallbackMock() + + err := r.Runner.Run(ctx, m, callback) + if testCase.ReturnedError == nil { + require.NoError(t, err) + } else { + require.ErrorIs(t, err, testCase.ReturnedError) + } + + require.Equal(t, + []saveStatusCall{ + { + name: name, + status: testCase.ExpectedStatus, + }, + }, + r.Storage.saveStatusCalls, + ) + } +} + +func TestRunner_MigrationIsNotExecutedIfItPreviouslySucceeded(t *testing.T) { + r := newTestRunner(t) + + name := fixtures.SomeString() + + ctx := fixtures.TestContext(t) + m := migrations.MustNewMigrations([]migrations.Migration{ + migrations.MustNewMigration( + name, + func(ctx context.Context, state migrations.State, saveStateFunc migrations.SaveStateFunc) error { + return nil + }, + ), + }) + + r.Storage.MockStatus(name, migrations.StatusFinished) + callback := newProgressCallbackMock() + + err := r.Runner.Run(ctx, m, callback) + require.NoError(t, err) + + require.Empty(t, r.Storage.loadStateCalls) + require.Equal(t, + []loadStatusCall{ + { + name: name, + }, + }, + r.Storage.loadStatusCalls, + ) +} + +func TestRunner_MigrationIsExecutedIfItPreviouslyFailed(t *testing.T) { + r := newTestRunner(t) + + name := fixtures.SomeString() + + ctx := fixtures.TestContext(t) + m := migrations.MustNewMigrations([]migrations.Migration{ + migrations.MustNewMigration( + name, + func(ctx context.Context, state migrations.State, saveStateFunc migrations.SaveStateFunc) error { + return nil + }, + ), + }) + + r.Storage.MockStatus(name, migrations.StatusFailed) + callback := newProgressCallbackMock() + + err := r.Runner.Run(ctx, m, callback) + require.NoError(t, err) + + require.Equal(t, + []loadStateCall{ + { + name: name, + }, + }, + r.Storage.loadStateCalls, + ) + require.Equal(t, + []loadStatusCall{ + { + name: name, + }, + }, + r.Storage.loadStatusCalls, + ) +} + +func TestRunner_MigrationsAreConsideredInOrder(t *testing.T) { + r := newTestRunner(t) + + name1 := fixtures.SomeString() + name2 := fixtures.SomeString() + + ctx := fixtures.TestContext(t) + m := migrations.MustNewMigrations([]migrations.Migration{ + migrations.MustNewMigration( + name1, + func(ctx context.Context, state migrations.State, saveStateFunc migrations.SaveStateFunc) error { + return nil + }, + ), + migrations.MustNewMigration( + name2, + func(ctx context.Context, state migrations.State, saveStateFunc migrations.SaveStateFunc) error { + return nil + }, + ), + }) + callback := newProgressCallbackMock() + + err := r.Runner.Run(ctx, m, callback) + require.NoError(t, err) + + require.Equal(t, + []loadStateCall{ + { + name: name1, + }, + { + name: name2, + }, + }, + r.Storage.loadStateCalls, + ) + require.Equal(t, + []loadStatusCall{ + { + name: name1, + }, + { + name: name2, + }, + }, + r.Storage.loadStatusCalls, + ) +} + +func TestRunner_MigrationsCanSaveState(t *testing.T) { + r := newTestRunner(t) + + name := fixtures.SomeString() + someState := migrations.State{ + fixtures.SomeString(): fixtures.SomeString(), + } + m := migrations.MustNewMigrations([]migrations.Migration{ + migrations.MustNewMigration( + name, + func(ctx context.Context, state migrations.State, saveStateFunc migrations.SaveStateFunc) error { + return saveStateFunc(someState) + }, + ), + }) + + ctx := fixtures.TestContext(t) + callback := newProgressCallbackMock() + err := r.Runner.Run(ctx, m, callback) + require.NoError(t, err) + + require.Equal(t, + []saveStateCall{ + { + name: name, + state: someState, + }, + }, + r.Storage.saveStateCalls, + ) +} + +func TestRunner_IfMigrationsAreEmptyOnlyOnDoneProgressCallbackIsCalled(t *testing.T) { + r := newTestRunner(t) + + ctx := fixtures.TestContext(t) + m := migrations.MustNewMigrations(nil) + callback := newProgressCallbackMock() + + err := r.Runner.Run(ctx, m, callback) + require.NoError(t, err) + + require.Empty(t, callback.OnRunningCalls) + require.Empty(t, callback.OnErrorCalls) + require.Equal(t, + []progressCallbackMockOnDoneCall{ + { + MigrationsCount: 0, + }, + }, + callback.OnDoneCalls, + ) +} + +func TestRunner_OnRunningProgressCallbackIsCalledWhenMigrationsAreRun(t *testing.T) { + r := newTestRunner(t) + + ctx := fixtures.TestContext(t) + + noop := func(ctx context.Context, state migrations.State, saveStateFunc migrations.SaveStateFunc) error { + return nil + } + + m := migrations.MustNewMigrations([]migrations.Migration{ + migrations.MustNewMigration(fixtures.SomeString(), noop), + migrations.MustNewMigration(fixtures.SomeString(), noop), + }) + + callback := newProgressCallbackMock() + + err := r.Runner.Run(ctx, m, callback) + require.NoError(t, err) + + require.Equal(t, + []progressCallbackMockOnRunningCall{ + { + MigrationIndex: 0, + MigrationsCount: 2, + }, + { + MigrationIndex: 1, + MigrationsCount: 2, + }, + }, + callback.OnRunningCalls, + ) + require.Empty(t, callback.OnErrorCalls) + require.Equal(t, + []progressCallbackMockOnDoneCall{ + { + MigrationsCount: 2, + }, + }, + callback.OnDoneCalls, + ) +} + +func TestRunner_OnRunningProgressCallbackIsOnlyCalledIfMigrationNeedsToBeRun(t *testing.T) { + r := newTestRunner(t) + + ctx := fixtures.TestContext(t) + + name1 := fixtures.SomeString() + name2 := fixtures.SomeString() + name3 := fixtures.SomeString() + + noop := func(ctx context.Context, state migrations.State, saveStateFunc migrations.SaveStateFunc) error { + return nil + } + + m := migrations.MustNewMigrations([]migrations.Migration{ + migrations.MustNewMigration(name1, noop), + migrations.MustNewMigration(name2, noop), + migrations.MustNewMigration(name3, noop), + }) + + r.Storage.MockStatus(name1, migrations.StatusFinished) + + callback := newProgressCallbackMock() + + err := r.Runner.Run(ctx, m, callback) + require.NoError(t, err) + + require.Equal(t, + []progressCallbackMockOnRunningCall{ + { + MigrationIndex: 1, + MigrationsCount: 3, + }, + { + MigrationIndex: 2, + MigrationsCount: 3, + }, + }, + callback.OnRunningCalls, + ) + require.Empty(t, callback.OnErrorCalls) + require.Equal(t, + []progressCallbackMockOnDoneCall{ + { + MigrationsCount: 3, + }, + }, + callback.OnDoneCalls, + ) +} + +func TestRunner_BothOnProgressAndOnErrorProgressCallbacksAreCalledIfMigrationFails(t *testing.T) { + r := newTestRunner(t) + + ctx := fixtures.TestContext(t) + + name1 := fixtures.SomeString() + name2 := fixtures.SomeString() + someError := fixtures.SomeError() + + noop := func(ctx context.Context, state migrations.State, saveStateFunc migrations.SaveStateFunc) error { + return nil + } + + returnsError := func(ctx context.Context, state migrations.State, saveStateFunc migrations.SaveStateFunc) error { + return someError + } + + m := migrations.MustNewMigrations([]migrations.Migration{ + migrations.MustNewMigration(name1, noop), + migrations.MustNewMigration(name2, returnsError), + }) + + callback := newProgressCallbackMock() + + err := r.Runner.Run(ctx, m, callback) + require.Error(t, err) + + require.Equal(t, + []progressCallbackMockOnRunningCall{ + { + MigrationIndex: 0, + MigrationsCount: 2, + }, + { + MigrationIndex: 1, + MigrationsCount: 2, + }, + }, + callback.OnRunningCalls, + ) + require.Len(t, callback.OnErrorCalls, 1) + require.Equal(t, 1, callback.OnErrorCalls[0].MigrationIndex) + require.Equal(t, 2, callback.OnErrorCalls[0].MigrationsCount) + require.EqualError(t, + callback.OnErrorCalls[0].Err, + fmt.Sprintf( + "error running migration '%s': 1 error occurred:\n\t* migration function returned an error: %s\n\n", + name2, + someError.Error(), + ), + ) + require.Empty(t, callback.OnDoneCalls) +} + +func TestRunner_OnlyOnErrorProgressCallbackIsCalledIfStatusLoadingFails(t *testing.T) { + r := newTestRunner(t) + + ctx := fixtures.TestContext(t) + + name1 := fixtures.SomeString() + name2 := fixtures.SomeString() + someError := fixtures.SomeError() + + noop := func(ctx context.Context, state migrations.State, saveStateFunc migrations.SaveStateFunc) error { + return nil + } + + m := migrations.MustNewMigrations([]migrations.Migration{ + migrations.MustNewMigration(name1, noop), + migrations.MustNewMigration(name2, noop), + }) + + callback := newProgressCallbackMock() + + r.Storage.MockLoadStatusError(name2, someError) + + err := r.Runner.Run(ctx, m, callback) + require.Error(t, err) + + require.Equal(t, + []progressCallbackMockOnRunningCall{ + { + MigrationIndex: 0, + MigrationsCount: 2, + }, + }, + callback.OnRunningCalls, + ) + require.Len(t, callback.OnErrorCalls, 1) + require.Equal(t, 1, callback.OnErrorCalls[0].MigrationIndex) + require.Equal(t, 2, callback.OnErrorCalls[0].MigrationsCount) + require.EqualError(t, + callback.OnErrorCalls[0].Err, + fmt.Sprintf( + "error running migration '%s': error checking if migration should be run: error loading status: %s", + name2, + someError.Error(), + ), + ) + require.Empty(t, callback.OnDoneCalls) +} + +type testRunner struct { + Runner *migrations.Runner + Storage *storageMock +} + +func newTestRunner(t *testing.T) testRunner { + logger := logging.NewDevNullLogger() + storage := newStorageMock() + runner := migrations.NewRunner(storage, logger) + + return testRunner{ + Runner: runner, + Storage: storage, + } +} + +type storageMock struct { + loadStateCalls []loadStateCall + loadStatusCalls []loadStatusCall + saveStateCalls []saveStateCall + saveStatusCalls []saveStatusCall + + returnedState map[string]migrations.State + returnedStatus map[string]migrations.Status + loadStatusErrors map[string]error +} + +func newStorageMock() *storageMock { + return &storageMock{ + returnedStatus: make(map[string]migrations.Status), + returnedState: make(map[string]migrations.State), + loadStatusErrors: make(map[string]error), + } +} + +func (s *storageMock) MockState(name string, state migrations.State) { + s.returnedState[name] = state +} + +func (s *storageMock) MockStatus(name string, status migrations.Status) { + s.returnedStatus[name] = status +} + +func (s *storageMock) MockLoadStatusError(name string, err error) { + s.loadStatusErrors[name] = err +} + +func (s *storageMock) LoadState(name string) (migrations.State, error) { + s.loadStateCalls = append(s.loadStateCalls, loadStateCall{name: name}) + state, ok := s.returnedState[name] + if !ok { + return nil, migrations.ErrStateNotFound + } + return state, nil +} + +func (s *storageMock) SaveState(name string, state migrations.State) error { + s.saveStateCalls = append(s.saveStateCalls, saveStateCall{name: name, state: state}) + return nil +} + +func (s *storageMock) LoadStatus(name string) (migrations.Status, error) { + s.loadStatusCalls = append(s.loadStatusCalls, loadStatusCall{name: name}) + + if err := s.loadStatusErrors[name]; err != nil { + return migrations.Status{}, err + } + + status, ok := s.returnedStatus[name] + if !ok { + return migrations.Status{}, migrations.ErrStatusNotFound + } + return status, nil +} + +func (s *storageMock) SaveStatus(name string, status migrations.Status) error { + s.saveStatusCalls = append(s.saveStatusCalls, saveStatusCall{name: name, status: status}) + return nil +} + +type loadStateCall struct { + name string +} + +type saveStateCall struct { + name string + state migrations.State +} + +type loadStatusCall struct { + name string +} + +type saveStatusCall struct { + name string + status migrations.Status +} + +func TestNewMigrations_DuplicateNamesAreNotAllowed(t *testing.T) { + name := "some name" + + _, err := migrations.NewMigrations( + []migrations.Migration{ + migrations.MustNewMigration( + name, + func(ctx context.Context, state migrations.State, saveStateFunc migrations.SaveStateFunc) error { + return nil + }, + ), + migrations.MustNewMigration( + name, + func(ctx context.Context, state migrations.State, saveStateFunc migrations.SaveStateFunc) error { + return nil + }, + ), + }, + ) + require.EqualError(t, err, "duplicate name 'some name'") +} + +func TestNewMigrations_ZeroValuesOfMigrationsAreNotAllowed(t *testing.T) { + _, err := migrations.NewMigrations( + []migrations.Migration{ + {}, + }, + ) + require.EqualError(t, err, "zero value of migration") +} + +type progressCallbackMockOnRunningCall struct { + MigrationIndex int + MigrationsCount int +} + +type progressCallbackMockOnErrorCall struct { + MigrationIndex int + MigrationsCount int + Err error +} + +type progressCallbackMockOnDoneCall struct { + MigrationsCount int +} + +type progressCallbackMock struct { + OnRunningCalls []progressCallbackMockOnRunningCall + OnErrorCalls []progressCallbackMockOnErrorCall + OnDoneCalls []progressCallbackMockOnDoneCall +} + +func newProgressCallbackMock() *progressCallbackMock { + return &progressCallbackMock{} +} + +func (p *progressCallbackMock) OnRunning(migrationIndex int, migrationsCount int) { + p.OnRunningCalls = append(p.OnRunningCalls, progressCallbackMockOnRunningCall{ + MigrationIndex: migrationIndex, + MigrationsCount: migrationsCount, + }) +} + +func (p *progressCallbackMock) OnError(migrationIndex int, migrationsCount int, err error) { + p.OnErrorCalls = append(p.OnErrorCalls, progressCallbackMockOnErrorCall{ + MigrationIndex: migrationIndex, + MigrationsCount: migrationsCount, + Err: err, + }) +} + +func (p *progressCallbackMock) OnDone(migrationsCount int) { + p.OnDoneCalls = append(p.OnDoneCalls, progressCallbackMockOnDoneCall{ + MigrationsCount: migrationsCount, + }) +} diff --git a/service/adapters/cache.go b/service/adapters/cache.go new file mode 100644 index 0000000..323c789 --- /dev/null +++ b/service/adapters/cache.go @@ -0,0 +1,64 @@ +package adapters + +import ( + "context" + "sync" + "time" + + "github.com/planetary-social/nos-event-service/service/domain" +) + +const ( + cacheSavedEventsFor = 60 * time.Minute + cleanupEvery = 5 * time.Minute +) + +type MemoryEventWasAlreadySavedCache struct { + cacheLock sync.Mutex + cache map[domain.EventId]time.Time +} + +func NewMemoryEventWasAlreadySavedCache() *MemoryEventWasAlreadySavedCache { + return &MemoryEventWasAlreadySavedCache{ + cache: make(map[domain.EventId]time.Time), + } +} + +func (m *MemoryEventWasAlreadySavedCache) Run(ctx context.Context) error { + for { + m.cleanup() + + select { + case <-time.After(cleanupEvery): + continue + case <-ctx.Done(): + return ctx.Err() + } + } +} + +func (m *MemoryEventWasAlreadySavedCache) cleanup() { + m.cacheLock.Lock() + defer m.cacheLock.Unlock() + + for id, timestamp := range m.cache { + if time.Since(timestamp) > cacheSavedEventsFor { + delete(m.cache, id) + } + } +} + +func (m *MemoryEventWasAlreadySavedCache) MarkEventAsAlreadySaved(id domain.EventId) { + m.cacheLock.Lock() + defer m.cacheLock.Unlock() + + m.cache[id] = time.Now() +} + +func (m *MemoryEventWasAlreadySavedCache) EventWasAlreadySaved(id domain.EventId) bool { + m.cacheLock.Lock() + defer m.cacheLock.Unlock() + + _, ok := m.cache[id] + return ok +} diff --git a/service/adapters/config/config.go b/service/adapters/config/config.go new file mode 100644 index 0000000..9292696 --- /dev/null +++ b/service/adapters/config/config.go @@ -0,0 +1,122 @@ +package config + +import ( + "fmt" + "io" + "os" + "strings" + + "github.com/boreq/errors" + "github.com/planetary-social/nos-event-service/internal/logging" + "github.com/planetary-social/nos-event-service/service/config" +) + +const ( + envPrefix = "EVENTS" + + envListenAddress = "LISTEN_ADDRESS" + envEnvironment = "ENVIRONMENT" + envLogLevel = "LOG_LEVEL" + envGooglePubsubEnabled = "GOOGLE_PUBSUB_ENABLED" + envGooglePubsubProjectID = "GOOGLE_PUBSUB_PROJECT_ID" + envGooglePubsubCredentialsJSONPath = "GOOGLE_PUBSUB_CREDENTIALS_JSON_PATH" + envDatabasePath = "DATABASE_PATH" +) + +type EnvironmentConfigLoader struct { +} + +func NewEnvironmentConfigLoader() *EnvironmentConfigLoader { + return &EnvironmentConfigLoader{} +} + +func (c *EnvironmentConfigLoader) Load() (config.Config, error) { + environment, err := c.loadEnvironment() + if err != nil { + return config.Config{}, errors.Wrap(err, "error loading the environment setting") + } + + logLevel, err := c.loadLogLevel() + if err != nil { + return config.Config{}, errors.Wrap(err, "error loading the log level") + } + + var googlePubSubCredentialsJSON []byte + if p := c.getenv(envGooglePubsubCredentialsJSONPath); p != "" { + f, err := os.Open(p) + if err != nil { + return config.Config{}, errors.Wrap(err, "error opening the pubsub credentials file") + } + + b, err := io.ReadAll(f) + if err != nil { + return config.Config{}, errors.Wrap(err, "error reading the pubsub credentials file") + } + + googlePubSubCredentialsJSON = b + } + + googlePubSubEnabled, err := c.getenvbool(envGooglePubsubEnabled) + if err != nil { + return config.Config{}, errors.Wrapf(err, "error loading variable '%s'", envGooglePubsubEnabled) + } + + return config.NewConfig( + c.getenv(envListenAddress), + environment, + logLevel, + googlePubSubEnabled, + c.getenv(envGooglePubsubProjectID), + googlePubSubCredentialsJSON, + c.getenv(envDatabasePath), + ) +} + +func (c *EnvironmentConfigLoader) loadEnvironment() (config.Environment, error) { + v := strings.ToUpper(c.getenv(envEnvironment)) + switch v { + case "PRODUCTION": + return config.EnvironmentProduction, nil + case "DEVELOPMENT": + return config.EnvironmentDevelopment, nil + case "": + return config.EnvironmentProduction, nil + default: + return config.Environment{}, fmt.Errorf("invalid environment requested '%s'", v) + } +} + +func (c *EnvironmentConfigLoader) loadLogLevel() (logging.Level, error) { + v := strings.ToUpper(c.getenv(envLogLevel)) + switch v { + case "TRACE": + return logging.LevelTrace, nil + case "DEBUG": + return logging.LevelDebug, nil + case "ERROR": + return logging.LevelError, nil + case "DISABLED": + return logging.LevelDisabled, nil + case "": + return logging.LevelDebug, nil + default: + return 0, fmt.Errorf("invalid log level requested '%s'", v) + } +} + +func (c *EnvironmentConfigLoader) getenv(key string) string { + return os.Getenv(fmt.Sprintf("%s_%s", envPrefix, key)) +} + +func (c *EnvironmentConfigLoader) getenvbool(key string) (bool, error) { + switch v := strings.ToUpper(c.getenv(key)); v { + case "": + return false, nil + case "TRUE": + return true, nil + case "FALSE": + return false, nil + default: + return false, fmt.Errorf("unknow value '%s'", v) + } +} diff --git a/service/adapters/gcp/noop_publisher.go b/service/adapters/gcp/noop_publisher.go new file mode 100644 index 0000000..0172e21 --- /dev/null +++ b/service/adapters/gcp/noop_publisher.go @@ -0,0 +1,18 @@ +package gcp + +import ( + "context" + + "github.com/planetary-social/nos-event-service/service/domain" +) + +type NoopPublisher struct { +} + +func NewNoopPublisher() *NoopPublisher { + return &NoopPublisher{} +} + +func (p *NoopPublisher) PublishNewEventReceived(ctx context.Context, event domain.Event) error { + return nil +} diff --git a/service/adapters/gcp/publisher.go b/service/adapters/gcp/publisher.go new file mode 100644 index 0000000..4eceea1 --- /dev/null +++ b/service/adapters/gcp/publisher.go @@ -0,0 +1,43 @@ +package gcp + +import ( + "context" + + "github.com/ThreeDotsLabs/watermill" + "github.com/ThreeDotsLabs/watermill-googlecloud/pkg/googlecloud" + "github.com/ThreeDotsLabs/watermill/message" + "github.com/planetary-social/nos-event-service/service/config" + "github.com/planetary-social/nos-event-service/service/domain" + "google.golang.org/api/option" +) + +const googlePubSubNostrEventsTopic = "nostr-events" + +func NewWatermillPublisher(config config.Config, logger watermill.LoggerAdapter) (*googlecloud.Publisher, error) { + var options []option.ClientOption + + if j := config.GooglePubSubCredentialsJSON(); len(j) > 0 { + options = append(options, option.WithCredentialsJSON(config.GooglePubSubCredentialsJSON())) + } + + publisherConfig := googlecloud.PublisherConfig{ + ProjectID: config.GooglePubSubProjectID(), + DoNotCreateTopicIfMissing: true, + ClientOptions: options, + } + + return googlecloud.NewPublisher(publisherConfig, logger) +} + +type Publisher struct { + publisher *googlecloud.Publisher +} + +func NewPublisher(publisher *googlecloud.Publisher) *Publisher { + return &Publisher{publisher: publisher} +} + +func (p *Publisher) PublishNewEventReceived(ctx context.Context, event domain.Event) error { + msg := message.NewMessage(watermill.NewULID(), event.Raw()) + return p.publisher.Publish(googlePubSubNostrEventsTopic, msg) +} diff --git a/service/adapters/memorypubsub/pubsub.go b/service/adapters/memorypubsub/pubsub.go new file mode 100644 index 0000000..6d3a2af --- /dev/null +++ b/service/adapters/memorypubsub/pubsub.go @@ -0,0 +1,67 @@ +package memorypubsub + +import ( + "context" + "sync" +) + +type channelWithContext[T any] struct { + Ch chan T + Ctx context.Context +} + +type GoChannelPubSub[T any] struct { + subscriptions []channelWithContext[T] + lock sync.Mutex +} + +func NewGoChannelPubSub[T any]() *GoChannelPubSub[T] { + return &GoChannelPubSub[T]{} +} + +func (g *GoChannelPubSub[T]) Subscribe(ctx context.Context) <-chan T { + ch := make(chan T) + + g.addSubscription(ctx, ch) + + go func() { + <-ctx.Done() + g.removeSubscription(ch) + close(ch) + }() + + return ch +} + +func (g *GoChannelPubSub[T]) Publish(value T) { + g.lock.Lock() + defer g.lock.Unlock() + + for _, sub := range g.subscriptions { + select { + case sub.Ch <- value: + case <-sub.Ctx.Done(): + } + } +} + +func (g *GoChannelPubSub[T]) addSubscription(ctx context.Context, ch chan T) { + g.lock.Lock() + defer g.lock.Unlock() + + g.subscriptions = append(g.subscriptions, channelWithContext[T]{Ch: ch, Ctx: ctx}) +} + +func (g *GoChannelPubSub[T]) removeSubscription(ch chan T) { + g.lock.Lock() + defer g.lock.Unlock() + + for i := range g.subscriptions { + if g.subscriptions[i].Ch == ch { + g.subscriptions = append(g.subscriptions[:i], g.subscriptions[i+1:]...) + return + } + } + + panic("somehow the subscription was already removed, this must be a bug") +} diff --git a/service/adapters/memorypubsub/received_event_pubsub.go b/service/adapters/memorypubsub/received_event_pubsub.go new file mode 100644 index 0000000..1e5b5bc --- /dev/null +++ b/service/adapters/memorypubsub/received_event_pubsub.go @@ -0,0 +1,28 @@ +package memorypubsub + +import ( + "context" + + "github.com/planetary-social/nos-event-service/service/app" + "github.com/planetary-social/nos-event-service/service/domain" +) + +type ReceivedEventPubSub struct { + pubsub *GoChannelPubSub[app.ReceivedEvent] +} + +func NewReceivedEventPubSub() *ReceivedEventPubSub { + return &ReceivedEventPubSub{ + pubsub: NewGoChannelPubSub[app.ReceivedEvent](), + } +} + +func (m *ReceivedEventPubSub) Publish(relay domain.RelayAddress, event domain.Event) { + m.pubsub.Publish( + app.NewReceivedEvent(relay, event), + ) +} + +func (m *ReceivedEventPubSub) Subscribe(ctx context.Context) <-chan app.ReceivedEvent { + return m.pubsub.Subscribe(ctx) +} diff --git a/service/adapters/migrations_progress_callback.go b/service/adapters/migrations_progress_callback.go new file mode 100644 index 0000000..de8fd40 --- /dev/null +++ b/service/adapters/migrations_progress_callback.go @@ -0,0 +1,32 @@ +package adapters + +import "github.com/planetary-social/nos-event-service/internal/logging" + +type LoggingMigrationsProgressCallback struct { + logger logging.Logger +} + +func NewLoggingMigrationsProgressCallback(logger logging.Logger) *LoggingMigrationsProgressCallback { + return &LoggingMigrationsProgressCallback{logger: logger.New("migrationProgressCallback")} +} + +func (l LoggingMigrationsProgressCallback) OnRunning(migrationIndex int, migrationsCount int) { + l.logger.Debug(). + WithField("index", migrationIndex). + WithField("count", migrationsCount). + Message("running") +} + +func (l LoggingMigrationsProgressCallback) OnError(migrationIndex int, migrationsCount int, err error) { + l.logger.Error(). + WithField("index", migrationIndex). + WithField("count", migrationsCount). + WithError(err). + Message("error") +} + +func (l LoggingMigrationsProgressCallback) OnDone(migrationsCount int) { + l.logger.Debug(). + WithField("count", migrationsCount). + Message("done") +} diff --git a/service/adapters/mocks/external_event_publisher.go b/service/adapters/mocks/external_event_publisher.go new file mode 100644 index 0000000..02c667c --- /dev/null +++ b/service/adapters/mocks/external_event_publisher.go @@ -0,0 +1,18 @@ +package mocks + +import ( + "context" + + "github.com/planetary-social/nos-event-service/service/domain" +) + +type MockExternalEventPublisher struct { +} + +func NewMockExternalEventPublisher() *MockExternalEventPublisher { + return &MockExternalEventPublisher{} +} + +func (m MockExternalEventPublisher) PublishNewEventReceived(ctx context.Context, event domain.Event) error { + return nil +} diff --git a/service/adapters/prometheus/prometheus.go b/service/adapters/prometheus/prometheus.go new file mode 100644 index 0000000..f4dc07a --- /dev/null +++ b/service/adapters/prometheus/prometheus.go @@ -0,0 +1,210 @@ +package prometheus + +import ( + "runtime/debug" + "strconv" + "time" + + "github.com/boreq/errors" + "github.com/planetary-social/nos-event-service/internal/logging" + "github.com/planetary-social/nos-event-service/service/app" + "github.com/planetary-social/nos-event-service/service/domain" + "github.com/planetary-social/nos-event-service/service/domain/relays" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/collectors" +) + +const ( + labelHandlerName = "handlerName" + labelRelayDownloaderState = "state" + labelTopic = "topic" + labelVcsRevision = "vcsRevision" + labelVcsTime = "vcsTime" + labelGo = "go" + + labelResult = "result" + labelResultSuccess = "success" + labelResultError = "error" + labelResultInvalidPointerPassed = "invalidPointerPassed" + + labelStatusCode = "statusCode" +) + +type Prometheus struct { + applicationHandlerCallsCounter *prometheus.CounterVec + applicationHandlerCallDurationHistogram *prometheus.HistogramVec + relayDownloaderStateGauge *prometheus.GaugeVec + subscriptionQueueLengthGauge *prometheus.GaugeVec + apnsCallsCounter *prometheus.CounterVec + + registry *prometheus.Registry + + logger logging.Logger +} + +func (p *Prometheus) ReportRelayConnectionsState(m map[domain.RelayAddress]relays.RelayConnectionState) { + // todo +} + +func NewPrometheus(logger logging.Logger) (*Prometheus, error) { + applicationHandlerCallsCounter := prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "application_handler_calls_total", + Help: "Total number of calls to application handlers.", + }, + []string{labelHandlerName, labelResult}, + ) + applicationHandlerCallDurationHistogram := prometheus.NewHistogramVec( + prometheus.HistogramOpts{ + Name: "application_handler_calls_duration", + Help: "Duration of calls to application handlers in seconds.", + }, + []string{labelHandlerName, labelResult}, + ) + relayDownloaderStateGauge := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Name: "relay_downloader_count", + Help: "Number of running relay downloaders.", + }, + []string{labelRelayDownloaderState}, + ) + subscriptionQueueLengthGauge := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Name: "subscription_queue_length", + Help: "Number of events in the subscription queue.", + }, + []string{labelTopic}, + ) + versionGague := prometheus.NewGaugeVec( + prometheus.GaugeOpts{ + Name: "version", + Help: "This metric exists just to put a commit label on it.", + }, + []string{labelVcsRevision, labelVcsTime, labelGo}, + ) + apnsCallsCounter := prometheus.NewCounterVec( + prometheus.CounterOpts{ + Name: "apns_calls_total", + Help: "Total number of calls to APNs.", + }, + []string{labelStatusCode, labelResult}, + ) + + reg := prometheus.NewRegistry() + for _, v := range []prometheus.Collector{ + applicationHandlerCallsCounter, + applicationHandlerCallDurationHistogram, + relayDownloaderStateGauge, + subscriptionQueueLengthGauge, + versionGague, + apnsCallsCounter, + collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}), + collectors.NewGoCollector(), + } { + if err := reg.Register(v); err != nil { + return nil, errors.Wrap(err, "error registering a collector") + } + } + + buildInfo, ok := debug.ReadBuildInfo() + if ok { + var vcsRevision, vcsTime string + for _, setting := range buildInfo.Settings { + if setting.Key == "vcs.revision" { + vcsRevision = setting.Value + } + if setting.Key == "vcs.time" { + vcsTime = setting.Value + } + } + versionGague.With(prometheus.Labels{labelGo: buildInfo.GoVersion, labelVcsRevision: vcsRevision, labelVcsTime: vcsTime}).Set(1) + } + + return &Prometheus{ + applicationHandlerCallsCounter: applicationHandlerCallsCounter, + applicationHandlerCallDurationHistogram: applicationHandlerCallDurationHistogram, + relayDownloaderStateGauge: relayDownloaderStateGauge, + subscriptionQueueLengthGauge: subscriptionQueueLengthGauge, + apnsCallsCounter: apnsCallsCounter, + + registry: reg, + + logger: logger.New("prometheus"), + }, nil +} + +func (p *Prometheus) StartApplicationCall(handlerName string) app.ApplicationCall { + return NewApplicationCall(p, handlerName, p.logger) +} + +func (p *Prometheus) ReportSubscriptionQueueLength(topic string, n int) { + p.subscriptionQueueLengthGauge.With(prometheus.Labels{labelTopic: topic}).Set(float64(n)) +} + +func (p *Prometheus) ReportCallToAPNS(statusCode int, err error) { + labels := prometheus.Labels{ + labelStatusCode: strconv.Itoa(statusCode), + } + if err == nil { + labels[labelResult] = labelResultSuccess + } else { + labels[labelResult] = labelResultError + } + p.apnsCallsCounter.With(labels).Inc() +} + +func (p *Prometheus) Registry() *prometheus.Registry { + return p.registry +} + +type ApplicationCall struct { + handlerName string + p *Prometheus + start time.Time + logger logging.Logger +} + +func NewApplicationCall(p *Prometheus, handlerName string, logger logging.Logger) *ApplicationCall { + return &ApplicationCall{ + p: p, + handlerName: handlerName, + logger: logger, + start: time.Now(), + } +} + +func (a *ApplicationCall) End(err *error) { + duration := time.Since(a.start) + + l := a.logger. + WithField("handlerName", a.handlerName). + WithField("duration", duration) + + if err == nil { + l.Error().Message("application call with an invalid error pointer") + } else { + l.Debug().WithError(*err).Message("application call") + } + + labels := a.getLabels(err) + a.p.applicationHandlerCallsCounter.With(labels).Inc() + a.p.applicationHandlerCallDurationHistogram.With(labels).Observe(duration.Seconds()) +} + +func (a *ApplicationCall) getLabels(err *error) prometheus.Labels { + labels := prometheus.Labels{ + labelHandlerName: a.handlerName, + } + + if err == nil { + labels[labelResult] = labelResultInvalidPointerPassed + } else { + if *err == nil { + labels[labelResult] = labelResultSuccess + } else { + labels[labelResult] = labelResultError + } + } + + return labels +} diff --git a/service/adapters/sqlite/event_repository.go b/service/adapters/sqlite/event_repository.go new file mode 100644 index 0000000..a9142df --- /dev/null +++ b/service/adapters/sqlite/event_repository.go @@ -0,0 +1,61 @@ +package sqlite + +import ( + "context" + "database/sql" + + "github.com/boreq/errors" + "github.com/planetary-social/nos-event-service/service/domain" +) + +type EventRepository struct { + tx *sql.Tx +} + +func NewEventRepository(tx *sql.Tx) (*EventRepository, error) { + return &EventRepository{ + tx: tx, + }, nil +} + +func (r *EventRepository) Save(ctx context.Context, event domain.Event) error { + _, err := r.tx.Exec(` + INSERT INTO events(event_id, payload) + VALUES($1, $2) + ON CONFLICT(event_id) DO UPDATE SET + payload=excluded.payload`, + event.Id().Hex(), + event.Raw(), + ) + if err != nil { + return errors.Wrap(err, "error executing the insert query") + } + + return nil +} + +func (r *EventRepository) Get(ctx context.Context, eventID domain.EventId) (domain.Event, error) { + result := r.tx.QueryRow(` + SELECT payload + FROM events + WHERE event_id=$1`, + eventID.Hex(), + ) + + return r.readEvent(result) +} + +func (m *EventRepository) readEvent(result *sql.Row) (domain.Event, error) { + var payload []byte + + if err := result.Scan(&payload); err != nil { + return domain.Event{}, errors.Wrap(err, "error reading the row") + } + + event, err := domain.NewEventFromRaw(payload) + if err != nil { + return domain.Event{}, errors.Wrap(err, "error creating an event") + } + + return event, nil +} diff --git a/service/adapters/sqlite/event_repository_test.go b/service/adapters/sqlite/event_repository_test.go new file mode 100644 index 0000000..8ba0b65 --- /dev/null +++ b/service/adapters/sqlite/event_repository_test.go @@ -0,0 +1,57 @@ +package sqlite_test + +import ( + "context" + "testing" + + "github.com/planetary-social/nos-event-service/internal/fixtures" + "github.com/planetary-social/nos-event-service/service/adapters/sqlite" + "github.com/stretchr/testify/require" +) + +func TestEventRepository_SavingTheSameEventTwiceReturnsNoErrors(t *testing.T) { + ctx := fixtures.TestContext(t) + adapters := NewTestAdapters(ctx, t) + + event := fixtures.SomeEvent() + + err := adapters.TransactionProvider.Transact(ctx, func(ctx context.Context, adapters sqlite.TestAdapters) error { + err := adapters.EventRepository.Save(ctx, event) + require.NoError(t, err) + + return nil + }) + require.NoError(t, err) + + err = adapters.TransactionProvider.Transact(ctx, func(ctx context.Context, adapters sqlite.TestAdapters) error { + err := adapters.EventRepository.Save(ctx, event) + require.NoError(t, err) + + return nil + }) + require.NoError(t, err) +} + +func TestEventRepository_ItIsPossibleToSaveAndGetEvents(t *testing.T) { + ctx := fixtures.TestContext(t) + adapters := NewTestAdapters(ctx, t) + + event := fixtures.SomeEvent() + + err := adapters.TransactionProvider.Transact(ctx, func(ctx context.Context, adapters sqlite.TestAdapters) error { + err := adapters.EventRepository.Save(ctx, event) + require.NoError(t, err) + + return nil + }) + require.NoError(t, err) + + err = adapters.TransactionProvider.Transact(ctx, func(ctx context.Context, adapters sqlite.TestAdapters) error { + readEvent, err := adapters.EventRepository.Get(ctx, event.Id()) + require.NoError(t, err) + require.Equal(t, event.Raw(), readEvent.Raw()) + + return nil + }) + require.NoError(t, err) +} diff --git a/service/adapters/sqlite/migrations.go b/service/adapters/sqlite/migrations.go new file mode 100644 index 0000000..38b212e --- /dev/null +++ b/service/adapters/sqlite/migrations.go @@ -0,0 +1,73 @@ +package sqlite + +import ( + "context" + "database/sql" + + "github.com/boreq/errors" + "github.com/planetary-social/nos-event-service/migrations" +) + +func NewMigrations(fns *MigrationFns) (migrations.Migrations, error) { + return migrations.NewMigrations([]migrations.Migration{ + migrations.MustNewMigration("initial", fns.Initial), + migrations.MustNewMigration("create_pubsub_tables", fns.CreatePubsubTables), + }) +} + +type MigrationFns struct { + db *sql.DB + pubsub *PubSub +} + +func NewMigrationFns(db *sql.DB, pubsub *PubSub) *MigrationFns { + return &MigrationFns{db: db, pubsub: pubsub} +} + +func (m *MigrationFns) Initial(ctx context.Context, state migrations.State, saveStateFunc migrations.SaveStateFunc) error { + _, err := m.db.Exec(` + CREATE TABLE IF NOT EXISTS events ( + id INTEGER PRIMARY KEY, + event_id TEXT UNIQUE, + payload BLOB + );`, + ) + if err != nil { + return errors.Wrap(err, "error creating the events table") + } + + _, err = m.db.Exec(` + CREATE TABLE IF NOT EXISTS events_to_relays ( + event_id INT, + relay_id INT, + PRIMARY KEY(event_id, relay_id), + FOREIGN KEY(event_id) REFERENCES events(id), + FOREIGN KEY(relay_id) REFERENCES relays(id) + );`, + ) + if err != nil { + return errors.Wrap(err, "error creating the events_to_relays table") + } + + _, err = m.db.Exec(` + CREATE TABLE IF NOT EXISTS relays ( + id INTEGER PRIMARY KEY, + address TEXT UNIQUE + );`, + ) + if err != nil { + return errors.Wrap(err, "error creating the relays table") + } + + return nil +} + +func (m *MigrationFns) CreatePubsubTables(ctx context.Context, state migrations.State, saveStateFunc migrations.SaveStateFunc) error { + for _, query := range m.pubsub.InitializingQueries() { + if _, err := m.db.Exec(query); err != nil { + return errors.Wrapf(err, "error initializing pubsub") + } + } + + return nil +} diff --git a/service/adapters/sqlite/migrations_storage.go b/service/adapters/sqlite/migrations_storage.go new file mode 100644 index 0000000..5676f9a --- /dev/null +++ b/service/adapters/sqlite/migrations_storage.go @@ -0,0 +1,136 @@ +package sqlite + +import ( + "database/sql" + "encoding/json" + + "github.com/boreq/errors" + "github.com/planetary-social/nos-event-service/migrations" +) + +type MigrationsStorage struct { + db *sql.DB +} + +func NewMigrationsStorage(db *sql.DB) (*MigrationsStorage, error) { + if _, err := db.Exec(` + CREATE TABLE IF NOT EXISTS migrations_state ( + name TEXT PRIMARY KEY, + state TEXT + );`, + ); err != nil { + return nil, errors.Wrap(err, "error creating the state table") + } + + if _, err := db.Exec(` + CREATE TABLE IF NOT EXISTS migrations_status ( + name TEXT PRIMARY KEY, + status TEXT + );`, + ); err != nil { + return nil, errors.Wrap(err, "error creating the status table") + } + + return &MigrationsStorage{db: db}, nil +} + +func (b *MigrationsStorage) LoadState(name string) (migrations.State, error) { + var marshaledState string + + row := b.db.QueryRow("SELECT state FROM migrations_state WHERE name=$1", name) + if err := row.Scan(&marshaledState); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, migrations.ErrStateNotFound + } + return nil, errors.Wrap(err, "error querying the database") + } + + var state migrations.State + if err := json.Unmarshal([]byte(marshaledState), &state); err != nil { + return nil, errors.Wrap(err, "error unmarshaling state") + } + + return state, nil +} + +func (b *MigrationsStorage) SaveState(name string, state migrations.State) error { + marshaledState, err := json.Marshal(state) + if err != nil { + return errors.Wrap(err, "error marshaling state") + } + + if _, err := b.db.Exec(` +INSERT INTO migrations_state(name, state) +VALUES ($1, $2) +ON CONFLICT(name) DO UPDATE SET + state=excluded.state`, + name, marshaledState); err != nil { + return errors.Wrap(err, "error running the query") + } + + return nil +} + +func (b *MigrationsStorage) LoadStatus(name string) (migrations.Status, error) { + var marshaledStatus string + + row := b.db.QueryRow("SELECT status FROM migrations_status WHERE name=$1", name) + if err := row.Scan(&marshaledStatus); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return migrations.Status{}, migrations.ErrStatusNotFound + } + return migrations.Status{}, errors.Wrap(err, "error querying the database") + } + + status, err := unmarshalStatus(marshaledStatus) + if err != nil { + return migrations.Status{}, errors.Wrap(err, "error unmarshaling status") + } + + return status, nil +} + +func (b *MigrationsStorage) SaveStatus(name string, status migrations.Status) error { + marshaledStatus, err := marshalStatus(status) + if err != nil { + return errors.Wrap(err, "error marshaling status") + } + + if _, err := b.db.Exec(` +INSERT INTO migrations_status(name, status) +VALUES ($1, $2) +ON CONFLICT(name) DO UPDATE SET + status=excluded.status`, + name, marshaledStatus); err != nil { + return errors.Wrap(err, "error running the query") + } + + return nil +} + +const ( + statusFailed = "failed" + statusFinished = "finished" +) + +func marshalStatus(status migrations.Status) (string, error) { + switch status { + case migrations.StatusFailed: + return statusFailed, nil + case migrations.StatusFinished: + return statusFinished, nil + default: + return "", errors.New("unknown status") + } +} + +func unmarshalStatus(status string) (migrations.Status, error) { + switch status { + case statusFailed: + return migrations.StatusFailed, nil + case statusFinished: + return migrations.StatusFinished, nil + default: + return migrations.Status{}, errors.New("unknown status") + } +} diff --git a/service/adapters/sqlite/migrations_storage_test.go b/service/adapters/sqlite/migrations_storage_test.go new file mode 100644 index 0000000..6d0adf1 --- /dev/null +++ b/service/adapters/sqlite/migrations_storage_test.go @@ -0,0 +1,99 @@ +package sqlite_test + +import ( + "testing" + + "github.com/planetary-social/nos-event-service/internal/fixtures" + "github.com/planetary-social/nos-event-service/migrations" + "github.com/stretchr/testify/require" +) + +func TestMigrationsStorage_LoadStateReturnsCorrectErrorWhenStateIsNotAvailable(t *testing.T) { + ctx := fixtures.TestContext(t) + adapters := NewTestAdapters(ctx, t) + + _, err := adapters.MigrationsStorage.LoadState(fixtures.SomeString()) + require.ErrorIs(t, err, migrations.ErrStateNotFound) +} + +func TestMigrationsStorage_LoadStateReturnsSavedState(t *testing.T) { + ctx := fixtures.TestContext(t) + adapters := NewTestAdapters(ctx, t) + + name := fixtures.SomeString() + state := migrations.State{ + fixtures.SomeString(): fixtures.SomeString(), + } + + err := adapters.MigrationsStorage.SaveState(name, state) + require.NoError(t, err) + + loadedState, err := adapters.MigrationsStorage.LoadState(name) + require.NoError(t, err) + require.Equal(t, state, loadedState) +} + +func TestMigrationsStorage_SavingStateTwiceOverwritesPreviousState(t *testing.T) { + ctx := fixtures.TestContext(t) + adapters := NewTestAdapters(ctx, t) + + name := fixtures.SomeString() + state1 := migrations.State{ + fixtures.SomeString(): fixtures.SomeString(), + } + state2 := migrations.State{ + fixtures.SomeString(): fixtures.SomeString(), + } + + err := adapters.MigrationsStorage.SaveState(name, state1) + require.NoError(t, err) + + err = adapters.MigrationsStorage.SaveState(name, state2) + require.NoError(t, err) + + loadedState, err := adapters.MigrationsStorage.LoadState(name) + require.NoError(t, err) + require.Equal(t, state2, loadedState) +} + +func TestMigrationsStorage_LoadStatusReturnsCorrectErrorWhenStatusIsNotAvailable(t *testing.T) { + ctx := fixtures.TestContext(t) + adapters := NewTestAdapters(ctx, t) + + _, err := adapters.MigrationsStorage.LoadStatus(fixtures.SomeString()) + require.ErrorIs(t, err, migrations.ErrStatusNotFound) +} + +func TestMigrationsStorage_LoadStatusReturnsSavedStatus(t *testing.T) { + ctx := fixtures.TestContext(t) + adapters := NewTestAdapters(ctx, t) + + name := fixtures.SomeString() + status := migrations.StatusFinished + + err := adapters.MigrationsStorage.SaveStatus(name, status) + require.NoError(t, err) + + loadedStatus, err := adapters.MigrationsStorage.LoadStatus(name) + require.NoError(t, err) + require.Equal(t, status, loadedStatus) +} + +func TestMigrationsStorage_SavingStatusTwiceOverwritesPreviousStatus(t *testing.T) { + ctx := fixtures.TestContext(t) + adapters := NewTestAdapters(ctx, t) + + name := fixtures.SomeString() + status1 := migrations.StatusFinished + status2 := migrations.StatusFinished + + err := adapters.MigrationsStorage.SaveStatus(name, status1) + require.NoError(t, err) + + err = adapters.MigrationsStorage.SaveStatus(name, status2) + require.NoError(t, err) + + loadedStatus, err := adapters.MigrationsStorage.LoadStatus(name) + require.NoError(t, err) + require.Equal(t, status2, loadedStatus) +} diff --git a/service/adapters/sqlite/publisher.go b/service/adapters/sqlite/publisher.go new file mode 100644 index 0000000..b4af1d5 --- /dev/null +++ b/service/adapters/sqlite/publisher.go @@ -0,0 +1,44 @@ +package sqlite + +import ( + "context" + "database/sql" + "encoding/json" + + "github.com/boreq/errors" + "github.com/oklog/ulid/v2" + "github.com/planetary-social/nos-event-service/service/domain" +) + +const EventSavedTopic = "event_saved" + +type Publisher struct { + pubsub *PubSub + tx *sql.Tx +} + +func NewPublisher(pubsub *PubSub, tx *sql.Tx) *Publisher { + return &Publisher{pubsub: pubsub, tx: tx} +} + +func (p *Publisher) PublishEventSaved(ctx context.Context, id domain.EventId) error { + transport := EventSavedEventTransport{ + EventID: id.Hex(), + } + + payload, err := json.Marshal(transport) + if err != nil { + return errors.Wrap(err, "error marshaling the transport type") + } + + msg, err := NewMessage(ulid.Make().String(), payload) + if err != nil { + return errors.Wrap(err, "error creating a message") + } + + return p.pubsub.PublishTx(p.tx, EventSavedTopic, msg) +} + +type EventSavedEventTransport struct { + EventID string `json:"eventID"` +} diff --git a/service/adapters/sqlite/publisher_test.go b/service/adapters/sqlite/publisher_test.go new file mode 100644 index 0000000..2810124 --- /dev/null +++ b/service/adapters/sqlite/publisher_test.go @@ -0,0 +1,23 @@ +package sqlite_test + +import ( + "context" + "testing" + + "github.com/planetary-social/nos-event-service/internal/fixtures" + "github.com/planetary-social/nos-event-service/service/adapters/sqlite" + "github.com/stretchr/testify/require" +) + +func TestPublisher_ItIsPossibleToPublishEvents(t *testing.T) { + ctx := fixtures.TestContext(t) + adapters := NewTestAdapters(ctx, t) + + err := adapters.TransactionProvider.Transact(ctx, func(ctx context.Context, adapters sqlite.TestAdapters) error { + err := adapters.Publisher.PublishEventSaved(ctx, fixtures.SomeEventID()) + require.NoError(t, err) + + return nil + }) + require.NoError(t, err) +} diff --git a/service/adapters/sqlite/pubsub.go b/service/adapters/sqlite/pubsub.go new file mode 100644 index 0000000..30ee9ac --- /dev/null +++ b/service/adapters/sqlite/pubsub.go @@ -0,0 +1,310 @@ +package sqlite + +import ( + "context" + "database/sql" + "math" + "math/rand" + "sync" + "time" + + "github.com/boreq/errors" + "github.com/planetary-social/nos-event-service/internal/logging" +) + +type BackoffManager interface { + // GetMessageErrorBackoff is used to backoff reprocessing of a single + // specific message if its processing fails. The first time message + // processing fails 1 is passed to this function, the second time 2 etc. + GetMessageErrorBackoff(nackCount int) time.Duration + + // GetNoMessagesBackoff is used to backoff querying for new messages on the + // queue. The first time in a row where the query returns no messages 1 is + // passed to this function, then 2 is passed etc. + GetNoMessagesBackoff(tick int) time.Duration +} + +type Message struct { + uuid string + payload []byte +} + +func NewMessage(uuid string, payload []byte) (Message, error) { + if uuid == "" { + return Message{}, errors.New("uuid can't be empty") + } + return Message{uuid: uuid, payload: payload}, nil +} + +func (m Message) UUID() string { + return m.uuid +} + +func (m Message) Payload() []byte { + return m.payload +} + +type ReceivedMessage struct { + Message + + lock sync.Mutex + state receivedMessageState + chAck chan struct{} + chNack chan struct{} +} + +func NewReceivedMessage(message Message) *ReceivedMessage { + return &ReceivedMessage{ + Message: message, + state: receivedMessageStateFresh, + chAck: make(chan struct{}), + chNack: make(chan struct{}), + } +} + +func (m *ReceivedMessage) Ack() error { + m.lock.Lock() + defer m.lock.Unlock() + + if m.state != receivedMessageStateFresh { + return errors.New("message was already acked or nacked") + } + + m.state = receivedMessageStateAcked + close(m.chAck) + return nil +} + +func (m *ReceivedMessage) Nack() error { + m.lock.Lock() + defer m.lock.Unlock() + + if m.state != receivedMessageStateFresh { + return errors.New("message was already acked or nacked") + } + + m.state = receivedMessageStateNacked + close(m.chNack) + return nil +} + +type receivedMessageState struct { + s string +} + +var ( + receivedMessageStateFresh = receivedMessageState{"fresh"} + receivedMessageStateAcked = receivedMessageState{"acked"} + receivedMessageStateNacked = receivedMessageState{"nacked"} +) + +type PubSub struct { + backoffManager BackoffManager + db *sql.DB + logger logging.Logger +} + +func NewPubSub(db *sql.DB, logger logging.Logger) *PubSub { + return &PubSub{ + backoffManager: NewDefaultBackoffManager(), + db: db, + logger: logger, + } +} + +func (p *PubSub) InitializingQueries() []string { + return []string{` + CREATE TABLE IF NOT EXISTS pubsub ( + topic TEXT NOT NULL, + uuid VARCHAR(36) NOT NULL PRIMARY KEY, + payload BLOB, + created_at INTEGER NOT NULL, + nack_count INTEGER NOT NULL, + backoff_until INTEGER + )`, + } +} + +func (p *PubSub) Publish(topic string, msg Message) error { + return p.publish(p.db, topic, msg) +} + +func (p *PubSub) PublishTx(tx *sql.Tx, topic string, msg Message) error { + return p.publish(tx, topic, msg) +} + +func (p *PubSub) publish(e executor, topic string, msg Message) error { + _, err := e.Exec( + "INSERT INTO pubsub VALUES (?, ?, ?, ?, ?, ?)", + topic, + msg.uuid, + msg.payload, + time.Now().Unix(), + 0, + nil, + ) + return err +} + +func (p *PubSub) Subscribe(ctx context.Context, topic string) <-chan *ReceivedMessage { + ch := make(chan *ReceivedMessage) + go p.subscribe(ctx, topic, ch) + return ch +} + +func (p *PubSub) QueueLength(topic string) (int, error) { + row := p.db.QueryRow( + "SELECT COUNT(*) FROM pubsub WHERE topic = ?", + topic, + ) + + var count int + if err := row.Scan(&count); err != nil { + return 0, errors.Wrap(err, "row scan error") + } + + return count, nil +} + +func (p *PubSub) subscribe(ctx context.Context, topic string, ch chan *ReceivedMessage) { + noMessagesCounter := 0 + + for { + msg, err := p.readMsg(topic) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + noMessagesCounter++ + backoff := p.backoffManager.GetNoMessagesBackoff(noMessagesCounter) + + p.logger.Trace(). + WithField("duration", backoff). + Message("backing off reading messages") + + select { + case <-time.After(backoff): + continue + case <-ctx.Done(): + return + } + } + + noMessagesCounter = 0 + p.logger.Error().WithError(err).Message("error reading message") + continue + } + + noMessagesCounter = 0 + receivedMsg := NewReceivedMessage(msg) + + select { + case ch <- receivedMsg: + case <-ctx.Done(): + return + } + + select { + case <-receivedMsg.chAck: + if err := p.ack(receivedMsg.Message); err != nil { + p.logger.Error().WithError(err).Message("error acking a message") + } + case <-receivedMsg.chNack: + if err := p.nack(receivedMsg.Message); err != nil { + p.logger.Error().WithError(err).Message("error nacking a message") + } + case <-ctx.Done(): + return + } + } +} + +func (p *PubSub) readMsg(topic string) (Message, error) { + row := p.db.QueryRow( + "SELECT uuid, payload FROM pubsub WHERE topic = ? AND (backoff_until IS NULL OR backoff_until <= ?) ORDER BY RANDOM() LIMIT 1", + topic, + time.Now().Unix(), + ) + + var uuid string + var payload []byte + if err := row.Scan(&uuid, &payload); err != nil { + return Message{}, errors.Wrap(err, "row scan error") + } + + return NewMessage(uuid, payload) +} + +func (p *PubSub) ack(msg Message) error { + _, err := p.db.Exec( + "DELETE FROM pubsub WHERE uuid = ?", + msg.uuid, + ) + return err +} + +func (p *PubSub) nack(msg Message) error { + row := p.db.QueryRow( + "SELECT nack_count FROM pubsub WHERE uuid = ? LIMIT 1", + msg.uuid, + ) + + var nackCount int + if err := row.Scan(&nackCount); err != nil { + return errors.Wrap(err, "error calling scan") + } + + nackCount = nackCount + 1 + backoffDuration := p.backoffManager.GetMessageErrorBackoff(nackCount) + backoffUntil := time.Now().Add(backoffDuration) + + p.logger.Trace(). + WithField("until", backoffUntil). + WithField("duration", backoffDuration). + Message("backing off a message") + + if _, err := p.db.Exec( + "UPDATE pubsub SET nack_count = ?, backoff_until = ? WHERE uuid = ?", + nackCount, + backoffUntil.Unix(), + msg.uuid, + ); err != nil { + return errors.Wrap(err, "error updating the message") + } + + return nil +} + +type executor interface { + Exec(query string, args ...any) (sql.Result, error) +} + +const ( + maxDefaultMessageErrorBackoff = 6 * time.Hour + maxDefaultNoMessagesBackoff = 30 * time.Second + + randomizeMessageErrorBackoffByFraction = 0.1 +) + +type DefaultBackoffManager struct { +} + +func NewDefaultBackoffManager() DefaultBackoffManager { + return DefaultBackoffManager{} +} + +func (d DefaultBackoffManager) GetMessageErrorBackoff(nackCount int) time.Duration { + a := time.Duration(math.Pow(4, float64(nackCount-1))) * time.Second + value := min(a, maxDefaultMessageErrorBackoff) + if value <= 0 { + value = maxDefaultMessageErrorBackoff + } + randFraction := 1 - randomizeMessageErrorBackoffByFraction + 2*randomizeMessageErrorBackoffByFraction*rand.Float64() + return time.Duration(float64(value) * randFraction) +} + +func (d DefaultBackoffManager) GetNoMessagesBackoff(tick int) time.Duration { + a := time.Duration(math.Pow(2, float64(tick-1))) * time.Second + if a <= 0 { + return maxDefaultNoMessagesBackoff + } + return min(a, maxDefaultNoMessagesBackoff) +} diff --git a/service/adapters/sqlite/pubsub_test.go b/service/adapters/sqlite/pubsub_test.go new file mode 100644 index 0000000..2300b54 --- /dev/null +++ b/service/adapters/sqlite/pubsub_test.go @@ -0,0 +1,243 @@ +package sqlite_test + +import ( + "context" + "sync" + "testing" + "time" + + "github.com/planetary-social/nos-event-service/internal/fixtures" + "github.com/planetary-social/nos-event-service/service/adapters/sqlite" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestPubSub_PublishDoesNotReturnErrors(t *testing.T) { + t.Parallel() + + ctx := fixtures.TestContext(t) + adapters := NewTestAdapters(ctx, t) + + msg, err := sqlite.NewMessage(fixtures.SomeString(), nil) + require.NoError(t, err) + + err = adapters.PubSub.Publish(fixtures.SomeString(), msg) + require.NoError(t, err) +} + +func TestPubSub_PublishingMessagesWithIdenticalUUIDsReturnsAnError(t *testing.T) { + t.Parallel() + + ctx := fixtures.TestContext(t) + adapters := NewTestAdapters(ctx, t) + + msg, err := sqlite.NewMessage(fixtures.SomeString(), nil) + require.NoError(t, err) + + err = adapters.PubSub.Publish(fixtures.SomeString(), msg) + require.NoError(t, err) + + err = adapters.PubSub.Publish(fixtures.SomeString(), msg) + require.EqualError(t, err, "UNIQUE constraint failed: pubsub.uuid") +} + +func TestPubSub_NackedMessagesAreRetried(t *testing.T) { + t.Parallel() + + ctx := fixtures.TestContext(t) + adapters := NewTestAdapters(ctx, t) + + msg, err := sqlite.NewMessage(fixtures.SomeString(), nil) + require.NoError(t, err) + + topic := fixtures.SomeString() + + err = adapters.PubSub.Publish(topic, msg) + require.NoError(t, err) + + var msgs []*sqlite.ReceivedMessage + var msgsLock sync.Mutex + + go func() { + for msg := range adapters.PubSub.Subscribe(ctx, topic) { + msgsLock.Lock() + msgs = append(msgs, msg) + msgsLock.Unlock() + err := msg.Nack() + require.NoError(t, err) + } + }() + + require.EventuallyWithT(t, func(collect *assert.CollectT) { + msgsLock.Lock() + assert.GreaterOrEqual(collect, len(msgs), 2) + msgsLock.Unlock() + }, 10*time.Second, 100*time.Microsecond) +} + +func TestPubSub_MessageContainCorrectPayloadAndAckedMessagesAreNotRetried(t *testing.T) { + t.Parallel() + + testCases := []struct { + Name string + Payload []byte + }{ + { + Name: "nil", + Payload: nil, + }, + { + Name: "not_nil", + Payload: fixtures.SomeBytesOfLen(10), + }, + } + + for i := range testCases { + testCase := testCases[i] + + t.Run(testCase.Name, func(t *testing.T) { + t.Parallel() + + ctx := fixtures.TestContext(t) + adapters := NewTestAdapters(ctx, t) + + msg, err := sqlite.NewMessage(fixtures.SomeString(), testCase.Payload) + require.NoError(t, err) + + topic := fixtures.SomeString() + + err = adapters.PubSub.Publish(topic, msg) + require.NoError(t, err) + + var msgs []*sqlite.ReceivedMessage + var msgsLock sync.Mutex + + go func() { + for msg := range adapters.PubSub.Subscribe(ctx, topic) { + msgsLock.Lock() + msgs = append(msgs, msg) + msgsLock.Unlock() + err := msg.Ack() + require.NoError(t, err) + } + }() + + <-time.After(10 * time.Second) + msgsLock.Lock() + require.Len(t, msgs, 1) + require.Equal(t, msg.UUID(), msgs[0].UUID()) + require.Equal(t, msg.Payload(), msgs[0].Payload()) + msgsLock.Unlock() + }) + } +} + +func TestPubSub_NotAckedOrNackedMessagesBlock(t *testing.T) { + t.Parallel() + + ctx := fixtures.TestContext(t) + adapters := NewTestAdapters(ctx, t) + + msg, err := sqlite.NewMessage(fixtures.SomeString(), nil) + require.NoError(t, err) + + topic := fixtures.SomeString() + + err = adapters.PubSub.Publish(topic, msg) + require.NoError(t, err) + + var msgs []*sqlite.ReceivedMessage + var msgsLock sync.Mutex + + go func() { + for msg := range adapters.PubSub.Subscribe(ctx, topic) { + msgsLock.Lock() + msgs = append(msgs, msg) + msgsLock.Unlock() + } + }() + + <-time.After(10 * time.Second) + msgsLock.Lock() + require.Len(t, msgs, 1) + msgsLock.Unlock() +} + +func TestPubSub_QueueLengthReportsNumberOfElementsInQueue(t *testing.T) { + t.Parallel() + + ctx := fixtures.TestContext(t) + adapters := NewTestAdapters(ctx, t) + + msg1, err := sqlite.NewMessage(fixtures.SomeString(), nil) + require.NoError(t, err) + + msg2, err := sqlite.NewMessage(fixtures.SomeString(), nil) + require.NoError(t, err) + + topic := fixtures.SomeString() + + err = adapters.PubSub.Publish(topic, msg1) + require.NoError(t, err) + + n, err := adapters.PubSub.QueueLength(topic) + require.NoError(t, err) + require.Equal(t, 1, n) + + err = adapters.PubSub.Publish(topic, msg2) + require.NoError(t, err) + + n, err = adapters.PubSub.QueueLength(topic) + require.NoError(t, err) + require.Equal(t, 2, n) + + go func() { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + + for msg := range adapters.PubSub.Subscribe(ctx, topic) { + err := msg.Ack() + require.NoError(t, err) + return + } + }() + + require.EventuallyWithT(t, func(collect *assert.CollectT) { + n, err = adapters.PubSub.QueueLength(topic) + assert.NoError(t, err) + assert.Equal(t, 1, n) + }, 10*time.Second, 100*time.Millisecond) +} + +func TestDefaultBackoffManager_GetMessageErrorBackoffStatisticallyFallsWithinCertainEpsilon(t *testing.T) { + const numSamples = 1000 + + m := sqlite.NewDefaultBackoffManager() + for i := 1; i < 100; i++ { + var sum float64 + var avg float64 + + for samples := 0; samples < numSamples; samples++ { + backoff := m.GetMessageErrorBackoff(i) + require.Positive(t, backoff) + + if samples > numSamples/2 { + require.InEpsilonf(t, avg, backoff, 0.15, "failed for i=%d and sample=%d", i, samples) + } + + sum += float64(backoff) + avg = sum / float64(samples) + } + + t.Log(i, time.Duration(avg)) + } +} + +func TestDefaultBackoffManager_NoMessagesBackoffIsPositive(t *testing.T) { + m := sqlite.NewDefaultBackoffManager() + for i := 1; i < 100; i++ { + backoff := m.GetNoMessagesBackoff(i) + t.Log(backoff) + require.Positive(t, backoff) + } +} diff --git a/service/adapters/sqlite/sqlite.go b/service/adapters/sqlite/sqlite.go new file mode 100644 index 0000000..fbcc8f4 --- /dev/null +++ b/service/adapters/sqlite/sqlite.go @@ -0,0 +1,100 @@ +package sqlite + +import ( + "context" + "database/sql" + + "github.com/boreq/errors" + "github.com/hashicorp/go-multierror" + _ "github.com/mattn/go-sqlite3" + "github.com/planetary-social/nos-event-service/migrations" + "github.com/planetary-social/nos-event-service/service/app" + "github.com/planetary-social/nos-event-service/service/config" +) + +type TestAdapters struct { + EventRepository *EventRepository + Publisher *Publisher +} + +type TestedItems struct { + TransactionProvider *TestTransactionProvider + Subscriber *Subscriber + MigrationsStorage *MigrationsStorage + PubSub *PubSub + + MigrationsRunner *migrations.Runner + Migrations migrations.Migrations + MigrationsProgressCallback migrations.ProgressCallback +} + +func Open(conf config.Config) (*sql.DB, error) { + db, err := sql.Open("sqlite3", conf.DatabasePath()) + if err != nil { + return nil, errors.Wrap(err, "error opening the database") + } + + return db, nil +} + +type AdaptersFactoryFn = GenericAdaptersFactoryFn[app.Adapters] +type TransactionProvider = GenericTransactionProvider[app.Adapters] + +func NewTransactionProvider(db *sql.DB, fn AdaptersFactoryFn) *TransactionProvider { + return &TransactionProvider{ + db: db, + fn: fn, + } +} + +type TestAdaptersFactoryFn = GenericAdaptersFactoryFn[TestAdapters] +type TestTransactionProvider = GenericTransactionProvider[TestAdapters] + +func NewTestTransactionProvider(db *sql.DB, fn TestAdaptersFactoryFn) *TestTransactionProvider { + return &TestTransactionProvider{ + db: db, + fn: fn, + } +} + +type GenericAdaptersFactoryFn[T any] func(*sql.DB, *sql.Tx) (T, error) + +type GenericTransactionProvider[T any] struct { + db *sql.DB + fn GenericAdaptersFactoryFn[T] +} + +func NewGenericTransactionProvider[T any](db *sql.DB, fn GenericAdaptersFactoryFn[T]) *GenericTransactionProvider[T] { + return &GenericTransactionProvider[T]{ + db: db, + fn: fn, + } +} + +func (t *GenericTransactionProvider[T]) Transact(ctx context.Context, f func(context.Context, T) error) error { + tx, err := t.db.BeginTx(ctx, nil) + if err != nil { + return errors.Wrap(err, "error starting the transaction") + } + + adapters, err := t.fn(t.db, tx) + if err != nil { + if rollbackErr := tx.Rollback(); rollbackErr != nil { + err = multierror.Append(err, errors.Wrap(rollbackErr, "rollback error")) + } + return errors.Wrap(err, "error building the adapters") + } + + if err := f(ctx, adapters); err != nil { + if rollbackErr := tx.Rollback(); rollbackErr != nil { + err = multierror.Append(err, errors.Wrap(rollbackErr, "rollback error")) + } + return errors.Wrap(err, "error calling the provided function") + } + + if err := tx.Commit(); err != nil { + return errors.Wrap(err, "error committing the transaction") + } + + return nil +} diff --git a/service/adapters/sqlite/sqlite_test.go b/service/adapters/sqlite/sqlite_test.go new file mode 100644 index 0000000..d913645 --- /dev/null +++ b/service/adapters/sqlite/sqlite_test.go @@ -0,0 +1,22 @@ +package sqlite_test + +import ( + "context" + "testing" + + "github.com/planetary-social/nos-event-service/cmd/event-service/di" + "github.com/planetary-social/nos-event-service/service/adapters/sqlite" + "github.com/stretchr/testify/require" +) + +func NewTestAdapters(ctx context.Context, tb testing.TB) sqlite.TestedItems { + adapters, f, err := di.BuildTestAdapters(ctx, tb) + require.NoError(tb, err) + + tb.Cleanup(f) + + err = adapters.MigrationsRunner.Run(ctx, adapters.Migrations, adapters.MigrationsProgressCallback) + require.NoError(tb, err) + + return adapters +} diff --git a/service/adapters/sqlite/subscriber.go b/service/adapters/sqlite/subscriber.go new file mode 100644 index 0000000..c0d2c7e --- /dev/null +++ b/service/adapters/sqlite/subscriber.go @@ -0,0 +1,29 @@ +package sqlite + +import ( + "context" + "database/sql" +) + +type Subscriber struct { + pubsub *PubSub + db *sql.DB +} + +func NewSubscriber( + pubsub *PubSub, + db *sql.DB, +) *Subscriber { + return &Subscriber{ + pubsub: pubsub, + db: db, + } +} + +func (s *Subscriber) SubscribeToEventSaved(ctx context.Context) <-chan *ReceivedMessage { + return s.pubsub.Subscribe(ctx, EventSavedTopic) +} + +func (s *Subscriber) EventSavedQueueLength(ctx context.Context) (int, error) { + return s.pubsub.QueueLength(EventSavedTopic) +} diff --git a/service/app/app.go b/service/app/app.go new file mode 100644 index 0000000..a65b0e9 --- /dev/null +++ b/service/app/app.go @@ -0,0 +1,69 @@ +package app + +import ( + "context" + + "github.com/planetary-social/nos-event-service/service/domain" +) + +type TransactionProvider interface { + Transact(context.Context, func(context.Context, Adapters) error) error +} + +type Adapters struct { + Events EventRepository + Publisher Publisher +} + +type EventRepository interface { + Save(ctx context.Context, event domain.Event) error + Get(ctx context.Context, eventID domain.EventId) (domain.Event, error) +} + +type Publisher interface { + PublishEventSaved(ctx context.Context, id domain.EventId) error +} + +type ExternalEventPublisher interface { + PublishNewEventReceived(ctx context.Context, event domain.Event) error +} + +type Application struct { + SaveReceivedEvent *SaveReceivedEventHandler + ProcessSavedEvent *ProcessSavedEventHandler +} + +type ReceivedEvent struct { + relay domain.RelayAddress + event domain.Event +} + +func NewReceivedEvent(relay domain.RelayAddress, event domain.Event) ReceivedEvent { + return ReceivedEvent{relay: relay, event: event} +} + +func (r ReceivedEvent) Relay() domain.RelayAddress { + return r.relay +} + +func (r ReceivedEvent) Event() domain.Event { + return r.event +} + +type ReceivedEventSubscriber interface { + Subscribe(ctx context.Context) <-chan ReceivedEvent +} + +type Metrics interface { + StartApplicationCall(handlerName string) ApplicationCall +} + +type ApplicationCall interface { + // End accepts a pointer so that you can defer this call without wrapping it + // in an anonymous function. + End(err *error) +} + +type RelaysExtractor interface { + Extract(event domain.Event) ([]domain.MaybeRelayAddress, error) +} diff --git a/service/app/downloader.go b/service/app/downloader.go new file mode 100644 index 0000000..c463c6c --- /dev/null +++ b/service/app/downloader.go @@ -0,0 +1,327 @@ +package app + +import ( + "context" + "fmt" + "sync" + "time" + + "github.com/boreq/errors" + "github.com/planetary-social/nos-event-service/internal" + "github.com/planetary-social/nos-event-service/internal/logging" + "github.com/planetary-social/nos-event-service/service/domain" + "github.com/planetary-social/nos-event-service/service/domain/relays" +) + +const ( + howFarIntoThePastToLook = 24 * time.Hour + storeMetricsEvery = 30 * time.Second + refreshDownloaderPublicKeysEvery = 1 * time.Minute + refreshPublicKeyDownloaderRelaysEvery = 1 * time.Minute +) + +type ReceivedEventPublisher interface { + Publish(relay domain.RelayAddress, event domain.Event) +} + +type BootstrapRelaySource interface { + GetRelays(ctx context.Context) ([]domain.RelayAddress, error) +} + +type RelaySource interface { + GetRelays(ctx context.Context) ([]domain.RelayAddress, error) +} + +type RelayConnections interface { + GetEvents(ctx context.Context, relayAddress domain.RelayAddress, filter domain.Filter) (<-chan relays.EventOrEndOfSavedEvents, error) +} + +type Downloader struct { + relayDownloaders map[domain.RelayAddress]context.CancelFunc + relayDownloadersLock sync.Mutex + + bootstrapRelaySource BootstrapRelaySource + relaySource RelaySource + relayConnections RelayConnections + receivedEventPublisher ReceivedEventPublisher + logger logging.Logger + //metrics Metrics + //relayEventDownloader RelayEventDownloader +} + +func NewDownloader( + bootstrapRelaySource BootstrapRelaySource, + relaySource RelaySource, + relayConnections RelayConnections, + receivedEventPublisher ReceivedEventPublisher, + logger logging.Logger, +) *Downloader { + return &Downloader{ + relayDownloaders: make(map[domain.RelayAddress]context.CancelFunc), + + bootstrapRelaySource: bootstrapRelaySource, + relaySource: relaySource, + relayConnections: relayConnections, + receivedEventPublisher: receivedEventPublisher, + logger: logger.New("downloader"), + } +} + +func (d *Downloader) Run(ctx context.Context) error { + //go d.storeMetricsLoop(ctx) + + for { + if err := d.updateDownloaders(ctx); err != nil { + d.logger.Error(). + WithError(err). + Message("error updating relays") + } + + select { + case <-time.After(refreshDownloaderPublicKeysEvery): + case <-ctx.Done(): + return ctx.Err() + } + } +} + +//func (d *Downloader) storeMetricsLoop(ctx context.Context) { +// for { +// d.storeMetrics() +// +// select { +// case <-time.After(storeMetricsEvery): +// case <-ctx.Done(): +// return +// } +// } +//} +// +//func (d *Downloader) storeMetrics() { +// d.publicKeyDownloadersLock.Lock() +// defer d.publicKeyDownloadersLock.Unlock() +// +// d.metrics.ReportNumberOfPublicKeyDownloaders(len(d.publicKeyDownloaders)) +//} + +func (d *Downloader) updateDownloaders(ctx context.Context) error { + relays, err := d.getRelays(ctx) + if err != nil { + return errors.Wrap(err, "error getting relays") + } + + d.relayDownloadersLock.Lock() + defer d.relayDownloadersLock.Unlock() + + for relayAddress, cancelFn := range d.relayDownloaders { + if !relays.Contains(relayAddress) { + d.logger. + Trace(). + WithField("address", relayAddress.String()). + Message("stopping a downloader") + delete(d.relayDownloaders, relayAddress) + cancelFn() + } + } + + for _, relayAddress := range relays.List() { + if _, ok := d.relayDownloaders[relayAddress]; !ok { + d.logger.Trace(). + WithField("address", relayAddress.String()). + Message("creating a downloader") + + downloader := NewRelayDownloader( + d.receivedEventPublisher, + d.relayConnections, + d.logger, + relayAddress, + ) + + ctx, cancel := context.WithCancel(ctx) + go downloader.Run(ctx) + d.relayDownloaders[relayAddress] = cancel + } + } + + return nil +} + +func (d *Downloader) getRelays(ctx context.Context) (*internal.Set[domain.RelayAddress], error) { + result := internal.NewEmptySet[domain.RelayAddress]() + + bootstrapRelays, err := d.bootstrapRelaySource.GetRelays(ctx) + if err != nil { + return nil, errors.Wrap(err, "error getting bootstrap relays") + } + result.PutMany(bootstrapRelays) + + relays, err := d.relaySource.GetRelays(ctx) + if err != nil { + return nil, errors.Wrap(err, "error getting relays") + } + result.PutMany(relays) + + return result, nil +} + +type RelayDownloader struct { + address domain.RelayAddress + + //downloaders map[relays.RelayAddress]context.CancelFunc + //downloadersLock sync.Mutex + + receivedEventPublisher ReceivedEventPublisher + relayConnections RelayConnections + logger logging.Logger +} + +func NewRelayDownloader( + receivedEventPublisher ReceivedEventPublisher, + relayConnections RelayConnections, + logger logging.Logger, + address domain.RelayAddress, +) *RelayDownloader { + v := &RelayDownloader{ + address: address, + + receivedEventPublisher: receivedEventPublisher, + relayConnections: relayConnections, + logger: logger.New(fmt.Sprintf("relayDownloader(%s)", address.String())), + } + return v +} + +func (d *RelayDownloader) Run(ctx context.Context) { + //go d.storeMetricsLoop(ctx) + + go d.downloadMessages(ctx, domain.NewFilter(nil, d.eventKindsToDownloadForEveryone(), nil, d.downloadSince())) + + //for { + // if err := d.refreshRelays(ctx); err != nil { + // d.logger.Error(). + // WithError(err). + // Message("error connecting and downloading") + // } + // + // select { + // case <-ctx.Done(): + // return + // case <-time.After(refreshPublicKeyDownloaderRelaysEvery): + // continue + // } + //} +} + +func (d *RelayDownloader) eventKindsToDownloadForEveryone() []domain.EventKind { + return []domain.EventKind{ + domain.EventKindMetadata, + domain.EventKindRecommendedRelay, + domain.EventKindContacts, + domain.EventKindRelayListMetadata, + } +} + +func (d *RelayDownloader) downloadSince() *time.Time { + return internal.Pointer(time.Now().Add(-howFarIntoThePastToLook)) + +} + +//func (d *RelayDownloader) storeMetricsLoop(ctx context.Context) { +// for { +// d.storeMetrics() +// +// select { +// case <-time.After(storeMetricsEvery): +// case <-ctx.Done(): +// return +// } +// } +//} +// +//func (d *RelayDownloader) storeMetrics() { +// d.downloadersLock.Lock() +// defer d.downloadersLock.Unlock() +// +// d.metrics.ReportNumberOfPublicKeyDownloaderRelays(d.publicKey, len(d.downloaders)) +//} +// +//func (d *RelayDownloader) refreshRelays(ctx context.Context) error { +// relayAddressesSet, err := d.getRelayAddresses(ctx) +// if err != nil { +// return errors.Wrap(err, "error getting relay addresses") +// } +// +// d.downloadersLock.Lock() +// defer d.downloadersLock.Unlock() +// +// for relayAddress, cancelFn := range d.downloaders { +// if !relayAddressesSet.Contains(relayAddress) { +// d.logger.Trace(). +// WithField("relayAddress", relayAddress.String()). +// Message("stopping a relay downloader") +// delete(d.downloaders, relayAddress) +// cancelFn() +// } +// } +// +// for _, relayAddress := range relayAddressesSet.List() { +// if _, ok := d.downloaders[relayAddress]; !ok { +// d.logger.Trace(). +// WithField("relayAddress", relayAddress.String()). +// Message("creating a relay downloader") +// +// ctx, cancel := context.WithCancel(ctx) +// go d.downloadMessages(ctx, relayAddress) +// d.downloaders[relayAddress] = cancel +// } +// } +// +// return nil +//} +// +//func (d *RelayDownloader) getRelayAddresses(ctx context.Context) (*internal.Set[relays.RelayAddress], error) { +// ctx, cancel := context.WithCancel(ctx) +// defer cancel() +// +// relayAddresses, err := d.relaySource.GetRelays(ctx, d.publicKey) +// if err != nil { +// return nil, errors.Wrap(err, "error getting relayAddresses") +// } +// +// d.logger.Debug(). +// WithField("numberOfAddresses", len(relayAddresses)). +// WithField("publicKey", d.publicKey.Hex()). +// Message("got relay addresses") +// +// normalizedRelayAddresses := internal.NewEmptySet[relays.RelayAddress]() +// for _, relayAddress := range relayAddresses { +// normalizedRelayAddress, err := domain.NormalizeRelayAddress(relayAddress) +// if err != nil { +// return nil, errors.Wrapf(err, "error normalizing a relay address '%s'", relayAddress.String()) +// } +// normalizedRelayAddresses.Put(normalizedRelayAddress) +// } +// +// return normalizedRelayAddresses, nil +//} + +func (d *RelayDownloader) downloadMessages(ctx context.Context, filter domain.Filter) { + if err := d.downloadMessagesWithErr(ctx, filter); err != nil { + d.logger.Error().WithError(err).Message("error downloading messages") + } +} + +func (d *RelayDownloader) downloadMessagesWithErr(ctx context.Context, filter domain.Filter) error { + ch, err := d.relayConnections.GetEvents(ctx, d.address, filter) + if err != nil { + return errors.Wrap(err, "error getting events ch") + } + + for eventOrEOSE := range ch { + if !eventOrEOSE.EOSE() { + d.receivedEventPublisher.Publish(d.address, eventOrEOSE.Event()) + } + } + + return nil +} diff --git a/service/app/handler_process_saved_event.go b/service/app/handler_process_saved_event.go new file mode 100644 index 0000000..8a8f8b9 --- /dev/null +++ b/service/app/handler_process_saved_event.go @@ -0,0 +1,73 @@ +package app + +import ( + "context" + + "github.com/boreq/errors" + "github.com/planetary-social/nos-event-service/internal/logging" + "github.com/planetary-social/nos-event-service/service/domain" +) + +type ProcessSavedEvent struct { + id domain.EventId +} + +func NewProcessSavedEvent(id domain.EventId) ProcessSavedEvent { + return ProcessSavedEvent{id: id} +} + +type ProcessSavedEventHandler struct { + transactionProvider TransactionProvider + relaysExtractor RelaysExtractor + logger logging.Logger + metrics Metrics +} + +func NewProcessSavedEventHandler( + transactionProvider TransactionProvider, + relaysExtractor RelaysExtractor, + logger logging.Logger, + metrics Metrics, +) *ProcessSavedEventHandler { + return &ProcessSavedEventHandler{ + transactionProvider: transactionProvider, + relaysExtractor: relaysExtractor, + logger: logger.New("processSavedEventHandler"), + metrics: metrics, + } +} + +func (h *ProcessSavedEventHandler) Handle(ctx context.Context, cmd ProcessSavedEvent) (err error) { + defer h.metrics.StartApplicationCall("processSavedEvent").End(&err) + + h.logger. + Trace(). + WithField("eventID", cmd.id). + Message("processing saved event") + + var event domain.Event + if err := h.transactionProvider.Transact(ctx, func(ctx context.Context, adapters Adapters) error { + tmp, err := adapters.Events.Get(ctx, cmd.id) + if err != nil { + return errors.Wrap(err, "error loading the event") + } + event = tmp + return nil + }); err != nil { + return errors.Wrap(err, "transaction error") + } + + maybeRelayAddresses, err := h.relaysExtractor.Extract(event) + if err != nil { + return errors.Wrap(err, "error extracting relay addresses from event") + } + + if len(maybeRelayAddresses) == 0 && !(event.Kind() == domain.EventKindContacts && event.Content() == "") { + h.logger.Debug().WithField("event", event.String()).WithField("addresses", maybeRelayAddresses).Message("addresses") + } + + // todo save relays + // todo publish event + + return nil +} diff --git a/service/app/handler_save_received_event.go b/service/app/handler_save_received_event.go new file mode 100644 index 0000000..8c5a504 --- /dev/null +++ b/service/app/handler_save_received_event.go @@ -0,0 +1,66 @@ +package app + +import ( + "context" + + "github.com/boreq/errors" + "github.com/planetary-social/nos-event-service/internal/logging" + "github.com/planetary-social/nos-event-service/service/domain" +) + +type SaveReceivedEvent struct { + relay domain.RelayAddress + event domain.Event +} + +func NewSaveReceivedEvent(relay domain.RelayAddress, event domain.Event) SaveReceivedEvent { + return SaveReceivedEvent{relay: relay, event: event} +} + +type SaveReceivedEventHandler struct { + transactionProvider TransactionProvider + logger logging.Logger + metrics Metrics +} + +func NewSaveReceivedEventHandler( + transactionProvider TransactionProvider, + logger logging.Logger, + metrics Metrics, +) *SaveReceivedEventHandler { + return &SaveReceivedEventHandler{ + transactionProvider: transactionProvider, + logger: logger.New("saveReceivedEventHandler"), + metrics: metrics, + } +} + +func (h *SaveReceivedEventHandler) Handle(ctx context.Context, cmd SaveReceivedEvent) (err error) { + defer h.metrics.StartApplicationCall("saveReceivedEvent").End(&err) + + h.logger. + Trace(). + WithField("relay", cmd.relay.String()). + WithField("event.id", cmd.event.Id().Hex()). + WithField("event.createdAt", cmd.event.CreatedAt().String()). + WithField("event.kind", cmd.event.Kind().Int()). + Message("saving received event") + + if err := h.transactionProvider.Transact(ctx, func(ctx context.Context, adapters Adapters) error { + // todo check if event should be saved + + if err := adapters.Events.Save(ctx, cmd.event); err != nil { + return errors.Wrap(err, "error saving the event") + } + + if err := adapters.Publisher.PublishEventSaved(ctx, cmd.event.Id()); err != nil { + return errors.Wrap(err, "error publishing") + } + + return nil + }); err != nil { + return errors.Wrap(err, "transaction error") + } + + return nil +} diff --git a/service/app/mock_relay_source.go b/service/app/mock_relay_source.go new file mode 100644 index 0000000..07c3467 --- /dev/null +++ b/service/app/mock_relay_source.go @@ -0,0 +1,18 @@ +package app + +import ( + "context" + + "github.com/planetary-social/nos-event-service/service/domain" +) + +type MockRelaySource struct { +} + +func NewMockRelaySource() *MockRelaySource { + return &MockRelaySource{} +} + +func (m MockRelaySource) GetRelays(ctx context.Context) ([]domain.RelayAddress, error) { + return nil, nil +} diff --git a/service/config/config.go b/service/config/config.go new file mode 100644 index 0000000..5befc8e --- /dev/null +++ b/service/config/config.go @@ -0,0 +1,120 @@ +package config + +import ( + "fmt" + + "github.com/boreq/errors" + "github.com/planetary-social/nos-event-service/internal/logging" +) + +type Environment struct { + s string +} + +var ( + EnvironmentProduction = Environment{"production"} + EnvironmentDevelopment = Environment{"development"} +) + +type Config struct { + listenAddress string + + environment Environment + logLevel logging.Level + + googlePubSubEnabled bool + googlePubSubProjectID string + googlePubSubCredentialsJSON []byte + + databasePath string +} + +func NewConfig( + listenAddress string, + environment Environment, + logLevel logging.Level, + googlePubSubEnabled bool, + googlePubSubProjectID string, + googlePubSubCredentialsJSON []byte, + databasePath string, +) (Config, error) { + c := Config{ + listenAddress: listenAddress, + environment: environment, + logLevel: logLevel, + googlePubSubEnabled: googlePubSubEnabled, + googlePubSubProjectID: googlePubSubProjectID, + googlePubSubCredentialsJSON: googlePubSubCredentialsJSON, + databasePath: databasePath, + } + + c.setDefaults() + if err := c.validate(); err != nil { + return Config{}, errors.Wrap(err, "invalid config") + } + + return c, nil +} + +func (c *Config) ListenAddress() string { + return c.listenAddress +} + +func (c *Config) Environment() Environment { + return c.environment +} + +func (c *Config) LogLevel() logging.Level { + return c.logLevel +} + +func (c *Config) GooglePubSubEnabled() bool { + return c.googlePubSubEnabled +} + +func (c *Config) GooglePubSubProjectID() string { + return c.googlePubSubProjectID +} + +func (c *Config) GooglePubSubCredentialsJSON() []byte { + return c.googlePubSubCredentialsJSON +} + +func (c *Config) DatabasePath() string { + return c.databasePath +} + +func (c *Config) setDefaults() { + if c.listenAddress == "" { + c.listenAddress = ":8008" + } +} + +func (c *Config) validate() error { + if c.listenAddress == "" { + return errors.New("missing listen address") + } + + switch c.environment { + case EnvironmentProduction: + case EnvironmentDevelopment: + default: + return fmt.Errorf("unknown environment '%+v'", c.environment) + } + + if c.googlePubSubEnabled { + if c.googlePubSubProjectID == "" { + return errors.New("missing google pub sub project id") + } + + if len(c.googlePubSubCredentialsJSON) == 0 { + return errors.New("missing google pub sub credentials json") + } + } + + if c.databasePath == "" { + return errors.New("missing database path") + } + + return nil +} diff --git a/service/domain/event.go b/service/domain/event.go new file mode 100644 index 0000000..e3b7052 --- /dev/null +++ b/service/domain/event.go @@ -0,0 +1,133 @@ +package domain + +import ( + "encoding/json" + "time" + + "github.com/boreq/errors" + "github.com/nbd-wtf/go-nostr" + "github.com/planetary-social/nos-event-service/internal" +) + +type Event struct { + id EventId + pubKey PublicKey + createdAt time.Time + kind EventKind + tags []EventTag + content string + sig EventSignature + + libevent nostr.Event +} + +func NewEventFromRaw(raw []byte) (Event, error) { + var libevent nostr.Event + if err := json.Unmarshal(raw, &libevent); err != nil { + return Event{}, errors.Wrap(err, "error unmarshaling") + + } + return NewEvent(libevent) +} + +func NewEvent(libevent nostr.Event) (Event, error) { + ok, err := libevent.CheckSignature() + if err != nil { + return Event{}, errors.Wrap(err, "error checking signature") + } + + if !ok { + return Event{}, errors.New("invalid signature") + } + + id, err := NewEventId(libevent.ID) + if err != nil { + return Event{}, errors.Wrap(err, "error creating an event id") + } + + pubKey, err := NewPublicKeyFromHex(libevent.PubKey) + if err != nil { + return Event{}, errors.Wrap(err, "error creating a pub key") + } + + createdAt := time.Unix(int64(libevent.CreatedAt), 0).UTC() + + kind, err := NewEventKind(libevent.Kind) + if err != nil { + return Event{}, errors.Wrap(err, "error creating event kind") + } + + var tags []EventTag + for _, libtag := range libevent.Tags { + eventTag, err := NewEventTag(libtag) + if err != nil { + return Event{}, errors.Wrap(err, "error creating a tag") + } + tags = append(tags, eventTag) + } + + sig, err := NewEventSignature(libevent.Sig) + if err != nil { + return Event{}, errors.Wrap(err, "error creating a signature") + } + + return Event{ + id: id, + pubKey: pubKey, + createdAt: createdAt, + kind: kind, + tags: tags, + content: libevent.Content, + sig: sig, + + libevent: libevent, + }, nil +} + +func (e Event) Id() EventId { + return e.id +} + +func (e Event) PubKey() PublicKey { + return e.pubKey +} + +func (e Event) CreatedAt() time.Time { + return e.createdAt +} + +func (e Event) Kind() EventKind { + return e.kind +} + +func (e Event) Tags() []EventTag { + return internal.CopySlice(e.tags) +} + +func (e Event) Content() string { + return e.content +} + +func (e Event) Sig() EventSignature { + return e.sig +} + +func (e Event) Libevent() nostr.Event { + return e.libevent +} + +func (e Event) MarshalJSON() ([]byte, error) { + return e.libevent.MarshalJSON() +} + +func (e Event) Raw() []byte { + j, err := e.libevent.MarshalJSON() + if err != nil { + panic(err) + } + return j +} + +func (e Event) String() string { + return string(e.Raw()) +} diff --git a/service/domain/event_id.go b/service/domain/event_id.go new file mode 100644 index 0000000..1eb22d1 --- /dev/null +++ b/service/domain/event_id.go @@ -0,0 +1,62 @@ +package domain + +import ( + "crypto/sha256" + "encoding/hex" + + "github.com/boreq/errors" + "github.com/nbd-wtf/go-nostr/nip19" +) + +type EventId struct { + s string +} + +func NewEventId(s string) (EventId, error) { + b, err := hex.DecodeString(s) + if err != nil { + return EventId{}, errors.Wrap(err, "error decoding hex") + } + + if len(b) != sha256.Size { + return EventId{}, errors.New("invalid length") + } + + s = hex.EncodeToString(b) + return EventId{s}, nil +} + +func MustNewEventId(s string) EventId { + v, err := NewEventId(s) + if err != nil { + panic(err) + } + return v +} + +func NewEventIdFromNote(s string) (EventId, error) { + prefix, value, err := nip19.Decode(s) + if err != nil { + return EventId{}, errors.Wrap(err, "error calling nip19 decode") + } + if prefix != "note" { + return EventId{}, errors.New("invalid prefix") + } + s, ok := value.(string) + if !ok { + return EventId{}, errors.New("library returned invalid type") + } + return NewEventId(s) +} + +func (id EventId) Hex() string { + return id.s +} + +func (id EventId) Bytes() []byte { + b, err := hex.DecodeString(id.s) + if err != nil { + panic(err) + } + return b +} diff --git a/service/domain/event_kind.go b/service/domain/event_kind.go new file mode 100644 index 0000000..e57cbbd --- /dev/null +++ b/service/domain/event_kind.go @@ -0,0 +1,38 @@ +package domain + +import ( + "github.com/boreq/errors" +) + +var ( + EventKindMetadata = MustNewEventKind(0) + EventKindNote = MustNewEventKind(1) + EventKindRecommendedRelay = MustNewEventKind(2) + EventKindContacts = MustNewEventKind(3) + EventKindEncryptedDirectMessage = MustNewEventKind(4) + EventKindReaction = MustNewEventKind(7) + EventKindRelayListMetadata = MustNewEventKind(10002) +) + +type EventKind struct { + k int +} + +func NewEventKind(k int) (EventKind, error) { + if k < 0 { + return EventKind{}, errors.New("kind must be positive") + } + return EventKind{k}, nil +} + +func MustNewEventKind(k int) EventKind { + v, err := NewEventKind(k) + if err != nil { + panic(err) + } + return v +} + +func (k EventKind) Int() int { + return k.k +} diff --git a/service/domain/event_signature.go b/service/domain/event_signature.go new file mode 100644 index 0000000..a7181a1 --- /dev/null +++ b/service/domain/event_signature.go @@ -0,0 +1,37 @@ +package domain + +import ( + "encoding/hex" + + "github.com/boreq/errors" +) + +type EventSignature struct { + s string +} + +func NewEventSignature(s string) (EventSignature, error) { + b, err := hex.DecodeString(s) + if err != nil { + return EventSignature{}, errors.Wrap(err, "error decoding hex") + } + + if len(b) != 64 { + return EventSignature{}, errors.New("invalid length") + } + + s = hex.EncodeToString(b) + return EventSignature{s}, nil +} + +func (sig EventSignature) Hex() string { + return sig.s +} + +func (sig EventSignature) Bytes() []byte { + b, err := hex.DecodeString(sig.s) + if err != nil { + panic(err) + } + return b +} diff --git a/service/domain/filter.go b/service/domain/filter.go new file mode 100644 index 0000000..5aa9f07 --- /dev/null +++ b/service/domain/filter.go @@ -0,0 +1,58 @@ +package domain + +import ( + "time" + + "github.com/nbd-wtf/go-nostr" + "github.com/planetary-social/nos-event-service/internal" +) + +type Filter struct { + filter nostr.Filter +} + +func NewFilter( + eventIDs []EventId, + eventKinds []EventKind, + authors []PublicKey, + since *time.Time, +) Filter { + filter := nostr.Filter{ + IDs: nil, + Kinds: nil, + Authors: nil, + Tags: nil, + Since: nil, + Until: nil, + Limit: 0, + Search: "", + } + + for _, eventID := range eventIDs { + filter.IDs = append(filter.IDs, eventID.Hex()) + } + + for _, eventKind := range eventKinds { + filter.Kinds = append(filter.Kinds, eventKind.Int()) + } + + for _, author := range authors { + filter.Authors = append(filter.Authors, author.Hex()) + } + + if since != nil { + filter.Since = internal.Pointer(nostr.Timestamp(since.Unix())) + } + + return Filter{ + filter: filter, + } +} + +func (e Filter) Libfilter() nostr.Filter { + return e.filter +} + +func (e Filter) MarshalJSON() ([]byte, error) { + return e.filter.MarshalJSON() +} diff --git a/service/domain/public_key.go b/service/domain/public_key.go new file mode 100644 index 0000000..78a4ce6 --- /dev/null +++ b/service/domain/public_key.go @@ -0,0 +1,52 @@ +package domain + +import ( + "encoding/hex" + + "github.com/boreq/errors" + "github.com/decred/dcrd/dcrec/secp256k1/v4" + "github.com/nbd-wtf/go-nostr/nip19" +) + +type PublicKey struct { + s string +} + +func NewPublicKeyFromHex(s string) (PublicKey, error) { + b, err := hex.DecodeString(s) + if err != nil { + return PublicKey{}, errors.Wrap(err, "error decoding hex") + } + + if len(b) != secp256k1.PrivKeyBytesLen { + return PublicKey{}, errors.New("invalid length") + } + + s = hex.EncodeToString(b) + return PublicKey{s}, nil +} + +func NewPublicKeyFromNpub(s string) (PublicKey, error) { + prefix, hexString, err := nip19.Decode(s) + if err != nil { + return PublicKey{}, errors.Wrap(err, "error decoding a nip19 entity") + } + + if prefix != "npub" { + return PublicKey{}, errors.New("passed something which isn't an npub") + } + + return NewPublicKeyFromHex(hexString.(string)) +} + +func (k PublicKey) Hex() string { + return k.s +} + +func (k PublicKey) Bytes() []byte { + b, err := hex.DecodeString(k.s) + if err != nil { + panic(err) + } + return b +} diff --git a/service/domain/public_key_test.go b/service/domain/public_key_test.go new file mode 100644 index 0000000..63391d8 --- /dev/null +++ b/service/domain/public_key_test.go @@ -0,0 +1,26 @@ +package domain_test + +import ( + "strings" + "testing" + + "github.com/planetary-social/nos-event-service/internal/fixtures" + "github.com/planetary-social/nos-event-service/service/domain" + "github.com/stretchr/testify/require" +) + +func TestPublicKey_IsCaseInsensitive(t *testing.T) { + hex := fixtures.SomeHexBytesOfLen(32) + hexLower := strings.ToLower(hex) + hexUpper := strings.ToUpper(hex) + + require.NotEqual(t, hexLower, hexUpper) + + a, err := domain.NewPublicKeyFromHex(hexLower) + require.NoError(t, err) + + b, err := domain.NewPublicKeyFromHex(hexUpper) + require.NoError(t, err) + + require.Equal(t, a, b) +} diff --git a/service/domain/relay_address.go b/service/domain/relay_address.go new file mode 100644 index 0000000..b3e2b87 --- /dev/null +++ b/service/domain/relay_address.go @@ -0,0 +1,30 @@ +package domain + +import ( + "strings" + + "github.com/boreq/errors" +) + +type RelayAddress struct { + s string +} + +func NewRelayAddress(s string) (RelayAddress, error) { + if !strings.HasPrefix(s, "ws://") && !strings.HasPrefix(s, "wss://") { + return RelayAddress{}, errors.New("invalid protocol") + } + return RelayAddress{s: s}, nil +} + +func MustNewRelayAddress(s string) RelayAddress { + v, err := NewRelayAddress(s) + if err != nil { + panic(err) + } + return v +} + +func (r RelayAddress) String() string { + return r.s +} diff --git a/service/domain/relays/bootstrap_relay_source.go b/service/domain/relays/bootstrap_relay_source.go new file mode 100644 index 0000000..2d1e69a --- /dev/null +++ b/service/domain/relays/bootstrap_relay_source.go @@ -0,0 +1,25 @@ +package relays + +import ( + "context" + + "github.com/planetary-social/nos-event-service/internal" + "github.com/planetary-social/nos-event-service/service/domain" +) + +var bootstrapRelayAddresses = []domain.RelayAddress{ + domain.MustNewRelayAddress("wss://relay.damus.io"), + domain.MustNewRelayAddress("wss://nos.lol"), + domain.MustNewRelayAddress("wss://relay.current.fyi"), +} + +type BootstrapRelaySource struct { +} + +func NewBootstrapRelaySource() *BootstrapRelaySource { + return &BootstrapRelaySource{} +} + +func (p BootstrapRelaySource) GetRelays(ctx context.Context) ([]domain.RelayAddress, error) { + return internal.CopySlice(bootstrapRelayAddresses), nil +} diff --git a/service/domain/relays/event_or_end_of_saved_events.go b/service/domain/relays/event_or_end_of_saved_events.go new file mode 100644 index 0000000..e6da3e0 --- /dev/null +++ b/service/domain/relays/event_or_end_of_saved_events.go @@ -0,0 +1,24 @@ +package relays + +import "github.com/planetary-social/nos-event-service/service/domain" + +type EventOrEndOfSavedEvents struct { + event domain.Event + eose bool +} + +func NewEventOrEndOfSavedEventsWithEvent(event domain.Event) EventOrEndOfSavedEvents { + return EventOrEndOfSavedEvents{event: event} +} + +func NewEventOrEndOfSavedEventsWithEOSE() EventOrEndOfSavedEvents { + return EventOrEndOfSavedEvents{eose: true} +} + +func (e *EventOrEndOfSavedEvents) Event() domain.Event { + return e.event +} + +func (e *EventOrEndOfSavedEvents) EOSE() bool { + return e.eose +} diff --git a/service/domain/relays/relay_connection.go b/service/domain/relays/relay_connection.go new file mode 100644 index 0000000..69ec308 --- /dev/null +++ b/service/domain/relays/relay_connection.go @@ -0,0 +1,375 @@ +package relays + +import ( + "context" + "encoding/hex" + "fmt" + "sync" + "time" + + "github.com/boreq/errors" + "github.com/gorilla/websocket" + "github.com/nbd-wtf/go-nostr" + "github.com/oklog/ulid/v2" + "github.com/planetary-social/nos-event-service/internal" + "github.com/planetary-social/nos-event-service/internal/logging" + "github.com/planetary-social/nos-event-service/service/domain" + transport2 "github.com/planetary-social/nos-event-service/service/domain/relays/transport" +) + +const ( + reconnectAfter = 1 * time.Minute +) + +type RelayConnection struct { + address domain.RelayAddress + logger logging.Logger + + state RelayConnectionState + stateMutex sync.Mutex + + subscriptions map[transport2.SubscriptionID]subscription + subscriptionsUpdatedCh chan struct{} + subscriptionsUpdatedChClosed bool + subscriptionsMutex sync.Mutex +} + +func NewRelayConnection(address domain.RelayAddress, logger logging.Logger) *RelayConnection { + return &RelayConnection{ + address: address, + logger: logger.New(fmt.Sprintf("relayConnection(%s)", address.String())), + state: RelayConnectionStateInitializing, + subscriptions: make(map[transport2.SubscriptionID]subscription), + subscriptionsUpdatedCh: make(chan struct{}), + } +} + +func (r *RelayConnection) Run(ctx context.Context) { + for { + if err := r.run(ctx); err != nil { + l := r.logger.Error() + if r.errorIsCommonAndShouldNotBeLoggedOnErrorLevel(err) { + l = r.logger.Debug() + } + l.WithError(err).Message("encountered an error") + } + + select { + case <-ctx.Done(): + return + case <-time.After(reconnectAfter): + continue + } + } +} + +func (r *RelayConnection) errorIsCommonAndShouldNotBeLoggedOnErrorLevel(err error) bool { + if errors.Is(err, DialError{}) { + return true + } + + if errors.Is(err, ReadMessageError{}) { + return true + } + + return false +} + +func (r *RelayConnection) GetEvents(ctx context.Context, filter domain.Filter) (<-chan EventOrEndOfSavedEvents, error) { + r.subscriptionsMutex.Lock() + defer r.subscriptionsMutex.Unlock() + + ch := make(chan EventOrEndOfSavedEvents) + id, err := transport2.NewSubscriptionID(ulid.Make().String()) + if err != nil { + return nil, errors.Wrap(err, "error creating a subscription id") + } + + r.subscriptions[id] = subscription{ + ctx: ctx, + ch: ch, + id: id, + filter: filter, + } + + r.triggerSubscriptionUpdate() + + go func() { + <-ctx.Done() + if err := r.removeChannel(ch); err != nil { + panic(err) + } + }() + + return ch, nil +} + +func (r *RelayConnection) State() RelayConnectionState { + r.stateMutex.Lock() + defer r.stateMutex.Unlock() + return r.state +} + +func (r *RelayConnection) Address() domain.RelayAddress { + return r.address +} + +func (r *RelayConnection) removeChannel(chToRemove chan EventOrEndOfSavedEvents) error { + r.subscriptionsMutex.Lock() + defer r.subscriptionsMutex.Unlock() + + for uuid, subscription := range r.subscriptions { + if chToRemove == subscription.ch { + close(subscription.ch) + delete(r.subscriptions, uuid) + r.triggerSubscriptionUpdate() + return nil + } + } + + return errors.New("somehow the channel was already removed") +} + +func (r *RelayConnection) triggerSubscriptionUpdate() { + if !r.subscriptionsUpdatedChClosed { + r.subscriptionsUpdatedChClosed = true + close(r.subscriptionsUpdatedCh) + } +} + +func (r *RelayConnection) resetSubscriptionUpdateCh() { + r.subscriptionsUpdatedChClosed = false + r.subscriptionsUpdatedCh = make(chan struct{}) +} + +func (r *RelayConnection) run(ctx context.Context) error { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + + defer r.setState(RelayConnectionStateDisconnected) + + r.logger.Trace().Message("connecting") + + conn, _, err := websocket.DefaultDialer.DialContext(ctx, r.address.String(), nil) + if err != nil { + return NewDialError(err) + } + + r.setState(RelayConnectionStateConnected) + r.logger.Trace().Message("connected") + + go func() { + <-ctx.Done() + if err := conn.Close(); err != nil { + r.logger.Debug().WithError(err).Message("error when closing connection due to closed context") + } + }() + + go func() { + if err := r.manageSubs(ctx, conn); err != nil { + if !errors.Is(err, context.Canceled) { + r.logger.Error(). + WithError(err). + Message("error managing subs") + } + } + }() + + for { + _, messageBytes, err := conn.ReadMessage() + if err != nil { + return NewReadMessageError(err) + } + + if err := r.handleMessage(messageBytes); err != nil { + return errors.Wrap(err, "error handling message") + } + } +} + +func (r *RelayConnection) handleMessage(messageBytes []byte) error { + envelope := nostr.ParseMessage(messageBytes) + if envelope == nil { + r.logger.Error(). + WithField("messageBytesAsHex", hex.EncodeToString(messageBytes)). + Message("error parsing an incoming message") + return errors.New("error parsing message, we are never going to find out what error unfortunately due to the design of this library") + } + + switch v := envelope.(type) { + case *nostr.EOSEEnvelope: + r.logger.Trace(). + WithField("subscription", string(*v)). + Message("received EOSE") + subscriptionID, err := transport2.NewSubscriptionID(string(*v)) + if err != nil { + return errors.Wrapf(err, "error creating subscription id from '%s'", string(*v)) + } + r.passValueToChannel(subscriptionID, NewEventOrEndOfSavedEventsWithEOSE()) + case *nostr.EventEnvelope: + r.logger.Trace(). + WithField("subscription", *v.SubscriptionID). + Message("received event") + subscriptionID, err := transport2.NewSubscriptionID(*v.SubscriptionID) + if err != nil { + return errors.Wrapf(err, "error creating subscription id from '%s'", *v.SubscriptionID) + } + event, err := domain.NewEvent(v.Event) + if err != nil { + return errors.Wrap(err, "error creating an event") + } + r.passValueToChannel(subscriptionID, NewEventOrEndOfSavedEventsWithEvent(event)) + default: + r.logger.Debug(). + WithField("message", string(messageBytes)). + Message("unhandled message") + } + + return nil +} + +func (r *RelayConnection) passValueToChannel(id transport2.SubscriptionID, value EventOrEndOfSavedEvents) { + r.subscriptionsMutex.Lock() + defer r.subscriptionsMutex.Unlock() + + if sub, ok := r.subscriptions[id]; ok { + select { + case <-sub.ctx.Done(): + case sub.ch <- value: + } + } +} + +func (r *RelayConnection) setState(state RelayConnectionState) { + r.stateMutex.Lock() + defer r.stateMutex.Unlock() + r.state = state +} + +func (r *RelayConnection) manageSubs( + ctx context.Context, + conn *websocket.Conn, +) error { + defer conn.Close() + + activeSubscriptions := internal.NewEmptySet[transport2.SubscriptionID]() + + for { + if err := r.updateSubs(conn, activeSubscriptions); err != nil { + return errors.Wrap(err, "error updating subscriptions") + } + + select { + case <-r.subscriptionsUpdatedCh: + continue + case <-ctx.Done(): + return ctx.Err() + } + } +} + +func (r *RelayConnection) updateSubs( + conn *websocket.Conn, + activeSubscriptions *internal.Set[transport2.SubscriptionID], +) error { + r.subscriptionsMutex.Lock() + defer r.subscriptionsMutex.Unlock() + + r.resetSubscriptionUpdateCh() + + for _, subscriptionID := range activeSubscriptions.List() { + if _, ok := r.subscriptions[subscriptionID]; !ok { + msg := transport2.NewMessageClose(subscriptionID) + msgJSON, err := msg.MarshalJSON() + if err != nil { + return errors.Wrap(err, "marshaling close message failed") + } + + r.logger.Trace(). + WithField("subscriptionID", subscriptionID). + WithField("payload", string(msgJSON)). + Message("closing subscription") + + if err := conn.WriteMessage(websocket.TextMessage, msgJSON); err != nil { + return errors.Wrap(err, "writing close message error") + } + + activeSubscriptions.Delete(subscriptionID) + } + } + + for subscriptionID, subscription := range r.subscriptions { + if ok := activeSubscriptions.Contains(subscriptionID); !ok { + msg := transport2.NewMessageReq(subscription.id, []domain.Filter{subscription.filter}) + msgJSON, err := msg.MarshalJSON() + if err != nil { + return errors.Wrap(err, "marshaling req message failed") + } + + r.logger.Trace(). + WithField("subscriptionID", subscriptionID). + WithField("payload", string(msgJSON)). + Message("opening subscription") + + if err := conn.WriteMessage(websocket.TextMessage, msgJSON); err != nil { + return errors.Wrap(err, "writing req message error") + } + + activeSubscriptions.Put(subscriptionID) + } + } + + return nil +} + +type subscription struct { + ctx context.Context + ch chan EventOrEndOfSavedEvents + + id transport2.SubscriptionID + filter domain.Filter +} + +type DialError struct { + underlying error +} + +func NewDialError(underlying error) DialError { + return DialError{underlying: underlying} +} + +func (t DialError) Error() string { + return fmt.Sprintf("error dialing the relay: %s", t.underlying) +} + +func (t DialError) Unwrap() error { + return t.underlying +} + +func (t DialError) Is(target error) bool { + _, ok1 := target.(DialError) + _, ok2 := target.(*DialError) + return ok1 || ok2 +} + +type ReadMessageError struct { + underlying error +} + +func NewReadMessageError(underlying error) ReadMessageError { + return ReadMessageError{underlying: underlying} +} + +func (t ReadMessageError) Error() string { + return fmt.Sprintf("error reading a message from websocket: %s", t.underlying) +} + +func (t ReadMessageError) Unwrap() error { + return t.underlying +} + +func (t ReadMessageError) Is(target error) bool { + _, ok1 := target.(ReadMessageError) + _, ok2 := target.(*ReadMessageError) + return ok1 || ok2 +} diff --git a/service/domain/relays/relay_connection_state.go b/service/domain/relays/relay_connection_state.go new file mode 100644 index 0000000..e2de85f --- /dev/null +++ b/service/domain/relays/relay_connection_state.go @@ -0,0 +1,15 @@ +package relays + +var ( + RelayConnectionStateInitializing = RelayConnectionState{"initializing"} + RelayConnectionStateConnected = RelayConnectionState{"connected"} + RelayConnectionStateDisconnected = RelayConnectionState{"disconnected"} +) + +type RelayConnectionState struct { + s string +} + +func (r RelayConnectionState) String() string { + return r.s +} diff --git a/service/domain/relays/relay_connection_test.go b/service/domain/relays/relay_connection_test.go new file mode 100644 index 0000000..34b2a9b --- /dev/null +++ b/service/domain/relays/relay_connection_test.go @@ -0,0 +1,26 @@ +package relays_test + +import ( + "testing" + + "github.com/boreq/errors" + "github.com/planetary-social/nos-event-service/internal/fixtures" + "github.com/planetary-social/nos-event-service/service/domain/relays" + "github.com/stretchr/testify/require" +) + +func TestDialErrorIs(t *testing.T) { + err := relays.NewDialError(fixtures.SomeError()) + require.ErrorIs(t, err, relays.DialError{}) + require.ErrorIs(t, err, &relays.DialError{}) + require.ErrorIs(t, errors.Wrap(err, "wrapped"), relays.DialError{}) + require.ErrorIs(t, errors.Wrap(err, "wrapped"), &relays.DialError{}) +} + +func TestReadMessageErrorIs(t *testing.T) { + err := relays.NewReadMessageError(fixtures.SomeError()) + require.ErrorIs(t, err, relays.ReadMessageError{}) + require.ErrorIs(t, err, &relays.ReadMessageError{}) + require.ErrorIs(t, errors.Wrap(err, "wrapped"), relays.ReadMessageError{}) + require.ErrorIs(t, errors.Wrap(err, "wrapped"), &relays.ReadMessageError{}) +} diff --git a/service/domain/relays/relay_connections.go b/service/domain/relays/relay_connections.go new file mode 100644 index 0000000..296b2d1 --- /dev/null +++ b/service/domain/relays/relay_connections.go @@ -0,0 +1,83 @@ +package relays + +import ( + "context" + "sync" + "time" + + "github.com/planetary-social/nos-event-service/internal/logging" + "github.com/planetary-social/nos-event-service/service/domain" +) + +type Metrics interface { + ReportRelayConnectionsState(m map[domain.RelayAddress]RelayConnectionState) +} + +const ( + storeMetricsEvery = 30 * time.Second +) + +type RelayConnections struct { + logger logging.Logger + metrics Metrics + + longCtx context.Context + + connections map[domain.RelayAddress]*RelayConnection + connectionsLock sync.Mutex +} + +func NewRelayConnections(ctx context.Context, logger logging.Logger, metrics Metrics) *RelayConnections { + v := &RelayConnections{ + logger: logger.New("relayConnections"), + metrics: metrics, + longCtx: ctx, + connections: make(map[domain.RelayAddress]*RelayConnection), + connectionsLock: sync.Mutex{}, + } + go v.storeMetricsLoop(ctx) + return v +} + +func (d *RelayConnections) GetEvents(ctx context.Context, relayAddress domain.RelayAddress, filter domain.Filter) (<-chan EventOrEndOfSavedEvents, error) { + connection := d.getConnection(relayAddress) + return connection.GetEvents(ctx, filter) +} + +func (d *RelayConnections) storeMetricsLoop(ctx context.Context) { + for { + d.storeMetrics() + + select { + case <-time.After(storeMetricsEvery): + case <-ctx.Done(): + return + } + } +} + +func (d *RelayConnections) storeMetrics() { + d.connectionsLock.Lock() + defer d.connectionsLock.Unlock() + + m := make(map[domain.RelayAddress]RelayConnectionState) + for _, connection := range d.connections { + m[connection.Address()] = connection.State() + } + d.metrics.ReportRelayConnectionsState(m) +} + +func (r *RelayConnections) getConnection(relayAddress domain.RelayAddress) *RelayConnection { + r.connectionsLock.Lock() + defer r.connectionsLock.Unlock() + + if connection, ok := r.connections[relayAddress]; ok { + return connection + } + + connection := NewRelayConnection(relayAddress, r.logger) + go connection.Run(r.longCtx) + + r.connections[relayAddress] = connection + return connection +} diff --git a/service/domain/relays/transport/messages.go b/service/domain/relays/transport/messages.go new file mode 100644 index 0000000..f07d1cc --- /dev/null +++ b/service/domain/relays/transport/messages.go @@ -0,0 +1,39 @@ +package transport + +import ( + "github.com/nbd-wtf/go-nostr" + "github.com/planetary-social/nos-event-service/service/domain" +) + +type MessageReq struct { + subscriptionID SubscriptionID + filters []domain.Filter +} + +func NewMessageReq(subscriptionID SubscriptionID, filters []domain.Filter) MessageReq { + return MessageReq{subscriptionID: subscriptionID, filters: filters} +} + +func (m MessageReq) MarshalJSON() ([]byte, error) { + env := nostr.ReqEnvelope{ + SubscriptionID: m.subscriptionID.String(), + Filters: nostr.Filters{}, + } + for _, filter := range m.filters { + env.Filters = append(env.Filters, filter.Libfilter()) + } + return env.MarshalJSON() +} + +type MessageClose struct { + subscriptionID SubscriptionID +} + +func NewMessageClose(subscriptionID SubscriptionID) MessageClose { + return MessageClose{subscriptionID: subscriptionID} +} + +func (m MessageClose) MarshalJSON() ([]byte, error) { + env := nostr.CloseEnvelope(m.subscriptionID.String()) + return env.MarshalJSON() +} diff --git a/service/domain/relays/transport/subscription_id.go b/service/domain/relays/transport/subscription_id.go new file mode 100644 index 0000000..d52f75a --- /dev/null +++ b/service/domain/relays/transport/subscription_id.go @@ -0,0 +1,20 @@ +package transport + +import ( + "github.com/boreq/errors" +) + +type SubscriptionID struct { + s string +} + +func NewSubscriptionID(s string) (SubscriptionID, error) { + if s == "" { + return SubscriptionID{}, errors.New("subscription id can't be an empty string") + } + return SubscriptionID{s: s}, nil +} + +func (s SubscriptionID) String() string { + return s.s +} diff --git a/service/domain/relays_extractor.go b/service/domain/relays_extractor.go new file mode 100644 index 0000000..abb0b95 --- /dev/null +++ b/service/domain/relays_extractor.go @@ -0,0 +1,108 @@ +package domain + +import ( + "encoding/json" + + "github.com/boreq/errors" + "github.com/hashicorp/go-multierror" + "github.com/planetary-social/nos-event-service/internal" + "github.com/planetary-social/nos-event-service/internal/logging" +) + +type MaybeRelayAddress struct { + s string +} + +func NewMaybeRelayAddress(s string) MaybeRelayAddress { + return MaybeRelayAddress{s: s} +} + +func (a MaybeRelayAddress) String() string { + return a.s +} + +// RelaysExtractor does its best to get relay addresses out of events. It should +// only error out on obvious programming errors but not on malformed user input. +type RelaysExtractor struct { + logger logging.Logger +} + +func NewRelaysExtractor(logger logging.Logger) *RelaysExtractor { + return &RelaysExtractor{logger: logger.New("relayExtractor")} +} + +func (e *RelaysExtractor) Extract(event Event) ([]MaybeRelayAddress, error) { + switch event.Kind() { + case EventKindMetadata: + return e.extractFromMetadata(event) + case EventKindContacts: + return e.extractFromContacts(event) + default: + return nil, nil + } +} + +func (e *RelaysExtractor) extractFromMetadata(event Event) ([]MaybeRelayAddress, error) { + if event.Kind() != EventKindMetadata { + return nil, errors.New("invalid event kind") + } + + results := internal.NewEmptySet[MaybeRelayAddress]() + for _, tag := range event.Tags() { + if tag.IsRelay() { + maybeRelayAddress, err := tag.Relay() + if err != nil { + return nil, errors.Wrap(err, "error creating a maybe relay address") + } + results.Put(maybeRelayAddress) + } + } + return results.List(), nil +} + +func (e *RelaysExtractor) extractFromContacts(event Event) ([]MaybeRelayAddress, error) { + if event.Kind() != EventKindContacts { + return nil, errors.New("incorrect event kind") + } + + if event.Content() == "" { + return nil, nil + } + + results := internal.NewEmptySet[MaybeRelayAddress]() + + var compoundErr error + + var asMap map[string]any + if err := json.Unmarshal([]byte(event.Content()), &asMap); err == nil { + for addressString := range asMap { + results.Put(NewMaybeRelayAddress(addressString)) + } + return results.List(), nil + } else { + compoundErr = multierror.Append(compoundErr, err) + } + + var asSlice [][]any + if err := json.Unmarshal([]byte(event.Content()), &asSlice); err == nil { + for _, elements := range asSlice { + if len(elements) > 0 { + s, ok := elements[0].(string) + if ok { + results.Put(NewMaybeRelayAddress(s)) + } + } + } + return results.List(), nil + } else { + compoundErr = multierror.Append(compoundErr, err) + } + + e.logger. + Debug(). + WithError(compoundErr). + WithField("content", event.Content()). + Message("can't unmarshal") + + return nil, nil +} diff --git a/service/domain/relays_extractor_test.go b/service/domain/relays_extractor_test.go new file mode 100644 index 0000000..e7b9a46 --- /dev/null +++ b/service/domain/relays_extractor_test.go @@ -0,0 +1,71 @@ +package domain_test + +import ( + "sort" + "testing" + + "github.com/planetary-social/nos-event-service/internal/fixtures" + "github.com/planetary-social/nos-event-service/service/domain" + "github.com/stretchr/testify/require" +) + +func TestRelaysExtractor(t *testing.T) { + testCases := []struct { + Name string + + Kind domain.EventKind + Tags domain.EventTag + Content string + + Result []domain.MaybeRelayAddress + }{ + { + Name: "contacts_with_map", + Kind: domain.EventKindContacts, + //Tags: domain.NewEventTag([]string{ + // "p, " + //}), + Content: `{"wss://relay.damus.io":{"read":true,"write":true},"wss://nostr.bitcoiner.social":{"read":true,"write":true}}`, + + Result: []domain.MaybeRelayAddress{ + domain.NewMaybeRelayAddress("wss://relay.damus.io"), + domain.NewMaybeRelayAddress("wss://nostr.bitcoiner.social"), + }, + }, + { + Name: "contacts_with_slice", + Kind: domain.EventKindContacts, + //Tags: domain.NewEventTag([]string{ + // "p, " + //}), + Content: `[["wss://nostr.wine",{"write":true,"read":true}],["wss://relay.current.fyi",{"read":true,"write":true}]]`, + + Result: []domain.MaybeRelayAddress{ + domain.NewMaybeRelayAddress("wss://nostr.wine"), + domain.NewMaybeRelayAddress("wss://relay.current.fyi"), + }, + }, + } + + for _, testCase := range testCases { + t.Run(testCase.Name, func(t *testing.T) { + event := fixtures.Event(testCase.Kind, nil, testCase.Content) + + logger := fixtures.TestLogger(t) + extractor := domain.NewRelaysExtractor(logger) + + result, err := extractor.Extract(event) + require.NoError(t, err) + + sort.Slice(result, func(i, j int) bool { + return result[i].String() < result[j].String() + }) + + sort.Slice(testCase.Result, func(i, j int) bool { + return testCase.Result[i].String() < testCase.Result[j].String() + }) + + require.Equal(t, testCase.Result, result) + }) + } +} diff --git a/service/domain/tags.go b/service/domain/tags.go new file mode 100644 index 0000000..9d39836 --- /dev/null +++ b/service/domain/tags.go @@ -0,0 +1,94 @@ +package domain + +import ( + "unicode" + + "github.com/boreq/errors" +) + +var ( + tagProfile = MustNewEventTagName("p") + tagRelay = MustNewEventTagName("r") +) + +type EventTag struct { + name EventTagName + tag []string +} + +func NewEventTag(tag []string) (EventTag, error) { + if len(tag) < 2 { + return EventTag{}, errors.New("tag needs at least two fields I recon") + } + + name, err := NewEventTagName(tag[0]) + if err != nil { + return EventTag{}, errors.Wrap(err, "invalid tag name") + } + + return EventTag{name: name, tag: tag}, nil +} + +func (e EventTag) Name() EventTagName { + return e.name +} + +func (e EventTag) FirstValue() string { + return e.tag[1] +} + +func (e EventTag) FirstValueIsAnEmptyString() bool { + return e.FirstValue() == "" +} + +func (e EventTag) IsProfile() bool { + return e.name == tagProfile +} + +func (e EventTag) IsRelay() bool { + return e.name == tagRelay +} + +func (e EventTag) Profile() (PublicKey, error) { + if !e.IsProfile() { + return PublicKey{}, errors.New("not a profile tag") + } + return NewPublicKeyFromHex(e.tag[1]) +} + +func (e EventTag) Relay() (MaybeRelayAddress, error) { + if !e.IsRelay() { + return MaybeRelayAddress{}, errors.New("not a relay address tag") + } + return NewMaybeRelayAddress(e.tag[1]), nil +} + +type EventTagName struct { + s string +} + +func NewEventTagName(s string) (EventTagName, error) { + if s == "" { + return EventTagName{}, errors.New("missing tag name") + } + + for _, r := range s { + if !unicode.IsLetter(r) && !unicode.IsNumber(r) && r != '_' && r != '-' { + return EventTagName{}, errors.New("tag name should only contain letters and numbers") + } + } + + return EventTagName{s}, nil +} + +func MustNewEventTagName(s string) EventTagName { + v, err := NewEventTagName(s) + if err != nil { + panic(err) + } + return v +} + +func (e EventTagName) String() string { + return e.s +} diff --git a/service/ports/http/http.go b/service/ports/http/http.go new file mode 100644 index 0000000..30a2bb9 --- /dev/null +++ b/service/ports/http/http.go @@ -0,0 +1,59 @@ +package http + +import ( + "context" + "net" + "net/http" + + "github.com/boreq/errors" + "github.com/planetary-social/nos-event-service/internal/logging" + prometheusadapters "github.com/planetary-social/nos-event-service/service/adapters/prometheus" + "github.com/planetary-social/nos-event-service/service/app" + "github.com/planetary-social/nos-event-service/service/config" + "github.com/prometheus/client_golang/prometheus/promhttp" +) + +type Server struct { + config config.Config + logger logging.Logger + app app.Application + prometheus *prometheusadapters.Prometheus +} + +func NewServer( + config config.Config, + logger logging.Logger, + app app.Application, + prometheus *prometheusadapters.Prometheus, +) Server { + return Server{ + config: config, + logger: logger.New("server"), + app: app, + prometheus: prometheus, + } +} + +func (s *Server) ListenAndServe(ctx context.Context) error { + var listenConfig net.ListenConfig + listener, err := listenConfig.Listen(ctx, "tcp", s.config.ListenAddress()) + if err != nil { + return errors.Wrap(err, "error listening") + } + + go func() { + <-ctx.Done() + if err := listener.Close(); err != nil { + s.logger.Error().WithError(err).Message("error closing listener") + } + }() + + mux := s.createMux() + return http.Serve(listener, mux) +} + +func (s *Server) createMux() *http.ServeMux { + mux := http.NewServeMux() + mux.Handle("/metrics", promhttp.HandlerFor(s.prometheus.Registry(), promhttp.HandlerOpts{})) + return mux +} diff --git a/service/ports/memorypubsub/received_events.go b/service/ports/memorypubsub/received_events.go new file mode 100644 index 0000000..f19c279 --- /dev/null +++ b/service/ports/memorypubsub/received_events.go @@ -0,0 +1,46 @@ +// Package pubsub receives internal events. +package memorypubsub + +import ( + "context" + + "github.com/planetary-social/nos-event-service/internal/logging" + "github.com/planetary-social/nos-event-service/service/adapters/memorypubsub" + "github.com/planetary-social/nos-event-service/service/app" +) + +type SaveReceivedEventHandler interface { + Handle(ctx context.Context, cmd app.SaveReceivedEvent) error +} + +type ReceivedEventSubscriber struct { + pubsub *memorypubsub.ReceivedEventPubSub + handler SaveReceivedEventHandler + logger logging.Logger +} + +func NewReceivedEventSubscriber( + pubsub *memorypubsub.ReceivedEventPubSub, + handler SaveReceivedEventHandler, + logger logging.Logger, +) *ReceivedEventSubscriber { + return &ReceivedEventSubscriber{ + pubsub: pubsub, + handler: handler, + logger: logger.New("receivedEventSubscriber"), + } +} + +func (p *ReceivedEventSubscriber) Run(ctx context.Context) error { + for v := range p.pubsub.Subscribe(ctx) { + cmd := app.NewSaveReceivedEvent(v.Relay(), v.Event()) + if err := p.handler.Handle(ctx, cmd); err != nil { + p.logger.Error(). + WithError(err). + WithField("relay", v.Relay()). + WithField("event", v.Event()). + Message("error handling a received event") + } + } + return nil +} diff --git a/service/ports/sqlitepubsub/event_saved.go b/service/ports/sqlitepubsub/event_saved.go new file mode 100644 index 0000000..0b43e17 --- /dev/null +++ b/service/ports/sqlitepubsub/event_saved.go @@ -0,0 +1,73 @@ +package sqlitepubsub + +import ( + "context" + "encoding/json" + + "github.com/boreq/errors" + "github.com/planetary-social/nos-event-service/internal/logging" + "github.com/planetary-social/nos-event-service/service/adapters/sqlite" + "github.com/planetary-social/nos-event-service/service/app" + "github.com/planetary-social/nos-event-service/service/domain" +) + +type ProcessSavedEventHandler interface { + Handle(ctx context.Context, cmd app.ProcessSavedEvent) (err error) +} + +type EventSavedEventSubscriber struct { + handler ProcessSavedEventHandler + subscriber *sqlite.Subscriber + logger logging.Logger + metrics app.Metrics +} + +func NewEventSavedEventSubscriber( + handler ProcessSavedEventHandler, + subscriber *sqlite.Subscriber, + logger logging.Logger, + metrics app.Metrics, +) *EventSavedEventSubscriber { + return &EventSavedEventSubscriber{ + handler: handler, + subscriber: subscriber, + logger: logger.New("eventSavedEventSubscriber"), + metrics: metrics, + } +} +func (s *EventSavedEventSubscriber) Run(ctx context.Context) error { + for msg := range s.subscriber.SubscribeToEventSaved(ctx) { + if err := s.handleMessage(ctx, msg); err != nil { + s.logger.Error().WithError(err).Message("error handling a message") + if err := msg.Nack(); err != nil { + return errors.Wrap(err, "error nacking a message") + } + } else { + if err := msg.Ack(); err != nil { + return errors.Wrap(err, "error acking a message") + } + } + } + + return errors.New("channel closed") +} + +func (s *EventSavedEventSubscriber) handleMessage(ctx context.Context, msg *sqlite.ReceivedMessage) error { + var transport sqlite.EventSavedEventTransport + if err := json.Unmarshal(msg.Payload(), &transport); err != nil { + return errors.Wrap(err, "error unmarshaling") + } + + eventID, err := domain.NewEventId(transport.EventID) + if err != nil { + return errors.Wrap(err, "error creating an account id") + } + + cmd := app.NewProcessSavedEvent(eventID) + + if err := s.handler.Handle(ctx, cmd); err != nil { + return errors.Wrap(err, "error calling the handler") + } + + return nil +} diff --git a/tools.go b/tools.go new file mode 100644 index 0000000..43d49d6 --- /dev/null +++ b/tools.go @@ -0,0 +1,10 @@ +//go:build tools +// +build tools + +// following https://github.com/golang/go/wiki/Modules#how-can-i-track-tool-dependencies-for-a-module + +package main + +import ( + _ "github.com/google/wire/cmd/wire" +)