From 2c09d0679373267fdca36e7ff6cdefca1e1795fd Mon Sep 17 00:00:00 2001 From: sh <37271604+shumvgolove@users.noreply.github.com> Date: Tue, 3 Nov 2026 17:24:17 +0400 Subject: [PATCH] store: rename badge service to store service (#7987) Co-authored-by: sh-agents <350651734+sh-agents@users.noreply.github.com> --- .github/workflows/build.yml | 4 +- .gitignore | 2 + .../Main.hs | 10 +- .../README.md | 70 +- .../src/StoreService}/Catalog.hs | 4 +- .../src/StoreService}/Codes.hs | 6 +- .../src/StoreService}/Config.hs | 4 +- .../src/StoreService}/Group.hs | 14 +- .../src/StoreService}/Group/Command.hs | 2 +- .../src/StoreService}/Log.hs | 2 +- .../src/StoreService}/Names/Chain.hs | 4 +- .../src/StoreService}/Names/Registration.hs | 2 +- .../src/StoreService}/Options.hs | 36 +- .../src/StoreService}/Orders.hs | 8 +- .../src/StoreService}/Poller.hs | 14 +- .../src/StoreService}/Providers.hs | 2 +- .../src/StoreService}/Providers/BTCPay.hs | 8 +- .../src/StoreService}/Providers/Stripe.hs | 6 +- .../src/StoreService}/Service.hs | 338 +++---- .../src/StoreService}/Store.hs | 8 +- .../src/StoreService}/Store/Invoices.hs | 8 +- .../src/StoreService}/Store/Migrate.hs | 20 +- .../Store/Postgres/Migrations.hs | 6 +- .../StoreService}/Store/SQLite/Migrations.hs | 6 +- .../src/StoreService}/StoreReceipts.hs | 6 +- .../src/StoreService}/StoreReceipts/Apple.hs | 8 +- .../src/StoreService}/StoreReceipts/Google.hs | 8 +- .../src/StoreService}/StoreReceipts/Mock.hs | 8 +- .../src/StoreService}/Waiters.hs | 2 +- .../src/StoreService}/Web/Server.hs | 20 +- .../store_service.ini.example} | 10 +- .../test-fixtures/apple/AppleRootCA-G3.cer | Bin .../apple/transaction-legend.json | 0 .../apple/transaction-sandbox.json | 0 .../apple/transaction-supporter.json | 0 .../test-fixtures/btcpay/invoice-expired.json | 0 .../test-fixtures/btcpay/invoice-invalid.json | 0 .../btcpay/invoice-list-alien-method.json | 0 .../btcpay/invoice-list-alien-status.json | 0 .../btcpay/invoice-list-no-id.json | 0 .../invoice-list-no-payment-methods.json | 0 .../test-fixtures/btcpay/invoice-list.json | 0 .../test-fixtures/btcpay/invoice-new.json | 0 .../btcpay/invoice-processing.json | 0 .../test-fixtures/btcpay/invoice-settled.json | 0 .../btcpay/payment-methods-btc.json | 0 .../btcpay/payment-methods-no-amount.json | 0 .../payment-methods-no-destination.json | 0 .../btcpay/payment-methods-xmr.json | 0 .../btcpay/store-payment-methods.json | 0 .../test-fixtures/stripe/intent-canceled.json | 0 .../stripe/intent-list-cursor-gap.json | 0 .../test-fixtures/stripe/intent-list.json | 0 .../test-fixtures/stripe/intent-open.json | 0 .../stripe/intent-succeeded.json | 0 .../web/.gitignore | 0 .../web/README.md | 26 +- .../web/build.js | 0 .../web/check-tests.js | 0 .../web/mock/server.py | 2 +- .../web/package-lock.json | 0 .../web/package.json | 0 .../public/fonts/GT-Walsheim-LC-Bold.woff2 | Bin .../web/public/fonts/Manrope-Bold.woff2 | Bin .../web/public/fonts/Manrope-Medium.woff2 | Bin .../web/public/fonts/Manrope-Regular.woff2 | Bin .../web/public/fonts/Manrope-SemiBold.woff2 | Bin .../web/public/img/hero-dark.png | Bin .../web/public/img/hero-light.png | Bin .../web/public/img/symbol-dark.svg | 0 .../web/public/img/symbol-light.svg | 0 .../web/public/img/wordmark-dark.svg | 0 .../web/public/img/wordmark-light.svg | 0 .../web/public/index.html | 0 .../web/public/styles.css | 0 .../web/public/sw.js | 0 .../web/src/api.ts | 0 .../web/src/catalog.ts | 0 .../web/src/codes.ts | 0 .../web/src/crowdfunding.ts | 0 .../web/src/domain.ts | 0 .../web/src/embed.ts | 0 .../web/src/flow.ts | 0 .../web/src/format.ts | 0 .../web/src/icons.ts | 0 .../web/src/main.ts | 0 .../web/src/order.ts | 0 .../web/src/parse.ts | 0 .../web/src/qr.ts | 0 .../web/src/routing.ts | 0 .../web/src/screens.ts | 0 .../web/src/store.ts | 0 .../web/src/stripe.ts | 0 .../web/test/boot.ts | 0 .../web/test/build.test.ts | 0 .../web/test/catalog.test.ts | 0 .../web/test/codes.test.ts | 0 .../web/test/css.ts | 0 .../web/test/design.test.ts | 0 .../web/test/embed.test.ts | 0 .../web/test/flow-controller.test.ts | 0 .../web/test/flow.test.ts | 0 .../web/test/main-app-desktop.test.ts | 0 .../web/test/main-app-mobile.test.ts | 0 .../web/test/main-app-reload.test.ts | 0 .../web/test/main-app-return.test.ts | 0 .../web/test/main-app-unsaved.test.ts | 0 .../web/test/main-boot.test.ts | 0 .../web/test/main-cancel-navigated.test.ts | 0 .../web/test/main-cancel-race.test.ts | 0 .../web/test/main-cancel-refusal.test.ts | 0 .../main-cancel-refused-navigated.test.ts | 0 .../web/test/main-cancel-reopened.test.ts | 0 .../web/test/main-cancel.test.ts | 0 .../web/test/main-card-cancel.test.ts | 0 .../web/test/main-card-full-store.test.ts | 0 .../web/test/main-card-return.test.ts | 0 .../web/test/main-forget-race.test.ts | 0 .../web/test/main-forget-refused.test.ts | 0 .../web/test/main-nav-race.test.ts | 0 .../web/test/main-no-storage.test.ts | 0 .../web/test/main-offline.test.ts | 0 .../web/test/main-one-month.test.ts | 0 .../web/test/main-pay-forget.test.ts | 0 .../web/test/main-pay-navigated.test.ts | 0 .../web/test/main-pay-rechoice.test.ts | 0 .../web/test/main-pay-repaint.test.ts | 0 .../web/test/main-quota-full.test.ts | 0 .../web/test/main-resume-step.test.ts | 0 .../web/test/main-resume.test.ts | 0 .../web/test/main-silent-storage.test.ts | 0 .../web/test/main.test.ts | 0 .../web/test/open-order.ts | 0 .../web/test/qr.test.ts | 0 .../web/test/routing.test.ts | 0 .../web/test/screens.test.ts | 0 .../web/test/smoke.test.ts | 0 .../web/test/store.test.ts | 0 .../web/test/stripe.test.ts | 0 .../web/test/stub-dom.ts | 0 .../web/test/sw.test.ts | 0 .../web/tsconfig.json | 0 .../web/tsconfig.test.json | 0 bots/api/TYPES.md | 58 +- bots/src/API/Docs/Types.hs | 6 +- docs/protocol/badges-rpc.md | 2 +- docs/protocol/badges-rpc.schema.json | 2 +- .../types/typescript/src/types.ts | 48 +- .../src/simplex_chat/types/_types.py | 6 +- scripts/ci/README.md | 4 +- scripts/ci/packages_release.py | 4 +- scripts/ci/scope-tests.sh | 2 +- scripts/ci/test_packages_release.py | 2 +- .../.gitignore | 0 .../Dockerfile | 18 +- .../Dockerfile.dockerignore | 10 +- .../compose.yml | 10 +- .../store_service.ini.example} | 6 +- simplex-chat.cabal | 146 +-- src/Simplex/Chat.hs | 2 +- src/Simplex/Chat/Badges.hs | 2 +- src/Simplex/Chat/Badges/Code.hs | 2 +- src/Simplex/Chat/Badges/Ledger.hs | 2 +- src/Simplex/Chat/Badges/Types.hs | 142 +-- src/Simplex/Chat/Controller.hs | 12 +- src/Simplex/Chat/Library/Commands.hs | 102 +- src/Simplex/Chat/Store/Badges.hs | 10 +- .../Migrations/M20260915_user_badges.hs | 2 +- .../Migrations/M20260915_user_badges.hs | 2 +- .../{Badges/Service.hs => StoreService.hs} | 92 +- src/Simplex/Chat/View.hs | 8 +- tests/BadgeTests.hs | 88 +- .../BTCPayTests.hs | 10 +- .../BotTests.hs | 904 +++++++++--------- .../CatalogTests.hs | 8 +- .../ConfigTests.hs | 12 +- .../FakeAppStore.hs | 6 +- .../FakeBTCPay.hs | 6 +- .../FakeEthNode.hs | 2 +- .../FakePlay.hs | 4 +- .../FakeStore.hs | 6 +- .../FakeStripe.hs | 6 +- .../GroupIntegrationTests.hs | 44 +- .../GroupTests.hs | 8 +- .../NameRegistrationTests.hs | 12 +- .../StoreVerifierTests.hs | 26 +- .../StripeTests.hs | 10 +- .../WaitersTests.hs | 6 +- .../WebTests.hs | 84 +- .../WebUIMock.hs | 4 +- tests/Test.hs | 28 +- 191 files changed, 1341 insertions(+), 1309 deletions(-) rename apps/{simplex-badge-service => simplex-store-service}/Main.hs (76%) rename apps/{simplex-badge-service => simplex-store-service}/README.md (91%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/Catalog.hs (98%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/Codes.hs (90%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/Config.hs (99%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/Group.hs (98%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/Group/Command.hs (99%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/Log.hs (98%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/Names/Chain.hs (97%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/Names/Registration.hs (99%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/Options.hs (80%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/Orders.hs (95%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/Poller.hs (97%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/Providers.hs (98%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/Providers/BTCPay.hs (99%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/Providers/Stripe.hs (99%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/Service.hs (86%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/Store.hs (98%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/Store/Invoices.hs (99%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/Store/Migrate.hs (67%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/Store/Postgres/Migrations.hs (98%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/Store/SQLite/Migrations.hs (98%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/StoreReceipts.hs (99%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/StoreReceipts/Apple.hs (98%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/StoreReceipts/Google.hs (98%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/StoreReceipts/Mock.hs (95%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/Waiters.hs (98%) rename apps/{simplex-badge-service/src/BadgeService => simplex-store-service/src/StoreService}/Web/Server.hs (98%) rename apps/{simplex-badge-service/badge_service.ini.example => simplex-store-service/store_service.ini.example} (96%) rename apps/{simplex-badge-service => simplex-store-service}/test-fixtures/apple/AppleRootCA-G3.cer (100%) rename apps/{simplex-badge-service => simplex-store-service}/test-fixtures/apple/transaction-legend.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/test-fixtures/apple/transaction-sandbox.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/test-fixtures/apple/transaction-supporter.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/test-fixtures/btcpay/invoice-expired.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/test-fixtures/btcpay/invoice-invalid.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/test-fixtures/btcpay/invoice-list-alien-method.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/test-fixtures/btcpay/invoice-list-alien-status.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/test-fixtures/btcpay/invoice-list-no-id.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/test-fixtures/btcpay/invoice-list-no-payment-methods.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/test-fixtures/btcpay/invoice-list.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/test-fixtures/btcpay/invoice-new.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/test-fixtures/btcpay/invoice-processing.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/test-fixtures/btcpay/invoice-settled.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/test-fixtures/btcpay/payment-methods-btc.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/test-fixtures/btcpay/payment-methods-no-amount.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/test-fixtures/btcpay/payment-methods-no-destination.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/test-fixtures/btcpay/payment-methods-xmr.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/test-fixtures/btcpay/store-payment-methods.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/test-fixtures/stripe/intent-canceled.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/test-fixtures/stripe/intent-list-cursor-gap.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/test-fixtures/stripe/intent-list.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/test-fixtures/stripe/intent-open.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/test-fixtures/stripe/intent-succeeded.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/.gitignore (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/README.md (95%) rename apps/{simplex-badge-service => simplex-store-service}/web/build.js (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/check-tests.js (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/mock/server.py (99%) rename apps/{simplex-badge-service => simplex-store-service}/web/package-lock.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/package.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/public/fonts/GT-Walsheim-LC-Bold.woff2 (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/public/fonts/Manrope-Bold.woff2 (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/public/fonts/Manrope-Medium.woff2 (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/public/fonts/Manrope-Regular.woff2 (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/public/fonts/Manrope-SemiBold.woff2 (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/public/img/hero-dark.png (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/public/img/hero-light.png (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/public/img/symbol-dark.svg (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/public/img/symbol-light.svg (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/public/img/wordmark-dark.svg (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/public/img/wordmark-light.svg (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/public/index.html (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/public/styles.css (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/public/sw.js (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/src/api.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/src/catalog.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/src/codes.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/src/crowdfunding.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/src/domain.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/src/embed.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/src/flow.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/src/format.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/src/icons.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/src/main.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/src/order.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/src/parse.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/src/qr.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/src/routing.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/src/screens.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/src/store.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/src/stripe.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/boot.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/build.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/catalog.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/codes.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/css.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/design.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/embed.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/flow-controller.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/flow.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-app-desktop.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-app-mobile.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-app-reload.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-app-return.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-app-unsaved.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-boot.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-cancel-navigated.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-cancel-race.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-cancel-refusal.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-cancel-refused-navigated.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-cancel-reopened.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-cancel.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-card-cancel.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-card-full-store.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-card-return.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-forget-race.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-forget-refused.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-nav-race.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-no-storage.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-offline.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-one-month.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-pay-forget.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-pay-navigated.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-pay-rechoice.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-pay-repaint.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-quota-full.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-resume-step.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-resume.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main-silent-storage.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/main.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/open-order.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/qr.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/routing.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/screens.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/smoke.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/store.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/stripe.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/stub-dom.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/test/sw.test.ts (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/tsconfig.json (100%) rename apps/{simplex-badge-service => simplex-store-service}/web/tsconfig.test.json (100%) rename scripts/{badge-service => store-service}/.gitignore (100%) rename scripts/{badge-service => store-service}/Dockerfile (86%) rename scripts/{badge-service => store-service}/Dockerfile.dockerignore (76%) rename scripts/{badge-service => store-service}/compose.yml (74%) rename scripts/{badge-service/badge_service.ini.example => store-service/store_service.ini.example} (96%) rename src/Simplex/Chat/{Badges/Service.hs => StoreService.hs} (80%) rename tests/Bots/{BadgeService => StoreService}/BTCPayTests.hs (99%) rename tests/Bots/{BadgeService => StoreService}/BotTests.hs (92%) rename tests/Bots/{BadgeService => StoreService}/CatalogTests.hs (98%) rename tests/Bots/{BadgeService => StoreService}/ConfigTests.hs (99%) rename tests/Bots/{BadgeService => StoreService}/FakeAppStore.hs (97%) rename tests/Bots/{BadgeService => StoreService}/FakeBTCPay.hs (99%) rename tests/Bots/{BadgeService => StoreService}/FakeEthNode.hs (98%) rename tests/Bots/{BadgeService => StoreService}/FakePlay.hs (99%) rename tests/Bots/{BadgeService => StoreService}/FakeStore.hs (98%) rename tests/Bots/{BadgeService => StoreService}/FakeStripe.hs (99%) rename tests/Bots/{BadgeService => StoreService}/GroupIntegrationTests.hs (98%) rename tests/Bots/{BadgeService => StoreService}/GroupTests.hs (98%) rename tests/Bots/{BadgeService => StoreService}/NameRegistrationTests.hs (97%) rename tests/Bots/{BadgeService => StoreService}/StoreVerifierTests.hs (98%) rename tests/Bots/{BadgeService => StoreService}/StripeTests.hs (98%) rename tests/Bots/{BadgeService => StoreService}/WaitersTests.hs (97%) rename tests/Bots/{BadgeService => StoreService}/WebTests.hs (98%) rename tests/Bots/{BadgeService => StoreService}/WebUIMock.hs (95%) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ed49944d3d..cd770a7243 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -15,7 +15,7 @@ on: - "apps/simplex-chat/**" - "apps/simplex-bot/**" - "apps/simplex-bot-advanced/**" - - "apps/simplex-badge-service/**" + - "apps/simplex-store-service/**" - "apps/simplex-broadcast-bot/**" - "apps/simplex-directory-service/**" - "apps/multiplatform/**" @@ -35,7 +35,7 @@ on: - "packages/simplex-chat-client/types/typescript/**" - "packages/simplex-chat-python/**" - "scripts/ci/package-tests.sh" - - "apps/simplex-badge-service/web/**" + - "apps/simplex-store-service/web/**" - "scripts/ci/packages_release.py" - "scripts/ci/test_packages_release.py" types: [opened, synchronize, reopened, ready_for_review] diff --git a/.gitignore b/.gitignore index 1bb18ef356..c14e66553e 100644 --- a/.gitignore +++ b/.gitignore @@ -88,4 +88,6 @@ website/test/stubs-layout-cache/_includes/*.js apps/android/app/release apps/multiplatform/.kotlin/sessions # anywhere in the tree: this file holds a real BTCPay api_key and webhook_secret +store_service.ini +# a local ini under its name before the store service rename holds the same secrets badge_service.ini diff --git a/apps/simplex-badge-service/Main.hs b/apps/simplex-store-service/Main.hs similarity index 76% rename from apps/simplex-badge-service/Main.hs rename to apps/simplex-store-service/Main.hs index 68369995e2..fb2798d875 100644 --- a/apps/simplex-badge-service/Main.hs +++ b/apps/simplex-store-service/Main.hs @@ -2,8 +2,8 @@ module Main where -import BadgeService.Options (BadgeServiceOpts (..)) -import BadgeService.Service +import StoreService.Options (StoreServiceOpts (..)) +import StoreService.Service import Control.Logger.Simple (LogConfig (..), LogLevel (..), setLogLevel, withGlobalLogging) import GHC.IO.Encoding (setLocaleEncoding) import Simplex.Chat.Terminal (terminalChatConfig) @@ -17,7 +17,7 @@ main = do mapM_ (`hSetEncoding` utf8) [stdout, stderr] withGlobalLogging LogConfig {lc_file = Nothing, lc_stderr = True} $ do setLogLevel LogWarn - opts@BadgeServiceOpts {runCLI} <- welcomeGetOpts + opts@StoreServiceOpts {runCLI} <- welcomeGetOpts if runCLI - then badgeServiceCLI opts - else newServiceState >>= badgeService opts terminalChatConfig + then storeServiceCLI opts + else newServiceState >>= storeService opts terminalChatConfig diff --git a/apps/simplex-badge-service/README.md b/apps/simplex-store-service/README.md similarity index 91% rename from apps/simplex-badge-service/README.md rename to apps/simplex-store-service/README.md index e2941f565b..8abf3052eb 100644 --- a/apps/simplex-badge-service/README.md +++ b/apps/simplex-store-service/README.md @@ -1,8 +1,8 @@ -# SimpleX badge service +# SimpleX store service -`simplex-badge-service` runs the whole supporter-badge service as one process, two +`simplex-store-service` runs the whole store service as one process, two lanes: a SimpleX chat bot that answers service RPC over a double-ratchet contact -address, and — only when `--service-config` names a `badge_service.ini` — the badge-codes +address, and — only when `--service-config` names a `store_service.ini` — the badge-codes web checkout (BTCPay and Stripe payment, code issuance, the poller). **Without `--service-config` the web listener does not start at all**; the process still runs the chat side and nothing else. @@ -11,7 +11,7 @@ The wire protocol for the RPC side is [`docs/protocol/badges-rpc.md`](../../docs/protocol/badges-rpc.md). The web checkout is specified in [`plans/badges-codes/2026-08-27-badge-codes.md`](../../plans/badges-codes/2026-08-27-badge-codes.md), -whose §9 is the `badge_service.ini` reference, with the implementation plan in +whose §9 is the `store_service.ini` reference, with the implementation plan in [`plans/badges-codes/2026-08-31-service-btcpay.md`](../../plans/badges-codes/2026-08-31-service-btcpay.md). Earlier plans (`2026-07-30-supporter-badges-v3-ux.md`, `2026-07-31-badges-core-implementation.md`, `2026-08-04-badges-mvp-scope.md`) predate the web checkout and describe the RPC-only @@ -37,13 +37,13 @@ purchase that already exists. Build prerequisites and the general contribution flow are in [`docs/CONTRIBUTING.md`](../../docs/CONTRIBUTING.md). ``` -cabal build exe:simplex-badge-service +cabal build exe:simplex-store-service ``` ## Run ``` -simplex-badge-service --help +simplex-store-service --help ``` - default (no `--run-cli`): background service mode, no interactive terminal. @@ -62,7 +62,7 @@ The service checks the secret against the configured public key at that index an if they disagree: credentials signed with the wrong key cannot be verified by any client, and the codes redeemed against them would be spent for nothing. -The key can come from `badge_service.ini` instead: +The key can come from `store_service.ini` instead: ```ini [issuer] @@ -77,12 +77,12 @@ index it signs with at startup. The command line wins over the file when both `--issuer-key-idx` and `--issuer-secret` are given. Note that a secret passed as a flag is visible to every user on the machine through `ps`, where one -in the ini is only as readable as the file: `badge_service.ini` is gitignored and already holds the +in the ini is only as readable as the file: `store_service.ini` is gitignored and already holds the provider API keys and webhook secrets. Other options: -- `--service-config INI_FILE`: path to `badge_service.ini`. Omit it to run the chat/RPC side +- `--service-config INI_FILE`: path to `store_service.ini`. Omit it to run the chat/RPC side only; the process never starts a web listener without it, and never starts one under `--run-cli`, which parses and validates the whole file (`[listener] static_dir` included) but uses only its `[issuer]`, `[apple]`, `[google]` and `[dev]` sections. An issuer key is @@ -90,28 +90,28 @@ Other options: - `--service-name NAME`: the bot's display name, without `*`s or spaces (default `SimpleX Badges`). - `--client-service`: use the client service certificate. - also accepts the standard SimpleX Chat core options — database path, SMP/XFTP servers, - `--socks-proxy`, `--log-level`/`-l`, and the rest — run `simplex-badge-service --help` + `--socks-proxy`, `--log-level`/`-l`, and the rest — run `simplex-store-service --help` for the complete list. ### Running the web checkout -`badge_service.ini` holds the listener bind address and `static_dir`, an optional +`store_service.ini` holds the listener bind address and `static_dir`, an optional `[btcpay]` section (omitting it disables Bitcoin and Monero), an optional `[stripe]` section (omitting it disables card payments), an optional `[group]` section (omitting it turns off the group's commands, though a group created earlier still has its code messages updated) and the poll cadence. -`badge_service.ini.example` is the committed template; `badge_service.ini` itself is +`store_service.ini.example` is the committed template; `store_service.ini` itself is gitignored, since a real one holds API keys and webhook secrets. The full walkthrough is in [`web/README.md`](web/README.md#running-the-real-service-against-this-build). Short version: ``` -cd apps/simplex-badge-service/web && npm install && npm run build && cd ../../.. -cp apps/simplex-badge-service/badge_service.ini.example apps/simplex-badge-service/badge_service.ini -cabal run simplex-badge-service -- \ +cd apps/simplex-store-service/web && npm install && npm run build && cd ../../.. +cp apps/simplex-store-service/store_service.ini.example apps/simplex-store-service/store_service.ini +cabal run simplex-store-service -- \ --issuer-key-idx IDX --issuer-secret SECRET \ - --service-config apps/simplex-badge-service/badge_service.ini + --service-config apps/simplex-store-service/store_service.ini ``` `IDX` and `SECRET` must be one of the issuer keys clients already ship, not a fresh @@ -221,14 +221,14 @@ account key, or either section beside ```ini [apple] bundle_id = chat.simplex.app -root_certificates = /etc/simplex-badge-service/AppleRootCA-G3.cer +root_certificates = /etc/simplex-store-service/AppleRootCA-G3.cer api_key_id = 2X9R4HXF34 api_issuer_id = 57246542-96fe-1a63-e053-0824d011072a -api_private_key_file = /etc/simplex-badge-service/AuthKey_2X9R4HXF34.p8 +api_private_key_file = /etc/simplex-store-service/AuthKey_2X9R4HXF34.p8 [google] package_name = chat.simplex.app -service_account_file = /etc/simplex-badge-service/play-service-account.json +service_account_file = /etc/simplex-store-service/play-service-account.json ``` - `[apple]` verifies the signed transaction offline, against the roots `root_certificates` lists, @@ -407,6 +407,36 @@ credits this way. Nothing tells a production `[google]` from a test one, so neve beside the production Play app's `[google]`, or every licence tester the Play Console lists gets a badge without paying. +## Deployment + +### Upgrading from the badge service + +The rename to StoreService changed what the operator runs: + +| Before | After | +|---|---| +| `scripts/badge-service/` | `scripts/store-service/` | +| compose service `badge-service`, image `simplex-badge-service` | compose service `store-service`, image `simplex-store-service` | +| `badge_service.ini` | `store_service.ini` | +| the folder `config`, mounted read-only at `/etc/simplex-badge-service` (before it, `badge_service.ini` alone, mounted at `/etc/simplex-badge-service/badge_service.ini`) | the folder `config`, mounted read-only at `/etc/simplex-store-service` | +| `[apple] root_certificates` and `[google] service_account_file` under `/etc/simplex-badge-service/` | the same files under `/etc/simplex-store-service/` | +| the binary `simplex-badge-service` | `simplex-store-service` | + +Move `scripts/badge-service/config/` to `scripts/store-service/config/` (a deployment from before +the config folder creates it and moves `badge_service.ini` into it), rename `badge_service.ini` in it +to `store_service.ini`, and change its paths as the table says, the +`/etc/simplex-badge-service/` files under `[apple]` and `[google]` among them. Point Caddy's badges root at +`scripts/store-service/web`, which the service fills at boot. Then start the new service with + +``` +docker compose up -d --build --remove-orphans +``` + +from `scripts/store-service/`. Without `--remove-orphans` the old `badge-service` container keeps +running beside the new one, on the same port and database. The database `badge_service`, +`BADGE_DB_CONN`, the `sx_badge_service_` tables and the chat database prefix +`simplex_badge_service` are unchanged. + ## Issuing codes Operators issue codes two ways: from the service's own command line in `--run-cli` mode, and from the @@ -448,7 +478,7 @@ why issuing codes lives in the service rather than in core. ### From the group -With `[group]` in `badge_service.ini`, the service manages one group and serves three commands in +With `[group]` in `store_service.ini`, the service manages one group and serves three commands in it: `/issue [months ] [uses ]` and `/bulk [months ] count ` for moderators and above, `/revoke ` for admins and owners. `months` is 1 to 255, `uses` 1 to 1000 and `count` 1 to 100; a value outside these gets the usage reply. A member's role is checked as the diff --git a/apps/simplex-badge-service/src/BadgeService/Catalog.hs b/apps/simplex-store-service/src/StoreService/Catalog.hs similarity index 98% rename from apps/simplex-badge-service/src/BadgeService/Catalog.hs rename to apps/simplex-store-service/src/StoreService/Catalog.hs index 58fc246399..8306a6c55a 100644 --- a/apps/simplex-badge-service/src/BadgeService/Catalog.hs +++ b/apps/simplex-store-service/src/StoreService/Catalog.hs @@ -3,7 +3,7 @@ {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} -module BadgeService.Catalog +module StoreService.Catalog ( OfferInvalid (..), CatalogRefusal (..), offerTotal, @@ -22,7 +22,7 @@ import Data.Text (Text) import Data.Time.Clock (UTCTime) import Data.Word (Word32, Word64, Word8) import Simplex.Chat.Badges (BadgeType (..)) -import Simplex.Chat.Badges.Service (BadgeOffer (..), BadgePrice (..)) +import Simplex.Chat.StoreService (BadgeOffer (..), BadgePrice (..)) import Simplex.Chat.Badges.Types (BadgeItemStatus (..), BadgeOfferId (..), BadgePriceId (..), OfferDiscount (..)) import Simplex.Chat.PaymentService.Types (CurrencyAmount (..), PaymentProvider (..)) diff --git a/apps/simplex-badge-service/src/BadgeService/Codes.hs b/apps/simplex-store-service/src/StoreService/Codes.hs similarity index 90% rename from apps/simplex-badge-service/src/BadgeService/Codes.hs rename to apps/simplex-store-service/src/StoreService/Codes.hs index 06d3517359..7d0168e080 100644 --- a/apps/simplex-badge-service/src/BadgeService/Codes.hs +++ b/apps/simplex-store-service/src/StoreService/Codes.hs @@ -1,7 +1,7 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} -module BadgeService.Codes +module StoreService.Codes ( issueOneCode, issueFailedText, revokeBadgeCode, @@ -9,8 +9,8 @@ module BadgeService.Codes ) where -import BadgeService.Store (RevokeResult, insertBadgeCode, revokeCode) -import BadgeService.Store.Invoices (truncateToSecond) +import StoreService.Store (RevokeResult, insertBadgeCode, revokeCode) +import StoreService.Store.Invoices (truncateToSecond) import Data.Int (Int64) import Data.Text (Text) import Data.Time.Clock (getCurrentTime) diff --git a/apps/simplex-badge-service/src/BadgeService/Config.hs b/apps/simplex-store-service/src/StoreService/Config.hs similarity index 99% rename from apps/simplex-badge-service/src/BadgeService/Config.hs rename to apps/simplex-store-service/src/StoreService/Config.hs index 8bd240ee56..da770e1cd6 100644 --- a/apps/simplex-badge-service/src/BadgeService/Config.hs +++ b/apps/simplex-store-service/src/StoreService/Config.hs @@ -3,7 +3,7 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -module BadgeService.Config +module StoreService.Config ( ListenerConfig (..), BTCPayConfig (..), StripeConfig (..), @@ -24,7 +24,7 @@ module BadgeService.Config where import qualified Control.Exception as E -import BadgeService.Log (logWarn) +import StoreService.Log (logWarn) import Control.Monad (mfilter, unless, when) import Data.Attoparsec.Text (Parser, endOfInput, isEndOfLine, parseOnly, satisfy, skipMany, skipSpace, skipWhile) import qualified Data.ByteString.Char8 as B diff --git a/apps/simplex-badge-service/src/BadgeService/Group.hs b/apps/simplex-store-service/src/StoreService/Group.hs similarity index 98% rename from apps/simplex-badge-service/src/BadgeService/Group.hs rename to apps/simplex-store-service/src/StoreService/Group.hs index b072277a76..e7e6c08299 100644 --- a/apps/simplex-badge-service/src/BadgeService/Group.hs +++ b/apps/simplex-store-service/src/StoreService/Group.hs @@ -5,7 +5,7 @@ {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-ambiguous-fields #-} -module BadgeService.Group +module StoreService.Group ( ensureManagedGroup, runGroupLane, inertGroupConfig, @@ -24,12 +24,12 @@ module BadgeService.Group ) where -import BadgeService.Codes (issueFailedText, issueOneCode, revokeBadgeCode, singleUse) -import BadgeService.Config (GroupConfig (..)) -import BadgeService.Group.Command (CmdAction (..), GroupCmd (..), groupCmdAction, groupCommands) -import BadgeService.Log (logError, logInfo, logWarn) -import BadgeService.Store (CodeTracker (..), ManagedGroup (..), RevokeResult (..), clearCodeGroupItems, getCodeTracker, getEditableTrackers, getManagedGroup, insertManagedGroup, markOwnerBootstrapped, setCodeGroupItem) -import BadgeService.Store.Invoices (truncateToSecond) +import StoreService.Codes (issueFailedText, issueOneCode, revokeBadgeCode, singleUse) +import StoreService.Config (GroupConfig (..)) +import StoreService.Group.Command (CmdAction (..), GroupCmd (..), groupCmdAction, groupCommands) +import StoreService.Log (logError, logInfo, logWarn) +import StoreService.Store (CodeTracker (..), ManagedGroup (..), RevokeResult (..), clearCodeGroupItems, getCodeTracker, getEditableTrackers, getManagedGroup, insertManagedGroup, markOwnerBootstrapped, setCodeGroupItem) +import StoreService.Store.Invoices (truncateToSecond) import Control.Concurrent.STM (TQueue, atomically, flushTQueue, readTQueue, readTVarIO, writeTQueue) import Control.Monad (forM_, forever, mfilter, replicateM, unless, void) import Control.Monad.Except (runExceptT) diff --git a/apps/simplex-badge-service/src/BadgeService/Group/Command.hs b/apps/simplex-store-service/src/StoreService/Group/Command.hs similarity index 99% rename from apps/simplex-badge-service/src/BadgeService/Group/Command.hs rename to apps/simplex-store-service/src/StoreService/Group/Command.hs index 799e1a2fcf..460450e44e 100644 --- a/apps/simplex-badge-service/src/BadgeService/Group/Command.hs +++ b/apps/simplex-store-service/src/StoreService/Group/Command.hs @@ -2,7 +2,7 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} -module BadgeService.Group.Command +module StoreService.Group.Command ( GroupCmd (..), CmdAction (..), groupCmdAction, diff --git a/apps/simplex-badge-service/src/BadgeService/Log.hs b/apps/simplex-store-service/src/StoreService/Log.hs similarity index 98% rename from apps/simplex-badge-service/src/BadgeService/Log.hs rename to apps/simplex-store-service/src/StoreService/Log.hs index 6ac7cd48a2..5aff5d2580 100644 --- a/apps/simplex-badge-service/src/BadgeService/Log.hs +++ b/apps/simplex-store-service/src/StoreService/Log.hs @@ -1,7 +1,7 @@ {-# LANGUAGE OverloadedStrings #-} -- | The SMP agent logs unconditionally at info on the global logger, so the service keeps its own info lines on this separate channel when that logger is raised to Warn. -module BadgeService.Log +module StoreService.Log ( logInfo, logWarn, logError, diff --git a/apps/simplex-badge-service/src/BadgeService/Names/Chain.hs b/apps/simplex-store-service/src/StoreService/Names/Chain.hs similarity index 97% rename from apps/simplex-badge-service/src/BadgeService/Names/Chain.hs rename to apps/simplex-store-service/src/StoreService/Names/Chain.hs index dd23fcac6e..35cd39974c 100644 --- a/apps/simplex-badge-service/src/BadgeService/Names/Chain.hs +++ b/apps/simplex-store-service/src/StoreService/Names/Chain.hs @@ -2,7 +2,7 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -module BadgeService.Names.Chain +module StoreService.Names.Chain ( ChainClient (..), ChainError (..), TxHash (..), @@ -11,7 +11,7 @@ module BadgeService.Names.Chain ) where -import BadgeService.Names.Registration (RegisterIntent, commitCalldata, registerWithCreditCalldata) +import StoreService.Names.Registration (RegisterIntent, commitCalldata, registerWithCreditCalldata) import Control.Concurrent.STM (TVar) import Control.Exception (try) import Control.Monad.Except (ExceptT, liftEither, runExceptT, throwError) diff --git a/apps/simplex-badge-service/src/BadgeService/Names/Registration.hs b/apps/simplex-store-service/src/StoreService/Names/Registration.hs similarity index 99% rename from apps/simplex-badge-service/src/BadgeService/Names/Registration.hs rename to apps/simplex-store-service/src/StoreService/Names/Registration.hs index 0881b6cb24..6d187c811a 100644 --- a/apps/simplex-badge-service/src/BadgeService/Names/Registration.hs +++ b/apps/simplex-store-service/src/StoreService/Names/Registration.hs @@ -2,7 +2,7 @@ {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} -module BadgeService.Names.Registration +module StoreService.Names.Registration ( Registration (..), RegisterIntent (..), sponsorDomain, diff --git a/apps/simplex-badge-service/src/BadgeService/Options.hs b/apps/simplex-store-service/src/StoreService/Options.hs similarity index 80% rename from apps/simplex-badge-service/src/BadgeService/Options.hs rename to apps/simplex-store-service/src/StoreService/Options.hs index 1d2423771a..cd2309372b 100644 --- a/apps/simplex-badge-service/src/BadgeService/Options.hs +++ b/apps/simplex-store-service/src/StoreService/Options.hs @@ -3,15 +3,15 @@ {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} -module BadgeService.Options - ( BadgeServiceOpts (..), - getBadgeServiceOpts, - badgeServiceOpts, +module StoreService.Options + ( StoreServiceOpts (..), + getStoreServiceOpts, + storeServiceOpts, mkChatOpts, ) where -import BadgeService.Config (BadgeIssuerKey (..)) +import StoreService.Config (BadgeIssuerKey (..)) import qualified Data.ByteString.Char8 as B import qualified Data.Text as T import Options.Applicative @@ -19,7 +19,7 @@ import Simplex.Chat.Controller (updateStr, versionNumber, versionString) import Simplex.Chat.Options (ChatCmdLog (..), ChatOpts (..), CoreChatOpts, CreateBotOpts (..), coreChatOptsP) import Simplex.Messaging.Encoding.String (strDecode) -data BadgeServiceOpts = BadgeServiceOpts +data StoreServiceOpts = StoreServiceOpts { coreOptions :: CoreChatOpts, serviceName :: T.Text, clientService :: Bool, @@ -30,14 +30,14 @@ data BadgeServiceOpts = BadgeServiceOpts testing :: Bool } -badgeServiceOpts :: FilePath -> FilePath -> Parser BadgeServiceOpts -badgeServiceOpts appDir defaultDbName = do +storeServiceOpts :: FilePath -> FilePath -> Parser StoreServiceOpts +storeServiceOpts appDir defaultDbName = do coreOptions <- coreChatOptsP appDir defaultDbName serviceName <- strOption ( long "service-name" <> metavar "SERVICE_NAME" - <> help "The display name of the badge service bot, without *'s and spaces (SimpleX Badges)" + <> help "The display name of the store service bot, without *'s and spaces (SimpleX Badges)" <> value "SimpleX Badges" ) clientService <- @@ -53,14 +53,14 @@ badgeServiceOpts appDir defaultDbName = do runCLI <- switch ( long "run-cli" - <> help "Run badge service as CLI" + <> help "Run store service as CLI" ) serviceConfigFile <- optional ( strOption ( long "service-config" <> metavar "INI_FILE" - <> help "Path to badge_service.ini: parsed in full in every mode, but --run-cli starts no web listener" + <> help "Path to store_service.ini: parsed in full in every mode, but --run-cli starts no web listener" ) ) issuerKeyIdx <- @@ -80,7 +80,7 @@ badgeServiceOpts appDir defaultDbName = do <> help "Issuer secret from `simplex-chat badge keygen` (base64url)" ) pure - BadgeServiceOpts + StoreServiceOpts { coreOptions, serviceName = T.pack serviceName, clientService, @@ -94,19 +94,19 @@ badgeServiceOpts appDir defaultDbName = do testing = False } -getBadgeServiceOpts :: FilePath -> FilePath -> IO BadgeServiceOpts -getBadgeServiceOpts appDir defaultDbName = +getStoreServiceOpts :: FilePath -> FilePath -> IO StoreServiceOpts +getStoreServiceOpts appDir defaultDbName = execParser $ info - (helper <*> versionOption <*> badgeServiceOpts appDir defaultDbName) - (header versionStr <> fullDesc <> progDesc "Start SimpleX Badge Service with DB_FILE options") + (helper <*> versionOption <*> storeServiceOpts appDir defaultDbName) + (header versionStr <> fullDesc <> progDesc "Start SimpleX Store Service with DB_FILE options") where versionStr = versionString versionNumber versionOption = infoOption versionAndUpdate (long "version" <> short 'v' <> help "Show version") versionAndUpdate = versionStr <> "\n" <> updateStr -mkChatOpts :: BadgeServiceOpts -> ChatOpts -mkChatOpts BadgeServiceOpts {coreOptions, serviceName, clientService} = +mkChatOpts :: StoreServiceOpts -> ChatOpts +mkChatOpts StoreServiceOpts {coreOptions, serviceName, clientService} = ChatOpts { coreOptions, chatCmd = "", diff --git a/apps/simplex-badge-service/src/BadgeService/Orders.hs b/apps/simplex-store-service/src/StoreService/Orders.hs similarity index 95% rename from apps/simplex-badge-service/src/BadgeService/Orders.hs rename to apps/simplex-store-service/src/StoreService/Orders.hs index 63359b0880..32be2ebc74 100644 --- a/apps/simplex-badge-service/src/BadgeService/Orders.hs +++ b/apps/simplex-store-service/src/StoreService/Orders.hs @@ -2,11 +2,11 @@ {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} -module BadgeService.Orders (settleOrder, decide, codeLifetime) where +module StoreService.Orders (settleOrder, decide, codeLifetime) where -import BadgeService.Providers (Funded (..), PaymentSignal (..), Received (..)) -import BadgeService.Store.Invoices (InvoicePayment (..), InvoiceRow (..), markCodePaid, paymentStatusText, settlementCodeHash, settlementInvoice, truncateToSecond, updateInvoiceStatus, upsertPayment) -import BadgeService.Waiters (Waiters, publish, publishPayment) +import StoreService.Providers (Funded (..), PaymentSignal (..), Received (..)) +import StoreService.Store.Invoices (InvoicePayment (..), InvoiceRow (..), markCodePaid, paymentStatusText, settlementCodeHash, settlementInvoice, truncateToSecond, updateInvoiceStatus, upsertPayment) +import StoreService.Waiters (Waiters, publish, publishPayment) import Control.Concurrent.STM (atomically) import Control.Monad (when) import Data.ByteString (ByteString) diff --git a/apps/simplex-badge-service/src/BadgeService/Poller.hs b/apps/simplex-store-service/src/StoreService/Poller.hs similarity index 97% rename from apps/simplex-badge-service/src/BadgeService/Poller.hs rename to apps/simplex-store-service/src/StoreService/Poller.hs index 989faa4396..10542fb4e4 100644 --- a/apps/simplex-badge-service/src/BadgeService/Poller.hs +++ b/apps/simplex-store-service/src/StoreService/Poller.hs @@ -4,7 +4,7 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -module BadgeService.Poller +module StoreService.Poller ( PollerEnv (..), ReadHints, newReadHints, @@ -27,14 +27,14 @@ module BadgeService.Poller ) where -import BadgeService.Config (PollConfig (..)) -import BadgeService.Orders (decide, settleOrder) -import BadgeService.Providers (ListPass (..), PaymentSignal (..), Provider (..), ProviderError (..), Received (..), expiresItself, settleWindow) -import BadgeService.Store.Invoices (InvoiceRow (..), OverdueInvoice (..), expireOverdue, getInvoiceByProviderRef, overdueInvoices, unpaidRefs) -import BadgeService.Waiters (Waiters, publish, waitingCount, waitingCountSTM) +import StoreService.Config (PollConfig (..)) +import StoreService.Orders (decide, settleOrder) +import StoreService.Providers (ListPass (..), PaymentSignal (..), Provider (..), ProviderError (..), Received (..), expiresItself, settleWindow) +import StoreService.Store.Invoices (InvoiceRow (..), OverdueInvoice (..), expireOverdue, getInvoiceByProviderRef, overdueInvoices, unpaidRefs) +import StoreService.Waiters (Waiters, publish, waitingCount, waitingCountSTM) import Control.Concurrent.STM import Control.Exception (SomeAsyncException, SomeException, fromException, throwIO, try) -import BadgeService.Log (logError, logInfo, logWarn) +import StoreService.Log (logError, logInfo, logWarn) import Control.Monad (filterM, forever, unless, void, when) import Data.List (find, partition, sortOn) import Data.Map.Strict (Map) diff --git a/apps/simplex-badge-service/src/BadgeService/Providers.hs b/apps/simplex-store-service/src/StoreService/Providers.hs similarity index 98% rename from apps/simplex-badge-service/src/BadgeService/Providers.hs rename to apps/simplex-store-service/src/StoreService/Providers.hs index 8faabd2a2c..c0904094c5 100644 --- a/apps/simplex-badge-service/src/BadgeService/Providers.hs +++ b/apps/simplex-store-service/src/StoreService/Providers.hs @@ -1,7 +1,7 @@ {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NamedFieldPuns #-} -module BadgeService.Providers +module StoreService.Providers ( ProviderError (..), WebhookError (..), Received (..), diff --git a/apps/simplex-badge-service/src/BadgeService/Providers/BTCPay.hs b/apps/simplex-store-service/src/StoreService/Providers/BTCPay.hs similarity index 99% rename from apps/simplex-badge-service/src/BadgeService/Providers/BTCPay.hs rename to apps/simplex-store-service/src/StoreService/Providers/BTCPay.hs index 2df54789a3..1a910205c6 100644 --- a/apps/simplex-badge-service/src/BadgeService/Providers/BTCPay.hs +++ b/apps/simplex-store-service/src/StoreService/Providers/BTCPay.hs @@ -3,7 +3,7 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -module BadgeService.Providers.BTCPay +module StoreService.Providers.BTCPay ( btcpayProvider, btcMethodId, xmrMethodId, @@ -16,8 +16,8 @@ module BadgeService.Providers.BTCPay ) where -import BadgeService.Config (BTCPayConfig (..), speedPolicyName) -import BadgeService.Providers +import StoreService.Config (BTCPayConfig (..), speedPolicyName) +import StoreService.Providers ( ListPass (..), OrderDraft (..), PaymentSignal (..), @@ -30,7 +30,7 @@ import BadgeService.Providers WebhookError (..), ) import Control.Exception (try) -import BadgeService.Log (logError, logInfo, logWarn) +import StoreService.Log (logError, logInfo, logWarn) import Control.Monad (unless) import Crypto.Hash (Digest, SHA256) import Crypto.MAC.HMAC (HMAC, hmac, hmacGetDigest) diff --git a/apps/simplex-badge-service/src/BadgeService/Providers/Stripe.hs b/apps/simplex-store-service/src/StoreService/Providers/Stripe.hs similarity index 99% rename from apps/simplex-badge-service/src/BadgeService/Providers/Stripe.hs rename to apps/simplex-store-service/src/StoreService/Providers/Stripe.hs index 93f55f37b2..aff7100cf7 100644 --- a/apps/simplex-badge-service/src/BadgeService/Providers/Stripe.hs +++ b/apps/simplex-store-service/src/StoreService/Providers/Stripe.hs @@ -3,15 +3,15 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -module BadgeService.Providers.Stripe +module StoreService.Providers.Stripe ( stripeProvider, signalOf, IntentRead (..), ) where -import BadgeService.Config (StripeConfig (..)) -import BadgeService.Providers +import StoreService.Config (StripeConfig (..)) +import StoreService.Providers ( ListPass (..), OrderDraft (..), PaymentSignal (..), diff --git a/apps/simplex-badge-service/src/BadgeService/Service.hs b/apps/simplex-store-service/src/StoreService/Service.hs similarity index 86% rename from apps/simplex-badge-service/src/BadgeService/Service.hs rename to apps/simplex-store-service/src/StoreService/Service.hs index d5d2b318a0..14f5958aa5 100644 --- a/apps/simplex-badge-service/src/BadgeService/Service.hs +++ b/apps/simplex-store-service/src/StoreService/Service.hs @@ -4,15 +4,15 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} -module BadgeService.Service +module StoreService.Service ( ServiceState (..), newServiceState, configureStoreVerifier, welcomeGetOpts, checkIssuerKey, - badgeService, - badgeServiceCLI, - badgeServiceResponse, + storeService, + storeServiceCLI, + storeServiceResponse, RequestLane (..), requestLane, PurchaseChecks (..), @@ -35,25 +35,25 @@ module BadgeService.Service ) where -import BadgeService.Catalog (StoreProduct (..), defaultCatalog, storeProduct) -import BadgeService.Codes (issueFailedText, issueOneCode, singleUse) -import BadgeService.Config (AppleStoreConfig (..), BadgeIssuerKey (..), PlayStoreConfig (..), ServiceConfig (..), readServiceConfig) -import BadgeService.Group (GroupEvent, ensureManagedGroup, groupEvent, hasTracker, refreshTracker, revokeWithTracker, runGroupLane) -import BadgeService.Group.Command (badgeTypeP, codeP, maxMonths, textTokenP) -import BadgeService.Log (logError, logInfo, logWarn) -import BadgeService.Options -import BadgeService.Poller (newPollerEnv, newReadHints, runPoller) -import BadgeService.Providers.BTCPay (btcpayProvider) -import BadgeService.Providers.Stripe (stripeProvider) -import BadgeService.Store -import BadgeService.Store.Invoices (seedCatalog, truncateToSecond) -import BadgeService.Store.Migrate (runBadgeServiceMigrations) -import BadgeService.StoreReceipts -import BadgeService.StoreReceipts.Apple (appleSubscriptionChecker, readAppleRoot, verifyAppleTransaction) -import BadgeService.StoreReceipts.Google (PlayVerifier (..), playStoreVerifier) -import BadgeService.StoreReceipts.Mock (newMockStoreVerifier) -import BadgeService.Waiters (Waiters, newWaiters) -import BadgeService.Web.Server (Bucket, exportWebapp, newWebEnv, runWebListener, takeFrom) +import StoreService.Catalog (StoreProduct (..), defaultCatalog, storeProduct) +import StoreService.Codes (issueFailedText, issueOneCode, singleUse) +import StoreService.Config (AppleStoreConfig (..), BadgeIssuerKey (..), PlayStoreConfig (..), ServiceConfig (..), readServiceConfig) +import StoreService.Group (GroupEvent, ensureManagedGroup, groupEvent, hasTracker, refreshTracker, revokeWithTracker, runGroupLane) +import StoreService.Group.Command (badgeTypeP, codeP, maxMonths, textTokenP) +import StoreService.Log (logError, logInfo, logWarn) +import StoreService.Options +import StoreService.Poller (newPollerEnv, newReadHints, runPoller) +import StoreService.Providers.BTCPay (btcpayProvider) +import StoreService.Providers.Stripe (stripeProvider) +import StoreService.Store +import StoreService.Store.Invoices (seedCatalog, truncateToSecond) +import StoreService.Store.Migrate (runStoreServiceMigrations) +import StoreService.StoreReceipts +import StoreService.StoreReceipts.Apple (appleSubscriptionChecker, readAppleRoot, verifyAppleTransaction) +import StoreService.StoreReceipts.Google (PlayVerifier (..), playStoreVerifier) +import StoreService.StoreReceipts.Mock (newMockStoreVerifier) +import StoreService.Waiters (Waiters, newWaiters) +import StoreService.Web.Server (Bucket, exportWebapp, newWebEnv, runWebListener, takeFrom) import Control.Applicative (optional) import Control.Concurrent.STM import Control.Monad @@ -73,7 +73,7 @@ import Data.Word (Word32) import Simplex.Chat.Badges import Simplex.Chat.Badges.Code import Simplex.Chat.Badges.Ledger -import Simplex.Chat.Badges.Service +import Simplex.Chat.StoreService import Simplex.Chat.Badges.StorePlan (storePlan) import Simplex.Chat.Badges.Types (BadgeCodePaymentStatus (..)) import Simplex.Chat.Bot (initializeBotAddress') @@ -103,7 +103,7 @@ data ServiceState = ServiceState storeVerifier :: StoreVerifier } --- | With no store verifier, which badge_service.ini configures, every store receipt not already credited +-- | With no store verifier, which store_service.ini configures, every store receipt not already credited -- is answered provider_not_configured. newServiceState :: IO ServiceState newServiceState = do @@ -112,22 +112,22 @@ newServiceState = do groupEventQ <- newTQueueIO pure ServiceState {serviceCC, serviceRequestQ, groupEventQ, storeVerifier = noStoreVerifier} -welcomeGetOpts :: IO BadgeServiceOpts +welcomeGetOpts :: IO StoreServiceOpts welcomeGetOpts = do appDir <- getAppUserDataDirectory "simplex" - opts@BadgeServiceOpts {coreOptions, testing, serviceName} <- getBadgeServiceOpts appDir "simplex_badge_service" + opts@StoreServiceOpts {coreOptions, testing, serviceName} <- getStoreServiceOpts appDir "simplex_badge_service" unless testing $ do - putStrLn $ "SimpleX Badge Service v" ++ versionNumber + putStrLn $ "SimpleX Store Service v" ++ versionNumber printDbOpts coreOptions putStrLn $ "Service name: " ++ T.unpack serviceName pure opts -checkIssuerKey :: BadgeServiceOpts -> Maybe ServiceConfig -> ChatConfig -> IO (Either String BadgeIssuerKey) -checkIssuerKey BadgeServiceOpts {issuerKey} serviceCfg cfg = case issuerKey of +checkIssuerKey :: StoreServiceOpts -> Maybe ServiceConfig -> ChatConfig -> IO (Either String BadgeIssuerKey) +checkIssuerKey StoreServiceOpts {issuerKey} serviceCfg cfg = case issuerKey of Left e -> pure (Left e) Right (Just k) -> checkOne cfg k Right Nothing -> case serviceCfg >>= issuer of - Nothing -> pure $ Left "an issuer key is required - pass --issuer-key-idx and --issuer-secret, or add an [issuer] section to badge_service.ini (see `simplex-chat badge keygen`)" + Nothing -> pure $ Left "an issuer key is required - pass --issuer-key-idx and --issuer-secret, or add an [issuer] section to store_service.ini (see `simplex-chat badge keygen`)" Just k -> checkOne cfg k checkOne :: ChatConfig -> BadgeIssuerKey -> IO (Either String BadgeIssuerKey) @@ -139,7 +139,7 @@ checkOne ChatConfig {badgePublicKeys} k@BadgeIssuerKey {keyIdx, secretKey} = Just _ -> Left $ "issuer secret does not match the configured key at index " <> show keyIdx <> ", its public key is " <> T.unpack (safeDecodeUtf8 $ strEncode pk) Nothing -> Left $ "no configured badge key at index " <> show keyIdx <> ", clients could not verify what this service signs" -requireIssuerKey :: BadgeServiceOpts -> Maybe ServiceConfig -> ChatConfig -> IO BadgeIssuerKey +requireIssuerKey :: StoreServiceOpts -> Maybe ServiceConfig -> ChatConfig -> IO BadgeIssuerKey requireIssuerKey opts serviceCfg cfg = checkIssuerKey opts serviceCfg cfg >>= either (\e -> putStrLn ("Error: " <> e) >> exitFailure) (\k@BadgeIssuerKey {keyIdx} -> logInfo ("signing badges with issuer key " <> tshow keyIdx) $> k) @@ -191,8 +191,8 @@ configureStoreVerifier serviceCfg env@ServiceState {serviceCC, storeVerifier = v orExit = (>>= either (\e -> putStrLn ("Error: " <> e) >> exitFailure) pure) notConfigured = pure $ Left SRNotConfigured -badgeService :: BadgeServiceOpts -> ChatConfig -> ServiceState -> IO () -badgeService opts@BadgeServiceOpts {serviceConfigFile} cfg env = do +storeService :: StoreServiceOpts -> ChatConfig -> ServiceState -> IO () +storeService opts@StoreServiceOpts {serviceConfigFile} cfg env = do serviceCfg <- traverse readConfigOrExit serviceConfigFile key <- requireIssuerKey opts serviceCfg cfg waiters <- newWaiters @@ -243,8 +243,8 @@ seedServiceCatalog st = do "badge catalog: " <> tshow (length prices) <> " prices and " <> tshow (length offers) <> " offers compiled in, " <> tshow seededPrices <> " prices and " <> tshow seededOffers <> " offers inserted" -badgeServiceCLI :: BadgeServiceOpts -> IO () -badgeServiceCLI opts@BadgeServiceOpts {serviceConfigFile} = do +storeServiceCLI :: StoreServiceOpts -> IO () +storeServiceCLI opts@StoreServiceOpts {serviceConfigFile} = do serviceCfg <- traverse readConfigOrExit serviceConfigFile key <- requireIssuerKey opts serviceCfg terminalChatConfig env <- newServiceState >>= configureStoreVerifier serviceCfg @@ -343,13 +343,13 @@ data RequestLane = MainLane | PurchaseLane | RenewalLane -- purchase's row lock before re-reading the tip, so the lanes may run concurrently at any --pool-size. requestLane :: StoreChecks -> ChatController -> Maybe C.PublicKeyEd25519 -> J.Object -> IO RequestLane requestLane checks cc sigKey reqData = case J.fromJSON (J.Object reqData) of - J.Success BadgeServiceRequest {request = BSCPurchaseBadge {payment = SPGoogle {}, upgrade = Nothing}} -> pure PurchaseLane - J.Success BadgeServiceRequest {request = BSCPurchaseBadge {payment = SPApple {jws}, upgrade = Nothing}} + J.Success StoreServiceRequest {request = STCPurchaseBadge {payment = SPGoogle {}, upgrade = Nothing}} -> pure PurchaseLane + J.Success StoreServiceRequest {request = STCPurchaseBadge {payment = SPApple {jws}, upgrade = Nothing}} | maybe False autoRenewable (appleTransactionFacts jws) -> pure PurchaseLane - J.Success BadgeServiceRequest {request = BSCTransferBadge {payment = SPApple {jws}}} + J.Success StoreServiceRequest {request = STCTransferBadge {payment = SPApple {jws}}} | maybe False autoRenewable (appleTransactionFacts jws) -> pure PurchaseLane - J.Success BadgeServiceRequest {request = BSCTransferBadge {payment = SPGoogle {}}} -> pure PurchaseLane - J.Success BadgeServiceRequest {purchaseKey = Just k, request = BSCIssueBadge {}} + J.Success StoreServiceRequest {request = STCTransferBadge {payment = SPGoogle {}}} -> pure PurchaseLane + J.Success StoreServiceRequest {purchaseKey = Just k, request = STCIssueBadge {}} | sigKey == Just k -> do now <- badgeNow cc withDB' "requestLane" cc (\db -> getIssuePurchase db k) <&> \case @@ -359,7 +359,7 @@ requestLane checks cc sigKey reqData = case J.fromJSON (J.Object reqData) of Right _ -> MainLane -- a read that failed may hide a due check, and the main lane is what must not wait on a store Left _ -> RenewalLane - J.Success BadgeServiceRequest {purchaseKey = Just k, request = BSCUpgradeBadgeSubscription {}} + J.Success StoreServiceRequest {purchaseKey = Just k, request = STCUpgradeBadgeSubscription {}} | sigKey == Just k -> do now <- badgeNow cc withDB' "requestLane" cc (\db -> getIssuePurchase db k) <&> \case @@ -376,14 +376,14 @@ routeLookahead = 60 -- | Cancellation is rethrown, since that is how the race stops this thread. The -- exception itself is not logged: it can quote the request, which carries codes and store receipts. survive :: T.Text -> IO () -> IO () -survive what action = action `catchOwn'` \_ -> logError $ "badge service: " <> what <> " failed; the next one will be handled" +survive what action = action `catchOwn'` \_ -> logError $ "store service: " <> what <> " failed; the next one will be handled" -badgePreStartHook :: BadgeServiceOpts -> ChatController -> IO () +badgePreStartHook :: StoreServiceOpts -> ChatController -> IO () badgePreStartHook opts ChatController {config, chatStore} = - runBadgeServiceMigrations opts config chatStore + runStoreServiceMigrations opts config chatStore -badgePostStartHook :: BadgeServiceOpts -> ServiceState -> ChatController -> IO () -badgePostStartHook BadgeServiceOpts {noAddress, testing} env cc = do +badgePostStartHook :: StoreServiceOpts -> ServiceState -> ChatController -> IO () +badgePostStartHook StoreServiceOpts {noAddress, testing} env cc = do -- Core starts this False and gates service request delivery on it, so the hook must set it. atomically $ writeTVar (processServiceRequests cc) True readTVarIO (currentUser cc) >>= \case @@ -396,70 +396,70 @@ badgePostStartHook BadgeServiceOpts {noAddress, testing} env cc = do handleServiceRequest :: BadgeIssuerKey -> StoreVerifier -> PurchaseChecks -> ChatController -> Maybe (TQueue GroupEvent) -> User -> AgentInvId -> Maybe C.PublicKeyEd25519 -> J.Object -> IO () handleServiceRequest key verifier checks cc trackerQ_ User {userId} reqId sigKey reqData = do let reqIdT = safeDecodeUtf8 (strEncode reqId) - logInfo $ "badge service request " <> reqIdT + logInfo $ "store service request " <> reqIdT resp <- - badgeServiceResponse key verifier checks cc trackerQ_ sigKey reqData `catchOwn'` \_ -> - logError ("badge service request " <> reqIdT <> " failed") $> errorResponse BSEInternal + storeServiceResponse key verifier checks cc trackerQ_ sigKey reqData `catchOwn'` \_ -> + logError ("store service request " <> reqIdT <> " failed") $> errorResponse STEInternal logInfo $ "badge answer: " <> responseName resp sendChatCmd cc (APISendServiceResponse userId reqId (responseObject resp)) >>= \case Right _ -> pure () - Left e -> logError $ "badge service response failed for " <> reqIdT <> ": " <> tshow e + Left e -> logError $ "store service response failed for " <> reqIdT <> ": " <> tshow e -responseObject :: BadgeServiceResponse -> J.Object +responseObject :: StoreServiceResponse -> J.Object responseObject r = case J.toJSON r of J.Object o -> o - _ -> KM.fromList [("type", J.String "error"), ("code", J.toJSON BSEInternal)] + _ -> KM.fromList [("type", J.String "error"), ("code", J.toJSON STEInternal)] -errorResponse :: BadgeServiceErrorCode -> BadgeServiceResponse -errorResponse code = BSPError {code, message = Nothing, retryAfter = badgeErrorRetryAfter code} +errorResponse :: StoreServiceErrorCode -> StoreServiceResponse +errorResponse code = STPError {code, message = Nothing, retryAfter = badgeErrorRetryAfter code} -badgeErrorRetryAfter :: BadgeServiceErrorCode -> Maybe Word32 +badgeErrorRetryAfter :: StoreServiceErrorCode -> Maybe Word32 badgeErrorRetryAfter = \case - BSEPaymentPending -> Just 300 - BSEProviderUnavailable -> Just 300 - BSERateLimited -> Just 60 + STEPaymentPending -> Just 300 + STEProviderUnavailable -> Just 300 + STERateLimited -> Just 60 _ -> Nothing -- | The agent verified the signature, so sigKey is a key the sender holds; a differing purchaseKey would let a client claim a purchase it cannot sign for. -badgeServiceResponse :: BadgeIssuerKey -> StoreVerifier -> PurchaseChecks -> ChatController -> Maybe (TQueue GroupEvent) -> Maybe C.PublicKeyEd25519 -> J.Object -> IO BadgeServiceResponse -badgeServiceResponse key verifier checks cc trackerQ_ sigKey reqData = case J.fromJSON (J.Object reqData) of - J.Error _ -> pure $ errorResponse BSEBadRequest - J.Success BadgeServiceRequest {version, purchaseKey, request} - | not (version `isCompatible` supportedBadgeServiceVRange) -> pure $ errorResponse BSEUnsupportedVersion - | purchaseKey /= sigKey -> pure $ errorResponse BSEBadRequest +storeServiceResponse :: BadgeIssuerKey -> StoreVerifier -> PurchaseChecks -> ChatController -> Maybe (TQueue GroupEvent) -> Maybe C.PublicKeyEd25519 -> J.Object -> IO StoreServiceResponse +storeServiceResponse key verifier checks cc trackerQ_ sigKey reqData = case J.fromJSON (J.Object reqData) of + J.Error _ -> pure $ errorResponse STEBadRequest + J.Success StoreServiceRequest {version, purchaseKey, request} + | not (version `isCompatible` supportedStoreServiceVRange) -> pure $ errorResponse STEUnsupportedVersion + | purchaseKey /= sigKey -> pure $ errorResponse STEBadRequest | otherwise -> logInfo ("badge request: " <> commandName request) >> case request of - BSCRedeemBadgeCode {masterKey, code} -> case purchaseKey of + STCRedeemBadgeCode {masterKey, code} -> case purchaseKey of Just k -> redeemCode key cc trackerQ_ k masterKey code - Nothing -> pure $ errorResponse BSEBadRequest - BSCPurchaseBadge {masterKey, payment, upgrade} + Nothing -> pure $ errorResponse STEBadRequest + STCPurchaseBadge {masterKey, payment, upgrade} | Just receipt_ <- toStoreReceipt verifier payment -> case (purchaseKey, upgrade) of (Just k, Nothing) -> either storeRefusalResponse (purchaseWithReceipt key cc verifier checks RUPurchase k masterKey) receipt_ -- store upgrades are not built, and ignoring one would credit its months at the discounted price - (Just _, Just _) -> pure $ errorResponse BSEBadRequest - (Nothing, _) -> pure $ errorResponse BSEBadRequest - BSCIssueBadge {balance} -> case purchaseKey of + (Just _, Just _) -> pure $ errorResponse STEBadRequest + (Nothing, _) -> pure $ errorResponse STEBadRequest + STCIssueBadge {balance} -> case purchaseKey of Just k -> issueBadgeCmd key cc verifier k Nothing balance - Nothing -> pure $ errorResponse BSEBadRequest + Nothing -> pure $ errorResponse STEBadRequest -- only an App Store subscription changes tier on the same transaction; Play gives a change a new token - BSCUpgradeBadgeSubscription {payment = payment@SPApple {}, balance} + STCUpgradeBadgeSubscription {payment = payment@SPApple {}, balance} | Just k <- purchaseKey, Just receipt_ <- toStoreReceipt verifier payment -> either storeRefusalResponse (upgradeSubscriptionCmd key cc verifier k balance) receipt_ - BSCUpgradeBadgeSubscription {} -> pure $ errorResponse BSEBadRequest - BSCTransferBadge {masterKey, payment} + STCUpgradeBadgeSubscription {} -> pure $ errorResponse STEBadRequest + STCTransferBadge {masterKey, payment} | Just k <- purchaseKey, Just receipt_ <- toStoreReceipt verifier payment -> either storeRefusalResponse (purchaseWithReceipt key cc verifier checks (RUTransfer $ presentedTransaction payment) k masterKey) receipt_ - BSCTransferBadge {} -> pure $ errorResponse BSEBadRequest + STCTransferBadge {} -> pure $ errorResponse STEBadRequest -- Every command but redeemBadgeCode and purchaseBadge from a store needs a key the service already knows; those two create the purchase, so their key is unknown on a first purchase. _ -> case purchaseKey of - Nothing -> pure $ errorResponse BSEUnsupportedVersion + Nothing -> pure $ errorResponse STEUnsupportedVersion Just k -> withDB' "purchaseKeyExists" cc (`purchaseKeyExists` k) >>= \case - Right True -> pure $ errorResponse BSEUnsupportedVersion - Right False -> pure $ errorResponse BSEUnknownPurchaseKey - Left _ -> pure $ errorResponse BSEInternal + Right True -> pure $ errorResponse STEUnsupportedVersion + Right False -> pure $ errorResponse STEUnknownPurchaseKey + Left _ -> pure $ errorResponse STEInternal badgeNow :: ChatController -> IO UTCTime badgeNow ChatController {config = ChatConfig {badgeCurrentTime}} = badgeCurrentTime @@ -476,18 +476,18 @@ credentialForEntry BadgeIssuerKey {keyIdx, secretKey} masterKey e@StatementEntry issuanceAfter :: StatementEntry -> (StatementEntry, BadgeCredential) -> (StatementEntry, StatementEntry, BadgeCredential) issuanceAfter previous (issued, credential) = (previous, issued, credential) -credentialResponse :: Maybe BadgeCredential -> Maybe T.Text -> Maybe SubscriptionState -> [StatementEntry] -> BadgeServiceResponse +credentialResponse :: Maybe BadgeCredential -> Maybe T.Text -> Maybe SubscriptionState -> [StatementEntry] -> StoreServiceResponse credentialResponse credential previousEntryId subscription entries = - BSPBadgeCredential {credential, receipt = Nothing, statement = BadgeStatement {entries, previousEntryId}, subscription} + STPBadgeCredential {credential, receipt = Nothing, statement = BadgeStatement {entries, previousEntryId}, subscription} -- | Nothing is written until the credential is signed, so a signing failure leaves the code unspent. -redeemCode :: BadgeIssuerKey -> ChatController -> Maybe (TQueue GroupEvent) -> C.PublicKeyEd25519 -> BadgeMasterKey -> T.Text -> IO BadgeServiceResponse +redeemCode :: BadgeIssuerKey -> ChatController -> Maybe (TQueue GroupEvent) -> C.PublicKeyEd25519 -> BadgeMasterKey -> T.Text -> IO StoreServiceResponse redeemCode key cc trackerQ_ purchaseKey masterKey codeText = case parseBadgeCode codeText of - Nothing -> pure $ errorResponse BSECodeInvalid + Nothing -> pure $ errorResponse STECodeInvalid Just code -> do now <- badgeNow cc withDB "getBadgeCode" cc (readCode now code) >>= \case - Left _ -> pure $ errorResponse BSEInternal + Left _ -> pure $ errorResponse STEInternal Right (Left resp) -> pure resp Right (Right IssuedCode {badgeCodeId, badgeType, months, redeemLimit}) -> signFirstMonth key cc masterKey badgeType months SCCode now >>= \case @@ -499,32 +499,32 @@ redeemCode key cc trackerQ_ purchaseKey masterKey codeText = case parseBadgeCode Nothing -> readCode now code db >>= \case Left resp -> pure (resp, False) - Right _ -> logError "badge service: redeeming a code failed, but the code has uses left and is not revoked" $> (errorResponse BSEInternal, False) + Right _ -> logError "store service: redeeming a code failed, but the code has uses left and is not revoked" $> (errorResponse STEInternal, False) Just purchaseId -> liftIO $ (,True) <$> firstMonthResponse db purchaseId Nothing Nothing firstMonth - let (resp, claimed) = fromRight (errorResponse BSEInternal, False) r + let (resp, claimed) = fromRight (errorResponse STEInternal, False) r when (claimed && hasTracker redeemLimit) $ refreshTracker cc trackerQ_ badgeCodeId code pure resp where readCode now code db = liftIO $ getBadgeCode db (badgeCodeHash code) >>= \case - Nothing -> pure $ Left $ errorResponse BSECodeInvalid + Nothing -> pure $ Left $ errorResponse STECodeInvalid Just c@IssuedCode {badgeCodeId, revokedAt, paymentStatus, expiresAt, redeemLimit, redeemCount} -> getCodePurchaseForKey db badgeCodeId purchaseKey >>= \case -- A key that already redeemed gets its credential back without a use, even if the code has since -- expired or been revoked: a client whose reply was lost retries, and would otherwise lose the badge. KeyRedeemed KeyPurchase {badgePurchaseId, credential} -> - maybe (Left $ errorResponse BSEInternal) (Left . credentialResponse (Just credential) Nothing Nothing) + maybe (Left $ errorResponse STEInternal) (Left . credentialResponse (Just credential) Nothing Nothing) <$> getLedgerEntries db badgePurchaseId 0 -- code_used would make the client drop its keys, so the holder could never get the badge back. KeyRedeemedUnreadable -> - logError "badge service: a redeemed code's credential is missing or unreadable" $> Left (errorResponse BSEInternal) + logError "store service: a redeemed code's credential is missing or unreadable" $> Left (errorResponse STEInternal) KeyUnredeemed -- Revoked is checked first, so it answers as if the code never existed. - | Just _ <- revokedAt -> pure $ Left $ errorResponse BSECodeInvalid + | Just _ <- revokedAt -> pure $ Left $ errorResponse STECodeInvalid -- Redeeming an unpaid code would issue a free badge, so unpaid is refused. - | CPSUnpaid <- paymentStatus -> pure $ Left $ errorResponse BSEPaymentPending - | redeemCount >= redeemLimit -> pure $ Left $ errorResponse BSECodeUsed - | maybe False (now >=) expiresAt -> pure $ Left $ errorResponse BSECodeExpired + | CPSUnpaid <- paymentStatus -> pure $ Left $ errorResponse STEPaymentPending + | redeemCount >= redeemLimit -> pure $ Left $ errorResponse STECodeUsed + | maybe False (now >=) expiresAt -> pure $ Left $ errorResponse STECodeExpired | otherwise -> pure $ Right c -- | What a store receipt is presented for. A transfer carries the Apple transaction the device presented, @@ -538,15 +538,15 @@ presentedTransaction = \case -- | Every refusal is answered before anything is written, so it leaves the receipt unclaimed; and -- nothing is written until the credential is signed. -purchaseWithReceipt :: BadgeIssuerKey -> ChatController -> StoreVerifier -> PurchaseChecks -> ReceiptUse -> C.PublicKeyEd25519 -> BadgeMasterKey -> StoreReceipt -> IO BadgeServiceResponse +purchaseWithReceipt :: BadgeIssuerKey -> ChatController -> StoreVerifier -> PurchaseChecks -> ReceiptUse -> C.PublicKeyEd25519 -> BadgeMasterKey -> StoreReceipt -> IO StoreServiceResponse purchaseWithReceipt key cc verifier checks use purchaseKey masterKey StoreReceipt {txRef = StoreTransactionRef {provider, transactionRef = providerRef}, receiptProductId, subscriptionRef, verifyReceipt, acknowledgeReceipt, acknowledgeSubscription} = withDB' "getStorePayment" cc (\db -> (,) <$> getStorePaymentCredit db provider providerRef <*> keyHoldsPurchase db) >>= \case - Left _ -> pure $ errorResponse BSEInternal + Left _ -> pure $ errorResponse STEInternal Right (credit, keyHeld) -- only the key it credited can ask, and it is told only what it was given, so the store is not asked | creditedBy credit -> answerCredit credit -- a payment moves only to a key with no purchase, so one transferOut alone names the purchase holding it - | keyHeld -> pure $ errorResponse BSEBadRequest + | keyHeld -> pure $ errorResponse STEBadRequest -- a Play subscription is verified by asking about the subscription itself | Just StoreSubscription <- storeProduct provider =<< receiptProductId -> purchaseSubscription receiptProductId credit | otherwise -> @@ -577,10 +577,10 @@ purchaseWithReceipt key cc verifier checks use purchaseKey masterKey StoreReceip answerCredit credit = withDB' "answerStoreCredit" cc (\db -> creditedResponse db purchaseKey credit) <&> \case Right (Left resp) -> resp - _ -> errorResponse BSEInternal + _ -> errorResponse STEInternal -- the product is read only for a receipt not yet credited, so retiring it leaves its replays answered newPurchase tx@VerifiedStoreTransaction {productId, paid, testPurchase} = case storeProduct provider productId of - Nothing -> pure $ errorResponse BSEProductUnavailable + Nothing -> pure $ errorResponse STEProductUnavailable -- an Apple subscription, whose JWS was verified offline Just StoreSubscription -> purchaseSubscription (Just productId) Uncredited Just StoreOneTime {badgeType, months} -> do @@ -597,10 +597,10 @@ purchaseWithReceipt key cc verifier checks use purchaseKey masterKey StoreReceip purchaseSubscription product_ credit = do now <- badgeNow cc atomically (subscriptionAsk now) >>= \case - ClaimHeld remaining -> pure BSPError {code = BSEPaymentPending, message = Nothing, retryAfter = Just (ceiling remaining)} + ClaimHeld remaining -> pure STPError {code = STEPaymentPending, message = Nothing, retryAfter = Just (ceiling remaining)} NoPlayRead wait -> do logWarn "Play subscription read refused: the purchase path's reads for this minute are used" - pure BSPError {code = BSERateLimited, message = Nothing, retryAfter = Just (ceiling wait)} + pure STPError {code = STERateLimited, message = Nothing, retryAfter = Just (ceiling wait)} AskStore -> checkStoreSubscription verifier subscriptionRef product_ >>= \case -- no store was asked, so the claim is not held off @@ -645,23 +645,23 @@ purchaseWithReceipt key cc verifier checks use purchaseKey masterKey StoreReceip -- an older transaction stops moving the subscription once the store charges again, so a leaked receipt lapses | SubscriptionApple _ <- subscriptionRef, presented /= ((\StoreCharge {chargeRef} -> chargeRef) <$> latestCharge) = - pure $ errorResponse BSEPaymentPending + pure $ errorResponse STEPaymentPending | otherwise = do now <- badgeNow cc withDB' "getMovedPayment" cc (\db -> getPurchaseSubscription db fromPurchaseId >>= mapM (movedPayment db)) >>= \case Right (Just (paymentId, movedFromExpiry_, Just fromTip)) -- A store receipt proves control of the store account but is no one-time secret, so this is the only bound on moves: -- waiting out the credential of the key the payment last moved from keeps each paid month with at most two keys. - | maybe False (now <) movedFromExpiry_ -> pure $ errorResponse BSETransferLimited + | maybe False (now <) movedFromExpiry_ -> pure $ errorResponse STETransferLimited | otherwise -> case grantableCharge provider now checked >>= fundsMonthNow purchaseKey now Nothing of Left notGranted -> firstChargeNotGranted provider notGranted Right grant -> movePayment now paymentId fromTip grant - _ -> pure $ errorResponse BSEInternal + _ -> pure $ errorResponse STEInternal where movedPayment db PurchaseSubscription {paymentId} = (paymentId,,) <$> getMovedFromExpiry db paymentId <*> getLedgerTip db fromPurchaseId movePayment now paymentId fromTip (charge@StoreCharge {chargeRef, periodStart}, (badgeType, months)) = withDB' "getSubscriptionCharge" cc (\db -> getSubscriptionCharge db paymentId chargeRef) >>= \case - Left _ -> pure $ errorResponse BSEInternal + Left _ -> pure $ errorResponse STEInternal Right recorded -> do chargeId <- maybe (randomId cc) (pure . fst) recorded entryIds <- (,,,) <$> randomId cc <*> randomId cc <*> randomId cc <*> randomId cc @@ -681,8 +681,8 @@ purchaseWithReceipt key cc verifier checks use purchaseKey masterKey StoreReceip Just <$> firstMonthResponse db purchaseId Nothing (Just subscriptionState) firstMonth case r of Right (Just resp) -> logInfo "store subscription moved to another key" $> resp - Right Nothing -> logError "badge service: a subscription moved, or its ledger changed, while its transfer was signed" $> errorResponse BSEInternal - Left _ -> pure $ errorResponse BSEInternal + Right Nothing -> logError "store service: a subscription moved, or its ledger changed, while its transfer was signed" $> errorResponse STEInternal + Left _ -> pure $ errorResponse STEInternal providerToken = case subscriptionRef of SubscriptionGoogle token -> Just token SubscriptionApple _ -> Nothing @@ -698,9 +698,9 @@ purchaseWithReceipt key cc verifier checks use purchaseKey masterKey StoreReceip Nothing -> liftIO (getStorePaymentCredit db provider providerRef >>= creditedResponse db purchaseKey) >>= \case Left resp -> pure resp - Right () -> logError "badge service: a store payment exists but funds no purchase" $> errorResponse BSEInternal + Right () -> logError "store service: a store payment exists but funds no purchase" $> errorResponse STEInternal Just purchaseId -> liftIO $ writeCredit db purchaseId paymentId - pure $ fromRight (errorResponse BSEInternal) r + pure $ fromRight (errorResponse STEInternal) r -- | Why a store charge grants nothing. data NotGranted @@ -749,38 +749,38 @@ coverageEnded db paymentId SubscriptionCheck {subscriptionState, latestCharge} | otherwise = pure False -- | No payment row exists yet to stamp, so a first purchase's checks are bounded by the purchase checks. -firstChargeNotGranted :: PaymentProvider -> NotGranted -> IO BadgeServiceResponse +firstChargeNotGranted :: PaymentProvider -> NotGranted -> IO StoreServiceResponse firstChargeNotGranted provider = \case NGMalformedPeriod -> storeRefusalResponse $ SRVerifierFailed "a charge whose period does not end after its start" -- Play issues a new token when an ended subscription is bought again, so this one can never be credited NGEnded | PPGoogle <- provider -> storeRefusalResponse $ SRInvalid "the subscription ended" NGNotStarted -> storeRefusalResponse SRPending -- a later charge, or an Apple resubscription under the same original id, may yet be credited from this receipt - reason -> logInfo ("store subscription not credited yet: " <> tshow reason) $> BSPError {code = BSEPaymentPending, message = Nothing, retryAfter = Just 86400} + reason -> logInfo ("store subscription not credited yet: " <> tshow reason) $> STPError {code = STEPaymentPending, message = Nothing, retryAfter = Just 86400} -- | What each request was answered, to pair with its command in a log. No payload: a credential, -- an invoice and a statement are the client's, and an error's message can quote what it refused. -responseName :: BadgeServiceResponse -> T.Text +responseName :: StoreServiceResponse -> T.Text responseName = \case - BSPBadgeCatalog {} -> "catalog" - BSPBadgeInvoice {} -> "invoice" - BSPBadgeCredential {credential = Just _, subscription} -> + STPBadgeCatalog {} -> "catalog" + STPBadgeInvoice {} -> "invoice" + STPBadgeCredential {credential = Just _, subscription} -> "badge issued" <> maybe "" (\s -> ", subscription " <> tshow s) subscription - BSPBadgeCredential {credential = Nothing} -> "no month to issue" - BSPError {code} -> "error " <> tshow code + STPBadgeCredential {credential = Nothing} -> "no month to issue" + STPError {code} -> "error " <> tshow code -- | The command each request ran, so a log can be followed without the request ids. No payload: -- a payment holds a store receipt, and an upgrade a receipt code. -commandName :: BadgeServiceCommand -> T.Text +commandName :: StoreServiceCommand -> T.Text commandName = \case - BSCGetBadgeCatalog -> "getBadgeCatalog" - BSCGetBadgeInvoice {} -> "getBadgeInvoice" - BSCRedeemBadgeCode {} -> "redeemBadgeCode" - BSCPurchaseBadge {payment} -> "purchaseBadge " <> paymentName payment - BSCUpgradeBadgeSubscription {payment} -> "upgradeBadgeSubscription " <> paymentName payment - BSCTransferBadge {payment} -> "transferBadge " <> paymentName payment - BSCIssueBadge {} -> "issueBadge" - BSCPauseBadge -> "pauseBadge" + STCGetBadgeCatalog -> "getBadgeCatalog" + STCGetBadgeInvoice {} -> "getBadgeInvoice" + STCRedeemBadgeCode {} -> "redeemBadgeCode" + STCPurchaseBadge {payment} -> "purchaseBadge " <> paymentName payment + STCUpgradeBadgeSubscription {payment} -> "upgradeBadgeSubscription " <> paymentName payment + STCTransferBadge {payment} -> "transferBadge " <> paymentName payment + STCIssueBadge {} -> "issueBadge" + STCPauseBadge -> "pauseBadge" where paymentName = \case SPApple {} -> "(App Store)" @@ -790,28 +790,28 @@ commandName = \case -- | A forged receipt and a refunded one are both receipt_invalid, so the client learns nothing a -- forger could iterate on. A test purchase is named, since the device that made it already knows. -storeRefusalResponse :: StoreRefusal -> IO BadgeServiceResponse +storeRefusalResponse :: StoreRefusal -> IO StoreServiceResponse storeRefusalResponse = \case -- warn, not info: every one of these ends a purchase for good, and one of them (a store that no longer -- knows a subscription it once sold) can do that to a purchase the user really paid for - SRInvalid reason -> logWarn ("store receipt refused for good: " <> reason) $> errorResponse BSEReceiptInvalid - SRTestPurchase -> logInfo "store receipt refused: test purchase" $> errorResponse BSETestPurchase - SRPending -> pure $ errorResponse BSEPaymentPending - SRUnreachable reason -> logWarn ("store unreachable: " <> reason) $> errorResponse BSEProviderUnavailable - SRVerifierFailed reason -> logError ("store receipt not verified: " <> reason) $> errorResponse BSEInternal - SRNotConfigured -> logWarn "store receipt refused: no verifier for this store is configured" $> errorResponse BSEProviderNotConfigured + SRInvalid reason -> logWarn ("store receipt refused for good: " <> reason) $> errorResponse STEReceiptInvalid + SRTestPurchase -> logInfo "store receipt refused: test purchase" $> errorResponse STETestPurchase + SRPending -> pure $ errorResponse STEPaymentPending + SRUnreachable reason -> logWarn ("store unreachable: " <> reason) $> errorResponse STEProviderUnavailable + SRVerifierFailed reason -> logError ("store receipt not verified: " <> reason) $> errorResponse STEInternal + SRNotConfigured -> logWarn "store receipt refused: no verifier for this store is configured" $> errorResponse STEProviderNotConfigured -creditedResponse :: DB.Connection -> C.PublicKeyEd25519 -> FundingCredit -> IO (Either BadgeServiceResponse ()) +creditedResponse :: DB.Connection -> C.PublicKeyEd25519 -> FundingCredit -> IO (Either StoreServiceResponse ()) creditedResponse db purchaseKey = \case Uncredited -> pure $ Right () - CreditedUnreadable -> pure $ Left $ errorResponse BSEInternal + CreditedUnreadable -> pure $ Left $ errorResponse STEInternal Credited CreditedPurchase {purchaseKey = k, badgePurchaseId, credential, subscription} - | k /= purchaseKey -> pure $ Left $ errorResponse BSEReceiptUsed + | k /= purchaseKey -> pure $ Left $ errorResponse STEReceiptUsed | otherwise -> - maybe (Left $ errorResponse BSEInternal) (Left . credentialResponse (Just credential) Nothing subscription) + maybe (Left $ errorResponse STEInternal) (Left . credentialResponse (Just credential) Nothing subscription) <$> getLedgerEntries db badgePurchaseId 0 -signFirstMonth :: BadgeIssuerKey -> ChatController -> BadgeMasterKey -> BadgeType -> Int -> StatementCreditType -> UTCTime -> IO (Either BadgeServiceResponse ([StatementEntry], (StatementEntry, StatementEntry, BadgeCredential))) +signFirstMonth :: BadgeIssuerKey -> ChatController -> BadgeMasterKey -> BadgeType -> Int -> StatementCreditType -> UTCTime -> IO (Either StoreServiceResponse ([StatementEntry], (StatementEntry, StatementEntry, BadgeCredential))) signFirstMonth key cc masterKey badgeType months credit now = do grantUuid <- randomId cc -- TODO [badges] a top-up grants onto an existing ledger, and must lapse before it or the @@ -820,22 +820,22 @@ signFirstMonth key cc masterKey badgeType months credit now = do signMonthAfter key cc masterKey now seed [grantEntry now grantUuid badgeType months credit seed] -- | The rows that fund a month, after the entry they follow, with that month issued at now and signed. -signMonthAfter :: BadgeIssuerKey -> ChatController -> BadgeMasterKey -> UTCTime -> StatementEntry -> [StatementEntry] -> IO (Either BadgeServiceResponse ([StatementEntry], (StatementEntry, StatementEntry, BadgeCredential))) +signMonthAfter :: BadgeIssuerKey -> ChatController -> BadgeMasterKey -> UTCTime -> StatementEntry -> [StatementEntry] -> IO (Either StoreServiceResponse ([StatementEntry], (StatementEntry, StatementEntry, BadgeCredential))) signMonthAfter key cc masterKey now previous rows = do issueUuid <- randomId cc let funded = last (previous : rows) case issueEntry now issueUuid funded of - Nothing -> logError "badge service: the rows written fund no month to issue" $> Left (errorResponse BSEInternal) + Nothing -> logError "store service: the rows written fund no month to issue" $> Left (errorResponse STEInternal) Just issued -> credentialForEntry key masterKey issued >>= \case - Left e -> logError ("badge service signing failed: " <> T.pack e) $> Left (errorResponse BSEInternal) + Left e -> logError ("store service signing failed: " <> T.pack e) $> Left (errorResponse STEInternal) Right signed -> pure $ Right (rows, issuanceAfter funded signed) -firstMonthResponse :: DB.Connection -> Int64 -> Maybe T.Text -> Maybe SubscriptionState -> ([StatementEntry], (StatementEntry, StatementEntry, BadgeCredential)) -> IO BadgeServiceResponse +firstMonthResponse :: DB.Connection -> Int64 -> Maybe T.Text -> Maybe SubscriptionState -> ([StatementEntry], (StatementEntry, StatementEntry, BadgeCredential)) -> IO StoreServiceResponse firstMonthResponse db purchaseId creditPaymentId_ subscription (rows, issuance@(_, _, credential)) = do appendLedgerPlan db purchaseId creditPaymentId_ rows $ Just issuance entries_ <- getLedgerEntries db purchaseId 0 - pure $ maybe (errorResponse BSEInternal) (credentialResponse (Just credential) Nothing subscription) entries_ + pure $ maybe (errorResponse STEInternal) (credentialResponse (Just credential) Nothing subscription) entries_ -- | The subscription a device's transaction names, its product and that product's tier: what an upgrade waits for, never what it grants. data SubscriptionUpgrade = SubscriptionUpgrade @@ -845,31 +845,31 @@ data SubscriptionUpgrade = SubscriptionUpgrade } -- | Refused before the store is asked: a transaction that does not verify, or that is of no subscription product. -upgradeSubscriptionCmd :: BadgeIssuerKey -> ChatController -> StoreVerifier -> C.PublicKeyEd25519 -> BadgeBalance -> StoreReceipt -> IO BadgeServiceResponse +upgradeSubscriptionCmd :: BadgeIssuerKey -> ChatController -> StoreVerifier -> C.PublicKeyEd25519 -> BadgeBalance -> StoreReceipt -> IO StoreServiceResponse upgradeSubscriptionCmd key cc verifier purchaseKey balance StoreReceipt {txRef = StoreTransactionRef {provider, transactionRef = claimedRef}, verifyReceipt} = verifyReceipt >>= \case Left refusal -> storeRefusalResponse refusal Right VerifiedStoreTransaction {transactionRef} | transactionRef /= claimedRef -> storeRefusalResponse $ SRVerifierFailed "verified a transaction other than the one claimed" Right VerifiedStoreTransaction {productId} -> case storePlan provider productId of - Nothing -> pure $ errorResponse BSEBadRequest + Nothing -> pure $ errorResponse STEBadRequest Just (tier, _) -> issueBadgeCmd key cc verifier purchaseKey (Just SubscriptionUpgrade {upgradeRef = claimedRef, upgradeProductId = productId, upgradeTier = tier}) balance -- | The purchase is reached through the verified signer key and no other way. -issueBadgeCmd :: BadgeIssuerKey -> ChatController -> StoreVerifier -> C.PublicKeyEd25519 -> Maybe SubscriptionUpgrade -> BadgeBalance -> IO BadgeServiceResponse +issueBadgeCmd :: BadgeIssuerKey -> ChatController -> StoreVerifier -> C.PublicKeyEd25519 -> Maybe SubscriptionUpgrade -> BadgeBalance -> IO StoreServiceResponse issueBadgeCmd key cc verifier purchaseKey upgrade_ BadgeBalance {lastEntry} = do now <- badgeNow cc purchase_ <- withDB' "getBadgePurchase" cc (\db -> getIssuePurchase db purchaseKey) case purchase_ of - Left _ -> pure $ errorResponse BSEInternal - Right Nothing -> pure $ errorResponse BSEUnknownPurchaseKey + Left _ -> pure $ errorResponse STEInternal + Right Nothing -> pure $ errorResponse STEUnknownPurchaseKey Right (Just (purchase, Just tip, Just subscription)) | Just upgrade <- upgrade_ -> upgradeSubscription upgrade purchase tip subscription now -- once a subscription's paid coverage has ended, only a new store charge funds another month | paidThrough tip <= now -> renewSubscription Nothing purchase tip subscription now | ChecksAtEveryRequest <- storeChecks verifier -> checkStoreDuringCoverage purchase tip subscription now | balanceStartTs tip <= now -> checkStoreBeforeMonth purchase tip subscription now - Right (Just _) | isJust upgrade_ -> pure $ errorResponse BSEBadRequest + Right (Just _) | isJust upgrade_ -> pure $ errorResponse STEBadRequest Right (Just (ServicePurchase {badgePurchaseId}, Just StatementEntry {entryType = SEDebit SDTransferOut {}}, Nothing)) -> answered "answerMovedOut" $ \db -> withoutCredential <$> issueResponse db badgePurchaseId now (Just SSEnded) Right (Just (purchase, tip, subscription_)) -> issueDue purchase tip ((\PurchaseSubscription {storedState} -> storedState) <$> subscription_) now @@ -883,7 +883,7 @@ issueBadgeCmd key cc verifier purchaseKey upgrade_ BadgeBalance {lastEntry} = do Nothing -> writeIssued badgePurchaseId tip (maybeToList lapsed) now Nothing state_ Just e -> credentialForEntry key masterKey e >>= \case - Left err -> logError ("badge service signing failed: " <> T.pack err) $> errorResponse BSEInternal + Left err -> logError ("store service signing failed: " <> T.pack err) $> errorResponse STEInternal Right signed -> writeIssued badgePurchaseId tip (maybeToList lapsed) now (Just $ issuanceAfter current signed) state_ -- Write only if the tip has not moved, since another request may have advanced it. @@ -892,13 +892,13 @@ issueBadgeCmd key cc verifier purchaseKey upgrade_ BadgeBalance {lastEntry} = do tip' <- lockedLedgerTip db purchaseId t when (fmap entryId tip' == fmap entryId tip) $ appendLedgerPlan db purchaseId Nothing rows issuance_ issueResponse db purchaseId t state_ - pure $ fromRight (errorResponse BSEInternal) r + pure $ fromRight (errorResponse STEInternal) r -- Answered pending until the tier the device saw is granted, so the old tier's credential is never taken for the new one. upgradeSubscription upgrade@SubscriptionUpgrade {upgradeRef, upgradeTier} purchase@ServicePurchase {badgePurchaseId} tip@StatementEntry {balanceBadgeType} subscription@PurchaseSubscription {subscriptionRef, storedState} now - | not ownSubscription = pure $ errorResponse BSEBadRequest + | not ownSubscription = pure $ errorResponse STEBadRequest | balanceBadgeType == upgradeTier = answered "answerUpgraded" $ \db -> issueResponse db badgePurchaseId now (Just storedState) | Just wait <- checkWait now subscription = - pure BSPError {code = BSEPaymentPending, message = Nothing, retryAfter = Just $ ceiling wait} + pure STPError {code = STEPaymentPending, message = Nothing, retryAfter = Just $ ceiling wait} | otherwise = renewSubscription (Just upgrade) purchase tip subscription now where ownSubscription = case subscriptionRef of @@ -910,7 +910,7 @@ issueBadgeCmd key cc verifier purchaseKey upgrade_ BadgeBalance {lastEntry} = do | isNothing upgrading_ && not (subscriptionCheckDue (storeChecks verifier) now tip subscription) = answered "answerStoredSubscription" $ \db -> issueResponse db badgePurchaseId now (Just storedState) | otherwise = withDB' "stampSubscriptionCheck" cc (\db -> stampSubscriptionCheck db paymentId now) >>= \case - Left _ -> pure $ errorResponse BSEInternal + Left _ -> pure $ errorResponse STEInternal Right () -> -- the stores ignore the raise's product; the development mock charges its plan from now on checkStoreSubscription verifier subscriptionRef (upgradeProductId <$> upgrading_) >>= \case @@ -922,7 +922,7 @@ issueBadgeCmd key cc verifier purchaseKey upgrade_ BadgeBalance {lastEntry} = do recordCheck latestCharge subscriptionState Right (charge@StoreCharge {chargeRef, periodStart}, (badgeType, months)) -> withDB' "getSubscriptionCharge" cc (\db -> getSubscriptionCharge db paymentId chargeRef) >>= \case - Left _ -> pure $ errorResponse BSEInternal + Left _ -> pure $ errorResponse STEInternal -- the store still reports the charge the ledger last granted Right (Just (_, True)) -> recordCheck (Just charge) subscriptionState Right recorded -> do @@ -943,8 +943,8 @@ issueBadgeCmd key cc verifier purchaseKey upgrade_ BadgeBalance {lastEntry} = do Just <$> checkedResponse db badgeType subscriptionState case r of Right (Just resp) -> logBanked months $> resp - Right Nothing -> logError "badge service: a subscription's ledger moved while its renewal was signed" $> errorResponse BSEInternal - Left _ -> pure $ errorResponse BSEInternal + Right Nothing -> logError "store service: a subscription's ledger moved while its renewal was signed" $> errorResponse STEInternal + Left _ -> pure $ errorResponse STEInternal where -- the store's answer is kept, and a charge it reports is recorded once, granted or not recordCheck charge_ state = do @@ -954,12 +954,12 @@ issueBadgeCmd key cc verifier purchaseKey upgrade_ BadgeBalance {lastEntry} = do setSubscriptionState db paymentId state now checkedResponse db balanceBadgeType state checkedResponse db ledgerTier state = case upgradeTier <$> upgrading_ of - Just tier | tier /= ledgerTier -> pure $ atLeastCheckInterval $ errorResponse BSEPaymentPending + Just tier | tier /= ledgerTier -> pure $ atLeastCheckInterval $ errorResponse STEPaymentPending _ -> issueResponse db badgePurchaseId now (Just state) -- A charge a dev deployment's store reports while coverage runs is banked with no issuance, and its month issued once coverage reaches it. checkStoreDuringCoverage purchase@ServicePurchase {badgePurchaseId} tip PurchaseSubscription {paymentId, provider, subscriptionRef} now = withDB' "stampSubscriptionCheck" cc (\db -> stampSubscriptionCheck db paymentId now) >>= \case - Left _ -> pure $ errorResponse BSEInternal + Left _ -> pure $ errorResponse STEInternal Right () -> checkStoreSubscription verifier subscriptionRef Nothing >>= \case Left refusal -> atLeastCheckInterval <$> storeRefusalResponse refusal @@ -988,7 +988,7 @@ issueBadgeCmd key cc verifier purchaseKey upgrade_ BadgeBalance {lastEntry} = do else pure Nothing (ended, banked,) <$> getLedgerTip db badgePurchaseId case r of - Left _ -> pure $ errorResponse BSEInternal + Left _ -> pure $ errorResponse STEInternal Right (True, _, _) -> refundRemaining purchase tip paymentId now Right (False, banked, tip_) -> do forM_ banked logBanked @@ -1000,7 +1000,7 @@ issueBadgeCmd key cc verifier purchaseKey upgrade_ BadgeBalance {lastEntry} = do | held = issueDue purchase (Just tip) (Just storedState) now | otherwise = withDB' "stampSubscriptionCheck" cc (\db -> stampSubscriptionCheck db paymentId now) >>= \case - Left _ -> pure $ errorResponse BSEInternal + Left _ -> pure $ errorResponse STEInternal Right () -> checkStoreSubscription verifier subscriptionRef Nothing >>= \case Left refusal -> storeRefusalResponse refusal >> issueDue purchase (Just tip) (Just storedState) now @@ -1013,7 +1013,7 @@ issueBadgeCmd key cc verifier purchaseKey upgrade_ BadgeBalance {lastEntry} = do setSubscriptionState db paymentId (if ended then SSEnded else subscriptionState) now pure ended case r of - Left _ -> pure $ errorResponse BSEInternal + Left _ -> pure $ errorResponse STEInternal Right True -> refundRemaining purchase tip paymentId now Right False -> issueDue purchase (Just tip) (Just subscriptionState) now where @@ -1033,11 +1033,11 @@ issueBadgeCmd key cc verifier purchaseKey upgrade_ BadgeBalance {lastEntry} = do Just . withoutCredential <$> issueResponse db badgePurchaseId now (Just SSEnded) case r of Right (Just resp) -> resp <$ unless (refunded == 0) (logInfo $ "store subscription ended during coverage: " <> tshow (negate refunded) <> " months refunded") - Right Nothing -> logError "badge service: a subscription's ledger moved while its refund was written" $> errorResponse BSEInternal - Left _ -> pure $ errorResponse BSEInternal - answered what action = fromRight (errorResponse BSEInternal) <$> withDB' what cc action + Right Nothing -> logError "store service: a subscription's ledger moved while its refund was written" $> errorResponse STEInternal + Left _ -> pure $ errorResponse STEInternal + answered what action = fromRight (errorResponse STEInternal) <$> withDB' what cc action withoutCredential = \case - BSPBadgeCredential {receipt, statement, subscription} -> BSPBadgeCredential {credential = Nothing, receipt, statement, subscription} + STPBadgeCredential {receipt, statement, subscription} -> STPBadgeCredential {credential = Nothing, receipt, statement, subscription} resp -> resp logBanked months = logInfo $ "store subscription charge banked: " <> tshow months <> " months" -- Only the asserted entry's identity is read, never the months it claims. @@ -1048,7 +1048,7 @@ issueBadgeCmd key cc verifier purchaseKey upgrade_ BadgeBalance {lastEntry} = do -- single opening credit, rather than resending the whole history entries_ <- getLedgerEntries db purchaseId (fromMaybe 0 assertedId) credential_ <- getCurrentIssuance db purchaseId t - pure $ maybe (errorResponse BSEInternal) (credentialResponse credential_ (assertedUuid <$ assertedId) subscription) entries_ + pure $ maybe (errorResponse STEInternal) (credentialResponse credential_ (assertedUuid <$ assertedId) subscription) entries_ getIssuePurchase :: DB.Connection -> C.PublicKeyEd25519 -> IO (Maybe (ServicePurchase, Maybe StatementEntry, Maybe PurchaseSubscription)) getIssuePurchase db purchaseKey = do @@ -1072,9 +1072,9 @@ subscriptionCheckInterval :: NominalDiffTime subscriptionCheckInterval = 3600 -- | The next check waits out the interval whatever the client is told, so its retry waits as long. -atLeastCheckInterval :: BadgeServiceResponse -> BadgeServiceResponse +atLeastCheckInterval :: StoreServiceResponse -> StoreServiceResponse atLeastCheckInterval = \case - BSPError {code, message, retryAfter = Just t} -> BSPError {code, message, retryAfter = Just $ max t $ round subscriptionCheckInterval} + STPError {code, message, retryAfter = Just t} -> STPError {code, message, retryAfter = Just $ max t $ round subscriptionCheckInterval} resp -> resp -- | The subscription claims the purchase path asked a store about, one map per store: the App Store's by original diff --git a/apps/simplex-badge-service/src/BadgeService/Store.hs b/apps/simplex-store-service/src/StoreService/Store.hs similarity index 98% rename from apps/simplex-badge-service/src/BadgeService/Store.hs rename to apps/simplex-store-service/src/StoreService/Store.hs index cec4de216a..feab05accc 100644 --- a/apps/simplex-badge-service/src/BadgeService/Store.hs +++ b/apps/simplex-store-service/src/StoreService/Store.hs @@ -6,7 +6,7 @@ {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeOperators #-} -module BadgeService.Store +module StoreService.Store ( IssuedCode (..), KeyRedemption (..), KeyPurchase (..), @@ -53,8 +53,8 @@ module BadgeService.Store ) where -import BadgeService.Store.Invoices (executeChanging, paymentStatusText) -import BadgeService.StoreReceipts (StoreCharge (..), SubscriptionRef (..)) +import StoreService.Store.Invoices (executeChanging, paymentStatusText) +import StoreService.StoreReceipts (StoreCharge (..), SubscriptionRef (..)) import qualified Data.Aeson as J import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Lazy.Char8 as LB @@ -64,7 +64,7 @@ import Data.Text (Text) import Data.Time.Clock (UTCTime) import Simplex.Chat.Badges (BadgeCredential, BadgeMasterKey (..), BadgeType) import Simplex.Chat.Badges.Ledger -import Simplex.Chat.Badges.Service (StatementCreditType (..), StatementDebitType (..), StatementEntry (..), StatementEntryType (..), SubscriptionState) +import Simplex.Chat.StoreService (StatementCreditType (..), StatementDebitType (..), StatementEntry (..), StatementEntryType (..), SubscriptionState) import Simplex.Chat.Badges.Types (BadgeCodePaymentStatus, BadgePurchaseStatus (..)) import Simplex.Chat.PaymentService.Types (CurrencyAmount (..), InvoiceId (..), PaymentProvider (..), PaymentStatus (..)) import Simplex.Chat.Store.Shared (insertedRowId) diff --git a/apps/simplex-badge-service/src/BadgeService/Store/Invoices.hs b/apps/simplex-store-service/src/StoreService/Store/Invoices.hs similarity index 99% rename from apps/simplex-badge-service/src/BadgeService/Store/Invoices.hs rename to apps/simplex-store-service/src/StoreService/Store/Invoices.hs index 57f9341308..7b12b2dfe8 100644 --- a/apps/simplex-badge-service/src/BadgeService/Store/Invoices.hs +++ b/apps/simplex-store-service/src/StoreService/Store/Invoices.hs @@ -5,7 +5,7 @@ {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeOperators #-} -module BadgeService.Store.Invoices +module StoreService.Store.Invoices ( InvoiceRow (..), InvoicePayment (..), paymentHolds, @@ -52,7 +52,7 @@ import Data.Time.Clock (UTCTime) import Data.Time.Clock.POSIX (posixSecondsToUTCTime, utcTimeToPOSIXSeconds) import Data.Word (Word8, Word32) import Simplex.Chat.Badges (BadgeType (..)) -import Simplex.Chat.Badges.Service (BadgePrice (..), BadgeOffer (..)) +import Simplex.Chat.StoreService (BadgePrice (..), BadgeOffer (..)) import Simplex.Chat.Badges.Types (BadgeCodePaymentStatus (..), BadgeItemStatus (..), BadgeOfferId (..), BadgePriceId (..), OfferDiscount (..)) import Simplex.Chat.Store.Shared (insertedRowId) import Simplex.Chat.PaymentService.Types (CardProvider (..), CryptoCurrency (..), CurrencyAmount (..), InvoiceId (..), InvoiceStatus (..), PaymentProvider (..), PaymentStatus (..), ServicePaymentDestination (..)) @@ -62,12 +62,12 @@ import Simplex.Messaging.Encoding.String (textDecode, textEncode) import Simplex.Messaging.Util (safeDecodeUtf8, tshow) #if defined(dbPostgres) -import BadgeService.Store.Postgres.Migrations (servicePrefix, withPrefix) +import StoreService.Store.Postgres.Migrations (servicePrefix, withPrefix) import Database.PostgreSQL.Simple (Only (..), Query, ToRow, (:.) (..)) import qualified Database.PostgreSQL.Simple as PSQL import Database.PostgreSQL.Simple.Errors (ConstraintViolation (..), constraintViolation) #else -import BadgeService.Store.SQLite.Migrations (servicePrefix, withPrefix) +import StoreService.Store.SQLite.Migrations (servicePrefix, withPrefix) import Database.SQLite.Simple (Only (..), Query, ToRow, (:.) (..)) import qualified Database.SQLite.Simple as SQL #endif diff --git a/apps/simplex-badge-service/src/BadgeService/Store/Migrate.hs b/apps/simplex-store-service/src/StoreService/Store/Migrate.hs similarity index 67% rename from apps/simplex-badge-service/src/BadgeService/Store/Migrate.hs rename to apps/simplex-store-service/src/StoreService/Store/Migrate.hs index 506043c262..d5dfc9dac2 100644 --- a/apps/simplex-badge-service/src/BadgeService/Store/Migrate.hs +++ b/apps/simplex-store-service/src/StoreService/Store/Migrate.hs @@ -3,12 +3,12 @@ {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} -module BadgeService.Store.Migrate - ( runBadgeServiceMigrations, +module StoreService.Store.Migrate + ( runStoreServiceMigrations, ) where -import BadgeService.Options +import StoreService.Options import Simplex.Chat.Controller (ChatConfig (..)) import Simplex.Chat.Options (CoreChatOpts (..)) import Simplex.Chat.Options.DB @@ -18,22 +18,22 @@ import Simplex.Messaging.Agent.Store.Shared (MigrationConfig (..), MigrationConf import System.Exit (exitFailure) #if defined(dbPostgres) -import BadgeService.Store.Postgres.Migrations +import StoreService.Store.Postgres.Migrations #else -import BadgeService.Store.SQLite.Migrations +import StoreService.Store.SQLite.Migrations #endif -runBadgeServiceMigrations :: BadgeServiceOpts -> ChatConfig -> DBStore -> IO () -runBadgeServiceMigrations opts ChatConfig {confirmMigrations} chatStore = +runStoreServiceMigrations :: StoreServiceOpts -> ChatConfig -> DBStore -> IO () +runStoreServiceMigrations opts ChatConfig {confirmMigrations} chatStore = migrateDBSchema chatStore (toDBOpts dbOptions chatSuffix False []) (Just "sx_badge_service_migrations") - badgeServiceSchemaMigrations + storeServiceSchemaMigrations MigrationConfig {confirm, backupPath = Nothing} - >>= either (exit . ("badge service migrations " <>) . show) pure + >>= either (exit . ("store service migrations " <>) . show) pure where - BadgeServiceOpts {coreOptions = CoreChatOpts {dbOptions, yesToUpMigrations}} = opts + StoreServiceOpts {coreOptions = CoreChatOpts {dbOptions, yesToUpMigrations}} = opts confirm = if confirmMigrations == MCConsole && yesToUpMigrations then MCYesUp else confirmMigrations exit :: String -> IO a diff --git a/apps/simplex-badge-service/src/BadgeService/Store/Postgres/Migrations.hs b/apps/simplex-store-service/src/StoreService/Store/Postgres/Migrations.hs similarity index 98% rename from apps/simplex-badge-service/src/BadgeService/Store/Postgres/Migrations.hs rename to apps/simplex-store-service/src/StoreService/Store/Postgres/Migrations.hs index b2c3b86002..7a18a807f0 100644 --- a/apps/simplex-badge-service/src/BadgeService/Store/Postgres/Migrations.hs +++ b/apps/simplex-store-service/src/StoreService/Store/Postgres/Migrations.hs @@ -2,7 +2,7 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} -module BadgeService.Store.Postgres.Migrations (badgeServiceSchemaMigrations, servicePrefix, withPrefix) where +module StoreService.Store.Postgres.Migrations (storeServiceSchemaMigrations, servicePrefix, withPrefix) where import Data.List (sortOn) import Data.Text (Text) @@ -10,8 +10,8 @@ import Simplex.Chat.Store.Postgres.Migrations.M20260915_user_badges (badgeSchema import Simplex.Messaging.Agent.Store.Shared (Migration (..)) import Text.RawString.QQ (r) -badgeServiceSchemaMigrations :: [Migration] -badgeServiceSchemaMigrations = sortOn name $ map migration schemaMigrations +storeServiceSchemaMigrations :: [Migration] +storeServiceSchemaMigrations = sortOn name $ map migration schemaMigrations where migration (name, up, down) = Migration {name, up, down} diff --git a/apps/simplex-badge-service/src/BadgeService/Store/SQLite/Migrations.hs b/apps/simplex-store-service/src/StoreService/Store/SQLite/Migrations.hs similarity index 98% rename from apps/simplex-badge-service/src/BadgeService/Store/SQLite/Migrations.hs rename to apps/simplex-store-service/src/StoreService/Store/SQLite/Migrations.hs index 7f8659d60d..396429f39e 100644 --- a/apps/simplex-badge-service/src/BadgeService/Store/SQLite/Migrations.hs +++ b/apps/simplex-store-service/src/StoreService/Store/SQLite/Migrations.hs @@ -2,7 +2,7 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} -module BadgeService.Store.SQLite.Migrations (badgeServiceSchemaMigrations, servicePrefix, withPrefix) where +module StoreService.Store.SQLite.Migrations (storeServiceSchemaMigrations, servicePrefix, withPrefix) where import Data.List (sortOn) import Data.Text (Text) @@ -11,8 +11,8 @@ import Database.SQLite.Simple.QQ (sql) import Simplex.Chat.Store.SQLite.Migrations.M20260915_user_badges (badgeSchema, badgeSchemaDown, withPrefix) import Simplex.Messaging.Agent.Store.Shared (Migration (..)) -badgeServiceSchemaMigrations :: [Migration] -badgeServiceSchemaMigrations = sortOn name $ map migration schemaMigrations +storeServiceSchemaMigrations :: [Migration] +storeServiceSchemaMigrations = sortOn name $ map migration schemaMigrations where migration (name, up, down) = Migration {name, up = fromQuery up, down = fromQuery <$> down} diff --git a/apps/simplex-badge-service/src/BadgeService/StoreReceipts.hs b/apps/simplex-store-service/src/StoreService/StoreReceipts.hs similarity index 99% rename from apps/simplex-badge-service/src/BadgeService/StoreReceipts.hs rename to apps/simplex-store-service/src/StoreService/StoreReceipts.hs index 064cc56ecb..1a696f1b55 100644 --- a/apps/simplex-badge-service/src/BadgeService/StoreReceipts.hs +++ b/apps/simplex-store-service/src/StoreService/StoreReceipts.hs @@ -5,7 +5,7 @@ {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} -module BadgeService.StoreReceipts +module StoreService.StoreReceipts ( VerifiedStoreTransaction (..), StoreRefusal (..), StoreVerifier (..), @@ -22,7 +22,7 @@ module BadgeService.StoreReceipts ) where -import BadgeService.Log (logInfo, logWarn) +import StoreService.Log (logInfo, logWarn) import Control.Exception (Exception, catch, evaluate, try) import qualified Data.ByteString.Lazy as LB import Data.Char (isAlphaNum, isAscii, isAsciiLower, isAsciiUpper, isControl, isDigit, isPrint, isSpace) @@ -34,7 +34,7 @@ import qualified Data.Text as T import Data.Time.Clock (UTCTime) import Network.HTTP.Client (HttpException (..), Manager, Request, Response (..), brReadSome, parseRequest, withResponse) import Network.HTTP.Types (Status (..)) -import Simplex.Chat.Badges.Service (SubscriptionState) +import Simplex.Chat.StoreService (SubscriptionState) import Simplex.Chat.PaymentService (ServicePayment (..), appleTransactionRef, googlePurchaseRef) import Simplex.Chat.PaymentService.Types (CurrencyAmount, PaymentProvider (..), StoreTransactionRef (..)) import Simplex.Messaging.Util (catchOwn', tshow) diff --git a/apps/simplex-badge-service/src/BadgeService/StoreReceipts/Apple.hs b/apps/simplex-store-service/src/StoreService/StoreReceipts/Apple.hs similarity index 98% rename from apps/simplex-badge-service/src/BadgeService/StoreReceipts/Apple.hs rename to apps/simplex-store-service/src/StoreService/StoreReceipts/Apple.hs index 1942a984e3..de92113fa2 100644 --- a/apps/simplex-badge-service/src/BadgeService/StoreReceipts/Apple.hs +++ b/apps/simplex-store-service/src/StoreService/StoreReceipts/Apple.hs @@ -4,15 +4,15 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -module BadgeService.StoreReceipts.Apple +module StoreService.StoreReceipts.Apple ( verifyAppleTransaction, appleSubscriptionChecker, readAppleRoot, ) where -import BadgeService.Config (AppleServerApi (..)) -import BadgeService.StoreReceipts (StoreCharge (..), StoreRefusal (..), StoreVerifierFailure (..), SubscriptionCheck (..), VerifiedStoreTransaction (..), storeRequest) +import StoreService.Config (AppleServerApi (..)) +import StoreService.StoreReceipts (StoreCharge (..), StoreRefusal (..), StoreVerifierFailure (..), SubscriptionCheck (..), VerifiedStoreTransaction (..), storeRequest) import Control.Concurrent.STM (TVar, atomically, newTVarIO, readTVarIO, writeTVar) import Control.Exception (IOException, evaluate, throwIO, try) import Control.Monad (guard, unless, when) @@ -48,7 +48,7 @@ import Data.X509.Validation (SignatureFailure (..), SignatureVerification (..), import Network.HTTP.Client (Manager, Request (..)) import Network.HTTP.Client.TLS (newTlsManager) import Network.HTTP.Types (hAuthorization) -import Simplex.Chat.Badges.Service (SubscriptionState (..)) +import Simplex.Chat.StoreService (SubscriptionState (..)) import Simplex.Chat.PaymentService (applePayloadRef) import Simplex.Chat.PaymentService.Types (CurrencyAmount (..)) import Simplex.Messaging.Util (catchOwn', eitherToMaybe, tshow) diff --git a/apps/simplex-badge-service/src/BadgeService/StoreReceipts/Google.hs b/apps/simplex-store-service/src/StoreService/StoreReceipts/Google.hs similarity index 98% rename from apps/simplex-badge-service/src/BadgeService/StoreReceipts/Google.hs rename to apps/simplex-store-service/src/StoreService/StoreReceipts/Google.hs index 19699c9da8..832daa0421 100644 --- a/apps/simplex-badge-service/src/BadgeService/StoreReceipts/Google.hs +++ b/apps/simplex-store-service/src/StoreService/StoreReceipts/Google.hs @@ -5,10 +5,10 @@ {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} -module BadgeService.StoreReceipts.Google (PlayVerifier (..), playStoreVerifier) where +module StoreService.StoreReceipts.Google (PlayVerifier (..), playStoreVerifier) where -import BadgeService.Config (PlayStoreConfig (..)) -import BadgeService.StoreReceipts (StoreCharge (..), StoreRefusal (..), SubscriptionCheck (..), VerifiedStoreTransaction (..), storeRequest) +import StoreService.Config (PlayStoreConfig (..)) +import StoreService.StoreReceipts (StoreCharge (..), StoreRefusal (..), SubscriptionCheck (..), VerifiedStoreTransaction (..), storeRequest) import Control.Concurrent.STM import Control.Exception (IOException, try) import Control.Monad (forM) @@ -36,7 +36,7 @@ import Network.HTTP.Client (Manager, Request (..), RequestBody (..)) import Network.HTTP.Client.TLS (newTlsManager) import Network.HTTP.Types (hAuthorization, hContentType, methodPost, renderSimpleQuery) import Simplex.Chat.Badges.Ledger (addMonths) -import Simplex.Chat.Badges.Service (SubscriptionState (..)) +import Simplex.Chat.StoreService (SubscriptionState (..)) import Simplex.Chat.Badges.StorePlan (playBasePlan) import Simplex.Chat.PaymentService (googlePurchaseRef) import Simplex.Messaging.Util (tshow) diff --git a/apps/simplex-badge-service/src/BadgeService/StoreReceipts/Mock.hs b/apps/simplex-store-service/src/StoreService/StoreReceipts/Mock.hs similarity index 95% rename from apps/simplex-badge-service/src/BadgeService/StoreReceipts/Mock.hs rename to apps/simplex-store-service/src/StoreService/StoreReceipts/Mock.hs index 823af288ea..9cf0e2a49e 100644 --- a/apps/simplex-badge-service/src/BadgeService/StoreReceipts/Mock.hs +++ b/apps/simplex-store-service/src/StoreService/StoreReceipts/Mock.hs @@ -2,10 +2,10 @@ {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} -module BadgeService.StoreReceipts.Mock (newMockStoreVerifier) where +module StoreService.StoreReceipts.Mock (newMockStoreVerifier) where -import BadgeService.Catalog (playMonthlyPlan) -import BadgeService.StoreReceipts +import StoreService.Catalog (playMonthlyPlan) +import StoreService.StoreReceipts import Control.Applicative ((<|>)) import Control.Concurrent.STM (TVar, atomically, modifyTVar', newTVarIO, readTVarIO) import Control.Monad (guard) @@ -18,7 +18,7 @@ import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) import Data.Time.Clock (UTCTime, addUTCTime) import Simplex.Chat.Badges.Ledger (addMonths) -import Simplex.Chat.Badges.Service (SubscriptionState (..)) +import Simplex.Chat.StoreService (SubscriptionState (..)) import Simplex.Chat.Badges.StorePlan (playBasePlan, storePlan) import Simplex.Chat.PaymentService (appleTransactionRef, googlePurchaseRef) import Simplex.Chat.PaymentService.Types (PaymentProvider (..)) diff --git a/apps/simplex-badge-service/src/BadgeService/Waiters.hs b/apps/simplex-store-service/src/StoreService/Waiters.hs similarity index 98% rename from apps/simplex-badge-service/src/BadgeService/Waiters.hs rename to apps/simplex-store-service/src/StoreService/Waiters.hs index d074b28185..aeee8152ca 100644 --- a/apps/simplex-badge-service/src/BadgeService/Waiters.hs +++ b/apps/simplex-store-service/src/StoreService/Waiters.hs @@ -1,6 +1,6 @@ {-# LANGUAGE NamedFieldPuns #-} -module BadgeService.Waiters (Waiters, Seen, newWaiters, publish, publishPayment, awaitStatus, waitingCount, waitingCountSTM) where +module StoreService.Waiters (Waiters, Seen, newWaiters, publish, publishPayment, awaitStatus, waitingCount, waitingCountSTM) where import Control.Concurrent.STM import Control.Exception (bracket) diff --git a/apps/simplex-badge-service/src/BadgeService/Web/Server.hs b/apps/simplex-store-service/src/StoreService/Web/Server.hs similarity index 98% rename from apps/simplex-badge-service/src/BadgeService/Web/Server.hs rename to apps/simplex-store-service/src/StoreService/Web/Server.hs index f3eb512dc0..6b4f75aa71 100644 --- a/apps/simplex-badge-service/src/BadgeService/Web/Server.hs +++ b/apps/simplex-store-service/src/StoreService/Web/Server.hs @@ -3,7 +3,7 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -module BadgeService.Web.Server +module StoreService.Web.Server ( WebEnv (..), Limit (..), Bucket (..), @@ -21,15 +21,15 @@ module BadgeService.Web.Server ) where -import BadgeService.Catalog (PricedOffer (..), priceOffer) -import BadgeService.Config (BTCPayConfig (..), ListenerConfig (..), ServiceConfig (..), SpeedPolicy (..), StripeConfig (..), defaultExpiryMinutes, defaultSessionMinutes) -import BadgeService.Poller (ReadHints, queueReadHint) -import BadgeService.Providers (OrderDraft (..), Provider (..), ProviderError (..), ProviderInvoice (..), WebhookError (..)) -import BadgeService.Store.Invoices (CreateError (..), InvoicePayment (..), InvoiceRow (..), NewInvoice (..), cancelOpenInvoice, codeHashExists, createInvoiceRows, cryptoCurrencyText, getInvoice, getInvoiceByProviderRef, invoiceStatusText, newInvoiceId, paymentHolds, readCatalogRows, textToInvoiceStatus, truncateToSecond) -import BadgeService.Waiters (Seen, Waiters, awaitStatus, publish) +import StoreService.Catalog (PricedOffer (..), priceOffer) +import StoreService.Config (BTCPayConfig (..), ListenerConfig (..), ServiceConfig (..), SpeedPolicy (..), StripeConfig (..), defaultExpiryMinutes, defaultSessionMinutes) +import StoreService.Poller (ReadHints, queueReadHint) +import StoreService.Providers (OrderDraft (..), Provider (..), ProviderError (..), ProviderInvoice (..), WebhookError (..)) +import StoreService.Store.Invoices (CreateError (..), InvoicePayment (..), InvoiceRow (..), NewInvoice (..), cancelOpenInvoice, codeHashExists, createInvoiceRows, cryptoCurrencyText, getInvoice, getInvoiceByProviderRef, invoiceStatusText, newInvoiceId, paymentHolds, readCatalogRows, textToInvoiceStatus, truncateToSecond) +import StoreService.Waiters (Seen, Waiters, awaitStatus, publish) import Control.Concurrent.STM import qualified Control.Exception as E -import BadgeService.Log (logError, logInfo, logWarn) +import StoreService.Log (logError, logInfo, logWarn) import Control.Monad (forM_, when) import Data.Aeson ((.=)) import qualified Data.Aeson as J @@ -336,7 +336,7 @@ exportWebapp lc@ListenerConfig {lStaticDir, lWebappExportDir} stripeCfg = emptyDir out copyTree lStaticDir out prepareShell lc stripeCfg >>= mapM_ (LB.writeFile (out "index.html")) - logInfo ("badge service: exported the webapp to " <> T.pack out) + logInfo ("store service: exported the webapp to " <> T.pack out) -- | Contents only: the directory itself may be a bind or volume mount point that cannot be removed. emptyDir :: FilePath -> IO () @@ -735,7 +735,7 @@ runWebListener env = do warnIfHeaderTrustIsExposed :: ListenerConfig -> IO () warnIfHeaderTrustIsExposed ListenerConfig {lHost, lTrustForwardedFor} = when (lTrustForwardedFor && not (isLoopbackHost lHost)) $ - logWarn ("badge service: trust_forwarded_for is on and the listener binds " <> lHost <> "; every caller can then choose its own rate limit bucket unless a proxy sets the header") + logWarn ("store service: trust_forwarded_for is on and the listener binds " <> lHost <> "; every caller can then choose its own rate limit bucket unless a proxy sets the header") isLoopbackHost :: Text -> Bool isLoopbackHost h = h `elem` ["127.0.0.1", "::1", "localhost"] diff --git a/apps/simplex-badge-service/badge_service.ini.example b/apps/simplex-store-service/store_service.ini.example similarity index 96% rename from apps/simplex-badge-service/badge_service.ini.example rename to apps/simplex-store-service/store_service.ini.example index 5fbce6b7f3..40fcbac4f2 100644 --- a/apps/simplex-badge-service/badge_service.ini.example +++ b/apps/simplex-store-service/store_service.ini.example @@ -3,8 +3,8 @@ ; the long poll's `wait`, `seenPaid` and `seenFull` all travel in it host = 127.0.0.1 port = 8080 -; required: the directory `npm run build` writes in apps/simplex-badge-service/web -static_dir = ./apps/simplex-badge-service/web/dist +; required: the directory `npm run build` writes in apps/simplex-store-service/web +static_dir = ./apps/simplex-store-service/web/dist ; serve the webapp over HTTP. On (default) is the all-in-one deployment. Off is a split deployment ; where a reverse proxy serves the exported folder and this service is only the API and webhooks. serve_webapp = on @@ -53,10 +53,10 @@ idle_seconds = 60 ; Keep the key file readable by this service alone. ;[apple] ;bundle_id = chat.simplex.app -;root_certificates = /etc/simplex-badge-service/AppleRootCA-G3.cer +;root_certificates = /etc/simplex-store-service/AppleRootCA-G3.cer ;api_key_id = 2X9R4HXF34 ;api_issuer_id = 57246542-96fe-1a63-e053-0824d011072a -;api_private_key_file = /etc/simplex-badge-service/AuthKey_2X9R4HXF34.p8 +;api_private_key_file = /etc/simplex-store-service/AuthKey_2X9R4HXF34.p8 ;api_host = https://api.storekit.itunes.apple.com ; verifies Play purchases with the Google Play Developer API. Omit the whole section and the service answers @@ -67,7 +67,7 @@ idle_seconds = 60 ; already acknowledged itself is answered internal until the permission is granted. Keep the file readable by this service alone. ;[google] ;package_name = chat.simplex.app -;service_account_file = /etc/simplex-badge-service/play-service-account.json +;service_account_file = /etc/simplex-store-service/play-service-account.json ; the key this service signs credentials with. index is the index clients verify against, so ; private_key has to be one whose public half already ships in the apps at that index: a fresh diff --git a/apps/simplex-badge-service/test-fixtures/apple/AppleRootCA-G3.cer b/apps/simplex-store-service/test-fixtures/apple/AppleRootCA-G3.cer similarity index 100% rename from apps/simplex-badge-service/test-fixtures/apple/AppleRootCA-G3.cer rename to apps/simplex-store-service/test-fixtures/apple/AppleRootCA-G3.cer diff --git a/apps/simplex-badge-service/test-fixtures/apple/transaction-legend.json b/apps/simplex-store-service/test-fixtures/apple/transaction-legend.json similarity index 100% rename from apps/simplex-badge-service/test-fixtures/apple/transaction-legend.json rename to apps/simplex-store-service/test-fixtures/apple/transaction-legend.json diff --git a/apps/simplex-badge-service/test-fixtures/apple/transaction-sandbox.json b/apps/simplex-store-service/test-fixtures/apple/transaction-sandbox.json similarity index 100% rename from apps/simplex-badge-service/test-fixtures/apple/transaction-sandbox.json rename to apps/simplex-store-service/test-fixtures/apple/transaction-sandbox.json diff --git a/apps/simplex-badge-service/test-fixtures/apple/transaction-supporter.json b/apps/simplex-store-service/test-fixtures/apple/transaction-supporter.json similarity index 100% rename from apps/simplex-badge-service/test-fixtures/apple/transaction-supporter.json rename to apps/simplex-store-service/test-fixtures/apple/transaction-supporter.json diff --git a/apps/simplex-badge-service/test-fixtures/btcpay/invoice-expired.json b/apps/simplex-store-service/test-fixtures/btcpay/invoice-expired.json similarity index 100% rename from apps/simplex-badge-service/test-fixtures/btcpay/invoice-expired.json rename to apps/simplex-store-service/test-fixtures/btcpay/invoice-expired.json diff --git a/apps/simplex-badge-service/test-fixtures/btcpay/invoice-invalid.json b/apps/simplex-store-service/test-fixtures/btcpay/invoice-invalid.json similarity index 100% rename from apps/simplex-badge-service/test-fixtures/btcpay/invoice-invalid.json rename to apps/simplex-store-service/test-fixtures/btcpay/invoice-invalid.json diff --git a/apps/simplex-badge-service/test-fixtures/btcpay/invoice-list-alien-method.json b/apps/simplex-store-service/test-fixtures/btcpay/invoice-list-alien-method.json similarity index 100% rename from apps/simplex-badge-service/test-fixtures/btcpay/invoice-list-alien-method.json rename to apps/simplex-store-service/test-fixtures/btcpay/invoice-list-alien-method.json diff --git a/apps/simplex-badge-service/test-fixtures/btcpay/invoice-list-alien-status.json b/apps/simplex-store-service/test-fixtures/btcpay/invoice-list-alien-status.json similarity index 100% rename from apps/simplex-badge-service/test-fixtures/btcpay/invoice-list-alien-status.json rename to apps/simplex-store-service/test-fixtures/btcpay/invoice-list-alien-status.json diff --git a/apps/simplex-badge-service/test-fixtures/btcpay/invoice-list-no-id.json b/apps/simplex-store-service/test-fixtures/btcpay/invoice-list-no-id.json similarity index 100% rename from apps/simplex-badge-service/test-fixtures/btcpay/invoice-list-no-id.json rename to apps/simplex-store-service/test-fixtures/btcpay/invoice-list-no-id.json diff --git a/apps/simplex-badge-service/test-fixtures/btcpay/invoice-list-no-payment-methods.json b/apps/simplex-store-service/test-fixtures/btcpay/invoice-list-no-payment-methods.json similarity index 100% rename from apps/simplex-badge-service/test-fixtures/btcpay/invoice-list-no-payment-methods.json rename to apps/simplex-store-service/test-fixtures/btcpay/invoice-list-no-payment-methods.json diff --git a/apps/simplex-badge-service/test-fixtures/btcpay/invoice-list.json b/apps/simplex-store-service/test-fixtures/btcpay/invoice-list.json similarity index 100% rename from apps/simplex-badge-service/test-fixtures/btcpay/invoice-list.json rename to apps/simplex-store-service/test-fixtures/btcpay/invoice-list.json diff --git a/apps/simplex-badge-service/test-fixtures/btcpay/invoice-new.json b/apps/simplex-store-service/test-fixtures/btcpay/invoice-new.json similarity index 100% rename from apps/simplex-badge-service/test-fixtures/btcpay/invoice-new.json rename to apps/simplex-store-service/test-fixtures/btcpay/invoice-new.json diff --git a/apps/simplex-badge-service/test-fixtures/btcpay/invoice-processing.json b/apps/simplex-store-service/test-fixtures/btcpay/invoice-processing.json similarity index 100% rename from apps/simplex-badge-service/test-fixtures/btcpay/invoice-processing.json rename to apps/simplex-store-service/test-fixtures/btcpay/invoice-processing.json diff --git a/apps/simplex-badge-service/test-fixtures/btcpay/invoice-settled.json b/apps/simplex-store-service/test-fixtures/btcpay/invoice-settled.json similarity index 100% rename from apps/simplex-badge-service/test-fixtures/btcpay/invoice-settled.json rename to apps/simplex-store-service/test-fixtures/btcpay/invoice-settled.json diff --git a/apps/simplex-badge-service/test-fixtures/btcpay/payment-methods-btc.json b/apps/simplex-store-service/test-fixtures/btcpay/payment-methods-btc.json similarity index 100% rename from apps/simplex-badge-service/test-fixtures/btcpay/payment-methods-btc.json rename to apps/simplex-store-service/test-fixtures/btcpay/payment-methods-btc.json diff --git a/apps/simplex-badge-service/test-fixtures/btcpay/payment-methods-no-amount.json b/apps/simplex-store-service/test-fixtures/btcpay/payment-methods-no-amount.json similarity index 100% rename from apps/simplex-badge-service/test-fixtures/btcpay/payment-methods-no-amount.json rename to apps/simplex-store-service/test-fixtures/btcpay/payment-methods-no-amount.json diff --git a/apps/simplex-badge-service/test-fixtures/btcpay/payment-methods-no-destination.json b/apps/simplex-store-service/test-fixtures/btcpay/payment-methods-no-destination.json similarity index 100% rename from apps/simplex-badge-service/test-fixtures/btcpay/payment-methods-no-destination.json rename to apps/simplex-store-service/test-fixtures/btcpay/payment-methods-no-destination.json diff --git a/apps/simplex-badge-service/test-fixtures/btcpay/payment-methods-xmr.json b/apps/simplex-store-service/test-fixtures/btcpay/payment-methods-xmr.json similarity index 100% rename from apps/simplex-badge-service/test-fixtures/btcpay/payment-methods-xmr.json rename to apps/simplex-store-service/test-fixtures/btcpay/payment-methods-xmr.json diff --git a/apps/simplex-badge-service/test-fixtures/btcpay/store-payment-methods.json b/apps/simplex-store-service/test-fixtures/btcpay/store-payment-methods.json similarity index 100% rename from apps/simplex-badge-service/test-fixtures/btcpay/store-payment-methods.json rename to apps/simplex-store-service/test-fixtures/btcpay/store-payment-methods.json diff --git a/apps/simplex-badge-service/test-fixtures/stripe/intent-canceled.json b/apps/simplex-store-service/test-fixtures/stripe/intent-canceled.json similarity index 100% rename from apps/simplex-badge-service/test-fixtures/stripe/intent-canceled.json rename to apps/simplex-store-service/test-fixtures/stripe/intent-canceled.json diff --git a/apps/simplex-badge-service/test-fixtures/stripe/intent-list-cursor-gap.json b/apps/simplex-store-service/test-fixtures/stripe/intent-list-cursor-gap.json similarity index 100% rename from apps/simplex-badge-service/test-fixtures/stripe/intent-list-cursor-gap.json rename to apps/simplex-store-service/test-fixtures/stripe/intent-list-cursor-gap.json diff --git a/apps/simplex-badge-service/test-fixtures/stripe/intent-list.json b/apps/simplex-store-service/test-fixtures/stripe/intent-list.json similarity index 100% rename from apps/simplex-badge-service/test-fixtures/stripe/intent-list.json rename to apps/simplex-store-service/test-fixtures/stripe/intent-list.json diff --git a/apps/simplex-badge-service/test-fixtures/stripe/intent-open.json b/apps/simplex-store-service/test-fixtures/stripe/intent-open.json similarity index 100% rename from apps/simplex-badge-service/test-fixtures/stripe/intent-open.json rename to apps/simplex-store-service/test-fixtures/stripe/intent-open.json diff --git a/apps/simplex-badge-service/test-fixtures/stripe/intent-succeeded.json b/apps/simplex-store-service/test-fixtures/stripe/intent-succeeded.json similarity index 100% rename from apps/simplex-badge-service/test-fixtures/stripe/intent-succeeded.json rename to apps/simplex-store-service/test-fixtures/stripe/intent-succeeded.json diff --git a/apps/simplex-badge-service/web/.gitignore b/apps/simplex-store-service/web/.gitignore similarity index 100% rename from apps/simplex-badge-service/web/.gitignore rename to apps/simplex-store-service/web/.gitignore diff --git a/apps/simplex-badge-service/web/README.md b/apps/simplex-store-service/web/README.md similarity index 95% rename from apps/simplex-badge-service/web/README.md rename to apps/simplex-store-service/web/README.md index ae2f5b37e5..9f83cad339 100644 --- a/apps/simplex-badge-service/web/README.md +++ b/apps/simplex-store-service/web/README.md @@ -68,23 +68,23 @@ is plain TypeScript, tested directly in Node. ## Running the real service against this build **`mock/server.py` is not the service.** The service is the Haskell -executable `simplex-badge-service`, in `apps/simplex-badge-service/`, and +executable `simplex-store-service`, in `apps/simplex-store-service/`, and `dist/` is the directory its listener serves. Nothing about the page changes between the two — the service matches this build, never the reverse. ``` # 1. build the page. dist/ is the deploy tree: index.html, sw.js, assets// -cd apps/simplex-badge-service/web +cd apps/simplex-store-service/web npm install && npm run build cd ../../.. # 2. configuration, from the committed example. Copy it IN # PLACE, beside the example: that path is the one .gitignore covers, and this # file is about to hold a real api_key and webhook_secret. -cd apps/simplex-badge-service -cp badge_service.ini.example badge_service.ini +cd apps/simplex-store-service +cp store_service.ini.example store_service.ini cd ../.. -# static_dir = ./apps/simplex-badge-service/web/dist <- the build above +# static_dir = ./apps/simplex-store-service/web/dist <- the build above # [btcpay] = a real store's host, api_key, store_id and webhook_secret, # or delete the whole section to disable BTC and XMR (the provider-unavailable screen) # [issuer] = uncomment the section and put a real issuer secret in private_key, @@ -98,28 +98,28 @@ cd ../.. # without a key it could sign a credential with. Put it in the ini's [issuer] # section, or pass --issuer-key-idx and --issuer-secret, which override it. # `simplex-chat badge keygen` prints a pair. -cabal run simplex-badge-service -- \ - --service-config apps/simplex-badge-service/badge_service.ini +cabal run simplex-store-service -- \ + --service-config apps/simplex-store-service/store_service.ini ``` Then open the `[listener]` host and port — `http://127.0.0.1:8080/` as the example ships. `static_dir` is relative to the working directory, so run from the repository root or make it absolute. -**The executable is the whole badge service, not just this listener.** -`badgeService` starts `simplexChatCore` unconditionally and the web listener +**The executable is the whole store service, not just this listener.** +`storeService` starts `simplexChatCore` unconditionally and the web listener is one lane beside the chat one, so a local run opens or creates a chat database (`printDbOpts` names the path at startup) and does agent network work. `--no-address` skips creating the service's contact address on first start, which a run of the web listener alone does not need. *These three steps are read out of `Options.hs`, `Service.hs`, `Config.hs` and -`badge_service.ini.example` rather than from a run — driving them end to end +`store_service.ini.example` rather than from a run — driving them end to end needs a chat database and a real BTCPay store.* What the mock cannot stand in for: -| | `mock/server.py` | `simplex-badge-service` | +| | `mock/server.py` | `simplex-store-service` | |---|---|---| | Invoices | invented in memory | created at BTCPay over Greenfield | | Payment detected by | `POST /control/settle/:id`, an endpoint that exists nowhere else | a poller reading the provider, which is the only thing that carries authority | @@ -129,10 +129,10 @@ What the mock cannot stand in for: The Haskell side's own end-to-end coverage of that lane — checkout, payment, polling, partial payment, expiry, late settlement and replay, all against a -fake Greenfield — is `tests/Bots/BadgeService/WebTests.hs`: +fake Greenfield — is `tests/Bots/StoreService/WebTests.hs`: ``` -cabal test --test-options='-m "/SimpleX badge service/"' +cabal test --test-options='-m "/SimpleX store service/"' ``` ## Running the mock diff --git a/apps/simplex-badge-service/web/build.js b/apps/simplex-store-service/web/build.js similarity index 100% rename from apps/simplex-badge-service/web/build.js rename to apps/simplex-store-service/web/build.js diff --git a/apps/simplex-badge-service/web/check-tests.js b/apps/simplex-store-service/web/check-tests.js similarity index 100% rename from apps/simplex-badge-service/web/check-tests.js rename to apps/simplex-store-service/web/check-tests.js diff --git a/apps/simplex-badge-service/web/mock/server.py b/apps/simplex-store-service/web/mock/server.py similarity index 99% rename from apps/simplex-badge-service/web/mock/server.py rename to apps/simplex-store-service/web/mock/server.py index 009aea31d4..ec8411be7b 100644 --- a/apps/simplex-badge-service/web/mock/server.py +++ b/apps/simplex-store-service/web/mock/server.py @@ -311,7 +311,7 @@ def main(): # so only a publishable key (pk_) is allowed. sys.exit("mock: STRIPE_PUBLISHABLE_KEY must be a publishable key (pk_...)") server = Server(("127.0.0.1", port), Handler) - print(f"mock badge service on http://localhost:{port}", flush=True) + print(f"mock store service on http://localhost:{port}", flush=True) print("stripe: " + (f"publishable key {STRIPE_PUBLISHABLE_KEY[:11]}… — the real card form" if STRIPE_PUBLISHABLE_KEY else "no STRIPE_PUBLISHABLE_KEY — no card form; pay with btc or xmr"), diff --git a/apps/simplex-badge-service/web/package-lock.json b/apps/simplex-store-service/web/package-lock.json similarity index 100% rename from apps/simplex-badge-service/web/package-lock.json rename to apps/simplex-store-service/web/package-lock.json diff --git a/apps/simplex-badge-service/web/package.json b/apps/simplex-store-service/web/package.json similarity index 100% rename from apps/simplex-badge-service/web/package.json rename to apps/simplex-store-service/web/package.json diff --git a/apps/simplex-badge-service/web/public/fonts/GT-Walsheim-LC-Bold.woff2 b/apps/simplex-store-service/web/public/fonts/GT-Walsheim-LC-Bold.woff2 similarity index 100% rename from apps/simplex-badge-service/web/public/fonts/GT-Walsheim-LC-Bold.woff2 rename to apps/simplex-store-service/web/public/fonts/GT-Walsheim-LC-Bold.woff2 diff --git a/apps/simplex-badge-service/web/public/fonts/Manrope-Bold.woff2 b/apps/simplex-store-service/web/public/fonts/Manrope-Bold.woff2 similarity index 100% rename from apps/simplex-badge-service/web/public/fonts/Manrope-Bold.woff2 rename to apps/simplex-store-service/web/public/fonts/Manrope-Bold.woff2 diff --git a/apps/simplex-badge-service/web/public/fonts/Manrope-Medium.woff2 b/apps/simplex-store-service/web/public/fonts/Manrope-Medium.woff2 similarity index 100% rename from apps/simplex-badge-service/web/public/fonts/Manrope-Medium.woff2 rename to apps/simplex-store-service/web/public/fonts/Manrope-Medium.woff2 diff --git a/apps/simplex-badge-service/web/public/fonts/Manrope-Regular.woff2 b/apps/simplex-store-service/web/public/fonts/Manrope-Regular.woff2 similarity index 100% rename from apps/simplex-badge-service/web/public/fonts/Manrope-Regular.woff2 rename to apps/simplex-store-service/web/public/fonts/Manrope-Regular.woff2 diff --git a/apps/simplex-badge-service/web/public/fonts/Manrope-SemiBold.woff2 b/apps/simplex-store-service/web/public/fonts/Manrope-SemiBold.woff2 similarity index 100% rename from apps/simplex-badge-service/web/public/fonts/Manrope-SemiBold.woff2 rename to apps/simplex-store-service/web/public/fonts/Manrope-SemiBold.woff2 diff --git a/apps/simplex-badge-service/web/public/img/hero-dark.png b/apps/simplex-store-service/web/public/img/hero-dark.png similarity index 100% rename from apps/simplex-badge-service/web/public/img/hero-dark.png rename to apps/simplex-store-service/web/public/img/hero-dark.png diff --git a/apps/simplex-badge-service/web/public/img/hero-light.png b/apps/simplex-store-service/web/public/img/hero-light.png similarity index 100% rename from apps/simplex-badge-service/web/public/img/hero-light.png rename to apps/simplex-store-service/web/public/img/hero-light.png diff --git a/apps/simplex-badge-service/web/public/img/symbol-dark.svg b/apps/simplex-store-service/web/public/img/symbol-dark.svg similarity index 100% rename from apps/simplex-badge-service/web/public/img/symbol-dark.svg rename to apps/simplex-store-service/web/public/img/symbol-dark.svg diff --git a/apps/simplex-badge-service/web/public/img/symbol-light.svg b/apps/simplex-store-service/web/public/img/symbol-light.svg similarity index 100% rename from apps/simplex-badge-service/web/public/img/symbol-light.svg rename to apps/simplex-store-service/web/public/img/symbol-light.svg diff --git a/apps/simplex-badge-service/web/public/img/wordmark-dark.svg b/apps/simplex-store-service/web/public/img/wordmark-dark.svg similarity index 100% rename from apps/simplex-badge-service/web/public/img/wordmark-dark.svg rename to apps/simplex-store-service/web/public/img/wordmark-dark.svg diff --git a/apps/simplex-badge-service/web/public/img/wordmark-light.svg b/apps/simplex-store-service/web/public/img/wordmark-light.svg similarity index 100% rename from apps/simplex-badge-service/web/public/img/wordmark-light.svg rename to apps/simplex-store-service/web/public/img/wordmark-light.svg diff --git a/apps/simplex-badge-service/web/public/index.html b/apps/simplex-store-service/web/public/index.html similarity index 100% rename from apps/simplex-badge-service/web/public/index.html rename to apps/simplex-store-service/web/public/index.html diff --git a/apps/simplex-badge-service/web/public/styles.css b/apps/simplex-store-service/web/public/styles.css similarity index 100% rename from apps/simplex-badge-service/web/public/styles.css rename to apps/simplex-store-service/web/public/styles.css diff --git a/apps/simplex-badge-service/web/public/sw.js b/apps/simplex-store-service/web/public/sw.js similarity index 100% rename from apps/simplex-badge-service/web/public/sw.js rename to apps/simplex-store-service/web/public/sw.js diff --git a/apps/simplex-badge-service/web/src/api.ts b/apps/simplex-store-service/web/src/api.ts similarity index 100% rename from apps/simplex-badge-service/web/src/api.ts rename to apps/simplex-store-service/web/src/api.ts diff --git a/apps/simplex-badge-service/web/src/catalog.ts b/apps/simplex-store-service/web/src/catalog.ts similarity index 100% rename from apps/simplex-badge-service/web/src/catalog.ts rename to apps/simplex-store-service/web/src/catalog.ts diff --git a/apps/simplex-badge-service/web/src/codes.ts b/apps/simplex-store-service/web/src/codes.ts similarity index 100% rename from apps/simplex-badge-service/web/src/codes.ts rename to apps/simplex-store-service/web/src/codes.ts diff --git a/apps/simplex-badge-service/web/src/crowdfunding.ts b/apps/simplex-store-service/web/src/crowdfunding.ts similarity index 100% rename from apps/simplex-badge-service/web/src/crowdfunding.ts rename to apps/simplex-store-service/web/src/crowdfunding.ts diff --git a/apps/simplex-badge-service/web/src/domain.ts b/apps/simplex-store-service/web/src/domain.ts similarity index 100% rename from apps/simplex-badge-service/web/src/domain.ts rename to apps/simplex-store-service/web/src/domain.ts diff --git a/apps/simplex-badge-service/web/src/embed.ts b/apps/simplex-store-service/web/src/embed.ts similarity index 100% rename from apps/simplex-badge-service/web/src/embed.ts rename to apps/simplex-store-service/web/src/embed.ts diff --git a/apps/simplex-badge-service/web/src/flow.ts b/apps/simplex-store-service/web/src/flow.ts similarity index 100% rename from apps/simplex-badge-service/web/src/flow.ts rename to apps/simplex-store-service/web/src/flow.ts diff --git a/apps/simplex-badge-service/web/src/format.ts b/apps/simplex-store-service/web/src/format.ts similarity index 100% rename from apps/simplex-badge-service/web/src/format.ts rename to apps/simplex-store-service/web/src/format.ts diff --git a/apps/simplex-badge-service/web/src/icons.ts b/apps/simplex-store-service/web/src/icons.ts similarity index 100% rename from apps/simplex-badge-service/web/src/icons.ts rename to apps/simplex-store-service/web/src/icons.ts diff --git a/apps/simplex-badge-service/web/src/main.ts b/apps/simplex-store-service/web/src/main.ts similarity index 100% rename from apps/simplex-badge-service/web/src/main.ts rename to apps/simplex-store-service/web/src/main.ts diff --git a/apps/simplex-badge-service/web/src/order.ts b/apps/simplex-store-service/web/src/order.ts similarity index 100% rename from apps/simplex-badge-service/web/src/order.ts rename to apps/simplex-store-service/web/src/order.ts diff --git a/apps/simplex-badge-service/web/src/parse.ts b/apps/simplex-store-service/web/src/parse.ts similarity index 100% rename from apps/simplex-badge-service/web/src/parse.ts rename to apps/simplex-store-service/web/src/parse.ts diff --git a/apps/simplex-badge-service/web/src/qr.ts b/apps/simplex-store-service/web/src/qr.ts similarity index 100% rename from apps/simplex-badge-service/web/src/qr.ts rename to apps/simplex-store-service/web/src/qr.ts diff --git a/apps/simplex-badge-service/web/src/routing.ts b/apps/simplex-store-service/web/src/routing.ts similarity index 100% rename from apps/simplex-badge-service/web/src/routing.ts rename to apps/simplex-store-service/web/src/routing.ts diff --git a/apps/simplex-badge-service/web/src/screens.ts b/apps/simplex-store-service/web/src/screens.ts similarity index 100% rename from apps/simplex-badge-service/web/src/screens.ts rename to apps/simplex-store-service/web/src/screens.ts diff --git a/apps/simplex-badge-service/web/src/store.ts b/apps/simplex-store-service/web/src/store.ts similarity index 100% rename from apps/simplex-badge-service/web/src/store.ts rename to apps/simplex-store-service/web/src/store.ts diff --git a/apps/simplex-badge-service/web/src/stripe.ts b/apps/simplex-store-service/web/src/stripe.ts similarity index 100% rename from apps/simplex-badge-service/web/src/stripe.ts rename to apps/simplex-store-service/web/src/stripe.ts diff --git a/apps/simplex-badge-service/web/test/boot.ts b/apps/simplex-store-service/web/test/boot.ts similarity index 100% rename from apps/simplex-badge-service/web/test/boot.ts rename to apps/simplex-store-service/web/test/boot.ts diff --git a/apps/simplex-badge-service/web/test/build.test.ts b/apps/simplex-store-service/web/test/build.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/build.test.ts rename to apps/simplex-store-service/web/test/build.test.ts diff --git a/apps/simplex-badge-service/web/test/catalog.test.ts b/apps/simplex-store-service/web/test/catalog.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/catalog.test.ts rename to apps/simplex-store-service/web/test/catalog.test.ts diff --git a/apps/simplex-badge-service/web/test/codes.test.ts b/apps/simplex-store-service/web/test/codes.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/codes.test.ts rename to apps/simplex-store-service/web/test/codes.test.ts diff --git a/apps/simplex-badge-service/web/test/css.ts b/apps/simplex-store-service/web/test/css.ts similarity index 100% rename from apps/simplex-badge-service/web/test/css.ts rename to apps/simplex-store-service/web/test/css.ts diff --git a/apps/simplex-badge-service/web/test/design.test.ts b/apps/simplex-store-service/web/test/design.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/design.test.ts rename to apps/simplex-store-service/web/test/design.test.ts diff --git a/apps/simplex-badge-service/web/test/embed.test.ts b/apps/simplex-store-service/web/test/embed.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/embed.test.ts rename to apps/simplex-store-service/web/test/embed.test.ts diff --git a/apps/simplex-badge-service/web/test/flow-controller.test.ts b/apps/simplex-store-service/web/test/flow-controller.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/flow-controller.test.ts rename to apps/simplex-store-service/web/test/flow-controller.test.ts diff --git a/apps/simplex-badge-service/web/test/flow.test.ts b/apps/simplex-store-service/web/test/flow.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/flow.test.ts rename to apps/simplex-store-service/web/test/flow.test.ts diff --git a/apps/simplex-badge-service/web/test/main-app-desktop.test.ts b/apps/simplex-store-service/web/test/main-app-desktop.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-app-desktop.test.ts rename to apps/simplex-store-service/web/test/main-app-desktop.test.ts diff --git a/apps/simplex-badge-service/web/test/main-app-mobile.test.ts b/apps/simplex-store-service/web/test/main-app-mobile.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-app-mobile.test.ts rename to apps/simplex-store-service/web/test/main-app-mobile.test.ts diff --git a/apps/simplex-badge-service/web/test/main-app-reload.test.ts b/apps/simplex-store-service/web/test/main-app-reload.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-app-reload.test.ts rename to apps/simplex-store-service/web/test/main-app-reload.test.ts diff --git a/apps/simplex-badge-service/web/test/main-app-return.test.ts b/apps/simplex-store-service/web/test/main-app-return.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-app-return.test.ts rename to apps/simplex-store-service/web/test/main-app-return.test.ts diff --git a/apps/simplex-badge-service/web/test/main-app-unsaved.test.ts b/apps/simplex-store-service/web/test/main-app-unsaved.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-app-unsaved.test.ts rename to apps/simplex-store-service/web/test/main-app-unsaved.test.ts diff --git a/apps/simplex-badge-service/web/test/main-boot.test.ts b/apps/simplex-store-service/web/test/main-boot.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-boot.test.ts rename to apps/simplex-store-service/web/test/main-boot.test.ts diff --git a/apps/simplex-badge-service/web/test/main-cancel-navigated.test.ts b/apps/simplex-store-service/web/test/main-cancel-navigated.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-cancel-navigated.test.ts rename to apps/simplex-store-service/web/test/main-cancel-navigated.test.ts diff --git a/apps/simplex-badge-service/web/test/main-cancel-race.test.ts b/apps/simplex-store-service/web/test/main-cancel-race.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-cancel-race.test.ts rename to apps/simplex-store-service/web/test/main-cancel-race.test.ts diff --git a/apps/simplex-badge-service/web/test/main-cancel-refusal.test.ts b/apps/simplex-store-service/web/test/main-cancel-refusal.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-cancel-refusal.test.ts rename to apps/simplex-store-service/web/test/main-cancel-refusal.test.ts diff --git a/apps/simplex-badge-service/web/test/main-cancel-refused-navigated.test.ts b/apps/simplex-store-service/web/test/main-cancel-refused-navigated.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-cancel-refused-navigated.test.ts rename to apps/simplex-store-service/web/test/main-cancel-refused-navigated.test.ts diff --git a/apps/simplex-badge-service/web/test/main-cancel-reopened.test.ts b/apps/simplex-store-service/web/test/main-cancel-reopened.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-cancel-reopened.test.ts rename to apps/simplex-store-service/web/test/main-cancel-reopened.test.ts diff --git a/apps/simplex-badge-service/web/test/main-cancel.test.ts b/apps/simplex-store-service/web/test/main-cancel.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-cancel.test.ts rename to apps/simplex-store-service/web/test/main-cancel.test.ts diff --git a/apps/simplex-badge-service/web/test/main-card-cancel.test.ts b/apps/simplex-store-service/web/test/main-card-cancel.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-card-cancel.test.ts rename to apps/simplex-store-service/web/test/main-card-cancel.test.ts diff --git a/apps/simplex-badge-service/web/test/main-card-full-store.test.ts b/apps/simplex-store-service/web/test/main-card-full-store.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-card-full-store.test.ts rename to apps/simplex-store-service/web/test/main-card-full-store.test.ts diff --git a/apps/simplex-badge-service/web/test/main-card-return.test.ts b/apps/simplex-store-service/web/test/main-card-return.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-card-return.test.ts rename to apps/simplex-store-service/web/test/main-card-return.test.ts diff --git a/apps/simplex-badge-service/web/test/main-forget-race.test.ts b/apps/simplex-store-service/web/test/main-forget-race.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-forget-race.test.ts rename to apps/simplex-store-service/web/test/main-forget-race.test.ts diff --git a/apps/simplex-badge-service/web/test/main-forget-refused.test.ts b/apps/simplex-store-service/web/test/main-forget-refused.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-forget-refused.test.ts rename to apps/simplex-store-service/web/test/main-forget-refused.test.ts diff --git a/apps/simplex-badge-service/web/test/main-nav-race.test.ts b/apps/simplex-store-service/web/test/main-nav-race.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-nav-race.test.ts rename to apps/simplex-store-service/web/test/main-nav-race.test.ts diff --git a/apps/simplex-badge-service/web/test/main-no-storage.test.ts b/apps/simplex-store-service/web/test/main-no-storage.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-no-storage.test.ts rename to apps/simplex-store-service/web/test/main-no-storage.test.ts diff --git a/apps/simplex-badge-service/web/test/main-offline.test.ts b/apps/simplex-store-service/web/test/main-offline.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-offline.test.ts rename to apps/simplex-store-service/web/test/main-offline.test.ts diff --git a/apps/simplex-badge-service/web/test/main-one-month.test.ts b/apps/simplex-store-service/web/test/main-one-month.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-one-month.test.ts rename to apps/simplex-store-service/web/test/main-one-month.test.ts diff --git a/apps/simplex-badge-service/web/test/main-pay-forget.test.ts b/apps/simplex-store-service/web/test/main-pay-forget.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-pay-forget.test.ts rename to apps/simplex-store-service/web/test/main-pay-forget.test.ts diff --git a/apps/simplex-badge-service/web/test/main-pay-navigated.test.ts b/apps/simplex-store-service/web/test/main-pay-navigated.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-pay-navigated.test.ts rename to apps/simplex-store-service/web/test/main-pay-navigated.test.ts diff --git a/apps/simplex-badge-service/web/test/main-pay-rechoice.test.ts b/apps/simplex-store-service/web/test/main-pay-rechoice.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-pay-rechoice.test.ts rename to apps/simplex-store-service/web/test/main-pay-rechoice.test.ts diff --git a/apps/simplex-badge-service/web/test/main-pay-repaint.test.ts b/apps/simplex-store-service/web/test/main-pay-repaint.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-pay-repaint.test.ts rename to apps/simplex-store-service/web/test/main-pay-repaint.test.ts diff --git a/apps/simplex-badge-service/web/test/main-quota-full.test.ts b/apps/simplex-store-service/web/test/main-quota-full.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-quota-full.test.ts rename to apps/simplex-store-service/web/test/main-quota-full.test.ts diff --git a/apps/simplex-badge-service/web/test/main-resume-step.test.ts b/apps/simplex-store-service/web/test/main-resume-step.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-resume-step.test.ts rename to apps/simplex-store-service/web/test/main-resume-step.test.ts diff --git a/apps/simplex-badge-service/web/test/main-resume.test.ts b/apps/simplex-store-service/web/test/main-resume.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-resume.test.ts rename to apps/simplex-store-service/web/test/main-resume.test.ts diff --git a/apps/simplex-badge-service/web/test/main-silent-storage.test.ts b/apps/simplex-store-service/web/test/main-silent-storage.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main-silent-storage.test.ts rename to apps/simplex-store-service/web/test/main-silent-storage.test.ts diff --git a/apps/simplex-badge-service/web/test/main.test.ts b/apps/simplex-store-service/web/test/main.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/main.test.ts rename to apps/simplex-store-service/web/test/main.test.ts diff --git a/apps/simplex-badge-service/web/test/open-order.ts b/apps/simplex-store-service/web/test/open-order.ts similarity index 100% rename from apps/simplex-badge-service/web/test/open-order.ts rename to apps/simplex-store-service/web/test/open-order.ts diff --git a/apps/simplex-badge-service/web/test/qr.test.ts b/apps/simplex-store-service/web/test/qr.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/qr.test.ts rename to apps/simplex-store-service/web/test/qr.test.ts diff --git a/apps/simplex-badge-service/web/test/routing.test.ts b/apps/simplex-store-service/web/test/routing.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/routing.test.ts rename to apps/simplex-store-service/web/test/routing.test.ts diff --git a/apps/simplex-badge-service/web/test/screens.test.ts b/apps/simplex-store-service/web/test/screens.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/screens.test.ts rename to apps/simplex-store-service/web/test/screens.test.ts diff --git a/apps/simplex-badge-service/web/test/smoke.test.ts b/apps/simplex-store-service/web/test/smoke.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/smoke.test.ts rename to apps/simplex-store-service/web/test/smoke.test.ts diff --git a/apps/simplex-badge-service/web/test/store.test.ts b/apps/simplex-store-service/web/test/store.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/store.test.ts rename to apps/simplex-store-service/web/test/store.test.ts diff --git a/apps/simplex-badge-service/web/test/stripe.test.ts b/apps/simplex-store-service/web/test/stripe.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/stripe.test.ts rename to apps/simplex-store-service/web/test/stripe.test.ts diff --git a/apps/simplex-badge-service/web/test/stub-dom.ts b/apps/simplex-store-service/web/test/stub-dom.ts similarity index 100% rename from apps/simplex-badge-service/web/test/stub-dom.ts rename to apps/simplex-store-service/web/test/stub-dom.ts diff --git a/apps/simplex-badge-service/web/test/sw.test.ts b/apps/simplex-store-service/web/test/sw.test.ts similarity index 100% rename from apps/simplex-badge-service/web/test/sw.test.ts rename to apps/simplex-store-service/web/test/sw.test.ts diff --git a/apps/simplex-badge-service/web/tsconfig.json b/apps/simplex-store-service/web/tsconfig.json similarity index 100% rename from apps/simplex-badge-service/web/tsconfig.json rename to apps/simplex-store-service/web/tsconfig.json diff --git a/apps/simplex-badge-service/web/tsconfig.test.json b/apps/simplex-store-service/web/tsconfig.test.json similarity index 100% rename from apps/simplex-badge-service/web/tsconfig.test.json rename to apps/simplex-store-service/web/tsconfig.test.json diff --git a/bots/api/TYPES.md b/bots/api/TYPES.md index 80aa0c044f..0ef16842d7 100644 --- a/bots/api/TYPES.md +++ b/bots/api/TYPES.md @@ -15,7 +15,6 @@ This file is generated automatically. - [BadgeInfo](#badgeinfo) - [BadgeProof](#badgeproof) - [BadgeRedeemError](#badgeredeemerror) -- [BadgeServiceErrorCode](#badgeserviceerrorcode) - [BadgeStatus](#badgestatus) - [BadgeType](#badgetype) - [BlockToken](#blocktoken) @@ -234,6 +233,7 @@ This file is generated automatically. - [SocksMode](#socksmode) - [SrvError](#srverror) - [StoreError](#storeerror) +- [StoreServiceErrorCode](#storeserviceerrorcode) - [SubscriptionStatus](#subscriptionstatus) - [SupportGroupPreference](#supportgrouppreference) - [SwitchPhase](#switchphase) @@ -496,7 +496,7 @@ StorePurchaseOpen: ServiceError: - type: "serviceError" -- serviceError: [BadgeServiceErrorCode](#badgeserviceerrorcode) +- serviceError: [StoreServiceErrorCode](#storeserviceerrorcode) InvalidResponse: - type: "invalidResponse" @@ -509,33 +509,6 @@ CredentialNotVerified: - type: "credentialNotVerified" ---- - -## BadgeServiceErrorCode - -**Enum type**: -- "bad_request" -- "unsupported_version" -- "unknown_purchase_key" -- "unknown_offer_id" -- "offer_disabled" -- "offer_mismatch" -- "product_unavailable" -- "payment_not_entitled" -- "payment_pending" -- "provider_unavailable" -- "provider_not_configured" -- "rate_limited" -- "code_invalid" -- "code_used" -- "code_expired" -- "receipt_invalid" -- "receipt_used" -- "transfer_limited" -- "test_purchase" -- "internal" - - --- ## BadgeStatus @@ -5019,6 +4992,33 @@ WorkItemError: - errContext: string +--- + +## StoreServiceErrorCode + +**Enum type**: +- "bad_request" +- "unsupported_version" +- "unknown_purchase_key" +- "unknown_offer_id" +- "offer_disabled" +- "offer_mismatch" +- "product_unavailable" +- "payment_not_entitled" +- "payment_pending" +- "provider_unavailable" +- "provider_not_configured" +- "rate_limited" +- "code_invalid" +- "code_used" +- "code_expired" +- "receipt_invalid" +- "receipt_used" +- "transfer_limited" +- "test_purchase" +- "internal" + + --- ## SubscriptionStatus diff --git a/bots/src/API/Docs/Types.hs b/bots/src/API/Docs/Types.hs index c10aa3cc75..8c99e4cf1c 100644 --- a/bots/src/API/Docs/Types.hs +++ b/bots/src/API/Docs/Types.hs @@ -35,7 +35,7 @@ import Simplex.Chat.Store.Shared import Simplex.Chat.Operators import Simplex.Messaging.Agent.Store.Entity (DBStored (..)) import Simplex.Chat.Badges -import Simplex.Chat.Badges.Service +import Simplex.Chat.StoreService import Simplex.Chat.Names import Simplex.Chat.Types import Simplex.Chat.Types.Preferences @@ -226,7 +226,6 @@ chatTypesDocsData = (sti @AutoAccept, STRecord, "", [], "", ""), (sti @BadgeProof, STRecord, "", [], "", ""), (sti @BadgeRedeemError, STUnion, "BRE", [], "", ""), - (sti @BadgeServiceErrorCode, STEnum' (consSep "BSE" '_'), "", ["BSEUnknown"], "", ""), (sti @BlockingInfo, STRecord, "", [], "", ""), (sti @BlockingReason, STEnum, "BR", [], "", ""), (sti @BlockToken, STUnion, "", [], "", ""), @@ -417,6 +416,7 @@ chatTypesDocsData = (sti @SocksMode, STEnum, "SM", [], "", ""), (sti @SrvError, STUnion, "SrvErr", [], "", ""), (sti @StoreError, STUnion, "SE", [], "", ""), + (sti @StoreServiceErrorCode, STEnum' (consSep "STE" '_'), "", ["STEUnknown"], "", ""), (sti @SubscriptionStatus, STUnion, "SS", [], "", ""), (sti @SupportGroupPreference, STRecord, "", [], "", ""), (sti @SwitchPhase, STEnum, "SP", [], "", ""), @@ -487,7 +487,6 @@ deriving instance Generic AgentServiceError deriving instance Generic AutoAccept deriving instance Generic BadgeProof deriving instance Generic BadgeRedeemError -deriving instance Generic BadgeServiceErrorCode deriving instance Generic BlockingInfo deriving instance Generic BlockingReason deriving instance Generic BlockToken @@ -683,6 +682,7 @@ deriving instance Generic SndGroupEvent deriving instance Generic SocksMode deriving instance Generic SrvError deriving instance Generic StoreError +deriving instance Generic StoreServiceErrorCode deriving instance Generic SubscriptionStatus deriving instance Generic SupportGroupPreference deriving instance Generic SwitchPhase diff --git a/docs/protocol/badges-rpc.md b/docs/protocol/badges-rpc.md index 549085ac54..f1f1d8cd6e 100644 --- a/docs/protocol/badges-rpc.md +++ b/docs/protocol/badges-rpc.md @@ -1,6 +1,6 @@ # Badge service RPC protocol -Schema: `badges-rpc.schema.json`, definitions `request` and `response`. Types: `Simplex.Chat.Badges.Service`. Model: `plans/2026-07-30-supporter-badges-v3-ux.md` §3 — cited below as "model". +Schema: `badges-rpc.schema.json`, definitions `request` and `response`. Types: `Simplex.Chat.StoreService`. Model: `plans/2026-07-30-supporter-badges-v3-ux.md` §3 — cited below as "model". ## Transport diff --git a/docs/protocol/badges-rpc.schema.json b/docs/protocol/badges-rpc.schema.json index 932dcb0449..c6623f7705 100644 --- a/docs/protocol/badges-rpc.schema.json +++ b/docs/protocol/badges-rpc.schema.json @@ -386,7 +386,7 @@ "properties": { "code": { "type": "string", - "metadata": {"comment": "BadgeServiceErrorCode"} + "metadata": {"comment": "StoreServiceErrorCode"} } }, "optionalProperties": { diff --git a/packages/simplex-chat-client/types/typescript/src/types.ts b/packages/simplex-chat-client/types/typescript/src/types.ts index 216498d748..214168155c 100644 --- a/packages/simplex-chat-client/types/typescript/src/types.ts +++ b/packages/simplex-chat-client/types/typescript/src/types.ts @@ -297,7 +297,7 @@ export namespace BadgeRedeemError { export interface ServiceError extends Interface { type: "serviceError" - serviceError: BadgeServiceErrorCode + serviceError: StoreServiceErrorCode } export interface InvalidResponse extends Interface { @@ -314,29 +314,6 @@ export namespace BadgeRedeemError { } } -export enum BadgeServiceErrorCode { - Bad_request = "bad_request", - Unsupported_version = "unsupported_version", - Unknown_purchase_key = "unknown_purchase_key", - Unknown_offer_id = "unknown_offer_id", - Offer_disabled = "offer_disabled", - Offer_mismatch = "offer_mismatch", - Product_unavailable = "product_unavailable", - Payment_not_entitled = "payment_not_entitled", - Payment_pending = "payment_pending", - Provider_unavailable = "provider_unavailable", - Provider_not_configured = "provider_not_configured", - Rate_limited = "rate_limited", - Code_invalid = "code_invalid", - Code_used = "code_used", - Code_expired = "code_expired", - Receipt_invalid = "receipt_invalid", - Receipt_used = "receipt_used", - Transfer_limited = "transfer_limited", - Test_purchase = "test_purchase", - Internal = "internal", -} - export enum BadgeStatus { Active = "active", Expired = "expired", @@ -5701,6 +5678,29 @@ export namespace StoreError { } } +export enum StoreServiceErrorCode { + Bad_request = "bad_request", + Unsupported_version = "unsupported_version", + Unknown_purchase_key = "unknown_purchase_key", + Unknown_offer_id = "unknown_offer_id", + Offer_disabled = "offer_disabled", + Offer_mismatch = "offer_mismatch", + Product_unavailable = "product_unavailable", + Payment_not_entitled = "payment_not_entitled", + Payment_pending = "payment_pending", + Provider_unavailable = "provider_unavailable", + Provider_not_configured = "provider_not_configured", + Rate_limited = "rate_limited", + Code_invalid = "code_invalid", + Code_used = "code_used", + Code_expired = "code_expired", + Receipt_invalid = "receipt_invalid", + Receipt_used = "receipt_used", + Transfer_limited = "transfer_limited", + Test_purchase = "test_purchase", + Internal = "internal", +} + export type SubscriptionStatus = | SubscriptionStatus.Active | SubscriptionStatus.Pending diff --git a/packages/simplex-chat-python/src/simplex_chat/types/_types.py b/packages/simplex-chat-python/src/simplex_chat/types/_types.py index 4e63c73c77..7b956297ee 100644 --- a/packages/simplex-chat-python/src/simplex_chat/types/_types.py +++ b/packages/simplex-chat-python/src/simplex_chat/types/_types.py @@ -203,7 +203,7 @@ class BadgeRedeemError_storePurchaseOpen(TypedDict): class BadgeRedeemError_serviceError(TypedDict): type: Literal["serviceError"] - serviceError: "BadgeServiceErrorCode" + serviceError: "StoreServiceErrorCode" class BadgeRedeemError_invalidResponse(TypedDict): type: Literal["invalidResponse"] @@ -229,8 +229,6 @@ BadgeRedeemError = ( BadgeRedeemError_Tag = Literal["invalidCode", "invalidReceipt", "serviceNotConfigured", "badgeActive", "storePurchaseOpen", "serviceError", "invalidResponse", "unknownKeyIndex", "credentialNotVerified"] -BadgeServiceErrorCode = Literal["bad_request", "unsupported_version", "unknown_purchase_key", "unknown_offer_id", "offer_disabled", "offer_mismatch", "product_unavailable", "payment_not_entitled", "payment_pending", "provider_unavailable", "provider_not_configured", "rate_limited", "code_invalid", "code_used", "code_expired", "receipt_invalid", "receipt_used", "transfer_limited", "test_purchase", "internal"] - BadgeStatus = Literal["active", "expired", "expiredOld", "failed", "unknownKey"] BadgeType = Literal["supporter", "legend", "investor"] @@ -3969,6 +3967,8 @@ StoreError = ( StoreError_Tag = Literal["duplicateName", "userNotFound", "relayUserNotFound", "userNotFoundByName", "userNotFoundByContactId", "userNotFoundByGroupId", "userNotFoundByFileId", "userNotFoundByContactRequestId", "contactNotFound", "contactNotFoundByName", "contactNotFoundByMemberId", "contactNotReady", "duplicateContactLink", "userContactLinkNotFound", "contactRequestNotFound", "contactRequestNotFoundByName", "invalidContactRequestEntity", "invalidBusinessChatContactRequest", "groupNotFound", "groupNotFoundByName", "groupMemberNameNotFound", "groupMemberNotFound", "groupMemberNotFoundByIndex", "memberRelationsVectorNotFound", "groupHostMemberNotFound", "groupMemberNotFoundByMemberId", "memberContactGroupMemberNotFound", "invalidMemberRelationUpdate", "groupWithoutUser", "duplicateGroupMember", "duplicateMemberId", "groupAlreadyJoined", "groupInvitationNotFound", "noteFolderAlreadyExists", "noteFolderNotFound", "userNoteFolderNotFound", "sndFileNotFound", "sndFileInvalid", "rcvFileNotFound", "rcvFileDescrNotFound", "fileNotFound", "rcvFileInvalid", "rcvFileInvalidDescrPart", "localFileNoTransfer", "sharedMsgIdNotFoundByFileId", "fileIdNotFoundBySharedMsgId", "sndFileNotFoundXFTP", "rcvFileNotFoundXFTP", "connectionNotFound", "connectionNotFoundById", "connectionNotFoundByMemberId", "pendingConnectionNotFound", "uniqueID", "largeMsg", "internalError", "dBException", "dBBusyError", "badChatItem", "chatItemNotFound", "chatItemNotFoundByText", "chatItemSharedMsgIdNotFound", "chatItemNotFoundByFileId", "chatItemNotFoundByContactId", "chatItemNotFoundByGroupId", "profileNotFound", "duplicateGroupLink", "groupLinkNotFound", "hostMemberIdNotFound", "contactNotFoundByFileId", "noGroupSndStatus", "duplicateGroupMessage", "remoteHostNotFound", "remoteHostUnknown", "remoteHostDuplicateCA", "remoteCtrlNotFound", "remoteCtrlDuplicateCA", "prohibitedDeleteUser", "operatorNotFound", "usageConditionsNotFound", "userChatRelayNotFound", "groupRelayNotFound", "groupRelayNotFoundByMemberId", "invalidQuote", "invalidMention", "invalidDeliveryTask", "deliveryTaskNotFound", "invalidDeliveryJob", "deliveryJobNotFound", "walletNotFound", "duplicateWallet", "workItemError"] +StoreServiceErrorCode = Literal["bad_request", "unsupported_version", "unknown_purchase_key", "unknown_offer_id", "offer_disabled", "offer_mismatch", "product_unavailable", "payment_not_entitled", "payment_pending", "provider_unavailable", "provider_not_configured", "rate_limited", "code_invalid", "code_used", "code_expired", "receipt_invalid", "receipt_used", "transfer_limited", "test_purchase", "internal"] + class SubscriptionStatus_active(TypedDict): type: Literal["active"] diff --git a/scripts/ci/README.md b/scripts/ci/README.md index 50fad152fb..3e358f8c7a 100644 --- a/scripts/ci/README.md +++ b/scripts/ci/README.md @@ -97,12 +97,12 @@ The reduced build runs one Linux job, build-linux (ubuntu-22.04 x86_64), for eve #### badge-web -- Globs: apps/simplex-badge-service/web/**. These paths are also in the core globs (apps/simplex-badge-service/**), and web/src/catalog.ts is read by core tests (tests/Bots/BadgeService/CatalogTests.hs, WebTests.hs). +- Globs: apps/simplex-store-service/web/**. These paths are also in the core globs (apps/simplex-store-service/**), and web/src/catalog.ts is read by core tests (tests/Bots/StoreService/CatalogTests.hs, WebTests.hs). - CI, in build-linux: core build and tests, then `scope-tests.sh badge-web` (step "Test changed scopes"). - Selected core tests: `/SimpleX badge service/` and `/SimpleX badge service e2e/`. - Local: ```sh - cd apps/simplex-badge-service/web + cd apps/simplex-store-service/web npm ci npm test ``` diff --git a/scripts/ci/packages_release.py b/scripts/ci/packages_release.py index 7b8d5db551..ac0d4947a4 100644 --- a/scripts/ci/packages_release.py +++ b/scripts/ci/packages_release.py @@ -55,7 +55,7 @@ BUILD_CHANGES = { "apps/simplex-chat/**", "apps/simplex-bot/**", "apps/simplex-bot-advanced/**", - "apps/simplex-badge-service/**", + "apps/simplex-store-service/**", "apps/simplex-broadcast-bot/**", "apps/simplex-directory-service/**", "tests/**", @@ -80,7 +80,7 @@ BUILD_CHANGES = { ], } SCOPE_CHANGES = { - "badge-web": ["apps/simplex-badge-service/web/**"], + "badge-web": ["apps/simplex-store-service/web/**"], "ci-scripts": ["scripts/ci/packages_release.py", "scripts/ci/test_packages_release.py"], } CABAL_FILE = "simplex-chat.cabal" diff --git a/scripts/ci/scope-tests.sh b/scripts/ci/scope-tests.sh index fe4b2807a9..02c0c33e0f 100755 --- a/scripts/ci/scope-tests.sh +++ b/scripts/ci/scope-tests.sh @@ -6,7 +6,7 @@ cd "$(dirname "$0")/../.." case "${1:-}" in badge-web) - (cd apps/simplex-badge-service/web && npm ci && npm test) + (cd apps/simplex-store-service/web && npm ci && npm test) ;; ci-scripts) python3 scripts/ci/test_packages_release.py diff --git a/scripts/ci/test_packages_release.py b/scripts/ci/test_packages_release.py index 72e4295a20..643df685be 100644 --- a/scripts/ci/test_packages_release.py +++ b/scripts/ci/test_packages_release.py @@ -507,7 +507,7 @@ class ChangesTest(GitRepoTest): self.assertEqual(self.builds("packages/simplex-chat-python/src/simplex_chat/client.py"), {"packages"}) def test_badge_web_change_builds_the_core_and_tests_its_scope(self): - self.assertEqual(self.builds("apps/simplex-badge-service/web/src/catalog.ts"), {"haskell"}) + self.assertEqual(self.builds("apps/simplex-store-service/web/src/catalog.ts"), {"haskell"}) self.assertEqual(self.values["scopes"], "badge-web") def test_release_script_change_tests_the_ci_scripts(self): diff --git a/scripts/badge-service/.gitignore b/scripts/store-service/.gitignore similarity index 100% rename from scripts/badge-service/.gitignore rename to scripts/store-service/.gitignore diff --git a/scripts/badge-service/Dockerfile b/scripts/store-service/Dockerfile similarity index 86% rename from scripts/badge-service/Dockerfile rename to scripts/store-service/Dockerfile index b368aa32ac..a08832e786 100644 --- a/scripts/badge-service/Dockerfile +++ b/scripts/store-service/Dockerfile @@ -12,9 +12,9 @@ ARG NODE=24 FROM node:${NODE}-bookworm-slim AS web WORKDIR /web -COPY apps/simplex-badge-service/web/package.json apps/simplex-badge-service/web/package-lock.json ./ +COPY apps/simplex-store-service/web/package.json apps/simplex-store-service/web/package-lock.json ./ RUN npm ci -COPY apps/simplex-badge-service/web ./ +COPY apps/simplex-store-service/web ./ RUN npm run build FROM ubuntu:${UBUNTU} AS build @@ -44,7 +44,7 @@ COPY scripts/cabal.project.local.linux ./cabal.project.local COPY src ./src # Excluding web/ keeps a webapp edit from invalidating this layer and re-running the cabal build, # and the binary does not depend on it. -COPY --exclude=web apps/simplex-badge-service ./apps/simplex-badge-service +COPY --exclude=web apps/simplex-store-service ./apps/simplex-store-service # The store and build tree are cache mounts rather than layers, so the binary is copied out inside # the same RUN because dist-newstyle does not exist in the resulting layer. @@ -52,10 +52,10 @@ RUN --mount=type=cache,target=/root/.cabal \ --mount=type=cache,target=/src/dist-newstyle \ set -eu; \ cabal update; \ - cabal build --flags="+client_postgres" exe:simplex-badge-service; \ + cabal build --flags="+client_postgres" exe:simplex-store-service; \ mkdir -p /out; \ - cp "$(cabal list-bin --flags="+client_postgres" exe:simplex-badge-service)" /out/simplex-badge-service; \ - strip /out/simplex-badge-service + cp "$(cabal list-bin --flags="+client_postgres" exe:simplex-store-service)" /out/simplex-store-service; \ + strip /out/simplex-store-service FROM ubuntu:${UBUNTU} AS runtime @@ -80,7 +80,7 @@ RUN if existing_user=$(getent passwd ${USER_UID} | cut -d: -f1) && [ -n "${exist groupadd -g ${USER_GID} badge && \ useradd -u ${USER_UID} -g ${USER_GID} -m -d /home/badge badge -COPY --from=build /out/simplex-badge-service /usr/local/bin/simplex-badge-service +COPY --from=build /out/simplex-store-service /usr/local/bin/simplex-store-service COPY --from=web /web/dist /srv/web USER badge @@ -93,7 +93,7 @@ EXPOSE 8080 # The flags live in CMD so `docker compose run` can replace them while dumb-init still forwards # signals. -ENTRYPOINT ["dumb-init", "--", "simplex-badge-service"] +ENTRYPOINT ["dumb-init", "--", "simplex-store-service"] # Without --yes-migrate the service blocks on stdin at every schema change, and a container has no # console to answer. -CMD ["-d", "postgresql://simplex@127.0.0.1:5432/badge_service", "--create-schema", "--yes-migrate", "--service-config", "/etc/simplex-badge-service/badge_service.ini"] +CMD ["-d", "postgresql://simplex@127.0.0.1:5432/badge_service", "--create-schema", "--yes-migrate", "--service-config", "/etc/simplex-store-service/store_service.ini"] diff --git a/scripts/badge-service/Dockerfile.dockerignore b/scripts/store-service/Dockerfile.dockerignore similarity index 76% rename from scripts/badge-service/Dockerfile.dockerignore rename to scripts/store-service/Dockerfile.dockerignore index 915d409570..3e985872de 100644 --- a/scripts/badge-service/Dockerfile.dockerignore +++ b/scripts/store-service/Dockerfile.dockerignore @@ -14,17 +14,17 @@ scripts/* !apps apps/* -!apps/simplex-badge-service +!apps/simplex-store-service # Build output, caches, local state, and anything holding a secret. The ini is # mounted at run time and must never be baked into an image: it holds the issuer # secret, and with [btcpay] the API key and webhook secret too. -badge_service.ini +store_service.ini **/dist **/dist-newstyle **/node_modules **/*.db **/*.db-* -apps/simplex-badge-service/test-fixtures -apps/simplex-badge-service/web-traversal-test -apps/simplex-badge-service/web/build +apps/simplex-store-service/test-fixtures +apps/simplex-store-service/web-traversal-test +apps/simplex-store-service/web/build diff --git a/scripts/badge-service/compose.yml b/scripts/store-service/compose.yml similarity index 74% rename from scripts/badge-service/compose.yml rename to scripts/store-service/compose.yml index 6a81ac8200..5aaa5c704b 100644 --- a/scripts/badge-service/compose.yml +++ b/scripts/store-service/compose.yml @@ -1,9 +1,9 @@ services: - badge-service: - image: simplex-badge-service:latest + store-service: + image: simplex-store-service:latest build: context: ../.. - dockerfile: scripts/badge-service/Dockerfile + dockerfile: scripts/store-service/Dockerfile args: USER_UID: ${USER_UID:-1000} USER_GID: ${USER_GID:-1000} @@ -17,11 +17,11 @@ services: - "--create-schema" - "--yes-migrate" - "--service-config" - - "/etc/simplex-badge-service/badge_service.ini" + - "/etc/simplex-store-service/store_service.ini" volumes: - type: bind source: ./config - target: /etc/simplex-badge-service + target: /etc/simplex-store-service read_only: true bind: create_host_path: false diff --git a/scripts/badge-service/badge_service.ini.example b/scripts/store-service/store_service.ini.example similarity index 96% rename from scripts/badge-service/badge_service.ini.example rename to scripts/store-service/store_service.ini.example index 6728a4f9e3..2a48ba4e37 100644 --- a/scripts/badge-service/badge_service.ini.example +++ b/scripts/store-service/store_service.ini.example @@ -46,10 +46,10 @@ idle_seconds = 60 ; only host accepted unless [dev] credit_test_purchases = on, which needs the Sandbox host instead. ;[apple] ;bundle_id = chat.simplex.app -;root_certificates = /etc/simplex-badge-service/AppleRootCA-G3.cer +;root_certificates = /etc/simplex-store-service/AppleRootCA-G3.cer ;api_key_id = 2X9R4HXF34 ;api_issuer_id = 57246542-96fe-1a63-e053-0824d011072a -;api_private_key_file = /etc/simplex-badge-service/AuthKey_2X9R4HXF34.p8 +;api_private_key_file = /etc/simplex-store-service/AuthKey_2X9R4HXF34.p8 ; optional; without it every Play receipt is answered provider_not_configured, which the app retries later. ; service_account_file is the JSON key of a service account with the Play Console permissions "View @@ -58,7 +58,7 @@ idle_seconds = 60 ; itself is answered internal until the permission is granted. Place it in config/; the file must be readable by the service's user alone. ;[google] ;package_name = chat.simplex.app -;service_account_file = /etc/simplex-badge-service/play-service-account.json +;service_account_file = /etc/simplex-store-service/play-service-account.json ; index is the one clients verify against; private_key is from `simplex-chat badge keygen`. ; To rotate, change both together, once clients trust the new index. diff --git a/simplex-chat.cabal b/simplex-chat.cabal index bb666a993d..38d99cee32 100644 --- a/simplex-chat.cabal +++ b/simplex-chat.cabal @@ -43,7 +43,6 @@ library Simplex.Chat.Badges.CLI Simplex.Chat.Badges.Code Simplex.Chat.Badges.Ledger - Simplex.Chat.Badges.Service Simplex.Chat.Badges.StorePlan Simplex.Chat.Badges.Types Simplex.Chat.Names @@ -98,6 +97,7 @@ library Simplex.Chat.Store.Remote Simplex.Chat.Store.Shared Simplex.Chat.Store.Wallets + Simplex.Chat.StoreService Simplex.Chat.Styled Simplex.Chat.Types Simplex.Chat.Types.MemberRelations @@ -445,38 +445,38 @@ library , template-haskell ==2.16.* , text >=1.2.4.0 && <1.3 -executable simplex-badge-service +executable simplex-store-service if flag(client_library) buildable: False main-is: Main.hs hs-source-dirs: - apps/simplex-badge-service - apps/simplex-badge-service/src + apps/simplex-store-service + apps/simplex-store-service/src default-extensions: StrictData other-modules: - BadgeService.Catalog - BadgeService.Codes - BadgeService.Config - BadgeService.Group - BadgeService.Group.Command - BadgeService.Log - BadgeService.Options - BadgeService.Orders - BadgeService.Poller - BadgeService.Providers - BadgeService.Providers.BTCPay - BadgeService.Providers.Stripe - BadgeService.Service - BadgeService.Store - BadgeService.Store.Invoices - BadgeService.Store.Migrate - BadgeService.StoreReceipts - BadgeService.StoreReceipts.Apple - BadgeService.StoreReceipts.Google - BadgeService.StoreReceipts.Mock - BadgeService.Waiters - BadgeService.Web.Server + StoreService.Catalog + StoreService.Codes + StoreService.Config + StoreService.Group + StoreService.Group.Command + StoreService.Log + StoreService.Options + StoreService.Orders + StoreService.Poller + StoreService.Providers + StoreService.Providers.BTCPay + StoreService.Providers.Stripe + StoreService.Service + StoreService.Store + StoreService.Store.Invoices + StoreService.Store.Migrate + StoreService.StoreReceipts + StoreService.StoreReceipts.Apple + StoreService.StoreReceipts.Google + StoreService.StoreReceipts.Mock + StoreService.Waiters + StoreService.Web.Server Paths_simplex_chat ghc-options: -O2 -Weverything -Wno-missing-exported-signatures -Wno-missing-import-lists -Wno-missed-specialisations -Wno-all-missed-specialisations -Wno-unsafe -Wno-safe -Wno-missing-local-signatures -Wno-missing-kind-signatures -Wno-missing-deriving-strategies -Wno-monomorphism-restriction -Wno-prepositive-qualified-module -Wno-unused-packages -Wno-implicit-prelude -Wno-missing-safe-haskell-mode -Wno-missing-export-lists -Wno-partial-fields -Wcompat -Werror=incomplete-record-updates -Werror=incomplete-patterns -Werror=missing-methods -Werror=incomplete-uni-patterns -Werror=tabs -Wredundant-constraints -Wincomplete-record-updates -Wunused-type-patterns -Werror=name-shadowing -threaded -rtsopts build-depends: @@ -510,14 +510,14 @@ executable simplex-badge-service default-language: Haskell2010 if flag(client_postgres) other-modules: - BadgeService.Store.Postgres.Migrations + StoreService.Store.Postgres.Migrations build-depends: postgresql-simple ==0.7.* , raw-strings-qq ==1.1.* cpp-options: -DdbPostgres else other-modules: - BadgeService.Store.SQLite.Migrations + StoreService.Store.SQLite.Migrations build-depends: sqlcipher-simple ==0.4.* if impl(ghc >= 9.6.2) @@ -755,48 +755,24 @@ test-suite simplex-chat-test API.Docs.Syntax.Types API.Docs.Types API.TypeInfo - BadgeService.Catalog - BadgeService.Codes - BadgeService.Config - BadgeService.Group - BadgeService.Group.Command - BadgeService.Log - BadgeService.Names.Chain - BadgeService.Names.Registration - BadgeService.Options - BadgeService.Orders - BadgeService.Poller - BadgeService.Providers - BadgeService.Providers.BTCPay - BadgeService.Providers.Stripe - BadgeService.Service - BadgeService.Store - BadgeService.Store.Invoices - BadgeService.Store.Migrate - BadgeService.StoreReceipts - BadgeService.StoreReceipts.Apple - BadgeService.StoreReceipts.Google - BadgeService.StoreReceipts.Mock - BadgeService.Waiters - BadgeService.Web.Server - Bots.BadgeService.BTCPayTests - Bots.BadgeService.BotTests - Bots.BadgeService.CatalogTests - Bots.BadgeService.ConfigTests - Bots.BadgeService.FakeAppStore - Bots.BadgeService.FakeBTCPay - Bots.BadgeService.FakeEthNode - Bots.BadgeService.FakePlay - Bots.BadgeService.FakeStore - Bots.BadgeService.FakeStripe - Bots.BadgeService.GroupIntegrationTests - Bots.BadgeService.GroupTests - Bots.BadgeService.NameRegistrationTests - Bots.BadgeService.StoreVerifierTests - Bots.BadgeService.StripeTests - Bots.BadgeService.WaitersTests - Bots.BadgeService.WebTests - Bots.BadgeService.WebUIMock + Bots.StoreService.BTCPayTests + Bots.StoreService.BotTests + Bots.StoreService.CatalogTests + Bots.StoreService.ConfigTests + Bots.StoreService.FakeAppStore + Bots.StoreService.FakeBTCPay + Bots.StoreService.FakeEthNode + Bots.StoreService.FakePlay + Bots.StoreService.FakeStore + Bots.StoreService.FakeStripe + Bots.StoreService.GroupIntegrationTests + Bots.StoreService.GroupTests + Bots.StoreService.NameRegistrationTests + Bots.StoreService.StoreVerifierTests + Bots.StoreService.StripeTests + Bots.StoreService.WaitersTests + Bots.StoreService.WebTests + Bots.StoreService.WebUIMock Broadcast.Bot Broadcast.Options Directory.BlockedWords @@ -808,6 +784,30 @@ test-suite simplex-chat-test Directory.Service Directory.Store Directory.Store.Migrate + StoreService.Catalog + StoreService.Codes + StoreService.Config + StoreService.Group + StoreService.Group.Command + StoreService.Log + StoreService.Names.Chain + StoreService.Names.Registration + StoreService.Options + StoreService.Orders + StoreService.Poller + StoreService.Providers + StoreService.Providers.BTCPay + StoreService.Providers.Stripe + StoreService.Service + StoreService.Store + StoreService.Store.Invoices + StoreService.Store.Migrate + StoreService.StoreReceipts + StoreService.StoreReceipts.Apple + StoreService.StoreReceipts.Google + StoreService.StoreReceipts.Mock + StoreService.Waiters + StoreService.Web.Server Paths_simplex_chat if flag(client_postgres) other-modules: @@ -822,7 +822,7 @@ test-suite simplex-chat-test hs-source-dirs: bots/src tests - apps/simplex-badge-service/src + apps/simplex-store-service/src apps/simplex-broadcast-bot/src apps/simplex-directory-service/src default-extensions: @@ -875,7 +875,7 @@ test-suite simplex-chat-test default-language: Haskell2010 if flag(client_postgres) other-modules: - BadgeService.Store.Postgres.Migrations + StoreService.Store.Postgres.Migrations Directory.Store.Postgres.Migrations build-depends: postgresql-simple ==0.7.* @@ -883,7 +883,7 @@ test-suite simplex-chat-test cpp-options: -DdbPostgres else other-modules: - BadgeService.Store.SQLite.Migrations + StoreService.Store.SQLite.Migrations Directory.Store.SQLite.Migrations build-depends: sqlcipher-simple ==0.4.* diff --git a/src/Simplex/Chat.hs b/src/Simplex/Chat.hs index 033bf31837..44aeaba236 100644 --- a/src/Simplex/Chat.hs +++ b/src/Simplex/Chat.hs @@ -71,7 +71,7 @@ defaultChatConfig = chatVRange = supportedChatVRange, callVRange = supportedCallVRange, badgePublicKeys = M.mapKeys fromIntegral entitlementIssuerKeys, - badgeServiceAddress = Just $ either error id $ strDecode "https://smp5.simplex.im/a#ooSNWlEZTO2RPE0Ff5ZoybAs5zEhWLMlQrXesnhaZHM", + storeServiceAddress = Just $ either error id $ strDecode "https://smp5.simplex.im/a#ooSNWlEZTO2RPE0Ff5ZoybAs5zEhWLMlQrXesnhaZHM", badgeCurrentTime = getCurrentTime, badgeRetryInterval = RetryInterval {initialInterval = 30_000000, increaseAfter = 0, maxInterval = 3600_000000}, badgeConsecutiveRetries = 3, diff --git a/src/Simplex/Chat/Badges.hs b/src/Simplex/Chat/Badges.hs index 7be33212f7..02e7a1d7b6 100644 --- a/src/Simplex/Chat/Badges.hs +++ b/src/Simplex/Chat/Badges.hs @@ -189,7 +189,7 @@ mkBadgeStatus now verified BadgeInfo {badgeExpiry = e} = case verified of -- A badge credential (own, secret) and a proof (a presentation) are independent records. -- badgeKeyIdx is the issuer key index: it tells verifiers which configured key to use. --- Only proofs ride the wire (in a profile); credentials come from the badge service. Neither is +-- Only proofs ride the wire (in a profile); credentials come from the store service. Neither is -- ever serialized as a sum - each travels as its own record, so the JSON carries no credential/proof tag. data BadgeCredential = BadgeCredential diff --git a/src/Simplex/Chat/Badges/Code.hs b/src/Simplex/Chat/Badges/Code.hs index 035ed2e9c5..e9a131a461 100644 --- a/src/Simplex/Chat/Badges/Code.hs +++ b/src/Simplex/Chat/Badges/Code.hs @@ -1,7 +1,7 @@ {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} --- | Badge redemption codes, shared by the client, the badge service and the checkout site. +-- | Badge redemption codes, shared by the client, the store service and the checkout site. -- -- A code is "SB-" and 20 Crockford base32 characters in four groups of five: -- 19 payload characters and a final check character. diff --git a/src/Simplex/Chat/Badges/Ledger.hs b/src/Simplex/Chat/Badges/Ledger.hs index d7f939058f..b74362faeb 100644 --- a/src/Simplex/Chat/Badges/Ledger.hs +++ b/src/Simplex/Chat/Badges/Ledger.hs @@ -29,7 +29,7 @@ import Data.Time.Calendar (addDays, addGregorianMonthsClip, toGregorian) import Data.Time.Calendar.WeekDate (toWeekDate) import Data.Time.Clock (NominalDiffTime, UTCTime (..), addUTCTime) import Simplex.Chat.Badges (BadgeType) -import Simplex.Chat.Badges.Service (StatementCreditType (..), StatementDebitType (..), StatementEntry (..), StatementEntryType (..)) +import Simplex.Chat.StoreService (StatementCreditType (..), StatementDebitType (..), StatementEntry (..), StatementEntryType (..)) import Simplex.Chat.PaymentService.Types (InvoiceId) import qualified Simplex.Messaging.Crypto as C diff --git a/src/Simplex/Chat/Badges/Types.hs b/src/Simplex/Chat/Badges/Types.hs index 8d6a1f23e2..bbb3b9be5f 100644 --- a/src/Simplex/Chat/Badges/Types.hs +++ b/src/Simplex/Chat/Badges/Types.hs @@ -19,7 +19,7 @@ module Simplex.Chat.Badges.Types LedgerCreditType (..), LedgerDebitType (..), BadgeAlertKind (..), - BadgeServiceErrorCode (..), + StoreServiceErrorCode (..), SubscriptionState (..), BadgeIssueFailure (..), BadgeIssueError (..), @@ -231,28 +231,28 @@ data BadgeAlertPrice = BadgeAlertPrice } deriving (Show) -data BadgeServiceErrorCode - = BSEBadRequest - | BSEUnsupportedVersion - | BSEUnknownPurchaseKey - | BSEUnknownOfferId - | BSEOfferDisabled - | BSEOfferMismatch - | BSEProductUnavailable - | BSEPaymentNotEntitled - | BSEPaymentPending - | BSEProviderUnavailable - | BSEProviderNotConfigured -- no verifier deployed: a dev service, not the store failing to answer - | BSERateLimited - | BSECodeInvalid - | BSECodeUsed - | BSECodeExpired - | BSEReceiptInvalid - | BSEReceiptUsed - | BSETransferLimited -- the subscription moved from another key whose credential has not expired yet - | BSETestPurchase -- the store vouched for a purchase that cost nothing: Apple's sandbox, a Play license tester - | BSEInternal - | BSEUnknown Text -- forwards-compatible: service is deployed ahead of clients +data StoreServiceErrorCode + = STEBadRequest + | STEUnsupportedVersion + | STEUnknownPurchaseKey + | STEUnknownOfferId + | STEOfferDisabled + | STEOfferMismatch + | STEProductUnavailable + | STEPaymentNotEntitled + | STEPaymentPending + | STEProviderUnavailable + | STEProviderNotConfigured -- no verifier deployed: a dev service, not the store failing to answer + | STERateLimited + | STECodeInvalid + | STECodeUsed + | STECodeExpired + | STEReceiptInvalid + | STEReceiptUsed + | STETransferLimited -- the subscription moved from another key whose credential has not expired yet + | STETestPurchase -- the store vouched for a purchase that cost nothing: Apple's sandbox, a Play license tester + | STEInternal + | STEUnknown Text -- forwards-compatible: service is deployed ahead of clients deriving (Eq, Show) -- | The store's answer as the service last read it. A client reads a state it does not know as not ended. @@ -267,7 +267,7 @@ data SubscriptionState -- | Why a renewal request ended without a credential stored. retryable is the service's own view of -- transience: it gave retryAfter, which holds for codes this version does not know. data BadgeIssueFailure - = BIFServiceError {code :: BadgeServiceErrorCode, retryable :: Bool} + = BIFServiceError {code :: StoreServiceErrorCode, retryable :: Bool} | BIFServiceTimeout | BIFNetwork {agentError :: Text} | BIFInvalidCredential @@ -359,58 +359,58 @@ instance FromField BadgeCodePaymentStatus where fromField = fromTextField_ textD instance ToField BadgeCodePaymentStatus where toField = toField . textEncode -instance TextEncoding BadgeServiceErrorCode where +instance TextEncoding StoreServiceErrorCode where textEncode = \case - BSEBadRequest -> "bad_request" - BSEUnsupportedVersion -> "unsupported_version" - BSEUnknownPurchaseKey -> "unknown_purchase_key" - BSEUnknownOfferId -> "unknown_offer_id" - BSEOfferDisabled -> "offer_disabled" - BSEOfferMismatch -> "offer_mismatch" - BSEProductUnavailable -> "product_unavailable" - BSEPaymentNotEntitled -> "payment_not_entitled" - BSEPaymentPending -> "payment_pending" - BSEProviderUnavailable -> "provider_unavailable" - BSEProviderNotConfigured -> "provider_not_configured" - BSERateLimited -> "rate_limited" - BSECodeInvalid -> "code_invalid" - BSECodeUsed -> "code_used" - BSECodeExpired -> "code_expired" - BSEReceiptInvalid -> "receipt_invalid" - BSEReceiptUsed -> "receipt_used" - BSETransferLimited -> "transfer_limited" - BSETestPurchase -> "test_purchase" - BSEInternal -> "internal" - BSEUnknown t -> t + STEBadRequest -> "bad_request" + STEUnsupportedVersion -> "unsupported_version" + STEUnknownPurchaseKey -> "unknown_purchase_key" + STEUnknownOfferId -> "unknown_offer_id" + STEOfferDisabled -> "offer_disabled" + STEOfferMismatch -> "offer_mismatch" + STEProductUnavailable -> "product_unavailable" + STEPaymentNotEntitled -> "payment_not_entitled" + STEPaymentPending -> "payment_pending" + STEProviderUnavailable -> "provider_unavailable" + STEProviderNotConfigured -> "provider_not_configured" + STERateLimited -> "rate_limited" + STECodeInvalid -> "code_invalid" + STECodeUsed -> "code_used" + STECodeExpired -> "code_expired" + STEReceiptInvalid -> "receipt_invalid" + STEReceiptUsed -> "receipt_used" + STETransferLimited -> "transfer_limited" + STETestPurchase -> "test_purchase" + STEInternal -> "internal" + STEUnknown t -> t textDecode s = Just $ case s of - "bad_request" -> BSEBadRequest - "unsupported_version" -> BSEUnsupportedVersion - "unknown_purchase_key" -> BSEUnknownPurchaseKey - "unknown_offer_id" -> BSEUnknownOfferId - "offer_disabled" -> BSEOfferDisabled - "offer_mismatch" -> BSEOfferMismatch - "product_unavailable" -> BSEProductUnavailable - "payment_not_entitled" -> BSEPaymentNotEntitled - "payment_pending" -> BSEPaymentPending - "provider_unavailable" -> BSEProviderUnavailable - "provider_not_configured" -> BSEProviderNotConfigured - "rate_limited" -> BSERateLimited - "code_invalid" -> BSECodeInvalid - "code_used" -> BSECodeUsed - "code_expired" -> BSECodeExpired - "receipt_invalid" -> BSEReceiptInvalid - "receipt_used" -> BSEReceiptUsed - "transfer_limited" -> BSETransferLimited - "test_purchase" -> BSETestPurchase - "internal" -> BSEInternal - t -> BSEUnknown t + "bad_request" -> STEBadRequest + "unsupported_version" -> STEUnsupportedVersion + "unknown_purchase_key" -> STEUnknownPurchaseKey + "unknown_offer_id" -> STEUnknownOfferId + "offer_disabled" -> STEOfferDisabled + "offer_mismatch" -> STEOfferMismatch + "product_unavailable" -> STEProductUnavailable + "payment_not_entitled" -> STEPaymentNotEntitled + "payment_pending" -> STEPaymentPending + "provider_unavailable" -> STEProviderUnavailable + "provider_not_configured" -> STEProviderNotConfigured + "rate_limited" -> STERateLimited + "code_invalid" -> STECodeInvalid + "code_used" -> STECodeUsed + "code_expired" -> STECodeExpired + "receipt_invalid" -> STEReceiptInvalid + "receipt_used" -> STEReceiptUsed + "transfer_limited" -> STETransferLimited + "test_purchase" -> STETestPurchase + "internal" -> STEInternal + t -> STEUnknown t -instance ToJSON BadgeServiceErrorCode where +instance ToJSON StoreServiceErrorCode where toJSON = textToJSON toEncoding = textToEncoding -instance FromJSON BadgeServiceErrorCode where - parseJSON = textParseJSON "BadgeServiceErrorCode" +instance FromJSON StoreServiceErrorCode where + parseJSON = textParseJSON "StoreServiceErrorCode" instance TextEncoding SubscriptionState where textEncode = \case @@ -465,7 +465,7 @@ instance StrEncoding BadgeIssueFailure where "retry" -> pure True "final" -> pure False _ -> fail "bad BadgeIssueFailure retry flag" - codeP = A.takeByteString >>= maybe (fail "bad BadgeServiceErrorCode") pure . textDecode . safeDecodeUtf8 + codeP = A.takeByteString >>= maybe (fail "bad StoreServiceErrorCode") pure . textDecode . safeDecodeUtf8 restP = safeDecodeUtf8 <$> (A.space *> A.takeByteString) instance ToField BadgeIssueFailure where toField = toField . decodeLatin1 . strEncode diff --git a/src/Simplex/Chat/Controller.hs b/src/Simplex/Chat/Controller.hs index da5c6e1a9f..3a74e4bb9c 100644 --- a/src/Simplex/Chat/Controller.hs +++ b/src/Simplex/Chat/Controller.hs @@ -85,7 +85,7 @@ import qualified Simplex.Messaging.Agent.Store.DB as DB import Simplex.Messaging.Client (HostMode (..), SMPProxyFallback (..), SMPProxyMode (..), SMPWebPortServers (..), SocksMode (..)) import qualified Simplex.Messaging.Crypto as C import Simplex.Chat.Badges (BadgeCredential, FileSizeLimits, LocalBadge) -import Simplex.Chat.Badges.Service (BadgeServiceErrorCode, StatementEntry) +import Simplex.Chat.StoreService (StoreServiceErrorCode, StatementEntry) import Simplex.Chat.Badges.Types (BadgeAlert (..), BadgeAlertKind, BadgeIssueFailure, BadgeState (..), OpenStorePurchase (..), StoreReceiptOrigin, SubscriptionState) import Simplex.Chat.PaymentService (ServicePayment) import Simplex.Messaging.Crypto.BBS (BBSPublicKey) @@ -149,15 +149,15 @@ data ChatConfig = ChatConfig callVRange :: VersionRangeCall, -- issuer public keys by index: credentials and proofs name the key that signed them, for rotation badgePublicKeys :: Map Int BBSPublicKey, - -- Nothing until the badge service is deployed - badgeServiceAddress :: Maybe (ConnectTarget 'CMContact), + -- Nothing until the store service is deployed + storeServiceAddress :: Maybe (ConnectTarget 'CMContact), -- the only clock badge code reads, so tests can shift it; production arithmetic is unchanged badgeCurrentTime :: IO UTCTime, -- how long a badge worker waits before repeating a renewal that failed for a passing reason badgeRetryInterval :: RetryInterval, -- attempts a store receipt gets in one turn before its next one waits for the stored schedule badgeConsecutiveRetries :: Int, - -- set only by builds for a dev badge service: allows /_badge request, sent off the shared schedule + -- set only by builds for a dev store service: allows /_badge request, sent off the shared schedule badgeDevRequests :: Bool, -- Local testing only: the badge worker treats a request as due this often, instead of near the -- credential's expiry, so a renewal can be watched without waiting weeks. @@ -676,7 +676,7 @@ data ChatCommand | UpdateProfileImage (Maybe ImageData) -- UserId (not used in UI) | UpdateProfileImageFromFile FilePath -- set profile image from a .png/.jpg/.jpeg file | AddBadge BadgeCredential -- attach an issued badge credential (testing; credential from `simplex-chat badge sign`) - | APIRedeemBadgeCode {userId :: UserId, code :: Text} -- redeem a badge code with the configured badge service + | APIRedeemBadgeCode {userId :: UserId, code :: Text} -- redeem a badge code with the configured store service | APIPurchaseBadge {userId :: UserId, echoedInvoiceId :: Maybe Text, origin :: StoreReceiptOrigin, payment :: ServicePayment} -- hand over an App Store or Google Play receipt, held until a worker credits it; answers from the record and sends nothing | APISetBadgeSubscriptionStatus {status :: SubscriptionState, payment :: ServicePayment} -- the device store's view of a credited subscription, which changes what is shown and alerted, and retires its badge once ended | APICreateBadgeInvoice {userId :: UserId} -- the record of a store purchase, created before the store charges; answers the id the store echoes @@ -1548,7 +1548,7 @@ data BadgeRedeemError | BREServiceNotConfigured | BREBadgeActive | BREStorePurchaseOpen -- a store receipt held for this profile may still be credited - | BREServiceError {serviceError :: BadgeServiceErrorCode} + | BREServiceError {serviceError :: StoreServiceErrorCode} | BREInvalidResponse {message :: String} | BREUnknownKeyIndex | BRECredentialNotVerified diff --git a/src/Simplex/Chat/Library/Commands.hs b/src/Simplex/Chat/Library/Commands.hs index 40b85b275d..0734f4ac41 100644 --- a/src/Simplex/Chat/Library/Commands.hs +++ b/src/Simplex/Chat/Library/Commands.hs @@ -64,7 +64,7 @@ import Simplex.Chat.Badges (BadgeCredential (..), BadgeInfo (..), BadgeMasterKey import qualified Simplex.Chat.Badges.Ledger as L import Simplex.Chat.Badges.Types (BadgeAlert (..), BadgeAlertKind (..), BadgeIssueError (..), BadgeIssueFailure (..), BadgeState (..), BadgeSubscription (..), OpenStorePurchase (..), StoreReceiptOrigin (..)) import Simplex.Chat.Badges.Code (badgeCodeText, parseBadgeCode) -import Simplex.Chat.Badges.Service (BadgeBalance (..), BadgeServiceCommand (..), BadgeServiceErrorCode (..), BadgeServiceRequest (..), BadgeServiceResponse (..), BadgeStatement (..), StatementDebitType (..), StatementEntry (..), StatementEntryType (..), SubscriptionState (..), currentBadgeServiceVersion) +import Simplex.Chat.StoreService (BadgeBalance (..), BadgeStatement (..), StatementDebitType (..), StatementEntry (..), StatementEntryType (..), StoreServiceCommand (..), StoreServiceErrorCode (..), StoreServiceRequest (..), StoreServiceResponse (..), SubscriptionState (..), currentStoreServiceVersion) import Simplex.Chat.Badges.StorePlan (storePlan) import Simplex.Chat.Names (SimplexDomainProof (..), SimplexDomainClaim (..), claimDomain, mkDomainClaim) import Simplex.Chat.Wallet (deriveAccount, masterMnemonic, newEntropy) @@ -3680,7 +3680,7 @@ processChatCommand cxt nm = \case APIPurchaseBadge userId echoedInvoiceId origin payment -> withUserId userId $ \user -> handOverStoreReceipt user echoedInvoiceId origin payment APISetBadgeSubscriptionStatus status payment -> recordStoreSubscriptionStatus status payment >> ok_ APICreateBadgeInvoice userId -> withUserId userId $ \user -> do - void requireBadgeService + void requireStoreService refuseWhileBadgeHeld user refuseWhileStoreReceiptPending user Nothing g <- asks random @@ -5477,7 +5477,7 @@ presentUserBadgeToContacts user'@User {userId, profile = LocalProfile {localBadg redeemBadgeCode :: NetworkRequestMode -> User -> Text -> CM ChatResponse redeemBadgeCode nm user@User {userId} codeText = do code <- maybe (throwRedeemError BREInvalidCode) pure $ parseBadgeCode codeText - sendTarget <- requireBadgeService + sendTarget <- requireStoreService g <- asks random now <- liftIO getCurrentTime let codeSent = badgeCodeText code @@ -5486,7 +5486,7 @@ redeemBadgeCode nm user@User {userId} codeText = do (present_, redeemed) <- withEntityLock "badgeRedeem" (CLBadgeUser userId) $ do stash_ <- withStore' $ \db -> getBadgeCodeRedemption db user codeSent stash@BadgeStash {masterKey} <- stashBadgeKeys user stash_ $ \db -> createBadgeCodeRedemption db g user codeSent now - requestBadgeStash nm user sendTarget stash BSCRedeemBadgeCode {masterKey, code = codeSent} >>= \case + requestBadgeStash nm user sendTarget stash STCRedeemBadgeCode {masterKey, code = codeSent} >>= \case Left (errCode, _) -> do when (terminalCodeError errCode) $ withStore' $ \db -> deleteBadgeCodeRedemption db user codeSent throwRedeemError $ BREServiceError errCode @@ -5497,9 +5497,9 @@ redeemBadgeCode nm user@User {userId} codeText = do where -- the code will never work, so the keys stashed for it are dead; a timeout keeps them terminalCodeError = \case - BSECodeInvalid -> True - BSECodeUsed -> True - BSECodeExpired -> True + STECodeInvalid -> True + STECodeUsed -> True + STECodeExpired -> True _ -> False -- | The app hands a receipt over until it is answered credited or refused, under whichever profile is @@ -5507,7 +5507,7 @@ redeemBadgeCode nm user@User {userId} codeText = do handOverStoreReceipt :: User -> Maybe Text -> StoreReceiptOrigin -> ServicePayment -> CM ChatResponse handOverStoreReceipt presentingUser echoedInvoiceId origin payment = do txRef <- maybe (throwRedeemError BREInvalidReceipt) pure $ storeTransactionRef payment - void requireBadgeService + void requireStoreService g <- asks random now <- badgeNow limited <- case origin of @@ -5524,7 +5524,7 @@ handOverStoreReceipt presentingUser echoedInvoiceId origin payment = do _ -> throwChatError $ CEInternalError "store receipt was not recorded" Just BadgeReceiptRecord {receiptId, ownerId, status} -> do owner <- withStore $ \db -> getUser db ownerId - when limited $ lift (resumeStoreReceiptWork ownerId) >> throwRedeemError (BREServiceError BSETransferLimited) + when limited $ lift (resumeStoreReceiptWork ownerId) >> throwRedeemError (BREServiceError STETransferLimited) case status of RSHeld {} -> lift (resumeStoreReceiptWork ownerId) >> badgeStateResponse owner RSCredited {badgePurchaseId, refusalRecorded} -> do @@ -5537,7 +5537,7 @@ handOverStoreReceipt presentingUser echoedInvoiceId origin payment = do True -> do unlessM (withStore' (`userHasBadge` owner)) $ whenM (withStore' $ \db -> holdStoreTransfer db g owner txRef payment now) $ - lift (resumeStoreReceiptWork ownerId) >> throwRedeemError (BREServiceError BSETransferLimited) + lift (resumeStoreReceiptWork ownerId) >> throwRedeemError (BREServiceError STETransferLimited) pure True movedOut <- withStore' (`purchaseMovedOut` badgePurchaseId) answeredHeld <- case resumeHold now payment of @@ -5597,13 +5597,13 @@ recordStoreSubscriptionStatus reported payment = do _ -> True -- | The receipt will never be credited to its key; any other refusal may pass on a retry. -storeReceiptRefused :: BadgeServiceErrorCode -> Bool +storeReceiptRefused :: StoreServiceErrorCode -> Bool storeReceiptRefused = \case - BSEReceiptInvalid -> True - BSEReceiptUsed -> True + STEReceiptInvalid -> True + STEReceiptUsed -> True -- a badge moves only on the user's Restore, never by a retry once the limit has passed - BSETransferLimited -> True - BSETestPurchase -> True + STETransferLimited -> True + STETestPurchase -> True _ -> False -- | How far ahead of this device's clock a charge's purchase date may be: a payload dated further ahead is never held. @@ -5683,8 +5683,8 @@ stashBadgeKeys user stash_ createStash = do unless replaying $ refuseWhileBadgeHeld user >> refuseWhileStoreReceiptPending user Nothing maybe (withStore' createStash) pure stash_ -requireBadgeService :: CM (ConnectTarget 'CMContact) -requireBadgeService = asks (badgeServiceAddress . config) >>= maybe (throwRedeemError BREServiceNotConfigured) pure +requireStoreService :: CM (ConnectTarget 'CMContact) +requireStoreService = asks (storeServiceAddress . config) >>= maybe (throwRedeemError BREServiceNotConfigured) pure refuseWhileBadgeHeld :: User -> CM () refuseWhileBadgeHeld user = whenM (withStore' (`userHasBadge` user)) $ throwRedeemError BREBadgeActive @@ -5706,29 +5706,29 @@ refuseWhileStoreReceiptPending user presented_ = do -- | One attempt to turn a stash into a badge. A refusal is answered rather than thrown, with the -- service's retryAfter. -requestBadgeStash :: NetworkRequestMode -> User -> ConnectTarget 'CMContact -> BadgeStash -> BadgeServiceCommand -> CM (Either (BadgeServiceErrorCode, Maybe Word32) (Maybe User, ChatResponse)) +requestBadgeStash :: NetworkRequestMode -> User -> ConnectTarget 'CMContact -> BadgeStash -> StoreServiceCommand -> CM (Either (StoreServiceErrorCode, Maybe Word32) (Maybe User, ChatResponse)) requestBadgeStash nm user sendTarget stash@BadgeStash {purchaseKey, purchasePrivKey} request = do - let req = BadgeServiceRequest {version = currentBadgeServiceVersion, purchaseKey = Just purchaseKey, request} + let req = StoreServiceRequest {version = currentStoreServiceVersion, purchaseKey = Just purchaseKey, request} respBytes <- sendServiceRequestBytes nm user sendTarget Nothing (Just purchasePrivKey) req respData <- either (const $ throwRedeemError $ BREInvalidResponse "not JSON") pure $ J.eitherDecodeStrict' respBytes case J.fromJSON (J.Object respData) of - J.Error _ -> throwRedeemError $ BREInvalidResponse "not a badge service response" - J.Success BSPError {code, retryAfter} -> pure $ Left (code, retryAfter) - J.Success BSPBadgeCredential {credential = Just cred, statement, subscription} -> Right <$> storeRedeemedBadge user stash cred statement (boundedSubscriptionState <$> subscription) + J.Error _ -> throwRedeemError $ BREInvalidResponse "not a store service response" + J.Success STPError {code, retryAfter} -> pure $ Left (code, retryAfter) + J.Success STPBadgeCredential {credential = Just cred, statement, subscription} -> Right <$> storeRedeemedBadge user stash cred statement (boundedSubscriptionState <$> subscription) J.Success _ -> throwRedeemError $ BREInvalidResponse "unexpected response type" throwRedeemError :: BadgeRedeemError -> CM a throwRedeemError = throwChatError . CEBadgeRedeemError -badgeServiceErrorText :: BadgeServiceErrorCode -> Text -badgeServiceErrorText = textEncode . boundedServiceErrorCode +storeServiceErrorText :: StoreServiceErrorCode -> Text +storeServiceErrorText = textEncode . boundedServiceErrorCode -- | An unknown code is reported and recorded, since the service is deployed ahead of clients, but -- its text is the service's - so it is bounded and stripped before it reaches a terminal that acts -- on controls, or a sentence the app shows the user as its own. -boundedServiceErrorCode :: BadgeServiceErrorCode -> BadgeServiceErrorCode +boundedServiceErrorCode :: StoreServiceErrorCode -> StoreServiceErrorCode boundedServiceErrorCode = \case - BSEUnknown t -> boundedServiceText BSEUnknown errorCodeChar t + STEUnknown t -> boundedServiceText STEUnknown errorCodeChar t code -> code where errorCodeChar c = isAsciiLower c || isDigit c || c == '_' @@ -5754,12 +5754,12 @@ badgeNow = asks (badgeCurrentTime . config) >>= liftIO -- | A signal carries nothing: each pass derives its work from stored state, so a signal lost or -- duplicated changes no outcome. startBadgeWork :: User -> CM' () -startBadgeWork user = whenM (isJust <$> asks (badgeServiceAddress . config)) $ void $ getBadgeWorker user +startBadgeWork user = whenM (isJust <$> asks (storeServiceAddress . config)) $ void $ getBadgeWorker user --- | Sent off the shared request moment, so only a build for a dev badge service may send it. +-- | Sent off the shared request moment, so only a build for a dev store service may send it. requestBadgeNow :: User -> CM ChatResponse requestBadgeNow user@User {userId} = do - unlessM (asks $ badgeDevRequests . config) $ throwCmdError "/_badge request is only available in builds for a dev badge service" + unlessM (asks $ badgeDevRequests . config) $ throwCmdError "/_badge request is only available in builds for a dev store service" withStore' (`getUserBadgePurchase` user) >>= \case Just p@UserBadgePurchase {shown = True} -> do badgeNow >>= requestBadgeIssue userId p >>= \case @@ -5928,19 +5928,19 @@ creditStoreReceipt a userId receiptId stash@BadgeStash {masterKey} invoiceId_ pa credit ri delay cmd = tryAllErrors (attempt cmd) >>= \answer -> serviceAnswered ri delay refuse (failed ri delay) answer $ \(present_, _) -> pure $ SROCredited present_ -- retried takes only a service error that is not a refusal: a thrown error is recorded as a failure as it is - serviceAnswered :: RetryInterval -> Int64 -> (BadgeIssueFailure -> CM StoreReceiptOutcome) -> (BadgeIssueFailure -> Maybe Word32 -> CM StoreReceiptOutcome) -> Either ChatError (Either (BadgeServiceErrorCode, Maybe Word32) r) -> (r -> CM StoreReceiptOutcome) -> CM StoreReceiptOutcome + serviceAnswered :: RetryInterval -> Int64 -> (BadgeIssueFailure -> CM StoreReceiptOutcome) -> (BadgeIssueFailure -> Maybe Word32 -> CM StoreReceiptOutcome) -> Either ChatError (Either (StoreServiceErrorCode, Maybe Word32) r) -> (r -> CM StoreReceiptOutcome) -> CM StoreReceiptOutcome serviceAnswered ri delay refused retried answer answered = case answer of Left e -> failed ri delay (badgeIssueFailure e) Nothing Right (Left (code, retryAfter)) | storeReceiptRefused code -> refused $ serviceFailure code retryAfter | otherwise -> retried (serviceFailure code retryAfter) retryAfter Right (Right r) -> answered r - purchaseCmd payment' = BSCPurchaseBadge {masterKey, payment = payment', upgrade = Nothing} - transferCmd payment' = BSCTransferBadge {masterKey, payment = payment'} + purchaseCmd payment' = STCPurchaseBadge {masterKey, payment = payment', upgrade = Nothing} + transferCmd payment' = STCTransferBadge {masterKey, payment = payment'} attempt cmd = do user <- withStore $ \db -> getUser db userId refuseWhileBadgeHeld user - sendTarget <- requireBadgeService + sendTarget <- requireStoreService payment' <- maybe (throwChatError $ CEInternalError "held store payment does not decode") pure $ decodeJSON payment requestBadgeStash NRMBackground user sendTarget stash (cmd payment') -- a held record whose keys already fund a purchase is a resume of that retired subscription, checked before every send @@ -5959,7 +5959,7 @@ creditStoreReceipt a userId receiptId stash@BadgeStash {masterKey} invoiceId_ pa | isNewest, Just hold <- resumeHold now =<< decodeJSON payment -> resumeIssue ri delay user p hold now _ -> refuse receiptInvalid resumeIssue ri delay user p@UserBadgePurchase {badgePurchaseId} hold now = do - answer <- tryAllErrors $ requireBadgeService >>= \sendTarget -> sendBadgeIssue sendTarget userId p BSCIssueBadge (recordBadgeIssueFailure p) now + answer <- tryAllErrors $ requireStoreService >>= \sendTarget -> sendBadgeIssue sendTarget userId p STCIssueBadge (recordBadgeIssueFailure p) now answeredAt <- badgeNow -- a charge the service does not grant, as a revoked one, stops holding the profile once its hold ends let notCredited failure retryAfter = case hold of @@ -5978,7 +5978,7 @@ creditStoreReceipt a userId receiptId stash@BadgeStash {masterKey} invoiceId_ pa lift $ startBadgeWork user' pure $ SROCredited (Just user') -- the service's own check interval - _ -> notCredited BIFServiceError {code = BSEPaymentPending, retryable = True} (Just 3600) + _ -> notCredited BIFServiceError {code = STEPaymentPending, retryable = True} (Just 3600) -- Settles with nothing to announce: a charge expired or no newer than the last one credited, or to a tier that is not -- higher, the renewal check grants the change, and a badge no longer shown is resumed by the charge's next hand-over. changeTier ri delay purchaseId = do @@ -5993,8 +5993,8 @@ creditStoreReceipt a userId receiptId stash@BadgeStash {masterKey} invoiceId_ pa -- the receipt's failures are recorded on the record, not as the purchase's failed renewal, as the badge shown still covers upgradeIssue ri delay user p@UserBadgePurchase {badgePurchaseId} payment' tier now = do failure_ <- newTVarIO Nothing - let upgradeCmd balance = BSCUpgradeBadgeSubscription {payment = payment', balance} - answer <- tryAllErrors $ requireBadgeService >>= \sendTarget -> sendBadgeIssue sendTarget userId p upgradeCmd (atomically . writeTVar failure_ . Just) now + let upgradeCmd balance = STCUpgradeBadgeSubscription {payment = payment', balance} + answer <- tryAllErrors $ requireStoreService >>= \sendTarget -> sendBadgeIssue sendTarget userId p upgradeCmd (atomically . writeTVar failure_ . Just) now answeredAt <- badgeNow recorded_ <- readTVarIO failure_ let refusedInSilence failure = SRODeferred <$ withStore' (\db -> refuseStoreReceipt db receiptId payment failure) @@ -6009,7 +6009,7 @@ creditStoreReceipt a userId receiptId stash@BadgeStash {masterKey} invoiceId_ pa setUserBadge db user (Just $ OwnBadge cred (mkBadgeStatus answeredAt (Just True) info)) lift $ startBadgeWork user' pure $ SROCredited (Just user') - _ -> failedHeld ri delay BIFServiceError {code = BSEPaymentPending, retryable = True} (Just 3600) + _ -> failedHeld ri delay BIFServiceError {code = STEPaymentPending, retryable = True} (Just 3600) -- out of attempts, the record is set aside without a refusal, so the next hand-over holds it again; -- this attempt's failure is not recorded yet, so it is counted here failedHeld ri delay failure retryAfter = do @@ -6018,7 +6018,7 @@ creditStoreReceipt a userId receiptId stash@BadgeStash {masterKey} invoiceId_ pa then setAside else failed ri delay failure retryAfter setAside = SRODeferred <$ withStore' (`settleStoreReceipt` receiptId) - receiptInvalid = BIFServiceError {code = BSEReceiptInvalid, retryable = False} + receiptInvalid = BIFServiceError {code = STEReceiptInvalid, retryable = False} -- a payment adopted while this one was with the service stays held and is sent next, so nothing is announced refuse failure = do refused <- withStore' $ \db -> refuseStoreReceipt db receiptId payment failure @@ -6312,7 +6312,7 @@ badgeIssueFailure e = case e of badgeFailureTransient :: BadgeIssueFailure -> Bool badgeFailureTransient = \case -- the service withholds retryAfter from internal to avoid being pressed while failing, not because it is final - BIFServiceError {code = BSEInternal} -> True + BIFServiceError {code = STEInternal} -> True BIFServiceError {retryable} -> retryable BIFServiceTimeout -> True BIFNetwork {} -> True @@ -6329,10 +6329,10 @@ badgeErrorRetry = badgeFailureTransient . badgeIssueFailure -- since a service error is answered rather than thrown. Any request that -- ends without a credential the ledger still owes is recorded on the purchase as a failed renewal; -- nothing else records one. -requestBadgeIssue :: UserId -> UserBadgePurchase -> UTCTime -> CM (Either (BadgeServiceErrorCode, Maybe Word32) (StatementEntry, Maybe SubscriptionState)) +requestBadgeIssue :: UserId -> UserBadgePurchase -> UTCTime -> CM (Either (StoreServiceErrorCode, Maybe Word32) (StatementEntry, Maybe SubscriptionState)) requestBadgeIssue userId p now = do - sendTarget <- asks (badgeServiceAddress . config) >>= maybe (throwCmdError "badge service not configured") pure - withEntityLock "badgeIssue" (CLBadgeUser userId) $ sendBadgeIssue sendTarget userId p BSCIssueBadge (recordBadgeIssueFailure p) now + sendTarget <- asks (storeServiceAddress . config) >>= maybe (throwCmdError "store service not configured") pure + withEntityLock "badgeIssue" (CLBadgeUser userId) $ sendBadgeIssue sendTarget userId p STCIssueBadge (recordBadgeIssueFailure p) now recordBadgeIssueFailure :: UserBadgePurchase -> BadgeIssueFailure -> CM () recordBadgeIssueFailure UserBadgePurchase {badgePurchaseId} failure = do @@ -6340,13 +6340,13 @@ recordBadgeIssueFailure UserBadgePurchase {badgePurchaseId} failure = do withStore' $ \db -> setBadgeIssueError db badgePurchaseId failedAt failure -- | 'requestBadgeIssue' for a caller that already holds the owner's badge lock, which is not reentrant. -sendBadgeIssue :: ConnectTarget 'CMContact -> UserId -> UserBadgePurchase -> (BadgeBalance -> BadgeServiceCommand) -> (BadgeIssueFailure -> CM ()) -> UTCTime -> CM (Either (BadgeServiceErrorCode, Maybe Word32) (StatementEntry, Maybe SubscriptionState)) +sendBadgeIssue :: ConnectTarget 'CMContact -> UserId -> UserBadgePurchase -> (BadgeBalance -> StoreServiceCommand) -> (BadgeIssueFailure -> CM ()) -> UTCTime -> CM (Either (StoreServiceErrorCode, Maybe Word32) (StatementEntry, Maybe SubscriptionState)) sendBadgeIssue sendTarget userId UserBadgePurchase {badgePurchaseId, badgeType, purchaseKey, purchasePrivKey, masterKey} command recordFailure now = do user <- withStore $ \db -> getUser db userId lastEntry <- withStore' (`getBadgeLedgerLastEntry` badgePurchaseId) >>= maybe (throwCmdError "badge ledger has no entry to assert") pure let req = - BadgeServiceRequest - { version = currentBadgeServiceVersion, + StoreServiceRequest + { version = currentStoreServiceVersion, purchaseKey = Just purchaseKey, request = command BadgeBalance {lastEntry} } @@ -6354,7 +6354,7 @@ sendBadgeIssue sendTarget userId UserBadgePurchase {badgePurchaseId, badgeType, sendServiceRequestTo NRMBackground user sendTarget Nothing (Just purchasePrivKey) req `catchAllErrors` \e -> recordFailure (badgeIssueFailure e) >> throwError e case J.fromJSON (J.Object respData) of - J.Success BSPBadgeCredential {credential = sentCred_, statement, subscription} -> do + J.Success STPBadgeCredential {credential = sentCred_, statement, subscription} -> do verifiedCred_ <- verifyIssuedCredential masterKey sentCred_ g <- asks random -- read again: now was taken before a lock wait and an untimed request, and the check reads @@ -6375,11 +6375,11 @@ sendBadgeIssue sendTarget userId UserBadgePurchase {badgePurchaseId, badgeType, (_, _, False) -> recordUnexpected "issued badge credential has no ledger row to store it against" -- no credential is the service saying nothing is owed - the months ran out, or a subscription -- waits for its store to charge - which its statement then shows; ended after a move leaves the issued month running - (Nothing, _, _) | subscription /= Just SSEnded && maybe False ((> storedAt) . L.paidThrough) balance_ -> recordUnexpected "badge service issued no credential" + (Nothing, _, _) | subscription /= Just SSEnded && maybe False ((> storedAt) . L.paidThrough) balance_ -> recordUnexpected "store service issued no credential" _ -> pure () maybe (throwCmdError "badge ledger has no balance") (pure . Right . (,storedSubscription)) balance_ - J.Success BSPError {code, retryAfter} -> do - eToView $ ChatError $ CECommandError $ "badge service error: " <> T.unpack (badgeServiceErrorText code) + J.Success STPError {code, retryAfter} -> do + eToView $ ChatError $ CECommandError $ "store service error: " <> T.unpack (storeServiceErrorText code) -- retryAfter only marks the failure as one that can clear: the retry waits a stall like any request that -- issued nothing, since a shorter wait would let the service choose how often activations reach it recordFailure BIFServiceError {code = boundedServiceErrorCode code, retryable = isJust retryAfter} @@ -6388,7 +6388,7 @@ sendBadgeIssue sendTarget userId UserBadgePurchase {badgePurchaseId, badgeType, recordFailure BIFUnexpected {message = unexpectedResponse} throwCmdError $ T.unpack unexpectedResponse where - unexpectedResponse = "unexpected badge service response" + unexpectedResponse = "unexpected store service response" recordUnexpected message = do eToView $ ChatError $ CEInternalError $ T.unpack message recordFailure BIFUnexpected {message} diff --git a/src/Simplex/Chat/Store/Badges.hs b/src/Simplex/Chat/Store/Badges.hs index 32978e3647..3051d3653b 100644 --- a/src/Simplex/Chat/Store/Badges.hs +++ b/src/Simplex/Chat/Store/Badges.hs @@ -73,8 +73,8 @@ import Data.Time.Clock (UTCTime, addUTCTime, nominalDay) import Data.Time.Clock.POSIX (posixSecondsToUTCTime) import Simplex.Chat.Badges import Simplex.Chat.Badges.Ledger -import Simplex.Chat.Badges.Service (StatementCreditType (..), StatementDebitType (..), StatementEntry (..), StatementEntryType (..)) -import Simplex.Chat.Badges.Types (BadgeAlertKind, BadgeIssueError (..), BadgeIssueFailure (..), BadgePurchaseStatus (..), BadgeServiceErrorCode (..), BadgeSubscription (..), OpenStorePurchase (..), StoreReceiptOrigin (..), SubscriptionState (..)) +import Simplex.Chat.StoreService (StatementCreditType (..), StatementDebitType (..), StatementEntry (..), StatementEntryType (..)) +import Simplex.Chat.Badges.Types (BadgeAlertKind, BadgeIssueError (..), BadgeIssueFailure (..), BadgePurchaseStatus (..), StoreServiceErrorCode (..), BadgeSubscription (..), OpenStorePurchase (..), StoreReceiptOrigin (..), SubscriptionState (..)) import Simplex.Chat.PaymentService (AppleTransactionFacts (..), ServicePayment (..), appleTransactionFacts) import Simplex.Chat.PaymentService.Types (StoreTransactionRef (..)) import Simplex.Chat.Store.Shared (StoreError, insertedRowId) @@ -256,7 +256,7 @@ holdStoreTransfer db g user@User {userId} txRef payment now = (userId, SHKTransfer, now, receiptId, SHKPurchase) Just _ -> pure False Just BadgeReceiptRecord {receiptId, status = RSRefused {refusal = Just BIFServiceError {code}}} - | code == BSEReceiptUsed || code == BSETransferLimited -> (code == BSETransferLimited) <$ holdTransfer receiptId + | code == STEReceiptUsed || code == STETransferLimited -> (code == STETransferLimited) <$ holdTransfer receiptId Just BadgeReceiptRecord {receiptId, ownerId, status = RSCredited {badgePurchaseId}} -> movesHere ownerId badgePurchaseId >>= \case False -> pure False @@ -267,7 +267,7 @@ holdStoreTransfer db g user@User {userId} txRef payment now = DB.execute db "UPDATE badge_store_receipts SET purchase_key = ?, purchase_priv_key = ?, master_key = ? WHERE badge_store_receipt_id = ? AND payment IS NULL" (purchaseKey, purchasePrivKey, Binary mk, receiptId) holdTransfer receiptId pure $ case join lastRefusal of - Just BIFServiceError {code = BSETransferLimited} -> True + Just BIFServiceError {code = STETransferLimited} -> True _ -> False _ -> pure False where @@ -337,7 +337,7 @@ getReceiptRecord db StoreTransactionRef {provider, transactionRef} = _ -> maybe (RSRefused refusal) (\badgePurchaseId -> RSCredited {badgePurchaseId, refusalRecorded = maybe False ownRefusal refusal}) purchaseId_ -- only a move is refused transfer_limited, and a refused move must not hold off the purchase's own resume or tier change ownRefusal = \case - BIFServiceError {code = BSETransferLimited} -> False + BIFServiceError {code = STETransferLimited} -> False _ -> True -- | The record made when Buy is tapped, before any receipt: the store echoes its invoice id. diff --git a/src/Simplex/Chat/Store/Postgres/Migrations/M20260915_user_badges.hs b/src/Simplex/Chat/Store/Postgres/Migrations/M20260915_user_badges.hs index d4cf2308d0..1ee5288d56 100644 --- a/src/Simplex/Chat/Store/Postgres/Migrations/M20260915_user_badges.hs +++ b/src/Simplex/Chat/Store/Postgres/Migrations/M20260915_user_badges.hs @@ -7,7 +7,7 @@ import Data.Text (Text) import qualified Data.Text as T import Text.RawString.QQ (r) --- the same tables in the client and in the badge service; '@' is replaced with the table name prefix +-- the same tables in the client and in the store service; '@' is replaced with the table name prefix badgeSchema :: Text -> Text badgeSchema pfx = withPrefix pfx badgeSchemaTables diff --git a/src/Simplex/Chat/Store/SQLite/Migrations/M20260915_user_badges.hs b/src/Simplex/Chat/Store/SQLite/Migrations/M20260915_user_badges.hs index 218fbd2410..95a0fc510e 100644 --- a/src/Simplex/Chat/Store/SQLite/Migrations/M20260915_user_badges.hs +++ b/src/Simplex/Chat/Store/SQLite/Migrations/M20260915_user_badges.hs @@ -8,7 +8,7 @@ import qualified Data.Text as T import Database.SQLite.Simple (Query (..)) import Database.SQLite.Simple.QQ (sql) --- the same tables in the client and in the badge service; '@' is replaced with the table name prefix +-- the same tables in the client and in the store service; '@' is replaced with the table name prefix badgeSchema :: Text -> Query badgeSchema pfx = withPrefix pfx badgeSchemaTables diff --git a/src/Simplex/Chat/Badges/Service.hs b/src/Simplex/Chat/StoreService.hs similarity index 80% rename from src/Simplex/Chat/Badges/Service.hs rename to src/Simplex/Chat/StoreService.hs index a828cfbf6b..facae0dff9 100644 --- a/src/Simplex/Chat/Badges/Service.hs +++ b/src/Simplex/Chat/StoreService.hs @@ -5,19 +5,19 @@ {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE TemplateHaskell #-} -module Simplex.Chat.Badges.Service - ( BadgeServiceRequest (..), - BadgeServiceCommand (..), - BadgeServiceVersion, - VersionBadgeService, - VersionRangeBadgeService, - pattern VersionBadgeService, - initialBadgeServiceVersion, - currentBadgeServiceVersion, - supportedBadgeServiceVRange, +module Simplex.Chat.StoreService + ( StoreServiceRequest (..), + StoreServiceCommand (..), + StoreServiceVersion, + VersionStoreService, + VersionRangeStoreService, + pattern VersionStoreService, + initialStoreServiceVersion, + currentStoreServiceVersion, + supportedStoreServiceVRange, BadgeUpgrade (..), - BadgeServiceResponse (..), - BadgeServiceErrorCode (..), + StoreServiceResponse (..), + StoreServiceErrorCode (..), SubscriptionState (..), BadgeCatalog (..), BadgePrice (..), @@ -47,63 +47,63 @@ import Simplex.Messaging.Parsers (defaultJSON, dropPrefix, taggedObjectJSON) import Simplex.Messaging.Version (VersionRange, VersionScope, mkVersionRange) import Simplex.Messaging.Version.Internal (Version (..)) -data BadgeServiceVersion +data StoreServiceVersion -instance VersionScope BadgeServiceVersion +instance VersionScope StoreServiceVersion -type VersionBadgeService = Version BadgeServiceVersion +type VersionStoreService = Version StoreServiceVersion -pattern VersionBadgeService :: Word16 -> VersionBadgeService -pattern VersionBadgeService v = Version v +pattern VersionStoreService :: Word16 -> VersionStoreService +pattern VersionStoreService v = Version v -type VersionRangeBadgeService = VersionRange BadgeServiceVersion +type VersionRangeStoreService = VersionRange StoreServiceVersion -initialBadgeServiceVersion :: VersionBadgeService -initialBadgeServiceVersion = VersionBadgeService 1 +initialStoreServiceVersion :: VersionStoreService +initialStoreServiceVersion = VersionStoreService 1 -currentBadgeServiceVersion :: VersionBadgeService -currentBadgeServiceVersion = VersionBadgeService 1 +currentStoreServiceVersion :: VersionStoreService +currentStoreServiceVersion = VersionStoreService 1 -- the service is deployed ahead of app releases, so it answers within the client's version -supportedBadgeServiceVRange :: VersionRangeBadgeService -supportedBadgeServiceVRange = mkVersionRange initialBadgeServiceVersion currentBadgeServiceVersion +supportedStoreServiceVRange :: VersionRangeStoreService +supportedStoreServiceVRange = mkVersionRange initialStoreServiceVersion currentStoreServiceVersion -data BadgeServiceRequest = BadgeServiceRequest - { version :: VersionBadgeService, - purchaseKey :: Maybe C.PublicKeyEd25519, -- optional for BSCGetBadgeCatalog, required for other commands - request :: BadgeServiceCommand +data StoreServiceRequest = StoreServiceRequest + { version :: VersionStoreService, + purchaseKey :: Maybe C.PublicKeyEd25519, -- optional for STCGetBadgeCatalog, required for other commands + request :: StoreServiceCommand } -data BadgeServiceCommand - = BSCGetBadgeCatalog - | BSCGetBadgeInvoice +data StoreServiceCommand + = STCGetBadgeCatalog + | STCGetBadgeInvoice { priceId :: BadgePriceId, offerId :: Maybe BadgeOfferId, -- absent for 1 month at the badge price badgeInfo :: BadgeInfo, paymentVia :: ServicePaymentMethod, upgrade :: Maybe BadgeUpgrade -- upgrade non-store badge } - | BSCRedeemBadgeCode + | STCRedeemBadgeCode { masterKey :: BadgeMasterKey, code :: Text -- no badgeRequest: a code carries no tier for the client to state } - | BSCPurchaseBadge + | STCPurchaseBadge { masterKey :: BadgeMasterKey, -- no badgeRequest: the tier is the product's, the expiry the one every credential of that week shares payment :: ServicePayment, upgrade :: Maybe BadgeUpgrade -- upgrade store 1-time badge } - | BSCUpgradeBadgeSubscription + | STCUpgradeBadgeSubscription { payment :: ServicePayment, -- names the subscription and the tier to wait for; the store's answer is what is granted balance :: BadgeBalance } - | BSCTransferBadge + | STCTransferBadge { masterKey :: BadgeMasterKey, payment :: ServicePayment -- the store receipt of the subscription to move to the signing key } - | BSCIssueBadge + | STCIssueBadge { balance :: BadgeBalance -- no badgeRequest: the service holds the key, the tier and the expiry } - | BSCPauseBadge + | STCPauseBadge data BadgeUpgrade = BadgeUpgrade { fromPurchaseKey :: C.PublicKeyEd25519, @@ -112,24 +112,24 @@ data BadgeUpgrade = BadgeUpgrade balance :: BadgeBalance } -data BadgeServiceResponse - = BSPBadgeCatalog +data StoreServiceResponse + = STPBadgeCatalog { catalog :: BadgeCatalog, badgeStatement :: Maybe BadgeStatement -- for signed getBadgeCatalog } - | BSPBadgeInvoice + | STPBadgeInvoice { invoice :: ServiceInvoice, badgeType :: BadgeType, months :: Word8 } - | BSPBadgeCredential + | STPBadgeCredential { credential :: Maybe BadgeCredential, -- Nothing when no balance to issueBadge or no current credential for pause receipt :: Maybe Text, -- not provided for lifetime badges statement :: BadgeStatement, subscription :: Maybe SubscriptionState -- present exactly when a store subscription funds the purchase } - | BSPError - { code :: BadgeServiceErrorCode, + | STPError + { code :: StoreServiceErrorCode, message :: Maybe Text, retryAfter :: Maybe Word32 } @@ -251,9 +251,9 @@ $(JQ.deriveJSON defaultJSON ''BadgeBalance) $(JQ.deriveJSON defaultJSON ''BadgeUpgrade) -$(JQ.deriveJSON (taggedObjectJSON $ dropPrefix "BSC") ''BadgeServiceCommand) +$(JQ.deriveJSON (taggedObjectJSON $ dropPrefix "STC") ''StoreServiceCommand) -$(JQ.deriveJSON defaultJSON ''BadgeServiceRequest) +$(JQ.deriveJSON defaultJSON ''StoreServiceRequest) $(JQ.deriveJSON defaultJSON ''BadgePrice) @@ -261,4 +261,4 @@ $(JQ.deriveJSON defaultJSON ''BadgeOffer) $(JQ.deriveJSON defaultJSON ''BadgeCatalog) -$(JQ.deriveJSON (taggedObjectJSON $ dropPrefix "BSP") ''BadgeServiceResponse) +$(JQ.deriveJSON (taggedObjectJSON $ dropPrefix "STP") ''StoreServiceResponse) diff --git a/src/Simplex/Chat/View.hs b/src/Simplex/Chat/View.hs index 0b81664348..67e895d1bc 100644 --- a/src/Simplex/Chat/View.hs +++ b/src/Simplex/Chat/View.hs @@ -41,11 +41,11 @@ import Numeric (showFFloat) import Simplex.Chat.Call import Simplex.Chat.Controller import Simplex.Chat.Help -import Simplex.Chat.Library.Commands (badgeServiceErrorText, maxImageSize) +import Simplex.Chat.Library.Commands (maxImageSize, storeServiceErrorText) import Simplex.Chat.Markdown import Simplex.Chat.Badges (BadgeInfo (..), BadgeStatus (..), BadgeType (..), LocalBadge, localBadgeInfo, localBadgeStatus) import Simplex.Chat.Badges.Ledger (creditTypeTag, debitTypeTag) -import Simplex.Chat.Badges.Service (StatementEntry (..), StatementEntryType (..)) +import Simplex.Chat.StoreService (StatementEntry (..), StatementEntryType (..)) import Simplex.Chat.Badges.Types (BadgeAlert (..), BadgeIssueError (..), BadgeState (..), BadgeSubscription (..), OpenStorePurchase (..)) import Simplex.Chat.Messages hiding (NewChatItem (..)) import Simplex.Chat.Messages.CIContent @@ -2946,10 +2946,10 @@ viewChatError isCmd logLevel testView = \case let reason = case e of BREInvalidCode -> "invalid code" BREInvalidReceipt -> "invalid store receipt" - BREServiceNotConfigured -> "badge service not configured" + BREServiceNotConfigured -> "store service not configured" BREBadgeActive -> "badge already active" BREStorePurchaseOpen -> "store purchase open" - BREServiceError code -> "badge service error: " <> T.unpack (badgeServiceErrorText code) + BREServiceError code -> "store service error: " <> T.unpack (storeServiceErrorText code) BREInvalidResponse m -> "invalid service response: " <> m BREUnknownKeyIndex -> "credential names an unknown badge key index" BRECredentialNotVerified -> "credential does not verify against configured key" diff --git a/tests/BadgeTests.hs b/tests/BadgeTests.hs index ac83848b47..507c477f32 100644 --- a/tests/BadgeTests.hs +++ b/tests/BadgeTests.hs @@ -9,9 +9,9 @@ module BadgeTests (badgeTests) where -import BadgeService.Service (NotGranted (..), badgeErrorRetryAfter, grantableCharge, shownServiceRequest, survive) -import BadgeService.StoreReceipts (StoreCharge (..), StoreChecks (..), StoreReceipt (..), StoreRefusal (..), StoreVerifier (..), SubscriptionCheck (..), VerifiedStoreTransaction (..), toStoreReceipt) -import BadgeService.StoreReceipts.Mock (newMockStoreVerifier) +import StoreService.Service (NotGranted (..), badgeErrorRetryAfter, grantableCharge, shownServiceRequest, survive) +import StoreService.StoreReceipts (StoreCharge (..), StoreChecks (..), StoreReceipt (..), StoreRefusal (..), StoreVerifier (..), SubscriptionCheck (..), VerifiedStoreTransaction (..), toStoreReceipt) +import StoreService.StoreReceipts.Mock (newMockStoreVerifier) import Control.Concurrent (forkIO, killThread, threadDelay) import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar) import Control.Concurrent.STM (atomically) @@ -36,12 +36,12 @@ import qualified Simplex.Messaging.Crypto as C import Simplex.Chat.Badges import Simplex.Chat.Badges.Code import Simplex.Chat.Badges.Ledger -import Simplex.Chat.Badges.Service +import Simplex.Chat.StoreService import Simplex.Chat.Badges.Types (BadgeAlertKind (..), BadgeIssueError (..), BadgeIssueFailure (..), BadgeSubscription (..)) import qualified Simplex.Chat.Badges.Types as BT import Simplex.Chat (defaultChatConfig) import Simplex.Chat.Controller (BadgeRedeemError (..), ChatError (..), ChatErrorType (..), badgeRetryInterval, chatErrorAgent) -import Simplex.Chat.Library.Commands (badgeErrorRetry, badgeFailureTransient, badgeIssueFailure, badgeRenewal, badgeRetryAfter, badgeServiceErrorText, badgeStalledInterval, boundedSubscriptionState, derivedBadgeAlert, resumableCharge, resumeHoldEnded, storeTransactionRef) +import Simplex.Chat.Library.Commands (badgeErrorRetry, badgeFailureTransient, badgeIssueFailure, badgeRenewal, badgeRetryAfter, badgeStalledInterval, boundedSubscriptionState, derivedBadgeAlert, resumableCharge, resumeHoldEnded, storeServiceErrorText, storeTransactionRef) import Simplex.Chat.PaymentService (AppleTransactionFacts (..), ServicePayment (..), appleTransactionFacts, appleTransactionRef) import Simplex.Chat.PaymentService.Types (InvoiceId (..), PaymentProvider (..), StoreTransactionRef (..)) import qualified Simplex.Chat.Store.Badges as SB @@ -136,7 +136,7 @@ badgeTests = do it "refuses for good a Play product id that could name another purchase, before any verifier" testGoogleProductIdPath it "does not send a Play token that could name another purchase, and leaves it retryable" testGoogleTokenPath it "has the dev mock vouch for the transaction its claim names, as a production purchase" testMockVouchesForClaim - describe "badge service request loop" $ do + describe "store service request loop" $ do it "survives a request that throws, and still stops when cancelled" testSurviveRequestFailure proofOf :: BadgeProof -> BBSProof @@ -936,7 +936,7 @@ testRetryClassification = do -- terminal: the same request would fail the same way, and repeating it would spin retryFor (AGENT (A_SERVICE ASEBadSignature)) `shouldBe` False retryFor (AGENT (A_SERVICE (ASERejected "no"))) `shouldBe` False - badgeErrorRetry (ChatError (CECommandError "unexpected badge service response")) `shouldBe` False + badgeErrorRetry (ChatError (CECommandError "unexpected store service response")) `shouldBe` False -- A failure that never clears is repeated for as long as the balance funds a month, so the wait -- has to grow: at a fixed interval an annual code would ask hundreds of times a day, all year. @@ -975,15 +975,15 @@ testServiceRetryFloor = do -- schedule, so the set is the protocol's and not a judgement to make per call site. testServiceRetryAfter :: IO () testServiceRetryAfter = do - badgeErrorRetryAfter BSEPaymentPending `shouldBe` Just 300 - badgeErrorRetryAfter BSEProviderUnavailable `shouldBe` Just 300 - badgeErrorRetryAfter BSERateLimited `shouldBe` Just 60 + badgeErrorRetryAfter STEPaymentPending `shouldBe` Just 300 + badgeErrorRetryAfter STEProviderUnavailable `shouldBe` Just 300 + badgeErrorRetryAfter STERateLimited `shouldBe` Just 60 -- internal is the one most likely to clear on its own, and is still terminal: repeating it on -- the service's cadence presses a service already failing, and the client has its own floor - badgeErrorRetryAfter BSEInternal `shouldBe` Nothing + badgeErrorRetryAfter STEInternal `shouldBe` Nothing mapM_ (\code -> badgeErrorRetryAfter code `shouldBe` Nothing) - [BSEBadRequest, BSEUnsupportedVersion, BSEUnknownPurchaseKey, BSECodeInvalid, BSECodeUsed, BSECodeExpired, BSEProviderNotConfigured, BSETestPurchase, BSETransferLimited, BSEUnknown "future_code"] + [STEBadRequest, STEUnsupportedVersion, STEUnknownPurchaseKey, STECodeInvalid, STECodeUsed, STECodeExpired, STEProviderNotConfigured, STETestPurchase, STETransferLimited, STEUnknown "future_code"] -- The app shows the recorded failure in a sentence, so an agent error is stored as the agent -- error and not as the chat error wrapping it, whether or not it can clear on its own. @@ -995,7 +995,7 @@ testIssueFailureClassification = do failureFor (AGENT (A_SERVICE ASETimeout)) `shouldBe` BIFServiceTimeout failureFor timeout `shouldBe` BIFNetwork {agentError = tshow timeout} failureFor auth `shouldBe` BIFUnexpected {message = tshow auth} - badgeIssueFailure (ChatError (CECommandError "unexpected badge service response")) `shouldBe` BIFUnexpected {message = "unexpected badge service response"} + badgeIssueFailure (ChatError (CECommandError "unexpected store service response")) `shouldBe` BIFUnexpected {message = "unexpected store service response"} badgeIssueFailure (ChatError (CEBadgeRedeemError BREUnknownKeyIndex)) `shouldBe` BIFInvalidCredential badgeIssueFailure (ChatError (CEBadgeRedeemError BRECredentialNotVerified)) `shouldBe` BIFInvalidCredential @@ -1004,11 +1004,11 @@ testIssueFailureClassification = do -- final, so it waits the same way; any other refusal is told at once. testServiceErrorTransience :: IO () testServiceErrorTransience = do - badgeFailureTransient BIFServiceError {code = BSERateLimited, retryable = True} `shouldBe` True - badgeFailureTransient BIFServiceError {code = BSEInternal, retryable = False} `shouldBe` True - badgeFailureTransient BIFServiceError {code = BSEUnknownPurchaseKey, retryable = False} `shouldBe` False - badgeFailureTransient BIFServiceError {code = BSEUnknown "future_code", retryable = False} `shouldBe` False - badgeFailureTransient BIFServiceError {code = BSEUnknown "future_code", retryable = True} `shouldBe` True + badgeFailureTransient BIFServiceError {code = STERateLimited, retryable = True} `shouldBe` True + badgeFailureTransient BIFServiceError {code = STEInternal, retryable = False} `shouldBe` True + badgeFailureTransient BIFServiceError {code = STEUnknownPurchaseKey, retryable = False} `shouldBe` False + badgeFailureTransient BIFServiceError {code = STEUnknown "future_code", retryable = False} `shouldBe` False + badgeFailureTransient BIFServiceError {code = STEUnknown "future_code", retryable = True} `shouldBe` True -- The failure is stored as text and read back by getBadgePurchase, so every value this version -- writes must read back as itself, and any other value must still read: a row it cannot parse @@ -1017,20 +1017,20 @@ testIssueFailureEncoding :: IO () testIssueFailureEncoding = do mapM_ (\f -> strDecode (strEncode f) `shouldBe` Right f) - [ BIFServiceError {code = BSEUnknownPurchaseKey, retryable = False}, - BIFServiceError {code = BSERateLimited, retryable = True}, - BIFServiceError {code = BSEUnknown "future_code", retryable = True}, - BIFServiceError {code = BSEUnknown "code with spaces", retryable = False}, - BIFServiceError {code = BSEUnknown "", retryable = False}, + [ BIFServiceError {code = STEUnknownPurchaseKey, retryable = False}, + BIFServiceError {code = STERateLimited, retryable = True}, + BIFServiceError {code = STEUnknown "future_code", retryable = True}, + BIFServiceError {code = STEUnknown "code with spaces", retryable = False}, + BIFServiceError {code = STEUnknown "", retryable = False}, BIFServiceTimeout, BIFNetwork {agentError = "BROKER \"smp://x\" NETWORK"}, BIFInvalidCredential, - BIFUnexpected {message = "unexpected badge service response"}, + BIFUnexpected {message = "unexpected store service response"}, BIFUnexpected {message = "several words and : punctuation"} ] -- the row the CLI prints, and what a reader of the database sees - strEncode BIFServiceError {code = BSECodeUsed, retryable = False} `shouldBe` "service_error final code_used" - strEncode BIFServiceError {code = BSERateLimited, retryable = True} `shouldBe` "service_error retry rate_limited" + strEncode BIFServiceError {code = STECodeUsed, retryable = False} `shouldBe` "service_error final code_used" + strEncode BIFServiceError {code = STERateLimited, retryable = True} `shouldBe` "service_error retry rate_limited" strEncode BIFServiceTimeout `shouldBe` "service_timeout" -- a row a later version wrote, or one edited by hand, still reads - as the text it holds strDecode "future_failure with text" `shouldBe` Right BIFUnexpected {message = "future_failure with text"} @@ -1041,11 +1041,11 @@ testIssueFailureEncoding = do -- a sentence of its own - so it is bounded and stripped of anything but a code before it is stored. testServiceErrorCodeBounded :: IO () testServiceErrorCodeBounded = do - badgeServiceErrorText BSECodeUsed `shouldBe` "code_used" - badgeServiceErrorText (BSEUnknown "future_code") `shouldBe` "future_code" - badgeServiceErrorText (BSEUnknown "two words") `shouldBe` "twowords" - badgeServiceErrorText (BSEUnknown (T.replicate 100 "a")) `shouldBe` T.replicate 32 "a" - badgeServiceErrorText (BSEUnknown "Visit evil.example.com!") `shouldBe` "isitevilexamplecom" + storeServiceErrorText STECodeUsed `shouldBe` "code_used" + storeServiceErrorText (STEUnknown "future_code") `shouldBe` "future_code" + storeServiceErrorText (STEUnknown "two words") `shouldBe` "twowords" + storeServiceErrorText (STEUnknown (T.replicate 100 "a")) `shouldBe` T.replicate 32 "a" + storeServiceErrorText (STEUnknown "Visit evil.example.com!") `shouldBe` "isitevilexamplecom" -- The client replicates entry_credit_type / entry_debit_type verbatim, so a stored tag that -- disagreed with the wire tag would put a different row on each side. @@ -1101,7 +1101,7 @@ testRedeemRequestJSON = do mk <- generateMasterKey drg (k, _) <- atomically $ C.generateKeyPair drg :: IO (C.KeyPair 'C.Ed25519) code <- randomBadgeCode drg - let req = BadgeServiceRequest {version = Version 1, purchaseKey = Just k, request = BSCRedeemBadgeCode {masterKey = mk, code = badgeCodeText code}} + let req = StoreServiceRequest {version = Version 1, purchaseKey = Just k, request = STCRedeemBadgeCode {masterKey = mk, code = badgeCodeText code}} J.toJSON req `shouldBe` J.object [ "version" J..= (1 :: Int), @@ -1109,7 +1109,7 @@ testRedeemRequestJSON = do "request" J..= J.object ["type" J..= ("redeemBadgeCode" :: T.Text), "masterKey" J..= mk, "code" J..= badgeCodeText code] ] -- purchaseKey is optional in the schema, and a nullary command is a bare tagged object - J.toJSON BadgeServiceRequest {version = Version 1, purchaseKey = Nothing, request = BSCGetBadgeCatalog} + J.toJSON StoreServiceRequest {version = Version 1, purchaseKey = Nothing, request = STCGetBadgeCatalog} `shouldBe` J.object ["version" J..= (1 :: Int), "request" J..= J.object ["type" J..= ("getBadgeCatalog" :: T.Text)]] roundTrips req @@ -1119,7 +1119,7 @@ testPurchaseRequestJSON = do mk <- generateMasterKey drg (k, _) <- atomically $ C.generateKeyPair drg :: IO (C.KeyPair 'C.Ed25519) let payment = SPGoogle {productId = "badge_supporter_01", token = "token"} - req = BadgeServiceRequest {version = Version 1, purchaseKey = Just k, request = BSCPurchaseBadge {masterKey = mk, payment, upgrade = Nothing}} + req = StoreServiceRequest {version = Version 1, purchaseKey = Just k, request = STCPurchaseBadge {masterKey = mk, payment, upgrade = Nothing}} -- the client states its master key and the store's evidence, and nothing a receipt already decides J.toJSON req `shouldBe` J.object @@ -1233,13 +1233,13 @@ testShownServiceRequest = do drg <- C.newRandom mk <- generateMasterKey drg (k, _) <- atomically $ C.generateKeyPair drg :: IO (C.KeyPair 'C.Ed25519) - let shown request = case J.toJSON BadgeServiceRequest {version = Version 1, purchaseKey = Just k, request} of + let shown request = case J.toJSON StoreServiceRequest {version = Version 1, purchaseKey = Just k, request} of J.Object o -> J.Object (shownServiceRequest o) _ -> J.Null typeOnly t = J.object ["request" J..= J.object ["type" J..= (t :: T.Text)]] - shown BSCPurchaseBadge {masterKey = mk, payment = SPApple {jws = "a.b.c"}, upgrade = Nothing} `shouldBe` typeOnly "purchaseBadge" - shown BSCRedeemBadgeCode {masterKey = mk, code = "SB-00000-00000-00000-00001"} `shouldBe` typeOnly "redeemBadgeCode" - shown BSCTransferBadge {masterKey = mk, payment = SPApple {jws = "a.b.c"}} `shouldBe` typeOnly "transferBadge" + shown STCPurchaseBadge {masterKey = mk, payment = SPApple {jws = "a.b.c"}, upgrade = Nothing} `shouldBe` typeOnly "purchaseBadge" + shown STCRedeemBadgeCode {masterKey = mk, code = "SB-00000-00000-00000-00001"} `shouldBe` typeOnly "redeemBadgeCode" + shown STCTransferBadge {masterKey = mk, payment = SPApple {jws = "a.b.c"}} `shouldBe` typeOnly "transferBadge" testGoogleProductIdPath :: IO () testGoogleProductIdPath = do @@ -1298,7 +1298,7 @@ testCredentialResponseJSON = do mk <- generateMasterKey drg let info = BadgeInfo {badgeType = BTSupporter, badgeExpiry = futureTime, badgeExtra = ""} Right cred <- issueBadge testKeyIdx sk (VerifiedBadgeRequest BadgeRequest {masterKey = mk, badgeInfo = info}) - let resp = BSPBadgeCredential {credential = Just cred, receipt = Nothing, statement = BadgeStatement {entries = [], previousEntryId = Nothing}, subscription = Nothing} + let resp = STPBadgeCredential {credential = Just cred, receipt = Nothing, statement = BadgeStatement {entries = [], previousEntryId = Nothing}, subscription = Nothing} J.toJSON resp `shouldBe` J.object [ "type" J..= ("badgeCredential" :: T.Text), @@ -1313,7 +1313,7 @@ testCredentialSubscriptionJSON = do mapM_ (\(s, t) -> (J.toJSON s, J.fromJSON (J.String t)) `shouldBe` (J.String t, J.Success s)) states let response subscription_ = J.object $ ["type" J..= ("badgeCredential" :: T.Text), "statement" J..= J.object ["entries" J..= ([] :: [J.Value])]] <> maybe [] (\s -> ["subscription" J..= (s :: T.Text)]) subscription_ subscriptionOf v = case J.fromJSON v of - J.Success BSPBadgeCredential {subscription} -> Right subscription + J.Success STPBadgeCredential {subscription} -> Right subscription J.Success _ -> Left "not a badgeCredential" J.Error e -> Left e subscriptionOf (response Nothing) `shouldBe` Right Nothing @@ -1321,7 +1321,7 @@ testCredentialSubscriptionJSON = do -- a state added by a newer service does not fail the response, and is not read as ended subscriptionOf (response (Just "paused")) `shouldBe` Right (Just (SSUnknown "paused")) J.toJSON (SSUnknown "paused") `shouldBe` J.String "paused" - let resp = BSPBadgeCredential {credential = Nothing, receipt = Nothing, statement = BadgeStatement {entries = [], previousEntryId = Nothing}, subscription = Just SSRenewing} + let resp = STPBadgeCredential {credential = Nothing, receipt = Nothing, statement = BadgeStatement {entries = [], previousEntryId = Nothing}, subscription = Just SSRenewing} J.toJSON resp `shouldBe` response (Just "renewing") roundTrips resp @@ -1365,7 +1365,7 @@ testSubscriptionAlertDerivation = do ends = addMonths 1 start balance = grant start 1 (newBalance start) failedAt = at 2026 3 20 - failure = BadgeIssueError {failedSince = failedAt, lastAttemptAt = failedAt, reason = BIFServiceError {code = BSEUnknownPurchaseKey, retryable = False}} + failure = BadgeIssueError {failedSince = failedAt, lastAttemptAt = failedAt, reason = BIFServiceError {code = STEUnknownPurchaseKey, retryable = False}} early = addUTCTime (-10 * nominalDay) ends soon = addUTCTime (-nominalDay) ends past = addUTCTime nominalDay ends @@ -1419,9 +1419,9 @@ testSubscriptionAlertDerivation = do testErrorResponseJSON :: IO () testErrorResponseJSON = do - let resp = BSPError {code = BSECodeInvalid, message = Nothing, retryAfter = Nothing} + let resp = STPError {code = STECodeInvalid, message = Nothing, retryAfter = Nothing} J.toJSON resp `shouldBe` J.object ["type" J..= ("error" :: T.Text), "code" J..= ("code_invalid" :: T.Text)] - J.toJSON BSPError {code = BSERateLimited, message = Just "slow down", retryAfter = Just 30} + J.toJSON STPError {code = STERateLimited, message = Just "slow down", retryAfter = Just 30} `shouldBe` J.object ["type" J..= ("error" :: T.Text), "code" J..= ("rate_limited" :: T.Text), "message" J..= ("slow down" :: T.Text), "retryAfter" J..= (30 :: Int)] testStatementJSON :: IO () diff --git a/tests/Bots/BadgeService/BTCPayTests.hs b/tests/Bots/StoreService/BTCPayTests.hs similarity index 99% rename from tests/Bots/BadgeService/BTCPayTests.hs rename to tests/Bots/StoreService/BTCPayTests.hs index b2f93250cc..edd164c046 100644 --- a/tests/Bots/BadgeService/BTCPayTests.hs +++ b/tests/Bots/StoreService/BTCPayTests.hs @@ -3,10 +3,10 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -module Bots.BadgeService.BTCPayTests (badgeBTCPayTests) where +module Bots.StoreService.BTCPayTests (badgeBTCPayTests) where -import BadgeService.Config (BTCPayConfig (..)) -import BadgeService.Providers +import StoreService.Config (BTCPayConfig (..)) +import StoreService.Providers ( Funded (..), ListPass (..), OrderDraft (..), @@ -18,8 +18,8 @@ import BadgeService.Providers WebhookError (..), settleWindow, ) -import BadgeService.Providers.BTCPay (btcMethodId, btcpayProvider, listSignals, minorToDecimal, paymentMethodsSignal, verifyBTCPaySig, xmrMethodId) -import Bots.BadgeService.FakeBTCPay +import StoreService.Providers.BTCPay (btcMethodId, btcpayProvider, listSignals, minorToDecimal, paymentMethodsSignal, verifyBTCPaySig, xmrMethodId) +import Bots.StoreService.FakeBTCPay import Control.Exception (evaluate) import Control.Monad (join) import Data.Aeson ((.=)) diff --git a/tests/Bots/BadgeService/BotTests.hs b/tests/Bots/StoreService/BotTests.hs similarity index 92% rename from tests/Bots/BadgeService/BotTests.hs rename to tests/Bots/StoreService/BotTests.hs index dc1d264545..30872eb868 100644 --- a/tests/Bots/BadgeService/BotTests.hs +++ b/tests/Bots/StoreService/BotTests.hs @@ -9,23 +9,23 @@ {-# LANGUAGE TupleSections #-} {-# OPTIONS_GHC -fno-warn-ambiguous-fields #-} -module Bots.BadgeService.BotTests where +module Bots.StoreService.BotTests where -import BadgeService.Codes (issueOneCode) -import BadgeService.Config (AppleStoreConfig (..), BadgeIssuerKey (..), PlayStoreConfig (..), ServiceConfig (..), readServiceConfig) -import BadgeService.Group (GroupEvent) -import BadgeService.StoreReceipts.Apple (appleSubscriptionChecker, verifyAppleTransaction) -import Bots.BadgeService.ConfigTests (withIssuer) -import Bots.BadgeService.FakeAppStore (FakeAppStore (..), withFakeAppStore) -import Bots.BadgeService.FakePlay (FakePlay (..), PlayAnswer (..), answerPurchase, withFakePlay) -import Bots.BadgeService.FakeStore -import Bots.BadgeService.StoreVerifierTests (TestChain (..), basePlan, lineItem, ourBundleId, purchaseRecord, signedBy, subscriptionPayload, subscriptionRecord, transactionPayload, trustedChain) -import BadgeService.Options -import BadgeService.Service -import BadgeService.Store (IssuedCode (..), getBadgeCode) -import BadgeService.Store.Invoices (markCodePaid, truncateToSecond) -import BadgeService.StoreReceipts (StoreCharge (..), StoreChecks (..), StoreRefusal (..), StoreVerifier (..), SubscriptionCheck (..), SubscriptionRef (..), checkStoreSubscription, noStoreVerifier) -import BadgeService.StoreReceipts.Mock (newMockStoreVerifier) +import StoreService.Codes (issueOneCode) +import StoreService.Config (AppleStoreConfig (..), BadgeIssuerKey (..), PlayStoreConfig (..), ServiceConfig (..), readServiceConfig) +import StoreService.Group (GroupEvent) +import StoreService.StoreReceipts.Apple (appleSubscriptionChecker, verifyAppleTransaction) +import Bots.StoreService.ConfigTests (withIssuer) +import Bots.StoreService.FakeAppStore (FakeAppStore (..), withFakeAppStore) +import Bots.StoreService.FakePlay (FakePlay (..), PlayAnswer (..), answerPurchase, withFakePlay) +import Bots.StoreService.FakeStore +import Bots.StoreService.StoreVerifierTests (TestChain (..), basePlan, lineItem, ourBundleId, purchaseRecord, signedBy, subscriptionPayload, subscriptionRecord, transactionPayload, trustedChain) +import StoreService.Options +import StoreService.Service +import StoreService.Store (IssuedCode (..), getBadgeCode) +import StoreService.Store.Invoices (markCodePaid, truncateToSecond) +import StoreService.StoreReceipts (StoreCharge (..), StoreChecks (..), StoreRefusal (..), StoreVerifier (..), SubscriptionCheck (..), SubscriptionRef (..), checkStoreSubscription, noStoreVerifier) +import StoreService.StoreReceipts.Mock (newMockStoreVerifier) import Simplex.Messaging.Agent.Store.DB (Binary (..)) import qualified Simplex.Messaging.Agent.Store.DB as DB import ChatClient @@ -62,7 +62,7 @@ import Simplex.Chat.Badges (BadgeCredential (..), BadgeInfo (..), BadgeMasterKey import Simplex.Chat.Badges.Code (BadgeCode, badgeCodeHash, badgeCodeText, formatBadgeCode, parseBadgeCode, randomBadgeCode) import Simplex.Chat.Badges.Ledger (addMonths, balanceChecked, creditTypeTag, debitTypeTag, emptyEntry, endOfMondayAfter) import qualified Simplex.Chat.Badges.Ledger as L -import Simplex.Chat.Badges.Service +import Simplex.Chat.StoreService import Simplex.Chat.Badges.Types (BadgeCodePaymentStatus (..)) import qualified Simplex.Chat.Badges.Types as BT import Simplex.Chat.Bot.Store (withDB') @@ -96,9 +96,9 @@ import Database.SQLite.Simple (Only (..)) #endif import Test.Hspec hiding (it) -badgeServiceTests :: SpecWith TestParams -badgeServiceTests = do - it "should answer unsupported_version to unsupported command" testBadgeServiceUnsupported +storeServiceTests :: SpecWith TestParams +storeServiceTests = do + it "should answer unsupported_version to unsupported command" testStoreServiceUnsupported it "should redeem an issued code into a badge a contact sees" testRedeemBadgeCode it "should return the same badge when the same code is redeemed twice" testRedeemBadgeCodeTwice it "should answer code_invalid to an unknown code, indistinguishably from a malformed one" testRedeemUnknownCode @@ -328,9 +328,9 @@ serviceDbPrefix = "badge_service" testIssuerKeyIdx :: Int testIssuerKeyIdx = 1 -mkBadgeServiceOpts :: TestParams -> BBSSecretKey -> BadgeServiceOpts -mkBadgeServiceOpts ps secretKey = - BadgeServiceOpts +mkStoreServiceOpts :: TestParams -> BBSSecretKey -> StoreServiceOpts +mkStoreServiceOpts ps secretKey = + StoreServiceOpts { coreOptions = coreOpts { dbOptions = @@ -366,7 +366,7 @@ testClockTime (TestClock r) = do setClockAt :: TestClock -> UTCTime -> IO () setClockAt (TestClock r) t = getCurrentTime >>= \real -> writeIORef r (diffUTCTime t real) -data BadgeServiceEnv = BadgeServiceEnv +data StoreServiceEnv = StoreServiceEnv { bsIssuerKey :: BadgeIssuerKey, bsClock :: TestClock, bsClientCfg :: ChatConfig, @@ -379,32 +379,32 @@ data BadgeServiceEnv = BadgeServiceEnv -- | Stop the service for good: requests sent after it go unanswered until they time out. Stopping -- chat unsubscribes its queues, where killing the thread could still let a request arrive mid-teardown. -stopBadgeService :: ChatController -> IO () -stopBadgeService cc = void $ sendChatCmdStr cc "/_stop" +stopStoreService :: ChatController -> IO () +stopStoreService cc = void $ sendChatCmdStr cc "/_stop" -withBadgeService :: HasCallStack => TestParams -> (ChatConfig -> String -> ChatController -> IO ()) -> IO () -withBadgeService ps test = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClientCfg, bsAddress, bsController} -> test bsClientCfg bsAddress bsController +withStoreService :: HasCallStack => TestParams -> (ChatConfig -> String -> ChatController -> IO ()) -> IO () +withStoreService ps test = + withStoreServiceEnv ps $ \StoreServiceEnv {bsClientCfg, bsAddress, bsController} -> test bsClientCfg bsAddress bsController -withBadgeServiceEnv :: HasCallStack => TestParams -> (BadgeServiceEnv -> IO ()) -> IO () -withBadgeServiceEnv ps = withBadgeServiceVerifier ps fakeVerifier +withStoreServiceEnv :: HasCallStack => TestParams -> (StoreServiceEnv -> IO ()) -> IO () +withStoreServiceEnv ps = withStoreServiceVerifier ps fakeVerifier -withBadgeServiceVerifier :: HasCallStack => TestParams -> (FakeStore -> StoreVerifier) -> (BadgeServiceEnv -> IO ()) -> IO () -withBadgeServiceVerifier ps verifierOf = withBadgeServiceVerifierIO ps (\_ store -> pure $ verifierOf store) +withStoreServiceVerifier :: HasCallStack => TestParams -> (FakeStore -> StoreVerifier) -> (StoreServiceEnv -> IO ()) -> IO () +withStoreServiceVerifier ps verifierOf = withStoreServiceVerifierIO ps (\_ store -> pure $ verifierOf store) -- | For a verifier that reads the service's clock, as the dev mock does. -withBadgeServiceVerifierIO :: HasCallStack => TestParams -> (TestClock -> FakeStore -> IO StoreVerifier) -> (BadgeServiceEnv -> IO ()) -> IO () -withBadgeServiceVerifierIO ps verifierOf test = do +withStoreServiceVerifierIO :: HasCallStack => TestParams -> (TestClock -> FakeStore -> IO StoreVerifier) -> (StoreServiceEnv -> IO ()) -> IO () +withStoreServiceVerifierIO ps verifierOf test = do Right (pk, sk) <- bbsKeyGen clock <- newTestClock store <- newFakeStore verifier <- verifierOf clock store purchaseChecks <- newPurchaseChecks - let opts = mkBadgeServiceOpts ps sk + let opts = mkStoreServiceOpts ps sk svcCfg = testCfg {badgePublicKeys = M.singleton testIssuerKeyIdx pk, badgeCurrentTime = testClockTime clock} withNewTestChatCfg ps testCfg serviceDbPrefix badgeProfile $ \_ -> pure () - -- First start: badge service takes the CreateMyAddress branch. - runBadgeService ps verifier svcCfg opts $ \_ -> pure () + -- First start: store service takes the CreateMyAddress branch. + runStoreService ps verifier svcCfg opts $ \_ -> pure () -- Reopen the DB to read the link the service created. bsLink <- withTestChat ps serviceDbPrefix $ \bs -> do bs <## "subscribed 1 connections on server localhost" @@ -415,11 +415,11 @@ withBadgeServiceVerifierIO ps verifierOf test = do bs <## "auto_accept off" pure sLink let clientCfg = - svcCfg {badgeServiceAddress = Just $ either (error . ("bad badge service address: " <>)) id $ strDecode (B.pack bsLink)} - -- Second start: badge service takes the ShowMyAddress branch, then serves the test body. - runBadgeService ps verifier svcCfg opts $ \env -> do + svcCfg {storeServiceAddress = Just $ either (error . ("bad store service address: " <>)) id $ strDecode (B.pack bsLink)} + -- Second start: store service takes the ShowMyAddress branch, then serves the test body. + runStoreService ps verifier svcCfg opts $ \env -> do cc <- atomically $ readTMVar $ serviceCC env - test BadgeServiceEnv {bsIssuerKey = BadgeIssuerKey {keyIdx = testIssuerKeyIdx, secretKey = sk}, bsClock = clock, bsClientCfg = clientCfg, bsAddress = bsLink, bsController = cc, bsStore = store, bsVerifier = verifier, bsPurchaseChecks = purchaseChecks} + test StoreServiceEnv {bsIssuerKey = BadgeIssuerKey {keyIdx = testIssuerKeyIdx, secretKey = sk}, bsClock = clock, bsClientCfg = clientCfg, bsAddress = bsLink, bsController = cc, bsStore = store, bsVerifier = verifier, bsPurchaseChecks = purchaseChecks} issueCode :: HasCallStack => ChatController -> BadgeType -> Int -> IO BadgeCode issueCode cc badgeType months = issueCodeAs cc badgeType months "free" @@ -446,20 +446,20 @@ issueCodeAs cc badgeType months status = -- | The post-start hook fills serviceCC once the address exists, so waiting on it is the service -- being ready. A fixed delay here raced with startup and left the address output of one start -- arriving during the next test. -runBadgeService :: TestParams -> StoreVerifier -> ChatConfig -> BadgeServiceOpts -> (ServiceState -> IO ()) -> IO () -runBadgeService ps verifier cfg opts action = do +runStoreService :: TestParams -> StoreVerifier -> ChatConfig -> StoreServiceOpts -> (ServiceState -> IO ()) -> IO () +runStoreService ps verifier cfg opts action = do env <- (\s -> s {storeVerifier = verifier}) <$> newServiceState - t <- async $ badgeService opts (fst $ testPortsCfg ps cfg testOpts) env + t <- async $ storeService opts (fst $ testPortsCfg ps cfg testOpts) env ready <- timeout 30000000 $ atomically $ readTMVar $ serviceCC env - when (isNothing ready) $ cancel t >> error "badge service did not start" + when (isNothing ready) $ cancel t >> error "store service did not start" action env `finally` (cancel t >> atomically (readTMVar $ serviceCC env) >>= disposeAgentClient . smpAgent) codeArg :: BadgeCode -> String codeArg = T.unpack . formatBadgeCode -testBadgeServiceUnsupported :: HasCallStack => TestParams -> IO () -testBadgeServiceUnsupported ps = - withBadgeService ps $ \clientCfg bsLink _ -> +testStoreServiceUnsupported :: HasCallStack => TestParams -> IO () +testStoreServiceUnsupported ps = + withStoreService ps $ \clientCfg bsLink _ -> withNewTestChatCfg ps clientCfg "client" bobProfile $ \client -> do let req = "{\"version\":1,\"request\":{\"type\":\"pauseBadge\"}}" client ##> ("/_service_request 1 " <> bsLink <> " " <> req) @@ -467,7 +467,7 @@ testBadgeServiceUnsupported ps = testRedeemBadgeCode :: HasCallStack => TestParams -> IO () testRedeemBadgeCode ps = - withBadgeService ps $ \clientCfg _ cc -> + withStoreService ps $ \clientCfg _ cc -> withNewTestChatCfg ps clientCfg "alice" aliceProfile $ \alice -> withNewTestChatCfg ps clientCfg "bob" bobProfile $ \bob -> do connectUsers alice bob @@ -494,7 +494,7 @@ testRedeemBadgeCode ps = testRedeemBadgeCodeTwice :: HasCallStack => TestParams -> IO () testRedeemBadgeCodeTwice ps = - withBadgeService ps $ \clientCfg _ cc -> + withStoreService ps $ \clientCfg _ cc -> withNewTestChatCfg ps clientCfg "alice" aliceProfile $ \alice -> do code <- issueCode cc BTSupporter 1 alice ##> ("/_redeem_badge_code 1 " <> codeArg code) @@ -509,12 +509,12 @@ testRedeemBadgeCodeTwice ps = testRedeemUnknownCode :: HasCallStack => TestParams -> IO () testRedeemUnknownCode ps = - withBadgeService ps $ \clientCfg bsLink _ -> + withStoreService ps $ \clientCfg bsLink _ -> withNewTestChatCfg ps clientCfg "alice" aliceProfile $ \alice -> do g <- C.newRandom unknown <- randomBadgeCode g alice ##> ("/_redeem_badge_code 1 " <> codeArg unknown) - alice <## "cannot get badge: badge service error: code_invalid" + alice <## "cannot get badge: store service error: code_invalid" -- a failed check character is refused before anything leaves the device alice ##> "/_redeem_badge_code 1 SB-00000-00000-00000-00001" alice <## "cannot get badge: invalid code" @@ -541,7 +541,7 @@ testMasterKeyB64 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" testIssueRejectsBadArguments :: HasCallStack => TestParams -> IO () testIssueRejectsBadArguments ps = - withBadgeService ps $ \_ _ cc -> do + withStoreService ps $ \_ _ cc -> do let refuses arg = issueRaw cc arg >>= (`shouldSatisfy` isLeft) refuses "suporter" refuses "supporter 0" @@ -561,7 +561,7 @@ issueRaw cc args = testRedeemSecondCode :: HasCallStack => TestParams -> IO () testRedeemSecondCode ps = - withBadgeService ps $ \clientCfg _ cc -> + withStoreService ps $ \clientCfg _ cc -> withNewTestChatCfg ps clientCfg "alice" aliceProfile $ \alice -> do supporter <- issueCode cc BTSupporter 1 legend <- issueCode cc BTLegend 1 @@ -582,7 +582,7 @@ testRedeemSecondCode ps = testRedeemSameCodeOtherProfile :: HasCallStack => TestParams -> IO () testRedeemSameCodeOtherProfile ps = - withBadgeService ps $ \clientCfg _ cc -> + withStoreService ps $ \clientCfg _ cc -> withNewTestChatCfg ps clientCfg "alice" aliceProfile $ \alice -> do code <- issueCode cc BTSupporter 1 alice ##> ("/_redeem_badge_code 1 " <> codeArg code) @@ -592,25 +592,25 @@ testRedeemSameCodeOtherProfile ps = alice ##> "/create user alisa" showActiveUser alice "alisa" alice ##> ("/_redeem_badge_code 2 " <> codeArg code) - alice <## "cannot get badge: badge service error: code_used" + alice <## "cannot get badge: store service error: code_used" alice ##> "/p" showActiveUser alice "alisa" alice ##> "/user alice" showActiveUser alice "alice (Alice, * supporter)" -serviceCmd :: HasCallStack => BadgeServiceEnv -> C.PublicKeyEd25519 -> BadgeServiceCommand -> IO BadgeServiceResponse -serviceCmd BadgeServiceEnv {bsIssuerKey, bsController, bsVerifier, bsPurchaseChecks} purchaseKey request = - badgeServiceResponse bsIssuerKey bsVerifier bsPurchaseChecks bsController Nothing (Just purchaseKey) (requestObject purchaseKey request) +serviceCmd :: HasCallStack => StoreServiceEnv -> C.PublicKeyEd25519 -> StoreServiceCommand -> IO StoreServiceResponse +serviceCmd StoreServiceEnv {bsIssuerKey, bsController, bsVerifier, bsPurchaseChecks} purchaseKey request = + storeServiceResponse bsIssuerKey bsVerifier bsPurchaseChecks bsController Nothing (Just purchaseKey) (requestObject purchaseKey request) -serviceCmdWith :: HasCallStack => BadgeIssuerKey -> ChatController -> Maybe (TQueue GroupEvent) -> C.PublicKeyEd25519 -> BadgeServiceCommand -> IO BadgeServiceResponse +serviceCmdWith :: HasCallStack => BadgeIssuerKey -> ChatController -> Maybe (TQueue GroupEvent) -> C.PublicKeyEd25519 -> StoreServiceCommand -> IO StoreServiceResponse serviceCmdWith key cc trackerQ_ purchaseKey request = do checks <- newPurchaseChecks - badgeServiceResponse key noStoreVerifier checks cc trackerQ_ (Just purchaseKey) (requestObject purchaseKey request) + storeServiceResponse key noStoreVerifier checks cc trackerQ_ (Just purchaseKey) (requestObject purchaseKey request) -requestObject :: HasCallStack => C.PublicKeyEd25519 -> BadgeServiceCommand -> J.Object -requestObject purchaseKey request = case J.toJSON BadgeServiceRequest {version = currentBadgeServiceVersion, purchaseKey = Just purchaseKey, request} of +requestObject :: HasCallStack => C.PublicKeyEd25519 -> StoreServiceCommand -> J.Object +requestObject purchaseKey request = case J.toJSON StoreServiceRequest {version = currentStoreServiceVersion, purchaseKey = Just purchaseKey, request} of J.Object o -> o - _ -> error "badge service request must encode as an object" + _ -> error "store service request must encode as an object" entryOf :: StatementEntry -> (Int, Int, UTCTime) entryOf StatementEntry {changeMonths, balanceMonths, balanceStartTs} = (changeMonths, balanceMonths, balanceStartTs) @@ -623,19 +623,19 @@ entryTag StatementEntry {entryType} = case entryType of SECredit c -> creditTypeTag c SEDebit d -> debitTypeTag d -statementOf :: HasCallStack => BadgeServiceResponse -> ([StatementEntry], Maybe Text) +statementOf :: HasCallStack => StoreServiceResponse -> ([StatementEntry], Maybe Text) statementOf = \case - BSPBadgeCredential {statement = BadgeStatement {entries, previousEntryId}} -> (entries, previousEntryId) + STPBadgeCredential {statement = BadgeStatement {entries, previousEntryId}} -> (entries, previousEntryId) r -> error $ "expected badgeCredential, got " <> show (J.toJSON r) -credentialOf :: HasCallStack => BadgeServiceResponse -> Maybe BadgeCredential +credentialOf :: HasCallStack => StoreServiceResponse -> Maybe BadgeCredential credentialOf = \case - BSPBadgeCredential {credential} -> credential + STPBadgeCredential {credential} -> credential r -> error $ "expected badgeCredential, got " <> show (J.toJSON r) -shouldAnswerError :: HasCallStack => BadgeServiceResponse -> BadgeServiceErrorCode -> IO () +shouldAnswerError :: HasCallStack => StoreServiceResponse -> StoreServiceErrorCode -> IO () shouldAnswerError r expected = case r of - BSPError {code = ec} -> ec `shouldBe` expected + STPError {code = ec} -> ec `shouldBe` expected _ -> expectationFailure $ "expected " <> show expected <> ", got: " <> show (J.toJSON r) codeCounts :: DBStore -> ByteString -> IO (Maybe (Int, Int)) @@ -653,33 +653,33 @@ newPurchaseKeys = do (purchaseKey, _) <- atomically $ C.generateKeyPair g :: IO (C.KeyPair 'C.Ed25519) (purchaseKey,) <$> generateMasterKey g -redeemAsNewPurchase :: HasCallStack => BadgeServiceEnv -> BadgeCode -> IO BadgeServiceResponse -redeemAsNewPurchase BadgeServiceEnv {bsIssuerKey, bsController} = redeemWithQueue bsIssuerKey bsController Nothing . badgeCodeText +redeemAsNewPurchase :: HasCallStack => StoreServiceEnv -> BadgeCode -> IO StoreServiceResponse +redeemAsNewPurchase StoreServiceEnv {bsIssuerKey, bsController} = redeemWithQueue bsIssuerKey bsController Nothing . badgeCodeText -redeemWithKeys :: HasCallStack => BadgeServiceEnv -> (C.PublicKeyEd25519, BadgeMasterKey) -> BadgeCode -> IO BadgeServiceResponse -redeemWithKeys env (purchaseKey, masterKey) code = serviceCmd env purchaseKey BSCRedeemBadgeCode {masterKey, code = badgeCodeText code} +redeemWithKeys :: HasCallStack => StoreServiceEnv -> (C.PublicKeyEd25519, BadgeMasterKey) -> BadgeCode -> IO StoreServiceResponse +redeemWithKeys env (purchaseKey, masterKey) code = serviceCmd env purchaseKey STCRedeemBadgeCode {masterKey, code = badgeCodeText code} -redeemWithQueue :: HasCallStack => BadgeIssuerKey -> ChatController -> Maybe (TQueue GroupEvent) -> Text -> IO BadgeServiceResponse +redeemWithQueue :: HasCallStack => BadgeIssuerKey -> ChatController -> Maybe (TQueue GroupEvent) -> Text -> IO StoreServiceResponse redeemWithQueue key cc trackerQ_ codeText = do (purchaseKey, masterKey) <- newPurchaseKeys - serviceCmdWith key cc trackerQ_ purchaseKey BSCRedeemBadgeCode {masterKey, code = codeText} + serviceCmdWith key cc trackerQ_ purchaseKey STCRedeemBadgeCode {masterKey, code = codeText} -assertBalance :: HasCallStack => BadgeServiceEnv -> C.PublicKeyEd25519 -> StatementEntry -> IO BadgeServiceResponse +assertBalance :: HasCallStack => StoreServiceEnv -> C.PublicKeyEd25519 -> StatementEntry -> IO StoreServiceResponse assertBalance env purchaseKey lastEntry = - serviceCmd env purchaseKey BSCIssueBadge {balance = BadgeBalance {lastEntry}} + serviceCmd env purchaseKey STCIssueBadge {balance = BadgeBalance {lastEntry}} -expiryOf :: HasCallStack => BadgeServiceResponse -> Maybe UTCTime +expiryOf :: HasCallStack => StoreServiceResponse -> Maybe UTCTime expiryOf r = (\(BadgeCredential _ _ _ BadgeInfo {badgeExpiry}) -> badgeExpiry) <$> credentialOf r -badgeTypeOf :: HasCallStack => BadgeServiceResponse -> Maybe BadgeType +badgeTypeOf :: HasCallStack => StoreServiceResponse -> Maybe BadgeType badgeTypeOf r = (\(BadgeCredential _ _ _ BadgeInfo {badgeType}) -> badgeType) <$> credentialOf r -masterKeyOf :: HasCallStack => BadgeServiceResponse -> Maybe BadgeMasterKey +masterKeyOf :: HasCallStack => StoreServiceResponse -> Maybe BadgeMasterKey masterKeyOf r = (\(BadgeCredential _ mk _ _) -> mk) <$> credentialOf r testCodeMonthsRenew :: HasCallStack => TestParams -> IO () testCodeMonthsRenew ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsController = cc} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsController = cc} -> do code <- issueCode cc BTSupporter 3 keys@(purchaseKey, _) <- newPurchaseKeys redeemed <- redeemWithKeys env keys code @@ -704,7 +704,7 @@ testCodeMonthsRenew ps = testRepeatInsideIssuedPeriod :: HasCallStack => TestParams -> IO () testRepeatInsideIssuedPeriod ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsController = cc} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsController = cc} -> do code <- issueCode cc BTSupporter 2 keys@(purchaseKey, _) <- newPurchaseKeys redeemed <- redeemWithKeys env keys code @@ -715,7 +715,7 @@ testRepeatInsideIssuedPeriod ps = testMultiUseRepeatAfterExpiry :: HasCallStack => TestParams -> IO () testMultiUseRepeatAfterExpiry ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do code <- issueMultiUseCode cc BTSupporter 1 2 redeemFirstBadge alice code @@ -736,11 +736,11 @@ testMultiUseRepeatAfterExpiry ps = waitShownBadge (chatController alice) Nothing codeUses cc code `shouldReturn` Just (2, 1) withNewTestChatCfg ps bsClientCfg "bob" bobProfile $ \bob -> redeemFirstBadge bob code - redeemAsNewPurchase env code >>= (`shouldAnswerError` BSECodeUsed) + redeemAsNewPurchase env code >>= (`shouldAnswerError` STECodeUsed) testMultiUseWithoutGroup :: HasCallStack => TestParams -> IO () testMultiUseWithoutGroup ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsController = cc} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsController = cc} -> do code <- issueMultiUseCode cc BTLegend 2 2 forM_ [1 :: Int, 2] $ \claimed -> do keys@(_, masterKey) <- newPurchaseKeys @@ -751,22 +751,22 @@ testMultiUseWithoutGroup ps = expiryOf redeemed `shouldBe` Just (endOfMondayAfter (nextDue entries)) masterKeyOf redeemed `shouldBe` Just masterKey codeUses cc code `shouldReturn` Just (2, claimed) - redeemAsNewPurchase env code >>= (`shouldAnswerError` BSECodeUsed) + redeemAsNewPurchase env code >>= (`shouldAnswerError` STECodeUsed) testUnreadableCredentialIsInternal :: HasCallStack => TestParams -> IO () testUnreadableCredentialIsInternal ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsController = cc} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsController = cc} -> do code <- issueMultiUseCode cc BTSupporter 1 2 let redeem keys = redeemWithKeys env keys code holder <- newPurchaseKeys redeem holder >>= (`shouldSatisfy` isJust) . credentialOf withTransaction (chatStore cc) $ \db -> DB.execute db "UPDATE sx_badge_service_badge_issuances SET credential = ?" (Only (Binary ("not a credential" :: ByteString))) - redeem holder >>= (`shouldAnswerError` BSEInternal) + redeem holder >>= (`shouldAnswerError` STEInternal) codeUses cc code `shouldReturn` Just (2, 1) newPurchaseKeys >>= redeem >>= (`shouldSatisfy` isJust) . credentialOf codeUses cc code `shouldReturn` Just (2, 2) - redeem holder >>= (`shouldAnswerError` BSEInternal) + redeem holder >>= (`shouldAnswerError` STEInternal) codeUses cc code `shouldReturn` Just (2, 2) -- Multi-use codes come from the group command, and this service has no group. @@ -778,7 +778,7 @@ issueMultiUseCode cc badgeType months uses = testLapseWhileAway :: HasCallStack => TestParams -> IO () testLapseWhileAway ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsController = cc} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsController = cc} -> do code <- issueCode cc BTSupporter 6 keys@(purchaseKey, _) <- newPurchaseKeys redeemed <- redeemWithKeys env keys code @@ -793,7 +793,7 @@ testLapseWhileAway ps = testLastMonthExpiryRounds :: HasCallStack => TestParams -> IO () testLastMonthExpiryRounds ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsController = cc} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsController = cc} -> do code <- issueCode cc BTSupporter 2 keys@(purchaseKey, _) <- newPurchaseKeys redeemed <- redeemWithKeys env keys code @@ -807,7 +807,7 @@ testLastMonthExpiryRounds ps = testRenewalSignsWithStoredMasterKey :: HasCallStack => TestParams -> IO () testRenewalSignsWithStoredMasterKey ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsController = cc} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsController = cc} -> do code <- issueCode cc BTSupporter 2 keys@(purchaseKey, masterKey) <- newPurchaseKeys redeemed <- redeemWithKeys env keys code @@ -861,7 +861,7 @@ balanceChecks ChatController {chatStore} = testClientReplicatesLedger :: HasCallStack => TestParams -> IO () testClientReplicatesLedger ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do code <- issueCode cc BTSupporter 3 alice ##> ("/_redeem_badge_code 1 " <> codeArg code) @@ -1032,7 +1032,7 @@ waitWakeArmed ChatController {chatStore} = loop (100 :: Int) testWorkerRenews :: HasCallStack => TestParams -> IO () testWorkerRenews ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do code <- issueCode cc BTSupporter 3 redeemFirstBadge alice code @@ -1068,7 +1068,7 @@ testWorkerRenews ps = testLatestIssuedByRow :: HasCallStack => TestParams -> IO () testLatestIssuedByRow ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do code <- issueCode cc BTSupporter 3 redeemFirstBadge alice code @@ -1089,13 +1089,13 @@ testLatestIssuedByRow ps = testRevokedMultiUseHolderRenews :: HasCallStack => TestParams -> IO () testRevokedMultiUseHolderRenews ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do code <- issueMultiUseCode cc BTSupporter 3 2 redeemFirstBadge alice code redeemed <- ledgerRows (chatController alice) "badge_ledger" revokeCodeAs cc code `shouldReturn` Right "Revoked." - redeemAsNewPurchase env code >>= (`shouldAnswerError` BSECodeInvalid) + redeemAsNewPurchase env code >>= (`shouldAnswerError` STECodeInvalid) codeUses cc code `shouldReturn` Just (2, 1) -- A holder whose reply was lost retries with the same key and still gets its badge. alice ##> ("/_redeem_badge_code 1 " <> codeArg code) @@ -1116,7 +1116,7 @@ testRevokedMultiUseHolderRenews ps = testMultiUseHoldersRenewApart :: HasCallStack => TestParams -> IO () testMultiUseHoldersRenewApart ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do code <- issueMultiUseCode cc BTSupporter 3 2 redeemFirstBadge alice code @@ -1161,7 +1161,7 @@ codeRedemptionKey ChatController {chatStore} = do testRequestWakeFires :: HasCallStack => TestParams -> IO () testRequestWakeFires ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do code <- issueCode cc BTSupporter 3 redeemFirstBadge alice code @@ -1175,7 +1175,7 @@ testRequestWakeFires ps = testPresentWakeFires :: HasCallStack => TestParams -> IO () testPresentWakeFires ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do code <- issueCode cc BTSupporter 3 redeemFirstBadge alice code @@ -1192,7 +1192,7 @@ testPresentWakeFires ps = testRenewsAfterUnknownEntry :: HasCallStack => TestParams -> IO () testRenewsAfterUnknownEntry ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do code <- issueCode cc BTSupporter 3 redeemFirstBadge alice code @@ -1210,7 +1210,7 @@ testRenewsAfterUnknownEntry ps = testRenewsAfterRestart :: HasCallStack => TestParams -> IO () testRenewsAfterRestart ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> do + withStoreServiceEnv ps $ \StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> do rows <- withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do code <- issueCode cc BTSupporter 6 redeemFirstBadge alice code @@ -1230,7 +1230,7 @@ testRenewsAfterRestart ps = testWorkerRetiresExpired :: HasCallStack => TestParams -> IO () testWorkerRetiresExpired ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> withNewTestChatCfg ps bsClientCfg "bob" bobProfile $ \bob -> do connectUsers alice bob @@ -1276,7 +1276,7 @@ testWorkerRetiresExpired ps = testRetiresWhenEntitlementEnds :: HasCallStack => TestParams -> IO () testRetiresWhenEntitlementEnds ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do code <- issueCode cc BTSupporter 1 redeemFirstBadge alice code @@ -1292,7 +1292,7 @@ testRetiresWhenEntitlementEnds ps = testEndedAlert :: HasCallStack => TestParams -> IO () testEndedAlert ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> do + withStoreServiceEnv ps $ \StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> do endsAt <- withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do code <- issueCode cc BTSupporter 1 redeemFirstBadge alice code @@ -1325,7 +1325,7 @@ testEndedAlert ps = -- worn and will start showing as expired. testIssueFailedAlert :: HasCallStack => TestParams -> IO () testIssueFailedAlert ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do code <- issueCode cc BTSupporter 3 redeemFirstBadge alice code @@ -1335,7 +1335,7 @@ testIssueFailedAlert ps = setClockAt bsClock $ fst $ renewalMoments rows alice ##> "/_app activate" alice <## "ok" - alice <## badgeServiceRefused + alice <## storeServiceRefused alice <##. "badge alert: issue_failed " -- the state reports the failure, when the next attempt is due, and the alert it raised alice <##. "1: supporter" @@ -1349,13 +1349,13 @@ testIssueFailedAlert ps = -- they stop. It is recorded from the first attempt, so the run's start is not lost. testIssueFailedWaitsForExpiry :: HasCallStack => TestParams -> IO () testIssueFailedWaitsForExpiry ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> do + withStoreServiceEnv ps $ \StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> do -- the redemption runs against the service, so it keeps the ordinary request timeout (requestAt, presentAt) <- withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do code <- issueCode cc BTSupporter 3 redeemFirstBadge alice code renewalMoments <$> ledgerRows (chatController alice) "badge_ledger" - stopBadgeService cc + stopStoreService cc let cfg = failingServiceCfg bsClientCfg -- the request goes unanswered and times out, which is a failure that can clear on its own setClockAt bsClock requestAt @@ -1388,7 +1388,7 @@ testIssueFailedWaitsForExpiry ps = -- screen while the alert goes quiet, and a later run raises it again under a new episode. testIssueFailedAckAndNewRun :: HasCallStack => TestParams -> IO () testIssueFailedAckAndNewRun ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do code <- issueCode cc BTSupporter 3 redeemFirstBadge alice code @@ -1399,7 +1399,7 @@ testIssueFailedAckAndNewRun ps = setClockAt bsClock requestAt alice ##> "/_app activate" alice <## "ok" - alice <## badgeServiceRefused + alice <## storeServiceRefused alice <##. "badge alert: issue_failed " alice <##. "1: supporter" alice <##. "renewal failing since " @@ -1439,7 +1439,7 @@ testIssueFailedAckAndNewRun ps = setClockAt bsClock $ fst $ renewalMoments renewed alice ##> "/_app activate" alice <## "ok" - alice <## badgeServiceRefused + alice <## storeServiceRefused alice <##. "badge alert: issue_failed " alice <##. "1: supporter" alice <##. "renewal failing since " @@ -1454,7 +1454,7 @@ testIssueFailedAckAndNewRun ps = -- credential that was never issued. testNoCredentialMonthsRanOut :: HasCallStack => TestParams -> IO () testNoCredentialMonthsRanOut ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do code <- issueCode cc BTSupporter 3 redeemFirstBadge alice code @@ -1479,7 +1479,7 @@ testNoCredentialMonthsRanOut ps = -- resolve, so it is recorded and told at once. testNoCredentialMonthsLeft :: HasCallStack => TestParams -> IO () testNoCredentialMonthsLeft ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do code <- issueCode cc BTSupporter 3 redeemFirstBadge alice code @@ -1488,13 +1488,13 @@ testNoCredentialMonthsLeft ps = setClockAt bsClock $ snd $ renewalMoments rows alice ##> "/_app activate" alice <## "ok" - alice <## "internal chat error: badge service issued no credential" + alice <## "internal chat error: store service issued no credential" alice <##. "badge alert: issue_failed " alice <##. "1: supporter" alice <##. "renewal failing since " alice <##. "badge alert: issue_failed " (_, reason) <- issueErrorRow (chatController alice) - reason `shouldBe` Just "unexpected badge service issued no credential" + reason `shouldBe` Just "unexpected store service issued no credential" -- | A debit the service wrote on its own, taking back the months the purchase had: copied from -- the tip so that it follows it in every column the client checks. @@ -1515,8 +1515,8 @@ zeroServiceLedgerTip ChatController {chatStore} = withTransaction chatStore $ \db -> DB.execute_ db "UPDATE sx_badge_service_badge_ledger SET balance_months = 0 WHERE entry_id = (SELECT MAX(entry_id) FROM sx_badge_service_badge_ledger)" -badgeServiceRefused :: String -badgeServiceRefused = "bad chat command: badge service error: unknown_purchase_key" +storeServiceRefused :: String +storeServiceRefused = "bad chat command: store service error: unknown_purchase_key" -- | The alert's episode is the start of the run of failures, as the ack command spells it. episodeOf :: HasCallStack => Maybe UTCTime -> Text @@ -1572,7 +1572,7 @@ waitIssueErrorCleared cc = loop (100 :: Int) testRenewalKeepsActiveProfile :: HasCallStack => TestParams -> IO () testRenewalKeepsActiveProfile ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do code <- issueCode cc BTSupporter 3 redeemFirstBadge alice code @@ -1596,7 +1596,7 @@ testRenewalKeepsActiveProfile ps = testSnoozedAlertReturns :: HasCallStack => TestParams -> IO () testSnoozedAlertReturns ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do code <- issueCode cc BTSupporter 1 redeemFirstBadge alice code @@ -1627,7 +1627,7 @@ testSnoozedAlertReturns ps = testRenewalKeepsProfileEdits :: HasCallStack => TestParams -> IO () testRenewalKeepsProfileEdits ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> withNewTestChatCfg ps bsClientCfg "bob" bobProfile $ \bob -> do connectUsers alice bob @@ -1667,7 +1667,7 @@ testRenewalKeepsProfileEdits ps = testPresentationCatchesUp :: HasCallStack => TestParams -> IO () testPresentationCatchesUp ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> withNewTestChatCfg ps bsClientCfg "bob" bobProfile $ \bob -> do connectUsers alice bob @@ -1713,7 +1713,7 @@ waitPeerBadgeExpiry cc expected = loop (100 :: Int) testPurchaseKeyMismatch :: HasCallStack => TestParams -> IO () testPurchaseKeyMismatch ps = - withBadgeService ps $ \clientCfg bsLink _ -> + withStoreService ps $ \clientCfg bsLink _ -> withNewTestChatCfg ps clientCfg "alice" aliceProfile $ \alice -> do g <- C.newRandom (_, signPriv) <- atomically $ C.generateKeyPair g :: IO (C.KeyPair 'C.Ed25519) @@ -1728,7 +1728,7 @@ testIssuerKeyMustMatchConfig :: HasCallStack => TestParams -> IO () testIssuerKeyMustMatchConfig ps = do Right (pk, sk) <- bbsKeyGen Right (_, otherSk) <- bbsKeyGen - let optsFor sk' = mkBadgeServiceOpts ps sk' + let optsFor sk' = mkStoreServiceOpts ps sk' cfg = testCfg {badgePublicKeys = M.singleton testIssuerKeyIdx pk} checkIssuerKey (optsFor sk) Nothing cfg >>= (`shouldSatisfy` isRight) checkIssuerKey (optsFor otherSk) Nothing cfg >>= (`shouldSatisfy` isLeft) @@ -1741,7 +1741,7 @@ testIssuerIniKeyMustBeTrusted ps = do Right (pk, sk) <- bbsKeyGen Right (_, untrusted) <- bbsKeyGen let cfg = testCfg {badgePublicKeys = M.singleton testIssuerKeyIdx pk} - fromCli = mkBadgeServiceOpts ps sk + fromCli = mkStoreServiceOpts ps sk fromIni = fromCli {issuerKey = Right Nothing} iniWith idx k = withIssuer ["index = " <> tshow idx, "private_key = " <> safeDecodeUtf8 (strEncode k)] readServiceConfig Right trusted <- iniWith testIssuerKeyIdx sk @@ -1757,11 +1757,11 @@ testIssuerIniKeyMustBeTrusted ps = do testRedeemUnpaidCode :: HasCallStack => TestParams -> IO () testRedeemUnpaidCode ps = - withBadgeService ps $ \clientCfg _ cc -> + withStoreService ps $ \clientCfg _ cc -> withNewTestChatCfg ps clientCfg "alice" aliceProfile $ \alice -> do unpaid <- issueCodeAs cc BTSupporter 1 "unpaid" alice ##> ("/_redeem_badge_code 1 " <> codeArg unpaid) - alice <## "cannot get badge: badge service error: payment_pending" + alice <## "cannot get badge: store service error: payment_pending" paid <- issueCodeAs cc BTSupporter 1 "paid" alice ##> ("/_redeem_badge_code 1 " <> codeArg paid) alice <## "badge redeemed" @@ -1771,18 +1771,18 @@ testRedeemUnpaidCode ps = -- | A redemption deadline is a year out and cannot be waited for, so the code is issued unpaid and then marked paid with a deadline already in the past. testExpiredCode :: HasCallStack => TestParams -> IO () testExpiredCode ps = - withBadgeService ps $ \clientCfg _ cc -> + withStoreService ps $ \clientCfg _ cc -> withNewTestChatCfg ps clientCfg "alice" aliceProfile $ \alice -> do code <- issueCodeAs cc BTSupporter 1 "unpaid" now <- getCurrentTime withDB' "markCodePaid" cc (\db -> markCodePaid db (badgeCodeHash code) (addUTCTime (-60) now)) `shouldReturn` Right () alice ##> ("/_redeem_badge_code 1 " <> codeArg code) - alice <## "cannot get badge: badge service error: code_expired" + alice <## "cannot get badge: store service error: code_expired" testRedeemedBeforeTheDeadline :: HasCallStack => TestParams -> IO () testRedeemedBeforeTheDeadline ps = - withBadgeService ps $ \clientCfg _ cc -> + withStoreService ps $ \clientCfg _ cc -> withNewTestChatCfg ps clientCfg "alice" aliceProfile $ \alice -> do code <- issueCodeAs cc BTSupporter 1 "unpaid" now <- getCurrentTime @@ -1805,7 +1805,7 @@ testRedeemedBeforeTheDeadline ps = testRevokeRedeemedCode :: HasCallStack => TestParams -> IO () testRevokeRedeemedCode ps = - withBadgeService ps $ \clientCfg _ cc -> + withStoreService ps $ \clientCfg _ cc -> withNewTestChatCfg ps clientCfg "alice" aliceProfile $ \alice -> do code <- issueCodeAs cc BTSupporter 1 "paid" alice ##> ("/_redeem_badge_code 1 " <> codeArg code) @@ -1819,7 +1819,7 @@ testRevokeRedeemedCode ps = testRevokeUnknownCode :: HasCallStack => TestParams -> IO () testRevokeUnknownCode ps = - withBadgeService ps $ \_ _ cc -> do + withStoreService ps $ \_ _ cc -> do g <- C.newRandom code <- randomBadgeCode g unknown <- revokeCodeAs cc code @@ -1827,24 +1827,24 @@ testRevokeUnknownCode ps = testRevokedCode :: HasCallStack => TestParams -> IO () testRevokedCode ps = - withBadgeService ps $ \clientCfg _ cc -> + withStoreService ps $ \clientCfg _ cc -> withNewTestChatCfg ps clientCfg "alice" aliceProfile $ \alice -> do paid <- issueCodeAs cc BTSupporter 1 "paid" revokeCodeAs cc paid `shouldReturn` Right "Revoked." alice ##> ("/_redeem_badge_code 1 " <> codeArg paid) - alice <## "cannot get badge: badge service error: code_invalid" + alice <## "cannot get badge: store service error: code_invalid" revokeCodeAs cc paid `shouldReturn` Right "Already revoked." testRevokedUnpaidCode :: HasCallStack => TestParams -> IO () testRevokedUnpaidCode ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsController = cc} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsController = cc} -> do code <- issueCodeAs cc BTSupporter 1 "unpaid" revokeCodeAs cc code `shouldReturn` Right "Revoked." - redeemAsNewPurchase env code >>= (`shouldAnswerError` BSECodeInvalid) + redeemAsNewPurchase env code >>= (`shouldAnswerError` STECodeInvalid) testRevokeRejectsTrailingInput :: HasCallStack => TestParams -> IO () testRevokeRejectsTrailingInput ps = - withBadgeService ps $ \_ _ cc -> do + withStoreService ps $ \_ _ cc -> do code <- issueCodeAs cc BTSupporter 1 "paid" refused <- revokeRaw cc (formatBadgeCode code <> " junk") -- If the refused call revoked the code anyway, this fails with "Already revoked.". @@ -1855,8 +1855,8 @@ testRevokeRejectsTrailingInput ps = badgeCmdUsage :: Text badgeCmdUsage = "Usage: //issue supporter|legend|investor [months 1-255] [paid|unpaid|free], or //revoke " -purchaseCmd :: BadgeMasterKey -> ServicePayment -> BadgeServiceCommand -purchaseCmd masterKey payment = BSCPurchaseBadge {masterKey, payment, upgrade = Nothing} +purchaseCmd :: BadgeMasterKey -> ServicePayment -> StoreServiceCommand +purchaseCmd masterKey payment = STCPurchaseBadge {masterKey, payment, upgrade = Nothing} supporterPlay :: ServicePayment supporterPlay = googlePayment "badge_supporter_01" googleSupporterToken @@ -1864,9 +1864,9 @@ supporterPlay = googlePayment "badge_supporter_01" googleSupporterToken paymentArg :: ServicePayment -> String paymentArg = LB.unpack . J.encode -refusalOf :: HasCallStack => BadgeServiceResponse -> (BadgeServiceErrorCode, Maybe Word32) +refusalOf :: HasCallStack => StoreServiceResponse -> (StoreServiceErrorCode, Maybe Word32) refusalOf = \case - BSPError {code, retryAfter} -> (code, retryAfter) + STPError {code, retryAfter} -> (code, retryAfter) r -> error $ "expected an error, got " <> show (J.toJSON r) rowCount :: ChatController -> String -> IO Int @@ -1891,7 +1891,7 @@ nothingPurchased cc = do testStorePurchase :: HasCallStack => TestParams -> IO () testStorePurchase ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsController = cc} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsController = cc} -> do (purchaseKey, masterKey) <- newPurchaseKeys purchased <- serviceCmd env purchaseKey $ purchaseCmd masterKey supporterPlay let (entries, previousEntryId) = statementOf purchased @@ -1906,31 +1906,31 @@ testStorePurchase ps = testStoreReceiptUsed :: HasCallStack => TestParams -> IO () testStoreReceiptUsed ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsController = cc} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsController = cc} -> do (firstKey, firstMasterKey) <- newPurchaseKeys _ <- serviceCmd env firstKey $ purchaseCmd firstMasterKey supporterPlay ledger <- ledgerRows cc "sx_badge_service_badge_ledger" (otherKey, otherMasterKey) <- newPurchaseKeys used <- serviceCmd env otherKey $ purchaseCmd otherMasterKey supporterPlay - refusalOf used `shouldBe` (BSEReceiptUsed, Nothing) + refusalOf used `shouldBe` (STEReceiptUsed, Nothing) ledgerRows cc "sx_badge_service_badge_ledger" `shouldReturn` ledger rowCount cc "sx_badge_service_badge_purchases" `shouldReturn` 1 testStoreReceiptInvalid :: HasCallStack => TestParams -> IO () testStoreReceiptInvalid ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsController = cc, bsStore = FakeStore {appleSandboxJWS}} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsController = cc, bsStore = FakeStore {appleSandboxJWS}} -> do (purchaseKey, masterKey) <- newPurchaseKeys let refused payment = refusalOf <$> serviceCmd env purchaseKey (purchaseCmd masterKey payment) - refused (googlePayment "badge_supporter_01" "not-a-purchase") `shouldReturn` (BSEReceiptInvalid, Nothing) - refused SPApple {jws = "not.a.jws"} `shouldReturn` (BSEReceiptInvalid, Nothing) - refused SPApple {jws = unsignedJWS "{\"transactionId\":\"2000000812345699\",\"productId\":\"BADGE_SUPPORTER_01\"}"} `shouldReturn` (BSEReceiptInvalid, Nothing) + refused (googlePayment "badge_supporter_01" "not-a-purchase") `shouldReturn` (STEReceiptInvalid, Nothing) + refused SPApple {jws = "not.a.jws"} `shouldReturn` (STEReceiptInvalid, Nothing) + refused SPApple {jws = unsignedJWS "{\"transactionId\":\"2000000812345699\",\"productId\":\"BADGE_SUPPORTER_01\"}"} `shouldReturn` (STEReceiptInvalid, Nothing) -- named rather than lumped in with a forgery, since the device that bought it already knows - refused SPApple {jws = appleSandboxJWS} `shouldReturn` (BSETestPurchase, Nothing) + refused SPApple {jws = appleSandboxJWS} `shouldReturn` (STETestPurchase, Nothing) nothingPurchased cc testStoreTestPurchaseCredited :: HasCallStack => TestParams -> IO () testStoreTestPurchaseCredited ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsController = cc, bsStore = store@FakeStore {appleSandboxJWS, appleSandboxSubscriptionJWS}} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsController = cc, bsStore = store@FakeStore {appleSandboxJWS, appleSandboxSubscriptionJWS}} -> do now <- serviceNow env let crediting = env {bsVerifier = (fakeVerifier store) {creditTestPurchases = True}} testToken = "fake-play-token-subscription-test.AO-J1Os2q5djX0pRm6" @@ -1947,16 +1947,16 @@ testStoreTestPurchaseCredited ps = -- past the hour the Play claim is held for since it was credited, so Play is asked again setClockAt bsClock $ addUTCTime 3700 now refused <- mapM (purchaseUnderNewKey env) receipts - map refusalOf refused `shouldBe` replicate 3 (BSETestPurchase, Nothing) + map refusalOf refused `shouldBe` replicate 3 (STETestPurchase, Nothing) rowCount cc "sx_badge_service_badge_purchases" `shouldReturn` 3 testStorePending :: HasCallStack => TestParams -> IO () testStorePending ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsController = cc, bsStore = store} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsController = cc, bsStore = store} -> do (purchaseKey, masterKey) <- newPurchaseKeys let unsettled = purchaseCmd masterKey $ googlePayment "badge_supporter_01" googlePendingToken waiting <- serviceCmd env purchaseKey unsettled - refusalOf waiting `shouldSatisfy` \(code, retryAfter) -> code == BSEPaymentPending && isJust retryAfter + refusalOf waiting `shouldSatisfy` \(code, retryAfter) -> code == STEPaymentPending && isJust retryAfter nothingPurchased cc settlePending store settled <- serviceCmd env purchaseKey unsettled @@ -1971,20 +1971,20 @@ testStoreAcknowledgesBeforeCrediting ps = do acknowledged <- newIORef [] acknowledgement <- newIORef $ Right () let acknowledging store = (fakeVerifier store) {acknowledgeGoogle = Just $ \_ token -> modifyIORef' acknowledged (token :) >> readIORef acknowledgement} - withBadgeServiceVerifier ps acknowledging $ \env@BadgeServiceEnv {bsController = cc} -> do + withStoreServiceVerifier ps acknowledging $ \env@StoreServiceEnv {bsController = cc} -> do (purchaseKey, masterKey) <- newPurchaseKeys let purchase payment = serviceCmd env purchaseKey $ purchaseCmd masterKey payment unsettled <- purchase $ googlePayment "badge_supporter_01" googlePendingToken - fst (refusalOf unsettled) `shouldBe` BSEPaymentPending + fst (refusalOf unsettled) `shouldBe` STEPaymentPending unpriced <- purchase $ googlePayment "badge_unknown_01" googleUnknownProductToken - refusalOf unpriced `shouldBe` (BSEProductUnavailable, Nothing) + refusalOf unpriced `shouldBe` (STEProductUnavailable, Nothing) readIORef acknowledged `shouldReturn` [] writeIORef acknowledgement $ Left $ SRUnreachable "acknowledging: fake store is down" unacknowledged <- purchase supporterPlay - refusalOf unacknowledged `shouldSatisfy` \(code, retryAfter) -> code == BSEProviderUnavailable && isJust retryAfter + refusalOf unacknowledged `shouldSatisfy` \(code, retryAfter) -> code == STEProviderUnavailable && isJust retryAfter writeIORef acknowledgement $ Left $ SRVerifierFailed "acknowledging: the service account lacks the Play Console permission for this call" forbidden <- purchase supporterPlay - refusalOf forbidden `shouldBe` (BSEInternal, Nothing) + refusalOf forbidden `shouldBe` (STEInternal, Nothing) nothingPurchased cc writeIORef acknowledgement $ Right () purchased <- purchase supporterPlay @@ -1996,28 +1996,28 @@ testStoreAcknowledgesBeforeCrediting ps = do testStoreUnknownProduct :: HasCallStack => TestParams -> IO () testStoreUnknownProduct ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsController = cc} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsController = cc} -> do (purchaseKey, masterKey) <- newPurchaseKeys -- a real purchase the store vouches for, of a product this service does not price unpriced <- serviceCmd env purchaseKey $ purchaseCmd masterKey $ googlePayment "badge_unknown_01" googleUnknownProductToken - refusalOf unpriced `shouldBe` (BSEProductUnavailable, Nothing) + refusalOf unpriced `shouldBe` (STEProductUnavailable, Nothing) nothingPurchased cc testStoreUpgradeRefused :: HasCallStack => TestParams -> IO () testStoreUpgradeRefused ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsController = cc} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsController = cc} -> do (purchaseKey, masterKey) <- newPurchaseKeys g <- C.newRandom (fromPurchaseKey, fromPriv) <- atomically $ C.generateKeyPair g :: IO (C.KeyPair 'C.Ed25519) now <- getCurrentTime let upgrade = BadgeUpgrade {fromPurchaseKey, receipt = "receipt", receiptSignature = C.sign' fromPriv "receipt", balance = BadgeBalance {lastEntry = emptyEntry now BTSupporter}} - upgraded <- serviceCmd env purchaseKey BSCPurchaseBadge {masterKey, payment = supporterPlay, upgrade = Just upgrade} - refusalOf upgraded `shouldBe` (BSEBadRequest, Nothing) + upgraded <- serviceCmd env purchaseKey STCPurchaseBadge {masterKey, payment = supporterPlay, upgrade = Just upgrade} + refusalOf upgraded `shouldBe` (STEBadRequest, Nothing) nothingPurchased cc testStoreBadgeTypeFromProduct :: HasCallStack => TestParams -> IO () testStoreBadgeTypeFromProduct ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsController = cc, bsStore = FakeStore {appleLegendJWS}} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsController = cc, bsStore = FakeStore {appleLegendJWS}} -> do (purchaseKey, masterKey) <- newPurchaseKeys legend <- serviceCmd env purchaseKey $ purchaseCmd masterKey SPApple {jws = appleLegendJWS} badgeTypeOf legend `shouldBe` Just BTLegend @@ -2026,17 +2026,17 @@ testStoreBadgeTypeFromProduct ps = testNonStoreFundingRefused :: HasCallStack => TestParams -> IO () testNonStoreFundingRefused ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsController = cc} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsController = cc} -> do (purchaseKey, masterKey) <- newPurchaseKeys invoice <- serviceCmd env purchaseKey $ purchaseCmd masterKey SPInvoice {invoiceId = InvoiceId "inv"} - refusalOf invoice `shouldBe` (BSEUnknownPurchaseKey, Nothing) + refusalOf invoice `shouldBe` (STEUnknownPurchaseKey, Nothing) transfer <- serviceCmd env purchaseKey $ purchaseCmd masterKey SPReceipt {receipt = "receipt"} - refusalOf transfer `shouldBe` (BSEUnknownPurchaseKey, Nothing) + refusalOf transfer `shouldBe` (STEUnknownPurchaseKey, Nothing) nothingPurchased cc testStoreReplayWhileStoreDown :: HasCallStack => TestParams -> IO () testStoreReplayWhileStoreDown ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsController = cc, bsStore = store} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsController = cc, bsStore = store} -> do (purchaseKey, masterKey) <- newPurchaseKeys purchased <- serviceCmd env purchaseKey $ purchaseCmd masterKey supporterPlay ledger <- ledgerRows cc "sx_badge_service_badge_ledger" @@ -2048,41 +2048,41 @@ testStoreReplayWhileStoreDown ps = -- any other key waits for the store, or the answer would tell it which purchases were credited (otherKey, otherMasterKey) <- newPurchaseKeys other <- serviceCmd env otherKey $ purchaseCmd otherMasterKey supporterPlay - fst (refusalOf other) `shouldBe` BSEProviderUnavailable + fst (refusalOf other) `shouldBe` STEProviderUnavailable ledgerRows cc "sx_badge_service_badge_ledger" `shouldReturn` ledger storePayments cc `shouldReturn` [("google", Nothing, Nothing, 1)] rowCount cc "sx_badge_service_badge_purchases" `shouldReturn` 1 testStoreVerifierFailures :: HasCallStack => TestParams -> IO () testStoreVerifierFailures ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsController = cc, bsStore = FakeStore {appleThrowingJWS}} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsController = cc, bsStore = FakeStore {appleThrowingJWS}} -> do (purchaseKey, masterKey) <- newPurchaseKeys let answer payment = refusalOf <$> serviceCmd env purchaseKey (purchaseCmd masterKey payment) -- Apple is checked offline, so a verifier that throws was answered by nothing but its own bug - answer SPApple {jws = appleThrowingJWS} `shouldReturn` (BSEInternal, Nothing) - answer (googlePayment "badge_supporter_01" googleThrowingToken) >>= (`shouldSatisfy` \(code, retryAfter) -> code == BSEProviderUnavailable && isJust retryAfter) - answer (googlePayment "badge_supporter_01" googleHangingToken) >>= (`shouldSatisfy` \(code, retryAfter) -> code == BSEProviderUnavailable && isJust retryAfter) + answer SPApple {jws = appleThrowingJWS} `shouldReturn` (STEInternal, Nothing) + answer (googlePayment "badge_supporter_01" googleThrowingToken) >>= (`shouldSatisfy` \(code, retryAfter) -> code == STEProviderUnavailable && isJust retryAfter) + answer (googlePayment "badge_supporter_01" googleHangingToken) >>= (`shouldSatisfy` \(code, retryAfter) -> code == STEProviderUnavailable && isJust retryAfter) nothingPurchased cc testStoreVerifiedOtherTransaction :: HasCallStack => TestParams -> IO () testStoreVerifiedOtherTransaction ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsController = cc, bsStore = FakeStore {appleMisnamedJWS}} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsController = cc, bsStore = FakeStore {appleMisnamedJWS}} -> do (purchaseKey, masterKey) <- newPurchaseKeys - refusalOf <$> serviceCmd env purchaseKey (purchaseCmd masterKey SPApple {jws = appleMisnamedJWS}) `shouldReturn` (BSEInternal, Nothing) + refusalOf <$> serviceCmd env purchaseKey (purchaseCmd masterKey SPApple {jws = appleMisnamedJWS}) `shouldReturn` (STEInternal, Nothing) nothingPurchased cc testStoreQuantityRefused :: HasCallStack => TestParams -> IO () testStoreQuantityRefused ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsController = cc, bsStore = FakeStore {appleQuantityJWS}} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsController = cc, bsStore = FakeStore {appleQuantityJWS}} -> do (purchaseKey, masterKey) <- newPurchaseKeys - refusalOf <$> serviceCmd env purchaseKey (purchaseCmd masterKey SPApple {jws = appleQuantityJWS}) `shouldReturn` (BSEInternal, Nothing) + refusalOf <$> serviceCmd env purchaseKey (purchaseCmd masterKey SPApple {jws = appleQuantityJWS}) `shouldReturn` (STEInternal, Nothing) nothingPurchased cc testPurchaseWithNoVerifier :: HasCallStack => TestParams -> IO () testPurchaseWithNoVerifier ps = - withBadgeServiceVerifier ps (const noStoreVerifier) $ \env@BadgeServiceEnv {bsClientCfg, bsController = cc} -> do + withStoreServiceVerifier ps (const noStoreVerifier) $ \env@StoreServiceEnv {bsClientCfg, bsController = cc} -> do (purchaseKey, masterKey) <- newPurchaseKeys - refusalOf <$> serviceCmd env purchaseKey (purchaseCmd masterKey supporterPlay) `shouldReturn` (BSEProviderNotConfigured, Nothing) + refusalOf <$> serviceCmd env purchaseKey (purchaseCmd masterKey supporterPlay) `shouldReturn` (STEProviderNotConfigured, Nothing) nothingPurchased cc withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do alice ##> ("/_badge purchase 1 " <> paymentArg supporterPlay) @@ -2096,7 +2096,7 @@ testPurchaseWithNoVerifier ps = testStorePurchaseRace :: HasCallStack => TestParams -> IO () testStorePurchaseRace ps = do hook <- newIORef (pure ()) - withBadgeServiceVerifier ps (googleVerifierWithHook hook) $ \env@BadgeServiceEnv {bsController = cc} -> do + withStoreServiceVerifier ps (googleVerifierWithHook hook) $ \env@StoreServiceEnv {bsController = cc} -> do (purchaseKey, masterKey) <- newPurchaseKeys winner <- newIORef Nothing -- the same purchase is presented again while the first is with the store, and credited first @@ -2111,14 +2111,14 @@ testStorePurchaseRace ps = do testStorePurchaseRaceOtherKey :: HasCallStack => TestParams -> IO () testStorePurchaseRaceOtherKey ps = do hook <- newIORef (pure ()) - withBadgeServiceVerifier ps (googleVerifierWithHook hook) $ \env@BadgeServiceEnv {bsController = cc} -> do + withStoreServiceVerifier ps (googleVerifierWithHook hook) $ \env@StoreServiceEnv {bsController = cc} -> do (purchaseKey, masterKey) <- newPurchaseKeys (otherKey, otherMasterKey) <- newPurchaseKeys winner <- newIORef Nothing -- another key presents the same purchase while the first is with the store, and is credited first writeIORef hook $ serviceCmd env otherKey (purchaseCmd otherMasterKey supporterPlay) >>= writeIORef winner . Just raced <- serviceCmd env purchaseKey $ purchaseCmd masterKey supporterPlay - refusalOf raced `shouldBe` (BSEReceiptUsed, Nothing) + refusalOf raced `shouldBe` (STEReceiptUsed, Nothing) Just credited <- readIORef winner masterKeyOf credited `shouldBe` Just otherMasterKey ledger <- ledgerRows cc "sx_badge_service_badge_ledger" @@ -2130,7 +2130,7 @@ testStorePurchaseRaceOtherKey ps = do testStorePurchaseKeyMismatch :: HasCallStack => TestParams -> IO () testStorePurchaseKeyMismatch ps = - withBadgeService ps $ \clientCfg bsLink cc -> + withStoreService ps $ \clientCfg bsLink cc -> withNewTestChatCfg ps clientCfg "alice" aliceProfile $ \alice -> do g <- C.newRandom (_, signPriv) <- atomically $ C.generateKeyPair g :: IO (C.KeyPair 'C.Ed25519) @@ -2149,9 +2149,9 @@ testStoreUnsentProductId :: HasCallStack => TestParams -> IO () testStoreUnsentProductId ps = do hook <- newIORef (pure ()) verifications <- countGoogleVerifications hook - withBadgeServiceVerifier ps (googleVerifierWithHook hook) $ \env@BadgeServiceEnv {bsController = cc} -> do + withStoreServiceVerifier ps (googleVerifierWithHook hook) $ \env@StoreServiceEnv {bsController = cc} -> do (purchaseKey, masterKey) <- newPurchaseKeys - refusalOf <$> serviceCmd env purchaseKey (purchaseCmd masterKey $ googlePayment "badge_supporter_01/../other" googleSupporterToken) `shouldReturn` (BSEReceiptInvalid, Nothing) + refusalOf <$> serviceCmd env purchaseKey (purchaseCmd masterKey $ googlePayment "badge_supporter_01/../other" googleSupporterToken) `shouldReturn` (STEReceiptInvalid, Nothing) verifications `shouldReturn` 0 nothingPurchased cc @@ -2165,17 +2165,17 @@ storeCharge :: Text -> UTCTime -> Integer -> StoreCharge storeCharge planId periodStart months = StoreCharge {chargeRef = "GPA.3301-1234-5678-90123", planId, periodStart, periodEnd = addMonths months periodStart, chargePaid = Nothing, revoked = False, offer = False} -subscriptionOf :: HasCallStack => BadgeServiceResponse -> Maybe SubscriptionState +subscriptionOf :: HasCallStack => StoreServiceResponse -> Maybe SubscriptionState subscriptionOf = \case - BSPBadgeCredential {subscription} -> subscription + STPBadgeCredential {subscription} -> subscription r -> error $ "expected badgeCredential, got " <> show (J.toJSON r) createdAtOf :: StatementEntry -> UTCTime createdAtOf StatementEntry {createdAt} = createdAt -- | The ledger stores whole seconds. -serviceNow :: BadgeServiceEnv -> IO UTCTime -serviceNow BadgeServiceEnv {bsClock} = truncateToSecond <$> testClockTime bsClock +serviceNow :: StoreServiceEnv -> IO UTCTime +serviceNow StoreServiceEnv {bsClock} = truncateToSecond <$> testClockTime bsClock subscriptionPayments :: ChatController -> IO [(Text, Text, Maybe Text, Maybe Text)] subscriptionPayments ChatController {chatStore} = @@ -2184,7 +2184,7 @@ subscriptionPayments ChatController {chatStore} = testSubscriptionPurchase :: HasCallStack => TestParams -> IO () testSubscriptionPurchase ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsController = cc, bsStore = store@FakeStore {appleSubscriptionJWS, appleSandboxSubscriptionJWS}} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsController = cc, bsStore = store@FakeStore {appleSubscriptionJWS, appleSandboxSubscriptionJWS}} -> do now <- serviceNow env let periodStart = addUTCTime (-3600) now changes = map (\e -> let (c, m, _) = entryOf e in (c, m)) . fst . statementOf @@ -2208,7 +2208,7 @@ testSubscriptionPurchase ps = (otherKey, otherMasterKey) <- newPurchaseKeys -- another key is told once Play is asked again, after the hour the token is held for setClockAt bsClock $ addUTCTime 3700 now - refusalOf <$> serviceCmd env otherKey (purchaseCmd otherMasterKey subscriptionPlay) `shouldReturn` (BSEReceiptUsed, Nothing) + refusalOf <$> serviceCmd env otherKey (purchaseCmd otherMasterKey subscriptionPlay) `shouldReturn` (STEReceiptUsed, Nothing) -- an annual Apple subscription is claimed by its original id, which the store is asked about setSubscription store (SubscriptionApple appleSubscriptionOriginalId) $ subscriptionCheck SSRenewing $ Just $ storeCharge "SUBSCR_BADGE_SUPPORTER_YEAR_01" periodStart 12 (appleKey, appleMasterKey) <- newPurchaseKeys @@ -2220,15 +2220,15 @@ testSubscriptionPurchase ps = let testToken = "fake-play-token-subscription-test.AO-J1Os2q5djX0pRm6" setSubscription store (SubscriptionGoogle testToken) SubscriptionCheck {subscriptionState = SSRenewing, testSubscription = True, latestCharge = Just $ storeCharge "subscr-badge-supporter-month-02" periodStart 1} (testKey, testMasterKey) <- newPurchaseKeys - refusalOf <$> serviceCmd env testKey (purchaseCmd testMasterKey $ googlePayment "subscr_badge_supporter_01" testToken) `shouldReturn` (BSETestPurchase, Nothing) + refusalOf <$> serviceCmd env testKey (purchaseCmd testMasterKey $ googlePayment "subscr_badge_supporter_01" testToken) `shouldReturn` (STETestPurchase, Nothing) sandboxChecks <- subscriptionChecks store - refusalOf <$> serviceCmd env testKey (purchaseCmd testMasterKey SPApple {jws = appleSandboxSubscriptionJWS}) `shouldReturn` (BSETestPurchase, Nothing) + refusalOf <$> serviceCmd env testKey (purchaseCmd testMasterKey SPApple {jws = appleSandboxSubscriptionJWS}) `shouldReturn` (STETestPurchase, Nothing) subscriptionChecks store `shouldReturn` sandboxChecks rowCount cc "sx_badge_service_badge_purchases" `shouldReturn` 2 testSubscriptionPurchaseNotGrantable :: HasCallStack => TestParams -> IO () testSubscriptionPurchaseNotGrantable ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsController = cc, bsStore = store@FakeStore {appleSubscriptionJWS}} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsController = cc, bsStore = store@FakeStore {appleSubscriptionJWS}} -> do now <- serviceNow env (purchaseKey, masterKey) <- newPurchaseKeys let monthlyFrom start = storeCharge "subscr-badge-supporter-month-02" start 1 @@ -2240,40 +2240,40 @@ testSubscriptionPurchaseNotGrantable ps = nextHour = testClockTime bsClock >>= setClockAt bsClock . addUTCTime 3700 play = answer (SubscriptionGoogle googleSubscriptionToken) subscriptionPlay aDay = Just 86400 - play (subscriptionCheck SSRenewing $ Just $ monthlyFrom $ addUTCTime 3600 now) `shouldReturn` (BSEPaymentPending, Just 3600) + play (subscriptionCheck SSRenewing $ Just $ monthlyFrom $ addUTCTime 3600 now) `shouldReturn` (STEPaymentPending, Just 3600) -- Play gives a subscription bought again a new token, so this one can never be credited - play (subscriptionCheck SSEnded $ Just monthly) `shouldReturn` (BSEReceiptInvalid, Nothing) + play (subscriptionCheck SSEnded $ Just monthly) `shouldReturn` (STEReceiptInvalid, Nothing) -- a later charge could still credit this receipt - play (subscriptionCheck SSRenewing $ Just monthly {revoked = True}) `shouldReturn` (BSEPaymentPending, aDay) - play (subscriptionCheck SSRenewing $ Just monthly {offer = True}) `shouldReturn` (BSEPaymentPending, aDay) - play (subscriptionCheck SSBillingRetry Nothing) `shouldReturn` (BSEPaymentPending, aDay) - play (subscriptionCheck SSBillingRetry $ Just $ monthlyFrom $ addMonths (-2) now) `shouldReturn` (BSEPaymentPending, aDay) - play (subscriptionCheck SSRenewing $ Just $ storeCharge "subscr-badge-supporter-month-99" (addUTCTime (-3600) now) 1) `shouldReturn` (BSEPaymentPending, aDay) + play (subscriptionCheck SSRenewing $ Just monthly {revoked = True}) `shouldReturn` (STEPaymentPending, aDay) + play (subscriptionCheck SSRenewing $ Just monthly {offer = True}) `shouldReturn` (STEPaymentPending, aDay) + play (subscriptionCheck SSBillingRetry Nothing) `shouldReturn` (STEPaymentPending, aDay) + play (subscriptionCheck SSBillingRetry $ Just $ monthlyFrom $ addMonths (-2) now) `shouldReturn` (STEPaymentPending, aDay) + play (subscriptionCheck SSRenewing $ Just $ storeCharge "subscr-badge-supporter-month-99" (addUTCTime (-3600) now) 1) `shouldReturn` (STEPaymentPending, aDay) -- Play gives a plan it does not know no length, so its charge has an empty period, and is still only an unsold plan let unsoldAt t = (storeCharge "subscr-badge-supporter-month-99" t 1) {periodEnd = t} - play (subscriptionCheck SSRenewing $ Just $ unsoldAt $ addMonths 1 now) `shouldReturn` (BSEPaymentPending, aDay) + play (subscriptionCheck SSRenewing $ Just $ unsoldAt $ addMonths 1 now) `shouldReturn` (STEPaymentPending, aDay) -- an Apple resubscription keeps the original id, so an ended subscription may yet be credited answer (SubscriptionApple appleSubscriptionOriginalId) SPApple {jws = appleSubscriptionJWS} (subscriptionCheck SSEnded $ Just $ storeCharge "SUBSCR_BADGE_SUPPORTER_MONTH_01" (addUTCTime (-3600) now) 1) - `shouldReturn` (BSEPaymentPending, aDay) - play (subscriptionCheck SSRenewing $ Just monthly {periodEnd = addUTCTime (-7200) now}) `shouldReturn` (BSEInternal, Nothing) + `shouldReturn` (STEPaymentPending, aDay) + play (subscriptionCheck SSRenewing $ Just monthly {periodEnd = addUTCTime (-7200) now}) `shouldReturn` (STEInternal, Nothing) nothingPurchased cc rowCount cc "sx_badge_service_subscription_charges" `shouldReturn` 0 -- | A monthly Play subscription bought an hour into its first period: its key, that period's start and the statement it was answered. -subscribedMonthly :: HasCallStack => BadgeServiceEnv -> IO (C.PublicKeyEd25519, UTCTime, [StatementEntry]) +subscribedMonthly :: HasCallStack => StoreServiceEnv -> IO (C.PublicKeyEd25519, UTCTime, [StatementEntry]) subscribedMonthly env = subscribedTo env "subscr-badge-supporter-month-02" 1 -- | The same for the Play plan given, of that many months. -subscribedTo :: HasCallStack => BadgeServiceEnv -> Text -> Integer -> IO (C.PublicKeyEd25519, UTCTime, [StatementEntry]) -subscribedTo env@BadgeServiceEnv {bsStore} planId months = do +subscribedTo :: HasCallStack => StoreServiceEnv -> Text -> Integer -> IO (C.PublicKeyEd25519, UTCTime, [StatementEntry]) +subscribedTo env@StoreServiceEnv {bsStore} planId months = do firstStart <- monthEndStart env setSubscription bsStore (SubscriptionGoogle googleSubscriptionToken) $ subscriptionCheck SSRenewing $ Just $ storeCharge planId firstStart months (purchaseKey, masterKey) <- newPurchaseKeys purchased <- serviceCmd env purchaseKey $ purchaseCmd masterKey subscriptionPlay pure (purchaseKey, firstStart, fst $ statementOf purchased) -monthEndStart :: BadgeServiceEnv -> IO UTCTime -monthEndStart env@BadgeServiceEnv {bsClock} = do +monthEndStart :: StoreServiceEnv -> IO UTCTime +monthEndStart env@StoreServiceEnv {bsClock} = do (year, _, _) <- toGregorian . utctDay <$> serviceNow env let start = UTCTime (fromGregorian (year + 1) 1 31) 36000 setClockAt bsClock $ addUTCTime 3600 start @@ -2293,7 +2293,7 @@ subscriptionCheckedAt ChatController {chatStore} = testSubscriptionChargeGrantedOnce :: HasCallStack => TestParams -> IO () testSubscriptionChargeGrantedOnce ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsController = cc, bsStore = store} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsController = cc, bsStore = store} -> do (purchaseKey, firstStart, purchased) <- subscribedMonthly env let renewalStart = addMonths 1 firstStart -- the store's period runs past the month granted, so the charge is still current once that month is spent @@ -2323,7 +2323,7 @@ testSubscriptionChargeGrantedOnce ps = testSubscriptionStoreChecksBounded :: HasCallStack => TestParams -> IO () testSubscriptionStoreChecksBounded ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsStore = store} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsStore = store} -> do (purchaseKey, firstStart, purchased) <- subscribedMonthly env let request = assertBalance env purchaseKey (last purchased) ended = addUTCTime (3 * nominalDay) (addMonths 1 firstStart) @@ -2343,7 +2343,7 @@ testSubscriptionStoreChecksBounded ps = -- an hour on it is asked again, and a check that fails holds the next one off as long setGoogleDown store True setClockAt bsClock $ addUTCTime 3700 ended - refusalOf <$> request `shouldReturn` (BSEProviderUnavailable, Just 3600) + refusalOf <$> request `shouldReturn` (STEProviderUnavailable, Just 3600) setGoogleDown store False setClockAt bsClock $ addUTCTime (3700 + 1800) ended subscriptionOf <$> request `shouldReturn` Just SSBillingRetry @@ -2351,7 +2351,7 @@ testSubscriptionStoreChecksBounded ps = testSubscriptionChargeNotGranted :: HasCallStack => TestParams -> IO () testSubscriptionChargeNotGranted ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsController = cc, bsStore = store} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsController = cc, bsStore = store} -> do (purchaseKey, firstStart, purchased) <- subscribedMonthly env ledger <- ledgerRows cc "sx_badge_service_badge_ledger" let monthly = "subscr-badge-supporter-month-02" @@ -2376,7 +2376,7 @@ testSubscriptionChargeNotGranted ps = testClippedPlayPeriodNotGranted :: HasCallStack => TestParams -> IO () testClippedPlayPeriodNotGranted ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsController = cc, bsStore = store} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsController = cc, bsStore = store} -> do (purchaseKey, firstStart, purchased) <- subscribedMonthly env ledger <- ledgerRows cc "sx_badge_service_badge_ledger" -- Play dates the period ending on 31 March from the last day of February, and the ledger's month from then ends before 31 March @@ -2393,7 +2393,7 @@ testClippedPlayPeriodNotGranted ps = (otherKey, otherMasterKey) <- newPurchaseKeys let otherToken = "fake-play-token-clipped.AO-J1Op9n4cjW9qQl5" setSubscription store (SubscriptionGoogle otherToken) $ subscriptionCheck SSRenewing $ Just clipped - refusalOf <$> serviceCmd env otherKey (purchaseCmd otherMasterKey $ googlePayment "subscr_badge_supporter_01" otherToken) `shouldReturn` (BSEPaymentPending, Just 86400) + refusalOf <$> serviceCmd env otherKey (purchaseCmd otherMasterKey $ googlePayment "subscr_badge_supporter_01" otherToken) `shouldReturn` (STEPaymentPending, Just 86400) testPlayMonthEndWalk :: HasCallStack => TestParams -> IO () testPlayMonthEndWalk ps = walkPlayMonthEnd ps "subscr-badge-supporter-month-02" 1 5 @@ -2407,11 +2407,11 @@ testPlayAnnualMonthEndWalk ps = walkPlayMonthEnd ps "subscr-badge-supporter-year walkPlayMonthEnd :: HasCallStack => TestParams -> Text -> Integer -> Int -> IO () walkPlayMonthEnd ps planId planMonths months = withFakePlay $ \fake@FakePlay {fpConfig} -> do - let ini = takeDirectory (gServiceAccountFile fpConfig) "badge_service.ini" + let ini = takeDirectory (gServiceAccountFile fpConfig) "store_service.ini" writeFile ini "[listener]\nstatic_dir = /srv/badges\n" Right cfg <- readServiceConfig ini ServiceState {storeVerifier} <- newServiceState >>= configureStoreVerifier (Just cfg {playStore = Just fpConfig}) - withBadgeServiceVerifier ps (const storeVerifier) $ \env@BadgeServiceEnv {bsClock, bsController = cc} -> do + withStoreServiceVerifier ps (const storeVerifier) $ \env@StoreServiceEnv {bsClock, bsController = cc} -> do (purchaseKey, masterKey) <- newPurchaseKeys let anchor = UTCTime (fromGregorian 2027 1 31) 39600 periodEnd k = addMonths ((k + 1) * planMonths) anchor @@ -2421,7 +2421,7 @@ walkPlayMonthEnd ps planId planMonths months = item = lineItem [("expiryTime", J.toJSON $ periodEnd k), ("latestSuccessfulOrderId", J.String $ "GPA.1234-5678-9012-34567.." <> tshow k), basePlan planId] [] answerPurchase fake googleSubscriptionToken $ PlayRecord $ subscriptionRecord "SUBSCRIPTION_STATE_ACTIVE" [] [item] setClockAt bsClock t - monthIssued :: UTCTime -> Int -> BadgeServiceResponse -> IO (StatementEntry, UTCTime, UTCTime) + monthIssued :: UTCTime -> Int -> StoreServiceResponse -> IO (StatementEntry, UTCTime, UTCTime) monthIssued t monthsHeld answer = do let rows = fst $ statementOf answer expected @@ -2453,21 +2453,21 @@ walkPlayMonthEnd ps planId planMonths months = testSubscriptionStoreUnreachable :: HasCallStack => TestParams -> IO () testSubscriptionStoreUnreachable ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsController = cc, bsStore = store} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsController = cc, bsStore = store} -> do (purchaseKey, firstStart, purchased) <- subscribedMonthly env ledger <- ledgerRows cc "sx_badge_service_badge_ledger" let ended = addUTCTime (3 * nominalDay) (addMonths 1 firstStart) storeReports store $ subscriptionCheck SSRenewing $ Just $ monthlyCharge "subscr-badge-supporter-month-02" firstStart 1 setGoogleDown store True setClockAt bsClock ended - refusalOf <$> assertBalance env purchaseKey (last purchased) `shouldReturn` (BSEProviderUnavailable, Just 3600) + refusalOf <$> assertBalance env purchaseKey (last purchased) `shouldReturn` (STEProviderUnavailable, Just 3600) subscriptionCheckedAt cc >>= (`shouldSatisfy` \case [Just t] -> abs (diffUTCTime t ended) < 60; _ -> False) ledgerRows cc "sx_badge_service_badge_ledger" `shouldReturn` ledger rowCount cc "sx_badge_service_subscription_charges" `shouldReturn` 1 testAppleSubscriptionRenews :: HasCallStack => TestParams -> IO () testAppleSubscriptionRenews ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsController = cc@ChatController {chatStore}, bsStore = store@FakeStore {appleSubscriptionJWS}} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsController = cc@ChatController {chatStore}, bsStore = store@FakeStore {appleSubscriptionJWS}} -> do firstStart <- addUTCTime (-3600) <$> serviceNow env let monthly = "SUBSCR_BADGE_SUPPORTER_MONTH_01" appleReports = setSubscription store (SubscriptionApple appleSubscriptionOriginalId) . subscriptionCheck SSRenewing . Just @@ -2505,8 +2505,8 @@ testAppleSubscriptionRenews ps = rowCount cc "sx_badge_service_subscription_charges" `shouldReturn` 2 -- | The client buys a monthly Play subscription an hour into its first period: that period's start, and its ledger then. -clientSubscribedMonthly :: HasCallStack => BadgeServiceEnv -> TestCC -> IO (UTCTime, [ReplicatedRow]) -clientSubscribedMonthly env@BadgeServiceEnv {bsStore} alice = do +clientSubscribedMonthly :: HasCallStack => StoreServiceEnv -> TestCC -> IO (UTCTime, [ReplicatedRow]) +clientSubscribedMonthly env@StoreServiceEnv {bsStore} alice = do firstStart <- monthEndStart env storeReports bsStore $ subscriptionCheck SSRenewing $ Just $ storeCharge "subscr-badge-supporter-month-02" firstStart 1 alice ##> ("/_badge purchase 1 " <> paymentArg subscriptionPlay) @@ -2535,7 +2535,7 @@ rowChanges = map (\(_, ch, m, start, _, t) -> (ch, m, start, t)) testSubscriptionRenews :: HasCallStack => TestParams -> IO () testSubscriptionRenews ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do (firstStart, rows) <- clientSubscribedMonthly env alice let (requestAt, presentAt) = renewalMoments rows @@ -2561,7 +2561,7 @@ testSubscriptionRenews ps = testSubscriptionTierChangeAtRenewal :: HasCallStack => TestParams -> IO () testSubscriptionTierChangeAtRenewal ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc, bsStore = store@FakeStore {appleSubscriptionJWS}} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsController = cc, bsStore = store@FakeStore {appleSubscriptionJWS}} -> do withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do firstStart <- monthEndStart env let monthly plan n = (monthlyCharge plan firstStart n) {chargeRef = "apple.renewal." <> tshow n} @@ -2626,12 +2626,12 @@ issuedBadgeTypes :: ChatController -> IO [Text] issuedBadgeTypes ChatController {chatStore} = withTransaction chatStore $ \db -> map fromOnly <$> DB.query_ db "SELECT badge_type FROM badge_issuances ORDER BY period_end" -upgradeCmdWith :: Text -> StatementEntry -> BadgeServiceCommand -upgradeCmdWith jws lastEntry = BSCUpgradeBadgeSubscription {payment = SPApple {jws}, balance = BadgeBalance {lastEntry}} +upgradeCmdWith :: Text -> StatementEntry -> StoreServiceCommand +upgradeCmdWith jws lastEntry = STCUpgradeBadgeSubscription {payment = SPApple {jws}, balance = BadgeBalance {lastEntry}} testSubscriptionUpgradeNow :: HasCallStack => TestParams -> IO () testSubscriptionUpgradeNow ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsController = cc, bsStore = store@FakeStore {appleSubscriptionJWS, appleLegendSubscriptionJWS}} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsController = cc, bsStore = store@FakeStore {appleSubscriptionJWS, appleLegendSubscriptionJWS}} -> do firstStart <- addUTCTime (-3600) <$> serviceNow env appleStoreReports store $ subscriptionCheck SSRenewing $ Just $ storeCharge "SUBSCR_BADGE_SUPPORTER_YEAR_01" firstStart 12 (purchaseKey, masterKey) <- newPurchaseKeys @@ -2652,14 +2652,14 @@ testSubscriptionUpgradeNow ps = subscriptionChecks store `shouldReturn` checks ledgerRows cc "sx_badge_service_badge_ledger" `shouldReturn` ledger -- while the store still reports the Supporter plan, nothing is granted and the Supporter credential is not given - refusalOf <$> upgrade appleLegendSubscriptionJWS `shouldReturn` (BSEPaymentPending, Just 3600) + refusalOf <$> upgrade appleLegendSubscriptionJWS `shouldReturn` (STEPaymentPending, Just 3600) subscriptionChecks store `shouldReturn` checks + 1 subscriptionCheckedAt cc >>= (`shouldSatisfy` \case [Just t] -> abs (diffUTCTime t upgradedAt) < 60; _ -> False) ledgerRows cc "sx_badge_service_badge_ledger" `shouldReturn` ledger -- the store now reports Legend, but the hour since it was asked holds appleStoreReports store $ subscriptionCheck SSRenewing $ Just (storeCharge "SUBSCR_BADGE_LEGEND_YEAR_01" upgradedAt 12) {chargeRef = "apple.legend"} setClockAt bsClock $ addUTCTime 1800 upgradedAt - refusalOf <$> upgrade appleLegendSubscriptionJWS >>= (`shouldSatisfy` \case (BSEPaymentPending, Just s) -> s > 1740 && s <= 1801; _ -> False) + refusalOf <$> upgrade appleLegendSubscriptionJWS >>= (`shouldSatisfy` \case (STEPaymentPending, Just s) -> s > 1740 && s <= 1801; _ -> False) subscriptionChecks store `shouldReturn` checks + 1 -- past it, the unissued Supporter months are debited and the Legend year starts at the store's period setClockAt bsClock $ addUTCTime 3700 upgradedAt @@ -2679,7 +2679,7 @@ testSubscriptionUpgradeNow ps = testSubscriptionUpgradeLateInMonth :: HasCallStack => TestParams -> IO () testSubscriptionUpgradeLateInMonth ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsStore = store@FakeStore {appleSubscriptionJWS, appleLegendSubscriptionJWS}} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsStore = store@FakeStore {appleSubscriptionJWS, appleLegendSubscriptionJWS}} -> do let anchor = UTCTime (fromGregorian 2027 1 31) 36000 upgradedAt = UTCTime (fromGregorian 2027 2 28) 54000 legendEnd = addMonths 1 upgradedAt @@ -2715,7 +2715,7 @@ testSubscriptionUpgradeLateInMonth ps = testUpgradeCheckGrantsRenewal :: HasCallStack => TestParams -> IO () testUpgradeCheckGrantsRenewal ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsController = cc, bsStore = store@FakeStore {appleSubscriptionJWS, appleLegendSubscriptionJWS}} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsController = cc, bsStore = store@FakeStore {appleSubscriptionJWS, appleLegendSubscriptionJWS}} -> do firstStart <- monthEndStart env appleStoreReports store $ subscriptionCheck SSRenewing $ Just $ storeCharge "SUBSCR_BADGE_SUPPORTER_MONTH_01" firstStart 1 (purchaseKey, masterKey) <- newPurchaseKeys @@ -2727,7 +2727,7 @@ testUpgradeCheckGrantsRenewal ps = appleStoreReports store $ subscriptionCheck SSRenewing $ Just (monthlyCharge "SUBSCR_BADGE_SUPPORTER_MONTH_01" firstStart 1) {chargeRef = "apple.renewal"} setClockAt bsClock upgradedAt checks <- subscriptionChecks store - refusalOf <$> serviceCmd env purchaseKey (upgradeCmdWith appleLegendSubscriptionJWS tip) `shouldReturn` (BSEPaymentPending, Just 3600) + refusalOf <$> serviceCmd env purchaseKey (upgradeCmdWith appleLegendSubscriptionJWS tip) `shouldReturn` (STEPaymentPending, Just 3600) subscriptionChecks store `shouldReturn` checks + 1 -- the check granted the renewal, so the hour's requests get its month without asking the store renewed <- assertBalance env purchaseKey tip @@ -2745,7 +2745,7 @@ testUpgradeCheckGrantsRenewal ps = testUpgradeRequestRefused :: HasCallStack => TestParams -> IO () testUpgradeRequestRefused ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsIssuerKey, bsVerifier, bsPurchaseChecks, bsController = cc, bsStore = store@FakeStore {appleSubscriptionJWS, appleLegendSubscriptionJWS, appleSecondSubscriptionJWS, appleSupporterJWS}} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsIssuerKey, bsVerifier, bsPurchaseChecks, bsController = cc, bsStore = store@FakeStore {appleSubscriptionJWS, appleLegendSubscriptionJWS, appleSecondSubscriptionJWS, appleSupporterJWS}} -> do now <- serviceNow env appleStoreReports store $ subscriptionCheck SSRenewing $ Just $ storeCharge "SUBSCR_BADGE_SUPPORTER_MONTH_01" (addUTCTime (-3600) now) 1 (appleKey, appleMasterKey) <- newPurchaseKeys @@ -2759,31 +2759,31 @@ testUpgradeRequestRefused ps = let appleTip = last $ fst $ statementOf apple refused key cmd = refusalOf <$> serviceCmd env key cmd -- signed by another key than the purchase it names - refusalOf <$> badgeServiceResponse bsIssuerKey bsVerifier bsPurchaseChecks cc Nothing (Just playKey) (requestObject appleKey $ upgradeCmdWith appleLegendSubscriptionJWS appleTip) - `shouldReturn` (BSEBadRequest, Nothing) - refused unknownKey (upgradeCmdWith appleLegendSubscriptionJWS appleTip) `shouldReturn` (BSEUnknownPurchaseKey, Nothing) + refusalOf <$> storeServiceResponse bsIssuerKey bsVerifier bsPurchaseChecks cc Nothing (Just playKey) (requestObject appleKey $ upgradeCmdWith appleLegendSubscriptionJWS appleTip) + `shouldReturn` (STEBadRequest, Nothing) + refused unknownKey (upgradeCmdWith appleLegendSubscriptionJWS appleTip) `shouldReturn` (STEUnknownPurchaseKey, Nothing) -- another purchase's subscription, and another subscription for this purchase - refused playKey (upgradeCmdWith appleLegendSubscriptionJWS $ last played) `shouldReturn` (BSEBadRequest, Nothing) - refused appleKey (upgradeCmdWith appleSecondSubscriptionJWS appleTip) `shouldReturn` (BSEBadRequest, Nothing) - refused prepaidKey (upgradeCmdWith appleLegendSubscriptionJWS $ last $ fst $ statementOf prepaid) `shouldReturn` (BSEBadRequest, Nothing) + refused playKey (upgradeCmdWith appleLegendSubscriptionJWS $ last played) `shouldReturn` (STEBadRequest, Nothing) + refused appleKey (upgradeCmdWith appleSecondSubscriptionJWS appleTip) `shouldReturn` (STEBadRequest, Nothing) + refused prepaidKey (upgradeCmdWith appleLegendSubscriptionJWS $ last $ fst $ statementOf prepaid) `shouldReturn` (STEBadRequest, Nothing) -- a transaction the verifier does not vouch for, one of no subscription product, and Play - refused appleKey (upgradeCmdWith (subscriptionJWS appleSubscriptionOriginalId "2000000812345689" []) appleTip) `shouldReturn` (BSEReceiptInvalid, Nothing) - refused appleKey (upgradeCmdWith appleSupporterJWS appleTip) `shouldReturn` (BSEBadRequest, Nothing) - refused playKey BSCUpgradeBadgeSubscription {payment = subscriptionPlay, balance = BadgeBalance {lastEntry = last played}} `shouldReturn` (BSEBadRequest, Nothing) + refused appleKey (upgradeCmdWith (subscriptionJWS appleSubscriptionOriginalId "2000000812345689" []) appleTip) `shouldReturn` (STEReceiptInvalid, Nothing) + refused appleKey (upgradeCmdWith appleSupporterJWS appleTip) `shouldReturn` (STEBadRequest, Nothing) + refused playKey STCUpgradeBadgeSubscription {payment = subscriptionPlay, balance = BadgeBalance {lastEntry = last played}} `shouldReturn` (STEBadRequest, Nothing) subscriptionChecks store `shouldReturn` checks ledgerRows cc "sx_badge_service_badge_ledger" `shouldReturn` ledger -transferCmd :: BadgeMasterKey -> ServicePayment -> BadgeServiceCommand -transferCmd masterKey payment = BSCTransferBadge {masterKey, payment} +transferCmd :: BadgeMasterKey -> ServicePayment -> StoreServiceCommand +transferCmd masterKey payment = STCTransferBadge {masterKey, payment} -transferWithNewKey :: HasCallStack => BadgeServiceEnv -> ServicePayment -> IO (C.PublicKeyEd25519, BadgeServiceResponse) +transferWithNewKey :: HasCallStack => StoreServiceEnv -> ServicePayment -> IO (C.PublicKeyEd25519, StoreServiceResponse) transferWithNewKey env payment = do (purchaseKey, masterKey) <- newPurchaseKeys (purchaseKey,) <$> serviceCmd env purchaseKey (transferCmd masterKey payment) -- | Past the hour a claim's store check holds the next one off. -nextClaimCheck :: BadgeServiceEnv -> IO () -nextClaimCheck BadgeServiceEnv {bsClock} = testClockTime bsClock >>= setClockAt bsClock . addUTCTime 3700 +nextClaimCheck :: StoreServiceEnv -> IO () +nextClaimCheck StoreServiceEnv {bsClock} = testClockTime bsClock >>= setClockAt bsClock . addUTCTime 3700 movedOutTo :: StatementEntry -> Maybe C.PublicKeyEd25519 movedOutTo StatementEntry {entryType = SEDebit (SDTransferOut k)} = Just k @@ -2794,7 +2794,7 @@ reboundPayments cc = rowCount cc "sx_badge_service_payments WHERE rebound_at IS testStoreRebind :: HasCallStack => TestParams -> IO () testStoreRebind ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsController = cc, bsStore = store@FakeStore {appleSubscriptionJWS}} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsController = cc, bsStore = store@FakeStore {appleSubscriptionJWS}} -> do let changes = map (\e -> let (c, m, _) = entryOf e in (c, m)) verified badgeType rows = verifiedAfter badgeType Nothing rows verifiedAfter badgeType tip_ rows = do @@ -2840,7 +2840,7 @@ testStoreRebind ps = testStoreRebindNewCharge :: HasCallStack => TestParams -> IO () testStoreRebindNewCharge ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsController = cc, bsStore = store} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsController = cc, bsStore = store} -> do (oldKey, firstStart, purchased) <- subscribedMonthly env let chargeStart = addMonths 2 firstStart changes = map (\e -> let (c, m, _) = entryOf e in (c, m)) @@ -2877,7 +2877,7 @@ testStoreRebindNewCharge ps = testStoreRebindCapped :: HasCallStack => TestParams -> IO () testStoreRebindCapped ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsStore = store} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsStore = store} -> do (_, firstStart, _) <- subscribedMonthly env let firstExpiry = endOfMondayAfter (addMonths 1 firstStart) nextClaimCheck env @@ -2886,7 +2886,7 @@ testStoreRebindCapped ps = expiryOf firstMove `shouldBe` Just firstExpiry nextClaimCheck env checks <- subscriptionChecks store - refusalOf . snd <$> transferWithNewKey env subscriptionPlay `shouldReturn` (BSETransferLimited, Nothing) + refusalOf . snd <$> transferWithNewKey env subscriptionPlay `shouldReturn` (STETransferLimited, Nothing) subscriptionChecks store `shouldReturn` checks + 1 -- past the first key's credential the first move's key renews, into a credential that outlives the first storeReports store $ subscriptionCheck SSRenewing $ Just $ monthlyCharge "subscr-badge-supporter-month-02" firstStart 1 @@ -2896,11 +2896,11 @@ testStoreRebindCapped ps = (_, secondMove) <- transferWithNewKey env subscriptionPlay credentialOf secondMove `shouldSatisfy` isJust nextClaimCheck env - refusalOf . snd <$> transferWithNewKey env subscriptionPlay `shouldReturn` (BSETransferLimited, Nothing) + refusalOf . snd <$> transferWithNewKey env subscriptionPlay `shouldReturn` (STETransferLimited, Nothing) testStoreRebindOldKeyEnded :: HasCallStack => TestParams -> IO () testStoreRebindOldKeyEnded ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsStore = store} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsStore = store} -> do (purchaseKey, _, purchased) <- subscribedMonthly env nextClaimCheck env (_, moved) <- transferWithNewKey env subscriptionPlay @@ -2912,11 +2912,11 @@ testStoreRebindOldKeyEnded ps = subscriptionChecks store `shouldReturn` checks nextClaimCheck env (_, masterKey) <- newPurchaseKeys - refusalOf <$> serviceCmd env purchaseKey (purchaseCmd masterKey subscriptionPlay) `shouldReturn` (BSEReceiptUsed, Nothing) + refusalOf <$> serviceCmd env purchaseKey (purchaseCmd masterKey subscriptionPlay) `shouldReturn` (STEReceiptUsed, Nothing) testStoreRebindStaleAppleTransaction :: HasCallStack => TestParams -> IO () testStoreRebindStaleAppleTransaction ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsController = cc, bsStore = store@FakeStore {appleSubscriptionJWS, appleRenewalSubscriptionJWS}} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsController = cc, bsStore = store@FakeStore {appleSubscriptionJWS, appleRenewalSubscriptionJWS}} -> do now <- serviceNow env appleStoreReports store $ subscriptionCheck SSRenewing $ Just (storeCharge "SUBSCR_BADGE_SUPPORTER_MONTH_01" (addUTCTime (-3600) now) 1) {chargeRef = "2000000812345683"} (purchaseKey, masterKey) <- newPurchaseKeys @@ -2924,7 +2924,7 @@ testStoreRebindStaleAppleTransaction ps = nextClaimCheck env ledger <- ledgerRows cc "sx_badge_service_badge_ledger" checks <- subscriptionChecks store - refusalOf . snd <$> transferWithNewKey env SPApple {jws = appleSubscriptionJWS} `shouldReturn` (BSEPaymentPending, Just 3600) + refusalOf . snd <$> transferWithNewKey env SPApple {jws = appleSubscriptionJWS} `shouldReturn` (STEPaymentPending, Just 3600) subscriptionChecks store `shouldReturn` checks + 1 ledgerRows cc "sx_badge_service_badge_ledger" `shouldReturn` ledger rowCount cc "sx_badge_service_badge_purchases" `shouldReturn` 1 @@ -2935,7 +2935,7 @@ testStoreRebindStaleAppleTransaction ps = testTransferUncredited :: HasCallStack => TestParams -> IO () testTransferUncredited ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsController = cc, bsStore = store} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsController = cc, bsStore = store} -> do periodStart <- addUTCTime (-3600) <$> serviceNow env storeReports store $ subscriptionCheck SSRenewing $ Just $ storeCharge "subscr-badge-supporter-month-02" periodStart 1 (_, transferred) <- transferWithNewKey env subscriptionPlay @@ -2948,7 +2948,7 @@ testTransferUncredited ps = testTransferReplayAnswered :: HasCallStack => TestParams -> IO () testTransferReplayAnswered ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsStore = store} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsStore = store} -> do _ <- subscribedMonthly env nextClaimCheck env (movedKey, movedMasterKey) <- newPurchaseKeys @@ -2961,14 +2961,14 @@ testTransferReplayAnswered ps = testTransferKnownKeyRefused :: HasCallStack => TestParams -> IO () testTransferKnownKeyRefused ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsController = cc, bsStore = store} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsController = cc, bsStore = store} -> do _ <- subscribedMonthly env (heldKey, heldMasterKey) <- newPurchaseKeys _ <- serviceCmd env heldKey $ purchaseCmd heldMasterKey supporterPlay nextClaimCheck env checks <- subscriptionChecks store ledger <- ledgerRows cc "sx_badge_service_badge_ledger" - refusalOf <$> serviceCmd env heldKey (transferCmd heldMasterKey subscriptionPlay) `shouldReturn` (BSEBadRequest, Nothing) + refusalOf <$> serviceCmd env heldKey (transferCmd heldMasterKey subscriptionPlay) `shouldReturn` (STEBadRequest, Nothing) subscriptionChecks store `shouldReturn` checks ledgerRows cc "sx_badge_service_badge_ledger" `shouldReturn` ledger rowCount cc "sx_badge_service_badge_purchases" `shouldReturn` 2 @@ -2977,7 +2977,7 @@ testTransferKnownKeyRefused ps = -- | Restore presents every transaction it finds as a transfer, a one-time purchase bought on another device included. testTransferOneTimeRefused :: HasCallStack => TestParams -> IO () testTransferOneTimeRefused ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsController = cc, bsStore = store@FakeStore {appleSupporterJWS}} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsController = cc, bsStore = store@FakeStore {appleSupporterJWS}} -> do let oneTime = [supporterPlay, SPApple {jws = appleSupporterJWS}] owned <- forM oneTime $ \payment -> do (ownerKey, ownerMasterKey) <- newPurchaseKeys @@ -2985,7 +2985,7 @@ testTransferOneTimeRefused ps = pure (ownerKey, ownerMasterKey, payment, purchased) checks <- subscriptionChecks store ledger <- ledgerRows cc "sx_badge_service_badge_ledger" - forM_ oneTime $ \payment -> refusalOf . snd <$> transferWithNewKey env payment `shouldReturn` (BSEReceiptUsed, Nothing) + forM_ oneTime $ \payment -> refusalOf . snd <$> transferWithNewKey env payment `shouldReturn` (STEReceiptUsed, Nothing) subscriptionChecks store `shouldReturn` checks ledgerRows cc "sx_badge_service_badge_ledger" `shouldReturn` ledger rowCount cc "sx_badge_service_badge_purchases" `shouldReturn` 2 @@ -3021,7 +3021,7 @@ dropOutput cc = timeout 1000000 (atomically $ readTQueue $ termQ cc) >>= mapM_ ( testRestoreOnNewDevice :: HasCallStack => TestParams -> IO () testRestoreOnNewDevice ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsController = cc, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> withNewTestChatCfg ps bsClientCfg "bob" bobProfile $ \bob -> do firstStart <- addUTCTime (-3600) <$> serviceNow env @@ -3051,7 +3051,7 @@ testRestoreOnNewDevice ps = testRestoreMovedOutAskedInMonth :: HasCallStack => TestParams -> IO () testRestoreMovedOutAskedInMonth ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg {badgeDevRequests = True} "alice" aliceProfile $ \alice -> withNewTestChatCfg ps bsClientCfg "bob" bobProfile $ \bob -> do firstStart <- addUTCTime (-3600) <$> serviceNow env @@ -3068,8 +3068,8 @@ testRestoreMovedOutAskedInMonth ps = testRestoreHeldPerPurpose :: HasCallStack => TestParams -> IO () testRestoreHeldPerPurpose ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsStore = store} -> do - let heldFor s (code, retryAfter) = code == BSEPaymentPending && maybe False (\t -> t > s - 60 && t <= s + 60) retryAfter + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsStore = store} -> do + let heldFor s (code, retryAfter) = code == STEPaymentPending && maybe False (\t -> t > s - 60 && t <= s + 60) retryAfter _ <- subscribedMonthly env purchasedAt <- testClockTime bsClock setClockAt bsClock $ addUTCTime 1800 purchasedAt @@ -3083,14 +3083,14 @@ testRestoreHeldPerPurpose ps = subscriptionChecks store `shouldReturn` checks + 1 (otherKey, otherMasterKey) <- newPurchaseKeys let presented = refusalOf <$> serviceCmd env otherKey (purchaseCmd otherMasterKey subscriptionPlay) - presented `shouldReturn` (BSEReceiptUsed, Nothing) + presented `shouldReturn` (STEReceiptUsed, Nothing) subscriptionChecks store `shouldReturn` checks + 2 presented >>= (`shouldSatisfy` heldFor 3600) subscriptionChecks store `shouldReturn` checks + 2 testRestoreOnOtherProfile :: HasCallStack => TestParams -> IO () testRestoreOnOtherProfile ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsController = cc, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do let a = chatController alice firstStart <- addUTCTime (-3600) <$> serviceNow env @@ -3135,7 +3135,7 @@ testRestoreOnOtherProfile ps = testRestoreMovesBack :: HasCallStack => TestParams -> IO () testRestoreMovesBack ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> withNewTestChatCfg ps bsClientCfg "bob" bobProfile $ \bob -> do firstStart <- addUTCTime (-3600) <$> serviceNow env @@ -3162,7 +3162,7 @@ testRestoreMovesBack ps = testRestoreLimitedOnNewDevice :: HasCallStack => TestParams -> IO () testRestoreLimitedOnNewDevice ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> withNewTestChatCfg ps bsClientCfg "bob" bobProfile $ \bob -> withNewTestChatCfg ps bsClientCfg "cath" cathProfile $ \cath -> do @@ -3189,7 +3189,7 @@ testRestoreLimitedOnNewDevice ps = testRestoreLeavesTierChangeHold :: HasCallStack => TestParams -> IO () testRestoreLeavesTierChangeHold ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClientCfg, bsStore = FakeStore {appleLegendSubscriptionJWS}} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClientCfg, bsStore = FakeStore {appleLegendSubscriptionJWS}} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do let a = chatController alice legend = SPApple {jws = appleLegendSubscriptionJWS} @@ -3207,7 +3207,7 @@ testRestoreLeavesTierChangeHold ps = -- | A Restore takes a held record without its owner's lock, so the owner's worker checks it again under the lock. testStoreReceiptHeldForAfterRestore :: HasCallStack => TestParams -> IO () testStoreReceiptHeldForAfterRestore ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClientCfg} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClientCfg} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do alice ##> "/create user alisa" showActiveUser alice "alisa" @@ -3228,7 +3228,7 @@ testStoreReceiptHeldForAfterRestore ps = testRefusedMoveKeepsTierChange :: HasCallStack => TestParams -> IO () testRefusedMoveKeepsTierChange ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsStore = store@FakeStore {appleSubscriptionJWS, appleLegendSubscriptionJWS}, bsClientCfg} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsStore = store@FakeStore {appleSubscriptionJWS, appleLegendSubscriptionJWS}, bsClientCfg} -> withNewTestChatCfg ps bsClientCfg "bob" bobProfile $ \bob -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do let a = chatController alice @@ -3253,7 +3253,7 @@ testRefusedMoveKeepsTierChange ps = testRestoreHeldProfileDeleted :: HasCallStack => TestParams -> IO () testRestoreHeldProfileDeleted ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do let a = chatController alice firstStart <- addUTCTime (-3600) <$> serviceNow env @@ -3281,7 +3281,7 @@ testRestoreHeldProfileDeleted ps = testRestoreTakesHeldPurchase :: HasCallStack => TestParams -> IO () testRestoreTakesHeldPurchase ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "bob" bobProfile $ \bob -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do let a = chatController alice @@ -3305,7 +3305,7 @@ testRestoreTakesHeldPurchase ps = testRestoreOnSameProfile :: HasCallStack => TestParams -> IO () testRestoreOnSameProfile ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsController = cc, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do let a = chatController alice (_, rows) <- clientSubscribedMonthly env alice @@ -3342,7 +3342,7 @@ testRestoreOnSameProfile ps = testRestoreLeavesResumeHold :: HasCallStack => TestParams -> IO () testRestoreLeavesResumeHold ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "dan" danProfile $ \dan -> do requestAt <- appleSubscriptionRetired env dan let resubscribedAt = addUTCTime 7200 requestAt @@ -3360,7 +3360,7 @@ testRestoreLeavesResumeHold ps = testRestoreAfterUnfinishedPass :: HasCallStack => TestParams -> IO () testRestoreAfterUnfinishedPass ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> withNewTestChatCfg ps bsClientCfg "bob" bobProfile $ \bob -> withNewTestChatCfg ps bsClientCfg "cath" cathProfile $ \cath -> do @@ -3393,7 +3393,7 @@ testRestoreAfterUnfinishedPass ps = testSubscriptionAwaitsCharge :: HasCallStack => TestParams -> IO () testSubscriptionAwaitsCharge ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsController = cc, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do (_, rows) <- clientSubscribedMonthly env alice let (requestAt, presentAt) = renewalMoments rows @@ -3442,7 +3442,7 @@ testSubscriptionAwaitsCharge ps = testFarWakeHoldsNothing :: HasCallStack => TestParams -> IO () testFarWakeHoldsNothing ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do (_, rows) <- clientSubscribedMonthly env alice let (requestAt, presentAt) = renewalMoments rows @@ -3468,7 +3468,7 @@ testFarWakeHoldsNothing ps = testStoreUnreachableWaitsStall :: HasCallStack => TestParams -> IO () testStoreUnreachableWaitsStall ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsController = cc, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do (firstStart, rows) <- clientSubscribedMonthly env alice let (requestAt, presentAt) = renewalMoments rows @@ -3480,7 +3480,7 @@ testStoreUnreachableWaitsStall ps = alice <### [ "/_app activate", "ok", - "bad chat command: badge service error: provider_unavailable", + "bad chat command: store service error: provider_unavailable", StartsWith "1: supporter" ] waitWakeFrom (chatController alice) (addUTCTime (nominalDay - 60) requestAt) @@ -3509,7 +3509,7 @@ testStoreUnreachableWaitsStall ps = testSnoozeKeepsRequestWait :: HasCallStack => TestParams -> IO () testSnoozeKeepsRequestWait ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsController = cc, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do (firstStart, rows) <- clientSubscribedMonthly env alice let (requestAt, presentAt) = renewalMoments rows @@ -3549,7 +3549,7 @@ testSnoozeKeepsRequestWait ps = testStallRejoinsSharedMoment :: HasCallStack => TestParams -> IO () testStallRejoinsSharedMoment ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do (_, rows) <- clientSubscribedMonthly env alice let (requestAt, presentAt) = renewalMoments rows @@ -3577,8 +3577,8 @@ testStallRejoinsSharedMoment ps = nextWakes (chatController alice) `shouldEventuallyReturn` [Just $ addUTCTime (2 * nominalDay) presentAt] -- | A service that asks its store at every issue request, so the store's check count counts the client's requests. -withRequestCountingService :: HasCallStack => TestParams -> (BadgeServiceEnv -> IO ()) -> IO () -withRequestCountingService ps = withBadgeServiceVerifier ps $ \store -> (fakeVerifier store) {storeChecks = ChecksAtEveryRequest} +withRequestCountingService :: HasCallStack => TestParams -> (StoreServiceEnv -> IO ()) -> IO () +withRequestCountingService ps = withStoreServiceVerifier ps $ \store -> (fakeVerifier store) {storeChecks = ChecksAtEveryRequest} -- | An hour past a midnight UTC three days before paidThrough: inside coverage, with the next daily moment of the -- shown expiry 23 hours on and every ledger moment days away, so only the dev interval can bring a request. @@ -3593,7 +3593,7 @@ activateAt cc clock t = do testDevIntervalRequests :: HasCallStack => TestParams -> IO () testDevIntervalRequests ps = - withRequestCountingService ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store} -> + withRequestCountingService ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg {badgeDevRequestInterval = Just 600} "alice" aliceProfile $ \alice -> do (_, rows) <- clientSubscribedMonthly env alice let t1 = devIntervalStart rows @@ -3624,7 +3624,7 @@ testDevIntervalRequests ps = testNoDevIntervalRequests :: HasCallStack => TestParams -> IO () testNoDevIntervalRequests ps = - withRequestCountingService ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store} -> + withRequestCountingService ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do (_, rows) <- clientSubscribedMonthly env alice let t1 = devIntervalStart rows @@ -3638,10 +3638,10 @@ testNoDevIntervalRequests ps = testDevIntervalRetries :: HasCallStack => TestParams -> IO () testDevIntervalRetries ps = - withRequestCountingService ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> do + withRequestCountingService ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> do let hourly cfg = cfg {badgeDevRequestInterval = Just 3600} rows <- withNewTestChatCfg ps (hourly bsClientCfg) "alice" aliceProfile $ \alice -> snd <$> clientSubscribedMonthly env alice - stopBadgeService cc + stopStoreService cc let t1 = devIntervalStart rows -- the start's pass sends the request the interval made due, which times out and is retried setClockAt bsClock t1 @@ -3655,14 +3655,14 @@ testDevIntervalRetries ps = testSubscriptionRetiredAfterRecoveryWindow :: HasCallStack => TestParams -> IO () testSubscriptionRetiredAfterRecoveryWindow ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do (_, rows) <- clientSubscribedMonthly env alice setServicePurchaseKey cc "not the purchase key" - t0 <- firstUnrenewedAnswer alice bsClock rows [badgeServiceRefused] + t0 <- firstUnrenewedAnswer alice bsClock rows [storeServiceRefused] let beforeEnd = addUTCTime (subscriptionRecoveryWindow - 3600) t0 setClockAt bsClock beforeEnd - activateAnswered alice [badgeServiceRefused] + activateAnswered alice [storeServiceRefused] fst <$> answeredRun (chatController alice) beforeEnd `shouldReturn` t0 shownBadgeId (chatController alice) >>= (`shouldSatisfy` isJust) errorAt <- issueErrorAt (chatController alice) @@ -3673,7 +3673,7 @@ testSubscriptionRetiredAfterRecoveryWindow ps = alice <### [ "/_app activate", "ok", - ConsoleString badgeServiceRefused, + ConsoleString storeServiceRefused, StartsWith "badge alert: subscription_ended ", StartsWith "1: supporter", StartsWith "renewal failing since ", @@ -3690,7 +3690,7 @@ testSubscriptionRetiredAfterRecoveryWindow ps = testBankedSubscriptionNotRetired :: HasCallStack => TestParams -> IO () testBankedSubscriptionNotRetired ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsController = cc, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do firstStart <- addUTCTime (-3600) <$> serviceNow env storeReports store $ subscriptionCheck SSRenewing $ Just $ storeCharge "subscr-badge-supporter-year-01" firstStart 12 @@ -3705,7 +3705,7 @@ testBankedSubscriptionNotRetired ps = alice <### [ "/_app activate", "ok", - ConsoleString badgeServiceRefused, + ConsoleString storeServiceRefused, StartsWith "badge alert: issue_failed ", StartsWith "1: supporter", StartsWith "renewal failing since ", @@ -3715,7 +3715,7 @@ testBankedSubscriptionNotRetired ps = testIdleSubscriptionKeptPastWindow :: HasCallStack => TestParams -> IO () testIdleSubscriptionKeptPastWindow ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do (firstStart, rows) <- clientSubscribedMonthly env alice -- the store kept charging while the app was not opened: its third renewal covers the day of the first activation @@ -3733,12 +3733,12 @@ testIdleSubscriptionKeptPastWindow ps = testSubscriptionNotRetiredWithoutAnswer :: HasCallStack => TestParams -> IO () testSubscriptionNotRetiredWithoutAnswer ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> do t0 <- withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do (_, rows) <- clientSubscribedMonthly env alice setServicePurchaseKey cc "not the purchase key" - firstUnrenewedAnswer alice bsClock rows [badgeServiceRefused] - stopBadgeService cc + firstUnrenewedAnswer alice bsClock rows [storeServiceRefused] + stopStoreService cc setClockAt bsClock $ addUTCTime (subscriptionRecoveryWindow + 3600) t0 withTestChatCfg ps (failingServiceCfg bsClientCfg) "alice" $ \alice -> do alice <##. "1: supporter" @@ -3751,13 +3751,13 @@ testSubscriptionNotRetiredWithoutAnswer ps = testUnrenewedRunStartsAtFirstAnswer :: HasCallStack => TestParams -> IO () testUnrenewedRunStartsAtFirstAnswer ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do (_, rows) <- clientSubscribedMonthly env alice setGoogleDown store True -- not opened for longer than the window: the first answer, which grants nothing, starts the run let firstAnswerAt = addUTCTime (subscriptionRecoveryWindow + nominalDay) $ dueAtOf rows - unreachable = "bad chat command: badge service error: provider_unavailable" + unreachable = "bad chat command: store service error: provider_unavailable" setClockAt bsClock firstAnswerAt activateAnswered alice [unreachable] shownBadgeId (chatController alice) >>= (`shouldSatisfy` isJust) @@ -3775,7 +3775,7 @@ testUnrenewedRunStartsAtFirstAnswer ps = testRenewalEndsUnrenewedRun :: HasCallStack => TestParams -> IO () testRenewalEndsUnrenewedRun ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do (firstStart, rows) <- clientSubscribedMonthly env alice storeReports store $ subscriptionCheck SSBillingRetry Nothing @@ -3806,11 +3806,11 @@ testRenewalEndsUnrenewedRun ps = testAbsenceRestartsUnrenewedRun :: HasCallStack => TestParams -> IO () testAbsenceRestartsUnrenewedRun ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do (_, rows) <- clientSubscribedMonthly env alice setServicePurchaseKey cc "not the purchase key" - t0 <- firstUnrenewedAnswer alice bsClock rows [badgeServiceRefused] + t0 <- firstUnrenewedAnswer alice bsClock rows [storeServiceRefused] -- held by the wake the refusal stored, so nothing is sent and the run stays setClockAt bsClock $ addUTCTime 3600 t0 alice ##> "/_app activate" @@ -3819,7 +3819,7 @@ testAbsenceRestartsUnrenewedRun ps = unrenewedRuns (chatController alice) `shouldReturn` [(Just t0, Just t0)] let returnAt = addUTCTime (subscriptionRecoveryWindow + 2 * nominalDay) t0 setClockAt bsClock returnAt - activateAnswered alice [badgeServiceRefused] + activateAnswered alice [storeServiceRefused] (since, lastAt) <- answeredRun (chatController alice) returnAt since `shouldBe` lastAt shownBadgeId (chatController alice) >>= (`shouldSatisfy` isJust) @@ -3827,7 +3827,7 @@ testAbsenceRestartsUnrenewedRun ps = testOutageRestartsUnrenewedRun :: HasCallStack => TestParams -> IO () testOutageRestartsUnrenewedRun ps = do hook <- newIORef (pure ()) - withBadgeServiceVerifier ps (subscriptionCheckWithHook hook) $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store} -> do + withStoreServiceVerifier ps (subscriptionCheckWithHook hook) $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store} -> do t0 <- withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do (_, rows) <- clientSubscribedMonthly env alice storeReports store $ subscriptionCheck SSBillingRetry Nothing @@ -3857,7 +3857,7 @@ setNextWake ChatController {chatStore} at = testSubscriptionEnds :: HasCallStack => TestParams -> IO () testSubscriptionEnds ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do (_, rows) <- clientSubscribedMonthly env alice let (requestAt, _) = renewalMoments rows @@ -3887,7 +3887,7 @@ testSubscriptionEnds ps = testSubscriptionEndsWhileCovered :: HasCallStack => TestParams -> IO () testSubscriptionEndsWhileCovered ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsController = ChatController {chatStore}, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsController = ChatController {chatStore}, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do firstStart <- addUTCTime (-3600) <$> serviceNow env storeReports store $ subscriptionCheck SSRenewing $ Just $ storeCharge "subscr-badge-supporter-year-01" firstStart 12 @@ -3935,7 +3935,7 @@ testPlayExpiredWhileCovered ps = -- | An annual subscription the client bought, whose store reports at the second month's request what endedWith makes of its charge. endedInSecondMonth :: HasCallStack => TestParams -> (FakeStore -> SubscriptionCheck -> IO ()) -> (FakeStore -> ServicePayment) -> Text -> (StoreCharge -> SubscriptionCheck) -> IO () endedInSecondMonth ps reports paymentOf planId endedWith = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsController = cc, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do firstStart <- addUTCTime (-3600) <$> serviceNow env let charge = storeCharge planId firstStart 12 @@ -3964,7 +3964,7 @@ endedInSecondMonth ps reports paymentOf planId endedWith = testRevokedChargeRefunded :: HasCallStack => TestParams -> IO () testRevokedChargeRefunded ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsStore = store} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsStore = store} -> do (purchaseKey, firstStart, purchased) <- subscribedTo env "subscr-badge-supporter-year-01" 12 let granted = storeCharge "subscr-badge-supporter-year-01" firstStart 12 changes = map (\e -> let (c, m, _) = entryOf e in (c, m)) . fst . statementOf @@ -3987,9 +3987,9 @@ testRevokedChargeRefunded ps = testAnnualAsksBeforeEachMonth :: HasCallStack => TestParams -> IO () testAnnualAsksBeforeEachMonth ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsController = cc, bsStore = store} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsController = cc, bsStore = store} -> do (purchaseKey, firstStart, purchased) <- subscribedTo env "subscr-badge-supporter-year-01" 12 - let issue = BSCIssueBadge {balance = BadgeBalance {lastEntry = last purchased}} + let issue = STCIssueBadge {balance = BadgeBalance {lastEntry = last purchased}} routedAt t = setClockAt bsClock t >> requestLane ChecksAfterCoverage cc (Just purchaseKey) (requestObject purchaseKey issue) checks <- subscriptionChecks store -- inside the issued month no month is due, so the store is not asked @@ -4007,7 +4007,7 @@ testAnnualAsksBeforeEachMonth ps = testAnnualIssuesWhenStoreFails :: HasCallStack => TestParams -> IO () testAnnualIssuesWhenStoreFails ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsStore = store} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsStore = store} -> do (purchaseKey, firstStart, purchased) <- subscribedTo env "subscr-badge-supporter-year-01" 12 setGoogleDown store True checks <- subscriptionChecks store @@ -4024,7 +4024,7 @@ testAnnualIssuesWhenStoreFails ps = testDeviceEndedRetires :: HasCallStack => TestParams -> IO () testDeviceEndedRetires ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do (_, rows) <- clientSubscribedMonthly env alice checks <- subscriptionChecks store @@ -4049,7 +4049,7 @@ testDeviceEndedRetires ps = testRequestBadgeNow :: HasCallStack => TestParams -> IO () testRequestBadgeNow ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClientCfg, bsController = ChatController {chatStore}, bsStore = store} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClientCfg, bsController = ChatController {chatStore}, bsStore = store} -> do withNewTestChatCfg ps bsClientCfg {badgeDevRequests = True} "alice" aliceProfile $ \alice -> do (_, rows) <- clientSubscribedMonthly env alice let cc = chatController alice @@ -4074,11 +4074,11 @@ testRequestBadgeNow ps = alice <## "bad chat command: no badge is shown" withNewTestChatCfg ps bsClientCfg "bob" bobProfile $ \bob -> do bob ##> "/_badge request 1" - bob <## "bad chat command: /_badge request is only available in builds for a dev badge service" + bob <## "bad chat command: /_badge request is only available in builds for a dev store service" testFreshAnswerOverridesDeviceEnded :: HasCallStack => TestParams -> IO () testFreshAnswerOverridesDeviceEnded ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do (firstStart, rows) <- clientSubscribedMonthly env alice storeReports store $ subscriptionCheck SSRenewing $ Just $ monthlyCharge "subscr-badge-supporter-month-02" firstStart 1 @@ -4135,7 +4135,7 @@ firstUnrenewedAnswer cc clock rows answer = do testSubscriptionStateKept :: HasCallStack => TestParams -> IO () testSubscriptionStateKept ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do (_, rows) <- clientSubscribedMonthly env alice subscriptionStatuses (chatController alice) `shouldReturn` [Just "renewing"] @@ -4156,7 +4156,7 @@ nextWakes ChatController {chatStore} = -- | A monthly plan is not reminded of its renewal; a cancellation is alerted until acknowledged. testSubscriptionAlerts :: HasCallStack => TestParams -> IO () testSubscriptionAlerts ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do (firstStart, _) <- clientSubscribedMonthly env alice let paidThrough = addMonths 1 firstStart @@ -4177,7 +4177,7 @@ testSubscriptionAlerts ps = -- | An annual plan is reminded three days before it renews, by a wake of its own. testRenewalReminder :: HasCallStack => TestParams -> IO () testRenewalReminder ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store@FakeStore {appleSubscriptionJWS}} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store@FakeStore {appleSubscriptionJWS}} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do firstStart <- addUTCTime (-3600) <$> serviceNow env setSubscription store (SubscriptionApple appleSubscriptionOriginalId) $ subscriptionCheck SSRenewing $ Just $ storeCharge "SUBSCR_BADGE_SUPPORTER_YEAR_01" firstStart 12 @@ -4212,7 +4212,7 @@ subscriptionCancelled = StartsWith "badge alert: subscription_cancelled " -- does not take while coverage runs. testAnnualStateNotFromStoredAnswer :: HasCallStack => TestParams -> IO () testAnnualStateNotFromStoredAnswer ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc@ChatController {chatStore}, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsController = cc@ChatController {chatStore}, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do firstStart <- addUTCTime (-3600) <$> serviceNow env storeReports store $ subscriptionCheck SSCancelled $ Just $ storeCharge "subscr-badge-supporter-year-01" firstStart 12 @@ -4236,7 +4236,7 @@ testAnnualStateNotFromStoredAnswer ps = testSubscriptionStateFromStore :: HasCallStack => TestParams -> IO () testSubscriptionStateFromStore ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do (_, rows) <- clientSubscribedMonthly env alice let report state payment = alice ##> ("/_badge subscription " <> state <> " " <> paymentArg payment) @@ -4278,7 +4278,7 @@ heldStoreReceiptAttempt ChatController {chatStore} = testAppleAdoptionRules :: HasCallStack => TestParams -> IO () testAppleAdoptionRules ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClientCfg, bsStore = store@FakeStore {appleSubscriptionJWS, appleRevokedSubscriptionJWS}} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClientCfg, bsStore = store@FakeStore {appleSubscriptionJWS, appleRevokedSubscriptionJWS}} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do now <- serviceNow env setSubscription store (SubscriptionApple appleSubscriptionOriginalId) $ subscriptionCheck SSRenewing $ Just $ storeCharge "SUBSCR_BADGE_SUPPORTER_MONTH_01" (addUTCTime 3600 now) 1 @@ -4302,7 +4302,7 @@ testAdoptedReceiptNotOverwritten ps = do entered <- newEmptyMVar release <- newEmptyMVar hook <- newIORef (pure ()) - withBadgeServiceVerifier ps (subscriptionCheckWithHook hook) $ \env@BadgeServiceEnv {bsClientCfg, bsClock, bsStore = store@FakeStore {appleSubscriptionJWS, appleRenewalSubscriptionJWS}} -> do + withStoreServiceVerifier ps (subscriptionCheckWithHook hook) $ \env@StoreServiceEnv {bsClientCfg, bsClock, bsStore = store@FakeStore {appleSubscriptionJWS, appleRenewalSubscriptionJWS}} -> do now <- serviceNow env checks <- subscriptionChecks store withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do @@ -4329,7 +4329,7 @@ testAdoptedReceiptNotOverwritten ps = do testAppleRenewalResolvesToPurchase :: HasCallStack => TestParams -> IO () testAppleRenewalResolvesToPurchase ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClientCfg, bsClock, bsController = cc, bsStore = store@FakeStore {appleSubscriptionJWS, appleRenewalSubscriptionJWS}} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClientCfg, bsClock, bsController = cc, bsStore = store@FakeStore {appleSubscriptionJWS, appleRenewalSubscriptionJWS}} -> do now <- serviceNow env let appleReports start = setSubscription store (SubscriptionApple appleSubscriptionOriginalId) $ subscriptionCheck SSRenewing $ Just $ storeCharge "SUBSCR_BADGE_SUPPORTER_MONTH_01" start 1 withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do @@ -4362,7 +4362,7 @@ testAppleRenewalResolvesToPurchase ps = testAppleResubscribeResumes :: HasCallStack => TestParams -> IO () testAppleResubscribeResumes ps = -- retired past its coverage on the service's answer that it ended, then charged again for the same tier - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do requestAt <- appleSubscriptionRetired env alice -- past the hour in which the service answers from the check that found it ended @@ -4384,7 +4384,7 @@ testAppleResubscribeResumes ps = testAppleResubscribeResumesWithinCoverage :: HasCallStack => TestParams -> IO () testAppleResubscribeResumesWithinCoverage ps = -- retired within its coverage, its months not issued refunded, when the store reported it ended - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store@FakeStore {appleSubscriptionJWS}} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store@FakeStore {appleSubscriptionJWS}} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do firstStart <- addUTCTime (-3600) <$> serviceNow env let yearly = storeCharge "SUBSCR_BADGE_SUPPORTER_YEAR_01" firstStart 12 @@ -4416,7 +4416,7 @@ testAppleResubscribeResumesWithinCoverage ps = testPlaySubscriptionResumes :: HasCallStack => TestParams -> IO () testPlaySubscriptionResumes ps = -- retired once the recovery window passed while Play retried the payment, then charged again on the same token - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do playSubscriptionRetired env alice -- past the hour in which the service answers from the check that retired it @@ -4431,8 +4431,8 @@ testPlaySubscriptionResumes ps = ledgerTags (chatController alice) `shouldReturn` [Just "charge", Just "badge", Just "charge", Just "badge"] -- | A monthly Play subscription the client bought, retired once the recovery window passed while Play retried the payment. -playSubscriptionRetired :: HasCallStack => BadgeServiceEnv -> TestCC -> IO () -playSubscriptionRetired env@BadgeServiceEnv {bsClock, bsStore = store} alice = do +playSubscriptionRetired :: HasCallStack => StoreServiceEnv -> TestCC -> IO () +playSubscriptionRetired env@StoreServiceEnv {bsClock, bsStore = store} alice = do (_, rows) <- clientSubscribedMonthly env alice storeReports store $ subscriptionCheck SSBillingRetry Nothing t0 <- firstUnrenewedAnswer alice bsClock rows [] @@ -4447,7 +4447,7 @@ playSubscriptionRetired env@BadgeServiceEnv {bsClock, bsStore = store} alice = d testPlayResumeAttemptsEnd :: HasCallStack => TestParams -> IO () testPlayResumeAttemptsEnd ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do playSubscriptionRetired env alice let a = chatController alice @@ -4473,7 +4473,7 @@ testPlayResumeAttemptsEnd ps = testMovedOutPlayResumeSetAside :: HasCallStack => TestParams -> IO () testMovedOutPlayResumeSetAside ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> withNewTestChatCfg ps bsClientCfg "bob" bobProfile $ \bob -> do playSubscriptionRetired env alice @@ -4491,7 +4491,7 @@ testMovedOutPlayResumeSetAside ps = testMovedOutPlayNotResumed :: HasCallStack => TestParams -> IO () testMovedOutPlayNotResumed ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> withNewTestChatCfg ps bsClientCfg "bob" bobProfile $ \bob -> do (_, rows) <- clientSubscribedMonthly env alice @@ -4512,7 +4512,7 @@ testMovedOutPlayNotResumed ps = testMovedOutAppleNoAlertNoResume :: HasCallStack => TestParams -> IO () testMovedOutAppleNoAlertNoResume ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store@FakeStore {appleSubscriptionJWS}} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store@FakeStore {appleSubscriptionJWS}} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> withNewTestChatCfg ps bsClientCfg "bob" bobProfile $ \bob -> do firstStart <- addUTCTime (-3600) <$> serviceNow env @@ -4544,7 +4544,7 @@ testMovedOutAppleNoAlertNoResume ps = testAppleResubscribeBounded :: HasCallStack => TestParams -> IO () testAppleResubscribeBounded ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do requestAt <- appleSubscriptionRetired env alice let handOver jws = alice ##> ("/_badge purchase 1 " <> paymentArg SPApple {jws}) @@ -4598,12 +4598,12 @@ legendBoughtAt :: UTCTime legendBoughtAt = posixSecondsToUTCTime 1769904000 -- | A monthly Apple Supporter subscription bought five days before the Legend transaction, shown; the clock an hour into that transaction. -appleSupporterBeforeLegend :: HasCallStack => BadgeServiceEnv -> TestCC -> IO () +appleSupporterBeforeLegend :: HasCallStack => StoreServiceEnv -> TestCC -> IO () appleSupporterBeforeLegend env alice = appleSupporterBeforeLegendWith env alice Nothing -- | The same, handed over with the invoice given, if any. -appleSupporterBeforeLegendWith :: HasCallStack => BadgeServiceEnv -> TestCC -> Maybe String -> IO () -appleSupporterBeforeLegendWith BadgeServiceEnv {bsClock, bsStore = store@FakeStore {appleSubscriptionJWS}} alice invoiceId_ = do +appleSupporterBeforeLegendWith :: HasCallStack => StoreServiceEnv -> TestCC -> Maybe String -> IO () +appleSupporterBeforeLegendWith StoreServiceEnv {bsClock, bsStore = store@FakeStore {appleSubscriptionJWS}} alice invoiceId_ = do let firstStart = addUTCTime (-5 * nominalDay) legendBoughtAt supporter = SPApple {jws = appleSubscriptionJWS} setClockAt bsClock $ addUTCTime 3600 firstStart @@ -4623,7 +4623,7 @@ appleReportsLegend store = appleStoreReports store $ subscriptionCheck SSRenewin testAppleTierChangeHandOver :: HasCallStack => TestParams -> IO () testAppleTierChangeHandOver ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClientCfg, bsStore = store@FakeStore {appleRenewalSubscriptionJWS, appleLegendSubscriptionJWS}} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClientCfg, bsStore = store@FakeStore {appleRenewalSubscriptionJWS, appleLegendSubscriptionJWS}} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do appleSupporterBeforeLegend env alice let handOver jws = alice ##> ("/_badge purchase 1 " <> paymentArg SPApple {jws}) @@ -4652,7 +4652,7 @@ testAppleTierChangeHandOver ps = testTierChangeReachesContacts :: HasCallStack => TestParams -> IO () testTierChangeReachesContacts ps = do legend <- legendInTwoHours - withBadgeServiceVerifier ps (vouchingFor legend fakeVerifier) $ \env@BadgeServiceEnv {bsClientCfg} -> + withStoreServiceVerifier ps (vouchingFor legend fakeVerifier) $ \env@StoreServiceEnv {bsClientCfg} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> withNewTestChatCfg ps bsClientCfg "bob" bobProfile $ \bob -> do raised <- supporterRaisedToLegend env alice bob @@ -4676,8 +4676,8 @@ vouchingFor jws verifierOf store@FakeStore {appleLegendSubscriptionJWS} = v {ver -- | A monthly Apple Supporter subscription bought now and shown to bob, then the clock two hours on, past the hour the -- purchase's store check holds an upgrade off, with the store reporting a Legend year from then: what the apps are told once it is granted. -supporterRaisedToLegend :: HasCallStack => BadgeServiceEnv -> TestCC -> TestCC -> IO String -supporterRaisedToLegend env@BadgeServiceEnv {bsClock, bsStore = store@FakeStore {appleSubscriptionJWS}} alice bob = do +supporterRaisedToLegend :: HasCallStack => StoreServiceEnv -> TestCC -> TestCC -> IO String +supporterRaisedToLegend env@StoreServiceEnv {bsClock, bsStore = store@FakeStore {appleSubscriptionJWS}} alice bob = do connectUsers alice bob boughtAt <- serviceNow env appleStoreReports store $ subscriptionCheck SSRenewing $ Just $ storeCharge "SUBSCR_BADGE_SUPPORTER_MONTH_01" (addUTCTime (-3600) boughtAt) 1 @@ -4692,13 +4692,13 @@ supporterRaisedToLegend env@BadgeServiceEnv {bsClock, bsStore = store@FakeStore testAppleTierChangeStoreLags :: HasCallStack => TestParams -> IO () testAppleTierChangeStoreLags ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store@FakeStore {appleLegendSubscriptionJWS}} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store@FakeStore {appleLegendSubscriptionJWS}} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do appleSupporterBeforeLegend env alice -- the store still reports Supporter: the record stays held, and the purchase records no failed renewal alice ##> ("/_badge purchase 1 " <> paymentArg SPApple {jws = appleLegendSubscriptionJWS}) heldStoreReceiptErrors (chatController alice) `shouldEventuallyReturn` ["service_error retry payment_pending"] - expectLinesWithin 30 alice ["bad chat command: badge service error: payment_pending"] ["1: supporter", "store purchase open", "subscribed "] + expectLinesWithin 30 alice ["bad chat command: store service error: payment_pending"] ["1: supporter", "store purchase open", "subscribed "] purchaseBadgeTypes (chatController alice) "badge_purchases" `shouldReturn` ["supporter"] issueErrorRow (chatController alice) `shouldReturn` (Nothing, Nothing) -- once the store reports Legend and the hour since it was asked has passed, the next attempt grants it @@ -4712,13 +4712,13 @@ testAppleTierChangeStoreLags ps = testAppleTierChangeExpiredSettles :: HasCallStack => TestParams -> IO () testAppleTierChangeExpiredSettles ps = - withBadgeServiceVerifier ps (vouchingFor legendForADay fakeVerifier) $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc, bsStore = store} -> + withStoreServiceVerifier ps (vouchingFor legendForADay fakeVerifier) $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsController = cc, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do appleSupporterBeforeLegend env alice let handOver = alice ##> ("/_badge purchase 1 " <> paymentArg SPApple {jws = legendForADay}) handOver heldStoreReceiptErrors (chatController alice) `shouldEventuallyReturn` ["service_error retry payment_pending"] - expectLinesWithin 30 alice ["bad chat command: badge service error: payment_pending"] ["1: supporter", "store purchase open", "subscribed "] + expectLinesWithin 30 alice ["bad chat command: store service error: payment_pending"] ["1: supporter", "store purchase open", "subscribed "] -- once the transaction has expired the record settles with no change and no request, and the renewal check is left to grant it checks <- subscriptionChecks store ledger <- ledgerRows cc "sx_badge_service_badge_ledger" @@ -4739,7 +4739,7 @@ testAppleTierChangeExpiredSettles ps = testAppleTierChangeHandedOverLate :: HasCallStack => TestParams -> IO () testAppleTierChangeHandedOverLate ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store@FakeStore {appleLegendSubscriptionJWS}} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store@FakeStore {appleLegendSubscriptionJWS}} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do appleSupporterBeforeLegend env alice appleReportsLegend store @@ -4751,12 +4751,12 @@ testAppleTierChangeHandedOverLate ps = testAppleTierChangeAttemptsEnd :: HasCallStack => TestParams -> IO () testAppleTierChangeAttemptsEnd ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store@FakeStore {appleLegendSubscriptionJWS}} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store@FakeStore {appleLegendSubscriptionJWS}} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do appleSupporterBeforeLegend env alice let a = chatController alice handOver = alice ##> ("/_badge purchase 1 " <> paymentArg SPApple {jws = appleLegendSubscriptionJWS}) - answeredPending = expectLinesWithin 30 alice ["bad chat command: badge service error: payment_pending"] ["1: supporter", "store purchase open", "subscribed "] + answeredPending = expectLinesWithin 30 alice ["bad chat command: store service error: payment_pending"] ["1: supporter", "store purchase open", "subscribed "] attemptAt i = do setClockAt bsClock $ addUTCTime (3600 + fromIntegral i * 3700) legendBoughtAt alice ##> "/_app activate" @@ -4789,7 +4789,7 @@ storeReceiptRetries ChatController {chatStore} = testAppleTierChangeKeepsPurchaseShown :: HasCallStack => TestParams -> IO () testAppleTierChangeKeepsPurchaseShown ps = do hook <- newIORef (pure ()) - withBadgeServiceVerifier ps (subscriptionCheckWithHook hook) $ \env@BadgeServiceEnv {bsClientCfg, bsStore = store@FakeStore {appleLegendSubscriptionJWS}} -> + withStoreServiceVerifier ps (subscriptionCheckWithHook hook) $ \env@StoreServiceEnv {bsClientCfg, bsStore = store@FakeStore {appleLegendSubscriptionJWS}} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do appleSupporterBeforeLegend env alice appleReportsLegend store @@ -4806,7 +4806,7 @@ testAppleTierChangeKeepsPurchaseShown ps = do testAppleTierChangeRefused :: HasCallStack => TestParams -> IO () testAppleTierChangeRefused ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClientCfg, bsStore = store} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do invoiceId <- createInvoice alice 1 appleSupporterBeforeLegendWith env alice (Just invoiceId) @@ -4814,7 +4814,7 @@ testAppleTierChangeRefused ps = handOver = alice ##> ("/_badge purchase 1 " <> paymentArg SPApple {jws = unvouched}) checks <- subscriptionChecks store handOver - expectLinesWithin 30 alice ["1: supporter", "bad chat command: badge service error: receipt_invalid"] ["store purchase open", "subscribed "] + expectLinesWithin 30 alice ["1: supporter", "bad chat command: store service error: receipt_invalid"] ["store purchase open", "subscribed "] heldStoreReceipts (chatController alice) `shouldEventuallyReturn` 0 storeReceiptCreditErrors (chatController alice) `shouldReturn` ["service_error final receipt_invalid"] (alice TestParams -> IO () testAppleTierChangeBesideHeldReceipt ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClientCfg, bsStore = store@FakeStore {appleLegendSubscriptionJWS}} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClientCfg, bsStore = store@FakeStore {appleLegendSubscriptionJWS}} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do appleSupporterBeforeLegend env alice alice ##> ("/_badge purchase 1 " <> paymentArg supporterPlay) @@ -4842,7 +4842,7 @@ testAppleTierChangeBesideHeldReceipt ps = testAppleTierChangeClearsEnded :: HasCallStack => TestParams -> IO () testAppleTierChangeClearsEnded ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store@FakeStore {appleSubscriptionJWS, appleLegendSubscriptionJWS}} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store@FakeStore {appleSubscriptionJWS, appleLegendSubscriptionJWS}} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do appleSupporterBeforeLegend env alice alice ##> ("/_badge subscription ended " <> paymentArg SPApple {jws = appleSubscriptionJWS}) @@ -4866,7 +4866,7 @@ testAppleTierChangeClearsEnded ps = testAppleTierChangeClearsBillingRetry :: HasCallStack => TestParams -> IO () testAppleTierChangeClearsBillingRetry ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClientCfg, bsStore = store@FakeStore {appleSubscriptionJWS, appleLegendSubscriptionJWS}} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClientCfg, bsStore = store@FakeStore {appleSubscriptionJWS, appleLegendSubscriptionJWS}} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do appleSupporterBeforeLegend env alice alice ##> ("/_badge subscription billingRetry " <> paymentArg SPApple {jws = appleSubscriptionJWS}) @@ -4883,7 +4883,7 @@ testAppleTierChangeClearsBillingRetry ps = testAppleTierChangeCredentialUnverified :: HasCallStack => TestParams -> IO () testAppleTierChangeCredentialUnverified ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClientCfg, bsStore = store@FakeStore {appleLegendSubscriptionJWS}} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClientCfg, bsStore = store@FakeStore {appleLegendSubscriptionJWS}} -> do withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> appleSupporterBeforeLegend env alice appleReportsLegend store -- trusting no issuer key, so the Legend credential the service issues does not verify @@ -4895,8 +4895,8 @@ testAppleTierChangeCredentialUnverified ps = shownBadgeId (chatController alice) `shouldReturn` Just 1 -- | A monthly Apple Legend subscription bought at legendBoughtAt, shown; the clock an hour into it. -appleLegendShown :: HasCallStack => BadgeServiceEnv -> TestCC -> IO () -appleLegendShown BadgeServiceEnv {bsClock, bsStore = store@FakeStore {appleLegendSubscriptionJWS}} alice = do +appleLegendShown :: HasCallStack => StoreServiceEnv -> TestCC -> IO () +appleLegendShown StoreServiceEnv {bsClock, bsStore = store@FakeStore {appleLegendSubscriptionJWS}} alice = do setClockAt bsClock $ addUTCTime 3600 legendBoughtAt appleStoreReports store $ subscriptionCheck SSRenewing $ Just $ storeCharge "SUBSCR_BADGE_LEGEND_MONTH_01" legendBoughtAt 1 alice ##> ("/_badge purchase 1 " <> paymentArg SPApple {jws = appleLegendSubscriptionJWS}) @@ -4905,7 +4905,7 @@ appleLegendShown BadgeServiceEnv {bsClock, bsStore = store@FakeStore {appleLegen testAppleTierChangeLowerWaitsForRenewal :: HasCallStack => TestParams -> IO () testAppleTierChangeLowerWaitsForRenewal ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc, bsStore = store@FakeStore {appleRenewalSubscriptionJWS}} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsController = cc, bsStore = store@FakeStore {appleRenewalSubscriptionJWS}} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do appleLegendShown env alice let a = chatController alice @@ -4940,7 +4940,7 @@ testAppleTierChangeLowerWaitsForRenewal ps = testAppleTierChangeHeldLowerSettles :: HasCallStack => TestParams -> IO () testAppleTierChangeHeldLowerSettles ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClientCfg, bsStore = store@FakeStore {appleRenewalSubscriptionJWS}} -> + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClientCfg, bsStore = store@FakeStore {appleRenewalSubscriptionJWS}} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do appleLegendShown env alice let a = chatController alice @@ -4961,8 +4961,8 @@ testAppleTierChangeHeldLowerSettles ps = -- | A monthly Apple subscription bought an hour into its first period and retired past its coverage, at its request -- moment, on the service's answer that it ended: that moment. -appleSubscriptionRetired :: HasCallStack => BadgeServiceEnv -> TestCC -> IO UTCTime -appleSubscriptionRetired env@BadgeServiceEnv {bsClock, bsStore = store@FakeStore {appleSubscriptionJWS}} alice = do +appleSubscriptionRetired :: HasCallStack => StoreServiceEnv -> TestCC -> IO UTCTime +appleSubscriptionRetired env@StoreServiceEnv {bsClock, bsStore = store@FakeStore {appleSubscriptionJWS}} alice = do firstStart <- addUTCTime (-3600) <$> serviceNow env appleStoreReports store $ subscriptionCheck SSRenewing $ Just $ storeCharge "SUBSCR_BADGE_SUPPORTER_MONTH_01" firstStart 1 alice ##> ("/_badge purchase 1 " <> paymentArg SPApple {jws = appleSubscriptionJWS}) @@ -5001,41 +5001,41 @@ storeReceiptCreditErrors ChatController {chatStore} = testApplePurchaseChecksBounded :: HasCallStack => TestParams -> IO () testApplePurchaseChecksBounded ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsController = cc, bsStore = store@FakeStore {appleSubscriptionJWS, appleRenewalSubscriptionJWS, appleSecondSubscriptionJWS, appleThirdSubscriptionJWS}} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsController = cc, bsStore = store@FakeStore {appleSubscriptionJWS, appleRenewalSubscriptionJWS, appleSecondSubscriptionJWS, appleThirdSubscriptionJWS}} -> do now <- serviceNow env let ended originalId = setSubscription store (SubscriptionApple originalId) $ subscriptionCheck SSEnded $ Just $ storeCharge "SUBSCR_BADGE_SUPPORTER_MONTH_01" (addUTCTime (-3600) now) 1 present (purchaseKey, masterKey) jws = refusalOf <$> serviceCmd env purchaseKey (purchaseCmd masterKey SPApple {jws}) - heldOff (code, retryAfter) = code == BSEPaymentPending && maybe False (\t -> t > 3540 && t <= 3600) retryAfter + heldOff (code, retryAfter) = code == STEPaymentPending && maybe False (\t -> t > 3540 && t <= 3600) retryAfter ended appleSubscriptionOriginalId ended appleSecondSubscriptionOriginalId keys <- newPurchaseKeys otherKeys <- newPurchaseKeys checks <- subscriptionChecks store firstCheck <- testClockTime bsClock - present keys appleSubscriptionJWS `shouldReturn` (BSEPaymentPending, Just 86400) + present keys appleSubscriptionJWS `shouldReturn` (STEPaymentPending, Just 86400) subscriptionChecks store `shouldReturn` checks + 1 present keys appleSubscriptionJWS >>= (`shouldSatisfy` heldOff) present otherKeys appleSubscriptionJWS >>= (`shouldSatisfy` heldOff) present keys appleRenewalSubscriptionJWS >>= (`shouldSatisfy` heldOff) subscriptionChecks store `shouldReturn` checks + 1 - present keys appleSecondSubscriptionJWS `shouldReturn` (BSEPaymentPending, Just 86400) + present keys appleSecondSubscriptionJWS `shouldReturn` (STEPaymentPending, Just 86400) subscriptionChecks store `shouldReturn` checks + 2 -- an answer that would bring the client back sooner carries the hour its claim is held for - present keys appleThirdSubscriptionJWS `shouldReturn` (BSEProviderUnavailable, Just 3600) + present keys appleThirdSubscriptionJWS `shouldReturn` (STEProviderUnavailable, Just 3600) subscriptionChecks store `shouldReturn` checks + 3 setClockAt bsClock $ addUTCTime 3700 firstCheck - present otherKeys appleSubscriptionJWS `shouldReturn` (BSEPaymentPending, Just 86400) + present otherKeys appleSubscriptionJWS `shouldReturn` (STEPaymentPending, Just 86400) subscriptionChecks store `shouldReturn` checks + 4 nothingPurchased cc testPlayPurchaseChecksBounded :: HasCallStack => TestParams -> IO () testPlayPurchaseChecksBounded ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsController = cc, bsStore = store} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsController = cc, bsStore = store} -> do let token n = "fake-play-token-bounded-" <> n <> ".AO-J1Om8l3biV8pPk4" reports t = setSubscription store (SubscriptionGoogle t) payment = googlePayment "subscr_badge_supporter_01" present (purchaseKey, masterKey) t = refusalOf <$> serviceCmd env purchaseKey (purchaseCmd masterKey $ payment t) - heldOff (code, retryAfter) = code == BSEPaymentPending && maybe False (\s -> s > 3540 && s <= 3600) retryAfter + heldOff (code, retryAfter) = code == STEPaymentPending && maybe False (\s -> s > 3540 && s <= 3600) retryAfter waiting = subscriptionCheck SSBillingRetry Nothing now <- serviceNow env reports (token "1") waiting @@ -5046,21 +5046,21 @@ testPlayPurchaseChecksBounded ps = otherKeys <- newPurchaseKeys checks <- subscriptionChecks store firstCheck <- testClockTime bsClock - present keys (token "1") `shouldReturn` (BSEPaymentPending, Just 86400) + present keys (token "1") `shouldReturn` (STEPaymentPending, Just 86400) subscriptionChecks store `shouldReturn` checks + 1 present keys (token "1") >>= (`shouldSatisfy` heldOff) present otherKeys (token "1") >>= (`shouldSatisfy` heldOff) subscriptionChecks store `shouldReturn` checks + 1 - present keys (token "2") `shouldReturn` (BSEPaymentPending, Just 86400) + present keys (token "2") `shouldReturn` (STEPaymentPending, Just 86400) subscriptionChecks store `shouldReturn` checks + 2 -- answers that would bring the client back sooner carry the hour the token is held for setGoogleDown store True - present keys (token "3") `shouldReturn` (BSEProviderUnavailable, Just 3600) + present keys (token "3") `shouldReturn` (STEProviderUnavailable, Just 3600) setGoogleDown store False - present keys (token "4") `shouldReturn` (BSEPaymentPending, Just 3600) + present keys (token "4") `shouldReturn` (STEPaymentPending, Just 3600) subscriptionChecks store `shouldReturn` checks + 4 setClockAt bsClock $ addUTCTime 3700 firstCheck - present otherKeys (token "1") `shouldReturn` (BSEPaymentPending, Just 86400) + present otherKeys (token "1") `shouldReturn` (STEPaymentPending, Just 86400) subscriptionChecks store `shouldReturn` checks + 5 nothingPurchased cc -- a token credited to one key is held for another key too, and its own key is answered from the record @@ -5074,7 +5074,7 @@ testPlayPurchaseChecksBounded ps = credentialOf <$> serviceCmd env creditKey (purchaseCmd creditMasterKey $ payment $ token "5") `shouldReturn` credentialOf credited subscriptionChecks store `shouldReturn` checks + 6 setClockAt bsClock $ addUTCTime 3700 creditedAt - present otherKeys (token "5") `shouldReturn` (BSEReceiptUsed, Nothing) + present otherKeys (token "5") `shouldReturn` (STEReceiptUsed, Nothing) subscriptionChecks store `shouldReturn` checks + 7 testPurchaseChecksBounded :: HasCallStack => TestParams -> IO () @@ -5114,12 +5114,12 @@ testPlayReadsBounded _ = do testPlayPurchaseReadsLimited :: HasCallStack => TestParams -> IO () testPlayPurchaseReadsLimited ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsController = cc, bsPurchaseChecks = PurchaseChecks {playReads = taken}, bsStore = store@FakeStore {appleSubscriptionJWS}} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsController = cc, bsPurchaseChecks = PurchaseChecks {playReads = taken}, bsStore = store@FakeStore {appleSubscriptionJWS}} -> do let token n = "fake-play-token-reads-" <> n <> ".AO-J1Om8l3biV8pPk4" play = googlePayment "subscr_badge_supporter_01" . token present (purchaseKey, masterKey) payment = refusalOf <$> serviceCmd env purchaseKey (purchaseCmd masterKey payment) - heldOff (code, retryAfter) = code == BSEPaymentPending && maybe False (\s -> s > 3540 && s <= 3600) retryAfter - readRefused (code, retryAfter) = code == BSERateLimited && maybe False (\s -> s >= 1 && s <= 60) retryAfter + heldOff (code, retryAfter) = code == STEPaymentPending && maybe False (\s -> s > 3540 && s <= 3600) retryAfter + readRefused (code, retryAfter) = code == STERateLimited && maybe False (\s -> s >= 1 && s <= 60) retryAfter useUpReads = do wait_ <- testClockTime bsClock >>= atomically . playReadWait taken when (isNothing wait_) useUpReads @@ -5129,17 +5129,17 @@ testPlayPurchaseReadsLimited ps = setSubscription store (SubscriptionApple appleSubscriptionOriginalId) $ subscriptionCheck SSEnded $ Just $ storeCharge "SUBSCR_BADGE_SUPPORTER_MONTH_01" (addUTCTime (-3600) now) 1 keys <- newPurchaseKeys checks <- subscriptionChecks store - present keys (play "A") `shouldReturn` (BSEPaymentPending, Just 86400) + present keys (play "A") `shouldReturn` (STEPaymentPending, Just 86400) firstReadAfter <- testClockTime bsClock subscriptionChecks store `shouldReturn` checks + 1 useUpReads present keys (play "A") >>= (`shouldSatisfy` heldOff) present keys (play "B") >>= (`shouldSatisfy` readRefused) subscriptionChecks store `shouldReturn` checks + 1 - present keys SPApple {jws = appleSubscriptionJWS} `shouldReturn` (BSEPaymentPending, Just 86400) + present keys SPApple {jws = appleSubscriptionJWS} `shouldReturn` (STEPaymentPending, Just 86400) subscriptionChecks store `shouldReturn` checks + 2 setClockAt bsClock $ addUTCTime 61 firstReadAfter - present keys (play "B") `shouldReturn` (BSEPaymentPending, Just 86400) + present keys (play "B") `shouldReturn` (STEPaymentPending, Just 86400) subscriptionChecks store `shouldReturn` checks + 3 nothingPurchased cc @@ -5153,10 +5153,10 @@ testAppleSandboxSubscriptionNotAsked ps = do SubscriptionApple originalId -> check originalId SubscriptionGoogle _ -> pure $ Left SRNotConfigured verifier = noStoreVerifier {verifyApple = Just (verifyAppleTransaction (rootCert chain :| []) ourBundleId), checkSubscription = Just checkApple} - withBadgeServiceVerifier ps (const verifier) $ \env@BadgeServiceEnv {bsController = cc} -> do + withStoreServiceVerifier ps (const verifier) $ \env@StoreServiceEnv {bsController = cc} -> do jws <- signedBy chain $ subscriptionPayload [("environment", "Sandbox")] [] (purchaseKey, masterKey) <- newPurchaseKeys - refusalOf <$> serviceCmd env purchaseKey (purchaseCmd masterKey SPApple {jws}) `shouldReturn` (BSETestPurchase, Nothing) + refusalOf <$> serviceCmd env purchaseKey (purchaseCmd masterKey SPApple {jws}) `shouldReturn` (STETestPurchase, Nothing) readTVarIO (fasTokens fake) `shouldReturn` [] nothingPurchased cc @@ -5166,16 +5166,16 @@ testAppleSubscriptionWithoutApiKey ps = do createDirectoryIfMissing True "tests/tmp" withTempDirectory "tests/tmp" "apple-no-api-key" $ \d -> do B.writeFile (d "root.cer") (encodeSignedObject $ rootCert chain) - writeFile (d "badge_service.ini") "[listener]\nstatic_dir = /srv/badges\n" - Right cfg <- readServiceConfig (d "badge_service.ini") + writeFile (d "store_service.ini") "[listener]\nstatic_dir = /srv/badges\n" + Right cfg <- readServiceConfig (d "store_service.ini") let apple = AppleStoreConfig {aBundleId = ourBundleId, aRootCertificates = (d "root.cer") :| [], aServerApi = Nothing} ServiceState {storeVerifier} <- newServiceState >>= configureStoreVerifier (Just cfg {appleStore = Just apple}) - withBadgeServiceVerifier ps (const storeVerifier) $ \env@BadgeServiceEnv {bsController = cc} -> do + withStoreServiceVerifier ps (const storeVerifier) $ \env@StoreServiceEnv {bsController = cc} -> do (purchaseKey, masterKey) <- newPurchaseKeys subscription <- signedBy chain $ subscriptionPayload [] [] let presentSubscription = refusalOf <$> serviceCmd env purchaseKey (purchaseCmd masterKey SPApple {jws = subscription}) - presentSubscription `shouldReturn` (BSEProviderNotConfigured, Nothing) - presentSubscription `shouldReturn` (BSEProviderNotConfigured, Nothing) + presentSubscription `shouldReturn` (STEProviderNotConfigured, Nothing) + presentSubscription `shouldReturn` (STEProviderNotConfigured, Nothing) nothingPurchased cc oneTime <- signedBy chain $ transactionPayload [] [] badgeTypeOf <$> serviceCmd env purchaseKey (purchaseCmd masterKey SPApple {jws = oneTime}) `shouldReturn` Just BTSupporter @@ -5190,7 +5190,7 @@ testPlaySubscriptionAcknowledgedBeforeCrediting ps = do { acknowledgeGoogle = Just $ \_ token -> modifyIORef' oneTimeAcknowledged (token :) >> pure (Right ()), acknowledgeGoogleSubscription = Just $ \productId token -> modifyIORef' acknowledged ((productId, token) :) >> readIORef acknowledgement } - withBadgeServiceVerifier ps acknowledging $ \env@BadgeServiceEnv {bsClock, bsController = cc, bsStore} -> do + withStoreServiceVerifier ps acknowledging $ \env@StoreServiceEnv {bsClock, bsController = cc, bsStore} -> do now <- serviceNow env (purchaseKey, masterKey) <- newPurchaseKeys let purchase = serviceCmd env purchaseKey $ purchaseCmd masterKey subscriptionPlay @@ -5199,14 +5199,14 @@ testPlaySubscriptionAcknowledgedBeforeCrediting ps = do nextHour = testClockTime bsClock >>= setClockAt bsClock . addUTCTime 3700 -- only a charge about to be credited is acknowledged chargedFrom $ addUTCTime 3600 now - fst . refusalOf <$> purchase `shouldReturn` BSEPaymentPending + fst . refusalOf <$> purchase `shouldReturn` STEPaymentPending readIORef acknowledged `shouldReturn` [] chargedFrom $ addUTCTime (-3600) now nextHour - refusalOf <$> purchase >>= (`shouldSatisfy` \(code, retryAfter) -> code == BSEProviderUnavailable && isJust retryAfter) + refusalOf <$> purchase >>= (`shouldSatisfy` \(code, retryAfter) -> code == STEProviderUnavailable && isJust retryAfter) writeIORef acknowledgement $ Left $ SRVerifierFailed "acknowledging: the service account lacks the Play Console permission for this call" nextHour - refusalOf <$> purchase `shouldReturn` (BSEInternal, Nothing) + refusalOf <$> purchase `shouldReturn` (STEInternal, Nothing) nothingPurchased cc rowCount cc "sx_badge_service_subscription_charges" `shouldReturn` 0 writeIORef acknowledgement $ Right () @@ -5222,16 +5222,16 @@ testPlaySubscriptionAcknowledgedBeforeCrediting ps = do testPlaySubscriptionThroughPlay :: HasCallStack => TestParams -> IO () testPlaySubscriptionThroughPlay ps = withFakePlay $ \fake@FakePlay {fpConfig} -> do - let ini = takeDirectory (gServiceAccountFile fpConfig) "badge_service.ini" + let ini = takeDirectory (gServiceAccountFile fpConfig) "store_service.ini" writeFile ini "[listener]\nstatic_dir = /srv/badges\n" Right cfg <- readServiceConfig ini ServiceState {storeVerifier = withoutPlay} <- newServiceState >>= configureStoreVerifier (Just cfg) ServiceState {storeVerifier} <- newServiceState >>= configureStoreVerifier (Just cfg {playStore = Just fpConfig}) - withBadgeServiceVerifier ps (const storeVerifier) $ \env@BadgeServiceEnv {bsController = cc} -> do + withStoreServiceVerifier ps (const storeVerifier) $ \env@StoreServiceEnv {bsController = cc} -> do periodEnd <- addMonths 1 . addUTCTime (-3600) <$> serviceNow env answerPurchase fake googleSubscriptionToken $ PlayRecord $ subscriptionRecord "SUBSCRIPTION_STATE_ACTIVE" [] [lineItem [("expiryTime", J.toJSON periodEnd)] []] (purchaseKey, masterKey) <- newPurchaseKeys - refusalOf <$> serviceCmd env {bsVerifier = withoutPlay} purchaseKey (purchaseCmd masterKey subscriptionPlay) `shouldReturn` (BSEProviderNotConfigured, Nothing) + refusalOf <$> serviceCmd env {bsVerifier = withoutPlay} purchaseKey (purchaseCmd masterKey subscriptionPlay) `shouldReturn` (STEProviderNotConfigured, Nothing) nothingPurchased cc readTVarIO (fpPurchasePaths fake) `shouldReturn` [] purchased <- serviceCmd env purchaseKey $ purchaseCmd masterKey subscriptionPlay @@ -5250,7 +5250,7 @@ testPlaySubscriptionThroughPlay ps = testMockSubscriptions :: HasCallStack => TestParams -> IO () testMockSubscriptions ps = - withBadgeServiceVerifierIO ps (\clock _ -> newMockStoreVerifier (testClockTime clock)) $ \env@BadgeServiceEnv {bsClock, bsVerifier} -> do + withStoreServiceVerifierIO ps (\clock _ -> newMockStoreVerifier (testClockTime clock)) $ \env@StoreServiceEnv {bsClock, bsVerifier} -> do now <- serviceNow env let purchase payment = newPurchaseKeys >>= \(purchaseKey, masterKey) -> (purchaseKey,) <$> serviceCmd env purchaseKey (purchaseCmd masterKey payment) changes = map (\e -> let (c, m, _) = entryOf e in (c, m)) . fst . statementOf @@ -5278,7 +5278,7 @@ testMockSubscriptions ps = map entryTag (fst $ statementOf renewed) `shouldBe` ["charge", "badge"] subscriptionOf renewed `shouldBe` Just SSRenewing restarted <- newMockStoreVerifier (testClockTime bsClock) - ended <- serviceCmd env {bsVerifier = restarted} forgottenKey BSCIssueBadge {balance = BadgeBalance {lastEntry = last $ fst $ statementOf forgotten}} + ended <- serviceCmd env {bsVerifier = restarted} forgottenKey STCIssueBadge {balance = BadgeBalance {lastEntry = last $ fst $ statementOf forgotten}} subscriptionOf ended `shouldBe` Just SSEnded credentialOf ended `shouldBe` Nothing -- a first purchase naming no plan it knows is not a verdict @@ -5289,7 +5289,7 @@ testMockSubscriptions ps = testStoreChecksDuringCoverage :: HasCallStack => TestParams -> IO () testStoreChecksDuringCoverage ps = - withBadgeServiceVerifierIO ps (\clock _ -> checkingAtEveryRequest <$> newMockStoreVerifier (testClockTime clock)) $ \env@BadgeServiceEnv {bsClock, bsController = cc} -> do + withStoreServiceVerifierIO ps (\clock _ -> checkingAtEveryRequest <$> newMockStoreVerifier (testClockTime clock)) $ \env@StoreServiceEnv {bsClock, bsController = cc} -> do now <- serviceNow env (purchaseKey, masterKey) <- newPurchaseKeys purchased <- serviceCmd env purchaseKey $ purchaseCmd masterKey $ googlePayment "subscr_badge_supporter_01" googleSubscriptionToken @@ -5323,14 +5323,14 @@ testStoreChecksDuringCoverage ps = -- a restarted mock has forgotten the plan, so the subscription has ended though coverage runs, and the banked month is refunded restarted <- checkingAtEveryRequest <$> newMockStoreVerifier (testClockTime bsClock) setClockAt bsClock endedAt - ended <- serviceCmd env {bsVerifier = restarted} purchaseKey BSCIssueBadge {balance = BadgeBalance {lastEntry = last $ entries renewed}} + ended <- serviceCmd env {bsVerifier = restarted} purchaseKey STCIssueBadge {balance = BadgeBalance {lastEntry = last $ entries renewed}} void $ stampedSince endedAt renewedStamp (credentialOf ended, subscriptionOf ended) `shouldBe` (Nothing, Just SSEnded) map entryTag (entries ended) `shouldBe` ["refund"] (\(c, m, _) -> (c, m)) (entryOf $ last $ entries ended) `shouldBe` (-1, 0) -- with nothing left to refund, a later request that month writes no row setClockAt bsClock $ addUTCTime 60 endedAt - again <- serviceCmd env {bsVerifier = restarted} purchaseKey BSCIssueBadge {balance = BadgeBalance {lastEntry = last $ entries ended}} + again <- serviceCmd env {bsVerifier = restarted} purchaseKey STCIssueBadge {balance = BadgeBalance {lastEntry = last $ entries ended}} (credentialOf again, subscriptionOf again) `shouldBe` (Nothing, Just SSEnded) map entryTag (entries again) `shouldBe` [] where @@ -5338,11 +5338,11 @@ testStoreChecksDuringCoverage ps = testStoreChecksDuringCoverageGrantedOnce :: HasCallStack => TestParams -> IO () testStoreChecksDuringCoverageGrantedOnce ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsController = cc, bsStore = store} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsController = cc, bsStore = store} -> do (purchaseKey, _, purchased) <- subscribedMonthly env ledger <- ledgerRows cc "sx_badge_service_badge_ledger" checks <- subscriptionChecks store - answered <- serviceCmd env {bsVerifier = (fakeVerifier store) {storeChecks = ChecksAtEveryRequest}} purchaseKey BSCIssueBadge {balance = BadgeBalance {lastEntry = last purchased}} + answered <- serviceCmd env {bsVerifier = (fakeVerifier store) {storeChecks = ChecksAtEveryRequest}} purchaseKey STCIssueBadge {balance = BadgeBalance {lastEntry = last purchased}} subscriptionChecks store `shouldReturn` checks + 1 map entryTag (fst $ statementOf answered) `shouldBe` [] ledgerRows cc "sx_badge_service_badge_ledger" `shouldReturn` ledger @@ -5350,7 +5350,7 @@ testStoreChecksDuringCoverageGrantedOnce ps = testBankedMonthAnnounced :: HasCallStack => TestParams -> IO () testBankedMonthAnnounced ps = - withRequestCountingService ps $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsStore = store} -> + withRequestCountingService ps $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsStore = store} -> withNewTestChatCfg ps bsClientCfg {badgeDevRequestInterval = Just 600} "alice" aliceProfile $ \alice -> do (firstStart, rows) <- clientSubscribedMonthly env alice let t1 = devIntervalStart rows @@ -5365,7 +5365,7 @@ testBankedMonthAnnounced ps = testPurchaseBadge :: HasCallStack => TestParams -> IO () testPurchaseBadge ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do invoiceId <- createInvoice alice 1 alice ##> purchaseWithInvoice 1 invoiceId supporterPlay @@ -5385,7 +5385,7 @@ testPurchaseBadge ps = testPurchaseNamesNoTransaction :: HasCallStack => TestParams -> IO () testPurchaseNamesNoTransaction ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do invoiceId <- createInvoice alice 1 alice ##> purchaseWithInvoice 1 invoiceId SPApple {jws = "not.a-jws"} @@ -5395,7 +5395,7 @@ testPurchaseNamesNoTransaction ps = testPurchaseStashReceiptUsed :: HasCallStack => TestParams -> IO () testPurchaseStashReceiptUsed ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> withNewTestChatCfg ps bsClientCfg "bob" bobProfile $ \bob -> do invoiceId <- createInvoice alice 1 @@ -5406,7 +5406,7 @@ testPurchaseStashReceiptUsed ps = bob ##> purchase bob <### [StartsWith (invoicePurchase "" invoiceId), ConsoleString (refusedLine "" invoiceId "service_error final receipt_used")] bob ##> purchase - bob <## "cannot get badge: badge service error: receipt_used" + bob <## "cannot get badge: store service error: receipt_used" storeReceiptRows (chatController bob) `shouldReturn` [(1, Just (T.pack invoiceId), True)] heldStoreReceipts (chatController bob) `shouldReturn` 0 rowCount (chatController alice) "badge_store_receipts" `shouldReturn` 1 @@ -5416,7 +5416,7 @@ testPurchaseStashReceiptUsed ps = testPurchaseUnsentPlayToken :: HasCallStack => TestParams -> IO () testPurchaseUnsentPlayToken ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do alice ##> ("/_badge purchase 1 " <> paymentArg (googlePayment "badge_supporter_01" "token/other")) storePurchaseOpen alice "" @@ -5427,7 +5427,7 @@ testPurchaseUnsentPlayToken ps = testPurchaseStrandedUnderOtherProfile :: HasCallStack => TestParams -> IO () testPurchaseStrandedUnderOtherProfile ps = do broken <- newIORef True - withBadgeServiceVerifier ps (brokenGoogle broken) $ \BadgeServiceEnv {bsClientCfg, bsController = cc} -> + withStoreServiceVerifier ps (brokenGoogle broken) $ \StoreServiceEnv {bsClientCfg, bsController = cc} -> withNewTestChatCfg ps (fastRetryCfg bsClientCfg) "alice" aliceProfile $ \alice -> do invoiceId <- createInvoice alice 1 let purchase userId = purchaseWithInvoice userId invoiceId supporterPlay @@ -5450,7 +5450,7 @@ testPurchaseStrandedUnderOtherProfile ps = do testPurchaseDeliveredToHiddenProfile :: HasCallStack => TestParams -> IO () testPurchaseDeliveredToHiddenProfile ps = do broken <- newIORef True - withBadgeServiceVerifier ps (brokenGoogle broken) $ \BadgeServiceEnv {bsClientCfg} -> + withStoreServiceVerifier ps (brokenGoogle broken) $ \StoreServiceEnv {bsClientCfg} -> withNewTestChatCfg ps (fastRetryCfg bsClientCfg) "alice" aliceProfile $ \alice -> do let purchase userId = "/_badge purchase " <> show (userId :: Int) <> " " <> paymentArg supporterPlay alice ##> purchase 1 @@ -5473,7 +5473,7 @@ testPurchaseDeliveredToHiddenProfile ps = do testInvoiceOtherProfile :: HasCallStack => TestParams -> IO () testInvoiceOtherProfile ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClientCfg, bsClock = clock} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClientCfg, bsClock = clock} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do invoiceId <- createInvoice alice 1 getCurrentTime >>= setClockAt clock . addUTCTime (8 * nominalDay) @@ -5489,7 +5489,7 @@ testInvoiceOtherProfile ps = -- | The store lists an account's purchases on every device signed into it, so a listed one may be another device's. testListedReceiptNotRecorded :: HasCallStack => TestParams -> IO () testListedReceiptNotRecorded ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do let listed invoiceId_ payment = "/_badge purchase 1" <> maybe "" (" invoice=" <>) invoiceId_ <> " listed " <> paymentArg payment alice ##> listed (Just "0b6a5e6c-4f3e-4d51-9f55-3a0f7c2f9e11") supporterPlay @@ -5516,7 +5516,7 @@ testListedReceiptNotRecorded ps = -- the service refuses a subscription for good, though not as a refused receipt, so the record stays held. testRedeemRefusedWhileReceiptHeld :: HasCallStack => TestParams -> IO () testRedeemRefusedWhileReceiptHeld ps = - withBadgeServiceVerifier ps (\store -> (fakeVerifier store) {checkSubscription = Nothing}) $ \BadgeServiceEnv {bsClientCfg, bsController = cc, bsStore = FakeStore {appleSubscriptionJWS}} -> + withStoreServiceVerifier ps (\store -> (fakeVerifier store) {checkSubscription = Nothing}) $ \StoreServiceEnv {bsClientCfg, bsController = cc, bsStore = FakeStore {appleSubscriptionJWS}} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do let refused cmd = do alice ##> cmd @@ -5553,7 +5553,7 @@ testRedeemRefusedWhileReceiptHeld ps = -- | A first Apple purchase refunded while the service could not credit it: Apple charges it no more after its expiry. testLapsedAppleChargeStopsBlocking :: HasCallStack => TestParams -> IO () testLapsedAppleChargeStopsBlocking ps = - withBadgeServiceVerifier ps (\store -> (fakeVerifier store) {verifyApple = Nothing}) $ \env@BadgeServiceEnv {bsClock, bsClientCfg, bsController = cc} -> + withStoreServiceVerifier ps (\store -> (fakeVerifier store) {verifyApple = Nothing}) $ \env@StoreServiceEnv {bsClock, bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do let a = chatController alice openPurchases = @@ -5587,7 +5587,7 @@ testInvoiceRefusedWhileFirstAttemptOpen ps = do release <- newEmptyMVar hook <- newIORef $ putMVar entered () >> takeMVar release let holding store = (googleVerifierWithHook hook store) {verifyTimeout = 60000000} - withBadgeServiceVerifier ps holding $ \BadgeServiceEnv {bsClientCfg} -> + withStoreServiceVerifier ps holding $ \StoreServiceEnv {bsClientCfg} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do alice ##> ("/_badge purchase 1 " <> paymentArg supporterPlay) storePurchaseOpen alice "" @@ -5601,7 +5601,7 @@ testInvoiceRefusedWhileFirstAttemptOpen ps = do testInvoiceUnknown :: HasCallStack => TestParams -> IO () testInvoiceUnknown ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClientCfg} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClientCfg} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do alice ##> "/create user alisa" showActiveUser alice "alisa" @@ -5613,7 +5613,7 @@ testInvoiceUnknown ps = testInvoiceHeldByAnotherRecord :: HasCallStack => TestParams -> IO () testInvoiceHeldByAnotherRecord ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do invoiceId <- createInvoice alice 1 alice ##> purchaseWithInvoice 1 invoiceId (googlePayment "badge_supporter_01" "not-a-purchase") @@ -5625,7 +5625,7 @@ testInvoiceHeldByAnotherRecord ps = testInvoiceAgedOut :: HasCallStack => TestParams -> IO () testInvoiceAgedOut ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClientCfg, bsClock = clock} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClientCfg, bsClock = clock} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do unpaid <- createInvoice alice 1 presented <- createInvoice alice 1 @@ -5650,11 +5650,11 @@ testInvoiceAgedOut ps = testInvoiceRefusedBeforeCharge :: HasCallStack => TestParams -> IO () testInvoiceRefusedBeforeCharge ps = do - withNewTestChatCfg ps testCfg {badgeServiceAddress = Nothing} "bob" bobProfile $ \bob -> do + withNewTestChatCfg ps testCfg {storeServiceAddress = Nothing} "bob" bobProfile $ \bob -> do bob ##> "/_badge invoice 1" - bob <## "cannot get badge: badge service not configured" + bob <## "cannot get badge: store service not configured" storeReceiptRows (chatController bob) `shouldReturn` [] - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do code <- issueCode cc BTSupporter 1 redeemFirstBadge alice code @@ -5664,7 +5664,7 @@ testInvoiceRefusedBeforeCharge ps = do testInvoiceWhileBadgeHeld :: HasCallStack => TestParams -> IO () testInvoiceWhileBadgeHeld ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do invoiceId <- createInvoice alice 1 code <- issueCode cc BTSupporter 1 @@ -5679,7 +5679,7 @@ testInvoiceWhileBadgeHeld ps = testInvoiceStateOtherProfile :: HasCallStack => TestParams -> IO () testInvoiceStateOtherProfile ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClientCfg} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClientCfg} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do _ <- createInvoice alice 1 alice ##> "/create user alisa" @@ -5696,7 +5696,7 @@ testInvoiceStateOtherProfile ps = testStoreReceiptRetried :: HasCallStack => TestParams -> IO () testStoreReceiptRetried ps = do broken <- newIORef True - withBadgeServiceVerifier ps (brokenGoogle broken) $ \BadgeServiceEnv {bsClientCfg, bsController = cc} -> + withStoreServiceVerifier ps (brokenGoogle broken) $ \StoreServiceEnv {bsClientCfg, bsController = cc} -> withNewTestChatCfg ps (fastRetryCfg bsClientCfg) "alice" aliceProfile $ \alice -> do invoiceId <- createInvoice alice 1 alice ##> purchaseWithInvoice 1 invoiceId supporterPlay @@ -5708,7 +5708,7 @@ testStoreReceiptRetried ps = do testStoreReceiptNotBlocked :: HasCallStack => TestParams -> IO () testStoreReceiptNotBlocked ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClientCfg, bsStore = store@FakeStore {appleSupporterJWS}} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClientCfg, bsStore = store@FakeStore {appleSupporterJWS}} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do setGoogleDown store True alice ##> ("/_badge purchase 1 " <> paymentArg supporterPlay) @@ -5725,7 +5725,7 @@ testStoreRefusalKept :: HasCallStack => TestParams -> IO () testStoreRefusalKept ps = do hook <- newIORef (pure ()) verifications <- countGoogleVerifications hook - withBadgeServiceVerifier ps (googleVerifierWithHook hook) $ \BadgeServiceEnv {bsClientCfg} -> + withStoreServiceVerifier ps (googleVerifierWithHook hook) $ \StoreServiceEnv {bsClientCfg} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do let refused = "/_badge purchase 1 " <> paymentArg (googlePayment "badge_supporter_01" "not-a-purchase") alice ##> refused @@ -5734,7 +5734,7 @@ testStoreRefusalKept ps = do heldStoreReceipts (chatController alice) `shouldEventuallyReturn` 0 (alice refused - alice <## "cannot get badge: badge service error: receipt_invalid" + alice <## "cannot get badge: store service error: receipt_invalid" alice ##> "/_badge state 1" (alice TestParams -> IO () testStoreTestPurchaseRefused ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClientCfg, bsStore = FakeStore {appleSandboxJWS}} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClientCfg, bsStore = FakeStore {appleSandboxJWS}} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do invoiceId <- createInvoice alice 1 let purchase = purchaseWithInvoice 1 invoiceId SPApple {jws = appleSandboxJWS} @@ -5750,11 +5750,11 @@ testStoreTestPurchaseRefused ps = alice <### [StartsWith (invoicePurchase "" invoiceId), ConsoleString (refusedLine "" invoiceId "service_error final test_purchase")] heldStoreReceipts (chatController alice) `shouldReturn` 0 alice ##> purchase - alice <## "cannot get badge: badge service error: test_purchase" + alice <## "cannot get badge: store service error: test_purchase" testStoreSettledOtherProfile :: HasCallStack => TestParams -> IO () testStoreSettledOtherProfile ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClientCfg} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClientCfg} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do shown <- createInvoice alice 1 hidden <- createInvoice alice 1 @@ -5779,7 +5779,7 @@ testStoreSettledOtherProfile ps = testStoreReceiptTwoAtOnce :: HasCallStack => TestParams -> IO () testStoreReceiptTwoAtOnce ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClientCfg, bsController = cc} -> + withStoreServiceEnv ps $ \StoreServiceEnv {bsClientCfg, bsController = cc} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> do invoiceId <- createInvoice alice 1 let handOver = void $ sendChatCmdStr (chatController alice) (purchaseWithInvoice 1 invoiceId supporterPlay) @@ -5791,7 +5791,7 @@ testStoreReceiptTwoAtOnce ps = testStoreReceiptCleanup :: HasCallStack => TestParams -> IO () testStoreReceiptCleanup ps = - withBadgeServiceEnv ps $ \BadgeServiceEnv {bsClientCfg, bsClock, bsStore = FakeStore {appleSupporterJWS}} -> do + withStoreServiceEnv ps $ \StoreServiceEnv {bsClientCfg, bsClock, bsStore = FakeStore {appleSupporterJWS}} -> do let cfg = bsClientCfg {initialCleanupManagerDelay = 0, cleanupManagerInterval = 1, cleanupManagerStepDelay = 0} withNewTestChatCfg ps cfg "alice" aliceProfile $ \alice -> do unpaid <- createInvoice alice 1 @@ -5823,7 +5823,7 @@ testStoreReceiptCleanup ps = testStoreReceiptAttemptThrows :: HasCallStack => TestParams -> IO () testStoreReceiptAttemptThrows ps = do broken <- newIORef True - withBadgeServiceVerifier ps (brokenGoogle broken) $ \BadgeServiceEnv {bsClientCfg} -> + withStoreServiceVerifier ps (brokenGoogle broken) $ \StoreServiceEnv {bsClientCfg} -> withNewTestChatCfg ps (fastRetryCfg bsClientCfg) "alice" aliceProfile $ \alice -> do alice ##> ("/_badge purchase 1 " <> paymentArg supporterPlay) storePurchaseOpen alice "" @@ -5837,7 +5837,7 @@ testStoreReceiptAttemptThrows ps = do testStoreReceiptAfterRestart :: HasCallStack => TestParams -> IO () testStoreReceiptAfterRestart ps = do broken <- newIORef True - withBadgeServiceVerifier ps (brokenGoogle broken) $ \BadgeServiceEnv {bsClientCfg} -> do + withStoreServiceVerifier ps (brokenGoogle broken) $ \StoreServiceEnv {bsClientCfg} -> do let cfg = fastRetryCfg bsClientCfg invoiceId <- withNewTestChatCfg ps cfg "alice" aliceProfile $ \alice -> do invoiceId <- createInvoice alice 1 @@ -5857,7 +5857,7 @@ testPlayHoldsNoOtherRequest ps = do hook <- newIORef $ putMVar entered () >> takeMVar release -- past the 20s line wait, so a request queued behind the held call cannot be answered in time let holding store = (googleVerifierWithHook hook store) {verifyTimeout = 60000000} - withBadgeServiceVerifier ps holding $ \BadgeServiceEnv {bsClientCfg, bsAddress, bsController = cc, bsStore = FakeStore {appleSupporterJWS}} -> + withStoreServiceVerifier ps holding $ \StoreServiceEnv {bsClientCfg, bsAddress, bsController = cc, bsStore = FakeStore {appleSupporterJWS}} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> withNewTestChatCfg ps bsClientCfg "bob" bobProfile $ \bob -> withNewTestChatCfg ps bsClientCfg "cath" cathProfile $ \cath -> do @@ -5877,7 +5877,7 @@ testPlayHoldsNoOtherRequest ps = do masterKey <- generateMasterKey g now <- getCurrentTime let upgrade = BadgeUpgrade {fromPurchaseKey, receipt = "receipt", receiptSignature = C.sign' fromPriv "receipt", balance = BadgeBalance {lastEntry = emptyEntry now BTSupporter}} - upgradeReq = LB.unpack $ J.encode $ requestObject upgradeKey BSCPurchaseBadge {masterKey, payment = supporterPlay, upgrade = Just upgrade} + upgradeReq = LB.unpack $ J.encode $ requestObject upgradeKey STCPurchaseBadge {masterKey, payment = supporterPlay, upgrade = Just upgrade} bob ##> ("/_service_request 1 " <> bsAddress <> " sign_key=" <> B.unpack (strEncode $ C.StoredPrivateKey upgradePriv) <> " " <> upgradeReq) bob <## "service response: {\"code\":\"bad_request\",\"type\":\"error\"}" putMVar release () @@ -5888,8 +5888,8 @@ testStoreChecksConfigured :: HasCallStack => TestParams -> IO () testStoreChecksConfigured _ = do createDirectoryIfMissing True "tests/tmp" withTempDirectory "tests/tmp" "store-checks" $ \d -> do - writeFile (d "badge_service.ini") "[listener]\nstatic_dir = /srv/badges\n" - Right cfg <- readServiceConfig (d "badge_service.ini") + writeFile (d "store_service.ini") "[listener]\nstatic_dir = /srv/badges\n" + Right cfg <- readServiceConfig (d "store_service.ini") let checksFor c = (\ServiceState {storeVerifier} -> storeChecks storeVerifier) <$> (newServiceState >>= configureStoreVerifier c) creditsFor c = (\ServiceState {storeVerifier} -> creditTestPurchases storeVerifier) <$> (newServiceState >>= configureStoreVerifier c) dev accept during credit = Just cfg {devAcceptUnverifiedStoreReceipts = accept, devCheckStoreDuringCoverage = during, devCreditTestPurchases = credit} @@ -5909,7 +5909,7 @@ testStoreChecksConfigured _ = do testStoreRouting :: HasCallStack => TestParams -> IO () testStoreRouting ps = - withBadgeServiceEnv ps $ \env@BadgeServiceEnv {bsClock, bsController = cc, bsStore = store@FakeStore {appleSubscriptionJWS, appleLegendSubscriptionJWS, appleSupporterJWS}} -> do + withStoreServiceEnv ps $ \env@StoreServiceEnv {bsClock, bsController = cc, bsStore = store@FakeStore {appleSubscriptionJWS, appleLegendSubscriptionJWS, appleSupporterJWS}} -> do let routedAs signer key cmd = requestLane ChecksAfterCoverage cc (Just signer) (requestObject key cmd) routed key = routedAs key key (purchaseKey, masterKey) <- newPurchaseKeys @@ -5925,14 +5925,14 @@ testStoreRouting ps = (fromPurchaseKey, fromPriv) <- atomically $ C.generateKeyPair g :: IO (C.KeyPair 'C.Ed25519) now <- getCurrentTime let upgrade = BadgeUpgrade {fromPurchaseKey, receipt = "receipt", receiptSignature = C.sign' fromPriv "receipt", balance = BadgeBalance {lastEntry = emptyEntry now BTSupporter}} - routed purchaseKey BSCPurchaseBadge {masterKey, payment = supporterPlay, upgrade = Just upgrade} `shouldReturn` MainLane + routed purchaseKey STCPurchaseBadge {masterKey, payment = supporterPlay, upgrade = Just upgrade} `shouldReturn` MainLane code <- issueCode cc BTSupporter 1 codeKeys@(codeKey, codeMasterKey) <- newPurchaseKeys - routed codeKey BSCRedeemBadgeCode {masterKey = codeMasterKey, code = badgeCodeText code} `shouldReturn` MainLane + routed codeKey STCRedeemBadgeCode {masterKey = codeMasterKey, code = badgeCodeText code} `shouldReturn` MainLane redeemed <- redeemWithKeys env codeKeys code - routed codeKey BSCIssueBadge {balance = BadgeBalance {lastEntry = last $ fst $ statementOf redeemed}} `shouldReturn` MainLane + routed codeKey STCIssueBadge {balance = BadgeBalance {lastEntry = last $ fst $ statementOf redeemed}} `shouldReturn` MainLane (subscriberKey, firstStart, purchased) <- subscribedMonthly env - let issue = BSCIssueBadge {balance = BadgeBalance {lastEntry = last purchased}} + let issue = STCIssueBadge {balance = BadgeBalance {lastEntry = last purchased}} coverageEnd = addMonths 1 firstStart routedAt t = setClockAt bsClock t >> routed subscriberKey issue answeredWithoutStore = do @@ -5953,7 +5953,7 @@ testStoreRouting ps = answeredWithoutStore routedAt (addUTCTime 3700 lastCheck) `shouldReturn` RenewalLane routedAs purchaseKey subscriberKey issue `shouldReturn` MainLane - let upgradeCmd = BSCUpgradeBadgeSubscription {payment = SPApple {jws = appleSubscriptionJWS}, balance = BadgeBalance {lastEntry = last purchased}} + let upgradeCmd = STCUpgradeBadgeSubscription {payment = SPApple {jws = appleSubscriptionJWS}, balance = BadgeBalance {lastEntry = last purchased}} routed subscriberKey upgradeCmd `shouldReturn` MainLane routedAs purchaseKey subscriberKey upgradeCmd `shouldReturn` MainLane routed codeKey upgradeCmd `shouldReturn` MainLane @@ -5980,7 +5980,7 @@ testRenewalHoldsNoOtherRequest ps = do -- the purchase asks the store too, so the hold is armed once it is credited hook <- newIORef (pure ()) let holding store = (subscriptionCheckWithHook hook store) {verifyTimeout = 60000000} - withBadgeServiceVerifier ps holding $ \env@BadgeServiceEnv {bsClientCfg, bsClock, bsController = cc, bsStore = store@FakeStore {appleSupporterJWS}} -> do + withStoreServiceVerifier ps holding $ \env@StoreServiceEnv {bsClientCfg, bsClock, bsController = cc, bsStore = store@FakeStore {appleSupporterJWS}} -> do -- her request outlives the hold, so her pass does not give up and send it again let patientCfg = bsClientCfg {agentConfig = (agentConfig bsClientCfg) {serviceRequestTimeout = 120}} withNewTestChatCfg ps patientCfg "alice" aliceProfile $ \alice -> @@ -6016,7 +6016,7 @@ testPurchaseHoldsNoRenewal ps = do release <- newEmptyMVar hook <- newIORef $ putMVar entered () >> takeMVar release let holding store = (googleVerifierWithHook hook store) {verifyTimeout = 60000000} - withBadgeServiceVerifier ps holding $ \env@BadgeServiceEnv {bsClientCfg, bsClock, bsStore = store} -> + withStoreServiceVerifier ps holding $ \env@StoreServiceEnv {bsClientCfg, bsClock, bsStore = store} -> withNewTestChatCfg ps bsClientCfg "alice" aliceProfile $ \alice -> withNewTestChatCfg ps bsClientCfg "bob" bobProfile $ \bob -> do (firstStart, rows) <- clientSubscribedMonthly env alice @@ -6041,7 +6041,7 @@ testAppleSubscriptionHoldsNoOtherRequest ps = do release <- newEmptyMVar hook <- newIORef $ putMVar entered () >> takeMVar release let holding store = (subscriptionCheckWithHook hook store) {verifyTimeout = 60000000} - withBadgeServiceVerifier ps holding $ \env@BadgeServiceEnv {bsClientCfg, bsController = cc, bsStore = store@FakeStore {appleSubscriptionJWS}} -> + withStoreServiceVerifier ps holding $ \env@StoreServiceEnv {bsClientCfg, bsController = cc, bsStore = store@FakeStore {appleSubscriptionJWS}} -> withNewTestChatCfg ps bsClientCfg "dan" danProfile $ \dan -> withNewTestChatCfg ps bsClientCfg "bob" bobProfile $ \bob -> do now <- serviceNow env diff --git a/tests/Bots/BadgeService/CatalogTests.hs b/tests/Bots/StoreService/CatalogTests.hs similarity index 98% rename from tests/Bots/BadgeService/CatalogTests.hs rename to tests/Bots/StoreService/CatalogTests.hs index 9e729cd8bb..ae853213fe 100644 --- a/tests/Bots/BadgeService/CatalogTests.hs +++ b/tests/Bots/StoreService/CatalogTests.hs @@ -2,9 +2,9 @@ {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} -module Bots.BadgeService.CatalogTests where +module Bots.StoreService.CatalogTests where -import BadgeService.Catalog +import StoreService.Catalog import Control.Monad (when) import Data.List (find) import qualified Data.Map.Strict as Map @@ -15,7 +15,7 @@ import Data.Time.Clock (UTCTime) import Data.Time.Clock.POSIX (posixSecondsToUTCTime) import Data.Word (Word32, Word8) import Simplex.Chat.Badges (BadgeType (..)) -import Simplex.Chat.Badges.Service (BadgeOffer (..), BadgePrice (..)) +import Simplex.Chat.StoreService (BadgeOffer (..), BadgePrice (..)) import Simplex.Chat.Badges.Types (BadgeItemStatus (..), BadgeOfferId (..), BadgePriceId (..), OfferDiscount (..)) import Simplex.Chat.PaymentService.Types (CurrencyAmount (..)) import Test.Hspec @@ -202,7 +202,7 @@ testPriceOfferAnyPrice = do testNoDriftFromWeb :: IO () testNoDriftFromWeb = do - src <- T.readFile "apps/simplex-badge-service/web/src/catalog.ts" + src <- T.readFile "apps/simplex-store-service/web/src/catalog.ts" case parseCatalogSource src of Nothing -> expectationFailure "could not parse CATALOG out of web/src/catalog.ts -- its shape has changed" Just (webPrices, webOffers) -> do diff --git a/tests/Bots/BadgeService/ConfigTests.hs b/tests/Bots/StoreService/ConfigTests.hs similarity index 99% rename from tests/Bots/BadgeService/ConfigTests.hs rename to tests/Bots/StoreService/ConfigTests.hs index 722dd453b3..9e4b5e9840 100644 --- a/tests/Bots/BadgeService/ConfigTests.hs +++ b/tests/Bots/StoreService/ConfigTests.hs @@ -2,9 +2,9 @@ {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} -module Bots.BadgeService.ConfigTests where +module Bots.StoreService.ConfigTests where -import BadgeService.Config +import StoreService.Config import Control.Monad (forM_) import qualified Data.ByteString.Char8 as B import Data.Either (isLeft) @@ -19,7 +19,7 @@ import Test.Hspec import UnliftIO.Temporary (withTempDirectory) badgeConfigTests :: Spec -badgeConfigTests = describe "badge service config" $ do +badgeConfigTests = describe "store service config" $ do it "applies every documented default" testDefaults it "falls back to the default host when the value is blank" testBlankHost it "disables a provider whose section is absent" testAbsentSection @@ -92,7 +92,7 @@ withIni :: T.Text -> (FilePath -> IO a) -> IO a withIni t f = do createDirectoryIfMissing True "tests/tmp" withTempDirectory "tests/tmp" "badge-ini" $ \d -> do - let p = d "badge_service.ini" + let p = d "store_service.ini" T.writeFile p t f p @@ -296,10 +296,10 @@ testTrailingCommentIsAccepted = do -- would put it in the line twice. testMissingFileIsReported :: IO () testMissingFileIsReported = - readServiceConfig "tests/tmp/no-such-badge_service.ini" >>= \r -> case r of + readServiceConfig "tests/tmp/no-such-store_service.ini" >>= \r -> case r of Left e -> do e `shouldContain` "does not exist" - e `shouldNotContain` "no-such-badge_service.ini" + e `shouldNotContain` "no-such-store_service.ini" Right _ -> expectationFailure "a file that is not there cannot be read" testPaymentTolerance :: IO () diff --git a/tests/Bots/BadgeService/FakeAppStore.hs b/tests/Bots/StoreService/FakeAppStore.hs similarity index 97% rename from tests/Bots/BadgeService/FakeAppStore.hs rename to tests/Bots/StoreService/FakeAppStore.hs index 01346d6666..1713ca19a4 100644 --- a/tests/Bots/BadgeService/FakeAppStore.hs +++ b/tests/Bots/StoreService/FakeAppStore.hs @@ -2,7 +2,7 @@ {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} -module Bots.BadgeService.FakeAppStore +module Bots.StoreService.FakeAppStore ( FakeAppStore (..), AppStoreAnswer (..), withFakeAppStore, @@ -11,8 +11,8 @@ module Bots.BadgeService.FakeAppStore ) where -import BadgeService.Config (AppleServerApi (..)) -import Bots.BadgeService.FakePlay (der, pem) +import StoreService.Config (AppleServerApi (..)) +import Bots.StoreService.FakePlay (der, pem) import Control.Concurrent (threadDelay) import Control.Concurrent.STM import Control.Monad (forever) diff --git a/tests/Bots/BadgeService/FakeBTCPay.hs b/tests/Bots/StoreService/FakeBTCPay.hs similarity index 99% rename from tests/Bots/BadgeService/FakeBTCPay.hs rename to tests/Bots/StoreService/FakeBTCPay.hs index a35b7bd8c8..b9bf45d954 100644 --- a/tests/Bots/BadgeService/FakeBTCPay.hs +++ b/tests/Bots/StoreService/FakeBTCPay.hs @@ -3,7 +3,7 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -module Bots.BadgeService.FakeBTCPay +module Bots.StoreService.FakeBTCPay ( FakeBTCPay (..), FakeRequest (..), withFakeBTCPay, @@ -26,7 +26,7 @@ module Bots.BadgeService.FakeBTCPay ) where -import BadgeService.Config (BTCPayConfig (..), SpeedPolicy (..)) +import StoreService.Config (BTCPayConfig (..), SpeedPolicy (..)) import Control.Applicative ((<|>)) import Control.Concurrent.STM import Control.Monad (join) @@ -75,7 +75,7 @@ import System.FilePath (()) import Text.Read (readMaybe) fixtureDir :: FilePath -fixtureDir = "apps" "simplex-badge-service" "test-fixtures" "btcpay" +fixtureDir = "apps" "simplex-store-service" "test-fixtures" "btcpay" fakeApiKey :: Text fakeApiKey = "7f3c1d9a2e5b48c6905ad1e2f3b4c5d6e7f80912" diff --git a/tests/Bots/BadgeService/FakeEthNode.hs b/tests/Bots/StoreService/FakeEthNode.hs similarity index 98% rename from tests/Bots/BadgeService/FakeEthNode.hs rename to tests/Bots/StoreService/FakeEthNode.hs index 6d9f9350a2..bec267bd31 100644 --- a/tests/Bots/BadgeService/FakeEthNode.hs +++ b/tests/Bots/StoreService/FakeEthNode.hs @@ -1,7 +1,7 @@ {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} -module Bots.BadgeService.FakeEthNode +module Bots.StoreService.FakeEthNode ( FakeEthNode (..), withFakeEthNode, revertCalls, diff --git a/tests/Bots/BadgeService/FakePlay.hs b/tests/Bots/StoreService/FakePlay.hs similarity index 99% rename from tests/Bots/BadgeService/FakePlay.hs rename to tests/Bots/StoreService/FakePlay.hs index 07b36471de..6078064bf7 100644 --- a/tests/Bots/BadgeService/FakePlay.hs +++ b/tests/Bots/StoreService/FakePlay.hs @@ -2,7 +2,7 @@ {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} -module Bots.BadgeService.FakePlay +module Bots.StoreService.FakePlay ( FakePlay (..), PlayAnswer (..), withFakePlay, @@ -16,7 +16,7 @@ module Bots.BadgeService.FakePlay ) where -import BadgeService.Config (PlayStoreConfig (..)) +import StoreService.Config (PlayStoreConfig (..)) import Control.Concurrent (threadDelay) import Control.Concurrent.STM import Control.Monad (forever) diff --git a/tests/Bots/BadgeService/FakeStore.hs b/tests/Bots/StoreService/FakeStore.hs similarity index 98% rename from tests/Bots/BadgeService/FakeStore.hs rename to tests/Bots/StoreService/FakeStore.hs index a8a29bfc57..0f2b5396da 100644 --- a/tests/Bots/BadgeService/FakeStore.hs +++ b/tests/Bots/StoreService/FakeStore.hs @@ -4,7 +4,7 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} -module Bots.BadgeService.FakeStore +module Bots.StoreService.FakeStore ( FakeStore (..), newFakeStore, googleVerifierWithHook, @@ -28,7 +28,7 @@ module Bots.BadgeService.FakeStore ) where -import BadgeService.StoreReceipts +import StoreService.StoreReceipts import Control.Concurrent (threadDelay) import Control.Monad (forever) import qualified Data.Aeson as J @@ -47,7 +47,7 @@ import Simplex.Messaging.Util (safeDecodeUtf8) import System.FilePath (()) fixtureDir :: FilePath -fixtureDir = "apps" "simplex-badge-service" "test-fixtures" "apple" +fixtureDir = "apps" "simplex-store-service" "test-fixtures" "apple" -- | The Apple JWS are the fixtures under no real signature, so they are accepted as these exact -- strings only, never because a payload decodes - which a real verifier must refuse to do. diff --git a/tests/Bots/BadgeService/FakeStripe.hs b/tests/Bots/StoreService/FakeStripe.hs similarity index 99% rename from tests/Bots/BadgeService/FakeStripe.hs rename to tests/Bots/StoreService/FakeStripe.hs index db4845c16f..e4fe3f86f7 100644 --- a/tests/Bots/BadgeService/FakeStripe.hs +++ b/tests/Bots/StoreService/FakeStripe.hs @@ -3,7 +3,7 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -module Bots.BadgeService.FakeStripe +module Bots.StoreService.FakeStripe ( FakeStripe (..), FakeRequest (..), withFakeStripe, @@ -21,7 +21,7 @@ module Bots.BadgeService.FakeStripe ) where -import BadgeService.Config (StripeConfig (..)) +import StoreService.Config (StripeConfig (..)) import Control.Concurrent.STM import Crypto.Hash (Digest, SHA256) import Crypto.MAC.HMAC (HMAC, hmac, hmacGetDigest) @@ -67,7 +67,7 @@ import System.FilePath (()) import Text.Read (readMaybe) fixtureDir :: FilePath -fixtureDir = "apps" "simplex-badge-service" "test-fixtures" "stripe" +fixtureDir = "apps" "simplex-store-service" "test-fixtures" "stripe" -- | A restricted `rk_` key shaped like Stripe's, the kind the service is configured with and never a live one. fakeSecretKey :: Text diff --git a/tests/Bots/BadgeService/GroupIntegrationTests.hs b/tests/Bots/StoreService/GroupIntegrationTests.hs similarity index 98% rename from tests/Bots/BadgeService/GroupIntegrationTests.hs rename to tests/Bots/StoreService/GroupIntegrationTests.hs index 0a632b46b5..c05e75385c 100644 --- a/tests/Bots/BadgeService/GroupIntegrationTests.hs +++ b/tests/Bots/StoreService/GroupIntegrationTests.hs @@ -7,15 +7,15 @@ {-# LANGUAGE ScopedTypeVariables #-} -- Members' messages reach a console over separate connections in no fixed order, so gating is asserted from the bot's store. -module Bots.BadgeService.GroupIntegrationTests (badgeGroupIntegrationTests) where +module Bots.StoreService.GroupIntegrationTests (badgeGroupIntegrationTests) where -import BadgeService.Config (BadgeIssuerKey (..), GroupConfig (..)) -import BadgeService.Group (GroupAction (..), GroupEvent (..), codeInTracker, ensureManagedGroup) -import BadgeService.Group.Command (maxUses) -import BadgeService.Options (BadgeServiceOpts (..)) -import BadgeService.Service (ServiceState (..), badgeService, newServiceState) -import BadgeService.Store (ManagedGroup (..), getManagedGroup) -import Bots.BadgeService.BotTests (badgeBotName, badgeProfile, badgeTypeOf, credentialOf, entryOf, issueCode, issueRaw, mkBadgeServiceOpts, newPurchaseKeys, redeemWithQueue, requestObject, revokeRaw, serviceDbPrefix, shouldAnswerError, statementOf, stopBadgeService, testIssuerKeyIdx) +import StoreService.Config (BadgeIssuerKey (..), GroupConfig (..)) +import StoreService.Group (GroupAction (..), GroupEvent (..), codeInTracker, ensureManagedGroup) +import StoreService.Group.Command (maxUses) +import StoreService.Options (StoreServiceOpts (..)) +import StoreService.Service (ServiceState (..), storeService, newServiceState) +import StoreService.Store (ManagedGroup (..), getManagedGroup) +import Bots.StoreService.BotTests (badgeBotName, badgeProfile, badgeTypeOf, credentialOf, entryOf, issueCode, issueRaw, mkStoreServiceOpts, newPurchaseKeys, redeemWithQueue, requestObject, revokeRaw, serviceDbPrefix, shouldAnswerError, statementOf, stopStoreService, testIssuerKeyIdx) import ChatClient import ChatTests.DBUtils import ChatTests.Utils @@ -40,7 +40,7 @@ import Network.Socket (Family (..), SockAddr (..), SocketType (..), close, conne import Network.Wai.Handler.Warp (openFreePort) import Simplex.Chat.Badges (BadgeType (..)) import Simplex.Chat.Badges.Code (formatBadgeCode, parseBadgeCode, randomBadgeCode) -import Simplex.Chat.Badges.Service +import Simplex.Chat.StoreService import Simplex.Chat.Controller (ChatCommand (APIDeleteChatItem), ChatConfig (..), ChatController (..), ChatResponse (CRChatItemsDeleted)) import Simplex.Chat.Core (sendChatCmd, sendChatCmdStr) import Simplex.Chat.Messages (ChatRef (ChatRef), ChatType (CTGroup)) @@ -184,13 +184,13 @@ startGroupService :: HasCallStack => GroupSvc -> Maybe GroupConfig -> IO (Async startGroupService svc@GroupSvc {gsCfg} groupCfg = do (opts, port) <- groupServiceOpts svc groupCfg env <- newServiceState - t <- async $ badgeService opts gsCfg env + t <- async $ storeService opts gsCfg env -- A service that ends before it is ready fails the test with its own error, not the timeout. cc <- timeout waitLimit (atomically $ (Right <$> readTMVar (serviceCC env)) `orElse` (Left <$> waitCatchSTM t)) >>= \case Just (Right cc) -> pure cc - Just (Left ended) -> either throwIO (\_ -> error "badge service ended before it started") ended - Nothing -> cancel t >> error "badge service did not start" + Just (Left ended) -> either throwIO (\_ -> error "store service ended before it started") ended + Nothing -> cancel t >> error "store service did not start" pure (t, cc, env, port) -- Cancelling ends the service lanes while chat still runs; stopping chat first would leave them running. @@ -203,10 +203,10 @@ stopGroupService t cc = do forM_ ended $ either throwIO pure stopChat :: ChatController -> IO () -stopChat cc = stopBadgeService cc >> disposeAgentClient (smpAgent cc) +stopChat cc = stopStoreService cc >> disposeAgentClient (smpAgent cc) -- It writes the service's ini on a free port; Nothing omits the [group] section. -groupServiceOpts :: GroupSvc -> Maybe GroupConfig -> IO (BadgeServiceOpts, Int) +groupServiceOpts :: GroupSvc -> Maybe GroupConfig -> IO (StoreServiceOpts, Int) groupServiceOpts GroupSvc {gsKey = BadgeIssuerKey {secretKey}, gsStaticDir, gsPs = ps@TestParams {tmpPath}} groupCfg = do (port, sock) <- openFreePort close sock @@ -219,7 +219,7 @@ groupServiceOpts GroupSvc {gsKey = BadgeIssuerKey {secretKey}, gsStaticDir, gsPs "static_dir = " <> gsStaticDir ] <> maybe [] groupSection groupCfg - pure ((mkBadgeServiceOpts ps secretKey) {serviceConfigFile = Just iniPath, noAddress = True}, port) + pure ((mkStoreServiceOpts ps secretKey) {serviceConfigFile = Just iniPath, noAddress = True}, port) where groupSection GroupConfig {gDisplayName, gDescription} = ["", "[group]", "display_name = " <> T.unpack gDisplayName] @@ -390,7 +390,7 @@ testGroupLookupFailureStops ps = do (opts, _) <- groupServiceOpts svc (Just testGroupConfig) env <- newServiceState -- Falling through to create would keep the service running, so the timeout would fire instead. - ended <- timeout waitLimit (try $ badgeService opts gsCfg env) + ended <- timeout waitLimit (try $ storeService opts gsCfg env) atomically (tryReadTMVar (serviceCC env)) >>= mapM_ stopChat ended `shouldBe` Just (Left (ExitFailure 1)) @@ -573,7 +573,7 @@ testBulkIssue ps = r <- redeemViaService gsKey cc env code badgeTypeOf r `shouldBe` Just BTLegend map (\e -> let (c, m, _) = entryOf e in (c, m)) (fst $ statementOf r) `shouldBe` [(2, 2), (-1, 1)] - forM_ codes $ \code -> redeemViaService gsKey cc env code >>= (`shouldAnswerError` BSECodeUsed) + forM_ codes $ \code -> redeemViaService gsKey cc env code >>= (`shouldAnswerError` STECodeUsed) countRows cc "sx_badge_service_badge_codes WHERE group_item_id IS NOT NULL" `shouldReturn` 0 testIssueMonths :: HasCallStack => TestParams -> IO () @@ -649,7 +649,7 @@ testMultiUseTracker ps = redeemOk gsKey cc env code usedUp <- waitItemText cc trackerItemId "All 2 uses redeemed" sentItemsWithCode cc code `shouldReturn` [usedUp] - redeemViaService gsKey cc env code >>= (`shouldAnswerError` BSECodeUsed) + redeemViaService gsKey cc env code >>= (`shouldAnswerError` STECodeUsed) testStaleRefreshIgnored :: HasCallStack => TestParams -> IO () testStaleRefreshIgnored ps = @@ -820,7 +820,7 @@ testGroupRevoke ps = code <- extractCode <$> replyTo cc alice "/issue supporter" other <- extractCode <$> replyTo cc alice "/issue legend" revokeInGroup cc alice code "Revoked." - redeemViaService gsKey cc env code >>= (`shouldAnswerError` BSECodeInvalid) + redeemViaService gsKey cc env code >>= (`shouldAnswerError` STECodeInvalid) redeemOk gsKey cc env other revokeInGroup cc alice code "Already revoked." -- The reply follows the tracker step, so the revoke has already passed it here. @@ -968,7 +968,7 @@ testRevokeRetiresTracker ps = awaitLane cc env readItemText cc trackerItemId `shouldReturn` retired revokedTrackerCount cc `shouldReturn` 1 - redeemViaService gsKey cc env code >>= (`shouldAnswerError` BSECodeInvalid) + redeemViaService gsKey cc env code >>= (`shouldAnswerError` STECodeInvalid) testServiceRevokeRetiresTracker :: HasCallStack => TestParams -> IO () testServiceRevokeRetiresTracker ps = @@ -1009,7 +1009,7 @@ redeemOkWith key cc trackerQ_ code = do r <- redeemWithQueue key cc trackerQ_ code credentialOf r `shouldSatisfy` isJust -redeemViaService :: HasCallStack => BadgeIssuerKey -> ChatController -> ServiceState -> Text -> IO BadgeServiceResponse +redeemViaService :: HasCallStack => BadgeIssuerKey -> ChatController -> ServiceState -> Text -> IO StoreServiceResponse redeemViaService key cc env = redeemWithQueue key cc (Just (groupEventQ env)) -- The reply to the made-up request id fails after the redemption, and the service only logs it. @@ -1017,7 +1017,7 @@ queueRedemption :: HasCallStack => ChatController -> ServiceState -> Text -> IO queueRedemption cc env codeText = do user <- readTVarIO (currentUser cc) >>= maybe (error "no current user") pure (purchaseKey, masterKey) <- newPurchaseKeys - let request = requestObject purchaseKey BSCRedeemBadgeCode {masterKey, code = codeText} + let request = requestObject purchaseKey STCRedeemBadgeCode {masterKey, code = codeText} atomically $ writeTQueue (serviceRequestQ env) (user, AgentInvId "test-request", Just purchaseKey, request) redeemLosingRefresh :: HasCallStack => BadgeIssuerKey -> ChatController -> Text -> IO () diff --git a/tests/Bots/BadgeService/GroupTests.hs b/tests/Bots/StoreService/GroupTests.hs similarity index 98% rename from tests/Bots/BadgeService/GroupTests.hs rename to tests/Bots/StoreService/GroupTests.hs index 40baa25f12..cbe23550a6 100644 --- a/tests/Bots/BadgeService/GroupTests.hs +++ b/tests/Bots/StoreService/GroupTests.hs @@ -1,10 +1,10 @@ {-# LANGUAGE OverloadedStrings #-} -module Bots.BadgeService.GroupTests where +module Bots.StoreService.GroupTests where -import BadgeService.Config (GroupConfig (..)) -import BadgeService.Group (GroupAction (..), GroupEvent (..), TrackerAction (..), coalesceTrackerRefreshes, inertGroupConfig, noOwnerHint, orphanHint, trackerDecision) -import BadgeService.Group.Command +import StoreService.Config (GroupConfig (..)) +import StoreService.Group (GroupAction (..), GroupEvent (..), TrackerAction (..), coalesceTrackerRefreshes, inertGroupConfig, noOwnerHint, orphanHint, trackerDecision) +import StoreService.Group.Command import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) import Data.Time.Calendar (fromGregorian) diff --git a/tests/Bots/BadgeService/NameRegistrationTests.hs b/tests/Bots/StoreService/NameRegistrationTests.hs similarity index 97% rename from tests/Bots/BadgeService/NameRegistrationTests.hs rename to tests/Bots/StoreService/NameRegistrationTests.hs index 79989c576f..fa5e096c4d 100644 --- a/tests/Bots/BadgeService/NameRegistrationTests.hs +++ b/tests/Bots/StoreService/NameRegistrationTests.hs @@ -1,12 +1,12 @@ {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} -module Bots.BadgeService.NameRegistrationTests (badgeNameRegistrationTests) where +module Bots.StoreService.NameRegistrationTests (badgeNameRegistrationTests) where -import BadgeService.Names.Chain -import BadgeService.Names.Registration -import Bots.BadgeService.FakeEthNode -import Bots.BadgeService.WebUIMock +import StoreService.Names.Chain +import StoreService.Names.Registration +import Bots.StoreService.FakeEthNode +import Bots.StoreService.WebUIMock import Control.Concurrent.STM (TVar) import Crypto.Random (ChaChaDRG) import qualified Data.ByteArray as BA @@ -25,7 +25,7 @@ import Simplex.Messaging.SimplexName (SimplexTLD (..)) import Test.Hspec badgeNameRegistrationTests :: Spec -badgeNameRegistrationTests = describe "badge service name registration" $ do +badgeNameRegistrationTests = describe "store service name registration" $ do g <- runIO C.newRandom -- expected encodings and signatures are viem's, against the SimplexController, SimplexSponsor and SimplexResolver ABIs describe "encoding" $ do diff --git a/tests/Bots/BadgeService/StoreVerifierTests.hs b/tests/Bots/StoreService/StoreVerifierTests.hs similarity index 98% rename from tests/Bots/BadgeService/StoreVerifierTests.hs rename to tests/Bots/StoreService/StoreVerifierTests.hs index e210389f0f..442ff4a880 100644 --- a/tests/Bots/BadgeService/StoreVerifierTests.hs +++ b/tests/Bots/StoreService/StoreVerifierTests.hs @@ -3,7 +3,7 @@ {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} -module Bots.BadgeService.StoreVerifierTests +module Bots.StoreService.StoreVerifierTests ( badgeStoreVerifierTests, TestChain (..), trustedChain, @@ -18,13 +18,13 @@ module Bots.BadgeService.StoreVerifierTests ) where -import BadgeService.Config (AppleServerApi (..), AppleStoreConfig (..), PlayStoreConfig (..), ServiceConfig (..), readServiceConfig) -import BadgeService.Service (ServiceState (..), configureStoreVerifier, newServiceState) -import BadgeService.StoreReceipts -import BadgeService.StoreReceipts.Apple (appleSubscriptionChecker, readAppleRoot, verifyAppleTransaction) -import BadgeService.StoreReceipts.Google (PlayVerifier (..), playStoreVerifier) -import Bots.BadgeService.FakeAppStore -import Bots.BadgeService.FakePlay +import StoreService.Config (AppleServerApi (..), AppleStoreConfig (..), PlayStoreConfig (..), ServiceConfig (..), readServiceConfig) +import StoreService.Service (ServiceState (..), configureStoreVerifier, newServiceState) +import StoreService.StoreReceipts +import StoreService.StoreReceipts.Apple (appleSubscriptionChecker, readAppleRoot, verifyAppleTransaction) +import StoreService.StoreReceipts.Google (PlayVerifier (..), playStoreVerifier) +import Bots.StoreService.FakeAppStore +import Bots.StoreService.FakePlay import Control.Concurrent.STM (readTVarIO) import Control.Exception (throwIO) import Control.Monad (forM_) @@ -51,7 +51,7 @@ import Data.Time.Calendar (fromGregorian) import Data.Time.Clock (UTCTime (..)) import Data.Time.Clock.POSIX (posixSecondsToUTCTime) import Data.X509 -import Simplex.Chat.Badges.Service (SubscriptionState (..)) +import Simplex.Chat.StoreService (SubscriptionState (..)) import Simplex.Chat.PaymentService (ServicePayment (..), appleTransactionRef, googlePurchaseRef) import Simplex.Chat.PaymentService.Types (CurrencyAmount (..)) import System.Directory (createDirectoryIfMissing) @@ -411,7 +411,7 @@ testApplePrice = do testReadAppleRoot :: IO () testReadAppleRoot = do TestChain {rootCert, intermediateCert} <- trustedChain - readAppleRoot ("apps" "simplex-badge-service" "test-fixtures" "apple" "AppleRootCA-G3.cer") >>= (`shouldSatisfy` isRight) + readAppleRoot ("apps" "simplex-store-service" "test-fixtures" "apple" "AppleRootCA-G3.cer") >>= (`shouldSatisfy` isRight) createDirectoryIfMissing True "tests/tmp" withTempDirectory "tests/tmp" "apple-root" $ \d -> do B.writeFile (d "root.cer") (encodeSignedObject rootCert) @@ -646,7 +646,7 @@ testAppleConfiguredSubscriptions = do withFakeAppStore ourBundleId $ \fake@FakeAppStore {fasApi} -> do let dir = takeDirectory (aPrivateKeyFile fasApi) rootFile = dir "root.cer" - ini = dir "badge_service.ini" + ini = dir "store_service.ini" apple serverApi = Just AppleStoreConfig {aBundleId = ourBundleId, aRootCertificates = rootFile :| [], aServerApi = serverApi} B.writeFile rootFile (encodeSignedObject $ rootCert chain) writeFile ini "[listener]\nstatic_dir = /srv/badges\n" @@ -878,7 +878,7 @@ testPlayAcknowledgementFails = withFakePlay $ \fake -> do testPlayConfiguredAcknowledges :: IO () testPlayConfiguredAcknowledges = withFakePlay $ \fake@FakePlay {fpConfig} -> do - let ini = takeDirectory (gServiceAccountFile fpConfig) "badge_service.ini" + let ini = takeDirectory (gServiceAccountFile fpConfig) "store_service.ini" writeFile ini "[listener]\nstatic_dir = /srv/badges\n" Right cfg <- readServiceConfig ini ServiceState {storeVerifier} <- newServiceState >>= configureStoreVerifier (Just cfg {playStore = Just fpConfig}) @@ -1071,7 +1071,7 @@ testPlayConfiguredSubscriptions = do withFakePlay $ \play@FakePlay {fpConfig} -> withFakeAppStore ourBundleId $ \appStore@FakeAppStore {fasApi} -> do let dir = takeDirectory (gServiceAccountFile fpConfig) rootFile = dir "root.cer" - ini = dir "badge_service.ini" + ini = dir "store_service.ini" apple = Just AppleStoreConfig {aBundleId = ourBundleId, aRootCertificates = rootFile :| [], aServerApi = Just fasApi} configured c = (\ServiceState {storeVerifier} -> storeVerifier) <$> (newServiceState >>= configureStoreVerifier (Just c)) outcomes v = (,) <$> (outcome <$> checkStoreSubscription v (SubscriptionGoogle subscriptionToken) Nothing) <*> (outcome <$> checkStoreSubscription v (SubscriptionApple subscriptionId) Nothing) diff --git a/tests/Bots/BadgeService/StripeTests.hs b/tests/Bots/StoreService/StripeTests.hs similarity index 98% rename from tests/Bots/BadgeService/StripeTests.hs rename to tests/Bots/StoreService/StripeTests.hs index 6ab5c58486..773df83c05 100644 --- a/tests/Bots/BadgeService/StripeTests.hs +++ b/tests/Bots/StoreService/StripeTests.hs @@ -2,10 +2,10 @@ {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} -module Bots.BadgeService.StripeTests (badgeStripeTests) where +module Bots.StoreService.StripeTests (badgeStripeTests) where -import BadgeService.Config (StripeConfig (..)) -import BadgeService.Providers +import StoreService.Config (StripeConfig (..)) +import StoreService.Providers ( ListPass (..), OrderDraft (..), PaymentSignal (..), @@ -16,8 +16,8 @@ import BadgeService.Providers settleWindow, WebhookError (..), ) -import BadgeService.Providers.Stripe (IntentRead (..), signalOf, stripeProvider) -import Bots.BadgeService.FakeStripe +import StoreService.Providers.Stripe (IntentRead (..), signalOf, stripeProvider) +import Bots.StoreService.FakeStripe import Control.Monad (join) import Data.Aeson ((.=)) import qualified Data.ByteString.Char8 as B8 diff --git a/tests/Bots/BadgeService/WaitersTests.hs b/tests/Bots/StoreService/WaitersTests.hs similarity index 97% rename from tests/Bots/BadgeService/WaitersTests.hs rename to tests/Bots/StoreService/WaitersTests.hs index 8e5b5a180d..1bdafc76b9 100644 --- a/tests/Bots/BadgeService/WaitersTests.hs +++ b/tests/Bots/StoreService/WaitersTests.hs @@ -3,9 +3,9 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeApplications #-} -module Bots.BadgeService.WaitersTests (badgeWaitersTests) where +module Bots.StoreService.WaitersTests (badgeWaitersTests) where -import BadgeService.Waiters +import StoreService.Waiters import Control.Concurrent.Async (wait, withAsync) import Control.Concurrent.STM import Control.Exception (Exception, SomeException, throwIO, try) @@ -16,7 +16,7 @@ import System.Timeout (timeout) import Test.Hspec badgeWaitersTests :: Spec -badgeWaitersTests = describe "badge service waiters" $ do +badgeWaitersTests = describe "store service waiters" $ do it "wakes on a status published between subscribe and the database read" testSubscribeBeforeRead it "answers a payment whose publish landed before this request subscribed" testPaymentPublishedBeforeSubscribe it "is not woken by a publish for a different invoice" testDifferentInvoiceNoWake diff --git a/tests/Bots/BadgeService/WebTests.hs b/tests/Bots/StoreService/WebTests.hs similarity index 98% rename from tests/Bots/BadgeService/WebTests.hs rename to tests/Bots/StoreService/WebTests.hs index 52d4b5ace9..a0b6906838 100644 --- a/tests/Bots/BadgeService/WebTests.hs +++ b/tests/Bots/StoreService/WebTests.hs @@ -5,24 +5,24 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} -module Bots.BadgeService.WebTests (badgeWebTests) where +module Bots.StoreService.WebTests (badgeWebTests) where -import BadgeService.Catalog (catalogCurrency, defaultCatalog) -import BadgeService.Config (BTCPayConfig (..), ListenerConfig (..), PollConfig (..), ServiceConfig (..), SpeedPolicy (..), StripeConfig (..)) -import BadgeService.Orders (codeLifetime, settleOrder) -import BadgeService.Poller -import BadgeService.Providers -import BadgeService.Providers.BTCPay (btcpayProvider, listPageSize, maxListPages) -import BadgeService.Providers.Stripe (stripeProvider) -import BadgeService.Store (CreditedPurchase (..), FundingCredit (..), KeyPurchase (..), KeyRedemption (..), ManagedGroup (..), NewCodePurchase (..), NewStorePurchase (..), PaymentRebind (..), PurchaseSubscription (..), RevokeResult (..), appendLedgerPlan, createCodePurchase, createStorePurchase, getCodePurchaseForKey, getLedgerEntries, getLedgerTip, getManagedGroup, getMovedFromExpiry, getPurchaseByKey, getPurchaseSubscription, getStorePaymentCredit, insertBadgeCode, insertManagedGroup, insertSubscriptionCharge, markOwnerBootstrapped, rebindStorePayment, revokeCode) -import BadgeService.StoreReceipts (StoreCharge (..)) -import BadgeService.Store.Invoices -import BadgeService.Waiters (awaitStatus, newWaiters, publish, waitingCount) -import BadgeService.Web.Server -import Bots.BadgeService.BotTests (codeCounts, newPurchaseKeys) -import Bots.BadgeService.CatalogTests (WebOffer (..), WebPrice (..), parseCatalogSource) -import Bots.BadgeService.FakeBTCPay -import Bots.BadgeService.FakeStripe (FakeStripe (..), fakeIntentStatus, setIntentState, stripeEvent, stripeSigHeader, withFakeStripe) +import StoreService.Catalog (catalogCurrency, defaultCatalog) +import StoreService.Config (BTCPayConfig (..), ListenerConfig (..), PollConfig (..), ServiceConfig (..), SpeedPolicy (..), StripeConfig (..)) +import StoreService.Orders (codeLifetime, settleOrder) +import StoreService.Poller +import StoreService.Providers +import StoreService.Providers.BTCPay (btcpayProvider, listPageSize, maxListPages) +import StoreService.Providers.Stripe (stripeProvider) +import StoreService.Store (CreditedPurchase (..), FundingCredit (..), KeyPurchase (..), KeyRedemption (..), ManagedGroup (..), NewCodePurchase (..), NewStorePurchase (..), PaymentRebind (..), PurchaseSubscription (..), RevokeResult (..), appendLedgerPlan, createCodePurchase, createStorePurchase, getCodePurchaseForKey, getLedgerEntries, getLedgerTip, getManagedGroup, getMovedFromExpiry, getPurchaseByKey, getPurchaseSubscription, getStorePaymentCredit, insertBadgeCode, insertManagedGroup, insertSubscriptionCharge, markOwnerBootstrapped, rebindStorePayment, revokeCode) +import StoreService.StoreReceipts (StoreCharge (..)) +import StoreService.Store.Invoices +import StoreService.Waiters (awaitStatus, newWaiters, publish, waitingCount) +import StoreService.Web.Server +import Bots.StoreService.BotTests (codeCounts, newPurchaseKeys) +import Bots.StoreService.CatalogTests (WebOffer (..), WebPrice (..), parseCatalogSource) +import Bots.StoreService.FakeBTCPay +import Bots.StoreService.FakeStripe (FakeStripe (..), fakeIntentStatus, setIntentState, stripeEvent, stripeSigHeader, withFakeStripe) import Control.Concurrent (forkIO, threadDelay) import Control.Concurrent.Async (async, wait) import qualified Control.Concurrent.Async as Async @@ -64,7 +64,7 @@ import Network.HTTP.Types.Status (statusCode) import qualified Network.Wai.Handler.Warp as Warp import Simplex.Chat.Badges (BadgeCredential (..), BadgeInfo (..), BadgeMasterKey (..), BadgeType (..)) import Simplex.Chat.Badges.Ledger (addMonths, debitEntry, emptyEntry, grantEntry, issueEntry) -import Simplex.Chat.Badges.Service (BadgeOffer (..), BadgePrice (..), StatementCreditType (..), StatementDebitType (..), StatementEntry (..), SubscriptionState (..)) +import Simplex.Chat.StoreService (BadgeOffer (..), BadgePrice (..), StatementCreditType (..), StatementDebitType (..), StatementEntry (..), SubscriptionState (..)) import Simplex.Chat.Badges.Types (BadgeCodePaymentStatus (..), BadgeItemStatus (..), BadgeOfferId (..), BadgePriceId (..), OfferDiscount (..)) import Simplex.Chat.PaymentService.Types (CryptoCurrency (..), CurrencyAmount (..), InvoiceId (..), InvoiceStatus (..), PaymentProvider (..), PaymentStatus (..), ServicePaymentDestination (..), ServicePaymentMethod (..)) import Simplex.Messaging.Agent.Store.Common (DBStore (..), withConnection, withTransaction) @@ -85,12 +85,12 @@ import Text.Read (readMaybe) import UnliftIO.Temporary (withTempDirectory) #if defined(dbPostgres) -import BadgeService.Store.Postgres.Migrations (badgeServiceSchemaMigrations) +import StoreService.Store.Postgres.Migrations (storeServiceSchemaMigrations) import ChatClient (testDBConnstr) import Database.PostgreSQL.Simple (Only (..)) import qualified Simplex.Messaging.Agent.Store.Postgres.Migrations as Migrations #else -import BadgeService.Store.SQLite.Migrations (badgeServiceSchemaMigrations) +import StoreService.Store.SQLite.Migrations (storeServiceSchemaMigrations) import Data.String (fromString) import Database.SQLite.Simple (Only (..)) import qualified Database.SQLite.Simple as SQL @@ -102,7 +102,7 @@ import qualified Simplex.Messaging.Agent.Store.SQLite.Migrations as Migrations withServiceStore :: (DBStore -> IO a) -> IO a withServiceStore action = do n <- atomicModifyIORef' serviceSchemaCounter (\i -> (i + 1, i)) - Right st <- createDBStore (serviceDBOpts n) badgeServiceSchemaMigrations (MigrationConfig MCError Nothing) + Right st <- createDBStore (serviceDBOpts n) storeServiceSchemaMigrations (MigrationConfig MCError Nothing) action st `E.finally` closeDBStore st where serviceDBOpts :: Int -> DBOpts @@ -122,7 +122,7 @@ withServiceStore :: (DBStore -> IO a) -> IO a withServiceStore action = do createDirectoryIfMissing True "tests/tmp" withTempDirectory "tests/tmp" "badge-web" $ \dir -> do - Right st <- createDBStore (DBOpts (dir "badge_service_test.db") [] "" False True TQOff) badgeServiceSchemaMigrations (MigrationConfig MCError Nothing) + Right st <- createDBStore (DBOpts (dir "badge_service_test.db") [] "" False True TQOff) storeServiceSchemaMigrations (MigrationConfig MCError Nothing) action st `E.finally` closeDBStore st #endif @@ -141,7 +141,7 @@ columnsOf st table = withConnection st $ \db -> badgeWebTests :: Spec badgeWebTests = do - describe "badge service schema" $ do + describe "store service schema" $ do it "carries the service-only columns, and none of the subscription columns it never wrote" testServiceColumns it "refuses a duplicate provider_ref" testProviderRefUnique it "M20260918 adds the multi-use columns and the group table" testGroupOpsColumns @@ -149,7 +149,7 @@ badgeWebTests = do it "migrates all the way down and up again" testSchemaDownUpCycle it "rolls back only the group migration and re-applies it, keeping a code redeemed twice spent" testGroupOpsDownUp it "rolls back only the subscription migration, restoring the columns it dropped, and re-applies it" testSubscriptionsDownUp - describe "badge service store" $ do + describe "store service store" $ do it "writes the invoice, its code and their link atomically" testCreationIsAtomic it "newInvoiceId is 128 CSPRNG bits, base64url, and two calls differ" testNewInvoiceIdRandom it "codeHashExists is true for a hash already written" testCodeHashExists @@ -174,17 +174,17 @@ badgeWebTests = do it "finds a key's own purchase with its newest credential, and none for another key" testKeyPurchaseLookup it "gives concurrent claims exactly the code's uses" testMultiUseConcurrentClaimsUpToLimit it "refuses a second claim by the same key without using up a use" testSameKeyClaimsOnce - describe "badge service catalog seed" $ do + describe "store service catalog seed" $ do it "writes the compiled-in catalog into an empty database" testSeedWritesTheCatalog it "leaves exactly one row per id when the service starts twice" testSeedIsIdempotent it "leaves a price and an offer an operator withdrew withdrawn" testSeedNeverResurrectsAWithdrawnRow it "seeds exactly what web/src/catalog.ts compiles into the page" testSeedMatchesWebCatalog it "prices a btc checkout, and answers card provider_unavailable" testSeededCatalogSellsSomething - describe "BadgeService.Providers stub" $ do + describe "StoreService.Providers stub" $ do it "constructs a Provider record and records every call, in order" testStubProviderRecordsCalls it "makes pCreateInvoice fail on demand, so provider_unavailable is exercisable" testStubProviderCreateFailsOnDemand it "records nothing when the caller never reaches the provider" testStubProviderNotCalledWhenSkipped - describe "badge service web" $ do + describe "store service web" $ do it "serves the shell at / and a hashed asset under /assets" testServesTheBuild it "fills the shell's publishable key from the ini at boot" testShellCarriesPublishableKey it "caches by where the file is, not by how the request spelled it" testCachingFollowsTheResolvedPath @@ -215,7 +215,7 @@ badgeWebTests = do it "answers a hold from the row it read, not from the status it woke on" testHoldReportsTheRowNotTheWake it "answers a hold that timed out with a change nothing published" testHoldTimeoutReportsAnUnpublishedChange it "answers a handler exception with 500 internal, and keeps serving" testHandlerExceptionIsContained - describe "badge service settlement" $ do + describe "store service settlement" $ do it "settles an open invoice: paid, a settled payment row, and the code" testSettlesAnOpenInvoice it "settles an expired invoice, because late settlement is routine" testLateSettlementIsLegal it "records what arrived without moving an unsettled invoice" testFundedRecordsWithoutMoving @@ -235,7 +235,7 @@ badgeWebTests = do it "reports settledAt from the payment row, not from the invoice" testSettledAtIsThePaymentRow it "refuses a settlement instant the provider cannot have meant" testAbsurdSettledInstantIsRefused it "refuses a settlement instant in the future, as a millisecond clock gives" testFutureSettledInstantIsRefused - describe "badge service poller" $ do + describe "store service poller" $ do it "settles a payment with no webhook delivered anywhere" testSettlesWithNoWebhookAtAll it "reads only the invoices it is waiting on, and lists on the stray cadence" testPassReadsWhatItAwaits it "asks the provider nothing when it is waiting on nothing" testIdlePassAsksNothing @@ -272,7 +272,7 @@ badgeWebTests = do it "settles the rest of the pass around an invoice that throws" testOneBadInvoiceDoesNotStopThePass it "pages past a hundred open invoices, a request per hundred" testListPaginates it "stops paging at its ceiling rather than looping on a server that ignores take" testPagingStopsAtTheCeiling - describe "badge service webhook" $ do + describe "store service webhook" $ do it "verifies a real BTCPay signature over the bytes as received, and queues" testWebhookVerifiesARealSignature it "hands the adapter the raw body, byte for byte" testWebhookPassesTheRawBytes it "queues a read and answers 200 empty, reaching no provider" testWebhookQueuesARead @@ -284,7 +284,7 @@ badgeWebTests = do it "queues a read of an order once, however often it is hinted before being served" testReadHintQueuedOnce it "drops a hint rather than blocking when the queue is full" testWebhookDropsAHintWhenFull it "answers 200 rather than any 5xx when the adapter or the store throws" testWebhookNeverAnswers5xx - describe "badge service checkout" $ do + describe "store service checkout" $ do it "answers the checkout fields and writes the three rows" testCreateInvoice it "carries no code and no code hash, over the raw bytes" testCreateCarriesNoCode it "tells the provider xmr rather than the chain another request used" testXmrReachesTheProviderAsXmr @@ -298,12 +298,12 @@ badgeWebTests = do it "answers method card with provider_unavailable when no Stripe provider is configured" testCardUnconfigured503 it "answers a provider that failed to create with provider_unavailable, writing nothing" testProviderFailureWritesNothing it "refuses the sixth create in a minute, without reaching the provider" testCreateRateLimit - describe "badge service card" $ do + describe "store service card" $ do it "creates a Stripe PaymentIntent, carrying its clientSecret and a stripe invoice row" testCardCreatesSession it "cancels an overdue card order's intent at Stripe before expiring it" testCardSweepCancelsTheIntent it "derives the shown expiry from stripe.session_minutes, not the btcpay window" testCardExpiryFollowsSessionMinutes it "settles a card invoice from a signed payment_intent.succeeded and a pass" testCardWebhookSettles - describe "badge service cancel" $ do + describe "store service cancel" $ do it "expires the invoice here and invalidates it at the provider" testCancelClosesTheInvoiceAtBothEnds it "wakes a hold another tab is sitting on" testCancelWakesAHeldRequest it "refuses to cancel an invoice that is no longer open" testCancelIsRefusedOnceItIsNotOpen @@ -312,7 +312,7 @@ badgeWebTests = do it "expires an invoice a payment landed on while the provider was being told" testCancelExpiresAFundedInvoice it "answers an unknown id with the same 404 the read does" testCancelIsOpaqueForAnUnknownInvoice it "answers GET with 405 and Allow: POST" testCancelRefusesOtherMethods - describe "badge service scenarios" $ do + describe "store service scenarios" $ do it "buys a code: create, pay at BTCPay, one pass, paid" scenarioPaidPurchase it "wakes a wait held from before the settlement, within a second of it" scenarioHeldWaitWakes it "reports a partial payment and leaves the invoice open" scenarioPartPaymentIsReported @@ -360,19 +360,19 @@ runMigrations st = Migrations.run st Nothing True testSchemaDownUpCycle :: IO () testSchemaDownUpCycle = withServiceStore $ \st -> do - let downMigrations = mapMaybe toDownMigration badgeServiceSchemaMigrations - length downMigrations `shouldBe` length badgeServiceSchemaMigrations + let downMigrations = mapMaybe toDownMigration storeServiceSchemaMigrations + length downMigrations `shouldBe` length storeServiceSchemaMigrations runMigrations st $ MTRDown downMigrations columnsOf st "sx_badge_service_badge_codes" `shouldReturn` [] columnsOf st "sx_badge_service_group" `shouldReturn` [] columnsOf st "sx_badge_service_subscription_charges" `shouldReturn` [] - runMigrations st $ MTRUp badgeServiceSchemaMigrations + runMigrations st $ MTRUp storeServiceSchemaMigrations assertGroupOpsColumns st assertSubscriptionColumns st testSubscriptionsDownUp :: IO () testSubscriptionsDownUp = withServiceStore $ \st -> do - let subscriptions = [m | m@Migration {name = "20261012_badge_subscriptions"} <- badgeServiceSchemaMigrations] + let subscriptions = [m | m@Migration {name = "20261012_badge_subscriptions"} <- storeServiceSchemaMigrations] length subscriptions `shouldBe` 1 runMigrations st $ MTRDown (mapMaybe toDownMigration subscriptions) columnsOf st "sx_badge_service_subscription_charges" `shouldReturn` [] @@ -388,7 +388,7 @@ testGroupOpsDownUp = withServiceStore $ \st -> do now <- truncateToSecond <$> getCurrentTime let redeemedHash = digestFixture 44 unredeemedHash = digestFixture 45 - groupOps = [m | m@Migration {name = "20260918_badge_group_ops"} <- badgeServiceSchemaMigrations] + groupOps = [m | m@Migration {name = "20260918_badge_group_ops"} <- storeServiceSchemaMigrations] redeemed <- insertCode st redeemedHash CPSPaid 2 now void $ insertCode st unredeemedHash CPSPaid 1 now -- Two purchases of one code would break a down migration that restored the unique index. @@ -685,7 +685,7 @@ testSeedNeverResurrectsAWithdrawnRow = withServiceStore $ \st -> do testSeedMatchesWebCatalog :: IO () testSeedMatchesWebCatalog = withServiceStore $ \st -> do - src <- T.readFile "apps/simplex-badge-service/web/src/catalog.ts" + src <- T.readFile "apps/simplex-store-service/web/src/catalog.ts" (webPrices, webOffers) <- case parseCatalogSource src of Nothing -> failWith "could not parse CATALOG out of web/src/catalog.ts -- its shape has changed" Just parsed -> pure parsed @@ -1364,13 +1364,13 @@ testServesTheBuild = bounded "serves the build" $ withWebApp $ \_ client -> do statusOf missing `shouldBe` 404 builtSiteDir :: FilePath -builtSiteDir = "apps" "simplex-badge-service" "web" "dist" +builtSiteDir = "apps" "simplex-store-service" "web" "dist" testServesBuiltWebApp :: IO () testServesBuiltWebApp = bounded "built web app" $ withServiceStore $ \st -> do built <- doesFileExist (builtSiteDir "index.html") if not built - then pendingWith ("no web build at " <> builtSiteDir <> ": run `npm run build` in apps/simplex-badge-service/web") + then pendingWith ("no web build at " <> builtSiteDir <> ": run `npm run build` in apps/simplex-store-service/web") else withListener [] True holdMicros st (testServiceConfig builtSiteDir False) $ \_ client -> do shell <- webGet client "/" statusOf shell `shouldBe` 200 diff --git a/tests/Bots/BadgeService/WebUIMock.hs b/tests/Bots/StoreService/WebUIMock.hs similarity index 95% rename from tests/Bots/BadgeService/WebUIMock.hs rename to tests/Bots/StoreService/WebUIMock.hs index a401fd59b3..0d684bb826 100644 --- a/tests/Bots/BadgeService/WebUIMock.hs +++ b/tests/Bots/StoreService/WebUIMock.hs @@ -1,7 +1,7 @@ {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} -module Bots.BadgeService.WebUIMock +module Bots.StoreService.WebUIMock ( EphemeralWallet (..), newEphemeralWallet, redemptionCode, @@ -10,7 +10,7 @@ module Bots.BadgeService.WebUIMock ) where -import BadgeService.Names.Registration (RegisterIntent (..), Registration, registerIntentDigest) +import StoreService.Names.Registration (RegisterIntent (..), Registration, registerIntentDigest) import Control.Concurrent.STM (TVar) import Crypto.Random (ChaChaDRG) import Data.Text (Text) diff --git a/tests/Test.hs b/tests/Test.hs index 243b09d0c8..5ef133be82 100644 --- a/tests/Test.hs +++ b/tests/Test.hs @@ -3,17 +3,17 @@ {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE TupleSections #-} -import Bots.BadgeService.BTCPayTests -import Bots.BadgeService.BotTests -import Bots.BadgeService.CatalogTests -import Bots.BadgeService.ConfigTests -import Bots.BadgeService.GroupIntegrationTests -import Bots.BadgeService.GroupTests -import Bots.BadgeService.NameRegistrationTests -import Bots.BadgeService.StoreVerifierTests -import Bots.BadgeService.StripeTests -import Bots.BadgeService.WaitersTests -import Bots.BadgeService.WebTests +import Bots.StoreService.BTCPayTests +import Bots.StoreService.BotTests +import Bots.StoreService.CatalogTests +import Bots.StoreService.ConfigTests +import Bots.StoreService.GroupIntegrationTests +import Bots.StoreService.GroupTests +import Bots.StoreService.NameRegistrationTests +import Bots.StoreService.StoreVerifierTests +import Bots.StoreService.StripeTests +import Bots.StoreService.WaitersTests +import Bots.StoreService.WebTests import Bots.BroadcastTests import Bots.DirectoryTests import ChatClient @@ -79,7 +79,7 @@ main = do around tmpBracket $ describe "WebRTC encryption" webRTCTests #endif describe "Supporter badges" badgeTests - describe "SimpleX badge service" $ do + describe "SimpleX store service" $ do badgeConfigTests badgeWebTests badgeCatalogTests @@ -117,8 +117,8 @@ main = do describe "Wallet" walletTests xdescribe'' "SimpleX Broadcast bot" broadcastBotTests describe "SimpleX Directory service bot" directoryServiceTests - describe "SimpleX badge service e2e" $ do - badgeServiceTests + describe "SimpleX store service e2e" $ do + storeServiceTests describe "managed group" badgeGroupIntegrationTests describe "Remote session" remoteTests #if !defined(dbPostgres)