package com.ankurm.cloudstream;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* The whole application: three plain java.util.function beans. Nothing here imports a binder or a
* broker client, which is what makes switching brokers a configuration change.
*
*
* orderSource (Supplier) --> orders --> priceOrder (Function) --> invoices --> bill (Consumer)
*
*/
@Configuration(proxyBeanMethods = false)
public class Pipeline {
private static final Logger log = LoggerFactory.getLogger(Pipeline.class);
private static final List CUSTOMERS = List.of("alice", "bob", "carol", "dave");
/**
* Polled by the framework (every second by default), one order per call. A supplier that returns
* {@code null} sends nothing, which is how {@code demo.max-orders} makes the demos finite (0 = unbounded).
*/
@Bean
public Supplier orderSource(@Value("${demo.max-orders:0}") int maxOrders) {
AtomicInteger n = new AtomicInteger();
return () -> {
int i = n.incrementAndGet();
if (maxOrders > 0 && i > maxOrders) {
return null;
}
return new Order("o-" + i, CUSTOMERS.get(i % CUSTOMERS.size()), 1 + i % 3, 9.5);
};
}
/** Input and output are both typed; the framework converts JSON to and from the records. */
@Bean
public Function priceOrder() {
return order -> new Invoice(order.orderId(), order.customerId(), order.quantity() * order.unitPrice());
}
/** A negative total is the "poison" in the dead-letter demos: this consumer throws on it. */
@Bean
public Consumer bill() {
return invoice -> {
log.info("bill attempt for {}", invoice.orderId());
if (invoice.total() < 0) {
throw new IllegalArgumentException("Refusing to bill " + invoice.orderId() + ": negative total");
}
log.info("billed {} for {}", invoice.orderId(), invoice.total());
};
}
}