Files
webup-cloud/backend/src/test/java/run/webup/platform/PreviewConfiguration.java
T
WebUp Cloud db82325ed7
Verify control plane / verify (push) Canceled after 0s
Initial import of WebUp Cloud
2026-11-07 13:31:14 +08:00

69 lines
2.4 KiB
Java

package run.webup.platform;
import java.math.BigDecimal;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
@TestConfiguration
public class PreviewConfiguration {
@Bean
@Primary
EphemeralStore previewStore() {
return new EphemeralStore(null) {
record Entry(String value, long expires) {}
final ConcurrentHashMap<String, Entry> entries = new ConcurrentHashMap<>();
public void put(String key, String value, Duration ttl) {
entries.put(key, new Entry(value, System.currentTimeMillis() + ttl.toMillis()));
}
public String consume(String key) {
Entry e = entries.remove(key);
return e != null && e.expires() > System.currentTimeMillis() ? e.value() : null;
}
public void limit(String key, int max, int seconds) {
long now = System.currentTimeMillis();
Entry e =
entries.compute(
"limit:" + key,
(k, old) ->
old == null || old.expires() <= now
? new Entry("1", now + seconds * 1000L)
: new Entry(
String.valueOf(Integer.parseInt(old.value()) + 1), old.expires()));
if (Integer.parseInt(e.value()) > max) throw new ApiError.Failure(429, "请求过于频繁,请稍后重试");
}
};
}
@Bean
ApplicationRunner previewAccount(
IdentityService users,
WalletService wallets,
JdbcTemplate db,
@Value("${PREVIEW_EMAIL}") String email,
@Value("${PREVIEW_PASSWORD}") String password) {
return args -> {
if (db.queryForObject("SELECT COUNT(*) FROM users WHERE email=?", Integer.class, email) > 0)
return;
UUID user = users.create(email, "预览管理员", password, "local-preview");
db.update("INSERT INTO user_roles VALUES (?,'SUPER_ADMIN')", user);
wallets.adjust(
user,
new BigDecimal("1000"),
"preview-initial-credit",
"仅限本地预览的测试余额,非真实充值",
user,
"local-preview");
};
}
}