Pular para conteúdo

a. Visão geral

Neste lab

  • Troque o provedor de pagamento falso do lab 9 por um real, em sandbox: o modo de teste da Stripe, em que nenhum dinheiro se move.
  • Mantenha o contrato que o order enxerga: o payment continua respondendo AUTHORIZED ou DECLINED, atrás de uma interface Psp com duas implementações — a falsa (ainda o padrão) e a Stripe.
  • Receba os webhooks da Stripe, confira a assinatura deles, processe cada evento uma vez e deixe um webhook registrar a cobrança cuja resposta se perdeu.
  • Reconcilie os seus pagamentos com o provedor, a fonte da verdade.
  • Veja como o mesmo design recebe o Pix com o Mercado Pago.

O lab 9 ensinou o payment a sobreviver a um provedor lento ou fora do ar — contra um WireMock que responde o que roteirizamos. Um provedor de serviços de pagamento (PSP, payment service provider) de verdade acrescenta o que um falso não tem: uma conta e chaves, valores em centavos, cartões recusados que são respostas e não falhas, e um segundo canal — o provedor chama você de volta, depois, talvez duas vezes, para dizer o que realmente aconteceu. Este lab liga o BoxOffice ao sandbox da Stripe e trata tudo isso, sem gastar um centavo.

A história até aqui

Capítulo 10 da história da disciplina, o seu segundo lab, que amarra três fios. A aula 3 avisou que, entre máquinas, uma mensagem pode se perder ou se duplicar: um "comprar" repetido pode cobrar duas vezes. O lab 9 respondeu com uma chave de idempotência por pedido (order-<orderId>) contra um provedor falso e mostrou a outra face de um timeout: quando o cliente do lab 9 desiste depois de 1 s e 3 tentativas, a cobrança pode ter acontecido mesmo assim — num dia de provedor lento, o simulador abaixo deixa 133 de 1.000 checkouts em UNKNOWN. A aula 12 acrescenta que todo endpoint que a internet alcança precisa provar quem está chamando. Este lab liga o payment ao sandbox de um provedor real, transforma o UNKNOWN numa resposta conhecida com webhooks assinados e uma reconciliação e mede isso: cada checkout cobrado exatamente uma vez e zero divergências com o provedor.

Antes de começar

Tempo 3–4 horas
Você precisa de as ferramentas do lab 0; uma conta Stripe gratuita (um e-mail basta para o sandbox); jq e openssl (os dois vêm com o macOS e a maioria das distribuições Linux)
Diretório todo comando roda a partir da raiz do seu repositório boxoffice/
Custos zero: o sandbox (modo de teste) não move dinheiro e o serviço se recusa a subir com uma chave de produção
docker compose version        # v2.x
jq --version                  # jq-1.6+
openssl version               # any

Estado inicial — o fim do lab 13 (o lab 9 é a base deste: payment, order, Toxiproxy e o provedor falso psp):

boxoffice/ at the start of lab 14
📁 boxoffice/
├── YAML compose.yaml                     # psp (WireMock), toxiproxy, payment, order…
├── 📁 services/payment/                # lab 9: PaymentController, PaymentService, PspClient, V1__create_payments.sql
└── 📁 services/order/                  # lab 9: PaymentClient, Idempotency-Key "order-<orderId>"

Recupere o atraso

Pulou ou quebrou um lab? Baixe boxoffice-after-lab-13.zip, descompacte e entre em boxoffice. Este lab acrescenta Psp.java, StripePsp.java, StripeSignature.java, StripeWebhookController.java, Reconciliation.java, V2__stripe_events.sql, um teste de unidade e scripts/send-webhook.sh e substitui o compose.yaml e, em services/payment/, pom.xml, application.yaml, ChargeRequest.java, PaymentService.java e PspClient.java. Todos estão completos nesta página e em boxoffice-after-lab-14.zip.

Slides

Clique nos slides e use ← → para navegar; F abre em tela cheia e P abre a visão do apresentador, com as notas. Abrir os slides em uma nova aba

O que você vai construir

flowchart LR
    order["order<br/>chave order-&lt;id&gt;"]:::comp -->|"POST /payments<br/>(via Toxiproxy)"| payment["payment<br/>Psp: fake | stripe"]:::comp
    payment -->|"POST /v1/payment_intents<br/>Idempotency-Key, confirm=true"| stripe["sandbox da Stripe"]:::tech
    stripe -->|"payment_intent.succeeded<br/>(depois, talvez duas vezes)"| cli["stripe-cli<br/>listen --forward-to"]:::tech
    cli -->|"POST /webhooks/stripe<br/>Stripe-Signature"| payment
    payment -->|"GET /payments/reconcile<br/>consulta cada PaymentIntent"| stripe
Passo O que muda Você deve ver
1. Um sandbox uma conta Stripe, uma chave de teste no .env GET /v1/balance responde com "livemode": false
2. O adaptador Psp + StripePsp, o falso ainda é o padrão o payment compila; 5 testes passam
3. Cobrar PSP_PROVIDER=stripe AUTHORIZED com uma referência pi_…; a mesma chave, o mesmo pagamento; um cartão recusado é DECLINED
4. Webhooks assinatura, um evento uma vez, stripe-cli webhook evt_… → AUTHORIZED; uma repetição é duplicate; uma falsificação é 400
5. A resposta perdida uma cobrança que o payment nunca gravou o webhook a grava; pagar de novo confirma o pedido sem segunda cobrança
6. Reconciliar o nosso contra o da Stripe {"checked": N, "mismatches": []} — depois uma divergência, encontrada

1. Um sandbox da Stripe

  1. Crie uma conta em dashboard.stripe.com/register. Você não precisa ativar pagamentos: um sandbox (o ambiente de teste da Stripe) fica disponível na hora.
  2. No Dashboard, abra Developers → API keys do seu sandbox e copie a secret key: ela começa com sk_test_.
  3. Coloque-a no .env, na raiz do repositório — o Compose o lê e o .gitignore do lab 0 o mantém fora do Git:
.env
PSP_PROVIDER=stripe
STRIPE_SECRET_KEY=sk_test_...
git check-ignore .env                  # prints ".env": it will never be committed
curl -s https://api.stripe.com/v1/balance -u "$(grep '^STRIPE_SECRET_KEY=' .env | cut -d= -f2-):" | jq '{object, livemode}'

Você deve ver {"object": "balance", "livemode": false}. livemode: false é o sandbox: nada que você fizer aqui cobra um cartão de verdade.

Uma secret key é uma senha para o seu dinheiro

Nunca a cole em código, num commit, num print de tela ou num chat. Se ela vazar, troque-a no Dashboard (Developers → API keys → Roll key). O StripePsp recusa qualquer chave que não comece com sk_test_: nesta disciplina, uma chave de produção é um bug.

2. O adaptador: uma interface, dois provedores

O order não pode saber qual provedor está atrás do payment — esse é o ponto do adaptador do lab 9. A nova interface Psp tem duas implementações, escolhidas por boxoffice.psp.provider: o PspClient do lab 9 (ainda o padrão, para que os experimentos de caos e o CI continuem funcionando sem chaves) e o StripePsp.

services/payment/src/main/java/boxoffice/payment/Psp.java
package boxoffice.payment;

import java.math.BigDecimal;
import java.util.UUID;

/** A payment service provider: the fake of lab 9 or the Stripe sandbox. */
public interface Psp {

    /** id: the provider's reference; approved: false when the card was declined. */
    record Charge(String id, boolean approved) {
    }

    /** Charges once per idempotency key, however many times it is called. */
    Charge charge(String idempotencyKey, BigDecimal amount, UUID orderId, String paymentMethod);
}
services/payment/src/main/java/boxoffice/payment/StripePsp.java
package boxoffice.payment;

import java.math.BigDecimal;
import java.net.http.HttpClient;
import java.time.Duration;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.MediaType;
import org.springframework.http.client.JdkClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClient;

/** The Stripe sandbox: one PaymentIntent per order, created and confirmed on the server. */
@Component
@ConditionalOnProperty(name = "boxoffice.psp.provider", havingValue = "stripe")
public class StripePsp implements Psp {

    /** The fields of a PaymentIntent this service reads. */
    record Intent(String id, String status) {
    }

    /** Stripe's error body: a declined card comes back as HTTP 402 with type card_error. */
    record ErrorBody(Error error) {
        record Error(String type, String code, String decline_code, String message, Intent payment_intent) {
        }
    }

