fix(rate-limit): 完善服务端限流场景的请求与重试策略

- fetchConfig 增加限流冷却判断,冷却期内挂起请求延迟后重试
- 限流冷却截止时间落盘持久化,进程重启后不立即触发限流
- 限流响应不再覆盖本地已成功应用的配置,保留离线可用数据
- 重试延时在指数退避基础上叠加随机抖动,避免集中重试
- updateAdminInfo 增加 5 分钟节流窗口与 AtomicBoolean 并发保护
- 时间回拨时自动重置节流基准,防止窗口被异常拉长
- TimeManager 对限流错误降级日志,不打印完整堆栈
- AGENTS.md 补充配置常量归属规范
This commit is contained in:
tongtong committed 2026-11-26 11:18:21 +08:00
1 parent 70f5b28481
commit 5528dbdb12
5 files changed
+171 -79

No files matched your search

@@ -15,6 +15,9 @@ public class CommonConfig {
public static final String MAP_onLocationChanged_time_KEY = "map_onLocationChanged_time_key";
public static final String MAP_BEAN = "MapBean";
/*设备基本信息上次上报时间(毫秒),用于 sn/updateAdminSn 的 5 分钟节流*/
public static final String UPDATE_SN_INFO_LAST_TIME = "update_admin_sn_last_time";
/*首次开机*/
public static final String JGY_FIRST_BOOT = "first_boot";
@@ -5,21 +5,19 @@ import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import com.fuying.sn.core.data.dto.time.AppTimeControlInfo;
import com.fuying.sn.core.common.gson.GsonUtils;
import com.fuying.sn.core.data.dto.common.BaseResponse;
import com.fuying.sn.core.data.dto.device.SnInfo;
import com.fuying.sn.core.data.dto.time.AppTimeControlInfo;
import com.fuying.sn.core.data.dto.time.SnTimeControlInfo;
import com.fuying.sn.core.common.config.CommonConfig;
import com.fuying.sn.core.data.repository.DeviceRepository;
import com.fuying.sn.core.data.remote.UrlAddress;
import com.fuying.sn.core.common.gson.GsonUtils;
import com.fuying.sn.core.data.local.db.time.AppRemainingEntity;
import com.fuying.sn.core.data.local.db.time.AppTimeControlEntity;
import com.fuying.sn.core.data.local.db.time.TimeControlDao;
import com.fuying.sn.core.data.local.db.time.TimeControlDatabase;
import com.fuying.sn.core.data.local.prefs.KVStore;
import com.fuying.sn.core.data.remote.UrlAddress;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.fuying.sn.core.data.local.prefs.KVStore;
import java.io.IOException;
import java.util.ArrayList;
@@ -61,6 +59,10 @@ public class TimeConfigRepository {
private static final long RETRY_TOO_FREQUENT_INTERVAL_MS = TimeUnit.MINUTES.toMillis(5); // 限流码退避
private static final int MAX_RETRY_COUNT = 10; // 最大重试次数,超过后停止重试
private static final Random RETRY_RANDOM = new Random();
/**
* 服务端返回“请求过于频繁”后的冷却截止时间,落盘保存,进程重启后也不会立即再次触发限流。
*/
private static final String CONFIG_TOO_FREQUENT_UNTIL = "config_too_frequent_until";
/**
* 数据库写调度器:单线程保证 clear + insert 等组合操作的提交顺序。
@@ -250,10 +252,26 @@ public class TimeConfigRepository {
}
/**
* @param forceRefresh true 时先失效内存中的两级管控配置,保证显式刷新一定回源;
* @param forceRefresh true 时在限流冷却结束后失效内存中的两级管控配置,保证显式刷新一定回源;
* 磁盘缓存保留,作为离线时的兜底数据
*/
public Observable<Boolean> fetchConfig(boolean forceRefresh) {
// 限流冷却期内不发起任何网络请求;用 defer 保证延迟结束后重新判断冷却状态。
return Observable.defer(() -> {
long remaining = getTooFrequentRemainingMillis();
if (remaining > 0) {
Log.e(TAG, "fetchConfig: 配置请求处于限流冷却,延后 " + remaining + "ms");
return Observable.timer(remaining, TimeUnit.MILLISECONDS)
.flatMap(ignored -> fetchConfig(forceRefresh));
}
return startConfigFetch(forceRefresh);
});
}
/**
* 真正发起三路配置请求。限流冷却结束后由 {@link #fetchConfig(boolean)} 调用。
*/
private Observable<Boolean> startConfigFetch(boolean forceRefresh) {
if (forceRefresh) {
DeviceRepository.getInstance().invalidateMemory(UrlAddress.SN_TIME_CONTROL);
DeviceRepository.getInstance().invalidateMemory(UrlAddress.APP_TIME_CONTROL);
@@ -262,22 +280,22 @@ public class TimeConfigRepository {
DeviceRepository.getInstance().getSnTimeControlObservable()
.map(resp -> {
Log.e(TAG, "fetchConfigOnce: sn resp=" + resp);
handleSnResponse(resp);
// 业务状态码中仅将 400 转为异常重试;网络等异常也会进入该路重试流程。
// 限流响应不覆盖本地已成功应用的配置,保留离线可用数据。
if (resp.code == 400) {
throw new ConfigRetryException("SN config too frequent, code=400");
}
handleSnResponse(resp);
return true;
});
Observable<Boolean> app =
DeviceRepository.getInstance().getAppTimeControlInfoObservable()
.map(resp -> {
Log.e(TAG, "fetchConfigOnce: app resp=" + resp);
handleAppResponse(resp);
// 业务状态码中仅将 400 转为异常重试;网络等异常也会进入该路重试流程。
// 限流响应不覆盖本地已成功应用的配置,保留离线可用数据。
if (resp.code == 400) {
throw new ConfigRetryException("App config too frequent, code=400");
}
handleAppResponse(resp);
return true;
});
Observable<Boolean> snInfo =
@@ -307,8 +325,13 @@ public class TimeConfigRepository {
throw error;
}
long delay = retryDelayMillis(error, attempt);
Log.e(TAG, "Config fetch failed, retry " + attempt + "/" + MAX_RETRY_COUNT
+ " after " + delay + "ms", error);
if (error instanceof ConfigRetryException) {
Log.e(TAG, "Config fetch rate limited, retry " + attempt + "/" + MAX_RETRY_COUNT
+ " after " + delay + "ms");
} else {
Log.e(TAG, "Config fetch failed, retry " + attempt + "/" + MAX_RETRY_COUNT
+ " after " + delay + "ms", error);
}
return delay;
})
.concatMap(delay -> Observable.timer(delay, TimeUnit.MILLISECONDS)));
@@ -333,18 +356,34 @@ public class TimeConfigRepository {
* 指数退避 + 随机抖动,避免大量设备同一时刻集中重试。
*/
private long retryDelayMillis(Throwable error, int attempt) {
long delay;
if (error instanceof ConfigRetryException) {
// 业务码 400 表示请求过于频繁,继续用短间隔重试只会延长限流时间
delay = RETRY_TOO_FREQUENT_INTERVAL_MS;
} else {
long exponential = RETRY_BASE_INTERVAL_MS << Math.min(attempt - 1, 4);
delay = Math.min(exponential, RETRY_MAX_INTERVAL_MS);
long delay = tooFrequentDelayMillis();
// 冷却时间与本次重试延时使用同一个值,避免外部触发在退避到期前再次请求
KVStore.encode(CONFIG_TOO_FREQUENT_UNTIL, System.currentTimeMillis() + delay);
return delay;
}
long exponential = RETRY_BASE_INTERVAL_MS << Math.min(attempt - 1, 4);
long delay = Math.min(exponential, RETRY_MAX_INTERVAL_MS);
long jitter = (long) (delay * 0.2 * RETRY_RANDOM.nextDouble());
return delay + jitter;
}
/**
* 限流冷却时长,在 5 分钟基础上叠加 20% 随机抖动。
*/
private long tooFrequentDelayMillis() {
return RETRY_TOO_FREQUENT_INTERVAL_MS
+ (long) (RETRY_TOO_FREQUENT_INTERVAL_MS * 0.2 * RETRY_RANDOM.nextDouble());
}
/**
* 剩余限流冷却时间;无冷却时返回 0。
*/
private long getTooFrequentRemainingMillis() {
long until = KVStore.decodeLong(CONFIG_TOO_FREQUENT_UNTIL, 0L);
return Math.max(0L, until - System.currentTimeMillis());
}
// --- 内部处理:单级响应更新 ---
private void handleSnResponse(BaseResponse<SnTimeControlInfo> response) {
@@ -579,6 +618,13 @@ public class TimeConfigRepository {
}
}
/**
* 供调用方识别服务端限流错误,降级日志而不打印完整堆栈。
*/
public static boolean isTooFrequentError(Throwable error) {
return error instanceof ConfigRetryException;
}
/**
* 业务层请求失败(HTTP 成功但 BaseResponse.code != 200,如 400 请求过于频繁)时抛出,
* 用于触发 retryWhen 的延时重试。
@@ -965,7 +965,11 @@ public class TimeManager {
@Override
public void onError(Throwable error) {
Log.e(TAG, "Config fetch failed after retries", error);
if (TimeConfigRepository.isTooFrequentError(error)) {
Log.e(TAG, "fetchConfigWithRetry: 服务端限流,保留本地配置并等待冷却结束");
} else {
Log.e(TAG, "Config fetch failed after retries", error);
}
}
@Override
@@ -22,6 +22,8 @@ import com.fuying.sn.platform.system.AndroidSettingsWriter;
import com.fuying.sn.platform.system.JgyUtils;
import com.google.gson.JsonObject;
import java.util.concurrent.atomic.AtomicBoolean;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.core.Observer;
@@ -32,11 +34,19 @@ import io.reactivex.rxjava3.disposables.Disposable;
*/
public final class DeviceProfileSync {
private static final String TAG = "DeviceProfileSync";
/**
* updateAdminSn 接口最小请求间隔,服务端限流要求 5 分钟内只请求一次。
*/
private static final long REPORT_INTERVAL_MS = 5 * 60 * 1000L;
private static volatile DeviceProfileSync instance;
private final Context mContext;
private final ContentResolver crv;
private final DeviceRepository repository;
/**
* 标记是否有上报请求在途,避免多个触发源同时命中时间窗口边界时重复发请求。
*/
private final AtomicBoolean mReporting = new AtomicBoolean(false);
private DeviceProfileSync(Context context) {
@@ -138,70 +148,96 @@ public final class DeviceProfileSync {
public void updateAdminInfo() {
String address = String.valueOf(KVStore.decodeString(CommonConfig.MAP_ADDRESS_KEY, "-"));
String longitude = String.valueOf(KVStore.decodeDouble(CommonConfig.MAP_LONGITUDE_KEY, 0L));
String latitude = String.valueOf(KVStore.decodeDouble(CommonConfig.MAP_LATITUDE_KEY, 0L));
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("address", address);
jsonObject.addProperty("longitude", longitude);
jsonObject.addProperty("latitude", latitude);
JsonObject softwareJson = new JsonObject();
softwareJson.addProperty("appstore_version", ApkUtils.getAPPVersionName(mContext, JgyUtils.PACKAGE_APPSTORE));
softwareJson.addProperty("updatetools_version", ApkUtils.getAPPVersionName(mContext, JgyUtils.PACKAGE_UPDATETOOLS));
softwareJson.addProperty("info_version", ApkUtils.getAPPVersionName(mContext, "com.fuying.sn"));
softwareJson.addProperty("jiaoguanyi_version", ApkUtils.getAPPVersionName(mContext, "com.jiaoguanyi.os"));
softwareJson.addProperty("gankao_version", ApkUtils.getAPPVersionName(mContext, "com.gankao.gkwxhd"));
softwareJson.addProperty("learning_version", ApkUtils.getAPPVersionName(mContext, "com.info.learning"));
softwareJson.addProperty("chat_version", ApkUtils.getAPPVersionName(mContext, "com.info.chat"));
// TODO: 2022/6/29
softwareJson.addProperty("jpush_id", "");
softwareJson.addProperty("notice_version", ApkUtils.getAPPVersionName(mContext, "com.uiui.info"));
softwareJson.addProperty("browser_version", ApkUtils.getAPPVersionName(mContext, "com.uiui.browser"));
softwareJson.addProperty("desktop_version", ApkUtils.getAPPVersionName(mContext, "com.fuying.fuxiaoying"));
String addr = jsonObject.toString();
String machine = HardwareInfoUtils.getMachine(mContext);
String hardware = HardwareInfoUtils.getHardware(mContext);
String software = softwareJson.toString();
JsonObject nowJson = new JsonObject();
nowJson.addProperty("address", addr);
nowJson.addProperty("machine", machine);
nowJson.addProperty("hardware", hardware);
nowJson.addProperty("software", software);
String string = GsonUtils.toJSONString(nowJson);
String oldString = KVStore.decodeString(UrlAddress.UPDATE_SN_INFO, "");
Log.e(TAG, "updateAdminInfo: oldString = " + oldString);
Log.e(TAG, "updateAdminInfo: string = " + string);
if (oldString.equals(string)) {
Log.e(TAG, "updateAdminInfo: skip");
long now = System.currentTimeMillis();
long lastReportTime = KVStore.decodeLong(CommonConfig.UPDATE_SN_INFO_LAST_TIME, 0L);
if (now < lastReportTime) {
// 系统时间被回拨时重置基准,避免节流窗口被异常拉长
lastReportTime = 0L;
}
if (now - lastReportTime < REPORT_INTERVAL_MS) {
Log.e(TAG, "updateAdminInfo: 5分钟内已上报,跳过, 剩余 = "
+ (REPORT_INTERVAL_MS - (now - lastReportTime)) + "ms");
return;
}
repository.reportDeviceInfo(addr, machine, hardware, software)
.to(BackgroundRequests.submit(new Observer<BaseResponse>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
Log.e(TAG, "updateAdminInfo: onSubscribe: ");
}
if (!mReporting.compareAndSet(false, true)) {
Log.e(TAG, "updateAdminInfo: 已有上报请求进行中,跳过");
return;
}
boolean requestSubmitted = false;
try {
String address = String.valueOf(KVStore.decodeString(CommonConfig.MAP_ADDRESS_KEY, "-"));
String longitude = String.valueOf(KVStore.decodeDouble(CommonConfig.MAP_LONGITUDE_KEY, 0L));
String latitude = String.valueOf(KVStore.decodeDouble(CommonConfig.MAP_LATITUDE_KEY, 0L));
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("address", address);
jsonObject.addProperty("longitude", longitude);
jsonObject.addProperty("latitude", latitude);
@Override
public void onNext(@NonNull BaseResponse baseResponse) {
if (baseResponse.code == 200) {
KVStore.encode(UrlAddress.UPDATE_SN_INFO, string);
JsonObject softwareJson = new JsonObject();
softwareJson.addProperty("appstore_version", ApkUtils.getAPPVersionName(mContext, JgyUtils.PACKAGE_APPSTORE));
softwareJson.addProperty("updatetools_version", ApkUtils.getAPPVersionName(mContext, JgyUtils.PACKAGE_UPDATETOOLS));
softwareJson.addProperty("info_version", ApkUtils.getAPPVersionName(mContext, "com.fuying.sn"));
softwareJson.addProperty("jiaoguanyi_version", ApkUtils.getAPPVersionName(mContext, "com.jiaoguanyi.os"));
softwareJson.addProperty("gankao_version", ApkUtils.getAPPVersionName(mContext, "com.gankao.gkwxhd"));
softwareJson.addProperty("learning_version", ApkUtils.getAPPVersionName(mContext, "com.info.learning"));
softwareJson.addProperty("chat_version", ApkUtils.getAPPVersionName(mContext, "com.info.chat"));
// TODO: 2022/6/29
softwareJson.addProperty("jpush_id", "");
softwareJson.addProperty("notice_version", ApkUtils.getAPPVersionName(mContext, "com.uiui.info"));
softwareJson.addProperty("browser_version", ApkUtils.getAPPVersionName(mContext, "com.uiui.browser"));
softwareJson.addProperty("desktop_version", ApkUtils.getAPPVersionName(mContext, "com.fuying.fuxiaoying"));
String addr = jsonObject.toString();
String machine = HardwareInfoUtils.getMachine(mContext);
String hardware = HardwareInfoUtils.getHardware(mContext);
String software = softwareJson.toString();
JsonObject nowJson = new JsonObject();
nowJson.addProperty("address", addr);
nowJson.addProperty("machine", machine);
nowJson.addProperty("hardware", hardware);
nowJson.addProperty("software", software);
String string = GsonUtils.toJSONString(nowJson);
String oldString = KVStore.decodeString(UrlAddress.UPDATE_SN_INFO, "");
Log.e(TAG, "updateAdminInfo: oldString = " + oldString);
Log.e(TAG, "updateAdminInfo: string = " + string);
if (oldString.equals(string)) {
Log.e(TAG, "updateAdminInfo: skip");
return;
}
// 成功、失败都占用 5 分钟窗口,避免失败后立刻重试持续打服务端
KVStore.encode(CommonConfig.UPDATE_SN_INFO_LAST_TIME, now);
repository.reportDeviceInfo(addr, machine, hardware, software)
.to(BackgroundRequests.submit(new Observer<BaseResponse>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
Log.e(TAG, "updateAdminInfo: onSubscribe: ");
}
Log.e(TAG, "updateAdminInfo: onNext: " + baseResponse);
}
@Override
public void onNext(@NonNull BaseResponse baseResponse) {
if (baseResponse.code == 200) {
KVStore.encode(UrlAddress.UPDATE_SN_INFO, string);
}
Log.e(TAG, "updateAdminInfo: onNext: " + baseResponse);
}
@Override
public void onError(@NonNull Throwable e) {
Log.e(TAG, "updateAdminInfo: onError: " + e.getMessage());
}
@Override
public void onError(@NonNull Throwable e) {
Log.e(TAG, "updateAdminInfo: onError: " + e.getMessage());
mReporting.set(false);
}
@Override
public void onComplete() {
Log.e(TAG, "updateAdminInfo: onComplete: ");
}
}));
@Override
public void onComplete() {
Log.e(TAG, "updateAdminInfo: onComplete: ");
mReporting.set(false);
}
}));
requestSubmitted = true;
} finally {
if (!requestSubmitted) {
mReporting.set(false);
}
}
}
}