Skip to content

StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.

Add Stalker catalog probe tool and associated tests

David Nashasha71a57f724f1
diff --git a/data/build.gradle.kts b/data/build.gradle.kts
index d04f4d59..315b9ba5 100644
--- a/data/build.gradle.kts
+++ b/data/build.gradle.kts
@@ -14,9 +14,19 @@ android {
defaultConfig {
minSdk = 25
+ // Enable only in validation builds until portal and multi-channel playback evidence exists.
+ buildConfigField("boolean", "STALKER_ADAPTIVE_INDEXING", (providers.gradleProperty("stalkerAdaptiveIndexing").orNull == "true").toString())
+ val requestedStalkerPageConcurrency = providers.gradleProperty("stalkerIndexPageConcurrency")
+ .orNull
+ ?.toIntOrNull()
+ ?.coerceIn(1, 2)
+ ?: 1
+ buildConfigField("int", "STALKER_INDEX_PAGE_CONCURRENCY", requestedStalkerPageConcurrency.toString())
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
+ buildFeatures { buildConfig = true }
+
compileOptions {
isCoreLibraryDesugaringEnabled = true
sourceCompatibility = JavaVersion.VERSION_17
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt b/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt
index b35b0491..8d6164bb 100644
--- a/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt
+++ b/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt
@@ -786,18 +786,28 @@ class OkHttpStalkerApiService @Inject constructor(
categoryId: String?,
page: Int,
searchQuery: String?
+ ): Result<StalkerPagedItems> = getVodStreamsPage(
+ session = session,
+ profile = profile,
+ categoryId = categoryId,
+ page = page,
+ searchQuery = searchQuery,
+ sortBy = null
+ )
+
+ override suspend fun getVodStreamsPage(
+ session: StalkerSession,
+ profile: StalkerDeviceProfile,
+ categoryId: String?,
+ page: Int,
+ searchQuery: String?,
+ sortBy: String?
): Result<StalkerPagedItems> = runApiCall("Failed to load movies") {
fetchPagedItemPage(
session = session,
profile = profile,
page = page,
- baseQuery = buildMap {
- put("type", "vod")
- put("action", "get_ordered_list")
- put("JsHttpRequest", "1-xml")
- categoryId?.takeIf { it.isNotBlank() }?.let { put("category", it) }
- searchQuery?.trim()?.takeIf { it.isNotBlank() }?.let { put("search", it) }
- }
+ baseQuery = vodOrderedListQuery(categoryId, searchQuery, sortBy)
)
}
@@ -807,22 +817,45 @@ class OkHttpStalkerApiService @Inject constructor(
categoryId: String?,
portalPage: Int,
searchQuery: String?
+ ): Result<StalkerPagedItems> = getVodStreamsPageAtPortalPage(
+ session = session,
+ profile = profile,
+ categoryId = categoryId,
+ portalPage = portalPage,
+ searchQuery = searchQuery,
+ sortBy = null
+ )
+
+ override suspend fun getVodStreamsPageAtPortalPage(
+ session: StalkerSession,
+ profile: StalkerDeviceProfile,
+ categoryId: String?,
+ portalPage: Int,
+ searchQuery: String?,
+ sortBy: String?
): Result<StalkerPagedItems> = runApiCall("Failed to load movies") {
fetchPagedItemPage(
session = session,
profile = profile,
page = portalPage,
allowPageZero = true,
- baseQuery = buildMap {
- put("type", "vod")
- put("action", "get_ordered_list")
- put("JsHttpRequest", "1-xml")
- categoryId?.takeIf { it.isNotBlank() }?.let { put("category", it) }
- searchQuery?.trim()?.takeIf { it.isNotBlank() }?.let { put("search", it) }
- }
+ baseQuery = vodOrderedListQuery(categoryId, searchQuery, sortBy)
)
}
+ private fun vodOrderedListQuery(
+ categoryId: String?,
+ searchQuery: String?,
+ sortBy: String?
+ ): Map<String, String> = buildMap {
+ put("type", "vod")
+ put("action", "get_ordered_list")
+ put("JsHttpRequest", "1-xml")
+ categoryId?.takeIf { it.isNotBlank() }?.let { put("category", it) }
+ searchQuery?.trim()?.takeIf { it.isNotBlank() }?.let { put("search", it) }
+ sortBy?.trim()?.takeIf { it.isNotBlank() }?.let { put("sortby", it) }
+ }
+
override suspend fun getVodFiles(
session: StalkerSession,
profile: StalkerDeviceProfile,
@@ -2807,10 +2840,11 @@ class OkHttpStalkerApiService @Inject constructor(
StalkerNetworkPriority.INTERACTIVE
request.url.queryParameter("action").equals("get_short_epg", ignoreCase = true) ->
StalkerNetworkPriority.PREFETCH
- currentCoroutineContext()[StalkerRequestPriorityContext]?.priority in setOf(
- com.streamvault.domain.model.StalkerRequestPriority.EPG,
- com.streamvault.domain.model.StalkerRequestPriority.BACKGROUND_INDEX
- ) -> StalkerNetworkPriority.BACKGROUND
+ currentCoroutineContext()[StalkerRequestPriorityContext]?.priority ==
+ com.streamvault.domain.model.StalkerRequestPriority.BACKGROUND_INDEX ->
+ StalkerNetworkPriority.INDEX
+ currentCoroutineContext()[StalkerRequestPriorityContext]?.priority ==
+ com.streamvault.domain.model.StalkerRequestPriority.EPG -> StalkerNetworkPriority.BACKGROUND
currentCoroutineContext()[StalkerRequestPriorityContext]?.priority ==
com.streamvault.domain.model.StalkerRequestPriority.VISIBLE_PREVIEW ->
StalkerNetworkPriority.PREFETCH
@@ -2836,10 +2870,11 @@ class OkHttpStalkerApiService @Inject constructor(
requestCoordinator.recordNetworkSuccess(permit)
}
block(response)
- }
+ }.also { requestCoordinator.recordIndexResponse(permit) }
} catch (error: CancellationException) {
throw error
} catch (error: Throwable) {
+ requestCoordinator.recordIndexResponse(permit, error)
if (!nonRateLimitedResponseObserved) {
requestCoordinator.recordNetworkFailure(permit, error)
}
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerAdaptiveIndexPolicy.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerAdaptiveIndexPolicy.kt
new file mode 100644
index 00000000..d9f8fb89
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerAdaptiveIndexPolicy.kt
@@ -0,0 +1,53 @@
+package com.streamvault.data.remote.stalker
+
+/** Pure, provider-owned pacing state. Admission, not parallelism, controls the wire rate. */
+internal class StalkerAdaptiveIndexPolicy(
+ intervalMillis: Long = INITIAL_INTERVAL_MILLIS,
+ minimumIntervalMillis: Long = MIN_INTERVAL_MILLIS
+) {
+ var minimumIntervalMillis = minimumIntervalMillis.coerceIn(MIN_INTERVAL_MILLIS, MAX_INTERVAL_MILLIS)
+ private set
+ var intervalMillis = intervalMillis.coerceIn(this.minimumIntervalMillis, MAX_INTERVAL_MILLIS)
+ private set
+ private var healthyResponses = 0
+ private var healthySince: Long? = null
+
+ fun success(now: Long, durationMillis: Long, playbackActive: Boolean): Boolean {
+ if (playbackActive) {
+ resetHealth()
+ return false
+ }
+ if (durationMillis >= SLOW_RESPONSE_MILLIS) return stress()
+ if (healthySince == null) healthySince = now
+ healthyResponses++
+ if (healthyResponses < HEALTHY_RESPONSES || now - requireNotNull(healthySince) < HEALTHY_WINDOW_MILLIS) return false
+ val previous = intervalMillis
+ intervalMillis = (intervalMillis * 3 / 4).coerceAtLeast(minimumIntervalMillis)
+ resetHealth()
+ return intervalMillis != previous
+ }
+
+ /** Remember the failed rate as a ceiling, including across process restarts. */
+ fun stress(): Boolean {
+ val previous = intervalMillis
+ minimumIntervalMillis = (intervalMillis * 2).coerceAtMost(MAX_INTERVAL_MILLIS)
+ intervalMillis = minimumIntervalMillis
+ resetHealth()
+ return intervalMillis != previous
+ }
+
+ fun resetHealth() {
+ healthyResponses = 0
+ healthySince = null
+ }
+
+ companion object {
+ const val INITIAL_INTERVAL_MILLIS = 5_000L
+ const val MIN_INTERVAL_MILLIS = 500L
+ const val MAX_INTERVAL_MILLIS = 30_000L
+ const val PLAYBACK_INTERVAL_MILLIS = 20_000L
+ const val HEALTHY_RESPONSES = 12
+ const val HEALTHY_WINDOW_MILLIS = 15_000L
+ const val SLOW_RESPONSE_MILLIS = 2_000L
+ }
+}
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiService.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiService.kt
index 00de7a66..82e3523e 100644
--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiService.kt
+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiService.kt
@@ -253,6 +253,20 @@ interface StalkerRawVodPageApi {
portalPage: Int,
searchQuery: String? = null
): Result<StalkerPagedItems>
+
+ /**
+ * Raw page fetch with an explicit ordering hint (for example `added`). Transports that
+ * cannot honor it keep the portal's default order by delegating to the basic overload.
+ */
+ suspend fun getVodStreamsPageAtPortalPage(
+ session: StalkerSession,
+ profile: StalkerDeviceProfile,
+ categoryId: String?,
+ portalPage: Int,
+ searchQuery: String?,
+ sortBy: String?
+ ): Result<StalkerPagedItems> =
+ getVodStreamsPageAtPortalPage(session, profile, categoryId, portalPage, searchQuery)
}
data class StalkerSeriesDetails(
@@ -372,6 +386,19 @@ interface StalkerApiService {
searchQuery: String?
): Result<StalkerPagedItems> = getVodStreamsPage(session, profile, categoryId, page)
+ /**
+ * Paged VOD fetch with an explicit ordering hint (for example `added`). Transports that
+ * cannot honor it keep the portal's default order by delegating to the basic overload.
+ */
+ suspend fun getVodStreamsPage(
+ session: StalkerSession,
+ profile: StalkerDeviceProfile,
+ categoryId: String?,
+ page: Int,
+ searchQuery: String?,
+ sortBy: String?
+ ): Result<StalkerPagedItems> = getVodStreamsPage(session, profile, categoryId, page, searchQuery)
+
/** Returns the playable file rows exposed when opening a video-club movie. */
suspend fun getVodFiles(
session: StalkerSession,
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerPortalStateStore.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerPortalStateStore.kt
index 5dca97c9..fabdd4f5 100644
--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerPortalStateStore.kt
+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerPortalStateStore.kt
@@ -38,6 +38,30 @@ class StalkerPortalStateStore @Inject constructor(
suspend fun get(providerId: Long): StalkerPortalStateEntity? = dao.get(providerId)
+ internal fun indexPacing(state: StalkerPortalStateEntity): StalkerAdaptiveIndexPolicy = runCatching {
+ val pacing = json.parseToJsonElement(state.learningJson).jsonObject.getValue("indexPacing").jsonObject
+ require(pacing.getValue("configurationGeneration").jsonPrimitive.longOrNull == state.configurationGeneration)
+ StalkerAdaptiveIndexPolicy(
+ pacing.getValue("intervalMillis").jsonPrimitive.content.toLong(),
+ pacing.getValue("minimumIntervalMillis").jsonPrimitive.content.toLong()
+ )
+ }.getOrElse { StalkerAdaptiveIndexPolicy() }
+
+ internal suspend fun recordIndexPacing(
+ providerId: Long,
+ configurationGeneration: Long,
+ intervalMillis: Long,
+ minimumIntervalMillis: Long
+ ) = update(providerId, configurationGeneration) { state ->
+ val learning = mutableLearning(state.learningJson)
+ learning["indexPacing"] = JsonObject(mapOf(
+ "configurationGeneration" to JsonPrimitive(configurationGeneration),
+ "intervalMillis" to JsonPrimitive(intervalMillis),
+ "minimumIntervalMillis" to JsonPrimitive(minimumIntervalMillis)
+ ))
+ state.copy(configurationGeneration = configurationGeneration, learningJson = JsonObject(learning).toString())
+ }
+
/** Returns a learned VOD page offset only while it belongs to this provider configuration. */
suspend fun getVodPageBase(providerId: Long, configurationGeneration: Long): Int? {
if (providerId <= 0L) return null
@@ -81,6 +105,77 @@ class StalkerPortalStateStore @Inject constructor(
}
}
+ /** Returns the largest validated page size observed for this content type and generation. */
+ internal suspend fun getVodPageSize(
+ providerId: Long,
+ contentType: ContentType,
+ configurationGeneration: Long
+ ): Int? {
+ if (providerId <= 0L || contentType !in VOD_CONTENT_TYPES) return null
+ val state = dao.get(providerId) ?: return null
+ if (state.configurationGeneration != configurationGeneration) return null
+ val learning = runCatching {
+ json.parseToJsonElement(state.learningJson.ifBlank { "{}" }).jsonObject
+ }.getOrNull() ?: return null
+ if (learning["configurationGeneration"]?.jsonPrimitive?.longOrNull != configurationGeneration) {
+ return null
+ }
+ val observation = runCatching {
+ learning["vodPageSizes"]?.jsonObject?.get(contentType.name)?.jsonObject
+ }.getOrNull() ?: return null
+ if (observation["configurationGeneration"]?.jsonPrimitive?.longOrNull != configurationGeneration) {
+ return null
+ }
+ return runCatching {
+ observation["value"]?.jsonPrimitive?.content?.toIntOrNull()
+ ?.takeIf { it in 1..MAX_LEARNED_VOD_PAGE_SIZE }
+ }.getOrNull()
+ }
+
+ /** Stores only a larger observed page size, using the existing generation-fenced learning envelope. */
+ internal suspend fun recordVodPageSize(
+ providerId: Long,
+ contentType: ContentType,
+ pageSize: Int,
+ configurationGeneration: Long,
+ now: Long = System.currentTimeMillis()
+ ) {
+ if (providerId <= 0L || contentType !in VOD_CONTENT_TYPES || pageSize !in 1..MAX_LEARNED_VOD_PAGE_SIZE) return
+ if (getVodPageSize(providerId, contentType, configurationGeneration)?.let { it >= pageSize } == true) return
+ update(providerId, configurationGeneration) { state ->
+ val learning = mutableLearning(state.learningJson)
+ val sizes = (learning["vodPageSizes"] as? JsonObject)?.toMutableMap() ?: mutableMapOf()
+ val previousObservation = sizes[contentType.name] as? JsonObject
+ val previousGeneration = runCatching {
+ previousObservation?.get("configurationGeneration")?.jsonPrimitive?.longOrNull
+ }.getOrNull()
+ val previous = if (previousGeneration == configurationGeneration) {
+ runCatching {
+ previousObservation?.get("value")?.jsonPrimitive?.content?.toIntOrNull()
+ }.getOrNull()
+ } else {
+ null
+ }
+ if (previous != null && previous >= pageSize) return@update state
+
+ val generation = configurationGeneration
+ sizes[contentType.name] = observationJson(
+ pageSize,
+ generation,
+ now,
+ "CATALOG"
+ )
+ learning["configurationGeneration"] = JsonPrimitive(generation)
+ learning["vodPageSizes"] = JsonObject(sizes)
+ state.copy(
+ configurationGeneration = generation,
+ learningJson = JsonObject(learning).toString(),
+ observationSource = "CATALOG",
+ observedAt = now
+ )
+ }
+ }
+
/**
* Durable session resurrected after a process restart. The session envelope is encrypted
* with the app's Keystore-backed credential crypto and is only reused for the same
@@ -537,6 +632,8 @@ class StalkerPortalStateStore @Inject constructor(
.joinToString("") { byte -> "%02x".format(byte.toInt() and 0xff) }
private companion object {
+ val VOD_CONTENT_TYPES = setOf(ContentType.MOVIE, ContentType.SERIES)
+ const val MAX_LEARNED_VOD_PAGE_SIZE = 128
const val VALIDATION_TTL_MILLIS = 7L * 24L * 60L * 60L * 1000L
const val ENDPOINT_COOLDOWN_MILLIS = 10L * 60L * 1000L
const val RECIPE_COOLDOWN_MILLIS = 10L * 60L * 1000L
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt
index 759f2cc9..5ccafca3 100644
--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt
+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt
@@ -153,6 +153,8 @@ internal companion object {
private const val AUTH_FAILURE_COOLDOWN_MILLIS = 2_000L
private const val FALLBACK_SURROGATE_FLOOR = 4_000_000_000L
const val CATALOG_LAYOUT_DETECTION_VERSION = 1
+ /** Ordering for the background wildcard index walk: newest titles first. */
+ internal const val WILDCARD_INDEX_SORT = "added"
private const val VOD_FILE_SOURCE_KEY = "vod_file"
private val BARE_VOD_MOVIE_CMD_REGEX = Regex("^/media/(\\d+)\\.mpg$", RegexOption.IGNORE_CASE)
private val BARE_VOD_FILE_CMD_REGEX = Regex("^/media/file_(\\d+)\\.mpg$", RegexOption.IGNORE_CASE)
@@ -608,7 +610,12 @@ internal companion object {
}
suspend fun getVodStreamsPageUsingItemCategories(categoryId: Long?, page: Int): Result<StalkerPagedResult<Movie>> =
- loadVodPageWithPortalPageBase(ContentType.MOVIE, categoryId, page).let { result ->
+ loadVodPageWithPortalPageBase(
+ ContentType.MOVIE,
+ categoryId,
+ page,
+ sortBy = WILDCARD_INDEX_SORT
+ ).let { result ->
mapResolvedPage(ContentType.MOVIE, result) { item ->
toMovie(item, requestedCategoryId = null)
}
@@ -617,6 +624,13 @@ internal companion object {
suspend fun getUnifiedVodPage(categoryId: Long, page: Int): Result<StalkerPagedResult<StalkerVodCatalogItem>> =
getClassifiedVodPage(ContentType.VOD, categoryId, page)
+ suspend fun getUnifiedVodPage(
+ categoryId: Long,
+ page: Int,
+ sortBy: String?
+ ): Result<StalkerPagedResult<StalkerVodCatalogItem>> =
+ getClassifiedVodPage(ContentType.VOD, categoryId, page, sortBy = sortBy)
+
suspend fun searchVodPage(
query: String,
page: Int
@@ -691,9 +705,10 @@ internal companion object {
categoryId: Long?,
page: Int,
seriesCategoryId: Long? = categoryId,
- searchQuery: String? = null
+ searchQuery: String? = null,
+ sortBy: String? = null
): Result<StalkerPagedResult<StalkerVodCatalogItem>> {
- val rawResult = loadVodPageWithPortalPageBase(categoryType, categoryId, page, searchQuery)
+ val rawResult = loadVodPageWithPortalPageBase(categoryType, categoryId, page, searchQuery, sortBy)
return when (rawResult) {
is Result.Success -> {
val raw = rawResult.data
@@ -1612,7 +1627,8 @@ is Result.Success -> {
categoryType: ContentType,
categoryId: Long?,
logicalPage: Int,
- searchQuery: String? = null
+ searchQuery: String? = null,
+ sortBy: String? = null
): Result<StalkerPagedItems> = runWithAuthorizedSession { session, _ ->
val profile = currentDeviceProfile()
val rawCategoryId = resolveRawCategoryId(categoryType, categoryId)
@@ -1621,10 +1637,17 @@ is Result.Success -> {
if (api !is StalkerRawVodPageApi) {
// Legacy transports do not expose a raw p=0 cursor. Keep their established
// 1-based call shape and avoid extra requests that cannot teach an offset.
- val pageResult = if (searchQuery == null) {
- api.getVodStreamsPage(session, profile, rawCategoryId, pageNumber)
- } else {
- api.getVodStreamsPage(session, profile, rawCategoryId, pageNumber, searchQuery)
+ val pageResult = when {
+ sortBy != null -> api.getVodStreamsPage(
+ session,
+ profile,
+ rawCategoryId,
+ pageNumber,
+ searchQuery,
+ sortBy
+ )
+ searchQuery == null -> api.getVodStreamsPage(session, profile, rawCategoryId, pageNumber)
+ else -> api.getVodStreamsPage(session, profile, rawCategoryId, pageNumber, searchQuery)
}
return@runWithAuthorizedSession normalizeVodPage(pageResult, pageNumber)
}
@@ -1643,7 +1666,8 @@ is Result.Success -> {
profile,
rawCategoryId,
portalPage = 0,
- searchQuery = searchQuery
+ searchQuery = searchQuery,
+ sortBy = sortBy
)
if (pageZero is Result.Error && isAuthorizationFailure(pageZero.message, pageZero.exception)) {
return@withLock VodPageBaseResolution.Failed(pageZero)
@@ -1657,7 +1681,8 @@ is Result.Success -> {
profile,
rawCategoryId,
portalPage = 1,
- searchQuery = searchQuery
+ searchQuery = searchQuery,
+ sortBy = sortBy
)
if (pageOne is Result.Error && isAuthorizationFailure(pageOne.message, pageOne.exception)) {
return@withLock VodPageBaseResolution.Failed(pageOne)
@@ -1691,7 +1716,8 @@ is Result.Success -> {
profile,
rawCategoryId,
portalPage,
- searchQuery
+ searchQuery,
+ sortBy
),
pageNumber
)
@@ -1706,7 +1732,8 @@ is Result.Success -> {
profile,
rawCategoryId,
portalPage,
- searchQuery
+ searchQuery,
+ sortBy
)
}
normalizeVodPage(target, pageNumber)
@@ -1771,15 +1798,15 @@ is Result.Success -> {
profile: StalkerDeviceProfile,
categoryId: String?,
portalPage: Int,
- searchQuery: String?
+ searchQuery: String?,
+ sortBy: String? = null
): Result<StalkerPagedItems> {
- return (api as StalkerRawVodPageApi).getVodStreamsPageAtPortalPage(
- session,
- profile,
- categoryId,
- portalPage,
- searchQuery
- )
+ val rawApi = api as StalkerRawVodPageApi
+ return if (sortBy == null) {
+ rawApi.getVodStreamsPageAtPortalPage(session, profile, categoryId, portalPage, searchQuery)
+ } else {
+ rawApi.getVodStreamsPageAtPortalPage(session, profile, categoryId, portalPage, searchQuery, sortBy)
+ }
}
private suspend fun mapPagedItems(
@@ -2124,6 +2151,15 @@ is Result.Success -> {
)
}
+ suspend fun recordVodPageSize(contentType: ContentType, pageSize: Int) {
+ portalStateStore?.recordVodPageSize(
+ providerId,
+ contentType,
+ pageSize,
+ configurationGeneration
+ )
+ }
+
suspend fun recordEpgCapability(supported: Boolean) {
portalStateStore?.recordEpg(
providerId,
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinator.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinator.kt
index 771e0db2..19dab0af 100644
--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinator.kt
+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinator.kt
@@ -1,5 +1,6 @@
package com.streamvault.data.remote.stalker
+import com.streamvault.data.BuildConfig
import com.streamvault.domain.model.StalkerRequestPriority
import com.streamvault.domain.model.Result
import java.net.SocketTimeoutException
@@ -9,6 +10,7 @@ import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import kotlinx.coroutines.sync.Mutex
@@ -26,13 +28,18 @@ data class StalkerRequestSnapshot(
class StalkerNetworkPermit internal constructor(
internal val providerId: Long,
internal val halfOpenProbe: Boolean,
- internal val priority: StalkerNetworkPriority
+ internal val priority: StalkerNetworkPriority,
+ internal val admittedAt: Long = 0L
)
-enum class StalkerNetworkPriority { INTERACTIVE, FOREGROUND, PREFETCH, BACKGROUND }
+enum class StalkerNetworkPriority { INTERACTIVE, FOREGROUND, PREFETCH, BACKGROUND, INDEX }
internal class StalkerRequestPriorityContext(
- val priority: StalkerRequestPriority
+ val priority: StalkerRequestPriority,
+ // Invoked only while the provider mutex is held, by network admission.
+ val yieldMetadata: (() -> Unit)? = null,
+ val resumeMetadata: (() -> Boolean)? = null,
+ val providerId: Long? = null
) : AbstractCoroutineContextElement(Key) {
companion object Key : CoroutineContext.Key<StalkerRequestPriorityContext>
}
@@ -64,18 +71,44 @@ data class StalkerResponseMetrics(
/** Provider-scoped priority, deduplication, and adaptive metadata admission. */
@Singleton
-class StalkerRequestCoordinator @Inject constructor(
- private val portalStateStore: StalkerPortalStateStore?
+class StalkerRequestCoordinator internal constructor(
+ private val portalStateStore: StalkerPortalStateStore?,
+ private val adaptiveIndexingEnabled: Boolean,
+ private val nowMillis: () -> Long,
+ configuredIndexConcurrency: Int
) {
+ internal constructor(
+ portalStateStore: StalkerPortalStateStore?,
+ adaptiveIndexingEnabled: Boolean,
+ nowMillis: () -> Long
+ ) : this(
+ portalStateStore,
+ adaptiveIndexingEnabled,
+ nowMillis,
+ BuildConfig.STALKER_INDEX_PAGE_CONCURRENCY
+ )
+
+ private val indexExecutionConcurrency = if (adaptiveIndexingEnabled) {
+ configuredIndexConcurrency.coerceIn(1, MAX_INDEX_EXECUTION_CONCURRENCY)
+ } else {
+ 1
+ }
+
+ @Inject constructor(portalStateStore: StalkerPortalStateStore?) : this(
+ portalStateStore,
+ BuildConfig.STALKER_ADAPTIVE_INDEXING,
+ System::currentTimeMillis,
+ BuildConfig.STALKER_INDEX_PAGE_CONCURRENCY
+ )
/** Isolated constructor for pure unit tests; production uses the injected state store. */
- constructor() : this(null)
+ constructor() : this(null, false, System::currentTimeMillis, 1)
private data class Waiter(
val ticket: Long,
val priority: StalkerRequestPriority
)
- private class ProviderState {
+ private class ProviderState(now: Long) {
val mutex = Mutex()
val waiters = mutableListOf<Waiter>()
val inFlight = mutableMapOf<String, CompletableDeferred<Any?>>()
@@ -87,11 +120,14 @@ class StalkerRequestCoordinator @Inject constructor(
var rateLimitStrikes = 0
var halfOpenProbeInFlight = false
var networkTokens = NETWORK_TOKEN_CAPACITY
- var lastNetworkRefillAt = System.currentTimeMillis()
+ var lastNetworkRefillAt = now
var nextBackgroundRequestAt = 0L
var interactiveWaiters = 0
var interactiveInFlight = 0
var persistedStateLoaded = false
+ var configurationGeneration = 0L
+ var indexPacing = StalkerAdaptiveIndexPolicy()
+ var lastIndexRequestAt: Long? = null
}
private val states = ConcurrentHashMap<Long, ProviderState>()
@@ -110,7 +146,7 @@ class StalkerRequestCoordinator @Inject constructor(
block: suspend () -> T
): T {
require(providerId > 0L)
- val state = states.computeIfAbsent(providerId) { ProviderState() }
+ val state = states.computeIfAbsent(providerId) { ProviderState(nowMillis()) }
hydratePersistedState(providerId, state)
val requestKey = descriptor.dedupeKey()
val deferred = CompletableDeferred<Any?>()
@@ -128,23 +164,25 @@ class StalkerRequestCoordinator @Inject constructor(
val waiter = Waiter(tickets.incrementAndGet(), priority)
var acquired = false
+ var operationStarted = false
var responseMetrics = StalkerResponseMetrics()
- val startedAt = System.currentTimeMillis()
+ val startedAt = nowMillis()
var outcome = "success"
try {
state.mutex.withLock { state.waiters += waiter }
while (!acquired) {
acquired = state.mutex.withLock {
- val now = System.currentTimeMillis()
+ val now = nowMillis()
val limit = state.currentLimit(now)
val first = state.waiters.minWithOrNull(
compareBy<Waiter>({ it.priority.ordinal }, { it.ticket })
)
val backgroundAllowed = priority != StalkerRequestPriority.BACKGROUND_INDEX ||
- state.activeBackground == 0
+ state.activeBackground < indexExecutionConcurrency
if (first == waiter && state.active < limit && backgroundAllowed) {
state.waiters.remove(waiter)
state.active += 1
+ operationStarted = true
if (priority == StalkerRequestPriority.BACKGROUND_INDEX) state.activeBackground += 1
true
} else {
@@ -153,7 +191,29 @@ class StalkerRequestCoordinator @Inject constructor(
}
if (!acquired) delay(ADMISSION_POLL_MILLIS)
}
- val result = withContext(StalkerRequestPriorityContext(priority)) { block() }
+ val canYieldMetadata = adaptiveIndexingEnabled && priority == StalkerRequestPriority.BACKGROUND_INDEX
+ val result = withContext(StalkerRequestPriorityContext(
+ priority,
+ yieldMetadata = if (canYieldMetadata) ({
+ if (acquired) {
+ state.active -= 1
+ acquired = false
+ state.waiters += waiter
+ }
+ }) else null,
+ resumeMetadata = if (canYieldMetadata) ({
+ if (acquired) true else {
+ val first = state.waiters.minWithOrNull(compareBy<Waiter>({ it.priority.ordinal }, { it.ticket }))
+ if (first == waiter && state.active < state.currentLimit(nowMillis())) {
+ state.waiters.remove(waiter)
+ state.active += 1
+ acquired = true
+ true
+ } else false
+ }
+ }) else null,
+ providerId = providerId
+ )) { block() }
if (result is Result.Error) {
// Catalog loaders return domain Result values rather than throwing. Keep the
// coordinator telemetry honest so an authentication/catalog failure cannot look
@@ -161,7 +221,7 @@ class StalkerRequestCoordinator @Inject constructor(
outcome = "error_${result.exception?.telemetryOutcome() ?: "unknown"}"
}
responseMetrics = metricsOf(result)
- val probeNow = System.currentTimeMillis()
+ val probeNow = nowMillis()
val restored = state.mutex.withLock {
if (state.safeMetadataConcurrency == 1 && state.stressCooldownUntil in 1..probeNow) {
state.safeMetadataConcurrency = NORMAL_METADATA_CONCURRENCY
@@ -183,7 +243,7 @@ class StalkerRequestCoordinator @Inject constructor(
if (error.findRateLimit() != null) {
recordRateLimit(providerId, error.findRateLimit()?.retryAfterMillis)
} else if (error.isProviderStressSignal()) {
- val cooldownUntil = System.currentTimeMillis() + STRESS_COOLDOWN_MILLIS
+ val cooldownUntil = nowMillis() + STRESS_COOLDOWN_MILLIS
state.mutex.withLock {
state.safeMetadataConcurrency = 1
state.stressCooldownUntil = cooldownUntil
@@ -197,12 +257,12 @@ class StalkerRequestCoordinator @Inject constructor(
state.waiters.remove(waiter)
if (acquired) {
state.active = (state.active - 1).coerceAtLeast(0)
- if (priority == StalkerRequestPriority.BACKGROUND_INDEX) {
- state.activeBackground = (state.activeBackground - 1).coerceAtLeast(0)
- }
+ }
+ if (operationStarted && priority == StalkerRequestPriority.BACKGROUND_INDEX) {
+ state.activeBackground = (state.activeBackground - 1).coerceAtLeast(0)
}
if (state.inFlight[requestKey] === deferred) state.inFlight.remove(requestKey)
- val limit = state.currentLimit(System.currentTimeMillis())
+ val limit = state.currentLimit(nowMillis())
StalkerRequestSnapshot(state.active, state.waiters.size, limit, state.stressCooldownUntil)
}
StalkerTelemetry.requestCompleted(
@@ -210,7 +270,7 @@ class StalkerRequestCoordinator @Inject constructor(
priority = priority,
descriptor = descriptor,
responseMetrics = responseMetrics,
- durationMillis = System.currentTimeMillis() - startedAt,
+ durationMillis = nowMillis() - startedAt,
active = finalSnapshot.active,
queued = finalSnapshot.queued,
concurrencyLimit = finalSnapshot.concurrencyLimit,
@@ -223,7 +283,7 @@ class StalkerRequestCoordinator @Inject constructor(
suspend fun snapshot(providerId: Long): StalkerRequestSnapshot {
val state = states[providerId] ?: return StalkerRequestSnapshot(0, 0, 2, 0L)
return state.mutex.withLock {
- val limit = state.currentLimit(System.currentTimeMillis())
+ val limit = state.currentLimit(nowMillis())
StalkerRequestSnapshot(state.active, state.waiters.size, limit, state.stressCooldownUntil)
}
}
@@ -231,9 +291,9 @@ class StalkerRequestCoordinator @Inject constructor(
/** Returns the currently admitted metadata limit after loading persisted portal health. */
suspend fun effectiveConcurrencyLimit(providerId: Long): Int {
if (providerId <= 0L) return NORMAL_METADATA_CONCURRENCY
- val state = states.computeIfAbsent(providerId) { ProviderState() }
+ val state = states.computeIfAbsent(providerId) { ProviderState(nowMillis()) }
hydratePersistedState(providerId, state)
- return state.mutex.withLock { state.currentLimit(System.currentTimeMillis()) }
+ return state.mutex.withLock { state.currentLimit(nowMillis()) }
}
suspend fun recordFailure(providerId: Long, error: Throwable?) {
@@ -243,9 +303,9 @@ class StalkerRequestCoordinator @Inject constructor(
return
}
if (error?.isProviderStressSignal() != true) return
- val state = states.computeIfAbsent(providerId) { ProviderState() }
+ val state = states.computeIfAbsent(providerId) { ProviderState(nowMillis()) }
hydratePersistedState(providerId, state)
- val cooldownUntil = System.currentTimeMillis() + STRESS_COOLDOWN_MILLIS
+ val cooldownUntil = nowMillis() + STRESS_COOLDOWN_MILLIS
state.mutex.withLock {
state.safeMetadataConcurrency = 1
state.stressCooldownUntil = cooldownUntil
@@ -263,15 +323,18 @@ class StalkerRequestCoordinator @Inject constructor(
priority: StalkerNetworkPriority = StalkerNetworkPriority.FOREGROUND
): StalkerNetworkPermit {
if (providerId <= 0L) return StalkerNetworkPermit(providerId, halfOpenProbe = false, priority)
- val state = states.computeIfAbsent(providerId) { ProviderState() }
+ val state = states.computeIfAbsent(providerId) { ProviderState(nowMillis()) }
hydratePersistedState(providerId, state)
+ val metadataContext = currentCoroutineContext()[StalkerRequestPriorityContext]?.takeIf { it.providerId == providerId }
val interactive = priority == StalkerNetworkPriority.INTERACTIVE
- if (interactive) state.mutex.withLock { state.interactiveWaiters += 1 }
+ val protectedForeground = interactive ||
+ (adaptiveIndexingEnabled && priority == StalkerNetworkPriority.FOREGROUND)
+ if (protectedForeground) state.mutex.withLock { state.interactiveWaiters += 1 }
try {
while (true) {
var waitMillis = NETWORK_ADMISSION_POLL_MILLIS
val permit = state.mutex.withLock {
- val now = System.currentTimeMillis()
+ val now = nowMillis()
if (state.rateLimitCooldownUntil > now) {
throw StalkerApiError.RateLimited(
retryAfterMillis = state.rateLimitCooldownUntil - now
@@ -283,9 +346,16 @@ class StalkerRequestCoordinator @Inject constructor(
state.refillNetworkTokens(now)
val lowPriority = priority == StalkerNetworkPriority.PREFETCH ||
- priority == StalkerNetworkPriority.BACKGROUND
+ priority == StalkerNetworkPriority.BACKGROUND || priority == StalkerNetworkPriority.INDEX
val backgroundBlocked = lowPriority &&
(state.interactiveWaiters > 0 || state.interactiveInFlight > 0)
+ val adaptiveIndex = adaptiveIndexingEnabled && priority == StalkerNetworkPriority.INDEX
+ val indexInterval = if (StalkerTrafficCoordinator.isPlaybackActive(providerId)) {
+ maxOf(state.indexPacing.intervalMillis, StalkerAdaptiveIndexPolicy.PLAYBACK_INTERVAL_MILLIS)
+ } else state.indexPacing.intervalMillis
+ val indexWait = if (adaptiveIndex) {
+ state.lastIndexRequestAt?.let { (it + indexInterval - now).coerceAtLeast(0L) } ?: 0L
+ } else 0L
val backgroundWait = if (lowPriority) {
(state.nextBackgroundRequestAt - now).coerceAtLeast(0L)
} else {
@@ -300,14 +370,24 @@ class StalkerRequestCoordinator @Inject constructor(
}
waitMillis = maxOf(
NETWORK_ADMISSION_POLL_MILLIS.takeIf { backgroundBlocked } ?: 0L,
- backgroundWait,
+ maxOf(backgroundWait, indexWait),
tokenWait
)
- if (waitMillis > 0L) return@withLock null
+ if (waitMillis > 0L) {
+ metadataContext?.yieldMetadata?.invoke()
+ return@withLock null
+ }
+ if (metadataContext?.resumeMetadata?.invoke() == false) {
+ waitMillis = NETWORK_ADMISSION_POLL_MILLIS
+ return@withLock null
+ }
- state.networkTokens -= 1.0
- if (lowPriority) {
- val interval = if (priority == StalkerNetworkPriority.BACKGROUND) {
+ // Index admission has its own strict spacing (no burst capacity). It still
+ // waits for foreground tokens and interactive work, but cannot drain them.
+ if (!adaptiveIndex) state.networkTokens -= 1.0
+ if (adaptiveIndex) state.lastIndexRequestAt = now
+ if (lowPriority && !adaptiveIndex) {
+ val interval = if (priority == StalkerNetworkPriority.BACKGROUND || priority == StalkerNetworkPriority.INDEX) {
BACKGROUND_REQUEST_INTERVAL_MILLIS
} else {
PREFETCH_REQUEST_INTERVAL_MILLIS
@@ -316,14 +396,14 @@ class StalkerRequestCoordinator @Inject constructor(
}
val halfOpen = state.rateLimitCooldownUntil > 0L
if (halfOpen) state.halfOpenProbeInFlight = true
- if (interactive) state.interactiveInFlight += 1
- StalkerNetworkPermit(providerId, halfOpen, priority)
+ if (protectedForeground) state.interactiveInFlight += 1
+ StalkerNetworkPermit(providerId, halfOpen, priority, now)
}
if (permit != null) return permit
delay(waitMillis.coerceAtMost(MAX_NETWORK_ADMISSION_SLEEP_MILLIS))
}
} finally {
- if (interactive) {
+ if (protectedForeground) {
state.mutex.withLock {
state.interactiveWaiters = (state.interactiveWaiters - 1).coerceAtLeast(0)
}
@@ -332,13 +412,42 @@ class StalkerRequestCoordinator @Inject constructor(
}
suspend fun releaseNetworkPermit(permit: StalkerNetworkPermit) {
- if (permit.providerId <= 0L || permit.priority != StalkerNetworkPriority.INTERACTIVE) return
+ val protectedForeground = permit.priority == StalkerNetworkPriority.INTERACTIVE ||
+ (adaptiveIndexingEnabled && permit.priority == StalkerNetworkPriority.FOREGROUND)
+ if (permit.providerId <= 0L || !protectedForeground) return
val state = states[permit.providerId] ?: return
state.mutex.withLock {
state.interactiveInFlight = (state.interactiveInFlight - 1).coerceAtLeast(0)
}
}
+ /** One parsed HTTP result per index permit; retries and local circuit rejections do not train health. */
+ internal suspend fun recordIndexResponse(permit: StalkerNetworkPermit, error: Throwable? = null) {
+ if (!adaptiveIndexingEnabled) return
+ // Portal stress on any lane lowers the index rate; only index successes may ramp it up.
+ if (permit.priority != StalkerNetworkPriority.INDEX && error?.isProviderStressSignal() != true) return
+ val state = states[permit.providerId] ?: return
+ state.mutex.withLock {
+ val changed = when {
+ error == null -> state.indexPacing.success(
+ nowMillis(), (nowMillis() - permit.admittedAt).coerceAtLeast(0L),
+ StalkerTrafficCoordinator.isPlaybackActive(permit.providerId)
+ )
+ error.isProviderStressSignal() -> state.indexPacing.stress()
+ else -> { state.indexPacing.resetHealth(); false }
+ }
+ if (changed) {
+ portalStateStore?.recordIndexPacing(
+ permit.providerId, state.configurationGeneration,
+ state.indexPacing.intervalMillis, state.indexPacing.minimumIntervalMillis
+ )
+ StalkerTelemetry.capabilityChanged(
+ permit.providerId, "INDEX_INTERVAL_MILLIS", state.indexPacing.intervalMillis.toString()
+ )
+ }
+ }
+ }
+
suspend fun recordNetworkSuccess(permit: StalkerNetworkPermit) {
if (permit.providerId <= 0L || !permit.halfOpenProbe) return
val state = states[permit.providerId] ?: return
@@ -359,7 +468,7 @@ class StalkerRequestCoordinator @Inject constructor(
}
if (!permit.halfOpenProbe) return
val state = states[permit.providerId] ?: return
- val retryAt = System.currentTimeMillis() + HALF_OPEN_FAILURE_COOLDOWN_MILLIS
+ val retryAt = nowMillis() + HALF_OPEN_FAILURE_COOLDOWN_MILLIS
state.mutex.withLock {
state.rateLimitCooldownUntil = retryAt
state.halfOpenProbeInFlight = false
@@ -369,9 +478,9 @@ class StalkerRequestCoordinator @Inject constructor(
private suspend fun recordRateLimit(providerId: Long, retryAfterMillis: Long?) {
if (providerId <= 0L) return
- val state = states.computeIfAbsent(providerId) { ProviderState() }
+ val state = states.computeIfAbsent(providerId) { ProviderState(nowMillis()) }
hydratePersistedState(providerId, state)
- val now = System.currentTimeMillis()
+ val now = nowMillis()
val cooldownUntil = state.mutex.withLock {
if (state.rateLimitCooldownUntil > now) {
val explicitUntil = retryAfterMillis
@@ -397,7 +506,9 @@ class StalkerRequestCoordinator @Inject constructor(
}
private suspend fun hydratePersistedState(providerId: Long, state: ProviderState) {
- if (state.mutex.withLock { state.persistedStateLoaded }) return
+ if (state.mutex.withLock {
+ state.persistedStateLoaded && (state.configurationGeneration > 0L || portalStateStore == null)
+ }) return
val persisted = portalStateStore?.get(providerId)
state.mutex.withLock {
if (!state.persistedStateLoaded) {
@@ -408,7 +519,14 @@ class StalkerRequestCoordinator @Inject constructor(
state.rateLimitCooldownUntil = persisted
?.let { portalStateStore?.rateLimitCooldownUntil(it) }
?: 0L
+ state.configurationGeneration = persisted?.configurationGeneration ?: 0L
+ if (persisted != null) state.indexPacing = portalStateStore?.indexPacing(persisted) ?: StalkerAdaptiveIndexPolicy()
state.persistedStateLoaded = true
+ } else if (state.configurationGeneration == 0L && (persisted?.configurationGeneration ?: 0L) > 0L) {
+ // The first handshake can precede the authentication learning row. Adopt its
+ // generation once present so the first indexing run can persist its pacing.
+ state.configurationGeneration = requireNotNull(persisted).configurationGeneration
+ state.indexPacing = portalStateStore?.indexPacing(persisted) ?: StalkerAdaptiveIndexPolicy()
}
}
}
@@ -459,6 +577,7 @@ class StalkerRequestCoordinator @Inject constructor(
}
private companion object {
+ const val MAX_INDEX_EXECUTION_CONCURRENCY = 2
const val NORMAL_METADATA_CONCURRENCY = 2
const val ADMISSION_POLL_MILLIS = 20L
const val STRESS_COOLDOWN_MILLIS = 5L * 60L * 1000L
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinator.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinator.kt
index 1250e06e..8ee34451 100644
--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinator.kt
+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinator.kt
@@ -1,5 +1,6 @@
package com.streamvault.data.remote.stalker
+import com.streamvault.data.BuildConfig
import java.util.concurrent.ConcurrentHashMap
internal object StalkerTrafficCoordinator {
@@ -32,13 +33,25 @@ internal object StalkerTrafficCoordinator {
}
/** Playback never blocks interactive requests; only maintenance slows between pages. */
- fun backgroundInterPageDelayMillis(providerId: Long): Long =
+ fun backgroundInterPageDelayMillis(
+ providerId: Long,
+ adaptiveIndexingEnabled: Boolean = BuildConfig.STALKER_ADAPTIVE_INDEXING
+ ): Long =
+ if (adaptiveIndexingEnabled) {
+ // Every wire request, including page-base probes, is paced by network admission.
+ 0L
+ } else
if (isPlaybackActive(providerId)) {
PLAYBACK_BACKGROUND_PAGE_DELAY_MILLIS
} else {
NORMAL_BACKGROUND_PAGE_DELAY_MILLIS
}
+ fun shouldDeferIndexForPlayback(
+ providerId: Long,
+ adaptiveIndexingEnabled: Boolean = BuildConfig.STALKER_ADAPTIVE_INDEXING
+ ): Boolean = !adaptiveIndexingEnabled && isPlaybackActive(providerId)
+
internal fun resetForTests() {
activePlaybackCountsByProvider.clear()
}
diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderContinuationScheduler.kt b/data/src/main/java/com/streamvault/data/sync/ProviderContinuationScheduler.kt
index 9cb73f46..7c25cd84 100644
--- a/data/src/main/java/com/streamvault/data/sync/ProviderContinuationScheduler.kt
+++ b/data/src/main/java/com/streamvault/data/sync/ProviderContinuationScheduler.kt
@@ -15,6 +15,12 @@ internal class ProviderContinuationScheduler(
// through the configuration-edit worker path (fresh providers have no revision row).
workScheduler.scheduleProviderResume(providerId)
}
+ if (work.any { it.operation == SyncContinuationOperation.STALKER_BOOTSTRAP_RESUME }) {
+ check(snapshot.provider.type == ProviderType.STALKER_PORTAL) {
+ "Only Stalker providers can declare a Stalker bootstrap resume"
+ }
+ workScheduler.scheduleStalkerBootstrapResume(providerId)
+ }
val indexWork = work.filter { it.operation == SyncContinuationOperation.INDEX_CATALOG }
when (snapshot.provider.type) {
ProviderType.XTREAM_CODES -> indexWork
diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderSyncPorts.kt b/data/src/main/java/com/streamvault/data/sync/ProviderSyncPorts.kt
index 86b05ec5..21832434 100644
--- a/data/src/main/java/com/streamvault/data/sync/ProviderSyncPorts.kt
+++ b/data/src/main/java/com/streamvault/data/sync/ProviderSyncPorts.kt
@@ -19,6 +19,10 @@ interface ProviderSyncCommands {
suspend fun resumePrimaryCatalog(providerId: Long, trackInitialLiveOnboarding: Boolean): Result<Unit> =
sync(providerId, force = false, trackInitialLiveOnboarding = trackInitialLiveOnboarding)
+ /** Complete Stalker bootstrap in one worker without rebuilding its committed VOD category shells. */
+ suspend fun resumeStalkerBootstrap(providerId: Long): Result<Unit> =
+ resumePrimaryCatalog(providerId, trackInitialLiveOnboarding = false)
+
suspend fun sync(
providerId: Long,
force: Boolean = false,
@@ -126,7 +130,8 @@ interface ProviderSyncCommands {
section: ContentType? = null,
force: Boolean = false,
maxCategoriesPerSection: Int? = null,
- onProgress: ((String) -> Unit)? = null
+ onProgress: ((String) -> Unit)? = null,
+ maxPagesPerSection: Int? = null
): Result<Unit>
suspend fun rebuildXtreamIndex(
diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorkScheduler.kt b/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorkScheduler.kt
index a4d75915..9ac005b7 100644
--- a/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorkScheduler.kt
+++ b/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorkScheduler.kt
@@ -46,6 +46,10 @@ class ProviderSyncWorkScheduler @Inject constructor(
}
}
+ fun scheduleStalkerBootstrapResume(providerId: Long) {
+ ProviderSyncWorker.enqueueStalkerBootstrapResume(applicationContext, providerId)
+ }
+
fun scheduleXtreamIndex(
providerId: Long,
section: ContentType? = null,
diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt b/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt
index 407dc549..7107f0f0 100644
--- a/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt
+++ b/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt
@@ -241,10 +241,14 @@ class ProviderSyncWorker(
onboardingDao = entryPoint.xtreamLiveOnboardingDao()
)
val result = if (requestedProviderId == provider.id) {
- entryPoint.syncCommands().resumePrimaryCatalog(
- provider.id,
- trackInitialLiveOnboarding = trackInitialLiveOnboarding
- )
+ if (inputData.getBoolean(KEY_STALKER_BOOTSTRAP_RESUME, false)) {
+ entryPoint.syncCommands().resumeStalkerBootstrap(provider.id)
+ } else {
+ entryPoint.syncCommands().resumePrimaryCatalog(
+ provider.id,
+ trackInitialLiveOnboarding = trackInitialLiveOnboarding
+ )
+ }
} else if (trackInitialLiveOnboarding) {
// Interrupted setup is recovery, independent of automatic refresh policy.
entryPoint.syncCommands().resumePrimaryCatalog(provider.id, true)
@@ -538,6 +542,7 @@ class ProviderSyncWorker(
private const val UNIQUE_LAUNCH_STALE_WORK_NAME = "provider-sync-launch-stale-check"
private const val KEY_PROVIDER_ID = "provider_id"
private const val KEY_PROVIDER_CONFIG_REVISION = "provider_config_revision"
+ private const val KEY_STALKER_BOOTSTRAP_RESUME = "stalker_bootstrap_resume"
private const val INVALID_PROVIDER_ID = -1L
private const val INVALID_REVISION = -1L
private const val STALE_CONFIG_SYNC_MILLIS = 60_000L
@@ -641,6 +646,35 @@ class ProviderSyncWorker(
)
}
+ fun enqueueStalkerBootstrapResume(context: Context, providerId: Long) {
+ if (providerId <= 0L) return
+ val request = OneTimeWorkRequestBuilder<ProviderSyncWorker>()
+ .setInputData(
+ workDataOf(
+ KEY_PROVIDER_ID to providerId,
+ KEY_STALKER_BOOTSTRAP_RESUME to true
+ )
+ )
+ .setConstraints(
+ Constraints.Builder()
+ .setRequiredNetworkType(NetworkType.CONNECTED)
+ .setRequiresBatteryNotLow(true)
+ .build()
+ )
+ .setBackoffCriteria(
+ BackoffPolicy.EXPONENTIAL,
+ WorkRequest.MIN_BACKOFF_MILLIS,
+ TimeUnit.MILLISECONDS
+ )
+ .build()
+
+ WorkManager.getInstance(context).enqueueUniqueWork(
+ providerWorkUniqueName(providerId),
+ providerWorkExistingPolicy(supersede = false),
+ request
+ )
+ }
+
fun enqueueProviderConfigRevision(
context: Context,
providerId: Long,
diff --git a/data/src/main/java/com/streamvault/data/sync/StalkerCatalogSyncExecutor.kt b/data/src/main/java/com/streamvault/data/sync/StalkerCatalogSyncExecutor.kt
index 17760892..fb8c260c 100644
--- a/data/src/main/java/com/streamvault/data/sync/StalkerCatalogSyncExecutor.kt
+++ b/data/src/main/java/com/streamvault/data/sync/StalkerCatalogSyncExecutor.kt
@@ -251,8 +251,7 @@ internal class StalkerCatalogSyncExecutor(
if (storedCategoryType == ContentType.VOD) ContentType.MOVIE.name else ContentType.VOD.name
)
movieCategoryCount = categories.size
- if (!bootstrap && provider.stalkerCatalogMode == StalkerCatalogMode.BACKGROUND_INDEX
- ) {
+ if (provider.stalkerCatalogMode == StalkerCatalogMode.BACKGROUND_INDEX) {
sectionExecutor.queueIndexSection(provider.id, ContentType.MOVIE, categories.size, now)
}
metadata = metadata.copy(
@@ -303,7 +302,7 @@ internal class StalkerCatalogSyncExecutor(
)
catalogActivated = true
seriesCategoryCount = categories.size
- if (!bootstrap && provider.stalkerCatalogMode == StalkerCatalogMode.BACKGROUND_INDEX) {
+ if (provider.stalkerCatalogMode == StalkerCatalogMode.BACKGROUND_INDEX) {
sectionExecutor.queueIndexSection(provider.id, ContentType.SERIES, categories.size, now)
}
metadata = metadata.copy(
@@ -337,7 +336,12 @@ internal class StalkerCatalogSyncExecutor(
force = force
)
}
- if (bootstrap) {
+ if (bootstrap && provider.stalkerCatalogMode == StalkerCatalogMode.BACKGROUND_INDEX) {
+ continuationWork += SyncContinuation(
+ operation = SyncContinuationOperation.STALKER_BOOTSTRAP_RESUME,
+ reason = "bootstrap category shells are committed; fetch the first VOD page and finish live onboarding"
+ )
+ } else if (bootstrap) {
continuationWork += SyncContinuation(
operation = SyncContinuationOperation.FULL_CATALOG,
reason = "bootstrap catalog is committed; durable full provider sync is queued",
diff --git a/data/src/main/java/com/streamvault/data/sync/StalkerIncrementalIndexExecutor.kt b/data/src/main/java/com/streamvault/data/sync/StalkerIncrementalIndexExecutor.kt
index cf21a857..647aecdb 100644
--- a/data/src/main/java/com/streamvault/data/sync/StalkerIncrementalIndexExecutor.kt
+++ b/data/src/main/java/com/streamvault/data/sync/StalkerIncrementalIndexExecutor.kt
@@ -1,5 +1,6 @@
package com.streamvault.data.sync
+import com.streamvault.data.BuildConfig
import com.streamvault.data.local.entity.CategoryEntity
import com.streamvault.data.local.entity.StalkerIndexJobEntity
import com.streamvault.data.remote.stalker.StalkerPagedResult
@@ -52,6 +53,9 @@ internal interface StalkerIncrementalIndexOperations {
suspend fun currentIndexedRowCount(providerId: Long, contentType: ContentType): Int
+ /** Local indexed row count per category id; used to find categories the wildcard walk did not cover. */
+ suspend fun categoriesWithLocalRows(providerId: Long, contentType: ContentType): Map<Long, Int>
+
suspend fun pruneStaleRows(providerId: Long, contentType: ContentType): Int
suspend fun updateSummaryMetadata(
@@ -156,14 +160,22 @@ internal interface StalkerIncrementalIndexOperations {
* handling, and page-level catalog commits.
*/
internal class StalkerIncrementalIndexExecutor(
- private val operations: StalkerIncrementalIndexOperations
+ private val operations: StalkerIncrementalIndexOperations,
+ configuredWildcardPageConcurrency: Int = if (BuildConfig.STALKER_ADAPTIVE_INDEXING) {
+ BuildConfig.STALKER_INDEX_PAGE_CONCURRENCY
+ } else {
+ 1
+ }
) {
+ private val wildcardPageConcurrency = configuredWildcardPageConcurrency.coerceIn(1, 2)
+
suspend fun processSummary(
provider: Provider,
api: StalkerProvider,
contentType: ContentType,
maxCategories: Int,
- onProgress: ((String) -> Unit)?
+ onProgress: ((String) -> Unit)?,
+ maxPages: Int? = null
) {
require(contentType == ContentType.MOVIE || contentType == ContentType.SERIES) {
"Unsupported Stalker summary index section: $contentType"
@@ -205,35 +217,57 @@ internal class StalkerIncrementalIndexExecutor(
else -> null
}
}
- if (
- wildcardCategory != null &&
- learnedWildcardSupport != false &&
- visibleCategories.size == 1 &&
- visibleCategories.first().categoryId == wildcardCategory.categoryId
- ) {
+ var categoryPlan = visibleCategories
+ if (wildcardCategory != null && learnedWildcardSupport != false) {
+ val wildcardIsSoleCategory = visibleCategories.size == 1 &&
+ visibleCategories.first().categoryId == wildcardCategory.categoryId
StalkerTelemetry.strategySelected(
provider.id,
"${contentType.name}_WILDCARD",
- if (learnedWildcardSupport == true) "VALIDATED_CACHE" else "CAPABILITY_PROBE"
+ when {
+ learnedWildcardSupport == true -> "VALIDATED_CACHE"
+ wildcardIsSoleCategory -> "CAPABILITY_PROBE"
+ else -> "EXPLICIT_CATEGORY_PROBE"
+ }
+ )
+ val outcome = processWildcard(
+ provider = provider,
+ api = api,
+ contentType = contentType,
+ wildcardCategory = wildcardCategory,
+ visibleCategories = allVisibleCategories,
+ maxPages = maxPages?.coerceAtLeast(1) ?: STALKER_INCREMENTAL_WILDCARD_PAGE_SLICE_SIZE,
+ initialJob = initialJob,
+ onProgress = onProgress
)
- if (processWildcard(
+ outcome.capabilitySupported?.let { supported ->
+ api.recordWildcardCapability(contentType, supported)
+ }
+ if (!outcome.shouldFallback) {
+ if (!outcome.complete) return
+ val backfill = wildcardBackfillCategories(
provider = provider,
api = api,
contentType = contentType,
- wildcardCategory = wildcardCategory,
- visibleCategories = allVisibleCategories,
- maxPages = STALKER_INCREMENTAL_WILDCARD_PAGE_SLICE_SIZE,
- initialJob = initialJob,
- onProgress = onProgress
- )) {
- api.recordWildcardCapability(contentType, supported = true)
- return
+ visibleCategories = visibleCategories
+ )
+ if (backfill.isEmpty()) {
+ if (!wildcardIsSoleCategory) {
+ operations.pruneStaleRows(provider.id, contentType)
+ }
+ return
+ }
+ operations.log(
+ "Stalker ${contentType.name} wildcard index complete for provider ${provider.id}; " +
+ "backfilling ${backfill.size} categories without wildcard rows."
+ )
+ categoryPlan = backfill
}
} else if (wildcardCategory != null && learnedWildcardSupport == false) {
StalkerTelemetry.strategySelected(provider.id, "${contentType.name}_CATEGORY", "WILDCARD_KNOWN_UNSUPPORTED")
}
- val hydrationByCategory = visibleCategories.associate { category ->
+ val hydrationByCategory = categoryPlan.associate { category ->
category.categoryId to operations.getHydration(provider.id, contentType, category.categoryId)
}
val completedBefore = hydrationByCategory.values.count { it?.isComplete == true }
@@ -244,7 +278,7 @@ internal class StalkerIncrementalIndexExecutor(
section = contentType.name,
state = "RUNNING",
now = now,
- totalCategories = visibleCategories.size,
+ totalCategories = categoryPlan.size,
completedCategories = completedBefore,
failedCategories = failedBefore,
indexedRows = indexedBefore,
@@ -255,7 +289,7 @@ internal class StalkerIncrementalIndexExecutor(
var restoreMovieWatchProgressPending = false
try {
val pending = buildList {
- visibleCategories.forEach { category ->
+ categoryPlan.forEach { category ->
if (size >= maxCategories) return@forEach
val hydration = hydrationByCategory[category.categoryId]
if (!canAttempt(hydration, now)) return@forEach
@@ -299,7 +333,11 @@ internal class StalkerIncrementalIndexExecutor(
val pendingQueue = ArrayDeque(pending)
var forceSequential = parallelFetchLimit <= 1
val retriedImmediately = mutableSetOf<Long>()
- while (pendingQueue.isNotEmpty() && System.currentTimeMillis() < runDeadlineAt) {
+ while (
+ pendingQueue.isNotEmpty() &&
+ System.currentTimeMillis() < runDeadlineAt &&
+ (maxPages == null || pagesCommitted < maxPages.coerceAtLeast(1))
+ ) {
if (pagesCommitted > 0) {
delay(StalkerTrafficCoordinator.backgroundInterPageDelayMillis(provider.id))
}
@@ -396,6 +434,7 @@ internal class StalkerIncrementalIndexExecutor(
)
continue
}
+ if (nextPage == 1) api.recordVodPageSize(contentType, result.data.pageSize)
val dedupedItems = StalkerIndexPolicy.dedupePageItems(result.data.items, contentType)
skippedMalformedRows += (result.data.items.size - dedupedItems.size).coerceAtLeast(0)
successfulPages += SuccessfulPage(
@@ -516,7 +555,7 @@ internal class StalkerIncrementalIndexExecutor(
}
}
- val refreshedHydration = visibleCategories.associate { category ->
+ val refreshedHydration = categoryPlan.associate { category ->
category.categoryId to operations.getHydration(provider.id, contentType, category.categoryId)
}
val finishedAt = System.currentTimeMillis()
@@ -546,7 +585,7 @@ internal class StalkerIncrementalIndexExecutor(
section = contentType.name,
state = finalState,
now = finishedAt,
- totalCategories = visibleCategories.size,
+ totalCategories = categoryPlan.size,
completedCategories = completedCategories,
nextCategoryIndex = completedCategories,
failedCategories = failedCategories,
@@ -571,6 +610,12 @@ internal class StalkerIncrementalIndexExecutor(
}
}
+ private data class WildcardRunOutcome(
+ val shouldFallback: Boolean = false,
+ val complete: Boolean = false,
+ val capabilitySupported: Boolean? = null
+ )
+
private suspend fun processWildcard(
provider: Provider,
api: StalkerProvider,
@@ -580,7 +625,7 @@ internal class StalkerIncrementalIndexExecutor(
maxPages: Int,
initialJob: StalkerIndexJobEntity?,
onProgress: ((String) -> Unit)?
- ): Boolean {
+ ): WildcardRunOutcome {
val now = System.currentTimeMillis()
val normalVisibleCategoryIds = mutableSetOf<Long>()
visibleCategories.forEach { category ->
@@ -590,7 +635,16 @@ internal class StalkerIncrementalIndexExecutor(
}
val visibleCategoryIds = normalVisibleCategoryIds.takeIf { it.isNotEmpty() }
val hydration = operations.getHydration(provider.id, contentType, wildcardCategory.categoryId)
- if (!canAttempt(hydration, now)) return false
+ if (hydration?.isComplete == true) {
+ return WildcardRunOutcome(complete = true, capabilitySupported = true)
+ }
+ if (hydration?.isTerminalFailure == true) {
+ return WildcardRunOutcome(shouldFallback = true, capabilitySupported = false)
+ }
+ if (hydration?.isTruncated == true) {
+ return WildcardRunOutcome(shouldFallback = true, capabilitySupported = true)
+ }
+ if (!canAttempt(hydration, now)) return WildcardRunOutcome()
upsertIndexJob(
providerId = provider.id,
@@ -613,6 +667,7 @@ internal class StalkerIncrementalIndexExecutor(
var restoreMovieWatchProgressPending = false
var indexedRowsEstimate = operations.currentIndexedRowCount(provider.id, contentType)
val sectionStartedAt = System.currentTimeMillis()
+ var capabilityProven = (hydration?.lastSuccessfulPage ?: 0) > 0
try {
while (pagesProcessed < maxPages) {
@@ -622,154 +677,202 @@ internal class StalkerIncrementalIndexExecutor(
val currentHydration = operations.getHydration(provider.id, contentType, wildcardCategory.categoryId)
if (!canAttempt(currentHydration, System.currentTimeMillis())) break
val nextPage = nextAttemptPage(currentHydration)
- operations.progress(provider.id, onProgress, "Indexing ${indexSectionLabel(contentType)}: All page $nextPage")
- operations.markAttemptStarted(
- providerId = provider.id,
- contentType = contentType,
- categoryId = wildcardCategory.categoryId,
- hydration = currentHydration,
- attemptedPage = nextPage,
- now = System.currentTimeMillis()
- )
- val coordinatedResult = operations.fetchWildcardPage(
- provider = provider,
- api = api,
- contentType = contentType,
- categoryId = wildcardCategory.categoryId,
- page = nextPage
- )
- if (coordinatedResult is Result.Error) {
- operations.recordRequestFailure(provider.id, coordinatedResult.exception)
+ val windowSize = minOf(
+ wildcardPageConcurrency,
+ maxPages - pagesProcessed,
+ STALKER_INCREMENTAL_MAX_PARALLEL_CATEGORY_FETCHES
+ ).coerceAtLeast(1)
+ val requestedPages = (nextPage until nextPage + windowSize).toList()
+ requestedPages.forEach { page ->
+ operations.progress(
+ provider.id,
+ onProgress,
+ "Indexing ${indexSectionLabel(contentType)}: All page $page"
+ )
}
- when (val result = coordinatedResult) {
- is Result.Success -> {
- val indexedAt = System.currentTimeMillis()
- val dedupedItems = StalkerIndexPolicy.dedupePageItems(result.data.items, contentType)
- val visibleItems = StalkerIndexPolicy.filterToVisibleCategories(
- dedupedItems,
- contentType,
- visibleCategoryIds
- )
- skippedMalformedRows += (result.data.items.size - visibleItems.size).coerceAtLeast(0)
- if (nextPage == 1 && visibleItems.isEmpty()) {
- val message = "Stalker wildcard catalog did not return usable visible ${indexSectionLabel(contentType)} rows."
- operations.markAttemptFailed(
- providerId = provider.id,
+ val fetchedPages = coroutineScope {
+ requestedPages.map { page ->
+ async {
+ val result = operations.fetchWildcardPage(
+ provider = provider,
+ api = api,
contentType = contentType,
categoryId = wildcardCategory.categoryId,
- hydration = currentHydration,
- attemptedPage = nextPage,
- now = indexedAt,
- message = message,
- retryable = false,
- pageFingerprint = null
+ page = page
)
- operations.log("$message Falling back to per-category indexing for provider ${provider.id}.")
- api.recordWildcardCapability(contentType, supported = false)
- return false
+ if (result is Result.Error) {
+ // Apply a 429 cooldown as soon as any concurrent request reports it,
+ // rather than waiting for slower siblings in this window to finish.
+ operations.recordRequestFailure(provider.id, result.exception)
+ }
+ page to result
}
+ }.awaitAll()
+ }.sortedBy { (page, _) -> page }
+
+ var stopAfterWindow = false
+ for ((requestedPage, coordinatedResult) in fetchedPages) {
+ val checkpoint = operations.getHydration(provider.id, contentType, wildcardCategory.categoryId)
+ if (!canAttempt(checkpoint, System.currentTimeMillis())) {
+ stopAfterWindow = true
+ break
+ }
+ if (nextAttemptPage(checkpoint) != requestedPage) {
+ operations.log(
+ "Discarding uncommitted Stalker wildcard page $requestedPage for provider ${provider.id}; " +
+ "the durable checkpoint now expects page ${nextAttemptPage(checkpoint)}."
+ )
+ stopAfterWindow = true
+ break
+ }
+ operations.markAttemptStarted(
+ providerId = provider.id,
+ contentType = contentType,
+ categoryId = wildcardCategory.categoryId,
+ hydration = checkpoint,
+ attemptedPage = requestedPage,
+ now = System.currentTimeMillis()
+ )
+ when (val result = coordinatedResult) {
+ is Result.Success -> {
+ val indexedAt = System.currentTimeMillis()
+ val dedupedItems = StalkerIndexPolicy.dedupePageItems(result.data.items, contentType)
+ val visibleItems = StalkerIndexPolicy.filterToVisibleCategories(
+ dedupedItems,
+ contentType,
+ visibleCategoryIds
+ )
+ skippedMalformedRows += (result.data.items.size - visibleItems.size).coerceAtLeast(0)
+ if (requestedPage == 1 && visibleItems.isEmpty()) {
+ val message = "Stalker wildcard catalog did not return usable visible ${indexSectionLabel(contentType)} rows."
+ operations.markAttemptFailed(
+ providerId = provider.id,
+ contentType = contentType,
+ categoryId = wildcardCategory.categoryId,
+ hydration = checkpoint,
+ attemptedPage = requestedPage,
+ now = indexedAt,
+ message = message,
+ retryable = false,
+ pageFingerprint = null
+ )
+ operations.log("$message Falling back to per-category indexing for provider ${provider.id}.")
+ return WildcardRunOutcome(shouldFallback = true, capabilitySupported = false)
+ }
- val pageFingerprint = StalkerIndexPolicy.pageFingerprint(visibleItems, contentType)
- val anomaly = StalkerIndexPolicy.detectPageAnomaly(
- hydration = currentHydration,
- requestedPage = nextPage,
- pagedResult = StalkerPagedResult(
- items = visibleItems,
- page = result.data.page,
+ val pageFingerprint = StalkerIndexPolicy.pageFingerprint(visibleItems, contentType)
+ val anomaly = StalkerIndexPolicy.detectPageAnomaly(
+ hydration = checkpoint,
+ requestedPage = requestedPage,
+ pagedResult = StalkerPagedResult(
+ items = visibleItems,
+ page = result.data.page,
+ totalPages = result.data.totalPages,
+ pageSize = result.data.pageSize,
+ advertisedTotalItems = result.data.advertisedTotalItems,
+ advertisedTotalPages = result.data.advertisedTotalPages,
+ hasAdvertisedTotal = result.data.hasAdvertisedTotal,
+ isTruncated = result.data.isTruncated,
+ terminationReason = result.data.terminationReason
+ ),
+ pageFingerprint = pageFingerprint
+ ) ?: pageFingerprint
+ ?.takeIf { !seenPageFingerprints.add(it) }
+ ?.let { "Portal repeated a wildcard page payload." }
+
+ if (anomaly != null) {
+ operations.markAttemptFailed(
+ providerId = provider.id,
+ contentType = contentType,
+ categoryId = wildcardCategory.categoryId,
+ hydration = checkpoint,
+ attemptedPage = requestedPage,
+ now = indexedAt,
+ message = anomaly,
+ retryable = false,
+ pageFingerprint = pageFingerprint
+ )
+ operations.log("Stalker wildcard ${contentType.name} indexing disabled for provider ${provider.id}: $anomaly")
+ return WildcardRunOutcome(shouldFallback = true, capabilitySupported = false)
+ }
+
+ if (requestedPage == 1) api.recordVodPageSize(contentType, result.data.pageSize)
+ when (contentType) {
+ ContentType.MOVIE -> operations.upsertMovieSummaryBatch(
+ provider.id,
+ visibleItems.filterIsInstance<Movie>(),
+ indexedAt
+ )
+ ContentType.SERIES -> operations.upsertSeriesSummaryBatch(
+ provider.id,
+ visibleItems.filterIsInstance<Series>(),
+ indexedAt
+ )
+ else -> Unit
+ }
+ if (contentType == ContentType.MOVIE && visibleItems.isNotEmpty()) {
+ restoreMovieWatchProgressPending = true
+ }
+ indexedRowsEstimate += visibleItems.size
+ rowsCommitted += visibleItems.size
+ val pageComplete = !result.data.isTruncated && (
+ result.data.isComplete ||
+ (result.data.items.isEmpty() && result.data.totalPages in 1..requestedPage)
+ )
+ operations.markAttemptSucceeded(
+ providerId = provider.id,
+ contentType = contentType,
+ categoryId = wildcardCategory.categoryId,
+ hydration = checkpoint,
+ attemptedPage = requestedPage,
+ now = indexedAt,
+ itemCount = indexedRowsEstimate,
totalPages = result.data.totalPages,
pageSize = result.data.pageSize,
advertisedTotalItems = result.data.advertisedTotalItems,
advertisedTotalPages = result.data.advertisedTotalPages,
- hasAdvertisedTotal = result.data.hasAdvertisedTotal,
- isTruncated = result.data.isTruncated,
- terminationReason = result.data.terminationReason
- ),
- pageFingerprint = pageFingerprint
- ) ?: pageFingerprint
- ?.takeIf { !seenPageFingerprints.add(it) }
- ?.let { "Portal repeated a wildcard page payload." }
-
- if (anomaly != null) {
+ pageComplete = pageComplete,
+ truncated = result.data.isTruncated,
+ terminationReason = result.data.terminationReason,
+ pageFingerprint = pageFingerprint
+ )
+ capabilityProven = true
+ pagesProcessed += 1
+ if (pageComplete || result.data.isTruncated) {
+ stopAfterWindow = true
+ break
+ }
+ }
+ is Result.Error -> {
+ val failedAt = System.currentTimeMillis()
+ lastError = result.message
+ val retryable = operations.failureState(
+ result.exception ?: IllegalStateException(result.message)
+ ) != "FAILED_PERMANENT"
operations.markAttemptFailed(
providerId = provider.id,
contentType = contentType,
categoryId = wildcardCategory.categoryId,
- hydration = currentHydration,
- attemptedPage = nextPage,
- now = indexedAt,
- message = anomaly,
- retryable = false,
- pageFingerprint = pageFingerprint
- )
- operations.log("Stalker wildcard ${contentType.name} indexing disabled for provider ${provider.id}: $anomaly")
- api.recordWildcardCapability(contentType, supported = false)
- return false
- }
-
- when (contentType) {
- ContentType.MOVIE -> operations.upsertMovieSummaryBatch(
- provider.id,
- visibleItems.filterIsInstance<Movie>(),
- indexedAt
- )
- ContentType.SERIES -> operations.upsertSeriesSummaryBatch(
- provider.id,
- visibleItems.filterIsInstance<Series>(),
- indexedAt
+ hydration = checkpoint,
+ attemptedPage = requestedPage,
+ now = failedAt,
+ message = result.message,
+ retryable = retryable,
+ pageFingerprint = checkpoint?.lastPageFingerprint
)
- else -> Unit
+ if (!retryable) {
+ return WildcardRunOutcome(shouldFallback = true, capabilitySupported = false)
+ }
+ stopAfterWindow = true
+ break
}
- if (contentType == ContentType.MOVIE && visibleItems.isNotEmpty()) {
- restoreMovieWatchProgressPending = true
+ is Result.Loading -> {
+ stopAfterWindow = true
+ break
}
- indexedRowsEstimate += visibleItems.size
- rowsCommitted += visibleItems.size
- val pageComplete = !result.data.isTruncated && (
- result.data.isComplete ||
- (result.data.items.isEmpty() && result.data.totalPages in 1..nextPage)
- )
- operations.markAttemptSucceeded(
- providerId = provider.id,
- contentType = contentType,
- categoryId = wildcardCategory.categoryId,
- hydration = currentHydration,
- attemptedPage = nextPage,
- now = indexedAt,
- itemCount = indexedRowsEstimate,
- totalPages = result.data.totalPages,
- pageSize = result.data.pageSize,
- advertisedTotalItems = result.data.advertisedTotalItems,
- advertisedTotalPages = result.data.advertisedTotalPages,
- pageComplete = pageComplete,
- truncated = result.data.isTruncated,
- terminationReason = result.data.terminationReason,
- pageFingerprint = pageFingerprint
- )
- pagesProcessed += 1
- if (pageComplete || result.data.isTruncated) break
- }
- is Result.Error -> {
- val failedAt = System.currentTimeMillis()
- lastError = result.message
- val retryable = operations.failureState(
- result.exception ?: IllegalStateException(result.message)
- ) != "FAILED_PERMANENT"
- operations.markAttemptFailed(
- providerId = provider.id,
- contentType = contentType,
- categoryId = wildcardCategory.categoryId,
- hydration = currentHydration,
- attemptedPage = nextPage,
- now = failedAt,
- message = result.message,
- retryable = retryable,
- pageFingerprint = currentHydration?.lastPageFingerprint
- )
- api.recordWildcardCapability(contentType, supported = false)
- return false
}
- is Result.Loading -> Unit
}
+ if (stopAfterWindow) break
}
val finishedAt = System.currentTimeMillis()
@@ -783,7 +886,7 @@ internal class StalkerIncrementalIndexExecutor(
refreshedHydration?.hasPruneSuppressionRisk == true -> "PARTIAL"
else -> "SUCCESS"
}
- val deletedRows = if (finalState == "SUCCESS") {
+ val deletedRows = if (finalState == "SUCCESS" && normalVisibleCategoryIds.isEmpty()) {
operations.pruneStaleRows(provider.id, contentType)
} else {
0
@@ -809,7 +912,10 @@ internal class StalkerIncrementalIndexExecutor(
operations.log(
"Stalker wildcard ${contentType.name} indexing finished for provider ${provider.id}: state=$finalState pages=$pagesProcessed rows=$rowsCommitted totalRows=$indexedRows throughput=${throughputSummary(sectionStartedAt, pagesProcessed, rowsCommitted)}"
)
- return true
+ return WildcardRunOutcome(
+ complete = finalState == "SUCCESS",
+ capabilitySupported = capabilityProven
+ )
} finally {
if (contentType == ContentType.MOVIE && restoreMovieWatchProgressPending) {
operations.restoreMovieWatchProgress(provider.id)
@@ -817,6 +923,20 @@ internal class StalkerIncrementalIndexExecutor(
}
}
+ private suspend fun wildcardBackfillCategories(
+ provider: Provider,
+ api: StalkerProvider,
+ contentType: ContentType,
+ visibleCategories: List<CategoryEntity>
+ ): List<CategoryEntity> {
+ val normalCategories = visibleCategories.filterNot { category ->
+ api.isWildcardCategory(category.type, category.categoryId)
+ }
+ if (normalCategories.isEmpty()) return emptyList()
+ val localRows = operations.categoriesWithLocalRows(provider.id, contentType)
+ return StalkerIndexPolicy.wildcardBackfillCategories(normalCategories, localRows)
+ }
+
private fun canAttempt(hydration: StalkerHydrationSnapshot?, now: Long): Boolean =
StalkerIndexPolicy.canAttempt(hydration, now)
diff --git a/data/src/main/java/com/streamvault/data/sync/StalkerIncrementalIndexOperationsAdapter.kt b/data/src/main/java/com/streamvault/data/sync/StalkerIncrementalIndexOperationsAdapter.kt
index 8c638605..a9fe174e 100644
--- a/data/src/main/java/com/streamvault/data/sync/StalkerIncrementalIndexOperationsAdapter.kt
+++ b/data/src/main/java/com/streamvault/data/sync/StalkerIncrementalIndexOperationsAdapter.kt
@@ -17,6 +17,7 @@ internal data class StalkerIncrementalIndexCallbacks(
val getJob: suspend (Long, ContentType) -> StalkerIndexJobEntity?,
val getHydration: suspend (Long, ContentType, Long) -> StalkerHydrationSnapshot?,
val currentIndexedRowCount: suspend (Long, ContentType) -> Int,
+ val categoriesWithLocalRows: suspend (Long, ContentType) -> Map<Long, Int>,
val pruneStaleRows: suspend (Long, ContentType) -> Int,
val updateSummaryMetadata: suspend (Long, ContentType, Int, String, Long) -> Unit,
val fetchSummaryPage: suspend (Provider, StalkerProvider, ContentType, Long, Int) -> Result<StalkerPagedResult<out Any>>,
@@ -88,6 +89,11 @@ internal class CallbackStalkerIncrementalIndexOperations(
override suspend fun currentIndexedRowCount(providerId: Long, contentType: ContentType): Int =
callbacks.currentIndexedRowCount(providerId, contentType)
+ override suspend fun categoriesWithLocalRows(
+ providerId: Long,
+ contentType: ContentType
+ ): Map<Long, Int> = callbacks.categoriesWithLocalRows(providerId, contentType)
+
override suspend fun pruneStaleRows(providerId: Long, contentType: ContentType): Int =
callbacks.pruneStaleRows(providerId, contentType)
diff --git a/data/src/main/java/com/streamvault/data/sync/StalkerIndexPolicy.kt b/data/src/main/java/com/streamvault/data/sync/StalkerIndexPolicy.kt
index d5404500..05d3259b 100644
--- a/data/src/main/java/com/streamvault/data/sync/StalkerIndexPolicy.kt
+++ b/data/src/main/java/com/streamvault/data/sync/StalkerIndexPolicy.kt
@@ -1,5 +1,6 @@
package com.streamvault.data.sync
+import com.streamvault.data.local.entity.CategoryEntity
import com.streamvault.data.remote.stalker.StalkerVodCatalogItem
import com.streamvault.data.remote.stalker.StalkerPagedResult
import com.streamvault.domain.model.CatalogLayout
@@ -202,6 +203,18 @@ internal object StalkerIndexPolicy {
return sha1Hex(seeds.joinToString("|"))
}
+ /**
+ * Categories the wildcard walk did not cover locally: they have no indexed rows after the
+ * sweep (adult-excluded categories, or genuinely empty ones) and need a targeted
+ * per-category backfill.
+ */
+ fun wildcardBackfillCategories(
+ normalCategories: List<CategoryEntity>,
+ localRowCounts: Map<Long, Int>
+ ): List<CategoryEntity> = normalCategories.filter { category ->
+ (localRowCounts[category.categoryId] ?: 0) == 0
+ }
+
fun dedupePageItems(items: List<out Any>, contentType: ContentType): List<out Any> {
val classified = items.filterIsInstance<StalkerVodCatalogItem>()
if (classified.isNotEmpty()) return classified.distinctBy(StalkerVodCatalogItem::rawItemId)
diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
index ee49494c..5687b7c1 100644
--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
@@ -295,6 +295,22 @@ class SyncManager @Inject constructor(
getJob = { providerId, contentType -> stalkerIndexJobStore.get(providerId, contentType) },
getHydration = stalkerIndexCheckpointStore::getHydrationSnapshot,
currentIndexedRowCount = ::currentStalkerIndexedRowCount,
+ categoriesWithLocalRows = { providerId, contentType ->
+ val counts = mutableMapOf<Long, Int>()
+ if (contentType == ContentType.MOVIE) {
+ movieDao.getCategoryCounts(providerId).first().forEach { count ->
+ counts[count.categoryId] = (counts[count.categoryId] ?: 0) + count.item_count
+ }
+ seriesDao.getCategoryCounts(providerId).first().forEach { count ->
+ counts[count.categoryId] = (counts[count.categoryId] ?: 0) + count.item_count
+ }
+ } else if (contentType == ContentType.SERIES) {
+ seriesDao.getCategoryCounts(providerId).first().forEach { count ->
+ counts[count.categoryId] = (counts[count.categoryId] ?: 0) + count.item_count
+ }
+ }
+ counts
+ },
pruneStaleRows = { providerId, contentType ->
inFencedStalkerIndexTransaction(providerId) {
xtreamContentIndexDao.pruneStaleLocalContentRows(providerId, contentType.name)
@@ -1226,6 +1242,39 @@ class SyncManager @Inject constructor(
override suspend fun resumePrimaryCatalog(providerId: Long, trackInitialLiveOnboarding: Boolean): Result<Unit> =
syncProviderInternal(providerId, false, null, null, null, trackInitialLiveOnboarding, null, null, false, resumeOnly = true)
+ override suspend fun resumeStalkerBootstrap(providerId: Long): Result<Unit> {
+ val provider = loadCompatibilityProvider(providerId)
+ ?: return Result.error("Provider $providerId has no typed configuration")
+ if (provider.type != ProviderType.STALKER_PORTAL) {
+ return Result.error("Provider $providerId is not a Stalker portal")
+ }
+
+ val firstPage = processQueuedStalkerIndexJobs(
+ providerId = providerId,
+ force = false,
+ maxCategoriesPerSection = 1,
+ maxPagesPerSection = 1
+ )
+ if (firstPage is Result.Error) {
+ Log.w(TAG, "Initial Stalker VOD page could not be indexed for provider $providerId: ${firstPage.message}")
+ scheduleStalkerIndexSync(providerId, section = null, force = false)
+ }
+
+ val live = syncSection(
+ providerId = providerId,
+ section = SyncRepairSection.LIVE
+ )
+ if (live is Result.Error) return live
+ if (live is Result.Loading) return Result.error("Stalker live bootstrap resume did not complete")
+
+ when (provider.epgSyncMode) {
+ ProviderEpgSyncMode.UPFRONT -> return syncEpg(providerId = providerId, force = true, onProgress = null)
+ ProviderEpgSyncMode.BACKGROUND -> scheduleBackgroundEpgSync(providerId)
+ ProviderEpgSyncMode.SKIP -> Unit
+ }
+ return Result.success(Unit)
+ }
+
private suspend fun syncProviderInternal(
providerId: Long,
force: Boolean,
@@ -1709,10 +1758,11 @@ class SyncManager @Inject constructor(
section: ContentType?,
force: Boolean,
maxCategoriesPerSection: Int?,
- onProgress: ((String) -> Unit)?
+ onProgress: ((String) -> Unit)?,
+ maxPagesPerSection: Int?
): com.streamvault.domain.model.Result<Unit> {
return withStalkerSummaryLock(providerId, section) lock@{
- val playbackDelayMillis = if (StalkerTrafficCoordinator.isPlaybackActive(providerId)) 2_000L else 0L
+ val playbackDelayMillis = if (StalkerTrafficCoordinator.shouldDeferIndexForPlayback(providerId)) 2_000L else 0L
if (playbackDelayMillis > 0L) {
Log.i(TAG, "Deferring Stalker catalog work for provider $providerId because playback is active.")
scheduleStalkerIndexSync(
@@ -1772,7 +1822,8 @@ class SyncManager @Inject constructor(
api = api,
contentType = contentType,
maxCategories = categoryLimit,
- onProgress = onProgress
+ onProgress = onProgress,
+ maxPages = maxPagesPerSection
)
}.exceptionOrNull()
if (failure != null) {
@@ -1868,7 +1919,7 @@ class SyncManager @Inject constructor(
): Result<com.streamvault.data.remote.stalker.StalkerPagedResult<out Any>> {
suspend fun fetch(): Result<com.streamvault.data.remote.stalker.StalkerPagedResult<out Any>> =
if (contentType == ContentType.MOVIE && provider.catalogLayout == CatalogLayout.UNIFIED_VOD) {
- api.getUnifiedVodPage(categoryId, page)
+ api.getUnifiedVodPage(categoryId, page, sortBy = StalkerProvider.WILDCARD_INDEX_SORT)
} else {
fetchStalkerWildcardSummaryPage(api, contentType, categoryId, page)
}
diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManagerSupport.kt b/data/src/main/java/com/streamvault/data/sync/SyncManagerSupport.kt
index 6d2f288c..79c53238 100644
--- a/data/src/main/java/com/streamvault/data/sync/SyncManagerSupport.kt
+++ b/data/src/main/java/com/streamvault/data/sync/SyncManagerSupport.kt
@@ -30,6 +30,7 @@ internal data class SyncContinuation(
internal enum class SyncContinuationOperation {
FULL_CATALOG,
+ STALKER_BOOTSTRAP_RESUME,
INDEX_CATALOG,
REFRESH_GUIDE
}
diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiServiceTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiServiceTest.kt
index 5c19a41a..1bece290 100644
--- a/data/src/test/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiServiceTest.kt
+++ b/data/src/test/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiServiceTest.kt
@@ -1959,6 +1959,75 @@ class OkHttpStalkerApiServiceTest {
assertThat((result as Result.Success).data.page).isEqualTo(0)
}
+ @Test
+ fun getVodStreamsPageAtPortalPage_forwards_sortby_ordering_hint() = runTest {
+ var requestedSortBy: String? = null
+ val service = OkHttpStalkerApiService(
+ okHttpClient = OkHttpClient.Builder()
+ .addInterceptor { chain ->
+ requestedSortBy = chain.request().url.queryParameter("sortby")
+ Response.Builder()
+ .request(chain.request())
+ .protocol(Protocol.HTTP_1_1)
+ .code(200)
+ .message("OK")
+ .body(
+ """{"js":{"total_items":1,"max_page_items":14,"data":[{"id":"1","name":"Newest","category_id":"42","cmd":"ffmpeg http://example.com/movie.mp4"}]}}"""
+ .toResponseBody("application/json".toMediaType())
+ )
+ .build()
+ }
+ .build(),
+ json = Json { ignoreUnknownKeys = true }
+ )
+
+ val result = service.getVodStreamsPageAtPortalPage(
+ stalkerSession(),
+ stalkerProfile(),
+ categoryId = "*",
+ portalPage = 1,
+ searchQuery = null,
+ sortBy = "added"
+ )
+
+ assertThat(result).isInstanceOf(Result.Success::class.java)
+ assertThat(requestedSortBy).isEqualTo("added")
+ }
+
+ @Test
+ fun getVodStreamsPage_omits_sortby_when_not_requested() = runTest {
+ var requestedSortBy: String? = "unset"
+ val service = OkHttpStalkerApiService(
+ okHttpClient = OkHttpClient.Builder()
+ .addInterceptor { chain ->
+ requestedSortBy = chain.request().url.queryParameter("sortby")
+ Response.Builder()
+ .request(chain.request())
+ .protocol(Protocol.HTTP_1_1)
+ .code(200)
+ .message("OK")
+ .body(
+ """{"js":{"total_items":1,"max_page_items":14,"data":[{"id":"1","name":"Movie","category_id":"42","cmd":"ffmpeg http://example.com/movie.mp4"}]}}"""
+ .toResponseBody("application/json".toMediaType())
+ )
+ .build()
+ }
+ .build(),
+ json = Json { ignoreUnknownKeys = true }
+ )
+
+ val result = service.getVodStreamsPage(
+ stalkerSession(),
+ stalkerProfile(),
+ "42",
+ page = 1,
+ searchQuery = null
+ )
+
+ assertThat(result).isInstanceOf(Result.Success::class.java)
+ assertThat(requestedSortBy).isNull()
+ }
+
@Test
fun getVodFiles_requests_movie_files_by_movie_id() = runTest {
var requestedMovieId: String? = null
diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerAdaptiveIndexPolicyTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerAdaptiveIndexPolicyTest.kt
new file mode 100644
index 00000000..7b26d3af
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerAdaptiveIndexPolicyTest.kt
@@ -0,0 +1,40 @@
+package com.streamvault.data.remote.stalker
+
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+
+class StalkerAdaptiveIndexPolicyTest {
+ @Test
+ fun healthyRampRequiresBothSamplesAndTimeAndStopsAtTwoRequestsPerSecond() {
+ val policy = StalkerAdaptiveIndexPolicy()
+ repeat(100) { policy.success(0L, 100L, false) }
+ assertThat(policy.intervalMillis).isEqualTo(5_000L)
+ policy.success(15_000L, 100L, false)
+ assertThat(policy.intervalMillis).isEqualTo(3_750L)
+ repeat(1_000) { policy.success(30_000L + it * 1_000L, 100L, false) }
+ assertThat(policy.intervalMillis).isEqualTo(500L)
+ }
+
+ @Test
+ fun stressPermanentlyLowersLearnedCeilingAndBoundsRepeatedBackoff() {
+ val policy = StalkerAdaptiveIndexPolicy(1_000L)
+ policy.stress()
+ repeat(1_000) { policy.success(it * 2_000L, 100L, false) }
+ assertThat(policy.intervalMillis).isEqualTo(2_000L)
+ assertThat(policy.minimumIntervalMillis).isEqualTo(2_000L)
+ repeat(100) { policy.stress() }
+ assertThat(policy.intervalMillis).isEqualTo(30_000L)
+ }
+
+ @Test
+ fun playbackAndFailuresBreakHealthyStreakAndSlowResponsesBackOff() {
+ val policy = StalkerAdaptiveIndexPolicy()
+ repeat(11) { policy.success(it * 2_000L, 100L, false) }
+ policy.success(30_000L, 100L, true)
+ policy.success(32_000L, 100L, false)
+ assertThat(policy.intervalMillis).isEqualTo(5_000L)
+ policy.resetHealth()
+ policy.success(60_000L, 2_000L, false)
+ assertThat(policy.intervalMillis).isEqualTo(10_000L)
+ }
+}
diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerPortalStateStoreTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerPortalStateStoreTest.kt
index 29355493..0bf08e7c 100644
--- a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerPortalStateStoreTest.kt
+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerPortalStateStoreTest.kt
@@ -17,6 +17,52 @@ import org.junit.Test
import java.util.Base64
class StalkerPortalStateStoreTest {
+ @Test
+ fun `first run adopts learning generation created after handshake`() = runTest {
+ val dao = FakePortalStateDao()
+ val store = StalkerPortalStateStore(dao, TestCredentialCrypto())
+ val coordinator = StalkerRequestCoordinator(store, true) { testScheduler.currentTime }
+ coordinator.acquireNetworkPermit(83L, StalkerNetworkPriority.FOREGROUND).also {
+ coordinator.releaseNetworkPermit(it)
+ }
+ dao.upsert(StalkerPortalStateEntity(providerId = 83L, configurationGeneration = 9L))
+ val page = coordinator.acquireNetworkPermit(83L, StalkerNetworkPriority.INDEX)
+ coordinator.recordIndexResponse(page, java.net.SocketTimeoutException())
+ val persisted = requireNotNull(store.get(83L))
+ assertThat(persisted.configurationGeneration).isEqualTo(9L)
+ assertThat(store.indexPacing(persisted).intervalMillis).isEqualTo(10_000L)
+ }
+
+ @Test
+ fun `learned index interval and stress ceiling survive coordinator restart`() = runTest {
+ val dao = FakePortalStateDao()
+ val store = StalkerPortalStateStore(dao, TestCredentialCrypto())
+ dao.upsert(StalkerPortalStateEntity(providerId = 82L, configurationGeneration = 7L))
+ val firstCoordinator = StalkerRequestCoordinator(store, true) { testScheduler.currentTime }
+ val permit = firstCoordinator.acquireNetworkPermit(82L, StalkerNetworkPriority.INDEX)
+ firstCoordinator.recordIndexResponse(permit, java.net.SocketTimeoutException())
+ val learned = store.indexPacing(requireNotNull(store.get(82L)))
+ assertThat(learned.intervalMillis).isEqualTo(10_000L)
+ assertThat(learned.minimumIntervalMillis).isEqualTo(10_000L)
+
+ val restarted = StalkerRequestCoordinator(store, true) { testScheduler.currentTime }
+ val first = restarted.acquireNetworkPermit(82L, StalkerNetworkPriority.INDEX)
+ val second = restarted.acquireNetworkPermit(82L, StalkerNetworkPriority.INDEX)
+ assertThat(second.admittedAt - first.admittedAt).isEqualTo(10_000L)
+ // A changed configuration cannot inherit pacing from the old generation.
+ val changed = requireNotNull(store.get(82L)).copy(configurationGeneration = 8L)
+ assertThat(store.indexPacing(changed).intervalMillis).isEqualTo(5_000L)
+ }
+
+ @Test
+ fun `malformed pacing falls back safely and valid values are bounded`() = runTest {
+ val store = StalkerPortalStateStore(FakePortalStateDao(), TestCredentialCrypto())
+ assertThat(store.indexPacing(StalkerPortalStateEntity(1L, learningJson = "bad")).intervalMillis)
+ .isEqualTo(5_000L)
+ store.recordIndexPacing(1L, 3L, 1L, 1L)
+ assertThat(store.indexPacing(requireNotNull(store.get(1L))).intervalMillis).isEqualTo(500L)
+ }
+
@Test
fun `VOD page base is persisted and isolated by configuration generation`() = runTest {
val store = StalkerPortalStateStore(FakePortalStateDao(), TestCredentialCrypto())
@@ -34,6 +80,25 @@ class StalkerPortalStateStoreTest {
assertThat(store.getVodPageBase(providerId = 42L, configurationGeneration = 8L)).isNull()
}
+ @Test
+ fun `largest VOD page size is learned per content type and configuration generation`() = runTest {
+ val store = StalkerPortalStateStore(FakePortalStateDao(), TestCredentialCrypto())
+
+ store.recordVodPageSize(43L, ContentType.MOVIE, pageSize = 14, configurationGeneration = 7L, now = 100L)
+ store.recordVodPageSize(43L, ContentType.MOVIE, pageSize = 8, configurationGeneration = 7L, now = 200L)
+ store.recordVodPageSize(43L, ContentType.SERIES, pageSize = 12, configurationGeneration = 7L, now = 300L)
+
+ assertThat(store.getVodPageSize(43L, ContentType.MOVIE, 7L)).isEqualTo(14)
+ assertThat(store.getVodPageSize(43L, ContentType.SERIES, 7L)).isEqualTo(12)
+ assertThat(store.getVodPageSize(43L, ContentType.MOVIE, 8L)).isNull()
+
+ store.recordVodPageSize(43L, ContentType.MOVIE, pageSize = 10, configurationGeneration = 8L, now = 400L)
+ assertThat(store.getVodPageSize(43L, ContentType.MOVIE, 8L)).isEqualTo(10)
+ assertThat(store.getVodPageSize(43L, ContentType.SERIES, 8L)).isNull()
+ store.recordVodPageSize(43L, ContentType.MOVIE, pageSize = 129, configurationGeneration = 8L)
+ assertThat(store.getVodPageSize(43L, ContentType.MOVIE, 8L)).isEqualTo(10)
+ }
+
@Test
fun `rate limit cooldown is persisted independently and can be cleared`() = runTest {
val dao = FakePortalStateDao()
diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinatorTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinatorTest.kt
index 6f1b8e25..60276053 100644
--- a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinatorTest.kt
+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinatorTest.kt
@@ -6,13 +6,211 @@ import java.net.SocketTimeoutException
import java.util.concurrent.atomic.AtomicInteger
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertThrows
import org.junit.Test
+@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
class StalkerRequestCoordinatorTest {
+ @Test
+ fun configuredIndexWindowAdmitsTwoPagesButNoThirdPageUntilOneFinishes() = runTest {
+ val coordinator = StalkerRequestCoordinator(
+ portalStateStore = null,
+ adaptiveIndexingEnabled = true,
+ nowMillis = { testScheduler.currentTime },
+ configuredIndexConcurrency = 2
+ )
+ val releasePages = CompletableDeferred<Unit>()
+ val startedPages = AtomicInteger()
+ val requests = (1..3).map { page ->
+ async {
+ coordinator.execute(
+ providerId = 91L,
+ priority = StalkerRequestPriority.BACKGROUND_INDEX,
+ descriptor = StalkerRequestDescriptor("MOVIE", "INDEX_PAGE", page = page)
+ ) {
+ startedPages.incrementAndGet()
+ releasePages.await()
+ }
+ }
+ }
+
+ runCurrent()
+ assertThat(startedPages.get()).isEqualTo(2)
+ assertThat(requests[2].isCompleted).isFalse()
+
+ releasePages.complete(Unit)
+ advanceUntilIdle()
+ requests.awaitAll()
+ assertThat(startedPages.get()).isEqualTo(3)
+ }
+
+ @Test
+ fun playbackPacingYieldsTheOnlyMetadataSlotAndCancellationCleansBothAdmissions() = runTest {
+ val coordinator = StalkerRequestCoordinator(null, true) { testScheduler.currentTime }
+ coordinator.recordFailure(79L, java.net.SocketTimeoutException())
+ StalkerTrafficCoordinator.notePlaybackStarted(79L)
+ try {
+ val background = async {
+ coordinator.execute(79L, StalkerRequestPriority.BACKGROUND_INDEX,
+ StalkerRequestDescriptor("MOVIE", "PAGE", page = 1)) {
+ coordinator.acquireNetworkPermit(79L, StalkerNetworkPriority.INDEX)
+ // The page-base probe's second HTTP call waits inside the same logical page.
+ coordinator.acquireNetworkPermit(79L, StalkerNetworkPriority.INDEX)
+ }
+ }
+ runCurrent()
+ assertThat(background.isCompleted).isFalse()
+ val interactive = async {
+ coordinator.execute(79L, StalkerRequestPriority.OPEN_CATEGORY,
+ StalkerRequestDescriptor("MOVIE", "CATEGORY", categoryKey = "42")) { "ready" }
+ }
+ runCurrent()
+ assertThat(interactive.isCompleted).isTrue()
+ assertThat(interactive.await()).isEqualTo("ready")
+ background.cancel()
+ background.join()
+ assertThat(coordinator.snapshot(79L).active).isEqualTo(0)
+ assertThat(coordinator.snapshot(79L).queued).isEqualTo(0)
+ // A canceled pacing wait must also release the one-background-operation guard.
+ val next = async {
+ coordinator.execute(79L, StalkerRequestPriority.BACKGROUND_INDEX,
+ StalkerRequestDescriptor("MOVIE", "PAGE", page = 2)) { "resumed" }
+ }
+ runCurrent()
+ assertThat(next.isCompleted).isTrue()
+ assertThat(next.await()).isEqualTo("resumed")
+ } finally { StalkerTrafficCoordinator.forgetProvider(79L) }
+ }
+
+ @Test
+ fun healthyIndexWalkRampsToTwoPerSecondWithoutTokenBucketBottleneck() = runTest {
+ val coordinator = StalkerRequestCoordinator(null, true) { testScheduler.currentTime }
+ val times = (1..715).map {
+ val permit = coordinator.acquireNetworkPermit(71L, StalkerNetworkPriority.INDEX)
+ coordinator.recordIndexResponse(permit)
+ testScheduler.currentTime
+ }
+ assertThat(times[1] - times[0]).isEqualTo(5_000L)
+ assertThat(times.zipWithNext { a, b -> b - a }.minOrNull()).isEqualTo(500L)
+ assertThat(times.takeLast(100).zipWithNext { a, b -> b - a }.toSet()).containsExactly(500L)
+ // Virtual admission benchmark, excluding transport/DB work: 715 pages / 10k rows.
+ assertThat(times.last()).isLessThan(600_000L)
+ println("Stalker virtual admission benchmark: pages=715 elapsedMillis=${times.last()} tailIntervalMillis=500")
+ }
+
+ @Test
+ fun stressSlowsOnlyItsProviderAndCannotRampAbovePreStressRate() = runTest {
+ val coordinator = StalkerRequestCoordinator(null, true) { testScheduler.currentTime }
+ val first = coordinator.acquireNetworkPermit(72L, StalkerNetworkPriority.INDEX)
+ coordinator.recordIndexResponse(first, StalkerApiError.Server("busy", httpStatus = 503))
+ val second = coordinator.acquireNetworkPermit(72L, StalkerNetworkPriority.INDEX)
+ assertThat(second.admittedAt - first.admittedAt).isEqualTo(10_000L)
+ repeat(60) {
+ coordinator.recordIndexResponse(coordinator.acquireNetworkPermit(72L, StalkerNetworkPriority.INDEX))
+ }
+ val before = testScheduler.currentTime
+ coordinator.acquireNetworkPermit(72L, StalkerNetworkPriority.INDEX)
+ assertThat(testScheduler.currentTime - before).isEqualTo(10_000L)
+ val other = coordinator.acquireNetworkPermit(73L, StalkerNetworkPriority.INDEX)
+ val otherNext = coordinator.acquireNetworkPermit(73L, StalkerNetworkPriority.INDEX)
+ assertThat(otherNext.admittedAt - other.admittedAt).isEqualTo(5_000L)
+ }
+
+ @Test
+ fun playbackTrickleUsesTwentySecondsForEveryWireRequestAndInteractiveStillWins() = runTest {
+ val coordinator = StalkerRequestCoordinator(null, true) { testScheduler.currentTime }
+ StalkerTrafficCoordinator.notePlaybackStarted(74L)
+ try {
+ val first = coordinator.acquireNetworkPermit(74L, StalkerNetworkPriority.INDEX)
+ val next = async { coordinator.acquireNetworkPermit(74L, StalkerNetworkPriority.INDEX) }
+ runCurrent()
+ val interactive = coordinator.acquireNetworkPermit(74L, StalkerNetworkPriority.INTERACTIVE)
+ assertThat(testScheduler.currentTime).isEqualTo(0L)
+ testScheduler.advanceTimeBy(21_000L)
+ runCurrent()
+ assertThat(next.isCompleted).isFalse()
+ coordinator.releaseNetworkPermit(interactive)
+ advanceUntilIdle()
+ assertThat(next.await().admittedAt - first.admittedAt).isAtLeast(20_000L)
+ } finally { StalkerTrafficCoordinator.forgetProvider(74L) }
+ }
+
+ @Test
+ fun foregroundTrafficYieldsNoIndexCreditAndItsStressSlowsTheIndex() = runTest {
+ val coordinator = StalkerRequestCoordinator(null, true) { testScheduler.currentTime }
+ val foreground = coordinator.acquireNetworkPermit(77L, StalkerNetworkPriority.FOREGROUND)
+ val background = async { coordinator.acquireNetworkPermit(77L, StalkerNetworkPriority.INDEX) }
+ runCurrent()
+ assertThat(background.isCompleted).isFalse()
+ coordinator.recordIndexResponse(foreground, java.net.SocketTimeoutException())
+ coordinator.releaseNetworkPermit(foreground)
+ advanceUntilIdle()
+ val first = background.await()
+ val second = coordinator.acquireNetworkPermit(77L, StalkerNetworkPriority.INDEX)
+ assertThat(second.admittedAt - first.admittedAt).isEqualTo(10_000L)
+ }
+
+ @Test
+ fun cancelledInteractiveWaiterDoesNotStarveIndex() = runTest {
+ val coordinator = StalkerRequestCoordinator(null, true) { testScheduler.currentTime }
+ // Drain foreground credits, then exceed interactive borrowing so its next permit queues.
+ repeat(8) { coordinator.acquireNetworkPermit(78L, StalkerNetworkPriority.FOREGROUND).also {
+ coordinator.releaseNetworkPermit(it)
+ } }
+ repeat(2) { coordinator.acquireNetworkPermit(78L, StalkerNetworkPriority.INTERACTIVE).also {
+ coordinator.releaseNetworkPermit(it)
+ } }
+ val interactive = async { coordinator.acquireNetworkPermit(78L, StalkerNetworkPriority.INTERACTIVE) }
+ runCurrent()
+ interactive.cancel()
+ interactive.join()
+ val index = coordinator.acquireNetworkPermit(78L, StalkerNetworkPriority.INDEX)
+ assertThat(index.admittedAt).isEqualTo(3_000L)
+ }
+
+ @Test
+ fun disabledPolicyPreservesFiveSecondIndexSpacing() = runTest {
+ val coordinator = StalkerRequestCoordinator(null, false) { testScheduler.currentTime }
+ val first = coordinator.acquireNetworkPermit(75L, StalkerNetworkPriority.INDEX)
+ coordinator.recordIndexResponse(first)
+ val next = coordinator.acquireNetworkPermit(75L, StalkerNetworkPriority.INDEX)
+ assertThat(next.admittedAt - first.admittedAt).isEqualTo(5_000L)
+ }
+
+ @Test
+ fun retryAfterBlocksAllLanesAndAllowsExactlyOneHalfOpenProbe() = runTest {
+ val coordinator = StalkerRequestCoordinator(null, true) { testScheduler.currentTime }
+ val first = coordinator.acquireNetworkPermit(76L, StalkerNetworkPriority.INDEX)
+ val error = StalkerApiError.RateLimited(retryAfterMillis = 1_200_000L)
+ coordinator.recordIndexResponse(first, error)
+ coordinator.recordNetworkFailure(first, error)
+ repeat(3) {
+ try {
+ coordinator.acquireNetworkPermit(76L, StalkerNetworkPriority.INTERACTIVE)
+ error("Cooldown must reject locally")
+ } catch (expected: StalkerApiError.RateLimited) {
+ assertThat(expected.retryAfterMillis).isEqualTo(1_200_000L)
+ }
+ }
+ testScheduler.advanceTimeBy(1_200_000L)
+ val probe = coordinator.acquireNetworkPermit(76L, StalkerNetworkPriority.INDEX)
+ assertThat(probe.halfOpenProbe).isTrue()
+ try {
+ coordinator.acquireNetworkPermit(76L, StalkerNetworkPriority.FOREGROUND)
+ error("Only one probe may run")
+ } catch (expected: StalkerApiError.RateLimited) {
+ assertThat(expected.retryAfterMillis).isEqualTo(1_000L)
+ }
+ coordinator.recordNetworkSuccess(probe)
+ coordinator.recordIndexResponse(probe)
+ val next = coordinator.acquireNetworkPermit(76L, StalkerNetworkPriority.INDEX)
+ assertThat(next.admittedAt - probe.admittedAt).isEqualTo(10_000L)
+ }
+
@Test
fun backgroundNetworkRequestWaitsWhileInteractivePlaybackIsActive() = runTest {
val coordinator = StalkerRequestCoordinator()
diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinatorTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinatorTest.kt
index 68fed4dd..a9fcbb9c 100644
--- a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinatorTest.kt
+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinatorTest.kt
@@ -6,6 +6,14 @@ import org.junit.Before
import org.junit.Test
class StalkerTrafficCoordinatorTest {
+ @Test
+ fun `opt in lets worker run during playback with all pacing at wire admission`() {
+ StalkerTrafficCoordinator.notePlaybackStarted(7L)
+ assertThat(StalkerTrafficCoordinator.shouldDeferIndexForPlayback(7L, false)).isTrue()
+ assertThat(StalkerTrafficCoordinator.shouldDeferIndexForPlayback(7L, true)).isFalse()
+ assertThat(StalkerTrafficCoordinator.backgroundInterPageDelayMillis(7L, true)).isEqualTo(0L)
+ }
+
@Before
fun setUp() {
StalkerTrafficCoordinator.resetForTests()
@@ -18,10 +26,10 @@ class StalkerTrafficCoordinatorTest {
@Test
fun `background delay increases while playback is active without blocking interactive work`() {
- val normalDelay = StalkerTrafficCoordinator.backgroundInterPageDelayMillis(providerId = 7L)
+ val normalDelay = StalkerTrafficCoordinator.backgroundInterPageDelayMillis(providerId = 7L, adaptiveIndexingEnabled = false)
StalkerTrafficCoordinator.notePlaybackStarted(providerId = 7L)
- val playbackDelay = StalkerTrafficCoordinator.backgroundInterPageDelayMillis(providerId = 7L)
+ val playbackDelay = StalkerTrafficCoordinator.backgroundInterPageDelayMillis(providerId = 7L, adaptiveIndexingEnabled = false)
assertThat(StalkerTrafficCoordinator.isPlaybackActive(7L)).isTrue()
assertThat(playbackDelay).isGreaterThan(normalDelay)
diff --git a/data/src/test/java/com/streamvault/data/sync/ProviderContinuationSchedulerTest.kt b/data/src/test/java/com/streamvault/data/sync/ProviderContinuationSchedulerTest.kt
index 944fb458..ee41f88c 100644
--- a/data/src/test/java/com/streamvault/data/sync/ProviderContinuationSchedulerTest.kt
+++ b/data/src/test/java/com/streamvault/data/sync/ProviderContinuationSchedulerTest.kt
@@ -41,6 +41,32 @@ class ProviderContinuationSchedulerTest {
verify(workScheduler).scheduleProviderResume(7L)
}
+ @Test
+ fun `Stalker bootstrap continuation schedules the one-hop catalog resume`() = runTest {
+ val workScheduler = mock<ProviderSyncWorkScheduler>()
+ val snapshot = ProviderSnapshot(
+ provider = Provider(id = 8L, name = "Portal", type = ProviderType.STALKER_PORTAL),
+ configuration = StalkerConfig(
+ portalUrl = "https://portal.example.com",
+ device = StalkerDeviceIdentity(macAddress = "00:11:22:33:44:55")
+ ),
+ configurationGeneration = 1L
+ )
+
+ ProviderContinuationScheduler(workScheduler).schedule(
+ snapshot,
+ listOf(
+ SyncContinuation(
+ operation = SyncContinuationOperation.STALKER_BOOTSTRAP_RESUME,
+ reason = "test"
+ )
+ )
+ )
+
+ verify(workScheduler).scheduleStalkerBootstrapResume(8L)
+ verify(workScheduler, org.mockito.kotlin.never()).scheduleProviderResume(8L)
+ }
+
@Test
fun `Xtream movie and series indexes are queued before delayed guide work`() = runTest {
val workScheduler = mock<ProviderSyncWorkScheduler>()
diff --git a/data/src/test/java/com/streamvault/data/sync/StalkerIncrementalIndexExecutorTest.kt b/data/src/test/java/com/streamvault/data/sync/StalkerIncrementalIndexExecutorTest.kt
new file mode 100644
index 00000000..374449c4
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/sync/StalkerIncrementalIndexExecutorTest.kt
@@ -0,0 +1,304 @@
+package com.streamvault.data.sync
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.data.local.entity.CategoryEntity
+import com.streamvault.data.local.entity.StalkerIndexJobEntity
+import com.streamvault.data.remote.stalker.StalkerPagedResult
+import com.streamvault.data.remote.stalker.StalkerProvider
+import com.streamvault.domain.model.CatalogLayout
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.LegacyProvider
+import com.streamvault.domain.model.Movie
+import com.streamvault.domain.model.ProviderType
+import com.streamvault.domain.model.Result
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.test.runTest
+import org.mockito.kotlin.mock
+import org.mockito.kotlin.whenever
+import org.junit.Test
+
+class StalkerIncrementalIndexExecutorTest {
+ @Test
+ fun wildcardWindowFetchesConcurrentlyAndCommitsCheckpointPagesInOrder() = runTest {
+ val wildcard = CategoryEntity(categoryId = -9L, name = "All", type = ContentType.MOVIE, providerId = 91L)
+ val operations = WildcardIndexOperations(wildcard)
+ val api = mock<StalkerProvider>()
+ whenever(api.isWildcardCategory(ContentType.MOVIE, wildcard.categoryId)).thenReturn(true)
+
+ StalkerIncrementalIndexExecutor(operations, configuredWildcardPageConcurrency = 2)
+ .processSummary(
+ provider = LegacyProvider(
+ id = 91L,
+ name = "Portal",
+ type = ProviderType.STALKER_PORTAL,
+ serverUrl = "https://portal.invalid",
+ catalogLayout = CatalogLayout.SPLIT
+ ),
+ api = api,
+ contentType = ContentType.MOVIE,
+ maxCategories = 2,
+ onProgress = null,
+ maxPages = 2
+ )
+
+ assertThat(operations.maxConcurrentFetches).isEqualTo(2)
+ assertThat(operations.completedFetchPages).containsExactly(2, 1).inOrder()
+ assertThat(operations.committedPages).containsExactly(1, 2).inOrder()
+ assertThat(operations.hydration?.lastSuccessfulPage).isEqualTo(2)
+ assertThat(operations.indexedMovies.map(Movie::id)).containsExactly(1L, 2L).inOrder()
+ }
+
+ @Test
+ fun failedPageDoesNotCommitLaterPageAndRetryResumesFromTheGap() = runTest {
+ val wildcard = CategoryEntity(categoryId = -9L, name = "All", type = ContentType.MOVIE, providerId = 91L)
+ val operations = WildcardIndexOperations(wildcard, failPageOneOnce = true)
+ val api = mock<StalkerProvider>()
+ whenever(api.isWildcardCategory(ContentType.MOVIE, wildcard.categoryId)).thenReturn(true)
+ val executor = StalkerIncrementalIndexExecutor(operations, configuredWildcardPageConcurrency = 2)
+ val provider = LegacyProvider(
+ id = 91L,
+ name = "Portal",
+ type = ProviderType.STALKER_PORTAL,
+ serverUrl = "https://portal.invalid",
+ catalogLayout = CatalogLayout.SPLIT
+ )
+
+ executor.processSummary(provider, api, ContentType.MOVIE, maxCategories = 2, onProgress = null, maxPages = 2)
+
+ assertThat(operations.committedPages).isEmpty()
+ assertThat(operations.failedPages).containsExactly(1)
+ assertThat(operations.indexedMovies).isEmpty()
+ assertThat(operations.hydration?.lastSuccessfulPage ?: 0).isEqualTo(0)
+
+ executor.processSummary(provider, api, ContentType.MOVIE, maxCategories = 2, onProgress = null, maxPages = 2)
+
+ assertThat(operations.committedPages).containsExactly(1, 2).inOrder()
+ assertThat(operations.hydration?.lastSuccessfulPage).isEqualTo(2)
+ assertThat(operations.indexedMovies.map(Movie::id)).containsExactly(1L, 2L).inOrder()
+ }
+
+ private class WildcardIndexOperations(
+ private val wildcard: CategoryEntity,
+ private var failPageOneOnce: Boolean = false
+ ) : StalkerIncrementalIndexOperations {
+ override val runtimeProfile = CatalogSyncRuntimeProfile(
+ tier = DeviceSyncTier.HIGH,
+ stageBatchSize = 100,
+ maxCategoryConcurrency = 2,
+ preferSegmentedLiveOnboarding = false,
+ deferBackgroundWorkOnLowMemory = false,
+ snapshot = SyncDeviceSnapshot(
+ memoryClassMb = 512,
+ largeMemoryClassMb = null,
+ isLowRamDevice = false,
+ isCurrentlyLowOnMemory = false,
+ availableMemMb = 512,
+ maxHeapMb = 512,
+ isTelevision = false,
+ manufacturer = "test",
+ model = "test",
+ sdkInt = 35
+ )
+ )
+
+ var hydration: StalkerHydrationSnapshot? = null
+ private set
+ val committedPages = mutableListOf<Int>()
+ val failedPages = mutableListOf<Int>()
+ val completedFetchPages = mutableListOf<Int>()
+ val indexedMovies = mutableListOf<Movie>()
+ var activeFetches = 0
+ private set
+ var maxConcurrentFetches = 0
+ private set
+ private val pageOneStarted = CompletableDeferred<Unit>()
+ private val pageTwoStarted = CompletableDeferred<Unit>()
+
+ override suspend fun allVisibleCategories(providerId: Long, contentType: ContentType) = listOf(wildcard)
+
+ override suspend fun visibleCategories(
+ contentType: ContentType,
+ categories: List<CategoryEntity>,
+ api: StalkerProvider
+ ) = categories
+
+ override suspend fun getJob(providerId: Long, contentType: ContentType): StalkerIndexJobEntity? = null
+
+ override suspend fun getHydration(
+ providerId: Long,
+ contentType: ContentType,
+ categoryId: Long
+ ): StalkerHydrationSnapshot? = hydration
+
+ override suspend fun currentIndexedRowCount(providerId: Long, contentType: ContentType): Int = indexedMovies.size
+
+ override suspend fun categoriesWithLocalRows(providerId: Long, contentType: ContentType): Map<Long, Int> = emptyMap()
+
+ override suspend fun pruneStaleRows(providerId: Long, contentType: ContentType): Int = 0
+
+ override suspend fun updateSummaryMetadata(
+ providerId: Long,
+ contentType: ContentType,
+ indexedRows: Int,
+ finalState: String,
+ now: Long
+ ) = Unit
+
+ override suspend fun fetchSummaryPage(
+ provider: LegacyProvider,
+ api: StalkerProvider,
+ contentType: ContentType,
+ categoryId: Long,
+ page: Int
+ ): Result<StalkerPagedResult<out Any>> = Result.error("Unexpected category fetch")
+
+ override suspend fun fetchWildcardPage(
+ provider: LegacyProvider,
+ api: StalkerProvider,
+ contentType: ContentType,
+ categoryId: Long,
+ page: Int
+ ): Result<StalkerPagedResult<out Any>> {
+ activeFetches += 1
+ maxConcurrentFetches = maxOf(maxConcurrentFetches, activeFetches)
+ try {
+ if (page == 1) {
+ pageOneStarted.complete(Unit)
+ pageTwoStarted.await()
+ delay(200)
+ } else {
+ pageTwoStarted.complete(Unit)
+ pageOneStarted.await()
+ delay(20)
+ }
+ completedFetchPages += page
+ if (page == 1 && failPageOneOnce) {
+ failPageOneOnce = false
+ return Result.error("temporary portal stress", IllegalStateException("temporary portal stress"))
+ }
+ val movie = Movie(id = page.toLong(), name = "Page $page", streamId = page.toLong())
+ return Result.success(
+ StalkerPagedResult(
+ items = listOf(movie),
+ page = page,
+ totalPages = 2,
+ pageSize = 1,
+ advertisedTotalItems = 2,
+ advertisedTotalPages = 2
+ )
+ )
+ } finally {
+ activeFetches -= 1
+ }
+ }
+
+ override suspend fun markAttemptStarted(
+ providerId: Long,
+ contentType: ContentType,
+ categoryId: Long,
+ hydration: StalkerHydrationSnapshot?,
+ attemptedPage: Int,
+ now: Long
+ ) = Unit
+
+ override suspend fun markAttemptSucceeded(
+ providerId: Long,
+ contentType: ContentType,
+ categoryId: Long,
+ hydration: StalkerHydrationSnapshot?,
+ attemptedPage: Int,
+ now: Long,
+ itemCount: Int,
+ totalPages: Int,
+ pageSize: Int,
+ advertisedTotalItems: Int?,
+ advertisedTotalPages: Int?,
+ pageComplete: Boolean,
+ truncated: Boolean,
+ terminationReason: String?,
+ pageFingerprint: String?
+ ) {
+ committedPages += attemptedPage
+ this.hydration = StalkerHydrationSnapshot(
+ lastHydratedAt = now,
+ itemCount = itemCount,
+ lastStatus = if (truncated) "TRUNCATED" else "SUCCESS",
+ lastError = terminationReason,
+ lastLoadedPage = attemptedPage,
+ lastAttemptedPage = attemptedPage,
+ lastSuccessfulPage = attemptedPage,
+ totalPages = totalPages,
+ advertisedTotalItems = advertisedTotalItems,
+ advertisedTotalPages = advertisedTotalPages,
+ isComplete = pageComplete && !truncated,
+ pageSize = pageSize,
+ retryAfterMs = 0L,
+ failureCount = 0,
+ retryBudgetRemaining = 3,
+ lastPageFingerprint = pageFingerprint
+ )
+ }
+
+ override suspend fun markAttemptFailed(
+ providerId: Long,
+ contentType: ContentType,
+ categoryId: Long,
+ hydration: StalkerHydrationSnapshot?,
+ attemptedPage: Int,
+ now: Long,
+ message: String,
+ retryable: Boolean,
+ pageFingerprint: String?
+ ) {
+ failedPages += attemptedPage
+ val previous = hydration
+ this.hydration = (previous ?: StalkerHydrationSnapshot(
+ lastHydratedAt = 0L,
+ itemCount = 0,
+ lastStatus = "RUNNING",
+ lastError = null,
+ lastLoadedPage = 0,
+ lastAttemptedPage = attemptedPage,
+ lastSuccessfulPage = 0,
+ totalPages = 0,
+ advertisedTotalItems = null,
+ advertisedTotalPages = null,
+ isComplete = false,
+ pageSize = 0,
+ retryAfterMs = 0L,
+ failureCount = 0,
+ retryBudgetRemaining = 3,
+ lastPageFingerprint = null
+ )).copy(
+ lastStatus = if (retryable) "FAILED_RETRYABLE" else "FAILED_PERMANENT",
+ lastError = message,
+ lastAttemptedPage = attemptedPage,
+ retryAfterMs = 0L,
+ failureCount = (previous?.failureCount ?: 0) + 1,
+ retryBudgetRemaining = ((previous?.retryBudgetRemaining ?: 3) - 1).coerceAtLeast(0),
+ lastPageFingerprint = pageFingerprint
+ )
+ }
+
+ override suspend fun upsertMovieSummaryBatch(providerId: Long, movies: List<Movie>, indexedAt: Long) {
+ indexedMovies += movies
+ }
+
+ override suspend fun upsertSeriesSummaryBatch(providerId: Long, series: List<com.streamvault.domain.model.Series>, indexedAt: Long) = Unit
+
+ override suspend fun upsertVodDerivedSeriesSummaryBatch(providerId: Long, series: List<com.streamvault.domain.model.Series>, indexedAt: Long) = Unit
+
+ override suspend fun recordRequestFailure(providerId: Long, error: Throwable?) = Unit
+
+ override fun failureState(error: Throwable): String = "FAILED_RETRYABLE"
+
+ override fun progress(providerId: Long, callback: ((String) -> Unit)?, message: String) = Unit
+
+ override suspend fun restoreMovieWatchProgress(providerId: Long) = Unit
+
+ override suspend fun upsertJob(update: CatalogIndexJobUpdate) = Unit
+
+ override fun log(message: String) = Unit
+ }
+}
diff --git a/data/src/test/java/com/streamvault/data/sync/StalkerIndexPolicyTest.kt b/data/src/test/java/com/streamvault/data/sync/StalkerIndexPolicyTest.kt
index 3621d5b0..d283e14a 100644
--- a/data/src/test/java/com/streamvault/data/sync/StalkerIndexPolicyTest.kt
+++ b/data/src/test/java/com/streamvault/data/sync/StalkerIndexPolicyTest.kt
@@ -1,6 +1,7 @@
package com.streamvault.data.sync
import com.google.common.truth.Truth.assertThat
+import com.streamvault.data.local.entity.CategoryEntity
import com.streamvault.data.remote.stalker.StalkerPagedResult
import com.streamvault.domain.model.CatalogLayout
import com.streamvault.domain.model.ContentType
@@ -95,6 +96,27 @@ class StalkerIndexPolicyTest {
assertThat(StalkerIndexPolicy.canAttempt(null, now)).isTrue()
}
+ @Test
+ fun `wildcard backfill targets categories without local rows`() {
+ val covered = category(1L, "Action")
+ val excluded = category(2L, "Adult")
+ val empty = category(3L, "Empty")
+
+ val backfill = StalkerIndexPolicy.wildcardBackfillCategories(
+ normalCategories = listOf(covered, excluded, empty),
+ localRowCounts = mapOf(1L to 25, 2L to 0)
+ )
+
+ assertThat(backfill.map { it.categoryId }).containsExactly(2L, 3L)
+ }
+
+ private fun category(categoryId: Long, name: String) = CategoryEntity(
+ categoryId = categoryId,
+ name = name,
+ type = ContentType.MOVIE,
+ providerId = 1L
+ )
+
private fun section(
contentType: ContentType,
updatedAt: Long,
diff --git a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
index ce630350..aad80818 100644
--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
@@ -2189,6 +2189,169 @@ class SyncManagerTest {
assertThat(finalMovieJob.state).isEqualTo("SUCCESS")
}
+ @Test
+ fun `processQueuedStalkerIndexJobs prefers wildcard for learned support and backfills excluded categories`() = runTest {
+ val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
+ serverUrl = "http://example.com",
+ username = "",
+ password = "",
+ stalkerMacAddress = "00:11:22:33:44:55",
+ epgSyncMode = ProviderEpgSyncMode.SKIP
+ )
+ val wildcardCategoryId = stalkerSyntheticCategoryId(providerEntity.id, ContentType.MOVIE, "*")
+ val actionCategoryId = stalkerSyntheticCategoryId(providerEntity.id, ContentType.MOVIE, "5")
+ val adultCategoryId = stalkerSyntheticCategoryId(providerEntity.id, ContentType.MOVIE, "9")
+ val portalStateStore = mock<com.streamvault.data.remote.stalker.StalkerPortalStateStore>()
+ org.mockito.kotlin.whenever(portalStateStore.getValidated(eq(1L), any())).thenReturn(
+ StalkerPortalStateEntity(
+ providerId = 1L,
+ movieWildcardSupported = true,
+ validatedAt = System.currentTimeMillis()
+ )
+ )
+ val manager = buildManager(
+ providerType = ProviderType.STALKER_PORTAL,
+ providerEntity = providerEntity,
+ portalStateStore = portalStateStore
+ )
+
+ org.mockito.kotlin.whenever(stalkerApiService.authenticate(any())).thenReturn(
+ Result.success(
+ StalkerSession(
+ loadUrl = "http://example.com/stalker_portal/server/load.php",
+ portalReferer = "http://example.com/stalker_portal/c/",
+ token = "token"
+ ) to StalkerProviderProfile(accountName = "Stalker")
+ )
+ )
+ org.mockito.kotlin.whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(
+ Result.success(
+ listOf(
+ StalkerCategoryRecord(id = "*", name = "All"),
+ StalkerCategoryRecord(id = "5", name = "Action"),
+ StalkerCategoryRecord(id = "9", name = "Adult")
+ )
+ )
+ )
+ org.mockito.kotlin.whenever(categoryDao.getByProviderAndTypeSync(1L, ContentType.MOVIE.name)).thenReturn(
+ listOf(
+ CategoryEntity(
+ categoryId = wildcardCategoryId,
+ name = "All",
+ type = ContentType.MOVIE,
+ providerId = 1L
+ ),
+ CategoryEntity(
+ categoryId = actionCategoryId,
+ name = "Action",
+ type = ContentType.MOVIE,
+ providerId = 1L
+ ),
+ CategoryEntity(
+ categoryId = adultCategoryId,
+ name = "Adult",
+ type = ContentType.MOVIE,
+ providerId = 1L
+ )
+ )
+ )
+ org.mockito.kotlin.whenever(xtreamIndexJobDao.get(1L, ContentType.MOVIE.name)).thenReturn(
+ XtreamIndexJobEntity(
+ providerId = 1L,
+ section = ContentType.MOVIE.name,
+ state = "QUEUED",
+ totalCategories = 3
+ )
+ )
+ val hydrationByCategory = mutableMapOf<Long, MovieCategoryHydrationEntity>()
+ org.mockito.kotlin.whenever(movieCategoryHydrationDao.get(eq(1L), any())).thenAnswer { invocation ->
+ hydrationByCategory[invocation.getArgument<Long>(1)]
+ }
+ org.mockito.kotlin.whenever(movieCategoryHydrationDao.upsert(any())).thenAnswer { invocation ->
+ val entity = invocation.getArgument<MovieCategoryHydrationEntity>(0)
+ hydrationByCategory[entity.categoryId] = entity
+ Unit
+ }
+ org.mockito.kotlin.whenever(movieDao.getByStreamIds(eq(1L), any())).thenReturn(emptyList())
+ org.mockito.kotlin.whenever(seriesDao.getBySeriesIds(eq(1L), any())).thenReturn(emptyList())
+ org.mockito.kotlin.whenever(movieDao.getCategoryCounts(1L)).thenReturn(
+ flowOf(
+ listOf(
+ com.streamvault.data.local.entity.CategoryCount(
+ categoryId = actionCategoryId,
+ item_count = 2
+ )
+ )
+ )
+ )
+ org.mockito.kotlin.whenever(seriesDao.getCategoryCounts(1L)).thenReturn(flowOf(emptyList()))
+ org.mockito.kotlin.whenever(
+ stalkerApiService.getVodStreamsPage(any(), any(), eq("*"), eq(1), anyOrNull(), eq("added"))
+ ).thenReturn(
+ Result.success(
+ StalkerPagedItems(
+ items = listOf(
+ StalkerItemRecord(
+ id = "100",
+ name = "Wildcard Movie",
+ categoryId = "5",
+ cmd = "ffmpeg http://example.com/100.ts"
+ ),
+ StalkerItemRecord(
+ id = "101",
+ name = "Wildcard Movie 2",
+ categoryId = "5",
+ cmd = "ffmpeg http://example.com/101.ts"
+ )
+ ),
+ page = 1,
+ totalPages = 1,
+ pageSize = 14,
+ advertisedTotalItems = 2,
+ advertisedTotalPages = 1
+ )
+ )
+ )
+ org.mockito.kotlin.whenever(stalkerApiService.getVodStreamsPage(any(), any(), eq("9"), eq(1))).thenReturn(
+ Result.success(
+ StalkerPagedItems(
+ items = listOf(
+ StalkerItemRecord(
+ id = "200",
+ name = "Adult Movie",
+ categoryId = "9",
+ cmd = "ffmpeg http://example.com/200.ts"
+ )
+ ),
+ page = 1,
+ totalPages = 1,
+ pageSize = 14,
+ advertisedTotalItems = 1,
+ advertisedTotalPages = 1
+ )
+ )
+ )
+
+ val result = manager.processQueuedStalkerIndexJobs(
+ providerId = 1L,
+ section = ContentType.MOVIE,
+ maxCategoriesPerSection = 4
+ )
+
+ if (result is Result.Error) fail(result.exception?.stackTraceToString() ?: result.message)
+ assertThat(result.isSuccess).isTrue()
+ assertThat(hydrationByCategory[wildcardCategoryId]?.lastError).isNull()
+ verify(stalkerApiService).getVodStreamsPage(any(), any(), eq("*"), eq(1), anyOrNull(), eq("added"))
+ verify(stalkerApiService).getVodStreamsPage(any(), any(), eq("9"), eq(1))
+ verify(portalStateStore).recordWildcard(eq(1L), eq(ContentType.MOVIE), eq(true), any(), anyOrNull())
+ verify(stalkerApiService, org.mockito.kotlin.never()).getVodStreamsPage(any(), any(), eq("5"), any())
+ verify(xtreamContentIndexDao, atLeastOnce()).pruneStaleLocalContentRows(1L, ContentType.MOVIE.name)
+ val jobs = argumentCaptor<XtreamIndexJobEntity>()
+ verify(xtreamIndexJobDao, atLeastOnce()).upsert(jobs.capture())
+ val finalMovieJob = jobs.allValues.last { it.section == ContentType.MOVIE.name }
+ assertThat(finalMovieJob.state).isEqualTo("SUCCESS")
+ }
+
@Test
fun `processQueuedStalkerIndexJobs runs movies before series for same provider`() = runTest {
val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
@@ -3260,7 +3423,9 @@ class SyncManagerTest {
org.mockito.kotlin.whenever(movieDao.getByStreamIds(eq(1L), any())).thenReturn(emptyList())
org.mockito.kotlin.whenever(movieDao.getCount(1L)).thenReturn(flowOf(0), flowOf(1), flowOf(1))
org.mockito.kotlin.whenever(xtreamContentIndexDao.pruneStaleLocalContentRows(1L, ContentType.MOVIE.name)).thenReturn(0)
- org.mockito.kotlin.whenever(stalkerApiService.getVodStreamsPage(any(), any(), eq("*"), eq(1))).thenReturn(
+ org.mockito.kotlin.whenever(
+ stalkerApiService.getVodStreamsPage(any(), any(), eq("*"), eq(1), anyOrNull(), eq("added"))
+ ).thenReturn(
Result.success(
StalkerPagedItems(
items = listOf(
@@ -3286,7 +3451,7 @@ class SyncManagerTest {
if (result is Result.Error) fail(result.exception?.stackTraceToString() ?: result.message)
assertThat(result.isSuccess).isTrue()
- verify(stalkerApiService).getVodStreamsPage(any(), any(), eq("*"), eq(1))
+ verify(stalkerApiService).getVodStreamsPage(any(), any(), eq("*"), eq(1), anyOrNull(), eq("added"))
verify(movieDao).insertAll(check { movies ->
assertThat(movies).hasSize(1)
assertThat(movies.first().providerId).isEqualTo(1L)
@@ -3976,6 +4141,41 @@ class SyncManagerTest {
verify(workScheduler).scheduleProviderResume(1L)
}
+ @Test
+ fun sync_stalker_background_bootstrap_queues_first_page_resume_without_full_catalog_resume() = runTest {
+ val provider = sampleProvider(ProviderType.STALKER_PORTAL).copy(
+ serverUrl = "http://example.com", username = "", password = "",
+ stalkerMacAddress = "00:11:22:33:44:55",
+ catalogLayout = CatalogLayout.SPLIT,
+ stalkerCatalogMode = com.streamvault.domain.model.StalkerCatalogMode.BACKGROUND_INDEX,
+ epgSyncMode = ProviderEpgSyncMode.SKIP
+ )
+ val manager = buildManager(
+ providerType = ProviderType.STALKER_PORTAL,
+ providerEntity = provider
+ )
+ org.mockito.kotlin.whenever(stalkerApiService.authenticate(any())).thenReturn(Result.success(
+ StalkerSession("http://example.com/stalker_portal/server/load.php", "http://example.com/c/", "token") to
+ StalkerProviderProfile(accountName = "Stalker")
+ ))
+ org.mockito.kotlin.whenever(stalkerApiService.getLiveCategories(any(), any())).thenReturn(
+ Result.success(listOf(StalkerCategoryRecord("10", "News")))
+ )
+ org.mockito.kotlin.whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(
+ Result.success(listOf(StalkerCategoryRecord("20", "Movies")))
+ )
+ org.mockito.kotlin.whenever(stalkerApiService.getSeriesCategories(any(), any())).thenReturn(Result.success(emptyList()))
+ stalkerApiService.stubStreamLiveStreams(listOf(
+ StalkerItemRecord("1", "Channel", categoryId = "10", cmd = "ffmpeg http://example.com/live.ts")
+ ))
+
+ assertThat(manager.sync(providerId = 1L, bootstrap = true)).isInstanceOf(Result.Success::class.java)
+
+ verify(workScheduler).scheduleStalkerBootstrapResume(1L)
+ verify(workScheduler, org.mockito.kotlin.never()).scheduleProviderResume(1L)
+ verify(stalkerApiService, org.mockito.kotlin.never()).getVodStreamsPage(any(), any(), anyOrNull(), any())
+ }
+
@Test
fun sync_stalker_bootstrap_category_fallback_stops_after_the_accepted_prefix() = runTest {
val provider = sampleProvider(ProviderType.STALKER_PORTAL).copy(
diff --git a/tools/stalker_catalog_fixture.py b/tools/stalker_catalog_fixture.py
new file mode 100644
index 00000000..5c0327c9
--- /dev/null
+++ b/tools/stalker_catalog_fixture.py
@@ -0,0 +1,543 @@
+#!/usr/bin/env python3
+"""Deterministic Stalker portal fixture for catalog-crawl measurements.
+
+No provider account is required. The fixture emulates the legacy STB API
+(`server/load.php`) for the catalog surface used by the app: handshake,
+profile, VOD categories, and paged `get_ordered_list`. It models stock
+Ministra behavior that the speed plan depends on:
+
+- fixed page size (a server constant, not a request parameter),
+- page-numbering variants (zero-based, one-based, stock `p=0` = last page),
+- category-less (wildcard) whole-catalog listings,
+- wildcard adult exclusion,
+- 429/503 injection, unstable totals, repeated pages, and latency.
+
+Events contain action/page/category/count/timing only, never credentials.
+"""
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import math
+import re
+import threading
+import time
+from collections import deque
+from dataclasses import asdict, dataclass, field
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from typing import Iterator
+from urllib.parse import parse_qs, urlparse
+
+PAGE_BASE_NAMES = {0: "ZERO_BASED", 1: "ONE_BASED", 2: "STOCK_LAST_PAGE_ON_ZERO"}
+SYNTHETIC_MAC = re.compile(r"02:00:00:[0-9a-fA-F:]{8}")
+TOKEN = "fixture-token"
+
+
+@dataclass(frozen=True)
+class Scenario:
+ movies: int = 10_000
+ categories: int = 100
+ channels: int = 50
+ live_genres: int = 3
+ page_size: int = 14
+ p_base: int = 1
+ advertised_page_size: int = 0
+ wildcard_supported: int = 1
+ adult_category: int = 0
+ adult_stride: int = 10
+ wildcard_excludes_adult: int = 0
+ seed: int = 1
+ header_delay_ms: int = 0
+ page_delay_ms: int = 0
+ throttle_every: int = 0
+ server_error_every: int = 0
+ unstable_totals_every: int = 0
+ repeat_page_every: int = 0
+
+ def __post_init__(self):
+ if not 1 <= self.movies <= 500_000:
+ raise ValueError("movies is outside fixture limits")
+ if not 1 <= self.categories <= 10_000:
+ raise ValueError("categories is outside fixture limits")
+ if not 0 <= self.channels <= 100_000:
+ raise ValueError("channels is outside fixture limits")
+ if not 1 <= self.live_genres <= 100:
+ raise ValueError("live_genres is outside fixture limits")
+ if not 1 <= self.page_size <= 500:
+ raise ValueError("page_size is outside fixture limits")
+ if self.p_base not in PAGE_BASE_NAMES:
+ raise ValueError("p_base must be 0, 1, or 2")
+ if self.advertised_page_size and not 1 <= self.advertised_page_size <= 500:
+ raise ValueError("advertised_page_size is outside fixture limits")
+ if self.wildcard_supported not in (0, 1) or self.wildcard_excludes_adult not in (0, 1):
+ raise ValueError("wildcard flags must be 0 or 1")
+ if self.adult_category:
+ if not self.categories < self.adult_category <= 10_000:
+ raise ValueError("adult_category must be greater than categories")
+ if not 2 <= self.adult_stride <= 1_000:
+ raise ValueError("adult_stride is outside fixture limits")
+ if self.wildcard_excludes_adult and self.movies // self.adult_stride == 0:
+ raise ValueError("adult exclusion requires at least one adult row")
+ for name, value in asdict(self).items():
+ if value < 0:
+ raise ValueError(name + " must be nonnegative")
+
+ @property
+ def page_base_name(self) -> str:
+ return PAGE_BASE_NAMES[self.p_base]
+
+ def category_of(self, number: int) -> int:
+ if self.adult_category and number % self.adult_stride == 0:
+ return self.adult_category
+ return (number - 1) % self.categories + 1
+
+ def row(self, number: int) -> dict:
+ added = 1_700_000_000 + number
+ return {
+ "id": str(100_000 + number),
+ "name": f"Benchmark Movie {number:06d}",
+ "o_name": f"Benchmark Movie {number:06d} Original",
+ "category_id": str(self.category_of(number)),
+ "added": str(added),
+ "cmd": f"/media/{100_000 + number}.mpg",
+ "screenshot_uri": f"/misc/screenshots/{self.seed}/{100_000 + number}.jpg",
+ "genres_str": "Benchmark",
+ "is_movie": 1,
+ "is_series": 0,
+ "hd": 0,
+ "lock": 0,
+ "fav": 0,
+ "has_files": 1,
+ }
+
+ def all_rows(self) -> Iterator[dict]:
+ for number in range(1, self.movies + 1):
+ yield self.row(number)
+
+ def category_rows(self, category_id: int) -> Iterator[dict]:
+ if not 1 <= category_id <= self.categories and category_id != self.adult_category:
+ return
+ for number in range(1, self.movies + 1):
+ if self.category_of(number) == category_id:
+ yield self.row(number)
+
+ def wildcard_rows(self) -> Iterator[dict]:
+ for number in range(1, self.movies + 1):
+ category = self.category_of(number)
+ if self.wildcard_excludes_adult and category == self.adult_category:
+ continue
+ yield self.row(number)
+
+ def channel_row(self, number: int) -> dict:
+ return {
+ "id": str(400_000 + number),
+ "name": f"Benchmark Channel {number:04d}",
+ "number": str(number),
+ "tv_genre_id": str((number - 1) % self.live_genres + 1),
+ "logo": "",
+ "cmd": f"ffmpeg http://127.0.0.1:1/iptv/{400_000 + number}",
+ "use_http_tmp_link": 0,
+ "xmltv_id": f"benchmark-{self.seed}-{number}",
+ }
+
+ def channel_rows(self, genre_id: int | None = None) -> Iterator[dict]:
+ if genre_id is not None and not 1 <= genre_id <= self.live_genres:
+ return
+ for number in range(1, self.channels + 1):
+ if genre_id is None or (number - 1) % self.live_genres + 1 == genre_id:
+ yield self.channel_row(number)
+
+ def advertised_size(self) -> int:
+ return self.advertised_page_size or self.page_size
+
+ @staticmethod
+ def page_count(rows: int, page_size: int) -> int:
+ return math.ceil(rows / page_size) if rows else 0
+
+ def metadata(self) -> dict:
+ digest = hashlib.sha256()
+ size = 0
+ visible = 0
+ for row in self.all_rows():
+ chunk = encode(row)
+ digest.update(chunk)
+ size += len(chunk)
+ if not (self.wildcard_excludes_adult and row["category_id"] == str(self.adult_category)):
+ visible += 1
+ pages_by_category = {
+ str(category): self.page_count(sum(1 for _ in self.category_rows(category)), self.page_size)
+ for category in range(1, self.categories + 1)
+ }
+ if self.adult_category:
+ pages_by_category[str(self.adult_category)] = self.page_count(
+ sum(1 for _ in self.category_rows(self.adult_category)), self.page_size
+ )
+ return {
+ "fixture": "streamvault-stalker-catalog-v1",
+ "scenario": asdict(self),
+ "page_base": self.page_base_name,
+ "expected_movies": self.movies,
+ "expected_channels": self.channels,
+ "live_genres": self.live_genres,
+ "expected_wildcard_rows": visible,
+ "expected_adult_rows": self.movies // self.adult_stride if self.adult_category else 0,
+ "pages_wildcard": self.page_count(visible, self.page_size),
+ "pages_by_category": pages_by_category,
+ "payload_sha256": digest.hexdigest(),
+ "payload_bytes": size,
+ "playback_media": False,
+ }
+
+
+def encode(value) -> bytes:
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
+
+
+@dataclass
+class Counters:
+ ordered_list_requests: int = 0
+ throttled: int = 0
+ server_errors: int = 0
+ page_walks: int = 0
+ last_rows_by_scope: dict = field(default_factory=dict)
+
+
+class FixtureServer(ThreadingHTTPServer):
+ daemon_threads = True
+
+ def __init__(self, address, scenario: Scenario, event_log: Path | None = None):
+ super().__init__(address, Handler)
+ self.scenario = scenario
+ self.metadata = scenario.metadata()
+ self.events = deque(maxlen=20_000)
+ self.event_log = event_log
+ self.lock = threading.Lock()
+ self.sequence = 0
+ self.active = 0
+ self.high_water = 0
+ self.counters = Counters()
+ self.epoch = time.monotonic()
+ if event_log:
+ event_log.parent.mkdir(parents=True, exist_ok=True)
+
+ def record(self, event: dict) -> None:
+ # Caller holds lock.
+ self.events.append(event)
+ if self.event_log:
+ with self.event_log.open("a", encoding="utf-8") as output:
+ output.write(json.dumps(event, separators=(",", ":")) + "\n")
+
+ def begin(self, action: str, page: int | None, category_id: int | None, wildcard: bool, run: str):
+ with self.lock:
+ self.sequence += 1
+ self.active += 1
+ self.high_water = max(self.high_water, self.active)
+ if action == "get_ordered_list":
+ self.counters.ordered_list_requests += 1
+ if page is not None and self.scenario.p_base == 1 and page == 1:
+ self.counters.page_walks += 1
+ self.record({
+ "event": "request_start", "request_id": self.sequence,
+ "at_ms": round((time.monotonic() - self.epoch) * 1000, 3),
+ "run": run, "action": action, "page": page,
+ "category_id": category_id, "wildcard": wildcard,
+ "active": self.active,
+ })
+ return self.sequence
+
+ def finish(self, request_id: int, rows: int, status: int, started: float, completed: bool, total_items: int | None):
+ with self.lock:
+ self.active -= 1
+ self.record({
+ "event": "request_end", "request_id": request_id,
+ "at_ms": round((time.monotonic() - self.epoch) * 1000, 3),
+ "elapsed_ms": round((time.monotonic() - started) * 1000, 3),
+ "rows": rows, "status": status, "completed": completed,
+ "total_items": total_items,
+ })
+
+ def ordered_list(self, category_raw: str | None, page_raw: str | None, sortby: str | None):
+ """Returns (status, payload, rows, total_items). Never called with the lock held."""
+ scenario = self.scenario
+ wildcard = not category_raw or category_raw == "*"
+ category_id = None
+ if not wildcard:
+ try:
+ category_id = int(category_raw)
+ except ValueError:
+ return 200, empty_page(scenario), 0, 0
+ try:
+ page = int(page_raw) if page_raw is not None else 1
+ except ValueError:
+ page = 1
+
+ with self.lock:
+ counters = self.counters
+ request_number = counters.ordered_list_requests
+ throttle = scenario.throttle_every and request_number % scenario.throttle_every == 0
+ server_error = scenario.server_error_every and request_number % scenario.server_error_every == 0
+ if throttle:
+ counters.throttled += 1
+ if server_error:
+ counters.server_errors += 1
+ if throttle:
+ return 429, {"error": "configured_throttle"}, 0, None
+ if server_error:
+ return 503, {"error": "configured_failure"}, 0, None
+
+ if wildcard and not scenario.wildcard_supported:
+ return 200, empty_page(scenario), 0, 0
+
+ if wildcard:
+ rows = list(scenario.wildcard_rows())
+ else:
+ rows = list(scenario.category_rows(category_id))
+ if sortby == "added":
+ rows.sort(key=lambda row: (row["added"], row["id"]), reverse=True)
+
+ total_items = len(rows)
+ if scenario.unstable_totals_every and request_number % scenario.unstable_totals_every == 0:
+ total_items += 7
+
+ pages = Scenario.page_count(len(rows), scenario.page_size)
+ index = page_index(scenario.p_base, page, pages)
+ scope = "*" if wildcard else str(category_id)
+ with self.lock:
+ previous = self.counters.last_rows_by_scope.get(scope)
+ if (
+ scenario.repeat_page_every
+ and index > 0
+ and request_number % scenario.repeat_page_every == 0
+ and previous
+ ):
+ slice_rows = previous
+ else:
+ start = index * scenario.page_size
+ slice_rows = rows[start:start + scenario.page_size]
+ self.counters.last_rows_by_scope[scope] = slice_rows
+
+ if scenario.page_delay_ms:
+ time.sleep(scenario.page_delay_ms / 1000)
+ payload = {
+ "js": {
+ "total_items": total_items,
+ "max_page_items": scenario.advertised_size(),
+ "cur_page": index + 1,
+ "data": slice_rows,
+ "selected_item": 0,
+ }
+ }
+ return 200, payload, len(slice_rows), total_items
+
+ def ordered_list_live(self, genre_raw: str | None, page_raw: str | None):
+ """Live fallback paging (`type=itv`, `genre` filter). No failure injection."""
+ scenario = self.scenario
+ genre_id = None
+ if genre_raw and genre_raw != "*":
+ try:
+ genre_id = int(genre_raw)
+ except ValueError:
+ return 200, empty_page(scenario), 0, 0
+ try:
+ page = int(page_raw) if page_raw is not None else 1
+ except ValueError:
+ page = 1
+ rows = list(scenario.channel_rows(genre_id))
+ pages = Scenario.page_count(len(rows), scenario.page_size)
+ index = page_index(scenario.p_base, page, pages)
+ start = index * scenario.page_size
+ slice_rows = rows[start:start + scenario.page_size]
+ payload = {
+ "js": {
+ "total_items": len(rows),
+ "max_page_items": scenario.advertised_size(),
+ "cur_page": index + 1,
+ "data": slice_rows,
+ "selected_item": 0,
+ }
+ }
+ return 200, payload, len(slice_rows), len(rows)
+
+
+def page_index(p_base: int, page: int, pages: int) -> int:
+ if p_base == 0:
+ return max(page, 0)
+ if p_base == 2 and page == 0:
+ return max(pages - 1, 0)
+ return max(page - 1, 0)
+
+
+def empty_page(scenario: Scenario) -> dict:
+ return {
+ "js": {
+ "total_items": 0,
+ "max_page_items": scenario.advertised_size(),
+ "cur_page": 1,
+ "data": [],
+ "selected_item": 0,
+ }
+ }
+
+
+class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *_args):
+ pass
+
+ def json_response(self, body, status=200, headers: dict | None = None):
+ raw = encode(body)
+ self.send_response(status)
+ self.send_header("Content-Type", "application/json; charset=utf-8")
+ self.send_header("Content-Length", str(len(raw)))
+ if headers:
+ for name, value in headers.items():
+ self.send_header(name, value)
+ self.end_headers()
+ self.wfile.write(raw)
+ return len(raw)
+
+ def do_GET(self):
+ parsed = urlparse(self.path)
+ self.dispatch(parsed.path, parse_qs(parsed.query))
+
+ def do_POST(self):
+ parsed = urlparse(self.path)
+ length = int(self.headers.get("Content-Length") or 0)
+ body = self.rfile.read(length).decode("utf-8") if length else ""
+ query = parse_qs(parsed.query)
+ for name, values in parse_qs(body).items():
+ query.setdefault(name, values)
+ self.dispatch(parsed.path, query)
+
+ def dispatch(self, path: str, query: dict):
+ server: FixtureServer = self.server
+ if path == "/fixture":
+ self.json_response(server.metadata)
+ return
+ if path == "/events":
+ with server.lock:
+ snapshot = {
+ "events": list(server.events),
+ "high_water": server.high_water,
+ "counters": asdict(server.counters),
+ }
+ self.json_response(snapshot)
+ return
+ if path not in ("/server/load.php", "/portal.php"):
+ self.json_response({"error": "not_found"}, 404)
+ return
+
+ action = query.get("action", [""])[0]
+ if not action:
+ self.json_response({"error": "missing_action"}, 400)
+ return
+ page = query.get("p", [None])[0]
+ category_raw = query.get("category", [None])[0]
+ wildcard = not category_raw or category_raw == "*"
+ category_id = None if wildcard else _safe_int(category_raw)
+ mac = query.get("mac", [""])[0]
+ run = mac if SYNTHETIC_MAC.fullmatch(mac or "") else "unlabelled"
+ started = time.monotonic()
+ request_id = server.begin(action, _safe_int(page), category_id, wildcard, run)
+ status = 200
+ rows = 0
+ total_items: int | None = None
+ completed = False
+ try:
+ time.sleep(server.scenario.header_delay_ms / 1000)
+ if action == "handshake":
+ status, size = 200, self.json_response({
+ "js": {"token": f"{TOKEN}-{server.scenario.seed}", "random": f"{server.scenario.seed:08x}"}
+ })
+ elif action in ("get_profile", "get_account_info", "get_localization"):
+ status, size = 200, self.json_response(self.profile_payload(action, server.scenario))
+ elif action == "get_genres":
+ status, size = 200, self.json_response({"js": self.live_genres_payload(server.scenario)})
+ elif action == "get_all_channels":
+ channel_rows = list(server.scenario.channel_rows())
+ status, size = 200, self.json_response({"js": {"data": channel_rows, "total_items": len(channel_rows)}})
+ elif action == "get_categories" and query.get("type", ["vod"])[0] == "vod":
+ status, size = 200, self.json_response({"js": self.vod_categories(server.scenario)})
+ elif action == "get_categories":
+ status, size = 200, self.json_response({"js": []})
+ elif action == "get_ordered_list" and query.get("type", ["vod"])[0] == "itv":
+ status, payload, rows, total_items = server.ordered_list_live(
+ query.get("genre", [None])[0], page
+ )
+ size = self.json_response(payload, status)
+ elif action == "get_ordered_list" and query.get("type", ["vod"])[0] == "vod":
+ status, payload, rows, total_items = server.ordered_list(category_raw, page, query.get("sortby", [None])[0])
+ headers = {"Retry-After": "1"} if status == 429 else None
+ size = self.json_response(payload, status, headers)
+ else:
+ status, size = 200, self.json_response({"js": []})
+ completed = True
+ except (BrokenPipeError, ConnectionResetError):
+ self.close_connection = True
+ finally:
+ server.finish(request_id, rows, status, started, completed, total_items)
+
+ @staticmethod
+ def profile_payload(action: str, scenario: Scenario) -> dict:
+ if action == "get_localization":
+ return {"js": {"locale": "en", "timezone": "UTC"}}
+ if action == "get_account_info":
+ return {"js": {"id": "1", "login": "fixture", "mac": "00:1A:79:12:34:56",
+ "phone": "", "status": 0, "tariff_plan": "fixture",
+ "end_date": "2030-01-01"}}
+ return {"js": {"id": "1", "name": "Fixture", "mac": "00:1A:79:12:34:56",
+ "token": f"{TOKEN}-{scenario.seed}", "hd": 1, "status": 0,
+ "stb_type": "MAG254", "timezone": "UTC", "locale": "en"}}
+
+ @staticmethod
+ def live_genres_payload(scenario: Scenario) -> list[dict]:
+ return [
+ {"id": str(genre), "title": f"Genre {genre:02d}", "alias": f"genre-{genre:02d}"}
+ for genre in range(1, scenario.live_genres + 1)
+ ]
+
+ @staticmethod
+ def vod_categories(scenario: Scenario) -> list[dict]:
+ categories = [{"id": "*", "title": "All", "alias": "*", "censored": 0}]
+ for category in range(1, scenario.categories + 1):
+ categories.append({
+ "id": str(category), "title": f"Category {category:04d}",
+ "alias": f"cat-{category:04d}", "censored": 0,
+ })
+ if scenario.adult_category:
+ categories.append({
+ "id": str(scenario.adult_category), "title": "Adult",
+ "alias": "adult", "censored": 0,
+ })
+ return categories
+
+
+def _safe_int(value: str | None) -> int | None:
+ try:
+ return int(value) if value is not None else None
+ except ValueError:
+ return None
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--bind", default="127.0.0.1")
+ parser.add_argument("--port", type=int, default=8767)
+ parser.add_argument("--events", type=Path)
+ for field_name, default in asdict(Scenario()).items():
+ parser.add_argument("--" + field_name.replace("_", "-"), type=int, default=default)
+ args = parser.parse_args()
+ scenario = Scenario(**{field_name: getattr(args, field_name) for field_name in asdict(Scenario())})
+ server = FixtureServer((args.bind, args.port), scenario, args.events)
+ print(json.dumps({"listening_port": server.server_address[1], **server.metadata}), flush=True)
+ try:
+ server.serve_forever()
+ except KeyboardInterrupt:
+ pass
+ finally:
+ server.server_close()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/stalker_catalog_probe.py b/tools/stalker_catalog_probe.py
new file mode 100644
index 00000000..d686b687
--- /dev/null
+++ b/tools/stalker_catalog_probe.py
@@ -0,0 +1,401 @@
+#!/usr/bin/env python3
+"""Validate Stalker wildcard catalog coverage and measure crawl cost.
+
+Compares a category-less (wildcard) whole-catalog walk against the
+per-category walk on the same portal session, mirroring the app's page-base
+inference (`StalkerProvider.inferVodPageBase`) and reporting the extra stock
+Ministra behavior the app cannot currently see (`p=0` = last page).
+
+The tool never prints credentials or full provider URLs; the report contains
+the portal host, row counts, request counts, and timing only.
+
+Run against the local fixture:
+
+ python tools/stalker_catalog_fixture.py --port 8767 &
+ python tools/stalker_catalog_probe.py --portal-url http://127.0.0.1:8767 --fixture-mode
+
+Run against a real portal (paced, bounded):
+
+ python tools/stalker_catalog_probe.py --portal-url https://portal.example.com/c \\
+ --mac 00:1A:79:12:34:56 --max-pages 50 --max-categories 20
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+from dataclasses import dataclass, field
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+USER_AGENT = ("Mozilla/5.0 (QtEmbedded; U; Linux; C) AppleWebKit/533.3 (KHTML, like Gecko) "
+ "MAG200 stbapp ver: 4 rev: 1812 Mobile Safari/533.3")
+X_USER_AGENT = "Model: MAG254; Link: Ethernet"
+
+
+@dataclass
+class ProbeOptions:
+ max_pages: int = 5_000
+ max_categories: int = 10_000
+ sortby: str = ""
+ request_interval_ms: int = 0
+ timeout_seconds: float = 30.0
+ probe_category: int = 1
+
+
+@dataclass
+class Counters:
+ requests: int = 0
+ ordered_list_requests: int = 0
+ retries: int = 0
+ throttled: int = 0
+ server_errors: int = 0
+
+
+class PortalError(RuntimeError):
+ pass
+
+
+@dataclass
+class Page:
+ total_items: int
+ max_page_items: int
+ rows: list[dict] = field(default_factory=list)
+
+
+class StalkerClient:
+ def __init__(self, portal_url: str, mac: str, options: ProbeOptions,
+ username: str = "", password: str = ""):
+ self.portal_url = portal_url.rstrip("/")
+ self.mac = mac
+ self.username = username
+ self.password = password
+ self.options = options
+ self.counters = Counters()
+ self.token = ""
+ self.load_url = self.portal_url + "/server/load.php"
+ self.last_request_at = 0.0
+
+ def _paced(self):
+ interval = self.options.request_interval_ms / 1000
+ if interval <= 0:
+ return
+ wait = self.last_request_at + interval - time.monotonic()
+ if wait > 0:
+ time.sleep(wait)
+ self.last_request_at = time.monotonic()
+
+ def _request(self, query: dict[str, Any], attempts: int = 3) -> dict:
+ url = self.load_url + "?" + urllib.parse.urlencode(query)
+ request = urllib.request.Request(url, headers={
+ "User-Agent": USER_AGENT,
+ "X-User-Agent": X_USER_AGENT,
+ "Referer": self.portal_url + "/c/",
+ "Accept": "*/*",
+ "Cookie": "mac=" + self.mac + "; stb_lang=en; timezone=UTC",
+ **({"Authorization": "Bearer " + self.token} if self.token else {}),
+ })
+ last_error: Exception | None = None
+ for attempt in range(attempts):
+ self._paced()
+ self.counters.requests += 1
+ try:
+ with urllib.request.urlopen(request, timeout=self.options.timeout_seconds) as response:
+ return json.load(response)
+ except urllib.error.HTTPError as error:
+ if error.code == 429:
+ self.counters.throttled += 1
+ elif error.code >= 500:
+ self.counters.server_errors += 1
+ retry_after = error.headers.get("Retry-After") if error.headers else None
+ last_error = error
+ error.close()
+ if error.code not in (429, 500, 502, 503, 504) or attempt == attempts - 1:
+ raise PortalError(f"HTTP {error.code}") from error
+ self.counters.retries += 1
+ delay = min(float(retry_after), 5.0) if retry_after and retry_after.replace(".", "", 1).isdigit() else 1.0
+ time.sleep(delay)
+ except (urllib.error.URLError, TimeoutError) as error:
+ last_error = error
+ if attempt == attempts - 1:
+ raise PortalError(f"transport failure: {type(error).__name__}") from error
+ self.counters.retries += 1
+ time.sleep(1.0)
+ raise PortalError("request failed") from last_error
+
+ def authenticate(self):
+ payload = self._request({"type": "stb", "action": "handshake", "token": "", "JsHttpRequest": "1-xml"})
+ self.token = str((payload.get("js") or {}).get("token") or "")
+ if not self.token:
+ raise PortalError("handshake did not return a token")
+ self._request({"type": "stb", "action": "get_profile", "JsHttpRequest": "1-xml"})
+ if self.username:
+ self._request({
+ "type": "stb", "action": "do_auth",
+ "login": self.username, "password": self.password,
+ "JsHttpRequest": "1-xml",
+ })
+
+ def categories(self) -> list[dict]:
+ payload = self._request({"type": "vod", "action": "get_categories", "JsHttpRequest": "1-xml"})
+ categories = payload.get("js") or []
+ if isinstance(categories, dict):
+ categories = categories.get("data") or []
+ return [category for category in categories if isinstance(category, dict)]
+
+ def ordered_list(self, category_id: str | None, page: int, sortby: str = "") -> Page:
+ self.counters.ordered_list_requests += 1
+ query: dict[str, Any] = {
+ "type": "vod", "action": "get_ordered_list", "p": str(page), "JsHttpRequest": "1-xml",
+ }
+ if category_id is not None:
+ query["category"] = category_id
+ if sortby:
+ query["sortby"] = sortby
+ payload = self._request(query)
+ js = payload.get("js") or {}
+ if not isinstance(js, dict):
+ raise PortalError("ordered list response is not an object")
+ rows = js.get("data") or []
+ return Page(
+ total_items=_int_or_zero(js.get("total_items")),
+ max_page_items=_int_or_zero(js.get("max_page_items")),
+ rows=[row for row in rows if isinstance(row, dict)],
+ )
+
+
+def _int_or_zero(value: Any) -> int:
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return 0
+
+
+def _page_signature(rows: list[dict]) -> list[str]:
+ return [str(row.get("id")) for row in rows]
+
+
+def detect_page_base(client: StalkerClient, category_id: str, options: ProbeOptions) -> dict:
+ """Mirrors StalkerProvider.inferVodPageBase and adds stock p=0 detection."""
+ page_zero = client.ordered_list(category_id, 0, options.sortby)
+ page_one = client.ordered_list(category_id, 1, options.sortby)
+ zero_ids = _page_signature(page_zero.rows)
+ one_ids = _page_signature(page_one.rows)
+ pages = math.ceil(page_zero.total_items / page_zero.max_page_items) if page_zero.max_page_items else 1
+ stock_last_page = False
+ if zero_ids and one_ids and zero_ids != one_ids and pages > 1:
+ last = client.ordered_list(category_id, pages, options.sortby)
+ stock_last_page = _page_signature(last.rows) == zero_ids
+ if not zero_ids and not one_ids:
+ base, kind = 1, "UNKNOWN"
+ elif zero_ids and one_ids and zero_ids == one_ids:
+ base, kind = 1, "ONE_BASED_CLAMPED"
+ elif zero_ids and not one_ids:
+ base, kind = 0, "ZERO_BASED"
+ elif zero_ids and one_ids and stock_last_page:
+ base, kind = 0, "STOCK_LAST_PAGE_ON_ZERO"
+ elif zero_ids:
+ base, kind = 0, "ZERO_BASED"
+ else:
+ base, kind = 1, "ONE_BASED"
+ return {
+ "page_base": base,
+ "page_base_kind": kind,
+ "stock_page_zero_is_last_page": stock_last_page,
+ "p0_rows": len(zero_ids),
+ "p1_rows": len(one_ids),
+ "p0_total_items": page_zero.total_items,
+ "p1_total_items": page_one.total_items,
+ "app_inference": base,
+ }
+
+
+@dataclass
+class CrawlResult:
+ scope: str
+ rows: dict[str, dict] = field(default_factory=dict)
+ duplicates: int = 0
+ pages_fetched: int = 0
+ early_empty_page: int | None = None
+ totals: set[int] = field(default_factory=set)
+ max_page_items: int = 0
+
+
+def crawl_scope(client: StalkerClient, category_id: str | None, scope: str, base: int,
+ options: ProbeOptions, budget: list[int]) -> CrawlResult:
+ result = CrawlResult(scope=scope)
+ page = 1
+ while page <= options.max_pages and budget[0] > 0:
+ portal_page = page - 1 + base
+ response = client.ordered_list(category_id, portal_page, options.sortby)
+ budget[0] -= 1
+ result.pages_fetched += 1
+ result.totals.add(response.total_items)
+ result.max_page_items = result.max_page_items or response.max_page_items
+ for row in response.rows:
+ row_id = str(row.get("id"))
+ if row_id in result.rows:
+ result.duplicates += 1
+ result.rows[row_id] = row
+ pages = math.ceil(response.total_items / response.max_page_items) if response.max_page_items else 0
+ if not response.rows and pages and page < pages:
+ result.early_empty_page = page
+ break
+ if not response.rows or page >= pages:
+ break
+ page += 1
+ return result
+
+
+def probe(client: StalkerClient, options: ProbeOptions) -> dict:
+ started = time.monotonic()
+ client.authenticate()
+ categories = [category for category in client.categories() if str(category.get("id")) != "*"]
+ if options.max_categories:
+ categories = categories[:options.max_categories]
+ if not categories:
+ raise PortalError("portal returned no VOD categories")
+ detection_category = str(categories[min(options.probe_category - 1, len(categories) - 1)].get("id"))
+ base_info = detect_page_base(client, detection_category, options)
+ base = base_info["page_base"]
+
+ budget = [options.max_pages]
+ category_results = [crawl_scope(client, str(category.get("id")), str(category.get("id")),
+ base, options, budget) for category in categories]
+ wildcard_budget = [options.max_pages]
+ wildcard = crawl_scope(client, None, "*", base, options, wildcard_budget)
+
+ per_category_ids: dict[str, dict] = {}
+ category_names = {str(category.get("id")): str(category.get("title") or "") for category in categories}
+ for result in category_results:
+ per_category_ids.update(result.rows)
+ missing = {row_id: row for row_id, row in per_category_ids.items() if row_id not in wildcard.rows}
+ missing_by_category: dict[str, int] = {}
+ for row in missing.values():
+ key = str(row.get("category_id"))
+ missing_by_category[key] = missing_by_category.get(key, 0) + 1
+ extra = {row_id: row for row_id, row in wildcard.rows.items() if row_id not in per_category_ids}
+ unexpected_categories = sorted({
+ str(row.get("category_id")) for row in wildcard.rows.values()
+ if str(row.get("category_id")) not in category_names
+ })
+ wildcard_by_category: dict[str, int] = {}
+ for row in wildcard.rows.values():
+ key = str(row.get("category_id"))
+ wildcard_by_category[key] = wildcard_by_category.get(key, 0) + 1
+ excluded_categories = sorted(
+ category_id for category_id in missing_by_category
+ if wildcard_by_category.get(category_id, 0) == 0
+ )
+ missing_outside_excluded = {
+ category_id: count for category_id, count in missing_by_category.items()
+ if category_id not in excluded_categories
+ }
+ totals_stable = all(len(result.totals) <= 1 for result in category_results) and len(wildcard.totals) <= 1
+ elapsed_ms = round((time.monotonic() - started) * 1000, 3)
+ per_category_requests = sum(result.pages_fetched for result in category_results)
+
+ if not wildcard.rows:
+ coverage = "wildcard_unsupported"
+ elif missing and not missing_outside_excluded:
+ coverage = "complete_with_excluded_categories"
+ elif missing:
+ coverage = "incomplete"
+ else:
+ coverage = "complete"
+
+ warnings: list[str] = []
+ if base_info["stock_page_zero_is_last_page"]:
+ warnings.append("p=0 returns the last page (stock Ministra); the app's inference maps it to a zero-based first page")
+ if wildcard.duplicates:
+ warnings.append(f"wildcard repeated {wildcard.duplicates} rows across pages")
+ if any(result.duplicates for result in category_results):
+ warnings.append("per-category crawl repeated rows across pages")
+ if any(result.early_empty_page is not None for result in category_results) or wildcard.early_empty_page is not None:
+ warnings.append("a page walk hit an empty page before the advertised total was reached")
+ if not totals_stable:
+ warnings.append("advertised total_items changed during the crawl")
+
+ return {
+ "portal_host": urllib.parse.urlparse(client.portal_url).netloc,
+ "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
+ "detection_category": detection_category,
+ **base_info,
+ "categories_crawled": len(categories),
+ "per_category": {
+ "rows": len(per_category_ids),
+ "requests": per_category_requests,
+ "duplicates": sum(result.duplicates for result in category_results),
+ },
+ "wildcard": {
+ "rows": len(wildcard.rows),
+ "requests": wildcard.pages_fetched,
+ "duplicates": wildcard.duplicates,
+ },
+ "missing_rows": len(missing),
+ "missing_by_category": missing_by_category,
+ "excluded_categories": excluded_categories,
+ "extra_rows": len(extra),
+ "unexpected_category_ids": unexpected_categories,
+ "coverage": coverage,
+ "totals_stable": totals_stable,
+ "request_interval_ms": options.request_interval_ms,
+ "counters": {
+ "requests": client.counters.requests,
+ "ordered_list_requests": client.counters.ordered_list_requests,
+ "retries": client.counters.retries,
+ "throttled": client.counters.throttled,
+ "server_errors": client.counters.server_errors,
+ },
+ "elapsed_ms": elapsed_ms,
+ "rows_per_second": round((len(per_category_ids) + len(wildcard.rows)) / (elapsed_ms / 1000), 2) if elapsed_ms else None,
+ "warnings": warnings,
+ }
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--portal-url", required=True)
+ parser.add_argument("--mac", default="00:1A:79:12:34:56")
+ parser.add_argument("--username", default="")
+ parser.add_argument("--password", default="")
+ parser.add_argument("--max-pages", type=int, default=5_000)
+ parser.add_argument("--max-categories", type=int, default=10_000)
+ parser.add_argument("--sortby", default="")
+ parser.add_argument("--request-interval-ms", type=int, default=None,
+ help="Defaults to 0 for loopback portals and 1000 for remote portals")
+ parser.add_argument("--timeout-seconds", type=float, default=30.0)
+ parser.add_argument("--output", type=Path)
+ args = parser.parse_args()
+
+ loopback = urllib.parse.urlparse(args.portal_url).hostname in ("127.0.0.1", "localhost", "::1")
+ interval = args.request_interval_ms if args.request_interval_ms is not None else (0 if loopback else 1_000)
+ options = ProbeOptions(
+ max_pages=args.max_pages,
+ max_categories=args.max_categories,
+ sortby=args.sortby,
+ request_interval_ms=interval,
+ timeout_seconds=args.timeout_seconds,
+ )
+ client = StalkerClient(args.portal_url, args.mac, options, args.username, args.password)
+ report = probe(client, options)
+ output = args.output or Path(__file__).resolve().parents[1] / "build" / "stalker-catalog-probe" / (
+ datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ") + ".json")
+ output.parent.mkdir(parents=True, exist_ok=True)
+ output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
+ print(json.dumps({key: report[key] for key in (
+ "portal_host", "page_base_kind", "coverage", "per_category", "wildcard",
+ "missing_rows", "missing_by_category", "totals_stable", "elapsed_ms", "warnings",
+ )}, indent=2))
+ print(f"report: {output}")
+ if report["coverage"] == "incomplete" or not report["totals_stable"]:
+ raise SystemExit(2)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/tests/test_stalker_catalog_fixture.py b/tools/tests/test_stalker_catalog_fixture.py
new file mode 100644
index 00000000..c5bb1949
--- /dev/null
+++ b/tools/tests/test_stalker_catalog_fixture.py
@@ -0,0 +1,258 @@
+import importlib.util
+import json
+import sys
+import threading
+import unittest
+from pathlib import Path
+from urllib.error import HTTPError
+from urllib.parse import urlencode
+from urllib.request import urlopen
+
+
+SPEC = importlib.util.spec_from_file_location(
+ "stalker_catalog_fixture", Path(__file__).parents[1] / "stalker_catalog_fixture.py"
+)
+FIXTURE = importlib.util.module_from_spec(SPEC)
+sys.modules[SPEC.name] = FIXTURE
+SPEC.loader.exec_module(FIXTURE)
+
+
+class StalkerCatalogFixtureTest(unittest.TestCase):
+ def start_server(self, **options):
+ server = FIXTURE.FixtureServer(("127.0.0.1", 0), FIXTURE.Scenario(**options))
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+
+ def close():
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=3)
+
+ self.addCleanup(close)
+ return server, "http://127.0.0.1:" + str(server.server_address[1])
+
+ def get(self, base, path, **params):
+ query = urlencode({key: value for key, value in params.items() if value is not None})
+ url = base + path + ("?" + query if query else "")
+ with urlopen(url, timeout=5) as response:
+ return json.load(response)
+
+ def ordered_list(self, base, **params):
+ params.setdefault("type", "vod")
+ params.setdefault("action", "get_ordered_list")
+ return self.get(base, "/server/load.php", **params)["js"]
+
+ # -- pure scenario behavior -------------------------------------------------
+
+ def test_category_partition_matches_wildcard_without_losing_rows(self):
+ scenario = FIXTURE.Scenario(movies=103, categories=12)
+ wildcard = list(scenario.wildcard_rows())
+ partition = [row for category in range(1, 13) for row in scenario.category_rows(category)]
+ self.assertEqual(wildcard, sorted(partition, key=lambda row: int(row["id"])))
+ self.assertEqual([], list(scenario.category_rows(999)))
+ self.assertEqual(103, len(wildcard))
+
+ def test_adult_rows_partition_into_adult_category_and_wildcard_excludes_them(self):
+ scenario = FIXTURE.Scenario(movies=100, categories=4, adult_category=9, adult_stride=10,
+ wildcard_excludes_adult=1)
+ adult = list(scenario.category_rows(9))
+ self.assertEqual(10, len(adult))
+ wildcard = list(scenario.wildcard_rows())
+ self.assertEqual(90, len(wildcard))
+ self.assertFalse(set(row["id"] for row in adult) & set(row["id"] for row in wildcard))
+ metadata = scenario.metadata()
+ self.assertEqual(10, metadata["expected_adult_rows"])
+ self.assertEqual(90, metadata["expected_wildcard_rows"])
+ self.assertEqual(7, metadata["pages_wildcard"])
+
+ def test_page_index_variants(self):
+ self.assertEqual(0, FIXTURE.page_index(0, 0, 5))
+ self.assertEqual(2, FIXTURE.page_index(0, 2, 5))
+ self.assertEqual(0, FIXTURE.page_index(1, 1, 5))
+ self.assertEqual(3, FIXTURE.page_index(1, 4, 5))
+ self.assertEqual(4, FIXTURE.page_index(2, 0, 5))
+ self.assertEqual(0, FIXTURE.page_index(2, 1, 5))
+
+ def test_hash_is_deterministic_and_seed_sensitive(self):
+ scenario = FIXTURE.Scenario(movies=103, categories=12)
+ self.assertEqual(scenario.metadata(), scenario.metadata())
+ self.assertNotEqual(scenario.metadata()["payload_sha256"],
+ FIXTURE.Scenario(movies=103, categories=12, seed=2).metadata()["payload_sha256"])
+
+ def test_invalid_scenarios_are_rejected(self):
+ with self.assertRaises(ValueError):
+ FIXTURE.Scenario(movies=0)
+ with self.assertRaises(ValueError):
+ FIXTURE.Scenario(p_base=3)
+ with self.assertRaises(ValueError):
+ FIXTURE.Scenario(categories=10, adult_category=5)
+ with self.assertRaises(ValueError):
+ FIXTURE.Scenario(wildcard_supported=2)
+
+ # -- HTTP behavior ----------------------------------------------------------
+
+ def test_handshake_profile_and_categories(self):
+ _, base = self.start_server(movies=30, categories=3)
+ handshake = self.get(base, "/server/load.php", type="stb", action="handshake")
+ self.assertTrue(handshake["js"]["token"].startswith(FIXTURE.TOKEN))
+ profile = self.get(base, "/server/load.php", type="stb", action="get_profile")
+ self.assertEqual("Fixture", profile["js"]["name"])
+ categories = self.get(base, "/server/load.php", type="vod", action="get_categories")["js"]
+ self.assertEqual("*", categories[0]["id"])
+ self.assertEqual(["1", "2", "3"], [category["id"] for category in categories[1:]])
+
+ def test_one_based_paging_walks_every_row_once(self):
+ _, base = self.start_server(movies=100, categories=2)
+ page = self.ordered_list(base, category="1", p="1")
+ self.assertEqual(50, page["total_items"])
+ self.assertEqual(14, page["max_page_items"])
+ self.assertEqual(4, FIXTURE.Scenario.page_count(50, 14))
+ collected = []
+ for number in range(1, 5):
+ collected += self.ordered_list(base, category="1", p=str(number))["data"]
+ self.assertEqual(50, len(collected))
+ self.assertEqual(50, len({row["id"] for row in collected}))
+ wildcard = []
+ for number in range(1, 9):
+ wildcard += self.ordered_list(base, p=str(number))["data"]
+ self.assertEqual(100, len(wildcard))
+
+ def test_stock_portal_treats_page_zero_as_last_page(self):
+ _, base = self.start_server(movies=60, categories=3, p_base=2)
+ last = self.ordered_list(base, category="1", p="0")
+ expected_last = self.ordered_list(base, category="1", p="2")
+ self.assertEqual(expected_last["data"], last["data"])
+ self.assertEqual(20, last["total_items"])
+ self.assertEqual(6, len(last["data"]))
+
+ def test_zero_based_portal_uses_page_zero_for_first_page(self):
+ _, base = self.start_server(movies=30, categories=3, p_base=0)
+ first = self.ordered_list(base, category="1", p="0")
+ self.assertEqual("100001", first["data"][0]["id"])
+ self.assertEqual(10, first["total_items"])
+
+ def test_wildcard_unsupported_returns_empty_but_categories_work(self):
+ _, base = self.start_server(movies=30, categories=3, wildcard_supported=0)
+ wildcard = self.ordered_list(base, p="1")
+ self.assertEqual(0, wildcard["total_items"])
+ self.assertEqual([], wildcard["data"])
+ category = self.ordered_list(base, category="2", p="1")
+ self.assertEqual(10, category["total_items"])
+
+ def test_advertised_page_size_can_lie_about_real_page_size(self):
+ _, base = self.start_server(movies=30, categories=3, advertised_page_size=100)
+ page = self.ordered_list(base, category="1", p="1")
+ self.assertEqual(100, page["max_page_items"])
+ self.assertEqual(10, len(page["data"]))
+
+ def test_sort_added_orders_newest_first(self):
+ _, base = self.start_server(movies=30, categories=3)
+ page = self.ordered_list(base, p="1", sortby="added")
+ self.assertEqual("100030", page["data"][0]["id"])
+ self.assertEqual("100029", page["data"][1]["id"])
+
+ def test_throttle_injection_returns_429_with_retry_after(self):
+ _, base = self.start_server(movies=30, categories=3, throttle_every=2)
+ self.ordered_list(base, category="1", p="1")
+ with self.assertRaises(HTTPError) as error:
+ self.ordered_list(base, category="1", p="2")
+ self.assertEqual(429, error.exception.code)
+ self.assertEqual("1", error.exception.headers["Retry-After"])
+ error.exception.close()
+ self.assertEqual(1, self.get(base, "/events")["counters"]["throttled"])
+
+ def test_server_error_injection_returns_503(self):
+ _, base = self.start_server(movies=30, categories=3, server_error_every=1)
+ with self.assertRaises(HTTPError) as error:
+ self.ordered_list(base, category="1", p="1")
+ self.assertEqual(503, error.exception.code)
+ error.exception.close()
+
+ def test_unstable_totals_change_advertised_count(self):
+ _, base = self.start_server(movies=30, categories=3, unstable_totals_every=2)
+ first = self.ordered_list(base, category="1", p="1")
+ second = self.ordered_list(base, category="1", p="1")
+ self.assertEqual(10, first["total_items"])
+ self.assertEqual(17, second["total_items"])
+
+ def test_repeated_page_mode_does_not_advance(self):
+ _, base = self.start_server(movies=60, categories=2, repeat_page_every=2)
+ page_two = self.ordered_list(base, category="1", p="2")
+ page_three = self.ordered_list(base, category="1", p="3")
+ self.assertEqual(page_two["data"], page_three["data"])
+
+ def test_events_never_expose_credentials_and_report_rows(self):
+ _, base = self.start_server(movies=30, categories=3)
+ self.get(base, "/server/load.php", type="vod", action="get_ordered_list",
+ category="1", p="1", mac="00:1A:79:AA:BB:CC", password="do-not-log")
+ events = self.get(base, "/events")
+ serialized = json.dumps(events)
+ self.assertNotIn("00:1A:79:AA:BB:CC", serialized)
+ self.assertNotIn("do-not-log", serialized)
+ self.assertEqual("unlabelled", events["events"][0]["run"])
+ self.assertEqual(10, events["events"][1]["rows"])
+ self.assertEqual(10, events["events"][1]["total_items"])
+ self.assertTrue(events["events"][1]["completed"])
+ self.assertEqual(1, events["counters"]["ordered_list_requests"])
+
+ def test_synthetic_run_token_is_recorded(self):
+ _, base = self.start_server(movies=30, categories=3)
+ self.get(base, "/server/load.php", type="vod", action="get_ordered_list",
+ category="1", p="1", mac="02:00:00:00:00:01")
+ events = self.get(base, "/events")
+ self.assertEqual("02:00:00:00:00:01", events["events"][0]["run"])
+
+ def test_slow_response_allows_overlapping_http_requests(self):
+ _, base = self.start_server(movies=30, categories=3, header_delay_ms=50)
+ barrier = threading.Barrier(3)
+ errors = []
+
+ def fetch(page):
+ try:
+ barrier.wait(timeout=2)
+ self.ordered_list(base, category="1", p=str(page))
+ except Exception as error: # pragma: no cover - diagnostic capture
+ errors.append(error)
+
+ threads = [threading.Thread(target=fetch, args=(page,)) for page in (1, 2)]
+ for thread in threads:
+ thread.start()
+ barrier.wait(timeout=2)
+ for thread in threads:
+ thread.join(timeout=3)
+ self.assertFalse(errors)
+ self.assertEqual(2, self.get(base, "/events")["high_water"])
+
+ def test_live_genres_and_bulk_channels(self):
+ _, base = self.start_server(movies=30, categories=3, channels=25, live_genres=3)
+ genres = self.get(base, "/server/load.php", type="itv", action="get_genres")["js"]
+ self.assertEqual(["1", "2", "3"], [genre["id"] for genre in genres])
+ payload = self.get(base, "/server/load.php", type="itv", action="get_all_channels")["js"]
+ self.assertEqual(25, payload["total_items"])
+ self.assertEqual(25, len(payload["data"]))
+ self.assertEqual("400001", payload["data"][0]["id"])
+ self.assertEqual("1", payload["data"][0]["tv_genre_id"])
+ metadata = self.get(base, "/fixture")
+ self.assertEqual(25, metadata["expected_channels"])
+ self.assertEqual(3, metadata["live_genres"])
+
+ def test_live_paged_fallback_filters_by_genre(self):
+ _, base = self.start_server(movies=30, categories=3, channels=25, live_genres=3)
+ page = self.get(base, "/server/load.php", type="itv", action="get_ordered_list",
+ genre="2", p="1")["js"]
+ self.assertEqual(8, page["total_items"])
+ self.assertEqual(8, len(page["data"]))
+ self.assertTrue(all(row["tv_genre_id"] == "2" for row in page["data"]))
+
+ def test_fixture_metadata_is_exposed(self):
+ _, base = self.start_server(movies=30, categories=3)
+ metadata = self.get(base, "/fixture")
+ self.assertEqual("streamvault-stalker-catalog-v1", metadata["fixture"])
+ self.assertEqual("ONE_BASED", metadata["page_base"])
+ self.assertEqual(30, metadata["expected_movies"])
+ self.assertEqual(3, metadata["pages_wildcard"])
+ self.assertIn("1", metadata["pages_by_category"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/tests/test_stalker_catalog_probe.py b/tools/tests/test_stalker_catalog_probe.py
new file mode 100644
index 00000000..147c74cf
--- /dev/null
+++ b/tools/tests/test_stalker_catalog_probe.py
@@ -0,0 +1,107 @@
+import importlib.util
+import sys
+import threading
+import unittest
+from pathlib import Path
+
+
+def load(name, path):
+ spec = importlib.util.spec_from_file_location(name, path)
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+TOOLS = Path(__file__).parents[1]
+FIXTURE = load("stalker_catalog_fixture", TOOLS / "stalker_catalog_fixture.py")
+PROBE = load("stalker_catalog_probe", TOOLS / "stalker_catalog_probe.py")
+
+
+class StalkerCatalogProbeTest(unittest.TestCase):
+ def run_probe(self, **scenario_options):
+ server = FIXTURE.FixtureServer(("127.0.0.1", 0), FIXTURE.Scenario(**scenario_options))
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+
+ def close():
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=3)
+
+ self.addCleanup(close)
+ base = "http://127.0.0.1:" + str(server.server_address[1])
+ options = PROBE.ProbeOptions(max_pages=100, request_interval_ms=0)
+ client = PROBE.StalkerClient(base, "02:00:00:00:00:01", options)
+ return PROBE.probe(client, options), server
+
+ def test_one_based_fixture_wildcard_matches_per_category(self):
+ report, _ = self.run_probe(movies=100, categories=5)
+ self.assertEqual("ONE_BASED_CLAMPED", report["page_base_kind"])
+ self.assertEqual("complete", report["coverage"])
+ self.assertEqual(0, report["missing_rows"])
+ self.assertEqual(0, report["extra_rows"])
+ self.assertEqual(100, report["per_category"]["rows"])
+ self.assertEqual(100, report["wildcard"]["rows"])
+ self.assertEqual(8, report["wildcard"]["requests"])
+ self.assertTrue(report["totals_stable"])
+ self.assertEqual([], report["warnings"])
+
+ def test_zero_based_fixture_detects_base_and_crawls_completely(self):
+ report, _ = self.run_probe(movies=60, categories=3, p_base=0)
+ self.assertEqual("ZERO_BASED", report["page_base_kind"])
+ self.assertEqual(0, report["page_base"])
+ self.assertEqual("complete", report["coverage"])
+ self.assertEqual(60, report["wildcard"]["rows"])
+
+ def test_stock_fixture_flags_page_zero_last_page_warning(self):
+ report, _ = self.run_probe(movies=60, categories=3, p_base=2)
+ self.assertEqual("STOCK_LAST_PAGE_ON_ZERO", report["page_base_kind"])
+ self.assertTrue(report["stock_page_zero_is_last_page"])
+ self.assertEqual("complete", report["coverage"])
+ self.assertTrue(any("last page" in warning for warning in report["warnings"]))
+
+ def test_wildcard_unsupported_is_reported(self):
+ report, _ = self.run_probe(movies=60, categories=3, wildcard_supported=0)
+ self.assertEqual("wildcard_unsupported", report["coverage"])
+ self.assertEqual(0, report["wildcard"]["rows"])
+ self.assertEqual(60, report["per_category"]["rows"])
+
+ def test_adult_exclusion_is_explained_not_incomplete(self):
+ report, _ = self.run_probe(movies=100, categories=4, adult_category=9, adult_stride=10,
+ wildcard_excludes_adult=1)
+ self.assertEqual("complete_with_excluded_categories", report["coverage"])
+ self.assertEqual(["9"], report["excluded_categories"])
+ self.assertEqual({"9": 10}, report["missing_by_category"])
+ self.assertEqual(90, report["wildcard"]["rows"])
+ self.assertEqual(100, report["per_category"]["rows"])
+
+ def test_unstable_totals_are_reported(self):
+ report, _ = self.run_probe(movies=60, categories=3, unstable_totals_every=2)
+ self.assertFalse(report["totals_stable"])
+ self.assertTrue(any("total_items" in warning for warning in report["warnings"]))
+
+ def test_repeated_pages_produce_duplicates_and_incomplete_coverage(self):
+ report, _ = self.run_probe(movies=60, categories=2, repeat_page_every=1)
+ self.assertGreater(report["per_category"]["duplicates"], 0)
+ self.assertEqual("incomplete", report["coverage"])
+ self.assertTrue(any("repeated" in warning for warning in report["warnings"]))
+
+ def test_throttle_events_are_counted_without_failing(self):
+ report, server = self.run_probe(movies=60, categories=3, throttle_every=4)
+ self.assertGreaterEqual(report["counters"]["throttled"], 1)
+ self.assertGreater(report["counters"]["retries"], 0)
+ self.assertEqual("complete", report["coverage"])
+ with server.lock:
+ self.assertGreaterEqual(server.counters.throttled, 1)
+
+ def test_report_never_contains_mac_or_full_url(self):
+ report, _ = self.run_probe(movies=30, categories=3)
+ serialized = repr(report)
+ self.assertNotIn("02:00:00:00:00:01", serialized)
+ self.assertNotIn("http://", serialized)
+ self.assertIn("127.0.0.1", report["portal_host"])
+
+
+if __name__ == "__main__":
+ unittest.main()