    private final RestClient http;
    private final String currency;
    private final String defaultMethod;

    public StripePsp(RestClient.Builder builder,
                     @Value("${boxoffice.stripe.url}") String url,
                     @Value("${boxoffice.stripe.secret-key}") String secretKey,
                     @Value("${boxoffice.stripe.currency}") String currency,
                     @Value("${boxoffice.stripe.payment-method}") String defaultMethod,
                     @Value("${boxoffice.psp.connect-timeout}") Duration connectTimeout,
                     @Value("${boxoffice.psp.read-timeout}") Duration readTimeout) {
        if (!secretKey.startsWith("sk_test_")) {
            // a live key (sk_live_…) moves real money: this lab refuses to start with one
            throw new IllegalStateException("STRIPE_SECRET_KEY must be a test key (sk_test_…)");
        }
        // the JDK HttpClient keeps the body of an error answer (HttpURLConnection may drop it)
        JdkClientHttpRequestFactory factory = new JdkClientHttpRequestFactory(
                HttpClient.newBuilder().connectTimeout(connectTimeout).build());
        factory.setReadTimeout(readTimeout);
        this.http = builder.baseUrl(url)
                .defaultHeader("Authorization", "Bearer " + secretKey)
                .requestFactory(factory)
                .build();
        this.currency = currency;
        this.defaultMethod = defaultMethod;
    }

    @Override
    public Charge charge(String idempotencyKey, BigDecimal amount, UUID orderId, String paymentMethod) {
        MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
        form.add("amount", String.valueOf(amount.movePointRight(2).longValueExact())); // centavos
        form.add("currency", currency);
        form.add("payment_method", paymentMethod != null ? paymentMethod : defaultMethod);
        form.add("confirm", "true");                                   // charge now, on the server
        form.add("automatic_payment_methods[enabled]", "true");
        form.add("automatic_payment_methods[allow_redirects]", "never"); // no browser to redirect
        form.add("metadata[order_id]", orderId.toString());
        form.add("metadata[idempotency_key]", idempotencyKey);         // lets a webhook find the payment
        return http.post()
                .uri("/v1/payment_intents")
                .header("Idempotency-Key", idempotencyKey)             // Stripe charges once per key
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .body(form)
                .exchange((request, response) -> {
                    if (response.getStatusCode().is2xxSuccessful()) {
                        Intent intent = response.bodyTo(Intent.class);
                        return new Charge(intent.id(), "succeeded".equals(intent.status()));
                    }
                    ErrorBody body = response.bodyTo(ErrorBody.class);
                    if (response.getStatusCode().value() == 402 && body != null && body.error().payment_intent() != null) {
                        return new Charge(body.error().payment_intent().id(), false); // declined: an answer, not a failure
                    }
                    String message = body != null ? body.error().message() : response.getStatusText();
                    throw new IllegalStateException("Stripe answered " + response.getStatusCode().value() + ": " + message);
                });
    }

    /** The provider's view of one PaymentIntent: the source of truth for reconciliation. */
    public Intent retrieve(String intentId) {
        return http.get().uri("/v1/payment_intents/{id}", intentId).retrieve().body(Intent.class);
    }
}
services/payment/src/main/java/boxoffice/payment/PspClient.java
package boxoffice.payment;

import java.math.BigDecimal;
import java.time.Duration;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;

/** Lab 9's fake provider (WireMock behind Toxiproxy): still the default, so the chaos experiments keep working. */
@Component
@ConditionalOnProperty(name = "boxoffice.psp.provider", havingValue = "fake", matchIfMissing = true)
public class PspClient implements Psp {

    record ChargeBody(BigDecimal amount, String currency, String reference) {
    }

    record ChargeOut(String id, String status) {
    }

    private final RestClient http;

    public PspClient(RestClient.Builder builder,
                     @Value("${boxoffice.psp.url}") String url,
                     @Value("${boxoffice.psp.connect-timeout}") Duration connectTimeout,
                     @Value("${boxoffice.psp.read-timeout}") Duration readTimeout) {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(connectTimeout); // time to open the TCP connection
        factory.setReadTimeout(readTimeout);       // max silence while waiting for the response
        this.http = builder.baseUrl(url).requestFactory(factory).build();
    }

    /** The provider deduplicates by Idempotency-Key, like real PSPs do. */
    @Override
    public Charge charge(String idempotencyKey, BigDecimal amount, UUID orderId, String paymentMethod) {
        ChargeOut out = http.post()
                .uri("/v1/charges")
                .header("Idempotency-Key", idempotencyKey)
                .body(new ChargeBody(amount, "BRL", "order-" + orderId))
                .retrieve()
                .body(ChargeOut.class);
        return new Charge(out.id(), "approved".equals(out.status()));
    }
}
services/payment/src/main/java/boxoffice/payment/ChargeRequest.java
package boxoffice.payment;

import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import java.math.BigDecimal;
import java.util.UUID;

/** paymentMethod: optional, a Stripe test payment method (pm_card_visa, pm_card_visa_chargeDeclined…). */
public record ChargeRequest(@NotNull UUID orderId, @NotNull @Positive BigDecimal amount, String paymentMethod) {
}
services/payment/src/main/resources/application.yaml
server:
  port: 8085

spring:
  application:
    name: payment
  mvc:
    problemdetails:
      enabled: true
  datasource:
    url: jdbc:postgresql://${DB_HOST:db}:${DB_PORT:5432}/${DB_NAME:boxoffice}?currentSchema=payment
    username: ${DB_USER:boxoffice}
    password: ${DB_PASSWORD:boxoffice}
  flyway:
    schemas: payment

boxoffice:
  psp:
    provider: ${PSP_PROVIDER:fake}        # fake (lab 9's WireMock) | stripe (the sandbox, lab 14)
    url: ${PSP_URL:http://psp:8080}
    connect-timeout: 500ms
    read-timeout: ${PSP_READ_TIMEOUT:2s}
  stripe:
    url: https://api.stripe.com
    secret-key: ${STRIPE_SECRET_KEY:}             # sk_test_…: from the environment, never from Git
    webhook-secret: ${STRIPE_WEBHOOK_SECRET:}     # whsec_…: printed by stripe listen
    currency: ${STRIPE_CURRENCY:brl}
    payment-method: ${STRIPE_PAYMENT_METHOD:pm_card_visa}   # a test card when the request names none
    tolerance: 300s                               # max age of a webhook signature

management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics
  endpoint:
    health:
      probes:
        enabled: true
services/payment/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>4.1.1</version>
        <relativePath/>
    </parent>

    <groupId>boxoffice</groupId>
    <artifactId>payment</artifactId>
    <version>1.0.0</version>

    <properties>
        <java.version>21</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webmvc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-restclient</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-flyway</artifactId>
        </dependency>
        <dependency>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-database-postgresql</artifactId>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>app</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

O que o StripePsp faz, e por quê:

  • Um PaymentIntent por pedido, confirmado no servidor. confirm=true cobra na hora com o meio de pagamento de teste (pm_card_visa por padrão — num checkout real, o Stripe.js no navegador transforma o cartão num id desses, de modo que números de cartão nunca tocam o BoxOffice). allow_redirects=never: não há navegador para mandar a uma página do banco.
  • Valores em centavos. R$ 350,00 é amount=35000; movePointRight(2).longValueExact() falha alto diante de uma fração de centavo em vez de arredondar dinheiro.
  • A mesma Idempotency-Key da tabela do próprio payment (order-<orderId>, vinda do order). A Stripe guarda o resultado do primeiro pedido com uma chave e o repete para todo retry com a mesma chave; um retry depois de uma queda entre "a Stripe cobrou" e "nós gravamos" não consegue cobrar duas vezes.
  • Um cartão recusado é uma resposta. A Stripe devolve HTTP 402 com type: card_error e o PaymentIntent; o payment registra DECLINED. Todo o resto (401, 5xx, um timeout) é uma exceção: o retry, o breaker e o fallback do lab 9 no order tratam dela.
  • Metadados order_id e idempotency_key viajam com o PaymentIntent: o webhook do passo 4 os usa para encontrar — ou criar — o pagamento.

O PaymentService agora pergunta à interface Psp em vez do PspClient; o código completo dele está no passo 4. Reconstrua o payment e rode os testes dele:

docker compose build payment                                   # the Dockerfile runs mvn package -DskipTests
docker run --rm -v "$PWD/services/payment":/src -w /src maven:3.9-eclipse-temurin-21 mvn -B -q test

Você deve ver Tests run: 5, Failures: 0 para o StripeSignatureTest (passo 4).

3. Cobre no sandbox

O compose.yaml passa as novas variáveis ao payment (e acrescenta o stripe-cli, usado no passo 4):

compose.yaml
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
name: boxoffice

# lab 8: OpenTelemetry settings shared by every Java service (merged into each "environment")
x-otel: &otel
  JAVA_TOOL_OPTIONS: -javaagent:/otel/opentelemetry-javaagent.jar
  OTEL_JAVAAGENT_ENABLED: ${OTEL_ON:-true}          # false = same image, agent off
  OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-lgtm:4318
  OTEL_METRIC_EXPORT_INTERVAL: "10000"              # 10 s instead of 60 s
  OTEL_RESOURCE_ATTRIBUTES: service.namespace=boxoffice,deployment.environment.name=local
  OTEL_TRACES_SAMPLER: ${OTEL_TRACES_SAMPLER:-parentbased_always_on}
  OTEL_TRACES_SAMPLER_ARG: ${OTEL_TRACES_SAMPLER_ARG:-1.0}
  LOGGING_PATTERN_CORRELATION: "[%X{trace_id:-},%X{span_id:-}] "   # trace id in console logs

# settings shared by the three catalog replicas (a YAML anchor)
x-catalog: &catalog
  build: ./services/catalog
  image: boxoffice-catalog
  volumes:
    - ./infra/otel:/otel:ro          # lab 8: the Java agent
  environment:
    <<: *otel
    OTEL_SERVICE_NAME: catalog       # three replicas, ONE service
    DB_HOST: db
    DB_PORT: 5432
    DB_NAME: ${DB_NAME:-boxoffice}
    DB_USER: ${DB_USER:-boxoffice}
    DB_PASSWORD: ${DB_PASSWORD:-boxoffice}
    DB_POOL_SIZE: ${DB_POOL_SIZE:-10}
    REDIS_HOST: redis
    REDIS_PORT: 6379
    CACHE_ENABLED: ${CACHE_ENABLED:-true}
    CACHE_TTL_EVENT: ${CACHE_TTL_EVENT:-60s}
    CACHE_TTL_LIST: ${CACHE_TTL_LIST:-10s}
    CACHE_STAMPEDE_PROTECTION: ${CACHE_STAMPEDE_PROTECTION:-false}
  depends_on:
    db:
      condition: service_healthy
    redis:
      condition: service_healthy
  deploy:
    resources:
      limits:
        cpus: "1.0"
        memory: 768M
  healthcheck:
    test: ["CMD-SHELL", "wget -qO- http://localhost:8082/actuator/health/readiness || exit 1"]
    interval: 10s
    timeout: 3s
    start_period: 120s       # lab 8: with the agent, JVMs starting together need up to ~90 s
    retries: 3

services:

  db:
    image: pgvector/pgvector:0.8.7-pg17-trixie   # lab 12: PostgreSQL 17 + the pgvector extension
    command: ["postgres", "-c", "max_connections=${DB_MAX_CONNECTIONS:-100}"]
    environment:
      POSTGRES_DB: ${DB_NAME:-boxoffice}
      POSTGRES_USER: ${DB_USER:-boxoffice}
      POSTGRES_PASSWORD: ${DB_PASSWORD:-boxoffice}
      REPLICATION_PASSWORD: ${REPLICATION_PASSWORD:-replicator}
    ports:
      - "5432:5432"
    volumes:
      - db-data:/var/lib/postgresql/data
      # runs only when the volume is new: creates the "replicator" user
      - ./infra/postgres/10-replication.sh:/docker-entrypoint-initdb.d/10-replication.sh:ro
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
      interval: 5s
      timeout: 3s
      retries: 10

  # read-only streaming replica of db (hot standby)
  db-replica:
    image: pgvector/pgvector:0.8.7-pg17-trixie   # lab 12: PostgreSQL 17 + the pgvector extension
    user: postgres
    entrypoint: ["/usr/local/bin/replica-entrypoint.sh"]
    environment:
      PGPASSWORD: ${REPLICATION_PASSWORD:-replicator}     # used by pg_basebackup
      REPLICA_DELAY: ${REPLICA_DELAY:-0}                   # e.g. 2s: artificial lag
    ports:
      - "5433:5432"
    volumes:
      - replica-data:/var/lib/postgresql/data
      - ./infra/postgres/replica-entrypoint.sh:/usr/local/bin/replica-entrypoint.sh:ro
    depends_on:
      db:
        condition: service_healthy
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U boxoffice -d boxoffice"]
      interval: 5s
      timeout: 3s
      retries: 20

  pgbouncer:
    image: edoburu/pgbouncer:v1.26.0-p0
    ports:
      - "6432:6432"
    volumes:
      - ./infra/pgbouncer/pgbouncer.ini:/etc/pgbouncer/pgbouncer.ini:ro
      - ./infra/pgbouncer/userlist.txt:/etc/pgbouncer/userlist.txt:ro
    depends_on:
      db:
        condition: service_healthy

  redis:
    image: redis:8-alpine
    # a pure cache: bounded memory, evict least-recently-used keys, no persistence
    command: ["redis-server", "--maxmemory", "256mb", "--maxmemory-policy", "allkeys-lru",
              "--save", "", "--appendonly", "no"]
    ports:
      - "6379:6379"
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 10

  # three identical replicas; no "ports:" — only the edge is reachable from outside
  catalog-1:
    <<: *catalog
    hostname: catalog-1
  catalog-2:
    <<: *catalog
    hostname: catalog-2
  catalog-3:
    <<: *catalog
    hostname: catalog-3

  inventory:
    build: ./services/inventory
    volumes:
      - ./infra/otel:/otel:ro
    environment:
      <<: *otel
      OTEL_SERVICE_NAME: inventory
      DB_HOST: ${INVENTORY_DB_HOST:-pgbouncer}      # writes go through PgBouncer...
      DB_PORT: ${INVENTORY_DB_PORT:-6432}
      DB_MIGRATION_HOST: db                         # ...migrations straight to the primary
      DB_REPLICA_HOST: ${DB_REPLICA_HOST:-db-replica}
      DB_REPLICA_PORT: 5432
      DB_NAME: ${DB_NAME:-boxoffice}
      DB_USER: ${DB_USER:-boxoffice}
      DB_PASSWORD: ${DB_PASSWORD:-boxoffice}
      DB_POOL_SIZE: ${INVENTORY_POOL_SIZE:-20}
      INVENTORY_LOCKING: ${INVENTORY_LOCKING:-pessimistic}
      INVENTORY_HOLD_TTL: ${INVENTORY_HOLD_TTL:-PT10M}
    ports:
      - "8083:8083"            # published for experiments; clients go through the edge
    depends_on:
      db:
        condition: service_healthy
      db-replica:
        condition: service_healthy
      pgbouncer:
        condition: service_started
    deploy:
      resources:
        limits:
          cpus: "1.0"
          memory: 768M
    healthcheck:
      test: ["CMD-SHELL", "wget -qO- http://localhost:8083/actuator/health/readiness || exit 1"]
      interval: 10s
      timeout: 3s
      start_period: 120s
      retries: 3

  auth:
    build: ./services/auth
    volumes:
      - ./infra/otel:/otel:ro
    environment:
      <<: *otel
      OTEL_SERVICE_NAME: auth
      DB_HOST: db
      DB_PORT: 5432
      DB_NAME: ${DB_NAME:-boxoffice}
      DB_USER: ${DB_USER:-boxoffice}
      DB_PASSWORD: ${DB_PASSWORD:-boxoffice}
      JWT_ISSUER: ${JWT_ISSUER:-boxoffice-auth}
      JWT_TTL: ${JWT_TTL:-PT1H}
      ADMIN_EMAIL: ${ADMIN_EMAIL:-admin@boxoffice.dev}
      ADMIN_PASSWORD: ${ADMIN_PASSWORD:-boxoffice-admin}
    depends_on:
      db:
        condition: service_healthy
    deploy:
      resources:
        limits:
          cpus: "1.0"
          memory: 768M
    healthcheck:
      test: ["CMD-SHELL", "wget -qO- http://localhost:8081/actuator/health/readiness || exit 1"]
      interval: 10s
      timeout: 3s
      start_period: 120s
      retries: 3

  gateway:
    build: ./services/gateway
    volumes:
      - ./infra/otel:/otel:ro
    environment:
      <<: *otel
      OTEL_SERVICE_NAME: gateway
      AUTH_URL: http://auth:8081
      INVENTORY_URL: http://inventory:8083
      AUTH_JWKS_URI: http://auth:8081/auth/.well-known/jwks.json
      JWT_ISSUER: ${JWT_ISSUER:-boxoffice-auth}
    ports:
      - "8080:8080"          # published for experiments; clients use the edge (port 80)
    depends_on:
      - auth
      - inventory
      - catalog-1
      - catalog-2
      - catalog-3
    deploy:
      resources:
        limits:
          cpus: "1.0"
          memory: 768M
    healthcheck:
      test: ["CMD-SHELL", "wget -qO- http://localhost:8080/actuator/health/readiness || exit 1"]
      interval: 10s
      timeout: 3s
      start_period: 120s
      retries: 3

  edge:
    image: nginx:1.30-alpine
    ports:
      - "80:80"
    volumes:
      - ./infra/nginx/nginx.conf:/etc/nginx/nginx.conf:ro
    depends_on:
      - gateway

  # ---- lab 7: Kafka (KRaft), Kafka UI, Mailpit, order and notification ----

  kafka:
    image: apache/kafka:4.3.1
    hostname: kafka
    ports:
      - "9094:9094"
    environment:
      KAFKA_NODE_ID: 1
      KAFKA_PROCESS_ROLES: broker,controller
      KAFKA_CONTROLLER_QUORUM_VOTERS: 1@kafka:9093
      KAFKA_LISTENERS: PLAINTEXT://:9092,CONTROLLER://:9093,EXTERNAL://:9094
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092,EXTERNAL://localhost:9094
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,CONTROLLER:PLAINTEXT,EXTERNAL:PLAINTEXT
      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      KAFKA_AUTO_CREATE_TOPICS_ENABLE: "false"
    healthcheck:
      test: ["CMD-SHELL", "/opt/kafka/bin/kafka-broker-api-versions.sh --bootstrap-server localhost:9092 > /dev/null 2>&1"]
      interval: 10s
      timeout: 10s
      start_period: 60s      # a busy laptop can take a minute to start the broker
      retries: 20

  kafka-init:
    image: apache/kafka:4.3.1
    depends_on:
      kafka:
        condition: service_healthy
    entrypoint: ["/bin/sh", "-c"]
    command:
      - |
        /opt/kafka/bin/kafka-topics.sh --bootstrap-server kafka:9092 --create --if-not-exists \
          --topic order-events --partitions 6 --replication-factor 1 &&
        /opt/kafka/bin/kafka-topics.sh --bootstrap-server kafka:9092 --create --if-not-exists \
          --topic order-events-dlt --partitions 6 --replication-factor 1
    restart: "no"

  kafka-ui:
    image: kafbat/kafka-ui:v1.5.0
    depends_on:
      kafka:
        condition: service_healthy
    ports:
      - "8089:8080"
    environment:
      KAFKA_CLUSTERS_0_NAME: boxoffice
      KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: kafka:9092

  mailpit:
    image: axllent/mailpit:v1.31
    ports:
      - "8025:8025"
      - "1025:1025"

  order:
    build: ./services/order
    volumes:
      - ./infra/otel:/otel:ro
    environment:
      <<: *otel
      OTEL_SERVICE_NAME: order
      DB_HOST: db
      DB_PORT: 5432
      DB_NAME: ${DB_NAME:-boxoffice}
      DB_USER: ${DB_USER:-boxoffice}
      DB_PASSWORD: ${DB_PASSWORD:-boxoffice}
      REDIS_HOST: redis
      KAFKA_BOOTSTRAP_SERVERS: kafka:9092
      NOTIFICATION_URL: http://notification:8086
      PAYMENT_URL: http://toxiproxy:18085            # lab 9: through Toxiproxy, not payment:8085
      PAYMENT_RESILIENCE: ${PAYMENT_RESILIENCE:-true}
      PAYMENT_READ_TIMEOUT: ${PAYMENT_READ_TIMEOUT:-1s}
      PAYMENT_RETRY_ATTEMPTS: ${PAYMENT_RETRY_ATTEMPTS:-3}
      PAYMENT_BULKHEAD: ${PAYMENT_BULKHEAD:-10}
      NOTIFY_MODE: ${NOTIFY_MODE:-outbox}            # outbox (after) | sync (before)
      ADMIT_PER_SECOND: ${ADMIT_PER_SECOND:-20}      # waiting-room admission rate
    ports:
      - "8084:8084"
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_healthy
      kafka-init:
        condition: service_completed_successfully
    deploy:
      resources:
        limits:
          cpus: "1.0"
          memory: 768M
    healthcheck:
      test: ["CMD-SHELL", "wget -qO- http://localhost:8084/actuator/health/readiness || exit 1"]
      interval: 10s
      timeout: 3s
      start_period: 120s
      retries: 3

  notification:
    build: ./services/notification
    volumes:
      - ./infra/otel:/otel:ro
    environment:
      <<: *otel
      OTEL_SERVICE_NAME: notification
      DB_HOST: db
      DB_PORT: 5432
      DB_NAME: ${DB_NAME:-boxoffice}
      DB_USER: ${DB_USER:-boxoffice}
      DB_PASSWORD: ${DB_PASSWORD:-boxoffice}
      KAFKA_BOOTSTRAP_SERVERS: kafka:9092
      MAIL_HOST: mailpit
      NOTIFY_CONCURRENCY: ${NOTIFY_CONCURRENCY:-3}   # consumer threads (max useful: 6 partitions)
      EMAIL_LATENCY: ${EMAIL_LATENCY:-50ms}          # simulated e-mail provider latency
      NOTIFY_IDEMPOTENT: ${NOTIFY_IDEMPOTENT:-true}  # false = no dedupe (to see duplicates)
    ports:
      - "8086:8086"
    depends_on:
      db:
        condition: service_healthy
      mailpit:
        condition: service_started
      kafka-init:
        condition: service_completed_successfully
    deploy:
      resources:
        limits:
          cpus: "1.0"
          memory: 768M
    healthcheck:
      test: ["CMD-SHELL", "wget -qO- http://localhost:8086/actuator/health/readiness || exit 1"]
      interval: 10s
      timeout: 3s
      start_period: 120s
      retries: 3

  # ---- lab 8: observability backend (Grafana, Prometheus, Tempo, Loki, OTel Collector) ----

  otel-lgtm:
    image: grafana/otel-lgtm:0.37.0
    ports:
      - "3000:3000"   # Grafana (no login)
      - "4317:4317"   # OTLP gRPC
      - "4318:4318"   # OTLP HTTP
    volumes:
      - ./infra/grafana/dashboards.yaml:/otel-lgtm/grafana/conf/provisioning/dashboards/boxoffice.yaml:ro
      - ./infra/grafana/dashboards:/otel-lgtm/boxoffice-dashboards:ro
      - ./infra/grafana/alerting:/otel-lgtm/grafana/conf/provisioning/alerting:ro

  # ---- lab 9: payment adapter, fake provider and fault injection ----

  psp:
    image: wiremock/wiremock:3.13.2
    volumes:
      - ./infra/psp:/home/wiremock:ro

  toxiproxy:
    image: ghcr.io/shopify/toxiproxy:2.13.0
    command: ["-host=0.0.0.0", "-config=/config/toxiproxy.json"]
    volumes:
      - ./infra/toxiproxy/toxiproxy.json:/config/toxiproxy.json:ro
    ports:
      - "8474:8474"

  payment:
    build: ./services/payment
    volumes:
      - ./infra/otel:/otel:ro
    environment:
      <<: *otel
      OTEL_SERVICE_NAME: payment
      DB_HOST: db
      DB_PORT: 5432
      DB_NAME: ${DB_NAME:-boxoffice}
      DB_USER: ${DB_USER:-boxoffice}
      DB_PASSWORD: ${DB_PASSWORD:-boxoffice}
      PSP_URL: http://toxiproxy:18095                 # the provider, through Toxiproxy
      PSP_PROVIDER: ${PSP_PROVIDER:-fake}             # lab 14: fake (lab 9) | stripe (the sandbox)
      STRIPE_SECRET_KEY: ${STRIPE_SECRET_KEY:-}       # sk_test_…: from your shell or .env, never committed
      STRIPE_WEBHOOK_SECRET: ${STRIPE_WEBHOOK_SECRET:-}
      STRIPE_CURRENCY: ${STRIPE_CURRENCY:-brl}
    ports:
      - "8085:8085"
    depends_on:
      db:
        condition: service_healthy
      toxiproxy:
        condition: service_started
      psp:
        condition: service_started
    deploy:
      resources:
        limits:
          cpus: "1.0"
          memory: 768M
    healthcheck:
      test: ["CMD-SHELL", "wget -qO- http://localhost:8085/actuator/health/readiness || exit 1"]
      interval: 10s
      timeout: 3s
      start_period: 120s
      retries: 3

  # ---- lab 12: AI assistant (FastAPI + LiteLLM + pgvector) and a local LLM ----

  stripe-cli:                    # lab 14: forwards the sandbox's webhooks to payment
    image: stripe/stripe-cli:v1.55.11
    profiles: ["stripe"]           # only with --profile stripe
    environment:
      STRIPE_API_KEY: ${STRIPE_SECRET_KEY:-}      # the CLI reads its key from STRIPE_API_KEY
    command: ["listen",
              "--events", "payment_intent.succeeded,payment_intent.payment_failed",
              "--forward-to", "http://payment:8085/webhooks/stripe"]
    depends_on:
      payment:
        condition: service_healthy

  ollama:
    image: ollama/ollama:0.40.6
    ports:
      - "11434:11434"
    volumes:
      - ollama-models:/root/.ollama      # models survive restarts (about 1.3 GB)
    healthcheck:                         # ollama-init must wait for the server, not just the container
      test: ["CMD", "ollama", "list"]
      interval: 5s
      timeout: 5s
      retries: 12

  # one-shot: download the chat model and the embedding model, then exit
  ollama-init:
    image: ollama/ollama:0.40.6
    environment:
      OLLAMA_HOST: ollama:11434
    entrypoint: ["/bin/sh", "-c"]
    command:
      - |
        ollama pull ${LOCAL_MODEL_TAG:-qwen2.5:1.5b} && ollama pull nomic-embed-text
    depends_on:
      ollama:
        condition: service_healthy
    restart: "no"

  assistant:
    build: ./services/assistant
    environment:
      DB_HOST: db
      DB_PORT: 5432
      DB_NAME: ${DB_NAME:-boxoffice}
      DB_USER: ${DB_USER:-boxoffice}
      DB_PASSWORD: ${DB_PASSWORD:-boxoffice}
      OLLAMA_URL: ${OLLAMA_URL:-http://ollama:11434}   # macOS: http://host.docker.internal:11434 (native Ollama)
      LOCAL_MODEL: ollama_chat/${LOCAL_MODEL_TAG:-qwen2.5:1.5b}
      CATALOG_URL: http://gateway:8080                  # GET /catalog/** is public at the gateway
      ORDER_URL: http://order:8084
      ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-}          # optional: empty = local model only
      OTEL_SERVICE_NAME: assistant
      OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-lgtm:4318
      OTEL_METRIC_EXPORT_INTERVAL: "10000"
      OTEL_RESOURCE_ATTRIBUTES: service.namespace=boxoffice,deployment.environment.name=local
    ports:
      - "8088:8088"
    extra_hosts:
      - "host.docker.internal:host-gateway"             # reach a native Ollama on the host
    depends_on:
      db:
        condition: service_healthy
    deploy:
      resources:
        limits:
          cpus: "1.0"
          memory: 1G
    healthcheck:
      test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8088/assistant/health')"]
      interval: 10s
      timeout: 5s
      start_period: 30s
      retries: 3

volumes:
  db-data:
  replica-data:
  ollama-models:

Suba o payment com o provedor Stripe (o .env define PSP_PROVIDER=stripe) e cobre direto nele, como no lab 9:

docker compose up -d --build --wait payment
curl -s -w '\n%{http_code}\n' -X POST localhost:8085/payments -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: sandbox-1' -d '{"orderId":"5b0c2f9e-7d0a-4f43-9a55-1c1c2c8f8e10","amount":350.00}'

Você deve ver 201 e "status":"AUTHORIZED","providerRef":"pi_…". No Dashboard (Payments), um pagamento de R$ 350,00 mostra os metadados order_id e idempotency_key. Depois:

  • O mesmo pedido de novo: 200, o mesmo id e o mesmo providerRef — e ainda um único pagamento no Dashboard.
  • Um cartão recusado, com uma chave nova: acrescente "paymentMethod":"pm_card_visa_chargeDeclined" ao corpo e use Idempotency-Key: sandbox-2. Você deve ver 201 com "status":"DECLINED"; pm_card_visa_chargeDeclinedInsufficientFunds também recusa, por outro motivo (os dois são meios de pagamento de teste da Stripe).
  • De ponta a ponta, pelo order e pelo Toxiproxy, como no lab 9:
ID=$(curl -s -X POST localhost:8084/orders -H 'Content-Type: application/json' \
  -d '{"showId":"show-9","holdId":"hold-sandbox-1","customerEmail":"bia@example.com","amount":350.00}' | jq -r .id)
curl -s -X POST localhost:8084/orders/$ID/pay | jq '{id, status}'

Você deve ver "status":"CONFIRMED". Se o primeiro pay responder 503, a Stripe demorou mais que o read timeout de 1 s do order: o payment terminou mesmo assim e gravou a cobrança, então chamar pay de novo confirma o pedido com o mesmo PaymentIntent — a resposta perdida do passo 5, por acidente.

4. Webhooks: o provedor conta depois

Uma resposta síncrona pode se perder; a Stripe também chama você de volta com um evento a cada mudança de um PaymentIntent. No sandbox, os eventos são reenviados três vezes em poucas horas se o seu endpoint não responder 2xx; o mesmo evento pode chegar mais de uma vez e os eventos podem chegar fora de ordem. Por isso o endpoint precisa: provar que a chamada vem da Stripe, processar cada evento uma vez e responder rápido.

services/payment/src/main/java/boxoffice/payment/StripeWebhookController.java
package boxoffice.payment;

import java.time.Clock;
import java.time.Duration;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import tools.jackson.databind.ObjectMapper;

/** Stripe tells us what happened, later and maybe twice: the webhook is the source of truth. */
@RestController
@ConditionalOnProperty(name = "boxoffice.psp.provider", havingValue = "stripe")
public class StripeWebhookController {

    private static final Logger log = LoggerFactory.getLogger(StripeWebhookController.class);

    record Event(String id, String type, Data data) {
        record Data(Intent object) {
        }

        record Intent(String id, String status, long amount, Map<String, String> metadata) {
        }
    }

    private final PaymentService payments;
    private final ObjectMapper json;
    private final String secret;
    private final Duration tolerance;
    private final Clock clock = Clock.systemUTC();

    public StripeWebhookController(PaymentService payments, ObjectMapper json,
                                   @Value("${boxoffice.stripe.webhook-secret}") String secret,
                                   @Value("${boxoffice.stripe.tolerance}") Duration tolerance) {
        this.payments = payments;
        this.json = json;
        this.secret = secret;
        this.tolerance = tolerance;
    }

    /** The raw body, as a String: the signature is computed over the exact bytes Stripe sent. */
    @PostMapping("/webhooks/stripe")
    public ResponseEntity<String> receive(@RequestBody String body,
                                          @RequestHeader(value = "Stripe-Signature", required = false) String signature) {
        if (!StripeSignature.valid(body, signature, secret, tolerance, clock)) {
            log.warn("webhook rejected: bad or missing Stripe-Signature");
            return ResponseEntity.badRequest().body("bad signature");
        }
        Event event = json.readValue(body, Event.class);
        String status = switch (event.type()) {
            case "payment_intent.succeeded" -> "AUTHORIZED";
            case "payment_intent.payment_failed" -> "DECLINED";
            default -> null; // other events: acknowledged, ignored
        };
        if (status == null) {
            return ResponseEntity.ok("ignored");
        }
        Event.Intent intent = event.data().object();
        boolean applied = payments.applyWebhook(event.id(), event.type(), intent.id(), status, intent.amount(), intent.metadata());
        log.info("webhook {} {} {} → {}", event.id(), event.type(), intent.id(), applied ? status : "duplicate, skipped");
        return ResponseEntity.ok(applied ? "applied" : "duplicate"); // 2xx quickly, or Stripe retries
    }
}
services/payment/src/main/java/boxoffice/payment/StripeSignature.java
package boxoffice.payment;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Clock;
import java.time.Duration;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * Checks the Stripe-Signature header of a webhook: t=<unix time>,v1=<hex HMAC-SHA256 of "t.body">.
 * Without it, anyone who finds the URL can post "payment succeeded".
 */
public final class StripeSignature {

    private StripeSignature() {
    }

    public static boolean valid(String body, String header, String secret, Duration tolerance, Clock clock) {
        if (header == null || secret == null || secret.isBlank()) {
            return false;
        }
        String timestamp = null;
        String expected = null;
        for (String part : header.split(",")) {
            String[] kv = part.split("=", 2);
            if (kv.length == 2 && kv[0].equals("t")) {
                timestamp = kv[1];
            } else if (kv.length == 2 && kv[0].equals("v1") && expected == null) {
                expected = kv[1];
            }
        }
        if (timestamp == null || expected == null) {
            return false;
        }
        long age = clock.instant().getEpochSecond() - Long.parseLong(timestamp);
        if (Math.abs(age) > tolerance.toSeconds()) {
            return false; // an old, replayed request: even with a correct signature
        }
        String computed = hmacSha256Hex(secret, timestamp + "." + body);
        // constant-time comparison: do not leak, byte by byte, how much of the signature matched
        return MessageDigest.isEqual(computed.getBytes(StandardCharsets.UTF_8), expected.getBytes(StandardCharsets.UTF_8));
    }

    static String hmacSha256Hex(String secret, String payload) {
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            return HexFormat.of().formatHex(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
}
services/payment/src/main/java/boxoffice/payment/PaymentService.java
package boxoffice.payment;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class PaymentService {

    public record Result(PaymentOut payment, boolean created) {
    }

    private final JdbcClient jdbc;
    private final Psp psp;

    public PaymentService(JdbcClient jdbc, Psp psp) {
        this.jdbc = jdbc;
        this.psp = psp;
    }

    public Result charge(String idempotencyKey, ChargeRequest req) {
        Optional<PaymentOut> done = find(idempotencyKey);
        if (done.isPresent()) {
            return new Result(done.get(), false); // a retry: answer, do not charge again
        }
        // remote call OUTSIDE any database transaction: never hold a connection while waiting
        Psp.Charge charge = psp.charge(idempotencyKey, req.amount(), req.orderId(), req.paymentMethod());
        String status = charge.approved() ? "AUTHORIZED" : "DECLINED";
        jdbc.sql("""
                INSERT INTO payments (id, idempotency_key, order_id, amount, status, provider_ref)
                VALUES (?, ?, ?, ?, ?, ?)
                ON CONFLICT DO NOTHING
                """)
                .params(UUID.randomUUID(), idempotencyKey, req.orderId(), req.amount(), status, charge.id())
                .update();
        return new Result(find(idempotencyKey).orElseThrow(), true);
    }

    /**
     * Applies a webhook once per event id. Updates the payment of that PaymentIntent, or creates it when
     * the charge went through but its answer never arrived (the caller timed out): the gap the webhook heals.
     * Returns false for a duplicate delivery.
     */
    @Transactional
    public boolean applyWebhook(String eventId, String type, String intentId, String status,
                                long amountInCents, Map<String, String> metadata) {
        int fresh = jdbc.sql("INSERT INTO stripe_events (id, type) VALUES (?, ?) ON CONFLICT DO NOTHING")
                .params(eventId, type).update();
        if (fresh == 0) {
            return false; // already processed: Stripe delivers at least once
        }
        int updated = jdbc.sql("UPDATE payments SET status = ? WHERE provider_ref = ?")
                .params(status, intentId).update();
        if (updated == 0 && metadata != null && metadata.containsKey("idempotency_key")) {
            jdbc.sql("""
                    INSERT INTO payments (id, idempotency_key, order_id, amount, status, provider_ref)
                    VALUES (?, ?, ?, ?, ?, ?)
                    ON CONFLICT DO NOTHING
                    """)
                    .params(UUID.randomUUID(), metadata.get("idempotency_key"), UUID.fromString(metadata.get("order_id")),
                            BigDecimal.valueOf(amountInCents).movePointLeft(2), status, intentId)
                    .update();
        }
        return true;
    }

    /** The payments of the last hours, with their provider reference: what reconciliation checks. */
    public List<PaymentOut> since(java.time.Duration window) {
        return jdbc.sql("""
                SELECT id, order_id, amount, status, provider_ref, created_at
                FROM payments WHERE created_at > now() - make_interval(secs => ?)
                ORDER BY created_at
                """)
                .param(window.toSeconds())
                .query(PaymentOut.class)
                .list();
    }

    private Optional<PaymentOut> find(String idempotencyKey) {
        return jdbc.sql("""
                SELECT id, order_id, amount, status, provider_ref, created_at
                FROM payments WHERE idempotency_key = ?
                """)
                .param(idempotencyKey)
                .query(PaymentOut.class)
                .optional();
    }
}
services/payment/src/main/resources/db/migration/V2__stripe_events.sql
1
2
3
4
5
6
7
8
9
-- every webhook event processed once: Stripe may deliver the same event more than once
CREATE TABLE stripe_events (
    id          VARCHAR(100) PRIMARY KEY,           -- evt_…
    type        VARCHAR(100) NOT NULL,
    received_at TIMESTAMPTZ  NOT NULL DEFAULT now()
);

-- the provider's PaymentIntent id is how a webhook finds its payment
CREATE UNIQUE INDEX payments_provider_ref ON payments (provider_ref);
services/payment/src/test/java/boxoffice/payment/StripeSignatureTest.java
package boxoffice.payment;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import org.junit.jupiter.api.Test;

class StripeSignatureTest {

    static final String SECRET = "whsec_test_secret";
    static final String BODY = "{\"id\":\"evt_1\",\"type\":\"payment_intent.succeeded\"}";
    static final long T = 1_800_000_000L;
    static final Clock NOW = Clock.fixed(Instant.ofEpochSecond(T + 10), ZoneOffset.UTC);
    static final Duration TOLERANCE = Duration.ofSeconds(300);

    static String header(long t, String body, String secret) {
        return "t=" + t + ",v1=" + StripeSignature.hmacSha256Hex(secret, t + "." + body);
    }

    @Test
    void acceptsTheSignatureStripeComputes() {
        assertTrue(StripeSignature.valid(BODY, header(T, BODY, SECRET), SECRET, TOLERANCE, NOW));
    }

    @Test
    void rejectsAnEditedBody() {
        assertFalse(StripeSignature.valid(BODY.replace("succeeded", "failed"), header(T, BODY, SECRET), SECRET, TOLERANCE, NOW));
    }

    @Test
    void rejectsAnotherSecret() {
        assertFalse(StripeSignature.valid(BODY, header(T, BODY, "whsec_other"), SECRET, TOLERANCE, NOW));
    }

    @Test
    void rejectsAnOldSignature() {
        long old = T - 600; // ten minutes before NOW: a replayed request
        assertFalse(StripeSignature.valid(BODY, header(old, BODY, SECRET), SECRET, TOLERANCE, NOW));
    }

    @Test
    void rejectsAMissingHeader() {
        assertFalse(StripeSignature.valid(BODY, null, SECRET, TOLERANCE, NOW));
    }
}
  • A assinatura. Stripe-Signature: t=<unix time>,v1=<hex>, em que v1 é o HMAC-SHA256 (um código de autenticação de mensagem baseado em hash, HMAC, hash-based message authentication code: um hash SHA-256 com a chave secreta do endpoint) de <t>.<corpo bruto>. O controller lê o corpo como String — interpretar primeiro e serializar de novo mudaria os bytes —, compara em tempo constante e recusa um timestamp com mais de 5 minutos, para que uma requisição capturada não possa ser repetida depois.
  • Uma vez por evento. A tabela stripe_events tem o id do evento como chave primária; INSERT … ON CONFLICT DO NOTHING devolve 0 para uma repetição, que é confirmada e pulada.
  • O webhook cura. Se nenhum pagamento tem aquele PaymentIntent — a cobrança passou, mas a resposta nunca chegou ao banco —, os metadados o recriam, com a mesma chave de idempotência. O próximo pay daquele pedido o encontra.

Encaminhe os eventos do sandbox ao payment. A interface de linha de comando (CLI, command-line interface) da Stripe abre uma conexão com a Stripe e encaminha os eventos a uma URL local — sem endereço público. Pegue o segredo de assinatura dela (ele não muda entre execuções), coloque-o no .env, reinicie o payment e suba o encaminhador:

docker compose run --rm --no-deps stripe-cli listen --print-secret     # prints whsec_…
echo "STRIPE_WEBHOOK_SECRET=whsec_..." >> .env                         # paste the value it printed
docker compose up -d --wait payment
docker compose --profile stripe up -d stripe-cli
docker compose logs stripe-cli | grep -i ready

Você deve ver Ready! … Your webhook signing secret is whsec_… (o mesmo valor). Pague outro pedido (passo 3) e acompanhe os logs:

docker compose logs -f payment | grep webhook

Você deve ver webhook evt_… payment_intent.succeeded pi_… → AUTHORIZED, um instante depois de o pay responder: o evento confirma o que a resposta síncrona disse.

Uma repetição e uma falsificação. O scripts/send-webhook.sh assina um evento do jeito que a Stripe assina, com o segredo do .env:

scripts/send-webhook.sh
#!/usr/bin/env bash
# Sends a webhook event to payment, signed the way Stripe signs it (lab 14, section 4):
# Stripe-Signature: t=<unix time>,v1=<hex HMAC-SHA256 of "<t>.<body>" with the webhook secret>.
#   scripts/send-webhook.sh event.json            # secret: STRIPE_WEBHOOK_SECRET from .env
#   scripts/send-webhook.sh event.json whsec_x    # another secret: payment must answer 400
set -euo pipefail
body=$(cat "$1")
secret=${2:-$(grep '^STRIPE_WEBHOOK_SECRET=' .env | cut -d= -f2-)}
t=$(date +%s)
sig=$(printf '%s.%s' "$t" "$body" | openssl dgst -sha256 -hmac "$secret" -hex | sed 's/^.* //')
curl -s -w ' %{http_code}\n' -X POST localhost:8085/webhooks/stripe \
  -H 'Content-Type: application/json' -H "Stripe-Signature: t=$t,v1=$sig" --data-binary "$body"
cat > /tmp/evt.json <<EOF
{"id":"evt_sandbox_1","type":"payment_intent.succeeded","data":{"object":{"id":"pi_sandbox_1","status":"succeeded","amount":35000,"metadata":{"order_id":"5b0c2f9e-7d0a-4f43-9a55-1c1c2c8f8e11","idempotency_key":"sandbox-replay"}}}}
EOF
bash scripts/send-webhook.sh /tmp/evt.json                 # applied 200
bash scripts/send-webhook.sh /tmp/evt.json                 # duplicate 200
bash scripts/send-webhook.sh /tmp/evt.json whsec_wrong     # bad signature 400

A primeira chamada grava um pagamento que o payment nunca cobrou — exatamente o que o passo 5 precisa de um evento real. A segunda é pulada, a terceira recusada (e registrada como webhook rejected).

5. A resposta perdida: cobrado, mas ninguém sabe

O pior caso do lab 9: a Stripe cobrou e o payment caiu antes de gravar — ou o order estourou o timeout em todas as tentativas. Para o fã, o checkout é UNKNOWN; para o provedor, o dinheiro se moveu. Reproduza: crie um pedido e mande à Stripe exatamente o pedido que o payment manda, à mão, como se o payment tivesse morrido logo depois:

ID=$(curl -s -X POST localhost:8084/orders -H 'Content-Type: application/json' \
  -d '{"showId":"show-9","holdId":"hold-sandbox-2","customerEmail":"bia@example.com","amount":350.00}' | jq -r .id)
KEY=$(grep '^STRIPE_SECRET_KEY=' .env | cut -d= -f2-)
curl -s https://api.stripe.com/v1/payment_intents -u "$KEY:" -H "Idempotency-Key: order-$ID" \
  -d amount=35000 -d currency=brl -d payment_method=pm_card_visa -d confirm=true \
  -d "automatic_payment_methods[enabled]=true" -d "automatic_payment_methods[allow_redirects]=never" \
  -d "metadata[order_id]=$ID" -d "metadata[idempotency_key]=order-$ID" | jq '{id, status}'

Você deve ver "status": "succeeded": o fã foi cobrado e o BoxOffice não tem registro. Depois:

  1. docker compose logs payment | grep webhook | tail -1 — o evento chegou e o payment criou o pagamento a partir dos metadados.
  2. curl -s -X POST localhost:8084/orders/$ID/pay | jq '{id, status}' — o fã (ou um retry) paga de novo: CONFIRMED. O payment achou o pagamento pela chave order-<id> e não chamou a Stripe; se tivesse chamado, a Stripe repetiria o mesmo PaymentIntent para aquela chave.
  3. No Dashboard, procure o id do pedido nos metadados: um pagamento.

O simulador mostra o tamanho do problema com o cliente do lab 9 e um provedor lento:

Experimente

Com o cliente do lab 9 (read timeout de 1 s, 3 tentativas) contra um provedor lento, 40,2% das chamadas estouram o timeout. Uma chave por pedido (a order-<orderId> do lab 9) mantém 1.000 cobranças para 1.000 fãs — 0 duplicadas —, mas 133 checkouts terminam UNKNOWN, cada um cobrado uma vez: é isso que o webhook e a reconciliação deste lab resolvem. Troque a chave para "nenhuma": 392 fãs pagam duas vezes ou mais.

6. Reconcilie: o provedor é a fonte da verdade

Webhooks podem se perder (um endpoint fora do ar por mais de algumas horas, um bug que respondeu 200 e não fez nada). Uma reconciliação periódica compara cada pagamento recente com o PaymentIntent do provedor:

services/payment/src/main/java/boxoffice/payment/Reconciliation.java
package boxoffice.payment;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/** Compares our payments with Stripe's PaymentIntents: what the provider says wins. */
@RestController
@ConditionalOnProperty(name = "boxoffice.psp.provider", havingValue = "stripe")
public class Reconciliation {

    record Mismatch(String providerRef, String ours, String stripe) {
    }

    record Report(int checked, List<Mismatch> mismatches) {
    }

    private final PaymentService payments;
    private final StripePsp stripe;

    public Reconciliation(PaymentService payments, StripePsp stripe) {
        this.payments = payments;
        this.stripe = stripe;
    }

    @GetMapping("/payments/reconcile")
    public Report reconcile(@RequestParam(defaultValue = "PT1H") Duration window) {
        List<PaymentOut> ours = payments.since(window);
        List<Mismatch> mismatches = new ArrayList<>();
        for (PaymentOut p : ours) {
            if (p.providerRef() == null || !p.providerRef().startsWith("pi_")) {
                continue; // not a Stripe payment (lab 9's fake provider)
            }
            String theirs;
            try {
                theirs = stripe.retrieve(p.providerRef()).status();
            } catch (HttpClientErrorException.NotFound e) {
                theirs = "missing"; // a payment Stripe never made: the worst mismatch
            }
            String expected = switch (theirs) {
                case "succeeded" -> "AUTHORIZED";
                case "requires_payment_method", "canceled" -> "DECLINED";
                default -> null; // processing, requires_action, missing…: always worth a look
            };
            if (!p.status().equals(expected)) {
                mismatches.add(new Mismatch(p.providerRef(), p.status(), theirs));
            }
        }
        return new Report(ours.size(), mismatches);
    }
}
curl -s 'localhost:8085/payments/reconcile?window=PT2H' | jq

Você deve ver checked contando os seus pagamentos Stripe das últimas duas horas (as referências falsas ch_… do lab 9 são puladas) e uma divergência: {"providerRef": "pi_sandbox_1", "ours": "AUTHORIZED", "stripe": "missing"} — o evento que você mesmo assinou no passo 4 registrou um pagamento que a Stripe nunca fez. É o pior tipo de divergência (um ingresso vendido por nada) e o motivo de a reconciliação existir. Remova-o, depois quebre um de verdade, de propósito, e encontre-o:

docker compose exec db psql -U boxoffice -d boxoffice -c "DELETE FROM payment.payments WHERE provider_ref = 'pi_sandbox_1'"
curl -s 'localhost:8085/payments/reconcile?window=PT2H' | jq '.mismatches'        # []
docker compose exec db psql -U boxoffice -d boxoffice -c \
  "UPDATE payment.payments SET status = 'DECLINED' WHERE id = (SELECT id FROM payment.payments WHERE status = 'AUTHORIZED' AND provider_ref LIKE 'pi_%' LIMIT 1)"
curl -s 'localhost:8085/payments/reconcile?window=PT2H' | jq '.mismatches'

Você deve ver uma divergência: "ours": "DECLINED", "stripe": "succeeded" — um fã que pagou e cujo pedido o BoxOffice teria cancelado. Em produção, esse relatório roda num agendamento e cada divergência vira um alerta ou uma correção automática (confirmar o pedido ou estornar).

Custos e limites do sandbox

O sandbox tem limites de taxa menores que o modo de produção e guarda os dados de teste até você apagá-los (Developers → … → Delete all test data). O GET /payments/reconcile faz uma chamada à Stripe por pagamento: tudo bem para um lab; para volumes reais, um job com paginação (GET /v1/payment_intents?created[gte]=…).

7. Pix com o Mercado Pago

A interface Psp é a junta para qualquer provedor. O Mercado Pago é a escolha comum no Brasil para o Pix e o Pix muda uma coisa no fluxo: a resposta a "cobrar" não é "pago" — é um QR code. O fã paga depois, no app do banco, e só o webhook diz que o dinheiro chegou. O que é uma rede de segurança com os cartões da Stripe vira o caminho principal.

Stripe (este lab) Mercado Pago, Pix
Sandbox chaves de modo de teste sk_test_… credenciais de teste (access token de teste) do painel de desenvolvedor
Criar POST /v1/payment_intents, confirm=true POST /v1/orders (Orders API), o meio de pagamento Pix em transactions.payments
Idempotência header Idempotency-Key header X-Idempotency-Key (obrigatório)
Primeira resposta succeeded ou uma recusa 402 pendente, com um QR code (qr_code, qr_code_base64) para mostrar ao fã
Confirmação webhook payment_intent.succeeded, Stripe-Signature notificação com um header x-signature (ts=…,v1=…), verificada com o segredo da Configuração de Webhooks (o kit de desenvolvimento oficial, SDK, software development kit, implementa a checagem HMAC)
Resultados de teste meios de pagamento de teste (pm_card_visa…) cartões de teste cujo nome do titular escolhe o resultado (APRO aprovado, OTHE erro, CONT pendente, FUND saldo insuficiente), Cadastro de Pessoa Física (CPF) 12345678909

Um MercadoPagoPsp devolveria Charge(id, false) com um estado novo — "pendente" — que o order precisa mostrar como "aguardando pagamento" e o webhook levaria o pagamento a AUTHORIZED. Confira a documentação de desenvolvedores do Mercado Pago atual antes de escrevê-lo: os nomes dos campos da Orders API diferem dos da Payments API, mais antiga.

Boas práticas neste lab

  • Mantenha o provedor atrás de uma interface — Psp com PspClient e StripePsp; o order nunca sabe qual deles cobrou (Compute — integrações externas).
  • Uma chave de idempotência por pedido, de ponta a ponta — order-<orderId> do order, a coluna única de payments e a Idempotency-Key da Stripe são o mesmo valor, então nenhum retry, em lugar nenhum, cobra duas vezes (Sistemas Distribuídos).
  • Trate uma recusa como resposta, não como falha — o StripePsp mapeia o 402 para DECLINED; só as falhas reais chegam ao retry e ao breaker do lab 9 (Padrões de confiabilidade).
  • Verifique todo webhook, processe cada evento uma vez — StripeSignature (HMAC, tempo constante, tolerância de 5 minutos) e a tabela stripe_events (Rede e Segurança).
  • Reconcilie com a fonte da verdade — a Reconciliation encontra o que os webhooks perderam; dinheiro precisa de uma segunda conferência, não de confiança (Observabilidade).
  • Segredos vindos do ambiente, só chaves de teste — .env ignorado pelo Git, sk_test_ exigido na subida.

Solução de problemas

Sintoma Causa Correção
o payment sai: STRIPE_SECRET_KEY must be a test key (sk_test_…) PSP_PROVIDER=stripe com uma chave vazia ou de produção coloque a chave sk_test_… no .env ou remova PSP_PROVIDER para voltar ao falso
500 e Stripe answered 401: Invalid API Key provided nos logs a chave foi copiada errada ou trocada copie-a de novo em Developers → API keys
Stripe answered 400 falando da moeda o país da sua conta não aceita cobranças em BRL acrescente STRIPE_CURRENCY=usd ao .env e reinicie o payment
Stripe answered 400 sobre idempotência a mesma Idempotency-Key enviada com outros parâmetros (outro valor ou cartão) use uma chave nova para um pedido novo; uma chave significa "este pedido exato"
os webhooks respondem 400 bad signature o STRIPE_WEBHOOK_SECRET difere do que listen --print-secret imprime ou o payment não foi reiniciado depois de editar o .env corrija o .env e rode docker compose up -d --wait payment
nenhuma linha webhook nos logs o stripe-cli não está rodando (ele tem um profile) docker compose --profile stripe up -d stripe-cli; confira docker compose logs stripe-cli
o primeiro pay responde 503 a Stripe respondeu depois do read timeout de 1 s do order chame pay de novo: a cobrança foi gravada e a mesma chave a devolve

Limpeza

docker compose --profile stripe stop stripe-cli
sed -i.bak '/^PSP_PROVIDER=/d' .env && rm .env.bak       # back to lab 9's fake provider
docker compose up -d --wait payment

Mantenha a chave no .env (ela fica fora do Git) ou apague-a; no Dashboard, você pode apagar todos os dados de teste.

Entrega

  • O payment cobra no sandbox: um AUTHORIZED, o mesmo pagamento para uma chave repetida, um DECLINED (cole as três respostas em results/lab14.md).
  • O StripeSignatureTest passa (5 testes); um webhook falsificado recebe 400, um repetido é duplicate.
  • A resposta perdida do passo 5: o webhook criou o pagamento e o pay confirmou o pedido — um pagamento no Dashboard.
  • GET /payments/reconcile: o pagamento missing do passo 4, nenhuma divergência depois de removê-lo e a que você criou (cole os três).
  • Em results/lab14.md, três frases: o que um MercadoPagoPsp para Pix muda no order.
  • Quiz respondido.

Estado final

boxoffice/ after lab 14 (changes only)
📁 boxoffice/
├──  .env                                   # not in Git: PSP_PROVIDER, STRIPE_SECRET_KEY, STRIPE_WEBHOOK_SECRET
├── YAML compose.yaml                           # payment's Stripe variables, stripe-cli (profile stripe)
├── GNU Bash scripts/send-webhook.sh
└── 📁 services/payment/
    ├──  pom.xml                            # + spring-boot-starter-test
    ├── 📁 src/main/java/boxoffice/payment/
    │   ├──  Psp.java  PspClient.java  StripePsp.java  StripeSignature.java
    │   ├──  StripeWebhookController.java  Reconciliation.java
    │   └──  ChargeRequest.java  PaymentService.java
    ├── YAML src/main/resources/application.yaml
    ├──  src/main/resources/db/migration/V2__stripe_events.sql
    └──  src/test/java/boxoffice/payment/StripeSignatureTest.java

O que quebra em seguida

Todo checkout agora é cobrado uma vez e toda cobrança é conhecida — mas saber não é consertar. A divergência da reconciliação é um fã que pagou por um pedido que o BoxOffice cancelou: isso pede um estorno (POST /v1/refunds) ou uma confirmação tardia, decididos por um job, não à mão. Cartões que pedem 3-D Secure precisam do navegador do fã (Stripe.js), o que significa um front end e um estado requires_action que o servidor sozinho não termina. O Pix torna "pendente" o caso normal, então o order precisa aprender um terceiro estado. E dinheiro de verdade significa chaves de produção, uma empresa verificada e as regras de dados de cartão do Padrão de Segurança de Dados da Indústria de Cartões de Pagamento (PCI DSS, Payment Card Industry Data Security Standard) — mantidas pequenas justamente porque números de cartão nunca tocam o BoxOffice. Se tudo isso ainda se sustenta às 10:00, com 2 milhões de fãs, é a pergunta da aula 15 — Engenharia de Desempenho e do seu projeto.